xref: /linux/drivers/scsi/NCR5380.c (revision f3a8b6645dc2e60d11f20c1c23afd964ff4e55ae)
1 /*
2  * NCR 5380 generic driver routines.  These should make it *trivial*
3  * to implement 5380 SCSI drivers under Linux with a non-trantor
4  * architecture.
5  *
6  * Note that these routines also work with NR53c400 family chips.
7  *
8  * Copyright 1993, Drew Eckhardt
9  * Visionary Computing
10  * (Unix and Linux consulting and custom programming)
11  * drew@colorado.edu
12  * +1 (303) 666-5836
13  *
14  * For more information, please consult
15  *
16  * NCR 5380 Family
17  * SCSI Protocol Controller
18  * Databook
19  *
20  * NCR Microelectronics
21  * 1635 Aeroplaza Drive
22  * Colorado Springs, CO 80916
23  * 1+ (719) 578-3400
24  * 1+ (800) 334-5454
25  */
26 
27 /*
28  * With contributions from Ray Van Tassle, Ingmar Baumgart,
29  * Ronald van Cuijlenborg, Alan Cox and others.
30  */
31 
32 /* Ported to Atari by Roman Hodek and others. */
33 
34 /* Adapted for the Sun 3 by Sam Creasey. */
35 
36 /*
37  * Design
38  *
39  * This is a generic 5380 driver.  To use it on a different platform,
40  * one simply writes appropriate system specific macros (ie, data
41  * transfer - some PC's will use the I/O bus, 68K's must use
42  * memory mapped) and drops this file in their 'C' wrapper.
43  *
44  * As far as command queueing, two queues are maintained for
45  * each 5380 in the system - commands that haven't been issued yet,
46  * and commands that are currently executing.  This means that an
47  * unlimited number of commands may be queued, letting
48  * more commands propagate from the higher driver levels giving higher
49  * throughput.  Note that both I_T_L and I_T_L_Q nexuses are supported,
50  * allowing multiple commands to propagate all the way to a SCSI-II device
51  * while a command is already executing.
52  *
53  *
54  * Issues specific to the NCR5380 :
55  *
56  * When used in a PIO or pseudo-dma mode, the NCR5380 is a braindead
57  * piece of hardware that requires you to sit in a loop polling for
58  * the REQ signal as long as you are connected.  Some devices are
59  * brain dead (ie, many TEXEL CD ROM drives) and won't disconnect
60  * while doing long seek operations. [...] These
61  * broken devices are the exception rather than the rule and I'd rather
62  * spend my time optimizing for the normal case.
63  *
64  * Architecture :
65  *
66  * At the heart of the design is a coroutine, NCR5380_main,
67  * which is started from a workqueue for each NCR5380 host in the
68  * system.  It attempts to establish I_T_L or I_T_L_Q nexuses by
69  * removing the commands from the issue queue and calling
70  * NCR5380_select() if a nexus is not established.
71  *
72  * Once a nexus is established, the NCR5380_information_transfer()
73  * phase goes through the various phases as instructed by the target.
74  * if the target goes into MSG IN and sends a DISCONNECT message,
75  * the command structure is placed into the per instance disconnected
76  * queue, and NCR5380_main tries to find more work.  If the target is
77  * idle for too long, the system will try to sleep.
78  *
79  * If a command has disconnected, eventually an interrupt will trigger,
80  * calling NCR5380_intr()  which will in turn call NCR5380_reselect
81  * to reestablish a nexus.  This will run main if necessary.
82  *
83  * On command termination, the done function will be called as
84  * appropriate.
85  *
86  * SCSI pointers are maintained in the SCp field of SCSI command
87  * structures, being initialized after the command is connected
88  * in NCR5380_select, and set as appropriate in NCR5380_information_transfer.
89  * Note that in violation of the standard, an implicit SAVE POINTERS operation
90  * is done, since some BROKEN disks fail to issue an explicit SAVE POINTERS.
91  */
92 
93 /*
94  * Using this file :
95  * This file a skeleton Linux SCSI driver for the NCR 5380 series
96  * of chips.  To use it, you write an architecture specific functions
97  * and macros and include this file in your driver.
98  *
99  * These macros control options :
100  * AUTOPROBE_IRQ - if defined, the NCR5380_probe_irq() function will be
101  * defined.
102  *
103  * AUTOSENSE - if defined, REQUEST SENSE will be performed automatically
104  * for commands that return with a CHECK CONDITION status.
105  *
106  * DIFFERENTIAL - if defined, NCR53c81 chips will use external differential
107  * transceivers.
108  *
109  * PSEUDO_DMA - if defined, PSEUDO DMA is used during the data transfer phases.
110  *
111  * REAL_DMA - if defined, REAL DMA is used during the data transfer phases.
112  *
113  * These macros MUST be defined :
114  *
115  * NCR5380_read(register)  - read from the specified register
116  *
117  * NCR5380_write(register, value) - write to the specific register
118  *
119  * NCR5380_implementation_fields  - additional fields needed for this
120  * specific implementation of the NCR5380
121  *
122  * Either real DMA *or* pseudo DMA may be implemented
123  *
124  * NCR5380_dma_write_setup(instance, src, count) - initialize
125  * NCR5380_dma_read_setup(instance, dst, count) - initialize
126  * NCR5380_dma_residual(instance); - residual count
127  *
128  * The generic driver is initialized by calling NCR5380_init(instance),
129  * after setting the appropriate host specific fields and ID.  If the
130  * driver wishes to autoprobe for an IRQ line, the NCR5380_probe_irq(instance,
131  * possible) function may be used.
132  */
133 
134 #ifndef NCR5380_io_delay
135 #define NCR5380_io_delay(x)
136 #endif
137 
138 #ifndef NCR5380_acquire_dma_irq
139 #define NCR5380_acquire_dma_irq(x)	(1)
140 #endif
141 
142 #ifndef NCR5380_release_dma_irq
143 #define NCR5380_release_dma_irq(x)
144 #endif
145 
146 static int do_abort(struct Scsi_Host *);
147 static void do_reset(struct Scsi_Host *);
148 
149 /**
150  * initialize_SCp - init the scsi pointer field
151  * @cmd: command block to set up
152  *
153  * Set up the internal fields in the SCSI command.
154  */
155 
156 static inline void initialize_SCp(struct scsi_cmnd *cmd)
157 {
158 	/*
159 	 * Initialize the Scsi Pointer field so that all of the commands in the
160 	 * various queues are valid.
161 	 */
162 
163 	if (scsi_bufflen(cmd)) {
164 		cmd->SCp.buffer = scsi_sglist(cmd);
165 		cmd->SCp.buffers_residual = scsi_sg_count(cmd) - 1;
166 		cmd->SCp.ptr = sg_virt(cmd->SCp.buffer);
167 		cmd->SCp.this_residual = cmd->SCp.buffer->length;
168 	} else {
169 		cmd->SCp.buffer = NULL;
170 		cmd->SCp.buffers_residual = 0;
171 		cmd->SCp.ptr = NULL;
172 		cmd->SCp.this_residual = 0;
173 	}
174 
175 	cmd->SCp.Status = 0;
176 	cmd->SCp.Message = 0;
177 }
178 
179 /**
180  * NCR5380_poll_politely2 - wait for two chip register values
181  * @instance: controller to poll
182  * @reg1: 5380 register to poll
183  * @bit1: Bitmask to check
184  * @val1: Expected value
185  * @reg2: Second 5380 register to poll
186  * @bit2: Second bitmask to check
187  * @val2: Second expected value
188  * @wait: Time-out in jiffies
189  *
190  * Polls the chip in a reasonably efficient manner waiting for an
191  * event to occur. After a short quick poll we begin to yield the CPU
192  * (if possible). In irq contexts the time-out is arbitrarily limited.
193  * Callers may hold locks as long as they are held in irq mode.
194  *
195  * Returns 0 if either or both event(s) occurred otherwise -ETIMEDOUT.
196  */
197 
198 static int NCR5380_poll_politely2(struct Scsi_Host *instance,
199                                   int reg1, int bit1, int val1,
200                                   int reg2, int bit2, int val2, int wait)
201 {
202 	struct NCR5380_hostdata *hostdata = shost_priv(instance);
203 	unsigned long deadline = jiffies + wait;
204 	unsigned long n;
205 
206 	/* Busy-wait for up to 10 ms */
207 	n = min(10000U, jiffies_to_usecs(wait));
208 	n *= hostdata->accesses_per_ms;
209 	n /= 2000;
210 	do {
211 		if ((NCR5380_read(reg1) & bit1) == val1)
212 			return 0;
213 		if ((NCR5380_read(reg2) & bit2) == val2)
214 			return 0;
215 		cpu_relax();
216 	} while (n--);
217 
218 	if (irqs_disabled() || in_interrupt())
219 		return -ETIMEDOUT;
220 
221 	/* Repeatedly sleep for 1 ms until deadline */
222 	while (time_is_after_jiffies(deadline)) {
223 		schedule_timeout_uninterruptible(1);
224 		if ((NCR5380_read(reg1) & bit1) == val1)
225 			return 0;
226 		if ((NCR5380_read(reg2) & bit2) == val2)
227 			return 0;
228 	}
229 
230 	return -ETIMEDOUT;
231 }
232 
233 #if NDEBUG
234 static struct {
235 	unsigned char mask;
236 	const char *name;
237 } signals[] = {
238 	{SR_DBP, "PARITY"},
239 	{SR_RST, "RST"},
240 	{SR_BSY, "BSY"},
241 	{SR_REQ, "REQ"},
242 	{SR_MSG, "MSG"},
243 	{SR_CD, "CD"},
244 	{SR_IO, "IO"},
245 	{SR_SEL, "SEL"},
246 	{0, NULL}
247 },
248 basrs[] = {
249 	{BASR_END_DMA_TRANSFER, "END OF DMA"},
250 	{BASR_DRQ, "DRQ"},
251 	{BASR_PARITY_ERROR, "PARITY ERROR"},
252 	{BASR_IRQ, "IRQ"},
253 	{BASR_PHASE_MATCH, "PHASE MATCH"},
254 	{BASR_BUSY_ERROR, "BUSY ERROR"},
255 	{BASR_ATN, "ATN"},
256 	{BASR_ACK, "ACK"},
257 	{0, NULL}
258 },
259 icrs[] = {
260 	{ICR_ASSERT_RST, "ASSERT RST"},
261 	{ICR_ARBITRATION_PROGRESS, "ARB. IN PROGRESS"},
262 	{ICR_ARBITRATION_LOST, "LOST ARB."},
263 	{ICR_ASSERT_ACK, "ASSERT ACK"},
264 	{ICR_ASSERT_BSY, "ASSERT BSY"},
265 	{ICR_ASSERT_SEL, "ASSERT SEL"},
266 	{ICR_ASSERT_ATN, "ASSERT ATN"},
267 	{ICR_ASSERT_DATA, "ASSERT DATA"},
268 	{0, NULL}
269 },
270 mrs[] = {
271 	{MR_BLOCK_DMA_MODE, "BLOCK DMA MODE"},
272 	{MR_TARGET, "TARGET"},
273 	{MR_ENABLE_PAR_CHECK, "PARITY CHECK"},
274 	{MR_ENABLE_PAR_INTR, "PARITY INTR"},
275 	{MR_ENABLE_EOP_INTR, "EOP INTR"},
276 	{MR_MONITOR_BSY, "MONITOR BSY"},
277 	{MR_DMA_MODE, "DMA MODE"},
278 	{MR_ARBITRATE, "ARBITRATE"},
279 	{0, NULL}
280 };
281 
282 /**
283  * NCR5380_print - print scsi bus signals
284  * @instance: adapter state to dump
285  *
286  * Print the SCSI bus signals for debugging purposes
287  */
288 
289 static void NCR5380_print(struct Scsi_Host *instance)
290 {
291 	unsigned char status, data, basr, mr, icr, i;
292 
293 	data = NCR5380_read(CURRENT_SCSI_DATA_REG);
294 	status = NCR5380_read(STATUS_REG);
295 	mr = NCR5380_read(MODE_REG);
296 	icr = NCR5380_read(INITIATOR_COMMAND_REG);
297 	basr = NCR5380_read(BUS_AND_STATUS_REG);
298 
299 	printk(KERN_DEBUG "SR =   0x%02x : ", status);
300 	for (i = 0; signals[i].mask; ++i)
301 		if (status & signals[i].mask)
302 			printk(KERN_CONT "%s, ", signals[i].name);
303 	printk(KERN_CONT "\nBASR = 0x%02x : ", basr);
304 	for (i = 0; basrs[i].mask; ++i)
305 		if (basr & basrs[i].mask)
306 			printk(KERN_CONT "%s, ", basrs[i].name);
307 	printk(KERN_CONT "\nICR =  0x%02x : ", icr);
308 	for (i = 0; icrs[i].mask; ++i)
309 		if (icr & icrs[i].mask)
310 			printk(KERN_CONT "%s, ", icrs[i].name);
311 	printk(KERN_CONT "\nMR =   0x%02x : ", mr);
312 	for (i = 0; mrs[i].mask; ++i)
313 		if (mr & mrs[i].mask)
314 			printk(KERN_CONT "%s, ", mrs[i].name);
315 	printk(KERN_CONT "\n");
316 }
317 
318 static struct {
319 	unsigned char value;
320 	const char *name;
321 } phases[] = {
322 	{PHASE_DATAOUT, "DATAOUT"},
323 	{PHASE_DATAIN, "DATAIN"},
324 	{PHASE_CMDOUT, "CMDOUT"},
325 	{PHASE_STATIN, "STATIN"},
326 	{PHASE_MSGOUT, "MSGOUT"},
327 	{PHASE_MSGIN, "MSGIN"},
328 	{PHASE_UNKNOWN, "UNKNOWN"}
329 };
330 
331 /**
332  * NCR5380_print_phase - show SCSI phase
333  * @instance: adapter to dump
334  *
335  * Print the current SCSI phase for debugging purposes
336  */
337 
338 static void NCR5380_print_phase(struct Scsi_Host *instance)
339 {
340 	unsigned char status;
341 	int i;
342 
343 	status = NCR5380_read(STATUS_REG);
344 	if (!(status & SR_REQ))
345 		shost_printk(KERN_DEBUG, instance, "REQ not asserted, phase unknown.\n");
346 	else {
347 		for (i = 0; (phases[i].value != PHASE_UNKNOWN) &&
348 		     (phases[i].value != (status & PHASE_MASK)); ++i)
349 			;
350 		shost_printk(KERN_DEBUG, instance, "phase %s\n", phases[i].name);
351 	}
352 }
353 #endif
354 
355 
356 static int probe_irq;
357 
358 /**
359  * probe_intr	-	helper for IRQ autoprobe
360  * @irq: interrupt number
361  * @dev_id: unused
362  * @regs: unused
363  *
364  * Set a flag to indicate the IRQ in question was received. This is
365  * used by the IRQ probe code.
366  */
367 
368 static irqreturn_t probe_intr(int irq, void *dev_id)
369 {
370 	probe_irq = irq;
371 	return IRQ_HANDLED;
372 }
373 
374 /**
375  * NCR5380_probe_irq	-	find the IRQ of an NCR5380
376  * @instance: NCR5380 controller
377  * @possible: bitmask of ISA IRQ lines
378  *
379  * Autoprobe for the IRQ line used by the NCR5380 by triggering an IRQ
380  * and then looking to see what interrupt actually turned up.
381  */
382 
383 static int __maybe_unused NCR5380_probe_irq(struct Scsi_Host *instance,
384 						int possible)
385 {
386 	struct NCR5380_hostdata *hostdata = shost_priv(instance);
387 	unsigned long timeout;
388 	int trying_irqs, i, mask;
389 
390 	for (trying_irqs = 0, i = 1, mask = 2; i < 16; ++i, mask <<= 1)
391 		if ((mask & possible) && (request_irq(i, &probe_intr, 0, "NCR-probe", NULL) == 0))
392 			trying_irqs |= mask;
393 
394 	timeout = jiffies + msecs_to_jiffies(250);
395 	probe_irq = NO_IRQ;
396 
397 	/*
398 	 * A interrupt is triggered whenever BSY = false, SEL = true
399 	 * and a bit set in the SELECT_ENABLE_REG is asserted on the
400 	 * SCSI bus.
401 	 *
402 	 * Note that the bus is only driven when the phase control signals
403 	 * (I/O, C/D, and MSG) match those in the TCR, so we must reset that
404 	 * to zero.
405 	 */
406 
407 	NCR5380_write(TARGET_COMMAND_REG, 0);
408 	NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
409 	NCR5380_write(OUTPUT_DATA_REG, hostdata->id_mask);
410 	NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_DATA | ICR_ASSERT_SEL);
411 
412 	while (probe_irq == NO_IRQ && time_before(jiffies, timeout))
413 		schedule_timeout_uninterruptible(1);
414 
415 	NCR5380_write(SELECT_ENABLE_REG, 0);
416 	NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
417 
418 	for (i = 1, mask = 2; i < 16; ++i, mask <<= 1)
419 		if (trying_irqs & mask)
420 			free_irq(i, NULL);
421 
422 	return probe_irq;
423 }
424 
425 /**
426  * NCR58380_info - report driver and host information
427  * @instance: relevant scsi host instance
428  *
429  * For use as the host template info() handler.
430  */
431 
432 static const char *NCR5380_info(struct Scsi_Host *instance)
433 {
434 	struct NCR5380_hostdata *hostdata = shost_priv(instance);
435 
436 	return hostdata->info;
437 }
438 
439 static void prepare_info(struct Scsi_Host *instance)
440 {
441 	struct NCR5380_hostdata *hostdata = shost_priv(instance);
442 
443 	snprintf(hostdata->info, sizeof(hostdata->info),
444 	         "%s, io_port 0x%lx, n_io_port %d, "
445 	         "base 0x%lx, irq %d, "
446 	         "can_queue %d, cmd_per_lun %d, "
447 	         "sg_tablesize %d, this_id %d, "
448 	         "flags { %s%s%s}, "
449 	         "options { %s} ",
450 	         instance->hostt->name, instance->io_port, instance->n_io_port,
451 	         instance->base, instance->irq,
452 	         instance->can_queue, instance->cmd_per_lun,
453 	         instance->sg_tablesize, instance->this_id,
454 	         hostdata->flags & FLAG_DMA_FIXUP     ? "DMA_FIXUP "     : "",
455 	         hostdata->flags & FLAG_NO_PSEUDO_DMA ? "NO_PSEUDO_DMA " : "",
456 	         hostdata->flags & FLAG_TOSHIBA_DELAY ? "TOSHIBA_DELAY "  : "",
457 #ifdef DIFFERENTIAL
458 	         "DIFFERENTIAL "
459 #endif
460 #ifdef PARITY
461 	         "PARITY "
462 #endif
463 	         "");
464 }
465 
466 /**
467  * NCR5380_init - initialise an NCR5380
468  * @instance: adapter to configure
469  * @flags: control flags
470  *
471  * Initializes *instance and corresponding 5380 chip,
472  * with flags OR'd into the initial flags value.
473  *
474  * Notes : I assume that the host, hostno, and id bits have been
475  * set correctly. I don't care about the irq and other fields.
476  *
477  * Returns 0 for success
478  */
479 
480 static int NCR5380_init(struct Scsi_Host *instance, int flags)
481 {
482 	struct NCR5380_hostdata *hostdata = shost_priv(instance);
483 	int i;
484 	unsigned long deadline;
485 
486 	instance->max_lun = 7;
487 
488 	hostdata->host = instance;
489 	hostdata->id_mask = 1 << instance->this_id;
490 	hostdata->id_higher_mask = 0;
491 	for (i = hostdata->id_mask; i <= 0x80; i <<= 1)
492 		if (i > hostdata->id_mask)
493 			hostdata->id_higher_mask |= i;
494 	for (i = 0; i < 8; ++i)
495 		hostdata->busy[i] = 0;
496 	hostdata->dma_len = 0;
497 
498 	spin_lock_init(&hostdata->lock);
499 	hostdata->connected = NULL;
500 	hostdata->sensing = NULL;
501 	INIT_LIST_HEAD(&hostdata->autosense);
502 	INIT_LIST_HEAD(&hostdata->unissued);
503 	INIT_LIST_HEAD(&hostdata->disconnected);
504 
505 	hostdata->flags = flags;
506 
507 	INIT_WORK(&hostdata->main_task, NCR5380_main);
508 	hostdata->work_q = alloc_workqueue("ncr5380_%d",
509 	                        WQ_UNBOUND | WQ_MEM_RECLAIM,
510 	                        1, instance->host_no);
511 	if (!hostdata->work_q)
512 		return -ENOMEM;
513 
514 	prepare_info(instance);
515 
516 	NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
517 	NCR5380_write(MODE_REG, MR_BASE);
518 	NCR5380_write(TARGET_COMMAND_REG, 0);
519 	NCR5380_write(SELECT_ENABLE_REG, 0);
520 
521 	/* Calibrate register polling loop */
522 	i = 0;
523 	deadline = jiffies + 1;
524 	do {
525 		cpu_relax();
526 	} while (time_is_after_jiffies(deadline));
527 	deadline += msecs_to_jiffies(256);
528 	do {
529 		NCR5380_read(STATUS_REG);
530 		++i;
531 		cpu_relax();
532 	} while (time_is_after_jiffies(deadline));
533 	hostdata->accesses_per_ms = i / 256;
534 
535 	return 0;
536 }
537 
538 /**
539  * NCR5380_maybe_reset_bus - Detect and correct bus wedge problems.
540  * @instance: adapter to check
541  *
542  * If the system crashed, it may have crashed with a connected target and
543  * the SCSI bus busy. Check for BUS FREE phase. If not, try to abort the
544  * currently established nexus, which we know nothing about. Failing that
545  * do a bus reset.
546  *
547  * Note that a bus reset will cause the chip to assert IRQ.
548  *
549  * Returns 0 if successful, otherwise -ENXIO.
550  */
551 
552 static int NCR5380_maybe_reset_bus(struct Scsi_Host *instance)
553 {
554 	struct NCR5380_hostdata *hostdata = shost_priv(instance);
555 	int pass;
556 
557 	for (pass = 1; (NCR5380_read(STATUS_REG) & SR_BSY) && pass <= 6; ++pass) {
558 		switch (pass) {
559 		case 1:
560 		case 3:
561 		case 5:
562 			shost_printk(KERN_ERR, instance, "SCSI bus busy, waiting up to five seconds\n");
563 			NCR5380_poll_politely(instance,
564 			                      STATUS_REG, SR_BSY, 0, 5 * HZ);
565 			break;
566 		case 2:
567 			shost_printk(KERN_ERR, instance, "bus busy, attempting abort\n");
568 			do_abort(instance);
569 			break;
570 		case 4:
571 			shost_printk(KERN_ERR, instance, "bus busy, attempting reset\n");
572 			do_reset(instance);
573 			/* Wait after a reset; the SCSI standard calls for
574 			 * 250ms, we wait 500ms to be on the safe side.
575 			 * But some Toshiba CD-ROMs need ten times that.
576 			 */
577 			if (hostdata->flags & FLAG_TOSHIBA_DELAY)
578 				msleep(2500);
579 			else
580 				msleep(500);
581 			break;
582 		case 6:
583 			shost_printk(KERN_ERR, instance, "bus locked solid\n");
584 			return -ENXIO;
585 		}
586 	}
587 	return 0;
588 }
589 
590 /**
591  * NCR5380_exit - remove an NCR5380
592  * @instance: adapter to remove
593  *
594  * Assumes that no more work can be queued (e.g. by NCR5380_intr).
595  */
596 
597 static void NCR5380_exit(struct Scsi_Host *instance)
598 {
599 	struct NCR5380_hostdata *hostdata = shost_priv(instance);
600 
601 	cancel_work_sync(&hostdata->main_task);
602 	destroy_workqueue(hostdata->work_q);
603 }
604 
605 /**
606  * complete_cmd - finish processing a command and return it to the SCSI ML
607  * @instance: the host instance
608  * @cmd: command to complete
609  */
610 
611 static void complete_cmd(struct Scsi_Host *instance,
612                          struct scsi_cmnd *cmd)
613 {
614 	struct NCR5380_hostdata *hostdata = shost_priv(instance);
615 
616 	dsprintk(NDEBUG_QUEUES, instance, "complete_cmd: cmd %p\n", cmd);
617 
618 	if (hostdata->sensing == cmd) {
619 		/* Autosense processing ends here */
620 		if ((cmd->result & 0xff) != SAM_STAT_GOOD) {
621 			scsi_eh_restore_cmnd(cmd, &hostdata->ses);
622 			set_host_byte(cmd, DID_ERROR);
623 		} else
624 			scsi_eh_restore_cmnd(cmd, &hostdata->ses);
625 		hostdata->sensing = NULL;
626 	}
627 
628 	hostdata->busy[scmd_id(cmd)] &= ~(1 << cmd->device->lun);
629 
630 	cmd->scsi_done(cmd);
631 }
632 
633 /**
634  * NCR5380_queue_command - queue a command
635  * @instance: the relevant SCSI adapter
636  * @cmd: SCSI command
637  *
638  * cmd is added to the per-instance issue queue, with minor
639  * twiddling done to the host specific fields of cmd.  If the
640  * main coroutine is not running, it is restarted.
641  */
642 
643 static int NCR5380_queue_command(struct Scsi_Host *instance,
644                                  struct scsi_cmnd *cmd)
645 {
646 	struct NCR5380_hostdata *hostdata = shost_priv(instance);
647 	struct NCR5380_cmd *ncmd = scsi_cmd_priv(cmd);
648 	unsigned long flags;
649 
650 #if (NDEBUG & NDEBUG_NO_WRITE)
651 	switch (cmd->cmnd[0]) {
652 	case WRITE_6:
653 	case WRITE_10:
654 		shost_printk(KERN_DEBUG, instance, "WRITE attempted with NDEBUG_NO_WRITE set\n");
655 		cmd->result = (DID_ERROR << 16);
656 		cmd->scsi_done(cmd);
657 		return 0;
658 	}
659 #endif /* (NDEBUG & NDEBUG_NO_WRITE) */
660 
661 	cmd->result = 0;
662 
663 	if (!NCR5380_acquire_dma_irq(instance))
664 		return SCSI_MLQUEUE_HOST_BUSY;
665 
666 	spin_lock_irqsave(&hostdata->lock, flags);
667 
668 	/*
669 	 * Insert the cmd into the issue queue. Note that REQUEST SENSE
670 	 * commands are added to the head of the queue since any command will
671 	 * clear the contingent allegiance condition that exists and the
672 	 * sense data is only guaranteed to be valid while the condition exists.
673 	 */
674 
675 	if (cmd->cmnd[0] == REQUEST_SENSE)
676 		list_add(&ncmd->list, &hostdata->unissued);
677 	else
678 		list_add_tail(&ncmd->list, &hostdata->unissued);
679 
680 	spin_unlock_irqrestore(&hostdata->lock, flags);
681 
682 	dsprintk(NDEBUG_QUEUES, instance, "command %p added to %s of queue\n",
683 	         cmd, (cmd->cmnd[0] == REQUEST_SENSE) ? "head" : "tail");
684 
685 	/* Kick off command processing */
686 	queue_work(hostdata->work_q, &hostdata->main_task);
687 	return 0;
688 }
689 
690 static inline void maybe_release_dma_irq(struct Scsi_Host *instance)
691 {
692 	struct NCR5380_hostdata *hostdata = shost_priv(instance);
693 
694 	/* Caller does the locking needed to set & test these data atomically */
695 	if (list_empty(&hostdata->disconnected) &&
696 	    list_empty(&hostdata->unissued) &&
697 	    list_empty(&hostdata->autosense) &&
698 	    !hostdata->connected &&
699 	    !hostdata->selecting)
700 		NCR5380_release_dma_irq(instance);
701 }
702 
703 /**
704  * dequeue_next_cmd - dequeue a command for processing
705  * @instance: the scsi host instance
706  *
707  * Priority is given to commands on the autosense queue. These commands
708  * need autosense because of a CHECK CONDITION result.
709  *
710  * Returns a command pointer if a command is found for a target that is
711  * not already busy. Otherwise returns NULL.
712  */
713 
714 static struct scsi_cmnd *dequeue_next_cmd(struct Scsi_Host *instance)
715 {
716 	struct NCR5380_hostdata *hostdata = shost_priv(instance);
717 	struct NCR5380_cmd *ncmd;
718 	struct scsi_cmnd *cmd;
719 
720 	if (hostdata->sensing || list_empty(&hostdata->autosense)) {
721 		list_for_each_entry(ncmd, &hostdata->unissued, list) {
722 			cmd = NCR5380_to_scmd(ncmd);
723 			dsprintk(NDEBUG_QUEUES, instance, "dequeue: cmd=%p target=%d busy=0x%02x lun=%llu\n",
724 			         cmd, scmd_id(cmd), hostdata->busy[scmd_id(cmd)], cmd->device->lun);
725 
726 			if (!(hostdata->busy[scmd_id(cmd)] & (1 << cmd->device->lun))) {
727 				list_del(&ncmd->list);
728 				dsprintk(NDEBUG_QUEUES, instance,
729 				         "dequeue: removed %p from issue queue\n", cmd);
730 				return cmd;
731 			}
732 		}
733 	} else {
734 		/* Autosense processing begins here */
735 		ncmd = list_first_entry(&hostdata->autosense,
736 		                        struct NCR5380_cmd, list);
737 		list_del(&ncmd->list);
738 		cmd = NCR5380_to_scmd(ncmd);
739 		dsprintk(NDEBUG_QUEUES, instance,
740 		         "dequeue: removed %p from autosense queue\n", cmd);
741 		scsi_eh_prep_cmnd(cmd, &hostdata->ses, NULL, 0, ~0);
742 		hostdata->sensing = cmd;
743 		return cmd;
744 	}
745 	return NULL;
746 }
747 
748 static void requeue_cmd(struct Scsi_Host *instance, struct scsi_cmnd *cmd)
749 {
750 	struct NCR5380_hostdata *hostdata = shost_priv(instance);
751 	struct NCR5380_cmd *ncmd = scsi_cmd_priv(cmd);
752 
753 	if (hostdata->sensing == cmd) {
754 		scsi_eh_restore_cmnd(cmd, &hostdata->ses);
755 		list_add(&ncmd->list, &hostdata->autosense);
756 		hostdata->sensing = NULL;
757 	} else
758 		list_add(&ncmd->list, &hostdata->unissued);
759 }
760 
761 /**
762  * NCR5380_main - NCR state machines
763  *
764  * NCR5380_main is a coroutine that runs as long as more work can
765  * be done on the NCR5380 host adapters in a system.  Both
766  * NCR5380_queue_command() and NCR5380_intr() will try to start it
767  * in case it is not running.
768  */
769 
770 static void NCR5380_main(struct work_struct *work)
771 {
772 	struct NCR5380_hostdata *hostdata =
773 		container_of(work, struct NCR5380_hostdata, main_task);
774 	struct Scsi_Host *instance = hostdata->host;
775 	int done;
776 
777 	do {
778 		done = 1;
779 
780 		spin_lock_irq(&hostdata->lock);
781 		while (!hostdata->connected && !hostdata->selecting) {
782 			struct scsi_cmnd *cmd = dequeue_next_cmd(instance);
783 
784 			if (!cmd)
785 				break;
786 
787 			dsprintk(NDEBUG_MAIN, instance, "main: dequeued %p\n", cmd);
788 
789 			/*
790 			 * Attempt to establish an I_T_L nexus here.
791 			 * On success, instance->hostdata->connected is set.
792 			 * On failure, we must add the command back to the
793 			 * issue queue so we can keep trying.
794 			 */
795 			/*
796 			 * REQUEST SENSE commands are issued without tagged
797 			 * queueing, even on SCSI-II devices because the
798 			 * contingent allegiance condition exists for the
799 			 * entire unit.
800 			 */
801 
802 			if (!NCR5380_select(instance, cmd)) {
803 				dsprintk(NDEBUG_MAIN, instance, "main: select complete\n");
804 				maybe_release_dma_irq(instance);
805 			} else {
806 				dsprintk(NDEBUG_MAIN | NDEBUG_QUEUES, instance,
807 				         "main: select failed, returning %p to queue\n", cmd);
808 				requeue_cmd(instance, cmd);
809 			}
810 		}
811 		if (hostdata->connected && !hostdata->dma_len) {
812 			dsprintk(NDEBUG_MAIN, instance, "main: performing information transfer\n");
813 			NCR5380_information_transfer(instance);
814 			done = 0;
815 		}
816 		spin_unlock_irq(&hostdata->lock);
817 		if (!done)
818 			cond_resched();
819 	} while (!done);
820 }
821 
822 /*
823  * NCR5380_dma_complete - finish DMA transfer
824  * @instance: the scsi host instance
825  *
826  * Called by the interrupt handler when DMA finishes or a phase
827  * mismatch occurs (which would end the DMA transfer).
828  */
829 
830 static void NCR5380_dma_complete(struct Scsi_Host *instance)
831 {
832 	struct NCR5380_hostdata *hostdata = shost_priv(instance);
833 	int transferred;
834 	unsigned char **data;
835 	int *count;
836 	int saved_data = 0, overrun = 0;
837 	unsigned char p;
838 
839 	if (hostdata->read_overruns) {
840 		p = hostdata->connected->SCp.phase;
841 		if (p & SR_IO) {
842 			udelay(10);
843 			if ((NCR5380_read(BUS_AND_STATUS_REG) &
844 			     (BASR_PHASE_MATCH | BASR_ACK)) ==
845 			    (BASR_PHASE_MATCH | BASR_ACK)) {
846 				saved_data = NCR5380_read(INPUT_DATA_REG);
847 				overrun = 1;
848 				dsprintk(NDEBUG_DMA, instance, "read overrun handled\n");
849 			}
850 		}
851 	}
852 
853 #ifdef CONFIG_SUN3
854 	if ((sun3scsi_dma_finish(rq_data_dir(hostdata->connected->request)))) {
855 		pr_err("scsi%d: overrun in UDC counter -- not prepared to deal with this!\n",
856 		       instance->host_no);
857 		BUG();
858 	}
859 
860 	if ((NCR5380_read(BUS_AND_STATUS_REG) & (BASR_PHASE_MATCH | BASR_ACK)) ==
861 	    (BASR_PHASE_MATCH | BASR_ACK)) {
862 		pr_err("scsi%d: BASR %02x\n", instance->host_no,
863 		       NCR5380_read(BUS_AND_STATUS_REG));
864 		pr_err("scsi%d: bus stuck in data phase -- probably a single byte overrun!\n",
865 		       instance->host_no);
866 		BUG();
867 	}
868 #endif
869 
870 	NCR5380_write(MODE_REG, MR_BASE);
871 	NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
872 	NCR5380_read(RESET_PARITY_INTERRUPT_REG);
873 
874 	transferred = hostdata->dma_len - NCR5380_dma_residual(instance);
875 	hostdata->dma_len = 0;
876 
877 	data = (unsigned char **)&hostdata->connected->SCp.ptr;
878 	count = &hostdata->connected->SCp.this_residual;
879 	*data += transferred;
880 	*count -= transferred;
881 
882 	if (hostdata->read_overruns) {
883 		int cnt, toPIO;
884 
885 		if ((NCR5380_read(STATUS_REG) & PHASE_MASK) == p && (p & SR_IO)) {
886 			cnt = toPIO = hostdata->read_overruns;
887 			if (overrun) {
888 				dsprintk(NDEBUG_DMA, instance,
889 				         "Got an input overrun, using saved byte\n");
890 				*(*data)++ = saved_data;
891 				(*count)--;
892 				cnt--;
893 				toPIO--;
894 			}
895 			if (toPIO > 0) {
896 				dsprintk(NDEBUG_DMA, instance,
897 				         "Doing %d byte PIO to 0x%p\n", cnt, *data);
898 				NCR5380_transfer_pio(instance, &p, &cnt, data);
899 				*count -= toPIO - cnt;
900 			}
901 		}
902 	}
903 }
904 
905 /**
906  * NCR5380_intr - generic NCR5380 irq handler
907  * @irq: interrupt number
908  * @dev_id: device info
909  *
910  * Handle interrupts, reestablishing I_T_L or I_T_L_Q nexuses
911  * from the disconnected queue, and restarting NCR5380_main()
912  * as required.
913  *
914  * The chip can assert IRQ in any of six different conditions. The IRQ flag
915  * is then cleared by reading the Reset Parity/Interrupt Register (RPIR).
916  * Three of these six conditions are latched in the Bus and Status Register:
917  * - End of DMA (cleared by ending DMA Mode)
918  * - Parity error (cleared by reading RPIR)
919  * - Loss of BSY (cleared by reading RPIR)
920  * Two conditions have flag bits that are not latched:
921  * - Bus phase mismatch (non-maskable in DMA Mode, cleared by ending DMA Mode)
922  * - Bus reset (non-maskable)
923  * The remaining condition has no flag bit at all:
924  * - Selection/reselection
925  *
926  * Hence, establishing the cause(s) of any interrupt is partly guesswork.
927  * In "The DP8490 and DP5380 Comparison Guide", National Semiconductor
928  * claimed that "the design of the [DP8490] interrupt logic ensures
929  * interrupts will not be lost (they can be on the DP5380)."
930  * The L5380/53C80 datasheet from LOGIC Devices has more details.
931  *
932  * Checking for bus reset by reading RST is futile because of interrupt
933  * latency, but a bus reset will reset chip logic. Checking for parity error
934  * is unnecessary because that interrupt is never enabled. A Loss of BSY
935  * condition will clear DMA Mode. We can tell when this occurs because the
936  * the Busy Monitor interrupt is enabled together with DMA Mode.
937  */
938 
939 static irqreturn_t __maybe_unused NCR5380_intr(int irq, void *dev_id)
940 {
941 	struct Scsi_Host *instance = dev_id;
942 	struct NCR5380_hostdata *hostdata = shost_priv(instance);
943 	int handled = 0;
944 	unsigned char basr;
945 	unsigned long flags;
946 
947 	spin_lock_irqsave(&hostdata->lock, flags);
948 
949 	basr = NCR5380_read(BUS_AND_STATUS_REG);
950 	if (basr & BASR_IRQ) {
951 		unsigned char mr = NCR5380_read(MODE_REG);
952 		unsigned char sr = NCR5380_read(STATUS_REG);
953 
954 		dsprintk(NDEBUG_INTR, instance, "IRQ %d, BASR 0x%02x, SR 0x%02x, MR 0x%02x\n",
955 		         irq, basr, sr, mr);
956 
957 		if ((mr & MR_DMA_MODE) || (mr & MR_MONITOR_BSY)) {
958 			/* Probably End of DMA, Phase Mismatch or Loss of BSY.
959 			 * We ack IRQ after clearing Mode Register. Workarounds
960 			 * for End of DMA errata need to happen in DMA Mode.
961 			 */
962 
963 			dsprintk(NDEBUG_INTR, instance, "interrupt in DMA mode\n");
964 
965 			if (hostdata->connected) {
966 				NCR5380_dma_complete(instance);
967 				queue_work(hostdata->work_q, &hostdata->main_task);
968 			} else {
969 				NCR5380_write(MODE_REG, MR_BASE);
970 				NCR5380_read(RESET_PARITY_INTERRUPT_REG);
971 			}
972 		} else if ((NCR5380_read(CURRENT_SCSI_DATA_REG) & hostdata->id_mask) &&
973 		    (sr & (SR_SEL | SR_IO | SR_BSY | SR_RST)) == (SR_SEL | SR_IO)) {
974 			/* Probably reselected */
975 			NCR5380_write(SELECT_ENABLE_REG, 0);
976 			NCR5380_read(RESET_PARITY_INTERRUPT_REG);
977 
978 			dsprintk(NDEBUG_INTR, instance, "interrupt with SEL and IO\n");
979 
980 			if (!hostdata->connected) {
981 				NCR5380_reselect(instance);
982 				queue_work(hostdata->work_q, &hostdata->main_task);
983 			}
984 			if (!hostdata->connected)
985 				NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
986 		} else {
987 			/* Probably Bus Reset */
988 			NCR5380_read(RESET_PARITY_INTERRUPT_REG);
989 
990 			dsprintk(NDEBUG_INTR, instance, "unknown interrupt\n");
991 #ifdef SUN3_SCSI_VME
992 			dregs->csr |= CSR_DMA_ENABLE;
993 #endif
994 		}
995 		handled = 1;
996 	} else {
997 		shost_printk(KERN_NOTICE, instance, "interrupt without IRQ bit\n");
998 #ifdef SUN3_SCSI_VME
999 		dregs->csr |= CSR_DMA_ENABLE;
1000 #endif
1001 	}
1002 
1003 	spin_unlock_irqrestore(&hostdata->lock, flags);
1004 
1005 	return IRQ_RETVAL(handled);
1006 }
1007 
1008 /*
1009  * Function : int NCR5380_select(struct Scsi_Host *instance,
1010  * struct scsi_cmnd *cmd)
1011  *
1012  * Purpose : establishes I_T_L or I_T_L_Q nexus for new or existing command,
1013  * including ARBITRATION, SELECTION, and initial message out for
1014  * IDENTIFY and queue messages.
1015  *
1016  * Inputs : instance - instantiation of the 5380 driver on which this
1017  * target lives, cmd - SCSI command to execute.
1018  *
1019  * Returns cmd if selection failed but should be retried,
1020  * NULL if selection failed and should not be retried, or
1021  * NULL if selection succeeded (hostdata->connected == cmd).
1022  *
1023  * Side effects :
1024  * If bus busy, arbitration failed, etc, NCR5380_select() will exit
1025  * with registers as they should have been on entry - ie
1026  * SELECT_ENABLE will be set appropriately, the NCR5380
1027  * will cease to drive any SCSI bus signals.
1028  *
1029  * If successful : I_T_L or I_T_L_Q nexus will be established,
1030  * instance->connected will be set to cmd.
1031  * SELECT interrupt will be disabled.
1032  *
1033  * If failed (no target) : cmd->scsi_done() will be called, and the
1034  * cmd->result host byte set to DID_BAD_TARGET.
1035  */
1036 
1037 static struct scsi_cmnd *NCR5380_select(struct Scsi_Host *instance,
1038                                         struct scsi_cmnd *cmd)
1039 {
1040 	struct NCR5380_hostdata *hostdata = shost_priv(instance);
1041 	unsigned char tmp[3], phase;
1042 	unsigned char *data;
1043 	int len;
1044 	int err;
1045 
1046 	NCR5380_dprint(NDEBUG_ARBITRATION, instance);
1047 	dsprintk(NDEBUG_ARBITRATION, instance, "starting arbitration, id = %d\n",
1048 	         instance->this_id);
1049 
1050 	/*
1051 	 * Arbitration and selection phases are slow and involve dropping the
1052 	 * lock, so we have to watch out for EH. An exception handler may
1053 	 * change 'selecting' to NULL. This function will then return NULL
1054 	 * so that the caller will forget about 'cmd'. (During information
1055 	 * transfer phases, EH may change 'connected' to NULL.)
1056 	 */
1057 	hostdata->selecting = cmd;
1058 
1059 	/*
1060 	 * Set the phase bits to 0, otherwise the NCR5380 won't drive the
1061 	 * data bus during SELECTION.
1062 	 */
1063 
1064 	NCR5380_write(TARGET_COMMAND_REG, 0);
1065 
1066 	/*
1067 	 * Start arbitration.
1068 	 */
1069 
1070 	NCR5380_write(OUTPUT_DATA_REG, hostdata->id_mask);
1071 	NCR5380_write(MODE_REG, MR_ARBITRATE);
1072 
1073 	/* The chip now waits for BUS FREE phase. Then after the 800 ns
1074 	 * Bus Free Delay, arbitration will begin.
1075 	 */
1076 
1077 	spin_unlock_irq(&hostdata->lock);
1078 	err = NCR5380_poll_politely2(instance, MODE_REG, MR_ARBITRATE, 0,
1079 	                INITIATOR_COMMAND_REG, ICR_ARBITRATION_PROGRESS,
1080 	                                       ICR_ARBITRATION_PROGRESS, HZ);
1081 	spin_lock_irq(&hostdata->lock);
1082 	if (!(NCR5380_read(MODE_REG) & MR_ARBITRATE)) {
1083 		/* Reselection interrupt */
1084 		goto out;
1085 	}
1086 	if (!hostdata->selecting) {
1087 		/* Command was aborted */
1088 		NCR5380_write(MODE_REG, MR_BASE);
1089 		goto out;
1090 	}
1091 	if (err < 0) {
1092 		NCR5380_write(MODE_REG, MR_BASE);
1093 		shost_printk(KERN_ERR, instance,
1094 		             "select: arbitration timeout\n");
1095 		goto out;
1096 	}
1097 	spin_unlock_irq(&hostdata->lock);
1098 
1099 	/* The SCSI-2 arbitration delay is 2.4 us */
1100 	udelay(3);
1101 
1102 	/* Check for lost arbitration */
1103 	if ((NCR5380_read(INITIATOR_COMMAND_REG) & ICR_ARBITRATION_LOST) ||
1104 	    (NCR5380_read(CURRENT_SCSI_DATA_REG) & hostdata->id_higher_mask) ||
1105 	    (NCR5380_read(INITIATOR_COMMAND_REG) & ICR_ARBITRATION_LOST)) {
1106 		NCR5380_write(MODE_REG, MR_BASE);
1107 		dsprintk(NDEBUG_ARBITRATION, instance, "lost arbitration, deasserting MR_ARBITRATE\n");
1108 		spin_lock_irq(&hostdata->lock);
1109 		goto out;
1110 	}
1111 
1112 	/* After/during arbitration, BSY should be asserted.
1113 	 * IBM DPES-31080 Version S31Q works now
1114 	 * Tnx to Thomas_Roesch@m2.maus.de for finding this! (Roman)
1115 	 */
1116 	NCR5380_write(INITIATOR_COMMAND_REG,
1117 		      ICR_BASE | ICR_ASSERT_SEL | ICR_ASSERT_BSY);
1118 
1119 	/*
1120 	 * Again, bus clear + bus settle time is 1.2us, however, this is
1121 	 * a minimum so we'll udelay ceil(1.2)
1122 	 */
1123 
1124 	if (hostdata->flags & FLAG_TOSHIBA_DELAY)
1125 		udelay(15);
1126 	else
1127 		udelay(2);
1128 
1129 	spin_lock_irq(&hostdata->lock);
1130 
1131 	/* NCR5380_reselect() clears MODE_REG after a reselection interrupt */
1132 	if (!(NCR5380_read(MODE_REG) & MR_ARBITRATE))
1133 		goto out;
1134 
1135 	if (!hostdata->selecting) {
1136 		NCR5380_write(MODE_REG, MR_BASE);
1137 		NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1138 		goto out;
1139 	}
1140 
1141 	dsprintk(NDEBUG_ARBITRATION, instance, "won arbitration\n");
1142 
1143 	/*
1144 	 * Now that we have won arbitration, start Selection process, asserting
1145 	 * the host and target ID's on the SCSI bus.
1146 	 */
1147 
1148 	NCR5380_write(OUTPUT_DATA_REG, hostdata->id_mask | (1 << scmd_id(cmd)));
1149 
1150 	/*
1151 	 * Raise ATN while SEL is true before BSY goes false from arbitration,
1152 	 * since this is the only way to guarantee that we'll get a MESSAGE OUT
1153 	 * phase immediately after selection.
1154 	 */
1155 
1156 	NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_BSY |
1157 	              ICR_ASSERT_DATA | ICR_ASSERT_ATN | ICR_ASSERT_SEL);
1158 	NCR5380_write(MODE_REG, MR_BASE);
1159 
1160 	/*
1161 	 * Reselect interrupts must be turned off prior to the dropping of BSY,
1162 	 * otherwise we will trigger an interrupt.
1163 	 */
1164 	NCR5380_write(SELECT_ENABLE_REG, 0);
1165 
1166 	spin_unlock_irq(&hostdata->lock);
1167 
1168 	/*
1169 	 * The initiator shall then wait at least two deskew delays and release
1170 	 * the BSY signal.
1171 	 */
1172 	udelay(1);        /* wingel -- wait two bus deskew delay >2*45ns */
1173 
1174 	/* Reset BSY */
1175 	NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_DATA |
1176 	              ICR_ASSERT_ATN | ICR_ASSERT_SEL);
1177 
1178 	/*
1179 	 * Something weird happens when we cease to drive BSY - looks
1180 	 * like the board/chip is letting us do another read before the
1181 	 * appropriate propagation delay has expired, and we're confusing
1182 	 * a BSY signal from ourselves as the target's response to SELECTION.
1183 	 *
1184 	 * A small delay (the 'C++' frontend breaks the pipeline with an
1185 	 * unnecessary jump, making it work on my 386-33/Trantor T128, the
1186 	 * tighter 'C' code breaks and requires this) solves the problem -
1187 	 * the 1 us delay is arbitrary, and only used because this delay will
1188 	 * be the same on other platforms and since it works here, it should
1189 	 * work there.
1190 	 *
1191 	 * wingel suggests that this could be due to failing to wait
1192 	 * one deskew delay.
1193 	 */
1194 
1195 	udelay(1);
1196 
1197 	dsprintk(NDEBUG_SELECTION, instance, "selecting target %d\n", scmd_id(cmd));
1198 
1199 	/*
1200 	 * The SCSI specification calls for a 250 ms timeout for the actual
1201 	 * selection.
1202 	 */
1203 
1204 	err = NCR5380_poll_politely(instance, STATUS_REG, SR_BSY, SR_BSY,
1205 	                            msecs_to_jiffies(250));
1206 
1207 	if ((NCR5380_read(STATUS_REG) & (SR_SEL | SR_IO)) == (SR_SEL | SR_IO)) {
1208 		spin_lock_irq(&hostdata->lock);
1209 		NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1210 		NCR5380_reselect(instance);
1211 		if (!hostdata->connected)
1212 			NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
1213 		shost_printk(KERN_ERR, instance, "reselection after won arbitration?\n");
1214 		goto out;
1215 	}
1216 
1217 	if (err < 0) {
1218 		spin_lock_irq(&hostdata->lock);
1219 		NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1220 		NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
1221 		/* Can't touch cmd if it has been reclaimed by the scsi ML */
1222 		if (hostdata->selecting) {
1223 			cmd->result = DID_BAD_TARGET << 16;
1224 			complete_cmd(instance, cmd);
1225 			dsprintk(NDEBUG_SELECTION, instance, "target did not respond within 250ms\n");
1226 			cmd = NULL;
1227 		}
1228 		goto out;
1229 	}
1230 
1231 	/*
1232 	 * No less than two deskew delays after the initiator detects the
1233 	 * BSY signal is true, it shall release the SEL signal and may
1234 	 * change the DATA BUS.                                     -wingel
1235 	 */
1236 
1237 	udelay(1);
1238 
1239 	NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN);
1240 
1241 	/*
1242 	 * Since we followed the SCSI spec, and raised ATN while SEL
1243 	 * was true but before BSY was false during selection, the information
1244 	 * transfer phase should be a MESSAGE OUT phase so that we can send the
1245 	 * IDENTIFY message.
1246 	 */
1247 
1248 	/* Wait for start of REQ/ACK handshake */
1249 
1250 	err = NCR5380_poll_politely(instance, STATUS_REG, SR_REQ, SR_REQ, HZ);
1251 	spin_lock_irq(&hostdata->lock);
1252 	if (err < 0) {
1253 		shost_printk(KERN_ERR, instance, "select: REQ timeout\n");
1254 		NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1255 		NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
1256 		goto out;
1257 	}
1258 	if (!hostdata->selecting) {
1259 		do_abort(instance);
1260 		goto out;
1261 	}
1262 
1263 	dsprintk(NDEBUG_SELECTION, instance, "target %d selected, going into MESSAGE OUT phase.\n",
1264 	         scmd_id(cmd));
1265 	tmp[0] = IDENTIFY(((instance->irq == NO_IRQ) ? 0 : 1), cmd->device->lun);
1266 
1267 	len = 1;
1268 	data = tmp;
1269 	phase = PHASE_MSGOUT;
1270 	NCR5380_transfer_pio(instance, &phase, &len, &data);
1271 	dsprintk(NDEBUG_SELECTION, instance, "nexus established.\n");
1272 	/* XXX need to handle errors here */
1273 
1274 	hostdata->connected = cmd;
1275 	hostdata->busy[cmd->device->id] |= 1 << cmd->device->lun;
1276 
1277 #ifdef SUN3_SCSI_VME
1278 	dregs->csr |= CSR_INTR;
1279 #endif
1280 
1281 	initialize_SCp(cmd);
1282 
1283 	cmd = NULL;
1284 
1285 out:
1286 	if (!hostdata->selecting)
1287 		return NULL;
1288 	hostdata->selecting = NULL;
1289 	return cmd;
1290 }
1291 
1292 /*
1293  * Function : int NCR5380_transfer_pio (struct Scsi_Host *instance,
1294  * unsigned char *phase, int *count, unsigned char **data)
1295  *
1296  * Purpose : transfers data in given phase using polled I/O
1297  *
1298  * Inputs : instance - instance of driver, *phase - pointer to
1299  * what phase is expected, *count - pointer to number of
1300  * bytes to transfer, **data - pointer to data pointer.
1301  *
1302  * Returns : -1 when different phase is entered without transferring
1303  * maximum number of bytes, 0 if all bytes are transferred or exit
1304  * is in same phase.
1305  *
1306  * Also, *phase, *count, *data are modified in place.
1307  *
1308  * XXX Note : handling for bus free may be useful.
1309  */
1310 
1311 /*
1312  * Note : this code is not as quick as it could be, however it
1313  * IS 100% reliable, and for the actual data transfer where speed
1314  * counts, we will always do a pseudo DMA or DMA transfer.
1315  */
1316 
1317 static int NCR5380_transfer_pio(struct Scsi_Host *instance,
1318 				unsigned char *phase, int *count,
1319 				unsigned char **data)
1320 {
1321 	unsigned char p = *phase, tmp;
1322 	int c = *count;
1323 	unsigned char *d = *data;
1324 
1325 	/*
1326 	 * The NCR5380 chip will only drive the SCSI bus when the
1327 	 * phase specified in the appropriate bits of the TARGET COMMAND
1328 	 * REGISTER match the STATUS REGISTER
1329 	 */
1330 
1331 	NCR5380_write(TARGET_COMMAND_REG, PHASE_SR_TO_TCR(p));
1332 
1333 	do {
1334 		/*
1335 		 * Wait for assertion of REQ, after which the phase bits will be
1336 		 * valid
1337 		 */
1338 
1339 		if (NCR5380_poll_politely(instance, STATUS_REG, SR_REQ, SR_REQ, HZ) < 0)
1340 			break;
1341 
1342 		dsprintk(NDEBUG_HANDSHAKE, instance, "REQ asserted\n");
1343 
1344 		/* Check for phase mismatch */
1345 		if ((NCR5380_read(STATUS_REG) & PHASE_MASK) != p) {
1346 			dsprintk(NDEBUG_PIO, instance, "phase mismatch\n");
1347 			NCR5380_dprint_phase(NDEBUG_PIO, instance);
1348 			break;
1349 		}
1350 
1351 		/* Do actual transfer from SCSI bus to / from memory */
1352 		if (!(p & SR_IO))
1353 			NCR5380_write(OUTPUT_DATA_REG, *d);
1354 		else
1355 			*d = NCR5380_read(CURRENT_SCSI_DATA_REG);
1356 
1357 		++d;
1358 
1359 		/*
1360 		 * The SCSI standard suggests that in MSGOUT phase, the initiator
1361 		 * should drop ATN on the last byte of the message phase
1362 		 * after REQ has been asserted for the handshake but before
1363 		 * the initiator raises ACK.
1364 		 */
1365 
1366 		if (!(p & SR_IO)) {
1367 			if (!((p & SR_MSG) && c > 1)) {
1368 				NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_DATA);
1369 				NCR5380_dprint(NDEBUG_PIO, instance);
1370 				NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE |
1371 				              ICR_ASSERT_DATA | ICR_ASSERT_ACK);
1372 			} else {
1373 				NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE |
1374 				              ICR_ASSERT_DATA | ICR_ASSERT_ATN);
1375 				NCR5380_dprint(NDEBUG_PIO, instance);
1376 				NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE |
1377 				              ICR_ASSERT_DATA | ICR_ASSERT_ATN | ICR_ASSERT_ACK);
1378 			}
1379 		} else {
1380 			NCR5380_dprint(NDEBUG_PIO, instance);
1381 			NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ACK);
1382 		}
1383 
1384 		if (NCR5380_poll_politely(instance,
1385 		                          STATUS_REG, SR_REQ, 0, 5 * HZ) < 0)
1386 			break;
1387 
1388 		dsprintk(NDEBUG_HANDSHAKE, instance, "REQ negated, handshake complete\n");
1389 
1390 /*
1391  * We have several special cases to consider during REQ/ACK handshaking :
1392  * 1.  We were in MSGOUT phase, and we are on the last byte of the
1393  * message.  ATN must be dropped as ACK is dropped.
1394  *
1395  * 2.  We are in a MSGIN phase, and we are on the last byte of the
1396  * message.  We must exit with ACK asserted, so that the calling
1397  * code may raise ATN before dropping ACK to reject the message.
1398  *
1399  * 3.  ACK and ATN are clear and the target may proceed as normal.
1400  */
1401 		if (!(p == PHASE_MSGIN && c == 1)) {
1402 			if (p == PHASE_MSGOUT && c > 1)
1403 				NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN);
1404 			else
1405 				NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1406 		}
1407 	} while (--c);
1408 
1409 	dsprintk(NDEBUG_PIO, instance, "residual %d\n", c);
1410 
1411 	*count = c;
1412 	*data = d;
1413 	tmp = NCR5380_read(STATUS_REG);
1414 	/* The phase read from the bus is valid if either REQ is (already)
1415 	 * asserted or if ACK hasn't been released yet. The latter applies if
1416 	 * we're in MSG IN, DATA IN or STATUS and all bytes have been received.
1417 	 */
1418 	if ((tmp & SR_REQ) || ((tmp & SR_IO) && c == 0))
1419 		*phase = tmp & PHASE_MASK;
1420 	else
1421 		*phase = PHASE_UNKNOWN;
1422 
1423 	if (!c || (*phase == p))
1424 		return 0;
1425 	else
1426 		return -1;
1427 }
1428 
1429 /**
1430  * do_reset - issue a reset command
1431  * @instance: adapter to reset
1432  *
1433  * Issue a reset sequence to the NCR5380 and try and get the bus
1434  * back into sane shape.
1435  *
1436  * This clears the reset interrupt flag because there may be no handler for
1437  * it. When the driver is initialized, the NCR5380_intr() handler has not yet
1438  * been installed. And when in EH we may have released the ST DMA interrupt.
1439  */
1440 
1441 static void do_reset(struct Scsi_Host *instance)
1442 {
1443 	unsigned long flags;
1444 
1445 	local_irq_save(flags);
1446 	NCR5380_write(TARGET_COMMAND_REG,
1447 	              PHASE_SR_TO_TCR(NCR5380_read(STATUS_REG) & PHASE_MASK));
1448 	NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_RST);
1449 	udelay(50);
1450 	NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1451 	(void)NCR5380_read(RESET_PARITY_INTERRUPT_REG);
1452 	local_irq_restore(flags);
1453 }
1454 
1455 /**
1456  * do_abort - abort the currently established nexus by going to
1457  * MESSAGE OUT phase and sending an ABORT message.
1458  * @instance: relevant scsi host instance
1459  *
1460  * Returns 0 on success, -1 on failure.
1461  */
1462 
1463 static int do_abort(struct Scsi_Host *instance)
1464 {
1465 	unsigned char *msgptr, phase, tmp;
1466 	int len;
1467 	int rc;
1468 
1469 	/* Request message out phase */
1470 	NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN);
1471 
1472 	/*
1473 	 * Wait for the target to indicate a valid phase by asserting
1474 	 * REQ.  Once this happens, we'll have either a MSGOUT phase
1475 	 * and can immediately send the ABORT message, or we'll have some
1476 	 * other phase and will have to source/sink data.
1477 	 *
1478 	 * We really don't care what value was on the bus or what value
1479 	 * the target sees, so we just handshake.
1480 	 */
1481 
1482 	rc = NCR5380_poll_politely(instance, STATUS_REG, SR_REQ, SR_REQ, 10 * HZ);
1483 	if (rc < 0)
1484 		goto timeout;
1485 
1486 	tmp = NCR5380_read(STATUS_REG) & PHASE_MASK;
1487 
1488 	NCR5380_write(TARGET_COMMAND_REG, PHASE_SR_TO_TCR(tmp));
1489 
1490 	if (tmp != PHASE_MSGOUT) {
1491 		NCR5380_write(INITIATOR_COMMAND_REG,
1492 		              ICR_BASE | ICR_ASSERT_ATN | ICR_ASSERT_ACK);
1493 		rc = NCR5380_poll_politely(instance, STATUS_REG, SR_REQ, 0, 3 * HZ);
1494 		if (rc < 0)
1495 			goto timeout;
1496 		NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN);
1497 	}
1498 
1499 	tmp = ABORT;
1500 	msgptr = &tmp;
1501 	len = 1;
1502 	phase = PHASE_MSGOUT;
1503 	NCR5380_transfer_pio(instance, &phase, &len, &msgptr);
1504 
1505 	/*
1506 	 * If we got here, and the command completed successfully,
1507 	 * we're about to go into bus free state.
1508 	 */
1509 
1510 	return len ? -1 : 0;
1511 
1512 timeout:
1513 	NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1514 	return -1;
1515 }
1516 
1517 /*
1518  * Function : int NCR5380_transfer_dma (struct Scsi_Host *instance,
1519  * unsigned char *phase, int *count, unsigned char **data)
1520  *
1521  * Purpose : transfers data in given phase using either real
1522  * or pseudo DMA.
1523  *
1524  * Inputs : instance - instance of driver, *phase - pointer to
1525  * what phase is expected, *count - pointer to number of
1526  * bytes to transfer, **data - pointer to data pointer.
1527  *
1528  * Returns : -1 when different phase is entered without transferring
1529  * maximum number of bytes, 0 if all bytes or transferred or exit
1530  * is in same phase.
1531  *
1532  * Also, *phase, *count, *data are modified in place.
1533  */
1534 
1535 
1536 static int NCR5380_transfer_dma(struct Scsi_Host *instance,
1537 				unsigned char *phase, int *count,
1538 				unsigned char **data)
1539 {
1540 	struct NCR5380_hostdata *hostdata = shost_priv(instance);
1541 	int c = *count;
1542 	unsigned char p = *phase;
1543 	unsigned char *d = *data;
1544 	unsigned char tmp;
1545 	int result = 0;
1546 
1547 	if ((tmp = (NCR5380_read(STATUS_REG) & PHASE_MASK)) != p) {
1548 		*phase = tmp;
1549 		return -1;
1550 	}
1551 
1552 	hostdata->connected->SCp.phase = p;
1553 
1554 	if (p & SR_IO) {
1555 		if (hostdata->read_overruns)
1556 			c -= hostdata->read_overruns;
1557 		else if (hostdata->flags & FLAG_DMA_FIXUP)
1558 			--c;
1559 	}
1560 
1561 	dsprintk(NDEBUG_DMA, instance, "initializing DMA %s: length %d, address %p\n",
1562 	         (p & SR_IO) ? "receive" : "send", c, d);
1563 
1564 #ifdef CONFIG_SUN3
1565 	/* send start chain */
1566 	sun3scsi_dma_start(c, *data);
1567 #endif
1568 
1569 	NCR5380_write(TARGET_COMMAND_REG, PHASE_SR_TO_TCR(p));
1570 	NCR5380_write(MODE_REG, MR_BASE | MR_DMA_MODE | MR_MONITOR_BSY |
1571 	                        MR_ENABLE_EOP_INTR);
1572 
1573 	if (!(hostdata->flags & FLAG_LATE_DMA_SETUP)) {
1574 		/* On the Medusa, it is a must to initialize the DMA before
1575 		 * starting the NCR. This is also the cleaner way for the TT.
1576 		 */
1577 		if (p & SR_IO)
1578 			result = NCR5380_dma_recv_setup(instance, d, c);
1579 		else
1580 			result = NCR5380_dma_send_setup(instance, d, c);
1581 	}
1582 
1583 	/*
1584 	 * On the PAS16 at least I/O recovery delays are not needed here.
1585 	 * Everyone else seems to want them.
1586 	 */
1587 
1588 	if (p & SR_IO) {
1589 		NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1590 		NCR5380_io_delay(1);
1591 		NCR5380_write(START_DMA_INITIATOR_RECEIVE_REG, 0);
1592 	} else {
1593 		NCR5380_io_delay(1);
1594 		NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_DATA);
1595 		NCR5380_io_delay(1);
1596 		NCR5380_write(START_DMA_SEND_REG, 0);
1597 		NCR5380_io_delay(1);
1598 	}
1599 
1600 #ifdef CONFIG_SUN3
1601 #ifdef SUN3_SCSI_VME
1602 	dregs->csr |= CSR_DMA_ENABLE;
1603 #endif
1604 	sun3_dma_active = 1;
1605 #endif
1606 
1607 	if (hostdata->flags & FLAG_LATE_DMA_SETUP) {
1608 		/* On the Falcon, the DMA setup must be done after the last
1609 		 * NCR access, else the DMA setup gets trashed!
1610 		 */
1611 		if (p & SR_IO)
1612 			result = NCR5380_dma_recv_setup(instance, d, c);
1613 		else
1614 			result = NCR5380_dma_send_setup(instance, d, c);
1615 	}
1616 
1617 	/* On failure, NCR5380_dma_xxxx_setup() returns a negative int. */
1618 	if (result < 0)
1619 		return result;
1620 
1621 	/* For real DMA, result is the byte count. DMA interrupt is expected. */
1622 	if (result > 0) {
1623 		hostdata->dma_len = result;
1624 		return 0;
1625 	}
1626 
1627 	/* The result is zero iff pseudo DMA send/receive was completed. */
1628 	hostdata->dma_len = c;
1629 
1630 /*
1631  * A note regarding the DMA errata workarounds for early NMOS silicon.
1632  *
1633  * For DMA sends, we want to wait until the last byte has been
1634  * transferred out over the bus before we turn off DMA mode.  Alas, there
1635  * seems to be no terribly good way of doing this on a 5380 under all
1636  * conditions.  For non-scatter-gather operations, we can wait until REQ
1637  * and ACK both go false, or until a phase mismatch occurs.  Gather-sends
1638  * are nastier, since the device will be expecting more data than we
1639  * are prepared to send it, and REQ will remain asserted.  On a 53C8[01] we
1640  * could test Last Byte Sent to assure transfer (I imagine this is precisely
1641  * why this signal was added to the newer chips) but on the older 538[01]
1642  * this signal does not exist.  The workaround for this lack is a watchdog;
1643  * we bail out of the wait-loop after a modest amount of wait-time if
1644  * the usual exit conditions are not met.  Not a terribly clean or
1645  * correct solution :-%
1646  *
1647  * DMA receive is equally tricky due to a nasty characteristic of the NCR5380.
1648  * If the chip is in DMA receive mode, it will respond to a target's
1649  * REQ by latching the SCSI data into the INPUT DATA register and asserting
1650  * ACK, even if it has _already_ been notified by the DMA controller that
1651  * the current DMA transfer has completed!  If the NCR5380 is then taken
1652  * out of DMA mode, this already-acknowledged byte is lost. This is
1653  * not a problem for "one DMA transfer per READ command", because
1654  * the situation will never arise... either all of the data is DMA'ed
1655  * properly, or the target switches to MESSAGE IN phase to signal a
1656  * disconnection (either operation bringing the DMA to a clean halt).
1657  * However, in order to handle scatter-receive, we must work around the
1658  * problem.  The chosen fix is to DMA fewer bytes, then check for the
1659  * condition before taking the NCR5380 out of DMA mode.  One or two extra
1660  * bytes are transferred via PIO as necessary to fill out the original
1661  * request.
1662  */
1663 
1664 	if (hostdata->flags & FLAG_DMA_FIXUP) {
1665 		if (p & SR_IO) {
1666 			/*
1667 			 * The workaround was to transfer fewer bytes than we
1668 			 * intended to with the pseudo-DMA read function, wait for
1669 			 * the chip to latch the last byte, read it, and then disable
1670 			 * pseudo-DMA mode.
1671 			 *
1672 			 * After REQ is asserted, the NCR5380 asserts DRQ and ACK.
1673 			 * REQ is deasserted when ACK is asserted, and not reasserted
1674 			 * until ACK goes false.  Since the NCR5380 won't lower ACK
1675 			 * until DACK is asserted, which won't happen unless we twiddle
1676 			 * the DMA port or we take the NCR5380 out of DMA mode, we
1677 			 * can guarantee that we won't handshake another extra
1678 			 * byte.
1679 			 */
1680 
1681 			if (NCR5380_poll_politely(instance, BUS_AND_STATUS_REG,
1682 			                          BASR_DRQ, BASR_DRQ, HZ) < 0) {
1683 				result = -1;
1684 				shost_printk(KERN_ERR, instance, "PDMA read: DRQ timeout\n");
1685 			}
1686 			if (NCR5380_poll_politely(instance, STATUS_REG,
1687 			                          SR_REQ, 0, HZ) < 0) {
1688 				result = -1;
1689 				shost_printk(KERN_ERR, instance, "PDMA read: !REQ timeout\n");
1690 			}
1691 			d[*count - 1] = NCR5380_read(INPUT_DATA_REG);
1692 		} else {
1693 			/*
1694 			 * Wait for the last byte to be sent.  If REQ is being asserted for
1695 			 * the byte we're interested, we'll ACK it and it will go false.
1696 			 */
1697 			if (NCR5380_poll_politely2(instance,
1698 			     BUS_AND_STATUS_REG, BASR_DRQ, BASR_DRQ,
1699 			     BUS_AND_STATUS_REG, BASR_PHASE_MATCH, 0, HZ) < 0) {
1700 				result = -1;
1701 				shost_printk(KERN_ERR, instance, "PDMA write: DRQ and phase timeout\n");
1702 			}
1703 		}
1704 	}
1705 
1706 	NCR5380_dma_complete(instance);
1707 	return result;
1708 }
1709 
1710 /*
1711  * Function : NCR5380_information_transfer (struct Scsi_Host *instance)
1712  *
1713  * Purpose : run through the various SCSI phases and do as the target
1714  * directs us to.  Operates on the currently connected command,
1715  * instance->connected.
1716  *
1717  * Inputs : instance, instance for which we are doing commands
1718  *
1719  * Side effects : SCSI things happen, the disconnected queue will be
1720  * modified if a command disconnects, *instance->connected will
1721  * change.
1722  *
1723  * XXX Note : we need to watch for bus free or a reset condition here
1724  * to recover from an unexpected bus free condition.
1725  */
1726 
1727 static void NCR5380_information_transfer(struct Scsi_Host *instance)
1728 {
1729 	struct NCR5380_hostdata *hostdata = shost_priv(instance);
1730 	unsigned char msgout = NOP;
1731 	int sink = 0;
1732 	int len;
1733 	int transfersize;
1734 	unsigned char *data;
1735 	unsigned char phase, tmp, extended_msg[10], old_phase = 0xff;
1736 	struct scsi_cmnd *cmd;
1737 
1738 #ifdef SUN3_SCSI_VME
1739 	dregs->csr |= CSR_INTR;
1740 #endif
1741 
1742 	while ((cmd = hostdata->connected)) {
1743 		struct NCR5380_cmd *ncmd = scsi_cmd_priv(cmd);
1744 
1745 		tmp = NCR5380_read(STATUS_REG);
1746 		/* We only have a valid SCSI phase when REQ is asserted */
1747 		if (tmp & SR_REQ) {
1748 			phase = (tmp & PHASE_MASK);
1749 			if (phase != old_phase) {
1750 				old_phase = phase;
1751 				NCR5380_dprint_phase(NDEBUG_INFORMATION, instance);
1752 			}
1753 #ifdef CONFIG_SUN3
1754 			if (phase == PHASE_CMDOUT) {
1755 				void *d;
1756 				unsigned long count;
1757 
1758 				if (!cmd->SCp.this_residual && cmd->SCp.buffers_residual) {
1759 					count = cmd->SCp.buffer->length;
1760 					d = sg_virt(cmd->SCp.buffer);
1761 				} else {
1762 					count = cmd->SCp.this_residual;
1763 					d = cmd->SCp.ptr;
1764 				}
1765 
1766 				if (sun3_dma_setup_done != cmd &&
1767 				    sun3scsi_dma_xfer_len(count, cmd) > 0) {
1768 					sun3scsi_dma_setup(instance, d, count,
1769 					                   rq_data_dir(cmd->request));
1770 					sun3_dma_setup_done = cmd;
1771 				}
1772 #ifdef SUN3_SCSI_VME
1773 				dregs->csr |= CSR_INTR;
1774 #endif
1775 			}
1776 #endif /* CONFIG_SUN3 */
1777 
1778 			if (sink && (phase != PHASE_MSGOUT)) {
1779 				NCR5380_write(TARGET_COMMAND_REG, PHASE_SR_TO_TCR(tmp));
1780 
1781 				NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN |
1782 				              ICR_ASSERT_ACK);
1783 				while (NCR5380_read(STATUS_REG) & SR_REQ)
1784 					;
1785 				NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE |
1786 				              ICR_ASSERT_ATN);
1787 				sink = 0;
1788 				continue;
1789 			}
1790 
1791 			switch (phase) {
1792 			case PHASE_DATAOUT:
1793 #if (NDEBUG & NDEBUG_NO_DATAOUT)
1794 				shost_printk(KERN_DEBUG, instance, "NDEBUG_NO_DATAOUT set, attempted DATAOUT aborted\n");
1795 				sink = 1;
1796 				do_abort(instance);
1797 				cmd->result = DID_ERROR << 16;
1798 				complete_cmd(instance, cmd);
1799 				hostdata->connected = NULL;
1800 				return;
1801 #endif
1802 			case PHASE_DATAIN:
1803 				/*
1804 				 * If there is no room left in the current buffer in the
1805 				 * scatter-gather list, move onto the next one.
1806 				 */
1807 
1808 				if (!cmd->SCp.this_residual && cmd->SCp.buffers_residual) {
1809 					++cmd->SCp.buffer;
1810 					--cmd->SCp.buffers_residual;
1811 					cmd->SCp.this_residual = cmd->SCp.buffer->length;
1812 					cmd->SCp.ptr = sg_virt(cmd->SCp.buffer);
1813 					dsprintk(NDEBUG_INFORMATION, instance, "%d bytes and %d buffers left\n",
1814 					         cmd->SCp.this_residual,
1815 					         cmd->SCp.buffers_residual);
1816 				}
1817 
1818 				/*
1819 				 * The preferred transfer method is going to be
1820 				 * PSEUDO-DMA for systems that are strictly PIO,
1821 				 * since we can let the hardware do the handshaking.
1822 				 *
1823 				 * For this to work, we need to know the transfersize
1824 				 * ahead of time, since the pseudo-DMA code will sit
1825 				 * in an unconditional loop.
1826 				 */
1827 
1828 				transfersize = 0;
1829 				if (!cmd->device->borken)
1830 					transfersize = NCR5380_dma_xfer_len(instance, cmd, phase);
1831 
1832 				if (transfersize > 0) {
1833 					len = transfersize;
1834 					if (NCR5380_transfer_dma(instance, &phase,
1835 					    &len, (unsigned char **)&cmd->SCp.ptr)) {
1836 						/*
1837 						 * If the watchdog timer fires, all future
1838 						 * accesses to this device will use the
1839 						 * polled-IO.
1840 						 */
1841 						scmd_printk(KERN_INFO, cmd,
1842 							"switching to slow handshake\n");
1843 						cmd->device->borken = 1;
1844 						sink = 1;
1845 						do_abort(instance);
1846 						cmd->result = DID_ERROR << 16;
1847 						/* XXX - need to source or sink data here, as appropriate */
1848 					}
1849 				} else {
1850 					/* Transfer a small chunk so that the
1851 					 * irq mode lock is not held too long.
1852 					 */
1853 					transfersize = min(cmd->SCp.this_residual,
1854 							   NCR5380_PIO_CHUNK_SIZE);
1855 					len = transfersize;
1856 					NCR5380_transfer_pio(instance, &phase, &len,
1857 					                     (unsigned char **)&cmd->SCp.ptr);
1858 					cmd->SCp.this_residual -= transfersize - len;
1859 				}
1860 #ifdef CONFIG_SUN3
1861 				if (sun3_dma_setup_done == cmd)
1862 					sun3_dma_setup_done = NULL;
1863 #endif
1864 				return;
1865 			case PHASE_MSGIN:
1866 				len = 1;
1867 				data = &tmp;
1868 				NCR5380_transfer_pio(instance, &phase, &len, &data);
1869 				cmd->SCp.Message = tmp;
1870 
1871 				switch (tmp) {
1872 				case ABORT:
1873 				case COMMAND_COMPLETE:
1874 					/* Accept message by clearing ACK */
1875 					sink = 1;
1876 					NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1877 					dsprintk(NDEBUG_QUEUES, instance,
1878 					         "COMMAND COMPLETE %p target %d lun %llu\n",
1879 					         cmd, scmd_id(cmd), cmd->device->lun);
1880 
1881 					hostdata->connected = NULL;
1882 
1883 					cmd->result &= ~0xffff;
1884 					cmd->result |= cmd->SCp.Status;
1885 					cmd->result |= cmd->SCp.Message << 8;
1886 
1887 					if (cmd->cmnd[0] == REQUEST_SENSE)
1888 						complete_cmd(instance, cmd);
1889 					else {
1890 						if (cmd->SCp.Status == SAM_STAT_CHECK_CONDITION ||
1891 						    cmd->SCp.Status == SAM_STAT_COMMAND_TERMINATED) {
1892 							dsprintk(NDEBUG_QUEUES, instance, "autosense: adding cmd %p to tail of autosense queue\n",
1893 							         cmd);
1894 							list_add_tail(&ncmd->list,
1895 							              &hostdata->autosense);
1896 						} else
1897 							complete_cmd(instance, cmd);
1898 					}
1899 
1900 					/*
1901 					 * Restore phase bits to 0 so an interrupted selection,
1902 					 * arbitration can resume.
1903 					 */
1904 					NCR5380_write(TARGET_COMMAND_REG, 0);
1905 
1906 					/* Enable reselect interrupts */
1907 					NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
1908 
1909 					maybe_release_dma_irq(instance);
1910 					return;
1911 				case MESSAGE_REJECT:
1912 					/* Accept message by clearing ACK */
1913 					NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1914 					switch (hostdata->last_message) {
1915 					case HEAD_OF_QUEUE_TAG:
1916 					case ORDERED_QUEUE_TAG:
1917 					case SIMPLE_QUEUE_TAG:
1918 						cmd->device->simple_tags = 0;
1919 						hostdata->busy[cmd->device->id] |= (1 << (cmd->device->lun & 0xFF));
1920 						break;
1921 					default:
1922 						break;
1923 					}
1924 					break;
1925 				case DISCONNECT:
1926 					/* Accept message by clearing ACK */
1927 					NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1928 					hostdata->connected = NULL;
1929 					list_add(&ncmd->list, &hostdata->disconnected);
1930 					dsprintk(NDEBUG_INFORMATION | NDEBUG_QUEUES,
1931 					         instance, "connected command %p for target %d lun %llu moved to disconnected queue\n",
1932 					         cmd, scmd_id(cmd), cmd->device->lun);
1933 
1934 					/*
1935 					 * Restore phase bits to 0 so an interrupted selection,
1936 					 * arbitration can resume.
1937 					 */
1938 					NCR5380_write(TARGET_COMMAND_REG, 0);
1939 
1940 					/* Enable reselect interrupts */
1941 					NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
1942 #ifdef SUN3_SCSI_VME
1943 					dregs->csr |= CSR_DMA_ENABLE;
1944 #endif
1945 					return;
1946 					/*
1947 					 * The SCSI data pointer is *IMPLICITLY* saved on a disconnect
1948 					 * operation, in violation of the SCSI spec so we can safely
1949 					 * ignore SAVE/RESTORE pointers calls.
1950 					 *
1951 					 * Unfortunately, some disks violate the SCSI spec and
1952 					 * don't issue the required SAVE_POINTERS message before
1953 					 * disconnecting, and we have to break spec to remain
1954 					 * compatible.
1955 					 */
1956 				case SAVE_POINTERS:
1957 				case RESTORE_POINTERS:
1958 					/* Accept message by clearing ACK */
1959 					NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1960 					break;
1961 				case EXTENDED_MESSAGE:
1962 					/*
1963 					 * Start the message buffer with the EXTENDED_MESSAGE
1964 					 * byte, since spi_print_msg() wants the whole thing.
1965 					 */
1966 					extended_msg[0] = EXTENDED_MESSAGE;
1967 					/* Accept first byte by clearing ACK */
1968 					NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1969 
1970 					spin_unlock_irq(&hostdata->lock);
1971 
1972 					dsprintk(NDEBUG_EXTENDED, instance, "receiving extended message\n");
1973 
1974 					len = 2;
1975 					data = extended_msg + 1;
1976 					phase = PHASE_MSGIN;
1977 					NCR5380_transfer_pio(instance, &phase, &len, &data);
1978 					dsprintk(NDEBUG_EXTENDED, instance, "length %d, code 0x%02x\n",
1979 					         (int)extended_msg[1],
1980 					         (int)extended_msg[2]);
1981 
1982 					if (!len && extended_msg[1] > 0 &&
1983 					    extended_msg[1] <= sizeof(extended_msg) - 2) {
1984 						/* Accept third byte by clearing ACK */
1985 						NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
1986 						len = extended_msg[1] - 1;
1987 						data = extended_msg + 3;
1988 						phase = PHASE_MSGIN;
1989 
1990 						NCR5380_transfer_pio(instance, &phase, &len, &data);
1991 						dsprintk(NDEBUG_EXTENDED, instance, "message received, residual %d\n",
1992 						         len);
1993 
1994 						switch (extended_msg[2]) {
1995 						case EXTENDED_SDTR:
1996 						case EXTENDED_WDTR:
1997 						case EXTENDED_MODIFY_DATA_POINTER:
1998 						case EXTENDED_EXTENDED_IDENTIFY:
1999 							tmp = 0;
2000 						}
2001 					} else if (len) {
2002 						shost_printk(KERN_ERR, instance, "error receiving extended message\n");
2003 						tmp = 0;
2004 					} else {
2005 						shost_printk(KERN_NOTICE, instance, "extended message code %02x length %d is too long\n",
2006 						             extended_msg[2], extended_msg[1]);
2007 						tmp = 0;
2008 					}
2009 
2010 					spin_lock_irq(&hostdata->lock);
2011 					if (!hostdata->connected)
2012 						return;
2013 
2014 					/* Fall through to reject message */
2015 
2016 					/*
2017 					 * If we get something weird that we aren't expecting,
2018 					 * reject it.
2019 					 */
2020 				default:
2021 					if (!tmp) {
2022 						shost_printk(KERN_ERR, instance, "rejecting message ");
2023 						spi_print_msg(extended_msg);
2024 						printk("\n");
2025 					} else if (tmp != EXTENDED_MESSAGE)
2026 						scmd_printk(KERN_INFO, cmd,
2027 						            "rejecting unknown message %02x\n",
2028 						            tmp);
2029 					else
2030 						scmd_printk(KERN_INFO, cmd,
2031 						            "rejecting unknown extended message code %02x, length %d\n",
2032 						            extended_msg[1], extended_msg[0]);
2033 
2034 					msgout = MESSAGE_REJECT;
2035 					NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ATN);
2036 					break;
2037 				} /* switch (tmp) */
2038 				break;
2039 			case PHASE_MSGOUT:
2040 				len = 1;
2041 				data = &msgout;
2042 				hostdata->last_message = msgout;
2043 				NCR5380_transfer_pio(instance, &phase, &len, &data);
2044 				if (msgout == ABORT) {
2045 					hostdata->connected = NULL;
2046 					cmd->result = DID_ERROR << 16;
2047 					complete_cmd(instance, cmd);
2048 					maybe_release_dma_irq(instance);
2049 					NCR5380_write(SELECT_ENABLE_REG, hostdata->id_mask);
2050 					return;
2051 				}
2052 				msgout = NOP;
2053 				break;
2054 			case PHASE_CMDOUT:
2055 				len = cmd->cmd_len;
2056 				data = cmd->cmnd;
2057 				/*
2058 				 * XXX for performance reasons, on machines with a
2059 				 * PSEUDO-DMA architecture we should probably
2060 				 * use the dma transfer function.
2061 				 */
2062 				NCR5380_transfer_pio(instance, &phase, &len, &data);
2063 				break;
2064 			case PHASE_STATIN:
2065 				len = 1;
2066 				data = &tmp;
2067 				NCR5380_transfer_pio(instance, &phase, &len, &data);
2068 				cmd->SCp.Status = tmp;
2069 				break;
2070 			default:
2071 				shost_printk(KERN_ERR, instance, "unknown phase\n");
2072 				NCR5380_dprint(NDEBUG_ANY, instance);
2073 			} /* switch(phase) */
2074 		} else {
2075 			spin_unlock_irq(&hostdata->lock);
2076 			NCR5380_poll_politely(instance, STATUS_REG, SR_REQ, SR_REQ, HZ);
2077 			spin_lock_irq(&hostdata->lock);
2078 		}
2079 	}
2080 }
2081 
2082 /*
2083  * Function : void NCR5380_reselect (struct Scsi_Host *instance)
2084  *
2085  * Purpose : does reselection, initializing the instance->connected
2086  * field to point to the scsi_cmnd for which the I_T_L or I_T_L_Q
2087  * nexus has been reestablished,
2088  *
2089  * Inputs : instance - this instance of the NCR5380.
2090  */
2091 
2092 static void NCR5380_reselect(struct Scsi_Host *instance)
2093 {
2094 	struct NCR5380_hostdata *hostdata = shost_priv(instance);
2095 	unsigned char target_mask;
2096 	unsigned char lun;
2097 	unsigned char msg[3];
2098 	struct NCR5380_cmd *ncmd;
2099 	struct scsi_cmnd *tmp;
2100 
2101 	/*
2102 	 * Disable arbitration, etc. since the host adapter obviously
2103 	 * lost, and tell an interrupted NCR5380_select() to restart.
2104 	 */
2105 
2106 	NCR5380_write(MODE_REG, MR_BASE);
2107 
2108 	target_mask = NCR5380_read(CURRENT_SCSI_DATA_REG) & ~(hostdata->id_mask);
2109 
2110 	dsprintk(NDEBUG_RESELECTION, instance, "reselect\n");
2111 
2112 	/*
2113 	 * At this point, we have detected that our SCSI ID is on the bus,
2114 	 * SEL is true and BSY was false for at least one bus settle delay
2115 	 * (400 ns).
2116 	 *
2117 	 * We must assert BSY ourselves, until the target drops the SEL
2118 	 * signal.
2119 	 */
2120 
2121 	NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_BSY);
2122 	if (NCR5380_poll_politely(instance,
2123 	                          STATUS_REG, SR_SEL, 0, 2 * HZ) < 0) {
2124 		NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
2125 		return;
2126 	}
2127 	NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
2128 
2129 	/*
2130 	 * Wait for target to go into MSGIN.
2131 	 */
2132 
2133 	if (NCR5380_poll_politely(instance,
2134 	                          STATUS_REG, SR_REQ, SR_REQ, 2 * HZ) < 0) {
2135 		do_abort(instance);
2136 		return;
2137 	}
2138 
2139 #ifdef CONFIG_SUN3
2140 	/* acknowledge toggle to MSGIN */
2141 	NCR5380_write(TARGET_COMMAND_REG, PHASE_SR_TO_TCR(PHASE_MSGIN));
2142 
2143 	/* peek at the byte without really hitting the bus */
2144 	msg[0] = NCR5380_read(CURRENT_SCSI_DATA_REG);
2145 #else
2146 	{
2147 		int len = 1;
2148 		unsigned char *data = msg;
2149 		unsigned char phase = PHASE_MSGIN;
2150 
2151 		NCR5380_transfer_pio(instance, &phase, &len, &data);
2152 
2153 		if (len) {
2154 			do_abort(instance);
2155 			return;
2156 		}
2157 	}
2158 #endif /* CONFIG_SUN3 */
2159 
2160 	if (!(msg[0] & 0x80)) {
2161 		shost_printk(KERN_ERR, instance, "expecting IDENTIFY message, got ");
2162 		spi_print_msg(msg);
2163 		printk("\n");
2164 		do_abort(instance);
2165 		return;
2166 	}
2167 	lun = msg[0] & 0x07;
2168 
2169 	/*
2170 	 * We need to add code for SCSI-II to track which devices have
2171 	 * I_T_L_Q nexuses established, and which have simple I_T_L
2172 	 * nexuses so we can chose to do additional data transfer.
2173 	 */
2174 
2175 	/*
2176 	 * Find the command corresponding to the I_T_L or I_T_L_Q  nexus we
2177 	 * just reestablished, and remove it from the disconnected queue.
2178 	 */
2179 
2180 	tmp = NULL;
2181 	list_for_each_entry(ncmd, &hostdata->disconnected, list) {
2182 		struct scsi_cmnd *cmd = NCR5380_to_scmd(ncmd);
2183 
2184 		if (target_mask == (1 << scmd_id(cmd)) &&
2185 		    lun == (u8)cmd->device->lun) {
2186 			list_del(&ncmd->list);
2187 			tmp = cmd;
2188 			break;
2189 		}
2190 	}
2191 
2192 	if (tmp) {
2193 		dsprintk(NDEBUG_RESELECTION | NDEBUG_QUEUES, instance,
2194 		         "reselect: removed %p from disconnected queue\n", tmp);
2195 	} else {
2196 		shost_printk(KERN_ERR, instance, "target bitmask 0x%02x lun %d not in disconnected queue.\n",
2197 		             target_mask, lun);
2198 		/*
2199 		 * Since we have an established nexus that we can't do anything
2200 		 * with, we must abort it.
2201 		 */
2202 		do_abort(instance);
2203 		return;
2204 	}
2205 
2206 #ifdef CONFIG_SUN3
2207 	{
2208 		void *d;
2209 		unsigned long count;
2210 
2211 		if (!tmp->SCp.this_residual && tmp->SCp.buffers_residual) {
2212 			count = tmp->SCp.buffer->length;
2213 			d = sg_virt(tmp->SCp.buffer);
2214 		} else {
2215 			count = tmp->SCp.this_residual;
2216 			d = tmp->SCp.ptr;
2217 		}
2218 
2219 		if (sun3_dma_setup_done != tmp &&
2220 		    sun3scsi_dma_xfer_len(count, tmp) > 0) {
2221 			sun3scsi_dma_setup(instance, d, count,
2222 			                   rq_data_dir(tmp->request));
2223 			sun3_dma_setup_done = tmp;
2224 		}
2225 	}
2226 
2227 	NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE | ICR_ASSERT_ACK);
2228 #endif /* CONFIG_SUN3 */
2229 
2230 	/* Accept message by clearing ACK */
2231 	NCR5380_write(INITIATOR_COMMAND_REG, ICR_BASE);
2232 
2233 	hostdata->connected = tmp;
2234 	dsprintk(NDEBUG_RESELECTION, instance, "nexus established, target %d, lun %llu\n",
2235 	         scmd_id(tmp), tmp->device->lun);
2236 }
2237 
2238 /**
2239  * list_find_cmd - test for presence of a command in a linked list
2240  * @haystack: list of commands
2241  * @needle: command to search for
2242  */
2243 
2244 static bool list_find_cmd(struct list_head *haystack,
2245                           struct scsi_cmnd *needle)
2246 {
2247 	struct NCR5380_cmd *ncmd;
2248 
2249 	list_for_each_entry(ncmd, haystack, list)
2250 		if (NCR5380_to_scmd(ncmd) == needle)
2251 			return true;
2252 	return false;
2253 }
2254 
2255 /**
2256  * list_remove_cmd - remove a command from linked list
2257  * @haystack: list of commands
2258  * @needle: command to remove
2259  */
2260 
2261 static bool list_del_cmd(struct list_head *haystack,
2262                          struct scsi_cmnd *needle)
2263 {
2264 	if (list_find_cmd(haystack, needle)) {
2265 		struct NCR5380_cmd *ncmd = scsi_cmd_priv(needle);
2266 
2267 		list_del(&ncmd->list);
2268 		return true;
2269 	}
2270 	return false;
2271 }
2272 
2273 /**
2274  * NCR5380_abort - scsi host eh_abort_handler() method
2275  * @cmd: the command to be aborted
2276  *
2277  * Try to abort a given command by removing it from queues and/or sending
2278  * the target an abort message. This may not succeed in causing a target
2279  * to abort the command. Nonetheless, the low-level driver must forget about
2280  * the command because the mid-layer reclaims it and it may be re-issued.
2281  *
2282  * The normal path taken by a command is as follows. For EH we trace this
2283  * same path to locate and abort the command.
2284  *
2285  * unissued -> selecting -> [unissued -> selecting ->]... connected ->
2286  * [disconnected -> connected ->]...
2287  * [autosense -> connected ->] done
2288  *
2289  * If cmd was not found at all then presumably it has already been completed,
2290  * in which case return SUCCESS to try to avoid further EH measures.
2291  *
2292  * If the command has not completed yet, we must not fail to find it.
2293  * We have no option but to forget the aborted command (even if it still
2294  * lacks sense data). The mid-layer may re-issue a command that is in error
2295  * recovery (see scsi_send_eh_cmnd), but the logic and data structures in
2296  * this driver are such that a command can appear on one queue only.
2297  *
2298  * The lock protects driver data structures, but EH handlers also use it
2299  * to serialize their own execution and prevent their own re-entry.
2300  */
2301 
2302 static int NCR5380_abort(struct scsi_cmnd *cmd)
2303 {
2304 	struct Scsi_Host *instance = cmd->device->host;
2305 	struct NCR5380_hostdata *hostdata = shost_priv(instance);
2306 	unsigned long flags;
2307 	int result = SUCCESS;
2308 
2309 	spin_lock_irqsave(&hostdata->lock, flags);
2310 
2311 #if (NDEBUG & NDEBUG_ANY)
2312 	scmd_printk(KERN_INFO, cmd, __func__);
2313 #endif
2314 	NCR5380_dprint(NDEBUG_ANY, instance);
2315 	NCR5380_dprint_phase(NDEBUG_ANY, instance);
2316 
2317 	if (list_del_cmd(&hostdata->unissued, cmd)) {
2318 		dsprintk(NDEBUG_ABORT, instance,
2319 		         "abort: removed %p from issue queue\n", cmd);
2320 		cmd->result = DID_ABORT << 16;
2321 		cmd->scsi_done(cmd); /* No tag or busy flag to worry about */
2322 		goto out;
2323 	}
2324 
2325 	if (hostdata->selecting == cmd) {
2326 		dsprintk(NDEBUG_ABORT, instance,
2327 		         "abort: cmd %p == selecting\n", cmd);
2328 		hostdata->selecting = NULL;
2329 		cmd->result = DID_ABORT << 16;
2330 		complete_cmd(instance, cmd);
2331 		goto out;
2332 	}
2333 
2334 	if (list_del_cmd(&hostdata->disconnected, cmd)) {
2335 		dsprintk(NDEBUG_ABORT, instance,
2336 		         "abort: removed %p from disconnected list\n", cmd);
2337 		/* Can't call NCR5380_select() and send ABORT because that
2338 		 * means releasing the lock. Need a bus reset.
2339 		 */
2340 		set_host_byte(cmd, DID_ERROR);
2341 		complete_cmd(instance, cmd);
2342 		result = FAILED;
2343 		goto out;
2344 	}
2345 
2346 	if (hostdata->connected == cmd) {
2347 		dsprintk(NDEBUG_ABORT, instance, "abort: cmd %p is connected\n", cmd);
2348 		hostdata->connected = NULL;
2349 		hostdata->dma_len = 0;
2350 		if (do_abort(instance)) {
2351 			set_host_byte(cmd, DID_ERROR);
2352 			complete_cmd(instance, cmd);
2353 			result = FAILED;
2354 			goto out;
2355 		}
2356 		set_host_byte(cmd, DID_ABORT);
2357 		complete_cmd(instance, cmd);
2358 		goto out;
2359 	}
2360 
2361 	if (list_del_cmd(&hostdata->autosense, cmd)) {
2362 		dsprintk(NDEBUG_ABORT, instance,
2363 		         "abort: removed %p from sense queue\n", cmd);
2364 		set_host_byte(cmd, DID_ERROR);
2365 		complete_cmd(instance, cmd);
2366 	}
2367 
2368 out:
2369 	if (result == FAILED)
2370 		dsprintk(NDEBUG_ABORT, instance, "abort: failed to abort %p\n", cmd);
2371 	else
2372 		dsprintk(NDEBUG_ABORT, instance, "abort: successfully aborted %p\n", cmd);
2373 
2374 	queue_work(hostdata->work_q, &hostdata->main_task);
2375 	maybe_release_dma_irq(instance);
2376 	spin_unlock_irqrestore(&hostdata->lock, flags);
2377 
2378 	return result;
2379 }
2380 
2381 
2382 /**
2383  * NCR5380_bus_reset - reset the SCSI bus
2384  * @cmd: SCSI command undergoing EH
2385  *
2386  * Returns SUCCESS
2387  */
2388 
2389 static int NCR5380_bus_reset(struct scsi_cmnd *cmd)
2390 {
2391 	struct Scsi_Host *instance = cmd->device->host;
2392 	struct NCR5380_hostdata *hostdata = shost_priv(instance);
2393 	int i;
2394 	unsigned long flags;
2395 	struct NCR5380_cmd *ncmd;
2396 
2397 	spin_lock_irqsave(&hostdata->lock, flags);
2398 
2399 #if (NDEBUG & NDEBUG_ANY)
2400 	scmd_printk(KERN_INFO, cmd, __func__);
2401 #endif
2402 	NCR5380_dprint(NDEBUG_ANY, instance);
2403 	NCR5380_dprint_phase(NDEBUG_ANY, instance);
2404 
2405 	do_reset(instance);
2406 
2407 	/* reset NCR registers */
2408 	NCR5380_write(MODE_REG, MR_BASE);
2409 	NCR5380_write(TARGET_COMMAND_REG, 0);
2410 	NCR5380_write(SELECT_ENABLE_REG, 0);
2411 
2412 	/* After the reset, there are no more connected or disconnected commands
2413 	 * and no busy units; so clear the low-level status here to avoid
2414 	 * conflicts when the mid-level code tries to wake up the affected
2415 	 * commands!
2416 	 */
2417 
2418 	if (list_del_cmd(&hostdata->unissued, cmd)) {
2419 		cmd->result = DID_RESET << 16;
2420 		cmd->scsi_done(cmd);
2421 	}
2422 
2423 	if (hostdata->selecting) {
2424 		hostdata->selecting->result = DID_RESET << 16;
2425 		complete_cmd(instance, hostdata->selecting);
2426 		hostdata->selecting = NULL;
2427 	}
2428 
2429 	list_for_each_entry(ncmd, &hostdata->disconnected, list) {
2430 		struct scsi_cmnd *cmd = NCR5380_to_scmd(ncmd);
2431 
2432 		set_host_byte(cmd, DID_RESET);
2433 		complete_cmd(instance, cmd);
2434 	}
2435 	INIT_LIST_HEAD(&hostdata->disconnected);
2436 
2437 	list_for_each_entry(ncmd, &hostdata->autosense, list) {
2438 		struct scsi_cmnd *cmd = NCR5380_to_scmd(ncmd);
2439 
2440 		set_host_byte(cmd, DID_RESET);
2441 		cmd->scsi_done(cmd);
2442 	}
2443 	INIT_LIST_HEAD(&hostdata->autosense);
2444 
2445 	if (hostdata->connected) {
2446 		set_host_byte(hostdata->connected, DID_RESET);
2447 		complete_cmd(instance, hostdata->connected);
2448 		hostdata->connected = NULL;
2449 	}
2450 
2451 	for (i = 0; i < 8; ++i)
2452 		hostdata->busy[i] = 0;
2453 	hostdata->dma_len = 0;
2454 
2455 	queue_work(hostdata->work_q, &hostdata->main_task);
2456 	maybe_release_dma_irq(instance);
2457 	spin_unlock_irqrestore(&hostdata->lock, flags);
2458 
2459 	return SUCCESS;
2460 }
2461