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