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