Merge branch 'master' into upstream
[pandora-kernel.git] / drivers / scsi / aic7xxx_old.c
1 /*+M*************************************************************************
2  * Adaptec AIC7xxx device driver for Linux.
3  *
4  * Copyright (c) 1994 John Aycock
5  *   The University of Calgary Department of Computer Science.
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2, or (at your option)
10  * any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; see the file COPYING.  If not, write to
19  * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
20  *
21  * Sources include the Adaptec 1740 driver (aha1740.c), the Ultrastor 24F
22  * driver (ultrastor.c), various Linux kernel source, the Adaptec EISA
23  * config file (!adp7771.cfg), the Adaptec AHA-2740A Series User's Guide,
24  * the Linux Kernel Hacker's Guide, Writing a SCSI Device Driver for Linux,
25  * the Adaptec 1542 driver (aha1542.c), the Adaptec EISA overlay file
26  * (adp7770.ovl), the Adaptec AHA-2740 Series Technical Reference Manual,
27  * the Adaptec AIC-7770 Data Book, the ANSI SCSI specification, the
28  * ANSI SCSI-2 specification (draft 10c), ...
29  *
30  * --------------------------------------------------------------------------
31  *
32  *  Modifications by Daniel M. Eischen (deischen@iworks.InterWorks.org):
33  *
34  *  Substantially modified to include support for wide and twin bus
35  *  adapters, DMAing of SCBs, tagged queueing, IRQ sharing, bug fixes,
36  *  SCB paging, and other rework of the code.
37  *
38  *  Parts of this driver were also based on the FreeBSD driver by
39  *  Justin T. Gibbs.  His copyright follows:
40  *
41  * --------------------------------------------------------------------------  
42  * Copyright (c) 1994-1997 Justin Gibbs.
43  * All rights reserved.
44  *
45  * Redistribution and use in source and binary forms, with or without
46  * modification, are permitted provided that the following conditions
47  * are met:
48  * 1. Redistributions of source code must retain the above copyright
49  *    notice, this list of conditions, and the following disclaimer,
50  *    without modification, immediately at the beginning of the file.
51  * 2. Redistributions in binary form must reproduce the above copyright
52  *    notice, this list of conditions and the following disclaimer in the
53  *    documentation and/or other materials provided with the distribution.
54  * 3. The name of the author may not be used to endorse or promote products
55  *    derived from this software without specific prior written permission.
56  *
57  * Where this Software is combined with software released under the terms of 
58  * the GNU General Public License ("GPL") and the terms of the GPL would require the 
59  * combined work to also be released under the terms of the GPL, the terms
60  * and conditions of this License will apply in addition to those of the
61  * GPL with the exception of any terms or conditions of this License that
62  * conflict with, or are expressly prohibited by, the GPL.
63  *
64  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
65  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
66  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
67  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
68  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
69  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
70  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
71  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
72  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
73  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
74  * SUCH DAMAGE.
75  *
76  *      $Id: aic7xxx.c,v 1.119 1997/06/27 19:39:18 gibbs Exp $
77  *---------------------------------------------------------------------------
78  *
79  *  Thanks also go to (in alphabetical order) the following:
80  *
81  *    Rory Bolt     - Sequencer bug fixes
82  *    Jay Estabrook - Initial DEC Alpha support
83  *    Doug Ledford  - Much needed abort/reset bug fixes
84  *    Kai Makisara  - DMAing of SCBs
85  *
86  *  A Boot time option was also added for not resetting the scsi bus.
87  *
88  *    Form:  aic7xxx=extended
89  *           aic7xxx=no_reset
90  *           aic7xxx=ultra
91  *           aic7xxx=irq_trigger:[0,1]  # 0 edge, 1 level
92  *           aic7xxx=verbose
93  *
94  *  Daniel M. Eischen, deischen@iworks.InterWorks.org, 1/23/97
95  *
96  *  $Id: aic7xxx.c,v 4.1 1997/06/12 08:23:42 deang Exp $
97  *-M*************************************************************************/
98
99 /*+M**************************************************************************
100  *
101  * Further driver modifications made by Doug Ledford <dledford@redhat.com>
102  *
103  * Copyright (c) 1997-1999 Doug Ledford
104  *
105  * These changes are released under the same licensing terms as the FreeBSD
106  * driver written by Justin Gibbs.  Please see his Copyright notice above
107  * for the exact terms and conditions covering my changes as well as the
108  * warranty statement.
109  *
110  * Modifications made to the aic7xxx.c,v 4.1 driver from Dan Eischen include
111  * but are not limited to:
112  *
113  *  1: Import of the latest FreeBSD sequencer code for this driver
114  *  2: Modification of kernel code to accommodate different sequencer semantics
115  *  3: Extensive changes throughout kernel portion of driver to improve
116  *     abort/reset processing and error hanndling
117  *  4: Other work contributed by various people on the Internet
118  *  5: Changes to printk information and verbosity selection code
119  *  6: General reliability related changes, especially in IRQ management
120  *  7: Modifications to the default probe/attach order for supported cards
121  *  8: SMP friendliness has been improved
122  *
123  * Overall, this driver represents a significant departure from the official
124  * aic7xxx driver released by Dan Eischen in two ways.  First, in the code
125  * itself.  A diff between the two version of the driver is now a several
126  * thousand line diff.  Second, in approach to solving the same problem.  The
127  * problem is importing the FreeBSD aic7xxx driver code to linux can be a
128  * difficult and time consuming process, that also can be error prone.  Dan
129  * Eischen's official driver uses the approach that the linux and FreeBSD
130  * drivers should be as identical as possible.  To that end, his next version
131  * of this driver will be using a mid-layer code library that he is developing
132  * to moderate communications between the linux mid-level SCSI code and the
133  * low level FreeBSD driver.  He intends to be able to essentially drop the
134  * FreeBSD driver into the linux kernel with only a few minor tweaks to some
135  * include files and the like and get things working, making for fast easy
136  * imports of the FreeBSD code into linux.
137  *
138  * I disagree with Dan's approach.  Not that I don't think his way of doing
139  * things would be nice, easy to maintain, and create a more uniform driver
140  * between FreeBSD and Linux.  I have no objection to those issues.  My
141  * disagreement is on the needed functionality.  There simply are certain
142  * things that are done differently in FreeBSD than linux that will cause
143  * problems for this driver regardless of any middle ware Dan implements.
144  * The biggest example of this at the moment is interrupt semantics.  Linux
145  * doesn't provide the same protection techniques as FreeBSD does, nor can
146  * they be easily implemented in any middle ware code since they would truly
147  * belong in the kernel proper and would effect all drivers.  For the time
148  * being, I see issues such as these as major stumbling blocks to the 
149  * reliability of code based upon such middle ware.  Therefore, I choose to
150  * use a different approach to importing the FreeBSD code that doesn't
151  * involve any middle ware type code.  My approach is to import the sequencer
152  * code from FreeBSD wholesale.  Then, to only make changes in the kernel
153  * portion of the driver as they are needed for the new sequencer semantics.
154  * In this way, the portion of the driver that speaks to the rest of the
155  * linux kernel is fairly static and can be changed/modified to solve
156  * any problems one might encounter without concern for the FreeBSD driver.
157  *
158  * Note: If time and experience should prove me wrong that the middle ware
159  * code Dan writes is reliable in its operation, then I'll retract my above
160  * statements.  But, for those that don't know, I'm from Missouri (in the US)
161  * and our state motto is "The Show-Me State".  Well, before I will put
162  * faith into it, you'll have to show me that it works :)
163  *
164  *_M*************************************************************************/
165
166 /*
167  * The next three defines are user configurable.  These should be the only
168  * defines a user might need to get in here and change.  There are other
169  * defines buried deeper in the code, but those really shouldn't need touched
170  * under normal conditions.
171  */
172
173 /*
174  * AIC7XXX_STRICT_PCI_SETUP
175  *   Should we assume the PCI config options on our controllers are set with
176  *   sane and proper values, or should we be anal about our PCI config
177  *   registers and force them to what we want?  The main advantage to
178  *   defining this option is on non-Intel hardware where the BIOS may not
179  *   have been run to set things up, or if you have one of the BIOSless
180  *   Adaptec controllers, such as a 2910, that don't get set up by the
181  *   BIOS.  However, keep in mind that we really do set the most important
182  *   items in the driver regardless of this setting, this only controls some
183  *   of the more esoteric PCI options on these cards.  In that sense, I
184  *   would default to leaving this off.  However, if people wish to try
185  *   things both ways, that would also help me to know if there are some
186  *   machines where it works one way but not another.
187  *
188  *   -- July 7, 17:09
189  *     OK...I need this on my machine for testing, so the default is to
190  *     leave it defined.
191  *
192  *   -- July 7, 18:49
193  *     I needed it for testing, but it didn't make any difference, so back
194  *     off she goes.
195  *
196  *   -- July 16, 23:04
197  *     I turned it back on to try and compensate for the 2.1.x PCI code
198  *     which no longer relies solely on the BIOS and now tries to set
199  *     things itself.
200  */
201
202 #define AIC7XXX_STRICT_PCI_SETUP
203
204 /*
205  * AIC7XXX_VERBOSE_DEBUGGING
206  *   This option enables a lot of extra printk();s in the code, surrounded
207  *   by if (aic7xxx_verbose ...) statements.  Executing all of those if
208  *   statements and the extra checks can get to where it actually does have
209  *   an impact on CPU usage and such, as well as code size.  Disabling this
210  *   define will keep some of those from becoming part of the code.
211  *
212  *   NOTE:  Currently, this option has no real effect, I will be adding the
213  *   various #ifdef's in the code later when I've decided a section is
214  *   complete and no longer needs debugging.  OK...a lot of things are now
215  *   surrounded by this define, so turning this off does have an impact.
216  */
217  
218 /*
219  * #define AIC7XXX_VERBOSE_DEBUGGING
220  */
221  
222 #include <linux/module.h>
223 #include <stdarg.h>
224 #include <asm/io.h>
225 #include <asm/irq.h>
226 #include <asm/byteorder.h>
227 #include <linux/string.h>
228 #include <linux/errno.h>
229 #include <linux/kernel.h>
230 #include <linux/ioport.h>
231 #include <linux/delay.h>
232 #include <linux/pci.h>
233 #include <linux/proc_fs.h>
234 #include <linux/blkdev.h>
235 #include <linux/init.h>
236 #include <linux/spinlock.h>
237 #include <linux/smp.h>
238 #include <linux/interrupt.h>
239 #include "scsi.h"
240 #include <scsi/scsi_host.h>
241 #include "aic7xxx_old/aic7xxx.h"
242
243 #include "aic7xxx_old/sequencer.h"
244 #include "aic7xxx_old/scsi_message.h"
245 #include "aic7xxx_old/aic7xxx_reg.h"
246 #include <scsi/scsicam.h>
247
248 #include <linux/stat.h>
249 #include <linux/slab.h>        /* for kmalloc() */
250
251 #define AIC7XXX_C_VERSION  "5.2.6"
252
253 #define ALL_TARGETS -1
254 #define ALL_CHANNELS -1
255 #define ALL_LUNS -1
256 #define MAX_TARGETS  16
257 #define MAX_LUNS     8
258 #ifndef TRUE
259 #  define TRUE 1
260 #endif
261 #ifndef FALSE
262 #  define FALSE 0
263 #endif
264
265 #if defined(__powerpc__) || defined(__i386__) || defined(__x86_64__)
266 #  define MMAPIO
267 #endif
268
269 /*
270  * You can try raising me for better performance or lowering me if you have
271  * flaky devices that go off the scsi bus when hit with too many tagged
272  * commands (like some IBM SCSI-3 LVD drives).
273  */
274 #define AIC7XXX_CMDS_PER_DEVICE 32
275
276 typedef struct
277 {
278   unsigned char tag_commands[16];   /* Allow for wide/twin adapters. */
279 } adapter_tag_info_t;
280
281 /*
282  * Make a define that will tell the driver not to the default tag depth
283  * everywhere.
284  */
285 #define DEFAULT_TAG_COMMANDS {0, 0, 0, 0, 0, 0, 0, 0,\
286                               0, 0, 0, 0, 0, 0, 0, 0}
287
288 /*
289  * Modify this as you see fit for your system.  By setting tag_commands
290  * to 0, the driver will use it's own algorithm for determining the
291  * number of commands to use (see above).  When 255, the driver will
292  * not enable tagged queueing for that particular device.  When positive
293  * (> 0) and (< 255) the values in the array are used for the queue_depth.
294  * Note that the maximum value for an entry is 254, but you're insane if
295  * you try to use that many commands on one device.
296  *
297  * In this example, the first line will disable tagged queueing for all
298  * the devices on the first probed aic7xxx adapter.
299  *
300  * The second line enables tagged queueing with 4 commands/LUN for IDs
301  * (1, 2-11, 13-15), disables tagged queueing for ID 12, and tells the
302  * driver to use its own algorithm for ID 1.
303  *
304  * The third line is the same as the first line.
305  *
306  * The fourth line disables tagged queueing for devices 0 and 3.  It
307  * enables tagged queueing for the other IDs, with 16 commands/LUN
308  * for IDs 1 and 4, 127 commands/LUN for ID 8, and 4 commands/LUN for
309  * IDs 2, 5-7, and 9-15.
310  */
311
312 /*
313  * NOTE: The below structure is for reference only, the actual structure
314  *       to modify in order to change things is found after this fake one.
315  *
316 adapter_tag_info_t aic7xxx_tag_info[] =
317 {
318   {DEFAULT_TAG_COMMANDS},
319   {{4, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 255, 4, 4, 4}},
320   {DEFAULT_TAG_COMMANDS},
321   {{255, 16, 4, 255, 16, 4, 4, 4, 127, 4, 4, 4, 4, 4, 4, 4}}
322 };
323 */
324
325 static adapter_tag_info_t aic7xxx_tag_info[] =
326 {
327   {DEFAULT_TAG_COMMANDS},
328   {DEFAULT_TAG_COMMANDS},
329   {DEFAULT_TAG_COMMANDS},
330   {DEFAULT_TAG_COMMANDS},
331   {DEFAULT_TAG_COMMANDS},
332   {DEFAULT_TAG_COMMANDS},
333   {DEFAULT_TAG_COMMANDS},
334   {DEFAULT_TAG_COMMANDS},
335   {DEFAULT_TAG_COMMANDS},
336   {DEFAULT_TAG_COMMANDS},
337   {DEFAULT_TAG_COMMANDS},
338   {DEFAULT_TAG_COMMANDS},
339   {DEFAULT_TAG_COMMANDS},
340   {DEFAULT_TAG_COMMANDS},
341   {DEFAULT_TAG_COMMANDS},
342   {DEFAULT_TAG_COMMANDS}
343 };
344
345
346 /*
347  * Define an array of board names that can be indexed by aha_type.
348  * Don't forget to change this when changing the types!
349  */
350 static const char *board_names[] = {
351   "AIC-7xxx Unknown",                                   /* AIC_NONE */
352   "Adaptec AIC-7810 Hardware RAID Controller",          /* AIC_7810 */
353   "Adaptec AIC-7770 SCSI host adapter",                 /* AIC_7770 */
354   "Adaptec AHA-274X SCSI host adapter",                 /* AIC_7771 */
355   "Adaptec AHA-284X SCSI host adapter",                 /* AIC_284x */
356   "Adaptec AIC-7850 SCSI host adapter",                 /* AIC_7850 */
357   "Adaptec AIC-7855 SCSI host adapter",                 /* AIC_7855 */
358   "Adaptec AIC-7860 Ultra SCSI host adapter",           /* AIC_7860 */
359   "Adaptec AHA-2940A Ultra SCSI host adapter",          /* AIC_7861 */
360   "Adaptec AIC-7870 SCSI host adapter",                 /* AIC_7870 */
361   "Adaptec AHA-294X SCSI host adapter",                 /* AIC_7871 */
362   "Adaptec AHA-394X SCSI host adapter",                 /* AIC_7872 */
363   "Adaptec AHA-398X SCSI host adapter",                 /* AIC_7873 */
364   "Adaptec AHA-2944 SCSI host adapter",                 /* AIC_7874 */
365   "Adaptec AIC-7880 Ultra SCSI host adapter",           /* AIC_7880 */
366   "Adaptec AHA-294X Ultra SCSI host adapter",           /* AIC_7881 */
367   "Adaptec AHA-394X Ultra SCSI host adapter",           /* AIC_7882 */
368   "Adaptec AHA-398X Ultra SCSI host adapter",           /* AIC_7883 */
369   "Adaptec AHA-2944 Ultra SCSI host adapter",           /* AIC_7884 */
370   "Adaptec AHA-2940UW Pro Ultra SCSI host adapter",     /* AIC_7887 */
371   "Adaptec AIC-7895 Ultra SCSI host adapter",           /* AIC_7895 */
372   "Adaptec AIC-7890/1 Ultra2 SCSI host adapter",        /* AIC_7890 */
373   "Adaptec AHA-293X Ultra2 SCSI host adapter",          /* AIC_7890 */
374   "Adaptec AHA-294X Ultra2 SCSI host adapter",          /* AIC_7890 */
375   "Adaptec AIC-7896/7 Ultra2 SCSI host adapter",        /* AIC_7896 */
376   "Adaptec AHA-394X Ultra2 SCSI host adapter",          /* AIC_7897 */
377   "Adaptec AHA-395X Ultra2 SCSI host adapter",          /* AIC_7897 */
378   "Adaptec PCMCIA SCSI controller",                     /* card bus stuff */
379   "Adaptec AIC-7892 Ultra 160/m SCSI host adapter",     /* AIC_7892 */
380   "Adaptec AIC-7899 Ultra 160/m SCSI host adapter",     /* AIC_7899 */
381 };
382
383 /*
384  * There should be a specific return value for this in scsi.h, but
385  * it seems that most drivers ignore it.
386  */
387 #define DID_UNDERFLOW   DID_ERROR
388
389 /*
390  *  What we want to do is have the higher level scsi driver requeue
391  *  the command to us. There is no specific driver status for this
392  *  condition, but the higher level scsi driver will requeue the
393  *  command on a DID_BUS_BUSY error.
394  *
395  *  Upon further inspection and testing, it seems that DID_BUS_BUSY
396  *  will *always* retry the command.  We can get into an infinite loop
397  *  if this happens when we really want some sort of counter that
398  *  will automatically abort/reset the command after so many retries.
399  *  Using DID_ERROR will do just that.  (Made by a suggestion by
400  *  Doug Ledford 8/1/96)
401  */
402 #define DID_RETRY_COMMAND DID_ERROR
403
404 #define HSCSIID        0x07
405 #define SCSI_RESET     0x040
406
407 /*
408  * EISA/VL-bus stuff
409  */
410 #define MINSLOT                1
411 #define MAXSLOT                15
412 #define SLOTBASE(x)        ((x) << 12)
413 #define BASE_TO_SLOT(x) ((x) >> 12)
414
415 /*
416  * Standard EISA Host ID regs  (Offset from slot base)
417  */
418 #define AHC_HID0              0x80   /* 0,1: msb of ID2, 2-7: ID1      */
419 #define AHC_HID1              0x81   /* 0-4: ID3, 5-7: LSB ID2         */
420 #define AHC_HID2              0x82   /* product                        */
421 #define AHC_HID3              0x83   /* firmware revision              */
422
423 /*
424  * AIC-7770 I/O range to reserve for a card
425  */
426 #define MINREG                0xC00
427 #define MAXREG                0xCFF
428
429 #define INTDEF                0x5C      /* Interrupt Definition Register */
430
431 /*
432  * AIC-78X0 PCI registers
433  */
434 #define        CLASS_PROGIF_REVID        0x08
435 #define                DEVREVID        0x000000FFul
436 #define                PROGINFC        0x0000FF00ul
437 #define                SUBCLASS        0x00FF0000ul
438 #define                BASECLASS        0xFF000000ul
439
440 #define        CSIZE_LATTIME                0x0C
441 #define                CACHESIZE        0x0000003Ful        /* only 5 bits */
442 #define                LATTIME                0x0000FF00ul
443
444 #define        DEVCONFIG                0x40
445 #define                SCBSIZE32        0x00010000ul        /* aic789X only */
446 #define                MPORTMODE        0x00000400ul        /* aic7870 only */
447 #define                RAMPSM           0x00000200ul        /* aic7870 only */
448 #define                RAMPSM_ULTRA2    0x00000004
449 #define                VOLSENSE         0x00000100ul
450 #define                SCBRAMSEL        0x00000080ul
451 #define                SCBRAMSEL_ULTRA2 0x00000008
452 #define                MRDCEN           0x00000040ul
453 #define                EXTSCBTIME       0x00000020ul        /* aic7870 only */
454 #define                EXTSCBPEN        0x00000010ul        /* aic7870 only */
455 #define                BERREN           0x00000008ul
456 #define                DACEN            0x00000004ul
457 #define                STPWLEVEL        0x00000002ul
458 #define                DIFACTNEGEN      0x00000001ul        /* aic7870 only */
459
460 #define        SCAMCTL                  0x1a                /* Ultra2 only  */
461 #define        CCSCBBADDR               0xf0                /* aic7895/6/7  */
462
463 /*
464  * Define the different types of SEEPROMs on aic7xxx adapters
465  * and make it also represent the address size used in accessing
466  * its registers.  The 93C46 chips have 1024 bits organized into
467  * 64 16-bit words, while the 93C56 chips have 2048 bits organized
468  * into 128 16-bit words.  The C46 chips use 6 bits to address
469  * each word, while the C56 and C66 (4096 bits) use 8 bits to
470  * address each word.
471  */
472 typedef enum {C46 = 6, C56_66 = 8} seeprom_chip_type;
473
474 /*
475  *
476  * Define the format of the SEEPROM registers (16 bits).
477  *
478  */
479 struct seeprom_config {
480
481 /*
482  * SCSI ID Configuration Flags
483  */
484 #define CFXFER                0x0007      /* synchronous transfer rate */
485 #define CFSYNCH               0x0008      /* enable synchronous transfer */
486 #define CFDISC                0x0010      /* enable disconnection */
487 #define CFWIDEB               0x0020      /* wide bus device (wide card) */
488 #define CFSYNCHISULTRA        0x0040      /* CFSYNC is an ultra offset */
489 #define CFNEWULTRAFORMAT      0x0080      /* Use the Ultra2 SEEPROM format */
490 #define CFSTART               0x0100      /* send start unit SCSI command */
491 #define CFINCBIOS             0x0200      /* include in BIOS scan */
492 #define CFRNFOUND             0x0400      /* report even if not found */
493 #define CFMULTILUN            0x0800      /* probe mult luns in BIOS scan */
494 #define CFWBCACHEYES          0x4000      /* Enable W-Behind Cache on drive */
495 #define CFWBCACHENC           0xc000      /* Don't change W-Behind Cache */
496 /* UNUSED                0x3000 */
497   unsigned short device_flags[16];        /* words 0-15 */
498
499 /*
500  * BIOS Control Bits
501  */
502 #define CFSUPREM        0x0001  /* support all removable drives */
503 #define CFSUPREMB       0x0002  /* support removable drives for boot only */
504 #define CFBIOSEN        0x0004  /* BIOS enabled */
505 /* UNUSED                0x0008 */
506 #define CFSM2DRV        0x0010  /* support more than two drives */
507 #define CF284XEXTEND    0x0020  /* extended translation (284x cards) */
508 /* UNUSED                0x0040 */
509 #define CFEXTEND        0x0080  /* extended translation enabled */
510 /* UNUSED                0xFF00 */
511   unsigned short bios_control;  /* word 16 */
512
513 /*
514  * Host Adapter Control Bits
515  */
516 #define CFAUTOTERM      0x0001  /* Perform Auto termination */
517 #define CFULTRAEN       0x0002  /* Ultra SCSI speed enable (Ultra cards) */
518 #define CF284XSELTO     0x0003  /* Selection timeout (284x cards) */
519 #define CF284XFIFO      0x000C  /* FIFO Threshold (284x cards) */
520 #define CFSTERM         0x0004  /* SCSI low byte termination */
521 #define CFWSTERM        0x0008  /* SCSI high byte termination (wide card) */
522 #define CFSPARITY       0x0010  /* SCSI parity */
523 #define CF284XSTERM     0x0020  /* SCSI low byte termination (284x cards) */
524 #define CFRESETB        0x0040  /* reset SCSI bus at boot */
525 #define CFBPRIMARY      0x0100  /* Channel B primary on 7895 chipsets */
526 #define CFSEAUTOTERM    0x0400  /* aic7890 Perform SE Auto Term */
527 #define CFLVDSTERM      0x0800  /* aic7890 LVD Termination */
528 /* UNUSED                0xF280 */
529   unsigned short adapter_control;        /* word 17 */
530
531 /*
532  * Bus Release, Host Adapter ID
533  */
534 #define CFSCSIID        0x000F                /* host adapter SCSI ID */
535 /* UNUSED                0x00F0 */
536 #define CFBRTIME        0xFF00                /* bus release time */
537   unsigned short brtime_id;                /* word 18 */
538
539 /*
540  * Maximum targets
541  */
542 #define CFMAXTARG        0x00FF        /* maximum targets */
543 /* UNUSED                0xFF00 */
544   unsigned short max_targets;                /* word 19 */
545
546   unsigned short res_1[11];                /* words 20-30 */
547   unsigned short checksum;                /* word 31 */
548 };
549
550 #define SELBUS_MASK                0x0a
551 #define         SELNARROW        0x00
552 #define         SELBUSB                0x08
553 #define SINGLE_BUS                0x00
554
555 #define SCB_TARGET(scb)         \
556        (((scb)->hscb->target_channel_lun & TID) >> 4)
557 #define SCB_LUN(scb)            \
558        ((scb)->hscb->target_channel_lun & LID)
559 #define SCB_IS_SCSIBUS_B(scb)   \
560        (((scb)->hscb->target_channel_lun & SELBUSB) != 0)
561
562 /*
563  * If an error occurs during a data transfer phase, run the command
564  * to completion - it's easier that way - making a note of the error
565  * condition in this location. This then will modify a DID_OK status
566  * into an appropriate error for the higher-level SCSI code.
567  */
568 #define aic7xxx_error(cmd)        ((cmd)->SCp.Status)
569
570 /*
571  * Keep track of the targets returned status.
572  */
573 #define aic7xxx_status(cmd)        ((cmd)->SCp.sent_command)
574
575 /*
576  * The position of the SCSI commands scb within the scb array.
577  */
578 #define aic7xxx_position(cmd)        ((cmd)->SCp.have_data_in)
579
580 /*
581  * The stored DMA mapping for single-buffer data transfers.
582  */
583 #define aic7xxx_mapping(cmd)         ((cmd)->SCp.phase)
584
585 /*
586  * Get out private data area from a scsi cmd pointer
587  */
588 #define AIC_DEV(cmd)    ((struct aic_dev_data *)(cmd)->device->hostdata)
589
590 /*
591  * So we can keep track of our host structs
592  */
593 static struct aic7xxx_host *first_aic7xxx = NULL;
594
595 /*
596  * As of Linux 2.1, the mid-level SCSI code uses virtual addresses
597  * in the scatter-gather lists.  We need to convert the virtual
598  * addresses to physical addresses.
599  */
600 struct hw_scatterlist {
601   unsigned int address;
602   unsigned int length;
603 };
604
605 /*
606  * Maximum number of SG segments these cards can support.
607  */
608 #define        AIC7XXX_MAX_SG 128
609
610 /*
611  * The maximum number of SCBs we could have for ANY type
612  * of card. DON'T FORGET TO CHANGE THE SCB MASK IN THE
613  * SEQUENCER CODE IF THIS IS MODIFIED!
614  */
615 #define AIC7XXX_MAXSCB        255
616
617
618 struct aic7xxx_hwscb {
619 /* ------------    Begin hardware supported fields    ---------------- */
620 /* 0*/  unsigned char control;
621 /* 1*/  unsigned char target_channel_lun;       /* 4/1/3 bits */
622 /* 2*/  unsigned char target_status;
623 /* 3*/  unsigned char SG_segment_count;
624 /* 4*/  unsigned int  SG_list_pointer;
625 /* 8*/  unsigned char residual_SG_segment_count;
626 /* 9*/  unsigned char residual_data_count[3];
627 /*12*/  unsigned int  data_pointer;
628 /*16*/  unsigned int  data_count;
629 /*20*/  unsigned int  SCSI_cmd_pointer;
630 /*24*/  unsigned char SCSI_cmd_length;
631 /*25*/  unsigned char tag;          /* Index into our kernel SCB array.
632                                      * Also used as the tag for tagged I/O
633                                      */
634 #define SCB_PIO_TRANSFER_SIZE  26   /* amount we need to upload/download
635                                      * via PIO to initialize a transaction.
636                                      */
637 /*26*/  unsigned char next;         /* Used to thread SCBs awaiting selection
638                                      * or disconnected down in the sequencer.
639                                      */
640 /*27*/  unsigned char prev;
641 /*28*/  unsigned int pad;           /*
642                                      * Unused by the kernel, but we require
643                                      * the padding so that the array of
644                                      * hardware SCBs is aligned on 32 byte
645                                      * boundaries so the sequencer can index
646                                      */
647 };
648
649 typedef enum {
650         SCB_FREE                = 0x0000,
651         SCB_DTR_SCB             = 0x0001,
652         SCB_WAITINGQ            = 0x0002,
653         SCB_ACTIVE              = 0x0004,
654         SCB_SENSE               = 0x0008,
655         SCB_ABORT               = 0x0010,
656         SCB_DEVICE_RESET        = 0x0020,
657         SCB_RESET               = 0x0040,
658         SCB_RECOVERY_SCB        = 0x0080,
659         SCB_MSGOUT_PPR          = 0x0100,
660         SCB_MSGOUT_SENT         = 0x0200,
661         SCB_MSGOUT_SDTR         = 0x0400,
662         SCB_MSGOUT_WDTR         = 0x0800,
663         SCB_MSGOUT_BITS         = SCB_MSGOUT_PPR |
664                                   SCB_MSGOUT_SENT | 
665                                   SCB_MSGOUT_SDTR |
666                                   SCB_MSGOUT_WDTR,
667         SCB_QUEUED_ABORT        = 0x1000,
668         SCB_QUEUED_FOR_DONE     = 0x2000,
669         SCB_WAS_BUSY            = 0x4000,
670         SCB_QUEUE_FULL          = 0x8000
671 } scb_flag_type;
672
673 typedef enum {
674         AHC_FNONE                 = 0x00000000,
675         AHC_PAGESCBS              = 0x00000001,
676         AHC_CHANNEL_B_PRIMARY     = 0x00000002,
677         AHC_USEDEFAULTS           = 0x00000004,
678         AHC_INDIRECT_PAGING       = 0x00000008,
679         AHC_CHNLB                 = 0x00000020,
680         AHC_CHNLC                 = 0x00000040,
681         AHC_EXTEND_TRANS_A        = 0x00000100,
682         AHC_EXTEND_TRANS_B        = 0x00000200,
683         AHC_TERM_ENB_A            = 0x00000400,
684         AHC_TERM_ENB_SE_LOW       = 0x00000400,
685         AHC_TERM_ENB_B            = 0x00000800,
686         AHC_TERM_ENB_SE_HIGH      = 0x00000800,
687         AHC_HANDLING_REQINITS     = 0x00001000,
688         AHC_TARGETMODE            = 0x00002000,
689         AHC_NEWEEPROM_FMT         = 0x00004000,
690  /*
691   *  Here ends the FreeBSD defined flags and here begins the linux defined
692   *  flags.  NOTE: I did not preserve the old flag name during this change
693   *  specifically to force me to evaluate what flags were being used properly
694   *  and what flags weren't.  This way, I could clean up the flag usage on
695   *  a use by use basis.  Doug Ledford
696   */
697         AHC_MOTHERBOARD           = 0x00020000,
698         AHC_NO_STPWEN             = 0x00040000,
699         AHC_RESET_DELAY           = 0x00080000,
700         AHC_A_SCANNED             = 0x00100000,
701         AHC_B_SCANNED             = 0x00200000,
702         AHC_MULTI_CHANNEL         = 0x00400000,
703         AHC_BIOS_ENABLED          = 0x00800000,
704         AHC_SEEPROM_FOUND         = 0x01000000,
705         AHC_TERM_ENB_LVD          = 0x02000000,
706         AHC_ABORT_PENDING         = 0x04000000,
707         AHC_RESET_PENDING         = 0x08000000,
708 #define AHC_IN_ISR_BIT              28
709         AHC_IN_ISR                = 0x10000000,
710         AHC_IN_ABORT              = 0x20000000,
711         AHC_IN_RESET              = 0x40000000,
712         AHC_EXTERNAL_SRAM         = 0x80000000
713 } ahc_flag_type;
714
715 typedef enum {
716   AHC_NONE             = 0x0000,
717   AHC_CHIPID_MASK      = 0x00ff,
718   AHC_AIC7770          = 0x0001,
719   AHC_AIC7850          = 0x0002,
720   AHC_AIC7860          = 0x0003,
721   AHC_AIC7870          = 0x0004,
722   AHC_AIC7880          = 0x0005,
723   AHC_AIC7890          = 0x0006,
724   AHC_AIC7895          = 0x0007,
725   AHC_AIC7896          = 0x0008,
726   AHC_AIC7892          = 0x0009,
727   AHC_AIC7899          = 0x000a,
728   AHC_VL               = 0x0100,
729   AHC_EISA             = 0x0200,
730   AHC_PCI              = 0x0400,
731 } ahc_chip;
732
733 typedef enum {
734   AHC_FENONE           = 0x0000,
735   AHC_ULTRA            = 0x0001,
736   AHC_ULTRA2           = 0x0002,
737   AHC_WIDE             = 0x0004,
738   AHC_TWIN             = 0x0008,
739   AHC_MORE_SRAM        = 0x0010,
740   AHC_CMD_CHAN         = 0x0020,
741   AHC_QUEUE_REGS       = 0x0040,
742   AHC_SG_PRELOAD       = 0x0080,
743   AHC_SPIOCAP          = 0x0100,
744   AHC_ULTRA3           = 0x0200,
745   AHC_NEW_AUTOTERM     = 0x0400,
746   AHC_AIC7770_FE       = AHC_FENONE,
747   AHC_AIC7850_FE       = AHC_SPIOCAP,
748   AHC_AIC7860_FE       = AHC_ULTRA|AHC_SPIOCAP,
749   AHC_AIC7870_FE       = AHC_FENONE,
750   AHC_AIC7880_FE       = AHC_ULTRA,
751   AHC_AIC7890_FE       = AHC_MORE_SRAM|AHC_CMD_CHAN|AHC_ULTRA2|
752                          AHC_QUEUE_REGS|AHC_SG_PRELOAD|AHC_NEW_AUTOTERM,
753   AHC_AIC7895_FE       = AHC_MORE_SRAM|AHC_CMD_CHAN|AHC_ULTRA,
754   AHC_AIC7896_FE       = AHC_AIC7890_FE,
755   AHC_AIC7892_FE       = AHC_AIC7890_FE|AHC_ULTRA3,
756   AHC_AIC7899_FE       = AHC_AIC7890_FE|AHC_ULTRA3,
757 } ahc_feature;
758
759 #define SCB_DMA_ADDR(scb, addr) ((unsigned long)(addr) + (scb)->scb_dma->dma_offset)
760
761 struct aic7xxx_scb_dma {
762         unsigned long          dma_offset;    /* Correction you have to add
763                                                * to virtual address to get
764                                                * dma handle in this region */
765         dma_addr_t             dma_address;   /* DMA handle of the start,
766                                                * for unmap */
767         unsigned int           dma_len;       /* DMA length */
768 };
769
770 typedef enum {
771   AHC_BUG_NONE            = 0x0000,
772   AHC_BUG_TMODE_WIDEODD   = 0x0001,
773   AHC_BUG_AUTOFLUSH       = 0x0002,
774   AHC_BUG_CACHETHEN       = 0x0004,
775   AHC_BUG_CACHETHEN_DIS   = 0x0008,
776   AHC_BUG_PCI_2_1_RETRY   = 0x0010,
777   AHC_BUG_PCI_MWI         = 0x0020,
778   AHC_BUG_SCBCHAN_UPLOAD  = 0x0040,
779 } ahc_bugs;
780
781 struct aic7xxx_scb {
782         struct aic7xxx_hwscb    *hscb;          /* corresponding hardware scb */
783         struct scsi_cmnd        *cmd;           /* scsi_cmnd for this scb */
784         struct aic7xxx_scb      *q_next;        /* next scb in queue */
785         volatile scb_flag_type  flags;          /* current state of scb */
786         struct hw_scatterlist   *sg_list;       /* SG list in adapter format */
787         unsigned char           tag_action;
788         unsigned char           sg_count;
789         unsigned char           *sense_cmd;     /*
790                                                  * Allocate 6 characters for
791                                                  * sense command.
792                                                  */
793         unsigned char           *cmnd;
794         unsigned int            sg_length;      /*
795                                                  * We init this during
796                                                  * buildscb so we don't have
797                                                  * to calculate anything during
798                                                  * underflow/overflow/stat code
799                                                  */
800         void                    *kmalloc_ptr;
801         struct aic7xxx_scb_dma  *scb_dma;
802 };
803
804 /*
805  * Define a linked list of SCBs.
806  */
807 typedef struct {
808   struct aic7xxx_scb *head;
809   struct aic7xxx_scb *tail;
810 } scb_queue_type;
811
812 static struct {
813   unsigned char errno;
814   const char *errmesg;
815 } hard_error[] = {
816   { ILLHADDR,  "Illegal Host Access" },
817   { ILLSADDR,  "Illegal Sequencer Address referenced" },
818   { ILLOPCODE, "Illegal Opcode in sequencer program" },
819   { SQPARERR,  "Sequencer Ram Parity Error" },
820   { DPARERR,   "Data-Path Ram Parity Error" },
821   { MPARERR,   "Scratch Ram/SCB Array Ram Parity Error" },
822   { PCIERRSTAT,"PCI Error detected" },
823   { CIOPARERR, "CIOBUS Parity Error" }
824 };
825
826 static unsigned char
827 generic_sense[] = { REQUEST_SENSE, 0, 0, 0, 255, 0 };
828
829 typedef struct {
830   scb_queue_type free_scbs;        /*
831                                     * SCBs assigned to free slot on
832                                     * card (no paging required)
833                                     */
834   struct aic7xxx_scb   *scb_array[AIC7XXX_MAXSCB];
835   struct aic7xxx_hwscb *hscbs;
836   unsigned char  numscbs;          /* current number of scbs */
837   unsigned char  maxhscbs;         /* hardware scbs */
838   unsigned char  maxscbs;          /* max scbs including pageable scbs */
839   dma_addr_t     hscbs_dma;        /* DMA handle to hscbs */
840   unsigned int   hscbs_dma_len;    /* length of the above DMA area */
841   void          *hscb_kmalloc_ptr;
842 } scb_data_type;
843
844 struct target_cmd {
845   unsigned char mesg_bytes[4];
846   unsigned char command[28];
847 };
848
849 #define AHC_TRANS_CUR    0x0001
850 #define AHC_TRANS_ACTIVE 0x0002
851 #define AHC_TRANS_GOAL   0x0004
852 #define AHC_TRANS_USER   0x0008
853 #define AHC_TRANS_QUITE  0x0010
854 typedef struct {
855   unsigned char width;
856   unsigned char period;
857   unsigned char offset;
858   unsigned char options;
859 } transinfo_type;
860
861 struct aic_dev_data {
862   volatile scb_queue_type  delayed_scbs;
863   volatile unsigned short  temp_q_depth;
864   unsigned short           max_q_depth;
865   volatile unsigned char   active_cmds;
866   /*
867    * Statistics Kept:
868    *
869    * Total Xfers (count for each command that has a data xfer),
870    * broken down by reads && writes.
871    *
872    * Further sorted into a few bins for keeping tabs on how many commands
873    * we get of various sizes.
874    *
875    */
876   long w_total;                          /* total writes */
877   long r_total;                          /* total reads */
878   long barrier_total;                    /* total num of REQ_BARRIER commands */
879   long ordered_total;                    /* How many REQ_BARRIER commands we
880                                             used ordered tags to satisfy */
881   long w_bins[6];                       /* binned write */
882   long r_bins[6];                       /* binned reads */
883   transinfo_type        cur;
884   transinfo_type        goal;
885 #define  BUS_DEVICE_RESET_PENDING       0x01
886 #define  DEVICE_RESET_DELAY             0x02
887 #define  DEVICE_PRINT_DTR               0x04
888 #define  DEVICE_WAS_BUSY                0x08
889 #define  DEVICE_DTR_SCANNED             0x10
890 #define  DEVICE_SCSI_3                  0x20
891   volatile unsigned char   flags;
892   unsigned needppr:1;
893   unsigned needppr_copy:1;
894   unsigned needsdtr:1;
895   unsigned needsdtr_copy:1;
896   unsigned needwdtr:1;
897   unsigned needwdtr_copy:1;
898   unsigned dtr_pending:1;
899   struct scsi_device *SDptr;
900   struct list_head list;
901 };
902
903 /*
904  * Define a structure used for each host adapter.  Note, in order to avoid
905  * problems with architectures I can't test on (because I don't have one,
906  * such as the Alpha based systems) which happen to give faults for
907  * non-aligned memory accesses, care was taken to align this structure
908  * in a way that gauranteed all accesses larger than 8 bits were aligned
909  * on the appropriate boundary.  It's also organized to try and be more
910  * cache line efficient.  Be careful when changing this lest you might hurt
911  * overall performance and bring down the wrath of the masses.
912  */
913 struct aic7xxx_host {
914   /*
915    *  This is the first 64 bytes in the host struct
916    */
917
918   /*
919    * We are grouping things here....first, items that get either read or
920    * written with nearly every interrupt
921    */
922         volatile long   flags;
923         ahc_feature     features;       /* chip features */
924         unsigned long   base;           /* card base address */
925         volatile unsigned char  __iomem *maddr; /* memory mapped address */
926         unsigned long   isr_count;      /* Interrupt count */
927         unsigned long   spurious_int;
928         scb_data_type   *scb_data;
929         struct aic7xxx_cmd_queue {
930                 struct scsi_cmnd *head;
931                 struct scsi_cmnd *tail;
932         } completeq;
933
934         /*
935         * Things read/written on nearly every entry into aic7xxx_queue()
936         */
937         volatile scb_queue_type waiting_scbs;
938         unsigned char   unpause;        /* unpause value for HCNTRL */
939         unsigned char   pause;          /* pause value for HCNTRL */
940         volatile unsigned char  qoutfifonext;
941         volatile unsigned char  activescbs;     /* active scbs */
942         volatile unsigned char  max_activescbs;
943         volatile unsigned char  qinfifonext;
944         volatile unsigned char  *untagged_scbs;
945         volatile unsigned char  *qoutfifo;
946         volatile unsigned char  *qinfifo;
947
948         unsigned char   dev_last_queue_full[MAX_TARGETS];
949         unsigned char   dev_last_queue_full_count[MAX_TARGETS];
950         unsigned short  ultraenb; /* Gets downloaded to card as a bitmap */
951         unsigned short  discenable; /* Gets downloaded to card as a bitmap */
952         transinfo_type  user[MAX_TARGETS];
953
954         unsigned char   msg_buf[13];    /* The message for the target */
955         unsigned char   msg_type;
956 #define MSG_TYPE_NONE              0x00
957 #define MSG_TYPE_INITIATOR_MSGOUT  0x01
958 #define MSG_TYPE_INITIATOR_MSGIN   0x02
959         unsigned char   msg_len;        /* Length of message */
960         unsigned char   msg_index;      /* Index into msg_buf array */
961
962
963         /*
964          * We put the less frequently used host structure items
965          * after the more frequently used items to try and ease
966          * the burden on the cache subsystem.
967          * These entries are not *commonly* accessed, whereas
968          * the preceding entries are accessed very often.
969          */
970
971         unsigned int    irq;            /* IRQ for this adapter */
972         int             instance;       /* aic7xxx instance number */
973         int             scsi_id;        /* host adapter SCSI ID */
974         int             scsi_id_b;      /* channel B for twin adapters */
975         unsigned int    bios_address;
976         int             board_name_index;
977         unsigned short  bios_control;           /* bios control - SEEPROM */
978         unsigned short  adapter_control;        /* adapter control - SEEPROM */
979         struct pci_dev  *pdev;
980         unsigned char   pci_bus;
981         unsigned char   pci_device_fn;
982         struct seeprom_config   sc;
983         unsigned short  sc_type;
984         unsigned short  sc_size;
985         struct aic7xxx_host     *next;  /* allow for multiple IRQs */
986         struct Scsi_Host        *host;  /* pointer to scsi host */
987         struct list_head         aic_devs; /* all aic_dev structs on host */
988         int             host_no;        /* SCSI host number */
989         unsigned long   mbase;          /* I/O memory address */
990         ahc_chip        chip;           /* chip type */
991         ahc_bugs        bugs;
992         dma_addr_t      fifo_dma;       /* DMA handle for fifo arrays */
993 };
994
995 /*
996  * Valid SCSIRATE values. (p. 3-17)
997  * Provides a mapping of transfer periods in ns/4 to the proper value to
998  * stick in the SCSIRATE reg to use that transfer rate.
999  */
1000 #define AHC_SYNCRATE_ULTRA3 0
1001 #define AHC_SYNCRATE_ULTRA2 1
1002 #define AHC_SYNCRATE_ULTRA  3
1003 #define AHC_SYNCRATE_FAST   6
1004 #define AHC_SYNCRATE_CRC 0x40
1005 #define AHC_SYNCRATE_SE  0x10
1006 static struct aic7xxx_syncrate {
1007   /* Rates in Ultra mode have bit 8 of sxfr set */
1008 #define                ULTRA_SXFR 0x100
1009   int sxfr_ultra2;
1010   int sxfr;
1011   unsigned char period;
1012   const char *rate[2];
1013 } aic7xxx_syncrates[] = {
1014   { 0x42,  0x000,   9,  {"80.0", "160.0"} },
1015   { 0x13,  0x000,  10,  {"40.0", "80.0"} },
1016   { 0x14,  0x000,  11,  {"33.0", "66.6"} },
1017   { 0x15,  0x100,  12,  {"20.0", "40.0"} },
1018   { 0x16,  0x110,  15,  {"16.0", "32.0"} },
1019   { 0x17,  0x120,  18,  {"13.4", "26.8"} },
1020   { 0x18,  0x000,  25,  {"10.0", "20.0"} },
1021   { 0x19,  0x010,  31,  {"8.0",  "16.0"} },
1022   { 0x1a,  0x020,  37,  {"6.67", "13.3"} },
1023   { 0x1b,  0x030,  43,  {"5.7",  "11.4"} },
1024   { 0x10,  0x040,  50,  {"5.0",  "10.0"} },
1025   { 0x00,  0x050,  56,  {"4.4",  "8.8" } },
1026   { 0x00,  0x060,  62,  {"4.0",  "8.0" } },
1027   { 0x00,  0x070,  68,  {"3.6",  "7.2" } },
1028   { 0x00,  0x000,  0,   {NULL, NULL}   },
1029 };
1030
1031 #define CTL_OF_SCB(scb) (((scb->hscb)->target_channel_lun >> 3) & 0x1),  \
1032                         (((scb->hscb)->target_channel_lun >> 4) & 0xf), \
1033                         ((scb->hscb)->target_channel_lun & 0x07)
1034
1035 #define CTL_OF_CMD(cmd) ((cmd->device->channel) & 0x01),  \
1036                         ((cmd->device->id) & 0x0f), \
1037                         ((cmd->device->lun) & 0x07)
1038
1039 #define TARGET_INDEX(cmd)  ((cmd)->device->id | ((cmd)->device->channel << 3))
1040
1041 /*
1042  * A nice little define to make doing our printks a little easier
1043  */
1044
1045 #define WARN_LEAD KERN_WARNING "(scsi%d:%d:%d:%d) "
1046 #define INFO_LEAD KERN_INFO "(scsi%d:%d:%d:%d) "
1047
1048 /*
1049  * XXX - these options apply unilaterally to _all_ 274x/284x/294x
1050  *       cards in the system.  This should be fixed.  Exceptions to this
1051  *       rule are noted in the comments.
1052  */
1053
1054 /*
1055  * Use this as the default queue depth when setting tagged queueing on.
1056  */
1057 static unsigned int aic7xxx_default_queue_depth = AIC7XXX_CMDS_PER_DEVICE;
1058
1059 /*
1060  * Skip the scsi bus reset.  Non 0 make us skip the reset at startup.  This
1061  * has no effect on any later resets that might occur due to things like
1062  * SCSI bus timeouts.
1063  */
1064 static unsigned int aic7xxx_no_reset = 0;
1065 /*
1066  * Certain PCI motherboards will scan PCI devices from highest to lowest,
1067  * others scan from lowest to highest, and they tend to do all kinds of
1068  * strange things when they come into contact with PCI bridge chips.  The
1069  * net result of all this is that the PCI card that is actually used to boot
1070  * the machine is very hard to detect.  Most motherboards go from lowest
1071  * PCI slot number to highest, and the first SCSI controller found is the
1072  * one you boot from.  The only exceptions to this are when a controller
1073  * has its BIOS disabled.  So, we by default sort all of our SCSI controllers
1074  * from lowest PCI slot number to highest PCI slot number.  We also force
1075  * all controllers with their BIOS disabled to the end of the list.  This
1076  * works on *almost* all computers.  Where it doesn't work, we have this
1077  * option.  Setting this option to non-0 will reverse the order of the sort
1078  * to highest first, then lowest, but will still leave cards with their BIOS
1079  * disabled at the very end.  That should fix everyone up unless there are
1080  * really strange cirumstances.
1081  */
1082 static int aic7xxx_reverse_scan = 0;
1083 /*
1084  * Should we force EXTENDED translation on a controller.
1085  *     0 == Use whatever is in the SEEPROM or default to off
1086  *     1 == Use whatever is in the SEEPROM or default to on
1087  */
1088 static unsigned int aic7xxx_extended = 0;
1089 /*
1090  * The IRQ trigger method used on EISA controllers. Does not effect PCI cards.
1091  *   -1 = Use detected settings.
1092  *    0 = Force Edge triggered mode.
1093  *    1 = Force Level triggered mode.
1094  */
1095 static int aic7xxx_irq_trigger = -1;
1096 /*
1097  * This variable is used to override the termination settings on a controller.
1098  * This should not be used under normal conditions.  However, in the case
1099  * that a controller does not have a readable SEEPROM (so that we can't
1100  * read the SEEPROM settings directly) and that a controller has a buggered
1101  * version of the cable detection logic, this can be used to force the 
1102  * correct termination.  It is preferable to use the manual termination
1103  * settings in the BIOS if possible, but some motherboard controllers store
1104  * those settings in a format we can't read.  In other cases, auto term
1105  * should also work, but the chipset was put together with no auto term
1106  * logic (common on motherboard controllers).  In those cases, we have
1107  * 32 bits here to work with.  That's good for 8 controllers/channels.  The
1108  * bits are organized as 4 bits per channel, with scsi0 getting the lowest
1109  * 4 bits in the int.  A 1 in a bit position indicates the termination setting
1110  * that corresponds to that bit should be enabled, a 0 is disabled.
1111  * It looks something like this:
1112  *
1113  *    0x0f =  1111-Single Ended Low Byte Termination on/off
1114  *            ||\-Single Ended High Byte Termination on/off
1115  *            |\-LVD Low Byte Termination on/off
1116  *            \-LVD High Byte Termination on/off
1117  *
1118  * For non-Ultra2 controllers, the upper 2 bits are not important.  So, to
1119  * enable both high byte and low byte termination on scsi0, I would need to
1120  * make sure that the override_term variable was set to 0x03 (bits 0011).
1121  * To make sure that all termination is enabled on an Ultra2 controller at
1122  * scsi2 and only high byte termination on scsi1 and high and low byte
1123  * termination on scsi0, I would set override_term=0xf23 (bits 1111 0010 0011)
1124  *
1125  * For the most part, users should never have to use this, that's why I
1126  * left it fairly cryptic instead of easy to understand.  If you need it,
1127  * most likely someone will be telling you what your's needs to be set to.
1128  */
1129 static int aic7xxx_override_term = -1;
1130 /*
1131  * Certain motherboard chipset controllers tend to screw
1132  * up the polarity of the term enable output pin.  Use this variable
1133  * to force the correct polarity for your system.  This is a bitfield variable
1134  * similar to the previous one, but this one has one bit per channel instead
1135  * of four.
1136  *    0 = Force the setting to active low.
1137  *    1 = Force setting to active high.
1138  * Most Adaptec cards are active high, several motherboards are active low.
1139  * To force a 2940 card at SCSI 0 to active high and a motherboard 7895
1140  * controller at scsi1 and scsi2 to active low, and a 2910 card at scsi3
1141  * to active high, you would need to set stpwlev=0x9 (bits 1001).
1142  *
1143  * People shouldn't need to use this, but if you are experiencing lots of
1144  * SCSI timeout problems, this may help.  There is one sure way to test what
1145  * this option needs to be.  Using a boot floppy to boot the system, configure
1146  * your system to enable all SCSI termination (in the Adaptec SCSI BIOS) and
1147  * if needed then also pass a value to override_term to make sure that the
1148  * driver is enabling SCSI termination, then set this variable to either 0
1149  * or 1.  When the driver boots, make sure there are *NO* SCSI cables
1150  * connected to your controller.  If it finds and inits the controller
1151  * without problem, then the setting you passed to stpwlev was correct.  If
1152  * the driver goes into a reset loop and hangs the system, then you need the
1153  * other setting for this variable.  If neither setting lets the machine
1154  * boot then you have definite termination problems that may not be fixable.
1155  */
1156 static int aic7xxx_stpwlev = -1;
1157 /*
1158  * Set this to non-0 in order to force the driver to panic the kernel
1159  * and print out debugging info on a SCSI abort or reset cycle.
1160  */
1161 static int aic7xxx_panic_on_abort = 0;
1162 /*
1163  * PCI bus parity checking of the Adaptec controllers.  This is somewhat
1164  * dubious at best.  To my knowledge, this option has never actually
1165  * solved a PCI parity problem, but on certain machines with broken PCI
1166  * chipset configurations, it can generate tons of false error messages.
1167  * It's included in the driver for completeness.
1168  *   0 = Shut off PCI parity check
1169  *  -1 = Normal polarity pci parity checking
1170  *   1 = reverse polarity pci parity checking
1171  *
1172  * NOTE: you can't actually pass -1 on the lilo prompt.  So, to set this
1173  * variable to -1 you would actually want to simply pass the variable
1174  * name without a number.  That will invert the 0 which will result in
1175  * -1.
1176  */
1177 static int aic7xxx_pci_parity = 0;
1178 /*
1179  * Set this to any non-0 value to cause us to dump the contents of all
1180  * the card's registers in a hex dump format tailored to each model of
1181  * controller.
1182  * 
1183  * NOTE: THE CONTROLLER IS LEFT IN AN UNUSEABLE STATE BY THIS OPTION.
1184  *       YOU CANNOT BOOT UP WITH THIS OPTION, IT IS FOR DEBUGGING PURPOSES
1185  *       ONLY
1186  */
1187 static int aic7xxx_dump_card = 0;
1188 /*
1189  * Set this to a non-0 value to make us dump out the 32 bit instruction
1190  * registers on the card after completing the sequencer download.  This
1191  * allows the actual sequencer download to be verified.  It is possible
1192  * to use this option and still boot up and run your system.  This is
1193  * only intended for debugging purposes.
1194  */
1195 static int aic7xxx_dump_sequencer = 0;
1196 /*
1197  * Certain newer motherboards have put new PCI based devices into the
1198  * IO spaces that used to typically be occupied by VLB or EISA cards.
1199  * This overlap can cause these newer motherboards to lock up when scanned
1200  * for older EISA and VLB devices.  Setting this option to non-0 will
1201  * cause the driver to skip scanning for any VLB or EISA controllers and
1202  * only support the PCI controllers.  NOTE: this means that if the kernel
1203  * os compiled with PCI support disabled, then setting this to non-0
1204  * would result in never finding any devices :)
1205  */
1206 static int aic7xxx_no_probe = 0;
1207 /*
1208  * On some machines, enabling the external SCB RAM isn't reliable yet.  I
1209  * haven't had time to make test patches for things like changing the
1210  * timing mode on that external RAM either.  Some of those changes may
1211  * fix the problem.  Until then though, we default to external SCB RAM
1212  * off and give a command line option to enable it.
1213  */
1214 static int aic7xxx_scbram = 0;
1215 /*
1216  * So that we can set how long each device is given as a selection timeout.
1217  * The table of values goes like this:
1218  *   0 - 256ms
1219  *   1 - 128ms
1220  *   2 - 64ms
1221  *   3 - 32ms
1222  * We default to 64ms because it's fast.  Some old SCSI-I devices need a
1223  * longer time.  The final value has to be left shifted by 3, hence 0x10
1224  * is the final value.
1225  */
1226 static int aic7xxx_seltime = 0x10;
1227 /*
1228  * So that insmod can find the variable and make it point to something
1229  */
1230 #ifdef MODULE
1231 static char * aic7xxx = NULL;
1232 module_param(aic7xxx, charp, 0);
1233 #endif
1234
1235 #define VERBOSE_NORMAL         0x0000
1236 #define VERBOSE_NEGOTIATION    0x0001
1237 #define VERBOSE_SEQINT         0x0002
1238 #define VERBOSE_SCSIINT        0x0004
1239 #define VERBOSE_PROBE          0x0008
1240 #define VERBOSE_PROBE2         0x0010
1241 #define VERBOSE_NEGOTIATION2   0x0020
1242 #define VERBOSE_MINOR_ERROR    0x0040
1243 #define VERBOSE_TRACING        0x0080
1244 #define VERBOSE_ABORT          0x0f00
1245 #define VERBOSE_ABORT_MID      0x0100
1246 #define VERBOSE_ABORT_FIND     0x0200
1247 #define VERBOSE_ABORT_PROCESS  0x0400
1248 #define VERBOSE_ABORT_RETURN   0x0800
1249 #define VERBOSE_RESET          0xf000
1250 #define VERBOSE_RESET_MID      0x1000
1251 #define VERBOSE_RESET_FIND     0x2000
1252 #define VERBOSE_RESET_PROCESS  0x4000
1253 #define VERBOSE_RESET_RETURN   0x8000
1254 static int aic7xxx_verbose = VERBOSE_NORMAL | VERBOSE_NEGOTIATION |
1255            VERBOSE_PROBE;                     /* verbose messages */
1256
1257
1258 /****************************************************************************
1259  *
1260  * We're going to start putting in function declarations so that order of
1261  * functions is no longer important.  As needed, they are added here.
1262  *
1263  ***************************************************************************/
1264
1265 static int aic7xxx_release(struct Scsi_Host *host);
1266 static void aic7xxx_set_syncrate(struct aic7xxx_host *p, 
1267                 struct aic7xxx_syncrate *syncrate, int target, int channel,
1268                 unsigned int period, unsigned int offset, unsigned char options,
1269                 unsigned int type, struct aic_dev_data *aic_dev);
1270 static void aic7xxx_set_width(struct aic7xxx_host *p, int target, int channel,
1271                 int lun, unsigned int width, unsigned int type,
1272                 struct aic_dev_data *aic_dev);
1273 static void aic7xxx_panic_abort(struct aic7xxx_host *p, struct scsi_cmnd *cmd);
1274 static void aic7xxx_print_card(struct aic7xxx_host *p);
1275 static void aic7xxx_print_scratch_ram(struct aic7xxx_host *p);
1276 static void aic7xxx_print_sequencer(struct aic7xxx_host *p, int downloaded);
1277 #ifdef AIC7XXX_VERBOSE_DEBUGGING
1278 static void aic7xxx_check_scbs(struct aic7xxx_host *p, char *buffer);
1279 #endif
1280
1281 /****************************************************************************
1282  *
1283  * These functions are now used.  They happen to be wrapped in useless
1284  * inb/outb port read/writes around the real reads and writes because it
1285  * seems that certain very fast CPUs have a problem dealing with us when
1286  * going at full speed.
1287  *
1288  ***************************************************************************/
1289
1290 static unsigned char
1291 aic_inb(struct aic7xxx_host *p, long port)
1292 {
1293 #ifdef MMAPIO
1294   unsigned char x;
1295   if(p->maddr)
1296   {
1297     x = readb(p->maddr + port);
1298   }
1299   else
1300   {
1301     x = inb(p->base + port);
1302   }
1303   return(x);
1304 #else
1305   return(inb(p->base + port));
1306 #endif
1307 }
1308
1309 static void
1310 aic_outb(struct aic7xxx_host *p, unsigned char val, long port)
1311 {
1312 #ifdef MMAPIO
1313   if(p->maddr)
1314   {
1315     writeb(val, p->maddr + port);
1316     mb(); /* locked operation in order to force CPU ordering */
1317     readb(p->maddr + HCNTRL); /* dummy read to flush the PCI write */
1318   }
1319   else
1320   {
1321     outb(val, p->base + port);
1322     mb(); /* locked operation in order to force CPU ordering */
1323   }
1324 #else
1325   outb(val, p->base + port);
1326   mb(); /* locked operation in order to force CPU ordering */
1327 #endif
1328 }
1329
1330 /*+F*************************************************************************
1331  * Function:
1332  *   aic7xxx_setup
1333  *
1334  * Description:
1335  *   Handle Linux boot parameters. This routine allows for assigning a value
1336  *   to a parameter with a ':' between the parameter and the value.
1337  *   ie. aic7xxx=unpause:0x0A,extended
1338  *-F*************************************************************************/
1339 static int
1340 aic7xxx_setup(char *s)
1341 {
1342   int   i, n;
1343   char *p;
1344   char *end;
1345
1346   static struct {
1347     const char *name;
1348     unsigned int *flag;
1349   } options[] = {
1350     { "extended",    &aic7xxx_extended },
1351     { "no_reset",    &aic7xxx_no_reset },
1352     { "irq_trigger", &aic7xxx_irq_trigger },
1353     { "verbose",     &aic7xxx_verbose },
1354     { "reverse_scan",&aic7xxx_reverse_scan },
1355     { "override_term", &aic7xxx_override_term },
1356     { "stpwlev", &aic7xxx_stpwlev },
1357     { "no_probe", &aic7xxx_no_probe },
1358     { "panic_on_abort", &aic7xxx_panic_on_abort },
1359     { "pci_parity", &aic7xxx_pci_parity },
1360     { "dump_card", &aic7xxx_dump_card },
1361     { "dump_sequencer", &aic7xxx_dump_sequencer },
1362     { "default_queue_depth", &aic7xxx_default_queue_depth },
1363     { "scbram", &aic7xxx_scbram },
1364     { "seltime", &aic7xxx_seltime },
1365     { "tag_info",    NULL }
1366   };
1367
1368   end = strchr(s, '\0');
1369
1370   while ((p = strsep(&s, ",.")) != NULL)
1371   {
1372     for (i = 0; i < ARRAY_SIZE(options); i++)
1373     {
1374       n = strlen(options[i].name);
1375       if (!strncmp(options[i].name, p, n))
1376       {
1377         if (!strncmp(p, "tag_info", n))
1378         {
1379           if (p[n] == ':')
1380           {
1381             char *base;
1382             char *tok, *tok_end, *tok_end2;
1383             char tok_list[] = { '.', ',', '{', '}', '\0' };
1384             int i, instance = -1, device = -1;
1385             unsigned char done = FALSE;
1386
1387             base = p;
1388             tok = base + n + 1;  /* Forward us just past the ':' */
1389             tok_end = strchr(tok, '\0');
1390             if (tok_end < end)
1391               *tok_end = ',';
1392             while(!done)
1393             {
1394               switch(*tok)
1395               {
1396                 case '{':
1397                   if (instance == -1)
1398                     instance = 0;
1399                   else if (device == -1)
1400                     device = 0;
1401                   tok++;
1402                   break;
1403                 case '}':
1404                   if (device != -1)
1405                     device = -1;
1406                   else if (instance != -1)
1407                     instance = -1;
1408                   tok++;
1409                   break;
1410                 case ',':
1411                 case '.':
1412                   if (instance == -1)
1413                     done = TRUE;
1414                   else if (device >= 0)
1415                     device++;
1416                   else if (instance >= 0)
1417                     instance++;
1418                   if ( (device >= MAX_TARGETS) || 
1419                        (instance >= ARRAY_SIZE(aic7xxx_tag_info)) )
1420                     done = TRUE;
1421                   tok++;
1422                   if (!done)
1423                   {
1424                     base = tok;
1425                   }
1426                   break;
1427                 case '\0':
1428                   done = TRUE;
1429                   break;
1430                 default:
1431                   done = TRUE;
1432                   tok_end = strchr(tok, '\0');
1433                   for(i=0; tok_list[i]; i++)
1434                   {
1435                     tok_end2 = strchr(tok, tok_list[i]);
1436                     if ( (tok_end2) && (tok_end2 < tok_end) )
1437                     {
1438                       tok_end = tok_end2;
1439                       done = FALSE;
1440                     }
1441                   }
1442                   if ( (instance >= 0) && (device >= 0) &&
1443                        (instance < ARRAY_SIZE(aic7xxx_tag_info)) &&
1444                        (device < MAX_TARGETS) )
1445                     aic7xxx_tag_info[instance].tag_commands[device] =
1446                       simple_strtoul(tok, NULL, 0) & 0xff;
1447                   tok = tok_end;
1448                   break;
1449               }
1450             }
1451             while((p != base) && (p != NULL))
1452               p = strsep(&s, ",.");
1453           }
1454         }
1455         else if (p[n] == ':')
1456         {
1457           *(options[i].flag) = simple_strtoul(p + n + 1, NULL, 0);
1458           if(!strncmp(p, "seltime", n))
1459           {
1460             *(options[i].flag) = (*(options[i].flag) % 4) << 3;
1461           }
1462         }
1463         else if (!strncmp(p, "verbose", n))
1464         {
1465           *(options[i].flag) = 0xff29;
1466         }
1467         else
1468         {
1469           *(options[i].flag) = ~(*(options[i].flag));
1470           if(!strncmp(p, "seltime", n))
1471           {
1472             *(options[i].flag) = (*(options[i].flag) % 4) << 3;
1473           }
1474         }
1475       }
1476     }
1477   }
1478   return 1;
1479 }
1480
1481 __setup("aic7xxx=", aic7xxx_setup);
1482
1483 /*+F*************************************************************************
1484  * Function:
1485  *   pause_sequencer
1486  *
1487  * Description:
1488  *   Pause the sequencer and wait for it to actually stop - this
1489  *   is important since the sequencer can disable pausing for critical
1490  *   sections.
1491  *-F*************************************************************************/
1492 static void
1493 pause_sequencer(struct aic7xxx_host *p)
1494 {
1495   aic_outb(p, p->pause, HCNTRL);
1496   while ((aic_inb(p, HCNTRL) & PAUSE) == 0)
1497   {
1498     ;
1499   }
1500   if(p->features & AHC_ULTRA2)
1501   {
1502     aic_inb(p, CCSCBCTL);
1503   }
1504 }
1505
1506 /*+F*************************************************************************
1507  * Function:
1508  *   unpause_sequencer
1509  *
1510  * Description:
1511  *   Unpause the sequencer. Unremarkable, yet done often enough to
1512  *   warrant an easy way to do it.
1513  *-F*************************************************************************/
1514 static void
1515 unpause_sequencer(struct aic7xxx_host *p, int unpause_always)
1516 {
1517   if (unpause_always ||
1518       ( !(aic_inb(p, INTSTAT) & (SCSIINT | SEQINT | BRKADRINT)) &&
1519         !(p->flags & AHC_HANDLING_REQINITS) ) )
1520   {
1521     aic_outb(p, p->unpause, HCNTRL);
1522   }
1523 }
1524
1525 /*+F*************************************************************************
1526  * Function:
1527  *   restart_sequencer
1528  *
1529  * Description:
1530  *   Restart the sequencer program from address zero.  This assumes
1531  *   that the sequencer is already paused.
1532  *-F*************************************************************************/
1533 static void
1534 restart_sequencer(struct aic7xxx_host *p)
1535 {
1536   aic_outb(p, 0, SEQADDR0);
1537   aic_outb(p, 0, SEQADDR1);
1538   aic_outb(p, FASTMODE, SEQCTL);
1539 }
1540
1541 /*
1542  * We include the aic7xxx_seq.c file here so that the other defines have
1543  * already been made, and so that it comes before the code that actually
1544  * downloads the instructions (since we don't typically use function
1545  * prototype, our code has to be ordered that way, it's a left-over from
1546  * the original driver days.....I should fix it some time DL).
1547  */
1548 #include "aic7xxx_old/aic7xxx_seq.c"
1549
1550 /*+F*************************************************************************
1551  * Function:
1552  *   aic7xxx_check_patch
1553  *
1554  * Description:
1555  *   See if the next patch to download should be downloaded.
1556  *-F*************************************************************************/
1557 static int
1558 aic7xxx_check_patch(struct aic7xxx_host *p,
1559   struct sequencer_patch **start_patch, int start_instr, int *skip_addr)
1560 {
1561   struct sequencer_patch *cur_patch;
1562   struct sequencer_patch *last_patch;
1563   int num_patches;
1564
1565   num_patches = ARRAY_SIZE(sequencer_patches);
1566   last_patch = &sequencer_patches[num_patches];
1567   cur_patch = *start_patch;
1568
1569   while ((cur_patch < last_patch) && (start_instr == cur_patch->begin))
1570   {
1571     if (cur_patch->patch_func(p) == 0)
1572     {
1573       /*
1574        * Start rejecting code.
1575        */
1576       *skip_addr = start_instr + cur_patch->skip_instr;
1577       cur_patch += cur_patch->skip_patch;
1578     }
1579     else
1580     {
1581       /*
1582        * Found an OK patch.  Advance the patch pointer to the next patch
1583        * and wait for our instruction pointer to get here.
1584        */
1585       cur_patch++;
1586     }
1587   }
1588
1589   *start_patch = cur_patch;
1590   if (start_instr < *skip_addr)
1591     /*
1592      * Still skipping
1593      */
1594     return (0);
1595   return(1);
1596 }
1597
1598
1599 /*+F*************************************************************************
1600  * Function:
1601  *   aic7xxx_download_instr
1602  *
1603  * Description:
1604  *   Find the next patch to download.
1605  *-F*************************************************************************/
1606 static void
1607 aic7xxx_download_instr(struct aic7xxx_host *p, int instrptr,
1608   unsigned char *dconsts)
1609 {
1610   union ins_formats instr;
1611   struct ins_format1 *fmt1_ins;
1612   struct ins_format3 *fmt3_ins;
1613   unsigned char opcode;
1614
1615   instr = *(union ins_formats*) &seqprog[instrptr * 4];
1616
1617   instr.integer = le32_to_cpu(instr.integer);
1618   
1619   fmt1_ins = &instr.format1;
1620   fmt3_ins = NULL;
1621
1622   /* Pull the opcode */
1623   opcode = instr.format1.opcode;
1624   switch (opcode)
1625   {
1626     case AIC_OP_JMP:
1627     case AIC_OP_JC:
1628     case AIC_OP_JNC:
1629     case AIC_OP_CALL:
1630     case AIC_OP_JNE:
1631     case AIC_OP_JNZ:
1632     case AIC_OP_JE:
1633     case AIC_OP_JZ:
1634     {
1635       struct sequencer_patch *cur_patch;
1636       int address_offset;
1637       unsigned int address;
1638       int skip_addr;
1639       int i;
1640
1641       fmt3_ins = &instr.format3;
1642       address_offset = 0;
1643       address = fmt3_ins->address;
1644       cur_patch = sequencer_patches;
1645       skip_addr = 0;
1646
1647       for (i = 0; i < address;)
1648       {
1649         aic7xxx_check_patch(p, &cur_patch, i, &skip_addr);
1650         if (skip_addr > i)
1651         {
1652           int end_addr;
1653
1654           end_addr = min_t(int, address, skip_addr);
1655           address_offset += end_addr - i;
1656           i = skip_addr;
1657         }
1658         else
1659         {
1660           i++;
1661         }
1662       }
1663       address -= address_offset;
1664       fmt3_ins->address = address;
1665       /* Fall Through to the next code section */
1666     }
1667     case AIC_OP_OR:
1668     case AIC_OP_AND:
1669     case AIC_OP_XOR:
1670     case AIC_OP_ADD:
1671     case AIC_OP_ADC:
1672     case AIC_OP_BMOV:
1673       if (fmt1_ins->parity != 0)
1674       {
1675         fmt1_ins->immediate = dconsts[fmt1_ins->immediate];
1676       }
1677       fmt1_ins->parity = 0;
1678       /* Fall Through to the next code section */
1679     case AIC_OP_ROL:
1680       if ((p->features & AHC_ULTRA2) != 0)
1681       {
1682         int i, count;
1683
1684         /* Calculate odd parity for the instruction */
1685         for ( i=0, count=0; i < 31; i++)
1686         {
1687           unsigned int mask;
1688
1689           mask = 0x01 << i;
1690           if ((instr.integer & mask) != 0)
1691             count++;
1692         }
1693         if (!(count & 0x01))
1694           instr.format1.parity = 1;
1695       }
1696       else
1697       {
1698         if (fmt3_ins != NULL)
1699         {
1700           instr.integer =  fmt3_ins->immediate |
1701                           (fmt3_ins->source << 8) |
1702                           (fmt3_ins->address << 16) |
1703                           (fmt3_ins->opcode << 25);
1704         }
1705         else
1706         {
1707           instr.integer =  fmt1_ins->immediate |
1708                           (fmt1_ins->source << 8) |
1709                           (fmt1_ins->destination << 16) |
1710                           (fmt1_ins->ret << 24) |
1711                           (fmt1_ins->opcode << 25);
1712         }
1713       }
1714       aic_outb(p, (instr.integer & 0xff), SEQRAM);
1715       aic_outb(p, ((instr.integer >> 8) & 0xff), SEQRAM);
1716       aic_outb(p, ((instr.integer >> 16) & 0xff), SEQRAM);
1717       aic_outb(p, ((instr.integer >> 24) & 0xff), SEQRAM);
1718       udelay(10);
1719       break;
1720
1721     default:
1722       panic("aic7xxx: Unknown opcode encountered in sequencer program.");
1723       break;
1724   }
1725 }
1726
1727
1728 /*+F*************************************************************************
1729  * Function:
1730  *   aic7xxx_loadseq
1731  *
1732  * Description:
1733  *   Load the sequencer code into the controller memory.
1734  *-F*************************************************************************/
1735 static void
1736 aic7xxx_loadseq(struct aic7xxx_host *p)
1737 {
1738   struct sequencer_patch *cur_patch;
1739   int i;
1740   int downloaded;
1741   int skip_addr;
1742   unsigned char download_consts[4] = {0, 0, 0, 0};
1743
1744   if (aic7xxx_verbose & VERBOSE_PROBE)
1745   {
1746     printk(KERN_INFO "(scsi%d) Downloading sequencer code...", p->host_no);
1747   }
1748 #if 0
1749   download_consts[TMODE_NUMCMDS] = p->num_targetcmds;
1750 #endif
1751   download_consts[TMODE_NUMCMDS] = 0;
1752   cur_patch = &sequencer_patches[0];
1753   downloaded = 0;
1754   skip_addr = 0;
1755
1756   aic_outb(p, PERRORDIS|LOADRAM|FAILDIS|FASTMODE, SEQCTL);
1757   aic_outb(p, 0, SEQADDR0);
1758   aic_outb(p, 0, SEQADDR1);
1759
1760   for (i = 0; i < sizeof(seqprog) / 4;  i++)
1761   {
1762     if (aic7xxx_check_patch(p, &cur_patch, i, &skip_addr) == 0)
1763     {
1764       /* Skip this instruction for this configuration. */
1765       continue;
1766     }
1767     aic7xxx_download_instr(p, i, &download_consts[0]);
1768     downloaded++;
1769   }
1770
1771   aic_outb(p, 0, SEQADDR0);
1772   aic_outb(p, 0, SEQADDR1);
1773   aic_outb(p, FASTMODE | FAILDIS, SEQCTL);
1774   unpause_sequencer(p, TRUE);
1775   mdelay(1);
1776   pause_sequencer(p);
1777   aic_outb(p, FASTMODE, SEQCTL);
1778   if (aic7xxx_verbose & VERBOSE_PROBE)
1779   {
1780     printk(" %d instructions downloaded\n", downloaded);
1781   }
1782   if (aic7xxx_dump_sequencer)
1783     aic7xxx_print_sequencer(p, downloaded);
1784 }
1785
1786 /*+F*************************************************************************
1787  * Function:
1788  *   aic7xxx_print_sequencer
1789  *
1790  * Description:
1791  *   Print the contents of the sequencer memory to the screen.
1792  *-F*************************************************************************/
1793 static void
1794 aic7xxx_print_sequencer(struct aic7xxx_host *p, int downloaded)
1795 {
1796   int i, k, temp;
1797   
1798   aic_outb(p, PERRORDIS|LOADRAM|FAILDIS|FASTMODE, SEQCTL);
1799   aic_outb(p, 0, SEQADDR0);
1800   aic_outb(p, 0, SEQADDR1);
1801
1802   k = 0;
1803   for (i=0; i < downloaded; i++)
1804   {
1805     if ( k == 0 )
1806       printk("%03x: ", i);
1807     temp = aic_inb(p, SEQRAM);
1808     temp |= (aic_inb(p, SEQRAM) << 8);
1809     temp |= (aic_inb(p, SEQRAM) << 16);
1810     temp |= (aic_inb(p, SEQRAM) << 24);
1811     printk("%08x", temp);
1812     if ( ++k == 8 )
1813     {
1814       printk("\n");
1815       k = 0;
1816     }
1817     else
1818       printk(" ");
1819   }
1820   aic_outb(p, 0, SEQADDR0);
1821   aic_outb(p, 0, SEQADDR1);
1822   aic_outb(p, FASTMODE | FAILDIS, SEQCTL);
1823   unpause_sequencer(p, TRUE);
1824   mdelay(1);
1825   pause_sequencer(p);
1826   aic_outb(p, FASTMODE, SEQCTL);
1827   printk("\n");
1828 }
1829
1830 /*+F*************************************************************************
1831  * Function:
1832  *   aic7xxx_info
1833  *
1834  * Description:
1835  *   Return a string describing the driver.
1836  *-F*************************************************************************/
1837 static const char *
1838 aic7xxx_info(struct Scsi_Host *dooh)
1839 {
1840   static char buffer[256];
1841   char *bp;
1842   struct aic7xxx_host *p;
1843
1844   bp = &buffer[0];
1845   p = (struct aic7xxx_host *)dooh->hostdata;
1846   memset(bp, 0, sizeof(buffer));
1847   strcpy(bp, "Adaptec AHA274x/284x/294x (EISA/VLB/PCI-Fast SCSI) ");
1848   strcat(bp, AIC7XXX_C_VERSION);
1849   strcat(bp, "/");
1850   strcat(bp, AIC7XXX_H_VERSION);
1851   strcat(bp, "\n");
1852   strcat(bp, "       <");
1853   strcat(bp, board_names[p->board_name_index]);
1854   strcat(bp, ">");
1855
1856   return(bp);
1857 }
1858
1859 /*+F*************************************************************************
1860  * Function:
1861  *   aic7xxx_find_syncrate
1862  *
1863  * Description:
1864  *   Look up the valid period to SCSIRATE conversion in our table
1865  *-F*************************************************************************/
1866 static struct aic7xxx_syncrate *
1867 aic7xxx_find_syncrate(struct aic7xxx_host *p, unsigned int *period,
1868   unsigned int maxsync, unsigned char *options)
1869 {
1870   struct aic7xxx_syncrate *syncrate;
1871   int done = FALSE;
1872
1873   switch(*options)
1874   {
1875     case MSG_EXT_PPR_OPTION_DT_CRC:
1876     case MSG_EXT_PPR_OPTION_DT_UNITS:
1877       if(!(p->features & AHC_ULTRA3))
1878       {
1879         *options = 0;
1880         maxsync = max_t(unsigned int, maxsync, AHC_SYNCRATE_ULTRA2);
1881       }
1882       break;
1883     case MSG_EXT_PPR_OPTION_DT_CRC_QUICK:
1884     case MSG_EXT_PPR_OPTION_DT_UNITS_QUICK:
1885       if(!(p->features & AHC_ULTRA3))
1886       {
1887         *options = 0;
1888         maxsync = max_t(unsigned int, maxsync, AHC_SYNCRATE_ULTRA2);
1889       }
1890       else
1891       {
1892         /*
1893          * we don't support the Quick Arbitration variants of dual edge
1894          * clocking.  As it turns out, we want to send back the
1895          * same basic option, but without the QA attribute.
1896          * We know that we are responding because we would never set
1897          * these options ourself, we would only respond to them.
1898          */
1899         switch(*options)
1900         {
1901           case MSG_EXT_PPR_OPTION_DT_CRC_QUICK:
1902             *options = MSG_EXT_PPR_OPTION_DT_CRC;
1903             break;
1904           case MSG_EXT_PPR_OPTION_DT_UNITS_QUICK:
1905             *options = MSG_EXT_PPR_OPTION_DT_UNITS;
1906             break;
1907         }
1908       }
1909       break;
1910     default:
1911       *options = 0;
1912       maxsync = max_t(unsigned int, maxsync, AHC_SYNCRATE_ULTRA2);
1913       break;
1914   }
1915   syncrate = &aic7xxx_syncrates[maxsync];
1916   while ( (syncrate->rate[0] != NULL) &&
1917          (!(p->features & AHC_ULTRA2) || syncrate->sxfr_ultra2) )
1918   {
1919     if (*period <= syncrate->period) 
1920     {
1921       switch(*options)
1922       {
1923         case MSG_EXT_PPR_OPTION_DT_CRC:
1924         case MSG_EXT_PPR_OPTION_DT_UNITS:
1925           if(!(syncrate->sxfr_ultra2 & AHC_SYNCRATE_CRC))
1926           {
1927             done = TRUE;
1928             /*
1929              * oops, we went too low for the CRC/DualEdge signalling, so
1930              * clear the options byte
1931              */
1932             *options = 0;
1933             /*
1934              * We'll be sending a reply to this packet to set the options
1935              * properly, so unilaterally set the period as well.
1936              */
1937             *period = syncrate->period;
1938           }
1939           else
1940           {
1941             done = TRUE;
1942             if(syncrate == &aic7xxx_syncrates[maxsync])
1943             {
1944               *period = syncrate->period;
1945             }
1946           }
1947           break;
1948         default:
1949           if(!(syncrate->sxfr_ultra2 & AHC_SYNCRATE_CRC))
1950           {
1951             done = TRUE;
1952             if(syncrate == &aic7xxx_syncrates[maxsync])
1953             {
1954               *period = syncrate->period;
1955             }
1956           }
1957           break;
1958       }
1959       if(done)
1960       {
1961         break;
1962       }
1963     }
1964     syncrate++;
1965   }
1966   if ( (*period == 0) || (syncrate->rate[0] == NULL) ||
1967        ((p->features & AHC_ULTRA2) && (syncrate->sxfr_ultra2 == 0)) )
1968   {
1969     /*
1970      * Use async transfers for this target
1971      */
1972     *options = 0;
1973     *period = 255;
1974     syncrate = NULL;
1975   }
1976   return (syncrate);
1977 }
1978
1979
1980 /*+F*************************************************************************
1981  * Function:
1982  *   aic7xxx_find_period
1983  *
1984  * Description:
1985  *   Look up the valid SCSIRATE to period conversion in our table
1986  *-F*************************************************************************/
1987 static unsigned int
1988 aic7xxx_find_period(struct aic7xxx_host *p, unsigned int scsirate,
1989   unsigned int maxsync)
1990 {
1991   struct aic7xxx_syncrate *syncrate;
1992
1993   if (p->features & AHC_ULTRA2)
1994   {
1995     scsirate &= SXFR_ULTRA2;
1996   }
1997   else
1998   {
1999     scsirate &= SXFR;
2000   }
2001
2002   syncrate = &aic7xxx_syncrates[maxsync];
2003   while (syncrate->rate[0] != NULL)
2004   {
2005     if (p->features & AHC_ULTRA2)
2006     {
2007       if (syncrate->sxfr_ultra2 == 0)
2008         break;
2009       else if (scsirate == syncrate->sxfr_ultra2)
2010         return (syncrate->period);
2011       else if (scsirate == (syncrate->sxfr_ultra2 & ~AHC_SYNCRATE_CRC))
2012         return (syncrate->period);
2013     }
2014     else if (scsirate == (syncrate->sxfr & ~ULTRA_SXFR))
2015     {
2016       return (syncrate->period);
2017     }
2018     syncrate++;
2019   }
2020   return (0); /* async */
2021 }
2022
2023 /*+F*************************************************************************
2024  * Function:
2025  *   aic7xxx_validate_offset
2026  *
2027  * Description:
2028  *   Set a valid offset value for a particular card in use and transfer
2029  *   settings in use.
2030  *-F*************************************************************************/
2031 static void
2032 aic7xxx_validate_offset(struct aic7xxx_host *p,
2033   struct aic7xxx_syncrate *syncrate, unsigned int *offset, int wide)
2034 {
2035   unsigned int maxoffset;
2036
2037   /* Limit offset to what the card (and device) can do */
2038   if (syncrate == NULL)
2039   {
2040     maxoffset = 0;
2041   }
2042   else if (p->features & AHC_ULTRA2)
2043   {
2044     maxoffset = MAX_OFFSET_ULTRA2;
2045   }
2046   else
2047   {
2048     if (wide)
2049       maxoffset = MAX_OFFSET_16BIT;
2050     else
2051       maxoffset = MAX_OFFSET_8BIT;
2052   }
2053   *offset = min(*offset, maxoffset);
2054 }
2055
2056 /*+F*************************************************************************
2057  * Function:
2058  *   aic7xxx_set_syncrate
2059  *
2060  * Description:
2061  *   Set the actual syncrate down in the card and in our host structs
2062  *-F*************************************************************************/
2063 static void
2064 aic7xxx_set_syncrate(struct aic7xxx_host *p, struct aic7xxx_syncrate *syncrate,
2065     int target, int channel, unsigned int period, unsigned int offset,
2066     unsigned char options, unsigned int type, struct aic_dev_data *aic_dev)
2067 {
2068   unsigned char tindex;
2069   unsigned short target_mask;
2070   unsigned char lun, old_options;
2071   unsigned int old_period, old_offset;
2072
2073   tindex = target | (channel << 3);
2074   target_mask = 0x01 << tindex;
2075   lun = aic_inb(p, SCB_TCL) & 0x07;
2076
2077   if (syncrate == NULL)
2078   {
2079     period = 0;
2080     offset = 0;
2081   }
2082
2083   old_period = aic_dev->cur.period;
2084   old_offset = aic_dev->cur.offset;
2085   old_options = aic_dev->cur.options;
2086
2087   
2088   if (type & AHC_TRANS_CUR)
2089   {
2090     unsigned int scsirate;
2091
2092     scsirate = aic_inb(p, TARG_SCSIRATE + tindex);
2093     if (p->features & AHC_ULTRA2)
2094     {
2095       scsirate &= ~SXFR_ULTRA2;
2096       if (syncrate != NULL)
2097       {
2098         switch(options)
2099         {
2100           case MSG_EXT_PPR_OPTION_DT_UNITS:
2101             /*
2102              * mask off the CRC bit in the xfer settings
2103              */
2104             scsirate |= (syncrate->sxfr_ultra2 & ~AHC_SYNCRATE_CRC);
2105             break;
2106           default:
2107             scsirate |= syncrate->sxfr_ultra2;
2108             break;
2109         }
2110       }
2111       if (type & AHC_TRANS_ACTIVE)
2112       {
2113         aic_outb(p, offset, SCSIOFFSET);
2114       }
2115       aic_outb(p, offset, TARG_OFFSET + tindex);
2116     }
2117     else /* Not an Ultra2 controller */
2118     {
2119       scsirate &= ~(SXFR|SOFS);
2120       p->ultraenb &= ~target_mask;
2121       if (syncrate != NULL)
2122       {
2123         if (syncrate->sxfr & ULTRA_SXFR)
2124         {
2125           p->ultraenb |= target_mask;
2126         }
2127         scsirate |= (syncrate->sxfr & SXFR);
2128         scsirate |= (offset & SOFS);
2129       }
2130       if (type & AHC_TRANS_ACTIVE)
2131       {
2132         unsigned char sxfrctl0;
2133
2134         sxfrctl0 = aic_inb(p, SXFRCTL0);
2135         sxfrctl0 &= ~FAST20;
2136         if (p->ultraenb & target_mask)
2137           sxfrctl0 |= FAST20;
2138         aic_outb(p, sxfrctl0, SXFRCTL0);
2139       }
2140       aic_outb(p, p->ultraenb & 0xff, ULTRA_ENB);
2141       aic_outb(p, (p->ultraenb >> 8) & 0xff, ULTRA_ENB + 1 );
2142     }
2143     if (type & AHC_TRANS_ACTIVE)
2144     {
2145       aic_outb(p, scsirate, SCSIRATE);
2146     }
2147     aic_outb(p, scsirate, TARG_SCSIRATE + tindex);
2148     aic_dev->cur.period = period;
2149     aic_dev->cur.offset = offset;
2150     aic_dev->cur.options = options;
2151     if ( !(type & AHC_TRANS_QUITE) &&
2152          (aic7xxx_verbose & VERBOSE_NEGOTIATION) &&
2153          (aic_dev->flags & DEVICE_PRINT_DTR) )
2154     {
2155       if (offset)
2156       {
2157         int rate_mod = (scsirate & WIDEXFER) ? 1 : 0;
2158       
2159         printk(INFO_LEAD "Synchronous at %s Mbyte/sec, "
2160                "offset %d.\n", p->host_no, channel, target, lun,
2161                syncrate->rate[rate_mod], offset);
2162       }
2163       else
2164       {
2165         printk(INFO_LEAD "Using asynchronous transfers.\n",
2166                p->host_no, channel, target, lun);
2167       }
2168       aic_dev->flags &= ~DEVICE_PRINT_DTR;
2169     }
2170   }
2171
2172   if (type & AHC_TRANS_GOAL)
2173   {
2174     aic_dev->goal.period = period;
2175     aic_dev->goal.offset = offset;
2176     aic_dev->goal.options = options;
2177   }
2178
2179   if (type & AHC_TRANS_USER)
2180   {
2181     p->user[tindex].period = period;
2182     p->user[tindex].offset = offset;
2183     p->user[tindex].options = options;
2184   }
2185 }
2186
2187 /*+F*************************************************************************
2188  * Function:
2189  *   aic7xxx_set_width
2190  *
2191  * Description:
2192  *   Set the actual width down in the card and in our host structs
2193  *-F*************************************************************************/
2194 static void
2195 aic7xxx_set_width(struct aic7xxx_host *p, int target, int channel, int lun,
2196     unsigned int width, unsigned int type, struct aic_dev_data *aic_dev)
2197 {
2198   unsigned char tindex;
2199   unsigned short target_mask;
2200   unsigned int old_width;
2201
2202   tindex = target | (channel << 3);
2203   target_mask = 1 << tindex;
2204   
2205   old_width = aic_dev->cur.width;
2206
2207   if (type & AHC_TRANS_CUR) 
2208   {
2209     unsigned char scsirate;
2210
2211     scsirate = aic_inb(p, TARG_SCSIRATE + tindex);
2212
2213     scsirate &= ~WIDEXFER;
2214     if (width == MSG_EXT_WDTR_BUS_16_BIT)
2215       scsirate |= WIDEXFER;
2216
2217     aic_outb(p, scsirate, TARG_SCSIRATE + tindex);
2218
2219     if (type & AHC_TRANS_ACTIVE)
2220       aic_outb(p, scsirate, SCSIRATE);
2221
2222     aic_dev->cur.width = width;
2223
2224     if ( !(type & AHC_TRANS_QUITE) &&
2225           (aic7xxx_verbose & VERBOSE_NEGOTIATION2) && 
2226           (aic_dev->flags & DEVICE_PRINT_DTR) )
2227     {
2228       printk(INFO_LEAD "Using %s transfers\n", p->host_no, channel, target,
2229         lun, (scsirate & WIDEXFER) ? "Wide(16bit)" : "Narrow(8bit)" );
2230     }
2231   }
2232
2233   if (type & AHC_TRANS_GOAL)
2234     aic_dev->goal.width = width;
2235   if (type & AHC_TRANS_USER)
2236     p->user[tindex].width = width;
2237
2238   if (aic_dev->goal.offset)
2239   {
2240     if (p->features & AHC_ULTRA2)
2241     {
2242       aic_dev->goal.offset = MAX_OFFSET_ULTRA2;
2243     }
2244     else if (width == MSG_EXT_WDTR_BUS_16_BIT)
2245     {
2246       aic_dev->goal.offset = MAX_OFFSET_16BIT;
2247     }
2248     else
2249     {
2250       aic_dev->goal.offset = MAX_OFFSET_8BIT;
2251     }
2252   }
2253 }
2254       
2255 /*+F*************************************************************************
2256  * Function:
2257  *   scbq_init
2258  *
2259  * Description:
2260  *   SCB queue initialization.
2261  *
2262  *-F*************************************************************************/
2263 static void
2264 scbq_init(volatile scb_queue_type *queue)
2265 {
2266   queue->head = NULL;
2267   queue->tail = NULL;
2268 }
2269
2270 /*+F*************************************************************************
2271  * Function:
2272  *   scbq_insert_head
2273  *
2274  * Description:
2275  *   Add an SCB to the head of the list.
2276  *
2277  *-F*************************************************************************/
2278 static inline void
2279 scbq_insert_head(volatile scb_queue_type *queue, struct aic7xxx_scb *scb)
2280 {
2281   scb->q_next = queue->head;
2282   queue->head = scb;
2283   if (queue->tail == NULL)       /* If list was empty, update tail. */
2284     queue->tail = queue->head;
2285 }
2286
2287 /*+F*************************************************************************
2288  * Function:
2289  *   scbq_remove_head
2290  *
2291  * Description:
2292  *   Remove an SCB from the head of the list.
2293  *
2294  *-F*************************************************************************/
2295 static inline struct aic7xxx_scb *
2296 scbq_remove_head(volatile scb_queue_type *queue)
2297 {
2298   struct aic7xxx_scb * scbp;
2299
2300   scbp = queue->head;
2301   if (queue->head != NULL)
2302     queue->head = queue->head->q_next;
2303   if (queue->head == NULL)       /* If list is now empty, update tail. */
2304     queue->tail = NULL;
2305   return(scbp);
2306 }
2307
2308 /*+F*************************************************************************
2309  * Function:
2310  *   scbq_remove
2311  *
2312  * Description:
2313  *   Removes an SCB from the list.
2314  *
2315  *-F*************************************************************************/
2316 static inline void
2317 scbq_remove(volatile scb_queue_type *queue, struct aic7xxx_scb *scb)
2318 {
2319   if (queue->head == scb)
2320   {
2321     /* At beginning of queue, remove from head. */
2322     scbq_remove_head(queue);
2323   }
2324   else
2325   {
2326     struct aic7xxx_scb *curscb = queue->head;
2327
2328     /*
2329      * Search until the next scb is the one we're looking for, or
2330      * we run out of queue.
2331      */
2332     while ((curscb != NULL) && (curscb->q_next != scb))
2333     {
2334       curscb = curscb->q_next;
2335     }
2336     if (curscb != NULL)
2337     {
2338       /* Found it. */
2339       curscb->q_next = scb->q_next;
2340       if (scb->q_next == NULL)
2341       {
2342         /* Update the tail when removing the tail. */
2343         queue->tail = curscb;
2344       }
2345     }
2346   }
2347 }
2348
2349 /*+F*************************************************************************
2350  * Function:
2351  *   scbq_insert_tail
2352  *
2353  * Description:
2354  *   Add an SCB at the tail of the list.
2355  *
2356  *-F*************************************************************************/
2357 static inline void
2358 scbq_insert_tail(volatile scb_queue_type *queue, struct aic7xxx_scb *scb)
2359 {
2360   scb->q_next = NULL;
2361   if (queue->tail != NULL)       /* Add the scb at the end of the list. */
2362     queue->tail->q_next = scb;
2363   queue->tail = scb;             /* Update the tail. */
2364   if (queue->head == NULL)       /* If list was empty, update head. */
2365     queue->head = queue->tail;
2366 }
2367
2368 /*+F*************************************************************************
2369  * Function:
2370  *   aic7xxx_match_scb
2371  *
2372  * Description:
2373  *   Checks to see if an scb matches the target/channel as specified.
2374  *   If target is ALL_TARGETS (-1), then we're looking for any device
2375  *   on the specified channel; this happens when a channel is going
2376  *   to be reset and all devices on that channel must be aborted.
2377  *-F*************************************************************************/
2378 static int
2379 aic7xxx_match_scb(struct aic7xxx_host *p, struct aic7xxx_scb *scb,
2380     int target, int channel, int lun, unsigned char tag)
2381 {
2382   int targ = (scb->hscb->target_channel_lun >> 4) & 0x0F;
2383   int chan = (scb->hscb->target_channel_lun >> 3) & 0x01;
2384   int slun = scb->hscb->target_channel_lun & 0x07;
2385   int match;
2386
2387   match = ((chan == channel) || (channel == ALL_CHANNELS));
2388   if (match != 0)
2389     match = ((targ == target) || (target == ALL_TARGETS));
2390   if (match != 0)
2391     match = ((lun == slun) || (lun == ALL_LUNS));
2392   if (match != 0)
2393     match = ((tag == scb->hscb->tag) || (tag == SCB_LIST_NULL));
2394
2395   return (match);
2396 }
2397
2398 /*+F*************************************************************************
2399  * Function:
2400  *   aic7xxx_add_curscb_to_free_list
2401  *
2402  * Description:
2403  *   Adds the current scb (in SCBPTR) to the list of free SCBs.
2404  *-F*************************************************************************/
2405 static void
2406 aic7xxx_add_curscb_to_free_list(struct aic7xxx_host *p)
2407 {
2408   /*
2409    * Invalidate the tag so that aic7xxx_find_scb doesn't think
2410    * it's active
2411    */
2412   aic_outb(p, SCB_LIST_NULL, SCB_TAG);
2413   aic_outb(p, 0, SCB_CONTROL);
2414
2415   aic_outb(p, aic_inb(p, FREE_SCBH), SCB_NEXT);
2416   aic_outb(p, aic_inb(p, SCBPTR), FREE_SCBH);
2417 }
2418
2419 /*+F*************************************************************************
2420  * Function:
2421  *   aic7xxx_rem_scb_from_disc_list
2422  *
2423  * Description:
2424  *   Removes the current SCB from the disconnected list and adds it
2425  *   to the free list.
2426  *-F*************************************************************************/
2427 static unsigned char
2428 aic7xxx_rem_scb_from_disc_list(struct aic7xxx_host *p, unsigned char scbptr,
2429                                unsigned char prev)
2430 {
2431   unsigned char next;
2432
2433   aic_outb(p, scbptr, SCBPTR);
2434   next = aic_inb(p, SCB_NEXT);
2435   aic7xxx_add_curscb_to_free_list(p);
2436
2437   if (prev != SCB_LIST_NULL)
2438   {
2439     aic_outb(p, prev, SCBPTR);
2440     aic_outb(p, next, SCB_NEXT);
2441   }
2442   else
2443   {
2444     aic_outb(p, next, DISCONNECTED_SCBH);
2445   }
2446
2447   return next;
2448 }
2449
2450 /*+F*************************************************************************
2451  * Function:
2452  *   aic7xxx_busy_target
2453  *
2454  * Description:
2455  *   Set the specified target busy.
2456  *-F*************************************************************************/
2457 static inline void
2458 aic7xxx_busy_target(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
2459 {
2460   p->untagged_scbs[scb->hscb->target_channel_lun] = scb->hscb->tag;
2461 }
2462
2463 /*+F*************************************************************************
2464  * Function:
2465  *   aic7xxx_index_busy_target
2466  *
2467  * Description:
2468  *   Returns the index of the busy target, and optionally sets the
2469  *   target inactive.
2470  *-F*************************************************************************/
2471 static inline unsigned char
2472 aic7xxx_index_busy_target(struct aic7xxx_host *p, unsigned char tcl,
2473     int unbusy)
2474 {
2475   unsigned char busy_scbid;
2476
2477   busy_scbid = p->untagged_scbs[tcl];
2478   if (unbusy)
2479   {
2480     p->untagged_scbs[tcl] = SCB_LIST_NULL;
2481   }
2482   return (busy_scbid);
2483 }
2484
2485 /*+F*************************************************************************
2486  * Function:
2487  *   aic7xxx_find_scb
2488  *
2489  * Description:
2490  *   Look through the SCB array of the card and attempt to find the
2491  *   hardware SCB that corresponds to the passed in SCB.  Return
2492  *   SCB_LIST_NULL if unsuccessful.  This routine assumes that the
2493  *   card is already paused.
2494  *-F*************************************************************************/
2495 static unsigned char
2496 aic7xxx_find_scb(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
2497 {
2498   unsigned char saved_scbptr;
2499   unsigned char curindex;
2500
2501   saved_scbptr = aic_inb(p, SCBPTR);
2502   curindex = 0;
2503   for (curindex = 0; curindex < p->scb_data->maxhscbs; curindex++)
2504   {
2505     aic_outb(p, curindex, SCBPTR);
2506     if (aic_inb(p, SCB_TAG) == scb->hscb->tag)
2507     {
2508       break;
2509     }
2510   }
2511   aic_outb(p, saved_scbptr, SCBPTR);
2512   if (curindex >= p->scb_data->maxhscbs)
2513   {
2514     curindex = SCB_LIST_NULL;
2515   }
2516
2517   return (curindex);
2518 }
2519
2520 /*+F*************************************************************************
2521  * Function:
2522  *   aic7xxx_allocate_scb
2523  *
2524  * Description:
2525  *   Get an SCB from the free list or by allocating a new one.
2526  *-F*************************************************************************/
2527 static int
2528 aic7xxx_allocate_scb(struct aic7xxx_host *p)
2529 {
2530   struct aic7xxx_scb   *scbp = NULL;
2531   int scb_size = (sizeof (struct hw_scatterlist) * AIC7XXX_MAX_SG) + 12 + 6;
2532   int i;
2533   int step = PAGE_SIZE / 1024;
2534   unsigned long scb_count = 0;
2535   struct hw_scatterlist *hsgp;
2536   struct aic7xxx_scb *scb_ap;
2537   struct aic7xxx_scb_dma *scb_dma;
2538   unsigned char *bufs;
2539
2540   if (p->scb_data->numscbs < p->scb_data->maxscbs)
2541   {
2542     /*
2543      * Calculate the optimal number of SCBs to allocate.
2544      *
2545      * NOTE: This formula works because the sizeof(sg_array) is always
2546      * 1024.  Therefore, scb_size * i would always be > PAGE_SIZE *
2547      * (i/step).  The (i-1) allows the left hand side of the equation
2548      * to grow into the right hand side to a point of near perfect
2549      * efficiency since scb_size * (i -1) is growing slightly faster
2550      * than the right hand side.  If the number of SG array elements
2551      * is changed, this function may not be near so efficient any more.
2552      *
2553      * Since the DMA'able buffers are now allocated in a separate
2554      * chunk this algorithm has been modified to match.  The '12'
2555      * and '6' factors in scb_size are for the DMA'able command byte
2556      * and sensebuffers respectively.  -DaveM
2557      */
2558     for ( i=step;; i *= 2 )
2559     {
2560       if ( (scb_size * (i-1)) >= ( (PAGE_SIZE * (i/step)) - 64 ) )
2561       {
2562         i /= 2;
2563         break;
2564       }
2565     }
2566     scb_count = min( (i-1), p->scb_data->maxscbs - p->scb_data->numscbs);
2567     scb_ap = kmalloc(sizeof (struct aic7xxx_scb) * scb_count
2568                                            + sizeof(struct aic7xxx_scb_dma), GFP_ATOMIC);
2569     if (scb_ap == NULL)
2570       return(0);
2571     scb_dma = (struct aic7xxx_scb_dma *)&scb_ap[scb_count];
2572     hsgp = (struct hw_scatterlist *)
2573       pci_alloc_consistent(p->pdev, scb_size * scb_count,
2574                            &scb_dma->dma_address);
2575     if (hsgp == NULL)
2576     {
2577       kfree(scb_ap);
2578       return(0);
2579     }
2580     bufs = (unsigned char *)&hsgp[scb_count * AIC7XXX_MAX_SG];
2581 #ifdef AIC7XXX_VERBOSE_DEBUGGING
2582     if (aic7xxx_verbose > 0xffff)
2583     {
2584       if (p->scb_data->numscbs == 0)
2585         printk(INFO_LEAD "Allocating initial %ld SCB structures.\n",
2586           p->host_no, -1, -1, -1, scb_count);
2587       else
2588         printk(INFO_LEAD "Allocating %ld additional SCB structures.\n",
2589           p->host_no, -1, -1, -1, scb_count);
2590     }
2591 #endif
2592     memset(scb_ap, 0, sizeof (struct aic7xxx_scb) * scb_count);
2593     scb_dma->dma_offset = (unsigned long)scb_dma->dma_address
2594                           - (unsigned long)hsgp;
2595     scb_dma->dma_len = scb_size * scb_count;
2596     for (i=0; i < scb_count; i++)
2597     {
2598       scbp = &scb_ap[i];
2599       scbp->hscb = &p->scb_data->hscbs[p->scb_data->numscbs];
2600       scbp->sg_list = &hsgp[i * AIC7XXX_MAX_SG];
2601       scbp->sense_cmd = bufs;
2602       scbp->cmnd = bufs + 6;
2603       bufs += 12 + 6;
2604       scbp->scb_dma = scb_dma;
2605       memset(scbp->hscb, 0, sizeof(struct aic7xxx_hwscb));
2606       scbp->hscb->tag = p->scb_data->numscbs;
2607       /*
2608        * Place in the scb array; never is removed
2609        */
2610       p->scb_data->scb_array[p->scb_data->numscbs++] = scbp;
2611       scbq_insert_tail(&p->scb_data->free_scbs, scbp);
2612     }
2613     scbp->kmalloc_ptr = scb_ap;
2614   }
2615   return(scb_count);
2616 }
2617
2618 /*+F*************************************************************************
2619  * Function:
2620  *   aic7xxx_queue_cmd_complete
2621  *
2622  * Description:
2623  *   Due to race conditions present in the SCSI subsystem, it is easier
2624  *   to queue completed commands, then call scsi_done() on them when
2625  *   we're finished.  This function queues the completed commands.
2626  *-F*************************************************************************/
2627 static void
2628 aic7xxx_queue_cmd_complete(struct aic7xxx_host *p, struct scsi_cmnd *cmd)
2629 {
2630   aic7xxx_position(cmd) = SCB_LIST_NULL;
2631   cmd->host_scribble = (char *)p->completeq.head;
2632   p->completeq.head = cmd;
2633 }
2634
2635 /*+F*************************************************************************
2636  * Function:
2637  *   aic7xxx_done_cmds_complete
2638  *
2639  * Description:
2640  *   Process the completed command queue.
2641  *-F*************************************************************************/
2642 static void aic7xxx_done_cmds_complete(struct aic7xxx_host *p)
2643 {
2644         struct scsi_cmnd *cmd;
2645
2646         while (p->completeq.head != NULL) {
2647                 cmd = p->completeq.head;
2648                 p->completeq.head = (struct scsi_cmnd *) cmd->host_scribble;
2649                 cmd->host_scribble = NULL;
2650                 cmd->scsi_done(cmd);
2651         }
2652 }
2653
2654 /*+F*************************************************************************
2655  * Function:
2656  *   aic7xxx_free_scb
2657  *
2658  * Description:
2659  *   Free the scb and insert into the free scb list.
2660  *-F*************************************************************************/
2661 static void
2662 aic7xxx_free_scb(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
2663 {
2664
2665   scb->flags = SCB_FREE;
2666   scb->cmd = NULL;
2667   scb->sg_count = 0;
2668   scb->sg_length = 0;
2669   scb->tag_action = 0;
2670   scb->hscb->control = 0;
2671   scb->hscb->target_status = 0;
2672   scb->hscb->target_channel_lun = SCB_LIST_NULL;
2673
2674   scbq_insert_head(&p->scb_data->free_scbs, scb);
2675 }
2676
2677 /*+F*************************************************************************
2678  * Function:
2679  *   aic7xxx_done
2680  *
2681  * Description:
2682  *   Calls the higher level scsi done function and frees the scb.
2683  *-F*************************************************************************/
2684 static void
2685 aic7xxx_done(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
2686 {
2687         struct scsi_cmnd *cmd = scb->cmd;
2688         struct aic_dev_data *aic_dev = cmd->device->hostdata;
2689         int tindex = TARGET_INDEX(cmd);
2690         struct aic7xxx_scb *scbp;
2691         unsigned char queue_depth;
2692
2693   if (cmd->use_sg > 1)
2694   {
2695     struct scatterlist *sg;
2696
2697     sg = (struct scatterlist *)cmd->request_buffer;
2698     pci_unmap_sg(p->pdev, sg, cmd->use_sg, cmd->sc_data_direction);
2699   }
2700   else if (cmd->request_bufflen)
2701     pci_unmap_single(p->pdev, aic7xxx_mapping(cmd),
2702                      cmd->request_bufflen,
2703                      cmd->sc_data_direction);
2704   if (scb->flags & SCB_SENSE)
2705   {
2706     pci_unmap_single(p->pdev,
2707                      le32_to_cpu(scb->sg_list[0].address),
2708                      sizeof(cmd->sense_buffer),
2709                      PCI_DMA_FROMDEVICE);
2710   }
2711   if (scb->flags & SCB_RECOVERY_SCB)
2712   {
2713     p->flags &= ~AHC_ABORT_PENDING;
2714   }
2715   if (scb->flags & (SCB_RESET|SCB_ABORT))
2716   {
2717     cmd->result |= (DID_RESET << 16);
2718   }
2719
2720   if ((scb->flags & SCB_MSGOUT_BITS) != 0)
2721   {
2722     unsigned short mask;
2723     int message_error = FALSE;
2724
2725     mask = 0x01 << tindex;
2726  
2727     /*
2728      * Check to see if we get an invalid message or a message error
2729      * after failing to negotiate a wide or sync transfer message.
2730      */
2731     if ((scb->flags & SCB_SENSE) && 
2732           ((scb->cmd->sense_buffer[12] == 0x43) ||  /* INVALID_MESSAGE */
2733           (scb->cmd->sense_buffer[12] == 0x49))) /* MESSAGE_ERROR  */
2734     {
2735       message_error = TRUE;
2736     }
2737
2738     if (scb->flags & SCB_MSGOUT_WDTR)
2739     {
2740       if (message_error)
2741       {
2742         if ( (aic7xxx_verbose & VERBOSE_NEGOTIATION2) &&
2743              (aic_dev->flags & DEVICE_PRINT_DTR) )
2744         {
2745           printk(INFO_LEAD "Device failed to complete Wide Negotiation "
2746             "processing and\n", p->host_no, CTL_OF_SCB(scb));
2747           printk(INFO_LEAD "returned a sense error code for invalid message, "
2748             "disabling future\n", p->host_no, CTL_OF_SCB(scb));
2749           printk(INFO_LEAD "Wide negotiation to this device.\n", p->host_no,
2750             CTL_OF_SCB(scb));
2751         }
2752         aic_dev->needwdtr = aic_dev->needwdtr_copy = 0;
2753       }
2754     }
2755     if (scb->flags & SCB_MSGOUT_SDTR)
2756     {
2757       if (message_error)
2758       {
2759         if ( (aic7xxx_verbose & VERBOSE_NEGOTIATION2) &&
2760              (aic_dev->flags & DEVICE_PRINT_DTR) )
2761         {
2762           printk(INFO_LEAD "Device failed to complete Sync Negotiation "
2763             "processing and\n", p->host_no, CTL_OF_SCB(scb));
2764           printk(INFO_LEAD "returned a sense error code for invalid message, "
2765             "disabling future\n", p->host_no, CTL_OF_SCB(scb));
2766           printk(INFO_LEAD "Sync negotiation to this device.\n", p->host_no,
2767             CTL_OF_SCB(scb));
2768           aic_dev->flags &= ~DEVICE_PRINT_DTR;
2769         }
2770         aic_dev->needsdtr = aic_dev->needsdtr_copy = 0;
2771       }
2772     }
2773     if (scb->flags & SCB_MSGOUT_PPR)
2774     {
2775       if(message_error)
2776       {
2777         if ( (aic7xxx_verbose & VERBOSE_NEGOTIATION2) &&
2778              (aic_dev->flags & DEVICE_PRINT_DTR) )
2779         {
2780           printk(INFO_LEAD "Device failed to complete Parallel Protocol "
2781             "Request processing and\n", p->host_no, CTL_OF_SCB(scb));
2782           printk(INFO_LEAD "returned a sense error code for invalid message, "
2783             "disabling future\n", p->host_no, CTL_OF_SCB(scb));
2784           printk(INFO_LEAD "Parallel Protocol Request negotiation to this "
2785             "device.\n", p->host_no, CTL_OF_SCB(scb));
2786         }
2787         /*
2788          * Disable PPR negotiation and revert back to WDTR and SDTR setup
2789          */
2790         aic_dev->needppr = aic_dev->needppr_copy = 0;
2791         aic_dev->needsdtr = aic_dev->needsdtr_copy = 1;
2792         aic_dev->needwdtr = aic_dev->needwdtr_copy = 1;
2793       }
2794     }
2795   }
2796
2797   queue_depth = aic_dev->temp_q_depth;
2798   if (queue_depth >= aic_dev->active_cmds)
2799   {
2800     scbp = scbq_remove_head(&aic_dev->delayed_scbs);
2801     if (scbp)
2802     {
2803       if (queue_depth == 1)
2804       {
2805         /*
2806          * Give extra preference to untagged devices, such as CD-R devices
2807          * This makes it more likely that a drive *won't* stuff up while
2808          * waiting on data at a critical time, such as CD-R writing and
2809          * audio CD ripping operations.  Should also benefit tape drives.
2810          */
2811         scbq_insert_head(&p->waiting_scbs, scbp);
2812       }
2813       else
2814       {
2815         scbq_insert_tail(&p->waiting_scbs, scbp);
2816       }
2817 #ifdef AIC7XXX_VERBOSE_DEBUGGING
2818       if (aic7xxx_verbose > 0xffff)
2819         printk(INFO_LEAD "Moving SCB from delayed to waiting queue.\n",
2820                p->host_no, CTL_OF_SCB(scbp));
2821 #endif
2822       if (queue_depth > aic_dev->active_cmds)
2823       {
2824         scbp = scbq_remove_head(&aic_dev->delayed_scbs);
2825         if (scbp)
2826           scbq_insert_tail(&p->waiting_scbs, scbp);
2827       }
2828     }
2829   }
2830   if (!(scb->tag_action))
2831   {
2832     aic7xxx_index_busy_target(p, scb->hscb->target_channel_lun,
2833                               /* unbusy */ TRUE);
2834     if (cmd->device->simple_tags)
2835     {
2836       aic_dev->temp_q_depth = aic_dev->max_q_depth;
2837     }
2838   }
2839   if(scb->flags & SCB_DTR_SCB)
2840   {
2841     aic_dev->dtr_pending = 0;
2842   }
2843   aic_dev->active_cmds--;
2844   p->activescbs--;
2845
2846   if ((scb->sg_length >= 512) && (((cmd->result >> 16) & 0xf) == DID_OK))
2847   {
2848     long *ptr;
2849     int x, i;
2850
2851
2852     if (rq_data_dir(cmd->request) == WRITE)
2853     {
2854       aic_dev->w_total++;
2855       ptr = aic_dev->w_bins;
2856     }
2857     else
2858     {
2859       aic_dev->r_total++;
2860       ptr = aic_dev->r_bins;
2861     }
2862     if(cmd->device->simple_tags && cmd->request->cmd_flags & REQ_HARDBARRIER)
2863     {
2864       aic_dev->barrier_total++;
2865       if(scb->tag_action == MSG_ORDERED_Q_TAG)
2866         aic_dev->ordered_total++;
2867     }
2868     x = scb->sg_length;
2869     x >>= 10;
2870     for(i=0; i<6; i++)
2871     {
2872       x >>= 2;
2873       if(!x) {
2874         ptr[i]++;
2875         break;
2876       }
2877     }
2878     if(i == 6 && x)
2879       ptr[5]++;
2880   }
2881   aic7xxx_free_scb(p, scb);
2882   aic7xxx_queue_cmd_complete(p, cmd);
2883
2884 }
2885
2886 /*+F*************************************************************************
2887  * Function:
2888  *   aic7xxx_run_done_queue
2889  *
2890  * Description:
2891  *   Calls the aic7xxx_done() for the scsi_cmnd of each scb in the
2892  *   aborted list, and adds each scb to the free list.  If complete
2893  *   is TRUE, we also process the commands complete list.
2894  *-F*************************************************************************/
2895 static void
2896 aic7xxx_run_done_queue(struct aic7xxx_host *p, /*complete*/ int complete)
2897 {
2898   struct aic7xxx_scb *scb;
2899   int i, found = 0;
2900
2901   for (i = 0; i < p->scb_data->numscbs; i++)
2902   {
2903     scb = p->scb_data->scb_array[i];
2904     if (scb->flags & SCB_QUEUED_FOR_DONE)
2905     {
2906       if (scb->flags & SCB_QUEUE_FULL)
2907       {
2908         scb->cmd->result = QUEUE_FULL << 1;
2909       }
2910       else
2911       {
2912         if (aic7xxx_verbose & (VERBOSE_ABORT_PROCESS | VERBOSE_RESET_PROCESS))
2913           printk(INFO_LEAD "Aborting scb %d\n",
2914                p->host_no, CTL_OF_SCB(scb), scb->hscb->tag);
2915         /*
2916          * Clear any residual information since the normal aic7xxx_done() path
2917          * doesn't touch the residuals.
2918          */
2919         scb->hscb->residual_SG_segment_count = 0;
2920         scb->hscb->residual_data_count[0] = 0;
2921         scb->hscb->residual_data_count[1] = 0;
2922         scb->hscb->residual_data_count[2] = 0;
2923       }
2924       found++;
2925       aic7xxx_done(p, scb);
2926     }
2927   }
2928   if (aic7xxx_verbose & (VERBOSE_ABORT_RETURN | VERBOSE_RESET_RETURN))
2929   {
2930     printk(INFO_LEAD "%d commands found and queued for "
2931         "completion.\n", p->host_no, -1, -1, -1, found);
2932   }
2933   if (complete)
2934   {
2935     aic7xxx_done_cmds_complete(p);
2936   }
2937 }
2938
2939 /*+F*************************************************************************
2940  * Function:
2941  *   aic7xxx_abort_waiting_scb
2942  *
2943  * Description:
2944  *   Manipulate the waiting for selection list and return the
2945  *   scb that follows the one that we remove.
2946  *-F*************************************************************************/
2947 static unsigned char
2948 aic7xxx_abort_waiting_scb(struct aic7xxx_host *p, struct aic7xxx_scb *scb,
2949     unsigned char scbpos, unsigned char prev)
2950 {
2951   unsigned char curscb, next;
2952
2953   /*
2954    * Select the SCB we want to abort and pull the next pointer out of it.
2955    */
2956   curscb = aic_inb(p, SCBPTR);
2957   aic_outb(p, scbpos, SCBPTR);
2958   next = aic_inb(p, SCB_NEXT);
2959
2960   aic7xxx_add_curscb_to_free_list(p);
2961
2962   /*
2963    * Update the waiting list
2964    */
2965   if (prev == SCB_LIST_NULL)
2966   {
2967     /*
2968      * First in the list
2969      */
2970     aic_outb(p, next, WAITING_SCBH);
2971   }
2972   else
2973   {
2974     /*
2975      * Select the scb that pointed to us and update its next pointer.
2976      */
2977     aic_outb(p, prev, SCBPTR);
2978     aic_outb(p, next, SCB_NEXT);
2979   }
2980   /*
2981    * Point us back at the original scb position and inform the SCSI
2982    * system that the command has been aborted.
2983    */
2984   aic_outb(p, curscb, SCBPTR);
2985   return (next);
2986 }
2987
2988 /*+F*************************************************************************
2989  * Function:
2990  *   aic7xxx_search_qinfifo
2991  *
2992  * Description:
2993  *   Search the queue-in FIFO for matching SCBs and conditionally
2994  *   requeue.  Returns the number of matching SCBs.
2995  *-F*************************************************************************/
2996 static int
2997 aic7xxx_search_qinfifo(struct aic7xxx_host *p, int target, int channel,
2998     int lun, unsigned char tag, int flags, int requeue,
2999     volatile scb_queue_type *queue)
3000 {
3001   int      found;
3002   unsigned char qinpos, qintail;
3003   struct aic7xxx_scb *scbp;
3004
3005   found = 0;
3006   qinpos = aic_inb(p, QINPOS);
3007   qintail = p->qinfifonext;
3008
3009   p->qinfifonext = qinpos;
3010
3011   while (qinpos != qintail)
3012   {
3013     scbp = p->scb_data->scb_array[p->qinfifo[qinpos++]];
3014     if (aic7xxx_match_scb(p, scbp, target, channel, lun, tag))
3015     {
3016        /*
3017         * We found an scb that needs to be removed.
3018         */
3019        if (requeue && (queue != NULL))
3020        {
3021          if (scbp->flags & SCB_WAITINGQ)
3022          {
3023            scbq_remove(queue, scbp);
3024            scbq_remove(&p->waiting_scbs, scbp);
3025            scbq_remove(&AIC_DEV(scbp->cmd)->delayed_scbs, scbp);
3026            AIC_DEV(scbp->cmd)->active_cmds++;
3027            p->activescbs++;
3028          }
3029          scbq_insert_tail(queue, scbp);
3030          AIC_DEV(scbp->cmd)->active_cmds--;
3031          p->activescbs--;
3032          scbp->flags |= SCB_WAITINGQ;
3033          if ( !(scbp->tag_action & TAG_ENB) )
3034          {
3035            aic7xxx_index_busy_target(p, scbp->hscb->target_channel_lun,
3036              TRUE);
3037          }
3038        }
3039        else if (requeue)
3040        {
3041          p->qinfifo[p->qinfifonext++] = scbp->hscb->tag;
3042        }
3043        else
3044        {
3045         /*
3046          * Preserve any SCB_RECOVERY_SCB flags on this scb then set the
3047          * flags we were called with, presumeably so aic7xxx_run_done_queue
3048          * can find this scb
3049          */
3050          scbp->flags = flags | (scbp->flags & SCB_RECOVERY_SCB);
3051          if (aic7xxx_index_busy_target(p, scbp->hscb->target_channel_lun,
3052                                        FALSE) == scbp->hscb->tag)
3053          {
3054            aic7xxx_index_busy_target(p, scbp->hscb->target_channel_lun,
3055              TRUE);
3056          }
3057        }
3058        found++;
3059     }
3060     else
3061     {
3062       p->qinfifo[p->qinfifonext++] = scbp->hscb->tag;
3063     }
3064   }
3065   /*
3066    * Now that we've done the work, clear out any left over commands in the
3067    * qinfifo and update the KERNEL_QINPOS down on the card.
3068    *
3069    *  NOTE: This routine expect the sequencer to already be paused when
3070    *        it is run....make sure it's that way!
3071    */
3072   qinpos = p->qinfifonext;
3073   while(qinpos != qintail)
3074   {
3075     p->qinfifo[qinpos++] = SCB_LIST_NULL;
3076   }
3077   if (p->features & AHC_QUEUE_REGS)
3078     aic_outb(p, p->qinfifonext, HNSCB_QOFF);
3079   else
3080     aic_outb(p, p->qinfifonext, KERNEL_QINPOS);
3081
3082   return (found);
3083 }
3084
3085 /*+F*************************************************************************
3086  * Function:
3087  *   aic7xxx_scb_on_qoutfifo
3088  *
3089  * Description:
3090  *   Is the scb that was passed to us currently on the qoutfifo?
3091  *-F*************************************************************************/
3092 static int
3093 aic7xxx_scb_on_qoutfifo(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
3094 {
3095   int i=0;
3096
3097   while(p->qoutfifo[(p->qoutfifonext + i) & 0xff ] != SCB_LIST_NULL)
3098   {
3099     if(p->qoutfifo[(p->qoutfifonext + i) & 0xff ] == scb->hscb->tag)
3100       return TRUE;
3101     else
3102       i++;
3103   }
3104   return FALSE;
3105 }
3106
3107
3108 /*+F*************************************************************************
3109  * Function:
3110  *   aic7xxx_reset_device
3111  *
3112  * Description:
3113  *   The device at the given target/channel has been reset.  Abort
3114  *   all active and queued scbs for that target/channel.  This function
3115  *   need not worry about linked next pointers because if was a MSG_ABORT_TAG
3116  *   then we had a tagged command (no linked next), if it was MSG_ABORT or
3117  *   MSG_BUS_DEV_RESET then the device won't know about any commands any more
3118  *   and no busy commands will exist, and if it was a bus reset, then nothing
3119  *   knows about any linked next commands any more.  In all cases, we don't
3120  *   need to worry about the linked next or busy scb, we just need to clear
3121  *   them.
3122  *-F*************************************************************************/
3123 static void
3124 aic7xxx_reset_device(struct aic7xxx_host *p, int target, int channel,
3125                      int lun, unsigned char tag)
3126 {
3127   struct aic7xxx_scb *scbp, *prev_scbp;
3128   struct scsi_device *sd;
3129   unsigned char active_scb, tcl, scb_tag;
3130   int i = 0, init_lists = FALSE;
3131   struct aic_dev_data *aic_dev;
3132
3133   /*
3134    * Restore this when we're done
3135    */
3136   active_scb = aic_inb(p, SCBPTR);
3137   scb_tag = aic_inb(p, SCB_TAG);
3138
3139   if (aic7xxx_verbose & (VERBOSE_RESET_PROCESS | VERBOSE_ABORT_PROCESS))
3140   {
3141     printk(INFO_LEAD "Reset device, hardware_scb %d,\n",
3142          p->host_no, channel, target, lun, active_scb);
3143     printk(INFO_LEAD "Current scb %d, SEQADDR 0x%x, LASTPHASE "
3144            "0x%x\n",
3145          p->host_no, channel, target, lun, scb_tag,
3146          aic_inb(p, SEQADDR0) | (aic_inb(p, SEQADDR1) << 8),
3147          aic_inb(p, LASTPHASE));
3148     printk(INFO_LEAD "SG_CACHEPTR 0x%x, SG_COUNT %d, SCSISIGI 0x%x\n",
3149          p->host_no, channel, target, lun,
3150          (p->features & AHC_ULTRA2) ?  aic_inb(p, SG_CACHEPTR) : 0,
3151          aic_inb(p, SG_COUNT), aic_inb(p, SCSISIGI));
3152     printk(INFO_LEAD "SSTAT0 0x%x, SSTAT1 0x%x, SSTAT2 0x%x\n",
3153          p->host_no, channel, target, lun, aic_inb(p, SSTAT0),
3154          aic_inb(p, SSTAT1), aic_inb(p, SSTAT2));
3155   }
3156
3157   /*
3158    * Deal with the busy target and linked next issues.
3159    */
3160   list_for_each_entry(aic_dev, &p->aic_devs, list)
3161   {
3162     if (aic7xxx_verbose & (VERBOSE_RESET_PROCESS | VERBOSE_ABORT_PROCESS))
3163       printk(INFO_LEAD "processing aic_dev %p\n", p->host_no, channel, target,
3164                     lun, aic_dev);
3165     sd = aic_dev->SDptr;
3166
3167     if((target != ALL_TARGETS && target != sd->id) ||
3168        (channel != ALL_CHANNELS && channel != sd->channel))
3169       continue;
3170     if (aic7xxx_verbose & (VERBOSE_ABORT_PROCESS | VERBOSE_RESET_PROCESS))
3171         printk(INFO_LEAD "Cleaning up status information "
3172           "and delayed_scbs.\n", p->host_no, sd->channel, sd->id, sd->lun);
3173     aic_dev->flags &= ~BUS_DEVICE_RESET_PENDING;
3174     if ( tag == SCB_LIST_NULL )
3175     {
3176       aic_dev->dtr_pending = 0;
3177       aic_dev->needppr = aic_dev->needppr_copy;
3178       aic_dev->needsdtr = aic_dev->needsdtr_copy;
3179       aic_dev->needwdtr = aic_dev->needwdtr_copy;
3180       aic_dev->flags = DEVICE_PRINT_DTR;
3181       aic_dev->temp_q_depth = aic_dev->max_q_depth;
3182     }
3183     tcl = (sd->id << 4) | (sd->channel << 3) | sd->lun;
3184     if ( (aic7xxx_index_busy_target(p, tcl, FALSE) == tag) ||
3185          (tag == SCB_LIST_NULL) )
3186       aic7xxx_index_busy_target(p, tcl, /* unbusy */ TRUE);
3187     prev_scbp = NULL; 
3188     scbp = aic_dev->delayed_scbs.head;
3189     while (scbp != NULL)
3190     {
3191       prev_scbp = scbp;
3192       scbp = scbp->q_next;
3193       if (aic7xxx_match_scb(p, prev_scbp, target, channel, lun, tag))
3194       {
3195         scbq_remove(&aic_dev->delayed_scbs, prev_scbp);
3196         if (prev_scbp->flags & SCB_WAITINGQ)
3197         {
3198           aic_dev->active_cmds++;
3199           p->activescbs++;
3200         }
3201         prev_scbp->flags &= ~(SCB_ACTIVE | SCB_WAITINGQ);
3202         prev_scbp->flags |= SCB_RESET | SCB_QUEUED_FOR_DONE;
3203       }
3204     }
3205   }
3206
3207   if (aic7xxx_verbose & (VERBOSE_ABORT_PROCESS | VERBOSE_RESET_PROCESS))
3208     printk(INFO_LEAD "Cleaning QINFIFO.\n", p->host_no, channel, target, lun );
3209   aic7xxx_search_qinfifo(p, target, channel, lun, tag,
3210       SCB_RESET | SCB_QUEUED_FOR_DONE, /* requeue */ FALSE, NULL);
3211
3212 /*
3213  *  Search the waiting_scbs queue for matches, this catches any SCB_QUEUED
3214  *  ABORT/RESET commands.
3215  */
3216   if (aic7xxx_verbose & (VERBOSE_ABORT_PROCESS | VERBOSE_RESET_PROCESS))
3217     printk(INFO_LEAD "Cleaning waiting_scbs.\n", p->host_no, channel,
3218       target, lun );
3219   {
3220     struct aic7xxx_scb *scbp, *prev_scbp;
3221
3222     prev_scbp = NULL; 
3223     scbp = p->waiting_scbs.head;
3224     while (scbp != NULL)
3225     {
3226       prev_scbp = scbp;
3227       scbp = scbp->q_next;
3228       if (aic7xxx_match_scb(p, prev_scbp, target, channel, lun, tag))
3229       {
3230         scbq_remove(&p->waiting_scbs, prev_scbp);
3231         if (prev_scbp->flags & SCB_WAITINGQ)
3232         {
3233           AIC_DEV(prev_scbp->cmd)->active_cmds++;
3234           p->activescbs++;
3235         }
3236         prev_scbp->flags &= ~(SCB_ACTIVE | SCB_WAITINGQ);
3237         prev_scbp->flags |= SCB_RESET | SCB_QUEUED_FOR_DONE;
3238       }
3239     }
3240   }
3241
3242
3243   /*
3244    * Search waiting for selection list.
3245    */
3246   if (aic7xxx_verbose & (VERBOSE_ABORT_PROCESS | VERBOSE_RESET_PROCESS))
3247     printk(INFO_LEAD "Cleaning waiting for selection "
3248       "list.\n", p->host_no, channel, target, lun);
3249   {
3250     unsigned char next, prev, scb_index;
3251
3252     next = aic_inb(p, WAITING_SCBH);  /* Start at head of list. */
3253     prev = SCB_LIST_NULL;
3254     while (next != SCB_LIST_NULL)
3255     {
3256       aic_outb(p, next, SCBPTR);
3257       scb_index = aic_inb(p, SCB_TAG);
3258       if (scb_index >= p->scb_data->numscbs)
3259       {
3260        /*
3261         * No aic7xxx_verbose check here.....we want to see this since it
3262         * means either the kernel driver or the sequencer screwed things up
3263         */
3264         printk(WARN_LEAD "Waiting List inconsistency; SCB index=%d, "
3265           "numscbs=%d\n", p->host_no, channel, target, lun, scb_index,
3266           p->scb_data->numscbs);
3267         next = aic_inb(p, SCB_NEXT);
3268         aic7xxx_add_curscb_to_free_list(p);
3269       }
3270       else
3271       {
3272         scbp = p->scb_data->scb_array[scb_index];
3273         if (aic7xxx_match_scb(p, scbp, target, channel, lun, tag))
3274         {
3275           next = aic7xxx_abort_waiting_scb(p, scbp, next, prev);
3276           if (scbp->flags & SCB_WAITINGQ)
3277           {
3278             AIC_DEV(scbp->cmd)->active_cmds++;
3279             p->activescbs++;
3280           }
3281           scbp->flags &= ~(SCB_ACTIVE | SCB_WAITINGQ);
3282           scbp->flags |= SCB_RESET | SCB_QUEUED_FOR_DONE;
3283           if (prev == SCB_LIST_NULL)
3284           {
3285             /*
3286              * This is either the first scb on the waiting list, or we
3287              * have already yanked the first and haven't left any behind.
3288              * Either way, we need to turn off the selection hardware if
3289              * it isn't already off.
3290              */
3291             aic_outb(p, aic_inb(p, SCSISEQ) & ~ENSELO, SCSISEQ);
3292             aic_outb(p, CLRSELTIMEO, CLRSINT1);
3293           }
3294         }
3295         else
3296         {
3297           prev = next;
3298           next = aic_inb(p, SCB_NEXT);
3299         }
3300       }
3301     }
3302   }
3303
3304   /*
3305    * Go through disconnected list and remove any entries we have queued
3306    * for completion, zeroing their control byte too.
3307    */
3308   if (aic7xxx_verbose & (VERBOSE_ABORT_PROCESS | VERBOSE_RESET_PROCESS))
3309     printk(INFO_LEAD "Cleaning disconnected scbs "
3310       "list.\n", p->host_no, channel, target, lun);
3311   if (p->flags & AHC_PAGESCBS)
3312   {
3313     unsigned char next, prev, scb_index;
3314
3315     next = aic_inb(p, DISCONNECTED_SCBH);
3316     prev = SCB_LIST_NULL;
3317     while (next != SCB_LIST_NULL)
3318     {
3319       aic_outb(p, next, SCBPTR);
3320       scb_index = aic_inb(p, SCB_TAG);
3321       if (scb_index > p->scb_data->numscbs)
3322       {
3323         printk(WARN_LEAD "Disconnected List inconsistency; SCB index=%d, "
3324           "numscbs=%d\n", p->host_no, channel, target, lun, scb_index,
3325           p->scb_data->numscbs);
3326         next = aic7xxx_rem_scb_from_disc_list(p, next, prev);
3327       }
3328       else
3329       {
3330         scbp = p->scb_data->scb_array[scb_index];
3331         if (aic7xxx_match_scb(p, scbp, target, channel, lun, tag))
3332         {
3333           next = aic7xxx_rem_scb_from_disc_list(p, next, prev);
3334           if (scbp->flags & SCB_WAITINGQ)
3335           {
3336             AIC_DEV(scbp->cmd)->active_cmds++;
3337             p->activescbs++;
3338           }
3339           scbp->flags &= ~(SCB_ACTIVE | SCB_WAITINGQ);
3340           scbp->flags |= SCB_RESET | SCB_QUEUED_FOR_DONE;
3341           scbp->hscb->control = 0;
3342         }
3343         else
3344         {
3345           prev = next;
3346           next = aic_inb(p, SCB_NEXT);
3347         }
3348       }
3349     }
3350   }
3351
3352   /*
3353    * Walk the free list making sure no entries on the free list have
3354    * a valid SCB_TAG value or SCB_CONTROL byte.
3355    */
3356   if (p->flags & AHC_PAGESCBS)
3357   {
3358     unsigned char next;
3359
3360     next = aic_inb(p, FREE_SCBH);
3361     while (next != SCB_LIST_NULL)
3362     {
3363       aic_outb(p, next, SCBPTR);
3364       if (aic_inb(p, SCB_TAG) < p->scb_data->numscbs)
3365       {
3366         printk(WARN_LEAD "Free list inconsistency!.\n", p->host_no, channel,
3367           target, lun);
3368         init_lists = TRUE;
3369         next = SCB_LIST_NULL;
3370       }
3371       else
3372       {
3373         aic_outb(p, SCB_LIST_NULL, SCB_TAG);
3374         aic_outb(p, 0, SCB_CONTROL);
3375         next = aic_inb(p, SCB_NEXT);
3376       }
3377     }
3378   }
3379
3380   /*
3381    * Go through the hardware SCB array looking for commands that
3382    * were active but not on any list.
3383    */
3384   if (init_lists)
3385   {
3386     aic_outb(p, SCB_LIST_NULL, FREE_SCBH);
3387     aic_outb(p, SCB_LIST_NULL, WAITING_SCBH);
3388     aic_outb(p, SCB_LIST_NULL, DISCONNECTED_SCBH);
3389   }
3390   for (i = p->scb_data->maxhscbs - 1; i >= 0; i--)
3391   {
3392     unsigned char scbid;
3393
3394     aic_outb(p, i, SCBPTR);
3395     if (init_lists)
3396     {
3397       aic_outb(p, SCB_LIST_NULL, SCB_TAG);
3398       aic_outb(p, SCB_LIST_NULL, SCB_NEXT);
3399       aic_outb(p, 0, SCB_CONTROL);
3400       aic7xxx_add_curscb_to_free_list(p);
3401     }
3402     else
3403     {
3404       scbid = aic_inb(p, SCB_TAG);
3405       if (scbid < p->scb_data->numscbs)
3406       {
3407         scbp = p->scb_data->scb_array[scbid];
3408         if (aic7xxx_match_scb(p, scbp, target, channel, lun, tag))
3409         {
3410           aic_outb(p, 0, SCB_CONTROL);
3411           aic_outb(p, SCB_LIST_NULL, SCB_TAG);
3412           aic7xxx_add_curscb_to_free_list(p);
3413         }
3414       }
3415     }
3416   }
3417
3418   /*
3419    * Go through the entire SCB array now and look for commands for
3420    * for this target that are stillactive.  These are other (most likely
3421    * tagged) commands that were disconnected when the reset occurred.
3422    * Any commands we find here we know this about, it wasn't on any queue,
3423    * it wasn't in the qinfifo, it wasn't in the disconnected or waiting
3424    * lists, so it really must have been a paged out SCB.  In that case,
3425    * we shouldn't need to bother with updating any counters, just mark
3426    * the correct flags and go on.
3427    */
3428   for (i = 0; i < p->scb_data->numscbs; i++)
3429   {
3430     scbp = p->scb_data->scb_array[i];
3431     if ((scbp->flags & SCB_ACTIVE) &&
3432         aic7xxx_match_scb(p, scbp, target, channel, lun, tag) &&
3433         !aic7xxx_scb_on_qoutfifo(p, scbp))
3434     {
3435       if (scbp->flags & SCB_WAITINGQ)
3436       {
3437         scbq_remove(&p->waiting_scbs, scbp);
3438         scbq_remove(&AIC_DEV(scbp->cmd)->delayed_scbs, scbp);
3439         AIC_DEV(scbp->cmd)->active_cmds++;
3440         p->activescbs++;
3441       }
3442       scbp->flags |= SCB_RESET | SCB_QUEUED_FOR_DONE;
3443       scbp->flags &= ~(SCB_ACTIVE | SCB_WAITINGQ);
3444     }
3445   }
3446
3447   aic_outb(p, active_scb, SCBPTR);
3448 }
3449
3450
3451 /*+F*************************************************************************
3452  * Function:
3453  *   aic7xxx_clear_intstat
3454  *
3455  * Description:
3456  *   Clears the interrupt status.
3457  *-F*************************************************************************/
3458 static void
3459 aic7xxx_clear_intstat(struct aic7xxx_host *p)
3460 {
3461   /* Clear any interrupt conditions this may have caused. */
3462   aic_outb(p, CLRSELDO | CLRSELDI | CLRSELINGO, CLRSINT0);
3463   aic_outb(p, CLRSELTIMEO | CLRATNO | CLRSCSIRSTI | CLRBUSFREE | CLRSCSIPERR |
3464        CLRPHASECHG | CLRREQINIT, CLRSINT1);
3465   aic_outb(p, CLRSCSIINT | CLRSEQINT | CLRBRKADRINT | CLRPARERR, CLRINT);
3466 }
3467
3468 /*+F*************************************************************************
3469  * Function:
3470  *   aic7xxx_reset_current_bus
3471  *
3472  * Description:
3473  *   Reset the current SCSI bus.
3474  *-F*************************************************************************/
3475 static void
3476 aic7xxx_reset_current_bus(struct aic7xxx_host *p)
3477 {
3478
3479   /* Disable reset interrupts. */
3480   aic_outb(p, aic_inb(p, SIMODE1) & ~ENSCSIRST, SIMODE1);
3481
3482   /* Turn off the bus' current operations, after all, we shouldn't have any
3483    * valid commands left to cause a RSELI and SELO once we've tossed the
3484    * bus away with this reset, so we might as well shut down the sequencer
3485    * until the bus is restarted as oppossed to saving the current settings
3486    * and restoring them (which makes no sense to me). */
3487
3488   /* Turn on the bus reset. */
3489   aic_outb(p, aic_inb(p, SCSISEQ) | SCSIRSTO, SCSISEQ);
3490   while ( (aic_inb(p, SCSISEQ) & SCSIRSTO) == 0)
3491     mdelay(5);
3492
3493   /*
3494    * Some of the new Ultra2 chipsets need a longer delay after a chip
3495    * reset than just the init setup creates, so we have to delay here
3496    * before we go into a reset in order to make the chips happy.
3497    */
3498   if (p->features & AHC_ULTRA2)
3499     mdelay(250);
3500   else
3501     mdelay(50);
3502
3503   /* Turn off the bus reset. */
3504   aic_outb(p, 0, SCSISEQ);
3505   mdelay(10);
3506
3507   aic7xxx_clear_intstat(p);
3508   /* Re-enable reset interrupts. */
3509   aic_outb(p, aic_inb(p, SIMODE1) | ENSCSIRST, SIMODE1);
3510
3511 }
3512
3513 /*+F*************************************************************************
3514  * Function:
3515  *   aic7xxx_reset_channel
3516  *
3517  * Description:
3518  *   Reset the channel.
3519  *-F*************************************************************************/
3520 static void
3521 aic7xxx_reset_channel(struct aic7xxx_host *p, int channel, int initiate_reset)
3522 {
3523   unsigned long offset_min, offset_max;
3524   unsigned char sblkctl;
3525   int cur_channel;
3526
3527   if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
3528     printk(INFO_LEAD "Reset channel called, %s initiate reset.\n",
3529       p->host_no, channel, -1, -1, (initiate_reset==TRUE) ? "will" : "won't" );
3530
3531
3532   if (channel == 1)
3533   {
3534     offset_min = 8;
3535     offset_max = 16;
3536   }
3537   else
3538   {
3539     if (p->features & AHC_TWIN)
3540     {
3541       /* Channel A */
3542       offset_min = 0;
3543       offset_max = 8;
3544     }
3545     else
3546     {
3547       offset_min = 0;
3548       if (p->features & AHC_WIDE)
3549       {
3550         offset_max = 16;
3551       }
3552       else
3553       {
3554         offset_max = 8;
3555       }
3556     }
3557   }
3558
3559   while (offset_min < offset_max)
3560   {
3561     /*
3562      * Revert to async/narrow transfers until we renegotiate.
3563      */
3564     aic_outb(p, 0, TARG_SCSIRATE + offset_min);
3565     if (p->features & AHC_ULTRA2)
3566     {
3567       aic_outb(p, 0, TARG_OFFSET + offset_min);
3568     }
3569     offset_min++;
3570   }
3571
3572   /*
3573    * Reset the bus and unpause/restart the controller
3574    */
3575   sblkctl = aic_inb(p, SBLKCTL);
3576   if ( (p->chip & AHC_CHIPID_MASK) == AHC_AIC7770 )
3577     cur_channel = (sblkctl & SELBUSB) >> 3;
3578   else
3579     cur_channel = 0;
3580   if ( (cur_channel != channel) && (p->features & AHC_TWIN) )
3581   {
3582     /*
3583      * Case 1: Command for another bus is active
3584      */
3585     if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
3586       printk(INFO_LEAD "Stealthily resetting idle channel.\n", p->host_no,
3587         channel, -1, -1);
3588     /*
3589      * Stealthily reset the other bus without upsetting the current bus.
3590      */
3591     aic_outb(p, sblkctl ^ SELBUSB, SBLKCTL);
3592     aic_outb(p, aic_inb(p, SIMODE1) & ~ENBUSFREE, SIMODE1);
3593     if (initiate_reset)
3594     {
3595       aic7xxx_reset_current_bus(p);
3596     }
3597     aic_outb(p, aic_inb(p, SCSISEQ) & (ENSELI|ENRSELI|ENAUTOATNP), SCSISEQ);
3598     aic7xxx_clear_intstat(p);
3599     aic_outb(p, sblkctl, SBLKCTL);
3600   }
3601   else
3602   {
3603     /*
3604      * Case 2: A command from this bus is active or we're idle.
3605      */
3606     if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
3607       printk(INFO_LEAD "Resetting currently active channel.\n", p->host_no,
3608         channel, -1, -1);
3609     aic_outb(p, aic_inb(p, SIMODE1) & ~(ENBUSFREE|ENREQINIT),
3610       SIMODE1);
3611     p->flags &= ~AHC_HANDLING_REQINITS;
3612     p->msg_type = MSG_TYPE_NONE;
3613     p->msg_len = 0;
3614     if (initiate_reset)
3615     {
3616       aic7xxx_reset_current_bus(p);
3617     }
3618     aic_outb(p, aic_inb(p, SCSISEQ) & (ENSELI|ENRSELI|ENAUTOATNP), SCSISEQ);
3619     aic7xxx_clear_intstat(p);
3620   }
3621   if (aic7xxx_verbose & VERBOSE_RESET_RETURN)
3622     printk(INFO_LEAD "Channel reset\n", p->host_no, channel, -1, -1);
3623   /*
3624    * Clean up all the state information for the pending transactions
3625    * on this bus.
3626    */
3627   aic7xxx_reset_device(p, ALL_TARGETS, channel, ALL_LUNS, SCB_LIST_NULL);
3628
3629   if ( !(p->features & AHC_TWIN) )
3630   {
3631     restart_sequencer(p);
3632   }
3633
3634   return;
3635 }
3636
3637 /*+F*************************************************************************
3638  * Function:
3639  *   aic7xxx_run_waiting_queues
3640  *
3641  * Description:
3642  *   Scan the awaiting_scbs queue downloading and starting as many
3643  *   scbs as we can.
3644  *-F*************************************************************************/
3645 static void
3646 aic7xxx_run_waiting_queues(struct aic7xxx_host *p)
3647 {
3648   struct aic7xxx_scb *scb;
3649   struct aic_dev_data *aic_dev;
3650   int sent;
3651
3652
3653   if (p->waiting_scbs.head == NULL)
3654     return;
3655
3656   sent = 0;
3657
3658   /*
3659    * First handle SCBs that are waiting but have been assigned a slot.
3660    */
3661   while ((scb = scbq_remove_head(&p->waiting_scbs)) != NULL)
3662   {
3663     aic_dev = scb->cmd->device->hostdata;
3664     if ( !scb->tag_action )
3665     {
3666       aic_dev->temp_q_depth = 1;
3667     }
3668     if ( aic_dev->active_cmds >= aic_dev->temp_q_depth)
3669     {
3670       scbq_insert_tail(&aic_dev->delayed_scbs, scb);
3671     }
3672     else
3673     {
3674         scb->flags &= ~SCB_WAITINGQ;
3675         aic_dev->active_cmds++;
3676         p->activescbs++;
3677         if ( !(scb->tag_action) )
3678         {
3679           aic7xxx_busy_target(p, scb);
3680         }
3681         p->qinfifo[p->qinfifonext++] = scb->hscb->tag;
3682         sent++;
3683     }
3684   }
3685   if (sent)
3686   {
3687     if (p->features & AHC_QUEUE_REGS)
3688       aic_outb(p, p->qinfifonext, HNSCB_QOFF);
3689     else
3690     {
3691       pause_sequencer(p);
3692       aic_outb(p, p->qinfifonext, KERNEL_QINPOS);
3693       unpause_sequencer(p, FALSE);
3694     }
3695     if (p->activescbs > p->max_activescbs)
3696       p->max_activescbs = p->activescbs;
3697   }
3698 }
3699
3700 #ifdef CONFIG_PCI
3701
3702 #define  DPE 0x80
3703 #define  SSE 0x40
3704 #define  RMA 0x20
3705 #define  RTA 0x10
3706 #define  STA 0x08
3707 #define  DPR 0x01
3708
3709 /*+F*************************************************************************
3710  * Function:
3711  *   aic7xxx_pci_intr
3712  *
3713  * Description:
3714  *   Check the scsi card for PCI errors and clear the interrupt
3715  *
3716  *   NOTE: If you don't have this function and a 2940 card encounters
3717  *         a PCI error condition, the machine will end up locked as the
3718  *         interrupt handler gets slammed with non-stop PCI error interrupts
3719  *-F*************************************************************************/
3720 static void
3721 aic7xxx_pci_intr(struct aic7xxx_host *p)
3722 {
3723   unsigned char status1;
3724
3725   pci_read_config_byte(p->pdev, PCI_STATUS + 1, &status1);
3726
3727   if ( (status1 & DPE) && (aic7xxx_verbose & VERBOSE_MINOR_ERROR) )
3728     printk(WARN_LEAD "Data Parity Error during PCI address or PCI write"
3729       "phase.\n", p->host_no, -1, -1, -1);
3730   if ( (status1 & SSE) && (aic7xxx_verbose & VERBOSE_MINOR_ERROR) )
3731     printk(WARN_LEAD "Signal System Error Detected\n", p->host_no,
3732       -1, -1, -1);
3733   if ( (status1 & RMA) && (aic7xxx_verbose & VERBOSE_MINOR_ERROR) )
3734     printk(WARN_LEAD "Received a PCI Master Abort\n", p->host_no,
3735       -1, -1, -1);
3736   if ( (status1 & RTA) && (aic7xxx_verbose & VERBOSE_MINOR_ERROR) )
3737     printk(WARN_LEAD "Received a PCI Target Abort\n", p->host_no,
3738       -1, -1, -1);
3739   if ( (status1 & STA) && (aic7xxx_verbose & VERBOSE_MINOR_ERROR) )
3740     printk(WARN_LEAD "Signaled a PCI Target Abort\n", p->host_no,
3741       -1, -1, -1);
3742   if ( (status1 & DPR) && (aic7xxx_verbose & VERBOSE_MINOR_ERROR) )
3743     printk(WARN_LEAD "Data Parity Error has been reported via PCI pin "
3744       "PERR#\n", p->host_no, -1, -1, -1);
3745   
3746   pci_write_config_byte(p->pdev, PCI_STATUS + 1, status1);
3747   if (status1 & (DPR|RMA|RTA))
3748     aic_outb(p,  CLRPARERR, CLRINT);
3749
3750   if ( (aic7xxx_panic_on_abort) && (p->spurious_int > 500) )
3751     aic7xxx_panic_abort(p, NULL);
3752
3753 }
3754 #endif /* CONFIG_PCI */
3755
3756 /*+F*************************************************************************
3757  * Function:
3758  *   aic7xxx_construct_ppr
3759  *
3760  * Description:
3761  *   Build up a Parallel Protocol Request message for use with SCSI-3
3762  *   devices.
3763  *-F*************************************************************************/
3764 static void
3765 aic7xxx_construct_ppr(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
3766 {
3767   p->msg_buf[p->msg_index++] = MSG_EXTENDED;
3768   p->msg_buf[p->msg_index++] = MSG_EXT_PPR_LEN;
3769   p->msg_buf[p->msg_index++] = MSG_EXT_PPR;
3770   p->msg_buf[p->msg_index++] = AIC_DEV(scb->cmd)->goal.period;
3771   p->msg_buf[p->msg_index++] = 0;
3772   p->msg_buf[p->msg_index++] = AIC_DEV(scb->cmd)->goal.offset;
3773   p->msg_buf[p->msg_index++] = AIC_DEV(scb->cmd)->goal.width;
3774   p->msg_buf[p->msg_index++] = AIC_DEV(scb->cmd)->goal.options;
3775   p->msg_len += 8;
3776 }
3777
3778 /*+F*************************************************************************
3779  * Function:
3780  *   aic7xxx_construct_sdtr
3781  *
3782  * Description:
3783  *   Constucts a synchronous data transfer message in the message
3784  *   buffer on the sequencer.
3785  *-F*************************************************************************/
3786 static void
3787 aic7xxx_construct_sdtr(struct aic7xxx_host *p, unsigned char period,
3788         unsigned char offset)
3789 {
3790   p->msg_buf[p->msg_index++] = MSG_EXTENDED;
3791   p->msg_buf[p->msg_index++] = MSG_EXT_SDTR_LEN;
3792   p->msg_buf[p->msg_index++] = MSG_EXT_SDTR;
3793   p->msg_buf[p->msg_index++] = period;
3794   p->msg_buf[p->msg_index++] = offset;
3795   p->msg_len += 5;
3796 }
3797
3798 /*+F*************************************************************************
3799  * Function:
3800  *   aic7xxx_construct_wdtr
3801  *
3802  * Description:
3803  *   Constucts a wide data transfer message in the message buffer
3804  *   on the sequencer.
3805  *-F*************************************************************************/
3806 static void
3807 aic7xxx_construct_wdtr(struct aic7xxx_host *p, unsigned char bus_width)
3808 {
3809   p->msg_buf[p->msg_index++] = MSG_EXTENDED;
3810   p->msg_buf[p->msg_index++] = MSG_EXT_WDTR_LEN;
3811   p->msg_buf[p->msg_index++] = MSG_EXT_WDTR;
3812   p->msg_buf[p->msg_index++] = bus_width;
3813   p->msg_len += 4;
3814 }
3815
3816 /*+F*************************************************************************
3817  * Function:
3818  *   aic7xxx_calc_residual
3819  *
3820  * Description:
3821  *   Calculate the residual data not yet transferred.
3822  *-F*************************************************************************/
3823 static void
3824 aic7xxx_calculate_residual (struct aic7xxx_host *p, struct aic7xxx_scb *scb)
3825 {
3826         struct aic7xxx_hwscb *hscb;
3827         struct scsi_cmnd *cmd;
3828         int actual, i;
3829
3830   cmd = scb->cmd;
3831   hscb = scb->hscb;
3832
3833   /*
3834    *  Don't destroy valid residual information with
3835    *  residual coming from a check sense operation.
3836    */
3837   if (((scb->hscb->control & DISCONNECTED) == 0) &&
3838       (scb->flags & SCB_SENSE) == 0)
3839   {
3840     /*
3841      *  We had an underflow. At this time, there's only
3842      *  one other driver that bothers to check for this,
3843      *  and cmd->underflow seems to be set rather half-
3844      *  heartedly in the higher-level SCSI code.
3845      */
3846     actual = scb->sg_length;
3847     for (i=1; i < hscb->residual_SG_segment_count; i++)
3848     {
3849       actual -= scb->sg_list[scb->sg_count - i].length;
3850     }
3851     actual -= (hscb->residual_data_count[2] << 16) |
3852               (hscb->residual_data_count[1] <<  8) |
3853               hscb->residual_data_count[0];
3854
3855     if (actual < cmd->underflow)
3856     {
3857       if (aic7xxx_verbose & VERBOSE_MINOR_ERROR)
3858       {
3859         printk(INFO_LEAD "Underflow - Wanted %u, %s %u, residual SG "
3860           "count %d.\n", p->host_no, CTL_OF_SCB(scb), cmd->underflow,
3861           (rq_data_dir(cmd->request) == WRITE) ? "wrote" : "read", actual,
3862           hscb->residual_SG_segment_count);
3863         printk(INFO_LEAD "status 0x%x.\n", p->host_no, CTL_OF_SCB(scb),
3864           hscb->target_status);
3865       }
3866       /*
3867        * In 2.4, only send back the residual information, don't flag this
3868        * as an error.  Before 2.4 we had to flag this as an error because
3869        * the mid layer didn't check residual data counts to see if the
3870        * command needs retried.
3871        */
3872       cmd->resid = scb->sg_length - actual;
3873       aic7xxx_status(cmd) = hscb->target_status;
3874     }
3875   }
3876
3877   /*
3878    * Clean out the residual information in the SCB for the
3879    * next consumer.
3880    */
3881   hscb->residual_data_count[2] = 0;
3882   hscb->residual_data_count[1] = 0;
3883   hscb->residual_data_count[0] = 0;
3884   hscb->residual_SG_segment_count = 0;
3885 }
3886
3887 /*+F*************************************************************************
3888  * Function:
3889  *   aic7xxx_handle_device_reset
3890  *
3891  * Description:
3892  *   Interrupt handler for sequencer interrupts (SEQINT).
3893  *-F*************************************************************************/
3894 static void
3895 aic7xxx_handle_device_reset(struct aic7xxx_host *p, int target, int channel)
3896 {
3897   unsigned char tindex = target;
3898
3899   tindex |= ((channel & 0x01) << 3);
3900
3901   /*
3902    * Go back to async/narrow transfers and renegotiate.
3903    */
3904   aic_outb(p, 0, TARG_SCSIRATE + tindex);
3905   if (p->features & AHC_ULTRA2)
3906     aic_outb(p, 0, TARG_OFFSET + tindex);
3907   aic7xxx_reset_device(p, target, channel, ALL_LUNS, SCB_LIST_NULL);
3908   if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
3909     printk(INFO_LEAD "Bus Device Reset delivered.\n", p->host_no, channel,
3910       target, -1);
3911   aic7xxx_run_done_queue(p, /*complete*/ TRUE);
3912 }
3913
3914 /*+F*************************************************************************
3915  * Function:
3916  *   aic7xxx_handle_seqint
3917  *
3918  * Description:
3919  *   Interrupt handler for sequencer interrupts (SEQINT).
3920  *-F*************************************************************************/
3921 static void
3922 aic7xxx_handle_seqint(struct aic7xxx_host *p, unsigned char intstat)
3923 {
3924   struct aic7xxx_scb *scb;
3925   struct aic_dev_data *aic_dev;
3926   unsigned short target_mask;
3927   unsigned char target, lun, tindex;
3928   unsigned char queue_flag = FALSE;
3929   char channel;
3930   int result;
3931
3932   target = ((aic_inb(p, SAVED_TCL) >> 4) & 0x0f);
3933   if ( (p->chip & AHC_CHIPID_MASK) == AHC_AIC7770 )
3934     channel = (aic_inb(p, SBLKCTL) & SELBUSB) >> 3;
3935   else
3936     channel = 0;
3937   tindex = target + (channel << 3);
3938   lun = aic_inb(p, SAVED_TCL) & 0x07;
3939   target_mask = (0x01 << tindex);
3940
3941   /*
3942    * Go ahead and clear the SEQINT now, that avoids any interrupt race
3943    * conditions later on in case we enable some other interrupt.
3944    */
3945   aic_outb(p, CLRSEQINT, CLRINT);
3946   switch (intstat & SEQINT_MASK)
3947   {
3948     case NO_MATCH:
3949       {
3950         aic_outb(p, aic_inb(p, SCSISEQ) & (ENSELI|ENRSELI|ENAUTOATNP),
3951                  SCSISEQ);
3952         printk(WARN_LEAD "No active SCB for reconnecting target - Issuing "
3953                "BUS DEVICE RESET.\n", p->host_no, channel, target, lun);
3954         printk(WARN_LEAD "      SAVED_TCL=0x%x, ARG_1=0x%x, SEQADDR=0x%x\n",
3955                p->host_no, channel, target, lun,
3956                aic_inb(p, SAVED_TCL), aic_inb(p, ARG_1),
3957                (aic_inb(p, SEQADDR1) << 8) | aic_inb(p, SEQADDR0));
3958         if (aic7xxx_panic_on_abort)
3959           aic7xxx_panic_abort(p, NULL);
3960       }
3961       break;
3962
3963     case SEND_REJECT:
3964       {
3965         if (aic7xxx_verbose & VERBOSE_MINOR_ERROR)
3966           printk(INFO_LEAD "Rejecting unknown message (0x%x) received from "
3967             "target, SEQ_FLAGS=0x%x\n", p->host_no, channel, target, lun,
3968             aic_inb(p, ACCUM), aic_inb(p, SEQ_FLAGS));
3969       }
3970       break;
3971
3972     case NO_IDENT:
3973       {
3974         /*
3975          * The reconnecting target either did not send an identify
3976          * message, or did, but we didn't find an SCB to match and
3977          * before it could respond to our ATN/abort, it hit a dataphase.
3978          * The only safe thing to do is to blow it away with a bus
3979          * reset.
3980          */
3981         if (aic7xxx_verbose & (VERBOSE_SEQINT | VERBOSE_RESET_MID))
3982           printk(INFO_LEAD "Target did not send an IDENTIFY message; "
3983             "LASTPHASE 0x%x, SAVED_TCL 0x%x\n", p->host_no, channel, target,
3984             lun, aic_inb(p, LASTPHASE), aic_inb(p, SAVED_TCL));
3985
3986         aic7xxx_reset_channel(p, channel, /*initiate reset*/ TRUE);
3987         aic7xxx_run_done_queue(p, TRUE);
3988
3989       }
3990       break;
3991
3992     case BAD_PHASE:
3993       if (aic_inb(p, LASTPHASE) == P_BUSFREE)
3994       {
3995         if (aic7xxx_verbose & VERBOSE_SEQINT)
3996           printk(INFO_LEAD "Missed busfree.\n", p->host_no, channel,
3997             target, lun);
3998         restart_sequencer(p);
3999       }
4000       else
4001       {
4002         if (aic7xxx_verbose & VERBOSE_SEQINT)
4003           printk(INFO_LEAD "Unknown scsi bus phase, continuing\n", p->host_no,
4004             channel, target, lun);
4005       }
4006       break;
4007
4008     case EXTENDED_MSG:
4009       {
4010         p->msg_type = MSG_TYPE_INITIATOR_MSGIN;
4011         p->msg_len = 0;
4012         p->msg_index = 0;
4013
4014 #ifdef AIC7XXX_VERBOSE_DEBUGGING
4015         if (aic7xxx_verbose > 0xffff)
4016           printk(INFO_LEAD "Enabling REQINITs for MSG_IN\n", p->host_no,
4017                  channel, target, lun);
4018 #endif
4019
4020        /*      
4021         * To actually receive the message, simply turn on
4022         * REQINIT interrupts and let our interrupt handler
4023         * do the rest (REQINIT should already be true).
4024         */
4025         p->flags |= AHC_HANDLING_REQINITS;
4026         aic_outb(p, aic_inb(p, SIMODE1) | ENREQINIT, SIMODE1);
4027
4028        /*
4029         * We don't want the sequencer unpaused yet so we return early
4030         */
4031         return;
4032       }
4033
4034     case REJECT_MSG:
4035       {
4036         /*
4037          * What we care about here is if we had an outstanding SDTR
4038          * or WDTR message for this target. If we did, this is a
4039          * signal that the target is refusing negotiation.
4040          */
4041         unsigned char scb_index;
4042         unsigned char last_msg;
4043
4044         scb_index = aic_inb(p, SCB_TAG);
4045         scb = p->scb_data->scb_array[scb_index];
4046         aic_dev = AIC_DEV(scb->cmd);
4047         last_msg = aic_inb(p, LAST_MSG);
4048
4049         if ( (last_msg == MSG_IDENTIFYFLAG) &&
4050              (scb->tag_action) &&
4051             !(scb->flags & SCB_MSGOUT_BITS) )
4052         {
4053           if (scb->tag_action == MSG_ORDERED_Q_TAG)
4054           {
4055             /*
4056              * OK...the device seems able to accept tagged commands, but
4057              * not ordered tag commands, only simple tag commands.  So, we
4058              * disable ordered tag commands and go on with life just like
4059              * normal.
4060              */
4061             scsi_adjust_queue_depth(scb->cmd->device, MSG_SIMPLE_TAG,
4062                             scb->cmd->device->queue_depth);
4063             scb->tag_action = MSG_SIMPLE_Q_TAG;
4064             scb->hscb->control &= ~SCB_TAG_TYPE;
4065             scb->hscb->control |= MSG_SIMPLE_Q_TAG;
4066             aic_outb(p, scb->hscb->control, SCB_CONTROL);
4067             /*
4068              * OK..we set the tag type to simple tag command, now we re-assert
4069              * ATNO and hope this will take us into the identify phase again
4070              * so we can resend the tag type and info to the device.
4071              */
4072             aic_outb(p, MSG_IDENTIFYFLAG, MSG_OUT);
4073             aic_outb(p, aic_inb(p, SCSISIGI) | ATNO, SCSISIGO);
4074           }
4075           else if (scb->tag_action == MSG_SIMPLE_Q_TAG)
4076           {
4077             unsigned char i;
4078             struct aic7xxx_scb *scbp;
4079             int old_verbose;
4080             /*
4081              * Hmmmm....the device is flaking out on tagged commands.
4082              */
4083             scsi_adjust_queue_depth(scb->cmd->device, 0 /* untagged */,
4084                             p->host->cmd_per_lun);
4085             aic_dev->max_q_depth = aic_dev->temp_q_depth = 1;
4086             /*
4087              * We set this command up as a bus device reset.  However, we have
4088              * to clear the tag type as it's causing us problems.  We shouldnt
4089              * have to worry about any other commands being active, since if
4090              * the device is refusing tagged commands, this should be the
4091              * first tagged command sent to the device, however, we do have
4092              * to worry about any other tagged commands that may already be
4093              * in the qinfifo.  The easiest way to do this, is to issue a BDR,
4094              * send all the commands back to the mid level code, then let them
4095              * come back and get rebuilt as untagged commands.
4096              */
4097             scb->tag_action = 0;
4098             scb->hscb->control &= ~(TAG_ENB | SCB_TAG_TYPE);
4099             aic_outb(p,  scb->hscb->control, SCB_CONTROL);
4100
4101             old_verbose = aic7xxx_verbose;
4102             aic7xxx_verbose &= ~(VERBOSE_RESET|VERBOSE_ABORT);
4103             for (i=0; i < p->scb_data->numscbs; i++)
4104             {
4105               scbp = p->scb_data->scb_array[i];
4106               if ((scbp->flags & SCB_ACTIVE) && (scbp != scb))
4107               {
4108                 if (aic7xxx_match_scb(p, scbp, target, channel, lun, i))
4109                 {
4110                   aic7xxx_reset_device(p, target, channel, lun, i);
4111                 }
4112               }
4113             }
4114             aic7xxx_run_done_queue(p, TRUE);
4115             aic7xxx_verbose = old_verbose;
4116             /*
4117              * Wait until after the for loop to set the busy index since
4118              * aic7xxx_reset_device will clear the busy index during its
4119              * operation.
4120              */
4121             aic7xxx_busy_target(p, scb);
4122             printk(INFO_LEAD "Device is refusing tagged commands, using "
4123               "untagged I/O.\n", p->host_no, channel, target, lun);
4124             aic_outb(p, MSG_IDENTIFYFLAG, MSG_OUT);
4125             aic_outb(p, aic_inb(p, SCSISIGI) | ATNO, SCSISIGO);
4126           }
4127         }
4128         else if (scb->flags & SCB_MSGOUT_PPR)
4129         {
4130           /*
4131            * As per the draft specs, any device capable of supporting any of
4132            * the option values other than 0 are not allowed to reject the
4133            * PPR message.  Instead, they must negotiate out what they do
4134            * support instead of rejecting our offering or else they cause
4135            * a parity error during msg_out phase to signal that they don't
4136            * like our settings.
4137            */
4138           aic_dev->needppr = aic_dev->needppr_copy = 0;
4139           aic7xxx_set_width(p, target, channel, lun, MSG_EXT_WDTR_BUS_8_BIT,
4140             (AHC_TRANS_ACTIVE|AHC_TRANS_CUR|AHC_TRANS_QUITE), aic_dev);
4141           aic7xxx_set_syncrate(p, NULL, target, channel, 0, 0, 0,
4142                                AHC_TRANS_ACTIVE|AHC_TRANS_CUR|AHC_TRANS_QUITE,
4143                                aic_dev);
4144           aic_dev->goal.options = aic_dev->dtr_pending = 0;
4145           scb->flags &= ~SCB_MSGOUT_BITS;
4146           if(aic7xxx_verbose & VERBOSE_NEGOTIATION2)
4147           {
4148             printk(INFO_LEAD "Device is rejecting PPR messages, falling "
4149               "back.\n", p->host_no, channel, target, lun);
4150           }
4151           if ( aic_dev->goal.width )
4152           {
4153             aic_dev->needwdtr = aic_dev->needwdtr_copy = 1;
4154             aic_dev->dtr_pending = 1;
4155             scb->flags |= SCB_MSGOUT_WDTR;
4156           }
4157           if ( aic_dev->goal.offset )
4158           {
4159             aic_dev->needsdtr = aic_dev->needsdtr_copy = 1;
4160             if( !aic_dev->dtr_pending )
4161             {
4162               aic_dev->dtr_pending = 1;
4163               scb->flags |= SCB_MSGOUT_SDTR;
4164             }
4165           }
4166           if ( aic_dev->dtr_pending )
4167           {
4168             aic_outb(p, HOST_MSG, MSG_OUT);
4169             aic_outb(p, aic_inb(p, SCSISIGI) | ATNO, SCSISIGO);
4170           }
4171         }
4172         else if (scb->flags & SCB_MSGOUT_WDTR)
4173         {
4174           /*
4175            * note 8bit xfers and clear flag
4176            */
4177           aic_dev->needwdtr = aic_dev->needwdtr_copy = 0;
4178           scb->flags &= ~SCB_MSGOUT_BITS;
4179           aic7xxx_set_width(p, target, channel, lun, MSG_EXT_WDTR_BUS_8_BIT,
4180             (AHC_TRANS_ACTIVE|AHC_TRANS_GOAL|AHC_TRANS_CUR), aic_dev);
4181           aic7xxx_set_syncrate(p, NULL, target, channel, 0, 0, 0,
4182                                AHC_TRANS_ACTIVE|AHC_TRANS_CUR|AHC_TRANS_QUITE,
4183                                aic_dev);
4184           if(aic7xxx_verbose & VERBOSE_NEGOTIATION2)
4185           {
4186             printk(INFO_LEAD "Device is rejecting WDTR messages, using "
4187               "narrow transfers.\n", p->host_no, channel, target, lun);
4188           }
4189           aic_dev->needsdtr = aic_dev->needsdtr_copy;
4190         }
4191         else if (scb->flags & SCB_MSGOUT_SDTR)
4192         {
4193          /*
4194           * note asynch xfers and clear flag
4195           */
4196           aic_dev->needsdtr = aic_dev->needsdtr_copy = 0;
4197           scb->flags &= ~SCB_MSGOUT_BITS;
4198           aic7xxx_set_syncrate(p, NULL, target, channel, 0, 0, 0,
4199             (AHC_TRANS_CUR|AHC_TRANS_ACTIVE|AHC_TRANS_GOAL), aic_dev);
4200           if(aic7xxx_verbose & VERBOSE_NEGOTIATION2)
4201           {
4202             printk(INFO_LEAD "Device is rejecting SDTR messages, using "
4203               "async transfers.\n", p->host_no, channel, target, lun);
4204           }
4205         }
4206         else if (aic7xxx_verbose & VERBOSE_SEQINT)
4207         {
4208           /*
4209            * Otherwise, we ignore it.
4210            */
4211           printk(INFO_LEAD "Received MESSAGE_REJECT for unknown cause.  "
4212             "Ignoring.\n", p->host_no, channel, target, lun);
4213         }
4214       }
4215       break;
4216
4217     case BAD_STATUS:
4218       {
4219         unsigned char scb_index;
4220         struct aic7xxx_hwscb *hscb;
4221         struct scsi_cmnd *cmd;
4222
4223         /* The sequencer will notify us when a command has an error that
4224          * would be of interest to the kernel.  This allows us to leave
4225          * the sequencer running in the common case of command completes
4226          * without error.  The sequencer will have DMA'd the SCB back
4227          * up to us, so we can reference the drivers SCB array.
4228          *
4229          * Set the default return value to 0 indicating not to send
4230          * sense.  The sense code will change this if needed and this
4231          * reduces code duplication.
4232          */
4233         aic_outb(p, 0, RETURN_1);
4234         scb_index = aic_inb(p, SCB_TAG);
4235         if (scb_index > p->scb_data->numscbs)
4236         {
4237           printk(WARN_LEAD "Invalid SCB during SEQINT 0x%02x, SCB_TAG %d.\n",
4238             p->host_no, channel, target, lun, intstat, scb_index);
4239           break;
4240         }
4241         scb = p->scb_data->scb_array[scb_index];
4242         hscb = scb->hscb;
4243
4244         if (!(scb->flags & SCB_ACTIVE) || (scb->cmd == NULL))
4245         {
4246           printk(WARN_LEAD "Invalid SCB during SEQINT 0x%x, scb %d, flags 0x%x,"
4247             " cmd 0x%lx.\n", p->host_no, channel, target, lun, intstat,
4248             scb_index, scb->flags, (unsigned long) scb->cmd);
4249         }
4250         else
4251         {
4252           cmd = scb->cmd;
4253           aic_dev = AIC_DEV(scb->cmd);
4254           hscb->target_status = aic_inb(p, SCB_TARGET_STATUS);
4255           aic7xxx_status(cmd) = hscb->target_status;
4256
4257           cmd->result = hscb->target_status;
4258
4259           switch (status_byte(hscb->target_status))
4260           {
4261             case GOOD:
4262               if (aic7xxx_verbose & VERBOSE_SEQINT)
4263                 printk(INFO_LEAD "Interrupted for status of GOOD???\n",
4264                   p->host_no, CTL_OF_SCB(scb));
4265               break;
4266
4267             case COMMAND_TERMINATED:
4268             case CHECK_CONDITION:
4269               if ( !(scb->flags & SCB_SENSE) )
4270               {
4271                 /*
4272                  * Send a sense command to the requesting target.
4273                  * XXX - revisit this and get rid of the memcopys.
4274                  */
4275                 memcpy(scb->sense_cmd, &generic_sense[0],
4276                        sizeof(generic_sense));
4277
4278                 scb->sense_cmd[1] = (cmd->device->lun << 5);
4279                 scb->sense_cmd[4] = sizeof(cmd->sense_buffer);
4280
4281                 scb->sg_list[0].length = 
4282                   cpu_to_le32(sizeof(cmd->sense_buffer));
4283                 scb->sg_list[0].address =
4284                         cpu_to_le32(pci_map_single(p->pdev, cmd->sense_buffer,
4285                                                    sizeof(cmd->sense_buffer),
4286                                                    PCI_DMA_FROMDEVICE));
4287
4288                 /*
4289                  * XXX - We should allow disconnection, but can't as it
4290                  * might allow overlapped tagged commands.
4291                  */
4292                 /* hscb->control &= DISCENB; */
4293                 hscb->control = 0;
4294                 hscb->target_status = 0;
4295                 hscb->SG_list_pointer = 
4296                   cpu_to_le32(SCB_DMA_ADDR(scb, scb->sg_list));
4297                 hscb->SCSI_cmd_pointer = 
4298                   cpu_to_le32(SCB_DMA_ADDR(scb, scb->sense_cmd));
4299                 hscb->data_count = scb->sg_list[0].length;
4300                 hscb->data_pointer = scb->sg_list[0].address;
4301                 hscb->SCSI_cmd_length = COMMAND_SIZE(scb->sense_cmd[0]);
4302                 hscb->residual_SG_segment_count = 0;
4303                 hscb->residual_data_count[0] = 0;
4304                 hscb->residual_data_count[1] = 0;
4305                 hscb->residual_data_count[2] = 0;
4306
4307                 scb->sg_count = hscb->SG_segment_count = 1;
4308                 scb->sg_length = sizeof(cmd->sense_buffer);
4309                 scb->tag_action = 0;
4310                 scb->flags |= SCB_SENSE;
4311                 /*
4312                  * Ensure the target is busy since this will be an
4313                  * an untagged request.
4314                  */
4315 #ifdef AIC7XXX_VERBOSE_DEBUGGING
4316                 if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
4317                 {
4318                   if (scb->flags & SCB_MSGOUT_BITS)
4319                     printk(INFO_LEAD "Requesting SENSE with %s\n", p->host_no,
4320                            CTL_OF_SCB(scb), (scb->flags & SCB_MSGOUT_SDTR) ?
4321                            "SDTR" : "WDTR");
4322                   else
4323                     printk(INFO_LEAD "Requesting SENSE, no MSG\n", p->host_no,
4324                            CTL_OF_SCB(scb));
4325                 }
4326 #endif
4327                 aic7xxx_busy_target(p, scb);
4328                 aic_outb(p, SEND_SENSE, RETURN_1);
4329                 aic7xxx_error(cmd) = DID_OK;
4330                 break;
4331               }  /* first time sense, no errors */
4332               printk(INFO_LEAD "CHECK_CONDITION on REQUEST_SENSE, returning "
4333                      "an error.\n", p->host_no, CTL_OF_SCB(scb));
4334               aic7xxx_error(cmd) = DID_ERROR;
4335               scb->flags &= ~SCB_SENSE;
4336               break;
4337
4338             case QUEUE_FULL:
4339               queue_flag = TRUE;    /* Mark that this is a QUEUE_FULL and */
4340             case BUSY:              /* drop through to here */
4341             {
4342               struct aic7xxx_scb *next_scbp, *prev_scbp;
4343               unsigned char active_hscb, next_hscb, prev_hscb, scb_index;
4344               /*
4345                * We have to look three places for queued commands:
4346                *  1: p->waiting_scbs queue
4347                *  2: QINFIFO
4348                *  3: WAITING_SCBS list on card (for commands that are started
4349                *     but haven't yet made it to the device)
4350                *
4351                * Of special note here is that commands on 2 or 3 above will
4352                * have already been marked as active, while commands on 1 will
4353                * not.  The aic7xxx_done() function will want to unmark them
4354                * from active, so any commands we pull off of 1 need to
4355                * up the active count.
4356                */
4357               next_scbp = p->waiting_scbs.head;
4358               while ( next_scbp != NULL )
4359               {
4360                 prev_scbp = next_scbp;
4361                 next_scbp = next_scbp->q_next;
4362                 if ( aic7xxx_match_scb(p, prev_scbp, target, channel, lun,
4363                      SCB_LIST_NULL) )
4364                 {
4365                   scbq_remove(&p->waiting_scbs, prev_scbp);
4366                   scb->flags = SCB_QUEUED_FOR_DONE | SCB_QUEUE_FULL;
4367                   p->activescbs++;
4368                   aic_dev->active_cmds++;
4369                 }
4370               }
4371               aic7xxx_search_qinfifo(p, target, channel, lun,
4372                 SCB_LIST_NULL, SCB_QUEUED_FOR_DONE | SCB_QUEUE_FULL,
4373                 FALSE, NULL);
4374               next_scbp = NULL;
4375               active_hscb = aic_inb(p, SCBPTR);
4376               prev_hscb = next_hscb = scb_index = SCB_LIST_NULL;
4377               next_hscb = aic_inb(p, WAITING_SCBH);
4378               while (next_hscb != SCB_LIST_NULL)
4379               {
4380                 aic_outb(p, next_hscb, SCBPTR);
4381                 scb_index = aic_inb(p, SCB_TAG);
4382                 if (scb_index < p->scb_data->numscbs)
4383                 {
4384                   next_scbp = p->scb_data->scb_array[scb_index];
4385                   if (aic7xxx_match_scb(p, next_scbp, target, channel, lun,
4386                       SCB_LIST_NULL) )
4387                   {
4388                     next_scbp->flags = SCB_QUEUED_FOR_DONE | SCB_QUEUE_FULL;
4389                     next_hscb = aic_inb(p, SCB_NEXT);
4390                     aic_outb(p, 0, SCB_CONTROL);
4391                     aic_outb(p, SCB_LIST_NULL, SCB_TAG);
4392                     aic7xxx_add_curscb_to_free_list(p);
4393                     if (prev_hscb == SCB_LIST_NULL)
4394                     {
4395                       /* We were first on the list,
4396                        * so we kill the selection
4397                        * hardware.  Let the sequencer
4398                        * re-init the hardware itself
4399                        */
4400                       aic_outb(p, aic_inb(p, SCSISEQ) & ~ENSELO, SCSISEQ);
4401                       aic_outb(p, CLRSELTIMEO, CLRSINT1);
4402                       aic_outb(p, next_hscb, WAITING_SCBH);
4403                     }
4404                     else
4405                     {
4406                       aic_outb(p, prev_hscb, SCBPTR);
4407                       aic_outb(p, next_hscb, SCB_NEXT);
4408                     }
4409                   }
4410                   else
4411                   {
4412                     prev_hscb = next_hscb;
4413                     next_hscb = aic_inb(p, SCB_NEXT);
4414                   }
4415                 } /* scb_index >= p->scb_data->numscbs */
4416               }
4417               aic_outb(p, active_hscb, SCBPTR);
4418               aic7xxx_run_done_queue(p, FALSE);
4419                   
4420 #ifdef AIC7XXX_VERBOSE_DEBUGGING
4421               if( (aic7xxx_verbose & VERBOSE_MINOR_ERROR) ||
4422                   (aic7xxx_verbose > 0xffff) )
4423               {
4424                 if (queue_flag)
4425                   printk(INFO_LEAD "Queue full received; queue depth %d, "
4426                     "active %d\n", p->host_no, CTL_OF_SCB(scb),
4427                     aic_dev->max_q_depth, aic_dev->active_cmds);
4428                 else
4429                   printk(INFO_LEAD "Target busy\n", p->host_no, CTL_OF_SCB(scb));
4430               }
4431 #endif
4432               if (queue_flag)
4433               {
4434                 int diff;
4435                 result = scsi_track_queue_full(cmd->device,
4436                                 aic_dev->active_cmds);
4437                 if ( result < 0 )
4438                 {
4439                   if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
4440                     printk(INFO_LEAD "Tagged Command Queueing disabled.\n",
4441                         p->host_no, CTL_OF_SCB(scb));
4442                   diff = aic_dev->max_q_depth - p->host->cmd_per_lun;
4443                   aic_dev->temp_q_depth = 1;
4444                   aic_dev->max_q_depth = 1;
4445                 }
4446                 else if ( result > 0 )
4447                 {
4448                   if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
4449                     printk(INFO_LEAD "Queue depth reduced to %d\n", p->host_no,
4450                       CTL_OF_SCB(scb), result);
4451                   diff = aic_dev->max_q_depth - result;
4452                   aic_dev->max_q_depth = result;
4453                   /* temp_q_depth could have been dropped to 1 for an untagged
4454                    * command that might be coming up */
4455                   if(aic_dev->temp_q_depth > result)
4456                     aic_dev->temp_q_depth = result;
4457                 }
4458                 /* We should free up the no unused SCB entries.  But, that's
4459                  * a difficult thing to do because we use a direct indexed
4460                  * array, so we can't just take any entries and free them,
4461                  * we *have* to free the ones at the end of the array, and
4462                  * they very well could be in use right now, which means
4463                  * in order to do this right, we have to add a delayed
4464                  * freeing mechanism tied into the scb_free() code area.
4465                  * We'll add that later.
4466                  */
4467               }
4468               break;
4469             }
4470             
4471             default:
4472               if (aic7xxx_verbose & VERBOSE_SEQINT)
4473                 printk(INFO_LEAD "Unexpected target status 0x%x.\n", p->host_no,
4474                      CTL_OF_SCB(scb), scb->hscb->target_status);
4475               if (!aic7xxx_error(cmd))
4476               {
4477                 aic7xxx_error(cmd) = DID_RETRY_COMMAND;
4478               }
4479               break;
4480           }  /* end switch */
4481         }  /* end else of */
4482       }
4483       break;
4484
4485     case AWAITING_MSG:
4486       {
4487         unsigned char scb_index, msg_out;
4488
4489         scb_index = aic_inb(p, SCB_TAG);
4490         msg_out = aic_inb(p, MSG_OUT);
4491         scb = p->scb_data->scb_array[scb_index];
4492         aic_dev = AIC_DEV(scb->cmd);
4493         p->msg_index = p->msg_len = 0;
4494         /*
4495          * This SCB had a MK_MESSAGE set in its control byte informing
4496          * the sequencer that we wanted to send a special message to
4497          * this target.
4498          */
4499
4500         if ( !(scb->flags & SCB_DEVICE_RESET) &&
4501               (msg_out == MSG_IDENTIFYFLAG) &&
4502               (scb->hscb->control & TAG_ENB) )
4503         {
4504           p->msg_buf[p->msg_index++] = scb->tag_action;
4505           p->msg_buf[p->msg_index++] = scb->hscb->tag;
4506           p->msg_len += 2;
4507         }
4508
4509         if (scb->flags & SCB_DEVICE_RESET)
4510         {
4511           p->msg_buf[p->msg_index++] = MSG_BUS_DEV_RESET;
4512           p->msg_len++;
4513           if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
4514             printk(INFO_LEAD "Bus device reset mailed.\n",
4515                  p->host_no, CTL_OF_SCB(scb));
4516         }
4517         else if (scb->flags & SCB_ABORT)
4518         {
4519           if (scb->tag_action)
4520           {
4521             p->msg_buf[p->msg_index++] = MSG_ABORT_TAG;
4522           }
4523           else
4524           {
4525             p->msg_buf[p->msg_index++] = MSG_ABORT;
4526           }
4527           p->msg_len++;
4528           if (aic7xxx_verbose & VERBOSE_ABORT_PROCESS)
4529             printk(INFO_LEAD "Abort message mailed.\n", p->host_no,
4530               CTL_OF_SCB(scb));
4531         }
4532         else if (scb->flags & SCB_MSGOUT_PPR)
4533         {
4534           if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
4535           {
4536             printk(INFO_LEAD "Sending PPR (%d/%d/%d/%d) message.\n",
4537                    p->host_no, CTL_OF_SCB(scb),
4538                    aic_dev->goal.period,
4539                    aic_dev->goal.offset,
4540                    aic_dev->goal.width,
4541                    aic_dev->goal.options);
4542           }
4543           aic7xxx_construct_ppr(p, scb);
4544         }
4545         else if (scb->flags & SCB_MSGOUT_WDTR)
4546         {
4547           if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
4548           {
4549             printk(INFO_LEAD "Sending WDTR message.\n", p->host_no,
4550                    CTL_OF_SCB(scb));
4551           }
4552           aic7xxx_construct_wdtr(p, aic_dev->goal.width);
4553         }
4554         else if (scb->flags & SCB_MSGOUT_SDTR)
4555         {
4556           unsigned int max_sync, period;
4557           unsigned char options = 0;
4558           /*
4559            * Now that the device is selected, use the bits in SBLKCTL and
4560            * SSTAT2 to determine the max sync rate for this device.
4561            */
4562           if (p->features & AHC_ULTRA2)
4563           {
4564             if ( (aic_inb(p, SBLKCTL) & ENAB40) &&
4565                 !(aic_inb(p, SSTAT2) & EXP_ACTIVE) )
4566             {
4567               max_sync = AHC_SYNCRATE_ULTRA2;
4568             }
4569             else
4570             {
4571               max_sync = AHC_SYNCRATE_ULTRA;
4572             }
4573           }
4574           else if (p->features & AHC_ULTRA)
4575           {
4576             max_sync = AHC_SYNCRATE_ULTRA;
4577           }
4578           else
4579           {
4580             max_sync = AHC_SYNCRATE_FAST;
4581           }
4582           period = aic_dev->goal.period;
4583           aic7xxx_find_syncrate(p, &period, max_sync, &options);
4584           if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
4585           {
4586             printk(INFO_LEAD "Sending SDTR %d/%d message.\n", p->host_no,
4587                    CTL_OF_SCB(scb), period,
4588                    aic_dev->goal.offset);
4589           }
4590           aic7xxx_construct_sdtr(p, period, aic_dev->goal.offset);
4591         }
4592         else 
4593         {
4594           panic("aic7xxx: AWAITING_MSG for an SCB that does "
4595                 "not have a waiting message.\n");
4596         }
4597         /*
4598          * We've set everything up to send our message, now to actually do
4599          * so we need to enable reqinit interrupts and let the interrupt
4600          * handler do the rest.  We don't want to unpause the sequencer yet
4601          * though so we'll return early.  We also have to make sure that
4602          * we clear the SEQINT *BEFORE* we set the REQINIT handler active
4603          * or else it's possible on VLB cards to lose the first REQINIT
4604          * interrupt.  Edge triggered EISA cards could also lose this
4605          * interrupt, although PCI and level triggered cards should not
4606          * have this problem since they continually interrupt the kernel
4607          * until we take care of the situation.
4608          */
4609         scb->flags |= SCB_MSGOUT_SENT;
4610         p->msg_index = 0;
4611         p->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
4612         p->flags |= AHC_HANDLING_REQINITS;
4613         aic_outb(p, aic_inb(p, SIMODE1) | ENREQINIT, SIMODE1);
4614         return;
4615       }
4616       break;
4617
4618     case DATA_OVERRUN:
4619       {
4620         unsigned char scb_index = aic_inb(p, SCB_TAG);
4621         unsigned char lastphase = aic_inb(p, LASTPHASE);
4622         unsigned int i;
4623
4624         scb = (p->scb_data->scb_array[scb_index]);
4625         /*
4626          * XXX - What do we really want to do on an overrun?  The
4627          *       mid-level SCSI code should handle this, but for now,
4628          *       we'll just indicate that the command should retried.
4629          *    If we retrieved sense info on this target, then the 
4630          *    base SENSE info should have been saved prior to the
4631          *    overrun error.  In that case, we return DID_OK and let
4632          *    the mid level code pick up on the sense info.  Otherwise
4633          *    we return DID_ERROR so the command will get retried.
4634          */
4635         if ( !(scb->flags & SCB_SENSE) )
4636         {
4637           printk(WARN_LEAD "Data overrun detected in %s phase, tag %d;\n",
4638             p->host_no, CTL_OF_SCB(scb), 
4639             (lastphase == P_DATAIN) ? "Data-In" : "Data-Out", scb->hscb->tag);
4640           printk(KERN_WARNING "  %s seen Data Phase. Length=%d, NumSGs=%d.\n",
4641             (aic_inb(p, SEQ_FLAGS) & DPHASE) ? "Have" : "Haven't",
4642             scb->sg_length, scb->sg_count);
4643           printk(KERN_WARNING "  Raw SCSI Command: 0x");
4644           for (i = 0; i < scb->hscb->SCSI_cmd_length; i++)
4645           {
4646             printk("%02x ", scb->cmd->cmnd[i]);
4647           }
4648           printk("\n");
4649           if(aic7xxx_verbose > 0xffff)
4650           {
4651             for (i = 0; i < scb->sg_count; i++)
4652             {
4653               printk(KERN_WARNING "     sg[%d] - Addr 0x%x : Length %d\n",
4654                  i, 
4655                  le32_to_cpu(scb->sg_list[i].address),
4656                  le32_to_cpu(scb->sg_list[i].length) );
4657             }
4658           }
4659           aic7xxx_error(scb->cmd) = DID_ERROR;
4660         }
4661         else
4662           printk(INFO_LEAD "Data Overrun during SEND_SENSE operation.\n",
4663             p->host_no, CTL_OF_SCB(scb));
4664       }
4665       break;
4666
4667     case WIDE_RESIDUE:
4668       {
4669         unsigned char resid_sgcnt, index;
4670         unsigned char scb_index = aic_inb(p, SCB_TAG);
4671         unsigned int cur_addr, resid_dcnt;
4672         unsigned int native_addr, native_length, sg_addr;
4673         int i;
4674
4675         if(scb_index > p->scb_data->numscbs)
4676         {
4677           printk(WARN_LEAD "invalid scb_index during WIDE_RESIDUE.\n",
4678             p->host_no, -1, -1, -1);
4679           /*
4680            * XXX: Add error handling here
4681            */
4682           break;
4683         }
4684         scb = p->scb_data->scb_array[scb_index];
4685         if(!(scb->flags & SCB_ACTIVE) || (scb->cmd == NULL))
4686         {
4687           printk(WARN_LEAD "invalid scb during WIDE_RESIDUE flags:0x%x "
4688                  "scb->cmd:0x%lx\n", p->host_no, CTL_OF_SCB(scb),
4689                  scb->flags, (unsigned long)scb->cmd);
4690           break;
4691         }
4692         if(aic7xxx_verbose & VERBOSE_MINOR_ERROR)
4693           printk(INFO_LEAD "Got WIDE_RESIDUE message, patching up data "
4694                  "pointer.\n", p->host_no, CTL_OF_SCB(scb));
4695
4696         /*
4697          * We have a valid scb to use on this WIDE_RESIDUE message, so
4698          * we need to walk the sg list looking for this particular sg
4699          * segment, then see if we happen to be at the very beginning of
4700          * the segment.  If we are, then we have to back things up to
4701          * the previous segment.  If not, then we simply need to remove
4702          * one byte from this segments address and add one to the byte
4703          * count.
4704          */
4705         cur_addr = aic_inb(p, SHADDR) | (aic_inb(p, SHADDR + 1) << 8) |
4706           (aic_inb(p, SHADDR + 2) << 16) | (aic_inb(p, SHADDR + 3) << 24);
4707         sg_addr = aic_inb(p, SG_COUNT + 1) | (aic_inb(p, SG_COUNT + 2) << 8) |
4708           (aic_inb(p, SG_COUNT + 3) << 16) | (aic_inb(p, SG_COUNT + 4) << 24);
4709         resid_sgcnt = aic_inb(p, SCB_RESID_SGCNT);
4710         resid_dcnt = aic_inb(p, SCB_RESID_DCNT) |
4711           (aic_inb(p, SCB_RESID_DCNT + 1) << 8) |
4712           (aic_inb(p, SCB_RESID_DCNT + 2) << 16);
4713         index = scb->sg_count - ((resid_sgcnt) ? resid_sgcnt : 1);
4714         native_addr = le32_to_cpu(scb->sg_list[index].address);
4715         native_length = le32_to_cpu(scb->sg_list[index].length);
4716         /*
4717          * If resid_dcnt == native_length, then we just loaded this SG
4718          * segment and we need to back it up one...
4719          */
4720         if(resid_dcnt == native_length)
4721         {
4722           if(index == 0)
4723           {
4724             /*
4725              * Oops, this isn't right, we can't back up to before the
4726              * beginning.  This must be a bogus message, ignore it.
4727              */
4728             break;
4729           }
4730           resid_dcnt = 1;
4731           resid_sgcnt += 1;
4732           native_addr = le32_to_cpu(scb->sg_list[index - 1].address);
4733           native_length = le32_to_cpu(scb->sg_list[index - 1].length);
4734           cur_addr = native_addr + (native_length - 1);
4735           sg_addr -= sizeof(struct hw_scatterlist);
4736         }
4737         else
4738         {
4739           /*
4740            * resid_dcnt != native_length, so we are in the middle of a SG
4741            * element.  Back it up one byte and leave the rest alone.
4742            */
4743           resid_dcnt += 1;
4744           cur_addr -= 1;
4745         }
4746         
4747         /*
4748          * Output the new addresses and counts to the right places on the
4749          * card.
4750          */
4751         aic_outb(p, resid_sgcnt, SG_COUNT);
4752         aic_outb(p, resid_sgcnt, SCB_RESID_SGCNT);
4753         aic_outb(p, sg_addr & 0xff, SG_COUNT + 1);
4754         aic_outb(p, (sg_addr >> 8) & 0xff, SG_COUNT + 2);
4755         aic_outb(p, (sg_addr >> 16) & 0xff, SG_COUNT + 3);
4756         aic_outb(p, (sg_addr >> 24) & 0xff, SG_COUNT + 4);
4757         aic_outb(p, resid_dcnt & 0xff, SCB_RESID_DCNT);
4758         aic_outb(p, (resid_dcnt >> 8) & 0xff, SCB_RESID_DCNT + 1);
4759         aic_outb(p, (resid_dcnt >> 16) & 0xff, SCB_RESID_DCNT + 2);
4760
4761         /*
4762          * The sequencer actually wants to find the new address
4763          * in the SHADDR register set.  On the Ultra2 and later controllers
4764          * this register set is readonly.  In order to get the right number
4765          * into the register, you actually have to enter it in HADDR and then
4766          * use the PRELOADEN bit of DFCNTRL to drop it through from the
4767          * HADDR register to the SHADDR register.  On non-Ultra2 controllers,
4768          * we simply write it direct.
4769          */
4770         if(p->features & AHC_ULTRA2)
4771         {
4772           /*
4773            * We might as well be accurate and drop both the resid_dcnt and
4774            * cur_addr into HCNT and HADDR and have both of them drop
4775            * through to the shadow layer together.
4776            */
4777           aic_outb(p, resid_dcnt & 0xff, HCNT);
4778           aic_outb(p, (resid_dcnt >> 8) & 0xff, HCNT + 1);
4779           aic_outb(p, (resid_dcnt >> 16) & 0xff, HCNT + 2);
4780           aic_outb(p, cur_addr & 0xff, HADDR);
4781           aic_outb(p, (cur_addr >> 8) & 0xff, HADDR + 1);
4782           aic_outb(p, (cur_addr >> 16) & 0xff, HADDR + 2);
4783           aic_outb(p, (cur_addr >> 24) & 0xff, HADDR + 3);
4784           aic_outb(p, aic_inb(p, DMAPARAMS) | PRELOADEN, DFCNTRL);
4785           udelay(1);
4786           aic_outb(p, aic_inb(p, DMAPARAMS) & ~(SCSIEN|HDMAEN), DFCNTRL);
4787           i=0;
4788           while(((aic_inb(p, DFCNTRL) & (SCSIEN|HDMAEN)) != 0) && (i++ < 1000))
4789           {
4790             udelay(1);
4791           }
4792         }
4793         else
4794         {
4795           aic_outb(p, cur_addr & 0xff, SHADDR);
4796           aic_outb(p, (cur_addr >> 8) & 0xff, SHADDR + 1);
4797           aic_outb(p, (cur_addr >> 16) & 0xff, SHADDR + 2);
4798           aic_outb(p, (cur_addr >> 24) & 0xff, SHADDR + 3);
4799         }
4800       }
4801       break;
4802
4803     case SEQ_SG_FIXUP:
4804     {
4805       unsigned char scb_index, tmp;
4806       int sg_addr, sg_length;
4807
4808       scb_index = aic_inb(p, SCB_TAG);
4809
4810       if(scb_index > p->scb_data->numscbs)
4811       {
4812         printk(WARN_LEAD "invalid scb_index during SEQ_SG_FIXUP.\n",
4813           p->host_no, -1, -1, -1);
4814         printk(INFO_LEAD "SCSISIGI 0x%x, SEQADDR 0x%x, SSTAT0 0x%x, SSTAT1 "
4815            "0x%x\n", p->host_no, -1, -1, -1,
4816            aic_inb(p, SCSISIGI),
4817            aic_inb(p, SEQADDR0) | (aic_inb(p, SEQADDR1) << 8),
4818            aic_inb(p, SSTAT0), aic_inb(p, SSTAT1));
4819         printk(INFO_LEAD "SG_CACHEPTR 0x%x, SSTAT2 0x%x, STCNT 0x%x\n",
4820            p->host_no, -1, -1, -1, aic_inb(p, SG_CACHEPTR),
4821            aic_inb(p, SSTAT2), aic_inb(p, STCNT + 2) << 16 |
4822            aic_inb(p, STCNT + 1) << 8 | aic_inb(p, STCNT));
4823         /*
4824          * XXX: Add error handling here
4825          */
4826         break;
4827       }
4828       scb = p->scb_data->scb_array[scb_index];
4829       if(!(scb->flags & SCB_ACTIVE) || (scb->cmd == NULL))
4830       {
4831         printk(WARN_LEAD "invalid scb during SEQ_SG_FIXUP flags:0x%x "
4832                "scb->cmd:0x%p\n", p->host_no, CTL_OF_SCB(scb),
4833                scb->flags, scb->cmd);
4834         printk(INFO_LEAD "SCSISIGI 0x%x, SEQADDR 0x%x, SSTAT0 0x%x, SSTAT1 "
4835            "0x%x\n", p->host_no, CTL_OF_SCB(scb),
4836            aic_inb(p, SCSISIGI),
4837            aic_inb(p, SEQADDR0) | (aic_inb(p, SEQADDR1) << 8),
4838            aic_inb(p, SSTAT0), aic_inb(p, SSTAT1));
4839         printk(INFO_LEAD "SG_CACHEPTR 0x%x, SSTAT2 0x%x, STCNT 0x%x\n",
4840            p->host_no, CTL_OF_SCB(scb), aic_inb(p, SG_CACHEPTR),
4841            aic_inb(p, SSTAT2), aic_inb(p, STCNT + 2) << 16 |
4842            aic_inb(p, STCNT + 1) << 8 | aic_inb(p, STCNT));
4843         break;
4844       }
4845       if(aic7xxx_verbose & VERBOSE_MINOR_ERROR)
4846         printk(INFO_LEAD "Fixing up SG address for sequencer.\n", p->host_no,
4847                CTL_OF_SCB(scb));
4848       /*
4849        * Advance the SG pointer to the next element in the list
4850        */
4851       tmp = aic_inb(p, SG_NEXT);
4852       tmp += SG_SIZEOF;
4853       aic_outb(p, tmp, SG_NEXT);
4854       if( tmp < SG_SIZEOF )
4855         aic_outb(p, aic_inb(p, SG_NEXT + 1) + 1, SG_NEXT + 1);
4856       tmp = aic_inb(p, SG_COUNT) - 1;
4857       aic_outb(p, tmp, SG_COUNT);
4858       sg_addr = le32_to_cpu(scb->sg_list[scb->sg_count - tmp].address);
4859       sg_length = le32_to_cpu(scb->sg_list[scb->sg_count - tmp].length);
4860       /*
4861        * Now stuff the element we just advanced past down onto the
4862        * card so it can be stored in the residual area.
4863        */
4864       aic_outb(p, sg_addr & 0xff, HADDR);
4865       aic_outb(p, (sg_addr >> 8) & 0xff, HADDR + 1);
4866       aic_outb(p, (sg_addr >> 16) & 0xff, HADDR + 2);
4867       aic_outb(p, (sg_addr >> 24) & 0xff, HADDR + 3);
4868       aic_outb(p, sg_length & 0xff, HCNT);
4869       aic_outb(p, (sg_length >> 8) & 0xff, HCNT + 1);
4870       aic_outb(p, (sg_length >> 16) & 0xff, HCNT + 2);
4871       aic_outb(p, (tmp << 2) | ((tmp == 1) ? LAST_SEG : 0), SG_CACHEPTR);
4872       aic_outb(p, aic_inb(p, DMAPARAMS), DFCNTRL);
4873       while(aic_inb(p, SSTAT0) & SDONE) udelay(1);
4874       while(aic_inb(p, DFCNTRL) & (HDMAEN|SCSIEN)) aic_outb(p, 0, DFCNTRL);
4875     }
4876     break;
4877
4878 #ifdef AIC7XXX_NOT_YET 
4879     case TRACEPOINT2:
4880       {
4881         printk(INFO_LEAD "Tracepoint #2 reached.\n", p->host_no,
4882                channel, target, lun);
4883       }
4884       break;
4885
4886     /* XXX Fill these in later */
4887     case MSG_BUFFER_BUSY:
4888       printk("aic7xxx: Message buffer busy.\n");
4889       break;
4890     case MSGIN_PHASEMIS:
4891       printk("aic7xxx: Message-in phasemis.\n");
4892       break;
4893 #endif
4894
4895     default:                   /* unknown */
4896       printk(WARN_LEAD "Unknown SEQINT, INTSTAT 0x%x, SCSISIGI 0x%x.\n",
4897              p->host_no, channel, target, lun, intstat,
4898              aic_inb(p, SCSISIGI));
4899       break;
4900   }
4901
4902   /*
4903    * Clear the sequencer interrupt and unpause the sequencer.
4904    */
4905   unpause_sequencer(p, /* unpause always */ TRUE);
4906 }
4907
4908 /*+F*************************************************************************
4909  * Function:
4910  *   aic7xxx_parse_msg
4911  *
4912  * Description:
4913  *   Parses incoming messages into actions on behalf of
4914  *   aic7xxx_handle_reqinit
4915  *_F*************************************************************************/
4916 static int
4917 aic7xxx_parse_msg(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
4918 {
4919   int reject, reply, done;
4920   unsigned char target_scsirate, tindex;
4921   unsigned short target_mask;
4922   unsigned char target, channel, lun;
4923   unsigned char bus_width, new_bus_width;
4924   unsigned char trans_options, new_trans_options;
4925   unsigned int period, new_period, offset, new_offset, maxsync;
4926   struct aic7xxx_syncrate *syncrate;
4927   struct aic_dev_data *aic_dev;
4928
4929   target = scb->cmd->device->id;
4930   channel = scb->cmd->device->channel;
4931   lun = scb->cmd->device->lun;
4932   reply = reject = done = FALSE;
4933   tindex = TARGET_INDEX(scb->cmd);
4934   aic_dev = AIC_DEV(scb->cmd);
4935   target_scsirate = aic_inb(p, TARG_SCSIRATE + tindex);
4936   target_mask = (0x01 << tindex);
4937
4938   /*
4939    * Parse as much of the message as is available,
4940    * rejecting it if we don't support it.  When
4941    * the entire message is available and has been
4942    * handled, return TRUE indicating that we have
4943    * parsed an entire message.
4944    */
4945
4946   if (p->msg_buf[0] != MSG_EXTENDED)
4947   {
4948     reject = TRUE;
4949   }
4950
4951   /*
4952    * Even if we are an Ultra3 card, don't allow Ultra3 sync rates when
4953    * using the SDTR messages.  We need the PPR messages to enable the
4954    * higher speeds that include things like Dual Edge clocking.
4955    */
4956   if (p->features & AHC_ULTRA2)
4957   {
4958     if ( (aic_inb(p, SBLKCTL) & ENAB40) &&
4959          !(aic_inb(p, SSTAT2) & EXP_ACTIVE) )
4960     {
4961       if (p->features & AHC_ULTRA3)
4962         maxsync = AHC_SYNCRATE_ULTRA3;
4963       else
4964         maxsync = AHC_SYNCRATE_ULTRA2;
4965     }
4966     else
4967     {
4968       maxsync = AHC_SYNCRATE_ULTRA;
4969     }
4970   }
4971   else if (p->features & AHC_ULTRA)
4972   {
4973     maxsync = AHC_SYNCRATE_ULTRA;
4974   }
4975   else
4976   {
4977     maxsync = AHC_SYNCRATE_FAST;
4978   }
4979
4980   /*
4981    * Just accept the length byte outright and perform
4982    * more checking once we know the message type.
4983    */
4984
4985   if ( !reject && (p->msg_len > 2) )
4986   {
4987     switch(p->msg_buf[2])
4988     {
4989       case MSG_EXT_SDTR:
4990       {
4991         
4992         if (p->msg_buf[1] != MSG_EXT_SDTR_LEN)
4993         {
4994           reject = TRUE;
4995           break;
4996         }
4997
4998         if (p->msg_len < (MSG_EXT_SDTR_LEN + 2))
4999         {
5000           break;
5001         }
5002
5003         period = new_period = p->msg_buf[3];
5004         offset = new_offset = p->msg_buf[4];
5005         trans_options = new_trans_options = 0;
5006         bus_width = new_bus_width = target_scsirate & WIDEXFER;
5007
5008         /*
5009          * If our current max syncrate is in the Ultra3 range, bump it back
5010          * down to Ultra2 since we can't negotiate DT transfers using SDTR
5011          */
5012         if(maxsync == AHC_SYNCRATE_ULTRA3)
5013           maxsync = AHC_SYNCRATE_ULTRA2;
5014
5015         /*
5016          * We might have a device that is starting negotiation with us
5017          * before we can start up negotiation with it....be prepared to
5018          * have a device ask for a higher speed then we want to give it
5019          * in that case
5020          */
5021         if ( (scb->flags & (SCB_MSGOUT_SENT|SCB_MSGOUT_SDTR)) !=
5022              (SCB_MSGOUT_SENT|SCB_MSGOUT_SDTR) )
5023         {
5024           if (!(aic_dev->flags & DEVICE_DTR_SCANNED))
5025           {
5026             /*
5027              * We shouldn't get here unless this is a narrow drive, wide
5028              * devices should trigger this same section of code in the WDTR
5029              * handler first instead.
5030              */
5031             aic_dev->goal.width = MSG_EXT_WDTR_BUS_8_BIT;
5032             aic_dev->goal.options = 0;
5033             if(p->user[tindex].offset)
5034             {
5035               aic_dev->needsdtr_copy = 1;
5036               aic_dev->goal.period = max_t(unsigned char, 10,p->user[tindex].period);
5037               if(p->features & AHC_ULTRA2)
5038               {
5039                 aic_dev->goal.offset = MAX_OFFSET_ULTRA2;
5040               }
5041               else
5042               {
5043                 aic_dev->goal.offset = MAX_OFFSET_8BIT;
5044               }
5045             }
5046             else
5047             {
5048               aic_dev->needsdtr_copy = 0;
5049               aic_dev->goal.period = 255;
5050               aic_dev->goal.offset = 0;
5051             }
5052             aic_dev->flags |= DEVICE_DTR_SCANNED | DEVICE_PRINT_DTR;
5053           }
5054           else if (aic_dev->needsdtr_copy == 0)
5055           {
5056             /*
5057              * This is a preemptive message from the target, we've already
5058              * scanned this target and set our options for it, and we
5059              * don't need a SDTR with this target (for whatever reason),
5060              * so reject this incoming SDTR
5061              */
5062             reject = TRUE;
5063             break;
5064           }
5065
5066           /* The device is sending this message first and we have to reply */
5067           reply = TRUE;
5068           
5069           if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
5070           {
5071             printk(INFO_LEAD "Received pre-emptive SDTR message from "
5072                    "target.\n", p->host_no, CTL_OF_SCB(scb));
5073           }
5074           /*
5075            * Validate the values the device passed to us against our SEEPROM
5076            * settings.  We don't have to do this if we aren't replying since
5077            * the device isn't allowed to send values greater than the ones
5078            * we first sent to it.
5079            */
5080           new_period = max_t(unsigned int, period, aic_dev->goal.period);
5081           new_offset = min_t(unsigned int, offset, aic_dev->goal.offset);
5082         }
5083  
5084         /*
5085          * Use our new_period, new_offset, bus_width, and card options
5086          * to determine the actual syncrate settings
5087          */
5088         syncrate = aic7xxx_find_syncrate(p, &new_period, maxsync,
5089                                          &trans_options);
5090         aic7xxx_validate_offset(p, syncrate, &new_offset, bus_width);
5091
5092         /*
5093          * Did we drop to async?  If so, send a reply regardless of whether
5094          * or not we initiated this negotiation.
5095          */
5096         if ((new_offset == 0) && (new_offset != offset))
5097         {
5098           aic_dev->needsdtr_copy = 0;
5099           reply = TRUE;
5100         }
5101         
5102         /*
5103          * Did we start this, if not, or if we went too low and had to
5104          * go async, then send an SDTR back to the target
5105          */
5106         if(reply)
5107         {
5108           /* when sending a reply, make sure that the goal settings are
5109            * updated along with current and active since the code that
5110            * will actually build the message for the sequencer uses the
5111            * goal settings as its guidelines.
5112            */
5113           aic7xxx_set_syncrate(p, syncrate, target, channel, new_period,
5114                                new_offset, trans_options,
5115                                AHC_TRANS_GOAL|AHC_TRANS_ACTIVE|AHC_TRANS_CUR,
5116                                aic_dev);
5117           scb->flags &= ~SCB_MSGOUT_BITS;
5118           scb->flags |= SCB_MSGOUT_SDTR;
5119           aic_outb(p, HOST_MSG, MSG_OUT);
5120           aic_outb(p, aic_inb(p, SCSISIGO) | ATNO, SCSISIGO);
5121         }
5122         else
5123         {
5124           aic7xxx_set_syncrate(p, syncrate, target, channel, new_period,
5125                                new_offset, trans_options,
5126                                AHC_TRANS_ACTIVE|AHC_TRANS_CUR, aic_dev);
5127           aic_dev->needsdtr = 0;
5128         }
5129         done = TRUE;
5130         break;
5131       }
5132       case MSG_EXT_WDTR:
5133       {
5134           
5135         if (p->msg_buf[1] != MSG_EXT_WDTR_LEN)
5136         {
5137           reject = TRUE;
5138           break;
5139         }
5140
5141         if (p->msg_len < (MSG_EXT_WDTR_LEN + 2))
5142         {
5143           break;
5144         }
5145
5146         bus_width = new_bus_width = p->msg_buf[3];
5147
5148         if ( (scb->flags & (SCB_MSGOUT_SENT|SCB_MSGOUT_WDTR)) ==
5149              (SCB_MSGOUT_SENT|SCB_MSGOUT_WDTR) )
5150         {
5151           switch(bus_width)
5152           {
5153             default:
5154             {
5155               reject = TRUE;
5156               if ( (aic7xxx_verbose & VERBOSE_NEGOTIATION2) &&
5157                    ((aic_dev->flags & DEVICE_PRINT_DTR) ||
5158                     (aic7xxx_verbose > 0xffff)) )
5159               {
5160                 printk(INFO_LEAD "Requesting %d bit transfers, rejecting.\n",
5161                   p->host_no, CTL_OF_SCB(scb), 8 * (0x01 << bus_width));
5162               }
5163             } /* We fall through on purpose */
5164             case MSG_EXT_WDTR_BUS_8_BIT:
5165             {
5166               aic_dev->goal.width = MSG_EXT_WDTR_BUS_8_BIT;
5167               aic_dev->needwdtr_copy &= ~target_mask;
5168               break;
5169             }
5170             case MSG_EXT_WDTR_BUS_16_BIT:
5171             {
5172               break;
5173             }
5174           }
5175           aic_dev->needwdtr = 0;
5176           aic7xxx_set_width(p, target, channel, lun, new_bus_width,
5177                             AHC_TRANS_ACTIVE|AHC_TRANS_CUR, aic_dev);
5178         }
5179         else
5180         {
5181           if ( !(aic_dev->flags & DEVICE_DTR_SCANNED) )
5182           {
5183             /* 
5184              * Well, we now know the WDTR and SYNC caps of this device since
5185              * it contacted us first, mark it as such and copy the user stuff
5186              * over to the goal stuff.
5187              */
5188             if( (p->features & AHC_WIDE) && p->user[tindex].width )
5189             {
5190               aic_dev->goal.width = MSG_EXT_WDTR_BUS_16_BIT;
5191               aic_dev->needwdtr_copy = 1;
5192             }
5193             
5194             /*
5195              * Devices that support DT transfers don't start WDTR requests
5196              */
5197             aic_dev->goal.options = 0;
5198
5199             if(p->user[tindex].offset)
5200             {
5201               aic_dev->needsdtr_copy = 1;
5202               aic_dev->goal.period = max_t(unsigned char, 10, p->user[tindex].period);
5203               if(p->features & AHC_ULTRA2)
5204               {
5205                 aic_dev->goal.offset = MAX_OFFSET_ULTRA2;
5206               }
5207               else if( aic_dev->goal.width )
5208               {
5209                 aic_dev->goal.offset = MAX_OFFSET_16BIT;
5210               }
5211               else
5212               {
5213                 aic_dev->goal.offset = MAX_OFFSET_8BIT;
5214               }
5215             } else {
5216               aic_dev->needsdtr_copy = 0;
5217               aic_dev->goal.period = 255;
5218               aic_dev->goal.offset = 0;
5219             }
5220             
5221             aic_dev->flags |= DEVICE_DTR_SCANNED | DEVICE_PRINT_DTR;
5222           }
5223           else if (aic_dev->needwdtr_copy == 0)
5224           {
5225             /*
5226              * This is a preemptive message from the target, we've already
5227              * scanned this target and set our options for it, and we
5228              * don't need a WDTR with this target (for whatever reason),
5229              * so reject this incoming WDTR
5230              */
5231             reject = TRUE;
5232             break;
5233           }
5234
5235           /* The device is sending this message first and we have to reply */
5236           reply = TRUE;
5237
5238           if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
5239           {
5240             printk(INFO_LEAD "Received pre-emptive WDTR message from "
5241                    "target.\n", p->host_no, CTL_OF_SCB(scb));
5242           }
5243           switch(bus_width)
5244           {
5245             case MSG_EXT_WDTR_BUS_16_BIT:
5246             {
5247               if ( (p->features & AHC_WIDE) &&
5248                    (aic_dev->goal.width == MSG_EXT_WDTR_BUS_16_BIT) )
5249               {
5250                 new_bus_width = MSG_EXT_WDTR_BUS_16_BIT;
5251                 break;
5252               }
5253             } /* Fall through if we aren't a wide card */
5254             default:
5255             case MSG_EXT_WDTR_BUS_8_BIT:
5256             {
5257               aic_dev->needwdtr_copy = 0;
5258               new_bus_width = MSG_EXT_WDTR_BUS_8_BIT;
5259               break;
5260             }
5261           }
5262           scb->flags &= ~SCB_MSGOUT_BITS;
5263           scb->flags |= SCB_MSGOUT_WDTR;
5264           aic_dev->needwdtr = 0;
5265           if(aic_dev->dtr_pending == 0)
5266           {
5267             /* there is no other command with SCB_DTR_SCB already set that will
5268              * trigger the release of the dtr_pending bit.  Both set the bit
5269              * and set scb->flags |= SCB_DTR_SCB
5270              */
5271             aic_dev->dtr_pending = 1;
5272             scb->flags |= SCB_DTR_SCB;
5273           }
5274           aic_outb(p, HOST_MSG, MSG_OUT);
5275           aic_outb(p, aic_inb(p, SCSISIGO) | ATNO, SCSISIGO);
5276           /* when sending a reply, make sure that the goal settings are
5277            * updated along with current and active since the code that
5278            * will actually build the message for the sequencer uses the
5279            * goal settings as its guidelines.
5280            */
5281           aic7xxx_set_width(p, target, channel, lun, new_bus_width,
5282                           AHC_TRANS_GOAL|AHC_TRANS_ACTIVE|AHC_TRANS_CUR,
5283                           aic_dev);
5284         }
5285         
5286         /*
5287          * By virtue of the SCSI spec, a WDTR message negates any existing
5288          * SDTR negotiations.  So, even if needsdtr isn't marked for this
5289          * device, we still have to do a new SDTR message if the device
5290          * supports SDTR at all.  Therefore, we check needsdtr_copy instead
5291          * of needstr.
5292          */
5293         aic7xxx_set_syncrate(p, NULL, target, channel, 0, 0, 0,
5294                              AHC_TRANS_ACTIVE|AHC_TRANS_CUR|AHC_TRANS_QUITE,
5295                              aic_dev);
5296         aic_dev->needsdtr = aic_dev->needsdtr_copy;
5297         done = TRUE;
5298         break;
5299       }
5300       case MSG_EXT_PPR:
5301       {
5302         
5303         if (p->msg_buf[1] != MSG_EXT_PPR_LEN)
5304         {
5305           reject = TRUE;
5306           break;
5307         }
5308
5309         if (p->msg_len < (MSG_EXT_PPR_LEN + 2))
5310         {
5311           break;
5312         }
5313
5314         period = new_period = p->msg_buf[3];
5315         offset = new_offset = p->msg_buf[5];
5316         bus_width = new_bus_width = p->msg_buf[6];
5317         trans_options = new_trans_options = p->msg_buf[7] & 0xf;
5318
5319         if(aic7xxx_verbose & VERBOSE_NEGOTIATION2)
5320         {
5321           printk(INFO_LEAD "Parsing PPR message (%d/%d/%d/%d)\n",
5322                  p->host_no, CTL_OF_SCB(scb), period, offset, bus_width,
5323                  trans_options);
5324         }
5325
5326         /*
5327          * We might have a device that is starting negotiation with us
5328          * before we can start up negotiation with it....be prepared to
5329          * have a device ask for a higher speed then we want to give it
5330          * in that case
5331          */
5332         if ( (scb->flags & (SCB_MSGOUT_SENT|SCB_MSGOUT_PPR)) !=
5333              (SCB_MSGOUT_SENT|SCB_MSGOUT_PPR) )
5334         { 
5335           /* Have we scanned the device yet? */
5336           if (!(aic_dev->flags & DEVICE_DTR_SCANNED))
5337           {
5338             /* The device is electing to use PPR messages, so we will too until
5339              * we know better */
5340             aic_dev->needppr = aic_dev->needppr_copy = 1;
5341             aic_dev->needsdtr = aic_dev->needsdtr_copy = 0;
5342             aic_dev->needwdtr = aic_dev->needwdtr_copy = 0;
5343           
5344             /* We know the device is SCSI-3 compliant due to PPR */
5345             aic_dev->flags |= DEVICE_SCSI_3;
5346           
5347             /*
5348              * Not only is the device starting this up, but it also hasn't
5349              * been scanned yet, so this would likely be our TUR or our
5350              * INQUIRY command at scan time, so we need to use the
5351              * settings from the SEEPROM if they existed.  Of course, even
5352              * if we didn't find a SEEPROM, we stuffed default values into
5353              * the user settings anyway, so use those in all cases.
5354              */
5355             aic_dev->goal.width = p->user[tindex].width;
5356             if(p->user[tindex].offset)
5357             {
5358               aic_dev->goal.period = p->user[tindex].period;
5359               aic_dev->goal.options = p->user[tindex].options;
5360               if(p->features & AHC_ULTRA2)
5361               {
5362                 aic_dev->goal.offset = MAX_OFFSET_ULTRA2;
5363               }
5364               else if( aic_dev->goal.width &&
5365                        (bus_width == MSG_EXT_WDTR_BUS_16_BIT) &&
5366                        p->features & AHC_WIDE )
5367               {
5368                 aic_dev->goal.offset = MAX_OFFSET_16BIT;
5369               }
5370               else
5371               {
5372                 aic_dev->goal.offset = MAX_OFFSET_8BIT;
5373               }
5374             }
5375             else
5376             {
5377               aic_dev->goal.period = 255;
5378               aic_dev->goal.offset = 0;
5379               aic_dev->goal.options = 0;
5380             }
5381             aic_dev->flags |= DEVICE_DTR_SCANNED | DEVICE_PRINT_DTR;
5382           }
5383           else if (aic_dev->needppr_copy == 0)
5384           {
5385             /*
5386              * This is a preemptive message from the target, we've already
5387              * scanned this target and set our options for it, and we
5388              * don't need a PPR with this target (for whatever reason),
5389              * so reject this incoming PPR
5390              */
5391             reject = TRUE;
5392             break;
5393           }
5394
5395           /* The device is sending this message first and we have to reply */
5396           reply = TRUE;
5397           
5398           if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
5399           {
5400             printk(INFO_LEAD "Received pre-emptive PPR message from "
5401                    "target.\n", p->host_no, CTL_OF_SCB(scb));
5402           }
5403
5404         }
5405
5406         switch(bus_width)
5407         {
5408           case MSG_EXT_WDTR_BUS_16_BIT:
5409           {
5410             if ( (aic_dev->goal.width == MSG_EXT_WDTR_BUS_16_BIT) &&
5411                             p->features & AHC_WIDE)
5412             {
5413               break;
5414             }
5415           }
5416           default:
5417           {
5418             if ( (aic7xxx_verbose & VERBOSE_NEGOTIATION2) &&
5419                  ((aic_dev->flags & DEVICE_PRINT_DTR) ||
5420                   (aic7xxx_verbose > 0xffff)) )
5421             {
5422               reply = TRUE;
5423               printk(INFO_LEAD "Requesting %d bit transfers, rejecting.\n",
5424                 p->host_no, CTL_OF_SCB(scb), 8 * (0x01 << bus_width));
5425             }
5426           } /* We fall through on purpose */
5427           case MSG_EXT_WDTR_BUS_8_BIT:
5428           {
5429             /*
5430              * According to the spec, if we aren't wide, we also can't be
5431              * Dual Edge so clear the options byte
5432              */
5433             new_trans_options = 0;
5434             new_bus_width = MSG_EXT_WDTR_BUS_8_BIT;
5435             break;
5436           }
5437         }
5438
5439         if(reply)
5440         {
5441           /* when sending a reply, make sure that the goal settings are
5442            * updated along with current and active since the code that
5443            * will actually build the message for the sequencer uses the
5444            * goal settings as its guidelines.
5445            */
5446           aic7xxx_set_width(p, target, channel, lun, new_bus_width,
5447                             AHC_TRANS_GOAL|AHC_TRANS_ACTIVE|AHC_TRANS_CUR,
5448                             aic_dev);
5449           syncrate = aic7xxx_find_syncrate(p, &new_period, maxsync,
5450                                            &new_trans_options);
5451           aic7xxx_validate_offset(p, syncrate, &new_offset, new_bus_width);
5452           aic7xxx_set_syncrate(p, syncrate, target, channel, new_period,
5453                                new_offset, new_trans_options,
5454                                AHC_TRANS_GOAL|AHC_TRANS_ACTIVE|AHC_TRANS_CUR,
5455                                aic_dev);
5456         }
5457         else
5458         {
5459           aic7xxx_set_width(p, target, channel, lun, new_bus_width,
5460                             AHC_TRANS_ACTIVE|AHC_TRANS_CUR, aic_dev);
5461           syncrate = aic7xxx_find_syncrate(p, &new_period, maxsync,
5462                                            &new_trans_options);
5463           aic7xxx_validate_offset(p, syncrate, &new_offset, new_bus_width);
5464           aic7xxx_set_syncrate(p, syncrate, target, channel, new_period,
5465                                new_offset, new_trans_options,
5466                                AHC_TRANS_ACTIVE|AHC_TRANS_CUR, aic_dev);
5467         }
5468
5469         /*
5470          * As it turns out, if we don't *have* to have PPR messages, then
5471          * configure ourselves not to use them since that makes some
5472          * external drive chassis work (those chassis can't parse PPR
5473          * messages and they mangle the SCSI bus until you send a WDTR
5474          * and SDTR that they can understand).
5475          */
5476         if(new_trans_options == 0)
5477         {
5478           aic_dev->needppr = aic_dev->needppr_copy = 0;
5479           if(new_offset)
5480           {
5481             aic_dev->needsdtr = aic_dev->needsdtr_copy = 1;
5482           }
5483           if (new_bus_width)
5484           {
5485             aic_dev->needwdtr = aic_dev->needwdtr_copy = 1;
5486           }
5487         }
5488
5489         if((new_offset == 0) && (offset != 0))
5490         {
5491           /*
5492            * Oops, the syncrate went to low for this card and we fell off
5493            * to async (should never happen with a device that uses PPR
5494            * messages, but have to be complete)
5495            */
5496           reply = TRUE;
5497         }
5498
5499         if(reply)
5500         {
5501           scb->flags &= ~SCB_MSGOUT_BITS;
5502           scb->flags |= SCB_MSGOUT_PPR;
5503           aic_outb(p, HOST_MSG, MSG_OUT);
5504           aic_outb(p, aic_inb(p, SCSISIGO) | ATNO, SCSISIGO);
5505         }
5506         else
5507         {
5508           aic_dev->needppr = 0;
5509         }
5510         done = TRUE;
5511         break;
5512       }
5513       default:
5514       {
5515         reject = TRUE;
5516         break;
5517       }
5518     } /* end of switch(p->msg_type) */
5519   } /* end of if (!reject && (p->msg_len > 2)) */
5520
5521   if (!reply && reject)
5522   {
5523     aic_outb(p, MSG_MESSAGE_REJECT, MSG_OUT);
5524     aic_outb(p, aic_inb(p, SCSISIGO) | ATNO, SCSISIGO);
5525     done = TRUE;
5526   }
5527   return(done);
5528 }
5529
5530
5531 /*+F*************************************************************************
5532  * Function:
5533  *   aic7xxx_handle_reqinit
5534  *
5535  * Description:
5536  *   Interrupt handler for REQINIT interrupts (used to transfer messages to
5537  *    and from devices).
5538  *_F*************************************************************************/
5539 static void
5540 aic7xxx_handle_reqinit(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
5541 {
5542   unsigned char lastbyte;
5543   unsigned char phasemis;
5544   int done = FALSE;
5545
5546   switch(p->msg_type)
5547   {
5548     case MSG_TYPE_INITIATOR_MSGOUT:
5549       {
5550         if (p->msg_len == 0)
5551           panic("aic7xxx: REQINIT with no active message!\n");
5552
5553         lastbyte = (p->msg_index == (p->msg_len - 1));
5554         phasemis = ( aic_inb(p, SCSISIGI) & PHASE_MASK) != P_MESGOUT;
5555
5556         if (lastbyte || phasemis)
5557         {
5558           /* Time to end the message */
5559           p->msg_len = 0;
5560           p->msg_type = MSG_TYPE_NONE;
5561           /*
5562            * NOTE-TO-MYSELF: If you clear the REQINIT after you
5563            * disable REQINITs, then cases of REJECT_MSG stop working
5564            * and hang the bus
5565            */
5566           aic_outb(p, aic_inb(p, SIMODE1) & ~ENREQINIT, SIMODE1);
5567           aic_outb(p, CLRSCSIINT, CLRINT);
5568           p->flags &= ~AHC_HANDLING_REQINITS;
5569
5570           if (phasemis == 0)
5571           {
5572             aic_outb(p, p->msg_buf[p->msg_index], SINDEX);
5573             aic_outb(p, 0, RETURN_1);
5574 #ifdef AIC7XXX_VERBOSE_DEBUGGING
5575             if (aic7xxx_verbose > 0xffff)
5576               printk(INFO_LEAD "Completed sending of REQINIT message.\n",
5577                      p->host_no, CTL_OF_SCB(scb));
5578 #endif
5579           }
5580           else
5581           {
5582             aic_outb(p, MSGOUT_PHASEMIS, RETURN_1);
5583 #ifdef AIC7XXX_VERBOSE_DEBUGGING
5584             if (aic7xxx_verbose > 0xffff)
5585               printk(INFO_LEAD "PHASEMIS while sending REQINIT message.\n",
5586                      p->host_no, CTL_OF_SCB(scb));
5587 #endif
5588           }
5589           unpause_sequencer(p, TRUE);
5590         }
5591         else
5592         {
5593           /*
5594            * Present the byte on the bus (clearing REQINIT) but don't
5595            * unpause the sequencer.
5596            */
5597           aic_outb(p, CLRREQINIT, CLRSINT1);
5598           aic_outb(p, CLRSCSIINT, CLRINT);
5599           aic_outb(p,  p->msg_buf[p->msg_index++], SCSIDATL);
5600         }
5601         break;
5602       }
5603     case MSG_TYPE_INITIATOR_MSGIN:
5604       {
5605         phasemis = ( aic_inb(p, SCSISIGI) & PHASE_MASK ) != P_MESGIN;
5606
5607         if (phasemis == 0)
5608         {
5609           p->msg_len++;
5610           /* Pull the byte in without acking it */
5611           p->msg_buf[p->msg_index] = aic_inb(p, SCSIBUSL);
5612           done = aic7xxx_parse_msg(p, scb);
5613           /* Ack the byte */
5614           aic_outb(p, CLRREQINIT, CLRSINT1);
5615           aic_outb(p, CLRSCSIINT, CLRINT);
5616           aic_inb(p, SCSIDATL);
5617           p->msg_index++;
5618         }
5619         if (phasemis || done)
5620         {
5621 #ifdef AIC7XXX_VERBOSE_DEBUGGING
5622           if (aic7xxx_verbose > 0xffff)
5623           {
5624             if (phasemis)
5625               printk(INFO_LEAD "PHASEMIS while receiving REQINIT message.\n",
5626                      p->host_no, CTL_OF_SCB(scb));
5627             else
5628               printk(INFO_LEAD "Completed receipt of REQINIT message.\n",
5629                      p->host_no, CTL_OF_SCB(scb));
5630           }
5631 #endif
5632           /* Time to end our message session */
5633           p->msg_len = 0;
5634           p->msg_type = MSG_TYPE_NONE;
5635           aic_outb(p, aic_inb(p, SIMODE1) & ~ENREQINIT, SIMODE1);
5636           aic_outb(p, CLRSCSIINT, CLRINT);
5637           p->flags &= ~AHC_HANDLING_REQINITS;
5638           unpause_sequencer(p, TRUE);
5639         }
5640         break;
5641       }
5642     default:
5643       {
5644         panic("aic7xxx: Unknown REQINIT message type.\n");
5645         break;
5646       }
5647   } /* End of switch(p->msg_type) */
5648 }
5649
5650 /*+F*************************************************************************
5651  * Function:
5652  *   aic7xxx_handle_scsiint
5653  *
5654  * Description:
5655  *   Interrupt handler for SCSI interrupts (SCSIINT).
5656  *-F*************************************************************************/
5657 static void
5658 aic7xxx_handle_scsiint(struct aic7xxx_host *p, unsigned char intstat)
5659 {
5660   unsigned char scb_index;
5661   unsigned char status;
5662   struct aic7xxx_scb *scb;
5663   struct aic_dev_data *aic_dev;
5664
5665   scb_index = aic_inb(p, SCB_TAG);
5666   status = aic_inb(p, SSTAT1);
5667
5668   if (scb_index < p->scb_data->numscbs)
5669   {
5670     scb = p->scb_data->scb_array[scb_index];
5671     if ((scb->flags & SCB_ACTIVE) == 0)
5672     {
5673       scb = NULL;
5674     }
5675   }
5676   else
5677   {
5678     scb = NULL;
5679   }
5680
5681
5682   if ((status & SCSIRSTI) != 0)
5683   {
5684     int channel;
5685
5686     if ( (p->chip & AHC_CHIPID_MASK) == AHC_AIC7770 )
5687       channel = (aic_inb(p, SBLKCTL) & SELBUSB) >> 3;
5688     else
5689       channel = 0;
5690
5691     if (aic7xxx_verbose & VERBOSE_RESET)
5692       printk(WARN_LEAD "Someone else reset the channel!!\n",
5693            p->host_no, channel, -1, -1);
5694     if (aic7xxx_panic_on_abort)
5695       aic7xxx_panic_abort(p, NULL);
5696     /*
5697      * Go through and abort all commands for the channel, but do not
5698      * reset the channel again.
5699      */
5700     aic7xxx_reset_channel(p, channel, /* Initiate Reset */ FALSE);
5701     aic7xxx_run_done_queue(p, TRUE);
5702     scb = NULL;
5703   }
5704   else if ( ((status & BUSFREE) != 0) && ((status & SELTO) == 0) )
5705   {
5706     /*
5707      * First look at what phase we were last in.  If it's message-out,
5708      * chances are pretty good that the bus free was in response to
5709      * one of our abort requests.
5710      */
5711     unsigned char lastphase = aic_inb(p, LASTPHASE);
5712     unsigned char saved_tcl = aic_inb(p, SAVED_TCL);
5713     unsigned char target = (saved_tcl >> 4) & 0x0F;
5714     int channel;
5715     int printerror = TRUE;
5716
5717     if ( (p->chip & AHC_CHIPID_MASK) == AHC_AIC7770 )
5718       channel = (aic_inb(p, SBLKCTL) & SELBUSB) >> 3;
5719     else
5720       channel = 0;
5721
5722     aic_outb(p, aic_inb(p, SCSISEQ) & (ENSELI|ENRSELI|ENAUTOATNP),
5723              SCSISEQ);
5724     if (lastphase == P_MESGOUT)
5725     {
5726       unsigned char message;
5727
5728       message = aic_inb(p, SINDEX);
5729
5730       if ((message == MSG_ABORT) || (message == MSG_ABORT_TAG))
5731       {
5732         if (aic7xxx_verbose & VERBOSE_ABORT_PROCESS)
5733           printk(INFO_LEAD "SCB %d abort delivered.\n", p->host_no,
5734             CTL_OF_SCB(scb), scb->hscb->tag);
5735         aic7xxx_reset_device(p, target, channel, ALL_LUNS,
5736                 (message == MSG_ABORT) ? SCB_LIST_NULL : scb->hscb->tag );
5737         aic7xxx_run_done_queue(p, TRUE);
5738         scb = NULL;
5739         printerror = 0;
5740       }
5741       else if (message == MSG_BUS_DEV_RESET)
5742       {
5743         aic7xxx_handle_device_reset(p, target, channel);
5744         scb = NULL;
5745         printerror = 0;
5746       }
5747     }
5748     if ( (scb != NULL) && (scb->flags & SCB_DTR_SCB) ) 
5749     {
5750       /*
5751        * Hmmm...error during a negotiation command.  Either we have a
5752        * borken bus, or the device doesn't like our negotiation message.
5753        * Since we check the INQUIRY data of a device before sending it
5754        * negotiation messages, assume the bus is borken for whatever
5755        * reason.  Complete the command.
5756        */
5757       printerror = 0;
5758       aic7xxx_reset_device(p, target, channel, ALL_LUNS, scb->hscb->tag);
5759       aic7xxx_run_done_queue(p, TRUE);
5760       scb = NULL;
5761     }
5762     if (printerror != 0)
5763     {
5764       if (scb != NULL)
5765       {
5766         unsigned char tag;
5767
5768         if ((scb->hscb->control & TAG_ENB) != 0)
5769         {
5770           tag = scb->hscb->tag;
5771         }
5772         else
5773         {
5774           tag = SCB_LIST_NULL;
5775         }
5776         aic7xxx_reset_device(p, target, channel, ALL_LUNS, tag);
5777         aic7xxx_run_done_queue(p, TRUE);
5778       }
5779       else
5780       {
5781         aic7xxx_reset_device(p, target, channel, ALL_LUNS, SCB_LIST_NULL);
5782         aic7xxx_run_done_queue(p, TRUE);
5783       }
5784       printk(INFO_LEAD "Unexpected busfree, LASTPHASE = 0x%x, "
5785              "SEQADDR = 0x%x\n", p->host_no, channel, target, -1, lastphase,
5786              (aic_inb(p, SEQADDR1) << 8) | aic_inb(p, SEQADDR0));
5787       scb = NULL;
5788     }
5789     aic_outb(p, MSG_NOOP, MSG_OUT);
5790     aic_outb(p, aic_inb(p, SIMODE1) & ~(ENBUSFREE|ENREQINIT),
5791       SIMODE1);
5792     p->flags &= ~AHC_HANDLING_REQINITS;
5793     aic_outb(p, CLRBUSFREE, CLRSINT1);
5794     aic_outb(p, CLRSCSIINT, CLRINT);
5795     restart_sequencer(p);
5796     unpause_sequencer(p, TRUE);
5797   }
5798   else if ((status & SELTO) != 0)
5799   {
5800         unsigned char scbptr;
5801         unsigned char nextscb;
5802         struct scsi_cmnd *cmd;
5803
5804     scbptr = aic_inb(p, WAITING_SCBH);
5805     if (scbptr > p->scb_data->maxhscbs)
5806     {
5807       /*
5808        * I'm still trying to track down exactly how this happens, but until
5809        * I find it, this code will make sure we aren't passing bogus values
5810        * into the SCBPTR register, even if that register will just wrap
5811        * things around, we still don't like having out of range variables.
5812        *
5813        * NOTE: Don't check the aic7xxx_verbose variable, I want this message
5814        * to always be displayed.
5815        */
5816       printk(INFO_LEAD "Invalid WAITING_SCBH value %d, improvising.\n",
5817              p->host_no, -1, -1, -1, scbptr);
5818       if (p->scb_data->maxhscbs > 4)
5819         scbptr &= (p->scb_data->maxhscbs - 1);
5820       else
5821         scbptr &= 0x03;
5822     }
5823     aic_outb(p, scbptr, SCBPTR);
5824     scb_index = aic_inb(p, SCB_TAG);
5825
5826     scb = NULL;
5827     if (scb_index < p->scb_data->numscbs)
5828     {
5829       scb = p->scb_data->scb_array[scb_index];
5830       if ((scb->flags & SCB_ACTIVE) == 0)
5831       {
5832         scb = NULL;
5833       }
5834     }
5835     if (scb == NULL)
5836     {
5837       printk(WARN_LEAD "Referenced SCB %d not valid during SELTO.\n",
5838              p->host_no, -1, -1, -1, scb_index);
5839       printk(KERN_WARNING "        SCSISEQ = 0x%x SEQADDR = 0x%x SSTAT0 = 0x%x "
5840              "SSTAT1 = 0x%x\n", aic_inb(p, SCSISEQ),
5841              aic_inb(p, SEQADDR0) | (aic_inb(p, SEQADDR1) << 8),
5842              aic_inb(p, SSTAT0), aic_inb(p, SSTAT1));
5843       if (aic7xxx_panic_on_abort)
5844         aic7xxx_panic_abort(p, NULL);
5845     }
5846     else
5847     {
5848       cmd = scb->cmd;
5849       cmd->result = (DID_TIME_OUT << 16);
5850
5851       /*
5852        * Clear out this hardware SCB
5853        */
5854       aic_outb(p, 0, SCB_CONTROL);
5855
5856       /*
5857        * Clear out a few values in the card that are in an undetermined
5858        * state.
5859        */
5860       aic_outb(p, MSG_NOOP, MSG_OUT);
5861
5862       /*
5863        * Shift the waiting for selection queue forward
5864        */
5865       nextscb = aic_inb(p, SCB_NEXT);
5866       aic_outb(p, nextscb, WAITING_SCBH);
5867
5868       /*
5869        * Put this SCB back on the free list.
5870        */
5871       aic7xxx_add_curscb_to_free_list(p);
5872 #ifdef AIC7XXX_VERBOSE_DEBUGGING
5873       if (aic7xxx_verbose > 0xffff)
5874         printk(INFO_LEAD "Selection Timeout.\n", p->host_no, CTL_OF_SCB(scb));
5875 #endif
5876       if (scb->flags & SCB_QUEUED_ABORT)
5877       {
5878         /*
5879          * We know that this particular SCB had to be the queued abort since
5880          * the disconnected SCB would have gotten a reconnect instead.
5881          * What we need to do then is to let the command timeout again so
5882          * we get a reset since this abort just failed.
5883          */
5884         cmd->result = 0;
5885         scb = NULL;
5886       }
5887     }
5888     /*
5889      * Keep the sequencer from trying to restart any selections
5890      */
5891     aic_outb(p, aic_inb(p, SCSISEQ) & ~ENSELO, SCSISEQ);
5892     /*
5893      * Make sure the data bits on the bus are released
5894      * Don't do this on 7770 chipsets, it makes them give us
5895      * a BRKADDRINT and kills the card.
5896      */
5897     if( (p->chip & ~AHC_CHIPID_MASK) == AHC_PCI )
5898       aic_outb(p, 0, SCSIBUSL);
5899
5900     /*
5901      * Delay for the selection timeout delay period then stop the selection
5902      */
5903     udelay(301);
5904     aic_outb(p, CLRSELINGO, CLRSINT0);
5905     /*
5906      * Clear out all the interrupt status bits
5907      */
5908     aic_outb(p, aic_inb(p, SIMODE1) & ~(ENREQINIT|ENBUSFREE), SIMODE1);
5909     p->flags &= ~AHC_HANDLING_REQINITS;
5910     aic_outb(p, CLRSELTIMEO | CLRBUSFREE, CLRSINT1);
5911     aic_outb(p, CLRSCSIINT, CLRINT);
5912     /*
5913      * Restarting the sequencer will stop the selection and make sure devices
5914      * are allowed to reselect in.
5915      */
5916     restart_sequencer(p);
5917     unpause_sequencer(p, TRUE);
5918   }
5919   else if (scb == NULL)
5920   {
5921     printk(WARN_LEAD "aic7xxx_isr - referenced scb not valid "
5922            "during scsiint 0x%x scb(%d)\n"
5923            "      SIMODE0 0x%x, SIMODE1 0x%x, SSTAT0 0x%x, SEQADDR 0x%x\n",
5924            p->host_no, -1, -1, -1, status, scb_index, aic_inb(p, SIMODE0),
5925            aic_inb(p, SIMODE1), aic_inb(p, SSTAT0),
5926            (aic_inb(p, SEQADDR1) << 8) | aic_inb(p, SEQADDR0));
5927     /*
5928      * Turn off the interrupt and set status to zero, so that it
5929      * falls through the rest of the SCSIINT code.
5930      */
5931     aic_outb(p, status, CLRSINT1);
5932     aic_outb(p, CLRSCSIINT, CLRINT);
5933     unpause_sequencer(p, /* unpause always */ TRUE);
5934     scb = NULL;
5935   }
5936   else if (status & SCSIPERR)
5937   {
5938     /*
5939      * Determine the bus phase and queue an appropriate message.
5940      */
5941         char  *phase;
5942         struct scsi_cmnd *cmd;
5943         unsigned char mesg_out = MSG_NOOP;
5944         unsigned char lastphase = aic_inb(p, LASTPHASE);
5945         unsigned char sstat2 = aic_inb(p, SSTAT2);
5946
5947     cmd = scb->cmd;
5948     switch (lastphase)
5949     {
5950       case P_DATAOUT:
5951         phase = "Data-Out";
5952         break;
5953       case P_DATAIN:
5954         phase = "Data-In";
5955         mesg_out = MSG_INITIATOR_DET_ERR;
5956         break;
5957       case P_COMMAND:
5958         phase = "Command";
5959         break;
5960       case P_MESGOUT:
5961         phase = "Message-Out";
5962         break;
5963       case P_STATUS:
5964         phase = "Status";
5965         mesg_out = MSG_INITIATOR_DET_ERR;
5966         break;
5967       case P_MESGIN:
5968         phase = "Message-In";
5969         mesg_out = MSG_PARITY_ERROR;
5970         break;
5971       default:
5972         phase = "unknown";
5973         break;
5974     }
5975
5976     /*
5977      * A parity error has occurred during a data
5978      * transfer phase. Flag it and continue.
5979      */
5980     if( (p->features & AHC_ULTRA3) && 
5981         (aic_inb(p, SCSIRATE) & AHC_SYNCRATE_CRC) &&
5982         (lastphase == P_DATAIN) )
5983     {
5984       printk(WARN_LEAD "CRC error during %s phase.\n",
5985              p->host_no, CTL_OF_SCB(scb), phase);
5986       if(sstat2 & CRCVALERR)
5987       {
5988         printk(WARN_LEAD "  CRC error in intermediate CRC packet.\n",
5989                p->host_no, CTL_OF_SCB(scb));
5990       }
5991       if(sstat2 & CRCENDERR)
5992       {
5993         printk(WARN_LEAD "  CRC error in ending CRC packet.\n",
5994                p->host_no, CTL_OF_SCB(scb));
5995       }
5996       if(sstat2 & CRCREQERR)
5997       {
5998         printk(WARN_LEAD "  Target incorrectly requested a CRC packet.\n",
5999                p->host_no, CTL_OF_SCB(scb));
6000       }
6001       if(sstat2 & DUAL_EDGE_ERROR)
6002       {
6003         printk(WARN_LEAD "  Dual Edge transmission error.\n",
6004                p->host_no, CTL_OF_SCB(scb));
6005       }
6006     }
6007     else if( (lastphase == P_MESGOUT) &&
6008              (scb->flags & SCB_MSGOUT_PPR) )
6009     {
6010       /*
6011        * As per the draft specs, any device capable of supporting any of
6012        * the option values other than 0 are not allowed to reject the
6013        * PPR message.  Instead, they must negotiate out what they do
6014        * support instead of rejecting our offering or else they cause
6015        * a parity error during msg_out phase to signal that they don't
6016        * like our settings.
6017        */
6018       aic_dev = AIC_DEV(scb->cmd);
6019       aic_dev->needppr = aic_dev->needppr_copy = 0;
6020       aic7xxx_set_width(p, scb->cmd->device->id, scb->cmd->device->channel, scb->cmd->device->lun,
6021                         MSG_EXT_WDTR_BUS_8_BIT,
6022                         (AHC_TRANS_ACTIVE|AHC_TRANS_CUR|AHC_TRANS_QUITE),
6023                         aic_dev);
6024       aic7xxx_set_syncrate(p, NULL, scb->cmd->device->id, scb->cmd->device->channel, 0, 0,
6025                            0, AHC_TRANS_ACTIVE|AHC_TRANS_CUR|AHC_TRANS_QUITE,
6026                            aic_dev);
6027       aic_dev->goal.options = 0;
6028       scb->flags &= ~SCB_MSGOUT_BITS;
6029       if(aic7xxx_verbose & VERBOSE_NEGOTIATION2)
6030       {
6031         printk(INFO_LEAD "parity error during PPR message, reverting "
6032                "to WDTR/SDTR\n", p->host_no, CTL_OF_SCB(scb));
6033       }
6034       if ( aic_dev->goal.width )
6035       {
6036         aic_dev->needwdtr = aic_dev->needwdtr_copy = 1;
6037       }
6038       if ( aic_dev->goal.offset )
6039       {
6040         if( aic_dev->goal.period <= 9 )
6041         {
6042           aic_dev->goal.period = 10;
6043         }
6044         aic_dev->needsdtr = aic_dev->needsdtr_copy = 1;
6045       }
6046       scb = NULL;
6047     }
6048
6049     /*
6050      * We've set the hardware to assert ATN if we get a parity
6051      * error on "in" phases, so all we need to do is stuff the
6052      * message buffer with the appropriate message.  "In" phases
6053      * have set mesg_out to something other than MSG_NOP.
6054      */
6055     if (mesg_out != MSG_NOOP)
6056     {
6057       aic_outb(p, mesg_out, MSG_OUT);
6058       aic_outb(p, aic_inb(p, SCSISIGI) | ATNO, SCSISIGO);
6059       scb = NULL;
6060     }
6061     aic_outb(p, CLRSCSIPERR, CLRSINT1);
6062     aic_outb(p, CLRSCSIINT, CLRINT);
6063     unpause_sequencer(p, /* unpause_always */ TRUE);
6064   }
6065   else if ( (status & REQINIT) &&
6066             (p->flags & AHC_HANDLING_REQINITS) )
6067   {
6068 #ifdef AIC7XXX_VERBOSE_DEBUGGING
6069     if (aic7xxx_verbose > 0xffff)
6070       printk(INFO_LEAD "Handling REQINIT, SSTAT1=0x%x.\n", p->host_no,
6071              CTL_OF_SCB(scb), aic_inb(p, SSTAT1));
6072 #endif
6073     aic7xxx_handle_reqinit(p, scb);
6074     return;
6075   }
6076   else
6077   {
6078     /*
6079      * We don't know what's going on. Turn off the
6080      * interrupt source and try to continue.
6081      */
6082     if (aic7xxx_verbose & VERBOSE_SCSIINT)
6083       printk(INFO_LEAD "Unknown SCSIINT status, SSTAT1(0x%x).\n",
6084         p->host_no, -1, -1, -1, status);
6085     aic_outb(p, status, CLRSINT1);
6086     aic_outb(p, CLRSCSIINT, CLRINT);
6087     unpause_sequencer(p, /* unpause always */ TRUE);
6088     scb = NULL;
6089   }
6090   if (scb != NULL)
6091   {
6092     aic7xxx_done(p, scb);
6093   }
6094 }
6095
6096 #ifdef AIC7XXX_VERBOSE_DEBUGGING
6097 static void
6098 aic7xxx_check_scbs(struct aic7xxx_host *p, char *buffer)
6099 {
6100   unsigned char saved_scbptr, free_scbh, dis_scbh, wait_scbh, temp;
6101   int i, bogus, lost;
6102   static unsigned char scb_status[AIC7XXX_MAXSCB];
6103
6104 #define SCB_NO_LIST 0
6105 #define SCB_FREE_LIST 1
6106 #define SCB_WAITING_LIST 2
6107 #define SCB_DISCONNECTED_LIST 4
6108 #define SCB_CURRENTLY_ACTIVE 8
6109
6110   /*
6111    * Note, these checks will fail on a regular basis once the machine moves
6112    * beyond the bus scan phase.  The problem is race conditions concerning
6113    * the scbs and where they are linked in.  When you have 30 or so commands
6114    * outstanding on the bus, and run this twice with every interrupt, the
6115    * chances get pretty good that you'll catch the sequencer with an SCB
6116    * only partially linked in.  Therefore, once we pass the scan phase
6117    * of the bus, we really should disable this function.
6118    */
6119   bogus = FALSE;
6120   memset(&scb_status[0], 0, sizeof(scb_status));
6121   pause_sequencer(p);
6122   saved_scbptr = aic_inb(p, SCBPTR);
6123   if (saved_scbptr >= p->scb_data->maxhscbs)
6124   {
6125     printk("Bogus SCBPTR %d\n", saved_scbptr);
6126     bogus = TRUE;
6127   }
6128   scb_status[saved_scbptr] = SCB_CURRENTLY_ACTIVE;
6129   free_scbh = aic_inb(p, FREE_SCBH);
6130   if ( (free_scbh != SCB_LIST_NULL) &&
6131        (free_scbh >= p->scb_data->maxhscbs) )
6132   {
6133     printk("Bogus FREE_SCBH %d\n", free_scbh);
6134     bogus = TRUE;
6135   }
6136   else
6137   {
6138     temp = free_scbh;
6139     while( (temp != SCB_LIST_NULL) && (temp < p->scb_data->maxhscbs) )
6140     {
6141       if(scb_status[temp] & 0x07)
6142       {
6143         printk("HSCB %d on multiple lists, status 0x%02x", temp,
6144                scb_status[temp] | SCB_FREE_LIST);
6145         bogus = TRUE;
6146       }
6147       scb_status[temp] |= SCB_FREE_LIST;
6148       aic_outb(p, temp, SCBPTR);
6149       temp = aic_inb(p, SCB_NEXT);
6150     }
6151   }
6152
6153   dis_scbh = aic_inb(p, DISCONNECTED_SCBH);
6154   if ( (dis_scbh != SCB_LIST_NULL) &&
6155        (dis_scbh >= p->scb_data->maxhscbs) )
6156   {
6157     printk("Bogus DISCONNECTED_SCBH %d\n", dis_scbh);
6158     bogus = TRUE;
6159   }
6160   else
6161   {
6162     temp = dis_scbh;
6163     while( (temp != SCB_LIST_NULL) && (temp < p->scb_data->maxhscbs) )
6164     {
6165       if(scb_status[temp] & 0x07)
6166       {
6167         printk("HSCB %d on multiple lists, status 0x%02x", temp,
6168                scb_status[temp] | SCB_DISCONNECTED_LIST);
6169         bogus = TRUE;
6170       }
6171       scb_status[temp] |= SCB_DISCONNECTED_LIST;
6172       aic_outb(p, temp, SCBPTR);
6173       temp = aic_inb(p, SCB_NEXT);
6174     }
6175   }
6176   
6177   wait_scbh = aic_inb(p, WAITING_SCBH);
6178   if ( (wait_scbh != SCB_LIST_NULL) &&
6179        (wait_scbh >= p->scb_data->maxhscbs) )
6180   {
6181     printk("Bogus WAITING_SCBH %d\n", wait_scbh);
6182     bogus = TRUE;
6183   }
6184   else
6185   {
6186     temp = wait_scbh;
6187     while( (temp != SCB_LIST_NULL) && (temp < p->scb_data->maxhscbs) )
6188     {
6189       if(scb_status[temp] & 0x07)
6190       {
6191         printk("HSCB %d on multiple lists, status 0x%02x", temp,
6192                scb_status[temp] | SCB_WAITING_LIST);
6193         bogus = TRUE;
6194       }
6195       scb_status[temp] |= SCB_WAITING_LIST;
6196       aic_outb(p, temp, SCBPTR);
6197       temp = aic_inb(p, SCB_NEXT);
6198     }
6199   }
6200
6201   lost=0;
6202   for(i=0; i < p->scb_data->maxhscbs; i++)
6203   {
6204     aic_outb(p, i, SCBPTR);
6205     temp = aic_inb(p, SCB_NEXT);
6206     if ( ((temp != SCB_LIST_NULL) &&
6207           (temp >= p->scb_data->maxhscbs)) )
6208     {
6209       printk("HSCB %d bad, SCB_NEXT invalid(%d).\n", i, temp);
6210       bogus = TRUE;
6211     }
6212     if ( temp == i )
6213     {
6214       printk("HSCB %d bad, SCB_NEXT points to self.\n", i);
6215       bogus = TRUE;
6216     }
6217     if (scb_status[i] == 0)
6218       lost++;
6219     if (lost > 1)
6220     {
6221       printk("Too many lost scbs.\n");
6222       bogus=TRUE;
6223     }
6224   }
6225   aic_outb(p, saved_scbptr, SCBPTR);
6226   unpause_sequencer(p, FALSE);
6227   if (bogus)
6228   {
6229     printk("Bogus parameters found in card SCB array structures.\n");
6230     printk("%s\n", buffer);
6231     aic7xxx_panic_abort(p, NULL);
6232   }
6233   return;
6234 }
6235 #endif
6236
6237
6238 /*+F*************************************************************************
6239  * Function:
6240  *   aic7xxx_handle_command_completion_intr
6241  *
6242  * Description:
6243  *   SCSI command completion interrupt handler.
6244  *-F*************************************************************************/
6245 static void
6246 aic7xxx_handle_command_completion_intr(struct aic7xxx_host *p)
6247 {
6248         struct aic7xxx_scb *scb = NULL;
6249         struct aic_dev_data *aic_dev;
6250         struct scsi_cmnd *cmd;
6251         unsigned char scb_index, tindex;
6252
6253 #ifdef AIC7XXX_VERBOSE_DEBUGGING
6254   if( (p->isr_count < 16) && (aic7xxx_verbose > 0xffff) )
6255     printk(INFO_LEAD "Command Complete Int.\n", p->host_no, -1, -1, -1);
6256 #endif
6257     
6258   /*
6259    * Read the INTSTAT location after clearing the CMDINT bit.  This forces
6260    * any posted PCI writes to flush to memory.  Gerard Roudier suggested
6261    * this fix to the possible race of clearing the CMDINT bit but not
6262    * having all command bytes flushed onto the qoutfifo.
6263    */
6264   aic_outb(p, CLRCMDINT, CLRINT);
6265   aic_inb(p, INTSTAT);
6266   /*
6267    * The sequencer will continue running when it
6268    * issues this interrupt. There may be >1 commands
6269    * finished, so loop until we've processed them all.
6270    */
6271
6272   while (p->qoutfifo[p->qoutfifonext] != SCB_LIST_NULL)
6273   {
6274     scb_index = p->qoutfifo[p->qoutfifonext];
6275     p->qoutfifo[p->qoutfifonext++] = SCB_LIST_NULL;
6276     if ( scb_index >= p->scb_data->numscbs )
6277     {
6278       printk(WARN_LEAD "CMDCMPLT with invalid SCB index %d\n", p->host_no,
6279         -1, -1, -1, scb_index);
6280       continue;
6281     }
6282     scb = p->scb_data->scb_array[scb_index];
6283     if (!(scb->flags & SCB_ACTIVE) || (scb->cmd == NULL))
6284     {
6285       printk(WARN_LEAD "CMDCMPLT without command for SCB %d, SCB flags "
6286         "0x%x, cmd 0x%lx\n", p->host_no, -1, -1, -1, scb_index, scb->flags,
6287         (unsigned long) scb->cmd);
6288       continue;
6289     }
6290     tindex = TARGET_INDEX(scb->cmd);
6291     aic_dev = AIC_DEV(scb->cmd);
6292     if (scb->flags & SCB_QUEUED_ABORT)
6293     {
6294       pause_sequencer(p);
6295       if ( ((aic_inb(p, LASTPHASE) & PHASE_MASK) != P_BUSFREE) &&
6296            (aic_inb(p, SCB_TAG) == scb->hscb->tag) )
6297       {
6298         unpause_sequencer(p, FALSE);
6299         continue;
6300       }
6301       aic7xxx_reset_device(p, scb->cmd->device->id, scb->cmd->device->channel,
6302         scb->cmd->device->lun, scb->hscb->tag);
6303       scb->flags &= ~(SCB_QUEUED_FOR_DONE | SCB_RESET | SCB_ABORT |
6304         SCB_QUEUED_ABORT);
6305       unpause_sequencer(p, FALSE);
6306     }
6307     else if (scb->flags & SCB_ABORT)
6308     {
6309       /*
6310        * We started to abort this, but it completed on us, let it
6311        * through as successful
6312        */
6313       scb->flags &= ~(SCB_ABORT|SCB_RESET);
6314     }
6315     else if (scb->flags & SCB_SENSE)
6316     {
6317       char *buffer = &scb->cmd->sense_buffer[0];
6318
6319       if (buffer[12] == 0x47 || buffer[12] == 0x54)
6320       {
6321         /*
6322          * Signal that we need to re-negotiate things.
6323          */
6324         aic_dev->needppr = aic_dev->needppr_copy;
6325         aic_dev->needsdtr = aic_dev->needsdtr_copy;
6326         aic_dev->needwdtr = aic_dev->needwdtr_copy;
6327       }
6328     }
6329     cmd = scb->cmd;
6330     if (scb->hscb->residual_SG_segment_count != 0)
6331     {
6332       aic7xxx_calculate_residual(p, scb);
6333     }
6334     cmd->result |= (aic7xxx_error(cmd) << 16);
6335     aic7xxx_done(p, scb);
6336   }
6337 }
6338
6339 /*+F*************************************************************************
6340  * Function:
6341  *   aic7xxx_isr
6342  *
6343  * Description:
6344  *   SCSI controller interrupt handler.
6345  *-F*************************************************************************/
6346 static void
6347 aic7xxx_isr(void *dev_id)
6348 {
6349   struct aic7xxx_host *p;
6350   unsigned char intstat;
6351
6352   p = dev_id;
6353
6354   /*
6355    * Just a few sanity checks.  Make sure that we have an int pending.
6356    * Also, if PCI, then we are going to check for a PCI bus error status
6357    * should we get too many spurious interrupts.
6358    */
6359   if (!((intstat = aic_inb(p, INTSTAT)) & INT_PEND))
6360   {
6361 #ifdef CONFIG_PCI
6362     if ( (p->chip & AHC_PCI) && (p->spurious_int > 500) &&
6363         !(p->flags & AHC_HANDLING_REQINITS) )
6364     {
6365       if ( aic_inb(p, ERROR) & PCIERRSTAT )
6366       {
6367         aic7xxx_pci_intr(p);
6368       }
6369       p->spurious_int = 0;
6370     }
6371     else if ( !(p->flags & AHC_HANDLING_REQINITS) )
6372     {
6373       p->spurious_int++;
6374     }
6375 #endif
6376     return;
6377   }
6378
6379   p->spurious_int = 0;
6380
6381   /*
6382    * Keep track of interrupts for /proc/scsi
6383    */
6384   p->isr_count++;
6385
6386 #ifdef AIC7XXX_VERBOSE_DEBUGGING
6387   if ( (p->isr_count < 16) && (aic7xxx_verbose > 0xffff) &&
6388        (aic7xxx_panic_on_abort) && (p->flags & AHC_PAGESCBS) )
6389     aic7xxx_check_scbs(p, "Bogus settings at start of interrupt.");
6390 #endif
6391
6392   /*
6393    * Handle all the interrupt sources - especially for SCSI
6394    * interrupts, we won't get a second chance at them.
6395    */
6396   if (intstat & CMDCMPLT)
6397   {
6398     aic7xxx_handle_command_completion_intr(p);
6399   }
6400
6401   if (intstat & BRKADRINT)
6402   {
6403     int i;
6404     unsigned char errno = aic_inb(p, ERROR);
6405
6406     printk(KERN_ERR "(scsi%d) BRKADRINT error(0x%x):\n", p->host_no, errno);
6407     for (i = 0; i < ARRAY_SIZE(hard_error); i++)
6408     {
6409       if (errno & hard_error[i].errno)
6410       {
6411         printk(KERN_ERR "  %s\n", hard_error[i].errmesg);
6412       }
6413     }
6414     printk(KERN_ERR "(scsi%d)   SEQADDR=0x%x\n", p->host_no,
6415       (((aic_inb(p, SEQADDR1) << 8) & 0x100) | aic_inb(p, SEQADDR0)));
6416     if (aic7xxx_panic_on_abort)
6417       aic7xxx_panic_abort(p, NULL);
6418 #ifdef CONFIG_PCI
6419     if (errno & PCIERRSTAT)
6420       aic7xxx_pci_intr(p);
6421 #endif
6422     if (errno & (SQPARERR | ILLOPCODE | ILLSADDR))
6423     {
6424       panic("aic7xxx: unrecoverable BRKADRINT.\n");
6425     }
6426     if (errno & ILLHADDR)
6427     {
6428       printk(KERN_ERR "(scsi%d) BUG! Driver accessed chip without first "
6429              "pausing controller!\n", p->host_no);
6430     }
6431 #ifdef AIC7XXX_VERBOSE_DEBUGGING
6432     if (errno & DPARERR)
6433     {
6434       if (aic_inb(p, DMAPARAMS) & DIRECTION)
6435         printk("(scsi%d) while DMAing SCB from host to card.\n", p->host_no);
6436       else
6437         printk("(scsi%d) while DMAing SCB from card to host.\n", p->host_no);
6438     }
6439 #endif
6440     aic_outb(p, CLRPARERR | CLRBRKADRINT, CLRINT);
6441     unpause_sequencer(p, FALSE);
6442   }
6443
6444   if (intstat & SEQINT)
6445   {
6446     /*
6447      * Read the CCSCBCTL register to work around a bug in the Ultra2 cards
6448      */
6449     if(p->features & AHC_ULTRA2)
6450     {
6451       aic_inb(p, CCSCBCTL);
6452     }
6453     aic7xxx_handle_seqint(p, intstat);
6454   }
6455
6456   if (intstat & SCSIINT)
6457   {
6458     aic7xxx_handle_scsiint(p, intstat);
6459   }
6460
6461 #ifdef AIC7XXX_VERBOSE_DEBUGGING
6462   if ( (p->isr_count < 16) && (aic7xxx_verbose > 0xffff) &&
6463        (aic7xxx_panic_on_abort) && (p->flags & AHC_PAGESCBS) )
6464     aic7xxx_check_scbs(p, "Bogus settings at end of interrupt.");
6465 #endif
6466
6467 }
6468
6469 /*+F*************************************************************************
6470  * Function:
6471  *   do_aic7xxx_isr
6472  *
6473  * Description:
6474  *   This is a gross hack to solve a problem in linux kernels 2.1.85 and
6475  *   above.  Please, children, do not try this at home, and if you ever see
6476  *   anything like it, please inform the Gross Hack Police immediately
6477  *-F*************************************************************************/
6478 static irqreturn_t
6479 do_aic7xxx_isr(int irq, void *dev_id)
6480 {
6481   unsigned long cpu_flags;
6482   struct aic7xxx_host *p;
6483   
6484   p = (struct aic7xxx_host *)dev_id;
6485   if(!p)
6486     return IRQ_NONE;
6487   spin_lock_irqsave(p->host->host_lock, cpu_flags);
6488   p->flags |= AHC_IN_ISR;
6489   do
6490   {
6491     aic7xxx_isr(dev_id);
6492   } while ( (aic_inb(p, INTSTAT) & INT_PEND) );
6493   aic7xxx_done_cmds_complete(p);
6494   aic7xxx_run_waiting_queues(p);
6495   p->flags &= ~AHC_IN_ISR;
6496   spin_unlock_irqrestore(p->host->host_lock, cpu_flags);
6497
6498   return IRQ_HANDLED;
6499 }
6500
6501 /*+F*************************************************************************
6502  * Function:
6503  *   aic7xxx_init_transinfo
6504  *
6505  * Description:
6506  *   Set up the initial aic_dev values from the BIOS settings and from
6507  *   INQUIRY results
6508  *-F*************************************************************************/
6509 static void
6510 aic7xxx_init_transinfo(struct aic7xxx_host *p, struct aic_dev_data *aic_dev)
6511 {
6512   struct scsi_device *sdpnt = aic_dev->SDptr;
6513   unsigned char tindex;
6514
6515   tindex = sdpnt->id | (sdpnt->channel << 3);
6516   if (!(aic_dev->flags & DEVICE_DTR_SCANNED))
6517   {
6518     aic_dev->flags |= DEVICE_DTR_SCANNED;
6519
6520     if ( sdpnt->wdtr && (p->features & AHC_WIDE) )
6521     {
6522       aic_dev->needwdtr = aic_dev->needwdtr_copy = 1;
6523       aic_dev->goal.width = p->user[tindex].width;
6524     }
6525     else
6526     {
6527       aic_dev->needwdtr = aic_dev->needwdtr_copy = 0;
6528       pause_sequencer(p);
6529       aic7xxx_set_width(p, sdpnt->id, sdpnt->channel, sdpnt->lun,
6530                         MSG_EXT_WDTR_BUS_8_BIT, (AHC_TRANS_ACTIVE |
6531                                                  AHC_TRANS_GOAL |
6532                                                  AHC_TRANS_CUR), aic_dev );
6533       unpause_sequencer(p, FALSE);
6534     }
6535     if ( sdpnt->sdtr && p->user[tindex].offset )
6536     {
6537       aic_dev->goal.period = p->user[tindex].period;
6538       aic_dev->goal.options = p->user[tindex].options;
6539       if (p->features & AHC_ULTRA2)
6540         aic_dev->goal.offset = MAX_OFFSET_ULTRA2;
6541       else if (aic_dev->goal.width == MSG_EXT_WDTR_BUS_16_BIT)
6542         aic_dev->goal.offset = MAX_OFFSET_16BIT;
6543       else
6544         aic_dev->goal.offset = MAX_OFFSET_8BIT;
6545       if ( sdpnt->ppr && p->user[tindex].period <= 9 &&
6546              p->user[tindex].options )
6547       {
6548         aic_dev->needppr = aic_dev->needppr_copy = 1;
6549         aic_dev->needsdtr = aic_dev->needsdtr_copy = 0;
6550         aic_dev->needwdtr = aic_dev->needwdtr_copy = 0;
6551         aic_dev->flags |= DEVICE_SCSI_3;
6552       }
6553       else
6554       {
6555         aic_dev->needsdtr = aic_dev->needsdtr_copy = 1;
6556         aic_dev->goal.period = max_t(unsigned char, 10, aic_dev->goal.period);
6557         aic_dev->goal.options = 0;
6558       }
6559     }
6560     else
6561     {
6562       aic_dev->needsdtr = aic_dev->needsdtr_copy = 0;
6563       aic_dev->goal.period = 255;
6564       aic_dev->goal.offset = 0;
6565       aic_dev->goal.options = 0;
6566     }
6567     aic_dev->flags |= DEVICE_PRINT_DTR;
6568   }
6569 }
6570
6571 /*+F*************************************************************************
6572  * Function:
6573  *   aic7xxx_slave_alloc
6574  *
6575  * Description:
6576  *   Set up the initial aic_dev struct pointers
6577  *-F*************************************************************************/
6578 static int
6579 aic7xxx_slave_alloc(struct scsi_device *SDptr)
6580 {
6581   struct aic7xxx_host *p = (struct aic7xxx_host *)SDptr->host->hostdata;
6582   struct aic_dev_data *aic_dev;
6583
6584   aic_dev = kmalloc(sizeof(struct aic_dev_data), GFP_ATOMIC | GFP_KERNEL);
6585   if(!aic_dev)
6586     return 1;
6587   /*
6588    * Check to see if channel was scanned.
6589    */
6590   
6591   if (!(p->flags & AHC_A_SCANNED) && (SDptr->channel == 0))
6592   {
6593     if (aic7xxx_verbose & VERBOSE_PROBE2)
6594       printk(INFO_LEAD "Scanning channel for devices.\n",
6595         p->host_no, 0, -1, -1);
6596     p->flags |= AHC_A_SCANNED;
6597   }
6598   else
6599   {
6600     if (!(p->flags & AHC_B_SCANNED) && (SDptr->channel == 1))
6601     {
6602       if (aic7xxx_verbose & VERBOSE_PROBE2)
6603         printk(INFO_LEAD "Scanning channel for devices.\n",
6604           p->host_no, 1, -1, -1);
6605       p->flags |= AHC_B_SCANNED;
6606     }
6607   }
6608
6609   memset(aic_dev, 0, sizeof(struct aic_dev_data));
6610   SDptr->hostdata = aic_dev;
6611   aic_dev->SDptr = SDptr;
6612   aic_dev->max_q_depth = 1;
6613   aic_dev->temp_q_depth = 1;
6614   scbq_init(&aic_dev->delayed_scbs);
6615   INIT_LIST_HEAD(&aic_dev->list);
6616   list_add_tail(&aic_dev->list, &p->aic_devs);
6617   return 0;
6618 }
6619
6620 /*+F*************************************************************************
6621  * Function:
6622  *   aic7xxx_device_queue_depth
6623  *
6624  * Description:
6625  *   Determines the queue depth for a given device.  There are two ways
6626  *   a queue depth can be obtained for a tagged queueing device.  One
6627  *   way is the default queue depth which is determined by whether
6628  *   aic7xxx_default_queue_depth.  The other is by the aic7xxx_tag_info
6629  *   array.
6630  *
6631  *   If tagged queueing isn't supported on the device, then we set the
6632  *   depth to p->host->hostt->cmd_per_lun for internal driver queueing.
6633  *   as the default queue depth.  Otherwise, we use either 4 or 8 as the
6634  *   default queue depth (dependent on the number of hardware SCBs).
6635  *   The other way we determine queue depth is through the use of the
6636  *   aic7xxx_tag_info array which is enabled by defining
6637  *   AIC7XXX_TAGGED_QUEUEING_BY_DEVICE.  This array can be initialized
6638  *   with queue depths for individual devices.  It also allows tagged
6639  *   queueing to be [en|dis]abled for a specific adapter.
6640  *-F*************************************************************************/
6641 static void
6642 aic7xxx_device_queue_depth(struct aic7xxx_host *p, struct scsi_device *device)
6643 {
6644   int tag_enabled = FALSE;
6645   struct aic_dev_data *aic_dev = device->hostdata;
6646   unsigned char tindex;
6647
6648   tindex = device->id | (device->channel << 3);
6649
6650   if (device->simple_tags)
6651     return; // We've already enabled this device
6652
6653   if (device->tagged_supported)
6654   {
6655     tag_enabled = TRUE;
6656
6657     if (!(p->discenable & (1 << tindex)))
6658     {
6659       if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
6660         printk(INFO_LEAD "Disconnection disabled, unable to "
6661              "enable tagged queueing.\n",
6662              p->host_no, device->channel, device->id, device->lun);
6663       tag_enabled = FALSE;
6664     }
6665     else
6666     {
6667       if (p->instance >= ARRAY_SIZE(aic7xxx_tag_info))
6668       {
6669         static int print_warning = TRUE;
6670         if(print_warning)
6671         {
6672           printk(KERN_INFO "aic7xxx: WARNING, insufficient tag_info instances for"
6673                            " installed controllers.\n");
6674           printk(KERN_INFO "aic7xxx: Please update the aic7xxx_tag_info array in"
6675                            " the aic7xxx.c source file.\n");
6676           print_warning = FALSE;
6677         }
6678         aic_dev->max_q_depth = aic_dev->temp_q_depth =
6679                 aic7xxx_default_queue_depth;
6680       }
6681       else
6682       {
6683
6684         if (aic7xxx_tag_info[p->instance].tag_commands[tindex] == 255)
6685         {
6686           tag_enabled = FALSE;
6687         }
6688         else if (aic7xxx_tag_info[p->instance].tag_commands[tindex] == 0)
6689         {
6690           aic_dev->max_q_depth = aic_dev->temp_q_depth =
6691                   aic7xxx_default_queue_depth;
6692         }
6693         else
6694         {
6695           aic_dev->max_q_depth = aic_dev->temp_q_depth = 
6696             aic7xxx_tag_info[p->instance].tag_commands[tindex];
6697         }
6698       }
6699     }
6700   }
6701   if (tag_enabled)
6702   {
6703     if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
6704     {
6705           printk(INFO_LEAD "Tagged queuing enabled, queue depth %d.\n",
6706             p->host_no, device->channel, device->id,
6707             device->lun, aic_dev->max_q_depth);
6708     }
6709     scsi_adjust_queue_depth(device, MSG_ORDERED_TAG, aic_dev->max_q_depth);
6710   }
6711   else
6712   {
6713     if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
6714     {
6715           printk(INFO_LEAD "Tagged queuing disabled, queue depth %d.\n",
6716             p->host_no, device->channel, device->id,
6717             device->lun, device->host->cmd_per_lun);
6718     }
6719     scsi_adjust_queue_depth(device, 0, device->host->cmd_per_lun);
6720   }
6721   return;
6722 }
6723
6724 /*+F*************************************************************************
6725  * Function:
6726  *   aic7xxx_slave_destroy
6727  *
6728  * Description:
6729  *   prepare for this device to go away
6730  *-F*************************************************************************/
6731 static void
6732 aic7xxx_slave_destroy(struct scsi_device *SDptr)
6733 {
6734   struct aic_dev_data *aic_dev = SDptr->hostdata;
6735
6736   list_del(&aic_dev->list);
6737   SDptr->hostdata = NULL;
6738   kfree(aic_dev);
6739   return;
6740 }
6741
6742 /*+F*************************************************************************
6743  * Function:
6744  *   aic7xxx_slave_configure
6745  *
6746  * Description:
6747  *   Configure the device we are attaching to the controller.  This is
6748  *   where we get to do things like scan the INQUIRY data, set queue
6749  *   depths, allocate command structs, etc.
6750  *-F*************************************************************************/
6751 static int
6752 aic7xxx_slave_configure(struct scsi_device *SDptr)
6753 {
6754   struct aic7xxx_host *p = (struct aic7xxx_host *) SDptr->host->hostdata;
6755   struct aic_dev_data *aic_dev;
6756   int scbnum;
6757
6758   aic_dev = (struct aic_dev_data *)SDptr->hostdata;
6759
6760   aic7xxx_init_transinfo(p, aic_dev);
6761   aic7xxx_device_queue_depth(p, SDptr);
6762   if(list_empty(&aic_dev->list))
6763     list_add_tail(&aic_dev->list, &p->aic_devs);
6764
6765   scbnum = 0;
6766   list_for_each_entry(aic_dev, &p->aic_devs, list) {
6767     scbnum += aic_dev->max_q_depth;
6768   }
6769   while (scbnum > p->scb_data->numscbs)
6770   {
6771     /*
6772      * Pre-allocate the needed SCBs to get around the possibility of having
6773      * to allocate some when memory is more or less exhausted and we need
6774      * the SCB in order to perform a swap operation (possible deadlock)
6775      */
6776     if ( aic7xxx_allocate_scb(p) == 0 )
6777       break;
6778   }
6779
6780
6781   return(0);
6782 }
6783
6784 /*+F*************************************************************************
6785  * Function:
6786  *   aic7xxx_probe
6787  *
6788  * Description:
6789  *   Probing for EISA boards: it looks like the first two bytes
6790  *   are a manufacturer code - three characters, five bits each:
6791  *
6792  *               BYTE 0   BYTE 1   BYTE 2   BYTE 3
6793  *              ?1111122 22233333 PPPPPPPP RRRRRRRR
6794  *
6795  *   The characters are baselined off ASCII '@', so add that value
6796  *   to each to get the real ASCII code for it. The next two bytes
6797  *   appear to be a product and revision number, probably vendor-
6798  *   specific. This is what is being searched for at each port,
6799  *   and what should probably correspond to the ID= field in the
6800  *   ECU's .cfg file for the card - if your card is not detected,
6801  *   make sure your signature is listed in the array.
6802  *
6803  *   The fourth byte's lowest bit seems to be an enabled/disabled
6804  *   flag (rest of the bits are reserved?).
6805  *
6806  * NOTE:  This function is only needed on Intel and Alpha platforms,
6807  *   the other platforms we support don't have EISA/VLB busses.  So,
6808  *   we #ifdef this entire function to avoid compiler warnings about
6809  *   an unused function.
6810  *-F*************************************************************************/
6811 #if defined(__i386__) || defined(__alpha__)
6812 static int
6813 aic7xxx_probe(int slot, int base, ahc_flag_type *flags)
6814 {
6815   int i;
6816   unsigned char buf[4];
6817
6818   static struct {
6819     int n;
6820     unsigned char signature[sizeof(buf)];
6821     ahc_chip type;
6822     int bios_disabled;
6823   } AIC7xxx[] = {
6824     { 4, { 0x04, 0x90, 0x77, 0x70 },
6825       AHC_AIC7770|AHC_EISA, FALSE },  /* mb 7770  */
6826     { 4, { 0x04, 0x90, 0x77, 0x71 },
6827       AHC_AIC7770|AHC_EISA, FALSE }, /* host adapter 274x */
6828     { 4, { 0x04, 0x90, 0x77, 0x56 },
6829       AHC_AIC7770|AHC_VL, FALSE }, /* 284x BIOS enabled */
6830     { 4, { 0x04, 0x90, 0x77, 0x57 },
6831       AHC_AIC7770|AHC_VL, TRUE }   /* 284x BIOS disabled */
6832   };
6833
6834   /*
6835    * The VL-bus cards need to be primed by
6836    * writing before a signature check.
6837    */
6838   for (i = 0; i < sizeof(buf); i++)
6839   {
6840     outb(0x80 + i, base);
6841     buf[i] = inb(base + i);
6842   }
6843
6844   for (i = 0; i < ARRAY_SIZE(AIC7xxx); i++)
6845   {
6846     /*
6847      * Signature match on enabled card?
6848      */
6849     if (!memcmp(buf, AIC7xxx[i].signature, AIC7xxx[i].n))
6850     {
6851       if (inb(base + 4) & 1)
6852       {
6853         if (AIC7xxx[i].bios_disabled)
6854         {
6855           *flags |= AHC_USEDEFAULTS;
6856         }
6857         else
6858         {
6859           *flags |= AHC_BIOS_ENABLED;
6860         }
6861         return (i);
6862       }
6863
6864       printk("aic7xxx: <Adaptec 7770 SCSI Host Adapter> "
6865              "disabled at slot %d, ignored.\n", slot);
6866     }
6867   }
6868
6869   return (-1);
6870 }
6871 #endif /* (__i386__) || (__alpha__) */
6872
6873
6874 /*+F*************************************************************************
6875  * Function:
6876  *   read_2840_seeprom
6877  *
6878  * Description:
6879  *   Reads the 2840 serial EEPROM and returns 1 if successful and 0 if
6880  *   not successful.
6881  *
6882  *   See read_seeprom (for the 2940) for the instruction set of the 93C46
6883  *   chip.
6884  *
6885  *   The 2840 interface to the 93C46 serial EEPROM is through the
6886  *   STATUS_2840 and SEECTL_2840 registers.  The CS_2840, CK_2840, and
6887  *   DO_2840 bits of the SEECTL_2840 register are connected to the chip
6888  *   select, clock, and data out lines respectively of the serial EEPROM.
6889  *   The DI_2840 bit of the STATUS_2840 is connected to the data in line
6890  *   of the serial EEPROM.  The EEPROM_TF bit of STATUS_2840 register is
6891  *   useful in that it gives us an 800 nsec timer.  After a read from the
6892  *   SEECTL_2840 register the timing flag is cleared and goes high 800 nsec
6893  *   later.
6894  *-F*************************************************************************/
6895 static int
6896 read_284x_seeprom(struct aic7xxx_host *p, struct seeprom_config *sc)
6897 {
6898   int i = 0, k = 0;
6899   unsigned char temp;
6900   unsigned short checksum = 0;
6901   unsigned short *seeprom = (unsigned short *) sc;
6902   struct seeprom_cmd {
6903     unsigned char len;
6904     unsigned char bits[3];
6905   };
6906   struct seeprom_cmd seeprom_read = {3, {1, 1, 0}};
6907
6908 #define CLOCK_PULSE(p) \
6909   while ((aic_inb(p, STATUS_2840) & EEPROM_TF) == 0)        \
6910   {                                                \
6911     ;  /* Do nothing */                                \
6912   }                                                \
6913   (void) aic_inb(p, SEECTL_2840);
6914
6915   /*
6916    * Read the first 32 registers of the seeprom.  For the 2840,
6917    * the 93C46 SEEPROM is a 1024-bit device with 64 16-bit registers
6918    * but only the first 32 are used by Adaptec BIOS.  The loop
6919    * will range from 0 to 31.
6920    */
6921   for (k = 0; k < (sizeof(*sc) / 2); k++)
6922   {
6923     /*
6924      * Send chip select for one clock cycle.
6925      */
6926     aic_outb(p, CK_2840 | CS_2840, SEECTL_2840);
6927     CLOCK_PULSE(p);
6928
6929     /*
6930      * Now we're ready to send the read command followed by the
6931      * address of the 16-bit register we want to read.
6932      */
6933     for (i = 0; i < seeprom_read.len; i++)
6934     {
6935       temp = CS_2840 | seeprom_read.bits[i];
6936       aic_outb(p, temp, SEECTL_2840);
6937       CLOCK_PULSE(p);
6938       temp = temp ^ CK_2840;
6939       aic_outb(p, temp, SEECTL_2840);
6940       CLOCK_PULSE(p);
6941     }
6942     /*
6943      * Send the 6 bit address (MSB first, LSB last).
6944      */
6945     for (i = 5; i >= 0; i--)
6946     {
6947       temp = k;
6948       temp = (temp >> i) & 1;  /* Mask out all but lower bit. */
6949       temp = CS_2840 | temp;
6950       aic_outb(p, temp, SEECTL_2840);
6951       CLOCK_PULSE(p);
6952       temp = temp ^ CK_2840;
6953       aic_outb(p, temp, SEECTL_2840);
6954       CLOCK_PULSE(p);
6955     }
6956
6957     /*
6958      * Now read the 16 bit register.  An initial 0 precedes the
6959      * register contents which begins with bit 15 (MSB) and ends
6960      * with bit 0 (LSB).  The initial 0 will be shifted off the
6961      * top of our word as we let the loop run from 0 to 16.
6962      */
6963     for (i = 0; i <= 16; i++)
6964     {
6965       temp = CS_2840;
6966       aic_outb(p, temp, SEECTL_2840);
6967       CLOCK_PULSE(p);
6968       temp = temp ^ CK_2840;
6969       seeprom[k] = (seeprom[k] << 1) | (aic_inb(p, STATUS_2840) & DI_2840);
6970       aic_outb(p, temp, SEECTL_2840);
6971       CLOCK_PULSE(p);
6972     }
6973     /*
6974      * The serial EEPROM has a checksum in the last word.  Keep a
6975      * running checksum for all words read except for the last
6976      * word.  We'll verify the checksum after all words have been
6977      * read.
6978      */
6979     if (k < (sizeof(*sc) / 2) - 1)
6980     {
6981       checksum = checksum + seeprom[k];
6982     }
6983
6984     /*
6985      * Reset the chip select for the next command cycle.
6986      */
6987     aic_outb(p, 0, SEECTL_2840);
6988     CLOCK_PULSE(p);
6989     aic_outb(p, CK_2840, SEECTL_2840);
6990     CLOCK_PULSE(p);
6991     aic_outb(p, 0, SEECTL_2840);
6992     CLOCK_PULSE(p);
6993   }
6994
6995 #if 0
6996   printk("Computed checksum 0x%x, checksum read 0x%x\n", checksum, sc->checksum);
6997   printk("Serial EEPROM:");
6998   for (k = 0; k < (sizeof(*sc) / 2); k++)
6999   {
7000     if (((k % 8) == 0) && (k != 0))
7001     {
7002       printk("\n              ");
7003     }
7004     printk(" 0x%x", seeprom[k]);
7005   }
7006   printk("\n");
7007 #endif
7008
7009   if (checksum != sc->checksum)
7010   {
7011     printk("aic7xxx: SEEPROM checksum error, ignoring SEEPROM settings.\n");
7012     return (0);
7013   }
7014
7015   return (1);
7016 #undef CLOCK_PULSE
7017 }
7018
7019 #define CLOCK_PULSE(p)                                               \
7020   do {                                                               \
7021     int limit = 0;                                                   \
7022     do {                                                             \
7023       mb();                                                          \
7024       pause_sequencer(p);  /* This is just to generate some PCI */   \
7025                            /* traffic so the PCI read is flushed */  \
7026                            /* it shouldn't be needed, but some */    \
7027                            /* chipsets do indeed appear to need */   \
7028                            /* something to force PCI reads to get */ \
7029                            /* flushed */                             \
7030       udelay(1);           /* Do nothing */                          \
7031     } while (((aic_inb(p, SEECTL) & SEERDY) == 0) && (++limit < 1000)); \
7032   } while(0)
7033
7034 /*+F*************************************************************************
7035  * Function:
7036  *   acquire_seeprom
7037  *
7038  * Description:
7039  *   Acquires access to the memory port on PCI controllers.
7040  *-F*************************************************************************/
7041 static int
7042 acquire_seeprom(struct aic7xxx_host *p)
7043 {
7044
7045   /*
7046    * Request access of the memory port.  When access is
7047    * granted, SEERDY will go high.  We use a 1 second
7048    * timeout which should be near 1 second more than
7049    * is needed.  Reason: after the 7870 chip reset, there
7050    * should be no contention.
7051    */
7052   aic_outb(p, SEEMS, SEECTL);
7053   CLOCK_PULSE(p);
7054   if ((aic_inb(p, SEECTL) & SEERDY) == 0)
7055   {
7056     aic_outb(p, 0, SEECTL);
7057     return (0);
7058   }
7059   return (1);
7060 }
7061
7062 /*+F*************************************************************************
7063  * Function:
7064  *   release_seeprom
7065  *
7066  * Description:
7067  *   Releases access to the memory port on PCI controllers.
7068  *-F*************************************************************************/
7069 static void
7070 release_seeprom(struct aic7xxx_host *p)
7071 {
7072   /*
7073    * Make sure the SEEPROM is ready before we release it.
7074    */
7075   CLOCK_PULSE(p);
7076   aic_outb(p, 0, SEECTL);
7077 }
7078
7079 /*+F*************************************************************************
7080  * Function:
7081  *   read_seeprom
7082  *
7083  * Description:
7084  *   Reads the serial EEPROM and returns 1 if successful and 0 if
7085  *   not successful.
7086  *
7087  *   The instruction set of the 93C46/56/66 chips is as follows:
7088  *
7089  *               Start  OP
7090  *     Function   Bit  Code  Address    Data     Description
7091  *     -------------------------------------------------------------------
7092  *     READ        1    10   A5 - A0             Reads data stored in memory,
7093  *                                               starting at specified address
7094  *     EWEN        1    00   11XXXX              Write enable must precede
7095  *                                               all programming modes
7096  *     ERASE       1    11   A5 - A0             Erase register A5A4A3A2A1A0
7097  *     WRITE       1    01   A5 - A0   D15 - D0  Writes register
7098  *     ERAL        1    00   10XXXX              Erase all registers
7099  *     WRAL        1    00   01XXXX    D15 - D0  Writes to all registers
7100  *     EWDS        1    00   00XXXX              Disables all programming
7101  *                                               instructions
7102  *     *Note: A value of X for address is a don't care condition.
7103  *     *Note: The 93C56 and 93C66 have 8 address bits.
7104  * 
7105  *
7106  *   The 93C46 has a four wire interface: clock, chip select, data in, and
7107  *   data out.  In order to perform one of the above functions, you need
7108  *   to enable the chip select for a clock period (typically a minimum of
7109  *   1 usec, with the clock high and low a minimum of 750 and 250 nsec
7110  *   respectively.  While the chip select remains high, you can clock in
7111  *   the instructions (above) starting with the start bit, followed by the
7112  *   OP code, Address, and Data (if needed).  For the READ instruction, the
7113  *   requested 16-bit register contents is read from the data out line but
7114  *   is preceded by an initial zero (leading 0, followed by 16-bits, MSB
7115  *   first).  The clock cycling from low to high initiates the next data
7116  *   bit to be sent from the chip.
7117  *
7118  *   The 78xx interface to the 93C46 serial EEPROM is through the SEECTL
7119  *   register.  After successful arbitration for the memory port, the
7120  *   SEECS bit of the SEECTL register is connected to the chip select.
7121  *   The SEECK, SEEDO, and SEEDI are connected to the clock, data out,
7122  *   and data in lines respectively.  The SEERDY bit of SEECTL is useful
7123  *   in that it gives us an 800 nsec timer.  After a write to the SEECTL
7124  *   register, the SEERDY goes high 800 nsec later.  The one exception
7125  *   to this is when we first request access to the memory port.  The
7126  *   SEERDY goes high to signify that access has been granted and, for
7127  *   this case, has no implied timing.
7128  *-F*************************************************************************/
7129 static int
7130 read_seeprom(struct aic7xxx_host *p, int offset, 
7131     unsigned short *scarray, unsigned int len, seeprom_chip_type chip)
7132 {
7133   int i = 0, k;
7134   unsigned char temp;
7135   unsigned short checksum = 0;
7136   struct seeprom_cmd {
7137     unsigned char len;
7138     unsigned char bits[3];
7139   };
7140   struct seeprom_cmd seeprom_read = {3, {1, 1, 0}};
7141
7142   /*
7143    * Request access of the memory port.
7144    */
7145   if (acquire_seeprom(p) == 0)
7146   {
7147     return (0);
7148   }
7149
7150   /*
7151    * Read 'len' registers of the seeprom.  For the 7870, the 93C46
7152    * SEEPROM is a 1024-bit device with 64 16-bit registers but only
7153    * the first 32 are used by Adaptec BIOS.  Some adapters use the
7154    * 93C56 SEEPROM which is a 2048-bit device.  The loop will range
7155    * from 0 to 'len' - 1.
7156    */
7157   for (k = 0; k < len; k++)
7158   {
7159     /*
7160      * Send chip select for one clock cycle.
7161      */
7162     aic_outb(p, SEEMS | SEECK | SEECS, SEECTL);
7163     CLOCK_PULSE(p);
7164
7165     /*
7166      * Now we're ready to send the read command followed by the
7167      * address of the 16-bit register we want to read.
7168      */
7169     for (i = 0; i < seeprom_read.len; i++)
7170     {
7171       temp = SEEMS | SEECS | (seeprom_read.bits[i] << 1);
7172       aic_outb(p, temp, SEECTL);
7173       CLOCK_PULSE(p);
7174       temp = temp ^ SEECK;
7175       aic_outb(p, temp, SEECTL);
7176       CLOCK_PULSE(p);
7177     }
7178     /*
7179      * Send the 6 or 8 bit address (MSB first, LSB last).
7180      */
7181     for (i = ((int) chip - 1); i >= 0; i--)
7182     {
7183       temp = k + offset;
7184       temp = (temp >> i) & 1;  /* Mask out all but lower bit. */
7185       temp = SEEMS | SEECS | (temp << 1);
7186       aic_outb(p, temp, SEECTL);
7187       CLOCK_PULSE(p);
7188       temp = temp ^ SEECK;
7189       aic_outb(p, temp, SEECTL);
7190       CLOCK_PULSE(p);
7191     }
7192
7193     /*
7194      * Now read the 16 bit register.  An initial 0 precedes the
7195      * register contents which begins with bit 15 (MSB) and ends
7196      * with bit 0 (LSB).  The initial 0 will be shifted off the
7197      * top of our word as we let the loop run from 0 to 16.
7198      */
7199     for (i = 0; i <= 16; i++)
7200     {
7201       temp = SEEMS | SEECS;
7202       aic_outb(p, temp, SEECTL);
7203       CLOCK_PULSE(p);
7204       temp = temp ^ SEECK;
7205       scarray[k] = (scarray[k] << 1) | (aic_inb(p, SEECTL) & SEEDI);
7206       aic_outb(p, temp, SEECTL);
7207       CLOCK_PULSE(p);
7208     }
7209
7210     /*
7211      * The serial EEPROM should have a checksum in the last word.
7212      * Keep a running checksum for all words read except for the
7213      * last word.  We'll verify the checksum after all words have
7214      * been read.
7215      */
7216     if (k < (len - 1))
7217     {
7218       checksum = checksum + scarray[k];
7219     }
7220
7221     /*
7222      * Reset the chip select for the next command cycle.
7223      */
7224     aic_outb(p, SEEMS, SEECTL);
7225     CLOCK_PULSE(p);
7226     aic_outb(p, SEEMS | SEECK, SEECTL);
7227     CLOCK_PULSE(p);
7228     aic_outb(p, SEEMS, SEECTL);
7229     CLOCK_PULSE(p);
7230   }
7231
7232   /*
7233    * Release access to the memory port and the serial EEPROM.
7234    */
7235   release_seeprom(p);
7236
7237 #if 0
7238   printk("Computed checksum 0x%x, checksum read 0x%x\n",
7239          checksum, scarray[len - 1]);
7240   printk("Serial EEPROM:");
7241   for (k = 0; k < len; k++)
7242   {
7243     if (((k % 8) == 0) && (k != 0))
7244     {
7245       printk("\n              ");
7246     }
7247     printk(" 0x%x", scarray[k]);
7248   }
7249   printk("\n");
7250 #endif
7251   if ( (checksum != scarray[len - 1]) || (checksum == 0) )
7252   {
7253     return (0);
7254   }
7255
7256   return (1);
7257 }
7258
7259 /*+F*************************************************************************
7260  * Function:
7261  *   read_brdctl
7262  *
7263  * Description:
7264  *   Reads the BRDCTL register.
7265  *-F*************************************************************************/
7266 static unsigned char
7267 read_brdctl(struct aic7xxx_host *p)
7268 {
7269   unsigned char brdctl, value;
7270
7271   /*
7272    * Make sure the SEEPROM is ready before we access it
7273    */
7274   CLOCK_PULSE(p);
7275   if (p->features & AHC_ULTRA2)
7276   {
7277     brdctl = BRDRW_ULTRA2;
7278     aic_outb(p, brdctl, BRDCTL);
7279     CLOCK_PULSE(p);
7280     value = aic_inb(p, BRDCTL);
7281     CLOCK_PULSE(p);
7282     return(value);
7283   }
7284   brdctl = BRDRW;
7285   if ( !((p->chip & AHC_CHIPID_MASK) == AHC_AIC7895) ||
7286         (p->flags & AHC_CHNLB) )
7287   {
7288     brdctl |= BRDCS;
7289   }
7290   aic_outb(p, brdctl, BRDCTL);
7291   CLOCK_PULSE(p);
7292   value = aic_inb(p, BRDCTL);
7293   CLOCK_PULSE(p);
7294   aic_outb(p, 0, BRDCTL);
7295   CLOCK_PULSE(p);
7296   return (value);
7297 }
7298
7299 /*+F*************************************************************************
7300  * Function:
7301  *   write_brdctl
7302  *
7303  * Description:
7304  *   Writes a value to the BRDCTL register.
7305  *-F*************************************************************************/
7306 static void
7307 write_brdctl(struct aic7xxx_host *p, unsigned char value)
7308 {
7309   unsigned char brdctl;
7310
7311   /*
7312    * Make sure the SEEPROM is ready before we access it
7313    */
7314   CLOCK_PULSE(p);
7315   if (p->features & AHC_ULTRA2)
7316   {
7317     brdctl = value;
7318     aic_outb(p, brdctl, BRDCTL);
7319     CLOCK_PULSE(p);
7320     brdctl |= BRDSTB_ULTRA2;
7321     aic_outb(p, brdctl, BRDCTL);
7322     CLOCK_PULSE(p);
7323     brdctl &= ~BRDSTB_ULTRA2;
7324     aic_outb(p, brdctl, BRDCTL);
7325     CLOCK_PULSE(p);
7326     read_brdctl(p);
7327     CLOCK_PULSE(p);
7328   }
7329   else
7330   {
7331     brdctl = BRDSTB;
7332     if ( !((p->chip & AHC_CHIPID_MASK) == AHC_AIC7895) ||
7333           (p->flags & AHC_CHNLB) )
7334     {
7335       brdctl |= BRDCS;
7336     }
7337     brdctl = BRDSTB | BRDCS;
7338     aic_outb(p, brdctl, BRDCTL);
7339     CLOCK_PULSE(p);
7340     brdctl |= value;
7341     aic_outb(p, brdctl, BRDCTL);
7342     CLOCK_PULSE(p);
7343     brdctl &= ~BRDSTB;
7344     aic_outb(p, brdctl, BRDCTL);
7345     CLOCK_PULSE(p);
7346     brdctl &= ~BRDCS;
7347     aic_outb(p, brdctl, BRDCTL);
7348     CLOCK_PULSE(p);
7349   }
7350 }
7351
7352 /*+F*************************************************************************
7353  * Function:
7354  *   aic785x_cable_detect
7355  *
7356  * Description:
7357  *   Detect the cables that are present on aic785x class controller chips
7358  *-F*************************************************************************/
7359 static void
7360 aic785x_cable_detect(struct aic7xxx_host *p, int *int_50,
7361     int *ext_present, int *eeprom)
7362 {
7363   unsigned char brdctl;
7364
7365   aic_outb(p, BRDRW | BRDCS, BRDCTL);
7366   CLOCK_PULSE(p);
7367   aic_outb(p, 0, BRDCTL);
7368   CLOCK_PULSE(p);
7369   brdctl = aic_inb(p, BRDCTL);
7370   CLOCK_PULSE(p);
7371   *int_50 = !(brdctl & BRDDAT5);
7372   *ext_present = !(brdctl & BRDDAT6);
7373   *eeprom = (aic_inb(p, SPIOCAP) & EEPROM);
7374 }
7375
7376 #undef CLOCK_PULSE
7377
7378 /*+F*************************************************************************
7379  * Function:
7380  *   aic2940_uwpro_cable_detect
7381  *
7382  * Description:
7383  *   Detect the cables that are present on the 2940-UWPro cards
7384  *
7385  * NOTE: This function assumes the SEEPROM will have already been acquired
7386  *       prior to invocation of this function.
7387  *-F*************************************************************************/
7388 static void
7389 aic2940_uwpro_wide_cable_detect(struct aic7xxx_host *p, int *int_68,
7390     int *ext_68, int *eeprom)
7391 {
7392   unsigned char brdctl;
7393
7394   /*
7395    * First read the status of our cables.  Set the rom bank to
7396    * 0 since the bank setting serves as a multiplexor for the
7397    * cable detection logic.  BRDDAT5 controls the bank switch.
7398    */
7399   write_brdctl(p, 0);
7400
7401   /*
7402    * Now we read the state of the internal 68 connector.  BRDDAT6
7403    * is don't care, BRDDAT7 is internal 68.  The cable is
7404    * present if the bit is 0
7405    */
7406   brdctl = read_brdctl(p);
7407   *int_68 = !(brdctl & BRDDAT7);
7408
7409   /*
7410    * Set the bank bit in brdctl and then read the external cable state
7411    * and the EEPROM status
7412    */
7413   write_brdctl(p, BRDDAT5);
7414   brdctl = read_brdctl(p);
7415
7416   *ext_68 = !(brdctl & BRDDAT6);
7417   *eeprom = !(brdctl & BRDDAT7);
7418
7419   /*
7420    * We're done, the calling function will release the SEEPROM for us
7421    */
7422 }
7423
7424 /*+F*************************************************************************
7425  * Function:
7426  *   aic787x_cable_detect
7427  *
7428  * Description:
7429  *   Detect the cables that are present on aic787x class controller chips
7430  *
7431  * NOTE: This function assumes the SEEPROM will have already been acquired
7432  *       prior to invocation of this function.
7433  *-F*************************************************************************/
7434 static void
7435 aic787x_cable_detect(struct aic7xxx_host *p, int *int_50, int *int_68,
7436     int *ext_present, int *eeprom)
7437 {
7438   unsigned char brdctl;
7439
7440   /*
7441    * First read the status of our cables.  Set the rom bank to
7442    * 0 since the bank setting serves as a multiplexor for the
7443    * cable detection logic.  BRDDAT5 controls the bank switch.
7444    */
7445   write_brdctl(p, 0);
7446
7447   /*
7448    * Now we read the state of the two internal connectors.  BRDDAT6
7449    * is internal 50, BRDDAT7 is internal 68.  For each, the cable is
7450    * present if the bit is 0
7451    */
7452   brdctl = read_brdctl(p);
7453   *int_50 = !(brdctl & BRDDAT6);
7454   *int_68 = !(brdctl & BRDDAT7);
7455
7456   /*
7457    * Set the bank bit in brdctl and then read the external cable state
7458    * and the EEPROM status
7459    */
7460   write_brdctl(p, BRDDAT5);
7461   brdctl = read_brdctl(p);
7462
7463   *ext_present = !(brdctl & BRDDAT6);
7464   *eeprom = !(brdctl & BRDDAT7);
7465
7466   /*
7467    * We're done, the calling function will release the SEEPROM for us
7468    */
7469 }
7470
7471 /*+F*************************************************************************
7472  * Function:
7473  *   aic787x_ultra2_term_detect
7474  *
7475  * Description:
7476  *   Detect the termination settings present on ultra2 class controllers
7477  *
7478  * NOTE: This function assumes the SEEPROM will have already been acquired
7479  *       prior to invocation of this function.
7480  *-F*************************************************************************/
7481 static void
7482 aic7xxx_ultra2_term_detect(struct aic7xxx_host *p, int *enableSE_low,
7483                            int *enableSE_high, int *enableLVD_low,
7484                            int *enableLVD_high, int *eprom_present)
7485 {
7486   unsigned char brdctl;
7487
7488   brdctl = read_brdctl(p);
7489
7490   *eprom_present  = (brdctl & BRDDAT7);
7491   *enableSE_high  = (brdctl & BRDDAT6);
7492   *enableSE_low   = (brdctl & BRDDAT5);
7493   *enableLVD_high = (brdctl & BRDDAT4);
7494   *enableLVD_low  = (brdctl & BRDDAT3);
7495 }
7496
7497 /*+F*************************************************************************
7498  * Function:
7499  *   configure_termination
7500  *
7501  * Description:
7502  *   Configures the termination settings on PCI adapters that have
7503  *   SEEPROMs available.
7504  *-F*************************************************************************/
7505 static void
7506 configure_termination(struct aic7xxx_host *p)
7507 {
7508   int internal50_present = 0;
7509   int internal68_present = 0;
7510   int external_present = 0;
7511   int eprom_present = 0;
7512   int enableSE_low = 0;
7513   int enableSE_high = 0;
7514   int enableLVD_low = 0;
7515   int enableLVD_high = 0;
7516   unsigned char brddat = 0;
7517   unsigned char max_target = 0;
7518   unsigned char sxfrctl1 = aic_inb(p, SXFRCTL1);
7519
7520   if (acquire_seeprom(p))
7521   {
7522     if (p->features & (AHC_WIDE|AHC_TWIN))
7523       max_target = 16;
7524     else
7525       max_target = 8;
7526     aic_outb(p, SEEMS | SEECS, SEECTL);
7527     sxfrctl1 &= ~STPWEN;
7528     /*
7529      * The termination/cable detection logic is split into three distinct
7530      * groups.  Ultra2 and later controllers, 2940UW-Pro controllers, and
7531      * older 7850, 7860, 7870, 7880, and 7895 controllers.  Each has its
7532      * own unique way of detecting their cables and writing the results
7533      * back to the card.
7534      */
7535     if (p->features & AHC_ULTRA2)
7536     {
7537       /*
7538        * As long as user hasn't overridden term settings, always check the
7539        * cable detection logic
7540        */
7541       if (aic7xxx_override_term == -1)
7542       {
7543         aic7xxx_ultra2_term_detect(p, &enableSE_low, &enableSE_high,
7544                                    &enableLVD_low, &enableLVD_high,
7545                                    &eprom_present);
7546       }
7547       
7548       /*
7549        * If the user is overriding settings, then they have been preserved
7550        * to here as fake adapter_control entries.  Parse them and allow
7551        * them to override the detected settings (if we even did detection).
7552        */
7553       if (!(p->adapter_control & CFSEAUTOTERM))
7554       {
7555         enableSE_low = (p->adapter_control & CFSTERM);
7556         enableSE_high = (p->adapter_control & CFWSTERM);
7557       }
7558       if (!(p->adapter_control & CFAUTOTERM))
7559       {
7560         enableLVD_low = enableLVD_high = (p->adapter_control & CFLVDSTERM);
7561       }
7562
7563       /*
7564        * Now take those settings that we have and translate them into the
7565        * values that must be written into the registers.
7566        *
7567        * Flash Enable = BRDDAT7
7568        * Secondary High Term Enable = BRDDAT6
7569        * Secondary Low Term Enable = BRDDAT5
7570        * LVD/Primary High Term Enable = BRDDAT4
7571        * LVD/Primary Low Term Enable = STPWEN bit in SXFRCTL1
7572        */
7573       if (enableLVD_low != 0)
7574       {
7575         sxfrctl1 |= STPWEN;
7576         p->flags |= AHC_TERM_ENB_LVD;
7577         if (aic7xxx_verbose & VERBOSE_PROBE2)
7578           printk(KERN_INFO "(scsi%d) LVD/Primary Low byte termination "
7579                  "Enabled\n", p->host_no);
7580       }
7581           
7582       if (enableLVD_high != 0)
7583       {
7584         brddat |= BRDDAT4;
7585         if (aic7xxx_verbose & VERBOSE_PROBE2)
7586           printk(KERN_INFO "(scsi%d) LVD/Primary High byte termination "
7587                  "Enabled\n", p->host_no);
7588       }
7589
7590       if (enableSE_low != 0)
7591       {
7592         brddat |= BRDDAT5;
7593         if (aic7xxx_verbose & VERBOSE_PROBE2)
7594           printk(KERN_INFO "(scsi%d) Secondary Low byte termination "
7595                  "Enabled\n", p->host_no);
7596       }
7597
7598       if (enableSE_high != 0)
7599       {
7600         brddat |= BRDDAT6;
7601         if (aic7xxx_verbose & VERBOSE_PROBE2)
7602           printk(KERN_INFO "(scsi%d) Secondary High byte termination "
7603                  "Enabled\n", p->host_no);
7604       }
7605     }
7606     else if (p->features & AHC_NEW_AUTOTERM)
7607     {
7608       /*
7609        * The 50 pin connector termination is controlled by STPWEN in the
7610        * SXFRCTL1 register.  Since the Adaptec docs typically say the
7611        * controller is not allowed to be in the middle of a cable and
7612        * this is the only connection on that stub of the bus, there is
7613        * no need to even check for narrow termination, it's simply
7614        * always on.
7615        */
7616       sxfrctl1 |= STPWEN;
7617       if (aic7xxx_verbose & VERBOSE_PROBE2)
7618         printk(KERN_INFO "(scsi%d) Narrow channel termination Enabled\n",
7619                p->host_no);
7620
7621       if (p->adapter_control & CFAUTOTERM)
7622       {
7623         aic2940_uwpro_wide_cable_detect(p, &internal68_present,
7624                                         &external_present,
7625                                         &eprom_present);
7626         printk(KERN_INFO "(scsi%d) Cables present (Int-50 %s, Int-68 %s, "
7627                "Ext-68 %s)\n", p->host_no,
7628                "Don't Care",
7629                internal68_present ? "YES" : "NO",
7630                external_present ? "YES" : "NO");
7631         if (aic7xxx_verbose & VERBOSE_PROBE2)
7632           printk(KERN_INFO "(scsi%d) EEPROM %s present.\n", p->host_no,
7633                eprom_present ? "is" : "is not");
7634         if (internal68_present && external_present)
7635         {
7636           brddat = 0;
7637           p->flags &= ~AHC_TERM_ENB_SE_HIGH;
7638           if (aic7xxx_verbose & VERBOSE_PROBE2)
7639             printk(KERN_INFO "(scsi%d) Wide channel termination Disabled\n",
7640                    p->host_no);
7641         }
7642         else
7643         {
7644           brddat = BRDDAT6;
7645           p->flags |= AHC_TERM_ENB_SE_HIGH;
7646           if (aic7xxx_verbose & VERBOSE_PROBE2)
7647             printk(KERN_INFO "(scsi%d) Wide channel termination Enabled\n",
7648                    p->host_no);
7649         }
7650       }
7651       else
7652       {
7653         /*
7654          * The termination of the Wide channel is done more like normal
7655          * though, and the setting of this termination is done by writing
7656          * either a 0 or 1 to BRDDAT6 of the BRDDAT register
7657          */
7658         if (p->adapter_control & CFWSTERM)
7659         {
7660           brddat = BRDDAT6;
7661           p->flags |= AHC_TERM_ENB_SE_HIGH;
7662           if (aic7xxx_verbose & VERBOSE_PROBE2)
7663             printk(KERN_INFO "(scsi%d) Wide channel termination Enabled\n",
7664                    p->host_no);
7665         }
7666         else
7667         {
7668           brddat = 0;
7669         }
7670       }
7671     }
7672     else
7673     {
7674       if (p->adapter_control & CFAUTOTERM)
7675       {
7676         if (p->flags & AHC_MOTHERBOARD)
7677         {
7678           printk(KERN_INFO "(scsi%d) Warning - detected auto-termination\n",
7679                  p->host_no);
7680           printk(KERN_INFO "(scsi%d) Please verify driver detected settings "
7681             "are correct.\n", p->host_no);
7682           printk(KERN_INFO "(scsi%d) If not, then please properly set the "
7683             "device termination\n", p->host_no);
7684           printk(KERN_INFO "(scsi%d) in the Adaptec SCSI BIOS by hitting "
7685             "CTRL-A when prompted\n", p->host_no);
7686           printk(KERN_INFO "(scsi%d) during machine bootup.\n", p->host_no);
7687         }
7688         /* Configure auto termination. */
7689
7690         if ( (p->chip & AHC_CHIPID_MASK) >= AHC_AIC7870 )
7691         {
7692           aic787x_cable_detect(p, &internal50_present, &internal68_present,
7693             &external_present, &eprom_present);
7694         }
7695         else
7696         {
7697           aic785x_cable_detect(p, &internal50_present, &external_present,
7698             &eprom_present);
7699         }
7700
7701         if (max_target <= 8)
7702           internal68_present = 0;
7703
7704         if (max_target > 8)
7705         {
7706           printk(KERN_INFO "(scsi%d) Cables present (Int-50 %s, Int-68 %s, "
7707                  "Ext-68 %s)\n", p->host_no,
7708                  internal50_present ? "YES" : "NO",
7709                  internal68_present ? "YES" : "NO",
7710                  external_present ? "YES" : "NO");
7711         }
7712         else
7713         {
7714           printk(KERN_INFO "(scsi%d) Cables present (Int-50 %s, Ext-50 %s)\n",
7715                  p->host_no,
7716                  internal50_present ? "YES" : "NO",
7717                  external_present ? "YES" : "NO");
7718         }
7719         if (aic7xxx_verbose & VERBOSE_PROBE2)
7720           printk(KERN_INFO "(scsi%d) EEPROM %s present.\n", p->host_no,
7721                eprom_present ? "is" : "is not");
7722
7723         /*
7724          * Now set the termination based on what we found.  BRDDAT6
7725          * controls wide termination enable.
7726          * Flash Enable = BRDDAT7
7727          * SE High Term Enable = BRDDAT6
7728          */
7729         if (internal50_present && internal68_present && external_present)
7730         {
7731           printk(KERN_INFO "(scsi%d) Illegal cable configuration!!  Only two\n",
7732                  p->host_no);
7733           printk(KERN_INFO "(scsi%d) connectors on the SCSI controller may be "
7734                  "in use at a time!\n", p->host_no);
7735           /*
7736            * Force termination (low and high byte) on.  This is safer than
7737            * leaving it completely off, especially since this message comes
7738            * most often from motherboard controllers that don't even have 3
7739            * connectors, but instead are failing the cable detection.
7740            */
7741           internal50_present = external_present = 0;
7742           enableSE_high = enableSE_low = 1;
7743         }
7744
7745         if ((max_target > 8) &&
7746             ((external_present == 0) || (internal68_present == 0)) )
7747         {
7748           brddat |= BRDDAT6;
7749           p->flags |= AHC_TERM_ENB_SE_HIGH;
7750           if (aic7xxx_verbose & VERBOSE_PROBE2)
7751             printk(KERN_INFO "(scsi%d) SE High byte termination Enabled\n",
7752                    p->host_no);
7753         }
7754
7755         if ( ((internal50_present ? 1 : 0) +
7756               (internal68_present ? 1 : 0) +
7757               (external_present   ? 1 : 0)) <= 1 )
7758         {
7759           sxfrctl1 |= STPWEN;
7760           p->flags |= AHC_TERM_ENB_SE_LOW;
7761           if (aic7xxx_verbose & VERBOSE_PROBE2)
7762             printk(KERN_INFO "(scsi%d) SE Low byte termination Enabled\n",
7763                    p->host_no);
7764         }
7765       }
7766       else /* p->adapter_control & CFAUTOTERM */
7767       {
7768         if (p->adapter_control & CFSTERM)
7769         {
7770           sxfrctl1 |= STPWEN;
7771           if (aic7xxx_verbose & VERBOSE_PROBE2)
7772             printk(KERN_INFO "(scsi%d) SE Low byte termination Enabled\n",
7773                    p->host_no);
7774         }
7775
7776         if (p->adapter_control & CFWSTERM)
7777         {
7778           brddat |= BRDDAT6;
7779           if (aic7xxx_verbose & VERBOSE_PROBE2)
7780             printk(KERN_INFO "(scsi%d) SE High byte termination Enabled\n",
7781                    p->host_no);
7782         }
7783       }
7784     }
7785
7786     aic_outb(p, sxfrctl1, SXFRCTL1);
7787     write_brdctl(p, brddat);
7788     release_seeprom(p);
7789   }
7790 }
7791
7792 /*+F*************************************************************************
7793  * Function:
7794  *   detect_maxscb
7795  *
7796  * Description:
7797  *   Detects the maximum number of SCBs for the controller and returns
7798  *   the count and a mask in p (p->maxscbs, p->qcntmask).
7799  *-F*************************************************************************/
7800 static void
7801 detect_maxscb(struct aic7xxx_host *p)
7802 {
7803   int i;
7804
7805   /*
7806    * It's possible that we've already done this for multichannel
7807    * adapters.
7808    */
7809   if (p->scb_data->maxhscbs == 0)
7810   {
7811     /*
7812      * We haven't initialized the SCB settings yet.  Walk the SCBs to
7813      * determince how many there are.
7814      */
7815     aic_outb(p, 0, FREE_SCBH);
7816
7817     for (i = 0; i < AIC7XXX_MAXSCB; i++)
7818     {
7819       aic_outb(p, i, SCBPTR);
7820       aic_outb(p, i, SCB_CONTROL);
7821       if (aic_inb(p, SCB_CONTROL) != i)
7822         break;
7823       aic_outb(p, 0, SCBPTR);
7824       if (aic_inb(p, SCB_CONTROL) != 0)
7825         break;
7826
7827       aic_outb(p, i, SCBPTR);
7828       aic_outb(p, 0, SCB_CONTROL);   /* Clear the control byte. */
7829       aic_outb(p, i + 1, SCB_NEXT);  /* Set the next pointer. */
7830       aic_outb(p, SCB_LIST_NULL, SCB_TAG);  /* Make the tag invalid. */
7831       aic_outb(p, SCB_LIST_NULL, SCB_BUSYTARGETS);  /* no busy untagged */
7832       aic_outb(p, SCB_LIST_NULL, SCB_BUSYTARGETS+1);/* targets active yet */
7833       aic_outb(p, SCB_LIST_NULL, SCB_BUSYTARGETS+2);
7834       aic_outb(p, SCB_LIST_NULL, SCB_BUSYTARGETS+3);
7835     }
7836
7837     /* Make sure the last SCB terminates the free list. */
7838     aic_outb(p, i - 1, SCBPTR);
7839     aic_outb(p, SCB_LIST_NULL, SCB_NEXT);
7840
7841     /* Ensure we clear the first (0) SCBs control byte. */
7842     aic_outb(p, 0, SCBPTR);
7843     aic_outb(p, 0, SCB_CONTROL);
7844
7845     p->scb_data->maxhscbs = i;
7846     /*
7847      * Use direct indexing instead for speed
7848      */
7849     if ( i == AIC7XXX_MAXSCB )
7850       p->flags &= ~AHC_PAGESCBS;
7851   }
7852
7853 }
7854
7855 /*+F*************************************************************************
7856  * Function:
7857  *   aic7xxx_register
7858  *
7859  * Description:
7860  *   Register a Adaptec aic7xxx chip SCSI controller with the kernel.
7861  *-F*************************************************************************/
7862 static int
7863 aic7xxx_register(struct scsi_host_template *template, struct aic7xxx_host *p,
7864   int reset_delay)
7865 {
7866   int i, result;
7867   int max_targets;
7868   int found = 1;
7869   unsigned char term, scsi_conf;
7870   struct Scsi_Host *host;
7871
7872   host = p->host;
7873
7874   p->scb_data->maxscbs = AIC7XXX_MAXSCB;
7875   host->can_queue = AIC7XXX_MAXSCB;
7876   host->cmd_per_lun = 3;
7877   host->sg_tablesize = AIC7XXX_MAX_SG;
7878   host->this_id = p->scsi_id;
7879   host->io_port = p->base;
7880   host->n_io_port = 0xFF;
7881   host->base = p->mbase;
7882   host->irq = p->irq;
7883   if (p->features & AHC_WIDE)
7884   {
7885     host->max_id = 16;
7886   }
7887   if (p->features & AHC_TWIN)
7888   {
7889     host->max_channel = 1;
7890   }
7891
7892   p->host = host;
7893   p->host_no = host->host_no;
7894   host->unique_id = p->instance;
7895   p->isr_count = 0;
7896   p->next = NULL;
7897   p->completeq.head = NULL;
7898   p->completeq.tail = NULL;
7899   scbq_init(&p->scb_data->free_scbs);
7900   scbq_init(&p->waiting_scbs);
7901   INIT_LIST_HEAD(&p->aic_devs);
7902
7903   /*
7904    * We currently have no commands of any type
7905    */
7906   p->qinfifonext = 0;
7907   p->qoutfifonext = 0;
7908
7909   printk(KERN_INFO "(scsi%d) <%s> found at ", p->host_no,
7910     board_names[p->board_name_index]);
7911   switch(p->chip)
7912   {
7913     case (AHC_AIC7770|AHC_EISA):
7914       printk("EISA slot %d\n", p->pci_device_fn);
7915       break;
7916     case (AHC_AIC7770|AHC_VL):
7917       printk("VLB slot %d\n", p->pci_device_fn);
7918       break;
7919     default:
7920       printk("PCI %d/%d/%d\n", p->pci_bus, PCI_SLOT(p->pci_device_fn),
7921         PCI_FUNC(p->pci_device_fn));
7922       break;
7923   }
7924   if (p->features & AHC_TWIN)
7925   {
7926     printk(KERN_INFO "(scsi%d) Twin Channel, A SCSI ID %d, B SCSI ID %d, ",
7927            p->host_no, p->scsi_id, p->scsi_id_b);
7928   }
7929   else
7930   {
7931     char *channel;
7932
7933     channel = "";
7934
7935     if ((p->flags & AHC_MULTI_CHANNEL) != 0)
7936     {
7937       channel = " A";
7938
7939       if ( (p->flags & (AHC_CHNLB|AHC_CHNLC)) != 0 )
7940       {
7941         channel = (p->flags & AHC_CHNLB) ? " B" : " C";
7942       }
7943     }
7944     if (p->features & AHC_WIDE)
7945     {
7946       printk(KERN_INFO "(scsi%d) Wide ", p->host_no);
7947     }
7948     else
7949     {
7950       printk(KERN_INFO "(scsi%d) Narrow ", p->host_no);
7951     }
7952     printk("Channel%s, SCSI ID=%d, ", channel, p->scsi_id);
7953   }
7954   aic_outb(p, 0, SEQ_FLAGS);
7955
7956   detect_maxscb(p);
7957
7958   printk("%d/%d SCBs\n", p->scb_data->maxhscbs, p->scb_data->maxscbs);
7959   if (aic7xxx_verbose & VERBOSE_PROBE2)
7960   {
7961     printk(KERN_INFO "(scsi%d) BIOS %sabled, IO Port 0x%lx, IRQ %d\n",
7962       p->host_no, (p->flags & AHC_BIOS_ENABLED) ? "en" : "dis",
7963       p->base, p->irq);
7964     printk(KERN_INFO "(scsi%d) IO Memory at 0x%lx, MMAP Memory at %p\n",
7965       p->host_no, p->mbase, p->maddr);
7966   }
7967
7968 #ifdef CONFIG_PCI
7969   /*
7970    * Now that we know our instance number, we can set the flags we need to
7971    * force termination if need be.
7972    */
7973   if (aic7xxx_stpwlev != -1)
7974   {
7975     /*
7976      * This option only applies to PCI controllers.
7977      */
7978     if ( (p->chip & ~AHC_CHIPID_MASK) == AHC_PCI)
7979     {
7980       unsigned char devconfig;
7981
7982       pci_read_config_byte(p->pdev, DEVCONFIG, &devconfig);
7983       if ( (aic7xxx_stpwlev >> p->instance) & 0x01 )
7984       {
7985         devconfig |= STPWLEVEL;
7986         if (aic7xxx_verbose & VERBOSE_PROBE2)
7987           printk("(scsi%d) Force setting STPWLEVEL bit\n", p->host_no);
7988       }
7989       else
7990       {
7991         devconfig &= ~STPWLEVEL;
7992         if (aic7xxx_verbose & VERBOSE_PROBE2)
7993           printk("(scsi%d) Force clearing STPWLEVEL bit\n", p->host_no);
7994       }
7995       pci_write_config_byte(p->pdev, DEVCONFIG, devconfig);
7996     }
7997   }
7998 #endif
7999
8000   /*
8001    * That took care of devconfig and stpwlev, now for the actual termination
8002    * settings.
8003    */
8004   if (aic7xxx_override_term != -1)
8005   {
8006     /*
8007      * Again, this only applies to PCI controllers.  We don't have problems
8008      * with the termination on 274x controllers to the best of my knowledge.
8009      */
8010     if ( (p->chip & ~AHC_CHIPID_MASK) == AHC_PCI)
8011     {
8012       unsigned char term_override;
8013
8014       term_override = ( (aic7xxx_override_term >> (p->instance * 4)) & 0x0f);
8015       p->adapter_control &= 
8016         ~(CFSTERM|CFWSTERM|CFLVDSTERM|CFAUTOTERM|CFSEAUTOTERM);
8017       if ( (p->features & AHC_ULTRA2) && (term_override & 0x0c) )
8018       {
8019         p->adapter_control |= CFLVDSTERM;
8020       }
8021       if (term_override & 0x02)
8022       {
8023         p->adapter_control |= CFWSTERM;
8024       }
8025       if (term_override & 0x01)
8026       {
8027         p->adapter_control |= CFSTERM;
8028       }
8029     }
8030   }
8031
8032   if ( (p->flags & AHC_SEEPROM_FOUND) || (aic7xxx_override_term != -1) )
8033   {
8034     if (p->features & AHC_SPIOCAP)
8035     {
8036       if ( aic_inb(p, SPIOCAP) & SSPIOCPS )
8037       /*
8038        * Update the settings in sxfrctl1 to match the termination
8039        * settings.
8040        */
8041         configure_termination(p);
8042     }
8043     else if ((p->chip & AHC_CHIPID_MASK) >= AHC_AIC7870)
8044     {
8045       configure_termination(p);
8046     }
8047   }
8048
8049   /*
8050    * Set the SCSI Id, SXFRCTL0, SXFRCTL1, and SIMODE1, for both channels
8051    */
8052   if (p->features & AHC_TWIN)
8053   {
8054     /* Select channel B */
8055     aic_outb(p, aic_inb(p, SBLKCTL) | SELBUSB, SBLKCTL);
8056
8057     if ((p->flags & AHC_SEEPROM_FOUND) || (aic7xxx_override_term != -1))
8058       term = (aic_inb(p, SXFRCTL1) & STPWEN);
8059     else
8060       term = ((p->flags & AHC_TERM_ENB_B) ? STPWEN : 0);
8061
8062     aic_outb(p, p->scsi_id_b, SCSIID);
8063     scsi_conf = aic_inb(p, SCSICONF + 1);
8064     aic_outb(p, DFON | SPIOEN, SXFRCTL0);
8065     aic_outb(p, (scsi_conf & ENSPCHK) | aic7xxx_seltime | term | 
8066          ENSTIMER | ACTNEGEN, SXFRCTL1);
8067     aic_outb(p, 0, SIMODE0);
8068     aic_outb(p, ENSELTIMO | ENSCSIRST | ENSCSIPERR, SIMODE1);
8069     aic_outb(p, 0, SCSIRATE);
8070
8071     /* Select channel A */
8072     aic_outb(p, aic_inb(p, SBLKCTL) & ~SELBUSB, SBLKCTL);
8073   }
8074
8075   if (p->features & AHC_ULTRA2)
8076   {
8077     aic_outb(p, p->scsi_id, SCSIID_ULTRA2);
8078   }
8079   else
8080   {
8081     aic_outb(p, p->scsi_id, SCSIID);
8082   }
8083   if ((p->flags & AHC_SEEPROM_FOUND) || (aic7xxx_override_term != -1))
8084     term = (aic_inb(p, SXFRCTL1) & STPWEN);
8085   else
8086     term = ((p->flags & (AHC_TERM_ENB_A|AHC_TERM_ENB_LVD)) ? STPWEN : 0);
8087   scsi_conf = aic_inb(p, SCSICONF);
8088   aic_outb(p, DFON | SPIOEN, SXFRCTL0);
8089   aic_outb(p, (scsi_conf & ENSPCHK) | aic7xxx_seltime | term | 
8090        ENSTIMER | ACTNEGEN, SXFRCTL1);
8091   aic_outb(p, 0, SIMODE0);
8092   /*
8093    * If we are a cardbus adapter then don't enable SCSI reset detection.
8094    * We shouldn't likely be sharing SCSI busses with someone else, and
8095    * if we don't have a cable currently plugged into the controller then
8096    * we won't have a power source for the SCSI termination, which means
8097    * we'll see infinite incoming bus resets.
8098    */
8099   if(p->flags & AHC_NO_STPWEN)
8100     aic_outb(p, ENSELTIMO | ENSCSIPERR, SIMODE1);
8101   else
8102     aic_outb(p, ENSELTIMO | ENSCSIRST | ENSCSIPERR, SIMODE1);
8103   aic_outb(p, 0, SCSIRATE);
8104   if ( p->features & AHC_ULTRA2)
8105     aic_outb(p, 0, SCSIOFFSET);
8106
8107   /*
8108    * Look at the information that board initialization or the board
8109    * BIOS has left us. In the lower four bits of each target's
8110    * scratch space any value other than 0 indicates that we should
8111    * initiate synchronous transfers. If it's zero, the user or the
8112    * BIOS has decided to disable synchronous negotiation to that
8113    * target so we don't activate the needsdtr flag.
8114    */
8115   if ((p->features & (AHC_TWIN|AHC_WIDE)) == 0)
8116   {
8117     max_targets = 8;
8118   }
8119   else
8120   {
8121     max_targets = 16;
8122   }
8123
8124   if (!(aic7xxx_no_reset))
8125   {
8126     /*
8127      * If we reset the bus, then clear the transfer settings, else leave
8128      * them be.
8129      */
8130     aic_outb(p, 0, ULTRA_ENB);
8131     aic_outb(p, 0, ULTRA_ENB + 1);
8132     p->ultraenb = 0;
8133   }
8134
8135   /*
8136    * Allocate enough hardware scbs to handle the maximum number of
8137    * concurrent transactions we can have.  We have to make sure that
8138    * the allocated memory is contiguous memory.  The Linux kmalloc
8139    * routine should only allocate contiguous memory, but note that
8140    * this could be a problem if kmalloc() is changed.
8141    */
8142   {
8143     size_t array_size;
8144     unsigned int hscb_physaddr;
8145
8146     array_size = p->scb_data->maxscbs * sizeof(struct aic7xxx_hwscb);
8147     if (p->scb_data->hscbs == NULL)
8148     {
8149       /* pci_alloc_consistent enforces the alignment already and
8150        * clears the area as well.
8151        */
8152       p->scb_data->hscbs = pci_alloc_consistent(p->pdev, array_size,
8153                                                 &p->scb_data->hscbs_dma);
8154       /* We have to use pci_free_consistent, not kfree */
8155       p->scb_data->hscb_kmalloc_ptr = NULL;
8156       p->scb_data->hscbs_dma_len = array_size;
8157     }
8158     if (p->scb_data->hscbs == NULL)
8159     {
8160       printk("(scsi%d) Unable to allocate hardware SCB array; "
8161              "failing detection.\n", p->host_no);
8162       aic_outb(p, 0, SIMODE1);
8163       p->irq = 0;
8164       return(0);
8165     }
8166
8167     hscb_physaddr = p->scb_data->hscbs_dma;
8168     aic_outb(p, hscb_physaddr & 0xFF, HSCB_ADDR);
8169     aic_outb(p, (hscb_physaddr >> 8) & 0xFF, HSCB_ADDR + 1);
8170     aic_outb(p, (hscb_physaddr >> 16) & 0xFF, HSCB_ADDR + 2);
8171     aic_outb(p, (hscb_physaddr >> 24) & 0xFF, HSCB_ADDR + 3);
8172
8173     /* Set up the fifo areas at the same time */
8174     p->untagged_scbs = pci_alloc_consistent(p->pdev, 3*256, &p->fifo_dma);
8175     if (p->untagged_scbs == NULL)
8176     {
8177       printk("(scsi%d) Unable to allocate hardware FIFO arrays; "
8178              "failing detection.\n", p->host_no);
8179       p->irq = 0;
8180       return(0);
8181     }
8182
8183     p->qoutfifo = p->untagged_scbs + 256;
8184     p->qinfifo = p->qoutfifo + 256;
8185     for (i = 0; i < 256; i++)
8186     {
8187       p->untagged_scbs[i] = SCB_LIST_NULL;
8188       p->qinfifo[i] = SCB_LIST_NULL;
8189       p->qoutfifo[i] = SCB_LIST_NULL;
8190     }
8191
8192     hscb_physaddr = p->fifo_dma;
8193     aic_outb(p, hscb_physaddr & 0xFF, SCBID_ADDR);
8194     aic_outb(p, (hscb_physaddr >> 8) & 0xFF, SCBID_ADDR + 1);
8195     aic_outb(p, (hscb_physaddr >> 16) & 0xFF, SCBID_ADDR + 2);
8196     aic_outb(p, (hscb_physaddr >> 24) & 0xFF, SCBID_ADDR + 3);
8197   }
8198
8199   /* The Q-FIFOs we just set up are all empty */
8200   aic_outb(p, 0, QINPOS);
8201   aic_outb(p, 0, KERNEL_QINPOS);
8202   aic_outb(p, 0, QOUTPOS);
8203
8204   if(p->features & AHC_QUEUE_REGS)
8205   {
8206     aic_outb(p, SCB_QSIZE_256, QOFF_CTLSTA);
8207     aic_outb(p, 0, SDSCB_QOFF);
8208     aic_outb(p, 0, SNSCB_QOFF);
8209     aic_outb(p, 0, HNSCB_QOFF);
8210   }
8211
8212   /*
8213    * We don't have any waiting selections or disconnected SCBs.
8214    */
8215   aic_outb(p, SCB_LIST_NULL, WAITING_SCBH);
8216   aic_outb(p, SCB_LIST_NULL, DISCONNECTED_SCBH);
8217
8218   /*
8219    * Message out buffer starts empty
8220    */
8221   aic_outb(p, MSG_NOOP, MSG_OUT);
8222   aic_outb(p, MSG_NOOP, LAST_MSG);
8223
8224   /*
8225    * Set all the other asundry items that haven't been set yet.
8226    * This includes just dumping init values to a lot of registers simply
8227    * to make sure they've been touched and are ready for use parity wise
8228    * speaking.
8229    */
8230   aic_outb(p, 0, TMODE_CMDADDR);
8231   aic_outb(p, 0, TMODE_CMDADDR + 1);
8232   aic_outb(p, 0, TMODE_CMDADDR + 2);
8233   aic_outb(p, 0, TMODE_CMDADDR + 3);
8234   aic_outb(p, 0, TMODE_CMDADDR_NEXT);
8235
8236   /*
8237    * Link us into the list of valid hosts
8238    */
8239   p->next = first_aic7xxx;
8240   first_aic7xxx = p;
8241
8242   /*
8243    * Allocate the first set of scbs for this controller.  This is to stream-
8244    * line code elsewhere in the driver.  If we have to check for the existence
8245    * of scbs in certain code sections, it slows things down.  However, as
8246    * soon as we register the IRQ for this card, we could get an interrupt that
8247    * includes possibly the SCSI_RSTI interrupt.  If we catch that interrupt
8248    * then we are likely to segfault if we don't have at least one chunk of
8249    * SCBs allocated or add checks all through the reset code to make sure
8250    * that the SCBs have been allocated which is an invalid running condition
8251    * and therefore I think it's preferable to simply pre-allocate the first
8252    * chunk of SCBs.
8253    */
8254   aic7xxx_allocate_scb(p);
8255
8256   /*
8257    * Load the sequencer program, then re-enable the board -
8258    * resetting the AIC-7770 disables it, leaving the lights
8259    * on with nobody home.
8260    */
8261   aic7xxx_loadseq(p);
8262
8263   /*
8264    * Make sure the AUTOFLUSHDIS bit is *not* set in the SBLKCTL register
8265    */
8266   aic_outb(p, aic_inb(p, SBLKCTL) & ~AUTOFLUSHDIS, SBLKCTL);
8267
8268   if ( (p->chip & AHC_CHIPID_MASK) == AHC_AIC7770 )
8269   {
8270     aic_outb(p, ENABLE, BCTL);  /* Enable the boards BUS drivers. */
8271   }
8272
8273   if ( !(aic7xxx_no_reset) )
8274   {
8275     if (p->features & AHC_TWIN)
8276     {
8277       if (aic7xxx_verbose & VERBOSE_PROBE2)
8278         printk(KERN_INFO "(scsi%d) Resetting channel B\n", p->host_no);
8279       aic_outb(p, aic_inb(p, SBLKCTL) | SELBUSB, SBLKCTL);
8280       aic7xxx_reset_current_bus(p);
8281       aic_outb(p, aic_inb(p, SBLKCTL) & ~SELBUSB, SBLKCTL);
8282     }
8283     /* Reset SCSI bus A. */
8284     if (aic7xxx_verbose & VERBOSE_PROBE2)
8285     {  /* In case we are a 3940, 3985, or 7895, print the right channel */
8286       char *channel = "";
8287       if (p->flags & AHC_MULTI_CHANNEL)
8288       {
8289         channel = " A";
8290         if (p->flags & (AHC_CHNLB|AHC_CHNLC))
8291           channel = (p->flags & AHC_CHNLB) ? " B" : " C";
8292       }
8293       printk(KERN_INFO "(scsi%d) Resetting channel%s\n", p->host_no, channel);
8294     }
8295     
8296     aic7xxx_reset_current_bus(p);
8297
8298   }
8299   else
8300   {
8301     if (!reset_delay)
8302     {
8303       printk(KERN_INFO "(scsi%d) Not resetting SCSI bus.  Note: Don't use "
8304              "the no_reset\n", p->host_no);
8305       printk(KERN_INFO "(scsi%d) option unless you have a verifiable need "
8306              "for it.\n", p->host_no);
8307     }
8308   }
8309   
8310   /*
8311    * Register IRQ with the kernel.  Only allow sharing IRQs with
8312    * PCI devices.
8313    */
8314   if (!(p->chip & AHC_PCI))
8315   {
8316     result = (request_irq(p->irq, do_aic7xxx_isr, 0, "aic7xxx", p));
8317   }
8318   else
8319   {
8320     result = (request_irq(p->irq, do_aic7xxx_isr, IRQF_SHARED,
8321               "aic7xxx", p));
8322     if (result < 0)
8323     {
8324       result = (request_irq(p->irq, do_aic7xxx_isr, IRQF_DISABLED | IRQF_SHARED,
8325               "aic7xxx", p));
8326     }
8327   }
8328   if (result < 0)
8329   {
8330     printk(KERN_WARNING "(scsi%d) Couldn't register IRQ %d, ignoring "
8331            "controller.\n", p->host_no, p->irq);
8332     aic_outb(p, 0, SIMODE1);
8333     p->irq = 0;
8334     return (0);
8335   }
8336
8337   if(aic_inb(p, INTSTAT) & INT_PEND)
8338     printk(INFO_LEAD "spurious interrupt during configuration, cleared.\n",
8339       p->host_no, -1, -1 , -1);
8340   aic7xxx_clear_intstat(p);
8341
8342   unpause_sequencer(p, /* unpause_always */ TRUE);
8343
8344   return (found);
8345 }
8346
8347 /*+F*************************************************************************
8348  * Function:
8349  *   aic7xxx_chip_reset
8350  *
8351  * Description:
8352  *   Perform a chip reset on the aic7xxx SCSI controller.  The controller
8353  *   is paused upon return.
8354  *-F*************************************************************************/
8355 static int
8356 aic7xxx_chip_reset(struct aic7xxx_host *p)
8357 {
8358   unsigned char sblkctl;
8359   int wait;
8360
8361   /*
8362    * For some 274x boards, we must clear the CHIPRST bit and pause
8363    * the sequencer. For some reason, this makes the driver work.
8364    */
8365   aic_outb(p, PAUSE | CHIPRST, HCNTRL);
8366
8367   /*
8368    * In the future, we may call this function as a last resort for
8369    * error handling.  Let's be nice and not do any unnecessary delays.
8370    */
8371   wait = 1000;  /* 1 msec (1000 * 1 msec) */
8372   while (--wait && !(aic_inb(p, HCNTRL) & CHIPRSTACK))
8373   {
8374     udelay(1);  /* 1 usec */
8375   }
8376
8377   pause_sequencer(p);
8378
8379   sblkctl = aic_inb(p, SBLKCTL) & (SELBUSB|SELWIDE);
8380   if (p->chip & AHC_PCI)
8381     sblkctl &= ~SELBUSB;
8382   switch( sblkctl )
8383   {
8384     case 0:  /* normal narrow card */
8385       break;
8386     case 2:  /* Wide card */
8387       p->features |= AHC_WIDE;
8388       break;
8389     case 8:  /* Twin card */
8390       p->features |= AHC_TWIN;
8391       p->flags |= AHC_MULTI_CHANNEL;
8392       break;
8393     default: /* hmmm...we don't know what this is */
8394       printk(KERN_WARNING "aic7xxx: Unsupported adapter type %d, ignoring.\n",
8395         aic_inb(p, SBLKCTL) & 0x0a);
8396       return(-1);
8397   }
8398   return(0);
8399 }
8400
8401 /*+F*************************************************************************
8402  * Function:
8403  *   aic7xxx_alloc
8404  *
8405  * Description:
8406  *   Allocate and initialize a host structure.  Returns NULL upon error
8407  *   and a pointer to a aic7xxx_host struct upon success.
8408  *-F*************************************************************************/
8409 static struct aic7xxx_host *
8410 aic7xxx_alloc(struct scsi_host_template *sht, struct aic7xxx_host *temp)
8411 {
8412   struct aic7xxx_host *p = NULL;
8413   struct Scsi_Host *host;
8414
8415   /*
8416    * Allocate a storage area by registering us with the mid-level
8417    * SCSI layer.
8418    */
8419   host = scsi_register(sht, sizeof(struct aic7xxx_host));
8420
8421   if (host != NULL)
8422   {
8423     p = (struct aic7xxx_host *) host->hostdata;
8424     memset(p, 0, sizeof(struct aic7xxx_host));
8425     *p = *temp;
8426     p->host = host;
8427
8428     p->scb_data = kmalloc(sizeof(scb_data_type), GFP_ATOMIC);
8429     if (p->scb_data != NULL)
8430     {
8431       memset(p->scb_data, 0, sizeof(scb_data_type));
8432       scbq_init (&p->scb_data->free_scbs);
8433     }
8434     else
8435     {
8436       /*
8437        * For some reason we don't have enough memory.  Free the
8438        * allocated memory for the aic7xxx_host struct, and return NULL.
8439        */
8440       release_region(p->base, MAXREG - MINREG);
8441       scsi_unregister(host);
8442       return(NULL);
8443     }
8444     p->host_no = host->host_no;
8445   }
8446   return (p);
8447 }
8448
8449 /*+F*************************************************************************
8450  * Function:
8451  *   aic7xxx_free
8452  *
8453  * Description:
8454  *   Frees and releases all resources associated with an instance of
8455  *   the driver (struct aic7xxx_host *).
8456  *-F*************************************************************************/
8457 static void
8458 aic7xxx_free(struct aic7xxx_host *p)
8459 {
8460   int i;
8461
8462   /*
8463    * Free the allocated hardware SCB space.
8464    */
8465   if (p->scb_data != NULL)
8466   {
8467     struct aic7xxx_scb_dma *scb_dma = NULL;
8468     if (p->scb_data->hscbs != NULL)
8469     {
8470       pci_free_consistent(p->pdev, p->scb_data->hscbs_dma_len,
8471                           p->scb_data->hscbs, p->scb_data->hscbs_dma);
8472       p->scb_data->hscbs = p->scb_data->hscb_kmalloc_ptr = NULL;
8473     }
8474     /*
8475      * Free the driver SCBs.  These were allocated on an as-need
8476      * basis.  We allocated these in groups depending on how many
8477      * we could fit into a given amount of RAM.  The tail SCB for
8478      * these allocations has a pointer to the alloced area.
8479      */
8480     for (i = 0; i < p->scb_data->numscbs; i++)
8481     {
8482       if (p->scb_data->scb_array[i]->scb_dma != scb_dma)
8483       {
8484         scb_dma = p->scb_data->scb_array[i]->scb_dma;
8485         pci_free_consistent(p->pdev, scb_dma->dma_len,
8486                             (void *)((unsigned long)scb_dma->dma_address
8487                                      - scb_dma->dma_offset),
8488                             scb_dma->dma_address);
8489       }
8490       kfree(p->scb_data->scb_array[i]->kmalloc_ptr);
8491       p->scb_data->scb_array[i] = NULL;
8492     }
8493   
8494     /*
8495      * Free the SCB data area.
8496      */
8497     kfree(p->scb_data);
8498   }
8499
8500   pci_free_consistent(p->pdev, 3*256, (void *)p->untagged_scbs, p->fifo_dma);
8501 }
8502
8503 /*+F*************************************************************************
8504  * Function:
8505  *   aic7xxx_load_seeprom
8506  *
8507  * Description:
8508  *   Load the seeprom and configure adapter and target settings.
8509  *   Returns 1 if the load was successful and 0 otherwise.
8510  *-F*************************************************************************/
8511 static void
8512 aic7xxx_load_seeprom(struct aic7xxx_host *p, unsigned char *sxfrctl1)
8513 {
8514   int have_seeprom = 0;
8515   int i, max_targets, mask;
8516   unsigned char scsirate, scsi_conf;
8517   unsigned short scarray[128];
8518   struct seeprom_config *sc = (struct seeprom_config *) scarray;
8519
8520   if (aic7xxx_verbose & VERBOSE_PROBE2)
8521   {
8522     printk(KERN_INFO "aic7xxx: Loading serial EEPROM...");
8523   }
8524   switch (p->chip)
8525   {
8526     case (AHC_AIC7770|AHC_EISA):  /* None of these adapters have seeproms. */
8527       if (aic_inb(p, SCSICONF) & TERM_ENB)
8528         p->flags |= AHC_TERM_ENB_A;
8529       if ( (p->features & AHC_TWIN) && (aic_inb(p, SCSICONF + 1) & TERM_ENB) )
8530         p->flags |= AHC_TERM_ENB_B;
8531       break;
8532
8533     case (AHC_AIC7770|AHC_VL):
8534       have_seeprom = read_284x_seeprom(p, (struct seeprom_config *) scarray);
8535       break;
8536
8537     default:
8538       have_seeprom = read_seeprom(p, (p->flags & (AHC_CHNLB|AHC_CHNLC)),
8539                                   scarray, p->sc_size, p->sc_type);
8540       if (!have_seeprom)
8541       {
8542         if(p->sc_type == C46)
8543           have_seeprom = read_seeprom(p, (p->flags & (AHC_CHNLB|AHC_CHNLC)),
8544                                       scarray, p->sc_size, C56_66);
8545         else
8546           have_seeprom = read_seeprom(p, (p->flags & (AHC_CHNLB|AHC_CHNLC)),
8547                                       scarray, p->sc_size, C46);
8548       }
8549       if (!have_seeprom)
8550       {
8551         p->sc_size = 128;
8552         have_seeprom = read_seeprom(p, 4*(p->flags & (AHC_CHNLB|AHC_CHNLC)),
8553                                     scarray, p->sc_size, p->sc_type);
8554         if (!have_seeprom)
8555         {
8556           if(p->sc_type == C46)
8557             have_seeprom = read_seeprom(p, 4*(p->flags & (AHC_CHNLB|AHC_CHNLC)),
8558                                         scarray, p->sc_size, C56_66);
8559           else
8560             have_seeprom = read_seeprom(p, 4*(p->flags & (AHC_CHNLB|AHC_CHNLC)),
8561                                         scarray, p->sc_size, C46);
8562         }
8563       }
8564       break;
8565   }
8566
8567   if (!have_seeprom)
8568   {
8569     if (aic7xxx_verbose & VERBOSE_PROBE2)
8570     {
8571       printk("\naic7xxx: No SEEPROM available.\n");
8572     }
8573     p->flags |= AHC_NEWEEPROM_FMT;
8574     if (aic_inb(p, SCSISEQ) == 0)
8575     {
8576       p->flags |= AHC_USEDEFAULTS;
8577       p->flags &= ~AHC_BIOS_ENABLED;
8578       p->scsi_id = p->scsi_id_b = 7;
8579       *sxfrctl1 |= STPWEN;
8580       if (aic7xxx_verbose & VERBOSE_PROBE2)
8581       {
8582         printk("aic7xxx: Using default values.\n");
8583       }
8584     }
8585     else if (aic7xxx_verbose & VERBOSE_PROBE2)
8586     {
8587       printk("aic7xxx: Using leftover BIOS values.\n");
8588     }
8589     if ( ((p->chip & ~AHC_CHIPID_MASK) == AHC_PCI) && (*sxfrctl1 & STPWEN) )
8590     {
8591       p->flags |= AHC_TERM_ENB_SE_LOW | AHC_TERM_ENB_SE_HIGH;
8592       sc->adapter_control &= ~CFAUTOTERM;
8593       sc->adapter_control |= CFSTERM | CFWSTERM | CFLVDSTERM;
8594     }
8595     if (aic7xxx_extended)
8596       p->flags |= (AHC_EXTEND_TRANS_A | AHC_EXTEND_TRANS_B);
8597     else
8598       p->flags &= ~(AHC_EXTEND_TRANS_A | AHC_EXTEND_TRANS_B);
8599   }
8600   else
8601   {
8602     if (aic7xxx_verbose & VERBOSE_PROBE2)
8603     {
8604       printk("done\n");
8605     }
8606
8607     /*
8608      * Note things in our flags
8609      */
8610     p->flags |= AHC_SEEPROM_FOUND;
8611
8612     /*
8613      * Update the settings in sxfrctl1 to match the termination settings.
8614      */
8615     *sxfrctl1 = 0;
8616
8617     /*
8618      * Get our SCSI ID from the SEEPROM setting...
8619      */
8620     p->scsi_id = (sc->brtime_id & CFSCSIID);
8621
8622     /*
8623      * First process the settings that are different between the VLB
8624      * and PCI adapter seeproms.
8625      */
8626     if ((p->chip & AHC_CHIPID_MASK) == AHC_AIC7770)
8627     {
8628       /* VLB adapter seeproms */
8629       if (sc->bios_control & CF284XEXTEND)
8630         p->flags |= AHC_EXTEND_TRANS_A;
8631
8632       if (sc->adapter_control & CF284XSTERM)
8633       {
8634         *sxfrctl1 |= STPWEN;
8635         p->flags |= AHC_TERM_ENB_SE_LOW | AHC_TERM_ENB_SE_HIGH;
8636       }
8637     }
8638     else
8639     {
8640       /* PCI adapter seeproms */
8641       if (sc->bios_control & CFEXTEND)
8642         p->flags |= AHC_EXTEND_TRANS_A;
8643       if (sc->bios_control & CFBIOSEN)
8644         p->flags |= AHC_BIOS_ENABLED;
8645       else
8646         p->flags &= ~AHC_BIOS_ENABLED;
8647
8648       if (sc->adapter_control & CFSTERM)
8649       {
8650         *sxfrctl1 |= STPWEN;
8651         p->flags |= AHC_TERM_ENB_SE_LOW | AHC_TERM_ENB_SE_HIGH;
8652       }
8653     }
8654     memcpy(&p->sc, sc, sizeof(struct seeprom_config));
8655   }
8656
8657   p->discenable = 0;
8658
8659   /*
8660    * Limit to 16 targets just in case.  The 2842 for one is known to
8661    * blow the max_targets setting, future cards might also.
8662    */
8663   max_targets = ((p->features & (AHC_TWIN | AHC_WIDE)) ? 16 : 8);
8664
8665   if (have_seeprom)
8666   {
8667     for (i = 0; i < max_targets; i++)
8668     {
8669       if( ((p->features & AHC_ULTRA) &&
8670           !(sc->adapter_control & CFULTRAEN) &&
8671            (sc->device_flags[i] & CFSYNCHISULTRA)) ||
8672           (sc->device_flags[i] & CFNEWULTRAFORMAT) )
8673       {
8674         p->flags |= AHC_NEWEEPROM_FMT;
8675         break;
8676       }
8677     }
8678   }
8679
8680   for (i = 0; i < max_targets; i++)
8681   {
8682     mask = (0x01 << i);
8683     if (!have_seeprom)
8684     {
8685       if (aic_inb(p, SCSISEQ) != 0)
8686       {
8687         /*
8688          * OK...the BIOS set things up and left behind the settings we need.
8689          * Just make our sc->device_flags[i] entry match what the card has
8690          * set for this device.
8691          */
8692         p->discenable =
8693           ~(aic_inb(p, DISC_DSB) | (aic_inb(p, DISC_DSB + 1) << 8) );
8694         p->ultraenb =
8695           (aic_inb(p, ULTRA_ENB) | (aic_inb(p, ULTRA_ENB + 1) << 8) );
8696         sc->device_flags[i] = (p->discenable & mask) ? CFDISC : 0;
8697         if (aic_inb(p, TARG_SCSIRATE + i) & WIDEXFER)
8698           sc->device_flags[i] |= CFWIDEB;
8699         if (p->features & AHC_ULTRA2)
8700         {
8701           if (aic_inb(p, TARG_OFFSET + i))
8702           {
8703             sc->device_flags[i] |= CFSYNCH;
8704             sc->device_flags[i] |= (aic_inb(p, TARG_SCSIRATE + i) & 0x07);
8705             if ( (aic_inb(p, TARG_SCSIRATE + i) & 0x18) == 0x18 )
8706               sc->device_flags[i] |= CFSYNCHISULTRA;
8707           }
8708         }
8709         else
8710         {
8711           if (aic_inb(p, TARG_SCSIRATE + i) & ~WIDEXFER)
8712           {
8713             sc->device_flags[i] |= CFSYNCH;
8714             if (p->features & AHC_ULTRA)
8715               sc->device_flags[i] |= ((p->ultraenb & mask) ?
8716                                       CFSYNCHISULTRA : 0);
8717           }
8718         }
8719       }
8720       else
8721       {
8722         /*
8723          * Assume the BIOS has NOT been run on this card and nothing between
8724          * the card and the devices is configured yet.
8725          */
8726         sc->device_flags[i] = CFDISC;
8727         if (p->features & AHC_WIDE)
8728           sc->device_flags[i] |= CFWIDEB;
8729         if (p->features & AHC_ULTRA3)
8730           sc->device_flags[i] |= 2;
8731         else if (p->features & AHC_ULTRA2)
8732           sc->device_flags[i] |= 3;
8733         else if (p->features & AHC_ULTRA)
8734           sc->device_flags[i] |= CFSYNCHISULTRA;
8735         sc->device_flags[i] |= CFSYNCH;
8736         aic_outb(p, 0, TARG_SCSIRATE + i);
8737         if (p->features & AHC_ULTRA2)
8738           aic_outb(p, 0, TARG_OFFSET + i);
8739       }
8740     }
8741     if (sc->device_flags[i] & CFDISC)
8742     {
8743       p->discenable |= mask;
8744     }
8745     if (p->flags & AHC_NEWEEPROM_FMT)
8746     {
8747       if ( !(p->features & AHC_ULTRA2) )
8748       {
8749         /*
8750          * I know of two different Ultra BIOSes that do this differently.
8751          * One on the Gigabyte 6BXU mb that wants flags[i] & CFXFER to
8752          * be == to 0x03 and SYNCHISULTRA to be true to mean 40MByte/s
8753          * while on the IBM Netfinity 5000 they want the same thing
8754          * to be something else, while flags[i] & CFXFER == 0x03 and
8755          * SYNCHISULTRA false should be 40MByte/s.  So, we set both to
8756          * 40MByte/s and the lower speeds be damned.  People will have
8757          * to select around the conversely mapped lower speeds in order
8758          * to select lower speeds on these boards.
8759          */
8760         if ( (sc->device_flags[i] & CFNEWULTRAFORMAT) &&
8761             ((sc->device_flags[i] & CFXFER) == 0x03) )
8762         {
8763           sc->device_flags[i] &= ~CFXFER;
8764           sc->device_flags[i] |= CFSYNCHISULTRA;
8765         }
8766         if (sc->device_flags[i] & CFSYNCHISULTRA)
8767         {
8768           p->ultraenb |= mask;
8769         }
8770       }
8771       else if ( !(sc->device_flags[i] & CFNEWULTRAFORMAT) &&
8772                  (p->features & AHC_ULTRA2) &&
8773                  (sc->device_flags[i] & CFSYNCHISULTRA) )
8774       {
8775         p->ultraenb |= mask;
8776       }
8777     }
8778     else if (sc->adapter_control & CFULTRAEN)
8779     {
8780       p->ultraenb |= mask;
8781     }
8782     if ( (sc->device_flags[i] & CFSYNCH) == 0)
8783     {
8784       sc->device_flags[i] &= ~CFXFER;
8785       p->ultraenb &= ~mask;
8786       p->user[i].offset = 0;
8787       p->user[i].period = 0;
8788       p->user[i].options = 0;
8789     }
8790     else
8791     {
8792       if (p->features & AHC_ULTRA3)
8793       {
8794         p->user[i].offset = MAX_OFFSET_ULTRA2;
8795         if( (sc->device_flags[i] & CFXFER) < 0x03 )
8796         {
8797           scsirate = (sc->device_flags[i] & CFXFER);
8798           p->user[i].options = MSG_EXT_PPR_OPTION_DT_CRC;
8799         }
8800         else
8801         {
8802           scsirate = (sc->device_flags[i] & CFXFER) |
8803                      ((p->ultraenb & mask) ? 0x18 : 0x10);
8804           p->user[i].options = 0;
8805         }
8806         p->user[i].period = aic7xxx_find_period(p, scsirate,
8807                                        AHC_SYNCRATE_ULTRA3);
8808       }
8809       else if (p->features & AHC_ULTRA2)
8810       {
8811         p->user[i].offset = MAX_OFFSET_ULTRA2;
8812         scsirate = (sc->device_flags[i] & CFXFER) |
8813                    ((p->ultraenb & mask) ? 0x18 : 0x10);
8814         p->user[i].options = 0;
8815         p->user[i].period = aic7xxx_find_period(p, scsirate,
8816                                        AHC_SYNCRATE_ULTRA2);
8817       }
8818       else
8819       {
8820         scsirate = (sc->device_flags[i] & CFXFER) << 4;
8821         p->user[i].options = 0;
8822         p->user[i].offset = MAX_OFFSET_8BIT;
8823         if (p->features & AHC_ULTRA)
8824         {
8825           short ultraenb;
8826           ultraenb = aic_inb(p, ULTRA_ENB) |
8827             (aic_inb(p, ULTRA_ENB + 1) << 8);
8828           p->user[i].period = aic7xxx_find_period(p, scsirate,
8829                                           (p->ultraenb & mask) ?
8830                                           AHC_SYNCRATE_ULTRA :
8831                                           AHC_SYNCRATE_FAST);
8832         }
8833         else
8834           p->user[i].period = aic7xxx_find_period(p, scsirate,
8835                                           AHC_SYNCRATE_FAST);
8836       }
8837     }
8838     if ( (sc->device_flags[i] & CFWIDEB) && (p->features & AHC_WIDE) )
8839     {
8840       p->user[i].width = MSG_EXT_WDTR_BUS_16_BIT;
8841     }
8842     else
8843     {
8844       p->user[i].width = MSG_EXT_WDTR_BUS_8_BIT;
8845     }
8846   }
8847   aic_outb(p, ~(p->discenable & 0xFF), DISC_DSB);
8848   aic_outb(p, ~((p->discenable >> 8) & 0xFF), DISC_DSB + 1);
8849
8850   /*
8851    * We set the p->ultraenb from the SEEPROM to begin with, but now we make
8852    * it match what is already down in the card.  If we are doing a reset
8853    * on the card then this will get put back to a default state anyway.
8854    * This allows us to not have to pre-emptively negotiate when using the
8855    * no_reset option.
8856    */
8857   if (p->features & AHC_ULTRA)
8858     p->ultraenb = aic_inb(p, ULTRA_ENB) | (aic_inb(p, ULTRA_ENB + 1) << 8);
8859
8860   
8861   scsi_conf = (p->scsi_id & HSCSIID);
8862
8863   if(have_seeprom)
8864   {
8865     p->adapter_control = sc->adapter_control;
8866     p->bios_control = sc->bios_control;
8867
8868     switch (p->chip & AHC_CHIPID_MASK)
8869     {
8870       case AHC_AIC7895:
8871       case AHC_AIC7896:
8872       case AHC_AIC7899:
8873         if (p->adapter_control & CFBPRIMARY)
8874           p->flags |= AHC_CHANNEL_B_PRIMARY;
8875       default:
8876         break;
8877     }
8878
8879     if (sc->adapter_control & CFSPARITY)
8880       scsi_conf |= ENSPCHK;
8881   }
8882   else
8883   {
8884     scsi_conf |= ENSPCHK | RESET_SCSI;
8885   }
8886
8887   /*
8888    * Only set the SCSICONF and SCSICONF + 1 registers if we are a PCI card.
8889    * The 2842 and 2742 cards already have these registers set and we don't
8890    * want to muck with them since we don't set all the bits they do.
8891    */
8892   if ( (p->chip & ~AHC_CHIPID_MASK) == AHC_PCI )
8893   {
8894     /* Set the host ID */
8895     aic_outb(p, scsi_conf, SCSICONF);
8896     /* In case we are a wide card */
8897     aic_outb(p, p->scsi_id, SCSICONF + 1);
8898   }
8899 }
8900
8901 /*+F*************************************************************************
8902  * Function:
8903  *   aic7xxx_configure_bugs
8904  *
8905  * Description:
8906  *   Take the card passed in and set the appropriate bug flags based upon
8907  *   the card model.  Also make any changes needed to device registers or
8908  *   PCI registers while we are here.
8909  *-F*************************************************************************/
8910 static void
8911 aic7xxx_configure_bugs(struct aic7xxx_host *p)
8912 {
8913   unsigned short tmp_word;
8914  
8915   switch(p->chip & AHC_CHIPID_MASK)
8916   {
8917     case AHC_AIC7860:
8918       p->bugs |= AHC_BUG_PCI_2_1_RETRY;
8919       /* fall through */
8920     case AHC_AIC7850:
8921     case AHC_AIC7870:
8922       p->bugs |= AHC_BUG_TMODE_WIDEODD | AHC_BUG_CACHETHEN | AHC_BUG_PCI_MWI;
8923       break;
8924     case AHC_AIC7880:
8925       p->bugs |= AHC_BUG_TMODE_WIDEODD | AHC_BUG_PCI_2_1_RETRY |
8926                  AHC_BUG_CACHETHEN | AHC_BUG_PCI_MWI;
8927       break;
8928     case AHC_AIC7890:
8929       p->bugs |= AHC_BUG_AUTOFLUSH | AHC_BUG_CACHETHEN;
8930       break;
8931     case AHC_AIC7892:
8932       p->bugs |= AHC_BUG_SCBCHAN_UPLOAD;
8933       break;
8934     case AHC_AIC7895:
8935       p->bugs |= AHC_BUG_TMODE_WIDEODD | AHC_BUG_PCI_2_1_RETRY |
8936                  AHC_BUG_CACHETHEN | AHC_BUG_PCI_MWI;
8937       break;
8938     case AHC_AIC7896:
8939       p->bugs |= AHC_BUG_CACHETHEN_DIS;
8940       break;
8941     case AHC_AIC7899:
8942       p->bugs |= AHC_BUG_SCBCHAN_UPLOAD;
8943       break;
8944     default:
8945       /* Nothing to do */
8946       break;
8947   }
8948
8949   /*
8950    * Now handle the bugs that require PCI register or card register tweaks
8951    */
8952   pci_read_config_word(p->pdev, PCI_COMMAND, &tmp_word);
8953   if(p->bugs & AHC_BUG_PCI_MWI)
8954   {
8955     tmp_word &= ~PCI_COMMAND_INVALIDATE;
8956   }
8957   else
8958   {
8959     tmp_word |= PCI_COMMAND_INVALIDATE;
8960   }
8961   pci_write_config_word(p->pdev, PCI_COMMAND, tmp_word);
8962
8963   if(p->bugs & AHC_BUG_CACHETHEN)
8964   {
8965     aic_outb(p, aic_inb(p, DSCOMMAND0) & ~CACHETHEN, DSCOMMAND0);
8966   }
8967   else if (p->bugs & AHC_BUG_CACHETHEN_DIS)
8968   {
8969     aic_outb(p, aic_inb(p, DSCOMMAND0) | CACHETHEN, DSCOMMAND0);
8970   }
8971
8972   return;
8973 }
8974
8975
8976 /*+F*************************************************************************
8977  * Function:
8978  *   aic7xxx_detect
8979  *
8980  * Description:
8981  *   Try to detect and register an Adaptec 7770 or 7870 SCSI controller.
8982  *
8983  * XXX - This should really be called aic7xxx_probe().  A sequence of
8984  *       probe(), attach()/detach(), and init() makes more sense than
8985  *       one do-it-all function.  This may be useful when (and if) the
8986  *       mid-level SCSI code is overhauled.
8987  *-F*************************************************************************/
8988 static int
8989 aic7xxx_detect(struct scsi_host_template *template)
8990 {
8991   struct aic7xxx_host *temp_p = NULL;
8992   struct aic7xxx_host *current_p = NULL;
8993   struct aic7xxx_host *list_p = NULL;
8994   int found = 0;
8995 #if defined(__i386__) || defined(__alpha__)
8996   ahc_flag_type flags = 0;
8997   int type;
8998 #endif
8999   unsigned char sxfrctl1;
9000 #if defined(__i386__) || defined(__alpha__)
9001   unsigned char hcntrl, hostconf;
9002   unsigned int slot, base;
9003 #endif
9004
9005 #ifdef MODULE
9006   /*
9007    * If we are called as a module, the aic7xxx pointer may not be null
9008    * and it would point to our bootup string, just like on the lilo
9009    * command line.  IF not NULL, then process this config string with
9010    * aic7xxx_setup
9011    */
9012   if(aic7xxx)
9013     aic7xxx_setup(aic7xxx);
9014 #endif
9015
9016   template->proc_name = "aic7xxx";
9017   template->sg_tablesize = AIC7XXX_MAX_SG;
9018
9019
9020 #ifdef CONFIG_PCI
9021   /*
9022    * PCI-bus probe.
9023    */
9024   {
9025     static struct
9026     {
9027       unsigned short      vendor_id;
9028       unsigned short      device_id;
9029       ahc_chip            chip;
9030       ahc_flag_type       flags;
9031       ahc_feature         features;
9032       int                 board_name_index;
9033       unsigned short      seeprom_size;
9034       unsigned short      seeprom_type;
9035     } const aic_pdevs[] = {
9036       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7810, AHC_NONE,
9037        AHC_FNONE, AHC_FENONE,                                1,
9038        32, C46 },
9039       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7850, AHC_AIC7850,
9040        AHC_PAGESCBS, AHC_AIC7850_FE,                         5,
9041        32, C46 },
9042       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7855, AHC_AIC7850,
9043        AHC_PAGESCBS, AHC_AIC7850_FE,                         6,
9044        32, C46 },
9045       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7821, AHC_AIC7860,
9046        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9047        AHC_AIC7860_FE,                                       7,
9048        32, C46 },
9049       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_3860, AHC_AIC7860,
9050        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9051        AHC_AIC7860_FE,                                       7,
9052        32, C46 },
9053       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_38602, AHC_AIC7860,
9054        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9055        AHC_AIC7860_FE,                                       7,
9056        32, C46 },
9057       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_38602, AHC_AIC7860,
9058        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9059        AHC_AIC7860_FE,                                       7,
9060        32, C46 },
9061       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7860, AHC_AIC7860,
9062        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MOTHERBOARD,
9063        AHC_AIC7860_FE,                                       7,
9064        32, C46 },
9065       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7861, AHC_AIC7860,
9066        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9067        AHC_AIC7860_FE,                                       8,
9068        32, C46 },
9069       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7870, AHC_AIC7870,
9070        AHC_PAGESCBS | AHC_BIOS_ENABLED | AHC_MOTHERBOARD,
9071        AHC_AIC7870_FE,                                       9,
9072        32, C46 },
9073       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7871, AHC_AIC7870,
9074        AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7870_FE,     10,
9075        32, C46 },
9076       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7872, AHC_AIC7870,
9077        AHC_PAGESCBS | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9078        AHC_AIC7870_FE,                                      11,
9079        32, C56_66 },
9080       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7873, AHC_AIC7870,
9081        AHC_PAGESCBS | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9082        AHC_AIC7870_FE,                                      12,
9083        32, C56_66 },
9084       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7874, AHC_AIC7870,
9085        AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7870_FE,     13,
9086        32, C46 },
9087       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7880, AHC_AIC7880,
9088        AHC_PAGESCBS | AHC_BIOS_ENABLED | AHC_MOTHERBOARD,
9089        AHC_AIC7880_FE,                                      14,
9090        32, C46 },
9091       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7881, AHC_AIC7880,
9092        AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7880_FE,     15,
9093        32, C46 },
9094       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7882, AHC_AIC7880,
9095        AHC_PAGESCBS | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9096        AHC_AIC7880_FE,                                      16,
9097        32, C56_66 },
9098       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7883, AHC_AIC7880,
9099        AHC_PAGESCBS | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9100        AHC_AIC7880_FE,                                      17,
9101        32, C56_66 },
9102       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7884, AHC_AIC7880,
9103        AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7880_FE,     18,
9104        32, C46 },
9105       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7885, AHC_AIC7880,
9106        AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7880_FE,     18,
9107        32, C46 },
9108       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7886, AHC_AIC7880,
9109        AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7880_FE,     18,
9110        32, C46 },
9111       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7887, AHC_AIC7880,
9112        AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7880_FE | AHC_NEW_AUTOTERM, 19,
9113        32, C46 },
9114       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7888, AHC_AIC7880,
9115        AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7880_FE,     18,
9116        32, C46 },
9117       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7895, AHC_AIC7895,
9118        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9119        AHC_AIC7895_FE,                                      20,
9120        32, C56_66 },
9121       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7890, AHC_AIC7890,
9122        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9123        AHC_AIC7890_FE,                                      21,
9124        32, C46 },
9125       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7890B, AHC_AIC7890,
9126        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9127        AHC_AIC7890_FE,                                      21,
9128        32, C46 },
9129       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_2930U2, AHC_AIC7890,
9130        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9131        AHC_AIC7890_FE,                                      22,
9132        32, C46 },
9133       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_2940U2, AHC_AIC7890,
9134        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9135        AHC_AIC7890_FE,                                      23,
9136        32, C46 },
9137       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7896, AHC_AIC7896,
9138        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9139        AHC_AIC7896_FE,                                      24,
9140        32, C56_66 },
9141       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_3940U2, AHC_AIC7896,
9142        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9143        AHC_AIC7896_FE,                                      25,
9144        32, C56_66 },
9145       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_3950U2D, AHC_AIC7896,
9146        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9147        AHC_AIC7896_FE,                                      26,
9148        32, C56_66 },
9149       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_1480A, AHC_AIC7860,
9150        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_NO_STPWEN,
9151        AHC_AIC7860_FE,                                      27,
9152        32, C46 },
9153       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7892A, AHC_AIC7892,
9154        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9155        AHC_AIC7892_FE,                                      28,
9156        32, C46 },
9157       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7892B, AHC_AIC7892,
9158        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9159        AHC_AIC7892_FE,                                      28,
9160        32, C46 },
9161       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7892D, AHC_AIC7892,
9162        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9163        AHC_AIC7892_FE,                                      28,
9164        32, C46 },
9165       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7892P, AHC_AIC7892,
9166        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9167        AHC_AIC7892_FE,                                      28,
9168        32, C46 },
9169       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7899A, AHC_AIC7899,
9170        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9171        AHC_AIC7899_FE,                                      29,
9172        32, C56_66 },
9173       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7899B, AHC_AIC7899,
9174        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9175        AHC_AIC7899_FE,                                      29,
9176        32, C56_66 },
9177       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7899D, AHC_AIC7899,
9178        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9179        AHC_AIC7899_FE,                                      29,
9180        32, C56_66 },
9181       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7899P, AHC_AIC7899,
9182        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9183        AHC_AIC7899_FE,                                      29,
9184        32, C56_66 },
9185     };
9186
9187     unsigned short command;
9188     unsigned int  devconfig, i, oldverbose;
9189     struct pci_dev *pdev = NULL;
9190
9191     for (i = 0; i < ARRAY_SIZE(aic_pdevs); i++)
9192     {
9193       pdev = NULL;
9194       while ((pdev = pci_get_device(aic_pdevs[i].vendor_id,
9195                                      aic_pdevs[i].device_id,
9196                                      pdev))) {
9197         if (pci_enable_device(pdev))
9198                 continue;
9199         if ( i == 0 ) /* We found one, but it's the 7810 RAID cont. */
9200         {
9201           if (aic7xxx_verbose & (VERBOSE_PROBE|VERBOSE_PROBE2))
9202           {
9203             printk(KERN_INFO "aic7xxx: The 7810 RAID controller is not "
9204               "supported by\n");
9205             printk(KERN_INFO "         this driver, we are ignoring it.\n");
9206           }
9207         }
9208         else if ( (temp_p = kmalloc(sizeof(struct aic7xxx_host),
9209                                     GFP_ATOMIC)) != NULL )
9210         {
9211           memset(temp_p, 0, sizeof(struct aic7xxx_host));
9212           temp_p->chip = aic_pdevs[i].chip | AHC_PCI;
9213           temp_p->flags = aic_pdevs[i].flags;
9214           temp_p->features = aic_pdevs[i].features;
9215           temp_p->board_name_index = aic_pdevs[i].board_name_index;
9216           temp_p->sc_size = aic_pdevs[i].seeprom_size;
9217           temp_p->sc_type = aic_pdevs[i].seeprom_type;
9218
9219           /*
9220            * Read sundry information from PCI BIOS.
9221            */
9222           temp_p->irq = pdev->irq;
9223           temp_p->pdev = pdev;
9224           temp_p->pci_bus = pdev->bus->number;
9225           temp_p->pci_device_fn = pdev->devfn;
9226           temp_p->base = pci_resource_start(pdev, 0);
9227           temp_p->mbase = pci_resource_start(pdev, 1);
9228           current_p = list_p;
9229           while(current_p && temp_p)
9230           {
9231             if ( ((current_p->pci_bus == temp_p->pci_bus) &&
9232                   (current_p->pci_device_fn == temp_p->pci_device_fn)) ||
9233                  (temp_p->base && (current_p->base == temp_p->base)) ||
9234                  (temp_p->mbase && (current_p->mbase == temp_p->mbase)) )
9235             {
9236               /* duplicate PCI entry, skip it */
9237               kfree(temp_p);
9238               temp_p = NULL;
9239               continue;
9240             }
9241             current_p = current_p->next;
9242           }
9243           if(pci_request_regions(temp_p->pdev, "aic7xxx"))
9244           {
9245             printk("aic7xxx: <%s> at PCI %d/%d/%d\n", 
9246               board_names[aic_pdevs[i].board_name_index],
9247               temp_p->pci_bus,
9248               PCI_SLOT(temp_p->pci_device_fn),
9249               PCI_FUNC(temp_p->pci_device_fn));
9250             printk("aic7xxx: I/O ports already in use, ignoring.\n");
9251             kfree(temp_p);
9252             continue;
9253           }
9254
9255           if (aic7xxx_verbose & VERBOSE_PROBE2)
9256             printk("aic7xxx: <%s> at PCI %d/%d\n", 
9257               board_names[aic_pdevs[i].board_name_index],
9258               PCI_SLOT(pdev->devfn),
9259               PCI_FUNC(pdev->devfn));
9260           pci_read_config_word(pdev, PCI_COMMAND, &command);
9261           if (aic7xxx_verbose & VERBOSE_PROBE2)
9262           {
9263             printk("aic7xxx: Initial PCI_COMMAND value was 0x%x\n",
9264               (int)command);
9265           }
9266 #ifdef AIC7XXX_STRICT_PCI_SETUP
9267           command |= PCI_COMMAND_SERR | PCI_COMMAND_PARITY |
9268             PCI_COMMAND_MASTER | PCI_COMMAND_MEMORY | PCI_COMMAND_IO;
9269 #else
9270           command |= PCI_COMMAND_MASTER | PCI_COMMAND_MEMORY | PCI_COMMAND_IO;
9271 #endif
9272           command &= ~PCI_COMMAND_INVALIDATE;
9273           if (aic7xxx_pci_parity == 0)
9274             command &= ~(PCI_COMMAND_SERR | PCI_COMMAND_PARITY);
9275           pci_write_config_word(pdev, PCI_COMMAND, command);
9276 #ifdef AIC7XXX_STRICT_PCI_SETUP
9277           pci_read_config_dword(pdev, DEVCONFIG, &devconfig);
9278           if (aic7xxx_verbose & VERBOSE_PROBE2)
9279           {
9280             printk("aic7xxx: Initial DEVCONFIG value was 0x%x\n", devconfig);
9281           }
9282           devconfig |= 0x80000040;
9283           pci_write_config_dword(pdev, DEVCONFIG, devconfig);
9284 #endif /* AIC7XXX_STRICT_PCI_SETUP */
9285
9286           temp_p->unpause = INTEN;
9287           temp_p->pause = temp_p->unpause | PAUSE;
9288           if ( ((temp_p->base == 0) &&
9289                 (temp_p->mbase == 0)) ||
9290                (temp_p->irq == 0) )
9291           {
9292             printk("aic7xxx: <%s> at PCI %d/%d/%d\n", 
9293               board_names[aic_pdevs[i].board_name_index],
9294               temp_p->pci_bus,
9295               PCI_SLOT(temp_p->pci_device_fn),
9296               PCI_FUNC(temp_p->pci_device_fn));
9297             printk("aic7xxx: Controller disabled by BIOS, ignoring.\n");
9298             goto skip_pci_controller;
9299           }
9300
9301 #ifdef MMAPIO
9302           if ( !(temp_p->base) || !(temp_p->flags & AHC_MULTI_CHANNEL) ||
9303                ((temp_p->chip != (AHC_AIC7870 | AHC_PCI)) &&
9304                 (temp_p->chip != (AHC_AIC7880 | AHC_PCI))) )
9305           {
9306             temp_p->maddr = ioremap_nocache(temp_p->mbase, 256);
9307             if(temp_p->maddr)
9308             {
9309               /*
9310                * We need to check the I/O with the MMAPed address.  Some machines
9311                * simply fail to work with MMAPed I/O and certain controllers.
9312                */
9313               if(aic_inb(temp_p, HCNTRL) == 0xff)
9314               {
9315                 /*
9316                  * OK.....we failed our test....go back to programmed I/O
9317                  */
9318                 printk(KERN_INFO "aic7xxx: <%s> at PCI %d/%d/%d\n", 
9319                   board_names[aic_pdevs[i].board_name_index],
9320                   temp_p->pci_bus,
9321                   PCI_SLOT(temp_p->pci_device_fn),
9322                   PCI_FUNC(temp_p->pci_device_fn));
9323                 printk(KERN_INFO "aic7xxx: MMAPed I/O failed, reverting to "
9324                                  "Programmed I/O.\n");
9325                 iounmap(temp_p->maddr);
9326                 temp_p->maddr = NULL;
9327                 if(temp_p->base == 0)
9328                 {
9329                   printk("aic7xxx: <%s> at PCI %d/%d/%d\n", 
9330                     board_names[aic_pdevs[i].board_name_index],
9331                     temp_p->pci_bus,
9332                     PCI_SLOT(temp_p->pci_device_fn),
9333                     PCI_FUNC(temp_p->pci_device_fn));
9334                   printk("aic7xxx: Controller disabled by BIOS, ignoring.\n");
9335                   goto skip_pci_controller;
9336                 }
9337               }
9338             }
9339           }
9340 #endif
9341
9342           /*
9343            * We HAVE to make sure the first pause_sequencer() and all other
9344            * subsequent I/O that isn't PCI config space I/O takes place
9345            * after the MMAPed I/O region is configured and tested.  The
9346            * problem is the PowerPC architecture that doesn't support
9347            * programmed I/O at all, so we have to have the MMAP I/O set up
9348            * for this pause to even work on those machines.
9349            */
9350           pause_sequencer(temp_p);
9351
9352           /*
9353            * Clear out any pending PCI error status messages.  Also set
9354            * verbose to 0 so that we don't emit strange PCI error messages
9355            * while cleaning out the current status bits.
9356            */
9357           oldverbose = aic7xxx_verbose;
9358           aic7xxx_verbose = 0;
9359           aic7xxx_pci_intr(temp_p);
9360           aic7xxx_verbose = oldverbose;
9361
9362           temp_p->bios_address = 0;
9363
9364           /*
9365            * Remember how the card was setup in case there is no seeprom.
9366            */
9367           if (temp_p->features & AHC_ULTRA2)
9368             temp_p->scsi_id = aic_inb(temp_p, SCSIID_ULTRA2) & OID;
9369           else
9370             temp_p->scsi_id = aic_inb(temp_p, SCSIID) & OID;
9371           /*
9372            * Get current termination setting
9373            */
9374           sxfrctl1 = aic_inb(temp_p, SXFRCTL1);
9375
9376           if (aic7xxx_chip_reset(temp_p) == -1)
9377           {
9378             goto skip_pci_controller;
9379           }
9380           /*
9381            * Very quickly put the term setting back into the register since
9382            * the chip reset may cause odd things to happen.  This is to keep
9383            * LVD busses with lots of drives from draining the power out of
9384            * the diffsense line before we get around to running the
9385            * configure_termination() function.  Also restore the STPWLEVEL
9386            * bit of DEVCONFIG
9387            */
9388           aic_outb(temp_p, sxfrctl1, SXFRCTL1);
9389           pci_write_config_dword(temp_p->pdev, DEVCONFIG, devconfig);
9390           sxfrctl1 &= STPWEN;
9391
9392           /*
9393            * We need to set the CHNL? assignments before loading the SEEPROM
9394            * The 3940 and 3985 cards (original stuff, not any of the later
9395            * stuff) are 7870 and 7880 class chips.  The Ultra2 stuff falls
9396            * under 7896 and 7897.  The 7895 is in a class by itself :)
9397            */
9398           switch (temp_p->chip & AHC_CHIPID_MASK)
9399           {
9400             case AHC_AIC7870: /* 3840 / 3985 */
9401             case AHC_AIC7880: /* 3840 UW / 3985 UW */
9402               if(temp_p->flags & AHC_MULTI_CHANNEL)
9403               {
9404                 switch(PCI_SLOT(temp_p->pci_device_fn))
9405                 {
9406                   case 5:
9407                     temp_p->flags |= AHC_CHNLB;
9408                     break;
9409                   case 8:
9410                     temp_p->flags |= AHC_CHNLB;
9411                     break;
9412                   case 12:
9413                     temp_p->flags |= AHC_CHNLC;
9414                     break;
9415                   default:
9416                     break;
9417                 }
9418               }
9419               break;
9420
9421             case AHC_AIC7895: /* 7895 */
9422             case AHC_AIC7896: /* 7896/7 */
9423             case AHC_AIC7899: /* 7899 */
9424               if (PCI_FUNC(pdev->devfn) != 0)
9425               {
9426                 temp_p->flags |= AHC_CHNLB;
9427               }
9428               /*
9429                * The 7895 is the only chipset that sets the SCBSIZE32 param
9430                * in the DEVCONFIG register.  The Ultra2 chipsets use
9431                * the DSCOMMAND0 register instead.
9432                */
9433               if ((temp_p->chip & AHC_CHIPID_MASK) == AHC_AIC7895)
9434               {
9435                 pci_read_config_dword(pdev, DEVCONFIG, &devconfig);
9436                 devconfig |= SCBSIZE32;
9437                 pci_write_config_dword(pdev, DEVCONFIG, devconfig);
9438               }
9439               break;
9440             default:
9441               break;
9442           }
9443
9444           /*
9445            * Loading of the SEEPROM needs to come after we've set the flags
9446            * to indicate possible CHNLB and CHNLC assigments.  Otherwise,
9447            * on 394x and 398x cards we'll end up reading the wrong settings
9448            * for channels B and C
9449            */
9450           switch (temp_p->chip & AHC_CHIPID_MASK)
9451           {
9452             case AHC_AIC7892:
9453             case AHC_AIC7899:
9454               aic_outb(temp_p, 0, SCAMCTL);
9455               /*
9456                * Switch to the alt mode of the chip...
9457                */
9458               aic_outb(temp_p, aic_inb(temp_p, SFUNCT) | ALT_MODE, SFUNCT);
9459               /*
9460                * Set our options...the last two items set our CRC after x byte
9461                * count in target mode...
9462                */
9463               aic_outb(temp_p, AUTO_MSGOUT_DE | DIS_MSGIN_DUALEDGE, OPTIONMODE);
9464               aic_outb(temp_p, 0x00, 0x0b);
9465               aic_outb(temp_p, 0x10, 0x0a);
9466               /*
9467                * switch back to normal mode...
9468                */
9469               aic_outb(temp_p, aic_inb(temp_p, SFUNCT) & ~ALT_MODE, SFUNCT);
9470               aic_outb(temp_p, CRCVALCHKEN | CRCENDCHKEN | CRCREQCHKEN |
9471                                TARGCRCENDEN | TARGCRCCNTEN,
9472                        CRCCONTROL1);
9473               aic_outb(temp_p, ((aic_inb(temp_p, DSCOMMAND0) | USCBSIZE32 |
9474                                  MPARCKEN | CIOPARCKEN | CACHETHEN) & 
9475                                ~DPARCKEN), DSCOMMAND0);
9476               aic7xxx_load_seeprom(temp_p, &sxfrctl1);
9477               break;
9478             case AHC_AIC7890:
9479             case AHC_AIC7896:
9480               aic_outb(temp_p, 0, SCAMCTL);
9481               aic_outb(temp_p, (aic_inb(temp_p, DSCOMMAND0) |
9482                                 CACHETHEN | MPARCKEN | USCBSIZE32 |
9483                                 CIOPARCKEN) & ~DPARCKEN, DSCOMMAND0);
9484               aic7xxx_load_seeprom(temp_p, &sxfrctl1);
9485               break;
9486             case AHC_AIC7850:
9487             case AHC_AIC7860:
9488               /*
9489                * Set the DSCOMMAND0 register on these cards different from
9490                * on the 789x cards.  Also, read the SEEPROM as well.
9491                */
9492               aic_outb(temp_p, (aic_inb(temp_p, DSCOMMAND0) |
9493                                 CACHETHEN | MPARCKEN) & ~DPARCKEN,
9494                        DSCOMMAND0);
9495               /* FALLTHROUGH */
9496             default:
9497               aic7xxx_load_seeprom(temp_p, &sxfrctl1);
9498               break;
9499             case AHC_AIC7880:
9500               /*
9501                * Check the rev of the chipset before we change DSCOMMAND0
9502                */
9503               pci_read_config_dword(pdev, DEVCONFIG, &devconfig);
9504               if ((devconfig & 0xff) >= 1)
9505               {
9506                 aic_outb(temp_p, (aic_inb(temp_p, DSCOMMAND0) |
9507                                   CACHETHEN | MPARCKEN) & ~DPARCKEN,
9508                          DSCOMMAND0);
9509               }
9510               aic7xxx_load_seeprom(temp_p, &sxfrctl1);
9511               break;
9512           }
9513           
9514
9515           /*
9516            * and then we need another switch based on the type in order to
9517            * make sure the channel B primary flag is set properly on 7895
9518            * controllers....Arrrgggghhh!!!  We also have to catch the fact
9519            * that when you disable the BIOS on the 7895 on the Intel DK440LX
9520            * motherboard, and possibly others, it only sets the BIOS disabled
9521            * bit on the A channel...I think I'm starting to lean towards
9522            * going postal....
9523            */
9524           switch(temp_p->chip & AHC_CHIPID_MASK)
9525           {
9526             case AHC_AIC7895:
9527             case AHC_AIC7896:
9528             case AHC_AIC7899:
9529               current_p = list_p;
9530               while(current_p != NULL)
9531               {
9532                 if ( (current_p->pci_bus == temp_p->pci_bus) &&
9533                      (PCI_SLOT(current_p->pci_device_fn) ==
9534                       PCI_SLOT(temp_p->pci_device_fn)) )
9535                 {
9536                   if ( PCI_FUNC(current_p->pci_device_fn) == 0 )
9537                   {
9538                     temp_p->flags |= 
9539                       (current_p->flags & AHC_CHANNEL_B_PRIMARY);
9540                     temp_p->flags &= ~(AHC_BIOS_ENABLED|AHC_USEDEFAULTS);
9541                     temp_p->flags |=
9542                       (current_p->flags & (AHC_BIOS_ENABLED|AHC_USEDEFAULTS));
9543                   }
9544                   else
9545                   {
9546                     current_p->flags |=
9547                       (temp_p->flags & AHC_CHANNEL_B_PRIMARY);
9548                     current_p->flags &= ~(AHC_BIOS_ENABLED|AHC_USEDEFAULTS);
9549                     current_p->flags |=
9550                       (temp_p->flags & (AHC_BIOS_ENABLED|AHC_USEDEFAULTS));
9551                   }
9552                 }
9553                 current_p = current_p->next;
9554               }
9555               break;
9556             default:
9557               break;
9558           }
9559
9560           /*
9561            * We only support external SCB RAM on the 7895/6/7 chipsets.
9562            * We could support it on the 7890/1 easy enough, but I don't
9563            * know of any 7890/1 based cards that have it.  I do know
9564            * of 7895/6/7 cards that have it and they work properly.
9565            */
9566           switch(temp_p->chip & AHC_CHIPID_MASK)
9567           {
9568             default:
9569               break;
9570             case AHC_AIC7895:
9571             case AHC_AIC7896:
9572             case AHC_AIC7899:
9573               pci_read_config_dword(pdev, DEVCONFIG, &devconfig);
9574               if (temp_p->features & AHC_ULTRA2)
9575               {
9576                 if ( (aic_inb(temp_p, DSCOMMAND0) & RAMPSM_ULTRA2) &&
9577                      (aic7xxx_scbram) )
9578                 {
9579                   aic_outb(temp_p,
9580                            aic_inb(temp_p, DSCOMMAND0) & ~SCBRAMSEL_ULTRA2,
9581                            DSCOMMAND0);
9582                   temp_p->flags |= AHC_EXTERNAL_SRAM;
9583                   devconfig |= EXTSCBPEN;
9584                 }
9585                 else if (aic_inb(temp_p, DSCOMMAND0) & RAMPSM_ULTRA2)
9586                 {
9587                   printk(KERN_INFO "aic7xxx: <%s> at PCI %d/%d/%d\n", 
9588                     board_names[aic_pdevs[i].board_name_index],
9589                     temp_p->pci_bus,
9590                     PCI_SLOT(temp_p->pci_device_fn),
9591                     PCI_FUNC(temp_p->pci_device_fn));
9592                   printk("aic7xxx: external SCB RAM detected, "
9593                          "but not enabled\n");
9594                 }
9595               }
9596               else
9597               {
9598                 if ((devconfig & RAMPSM) && (aic7xxx_scbram))
9599                 {
9600                   devconfig &= ~SCBRAMSEL;
9601                   devconfig |= EXTSCBPEN;
9602                   temp_p->flags |= AHC_EXTERNAL_SRAM;
9603                 }
9604                 else if (devconfig & RAMPSM)
9605                 {
9606                   printk(KERN_INFO "aic7xxx: <%s> at PCI %d/%d/%d\n", 
9607                     board_names[aic_pdevs[i].board_name_index],
9608                     temp_p->pci_bus,
9609                     PCI_SLOT(temp_p->pci_device_fn),
9610                     PCI_FUNC(temp_p->pci_device_fn));
9611                   printk("aic7xxx: external SCB RAM detected, "
9612                          "but not enabled\n");
9613                 }
9614               }
9615               pci_write_config_dword(pdev, DEVCONFIG, devconfig);
9616               if ( (temp_p->flags & AHC_EXTERNAL_SRAM) &&
9617                    (temp_p->flags & AHC_CHNLB) )
9618                 aic_outb(temp_p, 1, CCSCBBADDR);
9619               break;
9620           }
9621
9622           /*
9623            * Take the LED out of diagnostic mode
9624            */
9625           aic_outb(temp_p, 
9626             (aic_inb(temp_p, SBLKCTL) & ~(DIAGLEDEN | DIAGLEDON)),
9627             SBLKCTL);
9628
9629           /*
9630            * We don't know where this is set in the SEEPROM or by the
9631            * BIOS, so we default to 100%.  On Ultra2 controllers, use 75%
9632            * instead.
9633            */
9634           if (temp_p->features & AHC_ULTRA2)
9635           {
9636             aic_outb(temp_p, RD_DFTHRSH_MAX | WR_DFTHRSH_MAX, DFF_THRSH);
9637           }
9638           else
9639           {
9640             aic_outb(temp_p, DFTHRSH_100, DSPCISTATUS);
9641           }
9642
9643           /*
9644            * Call our function to fixup any bugs that exist on this chipset.
9645            * This may muck with PCI settings and other device settings, so
9646            * make sure it's after all the other PCI and device register
9647            * tweaks so it can back out bad settings on specific broken cards.
9648            */
9649           aic7xxx_configure_bugs(temp_p);
9650
9651           /* Hold a pci device reference */
9652           pci_dev_get(temp_p->pdev);
9653
9654           if ( list_p == NULL )
9655           {
9656             list_p = current_p = temp_p;
9657           }
9658           else
9659           {
9660             current_p = list_p;
9661             while(current_p->next != NULL)
9662               current_p = current_p->next;
9663             current_p->next = temp_p;
9664           }
9665           temp_p->next = NULL;
9666           found++;
9667           continue;
9668 skip_pci_controller:
9669 #ifdef CONFIG_PCI
9670           pci_release_regions(temp_p->pdev);
9671 #endif
9672           kfree(temp_p);
9673         }  /* Found an Adaptec PCI device. */
9674         else /* Well, we found one, but we couldn't get any memory */
9675         {
9676           printk("aic7xxx: Found <%s>\n", 
9677             board_names[aic_pdevs[i].board_name_index]);
9678           printk(KERN_INFO "aic7xxx: Unable to allocate device memory, "
9679             "skipping.\n");
9680         }
9681       } /* while(pdev=....) */
9682     } /* for PCI_DEVICES */
9683   }
9684 #endif /* CONFIG_PCI */
9685
9686 #if defined(__i386__) || defined(__alpha__)
9687   /*
9688    * EISA/VL-bus card signature probe.
9689    */
9690   slot = MINSLOT;
9691   while ( (slot <= MAXSLOT) &&
9692          !(aic7xxx_no_probe) )
9693   {
9694     base = SLOTBASE(slot) + MINREG;
9695
9696     if (!request_region(base, MAXREG - MINREG, "aic7xxx"))
9697     {
9698       /*
9699        * Some other driver has staked a
9700        * claim to this i/o region already.
9701        */
9702       slot++;
9703       continue; /* back to the beginning of the for loop */
9704     }
9705     flags = 0;
9706     type = aic7xxx_probe(slot, base + AHC_HID0, &flags);
9707     if (type == -1)
9708     {
9709       release_region(base, MAXREG - MINREG);
9710       slot++;
9711       continue;
9712     }
9713     temp_p = kmalloc(sizeof(struct aic7xxx_host), GFP_ATOMIC);
9714     if (temp_p == NULL)
9715     {
9716       printk(KERN_WARNING "aic7xxx: Unable to allocate device space.\n");
9717       release_region(base, MAXREG - MINREG);
9718       slot++;
9719       continue; /* back to the beginning of the while loop */
9720     }
9721
9722     /*
9723      * Pause the card preserving the IRQ type.  Allow the operator
9724      * to override the IRQ trigger.
9725      */
9726     if (aic7xxx_irq_trigger == 1)
9727       hcntrl = IRQMS;  /* Level */
9728     else if (aic7xxx_irq_trigger == 0)
9729       hcntrl = 0;  /* Edge */
9730     else
9731       hcntrl = inb(base + HCNTRL) & IRQMS;  /* Default */
9732     memset(temp_p, 0, sizeof(struct aic7xxx_host));
9733     temp_p->unpause = hcntrl | INTEN;
9734     temp_p->pause = hcntrl | PAUSE | INTEN;
9735     temp_p->base = base;
9736     temp_p->mbase = 0;
9737     temp_p->maddr = NULL;
9738     temp_p->pci_bus = 0;
9739     temp_p->pci_device_fn = slot;
9740     aic_outb(temp_p, hcntrl | PAUSE, HCNTRL);
9741     while( (aic_inb(temp_p, HCNTRL) & PAUSE) == 0 ) ;
9742     if (aic7xxx_chip_reset(temp_p) == -1)
9743       temp_p->irq = 0;
9744     else
9745       temp_p->irq = aic_inb(temp_p, INTDEF) & 0x0F;
9746     temp_p->flags |= AHC_PAGESCBS;
9747
9748     switch (temp_p->irq)
9749     {
9750       case 9:
9751       case 10:
9752       case 11:
9753       case 12:
9754       case 14:
9755       case 15:
9756         break;
9757
9758       default:
9759         printk(KERN_WARNING "aic7xxx: Host adapter uses unsupported IRQ "
9760           "level %d, ignoring.\n", temp_p->irq);
9761         kfree(temp_p);
9762         release_region(base, MAXREG - MINREG);
9763         slot++;
9764         continue; /* back to the beginning of the while loop */
9765     }
9766
9767     /*
9768      * We are commited now, everything has been checked and this card
9769      * has been found, now we just set it up
9770      */
9771
9772     /*
9773      * Insert our new struct into the list at the end
9774      */
9775     if (list_p == NULL)
9776     {
9777       list_p = current_p = temp_p;
9778     }
9779     else
9780     {
9781       current_p = list_p;
9782       while (current_p->next != NULL)
9783         current_p = current_p->next;
9784       current_p->next = temp_p;
9785     }
9786
9787     switch (type)
9788     {
9789       case 0:
9790         temp_p->board_name_index = 2;
9791         if (aic7xxx_verbose & VERBOSE_PROBE2)
9792           printk("aic7xxx: <%s> at EISA %d\n",
9793                board_names[2], slot);
9794         /* FALLTHROUGH */
9795       case 1:
9796       {
9797         temp_p->chip = AHC_AIC7770 | AHC_EISA;
9798         temp_p->features |= AHC_AIC7770_FE;
9799         temp_p->bios_control = aic_inb(temp_p, HA_274_BIOSCTRL);
9800
9801         /*
9802          * Get the primary channel information.  Right now we don't
9803          * do anything with this, but someday we will be able to inform
9804          * the mid-level SCSI code which channel is primary.
9805          */
9806         if (temp_p->board_name_index == 0)
9807         {
9808           temp_p->board_name_index = 3;
9809           if (aic7xxx_verbose & VERBOSE_PROBE2)
9810             printk("aic7xxx: <%s> at EISA %d\n",
9811                  board_names[3], slot);
9812         }
9813         if (temp_p->bios_control & CHANNEL_B_PRIMARY)
9814         {
9815           temp_p->flags |= AHC_CHANNEL_B_PRIMARY;
9816         }
9817
9818         if ((temp_p->bios_control & BIOSMODE) == BIOSDISABLED)
9819         {
9820           temp_p->flags &= ~AHC_BIOS_ENABLED;
9821         }
9822         else
9823         {
9824           temp_p->flags &= ~AHC_USEDEFAULTS;
9825           temp_p->flags |= AHC_BIOS_ENABLED;
9826           if ( (temp_p->bios_control & 0x20) == 0 )
9827           {
9828             temp_p->bios_address = 0xcc000;
9829             temp_p->bios_address += (0x4000 * (temp_p->bios_control & 0x07));
9830           }
9831           else
9832           {
9833             temp_p->bios_address = 0xd0000;
9834             temp_p->bios_address += (0x8000 * (temp_p->bios_control & 0x06));
9835           }
9836         }
9837         temp_p->adapter_control = aic_inb(temp_p, SCSICONF) << 8;
9838         temp_p->adapter_control |= aic_inb(temp_p, SCSICONF + 1);
9839         if (temp_p->features & AHC_WIDE)
9840         {
9841           temp_p->scsi_id = temp_p->adapter_control & HWSCSIID;
9842           temp_p->scsi_id_b = temp_p->scsi_id;
9843         }
9844         else
9845         {
9846           temp_p->scsi_id = (temp_p->adapter_control >> 8) & HSCSIID;
9847           temp_p->scsi_id_b = temp_p->adapter_control & HSCSIID;
9848         }
9849         aic7xxx_load_seeprom(temp_p, &sxfrctl1);
9850         break;
9851       }
9852
9853       case 2:
9854       case 3:
9855         temp_p->chip = AHC_AIC7770 | AHC_VL;
9856         temp_p->features |= AHC_AIC7770_FE;
9857         if (type == 2)
9858           temp_p->flags |= AHC_BIOS_ENABLED;
9859         else
9860           temp_p->flags &= ~AHC_BIOS_ENABLED;
9861         if (aic_inb(temp_p, SCSICONF) & TERM_ENB)
9862           sxfrctl1 = STPWEN;
9863         aic7xxx_load_seeprom(temp_p, &sxfrctl1);
9864         temp_p->board_name_index = 4;
9865         if (aic7xxx_verbose & VERBOSE_PROBE2)
9866           printk("aic7xxx: <%s> at VLB %d\n",
9867                board_names[2], slot);
9868         switch( aic_inb(temp_p, STATUS_2840) & BIOS_SEL )
9869         {
9870           case 0x00:
9871             temp_p->bios_address = 0xe0000;
9872             break;
9873           case 0x20:
9874             temp_p->bios_address = 0xc8000;
9875             break;
9876           case 0x40:
9877             temp_p->bios_address = 0xd0000;
9878             break;
9879           case 0x60:
9880             temp_p->bios_address = 0xd8000;
9881             break;
9882           default:
9883             break; /* can't get here */
9884         }
9885         break;
9886
9887       default:  /* Won't get here. */
9888         break;
9889     }
9890     if (aic7xxx_verbose & VERBOSE_PROBE2)
9891     {
9892       printk(KERN_INFO "aic7xxx: BIOS %sabled, IO Port 0x%lx, IRQ %d (%s)\n",
9893         (temp_p->flags & AHC_USEDEFAULTS) ? "dis" : "en", temp_p->base,
9894         temp_p->irq,
9895         (temp_p->pause & IRQMS) ? "level sensitive" : "edge triggered");
9896       printk(KERN_INFO "aic7xxx: Extended translation %sabled.\n",
9897              (temp_p->flags & AHC_EXTEND_TRANS_A) ? "en" : "dis");
9898     }
9899
9900     /*
9901      * All the 7770 based chipsets have this bug
9902      */
9903     temp_p->bugs |= AHC_BUG_TMODE_WIDEODD;
9904
9905     /*
9906      * Set the FIFO threshold and the bus off time.
9907      */
9908     hostconf = aic_inb(temp_p, HOSTCONF);
9909     aic_outb(temp_p, hostconf & DFTHRSH, BUSSPD);
9910     aic_outb(temp_p, (hostconf << 2) & BOFF, BUSTIME);
9911     slot++;
9912     found++;
9913   }
9914
9915 #endif /* defined(__i386__) || defined(__alpha__) */
9916
9917   /*
9918    * Now, we re-order the probed devices by BIOS address and BUS class.
9919    * In general, we follow this algorithm to make the adapters show up
9920    * in the same order under linux that the computer finds them.
9921    *  1: All VLB/EISA cards with BIOS_ENABLED first, according to BIOS
9922    *     address, going from lowest to highest.
9923    *  2: All PCI controllers with BIOS_ENABLED next, according to BIOS
9924    *     address, going from lowest to highest.
9925    *  3: Remaining VLB/EISA controllers going in slot order.
9926    *  4: Remaining PCI controllers, going in PCI device order (reversable)
9927    */
9928
9929   {
9930     struct aic7xxx_host *sort_list[4] = { NULL, NULL, NULL, NULL };
9931     struct aic7xxx_host *vlb, *pci;
9932     struct aic7xxx_host *prev_p;
9933     struct aic7xxx_host *p;
9934     unsigned char left;
9935
9936     prev_p = vlb = pci = NULL;
9937
9938     temp_p = list_p;
9939     while (temp_p != NULL)
9940     {
9941       switch(temp_p->chip & ~AHC_CHIPID_MASK)
9942       {
9943         case AHC_EISA:
9944         case AHC_VL:
9945         {
9946           p = temp_p;
9947           if (p->flags & AHC_BIOS_ENABLED)
9948             vlb = sort_list[0];
9949           else
9950             vlb = sort_list[2];
9951
9952           if (vlb == NULL)
9953           {
9954             vlb = temp_p;
9955             temp_p = temp_p->next;
9956             vlb->next = NULL;
9957           }
9958           else
9959           {
9960             current_p = vlb;
9961             prev_p = NULL;
9962             while ( (current_p != NULL) &&
9963                     (current_p->bios_address < temp_p->bios_address))
9964             {
9965               prev_p = current_p;
9966               current_p = current_p->next;
9967             }
9968             if (prev_p != NULL)
9969             {
9970               prev_p->next = temp_p;
9971               temp_p = temp_p->next;
9972               prev_p->next->next = current_p;
9973             }
9974             else
9975             {
9976               vlb = temp_p;
9977               temp_p = temp_p->next;
9978               vlb->next = current_p;
9979             }
9980           }
9981           
9982           if (p->flags & AHC_BIOS_ENABLED)
9983             sort_list[0] = vlb;
9984           else
9985             sort_list[2] = vlb;
9986           
9987           break;
9988         }
9989         default:  /* All PCI controllers fall through to default */
9990         {
9991
9992           p = temp_p;
9993           if (p->flags & AHC_BIOS_ENABLED) 
9994             pci = sort_list[1];
9995           else
9996             pci = sort_list[3];
9997
9998           if (pci == NULL)
9999           {
10000             pci = temp_p;
10001             temp_p = temp_p->next;
10002             pci->next = NULL;
10003           }
10004           else
10005           {
10006             current_p = pci;
10007             prev_p = NULL;
10008             if (!aic7xxx_reverse_scan)
10009             {
10010               while ( (current_p != NULL) &&
10011                       ( (PCI_SLOT(current_p->pci_device_fn) |
10012                         (current_p->pci_bus << 8)) < 
10013                         (PCI_SLOT(temp_p->pci_device_fn) |
10014                         (temp_p->pci_bus << 8)) ) )
10015               {
10016                 prev_p = current_p;
10017                 current_p = current_p->next;
10018               }
10019             }
10020             else
10021             {
10022               while ( (current_p != NULL) &&
10023                       ( (PCI_SLOT(current_p->pci_device_fn) |
10024                         (current_p->pci_bus << 8)) > 
10025                         (PCI_SLOT(temp_p->pci_device_fn) |
10026                         (temp_p->pci_bus << 8)) ) )
10027               {
10028                 prev_p = current_p;
10029                 current_p = current_p->next;
10030               }
10031             }
10032             /*
10033              * Are we dealing with a 7895/6/7/9 where we need to sort the
10034              * channels as well, if so, the bios_address values should
10035              * be the same
10036              */
10037             if ( (current_p) && (temp_p->flags & AHC_MULTI_CHANNEL) &&
10038                  (temp_p->pci_bus == current_p->pci_bus) &&
10039                  (PCI_SLOT(temp_p->pci_device_fn) ==
10040                   PCI_SLOT(current_p->pci_device_fn)) )
10041             {
10042               if (temp_p->flags & AHC_CHNLB)
10043               {
10044                 if ( !(temp_p->flags & AHC_CHANNEL_B_PRIMARY) )
10045                 {
10046                   prev_p = current_p;
10047                   current_p = current_p->next;
10048                 }
10049               }
10050               else
10051               {
10052                 if (temp_p->flags & AHC_CHANNEL_B_PRIMARY)
10053                 {
10054                   prev_p = current_p;
10055                   current_p = current_p->next;
10056                 }
10057               }
10058             }
10059             if (prev_p != NULL)
10060             {
10061               prev_p->next = temp_p;
10062               temp_p = temp_p->next;
10063               prev_p->next->next = current_p;
10064             }
10065             else
10066             {
10067               pci = temp_p;
10068               temp_p = temp_p->next;
10069               pci->next = current_p;
10070             }
10071           }
10072
10073           if (p->flags & AHC_BIOS_ENABLED)
10074             sort_list[1] = pci;
10075           else
10076             sort_list[3] = pci;
10077
10078           break;
10079         }
10080       }  /* End of switch(temp_p->type) */
10081     } /* End of while (temp_p != NULL) */
10082     /*
10083      * At this point, the cards have been broken into 4 sorted lists, now
10084      * we run through the lists in order and register each controller
10085      */
10086     {
10087       int i;
10088       
10089       left = found;
10090       for (i=0; i<ARRAY_SIZE(sort_list); i++)
10091       {
10092         temp_p = sort_list[i];
10093         while(temp_p != NULL)
10094         {
10095           template->name = board_names[temp_p->board_name_index];
10096           p = aic7xxx_alloc(template, temp_p);
10097           if (p != NULL)
10098           {
10099             p->instance = found - left;
10100             if (aic7xxx_register(template, p, (--left)) == 0)
10101             {
10102               found--;
10103               aic7xxx_release(p->host);
10104               scsi_unregister(p->host);
10105             }
10106             else if (aic7xxx_dump_card)
10107             {
10108               pause_sequencer(p);
10109               aic7xxx_print_card(p);
10110               aic7xxx_print_scratch_ram(p);
10111               unpause_sequencer(p, TRUE);
10112             }
10113           }
10114           current_p = temp_p;
10115           temp_p = (struct aic7xxx_host *)temp_p->next;
10116           kfree(current_p);
10117         }
10118       }
10119     }
10120   }
10121   return (found);
10122 }
10123
10124 /*+F*************************************************************************
10125  * Function:
10126  *   aic7xxx_buildscb
10127  *
10128  * Description:
10129  *   Build a SCB.
10130  *-F*************************************************************************/
10131 static void aic7xxx_buildscb(struct aic7xxx_host *p, struct scsi_cmnd *cmd,
10132                              struct aic7xxx_scb *scb)
10133 {
10134   unsigned short mask;
10135   struct aic7xxx_hwscb *hscb;
10136   struct aic_dev_data *aic_dev = cmd->device->hostdata;
10137   struct scsi_device *sdptr = cmd->device;
10138   unsigned char tindex = TARGET_INDEX(cmd);
10139   struct request *req = cmd->request;
10140
10141   mask = (0x01 << tindex);
10142   hscb = scb->hscb;
10143
10144   /*
10145    * Setup the control byte if we need negotiation and have not
10146    * already requested it.
10147    */
10148   hscb->control = 0;
10149   scb->tag_action = 0;
10150
10151   if (p->discenable & mask)
10152   {
10153     hscb->control |= DISCENB;
10154     /* We always force TEST_UNIT_READY to untagged */
10155     if (cmd->cmnd[0] != TEST_UNIT_READY && sdptr->simple_tags)
10156     {
10157       if (req->cmd_flags & REQ_HARDBARRIER)
10158       {
10159         if(sdptr->ordered_tags)
10160         {
10161           hscb->control |= MSG_ORDERED_Q_TAG;
10162           scb->tag_action = MSG_ORDERED_Q_TAG;
10163         }
10164       }
10165       else
10166       {
10167         hscb->control |= MSG_SIMPLE_Q_TAG;
10168         scb->tag_action = MSG_SIMPLE_Q_TAG;
10169       }
10170     }
10171   }
10172   if ( !(aic_dev->dtr_pending) &&
10173         (aic_dev->needppr || aic_dev->needwdtr || aic_dev->needsdtr) &&
10174         (aic_dev->flags & DEVICE_DTR_SCANNED) )
10175   {
10176     aic_dev->dtr_pending = 1;
10177     scb->tag_action = 0;
10178     hscb->control &= DISCENB;
10179     hscb->control |= MK_MESSAGE;
10180     if(aic_dev->needppr)
10181     {
10182       scb->flags |= SCB_MSGOUT_PPR;
10183     }
10184     else if(aic_dev->needwdtr)
10185     {
10186       scb->flags |= SCB_MSGOUT_WDTR;
10187     }
10188     else if(aic_dev->needsdtr)
10189     {
10190       scb->flags |= SCB_MSGOUT_SDTR;
10191     }
10192     scb->flags |= SCB_DTR_SCB;
10193   }
10194   hscb->target_channel_lun = ((cmd->device->id << 4) & 0xF0) |
10195         ((cmd->device->channel & 0x01) << 3) | (cmd->device->lun & 0x07);
10196
10197   /*
10198    * The interpretation of request_buffer and request_bufflen
10199    * changes depending on whether or not use_sg is zero; a
10200    * non-zero use_sg indicates the number of elements in the
10201    * scatter-gather array.
10202    */
10203
10204   /*
10205    * XXX - this relies on the host data being stored in a
10206    *       little-endian format.
10207    */
10208   hscb->SCSI_cmd_length = cmd->cmd_len;
10209   memcpy(scb->cmnd, cmd->cmnd, cmd->cmd_len);
10210   hscb->SCSI_cmd_pointer = cpu_to_le32(SCB_DMA_ADDR(scb, scb->cmnd));
10211
10212   if (cmd->use_sg)
10213   {
10214     struct scatterlist *sg;  /* Must be mid-level SCSI code scatterlist */
10215
10216     /*
10217      * We must build an SG list in adapter format, as the kernel's SG list
10218      * cannot be used directly because of data field size (__alpha__)
10219      * differences and the kernel SG list uses virtual addresses where
10220      * we need physical addresses.
10221      */
10222     int i, use_sg;
10223
10224     sg = (struct scatterlist *)cmd->request_buffer;
10225     scb->sg_length = 0;
10226     use_sg = pci_map_sg(p->pdev, sg, cmd->use_sg, cmd->sc_data_direction);
10227     /*
10228      * Copy the segments into the SG array.  NOTE!!! - We used to
10229      * have the first entry both in the data_pointer area and the first
10230      * SG element.  That has changed somewhat.  We still have the first
10231      * entry in both places, but now we download the address of
10232      * scb->sg_list[1] instead of 0 to the sg pointer in the hscb.
10233      */
10234     for (i = 0; i < use_sg; i++)
10235     {
10236       unsigned int len = sg_dma_len(sg+i);
10237       scb->sg_list[i].address = cpu_to_le32(sg_dma_address(sg+i));
10238       scb->sg_list[i].length = cpu_to_le32(len);
10239       scb->sg_length += len;
10240     }
10241     /* Copy the first SG into the data pointer area. */
10242     hscb->data_pointer = scb->sg_list[0].address;
10243     hscb->data_count = scb->sg_list[0].length;
10244     scb->sg_count = i;
10245     hscb->SG_segment_count = i;
10246     hscb->SG_list_pointer = cpu_to_le32(SCB_DMA_ADDR(scb, &scb->sg_list[1]));
10247   }
10248   else
10249   {
10250     if (cmd->request_bufflen)
10251     {
10252       unsigned int address = pci_map_single(p->pdev, cmd->request_buffer,
10253                                             cmd->request_bufflen,
10254                                             cmd->sc_data_direction);
10255       aic7xxx_mapping(cmd) = address;
10256       scb->sg_list[0].address = cpu_to_le32(address);
10257       scb->sg_list[0].length = cpu_to_le32(cmd->request_bufflen);
10258       scb->sg_count = 1;
10259       scb->sg_length = cmd->request_bufflen;
10260       hscb->SG_segment_count = 1;
10261       hscb->SG_list_pointer = cpu_to_le32(SCB_DMA_ADDR(scb, &scb->sg_list[0]));
10262       hscb->data_count = scb->sg_list[0].length;
10263       hscb->data_pointer = scb->sg_list[0].address;
10264     }
10265     else
10266     {
10267       scb->sg_count = 0;
10268       scb->sg_length = 0;
10269       hscb->SG_segment_count = 0;
10270       hscb->SG_list_pointer = 0;
10271       hscb->data_count = 0;
10272       hscb->data_pointer = 0;
10273     }
10274   }
10275 }
10276
10277 /*+F*************************************************************************
10278  * Function:
10279  *   aic7xxx_queue
10280  *
10281  * Description:
10282  *   Queue a SCB to the controller.
10283  *-F*************************************************************************/
10284 static int aic7xxx_queue(struct scsi_cmnd *cmd, void (*fn)(struct scsi_cmnd *))
10285 {
10286   struct aic7xxx_host *p;
10287   struct aic7xxx_scb *scb;
10288   struct aic_dev_data *aic_dev;
10289
10290   p = (struct aic7xxx_host *) cmd->device->host->hostdata;
10291
10292   aic_dev = cmd->device->hostdata;  
10293 #ifdef AIC7XXX_VERBOSE_DEBUGGING
10294   if (aic_dev->active_cmds > aic_dev->max_q_depth)
10295   {
10296     printk(WARN_LEAD "Commands queued exceeds queue "
10297            "depth, active=%d\n",
10298            p->host_no, CTL_OF_CMD(cmd), 
10299            aic_dev->active_cmds);
10300   }
10301 #endif
10302
10303   scb = scbq_remove_head(&p->scb_data->free_scbs);
10304   if (scb == NULL)
10305   {
10306     aic7xxx_allocate_scb(p);
10307     scb = scbq_remove_head(&p->scb_data->free_scbs);
10308     if(scb == NULL)
10309     {
10310       printk(WARN_LEAD "Couldn't get a free SCB.\n", p->host_no,
10311              CTL_OF_CMD(cmd));
10312       return 1;
10313     }
10314   }
10315   scb->cmd = cmd;
10316
10317         /*
10318         * Make sure the scsi_cmnd pointer is saved, the struct it points to
10319         * is set up properly, and the parity error flag is reset, then send
10320         * the SCB to the sequencer and watch the fun begin.
10321         */
10322   aic7xxx_position(cmd) = scb->hscb->tag;
10323   cmd->scsi_done = fn;
10324   cmd->result = DID_OK;
10325   memset(cmd->sense_buffer, 0, sizeof(cmd->sense_buffer));
10326   aic7xxx_error(cmd) = DID_OK;
10327   aic7xxx_status(cmd) = 0;
10328   cmd->host_scribble = NULL;
10329
10330   /*
10331    * Construct the SCB beforehand, so the sequencer is
10332    * paused a minimal amount of time.
10333    */
10334   aic7xxx_buildscb(p, cmd, scb);
10335
10336   scb->flags |= SCB_ACTIVE | SCB_WAITINGQ;
10337
10338   scbq_insert_tail(&p->waiting_scbs, scb);
10339   aic7xxx_run_waiting_queues(p);
10340   return (0);
10341 }
10342
10343 /*+F*************************************************************************
10344  * Function:
10345  *   aic7xxx_bus_device_reset
10346  *
10347  * Description:
10348  *   Abort or reset the current SCSI command(s).  If the scb has not
10349  *   previously been aborted, then we attempt to send a BUS_DEVICE_RESET
10350  *   message to the target.  If the scb has previously been unsuccessfully
10351  *   aborted, then we will reset the channel and have all devices renegotiate.
10352  *   Returns an enumerated type that indicates the status of the operation.
10353  *-F*************************************************************************/
10354 static int __aic7xxx_bus_device_reset(struct scsi_cmnd *cmd)
10355 {
10356   struct aic7xxx_host  *p;
10357   struct aic7xxx_scb   *scb;
10358   struct aic7xxx_hwscb *hscb;
10359   int channel;
10360   unsigned char saved_scbptr, lastphase;
10361   unsigned char hscb_index;
10362   int disconnected;
10363   struct aic_dev_data *aic_dev;
10364
10365   if(cmd == NULL)
10366   {
10367     printk(KERN_ERR "aic7xxx_bus_device_reset: called with NULL cmd!\n");
10368     return FAILED;
10369   }
10370   p = (struct aic7xxx_host *)cmd->device->host->hostdata;
10371   aic_dev = AIC_DEV(cmd);
10372   if(aic7xxx_position(cmd) < p->scb_data->numscbs)
10373     scb = (p->scb_data->scb_array[aic7xxx_position(cmd)]);
10374   else
10375     return FAILED;
10376
10377   hscb = scb->hscb;
10378
10379   aic7xxx_isr(p);
10380   aic7xxx_done_cmds_complete(p);
10381   /* If the command was already complete or just completed, then we didn't
10382    * do a reset, return FAILED */
10383   if(!(scb->flags & SCB_ACTIVE))
10384     return FAILED;
10385
10386   pause_sequencer(p);
10387   lastphase = aic_inb(p, LASTPHASE);
10388   if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
10389   {
10390     printk(INFO_LEAD "Bus Device reset, scb flags 0x%x, ",
10391          p->host_no, CTL_OF_SCB(scb), scb->flags);
10392     switch (lastphase)
10393     {
10394       case P_DATAOUT:
10395         printk("Data-Out phase\n");
10396         break;
10397       case P_DATAIN:
10398         printk("Data-In phase\n");
10399         break;
10400       case P_COMMAND:
10401         printk("Command phase\n");
10402         break;
10403       case P_MESGOUT:
10404         printk("Message-Out phase\n");
10405         break;
10406       case P_STATUS:
10407         printk("Status phase\n");
10408         break;
10409       case P_MESGIN:
10410         printk("Message-In phase\n");
10411         break;
10412       default:
10413       /*
10414        * We're not in a valid phase, so assume we're idle.
10415        */
10416         printk("while idle, LASTPHASE = 0x%x\n", lastphase);
10417         break;
10418     }
10419     printk(INFO_LEAD "SCSISIGI 0x%x, SEQADDR 0x%x, SSTAT0 0x%x, SSTAT1 "
10420          "0x%x\n", p->host_no, CTL_OF_SCB(scb),
10421          aic_inb(p, SCSISIGI),
10422          aic_inb(p, SEQADDR0) | (aic_inb(p, SEQADDR1) << 8),
10423          aic_inb(p, SSTAT0), aic_inb(p, SSTAT1));
10424     printk(INFO_LEAD "SG_CACHEPTR 0x%x, SSTAT2 0x%x, STCNT 0x%x\n", p->host_no,
10425          CTL_OF_SCB(scb),
10426          (p->features & AHC_ULTRA2) ? aic_inb(p, SG_CACHEPTR) : 0,
10427          aic_inb(p, SSTAT2),
10428          aic_inb(p, STCNT + 2) << 16 | aic_inb(p, STCNT + 1) << 8 |
10429          aic_inb(p, STCNT));
10430   }
10431
10432   channel = cmd->device->channel;
10433
10434     /*
10435      * Send a Device Reset Message:
10436      * The target that is holding up the bus may not be the same as
10437      * the one that triggered this timeout (different commands have
10438      * different timeout lengths).  Our strategy here is to queue an
10439      * abort message to the timed out target if it is disconnected.
10440      * Otherwise, if we have an active target we stuff the message buffer
10441      * with an abort message and assert ATN in the hopes that the target
10442      * will let go of the bus and go to the mesgout phase.  If this
10443      * fails, we'll get another timeout a few seconds later which will
10444      * attempt a bus reset.
10445      */
10446   saved_scbptr = aic_inb(p, SCBPTR);
10447   disconnected = FALSE;
10448
10449   if (lastphase != P_BUSFREE)
10450   {
10451     if (aic_inb(p, SCB_TAG) >= p->scb_data->numscbs)
10452     {
10453       printk(WARN_LEAD "Invalid SCB ID %d is active, "
10454              "SCB flags = 0x%x.\n", p->host_no,
10455             CTL_OF_CMD(cmd), scb->hscb->tag, scb->flags);
10456       unpause_sequencer(p, FALSE);
10457       return FAILED;
10458     }
10459     if (scb->hscb->tag == aic_inb(p, SCB_TAG))
10460     { 
10461       if ( (lastphase == P_MESGOUT) || (lastphase == P_MESGIN) )
10462       {
10463         printk(WARN_LEAD "Device reset, Message buffer "
10464                 "in use\n", p->host_no, CTL_OF_SCB(scb));
10465         unpause_sequencer(p, FALSE);
10466         return FAILED;
10467       }
10468         
10469       if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
10470         printk(INFO_LEAD "Device reset message in "
10471               "message buffer\n", p->host_no, CTL_OF_SCB(scb));
10472       scb->flags |= SCB_RESET | SCB_DEVICE_RESET;
10473       aic7xxx_error(cmd) = DID_RESET;
10474       aic_dev->flags |= BUS_DEVICE_RESET_PENDING;
10475       /* Send the abort message to the active SCB. */
10476       aic_outb(p, HOST_MSG, MSG_OUT);
10477       aic_outb(p, lastphase | ATNO, SCSISIGO);
10478       unpause_sequencer(p, FALSE);
10479       spin_unlock_irq(p->host->host_lock);
10480       ssleep(1);
10481       spin_lock_irq(p->host->host_lock);
10482       if(aic_dev->flags & BUS_DEVICE_RESET_PENDING)
10483         return FAILED;
10484       else
10485         return SUCCESS;
10486     }
10487   } /* if (last_phase != P_BUSFREE).....indicates we are idle and can work */
10488   /*
10489    * Simply set the MK_MESSAGE flag and the SEQINT handler will do
10490    * the rest on a reconnect/connect.
10491    */
10492   scb->hscb->control |= MK_MESSAGE;
10493   scb->flags |= SCB_RESET | SCB_DEVICE_RESET;
10494   aic_dev->flags |= BUS_DEVICE_RESET_PENDING;
10495   /*
10496    * Check to see if the command is on the qinfifo.  If it is, then we will
10497    * not need to queue the command again since the card should start it soon
10498    */
10499   if (aic7xxx_search_qinfifo(p, cmd->device->channel, cmd->device->id, cmd->device->lun, hscb->tag,
10500                           0, TRUE, NULL) == 0)
10501   {
10502     disconnected = TRUE;
10503     if ((hscb_index = aic7xxx_find_scb(p, scb)) != SCB_LIST_NULL)
10504     {
10505       unsigned char scb_control;
10506
10507       aic_outb(p, hscb_index, SCBPTR);
10508       scb_control = aic_inb(p, SCB_CONTROL);
10509       /*
10510        * If the DISCONNECTED bit is not set in SCB_CONTROL, then we are
10511        * actually on the waiting list, not disconnected, and we don't
10512        * need to requeue the command.
10513        */
10514       disconnected = (scb_control & DISCONNECTED);
10515       aic_outb(p, scb_control | MK_MESSAGE, SCB_CONTROL);
10516     }
10517     if (disconnected)
10518     {
10519       /*
10520        * Actually requeue this SCB in case we can select the
10521        * device before it reconnects.  This can result in the command
10522        * being on the qinfifo twice, but we don't care because it will
10523        * all get cleaned up if/when the reset takes place.
10524        */
10525       if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
10526         printk(INFO_LEAD "Queueing device reset command.\n", p->host_no,
10527                       CTL_OF_SCB(scb));
10528       p->qinfifo[p->qinfifonext++] = scb->hscb->tag;
10529       if (p->features & AHC_QUEUE_REGS)
10530         aic_outb(p, p->qinfifonext, HNSCB_QOFF);
10531       else
10532         aic_outb(p, p->qinfifonext, KERNEL_QINPOS);
10533       scb->flags |= SCB_QUEUED_ABORT;
10534     }
10535   }
10536   aic_outb(p, saved_scbptr, SCBPTR);
10537   unpause_sequencer(p, FALSE);
10538   spin_unlock_irq(p->host->host_lock);
10539   msleep(1000/4);
10540   spin_lock_irq(p->host->host_lock);
10541   if(aic_dev->flags & BUS_DEVICE_RESET_PENDING)
10542     return FAILED;
10543   else
10544     return SUCCESS;
10545 }
10546
10547 static int aic7xxx_bus_device_reset(struct scsi_cmnd *cmd)
10548 {
10549       int rc;
10550
10551       spin_lock_irq(cmd->device->host->host_lock);
10552       rc = __aic7xxx_bus_device_reset(cmd);
10553       spin_unlock_irq(cmd->device->host->host_lock);
10554
10555       return rc;
10556 }
10557
10558
10559 /*+F*************************************************************************
10560  * Function:
10561  *   aic7xxx_panic_abort
10562  *
10563  * Description:
10564  *   Abort the current SCSI command(s).
10565  *-F*************************************************************************/
10566 static void aic7xxx_panic_abort(struct aic7xxx_host *p, struct scsi_cmnd *cmd)
10567 {
10568
10569   printk("aic7xxx driver version %s\n", AIC7XXX_C_VERSION);
10570   printk("Controller type:\n    %s\n", board_names[p->board_name_index]);
10571   printk("p->flags=0x%lx, p->chip=0x%x, p->features=0x%x, "
10572          "sequencer %s paused\n",
10573      p->flags, p->chip, p->features,
10574     (aic_inb(p, HCNTRL) & PAUSE) ? "is" : "isn't" );
10575   pause_sequencer(p);
10576   disable_irq(p->irq);
10577   aic7xxx_print_card(p);
10578   aic7xxx_print_scratch_ram(p);
10579   spin_unlock_irq(p->host->host_lock);
10580   for(;;) barrier();
10581 }
10582
10583 /*+F*************************************************************************
10584  * Function:
10585  *   aic7xxx_abort
10586  *
10587  * Description:
10588  *   Abort the current SCSI command(s).
10589  *-F*************************************************************************/
10590 static int __aic7xxx_abort(struct scsi_cmnd *cmd)
10591 {
10592   struct aic7xxx_scb  *scb = NULL;
10593   struct aic7xxx_host *p;
10594   int    found=0, disconnected;
10595   unsigned char saved_hscbptr, hscbptr, scb_control;
10596   struct aic_dev_data *aic_dev;
10597
10598   if(cmd == NULL)
10599   {
10600     printk(KERN_ERR "aic7xxx_abort: called with NULL cmd!\n");
10601     return FAILED;
10602   }
10603   p = (struct aic7xxx_host *)cmd->device->host->hostdata;
10604   aic_dev = AIC_DEV(cmd);
10605   if(aic7xxx_position(cmd) < p->scb_data->numscbs)
10606     scb = (p->scb_data->scb_array[aic7xxx_position(cmd)]);
10607   else
10608     return FAILED;
10609
10610   aic7xxx_isr(p);
10611   aic7xxx_done_cmds_complete(p);
10612   /* If the command was already complete or just completed, then we didn't
10613    * do a reset, return FAILED */
10614   if(!(scb->flags & SCB_ACTIVE))
10615     return FAILED;
10616
10617   pause_sequencer(p);
10618
10619   /*
10620    * I added a new config option to the driver: "panic_on_abort" that will
10621    * cause the driver to panic and the machine to stop on the first abort
10622    * or reset call into the driver.  At that point, it prints out a lot of
10623    * useful information for me which I can then use to try and debug the
10624    * problem.  Simply enable the boot time prompt in order to activate this
10625    * code.
10626    */
10627   if (aic7xxx_panic_on_abort)
10628     aic7xxx_panic_abort(p, cmd);
10629
10630   if (aic7xxx_verbose & VERBOSE_ABORT)
10631   {
10632     printk(INFO_LEAD "Aborting scb %d, flags 0x%x, SEQADDR 0x%x, LASTPHASE "
10633            "0x%x\n",
10634          p->host_no, CTL_OF_SCB(scb), scb->hscb->tag, scb->flags,
10635          aic_inb(p, SEQADDR0) | (aic_inb(p, SEQADDR1) << 8),
10636          aic_inb(p, LASTPHASE));
10637     printk(INFO_LEAD "SG_CACHEPTR 0x%x, SG_COUNT %d, SCSISIGI 0x%x\n",
10638          p->host_no, CTL_OF_SCB(scb), (p->features & AHC_ULTRA2) ?
10639          aic_inb(p, SG_CACHEPTR) : 0, aic_inb(p, SG_COUNT),
10640          aic_inb(p, SCSISIGI));
10641     printk(INFO_LEAD "SSTAT0 0x%x, SSTAT1 0x%x, SSTAT2 0x%x\n",
10642          p->host_no, CTL_OF_SCB(scb), aic_inb(p, SSTAT0),
10643          aic_inb(p, SSTAT1), aic_inb(p, SSTAT2));
10644   }
10645
10646   if (scb->flags & SCB_WAITINGQ)
10647   {
10648     if (aic7xxx_verbose & VERBOSE_ABORT_PROCESS) 
10649       printk(INFO_LEAD "SCB found on waiting list and "
10650           "aborted.\n", p->host_no, CTL_OF_SCB(scb));
10651     scbq_remove(&p->waiting_scbs, scb);
10652     scbq_remove(&aic_dev->delayed_scbs, scb);
10653     aic_dev->active_cmds++;
10654     p->activescbs++;
10655     scb->flags &= ~(SCB_WAITINGQ | SCB_ACTIVE);
10656     scb->flags |= SCB_ABORT | SCB_QUEUED_FOR_DONE;
10657     goto success;
10658   }
10659
10660 /*
10661  *  We just checked the waiting_q, now for the QINFIFO
10662  */
10663   if ( ((found = aic7xxx_search_qinfifo(p, cmd->device->id, cmd->device->channel,
10664                      cmd->device->lun, scb->hscb->tag, SCB_ABORT | SCB_QUEUED_FOR_DONE,
10665                      FALSE, NULL)) != 0) &&
10666                     (aic7xxx_verbose & VERBOSE_ABORT_PROCESS))
10667   {
10668     printk(INFO_LEAD "SCB found in QINFIFO and aborted.\n", p->host_no,
10669                     CTL_OF_SCB(scb));
10670     goto success;
10671   }
10672
10673 /*
10674  *  QINFIFO, waitingq, completeq done.  Next, check WAITING_SCB list in card
10675  */
10676
10677   saved_hscbptr = aic_inb(p, SCBPTR);
10678   if ((hscbptr = aic7xxx_find_scb(p, scb)) != SCB_LIST_NULL)
10679   {
10680     aic_outb(p, hscbptr, SCBPTR);
10681     scb_control = aic_inb(p, SCB_CONTROL);
10682     disconnected = scb_control & DISCONNECTED;
10683     /*
10684      * If the DISCONNECTED bit is not set in SCB_CONTROL, then we are
10685      * either currently active or on the waiting list.
10686      */
10687     if(!disconnected && aic_inb(p, LASTPHASE) == P_BUSFREE) {
10688       if (aic7xxx_verbose & VERBOSE_ABORT_PROCESS)
10689         printk(INFO_LEAD "SCB found on hardware waiting"
10690           " list and aborted.\n", p->host_no, CTL_OF_SCB(scb));
10691       /* If we are the only waiting command, stop the selection engine */
10692       if (aic_inb(p, WAITING_SCBH) == hscbptr && aic_inb(p, SCB_NEXT) ==
10693                         SCB_LIST_NULL)
10694       {
10695         aic_outb(p, aic_inb(p, SCSISEQ) & ~ENSELO, SCSISEQ);
10696         aic_outb(p, CLRSELTIMEO, CLRSINT1);
10697         aic_outb(p, SCB_LIST_NULL, WAITING_SCBH);
10698       }
10699       else
10700       {
10701         unsigned char prev, next;
10702         prev = SCB_LIST_NULL;
10703         next = aic_inb(p, WAITING_SCBH);
10704         while(next != SCB_LIST_NULL)
10705         {
10706           aic_outb(p, next, SCBPTR);
10707           if (next == hscbptr)
10708           {
10709             next = aic_inb(p, SCB_NEXT);
10710             if (prev != SCB_LIST_NULL)
10711             {
10712               aic_outb(p, prev, SCBPTR);
10713               aic_outb(p, next, SCB_NEXT);
10714             }
10715             else
10716               aic_outb(p, next, WAITING_SCBH);
10717             aic_outb(p, hscbptr, SCBPTR);
10718             next = SCB_LIST_NULL;
10719           }
10720           else
10721           {
10722             prev = next;
10723             next = aic_inb(p, SCB_NEXT);
10724           }
10725         }
10726       }
10727       aic_outb(p, SCB_LIST_NULL, SCB_TAG);
10728       aic_outb(p, 0, SCB_CONTROL);
10729       aic7xxx_add_curscb_to_free_list(p);
10730       scb->flags = SCB_ABORT | SCB_QUEUED_FOR_DONE;
10731       goto success;
10732     }
10733     else if (!disconnected)
10734     {
10735       /*
10736        * We are the currently active command
10737        */
10738       if((aic_inb(p, LASTPHASE) == P_MESGIN) ||
10739          (aic_inb(p, LASTPHASE) == P_MESGOUT))
10740       {
10741         /*
10742          * Message buffer busy, unable to abort
10743          */
10744         printk(INFO_LEAD "message buffer busy, unable to abort.\n",
10745                           p->host_no, CTL_OF_SCB(scb));
10746         unpause_sequencer(p, FALSE);
10747         return FAILED;
10748       }
10749       /* Fallthrough to below, set ATNO after we set SCB_CONTROL */
10750     } 
10751     aic_outb(p,  scb_control | MK_MESSAGE, SCB_CONTROL);
10752     if(!disconnected)
10753     {
10754       aic_outb(p, HOST_MSG, MSG_OUT);
10755       aic_outb(p, aic_inb(p, SCSISIGI) | ATNO, SCSISIGO);
10756     }
10757     aic_outb(p, saved_hscbptr, SCBPTR);
10758   } 
10759   else
10760   {
10761     /*
10762      * The scb isn't in the card at all and it is active and it isn't in
10763      * any of the queues, so it must be disconnected and paged out.  Fall
10764      * through to the code below.
10765      */
10766     disconnected = 1;
10767   }
10768         
10769   p->flags |= AHC_ABORT_PENDING;
10770   scb->flags |= SCB_QUEUED_ABORT | SCB_ABORT | SCB_RECOVERY_SCB;
10771   scb->hscb->control |= MK_MESSAGE;
10772   if(disconnected)
10773   {
10774     if (aic7xxx_verbose & VERBOSE_ABORT_PROCESS)
10775       printk(INFO_LEAD "SCB disconnected.  Queueing Abort"
10776         " SCB.\n", p->host_no, CTL_OF_SCB(scb));
10777     p->qinfifo[p->qinfifonext++] = scb->hscb->tag;
10778     if (p->features & AHC_QUEUE_REGS)
10779       aic_outb(p, p->qinfifonext, HNSCB_QOFF);
10780     else
10781       aic_outb(p, p->qinfifonext, KERNEL_QINPOS);
10782   }
10783   unpause_sequencer(p, FALSE);
10784   spin_unlock_irq(p->host->host_lock);
10785   msleep(1000/4);
10786   spin_lock_irq(p->host->host_lock);
10787   if (p->flags & AHC_ABORT_PENDING)
10788   {
10789     if (aic7xxx_verbose & VERBOSE_ABORT_RETURN)
10790       printk(INFO_LEAD "Abort never delivered, returning FAILED\n", p->host_no,
10791                     CTL_OF_CMD(cmd));
10792     p->flags &= ~AHC_ABORT_PENDING;
10793     return FAILED;
10794   }
10795   if (aic7xxx_verbose & VERBOSE_ABORT_RETURN)
10796     printk(INFO_LEAD "Abort successful.\n", p->host_no, CTL_OF_CMD(cmd));
10797   return SUCCESS;
10798
10799 success:
10800   if (aic7xxx_verbose & VERBOSE_ABORT_RETURN)
10801     printk(INFO_LEAD "Abort successful.\n", p->host_no, CTL_OF_CMD(cmd));
10802   aic7xxx_run_done_queue(p, TRUE);
10803   unpause_sequencer(p, FALSE);
10804   return SUCCESS;
10805 }
10806
10807 static int aic7xxx_abort(struct scsi_cmnd *cmd)
10808 {
10809         int rc;
10810
10811         spin_lock_irq(cmd->device->host->host_lock);
10812         rc = __aic7xxx_abort(cmd);
10813         spin_unlock_irq(cmd->device->host->host_lock);
10814
10815         return rc;
10816 }
10817
10818
10819 /*+F*************************************************************************
10820  * Function:
10821  *   aic7xxx_reset
10822  *
10823  * Description:
10824  *   Resetting the bus always succeeds - is has to, otherwise the
10825  *   kernel will panic! Try a surgical technique - sending a BUS
10826  *   DEVICE RESET message - on the offending target before pulling
10827  *   the SCSI bus reset line.
10828  *-F*************************************************************************/
10829 static int aic7xxx_reset(struct scsi_cmnd *cmd)
10830 {
10831   struct aic7xxx_scb *scb;
10832   struct aic7xxx_host *p;
10833   struct aic_dev_data *aic_dev;
10834
10835   p = (struct aic7xxx_host *) cmd->device->host->hostdata;
10836   spin_lock_irq(p->host->host_lock);
10837
10838   aic_dev = AIC_DEV(cmd);
10839   if(aic7xxx_position(cmd) < p->scb_data->numscbs)
10840   {
10841     scb = (p->scb_data->scb_array[aic7xxx_position(cmd)]);
10842     if (scb->cmd != cmd)
10843       scb = NULL;
10844   }
10845   else
10846   {
10847     scb = NULL;
10848   }
10849
10850   /*
10851    * I added a new config option to the driver: "panic_on_abort" that will
10852    * cause the driver to panic and the machine to stop on the first abort
10853    * or reset call into the driver.  At that point, it prints out a lot of
10854    * useful information for me which I can then use to try and debug the
10855    * problem.  Simply enable the boot time prompt in order to activate this
10856    * code.
10857    */
10858   if (aic7xxx_panic_on_abort)
10859     aic7xxx_panic_abort(p, cmd);
10860
10861   pause_sequencer(p);
10862
10863   while((aic_inb(p, INTSTAT) & INT_PEND) && !(p->flags & AHC_IN_ISR))
10864   {
10865     aic7xxx_isr(p);
10866     pause_sequencer(p);
10867   }
10868   aic7xxx_done_cmds_complete(p);
10869
10870   if(scb && (scb->cmd == NULL))
10871   {
10872     /*
10873      * We just completed the command when we ran the isr stuff, so we no
10874      * longer have it.
10875      */
10876     unpause_sequencer(p, FALSE);
10877     spin_unlock_irq(p->host->host_lock);
10878     return SUCCESS;
10879   }
10880     
10881 /*
10882  *  By this point, we want to already know what we are going to do and
10883  *  only have the following code implement our course of action.
10884  */
10885   aic7xxx_reset_channel(p, cmd->device->channel, TRUE);
10886   if (p->features & AHC_TWIN)
10887   {
10888     aic7xxx_reset_channel(p, cmd->device->channel ^ 0x01, TRUE);
10889     restart_sequencer(p);
10890   }
10891   aic_outb(p,  aic_inb(p, SIMODE1) & ~(ENREQINIT|ENBUSFREE), SIMODE1);
10892   aic7xxx_clear_intstat(p);
10893   p->flags &= ~AHC_HANDLING_REQINITS;
10894   p->msg_type = MSG_TYPE_NONE;
10895   p->msg_index = 0;
10896   p->msg_len = 0;
10897   aic7xxx_run_done_queue(p, TRUE);
10898   unpause_sequencer(p, FALSE);
10899   spin_unlock_irq(p->host->host_lock);
10900   ssleep(2);
10901   return SUCCESS;
10902 }
10903
10904 /*+F*************************************************************************
10905  * Function:
10906  *   aic7xxx_biosparam
10907  *
10908  * Description:
10909  *   Return the disk geometry for the given SCSI device.
10910  *
10911  * Note:
10912  *   This function is broken for today's really large drives and needs
10913  *   fixed.
10914  *-F*************************************************************************/
10915 static int
10916 aic7xxx_biosparam(struct scsi_device *sdev, struct block_device *bdev,
10917                 sector_t capacity, int geom[])
10918 {
10919   sector_t heads, sectors, cylinders;
10920   int ret;
10921   struct aic7xxx_host *p;
10922   unsigned char *buf;
10923
10924   p = (struct aic7xxx_host *) sdev->host->hostdata;
10925   buf = scsi_bios_ptable(bdev);
10926
10927   if ( buf )
10928   {
10929     ret = scsi_partsize(buf, capacity, &geom[2], &geom[0], &geom[1]);
10930     kfree(buf);
10931     if ( ret != -1 )
10932       return(ret);
10933   }
10934   
10935   heads = 64;
10936   sectors = 32;
10937   cylinders = capacity >> 11;
10938
10939   if ((p->flags & AHC_EXTEND_TRANS_A) && (cylinders > 1024))
10940   {
10941     heads = 255;
10942     sectors = 63;
10943     cylinders = capacity >> 14;
10944     if(capacity > (65535 * heads * sectors))
10945       cylinders = 65535;
10946     else
10947       cylinders = ((unsigned int)capacity) / (unsigned int)(heads * sectors);
10948   }
10949
10950   geom[0] = (int)heads;
10951   geom[1] = (int)sectors;
10952   geom[2] = (int)cylinders;
10953
10954   return (0);
10955 }
10956
10957 /*+F*************************************************************************
10958  * Function:
10959  *   aic7xxx_release
10960  *
10961  * Description:
10962  *   Free the passed in Scsi_Host memory structures prior to unloading the
10963  *   module.
10964  *-F*************************************************************************/
10965 static int
10966 aic7xxx_release(struct Scsi_Host *host)
10967 {
10968   struct aic7xxx_host *p = (struct aic7xxx_host *) host->hostdata;
10969   struct aic7xxx_host *next, *prev;
10970
10971   if(p->irq)
10972     free_irq(p->irq, p);
10973 #ifdef MMAPIO
10974   if(p->maddr)
10975   {
10976     iounmap(p->maddr);
10977   }
10978 #endif /* MMAPIO */
10979   if(!p->pdev)
10980     release_region(p->base, MAXREG - MINREG);
10981 #ifdef CONFIG_PCI
10982   else {
10983     pci_release_regions(p->pdev);
10984     pci_dev_put(p->pdev);
10985   }
10986 #endif
10987   prev = NULL;
10988   next = first_aic7xxx;
10989   while(next != NULL)
10990   {
10991     if(next == p)
10992     {
10993       if(prev == NULL)
10994         first_aic7xxx = next->next;
10995       else
10996         prev->next = next->next;
10997     }
10998     else
10999     {
11000       prev = next;
11001     }
11002     next = next->next;
11003   }
11004   aic7xxx_free(p);
11005   return(0);
11006 }
11007
11008 /*+F*************************************************************************
11009  * Function:
11010  *   aic7xxx_print_card
11011  *
11012  * Description:
11013  *   Print out all of the control registers on the card
11014  *
11015  *   NOTE: This function is not yet safe for use on the VLB and EISA
11016  *   controllers, so it isn't used on those controllers at all.
11017  *-F*************************************************************************/
11018 static void
11019 aic7xxx_print_card(struct aic7xxx_host *p)
11020 {
11021   int i, j, k, chip;
11022   static struct register_ranges {
11023     int num_ranges;
11024     int range_val[32];
11025   } cards_ds[] = {
11026     { 0, {0,} }, /* none */
11027     {10, {0x00, 0x05, 0x08, 0x11, 0x18, 0x19, 0x1f, 0x1f, 0x60, 0x60, /*7771*/
11028           0x62, 0x66, 0x80, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9b, 0x9f} },
11029     { 9, {0x00, 0x05, 0x08, 0x11, 0x18, 0x1f, 0x60, 0x60, 0x62, 0x66, /*7850*/
11030           0x80, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9f} },
11031     { 9, {0x00, 0x05, 0x08, 0x11, 0x18, 0x1f, 0x60, 0x60, 0x62, 0x66, /*7860*/
11032           0x80, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9f} },
11033     {10, {0x00, 0x05, 0x08, 0x11, 0x18, 0x19, 0x1c, 0x1f, 0x60, 0x60, /*7870*/
11034           0x62, 0x66, 0x80, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9f} },
11035     {10, {0x00, 0x05, 0x08, 0x11, 0x18, 0x1a, 0x1c, 0x1f, 0x60, 0x60, /*7880*/
11036           0x62, 0x66, 0x80, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9f} },
11037     {16, {0x00, 0x05, 0x08, 0x11, 0x18, 0x1f, 0x60, 0x60, 0x62, 0x66, /*7890*/
11038           0x84, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9a, 0x9f, 0x9f,
11039           0xe0, 0xf1, 0xf4, 0xf4, 0xf6, 0xf6, 0xf8, 0xf8, 0xfa, 0xfc,
11040           0xfe, 0xff} },
11041     {12, {0x00, 0x05, 0x08, 0x11, 0x18, 0x19, 0x1b, 0x1f, 0x60, 0x60, /*7895*/
11042           0x62, 0x66, 0x80, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9a,
11043           0x9f, 0x9f, 0xe0, 0xf1} },
11044     {16, {0x00, 0x05, 0x08, 0x11, 0x18, 0x1f, 0x60, 0x60, 0x62, 0x66, /*7896*/
11045           0x84, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9a, 0x9f, 0x9f,
11046           0xe0, 0xf1, 0xf4, 0xf4, 0xf6, 0xf6, 0xf8, 0xf8, 0xfa, 0xfc,
11047           0xfe, 0xff} },
11048     {12, {0x00, 0x05, 0x08, 0x11, 0x18, 0x1f, 0x60, 0x60, 0x62, 0x66, /*7892*/
11049           0x84, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9a, 0x9c, 0x9f,
11050           0xe0, 0xf1, 0xf4, 0xfc} },
11051     {12, {0x00, 0x05, 0x08, 0x11, 0x18, 0x1f, 0x60, 0x60, 0x62, 0x66, /*7899*/
11052           0x84, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9a, 0x9c, 0x9f,
11053           0xe0, 0xf1, 0xf4, 0xfc} },
11054   };
11055   chip = p->chip & AHC_CHIPID_MASK;
11056   printk("%s at ",
11057          board_names[p->board_name_index]);
11058   switch(p->chip & ~AHC_CHIPID_MASK)
11059   {
11060     case AHC_VL:
11061       printk("VLB Slot %d.\n", p->pci_device_fn);
11062       break;
11063     case AHC_EISA:
11064       printk("EISA Slot %d.\n", p->pci_device_fn);
11065       break;
11066     case AHC_PCI:
11067     default:
11068       printk("PCI %d/%d/%d.\n", p->pci_bus, PCI_SLOT(p->pci_device_fn),
11069              PCI_FUNC(p->pci_device_fn));
11070       break;
11071   }
11072
11073   /*
11074    * the registers on the card....
11075    */
11076   printk("Card Dump:\n");
11077   k = 0;
11078   for(i=0; i<cards_ds[chip].num_ranges; i++)
11079   {
11080     for(j  = cards_ds[chip].range_val[ i * 2 ];
11081         j <= cards_ds[chip].range_val[ i * 2 + 1 ] ;
11082         j++)
11083     {
11084       printk("%02x:%02x ", j, aic_inb(p, j));
11085       if(++k == 13)
11086       {
11087         printk("\n");
11088         k=0;
11089       }
11090     }
11091   }
11092   if(k != 0)
11093     printk("\n");
11094
11095   /*
11096    * If this was an Ultra2 controller, then we just hosed the card in terms
11097    * of the QUEUE REGS.  This function is only called at init time or by
11098    * the panic_abort function, so it's safe to assume a generic init time
11099    * setting here
11100    */
11101
11102   if(p->features & AHC_QUEUE_REGS)
11103   {
11104     aic_outb(p, 0, SDSCB_QOFF);
11105     aic_outb(p, 0, SNSCB_QOFF);
11106     aic_outb(p, 0, HNSCB_QOFF);
11107   }
11108
11109 }
11110
11111 /*+F*************************************************************************
11112  * Function:
11113  *   aic7xxx_print_scratch_ram
11114  *
11115  * Description:
11116  *   Print out the scratch RAM values on the card.
11117  *-F*************************************************************************/
11118 static void
11119 aic7xxx_print_scratch_ram(struct aic7xxx_host *p)
11120 {
11121   int i, k;
11122
11123   k = 0;
11124   printk("Scratch RAM:\n");
11125   for(i = SRAM_BASE; i < SEQCTL; i++)
11126   {
11127     printk("%02x:%02x ", i, aic_inb(p, i));
11128     if(++k == 13)
11129     {
11130       printk("\n");
11131       k=0;
11132     }
11133   }
11134   if (p->features & AHC_MORE_SRAM)
11135   {
11136     for(i = TARG_OFFSET; i < 0x80; i++)
11137     {
11138       printk("%02x:%02x ", i, aic_inb(p, i));
11139       if(++k == 13)
11140       {
11141         printk("\n");
11142         k=0;
11143       }
11144     }
11145   }
11146   printk("\n");
11147 }
11148
11149
11150 #include "aic7xxx_old/aic7xxx_proc.c"
11151
11152 MODULE_LICENSE("Dual BSD/GPL");
11153 MODULE_VERSION(AIC7XXX_H_VERSION);
11154
11155
11156 static struct scsi_host_template driver_template = {
11157         .proc_info              = aic7xxx_proc_info,
11158         .detect                 = aic7xxx_detect,
11159         .release                = aic7xxx_release,
11160         .info                   = aic7xxx_info, 
11161         .queuecommand           = aic7xxx_queue,
11162         .slave_alloc            = aic7xxx_slave_alloc,
11163         .slave_configure        = aic7xxx_slave_configure,
11164         .slave_destroy          = aic7xxx_slave_destroy,
11165         .bios_param             = aic7xxx_biosparam,
11166         .eh_abort_handler       = aic7xxx_abort,
11167         .eh_device_reset_handler        = aic7xxx_bus_device_reset,
11168         .eh_host_reset_handler  = aic7xxx_reset,
11169         .can_queue              = 255,
11170         .this_id                = -1,
11171         .max_sectors            = 2048,
11172         .cmd_per_lun            = 3,
11173         .use_clustering         = ENABLE_CLUSTERING,
11174 };
11175
11176 #include "scsi_module.c"
11177
11178 /*
11179  * Overrides for Emacs so that we almost follow Linus's tabbing style.
11180  * Emacs will notice this stuff at the end of the file and automatically
11181  * adjust the settings for this buffer only.  This must remain at the end
11182  * of the file.
11183  * ---------------------------------------------------------------------------
11184  * Local variables:
11185  * c-indent-level: 2
11186  * c-brace-imaginary-offset: 0
11187  * c-brace-offset: -2
11188  * c-argdecl-indent: 2
11189  * c-label-offset: -2
11190  * c-continued-statement-offset: 2
11191  * c-continued-brace-offset: 0
11192  * indent-tabs-mode: nil
11193  * tab-width: 8
11194  * End:
11195  */