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