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