]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/scsi/atari_NCR5380.c
ncr5380: Always escalate bad target time-out in NCR5380_select()
[karo-tx-linux.git] / drivers / scsi / atari_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  * ++roman: To port the 5380 driver to the Atari, I had to do some changes in
29  * this file, too:
30  *
31  *  - Some of the debug statements were incorrect (undefined variables and the
32  *    like). I fixed that.
33  *
34  *  - In information_transfer(), I think a #ifdef was wrong. Looking at the
35  *    possible DMA transfer size should also happen for REAL_DMA. I added this
36  *    in the #if statement.
37  *
38  *  - When using real DMA, information_transfer() should return in a DATAOUT
39  *    phase after starting the DMA. It has nothing more to do.
40  *
41  *  - The interrupt service routine should run main after end of DMA, too (not
42  *    only after RESELECTION interrupts). Additionally, it should _not_ test
43  *    for more interrupts after running main, since a DMA process may have
44  *    been started and interrupts are turned on now. The new int could happen
45  *    inside the execution of NCR5380_intr(), leading to recursive
46  *    calls.
47  *
48  *  - I've added a function merge_contiguous_buffers() that tries to
49  *    merge scatter-gather buffers that are located at contiguous
50  *    physical addresses and can be processed with the same DMA setup.
51  *    Since most scatter-gather operations work on a page (4K) of
52  *    4 buffers (1K), in more than 90% of all cases three interrupts and
53  *    DMA setup actions are saved.
54  *
55  * - I've deleted all the stuff for AUTOPROBE_IRQ, REAL_DMA_POLL, PSEUDO_DMA
56  *    and USLEEP, because these were messing up readability and will never be
57  *    needed for Atari SCSI.
58  *
59  * - I've revised the NCR5380_main() calling scheme (relax the 'main_running'
60  *   stuff), and 'main' is executed in a bottom half if awoken by an
61  *   interrupt.
62  *
63  * - The code was quite cluttered up by "#if (NDEBUG & NDEBUG_*) printk..."
64  *   constructs. In my eyes, this made the source rather unreadable, so I
65  *   finally replaced that by the *_PRINTK() macros.
66  *
67  */
68
69 /*
70  * Further development / testing that should be done :
71  * 1.  Test linked command handling code after Eric is ready with
72  *     the high level code.
73  */
74
75 /* Adapted for the sun3 by Sam Creasey. */
76
77 #include <scsi/scsi_dbg.h>
78 #include <scsi/scsi_transport_spi.h>
79
80 #if (NDEBUG & NDEBUG_LISTS)
81 #define LIST(x, y)                                              \
82         do {                                                    \
83                 printk("LINE:%d   Adding %p to %p\n",           \
84                        __LINE__, (void*)(x), (void*)(y));       \
85                 if ((x) == (y))                                 \
86                         udelay(5);                              \
87         } while (0)
88 #define REMOVE(w, x, y, z)                                      \
89         do {                                                    \
90                 printk("LINE:%d   Removing: %p->%p  %p->%p \n", \
91                        __LINE__, (void*)(w), (void*)(x),        \
92                        (void*)(y), (void*)(z));                 \
93                 if ((x) == (y))                                 \
94                         udelay(5);                              \
95         } while (0)
96 #else
97 #define LIST(x,y)
98 #define REMOVE(w,x,y,z)
99 #endif
100
101 #ifndef notyet
102 #undef LINKED
103 #endif
104
105 /*
106  * Design
107  *
108  * This is a generic 5380 driver.  To use it on a different platform,
109  * one simply writes appropriate system specific macros (ie, data
110  * transfer - some PC's will use the I/O bus, 68K's must use
111  * memory mapped) and drops this file in their 'C' wrapper.
112  *
113  * As far as command queueing, two queues are maintained for
114  * each 5380 in the system - commands that haven't been issued yet,
115  * and commands that are currently executing.  This means that an
116  * unlimited number of commands may be queued, letting
117  * more commands propagate from the higher driver levels giving higher
118  * throughput.  Note that both I_T_L and I_T_L_Q nexuses are supported,
119  * allowing multiple commands to propagate all the way to a SCSI-II device
120  * while a command is already executing.
121  *
122  *
123  * Issues specific to the NCR5380 :
124  *
125  * When used in a PIO or pseudo-dma mode, the NCR5380 is a braindead
126  * piece of hardware that requires you to sit in a loop polling for
127  * the REQ signal as long as you are connected.  Some devices are
128  * brain dead (ie, many TEXEL CD ROM drives) and won't disconnect
129  * while doing long seek operations.
130  *
131  * The workaround for this is to keep track of devices that have
132  * disconnected.  If the device hasn't disconnected, for commands that
133  * should disconnect, we do something like
134  *
135  * while (!REQ is asserted) { sleep for N usecs; poll for M usecs }
136  *
137  * Some tweaking of N and M needs to be done.  An algorithm based
138  * on "time to data" would give the best results as long as short time
139  * to datas (ie, on the same track) were considered, however these
140  * broken devices are the exception rather than the rule and I'd rather
141  * spend my time optimizing for the normal case.
142  *
143  * Architecture :
144  *
145  * At the heart of the design is a coroutine, NCR5380_main,
146  * which is started from a workqueue for each NCR5380 host in the
147  * system.  It attempts to establish I_T_L or I_T_L_Q nexuses by
148  * removing the commands from the issue queue and calling
149  * NCR5380_select() if a nexus is not established.
150  *
151  * Once a nexus is established, the NCR5380_information_transfer()
152  * phase goes through the various phases as instructed by the target.
153  * if the target goes into MSG IN and sends a DISCONNECT message,
154  * the command structure is placed into the per instance disconnected
155  * queue, and NCR5380_main tries to find more work.  If the target is
156  * idle for too long, the system will try to sleep.
157  *
158  * If a command has disconnected, eventually an interrupt will trigger,
159  * calling NCR5380_intr()  which will in turn call NCR5380_reselect
160  * to reestablish a nexus.  This will run main if necessary.
161  *
162  * On command termination, the done function will be called as
163  * appropriate.
164  *
165  * SCSI pointers are maintained in the SCp field of SCSI command
166  * structures, being initialized after the command is connected
167  * in NCR5380_select, and set as appropriate in NCR5380_information_transfer.
168  * Note that in violation of the standard, an implicit SAVE POINTERS operation
169  * is done, since some BROKEN disks fail to issue an explicit SAVE POINTERS.
170  */
171
172 /*
173  * Using this file :
174  * This file a skeleton Linux SCSI driver for the NCR 5380 series
175  * of chips.  To use it, you write an architecture specific functions
176  * and macros and include this file in your driver.
177  *
178  * These macros control options :
179  * AUTOSENSE - if defined, REQUEST SENSE will be performed automatically
180  *      for commands that return with a CHECK CONDITION status.
181  *
182  * DIFFERENTIAL - if defined, NCR53c81 chips will use external differential
183  *      transceivers.
184  *
185  * LINKED - if defined, linked commands are supported.
186  *
187  * REAL_DMA - if defined, REAL DMA is used during the data transfer phases.
188  *
189  * SUPPORT_TAGS - if defined, SCSI-2 tagged queuing is used where possible
190  *
191  * These macros MUST be defined :
192  *
193  * NCR5380_read(register)  - read from the specified register
194  *
195  * NCR5380_write(register, value) - write to the specific register
196  *
197  * NCR5380_implementation_fields  - additional fields needed for this
198  *      specific implementation of the NCR5380
199  *
200  * Either real DMA *or* pseudo DMA may be implemented
201  * REAL functions :
202  * NCR5380_REAL_DMA should be defined if real DMA is to be used.
203  * Note that the DMA setup functions should return the number of bytes
204  *      that they were able to program the controller for.
205  *
206  * Also note that generic i386/PC versions of these macros are
207  *      available as NCR5380_i386_dma_write_setup,
208  *      NCR5380_i386_dma_read_setup, and NCR5380_i386_dma_residual.
209  *
210  * NCR5380_dma_write_setup(instance, src, count) - initialize
211  * NCR5380_dma_read_setup(instance, dst, count) - initialize
212  * NCR5380_dma_residual(instance); - residual count
213  *
214  * PSEUDO functions :
215  * NCR5380_pwrite(instance, src, count)
216  * NCR5380_pread(instance, dst, count);
217  *
218  * The generic driver is initialized by calling NCR5380_init(instance),
219  * after setting the appropriate host specific fields and ID.  If the
220  * driver wishes to autoprobe for an IRQ line, the NCR5380_probe_irq(instance,
221  * possible) function may be used.
222  */
223
224 /* Macros ease life... :-) */
225 #define SETUP_HOSTDATA(in)                              \
226     struct NCR5380_hostdata *hostdata =                 \
227         (struct NCR5380_hostdata *)(in)->hostdata
228 #define HOSTDATA(in) ((struct NCR5380_hostdata *)(in)->hostdata)
229
230 #define NEXT(cmd)               ((struct scsi_cmnd *)(cmd)->host_scribble)
231 #define SET_NEXT(cmd,next)      ((cmd)->host_scribble = (void *)(next))
232 #define NEXTADDR(cmd)           ((struct scsi_cmnd **)&(cmd)->host_scribble)
233
234 #define HOSTNO          instance->host_no
235 #define H_NO(cmd)       (cmd)->device->host->host_no
236
237 static int do_abort(struct Scsi_Host *);
238 static void do_reset(struct Scsi_Host *);
239
240 #ifdef SUPPORT_TAGS
241
242 /*
243  * Functions for handling tagged queuing
244  * =====================================
245  *
246  * ++roman (01/96): Now I've implemented SCSI-2 tagged queuing. Some notes:
247  *
248  * Using consecutive numbers for the tags is no good idea in my eyes. There
249  * could be wrong re-usings if the counter (8 bit!) wraps and some early
250  * command has been preempted for a long time. My solution: a bitfield for
251  * remembering used tags.
252  *
253  * There's also the problem that each target has a certain queue size, but we
254  * cannot know it in advance :-( We just see a QUEUE_FULL status being
255  * returned. So, in this case, the driver internal queue size assumption is
256  * reduced to the number of active tags if QUEUE_FULL is returned by the
257  * target. The command is returned to the mid-level, but with status changed
258  * to BUSY, since --as I've seen-- the mid-level can't handle QUEUE_FULL
259  * correctly.
260  *
261  * We're also not allowed running tagged commands as long as an untagged
262  * command is active. And REQUEST SENSE commands after a contingent allegiance
263  * condition _must_ be untagged. To keep track whether an untagged command has
264  * been issued, the host->busy array is still employed, as it is without
265  * support for tagged queuing.
266  *
267  * One could suspect that there are possible race conditions between
268  * is_lun_busy(), cmd_get_tag() and cmd_free_tag(). But I think this isn't the
269  * case: is_lun_busy() and cmd_get_tag() are both called from NCR5380_main(),
270  * which already guaranteed to be running at most once. It is also the only
271  * place where tags/LUNs are allocated. So no other allocation can slip
272  * between that pair, there could only happen a reselection, which can free a
273  * tag, but that doesn't hurt. Only the sequence in cmd_free_tag() becomes
274  * important: the tag bit must be cleared before 'nr_allocated' is decreased.
275  */
276
277 static void __init init_tags(struct NCR5380_hostdata *hostdata)
278 {
279         int target, lun;
280         struct tag_alloc *ta;
281
282         if (!(hostdata->flags & FLAG_TAGGED_QUEUING))
283                 return;
284
285         for (target = 0; target < 8; ++target) {
286                 for (lun = 0; lun < 8; ++lun) {
287                         ta = &hostdata->TagAlloc[target][lun];
288                         bitmap_zero(ta->allocated, MAX_TAGS);
289                         ta->nr_allocated = 0;
290                         /* At the beginning, assume the maximum queue size we could
291                          * support (MAX_TAGS). This value will be decreased if the target
292                          * returns QUEUE_FULL status.
293                          */
294                         ta->queue_size = MAX_TAGS;
295                 }
296         }
297 }
298
299
300 /* Check if we can issue a command to this LUN: First see if the LUN is marked
301  * busy by an untagged command. If the command should use tagged queuing, also
302  * check that there is a free tag and the target's queue won't overflow. This
303  * function should be called with interrupts disabled to avoid race
304  * conditions.
305  */
306
307 static int is_lun_busy(struct scsi_cmnd *cmd, int should_be_tagged)
308 {
309         u8 lun = cmd->device->lun;
310         SETUP_HOSTDATA(cmd->device->host);
311
312         if (hostdata->busy[cmd->device->id] & (1 << lun))
313                 return 1;
314         if (!should_be_tagged ||
315             !(hostdata->flags & FLAG_TAGGED_QUEUING) ||
316             !cmd->device->tagged_supported)
317                 return 0;
318         if (hostdata->TagAlloc[scmd_id(cmd)][lun].nr_allocated >=
319             hostdata->TagAlloc[scmd_id(cmd)][lun].queue_size) {
320                 dprintk(NDEBUG_TAGS, "scsi%d: target %d lun %d: no free tags\n",
321                            H_NO(cmd), cmd->device->id, lun);
322                 return 1;
323         }
324         return 0;
325 }
326
327
328 /* Allocate a tag for a command (there are no checks anymore, check_lun_busy()
329  * must be called before!), or reserve the LUN in 'busy' if the command is
330  * untagged.
331  */
332
333 static void cmd_get_tag(struct scsi_cmnd *cmd, int should_be_tagged)
334 {
335         u8 lun = cmd->device->lun;
336         SETUP_HOSTDATA(cmd->device->host);
337
338         /* If we or the target don't support tagged queuing, allocate the LUN for
339          * an untagged command.
340          */
341         if (!should_be_tagged ||
342             !(hostdata->flags & FLAG_TAGGED_QUEUING) ||
343             !cmd->device->tagged_supported) {
344                 cmd->tag = TAG_NONE;
345                 hostdata->busy[cmd->device->id] |= (1 << lun);
346                 dprintk(NDEBUG_TAGS, "scsi%d: target %d lun %d now allocated by untagged "
347                            "command\n", H_NO(cmd), cmd->device->id, lun);
348         } else {
349                 struct tag_alloc *ta = &hostdata->TagAlloc[scmd_id(cmd)][lun];
350
351                 cmd->tag = find_first_zero_bit(ta->allocated, MAX_TAGS);
352                 set_bit(cmd->tag, ta->allocated);
353                 ta->nr_allocated++;
354                 dprintk(NDEBUG_TAGS, "scsi%d: using tag %d for target %d lun %d "
355                            "(now %d tags in use)\n",
356                            H_NO(cmd), cmd->tag, cmd->device->id,
357                            lun, ta->nr_allocated);
358         }
359 }
360
361
362 /* Mark the tag of command 'cmd' as free, or in case of an untagged command,
363  * unlock the LUN.
364  */
365
366 static void cmd_free_tag(struct scsi_cmnd *cmd)
367 {
368         u8 lun = cmd->device->lun;
369         SETUP_HOSTDATA(cmd->device->host);
370
371         if (cmd->tag == TAG_NONE) {
372                 hostdata->busy[cmd->device->id] &= ~(1 << lun);
373                 dprintk(NDEBUG_TAGS, "scsi%d: target %d lun %d untagged cmd finished\n",
374                            H_NO(cmd), cmd->device->id, lun);
375         } else if (cmd->tag >= MAX_TAGS) {
376                 printk(KERN_NOTICE "scsi%d: trying to free bad tag %d!\n",
377                        H_NO(cmd), cmd->tag);
378         } else {
379                 struct tag_alloc *ta = &hostdata->TagAlloc[scmd_id(cmd)][lun];
380                 clear_bit(cmd->tag, ta->allocated);
381                 ta->nr_allocated--;
382                 dprintk(NDEBUG_TAGS, "scsi%d: freed tag %d for target %d lun %d\n",
383                            H_NO(cmd), cmd->tag, cmd->device->id, lun);
384         }
385 }
386
387
388 static void free_all_tags(struct NCR5380_hostdata *hostdata)
389 {
390         int target, lun;
391         struct tag_alloc *ta;
392
393         if (!(hostdata->flags & FLAG_TAGGED_QUEUING))
394                 return;
395
396         for (target = 0; target < 8; ++target) {
397                 for (lun = 0; lun < 8; ++lun) {
398                         ta = &hostdata->TagAlloc[target][lun];
399                         bitmap_zero(ta->allocated, MAX_TAGS);
400                         ta->nr_allocated = 0;
401                 }
402         }
403 }
404
405 #endif /* SUPPORT_TAGS */
406
407
408 /*
409  * Function: void merge_contiguous_buffers( struct scsi_cmnd *cmd )
410  *
411  * Purpose: Try to merge several scatter-gather requests into one DMA
412  *    transfer. This is possible if the scatter buffers lie on
413  *    physical contiguous addresses.
414  *
415  * Parameters: struct scsi_cmnd *cmd
416  *    The command to work on. The first scatter buffer's data are
417  *    assumed to be already transferred into ptr/this_residual.
418  */
419
420 static void merge_contiguous_buffers(struct scsi_cmnd *cmd)
421 {
422 #if !defined(CONFIG_SUN3)
423         unsigned long endaddr;
424 #if (NDEBUG & NDEBUG_MERGING)
425         unsigned long oldlen = cmd->SCp.this_residual;
426         int cnt = 1;
427 #endif
428
429         for (endaddr = virt_to_phys(cmd->SCp.ptr + cmd->SCp.this_residual - 1) + 1;
430              cmd->SCp.buffers_residual &&
431              virt_to_phys(sg_virt(&cmd->SCp.buffer[1])) == endaddr;) {
432                 dprintk(NDEBUG_MERGING, "VTOP(%p) == %08lx -> merging\n",
433                            page_address(sg_page(&cmd->SCp.buffer[1])), endaddr);
434 #if (NDEBUG & NDEBUG_MERGING)
435                 ++cnt;
436 #endif
437                 ++cmd->SCp.buffer;
438                 --cmd->SCp.buffers_residual;
439                 cmd->SCp.this_residual += cmd->SCp.buffer->length;
440                 endaddr += cmd->SCp.buffer->length;
441         }
442 #if (NDEBUG & NDEBUG_MERGING)
443         if (oldlen != cmd->SCp.this_residual)
444                 dprintk(NDEBUG_MERGING, "merged %d buffers from %p, new length %08x\n",
445                            cnt, cmd->SCp.ptr, cmd->SCp.this_residual);
446 #endif
447 #endif /* !defined(CONFIG_SUN3) */
448 }
449
450 /**
451  * initialize_SCp - init the scsi pointer field
452  * @cmd: command block to set up
453  *
454  * Set up the internal fields in the SCSI command.
455  */
456
457 static inline void initialize_SCp(struct scsi_cmnd *cmd)
458 {
459         /*
460          * Initialize the Scsi Pointer field so that all of the commands in the
461          * various queues are valid.
462          */
463
464         if (scsi_bufflen(cmd)) {
465                 cmd->SCp.buffer = scsi_sglist(cmd);
466                 cmd->SCp.buffers_residual = scsi_sg_count(cmd) - 1;
467                 cmd->SCp.ptr = sg_virt(cmd->SCp.buffer);
468                 cmd->SCp.this_residual = cmd->SCp.buffer->length;
469                 /* ++roman: Try to merge some scatter-buffers if they are at
470                  * contiguous physical addresses.
471                  */
472                 merge_contiguous_buffers(cmd);
473         } else {
474                 cmd->SCp.buffer = NULL;
475                 cmd->SCp.buffers_residual = 0;
476                 cmd->SCp.ptr = NULL;
477                 cmd->SCp.this_residual = 0;
478         }
479 }
480
481 /**
482  * NCR5380_poll_politely - wait for NCR5380 status bits
483  * @instance: controller to poll
484  * @reg: 5380 register to poll
485  * @bit: Bitmask to check
486  * @val: Value required to exit
487  *
488  * Polls the NCR5380 in a reasonably efficient manner waiting for
489  * an event to occur, after a short quick poll we begin giving the
490  * CPU back in non IRQ contexts
491  *
492  * Returns the value of the register or a negative error code.
493  */
494
495 static int NCR5380_poll_politely(struct Scsi_Host *instance,
496                                  int reg, int bit, int val, int t)
497 {
498         int n = 500;
499         unsigned long end = jiffies + t;
500         int r;
501
502         while (n-- > 0) {
503                 r = NCR5380_read(reg);
504                 if ((r & bit) == val)
505                         return 0;
506                 cpu_relax();
507         }
508
509         /* t time yet ? */
510         while (time_before(jiffies, end)) {
511                 r = NCR5380_read(reg);
512                 if ((r & bit) == val)
513                         return 0;
514                 if (!in_interrupt())
515                         cond_resched();
516                 else
517                         cpu_relax();
518         }
519         return -ETIMEDOUT;
520 }
521
522 #include <linux/delay.h>
523
524 #if NDEBUG
525 static struct {
526         unsigned char mask;
527         const char *name;
528 } signals[] = {
529         { SR_DBP, "PARITY"}, { SR_RST, "RST" }, { SR_BSY, "BSY" },
530         { SR_REQ, "REQ" }, { SR_MSG, "MSG" }, { SR_CD,  "CD" }, { SR_IO, "IO" },
531         { SR_SEL, "SEL" }, {0, NULL}
532 }, basrs[] = {
533         {BASR_ATN, "ATN"}, {BASR_ACK, "ACK"}, {0, NULL}
534 }, icrs[] = {
535         {ICR_ASSERT_RST, "ASSERT RST"},{ICR_ASSERT_ACK, "ASSERT ACK"},
536         {ICR_ASSERT_BSY, "ASSERT BSY"}, {ICR_ASSERT_SEL, "ASSERT SEL"},
537         {ICR_ASSERT_ATN, "ASSERT ATN"}, {ICR_ASSERT_DATA, "ASSERT DATA"},
538         {0, NULL}
539 }, mrs[] = {
540         {MR_BLOCK_DMA_MODE, "MODE BLOCK DMA"}, {MR_TARGET, "MODE TARGET"},
541         {MR_ENABLE_PAR_CHECK, "MODE PARITY CHECK"}, {MR_ENABLE_PAR_INTR,
542         "MODE PARITY INTR"}, {MR_ENABLE_EOP_INTR,"MODE EOP INTR"},
543         {MR_MONITOR_BSY, "MODE MONITOR BSY"},
544         {MR_DMA_MODE, "MODE DMA"}, {MR_ARBITRATE, "MODE ARBITRATION"},
545         {0, NULL}
546 };
547
548 /**
549  * NCR5380_print - print scsi bus signals
550  * @instance: adapter state to dump
551  *
552  * Print the SCSI bus signals for debugging purposes
553  */
554
555 static void NCR5380_print(struct Scsi_Host *instance)
556 {
557         unsigned char status, data, basr, mr, icr, i;
558         unsigned long flags;
559
560         local_irq_save(flags);
561         data = NCR5380_read(CURRENT_SCSI_DATA_REG);
562         status = NCR5380_read(STATUS_REG);
563         mr = NCR5380_read(MODE_REG);
564         icr = NCR5380_read(INITIATOR_COMMAND_REG);
565         basr = NCR5380_read(BUS_AND_STATUS_REG);
566         local_irq_restore(flags);
567         printk("STATUS_REG: %02x ", status);
568         for (i = 0; signals[i].mask; ++i)
569                 if (status & signals[i].mask)
570                         printk(",%s", signals[i].name);
571         printk("\nBASR: %02x ", basr);
572         for (i = 0; basrs[i].mask; ++i)
573                 if (basr & basrs[i].mask)
574                         printk(",%s", basrs[i].name);
575         printk("\nICR: %02x ", icr);
576         for (i = 0; icrs[i].mask; ++i)
577                 if (icr & icrs[i].mask)
578                         printk(",%s", icrs[i].name);
579         printk("\nMODE: %02x ", mr);
580         for (i = 0; mrs[i].mask; ++i)
581                 if (mr & mrs[i].mask)
582                         printk(",%s", mrs[i].name);
583         printk("\n");
584 }
585
586 static struct {
587         unsigned char value;
588         const char *name;
589 } phases[] = {
590         {PHASE_DATAOUT, "DATAOUT"}, {PHASE_DATAIN, "DATAIN"}, {PHASE_CMDOUT, "CMDOUT"},
591         {PHASE_STATIN, "STATIN"}, {PHASE_MSGOUT, "MSGOUT"}, {PHASE_MSGIN, "MSGIN"},
592         {PHASE_UNKNOWN, "UNKNOWN"}
593 };
594
595 /**
596  * NCR5380_print_phase - show SCSI phase
597  * @instance: adapter to dump
598  *
599  * Print the current SCSI phase for debugging purposes
600  *
601  * Locks: none
602  */
603
604 static void NCR5380_print_phase(struct Scsi_Host *instance)
605 {
606         unsigned char status;
607         int i;
608
609         status = NCR5380_read(STATUS_REG);
610         if (!(status & SR_REQ))
611                 printk(KERN_DEBUG "scsi%d: REQ not asserted, phase unknown.\n", HOSTNO);
612         else {
613                 for (i = 0; (phases[i].value != PHASE_UNKNOWN) &&
614                      (phases[i].value != (status & PHASE_MASK)); ++i)
615                         ;
616                 printk(KERN_DEBUG "scsi%d: phase %s\n", HOSTNO, phases[i].name);
617         }
618 }
619
620 #endif
621
622 /*
623  * ++roman: New scheme of calling NCR5380_main()
624  *
625  * If we're not in an interrupt, we can call our main directly, it cannot be
626  * already running. Else, we queue it on a task queue, if not 'main_running'
627  * tells us that a lower level is already executing it. This way,
628  * 'main_running' needs not be protected in a special way.
629  *
630  * queue_main() is a utility function for putting our main onto the task
631  * queue, if main_running is false. It should be called only from a
632  * interrupt or bottom half.
633  */
634
635 #include <linux/gfp.h>
636 #include <linux/workqueue.h>
637 #include <linux/interrupt.h>
638
639 static inline void queue_main(struct NCR5380_hostdata *hostdata)
640 {
641         if (!hostdata->main_running) {
642                 /* If in interrupt and NCR5380_main() not already running,
643                    queue it on the 'immediate' task queue, to be processed
644                    immediately after the current interrupt processing has
645                    finished. */
646                 schedule_work(&hostdata->main_task);
647         }
648         /* else: nothing to do: the running NCR5380_main() will pick up
649            any newly queued command. */
650 }
651
652 /**
653  * NCR58380_info - report driver and host information
654  * @instance: relevant scsi host instance
655  *
656  * For use as the host template info() handler.
657  *
658  * Locks: none
659  */
660
661 static const char *NCR5380_info(struct Scsi_Host *instance)
662 {
663         struct NCR5380_hostdata *hostdata = shost_priv(instance);
664
665         return hostdata->info;
666 }
667
668 static void prepare_info(struct Scsi_Host *instance)
669 {
670         struct NCR5380_hostdata *hostdata = shost_priv(instance);
671
672         snprintf(hostdata->info, sizeof(hostdata->info),
673                  "%s, io_port 0x%lx, n_io_port %d, "
674                  "base 0x%lx, irq %d, "
675                  "can_queue %d, cmd_per_lun %d, "
676                  "sg_tablesize %d, this_id %d, "
677                  "flags { %s%s}, "
678                  "options { %s} ",
679                  instance->hostt->name, instance->io_port, instance->n_io_port,
680                  instance->base, instance->irq,
681                  instance->can_queue, instance->cmd_per_lun,
682                  instance->sg_tablesize, instance->this_id,
683                  hostdata->flags & FLAG_TAGGED_QUEUING ? "TAGGED_QUEUING " : "",
684                  hostdata->flags & FLAG_TOSHIBA_DELAY  ? "TOSHIBA_DELAY "  : "",
685 #ifdef DIFFERENTIAL
686                  "DIFFERENTIAL "
687 #endif
688 #ifdef REAL_DMA
689                  "REAL_DMA "
690 #endif
691 #ifdef PARITY
692                  "PARITY "
693 #endif
694 #ifdef SUPPORT_TAGS
695                  "SUPPORT_TAGS "
696 #endif
697                  "");
698 }
699
700 /**
701  * NCR5380_print_status - dump controller info
702  * @instance: controller to dump
703  *
704  * Print commands in the various queues, called from NCR5380_abort
705  * to aid debugging.
706  */
707
708 static void lprint_Scsi_Cmnd(struct scsi_cmnd *cmd)
709 {
710         int i, s;
711         unsigned char *command;
712         printk("scsi%d: destination target %d, lun %llu\n",
713                 H_NO(cmd), cmd->device->id, cmd->device->lun);
714         printk(KERN_CONT "        command = ");
715         command = cmd->cmnd;
716         printk(KERN_CONT "%2d (0x%02x)", command[0], command[0]);
717         for (i = 1, s = COMMAND_SIZE(command[0]); i < s; ++i)
718                 printk(KERN_CONT " %02x", command[i]);
719         printk("\n");
720 }
721
722 static void __maybe_unused NCR5380_print_status(struct Scsi_Host *instance)
723 {
724         struct NCR5380_hostdata *hostdata;
725         struct scsi_cmnd *ptr;
726         unsigned long flags;
727
728         NCR5380_dprint(NDEBUG_ANY, instance);
729         NCR5380_dprint_phase(NDEBUG_ANY, instance);
730
731         hostdata = (struct NCR5380_hostdata *)instance->hostdata;
732
733         local_irq_save(flags);
734         printk("NCR5380: coroutine is%s running.\n",
735                 hostdata->main_running ? "" : "n't");
736         if (!hostdata->connected)
737                 printk("scsi%d: no currently connected command\n", HOSTNO);
738         else
739                 lprint_Scsi_Cmnd((struct scsi_cmnd *) hostdata->connected);
740         printk("scsi%d: issue_queue\n", HOSTNO);
741         for (ptr = (struct scsi_cmnd *)hostdata->issue_queue; ptr; ptr = NEXT(ptr))
742                 lprint_Scsi_Cmnd(ptr);
743
744         printk("scsi%d: disconnected_queue\n", HOSTNO);
745         for (ptr = (struct scsi_cmnd *) hostdata->disconnected_queue; ptr;
746              ptr = NEXT(ptr))
747                 lprint_Scsi_Cmnd(ptr);
748
749         local_irq_restore(flags);
750         printk("\n");
751 }
752
753 static void show_Scsi_Cmnd(struct scsi_cmnd *cmd, struct seq_file *m)
754 {
755         int i, s;
756         unsigned char *command;
757         seq_printf(m, "scsi%d: destination target %d, lun %llu\n",
758                 H_NO(cmd), cmd->device->id, cmd->device->lun);
759         seq_puts(m, "        command = ");
760         command = cmd->cmnd;
761         seq_printf(m, "%2d (0x%02x)", command[0], command[0]);
762         for (i = 1, s = COMMAND_SIZE(command[0]); i < s; ++i)
763                 seq_printf(m, " %02x", command[i]);
764         seq_putc(m, '\n');
765 }
766
767 static int __maybe_unused NCR5380_show_info(struct seq_file *m,
768                                             struct Scsi_Host *instance)
769 {
770         struct NCR5380_hostdata *hostdata;
771         struct scsi_cmnd *ptr;
772         unsigned long flags;
773
774         hostdata = (struct NCR5380_hostdata *)instance->hostdata;
775
776         local_irq_save(flags);
777         seq_printf(m, "NCR5380: coroutine is%s running.\n",
778                 hostdata->main_running ? "" : "n't");
779         if (!hostdata->connected)
780                 seq_printf(m, "scsi%d: no currently connected command\n", HOSTNO);
781         else
782                 show_Scsi_Cmnd((struct scsi_cmnd *) hostdata->connected, m);
783         seq_printf(m, "scsi%d: issue_queue\n", HOSTNO);
784         for (ptr = (struct scsi_cmnd *)hostdata->issue_queue; ptr; ptr = NEXT(ptr))
785                 show_Scsi_Cmnd(ptr, m);
786
787         seq_printf(m, "scsi%d: disconnected_queue\n", HOSTNO);
788         for (ptr = (struct scsi_cmnd *) hostdata->disconnected_queue; ptr;
789              ptr = NEXT(ptr))
790                 show_Scsi_Cmnd(ptr, m);
791
792         local_irq_restore(flags);
793         return 0;
794 }
795
796 /**
797  * NCR5380_init - initialise an NCR5380
798  * @instance: adapter to configure
799  * @flags: control flags
800  *
801  * Initializes *instance and corresponding 5380 chip,
802  * with flags OR'd into the initial flags value.
803  *
804  * Notes : I assume that the host, hostno, and id bits have been
805  * set correctly. I don't care about the irq and other fields.
806  *
807  * Returns 0 for success
808  */
809
810 static int __init NCR5380_init(struct Scsi_Host *instance, int flags)
811 {
812         int i;
813         SETUP_HOSTDATA(instance);
814
815         hostdata->host = instance;
816         hostdata->id_mask = 1 << instance->this_id;
817         hostdata->id_higher_mask = 0;
818         for (i = hostdata->id_mask; i <= 0x80; i <<= 1)
819                 if (i > hostdata->id_mask)
820                         hostdata->id_higher_mask |= i;
821         for (i = 0; i < 8; ++i)
822                 hostdata->busy[i] = 0;
823 #ifdef SUPPORT_TAGS
824         init_tags(hostdata);
825 #endif
826 #if defined (REAL_DMA)
827         hostdata->dma_len = 0;
828 #endif
829         hostdata->connected = NULL;
830         hostdata->issue_queue = NULL;
831         hostdata->disconnected_queue = NULL;
832         hostdata->flags = flags;
833
834         INIT_WORK(&hostdata->main_task, NCR5380_main);
835
836         prepare_info(instance);
837
838         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
839         NCR5380_write(MODE_REG, MR_BASE);
840         NCR5380_write(TARGET_COMMAND_REG, 0);
841         NCR5380_write(SELECT_ENABLE_REG, 0);
842
843         return 0;
844 }
845
846 /**
847  * NCR5380_maybe_reset_bus - Detect and correct bus wedge problems.
848  * @instance: adapter to check
849  *
850  * If the system crashed, it may have crashed with a connected target and
851  * the SCSI bus busy. Check for BUS FREE phase. If not, try to abort the
852  * currently established nexus, which we know nothing about. Failing that
853  * do a bus reset.
854  *
855  * Note that a bus reset will cause the chip to assert IRQ.
856  *
857  * Returns 0 if successful, otherwise -ENXIO.
858  */
859
860 static int NCR5380_maybe_reset_bus(struct Scsi_Host *instance)
861 {
862         struct NCR5380_hostdata *hostdata = shost_priv(instance);
863         int pass;
864
865         for (pass = 1; (NCR5380_read(STATUS_REG) & SR_BSY) && pass <= 6; ++pass) {
866                 switch (pass) {
867                 case 1:
868                 case 3:
869                 case 5:
870                         shost_printk(KERN_ERR, instance, "SCSI bus busy, waiting up to five seconds\n");
871                         NCR5380_poll_politely(instance,
872                                               STATUS_REG, SR_BSY, 0, 5 * HZ);
873                         break;
874                 case 2:
875                         shost_printk(KERN_ERR, instance, "bus busy, attempting abort\n");
876                         do_abort(instance);
877                         break;
878                 case 4:
879                         shost_printk(KERN_ERR, instance, "bus busy, attempting reset\n");
880                         do_reset(instance);
881                         /* Wait after a reset; the SCSI standard calls for
882                          * 250ms, we wait 500ms to be on the safe side.
883                          * But some Toshiba CD-ROMs need ten times that.
884                          */
885                         if (hostdata->flags & FLAG_TOSHIBA_DELAY)
886                                 msleep(2500);
887                         else
888                                 msleep(500);
889                         break;
890                 case 6:
891                         shost_printk(KERN_ERR, instance, "bus locked solid\n");
892                         return -ENXIO;
893                 }
894         }
895         return 0;
896 }
897
898 /**
899  * NCR5380_exit - remove an NCR5380
900  * @instance: adapter to remove
901  *
902  * Assumes that no more work can be queued (e.g. by NCR5380_intr).
903  */
904
905 static void NCR5380_exit(struct Scsi_Host *instance)
906 {
907         struct NCR5380_hostdata *hostdata = shost_priv(instance);
908
909         cancel_work_sync(&hostdata->main_task);
910 }
911
912 /**
913  * NCR5380_queue_command - queue a command
914  * @instance: the relevant SCSI adapter
915  * @cmd: SCSI command
916  *
917  * cmd is added to the per instance issue_queue, with minor
918  * twiddling done to the host specific fields of cmd.  If the
919  * main coroutine is not running, it is restarted.
920  */
921
922 static int NCR5380_queue_command(struct Scsi_Host *instance,
923                                  struct scsi_cmnd *cmd)
924 {
925         struct NCR5380_hostdata *hostdata = shost_priv(instance);
926         struct scsi_cmnd *tmp;
927         unsigned long flags;
928
929 #if (NDEBUG & NDEBUG_NO_WRITE)
930         switch (cmd->cmnd[0]) {
931         case WRITE_6:
932         case WRITE_10:
933                 printk(KERN_NOTICE "scsi%d: WRITE attempted with NO_WRITE debugging flag set\n",
934                        H_NO(cmd));
935                 cmd->result = (DID_ERROR << 16);
936                 cmd->scsi_done(cmd);
937                 return 0;
938         }
939 #endif /* (NDEBUG & NDEBUG_NO_WRITE) */
940
941         /*
942          * We use the host_scribble field as a pointer to the next command
943          * in a queue
944          */
945
946         SET_NEXT(cmd, NULL);
947         cmd->result = 0;
948
949         /*
950          * Insert the cmd into the issue queue. Note that REQUEST SENSE
951          * commands are added to the head of the queue since any command will
952          * clear the contingent allegiance condition that exists and the
953          * sense data is only guaranteed to be valid while the condition exists.
954          */
955
956         /* ++guenther: now that the issue queue is being set up, we can lock ST-DMA.
957          * Otherwise a running NCR5380_main may steal the lock.
958          * Lock before actually inserting due to fairness reasons explained in
959          * atari_scsi.c. If we insert first, then it's impossible for this driver
960          * to release the lock.
961          * Stop timer for this command while waiting for the lock, or timeouts
962          * may happen (and they really do), and it's no good if the command doesn't
963          * appear in any of the queues.
964          * ++roman: Just disabling the NCR interrupt isn't sufficient here,
965          * because also a timer int can trigger an abort or reset, which would
966          * alter queues and touch the lock.
967          */
968         if (!NCR5380_acquire_dma_irq(instance))
969                 return SCSI_MLQUEUE_HOST_BUSY;
970
971         local_irq_save(flags);
972
973         /*
974          * Insert the cmd into the issue queue. Note that REQUEST SENSE
975          * commands are added to the head of the queue since any command will
976          * clear the contingent allegiance condition that exists and the
977          * sense data is only guaranteed to be valid while the condition exists.
978          */
979
980         if (!(hostdata->issue_queue) || (cmd->cmnd[0] == REQUEST_SENSE)) {
981                 LIST(cmd, hostdata->issue_queue);
982                 SET_NEXT(cmd, hostdata->issue_queue);
983                 hostdata->issue_queue = cmd;
984         } else {
985                 for (tmp = (struct scsi_cmnd *)hostdata->issue_queue;
986                      NEXT(tmp); tmp = NEXT(tmp))
987                         ;
988                 LIST(cmd, tmp);
989                 SET_NEXT(tmp, cmd);
990         }
991         local_irq_restore(flags);
992
993         dprintk(NDEBUG_QUEUES, "scsi%d: command added to %s of queue\n", H_NO(cmd),
994                   (cmd->cmnd[0] == REQUEST_SENSE) ? "head" : "tail");
995
996         /* If queue_command() is called from an interrupt (real one or bottom
997          * half), we let queue_main() do the job of taking care about main. If it
998          * is already running, this is a no-op, else main will be queued.
999          *
1000          * If we're not in an interrupt, we can call NCR5380_main()
1001          * unconditionally, because it cannot be already running.
1002          */
1003         if (in_interrupt() || irqs_disabled())
1004                 queue_main(hostdata);
1005         else
1006                 NCR5380_main(&hostdata->main_task);
1007         return 0;
1008 }
1009
1010 static inline void maybe_release_dma_irq(struct Scsi_Host *instance)
1011 {
1012         struct NCR5380_hostdata *hostdata = shost_priv(instance);
1013
1014         /* Caller does the locking needed to set & test these data atomically */
1015         if (!hostdata->disconnected_queue &&
1016             !hostdata->issue_queue &&
1017             !hostdata->connected &&
1018             !hostdata->retain_dma_intr)
1019                 NCR5380_release_dma_irq(instance);
1020 }
1021
1022 /**
1023  * NCR5380_main - NCR state machines
1024  *
1025  * NCR5380_main is a coroutine that runs as long as more work can
1026  * be done on the NCR5380 host adapters in a system.  Both
1027  * NCR5380_queue_command() and NCR5380_intr() will try to start it
1028  * in case it is not running.
1029  *
1030  * Locks: called as its own thread with no locks held.
1031  */
1032
1033 static void NCR5380_main(struct work_struct *work)
1034 {
1035         struct NCR5380_hostdata *hostdata =
1036                 container_of(work, struct NCR5380_hostdata, main_task);
1037         struct Scsi_Host *instance = hostdata->host;
1038         struct scsi_cmnd *tmp, *prev;
1039         int done;
1040         unsigned long flags;
1041
1042         /*
1043          * We run (with interrupts disabled) until we're sure that none of
1044          * the host adapters have anything that can be done, at which point
1045          * we set main_running to 0 and exit.
1046          *
1047          * Interrupts are enabled before doing various other internal
1048          * instructions, after we've decided that we need to run through
1049          * the loop again.
1050          *
1051          * this should prevent any race conditions.
1052          *
1053          * ++roman: Just disabling the NCR interrupt isn't sufficient here,
1054          * because also a timer int can trigger an abort or reset, which can
1055          * alter queues and touch the Falcon lock.
1056          */
1057
1058         /* Tell int handlers main() is now already executing.  Note that
1059            no races are possible here. If an int comes in before
1060            'main_running' is set here, and queues/executes main via the
1061            task queue, it doesn't do any harm, just this instance of main
1062            won't find any work left to do. */
1063         if (hostdata->main_running)
1064                 return;
1065         hostdata->main_running = 1;
1066
1067         local_save_flags(flags);
1068         do {
1069                 local_irq_disable();    /* Freeze request queues */
1070                 done = 1;
1071
1072                 if (!hostdata->connected) {
1073                         dprintk(NDEBUG_MAIN, "scsi%d: not connected\n", HOSTNO);
1074                         /*
1075                          * Search through the issue_queue for a command destined
1076                          * for a target that's not busy.
1077                          */
1078 #if (NDEBUG & NDEBUG_LISTS)
1079                         for (tmp = (struct scsi_cmnd *) hostdata->issue_queue, prev = NULL;
1080                              tmp && (tmp != prev); prev = tmp, tmp = NEXT(tmp))
1081                                 ;
1082                         /*printk("%p  ", tmp);*/
1083                         if ((tmp == prev) && tmp)
1084                                 printk(" LOOP\n");
1085                         /* else printk("\n"); */
1086 #endif
1087                         for (tmp = (struct scsi_cmnd *) hostdata->issue_queue,
1088                              prev = NULL; tmp; prev = tmp, tmp = NEXT(tmp)) {
1089                                 u8 lun = tmp->device->lun;
1090
1091                                 dprintk(NDEBUG_LISTS,
1092                                         "MAIN tmp=%p target=%d busy=%d lun=%d\n",
1093                                         tmp, scmd_id(tmp), hostdata->busy[scmd_id(tmp)],
1094                                         lun);
1095                                 /*  When we find one, remove it from the issue queue. */
1096                                 /* ++guenther: possible race with Falcon locking */
1097                                 if (
1098 #ifdef SUPPORT_TAGS
1099                                     !is_lun_busy( tmp, tmp->cmnd[0] != REQUEST_SENSE)
1100 #else
1101                                     !(hostdata->busy[tmp->device->id] & (1 << lun))
1102 #endif
1103                                     ) {
1104                                         /* ++guenther: just to be sure, this must be atomic */
1105                                         local_irq_disable();
1106                                         if (prev) {
1107                                                 REMOVE(prev, NEXT(prev), tmp, NEXT(tmp));
1108                                                 SET_NEXT(prev, NEXT(tmp));
1109                                         } else {
1110                                                 REMOVE(-1, hostdata->issue_queue, tmp, NEXT(tmp));
1111                                                 hostdata->issue_queue = NEXT(tmp);
1112                                         }
1113                                         SET_NEXT(tmp, NULL);
1114                                         hostdata->retain_dma_intr++;
1115
1116                                         /* reenable interrupts after finding one */
1117                                         local_irq_restore(flags);
1118
1119                                         /*
1120                                          * Attempt to establish an I_T_L nexus here.
1121                                          * On success, instance->hostdata->connected is set.
1122                                          * On failure, we must add the command back to the
1123                                          *   issue queue so we can keep trying.
1124                                          */
1125                                         dprintk(NDEBUG_MAIN, "scsi%d: main(): command for target %d "
1126                                                     "lun %d removed from issue_queue\n",
1127                                                     HOSTNO, tmp->device->id, lun);
1128                                         /*
1129                                          * REQUEST SENSE commands are issued without tagged
1130                                          * queueing, even on SCSI-II devices because the
1131                                          * contingent allegiance condition exists for the
1132                                          * entire unit.
1133                                          */
1134                                         /* ++roman: ...and the standard also requires that
1135                                          * REQUEST SENSE command are untagged.
1136                                          */
1137
1138 #ifdef SUPPORT_TAGS
1139                                         cmd_get_tag(tmp, tmp->cmnd[0] != REQUEST_SENSE);
1140 #endif
1141                                         if (!NCR5380_select(instance, tmp)) {
1142                                                 local_irq_disable();
1143                                                 hostdata->retain_dma_intr--;
1144                                                 /* release if target did not response! */
1145                                                 maybe_release_dma_irq(instance);
1146                                                 local_irq_restore(flags);
1147                                                 break;
1148                                         } else {
1149                                                 local_irq_disable();
1150                                                 LIST(tmp, hostdata->issue_queue);
1151                                                 SET_NEXT(tmp, hostdata->issue_queue);
1152                                                 hostdata->issue_queue = tmp;
1153 #ifdef SUPPORT_TAGS
1154                                                 cmd_free_tag(tmp);
1155 #endif
1156                                                 hostdata->retain_dma_intr--;
1157                                                 local_irq_restore(flags);
1158                                                 dprintk(NDEBUG_MAIN, "scsi%d: main(): select() failed, "
1159                                                             "returned to issue_queue\n", HOSTNO);
1160                                                 if (hostdata->connected)
1161                                                         break;
1162                                         }
1163                                 } /* if target/lun/target queue is not busy */
1164                         } /* for issue_queue */
1165                 } /* if (!hostdata->connected) */
1166
1167                 if (hostdata->connected
1168 #ifdef REAL_DMA
1169                     && !hostdata->dma_len
1170 #endif
1171                     ) {
1172                         local_irq_restore(flags);
1173                         dprintk(NDEBUG_MAIN, "scsi%d: main: performing information transfer\n",
1174                                     HOSTNO);
1175                         NCR5380_information_transfer(instance);
1176                         dprintk(NDEBUG_MAIN, "scsi%d: main: done set false\n", HOSTNO);
1177                         done = 0;
1178                 }
1179         } while (!done);
1180
1181         /* Better allow ints _after_ 'main_running' has been cleared, else
1182            an interrupt could believe we'll pick up the work it left for
1183            us, but we won't see it anymore here... */
1184         hostdata->main_running = 0;
1185         local_irq_restore(flags);
1186 }
1187
1188
1189 #ifdef REAL_DMA
1190 /*
1191  * Function : void NCR5380_dma_complete (struct Scsi_Host *instance)
1192  *
1193  * Purpose : Called by interrupt handler when DMA finishes or a phase
1194  *      mismatch occurs (which would finish the DMA transfer).
1195  *
1196  * Inputs : instance - this instance of the NCR5380.
1197  *
1198  */
1199
1200 static void NCR5380_dma_complete(struct Scsi_Host *instance)
1201 {
1202         SETUP_HOSTDATA(instance);
1203         int transferred;
1204         unsigned char **data;
1205         volatile int *count;
1206         int saved_data = 0, overrun = 0;
1207         unsigned char p;
1208
1209         if (!hostdata->connected) {
1210                 printk(KERN_WARNING "scsi%d: received end of DMA interrupt with "
1211                        "no connected cmd\n", HOSTNO);
1212                 return;
1213         }
1214
1215         if (hostdata->read_overruns) {
1216                 p = hostdata->connected->SCp.phase;
1217                 if (p & SR_IO) {
1218                         udelay(10);
1219                         if ((NCR5380_read(BUS_AND_STATUS_REG) &
1220                              (BASR_PHASE_MATCH|BASR_ACK)) ==
1221                             (BASR_PHASE_MATCH|BASR_ACK)) {
1222                                 saved_data = NCR5380_read(INPUT_DATA_REG);
1223                                 overrun = 1;
1224                                 dprintk(NDEBUG_DMA, "scsi%d: read overrun handled\n", HOSTNO);
1225                         }
1226                 }
1227         }
1228
1229         dprintk(NDEBUG_DMA, "scsi%d: real DMA transfer complete, basr 0x%X, sr 0x%X\n",
1230                    HOSTNO, NCR5380_read(BUS_AND_STATUS_REG),
1231                    NCR5380_read(STATUS_REG));
1232
1233 #if defined(CONFIG_SUN3)
1234         if ((sun3scsi_dma_finish(rq_data_dir(hostdata->connected->request)))) {
1235                 pr_err("scsi%d: overrun in UDC counter -- not prepared to deal with this!\n",
1236                        instance->host_no);
1237                 BUG();
1238         }
1239
1240         /* make sure we're not stuck in a data phase */
1241         if ((NCR5380_read(BUS_AND_STATUS_REG) & (BASR_PHASE_MATCH | BASR_ACK)) ==
1242             (BASR_PHASE_MATCH | BASR_ACK)) {
1243                 pr_err("scsi%d: BASR %02x\n", instance->host_no,
1244                        NCR5380_read(BUS_AND_STATUS_REG));
1245                 pr_err("scsi%d: bus stuck in data phase -- probably a single byte overrun!\n",
1246                        instance->host_no);
1247                 BUG();
1248         }
1249 #endif
1250
1251         (void)NCR5380_read(RESET_PARITY_INTERRUPT_REG);
1252         NCR5380_write(MODE_REG, MR_BASE);
1253         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1254
1255         transferred = hostdata->dma_len - NCR5380_dma_residual(instance);
1256         hostdata->dma_len = 0;
1257
1258         data = (unsigned char **)&hostdata->connected->SCp.ptr;
1259         count = &hostdata->connected->SCp.this_residual;
1260         *data += transferred;
1261         *count -= transferred;
1262
1263         if (hostdata->read_overruns) {
1264                 int cnt, toPIO;
1265
1266                 if ((NCR5380_read(STATUS_REG) & PHASE_MASK) == p && (p & SR_IO)) {
1267                         cnt = toPIO = hostdata->read_overruns;
1268                         if (overrun) {
1269                                 dprintk(NDEBUG_DMA, "Got an input overrun, using saved byte\n");
1270                                 *(*data)++ = saved_data;
1271                                 (*count)--;
1272                                 cnt--;
1273                                 toPIO--;
1274                         }
1275                         dprintk(NDEBUG_DMA, "Doing %d-byte PIO to 0x%08lx\n", cnt, (long)*data);
1276                         NCR5380_transfer_pio(instance, &p, &cnt, data);
1277                         *count -= toPIO - cnt;
1278                 }
1279         }
1280 }
1281 #endif /* REAL_DMA */
1282
1283
1284 /**
1285  * NCR5380_intr - generic NCR5380 irq handler
1286  * @irq: interrupt number
1287  * @dev_id: device info
1288  *
1289  * Handle interrupts, reestablishing I_T_L or I_T_L_Q nexuses
1290  * from the disconnected queue, and restarting NCR5380_main()
1291  * as required.
1292  */
1293
1294 static irqreturn_t NCR5380_intr(int irq, void *dev_id)
1295 {
1296         struct Scsi_Host *instance = dev_id;
1297         int done = 1, handled = 0;
1298         unsigned char basr;
1299
1300         dprintk(NDEBUG_INTR, "scsi%d: NCR5380 irq triggered\n", HOSTNO);
1301
1302         /* Look for pending interrupts */
1303         basr = NCR5380_read(BUS_AND_STATUS_REG);
1304         dprintk(NDEBUG_INTR, "scsi%d: BASR=%02x\n", HOSTNO, basr);
1305         /* dispatch to appropriate routine if found and done=0 */
1306         if (basr & BASR_IRQ) {
1307                 NCR5380_dprint(NDEBUG_INTR, instance);
1308                 if ((NCR5380_read(STATUS_REG) & (SR_SEL|SR_IO)) == (SR_SEL|SR_IO)) {
1309                         done = 0;
1310                         dprintk(NDEBUG_INTR, "scsi%d: SEL interrupt\n", HOSTNO);
1311                         NCR5380_reselect(instance);
1312                         (void)NCR5380_read(RESET_PARITY_INTERRUPT_REG);
1313                 } else if (basr & BASR_PARITY_ERROR) {
1314                         dprintk(NDEBUG_INTR, "scsi%d: PARITY interrupt\n", HOSTNO);
1315                         (void)NCR5380_read(RESET_PARITY_INTERRUPT_REG);
1316                 } else if ((NCR5380_read(STATUS_REG) & SR_RST) == SR_RST) {
1317                         dprintk(NDEBUG_INTR, "scsi%d: RESET interrupt\n", HOSTNO);
1318                         (void)NCR5380_read(RESET_PARITY_INTERRUPT_REG);
1319                 } else {
1320                         /*
1321                          * The rest of the interrupt conditions can occur only during a
1322                          * DMA transfer
1323                          */
1324
1325 #if defined(REAL_DMA)
1326                         /*
1327                          * We should only get PHASE MISMATCH and EOP interrupts if we have
1328                          * DMA enabled, so do a sanity check based on the current setting
1329                          * of the MODE register.
1330                          */
1331
1332                         if ((NCR5380_read(MODE_REG) & MR_DMA_MODE) &&
1333                             ((basr & BASR_END_DMA_TRANSFER) ||
1334                              !(basr & BASR_PHASE_MATCH))) {
1335
1336                                 dprintk(NDEBUG_INTR, "scsi%d: PHASE MISM or EOP interrupt\n", HOSTNO);
1337                                 NCR5380_dma_complete( instance );
1338                                 done = 0;
1339                         } else
1340 #endif /* REAL_DMA */
1341                         {
1342 /* MS: Ignore unknown phase mismatch interrupts (caused by EOP interrupt) */
1343                                 if (basr & BASR_PHASE_MATCH)
1344                                         dprintk(NDEBUG_INTR, "scsi%d: unknown interrupt, "
1345                                                "BASR 0x%x, MR 0x%x, SR 0x%x\n",
1346                                                HOSTNO, basr, NCR5380_read(MODE_REG),
1347                                                NCR5380_read(STATUS_REG));
1348                                 (void)NCR5380_read(RESET_PARITY_INTERRUPT_REG);
1349 #ifdef SUN3_SCSI_VME
1350                                 dregs->csr |= CSR_DMA_ENABLE;
1351 #endif
1352                         }
1353                 } /* if !(SELECTION || PARITY) */
1354                 handled = 1;
1355         } /* BASR & IRQ */ else {
1356                 printk(KERN_NOTICE "scsi%d: interrupt without IRQ bit set in BASR, "
1357                        "BASR 0x%X, MR 0x%X, SR 0x%x\n", HOSTNO, basr,
1358                        NCR5380_read(MODE_REG), NCR5380_read(STATUS_REG));
1359                 (void)NCR5380_read(RESET_PARITY_INTERRUPT_REG);
1360 #ifdef SUN3_SCSI_VME
1361                 dregs->csr |= CSR_DMA_ENABLE;
1362 #endif
1363         }
1364
1365         if (!done) {
1366                 dprintk(NDEBUG_INTR, "scsi%d: in int routine, calling main\n", HOSTNO);
1367                 /* Put a call to NCR5380_main() on the queue... */
1368                 queue_main(shost_priv(instance));
1369         }
1370         return IRQ_RETVAL(handled);
1371 }
1372
1373 /*
1374  * Function : int NCR5380_select(struct Scsi_Host *instance,
1375  *                               struct scsi_cmnd *cmd)
1376  *
1377  * Purpose : establishes I_T_L or I_T_L_Q nexus for new or existing command,
1378  *      including ARBITRATION, SELECTION, and initial message out for
1379  *      IDENTIFY and queue messages.
1380  *
1381  * Inputs : instance - instantiation of the 5380 driver on which this
1382  *      target lives, cmd - SCSI command to execute.
1383  *
1384  * Returns : -1 if selection failed but should be retried.
1385  *      0 if selection failed and should not be retried.
1386  *      0 if selection succeeded completely (hostdata->connected == cmd).
1387  *
1388  * Side effects :
1389  *      If bus busy, arbitration failed, etc, NCR5380_select() will exit
1390  *              with registers as they should have been on entry - ie
1391  *              SELECT_ENABLE will be set appropriately, the NCR5380
1392  *              will cease to drive any SCSI bus signals.
1393  *
1394  *      If successful : I_T_L or I_T_L_Q nexus will be established,
1395  *              instance->connected will be set to cmd.
1396  *              SELECT interrupt will be disabled.
1397  *
1398  *      If failed (no target) : cmd->scsi_done() will be called, and the
1399  *              cmd->result host byte set to DID_BAD_TARGET.
1400  */
1401
1402 static int NCR5380_select(struct Scsi_Host *instance, struct scsi_cmnd *cmd)
1403 {
1404         SETUP_HOSTDATA(instance);
1405         unsigned char tmp[3], phase;
1406         unsigned char *data;
1407         int len;
1408         unsigned long timeout;
1409         unsigned long flags;
1410
1411         NCR5380_dprint(NDEBUG_ARBITRATION, instance);
1412         dprintk(NDEBUG_ARBITRATION, "scsi%d: starting arbitration, id = %d\n", HOSTNO,
1413                    instance->this_id);
1414
1415         /*
1416          * Set the phase bits to 0, otherwise the NCR5380 won't drive the
1417          * data bus during SELECTION.
1418          */
1419
1420         local_irq_save(flags);
1421         if (hostdata->connected) {
1422                 local_irq_restore(flags);
1423                 return -1;
1424         }
1425         NCR5380_write(TARGET_COMMAND_REG, 0);
1426
1427         /*
1428          * Start arbitration.
1429          */
1430
1431         NCR5380_write(OUTPUT_DATA_REG, hostdata->id_mask);
1432         NCR5380_write(MODE_REG, MR_ARBITRATE);
1433
1434         local_irq_restore(flags);
1435
1436         /* Wait for arbitration logic to complete */
1437 #if defined(NCR_TIMEOUT)
1438         {
1439                 unsigned long timeout = jiffies + 2*NCR_TIMEOUT;
1440
1441                 while (!(NCR5380_read(INITIATOR_COMMAND_REG) & ICR_ARBITRATION_PROGRESS) &&
1442                        time_before(jiffies, timeout) && !hostdata->connected)
1443                         ;
1444                 if (time_after_eq(jiffies, timeout)) {
1445                         printk("scsi : arbitration timeout at %d\n", __LINE__);
1446                         NCR5380_write(MODE_REG, MR_BASE);
1447                         NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
1448                         return -1;
1449                 }
1450         }
1451 #else /* NCR_TIMEOUT */
1452         while (!(NCR5380_read(INITIATOR_COMMAND_REG) & ICR_ARBITRATION_PROGRESS) &&
1453                !hostdata->connected)
1454                 ;
1455 #endif
1456
1457         dprintk(NDEBUG_ARBITRATION, "scsi%d: arbitration complete\n", HOSTNO);
1458
1459         if (hostdata->connected) {
1460                 NCR5380_write(MODE_REG, MR_BASE);
1461                 return -1;
1462         }
1463         /*
1464          * The arbitration delay is 2.2us, but this is a minimum and there is
1465          * no maximum so we can safely sleep for ceil(2.2) usecs to accommodate
1466          * the integral nature of udelay().
1467          *
1468          */
1469
1470         udelay(3);
1471
1472         /* Check for lost arbitration */
1473         if ((NCR5380_read(INITIATOR_COMMAND_REG) & ICR_ARBITRATION_LOST) ||
1474             (NCR5380_read(CURRENT_SCSI_DATA_REG) & hostdata->id_higher_mask) ||
1475             (NCR5380_read(INITIATOR_COMMAND_REG) & ICR_ARBITRATION_LOST) ||
1476             hostdata->connected) {
1477                 NCR5380_write(MODE_REG, MR_BASE);
1478                 dprintk(NDEBUG_ARBITRATION, "scsi%d: lost arbitration, deasserting MR_ARBITRATE\n",
1479                            HOSTNO);
1480                 return -1;
1481         }
1482
1483         /* after/during arbitration, BSY should be asserted.
1484            IBM DPES-31080 Version S31Q works now */
1485         /* Tnx to Thomas_Roesch@m2.maus.de for finding this! (Roman) */
1486         NCR5380_write(INITIATOR_COMMAND_REG,
1487                       ICR_BASE | ICR_ASSERT_SEL | ICR_ASSERT_BSY);
1488
1489         if ((NCR5380_read(INITIATOR_COMMAND_REG) & ICR_ARBITRATION_LOST) ||
1490             hostdata->connected) {
1491                 NCR5380_write(MODE_REG, MR_BASE);
1492                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1493                 dprintk(NDEBUG_ARBITRATION, "scsi%d: lost arbitration, deasserting ICR_ASSERT_SEL\n",
1494                            HOSTNO);
1495                 return -1;
1496         }
1497
1498         /*
1499          * Again, bus clear + bus settle time is 1.2us, however, this is
1500          * a minimum so we'll udelay ceil(1.2)
1501          */
1502
1503         if (hostdata->flags & FLAG_TOSHIBA_DELAY)
1504                 udelay(15);
1505         else
1506                 udelay(2);
1507
1508         if (hostdata->connected) {
1509                 NCR5380_write(MODE_REG, MR_BASE);
1510                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1511                 return -1;
1512         }
1513
1514         dprintk(NDEBUG_ARBITRATION, "scsi%d: won arbitration\n", HOSTNO);
1515
1516         /*
1517          * Now that we have won arbitration, start Selection process, asserting
1518          * the host and target ID's on the SCSI bus.
1519          */
1520
1521         NCR5380_write(OUTPUT_DATA_REG, (hostdata->id_mask | (1 << cmd->device->id)));
1522
1523         /*
1524          * Raise ATN while SEL is true before BSY goes false from arbitration,
1525          * since this is the only way to guarantee that we'll get a MESSAGE OUT
1526          * phase immediately after selection.
1527          */
1528
1529         NCR5380_write(INITIATOR_COMMAND_REG, (ICR_BASE | ICR_ASSERT_BSY |
1530                       ICR_ASSERT_DATA | ICR_ASSERT_ATN | ICR_ASSERT_SEL ));
1531         NCR5380_write(MODE_REG, MR_BASE);
1532
1533         /*
1534          * Reselect interrupts must be turned off prior to the dropping of BSY,
1535          * otherwise we will trigger an interrupt.
1536          */
1537
1538         if (hostdata->connected) {
1539                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1540                 return -1;
1541         }
1542
1543         NCR5380_write(SELECT_ENABLE_REG, 0);
1544
1545         /*
1546          * The initiator shall then wait at least two deskew delays and release
1547          * the BSY signal.
1548          */
1549         udelay(1);        /* wingel -- wait two bus deskew delay >2*45ns */
1550
1551         /* Reset BSY */
1552         NCR5380_write(INITIATOR_COMMAND_REG, (ICR_BASE | ICR_ASSERT_DATA |
1553                       ICR_ASSERT_ATN | ICR_ASSERT_SEL));
1554
1555         /*
1556          * Something weird happens when we cease to drive BSY - looks
1557          * like the board/chip is letting us do another read before the
1558          * appropriate propagation delay has expired, and we're confusing
1559          * a BSY signal from ourselves as the target's response to SELECTION.
1560          *
1561          * A small delay (the 'C++' frontend breaks the pipeline with an
1562          * unnecessary jump, making it work on my 386-33/Trantor T128, the
1563          * tighter 'C' code breaks and requires this) solves the problem -
1564          * the 1 us delay is arbitrary, and only used because this delay will
1565          * be the same on other platforms and since it works here, it should
1566          * work there.
1567          *
1568          * wingel suggests that this could be due to failing to wait
1569          * one deskew delay.
1570          */
1571
1572         udelay(1);
1573
1574         dprintk(NDEBUG_SELECTION, "scsi%d: selecting target %d\n", HOSTNO, cmd->device->id);
1575
1576         /*
1577          * The SCSI specification calls for a 250 ms timeout for the actual
1578          * selection.
1579          */
1580
1581         timeout = jiffies + msecs_to_jiffies(250);
1582
1583         /*
1584          * XXX very interesting - we're seeing a bounce where the BSY we
1585          * asserted is being reflected / still asserted (propagation delay?)
1586          * and it's detecting as true.  Sigh.
1587          */
1588
1589 #if 0
1590         /* ++roman: If a target conformed to the SCSI standard, it wouldn't assert
1591          * IO while SEL is true. But again, there are some disks out the in the
1592          * world that do that nevertheless. (Somebody claimed that this announces
1593          * reselection capability of the target.) So we better skip that test and
1594          * only wait for BSY... (Famous german words: Der Klügere gibt nach :-)
1595          */
1596
1597         while (time_before(jiffies, timeout) &&
1598                !(NCR5380_read(STATUS_REG) & (SR_BSY | SR_IO)))
1599                 ;
1600
1601         if ((NCR5380_read(STATUS_REG) & (SR_SEL | SR_IO)) == (SR_SEL | SR_IO)) {
1602                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1603                 NCR5380_reselect(instance);
1604                 printk(KERN_ERR "scsi%d: reselection after won arbitration?\n",
1605                        HOSTNO);
1606                 NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
1607                 return -1;
1608         }
1609 #else
1610         while (time_before(jiffies, timeout) && !(NCR5380_read(STATUS_REG) & SR_BSY))
1611                 ;
1612 #endif
1613
1614         /*
1615          * No less than two deskew delays after the initiator detects the
1616          * BSY signal is true, it shall release the SEL signal and may
1617          * change the DATA BUS.                                     -wingel
1618          */
1619
1620         udelay(1);
1621
1622         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN);
1623
1624         if (!(NCR5380_read(STATUS_REG) & SR_BSY)) {
1625                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1626                 cmd->result = DID_BAD_TARGET << 16;
1627 #ifdef SUPPORT_TAGS
1628                 cmd_free_tag(cmd);
1629 #endif
1630                 cmd->scsi_done(cmd);
1631                 NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
1632                 dprintk(NDEBUG_SELECTION, "scsi%d: target did not respond within 250ms\n", HOSTNO);
1633                 return 0;
1634         }
1635
1636         /*
1637          * Since we followed the SCSI spec, and raised ATN while SEL
1638          * was true but before BSY was false during selection, the information
1639          * transfer phase should be a MESSAGE OUT phase so that we can send the
1640          * IDENTIFY message.
1641          *
1642          * If SCSI-II tagged queuing is enabled, we also send a SIMPLE_QUEUE_TAG
1643          * message (2 bytes) with a tag ID that we increment with every command
1644          * until it wraps back to 0.
1645          *
1646          * XXX - it turns out that there are some broken SCSI-II devices,
1647          *           which claim to support tagged queuing but fail when more than
1648          *           some number of commands are issued at once.
1649          */
1650
1651         /* Wait for start of REQ/ACK handshake */
1652         while (!(NCR5380_read(STATUS_REG) & SR_REQ))
1653                 ;
1654
1655         dprintk(NDEBUG_SELECTION, "scsi%d: target %d selected, going into MESSAGE OUT phase.\n",
1656                    HOSTNO, cmd->device->id);
1657         tmp[0] = IDENTIFY(1, cmd->device->lun);
1658
1659 #ifdef SUPPORT_TAGS
1660         if (cmd->tag != TAG_NONE) {
1661                 tmp[1] = hostdata->last_message = SIMPLE_QUEUE_TAG;
1662                 tmp[2] = cmd->tag;
1663                 len = 3;
1664         } else
1665                 len = 1;
1666 #else
1667         len = 1;
1668         cmd->tag = 0;
1669 #endif /* SUPPORT_TAGS */
1670
1671         /* Send message(s) */
1672         data = tmp;
1673         phase = PHASE_MSGOUT;
1674         NCR5380_transfer_pio(instance, &phase, &len, &data);
1675         dprintk(NDEBUG_SELECTION, "scsi%d: nexus established.\n", HOSTNO);
1676         /* XXX need to handle errors here */
1677         hostdata->connected = cmd;
1678 #ifndef SUPPORT_TAGS
1679         hostdata->busy[cmd->device->id] |= (1 << cmd->device->lun);
1680 #endif
1681 #ifdef SUN3_SCSI_VME
1682         dregs->csr |= CSR_INTR;
1683 #endif
1684
1685         initialize_SCp(cmd);
1686
1687         return 0;
1688 }
1689
1690 /*
1691  * Function : int NCR5380_transfer_pio (struct Scsi_Host *instance,
1692  *      unsigned char *phase, int *count, unsigned char **data)
1693  *
1694  * Purpose : transfers data in given phase using polled I/O
1695  *
1696  * Inputs : instance - instance of driver, *phase - pointer to
1697  *      what phase is expected, *count - pointer to number of
1698  *      bytes to transfer, **data - pointer to data pointer.
1699  *
1700  * Returns : -1 when different phase is entered without transferring
1701  *      maximum number of bytes, 0 if all bytes are transferred or exit
1702  *      is in same phase.
1703  *
1704  *      Also, *phase, *count, *data are modified in place.
1705  *
1706  * XXX Note : handling for bus free may be useful.
1707  */
1708
1709 /*
1710  * Note : this code is not as quick as it could be, however it
1711  * IS 100% reliable, and for the actual data transfer where speed
1712  * counts, we will always do a pseudo DMA or DMA transfer.
1713  */
1714
1715 static int NCR5380_transfer_pio(struct Scsi_Host *instance,
1716                                 unsigned char *phase, int *count,
1717                                 unsigned char **data)
1718 {
1719         register unsigned char p = *phase, tmp;
1720         register int c = *count;
1721         register unsigned char *d = *data;
1722
1723         /*
1724          * The NCR5380 chip will only drive the SCSI bus when the
1725          * phase specified in the appropriate bits of the TARGET COMMAND
1726          * REGISTER match the STATUS REGISTER
1727          */
1728
1729         NCR5380_write(TARGET_COMMAND_REG, PHASE_SR_TO_TCR(p));
1730
1731         do {
1732                 /*
1733                  * Wait for assertion of REQ, after which the phase bits will be
1734                  * valid
1735                  */
1736                 while (!((tmp = NCR5380_read(STATUS_REG)) & SR_REQ))
1737                         ;
1738
1739                 dprintk(NDEBUG_HANDSHAKE, "scsi%d: REQ detected\n", HOSTNO);
1740
1741                 /* Check for phase mismatch */
1742                 if ((tmp & PHASE_MASK) != p) {
1743                         dprintk(NDEBUG_PIO, "scsi%d: phase mismatch\n", HOSTNO);
1744                         NCR5380_dprint_phase(NDEBUG_PIO, instance);
1745                         break;
1746                 }
1747
1748                 /* Do actual transfer from SCSI bus to / from memory */
1749                 if (!(p & SR_IO))
1750                         NCR5380_write(OUTPUT_DATA_REG, *d);
1751                 else
1752                         *d = NCR5380_read(CURRENT_SCSI_DATA_REG);
1753
1754                 ++d;
1755
1756                 /*
1757                  * The SCSI standard suggests that in MSGOUT phase, the initiator
1758                  * should drop ATN on the last byte of the message phase
1759                  * after REQ has been asserted for the handshake but before
1760                  * the initiator raises ACK.
1761                  */
1762
1763                 if (!(p & SR_IO)) {
1764                         if (!((p & SR_MSG) && c > 1)) {
1765                                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_DATA);
1766                                 NCR5380_dprint(NDEBUG_PIO, instance);
1767                                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE |
1768                                               ICR_ASSERT_DATA | ICR_ASSERT_ACK);
1769                         } else {
1770                                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE |
1771                                               ICR_ASSERT_DATA | ICR_ASSERT_ATN);
1772                                 NCR5380_dprint(NDEBUG_PIO, instance);
1773                                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE |
1774                                               ICR_ASSERT_DATA | ICR_ASSERT_ATN | ICR_ASSERT_ACK);
1775                         }
1776                 } else {
1777                         NCR5380_dprint(NDEBUG_PIO, instance);
1778                         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ACK);
1779                 }
1780
1781                 while (NCR5380_read(STATUS_REG) & SR_REQ)
1782                         ;
1783
1784                 dprintk(NDEBUG_HANDSHAKE, "scsi%d: req false, handshake complete\n", HOSTNO);
1785
1786                 /*
1787                  * We have several special cases to consider during REQ/ACK handshaking :
1788                  * 1.  We were in MSGOUT phase, and we are on the last byte of the
1789                  *      message.  ATN must be dropped as ACK is dropped.
1790                  *
1791                  * 2.  We are in a MSGIN phase, and we are on the last byte of the
1792                  *      message.  We must exit with ACK asserted, so that the calling
1793                  *      code may raise ATN before dropping ACK to reject the message.
1794                  *
1795                  * 3.  ACK and ATN are clear and the target may proceed as normal.
1796                  */
1797                 if (!(p == PHASE_MSGIN && c == 1)) {
1798                         if (p == PHASE_MSGOUT && c > 1)
1799                                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN);
1800                         else
1801                                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1802                 }
1803         } while (--c);
1804
1805         dprintk(NDEBUG_PIO, "scsi%d: residual %d\n", HOSTNO, c);
1806
1807         *count = c;
1808         *data = d;
1809         tmp = NCR5380_read(STATUS_REG);
1810         /* The phase read from the bus is valid if either REQ is (already)
1811          * asserted or if ACK hasn't been released yet. The latter is the case if
1812          * we're in MSGIN and all wanted bytes have been received.
1813          */
1814         if ((tmp & SR_REQ) || (p == PHASE_MSGIN && c == 0))
1815                 *phase = tmp & PHASE_MASK;
1816         else
1817                 *phase = PHASE_UNKNOWN;
1818
1819         if (!c || (*phase == p))
1820                 return 0;
1821         else
1822                 return -1;
1823 }
1824
1825 /**
1826  * do_reset - issue a reset command
1827  * @instance: adapter to reset
1828  *
1829  * Issue a reset sequence to the NCR5380 and try and get the bus
1830  * back into sane shape.
1831  *
1832  * This clears the reset interrupt flag because there may be no handler for
1833  * it. When the driver is initialized, the NCR5380_intr() handler has not yet
1834  * been installed. And when in EH we may have released the ST DMA interrupt.
1835  */
1836
1837 static void do_reset(struct Scsi_Host *instance)
1838 {
1839         unsigned long flags;
1840
1841         local_irq_save(flags);
1842         NCR5380_write(TARGET_COMMAND_REG,
1843                       PHASE_SR_TO_TCR(NCR5380_read(STATUS_REG) & PHASE_MASK));
1844         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_RST);
1845         udelay(50);
1846         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1847         (void)NCR5380_read(RESET_PARITY_INTERRUPT_REG);
1848         local_irq_restore(flags);
1849 }
1850
1851 /*
1852  * Function : do_abort (Scsi_Host *host)
1853  *
1854  * Purpose : abort the currently established nexus.  Should only be
1855  *      called from a routine which can drop into a
1856  *
1857  * Returns : 0 on success, -1 on failure.
1858  */
1859
1860 static int do_abort(struct Scsi_Host *instance)
1861 {
1862         unsigned char tmp, *msgptr, phase;
1863         int len;
1864
1865         /* Request message out phase */
1866         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN);
1867
1868         /*
1869          * Wait for the target to indicate a valid phase by asserting
1870          * REQ.  Once this happens, we'll have either a MSGOUT phase
1871          * and can immediately send the ABORT message, or we'll have some
1872          * other phase and will have to source/sink data.
1873          *
1874          * We really don't care what value was on the bus or what value
1875          * the target sees, so we just handshake.
1876          */
1877
1878         while (!((tmp = NCR5380_read(STATUS_REG)) & SR_REQ))
1879                 ;
1880
1881         NCR5380_write(TARGET_COMMAND_REG, PHASE_SR_TO_TCR(tmp));
1882
1883         if ((tmp & PHASE_MASK) != PHASE_MSGOUT) {
1884                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN |
1885                               ICR_ASSERT_ACK);
1886                 while (NCR5380_read(STATUS_REG) & SR_REQ)
1887                         ;
1888                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN);
1889         }
1890
1891         tmp = ABORT;
1892         msgptr = &tmp;
1893         len = 1;
1894         phase = PHASE_MSGOUT;
1895         NCR5380_transfer_pio(instance, &phase, &len, &msgptr);
1896
1897         /*
1898          * If we got here, and the command completed successfully,
1899          * we're about to go into bus free state.
1900          */
1901
1902         return len ? -1 : 0;
1903 }
1904
1905 #if defined(REAL_DMA)
1906 /*
1907  * Function : int NCR5380_transfer_dma (struct Scsi_Host *instance,
1908  *      unsigned char *phase, int *count, unsigned char **data)
1909  *
1910  * Purpose : transfers data in given phase using either real
1911  *      or pseudo DMA.
1912  *
1913  * Inputs : instance - instance of driver, *phase - pointer to
1914  *      what phase is expected, *count - pointer to number of
1915  *      bytes to transfer, **data - pointer to data pointer.
1916  *
1917  * Returns : -1 when different phase is entered without transferring
1918  *      maximum number of bytes, 0 if all bytes or transferred or exit
1919  *      is in same phase.
1920  *
1921  *      Also, *phase, *count, *data are modified in place.
1922  *
1923  */
1924
1925
1926 static int NCR5380_transfer_dma(struct Scsi_Host *instance,
1927                                 unsigned char *phase, int *count,
1928                                 unsigned char **data)
1929 {
1930         SETUP_HOSTDATA(instance);
1931         register int c = *count;
1932         register unsigned char p = *phase;
1933         unsigned long flags;
1934
1935 #if defined(CONFIG_SUN3)
1936         /* sanity check */
1937         if (!sun3_dma_setup_done) {
1938                 pr_err("scsi%d: transfer_dma without setup!\n",
1939                        instance->host_no);
1940                 BUG();
1941         }
1942         hostdata->dma_len = c;
1943
1944         dprintk(NDEBUG_DMA, "scsi%d: initializing DMA for %s, %d bytes %s %p\n",
1945                 instance->host_no, (p & SR_IO) ? "reading" : "writing",
1946                 c, (p & SR_IO) ? "to" : "from", *data);
1947
1948         /* netbsd turns off ints here, why not be safe and do it too */
1949         local_irq_save(flags);
1950
1951         /* send start chain */
1952         sun3scsi_dma_start(c, *data);
1953
1954         if (p & SR_IO) {
1955                 NCR5380_write(TARGET_COMMAND_REG, 1);
1956                 NCR5380_read(RESET_PARITY_INTERRUPT_REG);
1957                 NCR5380_write(INITIATOR_COMMAND_REG, 0);
1958                 NCR5380_write(MODE_REG,
1959                               (NCR5380_read(MODE_REG) | MR_DMA_MODE | MR_ENABLE_EOP_INTR));
1960                 NCR5380_write(START_DMA_INITIATOR_RECEIVE_REG, 0);
1961         } else {
1962                 NCR5380_write(TARGET_COMMAND_REG, 0);
1963                 NCR5380_read(RESET_PARITY_INTERRUPT_REG);
1964                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_ASSERT_DATA);
1965                 NCR5380_write(MODE_REG,
1966                               (NCR5380_read(MODE_REG) | MR_DMA_MODE | MR_ENABLE_EOP_INTR));
1967                 NCR5380_write(START_DMA_SEND_REG, 0);
1968         }
1969
1970 #ifdef SUN3_SCSI_VME
1971         dregs->csr |= CSR_DMA_ENABLE;
1972 #endif
1973
1974         local_irq_restore(flags);
1975
1976         sun3_dma_active = 1;
1977
1978 #else /* !defined(CONFIG_SUN3) */
1979         register unsigned char *d = *data;
1980         unsigned char tmp;
1981
1982         if ((tmp = (NCR5380_read(STATUS_REG) & PHASE_MASK)) != p) {
1983                 *phase = tmp;
1984                 return -1;
1985         }
1986
1987         if (hostdata->read_overruns && (p & SR_IO))
1988                 c -= hostdata->read_overruns;
1989
1990         dprintk(NDEBUG_DMA, "scsi%d: initializing DMA for %s, %d bytes %s %p\n",
1991                    HOSTNO, (p & SR_IO) ? "reading" : "writing",
1992                    c, (p & SR_IO) ? "to" : "from", d);
1993
1994         NCR5380_write(TARGET_COMMAND_REG, PHASE_SR_TO_TCR(p));
1995
1996 #ifdef REAL_DMA
1997         NCR5380_write(MODE_REG, MR_BASE | MR_DMA_MODE | MR_ENABLE_EOP_INTR | MR_MONITOR_BSY);
1998 #endif /* def REAL_DMA  */
1999
2000         if (!(hostdata->flags & FLAG_LATE_DMA_SETUP)) {
2001                 /* On the Medusa, it is a must to initialize the DMA before
2002                  * starting the NCR. This is also the cleaner way for the TT.
2003                  */
2004                 local_irq_save(flags);
2005                 hostdata->dma_len = (p & SR_IO) ?
2006                         NCR5380_dma_read_setup(instance, d, c) :
2007                         NCR5380_dma_write_setup(instance, d, c);
2008                 local_irq_restore(flags);
2009         }
2010
2011         if (p & SR_IO)
2012                 NCR5380_write(START_DMA_INITIATOR_RECEIVE_REG, 0);
2013         else {
2014                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_DATA);
2015                 NCR5380_write(START_DMA_SEND_REG, 0);
2016         }
2017
2018         if (hostdata->flags & FLAG_LATE_DMA_SETUP) {
2019                 /* On the Falcon, the DMA setup must be done after the last */
2020                 /* NCR access, else the DMA setup gets trashed!
2021                  */
2022                 local_irq_save(flags);
2023                 hostdata->dma_len = (p & SR_IO) ?
2024                         NCR5380_dma_read_setup(instance, d, c) :
2025                         NCR5380_dma_write_setup(instance, d, c);
2026                 local_irq_restore(flags);
2027         }
2028 #endif /* !defined(CONFIG_SUN3) */
2029
2030         return 0;
2031 }
2032 #endif /* defined(REAL_DMA) */
2033
2034 /*
2035  * Function : NCR5380_information_transfer (struct Scsi_Host *instance)
2036  *
2037  * Purpose : run through the various SCSI phases and do as the target
2038  *      directs us to.  Operates on the currently connected command,
2039  *      instance->connected.
2040  *
2041  * Inputs : instance, instance for which we are doing commands
2042  *
2043  * Side effects : SCSI things happen, the disconnected queue will be
2044  *      modified if a command disconnects, *instance->connected will
2045  *      change.
2046  *
2047  * XXX Note : we need to watch for bus free or a reset condition here
2048  *      to recover from an unexpected bus free condition.
2049  */
2050
2051 static void NCR5380_information_transfer(struct Scsi_Host *instance)
2052 {
2053         SETUP_HOSTDATA(instance);
2054         unsigned long flags;
2055         unsigned char msgout = NOP;
2056         int sink = 0;
2057         int len;
2058 #if defined(REAL_DMA)
2059         int transfersize;
2060 #endif
2061         unsigned char *data;
2062         unsigned char phase, tmp, extended_msg[10], old_phase = 0xff;
2063         struct scsi_cmnd *cmd = (struct scsi_cmnd *) hostdata->connected;
2064
2065 #ifdef SUN3_SCSI_VME
2066         dregs->csr |= CSR_INTR;
2067 #endif
2068
2069         while (1) {
2070                 tmp = NCR5380_read(STATUS_REG);
2071                 /* We only have a valid SCSI phase when REQ is asserted */
2072                 if (tmp & SR_REQ) {
2073                         phase = (tmp & PHASE_MASK);
2074                         if (phase != old_phase) {
2075                                 old_phase = phase;
2076                                 NCR5380_dprint_phase(NDEBUG_INFORMATION, instance);
2077                         }
2078 #if defined(CONFIG_SUN3)
2079                         if (phase == PHASE_CMDOUT) {
2080 #if defined(REAL_DMA)
2081                                 void *d;
2082                                 unsigned long count;
2083
2084                                 if (!cmd->SCp.this_residual && cmd->SCp.buffers_residual) {
2085                                         count = cmd->SCp.buffer->length;
2086                                         d = sg_virt(cmd->SCp.buffer);
2087                                 } else {
2088                                         count = cmd->SCp.this_residual;
2089                                         d = cmd->SCp.ptr;
2090                                 }
2091                                 /* this command setup for dma yet? */
2092                                 if ((count >= DMA_MIN_SIZE) && (sun3_dma_setup_done != cmd)) {
2093                                         if (cmd->request->cmd_type == REQ_TYPE_FS) {
2094                                                 sun3scsi_dma_setup(d, count,
2095                                                                    rq_data_dir(cmd->request));
2096                                                 sun3_dma_setup_done = cmd;
2097                                         }
2098                                 }
2099 #endif
2100 #ifdef SUN3_SCSI_VME
2101                                 dregs->csr |= CSR_INTR;
2102 #endif
2103                         }
2104 #endif /* CONFIG_SUN3 */
2105
2106                         if (sink && (phase != PHASE_MSGOUT)) {
2107                                 NCR5380_write(TARGET_COMMAND_REG, PHASE_SR_TO_TCR(tmp));
2108
2109                                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN |
2110                                               ICR_ASSERT_ACK);
2111                                 while (NCR5380_read(STATUS_REG) & SR_REQ)
2112                                         ;
2113                                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE |
2114                                               ICR_ASSERT_ATN);
2115                                 sink = 0;
2116                                 continue;
2117                         }
2118
2119                         switch (phase) {
2120                         case PHASE_DATAOUT:
2121 #if (NDEBUG & NDEBUG_NO_DATAOUT)
2122                                 printk("scsi%d: NDEBUG_NO_DATAOUT set, attempted DATAOUT "
2123                                        "aborted\n", HOSTNO);
2124                                 sink = 1;
2125                                 do_abort(instance);
2126                                 cmd->result = DID_ERROR << 16;
2127                                 cmd->scsi_done(cmd);
2128                                 return;
2129 #endif
2130                         case PHASE_DATAIN:
2131                                 /*
2132                                  * If there is no room left in the current buffer in the
2133                                  * scatter-gather list, move onto the next one.
2134                                  */
2135
2136                                 if (!cmd->SCp.this_residual && cmd->SCp.buffers_residual) {
2137                                         ++cmd->SCp.buffer;
2138                                         --cmd->SCp.buffers_residual;
2139                                         cmd->SCp.this_residual = cmd->SCp.buffer->length;
2140                                         cmd->SCp.ptr = sg_virt(cmd->SCp.buffer);
2141                                         /* ++roman: Try to merge some scatter-buffers if
2142                                          * they are at contiguous physical addresses.
2143                                          */
2144                                         merge_contiguous_buffers(cmd);
2145                                         dprintk(NDEBUG_INFORMATION, "scsi%d: %d bytes and %d buffers left\n",
2146                                                    HOSTNO, cmd->SCp.this_residual,
2147                                                    cmd->SCp.buffers_residual);
2148                                 }
2149
2150                                 /*
2151                                  * The preferred transfer method is going to be
2152                                  * PSEUDO-DMA for systems that are strictly PIO,
2153                                  * since we can let the hardware do the handshaking.
2154                                  *
2155                                  * For this to work, we need to know the transfersize
2156                                  * ahead of time, since the pseudo-DMA code will sit
2157                                  * in an unconditional loop.
2158                                  */
2159
2160                                 /* ++roman: I suggest, this should be
2161                                  *   #if def(REAL_DMA)
2162                                  * instead of leaving REAL_DMA out.
2163                                  */
2164
2165 #if defined(REAL_DMA)
2166                                 if (
2167 #if !defined(CONFIG_SUN3)
2168                                     !cmd->device->borken &&
2169 #endif
2170                                     (transfersize = NCR5380_dma_xfer_len(instance, cmd, phase)) >= DMA_MIN_SIZE) {
2171                                         len = transfersize;
2172                                         cmd->SCp.phase = phase;
2173                                         if (NCR5380_transfer_dma(instance, &phase,
2174                                             &len, (unsigned char **)&cmd->SCp.ptr)) {
2175                                                 /*
2176                                                  * If the watchdog timer fires, all future
2177                                                  * accesses to this device will use the
2178                                                  * polled-IO. */
2179                                                 scmd_printk(KERN_INFO, cmd,
2180                                                         "switching to slow handshake\n");
2181                                                 cmd->device->borken = 1;
2182                                                 sink = 1;
2183                                                 do_abort(instance);
2184                                                 cmd->result = DID_ERROR << 16;
2185                                                 cmd->scsi_done(cmd);
2186                                                 /* XXX - need to source or sink data here, as appropriate */
2187                                         } else {
2188 #ifdef REAL_DMA
2189                                                 /* ++roman: When using real DMA,
2190                                                  * information_transfer() should return after
2191                                                  * starting DMA since it has nothing more to
2192                                                  * do.
2193                                                  */
2194                                                 return;
2195 #else
2196                                                 cmd->SCp.this_residual -= transfersize - len;
2197 #endif
2198                                         }
2199                                 } else
2200 #endif /* defined(REAL_DMA) */
2201                                         NCR5380_transfer_pio(instance, &phase,
2202                                                              (int *)&cmd->SCp.this_residual,
2203                                                              (unsigned char **)&cmd->SCp.ptr);
2204 #if defined(CONFIG_SUN3) && defined(REAL_DMA)
2205                                 /* if we had intended to dma that command clear it */
2206                                 if (sun3_dma_setup_done == cmd)
2207                                         sun3_dma_setup_done = NULL;
2208 #endif
2209                                 break;
2210                         case PHASE_MSGIN:
2211                                 len = 1;
2212                                 data = &tmp;
2213                                 NCR5380_write(SELECT_ENABLE_REG, 0);    /* disable reselects */
2214                                 NCR5380_transfer_pio(instance, &phase, &len, &data);
2215                                 cmd->SCp.Message = tmp;
2216
2217                                 switch (tmp) {
2218                                 /*
2219                                  * Linking lets us reduce the time required to get the
2220                                  * next command out to the device, hopefully this will
2221                                  * mean we don't waste another revolution due to the delays
2222                                  * required by ARBITRATION and another SELECTION.
2223                                  *
2224                                  * In the current implementation proposal, low level drivers
2225                                  * merely have to start the next command, pointed to by
2226                                  * next_link, done() is called as with unlinked commands.
2227                                  */
2228 #ifdef LINKED
2229                                 case LINKED_CMD_COMPLETE:
2230                                 case LINKED_FLG_CMD_COMPLETE:
2231                                         /* Accept message by clearing ACK */
2232                                         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
2233
2234                                         dprintk(NDEBUG_LINKED, "scsi%d: target %d lun %llu linked command "
2235                                                    "complete.\n", HOSTNO, cmd->device->id, cmd->device->lun);
2236
2237                                         /* Enable reselect interrupts */
2238                                         NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
2239                                         /*
2240                                          * Sanity check : A linked command should only terminate
2241                                          * with one of these messages if there are more linked
2242                                          * commands available.
2243                                          */
2244
2245                                         if (!cmd->next_link) {
2246                                                  printk(KERN_NOTICE "scsi%d: target %d lun %llu "
2247                                                         "linked command complete, no next_link\n",
2248                                                         HOSTNO, cmd->device->id, cmd->device->lun);
2249                                                 sink = 1;
2250                                                 do_abort(instance);
2251                                                 return;
2252                                         }
2253
2254                                         initialize_SCp(cmd->next_link);
2255                                         /* The next command is still part of this process; copy it
2256                                          * and don't free it! */
2257                                         cmd->next_link->tag = cmd->tag;
2258                                         cmd->result = cmd->SCp.Status | (cmd->SCp.Message << 8);
2259                                         dprintk(NDEBUG_LINKED, "scsi%d: target %d lun %llu linked request "
2260                                                    "done, calling scsi_done().\n",
2261                                                    HOSTNO, cmd->device->id, cmd->device->lun);
2262                                         cmd->scsi_done(cmd);
2263                                         cmd = hostdata->connected;
2264                                         break;
2265 #endif /* def LINKED */
2266                                 case ABORT:
2267                                 case COMMAND_COMPLETE:
2268                                         /* Accept message by clearing ACK */
2269                                         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
2270                                         dprintk(NDEBUG_QUEUES, "scsi%d: command for target %d, lun %llu "
2271                                                   "completed\n", HOSTNO, cmd->device->id, cmd->device->lun);
2272
2273                                         local_irq_save(flags);
2274                                         hostdata->retain_dma_intr++;
2275                                         hostdata->connected = NULL;
2276 #ifdef SUPPORT_TAGS
2277                                         cmd_free_tag(cmd);
2278                                         if (status_byte(cmd->SCp.Status) == QUEUE_FULL) {
2279                                                 /* Turn a QUEUE FULL status into BUSY, I think the
2280                                                  * mid level cannot handle QUEUE FULL :-( (The
2281                                                  * command is retried after BUSY). Also update our
2282                                                  * queue size to the number of currently issued
2283                                                  * commands now.
2284                                                  */
2285                                                 /* ++Andreas: the mid level code knows about
2286                                                    QUEUE_FULL now. */
2287                                                 struct tag_alloc *ta = &hostdata->TagAlloc[scmd_id(cmd)][cmd->device->lun];
2288                                                 dprintk(NDEBUG_TAGS, "scsi%d: target %d lun %llu returned "
2289                                                            "QUEUE_FULL after %d commands\n",
2290                                                            HOSTNO, cmd->device->id, cmd->device->lun,
2291                                                            ta->nr_allocated);
2292                                                 if (ta->queue_size > ta->nr_allocated)
2293                                                         ta->nr_allocated = ta->queue_size;
2294                                         }
2295 #else
2296                                         hostdata->busy[cmd->device->id] &= ~(1 << cmd->device->lun);
2297 #endif
2298                                         /* Enable reselect interrupts */
2299                                         NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
2300
2301                                         /*
2302                                          * I'm not sure what the correct thing to do here is :
2303                                          *
2304                                          * If the command that just executed is NOT a request
2305                                          * sense, the obvious thing to do is to set the result
2306                                          * code to the values of the stored parameters.
2307                                          *
2308                                          * If it was a REQUEST SENSE command, we need some way to
2309                                          * differentiate between the failure code of the original
2310                                          * and the failure code of the REQUEST sense - the obvious
2311                                          * case is success, where we fall through and leave the
2312                                          * result code unchanged.
2313                                          *
2314                                          * The non-obvious place is where the REQUEST SENSE failed
2315                                          */
2316
2317                                         if (cmd->cmnd[0] != REQUEST_SENSE)
2318                                                 cmd->result = cmd->SCp.Status | (cmd->SCp.Message << 8);
2319                                         else if (status_byte(cmd->SCp.Status) != GOOD)
2320                                                 cmd->result = (cmd->result & 0x00ffff) | (DID_ERROR << 16);
2321
2322                                         if ((cmd->cmnd[0] == REQUEST_SENSE) &&
2323                                                 hostdata->ses.cmd_len) {
2324                                                 scsi_eh_restore_cmnd(cmd, &hostdata->ses);
2325                                                 hostdata->ses.cmd_len = 0 ;
2326                                         }
2327
2328                                         if ((cmd->cmnd[0] != REQUEST_SENSE) &&
2329                                             (status_byte(cmd->SCp.Status) == CHECK_CONDITION)) {
2330                                                 scsi_eh_prep_cmnd(cmd, &hostdata->ses, NULL, 0, ~0);
2331
2332                                                 dprintk(NDEBUG_AUTOSENSE, "scsi%d: performing request sense\n", HOSTNO);
2333
2334                                                 LIST(cmd,hostdata->issue_queue);
2335                                                 SET_NEXT(cmd, hostdata->issue_queue);
2336                                                 hostdata->issue_queue = (struct scsi_cmnd *) cmd;
2337                                                 dprintk(NDEBUG_QUEUES, "scsi%d: REQUEST SENSE added to head of "
2338                                                           "issue queue\n", H_NO(cmd));
2339                                         } else {
2340                                                 cmd->scsi_done(cmd);
2341                                         }
2342
2343                                         local_irq_restore(flags);
2344
2345                                         NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
2346                                         /*
2347                                          * Restore phase bits to 0 so an interrupted selection,
2348                                          * arbitration can resume.
2349                                          */
2350                                         NCR5380_write(TARGET_COMMAND_REG, 0);
2351
2352                                         while ((NCR5380_read(STATUS_REG) & SR_BSY) && !hostdata->connected)
2353                                                 barrier();
2354
2355                                         local_irq_save(flags);
2356                                         hostdata->retain_dma_intr--;
2357                                         /* ++roman: For Falcon SCSI, release the lock on the
2358                                          * ST-DMA here if no other commands are waiting on the
2359                                          * disconnected queue.
2360                                          */
2361                                         maybe_release_dma_irq(instance);
2362                                         local_irq_restore(flags);
2363                                         return;
2364                                 case MESSAGE_REJECT:
2365                                         /* Accept message by clearing ACK */
2366                                         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
2367                                         /* Enable reselect interrupts */
2368                                         NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
2369                                         switch (hostdata->last_message) {
2370                                         case HEAD_OF_QUEUE_TAG:
2371                                         case ORDERED_QUEUE_TAG:
2372                                         case SIMPLE_QUEUE_TAG:
2373                                                 /* The target obviously doesn't support tagged
2374                                                  * queuing, even though it announced this ability in
2375                                                  * its INQUIRY data ?!? (maybe only this LUN?) Ok,
2376                                                  * clear 'tagged_supported' and lock the LUN, since
2377                                                  * the command is treated as untagged further on.
2378                                                  */
2379                                                 cmd->device->tagged_supported = 0;
2380                                                 hostdata->busy[cmd->device->id] |= (1 << cmd->device->lun);
2381                                                 cmd->tag = TAG_NONE;
2382                                                 dprintk(NDEBUG_TAGS, "scsi%d: target %d lun %llu rejected "
2383                                                            "QUEUE_TAG message; tagged queuing "
2384                                                            "disabled\n",
2385                                                            HOSTNO, cmd->device->id, cmd->device->lun);
2386                                                 break;
2387                                         }
2388                                         break;
2389                                 case DISCONNECT:
2390                                         /* Accept message by clearing ACK */
2391                                         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
2392                                         local_irq_save(flags);
2393                                         cmd->device->disconnect = 1;
2394                                         LIST(cmd,hostdata->disconnected_queue);
2395                                         SET_NEXT(cmd, hostdata->disconnected_queue);
2396                                         hostdata->connected = NULL;
2397                                         hostdata->disconnected_queue = cmd;
2398                                         local_irq_restore(flags);
2399                                         dprintk(NDEBUG_QUEUES, "scsi%d: command for target %d lun %llu was "
2400                                                   "moved from connected to the "
2401                                                   "disconnected_queue\n", HOSTNO,
2402                                                   cmd->device->id, cmd->device->lun);
2403                                         /*
2404                                          * Restore phase bits to 0 so an interrupted selection,
2405                                          * arbitration can resume.
2406                                          */
2407                                         NCR5380_write(TARGET_COMMAND_REG, 0);
2408
2409                                         /* Enable reselect interrupts */
2410                                         NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
2411                                         /* Wait for bus free to avoid nasty timeouts */
2412                                         while ((NCR5380_read(STATUS_REG) & SR_BSY) && !hostdata->connected)
2413                                                 barrier();
2414 #ifdef SUN3_SCSI_VME
2415                                         dregs->csr |= CSR_DMA_ENABLE;
2416 #endif
2417                                         return;
2418                                         /*
2419                                          * The SCSI data pointer is *IMPLICITLY* saved on a disconnect
2420                                          * operation, in violation of the SCSI spec so we can safely
2421                                          * ignore SAVE/RESTORE pointers calls.
2422                                          *
2423                                          * Unfortunately, some disks violate the SCSI spec and
2424                                          * don't issue the required SAVE_POINTERS message before
2425                                          * disconnecting, and we have to break spec to remain
2426                                          * compatible.
2427                                          */
2428                                 case SAVE_POINTERS:
2429                                 case RESTORE_POINTERS:
2430                                         /* Accept message by clearing ACK */
2431                                         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
2432                                         /* Enable reselect interrupts */
2433                                         NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
2434                                         break;
2435                                 case EXTENDED_MESSAGE:
2436                                         /*
2437                                          * Extended messages are sent in the following format :
2438                                          * Byte
2439                                          * 0            EXTENDED_MESSAGE == 1
2440                                          * 1            length (includes one byte for code, doesn't
2441                                          *              include first two bytes)
2442                                          * 2            code
2443                                          * 3..length+1  arguments
2444                                          *
2445                                          * Start the extended message buffer with the EXTENDED_MESSAGE
2446                                          * byte, since spi_print_msg() wants the whole thing.
2447                                          */
2448                                         extended_msg[0] = EXTENDED_MESSAGE;
2449                                         /* Accept first byte by clearing ACK */
2450                                         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
2451
2452                                         dprintk(NDEBUG_EXTENDED, "scsi%d: receiving extended message\n", HOSTNO);
2453
2454                                         len = 2;
2455                                         data = extended_msg + 1;
2456                                         phase = PHASE_MSGIN;
2457                                         NCR5380_transfer_pio(instance, &phase, &len, &data);
2458                                         dprintk(NDEBUG_EXTENDED, "scsi%d: length=%d, code=0x%02x\n", HOSTNO,
2459                                                    (int)extended_msg[1], (int)extended_msg[2]);
2460
2461                                         if (!len && extended_msg[1] <=
2462                                             (sizeof(extended_msg) - 1)) {
2463                                                 /* Accept third byte by clearing ACK */
2464                                                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
2465                                                 len = extended_msg[1] - 1;
2466                                                 data = extended_msg + 3;
2467                                                 phase = PHASE_MSGIN;
2468
2469                                                 NCR5380_transfer_pio(instance, &phase, &len, &data);
2470                                                 dprintk(NDEBUG_EXTENDED, "scsi%d: message received, residual %d\n",
2471                                                            HOSTNO, len);
2472
2473                                                 switch (extended_msg[2]) {
2474                                                 case EXTENDED_SDTR:
2475                                                 case EXTENDED_WDTR:
2476                                                 case EXTENDED_MODIFY_DATA_POINTER:
2477                                                 case EXTENDED_EXTENDED_IDENTIFY:
2478                                                         tmp = 0;
2479                                                 }
2480                                         } else if (len) {
2481                                                 printk(KERN_NOTICE "scsi%d: error receiving "
2482                                                        "extended message\n", HOSTNO);
2483                                                 tmp = 0;
2484                                         } else {
2485                                                 printk(KERN_NOTICE "scsi%d: extended message "
2486                                                            "code %02x length %d is too long\n",
2487                                                            HOSTNO, extended_msg[2], extended_msg[1]);
2488                                                 tmp = 0;
2489                                         }
2490                                         /* Fall through to reject message */
2491
2492                                         /*
2493                                          * If we get something weird that we aren't expecting,
2494                                          * reject it.
2495                                          */
2496                                 default:
2497                                         if (!tmp) {
2498                                                 printk(KERN_INFO "scsi%d: rejecting message ",
2499                                                        instance->host_no);
2500                                                 spi_print_msg(extended_msg);
2501                                                 printk("\n");
2502                                         } else if (tmp != EXTENDED_MESSAGE)
2503                                                 scmd_printk(KERN_INFO, cmd,
2504                                                             "rejecting unknown message %02x\n",
2505                                                             tmp);
2506                                         else
2507                                                 scmd_printk(KERN_INFO, cmd,
2508                                                             "rejecting unknown extended message code %02x, length %d\n",
2509                                                             extended_msg[1], extended_msg[0]);
2510
2511                                         msgout = MESSAGE_REJECT;
2512                                         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN);
2513                                         break;
2514                                 } /* switch (tmp) */
2515                                 break;
2516                         case PHASE_MSGOUT:
2517                                 len = 1;
2518                                 data = &msgout;
2519                                 hostdata->last_message = msgout;
2520                                 NCR5380_transfer_pio(instance, &phase, &len, &data);
2521                                 if (msgout == ABORT) {
2522                                         local_irq_save(flags);
2523 #ifdef SUPPORT_TAGS
2524                                         cmd_free_tag(cmd);
2525 #else
2526                                         hostdata->busy[cmd->device->id] &= ~(1 << cmd->device->lun);
2527 #endif
2528                                         hostdata->connected = NULL;
2529                                         cmd->result = DID_ERROR << 16;
2530                                         NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
2531                                         maybe_release_dma_irq(instance);
2532                                         local_irq_restore(flags);
2533                                         cmd->scsi_done(cmd);
2534                                         return;
2535                                 }
2536                                 msgout = NOP;
2537                                 break;
2538                         case PHASE_CMDOUT:
2539                                 len = cmd->cmd_len;
2540                                 data = cmd->cmnd;
2541                                 /*
2542                                  * XXX for performance reasons, on machines with a
2543                                  * PSEUDO-DMA architecture we should probably
2544                                  * use the dma transfer function.
2545                                  */
2546                                 NCR5380_transfer_pio(instance, &phase, &len, &data);
2547                                 break;
2548                         case PHASE_STATIN:
2549                                 len = 1;
2550                                 data = &tmp;
2551                                 NCR5380_transfer_pio(instance, &phase, &len, &data);
2552                                 cmd->SCp.Status = tmp;
2553                                 break;
2554                         default:
2555                                 printk("scsi%d: unknown phase\n", HOSTNO);
2556                                 NCR5380_dprint(NDEBUG_ANY, instance);
2557                         } /* switch(phase) */
2558                 } /* if (tmp * SR_REQ) */
2559         } /* while (1) */
2560 }
2561
2562 /*
2563  * Function : void NCR5380_reselect (struct Scsi_Host *instance)
2564  *
2565  * Purpose : does reselection, initializing the instance->connected
2566  *      field to point to the scsi_cmnd for which the I_T_L or I_T_L_Q
2567  *      nexus has been reestablished,
2568  *
2569  * Inputs : instance - this instance of the NCR5380.
2570  *
2571  */
2572
2573
2574 /* it might eventually prove necessary to do a dma setup on
2575    reselection, but it doesn't seem to be needed now -- sam */
2576
2577 static void NCR5380_reselect(struct Scsi_Host *instance)
2578 {
2579         SETUP_HOSTDATA(instance);
2580         unsigned char target_mask;
2581         unsigned char lun;
2582 #ifdef SUPPORT_TAGS
2583         unsigned char tag;
2584 #endif
2585         unsigned char msg[3];
2586         int __maybe_unused len;
2587         unsigned char __maybe_unused *data, __maybe_unused phase;
2588         struct scsi_cmnd *tmp = NULL, *prev;
2589
2590         /*
2591          * Disable arbitration, etc. since the host adapter obviously
2592          * lost, and tell an interrupted NCR5380_select() to restart.
2593          */
2594
2595         NCR5380_write(MODE_REG, MR_BASE);
2596
2597         target_mask = NCR5380_read(CURRENT_SCSI_DATA_REG) & ~(hostdata->id_mask);
2598
2599         dprintk(NDEBUG_RESELECTION, "scsi%d: reselect\n", HOSTNO);
2600
2601         /*
2602          * At this point, we have detected that our SCSI ID is on the bus,
2603          * SEL is true and BSY was false for at least one bus settle delay
2604          * (400 ns).
2605          *
2606          * We must assert BSY ourselves, until the target drops the SEL
2607          * signal.
2608          */
2609
2610         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_BSY);
2611
2612         while (NCR5380_read(STATUS_REG) & SR_SEL)
2613                 ;
2614         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
2615
2616         /*
2617          * Wait for target to go into MSGIN.
2618          */
2619
2620         while (!(NCR5380_read(STATUS_REG) & SR_REQ))
2621                 ;
2622
2623 #if defined(CONFIG_SUN3) && defined(REAL_DMA)
2624         /* acknowledge toggle to MSGIN */
2625         NCR5380_write(TARGET_COMMAND_REG, PHASE_SR_TO_TCR(PHASE_MSGIN));
2626
2627         /* peek at the byte without really hitting the bus */
2628         msg[0] = NCR5380_read(CURRENT_SCSI_DATA_REG);
2629 #else
2630         len = 1;
2631         data = msg;
2632         phase = PHASE_MSGIN;
2633         NCR5380_transfer_pio(instance, &phase, &len, &data);
2634 #endif
2635
2636         if (!(msg[0] & 0x80)) {
2637                 printk(KERN_DEBUG "scsi%d: expecting IDENTIFY message, got ", HOSTNO);
2638                 spi_print_msg(msg);
2639                 do_abort(instance);
2640                 return;
2641         }
2642         lun = (msg[0] & 0x07);
2643
2644 #if defined(SUPPORT_TAGS) && !defined(CONFIG_SUN3)
2645         /* If the phase is still MSGIN, the target wants to send some more
2646          * messages. In case it supports tagged queuing, this is probably a
2647          * SIMPLE_QUEUE_TAG for the I_T_L_Q nexus.
2648          */
2649         tag = TAG_NONE;
2650         if (phase == PHASE_MSGIN && (hostdata->flags & FLAG_TAGGED_QUEUING)) {
2651                 /* Accept previous IDENTIFY message by clearing ACK */
2652                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
2653                 len = 2;
2654                 data = msg + 1;
2655                 if (!NCR5380_transfer_pio(instance, &phase, &len, &data) &&
2656                     msg[1] == SIMPLE_QUEUE_TAG)
2657                         tag = msg[2];
2658                 dprintk(NDEBUG_TAGS, "scsi%d: target mask %02x, lun %d sent tag %d at "
2659                            "reselection\n", HOSTNO, target_mask, lun, tag);
2660         }
2661 #endif
2662
2663         /*
2664          * Find the command corresponding to the I_T_L or I_T_L_Q  nexus we
2665          * just reestablished, and remove it from the disconnected queue.
2666          */
2667
2668         for (tmp = (struct scsi_cmnd *) hostdata->disconnected_queue, prev = NULL;
2669              tmp; prev = tmp, tmp = NEXT(tmp)) {
2670                 if ((target_mask == (1 << tmp->device->id)) && (lun == tmp->device->lun)
2671 #ifdef SUPPORT_TAGS
2672                     && (tag == tmp->tag)
2673 #endif
2674                     ) {
2675                         if (prev) {
2676                                 REMOVE(prev, NEXT(prev), tmp, NEXT(tmp));
2677                                 SET_NEXT(prev, NEXT(tmp));
2678                         } else {
2679                                 REMOVE(-1, hostdata->disconnected_queue, tmp, NEXT(tmp));
2680                                 hostdata->disconnected_queue = NEXT(tmp);
2681                         }
2682                         SET_NEXT(tmp, NULL);
2683                         break;
2684                 }
2685         }
2686
2687         if (!tmp) {
2688                 printk(KERN_WARNING "scsi%d: warning: target bitmask %02x lun %d "
2689 #ifdef SUPPORT_TAGS
2690                        "tag %d "
2691 #endif
2692                        "not in disconnected_queue.\n",
2693                        HOSTNO, target_mask, lun
2694 #ifdef SUPPORT_TAGS
2695                        , tag
2696 #endif
2697                         );
2698                 /*
2699                  * Since we have an established nexus that we can't do anything
2700                  * with, we must abort it.
2701                  */
2702                 do_abort(instance);
2703                 return;
2704         }
2705
2706 #if defined(CONFIG_SUN3) && defined(REAL_DMA)
2707         /* engage dma setup for the command we just saw */
2708         {
2709                 void *d;
2710                 unsigned long count;
2711
2712                 if (!tmp->SCp.this_residual && tmp->SCp.buffers_residual) {
2713                         count = tmp->SCp.buffer->length;
2714                         d = sg_virt(tmp->SCp.buffer);
2715                 } else {
2716                         count = tmp->SCp.this_residual;
2717                         d = tmp->SCp.ptr;
2718                 }
2719                 /* setup this command for dma if not already */
2720                 if ((count >= DMA_MIN_SIZE) && (sun3_dma_setup_done != tmp)) {
2721                         sun3scsi_dma_setup(d, count, rq_data_dir(tmp->request));
2722                         sun3_dma_setup_done = tmp;
2723                 }
2724         }
2725
2726         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ACK);
2727 #endif
2728
2729         /* Accept message by clearing ACK */
2730         NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
2731
2732 #if defined(SUPPORT_TAGS) && defined(CONFIG_SUN3)
2733         /* If the phase is still MSGIN, the target wants to send some more
2734          * messages. In case it supports tagged queuing, this is probably a
2735          * SIMPLE_QUEUE_TAG for the I_T_L_Q nexus.
2736          */
2737         tag = TAG_NONE;
2738         if (phase == PHASE_MSGIN && setup_use_tagged_queuing) {
2739                 /* Accept previous IDENTIFY message by clearing ACK */
2740                 NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
2741                 len = 2;
2742                 data = msg + 1;
2743                 if (!NCR5380_transfer_pio(instance, &phase, &len, &data) &&
2744                     msg[1] == SIMPLE_QUEUE_TAG)
2745                         tag = msg[2];
2746                 dprintk(NDEBUG_TAGS, "scsi%d: target mask %02x, lun %d sent tag %d at reselection\n"
2747                         HOSTNO, target_mask, lun, tag);
2748         }
2749 #endif
2750
2751         hostdata->connected = tmp;
2752         dprintk(NDEBUG_RESELECTION, "scsi%d: nexus established, target = %d, lun = %llu, tag = %d\n",
2753                    HOSTNO, tmp->device->id, tmp->device->lun, tmp->tag);
2754 }
2755
2756
2757 /*
2758  * Function : int NCR5380_abort (struct scsi_cmnd *cmd)
2759  *
2760  * Purpose : abort a command
2761  *
2762  * Inputs : cmd - the scsi_cmnd to abort, code - code to set the
2763  *      host byte of the result field to, if zero DID_ABORTED is
2764  *      used.
2765  *
2766  * Returns : SUCCESS - success, FAILED on failure.
2767  *
2768  * XXX - there is no way to abort the command that is currently
2769  *       connected, you have to wait for it to complete.  If this is
2770  *       a problem, we could implement longjmp() / setjmp(), setjmp()
2771  *       called where the loop started in NCR5380_main().
2772  */
2773
2774 static
2775 int NCR5380_abort(struct scsi_cmnd *cmd)
2776 {
2777         struct Scsi_Host *instance = cmd->device->host;
2778         SETUP_HOSTDATA(instance);
2779         struct scsi_cmnd *tmp, **prev;
2780         unsigned long flags;
2781
2782         scmd_printk(KERN_NOTICE, cmd, "aborting command\n");
2783
2784         NCR5380_print_status(instance);
2785
2786         local_irq_save(flags);
2787
2788         dprintk(NDEBUG_ABORT, "scsi%d: abort called basr 0x%02x, sr 0x%02x\n", HOSTNO,
2789                     NCR5380_read(BUS_AND_STATUS_REG),
2790                     NCR5380_read(STATUS_REG));
2791
2792 #if 1
2793         /*
2794          * Case 1 : If the command is the currently executing command,
2795          * we'll set the aborted flag and return control so that
2796          * information transfer routine can exit cleanly.
2797          */
2798
2799         if (hostdata->connected == cmd) {
2800
2801                 dprintk(NDEBUG_ABORT, "scsi%d: aborting connected command\n", HOSTNO);
2802                 /*
2803                  * We should perform BSY checking, and make sure we haven't slipped
2804                  * into BUS FREE.
2805                  */
2806
2807                 /*      NCR5380_write(INITIATOR_COMMAND_REG, ICR_ASSERT_ATN); */
2808                 /*
2809                  * Since we can't change phases until we've completed the current
2810                  * handshake, we have to source or sink a byte of data if the current
2811                  * phase is not MSGOUT.
2812                  */
2813
2814                 /*
2815                  * Return control to the executing NCR drive so we can clear the
2816                  * aborted flag and get back into our main loop.
2817                  */
2818
2819                 if (do_abort(instance) == 0) {
2820                         hostdata->connected = NULL;
2821                         cmd->result = DID_ABORT << 16;
2822 #ifdef SUPPORT_TAGS
2823                         cmd_free_tag(cmd);
2824 #else
2825                         hostdata->busy[cmd->device->id] &= ~(1 << cmd->device->lun);
2826 #endif
2827                         maybe_release_dma_irq(instance);
2828                         local_irq_restore(flags);
2829                         cmd->scsi_done(cmd);
2830                         return SUCCESS;
2831                 } else {
2832                         local_irq_restore(flags);
2833                         printk("scsi%d: abort of connected command failed!\n", HOSTNO);
2834                         return FAILED;
2835                 }
2836         }
2837 #endif
2838
2839         /*
2840          * Case 2 : If the command hasn't been issued yet, we simply remove it
2841          *          from the issue queue.
2842          */
2843         for (prev = (struct scsi_cmnd **)&(hostdata->issue_queue),
2844              tmp = (struct scsi_cmnd *)hostdata->issue_queue;
2845              tmp; prev = NEXTADDR(tmp), tmp = NEXT(tmp)) {
2846                 if (cmd == tmp) {
2847                         REMOVE(5, *prev, tmp, NEXT(tmp));
2848                         (*prev) = NEXT(tmp);
2849                         SET_NEXT(tmp, NULL);
2850                         tmp->result = DID_ABORT << 16;
2851                         maybe_release_dma_irq(instance);
2852                         local_irq_restore(flags);
2853                         dprintk(NDEBUG_ABORT, "scsi%d: abort removed command from issue queue.\n",
2854                                     HOSTNO);
2855                         /* Tagged queuing note: no tag to free here, hasn't been assigned
2856                          * yet... */
2857                         tmp->scsi_done(tmp);
2858                         return SUCCESS;
2859                 }
2860         }
2861
2862         /*
2863          * Case 3 : If any commands are connected, we're going to fail the abort
2864          *          and let the high level SCSI driver retry at a later time or
2865          *          issue a reset.
2866          *
2867          *          Timeouts, and therefore aborted commands, will be highly unlikely
2868          *          and handling them cleanly in this situation would make the common
2869          *          case of noresets less efficient, and would pollute our code.  So,
2870          *          we fail.
2871          */
2872
2873         if (hostdata->connected) {
2874                 local_irq_restore(flags);
2875                 dprintk(NDEBUG_ABORT, "scsi%d: abort failed, command connected.\n", HOSTNO);
2876                 return FAILED;
2877         }
2878
2879         /*
2880          * Case 4: If the command is currently disconnected from the bus, and
2881          *      there are no connected commands, we reconnect the I_T_L or
2882          *      I_T_L_Q nexus associated with it, go into message out, and send
2883          *      an abort message.
2884          *
2885          * This case is especially ugly. In order to reestablish the nexus, we
2886          * need to call NCR5380_select().  The easiest way to implement this
2887          * function was to abort if the bus was busy, and let the interrupt
2888          * handler triggered on the SEL for reselect take care of lost arbitrations
2889          * where necessary, meaning interrupts need to be enabled.
2890          *
2891          * When interrupts are enabled, the queues may change - so we
2892          * can't remove it from the disconnected queue before selecting it
2893          * because that could cause a failure in hashing the nexus if that
2894          * device reselected.
2895          *
2896          * Since the queues may change, we can't use the pointers from when we
2897          * first locate it.
2898          *
2899          * So, we must first locate the command, and if NCR5380_select()
2900          * succeeds, then issue the abort, relocate the command and remove
2901          * it from the disconnected queue.
2902          */
2903
2904         for (tmp = (struct scsi_cmnd *) hostdata->disconnected_queue; tmp;
2905              tmp = NEXT(tmp)) {
2906                 if (cmd == tmp) {
2907                         local_irq_restore(flags);
2908                         dprintk(NDEBUG_ABORT, "scsi%d: aborting disconnected command.\n", HOSTNO);
2909
2910                         if (NCR5380_select(instance, cmd))
2911                                 return FAILED;
2912
2913                         dprintk(NDEBUG_ABORT, "scsi%d: nexus reestablished.\n", HOSTNO);
2914
2915                         do_abort(instance);
2916
2917                         local_irq_save(flags);
2918                         for (prev = (struct scsi_cmnd **)&(hostdata->disconnected_queue),
2919                              tmp = (struct scsi_cmnd *)hostdata->disconnected_queue;
2920                              tmp; prev = NEXTADDR(tmp), tmp = NEXT(tmp)) {
2921                                 if (cmd == tmp) {
2922                                         REMOVE(5, *prev, tmp, NEXT(tmp));
2923                                         *prev = NEXT(tmp);
2924                                         SET_NEXT(tmp, NULL);
2925                                         tmp->result = DID_ABORT << 16;
2926                                         /* We must unlock the tag/LUN immediately here, since the
2927                                          * target goes to BUS FREE and doesn't send us another
2928                                          * message (COMMAND_COMPLETE or the like)
2929                                          */
2930 #ifdef SUPPORT_TAGS
2931                                         cmd_free_tag(tmp);
2932 #else
2933                                         hostdata->busy[cmd->device->id] &= ~(1 << cmd->device->lun);
2934 #endif
2935                                         maybe_release_dma_irq(instance);
2936                                         local_irq_restore(flags);
2937                                         tmp->scsi_done(tmp);
2938                                         return SUCCESS;
2939                                 }
2940                         }
2941                 }
2942         }
2943
2944         /* Maybe it is sufficient just to release the ST-DMA lock... (if
2945          * possible at all) At least, we should check if the lock could be
2946          * released after the abort, in case it is kept due to some bug.
2947          */
2948         maybe_release_dma_irq(instance);
2949         local_irq_restore(flags);
2950
2951         /*
2952          * Case 5 : If we reached this point, the command was not found in any of
2953          *          the queues.
2954          *
2955          * We probably reached this point because of an unlikely race condition
2956          * between the command completing successfully and the abortion code,
2957          * so we won't panic, but we will notify the user in case something really
2958          * broke.
2959          */
2960
2961         printk(KERN_INFO "scsi%d: warning : SCSI command probably completed successfully before abortion\n", HOSTNO);
2962
2963         return FAILED;
2964 }
2965
2966
2967 /**
2968  * NCR5380_bus_reset - reset the SCSI bus
2969  * @cmd: SCSI command undergoing EH
2970  *
2971  * Returns SUCCESS
2972  */
2973
2974 static int NCR5380_bus_reset(struct scsi_cmnd *cmd)
2975 {
2976         struct Scsi_Host *instance = cmd->device->host;
2977         struct NCR5380_hostdata *hostdata = shost_priv(instance);
2978         int i;
2979         unsigned long flags;
2980
2981         local_irq_save(flags);
2982
2983 #if (NDEBUG & NDEBUG_ANY)
2984         scmd_printk(KERN_INFO, cmd, "performing bus reset\n");
2985         NCR5380_print_status(instance);
2986 #endif
2987
2988         do_reset(instance);
2989
2990         /* reset NCR registers */
2991         NCR5380_write(MODE_REG, MR_BASE);
2992         NCR5380_write(TARGET_COMMAND_REG, 0);
2993         NCR5380_write(SELECT_ENABLE_REG, 0);
2994
2995         /* After the reset, there are no more connected or disconnected commands
2996          * and no busy units; so clear the low-level status here to avoid
2997          * conflicts when the mid-level code tries to wake up the affected
2998          * commands!
2999          */
3000
3001         if (hostdata->issue_queue)
3002                 dprintk(NDEBUG_ABORT, "scsi%d: reset aborted issued command(s)\n", H_NO(cmd));
3003         if (hostdata->connected)
3004                 dprintk(NDEBUG_ABORT, "scsi%d: reset aborted a connected command\n", H_NO(cmd));
3005         if (hostdata->disconnected_queue)
3006                 dprintk(NDEBUG_ABORT, "scsi%d: reset aborted disconnected command(s)\n", H_NO(cmd));
3007
3008         hostdata->issue_queue = NULL;
3009         hostdata->connected = NULL;
3010         hostdata->disconnected_queue = NULL;
3011 #ifdef SUPPORT_TAGS
3012         free_all_tags(hostdata);
3013 #endif
3014         for (i = 0; i < 8; ++i)
3015                 hostdata->busy[i] = 0;
3016 #ifdef REAL_DMA
3017         hostdata->dma_len = 0;
3018 #endif
3019
3020         maybe_release_dma_irq(instance);
3021         local_irq_restore(flags);
3022
3023         return SUCCESS;
3024 }