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