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