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