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 "wd33c93.h"
93
94#define optimum_sx_per(hostdata) (hostdata)->sx_table[1].period_ns
95
96
97#define WD33C93_VERSION    "1.26++"
98#define WD33C93_DATE       "10/Feb/2007"
99
100MODULE_AUTHOR("John Shifflett");
101MODULE_DESCRIPTION("Generic WD33C93 SCSI driver");
102MODULE_LICENSE("GPL");
103
104/*
105 * 'setup_strings' is a single string used to pass operating parameters and
106 * settings from the kernel/module command-line to the driver. 'setup_args[]'
107 * is an array of strings that define the compile-time default values for
108 * these settings. If Linux boots with an amiboot or insmod command-line,
109 * those settings are combined with 'setup_args[]'. Note that amiboot
110 * command-lines are prefixed with "wd33c93=" while insmod uses a
111 * "setup_strings=" prefix. The driver recognizes the following keywords
112 * (lower case required) and arguments:
113 *
114 * -  nosync:bitmask -bitmask is a byte where the 1st 7 bits correspond with
115 *                    the 7 possible SCSI devices. Set a bit to negotiate for
116 *                    asynchronous transfers on that device. To maintain
117 *                    backwards compatibility, a command-line such as
118 *                    "wd33c93=255" will be automatically translated to
119 *                    "wd33c93=nosync:0xff".
120 * -  nodma:x        -x = 1 to disable DMA, x = 0 to enable it. Argument is
121 *                    optional - if not present, same as "nodma:1".
122 * -  period:ns      -ns is the minimum # of nanoseconds in a SCSI data transfer
123 *                    period. Default is 500; acceptable values are 250 - 1000.
124 * -  disconnect:x   -x = 0 to never allow disconnects, 2 to always allow them.
125 *                    x = 1 does 'adaptive' disconnects, which is the default
126 *                    and generally the best choice.
127 * -  debug:x        -If 'DEBUGGING_ON' is defined, x is a bit mask that causes
128 *                    various types of debug output to printed - see the DB_xxx
129 *                    defines in wd33c93.h
130 * -  clock:x        -x = clock input in MHz for WD33c93 chip. Normal values
131 *                    would be from 8 through 20. Default is 8.
132 * -  burst:x        -x = 1 to use Burst Mode (or Demand-Mode) DMA, x = 0 to use
133 *                    Single Byte DMA, which is the default. Argument is
134 *                    optional - if not present, same as "burst:1".
135 * -  fast:x         -x = 1 to enable Fast SCSI, which is only effective with
136 *                    input-clock divisor 4 (WD33C93_FS_16_20), x = 0 to disable
137 *                    it, which is the default.  Argument is optional - if not
138 *                    present, same as "fast:1".
139 * -  next           -No argument. Used to separate blocks of keywords when
140 *                    there's more than one host adapter in the system.
141 *
142 * Syntax Notes:
143 * -  Numeric arguments can be decimal or the '0x' form of hex notation. There
144 *    _must_ be a colon between a keyword and its numeric argument, with no
145 *    spaces.
146 * -  Keywords are separated by commas, no spaces, in the standard kernel
147 *    command-line manner.
148 * -  A keyword in the 'nth' comma-separated command-line member will overwrite
149 *    the 'nth' element of setup_args[]. A blank command-line member (in
150 *    other words, a comma with no preceding keyword) will _not_ overwrite
151 *    the corresponding setup_args[] element.
152 * -  If a keyword is used more than once, the first one applies to the first
153 *    SCSI host found, the second to the second card, etc, unless the 'next'
154 *    keyword is used to change the order.
155 *
156 * Some amiboot examples (for insmod, use 'setup_strings' instead of 'wd33c93'):
157 * -  wd33c93=nosync:255
158 * -  wd33c93=nodma
159 * -  wd33c93=nodma:1
160 * -  wd33c93=disconnect:2,nosync:0x08,period:250
161 * -  wd33c93=debug:0x1c
162 */
163
164/* Normally, no defaults are specified */
165static char *setup_args[] = { "", "", "", "", "", "", "", "", "", "" };
166
167static char *setup_strings;
168module_param(setup_strings, charp, 0);
169
170static void wd33c93_execute(struct Scsi_Host *instance);
171
172#ifdef CONFIG_WD33C93_PIO
173static inline uchar
174read_wd33c93(const wd33c93_regs regs, uchar reg_num)
175{
176	uchar data;
177
178	outb(reg_num, regs.SASR);
179	data = inb(regs.SCMD);
180	return data;
181}
182
183static inline unsigned long
184read_wd33c93_count(const wd33c93_regs regs)
185{
186	unsigned long value;
187
188	outb(WD_TRANSFER_COUNT_MSB, regs.SASR);
189	value = inb(regs.SCMD) << 16;
190	value |= inb(regs.SCMD) << 8;
191	value |= inb(regs.SCMD);
192	return value;
193}
194
195static inline uchar
196read_aux_stat(const wd33c93_regs regs)
197{
198	return inb(regs.SASR);
199}
200
201static inline void
202write_wd33c93(const wd33c93_regs regs, uchar reg_num, uchar value)
203{
204      outb(reg_num, regs.SASR);
205      outb(value, regs.SCMD);
206}
207
208static inline void
209write_wd33c93_count(const wd33c93_regs regs, unsigned long value)
210{
211	outb(WD_TRANSFER_COUNT_MSB, regs.SASR);
212	outb((value >> 16) & 0xff, regs.SCMD);
213	outb((value >> 8) & 0xff, regs.SCMD);
214	outb( value & 0xff, regs.SCMD);
215}
216
217#define write_wd33c93_cmd(regs, cmd) \
218	write_wd33c93((regs), WD_COMMAND, (cmd))
219
220static inline void
221write_wd33c93_cdb(const wd33c93_regs regs, uint len, uchar cmnd[])
222{
223	int i;
224
225	outb(WD_CDB_1, regs.SASR);
226	for (i=0; i<len; i++)
227		outb(cmnd[i], regs.SCMD);
228}
229
230#else /* CONFIG_WD33C93_PIO */
231static inline uchar
232read_wd33c93(const wd33c93_regs regs, uchar reg_num)
233{
234	*regs.SASR = reg_num;
235	mb();
236	return (*regs.SCMD);
237}
238
239static unsigned long
240read_wd33c93_count(const wd33c93_regs regs)
241{
242	unsigned long value;
243
244	*regs.SASR = WD_TRANSFER_COUNT_MSB;
245	mb();
246	value = *regs.SCMD << 16;
247	value |= *regs.SCMD << 8;
248	value |= *regs.SCMD;
249	mb();
250	return value;
251}
252
253static inline uchar
254read_aux_stat(const wd33c93_regs regs)
255{
256	return *regs.SASR;
257}
258
259static inline void
260write_wd33c93(const wd33c93_regs regs, uchar reg_num, uchar value)
261{
262	*regs.SASR = reg_num;
263	mb();
264	*regs.SCMD = value;
265	mb();
266}
267
268static void
269write_wd33c93_count(const wd33c93_regs regs, unsigned long value)
270{
271	*regs.SASR = WD_TRANSFER_COUNT_MSB;
272	mb();
273	*regs.SCMD = value >> 16;
274	*regs.SCMD = value >> 8;
275	*regs.SCMD = value;
276	mb();
277}
278
279static inline void
280write_wd33c93_cmd(const wd33c93_regs regs, uchar cmd)
281{
282	*regs.SASR = WD_COMMAND;
283	mb();
284	*regs.SCMD = cmd;
285	mb();
286}
287
288static inline void
289write_wd33c93_cdb(const wd33c93_regs regs, uint len, uchar cmnd[])
290{
291	int i;
292
293	*regs.SASR = WD_CDB_1;
294	for (i = 0; i < len; i++)
295		*regs.SCMD = cmnd[i];
296}
297#endif /* CONFIG_WD33C93_PIO */
298
299static inline uchar
300read_1_byte(const wd33c93_regs regs)
301{
302	uchar asr;
303	uchar x = 0;
304
305	write_wd33c93(regs, WD_CONTROL, CTRL_IDI | CTRL_EDI | CTRL_POLLED);
306	write_wd33c93_cmd(regs, WD_CMD_TRANS_INFO | 0x80);
307	do {
308		asr = read_aux_stat(regs);
309		if (asr & ASR_DBR)
310			x = read_wd33c93(regs, WD_DATA);
311	} while (!(asr & ASR_INT));
312	return x;
313}
314
315static int
316round_period(unsigned int period, const struct sx_period *sx_table)
317{
318	int x;
319
320	for (x = 1; sx_table[x].period_ns; x++) {
321		if ((period <= sx_table[x - 0].period_ns) &&
322		    (period > sx_table[x - 1].period_ns)) {
323			return x;
324		}
325	}
326	return 7;
327}
328
329/*
330 * Calculate Synchronous Transfer Register value from SDTR code.
331 */
332static uchar
333calc_sync_xfer(unsigned int period, unsigned int offset, unsigned int fast,
334               const struct sx_period *sx_table)
335{
336	/* When doing Fast SCSI synchronous data transfers, the corresponding
337	 * value in 'sx_table' is two times the actually used transfer period.
338	 */
339	uchar result;
340
341	if (offset && fast) {
342		fast = STR_FSS;
343		period *= 2;
344	} else {
345		fast = 0;
346	}
347	period *= 4;		/* convert SDTR code to ns */
348	result = sx_table[round_period(period,sx_table)].reg_value;
349	result |= (offset < OPTIMUM_SX_OFF) ? offset : OPTIMUM_SX_OFF;
350	result |= fast;
351	return result;
352}
353
354/*
355 * Calculate SDTR code bytes [3],[4] from period and offset.
356 */
357static inline void
358calc_sync_msg(unsigned int period, unsigned int offset, unsigned int fast,
359                uchar  msg[2])
360{
361	/* 'period' is a "normal"-mode value, like the ones in 'sx_table'. The
362	 * actually used transfer period for Fast SCSI synchronous data
363	 * transfers is half that value.
364	 */
365	period /= 4;
366	if (offset && fast)
367		period /= 2;
368	msg[0] = period;
369	msg[1] = offset;
370}
371
372int
373wd33c93_queuecommand(struct scsi_cmnd *cmd,
374		void (*done)(struct scsi_cmnd *))
375{
376	struct WD33C93_hostdata *hostdata;
377	struct scsi_cmnd *tmp;
378
379	hostdata = (struct WD33C93_hostdata *) cmd->device->host->hostdata;
380
381	DB(DB_QUEUE_COMMAND,
382	   printk("Q-%d-%02x-%ld( ", cmd->device->id, cmd->cmnd[0], cmd->pid))
383
384/* Set up a few fields in the scsi_cmnd structure for our own use:
385 *  - host_scribble is the pointer to the next cmd in the input queue
386 *  - scsi_done points to the routine we call when a cmd is finished
387 *  - result is what you'd expect
388 */
389	cmd->host_scribble = NULL;
390	cmd->scsi_done = done;
391	cmd->result = 0;
392
393
394	if (cmd->use_sg) {
395		cmd->SCp.buffer = (struct scatterlist *) cmd->request_buffer;
396		cmd->SCp.buffers_residual = cmd->use_sg - 1;
397		cmd->SCp.ptr = page_address(cmd->SCp.buffer->page) +
398		    cmd->SCp.buffer->offset;
399		cmd->SCp.this_residual = cmd->SCp.buffer->length;
400	} else {
401		cmd->SCp.buffer = NULL;
402		cmd->SCp.buffers_residual = 0;
403		cmd->SCp.ptr = (char *) cmd->request_buffer;
404		cmd->SCp.this_residual = cmd->request_bufflen;
405	}
406
407/* WD docs state that at the conclusion of a "LEVEL2" command, the
408 * status byte can be retrieved from the LUN register. Apparently,
409 * this is the case only for *uninterrupted* LEVEL2 commands! If
410 * there are any unexpected phases entered, even if they are 100%
411 * legal (different devices may choose to do things differently),
412 * the LEVEL2 command sequence is exited. This often occurs prior
413 * to receiving the status byte, in which case the driver does a
414 * status phase interrupt and gets the status byte on its own.
415 * While such a command can then be "resumed" (ie restarted to
416 * finish up as a LEVEL2 command), the LUN register will NOT be
417 * a valid status byte at the command's conclusion, and we must
418 * use the byte obtained during the earlier interrupt. Here, we
419 * preset SCp.Status to an illegal value (0xff) so that when
420 * this command finally completes, we can tell where the actual
421 * status byte is stored.
422 */
423
424	cmd->SCp.Status = ILLEGAL_STATUS_BYTE;
425
426	/*
427	 * Add the cmd to the end of 'input_Q'. Note that REQUEST SENSE
428	 * commands are added to the head of the queue so that the desired
429	 * sense data is not lost before REQUEST_SENSE executes.
430	 */
431
432	spin_lock_irq(&hostdata->lock);
433
434	if (!(hostdata->input_Q) || (cmd->cmnd[0] == REQUEST_SENSE)) {
435		cmd->host_scribble = (uchar *) hostdata->input_Q;
436		hostdata->input_Q = cmd;
437	} else {		/* find the end of the queue */
438		for (tmp = (struct scsi_cmnd *) hostdata->input_Q;
439		     tmp->host_scribble;
440		     tmp = (struct scsi_cmnd *) tmp->host_scribble) ;
441		tmp->host_scribble = (uchar *) cmd;
442	}
443
444/* We know that there's at least one command in 'input_Q' now.
445 * Go see if any of them are runnable!
446 */
447
448	wd33c93_execute(cmd->device->host);
449
450	DB(DB_QUEUE_COMMAND, printk(")Q-%ld ", cmd->pid))
451
452	spin_unlock_irq(&hostdata->lock);
453	return 0;
454}
455
456/*
457 * This routine attempts to start a scsi command. If the host_card is
458 * already connected, we give up immediately. Otherwise, look through
459 * the input_Q, using the first command we find that's intended
460 * for a currently non-busy target/lun.
461 *
462 * wd33c93_execute() is always called with interrupts disabled or from
463 * the wd33c93_intr itself, which means that a wd33c93 interrupt
464 * cannot occur while we are in here.
465 */
466static void
467wd33c93_execute(struct Scsi_Host *instance)
468{
469	struct WD33C93_hostdata *hostdata =
470	    (struct WD33C93_hostdata *) instance->hostdata;
471	const wd33c93_regs regs = hostdata->regs;
472	struct scsi_cmnd *cmd, *prev;
473
474	DB(DB_EXECUTE, printk("EX("))
475	if (hostdata->selecting || hostdata->connected) {
476		DB(DB_EXECUTE, printk(")EX-0 "))
477		return;
478	}
479
480	/*
481	 * Search through the input_Q for a command destined
482	 * for an idle target/lun.
483	 */
484
485	cmd = (struct scsi_cmnd *) hostdata->input_Q;
486	prev = NULL;
487	while (cmd) {
488		if (!(hostdata->busy[cmd->device->id] & (1 << cmd->device->lun)))
489			break;
490		prev = cmd;
491		cmd = (struct scsi_cmnd *) cmd->host_scribble;
492	}
493
494	/* quit if queue empty or all possible targets are busy */
495
496	if (!cmd) {
497		DB(DB_EXECUTE, printk(")EX-1 "))
498		return;
499	}
500
501	/*  remove command from queue */
502
503	if (prev)
504		prev->host_scribble = cmd->host_scribble;
505	else
506		hostdata->input_Q = (struct scsi_cmnd *) cmd->host_scribble;
507
508#ifdef PROC_STATISTICS
509	hostdata->cmd_cnt[cmd->device->id]++;
510#endif
511
512	/*
513	 * Start the selection process
514	 */
515
516	if (cmd->sc_data_direction == DMA_TO_DEVICE)
517		write_wd33c93(regs, WD_DESTINATION_ID, cmd->device->id);
518	else
519		write_wd33c93(regs, WD_DESTINATION_ID, cmd->device->id | DSTID_DPD);
520
521/* Now we need to figure out whether or not this command is a good
522 * candidate for disconnect/reselect. We guess to the best of our
523 * ability, based on a set of hierarchical rules. When several
524 * devices are operating simultaneously, disconnects are usually
525 * an advantage. In a single device system, or if only 1 device
526 * is being accessed, transfers usually go faster if disconnects
527 * are not allowed:
528 *
529 * + Commands should NEVER disconnect if hostdata->disconnect =
530 *   DIS_NEVER (this holds for tape drives also), and ALWAYS
531 *   disconnect if hostdata->disconnect = DIS_ALWAYS.
532 * + Tape drive commands should always be allowed to disconnect.
533 * + Disconnect should be allowed if disconnected_Q isn't empty.
534 * + Commands should NOT disconnect if input_Q is empty.
535 * + Disconnect should be allowed if there are commands in input_Q
536 *   for a different target/lun. In this case, the other commands
537 *   should be made disconnect-able, if not already.
538 *
539 * I know, I know - this code would flunk me out of any
540 * "C Programming 101" class ever offered. But it's easy
541 * to change around and experiment with for now.
542 */
543
544	cmd->SCp.phase = 0;	/* assume no disconnect */
545	if (hostdata->disconnect == DIS_NEVER)
546		goto no;
547	if (hostdata->disconnect == DIS_ALWAYS)
548		goto yes;
549	if (cmd->device->type == 1)	/* tape drive? */
550		goto yes;
551	if (hostdata->disconnected_Q)	/* other commands disconnected? */
552		goto yes;
553	if (!(hostdata->input_Q))	/* input_Q empty? */
554		goto no;
555	for (prev = (struct scsi_cmnd *) hostdata->input_Q; prev;
556	     prev = (struct scsi_cmnd *) prev->host_scribble) {
557		if ((prev->device->id != cmd->device->id) ||
558		    (prev->device->lun != cmd->device->lun)) {
559			for (prev = (struct scsi_cmnd *) hostdata->input_Q; prev;
560			     prev = (struct scsi_cmnd *) prev->host_scribble)
561				prev->SCp.phase = 1;
562			goto yes;
563		}
564	}
565
566	goto no;
567
568 yes:
569	cmd->SCp.phase = 1;
570
571#ifdef PROC_STATISTICS
572	hostdata->disc_allowed_cnt[cmd->device->id]++;
573#endif
574
575 no:
576
577	write_wd33c93(regs, WD_SOURCE_ID, ((cmd->SCp.phase) ? SRCID_ER : 0));
578
579	write_wd33c93(regs, WD_TARGET_LUN, cmd->device->lun);
580	write_wd33c93(regs, WD_SYNCHRONOUS_TRANSFER,
581		      hostdata->sync_xfer[cmd->device->id]);
582	hostdata->busy[cmd->device->id] |= (1 << cmd->device->lun);
583
584	if ((hostdata->level2 == L2_NONE) ||
585	    (hostdata->sync_stat[cmd->device->id] == SS_UNSET)) {
586
587		/*
588		 * Do a 'Select-With-ATN' command. This will end with
589		 * one of the following interrupts:
590		 *    CSR_RESEL_AM:  failure - can try again later.
591		 *    CSR_TIMEOUT:   failure - give up.
592		 *    CSR_SELECT:    success - proceed.
593		 */
594
595		hostdata->selecting = cmd;
596
597/* Every target has its own synchronous transfer setting, kept in the
598 * sync_xfer array, and a corresponding status byte in sync_stat[].
599 * Each target's sync_stat[] entry is initialized to SX_UNSET, and its
600 * sync_xfer[] entry is initialized to the default/safe value. SS_UNSET
601 * means that the parameters are undetermined as yet, and that we
602 * need to send an SDTR message to this device after selection is
603 * complete: We set SS_FIRST to tell the interrupt routine to do so.
604 * If we've been asked not to try synchronous transfers on this
605 * target (and _all_ luns within it), we'll still send the SDTR message
606 * later, but at that time we'll negotiate for async by specifying a
607 * sync fifo depth of 0.
608 */
609		if (hostdata->sync_stat[cmd->device->id] == SS_UNSET)
610			hostdata->sync_stat[cmd->device->id] = SS_FIRST;
611		hostdata->state = S_SELECTING;
612		write_wd33c93_count(regs, 0);	/* guarantee a DATA_PHASE interrupt */
613		write_wd33c93_cmd(regs, WD_CMD_SEL_ATN);
614	} else {
615
616		/*
617		 * Do a 'Select-With-ATN-Xfer' command. This will end with
618		 * one of the following interrupts:
619		 *    CSR_RESEL_AM:  failure - can try again later.
620		 *    CSR_TIMEOUT:   failure - give up.
621		 *    anything else: success - proceed.
622		 */
623
624		hostdata->connected = cmd;
625		write_wd33c93(regs, WD_COMMAND_PHASE, 0);
626
627		/* copy command_descriptor_block into WD chip
628		 * (take advantage of auto-incrementing)
629		 */
630
631		write_wd33c93_cdb(regs, cmd->cmd_len, cmd->cmnd);
632
633		/* The wd33c93 only knows about Group 0, 1, and 5 commands when
634		 * it's doing a 'select-and-transfer'. To be safe, we write the
635		 * size of the CDB into the OWN_ID register for every case. This
636		 * way there won't be problems with vendor-unique, audio, etc.
637		 */
638
639		write_wd33c93(regs, WD_OWN_ID, cmd->cmd_len);
640
641		/* When doing a non-disconnect command with DMA, we can save
642		 * ourselves a DATA phase interrupt later by setting everything
643		 * up ahead of time.
644		 */
645
646		if ((cmd->SCp.phase == 0) && (hostdata->no_dma == 0)) {
647			if (hostdata->dma_setup(cmd,
648			    (cmd->sc_data_direction == DMA_TO_DEVICE) ?
649			     DATA_OUT_DIR : DATA_IN_DIR))
650				write_wd33c93_count(regs, 0);	/* guarantee a DATA_PHASE interrupt */
651			else {
652				write_wd33c93_count(regs,
653						    cmd->SCp.this_residual);
654				write_wd33c93(regs, WD_CONTROL,
655					      CTRL_IDI | CTRL_EDI | hostdata->dma_mode);
656				hostdata->dma = D_DMA_RUNNING;
657			}
658		} else
659			write_wd33c93_count(regs, 0);	/* guarantee a DATA_PHASE interrupt */
660
661		hostdata->state = S_RUNNING_LEVEL2;
662		write_wd33c93_cmd(regs, WD_CMD_SEL_ATN_XFER);
663	}
664
665	/*
666	 * Since the SCSI bus can handle only 1 connection at a time,
667	 * we get out of here now. If the selection fails, or when
668	 * the command disconnects, we'll come back to this routine
669	 * to search the input_Q again...
670	 */
671
672	DB(DB_EXECUTE,
673	   printk("%s%ld)EX-2 ", (cmd->SCp.phase) ? "d:" : "", cmd->pid))
674}
675
676static void
677transfer_pio(const wd33c93_regs regs, uchar * buf, int cnt,
678	     int data_in_dir, struct WD33C93_hostdata *hostdata)
679{
680	uchar asr;
681
682	DB(DB_TRANSFER,
683	   printk("(%p,%d,%s:", buf, cnt, data_in_dir ? "in" : "out"))
684
685	write_wd33c93(regs, WD_CONTROL, CTRL_IDI | CTRL_EDI | CTRL_POLLED);
686	write_wd33c93_count(regs, cnt);
687	write_wd33c93_cmd(regs, WD_CMD_TRANS_INFO);
688	if (data_in_dir) {
689		do {
690			asr = read_aux_stat(regs);
691			if (asr & ASR_DBR)
692				*buf++ = read_wd33c93(regs, WD_DATA);
693		} while (!(asr & ASR_INT));
694	} else {
695		do {
696			asr = read_aux_stat(regs);
697			if (asr & ASR_DBR)
698				write_wd33c93(regs, WD_DATA, *buf++);
699		} while (!(asr & ASR_INT));
700	}
701
702	/* Note: we are returning with the interrupt UN-cleared.
703	 * Since (presumably) an entire I/O operation has
704	 * completed, the bus phase is probably different, and
705	 * the interrupt routine will discover this when it
706	 * responds to the uncleared int.
707	 */
708
709}
710
711static void
712transfer_bytes(const wd33c93_regs regs, struct scsi_cmnd *cmd,
713		int data_in_dir)
714{
715	struct WD33C93_hostdata *hostdata;
716	unsigned long length;
717
718	hostdata = (struct WD33C93_hostdata *) cmd->device->host->hostdata;
719
720/* Normally, you'd expect 'this_residual' to be non-zero here.
721 * In a series of scatter-gather transfers, however, this
722 * routine will usually be called with 'this_residual' equal
723 * to 0 and 'buffers_residual' non-zero. This means that a
724 * previous transfer completed, clearing 'this_residual', and
725 * now we need to setup the next scatter-gather buffer as the
726 * source or destination for THIS transfer.
727 */
728	if (!cmd->SCp.this_residual && cmd->SCp.buffers_residual) {
729		++cmd->SCp.buffer;
730		--cmd->SCp.buffers_residual;
731		cmd->SCp.this_residual = cmd->SCp.buffer->length;
732		cmd->SCp.ptr = page_address(cmd->SCp.buffer->page) +
733		    cmd->SCp.buffer->offset;
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->pid))
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->pid))
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->pid))
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->pid);
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->pid))
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->pid))
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->pid))
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->pid);
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->pid);
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->pid);
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
1751int
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_sync = 0xff;	/* sync defaults to off */
1963	hostdata->no_dma = 0;	/* default is DMA enabled */
1964	hostdata->fast = 0;	/* default is Fast SCSI transfers disabled */
1965	hostdata->dma_mode = CTRL_DMA;	/* default is Single Byte DMA */
1966
1967#ifdef PROC_INTERFACE
1968	hostdata->proc = PR_VERSION | PR_INFO | PR_STATISTICS |
1969	    PR_CONNECTED | PR_INPUTQ | PR_DISCQ | PR_STOP;
1970#ifdef PROC_STATISTICS
1971	hostdata->dma_cnt = 0;
1972	hostdata->pio_cnt = 0;
1973	hostdata->int_cnt = 0;
1974#endif
1975#endif
1976
1977	if (check_setup_args("clock", &flags, &val, buf)) {
1978		hostdata->clock_freq = set_clk_freq(val, &val);
1979		calc_sx_table(val, hostdata->sx_table);
1980	}
1981
1982	if (check_setup_args("nosync", &flags, &val, buf))
1983		hostdata->no_sync = val;
1984
1985	if (check_setup_args("nodma", &flags, &val, buf))
1986		hostdata->no_dma = (val == -1) ? 1 : val;
1987
1988	if (check_setup_args("period", &flags, &val, buf))
1989		hostdata->default_sx_per =
1990		    hostdata->sx_table[round_period((unsigned int) val,
1991		                                    hostdata->sx_table)].period_ns;
1992
1993	if (check_setup_args("disconnect", &flags, &val, buf)) {
1994		if ((val >= DIS_NEVER) && (val <= DIS_ALWAYS))
1995			hostdata->disconnect = val;
1996		else
1997			hostdata->disconnect = DIS_ADAPTIVE;
1998	}
1999
2000	if (check_setup_args("level2", &flags, &val, buf))
2001		hostdata->level2 = val;
2002
2003	if (check_setup_args("debug", &flags, &val, buf))
2004		hostdata->args = val & DB_MASK;
2005
2006	if (check_setup_args("burst", &flags, &val, buf))
2007		hostdata->dma_mode = val ? CTRL_BURST:CTRL_DMA;
2008
2009	if (WD33C93_FS_16_20 == hostdata->clock_freq /* divisor 4 */
2010		&& check_setup_args("fast", &flags, &val, buf))
2011		hostdata->fast = !!val;
2012
2013	if ((i = check_setup_args("next", &flags, &val, buf))) {
2014		while (i)
2015			setup_used[--i] = 1;
2016	}
2017#ifdef PROC_INTERFACE
2018	if (check_setup_args("proc", &flags, &val, buf))
2019		hostdata->proc = val;
2020#endif
2021
2022	spin_lock_irq(&hostdata->lock);
2023	reset_wd33c93(instance);
2024	spin_unlock_irq(&hostdata->lock);
2025
2026	printk("wd33c93-%d: chip=%s/%d no_sync=0x%x no_dma=%d",
2027	       instance->host_no,
2028	       (hostdata->chip == C_WD33C93) ? "WD33c93" : (hostdata->chip ==
2029							    C_WD33C93A) ?
2030	       "WD33c93A" : (hostdata->chip ==
2031			     C_WD33C93B) ? "WD33c93B" : "unknown",
2032	       hostdata->microcode, hostdata->no_sync, hostdata->no_dma);
2033#ifdef DEBUGGING_ON
2034	printk(" debug_flags=0x%02x\n", hostdata->args);
2035#else
2036	printk(" debugging=OFF\n");
2037#endif
2038	printk("           setup_args=");
2039	for (i = 0; i < MAX_SETUP_ARGS; i++)
2040		printk("%s,", setup_args[i]);
2041	printk("\n");
2042	printk("           Version %s - %s, Compiled %s at %s\n",
2043	       WD33C93_VERSION, WD33C93_DATE, __DATE__, __TIME__);
2044}
2045
2046int
2047wd33c93_proc_info(struct Scsi_Host *instance, char *buf, char **start, off_t off, int len, int in)
2048{
2049
2050#ifdef PROC_INTERFACE
2051
2052	char *bp;
2053	char tbuf[128];
2054	struct WD33C93_hostdata *hd;
2055	struct scsi_cmnd *cmd;
2056	int x;
2057	static int stop = 0;
2058
2059	hd = (struct WD33C93_hostdata *) instance->hostdata;
2060
2061/* If 'in' is TRUE we need to _read_ the proc file. We accept the following
2062 * keywords (same format as command-line, but arguments are not optional):
2063 *    debug
2064 *    disconnect
2065 *    period
2066 *    resync
2067 *    proc
2068 *    nodma
2069 *    level2
2070 *    burst
2071 *    fast
2072 *    nosync
2073 */
2074
2075	if (in) {
2076		buf[len] = '\0';
2077		for (bp = buf; *bp; ) {
2078			while (',' == *bp || ' ' == *bp)
2079				++bp;
2080		if (!strncmp(bp, "debug:", 6)) {
2081				hd->args = simple_strtoul(bp+6, &bp, 0) & DB_MASK;
2082		} else if (!strncmp(bp, "disconnect:", 11)) {
2083				x = simple_strtoul(bp+11, &bp, 0);
2084			if (x < DIS_NEVER || x > DIS_ALWAYS)
2085				x = DIS_ADAPTIVE;
2086			hd->disconnect = x;
2087		} else if (!strncmp(bp, "period:", 7)) {
2088			x = simple_strtoul(bp+7, &bp, 0);
2089			hd->default_sx_per =
2090				hd->sx_table[round_period((unsigned int) x,
2091							  hd->sx_table)].period_ns;
2092		} else if (!strncmp(bp, "resync:", 7)) {
2093				set_resync(hd, (int)simple_strtoul(bp+7, &bp, 0));
2094		} else if (!strncmp(bp, "proc:", 5)) {
2095				hd->proc = simple_strtoul(bp+5, &bp, 0);
2096		} else if (!strncmp(bp, "nodma:", 6)) {
2097				hd->no_dma = simple_strtoul(bp+6, &bp, 0);
2098		} else if (!strncmp(bp, "level2:", 7)) {
2099				hd->level2 = simple_strtoul(bp+7, &bp, 0);
2100			} else if (!strncmp(bp, "burst:", 6)) {
2101				hd->dma_mode =
2102					simple_strtol(bp+6, &bp, 0) ? CTRL_BURST:CTRL_DMA;
2103			} else if (!strncmp(bp, "fast:", 5)) {
2104				x = !!simple_strtol(bp+5, &bp, 0);
2105				if (x != hd->fast)
2106					set_resync(hd, 0xff);
2107				hd->fast = x;
2108			} else if (!strncmp(bp, "nosync:", 7)) {
2109				x = simple_strtoul(bp+7, &bp, 0);
2110				set_resync(hd, x ^ hd->no_sync);
2111				hd->no_sync = x;
2112			} else {
2113				break; /* unknown keyword,syntax-error,... */
2114			}
2115		}
2116		return len;
2117	}
2118
2119	spin_lock_irq(&hd->lock);
2120	bp = buf;
2121	*bp = '\0';
2122	if (hd->proc & PR_VERSION) {
2123		sprintf(tbuf, "\nVersion %s - %s. Compiled %s %s",
2124			WD33C93_VERSION, WD33C93_DATE, __DATE__, __TIME__);
2125		strcat(bp, tbuf);
2126	}
2127	if (hd->proc & PR_INFO) {
2128		sprintf(tbuf, "\nclock_freq=%02x no_sync=%02x no_dma=%d"
2129			" dma_mode=%02x fast=%d",
2130			hd->clock_freq, hd->no_sync, hd->no_dma, hd->dma_mode, hd->fast);
2131		strcat(bp, tbuf);
2132		strcat(bp, "\nsync_xfer[] =       ");
2133		for (x = 0; x < 7; x++) {
2134			sprintf(tbuf, "\t%02x", hd->sync_xfer[x]);
2135			strcat(bp, tbuf);
2136		}
2137		strcat(bp, "\nsync_stat[] =       ");
2138		for (x = 0; x < 7; x++) {
2139			sprintf(tbuf, "\t%02x", hd->sync_stat[x]);
2140			strcat(bp, tbuf);
2141		}
2142	}
2143#ifdef PROC_STATISTICS
2144	if (hd->proc & PR_STATISTICS) {
2145		strcat(bp, "\ncommands issued:    ");
2146		for (x = 0; x < 7; x++) {
2147			sprintf(tbuf, "\t%ld", hd->cmd_cnt[x]);
2148			strcat(bp, tbuf);
2149		}
2150		strcat(bp, "\ndisconnects allowed:");
2151		for (x = 0; x < 7; x++) {
2152			sprintf(tbuf, "\t%ld", hd->disc_allowed_cnt[x]);
2153			strcat(bp, tbuf);
2154		}
2155		strcat(bp, "\ndisconnects done:   ");
2156		for (x = 0; x < 7; x++) {
2157			sprintf(tbuf, "\t%ld", hd->disc_done_cnt[x]);
2158			strcat(bp, tbuf);
2159		}
2160		sprintf(tbuf,
2161			"\ninterrupts: %ld, DATA_PHASE ints: %ld DMA, %ld PIO",
2162			hd->int_cnt, hd->dma_cnt, hd->pio_cnt);
2163		strcat(bp, tbuf);
2164	}
2165#endif
2166	if (hd->proc & PR_CONNECTED) {
2167		strcat(bp, "\nconnected:     ");
2168		if (hd->connected) {
2169			cmd = (struct scsi_cmnd *) hd->connected;
2170			sprintf(tbuf, " %ld-%d:%d(%02x)",
2171				cmd->pid, cmd->device->id, cmd->device->lun, cmd->cmnd[0]);
2172			strcat(bp, tbuf);
2173		}
2174	}
2175	if (hd->proc & PR_INPUTQ) {
2176		strcat(bp, "\ninput_Q:       ");
2177		cmd = (struct scsi_cmnd *) hd->input_Q;
2178		while (cmd) {
2179			sprintf(tbuf, " %ld-%d:%d(%02x)",
2180				cmd->pid, cmd->device->id, cmd->device->lun, cmd->cmnd[0]);
2181			strcat(bp, tbuf);
2182			cmd = (struct scsi_cmnd *) cmd->host_scribble;
2183		}
2184	}
2185	if (hd->proc & PR_DISCQ) {
2186		strcat(bp, "\ndisconnected_Q:");
2187		cmd = (struct scsi_cmnd *) hd->disconnected_Q;
2188		while (cmd) {
2189			sprintf(tbuf, " %ld-%d:%d(%02x)",
2190				cmd->pid, cmd->device->id, cmd->device->lun, cmd->cmnd[0]);
2191			strcat(bp, tbuf);
2192			cmd = (struct scsi_cmnd *) cmd->host_scribble;
2193		}
2194	}
2195	strcat(bp, "\n");
2196	spin_unlock_irq(&hd->lock);
2197	*start = buf;
2198	if (stop) {
2199		stop = 0;
2200		return 0;
2201	}
2202	if (off > 0x40000)	/* ALWAYS stop after 256k bytes have been read */
2203		stop = 1;
2204	if (hd->proc & PR_STOP)	/* stop every other time */
2205		stop = 1;
2206	return strlen(bp);
2207
2208#else				/* PROC_INTERFACE */
2209
2210	return 0;
2211
2212#endif				/* PROC_INTERFACE */
2213
2214}
2215
2216void
2217wd33c93_release(void)
2218{
2219}
2220
2221EXPORT_SYMBOL(wd33c93_host_reset);
2222EXPORT_SYMBOL(wd33c93_init);
2223EXPORT_SYMBOL(wd33c93_release);
2224EXPORT_SYMBOL(wd33c93_abort);
2225EXPORT_SYMBOL(wd33c93_queuecommand);
2226EXPORT_SYMBOL(wd33c93_intr);
2227EXPORT_SYMBOL(wd33c93_proc_info);
2228