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