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