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