make oldconfig will rebuild these...
[linux-2.4.21-pre4.git] / drivers / scsi / wd7000.c
1 /* $Id: wd7000.c,v 1.1.1.1 2005/04/11 02:50:37 jack Exp $
2  *  linux/drivers/scsi/wd7000.c
3  *
4  *  Copyright (C) 1992  Thomas Wuensche
5  *      closely related to the aha1542 driver from Tommy Thorn
6  *      ( as close as different hardware allows on a lowlevel-driver :-) )
7  *
8  *  Revised (and renamed) by John Boyd <boyd@cis.ohio-state.edu> to
9  *  accommodate Eric Youngdale's modifications to scsi.c.  Nov 1992.
10  *
11  *  Additional changes to support scatter/gather.  Dec. 1992.  tw/jb
12  *
13  *  No longer tries to reset SCSI bus at boot (it wasn't working anyway).
14  *  Rewritten to support multiple host adapters.
15  *  Miscellaneous cleanup.
16  *  So far, still doesn't do reset or abort correctly, since I have no idea
17  *  how to do them with this board (8^(.                      Jan 1994 jb
18  *
19  * This driver now supports both of the two standard configurations (per
20  * the 3.36 Owner's Manual, my latest reference) by the same method as
21  * before; namely, by looking for a BIOS signature.  Thus, the location of
22  * the BIOS signature determines the board configuration.  Until I have
23  * time to do something more flexible, users should stick to one of the
24  * following:
25  *
26  * Standard configuration for single-adapter systems:
27  *    - BIOS at CE00h
28  *    - I/O base address 350h
29  *    - IRQ level 15
30  *    - DMA channel 6
31  * Standard configuration for a second adapter in a system:
32  *    - BIOS at C800h
33  *    - I/O base address 330h
34  *    - IRQ level 11
35  *    - DMA channel 5
36  *
37  * Anyone who can recompile the kernel is welcome to add others as need
38  * arises, but unpredictable results may occur if there are conflicts.
39  * In any event, if there are multiple adapters in a system, they MUST
40  * use different I/O bases, IRQ levels, and DMA channels, since they will be
41  * indistinguishable (and in direct conflict) otherwise.
42  *
43  *   As a point of information, the NO_OP command toggles the CMD_RDY bit
44  * of the status port, and this fact could be used as a test for the I/O
45  * base address (or more generally, board detection).  There is an interrupt
46  * status port, so IRQ probing could also be done.  I suppose the full
47  * DMA diagnostic could be used to detect the DMA channel being used.  I
48  * haven't done any of this, though, because I think there's too much of
49  * a chance that such explorations could be destructive, if some other
50  * board's resources are used inadvertently.  So, call me a wimp, but I
51  * don't want to try it.  The only kind of exploration I trust is memory
52  * exploration, since it's more certain that reading memory won't be
53  * destructive.
54  *
55  * More to my liking would be a LILO boot command line specification, such
56  * as is used by the aha152x driver (and possibly others).  I'll look into
57  * it, as I have time...
58  *
59  *   I get mail occasionally from people who either are using or are
60  * considering using a WD7000 with Linux.  There is a variety of
61  * nomenclature describing WD7000's.  To the best of my knowledge, the
62  * following is a brief summary (from an old WD doc - I don't work for
63  * them or anything like that):
64  *
65  * WD7000-FASST2: This is a WD7000 board with the real-mode SST ROM BIOS
66  *        installed.  Last I heard, the BIOS was actually done by Columbia
67  *        Data Products.  The BIOS is only used by this driver (and thus
68  *        by Linux) to identify the board; none of it can be executed under
69  *        Linux.
70  *
71  * WD7000-ASC: This is the original adapter board, with or without BIOS.
72  *        The board uses a WD33C93 or WD33C93A SBIC, which in turn is
73  *        controlled by an onboard Z80 processor.  The board interface
74  *        visible to the host CPU is defined effectively by the Z80's
75  *        firmware, and it is this firmware's revision level that is
76  *        determined and reported by this driver.  (The version of the
77  *        on-board BIOS is of no interest whatsoever.)  The host CPU has
78  *        no access to the SBIC; hence the fact that it is a WD33C93 is
79  *        also of no interest to this driver.
80  *
81  * WD7000-AX:
82  * WD7000-MX:
83  * WD7000-EX: These are newer versions of the WD7000-ASC.  The -ASC is
84  *        largely built from discrete components; these boards use more
85  *        integration.  The -AX is an ISA bus board (like the -ASC),
86  *        the -MX is an MCA (i.e., PS/2) bus board), and the -EX is an
87  *        EISA bus board.
88  *
89  *  At the time of my documentation, the -?X boards were "future" products,
90  *  and were not yet available.  However, I vaguely recall that Thomas
91  *  Wuensche had an -AX, so I believe at least it is supported by this
92  *  driver.  I have no personal knowledge of either -MX or -EX boards.
93  *
94  *  P.S. Just recently, I've discovered (directly from WD and Future
95  *  Domain) that all but the WD7000-EX have been out of production for
96  *  two years now.  FD has production rights to the 7000-EX, and are
97  *  producing it under a new name, and with a new BIOS.  If anyone has
98  *  one of the FD boards, it would be nice to come up with a signature
99  *  for it.
100  *                                                           J.B. Jan 1994.
101  *
102  *
103  *  Revisions by Miroslav Zagorac <zaga@fly.cc.fer.hr>
104  *
105  *  08/24/1996.
106  *
107  *  Enhancement for wd7000_detect function has been made, so you don't have
108  *  to enter BIOS ROM address in initialisation data (see struct Config).
109  *  We cannot detect IRQ, DMA and I/O base address for now, so we have to
110  *  enter them as arguments while wd_7000 is detected. If someone has IRQ,
111  *  DMA or I/O base address set to some other value, he can enter them in
112  *  configuration without any problem. Also I wrote a function wd7000_setup,
113  *  so now you can enter WD-7000 definition as kernel arguments,
114  *  as in lilo.conf:
115  *
116  *     append="wd7000=IRQ,DMA,IO"
117  *
118  *  PS: If card BIOS ROM is disabled, function wd7000_detect now will recognize
119  *      adapter, unlike the old one. Anyway, BIOS ROM from WD7000 adapter is
120  *      useless for Linux. B^)
121  *
122  *
123  *  09/06/1996.
124  *
125  *  Autodetecting of I/O base address from wd7000_detect function is removed,
126  *  some little bugs removed, etc...
127  *
128  *  Thanks to Roger Scott for driver debugging.
129  *
130  *  06/07/1997
131  *
132  *  Added support for /proc file system (/proc/scsi/wd7000/[0...] files).
133  *  Now, driver can handle hard disks with capacity >1GB.
134  *
135  *  01/15/1998
136  *
137  *  Added support for BUS_ON and BUS_OFF parameters in config line.
138  *  Miscellaneous cleanup.
139  *
140  *  03/01/1998
141  *
142  *  WD7000 driver now work on kernels >= 2.1.x
143  */
144
145 #include <linux/module.h>
146
147 #include <stdarg.h>
148 #include <linux/kernel.h>
149 #include <linux/types.h>
150 #include <linux/string.h>
151 #include <linux/sched.h>
152 #include <linux/slab.h>
153 #include <linux/spinlock.h>
154 #include <asm/system.h>
155 #include <asm/dma.h>
156 #include <asm/io.h>
157 #include <linux/ioport.h>
158 #include <linux/proc_fs.h>
159 #include <linux/blk.h>
160 #include <linux/version.h>
161 #include <linux/init.h>
162 #include "scsi.h"
163 #include "hosts.h"
164 #include "sd.h"
165 #include <scsi/scsicam.h>
166
167 #define ANY2SCSI_INLINE         /* undef this to use old macros */
168 #undef  WD7000_DEBUG            /* general debug                */
169
170 #include "wd7000.h"
171 #include <linux/stat.h>
172
173 /*
174  *  Mailbox structure sizes.
175  *  I prefer to keep the number of ICMBs much larger than the number of
176  *  OGMBs.  OGMBs are used very quickly by the driver to start one or
177  *  more commands, while ICMBs are used by the host adapter per command.
178  */
179 #define OGMB_CNT        16
180 #define ICMB_CNT        32
181
182 /*
183  *  Scb's are shared by all active adapters.  So, if they all become busy,
184  *  callers may be made to wait in alloc_scbs for them to free.  That can
185  *  be avoided by setting MAX_SCBS to NUM_CONFIG * WD7000_Q.  If you'd
186  *  rather conserve memory, use a smaller number (> 0, of course) - things
187  *  will should still work OK.
188  */
189 #define MAX_SCBS        32
190
191 /*
192  *  WD7000-specific mailbox structure
193  *
194  */
195 typedef volatile struct mailbox {
196     unchar status;
197     unchar scbptr[3];           /* SCSI-style - MSB first (big endian) */
198 } Mailbox;
199
200 /*
201  *  This structure should contain all per-adapter global data.  I.e., any
202  *  new global per-adapter data should put in here.
203  */
204 typedef struct adapter {
205     struct Scsi_Host *sh;       /* Pointer to Scsi_Host structure    */
206     int iobase;                 /* This adapter's I/O base address   */
207     int irq;                    /* This adapter's IRQ level          */
208     int dma;                    /* This adapter's DMA channel        */
209     int int_counter;            /* This adapter's interrupt counter  */
210     int bus_on;                 /* This adapter's BUS_ON time        */
211     int bus_off;                /* This adapter's BUS_OFF time       */
212     struct {                    /* This adapter's mailboxes          */
213         Mailbox ogmb[OGMB_CNT]; /* Outgoing mailboxes                */
214         Mailbox icmb[ICMB_CNT]; /* Incoming mailboxes                */
215     } mb;
216     int next_ogmb;              /* to reduce contention at mailboxes */
217     unchar control;             /* shadows CONTROL port value        */
218     unchar rev1, rev2;          /* filled in by wd7000_revision      */
219 } Adapter;
220
221 /*
222  * (linear) base address for ROM BIOS
223  */
224 static const long wd7000_biosaddr[] =
225 {
226     0xc0000, 0xc2000, 0xc4000, 0xc6000, 0xc8000, 0xca000, 0xcc000, 0xce000,
227     0xd0000, 0xd2000, 0xd4000, 0xd6000, 0xd8000, 0xda000, 0xdc000, 0xde000
228 };
229 #define NUM_ADDRS (sizeof(wd7000_biosaddr)/sizeof(long))
230
231 static const unsigned short wd7000_iobase[] =
232 {
233     0x0300, 0x0308, 0x0310, 0x0318, 0x0320, 0x0328, 0x0330, 0x0338,
234     0x0340, 0x0348, 0x0350, 0x0358, 0x0360, 0x0368, 0x0370, 0x0378,
235     0x0380, 0x0388, 0x0390, 0x0398, 0x03a0, 0x03a8, 0x03b0, 0x03b8,
236     0x03c0, 0x03c8, 0x03d0, 0x03d8, 0x03e0, 0x03e8, 0x03f0, 0x03f8
237 };
238 #define NUM_IOPORTS (sizeof(wd7000_iobase)/sizeof(unsigned short))
239
240 static const short wd7000_irq[] = { 3, 4, 5, 7, 9, 10, 11, 12, 14, 15 };
241 #define NUM_IRQS (sizeof(wd7000_irq)/sizeof(short))
242
243 static const short wd7000_dma[] = { 5, 6, 7 };
244 #define NUM_DMAS (sizeof(wd7000_dma)/sizeof(short))
245
246 /*
247  * possible irq range
248  */
249 #define IRQ_MIN   3
250 #define IRQ_MAX   15
251 #define IRQS      (IRQ_MAX - IRQ_MIN + 1)
252
253 /*
254  * The following is set up by wd7000_detect, and used thereafter by
255  * wd7000_intr_handle to map the irq level to the corresponding Adapter.
256  * Note that if SA_INTERRUPT is not used, wd7000_intr_handle must be
257  * changed to pick up the IRQ level correctly.
258  */
259 static struct Scsi_Host *wd7000_host[IRQS];
260
261 #define BUS_ON    64    /* x 125ns = 8000ns (BIOS default) */
262 #define BUS_OFF   15    /* x 125ns = 1875ns (BIOS default) */
263
264 /*
265  *  Standard Adapter Configurations - used by wd7000_detect
266  */
267 typedef struct {
268     short irq;          /* IRQ level                                  */
269     short dma;          /* DMA channel                                */
270     unsigned iobase;    /* I/O base address                           */
271     short bus_on;       /* Time that WD7000 spends on the AT-bus when */
272                         /* transferring data. BIOS default is 8000ns. */
273     short bus_off;      /* Time that WD7000 spends OFF THE BUS after  */
274                         /* while it is transferring data.             */
275                         /* BIOS default is 1875ns                     */
276 } Config;
277
278 /*
279  * Add here your configuration...
280  */
281 static Config configs[] =
282 {
283     { 15,  6, 0x350, BUS_ON, BUS_OFF }, /* defaults for single adapter */
284     { 11,  5, 0x320, BUS_ON, BUS_OFF }, /* defaults for second adapter */
285     {  7,  6, 0x350, BUS_ON, BUS_OFF }, /* My configuration (Zaga)     */
286     { -1, -1, 0x0,   BUS_ON, BUS_OFF }  /* Empty slot                  */
287 };
288 #define NUM_CONFIGS (sizeof(configs)/sizeof(Config))
289
290 /*
291  *  The following list defines strings to look for in the BIOS that identify
292  *  it as the WD7000-FASST2 SST BIOS.  I suspect that something should be
293  *  added for the Future Domain version.
294  */
295 typedef struct signature {
296     const char *sig;            /* String to look for            */
297     unsigned long ofs;          /* offset from BIOS base address */
298     unsigned len;               /* length of string              */
299 } Signature;
300
301 static const Signature signatures[] =
302 {
303     {"SSTBIOS", 0x0000d, 7}     /* "SSTBIOS" @ offset 0x0000d */
304 };
305 #define NUM_SIGNATURES (sizeof(signatures)/sizeof(Signature))
306
307
308 /*
309  *  I/O Port Offsets and Bit Definitions
310  *  4 addresses are used.  Those not defined here are reserved.
311  */
312 #define ASC_STAT        0       /* Status,  Read          */
313 #define ASC_COMMAND     0       /* Command, Write         */
314 #define ASC_INTR_STAT   1       /* Interrupt Status, Read */
315 #define ASC_INTR_ACK    1       /* Acknowledge, Write     */
316 #define ASC_CONTROL     2       /* Control, Write         */
317
318 /*
319  * ASC Status Port
320  */
321 #define INT_IM          0x80    /* Interrupt Image Flag           */
322 #define CMD_RDY         0x40    /* Command Port Ready             */
323 #define CMD_REJ         0x20    /* Command Port Byte Rejected     */
324 #define ASC_INIT        0x10    /* ASC Initialized Flag           */
325 #define ASC_STATMASK    0xf0    /* The lower 4 Bytes are reserved */
326
327 /*
328  * COMMAND opcodes
329  *
330  *  Unfortunately, I have no idea how to properly use some of these commands,
331  *  as the OEM manual does not make it clear.  I have not been able to use
332  *  enable/disable unsolicited interrupts or the reset commands with any
333  *  discernible effect whatsoever.  I think they may be related to certain
334  *  ICB commands, but again, the OEM manual doesn't make that clear.
335  */
336 #define NO_OP             0     /* NO-OP toggles CMD_RDY bit in ASC_STAT  */
337 #define INITIALIZATION    1     /* initialization (10 bytes)              */
338 #define DISABLE_UNS_INTR  2     /* disable unsolicited interrupts         */
339 #define ENABLE_UNS_INTR   3     /* enable unsolicited interrupts          */
340 #define INTR_ON_FREE_OGMB 4     /* interrupt on free OGMB                 */
341 #define SOFT_RESET        5     /* SCSI bus soft reset                    */
342 #define HARD_RESET_ACK    6     /* SCSI bus hard reset acknowledge        */
343 #define START_OGMB        0x80  /* start command in OGMB (n)              */
344 #define SCAN_OGMBS        0xc0  /* start multiple commands, signature (n) */
345                                 /*    where (n) = lower 6 bits            */
346 /*
347  * For INITIALIZATION:
348  */
349 typedef struct initCmd {
350     unchar op;                  /* command opcode (= 1)                    */
351     unchar ID;                  /* Adapter's SCSI ID                       */
352     unchar bus_on;              /* Bus on time, x 125ns (see below)        */
353     unchar bus_off;             /* Bus off time, ""         ""             */
354     unchar rsvd;                /* Reserved                                */
355     unchar mailboxes[3];        /* Address of Mailboxes, MSB first         */
356     unchar ogmbs;               /* Number of outgoing MBs, max 64, 0,1 = 1 */
357     unchar icmbs;               /* Number of incoming MBs,   ""       ""   */
358 } InitCmd;
359
360 /*
361  * Interrupt Status Port - also returns diagnostic codes at ASC reset
362  *
363  * if msb is zero, the lower bits are diagnostic status
364  * Diagnostics:
365  * 01   No diagnostic error occurred
366  * 02   RAM failure
367  * 03   FIFO R/W failed
368  * 04   SBIC register read/write failed
369  * 05   Initialization D-FF failed
370  * 06   Host IRQ D-FF failed
371  * 07   ROM checksum error
372  * Interrupt status (bitwise):
373  * 10NNNNNN   outgoing mailbox NNNNNN is free
374  * 11NNNNNN   incoming mailbox NNNNNN needs service
375  */
376 #define MB_INTR    0xC0         /* Mailbox Service possible/required */
377 #define IMB_INTR   0x40         /* 1 Incoming / 0 Outgoing           */
378 #define MB_MASK    0x3f         /* mask for mailbox number           */
379
380 /*
381  * CONTROL port bits
382  */
383 #define INT_EN     0x08         /* Interrupt Enable */
384 #define DMA_EN     0x04         /* DMA Enable       */
385 #define SCSI_RES   0x02         /* SCSI Reset       */
386 #define ASC_RES    0x01         /* ASC Reset        */
387
388 /*
389  * Driver data structures:
390  *   - mb and scbs are required for interfacing with the host adapter.
391  *     An SCB has extra fields not visible to the adapter; mb's
392  *     _cannot_ do this, since the adapter assumes they are contiguous in
393  *     memory, 4 bytes each, with ICMBs following OGMBs, and uses this fact
394  *     to access them.
395  *   - An icb is for host-only (non-SCSI) commands.  ICBs are 16 bytes each;
396  *     the additional bytes are used only by the driver.
397  *   - For now, a pool of SCBs are kept in global storage by this driver,
398  *     and are allocated and freed as needed.
399  *
400  *  The 7000-FASST2 marks OGMBs empty as soon as it has _started_ a command,
401  *  not when it has finished.  Since the SCB must be around for completion,
402  *  problems arise when SCBs correspond to OGMBs, which may be reallocated
403  *  earlier (or delayed unnecessarily until a command completes).
404  *  Mailboxes are used as transient data structures, simply for
405  *  carrying SCB addresses to/from the 7000-FASST2.
406  *
407  *  Note also since SCBs are not "permanently" associated with mailboxes,
408  *  there is no need to keep a global list of Scsi_Cmnd pointers indexed
409  *  by OGMB.   Again, SCBs reference their Scsi_Cmnds directly, so mailbox
410  *  indices need not be involved.
411  */
412
413 /*
414  *  WD7000-specific scatter/gather element structure
415  */
416 typedef struct sgb {
417     unchar len[3];
418     unchar ptr[3];              /* Also SCSI-style - MSB first */
419 } Sgb;
420
421 typedef struct scb {            /* Command Control Block 5.4.1               */
422     unchar op;                  /* Command Control Block Operation Code      */
423     unchar idlun;               /* op=0,2:Target Id, op=1:Initiator Id       */
424                                 /* Outbound data transfer, length is checked */
425                                 /* Inbound data transfer, length is checked  */
426                                 /* Logical Unit Number                       */
427     unchar cdb[12];             /* SCSI Command Block                        */
428     volatile unchar status;     /* SCSI Return Status                        */
429     volatile unchar vue;        /* Vendor Unique Error Code                  */
430     unchar maxlen[3];           /* Maximum Data Transfer Length              */
431     unchar dataptr[3];          /* SCSI Data Block Pointer                   */
432     unchar linkptr[3];          /* Next Command Link Pointer                 */
433     unchar direc;               /* Transfer Direction                        */
434     unchar reserved2[6];        /* SCSI Command Descriptor Block             */
435                                 /* end of hardware SCB                       */
436     Scsi_Cmnd *SCpnt;           /* Scsi_Cmnd using this SCB                  */
437     Sgb sgb[WD7000_SG];         /* Scatter/gather list for this SCB          */
438     Adapter *host;              /* host adapter                              */
439     struct scb *next;           /* for lists of scbs                         */
440 } Scb;
441
442 /*
443  *  This driver is written to allow host-only commands to be executed.
444  *  These use a 16-byte block called an ICB.  The format is extended by the
445  *  driver to 18 bytes, to support the status returned in the ICMB and
446  *  an execution phase code.
447  *
448  *  There are other formats besides these; these are the ones I've tried
449  *  to use.  Formats for some of the defined ICB opcodes are not defined
450  *  (notably, get/set unsolicited interrupt status) in my copy of the OEM
451  *  manual, and others are ambiguous/hard to follow.
452  */
453 #define ICB_OP_MASK           0x80      /* distinguishes scbs from icbs        */
454 #define ICB_OP_OPEN_RBUF      0x80      /* open receive buffer                 */
455 #define ICB_OP_RECV_CMD       0x81      /* receive command from initiator      */
456 #define ICB_OP_RECV_DATA      0x82      /* receive data from initiator         */
457 #define ICB_OP_RECV_SDATA     0x83      /* receive data with status from init. */
458 #define ICB_OP_SEND_DATA      0x84      /* send data with status to initiator  */
459 #define ICB_OP_SEND_STAT      0x86      /* send command status to initiator    */
460                                         /* 0x87 is reserved                    */
461 #define ICB_OP_READ_INIT      0x88      /* read initialization bytes           */
462 #define ICB_OP_READ_ID        0x89      /* read adapter's SCSI ID              */
463 #define ICB_OP_SET_UMASK      0x8A      /* set unsolicited interrupt mask      */
464 #define ICB_OP_GET_UMASK      0x8B      /* read unsolicited interrupt mask     */
465 #define ICB_OP_GET_REVISION   0x8C      /* read firmware revision level        */
466 #define ICB_OP_DIAGNOSTICS    0x8D      /* execute diagnostics                 */
467 #define ICB_OP_SET_EPARMS     0x8E      /* set execution parameters            */
468 #define ICB_OP_GET_EPARMS     0x8F      /* read execution parameters           */
469
470 typedef struct icbRecvCmd {
471     unchar op;
472     unchar IDlun;               /* Initiator SCSI ID/lun     */
473     unchar len[3];              /* command buffer length     */
474     unchar ptr[3];              /* command buffer address    */
475     unchar rsvd[7];             /* reserved                  */
476     volatile unchar vue;        /* vendor-unique error code  */
477     volatile unchar status;     /* returned (icmb) status    */
478     volatile unchar phase;      /* used by interrupt handler */
479 } IcbRecvCmd;
480
481 typedef struct icbSendStat {
482     unchar op;
483     unchar IDlun;               /* Target SCSI ID/lun                  */
484     unchar stat;                /* (outgoing) completion status byte 1 */
485     unchar rsvd[12];            /* reserved                            */
486     volatile unchar vue;        /* vendor-unique error code            */
487     volatile unchar status;     /* returned (icmb) status              */
488     volatile unchar phase;      /* used by interrupt handler           */
489 } IcbSendStat;
490
491 typedef struct icbRevLvl {
492     unchar op;
493     volatile unchar primary;    /* primary revision level (returned)   */
494     volatile unchar secondary;  /* secondary revision level (returned) */
495     unchar rsvd[12];            /* reserved                            */
496     volatile unchar vue;        /* vendor-unique error code            */
497     volatile unchar status;     /* returned (icmb) status              */
498     volatile unchar phase;      /* used by interrupt handler           */
499 } IcbRevLvl;
500
501 typedef struct icbUnsMask {     /* I'm totally guessing here */
502     unchar op;
503     volatile unchar mask[14];   /* mask bits                 */
504 #if 0
505     unchar rsvd[12];            /* reserved                  */
506 #endif
507     volatile unchar vue;        /* vendor-unique error code  */
508     volatile unchar status;     /* returned (icmb) status    */
509     volatile unchar phase;      /* used by interrupt handler */
510 } IcbUnsMask;
511
512 typedef struct icbDiag {
513     unchar op;
514     unchar type;                /* diagnostics type code (0-3) */
515     unchar len[3];              /* buffer length               */
516     unchar ptr[3];              /* buffer address              */
517     unchar rsvd[7];             /* reserved                    */
518     volatile unchar vue;        /* vendor-unique error code    */
519     volatile unchar status;     /* returned (icmb) status      */
520     volatile unchar phase;      /* used by interrupt handler   */
521 } IcbDiag;
522
523 #define ICB_DIAG_POWERUP   0    /* Power-up diags only       */
524 #define ICB_DIAG_WALKING   1    /* walking 1's pattern       */
525 #define ICB_DIAG_DMA       2    /* DMA - system memory diags */
526 #define ICB_DIAG_FULL      3    /* do both 1 & 2             */
527
528 typedef struct icbParms {
529     unchar op;
530     unchar rsvd1;               /* reserved                  */
531     unchar len[3];              /* parms buffer length       */
532     unchar ptr[3];              /* parms buffer address      */
533     unchar idx[2];              /* index (MSB-LSB)           */
534     unchar rsvd2[5];            /* reserved                  */
535     volatile unchar vue;        /* vendor-unique error code  */
536     volatile unchar status;     /* returned (icmb) status    */
537     volatile unchar phase;      /* used by interrupt handler */
538 } IcbParms;
539
540 typedef struct icbAny {
541     unchar op;
542     unchar data[14];            /* format-specific data      */
543     volatile unchar vue;        /* vendor-unique error code  */
544     volatile unchar status;     /* returned (icmb) status    */
545     volatile unchar phase;      /* used by interrupt handler */
546 } IcbAny;
547
548 typedef union icb {
549     unchar op;                  /* ICB opcode                     */
550     IcbRecvCmd recv_cmd;        /* format for receive command     */
551     IcbSendStat send_stat;      /* format for send status         */
552     IcbRevLvl rev_lvl;          /* format for get revision level  */
553     IcbDiag diag;               /* format for execute diagnostics */
554     IcbParms eparms;            /* format for get/set exec parms  */
555     IcbAny icb;                 /* generic format                 */
556     unchar data[18];
557 } Icb;
558
559 #ifdef MODULE
560 static char * wd7000 = NULL;
561 MODULE_PARM(wd7000, "s");
562 #endif
563
564 /*
565  *  Driver SCB structure pool.
566  *
567  *  The SCBs declared here are shared by all host adapters; hence, this
568  *  structure is not part of the Adapter structure.
569  */
570 static Scb scbs[MAX_SCBS];
571 static Scb *scbfree = NULL;     /* free list         */
572 static int freescbs = MAX_SCBS; /* free list counter */
573
574 /*
575  *  END of data/declarations - code follows.
576  */
577 static void setup_error (char *mesg, int *ints)
578 {
579     if (ints[0] == 3)
580         printk ("wd7000_setup: \"wd7000=%d,%d,0x%x\" -> %s\n",
581                 ints[1], ints[2], ints[3], mesg);
582     else if (ints[0] == 4)
583         printk ("wd7000_setup: \"wd7000=%d,%d,0x%x,%d\" -> %s\n",
584                 ints[1], ints[2], ints[3], ints[4], mesg);
585     else
586         printk ("wd7000_setup: \"wd7000=%d,%d,0x%x,%d,%d\" -> %s\n",
587                 ints[1], ints[2], ints[3], ints[4], ints[5], mesg);
588 }
589
590
591 /*
592  * Note: You can now set these options from the kernel's "command line".
593  * The syntax is:
594  *
595  *     wd7000=<IRQ>,<DMA>,<IO>[,<BUS_ON>[,<BUS_OFF>]]
596  *
597  * , where BUS_ON and BUS_OFF are in nanoseconds. BIOS default values
598  * are 8000ns for BUS_ON and 1875ns for BUS_OFF.
599  * eg:
600  *     wd7000=7,6,0x350
601  *
602  * will configure the driver for a WD-7000 controller
603  * using IRQ 15 with a DMA channel 6, at IO base address 0x350.
604  */
605 static int __init wd7000_setup(char *str)
606 {
607         static short wd7000_card_num = 0;
608         short i, j;
609         int ints[6];
610
611         (void)get_options(str, ARRAY_SIZE(ints), ints);
612
613         if (wd7000_card_num >= NUM_CONFIGS) {
614                 printk("wd7000_setup: Too many \"wd7000=\" configurations in "
615                 "command line!\n");
616                 return 0;
617         }
618
619         if ((ints[0] < 3) || (ints[0] > 5)) {
620                 printk("wd7000_setup: Error in command line!  "
621                 "Usage: wd7000=<IRQ>,<DMA>,IO>[,<BUS_ON>[,<BUS_OFF>]]\n");
622         } else {
623                 for (i = 0; i < NUM_IRQS; i++)
624                         if (ints[1] == wd7000_irq[i])
625                                 break;
626
627                 if (i == NUM_IRQS) {
628                         setup_error("invalid IRQ.", ints);
629                         return 0;
630                 } else
631                         configs[wd7000_card_num].irq = ints[1];
632
633                 for (i = 0; i < NUM_DMAS; i++)
634                         if (ints[2] == wd7000_dma[i])
635                                 break;
636
637                 if (i == NUM_DMAS) {
638                         setup_error("invalid DMA channel.", ints);
639                         return 0;
640                 } else
641                         configs[wd7000_card_num].dma = ints[2];
642
643                 for (i = 0; i < NUM_IOPORTS; i++)
644                         if (ints[3] == wd7000_iobase[i])
645                                 break;
646
647                 if (i == NUM_IOPORTS) {
648                         setup_error("invalid I/O base address.", ints);
649                         return 0;
650                 } else
651                         configs[wd7000_card_num].iobase = ints[3];
652
653                 if (ints[0] > 3) {
654                         if ((ints[4] < 500) || (ints[4] > 31875)) {
655                                 setup_error("BUS_ON value is out of range (500 to 31875 nanoseconds)!", ints);
656                                 configs[wd7000_card_num].bus_on = BUS_ON;
657                         } else
658                                 configs[wd7000_card_num].bus_on = ints[4] / 125;
659                 } else
660                         configs[wd7000_card_num].bus_on = BUS_ON;
661
662                 if (ints[0] > 4) {
663                         if ((ints[5] < 500) || (ints[5] > 31875)) {
664                                 setup_error("BUS_OFF value is out of range (500 to 31875 nanoseconds)!", ints);
665                                 configs[wd7000_card_num].bus_off = BUS_OFF;
666                         } else
667                                 configs[wd7000_card_num].bus_off = ints[5] / 125;
668                 } else
669                         configs[wd7000_card_num].bus_off = BUS_OFF;
670
671                 if (wd7000_card_num) {
672                         for (i = 0; i < (wd7000_card_num - 1); i++)
673                                 for (j = i + 1; j < wd7000_card_num; j++)
674                                         if (configs[i].irq == configs[j].irq) {
675                                                 setup_error("duplicated IRQ!", ints);
676                                                 return 0;
677                                         } else if (configs[i].dma == configs[j].dma) {
678                                                 setup_error("duplicated DMA channel!", ints);
679                                                 return 0;
680                                         } else if (configs[i].iobase == configs[j].iobase) {
681                                                 setup_error ("duplicated I/O base address!", ints);
682                                                 return 0;
683                                         }
684                 }
685
686 #ifdef WD7000_DEBUG
687                 printk ("wd7000_setup: IRQ=%d, DMA=%d, I/O=0x%x, BUS_ON=%dns, BUS_OFF=%dns\n",
688                         configs[wd7000_card_num].irq,
689                         configs[wd7000_card_num].dma,
690                         configs[wd7000_card_num].iobase,
691                         configs[wd7000_card_num].bus_on * 125,
692                         configs[wd7000_card_num].bus_off * 125);
693 #endif
694
695                 wd7000_card_num++;
696         }
697         return 1;
698 }
699
700 __setup("wd7000=", wd7000_setup);
701
702 #ifdef ANY2SCSI_INLINE
703 /*
704  * Since they're used a lot, I've redone the following from the macros
705  * formerly in wd7000.h, hopefully to speed them up by getting rid of
706  * all the shifting (it may not matter; GCC might have done as well anyway).
707  *
708  * xany2scsi and xscsi2int were not being used, and are no longer defined.
709  * (They were simply 4-byte versions of these routines).
710  */
711 typedef union {                 /* let's cheat... */
712     int i;
713     unchar u[sizeof (int)];     /* the sizeof(int) makes it more portable */
714 } i_u;
715
716
717 static inline void any2scsi (unchar * scsi, int any)
718 {
719     *scsi++ = ((i_u) any).u[2];
720     *scsi++ = ((i_u) any).u[1];
721     *scsi++ = ((i_u) any).u[0];
722 }
723
724
725 static inline int scsi2int (unchar * scsi)
726 {
727     i_u result;
728
729     result.i = 0;               /* clears unused bytes */
730     result.u[2] = *scsi++;
731     result.u[1] = *scsi++;
732     result.u[0] = *scsi++;
733
734     return (result.i);
735 }
736 #else
737 /*
738  * These are the old ones - I've just moved them here...
739  */
740 #undef any2scsi
741 #define any2scsi(up, p)   (up)[0] = (((unsigned long) (p)) >> 16);      \
742                           (up)[1] = ((unsigned long) (p)) >> 8;         \
743                           (up)[2] = ((unsigned long) (p));
744
745 #undef scsi2int
746 #define scsi2int(up)   ( (((unsigned long) *(up)) << 16) +      \
747                          (((unsigned long) (up)[1]) << 8) +     \
748                          ((unsigned long) (up)[2]) )
749 #endif
750
751
752 static inline void wd7000_enable_intr (Adapter *host)
753 {
754     host->control |= INT_EN;
755     outb (host->control, host->iobase + ASC_CONTROL);
756 }
757
758
759 static inline void wd7000_enable_dma (Adapter *host)
760 {
761     unsigned long flags;
762     host->control |= DMA_EN;
763     outb (host->control, host->iobase + ASC_CONTROL);
764     
765     flags = claim_dma_lock();
766     set_dma_mode (host->dma, DMA_MODE_CASCADE);
767     enable_dma (host->dma);
768     release_dma_lock(flags);
769     
770 }
771
772
773 #define WAITnexttimeout 200     /* 2 seconds */
774
775 static inline short WAIT (unsigned port, unsigned mask, unsigned allof, unsigned noneof)
776 {
777     register unsigned WAITbits;
778     register unsigned long WAITtimeout = jiffies + WAITnexttimeout;
779
780     while (time_before_eq(jiffies, WAITtimeout)) {
781         WAITbits = inb (port) & mask;
782
783         if (((WAITbits & allof) == allof) && ((WAITbits & noneof) == 0))
784             return (0);
785     }
786
787     return (1);
788 }
789
790
791 static inline void delay (unsigned how_long)
792 {
793     register unsigned long time = jiffies + how_long;
794
795     while (time_before(jiffies, time));
796 }
797
798
799 static inline int command_out (Adapter * host, unchar * cmd, int len)
800 {
801     if (!WAIT (host->iobase + ASC_STAT, ASC_STATMASK, CMD_RDY, 0)) {
802         while (len--) {
803             do {
804                 outb (*cmd, host->iobase + ASC_COMMAND);
805                 WAIT (host->iobase + ASC_STAT, ASC_STATMASK, CMD_RDY, 0);
806             } while (inb (host->iobase + ASC_STAT) & CMD_REJ);
807
808             cmd++;
809         }
810
811         return (1);
812     }
813
814     printk ("wd7000 command_out: WAIT failed(%d)\n", len + 1);
815
816     return (0);
817 }
818
819
820 /*
821  *  This version of alloc_scbs is in preparation for supporting multiple
822  *  commands per lun and command chaining, by queueing pending commands.
823  *  We will need to allocate Scbs in blocks since they will wait to be
824  *  executed so there is the possibility of deadlock otherwise.
825  *  Also, to keep larger requests from being starved by smaller requests,
826  *  we limit access to this routine with an internal busy flag, so that
827  *  the satisfiability of a request is not dependent on the size of the
828  *  request.
829  */
830 static inline Scb *alloc_scbs (int needed)
831 {
832     register Scb *scb, *p;
833     register unsigned long flags;
834     register unsigned long timeout = jiffies + WAITnexttimeout;
835     register unsigned long now;
836     static int busy = 0;
837     int i;
838
839     if (needed <= 0)
840         return (NULL);          /* sanity check */
841
842     save_flags (flags);
843     cli ();
844     while (busy) {              /* someone else is allocating */
845         spin_unlock_irq(&io_request_lock);
846         for (now = jiffies; now == jiffies; );  /* wait a jiffy */
847         spin_lock_irq(&io_request_lock);
848     }
849     busy = 1;                   /* not busy now; it's our turn */
850
851     while (freescbs < needed) {
852         timeout = jiffies + WAITnexttimeout;
853         do {
854             spin_unlock_irq(&io_request_lock);
855             for (now = jiffies; now == jiffies; );      /* wait a jiffy */
856             spin_lock_irq(&io_request_lock);
857         } while (freescbs < needed && time_before_eq(jiffies, timeout));
858         /*
859          *  If we get here with enough free Scbs, we can take them.
860          *  Otherwise, we timed out and didn't get enough.
861          */
862         if (freescbs < needed) {
863             busy = 0;
864             printk (KERN_ERR "wd7000: can't get enough free SCBs.\n");
865             restore_flags (flags);
866             return (NULL);
867         }
868     }
869     scb = scbfree;
870     freescbs -= needed;
871     for (i = 0; i < needed; i++) {
872         p = scbfree;
873         scbfree = p->next;
874     }
875     p->next = NULL;
876     busy = 0;                   /* we're done */
877
878     restore_flags (flags);
879
880     return (scb);
881 }
882
883
884 static inline void free_scb (Scb *scb)
885 {
886     register unsigned long flags;
887
888     save_flags (flags);
889     cli ();
890
891     memset (scb, 0, sizeof (Scb));
892     scb->next = scbfree;
893     scbfree = scb;
894     freescbs++;
895
896     restore_flags (flags);
897 }
898
899
900 static inline void init_scbs (void)
901 {
902     int i;
903     unsigned long flags;
904
905     save_flags (flags);
906     cli ();
907
908     scbfree = &(scbs[0]);
909     memset (scbs, 0, sizeof (scbs));
910     for (i = 0; i < MAX_SCBS - 1; i++) {
911         scbs[i].next = &(scbs[i + 1]);
912         scbs[i].SCpnt = NULL;
913     }
914     scbs[MAX_SCBS - 1].next = NULL;
915     scbs[MAX_SCBS - 1].SCpnt = NULL;
916
917     restore_flags (flags);
918 }
919
920
921 static int mail_out (Adapter *host, Scb *scbptr)
922 /*
923  *  Note: this can also be used for ICBs; just cast to the parm type.
924  */
925 {
926     register int i, ogmb;
927     register unsigned long flags;
928     unchar start_ogmb;
929     Mailbox *ogmbs = host->mb.ogmb;
930     int *next_ogmb = &(host->next_ogmb);
931
932 #ifdef WD7000_DEBUG
933     printk ("wd7000_mail_out: 0x%06lx", (long) scbptr);
934 #endif
935
936     /* We first look for a free outgoing mailbox */
937     save_flags (flags);
938     cli ();
939     ogmb = *next_ogmb;
940     for (i = 0; i < OGMB_CNT; i++) {
941         if (ogmbs[ogmb].status == 0) {
942 #ifdef WD7000_DEBUG
943             printk (" using OGMB 0x%x", ogmb);
944 #endif
945             ogmbs[ogmb].status = 1;
946             any2scsi ((unchar *) ogmbs[ogmb].scbptr, (int) scbptr);
947
948             *next_ogmb = (ogmb + 1) % OGMB_CNT;
949             break;
950         }
951         else
952             ogmb = (ogmb + 1) % OGMB_CNT;
953     }
954     restore_flags (flags);
955
956 #ifdef WD7000_DEBUG
957     printk (", scb is 0x%06lx", (long) scbptr);
958 #endif
959
960     if (i >= OGMB_CNT) {
961         /*
962          *  Alternatively, we might issue the "interrupt on free OGMB",
963          *  and sleep, but it must be ensured that it isn't the init
964          *  task running.  Instead, this version assumes that the caller
965          *  will be persistent, and try again.  Since it's the adapter
966          *  that marks OGMB's free, waiting even with interrupts off
967          *  should work, since they are freed very quickly in most cases.
968          */
969 #ifdef WD7000_DEBUG
970         printk (", no free OGMBs.\n");
971 #endif
972         return (0);
973     }
974
975     wd7000_enable_intr (host);
976
977     start_ogmb = START_OGMB | ogmb;
978     command_out (host, &start_ogmb, 1);
979
980 #ifdef WD7000_DEBUG
981     printk (", awaiting interrupt.\n");
982 #endif
983
984     return (1);
985 }
986
987
988 int make_code (unsigned hosterr, unsigned scsierr)
989 {
990 #ifdef WD7000_DEBUG
991     int in_error = hosterr;
992 #endif
993
994     switch ((hosterr >> 8) & 0xff) {
995         case 0:  /* Reserved */
996                  hosterr = DID_ERROR;
997                  break;
998         case 1:  /* Command Complete, no errors */
999                  hosterr = DID_OK;
1000                  break;
1001         case 2:  /* Command complete, error logged in scb status (scsierr) */
1002                  hosterr = DID_OK;
1003                  break;
1004         case 4:  /* Command failed to complete - timeout */
1005                  hosterr = DID_TIME_OUT;
1006                  break;
1007         case 5:  /* Command terminated; Bus reset by external device */
1008                  hosterr = DID_RESET;
1009                  break;
1010         case 6:  /* Unexpected Command Received w/ host as target */
1011                  hosterr = DID_BAD_TARGET;
1012                  break;
1013         case 80: /* Unexpected Reselection */
1014         case 81: /* Unexpected Selection */
1015                  hosterr = DID_BAD_INTR;
1016                  break;
1017         case 82: /* Abort Command Message  */
1018                  hosterr = DID_ABORT;
1019                  break;
1020         case 83: /* SCSI Bus Software Reset */
1021         case 84: /* SCSI Bus Hardware Reset */
1022                  hosterr = DID_RESET;
1023                  break;
1024         default: /* Reserved */
1025                  hosterr = DID_ERROR;
1026     }
1027 #ifdef WD7000_DEBUG
1028     if (scsierr || hosterr)
1029         printk ("\nSCSI command error: SCSI 0x%02x host 0x%04x return %d\n",
1030                 scsierr, in_error, hosterr);
1031 #endif
1032     return (scsierr | (hosterr << 16));
1033 }
1034
1035
1036 static void wd7000_scsi_done (Scsi_Cmnd *SCpnt)
1037 {
1038 #ifdef WD7000_DEBUG
1039     printk ("wd7000_scsi_done: 0x%06lx\n", (long) SCpnt);
1040 #endif
1041
1042     SCpnt->SCp.phase = 0;
1043 }
1044
1045
1046 #define wd7000_intr_ack(host)   outb (0, host->iobase + ASC_INTR_ACK)
1047
1048 void wd7000_intr_handle (int irq, void *dev_id, struct pt_regs *regs)
1049 {
1050     register int flag, icmb, errstatus, icmb_status;
1051     register int host_error, scsi_error;
1052     register Scb *scb;          /* for SCSI commands */
1053     register IcbAny *icb;       /* for host commands */
1054     register Scsi_Cmnd *SCpnt;
1055     Adapter *host = (Adapter *) wd7000_host[irq - IRQ_MIN]->hostdata;   /* This MUST be set!!! */
1056     Mailbox *icmbs = host->mb.icmb;
1057
1058     host->int_counter++;
1059
1060 #ifdef WD7000_DEBUG
1061     printk ("wd7000_intr_handle: irq = %d, host = 0x%06lx\n", irq, (long) host);
1062 #endif
1063
1064     flag = inb (host->iobase + ASC_INTR_STAT);
1065
1066 #ifdef WD7000_DEBUG
1067     printk ("wd7000_intr_handle: intr stat = 0x%02x\n", flag);
1068 #endif
1069
1070     if (!(inb (host->iobase + ASC_STAT) & INT_IM)) {
1071         /* NB: these are _very_ possible if IRQ 15 is being used, since
1072          * it's the "garbage collector" on the 2nd 8259 PIC.  Specifically,
1073          * any interrupt signal into the 8259 which can't be identified
1074          * comes out as 7 from the 8259, which is 15 to the host.  Thus, it
1075          * is a good thing the WD7000 has an interrupt status port, so we
1076          * can sort these out.  Otherwise, electrical noise and other such
1077          * problems would be indistinguishable from valid interrupts...
1078          */
1079 #ifdef WD7000_DEBUG
1080         printk ("wd7000_intr_handle: phantom interrupt...\n");
1081 #endif
1082         wd7000_intr_ack (host);
1083         return;
1084     }
1085
1086     if (flag & MB_INTR) {
1087         /* The interrupt is for a mailbox */
1088         if (!(flag & IMB_INTR)) {
1089 #ifdef WD7000_DEBUG
1090             printk ("wd7000_intr_handle: free outgoing mailbox\n");
1091 #endif
1092             /*
1093              * If sleep_on() and the "interrupt on free OGMB" command are
1094              * used in mail_out(), wake_up() should correspondingly be called
1095              * here.  For now, we don't need to do anything special.
1096              */
1097             wd7000_intr_ack (host);
1098             return;
1099         }
1100         else {
1101             /* The interrupt is for an incoming mailbox */
1102             icmb = flag & MB_MASK;
1103             icmb_status = icmbs[icmb].status;
1104             if (icmb_status & 0x80) {   /* unsolicited - result in ICMB */
1105 #ifdef WD7000_DEBUG
1106                 printk ("wd7000_intr_handle: unsolicited interrupt 0x%02x\n",
1107                         icmb_status);
1108 #endif
1109                 wd7000_intr_ack (host);
1110                 return;
1111             }
1112             /* Aaaargh! (Zaga) */
1113             scb = bus_to_virt(scsi2int ((unchar *) icmbs[icmb].scbptr));
1114             icmbs[icmb].status = 0;
1115             if (!(scb->op & ICB_OP_MASK)) {     /* an SCB is done */
1116                 SCpnt = scb->SCpnt;
1117                 if (--(SCpnt->SCp.phase) <= 0) {        /* all scbs are done */
1118                     host_error = scb->vue | (icmb_status << 8);
1119                     scsi_error = scb->status;
1120                     errstatus = make_code (host_error, scsi_error);
1121                     SCpnt->result = errstatus;
1122
1123                     free_scb (scb);
1124
1125                     SCpnt->scsi_done (SCpnt);
1126                 }
1127             }
1128             else {              /* an ICB is done */
1129                 icb = (IcbAny *) scb;
1130                 icb->status = icmb_status;
1131                 icb->phase = 0;
1132             }
1133         }                       /* incoming mailbox */
1134     }
1135
1136     wd7000_intr_ack (host);
1137
1138 #ifdef WD7000_DEBUG
1139     printk ("wd7000_intr_handle: return from interrupt handler\n");
1140 #endif
1141 }
1142
1143 void do_wd7000_intr_handle (int irq, void *dev_id, struct pt_regs *regs)
1144 {
1145     unsigned long flags;
1146
1147     spin_lock_irqsave(&io_request_lock, flags);
1148     wd7000_intr_handle(irq, dev_id, regs);
1149     spin_unlock_irqrestore(&io_request_lock, flags);
1150 }
1151
1152
1153 int wd7000_queuecommand (Scsi_Cmnd *SCpnt, void (*done) (Scsi_Cmnd *))
1154 {
1155     register Scb *scb;
1156     register Sgb *sgb;
1157     register unchar *cdb = (unchar *) SCpnt->cmnd;
1158     register unchar idlun;
1159     register short cdblen;
1160     Adapter *host = (Adapter *) SCpnt->host->hostdata;
1161
1162     cdblen = SCpnt->cmd_len;
1163     idlun = ((SCpnt->target << 5) & 0xe0) | (SCpnt->lun & 7);
1164     SCpnt->scsi_done = done;
1165     SCpnt->SCp.phase = 1;
1166     scb = alloc_scbs (1);
1167     scb->idlun = idlun;
1168     memcpy (scb->cdb, cdb, cdblen);
1169     scb->direc = 0x40;          /* Disable direction check */
1170
1171     scb->SCpnt = SCpnt;         /* so we can find stuff later */
1172     SCpnt->host_scribble = (unchar *) scb;
1173     scb->host = host;
1174
1175     if (SCpnt->use_sg) {
1176         struct scatterlist *sg = (struct scatterlist *) SCpnt->request_buffer;
1177         unsigned i;
1178
1179         if (SCpnt->host->sg_tablesize == SG_NONE) {
1180             panic ("wd7000_queuecommand: scatter/gather not supported.\n");
1181         }
1182 #ifdef WD7000_DEBUG
1183         printk ("Using scatter/gather with %d elements.\n", SCpnt->use_sg);
1184 #endif
1185
1186         sgb = scb->sgb;
1187         scb->op = 1;
1188         any2scsi (scb->dataptr, (int) sgb);
1189         any2scsi (scb->maxlen, SCpnt->use_sg * sizeof (Sgb));
1190
1191         for (i = 0; i < SCpnt->use_sg; i++) {
1192             any2scsi (sgb[i].ptr, (int) sg[i].address);
1193             any2scsi (sgb[i].len, sg[i].length);
1194         }
1195     }
1196     else {
1197         scb->op = 0;
1198         any2scsi (scb->dataptr, (int) SCpnt->request_buffer);
1199         any2scsi (scb->maxlen, SCpnt->request_bufflen);
1200     }
1201
1202     while (!mail_out (host, scb));      /* keep trying */
1203
1204     return (1);
1205 }
1206
1207
1208 int wd7000_command (Scsi_Cmnd *SCpnt)
1209 {
1210     wd7000_queuecommand (SCpnt, wd7000_scsi_done);
1211
1212     while (SCpnt->SCp.phase > 0)
1213         barrier ();             /* phase counts scbs down to 0 */
1214
1215     return (SCpnt->result);
1216 }
1217
1218
1219 int wd7000_diagnostics (Adapter *host, int code)
1220 {
1221     static IcbDiag icb = {ICB_OP_DIAGNOSTICS};
1222     static unchar buf[256];
1223     unsigned long timeout;
1224
1225     icb.type = code;
1226     any2scsi (icb.len, sizeof (buf));
1227     any2scsi (icb.ptr, (int) &buf);
1228     icb.phase = 1;
1229     /*
1230      * This routine is only called at init, so there should be OGMBs
1231      * available.  I'm assuming so here.  If this is going to
1232      * fail, I can just let the timeout catch the failure.
1233      */
1234     mail_out (host, (struct scb *) &icb);
1235     timeout = jiffies + WAITnexttimeout;        /* wait up to 2 seconds */
1236     while (icb.phase && time_before(jiffies, timeout))
1237         barrier ();             /* wait for completion */
1238
1239     if (icb.phase) {
1240         printk ("wd7000_diagnostics: timed out.\n");
1241         return (0);
1242     }
1243     if (make_code (icb.vue | (icb.status << 8), 0)) {
1244         printk ("wd7000_diagnostics: failed (0x%02x,0x%02x)\n",
1245                 icb.vue, icb.status);
1246         return (0);
1247     }
1248
1249     return (1);
1250 }
1251
1252
1253 int wd7000_init (Adapter *host)
1254 {
1255     InitCmd init_cmd =
1256     {
1257         INITIALIZATION,
1258         7,
1259         host->bus_on,
1260         host->bus_off,
1261         0,
1262         { 0, 0, 0 },
1263         OGMB_CNT,
1264         ICMB_CNT
1265     };
1266     int diag;
1267
1268     /*
1269      *  Reset the adapter - only.  The SCSI bus was initialized at power-up,
1270      *  and we need to do this just so we control the mailboxes, etc.
1271      */
1272     outb (ASC_RES, host->iobase + ASC_CONTROL);
1273     delay (1);                  /* reset pulse: this is 10ms, only need 25us */
1274     outb (0, host->iobase + ASC_CONTROL);
1275     host->control = 0;          /* this must always shadow ASC_CONTROL */
1276
1277     if (WAIT (host->iobase + ASC_STAT, ASC_STATMASK, CMD_RDY, 0)) {
1278         printk ("wd7000_init: WAIT timed out.\n");
1279         return (0);             /* 0 = not ok */
1280     }
1281
1282     if ((diag = inb (host->iobase + ASC_INTR_STAT)) != 1) {
1283         printk ("wd7000_init: ");
1284
1285         switch (diag) {
1286             case 2:  printk ("RAM failure.\n");
1287                      break;
1288             case 3:  printk ("FIFO R/W failed\n");
1289                      break;
1290             case 4:  printk ("SBIC register R/W failed\n");
1291                      break;
1292             case 5:  printk ("Initialization D-FF failed.\n");
1293                      break;
1294             case 6:  printk ("Host IRQ D-FF failed.\n");
1295                      break;
1296             case 7:  printk ("ROM checksum error.\n");
1297                      break;
1298             default: printk ("diagnostic code 0x%02Xh received.\n", diag);
1299         }
1300         return (0);
1301     }
1302
1303     /* Clear mailboxes */
1304     memset (&(host->mb), 0, sizeof (host->mb));
1305
1306     /* Execute init command */
1307     any2scsi ((unchar *) & (init_cmd.mailboxes), (int) &(host->mb));
1308     if (!command_out (host, (unchar *) &init_cmd, sizeof (init_cmd))) {
1309         printk ("wd7000_init: adapter initialization failed.\n");
1310         return (0);
1311     }
1312
1313     if (WAIT (host->iobase + ASC_STAT, ASC_STATMASK, ASC_INIT, 0)) {
1314         printk ("wd7000_init: WAIT timed out.\n");
1315         return (0);
1316     }
1317
1318     if (request_irq (host->irq, do_wd7000_intr_handle, SA_INTERRUPT, "wd7000", NULL)) {
1319         printk ("wd7000_init: can't get IRQ %d.\n", host->irq);
1320         return (0);
1321     }
1322     if (request_dma (host->dma, "wd7000")) {
1323         printk ("wd7000_init: can't get DMA channel %d.\n", host->dma);
1324         free_irq (host->irq, NULL);
1325         return (0);
1326     }
1327     wd7000_enable_dma (host);
1328     wd7000_enable_intr (host);
1329
1330     if (!wd7000_diagnostics (host, ICB_DIAG_FULL)) {
1331         free_dma (host->dma);
1332         free_irq (host->irq, NULL);
1333         return (0);
1334     }
1335
1336     return (1);
1337 }
1338
1339
1340 void wd7000_revision (Adapter *host)
1341 {
1342     static IcbRevLvl icb =
1343     {ICB_OP_GET_REVISION};
1344
1345     icb.phase = 1;
1346     /*
1347      * Like diagnostics, this is only done at init time, in fact, from
1348      * wd7000_detect, so there should be OGMBs available.  If it fails,
1349      * the only damage will be that the revision will show up as 0.0,
1350      * which in turn means that scatter/gather will be disabled.
1351      */
1352     mail_out (host, (struct scb *) &icb);
1353     while (icb.phase)
1354         barrier ();             /* wait for completion */
1355     host->rev1 = icb.primary;
1356     host->rev2 = icb.secondary;
1357 }
1358
1359
1360 #undef SPRINTF
1361 #define SPRINTF(args...) { if (pos < (buffer + length)) pos += sprintf (pos, ## args); }
1362
1363 int wd7000_set_info (char *buffer, int length, struct Scsi_Host *host)
1364 {
1365     unsigned long flags;
1366
1367     save_flags (flags);
1368     cli ();
1369
1370 #ifdef WD7000_DEBUG
1371     printk ("Buffer = <%.*s>, length = %d\n", length, buffer, length);
1372 #endif
1373
1374     /*
1375      * Currently this is a no-op
1376      */
1377     printk ("Sorry, this function is currently out of order...\n");
1378
1379     restore_flags (flags);
1380
1381     return (length);
1382 }
1383
1384
1385 int wd7000_proc_info (char *buffer, char **start, off_t offset, int length, int hostno, int inout)
1386 {
1387     struct Scsi_Host *host = NULL;
1388     Scsi_Device *scd;
1389     Adapter *adapter;
1390     unsigned long flags;
1391     char *pos = buffer;
1392     short i;
1393
1394 #ifdef WD7000_DEBUG
1395     Mailbox *ogmbs, *icmbs;
1396     short count;
1397 #endif
1398
1399     /*
1400      * Find the specified host board.
1401      */
1402     for (i = 0; i < IRQS; i++)
1403         if (wd7000_host[i] && (wd7000_host[i]->host_no == hostno)) {
1404             host = wd7000_host[i];
1405
1406             break;
1407         }
1408
1409     /*
1410      * Host not found!
1411      */
1412     if (! host)
1413         return (-ESRCH);
1414
1415     /*
1416      * Has data been written to the file ?
1417      */
1418     if (inout)
1419         return (wd7000_set_info (buffer, length, host));
1420
1421     adapter = (Adapter *) host->hostdata;
1422
1423     save_flags (flags);
1424     cli ();
1425
1426     SPRINTF ("Host scsi%d: Western Digital WD-7000 (rev %d.%d)\n", hostno, adapter->rev1, adapter->rev2);
1427     SPRINTF ("  IO base:      0x%x\n", adapter->iobase);
1428     SPRINTF ("  IRQ:          %d\n", adapter->irq);
1429     SPRINTF ("  DMA channel:  %d\n", adapter->dma);
1430     SPRINTF ("  Interrupts:   %d\n", adapter->int_counter);
1431     SPRINTF ("  BUS_ON time:  %d nanoseconds\n", adapter->bus_on * 125);
1432     SPRINTF ("  BUS_OFF time: %d nanoseconds\n", adapter->bus_off * 125);
1433
1434 #ifdef WD7000_DEBUG
1435     ogmbs = adapter->mb.ogmb;
1436     icmbs = adapter->mb.icmb;
1437
1438     SPRINTF ("\nControl port value: 0x%x\n", adapter->control);
1439     SPRINTF ("Incoming mailbox:\n");
1440     SPRINTF ("  size: %d\n", ICMB_CNT);
1441     SPRINTF ("  queued messages: ");
1442
1443     for (i = count = 0; i < ICMB_CNT; i++)
1444         if (icmbs[i].status) {
1445             count++;
1446             SPRINTF ("0x%x ", i);
1447         }
1448
1449     SPRINTF (count ? "\n" : "none\n");
1450
1451     SPRINTF ("Outgoing mailbox:\n");
1452     SPRINTF ("  size: %d\n", OGMB_CNT);
1453     SPRINTF ("  next message: 0x%x\n", adapter->next_ogmb);
1454     SPRINTF ("  queued messages: ");
1455
1456     for (i = count = 0; i < OGMB_CNT; i++)
1457         if (ogmbs[i].status) {
1458             count++;
1459             SPRINTF ("0x%x ", i);
1460         }
1461
1462     SPRINTF (count ? "\n" : "none\n");
1463 #endif
1464
1465     /*
1466      * Display driver information for each device attached to the board.
1467      */
1468     scd = host->host_queue;
1469    
1470     SPRINTF ("\nAttached devices: %s\n", scd ? "" : "none");
1471
1472     for ( ; scd; scd = scd->next)
1473         if (scd->host->host_no == hostno) {
1474             SPRINTF ("  [Channel: %02d, Id: %02d, Lun: %02d]  ",
1475                      scd->channel, scd->id, scd->lun);
1476             SPRINTF ("%s ", (scd->type < MAX_SCSI_DEVICE_CODE) ?
1477                      scsi_device_types[(short) scd->type] : "Unknown device");
1478
1479             for (i = 0; (i < 8) && (scd->vendor[i] >= 0x20); i++)
1480                 SPRINTF ("%c", scd->vendor[i]);
1481             SPRINTF (" ");
1482
1483             for (i = 0; (i < 16) && (scd->model[i] >= 0x20); i++)
1484                 SPRINTF ("%c", scd->model[i]);
1485             SPRINTF ("\n");
1486         }
1487
1488     SPRINTF ("\n");
1489
1490     restore_flags (flags);
1491
1492     /*
1493      * Calculate start of next buffer, and return value.
1494      */
1495     *start = buffer + offset;
1496
1497     if ((pos - buffer) < offset)
1498         return (0);
1499     else if ((pos - buffer - offset) < length)
1500         return (pos - buffer - offset);
1501     else
1502         return (length);
1503 }
1504
1505
1506 /*
1507  *  Returns the number of adapters this driver is supporting.
1508  *
1509  *  The source for hosts.c says to wait to call scsi_register until 100%
1510  *  sure about an adapter.  We need to do it a little sooner here; we
1511  *  need the storage set up by scsi_register before wd7000_init, and
1512  *  changing the location of an Adapter structure is more trouble than
1513  *  calling scsi_unregister.
1514  *
1515  */
1516 int wd7000_detect (Scsi_Host_Template *tpnt)
1517 {
1518     short present = 0, biosaddr_ptr, sig_ptr, i, pass;
1519     short biosptr[NUM_CONFIGS];
1520     unsigned iobase;
1521     Adapter *host = NULL;
1522     struct Scsi_Host *sh;
1523
1524 #ifdef WD7000_DEBUG
1525     printk ("wd7000_detect: started\n");
1526 #endif
1527
1528 #ifdef MODULE
1529         if (wd7000)
1530                 wd7000_setup(wd7000);     
1531 #endif
1532
1533     for (i = 0; i < IRQS; wd7000_host[i++] = NULL) ;
1534     for (i = 0; i < NUM_CONFIGS; biosptr[i++] = -1) ;
1535
1536     tpnt->proc_name = "wd7000";
1537     tpnt->proc_info = &wd7000_proc_info;
1538
1539     /*
1540      * Set up SCB free list, which is shared by all adapters
1541      */
1542     init_scbs ();
1543
1544     for (pass = 0; pass < NUM_CONFIGS; pass++) {
1545         /*
1546          * First, search for BIOS SIGNATURE...
1547          */
1548         for (biosaddr_ptr = 0; biosaddr_ptr < NUM_ADDRS; biosaddr_ptr++)
1549             for (sig_ptr = 0; sig_ptr < NUM_SIGNATURES; sig_ptr++) {
1550                 for (i = 0; i < pass; i++)
1551                     if (biosptr[i] == biosaddr_ptr)
1552                         break;
1553
1554                 if (i == pass) {
1555                     void *biosaddr = ioremap (wd7000_biosaddr[biosaddr_ptr] +
1556                                               signatures[sig_ptr].ofs,
1557                                               signatures[sig_ptr].len);
1558                     short bios_match=0;
1559                     
1560                     if(biosaddr)
1561                         bios_match = memcmp ((char *) biosaddr, signatures[sig_ptr].sig,
1562                                                signatures[sig_ptr].len);
1563
1564                     iounmap (biosaddr);
1565
1566                     if (! bios_match)
1567                         goto bios_matched;
1568                 }
1569             }
1570
1571       bios_matched:
1572         /*
1573          * BIOS SIGNATURE has been found.
1574          */
1575 #ifdef WD7000_DEBUG
1576         printk ("wd7000_detect: pass %d\n", pass + 1);
1577
1578         if (biosaddr_ptr == NUM_ADDRS)
1579             printk ("WD-7000 SST BIOS not detected...\n");
1580         else
1581             printk ("WD-7000 SST BIOS detected at 0x%lx: checking...\n",
1582                     wd7000_biosaddr[biosaddr_ptr]);
1583 #endif
1584
1585         if (configs[pass].irq < 0)
1586             continue;
1587
1588         iobase = configs[pass].iobase;
1589
1590 #ifdef WD7000_DEBUG
1591         printk ("wd7000_detect: check IO 0x%x region...\n", iobase);
1592 #endif
1593
1594         if (request_region (iobase, 4, "wd7000")) {
1595
1596 #ifdef WD7000_DEBUG
1597             printk ("wd7000_detect: ASC reset (IO 0x%x) ...", iobase);
1598 #endif
1599             /*
1600              * ASC reset...
1601              */
1602             outb (ASC_RES, iobase + ASC_CONTROL);
1603             delay (1);
1604             outb (0, iobase + ASC_CONTROL);
1605
1606             if (WAIT (iobase + ASC_STAT, ASC_STATMASK, CMD_RDY, 0))
1607 #ifdef WD7000_DEBUG
1608             {
1609                 printk ("failed!\n");
1610                 goto err_release;
1611             }
1612             else 
1613                 printk ("ok!\n");
1614 #else
1615             goto err_release;
1616 #endif
1617
1618             if (inb (iobase + ASC_INTR_STAT) == 1) {
1619                 /*
1620                  *  We register here, to get a pointer to the extra space,
1621                  *  which we'll use as the Adapter structure (host) for
1622                  *  this adapter.  It is located just after the registered
1623                  *  Scsi_Host structure (sh), and is located by the empty
1624                  *  array hostdata.
1625                  */
1626                 sh = scsi_register (tpnt, sizeof (Adapter));
1627                 if(sh==NULL)
1628                     goto err_release;
1629
1630                 host = (Adapter *) sh->hostdata;
1631
1632 #ifdef WD7000_DEBUG
1633                 printk ("wd7000_detect: adapter allocated at 0x%x\n", (int) host);
1634 #endif
1635
1636                 memset (host, 0, sizeof (Adapter));
1637
1638                 host->irq = configs[pass].irq;
1639                 host->dma = configs[pass].dma;
1640                 host->iobase = iobase;
1641                 host->int_counter = 0;
1642                 host->bus_on = configs[pass].bus_on;
1643                 host->bus_off = configs[pass].bus_off;
1644                 host->sh = wd7000_host[host->irq - IRQ_MIN] = sh;
1645
1646 #ifdef WD7000_DEBUG
1647                 printk ("wd7000_detect: Trying init WD-7000 card at IO "
1648                         "0x%x, IRQ %d, DMA %d...\n",
1649                         host->iobase, host->irq, host->dma);
1650 #endif
1651
1652                 if (!wd7000_init (host))        /* Initialization failed */
1653                     goto err_unregister;
1654
1655                 /*
1656                  *  OK from here - we'll use this adapter/configuration.
1657                  */
1658                 wd7000_revision (host);         /* important for scatter/gather */
1659
1660                 /*
1661                  *  For boards before rev 6.0, scatter/gather isn't supported.
1662                  */
1663                 if (host->rev1 < 6)
1664                     sh->sg_tablesize = SG_NONE;
1665
1666                 present++;      /* count it */
1667
1668                 if (biosaddr_ptr != NUM_ADDRS)
1669                     biosptr[pass] = biosaddr_ptr;
1670
1671                 printk ("Western Digital WD-7000 (rev %d.%d) ",
1672                         host->rev1, host->rev2);
1673                 printk ("using IO 0x%x, IRQ %d, DMA %d.\n",
1674                         host->iobase, host->irq, host->dma);
1675                 printk ("  BUS_ON time: %dns, BUS_OFF time: %dns\n",
1676                         host->bus_on * 125, host->bus_off * 125);
1677             }
1678         }
1679
1680 #ifdef WD7000_DEBUG
1681         else
1682             printk ("wd7000_detect: IO 0x%x region already allocated!\n", iobase);
1683 #endif
1684
1685         continue;
1686
1687     err_unregister:
1688         scsi_unregister (sh);
1689     err_release:
1690         release_region(iobase, 4);
1691
1692     }
1693
1694     if (!present)
1695         printk ("Failed initialization of WD-7000 SCSI card!\n");
1696
1697     return (present);
1698 }
1699
1700
1701 /*
1702  *  I have absolutely NO idea how to do an abort with the WD7000...
1703  */
1704 int wd7000_abort (Scsi_Cmnd *SCpnt)
1705 {
1706     Adapter *host = (Adapter *) SCpnt->host->hostdata;
1707
1708     if (inb (host->iobase + ASC_STAT) & INT_IM) {
1709         printk ("wd7000_abort: lost interrupt\n");
1710         wd7000_intr_handle (host->irq, NULL, NULL);
1711
1712         return (SCSI_ABORT_SUCCESS);
1713     }
1714
1715     return (SCSI_ABORT_SNOOZE);
1716 }
1717
1718
1719 /*
1720  *  I also have no idea how to do a reset...
1721  */
1722 int wd7000_reset (Scsi_Cmnd *SCpnt, unsigned int unused)
1723 {
1724     return (SCSI_RESET_PUNT);
1725 }
1726
1727
1728 /*
1729  *  This was borrowed directly from aha1542.c. (Zaga)
1730  */
1731 int wd7000_biosparam (Disk *disk, kdev_t dev, int *ip)
1732 {
1733 #ifdef WD7000_DEBUG
1734     printk ("wd7000_biosparam: dev=%s, size=%d, ", kdevname (dev), disk->capacity);
1735 #endif
1736
1737     /*
1738      * try default translation
1739      */
1740     ip[0] = 64;
1741     ip[1] = 32;
1742     ip[2] = disk->capacity / (64 * 32);
1743
1744     /*
1745      * for disks >1GB do some guessing
1746      */
1747     if (ip[2] >= 1024) {
1748         int info[3];
1749
1750         /*
1751          * try to figure out the geometry from the partition table
1752          */
1753         if ((scsicam_bios_param (disk, dev, info) < 0) ||
1754             !(((info[0] == 64) && (info[1] == 32)) ||
1755               ((info[0] == 255) && (info[1] == 63)))) {
1756             printk ("wd7000_biosparam: unable to verify geometry for disk with >1GB.\n"
1757                     "                  using extended translation.\n");
1758
1759             ip[0] = 255;
1760             ip[1] = 63;
1761             ip[2] = disk->capacity / (255 * 63);
1762         }
1763         else {
1764             ip[0] = info[0];
1765             ip[1] = info[1];
1766             ip[2] = info[2];
1767
1768             if (info[0] == 255)
1769                 printk ("wd7000_biosparam: current partition table is using extended translation.\n");
1770         }
1771     }
1772
1773 #ifdef WD7000_DEBUG
1774     printk ("bios geometry: head=%d, sec=%d, cyl=%d\n", ip[0], ip[1], ip[2]);
1775     printk ("WARNING: check, if the bios geometry is correct.\n");
1776 #endif
1777
1778     return (0);
1779 }
1780
1781 MODULE_LICENSE("GPL");
1782
1783 /* Eventually this will go into an include file, but this will be later */
1784 static Scsi_Host_Template driver_template = WD7000;
1785
1786 #include "scsi_module.c"