Merge branches 'release', 'asus', 'sony-laptop' and 'thinkpad' into release
[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         scsi_dma_unmap(cmd);
2694
2695   if (scb->flags & SCB_SENSE)
2696   {
2697     pci_unmap_single(p->pdev,
2698                      le32_to_cpu(scb->sg_list[0].address),
2699                      SCSI_SENSE_BUFFERSIZE,
2700                      PCI_DMA_FROMDEVICE);
2701   }
2702   if (scb->flags & SCB_RECOVERY_SCB)
2703   {
2704     p->flags &= ~AHC_ABORT_PENDING;
2705   }
2706   if (scb->flags & (SCB_RESET|SCB_ABORT))
2707   {
2708     cmd->result |= (DID_RESET << 16);
2709   }
2710
2711   if ((scb->flags & SCB_MSGOUT_BITS) != 0)
2712   {
2713     unsigned short mask;
2714     int message_error = FALSE;
2715
2716     mask = 0x01 << tindex;
2717  
2718     /*
2719      * Check to see if we get an invalid message or a message error
2720      * after failing to negotiate a wide or sync transfer message.
2721      */
2722     if ((scb->flags & SCB_SENSE) && 
2723           ((scb->cmd->sense_buffer[12] == 0x43) ||  /* INVALID_MESSAGE */
2724           (scb->cmd->sense_buffer[12] == 0x49))) /* MESSAGE_ERROR  */
2725     {
2726       message_error = TRUE;
2727     }
2728
2729     if (scb->flags & SCB_MSGOUT_WDTR)
2730     {
2731       if (message_error)
2732       {
2733         if ( (aic7xxx_verbose & VERBOSE_NEGOTIATION2) &&
2734              (aic_dev->flags & DEVICE_PRINT_DTR) )
2735         {
2736           printk(INFO_LEAD "Device failed to complete Wide Negotiation "
2737             "processing and\n", p->host_no, CTL_OF_SCB(scb));
2738           printk(INFO_LEAD "returned a sense error code for invalid message, "
2739             "disabling future\n", p->host_no, CTL_OF_SCB(scb));
2740           printk(INFO_LEAD "Wide negotiation to this device.\n", p->host_no,
2741             CTL_OF_SCB(scb));
2742         }
2743         aic_dev->needwdtr = aic_dev->needwdtr_copy = 0;
2744       }
2745     }
2746     if (scb->flags & SCB_MSGOUT_SDTR)
2747     {
2748       if (message_error)
2749       {
2750         if ( (aic7xxx_verbose & VERBOSE_NEGOTIATION2) &&
2751              (aic_dev->flags & DEVICE_PRINT_DTR) )
2752         {
2753           printk(INFO_LEAD "Device failed to complete Sync Negotiation "
2754             "processing and\n", p->host_no, CTL_OF_SCB(scb));
2755           printk(INFO_LEAD "returned a sense error code for invalid message, "
2756             "disabling future\n", p->host_no, CTL_OF_SCB(scb));
2757           printk(INFO_LEAD "Sync negotiation to this device.\n", p->host_no,
2758             CTL_OF_SCB(scb));
2759           aic_dev->flags &= ~DEVICE_PRINT_DTR;
2760         }
2761         aic_dev->needsdtr = aic_dev->needsdtr_copy = 0;
2762       }
2763     }
2764     if (scb->flags & SCB_MSGOUT_PPR)
2765     {
2766       if(message_error)
2767       {
2768         if ( (aic7xxx_verbose & VERBOSE_NEGOTIATION2) &&
2769              (aic_dev->flags & DEVICE_PRINT_DTR) )
2770         {
2771           printk(INFO_LEAD "Device failed to complete Parallel Protocol "
2772             "Request processing and\n", p->host_no, CTL_OF_SCB(scb));
2773           printk(INFO_LEAD "returned a sense error code for invalid message, "
2774             "disabling future\n", p->host_no, CTL_OF_SCB(scb));
2775           printk(INFO_LEAD "Parallel Protocol Request negotiation to this "
2776             "device.\n", p->host_no, CTL_OF_SCB(scb));
2777         }
2778         /*
2779          * Disable PPR negotiation and revert back to WDTR and SDTR setup
2780          */
2781         aic_dev->needppr = aic_dev->needppr_copy = 0;
2782         aic_dev->needsdtr = aic_dev->needsdtr_copy = 1;
2783         aic_dev->needwdtr = aic_dev->needwdtr_copy = 1;
2784       }
2785     }
2786   }
2787
2788   queue_depth = aic_dev->temp_q_depth;
2789   if (queue_depth >= aic_dev->active_cmds)
2790   {
2791     scbp = scbq_remove_head(&aic_dev->delayed_scbs);
2792     if (scbp)
2793     {
2794       if (queue_depth == 1)
2795       {
2796         /*
2797          * Give extra preference to untagged devices, such as CD-R devices
2798          * This makes it more likely that a drive *won't* stuff up while
2799          * waiting on data at a critical time, such as CD-R writing and
2800          * audio CD ripping operations.  Should also benefit tape drives.
2801          */
2802         scbq_insert_head(&p->waiting_scbs, scbp);
2803       }
2804       else
2805       {
2806         scbq_insert_tail(&p->waiting_scbs, scbp);
2807       }
2808 #ifdef AIC7XXX_VERBOSE_DEBUGGING
2809       if (aic7xxx_verbose > 0xffff)
2810         printk(INFO_LEAD "Moving SCB from delayed to waiting queue.\n",
2811                p->host_no, CTL_OF_SCB(scbp));
2812 #endif
2813       if (queue_depth > aic_dev->active_cmds)
2814       {
2815         scbp = scbq_remove_head(&aic_dev->delayed_scbs);
2816         if (scbp)
2817           scbq_insert_tail(&p->waiting_scbs, scbp);
2818       }
2819     }
2820   }
2821   if (!(scb->tag_action))
2822   {
2823     aic7xxx_index_busy_target(p, scb->hscb->target_channel_lun,
2824                               /* unbusy */ TRUE);
2825     if (cmd->device->simple_tags)
2826     {
2827       aic_dev->temp_q_depth = aic_dev->max_q_depth;
2828     }
2829   }
2830   if(scb->flags & SCB_DTR_SCB)
2831   {
2832     aic_dev->dtr_pending = 0;
2833   }
2834   aic_dev->active_cmds--;
2835   p->activescbs--;
2836
2837   if ((scb->sg_length >= 512) && (((cmd->result >> 16) & 0xf) == DID_OK))
2838   {
2839     long *ptr;
2840     int x, i;
2841
2842
2843     if (rq_data_dir(cmd->request) == WRITE)
2844     {
2845       aic_dev->w_total++;
2846       ptr = aic_dev->w_bins;
2847     }
2848     else
2849     {
2850       aic_dev->r_total++;
2851       ptr = aic_dev->r_bins;
2852     }
2853     if(cmd->device->simple_tags && cmd->request->cmd_flags & REQ_HARDBARRIER)
2854     {
2855       aic_dev->barrier_total++;
2856       if(scb->tag_action == MSG_ORDERED_Q_TAG)
2857         aic_dev->ordered_total++;
2858     }
2859     x = scb->sg_length;
2860     x >>= 10;
2861     for(i=0; i<6; i++)
2862     {
2863       x >>= 2;
2864       if(!x) {
2865         ptr[i]++;
2866         break;
2867       }
2868     }
2869     if(i == 6 && x)
2870       ptr[5]++;
2871   }
2872   aic7xxx_free_scb(p, scb);
2873   aic7xxx_queue_cmd_complete(p, cmd);
2874
2875 }
2876
2877 /*+F*************************************************************************
2878  * Function:
2879  *   aic7xxx_run_done_queue
2880  *
2881  * Description:
2882  *   Calls the aic7xxx_done() for the scsi_cmnd of each scb in the
2883  *   aborted list, and adds each scb to the free list.  If complete
2884  *   is TRUE, we also process the commands complete list.
2885  *-F*************************************************************************/
2886 static void
2887 aic7xxx_run_done_queue(struct aic7xxx_host *p, /*complete*/ int complete)
2888 {
2889   struct aic7xxx_scb *scb;
2890   int i, found = 0;
2891
2892   for (i = 0; i < p->scb_data->numscbs; i++)
2893   {
2894     scb = p->scb_data->scb_array[i];
2895     if (scb->flags & SCB_QUEUED_FOR_DONE)
2896     {
2897       if (scb->flags & SCB_QUEUE_FULL)
2898       {
2899         scb->cmd->result = QUEUE_FULL << 1;
2900       }
2901       else
2902       {
2903         if (aic7xxx_verbose & (VERBOSE_ABORT_PROCESS | VERBOSE_RESET_PROCESS))
2904           printk(INFO_LEAD "Aborting scb %d\n",
2905                p->host_no, CTL_OF_SCB(scb), scb->hscb->tag);
2906         /*
2907          * Clear any residual information since the normal aic7xxx_done() path
2908          * doesn't touch the residuals.
2909          */
2910         scb->hscb->residual_SG_segment_count = 0;
2911         scb->hscb->residual_data_count[0] = 0;
2912         scb->hscb->residual_data_count[1] = 0;
2913         scb->hscb->residual_data_count[2] = 0;
2914       }
2915       found++;
2916       aic7xxx_done(p, scb);
2917     }
2918   }
2919   if (aic7xxx_verbose & (VERBOSE_ABORT_RETURN | VERBOSE_RESET_RETURN))
2920   {
2921     printk(INFO_LEAD "%d commands found and queued for "
2922         "completion.\n", p->host_no, -1, -1, -1, found);
2923   }
2924   if (complete)
2925   {
2926     aic7xxx_done_cmds_complete(p);
2927   }
2928 }
2929
2930 /*+F*************************************************************************
2931  * Function:
2932  *   aic7xxx_abort_waiting_scb
2933  *
2934  * Description:
2935  *   Manipulate the waiting for selection list and return the
2936  *   scb that follows the one that we remove.
2937  *-F*************************************************************************/
2938 static unsigned char
2939 aic7xxx_abort_waiting_scb(struct aic7xxx_host *p, struct aic7xxx_scb *scb,
2940     unsigned char scbpos, unsigned char prev)
2941 {
2942   unsigned char curscb, next;
2943
2944   /*
2945    * Select the SCB we want to abort and pull the next pointer out of it.
2946    */
2947   curscb = aic_inb(p, SCBPTR);
2948   aic_outb(p, scbpos, SCBPTR);
2949   next = aic_inb(p, SCB_NEXT);
2950
2951   aic7xxx_add_curscb_to_free_list(p);
2952
2953   /*
2954    * Update the waiting list
2955    */
2956   if (prev == SCB_LIST_NULL)
2957   {
2958     /*
2959      * First in the list
2960      */
2961     aic_outb(p, next, WAITING_SCBH);
2962   }
2963   else
2964   {
2965     /*
2966      * Select the scb that pointed to us and update its next pointer.
2967      */
2968     aic_outb(p, prev, SCBPTR);
2969     aic_outb(p, next, SCB_NEXT);
2970   }
2971   /*
2972    * Point us back at the original scb position and inform the SCSI
2973    * system that the command has been aborted.
2974    */
2975   aic_outb(p, curscb, SCBPTR);
2976   return (next);
2977 }
2978
2979 /*+F*************************************************************************
2980  * Function:
2981  *   aic7xxx_search_qinfifo
2982  *
2983  * Description:
2984  *   Search the queue-in FIFO for matching SCBs and conditionally
2985  *   requeue.  Returns the number of matching SCBs.
2986  *-F*************************************************************************/
2987 static int
2988 aic7xxx_search_qinfifo(struct aic7xxx_host *p, int target, int channel,
2989     int lun, unsigned char tag, int flags, int requeue,
2990     volatile scb_queue_type *queue)
2991 {
2992   int      found;
2993   unsigned char qinpos, qintail;
2994   struct aic7xxx_scb *scbp;
2995
2996   found = 0;
2997   qinpos = aic_inb(p, QINPOS);
2998   qintail = p->qinfifonext;
2999
3000   p->qinfifonext = qinpos;
3001
3002   while (qinpos != qintail)
3003   {
3004     scbp = p->scb_data->scb_array[p->qinfifo[qinpos++]];
3005     if (aic7xxx_match_scb(p, scbp, target, channel, lun, tag))
3006     {
3007        /*
3008         * We found an scb that needs to be removed.
3009         */
3010        if (requeue && (queue != NULL))
3011        {
3012          if (scbp->flags & SCB_WAITINGQ)
3013          {
3014            scbq_remove(queue, scbp);
3015            scbq_remove(&p->waiting_scbs, scbp);
3016            scbq_remove(&AIC_DEV(scbp->cmd)->delayed_scbs, scbp);
3017            AIC_DEV(scbp->cmd)->active_cmds++;
3018            p->activescbs++;
3019          }
3020          scbq_insert_tail(queue, scbp);
3021          AIC_DEV(scbp->cmd)->active_cmds--;
3022          p->activescbs--;
3023          scbp->flags |= SCB_WAITINGQ;
3024          if ( !(scbp->tag_action & TAG_ENB) )
3025          {
3026            aic7xxx_index_busy_target(p, scbp->hscb->target_channel_lun,
3027              TRUE);
3028          }
3029        }
3030        else if (requeue)
3031        {
3032          p->qinfifo[p->qinfifonext++] = scbp->hscb->tag;
3033        }
3034        else
3035        {
3036         /*
3037          * Preserve any SCB_RECOVERY_SCB flags on this scb then set the
3038          * flags we were called with, presumeably so aic7xxx_run_done_queue
3039          * can find this scb
3040          */
3041          scbp->flags = flags | (scbp->flags & SCB_RECOVERY_SCB);
3042          if (aic7xxx_index_busy_target(p, scbp->hscb->target_channel_lun,
3043                                        FALSE) == scbp->hscb->tag)
3044          {
3045            aic7xxx_index_busy_target(p, scbp->hscb->target_channel_lun,
3046              TRUE);
3047          }
3048        }
3049        found++;
3050     }
3051     else
3052     {
3053       p->qinfifo[p->qinfifonext++] = scbp->hscb->tag;
3054     }
3055   }
3056   /*
3057    * Now that we've done the work, clear out any left over commands in the
3058    * qinfifo and update the KERNEL_QINPOS down on the card.
3059    *
3060    *  NOTE: This routine expect the sequencer to already be paused when
3061    *        it is run....make sure it's that way!
3062    */
3063   qinpos = p->qinfifonext;
3064   while(qinpos != qintail)
3065   {
3066     p->qinfifo[qinpos++] = SCB_LIST_NULL;
3067   }
3068   if (p->features & AHC_QUEUE_REGS)
3069     aic_outb(p, p->qinfifonext, HNSCB_QOFF);
3070   else
3071     aic_outb(p, p->qinfifonext, KERNEL_QINPOS);
3072
3073   return (found);
3074 }
3075
3076 /*+F*************************************************************************
3077  * Function:
3078  *   aic7xxx_scb_on_qoutfifo
3079  *
3080  * Description:
3081  *   Is the scb that was passed to us currently on the qoutfifo?
3082  *-F*************************************************************************/
3083 static int
3084 aic7xxx_scb_on_qoutfifo(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
3085 {
3086   int i=0;
3087
3088   while(p->qoutfifo[(p->qoutfifonext + i) & 0xff ] != SCB_LIST_NULL)
3089   {
3090     if(p->qoutfifo[(p->qoutfifonext + i) & 0xff ] == scb->hscb->tag)
3091       return TRUE;
3092     else
3093       i++;
3094   }
3095   return FALSE;
3096 }
3097
3098
3099 /*+F*************************************************************************
3100  * Function:
3101  *   aic7xxx_reset_device
3102  *
3103  * Description:
3104  *   The device at the given target/channel has been reset.  Abort
3105  *   all active and queued scbs for that target/channel.  This function
3106  *   need not worry about linked next pointers because if was a MSG_ABORT_TAG
3107  *   then we had a tagged command (no linked next), if it was MSG_ABORT or
3108  *   MSG_BUS_DEV_RESET then the device won't know about any commands any more
3109  *   and no busy commands will exist, and if it was a bus reset, then nothing
3110  *   knows about any linked next commands any more.  In all cases, we don't
3111  *   need to worry about the linked next or busy scb, we just need to clear
3112  *   them.
3113  *-F*************************************************************************/
3114 static void
3115 aic7xxx_reset_device(struct aic7xxx_host *p, int target, int channel,
3116                      int lun, unsigned char tag)
3117 {
3118   struct aic7xxx_scb *scbp, *prev_scbp;
3119   struct scsi_device *sd;
3120   unsigned char active_scb, tcl, scb_tag;
3121   int i = 0, init_lists = FALSE;
3122   struct aic_dev_data *aic_dev;
3123
3124   /*
3125    * Restore this when we're done
3126    */
3127   active_scb = aic_inb(p, SCBPTR);
3128   scb_tag = aic_inb(p, SCB_TAG);
3129
3130   if (aic7xxx_verbose & (VERBOSE_RESET_PROCESS | VERBOSE_ABORT_PROCESS))
3131   {
3132     printk(INFO_LEAD "Reset device, hardware_scb %d,\n",
3133          p->host_no, channel, target, lun, active_scb);
3134     printk(INFO_LEAD "Current scb %d, SEQADDR 0x%x, LASTPHASE "
3135            "0x%x\n",
3136          p->host_no, channel, target, lun, scb_tag,
3137          aic_inb(p, SEQADDR0) | (aic_inb(p, SEQADDR1) << 8),
3138          aic_inb(p, LASTPHASE));
3139     printk(INFO_LEAD "SG_CACHEPTR 0x%x, SG_COUNT %d, SCSISIGI 0x%x\n",
3140          p->host_no, channel, target, lun,
3141          (p->features & AHC_ULTRA2) ?  aic_inb(p, SG_CACHEPTR) : 0,
3142          aic_inb(p, SG_COUNT), aic_inb(p, SCSISIGI));
3143     printk(INFO_LEAD "SSTAT0 0x%x, SSTAT1 0x%x, SSTAT2 0x%x\n",
3144          p->host_no, channel, target, lun, aic_inb(p, SSTAT0),
3145          aic_inb(p, SSTAT1), aic_inb(p, SSTAT2));
3146   }
3147
3148   /*
3149    * Deal with the busy target and linked next issues.
3150    */
3151   list_for_each_entry(aic_dev, &p->aic_devs, list)
3152   {
3153     if (aic7xxx_verbose & (VERBOSE_RESET_PROCESS | VERBOSE_ABORT_PROCESS))
3154       printk(INFO_LEAD "processing aic_dev %p\n", p->host_no, channel, target,
3155                     lun, aic_dev);
3156     sd = aic_dev->SDptr;
3157
3158     if((target != ALL_TARGETS && target != sd->id) ||
3159        (channel != ALL_CHANNELS && channel != sd->channel))
3160       continue;
3161     if (aic7xxx_verbose & (VERBOSE_ABORT_PROCESS | VERBOSE_RESET_PROCESS))
3162         printk(INFO_LEAD "Cleaning up status information "
3163           "and delayed_scbs.\n", p->host_no, sd->channel, sd->id, sd->lun);
3164     aic_dev->flags &= ~BUS_DEVICE_RESET_PENDING;
3165     if ( tag == SCB_LIST_NULL )
3166     {
3167       aic_dev->dtr_pending = 0;
3168       aic_dev->needppr = aic_dev->needppr_copy;
3169       aic_dev->needsdtr = aic_dev->needsdtr_copy;
3170       aic_dev->needwdtr = aic_dev->needwdtr_copy;
3171       aic_dev->flags = DEVICE_PRINT_DTR;
3172       aic_dev->temp_q_depth = aic_dev->max_q_depth;
3173     }
3174     tcl = (sd->id << 4) | (sd->channel << 3) | sd->lun;
3175     if ( (aic7xxx_index_busy_target(p, tcl, FALSE) == tag) ||
3176          (tag == SCB_LIST_NULL) )
3177       aic7xxx_index_busy_target(p, tcl, /* unbusy */ TRUE);
3178     prev_scbp = NULL; 
3179     scbp = aic_dev->delayed_scbs.head;
3180     while (scbp != NULL)
3181     {
3182       prev_scbp = scbp;
3183       scbp = scbp->q_next;
3184       if (aic7xxx_match_scb(p, prev_scbp, target, channel, lun, tag))
3185       {
3186         scbq_remove(&aic_dev->delayed_scbs, prev_scbp);
3187         if (prev_scbp->flags & SCB_WAITINGQ)
3188         {
3189           aic_dev->active_cmds++;
3190           p->activescbs++;
3191         }
3192         prev_scbp->flags &= ~(SCB_ACTIVE | SCB_WAITINGQ);
3193         prev_scbp->flags |= SCB_RESET | SCB_QUEUED_FOR_DONE;
3194       }
3195     }
3196   }
3197
3198   if (aic7xxx_verbose & (VERBOSE_ABORT_PROCESS | VERBOSE_RESET_PROCESS))
3199     printk(INFO_LEAD "Cleaning QINFIFO.\n", p->host_no, channel, target, lun );
3200   aic7xxx_search_qinfifo(p, target, channel, lun, tag,
3201       SCB_RESET | SCB_QUEUED_FOR_DONE, /* requeue */ FALSE, NULL);
3202
3203 /*
3204  *  Search the waiting_scbs queue for matches, this catches any SCB_QUEUED
3205  *  ABORT/RESET commands.
3206  */
3207   if (aic7xxx_verbose & (VERBOSE_ABORT_PROCESS | VERBOSE_RESET_PROCESS))
3208     printk(INFO_LEAD "Cleaning waiting_scbs.\n", p->host_no, channel,
3209       target, lun );
3210   {
3211     struct aic7xxx_scb *scbp, *prev_scbp;
3212
3213     prev_scbp = NULL; 
3214     scbp = p->waiting_scbs.head;
3215     while (scbp != NULL)
3216     {
3217       prev_scbp = scbp;
3218       scbp = scbp->q_next;
3219       if (aic7xxx_match_scb(p, prev_scbp, target, channel, lun, tag))
3220       {
3221         scbq_remove(&p->waiting_scbs, prev_scbp);
3222         if (prev_scbp->flags & SCB_WAITINGQ)
3223         {
3224           AIC_DEV(prev_scbp->cmd)->active_cmds++;
3225           p->activescbs++;
3226         }
3227         prev_scbp->flags &= ~(SCB_ACTIVE | SCB_WAITINGQ);
3228         prev_scbp->flags |= SCB_RESET | SCB_QUEUED_FOR_DONE;
3229       }
3230     }
3231   }
3232
3233
3234   /*
3235    * Search waiting for selection list.
3236    */
3237   if (aic7xxx_verbose & (VERBOSE_ABORT_PROCESS | VERBOSE_RESET_PROCESS))
3238     printk(INFO_LEAD "Cleaning waiting for selection "
3239       "list.\n", p->host_no, channel, target, lun);
3240   {
3241     unsigned char next, prev, scb_index;
3242
3243     next = aic_inb(p, WAITING_SCBH);  /* Start at head of list. */
3244     prev = SCB_LIST_NULL;
3245     while (next != SCB_LIST_NULL)
3246     {
3247       aic_outb(p, next, SCBPTR);
3248       scb_index = aic_inb(p, SCB_TAG);
3249       if (scb_index >= p->scb_data->numscbs)
3250       {
3251        /*
3252         * No aic7xxx_verbose check here.....we want to see this since it
3253         * means either the kernel driver or the sequencer screwed things up
3254         */
3255         printk(WARN_LEAD "Waiting List inconsistency; SCB index=%d, "
3256           "numscbs=%d\n", p->host_no, channel, target, lun, scb_index,
3257           p->scb_data->numscbs);
3258         next = aic_inb(p, SCB_NEXT);
3259         aic7xxx_add_curscb_to_free_list(p);
3260       }
3261       else
3262       {
3263         scbp = p->scb_data->scb_array[scb_index];
3264         if (aic7xxx_match_scb(p, scbp, target, channel, lun, tag))
3265         {
3266           next = aic7xxx_abort_waiting_scb(p, scbp, next, prev);
3267           if (scbp->flags & SCB_WAITINGQ)
3268           {
3269             AIC_DEV(scbp->cmd)->active_cmds++;
3270             p->activescbs++;
3271           }
3272           scbp->flags &= ~(SCB_ACTIVE | SCB_WAITINGQ);
3273           scbp->flags |= SCB_RESET | SCB_QUEUED_FOR_DONE;
3274           if (prev == SCB_LIST_NULL)
3275           {
3276             /*
3277              * This is either the first scb on the waiting list, or we
3278              * have already yanked the first and haven't left any behind.
3279              * Either way, we need to turn off the selection hardware if
3280              * it isn't already off.
3281              */
3282             aic_outb(p, aic_inb(p, SCSISEQ) & ~ENSELO, SCSISEQ);
3283             aic_outb(p, CLRSELTIMEO, CLRSINT1);
3284           }
3285         }
3286         else
3287         {
3288           prev = next;
3289           next = aic_inb(p, SCB_NEXT);
3290         }
3291       }
3292     }
3293   }
3294
3295   /*
3296    * Go through disconnected list and remove any entries we have queued
3297    * for completion, zeroing their control byte too.
3298    */
3299   if (aic7xxx_verbose & (VERBOSE_ABORT_PROCESS | VERBOSE_RESET_PROCESS))
3300     printk(INFO_LEAD "Cleaning disconnected scbs "
3301       "list.\n", p->host_no, channel, target, lun);
3302   if (p->flags & AHC_PAGESCBS)
3303   {
3304     unsigned char next, prev, scb_index;
3305
3306     next = aic_inb(p, DISCONNECTED_SCBH);
3307     prev = SCB_LIST_NULL;
3308     while (next != SCB_LIST_NULL)
3309     {
3310       aic_outb(p, next, SCBPTR);
3311       scb_index = aic_inb(p, SCB_TAG);
3312       if (scb_index > p->scb_data->numscbs)
3313       {
3314         printk(WARN_LEAD "Disconnected List inconsistency; SCB index=%d, "
3315           "numscbs=%d\n", p->host_no, channel, target, lun, scb_index,
3316           p->scb_data->numscbs);
3317         next = aic7xxx_rem_scb_from_disc_list(p, next, prev);
3318       }
3319       else
3320       {
3321         scbp = p->scb_data->scb_array[scb_index];
3322         if (aic7xxx_match_scb(p, scbp, target, channel, lun, tag))
3323         {
3324           next = aic7xxx_rem_scb_from_disc_list(p, next, prev);
3325           if (scbp->flags & SCB_WAITINGQ)
3326           {
3327             AIC_DEV(scbp->cmd)->active_cmds++;
3328             p->activescbs++;
3329           }
3330           scbp->flags &= ~(SCB_ACTIVE | SCB_WAITINGQ);
3331           scbp->flags |= SCB_RESET | SCB_QUEUED_FOR_DONE;
3332           scbp->hscb->control = 0;
3333         }
3334         else
3335         {
3336           prev = next;
3337           next = aic_inb(p, SCB_NEXT);
3338         }
3339       }
3340     }
3341   }
3342
3343   /*
3344    * Walk the free list making sure no entries on the free list have
3345    * a valid SCB_TAG value or SCB_CONTROL byte.
3346    */
3347   if (p->flags & AHC_PAGESCBS)
3348   {
3349     unsigned char next;
3350
3351     next = aic_inb(p, FREE_SCBH);
3352     while (next != SCB_LIST_NULL)
3353     {
3354       aic_outb(p, next, SCBPTR);
3355       if (aic_inb(p, SCB_TAG) < p->scb_data->numscbs)
3356       {
3357         printk(WARN_LEAD "Free list inconsistency!.\n", p->host_no, channel,
3358           target, lun);
3359         init_lists = TRUE;
3360         next = SCB_LIST_NULL;
3361       }
3362       else
3363       {
3364         aic_outb(p, SCB_LIST_NULL, SCB_TAG);
3365         aic_outb(p, 0, SCB_CONTROL);
3366         next = aic_inb(p, SCB_NEXT);
3367       }
3368     }
3369   }
3370
3371   /*
3372    * Go through the hardware SCB array looking for commands that
3373    * were active but not on any list.
3374    */
3375   if (init_lists)
3376   {
3377     aic_outb(p, SCB_LIST_NULL, FREE_SCBH);
3378     aic_outb(p, SCB_LIST_NULL, WAITING_SCBH);
3379     aic_outb(p, SCB_LIST_NULL, DISCONNECTED_SCBH);
3380   }
3381   for (i = p->scb_data->maxhscbs - 1; i >= 0; i--)
3382   {
3383     unsigned char scbid;
3384
3385     aic_outb(p, i, SCBPTR);
3386     if (init_lists)
3387     {
3388       aic_outb(p, SCB_LIST_NULL, SCB_TAG);
3389       aic_outb(p, SCB_LIST_NULL, SCB_NEXT);
3390       aic_outb(p, 0, SCB_CONTROL);
3391       aic7xxx_add_curscb_to_free_list(p);
3392     }
3393     else
3394     {
3395       scbid = aic_inb(p, SCB_TAG);
3396       if (scbid < p->scb_data->numscbs)
3397       {
3398         scbp = p->scb_data->scb_array[scbid];
3399         if (aic7xxx_match_scb(p, scbp, target, channel, lun, tag))
3400         {
3401           aic_outb(p, 0, SCB_CONTROL);
3402           aic_outb(p, SCB_LIST_NULL, SCB_TAG);
3403           aic7xxx_add_curscb_to_free_list(p);
3404         }
3405       }
3406     }
3407   }
3408
3409   /*
3410    * Go through the entire SCB array now and look for commands for
3411    * for this target that are stillactive.  These are other (most likely
3412    * tagged) commands that were disconnected when the reset occurred.
3413    * Any commands we find here we know this about, it wasn't on any queue,
3414    * it wasn't in the qinfifo, it wasn't in the disconnected or waiting
3415    * lists, so it really must have been a paged out SCB.  In that case,
3416    * we shouldn't need to bother with updating any counters, just mark
3417    * the correct flags and go on.
3418    */
3419   for (i = 0; i < p->scb_data->numscbs; i++)
3420   {
3421     scbp = p->scb_data->scb_array[i];
3422     if ((scbp->flags & SCB_ACTIVE) &&
3423         aic7xxx_match_scb(p, scbp, target, channel, lun, tag) &&
3424         !aic7xxx_scb_on_qoutfifo(p, scbp))
3425     {
3426       if (scbp->flags & SCB_WAITINGQ)
3427       {
3428         scbq_remove(&p->waiting_scbs, scbp);
3429         scbq_remove(&AIC_DEV(scbp->cmd)->delayed_scbs, scbp);
3430         AIC_DEV(scbp->cmd)->active_cmds++;
3431         p->activescbs++;
3432       }
3433       scbp->flags |= SCB_RESET | SCB_QUEUED_FOR_DONE;
3434       scbp->flags &= ~(SCB_ACTIVE | SCB_WAITINGQ);
3435     }
3436   }
3437
3438   aic_outb(p, active_scb, SCBPTR);
3439 }
3440
3441
3442 /*+F*************************************************************************
3443  * Function:
3444  *   aic7xxx_clear_intstat
3445  *
3446  * Description:
3447  *   Clears the interrupt status.
3448  *-F*************************************************************************/
3449 static void
3450 aic7xxx_clear_intstat(struct aic7xxx_host *p)
3451 {
3452   /* Clear any interrupt conditions this may have caused. */
3453   aic_outb(p, CLRSELDO | CLRSELDI | CLRSELINGO, CLRSINT0);
3454   aic_outb(p, CLRSELTIMEO | CLRATNO | CLRSCSIRSTI | CLRBUSFREE | CLRSCSIPERR |
3455        CLRPHASECHG | CLRREQINIT, CLRSINT1);
3456   aic_outb(p, CLRSCSIINT | CLRSEQINT | CLRBRKADRINT | CLRPARERR, CLRINT);
3457 }
3458
3459 /*+F*************************************************************************
3460  * Function:
3461  *   aic7xxx_reset_current_bus
3462  *
3463  * Description:
3464  *   Reset the current SCSI bus.
3465  *-F*************************************************************************/
3466 static void
3467 aic7xxx_reset_current_bus(struct aic7xxx_host *p)
3468 {
3469
3470   /* Disable reset interrupts. */
3471   aic_outb(p, aic_inb(p, SIMODE1) & ~ENSCSIRST, SIMODE1);
3472
3473   /* Turn off the bus' current operations, after all, we shouldn't have any
3474    * valid commands left to cause a RSELI and SELO once we've tossed the
3475    * bus away with this reset, so we might as well shut down the sequencer
3476    * until the bus is restarted as oppossed to saving the current settings
3477    * and restoring them (which makes no sense to me). */
3478
3479   /* Turn on the bus reset. */
3480   aic_outb(p, aic_inb(p, SCSISEQ) | SCSIRSTO, SCSISEQ);
3481   while ( (aic_inb(p, SCSISEQ) & SCSIRSTO) == 0)
3482     mdelay(5);
3483
3484   /*
3485    * Some of the new Ultra2 chipsets need a longer delay after a chip
3486    * reset than just the init setup creates, so we have to delay here
3487    * before we go into a reset in order to make the chips happy.
3488    */
3489   if (p->features & AHC_ULTRA2)
3490     mdelay(250);
3491   else
3492     mdelay(50);
3493
3494   /* Turn off the bus reset. */
3495   aic_outb(p, 0, SCSISEQ);
3496   mdelay(10);
3497
3498   aic7xxx_clear_intstat(p);
3499   /* Re-enable reset interrupts. */
3500   aic_outb(p, aic_inb(p, SIMODE1) | ENSCSIRST, SIMODE1);
3501
3502 }
3503
3504 /*+F*************************************************************************
3505  * Function:
3506  *   aic7xxx_reset_channel
3507  *
3508  * Description:
3509  *   Reset the channel.
3510  *-F*************************************************************************/
3511 static void
3512 aic7xxx_reset_channel(struct aic7xxx_host *p, int channel, int initiate_reset)
3513 {
3514   unsigned long offset_min, offset_max;
3515   unsigned char sblkctl;
3516   int cur_channel;
3517
3518   if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
3519     printk(INFO_LEAD "Reset channel called, %s initiate reset.\n",
3520       p->host_no, channel, -1, -1, (initiate_reset==TRUE) ? "will" : "won't" );
3521
3522
3523   if (channel == 1)
3524   {
3525     offset_min = 8;
3526     offset_max = 16;
3527   }
3528   else
3529   {
3530     if (p->features & AHC_TWIN)
3531     {
3532       /* Channel A */
3533       offset_min = 0;
3534       offset_max = 8;
3535     }
3536     else
3537     {
3538       offset_min = 0;
3539       if (p->features & AHC_WIDE)
3540       {
3541         offset_max = 16;
3542       }
3543       else
3544       {
3545         offset_max = 8;
3546       }
3547     }
3548   }
3549
3550   while (offset_min < offset_max)
3551   {
3552     /*
3553      * Revert to async/narrow transfers until we renegotiate.
3554      */
3555     aic_outb(p, 0, TARG_SCSIRATE + offset_min);
3556     if (p->features & AHC_ULTRA2)
3557     {
3558       aic_outb(p, 0, TARG_OFFSET + offset_min);
3559     }
3560     offset_min++;
3561   }
3562
3563   /*
3564    * Reset the bus and unpause/restart the controller
3565    */
3566   sblkctl = aic_inb(p, SBLKCTL);
3567   if ( (p->chip & AHC_CHIPID_MASK) == AHC_AIC7770 )
3568     cur_channel = (sblkctl & SELBUSB) >> 3;
3569   else
3570     cur_channel = 0;
3571   if ( (cur_channel != channel) && (p->features & AHC_TWIN) )
3572   {
3573     /*
3574      * Case 1: Command for another bus is active
3575      */
3576     if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
3577       printk(INFO_LEAD "Stealthily resetting idle channel.\n", p->host_no,
3578         channel, -1, -1);
3579     /*
3580      * Stealthily reset the other bus without upsetting the current bus.
3581      */
3582     aic_outb(p, sblkctl ^ SELBUSB, SBLKCTL);
3583     aic_outb(p, aic_inb(p, SIMODE1) & ~ENBUSFREE, SIMODE1);
3584     if (initiate_reset)
3585     {
3586       aic7xxx_reset_current_bus(p);
3587     }
3588     aic_outb(p, aic_inb(p, SCSISEQ) & (ENSELI|ENRSELI|ENAUTOATNP), SCSISEQ);
3589     aic7xxx_clear_intstat(p);
3590     aic_outb(p, sblkctl, SBLKCTL);
3591   }
3592   else
3593   {
3594     /*
3595      * Case 2: A command from this bus is active or we're idle.
3596      */
3597     if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
3598       printk(INFO_LEAD "Resetting currently active channel.\n", p->host_no,
3599         channel, -1, -1);
3600     aic_outb(p, aic_inb(p, SIMODE1) & ~(ENBUSFREE|ENREQINIT),
3601       SIMODE1);
3602     p->flags &= ~AHC_HANDLING_REQINITS;
3603     p->msg_type = MSG_TYPE_NONE;
3604     p->msg_len = 0;
3605     if (initiate_reset)
3606     {
3607       aic7xxx_reset_current_bus(p);
3608     }
3609     aic_outb(p, aic_inb(p, SCSISEQ) & (ENSELI|ENRSELI|ENAUTOATNP), SCSISEQ);
3610     aic7xxx_clear_intstat(p);
3611   }
3612   if (aic7xxx_verbose & VERBOSE_RESET_RETURN)
3613     printk(INFO_LEAD "Channel reset\n", p->host_no, channel, -1, -1);
3614   /*
3615    * Clean up all the state information for the pending transactions
3616    * on this bus.
3617    */
3618   aic7xxx_reset_device(p, ALL_TARGETS, channel, ALL_LUNS, SCB_LIST_NULL);
3619
3620   if ( !(p->features & AHC_TWIN) )
3621   {
3622     restart_sequencer(p);
3623   }
3624
3625   return;
3626 }
3627
3628 /*+F*************************************************************************
3629  * Function:
3630  *   aic7xxx_run_waiting_queues
3631  *
3632  * Description:
3633  *   Scan the awaiting_scbs queue downloading and starting as many
3634  *   scbs as we can.
3635  *-F*************************************************************************/
3636 static void
3637 aic7xxx_run_waiting_queues(struct aic7xxx_host *p)
3638 {
3639   struct aic7xxx_scb *scb;
3640   struct aic_dev_data *aic_dev;
3641   int sent;
3642
3643
3644   if (p->waiting_scbs.head == NULL)
3645     return;
3646
3647   sent = 0;
3648
3649   /*
3650    * First handle SCBs that are waiting but have been assigned a slot.
3651    */
3652   while ((scb = scbq_remove_head(&p->waiting_scbs)) != NULL)
3653   {
3654     aic_dev = scb->cmd->device->hostdata;
3655     if ( !scb->tag_action )
3656     {
3657       aic_dev->temp_q_depth = 1;
3658     }
3659     if ( aic_dev->active_cmds >= aic_dev->temp_q_depth)
3660     {
3661       scbq_insert_tail(&aic_dev->delayed_scbs, scb);
3662     }
3663     else
3664     {
3665         scb->flags &= ~SCB_WAITINGQ;
3666         aic_dev->active_cmds++;
3667         p->activescbs++;
3668         if ( !(scb->tag_action) )
3669         {
3670           aic7xxx_busy_target(p, scb);
3671         }
3672         p->qinfifo[p->qinfifonext++] = scb->hscb->tag;
3673         sent++;
3674     }
3675   }
3676   if (sent)
3677   {
3678     if (p->features & AHC_QUEUE_REGS)
3679       aic_outb(p, p->qinfifonext, HNSCB_QOFF);
3680     else
3681     {
3682       pause_sequencer(p);
3683       aic_outb(p, p->qinfifonext, KERNEL_QINPOS);
3684       unpause_sequencer(p, FALSE);
3685     }
3686     if (p->activescbs > p->max_activescbs)
3687       p->max_activescbs = p->activescbs;
3688   }
3689 }
3690
3691 #ifdef CONFIG_PCI
3692
3693 #define  DPE 0x80
3694 #define  SSE 0x40
3695 #define  RMA 0x20
3696 #define  RTA 0x10
3697 #define  STA 0x08
3698 #define  DPR 0x01
3699
3700 /*+F*************************************************************************
3701  * Function:
3702  *   aic7xxx_pci_intr
3703  *
3704  * Description:
3705  *   Check the scsi card for PCI errors and clear the interrupt
3706  *
3707  *   NOTE: If you don't have this function and a 2940 card encounters
3708  *         a PCI error condition, the machine will end up locked as the
3709  *         interrupt handler gets slammed with non-stop PCI error interrupts
3710  *-F*************************************************************************/
3711 static void
3712 aic7xxx_pci_intr(struct aic7xxx_host *p)
3713 {
3714   unsigned char status1;
3715
3716   pci_read_config_byte(p->pdev, PCI_STATUS + 1, &status1);
3717
3718   if ( (status1 & DPE) && (aic7xxx_verbose & VERBOSE_MINOR_ERROR) )
3719     printk(WARN_LEAD "Data Parity Error during PCI address or PCI write"
3720       "phase.\n", p->host_no, -1, -1, -1);
3721   if ( (status1 & SSE) && (aic7xxx_verbose & VERBOSE_MINOR_ERROR) )
3722     printk(WARN_LEAD "Signal System Error Detected\n", p->host_no,
3723       -1, -1, -1);
3724   if ( (status1 & RMA) && (aic7xxx_verbose & VERBOSE_MINOR_ERROR) )
3725     printk(WARN_LEAD "Received a PCI Master Abort\n", p->host_no,
3726       -1, -1, -1);
3727   if ( (status1 & RTA) && (aic7xxx_verbose & VERBOSE_MINOR_ERROR) )
3728     printk(WARN_LEAD "Received a PCI Target Abort\n", p->host_no,
3729       -1, -1, -1);
3730   if ( (status1 & STA) && (aic7xxx_verbose & VERBOSE_MINOR_ERROR) )
3731     printk(WARN_LEAD "Signaled a PCI Target Abort\n", p->host_no,
3732       -1, -1, -1);
3733   if ( (status1 & DPR) && (aic7xxx_verbose & VERBOSE_MINOR_ERROR) )
3734     printk(WARN_LEAD "Data Parity Error has been reported via PCI pin "
3735       "PERR#\n", p->host_no, -1, -1, -1);
3736   
3737   pci_write_config_byte(p->pdev, PCI_STATUS + 1, status1);
3738   if (status1 & (DPR|RMA|RTA))
3739     aic_outb(p,  CLRPARERR, CLRINT);
3740
3741   if ( (aic7xxx_panic_on_abort) && (p->spurious_int > 500) )
3742     aic7xxx_panic_abort(p, NULL);
3743
3744 }
3745 #endif /* CONFIG_PCI */
3746
3747 /*+F*************************************************************************
3748  * Function:
3749  *   aic7xxx_construct_ppr
3750  *
3751  * Description:
3752  *   Build up a Parallel Protocol Request message for use with SCSI-3
3753  *   devices.
3754  *-F*************************************************************************/
3755 static void
3756 aic7xxx_construct_ppr(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
3757 {
3758   p->msg_buf[p->msg_index++] = MSG_EXTENDED;
3759   p->msg_buf[p->msg_index++] = MSG_EXT_PPR_LEN;
3760   p->msg_buf[p->msg_index++] = MSG_EXT_PPR;
3761   p->msg_buf[p->msg_index++] = AIC_DEV(scb->cmd)->goal.period;
3762   p->msg_buf[p->msg_index++] = 0;
3763   p->msg_buf[p->msg_index++] = AIC_DEV(scb->cmd)->goal.offset;
3764   p->msg_buf[p->msg_index++] = AIC_DEV(scb->cmd)->goal.width;
3765   p->msg_buf[p->msg_index++] = AIC_DEV(scb->cmd)->goal.options;
3766   p->msg_len += 8;
3767 }
3768
3769 /*+F*************************************************************************
3770  * Function:
3771  *   aic7xxx_construct_sdtr
3772  *
3773  * Description:
3774  *   Constucts a synchronous data transfer message in the message
3775  *   buffer on the sequencer.
3776  *-F*************************************************************************/
3777 static void
3778 aic7xxx_construct_sdtr(struct aic7xxx_host *p, unsigned char period,
3779         unsigned char offset)
3780 {
3781   p->msg_buf[p->msg_index++] = MSG_EXTENDED;
3782   p->msg_buf[p->msg_index++] = MSG_EXT_SDTR_LEN;
3783   p->msg_buf[p->msg_index++] = MSG_EXT_SDTR;
3784   p->msg_buf[p->msg_index++] = period;
3785   p->msg_buf[p->msg_index++] = offset;
3786   p->msg_len += 5;
3787 }
3788
3789 /*+F*************************************************************************
3790  * Function:
3791  *   aic7xxx_construct_wdtr
3792  *
3793  * Description:
3794  *   Constucts a wide data transfer message in the message buffer
3795  *   on the sequencer.
3796  *-F*************************************************************************/
3797 static void
3798 aic7xxx_construct_wdtr(struct aic7xxx_host *p, unsigned char bus_width)
3799 {
3800   p->msg_buf[p->msg_index++] = MSG_EXTENDED;
3801   p->msg_buf[p->msg_index++] = MSG_EXT_WDTR_LEN;
3802   p->msg_buf[p->msg_index++] = MSG_EXT_WDTR;
3803   p->msg_buf[p->msg_index++] = bus_width;
3804   p->msg_len += 4;
3805 }
3806
3807 /*+F*************************************************************************
3808  * Function:
3809  *   aic7xxx_calc_residual
3810  *
3811  * Description:
3812  *   Calculate the residual data not yet transferred.
3813  *-F*************************************************************************/
3814 static void
3815 aic7xxx_calculate_residual (struct aic7xxx_host *p, struct aic7xxx_scb *scb)
3816 {
3817         struct aic7xxx_hwscb *hscb;
3818         struct scsi_cmnd *cmd;
3819         int actual, i;
3820
3821   cmd = scb->cmd;
3822   hscb = scb->hscb;
3823
3824   /*
3825    *  Don't destroy valid residual information with
3826    *  residual coming from a check sense operation.
3827    */
3828   if (((scb->hscb->control & DISCONNECTED) == 0) &&
3829       (scb->flags & SCB_SENSE) == 0)
3830   {
3831     /*
3832      *  We had an underflow. At this time, there's only
3833      *  one other driver that bothers to check for this,
3834      *  and cmd->underflow seems to be set rather half-
3835      *  heartedly in the higher-level SCSI code.
3836      */
3837     actual = scb->sg_length;
3838     for (i=1; i < hscb->residual_SG_segment_count; i++)
3839     {
3840       actual -= scb->sg_list[scb->sg_count - i].length;
3841     }
3842     actual -= (hscb->residual_data_count[2] << 16) |
3843               (hscb->residual_data_count[1] <<  8) |
3844               hscb->residual_data_count[0];
3845
3846     if (actual < cmd->underflow)
3847     {
3848       if (aic7xxx_verbose & VERBOSE_MINOR_ERROR)
3849       {
3850         printk(INFO_LEAD "Underflow - Wanted %u, %s %u, residual SG "
3851           "count %d.\n", p->host_no, CTL_OF_SCB(scb), cmd->underflow,
3852           (rq_data_dir(cmd->request) == WRITE) ? "wrote" : "read", actual,
3853           hscb->residual_SG_segment_count);
3854         printk(INFO_LEAD "status 0x%x.\n", p->host_no, CTL_OF_SCB(scb),
3855           hscb->target_status);
3856       }
3857       /*
3858        * In 2.4, only send back the residual information, don't flag this
3859        * as an error.  Before 2.4 we had to flag this as an error because
3860        * the mid layer didn't check residual data counts to see if the
3861        * command needs retried.
3862        */
3863       scsi_set_resid(cmd, scb->sg_length - actual);
3864       aic7xxx_status(cmd) = hscb->target_status;
3865     }
3866   }
3867
3868   /*
3869    * Clean out the residual information in the SCB for the
3870    * next consumer.
3871    */
3872   hscb->residual_data_count[2] = 0;
3873   hscb->residual_data_count[1] = 0;
3874   hscb->residual_data_count[0] = 0;
3875   hscb->residual_SG_segment_count = 0;
3876 }
3877
3878 /*+F*************************************************************************
3879  * Function:
3880  *   aic7xxx_handle_device_reset
3881  *
3882  * Description:
3883  *   Interrupt handler for sequencer interrupts (SEQINT).
3884  *-F*************************************************************************/
3885 static void
3886 aic7xxx_handle_device_reset(struct aic7xxx_host *p, int target, int channel)
3887 {
3888   unsigned char tindex = target;
3889
3890   tindex |= ((channel & 0x01) << 3);
3891
3892   /*
3893    * Go back to async/narrow transfers and renegotiate.
3894    */
3895   aic_outb(p, 0, TARG_SCSIRATE + tindex);
3896   if (p->features & AHC_ULTRA2)
3897     aic_outb(p, 0, TARG_OFFSET + tindex);
3898   aic7xxx_reset_device(p, target, channel, ALL_LUNS, SCB_LIST_NULL);
3899   if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
3900     printk(INFO_LEAD "Bus Device Reset delivered.\n", p->host_no, channel,
3901       target, -1);
3902   aic7xxx_run_done_queue(p, /*complete*/ TRUE);
3903 }
3904
3905 /*+F*************************************************************************
3906  * Function:
3907  *   aic7xxx_handle_seqint
3908  *
3909  * Description:
3910  *   Interrupt handler for sequencer interrupts (SEQINT).
3911  *-F*************************************************************************/
3912 static void
3913 aic7xxx_handle_seqint(struct aic7xxx_host *p, unsigned char intstat)
3914 {
3915   struct aic7xxx_scb *scb;
3916   struct aic_dev_data *aic_dev;
3917   unsigned short target_mask;
3918   unsigned char target, lun, tindex;
3919   unsigned char queue_flag = FALSE;
3920   char channel;
3921   int result;
3922
3923   target = ((aic_inb(p, SAVED_TCL) >> 4) & 0x0f);
3924   if ( (p->chip & AHC_CHIPID_MASK) == AHC_AIC7770 )
3925     channel = (aic_inb(p, SBLKCTL) & SELBUSB) >> 3;
3926   else
3927     channel = 0;
3928   tindex = target + (channel << 3);
3929   lun = aic_inb(p, SAVED_TCL) & 0x07;
3930   target_mask = (0x01 << tindex);
3931
3932   /*
3933    * Go ahead and clear the SEQINT now, that avoids any interrupt race
3934    * conditions later on in case we enable some other interrupt.
3935    */
3936   aic_outb(p, CLRSEQINT, CLRINT);
3937   switch (intstat & SEQINT_MASK)
3938   {
3939     case NO_MATCH:
3940       {
3941         aic_outb(p, aic_inb(p, SCSISEQ) & (ENSELI|ENRSELI|ENAUTOATNP),
3942                  SCSISEQ);
3943         printk(WARN_LEAD "No active SCB for reconnecting target - Issuing "
3944                "BUS DEVICE RESET.\n", p->host_no, channel, target, lun);
3945         printk(WARN_LEAD "      SAVED_TCL=0x%x, ARG_1=0x%x, SEQADDR=0x%x\n",
3946                p->host_no, channel, target, lun,
3947                aic_inb(p, SAVED_TCL), aic_inb(p, ARG_1),
3948                (aic_inb(p, SEQADDR1) << 8) | aic_inb(p, SEQADDR0));
3949         if (aic7xxx_panic_on_abort)
3950           aic7xxx_panic_abort(p, NULL);
3951       }
3952       break;
3953
3954     case SEND_REJECT:
3955       {
3956         if (aic7xxx_verbose & VERBOSE_MINOR_ERROR)
3957           printk(INFO_LEAD "Rejecting unknown message (0x%x) received from "
3958             "target, SEQ_FLAGS=0x%x\n", p->host_no, channel, target, lun,
3959             aic_inb(p, ACCUM), aic_inb(p, SEQ_FLAGS));
3960       }
3961       break;
3962
3963     case NO_IDENT:
3964       {
3965         /*
3966          * The reconnecting target either did not send an identify
3967          * message, or did, but we didn't find an SCB to match and
3968          * before it could respond to our ATN/abort, it hit a dataphase.
3969          * The only safe thing to do is to blow it away with a bus
3970          * reset.
3971          */
3972         if (aic7xxx_verbose & (VERBOSE_SEQINT | VERBOSE_RESET_MID))
3973           printk(INFO_LEAD "Target did not send an IDENTIFY message; "
3974             "LASTPHASE 0x%x, SAVED_TCL 0x%x\n", p->host_no, channel, target,
3975             lun, aic_inb(p, LASTPHASE), aic_inb(p, SAVED_TCL));
3976
3977         aic7xxx_reset_channel(p, channel, /*initiate reset*/ TRUE);
3978         aic7xxx_run_done_queue(p, TRUE);
3979
3980       }
3981       break;
3982
3983     case BAD_PHASE:
3984       if (aic_inb(p, LASTPHASE) == P_BUSFREE)
3985       {
3986         if (aic7xxx_verbose & VERBOSE_SEQINT)
3987           printk(INFO_LEAD "Missed busfree.\n", p->host_no, channel,
3988             target, lun);
3989         restart_sequencer(p);
3990       }
3991       else
3992       {
3993         if (aic7xxx_verbose & VERBOSE_SEQINT)
3994           printk(INFO_LEAD "Unknown scsi bus phase, continuing\n", p->host_no,
3995             channel, target, lun);
3996       }
3997       break;
3998
3999     case EXTENDED_MSG:
4000       {
4001         p->msg_type = MSG_TYPE_INITIATOR_MSGIN;
4002         p->msg_len = 0;
4003         p->msg_index = 0;
4004
4005 #ifdef AIC7XXX_VERBOSE_DEBUGGING
4006         if (aic7xxx_verbose > 0xffff)
4007           printk(INFO_LEAD "Enabling REQINITs for MSG_IN\n", p->host_no,
4008                  channel, target, lun);
4009 #endif
4010
4011        /*      
4012         * To actually receive the message, simply turn on
4013         * REQINIT interrupts and let our interrupt handler
4014         * do the rest (REQINIT should already be true).
4015         */
4016         p->flags |= AHC_HANDLING_REQINITS;
4017         aic_outb(p, aic_inb(p, SIMODE1) | ENREQINIT, SIMODE1);
4018
4019        /*
4020         * We don't want the sequencer unpaused yet so we return early
4021         */
4022         return;
4023       }
4024
4025     case REJECT_MSG:
4026       {
4027         /*
4028          * What we care about here is if we had an outstanding SDTR
4029          * or WDTR message for this target. If we did, this is a
4030          * signal that the target is refusing negotiation.
4031          */
4032         unsigned char scb_index;
4033         unsigned char last_msg;
4034
4035         scb_index = aic_inb(p, SCB_TAG);
4036         scb = p->scb_data->scb_array[scb_index];
4037         aic_dev = AIC_DEV(scb->cmd);
4038         last_msg = aic_inb(p, LAST_MSG);
4039
4040         if ( (last_msg == MSG_IDENTIFYFLAG) &&
4041              (scb->tag_action) &&
4042             !(scb->flags & SCB_MSGOUT_BITS) )
4043         {
4044           if (scb->tag_action == MSG_ORDERED_Q_TAG)
4045           {
4046             /*
4047              * OK...the device seems able to accept tagged commands, but
4048              * not ordered tag commands, only simple tag commands.  So, we
4049              * disable ordered tag commands and go on with life just like
4050              * normal.
4051              */
4052             scsi_adjust_queue_depth(scb->cmd->device, MSG_SIMPLE_TAG,
4053                             scb->cmd->device->queue_depth);
4054             scb->tag_action = MSG_SIMPLE_Q_TAG;
4055             scb->hscb->control &= ~SCB_TAG_TYPE;
4056             scb->hscb->control |= MSG_SIMPLE_Q_TAG;
4057             aic_outb(p, scb->hscb->control, SCB_CONTROL);
4058             /*
4059              * OK..we set the tag type to simple tag command, now we re-assert
4060              * ATNO and hope this will take us into the identify phase again
4061              * so we can resend the tag type and info to the device.
4062              */
4063             aic_outb(p, MSG_IDENTIFYFLAG, MSG_OUT);
4064             aic_outb(p, aic_inb(p, SCSISIGI) | ATNO, SCSISIGO);
4065           }
4066           else if (scb->tag_action == MSG_SIMPLE_Q_TAG)
4067           {
4068             unsigned char i;
4069             struct aic7xxx_scb *scbp;
4070             int old_verbose;
4071             /*
4072              * Hmmmm....the device is flaking out on tagged commands.
4073              */
4074             scsi_adjust_queue_depth(scb->cmd->device, 0 /* untagged */,
4075                             p->host->cmd_per_lun);
4076             aic_dev->max_q_depth = aic_dev->temp_q_depth = 1;
4077             /*
4078              * We set this command up as a bus device reset.  However, we have
4079              * to clear the tag type as it's causing us problems.  We shouldnt
4080              * have to worry about any other commands being active, since if
4081              * the device is refusing tagged commands, this should be the
4082              * first tagged command sent to the device, however, we do have
4083              * to worry about any other tagged commands that may already be
4084              * in the qinfifo.  The easiest way to do this, is to issue a BDR,
4085              * send all the commands back to the mid level code, then let them
4086              * come back and get rebuilt as untagged commands.
4087              */
4088             scb->tag_action = 0;
4089             scb->hscb->control &= ~(TAG_ENB | SCB_TAG_TYPE);
4090             aic_outb(p,  scb->hscb->control, SCB_CONTROL);
4091
4092             old_verbose = aic7xxx_verbose;
4093             aic7xxx_verbose &= ~(VERBOSE_RESET|VERBOSE_ABORT);
4094             for (i=0; i < p->scb_data->numscbs; i++)
4095             {
4096               scbp = p->scb_data->scb_array[i];
4097               if ((scbp->flags & SCB_ACTIVE) && (scbp != scb))
4098               {
4099                 if (aic7xxx_match_scb(p, scbp, target, channel, lun, i))
4100                 {
4101                   aic7xxx_reset_device(p, target, channel, lun, i);
4102                 }
4103               }
4104             }
4105             aic7xxx_run_done_queue(p, TRUE);
4106             aic7xxx_verbose = old_verbose;
4107             /*
4108              * Wait until after the for loop to set the busy index since
4109              * aic7xxx_reset_device will clear the busy index during its
4110              * operation.
4111              */
4112             aic7xxx_busy_target(p, scb);
4113             printk(INFO_LEAD "Device is refusing tagged commands, using "
4114               "untagged I/O.\n", p->host_no, channel, target, lun);
4115             aic_outb(p, MSG_IDENTIFYFLAG, MSG_OUT);
4116             aic_outb(p, aic_inb(p, SCSISIGI) | ATNO, SCSISIGO);
4117           }
4118         }
4119         else if (scb->flags & SCB_MSGOUT_PPR)
4120         {
4121           /*
4122            * As per the draft specs, any device capable of supporting any of
4123            * the option values other than 0 are not allowed to reject the
4124            * PPR message.  Instead, they must negotiate out what they do
4125            * support instead of rejecting our offering or else they cause
4126            * a parity error during msg_out phase to signal that they don't
4127            * like our settings.
4128            */
4129           aic_dev->needppr = aic_dev->needppr_copy = 0;
4130           aic7xxx_set_width(p, target, channel, lun, MSG_EXT_WDTR_BUS_8_BIT,
4131             (AHC_TRANS_ACTIVE|AHC_TRANS_CUR|AHC_TRANS_QUITE), aic_dev);
4132           aic7xxx_set_syncrate(p, NULL, target, channel, 0, 0, 0,
4133                                AHC_TRANS_ACTIVE|AHC_TRANS_CUR|AHC_TRANS_QUITE,
4134                                aic_dev);
4135           aic_dev->goal.options = aic_dev->dtr_pending = 0;
4136           scb->flags &= ~SCB_MSGOUT_BITS;
4137           if(aic7xxx_verbose & VERBOSE_NEGOTIATION2)
4138           {
4139             printk(INFO_LEAD "Device is rejecting PPR messages, falling "
4140               "back.\n", p->host_no, channel, target, lun);
4141           }
4142           if ( aic_dev->goal.width )
4143           {
4144             aic_dev->needwdtr = aic_dev->needwdtr_copy = 1;
4145             aic_dev->dtr_pending = 1;
4146             scb->flags |= SCB_MSGOUT_WDTR;
4147           }
4148           if ( aic_dev->goal.offset )
4149           {
4150             aic_dev->needsdtr = aic_dev->needsdtr_copy = 1;
4151             if( !aic_dev->dtr_pending )
4152             {
4153               aic_dev->dtr_pending = 1;
4154               scb->flags |= SCB_MSGOUT_SDTR;
4155             }
4156           }
4157           if ( aic_dev->dtr_pending )
4158           {
4159             aic_outb(p, HOST_MSG, MSG_OUT);
4160             aic_outb(p, aic_inb(p, SCSISIGI) | ATNO, SCSISIGO);
4161           }
4162         }
4163         else if (scb->flags & SCB_MSGOUT_WDTR)
4164         {
4165           /*
4166            * note 8bit xfers and clear flag
4167            */
4168           aic_dev->needwdtr = aic_dev->needwdtr_copy = 0;
4169           scb->flags &= ~SCB_MSGOUT_BITS;
4170           aic7xxx_set_width(p, target, channel, lun, MSG_EXT_WDTR_BUS_8_BIT,
4171             (AHC_TRANS_ACTIVE|AHC_TRANS_GOAL|AHC_TRANS_CUR), aic_dev);
4172           aic7xxx_set_syncrate(p, NULL, target, channel, 0, 0, 0,
4173                                AHC_TRANS_ACTIVE|AHC_TRANS_CUR|AHC_TRANS_QUITE,
4174                                aic_dev);
4175           if(aic7xxx_verbose & VERBOSE_NEGOTIATION2)
4176           {
4177             printk(INFO_LEAD "Device is rejecting WDTR messages, using "
4178               "narrow transfers.\n", p->host_no, channel, target, lun);
4179           }
4180           aic_dev->needsdtr = aic_dev->needsdtr_copy;
4181         }
4182         else if (scb->flags & SCB_MSGOUT_SDTR)
4183         {
4184          /*
4185           * note asynch xfers and clear flag
4186           */
4187           aic_dev->needsdtr = aic_dev->needsdtr_copy = 0;
4188           scb->flags &= ~SCB_MSGOUT_BITS;
4189           aic7xxx_set_syncrate(p, NULL, target, channel, 0, 0, 0,
4190             (AHC_TRANS_CUR|AHC_TRANS_ACTIVE|AHC_TRANS_GOAL), aic_dev);
4191           if(aic7xxx_verbose & VERBOSE_NEGOTIATION2)
4192           {
4193             printk(INFO_LEAD "Device is rejecting SDTR messages, using "
4194               "async transfers.\n", p->host_no, channel, target, lun);
4195           }
4196         }
4197         else if (aic7xxx_verbose & VERBOSE_SEQINT)
4198         {
4199           /*
4200            * Otherwise, we ignore it.
4201            */
4202           printk(INFO_LEAD "Received MESSAGE_REJECT for unknown cause.  "
4203             "Ignoring.\n", p->host_no, channel, target, lun);
4204         }
4205       }
4206       break;
4207
4208     case BAD_STATUS:
4209       {
4210         unsigned char scb_index;
4211         struct aic7xxx_hwscb *hscb;
4212         struct scsi_cmnd *cmd;
4213
4214         /* The sequencer will notify us when a command has an error that
4215          * would be of interest to the kernel.  This allows us to leave
4216          * the sequencer running in the common case of command completes
4217          * without error.  The sequencer will have DMA'd the SCB back
4218          * up to us, so we can reference the drivers SCB array.
4219          *
4220          * Set the default return value to 0 indicating not to send
4221          * sense.  The sense code will change this if needed and this
4222          * reduces code duplication.
4223          */
4224         aic_outb(p, 0, RETURN_1);
4225         scb_index = aic_inb(p, SCB_TAG);
4226         if (scb_index > p->scb_data->numscbs)
4227         {
4228           printk(WARN_LEAD "Invalid SCB during SEQINT 0x%02x, SCB_TAG %d.\n",
4229             p->host_no, channel, target, lun, intstat, scb_index);
4230           break;
4231         }
4232         scb = p->scb_data->scb_array[scb_index];
4233         hscb = scb->hscb;
4234
4235         if (!(scb->flags & SCB_ACTIVE) || (scb->cmd == NULL))
4236         {
4237           printk(WARN_LEAD "Invalid SCB during SEQINT 0x%x, scb %d, flags 0x%x,"
4238             " cmd 0x%lx.\n", p->host_no, channel, target, lun, intstat,
4239             scb_index, scb->flags, (unsigned long) scb->cmd);
4240         }
4241         else
4242         {
4243           cmd = scb->cmd;
4244           aic_dev = AIC_DEV(scb->cmd);
4245           hscb->target_status = aic_inb(p, SCB_TARGET_STATUS);
4246           aic7xxx_status(cmd) = hscb->target_status;
4247
4248           cmd->result = hscb->target_status;
4249
4250           switch (status_byte(hscb->target_status))
4251           {
4252             case GOOD:
4253               if (aic7xxx_verbose & VERBOSE_SEQINT)
4254                 printk(INFO_LEAD "Interrupted for status of GOOD???\n",
4255                   p->host_no, CTL_OF_SCB(scb));
4256               break;
4257
4258             case COMMAND_TERMINATED:
4259             case CHECK_CONDITION:
4260               if ( !(scb->flags & SCB_SENSE) )
4261               {
4262                 /*
4263                  * Send a sense command to the requesting target.
4264                  * XXX - revisit this and get rid of the memcopys.
4265                  */
4266                 memcpy(scb->sense_cmd, &generic_sense[0],
4267                        sizeof(generic_sense));
4268
4269                 scb->sense_cmd[1] = (cmd->device->lun << 5);
4270                 scb->sense_cmd[4] = SCSI_SENSE_BUFFERSIZE;
4271
4272                 scb->sg_list[0].length = 
4273                   cpu_to_le32(SCSI_SENSE_BUFFERSIZE);
4274                 scb->sg_list[0].address =
4275                         cpu_to_le32(pci_map_single(p->pdev, cmd->sense_buffer,
4276                                                    SCSI_SENSE_BUFFERSIZE,
4277                                                    PCI_DMA_FROMDEVICE));
4278
4279                 /*
4280                  * XXX - We should allow disconnection, but can't as it
4281                  * might allow overlapped tagged commands.
4282                  */
4283                 /* hscb->control &= DISCENB; */
4284                 hscb->control = 0;
4285                 hscb->target_status = 0;
4286                 hscb->SG_list_pointer = 
4287                   cpu_to_le32(SCB_DMA_ADDR(scb, scb->sg_list));
4288                 hscb->SCSI_cmd_pointer = 
4289                   cpu_to_le32(SCB_DMA_ADDR(scb, scb->sense_cmd));
4290                 hscb->data_count = scb->sg_list[0].length;
4291                 hscb->data_pointer = scb->sg_list[0].address;
4292                 hscb->SCSI_cmd_length = COMMAND_SIZE(scb->sense_cmd[0]);
4293                 hscb->residual_SG_segment_count = 0;
4294                 hscb->residual_data_count[0] = 0;
4295                 hscb->residual_data_count[1] = 0;
4296                 hscb->residual_data_count[2] = 0;
4297
4298                 scb->sg_count = hscb->SG_segment_count = 1;
4299                 scb->sg_length = SCSI_SENSE_BUFFERSIZE;
4300                 scb->tag_action = 0;
4301                 scb->flags |= SCB_SENSE;
4302                 /*
4303                  * Ensure the target is busy since this will be an
4304                  * an untagged request.
4305                  */
4306 #ifdef AIC7XXX_VERBOSE_DEBUGGING
4307                 if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
4308                 {
4309                   if (scb->flags & SCB_MSGOUT_BITS)
4310                     printk(INFO_LEAD "Requesting SENSE with %s\n", p->host_no,
4311                            CTL_OF_SCB(scb), (scb->flags & SCB_MSGOUT_SDTR) ?
4312                            "SDTR" : "WDTR");
4313                   else
4314                     printk(INFO_LEAD "Requesting SENSE, no MSG\n", p->host_no,
4315                            CTL_OF_SCB(scb));
4316                 }
4317 #endif
4318                 aic7xxx_busy_target(p, scb);
4319                 aic_outb(p, SEND_SENSE, RETURN_1);
4320                 aic7xxx_error(cmd) = DID_OK;
4321                 break;
4322               }  /* first time sense, no errors */
4323               printk(INFO_LEAD "CHECK_CONDITION on REQUEST_SENSE, returning "
4324                      "an error.\n", p->host_no, CTL_OF_SCB(scb));
4325               aic7xxx_error(cmd) = DID_ERROR;
4326               scb->flags &= ~SCB_SENSE;
4327               break;
4328
4329             case QUEUE_FULL:
4330               queue_flag = TRUE;    /* Mark that this is a QUEUE_FULL and */
4331             case BUSY:              /* drop through to here */
4332             {
4333               struct aic7xxx_scb *next_scbp, *prev_scbp;
4334               unsigned char active_hscb, next_hscb, prev_hscb, scb_index;
4335               /*
4336                * We have to look three places for queued commands:
4337                *  1: p->waiting_scbs queue
4338                *  2: QINFIFO
4339                *  3: WAITING_SCBS list on card (for commands that are started
4340                *     but haven't yet made it to the device)
4341                *
4342                * Of special note here is that commands on 2 or 3 above will
4343                * have already been marked as active, while commands on 1 will
4344                * not.  The aic7xxx_done() function will want to unmark them
4345                * from active, so any commands we pull off of 1 need to
4346                * up the active count.
4347                */
4348               next_scbp = p->waiting_scbs.head;
4349               while ( next_scbp != NULL )
4350               {
4351                 prev_scbp = next_scbp;
4352                 next_scbp = next_scbp->q_next;
4353                 if ( aic7xxx_match_scb(p, prev_scbp, target, channel, lun,
4354                      SCB_LIST_NULL) )
4355                 {
4356                   scbq_remove(&p->waiting_scbs, prev_scbp);
4357                   scb->flags = SCB_QUEUED_FOR_DONE | SCB_QUEUE_FULL;
4358                   p->activescbs++;
4359                   aic_dev->active_cmds++;
4360                 }
4361               }
4362               aic7xxx_search_qinfifo(p, target, channel, lun,
4363                 SCB_LIST_NULL, SCB_QUEUED_FOR_DONE | SCB_QUEUE_FULL,
4364                 FALSE, NULL);
4365               next_scbp = NULL;
4366               active_hscb = aic_inb(p, SCBPTR);
4367               prev_hscb = next_hscb = scb_index = SCB_LIST_NULL;
4368               next_hscb = aic_inb(p, WAITING_SCBH);
4369               while (next_hscb != SCB_LIST_NULL)
4370               {
4371                 aic_outb(p, next_hscb, SCBPTR);
4372                 scb_index = aic_inb(p, SCB_TAG);
4373                 if (scb_index < p->scb_data->numscbs)
4374                 {
4375                   next_scbp = p->scb_data->scb_array[scb_index];
4376                   if (aic7xxx_match_scb(p, next_scbp, target, channel, lun,
4377                       SCB_LIST_NULL) )
4378                   {
4379                     next_scbp->flags = SCB_QUEUED_FOR_DONE | SCB_QUEUE_FULL;
4380                     next_hscb = aic_inb(p, SCB_NEXT);
4381                     aic_outb(p, 0, SCB_CONTROL);
4382                     aic_outb(p, SCB_LIST_NULL, SCB_TAG);
4383                     aic7xxx_add_curscb_to_free_list(p);
4384                     if (prev_hscb == SCB_LIST_NULL)
4385                     {
4386                       /* We were first on the list,
4387                        * so we kill the selection
4388                        * hardware.  Let the sequencer
4389                        * re-init the hardware itself
4390                        */
4391                       aic_outb(p, aic_inb(p, SCSISEQ) & ~ENSELO, SCSISEQ);
4392                       aic_outb(p, CLRSELTIMEO, CLRSINT1);
4393                       aic_outb(p, next_hscb, WAITING_SCBH);
4394                     }
4395                     else
4396                     {
4397                       aic_outb(p, prev_hscb, SCBPTR);
4398                       aic_outb(p, next_hscb, SCB_NEXT);
4399                     }
4400                   }
4401                   else
4402                   {
4403                     prev_hscb = next_hscb;
4404                     next_hscb = aic_inb(p, SCB_NEXT);
4405                   }
4406                 } /* scb_index >= p->scb_data->numscbs */
4407               }
4408               aic_outb(p, active_hscb, SCBPTR);
4409               aic7xxx_run_done_queue(p, FALSE);
4410                   
4411 #ifdef AIC7XXX_VERBOSE_DEBUGGING
4412               if( (aic7xxx_verbose & VERBOSE_MINOR_ERROR) ||
4413                   (aic7xxx_verbose > 0xffff) )
4414               {
4415                 if (queue_flag)
4416                   printk(INFO_LEAD "Queue full received; queue depth %d, "
4417                     "active %d\n", p->host_no, CTL_OF_SCB(scb),
4418                     aic_dev->max_q_depth, aic_dev->active_cmds);
4419                 else
4420                   printk(INFO_LEAD "Target busy\n", p->host_no, CTL_OF_SCB(scb));
4421               }
4422 #endif
4423               if (queue_flag)
4424               {
4425                 int diff;
4426                 result = scsi_track_queue_full(cmd->device,
4427                                 aic_dev->active_cmds);
4428                 if ( result < 0 )
4429                 {
4430                   if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
4431                     printk(INFO_LEAD "Tagged Command Queueing disabled.\n",
4432                         p->host_no, CTL_OF_SCB(scb));
4433                   diff = aic_dev->max_q_depth - p->host->cmd_per_lun;
4434                   aic_dev->temp_q_depth = 1;
4435                   aic_dev->max_q_depth = 1;
4436                 }
4437                 else if ( result > 0 )
4438                 {
4439                   if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
4440                     printk(INFO_LEAD "Queue depth reduced to %d\n", p->host_no,
4441                       CTL_OF_SCB(scb), result);
4442                   diff = aic_dev->max_q_depth - result;
4443                   aic_dev->max_q_depth = result;
4444                   /* temp_q_depth could have been dropped to 1 for an untagged
4445                    * command that might be coming up */
4446                   if(aic_dev->temp_q_depth > result)
4447                     aic_dev->temp_q_depth = result;
4448                 }
4449                 /* We should free up the no unused SCB entries.  But, that's
4450                  * a difficult thing to do because we use a direct indexed
4451                  * array, so we can't just take any entries and free them,
4452                  * we *have* to free the ones at the end of the array, and
4453                  * they very well could be in use right now, which means
4454                  * in order to do this right, we have to add a delayed
4455                  * freeing mechanism tied into the scb_free() code area.
4456                  * We'll add that later.
4457                  */
4458               }
4459               break;
4460             }
4461             
4462             default:
4463               if (aic7xxx_verbose & VERBOSE_SEQINT)
4464                 printk(INFO_LEAD "Unexpected target status 0x%x.\n", p->host_no,
4465                      CTL_OF_SCB(scb), scb->hscb->target_status);
4466               if (!aic7xxx_error(cmd))
4467               {
4468                 aic7xxx_error(cmd) = DID_RETRY_COMMAND;
4469               }
4470               break;
4471           }  /* end switch */
4472         }  /* end else of */
4473       }
4474       break;
4475
4476     case AWAITING_MSG:
4477       {
4478         unsigned char scb_index, msg_out;
4479
4480         scb_index = aic_inb(p, SCB_TAG);
4481         msg_out = aic_inb(p, MSG_OUT);
4482         scb = p->scb_data->scb_array[scb_index];
4483         aic_dev = AIC_DEV(scb->cmd);
4484         p->msg_index = p->msg_len = 0;
4485         /*
4486          * This SCB had a MK_MESSAGE set in its control byte informing
4487          * the sequencer that we wanted to send a special message to
4488          * this target.
4489          */
4490
4491         if ( !(scb->flags & SCB_DEVICE_RESET) &&
4492               (msg_out == MSG_IDENTIFYFLAG) &&
4493               (scb->hscb->control & TAG_ENB) )
4494         {
4495           p->msg_buf[p->msg_index++] = scb->tag_action;
4496           p->msg_buf[p->msg_index++] = scb->hscb->tag;
4497           p->msg_len += 2;
4498         }
4499
4500         if (scb->flags & SCB_DEVICE_RESET)
4501         {
4502           p->msg_buf[p->msg_index++] = MSG_BUS_DEV_RESET;
4503           p->msg_len++;
4504           if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
4505             printk(INFO_LEAD "Bus device reset mailed.\n",
4506                  p->host_no, CTL_OF_SCB(scb));
4507         }
4508         else if (scb->flags & SCB_ABORT)
4509         {
4510           if (scb->tag_action)
4511           {
4512             p->msg_buf[p->msg_index++] = MSG_ABORT_TAG;
4513           }
4514           else
4515           {
4516             p->msg_buf[p->msg_index++] = MSG_ABORT;
4517           }
4518           p->msg_len++;
4519           if (aic7xxx_verbose & VERBOSE_ABORT_PROCESS)
4520             printk(INFO_LEAD "Abort message mailed.\n", p->host_no,
4521               CTL_OF_SCB(scb));
4522         }
4523         else if (scb->flags & SCB_MSGOUT_PPR)
4524         {
4525           if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
4526           {
4527             printk(INFO_LEAD "Sending PPR (%d/%d/%d/%d) message.\n",
4528                    p->host_no, CTL_OF_SCB(scb),
4529                    aic_dev->goal.period,
4530                    aic_dev->goal.offset,
4531                    aic_dev->goal.width,
4532                    aic_dev->goal.options);
4533           }
4534           aic7xxx_construct_ppr(p, scb);
4535         }
4536         else if (scb->flags & SCB_MSGOUT_WDTR)
4537         {
4538           if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
4539           {
4540             printk(INFO_LEAD "Sending WDTR message.\n", p->host_no,
4541                    CTL_OF_SCB(scb));
4542           }
4543           aic7xxx_construct_wdtr(p, aic_dev->goal.width);
4544         }
4545         else if (scb->flags & SCB_MSGOUT_SDTR)
4546         {
4547           unsigned int max_sync, period;
4548           unsigned char options = 0;
4549           /*
4550            * Now that the device is selected, use the bits in SBLKCTL and
4551            * SSTAT2 to determine the max sync rate for this device.
4552            */
4553           if (p->features & AHC_ULTRA2)
4554           {
4555             if ( (aic_inb(p, SBLKCTL) & ENAB40) &&
4556                 !(aic_inb(p, SSTAT2) & EXP_ACTIVE) )
4557             {
4558               max_sync = AHC_SYNCRATE_ULTRA2;
4559             }
4560             else
4561             {
4562               max_sync = AHC_SYNCRATE_ULTRA;
4563             }
4564           }
4565           else if (p->features & AHC_ULTRA)
4566           {
4567             max_sync = AHC_SYNCRATE_ULTRA;
4568           }
4569           else
4570           {
4571             max_sync = AHC_SYNCRATE_FAST;
4572           }
4573           period = aic_dev->goal.period;
4574           aic7xxx_find_syncrate(p, &period, max_sync, &options);
4575           if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
4576           {
4577             printk(INFO_LEAD "Sending SDTR %d/%d message.\n", p->host_no,
4578                    CTL_OF_SCB(scb), period,
4579                    aic_dev->goal.offset);
4580           }
4581           aic7xxx_construct_sdtr(p, period, aic_dev->goal.offset);
4582         }
4583         else 
4584         {
4585           panic("aic7xxx: AWAITING_MSG for an SCB that does "
4586                 "not have a waiting message.\n");
4587         }
4588         /*
4589          * We've set everything up to send our message, now to actually do
4590          * so we need to enable reqinit interrupts and let the interrupt
4591          * handler do the rest.  We don't want to unpause the sequencer yet
4592          * though so we'll return early.  We also have to make sure that
4593          * we clear the SEQINT *BEFORE* we set the REQINIT handler active
4594          * or else it's possible on VLB cards to lose the first REQINIT
4595          * interrupt.  Edge triggered EISA cards could also lose this
4596          * interrupt, although PCI and level triggered cards should not
4597          * have this problem since they continually interrupt the kernel
4598          * until we take care of the situation.
4599          */
4600         scb->flags |= SCB_MSGOUT_SENT;
4601         p->msg_index = 0;
4602         p->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
4603         p->flags |= AHC_HANDLING_REQINITS;
4604         aic_outb(p, aic_inb(p, SIMODE1) | ENREQINIT, SIMODE1);
4605         return;
4606       }
4607       break;
4608
4609     case DATA_OVERRUN:
4610       {
4611         unsigned char scb_index = aic_inb(p, SCB_TAG);
4612         unsigned char lastphase = aic_inb(p, LASTPHASE);
4613         unsigned int i;
4614
4615         scb = (p->scb_data->scb_array[scb_index]);
4616         /*
4617          * XXX - What do we really want to do on an overrun?  The
4618          *       mid-level SCSI code should handle this, but for now,
4619          *       we'll just indicate that the command should retried.
4620          *    If we retrieved sense info on this target, then the 
4621          *    base SENSE info should have been saved prior to the
4622          *    overrun error.  In that case, we return DID_OK and let
4623          *    the mid level code pick up on the sense info.  Otherwise
4624          *    we return DID_ERROR so the command will get retried.
4625          */
4626         if ( !(scb->flags & SCB_SENSE) )
4627         {
4628           printk(WARN_LEAD "Data overrun detected in %s phase, tag %d;\n",
4629             p->host_no, CTL_OF_SCB(scb), 
4630             (lastphase == P_DATAIN) ? "Data-In" : "Data-Out", scb->hscb->tag);
4631           printk(KERN_WARNING "  %s seen Data Phase. Length=%d, NumSGs=%d.\n",
4632             (aic_inb(p, SEQ_FLAGS) & DPHASE) ? "Have" : "Haven't",
4633             scb->sg_length, scb->sg_count);
4634           printk(KERN_WARNING "  Raw SCSI Command: 0x");
4635           for (i = 0; i < scb->hscb->SCSI_cmd_length; i++)
4636           {
4637             printk("%02x ", scb->cmd->cmnd[i]);
4638           }
4639           printk("\n");
4640           if(aic7xxx_verbose > 0xffff)
4641           {
4642             for (i = 0; i < scb->sg_count; i++)
4643             {
4644               printk(KERN_WARNING "     sg[%d] - Addr 0x%x : Length %d\n",
4645                  i, 
4646                  le32_to_cpu(scb->sg_list[i].address),
4647                  le32_to_cpu(scb->sg_list[i].length) );
4648             }
4649           }
4650           aic7xxx_error(scb->cmd) = DID_ERROR;
4651         }
4652         else
4653           printk(INFO_LEAD "Data Overrun during SEND_SENSE operation.\n",
4654             p->host_no, CTL_OF_SCB(scb));
4655       }
4656       break;
4657
4658     case WIDE_RESIDUE:
4659       {
4660         unsigned char resid_sgcnt, index;
4661         unsigned char scb_index = aic_inb(p, SCB_TAG);
4662         unsigned int cur_addr, resid_dcnt;
4663         unsigned int native_addr, native_length, sg_addr;
4664         int i;
4665
4666         if(scb_index > p->scb_data->numscbs)
4667         {
4668           printk(WARN_LEAD "invalid scb_index during WIDE_RESIDUE.\n",
4669             p->host_no, -1, -1, -1);
4670           /*
4671            * XXX: Add error handling here
4672            */
4673           break;
4674         }
4675         scb = p->scb_data->scb_array[scb_index];
4676         if(!(scb->flags & SCB_ACTIVE) || (scb->cmd == NULL))
4677         {
4678           printk(WARN_LEAD "invalid scb during WIDE_RESIDUE flags:0x%x "
4679                  "scb->cmd:0x%lx\n", p->host_no, CTL_OF_SCB(scb),
4680                  scb->flags, (unsigned long)scb->cmd);
4681           break;
4682         }
4683         if(aic7xxx_verbose & VERBOSE_MINOR_ERROR)
4684           printk(INFO_LEAD "Got WIDE_RESIDUE message, patching up data "
4685                  "pointer.\n", p->host_no, CTL_OF_SCB(scb));
4686
4687         /*
4688          * We have a valid scb to use on this WIDE_RESIDUE message, so
4689          * we need to walk the sg list looking for this particular sg
4690          * segment, then see if we happen to be at the very beginning of
4691          * the segment.  If we are, then we have to back things up to
4692          * the previous segment.  If not, then we simply need to remove
4693          * one byte from this segments address and add one to the byte
4694          * count.
4695          */
4696         cur_addr = aic_inb(p, SHADDR) | (aic_inb(p, SHADDR + 1) << 8) |
4697           (aic_inb(p, SHADDR + 2) << 16) | (aic_inb(p, SHADDR + 3) << 24);
4698         sg_addr = aic_inb(p, SG_COUNT + 1) | (aic_inb(p, SG_COUNT + 2) << 8) |
4699           (aic_inb(p, SG_COUNT + 3) << 16) | (aic_inb(p, SG_COUNT + 4) << 24);
4700         resid_sgcnt = aic_inb(p, SCB_RESID_SGCNT);
4701         resid_dcnt = aic_inb(p, SCB_RESID_DCNT) |
4702           (aic_inb(p, SCB_RESID_DCNT + 1) << 8) |
4703           (aic_inb(p, SCB_RESID_DCNT + 2) << 16);
4704         index = scb->sg_count - ((resid_sgcnt) ? resid_sgcnt : 1);
4705         native_addr = le32_to_cpu(scb->sg_list[index].address);
4706         native_length = le32_to_cpu(scb->sg_list[index].length);
4707         /*
4708          * If resid_dcnt == native_length, then we just loaded this SG
4709          * segment and we need to back it up one...
4710          */
4711         if(resid_dcnt == native_length)
4712         {
4713           if(index == 0)
4714           {
4715             /*
4716              * Oops, this isn't right, we can't back up to before the
4717              * beginning.  This must be a bogus message, ignore it.
4718              */
4719             break;
4720           }
4721           resid_dcnt = 1;
4722           resid_sgcnt += 1;
4723           native_addr = le32_to_cpu(scb->sg_list[index - 1].address);
4724           native_length = le32_to_cpu(scb->sg_list[index - 1].length);
4725           cur_addr = native_addr + (native_length - 1);
4726           sg_addr -= sizeof(struct hw_scatterlist);
4727         }
4728         else
4729         {
4730           /*
4731            * resid_dcnt != native_length, so we are in the middle of a SG
4732            * element.  Back it up one byte and leave the rest alone.
4733            */
4734           resid_dcnt += 1;
4735           cur_addr -= 1;
4736         }
4737         
4738         /*
4739          * Output the new addresses and counts to the right places on the
4740          * card.
4741          */
4742         aic_outb(p, resid_sgcnt, SG_COUNT);
4743         aic_outb(p, resid_sgcnt, SCB_RESID_SGCNT);
4744         aic_outb(p, sg_addr & 0xff, SG_COUNT + 1);
4745         aic_outb(p, (sg_addr >> 8) & 0xff, SG_COUNT + 2);
4746         aic_outb(p, (sg_addr >> 16) & 0xff, SG_COUNT + 3);
4747         aic_outb(p, (sg_addr >> 24) & 0xff, SG_COUNT + 4);
4748         aic_outb(p, resid_dcnt & 0xff, SCB_RESID_DCNT);
4749         aic_outb(p, (resid_dcnt >> 8) & 0xff, SCB_RESID_DCNT + 1);
4750         aic_outb(p, (resid_dcnt >> 16) & 0xff, SCB_RESID_DCNT + 2);
4751
4752         /*
4753          * The sequencer actually wants to find the new address
4754          * in the SHADDR register set.  On the Ultra2 and later controllers
4755          * this register set is readonly.  In order to get the right number
4756          * into the register, you actually have to enter it in HADDR and then
4757          * use the PRELOADEN bit of DFCNTRL to drop it through from the
4758          * HADDR register to the SHADDR register.  On non-Ultra2 controllers,
4759          * we simply write it direct.
4760          */
4761         if(p->features & AHC_ULTRA2)
4762         {
4763           /*
4764            * We might as well be accurate and drop both the resid_dcnt and
4765            * cur_addr into HCNT and HADDR and have both of them drop
4766            * through to the shadow layer together.
4767            */
4768           aic_outb(p, resid_dcnt & 0xff, HCNT);
4769           aic_outb(p, (resid_dcnt >> 8) & 0xff, HCNT + 1);
4770           aic_outb(p, (resid_dcnt >> 16) & 0xff, HCNT + 2);
4771           aic_outb(p, cur_addr & 0xff, HADDR);
4772           aic_outb(p, (cur_addr >> 8) & 0xff, HADDR + 1);
4773           aic_outb(p, (cur_addr >> 16) & 0xff, HADDR + 2);
4774           aic_outb(p, (cur_addr >> 24) & 0xff, HADDR + 3);
4775           aic_outb(p, aic_inb(p, DMAPARAMS) | PRELOADEN, DFCNTRL);
4776           udelay(1);
4777           aic_outb(p, aic_inb(p, DMAPARAMS) & ~(SCSIEN|HDMAEN), DFCNTRL);
4778           i=0;
4779           while(((aic_inb(p, DFCNTRL) & (SCSIEN|HDMAEN)) != 0) && (i++ < 1000))
4780           {
4781             udelay(1);
4782           }
4783         }
4784         else
4785         {
4786           aic_outb(p, cur_addr & 0xff, SHADDR);
4787           aic_outb(p, (cur_addr >> 8) & 0xff, SHADDR + 1);
4788           aic_outb(p, (cur_addr >> 16) & 0xff, SHADDR + 2);
4789           aic_outb(p, (cur_addr >> 24) & 0xff, SHADDR + 3);
4790         }
4791       }
4792       break;
4793
4794     case SEQ_SG_FIXUP:
4795     {
4796       unsigned char scb_index, tmp;
4797       int sg_addr, sg_length;
4798
4799       scb_index = aic_inb(p, SCB_TAG);
4800
4801       if(scb_index > p->scb_data->numscbs)
4802       {
4803         printk(WARN_LEAD "invalid scb_index during SEQ_SG_FIXUP.\n",
4804           p->host_no, -1, -1, -1);
4805         printk(INFO_LEAD "SCSISIGI 0x%x, SEQADDR 0x%x, SSTAT0 0x%x, SSTAT1 "
4806            "0x%x\n", p->host_no, -1, -1, -1,
4807            aic_inb(p, SCSISIGI),
4808            aic_inb(p, SEQADDR0) | (aic_inb(p, SEQADDR1) << 8),
4809            aic_inb(p, SSTAT0), aic_inb(p, SSTAT1));
4810         printk(INFO_LEAD "SG_CACHEPTR 0x%x, SSTAT2 0x%x, STCNT 0x%x\n",
4811            p->host_no, -1, -1, -1, aic_inb(p, SG_CACHEPTR),
4812            aic_inb(p, SSTAT2), aic_inb(p, STCNT + 2) << 16 |
4813            aic_inb(p, STCNT + 1) << 8 | aic_inb(p, STCNT));
4814         /*
4815          * XXX: Add error handling here
4816          */
4817         break;
4818       }
4819       scb = p->scb_data->scb_array[scb_index];
4820       if(!(scb->flags & SCB_ACTIVE) || (scb->cmd == NULL))
4821       {
4822         printk(WARN_LEAD "invalid scb during SEQ_SG_FIXUP flags:0x%x "
4823                "scb->cmd:0x%p\n", p->host_no, CTL_OF_SCB(scb),
4824                scb->flags, scb->cmd);
4825         printk(INFO_LEAD "SCSISIGI 0x%x, SEQADDR 0x%x, SSTAT0 0x%x, SSTAT1 "
4826            "0x%x\n", p->host_no, CTL_OF_SCB(scb),
4827            aic_inb(p, SCSISIGI),
4828            aic_inb(p, SEQADDR0) | (aic_inb(p, SEQADDR1) << 8),
4829            aic_inb(p, SSTAT0), aic_inb(p, SSTAT1));
4830         printk(INFO_LEAD "SG_CACHEPTR 0x%x, SSTAT2 0x%x, STCNT 0x%x\n",
4831            p->host_no, CTL_OF_SCB(scb), aic_inb(p, SG_CACHEPTR),
4832            aic_inb(p, SSTAT2), aic_inb(p, STCNT + 2) << 16 |
4833            aic_inb(p, STCNT + 1) << 8 | aic_inb(p, STCNT));
4834         break;
4835       }
4836       if(aic7xxx_verbose & VERBOSE_MINOR_ERROR)
4837         printk(INFO_LEAD "Fixing up SG address for sequencer.\n", p->host_no,
4838                CTL_OF_SCB(scb));
4839       /*
4840        * Advance the SG pointer to the next element in the list
4841        */
4842       tmp = aic_inb(p, SG_NEXT);
4843       tmp += SG_SIZEOF;
4844       aic_outb(p, tmp, SG_NEXT);
4845       if( tmp < SG_SIZEOF )
4846         aic_outb(p, aic_inb(p, SG_NEXT + 1) + 1, SG_NEXT + 1);
4847       tmp = aic_inb(p, SG_COUNT) - 1;
4848       aic_outb(p, tmp, SG_COUNT);
4849       sg_addr = le32_to_cpu(scb->sg_list[scb->sg_count - tmp].address);
4850       sg_length = le32_to_cpu(scb->sg_list[scb->sg_count - tmp].length);
4851       /*
4852        * Now stuff the element we just advanced past down onto the
4853        * card so it can be stored in the residual area.
4854        */
4855       aic_outb(p, sg_addr & 0xff, HADDR);
4856       aic_outb(p, (sg_addr >> 8) & 0xff, HADDR + 1);
4857       aic_outb(p, (sg_addr >> 16) & 0xff, HADDR + 2);
4858       aic_outb(p, (sg_addr >> 24) & 0xff, HADDR + 3);
4859       aic_outb(p, sg_length & 0xff, HCNT);
4860       aic_outb(p, (sg_length >> 8) & 0xff, HCNT + 1);
4861       aic_outb(p, (sg_length >> 16) & 0xff, HCNT + 2);
4862       aic_outb(p, (tmp << 2) | ((tmp == 1) ? LAST_SEG : 0), SG_CACHEPTR);
4863       aic_outb(p, aic_inb(p, DMAPARAMS), DFCNTRL);
4864       while(aic_inb(p, SSTAT0) & SDONE) udelay(1);
4865       while(aic_inb(p, DFCNTRL) & (HDMAEN|SCSIEN)) aic_outb(p, 0, DFCNTRL);
4866     }
4867     break;
4868
4869 #ifdef AIC7XXX_NOT_YET 
4870     case TRACEPOINT2:
4871       {
4872         printk(INFO_LEAD "Tracepoint #2 reached.\n", p->host_no,
4873                channel, target, lun);
4874       }
4875       break;
4876
4877     /* XXX Fill these in later */
4878     case MSG_BUFFER_BUSY:
4879       printk("aic7xxx: Message buffer busy.\n");
4880       break;
4881     case MSGIN_PHASEMIS:
4882       printk("aic7xxx: Message-in phasemis.\n");
4883       break;
4884 #endif
4885
4886     default:                   /* unknown */
4887       printk(WARN_LEAD "Unknown SEQINT, INTSTAT 0x%x, SCSISIGI 0x%x.\n",
4888              p->host_no, channel, target, lun, intstat,
4889              aic_inb(p, SCSISIGI));
4890       break;
4891   }
4892
4893   /*
4894    * Clear the sequencer interrupt and unpause the sequencer.
4895    */
4896   unpause_sequencer(p, /* unpause always */ TRUE);
4897 }
4898
4899 /*+F*************************************************************************
4900  * Function:
4901  *   aic7xxx_parse_msg
4902  *
4903  * Description:
4904  *   Parses incoming messages into actions on behalf of
4905  *   aic7xxx_handle_reqinit
4906  *_F*************************************************************************/
4907 static int
4908 aic7xxx_parse_msg(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
4909 {
4910   int reject, reply, done;
4911   unsigned char target_scsirate, tindex;
4912   unsigned short target_mask;
4913   unsigned char target, channel, lun;
4914   unsigned char bus_width, new_bus_width;
4915   unsigned char trans_options, new_trans_options;
4916   unsigned int period, new_period, offset, new_offset, maxsync;
4917   struct aic7xxx_syncrate *syncrate;
4918   struct aic_dev_data *aic_dev;
4919
4920   target = scb->cmd->device->id;
4921   channel = scb->cmd->device->channel;
4922   lun = scb->cmd->device->lun;
4923   reply = reject = done = FALSE;
4924   tindex = TARGET_INDEX(scb->cmd);
4925   aic_dev = AIC_DEV(scb->cmd);
4926   target_scsirate = aic_inb(p, TARG_SCSIRATE + tindex);
4927   target_mask = (0x01 << tindex);
4928
4929   /*
4930    * Parse as much of the message as is available,
4931    * rejecting it if we don't support it.  When
4932    * the entire message is available and has been
4933    * handled, return TRUE indicating that we have
4934    * parsed an entire message.
4935    */
4936
4937   if (p->msg_buf[0] != MSG_EXTENDED)
4938   {
4939     reject = TRUE;
4940   }
4941
4942   /*
4943    * Even if we are an Ultra3 card, don't allow Ultra3 sync rates when
4944    * using the SDTR messages.  We need the PPR messages to enable the
4945    * higher speeds that include things like Dual Edge clocking.
4946    */
4947   if (p->features & AHC_ULTRA2)
4948   {
4949     if ( (aic_inb(p, SBLKCTL) & ENAB40) &&
4950          !(aic_inb(p, SSTAT2) & EXP_ACTIVE) )
4951     {
4952       if (p->features & AHC_ULTRA3)
4953         maxsync = AHC_SYNCRATE_ULTRA3;
4954       else
4955         maxsync = AHC_SYNCRATE_ULTRA2;
4956     }
4957     else
4958     {
4959       maxsync = AHC_SYNCRATE_ULTRA;
4960     }
4961   }
4962   else if (p->features & AHC_ULTRA)
4963   {
4964     maxsync = AHC_SYNCRATE_ULTRA;
4965   }
4966   else
4967   {
4968     maxsync = AHC_SYNCRATE_FAST;
4969   }
4970
4971   /*
4972    * Just accept the length byte outright and perform
4973    * more checking once we know the message type.
4974    */
4975
4976   if ( !reject && (p->msg_len > 2) )
4977   {
4978     switch(p->msg_buf[2])
4979     {
4980       case MSG_EXT_SDTR:
4981       {
4982         
4983         if (p->msg_buf[1] != MSG_EXT_SDTR_LEN)
4984         {
4985           reject = TRUE;
4986           break;
4987         }
4988
4989         if (p->msg_len < (MSG_EXT_SDTR_LEN + 2))
4990         {
4991           break;
4992         }
4993
4994         period = new_period = p->msg_buf[3];
4995         offset = new_offset = p->msg_buf[4];
4996         trans_options = new_trans_options = 0;
4997         bus_width = new_bus_width = target_scsirate & WIDEXFER;
4998
4999         /*
5000          * If our current max syncrate is in the Ultra3 range, bump it back
5001          * down to Ultra2 since we can't negotiate DT transfers using SDTR
5002          */
5003         if(maxsync == AHC_SYNCRATE_ULTRA3)
5004           maxsync = AHC_SYNCRATE_ULTRA2;
5005
5006         /*
5007          * We might have a device that is starting negotiation with us
5008          * before we can start up negotiation with it....be prepared to
5009          * have a device ask for a higher speed then we want to give it
5010          * in that case
5011          */
5012         if ( (scb->flags & (SCB_MSGOUT_SENT|SCB_MSGOUT_SDTR)) !=
5013              (SCB_MSGOUT_SENT|SCB_MSGOUT_SDTR) )
5014         {
5015           if (!(aic_dev->flags & DEVICE_DTR_SCANNED))
5016           {
5017             /*
5018              * We shouldn't get here unless this is a narrow drive, wide
5019              * devices should trigger this same section of code in the WDTR
5020              * handler first instead.
5021              */
5022             aic_dev->goal.width = MSG_EXT_WDTR_BUS_8_BIT;
5023             aic_dev->goal.options = 0;
5024             if(p->user[tindex].offset)
5025             {
5026               aic_dev->needsdtr_copy = 1;
5027               aic_dev->goal.period = max_t(unsigned char, 10,p->user[tindex].period);
5028               if(p->features & AHC_ULTRA2)
5029               {
5030                 aic_dev->goal.offset = MAX_OFFSET_ULTRA2;
5031               }
5032               else
5033               {
5034                 aic_dev->goal.offset = MAX_OFFSET_8BIT;
5035               }
5036             }
5037             else
5038             {
5039               aic_dev->needsdtr_copy = 0;
5040               aic_dev->goal.period = 255;
5041               aic_dev->goal.offset = 0;
5042             }
5043             aic_dev->flags |= DEVICE_DTR_SCANNED | DEVICE_PRINT_DTR;
5044           }
5045           else if (aic_dev->needsdtr_copy == 0)
5046           {
5047             /*
5048              * This is a preemptive message from the target, we've already
5049              * scanned this target and set our options for it, and we
5050              * don't need a SDTR with this target (for whatever reason),
5051              * so reject this incoming SDTR
5052              */
5053             reject = TRUE;
5054             break;
5055           }
5056
5057           /* The device is sending this message first and we have to reply */
5058           reply = TRUE;
5059           
5060           if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
5061           {
5062             printk(INFO_LEAD "Received pre-emptive SDTR message from "
5063                    "target.\n", p->host_no, CTL_OF_SCB(scb));
5064           }
5065           /*
5066            * Validate the values the device passed to us against our SEEPROM
5067            * settings.  We don't have to do this if we aren't replying since
5068            * the device isn't allowed to send values greater than the ones
5069            * we first sent to it.
5070            */
5071           new_period = max_t(unsigned int, period, aic_dev->goal.period);
5072           new_offset = min_t(unsigned int, offset, aic_dev->goal.offset);
5073         }
5074  
5075         /*
5076          * Use our new_period, new_offset, bus_width, and card options
5077          * to determine the actual syncrate settings
5078          */
5079         syncrate = aic7xxx_find_syncrate(p, &new_period, maxsync,
5080                                          &trans_options);
5081         aic7xxx_validate_offset(p, syncrate, &new_offset, bus_width);
5082
5083         /*
5084          * Did we drop to async?  If so, send a reply regardless of whether
5085          * or not we initiated this negotiation.
5086          */
5087         if ((new_offset == 0) && (new_offset != offset))
5088         {
5089           aic_dev->needsdtr_copy = 0;
5090           reply = TRUE;
5091         }
5092         
5093         /*
5094          * Did we start this, if not, or if we went too low and had to
5095          * go async, then send an SDTR back to the target
5096          */
5097         if(reply)
5098         {
5099           /* when sending a reply, make sure that the goal settings are
5100            * updated along with current and active since the code that
5101            * will actually build the message for the sequencer uses the
5102            * goal settings as its guidelines.
5103            */
5104           aic7xxx_set_syncrate(p, syncrate, target, channel, new_period,
5105                                new_offset, trans_options,
5106                                AHC_TRANS_GOAL|AHC_TRANS_ACTIVE|AHC_TRANS_CUR,
5107                                aic_dev);
5108           scb->flags &= ~SCB_MSGOUT_BITS;
5109           scb->flags |= SCB_MSGOUT_SDTR;
5110           aic_outb(p, HOST_MSG, MSG_OUT);
5111           aic_outb(p, aic_inb(p, SCSISIGO) | ATNO, SCSISIGO);
5112         }
5113         else
5114         {
5115           aic7xxx_set_syncrate(p, syncrate, target, channel, new_period,
5116                                new_offset, trans_options,
5117                                AHC_TRANS_ACTIVE|AHC_TRANS_CUR, aic_dev);
5118           aic_dev->needsdtr = 0;
5119         }
5120         done = TRUE;
5121         break;
5122       }
5123       case MSG_EXT_WDTR:
5124       {
5125           
5126         if (p->msg_buf[1] != MSG_EXT_WDTR_LEN)
5127         {
5128           reject = TRUE;
5129           break;
5130         }
5131
5132         if (p->msg_len < (MSG_EXT_WDTR_LEN + 2))
5133         {
5134           break;
5135         }
5136
5137         bus_width = new_bus_width = p->msg_buf[3];
5138
5139         if ( (scb->flags & (SCB_MSGOUT_SENT|SCB_MSGOUT_WDTR)) ==
5140              (SCB_MSGOUT_SENT|SCB_MSGOUT_WDTR) )
5141         {
5142           switch(bus_width)
5143           {
5144             default:
5145             {
5146               reject = TRUE;
5147               if ( (aic7xxx_verbose & VERBOSE_NEGOTIATION2) &&
5148                    ((aic_dev->flags & DEVICE_PRINT_DTR) ||
5149                     (aic7xxx_verbose > 0xffff)) )
5150               {
5151                 printk(INFO_LEAD "Requesting %d bit transfers, rejecting.\n",
5152                   p->host_no, CTL_OF_SCB(scb), 8 * (0x01 << bus_width));
5153               }
5154             } /* We fall through on purpose */
5155             case MSG_EXT_WDTR_BUS_8_BIT:
5156             {
5157               aic_dev->goal.width = MSG_EXT_WDTR_BUS_8_BIT;
5158               aic_dev->needwdtr_copy &= ~target_mask;
5159               break;
5160             }
5161             case MSG_EXT_WDTR_BUS_16_BIT:
5162             {
5163               break;
5164             }
5165           }
5166           aic_dev->needwdtr = 0;
5167           aic7xxx_set_width(p, target, channel, lun, new_bus_width,
5168                             AHC_TRANS_ACTIVE|AHC_TRANS_CUR, aic_dev);
5169         }
5170         else
5171         {
5172           if ( !(aic_dev->flags & DEVICE_DTR_SCANNED) )
5173           {
5174             /* 
5175              * Well, we now know the WDTR and SYNC caps of this device since
5176              * it contacted us first, mark it as such and copy the user stuff
5177              * over to the goal stuff.
5178              */
5179             if( (p->features & AHC_WIDE) && p->user[tindex].width )
5180             {
5181               aic_dev->goal.width = MSG_EXT_WDTR_BUS_16_BIT;
5182               aic_dev->needwdtr_copy = 1;
5183             }
5184             
5185             /*
5186              * Devices that support DT transfers don't start WDTR requests
5187              */
5188             aic_dev->goal.options = 0;
5189
5190             if(p->user[tindex].offset)
5191             {
5192               aic_dev->needsdtr_copy = 1;
5193               aic_dev->goal.period = max_t(unsigned char, 10, p->user[tindex].period);
5194               if(p->features & AHC_ULTRA2)
5195               {
5196                 aic_dev->goal.offset = MAX_OFFSET_ULTRA2;
5197               }
5198               else if( aic_dev->goal.width )
5199               {
5200                 aic_dev->goal.offset = MAX_OFFSET_16BIT;
5201               }
5202               else
5203               {
5204                 aic_dev->goal.offset = MAX_OFFSET_8BIT;
5205               }
5206             } else {
5207               aic_dev->needsdtr_copy = 0;
5208               aic_dev->goal.period = 255;
5209               aic_dev->goal.offset = 0;
5210             }
5211             
5212             aic_dev->flags |= DEVICE_DTR_SCANNED | DEVICE_PRINT_DTR;
5213           }
5214           else if (aic_dev->needwdtr_copy == 0)
5215           {
5216             /*
5217              * This is a preemptive message from the target, we've already
5218              * scanned this target and set our options for it, and we
5219              * don't need a WDTR with this target (for whatever reason),
5220              * so reject this incoming WDTR
5221              */
5222             reject = TRUE;
5223             break;
5224           }
5225
5226           /* The device is sending this message first and we have to reply */
5227           reply = TRUE;
5228
5229           if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
5230           {
5231             printk(INFO_LEAD "Received pre-emptive WDTR message from "
5232                    "target.\n", p->host_no, CTL_OF_SCB(scb));
5233           }
5234           switch(bus_width)
5235           {
5236             case MSG_EXT_WDTR_BUS_16_BIT:
5237             {
5238               if ( (p->features & AHC_WIDE) &&
5239                    (aic_dev->goal.width == MSG_EXT_WDTR_BUS_16_BIT) )
5240               {
5241                 new_bus_width = MSG_EXT_WDTR_BUS_16_BIT;
5242                 break;
5243               }
5244             } /* Fall through if we aren't a wide card */
5245             default:
5246             case MSG_EXT_WDTR_BUS_8_BIT:
5247             {
5248               aic_dev->needwdtr_copy = 0;
5249               new_bus_width = MSG_EXT_WDTR_BUS_8_BIT;
5250               break;
5251             }
5252           }
5253           scb->flags &= ~SCB_MSGOUT_BITS;
5254           scb->flags |= SCB_MSGOUT_WDTR;
5255           aic_dev->needwdtr = 0;
5256           if(aic_dev->dtr_pending == 0)
5257           {
5258             /* there is no other command with SCB_DTR_SCB already set that will
5259              * trigger the release of the dtr_pending bit.  Both set the bit
5260              * and set scb->flags |= SCB_DTR_SCB
5261              */
5262             aic_dev->dtr_pending = 1;
5263             scb->flags |= SCB_DTR_SCB;
5264           }
5265           aic_outb(p, HOST_MSG, MSG_OUT);
5266           aic_outb(p, aic_inb(p, SCSISIGO) | ATNO, SCSISIGO);
5267           /* when sending a reply, make sure that the goal settings are
5268            * updated along with current and active since the code that
5269            * will actually build the message for the sequencer uses the
5270            * goal settings as its guidelines.
5271            */
5272           aic7xxx_set_width(p, target, channel, lun, new_bus_width,
5273                           AHC_TRANS_GOAL|AHC_TRANS_ACTIVE|AHC_TRANS_CUR,
5274                           aic_dev);
5275         }
5276         
5277         /*
5278          * By virtue of the SCSI spec, a WDTR message negates any existing
5279          * SDTR negotiations.  So, even if needsdtr isn't marked for this
5280          * device, we still have to do a new SDTR message if the device
5281          * supports SDTR at all.  Therefore, we check needsdtr_copy instead
5282          * of needstr.
5283          */
5284         aic7xxx_set_syncrate(p, NULL, target, channel, 0, 0, 0,
5285                              AHC_TRANS_ACTIVE|AHC_TRANS_CUR|AHC_TRANS_QUITE,
5286                              aic_dev);
5287         aic_dev->needsdtr = aic_dev->needsdtr_copy;
5288         done = TRUE;
5289         break;
5290       }
5291       case MSG_EXT_PPR:
5292       {
5293         
5294         if (p->msg_buf[1] != MSG_EXT_PPR_LEN)
5295         {
5296           reject = TRUE;
5297           break;
5298         }
5299
5300         if (p->msg_len < (MSG_EXT_PPR_LEN + 2))
5301         {
5302           break;
5303         }
5304
5305         period = new_period = p->msg_buf[3];
5306         offset = new_offset = p->msg_buf[5];
5307         bus_width = new_bus_width = p->msg_buf[6];
5308         trans_options = new_trans_options = p->msg_buf[7] & 0xf;
5309
5310         if(aic7xxx_verbose & VERBOSE_NEGOTIATION2)
5311         {
5312           printk(INFO_LEAD "Parsing PPR message (%d/%d/%d/%d)\n",
5313                  p->host_no, CTL_OF_SCB(scb), period, offset, bus_width,
5314                  trans_options);
5315         }
5316
5317         /*
5318          * We might have a device that is starting negotiation with us
5319          * before we can start up negotiation with it....be prepared to
5320          * have a device ask for a higher speed then we want to give it
5321          * in that case
5322          */
5323         if ( (scb->flags & (SCB_MSGOUT_SENT|SCB_MSGOUT_PPR)) !=
5324              (SCB_MSGOUT_SENT|SCB_MSGOUT_PPR) )
5325         { 
5326           /* Have we scanned the device yet? */
5327           if (!(aic_dev->flags & DEVICE_DTR_SCANNED))
5328           {
5329             /* The device is electing to use PPR messages, so we will too until
5330              * we know better */
5331             aic_dev->needppr = aic_dev->needppr_copy = 1;
5332             aic_dev->needsdtr = aic_dev->needsdtr_copy = 0;
5333             aic_dev->needwdtr = aic_dev->needwdtr_copy = 0;
5334           
5335             /* We know the device is SCSI-3 compliant due to PPR */
5336             aic_dev->flags |= DEVICE_SCSI_3;
5337           
5338             /*
5339              * Not only is the device starting this up, but it also hasn't
5340              * been scanned yet, so this would likely be our TUR or our
5341              * INQUIRY command at scan time, so we need to use the
5342              * settings from the SEEPROM if they existed.  Of course, even
5343              * if we didn't find a SEEPROM, we stuffed default values into
5344              * the user settings anyway, so use those in all cases.
5345              */
5346             aic_dev->goal.width = p->user[tindex].width;
5347             if(p->user[tindex].offset)
5348             {
5349               aic_dev->goal.period = p->user[tindex].period;
5350               aic_dev->goal.options = p->user[tindex].options;
5351               if(p->features & AHC_ULTRA2)
5352               {
5353                 aic_dev->goal.offset = MAX_OFFSET_ULTRA2;
5354               }
5355               else if( aic_dev->goal.width &&
5356                        (bus_width == MSG_EXT_WDTR_BUS_16_BIT) &&
5357                        p->features & AHC_WIDE )
5358               {
5359                 aic_dev->goal.offset = MAX_OFFSET_16BIT;
5360               }
5361               else
5362               {
5363                 aic_dev->goal.offset = MAX_OFFSET_8BIT;
5364               }
5365             }
5366             else
5367             {
5368               aic_dev->goal.period = 255;
5369               aic_dev->goal.offset = 0;
5370               aic_dev->goal.options = 0;
5371             }
5372             aic_dev->flags |= DEVICE_DTR_SCANNED | DEVICE_PRINT_DTR;
5373           }
5374           else if (aic_dev->needppr_copy == 0)
5375           {
5376             /*
5377              * This is a preemptive message from the target, we've already
5378              * scanned this target and set our options for it, and we
5379              * don't need a PPR with this target (for whatever reason),
5380              * so reject this incoming PPR
5381              */
5382             reject = TRUE;
5383             break;
5384           }
5385
5386           /* The device is sending this message first and we have to reply */
5387           reply = TRUE;
5388           
5389           if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
5390           {
5391             printk(INFO_LEAD "Received pre-emptive PPR message from "
5392                    "target.\n", p->host_no, CTL_OF_SCB(scb));
5393           }
5394
5395         }
5396
5397         switch(bus_width)
5398         {
5399           case MSG_EXT_WDTR_BUS_16_BIT:
5400           {
5401             if ( (aic_dev->goal.width == MSG_EXT_WDTR_BUS_16_BIT) &&
5402                             p->features & AHC_WIDE)
5403             {
5404               break;
5405             }
5406           }
5407           default:
5408           {
5409             if ( (aic7xxx_verbose & VERBOSE_NEGOTIATION2) &&
5410                  ((aic_dev->flags & DEVICE_PRINT_DTR) ||
5411                   (aic7xxx_verbose > 0xffff)) )
5412             {
5413               reply = TRUE;
5414               printk(INFO_LEAD "Requesting %d bit transfers, rejecting.\n",
5415                 p->host_no, CTL_OF_SCB(scb), 8 * (0x01 << bus_width));
5416             }
5417           } /* We fall through on purpose */
5418           case MSG_EXT_WDTR_BUS_8_BIT:
5419           {
5420             /*
5421              * According to the spec, if we aren't wide, we also can't be
5422              * Dual Edge so clear the options byte
5423              */
5424             new_trans_options = 0;
5425             new_bus_width = MSG_EXT_WDTR_BUS_8_BIT;
5426             break;
5427           }
5428         }
5429
5430         if(reply)
5431         {
5432           /* when sending a reply, make sure that the goal settings are
5433            * updated along with current and active since the code that
5434            * will actually build the message for the sequencer uses the
5435            * goal settings as its guidelines.
5436            */
5437           aic7xxx_set_width(p, target, channel, lun, new_bus_width,
5438                             AHC_TRANS_GOAL|AHC_TRANS_ACTIVE|AHC_TRANS_CUR,
5439                             aic_dev);
5440           syncrate = aic7xxx_find_syncrate(p, &new_period, maxsync,
5441                                            &new_trans_options);
5442           aic7xxx_validate_offset(p, syncrate, &new_offset, new_bus_width);
5443           aic7xxx_set_syncrate(p, syncrate, target, channel, new_period,
5444                                new_offset, new_trans_options,
5445                                AHC_TRANS_GOAL|AHC_TRANS_ACTIVE|AHC_TRANS_CUR,
5446                                aic_dev);
5447         }
5448         else
5449         {
5450           aic7xxx_set_width(p, target, channel, lun, new_bus_width,
5451                             AHC_TRANS_ACTIVE|AHC_TRANS_CUR, aic_dev);
5452           syncrate = aic7xxx_find_syncrate(p, &new_period, maxsync,
5453                                            &new_trans_options);
5454           aic7xxx_validate_offset(p, syncrate, &new_offset, new_bus_width);
5455           aic7xxx_set_syncrate(p, syncrate, target, channel, new_period,
5456                                new_offset, new_trans_options,
5457                                AHC_TRANS_ACTIVE|AHC_TRANS_CUR, aic_dev);
5458         }
5459
5460         /*
5461          * As it turns out, if we don't *have* to have PPR messages, then
5462          * configure ourselves not to use them since that makes some
5463          * external drive chassis work (those chassis can't parse PPR
5464          * messages and they mangle the SCSI bus until you send a WDTR
5465          * and SDTR that they can understand).
5466          */
5467         if(new_trans_options == 0)
5468         {
5469           aic_dev->needppr = aic_dev->needppr_copy = 0;
5470           if(new_offset)
5471           {
5472             aic_dev->needsdtr = aic_dev->needsdtr_copy = 1;
5473           }
5474           if (new_bus_width)
5475           {
5476             aic_dev->needwdtr = aic_dev->needwdtr_copy = 1;
5477           }
5478         }
5479
5480         if((new_offset == 0) && (offset != 0))
5481         {
5482           /*
5483            * Oops, the syncrate went to low for this card and we fell off
5484            * to async (should never happen with a device that uses PPR
5485            * messages, but have to be complete)
5486            */
5487           reply = TRUE;
5488         }
5489
5490         if(reply)
5491         {
5492           scb->flags &= ~SCB_MSGOUT_BITS;
5493           scb->flags |= SCB_MSGOUT_PPR;
5494           aic_outb(p, HOST_MSG, MSG_OUT);
5495           aic_outb(p, aic_inb(p, SCSISIGO) | ATNO, SCSISIGO);
5496         }
5497         else
5498         {
5499           aic_dev->needppr = 0;
5500         }
5501         done = TRUE;
5502         break;
5503       }
5504       default:
5505       {
5506         reject = TRUE;
5507         break;
5508       }
5509     } /* end of switch(p->msg_type) */
5510   } /* end of if (!reject && (p->msg_len > 2)) */
5511
5512   if (!reply && reject)
5513   {
5514     aic_outb(p, MSG_MESSAGE_REJECT, MSG_OUT);
5515     aic_outb(p, aic_inb(p, SCSISIGO) | ATNO, SCSISIGO);
5516     done = TRUE;
5517   }
5518   return(done);
5519 }
5520
5521
5522 /*+F*************************************************************************
5523  * Function:
5524  *   aic7xxx_handle_reqinit
5525  *
5526  * Description:
5527  *   Interrupt handler for REQINIT interrupts (used to transfer messages to
5528  *    and from devices).
5529  *_F*************************************************************************/
5530 static void
5531 aic7xxx_handle_reqinit(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
5532 {
5533   unsigned char lastbyte;
5534   unsigned char phasemis;
5535   int done = FALSE;
5536
5537   switch(p->msg_type)
5538   {
5539     case MSG_TYPE_INITIATOR_MSGOUT:
5540       {
5541         if (p->msg_len == 0)
5542           panic("aic7xxx: REQINIT with no active message!\n");
5543
5544         lastbyte = (p->msg_index == (p->msg_len - 1));
5545         phasemis = ( aic_inb(p, SCSISIGI) & PHASE_MASK) != P_MESGOUT;
5546
5547         if (lastbyte || phasemis)
5548         {
5549           /* Time to end the message */
5550           p->msg_len = 0;
5551           p->msg_type = MSG_TYPE_NONE;
5552           /*
5553            * NOTE-TO-MYSELF: If you clear the REQINIT after you
5554            * disable REQINITs, then cases of REJECT_MSG stop working
5555            * and hang the bus
5556            */
5557           aic_outb(p, aic_inb(p, SIMODE1) & ~ENREQINIT, SIMODE1);
5558           aic_outb(p, CLRSCSIINT, CLRINT);
5559           p->flags &= ~AHC_HANDLING_REQINITS;
5560
5561           if (phasemis == 0)
5562           {
5563             aic_outb(p, p->msg_buf[p->msg_index], SINDEX);
5564             aic_outb(p, 0, RETURN_1);
5565 #ifdef AIC7XXX_VERBOSE_DEBUGGING
5566             if (aic7xxx_verbose > 0xffff)
5567               printk(INFO_LEAD "Completed sending of REQINIT message.\n",
5568                      p->host_no, CTL_OF_SCB(scb));
5569 #endif
5570           }
5571           else
5572           {
5573             aic_outb(p, MSGOUT_PHASEMIS, RETURN_1);
5574 #ifdef AIC7XXX_VERBOSE_DEBUGGING
5575             if (aic7xxx_verbose > 0xffff)
5576               printk(INFO_LEAD "PHASEMIS while sending REQINIT message.\n",
5577                      p->host_no, CTL_OF_SCB(scb));
5578 #endif
5579           }
5580           unpause_sequencer(p, TRUE);
5581         }
5582         else
5583         {
5584           /*
5585            * Present the byte on the bus (clearing REQINIT) but don't
5586            * unpause the sequencer.
5587            */
5588           aic_outb(p, CLRREQINIT, CLRSINT1);
5589           aic_outb(p, CLRSCSIINT, CLRINT);
5590           aic_outb(p,  p->msg_buf[p->msg_index++], SCSIDATL);
5591         }
5592         break;
5593       }
5594     case MSG_TYPE_INITIATOR_MSGIN:
5595       {
5596         phasemis = ( aic_inb(p, SCSISIGI) & PHASE_MASK ) != P_MESGIN;
5597
5598         if (phasemis == 0)
5599         {
5600           p->msg_len++;
5601           /* Pull the byte in without acking it */
5602           p->msg_buf[p->msg_index] = aic_inb(p, SCSIBUSL);
5603           done = aic7xxx_parse_msg(p, scb);
5604           /* Ack the byte */
5605           aic_outb(p, CLRREQINIT, CLRSINT1);
5606           aic_outb(p, CLRSCSIINT, CLRINT);
5607           aic_inb(p, SCSIDATL);
5608           p->msg_index++;
5609         }
5610         if (phasemis || done)
5611         {
5612 #ifdef AIC7XXX_VERBOSE_DEBUGGING
5613           if (aic7xxx_verbose > 0xffff)
5614           {
5615             if (phasemis)
5616               printk(INFO_LEAD "PHASEMIS while receiving REQINIT message.\n",
5617                      p->host_no, CTL_OF_SCB(scb));
5618             else
5619               printk(INFO_LEAD "Completed receipt of REQINIT message.\n",
5620                      p->host_no, CTL_OF_SCB(scb));
5621           }
5622 #endif
5623           /* Time to end our message session */
5624           p->msg_len = 0;
5625           p->msg_type = MSG_TYPE_NONE;
5626           aic_outb(p, aic_inb(p, SIMODE1) & ~ENREQINIT, SIMODE1);
5627           aic_outb(p, CLRSCSIINT, CLRINT);
5628           p->flags &= ~AHC_HANDLING_REQINITS;
5629           unpause_sequencer(p, TRUE);
5630         }
5631         break;
5632       }
5633     default:
5634       {
5635         panic("aic7xxx: Unknown REQINIT message type.\n");
5636         break;
5637       }
5638   } /* End of switch(p->msg_type) */
5639 }
5640
5641 /*+F*************************************************************************
5642  * Function:
5643  *   aic7xxx_handle_scsiint
5644  *
5645  * Description:
5646  *   Interrupt handler for SCSI interrupts (SCSIINT).
5647  *-F*************************************************************************/
5648 static void
5649 aic7xxx_handle_scsiint(struct aic7xxx_host *p, unsigned char intstat)
5650 {
5651   unsigned char scb_index;
5652   unsigned char status;
5653   struct aic7xxx_scb *scb;
5654   struct aic_dev_data *aic_dev;
5655
5656   scb_index = aic_inb(p, SCB_TAG);
5657   status = aic_inb(p, SSTAT1);
5658
5659   if (scb_index < p->scb_data->numscbs)
5660   {
5661     scb = p->scb_data->scb_array[scb_index];
5662     if ((scb->flags & SCB_ACTIVE) == 0)
5663     {
5664       scb = NULL;
5665     }
5666   }
5667   else
5668   {
5669     scb = NULL;
5670   }
5671
5672
5673   if ((status & SCSIRSTI) != 0)
5674   {
5675     int channel;
5676
5677     if ( (p->chip & AHC_CHIPID_MASK) == AHC_AIC7770 )
5678       channel = (aic_inb(p, SBLKCTL) & SELBUSB) >> 3;
5679     else
5680       channel = 0;
5681
5682     if (aic7xxx_verbose & VERBOSE_RESET)
5683       printk(WARN_LEAD "Someone else reset the channel!!\n",
5684            p->host_no, channel, -1, -1);
5685     if (aic7xxx_panic_on_abort)
5686       aic7xxx_panic_abort(p, NULL);
5687     /*
5688      * Go through and abort all commands for the channel, but do not
5689      * reset the channel again.
5690      */
5691     aic7xxx_reset_channel(p, channel, /* Initiate Reset */ FALSE);
5692     aic7xxx_run_done_queue(p, TRUE);
5693     scb = NULL;
5694   }
5695   else if ( ((status & BUSFREE) != 0) && ((status & SELTO) == 0) )
5696   {
5697     /*
5698      * First look at what phase we were last in.  If it's message-out,
5699      * chances are pretty good that the bus free was in response to
5700      * one of our abort requests.
5701      */
5702     unsigned char lastphase = aic_inb(p, LASTPHASE);
5703     unsigned char saved_tcl = aic_inb(p, SAVED_TCL);
5704     unsigned char target = (saved_tcl >> 4) & 0x0F;
5705     int channel;
5706     int printerror = TRUE;
5707
5708     if ( (p->chip & AHC_CHIPID_MASK) == AHC_AIC7770 )
5709       channel = (aic_inb(p, SBLKCTL) & SELBUSB) >> 3;
5710     else
5711       channel = 0;
5712
5713     aic_outb(p, aic_inb(p, SCSISEQ) & (ENSELI|ENRSELI|ENAUTOATNP),
5714              SCSISEQ);
5715     if (lastphase == P_MESGOUT)
5716     {
5717       unsigned char message;
5718
5719       message = aic_inb(p, SINDEX);
5720
5721       if ((message == MSG_ABORT) || (message == MSG_ABORT_TAG))
5722       {
5723         if (aic7xxx_verbose & VERBOSE_ABORT_PROCESS)
5724           printk(INFO_LEAD "SCB %d abort delivered.\n", p->host_no,
5725             CTL_OF_SCB(scb), scb->hscb->tag);
5726         aic7xxx_reset_device(p, target, channel, ALL_LUNS,
5727                 (message == MSG_ABORT) ? SCB_LIST_NULL : scb->hscb->tag );
5728         aic7xxx_run_done_queue(p, TRUE);
5729         scb = NULL;
5730         printerror = 0;
5731       }
5732       else if (message == MSG_BUS_DEV_RESET)
5733       {
5734         aic7xxx_handle_device_reset(p, target, channel);
5735         scb = NULL;
5736         printerror = 0;
5737       }
5738     }
5739     if ( (scb != NULL) && (scb->flags & SCB_DTR_SCB) ) 
5740     {
5741       /*
5742        * Hmmm...error during a negotiation command.  Either we have a
5743        * borken bus, or the device doesn't like our negotiation message.
5744        * Since we check the INQUIRY data of a device before sending it
5745        * negotiation messages, assume the bus is borken for whatever
5746        * reason.  Complete the command.
5747        */
5748       printerror = 0;
5749       aic7xxx_reset_device(p, target, channel, ALL_LUNS, scb->hscb->tag);
5750       aic7xxx_run_done_queue(p, TRUE);
5751       scb = NULL;
5752     }
5753     if (printerror != 0)
5754     {
5755       if (scb != NULL)
5756       {
5757         unsigned char tag;
5758
5759         if ((scb->hscb->control & TAG_ENB) != 0)
5760         {
5761           tag = scb->hscb->tag;
5762         }
5763         else
5764         {
5765           tag = SCB_LIST_NULL;
5766         }
5767         aic7xxx_reset_device(p, target, channel, ALL_LUNS, tag);
5768         aic7xxx_run_done_queue(p, TRUE);
5769       }
5770       else
5771       {
5772         aic7xxx_reset_device(p, target, channel, ALL_LUNS, SCB_LIST_NULL);
5773         aic7xxx_run_done_queue(p, TRUE);
5774       }
5775       printk(INFO_LEAD "Unexpected busfree, LASTPHASE = 0x%x, "
5776              "SEQADDR = 0x%x\n", p->host_no, channel, target, -1, lastphase,
5777              (aic_inb(p, SEQADDR1) << 8) | aic_inb(p, SEQADDR0));
5778       scb = NULL;
5779     }
5780     aic_outb(p, MSG_NOOP, MSG_OUT);
5781     aic_outb(p, aic_inb(p, SIMODE1) & ~(ENBUSFREE|ENREQINIT),
5782       SIMODE1);
5783     p->flags &= ~AHC_HANDLING_REQINITS;
5784     aic_outb(p, CLRBUSFREE, CLRSINT1);
5785     aic_outb(p, CLRSCSIINT, CLRINT);
5786     restart_sequencer(p);
5787     unpause_sequencer(p, TRUE);
5788   }
5789   else if ((status & SELTO) != 0)
5790   {
5791         unsigned char scbptr;
5792         unsigned char nextscb;
5793         struct scsi_cmnd *cmd;
5794
5795     scbptr = aic_inb(p, WAITING_SCBH);
5796     if (scbptr > p->scb_data->maxhscbs)
5797     {
5798       /*
5799        * I'm still trying to track down exactly how this happens, but until
5800        * I find it, this code will make sure we aren't passing bogus values
5801        * into the SCBPTR register, even if that register will just wrap
5802        * things around, we still don't like having out of range variables.
5803        *
5804        * NOTE: Don't check the aic7xxx_verbose variable, I want this message
5805        * to always be displayed.
5806        */
5807       printk(INFO_LEAD "Invalid WAITING_SCBH value %d, improvising.\n",
5808              p->host_no, -1, -1, -1, scbptr);
5809       if (p->scb_data->maxhscbs > 4)
5810         scbptr &= (p->scb_data->maxhscbs - 1);
5811       else
5812         scbptr &= 0x03;
5813     }
5814     aic_outb(p, scbptr, SCBPTR);
5815     scb_index = aic_inb(p, SCB_TAG);
5816
5817     scb = NULL;
5818     if (scb_index < p->scb_data->numscbs)
5819     {
5820       scb = p->scb_data->scb_array[scb_index];
5821       if ((scb->flags & SCB_ACTIVE) == 0)
5822       {
5823         scb = NULL;
5824       }
5825     }
5826     if (scb == NULL)
5827     {
5828       printk(WARN_LEAD "Referenced SCB %d not valid during SELTO.\n",
5829              p->host_no, -1, -1, -1, scb_index);
5830       printk(KERN_WARNING "        SCSISEQ = 0x%x SEQADDR = 0x%x SSTAT0 = 0x%x "
5831              "SSTAT1 = 0x%x\n", aic_inb(p, SCSISEQ),
5832              aic_inb(p, SEQADDR0) | (aic_inb(p, SEQADDR1) << 8),
5833              aic_inb(p, SSTAT0), aic_inb(p, SSTAT1));
5834       if (aic7xxx_panic_on_abort)
5835         aic7xxx_panic_abort(p, NULL);
5836     }
5837     else
5838     {
5839       cmd = scb->cmd;
5840       cmd->result = (DID_TIME_OUT << 16);
5841
5842       /*
5843        * Clear out this hardware SCB
5844        */
5845       aic_outb(p, 0, SCB_CONTROL);
5846
5847       /*
5848        * Clear out a few values in the card that are in an undetermined
5849        * state.
5850        */
5851       aic_outb(p, MSG_NOOP, MSG_OUT);
5852
5853       /*
5854        * Shift the waiting for selection queue forward
5855        */
5856       nextscb = aic_inb(p, SCB_NEXT);
5857       aic_outb(p, nextscb, WAITING_SCBH);
5858
5859       /*
5860        * Put this SCB back on the free list.
5861        */
5862       aic7xxx_add_curscb_to_free_list(p);
5863 #ifdef AIC7XXX_VERBOSE_DEBUGGING
5864       if (aic7xxx_verbose > 0xffff)
5865         printk(INFO_LEAD "Selection Timeout.\n", p->host_no, CTL_OF_SCB(scb));
5866 #endif
5867       if (scb->flags & SCB_QUEUED_ABORT)
5868       {
5869         /*
5870          * We know that this particular SCB had to be the queued abort since
5871          * the disconnected SCB would have gotten a reconnect instead.
5872          * What we need to do then is to let the command timeout again so
5873          * we get a reset since this abort just failed.
5874          */
5875         cmd->result = 0;
5876         scb = NULL;
5877       }
5878     }
5879     /*
5880      * Keep the sequencer from trying to restart any selections
5881      */
5882     aic_outb(p, aic_inb(p, SCSISEQ) & ~ENSELO, SCSISEQ);
5883     /*
5884      * Make sure the data bits on the bus are released
5885      * Don't do this on 7770 chipsets, it makes them give us
5886      * a BRKADDRINT and kills the card.
5887      */
5888     if( (p->chip & ~AHC_CHIPID_MASK) == AHC_PCI )
5889       aic_outb(p, 0, SCSIBUSL);
5890
5891     /*
5892      * Delay for the selection timeout delay period then stop the selection
5893      */
5894     udelay(301);
5895     aic_outb(p, CLRSELINGO, CLRSINT0);
5896     /*
5897      * Clear out all the interrupt status bits
5898      */
5899     aic_outb(p, aic_inb(p, SIMODE1) & ~(ENREQINIT|ENBUSFREE), SIMODE1);
5900     p->flags &= ~AHC_HANDLING_REQINITS;
5901     aic_outb(p, CLRSELTIMEO | CLRBUSFREE, CLRSINT1);
5902     aic_outb(p, CLRSCSIINT, CLRINT);
5903     /*
5904      * Restarting the sequencer will stop the selection and make sure devices
5905      * are allowed to reselect in.
5906      */
5907     restart_sequencer(p);
5908     unpause_sequencer(p, TRUE);
5909   }
5910   else if (scb == NULL)
5911   {
5912     printk(WARN_LEAD "aic7xxx_isr - referenced scb not valid "
5913            "during scsiint 0x%x scb(%d)\n"
5914            "      SIMODE0 0x%x, SIMODE1 0x%x, SSTAT0 0x%x, SEQADDR 0x%x\n",
5915            p->host_no, -1, -1, -1, status, scb_index, aic_inb(p, SIMODE0),
5916            aic_inb(p, SIMODE1), aic_inb(p, SSTAT0),
5917            (aic_inb(p, SEQADDR1) << 8) | aic_inb(p, SEQADDR0));
5918     /*
5919      * Turn off the interrupt and set status to zero, so that it
5920      * falls through the rest of the SCSIINT code.
5921      */
5922     aic_outb(p, status, CLRSINT1);
5923     aic_outb(p, CLRSCSIINT, CLRINT);
5924     unpause_sequencer(p, /* unpause always */ TRUE);
5925     scb = NULL;
5926   }
5927   else if (status & SCSIPERR)
5928   {
5929     /*
5930      * Determine the bus phase and queue an appropriate message.
5931      */
5932         char  *phase;
5933         struct scsi_cmnd *cmd;
5934         unsigned char mesg_out = MSG_NOOP;
5935         unsigned char lastphase = aic_inb(p, LASTPHASE);
5936         unsigned char sstat2 = aic_inb(p, SSTAT2);
5937
5938     cmd = scb->cmd;
5939     switch (lastphase)
5940     {
5941       case P_DATAOUT:
5942         phase = "Data-Out";
5943         break;
5944       case P_DATAIN:
5945         phase = "Data-In";
5946         mesg_out = MSG_INITIATOR_DET_ERR;
5947         break;
5948       case P_COMMAND:
5949         phase = "Command";
5950         break;
5951       case P_MESGOUT:
5952         phase = "Message-Out";
5953         break;
5954       case P_STATUS:
5955         phase = "Status";
5956         mesg_out = MSG_INITIATOR_DET_ERR;
5957         break;
5958       case P_MESGIN:
5959         phase = "Message-In";
5960         mesg_out = MSG_PARITY_ERROR;
5961         break;
5962       default:
5963         phase = "unknown";
5964         break;
5965     }
5966
5967     /*
5968      * A parity error has occurred during a data
5969      * transfer phase. Flag it and continue.
5970      */
5971     if( (p->features & AHC_ULTRA3) && 
5972         (aic_inb(p, SCSIRATE) & AHC_SYNCRATE_CRC) &&
5973         (lastphase == P_DATAIN) )
5974     {
5975       printk(WARN_LEAD "CRC error during %s phase.\n",
5976              p->host_no, CTL_OF_SCB(scb), phase);
5977       if(sstat2 & CRCVALERR)
5978       {
5979         printk(WARN_LEAD "  CRC error in intermediate CRC packet.\n",
5980                p->host_no, CTL_OF_SCB(scb));
5981       }
5982       if(sstat2 & CRCENDERR)
5983       {
5984         printk(WARN_LEAD "  CRC error in ending CRC packet.\n",
5985                p->host_no, CTL_OF_SCB(scb));
5986       }
5987       if(sstat2 & CRCREQERR)
5988       {
5989         printk(WARN_LEAD "  Target incorrectly requested a CRC packet.\n",
5990                p->host_no, CTL_OF_SCB(scb));
5991       }
5992       if(sstat2 & DUAL_EDGE_ERROR)
5993       {
5994         printk(WARN_LEAD "  Dual Edge transmission error.\n",
5995                p->host_no, CTL_OF_SCB(scb));
5996       }
5997     }
5998     else if( (lastphase == P_MESGOUT) &&
5999              (scb->flags & SCB_MSGOUT_PPR) )
6000     {
6001       /*
6002        * As per the draft specs, any device capable of supporting any of
6003        * the option values other than 0 are not allowed to reject the
6004        * PPR message.  Instead, they must negotiate out what they do
6005        * support instead of rejecting our offering or else they cause
6006        * a parity error during msg_out phase to signal that they don't
6007        * like our settings.
6008        */
6009       aic_dev = AIC_DEV(scb->cmd);
6010       aic_dev->needppr = aic_dev->needppr_copy = 0;
6011       aic7xxx_set_width(p, scb->cmd->device->id, scb->cmd->device->channel, scb->cmd->device->lun,
6012                         MSG_EXT_WDTR_BUS_8_BIT,
6013                         (AHC_TRANS_ACTIVE|AHC_TRANS_CUR|AHC_TRANS_QUITE),
6014                         aic_dev);
6015       aic7xxx_set_syncrate(p, NULL, scb->cmd->device->id, scb->cmd->device->channel, 0, 0,
6016                            0, AHC_TRANS_ACTIVE|AHC_TRANS_CUR|AHC_TRANS_QUITE,
6017                            aic_dev);
6018       aic_dev->goal.options = 0;
6019       scb->flags &= ~SCB_MSGOUT_BITS;
6020       if(aic7xxx_verbose & VERBOSE_NEGOTIATION2)
6021       {
6022         printk(INFO_LEAD "parity error during PPR message, reverting "
6023                "to WDTR/SDTR\n", p->host_no, CTL_OF_SCB(scb));
6024       }
6025       if ( aic_dev->goal.width )
6026       {
6027         aic_dev->needwdtr = aic_dev->needwdtr_copy = 1;
6028       }
6029       if ( aic_dev->goal.offset )
6030       {
6031         if( aic_dev->goal.period <= 9 )
6032         {
6033           aic_dev->goal.period = 10;
6034         }
6035         aic_dev->needsdtr = aic_dev->needsdtr_copy = 1;
6036       }
6037       scb = NULL;
6038     }
6039
6040     /*
6041      * We've set the hardware to assert ATN if we get a parity
6042      * error on "in" phases, so all we need to do is stuff the
6043      * message buffer with the appropriate message.  "In" phases
6044      * have set mesg_out to something other than MSG_NOP.
6045      */
6046     if (mesg_out != MSG_NOOP)
6047     {
6048       aic_outb(p, mesg_out, MSG_OUT);
6049       aic_outb(p, aic_inb(p, SCSISIGI) | ATNO, SCSISIGO);
6050       scb = NULL;
6051     }
6052     aic_outb(p, CLRSCSIPERR, CLRSINT1);
6053     aic_outb(p, CLRSCSIINT, CLRINT);
6054     unpause_sequencer(p, /* unpause_always */ TRUE);
6055   }
6056   else if ( (status & REQINIT) &&
6057             (p->flags & AHC_HANDLING_REQINITS) )
6058   {
6059 #ifdef AIC7XXX_VERBOSE_DEBUGGING
6060     if (aic7xxx_verbose > 0xffff)
6061       printk(INFO_LEAD "Handling REQINIT, SSTAT1=0x%x.\n", p->host_no,
6062              CTL_OF_SCB(scb), aic_inb(p, SSTAT1));
6063 #endif
6064     aic7xxx_handle_reqinit(p, scb);
6065     return;
6066   }
6067   else
6068   {
6069     /*
6070      * We don't know what's going on. Turn off the
6071      * interrupt source and try to continue.
6072      */
6073     if (aic7xxx_verbose & VERBOSE_SCSIINT)
6074       printk(INFO_LEAD "Unknown SCSIINT status, SSTAT1(0x%x).\n",
6075         p->host_no, -1, -1, -1, status);
6076     aic_outb(p, status, CLRSINT1);
6077     aic_outb(p, CLRSCSIINT, CLRINT);
6078     unpause_sequencer(p, /* unpause always */ TRUE);
6079     scb = NULL;
6080   }
6081   if (scb != NULL)
6082   {
6083     aic7xxx_done(p, scb);
6084   }
6085 }
6086
6087 #ifdef AIC7XXX_VERBOSE_DEBUGGING
6088 static void
6089 aic7xxx_check_scbs(struct aic7xxx_host *p, char *buffer)
6090 {
6091   unsigned char saved_scbptr, free_scbh, dis_scbh, wait_scbh, temp;
6092   int i, bogus, lost;
6093   static unsigned char scb_status[AIC7XXX_MAXSCB];
6094
6095 #define SCB_NO_LIST 0
6096 #define SCB_FREE_LIST 1
6097 #define SCB_WAITING_LIST 2
6098 #define SCB_DISCONNECTED_LIST 4
6099 #define SCB_CURRENTLY_ACTIVE 8
6100
6101   /*
6102    * Note, these checks will fail on a regular basis once the machine moves
6103    * beyond the bus scan phase.  The problem is race conditions concerning
6104    * the scbs and where they are linked in.  When you have 30 or so commands
6105    * outstanding on the bus, and run this twice with every interrupt, the
6106    * chances get pretty good that you'll catch the sequencer with an SCB
6107    * only partially linked in.  Therefore, once we pass the scan phase
6108    * of the bus, we really should disable this function.
6109    */
6110   bogus = FALSE;
6111   memset(&scb_status[0], 0, sizeof(scb_status));
6112   pause_sequencer(p);
6113   saved_scbptr = aic_inb(p, SCBPTR);
6114   if (saved_scbptr >= p->scb_data->maxhscbs)
6115   {
6116     printk("Bogus SCBPTR %d\n", saved_scbptr);
6117     bogus = TRUE;
6118   }
6119   scb_status[saved_scbptr] = SCB_CURRENTLY_ACTIVE;
6120   free_scbh = aic_inb(p, FREE_SCBH);
6121   if ( (free_scbh != SCB_LIST_NULL) &&
6122        (free_scbh >= p->scb_data->maxhscbs) )
6123   {
6124     printk("Bogus FREE_SCBH %d\n", free_scbh);
6125     bogus = TRUE;
6126   }
6127   else
6128   {
6129     temp = free_scbh;
6130     while( (temp != SCB_LIST_NULL) && (temp < p->scb_data->maxhscbs) )
6131     {
6132       if(scb_status[temp] & 0x07)
6133       {
6134         printk("HSCB %d on multiple lists, status 0x%02x", temp,
6135                scb_status[temp] | SCB_FREE_LIST);
6136         bogus = TRUE;
6137       }
6138       scb_status[temp] |= SCB_FREE_LIST;
6139       aic_outb(p, temp, SCBPTR);
6140       temp = aic_inb(p, SCB_NEXT);
6141     }
6142   }
6143
6144   dis_scbh = aic_inb(p, DISCONNECTED_SCBH);
6145   if ( (dis_scbh != SCB_LIST_NULL) &&
6146        (dis_scbh >= p->scb_data->maxhscbs) )
6147   {
6148     printk("Bogus DISCONNECTED_SCBH %d\n", dis_scbh);
6149     bogus = TRUE;
6150   }
6151   else
6152   {
6153     temp = dis_scbh;
6154     while( (temp != SCB_LIST_NULL) && (temp < p->scb_data->maxhscbs) )
6155     {
6156       if(scb_status[temp] & 0x07)
6157       {
6158         printk("HSCB %d on multiple lists, status 0x%02x", temp,
6159                scb_status[temp] | SCB_DISCONNECTED_LIST);
6160         bogus = TRUE;
6161       }
6162       scb_status[temp] |= SCB_DISCONNECTED_LIST;
6163       aic_outb(p, temp, SCBPTR);
6164       temp = aic_inb(p, SCB_NEXT);
6165     }
6166   }
6167   
6168   wait_scbh = aic_inb(p, WAITING_SCBH);
6169   if ( (wait_scbh != SCB_LIST_NULL) &&
6170        (wait_scbh >= p->scb_data->maxhscbs) )
6171   {
6172     printk("Bogus WAITING_SCBH %d\n", wait_scbh);
6173     bogus = TRUE;
6174   }
6175   else
6176   {
6177     temp = wait_scbh;
6178     while( (temp != SCB_LIST_NULL) && (temp < p->scb_data->maxhscbs) )
6179     {
6180       if(scb_status[temp] & 0x07)
6181       {
6182         printk("HSCB %d on multiple lists, status 0x%02x", temp,
6183                scb_status[temp] | SCB_WAITING_LIST);
6184         bogus = TRUE;
6185       }
6186       scb_status[temp] |= SCB_WAITING_LIST;
6187       aic_outb(p, temp, SCBPTR);
6188       temp = aic_inb(p, SCB_NEXT);
6189     }
6190   }
6191
6192   lost=0;
6193   for(i=0; i < p->scb_data->maxhscbs; i++)
6194   {
6195     aic_outb(p, i, SCBPTR);
6196     temp = aic_inb(p, SCB_NEXT);
6197     if ( ((temp != SCB_LIST_NULL) &&
6198           (temp >= p->scb_data->maxhscbs)) )
6199     {
6200       printk("HSCB %d bad, SCB_NEXT invalid(%d).\n", i, temp);
6201       bogus = TRUE;
6202     }
6203     if ( temp == i )
6204     {
6205       printk("HSCB %d bad, SCB_NEXT points to self.\n", i);
6206       bogus = TRUE;
6207     }
6208     if (scb_status[i] == 0)
6209       lost++;
6210     if (lost > 1)
6211     {
6212       printk("Too many lost scbs.\n");
6213       bogus=TRUE;
6214     }
6215   }
6216   aic_outb(p, saved_scbptr, SCBPTR);
6217   unpause_sequencer(p, FALSE);
6218   if (bogus)
6219   {
6220     printk("Bogus parameters found in card SCB array structures.\n");
6221     printk("%s\n", buffer);
6222     aic7xxx_panic_abort(p, NULL);
6223   }
6224   return;
6225 }
6226 #endif
6227
6228
6229 /*+F*************************************************************************
6230  * Function:
6231  *   aic7xxx_handle_command_completion_intr
6232  *
6233  * Description:
6234  *   SCSI command completion interrupt handler.
6235  *-F*************************************************************************/
6236 static void
6237 aic7xxx_handle_command_completion_intr(struct aic7xxx_host *p)
6238 {
6239         struct aic7xxx_scb *scb = NULL;
6240         struct aic_dev_data *aic_dev;
6241         struct scsi_cmnd *cmd;
6242         unsigned char scb_index, tindex;
6243
6244 #ifdef AIC7XXX_VERBOSE_DEBUGGING
6245   if( (p->isr_count < 16) && (aic7xxx_verbose > 0xffff) )
6246     printk(INFO_LEAD "Command Complete Int.\n", p->host_no, -1, -1, -1);
6247 #endif
6248     
6249   /*
6250    * Read the INTSTAT location after clearing the CMDINT bit.  This forces
6251    * any posted PCI writes to flush to memory.  Gerard Roudier suggested
6252    * this fix to the possible race of clearing the CMDINT bit but not
6253    * having all command bytes flushed onto the qoutfifo.
6254    */
6255   aic_outb(p, CLRCMDINT, CLRINT);
6256   aic_inb(p, INTSTAT);
6257   /*
6258    * The sequencer will continue running when it
6259    * issues this interrupt. There may be >1 commands
6260    * finished, so loop until we've processed them all.
6261    */
6262
6263   while (p->qoutfifo[p->qoutfifonext] != SCB_LIST_NULL)
6264   {
6265     scb_index = p->qoutfifo[p->qoutfifonext];
6266     p->qoutfifo[p->qoutfifonext++] = SCB_LIST_NULL;
6267     if ( scb_index >= p->scb_data->numscbs )
6268     {
6269       printk(WARN_LEAD "CMDCMPLT with invalid SCB index %d\n", p->host_no,
6270         -1, -1, -1, scb_index);
6271       continue;
6272     }
6273     scb = p->scb_data->scb_array[scb_index];
6274     if (!(scb->flags & SCB_ACTIVE) || (scb->cmd == NULL))
6275     {
6276       printk(WARN_LEAD "CMDCMPLT without command for SCB %d, SCB flags "
6277         "0x%x, cmd 0x%lx\n", p->host_no, -1, -1, -1, scb_index, scb->flags,
6278         (unsigned long) scb->cmd);
6279       continue;
6280     }
6281     tindex = TARGET_INDEX(scb->cmd);
6282     aic_dev = AIC_DEV(scb->cmd);
6283     if (scb->flags & SCB_QUEUED_ABORT)
6284     {
6285       pause_sequencer(p);
6286       if ( ((aic_inb(p, LASTPHASE) & PHASE_MASK) != P_BUSFREE) &&
6287            (aic_inb(p, SCB_TAG) == scb->hscb->tag) )
6288       {
6289         unpause_sequencer(p, FALSE);
6290         continue;
6291       }
6292       aic7xxx_reset_device(p, scb->cmd->device->id, scb->cmd->device->channel,
6293         scb->cmd->device->lun, scb->hscb->tag);
6294       scb->flags &= ~(SCB_QUEUED_FOR_DONE | SCB_RESET | SCB_ABORT |
6295         SCB_QUEUED_ABORT);
6296       unpause_sequencer(p, FALSE);
6297     }
6298     else if (scb->flags & SCB_ABORT)
6299     {
6300       /*
6301        * We started to abort this, but it completed on us, let it
6302        * through as successful
6303        */
6304       scb->flags &= ~(SCB_ABORT|SCB_RESET);
6305     }
6306     else if (scb->flags & SCB_SENSE)
6307     {
6308       char *buffer = &scb->cmd->sense_buffer[0];
6309
6310       if (buffer[12] == 0x47 || buffer[12] == 0x54)
6311       {
6312         /*
6313          * Signal that we need to re-negotiate things.
6314          */
6315         aic_dev->needppr = aic_dev->needppr_copy;
6316         aic_dev->needsdtr = aic_dev->needsdtr_copy;
6317         aic_dev->needwdtr = aic_dev->needwdtr_copy;
6318       }
6319     }
6320     cmd = scb->cmd;
6321     if (scb->hscb->residual_SG_segment_count != 0)
6322     {
6323       aic7xxx_calculate_residual(p, scb);
6324     }
6325     cmd->result |= (aic7xxx_error(cmd) << 16);
6326     aic7xxx_done(p, scb);
6327   }
6328 }
6329
6330 /*+F*************************************************************************
6331  * Function:
6332  *   aic7xxx_isr
6333  *
6334  * Description:
6335  *   SCSI controller interrupt handler.
6336  *-F*************************************************************************/
6337 static void
6338 aic7xxx_isr(void *dev_id)
6339 {
6340   struct aic7xxx_host *p;
6341   unsigned char intstat;
6342
6343   p = dev_id;
6344
6345   /*
6346    * Just a few sanity checks.  Make sure that we have an int pending.
6347    * Also, if PCI, then we are going to check for a PCI bus error status
6348    * should we get too many spurious interrupts.
6349    */
6350   if (!((intstat = aic_inb(p, INTSTAT)) & INT_PEND))
6351   {
6352 #ifdef CONFIG_PCI
6353     if ( (p->chip & AHC_PCI) && (p->spurious_int > 500) &&
6354         !(p->flags & AHC_HANDLING_REQINITS) )
6355     {
6356       if ( aic_inb(p, ERROR) & PCIERRSTAT )
6357       {
6358         aic7xxx_pci_intr(p);
6359       }
6360       p->spurious_int = 0;
6361     }
6362     else if ( !(p->flags & AHC_HANDLING_REQINITS) )
6363     {
6364       p->spurious_int++;
6365     }
6366 #endif
6367     return;
6368   }
6369
6370   p->spurious_int = 0;
6371
6372   /*
6373    * Keep track of interrupts for /proc/scsi
6374    */
6375   p->isr_count++;
6376
6377 #ifdef AIC7XXX_VERBOSE_DEBUGGING
6378   if ( (p->isr_count < 16) && (aic7xxx_verbose > 0xffff) &&
6379        (aic7xxx_panic_on_abort) && (p->flags & AHC_PAGESCBS) )
6380     aic7xxx_check_scbs(p, "Bogus settings at start of interrupt.");
6381 #endif
6382
6383   /*
6384    * Handle all the interrupt sources - especially for SCSI
6385    * interrupts, we won't get a second chance at them.
6386    */
6387   if (intstat & CMDCMPLT)
6388   {
6389     aic7xxx_handle_command_completion_intr(p);
6390   }
6391
6392   if (intstat & BRKADRINT)
6393   {
6394     int i;
6395     unsigned char errno = aic_inb(p, ERROR);
6396
6397     printk(KERN_ERR "(scsi%d) BRKADRINT error(0x%x):\n", p->host_no, errno);
6398     for (i = 0; i < ARRAY_SIZE(hard_error); i++)
6399     {
6400       if (errno & hard_error[i].errno)
6401       {
6402         printk(KERN_ERR "  %s\n", hard_error[i].errmesg);
6403       }
6404     }
6405     printk(KERN_ERR "(scsi%d)   SEQADDR=0x%x\n", p->host_no,
6406       (((aic_inb(p, SEQADDR1) << 8) & 0x100) | aic_inb(p, SEQADDR0)));
6407     if (aic7xxx_panic_on_abort)
6408       aic7xxx_panic_abort(p, NULL);
6409 #ifdef CONFIG_PCI
6410     if (errno & PCIERRSTAT)
6411       aic7xxx_pci_intr(p);
6412 #endif
6413     if (errno & (SQPARERR | ILLOPCODE | ILLSADDR))
6414     {
6415       panic("aic7xxx: unrecoverable BRKADRINT.\n");
6416     }
6417     if (errno & ILLHADDR)
6418     {
6419       printk(KERN_ERR "(scsi%d) BUG! Driver accessed chip without first "
6420              "pausing controller!\n", p->host_no);
6421     }
6422 #ifdef AIC7XXX_VERBOSE_DEBUGGING
6423     if (errno & DPARERR)
6424     {
6425       if (aic_inb(p, DMAPARAMS) & DIRECTION)
6426         printk("(scsi%d) while DMAing SCB from host to card.\n", p->host_no);
6427       else
6428         printk("(scsi%d) while DMAing SCB from card to host.\n", p->host_no);
6429     }
6430 #endif
6431     aic_outb(p, CLRPARERR | CLRBRKADRINT, CLRINT);
6432     unpause_sequencer(p, FALSE);
6433   }
6434
6435   if (intstat & SEQINT)
6436   {
6437     /*
6438      * Read the CCSCBCTL register to work around a bug in the Ultra2 cards
6439      */
6440     if(p->features & AHC_ULTRA2)
6441     {
6442       aic_inb(p, CCSCBCTL);
6443     }
6444     aic7xxx_handle_seqint(p, intstat);
6445   }
6446
6447   if (intstat & SCSIINT)
6448   {
6449     aic7xxx_handle_scsiint(p, intstat);
6450   }
6451
6452 #ifdef AIC7XXX_VERBOSE_DEBUGGING
6453   if ( (p->isr_count < 16) && (aic7xxx_verbose > 0xffff) &&
6454        (aic7xxx_panic_on_abort) && (p->flags & AHC_PAGESCBS) )
6455     aic7xxx_check_scbs(p, "Bogus settings at end of interrupt.");
6456 #endif
6457
6458 }
6459
6460 /*+F*************************************************************************
6461  * Function:
6462  *   do_aic7xxx_isr
6463  *
6464  * Description:
6465  *   This is a gross hack to solve a problem in linux kernels 2.1.85 and
6466  *   above.  Please, children, do not try this at home, and if you ever see
6467  *   anything like it, please inform the Gross Hack Police immediately
6468  *-F*************************************************************************/
6469 static irqreturn_t
6470 do_aic7xxx_isr(int irq, void *dev_id)
6471 {
6472   unsigned long cpu_flags;
6473   struct aic7xxx_host *p;
6474   
6475   p = dev_id;
6476   if(!p)
6477     return IRQ_NONE;
6478   spin_lock_irqsave(p->host->host_lock, cpu_flags);
6479   p->flags |= AHC_IN_ISR;
6480   do
6481   {
6482     aic7xxx_isr(dev_id);
6483   } while ( (aic_inb(p, INTSTAT) & INT_PEND) );
6484   aic7xxx_done_cmds_complete(p);
6485   aic7xxx_run_waiting_queues(p);
6486   p->flags &= ~AHC_IN_ISR;
6487   spin_unlock_irqrestore(p->host->host_lock, cpu_flags);
6488
6489   return IRQ_HANDLED;
6490 }
6491
6492 /*+F*************************************************************************
6493  * Function:
6494  *   aic7xxx_init_transinfo
6495  *
6496  * Description:
6497  *   Set up the initial aic_dev values from the BIOS settings and from
6498  *   INQUIRY results
6499  *-F*************************************************************************/
6500 static void
6501 aic7xxx_init_transinfo(struct aic7xxx_host *p, struct aic_dev_data *aic_dev)
6502 {
6503   struct scsi_device *sdpnt = aic_dev->SDptr;
6504   unsigned char tindex;
6505
6506   tindex = sdpnt->id | (sdpnt->channel << 3);
6507   if (!(aic_dev->flags & DEVICE_DTR_SCANNED))
6508   {
6509     aic_dev->flags |= DEVICE_DTR_SCANNED;
6510
6511     if ( sdpnt->wdtr && (p->features & AHC_WIDE) )
6512     {
6513       aic_dev->needwdtr = aic_dev->needwdtr_copy = 1;
6514       aic_dev->goal.width = p->user[tindex].width;
6515     }
6516     else
6517     {
6518       aic_dev->needwdtr = aic_dev->needwdtr_copy = 0;
6519       pause_sequencer(p);
6520       aic7xxx_set_width(p, sdpnt->id, sdpnt->channel, sdpnt->lun,
6521                         MSG_EXT_WDTR_BUS_8_BIT, (AHC_TRANS_ACTIVE |
6522                                                  AHC_TRANS_GOAL |
6523                                                  AHC_TRANS_CUR), aic_dev );
6524       unpause_sequencer(p, FALSE);
6525     }
6526     if ( sdpnt->sdtr && p->user[tindex].offset )
6527     {
6528       aic_dev->goal.period = p->user[tindex].period;
6529       aic_dev->goal.options = p->user[tindex].options;
6530       if (p->features & AHC_ULTRA2)
6531         aic_dev->goal.offset = MAX_OFFSET_ULTRA2;
6532       else if (aic_dev->goal.width == MSG_EXT_WDTR_BUS_16_BIT)
6533         aic_dev->goal.offset = MAX_OFFSET_16BIT;
6534       else
6535         aic_dev->goal.offset = MAX_OFFSET_8BIT;
6536       if ( sdpnt->ppr && p->user[tindex].period <= 9 &&
6537              p->user[tindex].options )
6538       {
6539         aic_dev->needppr = aic_dev->needppr_copy = 1;
6540         aic_dev->needsdtr = aic_dev->needsdtr_copy = 0;
6541         aic_dev->needwdtr = aic_dev->needwdtr_copy = 0;
6542         aic_dev->flags |= DEVICE_SCSI_3;
6543       }
6544       else
6545       {
6546         aic_dev->needsdtr = aic_dev->needsdtr_copy = 1;
6547         aic_dev->goal.period = max_t(unsigned char, 10, aic_dev->goal.period);
6548         aic_dev->goal.options = 0;
6549       }
6550     }
6551     else
6552     {
6553       aic_dev->needsdtr = aic_dev->needsdtr_copy = 0;
6554       aic_dev->goal.period = 255;
6555       aic_dev->goal.offset = 0;
6556       aic_dev->goal.options = 0;
6557     }
6558     aic_dev->flags |= DEVICE_PRINT_DTR;
6559   }
6560 }
6561
6562 /*+F*************************************************************************
6563  * Function:
6564  *   aic7xxx_slave_alloc
6565  *
6566  * Description:
6567  *   Set up the initial aic_dev struct pointers
6568  *-F*************************************************************************/
6569 static int
6570 aic7xxx_slave_alloc(struct scsi_device *SDptr)
6571 {
6572   struct aic7xxx_host *p = (struct aic7xxx_host *)SDptr->host->hostdata;
6573   struct aic_dev_data *aic_dev;
6574
6575   aic_dev = kmalloc(sizeof(struct aic_dev_data), GFP_KERNEL);
6576   if(!aic_dev)
6577     return 1;
6578   /*
6579    * Check to see if channel was scanned.
6580    */
6581   
6582   if (!(p->flags & AHC_A_SCANNED) && (SDptr->channel == 0))
6583   {
6584     if (aic7xxx_verbose & VERBOSE_PROBE2)
6585       printk(INFO_LEAD "Scanning channel for devices.\n",
6586         p->host_no, 0, -1, -1);
6587     p->flags |= AHC_A_SCANNED;
6588   }
6589   else
6590   {
6591     if (!(p->flags & AHC_B_SCANNED) && (SDptr->channel == 1))
6592     {
6593       if (aic7xxx_verbose & VERBOSE_PROBE2)
6594         printk(INFO_LEAD "Scanning channel for devices.\n",
6595           p->host_no, 1, -1, -1);
6596       p->flags |= AHC_B_SCANNED;
6597     }
6598   }
6599
6600   memset(aic_dev, 0, sizeof(struct aic_dev_data));
6601   SDptr->hostdata = aic_dev;
6602   aic_dev->SDptr = SDptr;
6603   aic_dev->max_q_depth = 1;
6604   aic_dev->temp_q_depth = 1;
6605   scbq_init(&aic_dev->delayed_scbs);
6606   INIT_LIST_HEAD(&aic_dev->list);
6607   list_add_tail(&aic_dev->list, &p->aic_devs);
6608   return 0;
6609 }
6610
6611 /*+F*************************************************************************
6612  * Function:
6613  *   aic7xxx_device_queue_depth
6614  *
6615  * Description:
6616  *   Determines the queue depth for a given device.  There are two ways
6617  *   a queue depth can be obtained for a tagged queueing device.  One
6618  *   way is the default queue depth which is determined by whether
6619  *   aic7xxx_default_queue_depth.  The other is by the aic7xxx_tag_info
6620  *   array.
6621  *
6622  *   If tagged queueing isn't supported on the device, then we set the
6623  *   depth to p->host->hostt->cmd_per_lun for internal driver queueing.
6624  *   as the default queue depth.  Otherwise, we use either 4 or 8 as the
6625  *   default queue depth (dependent on the number of hardware SCBs).
6626  *   The other way we determine queue depth is through the use of the
6627  *   aic7xxx_tag_info array which is enabled by defining
6628  *   AIC7XXX_TAGGED_QUEUEING_BY_DEVICE.  This array can be initialized
6629  *   with queue depths for individual devices.  It also allows tagged
6630  *   queueing to be [en|dis]abled for a specific adapter.
6631  *-F*************************************************************************/
6632 static void
6633 aic7xxx_device_queue_depth(struct aic7xxx_host *p, struct scsi_device *device)
6634 {
6635   int tag_enabled = FALSE;
6636   struct aic_dev_data *aic_dev = device->hostdata;
6637   unsigned char tindex;
6638
6639   tindex = device->id | (device->channel << 3);
6640
6641   if (device->simple_tags)
6642     return; // We've already enabled this device
6643
6644   if (device->tagged_supported)
6645   {
6646     tag_enabled = TRUE;
6647
6648     if (!(p->discenable & (1 << tindex)))
6649     {
6650       if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
6651         printk(INFO_LEAD "Disconnection disabled, unable to "
6652              "enable tagged queueing.\n",
6653              p->host_no, device->channel, device->id, device->lun);
6654       tag_enabled = FALSE;
6655     }
6656     else
6657     {
6658       if (p->instance >= ARRAY_SIZE(aic7xxx_tag_info))
6659       {
6660         static int print_warning = TRUE;
6661         if(print_warning)
6662         {
6663           printk(KERN_INFO "aic7xxx: WARNING, insufficient tag_info instances for"
6664                            " installed controllers.\n");
6665           printk(KERN_INFO "aic7xxx: Please update the aic7xxx_tag_info array in"
6666                            " the aic7xxx.c source file.\n");
6667           print_warning = FALSE;
6668         }
6669         aic_dev->max_q_depth = aic_dev->temp_q_depth =
6670                 aic7xxx_default_queue_depth;
6671       }
6672       else
6673       {
6674
6675         if (aic7xxx_tag_info[p->instance].tag_commands[tindex] == 255)
6676         {
6677           tag_enabled = FALSE;
6678         }
6679         else if (aic7xxx_tag_info[p->instance].tag_commands[tindex] == 0)
6680         {
6681           aic_dev->max_q_depth = aic_dev->temp_q_depth =
6682                   aic7xxx_default_queue_depth;
6683         }
6684         else
6685         {
6686           aic_dev->max_q_depth = aic_dev->temp_q_depth = 
6687             aic7xxx_tag_info[p->instance].tag_commands[tindex];
6688         }
6689       }
6690     }
6691   }
6692   if (tag_enabled)
6693   {
6694     if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
6695     {
6696           printk(INFO_LEAD "Tagged queuing enabled, queue depth %d.\n",
6697             p->host_no, device->channel, device->id,
6698             device->lun, aic_dev->max_q_depth);
6699     }
6700     scsi_adjust_queue_depth(device, MSG_ORDERED_TAG, aic_dev->max_q_depth);
6701   }
6702   else
6703   {
6704     if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
6705     {
6706           printk(INFO_LEAD "Tagged queuing disabled, queue depth %d.\n",
6707             p->host_no, device->channel, device->id,
6708             device->lun, device->host->cmd_per_lun);
6709     }
6710     scsi_adjust_queue_depth(device, 0, device->host->cmd_per_lun);
6711   }
6712   return;
6713 }
6714
6715 /*+F*************************************************************************
6716  * Function:
6717  *   aic7xxx_slave_destroy
6718  *
6719  * Description:
6720  *   prepare for this device to go away
6721  *-F*************************************************************************/
6722 static void
6723 aic7xxx_slave_destroy(struct scsi_device *SDptr)
6724 {
6725   struct aic_dev_data *aic_dev = SDptr->hostdata;
6726
6727   list_del(&aic_dev->list);
6728   SDptr->hostdata = NULL;
6729   kfree(aic_dev);
6730   return;
6731 }
6732
6733 /*+F*************************************************************************
6734  * Function:
6735  *   aic7xxx_slave_configure
6736  *
6737  * Description:
6738  *   Configure the device we are attaching to the controller.  This is
6739  *   where we get to do things like scan the INQUIRY data, set queue
6740  *   depths, allocate command structs, etc.
6741  *-F*************************************************************************/
6742 static int
6743 aic7xxx_slave_configure(struct scsi_device *SDptr)
6744 {
6745   struct aic7xxx_host *p = (struct aic7xxx_host *) SDptr->host->hostdata;
6746   struct aic_dev_data *aic_dev;
6747   int scbnum;
6748
6749   aic_dev = (struct aic_dev_data *)SDptr->hostdata;
6750
6751   aic7xxx_init_transinfo(p, aic_dev);
6752   aic7xxx_device_queue_depth(p, SDptr);
6753   if(list_empty(&aic_dev->list))
6754     list_add_tail(&aic_dev->list, &p->aic_devs);
6755
6756   scbnum = 0;
6757   list_for_each_entry(aic_dev, &p->aic_devs, list) {
6758     scbnum += aic_dev->max_q_depth;
6759   }
6760   while (scbnum > p->scb_data->numscbs)
6761   {
6762     /*
6763      * Pre-allocate the needed SCBs to get around the possibility of having
6764      * to allocate some when memory is more or less exhausted and we need
6765      * the SCB in order to perform a swap operation (possible deadlock)
6766      */
6767     if ( aic7xxx_allocate_scb(p) == 0 )
6768       break;
6769   }
6770
6771
6772   return(0);
6773 }
6774
6775 /*+F*************************************************************************
6776  * Function:
6777  *   aic7xxx_probe
6778  *
6779  * Description:
6780  *   Probing for EISA boards: it looks like the first two bytes
6781  *   are a manufacturer code - three characters, five bits each:
6782  *
6783  *               BYTE 0   BYTE 1   BYTE 2   BYTE 3
6784  *              ?1111122 22233333 PPPPPPPP RRRRRRRR
6785  *
6786  *   The characters are baselined off ASCII '@', so add that value
6787  *   to each to get the real ASCII code for it. The next two bytes
6788  *   appear to be a product and revision number, probably vendor-
6789  *   specific. This is what is being searched for at each port,
6790  *   and what should probably correspond to the ID= field in the
6791  *   ECU's .cfg file for the card - if your card is not detected,
6792  *   make sure your signature is listed in the array.
6793  *
6794  *   The fourth byte's lowest bit seems to be an enabled/disabled
6795  *   flag (rest of the bits are reserved?).
6796  *
6797  * NOTE:  This function is only needed on Intel and Alpha platforms,
6798  *   the other platforms we support don't have EISA/VLB busses.  So,
6799  *   we #ifdef this entire function to avoid compiler warnings about
6800  *   an unused function.
6801  *-F*************************************************************************/
6802 #if defined(__i386__) || defined(__alpha__)
6803 static int
6804 aic7xxx_probe(int slot, int base, ahc_flag_type *flags)
6805 {
6806   int i;
6807   unsigned char buf[4];
6808
6809   static struct {
6810     int n;
6811     unsigned char signature[sizeof(buf)];
6812     ahc_chip type;
6813     int bios_disabled;
6814   } AIC7xxx[] = {
6815     { 4, { 0x04, 0x90, 0x77, 0x70 },
6816       AHC_AIC7770|AHC_EISA, FALSE },  /* mb 7770  */
6817     { 4, { 0x04, 0x90, 0x77, 0x71 },
6818       AHC_AIC7770|AHC_EISA, FALSE }, /* host adapter 274x */
6819     { 4, { 0x04, 0x90, 0x77, 0x56 },
6820       AHC_AIC7770|AHC_VL, FALSE }, /* 284x BIOS enabled */
6821     { 4, { 0x04, 0x90, 0x77, 0x57 },
6822       AHC_AIC7770|AHC_VL, TRUE }   /* 284x BIOS disabled */
6823   };
6824
6825   /*
6826    * The VL-bus cards need to be primed by
6827    * writing before a signature check.
6828    */
6829   for (i = 0; i < sizeof(buf); i++)
6830   {
6831     outb(0x80 + i, base);
6832     buf[i] = inb(base + i);
6833   }
6834
6835   for (i = 0; i < ARRAY_SIZE(AIC7xxx); i++)
6836   {
6837     /*
6838      * Signature match on enabled card?
6839      */
6840     if (!memcmp(buf, AIC7xxx[i].signature, AIC7xxx[i].n))
6841     {
6842       if (inb(base + 4) & 1)
6843       {
6844         if (AIC7xxx[i].bios_disabled)
6845         {
6846           *flags |= AHC_USEDEFAULTS;
6847         }
6848         else
6849         {
6850           *flags |= AHC_BIOS_ENABLED;
6851         }
6852         return (i);
6853       }
6854
6855       printk("aic7xxx: <Adaptec 7770 SCSI Host Adapter> "
6856              "disabled at slot %d, ignored.\n", slot);
6857     }
6858   }
6859
6860   return (-1);
6861 }
6862 #endif /* (__i386__) || (__alpha__) */
6863
6864
6865 /*+F*************************************************************************
6866  * Function:
6867  *   read_2840_seeprom
6868  *
6869  * Description:
6870  *   Reads the 2840 serial EEPROM and returns 1 if successful and 0 if
6871  *   not successful.
6872  *
6873  *   See read_seeprom (for the 2940) for the instruction set of the 93C46
6874  *   chip.
6875  *
6876  *   The 2840 interface to the 93C46 serial EEPROM is through the
6877  *   STATUS_2840 and SEECTL_2840 registers.  The CS_2840, CK_2840, and
6878  *   DO_2840 bits of the SEECTL_2840 register are connected to the chip
6879  *   select, clock, and data out lines respectively of the serial EEPROM.
6880  *   The DI_2840 bit of the STATUS_2840 is connected to the data in line
6881  *   of the serial EEPROM.  The EEPROM_TF bit of STATUS_2840 register is
6882  *   useful in that it gives us an 800 nsec timer.  After a read from the
6883  *   SEECTL_2840 register the timing flag is cleared and goes high 800 nsec
6884  *   later.
6885  *-F*************************************************************************/
6886 static int
6887 read_284x_seeprom(struct aic7xxx_host *p, struct seeprom_config *sc)
6888 {
6889   int i = 0, k = 0;
6890   unsigned char temp;
6891   unsigned short checksum = 0;
6892   unsigned short *seeprom = (unsigned short *) sc;
6893   struct seeprom_cmd {
6894     unsigned char len;
6895     unsigned char bits[3];
6896   };
6897   struct seeprom_cmd seeprom_read = {3, {1, 1, 0}};
6898
6899 #define CLOCK_PULSE(p) \
6900   while ((aic_inb(p, STATUS_2840) & EEPROM_TF) == 0)        \
6901   {                                                \
6902     ;  /* Do nothing */                                \
6903   }                                                \
6904   (void) aic_inb(p, SEECTL_2840);
6905
6906   /*
6907    * Read the first 32 registers of the seeprom.  For the 2840,
6908    * the 93C46 SEEPROM is a 1024-bit device with 64 16-bit registers
6909    * but only the first 32 are used by Adaptec BIOS.  The loop
6910    * will range from 0 to 31.
6911    */
6912   for (k = 0; k < (sizeof(*sc) / 2); k++)
6913   {
6914     /*
6915      * Send chip select for one clock cycle.
6916      */
6917     aic_outb(p, CK_2840 | CS_2840, SEECTL_2840);
6918     CLOCK_PULSE(p);
6919
6920     /*
6921      * Now we're ready to send the read command followed by the
6922      * address of the 16-bit register we want to read.
6923      */
6924     for (i = 0; i < seeprom_read.len; i++)
6925     {
6926       temp = CS_2840 | seeprom_read.bits[i];
6927       aic_outb(p, temp, SEECTL_2840);
6928       CLOCK_PULSE(p);
6929       temp = temp ^ CK_2840;
6930       aic_outb(p, temp, SEECTL_2840);
6931       CLOCK_PULSE(p);
6932     }
6933     /*
6934      * Send the 6 bit address (MSB first, LSB last).
6935      */
6936     for (i = 5; i >= 0; i--)
6937     {
6938       temp = k;
6939       temp = (temp >> i) & 1;  /* Mask out all but lower bit. */
6940       temp = CS_2840 | temp;
6941       aic_outb(p, temp, SEECTL_2840);
6942       CLOCK_PULSE(p);
6943       temp = temp ^ CK_2840;
6944       aic_outb(p, temp, SEECTL_2840);
6945       CLOCK_PULSE(p);
6946     }
6947
6948     /*
6949      * Now read the 16 bit register.  An initial 0 precedes the
6950      * register contents which begins with bit 15 (MSB) and ends
6951      * with bit 0 (LSB).  The initial 0 will be shifted off the
6952      * top of our word as we let the loop run from 0 to 16.
6953      */
6954     for (i = 0; i <= 16; i++)
6955     {
6956       temp = CS_2840;
6957       aic_outb(p, temp, SEECTL_2840);
6958       CLOCK_PULSE(p);
6959       temp = temp ^ CK_2840;
6960       seeprom[k] = (seeprom[k] << 1) | (aic_inb(p, STATUS_2840) & DI_2840);
6961       aic_outb(p, temp, SEECTL_2840);
6962       CLOCK_PULSE(p);
6963     }
6964     /*
6965      * The serial EEPROM has a checksum in the last word.  Keep a
6966      * running checksum for all words read except for the last
6967      * word.  We'll verify the checksum after all words have been
6968      * read.
6969      */
6970     if (k < (sizeof(*sc) / 2) - 1)
6971     {
6972       checksum = checksum + seeprom[k];
6973     }
6974
6975     /*
6976      * Reset the chip select for the next command cycle.
6977      */
6978     aic_outb(p, 0, SEECTL_2840);
6979     CLOCK_PULSE(p);
6980     aic_outb(p, CK_2840, SEECTL_2840);
6981     CLOCK_PULSE(p);
6982     aic_outb(p, 0, SEECTL_2840);
6983     CLOCK_PULSE(p);
6984   }
6985
6986 #if 0
6987   printk("Computed checksum 0x%x, checksum read 0x%x\n", checksum, sc->checksum);
6988   printk("Serial EEPROM:");
6989   for (k = 0; k < (sizeof(*sc) / 2); k++)
6990   {
6991     if (((k % 8) == 0) && (k != 0))
6992     {
6993       printk("\n              ");
6994     }
6995     printk(" 0x%x", seeprom[k]);
6996   }
6997   printk("\n");
6998 #endif
6999
7000   if (checksum != sc->checksum)
7001   {
7002     printk("aic7xxx: SEEPROM checksum error, ignoring SEEPROM settings.\n");
7003     return (0);
7004   }
7005
7006   return (1);
7007 #undef CLOCK_PULSE
7008 }
7009
7010 #define CLOCK_PULSE(p)                                               \
7011   do {                                                               \
7012     int limit = 0;                                                   \
7013     do {                                                             \
7014       mb();                                                          \
7015       pause_sequencer(p);  /* This is just to generate some PCI */   \
7016                            /* traffic so the PCI read is flushed */  \
7017                            /* it shouldn't be needed, but some */    \
7018                            /* chipsets do indeed appear to need */   \
7019                            /* something to force PCI reads to get */ \
7020                            /* flushed */                             \
7021       udelay(1);           /* Do nothing */                          \
7022     } while (((aic_inb(p, SEECTL) & SEERDY) == 0) && (++limit < 1000)); \
7023   } while(0)
7024
7025 /*+F*************************************************************************
7026  * Function:
7027  *   acquire_seeprom
7028  *
7029  * Description:
7030  *   Acquires access to the memory port on PCI controllers.
7031  *-F*************************************************************************/
7032 static int
7033 acquire_seeprom(struct aic7xxx_host *p)
7034 {
7035
7036   /*
7037    * Request access of the memory port.  When access is
7038    * granted, SEERDY will go high.  We use a 1 second
7039    * timeout which should be near 1 second more than
7040    * is needed.  Reason: after the 7870 chip reset, there
7041    * should be no contention.
7042    */
7043   aic_outb(p, SEEMS, SEECTL);
7044   CLOCK_PULSE(p);
7045   if ((aic_inb(p, SEECTL) & SEERDY) == 0)
7046   {
7047     aic_outb(p, 0, SEECTL);
7048     return (0);
7049   }
7050   return (1);
7051 }
7052
7053 /*+F*************************************************************************
7054  * Function:
7055  *   release_seeprom
7056  *
7057  * Description:
7058  *   Releases access to the memory port on PCI controllers.
7059  *-F*************************************************************************/
7060 static void
7061 release_seeprom(struct aic7xxx_host *p)
7062 {
7063   /*
7064    * Make sure the SEEPROM is ready before we release it.
7065    */
7066   CLOCK_PULSE(p);
7067   aic_outb(p, 0, SEECTL);
7068 }
7069
7070 /*+F*************************************************************************
7071  * Function:
7072  *   read_seeprom
7073  *
7074  * Description:
7075  *   Reads the serial EEPROM and returns 1 if successful and 0 if
7076  *   not successful.
7077  *
7078  *   The instruction set of the 93C46/56/66 chips is as follows:
7079  *
7080  *               Start  OP
7081  *     Function   Bit  Code  Address    Data     Description
7082  *     -------------------------------------------------------------------
7083  *     READ        1    10   A5 - A0             Reads data stored in memory,
7084  *                                               starting at specified address
7085  *     EWEN        1    00   11XXXX              Write enable must precede
7086  *                                               all programming modes
7087  *     ERASE       1    11   A5 - A0             Erase register A5A4A3A2A1A0
7088  *     WRITE       1    01   A5 - A0   D15 - D0  Writes register
7089  *     ERAL        1    00   10XXXX              Erase all registers
7090  *     WRAL        1    00   01XXXX    D15 - D0  Writes to all registers
7091  *     EWDS        1    00   00XXXX              Disables all programming
7092  *                                               instructions
7093  *     *Note: A value of X for address is a don't care condition.
7094  *     *Note: The 93C56 and 93C66 have 8 address bits.
7095  * 
7096  *
7097  *   The 93C46 has a four wire interface: clock, chip select, data in, and
7098  *   data out.  In order to perform one of the above functions, you need
7099  *   to enable the chip select for a clock period (typically a minimum of
7100  *   1 usec, with the clock high and low a minimum of 750 and 250 nsec
7101  *   respectively.  While the chip select remains high, you can clock in
7102  *   the instructions (above) starting with the start bit, followed by the
7103  *   OP code, Address, and Data (if needed).  For the READ instruction, the
7104  *   requested 16-bit register contents is read from the data out line but
7105  *   is preceded by an initial zero (leading 0, followed by 16-bits, MSB
7106  *   first).  The clock cycling from low to high initiates the next data
7107  *   bit to be sent from the chip.
7108  *
7109  *   The 78xx interface to the 93C46 serial EEPROM is through the SEECTL
7110  *   register.  After successful arbitration for the memory port, the
7111  *   SEECS bit of the SEECTL register is connected to the chip select.
7112  *   The SEECK, SEEDO, and SEEDI are connected to the clock, data out,
7113  *   and data in lines respectively.  The SEERDY bit of SEECTL is useful
7114  *   in that it gives us an 800 nsec timer.  After a write to the SEECTL
7115  *   register, the SEERDY goes high 800 nsec later.  The one exception
7116  *   to this is when we first request access to the memory port.  The
7117  *   SEERDY goes high to signify that access has been granted and, for
7118  *   this case, has no implied timing.
7119  *-F*************************************************************************/
7120 static int
7121 read_seeprom(struct aic7xxx_host *p, int offset, 
7122     unsigned short *scarray, unsigned int len, seeprom_chip_type chip)
7123 {
7124   int i = 0, k;
7125   unsigned char temp;
7126   unsigned short checksum = 0;
7127   struct seeprom_cmd {
7128     unsigned char len;
7129     unsigned char bits[3];
7130   };
7131   struct seeprom_cmd seeprom_read = {3, {1, 1, 0}};
7132
7133   /*
7134    * Request access of the memory port.
7135    */
7136   if (acquire_seeprom(p) == 0)
7137   {
7138     return (0);
7139   }
7140
7141   /*
7142    * Read 'len' registers of the seeprom.  For the 7870, the 93C46
7143    * SEEPROM is a 1024-bit device with 64 16-bit registers but only
7144    * the first 32 are used by Adaptec BIOS.  Some adapters use the
7145    * 93C56 SEEPROM which is a 2048-bit device.  The loop will range
7146    * from 0 to 'len' - 1.
7147    */
7148   for (k = 0; k < len; k++)
7149   {
7150     /*
7151      * Send chip select for one clock cycle.
7152      */
7153     aic_outb(p, SEEMS | SEECK | SEECS, SEECTL);
7154     CLOCK_PULSE(p);
7155
7156     /*
7157      * Now we're ready to send the read command followed by the
7158      * address of the 16-bit register we want to read.
7159      */
7160     for (i = 0; i < seeprom_read.len; i++)
7161     {
7162       temp = SEEMS | SEECS | (seeprom_read.bits[i] << 1);
7163       aic_outb(p, temp, SEECTL);
7164       CLOCK_PULSE(p);
7165       temp = temp ^ SEECK;
7166       aic_outb(p, temp, SEECTL);
7167       CLOCK_PULSE(p);
7168     }
7169     /*
7170      * Send the 6 or 8 bit address (MSB first, LSB last).
7171      */
7172     for (i = ((int) chip - 1); i >= 0; i--)
7173     {
7174       temp = k + offset;
7175       temp = (temp >> i) & 1;  /* Mask out all but lower bit. */
7176       temp = SEEMS | SEECS | (temp << 1);
7177       aic_outb(p, temp, SEECTL);
7178       CLOCK_PULSE(p);
7179       temp = temp ^ SEECK;
7180       aic_outb(p, temp, SEECTL);
7181       CLOCK_PULSE(p);
7182     }
7183
7184     /*
7185      * Now read the 16 bit register.  An initial 0 precedes the
7186      * register contents which begins with bit 15 (MSB) and ends
7187      * with bit 0 (LSB).  The initial 0 will be shifted off the
7188      * top of our word as we let the loop run from 0 to 16.
7189      */
7190     for (i = 0; i <= 16; i++)
7191     {
7192       temp = SEEMS | SEECS;
7193       aic_outb(p, temp, SEECTL);
7194       CLOCK_PULSE(p);
7195       temp = temp ^ SEECK;
7196       scarray[k] = (scarray[k] << 1) | (aic_inb(p, SEECTL) & SEEDI);
7197       aic_outb(p, temp, SEECTL);
7198       CLOCK_PULSE(p);
7199     }
7200
7201     /*
7202      * The serial EEPROM should have a checksum in the last word.
7203      * Keep a running checksum for all words read except for the
7204      * last word.  We'll verify the checksum after all words have
7205      * been read.
7206      */
7207     if (k < (len - 1))
7208     {
7209       checksum = checksum + scarray[k];
7210     }
7211
7212     /*
7213      * Reset the chip select for the next command cycle.
7214      */
7215     aic_outb(p, SEEMS, SEECTL);
7216     CLOCK_PULSE(p);
7217     aic_outb(p, SEEMS | SEECK, SEECTL);
7218     CLOCK_PULSE(p);
7219     aic_outb(p, SEEMS, SEECTL);
7220     CLOCK_PULSE(p);
7221   }
7222
7223   /*
7224    * Release access to the memory port and the serial EEPROM.
7225    */
7226   release_seeprom(p);
7227
7228 #if 0
7229   printk("Computed checksum 0x%x, checksum read 0x%x\n",
7230          checksum, scarray[len - 1]);
7231   printk("Serial EEPROM:");
7232   for (k = 0; k < len; k++)
7233   {
7234     if (((k % 8) == 0) && (k != 0))
7235     {
7236       printk("\n              ");
7237     }
7238     printk(" 0x%x", scarray[k]);
7239   }
7240   printk("\n");
7241 #endif
7242   if ( (checksum != scarray[len - 1]) || (checksum == 0) )
7243   {
7244     return (0);
7245   }
7246
7247   return (1);
7248 }
7249
7250 /*+F*************************************************************************
7251  * Function:
7252  *   read_brdctl
7253  *
7254  * Description:
7255  *   Reads the BRDCTL register.
7256  *-F*************************************************************************/
7257 static unsigned char
7258 read_brdctl(struct aic7xxx_host *p)
7259 {
7260   unsigned char brdctl, value;
7261
7262   /*
7263    * Make sure the SEEPROM is ready before we access it
7264    */
7265   CLOCK_PULSE(p);
7266   if (p->features & AHC_ULTRA2)
7267   {
7268     brdctl = BRDRW_ULTRA2;
7269     aic_outb(p, brdctl, BRDCTL);
7270     CLOCK_PULSE(p);
7271     value = aic_inb(p, BRDCTL);
7272     CLOCK_PULSE(p);
7273     return(value);
7274   }
7275   brdctl = BRDRW;
7276   if ( !((p->chip & AHC_CHIPID_MASK) == AHC_AIC7895) ||
7277         (p->flags & AHC_CHNLB) )
7278   {
7279     brdctl |= BRDCS;
7280   }
7281   aic_outb(p, brdctl, BRDCTL);
7282   CLOCK_PULSE(p);
7283   value = aic_inb(p, BRDCTL);
7284   CLOCK_PULSE(p);
7285   aic_outb(p, 0, BRDCTL);
7286   CLOCK_PULSE(p);
7287   return (value);
7288 }
7289
7290 /*+F*************************************************************************
7291  * Function:
7292  *   write_brdctl
7293  *
7294  * Description:
7295  *   Writes a value to the BRDCTL register.
7296  *-F*************************************************************************/
7297 static void
7298 write_brdctl(struct aic7xxx_host *p, unsigned char value)
7299 {
7300   unsigned char brdctl;
7301
7302   /*
7303    * Make sure the SEEPROM is ready before we access it
7304    */
7305   CLOCK_PULSE(p);
7306   if (p->features & AHC_ULTRA2)
7307   {
7308     brdctl = value;
7309     aic_outb(p, brdctl, BRDCTL);
7310     CLOCK_PULSE(p);
7311     brdctl |= BRDSTB_ULTRA2;
7312     aic_outb(p, brdctl, BRDCTL);
7313     CLOCK_PULSE(p);
7314     brdctl &= ~BRDSTB_ULTRA2;
7315     aic_outb(p, brdctl, BRDCTL);
7316     CLOCK_PULSE(p);
7317     read_brdctl(p);
7318     CLOCK_PULSE(p);
7319   }
7320   else
7321   {
7322     brdctl = BRDSTB;
7323     if ( !((p->chip & AHC_CHIPID_MASK) == AHC_AIC7895) ||
7324           (p->flags & AHC_CHNLB) )
7325     {
7326       brdctl |= BRDCS;
7327     }
7328     brdctl = BRDSTB | BRDCS;
7329     aic_outb(p, brdctl, BRDCTL);
7330     CLOCK_PULSE(p);
7331     brdctl |= value;
7332     aic_outb(p, brdctl, BRDCTL);
7333     CLOCK_PULSE(p);
7334     brdctl &= ~BRDSTB;
7335     aic_outb(p, brdctl, BRDCTL);
7336     CLOCK_PULSE(p);
7337     brdctl &= ~BRDCS;
7338     aic_outb(p, brdctl, BRDCTL);
7339     CLOCK_PULSE(p);
7340   }
7341 }
7342
7343 /*+F*************************************************************************
7344  * Function:
7345  *   aic785x_cable_detect
7346  *
7347  * Description:
7348  *   Detect the cables that are present on aic785x class controller chips
7349  *-F*************************************************************************/
7350 static void
7351 aic785x_cable_detect(struct aic7xxx_host *p, int *int_50,
7352     int *ext_present, int *eeprom)
7353 {
7354   unsigned char brdctl;
7355
7356   aic_outb(p, BRDRW | BRDCS, BRDCTL);
7357   CLOCK_PULSE(p);
7358   aic_outb(p, 0, BRDCTL);
7359   CLOCK_PULSE(p);
7360   brdctl = aic_inb(p, BRDCTL);
7361   CLOCK_PULSE(p);
7362   *int_50 = !(brdctl & BRDDAT5);
7363   *ext_present = !(brdctl & BRDDAT6);
7364   *eeprom = (aic_inb(p, SPIOCAP) & EEPROM);
7365 }
7366
7367 #undef CLOCK_PULSE
7368
7369 /*+F*************************************************************************
7370  * Function:
7371  *   aic2940_uwpro_cable_detect
7372  *
7373  * Description:
7374  *   Detect the cables that are present on the 2940-UWPro cards
7375  *
7376  * NOTE: This function assumes the SEEPROM will have already been acquired
7377  *       prior to invocation of this function.
7378  *-F*************************************************************************/
7379 static void
7380 aic2940_uwpro_wide_cable_detect(struct aic7xxx_host *p, int *int_68,
7381     int *ext_68, int *eeprom)
7382 {
7383   unsigned char brdctl;
7384
7385   /*
7386    * First read the status of our cables.  Set the rom bank to
7387    * 0 since the bank setting serves as a multiplexor for the
7388    * cable detection logic.  BRDDAT5 controls the bank switch.
7389    */
7390   write_brdctl(p, 0);
7391
7392   /*
7393    * Now we read the state of the internal 68 connector.  BRDDAT6
7394    * is don't care, BRDDAT7 is internal 68.  The cable is
7395    * present if the bit is 0
7396    */
7397   brdctl = read_brdctl(p);
7398   *int_68 = !(brdctl & BRDDAT7);
7399
7400   /*
7401    * Set the bank bit in brdctl and then read the external cable state
7402    * and the EEPROM status
7403    */
7404   write_brdctl(p, BRDDAT5);
7405   brdctl = read_brdctl(p);
7406
7407   *ext_68 = !(brdctl & BRDDAT6);
7408   *eeprom = !(brdctl & BRDDAT7);
7409
7410   /*
7411    * We're done, the calling function will release the SEEPROM for us
7412    */
7413 }
7414
7415 /*+F*************************************************************************
7416  * Function:
7417  *   aic787x_cable_detect
7418  *
7419  * Description:
7420  *   Detect the cables that are present on aic787x class controller chips
7421  *
7422  * NOTE: This function assumes the SEEPROM will have already been acquired
7423  *       prior to invocation of this function.
7424  *-F*************************************************************************/
7425 static void
7426 aic787x_cable_detect(struct aic7xxx_host *p, int *int_50, int *int_68,
7427     int *ext_present, int *eeprom)
7428 {
7429   unsigned char brdctl;
7430
7431   /*
7432    * First read the status of our cables.  Set the rom bank to
7433    * 0 since the bank setting serves as a multiplexor for the
7434    * cable detection logic.  BRDDAT5 controls the bank switch.
7435    */
7436   write_brdctl(p, 0);
7437
7438   /*
7439    * Now we read the state of the two internal connectors.  BRDDAT6
7440    * is internal 50, BRDDAT7 is internal 68.  For each, the cable is
7441    * present if the bit is 0
7442    */
7443   brdctl = read_brdctl(p);
7444   *int_50 = !(brdctl & BRDDAT6);
7445   *int_68 = !(brdctl & BRDDAT7);
7446
7447   /*
7448    * Set the bank bit in brdctl and then read the external cable state
7449    * and the EEPROM status
7450    */
7451   write_brdctl(p, BRDDAT5);
7452   brdctl = read_brdctl(p);
7453
7454   *ext_present = !(brdctl & BRDDAT6);
7455   *eeprom = !(brdctl & BRDDAT7);
7456
7457   /*
7458    * We're done, the calling function will release the SEEPROM for us
7459    */
7460 }
7461
7462 /*+F*************************************************************************
7463  * Function:
7464  *   aic787x_ultra2_term_detect
7465  *
7466  * Description:
7467  *   Detect the termination settings present on ultra2 class controllers
7468  *
7469  * NOTE: This function assumes the SEEPROM will have already been acquired
7470  *       prior to invocation of this function.
7471  *-F*************************************************************************/
7472 static void
7473 aic7xxx_ultra2_term_detect(struct aic7xxx_host *p, int *enableSE_low,
7474                            int *enableSE_high, int *enableLVD_low,
7475                            int *enableLVD_high, int *eprom_present)
7476 {
7477   unsigned char brdctl;
7478
7479   brdctl = read_brdctl(p);
7480
7481   *eprom_present  = (brdctl & BRDDAT7);
7482   *enableSE_high  = (brdctl & BRDDAT6);
7483   *enableSE_low   = (brdctl & BRDDAT5);
7484   *enableLVD_high = (brdctl & BRDDAT4);
7485   *enableLVD_low  = (brdctl & BRDDAT3);
7486 }
7487
7488 /*+F*************************************************************************
7489  * Function:
7490  *   configure_termination
7491  *
7492  * Description:
7493  *   Configures the termination settings on PCI adapters that have
7494  *   SEEPROMs available.
7495  *-F*************************************************************************/
7496 static void
7497 configure_termination(struct aic7xxx_host *p)
7498 {
7499   int internal50_present = 0;
7500   int internal68_present = 0;
7501   int external_present = 0;
7502   int eprom_present = 0;
7503   int enableSE_low = 0;
7504   int enableSE_high = 0;
7505   int enableLVD_low = 0;
7506   int enableLVD_high = 0;
7507   unsigned char brddat = 0;
7508   unsigned char max_target = 0;
7509   unsigned char sxfrctl1 = aic_inb(p, SXFRCTL1);
7510
7511   if (acquire_seeprom(p))
7512   {
7513     if (p->features & (AHC_WIDE|AHC_TWIN))
7514       max_target = 16;
7515     else
7516       max_target = 8;
7517     aic_outb(p, SEEMS | SEECS, SEECTL);
7518     sxfrctl1 &= ~STPWEN;
7519     /*
7520      * The termination/cable detection logic is split into three distinct
7521      * groups.  Ultra2 and later controllers, 2940UW-Pro controllers, and
7522      * older 7850, 7860, 7870, 7880, and 7895 controllers.  Each has its
7523      * own unique way of detecting their cables and writing the results
7524      * back to the card.
7525      */
7526     if (p->features & AHC_ULTRA2)
7527     {
7528       /*
7529        * As long as user hasn't overridden term settings, always check the
7530        * cable detection logic
7531        */
7532       if (aic7xxx_override_term == -1)
7533       {
7534         aic7xxx_ultra2_term_detect(p, &enableSE_low, &enableSE_high,
7535                                    &enableLVD_low, &enableLVD_high,
7536                                    &eprom_present);
7537       }
7538       
7539       /*
7540        * If the user is overriding settings, then they have been preserved
7541        * to here as fake adapter_control entries.  Parse them and allow
7542        * them to override the detected settings (if we even did detection).
7543        */
7544       if (!(p->adapter_control & CFSEAUTOTERM))
7545       {
7546         enableSE_low = (p->adapter_control & CFSTERM);
7547         enableSE_high = (p->adapter_control & CFWSTERM);
7548       }
7549       if (!(p->adapter_control & CFAUTOTERM))
7550       {
7551         enableLVD_low = enableLVD_high = (p->adapter_control & CFLVDSTERM);
7552       }
7553
7554       /*
7555        * Now take those settings that we have and translate them into the
7556        * values that must be written into the registers.
7557        *
7558        * Flash Enable = BRDDAT7
7559        * Secondary High Term Enable = BRDDAT6
7560        * Secondary Low Term Enable = BRDDAT5
7561        * LVD/Primary High Term Enable = BRDDAT4
7562        * LVD/Primary Low Term Enable = STPWEN bit in SXFRCTL1
7563        */
7564       if (enableLVD_low != 0)
7565       {
7566         sxfrctl1 |= STPWEN;
7567         p->flags |= AHC_TERM_ENB_LVD;
7568         if (aic7xxx_verbose & VERBOSE_PROBE2)
7569           printk(KERN_INFO "(scsi%d) LVD/Primary Low byte termination "
7570                  "Enabled\n", p->host_no);
7571       }
7572           
7573       if (enableLVD_high != 0)
7574       {
7575         brddat |= BRDDAT4;
7576         if (aic7xxx_verbose & VERBOSE_PROBE2)
7577           printk(KERN_INFO "(scsi%d) LVD/Primary High byte termination "
7578                  "Enabled\n", p->host_no);
7579       }
7580
7581       if (enableSE_low != 0)
7582       {
7583         brddat |= BRDDAT5;
7584         if (aic7xxx_verbose & VERBOSE_PROBE2)
7585           printk(KERN_INFO "(scsi%d) Secondary Low byte termination "
7586                  "Enabled\n", p->host_no);
7587       }
7588
7589       if (enableSE_high != 0)
7590       {
7591         brddat |= BRDDAT6;
7592         if (aic7xxx_verbose & VERBOSE_PROBE2)
7593           printk(KERN_INFO "(scsi%d) Secondary High byte termination "
7594                  "Enabled\n", p->host_no);
7595       }
7596     }
7597     else if (p->features & AHC_NEW_AUTOTERM)
7598     {
7599       /*
7600        * The 50 pin connector termination is controlled by STPWEN in the
7601        * SXFRCTL1 register.  Since the Adaptec docs typically say the
7602        * controller is not allowed to be in the middle of a cable and
7603        * this is the only connection on that stub of the bus, there is
7604        * no need to even check for narrow termination, it's simply
7605        * always on.
7606        */
7607       sxfrctl1 |= STPWEN;
7608       if (aic7xxx_verbose & VERBOSE_PROBE2)
7609         printk(KERN_INFO "(scsi%d) Narrow channel termination Enabled\n",
7610                p->host_no);
7611
7612       if (p->adapter_control & CFAUTOTERM)
7613       {
7614         aic2940_uwpro_wide_cable_detect(p, &internal68_present,
7615                                         &external_present,
7616                                         &eprom_present);
7617         printk(KERN_INFO "(scsi%d) Cables present (Int-50 %s, Int-68 %s, "
7618                "Ext-68 %s)\n", p->host_no,
7619                "Don't Care",
7620                internal68_present ? "YES" : "NO",
7621                external_present ? "YES" : "NO");
7622         if (aic7xxx_verbose & VERBOSE_PROBE2)
7623           printk(KERN_INFO "(scsi%d) EEPROM %s present.\n", p->host_no,
7624                eprom_present ? "is" : "is not");
7625         if (internal68_present && external_present)
7626         {
7627           brddat = 0;
7628           p->flags &= ~AHC_TERM_ENB_SE_HIGH;
7629           if (aic7xxx_verbose & VERBOSE_PROBE2)
7630             printk(KERN_INFO "(scsi%d) Wide channel termination Disabled\n",
7631                    p->host_no);
7632         }
7633         else
7634         {
7635           brddat = BRDDAT6;
7636           p->flags |= AHC_TERM_ENB_SE_HIGH;
7637           if (aic7xxx_verbose & VERBOSE_PROBE2)
7638             printk(KERN_INFO "(scsi%d) Wide channel termination Enabled\n",
7639                    p->host_no);
7640         }
7641       }
7642       else
7643       {
7644         /*
7645          * The termination of the Wide channel is done more like normal
7646          * though, and the setting of this termination is done by writing
7647          * either a 0 or 1 to BRDDAT6 of the BRDDAT register
7648          */
7649         if (p->adapter_control & CFWSTERM)
7650         {
7651           brddat = BRDDAT6;
7652           p->flags |= AHC_TERM_ENB_SE_HIGH;
7653           if (aic7xxx_verbose & VERBOSE_PROBE2)
7654             printk(KERN_INFO "(scsi%d) Wide channel termination Enabled\n",
7655                    p->host_no);
7656         }
7657         else
7658         {
7659           brddat = 0;
7660         }
7661       }
7662     }
7663     else
7664     {
7665       if (p->adapter_control & CFAUTOTERM)
7666       {
7667         if (p->flags & AHC_MOTHERBOARD)
7668         {
7669           printk(KERN_INFO "(scsi%d) Warning - detected auto-termination\n",
7670                  p->host_no);
7671           printk(KERN_INFO "(scsi%d) Please verify driver detected settings "
7672             "are correct.\n", p->host_no);
7673           printk(KERN_INFO "(scsi%d) If not, then please properly set the "
7674             "device termination\n", p->host_no);
7675           printk(KERN_INFO "(scsi%d) in the Adaptec SCSI BIOS by hitting "
7676             "CTRL-A when prompted\n", p->host_no);
7677           printk(KERN_INFO "(scsi%d) during machine bootup.\n", p->host_no);
7678         }
7679         /* Configure auto termination. */
7680
7681         if ( (p->chip & AHC_CHIPID_MASK) >= AHC_AIC7870 )
7682         {
7683           aic787x_cable_detect(p, &internal50_present, &internal68_present,
7684             &external_present, &eprom_present);
7685         }
7686         else
7687         {
7688           aic785x_cable_detect(p, &internal50_present, &external_present,
7689             &eprom_present);
7690         }
7691
7692         if (max_target <= 8)
7693           internal68_present = 0;
7694
7695         if (max_target > 8)
7696         {
7697           printk(KERN_INFO "(scsi%d) Cables present (Int-50 %s, Int-68 %s, "
7698                  "Ext-68 %s)\n", p->host_no,
7699                  internal50_present ? "YES" : "NO",
7700                  internal68_present ? "YES" : "NO",
7701                  external_present ? "YES" : "NO");
7702         }
7703         else
7704         {
7705           printk(KERN_INFO "(scsi%d) Cables present (Int-50 %s, Ext-50 %s)\n",
7706                  p->host_no,
7707                  internal50_present ? "YES" : "NO",
7708                  external_present ? "YES" : "NO");
7709         }
7710         if (aic7xxx_verbose & VERBOSE_PROBE2)
7711           printk(KERN_INFO "(scsi%d) EEPROM %s present.\n", p->host_no,
7712                eprom_present ? "is" : "is not");
7713
7714         /*
7715          * Now set the termination based on what we found.  BRDDAT6
7716          * controls wide termination enable.
7717          * Flash Enable = BRDDAT7
7718          * SE High Term Enable = BRDDAT6
7719          */
7720         if (internal50_present && internal68_present && external_present)
7721         {
7722           printk(KERN_INFO "(scsi%d) Illegal cable configuration!!  Only two\n",
7723                  p->host_no);
7724           printk(KERN_INFO "(scsi%d) connectors on the SCSI controller may be "
7725                  "in use at a time!\n", p->host_no);
7726           /*
7727            * Force termination (low and high byte) on.  This is safer than
7728            * leaving it completely off, especially since this message comes
7729            * most often from motherboard controllers that don't even have 3
7730            * connectors, but instead are failing the cable detection.
7731            */
7732           internal50_present = external_present = 0;
7733           enableSE_high = enableSE_low = 1;
7734         }
7735
7736         if ((max_target > 8) &&
7737             ((external_present == 0) || (internal68_present == 0)) )
7738         {
7739           brddat |= BRDDAT6;
7740           p->flags |= AHC_TERM_ENB_SE_HIGH;
7741           if (aic7xxx_verbose & VERBOSE_PROBE2)
7742             printk(KERN_INFO "(scsi%d) SE High byte termination Enabled\n",
7743                    p->host_no);
7744         }
7745
7746         if ( ((internal50_present ? 1 : 0) +
7747               (internal68_present ? 1 : 0) +
7748               (external_present   ? 1 : 0)) <= 1 )
7749         {
7750           sxfrctl1 |= STPWEN;
7751           p->flags |= AHC_TERM_ENB_SE_LOW;
7752           if (aic7xxx_verbose & VERBOSE_PROBE2)
7753             printk(KERN_INFO "(scsi%d) SE Low byte termination Enabled\n",
7754                    p->host_no);
7755         }
7756       }
7757       else /* p->adapter_control & CFAUTOTERM */
7758       {
7759         if (p->adapter_control & CFSTERM)
7760         {
7761           sxfrctl1 |= STPWEN;
7762           if (aic7xxx_verbose & VERBOSE_PROBE2)
7763             printk(KERN_INFO "(scsi%d) SE Low byte termination Enabled\n",
7764                    p->host_no);
7765         }
7766
7767         if (p->adapter_control & CFWSTERM)
7768         {
7769           brddat |= BRDDAT6;
7770           if (aic7xxx_verbose & VERBOSE_PROBE2)
7771             printk(KERN_INFO "(scsi%d) SE High byte termination Enabled\n",
7772                    p->host_no);
7773         }
7774       }
7775     }
7776
7777     aic_outb(p, sxfrctl1, SXFRCTL1);
7778     write_brdctl(p, brddat);
7779     release_seeprom(p);
7780   }
7781 }
7782
7783 /*+F*************************************************************************
7784  * Function:
7785  *   detect_maxscb
7786  *
7787  * Description:
7788  *   Detects the maximum number of SCBs for the controller and returns
7789  *   the count and a mask in p (p->maxscbs, p->qcntmask).
7790  *-F*************************************************************************/
7791 static void
7792 detect_maxscb(struct aic7xxx_host *p)
7793 {
7794   int i;
7795
7796   /*
7797    * It's possible that we've already done this for multichannel
7798    * adapters.
7799    */
7800   if (p->scb_data->maxhscbs == 0)
7801   {
7802     /*
7803      * We haven't initialized the SCB settings yet.  Walk the SCBs to
7804      * determince how many there are.
7805      */
7806     aic_outb(p, 0, FREE_SCBH);
7807
7808     for (i = 0; i < AIC7XXX_MAXSCB; i++)
7809     {
7810       aic_outb(p, i, SCBPTR);
7811       aic_outb(p, i, SCB_CONTROL);
7812       if (aic_inb(p, SCB_CONTROL) != i)
7813         break;
7814       aic_outb(p, 0, SCBPTR);
7815       if (aic_inb(p, SCB_CONTROL) != 0)
7816         break;
7817
7818       aic_outb(p, i, SCBPTR);
7819       aic_outb(p, 0, SCB_CONTROL);   /* Clear the control byte. */
7820       aic_outb(p, i + 1, SCB_NEXT);  /* Set the next pointer. */
7821       aic_outb(p, SCB_LIST_NULL, SCB_TAG);  /* Make the tag invalid. */
7822       aic_outb(p, SCB_LIST_NULL, SCB_BUSYTARGETS);  /* no busy untagged */
7823       aic_outb(p, SCB_LIST_NULL, SCB_BUSYTARGETS+1);/* targets active yet */
7824       aic_outb(p, SCB_LIST_NULL, SCB_BUSYTARGETS+2);
7825       aic_outb(p, SCB_LIST_NULL, SCB_BUSYTARGETS+3);
7826     }
7827
7828     /* Make sure the last SCB terminates the free list. */
7829     aic_outb(p, i - 1, SCBPTR);
7830     aic_outb(p, SCB_LIST_NULL, SCB_NEXT);
7831
7832     /* Ensure we clear the first (0) SCBs control byte. */
7833     aic_outb(p, 0, SCBPTR);
7834     aic_outb(p, 0, SCB_CONTROL);
7835
7836     p->scb_data->maxhscbs = i;
7837     /*
7838      * Use direct indexing instead for speed
7839      */
7840     if ( i == AIC7XXX_MAXSCB )
7841       p->flags &= ~AHC_PAGESCBS;
7842   }
7843
7844 }
7845
7846 /*+F*************************************************************************
7847  * Function:
7848  *   aic7xxx_register
7849  *
7850  * Description:
7851  *   Register a Adaptec aic7xxx chip SCSI controller with the kernel.
7852  *-F*************************************************************************/
7853 static int
7854 aic7xxx_register(struct scsi_host_template *template, struct aic7xxx_host *p,
7855   int reset_delay)
7856 {
7857   int i, result;
7858   int max_targets;
7859   int found = 1;
7860   unsigned char term, scsi_conf;
7861   struct Scsi_Host *host;
7862
7863   host = p->host;
7864
7865   p->scb_data->maxscbs = AIC7XXX_MAXSCB;
7866   host->can_queue = AIC7XXX_MAXSCB;
7867   host->cmd_per_lun = 3;
7868   host->sg_tablesize = AIC7XXX_MAX_SG;
7869   host->this_id = p->scsi_id;
7870   host->io_port = p->base;
7871   host->n_io_port = 0xFF;
7872   host->base = p->mbase;
7873   host->irq = p->irq;
7874   if (p->features & AHC_WIDE)
7875   {
7876     host->max_id = 16;
7877   }
7878   if (p->features & AHC_TWIN)
7879   {
7880     host->max_channel = 1;
7881   }
7882
7883   p->host = host;
7884   p->host_no = host->host_no;
7885   host->unique_id = p->instance;
7886   p->isr_count = 0;
7887   p->next = NULL;
7888   p->completeq.head = NULL;
7889   p->completeq.tail = NULL;
7890   scbq_init(&p->scb_data->free_scbs);
7891   scbq_init(&p->waiting_scbs);
7892   INIT_LIST_HEAD(&p->aic_devs);
7893
7894   /*
7895    * We currently have no commands of any type
7896    */
7897   p->qinfifonext = 0;
7898   p->qoutfifonext = 0;
7899
7900   printk(KERN_INFO "(scsi%d) <%s> found at ", p->host_no,
7901     board_names[p->board_name_index]);
7902   switch(p->chip)
7903   {
7904     case (AHC_AIC7770|AHC_EISA):
7905       printk("EISA slot %d\n", p->pci_device_fn);
7906       break;
7907     case (AHC_AIC7770|AHC_VL):
7908       printk("VLB slot %d\n", p->pci_device_fn);
7909       break;
7910     default:
7911       printk("PCI %d/%d/%d\n", p->pci_bus, PCI_SLOT(p->pci_device_fn),
7912         PCI_FUNC(p->pci_device_fn));
7913       break;
7914   }
7915   if (p->features & AHC_TWIN)
7916   {
7917     printk(KERN_INFO "(scsi%d) Twin Channel, A SCSI ID %d, B SCSI ID %d, ",
7918            p->host_no, p->scsi_id, p->scsi_id_b);
7919   }
7920   else
7921   {
7922     char *channel;
7923
7924     channel = "";
7925
7926     if ((p->flags & AHC_MULTI_CHANNEL) != 0)
7927     {
7928       channel = " A";
7929
7930       if ( (p->flags & (AHC_CHNLB|AHC_CHNLC)) != 0 )
7931       {
7932         channel = (p->flags & AHC_CHNLB) ? " B" : " C";
7933       }
7934     }
7935     if (p->features & AHC_WIDE)
7936     {
7937       printk(KERN_INFO "(scsi%d) Wide ", p->host_no);
7938     }
7939     else
7940     {
7941       printk(KERN_INFO "(scsi%d) Narrow ", p->host_no);
7942     }
7943     printk("Channel%s, SCSI ID=%d, ", channel, p->scsi_id);
7944   }
7945   aic_outb(p, 0, SEQ_FLAGS);
7946
7947   detect_maxscb(p);
7948
7949   printk("%d/%d SCBs\n", p->scb_data->maxhscbs, p->scb_data->maxscbs);
7950   if (aic7xxx_verbose & VERBOSE_PROBE2)
7951   {
7952     printk(KERN_INFO "(scsi%d) BIOS %sabled, IO Port 0x%lx, IRQ %d\n",
7953       p->host_no, (p->flags & AHC_BIOS_ENABLED) ? "en" : "dis",
7954       p->base, p->irq);
7955     printk(KERN_INFO "(scsi%d) IO Memory at 0x%lx, MMAP Memory at %p\n",
7956       p->host_no, p->mbase, p->maddr);
7957   }
7958
7959 #ifdef CONFIG_PCI
7960   /*
7961    * Now that we know our instance number, we can set the flags we need to
7962    * force termination if need be.
7963    */
7964   if (aic7xxx_stpwlev != -1)
7965   {
7966     /*
7967      * This option only applies to PCI controllers.
7968      */
7969     if ( (p->chip & ~AHC_CHIPID_MASK) == AHC_PCI)
7970     {
7971       unsigned char devconfig;
7972
7973       pci_read_config_byte(p->pdev, DEVCONFIG, &devconfig);
7974       if ( (aic7xxx_stpwlev >> p->instance) & 0x01 )
7975       {
7976         devconfig |= STPWLEVEL;
7977         if (aic7xxx_verbose & VERBOSE_PROBE2)
7978           printk("(scsi%d) Force setting STPWLEVEL bit\n", p->host_no);
7979       }
7980       else
7981       {
7982         devconfig &= ~STPWLEVEL;
7983         if (aic7xxx_verbose & VERBOSE_PROBE2)
7984           printk("(scsi%d) Force clearing STPWLEVEL bit\n", p->host_no);
7985       }
7986       pci_write_config_byte(p->pdev, DEVCONFIG, devconfig);
7987     }
7988   }
7989 #endif
7990
7991   /*
7992    * That took care of devconfig and stpwlev, now for the actual termination
7993    * settings.
7994    */
7995   if (aic7xxx_override_term != -1)
7996   {
7997     /*
7998      * Again, this only applies to PCI controllers.  We don't have problems
7999      * with the termination on 274x controllers to the best of my knowledge.
8000      */
8001     if ( (p->chip & ~AHC_CHIPID_MASK) == AHC_PCI)
8002     {
8003       unsigned char term_override;
8004
8005       term_override = ( (aic7xxx_override_term >> (p->instance * 4)) & 0x0f);
8006       p->adapter_control &= 
8007         ~(CFSTERM|CFWSTERM|CFLVDSTERM|CFAUTOTERM|CFSEAUTOTERM);
8008       if ( (p->features & AHC_ULTRA2) && (term_override & 0x0c) )
8009       {
8010         p->adapter_control |= CFLVDSTERM;
8011       }
8012       if (term_override & 0x02)
8013       {
8014         p->adapter_control |= CFWSTERM;
8015       }
8016       if (term_override & 0x01)
8017       {
8018         p->adapter_control |= CFSTERM;
8019       }
8020     }
8021   }
8022
8023   if ( (p->flags & AHC_SEEPROM_FOUND) || (aic7xxx_override_term != -1) )
8024   {
8025     if (p->features & AHC_SPIOCAP)
8026     {
8027       if ( aic_inb(p, SPIOCAP) & SSPIOCPS )
8028       /*
8029        * Update the settings in sxfrctl1 to match the termination
8030        * settings.
8031        */
8032         configure_termination(p);
8033     }
8034     else if ((p->chip & AHC_CHIPID_MASK) >= AHC_AIC7870)
8035     {
8036       configure_termination(p);
8037     }
8038   }
8039
8040   /*
8041    * Set the SCSI Id, SXFRCTL0, SXFRCTL1, and SIMODE1, for both channels
8042    */
8043   if (p->features & AHC_TWIN)
8044   {
8045     /* Select channel B */
8046     aic_outb(p, aic_inb(p, SBLKCTL) | SELBUSB, SBLKCTL);
8047
8048     if ((p->flags & AHC_SEEPROM_FOUND) || (aic7xxx_override_term != -1))
8049       term = (aic_inb(p, SXFRCTL1) & STPWEN);
8050     else
8051       term = ((p->flags & AHC_TERM_ENB_B) ? STPWEN : 0);
8052
8053     aic_outb(p, p->scsi_id_b, SCSIID);
8054     scsi_conf = aic_inb(p, SCSICONF + 1);
8055     aic_outb(p, DFON | SPIOEN, SXFRCTL0);
8056     aic_outb(p, (scsi_conf & ENSPCHK) | aic7xxx_seltime | term | 
8057          ENSTIMER | ACTNEGEN, SXFRCTL1);
8058     aic_outb(p, 0, SIMODE0);
8059     aic_outb(p, ENSELTIMO | ENSCSIRST | ENSCSIPERR, SIMODE1);
8060     aic_outb(p, 0, SCSIRATE);
8061
8062     /* Select channel A */
8063     aic_outb(p, aic_inb(p, SBLKCTL) & ~SELBUSB, SBLKCTL);
8064   }
8065
8066   if (p->features & AHC_ULTRA2)
8067   {
8068     aic_outb(p, p->scsi_id, SCSIID_ULTRA2);
8069   }
8070   else
8071   {
8072     aic_outb(p, p->scsi_id, SCSIID);
8073   }
8074   if ((p->flags & AHC_SEEPROM_FOUND) || (aic7xxx_override_term != -1))
8075     term = (aic_inb(p, SXFRCTL1) & STPWEN);
8076   else
8077     term = ((p->flags & (AHC_TERM_ENB_A|AHC_TERM_ENB_LVD)) ? STPWEN : 0);
8078   scsi_conf = aic_inb(p, SCSICONF);
8079   aic_outb(p, DFON | SPIOEN, SXFRCTL0);
8080   aic_outb(p, (scsi_conf & ENSPCHK) | aic7xxx_seltime | term | 
8081        ENSTIMER | ACTNEGEN, SXFRCTL1);
8082   aic_outb(p, 0, SIMODE0);
8083   /*
8084    * If we are a cardbus adapter then don't enable SCSI reset detection.
8085    * We shouldn't likely be sharing SCSI busses with someone else, and
8086    * if we don't have a cable currently plugged into the controller then
8087    * we won't have a power source for the SCSI termination, which means
8088    * we'll see infinite incoming bus resets.
8089    */
8090   if(p->flags & AHC_NO_STPWEN)
8091     aic_outb(p, ENSELTIMO | ENSCSIPERR, SIMODE1);
8092   else
8093     aic_outb(p, ENSELTIMO | ENSCSIRST | ENSCSIPERR, SIMODE1);
8094   aic_outb(p, 0, SCSIRATE);
8095   if ( p->features & AHC_ULTRA2)
8096     aic_outb(p, 0, SCSIOFFSET);
8097
8098   /*
8099    * Look at the information that board initialization or the board
8100    * BIOS has left us. In the lower four bits of each target's
8101    * scratch space any value other than 0 indicates that we should
8102    * initiate synchronous transfers. If it's zero, the user or the
8103    * BIOS has decided to disable synchronous negotiation to that
8104    * target so we don't activate the needsdtr flag.
8105    */
8106   if ((p->features & (AHC_TWIN|AHC_WIDE)) == 0)
8107   {
8108     max_targets = 8;
8109   }
8110   else
8111   {
8112     max_targets = 16;
8113   }
8114
8115   if (!(aic7xxx_no_reset))
8116   {
8117     /*
8118      * If we reset the bus, then clear the transfer settings, else leave
8119      * them be.
8120      */
8121     aic_outb(p, 0, ULTRA_ENB);
8122     aic_outb(p, 0, ULTRA_ENB + 1);
8123     p->ultraenb = 0;
8124   }
8125
8126   /*
8127    * Allocate enough hardware scbs to handle the maximum number of
8128    * concurrent transactions we can have.  We have to make sure that
8129    * the allocated memory is contiguous memory.  The Linux kmalloc
8130    * routine should only allocate contiguous memory, but note that
8131    * this could be a problem if kmalloc() is changed.
8132    */
8133   {
8134     size_t array_size;
8135     unsigned int hscb_physaddr;
8136
8137     array_size = p->scb_data->maxscbs * sizeof(struct aic7xxx_hwscb);
8138     if (p->scb_data->hscbs == NULL)
8139     {
8140       /* pci_alloc_consistent enforces the alignment already and
8141        * clears the area as well.
8142        */
8143       p->scb_data->hscbs = pci_alloc_consistent(p->pdev, array_size,
8144                                                 &p->scb_data->hscbs_dma);
8145       /* We have to use pci_free_consistent, not kfree */
8146       p->scb_data->hscb_kmalloc_ptr = NULL;
8147       p->scb_data->hscbs_dma_len = array_size;
8148     }
8149     if (p->scb_data->hscbs == NULL)
8150     {
8151       printk("(scsi%d) Unable to allocate hardware SCB array; "
8152              "failing detection.\n", p->host_no);
8153       aic_outb(p, 0, SIMODE1);
8154       p->irq = 0;
8155       return(0);
8156     }
8157
8158     hscb_physaddr = p->scb_data->hscbs_dma;
8159     aic_outb(p, hscb_physaddr & 0xFF, HSCB_ADDR);
8160     aic_outb(p, (hscb_physaddr >> 8) & 0xFF, HSCB_ADDR + 1);
8161     aic_outb(p, (hscb_physaddr >> 16) & 0xFF, HSCB_ADDR + 2);
8162     aic_outb(p, (hscb_physaddr >> 24) & 0xFF, HSCB_ADDR + 3);
8163
8164     /* Set up the fifo areas at the same time */
8165     p->untagged_scbs = pci_alloc_consistent(p->pdev, 3*256, &p->fifo_dma);
8166     if (p->untagged_scbs == NULL)
8167     {
8168       printk("(scsi%d) Unable to allocate hardware FIFO arrays; "
8169              "failing detection.\n", p->host_no);
8170       p->irq = 0;
8171       return(0);
8172     }
8173
8174     p->qoutfifo = p->untagged_scbs + 256;
8175     p->qinfifo = p->qoutfifo + 256;
8176     for (i = 0; i < 256; i++)
8177     {
8178       p->untagged_scbs[i] = SCB_LIST_NULL;
8179       p->qinfifo[i] = SCB_LIST_NULL;
8180       p->qoutfifo[i] = SCB_LIST_NULL;
8181     }
8182
8183     hscb_physaddr = p->fifo_dma;
8184     aic_outb(p, hscb_physaddr & 0xFF, SCBID_ADDR);
8185     aic_outb(p, (hscb_physaddr >> 8) & 0xFF, SCBID_ADDR + 1);
8186     aic_outb(p, (hscb_physaddr >> 16) & 0xFF, SCBID_ADDR + 2);
8187     aic_outb(p, (hscb_physaddr >> 24) & 0xFF, SCBID_ADDR + 3);
8188   }
8189
8190   /* The Q-FIFOs we just set up are all empty */
8191   aic_outb(p, 0, QINPOS);
8192   aic_outb(p, 0, KERNEL_QINPOS);
8193   aic_outb(p, 0, QOUTPOS);
8194
8195   if(p->features & AHC_QUEUE_REGS)
8196   {
8197     aic_outb(p, SCB_QSIZE_256, QOFF_CTLSTA);
8198     aic_outb(p, 0, SDSCB_QOFF);
8199     aic_outb(p, 0, SNSCB_QOFF);
8200     aic_outb(p, 0, HNSCB_QOFF);
8201   }
8202
8203   /*
8204    * We don't have any waiting selections or disconnected SCBs.
8205    */
8206   aic_outb(p, SCB_LIST_NULL, WAITING_SCBH);
8207   aic_outb(p, SCB_LIST_NULL, DISCONNECTED_SCBH);
8208
8209   /*
8210    * Message out buffer starts empty
8211    */
8212   aic_outb(p, MSG_NOOP, MSG_OUT);
8213   aic_outb(p, MSG_NOOP, LAST_MSG);
8214
8215   /*
8216    * Set all the other asundry items that haven't been set yet.
8217    * This includes just dumping init values to a lot of registers simply
8218    * to make sure they've been touched and are ready for use parity wise
8219    * speaking.
8220    */
8221   aic_outb(p, 0, TMODE_CMDADDR);
8222   aic_outb(p, 0, TMODE_CMDADDR + 1);
8223   aic_outb(p, 0, TMODE_CMDADDR + 2);
8224   aic_outb(p, 0, TMODE_CMDADDR + 3);
8225   aic_outb(p, 0, TMODE_CMDADDR_NEXT);
8226
8227   /*
8228    * Link us into the list of valid hosts
8229    */
8230   p->next = first_aic7xxx;
8231   first_aic7xxx = p;
8232
8233   /*
8234    * Allocate the first set of scbs for this controller.  This is to stream-
8235    * line code elsewhere in the driver.  If we have to check for the existence
8236    * of scbs in certain code sections, it slows things down.  However, as
8237    * soon as we register the IRQ for this card, we could get an interrupt that
8238    * includes possibly the SCSI_RSTI interrupt.  If we catch that interrupt
8239    * then we are likely to segfault if we don't have at least one chunk of
8240    * SCBs allocated or add checks all through the reset code to make sure
8241    * that the SCBs have been allocated which is an invalid running condition
8242    * and therefore I think it's preferable to simply pre-allocate the first
8243    * chunk of SCBs.
8244    */
8245   aic7xxx_allocate_scb(p);
8246
8247   /*
8248    * Load the sequencer program, then re-enable the board -
8249    * resetting the AIC-7770 disables it, leaving the lights
8250    * on with nobody home.
8251    */
8252   aic7xxx_loadseq(p);
8253
8254   /*
8255    * Make sure the AUTOFLUSHDIS bit is *not* set in the SBLKCTL register
8256    */
8257   aic_outb(p, aic_inb(p, SBLKCTL) & ~AUTOFLUSHDIS, SBLKCTL);
8258
8259   if ( (p->chip & AHC_CHIPID_MASK) == AHC_AIC7770 )
8260   {
8261     aic_outb(p, ENABLE, BCTL);  /* Enable the boards BUS drivers. */
8262   }
8263
8264   if ( !(aic7xxx_no_reset) )
8265   {
8266     if (p->features & AHC_TWIN)
8267     {
8268       if (aic7xxx_verbose & VERBOSE_PROBE2)
8269         printk(KERN_INFO "(scsi%d) Resetting channel B\n", p->host_no);
8270       aic_outb(p, aic_inb(p, SBLKCTL) | SELBUSB, SBLKCTL);
8271       aic7xxx_reset_current_bus(p);
8272       aic_outb(p, aic_inb(p, SBLKCTL) & ~SELBUSB, SBLKCTL);
8273     }
8274     /* Reset SCSI bus A. */
8275     if (aic7xxx_verbose & VERBOSE_PROBE2)
8276     {  /* In case we are a 3940, 3985, or 7895, print the right channel */
8277       char *channel = "";
8278       if (p->flags & AHC_MULTI_CHANNEL)
8279       {
8280         channel = " A";
8281         if (p->flags & (AHC_CHNLB|AHC_CHNLC))
8282           channel = (p->flags & AHC_CHNLB) ? " B" : " C";
8283       }
8284       printk(KERN_INFO "(scsi%d) Resetting channel%s\n", p->host_no, channel);
8285     }
8286     
8287     aic7xxx_reset_current_bus(p);
8288
8289   }
8290   else
8291   {
8292     if (!reset_delay)
8293     {
8294       printk(KERN_INFO "(scsi%d) Not resetting SCSI bus.  Note: Don't use "
8295              "the no_reset\n", p->host_no);
8296       printk(KERN_INFO "(scsi%d) option unless you have a verifiable need "
8297              "for it.\n", p->host_no);
8298     }
8299   }
8300   
8301   /*
8302    * Register IRQ with the kernel.  Only allow sharing IRQs with
8303    * PCI devices.
8304    */
8305   if (!(p->chip & AHC_PCI))
8306   {
8307     result = (request_irq(p->irq, do_aic7xxx_isr, 0, "aic7xxx", p));
8308   }
8309   else
8310   {
8311     result = (request_irq(p->irq, do_aic7xxx_isr, IRQF_SHARED,
8312               "aic7xxx", p));
8313     if (result < 0)
8314     {
8315       result = (request_irq(p->irq, do_aic7xxx_isr, IRQF_DISABLED | IRQF_SHARED,
8316               "aic7xxx", p));
8317     }
8318   }
8319   if (result < 0)
8320   {
8321     printk(KERN_WARNING "(scsi%d) Couldn't register IRQ %d, ignoring "
8322            "controller.\n", p->host_no, p->irq);
8323     aic_outb(p, 0, SIMODE1);
8324     p->irq = 0;
8325     return (0);
8326   }
8327
8328   if(aic_inb(p, INTSTAT) & INT_PEND)
8329     printk(INFO_LEAD "spurious interrupt during configuration, cleared.\n",
8330       p->host_no, -1, -1 , -1);
8331   aic7xxx_clear_intstat(p);
8332
8333   unpause_sequencer(p, /* unpause_always */ TRUE);
8334
8335   return (found);
8336 }
8337
8338 /*+F*************************************************************************
8339  * Function:
8340  *   aic7xxx_chip_reset
8341  *
8342  * Description:
8343  *   Perform a chip reset on the aic7xxx SCSI controller.  The controller
8344  *   is paused upon return.
8345  *-F*************************************************************************/
8346 static int
8347 aic7xxx_chip_reset(struct aic7xxx_host *p)
8348 {
8349   unsigned char sblkctl;
8350   int wait;
8351
8352   /*
8353    * For some 274x boards, we must clear the CHIPRST bit and pause
8354    * the sequencer. For some reason, this makes the driver work.
8355    */
8356   aic_outb(p, PAUSE | CHIPRST, HCNTRL);
8357
8358   /*
8359    * In the future, we may call this function as a last resort for
8360    * error handling.  Let's be nice and not do any unnecessary delays.
8361    */
8362   wait = 1000;  /* 1 msec (1000 * 1 msec) */
8363   while (--wait && !(aic_inb(p, HCNTRL) & CHIPRSTACK))
8364   {
8365     udelay(1);  /* 1 usec */
8366   }
8367
8368   pause_sequencer(p);
8369
8370   sblkctl = aic_inb(p, SBLKCTL) & (SELBUSB|SELWIDE);
8371   if (p->chip & AHC_PCI)
8372     sblkctl &= ~SELBUSB;
8373   switch( sblkctl )
8374   {
8375     case 0:  /* normal narrow card */
8376       break;
8377     case 2:  /* Wide card */
8378       p->features |= AHC_WIDE;
8379       break;
8380     case 8:  /* Twin card */
8381       p->features |= AHC_TWIN;
8382       p->flags |= AHC_MULTI_CHANNEL;
8383       break;
8384     default: /* hmmm...we don't know what this is */
8385       printk(KERN_WARNING "aic7xxx: Unsupported adapter type %d, ignoring.\n",
8386         aic_inb(p, SBLKCTL) & 0x0a);
8387       return(-1);
8388   }
8389   return(0);
8390 }
8391
8392 /*+F*************************************************************************
8393  * Function:
8394  *   aic7xxx_alloc
8395  *
8396  * Description:
8397  *   Allocate and initialize a host structure.  Returns NULL upon error
8398  *   and a pointer to a aic7xxx_host struct upon success.
8399  *-F*************************************************************************/
8400 static struct aic7xxx_host *
8401 aic7xxx_alloc(struct scsi_host_template *sht, struct aic7xxx_host *temp)
8402 {
8403   struct aic7xxx_host *p = NULL;
8404   struct Scsi_Host *host;
8405
8406   /*
8407    * Allocate a storage area by registering us with the mid-level
8408    * SCSI layer.
8409    */
8410   host = scsi_register(sht, sizeof(struct aic7xxx_host));
8411
8412   if (host != NULL)
8413   {
8414     p = (struct aic7xxx_host *) host->hostdata;
8415     memset(p, 0, sizeof(struct aic7xxx_host));
8416     *p = *temp;
8417     p->host = host;
8418
8419     p->scb_data = kzalloc(sizeof(scb_data_type), GFP_ATOMIC);
8420     if (p->scb_data)
8421     {
8422       scbq_init (&p->scb_data->free_scbs);
8423     }
8424     else
8425     {
8426       /*
8427        * For some reason we don't have enough memory.  Free the
8428        * allocated memory for the aic7xxx_host struct, and return NULL.
8429        */
8430       release_region(p->base, MAXREG - MINREG);
8431       scsi_unregister(host);
8432       return(NULL);
8433     }
8434     p->host_no = host->host_no;
8435   }
8436   return (p);
8437 }
8438
8439 /*+F*************************************************************************
8440  * Function:
8441  *   aic7xxx_free
8442  *
8443  * Description:
8444  *   Frees and releases all resources associated with an instance of
8445  *   the driver (struct aic7xxx_host *).
8446  *-F*************************************************************************/
8447 static void
8448 aic7xxx_free(struct aic7xxx_host *p)
8449 {
8450   int i;
8451
8452   /*
8453    * Free the allocated hardware SCB space.
8454    */
8455   if (p->scb_data != NULL)
8456   {
8457     struct aic7xxx_scb_dma *scb_dma = NULL;
8458     if (p->scb_data->hscbs != NULL)
8459     {
8460       pci_free_consistent(p->pdev, p->scb_data->hscbs_dma_len,
8461                           p->scb_data->hscbs, p->scb_data->hscbs_dma);
8462       p->scb_data->hscbs = p->scb_data->hscb_kmalloc_ptr = NULL;
8463     }
8464     /*
8465      * Free the driver SCBs.  These were allocated on an as-need
8466      * basis.  We allocated these in groups depending on how many
8467      * we could fit into a given amount of RAM.  The tail SCB for
8468      * these allocations has a pointer to the alloced area.
8469      */
8470     for (i = 0; i < p->scb_data->numscbs; i++)
8471     {
8472       if (p->scb_data->scb_array[i]->scb_dma != scb_dma)
8473       {
8474         scb_dma = p->scb_data->scb_array[i]->scb_dma;
8475         pci_free_consistent(p->pdev, scb_dma->dma_len,
8476                             (void *)((unsigned long)scb_dma->dma_address
8477                                      - scb_dma->dma_offset),
8478                             scb_dma->dma_address);
8479       }
8480       kfree(p->scb_data->scb_array[i]->kmalloc_ptr);
8481       p->scb_data->scb_array[i] = NULL;
8482     }
8483   
8484     /*
8485      * Free the SCB data area.
8486      */
8487     kfree(p->scb_data);
8488   }
8489
8490   pci_free_consistent(p->pdev, 3*256, (void *)p->untagged_scbs, p->fifo_dma);
8491 }
8492
8493 /*+F*************************************************************************
8494  * Function:
8495  *   aic7xxx_load_seeprom
8496  *
8497  * Description:
8498  *   Load the seeprom and configure adapter and target settings.
8499  *   Returns 1 if the load was successful and 0 otherwise.
8500  *-F*************************************************************************/
8501 static void
8502 aic7xxx_load_seeprom(struct aic7xxx_host *p, unsigned char *sxfrctl1)
8503 {
8504   int have_seeprom = 0;
8505   int i, max_targets, mask;
8506   unsigned char scsirate, scsi_conf;
8507   unsigned short scarray[128];
8508   struct seeprom_config *sc = (struct seeprom_config *) scarray;
8509
8510   if (aic7xxx_verbose & VERBOSE_PROBE2)
8511   {
8512     printk(KERN_INFO "aic7xxx: Loading serial EEPROM...");
8513   }
8514   switch (p->chip)
8515   {
8516     case (AHC_AIC7770|AHC_EISA):  /* None of these adapters have seeproms. */
8517       if (aic_inb(p, SCSICONF) & TERM_ENB)
8518         p->flags |= AHC_TERM_ENB_A;
8519       if ( (p->features & AHC_TWIN) && (aic_inb(p, SCSICONF + 1) & TERM_ENB) )
8520         p->flags |= AHC_TERM_ENB_B;
8521       break;
8522
8523     case (AHC_AIC7770|AHC_VL):
8524       have_seeprom = read_284x_seeprom(p, (struct seeprom_config *) scarray);
8525       break;
8526
8527     default:
8528       have_seeprom = read_seeprom(p, (p->flags & (AHC_CHNLB|AHC_CHNLC)),
8529                                   scarray, p->sc_size, p->sc_type);
8530       if (!have_seeprom)
8531       {
8532         if(p->sc_type == C46)
8533           have_seeprom = read_seeprom(p, (p->flags & (AHC_CHNLB|AHC_CHNLC)),
8534                                       scarray, p->sc_size, C56_66);
8535         else
8536           have_seeprom = read_seeprom(p, (p->flags & (AHC_CHNLB|AHC_CHNLC)),
8537                                       scarray, p->sc_size, C46);
8538       }
8539       if (!have_seeprom)
8540       {
8541         p->sc_size = 128;
8542         have_seeprom = read_seeprom(p, 4*(p->flags & (AHC_CHNLB|AHC_CHNLC)),
8543                                     scarray, p->sc_size, p->sc_type);
8544         if (!have_seeprom)
8545         {
8546           if(p->sc_type == C46)
8547             have_seeprom = read_seeprom(p, 4*(p->flags & (AHC_CHNLB|AHC_CHNLC)),
8548                                         scarray, p->sc_size, C56_66);
8549           else
8550             have_seeprom = read_seeprom(p, 4*(p->flags & (AHC_CHNLB|AHC_CHNLC)),
8551                                         scarray, p->sc_size, C46);
8552         }
8553       }
8554       break;
8555   }
8556
8557   if (!have_seeprom)
8558   {
8559     if (aic7xxx_verbose & VERBOSE_PROBE2)
8560     {
8561       printk("\naic7xxx: No SEEPROM available.\n");
8562     }
8563     p->flags |= AHC_NEWEEPROM_FMT;
8564     if (aic_inb(p, SCSISEQ) == 0)
8565     {
8566       p->flags |= AHC_USEDEFAULTS;
8567       p->flags &= ~AHC_BIOS_ENABLED;
8568       p->scsi_id = p->scsi_id_b = 7;
8569       *sxfrctl1 |= STPWEN;
8570       if (aic7xxx_verbose & VERBOSE_PROBE2)
8571       {
8572         printk("aic7xxx: Using default values.\n");
8573       }
8574     }
8575     else if (aic7xxx_verbose & VERBOSE_PROBE2)
8576     {
8577       printk("aic7xxx: Using leftover BIOS values.\n");
8578     }
8579     if ( ((p->chip & ~AHC_CHIPID_MASK) == AHC_PCI) && (*sxfrctl1 & STPWEN) )
8580     {
8581       p->flags |= AHC_TERM_ENB_SE_LOW | AHC_TERM_ENB_SE_HIGH;
8582       sc->adapter_control &= ~CFAUTOTERM;
8583       sc->adapter_control |= CFSTERM | CFWSTERM | CFLVDSTERM;
8584     }
8585     if (aic7xxx_extended)
8586       p->flags |= (AHC_EXTEND_TRANS_A | AHC_EXTEND_TRANS_B);
8587     else
8588       p->flags &= ~(AHC_EXTEND_TRANS_A | AHC_EXTEND_TRANS_B);
8589   }
8590   else
8591   {
8592     if (aic7xxx_verbose & VERBOSE_PROBE2)
8593     {
8594       printk("done\n");
8595     }
8596
8597     /*
8598      * Note things in our flags
8599      */
8600     p->flags |= AHC_SEEPROM_FOUND;
8601
8602     /*
8603      * Update the settings in sxfrctl1 to match the termination settings.
8604      */
8605     *sxfrctl1 = 0;
8606
8607     /*
8608      * Get our SCSI ID from the SEEPROM setting...
8609      */
8610     p->scsi_id = (sc->brtime_id & CFSCSIID);
8611
8612     /*
8613      * First process the settings that are different between the VLB
8614      * and PCI adapter seeproms.
8615      */
8616     if ((p->chip & AHC_CHIPID_MASK) == AHC_AIC7770)
8617     {
8618       /* VLB adapter seeproms */
8619       if (sc->bios_control & CF284XEXTEND)
8620         p->flags |= AHC_EXTEND_TRANS_A;
8621
8622       if (sc->adapter_control & CF284XSTERM)
8623       {
8624         *sxfrctl1 |= STPWEN;
8625         p->flags |= AHC_TERM_ENB_SE_LOW | AHC_TERM_ENB_SE_HIGH;
8626       }
8627     }
8628     else
8629     {
8630       /* PCI adapter seeproms */
8631       if (sc->bios_control & CFEXTEND)
8632         p->flags |= AHC_EXTEND_TRANS_A;
8633       if (sc->bios_control & CFBIOSEN)
8634         p->flags |= AHC_BIOS_ENABLED;
8635       else
8636         p->flags &= ~AHC_BIOS_ENABLED;
8637
8638       if (sc->adapter_control & CFSTERM)
8639       {
8640         *sxfrctl1 |= STPWEN;
8641         p->flags |= AHC_TERM_ENB_SE_LOW | AHC_TERM_ENB_SE_HIGH;
8642       }
8643     }
8644     memcpy(&p->sc, sc, sizeof(struct seeprom_config));
8645   }
8646
8647   p->discenable = 0;
8648
8649   /*
8650    * Limit to 16 targets just in case.  The 2842 for one is known to
8651    * blow the max_targets setting, future cards might also.
8652    */
8653   max_targets = ((p->features & (AHC_TWIN | AHC_WIDE)) ? 16 : 8);
8654
8655   if (have_seeprom)
8656   {
8657     for (i = 0; i < max_targets; i++)
8658     {
8659       if( ((p->features & AHC_ULTRA) &&
8660           !(sc->adapter_control & CFULTRAEN) &&
8661            (sc->device_flags[i] & CFSYNCHISULTRA)) ||
8662           (sc->device_flags[i] & CFNEWULTRAFORMAT) )
8663       {
8664         p->flags |= AHC_NEWEEPROM_FMT;
8665         break;
8666       }
8667     }
8668   }
8669
8670   for (i = 0; i < max_targets; i++)
8671   {
8672     mask = (0x01 << i);
8673     if (!have_seeprom)
8674     {
8675       if (aic_inb(p, SCSISEQ) != 0)
8676       {
8677         /*
8678          * OK...the BIOS set things up and left behind the settings we need.
8679          * Just make our sc->device_flags[i] entry match what the card has
8680          * set for this device.
8681          */
8682         p->discenable =
8683           ~(aic_inb(p, DISC_DSB) | (aic_inb(p, DISC_DSB + 1) << 8) );
8684         p->ultraenb =
8685           (aic_inb(p, ULTRA_ENB) | (aic_inb(p, ULTRA_ENB + 1) << 8) );
8686         sc->device_flags[i] = (p->discenable & mask) ? CFDISC : 0;
8687         if (aic_inb(p, TARG_SCSIRATE + i) & WIDEXFER)
8688           sc->device_flags[i] |= CFWIDEB;
8689         if (p->features & AHC_ULTRA2)
8690         {
8691           if (aic_inb(p, TARG_OFFSET + i))
8692           {
8693             sc->device_flags[i] |= CFSYNCH;
8694             sc->device_flags[i] |= (aic_inb(p, TARG_SCSIRATE + i) & 0x07);
8695             if ( (aic_inb(p, TARG_SCSIRATE + i) & 0x18) == 0x18 )
8696               sc->device_flags[i] |= CFSYNCHISULTRA;
8697           }
8698         }
8699         else
8700         {
8701           if (aic_inb(p, TARG_SCSIRATE + i) & ~WIDEXFER)
8702           {
8703             sc->device_flags[i] |= CFSYNCH;
8704             if (p->features & AHC_ULTRA)
8705               sc->device_flags[i] |= ((p->ultraenb & mask) ?
8706                                       CFSYNCHISULTRA : 0);
8707           }
8708         }
8709       }
8710       else
8711       {
8712         /*
8713          * Assume the BIOS has NOT been run on this card and nothing between
8714          * the card and the devices is configured yet.
8715          */
8716         sc->device_flags[i] = CFDISC;
8717         if (p->features & AHC_WIDE)
8718           sc->device_flags[i] |= CFWIDEB;
8719         if (p->features & AHC_ULTRA3)
8720           sc->device_flags[i] |= 2;
8721         else if (p->features & AHC_ULTRA2)
8722           sc->device_flags[i] |= 3;
8723         else if (p->features & AHC_ULTRA)
8724           sc->device_flags[i] |= CFSYNCHISULTRA;
8725         sc->device_flags[i] |= CFSYNCH;
8726         aic_outb(p, 0, TARG_SCSIRATE + i);
8727         if (p->features & AHC_ULTRA2)
8728           aic_outb(p, 0, TARG_OFFSET + i);
8729       }
8730     }
8731     if (sc->device_flags[i] & CFDISC)
8732     {
8733       p->discenable |= mask;
8734     }
8735     if (p->flags & AHC_NEWEEPROM_FMT)
8736     {
8737       if ( !(p->features & AHC_ULTRA2) )
8738       {
8739         /*
8740          * I know of two different Ultra BIOSes that do this differently.
8741          * One on the Gigabyte 6BXU mb that wants flags[i] & CFXFER to
8742          * be == to 0x03 and SYNCHISULTRA to be true to mean 40MByte/s
8743          * while on the IBM Netfinity 5000 they want the same thing
8744          * to be something else, while flags[i] & CFXFER == 0x03 and
8745          * SYNCHISULTRA false should be 40MByte/s.  So, we set both to
8746          * 40MByte/s and the lower speeds be damned.  People will have
8747          * to select around the conversely mapped lower speeds in order
8748          * to select lower speeds on these boards.
8749          */
8750         if ( (sc->device_flags[i] & CFNEWULTRAFORMAT) &&
8751             ((sc->device_flags[i] & CFXFER) == 0x03) )
8752         {
8753           sc->device_flags[i] &= ~CFXFER;
8754           sc->device_flags[i] |= CFSYNCHISULTRA;
8755         }
8756         if (sc->device_flags[i] & CFSYNCHISULTRA)
8757         {
8758           p->ultraenb |= mask;
8759         }
8760       }
8761       else if ( !(sc->device_flags[i] & CFNEWULTRAFORMAT) &&
8762                  (p->features & AHC_ULTRA2) &&
8763                  (sc->device_flags[i] & CFSYNCHISULTRA) )
8764       {
8765         p->ultraenb |= mask;
8766       }
8767     }
8768     else if (sc->adapter_control & CFULTRAEN)
8769     {
8770       p->ultraenb |= mask;
8771     }
8772     if ( (sc->device_flags[i] & CFSYNCH) == 0)
8773     {
8774       sc->device_flags[i] &= ~CFXFER;
8775       p->ultraenb &= ~mask;
8776       p->user[i].offset = 0;
8777       p->user[i].period = 0;
8778       p->user[i].options = 0;
8779     }
8780     else
8781     {
8782       if (p->features & AHC_ULTRA3)
8783       {
8784         p->user[i].offset = MAX_OFFSET_ULTRA2;
8785         if( (sc->device_flags[i] & CFXFER) < 0x03 )
8786         {
8787           scsirate = (sc->device_flags[i] & CFXFER);
8788           p->user[i].options = MSG_EXT_PPR_OPTION_DT_CRC;
8789         }
8790         else
8791         {
8792           scsirate = (sc->device_flags[i] & CFXFER) |
8793                      ((p->ultraenb & mask) ? 0x18 : 0x10);
8794           p->user[i].options = 0;
8795         }
8796         p->user[i].period = aic7xxx_find_period(p, scsirate,
8797                                        AHC_SYNCRATE_ULTRA3);
8798       }
8799       else if (p->features & AHC_ULTRA2)
8800       {
8801         p->user[i].offset = MAX_OFFSET_ULTRA2;
8802         scsirate = (sc->device_flags[i] & CFXFER) |
8803                    ((p->ultraenb & mask) ? 0x18 : 0x10);
8804         p->user[i].options = 0;
8805         p->user[i].period = aic7xxx_find_period(p, scsirate,
8806                                        AHC_SYNCRATE_ULTRA2);
8807       }
8808       else
8809       {
8810         scsirate = (sc->device_flags[i] & CFXFER) << 4;
8811         p->user[i].options = 0;
8812         p->user[i].offset = MAX_OFFSET_8BIT;
8813         if (p->features & AHC_ULTRA)
8814         {
8815           short ultraenb;
8816           ultraenb = aic_inb(p, ULTRA_ENB) |
8817             (aic_inb(p, ULTRA_ENB + 1) << 8);
8818           p->user[i].period = aic7xxx_find_period(p, scsirate,
8819                                           (p->ultraenb & mask) ?
8820                                           AHC_SYNCRATE_ULTRA :
8821                                           AHC_SYNCRATE_FAST);
8822         }
8823         else
8824           p->user[i].period = aic7xxx_find_period(p, scsirate,
8825                                           AHC_SYNCRATE_FAST);
8826       }
8827     }
8828     if ( (sc->device_flags[i] & CFWIDEB) && (p->features & AHC_WIDE) )
8829     {
8830       p->user[i].width = MSG_EXT_WDTR_BUS_16_BIT;
8831     }
8832     else
8833     {
8834       p->user[i].width = MSG_EXT_WDTR_BUS_8_BIT;
8835     }
8836   }
8837   aic_outb(p, ~(p->discenable & 0xFF), DISC_DSB);
8838   aic_outb(p, ~((p->discenable >> 8) & 0xFF), DISC_DSB + 1);
8839
8840   /*
8841    * We set the p->ultraenb from the SEEPROM to begin with, but now we make
8842    * it match what is already down in the card.  If we are doing a reset
8843    * on the card then this will get put back to a default state anyway.
8844    * This allows us to not have to pre-emptively negotiate when using the
8845    * no_reset option.
8846    */
8847   if (p->features & AHC_ULTRA)
8848     p->ultraenb = aic_inb(p, ULTRA_ENB) | (aic_inb(p, ULTRA_ENB + 1) << 8);
8849
8850   
8851   scsi_conf = (p->scsi_id & HSCSIID);
8852
8853   if(have_seeprom)
8854   {
8855     p->adapter_control = sc->adapter_control;
8856     p->bios_control = sc->bios_control;
8857
8858     switch (p->chip & AHC_CHIPID_MASK)
8859     {
8860       case AHC_AIC7895:
8861       case AHC_AIC7896:
8862       case AHC_AIC7899:
8863         if (p->adapter_control & CFBPRIMARY)
8864           p->flags |= AHC_CHANNEL_B_PRIMARY;
8865       default:
8866         break;
8867     }
8868
8869     if (sc->adapter_control & CFSPARITY)
8870       scsi_conf |= ENSPCHK;
8871   }
8872   else
8873   {
8874     scsi_conf |= ENSPCHK | RESET_SCSI;
8875   }
8876
8877   /*
8878    * Only set the SCSICONF and SCSICONF + 1 registers if we are a PCI card.
8879    * The 2842 and 2742 cards already have these registers set and we don't
8880    * want to muck with them since we don't set all the bits they do.
8881    */
8882   if ( (p->chip & ~AHC_CHIPID_MASK) == AHC_PCI )
8883   {
8884     /* Set the host ID */
8885     aic_outb(p, scsi_conf, SCSICONF);
8886     /* In case we are a wide card */
8887     aic_outb(p, p->scsi_id, SCSICONF + 1);
8888   }
8889 }
8890
8891 /*+F*************************************************************************
8892  * Function:
8893  *   aic7xxx_configure_bugs
8894  *
8895  * Description:
8896  *   Take the card passed in and set the appropriate bug flags based upon
8897  *   the card model.  Also make any changes needed to device registers or
8898  *   PCI registers while we are here.
8899  *-F*************************************************************************/
8900 static void
8901 aic7xxx_configure_bugs(struct aic7xxx_host *p)
8902 {
8903   unsigned short tmp_word;
8904  
8905   switch(p->chip & AHC_CHIPID_MASK)
8906   {
8907     case AHC_AIC7860:
8908       p->bugs |= AHC_BUG_PCI_2_1_RETRY;
8909       /* fall through */
8910     case AHC_AIC7850:
8911     case AHC_AIC7870:
8912       p->bugs |= AHC_BUG_TMODE_WIDEODD | AHC_BUG_CACHETHEN | AHC_BUG_PCI_MWI;
8913       break;
8914     case AHC_AIC7880:
8915       p->bugs |= AHC_BUG_TMODE_WIDEODD | AHC_BUG_PCI_2_1_RETRY |
8916                  AHC_BUG_CACHETHEN | AHC_BUG_PCI_MWI;
8917       break;
8918     case AHC_AIC7890:
8919       p->bugs |= AHC_BUG_AUTOFLUSH | AHC_BUG_CACHETHEN;
8920       break;
8921     case AHC_AIC7892:
8922       p->bugs |= AHC_BUG_SCBCHAN_UPLOAD;
8923       break;
8924     case AHC_AIC7895:
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_AIC7896:
8929       p->bugs |= AHC_BUG_CACHETHEN_DIS;
8930       break;
8931     case AHC_AIC7899:
8932       p->bugs |= AHC_BUG_SCBCHAN_UPLOAD;
8933       break;
8934     default:
8935       /* Nothing to do */
8936       break;
8937   }
8938
8939   /*
8940    * Now handle the bugs that require PCI register or card register tweaks
8941    */
8942   pci_read_config_word(p->pdev, PCI_COMMAND, &tmp_word);
8943   if(p->bugs & AHC_BUG_PCI_MWI)
8944   {
8945     tmp_word &= ~PCI_COMMAND_INVALIDATE;
8946   }
8947   else
8948   {
8949     tmp_word |= PCI_COMMAND_INVALIDATE;
8950   }
8951   pci_write_config_word(p->pdev, PCI_COMMAND, tmp_word);
8952
8953   if(p->bugs & AHC_BUG_CACHETHEN)
8954   {
8955     aic_outb(p, aic_inb(p, DSCOMMAND0) & ~CACHETHEN, DSCOMMAND0);
8956   }
8957   else if (p->bugs & AHC_BUG_CACHETHEN_DIS)
8958   {
8959     aic_outb(p, aic_inb(p, DSCOMMAND0) | CACHETHEN, DSCOMMAND0);
8960   }
8961
8962   return;
8963 }
8964
8965
8966 /*+F*************************************************************************
8967  * Function:
8968  *   aic7xxx_detect
8969  *
8970  * Description:
8971  *   Try to detect and register an Adaptec 7770 or 7870 SCSI controller.
8972  *
8973  * XXX - This should really be called aic7xxx_probe().  A sequence of
8974  *       probe(), attach()/detach(), and init() makes more sense than
8975  *       one do-it-all function.  This may be useful when (and if) the
8976  *       mid-level SCSI code is overhauled.
8977  *-F*************************************************************************/
8978 static int
8979 aic7xxx_detect(struct scsi_host_template *template)
8980 {
8981   struct aic7xxx_host *temp_p = NULL;
8982   struct aic7xxx_host *current_p = NULL;
8983   struct aic7xxx_host *list_p = NULL;
8984   int found = 0;
8985 #if defined(__i386__) || defined(__alpha__)
8986   ahc_flag_type flags = 0;
8987   int type;
8988 #endif
8989   unsigned char sxfrctl1;
8990 #if defined(__i386__) || defined(__alpha__)
8991   unsigned char hcntrl, hostconf;
8992   unsigned int slot, base;
8993 #endif
8994
8995 #ifdef MODULE
8996   /*
8997    * If we are called as a module, the aic7xxx pointer may not be null
8998    * and it would point to our bootup string, just like on the lilo
8999    * command line.  IF not NULL, then process this config string with
9000    * aic7xxx_setup
9001    */
9002   if(aic7xxx)
9003     aic7xxx_setup(aic7xxx);
9004 #endif
9005
9006   template->proc_name = "aic7xxx";
9007   template->sg_tablesize = AIC7XXX_MAX_SG;
9008
9009
9010 #ifdef CONFIG_PCI
9011   /*
9012    * PCI-bus probe.
9013    */
9014   {
9015     static struct
9016     {
9017       unsigned short      vendor_id;
9018       unsigned short      device_id;
9019       ahc_chip            chip;
9020       ahc_flag_type       flags;
9021       ahc_feature         features;
9022       int                 board_name_index;
9023       unsigned short      seeprom_size;
9024       unsigned short      seeprom_type;
9025     } const aic_pdevs[] = {
9026       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7810, AHC_NONE,
9027        AHC_FNONE, AHC_FENONE,                                1,
9028        32, C46 },
9029       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7850, AHC_AIC7850,
9030        AHC_PAGESCBS, AHC_AIC7850_FE,                         5,
9031        32, C46 },
9032       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7855, AHC_AIC7850,
9033        AHC_PAGESCBS, AHC_AIC7850_FE,                         6,
9034        32, C46 },
9035       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7821, AHC_AIC7860,
9036        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9037        AHC_AIC7860_FE,                                       7,
9038        32, C46 },
9039       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_3860, AHC_AIC7860,
9040        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9041        AHC_AIC7860_FE,                                       7,
9042        32, C46 },
9043       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_38602, AHC_AIC7860,
9044        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9045        AHC_AIC7860_FE,                                       7,
9046        32, C46 },
9047       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_38602, AHC_AIC7860,
9048        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9049        AHC_AIC7860_FE,                                       7,
9050        32, C46 },
9051       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7860, AHC_AIC7860,
9052        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MOTHERBOARD,
9053        AHC_AIC7860_FE,                                       7,
9054        32, C46 },
9055       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7861, AHC_AIC7860,
9056        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9057        AHC_AIC7860_FE,                                       8,
9058        32, C46 },
9059       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7870, AHC_AIC7870,
9060        AHC_PAGESCBS | AHC_BIOS_ENABLED | AHC_MOTHERBOARD,
9061        AHC_AIC7870_FE,                                       9,
9062        32, C46 },
9063       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7871, AHC_AIC7870,
9064        AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7870_FE,     10,
9065        32, C46 },
9066       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7872, AHC_AIC7870,
9067        AHC_PAGESCBS | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9068        AHC_AIC7870_FE,                                      11,
9069        32, C56_66 },
9070       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7873, AHC_AIC7870,
9071        AHC_PAGESCBS | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9072        AHC_AIC7870_FE,                                      12,
9073        32, C56_66 },
9074       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7874, AHC_AIC7870,
9075        AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7870_FE,     13,
9076        32, C46 },
9077       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7880, AHC_AIC7880,
9078        AHC_PAGESCBS | AHC_BIOS_ENABLED | AHC_MOTHERBOARD,
9079        AHC_AIC7880_FE,                                      14,
9080        32, C46 },
9081       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7881, AHC_AIC7880,
9082        AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7880_FE,     15,
9083        32, C46 },
9084       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7882, AHC_AIC7880,
9085        AHC_PAGESCBS | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9086        AHC_AIC7880_FE,                                      16,
9087        32, C56_66 },
9088       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7883, AHC_AIC7880,
9089        AHC_PAGESCBS | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9090        AHC_AIC7880_FE,                                      17,
9091        32, C56_66 },
9092       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7884, AHC_AIC7880,
9093        AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7880_FE,     18,
9094        32, C46 },
9095       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7885, AHC_AIC7880,
9096        AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7880_FE,     18,
9097        32, C46 },
9098       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7886, AHC_AIC7880,
9099        AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7880_FE,     18,
9100        32, C46 },
9101       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7887, AHC_AIC7880,
9102        AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7880_FE | AHC_NEW_AUTOTERM, 19,
9103        32, C46 },
9104       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7888, AHC_AIC7880,
9105        AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7880_FE,     18,
9106        32, C46 },
9107       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7895, AHC_AIC7895,
9108        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9109        AHC_AIC7895_FE,                                      20,
9110        32, C56_66 },
9111       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7890, AHC_AIC7890,
9112        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9113        AHC_AIC7890_FE,                                      21,
9114        32, C46 },
9115       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7890B, AHC_AIC7890,
9116        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9117        AHC_AIC7890_FE,                                      21,
9118        32, C46 },
9119       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_2930U2, AHC_AIC7890,
9120        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9121        AHC_AIC7890_FE,                                      22,
9122        32, C46 },
9123       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_2940U2, AHC_AIC7890,
9124        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9125        AHC_AIC7890_FE,                                      23,
9126        32, C46 },
9127       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7896, AHC_AIC7896,
9128        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9129        AHC_AIC7896_FE,                                      24,
9130        32, C56_66 },
9131       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_3940U2, AHC_AIC7896,
9132        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9133        AHC_AIC7896_FE,                                      25,
9134        32, C56_66 },
9135       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_3950U2D, AHC_AIC7896,
9136        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9137        AHC_AIC7896_FE,                                      26,
9138        32, C56_66 },
9139       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_1480A, AHC_AIC7860,
9140        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_NO_STPWEN,
9141        AHC_AIC7860_FE,                                      27,
9142        32, C46 },
9143       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7892A, AHC_AIC7892,
9144        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9145        AHC_AIC7892_FE,                                      28,
9146        32, C46 },
9147       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7892B, AHC_AIC7892,
9148        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9149        AHC_AIC7892_FE,                                      28,
9150        32, C46 },
9151       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7892D, AHC_AIC7892,
9152        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9153        AHC_AIC7892_FE,                                      28,
9154        32, C46 },
9155       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7892P, AHC_AIC7892,
9156        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9157        AHC_AIC7892_FE,                                      28,
9158        32, C46 },
9159       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7899A, AHC_AIC7899,
9160        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9161        AHC_AIC7899_FE,                                      29,
9162        32, C56_66 },
9163       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7899B, AHC_AIC7899,
9164        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9165        AHC_AIC7899_FE,                                      29,
9166        32, C56_66 },
9167       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7899D, AHC_AIC7899,
9168        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9169        AHC_AIC7899_FE,                                      29,
9170        32, C56_66 },
9171       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7899P, AHC_AIC7899,
9172        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9173        AHC_AIC7899_FE,                                      29,
9174        32, C56_66 },
9175     };
9176
9177     unsigned short command;
9178     unsigned int  devconfig, i, oldverbose;
9179     struct pci_dev *pdev = NULL;
9180
9181     for (i = 0; i < ARRAY_SIZE(aic_pdevs); i++)
9182     {
9183       pdev = NULL;
9184       while ((pdev = pci_get_device(aic_pdevs[i].vendor_id,
9185                                      aic_pdevs[i].device_id,
9186                                      pdev))) {
9187         if (pci_enable_device(pdev))
9188                 continue;
9189         if ( i == 0 ) /* We found one, but it's the 7810 RAID cont. */
9190         {
9191           if (aic7xxx_verbose & (VERBOSE_PROBE|VERBOSE_PROBE2))
9192           {
9193             printk(KERN_INFO "aic7xxx: The 7810 RAID controller is not "
9194               "supported by\n");
9195             printk(KERN_INFO "         this driver, we are ignoring it.\n");
9196           }
9197         }
9198         else if ( (temp_p = kzalloc(sizeof(struct aic7xxx_host),
9199                                     GFP_ATOMIC)) != NULL )
9200         {
9201           temp_p->chip = aic_pdevs[i].chip | AHC_PCI;
9202           temp_p->flags = aic_pdevs[i].flags;
9203           temp_p->features = aic_pdevs[i].features;
9204           temp_p->board_name_index = aic_pdevs[i].board_name_index;
9205           temp_p->sc_size = aic_pdevs[i].seeprom_size;
9206           temp_p->sc_type = aic_pdevs[i].seeprom_type;
9207
9208           /*
9209            * Read sundry information from PCI BIOS.
9210            */
9211           temp_p->irq = pdev->irq;
9212           temp_p->pdev = pdev;
9213           temp_p->pci_bus = pdev->bus->number;
9214           temp_p->pci_device_fn = pdev->devfn;
9215           temp_p->base = pci_resource_start(pdev, 0);
9216           temp_p->mbase = pci_resource_start(pdev, 1);
9217           current_p = list_p;
9218           while(current_p && temp_p)
9219           {
9220             if ( ((current_p->pci_bus == temp_p->pci_bus) &&
9221                   (current_p->pci_device_fn == temp_p->pci_device_fn)) ||
9222                  (temp_p->base && (current_p->base == temp_p->base)) ||
9223                  (temp_p->mbase && (current_p->mbase == temp_p->mbase)) )
9224             {
9225               /* duplicate PCI entry, skip it */
9226               kfree(temp_p);
9227               temp_p = NULL;
9228               continue;
9229             }
9230             current_p = current_p->next;
9231           }
9232           if(pci_request_regions(temp_p->pdev, "aic7xxx"))
9233           {
9234             printk("aic7xxx: <%s> at PCI %d/%d/%d\n", 
9235               board_names[aic_pdevs[i].board_name_index],
9236               temp_p->pci_bus,
9237               PCI_SLOT(temp_p->pci_device_fn),
9238               PCI_FUNC(temp_p->pci_device_fn));
9239             printk("aic7xxx: I/O ports already in use, ignoring.\n");
9240             kfree(temp_p);
9241             continue;
9242           }
9243
9244           if (aic7xxx_verbose & VERBOSE_PROBE2)
9245             printk("aic7xxx: <%s> at PCI %d/%d\n", 
9246               board_names[aic_pdevs[i].board_name_index],
9247               PCI_SLOT(pdev->devfn),
9248               PCI_FUNC(pdev->devfn));
9249           pci_read_config_word(pdev, PCI_COMMAND, &command);
9250           if (aic7xxx_verbose & VERBOSE_PROBE2)
9251           {
9252             printk("aic7xxx: Initial PCI_COMMAND value was 0x%x\n",
9253               (int)command);
9254           }
9255 #ifdef AIC7XXX_STRICT_PCI_SETUP
9256           command |= PCI_COMMAND_SERR | PCI_COMMAND_PARITY |
9257             PCI_COMMAND_MASTER | PCI_COMMAND_MEMORY | PCI_COMMAND_IO;
9258 #else
9259           command |= PCI_COMMAND_MASTER | PCI_COMMAND_MEMORY | PCI_COMMAND_IO;
9260 #endif
9261           command &= ~PCI_COMMAND_INVALIDATE;
9262           if (aic7xxx_pci_parity == 0)
9263             command &= ~(PCI_COMMAND_SERR | PCI_COMMAND_PARITY);
9264           pci_write_config_word(pdev, PCI_COMMAND, command);
9265 #ifdef AIC7XXX_STRICT_PCI_SETUP
9266           pci_read_config_dword(pdev, DEVCONFIG, &devconfig);
9267           if (aic7xxx_verbose & VERBOSE_PROBE2)
9268           {
9269             printk("aic7xxx: Initial DEVCONFIG value was 0x%x\n", devconfig);
9270           }
9271           devconfig |= 0x80000040;
9272           pci_write_config_dword(pdev, DEVCONFIG, devconfig);
9273 #endif /* AIC7XXX_STRICT_PCI_SETUP */
9274
9275           temp_p->unpause = INTEN;
9276           temp_p->pause = temp_p->unpause | PAUSE;
9277           if ( ((temp_p->base == 0) &&
9278                 (temp_p->mbase == 0)) ||
9279                (temp_p->irq == 0) )
9280           {
9281             printk("aic7xxx: <%s> at PCI %d/%d/%d\n", 
9282               board_names[aic_pdevs[i].board_name_index],
9283               temp_p->pci_bus,
9284               PCI_SLOT(temp_p->pci_device_fn),
9285               PCI_FUNC(temp_p->pci_device_fn));
9286             printk("aic7xxx: Controller disabled by BIOS, ignoring.\n");
9287             goto skip_pci_controller;
9288           }
9289
9290 #ifdef MMAPIO
9291           if ( !(temp_p->base) || !(temp_p->flags & AHC_MULTI_CHANNEL) ||
9292                ((temp_p->chip != (AHC_AIC7870 | AHC_PCI)) &&
9293                 (temp_p->chip != (AHC_AIC7880 | AHC_PCI))) )
9294           {
9295             temp_p->maddr = ioremap_nocache(temp_p->mbase, 256);
9296             if(temp_p->maddr)
9297             {
9298               /*
9299                * We need to check the I/O with the MMAPed address.  Some machines
9300                * simply fail to work with MMAPed I/O and certain controllers.
9301                */
9302               if(aic_inb(temp_p, HCNTRL) == 0xff)
9303               {
9304                 /*
9305                  * OK.....we failed our test....go back to programmed I/O
9306                  */
9307                 printk(KERN_INFO "aic7xxx: <%s> at PCI %d/%d/%d\n", 
9308                   board_names[aic_pdevs[i].board_name_index],
9309                   temp_p->pci_bus,
9310                   PCI_SLOT(temp_p->pci_device_fn),
9311                   PCI_FUNC(temp_p->pci_device_fn));
9312                 printk(KERN_INFO "aic7xxx: MMAPed I/O failed, reverting to "
9313                                  "Programmed I/O.\n");
9314                 iounmap(temp_p->maddr);
9315                 temp_p->maddr = NULL;
9316                 if(temp_p->base == 0)
9317                 {
9318                   printk("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("aic7xxx: Controller disabled by BIOS, ignoring.\n");
9324                   goto skip_pci_controller;
9325                 }
9326               }
9327             }
9328           }
9329 #endif
9330
9331           /*
9332            * We HAVE to make sure the first pause_sequencer() and all other
9333            * subsequent I/O that isn't PCI config space I/O takes place
9334            * after the MMAPed I/O region is configured and tested.  The
9335            * problem is the PowerPC architecture that doesn't support
9336            * programmed I/O at all, so we have to have the MMAP I/O set up
9337            * for this pause to even work on those machines.
9338            */
9339           pause_sequencer(temp_p);
9340
9341           /*
9342            * Clear out any pending PCI error status messages.  Also set
9343            * verbose to 0 so that we don't emit strange PCI error messages
9344            * while cleaning out the current status bits.
9345            */
9346           oldverbose = aic7xxx_verbose;
9347           aic7xxx_verbose = 0;
9348           aic7xxx_pci_intr(temp_p);
9349           aic7xxx_verbose = oldverbose;
9350
9351           temp_p->bios_address = 0;
9352
9353           /*
9354            * Remember how the card was setup in case there is no seeprom.
9355            */
9356           if (temp_p->features & AHC_ULTRA2)
9357             temp_p->scsi_id = aic_inb(temp_p, SCSIID_ULTRA2) & OID;
9358           else
9359             temp_p->scsi_id = aic_inb(temp_p, SCSIID) & OID;
9360           /*
9361            * Get current termination setting
9362            */
9363           sxfrctl1 = aic_inb(temp_p, SXFRCTL1);
9364
9365           if (aic7xxx_chip_reset(temp_p) == -1)
9366           {
9367             goto skip_pci_controller;
9368           }
9369           /*
9370            * Very quickly put the term setting back into the register since
9371            * the chip reset may cause odd things to happen.  This is to keep
9372            * LVD busses with lots of drives from draining the power out of
9373            * the diffsense line before we get around to running the
9374            * configure_termination() function.  Also restore the STPWLEVEL
9375            * bit of DEVCONFIG
9376            */
9377           aic_outb(temp_p, sxfrctl1, SXFRCTL1);
9378           pci_write_config_dword(temp_p->pdev, DEVCONFIG, devconfig);
9379           sxfrctl1 &= STPWEN;
9380
9381           /*
9382            * We need to set the CHNL? assignments before loading the SEEPROM
9383            * The 3940 and 3985 cards (original stuff, not any of the later
9384            * stuff) are 7870 and 7880 class chips.  The Ultra2 stuff falls
9385            * under 7896 and 7897.  The 7895 is in a class by itself :)
9386            */
9387           switch (temp_p->chip & AHC_CHIPID_MASK)
9388           {
9389             case AHC_AIC7870: /* 3840 / 3985 */
9390             case AHC_AIC7880: /* 3840 UW / 3985 UW */
9391               if(temp_p->flags & AHC_MULTI_CHANNEL)
9392               {
9393                 switch(PCI_SLOT(temp_p->pci_device_fn))
9394                 {
9395                   case 5:
9396                     temp_p->flags |= AHC_CHNLB;
9397                     break;
9398                   case 8:
9399                     temp_p->flags |= AHC_CHNLB;
9400                     break;
9401                   case 12:
9402                     temp_p->flags |= AHC_CHNLC;
9403                     break;
9404                   default:
9405                     break;
9406                 }
9407               }
9408               break;
9409
9410             case AHC_AIC7895: /* 7895 */
9411             case AHC_AIC7896: /* 7896/7 */
9412             case AHC_AIC7899: /* 7899 */
9413               if (PCI_FUNC(pdev->devfn) != 0)
9414               {
9415                 temp_p->flags |= AHC_CHNLB;
9416               }
9417               /*
9418                * The 7895 is the only chipset that sets the SCBSIZE32 param
9419                * in the DEVCONFIG register.  The Ultra2 chipsets use
9420                * the DSCOMMAND0 register instead.
9421                */
9422               if ((temp_p->chip & AHC_CHIPID_MASK) == AHC_AIC7895)
9423               {
9424                 pci_read_config_dword(pdev, DEVCONFIG, &devconfig);
9425                 devconfig |= SCBSIZE32;
9426                 pci_write_config_dword(pdev, DEVCONFIG, devconfig);
9427               }
9428               break;
9429             default:
9430               break;
9431           }
9432
9433           /*
9434            * Loading of the SEEPROM needs to come after we've set the flags
9435            * to indicate possible CHNLB and CHNLC assigments.  Otherwise,
9436            * on 394x and 398x cards we'll end up reading the wrong settings
9437            * for channels B and C
9438            */
9439           switch (temp_p->chip & AHC_CHIPID_MASK)
9440           {
9441             case AHC_AIC7892:
9442             case AHC_AIC7899:
9443               aic_outb(temp_p, 0, SCAMCTL);
9444               /*
9445                * Switch to the alt mode of the chip...
9446                */
9447               aic_outb(temp_p, aic_inb(temp_p, SFUNCT) | ALT_MODE, SFUNCT);
9448               /*
9449                * Set our options...the last two items set our CRC after x byte
9450                * count in target mode...
9451                */
9452               aic_outb(temp_p, AUTO_MSGOUT_DE | DIS_MSGIN_DUALEDGE, OPTIONMODE);
9453               aic_outb(temp_p, 0x00, 0x0b);
9454               aic_outb(temp_p, 0x10, 0x0a);
9455               /*
9456                * switch back to normal mode...
9457                */
9458               aic_outb(temp_p, aic_inb(temp_p, SFUNCT) & ~ALT_MODE, SFUNCT);
9459               aic_outb(temp_p, CRCVALCHKEN | CRCENDCHKEN | CRCREQCHKEN |
9460                                TARGCRCENDEN | TARGCRCCNTEN,
9461                        CRCCONTROL1);
9462               aic_outb(temp_p, ((aic_inb(temp_p, DSCOMMAND0) | USCBSIZE32 |
9463                                  MPARCKEN | CIOPARCKEN | CACHETHEN) & 
9464                                ~DPARCKEN), DSCOMMAND0);
9465               aic7xxx_load_seeprom(temp_p, &sxfrctl1);
9466               break;
9467             case AHC_AIC7890:
9468             case AHC_AIC7896:
9469               aic_outb(temp_p, 0, SCAMCTL);
9470               aic_outb(temp_p, (aic_inb(temp_p, DSCOMMAND0) |
9471                                 CACHETHEN | MPARCKEN | USCBSIZE32 |
9472                                 CIOPARCKEN) & ~DPARCKEN, DSCOMMAND0);
9473               aic7xxx_load_seeprom(temp_p, &sxfrctl1);
9474               break;
9475             case AHC_AIC7850:
9476             case AHC_AIC7860:
9477               /*
9478                * Set the DSCOMMAND0 register on these cards different from
9479                * on the 789x cards.  Also, read the SEEPROM as well.
9480                */
9481               aic_outb(temp_p, (aic_inb(temp_p, DSCOMMAND0) |
9482                                 CACHETHEN | MPARCKEN) & ~DPARCKEN,
9483                        DSCOMMAND0);
9484               /* FALLTHROUGH */
9485             default:
9486               aic7xxx_load_seeprom(temp_p, &sxfrctl1);
9487               break;
9488             case AHC_AIC7880:
9489               /*
9490                * Check the rev of the chipset before we change DSCOMMAND0
9491                */
9492               pci_read_config_dword(pdev, DEVCONFIG, &devconfig);
9493               if ((devconfig & 0xff) >= 1)
9494               {
9495                 aic_outb(temp_p, (aic_inb(temp_p, DSCOMMAND0) |
9496                                   CACHETHEN | MPARCKEN) & ~DPARCKEN,
9497                          DSCOMMAND0);
9498               }
9499               aic7xxx_load_seeprom(temp_p, &sxfrctl1);
9500               break;
9501           }
9502           
9503
9504           /*
9505            * and then we need another switch based on the type in order to
9506            * make sure the channel B primary flag is set properly on 7895
9507            * controllers....Arrrgggghhh!!!  We also have to catch the fact
9508            * that when you disable the BIOS on the 7895 on the Intel DK440LX
9509            * motherboard, and possibly others, it only sets the BIOS disabled
9510            * bit on the A channel...I think I'm starting to lean towards
9511            * going postal....
9512            */
9513           switch(temp_p->chip & AHC_CHIPID_MASK)
9514           {
9515             case AHC_AIC7895:
9516             case AHC_AIC7896:
9517             case AHC_AIC7899:
9518               current_p = list_p;
9519               while(current_p != NULL)
9520               {
9521                 if ( (current_p->pci_bus == temp_p->pci_bus) &&
9522                      (PCI_SLOT(current_p->pci_device_fn) ==
9523                       PCI_SLOT(temp_p->pci_device_fn)) )
9524                 {
9525                   if ( PCI_FUNC(current_p->pci_device_fn) == 0 )
9526                   {
9527                     temp_p->flags |= 
9528                       (current_p->flags & AHC_CHANNEL_B_PRIMARY);
9529                     temp_p->flags &= ~(AHC_BIOS_ENABLED|AHC_USEDEFAULTS);
9530                     temp_p->flags |=
9531                       (current_p->flags & (AHC_BIOS_ENABLED|AHC_USEDEFAULTS));
9532                   }
9533                   else
9534                   {
9535                     current_p->flags |=
9536                       (temp_p->flags & AHC_CHANNEL_B_PRIMARY);
9537                     current_p->flags &= ~(AHC_BIOS_ENABLED|AHC_USEDEFAULTS);
9538                     current_p->flags |=
9539                       (temp_p->flags & (AHC_BIOS_ENABLED|AHC_USEDEFAULTS));
9540                   }
9541                 }
9542                 current_p = current_p->next;
9543               }
9544               break;
9545             default:
9546               break;
9547           }
9548
9549           /*
9550            * We only support external SCB RAM on the 7895/6/7 chipsets.
9551            * We could support it on the 7890/1 easy enough, but I don't
9552            * know of any 7890/1 based cards that have it.  I do know
9553            * of 7895/6/7 cards that have it and they work properly.
9554            */
9555           switch(temp_p->chip & AHC_CHIPID_MASK)
9556           {
9557             default:
9558               break;
9559             case AHC_AIC7895:
9560             case AHC_AIC7896:
9561             case AHC_AIC7899:
9562               pci_read_config_dword(pdev, DEVCONFIG, &devconfig);
9563               if (temp_p->features & AHC_ULTRA2)
9564               {
9565                 if ( (aic_inb(temp_p, DSCOMMAND0) & RAMPSM_ULTRA2) &&
9566                      (aic7xxx_scbram) )
9567                 {
9568                   aic_outb(temp_p,
9569                            aic_inb(temp_p, DSCOMMAND0) & ~SCBRAMSEL_ULTRA2,
9570                            DSCOMMAND0);
9571                   temp_p->flags |= AHC_EXTERNAL_SRAM;
9572                   devconfig |= EXTSCBPEN;
9573                 }
9574                 else if (aic_inb(temp_p, DSCOMMAND0) & RAMPSM_ULTRA2)
9575                 {
9576                   printk(KERN_INFO "aic7xxx: <%s> at PCI %d/%d/%d\n", 
9577                     board_names[aic_pdevs[i].board_name_index],
9578                     temp_p->pci_bus,
9579                     PCI_SLOT(temp_p->pci_device_fn),
9580                     PCI_FUNC(temp_p->pci_device_fn));
9581                   printk("aic7xxx: external SCB RAM detected, "
9582                          "but not enabled\n");
9583                 }
9584               }
9585               else
9586               {
9587                 if ((devconfig & RAMPSM) && (aic7xxx_scbram))
9588                 {
9589                   devconfig &= ~SCBRAMSEL;
9590                   devconfig |= EXTSCBPEN;
9591                   temp_p->flags |= AHC_EXTERNAL_SRAM;
9592                 }
9593                 else if (devconfig & RAMPSM)
9594                 {
9595                   printk(KERN_INFO "aic7xxx: <%s> at PCI %d/%d/%d\n", 
9596                     board_names[aic_pdevs[i].board_name_index],
9597                     temp_p->pci_bus,
9598                     PCI_SLOT(temp_p->pci_device_fn),
9599                     PCI_FUNC(temp_p->pci_device_fn));
9600                   printk("aic7xxx: external SCB RAM detected, "
9601                          "but not enabled\n");
9602                 }
9603               }
9604               pci_write_config_dword(pdev, DEVCONFIG, devconfig);
9605               if ( (temp_p->flags & AHC_EXTERNAL_SRAM) &&
9606                    (temp_p->flags & AHC_CHNLB) )
9607                 aic_outb(temp_p, 1, CCSCBBADDR);
9608               break;
9609           }
9610
9611           /*
9612            * Take the LED out of diagnostic mode
9613            */
9614           aic_outb(temp_p, 
9615             (aic_inb(temp_p, SBLKCTL) & ~(DIAGLEDEN | DIAGLEDON)),
9616             SBLKCTL);
9617
9618           /*
9619            * We don't know where this is set in the SEEPROM or by the
9620            * BIOS, so we default to 100%.  On Ultra2 controllers, use 75%
9621            * instead.
9622            */
9623           if (temp_p->features & AHC_ULTRA2)
9624           {
9625             aic_outb(temp_p, RD_DFTHRSH_MAX | WR_DFTHRSH_MAX, DFF_THRSH);
9626           }
9627           else
9628           {
9629             aic_outb(temp_p, DFTHRSH_100, DSPCISTATUS);
9630           }
9631
9632           /*
9633            * Call our function to fixup any bugs that exist on this chipset.
9634            * This may muck with PCI settings and other device settings, so
9635            * make sure it's after all the other PCI and device register
9636            * tweaks so it can back out bad settings on specific broken cards.
9637            */
9638           aic7xxx_configure_bugs(temp_p);
9639
9640           /* Hold a pci device reference */
9641           pci_dev_get(temp_p->pdev);
9642
9643           if ( list_p == NULL )
9644           {
9645             list_p = current_p = temp_p;
9646           }
9647           else
9648           {
9649             current_p = list_p;
9650             while(current_p->next != NULL)
9651               current_p = current_p->next;
9652             current_p->next = temp_p;
9653           }
9654           temp_p->next = NULL;
9655           found++;
9656           continue;
9657 skip_pci_controller:
9658 #ifdef CONFIG_PCI
9659           pci_release_regions(temp_p->pdev);
9660 #endif
9661           kfree(temp_p);
9662         }  /* Found an Adaptec PCI device. */
9663         else /* Well, we found one, but we couldn't get any memory */
9664         {
9665           printk("aic7xxx: Found <%s>\n", 
9666             board_names[aic_pdevs[i].board_name_index]);
9667           printk(KERN_INFO "aic7xxx: Unable to allocate device memory, "
9668             "skipping.\n");
9669         }
9670       } /* while(pdev=....) */
9671     } /* for PCI_DEVICES */
9672   }
9673 #endif /* CONFIG_PCI */
9674
9675 #if defined(__i386__) || defined(__alpha__)
9676   /*
9677    * EISA/VL-bus card signature probe.
9678    */
9679   slot = MINSLOT;
9680   while ( (slot <= MAXSLOT) &&
9681          !(aic7xxx_no_probe) )
9682   {
9683     base = SLOTBASE(slot) + MINREG;
9684
9685     if (!request_region(base, MAXREG - MINREG, "aic7xxx"))
9686     {
9687       /*
9688        * Some other driver has staked a
9689        * claim to this i/o region already.
9690        */
9691       slot++;
9692       continue; /* back to the beginning of the for loop */
9693     }
9694     flags = 0;
9695     type = aic7xxx_probe(slot, base + AHC_HID0, &flags);
9696     if (type == -1)
9697     {
9698       release_region(base, MAXREG - MINREG);
9699       slot++;
9700       continue;
9701     }
9702     temp_p = kmalloc(sizeof(struct aic7xxx_host), GFP_ATOMIC);
9703     if (temp_p == NULL)
9704     {
9705       printk(KERN_WARNING "aic7xxx: Unable to allocate device space.\n");
9706       release_region(base, MAXREG - MINREG);
9707       slot++;
9708       continue; /* back to the beginning of the while loop */
9709     }
9710
9711     /*
9712      * Pause the card preserving the IRQ type.  Allow the operator
9713      * to override the IRQ trigger.
9714      */
9715     if (aic7xxx_irq_trigger == 1)
9716       hcntrl = IRQMS;  /* Level */
9717     else if (aic7xxx_irq_trigger == 0)
9718       hcntrl = 0;  /* Edge */
9719     else
9720       hcntrl = inb(base + HCNTRL) & IRQMS;  /* Default */
9721     memset(temp_p, 0, sizeof(struct aic7xxx_host));
9722     temp_p->unpause = hcntrl | INTEN;
9723     temp_p->pause = hcntrl | PAUSE | INTEN;
9724     temp_p->base = base;
9725     temp_p->mbase = 0;
9726     temp_p->maddr = NULL;
9727     temp_p->pci_bus = 0;
9728     temp_p->pci_device_fn = slot;
9729     aic_outb(temp_p, hcntrl | PAUSE, HCNTRL);
9730     while( (aic_inb(temp_p, HCNTRL) & PAUSE) == 0 ) ;
9731     if (aic7xxx_chip_reset(temp_p) == -1)
9732       temp_p->irq = 0;
9733     else
9734       temp_p->irq = aic_inb(temp_p, INTDEF) & 0x0F;
9735     temp_p->flags |= AHC_PAGESCBS;
9736
9737     switch (temp_p->irq)
9738     {
9739       case 9:
9740       case 10:
9741       case 11:
9742       case 12:
9743       case 14:
9744       case 15:
9745         break;
9746
9747       default:
9748         printk(KERN_WARNING "aic7xxx: Host adapter uses unsupported IRQ "
9749           "level %d, ignoring.\n", temp_p->irq);
9750         kfree(temp_p);
9751         release_region(base, MAXREG - MINREG);
9752         slot++;
9753         continue; /* back to the beginning of the while loop */
9754     }
9755
9756     /*
9757      * We are commited now, everything has been checked and this card
9758      * has been found, now we just set it up
9759      */
9760
9761     /*
9762      * Insert our new struct into the list at the end
9763      */
9764     if (list_p == NULL)
9765     {
9766       list_p = current_p = temp_p;
9767     }
9768     else
9769     {
9770       current_p = list_p;
9771       while (current_p->next != NULL)
9772         current_p = current_p->next;
9773       current_p->next = temp_p;
9774     }
9775
9776     switch (type)
9777     {
9778       case 0:
9779         temp_p->board_name_index = 2;
9780         if (aic7xxx_verbose & VERBOSE_PROBE2)
9781           printk("aic7xxx: <%s> at EISA %d\n",
9782                board_names[2], slot);
9783         /* FALLTHROUGH */
9784       case 1:
9785       {
9786         temp_p->chip = AHC_AIC7770 | AHC_EISA;
9787         temp_p->features |= AHC_AIC7770_FE;
9788         temp_p->bios_control = aic_inb(temp_p, HA_274_BIOSCTRL);
9789
9790         /*
9791          * Get the primary channel information.  Right now we don't
9792          * do anything with this, but someday we will be able to inform
9793          * the mid-level SCSI code which channel is primary.
9794          */
9795         if (temp_p->board_name_index == 0)
9796         {
9797           temp_p->board_name_index = 3;
9798           if (aic7xxx_verbose & VERBOSE_PROBE2)
9799             printk("aic7xxx: <%s> at EISA %d\n",
9800                  board_names[3], slot);
9801         }
9802         if (temp_p->bios_control & CHANNEL_B_PRIMARY)
9803         {
9804           temp_p->flags |= AHC_CHANNEL_B_PRIMARY;
9805         }
9806
9807         if ((temp_p->bios_control & BIOSMODE) == BIOSDISABLED)
9808         {
9809           temp_p->flags &= ~AHC_BIOS_ENABLED;
9810         }
9811         else
9812         {
9813           temp_p->flags &= ~AHC_USEDEFAULTS;
9814           temp_p->flags |= AHC_BIOS_ENABLED;
9815           if ( (temp_p->bios_control & 0x20) == 0 )
9816           {
9817             temp_p->bios_address = 0xcc000;
9818             temp_p->bios_address += (0x4000 * (temp_p->bios_control & 0x07));
9819           }
9820           else
9821           {
9822             temp_p->bios_address = 0xd0000;
9823             temp_p->bios_address += (0x8000 * (temp_p->bios_control & 0x06));
9824           }
9825         }
9826         temp_p->adapter_control = aic_inb(temp_p, SCSICONF) << 8;
9827         temp_p->adapter_control |= aic_inb(temp_p, SCSICONF + 1);
9828         if (temp_p->features & AHC_WIDE)
9829         {
9830           temp_p->scsi_id = temp_p->adapter_control & HWSCSIID;
9831           temp_p->scsi_id_b = temp_p->scsi_id;
9832         }
9833         else
9834         {
9835           temp_p->scsi_id = (temp_p->adapter_control >> 8) & HSCSIID;
9836           temp_p->scsi_id_b = temp_p->adapter_control & HSCSIID;
9837         }
9838         aic7xxx_load_seeprom(temp_p, &sxfrctl1);
9839         break;
9840       }
9841
9842       case 2:
9843       case 3:
9844         temp_p->chip = AHC_AIC7770 | AHC_VL;
9845         temp_p->features |= AHC_AIC7770_FE;
9846         if (type == 2)
9847           temp_p->flags |= AHC_BIOS_ENABLED;
9848         else
9849           temp_p->flags &= ~AHC_BIOS_ENABLED;
9850         if (aic_inb(temp_p, SCSICONF) & TERM_ENB)
9851           sxfrctl1 = STPWEN;
9852         aic7xxx_load_seeprom(temp_p, &sxfrctl1);
9853         temp_p->board_name_index = 4;
9854         if (aic7xxx_verbose & VERBOSE_PROBE2)
9855           printk("aic7xxx: <%s> at VLB %d\n",
9856                board_names[2], slot);
9857         switch( aic_inb(temp_p, STATUS_2840) & BIOS_SEL )
9858         {
9859           case 0x00:
9860             temp_p->bios_address = 0xe0000;
9861             break;
9862           case 0x20:
9863             temp_p->bios_address = 0xc8000;
9864             break;
9865           case 0x40:
9866             temp_p->bios_address = 0xd0000;
9867             break;
9868           case 0x60:
9869             temp_p->bios_address = 0xd8000;
9870             break;
9871           default:
9872             break; /* can't get here */
9873         }
9874         break;
9875
9876       default:  /* Won't get here. */
9877         break;
9878     }
9879     if (aic7xxx_verbose & VERBOSE_PROBE2)
9880     {
9881       printk(KERN_INFO "aic7xxx: BIOS %sabled, IO Port 0x%lx, IRQ %d (%s)\n",
9882         (temp_p->flags & AHC_USEDEFAULTS) ? "dis" : "en", temp_p->base,
9883         temp_p->irq,
9884         (temp_p->pause & IRQMS) ? "level sensitive" : "edge triggered");
9885       printk(KERN_INFO "aic7xxx: Extended translation %sabled.\n",
9886              (temp_p->flags & AHC_EXTEND_TRANS_A) ? "en" : "dis");
9887     }
9888
9889     /*
9890      * All the 7770 based chipsets have this bug
9891      */
9892     temp_p->bugs |= AHC_BUG_TMODE_WIDEODD;
9893
9894     /*
9895      * Set the FIFO threshold and the bus off time.
9896      */
9897     hostconf = aic_inb(temp_p, HOSTCONF);
9898     aic_outb(temp_p, hostconf & DFTHRSH, BUSSPD);
9899     aic_outb(temp_p, (hostconf << 2) & BOFF, BUSTIME);
9900     slot++;
9901     found++;
9902   }
9903
9904 #endif /* defined(__i386__) || defined(__alpha__) */
9905
9906   /*
9907    * Now, we re-order the probed devices by BIOS address and BUS class.
9908    * In general, we follow this algorithm to make the adapters show up
9909    * in the same order under linux that the computer finds them.
9910    *  1: All VLB/EISA cards with BIOS_ENABLED first, according to BIOS
9911    *     address, going from lowest to highest.
9912    *  2: All PCI controllers with BIOS_ENABLED next, according to BIOS
9913    *     address, going from lowest to highest.
9914    *  3: Remaining VLB/EISA controllers going in slot order.
9915    *  4: Remaining PCI controllers, going in PCI device order (reversable)
9916    */
9917
9918   {
9919     struct aic7xxx_host *sort_list[4] = { NULL, NULL, NULL, NULL };
9920     struct aic7xxx_host *vlb, *pci;
9921     struct aic7xxx_host *prev_p;
9922     struct aic7xxx_host *p;
9923     unsigned char left;
9924
9925     prev_p = vlb = pci = NULL;
9926
9927     temp_p = list_p;
9928     while (temp_p != NULL)
9929     {
9930       switch(temp_p->chip & ~AHC_CHIPID_MASK)
9931       {
9932         case AHC_EISA:
9933         case AHC_VL:
9934         {
9935           p = temp_p;
9936           if (p->flags & AHC_BIOS_ENABLED)
9937             vlb = sort_list[0];
9938           else
9939             vlb = sort_list[2];
9940
9941           if (vlb == NULL)
9942           {
9943             vlb = temp_p;
9944             temp_p = temp_p->next;
9945             vlb->next = NULL;
9946           }
9947           else
9948           {
9949             current_p = vlb;
9950             prev_p = NULL;
9951             while ( (current_p != NULL) &&
9952                     (current_p->bios_address < temp_p->bios_address))
9953             {
9954               prev_p = current_p;
9955               current_p = current_p->next;
9956             }
9957             if (prev_p != NULL)
9958             {
9959               prev_p->next = temp_p;
9960               temp_p = temp_p->next;
9961               prev_p->next->next = current_p;
9962             }
9963             else
9964             {
9965               vlb = temp_p;
9966               temp_p = temp_p->next;
9967               vlb->next = current_p;
9968             }
9969           }
9970           
9971           if (p->flags & AHC_BIOS_ENABLED)
9972             sort_list[0] = vlb;
9973           else
9974             sort_list[2] = vlb;
9975           
9976           break;
9977         }
9978         default:  /* All PCI controllers fall through to default */
9979         {
9980
9981           p = temp_p;
9982           if (p->flags & AHC_BIOS_ENABLED) 
9983             pci = sort_list[1];
9984           else
9985             pci = sort_list[3];
9986
9987           if (pci == NULL)
9988           {
9989             pci = temp_p;
9990             temp_p = temp_p->next;
9991             pci->next = NULL;
9992           }
9993           else
9994           {
9995             current_p = pci;
9996             prev_p = NULL;
9997             if (!aic7xxx_reverse_scan)
9998             {
9999               while ( (current_p != NULL) &&
10000                       ( (PCI_SLOT(current_p->pci_device_fn) |
10001                         (current_p->pci_bus << 8)) < 
10002                         (PCI_SLOT(temp_p->pci_device_fn) |
10003                         (temp_p->pci_bus << 8)) ) )
10004               {
10005                 prev_p = current_p;
10006                 current_p = current_p->next;
10007               }
10008             }
10009             else
10010             {
10011               while ( (current_p != NULL) &&
10012                       ( (PCI_SLOT(current_p->pci_device_fn) |
10013                         (current_p->pci_bus << 8)) > 
10014                         (PCI_SLOT(temp_p->pci_device_fn) |
10015                         (temp_p->pci_bus << 8)) ) )
10016               {
10017                 prev_p = current_p;
10018                 current_p = current_p->next;
10019               }
10020             }
10021             /*
10022              * Are we dealing with a 7895/6/7/9 where we need to sort the
10023              * channels as well, if so, the bios_address values should
10024              * be the same
10025              */
10026             if ( (current_p) && (temp_p->flags & AHC_MULTI_CHANNEL) &&
10027                  (temp_p->pci_bus == current_p->pci_bus) &&
10028                  (PCI_SLOT(temp_p->pci_device_fn) ==
10029                   PCI_SLOT(current_p->pci_device_fn)) )
10030             {
10031               if (temp_p->flags & AHC_CHNLB)
10032               {
10033                 if ( !(temp_p->flags & AHC_CHANNEL_B_PRIMARY) )
10034                 {
10035                   prev_p = current_p;
10036                   current_p = current_p->next;
10037                 }
10038               }
10039               else
10040               {
10041                 if (temp_p->flags & AHC_CHANNEL_B_PRIMARY)
10042                 {
10043                   prev_p = current_p;
10044                   current_p = current_p->next;
10045                 }
10046               }
10047             }
10048             if (prev_p != NULL)
10049             {
10050               prev_p->next = temp_p;
10051               temp_p = temp_p->next;
10052               prev_p->next->next = current_p;
10053             }
10054             else
10055             {
10056               pci = temp_p;
10057               temp_p = temp_p->next;
10058               pci->next = current_p;
10059             }
10060           }
10061
10062           if (p->flags & AHC_BIOS_ENABLED)
10063             sort_list[1] = pci;
10064           else
10065             sort_list[3] = pci;
10066
10067           break;
10068         }
10069       }  /* End of switch(temp_p->type) */
10070     } /* End of while (temp_p != NULL) */
10071     /*
10072      * At this point, the cards have been broken into 4 sorted lists, now
10073      * we run through the lists in order and register each controller
10074      */
10075     {
10076       int i;
10077       
10078       left = found;
10079       for (i=0; i<ARRAY_SIZE(sort_list); i++)
10080       {
10081         temp_p = sort_list[i];
10082         while(temp_p != NULL)
10083         {
10084           template->name = board_names[temp_p->board_name_index];
10085           p = aic7xxx_alloc(template, temp_p);
10086           if (p != NULL)
10087           {
10088             p->instance = found - left;
10089             if (aic7xxx_register(template, p, (--left)) == 0)
10090             {
10091               found--;
10092               aic7xxx_release(p->host);
10093               scsi_unregister(p->host);
10094             }
10095             else if (aic7xxx_dump_card)
10096             {
10097               pause_sequencer(p);
10098               aic7xxx_print_card(p);
10099               aic7xxx_print_scratch_ram(p);
10100               unpause_sequencer(p, TRUE);
10101             }
10102           }
10103           current_p = temp_p;
10104           temp_p = (struct aic7xxx_host *)temp_p->next;
10105           kfree(current_p);
10106         }
10107       }
10108     }
10109   }
10110   return (found);
10111 }
10112
10113 /*+F*************************************************************************
10114  * Function:
10115  *   aic7xxx_buildscb
10116  *
10117  * Description:
10118  *   Build a SCB.
10119  *-F*************************************************************************/
10120 static void aic7xxx_buildscb(struct aic7xxx_host *p, struct scsi_cmnd *cmd,
10121                              struct aic7xxx_scb *scb)
10122 {
10123   unsigned short mask;
10124   struct aic7xxx_hwscb *hscb;
10125   struct aic_dev_data *aic_dev = cmd->device->hostdata;
10126   struct scsi_device *sdptr = cmd->device;
10127   unsigned char tindex = TARGET_INDEX(cmd);
10128   struct request *req = cmd->request;
10129   int use_sg;
10130
10131   mask = (0x01 << tindex);
10132   hscb = scb->hscb;
10133
10134   /*
10135    * Setup the control byte if we need negotiation and have not
10136    * already requested it.
10137    */
10138   hscb->control = 0;
10139   scb->tag_action = 0;
10140
10141   if (p->discenable & mask)
10142   {
10143     hscb->control |= DISCENB;
10144     /* We always force TEST_UNIT_READY to untagged */
10145     if (cmd->cmnd[0] != TEST_UNIT_READY && sdptr->simple_tags)
10146     {
10147       if (req->cmd_flags & REQ_HARDBARRIER)
10148       {
10149         if(sdptr->ordered_tags)
10150         {
10151           hscb->control |= MSG_ORDERED_Q_TAG;
10152           scb->tag_action = MSG_ORDERED_Q_TAG;
10153         }
10154       }
10155       else
10156       {
10157         hscb->control |= MSG_SIMPLE_Q_TAG;
10158         scb->tag_action = MSG_SIMPLE_Q_TAG;
10159       }
10160     }
10161   }
10162   if ( !(aic_dev->dtr_pending) &&
10163         (aic_dev->needppr || aic_dev->needwdtr || aic_dev->needsdtr) &&
10164         (aic_dev->flags & DEVICE_DTR_SCANNED) )
10165   {
10166     aic_dev->dtr_pending = 1;
10167     scb->tag_action = 0;
10168     hscb->control &= DISCENB;
10169     hscb->control |= MK_MESSAGE;
10170     if(aic_dev->needppr)
10171     {
10172       scb->flags |= SCB_MSGOUT_PPR;
10173     }
10174     else if(aic_dev->needwdtr)
10175     {
10176       scb->flags |= SCB_MSGOUT_WDTR;
10177     }
10178     else if(aic_dev->needsdtr)
10179     {
10180       scb->flags |= SCB_MSGOUT_SDTR;
10181     }
10182     scb->flags |= SCB_DTR_SCB;
10183   }
10184   hscb->target_channel_lun = ((cmd->device->id << 4) & 0xF0) |
10185         ((cmd->device->channel & 0x01) << 3) | (cmd->device->lun & 0x07);
10186
10187   /*
10188    * The interpretation of request_buffer and request_bufflen
10189    * changes depending on whether or not use_sg is zero; a
10190    * non-zero use_sg indicates the number of elements in the
10191    * scatter-gather array.
10192    */
10193
10194   /*
10195    * XXX - this relies on the host data being stored in a
10196    *       little-endian format.
10197    */
10198   hscb->SCSI_cmd_length = cmd->cmd_len;
10199   memcpy(scb->cmnd, cmd->cmnd, cmd->cmd_len);
10200   hscb->SCSI_cmd_pointer = cpu_to_le32(SCB_DMA_ADDR(scb, scb->cmnd));
10201
10202   use_sg = scsi_dma_map(cmd);
10203   BUG_ON(use_sg < 0);
10204
10205   if (use_sg) {
10206     struct scatterlist *sg;  /* Must be mid-level SCSI code scatterlist */
10207
10208     /*
10209      * We must build an SG list in adapter format, as the kernel's SG list
10210      * cannot be used directly because of data field size (__alpha__)
10211      * differences and the kernel SG list uses virtual addresses where
10212      * we need physical addresses.
10213      */
10214     int i;
10215
10216     scb->sg_length = 0;
10217
10218
10219     /*
10220      * Copy the segments into the SG array.  NOTE!!! - We used to
10221      * have the first entry both in the data_pointer area and the first
10222      * SG element.  That has changed somewhat.  We still have the first
10223      * entry in both places, but now we download the address of
10224      * scb->sg_list[1] instead of 0 to the sg pointer in the hscb.
10225      */
10226     scsi_for_each_sg(cmd, sg, use_sg, i) {
10227       unsigned int len = sg_dma_len(sg);
10228       scb->sg_list[i].address = cpu_to_le32(sg_dma_address(sg));
10229       scb->sg_list[i].length = cpu_to_le32(len);
10230       scb->sg_length += len;
10231     }
10232     /* Copy the first SG into the data pointer area. */
10233     hscb->data_pointer = scb->sg_list[0].address;
10234     hscb->data_count = scb->sg_list[0].length;
10235     scb->sg_count = i;
10236     hscb->SG_segment_count = i;
10237     hscb->SG_list_pointer = cpu_to_le32(SCB_DMA_ADDR(scb, &scb->sg_list[1]));
10238   } else {
10239       scb->sg_count = 0;
10240       scb->sg_length = 0;
10241       hscb->SG_segment_count = 0;
10242       hscb->SG_list_pointer = 0;
10243       hscb->data_count = 0;
10244       hscb->data_pointer = 0;
10245   }
10246 }
10247
10248 /*+F*************************************************************************
10249  * Function:
10250  *   aic7xxx_queue
10251  *
10252  * Description:
10253  *   Queue a SCB to the controller.
10254  *-F*************************************************************************/
10255 static int aic7xxx_queue(struct scsi_cmnd *cmd, void (*fn)(struct scsi_cmnd *))
10256 {
10257   struct aic7xxx_host *p;
10258   struct aic7xxx_scb *scb;
10259   struct aic_dev_data *aic_dev;
10260
10261   p = (struct aic7xxx_host *) cmd->device->host->hostdata;
10262
10263   aic_dev = cmd->device->hostdata;  
10264 #ifdef AIC7XXX_VERBOSE_DEBUGGING
10265   if (aic_dev->active_cmds > aic_dev->max_q_depth)
10266   {
10267     printk(WARN_LEAD "Commands queued exceeds queue "
10268            "depth, active=%d\n",
10269            p->host_no, CTL_OF_CMD(cmd), 
10270            aic_dev->active_cmds);
10271   }
10272 #endif
10273
10274   scb = scbq_remove_head(&p->scb_data->free_scbs);
10275   if (scb == NULL)
10276   {
10277     aic7xxx_allocate_scb(p);
10278     scb = scbq_remove_head(&p->scb_data->free_scbs);
10279     if(scb == NULL)
10280     {
10281       printk(WARN_LEAD "Couldn't get a free SCB.\n", p->host_no,
10282              CTL_OF_CMD(cmd));
10283       return 1;
10284     }
10285   }
10286   scb->cmd = cmd;
10287
10288         /*
10289         * Make sure the scsi_cmnd pointer is saved, the struct it points to
10290         * is set up properly, and the parity error flag is reset, then send
10291         * the SCB to the sequencer and watch the fun begin.
10292         */
10293   aic7xxx_position(cmd) = scb->hscb->tag;
10294   cmd->scsi_done = fn;
10295   cmd->result = DID_OK;
10296   aic7xxx_error(cmd) = DID_OK;
10297   aic7xxx_status(cmd) = 0;
10298   cmd->host_scribble = NULL;
10299
10300   /*
10301    * Construct the SCB beforehand, so the sequencer is
10302    * paused a minimal amount of time.
10303    */
10304   aic7xxx_buildscb(p, cmd, scb);
10305
10306   scb->flags |= SCB_ACTIVE | SCB_WAITINGQ;
10307
10308   scbq_insert_tail(&p->waiting_scbs, scb);
10309   aic7xxx_run_waiting_queues(p);
10310   return (0);
10311 }
10312
10313 /*+F*************************************************************************
10314  * Function:
10315  *   aic7xxx_bus_device_reset
10316  *
10317  * Description:
10318  *   Abort or reset the current SCSI command(s).  If the scb has not
10319  *   previously been aborted, then we attempt to send a BUS_DEVICE_RESET
10320  *   message to the target.  If the scb has previously been unsuccessfully
10321  *   aborted, then we will reset the channel and have all devices renegotiate.
10322  *   Returns an enumerated type that indicates the status of the operation.
10323  *-F*************************************************************************/
10324 static int __aic7xxx_bus_device_reset(struct scsi_cmnd *cmd)
10325 {
10326   struct aic7xxx_host  *p;
10327   struct aic7xxx_scb   *scb;
10328   struct aic7xxx_hwscb *hscb;
10329   int channel;
10330   unsigned char saved_scbptr, lastphase;
10331   unsigned char hscb_index;
10332   int disconnected;
10333   struct aic_dev_data *aic_dev;
10334
10335   if(cmd == NULL)
10336   {
10337     printk(KERN_ERR "aic7xxx_bus_device_reset: called with NULL cmd!\n");
10338     return FAILED;
10339   }
10340   p = (struct aic7xxx_host *)cmd->device->host->hostdata;
10341   aic_dev = AIC_DEV(cmd);
10342   if(aic7xxx_position(cmd) < p->scb_data->numscbs)
10343     scb = (p->scb_data->scb_array[aic7xxx_position(cmd)]);
10344   else
10345     return FAILED;
10346
10347   hscb = scb->hscb;
10348
10349   aic7xxx_isr(p);
10350   aic7xxx_done_cmds_complete(p);
10351   /* If the command was already complete or just completed, then we didn't
10352    * do a reset, return FAILED */
10353   if(!(scb->flags & SCB_ACTIVE))
10354     return FAILED;
10355
10356   pause_sequencer(p);
10357   lastphase = aic_inb(p, LASTPHASE);
10358   if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
10359   {
10360     printk(INFO_LEAD "Bus Device reset, scb flags 0x%x, ",
10361          p->host_no, CTL_OF_SCB(scb), scb->flags);
10362     switch (lastphase)
10363     {
10364       case P_DATAOUT:
10365         printk("Data-Out phase\n");
10366         break;
10367       case P_DATAIN:
10368         printk("Data-In phase\n");
10369         break;
10370       case P_COMMAND:
10371         printk("Command phase\n");
10372         break;
10373       case P_MESGOUT:
10374         printk("Message-Out phase\n");
10375         break;
10376       case P_STATUS:
10377         printk("Status phase\n");
10378         break;
10379       case P_MESGIN:
10380         printk("Message-In phase\n");
10381         break;
10382       default:
10383       /*
10384        * We're not in a valid phase, so assume we're idle.
10385        */
10386         printk("while idle, LASTPHASE = 0x%x\n", lastphase);
10387         break;
10388     }
10389     printk(INFO_LEAD "SCSISIGI 0x%x, SEQADDR 0x%x, SSTAT0 0x%x, SSTAT1 "
10390          "0x%x\n", p->host_no, CTL_OF_SCB(scb),
10391          aic_inb(p, SCSISIGI),
10392          aic_inb(p, SEQADDR0) | (aic_inb(p, SEQADDR1) << 8),
10393          aic_inb(p, SSTAT0), aic_inb(p, SSTAT1));
10394     printk(INFO_LEAD "SG_CACHEPTR 0x%x, SSTAT2 0x%x, STCNT 0x%x\n", p->host_no,
10395          CTL_OF_SCB(scb),
10396          (p->features & AHC_ULTRA2) ? aic_inb(p, SG_CACHEPTR) : 0,
10397          aic_inb(p, SSTAT2),
10398          aic_inb(p, STCNT + 2) << 16 | aic_inb(p, STCNT + 1) << 8 |
10399          aic_inb(p, STCNT));
10400   }
10401
10402   channel = cmd->device->channel;
10403
10404     /*
10405      * Send a Device Reset Message:
10406      * The target that is holding up the bus may not be the same as
10407      * the one that triggered this timeout (different commands have
10408      * different timeout lengths).  Our strategy here is to queue an
10409      * abort message to the timed out target if it is disconnected.
10410      * Otherwise, if we have an active target we stuff the message buffer
10411      * with an abort message and assert ATN in the hopes that the target
10412      * will let go of the bus and go to the mesgout phase.  If this
10413      * fails, we'll get another timeout a few seconds later which will
10414      * attempt a bus reset.
10415      */
10416   saved_scbptr = aic_inb(p, SCBPTR);
10417   disconnected = FALSE;
10418
10419   if (lastphase != P_BUSFREE)
10420   {
10421     if (aic_inb(p, SCB_TAG) >= p->scb_data->numscbs)
10422     {
10423       printk(WARN_LEAD "Invalid SCB ID %d is active, "
10424              "SCB flags = 0x%x.\n", p->host_no,
10425             CTL_OF_CMD(cmd), scb->hscb->tag, scb->flags);
10426       unpause_sequencer(p, FALSE);
10427       return FAILED;
10428     }
10429     if (scb->hscb->tag == aic_inb(p, SCB_TAG))
10430     { 
10431       if ( (lastphase == P_MESGOUT) || (lastphase == P_MESGIN) )
10432       {
10433         printk(WARN_LEAD "Device reset, Message buffer "
10434                 "in use\n", p->host_no, CTL_OF_SCB(scb));
10435         unpause_sequencer(p, FALSE);
10436         return FAILED;
10437       }
10438         
10439       if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
10440         printk(INFO_LEAD "Device reset message in "
10441               "message buffer\n", p->host_no, CTL_OF_SCB(scb));
10442       scb->flags |= SCB_RESET | SCB_DEVICE_RESET;
10443       aic7xxx_error(cmd) = DID_RESET;
10444       aic_dev->flags |= BUS_DEVICE_RESET_PENDING;
10445       /* Send the abort message to the active SCB. */
10446       aic_outb(p, HOST_MSG, MSG_OUT);
10447       aic_outb(p, lastphase | ATNO, SCSISIGO);
10448       unpause_sequencer(p, FALSE);
10449       spin_unlock_irq(p->host->host_lock);
10450       ssleep(1);
10451       spin_lock_irq(p->host->host_lock);
10452       if(aic_dev->flags & BUS_DEVICE_RESET_PENDING)
10453         return FAILED;
10454       else
10455         return SUCCESS;
10456     }
10457   } /* if (last_phase != P_BUSFREE).....indicates we are idle and can work */
10458   /*
10459    * Simply set the MK_MESSAGE flag and the SEQINT handler will do
10460    * the rest on a reconnect/connect.
10461    */
10462   scb->hscb->control |= MK_MESSAGE;
10463   scb->flags |= SCB_RESET | SCB_DEVICE_RESET;
10464   aic_dev->flags |= BUS_DEVICE_RESET_PENDING;
10465   /*
10466    * Check to see if the command is on the qinfifo.  If it is, then we will
10467    * not need to queue the command again since the card should start it soon
10468    */
10469   if (aic7xxx_search_qinfifo(p, cmd->device->channel, cmd->device->id, cmd->device->lun, hscb->tag,
10470                           0, TRUE, NULL) == 0)
10471   {
10472     disconnected = TRUE;
10473     if ((hscb_index = aic7xxx_find_scb(p, scb)) != SCB_LIST_NULL)
10474     {
10475       unsigned char scb_control;
10476
10477       aic_outb(p, hscb_index, SCBPTR);
10478       scb_control = aic_inb(p, SCB_CONTROL);
10479       /*
10480        * If the DISCONNECTED bit is not set in SCB_CONTROL, then we are
10481        * actually on the waiting list, not disconnected, and we don't
10482        * need to requeue the command.
10483        */
10484       disconnected = (scb_control & DISCONNECTED);
10485       aic_outb(p, scb_control | MK_MESSAGE, SCB_CONTROL);
10486     }
10487     if (disconnected)
10488     {
10489       /*
10490        * Actually requeue this SCB in case we can select the
10491        * device before it reconnects.  This can result in the command
10492        * being on the qinfifo twice, but we don't care because it will
10493        * all get cleaned up if/when the reset takes place.
10494        */
10495       if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
10496         printk(INFO_LEAD "Queueing device reset command.\n", p->host_no,
10497                       CTL_OF_SCB(scb));
10498       p->qinfifo[p->qinfifonext++] = scb->hscb->tag;
10499       if (p->features & AHC_QUEUE_REGS)
10500         aic_outb(p, p->qinfifonext, HNSCB_QOFF);
10501       else
10502         aic_outb(p, p->qinfifonext, KERNEL_QINPOS);
10503       scb->flags |= SCB_QUEUED_ABORT;
10504     }
10505   }
10506   aic_outb(p, saved_scbptr, SCBPTR);
10507   unpause_sequencer(p, FALSE);
10508   spin_unlock_irq(p->host->host_lock);
10509   msleep(1000/4);
10510   spin_lock_irq(p->host->host_lock);
10511   if(aic_dev->flags & BUS_DEVICE_RESET_PENDING)
10512     return FAILED;
10513   else
10514     return SUCCESS;
10515 }
10516
10517 static int aic7xxx_bus_device_reset(struct scsi_cmnd *cmd)
10518 {
10519       int rc;
10520
10521       spin_lock_irq(cmd->device->host->host_lock);
10522       rc = __aic7xxx_bus_device_reset(cmd);
10523       spin_unlock_irq(cmd->device->host->host_lock);
10524
10525       return rc;
10526 }
10527
10528
10529 /*+F*************************************************************************
10530  * Function:
10531  *   aic7xxx_panic_abort
10532  *
10533  * Description:
10534  *   Abort the current SCSI command(s).
10535  *-F*************************************************************************/
10536 static void aic7xxx_panic_abort(struct aic7xxx_host *p, struct scsi_cmnd *cmd)
10537 {
10538
10539   printk("aic7xxx driver version %s\n", AIC7XXX_C_VERSION);
10540   printk("Controller type:\n    %s\n", board_names[p->board_name_index]);
10541   printk("p->flags=0x%lx, p->chip=0x%x, p->features=0x%x, "
10542          "sequencer %s paused\n",
10543      p->flags, p->chip, p->features,
10544     (aic_inb(p, HCNTRL) & PAUSE) ? "is" : "isn't" );
10545   pause_sequencer(p);
10546   disable_irq(p->irq);
10547   aic7xxx_print_card(p);
10548   aic7xxx_print_scratch_ram(p);
10549   spin_unlock_irq(p->host->host_lock);
10550   for(;;) barrier();
10551 }
10552
10553 /*+F*************************************************************************
10554  * Function:
10555  *   aic7xxx_abort
10556  *
10557  * Description:
10558  *   Abort the current SCSI command(s).
10559  *-F*************************************************************************/
10560 static int __aic7xxx_abort(struct scsi_cmnd *cmd)
10561 {
10562   struct aic7xxx_scb  *scb = NULL;
10563   struct aic7xxx_host *p;
10564   int    found=0, disconnected;
10565   unsigned char saved_hscbptr, hscbptr, scb_control;
10566   struct aic_dev_data *aic_dev;
10567
10568   if(cmd == NULL)
10569   {
10570     printk(KERN_ERR "aic7xxx_abort: called with NULL cmd!\n");
10571     return FAILED;
10572   }
10573   p = (struct aic7xxx_host *)cmd->device->host->hostdata;
10574   aic_dev = AIC_DEV(cmd);
10575   if(aic7xxx_position(cmd) < p->scb_data->numscbs)
10576     scb = (p->scb_data->scb_array[aic7xxx_position(cmd)]);
10577   else
10578     return FAILED;
10579
10580   aic7xxx_isr(p);
10581   aic7xxx_done_cmds_complete(p);
10582   /* If the command was already complete or just completed, then we didn't
10583    * do a reset, return FAILED */
10584   if(!(scb->flags & SCB_ACTIVE))
10585     return FAILED;
10586
10587   pause_sequencer(p);
10588
10589   /*
10590    * I added a new config option to the driver: "panic_on_abort" that will
10591    * cause the driver to panic and the machine to stop on the first abort
10592    * or reset call into the driver.  At that point, it prints out a lot of
10593    * useful information for me which I can then use to try and debug the
10594    * problem.  Simply enable the boot time prompt in order to activate this
10595    * code.
10596    */
10597   if (aic7xxx_panic_on_abort)
10598     aic7xxx_panic_abort(p, cmd);
10599
10600   if (aic7xxx_verbose & VERBOSE_ABORT)
10601   {
10602     printk(INFO_LEAD "Aborting scb %d, flags 0x%x, SEQADDR 0x%x, LASTPHASE "
10603            "0x%x\n",
10604          p->host_no, CTL_OF_SCB(scb), scb->hscb->tag, scb->flags,
10605          aic_inb(p, SEQADDR0) | (aic_inb(p, SEQADDR1) << 8),
10606          aic_inb(p, LASTPHASE));
10607     printk(INFO_LEAD "SG_CACHEPTR 0x%x, SG_COUNT %d, SCSISIGI 0x%x\n",
10608          p->host_no, CTL_OF_SCB(scb), (p->features & AHC_ULTRA2) ?
10609          aic_inb(p, SG_CACHEPTR) : 0, aic_inb(p, SG_COUNT),
10610          aic_inb(p, SCSISIGI));
10611     printk(INFO_LEAD "SSTAT0 0x%x, SSTAT1 0x%x, SSTAT2 0x%x\n",
10612          p->host_no, CTL_OF_SCB(scb), aic_inb(p, SSTAT0),
10613          aic_inb(p, SSTAT1), aic_inb(p, SSTAT2));
10614   }
10615
10616   if (scb->flags & SCB_WAITINGQ)
10617   {
10618     if (aic7xxx_verbose & VERBOSE_ABORT_PROCESS) 
10619       printk(INFO_LEAD "SCB found on waiting list and "
10620           "aborted.\n", p->host_no, CTL_OF_SCB(scb));
10621     scbq_remove(&p->waiting_scbs, scb);
10622     scbq_remove(&aic_dev->delayed_scbs, scb);
10623     aic_dev->active_cmds++;
10624     p->activescbs++;
10625     scb->flags &= ~(SCB_WAITINGQ | SCB_ACTIVE);
10626     scb->flags |= SCB_ABORT | SCB_QUEUED_FOR_DONE;
10627     goto success;
10628   }
10629
10630 /*
10631  *  We just checked the waiting_q, now for the QINFIFO
10632  */
10633   if ( ((found = aic7xxx_search_qinfifo(p, cmd->device->id, cmd->device->channel,
10634                      cmd->device->lun, scb->hscb->tag, SCB_ABORT | SCB_QUEUED_FOR_DONE,
10635                      FALSE, NULL)) != 0) &&
10636                     (aic7xxx_verbose & VERBOSE_ABORT_PROCESS))
10637   {
10638     printk(INFO_LEAD "SCB found in QINFIFO and aborted.\n", p->host_no,
10639                     CTL_OF_SCB(scb));
10640     goto success;
10641   }
10642
10643 /*
10644  *  QINFIFO, waitingq, completeq done.  Next, check WAITING_SCB list in card
10645  */
10646
10647   saved_hscbptr = aic_inb(p, SCBPTR);
10648   if ((hscbptr = aic7xxx_find_scb(p, scb)) != SCB_LIST_NULL)
10649   {
10650     aic_outb(p, hscbptr, SCBPTR);
10651     scb_control = aic_inb(p, SCB_CONTROL);
10652     disconnected = scb_control & DISCONNECTED;
10653     /*
10654      * If the DISCONNECTED bit is not set in SCB_CONTROL, then we are
10655      * either currently active or on the waiting list.
10656      */
10657     if(!disconnected && aic_inb(p, LASTPHASE) == P_BUSFREE) {
10658       if (aic7xxx_verbose & VERBOSE_ABORT_PROCESS)
10659         printk(INFO_LEAD "SCB found on hardware waiting"
10660           " list and aborted.\n", p->host_no, CTL_OF_SCB(scb));
10661       /* If we are the only waiting command, stop the selection engine */
10662       if (aic_inb(p, WAITING_SCBH) == hscbptr && aic_inb(p, SCB_NEXT) ==
10663                         SCB_LIST_NULL)
10664       {
10665         aic_outb(p, aic_inb(p, SCSISEQ) & ~ENSELO, SCSISEQ);
10666         aic_outb(p, CLRSELTIMEO, CLRSINT1);
10667         aic_outb(p, SCB_LIST_NULL, WAITING_SCBH);
10668       }
10669       else
10670       {
10671         unsigned char prev, next;
10672         prev = SCB_LIST_NULL;
10673         next = aic_inb(p, WAITING_SCBH);
10674         while(next != SCB_LIST_NULL)
10675         {
10676           aic_outb(p, next, SCBPTR);
10677           if (next == hscbptr)
10678           {
10679             next = aic_inb(p, SCB_NEXT);
10680             if (prev != SCB_LIST_NULL)
10681             {
10682               aic_outb(p, prev, SCBPTR);
10683               aic_outb(p, next, SCB_NEXT);
10684             }
10685             else
10686               aic_outb(p, next, WAITING_SCBH);
10687             aic_outb(p, hscbptr, SCBPTR);
10688             next = SCB_LIST_NULL;
10689           }
10690           else
10691           {
10692             prev = next;
10693             next = aic_inb(p, SCB_NEXT);
10694           }
10695         }
10696       }
10697       aic_outb(p, SCB_LIST_NULL, SCB_TAG);
10698       aic_outb(p, 0, SCB_CONTROL);
10699       aic7xxx_add_curscb_to_free_list(p);
10700       scb->flags = SCB_ABORT | SCB_QUEUED_FOR_DONE;
10701       goto success;
10702     }
10703     else if (!disconnected)
10704     {
10705       /*
10706        * We are the currently active command
10707        */
10708       if((aic_inb(p, LASTPHASE) == P_MESGIN) ||
10709          (aic_inb(p, LASTPHASE) == P_MESGOUT))
10710       {
10711         /*
10712          * Message buffer busy, unable to abort
10713          */
10714         printk(INFO_LEAD "message buffer busy, unable to abort.\n",
10715                           p->host_no, CTL_OF_SCB(scb));
10716         unpause_sequencer(p, FALSE);
10717         return FAILED;
10718       }
10719       /* Fallthrough to below, set ATNO after we set SCB_CONTROL */
10720     } 
10721     aic_outb(p,  scb_control | MK_MESSAGE, SCB_CONTROL);
10722     if(!disconnected)
10723     {
10724       aic_outb(p, HOST_MSG, MSG_OUT);
10725       aic_outb(p, aic_inb(p, SCSISIGI) | ATNO, SCSISIGO);
10726     }
10727     aic_outb(p, saved_hscbptr, SCBPTR);
10728   } 
10729   else
10730   {
10731     /*
10732      * The scb isn't in the card at all and it is active and it isn't in
10733      * any of the queues, so it must be disconnected and paged out.  Fall
10734      * through to the code below.
10735      */
10736     disconnected = 1;
10737   }
10738         
10739   p->flags |= AHC_ABORT_PENDING;
10740   scb->flags |= SCB_QUEUED_ABORT | SCB_ABORT | SCB_RECOVERY_SCB;
10741   scb->hscb->control |= MK_MESSAGE;
10742   if(disconnected)
10743   {
10744     if (aic7xxx_verbose & VERBOSE_ABORT_PROCESS)
10745       printk(INFO_LEAD "SCB disconnected.  Queueing Abort"
10746         " SCB.\n", p->host_no, CTL_OF_SCB(scb));
10747     p->qinfifo[p->qinfifonext++] = scb->hscb->tag;
10748     if (p->features & AHC_QUEUE_REGS)
10749       aic_outb(p, p->qinfifonext, HNSCB_QOFF);
10750     else
10751       aic_outb(p, p->qinfifonext, KERNEL_QINPOS);
10752   }
10753   unpause_sequencer(p, FALSE);
10754   spin_unlock_irq(p->host->host_lock);
10755   msleep(1000/4);
10756   spin_lock_irq(p->host->host_lock);
10757   if (p->flags & AHC_ABORT_PENDING)
10758   {
10759     if (aic7xxx_verbose & VERBOSE_ABORT_RETURN)
10760       printk(INFO_LEAD "Abort never delivered, returning FAILED\n", p->host_no,
10761                     CTL_OF_CMD(cmd));
10762     p->flags &= ~AHC_ABORT_PENDING;
10763     return FAILED;
10764   }
10765   if (aic7xxx_verbose & VERBOSE_ABORT_RETURN)
10766     printk(INFO_LEAD "Abort successful.\n", p->host_no, CTL_OF_CMD(cmd));
10767   return SUCCESS;
10768
10769 success:
10770   if (aic7xxx_verbose & VERBOSE_ABORT_RETURN)
10771     printk(INFO_LEAD "Abort successful.\n", p->host_no, CTL_OF_CMD(cmd));
10772   aic7xxx_run_done_queue(p, TRUE);
10773   unpause_sequencer(p, FALSE);
10774   return SUCCESS;
10775 }
10776
10777 static int aic7xxx_abort(struct scsi_cmnd *cmd)
10778 {
10779         int rc;
10780
10781         spin_lock_irq(cmd->device->host->host_lock);
10782         rc = __aic7xxx_abort(cmd);
10783         spin_unlock_irq(cmd->device->host->host_lock);
10784
10785         return rc;
10786 }
10787
10788
10789 /*+F*************************************************************************
10790  * Function:
10791  *   aic7xxx_reset
10792  *
10793  * Description:
10794  *   Resetting the bus always succeeds - is has to, otherwise the
10795  *   kernel will panic! Try a surgical technique - sending a BUS
10796  *   DEVICE RESET message - on the offending target before pulling
10797  *   the SCSI bus reset line.
10798  *-F*************************************************************************/
10799 static int aic7xxx_reset(struct scsi_cmnd *cmd)
10800 {
10801   struct aic7xxx_scb *scb;
10802   struct aic7xxx_host *p;
10803   struct aic_dev_data *aic_dev;
10804
10805   p = (struct aic7xxx_host *) cmd->device->host->hostdata;
10806   spin_lock_irq(p->host->host_lock);
10807
10808   aic_dev = AIC_DEV(cmd);
10809   if(aic7xxx_position(cmd) < p->scb_data->numscbs)
10810   {
10811     scb = (p->scb_data->scb_array[aic7xxx_position(cmd)]);
10812     if (scb->cmd != cmd)
10813       scb = NULL;
10814   }
10815   else
10816   {
10817     scb = NULL;
10818   }
10819
10820   /*
10821    * I added a new config option to the driver: "panic_on_abort" that will
10822    * cause the driver to panic and the machine to stop on the first abort
10823    * or reset call into the driver.  At that point, it prints out a lot of
10824    * useful information for me which I can then use to try and debug the
10825    * problem.  Simply enable the boot time prompt in order to activate this
10826    * code.
10827    */
10828   if (aic7xxx_panic_on_abort)
10829     aic7xxx_panic_abort(p, cmd);
10830
10831   pause_sequencer(p);
10832
10833   while((aic_inb(p, INTSTAT) & INT_PEND) && !(p->flags & AHC_IN_ISR))
10834   {
10835     aic7xxx_isr(p);
10836     pause_sequencer(p);
10837   }
10838   aic7xxx_done_cmds_complete(p);
10839
10840   if(scb && (scb->cmd == NULL))
10841   {
10842     /*
10843      * We just completed the command when we ran the isr stuff, so we no
10844      * longer have it.
10845      */
10846     unpause_sequencer(p, FALSE);
10847     spin_unlock_irq(p->host->host_lock);
10848     return SUCCESS;
10849   }
10850     
10851 /*
10852  *  By this point, we want to already know what we are going to do and
10853  *  only have the following code implement our course of action.
10854  */
10855   aic7xxx_reset_channel(p, cmd->device->channel, TRUE);
10856   if (p->features & AHC_TWIN)
10857   {
10858     aic7xxx_reset_channel(p, cmd->device->channel ^ 0x01, TRUE);
10859     restart_sequencer(p);
10860   }
10861   aic_outb(p,  aic_inb(p, SIMODE1) & ~(ENREQINIT|ENBUSFREE), SIMODE1);
10862   aic7xxx_clear_intstat(p);
10863   p->flags &= ~AHC_HANDLING_REQINITS;
10864   p->msg_type = MSG_TYPE_NONE;
10865   p->msg_index = 0;
10866   p->msg_len = 0;
10867   aic7xxx_run_done_queue(p, TRUE);
10868   unpause_sequencer(p, FALSE);
10869   spin_unlock_irq(p->host->host_lock);
10870   ssleep(2);
10871   return SUCCESS;
10872 }
10873
10874 /*+F*************************************************************************
10875  * Function:
10876  *   aic7xxx_biosparam
10877  *
10878  * Description:
10879  *   Return the disk geometry for the given SCSI device.
10880  *
10881  * Note:
10882  *   This function is broken for today's really large drives and needs
10883  *   fixed.
10884  *-F*************************************************************************/
10885 static int
10886 aic7xxx_biosparam(struct scsi_device *sdev, struct block_device *bdev,
10887                 sector_t capacity, int geom[])
10888 {
10889   sector_t heads, sectors, cylinders;
10890   int ret;
10891   struct aic7xxx_host *p;
10892   unsigned char *buf;
10893
10894   p = (struct aic7xxx_host *) sdev->host->hostdata;
10895   buf = scsi_bios_ptable(bdev);
10896
10897   if ( buf )
10898   {
10899     ret = scsi_partsize(buf, capacity, &geom[2], &geom[0], &geom[1]);
10900     kfree(buf);
10901     if ( ret != -1 )
10902       return(ret);
10903   }
10904   
10905   heads = 64;
10906   sectors = 32;
10907   cylinders = capacity >> 11;
10908
10909   if ((p->flags & AHC_EXTEND_TRANS_A) && (cylinders > 1024))
10910   {
10911     heads = 255;
10912     sectors = 63;
10913     cylinders = capacity >> 14;
10914     if(capacity > (65535 * heads * sectors))
10915       cylinders = 65535;
10916     else
10917       cylinders = ((unsigned int)capacity) / (unsigned int)(heads * sectors);
10918   }
10919
10920   geom[0] = (int)heads;
10921   geom[1] = (int)sectors;
10922   geom[2] = (int)cylinders;
10923
10924   return (0);
10925 }
10926
10927 /*+F*************************************************************************
10928  * Function:
10929  *   aic7xxx_release
10930  *
10931  * Description:
10932  *   Free the passed in Scsi_Host memory structures prior to unloading the
10933  *   module.
10934  *-F*************************************************************************/
10935 static int
10936 aic7xxx_release(struct Scsi_Host *host)
10937 {
10938   struct aic7xxx_host *p = (struct aic7xxx_host *) host->hostdata;
10939   struct aic7xxx_host *next, *prev;
10940
10941   if(p->irq)
10942     free_irq(p->irq, p);
10943 #ifdef MMAPIO
10944   if(p->maddr)
10945   {
10946     iounmap(p->maddr);
10947   }
10948 #endif /* MMAPIO */
10949   if(!p->pdev)
10950     release_region(p->base, MAXREG - MINREG);
10951 #ifdef CONFIG_PCI
10952   else {
10953     pci_release_regions(p->pdev);
10954     pci_dev_put(p->pdev);
10955   }
10956 #endif
10957   prev = NULL;
10958   next = first_aic7xxx;
10959   while(next != NULL)
10960   {
10961     if(next == p)
10962     {
10963       if(prev == NULL)
10964         first_aic7xxx = next->next;
10965       else
10966         prev->next = next->next;
10967     }
10968     else
10969     {
10970       prev = next;
10971     }
10972     next = next->next;
10973   }
10974   aic7xxx_free(p);
10975   return(0);
10976 }
10977
10978 /*+F*************************************************************************
10979  * Function:
10980  *   aic7xxx_print_card
10981  *
10982  * Description:
10983  *   Print out all of the control registers on the card
10984  *
10985  *   NOTE: This function is not yet safe for use on the VLB and EISA
10986  *   controllers, so it isn't used on those controllers at all.
10987  *-F*************************************************************************/
10988 static void
10989 aic7xxx_print_card(struct aic7xxx_host *p)
10990 {
10991   int i, j, k, chip;
10992   static struct register_ranges {
10993     int num_ranges;
10994     int range_val[32];
10995   } cards_ds[] = {
10996     { 0, {0,} }, /* none */
10997     {10, {0x00, 0x05, 0x08, 0x11, 0x18, 0x19, 0x1f, 0x1f, 0x60, 0x60, /*7771*/
10998           0x62, 0x66, 0x80, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9b, 0x9f} },
10999     { 9, {0x00, 0x05, 0x08, 0x11, 0x18, 0x1f, 0x60, 0x60, 0x62, 0x66, /*7850*/
11000           0x80, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9f} },
11001     { 9, {0x00, 0x05, 0x08, 0x11, 0x18, 0x1f, 0x60, 0x60, 0x62, 0x66, /*7860*/
11002           0x80, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9f} },
11003     {10, {0x00, 0x05, 0x08, 0x11, 0x18, 0x19, 0x1c, 0x1f, 0x60, 0x60, /*7870*/
11004           0x62, 0x66, 0x80, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9f} },
11005     {10, {0x00, 0x05, 0x08, 0x11, 0x18, 0x1a, 0x1c, 0x1f, 0x60, 0x60, /*7880*/
11006           0x62, 0x66, 0x80, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9f} },
11007     {16, {0x00, 0x05, 0x08, 0x11, 0x18, 0x1f, 0x60, 0x60, 0x62, 0x66, /*7890*/
11008           0x84, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9a, 0x9f, 0x9f,
11009           0xe0, 0xf1, 0xf4, 0xf4, 0xf6, 0xf6, 0xf8, 0xf8, 0xfa, 0xfc,
11010           0xfe, 0xff} },
11011     {12, {0x00, 0x05, 0x08, 0x11, 0x18, 0x19, 0x1b, 0x1f, 0x60, 0x60, /*7895*/
11012           0x62, 0x66, 0x80, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9a,
11013           0x9f, 0x9f, 0xe0, 0xf1} },
11014     {16, {0x00, 0x05, 0x08, 0x11, 0x18, 0x1f, 0x60, 0x60, 0x62, 0x66, /*7896*/
11015           0x84, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9a, 0x9f, 0x9f,
11016           0xe0, 0xf1, 0xf4, 0xf4, 0xf6, 0xf6, 0xf8, 0xf8, 0xfa, 0xfc,
11017           0xfe, 0xff} },
11018     {12, {0x00, 0x05, 0x08, 0x11, 0x18, 0x1f, 0x60, 0x60, 0x62, 0x66, /*7892*/
11019           0x84, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9a, 0x9c, 0x9f,
11020           0xe0, 0xf1, 0xf4, 0xfc} },
11021     {12, {0x00, 0x05, 0x08, 0x11, 0x18, 0x1f, 0x60, 0x60, 0x62, 0x66, /*7899*/
11022           0x84, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9a, 0x9c, 0x9f,
11023           0xe0, 0xf1, 0xf4, 0xfc} },
11024   };
11025   chip = p->chip & AHC_CHIPID_MASK;
11026   printk("%s at ",
11027          board_names[p->board_name_index]);
11028   switch(p->chip & ~AHC_CHIPID_MASK)
11029   {
11030     case AHC_VL:
11031       printk("VLB Slot %d.\n", p->pci_device_fn);
11032       break;
11033     case AHC_EISA:
11034       printk("EISA Slot %d.\n", p->pci_device_fn);
11035       break;
11036     case AHC_PCI:
11037     default:
11038       printk("PCI %d/%d/%d.\n", p->pci_bus, PCI_SLOT(p->pci_device_fn),
11039              PCI_FUNC(p->pci_device_fn));
11040       break;
11041   }
11042
11043   /*
11044    * the registers on the card....
11045    */
11046   printk("Card Dump:\n");
11047   k = 0;
11048   for(i=0; i<cards_ds[chip].num_ranges; i++)
11049   {
11050     for(j  = cards_ds[chip].range_val[ i * 2 ];
11051         j <= cards_ds[chip].range_val[ i * 2 + 1 ] ;
11052         j++)
11053     {
11054       printk("%02x:%02x ", j, aic_inb(p, j));
11055       if(++k == 13)
11056       {
11057         printk("\n");
11058         k=0;
11059       }
11060     }
11061   }
11062   if(k != 0)
11063     printk("\n");
11064
11065   /*
11066    * If this was an Ultra2 controller, then we just hosed the card in terms
11067    * of the QUEUE REGS.  This function is only called at init time or by
11068    * the panic_abort function, so it's safe to assume a generic init time
11069    * setting here
11070    */
11071
11072   if(p->features & AHC_QUEUE_REGS)
11073   {
11074     aic_outb(p, 0, SDSCB_QOFF);
11075     aic_outb(p, 0, SNSCB_QOFF);
11076     aic_outb(p, 0, HNSCB_QOFF);
11077   }
11078
11079 }
11080
11081 /*+F*************************************************************************
11082  * Function:
11083  *   aic7xxx_print_scratch_ram
11084  *
11085  * Description:
11086  *   Print out the scratch RAM values on the card.
11087  *-F*************************************************************************/
11088 static void
11089 aic7xxx_print_scratch_ram(struct aic7xxx_host *p)
11090 {
11091   int i, k;
11092
11093   k = 0;
11094   printk("Scratch RAM:\n");
11095   for(i = SRAM_BASE; i < SEQCTL; i++)
11096   {
11097     printk("%02x:%02x ", i, aic_inb(p, i));
11098     if(++k == 13)
11099     {
11100       printk("\n");
11101       k=0;
11102     }
11103   }
11104   if (p->features & AHC_MORE_SRAM)
11105   {
11106     for(i = TARG_OFFSET; i < 0x80; i++)
11107     {
11108       printk("%02x:%02x ", i, aic_inb(p, i));
11109       if(++k == 13)
11110       {
11111         printk("\n");
11112         k=0;
11113       }
11114     }
11115   }
11116   printk("\n");
11117 }
11118
11119
11120 #include "aic7xxx_old/aic7xxx_proc.c"
11121
11122 MODULE_LICENSE("Dual BSD/GPL");
11123 MODULE_VERSION(AIC7XXX_H_VERSION);
11124
11125
11126 static struct scsi_host_template driver_template = {
11127         .proc_info              = aic7xxx_proc_info,
11128         .detect                 = aic7xxx_detect,
11129         .release                = aic7xxx_release,
11130         .info                   = aic7xxx_info, 
11131         .queuecommand           = aic7xxx_queue,
11132         .slave_alloc            = aic7xxx_slave_alloc,
11133         .slave_configure        = aic7xxx_slave_configure,
11134         .slave_destroy          = aic7xxx_slave_destroy,
11135         .bios_param             = aic7xxx_biosparam,
11136         .eh_abort_handler       = aic7xxx_abort,
11137         .eh_device_reset_handler        = aic7xxx_bus_device_reset,
11138         .eh_host_reset_handler  = aic7xxx_reset,
11139         .can_queue              = 255,
11140         .this_id                = -1,
11141         .max_sectors            = 2048,
11142         .cmd_per_lun            = 3,
11143         .use_clustering         = ENABLE_CLUSTERING,
11144 };
11145
11146 #include "scsi_module.c"
11147
11148 /*
11149  * Overrides for Emacs so that we almost follow Linus's tabbing style.
11150  * Emacs will notice this stuff at the end of the file and automatically
11151  * adjust the settings for this buffer only.  This must remain at the end
11152  * of the file.
11153  * ---------------------------------------------------------------------------
11154  * Local variables:
11155  * c-indent-level: 2
11156  * c-brace-imaginary-offset: 0
11157  * c-brace-offset: -2
11158  * c-argdecl-indent: 2
11159  * c-label-offset: -2
11160  * c-continued-statement-offset: 2
11161  * c-continued-brace-offset: 0
11162  * indent-tabs-mode: nil
11163  * tab-width: 8
11164  * End:
11165  */