xref: /openbmc/linux/drivers/scsi/wd33c93.c (revision 8dd3cdea)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) 1996 John Shifflett, GeoLog Consulting
4  *    john@geolog.com
5  *    jshiffle@netcom.com
6  */
7 
8 /*
9  * Drew Eckhardt's excellent 'Generic NCR5380' sources from Linux-PC
10  * provided much of the inspiration and some of the code for this
11  * driver. Everything I know about Amiga DMA was gleaned from careful
12  * reading of Hamish Mcdonald's original wd33c93 driver; in fact, I
13  * borrowed shamelessly from all over that source. Thanks Hamish!
14  *
15  * _This_ driver is (I feel) an improvement over the old one in
16  * several respects:
17  *
18  *    -  Target Disconnection/Reconnection  is now supported. Any
19  *          system with more than one device active on the SCSI bus
20  *          will benefit from this. The driver defaults to what I
21  *          call 'adaptive disconnect' - meaning that each command
22  *          is evaluated individually as to whether or not it should
23  *          be run with the option to disconnect/reselect (if the
24  *          device chooses), or as a "SCSI-bus-hog".
25  *
26  *    -  Synchronous data transfers are now supported. Because of
27  *          a few devices that choke after telling the driver that
28  *          they can do sync transfers, we don't automatically use
29  *          this faster protocol - it can be enabled via the command-
30  *          line on a device-by-device basis.
31  *
32  *    -  Runtime operating parameters can now be specified through
33  *       the 'amiboot' or the 'insmod' command line. For amiboot do:
34  *          "amiboot [usual stuff] wd33c93=blah,blah,blah"
35  *       The defaults should be good for most people. See the comment
36  *       for 'setup_strings' below for more details.
37  *
38  *    -  The old driver relied exclusively on what the Western Digital
39  *          docs call "Combination Level 2 Commands", which are a great
40  *          idea in that the CPU is relieved of a lot of interrupt
41  *          overhead. However, by accepting a certain (user-settable)
42  *          amount of additional interrupts, this driver achieves
43  *          better control over the SCSI bus, and data transfers are
44  *          almost as fast while being much easier to define, track,
45  *          and debug.
46  *
47  *
48  * TODO:
49  *       more speed. linked commands.
50  *
51  *
52  * People with bug reports, wish-lists, complaints, comments,
53  * or improvements are asked to pah-leeez email me (John Shifflett)
54  * at john@geolog.com or jshiffle@netcom.com! I'm anxious to get
55  * this thing into as good a shape as possible, and I'm positive
56  * there are lots of lurking bugs and "Stupid Places".
57  *
58  * Updates:
59  *
60  * Added support for pre -A chips, which don't have advanced features
61  * and will generate CSR_RESEL rather than CSR_RESEL_AM.
62  *	Richard Hirst <richard@sleepie.demon.co.uk>  August 2000
63  *
64  * Added support for Burst Mode DMA and Fast SCSI. Enabled the use of
65  * default_sx_per for asynchronous data transfers. Added adjustment
66  * of transfer periods in sx_table to the actual input-clock.
67  *  peter fuerst <post@pfrst.de>  February 2007
68  */
69 
70 #include <linux/module.h>
71 
72 #include <linux/string.h>
73 #include <linux/delay.h>
74 #include <linux/init.h>
75 #include <linux/interrupt.h>
76 #include <linux/blkdev.h>
77 
78 #include <scsi/scsi.h>
79 #include <scsi/scsi_cmnd.h>
80 #include <scsi/scsi_device.h>
81 #include <scsi/scsi_host.h>
82 
83 #include <asm/irq.h>
84 
85 #include "wd33c93.h"
86 
87 #define optimum_sx_per(hostdata) (hostdata)->sx_table[1].period_ns
88 
89 
90 #define WD33C93_VERSION    "1.26++"
91 #define WD33C93_DATE       "10/Feb/2007"
92 
93 MODULE_AUTHOR("John Shifflett");
94 MODULE_DESCRIPTION("Generic WD33C93 SCSI driver");
95 MODULE_LICENSE("GPL");
96 
97 /*
98  * 'setup_strings' is a single string used to pass operating parameters and
99  * settings from the kernel/module command-line to the driver. 'setup_args[]'
100  * is an array of strings that define the compile-time default values for
101  * these settings. If Linux boots with an amiboot or insmod command-line,
102  * those settings are combined with 'setup_args[]'. Note that amiboot
103  * command-lines are prefixed with "wd33c93=" while insmod uses a
104  * "setup_strings=" prefix. The driver recognizes the following keywords
105  * (lower case required) and arguments:
106  *
107  * -  nosync:bitmask -bitmask is a byte where the 1st 7 bits correspond with
108  *                    the 7 possible SCSI devices. Set a bit to negotiate for
109  *                    asynchronous transfers on that device. To maintain
110  *                    backwards compatibility, a command-line such as
111  *                    "wd33c93=255" will be automatically translated to
112  *                    "wd33c93=nosync:0xff".
113  * -  nodma:x        -x = 1 to disable DMA, x = 0 to enable it. Argument is
114  *                    optional - if not present, same as "nodma:1".
115  * -  period:ns      -ns is the minimum # of nanoseconds in a SCSI data transfer
116  *                    period. Default is 500; acceptable values are 250 - 1000.
117  * -  disconnect:x   -x = 0 to never allow disconnects, 2 to always allow them.
118  *                    x = 1 does 'adaptive' disconnects, which is the default
119  *                    and generally the best choice.
120  * -  debug:x        -If 'DEBUGGING_ON' is defined, x is a bit mask that causes
121  *                    various types of debug output to printed - see the DB_xxx
122  *                    defines in wd33c93.h
123  * -  clock:x        -x = clock input in MHz for WD33c93 chip. Normal values
124  *                    would be from 8 through 20. Default is 8.
125  * -  burst:x        -x = 1 to use Burst Mode (or Demand-Mode) DMA, x = 0 to use
126  *                    Single Byte DMA, which is the default. Argument is
127  *                    optional - if not present, same as "burst:1".
128  * -  fast:x         -x = 1 to enable Fast SCSI, which is only effective with
129  *                    input-clock divisor 4 (WD33C93_FS_16_20), x = 0 to disable
130  *                    it, which is the default.  Argument is optional - if not
131  *                    present, same as "fast:1".
132  * -  next           -No argument. Used to separate blocks of keywords when
133  *                    there's more than one host adapter in the system.
134  *
135  * Syntax Notes:
136  * -  Numeric arguments can be decimal or the '0x' form of hex notation. There
137  *    _must_ be a colon between a keyword and its numeric argument, with no
138  *    spaces.
139  * -  Keywords are separated by commas, no spaces, in the standard kernel
140  *    command-line manner.
141  * -  A keyword in the 'nth' comma-separated command-line member will overwrite
142  *    the 'nth' element of setup_args[]. A blank command-line member (in
143  *    other words, a comma with no preceding keyword) will _not_ overwrite
144  *    the corresponding setup_args[] element.
145  * -  If a keyword is used more than once, the first one applies to the first
146  *    SCSI host found, the second to the second card, etc, unless the 'next'
147  *    keyword is used to change the order.
148  *
149  * Some amiboot examples (for insmod, use 'setup_strings' instead of 'wd33c93'):
150  * -  wd33c93=nosync:255
151  * -  wd33c93=nodma
152  * -  wd33c93=nodma:1
153  * -  wd33c93=disconnect:2,nosync:0x08,period:250
154  * -  wd33c93=debug:0x1c
155  */
156 
157 /* Normally, no defaults are specified */
158 static char *setup_args[] = { "", "", "", "", "", "", "", "", "", "" };
159 
160 static char *setup_strings;
161 module_param(setup_strings, charp, 0);
162 
163 static void wd33c93_execute(struct Scsi_Host *instance);
164 
165 #ifdef CONFIG_WD33C93_PIO
166 static inline uchar
167 read_wd33c93(const wd33c93_regs regs, uchar reg_num)
168 {
169 	uchar data;
170 
171 	outb(reg_num, regs.SASR);
172 	data = inb(regs.SCMD);
173 	return data;
174 }
175 
176 static inline unsigned long
177 read_wd33c93_count(const wd33c93_regs regs)
178 {
179 	unsigned long value;
180 
181 	outb(WD_TRANSFER_COUNT_MSB, regs.SASR);
182 	value = inb(regs.SCMD) << 16;
183 	value |= inb(regs.SCMD) << 8;
184 	value |= inb(regs.SCMD);
185 	return value;
186 }
187 
188 static inline uchar
189 read_aux_stat(const wd33c93_regs regs)
190 {
191 	return inb(regs.SASR);
192 }
193 
194 static inline void
195 write_wd33c93(const wd33c93_regs regs, uchar reg_num, uchar value)
196 {
197       outb(reg_num, regs.SASR);
198       outb(value, regs.SCMD);
199 }
200 
201 static inline void
202 write_wd33c93_count(const wd33c93_regs regs, unsigned long value)
203 {
204 	outb(WD_TRANSFER_COUNT_MSB, regs.SASR);
205 	outb((value >> 16) & 0xff, regs.SCMD);
206 	outb((value >> 8) & 0xff, regs.SCMD);
207 	outb( value & 0xff, regs.SCMD);
208 }
209 
210 #define write_wd33c93_cmd(regs, cmd) \
211 	write_wd33c93((regs), WD_COMMAND, (cmd))
212 
213 static inline void
214 write_wd33c93_cdb(const wd33c93_regs regs, uint len, uchar cmnd[])
215 {
216 	int i;
217 
218 	outb(WD_CDB_1, regs.SASR);
219 	for (i=0; i<len; i++)
220 		outb(cmnd[i], regs.SCMD);
221 }
222 
223 #else /* CONFIG_WD33C93_PIO */
224 static inline uchar
225 read_wd33c93(const wd33c93_regs regs, uchar reg_num)
226 {
227 	*regs.SASR = reg_num;
228 	mb();
229 	return (*regs.SCMD);
230 }
231 
232 static unsigned long
233 read_wd33c93_count(const wd33c93_regs regs)
234 {
235 	unsigned long value;
236 
237 	*regs.SASR = WD_TRANSFER_COUNT_MSB;
238 	mb();
239 	value = *regs.SCMD << 16;
240 	value |= *regs.SCMD << 8;
241 	value |= *regs.SCMD;
242 	mb();
243 	return value;
244 }
245 
246 static inline uchar
247 read_aux_stat(const wd33c93_regs regs)
248 {
249 	return *regs.SASR;
250 }
251 
252 static inline void
253 write_wd33c93(const wd33c93_regs regs, uchar reg_num, uchar value)
254 {
255 	*regs.SASR = reg_num;
256 	mb();
257 	*regs.SCMD = value;
258 	mb();
259 }
260 
261 static void
262 write_wd33c93_count(const wd33c93_regs regs, unsigned long value)
263 {
264 	*regs.SASR = WD_TRANSFER_COUNT_MSB;
265 	mb();
266 	*regs.SCMD = value >> 16;
267 	*regs.SCMD = value >> 8;
268 	*regs.SCMD = value;
269 	mb();
270 }
271 
272 static inline void
273 write_wd33c93_cmd(const wd33c93_regs regs, uchar cmd)
274 {
275 	*regs.SASR = WD_COMMAND;
276 	mb();
277 	*regs.SCMD = cmd;
278 	mb();
279 }
280 
281 static inline void
282 write_wd33c93_cdb(const wd33c93_regs regs, uint len, uchar cmnd[])
283 {
284 	int i;
285 
286 	*regs.SASR = WD_CDB_1;
287 	for (i = 0; i < len; i++)
288 		*regs.SCMD = cmnd[i];
289 }
290 #endif /* CONFIG_WD33C93_PIO */
291 
292 static inline uchar
293 read_1_byte(const wd33c93_regs regs)
294 {
295 	uchar asr;
296 	uchar x = 0;
297 
298 	write_wd33c93(regs, WD_CONTROL, CTRL_IDI | CTRL_EDI | CTRL_POLLED);
299 	write_wd33c93_cmd(regs, WD_CMD_TRANS_INFO | 0x80);
300 	do {
301 		asr = read_aux_stat(regs);
302 		if (asr & ASR_DBR)
303 			x = read_wd33c93(regs, WD_DATA);
304 	} while (!(asr & ASR_INT));
305 	return x;
306 }
307 
308 static int
309 round_period(unsigned int period, const struct sx_period *sx_table)
310 {
311 	int x;
312 
313 	for (x = 1; sx_table[x].period_ns; x++) {
314 		if ((period <= sx_table[x - 0].period_ns) &&
315 		    (period > sx_table[x - 1].period_ns)) {
316 			return x;
317 		}
318 	}
319 	return 7;
320 }
321 
322 /*
323  * Calculate Synchronous Transfer Register value from SDTR code.
324  */
325 static uchar
326 calc_sync_xfer(unsigned int period, unsigned int offset, unsigned int fast,
327                const struct sx_period *sx_table)
328 {
329 	/* When doing Fast SCSI synchronous data transfers, the corresponding
330 	 * value in 'sx_table' is two times the actually used transfer period.
331 	 */
332 	uchar result;
333 
334 	if (offset && fast) {
335 		fast = STR_FSS;
336 		period *= 2;
337 	} else {
338 		fast = 0;
339 	}
340 	period *= 4;		/* convert SDTR code to ns */
341 	result = sx_table[round_period(period,sx_table)].reg_value;
342 	result |= (offset < OPTIMUM_SX_OFF) ? offset : OPTIMUM_SX_OFF;
343 	result |= fast;
344 	return result;
345 }
346 
347 /*
348  * Calculate SDTR code bytes [3],[4] from period and offset.
349  */
350 static inline void
351 calc_sync_msg(unsigned int period, unsigned int offset, unsigned int fast,
352                 uchar  msg[2])
353 {
354 	/* 'period' is a "normal"-mode value, like the ones in 'sx_table'. The
355 	 * actually used transfer period for Fast SCSI synchronous data
356 	 * transfers is half that value.
357 	 */
358 	period /= 4;
359 	if (offset && fast)
360 		period /= 2;
361 	msg[0] = period;
362 	msg[1] = offset;
363 }
364 
365 static int wd33c93_queuecommand_lck(struct scsi_cmnd *cmd)
366 {
367 	struct scsi_pointer *scsi_pointer = WD33C93_scsi_pointer(cmd);
368 	struct WD33C93_hostdata *hostdata;
369 	struct scsi_cmnd *tmp;
370 
371 	hostdata = (struct WD33C93_hostdata *) cmd->device->host->hostdata;
372 
373 	DB(DB_QUEUE_COMMAND,
374 	   printk("Q-%d-%02x( ", cmd->device->id, cmd->cmnd[0]))
375 
376 /* Set up a few fields in the scsi_cmnd structure for our own use:
377  *  - host_scribble is the pointer to the next cmd in the input queue
378  *  - result is what you'd expect
379  */
380 	cmd->host_scribble = NULL;
381 	cmd->result = 0;
382 
383 /* We use the Scsi_Pointer structure that's included with each command
384  * as a scratchpad (as it's intended to be used!). The handy thing about
385  * the SCp.xxx fields is that they're always associated with a given
386  * cmd, and are preserved across disconnect-reselect. This means we
387  * can pretty much ignore SAVE_POINTERS and RESTORE_POINTERS messages
388  * if we keep all the critical pointers and counters in SCp:
389  *  - SCp.ptr is the pointer into the RAM buffer
390  *  - SCp.this_residual is the size of that buffer
391  *  - SCp.buffer points to the current scatter-gather buffer
392  *  - SCp.buffers_residual tells us how many S.G. buffers there are
393  *  - SCp.have_data_in is not used
394  *  - SCp.sent_command is not used
395  *  - SCp.phase records this command's SRCID_ER bit setting
396  */
397 
398 	if (scsi_bufflen(cmd)) {
399 		scsi_pointer->buffer = scsi_sglist(cmd);
400 		scsi_pointer->buffers_residual = scsi_sg_count(cmd) - 1;
401 		scsi_pointer->ptr = sg_virt(scsi_pointer->buffer);
402 		scsi_pointer->this_residual = scsi_pointer->buffer->length;
403 	} else {
404 		scsi_pointer->buffer = NULL;
405 		scsi_pointer->buffers_residual = 0;
406 		scsi_pointer->ptr = NULL;
407 		scsi_pointer->this_residual = 0;
408 	}
409 
410 /* WD docs state that at the conclusion of a "LEVEL2" command, the
411  * status byte can be retrieved from the LUN register. Apparently,
412  * this is the case only for *uninterrupted* LEVEL2 commands! If
413  * there are any unexpected phases entered, even if they are 100%
414  * legal (different devices may choose to do things differently),
415  * the LEVEL2 command sequence is exited. This often occurs prior
416  * to receiving the status byte, in which case the driver does a
417  * status phase interrupt and gets the status byte on its own.
418  * While such a command can then be "resumed" (ie restarted to
419  * finish up as a LEVEL2 command), the LUN register will NOT be
420  * a valid status byte at the command's conclusion, and we must
421  * use the byte obtained during the earlier interrupt. Here, we
422  * preset SCp.Status to an illegal value (0xff) so that when
423  * this command finally completes, we can tell where the actual
424  * status byte is stored.
425  */
426 
427 	scsi_pointer->Status = ILLEGAL_STATUS_BYTE;
428 
429 	/*
430 	 * Add the cmd to the end of 'input_Q'. Note that REQUEST SENSE
431 	 * commands are added to the head of the queue so that the desired
432 	 * sense data is not lost before REQUEST_SENSE executes.
433 	 */
434 
435 	spin_lock_irq(&hostdata->lock);
436 
437 	if (!(hostdata->input_Q) || (cmd->cmnd[0] == REQUEST_SENSE)) {
438 		cmd->host_scribble = (uchar *) hostdata->input_Q;
439 		hostdata->input_Q = cmd;
440 	} else {		/* find the end of the queue */
441 		for (tmp = (struct scsi_cmnd *) hostdata->input_Q;
442 		     tmp->host_scribble;
443 		     tmp = (struct scsi_cmnd *) tmp->host_scribble) ;
444 		tmp->host_scribble = (uchar *) cmd;
445 	}
446 
447 /* We know that there's at least one command in 'input_Q' now.
448  * Go see if any of them are runnable!
449  */
450 
451 	wd33c93_execute(cmd->device->host);
452 
453 	DB(DB_QUEUE_COMMAND, printk(")Q "))
454 
455 	spin_unlock_irq(&hostdata->lock);
456 	return 0;
457 }
458 
459 DEF_SCSI_QCMD(wd33c93_queuecommand)
460 
461 /*
462  * This routine attempts to start a scsi command. If the host_card is
463  * already connected, we give up immediately. Otherwise, look through
464  * the input_Q, using the first command we find that's intended
465  * for a currently non-busy target/lun.
466  *
467  * wd33c93_execute() is always called with interrupts disabled or from
468  * the wd33c93_intr itself, which means that a wd33c93 interrupt
469  * cannot occur while we are in here.
470  */
471 static void
472 wd33c93_execute(struct Scsi_Host *instance)
473 {
474 	struct scsi_pointer *scsi_pointer;
475 	struct WD33C93_hostdata *hostdata =
476 	    (struct WD33C93_hostdata *) instance->hostdata;
477 	const wd33c93_regs regs = hostdata->regs;
478 	struct scsi_cmnd *cmd, *prev;
479 
480 	DB(DB_EXECUTE, printk("EX("))
481 	if (hostdata->selecting || hostdata->connected) {
482 		DB(DB_EXECUTE, printk(")EX-0 "))
483 		return;
484 	}
485 
486 	/*
487 	 * Search through the input_Q for a command destined
488 	 * for an idle target/lun.
489 	 */
490 
491 	cmd = (struct scsi_cmnd *) hostdata->input_Q;
492 	prev = NULL;
493 	while (cmd) {
494 		if (!(hostdata->busy[cmd->device->id] &
495 		      (1 << (cmd->device->lun & 0xff))))
496 			break;
497 		prev = cmd;
498 		cmd = (struct scsi_cmnd *) cmd->host_scribble;
499 	}
500 
501 	/* quit if queue empty or all possible targets are busy */
502 
503 	if (!cmd) {
504 		DB(DB_EXECUTE, printk(")EX-1 "))
505 		return;
506 	}
507 
508 	/*  remove command from queue */
509 
510 	if (prev)
511 		prev->host_scribble = cmd->host_scribble;
512 	else
513 		hostdata->input_Q = (struct scsi_cmnd *) cmd->host_scribble;
514 
515 #ifdef PROC_STATISTICS
516 	hostdata->cmd_cnt[cmd->device->id]++;
517 #endif
518 
519 	/*
520 	 * Start the selection process
521 	 */
522 
523 	if (cmd->sc_data_direction == DMA_TO_DEVICE)
524 		write_wd33c93(regs, WD_DESTINATION_ID, cmd->device->id);
525 	else
526 		write_wd33c93(regs, WD_DESTINATION_ID, cmd->device->id | DSTID_DPD);
527 
528 /* Now we need to figure out whether or not this command is a good
529  * candidate for disconnect/reselect. We guess to the best of our
530  * ability, based on a set of hierarchical rules. When several
531  * devices are operating simultaneously, disconnects are usually
532  * an advantage. In a single device system, or if only 1 device
533  * is being accessed, transfers usually go faster if disconnects
534  * are not allowed:
535  *
536  * + Commands should NEVER disconnect if hostdata->disconnect =
537  *   DIS_NEVER (this holds for tape drives also), and ALWAYS
538  *   disconnect if hostdata->disconnect = DIS_ALWAYS.
539  * + Tape drive commands should always be allowed to disconnect.
540  * + Disconnect should be allowed if disconnected_Q isn't empty.
541  * + Commands should NOT disconnect if input_Q is empty.
542  * + Disconnect should be allowed if there are commands in input_Q
543  *   for a different target/lun. In this case, the other commands
544  *   should be made disconnect-able, if not already.
545  *
546  * I know, I know - this code would flunk me out of any
547  * "C Programming 101" class ever offered. But it's easy
548  * to change around and experiment with for now.
549  */
550 
551 	scsi_pointer = WD33C93_scsi_pointer(cmd);
552 	scsi_pointer->phase = 0;	/* assume no disconnect */
553 	if (hostdata->disconnect == DIS_NEVER)
554 		goto no;
555 	if (hostdata->disconnect == DIS_ALWAYS)
556 		goto yes;
557 	if (cmd->device->type == 1)	/* tape drive? */
558 		goto yes;
559 	if (hostdata->disconnected_Q)	/* other commands disconnected? */
560 		goto yes;
561 	if (!(hostdata->input_Q))	/* input_Q empty? */
562 		goto no;
563 	for (prev = (struct scsi_cmnd *) hostdata->input_Q; prev;
564 	     prev = (struct scsi_cmnd *) prev->host_scribble) {
565 		if ((prev->device->id != cmd->device->id) ||
566 		    (prev->device->lun != cmd->device->lun)) {
567 			for (prev = (struct scsi_cmnd *) hostdata->input_Q; prev;
568 			     prev = (struct scsi_cmnd *) prev->host_scribble)
569 				WD33C93_scsi_pointer(prev)->phase = 1;
570 			goto yes;
571 		}
572 	}
573 
574 	goto no;
575 
576  yes:
577 	scsi_pointer->phase = 1;
578 
579 #ifdef PROC_STATISTICS
580 	hostdata->disc_allowed_cnt[cmd->device->id]++;
581 #endif
582 
583  no:
584 
585 	write_wd33c93(regs, WD_SOURCE_ID, scsi_pointer->phase ? SRCID_ER : 0);
586 
587 	write_wd33c93(regs, WD_TARGET_LUN, (u8)cmd->device->lun);
588 	write_wd33c93(regs, WD_SYNCHRONOUS_TRANSFER,
589 		      hostdata->sync_xfer[cmd->device->id]);
590 	hostdata->busy[cmd->device->id] |= (1 << (cmd->device->lun & 0xFF));
591 
592 	if ((hostdata->level2 == L2_NONE) ||
593 	    (hostdata->sync_stat[cmd->device->id] == SS_UNSET)) {
594 
595 		/*
596 		 * Do a 'Select-With-ATN' command. This will end with
597 		 * one of the following interrupts:
598 		 *    CSR_RESEL_AM:  failure - can try again later.
599 		 *    CSR_TIMEOUT:   failure - give up.
600 		 *    CSR_SELECT:    success - proceed.
601 		 */
602 
603 		hostdata->selecting = cmd;
604 
605 /* Every target has its own synchronous transfer setting, kept in the
606  * sync_xfer array, and a corresponding status byte in sync_stat[].
607  * Each target's sync_stat[] entry is initialized to SX_UNSET, and its
608  * sync_xfer[] entry is initialized to the default/safe value. SS_UNSET
609  * means that the parameters are undetermined as yet, and that we
610  * need to send an SDTR message to this device after selection is
611  * complete: We set SS_FIRST to tell the interrupt routine to do so.
612  * If we've been asked not to try synchronous transfers on this
613  * target (and _all_ luns within it), we'll still send the SDTR message
614  * later, but at that time we'll negotiate for async by specifying a
615  * sync fifo depth of 0.
616  */
617 		if (hostdata->sync_stat[cmd->device->id] == SS_UNSET)
618 			hostdata->sync_stat[cmd->device->id] = SS_FIRST;
619 		hostdata->state = S_SELECTING;
620 		write_wd33c93_count(regs, 0);	/* guarantee a DATA_PHASE interrupt */
621 		write_wd33c93_cmd(regs, WD_CMD_SEL_ATN);
622 	} else {
623 
624 		/*
625 		 * Do a 'Select-With-ATN-Xfer' command. This will end with
626 		 * one of the following interrupts:
627 		 *    CSR_RESEL_AM:  failure - can try again later.
628 		 *    CSR_TIMEOUT:   failure - give up.
629 		 *    anything else: success - proceed.
630 		 */
631 
632 		hostdata->connected = cmd;
633 		write_wd33c93(regs, WD_COMMAND_PHASE, 0);
634 
635 		/* copy command_descriptor_block into WD chip
636 		 * (take advantage of auto-incrementing)
637 		 */
638 
639 		write_wd33c93_cdb(regs, cmd->cmd_len, cmd->cmnd);
640 
641 		/* The wd33c93 only knows about Group 0, 1, and 5 commands when
642 		 * it's doing a 'select-and-transfer'. To be safe, we write the
643 		 * size of the CDB into the OWN_ID register for every case. This
644 		 * way there won't be problems with vendor-unique, audio, etc.
645 		 */
646 
647 		write_wd33c93(regs, WD_OWN_ID, cmd->cmd_len);
648 
649 		/* When doing a non-disconnect command with DMA, we can save
650 		 * ourselves a DATA phase interrupt later by setting everything
651 		 * up ahead of time.
652 		 */
653 
654 		if (scsi_pointer->phase == 0 && hostdata->no_dma == 0) {
655 			if (hostdata->dma_setup(cmd,
656 			    (cmd->sc_data_direction == DMA_TO_DEVICE) ?
657 			     DATA_OUT_DIR : DATA_IN_DIR))
658 				write_wd33c93_count(regs, 0);	/* guarantee a DATA_PHASE interrupt */
659 			else {
660 				write_wd33c93_count(regs,
661 						scsi_pointer->this_residual);
662 				write_wd33c93(regs, WD_CONTROL,
663 					      CTRL_IDI | CTRL_EDI | hostdata->dma_mode);
664 				hostdata->dma = D_DMA_RUNNING;
665 			}
666 		} else
667 			write_wd33c93_count(regs, 0);	/* guarantee a DATA_PHASE interrupt */
668 
669 		hostdata->state = S_RUNNING_LEVEL2;
670 		write_wd33c93_cmd(regs, WD_CMD_SEL_ATN_XFER);
671 	}
672 
673 	/*
674 	 * Since the SCSI bus can handle only 1 connection at a time,
675 	 * we get out of here now. If the selection fails, or when
676 	 * the command disconnects, we'll come back to this routine
677 	 * to search the input_Q again...
678 	 */
679 
680 	DB(DB_EXECUTE,
681 	   printk("%s)EX-2 ", scsi_pointer->phase ? "d:" : ""))
682 }
683 
684 static void
685 transfer_pio(const wd33c93_regs regs, uchar * buf, int cnt,
686 	     int data_in_dir, struct WD33C93_hostdata *hostdata)
687 {
688 	uchar asr;
689 
690 	DB(DB_TRANSFER,
691 	   printk("(%p,%d,%s:", buf, cnt, data_in_dir ? "in" : "out"))
692 
693 	write_wd33c93(regs, WD_CONTROL, CTRL_IDI | CTRL_EDI | CTRL_POLLED);
694 	write_wd33c93_count(regs, cnt);
695 	write_wd33c93_cmd(regs, WD_CMD_TRANS_INFO);
696 	if (data_in_dir) {
697 		do {
698 			asr = read_aux_stat(regs);
699 			if (asr & ASR_DBR)
700 				*buf++ = read_wd33c93(regs, WD_DATA);
701 		} while (!(asr & ASR_INT));
702 	} else {
703 		do {
704 			asr = read_aux_stat(regs);
705 			if (asr & ASR_DBR)
706 				write_wd33c93(regs, WD_DATA, *buf++);
707 		} while (!(asr & ASR_INT));
708 	}
709 
710 	/* Note: we are returning with the interrupt UN-cleared.
711 	 * Since (presumably) an entire I/O operation has
712 	 * completed, the bus phase is probably different, and
713 	 * the interrupt routine will discover this when it
714 	 * responds to the uncleared int.
715 	 */
716 
717 }
718 
719 static void
720 transfer_bytes(const wd33c93_regs regs, struct scsi_cmnd *cmd,
721 		int data_in_dir)
722 {
723 	struct scsi_pointer *scsi_pointer = WD33C93_scsi_pointer(cmd);
724 	struct WD33C93_hostdata *hostdata;
725 	unsigned long length;
726 
727 	hostdata = (struct WD33C93_hostdata *) cmd->device->host->hostdata;
728 
729 /* Normally, you'd expect 'this_residual' to be non-zero here.
730  * In a series of scatter-gather transfers, however, this
731  * routine will usually be called with 'this_residual' equal
732  * to 0 and 'buffers_residual' non-zero. This means that a
733  * previous transfer completed, clearing 'this_residual', and
734  * now we need to setup the next scatter-gather buffer as the
735  * source or destination for THIS transfer.
736  */
737 	if (!scsi_pointer->this_residual && scsi_pointer->buffers_residual) {
738 		scsi_pointer->buffer = sg_next(scsi_pointer->buffer);
739 		--scsi_pointer->buffers_residual;
740 		scsi_pointer->this_residual = scsi_pointer->buffer->length;
741 		scsi_pointer->ptr = sg_virt(scsi_pointer->buffer);
742 	}
743 	if (!scsi_pointer->this_residual) /* avoid bogus setups */
744 		return;
745 
746 	write_wd33c93(regs, WD_SYNCHRONOUS_TRANSFER,
747 		      hostdata->sync_xfer[cmd->device->id]);
748 
749 /* 'hostdata->no_dma' is TRUE if we don't even want to try DMA.
750  * Update 'this_residual' and 'ptr' after 'transfer_pio()' returns.
751  */
752 
753 	if (hostdata->no_dma || hostdata->dma_setup(cmd, data_in_dir)) {
754 #ifdef PROC_STATISTICS
755 		hostdata->pio_cnt++;
756 #endif
757 		transfer_pio(regs, (uchar *) scsi_pointer->ptr,
758 			     scsi_pointer->this_residual, data_in_dir,
759 			     hostdata);
760 		length = scsi_pointer->this_residual;
761 		scsi_pointer->this_residual = read_wd33c93_count(regs);
762 		scsi_pointer->ptr += length - scsi_pointer->this_residual;
763 	}
764 
765 /* We are able to do DMA (in fact, the Amiga hardware is
766  * already going!), so start up the wd33c93 in DMA mode.
767  * We set 'hostdata->dma' = D_DMA_RUNNING so that when the
768  * transfer completes and causes an interrupt, we're
769  * reminded to tell the Amiga to shut down its end. We'll
770  * postpone the updating of 'this_residual' and 'ptr'
771  * until then.
772  */
773 
774 	else {
775 #ifdef PROC_STATISTICS
776 		hostdata->dma_cnt++;
777 #endif
778 		write_wd33c93(regs, WD_CONTROL, CTRL_IDI | CTRL_EDI | hostdata->dma_mode);
779 		write_wd33c93_count(regs, scsi_pointer->this_residual);
780 
781 		if ((hostdata->level2 >= L2_DATA) ||
782 		    (hostdata->level2 == L2_BASIC && scsi_pointer->phase == 0)) {
783 			write_wd33c93(regs, WD_COMMAND_PHASE, 0x45);
784 			write_wd33c93_cmd(regs, WD_CMD_SEL_ATN_XFER);
785 			hostdata->state = S_RUNNING_LEVEL2;
786 		} else
787 			write_wd33c93_cmd(regs, WD_CMD_TRANS_INFO);
788 
789 		hostdata->dma = D_DMA_RUNNING;
790 	}
791 }
792 
793 void
794 wd33c93_intr(struct Scsi_Host *instance)
795 {
796 	struct scsi_pointer *scsi_pointer;
797 	struct WD33C93_hostdata *hostdata =
798 	    (struct WD33C93_hostdata *) instance->hostdata;
799 	const wd33c93_regs regs = hostdata->regs;
800 	struct scsi_cmnd *patch, *cmd;
801 	uchar asr, sr, phs, id, lun, *ucp, msg;
802 	unsigned long length, flags;
803 
804 	asr = read_aux_stat(regs);
805 	if (!(asr & ASR_INT) || (asr & ASR_BSY))
806 		return;
807 
808 	spin_lock_irqsave(&hostdata->lock, flags);
809 
810 #ifdef PROC_STATISTICS
811 	hostdata->int_cnt++;
812 #endif
813 
814 	cmd = (struct scsi_cmnd *) hostdata->connected;	/* assume we're connected */
815 	scsi_pointer = WD33C93_scsi_pointer(cmd);
816 	sr = read_wd33c93(regs, WD_SCSI_STATUS);	/* clear the interrupt */
817 	phs = read_wd33c93(regs, WD_COMMAND_PHASE);
818 
819 	DB(DB_INTR, printk("{%02x:%02x-", asr, sr))
820 
821 /* After starting a DMA transfer, the next interrupt
822  * is guaranteed to be in response to completion of
823  * the transfer. Since the Amiga DMA hardware runs in
824  * in an open-ended fashion, it needs to be told when
825  * to stop; do that here if D_DMA_RUNNING is true.
826  * Also, we have to update 'this_residual' and 'ptr'
827  * based on the contents of the TRANSFER_COUNT register,
828  * in case the device decided to do an intermediate
829  * disconnect (a device may do this if it has to do a
830  * seek, or just to be nice and let other devices have
831  * some bus time during long transfers). After doing
832  * whatever is needed, we go on and service the WD3393
833  * interrupt normally.
834  */
835 	    if (hostdata->dma == D_DMA_RUNNING) {
836 		DB(DB_TRANSFER,
837 		   printk("[%p/%d:", scsi_pointer->ptr, scsi_pointer->this_residual))
838 		    hostdata->dma_stop(cmd->device->host, cmd, 1);
839 		hostdata->dma = D_DMA_OFF;
840 		length = scsi_pointer->this_residual;
841 		scsi_pointer->this_residual = read_wd33c93_count(regs);
842 		scsi_pointer->ptr += length - scsi_pointer->this_residual;
843 		DB(DB_TRANSFER,
844 		   printk("%p/%d]", scsi_pointer->ptr, scsi_pointer->this_residual))
845 	}
846 
847 /* Respond to the specific WD3393 interrupt - there are quite a few! */
848 	switch (sr) {
849 	case CSR_TIMEOUT:
850 		DB(DB_INTR, printk("TIMEOUT"))
851 
852 		    if (hostdata->state == S_RUNNING_LEVEL2)
853 			hostdata->connected = NULL;
854 		else {
855 			cmd = (struct scsi_cmnd *) hostdata->selecting;	/* get a valid cmd */
856 			hostdata->selecting = NULL;
857 		}
858 
859 		cmd->result = DID_NO_CONNECT << 16;
860 		hostdata->busy[cmd->device->id] &= ~(1 << (cmd->device->lun & 0xff));
861 		hostdata->state = S_UNCONNECTED;
862 		scsi_done(cmd);
863 
864 		/* From esp.c:
865 		 * There is a window of time within the scsi_done() path
866 		 * of execution where interrupts are turned back on full
867 		 * blast and left that way.  During that time we could
868 		 * reconnect to a disconnected command, then we'd bomb
869 		 * out below.  We could also end up executing two commands
870 		 * at _once_.  ...just so you know why the restore_flags()
871 		 * is here...
872 		 */
873 
874 		spin_unlock_irqrestore(&hostdata->lock, flags);
875 
876 /* We are not connected to a target - check to see if there
877  * are commands waiting to be executed.
878  */
879 
880 		wd33c93_execute(instance);
881 		break;
882 
883 /* Note: this interrupt should not occur in a LEVEL2 command */
884 
885 	case CSR_SELECT:
886 		DB(DB_INTR, printk("SELECT"))
887 		    hostdata->connected = cmd =
888 		    (struct scsi_cmnd *) hostdata->selecting;
889 		hostdata->selecting = NULL;
890 
891 		/* construct an IDENTIFY message with correct disconnect bit */
892 
893 		hostdata->outgoing_msg[0] = IDENTIFY(0, cmd->device->lun);
894 		if (scsi_pointer->phase)
895 			hostdata->outgoing_msg[0] |= 0x40;
896 
897 		if (hostdata->sync_stat[cmd->device->id] == SS_FIRST) {
898 
899 			hostdata->sync_stat[cmd->device->id] = SS_WAITING;
900 
901 /* Tack on a 2nd message to ask about synchronous transfers. If we've
902  * been asked to do only asynchronous transfers on this device, we
903  * request a fifo depth of 0, which is equivalent to async - should
904  * solve the problems some people have had with GVP's Guru ROM.
905  */
906 
907 			hostdata->outgoing_msg[1] = EXTENDED_MESSAGE;
908 			hostdata->outgoing_msg[2] = 3;
909 			hostdata->outgoing_msg[3] = EXTENDED_SDTR;
910 			if (hostdata->no_sync & (1 << cmd->device->id)) {
911 				calc_sync_msg(hostdata->default_sx_per, 0,
912 						0, hostdata->outgoing_msg + 4);
913 			} else {
914 				calc_sync_msg(optimum_sx_per(hostdata),
915 						OPTIMUM_SX_OFF,
916 						hostdata->fast,
917 						hostdata->outgoing_msg + 4);
918 			}
919 			hostdata->outgoing_len = 6;
920 #ifdef SYNC_DEBUG
921 			ucp = hostdata->outgoing_msg + 1;
922 			printk(" sending SDTR %02x03%02x%02x%02x ",
923 				ucp[0], ucp[2], ucp[3], ucp[4]);
924 #endif
925 		} else
926 			hostdata->outgoing_len = 1;
927 
928 		hostdata->state = S_CONNECTED;
929 		spin_unlock_irqrestore(&hostdata->lock, flags);
930 		break;
931 
932 	case CSR_XFER_DONE | PHS_DATA_IN:
933 	case CSR_UNEXP | PHS_DATA_IN:
934 	case CSR_SRV_REQ | PHS_DATA_IN:
935 		DB(DB_INTR,
936 		   printk("IN-%d.%d", scsi_pointer->this_residual,
937 			  scsi_pointer->buffers_residual))
938 		    transfer_bytes(regs, cmd, DATA_IN_DIR);
939 		if (hostdata->state != S_RUNNING_LEVEL2)
940 			hostdata->state = S_CONNECTED;
941 		spin_unlock_irqrestore(&hostdata->lock, flags);
942 		break;
943 
944 	case CSR_XFER_DONE | PHS_DATA_OUT:
945 	case CSR_UNEXP | PHS_DATA_OUT:
946 	case CSR_SRV_REQ | PHS_DATA_OUT:
947 		DB(DB_INTR,
948 		   printk("OUT-%d.%d", scsi_pointer->this_residual,
949 			  scsi_pointer->buffers_residual))
950 		    transfer_bytes(regs, cmd, DATA_OUT_DIR);
951 		if (hostdata->state != S_RUNNING_LEVEL2)
952 			hostdata->state = S_CONNECTED;
953 		spin_unlock_irqrestore(&hostdata->lock, flags);
954 		break;
955 
956 /* Note: this interrupt should not occur in a LEVEL2 command */
957 
958 	case CSR_XFER_DONE | PHS_COMMAND:
959 	case CSR_UNEXP | PHS_COMMAND:
960 	case CSR_SRV_REQ | PHS_COMMAND:
961 		DB(DB_INTR, printk("CMND-%02x", cmd->cmnd[0]))
962 		    transfer_pio(regs, cmd->cmnd, cmd->cmd_len, DATA_OUT_DIR,
963 				 hostdata);
964 		hostdata->state = S_CONNECTED;
965 		spin_unlock_irqrestore(&hostdata->lock, flags);
966 		break;
967 
968 	case CSR_XFER_DONE | PHS_STATUS:
969 	case CSR_UNEXP | PHS_STATUS:
970 	case CSR_SRV_REQ | PHS_STATUS:
971 		DB(DB_INTR, printk("STATUS="))
972 		scsi_pointer->Status = read_1_byte(regs);
973 		DB(DB_INTR, printk("%02x", scsi_pointer->Status))
974 		    if (hostdata->level2 >= L2_BASIC) {
975 			sr = read_wd33c93(regs, WD_SCSI_STATUS);	/* clear interrupt */
976 			udelay(7);
977 			hostdata->state = S_RUNNING_LEVEL2;
978 			write_wd33c93(regs, WD_COMMAND_PHASE, 0x50);
979 			write_wd33c93_cmd(regs, WD_CMD_SEL_ATN_XFER);
980 		} else {
981 			hostdata->state = S_CONNECTED;
982 		}
983 		spin_unlock_irqrestore(&hostdata->lock, flags);
984 		break;
985 
986 	case CSR_XFER_DONE | PHS_MESS_IN:
987 	case CSR_UNEXP | PHS_MESS_IN:
988 	case CSR_SRV_REQ | PHS_MESS_IN:
989 		DB(DB_INTR, printk("MSG_IN="))
990 
991 		msg = read_1_byte(regs);
992 		sr = read_wd33c93(regs, WD_SCSI_STATUS);	/* clear interrupt */
993 		udelay(7);
994 
995 		hostdata->incoming_msg[hostdata->incoming_ptr] = msg;
996 		if (hostdata->incoming_msg[0] == EXTENDED_MESSAGE)
997 			msg = EXTENDED_MESSAGE;
998 		else
999 			hostdata->incoming_ptr = 0;
1000 
1001 		scsi_pointer->Message = msg;
1002 		switch (msg) {
1003 
1004 		case COMMAND_COMPLETE:
1005 			DB(DB_INTR, printk("CCMP"))
1006 			    write_wd33c93_cmd(regs, WD_CMD_NEGATE_ACK);
1007 			hostdata->state = S_PRE_CMP_DISC;
1008 			break;
1009 
1010 		case SAVE_POINTERS:
1011 			DB(DB_INTR, printk("SDP"))
1012 			    write_wd33c93_cmd(regs, WD_CMD_NEGATE_ACK);
1013 			hostdata->state = S_CONNECTED;
1014 			break;
1015 
1016 		case RESTORE_POINTERS:
1017 			DB(DB_INTR, printk("RDP"))
1018 			    if (hostdata->level2 >= L2_BASIC) {
1019 				write_wd33c93(regs, WD_COMMAND_PHASE, 0x45);
1020 				write_wd33c93_cmd(regs, WD_CMD_SEL_ATN_XFER);
1021 				hostdata->state = S_RUNNING_LEVEL2;
1022 			} else {
1023 				write_wd33c93_cmd(regs, WD_CMD_NEGATE_ACK);
1024 				hostdata->state = S_CONNECTED;
1025 			}
1026 			break;
1027 
1028 		case DISCONNECT:
1029 			DB(DB_INTR, printk("DIS"))
1030 			    cmd->device->disconnect = 1;
1031 			write_wd33c93_cmd(regs, WD_CMD_NEGATE_ACK);
1032 			hostdata->state = S_PRE_TMP_DISC;
1033 			break;
1034 
1035 		case MESSAGE_REJECT:
1036 			DB(DB_INTR, printk("REJ"))
1037 #ifdef SYNC_DEBUG
1038 			    printk("-REJ-");
1039 #endif
1040 			if (hostdata->sync_stat[cmd->device->id] == SS_WAITING) {
1041 				hostdata->sync_stat[cmd->device->id] = SS_SET;
1042 				/* we want default_sx_per, not DEFAULT_SX_PER */
1043 				hostdata->sync_xfer[cmd->device->id] =
1044 					calc_sync_xfer(hostdata->default_sx_per
1045 						/ 4, 0, 0, hostdata->sx_table);
1046 			}
1047 			write_wd33c93_cmd(regs, WD_CMD_NEGATE_ACK);
1048 			hostdata->state = S_CONNECTED;
1049 			break;
1050 
1051 		case EXTENDED_MESSAGE:
1052 			DB(DB_INTR, printk("EXT"))
1053 
1054 			    ucp = hostdata->incoming_msg;
1055 
1056 #ifdef SYNC_DEBUG
1057 			printk("%02x", ucp[hostdata->incoming_ptr]);
1058 #endif
1059 			/* Is this the last byte of the extended message? */
1060 
1061 			if ((hostdata->incoming_ptr >= 2) &&
1062 			    (hostdata->incoming_ptr == (ucp[1] + 1))) {
1063 
1064 				switch (ucp[2]) {	/* what's the EXTENDED code? */
1065 				case EXTENDED_SDTR:
1066 					/* default to default async period */
1067 					id = calc_sync_xfer(hostdata->
1068 							default_sx_per / 4, 0,
1069 							0, hostdata->sx_table);
1070 					if (hostdata->sync_stat[cmd->device->id] !=
1071 					    SS_WAITING) {
1072 
1073 /* A device has sent an unsolicited SDTR message; rather than go
1074  * through the effort of decoding it and then figuring out what
1075  * our reply should be, we're just gonna say that we have a
1076  * synchronous fifo depth of 0. This will result in asynchronous
1077  * transfers - not ideal but so much easier.
1078  * Actually, this is OK because it assures us that if we don't
1079  * specifically ask for sync transfers, we won't do any.
1080  */
1081 
1082 						write_wd33c93_cmd(regs, WD_CMD_ASSERT_ATN);	/* want MESS_OUT */
1083 						hostdata->outgoing_msg[0] =
1084 						    EXTENDED_MESSAGE;
1085 						hostdata->outgoing_msg[1] = 3;
1086 						hostdata->outgoing_msg[2] =
1087 						    EXTENDED_SDTR;
1088 						calc_sync_msg(hostdata->
1089 							default_sx_per, 0,
1090 							0, hostdata->outgoing_msg + 3);
1091 						hostdata->outgoing_len = 5;
1092 					} else {
1093 						if (ucp[4]) /* well, sync transfer */
1094 							id = calc_sync_xfer(ucp[3], ucp[4],
1095 									hostdata->fast,
1096 									hostdata->sx_table);
1097 						else if (ucp[3]) /* very unlikely... */
1098 							id = calc_sync_xfer(ucp[3], ucp[4],
1099 									0, hostdata->sx_table);
1100 					}
1101 					hostdata->sync_xfer[cmd->device->id] = id;
1102 #ifdef SYNC_DEBUG
1103 					printk(" sync_xfer=%02x\n",
1104 					       hostdata->sync_xfer[cmd->device->id]);
1105 #endif
1106 					hostdata->sync_stat[cmd->device->id] =
1107 					    SS_SET;
1108 					write_wd33c93_cmd(regs,
1109 							  WD_CMD_NEGATE_ACK);
1110 					hostdata->state = S_CONNECTED;
1111 					break;
1112 				case EXTENDED_WDTR:
1113 					write_wd33c93_cmd(regs, WD_CMD_ASSERT_ATN);	/* want MESS_OUT */
1114 					printk("sending WDTR ");
1115 					hostdata->outgoing_msg[0] =
1116 					    EXTENDED_MESSAGE;
1117 					hostdata->outgoing_msg[1] = 2;
1118 					hostdata->outgoing_msg[2] =
1119 					    EXTENDED_WDTR;
1120 					hostdata->outgoing_msg[3] = 0;	/* 8 bit transfer width */
1121 					hostdata->outgoing_len = 4;
1122 					write_wd33c93_cmd(regs,
1123 							  WD_CMD_NEGATE_ACK);
1124 					hostdata->state = S_CONNECTED;
1125 					break;
1126 				default:
1127 					write_wd33c93_cmd(regs, WD_CMD_ASSERT_ATN);	/* want MESS_OUT */
1128 					printk
1129 					    ("Rejecting Unknown Extended Message(%02x). ",
1130 					     ucp[2]);
1131 					hostdata->outgoing_msg[0] =
1132 					    MESSAGE_REJECT;
1133 					hostdata->outgoing_len = 1;
1134 					write_wd33c93_cmd(regs,
1135 							  WD_CMD_NEGATE_ACK);
1136 					hostdata->state = S_CONNECTED;
1137 					break;
1138 				}
1139 				hostdata->incoming_ptr = 0;
1140 			}
1141 
1142 			/* We need to read more MESS_IN bytes for the extended message */
1143 
1144 			else {
1145 				hostdata->incoming_ptr++;
1146 				write_wd33c93_cmd(regs, WD_CMD_NEGATE_ACK);
1147 				hostdata->state = S_CONNECTED;
1148 			}
1149 			break;
1150 
1151 		default:
1152 			printk("Rejecting Unknown Message(%02x) ", msg);
1153 			write_wd33c93_cmd(regs, WD_CMD_ASSERT_ATN);	/* want MESS_OUT */
1154 			hostdata->outgoing_msg[0] = MESSAGE_REJECT;
1155 			hostdata->outgoing_len = 1;
1156 			write_wd33c93_cmd(regs, WD_CMD_NEGATE_ACK);
1157 			hostdata->state = S_CONNECTED;
1158 		}
1159 		spin_unlock_irqrestore(&hostdata->lock, flags);
1160 		break;
1161 
1162 /* Note: this interrupt will occur only after a LEVEL2 command */
1163 
1164 	case CSR_SEL_XFER_DONE:
1165 
1166 /* Make sure that reselection is enabled at this point - it may
1167  * have been turned off for the command that just completed.
1168  */
1169 
1170 		write_wd33c93(regs, WD_SOURCE_ID, SRCID_ER);
1171 		if (phs == 0x60) {
1172 			DB(DB_INTR, printk("SX-DONE"))
1173 			    scsi_pointer->Message = COMMAND_COMPLETE;
1174 			lun = read_wd33c93(regs, WD_TARGET_LUN);
1175 			DB(DB_INTR, printk(":%d.%d", scsi_pointer->Status, lun))
1176 			    hostdata->connected = NULL;
1177 			hostdata->busy[cmd->device->id] &= ~(1 << (cmd->device->lun & 0xff));
1178 			hostdata->state = S_UNCONNECTED;
1179 			if (scsi_pointer->Status == ILLEGAL_STATUS_BYTE)
1180 				scsi_pointer->Status = lun;
1181 			if (cmd->cmnd[0] == REQUEST_SENSE
1182 			    && scsi_pointer->Status != SAM_STAT_GOOD) {
1183 				set_host_byte(cmd, DID_ERROR);
1184 			} else {
1185 				set_host_byte(cmd, DID_OK);
1186 				scsi_msg_to_host_byte(cmd, scsi_pointer->Message);
1187 				set_status_byte(cmd, scsi_pointer->Status);
1188 			}
1189 			scsi_done(cmd);
1190 
1191 /* We are no longer  connected to a target - check to see if
1192  * there are commands waiting to be executed.
1193  */
1194 			spin_unlock_irqrestore(&hostdata->lock, flags);
1195 			wd33c93_execute(instance);
1196 		} else {
1197 			printk
1198 			    ("%02x:%02x:%02x: Unknown SEL_XFER_DONE phase!!---",
1199 			     asr, sr, phs);
1200 			spin_unlock_irqrestore(&hostdata->lock, flags);
1201 		}
1202 		break;
1203 
1204 /* Note: this interrupt will occur only after a LEVEL2 command */
1205 
1206 	case CSR_SDP:
1207 		DB(DB_INTR, printk("SDP"))
1208 		    hostdata->state = S_RUNNING_LEVEL2;
1209 		write_wd33c93(regs, WD_COMMAND_PHASE, 0x41);
1210 		write_wd33c93_cmd(regs, WD_CMD_SEL_ATN_XFER);
1211 		spin_unlock_irqrestore(&hostdata->lock, flags);
1212 		break;
1213 
1214 	case CSR_XFER_DONE | PHS_MESS_OUT:
1215 	case CSR_UNEXP | PHS_MESS_OUT:
1216 	case CSR_SRV_REQ | PHS_MESS_OUT:
1217 		DB(DB_INTR, printk("MSG_OUT="))
1218 
1219 /* To get here, we've probably requested MESSAGE_OUT and have
1220  * already put the correct bytes in outgoing_msg[] and filled
1221  * in outgoing_len. We simply send them out to the SCSI bus.
1222  * Sometimes we get MESSAGE_OUT phase when we're not expecting
1223  * it - like when our SDTR message is rejected by a target. Some
1224  * targets send the REJECT before receiving all of the extended
1225  * message, and then seem to go back to MESSAGE_OUT for a byte
1226  * or two. Not sure why, or if I'm doing something wrong to
1227  * cause this to happen. Regardless, it seems that sending
1228  * NOP messages in these situations results in no harm and
1229  * makes everyone happy.
1230  */
1231 		    if (hostdata->outgoing_len == 0) {
1232 			hostdata->outgoing_len = 1;
1233 			hostdata->outgoing_msg[0] = NOP;
1234 		}
1235 		transfer_pio(regs, hostdata->outgoing_msg,
1236 			     hostdata->outgoing_len, DATA_OUT_DIR, hostdata);
1237 		DB(DB_INTR, printk("%02x", hostdata->outgoing_msg[0]))
1238 		    hostdata->outgoing_len = 0;
1239 		hostdata->state = S_CONNECTED;
1240 		spin_unlock_irqrestore(&hostdata->lock, flags);
1241 		break;
1242 
1243 	case CSR_UNEXP_DISC:
1244 
1245 /* I think I've seen this after a request-sense that was in response
1246  * to an error condition, but not sure. We certainly need to do
1247  * something when we get this interrupt - the question is 'what?'.
1248  * Let's think positively, and assume some command has finished
1249  * in a legal manner (like a command that provokes a request-sense),
1250  * so we treat it as a normal command-complete-disconnect.
1251  */
1252 
1253 /* Make sure that reselection is enabled at this point - it may
1254  * have been turned off for the command that just completed.
1255  */
1256 
1257 		write_wd33c93(regs, WD_SOURCE_ID, SRCID_ER);
1258 		if (cmd == NULL) {
1259 			printk(" - Already disconnected! ");
1260 			hostdata->state = S_UNCONNECTED;
1261 			spin_unlock_irqrestore(&hostdata->lock, flags);
1262 			return;
1263 		}
1264 		DB(DB_INTR, printk("UNEXP_DISC"))
1265 		    hostdata->connected = NULL;
1266 		hostdata->busy[cmd->device->id] &= ~(1 << (cmd->device->lun & 0xff));
1267 		hostdata->state = S_UNCONNECTED;
1268 		if (cmd->cmnd[0] == REQUEST_SENSE &&
1269 		    scsi_pointer->Status != SAM_STAT_GOOD) {
1270 			set_host_byte(cmd, DID_ERROR);
1271 		} else {
1272 			set_host_byte(cmd, DID_OK);
1273 			scsi_msg_to_host_byte(cmd, scsi_pointer->Message);
1274 			set_status_byte(cmd, scsi_pointer->Status);
1275 		}
1276 		scsi_done(cmd);
1277 
1278 /* We are no longer connected to a target - check to see if
1279  * there are commands waiting to be executed.
1280  */
1281 		/* look above for comments on scsi_done() */
1282 		spin_unlock_irqrestore(&hostdata->lock, flags);
1283 		wd33c93_execute(instance);
1284 		break;
1285 
1286 	case CSR_DISC:
1287 
1288 /* Make sure that reselection is enabled at this point - it may
1289  * have been turned off for the command that just completed.
1290  */
1291 
1292 		write_wd33c93(regs, WD_SOURCE_ID, SRCID_ER);
1293 		DB(DB_INTR, printk("DISC"))
1294 		    if (cmd == NULL) {
1295 			printk(" - Already disconnected! ");
1296 			hostdata->state = S_UNCONNECTED;
1297 		}
1298 		switch (hostdata->state) {
1299 		case S_PRE_CMP_DISC:
1300 			hostdata->connected = NULL;
1301 			hostdata->busy[cmd->device->id] &= ~(1 << (cmd->device->lun & 0xff));
1302 			hostdata->state = S_UNCONNECTED;
1303 			DB(DB_INTR, printk(":%d", scsi_pointer->Status))
1304 			if (cmd->cmnd[0] == REQUEST_SENSE
1305 			    && scsi_pointer->Status != SAM_STAT_GOOD) {
1306 				set_host_byte(cmd, DID_ERROR);
1307 			} else {
1308 				set_host_byte(cmd, DID_OK);
1309 				scsi_msg_to_host_byte(cmd, scsi_pointer->Message);
1310 				set_status_byte(cmd, scsi_pointer->Status);
1311 			}
1312 			scsi_done(cmd);
1313 			break;
1314 		case S_PRE_TMP_DISC:
1315 		case S_RUNNING_LEVEL2:
1316 			cmd->host_scribble = (uchar *) hostdata->disconnected_Q;
1317 			hostdata->disconnected_Q = cmd;
1318 			hostdata->connected = NULL;
1319 			hostdata->state = S_UNCONNECTED;
1320 
1321 #ifdef PROC_STATISTICS
1322 			hostdata->disc_done_cnt[cmd->device->id]++;
1323 #endif
1324 
1325 			break;
1326 		default:
1327 			printk("*** Unexpected DISCONNECT interrupt! ***");
1328 			hostdata->state = S_UNCONNECTED;
1329 		}
1330 
1331 /* We are no longer connected to a target - check to see if
1332  * there are commands waiting to be executed.
1333  */
1334 		spin_unlock_irqrestore(&hostdata->lock, flags);
1335 		wd33c93_execute(instance);
1336 		break;
1337 
1338 	case CSR_RESEL_AM:
1339 	case CSR_RESEL:
1340 		DB(DB_INTR, printk("RESEL%s", sr == CSR_RESEL_AM ? "_AM" : ""))
1341 
1342 		    /* Old chips (pre -A ???) don't have advanced features and will
1343 		     * generate CSR_RESEL.  In that case we have to extract the LUN the
1344 		     * hard way (see below).
1345 		     * First we have to make sure this reselection didn't
1346 		     * happen during Arbitration/Selection of some other device.
1347 		     * If yes, put losing command back on top of input_Q.
1348 		     */
1349 		    if (hostdata->level2 <= L2_NONE) {
1350 
1351 			if (hostdata->selecting) {
1352 				cmd = (struct scsi_cmnd *) hostdata->selecting;
1353 				hostdata->selecting = NULL;
1354 				hostdata->busy[cmd->device->id] &= ~(1 << (cmd->device->lun & 0xff));
1355 				cmd->host_scribble =
1356 				    (uchar *) hostdata->input_Q;
1357 				hostdata->input_Q = cmd;
1358 			}
1359 		}
1360 
1361 		else {
1362 
1363 			if (cmd) {
1364 				if (phs == 0x00) {
1365 					hostdata->busy[cmd->device->id] &=
1366 						~(1 << (cmd->device->lun & 0xff));
1367 					cmd->host_scribble =
1368 					    (uchar *) hostdata->input_Q;
1369 					hostdata->input_Q = cmd;
1370 				} else {
1371 					printk
1372 					    ("---%02x:%02x:%02x-TROUBLE: Intrusive ReSelect!---",
1373 					     asr, sr, phs);
1374 					while (1)
1375 						printk("\r");
1376 				}
1377 			}
1378 
1379 		}
1380 
1381 		/* OK - find out which device reselected us. */
1382 
1383 		id = read_wd33c93(regs, WD_SOURCE_ID);
1384 		id &= SRCID_MASK;
1385 
1386 		/* and extract the lun from the ID message. (Note that we don't
1387 		 * bother to check for a valid message here - I guess this is
1388 		 * not the right way to go, but...)
1389 		 */
1390 
1391 		if (sr == CSR_RESEL_AM) {
1392 			lun = read_wd33c93(regs, WD_DATA);
1393 			if (hostdata->level2 < L2_RESELECT)
1394 				write_wd33c93_cmd(regs, WD_CMD_NEGATE_ACK);
1395 			lun &= 7;
1396 		} else {
1397 			/* Old chip; wait for msgin phase to pick up the LUN. */
1398 			for (lun = 255; lun; lun--) {
1399 				if ((asr = read_aux_stat(regs)) & ASR_INT)
1400 					break;
1401 				udelay(10);
1402 			}
1403 			if (!(asr & ASR_INT)) {
1404 				printk
1405 				    ("wd33c93: Reselected without IDENTIFY\n");
1406 				lun = 0;
1407 			} else {
1408 				/* Verify this is a change to MSG_IN and read the message */
1409 				sr = read_wd33c93(regs, WD_SCSI_STATUS);
1410 				udelay(7);
1411 				if (sr == (CSR_ABORT | PHS_MESS_IN) ||
1412 				    sr == (CSR_UNEXP | PHS_MESS_IN) ||
1413 				    sr == (CSR_SRV_REQ | PHS_MESS_IN)) {
1414 					/* Got MSG_IN, grab target LUN */
1415 					lun = read_1_byte(regs);
1416 					/* Now we expect a 'paused with ACK asserted' int.. */
1417 					asr = read_aux_stat(regs);
1418 					if (!(asr & ASR_INT)) {
1419 						udelay(10);
1420 						asr = read_aux_stat(regs);
1421 						if (!(asr & ASR_INT))
1422 							printk
1423 							    ("wd33c93: No int after LUN on RESEL (%02x)\n",
1424 							     asr);
1425 					}
1426 					sr = read_wd33c93(regs, WD_SCSI_STATUS);
1427 					udelay(7);
1428 					if (sr != CSR_MSGIN)
1429 						printk
1430 						    ("wd33c93: Not paused with ACK on RESEL (%02x)\n",
1431 						     sr);
1432 					lun &= 7;
1433 					write_wd33c93_cmd(regs,
1434 							  WD_CMD_NEGATE_ACK);
1435 				} else {
1436 					printk
1437 					    ("wd33c93: Not MSG_IN on reselect (%02x)\n",
1438 					     sr);
1439 					lun = 0;
1440 				}
1441 			}
1442 		}
1443 
1444 		/* Now we look for the command that's reconnecting. */
1445 
1446 		cmd = (struct scsi_cmnd *) hostdata->disconnected_Q;
1447 		patch = NULL;
1448 		while (cmd) {
1449 			if (id == cmd->device->id && lun == (u8)cmd->device->lun)
1450 				break;
1451 			patch = cmd;
1452 			cmd = (struct scsi_cmnd *) cmd->host_scribble;
1453 		}
1454 
1455 		/* Hmm. Couldn't find a valid command.... What to do? */
1456 
1457 		if (!cmd) {
1458 			printk
1459 			    ("---TROUBLE: target %d.%d not in disconnect queue---",
1460 			     id, (u8)lun);
1461 			spin_unlock_irqrestore(&hostdata->lock, flags);
1462 			return;
1463 		}
1464 
1465 		/* Ok, found the command - now start it up again. */
1466 
1467 		if (patch)
1468 			patch->host_scribble = cmd->host_scribble;
1469 		else
1470 			hostdata->disconnected_Q =
1471 			    (struct scsi_cmnd *) cmd->host_scribble;
1472 		hostdata->connected = cmd;
1473 
1474 		/* We don't need to worry about 'initialize_SCp()' or 'hostdata->busy[]'
1475 		 * because these things are preserved over a disconnect.
1476 		 * But we DO need to fix the DPD bit so it's correct for this command.
1477 		 */
1478 
1479 		if (cmd->sc_data_direction == DMA_TO_DEVICE)
1480 			write_wd33c93(regs, WD_DESTINATION_ID, cmd->device->id);
1481 		else
1482 			write_wd33c93(regs, WD_DESTINATION_ID,
1483 				      cmd->device->id | DSTID_DPD);
1484 		if (hostdata->level2 >= L2_RESELECT) {
1485 			write_wd33c93_count(regs, 0);	/* we want a DATA_PHASE interrupt */
1486 			write_wd33c93(regs, WD_COMMAND_PHASE, 0x45);
1487 			write_wd33c93_cmd(regs, WD_CMD_SEL_ATN_XFER);
1488 			hostdata->state = S_RUNNING_LEVEL2;
1489 		} else
1490 			hostdata->state = S_CONNECTED;
1491 
1492 		    spin_unlock_irqrestore(&hostdata->lock, flags);
1493 		break;
1494 
1495 	default:
1496 		printk("--UNKNOWN INTERRUPT:%02x:%02x:%02x--", asr, sr, phs);
1497 		spin_unlock_irqrestore(&hostdata->lock, flags);
1498 	}
1499 
1500 	DB(DB_INTR, printk("} "))
1501 
1502 }
1503 
1504 static void
1505 reset_wd33c93(struct Scsi_Host *instance)
1506 {
1507 	struct WD33C93_hostdata *hostdata =
1508 	    (struct WD33C93_hostdata *) instance->hostdata;
1509 	const wd33c93_regs regs = hostdata->regs;
1510 	uchar sr;
1511 
1512 #ifdef CONFIG_SGI_IP22
1513 	{
1514 		int busycount = 0;
1515 		extern void sgiwd93_reset(unsigned long);
1516 		/* wait 'til the chip gets some time for us */
1517 		while ((read_aux_stat(regs) & ASR_BSY) && busycount++ < 100)
1518 			udelay (10);
1519 	/*
1520  	 * there are scsi devices out there, which manage to lock up
1521 	 * the wd33c93 in a busy condition. In this state it won't
1522 	 * accept the reset command. The only way to solve this is to
1523  	 * give the chip a hardware reset (if possible). The code below
1524 	 * does this for the SGI Indy, where this is possible
1525 	 */
1526 	/* still busy ? */
1527 	if (read_aux_stat(regs) & ASR_BSY)
1528 		sgiwd93_reset(instance->base); /* yeah, give it the hard one */
1529 	}
1530 #endif
1531 
1532 	write_wd33c93(regs, WD_OWN_ID, OWNID_EAF | OWNID_RAF |
1533 		      instance->this_id | hostdata->clock_freq);
1534 	write_wd33c93(regs, WD_CONTROL, CTRL_IDI | CTRL_EDI | CTRL_POLLED);
1535 	write_wd33c93(regs, WD_SYNCHRONOUS_TRANSFER,
1536 		      calc_sync_xfer(hostdata->default_sx_per / 4,
1537 				     DEFAULT_SX_OFF, 0, hostdata->sx_table));
1538 	write_wd33c93(regs, WD_COMMAND, WD_CMD_RESET);
1539 
1540 
1541 #ifdef CONFIG_MVME147_SCSI
1542 	udelay(25);		/* The old wd33c93 on MVME147 needs this, at least */
1543 #endif
1544 
1545 	while (!(read_aux_stat(regs) & ASR_INT))
1546 		;
1547 	sr = read_wd33c93(regs, WD_SCSI_STATUS);
1548 
1549 	hostdata->microcode = read_wd33c93(regs, WD_CDB_1);
1550 	if (sr == 0x00)
1551 		hostdata->chip = C_WD33C93;
1552 	else if (sr == 0x01) {
1553 		write_wd33c93(regs, WD_QUEUE_TAG, 0xa5);	/* any random number */
1554 		sr = read_wd33c93(regs, WD_QUEUE_TAG);
1555 		if (sr == 0xa5) {
1556 			hostdata->chip = C_WD33C93B;
1557 			write_wd33c93(regs, WD_QUEUE_TAG, 0);
1558 		} else
1559 			hostdata->chip = C_WD33C93A;
1560 	} else
1561 		hostdata->chip = C_UNKNOWN_CHIP;
1562 
1563 	if (hostdata->chip != C_WD33C93B)	/* Fast SCSI unavailable */
1564 		hostdata->fast = 0;
1565 
1566 	write_wd33c93(regs, WD_TIMEOUT_PERIOD, TIMEOUT_PERIOD_VALUE);
1567 	write_wd33c93(regs, WD_CONTROL, CTRL_IDI | CTRL_EDI | CTRL_POLLED);
1568 }
1569 
1570 int
1571 wd33c93_host_reset(struct scsi_cmnd * SCpnt)
1572 {
1573 	struct Scsi_Host *instance;
1574 	struct WD33C93_hostdata *hostdata;
1575 	int i;
1576 
1577 	instance = SCpnt->device->host;
1578 	spin_lock_irq(instance->host_lock);
1579 	hostdata = (struct WD33C93_hostdata *) instance->hostdata;
1580 
1581 	printk("scsi%d: reset. ", instance->host_no);
1582 	disable_irq(instance->irq);
1583 
1584 	hostdata->dma_stop(instance, NULL, 0);
1585 	for (i = 0; i < 8; i++) {
1586 		hostdata->busy[i] = 0;
1587 		hostdata->sync_xfer[i] =
1588 			calc_sync_xfer(DEFAULT_SX_PER / 4, DEFAULT_SX_OFF,
1589 					0, hostdata->sx_table);
1590 		hostdata->sync_stat[i] = SS_UNSET;	/* using default sync values */
1591 	}
1592 	hostdata->input_Q = NULL;
1593 	hostdata->selecting = NULL;
1594 	hostdata->connected = NULL;
1595 	hostdata->disconnected_Q = NULL;
1596 	hostdata->state = S_UNCONNECTED;
1597 	hostdata->dma = D_DMA_OFF;
1598 	hostdata->incoming_ptr = 0;
1599 	hostdata->outgoing_len = 0;
1600 
1601 	reset_wd33c93(instance);
1602 	SCpnt->result = DID_RESET << 16;
1603 	enable_irq(instance->irq);
1604 	spin_unlock_irq(instance->host_lock);
1605 	return SUCCESS;
1606 }
1607 
1608 int
1609 wd33c93_abort(struct scsi_cmnd * cmd)
1610 {
1611 	struct Scsi_Host *instance;
1612 	struct WD33C93_hostdata *hostdata;
1613 	wd33c93_regs regs;
1614 	struct scsi_cmnd *tmp, *prev;
1615 
1616 	disable_irq(cmd->device->host->irq);
1617 
1618 	instance = cmd->device->host;
1619 	hostdata = (struct WD33C93_hostdata *) instance->hostdata;
1620 	regs = hostdata->regs;
1621 
1622 /*
1623  * Case 1 : If the command hasn't been issued yet, we simply remove it
1624  *     from the input_Q.
1625  */
1626 
1627 	tmp = (struct scsi_cmnd *) hostdata->input_Q;
1628 	prev = NULL;
1629 	while (tmp) {
1630 		if (tmp == cmd) {
1631 			if (prev)
1632 				prev->host_scribble = cmd->host_scribble;
1633 			else
1634 				hostdata->input_Q =
1635 				    (struct scsi_cmnd *) cmd->host_scribble;
1636 			cmd->host_scribble = NULL;
1637 			cmd->result = DID_ABORT << 16;
1638 			printk
1639 			    ("scsi%d: Abort - removing command from input_Q. ",
1640 			     instance->host_no);
1641 			enable_irq(cmd->device->host->irq);
1642 			scsi_done(cmd);
1643 			return SUCCESS;
1644 		}
1645 		prev = tmp;
1646 		tmp = (struct scsi_cmnd *) tmp->host_scribble;
1647 	}
1648 
1649 /*
1650  * Case 2 : If the command is connected, we're going to fail the abort
1651  *     and let the high level SCSI driver retry at a later time or
1652  *     issue a reset.
1653  *
1654  *     Timeouts, and therefore aborted commands, will be highly unlikely
1655  *     and handling them cleanly in this situation would make the common
1656  *     case of noresets less efficient, and would pollute our code.  So,
1657  *     we fail.
1658  */
1659 
1660 	if (hostdata->connected == cmd) {
1661 		uchar sr, asr;
1662 		unsigned long timeout;
1663 
1664 		printk("scsi%d: Aborting connected command - ",
1665 		       instance->host_no);
1666 
1667 		printk("stopping DMA - ");
1668 		if (hostdata->dma == D_DMA_RUNNING) {
1669 			hostdata->dma_stop(instance, cmd, 0);
1670 			hostdata->dma = D_DMA_OFF;
1671 		}
1672 
1673 		printk("sending wd33c93 ABORT command - ");
1674 		write_wd33c93(regs, WD_CONTROL,
1675 			      CTRL_IDI | CTRL_EDI | CTRL_POLLED);
1676 		write_wd33c93_cmd(regs, WD_CMD_ABORT);
1677 
1678 /* Now we have to attempt to flush out the FIFO... */
1679 
1680 		printk("flushing fifo - ");
1681 		timeout = 1000000;
1682 		do {
1683 			asr = read_aux_stat(regs);
1684 			if (asr & ASR_DBR)
1685 				read_wd33c93(regs, WD_DATA);
1686 		} while (!(asr & ASR_INT) && timeout-- > 0);
1687 		sr = read_wd33c93(regs, WD_SCSI_STATUS);
1688 		printk
1689 		    ("asr=%02x, sr=%02x, %ld bytes un-transferred (timeout=%ld) - ",
1690 		     asr, sr, read_wd33c93_count(regs), timeout);
1691 
1692 		/*
1693 		 * Abort command processed.
1694 		 * Still connected.
1695 		 * We must disconnect.
1696 		 */
1697 
1698 		printk("sending wd33c93 DISCONNECT command - ");
1699 		write_wd33c93_cmd(regs, WD_CMD_DISCONNECT);
1700 
1701 		timeout = 1000000;
1702 		asr = read_aux_stat(regs);
1703 		while ((asr & ASR_CIP) && timeout-- > 0)
1704 			asr = read_aux_stat(regs);
1705 		sr = read_wd33c93(regs, WD_SCSI_STATUS);
1706 		printk("asr=%02x, sr=%02x.", asr, sr);
1707 
1708 		hostdata->busy[cmd->device->id] &= ~(1 << (cmd->device->lun & 0xff));
1709 		hostdata->connected = NULL;
1710 		hostdata->state = S_UNCONNECTED;
1711 		cmd->result = DID_ABORT << 16;
1712 
1713 /*      sti();*/
1714 		wd33c93_execute(instance);
1715 
1716 		enable_irq(cmd->device->host->irq);
1717 		scsi_done(cmd);
1718 		return SUCCESS;
1719 	}
1720 
1721 /*
1722  * Case 3: If the command is currently disconnected from the bus,
1723  * we're not going to expend much effort here: Let's just return
1724  * an ABORT_SNOOZE and hope for the best...
1725  */
1726 
1727 	tmp = (struct scsi_cmnd *) hostdata->disconnected_Q;
1728 	while (tmp) {
1729 		if (tmp == cmd) {
1730 			printk
1731 			    ("scsi%d: Abort - command found on disconnected_Q - ",
1732 			     instance->host_no);
1733 			printk("Abort SNOOZE. ");
1734 			enable_irq(cmd->device->host->irq);
1735 			return FAILED;
1736 		}
1737 		tmp = (struct scsi_cmnd *) tmp->host_scribble;
1738 	}
1739 
1740 /*
1741  * Case 4 : If we reached this point, the command was not found in any of
1742  *     the queues.
1743  *
1744  * We probably reached this point because of an unlikely race condition
1745  * between the command completing successfully and the abortion code,
1746  * so we won't panic, but we will notify the user in case something really
1747  * broke.
1748  */
1749 
1750 /*   sti();*/
1751 	wd33c93_execute(instance);
1752 
1753 	enable_irq(cmd->device->host->irq);
1754 	printk("scsi%d: warning : SCSI command probably completed successfully"
1755 	       "         before abortion. ", instance->host_no);
1756 	return FAILED;
1757 }
1758 
1759 #define MAX_WD33C93_HOSTS 4
1760 #define MAX_SETUP_ARGS ARRAY_SIZE(setup_args)
1761 #define SETUP_BUFFER_SIZE 200
1762 static char setup_buffer[SETUP_BUFFER_SIZE];
1763 static char setup_used[MAX_SETUP_ARGS];
1764 static int done_setup = 0;
1765 
1766 static int
1767 wd33c93_setup(char *str)
1768 {
1769 	int i;
1770 	char *p1, *p2;
1771 
1772 	/* The kernel does some processing of the command-line before calling
1773 	 * this function: If it begins with any decimal or hex number arguments,
1774 	 * ints[0] = how many numbers found and ints[1] through [n] are the values
1775 	 * themselves. str points to where the non-numeric arguments (if any)
1776 	 * start: We do our own parsing of those. We construct synthetic 'nosync'
1777 	 * keywords out of numeric args (to maintain compatibility with older
1778 	 * versions) and then add the rest of the arguments.
1779 	 */
1780 
1781 	p1 = setup_buffer;
1782 	*p1 = '\0';
1783 	if (str)
1784 		strncpy(p1, str, SETUP_BUFFER_SIZE - strlen(setup_buffer));
1785 	setup_buffer[SETUP_BUFFER_SIZE - 1] = '\0';
1786 	p1 = setup_buffer;
1787 	i = 0;
1788 	while (*p1 && (i < MAX_SETUP_ARGS)) {
1789 		p2 = strchr(p1, ',');
1790 		if (p2) {
1791 			*p2 = '\0';
1792 			if (p1 != p2)
1793 				setup_args[i] = p1;
1794 			p1 = p2 + 1;
1795 			i++;
1796 		} else {
1797 			setup_args[i] = p1;
1798 			break;
1799 		}
1800 	}
1801 	for (i = 0; i < MAX_SETUP_ARGS; i++)
1802 		setup_used[i] = 0;
1803 	done_setup = 1;
1804 
1805 	return 1;
1806 }
1807 __setup("wd33c93=", wd33c93_setup);
1808 
1809 /* check_setup_args() returns index if key found, 0 if not
1810  */
1811 static int
1812 check_setup_args(char *key, int *flags, int *val, char *buf)
1813 {
1814 	int x;
1815 	char *cp;
1816 
1817 	for (x = 0; x < MAX_SETUP_ARGS; x++) {
1818 		if (setup_used[x])
1819 			continue;
1820 		if (!strncmp(setup_args[x], key, strlen(key)))
1821 			break;
1822 		if (!strncmp(setup_args[x], "next", strlen("next")))
1823 			return 0;
1824 	}
1825 	if (x == MAX_SETUP_ARGS)
1826 		return 0;
1827 	setup_used[x] = 1;
1828 	cp = setup_args[x] + strlen(key);
1829 	*val = -1;
1830 	if (*cp != ':')
1831 		return ++x;
1832 	cp++;
1833 	if ((*cp >= '0') && (*cp <= '9')) {
1834 		*val = simple_strtoul(cp, NULL, 0);
1835 	}
1836 	return ++x;
1837 }
1838 
1839 /*
1840  * Calculate internal data-transfer-clock cycle from input-clock
1841  * frequency (/MHz) and fill 'sx_table'.
1842  *
1843  * The original driver used to rely on a fixed sx_table, containing periods
1844  * for (only) the lower limits of the respective input-clock-frequency ranges
1845  * (8-10/12-15/16-20 MHz). Although it seems, that no problems occurred with
1846  * this setting so far, it might be desirable to adjust the transfer periods
1847  * closer to the really attached, possibly 25% higher, input-clock, since
1848  * - the wd33c93 may really use a significant shorter period, than it has
1849  *   negotiated (eg. thrashing the target, which expects 4/8MHz, with 5/10MHz
1850  *   instead).
1851  * - the wd33c93 may ask the target for a lower transfer rate, than the target
1852  *   is capable of (eg. negotiating for an assumed minimum of 252ns instead of
1853  *   possible 200ns, which indeed shows up in tests as an approx. 10% lower
1854  *   transfer rate).
1855  */
1856 static inline unsigned int
1857 round_4(unsigned int x)
1858 {
1859 	switch (x & 3) {
1860 		case 1: --x;
1861 			break;
1862 		case 2: ++x;
1863 			fallthrough;
1864 		case 3: ++x;
1865 	}
1866 	return x;
1867 }
1868 
1869 static void
1870 calc_sx_table(unsigned int mhz, struct sx_period sx_table[9])
1871 {
1872 	unsigned int d, i;
1873 	if (mhz < 11)
1874 		d = 2;	/* divisor for  8-10 MHz input-clock */
1875 	else if (mhz < 16)
1876 		d = 3;	/* divisor for 12-15 MHz input-clock */
1877 	else
1878 		d = 4;	/* divisor for 16-20 MHz input-clock */
1879 
1880 	d = (100000 * d) / 2 / mhz; /* 100 x DTCC / nanosec */
1881 
1882 	sx_table[0].period_ns = 1;
1883 	sx_table[0].reg_value = 0x20;
1884 	for (i = 1; i < 8; i++) {
1885 		sx_table[i].period_ns = round_4((i+1)*d / 100);
1886 		sx_table[i].reg_value = (i+1)*0x10;
1887 	}
1888 	sx_table[7].reg_value = 0;
1889 	sx_table[8].period_ns = 0;
1890 	sx_table[8].reg_value = 0;
1891 }
1892 
1893 /*
1894  * check and, maybe, map an init- or "clock:"- argument.
1895  */
1896 static uchar
1897 set_clk_freq(int freq, int *mhz)
1898 {
1899 	int x = freq;
1900 	if (WD33C93_FS_8_10 == freq)
1901 		freq = 8;
1902 	else if (WD33C93_FS_12_15 == freq)
1903 		freq = 12;
1904 	else if (WD33C93_FS_16_20 == freq)
1905 		freq = 16;
1906 	else if (freq > 7 && freq < 11)
1907 		x = WD33C93_FS_8_10;
1908 		else if (freq > 11 && freq < 16)
1909 		x = WD33C93_FS_12_15;
1910 		else if (freq > 15 && freq < 21)
1911 		x = WD33C93_FS_16_20;
1912 	else {
1913 			/* Hmm, wouldn't it be safer to assume highest freq here? */
1914 		x = WD33C93_FS_8_10;
1915 		freq = 8;
1916 	}
1917 	*mhz = freq;
1918 	return x;
1919 }
1920 
1921 /*
1922  * to be used with the resync: fast: ... options
1923  */
1924 static inline void set_resync ( struct WD33C93_hostdata *hd, int mask )
1925 {
1926 	int i;
1927 	for (i = 0; i < 8; i++)
1928 		if (mask & (1 << i))
1929 			hd->sync_stat[i] = SS_UNSET;
1930 }
1931 
1932 void
1933 wd33c93_init(struct Scsi_Host *instance, const wd33c93_regs regs,
1934 	     dma_setup_t setup, dma_stop_t stop, int clock_freq)
1935 {
1936 	struct WD33C93_hostdata *hostdata;
1937 	int i;
1938 	int flags;
1939 	int val;
1940 	char buf[32];
1941 
1942 	if (!done_setup && setup_strings)
1943 		wd33c93_setup(setup_strings);
1944 
1945 	hostdata = (struct WD33C93_hostdata *) instance->hostdata;
1946 
1947 	hostdata->regs = regs;
1948 	hostdata->clock_freq = set_clk_freq(clock_freq, &i);
1949 	calc_sx_table(i, hostdata->sx_table);
1950 	hostdata->dma_setup = setup;
1951 	hostdata->dma_stop = stop;
1952 	hostdata->dma_bounce_buffer = NULL;
1953 	hostdata->dma_bounce_len = 0;
1954 	for (i = 0; i < 8; i++) {
1955 		hostdata->busy[i] = 0;
1956 		hostdata->sync_xfer[i] =
1957 			calc_sync_xfer(DEFAULT_SX_PER / 4, DEFAULT_SX_OFF,
1958 					0, hostdata->sx_table);
1959 		hostdata->sync_stat[i] = SS_UNSET;	/* using default sync values */
1960 #ifdef PROC_STATISTICS
1961 		hostdata->cmd_cnt[i] = 0;
1962 		hostdata->disc_allowed_cnt[i] = 0;
1963 		hostdata->disc_done_cnt[i] = 0;
1964 #endif
1965 	}
1966 	hostdata->input_Q = NULL;
1967 	hostdata->selecting = NULL;
1968 	hostdata->connected = NULL;
1969 	hostdata->disconnected_Q = NULL;
1970 	hostdata->state = S_UNCONNECTED;
1971 	hostdata->dma = D_DMA_OFF;
1972 	hostdata->level2 = L2_BASIC;
1973 	hostdata->disconnect = DIS_ADAPTIVE;
1974 	hostdata->args = DEBUG_DEFAULTS;
1975 	hostdata->incoming_ptr = 0;
1976 	hostdata->outgoing_len = 0;
1977 	hostdata->default_sx_per = DEFAULT_SX_PER;
1978 	hostdata->no_dma = 0;	/* default is DMA enabled */
1979 
1980 #ifdef PROC_INTERFACE
1981 	hostdata->proc = PR_VERSION | PR_INFO | PR_STATISTICS |
1982 	    PR_CONNECTED | PR_INPUTQ | PR_DISCQ | PR_STOP;
1983 #ifdef PROC_STATISTICS
1984 	hostdata->dma_cnt = 0;
1985 	hostdata->pio_cnt = 0;
1986 	hostdata->int_cnt = 0;
1987 #endif
1988 #endif
1989 
1990 	if (check_setup_args("clock", &flags, &val, buf)) {
1991 		hostdata->clock_freq = set_clk_freq(val, &val);
1992 		calc_sx_table(val, hostdata->sx_table);
1993 	}
1994 
1995 	if (check_setup_args("nosync", &flags, &val, buf))
1996 		hostdata->no_sync = val;
1997 
1998 	if (check_setup_args("nodma", &flags, &val, buf))
1999 		hostdata->no_dma = (val == -1) ? 1 : val;
2000 
2001 	if (check_setup_args("period", &flags, &val, buf))
2002 		hostdata->default_sx_per =
2003 		    hostdata->sx_table[round_period((unsigned int) val,
2004 		                                    hostdata->sx_table)].period_ns;
2005 
2006 	if (check_setup_args("disconnect", &flags, &val, buf)) {
2007 		if ((val >= DIS_NEVER) && (val <= DIS_ALWAYS))
2008 			hostdata->disconnect = val;
2009 		else
2010 			hostdata->disconnect = DIS_ADAPTIVE;
2011 	}
2012 
2013 	if (check_setup_args("level2", &flags, &val, buf))
2014 		hostdata->level2 = val;
2015 
2016 	if (check_setup_args("debug", &flags, &val, buf))
2017 		hostdata->args = val & DB_MASK;
2018 
2019 	if (check_setup_args("burst", &flags, &val, buf))
2020 		hostdata->dma_mode = val ? CTRL_BURST:CTRL_DMA;
2021 
2022 	if (WD33C93_FS_16_20 == hostdata->clock_freq /* divisor 4 */
2023 		&& check_setup_args("fast", &flags, &val, buf))
2024 		hostdata->fast = !!val;
2025 
2026 	if ((i = check_setup_args("next", &flags, &val, buf))) {
2027 		while (i)
2028 			setup_used[--i] = 1;
2029 	}
2030 #ifdef PROC_INTERFACE
2031 	if (check_setup_args("proc", &flags, &val, buf))
2032 		hostdata->proc = val;
2033 #endif
2034 
2035 	spin_lock_irq(&hostdata->lock);
2036 	reset_wd33c93(instance);
2037 	spin_unlock_irq(&hostdata->lock);
2038 
2039 	printk("wd33c93-%d: chip=%s/%d no_sync=0x%x no_dma=%d",
2040 	       instance->host_no,
2041 	       (hostdata->chip == C_WD33C93) ? "WD33c93" : (hostdata->chip ==
2042 							    C_WD33C93A) ?
2043 	       "WD33c93A" : (hostdata->chip ==
2044 			     C_WD33C93B) ? "WD33c93B" : "unknown",
2045 	       hostdata->microcode, hostdata->no_sync, hostdata->no_dma);
2046 #ifdef DEBUGGING_ON
2047 	printk(" debug_flags=0x%02x\n", hostdata->args);
2048 #else
2049 	printk(" debugging=OFF\n");
2050 #endif
2051 	printk("           setup_args=");
2052 	for (i = 0; i < MAX_SETUP_ARGS; i++)
2053 		printk("%s,", setup_args[i]);
2054 	printk("\n");
2055 	printk("           Version %s - %s\n", WD33C93_VERSION, WD33C93_DATE);
2056 }
2057 
2058 int wd33c93_write_info(struct Scsi_Host *instance, char *buf, int len)
2059 {
2060 #ifdef PROC_INTERFACE
2061 	char *bp;
2062 	struct WD33C93_hostdata *hd;
2063 	int x;
2064 
2065 	hd = (struct WD33C93_hostdata *) instance->hostdata;
2066 
2067 /* We accept the following
2068  * keywords (same format as command-line, but arguments are not optional):
2069  *    debug
2070  *    disconnect
2071  *    period
2072  *    resync
2073  *    proc
2074  *    nodma
2075  *    level2
2076  *    burst
2077  *    fast
2078  *    nosync
2079  */
2080 
2081 	buf[len] = '\0';
2082 	for (bp = buf; *bp; ) {
2083 		while (',' == *bp || ' ' == *bp)
2084 			++bp;
2085 	if (!strncmp(bp, "debug:", 6)) {
2086 			hd->args = simple_strtoul(bp+6, &bp, 0) & DB_MASK;
2087 	} else if (!strncmp(bp, "disconnect:", 11)) {
2088 			x = simple_strtoul(bp+11, &bp, 0);
2089 		if (x < DIS_NEVER || x > DIS_ALWAYS)
2090 			x = DIS_ADAPTIVE;
2091 		hd->disconnect = x;
2092 	} else if (!strncmp(bp, "period:", 7)) {
2093 		x = simple_strtoul(bp+7, &bp, 0);
2094 		hd->default_sx_per =
2095 			hd->sx_table[round_period((unsigned int) x,
2096 						  hd->sx_table)].period_ns;
2097 	} else if (!strncmp(bp, "resync:", 7)) {
2098 			set_resync(hd, (int)simple_strtoul(bp+7, &bp, 0));
2099 	} else if (!strncmp(bp, "proc:", 5)) {
2100 			hd->proc = simple_strtoul(bp+5, &bp, 0);
2101 	} else if (!strncmp(bp, "nodma:", 6)) {
2102 			hd->no_dma = simple_strtoul(bp+6, &bp, 0);
2103 	} else if (!strncmp(bp, "level2:", 7)) {
2104 			hd->level2 = simple_strtoul(bp+7, &bp, 0);
2105 		} else if (!strncmp(bp, "burst:", 6)) {
2106 			hd->dma_mode =
2107 				simple_strtol(bp+6, &bp, 0) ? CTRL_BURST:CTRL_DMA;
2108 		} else if (!strncmp(bp, "fast:", 5)) {
2109 			x = !!simple_strtol(bp+5, &bp, 0);
2110 			if (x != hd->fast)
2111 				set_resync(hd, 0xff);
2112 			hd->fast = x;
2113 		} else if (!strncmp(bp, "nosync:", 7)) {
2114 			x = simple_strtoul(bp+7, &bp, 0);
2115 			set_resync(hd, x ^ hd->no_sync);
2116 			hd->no_sync = x;
2117 		} else {
2118 			break; /* unknown keyword,syntax-error,... */
2119 		}
2120 	}
2121 	return len;
2122 #else
2123 	return 0;
2124 #endif
2125 }
2126 
2127 int
2128 wd33c93_show_info(struct seq_file *m, struct Scsi_Host *instance)
2129 {
2130 #ifdef PROC_INTERFACE
2131 	struct WD33C93_hostdata *hd;
2132 	struct scsi_cmnd *cmd;
2133 	int x;
2134 
2135 	hd = (struct WD33C93_hostdata *) instance->hostdata;
2136 
2137 	spin_lock_irq(&hd->lock);
2138 	if (hd->proc & PR_VERSION)
2139 		seq_printf(m, "\nVersion %s - %s.",
2140 			WD33C93_VERSION, WD33C93_DATE);
2141 
2142 	if (hd->proc & PR_INFO) {
2143 		seq_printf(m, "\nclock_freq=%02x no_sync=%02x no_dma=%d"
2144 			" dma_mode=%02x fast=%d",
2145 			hd->clock_freq, hd->no_sync, hd->no_dma, hd->dma_mode, hd->fast);
2146 		seq_puts(m, "\nsync_xfer[] =       ");
2147 		for (x = 0; x < 7; x++)
2148 			seq_printf(m, "\t%02x", hd->sync_xfer[x]);
2149 		seq_puts(m, "\nsync_stat[] =       ");
2150 		for (x = 0; x < 7; x++)
2151 			seq_printf(m, "\t%02x", hd->sync_stat[x]);
2152 	}
2153 #ifdef PROC_STATISTICS
2154 	if (hd->proc & PR_STATISTICS) {
2155 		seq_puts(m, "\ncommands issued:    ");
2156 		for (x = 0; x < 7; x++)
2157 			seq_printf(m, "\t%ld", hd->cmd_cnt[x]);
2158 		seq_puts(m, "\ndisconnects allowed:");
2159 		for (x = 0; x < 7; x++)
2160 			seq_printf(m, "\t%ld", hd->disc_allowed_cnt[x]);
2161 		seq_puts(m, "\ndisconnects done:   ");
2162 		for (x = 0; x < 7; x++)
2163 			seq_printf(m, "\t%ld", hd->disc_done_cnt[x]);
2164 		seq_printf(m,
2165 			"\ninterrupts: %ld, DATA_PHASE ints: %ld DMA, %ld PIO",
2166 			hd->int_cnt, hd->dma_cnt, hd->pio_cnt);
2167 	}
2168 #endif
2169 	if (hd->proc & PR_CONNECTED) {
2170 		seq_puts(m, "\nconnected:     ");
2171 		if (hd->connected) {
2172 			cmd = (struct scsi_cmnd *) hd->connected;
2173 			seq_printf(m, " %d:%llu(%02x)",
2174 				cmd->device->id, cmd->device->lun, cmd->cmnd[0]);
2175 		}
2176 	}
2177 	if (hd->proc & PR_INPUTQ) {
2178 		seq_puts(m, "\ninput_Q:       ");
2179 		cmd = (struct scsi_cmnd *) hd->input_Q;
2180 		while (cmd) {
2181 			seq_printf(m, " %d:%llu(%02x)",
2182 				cmd->device->id, cmd->device->lun, cmd->cmnd[0]);
2183 			cmd = (struct scsi_cmnd *) cmd->host_scribble;
2184 		}
2185 	}
2186 	if (hd->proc & PR_DISCQ) {
2187 		seq_puts(m, "\ndisconnected_Q:");
2188 		cmd = (struct scsi_cmnd *) hd->disconnected_Q;
2189 		while (cmd) {
2190 			seq_printf(m, " %d:%llu(%02x)",
2191 				cmd->device->id, cmd->device->lun, cmd->cmnd[0]);
2192 			cmd = (struct scsi_cmnd *) cmd->host_scribble;
2193 		}
2194 	}
2195 	seq_putc(m, '\n');
2196 	spin_unlock_irq(&hd->lock);
2197 #endif				/* PROC_INTERFACE */
2198 	return 0;
2199 }
2200 
2201 EXPORT_SYMBOL(wd33c93_host_reset);
2202 EXPORT_SYMBOL(wd33c93_init);
2203 EXPORT_SYMBOL(wd33c93_abort);
2204 EXPORT_SYMBOL(wd33c93_queuecommand);
2205 EXPORT_SYMBOL(wd33c93_intr);
2206 EXPORT_SYMBOL(wd33c93_show_info);
2207 EXPORT_SYMBOL(wd33c93_write_info);
2208