Merge master.kernel.org:/home/rmk/linux-2.6-arm
[linux-2.6] / drivers / scsi / aha1542.c
1 /* $Id: aha1542.c,v 1.1 1992/07/24 06:27:38 root Exp root $
2  *  linux/kernel/aha1542.c
3  *
4  *  Copyright (C) 1992  Tommy Thorn
5  *  Copyright (C) 1993, 1994, 1995 Eric Youngdale
6  *
7  *  Modified by Eric Youngdale
8  *        Use request_irq and request_dma to help prevent unexpected conflicts
9  *        Set up on-board DMA controller, such that we do not have to
10  *        have the bios enabled to use the aha1542.
11  *  Modified by David Gentzel
12  *        Don't call request_dma if dma mask is 0 (for BusLogic BT-445S VL-Bus
13  *        controller).
14  *  Modified by Matti Aarnio
15  *        Accept parameters from LILO cmd-line. -- 1-Oct-94
16  *  Modified by Mike McLagan <mike.mclagan@linux.org>
17  *        Recognise extended mode on AHA1542CP, different bit than 1542CF
18  *        1-Jan-97
19  *  Modified by Bjorn L. Thordarson and Einar Thor Einarsson
20  *        Recognize that DMA0 is valid DMA channel -- 13-Jul-98
21  *  Modified by Chris Faulhaber <jedgar@fxp.org>
22  *        Added module command-line options
23  *        19-Jul-99
24  *  Modified by Adam Fritzler
25  *        Added proper detection of the AHA-1640 (MCA version of AHA-1540)
26  */
27
28 #include <linux/module.h>
29 #include <linux/interrupt.h>
30 #include <linux/kernel.h>
31 #include <linux/types.h>
32 #include <linux/string.h>
33 #include <linux/ioport.h>
34 #include <linux/delay.h>
35 #include <linux/proc_fs.h>
36 #include <linux/init.h>
37 #include <linux/spinlock.h>
38 #include <linux/isapnp.h>
39 #include <linux/blkdev.h>
40 #include <linux/mca.h>
41 #include <linux/mca-legacy.h>
42
43 #include <asm/dma.h>
44 #include <asm/system.h>
45 #include <asm/io.h>
46
47 #include "scsi.h"
48 #include <scsi/scsi_host.h>
49 #include "aha1542.h"
50
51 #define SCSI_BUF_PA(address)    isa_virt_to_bus(address)
52 #define SCSI_SG_PA(sgent)       (isa_page_to_bus(sg_page((sgent))) + (sgent)->offset)
53
54 static void BAD_SG_DMA(Scsi_Cmnd * SCpnt,
55                        struct scatterlist *sgp,
56                        int nseg,
57                        int badseg)
58 {
59         printk(KERN_CRIT "sgpnt[%d:%d] page %p/0x%llx length %u\n",
60                badseg, nseg, sg_virt(sgp),
61                (unsigned long long)SCSI_SG_PA(sgp),
62                sgp->length);
63
64         /*
65          * Not safe to continue.
66          */
67         panic("Buffer at physical address > 16Mb used for aha1542");
68 }
69
70 #include<linux/stat.h>
71
72 #ifdef DEBUG
73 #define DEB(x) x
74 #else
75 #define DEB(x)
76 #endif
77
78 /*
79    static const char RCSid[] = "$Header: /usr/src/linux/kernel/blk_drv/scsi/RCS/aha1542.c,v 1.1 1992/07/24 06:27:38 root Exp root $";
80  */
81
82 /* The adaptec can be configured for quite a number of addresses, but
83    I generally do not want the card poking around at random.  We allow
84    two addresses - this allows people to use the Adaptec with a Midi
85    card, which also used 0x330 -- can be overridden with LILO! */
86
87 #define MAXBOARDS 4             /* Increase this and the sizes of the
88                                    arrays below, if you need more.. */
89
90 /* Boards 3,4 slots are reserved for ISAPnP/MCA scans */
91
92 static unsigned int bases[MAXBOARDS] __initdata = {0x330, 0x334, 0, 0};
93
94 /* set by aha1542_setup according to the command line; they also may
95    be marked __initdata, but require zero initializers then */
96
97 static int setup_called[MAXBOARDS];
98 static int setup_buson[MAXBOARDS];
99 static int setup_busoff[MAXBOARDS];
100 static int setup_dmaspeed[MAXBOARDS] __initdata = { -1, -1, -1, -1 };
101
102 /*
103  * LILO/Module params:  aha1542=<PORTBASE>[,<BUSON>,<BUSOFF>[,<DMASPEED>]]
104  *
105  * Where:  <PORTBASE> is any of the valid AHA addresses:
106  *                      0x130, 0x134, 0x230, 0x234, 0x330, 0x334
107  *         <BUSON>  is the time (in microsecs) that AHA spends on the AT-bus
108  *                  when transferring data.  1542A power-on default is 11us,
109  *                  valid values are in range: 2..15 (decimal)
110  *         <BUSOFF> is the time that AHA spends OFF THE BUS after while
111  *                  it is transferring data (not to monopolize the bus).
112  *                  Power-on default is 4us, valid range: 1..64 microseconds.
113  *         <DMASPEED> Default is jumper selected (1542A: on the J1),
114  *                  but experimenter can alter it with this.
115  *                  Valid values: 5, 6, 7, 8, 10 (MB/s)
116  *                  Factory default is 5 MB/s.
117  */
118
119 #if defined(MODULE)
120 static int isapnp = 0;
121 static int aha1542[] = {0x330, 11, 4, -1};
122 module_param_array(aha1542, int, NULL, 0);
123 module_param(isapnp, bool, 0);
124
125 static struct isapnp_device_id id_table[] __initdata = {
126         {
127                 ISAPNP_ANY_ID, ISAPNP_ANY_ID,
128                 ISAPNP_VENDOR('A', 'D', 'P'), ISAPNP_FUNCTION(0x1542),
129                 0
130         },
131         {0}
132 };
133
134 MODULE_DEVICE_TABLE(isapnp, id_table);
135
136 #else
137 static int isapnp = 1;
138 #endif
139
140 #define BIOS_TRANSLATION_1632 0 /* Used by some old 1542A boards */
141 #define BIOS_TRANSLATION_6432 1 /* Default case these days */
142 #define BIOS_TRANSLATION_25563 2        /* Big disk case */
143
144 struct aha1542_hostdata {
145         /* This will effectively start both of them at the first mailbox */
146         int bios_translation;   /* Mapping bios uses - for compatibility */
147         int aha1542_last_mbi_used;
148         int aha1542_last_mbo_used;
149         Scsi_Cmnd *SCint[AHA1542_MAILBOXES];
150         struct mailbox mb[2 * AHA1542_MAILBOXES];
151         struct ccb ccb[AHA1542_MAILBOXES];
152 };
153
154 #define HOSTDATA(host) ((struct aha1542_hostdata *) &host->hostdata)
155
156 static DEFINE_SPINLOCK(aha1542_lock);
157
158
159
160 #define WAITnexttimeout 3000000
161
162 static void setup_mailboxes(int base_io, struct Scsi_Host *shpnt);
163 static int aha1542_restart(struct Scsi_Host *shost);
164 static void aha1542_intr_handle(struct Scsi_Host *shost);
165
166 #define aha1542_intr_reset(base)  outb(IRST, CONTROL(base))
167
168 #define WAIT(port, mask, allof, noneof)                                 \
169  { register int WAITbits;                                               \
170    register int WAITtimeout = WAITnexttimeout;                          \
171    while (1) {                                                          \
172      WAITbits = inb(port) & (mask);                                     \
173      if ((WAITbits & (allof)) == (allof) && ((WAITbits & (noneof)) == 0)) \
174        break;                                                           \
175      if (--WAITtimeout == 0) goto fail;                                 \
176    }                                                                    \
177  }
178
179 /* Similar to WAIT, except we use the udelay call to regulate the
180    amount of time we wait.  */
181 #define WAITd(port, mask, allof, noneof, timeout)                       \
182  { register int WAITbits;                                               \
183    register int WAITtimeout = timeout;                                  \
184    while (1) {                                                          \
185      WAITbits = inb(port) & (mask);                                     \
186      if ((WAITbits & (allof)) == (allof) && ((WAITbits & (noneof)) == 0)) \
187        break;                                                           \
188      mdelay(1);                                                 \
189      if (--WAITtimeout == 0) goto fail;                                 \
190    }                                                                    \
191  }
192
193 static void aha1542_stat(void)
194 {
195 /*      int s = inb(STATUS), i = inb(INTRFLAGS);
196         printk("status=%x intrflags=%x\n", s, i, WAITnexttimeout-WAITtimeout); */
197 }
198
199 /* This is a bit complicated, but we need to make sure that an interrupt
200    routine does not send something out while we are in the middle of this.
201    Fortunately, it is only at boot time that multi-byte messages
202    are ever sent. */
203 static int aha1542_out(unsigned int base, unchar * cmdp, int len)
204 {
205         unsigned long flags = 0;
206         int got_lock;
207
208         if (len == 1) {
209                 got_lock = 0;
210                 while (1 == 1) {
211                         WAIT(STATUS(base), CDF, 0, CDF);
212                         spin_lock_irqsave(&aha1542_lock, flags);
213                         if (inb(STATUS(base)) & CDF) {
214                                 spin_unlock_irqrestore(&aha1542_lock, flags);
215                                 continue;
216                         }
217                         outb(*cmdp, DATA(base));
218                         spin_unlock_irqrestore(&aha1542_lock, flags);
219                         return 0;
220                 }
221         } else {
222                 spin_lock_irqsave(&aha1542_lock, flags);
223                 got_lock = 1;
224                 while (len--) {
225                         WAIT(STATUS(base), CDF, 0, CDF);
226                         outb(*cmdp++, DATA(base));
227                 }
228                 spin_unlock_irqrestore(&aha1542_lock, flags);
229         }
230         return 0;
231 fail:
232         if (got_lock)
233                 spin_unlock_irqrestore(&aha1542_lock, flags);
234         printk(KERN_ERR "aha1542_out failed(%d): ", len + 1);
235         aha1542_stat();
236         return 1;
237 }
238
239 /* Only used at boot time, so we do not need to worry about latency as much
240    here */
241
242 static int __init aha1542_in(unsigned int base, unchar * cmdp, int len)
243 {
244         unsigned long flags;
245
246         spin_lock_irqsave(&aha1542_lock, flags);
247         while (len--) {
248                 WAIT(STATUS(base), DF, DF, 0);
249                 *cmdp++ = inb(DATA(base));
250         }
251         spin_unlock_irqrestore(&aha1542_lock, flags);
252         return 0;
253 fail:
254         spin_unlock_irqrestore(&aha1542_lock, flags);
255         printk(KERN_ERR "aha1542_in failed(%d): ", len + 1);
256         aha1542_stat();
257         return 1;
258 }
259
260 /* Similar to aha1542_in, except that we wait a very short period of time.
261    We use this if we know the board is alive and awake, but we are not sure
262    if the board will respond to the command we are about to send or not */
263 static int __init aha1542_in1(unsigned int base, unchar * cmdp, int len)
264 {
265         unsigned long flags;
266
267         spin_lock_irqsave(&aha1542_lock, flags);
268         while (len--) {
269                 WAITd(STATUS(base), DF, DF, 0, 100);
270                 *cmdp++ = inb(DATA(base));
271         }
272         spin_unlock_irqrestore(&aha1542_lock, flags);
273         return 0;
274 fail:
275         spin_unlock_irqrestore(&aha1542_lock, flags);
276         return 1;
277 }
278
279 static int makecode(unsigned hosterr, unsigned scsierr)
280 {
281         switch (hosterr) {
282         case 0x0:
283         case 0xa:               /* Linked command complete without error and linked normally */
284         case 0xb:               /* Linked command complete without error, interrupt generated */
285                 hosterr = 0;
286                 break;
287
288         case 0x11:              /* Selection time out-The initiator selection or target
289                                    reselection was not complete within the SCSI Time out period */
290                 hosterr = DID_TIME_OUT;
291                 break;
292
293         case 0x12:              /* Data overrun/underrun-The target attempted to transfer more data
294                                    than was allocated by the Data Length field or the sum of the
295                                    Scatter / Gather Data Length fields. */
296
297         case 0x13:              /* Unexpected bus free-The target dropped the SCSI BSY at an unexpected time. */
298
299         case 0x15:              /* MBO command was not 00, 01 or 02-The first byte of the CB was
300                                    invalid. This usually indicates a software failure. */
301
302         case 0x16:              /* Invalid CCB Operation Code-The first byte of the CCB was invalid.
303                                    This usually indicates a software failure. */
304
305         case 0x17:              /* Linked CCB does not have the same LUN-A subsequent CCB of a set
306                                    of linked CCB's does not specify the same logical unit number as
307                                    the first. */
308         case 0x18:              /* Invalid Target Direction received from Host-The direction of a
309                                    Target Mode CCB was invalid. */
310
311         case 0x19:              /* Duplicate CCB Received in Target Mode-More than once CCB was
312                                    received to service data transfer between the same target LUN
313                                    and initiator SCSI ID in the same direction. */
314
315         case 0x1a:              /* Invalid CCB or Segment List Parameter-A segment list with a zero
316                                    length segment or invalid segment list boundaries was received.
317                                    A CCB parameter was invalid. */
318                 DEB(printk("Aha1542: %x %x\n", hosterr, scsierr));
319                 hosterr = DID_ERROR;    /* Couldn't find any better */
320                 break;
321
322         case 0x14:              /* Target bus phase sequence failure-An invalid bus phase or bus
323                                    phase sequence was requested by the target. The host adapter
324                                    will generate a SCSI Reset Condition, notifying the host with
325                                    a SCRD interrupt */
326                 hosterr = DID_RESET;
327                 break;
328         default:
329                 printk(KERN_ERR "aha1542: makecode: unknown hoststatus %x\n", hosterr);
330                 break;
331         }
332         return scsierr | (hosterr << 16);
333 }
334
335 static int __init aha1542_test_port(int bse, struct Scsi_Host *shpnt)
336 {
337         unchar inquiry_cmd[] = {CMD_INQUIRY};
338         unchar inquiry_result[4];
339         unchar *cmdp;
340         int len;
341         volatile int debug = 0;
342
343         /* Quick and dirty test for presence of the card. */
344         if (inb(STATUS(bse)) == 0xff)
345                 return 0;
346
347         /* Reset the adapter. I ought to make a hard reset, but it's not really necessary */
348
349         /*  DEB(printk("aha1542_test_port called \n")); */
350
351         /* In case some other card was probing here, reset interrupts */
352         aha1542_intr_reset(bse);        /* reset interrupts, so they don't block */
353
354         outb(SRST | IRST /*|SCRST */ , CONTROL(bse));
355
356         mdelay(20);             /* Wait a little bit for things to settle down. */
357
358         debug = 1;
359         /* Expect INIT and IDLE, any of the others are bad */
360         WAIT(STATUS(bse), STATMASK, INIT | IDLE, STST | DIAGF | INVDCMD | DF | CDF);
361
362         debug = 2;
363         /* Shouldn't have generated any interrupts during reset */
364         if (inb(INTRFLAGS(bse)) & INTRMASK)
365                 goto fail;
366
367
368         /* Perform a host adapter inquiry instead so we do not need to set
369            up the mailboxes ahead of time */
370
371         aha1542_out(bse, inquiry_cmd, 1);
372
373         debug = 3;
374         len = 4;
375         cmdp = &inquiry_result[0];
376
377         while (len--) {
378                 WAIT(STATUS(bse), DF, DF, 0);
379                 *cmdp++ = inb(DATA(bse));
380         }
381
382         debug = 8;
383         /* Reading port should reset DF */
384         if (inb(STATUS(bse)) & DF)
385                 goto fail;
386
387         debug = 9;
388         /* When HACC, command is completed, and we're though testing */
389         WAIT(INTRFLAGS(bse), HACC, HACC, 0);
390         /* now initialize adapter */
391
392         debug = 10;
393         /* Clear interrupts */
394         outb(IRST, CONTROL(bse));
395
396         debug = 11;
397
398         return debug;           /* 1 = ok */
399 fail:
400         return 0;               /* 0 = not ok */
401 }
402
403 /* A quick wrapper for do_aha1542_intr_handle to grab the spin lock */
404 static irqreturn_t do_aha1542_intr_handle(int dummy, void *dev_id)
405 {
406         unsigned long flags;
407         struct Scsi_Host *shost = dev_id;
408
409         spin_lock_irqsave(shost->host_lock, flags);
410         aha1542_intr_handle(shost);
411         spin_unlock_irqrestore(shost->host_lock, flags);
412         return IRQ_HANDLED;
413 }
414
415 /* A "high" level interrupt handler */
416 static void aha1542_intr_handle(struct Scsi_Host *shost)
417 {
418         void (*my_done) (Scsi_Cmnd *) = NULL;
419         int errstatus, mbi, mbo, mbistatus;
420         int number_serviced;
421         unsigned long flags;
422         Scsi_Cmnd *SCtmp;
423         int flag;
424         int needs_restart;
425         struct mailbox *mb;
426         struct ccb *ccb;
427
428         mb = HOSTDATA(shost)->mb;
429         ccb = HOSTDATA(shost)->ccb;
430
431 #ifdef DEBUG
432         {
433                 flag = inb(INTRFLAGS(shost->io_port));
434                 printk(KERN_DEBUG "aha1542_intr_handle: ");
435                 if (!(flag & ANYINTR))
436                         printk("no interrupt?");
437                 if (flag & MBIF)
438                         printk("MBIF ");
439                 if (flag & MBOA)
440                         printk("MBOF ");
441                 if (flag & HACC)
442                         printk("HACC ");
443                 if (flag & SCRD)
444                         printk("SCRD ");
445                 printk("status %02x\n", inb(STATUS(shost->io_port)));
446         };
447 #endif
448         number_serviced = 0;
449         needs_restart = 0;
450
451         while (1 == 1) {
452                 flag = inb(INTRFLAGS(shost->io_port));
453
454                 /* Check for unusual interrupts.  If any of these happen, we should
455                    probably do something special, but for now just printing a message
456                    is sufficient.  A SCSI reset detected is something that we really
457                    need to deal with in some way. */
458                 if (flag & ~MBIF) {
459                         if (flag & MBOA)
460                                 printk("MBOF ");
461                         if (flag & HACC)
462                                 printk("HACC ");
463                         if (flag & SCRD) {
464                                 needs_restart = 1;
465                                 printk("SCRD ");
466                         }
467                 }
468                 aha1542_intr_reset(shost->io_port);
469
470                 spin_lock_irqsave(&aha1542_lock, flags);
471                 mbi = HOSTDATA(shost)->aha1542_last_mbi_used + 1;
472                 if (mbi >= 2 * AHA1542_MAILBOXES)
473                         mbi = AHA1542_MAILBOXES;
474
475                 do {
476                         if (mb[mbi].status != 0)
477                                 break;
478                         mbi++;
479                         if (mbi >= 2 * AHA1542_MAILBOXES)
480                                 mbi = AHA1542_MAILBOXES;
481                 } while (mbi != HOSTDATA(shost)->aha1542_last_mbi_used);
482
483                 if (mb[mbi].status == 0) {
484                         spin_unlock_irqrestore(&aha1542_lock, flags);
485                         /* Hmm, no mail.  Must have read it the last time around */
486                         if (!number_serviced && !needs_restart)
487                                 printk(KERN_WARNING "aha1542.c: interrupt received, but no mail.\n");
488                         /* We detected a reset.  Restart all pending commands for
489                            devices that use the hard reset option */
490                         if (needs_restart)
491                                 aha1542_restart(shost);
492                         return;
493                 };
494
495                 mbo = (scsi2int(mb[mbi].ccbptr) - (SCSI_BUF_PA(&ccb[0]))) / sizeof(struct ccb);
496                 mbistatus = mb[mbi].status;
497                 mb[mbi].status = 0;
498                 HOSTDATA(shost)->aha1542_last_mbi_used = mbi;
499                 spin_unlock_irqrestore(&aha1542_lock, flags);
500
501 #ifdef DEBUG
502                 {
503                         if (ccb[mbo].tarstat | ccb[mbo].hastat)
504                                 printk(KERN_DEBUG "aha1542_command: returning %x (status %d)\n",
505                                        ccb[mbo].tarstat + ((int) ccb[mbo].hastat << 16), mb[mbi].status);
506                 };
507 #endif
508
509                 if (mbistatus == 3)
510                         continue;       /* Aborted command not found */
511
512 #ifdef DEBUG
513                 printk(KERN_DEBUG "...done %d %d\n", mbo, mbi);
514 #endif
515
516                 SCtmp = HOSTDATA(shost)->SCint[mbo];
517
518                 if (!SCtmp || !SCtmp->scsi_done) {
519                         printk(KERN_WARNING "aha1542_intr_handle: Unexpected interrupt\n");
520                         printk(KERN_WARNING "tarstat=%x, hastat=%x idlun=%x ccb#=%d \n", ccb[mbo].tarstat,
521                                ccb[mbo].hastat, ccb[mbo].idlun, mbo);
522                         return;
523                 }
524                 my_done = SCtmp->scsi_done;
525                 kfree(SCtmp->host_scribble);
526                 SCtmp->host_scribble = NULL;
527                 /* Fetch the sense data, and tuck it away, in the required slot.  The
528                    Adaptec automatically fetches it, and there is no guarantee that
529                    we will still have it in the cdb when we come back */
530                 if (ccb[mbo].tarstat == 2)
531                         memcpy(SCtmp->sense_buffer, &ccb[mbo].cdb[ccb[mbo].cdblen],
532                                SCSI_SENSE_BUFFERSIZE);
533
534
535                 /* is there mail :-) */
536
537                 /* more error checking left out here */
538                 if (mbistatus != 1)
539                         /* This is surely wrong, but I don't know what's right */
540                         errstatus = makecode(ccb[mbo].hastat, ccb[mbo].tarstat);
541                 else
542                         errstatus = 0;
543
544 #ifdef DEBUG
545                 if (errstatus)
546                         printk(KERN_DEBUG "(aha1542 error:%x %x %x) ", errstatus,
547                                ccb[mbo].hastat, ccb[mbo].tarstat);
548 #endif
549
550                 if (ccb[mbo].tarstat == 2) {
551 #ifdef DEBUG
552                         int i;
553 #endif
554                         DEB(printk("aha1542_intr_handle: sense:"));
555 #ifdef DEBUG
556                         for (i = 0; i < 12; i++)
557                                 printk("%02x ", ccb[mbo].cdb[ccb[mbo].cdblen + i]);
558                         printk("\n");
559 #endif
560                         /*
561                            DEB(printk("aha1542_intr_handle: buf:"));
562                            for (i = 0; i < bufflen; i++)
563                            printk("%02x ", ((unchar *)buff)[i]);
564                            printk("\n");
565                          */
566                 }
567                 DEB(if (errstatus) printk("aha1542_intr_handle: returning %6x\n", errstatus));
568                 SCtmp->result = errstatus;
569                 HOSTDATA(shost)->SCint[mbo] = NULL;     /* This effectively frees up the mailbox slot, as
570                                                            far as queuecommand is concerned */
571                 my_done(SCtmp);
572                 number_serviced++;
573         };
574 }
575
576 static int aha1542_queuecommand(Scsi_Cmnd * SCpnt, void (*done) (Scsi_Cmnd *))
577 {
578         unchar ahacmd = CMD_START_SCSI;
579         unchar direction;
580         unchar *cmd = (unchar *) SCpnt->cmnd;
581         unchar target = SCpnt->device->id;
582         unchar lun = SCpnt->device->lun;
583         unsigned long flags;
584         int bufflen = scsi_bufflen(SCpnt);
585         int mbo;
586         struct mailbox *mb;
587         struct ccb *ccb;
588
589         DEB(int i);
590
591         mb = HOSTDATA(SCpnt->device->host)->mb;
592         ccb = HOSTDATA(SCpnt->device->host)->ccb;
593
594         DEB(if (target > 1) {
595             SCpnt->result = DID_TIME_OUT << 16;
596             done(SCpnt); return 0;
597             }
598         );
599
600         if (*cmd == REQUEST_SENSE) {
601                 /* Don't do the command - we have the sense data already */
602 #if 0
603                 /* scsi_request_sense() provides a buffer of size 256,
604                    so there is no reason to expect equality */
605                 if (bufflen != SCSI_SENSE_BUFFERSIZE)
606                         printk(KERN_CRIT "aha1542: Wrong buffer length supplied "
607                                "for request sense (%d)\n", bufflen);
608 #endif
609                 SCpnt->result = 0;
610                 done(SCpnt);
611                 return 0;
612         }
613 #ifdef DEBUG
614         if (*cmd == READ_10 || *cmd == WRITE_10)
615                 i = xscsi2int(cmd + 2);
616         else if (*cmd == READ_6 || *cmd == WRITE_6)
617                 i = scsi2int(cmd + 2);
618         else
619                 i = -1;
620         if (done)
621                 printk(KERN_DEBUG "aha1542_queuecommand: dev %d cmd %02x pos %d len %d ", target, *cmd, i, bufflen);
622         else
623                 printk(KERN_DEBUG "aha1542_command: dev %d cmd %02x pos %d len %d ", target, *cmd, i, bufflen);
624         aha1542_stat();
625         printk(KERN_DEBUG "aha1542_queuecommand: dumping scsi cmd:");
626         for (i = 0; i < SCpnt->cmd_len; i++)
627                 printk("%02x ", cmd[i]);
628         printk("\n");
629         if (*cmd == WRITE_10 || *cmd == WRITE_6)
630                 return 0;       /* we are still testing, so *don't* write */
631 #endif
632         /* Use the outgoing mailboxes in a round-robin fashion, because this
633            is how the host adapter will scan for them */
634
635         spin_lock_irqsave(&aha1542_lock, flags);
636         mbo = HOSTDATA(SCpnt->device->host)->aha1542_last_mbo_used + 1;
637         if (mbo >= AHA1542_MAILBOXES)
638                 mbo = 0;
639
640         do {
641                 if (mb[mbo].status == 0 && HOSTDATA(SCpnt->device->host)->SCint[mbo] == NULL)
642                         break;
643                 mbo++;
644                 if (mbo >= AHA1542_MAILBOXES)
645                         mbo = 0;
646         } while (mbo != HOSTDATA(SCpnt->device->host)->aha1542_last_mbo_used);
647
648         if (mb[mbo].status || HOSTDATA(SCpnt->device->host)->SCint[mbo])
649                 panic("Unable to find empty mailbox for aha1542.\n");
650
651         HOSTDATA(SCpnt->device->host)->SCint[mbo] = SCpnt;      /* This will effectively prevent someone else from
652                                                            screwing with this cdb. */
653
654         HOSTDATA(SCpnt->device->host)->aha1542_last_mbo_used = mbo;
655         spin_unlock_irqrestore(&aha1542_lock, flags);
656
657 #ifdef DEBUG
658         printk(KERN_DEBUG "Sending command (%d %x)...", mbo, done);
659 #endif
660
661         any2scsi(mb[mbo].ccbptr, SCSI_BUF_PA(&ccb[mbo]));       /* This gets trashed for some reason */
662
663         memset(&ccb[mbo], 0, sizeof(struct ccb));
664
665         ccb[mbo].cdblen = SCpnt->cmd_len;
666
667         direction = 0;
668         if (*cmd == READ_10 || *cmd == READ_6)
669                 direction = 8;
670         else if (*cmd == WRITE_10 || *cmd == WRITE_6)
671                 direction = 16;
672
673         memcpy(ccb[mbo].cdb, cmd, ccb[mbo].cdblen);
674
675         if (bufflen) {
676                 struct scatterlist *sg;
677                 struct chain *cptr;
678 #ifdef DEBUG
679                 unsigned char *ptr;
680 #endif
681                 int i, sg_count = scsi_sg_count(SCpnt);
682                 ccb[mbo].op = 2;        /* SCSI Initiator Command  w/scatter-gather */
683                 SCpnt->host_scribble = kmalloc(sizeof(*cptr)*sg_count,
684                                                          GFP_KERNEL | GFP_DMA);
685                 cptr = (struct chain *) SCpnt->host_scribble;
686                 if (cptr == NULL) {
687                         /* free the claimed mailbox slot */
688                         HOSTDATA(SCpnt->device->host)->SCint[mbo] = NULL;
689                         return SCSI_MLQUEUE_HOST_BUSY;
690                 }
691                 scsi_for_each_sg(SCpnt, sg, sg_count, i) {
692                         any2scsi(cptr[i].dataptr, SCSI_SG_PA(sg));
693                         if (SCSI_SG_PA(sg) + sg->length - 1 > ISA_DMA_THRESHOLD)
694                                 BAD_SG_DMA(SCpnt, scsi_sglist(SCpnt), sg_count, i);
695                         any2scsi(cptr[i].datalen, sg->length);
696                 };
697                 any2scsi(ccb[mbo].datalen, sg_count * sizeof(struct chain));
698                 any2scsi(ccb[mbo].dataptr, SCSI_BUF_PA(cptr));
699 #ifdef DEBUG
700                 printk("cptr %x: ", cptr);
701                 ptr = (unsigned char *) cptr;
702                 for (i = 0; i < 18; i++)
703                         printk("%02x ", ptr[i]);
704 #endif
705         } else {
706                 ccb[mbo].op = 0;        /* SCSI Initiator Command */
707                 SCpnt->host_scribble = NULL;
708                 any2scsi(ccb[mbo].datalen, 0);
709                 any2scsi(ccb[mbo].dataptr, 0);
710         };
711         ccb[mbo].idlun = (target & 7) << 5 | direction | (lun & 7);     /*SCSI Target Id */
712         ccb[mbo].rsalen = 16;
713         ccb[mbo].linkptr[0] = ccb[mbo].linkptr[1] = ccb[mbo].linkptr[2] = 0;
714         ccb[mbo].commlinkid = 0;
715
716 #ifdef DEBUG
717         {
718                 int i;
719                 printk(KERN_DEBUG "aha1542_command: sending.. ");
720                 for (i = 0; i < sizeof(ccb[mbo]) - 10; i++)
721                         printk("%02x ", ((unchar *) & ccb[mbo])[i]);
722         };
723 #endif
724
725         if (done) {
726                 DEB(printk("aha1542_queuecommand: now waiting for interrupt ");
727                     aha1542_stat());
728                 SCpnt->scsi_done = done;
729                 mb[mbo].status = 1;
730                 aha1542_out(SCpnt->device->host->io_port, &ahacmd, 1);  /* start scsi command */
731                 DEB(aha1542_stat());
732         } else
733                 printk("aha1542_queuecommand: done can't be NULL\n");
734
735         return 0;
736 }
737
738 /* Initialize mailboxes */
739 static void setup_mailboxes(int bse, struct Scsi_Host *shpnt)
740 {
741         int i;
742         struct mailbox *mb;
743         struct ccb *ccb;
744
745         unchar cmd[5] = { CMD_MBINIT, AHA1542_MAILBOXES, 0, 0, 0};
746
747         mb = HOSTDATA(shpnt)->mb;
748         ccb = HOSTDATA(shpnt)->ccb;
749
750         for (i = 0; i < AHA1542_MAILBOXES; i++) {
751                 mb[i].status = mb[AHA1542_MAILBOXES + i].status = 0;
752                 any2scsi(mb[i].ccbptr, SCSI_BUF_PA(&ccb[i]));
753         };
754         aha1542_intr_reset(bse);        /* reset interrupts, so they don't block */
755         any2scsi((cmd + 2), SCSI_BUF_PA(mb));
756         aha1542_out(bse, cmd, 5);
757         WAIT(INTRFLAGS(bse), INTRMASK, HACC, 0);
758         while (0) {
759 fail:
760                 printk(KERN_ERR "aha1542_detect: failed setting up mailboxes\n");
761         }
762         aha1542_intr_reset(bse);
763 }
764
765 static int __init aha1542_getconfig(int base_io, unsigned char *irq_level, unsigned char *dma_chan, unsigned char *scsi_id)
766 {
767         unchar inquiry_cmd[] = {CMD_RETCONF};
768         unchar inquiry_result[3];
769         int i;
770         i = inb(STATUS(base_io));
771         if (i & DF) {
772                 i = inb(DATA(base_io));
773         };
774         aha1542_out(base_io, inquiry_cmd, 1);
775         aha1542_in(base_io, inquiry_result, 3);
776         WAIT(INTRFLAGS(base_io), INTRMASK, HACC, 0);
777         while (0) {
778 fail:
779                 printk(KERN_ERR "aha1542_detect: query board settings\n");
780         }
781         aha1542_intr_reset(base_io);
782         switch (inquiry_result[0]) {
783         case 0x80:
784                 *dma_chan = 7;
785                 break;
786         case 0x40:
787                 *dma_chan = 6;
788                 break;
789         case 0x20:
790                 *dma_chan = 5;
791                 break;
792         case 0x01:
793                 *dma_chan = 0;
794                 break;
795         case 0:
796                 /* This means that the adapter, although Adaptec 1542 compatible, doesn't use a DMA channel.
797                    Currently only aware of the BusLogic BT-445S VL-Bus adapter which needs this. */
798                 *dma_chan = 0xFF;
799                 break;
800         default:
801                 printk(KERN_ERR "Unable to determine Adaptec DMA priority.  Disabling board\n");
802                 return -1;
803         };
804         switch (inquiry_result[1]) {
805         case 0x40:
806                 *irq_level = 15;
807                 break;
808         case 0x20:
809                 *irq_level = 14;
810                 break;
811         case 0x8:
812                 *irq_level = 12;
813                 break;
814         case 0x4:
815                 *irq_level = 11;
816                 break;
817         case 0x2:
818                 *irq_level = 10;
819                 break;
820         case 0x1:
821                 *irq_level = 9;
822                 break;
823         default:
824                 printk(KERN_ERR "Unable to determine Adaptec IRQ level.  Disabling board\n");
825                 return -1;
826         };
827         *scsi_id = inquiry_result[2] & 7;
828         return 0;
829 }
830
831 /* This function should only be called for 1542C boards - we can detect
832    the special firmware settings and unlock the board */
833
834 static int __init aha1542_mbenable(int base)
835 {
836         static unchar mbenable_cmd[3];
837         static unchar mbenable_result[2];
838         int retval;
839
840         retval = BIOS_TRANSLATION_6432;
841
842         mbenable_cmd[0] = CMD_EXTBIOS;
843         aha1542_out(base, mbenable_cmd, 1);
844         if (aha1542_in1(base, mbenable_result, 2))
845                 return retval;
846         WAITd(INTRFLAGS(base), INTRMASK, HACC, 0, 100);
847         aha1542_intr_reset(base);
848
849         if ((mbenable_result[0] & 0x08) || mbenable_result[1]) {
850                 mbenable_cmd[0] = CMD_MBENABLE;
851                 mbenable_cmd[1] = 0;
852                 mbenable_cmd[2] = mbenable_result[1];
853
854                 if ((mbenable_result[0] & 0x08) && (mbenable_result[1] & 0x03))
855                         retval = BIOS_TRANSLATION_25563;
856
857                 aha1542_out(base, mbenable_cmd, 3);
858                 WAIT(INTRFLAGS(base), INTRMASK, HACC, 0);
859         };
860         while (0) {
861 fail:
862                 printk(KERN_ERR "aha1542_mbenable: Mailbox init failed\n");
863         }
864         aha1542_intr_reset(base);
865         return retval;
866 }
867
868 /* Query the board to find out if it is a 1542 or a 1740, or whatever. */
869 static int __init aha1542_query(int base_io, int *transl)
870 {
871         unchar inquiry_cmd[] = {CMD_INQUIRY};
872         unchar inquiry_result[4];
873         int i;
874         i = inb(STATUS(base_io));
875         if (i & DF) {
876                 i = inb(DATA(base_io));
877         };
878         aha1542_out(base_io, inquiry_cmd, 1);
879         aha1542_in(base_io, inquiry_result, 4);
880         WAIT(INTRFLAGS(base_io), INTRMASK, HACC, 0);
881         while (0) {
882 fail:
883                 printk(KERN_ERR "aha1542_detect: query card type\n");
884         }
885         aha1542_intr_reset(base_io);
886
887         *transl = BIOS_TRANSLATION_6432;        /* Default case */
888
889         /* For an AHA1740 series board, we ignore the board since there is a
890            hardware bug which can lead to wrong blocks being returned if the board
891            is operating in the 1542 emulation mode.  Since there is an extended mode
892            driver, we simply ignore the board and let the 1740 driver pick it up.
893          */
894
895         if (inquiry_result[0] == 0x43) {
896                 printk(KERN_INFO "aha1542.c: Emulation mode not supported for AHA 174N hardware.\n");
897                 return 1;
898         };
899
900         /* Always call this - boards that do not support extended bios translation
901            will ignore the command, and we will set the proper default */
902
903         *transl = aha1542_mbenable(base_io);
904
905         return 0;
906 }
907
908 #ifndef MODULE
909 static char *setup_str[MAXBOARDS] __initdata;
910 static int setup_idx = 0;
911
912 static void __init aha1542_setup(char *str, int *ints)
913 {
914         const char *ahausage = "aha1542: usage: aha1542=<PORTBASE>[,<BUSON>,<BUSOFF>[,<DMASPEED>]]\n";
915         int setup_portbase;
916
917         if (setup_idx >= MAXBOARDS) {
918                 printk(KERN_ERR "aha1542: aha1542_setup called too many times! Bad LILO params ?\n");
919                 printk(KERN_ERR "   Entryline 1: %s\n", setup_str[0]);
920                 printk(KERN_ERR "   Entryline 2: %s\n", setup_str[1]);
921                 printk(KERN_ERR "   This line:   %s\n", str);
922                 return;
923         }
924         if (ints[0] < 1 || ints[0] > 4) {
925                 printk(KERN_ERR "aha1542: %s\n", str);
926                 printk(ahausage);
927                 printk(KERN_ERR "aha1542: Wrong parameters may cause system malfunction.. We try anyway..\n");
928         }
929         setup_called[setup_idx] = ints[0];
930         setup_str[setup_idx] = str;
931
932         setup_portbase = ints[0] >= 1 ? ints[1] : 0;    /* Preserve the default value.. */
933         setup_buson[setup_idx] = ints[0] >= 2 ? ints[2] : 7;
934         setup_busoff[setup_idx] = ints[0] >= 3 ? ints[3] : 5;
935         if (ints[0] >= 4) 
936         {
937                 int atbt = -1;
938                 switch (ints[4]) {
939                 case 5:
940                         atbt = 0x00;
941                         break;
942                 case 6:
943                         atbt = 0x04;
944                         break;
945                 case 7:
946                         atbt = 0x01;
947                         break;
948                 case 8:
949                         atbt = 0x02;
950                         break;
951                 case 10:
952                         atbt = 0x03;
953                         break;
954                 default:
955                         printk(KERN_ERR "aha1542: %s\n", str);
956                         printk(ahausage);
957                         printk(KERN_ERR "aha1542: Valid values for DMASPEED are 5-8, 10 MB/s.  Using jumper defaults.\n");
958                         break;
959                 }
960                 setup_dmaspeed[setup_idx] = atbt;
961         }
962         if (setup_portbase != 0)
963                 bases[setup_idx] = setup_portbase;
964
965         ++setup_idx;
966 }
967
968 static int __init do_setup(char *str)
969 {
970         int ints[5];
971
972         int count=setup_idx;
973
974         get_options(str, ARRAY_SIZE(ints), ints);
975         aha1542_setup(str,ints);
976
977         return count<setup_idx;
978 }
979
980 __setup("aha1542=",do_setup);
981 #endif
982
983 /* return non-zero on detection */
984 static int __init aha1542_detect(struct scsi_host_template * tpnt)
985 {
986         unsigned char dma_chan;
987         unsigned char irq_level;
988         unsigned char scsi_id;
989         unsigned long flags;
990         unsigned int base_io;
991         int trans;
992         struct Scsi_Host *shpnt = NULL;
993         int count = 0;
994         int indx;
995
996         DEB(printk("aha1542_detect: \n"));
997
998         tpnt->proc_name = "aha1542";
999
1000 #ifdef MODULE
1001         bases[0] = aha1542[0];
1002         setup_buson[0] = aha1542[1];
1003         setup_busoff[0] = aha1542[2];
1004         {
1005                 int atbt = -1;
1006                 switch (aha1542[3]) {
1007                 case 5:
1008                         atbt = 0x00;
1009                         break;
1010                 case 6:
1011                         atbt = 0x04;
1012                         break;
1013                 case 7:
1014                         atbt = 0x01;
1015                         break;
1016                 case 8:
1017                         atbt = 0x02;
1018                         break;
1019                 case 10:
1020                         atbt = 0x03;
1021                         break;
1022                 };
1023                 setup_dmaspeed[0] = atbt;
1024         }
1025 #endif
1026
1027         /*
1028          *      Find MicroChannel cards (AHA1640)
1029          */
1030 #ifdef CONFIG_MCA_LEGACY
1031         if(MCA_bus) {
1032                 int slot = 0;
1033                 int pos = 0;
1034
1035                 for (indx = 0; (slot != MCA_NOTFOUND) && (indx < ARRAY_SIZE(bases)); indx++) {
1036
1037                         if (bases[indx])
1038                                 continue;
1039
1040                         /* Detect only AHA-1640 cards -- MCA ID 0F1F */
1041                         slot = mca_find_unused_adapter(0x0f1f, slot);
1042                         if (slot == MCA_NOTFOUND)
1043                                 break;
1044
1045                         /* Found one */
1046                         pos = mca_read_stored_pos(slot, 3);
1047
1048                         /* Decode address */
1049                         if (pos & 0x80) {
1050                                 if (pos & 0x02) {
1051                                         if (pos & 0x01)
1052                                                 bases[indx] = 0x334;
1053                                         else
1054                                                 bases[indx] = 0x234;
1055                                 } else {
1056                                         if (pos & 0x01)
1057                                                 bases[indx] = 0x134;
1058                                 }
1059                         } else {
1060                                 if (pos & 0x02) {
1061                                         if (pos & 0x01)
1062                                                 bases[indx] = 0x330;
1063                                         else
1064                                                 bases[indx] = 0x230;
1065                                 } else {
1066                                         if (pos & 0x01)
1067                                                 bases[indx] = 0x130;
1068                                 }
1069                         }
1070
1071                         /* No need to decode IRQ and Arb level -- those are
1072                          * read off the card later.
1073                          */
1074                         printk(KERN_INFO "Found an AHA-1640 in MCA slot %d, I/O 0x%04x\n", slot, bases[indx]);
1075
1076                         mca_set_adapter_name(slot, "Adapter AHA-1640");
1077                         mca_set_adapter_procfn(slot, NULL, NULL);
1078                         mca_mark_as_used(slot);
1079
1080                         /* Go on */
1081                         slot++;
1082                 }
1083
1084         }
1085 #endif
1086
1087         /*
1088          *      Hunt for ISA Plug'n'Pray Adaptecs (AHA1535)
1089          */
1090
1091         if(isapnp)
1092         {
1093                 struct pnp_dev *pdev = NULL;
1094                 for(indx = 0; indx < ARRAY_SIZE(bases); indx++) {
1095                         if(bases[indx])
1096                                 continue;
1097                         pdev = pnp_find_dev(NULL, ISAPNP_VENDOR('A', 'D', 'P'), 
1098                                 ISAPNP_FUNCTION(0x1542), pdev);
1099                         if(pdev==NULL)
1100                                 break;
1101                         /*
1102                          *      Activate the PnP card
1103                          */
1104
1105                         if(pnp_device_attach(pdev)<0)
1106                                 continue;
1107
1108                         if(pnp_activate_dev(pdev)<0) {
1109                                 pnp_device_detach(pdev);
1110                                 continue;
1111                         }
1112
1113                         if(!pnp_port_valid(pdev, 0)) {
1114                                 pnp_device_detach(pdev);
1115                                 continue;
1116                         }
1117
1118                         bases[indx] = pnp_port_start(pdev, 0);
1119
1120                         /* The card can be queried for its DMA, we have 
1121                            the DMA set up that is enough */
1122
1123                         printk(KERN_INFO "ISAPnP found an AHA1535 at I/O 0x%03X\n", bases[indx]);
1124                 }
1125         }
1126         for (indx = 0; indx < ARRAY_SIZE(bases); indx++)
1127                 if (bases[indx] != 0 && request_region(bases[indx], 4, "aha1542")) {
1128                         shpnt = scsi_register(tpnt,
1129                                         sizeof(struct aha1542_hostdata));
1130
1131                         if(shpnt==NULL) {
1132                                 release_region(bases[indx], 4);
1133                                 continue;
1134                         }
1135                         /* For now we do this - until kmalloc is more intelligent
1136                            we are resigned to stupid hacks like this */
1137                         if (SCSI_BUF_PA(shpnt) >= ISA_DMA_THRESHOLD) {
1138                                 printk(KERN_ERR "Invalid address for shpnt with 1542.\n");
1139                                 goto unregister;
1140                         }
1141                         if (!aha1542_test_port(bases[indx], shpnt))
1142                                 goto unregister;
1143
1144
1145                         base_io = bases[indx];
1146
1147                         /* Set the Bus on/off-times as not to ruin floppy performance */
1148                         {
1149                                 unchar oncmd[] = {CMD_BUSON_TIME, 7};
1150                                 unchar offcmd[] = {CMD_BUSOFF_TIME, 5};
1151
1152                                 if (setup_called[indx]) {
1153                                         oncmd[1] = setup_buson[indx];
1154                                         offcmd[1] = setup_busoff[indx];
1155                                 }
1156                                 aha1542_intr_reset(base_io);
1157                                 aha1542_out(base_io, oncmd, 2);
1158                                 WAIT(INTRFLAGS(base_io), INTRMASK, HACC, 0);
1159                                 aha1542_intr_reset(base_io);
1160                                 aha1542_out(base_io, offcmd, 2);
1161                                 WAIT(INTRFLAGS(base_io), INTRMASK, HACC, 0);
1162                                 if (setup_dmaspeed[indx] >= 0) {
1163                                         unchar dmacmd[] = {CMD_DMASPEED, 0};
1164                                         dmacmd[1] = setup_dmaspeed[indx];
1165                                         aha1542_intr_reset(base_io);
1166                                         aha1542_out(base_io, dmacmd, 2);
1167                                         WAIT(INTRFLAGS(base_io), INTRMASK, HACC, 0);
1168                                 }
1169                                 while (0) {
1170 fail:
1171                                         printk(KERN_ERR "aha1542_detect: setting bus on/off-time failed\n");
1172                                 }
1173                                 aha1542_intr_reset(base_io);
1174                         }
1175                         if (aha1542_query(base_io, &trans))
1176                                 goto unregister;
1177
1178                         if (aha1542_getconfig(base_io, &irq_level, &dma_chan, &scsi_id) == -1)
1179                                 goto unregister;
1180
1181                         printk(KERN_INFO "Configuring Adaptec (SCSI-ID %d) at IO:%x, IRQ %d", scsi_id, base_io, irq_level);
1182                         if (dma_chan != 0xFF)
1183                                 printk(", DMA priority %d", dma_chan);
1184                         printk("\n");
1185
1186                         DEB(aha1542_stat());
1187                         setup_mailboxes(base_io, shpnt);
1188
1189                         DEB(aha1542_stat());
1190
1191                         DEB(printk("aha1542_detect: enable interrupt channel %d\n", irq_level));
1192                         spin_lock_irqsave(&aha1542_lock, flags);
1193                         if (request_irq(irq_level, do_aha1542_intr_handle, 0,
1194                                         "aha1542", shpnt)) {
1195                                 printk(KERN_ERR "Unable to allocate IRQ for adaptec controller.\n");
1196                                 spin_unlock_irqrestore(&aha1542_lock, flags);
1197                                 goto unregister;
1198                         }
1199                         if (dma_chan != 0xFF) {
1200                                 if (request_dma(dma_chan, "aha1542")) {
1201                                         printk(KERN_ERR "Unable to allocate DMA channel for Adaptec.\n");
1202                                         free_irq(irq_level, shpnt);
1203                                         spin_unlock_irqrestore(&aha1542_lock, flags);
1204                                         goto unregister;
1205                                 }
1206                                 if (dma_chan == 0 || dma_chan >= 5) {
1207                                         set_dma_mode(dma_chan, DMA_MODE_CASCADE);
1208                                         enable_dma(dma_chan);
1209                                 }
1210                         }
1211
1212                         shpnt->this_id = scsi_id;
1213                         shpnt->unique_id = base_io;
1214                         shpnt->io_port = base_io;
1215                         shpnt->n_io_port = 4;   /* Number of bytes of I/O space used */
1216                         shpnt->dma_channel = dma_chan;
1217                         shpnt->irq = irq_level;
1218                         HOSTDATA(shpnt)->bios_translation = trans;
1219                         if (trans == BIOS_TRANSLATION_25563)
1220                                 printk(KERN_INFO "aha1542.c: Using extended bios translation\n");
1221                         HOSTDATA(shpnt)->aha1542_last_mbi_used = (2 * AHA1542_MAILBOXES - 1);
1222                         HOSTDATA(shpnt)->aha1542_last_mbo_used = (AHA1542_MAILBOXES - 1);
1223                         memset(HOSTDATA(shpnt)->SCint, 0, sizeof(HOSTDATA(shpnt)->SCint));
1224                         spin_unlock_irqrestore(&aha1542_lock, flags);
1225 #if 0
1226                         DEB(printk(" *** READ CAPACITY ***\n"));
1227
1228                         {
1229                                 unchar buf[8];
1230                                 static unchar cmd[] = { READ_CAPACITY, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
1231                                 int i;
1232
1233                                 for (i = 0; i < sizeof(buf); ++i)
1234                                         buf[i] = 0x87;
1235                                 for (i = 0; i < 2; ++i)
1236                                         if (!aha1542_command(i, cmd, buf, sizeof(buf))) {
1237                                                 printk(KERN_DEBUG "aha_detect: LU %d sector_size %d device_size %d\n",
1238                                                        i, xscsi2int(buf + 4), xscsi2int(buf));
1239                                         }
1240                         }
1241
1242                         DEB(printk(" *** NOW RUNNING MY OWN TEST *** \n"));
1243
1244                         for (i = 0; i < 4; ++i) {
1245                                 unsigned char cmd[10];
1246                                 static buffer[512];
1247
1248                                 cmd[0] = READ_10;
1249                                 cmd[1] = 0;
1250                                 xany2scsi(cmd + 2, i);
1251                                 cmd[6] = 0;
1252                                 cmd[7] = 0;
1253                                 cmd[8] = 1;
1254                                 cmd[9] = 0;
1255                                 aha1542_command(0, cmd, buffer, 512);
1256                         }
1257 #endif
1258                         count++;
1259                         continue;
1260 unregister:
1261                         release_region(bases[indx], 4);
1262                         scsi_unregister(shpnt);
1263                         continue;
1264
1265                 };
1266
1267         return count;
1268 }
1269
1270 static int aha1542_release(struct Scsi_Host *shost)
1271 {
1272         if (shost->irq)
1273                 free_irq(shost->irq, shost);
1274         if (shost->dma_channel != 0xff)
1275                 free_dma(shost->dma_channel);
1276         if (shost->io_port && shost->n_io_port)
1277                 release_region(shost->io_port, shost->n_io_port);
1278         scsi_unregister(shost);
1279         return 0;
1280 }
1281
1282 static int aha1542_restart(struct Scsi_Host *shost)
1283 {
1284         int i;
1285         int count = 0;
1286 #if 0
1287         unchar ahacmd = CMD_START_SCSI;
1288 #endif
1289
1290         for (i = 0; i < AHA1542_MAILBOXES; i++)
1291                 if (HOSTDATA(shost)->SCint[i] &&
1292                     !(HOSTDATA(shost)->SCint[i]->device->soft_reset)) {
1293 #if 0
1294                         HOSTDATA(shost)->mb[i].status = 1;      /* Indicate ready to restart... */
1295 #endif
1296                         count++;
1297                 }
1298         printk(KERN_DEBUG "Potential to restart %d stalled commands...\n", count);
1299 #if 0
1300         /* start scsi command */
1301         if (count)
1302                 aha1542_out(shost->io_port, &ahacmd, 1);
1303 #endif
1304         return 0;
1305 }
1306
1307 /*
1308  * This is a device reset.  This is handled by sending a special command
1309  * to the device.
1310  */
1311 static int aha1542_dev_reset(Scsi_Cmnd * SCpnt)
1312 {
1313         unsigned long flags;
1314         struct mailbox *mb;
1315         unchar target = SCpnt->device->id;
1316         unchar lun = SCpnt->device->lun;
1317         int mbo;
1318         struct ccb *ccb;
1319         unchar ahacmd = CMD_START_SCSI;
1320
1321         ccb = HOSTDATA(SCpnt->device->host)->ccb;
1322         mb = HOSTDATA(SCpnt->device->host)->mb;
1323
1324         spin_lock_irqsave(&aha1542_lock, flags);
1325         mbo = HOSTDATA(SCpnt->device->host)->aha1542_last_mbo_used + 1;
1326         if (mbo >= AHA1542_MAILBOXES)
1327                 mbo = 0;
1328
1329         do {
1330                 if (mb[mbo].status == 0 && HOSTDATA(SCpnt->device->host)->SCint[mbo] == NULL)
1331                         break;
1332                 mbo++;
1333                 if (mbo >= AHA1542_MAILBOXES)
1334                         mbo = 0;
1335         } while (mbo != HOSTDATA(SCpnt->device->host)->aha1542_last_mbo_used);
1336
1337         if (mb[mbo].status || HOSTDATA(SCpnt->device->host)->SCint[mbo])
1338                 panic("Unable to find empty mailbox for aha1542.\n");
1339
1340         HOSTDATA(SCpnt->device->host)->SCint[mbo] = SCpnt;      /* This will effectively
1341                                                            prevent someone else from
1342                                                            screwing with this cdb. */
1343
1344         HOSTDATA(SCpnt->device->host)->aha1542_last_mbo_used = mbo;
1345         spin_unlock_irqrestore(&aha1542_lock, flags);
1346
1347         any2scsi(mb[mbo].ccbptr, SCSI_BUF_PA(&ccb[mbo]));       /* This gets trashed for some reason */
1348
1349         memset(&ccb[mbo], 0, sizeof(struct ccb));
1350
1351         ccb[mbo].op = 0x81;     /* BUS DEVICE RESET */
1352
1353         ccb[mbo].idlun = (target & 7) << 5 | (lun & 7);         /*SCSI Target Id */
1354
1355         ccb[mbo].linkptr[0] = ccb[mbo].linkptr[1] = ccb[mbo].linkptr[2] = 0;
1356         ccb[mbo].commlinkid = 0;
1357
1358         /* 
1359          * Now tell the 1542 to flush all pending commands for this 
1360          * target 
1361          */
1362         aha1542_out(SCpnt->device->host->io_port, &ahacmd, 1);
1363
1364         scmd_printk(KERN_WARNING, SCpnt,
1365                 "Trying device reset for target\n");
1366
1367         return SUCCESS;
1368
1369
1370 #ifdef ERIC_neverdef
1371         /* 
1372          * With the 1542 we apparently never get an interrupt to
1373          * acknowledge a device reset being sent.  Then again, Leonard
1374          * says we are doing this wrong in the first place...
1375          *
1376          * Take a wait and see attitude.  If we get spurious interrupts,
1377          * then the device reset is doing something sane and useful, and
1378          * we will wait for the interrupt to post completion.
1379          */
1380         printk(KERN_WARNING "Sent BUS DEVICE RESET to target %d\n", SCpnt->target);
1381
1382         /*
1383          * Free the command block for all commands running on this 
1384          * target... 
1385          */
1386         for (i = 0; i < AHA1542_MAILBOXES; i++) {
1387                 if (HOSTDATA(SCpnt->host)->SCint[i] &&
1388                     HOSTDATA(SCpnt->host)->SCint[i]->target == SCpnt->target) {
1389                         Scsi_Cmnd *SCtmp;
1390                         SCtmp = HOSTDATA(SCpnt->host)->SCint[i];
1391                         kfree(SCtmp->host_scribble);
1392                         SCtmp->host_scribble = NULL;
1393                         HOSTDATA(SCpnt->host)->SCint[i] = NULL;
1394                         HOSTDATA(SCpnt->host)->mb[i].status = 0;
1395                 }
1396         }
1397         return SUCCESS;
1398
1399         return FAILED;
1400 #endif                          /* ERIC_neverdef */
1401 }
1402
1403 static int aha1542_bus_reset(Scsi_Cmnd * SCpnt)
1404 {
1405         int i;
1406
1407         /* 
1408          * This does a scsi reset for all devices on the bus.
1409          * In principle, we could also reset the 1542 - should
1410          * we do this?  Try this first, and we can add that later
1411          * if it turns out to be useful.
1412          */
1413         outb(SCRST, CONTROL(SCpnt->device->host->io_port));
1414
1415         /*
1416          * Wait for the thing to settle down a bit.  Unfortunately
1417          * this is going to basically lock up the machine while we
1418          * wait for this to complete.  To be 100% correct, we need to
1419          * check for timeout, and if we are doing something like this
1420          * we are pretty desperate anyways.
1421          */
1422         ssleep(4);
1423
1424         spin_lock_irq(SCpnt->device->host->host_lock);
1425
1426         WAIT(STATUS(SCpnt->device->host->io_port),
1427              STATMASK, INIT | IDLE, STST | DIAGF | INVDCMD | DF | CDF);
1428
1429         /*
1430          * Now try to pick up the pieces.  For all pending commands,
1431          * free any internal data structures, and basically clear things
1432          * out.  We do not try and restart any commands or anything - 
1433          * the strategy handler takes care of that crap.
1434          */
1435         printk(KERN_WARNING "Sent BUS RESET to scsi host %d\n", SCpnt->device->host->host_no);
1436
1437         for (i = 0; i < AHA1542_MAILBOXES; i++) {
1438                 if (HOSTDATA(SCpnt->device->host)->SCint[i] != NULL) {
1439                         Scsi_Cmnd *SCtmp;
1440                         SCtmp = HOSTDATA(SCpnt->device->host)->SCint[i];
1441
1442
1443                         if (SCtmp->device->soft_reset) {
1444                                 /*
1445                                  * If this device implements the soft reset option,
1446                                  * then it is still holding onto the command, and
1447                                  * may yet complete it.  In this case, we don't
1448                                  * flush the data.
1449                                  */
1450                                 continue;
1451                         }
1452                         kfree(SCtmp->host_scribble);
1453                         SCtmp->host_scribble = NULL;
1454                         HOSTDATA(SCpnt->device->host)->SCint[i] = NULL;
1455                         HOSTDATA(SCpnt->device->host)->mb[i].status = 0;
1456                 }
1457         }
1458
1459         spin_unlock_irq(SCpnt->device->host->host_lock);
1460         return SUCCESS;
1461
1462 fail:
1463         spin_unlock_irq(SCpnt->device->host->host_lock);
1464         return FAILED;
1465 }
1466
1467 static int aha1542_host_reset(Scsi_Cmnd * SCpnt)
1468 {
1469         int i;
1470
1471         /* 
1472          * This does a scsi reset for all devices on the bus.
1473          * In principle, we could also reset the 1542 - should
1474          * we do this?  Try this first, and we can add that later
1475          * if it turns out to be useful.
1476          */
1477         outb(HRST | SCRST, CONTROL(SCpnt->device->host->io_port));
1478
1479         /*
1480          * Wait for the thing to settle down a bit.  Unfortunately
1481          * this is going to basically lock up the machine while we
1482          * wait for this to complete.  To be 100% correct, we need to
1483          * check for timeout, and if we are doing something like this
1484          * we are pretty desperate anyways.
1485          */
1486         ssleep(4);
1487         spin_lock_irq(SCpnt->device->host->host_lock);
1488
1489         WAIT(STATUS(SCpnt->device->host->io_port),
1490              STATMASK, INIT | IDLE, STST | DIAGF | INVDCMD | DF | CDF);
1491
1492         /*
1493          * We need to do this too before the 1542 can interact with
1494          * us again.
1495          */
1496         setup_mailboxes(SCpnt->device->host->io_port, SCpnt->device->host);
1497
1498         /*
1499          * Now try to pick up the pieces.  For all pending commands,
1500          * free any internal data structures, and basically clear things
1501          * out.  We do not try and restart any commands or anything - 
1502          * the strategy handler takes care of that crap.
1503          */
1504         printk(KERN_WARNING "Sent BUS RESET to scsi host %d\n", SCpnt->device->host->host_no);
1505
1506         for (i = 0; i < AHA1542_MAILBOXES; i++) {
1507                 if (HOSTDATA(SCpnt->device->host)->SCint[i] != NULL) {
1508                         Scsi_Cmnd *SCtmp;
1509                         SCtmp = HOSTDATA(SCpnt->device->host)->SCint[i];
1510
1511                         if (SCtmp->device->soft_reset) {
1512                                 /*
1513                                  * If this device implements the soft reset option,
1514                                  * then it is still holding onto the command, and
1515                                  * may yet complete it.  In this case, we don't
1516                                  * flush the data.
1517                                  */
1518                                 continue;
1519                         }
1520                         kfree(SCtmp->host_scribble);
1521                         SCtmp->host_scribble = NULL;
1522                         HOSTDATA(SCpnt->device->host)->SCint[i] = NULL;
1523                         HOSTDATA(SCpnt->device->host)->mb[i].status = 0;
1524                 }
1525         }
1526
1527         spin_unlock_irq(SCpnt->device->host->host_lock);
1528         return SUCCESS;
1529
1530 fail:
1531         spin_unlock_irq(SCpnt->device->host->host_lock);
1532         return FAILED;
1533 }
1534
1535 #if 0
1536 /*
1537  * These are the old error handling routines.  They are only temporarily
1538  * here while we play with the new error handling code.
1539  */
1540 static int aha1542_old_abort(Scsi_Cmnd * SCpnt)
1541 {
1542 #if 0
1543         unchar ahacmd = CMD_START_SCSI;
1544         unsigned long flags;
1545         struct mailbox *mb;
1546         int mbi, mbo, i;
1547
1548         printk(KERN_DEBUG "In aha1542_abort: %x %x\n",
1549                inb(STATUS(SCpnt->host->io_port)),
1550                inb(INTRFLAGS(SCpnt->host->io_port)));
1551
1552         spin_lock_irqsave(&aha1542_lock, flags);
1553         mb = HOSTDATA(SCpnt->host)->mb;
1554         mbi = HOSTDATA(SCpnt->host)->aha1542_last_mbi_used + 1;
1555         if (mbi >= 2 * AHA1542_MAILBOXES)
1556                 mbi = AHA1542_MAILBOXES;
1557
1558         do {
1559                 if (mb[mbi].status != 0)
1560                         break;
1561                 mbi++;
1562                 if (mbi >= 2 * AHA1542_MAILBOXES)
1563                         mbi = AHA1542_MAILBOXES;
1564         } while (mbi != HOSTDATA(SCpnt->host)->aha1542_last_mbi_used);
1565         spin_unlock_irqrestore(&aha1542_lock, flags);
1566
1567         if (mb[mbi].status) {
1568                 printk(KERN_ERR "Lost interrupt discovered on irq %d - attempting to recover\n",
1569                        SCpnt->host->irq);
1570                 aha1542_intr_handle(SCpnt->host, NULL);
1571                 return 0;
1572         }
1573         /* OK, no lost interrupt.  Try looking to see how many pending commands
1574            we think we have. */
1575
1576         for (i = 0; i < AHA1542_MAILBOXES; i++)
1577                 if (HOSTDATA(SCpnt->host)->SCint[i]) {
1578                         if (HOSTDATA(SCpnt->host)->SCint[i] == SCpnt) {
1579                                 printk(KERN_ERR "Timed out command pending for %s\n",
1580                                        SCpnt->request->rq_disk ?
1581                                        SCpnt->request->rq_disk->disk_name : "?"
1582                                        );
1583                                 if (HOSTDATA(SCpnt->host)->mb[i].status) {
1584                                         printk(KERN_ERR "OGMB still full - restarting\n");
1585                                         aha1542_out(SCpnt->host->io_port, &ahacmd, 1);
1586                                 };
1587                         } else
1588                                 printk(KERN_ERR "Other pending command %s\n",
1589                                        SCpnt->request->rq_disk ?
1590                                        SCpnt->request->rq_disk->disk_name : "?"
1591                                        );
1592                 }
1593 #endif
1594
1595         DEB(printk("aha1542_abort\n"));
1596 #if 0
1597         spin_lock_irqsave(&aha1542_lock, flags);
1598         for (mbo = 0; mbo < AHA1542_MAILBOXES; mbo++) {
1599                 if (SCpnt == HOSTDATA(SCpnt->host)->SCint[mbo]) {
1600                         mb[mbo].status = 2;     /* Abort command */
1601                         aha1542_out(SCpnt->host->io_port, &ahacmd, 1);  /* start scsi command */
1602                         spin_unlock_irqrestore(&aha1542_lock, flags);
1603                         break;
1604                 }
1605         }
1606         if (AHA1542_MAILBOXES == mbo)
1607                 spin_unlock_irqrestore(&aha1542_lock, flags);
1608 #endif
1609         return SCSI_ABORT_SNOOZE;
1610 }
1611
1612 /* We do not implement a reset function here, but the upper level code
1613    assumes that it will get some kind of response for the command in
1614    SCpnt.  We must oblige, or the command will hang the scsi system.
1615    For a first go, we assume that the 1542 notifies us with all of the
1616    pending commands (it does implement soft reset, after all). */
1617
1618 static int aha1542_old_reset(Scsi_Cmnd * SCpnt, unsigned int reset_flags)
1619 {
1620         unchar ahacmd = CMD_START_SCSI;
1621         int i;
1622
1623         /*
1624          * See if a bus reset was suggested.
1625          */
1626         if (reset_flags & SCSI_RESET_SUGGEST_BUS_RESET) {
1627                 /* 
1628                  * This does a scsi reset for all devices on the bus.
1629                  * In principle, we could also reset the 1542 - should
1630                  * we do this?  Try this first, and we can add that later
1631                  * if it turns out to be useful.
1632                  */
1633                 outb(HRST | SCRST, CONTROL(SCpnt->host->io_port));
1634
1635                 /*
1636                  * Wait for the thing to settle down a bit.  Unfortunately
1637                  * this is going to basically lock up the machine while we
1638                  * wait for this to complete.  To be 100% correct, we need to
1639                  * check for timeout, and if we are doing something like this
1640                  * we are pretty desperate anyways.
1641                  */
1642                 WAIT(STATUS(SCpnt->host->io_port),
1643                 STATMASK, INIT | IDLE, STST | DIAGF | INVDCMD | DF | CDF);
1644
1645                 /*
1646                  * We need to do this too before the 1542 can interact with
1647                  * us again.
1648                  */
1649                 setup_mailboxes(SCpnt->host->io_port, SCpnt->host);
1650
1651                 /*
1652                  * Now try to pick up the pieces.  Restart all commands
1653                  * that are currently active on the bus, and reset all of
1654                  * the datastructures.  We have some time to kill while
1655                  * things settle down, so print a nice message.
1656                  */
1657                 printk(KERN_WARNING "Sent BUS RESET to scsi host %d\n", SCpnt->host->host_no);
1658
1659                 for (i = 0; i < AHA1542_MAILBOXES; i++)
1660                         if (HOSTDATA(SCpnt->host)->SCint[i] != NULL) {
1661                                 Scsi_Cmnd *SCtmp;
1662                                 SCtmp = HOSTDATA(SCpnt->host)->SCint[i];
1663                                 SCtmp->result = DID_RESET << 16;
1664                                 kfree(SCtmp->host_scribble);
1665                                 SCtmp->host_scribble = NULL;
1666                                 printk(KERN_WARNING "Sending DID_RESET for target %d\n", SCpnt->target);
1667                                 SCtmp->scsi_done(SCpnt);
1668
1669                                 HOSTDATA(SCpnt->host)->SCint[i] = NULL;
1670                                 HOSTDATA(SCpnt->host)->mb[i].status = 0;
1671                         }
1672                 /*
1673                  * Now tell the mid-level code what we did here.  Since
1674                  * we have restarted all of the outstanding commands,
1675                  * then report SUCCESS.
1676                  */
1677                 return (SCSI_RESET_SUCCESS | SCSI_RESET_BUS_RESET);
1678 fail:
1679                 printk(KERN_CRIT "aha1542.c: Unable to perform hard reset.\n");
1680                 printk(KERN_CRIT "Power cycle machine to reset\n");
1681                 return (SCSI_RESET_ERROR | SCSI_RESET_BUS_RESET);
1682
1683
1684         } else {
1685                 /* This does a selective reset of just the one device */
1686                 /* First locate the ccb for this command */
1687                 for (i = 0; i < AHA1542_MAILBOXES; i++)
1688                         if (HOSTDATA(SCpnt->host)->SCint[i] == SCpnt) {
1689                                 HOSTDATA(SCpnt->host)->ccb[i].op = 0x81;        /* BUS DEVICE RESET */
1690                                 /* Now tell the 1542 to flush all pending commands for this target */
1691                                 aha1542_out(SCpnt->host->io_port, &ahacmd, 1);
1692
1693                                 /* Here is the tricky part.  What to do next.  Do we get an interrupt
1694                                    for the commands that we aborted with the specified target, or
1695                                    do we generate this on our own?  Try it without first and see
1696                                    what happens */
1697                                 printk(KERN_WARNING "Sent BUS DEVICE RESET to target %d\n", SCpnt->target);
1698
1699                                 /* If the first does not work, then try the second.  I think the
1700                                    first option is more likely to be correct. Free the command
1701                                    block for all commands running on this target... */
1702                                 for (i = 0; i < AHA1542_MAILBOXES; i++)
1703                                         if (HOSTDATA(SCpnt->host)->SCint[i] &&
1704                                             HOSTDATA(SCpnt->host)->SCint[i]->target == SCpnt->target) {
1705                                                 Scsi_Cmnd *SCtmp;
1706                                                 SCtmp = HOSTDATA(SCpnt->host)->SCint[i];
1707                                                 SCtmp->result = DID_RESET << 16;
1708                                                 kfree(SCtmp->host_scribble);
1709                                                 SCtmp->host_scribble = NULL;
1710                                                 printk(KERN_WARNING "Sending DID_RESET for target %d\n", SCpnt->target);
1711                                                 SCtmp->scsi_done(SCpnt);
1712
1713                                                 HOSTDATA(SCpnt->host)->SCint[i] = NULL;
1714                                                 HOSTDATA(SCpnt->host)->mb[i].status = 0;
1715                                         }
1716                                 return SCSI_RESET_SUCCESS;
1717                         }
1718         }
1719         /* No active command at this time, so this means that each time we got
1720            some kind of response the last time through.  Tell the mid-level code
1721            to request sense information in order to decide what to do next. */
1722         return SCSI_RESET_PUNT;
1723 }
1724 #endif    /* end of big comment block around old_abort + old_reset */
1725
1726 static int aha1542_biosparam(struct scsi_device *sdev,
1727                 struct block_device *bdev, sector_t capacity, int *ip)
1728 {
1729         int translation_algorithm;
1730         int size = capacity;
1731
1732         translation_algorithm = HOSTDATA(sdev->host)->bios_translation;
1733
1734         if ((size >> 11) > 1024 && translation_algorithm == BIOS_TRANSLATION_25563) {
1735                 /* Please verify that this is the same as what DOS returns */
1736                 ip[0] = 255;
1737                 ip[1] = 63;
1738                 ip[2] = size / 255 / 63;
1739         } else {
1740                 ip[0] = 64;
1741                 ip[1] = 32;
1742                 ip[2] = size >> 11;
1743         }
1744
1745         return 0;
1746 }
1747 MODULE_LICENSE("GPL");
1748
1749
1750 static struct scsi_host_template driver_template = {
1751         .proc_name              = "aha1542",
1752         .name                   = "Adaptec 1542",
1753         .detect                 = aha1542_detect,
1754         .release                = aha1542_release,
1755         .queuecommand           = aha1542_queuecommand,
1756         .eh_device_reset_handler= aha1542_dev_reset,
1757         .eh_bus_reset_handler   = aha1542_bus_reset,
1758         .eh_host_reset_handler  = aha1542_host_reset,
1759         .bios_param             = aha1542_biosparam,
1760         .can_queue              = AHA1542_MAILBOXES, 
1761         .this_id                = 7,
1762         .sg_tablesize           = AHA1542_SCATTER,
1763         .cmd_per_lun            = AHA1542_CMDLUN,
1764         .unchecked_isa_dma      = 1, 
1765         .use_clustering         = ENABLE_CLUSTERING,
1766 };
1767 #include "scsi_module.c"