7d1fec620948bd11f1c90c043fbb88b450a5b6e1
[sfrench/cifs-2.6.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/sched.h>
233 #include <linux/pci.h>
234 #include <linux/proc_fs.h>
235 #include <linux/blkdev.h>
236 #include <linux/init.h>
237 #include <linux/spinlock.h>
238 #include <linux/smp.h>
239 #include <linux/interrupt.h>
240 #include "scsi.h"
241 #include <scsi/scsi_host.h>
242 #include "aic7xxx_old/aic7xxx.h"
243
244 #include "aic7xxx_old/sequencer.h"
245 #include "aic7xxx_old/scsi_message.h"
246 #include "aic7xxx_old/aic7xxx_reg.h"
247 #include <scsi/scsicam.h>
248
249 #include <linux/stat.h>
250 #include <linux/slab.h>        /* for kmalloc() */
251
252 #define AIC7XXX_C_VERSION  "5.2.6"
253
254 #define ALL_TARGETS -1
255 #define ALL_CHANNELS -1
256 #define ALL_LUNS -1
257 #define MAX_TARGETS  16
258 #define MAX_LUNS     8
259 #ifndef TRUE
260 #  define TRUE 1
261 #endif
262 #ifndef FALSE
263 #  define FALSE 0
264 #endif
265
266 #if defined(__powerpc__) || defined(__i386__) || defined(__x86_64__)
267 #  define MMAPIO
268 #endif
269
270 /*
271  * You can try raising me for better performance or lowering me if you have
272  * flaky devices that go off the scsi bus when hit with too many tagged
273  * commands (like some IBM SCSI-3 LVD drives).
274  */
275 #define AIC7XXX_CMDS_PER_DEVICE 32
276
277 typedef struct
278 {
279   unsigned char tag_commands[16];   /* Allow for wide/twin adapters. */
280 } adapter_tag_info_t;
281
282 /*
283  * Make a define that will tell the driver not to the default tag depth
284  * everywhere.
285  */
286 #define DEFAULT_TAG_COMMANDS {0, 0, 0, 0, 0, 0, 0, 0,\
287                               0, 0, 0, 0, 0, 0, 0, 0}
288
289 /*
290  * Modify this as you see fit for your system.  By setting tag_commands
291  * to 0, the driver will use it's own algorithm for determining the
292  * number of commands to use (see above).  When 255, the driver will
293  * not enable tagged queueing for that particular device.  When positive
294  * (> 0) and (< 255) the values in the array are used for the queue_depth.
295  * Note that the maximum value for an entry is 254, but you're insane if
296  * you try to use that many commands on one device.
297  *
298  * In this example, the first line will disable tagged queueing for all
299  * the devices on the first probed aic7xxx adapter.
300  *
301  * The second line enables tagged queueing with 4 commands/LUN for IDs
302  * (1, 2-11, 13-15), disables tagged queueing for ID 12, and tells the
303  * driver to use its own algorithm for ID 1.
304  *
305  * The third line is the same as the first line.
306  *
307  * The fourth line disables tagged queueing for devices 0 and 3.  It
308  * enables tagged queueing for the other IDs, with 16 commands/LUN
309  * for IDs 1 and 4, 127 commands/LUN for ID 8, and 4 commands/LUN for
310  * IDs 2, 5-7, and 9-15.
311  */
312
313 /*
314  * NOTE: The below structure is for reference only, the actual structure
315  *       to modify in order to change things is found after this fake one.
316  *
317 adapter_tag_info_t aic7xxx_tag_info[] =
318 {
319   {DEFAULT_TAG_COMMANDS},
320   {{4, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 255, 4, 4, 4}},
321   {DEFAULT_TAG_COMMANDS},
322   {{255, 16, 4, 255, 16, 4, 4, 4, 127, 4, 4, 4, 4, 4, 4, 4}}
323 };
324 */
325
326 static adapter_tag_info_t aic7xxx_tag_info[] =
327 {
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   {DEFAULT_TAG_COMMANDS}
344 };
345
346
347 /*
348  * Define an array of board names that can be indexed by aha_type.
349  * Don't forget to change this when changing the types!
350  */
351 static const char *board_names[] = {
352   "AIC-7xxx Unknown",                                   /* AIC_NONE */
353   "Adaptec AIC-7810 Hardware RAID Controller",          /* AIC_7810 */
354   "Adaptec AIC-7770 SCSI host adapter",                 /* AIC_7770 */
355   "Adaptec AHA-274X SCSI host adapter",                 /* AIC_7771 */
356   "Adaptec AHA-284X SCSI host adapter",                 /* AIC_284x */
357   "Adaptec AIC-7850 SCSI host adapter",                 /* AIC_7850 */
358   "Adaptec AIC-7855 SCSI host adapter",                 /* AIC_7855 */
359   "Adaptec AIC-7860 Ultra SCSI host adapter",           /* AIC_7860 */
360   "Adaptec AHA-2940A Ultra SCSI host adapter",          /* AIC_7861 */
361   "Adaptec AIC-7870 SCSI host adapter",                 /* AIC_7870 */
362   "Adaptec AHA-294X SCSI host adapter",                 /* AIC_7871 */
363   "Adaptec AHA-394X SCSI host adapter",                 /* AIC_7872 */
364   "Adaptec AHA-398X SCSI host adapter",                 /* AIC_7873 */
365   "Adaptec AHA-2944 SCSI host adapter",                 /* AIC_7874 */
366   "Adaptec AIC-7880 Ultra SCSI host adapter",           /* AIC_7880 */
367   "Adaptec AHA-294X Ultra SCSI host adapter",           /* AIC_7881 */
368   "Adaptec AHA-394X Ultra SCSI host adapter",           /* AIC_7882 */
369   "Adaptec AHA-398X Ultra SCSI host adapter",           /* AIC_7883 */
370   "Adaptec AHA-2944 Ultra SCSI host adapter",           /* AIC_7884 */
371   "Adaptec AHA-2940UW Pro Ultra SCSI host adapter",     /* AIC_7887 */
372   "Adaptec AIC-7895 Ultra SCSI host adapter",           /* AIC_7895 */
373   "Adaptec AIC-7890/1 Ultra2 SCSI host adapter",        /* AIC_7890 */
374   "Adaptec AHA-293X Ultra2 SCSI host adapter",          /* AIC_7890 */
375   "Adaptec AHA-294X Ultra2 SCSI host adapter",          /* AIC_7890 */
376   "Adaptec AIC-7896/7 Ultra2 SCSI host adapter",        /* AIC_7896 */
377   "Adaptec AHA-394X Ultra2 SCSI host adapter",          /* AIC_7897 */
378   "Adaptec AHA-395X Ultra2 SCSI host adapter",          /* AIC_7897 */
379   "Adaptec PCMCIA SCSI controller",                     /* card bus stuff */
380   "Adaptec AIC-7892 Ultra 160/m SCSI host adapter",     /* AIC_7892 */
381   "Adaptec AIC-7899 Ultra 160/m SCSI host adapter",     /* AIC_7899 */
382 };
383
384 /*
385  * There should be a specific return value for this in scsi.h, but
386  * it seems that most drivers ignore it.
387  */
388 #define DID_UNDERFLOW   DID_ERROR
389
390 /*
391  *  What we want to do is have the higher level scsi driver requeue
392  *  the command to us. There is no specific driver status for this
393  *  condition, but the higher level scsi driver will requeue the
394  *  command on a DID_BUS_BUSY error.
395  *
396  *  Upon further inspection and testing, it seems that DID_BUS_BUSY
397  *  will *always* retry the command.  We can get into an infinite loop
398  *  if this happens when we really want some sort of counter that
399  *  will automatically abort/reset the command after so many retries.
400  *  Using DID_ERROR will do just that.  (Made by a suggestion by
401  *  Doug Ledford 8/1/96)
402  */
403 #define DID_RETRY_COMMAND DID_ERROR
404
405 #define HSCSIID        0x07
406 #define SCSI_RESET     0x040
407
408 /*
409  * EISA/VL-bus stuff
410  */
411 #define MINSLOT                1
412 #define MAXSLOT                15
413 #define SLOTBASE(x)        ((x) << 12)
414 #define BASE_TO_SLOT(x) ((x) >> 12)
415
416 /*
417  * Standard EISA Host ID regs  (Offset from slot base)
418  */
419 #define AHC_HID0              0x80   /* 0,1: msb of ID2, 2-7: ID1      */
420 #define AHC_HID1              0x81   /* 0-4: ID3, 5-7: LSB ID2         */
421 #define AHC_HID2              0x82   /* product                        */
422 #define AHC_HID3              0x83   /* firmware revision              */
423
424 /*
425  * AIC-7770 I/O range to reserve for a card
426  */
427 #define MINREG                0xC00
428 #define MAXREG                0xCFF
429
430 #define INTDEF                0x5C      /* Interrupt Definition Register */
431
432 /*
433  * AIC-78X0 PCI registers
434  */
435 #define        CLASS_PROGIF_REVID        0x08
436 #define                DEVREVID        0x000000FFul
437 #define                PROGINFC        0x0000FF00ul
438 #define                SUBCLASS        0x00FF0000ul
439 #define                BASECLASS        0xFF000000ul
440
441 #define        CSIZE_LATTIME                0x0C
442 #define                CACHESIZE        0x0000003Ful        /* only 5 bits */
443 #define                LATTIME                0x0000FF00ul
444
445 #define        DEVCONFIG                0x40
446 #define                SCBSIZE32        0x00010000ul        /* aic789X only */
447 #define                MPORTMODE        0x00000400ul        /* aic7870 only */
448 #define                RAMPSM           0x00000200ul        /* aic7870 only */
449 #define                RAMPSM_ULTRA2    0x00000004
450 #define                VOLSENSE         0x00000100ul
451 #define                SCBRAMSEL        0x00000080ul
452 #define                SCBRAMSEL_ULTRA2 0x00000008
453 #define                MRDCEN           0x00000040ul
454 #define                EXTSCBTIME       0x00000020ul        /* aic7870 only */
455 #define                EXTSCBPEN        0x00000010ul        /* aic7870 only */
456 #define                BERREN           0x00000008ul
457 #define                DACEN            0x00000004ul
458 #define                STPWLEVEL        0x00000002ul
459 #define                DIFACTNEGEN      0x00000001ul        /* aic7870 only */
460
461 #define        SCAMCTL                  0x1a                /* Ultra2 only  */
462 #define        CCSCBBADDR               0xf0                /* aic7895/6/7  */
463
464 /*
465  * Define the different types of SEEPROMs on aic7xxx adapters
466  * and make it also represent the address size used in accessing
467  * its registers.  The 93C46 chips have 1024 bits organized into
468  * 64 16-bit words, while the 93C56 chips have 2048 bits organized
469  * into 128 16-bit words.  The C46 chips use 6 bits to address
470  * each word, while the C56 and C66 (4096 bits) use 8 bits to
471  * address each word.
472  */
473 typedef enum {C46 = 6, C56_66 = 8} seeprom_chip_type;
474
475 /*
476  *
477  * Define the format of the SEEPROM registers (16 bits).
478  *
479  */
480 struct seeprom_config {
481
482 /*
483  * SCSI ID Configuration Flags
484  */
485 #define CFXFER                0x0007      /* synchronous transfer rate */
486 #define CFSYNCH               0x0008      /* enable synchronous transfer */
487 #define CFDISC                0x0010      /* enable disconnection */
488 #define CFWIDEB               0x0020      /* wide bus device (wide card) */
489 #define CFSYNCHISULTRA        0x0040      /* CFSYNC is an ultra offset */
490 #define CFNEWULTRAFORMAT      0x0080      /* Use the Ultra2 SEEPROM format */
491 #define CFSTART               0x0100      /* send start unit SCSI command */
492 #define CFINCBIOS             0x0200      /* include in BIOS scan */
493 #define CFRNFOUND             0x0400      /* report even if not found */
494 #define CFMULTILUN            0x0800      /* probe mult luns in BIOS scan */
495 #define CFWBCACHEYES          0x4000      /* Enable W-Behind Cache on drive */
496 #define CFWBCACHENC           0xc000      /* Don't change W-Behind Cache */
497 /* UNUSED                0x3000 */
498   unsigned short device_flags[16];        /* words 0-15 */
499
500 /*
501  * BIOS Control Bits
502  */
503 #define CFSUPREM        0x0001  /* support all removable drives */
504 #define CFSUPREMB       0x0002  /* support removable drives for boot only */
505 #define CFBIOSEN        0x0004  /* BIOS enabled */
506 /* UNUSED                0x0008 */
507 #define CFSM2DRV        0x0010  /* support more than two drives */
508 #define CF284XEXTEND    0x0020  /* extended translation (284x cards) */
509 /* UNUSED                0x0040 */
510 #define CFEXTEND        0x0080  /* extended translation enabled */
511 /* UNUSED                0xFF00 */
512   unsigned short bios_control;  /* word 16 */
513
514 /*
515  * Host Adapter Control Bits
516  */
517 #define CFAUTOTERM      0x0001  /* Perform Auto termination */
518 #define CFULTRAEN       0x0002  /* Ultra SCSI speed enable (Ultra cards) */
519 #define CF284XSELTO     0x0003  /* Selection timeout (284x cards) */
520 #define CF284XFIFO      0x000C  /* FIFO Threshold (284x cards) */
521 #define CFSTERM         0x0004  /* SCSI low byte termination */
522 #define CFWSTERM        0x0008  /* SCSI high byte termination (wide card) */
523 #define CFSPARITY       0x0010  /* SCSI parity */
524 #define CF284XSTERM     0x0020  /* SCSI low byte termination (284x cards) */
525 #define CFRESETB        0x0040  /* reset SCSI bus at boot */
526 #define CFBPRIMARY      0x0100  /* Channel B primary on 7895 chipsets */
527 #define CFSEAUTOTERM    0x0400  /* aic7890 Perform SE Auto Term */
528 #define CFLVDSTERM      0x0800  /* aic7890 LVD Termination */
529 /* UNUSED                0xF280 */
530   unsigned short adapter_control;        /* word 17 */
531
532 /*
533  * Bus Release, Host Adapter ID
534  */
535 #define CFSCSIID        0x000F                /* host adapter SCSI ID */
536 /* UNUSED                0x00F0 */
537 #define CFBRTIME        0xFF00                /* bus release time */
538   unsigned short brtime_id;                /* word 18 */
539
540 /*
541  * Maximum targets
542  */
543 #define CFMAXTARG        0x00FF        /* maximum targets */
544 /* UNUSED                0xFF00 */
545   unsigned short max_targets;                /* word 19 */
546
547   unsigned short res_1[11];                /* words 20-30 */
548   unsigned short checksum;                /* word 31 */
549 };
550
551 #define SELBUS_MASK                0x0a
552 #define         SELNARROW        0x00
553 #define         SELBUSB                0x08
554 #define SINGLE_BUS                0x00
555
556 #define SCB_TARGET(scb)         \
557        (((scb)->hscb->target_channel_lun & TID) >> 4)
558 #define SCB_LUN(scb)            \
559        ((scb)->hscb->target_channel_lun & LID)
560 #define SCB_IS_SCSIBUS_B(scb)   \
561        (((scb)->hscb->target_channel_lun & SELBUSB) != 0)
562
563 /*
564  * If an error occurs during a data transfer phase, run the command
565  * to completion - it's easier that way - making a note of the error
566  * condition in this location. This then will modify a DID_OK status
567  * into an appropriate error for the higher-level SCSI code.
568  */
569 #define aic7xxx_error(cmd)        ((cmd)->SCp.Status)
570
571 /*
572  * Keep track of the targets returned status.
573  */
574 #define aic7xxx_status(cmd)        ((cmd)->SCp.sent_command)
575
576 /*
577  * The position of the SCSI commands scb within the scb array.
578  */
579 #define aic7xxx_position(cmd)        ((cmd)->SCp.have_data_in)
580
581 /*
582  * The stored DMA mapping for single-buffer data transfers.
583  */
584 #define aic7xxx_mapping(cmd)         ((cmd)->SCp.phase)
585
586 /*
587  * Get out private data area from a scsi cmd pointer
588  */
589 #define AIC_DEV(cmd)    ((struct aic_dev_data *)(cmd)->device->hostdata)
590
591 /*
592  * So we can keep track of our host structs
593  */
594 static struct aic7xxx_host *first_aic7xxx = NULL;
595
596 /*
597  * As of Linux 2.1, the mid-level SCSI code uses virtual addresses
598  * in the scatter-gather lists.  We need to convert the virtual
599  * addresses to physical addresses.
600  */
601 struct hw_scatterlist {
602   unsigned int address;
603   unsigned int length;
604 };
605
606 /*
607  * Maximum number of SG segments these cards can support.
608  */
609 #define        AIC7XXX_MAX_SG 128
610
611 /*
612  * The maximum number of SCBs we could have for ANY type
613  * of card. DON'T FORGET TO CHANGE THE SCB MASK IN THE
614  * SEQUENCER CODE IF THIS IS MODIFIED!
615  */
616 #define AIC7XXX_MAXSCB        255
617
618
619 struct aic7xxx_hwscb {
620 /* ------------    Begin hardware supported fields    ---------------- */
621 /* 0*/  unsigned char control;
622 /* 1*/  unsigned char target_channel_lun;       /* 4/1/3 bits */
623 /* 2*/  unsigned char target_status;
624 /* 3*/  unsigned char SG_segment_count;
625 /* 4*/  unsigned int  SG_list_pointer;
626 /* 8*/  unsigned char residual_SG_segment_count;
627 /* 9*/  unsigned char residual_data_count[3];
628 /*12*/  unsigned int  data_pointer;
629 /*16*/  unsigned int  data_count;
630 /*20*/  unsigned int  SCSI_cmd_pointer;
631 /*24*/  unsigned char SCSI_cmd_length;
632 /*25*/  unsigned char tag;          /* Index into our kernel SCB array.
633                                      * Also used as the tag for tagged I/O
634                                      */
635 #define SCB_PIO_TRANSFER_SIZE  26   /* amount we need to upload/download
636                                      * via PIO to initialize a transaction.
637                                      */
638 /*26*/  unsigned char next;         /* Used to thread SCBs awaiting selection
639                                      * or disconnected down in the sequencer.
640                                      */
641 /*27*/  unsigned char prev;
642 /*28*/  unsigned int pad;           /*
643                                      * Unused by the kernel, but we require
644                                      * the padding so that the array of
645                                      * hardware SCBs is aligned on 32 byte
646                                      * boundaries so the sequencer can index
647                                      */
648 };
649
650 typedef enum {
651         SCB_FREE                = 0x0000,
652         SCB_DTR_SCB             = 0x0001,
653         SCB_WAITINGQ            = 0x0002,
654         SCB_ACTIVE              = 0x0004,
655         SCB_SENSE               = 0x0008,
656         SCB_ABORT               = 0x0010,
657         SCB_DEVICE_RESET        = 0x0020,
658         SCB_RESET               = 0x0040,
659         SCB_RECOVERY_SCB        = 0x0080,
660         SCB_MSGOUT_PPR          = 0x0100,
661         SCB_MSGOUT_SENT         = 0x0200,
662         SCB_MSGOUT_SDTR         = 0x0400,
663         SCB_MSGOUT_WDTR         = 0x0800,
664         SCB_MSGOUT_BITS         = SCB_MSGOUT_PPR |
665                                   SCB_MSGOUT_SENT | 
666                                   SCB_MSGOUT_SDTR |
667                                   SCB_MSGOUT_WDTR,
668         SCB_QUEUED_ABORT        = 0x1000,
669         SCB_QUEUED_FOR_DONE     = 0x2000,
670         SCB_WAS_BUSY            = 0x4000,
671         SCB_QUEUE_FULL          = 0x8000
672 } scb_flag_type;
673
674 typedef enum {
675         AHC_FNONE                 = 0x00000000,
676         AHC_PAGESCBS              = 0x00000001,
677         AHC_CHANNEL_B_PRIMARY     = 0x00000002,
678         AHC_USEDEFAULTS           = 0x00000004,
679         AHC_INDIRECT_PAGING       = 0x00000008,
680         AHC_CHNLB                 = 0x00000020,
681         AHC_CHNLC                 = 0x00000040,
682         AHC_EXTEND_TRANS_A        = 0x00000100,
683         AHC_EXTEND_TRANS_B        = 0x00000200,
684         AHC_TERM_ENB_A            = 0x00000400,
685         AHC_TERM_ENB_SE_LOW       = 0x00000400,
686         AHC_TERM_ENB_B            = 0x00000800,
687         AHC_TERM_ENB_SE_HIGH      = 0x00000800,
688         AHC_HANDLING_REQINITS     = 0x00001000,
689         AHC_TARGETMODE            = 0x00002000,
690         AHC_NEWEEPROM_FMT         = 0x00004000,
691  /*
692   *  Here ends the FreeBSD defined flags and here begins the linux defined
693   *  flags.  NOTE: I did not preserve the old flag name during this change
694   *  specifically to force me to evaluate what flags were being used properly
695   *  and what flags weren't.  This way, I could clean up the flag usage on
696   *  a use by use basis.  Doug Ledford
697   */
698         AHC_MOTHERBOARD           = 0x00020000,
699         AHC_NO_STPWEN             = 0x00040000,
700         AHC_RESET_DELAY           = 0x00080000,
701         AHC_A_SCANNED             = 0x00100000,
702         AHC_B_SCANNED             = 0x00200000,
703         AHC_MULTI_CHANNEL         = 0x00400000,
704         AHC_BIOS_ENABLED          = 0x00800000,
705         AHC_SEEPROM_FOUND         = 0x01000000,
706         AHC_TERM_ENB_LVD          = 0x02000000,
707         AHC_ABORT_PENDING         = 0x04000000,
708         AHC_RESET_PENDING         = 0x08000000,
709 #define AHC_IN_ISR_BIT              28
710         AHC_IN_ISR                = 0x10000000,
711         AHC_IN_ABORT              = 0x20000000,
712         AHC_IN_RESET              = 0x40000000,
713         AHC_EXTERNAL_SRAM         = 0x80000000
714 } ahc_flag_type;
715
716 typedef enum {
717   AHC_NONE             = 0x0000,
718   AHC_CHIPID_MASK      = 0x00ff,
719   AHC_AIC7770          = 0x0001,
720   AHC_AIC7850          = 0x0002,
721   AHC_AIC7860          = 0x0003,
722   AHC_AIC7870          = 0x0004,
723   AHC_AIC7880          = 0x0005,
724   AHC_AIC7890          = 0x0006,
725   AHC_AIC7895          = 0x0007,
726   AHC_AIC7896          = 0x0008,
727   AHC_AIC7892          = 0x0009,
728   AHC_AIC7899          = 0x000a,
729   AHC_VL               = 0x0100,
730   AHC_EISA             = 0x0200,
731   AHC_PCI              = 0x0400,
732 } ahc_chip;
733
734 typedef enum {
735   AHC_FENONE           = 0x0000,
736   AHC_ULTRA            = 0x0001,
737   AHC_ULTRA2           = 0x0002,
738   AHC_WIDE             = 0x0004,
739   AHC_TWIN             = 0x0008,
740   AHC_MORE_SRAM        = 0x0010,
741   AHC_CMD_CHAN         = 0x0020,
742   AHC_QUEUE_REGS       = 0x0040,
743   AHC_SG_PRELOAD       = 0x0080,
744   AHC_SPIOCAP          = 0x0100,
745   AHC_ULTRA3           = 0x0200,
746   AHC_NEW_AUTOTERM     = 0x0400,
747   AHC_AIC7770_FE       = AHC_FENONE,
748   AHC_AIC7850_FE       = AHC_SPIOCAP,
749   AHC_AIC7860_FE       = AHC_ULTRA|AHC_SPIOCAP,
750   AHC_AIC7870_FE       = AHC_FENONE,
751   AHC_AIC7880_FE       = AHC_ULTRA,
752   AHC_AIC7890_FE       = AHC_MORE_SRAM|AHC_CMD_CHAN|AHC_ULTRA2|
753                          AHC_QUEUE_REGS|AHC_SG_PRELOAD|AHC_NEW_AUTOTERM,
754   AHC_AIC7895_FE       = AHC_MORE_SRAM|AHC_CMD_CHAN|AHC_ULTRA,
755   AHC_AIC7896_FE       = AHC_AIC7890_FE,
756   AHC_AIC7892_FE       = AHC_AIC7890_FE|AHC_ULTRA3,
757   AHC_AIC7899_FE       = AHC_AIC7890_FE|AHC_ULTRA3,
758 } ahc_feature;
759
760 #define SCB_DMA_ADDR(scb, addr) ((unsigned long)(addr) + (scb)->scb_dma->dma_offset)
761
762 struct aic7xxx_scb_dma {
763         unsigned long          dma_offset;    /* Correction you have to add
764                                                * to virtual address to get
765                                                * dma handle in this region */
766         dma_addr_t             dma_address;   /* DMA handle of the start,
767                                                * for unmap */
768         unsigned int           dma_len;       /* DMA length */
769 };
770
771 typedef enum {
772   AHC_BUG_NONE            = 0x0000,
773   AHC_BUG_TMODE_WIDEODD   = 0x0001,
774   AHC_BUG_AUTOFLUSH       = 0x0002,
775   AHC_BUG_CACHETHEN       = 0x0004,
776   AHC_BUG_CACHETHEN_DIS   = 0x0008,
777   AHC_BUG_PCI_2_1_RETRY   = 0x0010,
778   AHC_BUG_PCI_MWI         = 0x0020,
779   AHC_BUG_SCBCHAN_UPLOAD  = 0x0040,
780 } ahc_bugs;
781
782 struct aic7xxx_scb {
783         struct aic7xxx_hwscb    *hscb;          /* corresponding hardware scb */
784         struct scsi_cmnd        *cmd;           /* scsi_cmnd for this scb */
785         struct aic7xxx_scb      *q_next;        /* next scb in queue */
786         volatile scb_flag_type  flags;          /* current state of scb */
787         struct hw_scatterlist   *sg_list;       /* SG list in adapter format */
788         unsigned char           tag_action;
789         unsigned char           sg_count;
790         unsigned char           *sense_cmd;     /*
791                                                  * Allocate 6 characters for
792                                                  * sense command.
793                                                  */
794         unsigned char           *cmnd;
795         unsigned int            sg_length;      /*
796                                                  * We init this during
797                                                  * buildscb so we don't have
798                                                  * to calculate anything during
799                                                  * underflow/overflow/stat code
800                                                  */
801         void                    *kmalloc_ptr;
802         struct aic7xxx_scb_dma  *scb_dma;
803 };
804
805 /*
806  * Define a linked list of SCBs.
807  */
808 typedef struct {
809   struct aic7xxx_scb *head;
810   struct aic7xxx_scb *tail;
811 } scb_queue_type;
812
813 static struct {
814   unsigned char errno;
815   const char *errmesg;
816 } hard_error[] = {
817   { ILLHADDR,  "Illegal Host Access" },
818   { ILLSADDR,  "Illegal Sequencer Address referenced" },
819   { ILLOPCODE, "Illegal Opcode in sequencer program" },
820   { SQPARERR,  "Sequencer Ram Parity Error" },
821   { DPARERR,   "Data-Path Ram Parity Error" },
822   { MPARERR,   "Scratch Ram/SCB Array Ram Parity Error" },
823   { PCIERRSTAT,"PCI Error detected" },
824   { CIOPARERR, "CIOBUS Parity Error" }
825 };
826
827 static unsigned char
828 generic_sense[] = { REQUEST_SENSE, 0, 0, 0, 255, 0 };
829
830 typedef struct {
831   scb_queue_type free_scbs;        /*
832                                     * SCBs assigned to free slot on
833                                     * card (no paging required)
834                                     */
835   struct aic7xxx_scb   *scb_array[AIC7XXX_MAXSCB];
836   struct aic7xxx_hwscb *hscbs;
837   unsigned char  numscbs;          /* current number of scbs */
838   unsigned char  maxhscbs;         /* hardware scbs */
839   unsigned char  maxscbs;          /* max scbs including pageable scbs */
840   dma_addr_t     hscbs_dma;        /* DMA handle to hscbs */
841   unsigned int   hscbs_dma_len;    /* length of the above DMA area */
842   void          *hscb_kmalloc_ptr;
843 } scb_data_type;
844
845 struct target_cmd {
846   unsigned char mesg_bytes[4];
847   unsigned char command[28];
848 };
849
850 #define AHC_TRANS_CUR    0x0001
851 #define AHC_TRANS_ACTIVE 0x0002
852 #define AHC_TRANS_GOAL   0x0004
853 #define AHC_TRANS_USER   0x0008
854 #define AHC_TRANS_QUITE  0x0010
855 typedef struct {
856   unsigned char width;
857   unsigned char period;
858   unsigned char offset;
859   unsigned char options;
860 } transinfo_type;
861
862 struct aic_dev_data {
863   volatile scb_queue_type  delayed_scbs;
864   volatile unsigned short  temp_q_depth;
865   unsigned short           max_q_depth;
866   volatile unsigned char   active_cmds;
867   /*
868    * Statistics Kept:
869    *
870    * Total Xfers (count for each command that has a data xfer),
871    * broken down by reads && writes.
872    *
873    * Further sorted into a few bins for keeping tabs on how many commands
874    * we get of various sizes.
875    *
876    */
877   long w_total;                          /* total writes */
878   long r_total;                          /* total reads */
879   long barrier_total;                    /* total num of REQ_BARRIER commands */
880   long ordered_total;                    /* How many REQ_BARRIER commands we
881                                             used ordered tags to satisfy */
882   long w_bins[6];                       /* binned write */
883   long r_bins[6];                       /* binned reads */
884   transinfo_type        cur;
885   transinfo_type        goal;
886 #define  BUS_DEVICE_RESET_PENDING       0x01
887 #define  DEVICE_RESET_DELAY             0x02
888 #define  DEVICE_PRINT_DTR               0x04
889 #define  DEVICE_WAS_BUSY                0x08
890 #define  DEVICE_DTR_SCANNED             0x10
891 #define  DEVICE_SCSI_3                  0x20
892   volatile unsigned char   flags;
893   unsigned needppr:1;
894   unsigned needppr_copy:1;
895   unsigned needsdtr:1;
896   unsigned needsdtr_copy:1;
897   unsigned needwdtr:1;
898   unsigned needwdtr_copy:1;
899   unsigned dtr_pending:1;
900   struct scsi_device *SDptr;
901   struct list_head list;
902 };
903
904 /*
905  * Define a structure used for each host adapter.  Note, in order to avoid
906  * problems with architectures I can't test on (because I don't have one,
907  * such as the Alpha based systems) which happen to give faults for
908  * non-aligned memory accesses, care was taken to align this structure
909  * in a way that gauranteed all accesses larger than 8 bits were aligned
910  * on the appropriate boundary.  It's also organized to try and be more
911  * cache line efficient.  Be careful when changing this lest you might hurt
912  * overall performance and bring down the wrath of the masses.
913  */
914 struct aic7xxx_host {
915   /*
916    *  This is the first 64 bytes in the host struct
917    */
918
919   /*
920    * We are grouping things here....first, items that get either read or
921    * written with nearly every interrupt
922    */
923         volatile long   flags;
924         ahc_feature     features;       /* chip features */
925         unsigned long   base;           /* card base address */
926         volatile unsigned char  __iomem *maddr; /* memory mapped address */
927         unsigned long   isr_count;      /* Interrupt count */
928         unsigned long   spurious_int;
929         scb_data_type   *scb_data;
930         struct aic7xxx_cmd_queue {
931                 struct scsi_cmnd *head;
932                 struct scsi_cmnd *tail;
933         } completeq;
934
935         /*
936         * Things read/written on nearly every entry into aic7xxx_queue()
937         */
938         volatile scb_queue_type waiting_scbs;
939         unsigned char   unpause;        /* unpause value for HCNTRL */
940         unsigned char   pause;          /* pause value for HCNTRL */
941         volatile unsigned char  qoutfifonext;
942         volatile unsigned char  activescbs;     /* active scbs */
943         volatile unsigned char  max_activescbs;
944         volatile unsigned char  qinfifonext;
945         volatile unsigned char  *untagged_scbs;
946         volatile unsigned char  *qoutfifo;
947         volatile unsigned char  *qinfifo;
948
949         unsigned char   dev_last_queue_full[MAX_TARGETS];
950         unsigned char   dev_last_queue_full_count[MAX_TARGETS];
951         unsigned short  ultraenb; /* Gets downloaded to card as a bitmap */
952         unsigned short  discenable; /* Gets downloaded to card as a bitmap */
953         transinfo_type  user[MAX_TARGETS];
954
955         unsigned char   msg_buf[13];    /* The message for the target */
956         unsigned char   msg_type;
957 #define MSG_TYPE_NONE              0x00
958 #define MSG_TYPE_INITIATOR_MSGOUT  0x01
959 #define MSG_TYPE_INITIATOR_MSGIN   0x02
960         unsigned char   msg_len;        /* Length of message */
961         unsigned char   msg_index;      /* Index into msg_buf array */
962
963
964         /*
965          * We put the less frequently used host structure items
966          * after the more frequently used items to try and ease
967          * the burden on the cache subsystem.
968          * These entries are not *commonly* accessed, whereas
969          * the preceding entries are accessed very often.
970          */
971
972         unsigned int    irq;            /* IRQ for this adapter */
973         int             instance;       /* aic7xxx instance number */
974         int             scsi_id;        /* host adapter SCSI ID */
975         int             scsi_id_b;      /* channel B for twin adapters */
976         unsigned int    bios_address;
977         int             board_name_index;
978         unsigned short  bios_control;           /* bios control - SEEPROM */
979         unsigned short  adapter_control;        /* adapter control - SEEPROM */
980         struct pci_dev  *pdev;
981         unsigned char   pci_bus;
982         unsigned char   pci_device_fn;
983         struct seeprom_config   sc;
984         unsigned short  sc_type;
985         unsigned short  sc_size;
986         struct aic7xxx_host     *next;  /* allow for multiple IRQs */
987         struct Scsi_Host        *host;  /* pointer to scsi host */
988         struct list_head         aic_devs; /* all aic_dev structs on host */
989         int             host_no;        /* SCSI host number */
990         unsigned long   mbase;          /* I/O memory address */
991         ahc_chip        chip;           /* chip type */
992         ahc_bugs        bugs;
993         dma_addr_t      fifo_dma;       /* DMA handle for fifo arrays */
994 };
995
996 /*
997  * Valid SCSIRATE values. (p. 3-17)
998  * Provides a mapping of transfer periods in ns/4 to the proper value to
999  * stick in the SCSIRATE reg to use that transfer rate.
1000  */
1001 #define AHC_SYNCRATE_ULTRA3 0
1002 #define AHC_SYNCRATE_ULTRA2 1
1003 #define AHC_SYNCRATE_ULTRA  3
1004 #define AHC_SYNCRATE_FAST   6
1005 #define AHC_SYNCRATE_CRC 0x40
1006 #define AHC_SYNCRATE_SE  0x10
1007 static struct aic7xxx_syncrate {
1008   /* Rates in Ultra mode have bit 8 of sxfr set */
1009 #define                ULTRA_SXFR 0x100
1010   int sxfr_ultra2;
1011   int sxfr;
1012   unsigned char period;
1013   const char *rate[2];
1014 } aic7xxx_syncrates[] = {
1015   { 0x42,  0x000,   9,  {"80.0", "160.0"} },
1016   { 0x13,  0x000,  10,  {"40.0", "80.0"} },
1017   { 0x14,  0x000,  11,  {"33.0", "66.6"} },
1018   { 0x15,  0x100,  12,  {"20.0", "40.0"} },
1019   { 0x16,  0x110,  15,  {"16.0", "32.0"} },
1020   { 0x17,  0x120,  18,  {"13.4", "26.8"} },
1021   { 0x18,  0x000,  25,  {"10.0", "20.0"} },
1022   { 0x19,  0x010,  31,  {"8.0",  "16.0"} },
1023   { 0x1a,  0x020,  37,  {"6.67", "13.3"} },
1024   { 0x1b,  0x030,  43,  {"5.7",  "11.4"} },
1025   { 0x10,  0x040,  50,  {"5.0",  "10.0"} },
1026   { 0x00,  0x050,  56,  {"4.4",  "8.8" } },
1027   { 0x00,  0x060,  62,  {"4.0",  "8.0" } },
1028   { 0x00,  0x070,  68,  {"3.6",  "7.2" } },
1029   { 0x00,  0x000,  0,   {NULL, NULL}   },
1030 };
1031
1032 #define CTL_OF_SCB(scb) (((scb->hscb)->target_channel_lun >> 3) & 0x1),  \
1033                         (((scb->hscb)->target_channel_lun >> 4) & 0xf), \
1034                         ((scb->hscb)->target_channel_lun & 0x07)
1035
1036 #define CTL_OF_CMD(cmd) ((cmd->device->channel) & 0x01),  \
1037                         ((cmd->device->id) & 0x0f), \
1038                         ((cmd->device->lun) & 0x07)
1039
1040 #define TARGET_INDEX(cmd)  ((cmd)->device->id | ((cmd)->device->channel << 3))
1041
1042 /*
1043  * A nice little define to make doing our printks a little easier
1044  */
1045
1046 #define WARN_LEAD KERN_WARNING "(scsi%d:%d:%d:%d) "
1047 #define INFO_LEAD KERN_INFO "(scsi%d:%d:%d:%d) "
1048
1049 /*
1050  * XXX - these options apply unilaterally to _all_ 274x/284x/294x
1051  *       cards in the system.  This should be fixed.  Exceptions to this
1052  *       rule are noted in the comments.
1053  */
1054
1055 /*
1056  * Use this as the default queue depth when setting tagged queueing on.
1057  */
1058 static unsigned int aic7xxx_default_queue_depth = AIC7XXX_CMDS_PER_DEVICE;
1059
1060 /*
1061  * Skip the scsi bus reset.  Non 0 make us skip the reset at startup.  This
1062  * has no effect on any later resets that might occur due to things like
1063  * SCSI bus timeouts.
1064  */
1065 static unsigned int aic7xxx_no_reset = 0;
1066 /*
1067  * Certain PCI motherboards will scan PCI devices from highest to lowest,
1068  * others scan from lowest to highest, and they tend to do all kinds of
1069  * strange things when they come into contact with PCI bridge chips.  The
1070  * net result of all this is that the PCI card that is actually used to boot
1071  * the machine is very hard to detect.  Most motherboards go from lowest
1072  * PCI slot number to highest, and the first SCSI controller found is the
1073  * one you boot from.  The only exceptions to this are when a controller
1074  * has its BIOS disabled.  So, we by default sort all of our SCSI controllers
1075  * from lowest PCI slot number to highest PCI slot number.  We also force
1076  * all controllers with their BIOS disabled to the end of the list.  This
1077  * works on *almost* all computers.  Where it doesn't work, we have this
1078  * option.  Setting this option to non-0 will reverse the order of the sort
1079  * to highest first, then lowest, but will still leave cards with their BIOS
1080  * disabled at the very end.  That should fix everyone up unless there are
1081  * really strange cirumstances.
1082  */
1083 static int aic7xxx_reverse_scan = 0;
1084 /*
1085  * Should we force EXTENDED translation on a controller.
1086  *     0 == Use whatever is in the SEEPROM or default to off
1087  *     1 == Use whatever is in the SEEPROM or default to on
1088  */
1089 static unsigned int aic7xxx_extended = 0;
1090 /*
1091  * The IRQ trigger method used on EISA controllers. Does not effect PCI cards.
1092  *   -1 = Use detected settings.
1093  *    0 = Force Edge triggered mode.
1094  *    1 = Force Level triggered mode.
1095  */
1096 static int aic7xxx_irq_trigger = -1;
1097 /*
1098  * This variable is used to override the termination settings on a controller.
1099  * This should not be used under normal conditions.  However, in the case
1100  * that a controller does not have a readable SEEPROM (so that we can't
1101  * read the SEEPROM settings directly) and that a controller has a buggered
1102  * version of the cable detection logic, this can be used to force the 
1103  * correct termination.  It is preferable to use the manual termination
1104  * settings in the BIOS if possible, but some motherboard controllers store
1105  * those settings in a format we can't read.  In other cases, auto term
1106  * should also work, but the chipset was put together with no auto term
1107  * logic (common on motherboard controllers).  In those cases, we have
1108  * 32 bits here to work with.  That's good for 8 controllers/channels.  The
1109  * bits are organized as 4 bits per channel, with scsi0 getting the lowest
1110  * 4 bits in the int.  A 1 in a bit position indicates the termination setting
1111  * that corresponds to that bit should be enabled, a 0 is disabled.
1112  * It looks something like this:
1113  *
1114  *    0x0f =  1111-Single Ended Low Byte Termination on/off
1115  *            ||\-Single Ended High Byte Termination on/off
1116  *            |\-LVD Low Byte Termination on/off
1117  *            \-LVD High Byte Termination on/off
1118  *
1119  * For non-Ultra2 controllers, the upper 2 bits are not important.  So, to
1120  * enable both high byte and low byte termination on scsi0, I would need to
1121  * make sure that the override_term variable was set to 0x03 (bits 0011).
1122  * To make sure that all termination is enabled on an Ultra2 controller at
1123  * scsi2 and only high byte termination on scsi1 and high and low byte
1124  * termination on scsi0, I would set override_term=0xf23 (bits 1111 0010 0011)
1125  *
1126  * For the most part, users should never have to use this, that's why I
1127  * left it fairly cryptic instead of easy to understand.  If you need it,
1128  * most likely someone will be telling you what your's needs to be set to.
1129  */
1130 static int aic7xxx_override_term = -1;
1131 /*
1132  * Certain motherboard chipset controllers tend to screw
1133  * up the polarity of the term enable output pin.  Use this variable
1134  * to force the correct polarity for your system.  This is a bitfield variable
1135  * similar to the previous one, but this one has one bit per channel instead
1136  * of four.
1137  *    0 = Force the setting to active low.
1138  *    1 = Force setting to active high.
1139  * Most Adaptec cards are active high, several motherboards are active low.
1140  * To force a 2940 card at SCSI 0 to active high and a motherboard 7895
1141  * controller at scsi1 and scsi2 to active low, and a 2910 card at scsi3
1142  * to active high, you would need to set stpwlev=0x9 (bits 1001).
1143  *
1144  * People shouldn't need to use this, but if you are experiencing lots of
1145  * SCSI timeout problems, this may help.  There is one sure way to test what
1146  * this option needs to be.  Using a boot floppy to boot the system, configure
1147  * your system to enable all SCSI termination (in the Adaptec SCSI BIOS) and
1148  * if needed then also pass a value to override_term to make sure that the
1149  * driver is enabling SCSI termination, then set this variable to either 0
1150  * or 1.  When the driver boots, make sure there are *NO* SCSI cables
1151  * connected to your controller.  If it finds and inits the controller
1152  * without problem, then the setting you passed to stpwlev was correct.  If
1153  * the driver goes into a reset loop and hangs the system, then you need the
1154  * other setting for this variable.  If neither setting lets the machine
1155  * boot then you have definite termination problems that may not be fixable.
1156  */
1157 static int aic7xxx_stpwlev = -1;
1158 /*
1159  * Set this to non-0 in order to force the driver to panic the kernel
1160  * and print out debugging info on a SCSI abort or reset cycle.
1161  */
1162 static int aic7xxx_panic_on_abort = 0;
1163 /*
1164  * PCI bus parity checking of the Adaptec controllers.  This is somewhat
1165  * dubious at best.  To my knowledge, this option has never actually
1166  * solved a PCI parity problem, but on certain machines with broken PCI
1167  * chipset configurations, it can generate tons of false error messages.
1168  * It's included in the driver for completeness.
1169  *   0 = Shut off PCI parity check
1170  *  -1 = Normal polarity pci parity checking
1171  *   1 = reverse polarity pci parity checking
1172  *
1173  * NOTE: you can't actually pass -1 on the lilo prompt.  So, to set this
1174  * variable to -1 you would actually want to simply pass the variable
1175  * name without a number.  That will invert the 0 which will result in
1176  * -1.
1177  */
1178 static int aic7xxx_pci_parity = 0;
1179 /*
1180  * Set this to any non-0 value to cause us to dump the contents of all
1181  * the card's registers in a hex dump format tailored to each model of
1182  * controller.
1183  * 
1184  * NOTE: THE CONTROLLER IS LEFT IN AN UNUSEABLE STATE BY THIS OPTION.
1185  *       YOU CANNOT BOOT UP WITH THIS OPTION, IT IS FOR DEBUGGING PURPOSES
1186  *       ONLY
1187  */
1188 static int aic7xxx_dump_card = 0;
1189 /*
1190  * Set this to a non-0 value to make us dump out the 32 bit instruction
1191  * registers on the card after completing the sequencer download.  This
1192  * allows the actual sequencer download to be verified.  It is possible
1193  * to use this option and still boot up and run your system.  This is
1194  * only intended for debugging purposes.
1195  */
1196 static int aic7xxx_dump_sequencer = 0;
1197 /*
1198  * Certain newer motherboards have put new PCI based devices into the
1199  * IO spaces that used to typically be occupied by VLB or EISA cards.
1200  * This overlap can cause these newer motherboards to lock up when scanned
1201  * for older EISA and VLB devices.  Setting this option to non-0 will
1202  * cause the driver to skip scanning for any VLB or EISA controllers and
1203  * only support the PCI controllers.  NOTE: this means that if the kernel
1204  * os compiled with PCI support disabled, then setting this to non-0
1205  * would result in never finding any devices :)
1206  */
1207 static int aic7xxx_no_probe = 0;
1208 /*
1209  * On some machines, enabling the external SCB RAM isn't reliable yet.  I
1210  * haven't had time to make test patches for things like changing the
1211  * timing mode on that external RAM either.  Some of those changes may
1212  * fix the problem.  Until then though, we default to external SCB RAM
1213  * off and give a command line option to enable it.
1214  */
1215 static int aic7xxx_scbram = 0;
1216 /*
1217  * So that we can set how long each device is given as a selection timeout.
1218  * The table of values goes like this:
1219  *   0 - 256ms
1220  *   1 - 128ms
1221  *   2 - 64ms
1222  *   3 - 32ms
1223  * We default to 64ms because it's fast.  Some old SCSI-I devices need a
1224  * longer time.  The final value has to be left shifted by 3, hence 0x10
1225  * is the final value.
1226  */
1227 static int aic7xxx_seltime = 0x10;
1228 /*
1229  * So that insmod can find the variable and make it point to something
1230  */
1231 #ifdef MODULE
1232 static char * aic7xxx = NULL;
1233 module_param(aic7xxx, charp, 0);
1234 #endif
1235
1236 #define VERBOSE_NORMAL         0x0000
1237 #define VERBOSE_NEGOTIATION    0x0001
1238 #define VERBOSE_SEQINT         0x0002
1239 #define VERBOSE_SCSIINT        0x0004
1240 #define VERBOSE_PROBE          0x0008
1241 #define VERBOSE_PROBE2         0x0010
1242 #define VERBOSE_NEGOTIATION2   0x0020
1243 #define VERBOSE_MINOR_ERROR    0x0040
1244 #define VERBOSE_TRACING        0x0080
1245 #define VERBOSE_ABORT          0x0f00
1246 #define VERBOSE_ABORT_MID      0x0100
1247 #define VERBOSE_ABORT_FIND     0x0200
1248 #define VERBOSE_ABORT_PROCESS  0x0400
1249 #define VERBOSE_ABORT_RETURN   0x0800
1250 #define VERBOSE_RESET          0xf000
1251 #define VERBOSE_RESET_MID      0x1000
1252 #define VERBOSE_RESET_FIND     0x2000
1253 #define VERBOSE_RESET_PROCESS  0x4000
1254 #define VERBOSE_RESET_RETURN   0x8000
1255 static int aic7xxx_verbose = VERBOSE_NORMAL | VERBOSE_NEGOTIATION |
1256            VERBOSE_PROBE;                     /* verbose messages */
1257
1258
1259 /****************************************************************************
1260  *
1261  * We're going to start putting in function declarations so that order of
1262  * functions is no longer important.  As needed, they are added here.
1263  *
1264  ***************************************************************************/
1265
1266 static int aic7xxx_release(struct Scsi_Host *host);
1267 static void aic7xxx_set_syncrate(struct aic7xxx_host *p, 
1268                 struct aic7xxx_syncrate *syncrate, int target, int channel,
1269                 unsigned int period, unsigned int offset, unsigned char options,
1270                 unsigned int type, struct aic_dev_data *aic_dev);
1271 static void aic7xxx_set_width(struct aic7xxx_host *p, int target, int channel,
1272                 int lun, unsigned int width, unsigned int type,
1273                 struct aic_dev_data *aic_dev);
1274 static void aic7xxx_panic_abort(struct aic7xxx_host *p, struct scsi_cmnd *cmd);
1275 static void aic7xxx_print_card(struct aic7xxx_host *p);
1276 static void aic7xxx_print_scratch_ram(struct aic7xxx_host *p);
1277 static void aic7xxx_print_sequencer(struct aic7xxx_host *p, int downloaded);
1278 #ifdef AIC7XXX_VERBOSE_DEBUGGING
1279 static void aic7xxx_check_scbs(struct aic7xxx_host *p, char *buffer);
1280 #endif
1281
1282 /****************************************************************************
1283  *
1284  * These functions are now used.  They happen to be wrapped in useless
1285  * inb/outb port read/writes around the real reads and writes because it
1286  * seems that certain very fast CPUs have a problem dealing with us when
1287  * going at full speed.
1288  *
1289  ***************************************************************************/
1290
1291 static unsigned char
1292 aic_inb(struct aic7xxx_host *p, long port)
1293 {
1294 #ifdef MMAPIO
1295   unsigned char x;
1296   if(p->maddr)
1297   {
1298     x = readb(p->maddr + port);
1299   }
1300   else
1301   {
1302     x = inb(p->base + port);
1303   }
1304   return(x);
1305 #else
1306   return(inb(p->base + port));
1307 #endif
1308 }
1309
1310 static void
1311 aic_outb(struct aic7xxx_host *p, unsigned char val, long port)
1312 {
1313 #ifdef MMAPIO
1314   if(p->maddr)
1315   {
1316     writeb(val, p->maddr + port);
1317     mb(); /* locked operation in order to force CPU ordering */
1318     readb(p->maddr + HCNTRL); /* dummy read to flush the PCI write */
1319   }
1320   else
1321   {
1322     outb(val, p->base + port);
1323     mb(); /* locked operation in order to force CPU ordering */
1324   }
1325 #else
1326   outb(val, p->base + port);
1327   mb(); /* locked operation in order to force CPU ordering */
1328 #endif
1329 }
1330
1331 /*+F*************************************************************************
1332  * Function:
1333  *   aic7xxx_setup
1334  *
1335  * Description:
1336  *   Handle Linux boot parameters. This routine allows for assigning a value
1337  *   to a parameter with a ':' between the parameter and the value.
1338  *   ie. aic7xxx=unpause:0x0A,extended
1339  *-F*************************************************************************/
1340 static int
1341 aic7xxx_setup(char *s)
1342 {
1343   int   i, n;
1344   char *p;
1345   char *end;
1346
1347   static struct {
1348     const char *name;
1349     unsigned int *flag;
1350   } options[] = {
1351     { "extended",    &aic7xxx_extended },
1352     { "no_reset",    &aic7xxx_no_reset },
1353     { "irq_trigger", &aic7xxx_irq_trigger },
1354     { "verbose",     &aic7xxx_verbose },
1355     { "reverse_scan",&aic7xxx_reverse_scan },
1356     { "override_term", &aic7xxx_override_term },
1357     { "stpwlev", &aic7xxx_stpwlev },
1358     { "no_probe", &aic7xxx_no_probe },
1359     { "panic_on_abort", &aic7xxx_panic_on_abort },
1360     { "pci_parity", &aic7xxx_pci_parity },
1361     { "dump_card", &aic7xxx_dump_card },
1362     { "dump_sequencer", &aic7xxx_dump_sequencer },
1363     { "default_queue_depth", &aic7xxx_default_queue_depth },
1364     { "scbram", &aic7xxx_scbram },
1365     { "seltime", &aic7xxx_seltime },
1366     { "tag_info",    NULL }
1367   };
1368
1369   end = strchr(s, '\0');
1370
1371   while ((p = strsep(&s, ",.")) != NULL)
1372   {
1373     for (i = 0; i < ARRAY_SIZE(options); i++)
1374     {
1375       n = strlen(options[i].name);
1376       if (!strncmp(options[i].name, p, n))
1377       {
1378         if (!strncmp(p, "tag_info", n))
1379         {
1380           if (p[n] == ':')
1381           {
1382             char *base;
1383             char *tok, *tok_end, *tok_end2;
1384             char tok_list[] = { '.', ',', '{', '}', '\0' };
1385             int i, instance = -1, device = -1;
1386             unsigned char done = FALSE;
1387
1388             base = p;
1389             tok = base + n + 1;  /* Forward us just past the ':' */
1390             tok_end = strchr(tok, '\0');
1391             if (tok_end < end)
1392               *tok_end = ',';
1393             while(!done)
1394             {
1395               switch(*tok)
1396               {
1397                 case '{':
1398                   if (instance == -1)
1399                     instance = 0;
1400                   else if (device == -1)
1401                     device = 0;
1402                   tok++;
1403                   break;
1404                 case '}':
1405                   if (device != -1)
1406                     device = -1;
1407                   else if (instance != -1)
1408                     instance = -1;
1409                   tok++;
1410                   break;
1411                 case ',':
1412                 case '.':
1413                   if (instance == -1)
1414                     done = TRUE;
1415                   else if (device >= 0)
1416                     device++;
1417                   else if (instance >= 0)
1418                     instance++;
1419                   if ( (device >= MAX_TARGETS) || 
1420                        (instance >= ARRAY_SIZE(aic7xxx_tag_info)) )
1421                     done = TRUE;
1422                   tok++;
1423                   if (!done)
1424                   {
1425                     base = tok;
1426                   }
1427                   break;
1428                 case '\0':
1429                   done = TRUE;
1430                   break;
1431                 default:
1432                   done = TRUE;
1433                   tok_end = strchr(tok, '\0');
1434                   for(i=0; tok_list[i]; i++)
1435                   {
1436                     tok_end2 = strchr(tok, tok_list[i]);
1437                     if ( (tok_end2) && (tok_end2 < tok_end) )
1438                     {
1439                       tok_end = tok_end2;
1440                       done = FALSE;
1441                     }
1442                   }
1443                   if ( (instance >= 0) && (device >= 0) &&
1444                        (instance < ARRAY_SIZE(aic7xxx_tag_info)) &&
1445                        (device < MAX_TARGETS) )
1446                     aic7xxx_tag_info[instance].tag_commands[device] =
1447                       simple_strtoul(tok, NULL, 0) & 0xff;
1448                   tok = tok_end;
1449                   break;
1450               }
1451             }
1452             while((p != base) && (p != NULL))
1453               p = strsep(&s, ",.");
1454           }
1455         }
1456         else if (p[n] == ':')
1457         {
1458           *(options[i].flag) = simple_strtoul(p + n + 1, NULL, 0);
1459           if(!strncmp(p, "seltime", n))
1460           {
1461             *(options[i].flag) = (*(options[i].flag) % 4) << 3;
1462           }
1463         }
1464         else if (!strncmp(p, "verbose", n))
1465         {
1466           *(options[i].flag) = 0xff29;
1467         }
1468         else
1469         {
1470           *(options[i].flag) = ~(*(options[i].flag));
1471           if(!strncmp(p, "seltime", n))
1472           {
1473             *(options[i].flag) = (*(options[i].flag) % 4) << 3;
1474           }
1475         }
1476       }
1477     }
1478   }
1479   return 1;
1480 }
1481
1482 __setup("aic7xxx=", aic7xxx_setup);
1483
1484 /*+F*************************************************************************
1485  * Function:
1486  *   pause_sequencer
1487  *
1488  * Description:
1489  *   Pause the sequencer and wait for it to actually stop - this
1490  *   is important since the sequencer can disable pausing for critical
1491  *   sections.
1492  *-F*************************************************************************/
1493 static void
1494 pause_sequencer(struct aic7xxx_host *p)
1495 {
1496   aic_outb(p, p->pause, HCNTRL);
1497   while ((aic_inb(p, HCNTRL) & PAUSE) == 0)
1498   {
1499     ;
1500   }
1501   if(p->features & AHC_ULTRA2)
1502   {
1503     aic_inb(p, CCSCBCTL);
1504   }
1505 }
1506
1507 /*+F*************************************************************************
1508  * Function:
1509  *   unpause_sequencer
1510  *
1511  * Description:
1512  *   Unpause the sequencer. Unremarkable, yet done often enough to
1513  *   warrant an easy way to do it.
1514  *-F*************************************************************************/
1515 static void
1516 unpause_sequencer(struct aic7xxx_host *p, int unpause_always)
1517 {
1518   if (unpause_always ||
1519       ( !(aic_inb(p, INTSTAT) & (SCSIINT | SEQINT | BRKADRINT)) &&
1520         !(p->flags & AHC_HANDLING_REQINITS) ) )
1521   {
1522     aic_outb(p, p->unpause, HCNTRL);
1523   }
1524 }
1525
1526 /*+F*************************************************************************
1527  * Function:
1528  *   restart_sequencer
1529  *
1530  * Description:
1531  *   Restart the sequencer program from address zero.  This assumes
1532  *   that the sequencer is already paused.
1533  *-F*************************************************************************/
1534 static void
1535 restart_sequencer(struct aic7xxx_host *p)
1536 {
1537   aic_outb(p, 0, SEQADDR0);
1538   aic_outb(p, 0, SEQADDR1);
1539   aic_outb(p, FASTMODE, SEQCTL);
1540 }
1541
1542 /*
1543  * We include the aic7xxx_seq.c file here so that the other defines have
1544  * already been made, and so that it comes before the code that actually
1545  * downloads the instructions (since we don't typically use function
1546  * prototype, our code has to be ordered that way, it's a left-over from
1547  * the original driver days.....I should fix it some time DL).
1548  */
1549 #include "aic7xxx_old/aic7xxx_seq.c"
1550
1551 /*+F*************************************************************************
1552  * Function:
1553  *   aic7xxx_check_patch
1554  *
1555  * Description:
1556  *   See if the next patch to download should be downloaded.
1557  *-F*************************************************************************/
1558 static int
1559 aic7xxx_check_patch(struct aic7xxx_host *p,
1560   struct sequencer_patch **start_patch, int start_instr, int *skip_addr)
1561 {
1562   struct sequencer_patch *cur_patch;
1563   struct sequencer_patch *last_patch;
1564   int num_patches;
1565
1566   num_patches = ARRAY_SIZE(sequencer_patches);
1567   last_patch = &sequencer_patches[num_patches];
1568   cur_patch = *start_patch;
1569
1570   while ((cur_patch < last_patch) && (start_instr == cur_patch->begin))
1571   {
1572     if (cur_patch->patch_func(p) == 0)
1573     {
1574       /*
1575        * Start rejecting code.
1576        */
1577       *skip_addr = start_instr + cur_patch->skip_instr;
1578       cur_patch += cur_patch->skip_patch;
1579     }
1580     else
1581     {
1582       /*
1583        * Found an OK patch.  Advance the patch pointer to the next patch
1584        * and wait for our instruction pointer to get here.
1585        */
1586       cur_patch++;
1587     }
1588   }
1589
1590   *start_patch = cur_patch;
1591   if (start_instr < *skip_addr)
1592     /*
1593      * Still skipping
1594      */
1595     return (0);
1596   return(1);
1597 }
1598
1599
1600 /*+F*************************************************************************
1601  * Function:
1602  *   aic7xxx_download_instr
1603  *
1604  * Description:
1605  *   Find the next patch to download.
1606  *-F*************************************************************************/
1607 static void
1608 aic7xxx_download_instr(struct aic7xxx_host *p, int instrptr,
1609   unsigned char *dconsts)
1610 {
1611   union ins_formats instr;
1612   struct ins_format1 *fmt1_ins;
1613   struct ins_format3 *fmt3_ins;
1614   unsigned char opcode;
1615
1616   instr = *(union ins_formats*) &seqprog[instrptr * 4];
1617
1618   instr.integer = le32_to_cpu(instr.integer);
1619   
1620   fmt1_ins = &instr.format1;
1621   fmt3_ins = NULL;
1622
1623   /* Pull the opcode */
1624   opcode = instr.format1.opcode;
1625   switch (opcode)
1626   {
1627     case AIC_OP_JMP:
1628     case AIC_OP_JC:
1629     case AIC_OP_JNC:
1630     case AIC_OP_CALL:
1631     case AIC_OP_JNE:
1632     case AIC_OP_JNZ:
1633     case AIC_OP_JE:
1634     case AIC_OP_JZ:
1635     {
1636       struct sequencer_patch *cur_patch;
1637       int address_offset;
1638       unsigned int address;
1639       int skip_addr;
1640       int i;
1641
1642       fmt3_ins = &instr.format3;
1643       address_offset = 0;
1644       address = fmt3_ins->address;
1645       cur_patch = sequencer_patches;
1646       skip_addr = 0;
1647
1648       for (i = 0; i < address;)
1649       {
1650         aic7xxx_check_patch(p, &cur_patch, i, &skip_addr);
1651         if (skip_addr > i)
1652         {
1653           int end_addr;
1654
1655           end_addr = min_t(int, address, skip_addr);
1656           address_offset += end_addr - i;
1657           i = skip_addr;
1658         }
1659         else
1660         {
1661           i++;
1662         }
1663       }
1664       address -= address_offset;
1665       fmt3_ins->address = address;
1666       /* Fall Through to the next code section */
1667     }
1668     case AIC_OP_OR:
1669     case AIC_OP_AND:
1670     case AIC_OP_XOR:
1671     case AIC_OP_ADD:
1672     case AIC_OP_ADC:
1673     case AIC_OP_BMOV:
1674       if (fmt1_ins->parity != 0)
1675       {
1676         fmt1_ins->immediate = dconsts[fmt1_ins->immediate];
1677       }
1678       fmt1_ins->parity = 0;
1679       /* Fall Through to the next code section */
1680     case AIC_OP_ROL:
1681       if ((p->features & AHC_ULTRA2) != 0)
1682       {
1683         int i, count;
1684
1685         /* Calculate odd parity for the instruction */
1686         for ( i=0, count=0; i < 31; i++)
1687         {
1688           unsigned int mask;
1689
1690           mask = 0x01 << i;
1691           if ((instr.integer & mask) != 0)
1692             count++;
1693         }
1694         if (!(count & 0x01))
1695           instr.format1.parity = 1;
1696       }
1697       else
1698       {
1699         if (fmt3_ins != NULL)
1700         {
1701           instr.integer =  fmt3_ins->immediate |
1702                           (fmt3_ins->source << 8) |
1703                           (fmt3_ins->address << 16) |
1704                           (fmt3_ins->opcode << 25);
1705         }
1706         else
1707         {
1708           instr.integer =  fmt1_ins->immediate |
1709                           (fmt1_ins->source << 8) |
1710                           (fmt1_ins->destination << 16) |
1711                           (fmt1_ins->ret << 24) |
1712                           (fmt1_ins->opcode << 25);
1713         }
1714       }
1715       aic_outb(p, (instr.integer & 0xff), SEQRAM);
1716       aic_outb(p, ((instr.integer >> 8) & 0xff), SEQRAM);
1717       aic_outb(p, ((instr.integer >> 16) & 0xff), SEQRAM);
1718       aic_outb(p, ((instr.integer >> 24) & 0xff), SEQRAM);
1719       udelay(10);
1720       break;
1721
1722     default:
1723       panic("aic7xxx: Unknown opcode encountered in sequencer program.");
1724       break;
1725   }
1726 }
1727
1728
1729 /*+F*************************************************************************
1730  * Function:
1731  *   aic7xxx_loadseq
1732  *
1733  * Description:
1734  *   Load the sequencer code into the controller memory.
1735  *-F*************************************************************************/
1736 static void
1737 aic7xxx_loadseq(struct aic7xxx_host *p)
1738 {
1739   struct sequencer_patch *cur_patch;
1740   int i;
1741   int downloaded;
1742   int skip_addr;
1743   unsigned char download_consts[4] = {0, 0, 0, 0};
1744
1745   if (aic7xxx_verbose & VERBOSE_PROBE)
1746   {
1747     printk(KERN_INFO "(scsi%d) Downloading sequencer code...", p->host_no);
1748   }
1749 #if 0
1750   download_consts[TMODE_NUMCMDS] = p->num_targetcmds;
1751 #endif
1752   download_consts[TMODE_NUMCMDS] = 0;
1753   cur_patch = &sequencer_patches[0];
1754   downloaded = 0;
1755   skip_addr = 0;
1756
1757   aic_outb(p, PERRORDIS|LOADRAM|FAILDIS|FASTMODE, SEQCTL);
1758   aic_outb(p, 0, SEQADDR0);
1759   aic_outb(p, 0, SEQADDR1);
1760
1761   for (i = 0; i < sizeof(seqprog) / 4;  i++)
1762   {
1763     if (aic7xxx_check_patch(p, &cur_patch, i, &skip_addr) == 0)
1764     {
1765       /* Skip this instruction for this configuration. */
1766       continue;
1767     }
1768     aic7xxx_download_instr(p, i, &download_consts[0]);
1769     downloaded++;
1770   }
1771
1772   aic_outb(p, 0, SEQADDR0);
1773   aic_outb(p, 0, SEQADDR1);
1774   aic_outb(p, FASTMODE | FAILDIS, SEQCTL);
1775   unpause_sequencer(p, TRUE);
1776   mdelay(1);
1777   pause_sequencer(p);
1778   aic_outb(p, FASTMODE, SEQCTL);
1779   if (aic7xxx_verbose & VERBOSE_PROBE)
1780   {
1781     printk(" %d instructions downloaded\n", downloaded);
1782   }
1783   if (aic7xxx_dump_sequencer)
1784     aic7xxx_print_sequencer(p, downloaded);
1785 }
1786
1787 /*+F*************************************************************************
1788  * Function:
1789  *   aic7xxx_print_sequencer
1790  *
1791  * Description:
1792  *   Print the contents of the sequencer memory to the screen.
1793  *-F*************************************************************************/
1794 static void
1795 aic7xxx_print_sequencer(struct aic7xxx_host *p, int downloaded)
1796 {
1797   int i, k, temp;
1798   
1799   aic_outb(p, PERRORDIS|LOADRAM|FAILDIS|FASTMODE, SEQCTL);
1800   aic_outb(p, 0, SEQADDR0);
1801   aic_outb(p, 0, SEQADDR1);
1802
1803   k = 0;
1804   for (i=0; i < downloaded; i++)
1805   {
1806     if ( k == 0 )
1807       printk("%03x: ", i);
1808     temp = aic_inb(p, SEQRAM);
1809     temp |= (aic_inb(p, SEQRAM) << 8);
1810     temp |= (aic_inb(p, SEQRAM) << 16);
1811     temp |= (aic_inb(p, SEQRAM) << 24);
1812     printk("%08x", temp);
1813     if ( ++k == 8 )
1814     {
1815       printk("\n");
1816       k = 0;
1817     }
1818     else
1819       printk(" ");
1820   }
1821   aic_outb(p, 0, SEQADDR0);
1822   aic_outb(p, 0, SEQADDR1);
1823   aic_outb(p, FASTMODE | FAILDIS, SEQCTL);
1824   unpause_sequencer(p, TRUE);
1825   mdelay(1);
1826   pause_sequencer(p);
1827   aic_outb(p, FASTMODE, SEQCTL);
1828   printk("\n");
1829 }
1830
1831 /*+F*************************************************************************
1832  * Function:
1833  *   aic7xxx_info
1834  *
1835  * Description:
1836  *   Return a string describing the driver.
1837  *-F*************************************************************************/
1838 static const char *
1839 aic7xxx_info(struct Scsi_Host *dooh)
1840 {
1841   static char buffer[256];
1842   char *bp;
1843   struct aic7xxx_host *p;
1844
1845   bp = &buffer[0];
1846   p = (struct aic7xxx_host *)dooh->hostdata;
1847   memset(bp, 0, sizeof(buffer));
1848   strcpy(bp, "Adaptec AHA274x/284x/294x (EISA/VLB/PCI-Fast SCSI) ");
1849   strcat(bp, AIC7XXX_C_VERSION);
1850   strcat(bp, "/");
1851   strcat(bp, AIC7XXX_H_VERSION);
1852   strcat(bp, "\n");
1853   strcat(bp, "       <");
1854   strcat(bp, board_names[p->board_name_index]);
1855   strcat(bp, ">");
1856
1857   return(bp);
1858 }
1859
1860 /*+F*************************************************************************
1861  * Function:
1862  *   aic7xxx_find_syncrate
1863  *
1864  * Description:
1865  *   Look up the valid period to SCSIRATE conversion in our table
1866  *-F*************************************************************************/
1867 static struct aic7xxx_syncrate *
1868 aic7xxx_find_syncrate(struct aic7xxx_host *p, unsigned int *period,
1869   unsigned int maxsync, unsigned char *options)
1870 {
1871   struct aic7xxx_syncrate *syncrate;
1872   int done = FALSE;
1873
1874   switch(*options)
1875   {
1876     case MSG_EXT_PPR_OPTION_DT_CRC:
1877     case MSG_EXT_PPR_OPTION_DT_UNITS:
1878       if(!(p->features & AHC_ULTRA3))
1879       {
1880         *options = 0;
1881         maxsync = max_t(unsigned int, maxsync, AHC_SYNCRATE_ULTRA2);
1882       }
1883       break;
1884     case MSG_EXT_PPR_OPTION_DT_CRC_QUICK:
1885     case MSG_EXT_PPR_OPTION_DT_UNITS_QUICK:
1886       if(!(p->features & AHC_ULTRA3))
1887       {
1888         *options = 0;
1889         maxsync = max_t(unsigned int, maxsync, AHC_SYNCRATE_ULTRA2);
1890       }
1891       else
1892       {
1893         /*
1894          * we don't support the Quick Arbitration variants of dual edge
1895          * clocking.  As it turns out, we want to send back the
1896          * same basic option, but without the QA attribute.
1897          * We know that we are responding because we would never set
1898          * these options ourself, we would only respond to them.
1899          */
1900         switch(*options)
1901         {
1902           case MSG_EXT_PPR_OPTION_DT_CRC_QUICK:
1903             *options = MSG_EXT_PPR_OPTION_DT_CRC;
1904             break;
1905           case MSG_EXT_PPR_OPTION_DT_UNITS_QUICK:
1906             *options = MSG_EXT_PPR_OPTION_DT_UNITS;
1907             break;
1908         }
1909       }
1910       break;
1911     default:
1912       *options = 0;
1913       maxsync = max_t(unsigned int, maxsync, AHC_SYNCRATE_ULTRA2);
1914       break;
1915   }
1916   syncrate = &aic7xxx_syncrates[maxsync];
1917   while ( (syncrate->rate[0] != NULL) &&
1918          (!(p->features & AHC_ULTRA2) || syncrate->sxfr_ultra2) )
1919   {
1920     if (*period <= syncrate->period) 
1921     {
1922       switch(*options)
1923       {
1924         case MSG_EXT_PPR_OPTION_DT_CRC:
1925         case MSG_EXT_PPR_OPTION_DT_UNITS:
1926           if(!(syncrate->sxfr_ultra2 & AHC_SYNCRATE_CRC))
1927           {
1928             done = TRUE;
1929             /*
1930              * oops, we went too low for the CRC/DualEdge signalling, so
1931              * clear the options byte
1932              */
1933             *options = 0;
1934             /*
1935              * We'll be sending a reply to this packet to set the options
1936              * properly, so unilaterally set the period as well.
1937              */
1938             *period = syncrate->period;
1939           }
1940           else
1941           {
1942             done = TRUE;
1943             if(syncrate == &aic7xxx_syncrates[maxsync])
1944             {
1945               *period = syncrate->period;
1946             }
1947           }
1948           break;
1949         default:
1950           if(!(syncrate->sxfr_ultra2 & AHC_SYNCRATE_CRC))
1951           {
1952             done = TRUE;
1953             if(syncrate == &aic7xxx_syncrates[maxsync])
1954             {
1955               *period = syncrate->period;
1956             }
1957           }
1958           break;
1959       }
1960       if(done)
1961       {
1962         break;
1963       }
1964     }
1965     syncrate++;
1966   }
1967   if ( (*period == 0) || (syncrate->rate[0] == NULL) ||
1968        ((p->features & AHC_ULTRA2) && (syncrate->sxfr_ultra2 == 0)) )
1969   {
1970     /*
1971      * Use async transfers for this target
1972      */
1973     *options = 0;
1974     *period = 255;
1975     syncrate = NULL;
1976   }
1977   return (syncrate);
1978 }
1979
1980
1981 /*+F*************************************************************************
1982  * Function:
1983  *   aic7xxx_find_period
1984  *
1985  * Description:
1986  *   Look up the valid SCSIRATE to period conversion in our table
1987  *-F*************************************************************************/
1988 static unsigned int
1989 aic7xxx_find_period(struct aic7xxx_host *p, unsigned int scsirate,
1990   unsigned int maxsync)
1991 {
1992   struct aic7xxx_syncrate *syncrate;
1993
1994   if (p->features & AHC_ULTRA2)
1995   {
1996     scsirate &= SXFR_ULTRA2;
1997   }
1998   else
1999   {
2000     scsirate &= SXFR;
2001   }
2002
2003   syncrate = &aic7xxx_syncrates[maxsync];
2004   while (syncrate->rate[0] != NULL)
2005   {
2006     if (p->features & AHC_ULTRA2)
2007     {
2008       if (syncrate->sxfr_ultra2 == 0)
2009         break;
2010       else if (scsirate == syncrate->sxfr_ultra2)
2011         return (syncrate->period);
2012       else if (scsirate == (syncrate->sxfr_ultra2 & ~AHC_SYNCRATE_CRC))
2013         return (syncrate->period);
2014     }
2015     else if (scsirate == (syncrate->sxfr & ~ULTRA_SXFR))
2016     {
2017       return (syncrate->period);
2018     }
2019     syncrate++;
2020   }
2021   return (0); /* async */
2022 }
2023
2024 /*+F*************************************************************************
2025  * Function:
2026  *   aic7xxx_validate_offset
2027  *
2028  * Description:
2029  *   Set a valid offset value for a particular card in use and transfer
2030  *   settings in use.
2031  *-F*************************************************************************/
2032 static void
2033 aic7xxx_validate_offset(struct aic7xxx_host *p,
2034   struct aic7xxx_syncrate *syncrate, unsigned int *offset, int wide)
2035 {
2036   unsigned int maxoffset;
2037
2038   /* Limit offset to what the card (and device) can do */
2039   if (syncrate == NULL)
2040   {
2041     maxoffset = 0;
2042   }
2043   else if (p->features & AHC_ULTRA2)
2044   {
2045     maxoffset = MAX_OFFSET_ULTRA2;
2046   }
2047   else
2048   {
2049     if (wide)
2050       maxoffset = MAX_OFFSET_16BIT;
2051     else
2052       maxoffset = MAX_OFFSET_8BIT;
2053   }
2054   *offset = min(*offset, maxoffset);
2055 }
2056
2057 /*+F*************************************************************************
2058  * Function:
2059  *   aic7xxx_set_syncrate
2060  *
2061  * Description:
2062  *   Set the actual syncrate down in the card and in our host structs
2063  *-F*************************************************************************/
2064 static void
2065 aic7xxx_set_syncrate(struct aic7xxx_host *p, struct aic7xxx_syncrate *syncrate,
2066     int target, int channel, unsigned int period, unsigned int offset,
2067     unsigned char options, unsigned int type, struct aic_dev_data *aic_dev)
2068 {
2069   unsigned char tindex;
2070   unsigned short target_mask;
2071   unsigned char lun, old_options;
2072   unsigned int old_period, old_offset;
2073
2074   tindex = target | (channel << 3);
2075   target_mask = 0x01 << tindex;
2076   lun = aic_inb(p, SCB_TCL) & 0x07;
2077
2078   if (syncrate == NULL)
2079   {
2080     period = 0;
2081     offset = 0;
2082   }
2083
2084   old_period = aic_dev->cur.period;
2085   old_offset = aic_dev->cur.offset;
2086   old_options = aic_dev->cur.options;
2087
2088   
2089   if (type & AHC_TRANS_CUR)
2090   {
2091     unsigned int scsirate;
2092
2093     scsirate = aic_inb(p, TARG_SCSIRATE + tindex);
2094     if (p->features & AHC_ULTRA2)
2095     {
2096       scsirate &= ~SXFR_ULTRA2;
2097       if (syncrate != NULL)
2098       {
2099         switch(options)
2100         {
2101           case MSG_EXT_PPR_OPTION_DT_UNITS:
2102             /*
2103              * mask off the CRC bit in the xfer settings
2104              */
2105             scsirate |= (syncrate->sxfr_ultra2 & ~AHC_SYNCRATE_CRC);
2106             break;
2107           default:
2108             scsirate |= syncrate->sxfr_ultra2;
2109             break;
2110         }
2111       }
2112       if (type & AHC_TRANS_ACTIVE)
2113       {
2114         aic_outb(p, offset, SCSIOFFSET);
2115       }
2116       aic_outb(p, offset, TARG_OFFSET + tindex);
2117     }
2118     else /* Not an Ultra2 controller */
2119     {
2120       scsirate &= ~(SXFR|SOFS);
2121       p->ultraenb &= ~target_mask;
2122       if (syncrate != NULL)
2123       {
2124         if (syncrate->sxfr & ULTRA_SXFR)
2125         {
2126           p->ultraenb |= target_mask;
2127         }
2128         scsirate |= (syncrate->sxfr & SXFR);
2129         scsirate |= (offset & SOFS);
2130       }
2131       if (type & AHC_TRANS_ACTIVE)
2132       {
2133         unsigned char sxfrctl0;
2134
2135         sxfrctl0 = aic_inb(p, SXFRCTL0);
2136         sxfrctl0 &= ~FAST20;
2137         if (p->ultraenb & target_mask)
2138           sxfrctl0 |= FAST20;
2139         aic_outb(p, sxfrctl0, SXFRCTL0);
2140       }
2141       aic_outb(p, p->ultraenb & 0xff, ULTRA_ENB);
2142       aic_outb(p, (p->ultraenb >> 8) & 0xff, ULTRA_ENB + 1 );
2143     }
2144     if (type & AHC_TRANS_ACTIVE)
2145     {
2146       aic_outb(p, scsirate, SCSIRATE);
2147     }
2148     aic_outb(p, scsirate, TARG_SCSIRATE + tindex);
2149     aic_dev->cur.period = period;
2150     aic_dev->cur.offset = offset;
2151     aic_dev->cur.options = options;
2152     if ( !(type & AHC_TRANS_QUITE) &&
2153          (aic7xxx_verbose & VERBOSE_NEGOTIATION) &&
2154          (aic_dev->flags & DEVICE_PRINT_DTR) )
2155     {
2156       if (offset)
2157       {
2158         int rate_mod = (scsirate & WIDEXFER) ? 1 : 0;
2159       
2160         printk(INFO_LEAD "Synchronous at %s Mbyte/sec, "
2161                "offset %d.\n", p->host_no, channel, target, lun,
2162                syncrate->rate[rate_mod], offset);
2163       }
2164       else
2165       {
2166         printk(INFO_LEAD "Using asynchronous transfers.\n",
2167                p->host_no, channel, target, lun);
2168       }
2169       aic_dev->flags &= ~DEVICE_PRINT_DTR;
2170     }
2171   }
2172
2173   if (type & AHC_TRANS_GOAL)
2174   {
2175     aic_dev->goal.period = period;
2176     aic_dev->goal.offset = offset;
2177     aic_dev->goal.options = options;
2178   }
2179
2180   if (type & AHC_TRANS_USER)
2181   {
2182     p->user[tindex].period = period;
2183     p->user[tindex].offset = offset;
2184     p->user[tindex].options = options;
2185   }
2186 }
2187
2188 /*+F*************************************************************************
2189  * Function:
2190  *   aic7xxx_set_width
2191  *
2192  * Description:
2193  *   Set the actual width down in the card and in our host structs
2194  *-F*************************************************************************/
2195 static void
2196 aic7xxx_set_width(struct aic7xxx_host *p, int target, int channel, int lun,
2197     unsigned int width, unsigned int type, struct aic_dev_data *aic_dev)
2198 {
2199   unsigned char tindex;
2200   unsigned short target_mask;
2201   unsigned int old_width;
2202
2203   tindex = target | (channel << 3);
2204   target_mask = 1 << tindex;
2205   
2206   old_width = aic_dev->cur.width;
2207
2208   if (type & AHC_TRANS_CUR) 
2209   {
2210     unsigned char scsirate;
2211
2212     scsirate = aic_inb(p, TARG_SCSIRATE + tindex);
2213
2214     scsirate &= ~WIDEXFER;
2215     if (width == MSG_EXT_WDTR_BUS_16_BIT)
2216       scsirate |= WIDEXFER;
2217
2218     aic_outb(p, scsirate, TARG_SCSIRATE + tindex);
2219
2220     if (type & AHC_TRANS_ACTIVE)
2221       aic_outb(p, scsirate, SCSIRATE);
2222
2223     aic_dev->cur.width = width;
2224
2225     if ( !(type & AHC_TRANS_QUITE) &&
2226           (aic7xxx_verbose & VERBOSE_NEGOTIATION2) && 
2227           (aic_dev->flags & DEVICE_PRINT_DTR) )
2228     {
2229       printk(INFO_LEAD "Using %s transfers\n", p->host_no, channel, target,
2230         lun, (scsirate & WIDEXFER) ? "Wide(16bit)" : "Narrow(8bit)" );
2231     }
2232   }
2233
2234   if (type & AHC_TRANS_GOAL)
2235     aic_dev->goal.width = width;
2236   if (type & AHC_TRANS_USER)
2237     p->user[tindex].width = width;
2238
2239   if (aic_dev->goal.offset)
2240   {
2241     if (p->features & AHC_ULTRA2)
2242     {
2243       aic_dev->goal.offset = MAX_OFFSET_ULTRA2;
2244     }
2245     else if (width == MSG_EXT_WDTR_BUS_16_BIT)
2246     {
2247       aic_dev->goal.offset = MAX_OFFSET_16BIT;
2248     }
2249     else
2250     {
2251       aic_dev->goal.offset = MAX_OFFSET_8BIT;
2252     }
2253   }
2254 }
2255       
2256 /*+F*************************************************************************
2257  * Function:
2258  *   scbq_init
2259  *
2260  * Description:
2261  *   SCB queue initialization.
2262  *
2263  *-F*************************************************************************/
2264 static void
2265 scbq_init(volatile scb_queue_type *queue)
2266 {
2267   queue->head = NULL;
2268   queue->tail = NULL;
2269 }
2270
2271 /*+F*************************************************************************
2272  * Function:
2273  *   scbq_insert_head
2274  *
2275  * Description:
2276  *   Add an SCB to the head of the list.
2277  *
2278  *-F*************************************************************************/
2279 static inline void
2280 scbq_insert_head(volatile scb_queue_type *queue, struct aic7xxx_scb *scb)
2281 {
2282   scb->q_next = queue->head;
2283   queue->head = scb;
2284   if (queue->tail == NULL)       /* If list was empty, update tail. */
2285     queue->tail = queue->head;
2286 }
2287
2288 /*+F*************************************************************************
2289  * Function:
2290  *   scbq_remove_head
2291  *
2292  * Description:
2293  *   Remove an SCB from the head of the list.
2294  *
2295  *-F*************************************************************************/
2296 static inline struct aic7xxx_scb *
2297 scbq_remove_head(volatile scb_queue_type *queue)
2298 {
2299   struct aic7xxx_scb * scbp;
2300
2301   scbp = queue->head;
2302   if (queue->head != NULL)
2303     queue->head = queue->head->q_next;
2304   if (queue->head == NULL)       /* If list is now empty, update tail. */
2305     queue->tail = NULL;
2306   return(scbp);
2307 }
2308
2309 /*+F*************************************************************************
2310  * Function:
2311  *   scbq_remove
2312  *
2313  * Description:
2314  *   Removes an SCB from the list.
2315  *
2316  *-F*************************************************************************/
2317 static inline void
2318 scbq_remove(volatile scb_queue_type *queue, struct aic7xxx_scb *scb)
2319 {
2320   if (queue->head == scb)
2321   {
2322     /* At beginning of queue, remove from head. */
2323     scbq_remove_head(queue);
2324   }
2325   else
2326   {
2327     struct aic7xxx_scb *curscb = queue->head;
2328
2329     /*
2330      * Search until the next scb is the one we're looking for, or
2331      * we run out of queue.
2332      */
2333     while ((curscb != NULL) && (curscb->q_next != scb))
2334     {
2335       curscb = curscb->q_next;
2336     }
2337     if (curscb != NULL)
2338     {
2339       /* Found it. */
2340       curscb->q_next = scb->q_next;
2341       if (scb->q_next == NULL)
2342       {
2343         /* Update the tail when removing the tail. */
2344         queue->tail = curscb;
2345       }
2346     }
2347   }
2348 }
2349
2350 /*+F*************************************************************************
2351  * Function:
2352  *   scbq_insert_tail
2353  *
2354  * Description:
2355  *   Add an SCB at the tail of the list.
2356  *
2357  *-F*************************************************************************/
2358 static inline void
2359 scbq_insert_tail(volatile scb_queue_type *queue, struct aic7xxx_scb *scb)
2360 {
2361   scb->q_next = NULL;
2362   if (queue->tail != NULL)       /* Add the scb at the end of the list. */
2363     queue->tail->q_next = scb;
2364   queue->tail = scb;             /* Update the tail. */
2365   if (queue->head == NULL)       /* If list was empty, update head. */
2366     queue->head = queue->tail;
2367 }
2368
2369 /*+F*************************************************************************
2370  * Function:
2371  *   aic7xxx_match_scb
2372  *
2373  * Description:
2374  *   Checks to see if an scb matches the target/channel as specified.
2375  *   If target is ALL_TARGETS (-1), then we're looking for any device
2376  *   on the specified channel; this happens when a channel is going
2377  *   to be reset and all devices on that channel must be aborted.
2378  *-F*************************************************************************/
2379 static int
2380 aic7xxx_match_scb(struct aic7xxx_host *p, struct aic7xxx_scb *scb,
2381     int target, int channel, int lun, unsigned char tag)
2382 {
2383   int targ = (scb->hscb->target_channel_lun >> 4) & 0x0F;
2384   int chan = (scb->hscb->target_channel_lun >> 3) & 0x01;
2385   int slun = scb->hscb->target_channel_lun & 0x07;
2386   int match;
2387
2388   match = ((chan == channel) || (channel == ALL_CHANNELS));
2389   if (match != 0)
2390     match = ((targ == target) || (target == ALL_TARGETS));
2391   if (match != 0)
2392     match = ((lun == slun) || (lun == ALL_LUNS));
2393   if (match != 0)
2394     match = ((tag == scb->hscb->tag) || (tag == SCB_LIST_NULL));
2395
2396   return (match);
2397 }
2398
2399 /*+F*************************************************************************
2400  * Function:
2401  *   aic7xxx_add_curscb_to_free_list
2402  *
2403  * Description:
2404  *   Adds the current scb (in SCBPTR) to the list of free SCBs.
2405  *-F*************************************************************************/
2406 static void
2407 aic7xxx_add_curscb_to_free_list(struct aic7xxx_host *p)
2408 {
2409   /*
2410    * Invalidate the tag so that aic7xxx_find_scb doesn't think
2411    * it's active
2412    */
2413   aic_outb(p, SCB_LIST_NULL, SCB_TAG);
2414   aic_outb(p, 0, SCB_CONTROL);
2415
2416   aic_outb(p, aic_inb(p, FREE_SCBH), SCB_NEXT);
2417   aic_outb(p, aic_inb(p, SCBPTR), FREE_SCBH);
2418 }
2419
2420 /*+F*************************************************************************
2421  * Function:
2422  *   aic7xxx_rem_scb_from_disc_list
2423  *
2424  * Description:
2425  *   Removes the current SCB from the disconnected list and adds it
2426  *   to the free list.
2427  *-F*************************************************************************/
2428 static unsigned char
2429 aic7xxx_rem_scb_from_disc_list(struct aic7xxx_host *p, unsigned char scbptr,
2430                                unsigned char prev)
2431 {
2432   unsigned char next;
2433
2434   aic_outb(p, scbptr, SCBPTR);
2435   next = aic_inb(p, SCB_NEXT);
2436   aic7xxx_add_curscb_to_free_list(p);
2437
2438   if (prev != SCB_LIST_NULL)
2439   {
2440     aic_outb(p, prev, SCBPTR);
2441     aic_outb(p, next, SCB_NEXT);
2442   }
2443   else
2444   {
2445     aic_outb(p, next, DISCONNECTED_SCBH);
2446   }
2447
2448   return next;
2449 }
2450
2451 /*+F*************************************************************************
2452  * Function:
2453  *   aic7xxx_busy_target
2454  *
2455  * Description:
2456  *   Set the specified target busy.
2457  *-F*************************************************************************/
2458 static inline void
2459 aic7xxx_busy_target(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
2460 {
2461   p->untagged_scbs[scb->hscb->target_channel_lun] = scb->hscb->tag;
2462 }
2463
2464 /*+F*************************************************************************
2465  * Function:
2466  *   aic7xxx_index_busy_target
2467  *
2468  * Description:
2469  *   Returns the index of the busy target, and optionally sets the
2470  *   target inactive.
2471  *-F*************************************************************************/
2472 static inline unsigned char
2473 aic7xxx_index_busy_target(struct aic7xxx_host *p, unsigned char tcl,
2474     int unbusy)
2475 {
2476   unsigned char busy_scbid;
2477
2478   busy_scbid = p->untagged_scbs[tcl];
2479   if (unbusy)
2480   {
2481     p->untagged_scbs[tcl] = SCB_LIST_NULL;
2482   }
2483   return (busy_scbid);
2484 }
2485
2486 /*+F*************************************************************************
2487  * Function:
2488  *   aic7xxx_find_scb
2489  *
2490  * Description:
2491  *   Look through the SCB array of the card and attempt to find the
2492  *   hardware SCB that corresponds to the passed in SCB.  Return
2493  *   SCB_LIST_NULL if unsuccessful.  This routine assumes that the
2494  *   card is already paused.
2495  *-F*************************************************************************/
2496 static unsigned char
2497 aic7xxx_find_scb(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
2498 {
2499   unsigned char saved_scbptr;
2500   unsigned char curindex;
2501
2502   saved_scbptr = aic_inb(p, SCBPTR);
2503   curindex = 0;
2504   for (curindex = 0; curindex < p->scb_data->maxhscbs; curindex++)
2505   {
2506     aic_outb(p, curindex, SCBPTR);
2507     if (aic_inb(p, SCB_TAG) == scb->hscb->tag)
2508     {
2509       break;
2510     }
2511   }
2512   aic_outb(p, saved_scbptr, SCBPTR);
2513   if (curindex >= p->scb_data->maxhscbs)
2514   {
2515     curindex = SCB_LIST_NULL;
2516   }
2517
2518   return (curindex);
2519 }
2520
2521 /*+F*************************************************************************
2522  * Function:
2523  *   aic7xxx_allocate_scb
2524  *
2525  * Description:
2526  *   Get an SCB from the free list or by allocating a new one.
2527  *-F*************************************************************************/
2528 static int
2529 aic7xxx_allocate_scb(struct aic7xxx_host *p)
2530 {
2531   struct aic7xxx_scb   *scbp = NULL;
2532   int scb_size = (sizeof (struct hw_scatterlist) * AIC7XXX_MAX_SG) + 12 + 6;
2533   int i;
2534   int step = PAGE_SIZE / 1024;
2535   unsigned long scb_count = 0;
2536   struct hw_scatterlist *hsgp;
2537   struct aic7xxx_scb *scb_ap;
2538   struct aic7xxx_scb_dma *scb_dma;
2539   unsigned char *bufs;
2540
2541   if (p->scb_data->numscbs < p->scb_data->maxscbs)
2542   {
2543     /*
2544      * Calculate the optimal number of SCBs to allocate.
2545      *
2546      * NOTE: This formula works because the sizeof(sg_array) is always
2547      * 1024.  Therefore, scb_size * i would always be > PAGE_SIZE *
2548      * (i/step).  The (i-1) allows the left hand side of the equation
2549      * to grow into the right hand side to a point of near perfect
2550      * efficiency since scb_size * (i -1) is growing slightly faster
2551      * than the right hand side.  If the number of SG array elements
2552      * is changed, this function may not be near so efficient any more.
2553      *
2554      * Since the DMA'able buffers are now allocated in a separate
2555      * chunk this algorithm has been modified to match.  The '12'
2556      * and '6' factors in scb_size are for the DMA'able command byte
2557      * and sensebuffers respectively.  -DaveM
2558      */
2559     for ( i=step;; i *= 2 )
2560     {
2561       if ( (scb_size * (i-1)) >= ( (PAGE_SIZE * (i/step)) - 64 ) )
2562       {
2563         i /= 2;
2564         break;
2565       }
2566     }
2567     scb_count = min( (i-1), p->scb_data->maxscbs - p->scb_data->numscbs);
2568     scb_ap = kmalloc(sizeof (struct aic7xxx_scb) * scb_count
2569                                            + sizeof(struct aic7xxx_scb_dma), GFP_ATOMIC);
2570     if (scb_ap == NULL)
2571       return(0);
2572     scb_dma = (struct aic7xxx_scb_dma *)&scb_ap[scb_count];
2573     hsgp = (struct hw_scatterlist *)
2574       pci_alloc_consistent(p->pdev, scb_size * scb_count,
2575                            &scb_dma->dma_address);
2576     if (hsgp == NULL)
2577     {
2578       kfree(scb_ap);
2579       return(0);
2580     }
2581     bufs = (unsigned char *)&hsgp[scb_count * AIC7XXX_MAX_SG];
2582 #ifdef AIC7XXX_VERBOSE_DEBUGGING
2583     if (aic7xxx_verbose > 0xffff)
2584     {
2585       if (p->scb_data->numscbs == 0)
2586         printk(INFO_LEAD "Allocating initial %ld SCB structures.\n",
2587           p->host_no, -1, -1, -1, scb_count);
2588       else
2589         printk(INFO_LEAD "Allocating %ld additional SCB structures.\n",
2590           p->host_no, -1, -1, -1, scb_count);
2591     }
2592 #endif
2593     memset(scb_ap, 0, sizeof (struct aic7xxx_scb) * scb_count);
2594     scb_dma->dma_offset = (unsigned long)scb_dma->dma_address
2595                           - (unsigned long)hsgp;
2596     scb_dma->dma_len = scb_size * scb_count;
2597     for (i=0; i < scb_count; i++)
2598     {
2599       scbp = &scb_ap[i];
2600       scbp->hscb = &p->scb_data->hscbs[p->scb_data->numscbs];
2601       scbp->sg_list = &hsgp[i * AIC7XXX_MAX_SG];
2602       scbp->sense_cmd = bufs;
2603       scbp->cmnd = bufs + 6;
2604       bufs += 12 + 6;
2605       scbp->scb_dma = scb_dma;
2606       memset(scbp->hscb, 0, sizeof(struct aic7xxx_hwscb));
2607       scbp->hscb->tag = p->scb_data->numscbs;
2608       /*
2609        * Place in the scb array; never is removed
2610        */
2611       p->scb_data->scb_array[p->scb_data->numscbs++] = scbp;
2612       scbq_insert_tail(&p->scb_data->free_scbs, scbp);
2613     }
2614     scbp->kmalloc_ptr = scb_ap;
2615   }
2616   return(scb_count);
2617 }
2618
2619 /*+F*************************************************************************
2620  * Function:
2621  *   aic7xxx_queue_cmd_complete
2622  *
2623  * Description:
2624  *   Due to race conditions present in the SCSI subsystem, it is easier
2625  *   to queue completed commands, then call scsi_done() on them when
2626  *   we're finished.  This function queues the completed commands.
2627  *-F*************************************************************************/
2628 static void
2629 aic7xxx_queue_cmd_complete(struct aic7xxx_host *p, struct scsi_cmnd *cmd)
2630 {
2631   aic7xxx_position(cmd) = SCB_LIST_NULL;
2632   cmd->host_scribble = (char *)p->completeq.head;
2633   p->completeq.head = cmd;
2634 }
2635
2636 /*+F*************************************************************************
2637  * Function:
2638  *   aic7xxx_done_cmds_complete
2639  *
2640  * Description:
2641  *   Process the completed command queue.
2642  *-F*************************************************************************/
2643 static void aic7xxx_done_cmds_complete(struct aic7xxx_host *p)
2644 {
2645         struct scsi_cmnd *cmd;
2646
2647         while (p->completeq.head != NULL) {
2648                 cmd = p->completeq.head;
2649                 p->completeq.head = (struct scsi_cmnd *) cmd->host_scribble;
2650                 cmd->host_scribble = NULL;
2651                 cmd->scsi_done(cmd);
2652         }
2653 }
2654
2655 /*+F*************************************************************************
2656  * Function:
2657  *   aic7xxx_free_scb
2658  *
2659  * Description:
2660  *   Free the scb and insert into the free scb list.
2661  *-F*************************************************************************/
2662 static void
2663 aic7xxx_free_scb(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
2664 {
2665
2666   scb->flags = SCB_FREE;
2667   scb->cmd = NULL;
2668   scb->sg_count = 0;
2669   scb->sg_length = 0;
2670   scb->tag_action = 0;
2671   scb->hscb->control = 0;
2672   scb->hscb->target_status = 0;
2673   scb->hscb->target_channel_lun = SCB_LIST_NULL;
2674
2675   scbq_insert_head(&p->scb_data->free_scbs, scb);
2676 }
2677
2678 /*+F*************************************************************************
2679  * Function:
2680  *   aic7xxx_done
2681  *
2682  * Description:
2683  *   Calls the higher level scsi done function and frees the scb.
2684  *-F*************************************************************************/
2685 static void
2686 aic7xxx_done(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
2687 {
2688         struct scsi_cmnd *cmd = scb->cmd;
2689         struct aic_dev_data *aic_dev = cmd->device->hostdata;
2690         int tindex = TARGET_INDEX(cmd);
2691         struct aic7xxx_scb *scbp;
2692         unsigned char queue_depth;
2693
2694   if (cmd->use_sg > 1)
2695   {
2696     struct scatterlist *sg;
2697
2698     sg = (struct scatterlist *)cmd->request_buffer;
2699     pci_unmap_sg(p->pdev, sg, cmd->use_sg, cmd->sc_data_direction);
2700   }
2701   else if (cmd->request_bufflen)
2702     pci_unmap_single(p->pdev, aic7xxx_mapping(cmd),
2703                      cmd->request_bufflen,
2704                      cmd->sc_data_direction);
2705   if (scb->flags & SCB_SENSE)
2706   {
2707     pci_unmap_single(p->pdev,
2708                      le32_to_cpu(scb->sg_list[0].address),
2709                      sizeof(cmd->sense_buffer),
2710                      PCI_DMA_FROMDEVICE);
2711   }
2712   if (scb->flags & SCB_RECOVERY_SCB)
2713   {
2714     p->flags &= ~AHC_ABORT_PENDING;
2715   }
2716   if (scb->flags & (SCB_RESET|SCB_ABORT))
2717   {
2718     cmd->result |= (DID_RESET << 16);
2719   }
2720
2721   if ((scb->flags & SCB_MSGOUT_BITS) != 0)
2722   {
2723     unsigned short mask;
2724     int message_error = FALSE;
2725
2726     mask = 0x01 << tindex;
2727  
2728     /*
2729      * Check to see if we get an invalid message or a message error
2730      * after failing to negotiate a wide or sync transfer message.
2731      */
2732     if ((scb->flags & SCB_SENSE) && 
2733           ((scb->cmd->sense_buffer[12] == 0x43) ||  /* INVALID_MESSAGE */
2734           (scb->cmd->sense_buffer[12] == 0x49))) /* MESSAGE_ERROR  */
2735     {
2736       message_error = TRUE;
2737     }
2738
2739     if (scb->flags & SCB_MSGOUT_WDTR)
2740     {
2741       if (message_error)
2742       {
2743         if ( (aic7xxx_verbose & VERBOSE_NEGOTIATION2) &&
2744              (aic_dev->flags & DEVICE_PRINT_DTR) )
2745         {
2746           printk(INFO_LEAD "Device failed to complete Wide Negotiation "
2747             "processing and\n", p->host_no, CTL_OF_SCB(scb));
2748           printk(INFO_LEAD "returned a sense error code for invalid message, "
2749             "disabling future\n", p->host_no, CTL_OF_SCB(scb));
2750           printk(INFO_LEAD "Wide negotiation to this device.\n", p->host_no,
2751             CTL_OF_SCB(scb));
2752         }
2753         aic_dev->needwdtr = aic_dev->needwdtr_copy = 0;
2754       }
2755     }
2756     if (scb->flags & SCB_MSGOUT_SDTR)
2757     {
2758       if (message_error)
2759       {
2760         if ( (aic7xxx_verbose & VERBOSE_NEGOTIATION2) &&
2761              (aic_dev->flags & DEVICE_PRINT_DTR) )
2762         {
2763           printk(INFO_LEAD "Device failed to complete Sync Negotiation "
2764             "processing and\n", p->host_no, CTL_OF_SCB(scb));
2765           printk(INFO_LEAD "returned a sense error code for invalid message, "
2766             "disabling future\n", p->host_no, CTL_OF_SCB(scb));
2767           printk(INFO_LEAD "Sync negotiation to this device.\n", p->host_no,
2768             CTL_OF_SCB(scb));
2769           aic_dev->flags &= ~DEVICE_PRINT_DTR;
2770         }
2771         aic_dev->needsdtr = aic_dev->needsdtr_copy = 0;
2772       }
2773     }
2774     if (scb->flags & SCB_MSGOUT_PPR)
2775     {
2776       if(message_error)
2777       {
2778         if ( (aic7xxx_verbose & VERBOSE_NEGOTIATION2) &&
2779              (aic_dev->flags & DEVICE_PRINT_DTR) )
2780         {
2781           printk(INFO_LEAD "Device failed to complete Parallel Protocol "
2782             "Request processing and\n", p->host_no, CTL_OF_SCB(scb));
2783           printk(INFO_LEAD "returned a sense error code for invalid message, "
2784             "disabling future\n", p->host_no, CTL_OF_SCB(scb));
2785           printk(INFO_LEAD "Parallel Protocol Request negotiation to this "
2786             "device.\n", p->host_no, CTL_OF_SCB(scb));
2787         }
2788         /*
2789          * Disable PPR negotiation and revert back to WDTR and SDTR setup
2790          */
2791         aic_dev->needppr = aic_dev->needppr_copy = 0;
2792         aic_dev->needsdtr = aic_dev->needsdtr_copy = 1;
2793         aic_dev->needwdtr = aic_dev->needwdtr_copy = 1;
2794       }
2795     }
2796   }
2797
2798   queue_depth = aic_dev->temp_q_depth;
2799   if (queue_depth >= aic_dev->active_cmds)
2800   {
2801     scbp = scbq_remove_head(&aic_dev->delayed_scbs);
2802     if (scbp)
2803     {
2804       if (queue_depth == 1)
2805       {
2806         /*
2807          * Give extra preference to untagged devices, such as CD-R devices
2808          * This makes it more likely that a drive *won't* stuff up while
2809          * waiting on data at a critical time, such as CD-R writing and
2810          * audio CD ripping operations.  Should also benefit tape drives.
2811          */
2812         scbq_insert_head(&p->waiting_scbs, scbp);
2813       }
2814       else
2815       {
2816         scbq_insert_tail(&p->waiting_scbs, scbp);
2817       }
2818 #ifdef AIC7XXX_VERBOSE_DEBUGGING
2819       if (aic7xxx_verbose > 0xffff)
2820         printk(INFO_LEAD "Moving SCB from delayed to waiting queue.\n",
2821                p->host_no, CTL_OF_SCB(scbp));
2822 #endif
2823       if (queue_depth > aic_dev->active_cmds)
2824       {
2825         scbp = scbq_remove_head(&aic_dev->delayed_scbs);
2826         if (scbp)
2827           scbq_insert_tail(&p->waiting_scbs, scbp);
2828       }
2829     }
2830   }
2831   if (!(scb->tag_action))
2832   {
2833     aic7xxx_index_busy_target(p, scb->hscb->target_channel_lun,
2834                               /* unbusy */ TRUE);
2835     if (cmd->device->simple_tags)
2836     {
2837       aic_dev->temp_q_depth = aic_dev->max_q_depth;
2838     }
2839   }
2840   if(scb->flags & SCB_DTR_SCB)
2841   {
2842     aic_dev->dtr_pending = 0;
2843   }
2844   aic_dev->active_cmds--;
2845   p->activescbs--;
2846
2847   if ((scb->sg_length >= 512) && (((cmd->result >> 16) & 0xf) == DID_OK))
2848   {
2849     long *ptr;
2850     int x, i;
2851
2852
2853     if (rq_data_dir(cmd->request) == WRITE)
2854     {
2855       aic_dev->w_total++;
2856       ptr = aic_dev->w_bins;
2857     }
2858     else
2859     {
2860       aic_dev->r_total++;
2861       ptr = aic_dev->r_bins;
2862     }
2863     if(cmd->device->simple_tags && cmd->request->cmd_flags & REQ_HARDBARRIER)
2864     {
2865       aic_dev->barrier_total++;
2866       if(scb->tag_action == MSG_ORDERED_Q_TAG)
2867         aic_dev->ordered_total++;
2868     }
2869     x = scb->sg_length;
2870     x >>= 10;
2871     for(i=0; i<6; i++)
2872     {
2873       x >>= 2;
2874       if(!x) {
2875         ptr[i]++;
2876         break;
2877       }
2878     }
2879     if(i == 6 && x)
2880       ptr[5]++;
2881   }
2882   aic7xxx_free_scb(p, scb);
2883   aic7xxx_queue_cmd_complete(p, cmd);
2884
2885 }
2886
2887 /*+F*************************************************************************
2888  * Function:
2889  *   aic7xxx_run_done_queue
2890  *
2891  * Description:
2892  *   Calls the aic7xxx_done() for the scsi_cmnd of each scb in the
2893  *   aborted list, and adds each scb to the free list.  If complete
2894  *   is TRUE, we also process the commands complete list.
2895  *-F*************************************************************************/
2896 static void
2897 aic7xxx_run_done_queue(struct aic7xxx_host *p, /*complete*/ int complete)
2898 {
2899   struct aic7xxx_scb *scb;
2900   int i, found = 0;
2901
2902   for (i = 0; i < p->scb_data->numscbs; i++)
2903   {
2904     scb = p->scb_data->scb_array[i];
2905     if (scb->flags & SCB_QUEUED_FOR_DONE)
2906     {
2907       if (scb->flags & SCB_QUEUE_FULL)
2908       {
2909         scb->cmd->result = QUEUE_FULL << 1;
2910       }
2911       else
2912       {
2913         if (aic7xxx_verbose & (VERBOSE_ABORT_PROCESS | VERBOSE_RESET_PROCESS))
2914           printk(INFO_LEAD "Aborting scb %d\n",
2915                p->host_no, CTL_OF_SCB(scb), scb->hscb->tag);
2916         /*
2917          * Clear any residual information since the normal aic7xxx_done() path
2918          * doesn't touch the residuals.
2919          */
2920         scb->hscb->residual_SG_segment_count = 0;
2921         scb->hscb->residual_data_count[0] = 0;
2922         scb->hscb->residual_data_count[1] = 0;
2923         scb->hscb->residual_data_count[2] = 0;
2924       }
2925       found++;
2926       aic7xxx_done(p, scb);
2927     }
2928   }
2929   if (aic7xxx_verbose & (VERBOSE_ABORT_RETURN | VERBOSE_RESET_RETURN))
2930   {
2931     printk(INFO_LEAD "%d commands found and queued for "
2932         "completion.\n", p->host_no, -1, -1, -1, found);
2933   }
2934   if (complete)
2935   {
2936     aic7xxx_done_cmds_complete(p);
2937   }
2938 }
2939
2940 /*+F*************************************************************************
2941  * Function:
2942  *   aic7xxx_abort_waiting_scb
2943  *
2944  * Description:
2945  *   Manipulate the waiting for selection list and return the
2946  *   scb that follows the one that we remove.
2947  *-F*************************************************************************/
2948 static unsigned char
2949 aic7xxx_abort_waiting_scb(struct aic7xxx_host *p, struct aic7xxx_scb *scb,
2950     unsigned char scbpos, unsigned char prev)
2951 {
2952   unsigned char curscb, next;
2953
2954   /*
2955    * Select the SCB we want to abort and pull the next pointer out of it.
2956    */
2957   curscb = aic_inb(p, SCBPTR);
2958   aic_outb(p, scbpos, SCBPTR);
2959   next = aic_inb(p, SCB_NEXT);
2960
2961   aic7xxx_add_curscb_to_free_list(p);
2962
2963   /*
2964    * Update the waiting list
2965    */
2966   if (prev == SCB_LIST_NULL)
2967   {
2968     /*
2969      * First in the list
2970      */
2971     aic_outb(p, next, WAITING_SCBH);
2972   }
2973   else
2974   {
2975     /*
2976      * Select the scb that pointed to us and update its next pointer.
2977      */
2978     aic_outb(p, prev, SCBPTR);
2979     aic_outb(p, next, SCB_NEXT);
2980   }
2981   /*
2982    * Point us back at the original scb position and inform the SCSI
2983    * system that the command has been aborted.
2984    */
2985   aic_outb(p, curscb, SCBPTR);
2986   return (next);
2987 }
2988
2989 /*+F*************************************************************************
2990  * Function:
2991  *   aic7xxx_search_qinfifo
2992  *
2993  * Description:
2994  *   Search the queue-in FIFO for matching SCBs and conditionally
2995  *   requeue.  Returns the number of matching SCBs.
2996  *-F*************************************************************************/
2997 static int
2998 aic7xxx_search_qinfifo(struct aic7xxx_host *p, int target, int channel,
2999     int lun, unsigned char tag, int flags, int requeue,
3000     volatile scb_queue_type *queue)
3001 {
3002   int      found;
3003   unsigned char qinpos, qintail;
3004   struct aic7xxx_scb *scbp;
3005
3006   found = 0;
3007   qinpos = aic_inb(p, QINPOS);
3008   qintail = p->qinfifonext;
3009
3010   p->qinfifonext = qinpos;
3011
3012   while (qinpos != qintail)
3013   {
3014     scbp = p->scb_data->scb_array[p->qinfifo[qinpos++]];
3015     if (aic7xxx_match_scb(p, scbp, target, channel, lun, tag))
3016     {
3017        /*
3018         * We found an scb that needs to be removed.
3019         */
3020        if (requeue && (queue != NULL))
3021        {
3022          if (scbp->flags & SCB_WAITINGQ)
3023          {
3024            scbq_remove(queue, scbp);
3025            scbq_remove(&p->waiting_scbs, scbp);
3026            scbq_remove(&AIC_DEV(scbp->cmd)->delayed_scbs, scbp);
3027            AIC_DEV(scbp->cmd)->active_cmds++;
3028            p->activescbs++;
3029          }
3030          scbq_insert_tail(queue, scbp);
3031          AIC_DEV(scbp->cmd)->active_cmds--;
3032          p->activescbs--;
3033          scbp->flags |= SCB_WAITINGQ;
3034          if ( !(scbp->tag_action & TAG_ENB) )
3035          {
3036            aic7xxx_index_busy_target(p, scbp->hscb->target_channel_lun,
3037              TRUE);
3038          }
3039        }
3040        else if (requeue)
3041        {
3042          p->qinfifo[p->qinfifonext++] = scbp->hscb->tag;
3043        }
3044        else
3045        {
3046         /*
3047          * Preserve any SCB_RECOVERY_SCB flags on this scb then set the
3048          * flags we were called with, presumeably so aic7xxx_run_done_queue
3049          * can find this scb
3050          */
3051          scbp->flags = flags | (scbp->flags & SCB_RECOVERY_SCB);
3052          if (aic7xxx_index_busy_target(p, scbp->hscb->target_channel_lun,
3053                                        FALSE) == scbp->hscb->tag)
3054          {
3055            aic7xxx_index_busy_target(p, scbp->hscb->target_channel_lun,
3056              TRUE);
3057          }
3058        }
3059        found++;
3060     }
3061     else
3062     {
3063       p->qinfifo[p->qinfifonext++] = scbp->hscb->tag;
3064     }
3065   }
3066   /*
3067    * Now that we've done the work, clear out any left over commands in the
3068    * qinfifo and update the KERNEL_QINPOS down on the card.
3069    *
3070    *  NOTE: This routine expect the sequencer to already be paused when
3071    *        it is run....make sure it's that way!
3072    */
3073   qinpos = p->qinfifonext;
3074   while(qinpos != qintail)
3075   {
3076     p->qinfifo[qinpos++] = SCB_LIST_NULL;
3077   }
3078   if (p->features & AHC_QUEUE_REGS)
3079     aic_outb(p, p->qinfifonext, HNSCB_QOFF);
3080   else
3081     aic_outb(p, p->qinfifonext, KERNEL_QINPOS);
3082
3083   return (found);
3084 }
3085
3086 /*+F*************************************************************************
3087  * Function:
3088  *   aic7xxx_scb_on_qoutfifo
3089  *
3090  * Description:
3091  *   Is the scb that was passed to us currently on the qoutfifo?
3092  *-F*************************************************************************/
3093 static int
3094 aic7xxx_scb_on_qoutfifo(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
3095 {
3096   int i=0;
3097
3098   while(p->qoutfifo[(p->qoutfifonext + i) & 0xff ] != SCB_LIST_NULL)
3099   {
3100     if(p->qoutfifo[(p->qoutfifonext + i) & 0xff ] == scb->hscb->tag)
3101       return TRUE;
3102     else
3103       i++;
3104   }
3105   return FALSE;
3106 }
3107
3108
3109 /*+F*************************************************************************
3110  * Function:
3111  *   aic7xxx_reset_device
3112  *
3113  * Description:
3114  *   The device at the given target/channel has been reset.  Abort
3115  *   all active and queued scbs for that target/channel.  This function
3116  *   need not worry about linked next pointers because if was a MSG_ABORT_TAG
3117  *   then we had a tagged command (no linked next), if it was MSG_ABORT or
3118  *   MSG_BUS_DEV_RESET then the device won't know about any commands any more
3119  *   and no busy commands will exist, and if it was a bus reset, then nothing
3120  *   knows about any linked next commands any more.  In all cases, we don't
3121  *   need to worry about the linked next or busy scb, we just need to clear
3122  *   them.
3123  *-F*************************************************************************/
3124 static void
3125 aic7xxx_reset_device(struct aic7xxx_host *p, int target, int channel,
3126                      int lun, unsigned char tag)
3127 {
3128   struct aic7xxx_scb *scbp, *prev_scbp;
3129   struct scsi_device *sd;
3130   unsigned char active_scb, tcl, scb_tag;
3131   int i = 0, init_lists = FALSE;
3132   struct aic_dev_data *aic_dev;
3133
3134   /*
3135    * Restore this when we're done
3136    */
3137   active_scb = aic_inb(p, SCBPTR);
3138   scb_tag = aic_inb(p, SCB_TAG);
3139
3140   if (aic7xxx_verbose & (VERBOSE_RESET_PROCESS | VERBOSE_ABORT_PROCESS))
3141   {
3142     printk(INFO_LEAD "Reset device, hardware_scb %d,\n",
3143          p->host_no, channel, target, lun, active_scb);
3144     printk(INFO_LEAD "Current scb %d, SEQADDR 0x%x, LASTPHASE "
3145            "0x%x\n",
3146          p->host_no, channel, target, lun, scb_tag,
3147          aic_inb(p, SEQADDR0) | (aic_inb(p, SEQADDR1) << 8),
3148          aic_inb(p, LASTPHASE));
3149     printk(INFO_LEAD "SG_CACHEPTR 0x%x, SG_COUNT %d, SCSISIGI 0x%x\n",
3150          p->host_no, channel, target, lun,
3151          (p->features & AHC_ULTRA2) ?  aic_inb(p, SG_CACHEPTR) : 0,
3152          aic_inb(p, SG_COUNT), aic_inb(p, SCSISIGI));
3153     printk(INFO_LEAD "SSTAT0 0x%x, SSTAT1 0x%x, SSTAT2 0x%x\n",
3154          p->host_no, channel, target, lun, aic_inb(p, SSTAT0),
3155          aic_inb(p, SSTAT1), aic_inb(p, SSTAT2));
3156   }
3157
3158   /*
3159    * Deal with the busy target and linked next issues.
3160    */
3161   list_for_each_entry(aic_dev, &p->aic_devs, list)
3162   {
3163     if (aic7xxx_verbose & (VERBOSE_RESET_PROCESS | VERBOSE_ABORT_PROCESS))
3164       printk(INFO_LEAD "processing aic_dev %p\n", p->host_no, channel, target,
3165                     lun, aic_dev);
3166     sd = aic_dev->SDptr;
3167
3168     if((target != ALL_TARGETS && target != sd->id) ||
3169        (channel != ALL_CHANNELS && channel != sd->channel))
3170       continue;
3171     if (aic7xxx_verbose & (VERBOSE_ABORT_PROCESS | VERBOSE_RESET_PROCESS))
3172         printk(INFO_LEAD "Cleaning up status information "
3173           "and delayed_scbs.\n", p->host_no, sd->channel, sd->id, sd->lun);
3174     aic_dev->flags &= ~BUS_DEVICE_RESET_PENDING;
3175     if ( tag == SCB_LIST_NULL )
3176     {
3177       aic_dev->dtr_pending = 0;
3178       aic_dev->needppr = aic_dev->needppr_copy;
3179       aic_dev->needsdtr = aic_dev->needsdtr_copy;
3180       aic_dev->needwdtr = aic_dev->needwdtr_copy;
3181       aic_dev->flags = DEVICE_PRINT_DTR;
3182       aic_dev->temp_q_depth = aic_dev->max_q_depth;
3183     }
3184     tcl = (sd->id << 4) | (sd->channel << 3) | sd->lun;
3185     if ( (aic7xxx_index_busy_target(p, tcl, FALSE) == tag) ||
3186          (tag == SCB_LIST_NULL) )
3187       aic7xxx_index_busy_target(p, tcl, /* unbusy */ TRUE);
3188     prev_scbp = NULL; 
3189     scbp = aic_dev->delayed_scbs.head;
3190     while (scbp != NULL)
3191     {
3192       prev_scbp = scbp;
3193       scbp = scbp->q_next;
3194       if (aic7xxx_match_scb(p, prev_scbp, target, channel, lun, tag))
3195       {
3196         scbq_remove(&aic_dev->delayed_scbs, prev_scbp);
3197         if (prev_scbp->flags & SCB_WAITINGQ)
3198         {
3199           aic_dev->active_cmds++;
3200           p->activescbs++;
3201         }
3202         prev_scbp->flags &= ~(SCB_ACTIVE | SCB_WAITINGQ);
3203         prev_scbp->flags |= SCB_RESET | SCB_QUEUED_FOR_DONE;
3204       }
3205     }
3206   }
3207
3208   if (aic7xxx_verbose & (VERBOSE_ABORT_PROCESS | VERBOSE_RESET_PROCESS))
3209     printk(INFO_LEAD "Cleaning QINFIFO.\n", p->host_no, channel, target, lun );
3210   aic7xxx_search_qinfifo(p, target, channel, lun, tag,
3211       SCB_RESET | SCB_QUEUED_FOR_DONE, /* requeue */ FALSE, NULL);
3212
3213 /*
3214  *  Search the waiting_scbs queue for matches, this catches any SCB_QUEUED
3215  *  ABORT/RESET commands.
3216  */
3217   if (aic7xxx_verbose & (VERBOSE_ABORT_PROCESS | VERBOSE_RESET_PROCESS))
3218     printk(INFO_LEAD "Cleaning waiting_scbs.\n", p->host_no, channel,
3219       target, lun );
3220   {
3221     struct aic7xxx_scb *scbp, *prev_scbp;
3222
3223     prev_scbp = NULL; 
3224     scbp = p->waiting_scbs.head;
3225     while (scbp != NULL)
3226     {
3227       prev_scbp = scbp;
3228       scbp = scbp->q_next;
3229       if (aic7xxx_match_scb(p, prev_scbp, target, channel, lun, tag))
3230       {
3231         scbq_remove(&p->waiting_scbs, prev_scbp);
3232         if (prev_scbp->flags & SCB_WAITINGQ)
3233         {
3234           AIC_DEV(prev_scbp->cmd)->active_cmds++;
3235           p->activescbs++;
3236         }
3237         prev_scbp->flags &= ~(SCB_ACTIVE | SCB_WAITINGQ);
3238         prev_scbp->flags |= SCB_RESET | SCB_QUEUED_FOR_DONE;
3239       }
3240     }
3241   }
3242
3243
3244   /*
3245    * Search waiting for selection list.
3246    */
3247   if (aic7xxx_verbose & (VERBOSE_ABORT_PROCESS | VERBOSE_RESET_PROCESS))
3248     printk(INFO_LEAD "Cleaning waiting for selection "
3249       "list.\n", p->host_no, channel, target, lun);
3250   {
3251     unsigned char next, prev, scb_index;
3252
3253     next = aic_inb(p, WAITING_SCBH);  /* Start at head of list. */
3254     prev = SCB_LIST_NULL;
3255     while (next != SCB_LIST_NULL)
3256     {
3257       aic_outb(p, next, SCBPTR);
3258       scb_index = aic_inb(p, SCB_TAG);
3259       if (scb_index >= p->scb_data->numscbs)
3260       {
3261        /*
3262         * No aic7xxx_verbose check here.....we want to see this since it
3263         * means either the kernel driver or the sequencer screwed things up
3264         */
3265         printk(WARN_LEAD "Waiting List inconsistency; SCB index=%d, "
3266           "numscbs=%d\n", p->host_no, channel, target, lun, scb_index,
3267           p->scb_data->numscbs);
3268         next = aic_inb(p, SCB_NEXT);
3269         aic7xxx_add_curscb_to_free_list(p);
3270       }
3271       else
3272       {
3273         scbp = p->scb_data->scb_array[scb_index];
3274         if (aic7xxx_match_scb(p, scbp, target, channel, lun, tag))
3275         {
3276           next = aic7xxx_abort_waiting_scb(p, scbp, next, prev);
3277           if (scbp->flags & SCB_WAITINGQ)
3278           {
3279             AIC_DEV(scbp->cmd)->active_cmds++;
3280             p->activescbs++;
3281           }
3282           scbp->flags &= ~(SCB_ACTIVE | SCB_WAITINGQ);
3283           scbp->flags |= SCB_RESET | SCB_QUEUED_FOR_DONE;
3284           if (prev == SCB_LIST_NULL)
3285           {
3286             /*
3287              * This is either the first scb on the waiting list, or we
3288              * have already yanked the first and haven't left any behind.
3289              * Either way, we need to turn off the selection hardware if
3290              * it isn't already off.
3291              */
3292             aic_outb(p, aic_inb(p, SCSISEQ) & ~ENSELO, SCSISEQ);
3293             aic_outb(p, CLRSELTIMEO, CLRSINT1);
3294           }
3295         }
3296         else
3297         {
3298           prev = next;
3299           next = aic_inb(p, SCB_NEXT);
3300         }
3301       }
3302     }
3303   }
3304
3305   /*
3306    * Go through disconnected list and remove any entries we have queued
3307    * for completion, zeroing their control byte too.
3308    */
3309   if (aic7xxx_verbose & (VERBOSE_ABORT_PROCESS | VERBOSE_RESET_PROCESS))
3310     printk(INFO_LEAD "Cleaning disconnected scbs "
3311       "list.\n", p->host_no, channel, target, lun);
3312   if (p->flags & AHC_PAGESCBS)
3313   {
3314     unsigned char next, prev, scb_index;
3315
3316     next = aic_inb(p, DISCONNECTED_SCBH);
3317     prev = SCB_LIST_NULL;
3318     while (next != SCB_LIST_NULL)
3319     {
3320       aic_outb(p, next, SCBPTR);
3321       scb_index = aic_inb(p, SCB_TAG);
3322       if (scb_index > p->scb_data->numscbs)
3323       {
3324         printk(WARN_LEAD "Disconnected List inconsistency; SCB index=%d, "
3325           "numscbs=%d\n", p->host_no, channel, target, lun, scb_index,
3326           p->scb_data->numscbs);
3327         next = aic7xxx_rem_scb_from_disc_list(p, next, prev);
3328       }
3329       else
3330       {
3331         scbp = p->scb_data->scb_array[scb_index];
3332         if (aic7xxx_match_scb(p, scbp, target, channel, lun, tag))
3333         {
3334           next = aic7xxx_rem_scb_from_disc_list(p, next, prev);
3335           if (scbp->flags & SCB_WAITINGQ)
3336           {
3337             AIC_DEV(scbp->cmd)->active_cmds++;
3338             p->activescbs++;
3339           }
3340           scbp->flags &= ~(SCB_ACTIVE | SCB_WAITINGQ);
3341           scbp->flags |= SCB_RESET | SCB_QUEUED_FOR_DONE;
3342           scbp->hscb->control = 0;
3343         }
3344         else
3345         {
3346           prev = next;
3347           next = aic_inb(p, SCB_NEXT);
3348         }
3349       }
3350     }
3351   }
3352
3353   /*
3354    * Walk the free list making sure no entries on the free list have
3355    * a valid SCB_TAG value or SCB_CONTROL byte.
3356    */
3357   if (p->flags & AHC_PAGESCBS)
3358   {
3359     unsigned char next;
3360
3361     next = aic_inb(p, FREE_SCBH);
3362     while (next != SCB_LIST_NULL)
3363     {
3364       aic_outb(p, next, SCBPTR);
3365       if (aic_inb(p, SCB_TAG) < p->scb_data->numscbs)
3366       {
3367         printk(WARN_LEAD "Free list inconsistency!.\n", p->host_no, channel,
3368           target, lun);
3369         init_lists = TRUE;
3370         next = SCB_LIST_NULL;
3371       }
3372       else
3373       {
3374         aic_outb(p, SCB_LIST_NULL, SCB_TAG);
3375         aic_outb(p, 0, SCB_CONTROL);
3376         next = aic_inb(p, SCB_NEXT);
3377       }
3378     }
3379   }
3380
3381   /*
3382    * Go through the hardware SCB array looking for commands that
3383    * were active but not on any list.
3384    */
3385   if (init_lists)
3386   {
3387     aic_outb(p, SCB_LIST_NULL, FREE_SCBH);
3388     aic_outb(p, SCB_LIST_NULL, WAITING_SCBH);
3389     aic_outb(p, SCB_LIST_NULL, DISCONNECTED_SCBH);
3390   }
3391   for (i = p->scb_data->maxhscbs - 1; i >= 0; i--)
3392   {
3393     unsigned char scbid;
3394
3395     aic_outb(p, i, SCBPTR);
3396     if (init_lists)
3397     {
3398       aic_outb(p, SCB_LIST_NULL, SCB_TAG);
3399       aic_outb(p, SCB_LIST_NULL, SCB_NEXT);
3400       aic_outb(p, 0, SCB_CONTROL);
3401       aic7xxx_add_curscb_to_free_list(p);
3402     }
3403     else
3404     {
3405       scbid = aic_inb(p, SCB_TAG);
3406       if (scbid < p->scb_data->numscbs)
3407       {
3408         scbp = p->scb_data->scb_array[scbid];
3409         if (aic7xxx_match_scb(p, scbp, target, channel, lun, tag))
3410         {
3411           aic_outb(p, 0, SCB_CONTROL);
3412           aic_outb(p, SCB_LIST_NULL, SCB_TAG);
3413           aic7xxx_add_curscb_to_free_list(p);
3414         }
3415       }
3416     }
3417   }
3418
3419   /*
3420    * Go through the entire SCB array now and look for commands for
3421    * for this target that are stillactive.  These are other (most likely
3422    * tagged) commands that were disconnected when the reset occurred.
3423    * Any commands we find here we know this about, it wasn't on any queue,
3424    * it wasn't in the qinfifo, it wasn't in the disconnected or waiting
3425    * lists, so it really must have been a paged out SCB.  In that case,
3426    * we shouldn't need to bother with updating any counters, just mark
3427    * the correct flags and go on.
3428    */
3429   for (i = 0; i < p->scb_data->numscbs; i++)
3430   {
3431     scbp = p->scb_data->scb_array[i];
3432     if ((scbp->flags & SCB_ACTIVE) &&
3433         aic7xxx_match_scb(p, scbp, target, channel, lun, tag) &&
3434         !aic7xxx_scb_on_qoutfifo(p, scbp))
3435     {
3436       if (scbp->flags & SCB_WAITINGQ)
3437       {
3438         scbq_remove(&p->waiting_scbs, scbp);
3439         scbq_remove(&AIC_DEV(scbp->cmd)->delayed_scbs, scbp);
3440         AIC_DEV(scbp->cmd)->active_cmds++;
3441         p->activescbs++;
3442       }
3443       scbp->flags |= SCB_RESET | SCB_QUEUED_FOR_DONE;
3444       scbp->flags &= ~(SCB_ACTIVE | SCB_WAITINGQ);
3445     }
3446   }
3447
3448   aic_outb(p, active_scb, SCBPTR);
3449 }
3450
3451
3452 /*+F*************************************************************************
3453  * Function:
3454  *   aic7xxx_clear_intstat
3455  *
3456  * Description:
3457  *   Clears the interrupt status.
3458  *-F*************************************************************************/
3459 static void
3460 aic7xxx_clear_intstat(struct aic7xxx_host *p)
3461 {
3462   /* Clear any interrupt conditions this may have caused. */
3463   aic_outb(p, CLRSELDO | CLRSELDI | CLRSELINGO, CLRSINT0);
3464   aic_outb(p, CLRSELTIMEO | CLRATNO | CLRSCSIRSTI | CLRBUSFREE | CLRSCSIPERR |
3465        CLRPHASECHG | CLRREQINIT, CLRSINT1);
3466   aic_outb(p, CLRSCSIINT | CLRSEQINT | CLRBRKADRINT | CLRPARERR, CLRINT);
3467 }
3468
3469 /*+F*************************************************************************
3470  * Function:
3471  *   aic7xxx_reset_current_bus
3472  *
3473  * Description:
3474  *   Reset the current SCSI bus.
3475  *-F*************************************************************************/
3476 static void
3477 aic7xxx_reset_current_bus(struct aic7xxx_host *p)
3478 {
3479
3480   /* Disable reset interrupts. */
3481   aic_outb(p, aic_inb(p, SIMODE1) & ~ENSCSIRST, SIMODE1);
3482
3483   /* Turn off the bus' current operations, after all, we shouldn't have any
3484    * valid commands left to cause a RSELI and SELO once we've tossed the
3485    * bus away with this reset, so we might as well shut down the sequencer
3486    * until the bus is restarted as oppossed to saving the current settings
3487    * and restoring them (which makes no sense to me). */
3488
3489   /* Turn on the bus reset. */
3490   aic_outb(p, aic_inb(p, SCSISEQ) | SCSIRSTO, SCSISEQ);
3491   while ( (aic_inb(p, SCSISEQ) & SCSIRSTO) == 0)
3492     mdelay(5);
3493
3494   /*
3495    * Some of the new Ultra2 chipsets need a longer delay after a chip
3496    * reset than just the init setup creates, so we have to delay here
3497    * before we go into a reset in order to make the chips happy.
3498    */
3499   if (p->features & AHC_ULTRA2)
3500     mdelay(250);
3501   else
3502     mdelay(50);
3503
3504   /* Turn off the bus reset. */
3505   aic_outb(p, 0, SCSISEQ);
3506   mdelay(10);
3507
3508   aic7xxx_clear_intstat(p);
3509   /* Re-enable reset interrupts. */
3510   aic_outb(p, aic_inb(p, SIMODE1) | ENSCSIRST, SIMODE1);
3511
3512 }
3513
3514 /*+F*************************************************************************
3515  * Function:
3516  *   aic7xxx_reset_channel
3517  *
3518  * Description:
3519  *   Reset the channel.
3520  *-F*************************************************************************/
3521 static void
3522 aic7xxx_reset_channel(struct aic7xxx_host *p, int channel, int initiate_reset)
3523 {
3524   unsigned long offset_min, offset_max;
3525   unsigned char sblkctl;
3526   int cur_channel;
3527
3528   if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
3529     printk(INFO_LEAD "Reset channel called, %s initiate reset.\n",
3530       p->host_no, channel, -1, -1, (initiate_reset==TRUE) ? "will" : "won't" );
3531
3532
3533   if (channel == 1)
3534   {
3535     offset_min = 8;
3536     offset_max = 16;
3537   }
3538   else
3539   {
3540     if (p->features & AHC_TWIN)
3541     {
3542       /* Channel A */
3543       offset_min = 0;
3544       offset_max = 8;
3545     }
3546     else
3547     {
3548       offset_min = 0;
3549       if (p->features & AHC_WIDE)
3550       {
3551         offset_max = 16;
3552       }
3553       else
3554       {
3555         offset_max = 8;
3556       }
3557     }
3558   }
3559
3560   while (offset_min < offset_max)
3561   {
3562     /*
3563      * Revert to async/narrow transfers until we renegotiate.
3564      */
3565     aic_outb(p, 0, TARG_SCSIRATE + offset_min);
3566     if (p->features & AHC_ULTRA2)
3567     {
3568       aic_outb(p, 0, TARG_OFFSET + offset_min);
3569     }
3570     offset_min++;
3571   }
3572
3573   /*
3574    * Reset the bus and unpause/restart the controller
3575    */
3576   sblkctl = aic_inb(p, SBLKCTL);
3577   if ( (p->chip & AHC_CHIPID_MASK) == AHC_AIC7770 )
3578     cur_channel = (sblkctl & SELBUSB) >> 3;
3579   else
3580     cur_channel = 0;
3581   if ( (cur_channel != channel) && (p->features & AHC_TWIN) )
3582   {
3583     /*
3584      * Case 1: Command for another bus is active
3585      */
3586     if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
3587       printk(INFO_LEAD "Stealthily resetting idle channel.\n", p->host_no,
3588         channel, -1, -1);
3589     /*
3590      * Stealthily reset the other bus without upsetting the current bus.
3591      */
3592     aic_outb(p, sblkctl ^ SELBUSB, SBLKCTL);
3593     aic_outb(p, aic_inb(p, SIMODE1) & ~ENBUSFREE, SIMODE1);
3594     if (initiate_reset)
3595     {
3596       aic7xxx_reset_current_bus(p);
3597     }
3598     aic_outb(p, aic_inb(p, SCSISEQ) & (ENSELI|ENRSELI|ENAUTOATNP), SCSISEQ);
3599     aic7xxx_clear_intstat(p);
3600     aic_outb(p, sblkctl, SBLKCTL);
3601   }
3602   else
3603   {
3604     /*
3605      * Case 2: A command from this bus is active or we're idle.
3606      */
3607     if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
3608       printk(INFO_LEAD "Resetting currently active channel.\n", p->host_no,
3609         channel, -1, -1);
3610     aic_outb(p, aic_inb(p, SIMODE1) & ~(ENBUSFREE|ENREQINIT),
3611       SIMODE1);
3612     p->flags &= ~AHC_HANDLING_REQINITS;
3613     p->msg_type = MSG_TYPE_NONE;
3614     p->msg_len = 0;
3615     if (initiate_reset)
3616     {
3617       aic7xxx_reset_current_bus(p);
3618     }
3619     aic_outb(p, aic_inb(p, SCSISEQ) & (ENSELI|ENRSELI|ENAUTOATNP), SCSISEQ);
3620     aic7xxx_clear_intstat(p);
3621   }
3622   if (aic7xxx_verbose & VERBOSE_RESET_RETURN)
3623     printk(INFO_LEAD "Channel reset\n", p->host_no, channel, -1, -1);
3624   /*
3625    * Clean up all the state information for the pending transactions
3626    * on this bus.
3627    */
3628   aic7xxx_reset_device(p, ALL_TARGETS, channel, ALL_LUNS, SCB_LIST_NULL);
3629
3630   if ( !(p->features & AHC_TWIN) )
3631   {
3632     restart_sequencer(p);
3633   }
3634
3635   return;
3636 }
3637
3638 /*+F*************************************************************************
3639  * Function:
3640  *   aic7xxx_run_waiting_queues
3641  *
3642  * Description:
3643  *   Scan the awaiting_scbs queue downloading and starting as many
3644  *   scbs as we can.
3645  *-F*************************************************************************/
3646 static void
3647 aic7xxx_run_waiting_queues(struct aic7xxx_host *p)
3648 {
3649   struct aic7xxx_scb *scb;
3650   struct aic_dev_data *aic_dev;
3651   int sent;
3652
3653
3654   if (p->waiting_scbs.head == NULL)
3655     return;
3656
3657   sent = 0;
3658
3659   /*
3660    * First handle SCBs that are waiting but have been assigned a slot.
3661    */
3662   while ((scb = scbq_remove_head(&p->waiting_scbs)) != NULL)
3663   {
3664     aic_dev = scb->cmd->device->hostdata;
3665     if ( !scb->tag_action )
3666     {
3667       aic_dev->temp_q_depth = 1;
3668     }
3669     if ( aic_dev->active_cmds >= aic_dev->temp_q_depth)
3670     {
3671       scbq_insert_tail(&aic_dev->delayed_scbs, scb);
3672     }
3673     else
3674     {
3675         scb->flags &= ~SCB_WAITINGQ;
3676         aic_dev->active_cmds++;
3677         p->activescbs++;
3678         if ( !(scb->tag_action) )
3679         {
3680           aic7xxx_busy_target(p, scb);
3681         }
3682         p->qinfifo[p->qinfifonext++] = scb->hscb->tag;
3683         sent++;
3684     }
3685   }
3686   if (sent)
3687   {
3688     if (p->features & AHC_QUEUE_REGS)
3689       aic_outb(p, p->qinfifonext, HNSCB_QOFF);
3690     else
3691     {
3692       pause_sequencer(p);
3693       aic_outb(p, p->qinfifonext, KERNEL_QINPOS);
3694       unpause_sequencer(p, FALSE);
3695     }
3696     if (p->activescbs > p->max_activescbs)
3697       p->max_activescbs = p->activescbs;
3698   }
3699 }
3700
3701 #ifdef CONFIG_PCI
3702
3703 #define  DPE 0x80
3704 #define  SSE 0x40
3705 #define  RMA 0x20
3706 #define  RTA 0x10
3707 #define  STA 0x08
3708 #define  DPR 0x01
3709
3710 /*+F*************************************************************************
3711  * Function:
3712  *   aic7xxx_pci_intr
3713  *
3714  * Description:
3715  *   Check the scsi card for PCI errors and clear the interrupt
3716  *
3717  *   NOTE: If you don't have this function and a 2940 card encounters
3718  *         a PCI error condition, the machine will end up locked as the
3719  *         interrupt handler gets slammed with non-stop PCI error interrupts
3720  *-F*************************************************************************/
3721 static void
3722 aic7xxx_pci_intr(struct aic7xxx_host *p)
3723 {
3724   unsigned char status1;
3725
3726   pci_read_config_byte(p->pdev, PCI_STATUS + 1, &status1);
3727
3728   if ( (status1 & DPE) && (aic7xxx_verbose & VERBOSE_MINOR_ERROR) )
3729     printk(WARN_LEAD "Data Parity Error during PCI address or PCI write"
3730       "phase.\n", p->host_no, -1, -1, -1);
3731   if ( (status1 & SSE) && (aic7xxx_verbose & VERBOSE_MINOR_ERROR) )
3732     printk(WARN_LEAD "Signal System Error Detected\n", p->host_no,
3733       -1, -1, -1);
3734   if ( (status1 & RMA) && (aic7xxx_verbose & VERBOSE_MINOR_ERROR) )
3735     printk(WARN_LEAD "Received a PCI Master Abort\n", p->host_no,
3736       -1, -1, -1);
3737   if ( (status1 & RTA) && (aic7xxx_verbose & VERBOSE_MINOR_ERROR) )
3738     printk(WARN_LEAD "Received a PCI Target Abort\n", p->host_no,
3739       -1, -1, -1);
3740   if ( (status1 & STA) && (aic7xxx_verbose & VERBOSE_MINOR_ERROR) )
3741     printk(WARN_LEAD "Signaled a PCI Target Abort\n", p->host_no,
3742       -1, -1, -1);
3743   if ( (status1 & DPR) && (aic7xxx_verbose & VERBOSE_MINOR_ERROR) )
3744     printk(WARN_LEAD "Data Parity Error has been reported via PCI pin "
3745       "PERR#\n", p->host_no, -1, -1, -1);
3746   
3747   pci_write_config_byte(p->pdev, PCI_STATUS + 1, status1);
3748   if (status1 & (DPR|RMA|RTA))
3749     aic_outb(p,  CLRPARERR, CLRINT);
3750
3751   if ( (aic7xxx_panic_on_abort) && (p->spurious_int > 500) )
3752     aic7xxx_panic_abort(p, NULL);
3753
3754 }
3755 #endif /* CONFIG_PCI */
3756
3757 /*+F*************************************************************************
3758  * Function:
3759  *   aic7xxx_construct_ppr
3760  *
3761  * Description:
3762  *   Build up a Parallel Protocol Request message for use with SCSI-3
3763  *   devices.
3764  *-F*************************************************************************/
3765 static void
3766 aic7xxx_construct_ppr(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
3767 {
3768   p->msg_buf[p->msg_index++] = MSG_EXTENDED;
3769   p->msg_buf[p->msg_index++] = MSG_EXT_PPR_LEN;
3770   p->msg_buf[p->msg_index++] = MSG_EXT_PPR;
3771   p->msg_buf[p->msg_index++] = AIC_DEV(scb->cmd)->goal.period;
3772   p->msg_buf[p->msg_index++] = 0;
3773   p->msg_buf[p->msg_index++] = AIC_DEV(scb->cmd)->goal.offset;
3774   p->msg_buf[p->msg_index++] = AIC_DEV(scb->cmd)->goal.width;
3775   p->msg_buf[p->msg_index++] = AIC_DEV(scb->cmd)->goal.options;
3776   p->msg_len += 8;
3777 }
3778
3779 /*+F*************************************************************************
3780  * Function:
3781  *   aic7xxx_construct_sdtr
3782  *
3783  * Description:
3784  *   Constucts a synchronous data transfer message in the message
3785  *   buffer on the sequencer.
3786  *-F*************************************************************************/
3787 static void
3788 aic7xxx_construct_sdtr(struct aic7xxx_host *p, unsigned char period,
3789         unsigned char offset)
3790 {
3791   p->msg_buf[p->msg_index++] = MSG_EXTENDED;
3792   p->msg_buf[p->msg_index++] = MSG_EXT_SDTR_LEN;
3793   p->msg_buf[p->msg_index++] = MSG_EXT_SDTR;
3794   p->msg_buf[p->msg_index++] = period;
3795   p->msg_buf[p->msg_index++] = offset;
3796   p->msg_len += 5;
3797 }
3798
3799 /*+F*************************************************************************
3800  * Function:
3801  *   aic7xxx_construct_wdtr
3802  *
3803  * Description:
3804  *   Constucts a wide data transfer message in the message buffer
3805  *   on the sequencer.
3806  *-F*************************************************************************/
3807 static void
3808 aic7xxx_construct_wdtr(struct aic7xxx_host *p, unsigned char bus_width)
3809 {
3810   p->msg_buf[p->msg_index++] = MSG_EXTENDED;
3811   p->msg_buf[p->msg_index++] = MSG_EXT_WDTR_LEN;
3812   p->msg_buf[p->msg_index++] = MSG_EXT_WDTR;
3813   p->msg_buf[p->msg_index++] = bus_width;
3814   p->msg_len += 4;
3815 }
3816
3817 /*+F*************************************************************************
3818  * Function:
3819  *   aic7xxx_calc_residual
3820  *
3821  * Description:
3822  *   Calculate the residual data not yet transferred.
3823  *-F*************************************************************************/
3824 static void
3825 aic7xxx_calculate_residual (struct aic7xxx_host *p, struct aic7xxx_scb *scb)
3826 {
3827         struct aic7xxx_hwscb *hscb;
3828         struct scsi_cmnd *cmd;
3829         int actual, i;
3830
3831   cmd = scb->cmd;
3832   hscb = scb->hscb;
3833
3834   /*
3835    *  Don't destroy valid residual information with
3836    *  residual coming from a check sense operation.
3837    */
3838   if (((scb->hscb->control & DISCONNECTED) == 0) &&
3839       (scb->flags & SCB_SENSE) == 0)
3840   {
3841     /*
3842      *  We had an underflow. At this time, there's only
3843      *  one other driver that bothers to check for this,
3844      *  and cmd->underflow seems to be set rather half-
3845      *  heartedly in the higher-level SCSI code.
3846      */
3847     actual = scb->sg_length;
3848     for (i=1; i < hscb->residual_SG_segment_count; i++)
3849     {
3850       actual -= scb->sg_list[scb->sg_count - i].length;
3851     }
3852     actual -= (hscb->residual_data_count[2] << 16) |
3853               (hscb->residual_data_count[1] <<  8) |
3854               hscb->residual_data_count[0];
3855
3856     if (actual < cmd->underflow)
3857     {
3858       if (aic7xxx_verbose & VERBOSE_MINOR_ERROR)
3859       {
3860         printk(INFO_LEAD "Underflow - Wanted %u, %s %u, residual SG "
3861           "count %d.\n", p->host_no, CTL_OF_SCB(scb), cmd->underflow,
3862           (rq_data_dir(cmd->request) == WRITE) ? "wrote" : "read", actual,
3863           hscb->residual_SG_segment_count);
3864         printk(INFO_LEAD "status 0x%x.\n", p->host_no, CTL_OF_SCB(scb),
3865           hscb->target_status);
3866       }
3867       /*
3868        * In 2.4, only send back the residual information, don't flag this
3869        * as an error.  Before 2.4 we had to flag this as an error because
3870        * the mid layer didn't check residual data counts to see if the
3871        * command needs retried.
3872        */
3873       cmd->resid = scb->sg_length - actual;
3874       aic7xxx_status(cmd) = hscb->target_status;
3875     }
3876   }
3877
3878   /*
3879    * Clean out the residual information in the SCB for the
3880    * next consumer.
3881    */
3882   hscb->residual_data_count[2] = 0;
3883   hscb->residual_data_count[1] = 0;
3884   hscb->residual_data_count[0] = 0;
3885   hscb->residual_SG_segment_count = 0;
3886 }
3887
3888 /*+F*************************************************************************
3889  * Function:
3890  *   aic7xxx_handle_device_reset
3891  *
3892  * Description:
3893  *   Interrupt handler for sequencer interrupts (SEQINT).
3894  *-F*************************************************************************/
3895 static void
3896 aic7xxx_handle_device_reset(struct aic7xxx_host *p, int target, int channel)
3897 {
3898   unsigned char tindex = target;
3899
3900   tindex |= ((channel & 0x01) << 3);
3901
3902   /*
3903    * Go back to async/narrow transfers and renegotiate.
3904    */
3905   aic_outb(p, 0, TARG_SCSIRATE + tindex);
3906   if (p->features & AHC_ULTRA2)
3907     aic_outb(p, 0, TARG_OFFSET + tindex);
3908   aic7xxx_reset_device(p, target, channel, ALL_LUNS, SCB_LIST_NULL);
3909   if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
3910     printk(INFO_LEAD "Bus Device Reset delivered.\n", p->host_no, channel,
3911       target, -1);
3912   aic7xxx_run_done_queue(p, /*complete*/ TRUE);
3913 }
3914
3915 /*+F*************************************************************************
3916  * Function:
3917  *   aic7xxx_handle_seqint
3918  *
3919  * Description:
3920  *   Interrupt handler for sequencer interrupts (SEQINT).
3921  *-F*************************************************************************/
3922 static void
3923 aic7xxx_handle_seqint(struct aic7xxx_host *p, unsigned char intstat)
3924 {
3925   struct aic7xxx_scb *scb;
3926   struct aic_dev_data *aic_dev;
3927   unsigned short target_mask;
3928   unsigned char target, lun, tindex;
3929   unsigned char queue_flag = FALSE;
3930   char channel;
3931   int result;
3932
3933   target = ((aic_inb(p, SAVED_TCL) >> 4) & 0x0f);
3934   if ( (p->chip & AHC_CHIPID_MASK) == AHC_AIC7770 )
3935     channel = (aic_inb(p, SBLKCTL) & SELBUSB) >> 3;
3936   else
3937     channel = 0;
3938   tindex = target + (channel << 3);
3939   lun = aic_inb(p, SAVED_TCL) & 0x07;
3940   target_mask = (0x01 << tindex);
3941
3942   /*
3943    * Go ahead and clear the SEQINT now, that avoids any interrupt race
3944    * conditions later on in case we enable some other interrupt.
3945    */
3946   aic_outb(p, CLRSEQINT, CLRINT);
3947   switch (intstat & SEQINT_MASK)
3948   {
3949     case NO_MATCH:
3950       {
3951         aic_outb(p, aic_inb(p, SCSISEQ) & (ENSELI|ENRSELI|ENAUTOATNP),
3952                  SCSISEQ);
3953         printk(WARN_LEAD "No active SCB for reconnecting target - Issuing "
3954                "BUS DEVICE RESET.\n", p->host_no, channel, target, lun);
3955         printk(WARN_LEAD "      SAVED_TCL=0x%x, ARG_1=0x%x, SEQADDR=0x%x\n",
3956                p->host_no, channel, target, lun,
3957                aic_inb(p, SAVED_TCL), aic_inb(p, ARG_1),
3958                (aic_inb(p, SEQADDR1) << 8) | aic_inb(p, SEQADDR0));
3959         if (aic7xxx_panic_on_abort)
3960           aic7xxx_panic_abort(p, NULL);
3961       }
3962       break;
3963
3964     case SEND_REJECT:
3965       {
3966         if (aic7xxx_verbose & VERBOSE_MINOR_ERROR)
3967           printk(INFO_LEAD "Rejecting unknown message (0x%x) received from "
3968             "target, SEQ_FLAGS=0x%x\n", p->host_no, channel, target, lun,
3969             aic_inb(p, ACCUM), aic_inb(p, SEQ_FLAGS));
3970       }
3971       break;
3972
3973     case NO_IDENT:
3974       {
3975         /*
3976          * The reconnecting target either did not send an identify
3977          * message, or did, but we didn't find an SCB to match and
3978          * before it could respond to our ATN/abort, it hit a dataphase.
3979          * The only safe thing to do is to blow it away with a bus
3980          * reset.
3981          */
3982         if (aic7xxx_verbose & (VERBOSE_SEQINT | VERBOSE_RESET_MID))
3983           printk(INFO_LEAD "Target did not send an IDENTIFY message; "
3984             "LASTPHASE 0x%x, SAVED_TCL 0x%x\n", p->host_no, channel, target,
3985             lun, aic_inb(p, LASTPHASE), aic_inb(p, SAVED_TCL));
3986
3987         aic7xxx_reset_channel(p, channel, /*initiate reset*/ TRUE);
3988         aic7xxx_run_done_queue(p, TRUE);
3989
3990       }
3991       break;
3992
3993     case BAD_PHASE:
3994       if (aic_inb(p, LASTPHASE) == P_BUSFREE)
3995       {
3996         if (aic7xxx_verbose & VERBOSE_SEQINT)
3997           printk(INFO_LEAD "Missed busfree.\n", p->host_no, channel,
3998             target, lun);
3999         restart_sequencer(p);
4000       }
4001       else
4002       {
4003         if (aic7xxx_verbose & VERBOSE_SEQINT)
4004           printk(INFO_LEAD "Unknown scsi bus phase, continuing\n", p->host_no,
4005             channel, target, lun);
4006       }
4007       break;
4008
4009     case EXTENDED_MSG:
4010       {
4011         p->msg_type = MSG_TYPE_INITIATOR_MSGIN;
4012         p->msg_len = 0;
4013         p->msg_index = 0;
4014
4015 #ifdef AIC7XXX_VERBOSE_DEBUGGING
4016         if (aic7xxx_verbose > 0xffff)
4017           printk(INFO_LEAD "Enabling REQINITs for MSG_IN\n", p->host_no,
4018                  channel, target, lun);
4019 #endif
4020
4021        /*      
4022         * To actually receive the message, simply turn on
4023         * REQINIT interrupts and let our interrupt handler
4024         * do the rest (REQINIT should already be true).
4025         */
4026         p->flags |= AHC_HANDLING_REQINITS;
4027         aic_outb(p, aic_inb(p, SIMODE1) | ENREQINIT, SIMODE1);
4028
4029        /*
4030         * We don't want the sequencer unpaused yet so we return early
4031         */
4032         return;
4033       }
4034
4035     case REJECT_MSG:
4036       {
4037         /*
4038          * What we care about here is if we had an outstanding SDTR
4039          * or WDTR message for this target. If we did, this is a
4040          * signal that the target is refusing negotiation.
4041          */
4042         unsigned char scb_index;
4043         unsigned char last_msg;
4044
4045         scb_index = aic_inb(p, SCB_TAG);
4046         scb = p->scb_data->scb_array[scb_index];
4047         aic_dev = AIC_DEV(scb->cmd);
4048         last_msg = aic_inb(p, LAST_MSG);
4049
4050         if ( (last_msg == MSG_IDENTIFYFLAG) &&
4051              (scb->tag_action) &&
4052             !(scb->flags & SCB_MSGOUT_BITS) )
4053         {
4054           if (scb->tag_action == MSG_ORDERED_Q_TAG)
4055           {
4056             /*
4057              * OK...the device seems able to accept tagged commands, but
4058              * not ordered tag commands, only simple tag commands.  So, we
4059              * disable ordered tag commands and go on with life just like
4060              * normal.
4061              */
4062             scsi_adjust_queue_depth(scb->cmd->device, MSG_SIMPLE_TAG,
4063                             scb->cmd->device->queue_depth);
4064             scb->tag_action = MSG_SIMPLE_Q_TAG;
4065             scb->hscb->control &= ~SCB_TAG_TYPE;
4066             scb->hscb->control |= MSG_SIMPLE_Q_TAG;
4067             aic_outb(p, scb->hscb->control, SCB_CONTROL);
4068             /*
4069              * OK..we set the tag type to simple tag command, now we re-assert
4070              * ATNO and hope this will take us into the identify phase again
4071              * so we can resend the tag type and info to the device.
4072              */
4073             aic_outb(p, MSG_IDENTIFYFLAG, MSG_OUT);
4074             aic_outb(p, aic_inb(p, SCSISIGI) | ATNO, SCSISIGO);
4075           }
4076           else if (scb->tag_action == MSG_SIMPLE_Q_TAG)
4077           {
4078             unsigned char i;
4079             struct aic7xxx_scb *scbp;
4080             int old_verbose;
4081             /*
4082              * Hmmmm....the device is flaking out on tagged commands.
4083              */
4084             scsi_adjust_queue_depth(scb->cmd->device, 0 /* untagged */,
4085                             p->host->cmd_per_lun);
4086             aic_dev->max_q_depth = aic_dev->temp_q_depth = 1;
4087             /*
4088              * We set this command up as a bus device reset.  However, we have
4089              * to clear the tag type as it's causing us problems.  We shouldnt
4090              * have to worry about any other commands being active, since if
4091              * the device is refusing tagged commands, this should be the
4092              * first tagged command sent to the device, however, we do have
4093              * to worry about any other tagged commands that may already be
4094              * in the qinfifo.  The easiest way to do this, is to issue a BDR,
4095              * send all the commands back to the mid level code, then let them
4096              * come back and get rebuilt as untagged commands.
4097              */
4098             scb->tag_action = 0;
4099             scb->hscb->control &= ~(TAG_ENB | SCB_TAG_TYPE);
4100             aic_outb(p,  scb->hscb->control, SCB_CONTROL);
4101
4102             old_verbose = aic7xxx_verbose;
4103             aic7xxx_verbose &= ~(VERBOSE_RESET|VERBOSE_ABORT);
4104             for (i=0; i < p->scb_data->numscbs; i++)
4105             {
4106               scbp = p->scb_data->scb_array[i];
4107               if ((scbp->flags & SCB_ACTIVE) && (scbp != scb))
4108               {
4109                 if (aic7xxx_match_scb(p, scbp, target, channel, lun, i))
4110                 {
4111                   aic7xxx_reset_device(p, target, channel, lun, i);
4112                 }
4113               }
4114             }
4115             aic7xxx_run_done_queue(p, TRUE);
4116             aic7xxx_verbose = old_verbose;
4117             /*
4118              * Wait until after the for loop to set the busy index since
4119              * aic7xxx_reset_device will clear the busy index during its
4120              * operation.
4121              */
4122             aic7xxx_busy_target(p, scb);
4123             printk(INFO_LEAD "Device is refusing tagged commands, using "
4124               "untagged I/O.\n", p->host_no, channel, target, lun);
4125             aic_outb(p, MSG_IDENTIFYFLAG, MSG_OUT);
4126             aic_outb(p, aic_inb(p, SCSISIGI) | ATNO, SCSISIGO);
4127           }
4128         }
4129         else if (scb->flags & SCB_MSGOUT_PPR)
4130         {
4131           /*
4132            * As per the draft specs, any device capable of supporting any of
4133            * the option values other than 0 are not allowed to reject the
4134            * PPR message.  Instead, they must negotiate out what they do
4135            * support instead of rejecting our offering or else they cause
4136            * a parity error during msg_out phase to signal that they don't
4137            * like our settings.
4138            */
4139           aic_dev->needppr = aic_dev->needppr_copy = 0;
4140           aic7xxx_set_width(p, target, channel, lun, MSG_EXT_WDTR_BUS_8_BIT,
4141             (AHC_TRANS_ACTIVE|AHC_TRANS_CUR|AHC_TRANS_QUITE), aic_dev);
4142           aic7xxx_set_syncrate(p, NULL, target, channel, 0, 0, 0,
4143                                AHC_TRANS_ACTIVE|AHC_TRANS_CUR|AHC_TRANS_QUITE,
4144                                aic_dev);
4145           aic_dev->goal.options = aic_dev->dtr_pending = 0;
4146           scb->flags &= ~SCB_MSGOUT_BITS;
4147           if(aic7xxx_verbose & VERBOSE_NEGOTIATION2)
4148           {
4149             printk(INFO_LEAD "Device is rejecting PPR messages, falling "
4150               "back.\n", p->host_no, channel, target, lun);
4151           }
4152           if ( aic_dev->goal.width )
4153           {
4154             aic_dev->needwdtr = aic_dev->needwdtr_copy = 1;
4155             aic_dev->dtr_pending = 1;
4156             scb->flags |= SCB_MSGOUT_WDTR;
4157           }
4158           if ( aic_dev->goal.offset )
4159           {
4160             aic_dev->needsdtr = aic_dev->needsdtr_copy = 1;
4161             if( !aic_dev->dtr_pending )
4162             {
4163               aic_dev->dtr_pending = 1;
4164               scb->flags |= SCB_MSGOUT_SDTR;
4165             }
4166           }
4167           if ( aic_dev->dtr_pending )
4168           {
4169             aic_outb(p, HOST_MSG, MSG_OUT);
4170             aic_outb(p, aic_inb(p, SCSISIGI) | ATNO, SCSISIGO);
4171           }
4172         }
4173         else if (scb->flags & SCB_MSGOUT_WDTR)
4174         {
4175           /*
4176            * note 8bit xfers and clear flag
4177            */
4178           aic_dev->needwdtr = aic_dev->needwdtr_copy = 0;
4179           scb->flags &= ~SCB_MSGOUT_BITS;
4180           aic7xxx_set_width(p, target, channel, lun, MSG_EXT_WDTR_BUS_8_BIT,
4181             (AHC_TRANS_ACTIVE|AHC_TRANS_GOAL|AHC_TRANS_CUR), aic_dev);
4182           aic7xxx_set_syncrate(p, NULL, target, channel, 0, 0, 0,
4183                                AHC_TRANS_ACTIVE|AHC_TRANS_CUR|AHC_TRANS_QUITE,
4184                                aic_dev);
4185           if(aic7xxx_verbose & VERBOSE_NEGOTIATION2)
4186           {
4187             printk(INFO_LEAD "Device is rejecting WDTR messages, using "
4188               "narrow transfers.\n", p->host_no, channel, target, lun);
4189           }
4190           aic_dev->needsdtr = aic_dev->needsdtr_copy;
4191         }
4192         else if (scb->flags & SCB_MSGOUT_SDTR)
4193         {
4194          /*
4195           * note asynch xfers and clear flag
4196           */
4197           aic_dev->needsdtr = aic_dev->needsdtr_copy = 0;
4198           scb->flags &= ~SCB_MSGOUT_BITS;
4199           aic7xxx_set_syncrate(p, NULL, target, channel, 0, 0, 0,
4200             (AHC_TRANS_CUR|AHC_TRANS_ACTIVE|AHC_TRANS_GOAL), aic_dev);
4201           if(aic7xxx_verbose & VERBOSE_NEGOTIATION2)
4202           {
4203             printk(INFO_LEAD "Device is rejecting SDTR messages, using "
4204               "async transfers.\n", p->host_no, channel, target, lun);
4205           }
4206         }
4207         else if (aic7xxx_verbose & VERBOSE_SEQINT)
4208         {
4209           /*
4210            * Otherwise, we ignore it.
4211            */
4212           printk(INFO_LEAD "Received MESSAGE_REJECT for unknown cause.  "
4213             "Ignoring.\n", p->host_no, channel, target, lun);
4214         }
4215       }
4216       break;
4217
4218     case BAD_STATUS:
4219       {
4220         unsigned char scb_index;
4221         struct aic7xxx_hwscb *hscb;
4222         struct scsi_cmnd *cmd;
4223
4224         /* The sequencer will notify us when a command has an error that
4225          * would be of interest to the kernel.  This allows us to leave
4226          * the sequencer running in the common case of command completes
4227          * without error.  The sequencer will have DMA'd the SCB back
4228          * up to us, so we can reference the drivers SCB array.
4229          *
4230          * Set the default return value to 0 indicating not to send
4231          * sense.  The sense code will change this if needed and this
4232          * reduces code duplication.
4233          */
4234         aic_outb(p, 0, RETURN_1);
4235         scb_index = aic_inb(p, SCB_TAG);
4236         if (scb_index > p->scb_data->numscbs)
4237         {
4238           printk(WARN_LEAD "Invalid SCB during SEQINT 0x%02x, SCB_TAG %d.\n",
4239             p->host_no, channel, target, lun, intstat, scb_index);
4240           break;
4241         }
4242         scb = p->scb_data->scb_array[scb_index];
4243         hscb = scb->hscb;
4244
4245         if (!(scb->flags & SCB_ACTIVE) || (scb->cmd == NULL))
4246         {
4247           printk(WARN_LEAD "Invalid SCB during SEQINT 0x%x, scb %d, flags 0x%x,"
4248             " cmd 0x%lx.\n", p->host_no, channel, target, lun, intstat,
4249             scb_index, scb->flags, (unsigned long) scb->cmd);
4250         }
4251         else
4252         {
4253           cmd = scb->cmd;
4254           aic_dev = AIC_DEV(scb->cmd);
4255           hscb->target_status = aic_inb(p, SCB_TARGET_STATUS);
4256           aic7xxx_status(cmd) = hscb->target_status;
4257
4258           cmd->result = hscb->target_status;
4259
4260           switch (status_byte(hscb->target_status))
4261           {
4262             case GOOD:
4263               if (aic7xxx_verbose & VERBOSE_SEQINT)
4264                 printk(INFO_LEAD "Interrupted for status of GOOD???\n",
4265                   p->host_no, CTL_OF_SCB(scb));
4266               break;
4267
4268             case COMMAND_TERMINATED:
4269             case CHECK_CONDITION:
4270               if ( !(scb->flags & SCB_SENSE) )
4271               {
4272                 /*
4273                  * Send a sense command to the requesting target.
4274                  * XXX - revisit this and get rid of the memcopys.
4275                  */
4276                 memcpy(scb->sense_cmd, &generic_sense[0],
4277                        sizeof(generic_sense));
4278
4279                 scb->sense_cmd[1] = (cmd->device->lun << 5);
4280                 scb->sense_cmd[4] = sizeof(cmd->sense_buffer);
4281
4282                 scb->sg_list[0].length = 
4283                   cpu_to_le32(sizeof(cmd->sense_buffer));
4284                 scb->sg_list[0].address =
4285                         cpu_to_le32(pci_map_single(p->pdev, cmd->sense_buffer,
4286                                                    sizeof(cmd->sense_buffer),
4287                                                    PCI_DMA_FROMDEVICE));
4288
4289                 /*
4290                  * XXX - We should allow disconnection, but can't as it
4291                  * might allow overlapped tagged commands.
4292                  */
4293                 /* hscb->control &= DISCENB; */
4294                 hscb->control = 0;
4295                 hscb->target_status = 0;
4296                 hscb->SG_list_pointer = 
4297                   cpu_to_le32(SCB_DMA_ADDR(scb, scb->sg_list));
4298                 hscb->SCSI_cmd_pointer = 
4299                   cpu_to_le32(SCB_DMA_ADDR(scb, scb->sense_cmd));
4300                 hscb->data_count = scb->sg_list[0].length;
4301                 hscb->data_pointer = scb->sg_list[0].address;
4302                 hscb->SCSI_cmd_length = COMMAND_SIZE(scb->sense_cmd[0]);
4303                 hscb->residual_SG_segment_count = 0;
4304                 hscb->residual_data_count[0] = 0;
4305                 hscb->residual_data_count[1] = 0;
4306                 hscb->residual_data_count[2] = 0;
4307
4308                 scb->sg_count = hscb->SG_segment_count = 1;
4309                 scb->sg_length = sizeof(cmd->sense_buffer);
4310                 scb->tag_action = 0;
4311                 scb->flags |= SCB_SENSE;
4312                 /*
4313                  * Ensure the target is busy since this will be an
4314                  * an untagged request.
4315                  */
4316 #ifdef AIC7XXX_VERBOSE_DEBUGGING
4317                 if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
4318                 {
4319                   if (scb->flags & SCB_MSGOUT_BITS)
4320                     printk(INFO_LEAD "Requesting SENSE with %s\n", p->host_no,
4321                            CTL_OF_SCB(scb), (scb->flags & SCB_MSGOUT_SDTR) ?
4322                            "SDTR" : "WDTR");
4323                   else
4324                     printk(INFO_LEAD "Requesting SENSE, no MSG\n", p->host_no,
4325                            CTL_OF_SCB(scb));
4326                 }
4327 #endif
4328                 aic7xxx_busy_target(p, scb);
4329                 aic_outb(p, SEND_SENSE, RETURN_1);
4330                 aic7xxx_error(cmd) = DID_OK;
4331                 break;
4332               }  /* first time sense, no errors */
4333               printk(INFO_LEAD "CHECK_CONDITION on REQUEST_SENSE, returning "
4334                      "an error.\n", p->host_no, CTL_OF_SCB(scb));
4335               aic7xxx_error(cmd) = DID_ERROR;
4336               scb->flags &= ~SCB_SENSE;
4337               break;
4338
4339             case QUEUE_FULL:
4340               queue_flag = TRUE;    /* Mark that this is a QUEUE_FULL and */
4341             case BUSY:              /* drop through to here */
4342             {
4343               struct aic7xxx_scb *next_scbp, *prev_scbp;
4344               unsigned char active_hscb, next_hscb, prev_hscb, scb_index;
4345               /*
4346                * We have to look three places for queued commands:
4347                *  1: p->waiting_scbs queue
4348                *  2: QINFIFO
4349                *  3: WAITING_SCBS list on card (for commands that are started
4350                *     but haven't yet made it to the device)
4351                *
4352                * Of special note here is that commands on 2 or 3 above will
4353                * have already been marked as active, while commands on 1 will
4354                * not.  The aic7xxx_done() function will want to unmark them
4355                * from active, so any commands we pull off of 1 need to
4356                * up the active count.
4357                */
4358               next_scbp = p->waiting_scbs.head;
4359               while ( next_scbp != NULL )
4360               {
4361                 prev_scbp = next_scbp;
4362                 next_scbp = next_scbp->q_next;
4363                 if ( aic7xxx_match_scb(p, prev_scbp, target, channel, lun,
4364                      SCB_LIST_NULL) )
4365                 {
4366                   scbq_remove(&p->waiting_scbs, prev_scbp);
4367                   scb->flags = SCB_QUEUED_FOR_DONE | SCB_QUEUE_FULL;
4368                   p->activescbs++;
4369                   aic_dev->active_cmds++;
4370                 }
4371               }
4372               aic7xxx_search_qinfifo(p, target, channel, lun,
4373                 SCB_LIST_NULL, SCB_QUEUED_FOR_DONE | SCB_QUEUE_FULL,
4374                 FALSE, NULL);
4375               next_scbp = NULL;
4376               active_hscb = aic_inb(p, SCBPTR);
4377               prev_hscb = next_hscb = scb_index = SCB_LIST_NULL;
4378               next_hscb = aic_inb(p, WAITING_SCBH);
4379               while (next_hscb != SCB_LIST_NULL)
4380               {
4381                 aic_outb(p, next_hscb, SCBPTR);
4382                 scb_index = aic_inb(p, SCB_TAG);
4383                 if (scb_index < p->scb_data->numscbs)
4384                 {
4385                   next_scbp = p->scb_data->scb_array[scb_index];
4386                   if (aic7xxx_match_scb(p, next_scbp, target, channel, lun,
4387                       SCB_LIST_NULL) )
4388                   {
4389                     next_scbp->flags = SCB_QUEUED_FOR_DONE | SCB_QUEUE_FULL;
4390                     next_hscb = aic_inb(p, SCB_NEXT);
4391                     aic_outb(p, 0, SCB_CONTROL);
4392                     aic_outb(p, SCB_LIST_NULL, SCB_TAG);
4393                     aic7xxx_add_curscb_to_free_list(p);
4394                     if (prev_hscb == SCB_LIST_NULL)
4395                     {
4396                       /* We were first on the list,
4397                        * so we kill the selection
4398                        * hardware.  Let the sequencer
4399                        * re-init the hardware itself
4400                        */
4401                       aic_outb(p, aic_inb(p, SCSISEQ) & ~ENSELO, SCSISEQ);
4402                       aic_outb(p, CLRSELTIMEO, CLRSINT1);
4403                       aic_outb(p, next_hscb, WAITING_SCBH);
4404                     }
4405                     else
4406                     {
4407                       aic_outb(p, prev_hscb, SCBPTR);
4408                       aic_outb(p, next_hscb, SCB_NEXT);
4409                     }
4410                   }
4411                   else
4412                   {
4413                     prev_hscb = next_hscb;
4414                     next_hscb = aic_inb(p, SCB_NEXT);
4415                   }
4416                 } /* scb_index >= p->scb_data->numscbs */
4417               }
4418               aic_outb(p, active_hscb, SCBPTR);
4419               aic7xxx_run_done_queue(p, FALSE);
4420                   
4421 #ifdef AIC7XXX_VERBOSE_DEBUGGING
4422               if( (aic7xxx_verbose & VERBOSE_MINOR_ERROR) ||
4423                   (aic7xxx_verbose > 0xffff) )
4424               {
4425                 if (queue_flag)
4426                   printk(INFO_LEAD "Queue full received; queue depth %d, "
4427                     "active %d\n", p->host_no, CTL_OF_SCB(scb),
4428                     aic_dev->max_q_depth, aic_dev->active_cmds);
4429                 else
4430                   printk(INFO_LEAD "Target busy\n", p->host_no, CTL_OF_SCB(scb));
4431               }
4432 #endif
4433               if (queue_flag)
4434               {
4435                 int diff;
4436                 result = scsi_track_queue_full(cmd->device,
4437                                 aic_dev->active_cmds);
4438                 if ( result < 0 )
4439                 {
4440                   if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
4441                     printk(INFO_LEAD "Tagged Command Queueing disabled.\n",
4442                         p->host_no, CTL_OF_SCB(scb));
4443                   diff = aic_dev->max_q_depth - p->host->cmd_per_lun;
4444                   aic_dev->temp_q_depth = 1;
4445                   aic_dev->max_q_depth = 1;
4446                 }
4447                 else if ( result > 0 )
4448                 {
4449                   if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
4450                     printk(INFO_LEAD "Queue depth reduced to %d\n", p->host_no,
4451                       CTL_OF_SCB(scb), result);
4452                   diff = aic_dev->max_q_depth - result;
4453                   aic_dev->max_q_depth = result;
4454                   /* temp_q_depth could have been dropped to 1 for an untagged
4455                    * command that might be coming up */
4456                   if(aic_dev->temp_q_depth > result)
4457                     aic_dev->temp_q_depth = result;
4458                 }
4459                 /* We should free up the no unused SCB entries.  But, that's
4460                  * a difficult thing to do because we use a direct indexed
4461                  * array, so we can't just take any entries and free them,
4462                  * we *have* to free the ones at the end of the array, and
4463                  * they very well could be in use right now, which means
4464                  * in order to do this right, we have to add a delayed
4465                  * freeing mechanism tied into the scb_free() code area.
4466                  * We'll add that later.
4467                  */
4468               }
4469               break;
4470             }
4471             
4472             default:
4473               if (aic7xxx_verbose & VERBOSE_SEQINT)
4474                 printk(INFO_LEAD "Unexpected target status 0x%x.\n", p->host_no,
4475                      CTL_OF_SCB(scb), scb->hscb->target_status);
4476               if (!aic7xxx_error(cmd))
4477               {
4478                 aic7xxx_error(cmd) = DID_RETRY_COMMAND;
4479               }
4480               break;
4481           }  /* end switch */
4482         }  /* end else of */
4483       }
4484       break;
4485
4486     case AWAITING_MSG:
4487       {
4488         unsigned char scb_index, msg_out;
4489
4490         scb_index = aic_inb(p, SCB_TAG);
4491         msg_out = aic_inb(p, MSG_OUT);
4492         scb = p->scb_data->scb_array[scb_index];
4493         aic_dev = AIC_DEV(scb->cmd);
4494         p->msg_index = p->msg_len = 0;
4495         /*
4496          * This SCB had a MK_MESSAGE set in its control byte informing
4497          * the sequencer that we wanted to send a special message to
4498          * this target.
4499          */
4500
4501         if ( !(scb->flags & SCB_DEVICE_RESET) &&
4502               (msg_out == MSG_IDENTIFYFLAG) &&
4503               (scb->hscb->control & TAG_ENB) )
4504         {
4505           p->msg_buf[p->msg_index++] = scb->tag_action;
4506           p->msg_buf[p->msg_index++] = scb->hscb->tag;
4507           p->msg_len += 2;
4508         }
4509
4510         if (scb->flags & SCB_DEVICE_RESET)
4511         {
4512           p->msg_buf[p->msg_index++] = MSG_BUS_DEV_RESET;
4513           p->msg_len++;
4514           if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
4515             printk(INFO_LEAD "Bus device reset mailed.\n",
4516                  p->host_no, CTL_OF_SCB(scb));
4517         }
4518         else if (scb->flags & SCB_ABORT)
4519         {
4520           if (scb->tag_action)
4521           {
4522             p->msg_buf[p->msg_index++] = MSG_ABORT_TAG;
4523           }
4524           else
4525           {
4526             p->msg_buf[p->msg_index++] = MSG_ABORT;
4527           }
4528           p->msg_len++;
4529           if (aic7xxx_verbose & VERBOSE_ABORT_PROCESS)
4530             printk(INFO_LEAD "Abort message mailed.\n", p->host_no,
4531               CTL_OF_SCB(scb));
4532         }
4533         else if (scb->flags & SCB_MSGOUT_PPR)
4534         {
4535           if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
4536           {
4537             printk(INFO_LEAD "Sending PPR (%d/%d/%d/%d) message.\n",
4538                    p->host_no, CTL_OF_SCB(scb),
4539                    aic_dev->goal.period,
4540                    aic_dev->goal.offset,
4541                    aic_dev->goal.width,
4542                    aic_dev->goal.options);
4543           }
4544           aic7xxx_construct_ppr(p, scb);
4545         }
4546         else if (scb->flags & SCB_MSGOUT_WDTR)
4547         {
4548           if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
4549           {
4550             printk(INFO_LEAD "Sending WDTR message.\n", p->host_no,
4551                    CTL_OF_SCB(scb));
4552           }
4553           aic7xxx_construct_wdtr(p, aic_dev->goal.width);
4554         }
4555         else if (scb->flags & SCB_MSGOUT_SDTR)
4556         {
4557           unsigned int max_sync, period;
4558           unsigned char options = 0;
4559           /*
4560            * Now that the device is selected, use the bits in SBLKCTL and
4561            * SSTAT2 to determine the max sync rate for this device.
4562            */
4563           if (p->features & AHC_ULTRA2)
4564           {
4565             if ( (aic_inb(p, SBLKCTL) & ENAB40) &&
4566                 !(aic_inb(p, SSTAT2) & EXP_ACTIVE) )
4567             {
4568               max_sync = AHC_SYNCRATE_ULTRA2;
4569             }
4570             else
4571             {
4572               max_sync = AHC_SYNCRATE_ULTRA;
4573             }
4574           }
4575           else if (p->features & AHC_ULTRA)
4576           {
4577             max_sync = AHC_SYNCRATE_ULTRA;
4578           }
4579           else
4580           {
4581             max_sync = AHC_SYNCRATE_FAST;
4582           }
4583           period = aic_dev->goal.period;
4584           aic7xxx_find_syncrate(p, &period, max_sync, &options);
4585           if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
4586           {
4587             printk(INFO_LEAD "Sending SDTR %d/%d message.\n", p->host_no,
4588                    CTL_OF_SCB(scb), period,
4589                    aic_dev->goal.offset);
4590           }
4591           aic7xxx_construct_sdtr(p, period, aic_dev->goal.offset);
4592         }
4593         else 
4594         {
4595           panic("aic7xxx: AWAITING_MSG for an SCB that does "
4596                 "not have a waiting message.\n");
4597         }
4598         /*
4599          * We've set everything up to send our message, now to actually do
4600          * so we need to enable reqinit interrupts and let the interrupt
4601          * handler do the rest.  We don't want to unpause the sequencer yet
4602          * though so we'll return early.  We also have to make sure that
4603          * we clear the SEQINT *BEFORE* we set the REQINIT handler active
4604          * or else it's possible on VLB cards to lose the first REQINIT
4605          * interrupt.  Edge triggered EISA cards could also lose this
4606          * interrupt, although PCI and level triggered cards should not
4607          * have this problem since they continually interrupt the kernel
4608          * until we take care of the situation.
4609          */
4610         scb->flags |= SCB_MSGOUT_SENT;
4611         p->msg_index = 0;
4612         p->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
4613         p->flags |= AHC_HANDLING_REQINITS;
4614         aic_outb(p, aic_inb(p, SIMODE1) | ENREQINIT, SIMODE1);
4615         return;
4616       }
4617       break;
4618
4619     case DATA_OVERRUN:
4620       {
4621         unsigned char scb_index = aic_inb(p, SCB_TAG);
4622         unsigned char lastphase = aic_inb(p, LASTPHASE);
4623         unsigned int i;
4624
4625         scb = (p->scb_data->scb_array[scb_index]);
4626         /*
4627          * XXX - What do we really want to do on an overrun?  The
4628          *       mid-level SCSI code should handle this, but for now,
4629          *       we'll just indicate that the command should retried.
4630          *    If we retrieved sense info on this target, then the 
4631          *    base SENSE info should have been saved prior to the
4632          *    overrun error.  In that case, we return DID_OK and let
4633          *    the mid level code pick up on the sense info.  Otherwise
4634          *    we return DID_ERROR so the command will get retried.
4635          */
4636         if ( !(scb->flags & SCB_SENSE) )
4637         {
4638           printk(WARN_LEAD "Data overrun detected in %s phase, tag %d;\n",
4639             p->host_no, CTL_OF_SCB(scb), 
4640             (lastphase == P_DATAIN) ? "Data-In" : "Data-Out", scb->hscb->tag);
4641           printk(KERN_WARNING "  %s seen Data Phase. Length=%d, NumSGs=%d.\n",
4642             (aic_inb(p, SEQ_FLAGS) & DPHASE) ? "Have" : "Haven't",
4643             scb->sg_length, scb->sg_count);
4644           printk(KERN_WARNING "  Raw SCSI Command: 0x");
4645           for (i = 0; i < scb->hscb->SCSI_cmd_length; i++)
4646           {
4647             printk("%02x ", scb->cmd->cmnd[i]);
4648           }
4649           printk("\n");
4650           if(aic7xxx_verbose > 0xffff)
4651           {
4652             for (i = 0; i < scb->sg_count; i++)
4653             {
4654               printk(KERN_WARNING "     sg[%d] - Addr 0x%x : Length %d\n",
4655                  i, 
4656                  le32_to_cpu(scb->sg_list[i].address),
4657                  le32_to_cpu(scb->sg_list[i].length) );
4658             }
4659           }
4660           aic7xxx_error(scb->cmd) = DID_ERROR;
4661         }
4662         else
4663           printk(INFO_LEAD "Data Overrun during SEND_SENSE operation.\n",
4664             p->host_no, CTL_OF_SCB(scb));
4665       }
4666       break;
4667
4668     case WIDE_RESIDUE:
4669       {
4670         unsigned char resid_sgcnt, index;
4671         unsigned char scb_index = aic_inb(p, SCB_TAG);
4672         unsigned int cur_addr, resid_dcnt;
4673         unsigned int native_addr, native_length, sg_addr;
4674         int i;
4675
4676         if(scb_index > p->scb_data->numscbs)
4677         {
4678           printk(WARN_LEAD "invalid scb_index during WIDE_RESIDUE.\n",
4679             p->host_no, -1, -1, -1);
4680           /*
4681            * XXX: Add error handling here
4682            */
4683           break;
4684         }
4685         scb = p->scb_data->scb_array[scb_index];
4686         if(!(scb->flags & SCB_ACTIVE) || (scb->cmd == NULL))
4687         {
4688           printk(WARN_LEAD "invalid scb during WIDE_RESIDUE flags:0x%x "
4689                  "scb->cmd:0x%lx\n", p->host_no, CTL_OF_SCB(scb),
4690                  scb->flags, (unsigned long)scb->cmd);
4691           break;
4692         }
4693         if(aic7xxx_verbose & VERBOSE_MINOR_ERROR)
4694           printk(INFO_LEAD "Got WIDE_RESIDUE message, patching up data "
4695                  "pointer.\n", p->host_no, CTL_OF_SCB(scb));
4696
4697         /*
4698          * We have a valid scb to use on this WIDE_RESIDUE message, so
4699          * we need to walk the sg list looking for this particular sg
4700          * segment, then see if we happen to be at the very beginning of
4701          * the segment.  If we are, then we have to back things up to
4702          * the previous segment.  If not, then we simply need to remove
4703          * one byte from this segments address and add one to the byte
4704          * count.
4705          */
4706         cur_addr = aic_inb(p, SHADDR) | (aic_inb(p, SHADDR + 1) << 8) |
4707           (aic_inb(p, SHADDR + 2) << 16) | (aic_inb(p, SHADDR + 3) << 24);
4708         sg_addr = aic_inb(p, SG_COUNT + 1) | (aic_inb(p, SG_COUNT + 2) << 8) |
4709           (aic_inb(p, SG_COUNT + 3) << 16) | (aic_inb(p, SG_COUNT + 4) << 24);
4710         resid_sgcnt = aic_inb(p, SCB_RESID_SGCNT);
4711         resid_dcnt = aic_inb(p, SCB_RESID_DCNT) |
4712           (aic_inb(p, SCB_RESID_DCNT + 1) << 8) |
4713           (aic_inb(p, SCB_RESID_DCNT + 2) << 16);
4714         index = scb->sg_count - ((resid_sgcnt) ? resid_sgcnt : 1);
4715         native_addr = le32_to_cpu(scb->sg_list[index].address);
4716         native_length = le32_to_cpu(scb->sg_list[index].length);
4717         /*
4718          * If resid_dcnt == native_length, then we just loaded this SG
4719          * segment and we need to back it up one...
4720          */
4721         if(resid_dcnt == native_length)
4722         {
4723           if(index == 0)
4724           {
4725             /*
4726              * Oops, this isn't right, we can't back up to before the
4727              * beginning.  This must be a bogus message, ignore it.
4728              */
4729             break;
4730           }
4731           resid_dcnt = 1;
4732           resid_sgcnt += 1;
4733           native_addr = le32_to_cpu(scb->sg_list[index - 1].address);
4734           native_length = le32_to_cpu(scb->sg_list[index - 1].length);
4735           cur_addr = native_addr + (native_length - 1);
4736           sg_addr -= sizeof(struct hw_scatterlist);
4737         }
4738         else
4739         {
4740           /*
4741            * resid_dcnt != native_length, so we are in the middle of a SG
4742            * element.  Back it up one byte and leave the rest alone.
4743            */
4744           resid_dcnt += 1;
4745           cur_addr -= 1;
4746         }
4747         
4748         /*
4749          * Output the new addresses and counts to the right places on the
4750          * card.
4751          */
4752         aic_outb(p, resid_sgcnt, SG_COUNT);
4753         aic_outb(p, resid_sgcnt, SCB_RESID_SGCNT);
4754         aic_outb(p, sg_addr & 0xff, SG_COUNT + 1);
4755         aic_outb(p, (sg_addr >> 8) & 0xff, SG_COUNT + 2);
4756         aic_outb(p, (sg_addr >> 16) & 0xff, SG_COUNT + 3);
4757         aic_outb(p, (sg_addr >> 24) & 0xff, SG_COUNT + 4);
4758         aic_outb(p, resid_dcnt & 0xff, SCB_RESID_DCNT);
4759         aic_outb(p, (resid_dcnt >> 8) & 0xff, SCB_RESID_DCNT + 1);
4760         aic_outb(p, (resid_dcnt >> 16) & 0xff, SCB_RESID_DCNT + 2);
4761
4762         /*
4763          * The sequencer actually wants to find the new address
4764          * in the SHADDR register set.  On the Ultra2 and later controllers
4765          * this register set is readonly.  In order to get the right number
4766          * into the register, you actually have to enter it in HADDR and then
4767          * use the PRELOADEN bit of DFCNTRL to drop it through from the
4768          * HADDR register to the SHADDR register.  On non-Ultra2 controllers,
4769          * we simply write it direct.
4770          */
4771         if(p->features & AHC_ULTRA2)
4772         {
4773           /*
4774            * We might as well be accurate and drop both the resid_dcnt and
4775            * cur_addr into HCNT and HADDR and have both of them drop
4776            * through to the shadow layer together.
4777            */
4778           aic_outb(p, resid_dcnt & 0xff, HCNT);
4779           aic_outb(p, (resid_dcnt >> 8) & 0xff, HCNT + 1);
4780           aic_outb(p, (resid_dcnt >> 16) & 0xff, HCNT + 2);
4781           aic_outb(p, cur_addr & 0xff, HADDR);
4782           aic_outb(p, (cur_addr >> 8) & 0xff, HADDR + 1);
4783           aic_outb(p, (cur_addr >> 16) & 0xff, HADDR + 2);
4784           aic_outb(p, (cur_addr >> 24) & 0xff, HADDR + 3);
4785           aic_outb(p, aic_inb(p, DMAPARAMS) | PRELOADEN, DFCNTRL);
4786           udelay(1);
4787           aic_outb(p, aic_inb(p, DMAPARAMS) & ~(SCSIEN|HDMAEN), DFCNTRL);
4788           i=0;
4789           while(((aic_inb(p, DFCNTRL) & (SCSIEN|HDMAEN)) != 0) && (i++ < 1000))
4790           {
4791             udelay(1);
4792           }
4793         }
4794         else
4795         {
4796           aic_outb(p, cur_addr & 0xff, SHADDR);
4797           aic_outb(p, (cur_addr >> 8) & 0xff, SHADDR + 1);
4798           aic_outb(p, (cur_addr >> 16) & 0xff, SHADDR + 2);
4799           aic_outb(p, (cur_addr >> 24) & 0xff, SHADDR + 3);
4800         }
4801       }
4802       break;
4803
4804     case SEQ_SG_FIXUP:
4805     {
4806       unsigned char scb_index, tmp;
4807       int sg_addr, sg_length;
4808
4809       scb_index = aic_inb(p, SCB_TAG);
4810
4811       if(scb_index > p->scb_data->numscbs)
4812       {
4813         printk(WARN_LEAD "invalid scb_index during SEQ_SG_FIXUP.\n",
4814           p->host_no, -1, -1, -1);
4815         printk(INFO_LEAD "SCSISIGI 0x%x, SEQADDR 0x%x, SSTAT0 0x%x, SSTAT1 "
4816            "0x%x\n", p->host_no, -1, -1, -1,
4817            aic_inb(p, SCSISIGI),
4818            aic_inb(p, SEQADDR0) | (aic_inb(p, SEQADDR1) << 8),
4819            aic_inb(p, SSTAT0), aic_inb(p, SSTAT1));
4820         printk(INFO_LEAD "SG_CACHEPTR 0x%x, SSTAT2 0x%x, STCNT 0x%x\n",
4821            p->host_no, -1, -1, -1, aic_inb(p, SG_CACHEPTR),
4822            aic_inb(p, SSTAT2), aic_inb(p, STCNT + 2) << 16 |
4823            aic_inb(p, STCNT + 1) << 8 | aic_inb(p, STCNT));
4824         /*
4825          * XXX: Add error handling here
4826          */
4827         break;
4828       }
4829       scb = p->scb_data->scb_array[scb_index];
4830       if(!(scb->flags & SCB_ACTIVE) || (scb->cmd == NULL))
4831       {
4832         printk(WARN_LEAD "invalid scb during SEQ_SG_FIXUP flags:0x%x "
4833                "scb->cmd:0x%p\n", p->host_no, CTL_OF_SCB(scb),
4834                scb->flags, scb->cmd);
4835         printk(INFO_LEAD "SCSISIGI 0x%x, SEQADDR 0x%x, SSTAT0 0x%x, SSTAT1 "
4836            "0x%x\n", p->host_no, CTL_OF_SCB(scb),
4837            aic_inb(p, SCSISIGI),
4838            aic_inb(p, SEQADDR0) | (aic_inb(p, SEQADDR1) << 8),
4839            aic_inb(p, SSTAT0), aic_inb(p, SSTAT1));
4840         printk(INFO_LEAD "SG_CACHEPTR 0x%x, SSTAT2 0x%x, STCNT 0x%x\n",
4841            p->host_no, CTL_OF_SCB(scb), aic_inb(p, SG_CACHEPTR),
4842            aic_inb(p, SSTAT2), aic_inb(p, STCNT + 2) << 16 |
4843            aic_inb(p, STCNT + 1) << 8 | aic_inb(p, STCNT));
4844         break;
4845       }
4846       if(aic7xxx_verbose & VERBOSE_MINOR_ERROR)
4847         printk(INFO_LEAD "Fixing up SG address for sequencer.\n", p->host_no,
4848                CTL_OF_SCB(scb));
4849       /*
4850        * Advance the SG pointer to the next element in the list
4851        */
4852       tmp = aic_inb(p, SG_NEXT);
4853       tmp += SG_SIZEOF;
4854       aic_outb(p, tmp, SG_NEXT);
4855       if( tmp < SG_SIZEOF )
4856         aic_outb(p, aic_inb(p, SG_NEXT + 1) + 1, SG_NEXT + 1);
4857       tmp = aic_inb(p, SG_COUNT) - 1;
4858       aic_outb(p, tmp, SG_COUNT);
4859       sg_addr = le32_to_cpu(scb->sg_list[scb->sg_count - tmp].address);
4860       sg_length = le32_to_cpu(scb->sg_list[scb->sg_count - tmp].length);
4861       /*
4862        * Now stuff the element we just advanced past down onto the
4863        * card so it can be stored in the residual area.
4864        */
4865       aic_outb(p, sg_addr & 0xff, HADDR);
4866       aic_outb(p, (sg_addr >> 8) & 0xff, HADDR + 1);
4867       aic_outb(p, (sg_addr >> 16) & 0xff, HADDR + 2);
4868       aic_outb(p, (sg_addr >> 24) & 0xff, HADDR + 3);
4869       aic_outb(p, sg_length & 0xff, HCNT);
4870       aic_outb(p, (sg_length >> 8) & 0xff, HCNT + 1);
4871       aic_outb(p, (sg_length >> 16) & 0xff, HCNT + 2);
4872       aic_outb(p, (tmp << 2) | ((tmp == 1) ? LAST_SEG : 0), SG_CACHEPTR);
4873       aic_outb(p, aic_inb(p, DMAPARAMS), DFCNTRL);
4874       while(aic_inb(p, SSTAT0) & SDONE) udelay(1);
4875       while(aic_inb(p, DFCNTRL) & (HDMAEN|SCSIEN)) aic_outb(p, 0, DFCNTRL);
4876     }
4877     break;
4878
4879 #ifdef AIC7XXX_NOT_YET 
4880     case TRACEPOINT2:
4881       {
4882         printk(INFO_LEAD "Tracepoint #2 reached.\n", p->host_no,
4883                channel, target, lun);
4884       }
4885       break;
4886
4887     /* XXX Fill these in later */
4888     case MSG_BUFFER_BUSY:
4889       printk("aic7xxx: Message buffer busy.\n");
4890       break;
4891     case MSGIN_PHASEMIS:
4892       printk("aic7xxx: Message-in phasemis.\n");
4893       break;
4894 #endif
4895
4896     default:                   /* unknown */
4897       printk(WARN_LEAD "Unknown SEQINT, INTSTAT 0x%x, SCSISIGI 0x%x.\n",
4898              p->host_no, channel, target, lun, intstat,
4899              aic_inb(p, SCSISIGI));
4900       break;
4901   }
4902
4903   /*
4904    * Clear the sequencer interrupt and unpause the sequencer.
4905    */
4906   unpause_sequencer(p, /* unpause always */ TRUE);
4907 }
4908
4909 /*+F*************************************************************************
4910  * Function:
4911  *   aic7xxx_parse_msg
4912  *
4913  * Description:
4914  *   Parses incoming messages into actions on behalf of
4915  *   aic7xxx_handle_reqinit
4916  *_F*************************************************************************/
4917 static int
4918 aic7xxx_parse_msg(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
4919 {
4920   int reject, reply, done;
4921   unsigned char target_scsirate, tindex;
4922   unsigned short target_mask;
4923   unsigned char target, channel, lun;
4924   unsigned char bus_width, new_bus_width;
4925   unsigned char trans_options, new_trans_options;
4926   unsigned int period, new_period, offset, new_offset, maxsync;
4927   struct aic7xxx_syncrate *syncrate;
4928   struct aic_dev_data *aic_dev;
4929
4930   target = scb->cmd->device->id;
4931   channel = scb->cmd->device->channel;
4932   lun = scb->cmd->device->lun;
4933   reply = reject = done = FALSE;
4934   tindex = TARGET_INDEX(scb->cmd);
4935   aic_dev = AIC_DEV(scb->cmd);
4936   target_scsirate = aic_inb(p, TARG_SCSIRATE + tindex);
4937   target_mask = (0x01 << tindex);
4938
4939   /*
4940    * Parse as much of the message as is available,
4941    * rejecting it if we don't support it.  When
4942    * the entire message is available and has been
4943    * handled, return TRUE indicating that we have
4944    * parsed an entire message.
4945    */
4946
4947   if (p->msg_buf[0] != MSG_EXTENDED)
4948   {
4949     reject = TRUE;
4950   }
4951
4952   /*
4953    * Even if we are an Ultra3 card, don't allow Ultra3 sync rates when
4954    * using the SDTR messages.  We need the PPR messages to enable the
4955    * higher speeds that include things like Dual Edge clocking.
4956    */
4957   if (p->features & AHC_ULTRA2)
4958   {
4959     if ( (aic_inb(p, SBLKCTL) & ENAB40) &&
4960          !(aic_inb(p, SSTAT2) & EXP_ACTIVE) )
4961     {
4962       if (p->features & AHC_ULTRA3)
4963         maxsync = AHC_SYNCRATE_ULTRA3;
4964       else
4965         maxsync = AHC_SYNCRATE_ULTRA2;
4966     }
4967     else
4968     {
4969       maxsync = AHC_SYNCRATE_ULTRA;
4970     }
4971   }
4972   else if (p->features & AHC_ULTRA)
4973   {
4974     maxsync = AHC_SYNCRATE_ULTRA;
4975   }
4976   else
4977   {
4978     maxsync = AHC_SYNCRATE_FAST;
4979   }
4980
4981   /*
4982    * Just accept the length byte outright and perform
4983    * more checking once we know the message type.
4984    */
4985
4986   if ( !reject && (p->msg_len > 2) )
4987   {
4988     switch(p->msg_buf[2])
4989     {
4990       case MSG_EXT_SDTR:
4991       {
4992         
4993         if (p->msg_buf[1] != MSG_EXT_SDTR_LEN)
4994         {
4995           reject = TRUE;
4996           break;
4997         }
4998
4999         if (p->msg_len < (MSG_EXT_SDTR_LEN + 2))
5000         {
5001           break;
5002         }
5003
5004         period = new_period = p->msg_buf[3];
5005         offset = new_offset = p->msg_buf[4];
5006         trans_options = new_trans_options = 0;
5007         bus_width = new_bus_width = target_scsirate & WIDEXFER;
5008
5009         /*
5010          * If our current max syncrate is in the Ultra3 range, bump it back
5011          * down to Ultra2 since we can't negotiate DT transfers using SDTR
5012          */
5013         if(maxsync == AHC_SYNCRATE_ULTRA3)
5014           maxsync = AHC_SYNCRATE_ULTRA2;
5015
5016         /*
5017          * We might have a device that is starting negotiation with us
5018          * before we can start up negotiation with it....be prepared to
5019          * have a device ask for a higher speed then we want to give it
5020          * in that case
5021          */
5022         if ( (scb->flags & (SCB_MSGOUT_SENT|SCB_MSGOUT_SDTR)) !=
5023              (SCB_MSGOUT_SENT|SCB_MSGOUT_SDTR) )
5024         {
5025           if (!(aic_dev->flags & DEVICE_DTR_SCANNED))
5026           {
5027             /*
5028              * We shouldn't get here unless this is a narrow drive, wide
5029              * devices should trigger this same section of code in the WDTR
5030              * handler first instead.
5031              */
5032             aic_dev->goal.width = MSG_EXT_WDTR_BUS_8_BIT;
5033             aic_dev->goal.options = 0;
5034             if(p->user[tindex].offset)
5035             {
5036               aic_dev->needsdtr_copy = 1;
5037               aic_dev->goal.period = max_t(unsigned char, 10,p->user[tindex].period);
5038               if(p->features & AHC_ULTRA2)
5039               {
5040                 aic_dev->goal.offset = MAX_OFFSET_ULTRA2;
5041               }
5042               else
5043               {
5044                 aic_dev->goal.offset = MAX_OFFSET_8BIT;
5045               }
5046             }
5047             else
5048             {
5049               aic_dev->needsdtr_copy = 0;
5050               aic_dev->goal.period = 255;
5051               aic_dev->goal.offset = 0;
5052             }
5053             aic_dev->flags |= DEVICE_DTR_SCANNED | DEVICE_PRINT_DTR;
5054           }
5055           else if (aic_dev->needsdtr_copy == 0)
5056           {
5057             /*
5058              * This is a preemptive message from the target, we've already
5059              * scanned this target and set our options for it, and we
5060              * don't need a SDTR with this target (for whatever reason),
5061              * so reject this incoming SDTR
5062              */
5063             reject = TRUE;
5064             break;
5065           }
5066
5067           /* The device is sending this message first and we have to reply */
5068           reply = TRUE;
5069           
5070           if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
5071           {
5072             printk(INFO_LEAD "Received pre-emptive SDTR message from "
5073                    "target.\n", p->host_no, CTL_OF_SCB(scb));
5074           }
5075           /*
5076            * Validate the values the device passed to us against our SEEPROM
5077            * settings.  We don't have to do this if we aren't replying since
5078            * the device isn't allowed to send values greater than the ones
5079            * we first sent to it.
5080            */
5081           new_period = max_t(unsigned int, period, aic_dev->goal.period);
5082           new_offset = min_t(unsigned int, offset, aic_dev->goal.offset);
5083         }
5084  
5085         /*
5086          * Use our new_period, new_offset, bus_width, and card options
5087          * to determine the actual syncrate settings
5088          */
5089         syncrate = aic7xxx_find_syncrate(p, &new_period, maxsync,
5090                                          &trans_options);
5091         aic7xxx_validate_offset(p, syncrate, &new_offset, bus_width);
5092
5093         /*
5094          * Did we drop to async?  If so, send a reply regardless of whether
5095          * or not we initiated this negotiation.
5096          */
5097         if ((new_offset == 0) && (new_offset != offset))
5098         {
5099           aic_dev->needsdtr_copy = 0;
5100           reply = TRUE;
5101         }
5102         
5103         /*
5104          * Did we start this, if not, or if we went too low and had to
5105          * go async, then send an SDTR back to the target
5106          */
5107         if(reply)
5108         {
5109           /* when sending a reply, make sure that the goal settings are
5110            * updated along with current and active since the code that
5111            * will actually build the message for the sequencer uses the
5112            * goal settings as its guidelines.
5113            */
5114           aic7xxx_set_syncrate(p, syncrate, target, channel, new_period,
5115                                new_offset, trans_options,
5116                                AHC_TRANS_GOAL|AHC_TRANS_ACTIVE|AHC_TRANS_CUR,
5117                                aic_dev);
5118           scb->flags &= ~SCB_MSGOUT_BITS;
5119           scb->flags |= SCB_MSGOUT_SDTR;
5120           aic_outb(p, HOST_MSG, MSG_OUT);
5121           aic_outb(p, aic_inb(p, SCSISIGO) | ATNO, SCSISIGO);
5122         }
5123         else
5124         {
5125           aic7xxx_set_syncrate(p, syncrate, target, channel, new_period,
5126                                new_offset, trans_options,
5127                                AHC_TRANS_ACTIVE|AHC_TRANS_CUR, aic_dev);
5128           aic_dev->needsdtr = 0;
5129         }
5130         done = TRUE;
5131         break;
5132       }
5133       case MSG_EXT_WDTR:
5134       {
5135           
5136         if (p->msg_buf[1] != MSG_EXT_WDTR_LEN)
5137         {
5138           reject = TRUE;
5139           break;
5140         }
5141
5142         if (p->msg_len < (MSG_EXT_WDTR_LEN + 2))
5143         {
5144           break;
5145         }
5146
5147         bus_width = new_bus_width = p->msg_buf[3];
5148
5149         if ( (scb->flags & (SCB_MSGOUT_SENT|SCB_MSGOUT_WDTR)) ==
5150              (SCB_MSGOUT_SENT|SCB_MSGOUT_WDTR) )
5151         {
5152           switch(bus_width)
5153           {
5154             default:
5155             {
5156               reject = TRUE;
5157               if ( (aic7xxx_verbose & VERBOSE_NEGOTIATION2) &&
5158                    ((aic_dev->flags & DEVICE_PRINT_DTR) ||
5159                     (aic7xxx_verbose > 0xffff)) )
5160               {
5161                 printk(INFO_LEAD "Requesting %d bit transfers, rejecting.\n",
5162                   p->host_no, CTL_OF_SCB(scb), 8 * (0x01 << bus_width));
5163               }
5164             } /* We fall through on purpose */
5165             case MSG_EXT_WDTR_BUS_8_BIT:
5166             {
5167               aic_dev->goal.width = MSG_EXT_WDTR_BUS_8_BIT;
5168               aic_dev->needwdtr_copy &= ~target_mask;
5169               break;
5170             }
5171             case MSG_EXT_WDTR_BUS_16_BIT:
5172             {
5173               break;
5174             }
5175           }
5176           aic_dev->needwdtr = 0;
5177           aic7xxx_set_width(p, target, channel, lun, new_bus_width,
5178                             AHC_TRANS_ACTIVE|AHC_TRANS_CUR, aic_dev);
5179         }
5180         else
5181         {
5182           if ( !(aic_dev->flags & DEVICE_DTR_SCANNED) )
5183           {
5184             /* 
5185              * Well, we now know the WDTR and SYNC caps of this device since
5186              * it contacted us first, mark it as such and copy the user stuff
5187              * over to the goal stuff.
5188              */
5189             if( (p->features & AHC_WIDE) && p->user[tindex].width )
5190             {
5191               aic_dev->goal.width = MSG_EXT_WDTR_BUS_16_BIT;
5192               aic_dev->needwdtr_copy = 1;
5193             }
5194             
5195             /*
5196              * Devices that support DT transfers don't start WDTR requests
5197              */
5198             aic_dev->goal.options = 0;
5199
5200             if(p->user[tindex].offset)
5201             {
5202               aic_dev->needsdtr_copy = 1;
5203               aic_dev->goal.period = max_t(unsigned char, 10, p->user[tindex].period);
5204               if(p->features & AHC_ULTRA2)
5205               {
5206                 aic_dev->goal.offset = MAX_OFFSET_ULTRA2;
5207               }
5208               else if( aic_dev->goal.width )
5209               {
5210                 aic_dev->goal.offset = MAX_OFFSET_16BIT;
5211               }
5212               else
5213               {
5214                 aic_dev->goal.offset = MAX_OFFSET_8BIT;
5215               }
5216             } else {
5217               aic_dev->needsdtr_copy = 0;
5218               aic_dev->goal.period = 255;
5219               aic_dev->goal.offset = 0;
5220             }
5221             
5222             aic_dev->flags |= DEVICE_DTR_SCANNED | DEVICE_PRINT_DTR;
5223           }
5224           else if (aic_dev->needwdtr_copy == 0)
5225           {
5226             /*
5227              * This is a preemptive message from the target, we've already
5228              * scanned this target and set our options for it, and we
5229              * don't need a WDTR with this target (for whatever reason),
5230              * so reject this incoming WDTR
5231              */
5232             reject = TRUE;
5233             break;
5234           }
5235
5236           /* The device is sending this message first and we have to reply */
5237           reply = TRUE;
5238
5239           if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
5240           {
5241             printk(INFO_LEAD "Received pre-emptive WDTR message from "
5242                    "target.\n", p->host_no, CTL_OF_SCB(scb));
5243           }
5244           switch(bus_width)
5245           {
5246             case MSG_EXT_WDTR_BUS_16_BIT:
5247             {
5248               if ( (p->features & AHC_WIDE) &&
5249                    (aic_dev->goal.width == MSG_EXT_WDTR_BUS_16_BIT) )
5250               {
5251                 new_bus_width = MSG_EXT_WDTR_BUS_16_BIT;
5252                 break;
5253               }
5254             } /* Fall through if we aren't a wide card */
5255             default:
5256             case MSG_EXT_WDTR_BUS_8_BIT:
5257             {
5258               aic_dev->needwdtr_copy = 0;
5259               new_bus_width = MSG_EXT_WDTR_BUS_8_BIT;
5260               break;
5261             }
5262           }
5263           scb->flags &= ~SCB_MSGOUT_BITS;
5264           scb->flags |= SCB_MSGOUT_WDTR;
5265           aic_dev->needwdtr = 0;
5266           if(aic_dev->dtr_pending == 0)
5267           {
5268             /* there is no other command with SCB_DTR_SCB already set that will
5269              * trigger the release of the dtr_pending bit.  Both set the bit
5270              * and set scb->flags |= SCB_DTR_SCB
5271              */
5272             aic_dev->dtr_pending = 1;
5273             scb->flags |= SCB_DTR_SCB;
5274           }
5275           aic_outb(p, HOST_MSG, MSG_OUT);
5276           aic_outb(p, aic_inb(p, SCSISIGO) | ATNO, SCSISIGO);
5277           /* when sending a reply, make sure that the goal settings are
5278            * updated along with current and active since the code that
5279            * will actually build the message for the sequencer uses the
5280            * goal settings as its guidelines.
5281            */
5282           aic7xxx_set_width(p, target, channel, lun, new_bus_width,
5283                           AHC_TRANS_GOAL|AHC_TRANS_ACTIVE|AHC_TRANS_CUR,
5284                           aic_dev);
5285         }
5286         
5287         /*
5288          * By virtue of the SCSI spec, a WDTR message negates any existing
5289          * SDTR negotiations.  So, even if needsdtr isn't marked for this
5290          * device, we still have to do a new SDTR message if the device
5291          * supports SDTR at all.  Therefore, we check needsdtr_copy instead
5292          * of needstr.
5293          */
5294         aic7xxx_set_syncrate(p, NULL, target, channel, 0, 0, 0,
5295                              AHC_TRANS_ACTIVE|AHC_TRANS_CUR|AHC_TRANS_QUITE,
5296                              aic_dev);
5297         aic_dev->needsdtr = aic_dev->needsdtr_copy;
5298         done = TRUE;
5299         break;
5300       }
5301       case MSG_EXT_PPR:
5302       {
5303         
5304         if (p->msg_buf[1] != MSG_EXT_PPR_LEN)
5305         {
5306           reject = TRUE;
5307           break;
5308         }
5309
5310         if (p->msg_len < (MSG_EXT_PPR_LEN + 2))
5311         {
5312           break;
5313         }
5314
5315         period = new_period = p->msg_buf[3];
5316         offset = new_offset = p->msg_buf[5];
5317         bus_width = new_bus_width = p->msg_buf[6];
5318         trans_options = new_trans_options = p->msg_buf[7] & 0xf;
5319
5320         if(aic7xxx_verbose & VERBOSE_NEGOTIATION2)
5321         {
5322           printk(INFO_LEAD "Parsing PPR message (%d/%d/%d/%d)\n",
5323                  p->host_no, CTL_OF_SCB(scb), period, offset, bus_width,
5324                  trans_options);
5325         }
5326
5327         /*
5328          * We might have a device that is starting negotiation with us
5329          * before we can start up negotiation with it....be prepared to
5330          * have a device ask for a higher speed then we want to give it
5331          * in that case
5332          */
5333         if ( (scb->flags & (SCB_MSGOUT_SENT|SCB_MSGOUT_PPR)) !=
5334              (SCB_MSGOUT_SENT|SCB_MSGOUT_PPR) )
5335         { 
5336           /* Have we scanned the device yet? */
5337           if (!(aic_dev->flags & DEVICE_DTR_SCANNED))
5338           {
5339             /* The device is electing to use PPR messages, so we will too until
5340              * we know better */
5341             aic_dev->needppr = aic_dev->needppr_copy = 1;
5342             aic_dev->needsdtr = aic_dev->needsdtr_copy = 0;
5343             aic_dev->needwdtr = aic_dev->needwdtr_copy = 0;
5344           
5345             /* We know the device is SCSI-3 compliant due to PPR */
5346             aic_dev->flags |= DEVICE_SCSI_3;
5347           
5348             /*
5349              * Not only is the device starting this up, but it also hasn't
5350              * been scanned yet, so this would likely be our TUR or our
5351              * INQUIRY command at scan time, so we need to use the
5352              * settings from the SEEPROM if they existed.  Of course, even
5353              * if we didn't find a SEEPROM, we stuffed default values into
5354              * the user settings anyway, so use those in all cases.
5355              */
5356             aic_dev->goal.width = p->user[tindex].width;
5357             if(p->user[tindex].offset)
5358             {
5359               aic_dev->goal.period = p->user[tindex].period;
5360               aic_dev->goal.options = p->user[tindex].options;
5361               if(p->features & AHC_ULTRA2)
5362               {
5363                 aic_dev->goal.offset = MAX_OFFSET_ULTRA2;
5364               }
5365               else if( aic_dev->goal.width &&
5366                        (bus_width == MSG_EXT_WDTR_BUS_16_BIT) &&
5367                        p->features & AHC_WIDE )
5368               {
5369                 aic_dev->goal.offset = MAX_OFFSET_16BIT;
5370               }
5371               else
5372               {
5373                 aic_dev->goal.offset = MAX_OFFSET_8BIT;
5374               }
5375             }
5376             else
5377             {
5378               aic_dev->goal.period = 255;
5379               aic_dev->goal.offset = 0;
5380               aic_dev->goal.options = 0;
5381             }
5382             aic_dev->flags |= DEVICE_DTR_SCANNED | DEVICE_PRINT_DTR;
5383           }
5384           else if (aic_dev->needppr_copy == 0)
5385           {
5386             /*
5387              * This is a preemptive message from the target, we've already
5388              * scanned this target and set our options for it, and we
5389              * don't need a PPR with this target (for whatever reason),
5390              * so reject this incoming PPR
5391              */
5392             reject = TRUE;
5393             break;
5394           }
5395
5396           /* The device is sending this message first and we have to reply */
5397           reply = TRUE;
5398           
5399           if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
5400           {
5401             printk(INFO_LEAD "Received pre-emptive PPR message from "
5402                    "target.\n", p->host_no, CTL_OF_SCB(scb));
5403           }
5404
5405         }
5406
5407         switch(bus_width)
5408         {
5409           case MSG_EXT_WDTR_BUS_16_BIT:
5410           {
5411             if ( (aic_dev->goal.width == MSG_EXT_WDTR_BUS_16_BIT) &&
5412                             p->features & AHC_WIDE)
5413             {
5414               break;
5415             }
5416           }
5417           default:
5418           {
5419             if ( (aic7xxx_verbose & VERBOSE_NEGOTIATION2) &&
5420                  ((aic_dev->flags & DEVICE_PRINT_DTR) ||
5421                   (aic7xxx_verbose > 0xffff)) )
5422             {
5423               reply = TRUE;
5424               printk(INFO_LEAD "Requesting %d bit transfers, rejecting.\n",
5425                 p->host_no, CTL_OF_SCB(scb), 8 * (0x01 << bus_width));
5426             }
5427           } /* We fall through on purpose */
5428           case MSG_EXT_WDTR_BUS_8_BIT:
5429           {
5430             /*
5431              * According to the spec, if we aren't wide, we also can't be
5432              * Dual Edge so clear the options byte
5433              */
5434             new_trans_options = 0;
5435             new_bus_width = MSG_EXT_WDTR_BUS_8_BIT;
5436             break;
5437           }
5438         }
5439
5440         if(reply)
5441         {
5442           /* when sending a reply, make sure that the goal settings are
5443            * updated along with current and active since the code that
5444            * will actually build the message for the sequencer uses the
5445            * goal settings as its guidelines.
5446            */
5447           aic7xxx_set_width(p, target, channel, lun, new_bus_width,
5448                             AHC_TRANS_GOAL|AHC_TRANS_ACTIVE|AHC_TRANS_CUR,
5449                             aic_dev);
5450           syncrate = aic7xxx_find_syncrate(p, &new_period, maxsync,
5451                                            &new_trans_options);
5452           aic7xxx_validate_offset(p, syncrate, &new_offset, new_bus_width);
5453           aic7xxx_set_syncrate(p, syncrate, target, channel, new_period,
5454                                new_offset, new_trans_options,
5455                                AHC_TRANS_GOAL|AHC_TRANS_ACTIVE|AHC_TRANS_CUR,
5456                                aic_dev);
5457         }
5458         else
5459         {
5460           aic7xxx_set_width(p, target, channel, lun, new_bus_width,
5461                             AHC_TRANS_ACTIVE|AHC_TRANS_CUR, aic_dev);
5462           syncrate = aic7xxx_find_syncrate(p, &new_period, maxsync,
5463                                            &new_trans_options);
5464           aic7xxx_validate_offset(p, syncrate, &new_offset, new_bus_width);
5465           aic7xxx_set_syncrate(p, syncrate, target, channel, new_period,
5466                                new_offset, new_trans_options,
5467                                AHC_TRANS_ACTIVE|AHC_TRANS_CUR, aic_dev);
5468         }
5469
5470         /*
5471          * As it turns out, if we don't *have* to have PPR messages, then
5472          * configure ourselves not to use them since that makes some
5473          * external drive chassis work (those chassis can't parse PPR
5474          * messages and they mangle the SCSI bus until you send a WDTR
5475          * and SDTR that they can understand).
5476          */
5477         if(new_trans_options == 0)
5478         {
5479           aic_dev->needppr = aic_dev->needppr_copy = 0;
5480           if(new_offset)
5481           {
5482             aic_dev->needsdtr = aic_dev->needsdtr_copy = 1;
5483           }
5484           if (new_bus_width)
5485           {
5486             aic_dev->needwdtr = aic_dev->needwdtr_copy = 1;
5487           }
5488         }
5489
5490         if((new_offset == 0) && (offset != 0))
5491         {
5492           /*
5493            * Oops, the syncrate went to low for this card and we fell off
5494            * to async (should never happen with a device that uses PPR
5495            * messages, but have to be complete)
5496            */
5497           reply = TRUE;
5498         }
5499
5500         if(reply)
5501         {
5502           scb->flags &= ~SCB_MSGOUT_BITS;
5503           scb->flags |= SCB_MSGOUT_PPR;
5504           aic_outb(p, HOST_MSG, MSG_OUT);
5505           aic_outb(p, aic_inb(p, SCSISIGO) | ATNO, SCSISIGO);
5506         }
5507         else
5508         {
5509           aic_dev->needppr = 0;
5510         }
5511         done = TRUE;
5512         break;
5513       }
5514       default:
5515       {
5516         reject = TRUE;
5517         break;
5518       }
5519     } /* end of switch(p->msg_type) */
5520   } /* end of if (!reject && (p->msg_len > 2)) */
5521
5522   if (!reply && reject)
5523   {
5524     aic_outb(p, MSG_MESSAGE_REJECT, MSG_OUT);
5525     aic_outb(p, aic_inb(p, SCSISIGO) | ATNO, SCSISIGO);
5526     done = TRUE;
5527   }
5528   return(done);
5529 }
5530
5531
5532 /*+F*************************************************************************
5533  * Function:
5534  *   aic7xxx_handle_reqinit
5535  *
5536  * Description:
5537  *   Interrupt handler for REQINIT interrupts (used to transfer messages to
5538  *    and from devices).
5539  *_F*************************************************************************/
5540 static void
5541 aic7xxx_handle_reqinit(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
5542 {
5543   unsigned char lastbyte;
5544   unsigned char phasemis;
5545   int done = FALSE;
5546
5547   switch(p->msg_type)
5548   {
5549     case MSG_TYPE_INITIATOR_MSGOUT:
5550       {
5551         if (p->msg_len == 0)
5552           panic("aic7xxx: REQINIT with no active message!\n");
5553
5554         lastbyte = (p->msg_index == (p->msg_len - 1));
5555         phasemis = ( aic_inb(p, SCSISIGI) & PHASE_MASK) != P_MESGOUT;
5556
5557         if (lastbyte || phasemis)
5558         {
5559           /* Time to end the message */
5560           p->msg_len = 0;
5561           p->msg_type = MSG_TYPE_NONE;
5562           /*
5563            * NOTE-TO-MYSELF: If you clear the REQINIT after you
5564            * disable REQINITs, then cases of REJECT_MSG stop working
5565            * and hang the bus
5566            */
5567           aic_outb(p, aic_inb(p, SIMODE1) & ~ENREQINIT, SIMODE1);
5568           aic_outb(p, CLRSCSIINT, CLRINT);
5569           p->flags &= ~AHC_HANDLING_REQINITS;
5570
5571           if (phasemis == 0)
5572           {
5573             aic_outb(p, p->msg_buf[p->msg_index], SINDEX);
5574             aic_outb(p, 0, RETURN_1);
5575 #ifdef AIC7XXX_VERBOSE_DEBUGGING
5576             if (aic7xxx_verbose > 0xffff)
5577               printk(INFO_LEAD "Completed sending of REQINIT message.\n",
5578                      p->host_no, CTL_OF_SCB(scb));
5579 #endif
5580           }
5581           else
5582           {
5583             aic_outb(p, MSGOUT_PHASEMIS, RETURN_1);
5584 #ifdef AIC7XXX_VERBOSE_DEBUGGING
5585             if (aic7xxx_verbose > 0xffff)
5586               printk(INFO_LEAD "PHASEMIS while sending REQINIT message.\n",
5587                      p->host_no, CTL_OF_SCB(scb));
5588 #endif
5589           }
5590           unpause_sequencer(p, TRUE);
5591         }
5592         else
5593         {
5594           /*
5595            * Present the byte on the bus (clearing REQINIT) but don't
5596            * unpause the sequencer.
5597            */
5598           aic_outb(p, CLRREQINIT, CLRSINT1);
5599           aic_outb(p, CLRSCSIINT, CLRINT);
5600           aic_outb(p,  p->msg_buf[p->msg_index++], SCSIDATL);
5601         }
5602         break;
5603       }
5604     case MSG_TYPE_INITIATOR_MSGIN:
5605       {
5606         phasemis = ( aic_inb(p, SCSISIGI) & PHASE_MASK ) != P_MESGIN;
5607
5608         if (phasemis == 0)
5609         {
5610           p->msg_len++;
5611           /* Pull the byte in without acking it */
5612           p->msg_buf[p->msg_index] = aic_inb(p, SCSIBUSL);
5613           done = aic7xxx_parse_msg(p, scb);
5614           /* Ack the byte */
5615           aic_outb(p, CLRREQINIT, CLRSINT1);
5616           aic_outb(p, CLRSCSIINT, CLRINT);
5617           aic_inb(p, SCSIDATL);
5618           p->msg_index++;
5619         }
5620         if (phasemis || done)
5621         {
5622 #ifdef AIC7XXX_VERBOSE_DEBUGGING
5623           if (aic7xxx_verbose > 0xffff)
5624           {
5625             if (phasemis)
5626               printk(INFO_LEAD "PHASEMIS while receiving REQINIT message.\n",
5627                      p->host_no, CTL_OF_SCB(scb));
5628             else
5629               printk(INFO_LEAD "Completed receipt of REQINIT message.\n",
5630                      p->host_no, CTL_OF_SCB(scb));
5631           }
5632 #endif
5633           /* Time to end our message session */
5634           p->msg_len = 0;
5635           p->msg_type = MSG_TYPE_NONE;
5636           aic_outb(p, aic_inb(p, SIMODE1) & ~ENREQINIT, SIMODE1);
5637           aic_outb(p, CLRSCSIINT, CLRINT);
5638           p->flags &= ~AHC_HANDLING_REQINITS;
5639           unpause_sequencer(p, TRUE);
5640         }
5641         break;
5642       }
5643     default:
5644       {
5645         panic("aic7xxx: Unknown REQINIT message type.\n");
5646         break;
5647       }
5648   } /* End of switch(p->msg_type) */
5649 }
5650
5651 /*+F*************************************************************************
5652  * Function:
5653  *   aic7xxx_handle_scsiint
5654  *
5655  * Description:
5656  *   Interrupt handler for SCSI interrupts (SCSIINT).
5657  *-F*************************************************************************/
5658 static void
5659 aic7xxx_handle_scsiint(struct aic7xxx_host *p, unsigned char intstat)
5660 {
5661   unsigned char scb_index;
5662   unsigned char status;
5663   struct aic7xxx_scb *scb;
5664   struct aic_dev_data *aic_dev;
5665
5666   scb_index = aic_inb(p, SCB_TAG);
5667   status = aic_inb(p, SSTAT1);
5668
5669   if (scb_index < p->scb_data->numscbs)
5670   {
5671     scb = p->scb_data->scb_array[scb_index];
5672     if ((scb->flags & SCB_ACTIVE) == 0)
5673     {
5674       scb = NULL;
5675     }
5676   }
5677   else
5678   {
5679     scb = NULL;
5680   }
5681
5682
5683   if ((status & SCSIRSTI) != 0)
5684   {
5685     int channel;
5686
5687     if ( (p->chip & AHC_CHIPID_MASK) == AHC_AIC7770 )
5688       channel = (aic_inb(p, SBLKCTL) & SELBUSB) >> 3;
5689     else
5690       channel = 0;
5691
5692     if (aic7xxx_verbose & VERBOSE_RESET)
5693       printk(WARN_LEAD "Someone else reset the channel!!\n",
5694            p->host_no, channel, -1, -1);
5695     if (aic7xxx_panic_on_abort)
5696       aic7xxx_panic_abort(p, NULL);
5697     /*
5698      * Go through and abort all commands for the channel, but do not
5699      * reset the channel again.
5700      */
5701     aic7xxx_reset_channel(p, channel, /* Initiate Reset */ FALSE);
5702     aic7xxx_run_done_queue(p, TRUE);
5703     scb = NULL;
5704   }
5705   else if ( ((status & BUSFREE) != 0) && ((status & SELTO) == 0) )
5706   {
5707     /*
5708      * First look at what phase we were last in.  If it's message-out,
5709      * chances are pretty good that the bus free was in response to
5710      * one of our abort requests.
5711      */
5712     unsigned char lastphase = aic_inb(p, LASTPHASE);
5713     unsigned char saved_tcl = aic_inb(p, SAVED_TCL);
5714     unsigned char target = (saved_tcl >> 4) & 0x0F;
5715     int channel;
5716     int printerror = TRUE;
5717
5718     if ( (p->chip & AHC_CHIPID_MASK) == AHC_AIC7770 )
5719       channel = (aic_inb(p, SBLKCTL) & SELBUSB) >> 3;
5720     else
5721       channel = 0;
5722
5723     aic_outb(p, aic_inb(p, SCSISEQ) & (ENSELI|ENRSELI|ENAUTOATNP),
5724              SCSISEQ);
5725     if (lastphase == P_MESGOUT)
5726     {
5727       unsigned char message;
5728
5729       message = aic_inb(p, SINDEX);
5730
5731       if ((message == MSG_ABORT) || (message == MSG_ABORT_TAG))
5732       {
5733         if (aic7xxx_verbose & VERBOSE_ABORT_PROCESS)
5734           printk(INFO_LEAD "SCB %d abort delivered.\n", p->host_no,
5735             CTL_OF_SCB(scb), scb->hscb->tag);
5736         aic7xxx_reset_device(p, target, channel, ALL_LUNS,
5737                 (message == MSG_ABORT) ? SCB_LIST_NULL : scb->hscb->tag );
5738         aic7xxx_run_done_queue(p, TRUE);
5739         scb = NULL;
5740         printerror = 0;
5741       }
5742       else if (message == MSG_BUS_DEV_RESET)
5743       {
5744         aic7xxx_handle_device_reset(p, target, channel);
5745         scb = NULL;
5746         printerror = 0;
5747       }
5748     }
5749     if ( (scb != NULL) && (scb->flags & SCB_DTR_SCB) ) 
5750     {
5751       /*
5752        * Hmmm...error during a negotiation command.  Either we have a
5753        * borken bus, or the device doesn't like our negotiation message.
5754        * Since we check the INQUIRY data of a device before sending it
5755        * negotiation messages, assume the bus is borken for whatever
5756        * reason.  Complete the command.
5757        */
5758       printerror = 0;
5759       aic7xxx_reset_device(p, target, channel, ALL_LUNS, scb->hscb->tag);
5760       aic7xxx_run_done_queue(p, TRUE);
5761       scb = NULL;
5762     }
5763     if (printerror != 0)
5764     {
5765       if (scb != NULL)
5766       {
5767         unsigned char tag;
5768
5769         if ((scb->hscb->control & TAG_ENB) != 0)
5770         {
5771           tag = scb->hscb->tag;
5772         }
5773         else
5774         {
5775           tag = SCB_LIST_NULL;
5776         }
5777         aic7xxx_reset_device(p, target, channel, ALL_LUNS, tag);
5778         aic7xxx_run_done_queue(p, TRUE);
5779       }
5780       else
5781       {
5782         aic7xxx_reset_device(p, target, channel, ALL_LUNS, SCB_LIST_NULL);
5783         aic7xxx_run_done_queue(p, TRUE);
5784       }
5785       printk(INFO_LEAD "Unexpected busfree, LASTPHASE = 0x%x, "
5786              "SEQADDR = 0x%x\n", p->host_no, channel, target, -1, lastphase,
5787              (aic_inb(p, SEQADDR1) << 8) | aic_inb(p, SEQADDR0));
5788       scb = NULL;
5789     }
5790     aic_outb(p, MSG_NOOP, MSG_OUT);
5791     aic_outb(p, aic_inb(p, SIMODE1) & ~(ENBUSFREE|ENREQINIT),
5792       SIMODE1);
5793     p->flags &= ~AHC_HANDLING_REQINITS;
5794     aic_outb(p, CLRBUSFREE, CLRSINT1);
5795     aic_outb(p, CLRSCSIINT, CLRINT);
5796     restart_sequencer(p);
5797     unpause_sequencer(p, TRUE);
5798   }
5799   else if ((status & SELTO) != 0)
5800   {
5801         unsigned char scbptr;
5802         unsigned char nextscb;
5803         struct scsi_cmnd *cmd;
5804
5805     scbptr = aic_inb(p, WAITING_SCBH);
5806     if (scbptr > p->scb_data->maxhscbs)
5807     {
5808       /*
5809        * I'm still trying to track down exactly how this happens, but until
5810        * I find it, this code will make sure we aren't passing bogus values
5811        * into the SCBPTR register, even if that register will just wrap
5812        * things around, we still don't like having out of range variables.
5813        *
5814        * NOTE: Don't check the aic7xxx_verbose variable, I want this message
5815        * to always be displayed.
5816        */
5817       printk(INFO_LEAD "Invalid WAITING_SCBH value %d, improvising.\n",
5818              p->host_no, -1, -1, -1, scbptr);
5819       if (p->scb_data->maxhscbs > 4)
5820         scbptr &= (p->scb_data->maxhscbs - 1);
5821       else
5822         scbptr &= 0x03;
5823     }
5824     aic_outb(p, scbptr, SCBPTR);
5825     scb_index = aic_inb(p, SCB_TAG);
5826
5827     scb = NULL;
5828     if (scb_index < p->scb_data->numscbs)
5829     {
5830       scb = p->scb_data->scb_array[scb_index];
5831       if ((scb->flags & SCB_ACTIVE) == 0)
5832       {
5833         scb = NULL;
5834       }
5835     }
5836     if (scb == NULL)
5837     {
5838       printk(WARN_LEAD "Referenced SCB %d not valid during SELTO.\n",
5839              p->host_no, -1, -1, -1, scb_index);
5840       printk(KERN_WARNING "        SCSISEQ = 0x%x SEQADDR = 0x%x SSTAT0 = 0x%x "
5841              "SSTAT1 = 0x%x\n", aic_inb(p, SCSISEQ),
5842              aic_inb(p, SEQADDR0) | (aic_inb(p, SEQADDR1) << 8),
5843              aic_inb(p, SSTAT0), aic_inb(p, SSTAT1));
5844       if (aic7xxx_panic_on_abort)
5845         aic7xxx_panic_abort(p, NULL);
5846     }
5847     else
5848     {
5849       cmd = scb->cmd;
5850       cmd->result = (DID_TIME_OUT << 16);
5851
5852       /*
5853        * Clear out this hardware SCB
5854        */
5855       aic_outb(p, 0, SCB_CONTROL);
5856
5857       /*
5858        * Clear out a few values in the card that are in an undetermined
5859        * state.
5860        */
5861       aic_outb(p, MSG_NOOP, MSG_OUT);
5862
5863       /*
5864        * Shift the waiting for selection queue forward
5865        */
5866       nextscb = aic_inb(p, SCB_NEXT);
5867       aic_outb(p, nextscb, WAITING_SCBH);
5868
5869       /*
5870        * Put this SCB back on the free list.
5871        */
5872       aic7xxx_add_curscb_to_free_list(p);
5873 #ifdef AIC7XXX_VERBOSE_DEBUGGING
5874       if (aic7xxx_verbose > 0xffff)
5875         printk(INFO_LEAD "Selection Timeout.\n", p->host_no, CTL_OF_SCB(scb));
5876 #endif
5877       if (scb->flags & SCB_QUEUED_ABORT)
5878       {
5879         /*
5880          * We know that this particular SCB had to be the queued abort since
5881          * the disconnected SCB would have gotten a reconnect instead.
5882          * What we need to do then is to let the command timeout again so
5883          * we get a reset since this abort just failed.
5884          */
5885         cmd->result = 0;
5886         scb = NULL;
5887       }
5888     }
5889     /*
5890      * Keep the sequencer from trying to restart any selections
5891      */
5892     aic_outb(p, aic_inb(p, SCSISEQ) & ~ENSELO, SCSISEQ);
5893     /*
5894      * Make sure the data bits on the bus are released
5895      * Don't do this on 7770 chipsets, it makes them give us
5896      * a BRKADDRINT and kills the card.
5897      */
5898     if( (p->chip & ~AHC_CHIPID_MASK) == AHC_PCI )
5899       aic_outb(p, 0, SCSIBUSL);
5900
5901     /*
5902      * Delay for the selection timeout delay period then stop the selection
5903      */
5904     udelay(301);
5905     aic_outb(p, CLRSELINGO, CLRSINT0);
5906     /*
5907      * Clear out all the interrupt status bits
5908      */
5909     aic_outb(p, aic_inb(p, SIMODE1) & ~(ENREQINIT|ENBUSFREE), SIMODE1);
5910     p->flags &= ~AHC_HANDLING_REQINITS;
5911     aic_outb(p, CLRSELTIMEO | CLRBUSFREE, CLRSINT1);
5912     aic_outb(p, CLRSCSIINT, CLRINT);
5913     /*
5914      * Restarting the sequencer will stop the selection and make sure devices
5915      * are allowed to reselect in.
5916      */
5917     restart_sequencer(p);
5918     unpause_sequencer(p, TRUE);
5919   }
5920   else if (scb == NULL)
5921   {
5922     printk(WARN_LEAD "aic7xxx_isr - referenced scb not valid "
5923            "during scsiint 0x%x scb(%d)\n"
5924            "      SIMODE0 0x%x, SIMODE1 0x%x, SSTAT0 0x%x, SEQADDR 0x%x\n",
5925            p->host_no, -1, -1, -1, status, scb_index, aic_inb(p, SIMODE0),
5926            aic_inb(p, SIMODE1), aic_inb(p, SSTAT0),
5927            (aic_inb(p, SEQADDR1) << 8) | aic_inb(p, SEQADDR0));
5928     /*
5929      * Turn off the interrupt and set status to zero, so that it
5930      * falls through the rest of the SCSIINT code.
5931      */
5932     aic_outb(p, status, CLRSINT1);
5933     aic_outb(p, CLRSCSIINT, CLRINT);
5934     unpause_sequencer(p, /* unpause always */ TRUE);
5935     scb = NULL;
5936   }
5937   else if (status & SCSIPERR)
5938   {
5939     /*
5940      * Determine the bus phase and queue an appropriate message.
5941      */
5942         char  *phase;
5943         struct scsi_cmnd *cmd;
5944         unsigned char mesg_out = MSG_NOOP;
5945         unsigned char lastphase = aic_inb(p, LASTPHASE);
5946         unsigned char sstat2 = aic_inb(p, SSTAT2);
5947
5948     cmd = scb->cmd;
5949     switch (lastphase)
5950     {
5951       case P_DATAOUT:
5952         phase = "Data-Out";
5953         break;
5954       case P_DATAIN:
5955         phase = "Data-In";
5956         mesg_out = MSG_INITIATOR_DET_ERR;
5957         break;
5958       case P_COMMAND:
5959         phase = "Command";
5960         break;
5961       case P_MESGOUT:
5962         phase = "Message-Out";
5963         break;
5964       case P_STATUS:
5965         phase = "Status";
5966         mesg_out = MSG_INITIATOR_DET_ERR;
5967         break;
5968       case P_MESGIN:
5969         phase = "Message-In";
5970         mesg_out = MSG_PARITY_ERROR;
5971         break;
5972       default:
5973         phase = "unknown";
5974         break;
5975     }
5976
5977     /*
5978      * A parity error has occurred during a data
5979      * transfer phase. Flag it and continue.
5980      */
5981     if( (p->features & AHC_ULTRA3) && 
5982         (aic_inb(p, SCSIRATE) & AHC_SYNCRATE_CRC) &&
5983         (lastphase == P_DATAIN) )
5984     {
5985       printk(WARN_LEAD "CRC error during %s phase.\n",
5986              p->host_no, CTL_OF_SCB(scb), phase);
5987       if(sstat2 & CRCVALERR)
5988       {
5989         printk(WARN_LEAD "  CRC error in intermediate CRC packet.\n",
5990                p->host_no, CTL_OF_SCB(scb));
5991       }
5992       if(sstat2 & CRCENDERR)
5993       {
5994         printk(WARN_LEAD "  CRC error in ending CRC packet.\n",
5995                p->host_no, CTL_OF_SCB(scb));
5996       }
5997       if(sstat2 & CRCREQERR)
5998       {
5999         printk(WARN_LEAD "  Target incorrectly requested a CRC packet.\n",
6000                p->host_no, CTL_OF_SCB(scb));
6001       }
6002       if(sstat2 & DUAL_EDGE_ERROR)
6003       {
6004         printk(WARN_LEAD "  Dual Edge transmission error.\n",
6005                p->host_no, CTL_OF_SCB(scb));
6006       }
6007     }
6008     else if( (lastphase == P_MESGOUT) &&
6009              (scb->flags & SCB_MSGOUT_PPR) )
6010     {
6011       /*
6012        * As per the draft specs, any device capable of supporting any of
6013        * the option values other than 0 are not allowed to reject the
6014        * PPR message.  Instead, they must negotiate out what they do
6015        * support instead of rejecting our offering or else they cause
6016        * a parity error during msg_out phase to signal that they don't
6017        * like our settings.
6018        */
6019       aic_dev = AIC_DEV(scb->cmd);
6020       aic_dev->needppr = aic_dev->needppr_copy = 0;
6021       aic7xxx_set_width(p, scb->cmd->device->id, scb->cmd->device->channel, scb->cmd->device->lun,
6022                         MSG_EXT_WDTR_BUS_8_BIT,
6023                         (AHC_TRANS_ACTIVE|AHC_TRANS_CUR|AHC_TRANS_QUITE),
6024                         aic_dev);
6025       aic7xxx_set_syncrate(p, NULL, scb->cmd->device->id, scb->cmd->device->channel, 0, 0,
6026                            0, AHC_TRANS_ACTIVE|AHC_TRANS_CUR|AHC_TRANS_QUITE,
6027                            aic_dev);
6028       aic_dev->goal.options = 0;
6029       scb->flags &= ~SCB_MSGOUT_BITS;
6030       if(aic7xxx_verbose & VERBOSE_NEGOTIATION2)
6031       {
6032         printk(INFO_LEAD "parity error during PPR message, reverting "
6033                "to WDTR/SDTR\n", p->host_no, CTL_OF_SCB(scb));
6034       }
6035       if ( aic_dev->goal.width )
6036       {
6037         aic_dev->needwdtr = aic_dev->needwdtr_copy = 1;
6038       }
6039       if ( aic_dev->goal.offset )
6040       {
6041         if( aic_dev->goal.period <= 9 )
6042         {
6043           aic_dev->goal.period = 10;
6044         }
6045         aic_dev->needsdtr = aic_dev->needsdtr_copy = 1;
6046       }
6047       scb = NULL;
6048     }
6049
6050     /*
6051      * We've set the hardware to assert ATN if we get a parity
6052      * error on "in" phases, so all we need to do is stuff the
6053      * message buffer with the appropriate message.  "In" phases
6054      * have set mesg_out to something other than MSG_NOP.
6055      */
6056     if (mesg_out != MSG_NOOP)
6057     {
6058       aic_outb(p, mesg_out, MSG_OUT);
6059       aic_outb(p, aic_inb(p, SCSISIGI) | ATNO, SCSISIGO);
6060       scb = NULL;
6061     }
6062     aic_outb(p, CLRSCSIPERR, CLRSINT1);
6063     aic_outb(p, CLRSCSIINT, CLRINT);
6064     unpause_sequencer(p, /* unpause_always */ TRUE);
6065   }
6066   else if ( (status & REQINIT) &&
6067             (p->flags & AHC_HANDLING_REQINITS) )
6068   {
6069 #ifdef AIC7XXX_VERBOSE_DEBUGGING
6070     if (aic7xxx_verbose > 0xffff)
6071       printk(INFO_LEAD "Handling REQINIT, SSTAT1=0x%x.\n", p->host_no,
6072              CTL_OF_SCB(scb), aic_inb(p, SSTAT1));
6073 #endif
6074     aic7xxx_handle_reqinit(p, scb);
6075     return;
6076   }
6077   else
6078   {
6079     /*
6080      * We don't know what's going on. Turn off the
6081      * interrupt source and try to continue.
6082      */
6083     if (aic7xxx_verbose & VERBOSE_SCSIINT)
6084       printk(INFO_LEAD "Unknown SCSIINT status, SSTAT1(0x%x).\n",
6085         p->host_no, -1, -1, -1, status);
6086     aic_outb(p, status, CLRSINT1);
6087     aic_outb(p, CLRSCSIINT, CLRINT);
6088     unpause_sequencer(p, /* unpause always */ TRUE);
6089     scb = NULL;
6090   }
6091   if (scb != NULL)
6092   {
6093     aic7xxx_done(p, scb);
6094   }
6095 }
6096
6097 #ifdef AIC7XXX_VERBOSE_DEBUGGING
6098 static void
6099 aic7xxx_check_scbs(struct aic7xxx_host *p, char *buffer)
6100 {
6101   unsigned char saved_scbptr, free_scbh, dis_scbh, wait_scbh, temp;
6102   int i, bogus, lost;
6103   static unsigned char scb_status[AIC7XXX_MAXSCB];
6104
6105 #define SCB_NO_LIST 0
6106 #define SCB_FREE_LIST 1
6107 #define SCB_WAITING_LIST 2
6108 #define SCB_DISCONNECTED_LIST 4
6109 #define SCB_CURRENTLY_ACTIVE 8
6110
6111   /*
6112    * Note, these checks will fail on a regular basis once the machine moves
6113    * beyond the bus scan phase.  The problem is race conditions concerning
6114    * the scbs and where they are linked in.  When you have 30 or so commands
6115    * outstanding on the bus, and run this twice with every interrupt, the
6116    * chances get pretty good that you'll catch the sequencer with an SCB
6117    * only partially linked in.  Therefore, once we pass the scan phase
6118    * of the bus, we really should disable this function.
6119    */
6120   bogus = FALSE;
6121   memset(&scb_status[0], 0, sizeof(scb_status));
6122   pause_sequencer(p);
6123   saved_scbptr = aic_inb(p, SCBPTR);
6124   if (saved_scbptr >= p->scb_data->maxhscbs)
6125   {
6126     printk("Bogus SCBPTR %d\n", saved_scbptr);
6127     bogus = TRUE;
6128   }
6129   scb_status[saved_scbptr] = SCB_CURRENTLY_ACTIVE;
6130   free_scbh = aic_inb(p, FREE_SCBH);
6131   if ( (free_scbh != SCB_LIST_NULL) &&
6132        (free_scbh >= p->scb_data->maxhscbs) )
6133   {
6134     printk("Bogus FREE_SCBH %d\n", free_scbh);
6135     bogus = TRUE;
6136   }
6137   else
6138   {
6139     temp = free_scbh;
6140     while( (temp != SCB_LIST_NULL) && (temp < p->scb_data->maxhscbs) )
6141     {
6142       if(scb_status[temp] & 0x07)
6143       {
6144         printk("HSCB %d on multiple lists, status 0x%02x", temp,
6145                scb_status[temp] | SCB_FREE_LIST);
6146         bogus = TRUE;
6147       }
6148       scb_status[temp] |= SCB_FREE_LIST;
6149       aic_outb(p, temp, SCBPTR);
6150       temp = aic_inb(p, SCB_NEXT);
6151     }
6152   }
6153
6154   dis_scbh = aic_inb(p, DISCONNECTED_SCBH);
6155   if ( (dis_scbh != SCB_LIST_NULL) &&
6156        (dis_scbh >= p->scb_data->maxhscbs) )
6157   {
6158     printk("Bogus DISCONNECTED_SCBH %d\n", dis_scbh);
6159     bogus = TRUE;
6160   }
6161   else
6162   {
6163     temp = dis_scbh;
6164     while( (temp != SCB_LIST_NULL) && (temp < p->scb_data->maxhscbs) )
6165     {
6166       if(scb_status[temp] & 0x07)
6167       {
6168         printk("HSCB %d on multiple lists, status 0x%02x", temp,
6169                scb_status[temp] | SCB_DISCONNECTED_LIST);
6170         bogus = TRUE;
6171       }
6172       scb_status[temp] |= SCB_DISCONNECTED_LIST;
6173       aic_outb(p, temp, SCBPTR);
6174       temp = aic_inb(p, SCB_NEXT);
6175     }
6176   }
6177   
6178   wait_scbh = aic_inb(p, WAITING_SCBH);
6179   if ( (wait_scbh != SCB_LIST_NULL) &&
6180        (wait_scbh >= p->scb_data->maxhscbs) )
6181   {
6182     printk("Bogus WAITING_SCBH %d\n", wait_scbh);
6183     bogus = TRUE;
6184   }
6185   else
6186   {
6187     temp = wait_scbh;
6188     while( (temp != SCB_LIST_NULL) && (temp < p->scb_data->maxhscbs) )
6189     {
6190       if(scb_status[temp] & 0x07)
6191       {
6192         printk("HSCB %d on multiple lists, status 0x%02x", temp,
6193                scb_status[temp] | SCB_WAITING_LIST);
6194         bogus = TRUE;
6195       }
6196       scb_status[temp] |= SCB_WAITING_LIST;
6197       aic_outb(p, temp, SCBPTR);
6198       temp = aic_inb(p, SCB_NEXT);
6199     }
6200   }
6201
6202   lost=0;
6203   for(i=0; i < p->scb_data->maxhscbs; i++)
6204   {
6205     aic_outb(p, i, SCBPTR);
6206     temp = aic_inb(p, SCB_NEXT);
6207     if ( ((temp != SCB_LIST_NULL) &&
6208           (temp >= p->scb_data->maxhscbs)) )
6209     {
6210       printk("HSCB %d bad, SCB_NEXT invalid(%d).\n", i, temp);
6211       bogus = TRUE;
6212     }
6213     if ( temp == i )
6214     {
6215       printk("HSCB %d bad, SCB_NEXT points to self.\n", i);
6216       bogus = TRUE;
6217     }
6218     if (scb_status[i] == 0)
6219       lost++;
6220     if (lost > 1)
6221     {
6222       printk("Too many lost scbs.\n");
6223       bogus=TRUE;
6224     }
6225   }
6226   aic_outb(p, saved_scbptr, SCBPTR);
6227   unpause_sequencer(p, FALSE);
6228   if (bogus)
6229   {
6230     printk("Bogus parameters found in card SCB array structures.\n");
6231     printk("%s\n", buffer);
6232     aic7xxx_panic_abort(p, NULL);
6233   }
6234   return;
6235 }
6236 #endif
6237
6238
6239 /*+F*************************************************************************
6240  * Function:
6241  *   aic7xxx_handle_command_completion_intr
6242  *
6243  * Description:
6244  *   SCSI command completion interrupt handler.
6245  *-F*************************************************************************/
6246 static void
6247 aic7xxx_handle_command_completion_intr(struct aic7xxx_host *p)
6248 {
6249         struct aic7xxx_scb *scb = NULL;
6250         struct aic_dev_data *aic_dev;
6251         struct scsi_cmnd *cmd;
6252         unsigned char scb_index, tindex;
6253
6254 #ifdef AIC7XXX_VERBOSE_DEBUGGING
6255   if( (p->isr_count < 16) && (aic7xxx_verbose > 0xffff) )
6256     printk(INFO_LEAD "Command Complete Int.\n", p->host_no, -1, -1, -1);
6257 #endif
6258     
6259   /*
6260    * Read the INTSTAT location after clearing the CMDINT bit.  This forces
6261    * any posted PCI writes to flush to memory.  Gerard Roudier suggested
6262    * this fix to the possible race of clearing the CMDINT bit but not
6263    * having all command bytes flushed onto the qoutfifo.
6264    */
6265   aic_outb(p, CLRCMDINT, CLRINT);
6266   aic_inb(p, INTSTAT);
6267   /*
6268    * The sequencer will continue running when it
6269    * issues this interrupt. There may be >1 commands
6270    * finished, so loop until we've processed them all.
6271    */
6272
6273   while (p->qoutfifo[p->qoutfifonext] != SCB_LIST_NULL)
6274   {
6275     scb_index = p->qoutfifo[p->qoutfifonext];
6276     p->qoutfifo[p->qoutfifonext++] = SCB_LIST_NULL;
6277     if ( scb_index >= p->scb_data->numscbs )
6278     {
6279       printk(WARN_LEAD "CMDCMPLT with invalid SCB index %d\n", p->host_no,
6280         -1, -1, -1, scb_index);
6281       continue;
6282     }
6283     scb = p->scb_data->scb_array[scb_index];
6284     if (!(scb->flags & SCB_ACTIVE) || (scb->cmd == NULL))
6285     {
6286       printk(WARN_LEAD "CMDCMPLT without command for SCB %d, SCB flags "
6287         "0x%x, cmd 0x%lx\n", p->host_no, -1, -1, -1, scb_index, scb->flags,
6288         (unsigned long) scb->cmd);
6289       continue;
6290     }
6291     tindex = TARGET_INDEX(scb->cmd);
6292     aic_dev = AIC_DEV(scb->cmd);
6293     if (scb->flags & SCB_QUEUED_ABORT)
6294     {
6295       pause_sequencer(p);
6296       if ( ((aic_inb(p, LASTPHASE) & PHASE_MASK) != P_BUSFREE) &&
6297            (aic_inb(p, SCB_TAG) == scb->hscb->tag) )
6298       {
6299         unpause_sequencer(p, FALSE);
6300         continue;
6301       }
6302       aic7xxx_reset_device(p, scb->cmd->device->id, scb->cmd->device->channel,
6303         scb->cmd->device->lun, scb->hscb->tag);
6304       scb->flags &= ~(SCB_QUEUED_FOR_DONE | SCB_RESET | SCB_ABORT |
6305         SCB_QUEUED_ABORT);
6306       unpause_sequencer(p, FALSE);
6307     }
6308     else if (scb->flags & SCB_ABORT)
6309     {
6310       /*
6311        * We started to abort this, but it completed on us, let it
6312        * through as successful
6313        */
6314       scb->flags &= ~(SCB_ABORT|SCB_RESET);
6315     }
6316     else if (scb->flags & SCB_SENSE)
6317     {
6318       char *buffer = &scb->cmd->sense_buffer[0];
6319
6320       if (buffer[12] == 0x47 || buffer[12] == 0x54)
6321       {
6322         /*
6323          * Signal that we need to re-negotiate things.
6324          */
6325         aic_dev->needppr = aic_dev->needppr_copy;
6326         aic_dev->needsdtr = aic_dev->needsdtr_copy;
6327         aic_dev->needwdtr = aic_dev->needwdtr_copy;
6328       }
6329     }
6330     cmd = scb->cmd;
6331     if (scb->hscb->residual_SG_segment_count != 0)
6332     {
6333       aic7xxx_calculate_residual(p, scb);
6334     }
6335     cmd->result |= (aic7xxx_error(cmd) << 16);
6336     aic7xxx_done(p, scb);
6337   }
6338 }
6339
6340 /*+F*************************************************************************
6341  * Function:
6342  *   aic7xxx_isr
6343  *
6344  * Description:
6345  *   SCSI controller interrupt handler.
6346  *-F*************************************************************************/
6347 static void
6348 aic7xxx_isr(void *dev_id)
6349 {
6350   struct aic7xxx_host *p;
6351   unsigned char intstat;
6352
6353   p = dev_id;
6354
6355   /*
6356    * Just a few sanity checks.  Make sure that we have an int pending.
6357    * Also, if PCI, then we are going to check for a PCI bus error status
6358    * should we get too many spurious interrupts.
6359    */
6360   if (!((intstat = aic_inb(p, INTSTAT)) & INT_PEND))
6361   {
6362 #ifdef CONFIG_PCI
6363     if ( (p->chip & AHC_PCI) && (p->spurious_int > 500) &&
6364         !(p->flags & AHC_HANDLING_REQINITS) )
6365     {
6366       if ( aic_inb(p, ERROR) & PCIERRSTAT )
6367       {
6368         aic7xxx_pci_intr(p);
6369       }
6370       p->spurious_int = 0;
6371     }
6372     else if ( !(p->flags & AHC_HANDLING_REQINITS) )
6373     {
6374       p->spurious_int++;
6375     }
6376 #endif
6377     return;
6378   }
6379
6380   p->spurious_int = 0;
6381
6382   /*
6383    * Keep track of interrupts for /proc/scsi
6384    */
6385   p->isr_count++;
6386
6387 #ifdef AIC7XXX_VERBOSE_DEBUGGING
6388   if ( (p->isr_count < 16) && (aic7xxx_verbose > 0xffff) &&
6389        (aic7xxx_panic_on_abort) && (p->flags & AHC_PAGESCBS) )
6390     aic7xxx_check_scbs(p, "Bogus settings at start of interrupt.");
6391 #endif
6392
6393   /*
6394    * Handle all the interrupt sources - especially for SCSI
6395    * interrupts, we won't get a second chance at them.
6396    */
6397   if (intstat & CMDCMPLT)
6398   {
6399     aic7xxx_handle_command_completion_intr(p);
6400   }
6401
6402   if (intstat & BRKADRINT)
6403   {
6404     int i;
6405     unsigned char errno = aic_inb(p, ERROR);
6406
6407     printk(KERN_ERR "(scsi%d) BRKADRINT error(0x%x):\n", p->host_no, errno);
6408     for (i = 0; i < ARRAY_SIZE(hard_error); i++)
6409     {
6410       if (errno & hard_error[i].errno)
6411       {
6412         printk(KERN_ERR "  %s\n", hard_error[i].errmesg);
6413       }
6414     }
6415     printk(KERN_ERR "(scsi%d)   SEQADDR=0x%x\n", p->host_no,
6416       (((aic_inb(p, SEQADDR1) << 8) & 0x100) | aic_inb(p, SEQADDR0)));
6417     if (aic7xxx_panic_on_abort)
6418       aic7xxx_panic_abort(p, NULL);
6419 #ifdef CONFIG_PCI
6420     if (errno & PCIERRSTAT)
6421       aic7xxx_pci_intr(p);
6422 #endif
6423     if (errno & (SQPARERR | ILLOPCODE | ILLSADDR))
6424     {
6425       panic("aic7xxx: unrecoverable BRKADRINT.\n");
6426     }
6427     if (errno & ILLHADDR)
6428     {
6429       printk(KERN_ERR "(scsi%d) BUG! Driver accessed chip without first "
6430              "pausing controller!\n", p->host_no);
6431     }
6432 #ifdef AIC7XXX_VERBOSE_DEBUGGING
6433     if (errno & DPARERR)
6434     {
6435       if (aic_inb(p, DMAPARAMS) & DIRECTION)
6436         printk("(scsi%d) while DMAing SCB from host to card.\n", p->host_no);
6437       else
6438         printk("(scsi%d) while DMAing SCB from card to host.\n", p->host_no);
6439     }
6440 #endif
6441     aic_outb(p, CLRPARERR | CLRBRKADRINT, CLRINT);
6442     unpause_sequencer(p, FALSE);
6443   }
6444
6445   if (intstat & SEQINT)
6446   {
6447     /*
6448      * Read the CCSCBCTL register to work around a bug in the Ultra2 cards
6449      */
6450     if(p->features & AHC_ULTRA2)
6451     {
6452       aic_inb(p, CCSCBCTL);
6453     }
6454     aic7xxx_handle_seqint(p, intstat);
6455   }
6456
6457   if (intstat & SCSIINT)
6458   {
6459     aic7xxx_handle_scsiint(p, intstat);
6460   }
6461
6462 #ifdef AIC7XXX_VERBOSE_DEBUGGING
6463   if ( (p->isr_count < 16) && (aic7xxx_verbose > 0xffff) &&
6464        (aic7xxx_panic_on_abort) && (p->flags & AHC_PAGESCBS) )
6465     aic7xxx_check_scbs(p, "Bogus settings at end of interrupt.");
6466 #endif
6467
6468 }
6469
6470 /*+F*************************************************************************
6471  * Function:
6472  *   do_aic7xxx_isr
6473  *
6474  * Description:
6475  *   This is a gross hack to solve a problem in linux kernels 2.1.85 and
6476  *   above.  Please, children, do not try this at home, and if you ever see
6477  *   anything like it, please inform the Gross Hack Police immediately
6478  *-F*************************************************************************/
6479 static irqreturn_t
6480 do_aic7xxx_isr(int irq, void *dev_id)
6481 {
6482   unsigned long cpu_flags;
6483   struct aic7xxx_host *p;
6484   
6485   p = (struct aic7xxx_host *)dev_id;
6486   if(!p)
6487     return IRQ_NONE;
6488   spin_lock_irqsave(p->host->host_lock, cpu_flags);
6489   p->flags |= AHC_IN_ISR;
6490   do
6491   {
6492     aic7xxx_isr(dev_id);
6493   } while ( (aic_inb(p, INTSTAT) & INT_PEND) );
6494   aic7xxx_done_cmds_complete(p);
6495   aic7xxx_run_waiting_queues(p);
6496   p->flags &= ~AHC_IN_ISR;
6497   spin_unlock_irqrestore(p->host->host_lock, cpu_flags);
6498
6499   return IRQ_HANDLED;
6500 }
6501
6502 /*+F*************************************************************************
6503  * Function:
6504  *   aic7xxx_init_transinfo
6505  *
6506  * Description:
6507  *   Set up the initial aic_dev values from the BIOS settings and from
6508  *   INQUIRY results
6509  *-F*************************************************************************/
6510 static void
6511 aic7xxx_init_transinfo(struct aic7xxx_host *p, struct aic_dev_data *aic_dev)
6512 {
6513   struct scsi_device *sdpnt = aic_dev->SDptr;
6514   unsigned char tindex;
6515
6516   tindex = sdpnt->id | (sdpnt->channel << 3);
6517   if (!(aic_dev->flags & DEVICE_DTR_SCANNED))
6518   {
6519     aic_dev->flags |= DEVICE_DTR_SCANNED;
6520
6521     if ( sdpnt->wdtr && (p->features & AHC_WIDE) )
6522     {
6523       aic_dev->needwdtr = aic_dev->needwdtr_copy = 1;
6524       aic_dev->goal.width = p->user[tindex].width;
6525     }
6526     else
6527     {
6528       aic_dev->needwdtr = aic_dev->needwdtr_copy = 0;
6529       pause_sequencer(p);
6530       aic7xxx_set_width(p, sdpnt->id, sdpnt->channel, sdpnt->lun,
6531                         MSG_EXT_WDTR_BUS_8_BIT, (AHC_TRANS_ACTIVE |
6532                                                  AHC_TRANS_GOAL |
6533                                                  AHC_TRANS_CUR), aic_dev );
6534       unpause_sequencer(p, FALSE);
6535     }
6536     if ( sdpnt->sdtr && p->user[tindex].offset )
6537     {
6538       aic_dev->goal.period = p->user[tindex].period;
6539       aic_dev->goal.options = p->user[tindex].options;
6540       if (p->features & AHC_ULTRA2)
6541         aic_dev->goal.offset = MAX_OFFSET_ULTRA2;
6542       else if (aic_dev->goal.width == MSG_EXT_WDTR_BUS_16_BIT)
6543         aic_dev->goal.offset = MAX_OFFSET_16BIT;
6544       else
6545         aic_dev->goal.offset = MAX_OFFSET_8BIT;
6546       if ( sdpnt->ppr && p->user[tindex].period <= 9 &&
6547              p->user[tindex].options )
6548       {
6549         aic_dev->needppr = aic_dev->needppr_copy = 1;
6550         aic_dev->needsdtr = aic_dev->needsdtr_copy = 0;
6551         aic_dev->needwdtr = aic_dev->needwdtr_copy = 0;
6552         aic_dev->flags |= DEVICE_SCSI_3;
6553       }
6554       else
6555       {
6556         aic_dev->needsdtr = aic_dev->needsdtr_copy = 1;
6557         aic_dev->goal.period = max_t(unsigned char, 10, aic_dev->goal.period);
6558         aic_dev->goal.options = 0;
6559       }
6560     }
6561     else
6562     {
6563       aic_dev->needsdtr = aic_dev->needsdtr_copy = 0;
6564       aic_dev->goal.period = 255;
6565       aic_dev->goal.offset = 0;
6566       aic_dev->goal.options = 0;
6567     }
6568     aic_dev->flags |= DEVICE_PRINT_DTR;
6569   }
6570 }
6571
6572 /*+F*************************************************************************
6573  * Function:
6574  *   aic7xxx_slave_alloc
6575  *
6576  * Description:
6577  *   Set up the initial aic_dev struct pointers
6578  *-F*************************************************************************/
6579 static int
6580 aic7xxx_slave_alloc(struct scsi_device *SDptr)
6581 {
6582   struct aic7xxx_host *p = (struct aic7xxx_host *)SDptr->host->hostdata;
6583   struct aic_dev_data *aic_dev;
6584
6585   aic_dev = kmalloc(sizeof(struct aic_dev_data), GFP_ATOMIC | GFP_KERNEL);
6586   if(!aic_dev)
6587     return 1;
6588   /*
6589    * Check to see if channel was scanned.
6590    */
6591   
6592   if (!(p->flags & AHC_A_SCANNED) && (SDptr->channel == 0))
6593   {
6594     if (aic7xxx_verbose & VERBOSE_PROBE2)
6595       printk(INFO_LEAD "Scanning channel for devices.\n",
6596         p->host_no, 0, -1, -1);
6597     p->flags |= AHC_A_SCANNED;
6598   }
6599   else
6600   {
6601     if (!(p->flags & AHC_B_SCANNED) && (SDptr->channel == 1))
6602     {
6603       if (aic7xxx_verbose & VERBOSE_PROBE2)
6604         printk(INFO_LEAD "Scanning channel for devices.\n",
6605           p->host_no, 1, -1, -1);
6606       p->flags |= AHC_B_SCANNED;
6607     }
6608   }
6609
6610   memset(aic_dev, 0, sizeof(struct aic_dev_data));
6611   SDptr->hostdata = aic_dev;
6612   aic_dev->SDptr = SDptr;
6613   aic_dev->max_q_depth = 1;
6614   aic_dev->temp_q_depth = 1;
6615   scbq_init(&aic_dev->delayed_scbs);
6616   INIT_LIST_HEAD(&aic_dev->list);
6617   list_add_tail(&aic_dev->list, &p->aic_devs);
6618   return 0;
6619 }
6620
6621 /*+F*************************************************************************
6622  * Function:
6623  *   aic7xxx_device_queue_depth
6624  *
6625  * Description:
6626  *   Determines the queue depth for a given device.  There are two ways
6627  *   a queue depth can be obtained for a tagged queueing device.  One
6628  *   way is the default queue depth which is determined by whether
6629  *   aic7xxx_default_queue_depth.  The other is by the aic7xxx_tag_info
6630  *   array.
6631  *
6632  *   If tagged queueing isn't supported on the device, then we set the
6633  *   depth to p->host->hostt->cmd_per_lun for internal driver queueing.
6634  *   as the default queue depth.  Otherwise, we use either 4 or 8 as the
6635  *   default queue depth (dependent on the number of hardware SCBs).
6636  *   The other way we determine queue depth is through the use of the
6637  *   aic7xxx_tag_info array which is enabled by defining
6638  *   AIC7XXX_TAGGED_QUEUEING_BY_DEVICE.  This array can be initialized
6639  *   with queue depths for individual devices.  It also allows tagged
6640  *   queueing to be [en|dis]abled for a specific adapter.
6641  *-F*************************************************************************/
6642 static void
6643 aic7xxx_device_queue_depth(struct aic7xxx_host *p, struct scsi_device *device)
6644 {
6645   int tag_enabled = FALSE;
6646   struct aic_dev_data *aic_dev = device->hostdata;
6647   unsigned char tindex;
6648
6649   tindex = device->id | (device->channel << 3);
6650
6651   if (device->simple_tags)
6652     return; // We've already enabled this device
6653
6654   if (device->tagged_supported)
6655   {
6656     tag_enabled = TRUE;
6657
6658     if (!(p->discenable & (1 << tindex)))
6659     {
6660       if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
6661         printk(INFO_LEAD "Disconnection disabled, unable to "
6662              "enable tagged queueing.\n",
6663              p->host_no, device->channel, device->id, device->lun);
6664       tag_enabled = FALSE;
6665     }
6666     else
6667     {
6668       if (p->instance >= ARRAY_SIZE(aic7xxx_tag_info))
6669       {
6670         static int print_warning = TRUE;
6671         if(print_warning)
6672         {
6673           printk(KERN_INFO "aic7xxx: WARNING, insufficient tag_info instances for"
6674                            " installed controllers.\n");
6675           printk(KERN_INFO "aic7xxx: Please update the aic7xxx_tag_info array in"
6676                            " the aic7xxx.c source file.\n");
6677           print_warning = FALSE;
6678         }
6679         aic_dev->max_q_depth = aic_dev->temp_q_depth =
6680                 aic7xxx_default_queue_depth;
6681       }
6682       else
6683       {
6684
6685         if (aic7xxx_tag_info[p->instance].tag_commands[tindex] == 255)
6686         {
6687           tag_enabled = FALSE;
6688         }
6689         else if (aic7xxx_tag_info[p->instance].tag_commands[tindex] == 0)
6690         {
6691           aic_dev->max_q_depth = aic_dev->temp_q_depth =
6692                   aic7xxx_default_queue_depth;
6693         }
6694         else
6695         {
6696           aic_dev->max_q_depth = aic_dev->temp_q_depth = 
6697             aic7xxx_tag_info[p->instance].tag_commands[tindex];
6698         }
6699       }
6700     }
6701   }
6702   if (tag_enabled)
6703   {
6704     if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
6705     {
6706           printk(INFO_LEAD "Tagged queuing enabled, queue depth %d.\n",
6707             p->host_no, device->channel, device->id,
6708             device->lun, aic_dev->max_q_depth);
6709     }
6710     scsi_adjust_queue_depth(device, MSG_ORDERED_TAG, aic_dev->max_q_depth);
6711   }
6712   else
6713   {
6714     if (aic7xxx_verbose & VERBOSE_NEGOTIATION2)
6715     {
6716           printk(INFO_LEAD "Tagged queuing disabled, queue depth %d.\n",
6717             p->host_no, device->channel, device->id,
6718             device->lun, device->host->cmd_per_lun);
6719     }
6720     scsi_adjust_queue_depth(device, 0, device->host->cmd_per_lun);
6721   }
6722   return;
6723 }
6724
6725 /*+F*************************************************************************
6726  * Function:
6727  *   aic7xxx_slave_destroy
6728  *
6729  * Description:
6730  *   prepare for this device to go away
6731  *-F*************************************************************************/
6732 static void
6733 aic7xxx_slave_destroy(struct scsi_device *SDptr)
6734 {
6735   struct aic_dev_data *aic_dev = SDptr->hostdata;
6736
6737   list_del(&aic_dev->list);
6738   SDptr->hostdata = NULL;
6739   kfree(aic_dev);
6740   return;
6741 }
6742
6743 /*+F*************************************************************************
6744  * Function:
6745  *   aic7xxx_slave_configure
6746  *
6747  * Description:
6748  *   Configure the device we are attaching to the controller.  This is
6749  *   where we get to do things like scan the INQUIRY data, set queue
6750  *   depths, allocate command structs, etc.
6751  *-F*************************************************************************/
6752 static int
6753 aic7xxx_slave_configure(struct scsi_device *SDptr)
6754 {
6755   struct aic7xxx_host *p = (struct aic7xxx_host *) SDptr->host->hostdata;
6756   struct aic_dev_data *aic_dev;
6757   int scbnum;
6758
6759   aic_dev = (struct aic_dev_data *)SDptr->hostdata;
6760
6761   aic7xxx_init_transinfo(p, aic_dev);
6762   aic7xxx_device_queue_depth(p, SDptr);
6763   if(list_empty(&aic_dev->list))
6764     list_add_tail(&aic_dev->list, &p->aic_devs);
6765
6766   scbnum = 0;
6767   list_for_each_entry(aic_dev, &p->aic_devs, list) {
6768     scbnum += aic_dev->max_q_depth;
6769   }
6770   while (scbnum > p->scb_data->numscbs)
6771   {
6772     /*
6773      * Pre-allocate the needed SCBs to get around the possibility of having
6774      * to allocate some when memory is more or less exhausted and we need
6775      * the SCB in order to perform a swap operation (possible deadlock)
6776      */
6777     if ( aic7xxx_allocate_scb(p) == 0 )
6778       break;
6779   }
6780
6781
6782   return(0);
6783 }
6784
6785 /*+F*************************************************************************
6786  * Function:
6787  *   aic7xxx_probe
6788  *
6789  * Description:
6790  *   Probing for EISA boards: it looks like the first two bytes
6791  *   are a manufacturer code - three characters, five bits each:
6792  *
6793  *               BYTE 0   BYTE 1   BYTE 2   BYTE 3
6794  *              ?1111122 22233333 PPPPPPPP RRRRRRRR
6795  *
6796  *   The characters are baselined off ASCII '@', so add that value
6797  *   to each to get the real ASCII code for it. The next two bytes
6798  *   appear to be a product and revision number, probably vendor-
6799  *   specific. This is what is being searched for at each port,
6800  *   and what should probably correspond to the ID= field in the
6801  *   ECU's .cfg file for the card - if your card is not detected,
6802  *   make sure your signature is listed in the array.
6803  *
6804  *   The fourth byte's lowest bit seems to be an enabled/disabled
6805  *   flag (rest of the bits are reserved?).
6806  *
6807  * NOTE:  This function is only needed on Intel and Alpha platforms,
6808  *   the other platforms we support don't have EISA/VLB busses.  So,
6809  *   we #ifdef this entire function to avoid compiler warnings about
6810  *   an unused function.
6811  *-F*************************************************************************/
6812 #if defined(__i386__) || defined(__alpha__)
6813 static int
6814 aic7xxx_probe(int slot, int base, ahc_flag_type *flags)
6815 {
6816   int i;
6817   unsigned char buf[4];
6818
6819   static struct {
6820     int n;
6821     unsigned char signature[sizeof(buf)];
6822     ahc_chip type;
6823     int bios_disabled;
6824   } AIC7xxx[] = {
6825     { 4, { 0x04, 0x90, 0x77, 0x70 },
6826       AHC_AIC7770|AHC_EISA, FALSE },  /* mb 7770  */
6827     { 4, { 0x04, 0x90, 0x77, 0x71 },
6828       AHC_AIC7770|AHC_EISA, FALSE }, /* host adapter 274x */
6829     { 4, { 0x04, 0x90, 0x77, 0x56 },
6830       AHC_AIC7770|AHC_VL, FALSE }, /* 284x BIOS enabled */
6831     { 4, { 0x04, 0x90, 0x77, 0x57 },
6832       AHC_AIC7770|AHC_VL, TRUE }   /* 284x BIOS disabled */
6833   };
6834
6835   /*
6836    * The VL-bus cards need to be primed by
6837    * writing before a signature check.
6838    */
6839   for (i = 0; i < sizeof(buf); i++)
6840   {
6841     outb(0x80 + i, base);
6842     buf[i] = inb(base + i);
6843   }
6844
6845   for (i = 0; i < ARRAY_SIZE(AIC7xxx); i++)
6846   {
6847     /*
6848      * Signature match on enabled card?
6849      */
6850     if (!memcmp(buf, AIC7xxx[i].signature, AIC7xxx[i].n))
6851     {
6852       if (inb(base + 4) & 1)
6853       {
6854         if (AIC7xxx[i].bios_disabled)
6855         {
6856           *flags |= AHC_USEDEFAULTS;
6857         }
6858         else
6859         {
6860           *flags |= AHC_BIOS_ENABLED;
6861         }
6862         return (i);
6863       }
6864
6865       printk("aic7xxx: <Adaptec 7770 SCSI Host Adapter> "
6866              "disabled at slot %d, ignored.\n", slot);
6867     }
6868   }
6869
6870   return (-1);
6871 }
6872 #endif /* (__i386__) || (__alpha__) */
6873
6874
6875 /*+F*************************************************************************
6876  * Function:
6877  *   read_2840_seeprom
6878  *
6879  * Description:
6880  *   Reads the 2840 serial EEPROM and returns 1 if successful and 0 if
6881  *   not successful.
6882  *
6883  *   See read_seeprom (for the 2940) for the instruction set of the 93C46
6884  *   chip.
6885  *
6886  *   The 2840 interface to the 93C46 serial EEPROM is through the
6887  *   STATUS_2840 and SEECTL_2840 registers.  The CS_2840, CK_2840, and
6888  *   DO_2840 bits of the SEECTL_2840 register are connected to the chip
6889  *   select, clock, and data out lines respectively of the serial EEPROM.
6890  *   The DI_2840 bit of the STATUS_2840 is connected to the data in line
6891  *   of the serial EEPROM.  The EEPROM_TF bit of STATUS_2840 register is
6892  *   useful in that it gives us an 800 nsec timer.  After a read from the
6893  *   SEECTL_2840 register the timing flag is cleared and goes high 800 nsec
6894  *   later.
6895  *-F*************************************************************************/
6896 static int
6897 read_284x_seeprom(struct aic7xxx_host *p, struct seeprom_config *sc)
6898 {
6899   int i = 0, k = 0;
6900   unsigned char temp;
6901   unsigned short checksum = 0;
6902   unsigned short *seeprom = (unsigned short *) sc;
6903   struct seeprom_cmd {
6904     unsigned char len;
6905     unsigned char bits[3];
6906   };
6907   struct seeprom_cmd seeprom_read = {3, {1, 1, 0}};
6908
6909 #define CLOCK_PULSE(p) \
6910   while ((aic_inb(p, STATUS_2840) & EEPROM_TF) == 0)        \
6911   {                                                \
6912     ;  /* Do nothing */                                \
6913   }                                                \
6914   (void) aic_inb(p, SEECTL_2840);
6915
6916   /*
6917    * Read the first 32 registers of the seeprom.  For the 2840,
6918    * the 93C46 SEEPROM is a 1024-bit device with 64 16-bit registers
6919    * but only the first 32 are used by Adaptec BIOS.  The loop
6920    * will range from 0 to 31.
6921    */
6922   for (k = 0; k < (sizeof(*sc) / 2); k++)
6923   {
6924     /*
6925      * Send chip select for one clock cycle.
6926      */
6927     aic_outb(p, CK_2840 | CS_2840, SEECTL_2840);
6928     CLOCK_PULSE(p);
6929
6930     /*
6931      * Now we're ready to send the read command followed by the
6932      * address of the 16-bit register we want to read.
6933      */
6934     for (i = 0; i < seeprom_read.len; i++)
6935     {
6936       temp = CS_2840 | seeprom_read.bits[i];
6937       aic_outb(p, temp, SEECTL_2840);
6938       CLOCK_PULSE(p);
6939       temp = temp ^ CK_2840;
6940       aic_outb(p, temp, SEECTL_2840);
6941       CLOCK_PULSE(p);
6942     }
6943     /*
6944      * Send the 6 bit address (MSB first, LSB last).
6945      */
6946     for (i = 5; i >= 0; i--)
6947     {
6948       temp = k;
6949       temp = (temp >> i) & 1;  /* Mask out all but lower bit. */
6950       temp = CS_2840 | temp;
6951       aic_outb(p, temp, SEECTL_2840);
6952       CLOCK_PULSE(p);
6953       temp = temp ^ CK_2840;
6954       aic_outb(p, temp, SEECTL_2840);
6955       CLOCK_PULSE(p);
6956     }
6957
6958     /*
6959      * Now read the 16 bit register.  An initial 0 precedes the
6960      * register contents which begins with bit 15 (MSB) and ends
6961      * with bit 0 (LSB).  The initial 0 will be shifted off the
6962      * top of our word as we let the loop run from 0 to 16.
6963      */
6964     for (i = 0; i <= 16; i++)
6965     {
6966       temp = CS_2840;
6967       aic_outb(p, temp, SEECTL_2840);
6968       CLOCK_PULSE(p);
6969       temp = temp ^ CK_2840;
6970       seeprom[k] = (seeprom[k] << 1) | (aic_inb(p, STATUS_2840) & DI_2840);
6971       aic_outb(p, temp, SEECTL_2840);
6972       CLOCK_PULSE(p);
6973     }
6974     /*
6975      * The serial EEPROM has a checksum in the last word.  Keep a
6976      * running checksum for all words read except for the last
6977      * word.  We'll verify the checksum after all words have been
6978      * read.
6979      */
6980     if (k < (sizeof(*sc) / 2) - 1)
6981     {
6982       checksum = checksum + seeprom[k];
6983     }
6984
6985     /*
6986      * Reset the chip select for the next command cycle.
6987      */
6988     aic_outb(p, 0, SEECTL_2840);
6989     CLOCK_PULSE(p);
6990     aic_outb(p, CK_2840, SEECTL_2840);
6991     CLOCK_PULSE(p);
6992     aic_outb(p, 0, SEECTL_2840);
6993     CLOCK_PULSE(p);
6994   }
6995
6996 #if 0
6997   printk("Computed checksum 0x%x, checksum read 0x%x\n", checksum, sc->checksum);
6998   printk("Serial EEPROM:");
6999   for (k = 0; k < (sizeof(*sc) / 2); k++)
7000   {
7001     if (((k % 8) == 0) && (k != 0))
7002     {
7003       printk("\n              ");
7004     }
7005     printk(" 0x%x", seeprom[k]);
7006   }
7007   printk("\n");
7008 #endif
7009
7010   if (checksum != sc->checksum)
7011   {
7012     printk("aic7xxx: SEEPROM checksum error, ignoring SEEPROM settings.\n");
7013     return (0);
7014   }
7015
7016   return (1);
7017 #undef CLOCK_PULSE
7018 }
7019
7020 #define CLOCK_PULSE(p)                                               \
7021   do {                                                               \
7022     int limit = 0;                                                   \
7023     do {                                                             \
7024       mb();                                                          \
7025       pause_sequencer(p);  /* This is just to generate some PCI */   \
7026                            /* traffic so the PCI read is flushed */  \
7027                            /* it shouldn't be needed, but some */    \
7028                            /* chipsets do indeed appear to need */   \
7029                            /* something to force PCI reads to get */ \
7030                            /* flushed */                             \
7031       udelay(1);           /* Do nothing */                          \
7032     } while (((aic_inb(p, SEECTL) & SEERDY) == 0) && (++limit < 1000)); \
7033   } while(0)
7034
7035 /*+F*************************************************************************
7036  * Function:
7037  *   acquire_seeprom
7038  *
7039  * Description:
7040  *   Acquires access to the memory port on PCI controllers.
7041  *-F*************************************************************************/
7042 static int
7043 acquire_seeprom(struct aic7xxx_host *p)
7044 {
7045
7046   /*
7047    * Request access of the memory port.  When access is
7048    * granted, SEERDY will go high.  We use a 1 second
7049    * timeout which should be near 1 second more than
7050    * is needed.  Reason: after the 7870 chip reset, there
7051    * should be no contention.
7052    */
7053   aic_outb(p, SEEMS, SEECTL);
7054   CLOCK_PULSE(p);
7055   if ((aic_inb(p, SEECTL) & SEERDY) == 0)
7056   {
7057     aic_outb(p, 0, SEECTL);
7058     return (0);
7059   }
7060   return (1);
7061 }
7062
7063 /*+F*************************************************************************
7064  * Function:
7065  *   release_seeprom
7066  *
7067  * Description:
7068  *   Releases access to the memory port on PCI controllers.
7069  *-F*************************************************************************/
7070 static void
7071 release_seeprom(struct aic7xxx_host *p)
7072 {
7073   /*
7074    * Make sure the SEEPROM is ready before we release it.
7075    */
7076   CLOCK_PULSE(p);
7077   aic_outb(p, 0, SEECTL);
7078 }
7079
7080 /*+F*************************************************************************
7081  * Function:
7082  *   read_seeprom
7083  *
7084  * Description:
7085  *   Reads the serial EEPROM and returns 1 if successful and 0 if
7086  *   not successful.
7087  *
7088  *   The instruction set of the 93C46/56/66 chips is as follows:
7089  *
7090  *               Start  OP
7091  *     Function   Bit  Code  Address    Data     Description
7092  *     -------------------------------------------------------------------
7093  *     READ        1    10   A5 - A0             Reads data stored in memory,
7094  *                                               starting at specified address
7095  *     EWEN        1    00   11XXXX              Write enable must precede
7096  *                                               all programming modes
7097  *     ERASE       1    11   A5 - A0             Erase register A5A4A3A2A1A0
7098  *     WRITE       1    01   A5 - A0   D15 - D0  Writes register
7099  *     ERAL        1    00   10XXXX              Erase all registers
7100  *     WRAL        1    00   01XXXX    D15 - D0  Writes to all registers
7101  *     EWDS        1    00   00XXXX              Disables all programming
7102  *                                               instructions
7103  *     *Note: A value of X for address is a don't care condition.
7104  *     *Note: The 93C56 and 93C66 have 8 address bits.
7105  * 
7106  *
7107  *   The 93C46 has a four wire interface: clock, chip select, data in, and
7108  *   data out.  In order to perform one of the above functions, you need
7109  *   to enable the chip select for a clock period (typically a minimum of
7110  *   1 usec, with the clock high and low a minimum of 750 and 250 nsec
7111  *   respectively.  While the chip select remains high, you can clock in
7112  *   the instructions (above) starting with the start bit, followed by the
7113  *   OP code, Address, and Data (if needed).  For the READ instruction, the
7114  *   requested 16-bit register contents is read from the data out line but
7115  *   is preceded by an initial zero (leading 0, followed by 16-bits, MSB
7116  *   first).  The clock cycling from low to high initiates the next data
7117  *   bit to be sent from the chip.
7118  *
7119  *   The 78xx interface to the 93C46 serial EEPROM is through the SEECTL
7120  *   register.  After successful arbitration for the memory port, the
7121  *   SEECS bit of the SEECTL register is connected to the chip select.
7122  *   The SEECK, SEEDO, and SEEDI are connected to the clock, data out,
7123  *   and data in lines respectively.  The SEERDY bit of SEECTL is useful
7124  *   in that it gives us an 800 nsec timer.  After a write to the SEECTL
7125  *   register, the SEERDY goes high 800 nsec later.  The one exception
7126  *   to this is when we first request access to the memory port.  The
7127  *   SEERDY goes high to signify that access has been granted and, for
7128  *   this case, has no implied timing.
7129  *-F*************************************************************************/
7130 static int
7131 read_seeprom(struct aic7xxx_host *p, int offset, 
7132     unsigned short *scarray, unsigned int len, seeprom_chip_type chip)
7133 {
7134   int i = 0, k;
7135   unsigned char temp;
7136   unsigned short checksum = 0;
7137   struct seeprom_cmd {
7138     unsigned char len;
7139     unsigned char bits[3];
7140   };
7141   struct seeprom_cmd seeprom_read = {3, {1, 1, 0}};
7142
7143   /*
7144    * Request access of the memory port.
7145    */
7146   if (acquire_seeprom(p) == 0)
7147   {
7148     return (0);
7149   }
7150
7151   /*
7152    * Read 'len' registers of the seeprom.  For the 7870, the 93C46
7153    * SEEPROM is a 1024-bit device with 64 16-bit registers but only
7154    * the first 32 are used by Adaptec BIOS.  Some adapters use the
7155    * 93C56 SEEPROM which is a 2048-bit device.  The loop will range
7156    * from 0 to 'len' - 1.
7157    */
7158   for (k = 0; k < len; k++)
7159   {
7160     /*
7161      * Send chip select for one clock cycle.
7162      */
7163     aic_outb(p, SEEMS | SEECK | SEECS, SEECTL);
7164     CLOCK_PULSE(p);
7165
7166     /*
7167      * Now we're ready to send the read command followed by the
7168      * address of the 16-bit register we want to read.
7169      */
7170     for (i = 0; i < seeprom_read.len; i++)
7171     {
7172       temp = SEEMS | SEECS | (seeprom_read.bits[i] << 1);
7173       aic_outb(p, temp, SEECTL);
7174       CLOCK_PULSE(p);
7175       temp = temp ^ SEECK;
7176       aic_outb(p, temp, SEECTL);
7177       CLOCK_PULSE(p);
7178     }
7179     /*
7180      * Send the 6 or 8 bit address (MSB first, LSB last).
7181      */
7182     for (i = ((int) chip - 1); i >= 0; i--)
7183     {
7184       temp = k + offset;
7185       temp = (temp >> i) & 1;  /* Mask out all but lower bit. */
7186       temp = SEEMS | SEECS | (temp << 1);
7187       aic_outb(p, temp, SEECTL);
7188       CLOCK_PULSE(p);
7189       temp = temp ^ SEECK;
7190       aic_outb(p, temp, SEECTL);
7191       CLOCK_PULSE(p);
7192     }
7193
7194     /*
7195      * Now read the 16 bit register.  An initial 0 precedes the
7196      * register contents which begins with bit 15 (MSB) and ends
7197      * with bit 0 (LSB).  The initial 0 will be shifted off the
7198      * top of our word as we let the loop run from 0 to 16.
7199      */
7200     for (i = 0; i <= 16; i++)
7201     {
7202       temp = SEEMS | SEECS;
7203       aic_outb(p, temp, SEECTL);
7204       CLOCK_PULSE(p);
7205       temp = temp ^ SEECK;
7206       scarray[k] = (scarray[k] << 1) | (aic_inb(p, SEECTL) & SEEDI);
7207       aic_outb(p, temp, SEECTL);
7208       CLOCK_PULSE(p);
7209     }
7210
7211     /*
7212      * The serial EEPROM should have a checksum in the last word.
7213      * Keep a running checksum for all words read except for the
7214      * last word.  We'll verify the checksum after all words have
7215      * been read.
7216      */
7217     if (k < (len - 1))
7218     {
7219       checksum = checksum + scarray[k];
7220     }
7221
7222     /*
7223      * Reset the chip select for the next command cycle.
7224      */
7225     aic_outb(p, SEEMS, SEECTL);
7226     CLOCK_PULSE(p);
7227     aic_outb(p, SEEMS | SEECK, SEECTL);
7228     CLOCK_PULSE(p);
7229     aic_outb(p, SEEMS, SEECTL);
7230     CLOCK_PULSE(p);
7231   }
7232
7233   /*
7234    * Release access to the memory port and the serial EEPROM.
7235    */
7236   release_seeprom(p);
7237
7238 #if 0
7239   printk("Computed checksum 0x%x, checksum read 0x%x\n",
7240          checksum, scarray[len - 1]);
7241   printk("Serial EEPROM:");
7242   for (k = 0; k < len; k++)
7243   {
7244     if (((k % 8) == 0) && (k != 0))
7245     {
7246       printk("\n              ");
7247     }
7248     printk(" 0x%x", scarray[k]);
7249   }
7250   printk("\n");
7251 #endif
7252   if ( (checksum != scarray[len - 1]) || (checksum == 0) )
7253   {
7254     return (0);
7255   }
7256
7257   return (1);
7258 }
7259
7260 /*+F*************************************************************************
7261  * Function:
7262  *   read_brdctl
7263  *
7264  * Description:
7265  *   Reads the BRDCTL register.
7266  *-F*************************************************************************/
7267 static unsigned char
7268 read_brdctl(struct aic7xxx_host *p)
7269 {
7270   unsigned char brdctl, value;
7271
7272   /*
7273    * Make sure the SEEPROM is ready before we access it
7274    */
7275   CLOCK_PULSE(p);
7276   if (p->features & AHC_ULTRA2)
7277   {
7278     brdctl = BRDRW_ULTRA2;
7279     aic_outb(p, brdctl, BRDCTL);
7280     CLOCK_PULSE(p);
7281     value = aic_inb(p, BRDCTL);
7282     CLOCK_PULSE(p);
7283     return(value);
7284   }
7285   brdctl = BRDRW;
7286   if ( !((p->chip & AHC_CHIPID_MASK) == AHC_AIC7895) ||
7287         (p->flags & AHC_CHNLB) )
7288   {
7289     brdctl |= BRDCS;
7290   }
7291   aic_outb(p, brdctl, BRDCTL);
7292   CLOCK_PULSE(p);
7293   value = aic_inb(p, BRDCTL);
7294   CLOCK_PULSE(p);
7295   aic_outb(p, 0, BRDCTL);
7296   CLOCK_PULSE(p);
7297   return (value);
7298 }
7299
7300 /*+F*************************************************************************
7301  * Function:
7302  *   write_brdctl
7303  *
7304  * Description:
7305  *   Writes a value to the BRDCTL register.
7306  *-F*************************************************************************/
7307 static void
7308 write_brdctl(struct aic7xxx_host *p, unsigned char value)
7309 {
7310   unsigned char brdctl;
7311
7312   /*
7313    * Make sure the SEEPROM is ready before we access it
7314    */
7315   CLOCK_PULSE(p);
7316   if (p->features & AHC_ULTRA2)
7317   {
7318     brdctl = value;
7319     aic_outb(p, brdctl, BRDCTL);
7320     CLOCK_PULSE(p);
7321     brdctl |= BRDSTB_ULTRA2;
7322     aic_outb(p, brdctl, BRDCTL);
7323     CLOCK_PULSE(p);
7324     brdctl &= ~BRDSTB_ULTRA2;
7325     aic_outb(p, brdctl, BRDCTL);
7326     CLOCK_PULSE(p);
7327     read_brdctl(p);
7328     CLOCK_PULSE(p);
7329   }
7330   else
7331   {
7332     brdctl = BRDSTB;
7333     if ( !((p->chip & AHC_CHIPID_MASK) == AHC_AIC7895) ||
7334           (p->flags & AHC_CHNLB) )
7335     {
7336       brdctl |= BRDCS;
7337     }
7338     brdctl = BRDSTB | BRDCS;
7339     aic_outb(p, brdctl, BRDCTL);
7340     CLOCK_PULSE(p);
7341     brdctl |= value;
7342     aic_outb(p, brdctl, BRDCTL);
7343     CLOCK_PULSE(p);
7344     brdctl &= ~BRDSTB;
7345     aic_outb(p, brdctl, BRDCTL);
7346     CLOCK_PULSE(p);
7347     brdctl &= ~BRDCS;
7348     aic_outb(p, brdctl, BRDCTL);
7349     CLOCK_PULSE(p);
7350   }
7351 }
7352
7353 /*+F*************************************************************************
7354  * Function:
7355  *   aic785x_cable_detect
7356  *
7357  * Description:
7358  *   Detect the cables that are present on aic785x class controller chips
7359  *-F*************************************************************************/
7360 static void
7361 aic785x_cable_detect(struct aic7xxx_host *p, int *int_50,
7362     int *ext_present, int *eeprom)
7363 {
7364   unsigned char brdctl;
7365
7366   aic_outb(p, BRDRW | BRDCS, BRDCTL);
7367   CLOCK_PULSE(p);
7368   aic_outb(p, 0, BRDCTL);
7369   CLOCK_PULSE(p);
7370   brdctl = aic_inb(p, BRDCTL);
7371   CLOCK_PULSE(p);
7372   *int_50 = !(brdctl & BRDDAT5);
7373   *ext_present = !(brdctl & BRDDAT6);
7374   *eeprom = (aic_inb(p, SPIOCAP) & EEPROM);
7375 }
7376
7377 #undef CLOCK_PULSE
7378
7379 /*+F*************************************************************************
7380  * Function:
7381  *   aic2940_uwpro_cable_detect
7382  *
7383  * Description:
7384  *   Detect the cables that are present on the 2940-UWPro cards
7385  *
7386  * NOTE: This function assumes the SEEPROM will have already been acquired
7387  *       prior to invocation of this function.
7388  *-F*************************************************************************/
7389 static void
7390 aic2940_uwpro_wide_cable_detect(struct aic7xxx_host *p, int *int_68,
7391     int *ext_68, int *eeprom)
7392 {
7393   unsigned char brdctl;
7394
7395   /*
7396    * First read the status of our cables.  Set the rom bank to
7397    * 0 since the bank setting serves as a multiplexor for the
7398    * cable detection logic.  BRDDAT5 controls the bank switch.
7399    */
7400   write_brdctl(p, 0);
7401
7402   /*
7403    * Now we read the state of the internal 68 connector.  BRDDAT6
7404    * is don't care, BRDDAT7 is internal 68.  The cable is
7405    * present if the bit is 0
7406    */
7407   brdctl = read_brdctl(p);
7408   *int_68 = !(brdctl & BRDDAT7);
7409
7410   /*
7411    * Set the bank bit in brdctl and then read the external cable state
7412    * and the EEPROM status
7413    */
7414   write_brdctl(p, BRDDAT5);
7415   brdctl = read_brdctl(p);
7416
7417   *ext_68 = !(brdctl & BRDDAT6);
7418   *eeprom = !(brdctl & BRDDAT7);
7419
7420   /*
7421    * We're done, the calling function will release the SEEPROM for us
7422    */
7423 }
7424
7425 /*+F*************************************************************************
7426  * Function:
7427  *   aic787x_cable_detect
7428  *
7429  * Description:
7430  *   Detect the cables that are present on aic787x class controller chips
7431  *
7432  * NOTE: This function assumes the SEEPROM will have already been acquired
7433  *       prior to invocation of this function.
7434  *-F*************************************************************************/
7435 static void
7436 aic787x_cable_detect(struct aic7xxx_host *p, int *int_50, int *int_68,
7437     int *ext_present, int *eeprom)
7438 {
7439   unsigned char brdctl;
7440
7441   /*
7442    * First read the status of our cables.  Set the rom bank to
7443    * 0 since the bank setting serves as a multiplexor for the
7444    * cable detection logic.  BRDDAT5 controls the bank switch.
7445    */
7446   write_brdctl(p, 0);
7447
7448   /*
7449    * Now we read the state of the two internal connectors.  BRDDAT6
7450    * is internal 50, BRDDAT7 is internal 68.  For each, the cable is
7451    * present if the bit is 0
7452    */
7453   brdctl = read_brdctl(p);
7454   *int_50 = !(brdctl & BRDDAT6);
7455   *int_68 = !(brdctl & BRDDAT7);
7456
7457   /*
7458    * Set the bank bit in brdctl and then read the external cable state
7459    * and the EEPROM status
7460    */
7461   write_brdctl(p, BRDDAT5);
7462   brdctl = read_brdctl(p);
7463
7464   *ext_present = !(brdctl & BRDDAT6);
7465   *eeprom = !(brdctl & BRDDAT7);
7466
7467   /*
7468    * We're done, the calling function will release the SEEPROM for us
7469    */
7470 }
7471
7472 /*+F*************************************************************************
7473  * Function:
7474  *   aic787x_ultra2_term_detect
7475  *
7476  * Description:
7477  *   Detect the termination settings present on ultra2 class controllers
7478  *
7479  * NOTE: This function assumes the SEEPROM will have already been acquired
7480  *       prior to invocation of this function.
7481  *-F*************************************************************************/
7482 static void
7483 aic7xxx_ultra2_term_detect(struct aic7xxx_host *p, int *enableSE_low,
7484                            int *enableSE_high, int *enableLVD_low,
7485                            int *enableLVD_high, int *eprom_present)
7486 {
7487   unsigned char brdctl;
7488
7489   brdctl = read_brdctl(p);
7490
7491   *eprom_present  = (brdctl & BRDDAT7);
7492   *enableSE_high  = (brdctl & BRDDAT6);
7493   *enableSE_low   = (brdctl & BRDDAT5);
7494   *enableLVD_high = (brdctl & BRDDAT4);
7495   *enableLVD_low  = (brdctl & BRDDAT3);
7496 }
7497
7498 /*+F*************************************************************************
7499  * Function:
7500  *   configure_termination
7501  *
7502  * Description:
7503  *   Configures the termination settings on PCI adapters that have
7504  *   SEEPROMs available.
7505  *-F*************************************************************************/
7506 static void
7507 configure_termination(struct aic7xxx_host *p)
7508 {
7509   int internal50_present = 0;
7510   int internal68_present = 0;
7511   int external_present = 0;
7512   int eprom_present = 0;
7513   int enableSE_low = 0;
7514   int enableSE_high = 0;
7515   int enableLVD_low = 0;
7516   int enableLVD_high = 0;
7517   unsigned char brddat = 0;
7518   unsigned char max_target = 0;
7519   unsigned char sxfrctl1 = aic_inb(p, SXFRCTL1);
7520
7521   if (acquire_seeprom(p))
7522   {
7523     if (p->features & (AHC_WIDE|AHC_TWIN))
7524       max_target = 16;
7525     else
7526       max_target = 8;
7527     aic_outb(p, SEEMS | SEECS, SEECTL);
7528     sxfrctl1 &= ~STPWEN;
7529     /*
7530      * The termination/cable detection logic is split into three distinct
7531      * groups.  Ultra2 and later controllers, 2940UW-Pro controllers, and
7532      * older 7850, 7860, 7870, 7880, and 7895 controllers.  Each has its
7533      * own unique way of detecting their cables and writing the results
7534      * back to the card.
7535      */
7536     if (p->features & AHC_ULTRA2)
7537     {
7538       /*
7539        * As long as user hasn't overridden term settings, always check the
7540        * cable detection logic
7541        */
7542       if (aic7xxx_override_term == -1)
7543       {
7544         aic7xxx_ultra2_term_detect(p, &enableSE_low, &enableSE_high,
7545                                    &enableLVD_low, &enableLVD_high,
7546                                    &eprom_present);
7547       }
7548       
7549       /*
7550        * If the user is overriding settings, then they have been preserved
7551        * to here as fake adapter_control entries.  Parse them and allow
7552        * them to override the detected settings (if we even did detection).
7553        */
7554       if (!(p->adapter_control & CFSEAUTOTERM))
7555       {
7556         enableSE_low = (p->adapter_control & CFSTERM);
7557         enableSE_high = (p->adapter_control & CFWSTERM);
7558       }
7559       if (!(p->adapter_control & CFAUTOTERM))
7560       {
7561         enableLVD_low = enableLVD_high = (p->adapter_control & CFLVDSTERM);
7562       }
7563
7564       /*
7565        * Now take those settings that we have and translate them into the
7566        * values that must be written into the registers.
7567        *
7568        * Flash Enable = BRDDAT7
7569        * Secondary High Term Enable = BRDDAT6
7570        * Secondary Low Term Enable = BRDDAT5
7571        * LVD/Primary High Term Enable = BRDDAT4
7572        * LVD/Primary Low Term Enable = STPWEN bit in SXFRCTL1
7573        */
7574       if (enableLVD_low != 0)
7575       {
7576         sxfrctl1 |= STPWEN;
7577         p->flags |= AHC_TERM_ENB_LVD;
7578         if (aic7xxx_verbose & VERBOSE_PROBE2)
7579           printk(KERN_INFO "(scsi%d) LVD/Primary Low byte termination "
7580                  "Enabled\n", p->host_no);
7581       }
7582           
7583       if (enableLVD_high != 0)
7584       {
7585         brddat |= BRDDAT4;
7586         if (aic7xxx_verbose & VERBOSE_PROBE2)
7587           printk(KERN_INFO "(scsi%d) LVD/Primary High byte termination "
7588                  "Enabled\n", p->host_no);
7589       }
7590
7591       if (enableSE_low != 0)
7592       {
7593         brddat |= BRDDAT5;
7594         if (aic7xxx_verbose & VERBOSE_PROBE2)
7595           printk(KERN_INFO "(scsi%d) Secondary Low byte termination "
7596                  "Enabled\n", p->host_no);
7597       }
7598
7599       if (enableSE_high != 0)
7600       {
7601         brddat |= BRDDAT6;
7602         if (aic7xxx_verbose & VERBOSE_PROBE2)
7603           printk(KERN_INFO "(scsi%d) Secondary High byte termination "
7604                  "Enabled\n", p->host_no);
7605       }
7606     }
7607     else if (p->features & AHC_NEW_AUTOTERM)
7608     {
7609       /*
7610        * The 50 pin connector termination is controlled by STPWEN in the
7611        * SXFRCTL1 register.  Since the Adaptec docs typically say the
7612        * controller is not allowed to be in the middle of a cable and
7613        * this is the only connection on that stub of the bus, there is
7614        * no need to even check for narrow termination, it's simply
7615        * always on.
7616        */
7617       sxfrctl1 |= STPWEN;
7618       if (aic7xxx_verbose & VERBOSE_PROBE2)
7619         printk(KERN_INFO "(scsi%d) Narrow channel termination Enabled\n",
7620                p->host_no);
7621
7622       if (p->adapter_control & CFAUTOTERM)
7623       {
7624         aic2940_uwpro_wide_cable_detect(p, &internal68_present,
7625                                         &external_present,
7626                                         &eprom_present);
7627         printk(KERN_INFO "(scsi%d) Cables present (Int-50 %s, Int-68 %s, "
7628                "Ext-68 %s)\n", p->host_no,
7629                "Don't Care",
7630                internal68_present ? "YES" : "NO",
7631                external_present ? "YES" : "NO");
7632         if (aic7xxx_verbose & VERBOSE_PROBE2)
7633           printk(KERN_INFO "(scsi%d) EEPROM %s present.\n", p->host_no,
7634                eprom_present ? "is" : "is not");
7635         if (internal68_present && external_present)
7636         {
7637           brddat = 0;
7638           p->flags &= ~AHC_TERM_ENB_SE_HIGH;
7639           if (aic7xxx_verbose & VERBOSE_PROBE2)
7640             printk(KERN_INFO "(scsi%d) Wide channel termination Disabled\n",
7641                    p->host_no);
7642         }
7643         else
7644         {
7645           brddat = BRDDAT6;
7646           p->flags |= AHC_TERM_ENB_SE_HIGH;
7647           if (aic7xxx_verbose & VERBOSE_PROBE2)
7648             printk(KERN_INFO "(scsi%d) Wide channel termination Enabled\n",
7649                    p->host_no);
7650         }
7651       }
7652       else
7653       {
7654         /*
7655          * The termination of the Wide channel is done more like normal
7656          * though, and the setting of this termination is done by writing
7657          * either a 0 or 1 to BRDDAT6 of the BRDDAT register
7658          */
7659         if (p->adapter_control & CFWSTERM)
7660         {
7661           brddat = BRDDAT6;
7662           p->flags |= AHC_TERM_ENB_SE_HIGH;
7663           if (aic7xxx_verbose & VERBOSE_PROBE2)
7664             printk(KERN_INFO "(scsi%d) Wide channel termination Enabled\n",
7665                    p->host_no);
7666         }
7667         else
7668         {
7669           brddat = 0;
7670         }
7671       }
7672     }
7673     else
7674     {
7675       if (p->adapter_control & CFAUTOTERM)
7676       {
7677         if (p->flags & AHC_MOTHERBOARD)
7678         {
7679           printk(KERN_INFO "(scsi%d) Warning - detected auto-termination\n",
7680                  p->host_no);
7681           printk(KERN_INFO "(scsi%d) Please verify driver detected settings "
7682             "are correct.\n", p->host_no);
7683           printk(KERN_INFO "(scsi%d) If not, then please properly set the "
7684             "device termination\n", p->host_no);
7685           printk(KERN_INFO "(scsi%d) in the Adaptec SCSI BIOS by hitting "
7686             "CTRL-A when prompted\n", p->host_no);
7687           printk(KERN_INFO "(scsi%d) during machine bootup.\n", p->host_no);
7688         }
7689         /* Configure auto termination. */
7690
7691         if ( (p->chip & AHC_CHIPID_MASK) >= AHC_AIC7870 )
7692         {
7693           aic787x_cable_detect(p, &internal50_present, &internal68_present,
7694             &external_present, &eprom_present);
7695         }
7696         else
7697         {
7698           aic785x_cable_detect(p, &internal50_present, &external_present,
7699             &eprom_present);
7700         }
7701
7702         if (max_target <= 8)
7703           internal68_present = 0;
7704
7705         if (max_target > 8)
7706         {
7707           printk(KERN_INFO "(scsi%d) Cables present (Int-50 %s, Int-68 %s, "
7708                  "Ext-68 %s)\n", p->host_no,
7709                  internal50_present ? "YES" : "NO",
7710                  internal68_present ? "YES" : "NO",
7711                  external_present ? "YES" : "NO");
7712         }
7713         else
7714         {
7715           printk(KERN_INFO "(scsi%d) Cables present (Int-50 %s, Ext-50 %s)\n",
7716                  p->host_no,
7717                  internal50_present ? "YES" : "NO",
7718                  external_present ? "YES" : "NO");
7719         }
7720         if (aic7xxx_verbose & VERBOSE_PROBE2)
7721           printk(KERN_INFO "(scsi%d) EEPROM %s present.\n", p->host_no,
7722                eprom_present ? "is" : "is not");
7723
7724         /*
7725          * Now set the termination based on what we found.  BRDDAT6
7726          * controls wide termination enable.
7727          * Flash Enable = BRDDAT7
7728          * SE High Term Enable = BRDDAT6
7729          */
7730         if (internal50_present && internal68_present && external_present)
7731         {
7732           printk(KERN_INFO "(scsi%d) Illegal cable configuration!!  Only two\n",
7733                  p->host_no);
7734           printk(KERN_INFO "(scsi%d) connectors on the SCSI controller may be "
7735                  "in use at a time!\n", p->host_no);
7736           /*
7737            * Force termination (low and high byte) on.  This is safer than
7738            * leaving it completely off, especially since this message comes
7739            * most often from motherboard controllers that don't even have 3
7740            * connectors, but instead are failing the cable detection.
7741            */
7742           internal50_present = external_present = 0;
7743           enableSE_high = enableSE_low = 1;
7744         }
7745
7746         if ((max_target > 8) &&
7747             ((external_present == 0) || (internal68_present == 0)) )
7748         {
7749           brddat |= BRDDAT6;
7750           p->flags |= AHC_TERM_ENB_SE_HIGH;
7751           if (aic7xxx_verbose & VERBOSE_PROBE2)
7752             printk(KERN_INFO "(scsi%d) SE High byte termination Enabled\n",
7753                    p->host_no);
7754         }
7755
7756         if ( ((internal50_present ? 1 : 0) +
7757               (internal68_present ? 1 : 0) +
7758               (external_present   ? 1 : 0)) <= 1 )
7759         {
7760           sxfrctl1 |= STPWEN;
7761           p->flags |= AHC_TERM_ENB_SE_LOW;
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       else /* p->adapter_control & CFAUTOTERM */
7768       {
7769         if (p->adapter_control & CFSTERM)
7770         {
7771           sxfrctl1 |= STPWEN;
7772           if (aic7xxx_verbose & VERBOSE_PROBE2)
7773             printk(KERN_INFO "(scsi%d) SE Low byte termination Enabled\n",
7774                    p->host_no);
7775         }
7776
7777         if (p->adapter_control & CFWSTERM)
7778         {
7779           brddat |= BRDDAT6;
7780           if (aic7xxx_verbose & VERBOSE_PROBE2)
7781             printk(KERN_INFO "(scsi%d) SE High byte termination Enabled\n",
7782                    p->host_no);
7783         }
7784       }
7785     }
7786
7787     aic_outb(p, sxfrctl1, SXFRCTL1);
7788     write_brdctl(p, brddat);
7789     release_seeprom(p);
7790   }
7791 }
7792
7793 /*+F*************************************************************************
7794  * Function:
7795  *   detect_maxscb
7796  *
7797  * Description:
7798  *   Detects the maximum number of SCBs for the controller and returns
7799  *   the count and a mask in p (p->maxscbs, p->qcntmask).
7800  *-F*************************************************************************/
7801 static void
7802 detect_maxscb(struct aic7xxx_host *p)
7803 {
7804   int i;
7805
7806   /*
7807    * It's possible that we've already done this for multichannel
7808    * adapters.
7809    */
7810   if (p->scb_data->maxhscbs == 0)
7811   {
7812     /*
7813      * We haven't initialized the SCB settings yet.  Walk the SCBs to
7814      * determince how many there are.
7815      */
7816     aic_outb(p, 0, FREE_SCBH);
7817
7818     for (i = 0; i < AIC7XXX_MAXSCB; i++)
7819     {
7820       aic_outb(p, i, SCBPTR);
7821       aic_outb(p, i, SCB_CONTROL);
7822       if (aic_inb(p, SCB_CONTROL) != i)
7823         break;
7824       aic_outb(p, 0, SCBPTR);
7825       if (aic_inb(p, SCB_CONTROL) != 0)
7826         break;
7827
7828       aic_outb(p, i, SCBPTR);
7829       aic_outb(p, 0, SCB_CONTROL);   /* Clear the control byte. */
7830       aic_outb(p, i + 1, SCB_NEXT);  /* Set the next pointer. */
7831       aic_outb(p, SCB_LIST_NULL, SCB_TAG);  /* Make the tag invalid. */
7832       aic_outb(p, SCB_LIST_NULL, SCB_BUSYTARGETS);  /* no busy untagged */
7833       aic_outb(p, SCB_LIST_NULL, SCB_BUSYTARGETS+1);/* targets active yet */
7834       aic_outb(p, SCB_LIST_NULL, SCB_BUSYTARGETS+2);
7835       aic_outb(p, SCB_LIST_NULL, SCB_BUSYTARGETS+3);
7836     }
7837
7838     /* Make sure the last SCB terminates the free list. */
7839     aic_outb(p, i - 1, SCBPTR);
7840     aic_outb(p, SCB_LIST_NULL, SCB_NEXT);
7841
7842     /* Ensure we clear the first (0) SCBs control byte. */
7843     aic_outb(p, 0, SCBPTR);
7844     aic_outb(p, 0, SCB_CONTROL);
7845
7846     p->scb_data->maxhscbs = i;
7847     /*
7848      * Use direct indexing instead for speed
7849      */
7850     if ( i == AIC7XXX_MAXSCB )
7851       p->flags &= ~AHC_PAGESCBS;
7852   }
7853
7854 }
7855
7856 /*+F*************************************************************************
7857  * Function:
7858  *   aic7xxx_register
7859  *
7860  * Description:
7861  *   Register a Adaptec aic7xxx chip SCSI controller with the kernel.
7862  *-F*************************************************************************/
7863 static int
7864 aic7xxx_register(struct scsi_host_template *template, struct aic7xxx_host *p,
7865   int reset_delay)
7866 {
7867   int i, result;
7868   int max_targets;
7869   int found = 1;
7870   unsigned char term, scsi_conf;
7871   struct Scsi_Host *host;
7872
7873   host = p->host;
7874
7875   p->scb_data->maxscbs = AIC7XXX_MAXSCB;
7876   host->can_queue = AIC7XXX_MAXSCB;
7877   host->cmd_per_lun = 3;
7878   host->sg_tablesize = AIC7XXX_MAX_SG;
7879   host->this_id = p->scsi_id;
7880   host->io_port = p->base;
7881   host->n_io_port = 0xFF;
7882   host->base = p->mbase;
7883   host->irq = p->irq;
7884   if (p->features & AHC_WIDE)
7885   {
7886     host->max_id = 16;
7887   }
7888   if (p->features & AHC_TWIN)
7889   {
7890     host->max_channel = 1;
7891   }
7892
7893   p->host = host;
7894   p->host_no = host->host_no;
7895   host->unique_id = p->instance;
7896   p->isr_count = 0;
7897   p->next = NULL;
7898   p->completeq.head = NULL;
7899   p->completeq.tail = NULL;
7900   scbq_init(&p->scb_data->free_scbs);
7901   scbq_init(&p->waiting_scbs);
7902   INIT_LIST_HEAD(&p->aic_devs);
7903
7904   /*
7905    * We currently have no commands of any type
7906    */
7907   p->qinfifonext = 0;
7908   p->qoutfifonext = 0;
7909
7910   printk(KERN_INFO "(scsi%d) <%s> found at ", p->host_no,
7911     board_names[p->board_name_index]);
7912   switch(p->chip)
7913   {
7914     case (AHC_AIC7770|AHC_EISA):
7915       printk("EISA slot %d\n", p->pci_device_fn);
7916       break;
7917     case (AHC_AIC7770|AHC_VL):
7918       printk("VLB slot %d\n", p->pci_device_fn);
7919       break;
7920     default:
7921       printk("PCI %d/%d/%d\n", p->pci_bus, PCI_SLOT(p->pci_device_fn),
7922         PCI_FUNC(p->pci_device_fn));
7923       break;
7924   }
7925   if (p->features & AHC_TWIN)
7926   {
7927     printk(KERN_INFO "(scsi%d) Twin Channel, A SCSI ID %d, B SCSI ID %d, ",
7928            p->host_no, p->scsi_id, p->scsi_id_b);
7929   }
7930   else
7931   {
7932     char *channel;
7933
7934     channel = "";
7935
7936     if ((p->flags & AHC_MULTI_CHANNEL) != 0)
7937     {
7938       channel = " A";
7939
7940       if ( (p->flags & (AHC_CHNLB|AHC_CHNLC)) != 0 )
7941       {
7942         channel = (p->flags & AHC_CHNLB) ? " B" : " C";
7943       }
7944     }
7945     if (p->features & AHC_WIDE)
7946     {
7947       printk(KERN_INFO "(scsi%d) Wide ", p->host_no);
7948     }
7949     else
7950     {
7951       printk(KERN_INFO "(scsi%d) Narrow ", p->host_no);
7952     }
7953     printk("Channel%s, SCSI ID=%d, ", channel, p->scsi_id);
7954   }
7955   aic_outb(p, 0, SEQ_FLAGS);
7956
7957   detect_maxscb(p);
7958
7959   printk("%d/%d SCBs\n", p->scb_data->maxhscbs, p->scb_data->maxscbs);
7960   if (aic7xxx_verbose & VERBOSE_PROBE2)
7961   {
7962     printk(KERN_INFO "(scsi%d) BIOS %sabled, IO Port 0x%lx, IRQ %d\n",
7963       p->host_no, (p->flags & AHC_BIOS_ENABLED) ? "en" : "dis",
7964       p->base, p->irq);
7965     printk(KERN_INFO "(scsi%d) IO Memory at 0x%lx, MMAP Memory at %p\n",
7966       p->host_no, p->mbase, p->maddr);
7967   }
7968
7969 #ifdef CONFIG_PCI
7970   /*
7971    * Now that we know our instance number, we can set the flags we need to
7972    * force termination if need be.
7973    */
7974   if (aic7xxx_stpwlev != -1)
7975   {
7976     /*
7977      * This option only applies to PCI controllers.
7978      */
7979     if ( (p->chip & ~AHC_CHIPID_MASK) == AHC_PCI)
7980     {
7981       unsigned char devconfig;
7982
7983       pci_read_config_byte(p->pdev, DEVCONFIG, &devconfig);
7984       if ( (aic7xxx_stpwlev >> p->instance) & 0x01 )
7985       {
7986         devconfig |= STPWLEVEL;
7987         if (aic7xxx_verbose & VERBOSE_PROBE2)
7988           printk("(scsi%d) Force setting STPWLEVEL bit\n", p->host_no);
7989       }
7990       else
7991       {
7992         devconfig &= ~STPWLEVEL;
7993         if (aic7xxx_verbose & VERBOSE_PROBE2)
7994           printk("(scsi%d) Force clearing STPWLEVEL bit\n", p->host_no);
7995       }
7996       pci_write_config_byte(p->pdev, DEVCONFIG, devconfig);
7997     }
7998   }
7999 #endif
8000
8001   /*
8002    * That took care of devconfig and stpwlev, now for the actual termination
8003    * settings.
8004    */
8005   if (aic7xxx_override_term != -1)
8006   {
8007     /*
8008      * Again, this only applies to PCI controllers.  We don't have problems
8009      * with the termination on 274x controllers to the best of my knowledge.
8010      */
8011     if ( (p->chip & ~AHC_CHIPID_MASK) == AHC_PCI)
8012     {
8013       unsigned char term_override;
8014
8015       term_override = ( (aic7xxx_override_term >> (p->instance * 4)) & 0x0f);
8016       p->adapter_control &= 
8017         ~(CFSTERM|CFWSTERM|CFLVDSTERM|CFAUTOTERM|CFSEAUTOTERM);
8018       if ( (p->features & AHC_ULTRA2) && (term_override & 0x0c) )
8019       {
8020         p->adapter_control |= CFLVDSTERM;
8021       }
8022       if (term_override & 0x02)
8023       {
8024         p->adapter_control |= CFWSTERM;
8025       }
8026       if (term_override & 0x01)
8027       {
8028         p->adapter_control |= CFSTERM;
8029       }
8030     }
8031   }
8032
8033   if ( (p->flags & AHC_SEEPROM_FOUND) || (aic7xxx_override_term != -1) )
8034   {
8035     if (p->features & AHC_SPIOCAP)
8036     {
8037       if ( aic_inb(p, SPIOCAP) & SSPIOCPS )
8038       /*
8039        * Update the settings in sxfrctl1 to match the termination
8040        * settings.
8041        */
8042         configure_termination(p);
8043     }
8044     else if ((p->chip & AHC_CHIPID_MASK) >= AHC_AIC7870)
8045     {
8046       configure_termination(p);
8047     }
8048   }
8049
8050   /*
8051    * Set the SCSI Id, SXFRCTL0, SXFRCTL1, and SIMODE1, for both channels
8052    */
8053   if (p->features & AHC_TWIN)
8054   {
8055     /* Select channel B */
8056     aic_outb(p, aic_inb(p, SBLKCTL) | SELBUSB, SBLKCTL);
8057
8058     if ((p->flags & AHC_SEEPROM_FOUND) || (aic7xxx_override_term != -1))
8059       term = (aic_inb(p, SXFRCTL1) & STPWEN);
8060     else
8061       term = ((p->flags & AHC_TERM_ENB_B) ? STPWEN : 0);
8062
8063     aic_outb(p, p->scsi_id_b, SCSIID);
8064     scsi_conf = aic_inb(p, SCSICONF + 1);
8065     aic_outb(p, DFON | SPIOEN, SXFRCTL0);
8066     aic_outb(p, (scsi_conf & ENSPCHK) | aic7xxx_seltime | term | 
8067          ENSTIMER | ACTNEGEN, SXFRCTL1);
8068     aic_outb(p, 0, SIMODE0);
8069     aic_outb(p, ENSELTIMO | ENSCSIRST | ENSCSIPERR, SIMODE1);
8070     aic_outb(p, 0, SCSIRATE);
8071
8072     /* Select channel A */
8073     aic_outb(p, aic_inb(p, SBLKCTL) & ~SELBUSB, SBLKCTL);
8074   }
8075
8076   if (p->features & AHC_ULTRA2)
8077   {
8078     aic_outb(p, p->scsi_id, SCSIID_ULTRA2);
8079   }
8080   else
8081   {
8082     aic_outb(p, p->scsi_id, SCSIID);
8083   }
8084   if ((p->flags & AHC_SEEPROM_FOUND) || (aic7xxx_override_term != -1))
8085     term = (aic_inb(p, SXFRCTL1) & STPWEN);
8086   else
8087     term = ((p->flags & (AHC_TERM_ENB_A|AHC_TERM_ENB_LVD)) ? STPWEN : 0);
8088   scsi_conf = aic_inb(p, SCSICONF);
8089   aic_outb(p, DFON | SPIOEN, SXFRCTL0);
8090   aic_outb(p, (scsi_conf & ENSPCHK) | aic7xxx_seltime | term | 
8091        ENSTIMER | ACTNEGEN, SXFRCTL1);
8092   aic_outb(p, 0, SIMODE0);
8093   /*
8094    * If we are a cardbus adapter then don't enable SCSI reset detection.
8095    * We shouldn't likely be sharing SCSI busses with someone else, and
8096    * if we don't have a cable currently plugged into the controller then
8097    * we won't have a power source for the SCSI termination, which means
8098    * we'll see infinite incoming bus resets.
8099    */
8100   if(p->flags & AHC_NO_STPWEN)
8101     aic_outb(p, ENSELTIMO | ENSCSIPERR, SIMODE1);
8102   else
8103     aic_outb(p, ENSELTIMO | ENSCSIRST | ENSCSIPERR, SIMODE1);
8104   aic_outb(p, 0, SCSIRATE);
8105   if ( p->features & AHC_ULTRA2)
8106     aic_outb(p, 0, SCSIOFFSET);
8107
8108   /*
8109    * Look at the information that board initialization or the board
8110    * BIOS has left us. In the lower four bits of each target's
8111    * scratch space any value other than 0 indicates that we should
8112    * initiate synchronous transfers. If it's zero, the user or the
8113    * BIOS has decided to disable synchronous negotiation to that
8114    * target so we don't activate the needsdtr flag.
8115    */
8116   if ((p->features & (AHC_TWIN|AHC_WIDE)) == 0)
8117   {
8118     max_targets = 8;
8119   }
8120   else
8121   {
8122     max_targets = 16;
8123   }
8124
8125   if (!(aic7xxx_no_reset))
8126   {
8127     /*
8128      * If we reset the bus, then clear the transfer settings, else leave
8129      * them be.
8130      */
8131     aic_outb(p, 0, ULTRA_ENB);
8132     aic_outb(p, 0, ULTRA_ENB + 1);
8133     p->ultraenb = 0;
8134   }
8135
8136   /*
8137    * Allocate enough hardware scbs to handle the maximum number of
8138    * concurrent transactions we can have.  We have to make sure that
8139    * the allocated memory is contiguous memory.  The Linux kmalloc
8140    * routine should only allocate contiguous memory, but note that
8141    * this could be a problem if kmalloc() is changed.
8142    */
8143   {
8144     size_t array_size;
8145     unsigned int hscb_physaddr;
8146
8147     array_size = p->scb_data->maxscbs * sizeof(struct aic7xxx_hwscb);
8148     if (p->scb_data->hscbs == NULL)
8149     {
8150       /* pci_alloc_consistent enforces the alignment already and
8151        * clears the area as well.
8152        */
8153       p->scb_data->hscbs = pci_alloc_consistent(p->pdev, array_size,
8154                                                 &p->scb_data->hscbs_dma);
8155       /* We have to use pci_free_consistent, not kfree */
8156       p->scb_data->hscb_kmalloc_ptr = NULL;
8157       p->scb_data->hscbs_dma_len = array_size;
8158     }
8159     if (p->scb_data->hscbs == NULL)
8160     {
8161       printk("(scsi%d) Unable to allocate hardware SCB array; "
8162              "failing detection.\n", p->host_no);
8163       aic_outb(p, 0, SIMODE1);
8164       p->irq = 0;
8165       return(0);
8166     }
8167
8168     hscb_physaddr = p->scb_data->hscbs_dma;
8169     aic_outb(p, hscb_physaddr & 0xFF, HSCB_ADDR);
8170     aic_outb(p, (hscb_physaddr >> 8) & 0xFF, HSCB_ADDR + 1);
8171     aic_outb(p, (hscb_physaddr >> 16) & 0xFF, HSCB_ADDR + 2);
8172     aic_outb(p, (hscb_physaddr >> 24) & 0xFF, HSCB_ADDR + 3);
8173
8174     /* Set up the fifo areas at the same time */
8175     p->untagged_scbs = pci_alloc_consistent(p->pdev, 3*256, &p->fifo_dma);
8176     if (p->untagged_scbs == NULL)
8177     {
8178       printk("(scsi%d) Unable to allocate hardware FIFO arrays; "
8179              "failing detection.\n", p->host_no);
8180       p->irq = 0;
8181       return(0);
8182     }
8183
8184     p->qoutfifo = p->untagged_scbs + 256;
8185     p->qinfifo = p->qoutfifo + 256;
8186     for (i = 0; i < 256; i++)
8187     {
8188       p->untagged_scbs[i] = SCB_LIST_NULL;
8189       p->qinfifo[i] = SCB_LIST_NULL;
8190       p->qoutfifo[i] = SCB_LIST_NULL;
8191     }
8192
8193     hscb_physaddr = p->fifo_dma;
8194     aic_outb(p, hscb_physaddr & 0xFF, SCBID_ADDR);
8195     aic_outb(p, (hscb_physaddr >> 8) & 0xFF, SCBID_ADDR + 1);
8196     aic_outb(p, (hscb_physaddr >> 16) & 0xFF, SCBID_ADDR + 2);
8197     aic_outb(p, (hscb_physaddr >> 24) & 0xFF, SCBID_ADDR + 3);
8198   }
8199
8200   /* The Q-FIFOs we just set up are all empty */
8201   aic_outb(p, 0, QINPOS);
8202   aic_outb(p, 0, KERNEL_QINPOS);
8203   aic_outb(p, 0, QOUTPOS);
8204
8205   if(p->features & AHC_QUEUE_REGS)
8206   {
8207     aic_outb(p, SCB_QSIZE_256, QOFF_CTLSTA);
8208     aic_outb(p, 0, SDSCB_QOFF);
8209     aic_outb(p, 0, SNSCB_QOFF);
8210     aic_outb(p, 0, HNSCB_QOFF);
8211   }
8212
8213   /*
8214    * We don't have any waiting selections or disconnected SCBs.
8215    */
8216   aic_outb(p, SCB_LIST_NULL, WAITING_SCBH);
8217   aic_outb(p, SCB_LIST_NULL, DISCONNECTED_SCBH);
8218
8219   /*
8220    * Message out buffer starts empty
8221    */
8222   aic_outb(p, MSG_NOOP, MSG_OUT);
8223   aic_outb(p, MSG_NOOP, LAST_MSG);
8224
8225   /*
8226    * Set all the other asundry items that haven't been set yet.
8227    * This includes just dumping init values to a lot of registers simply
8228    * to make sure they've been touched and are ready for use parity wise
8229    * speaking.
8230    */
8231   aic_outb(p, 0, TMODE_CMDADDR);
8232   aic_outb(p, 0, TMODE_CMDADDR + 1);
8233   aic_outb(p, 0, TMODE_CMDADDR + 2);
8234   aic_outb(p, 0, TMODE_CMDADDR + 3);
8235   aic_outb(p, 0, TMODE_CMDADDR_NEXT);
8236
8237   /*
8238    * Link us into the list of valid hosts
8239    */
8240   p->next = first_aic7xxx;
8241   first_aic7xxx = p;
8242
8243   /*
8244    * Allocate the first set of scbs for this controller.  This is to stream-
8245    * line code elsewhere in the driver.  If we have to check for the existence
8246    * of scbs in certain code sections, it slows things down.  However, as
8247    * soon as we register the IRQ for this card, we could get an interrupt that
8248    * includes possibly the SCSI_RSTI interrupt.  If we catch that interrupt
8249    * then we are likely to segfault if we don't have at least one chunk of
8250    * SCBs allocated or add checks all through the reset code to make sure
8251    * that the SCBs have been allocated which is an invalid running condition
8252    * and therefore I think it's preferable to simply pre-allocate the first
8253    * chunk of SCBs.
8254    */
8255   aic7xxx_allocate_scb(p);
8256
8257   /*
8258    * Load the sequencer program, then re-enable the board -
8259    * resetting the AIC-7770 disables it, leaving the lights
8260    * on with nobody home.
8261    */
8262   aic7xxx_loadseq(p);
8263
8264   /*
8265    * Make sure the AUTOFLUSHDIS bit is *not* set in the SBLKCTL register
8266    */
8267   aic_outb(p, aic_inb(p, SBLKCTL) & ~AUTOFLUSHDIS, SBLKCTL);
8268
8269   if ( (p->chip & AHC_CHIPID_MASK) == AHC_AIC7770 )
8270   {
8271     aic_outb(p, ENABLE, BCTL);  /* Enable the boards BUS drivers. */
8272   }
8273
8274   if ( !(aic7xxx_no_reset) )
8275   {
8276     if (p->features & AHC_TWIN)
8277     {
8278       if (aic7xxx_verbose & VERBOSE_PROBE2)
8279         printk(KERN_INFO "(scsi%d) Resetting channel B\n", p->host_no);
8280       aic_outb(p, aic_inb(p, SBLKCTL) | SELBUSB, SBLKCTL);
8281       aic7xxx_reset_current_bus(p);
8282       aic_outb(p, aic_inb(p, SBLKCTL) & ~SELBUSB, SBLKCTL);
8283     }
8284     /* Reset SCSI bus A. */
8285     if (aic7xxx_verbose & VERBOSE_PROBE2)
8286     {  /* In case we are a 3940, 3985, or 7895, print the right channel */
8287       char *channel = "";
8288       if (p->flags & AHC_MULTI_CHANNEL)
8289       {
8290         channel = " A";
8291         if (p->flags & (AHC_CHNLB|AHC_CHNLC))
8292           channel = (p->flags & AHC_CHNLB) ? " B" : " C";
8293       }
8294       printk(KERN_INFO "(scsi%d) Resetting channel%s\n", p->host_no, channel);
8295     }
8296     
8297     aic7xxx_reset_current_bus(p);
8298
8299   }
8300   else
8301   {
8302     if (!reset_delay)
8303     {
8304       printk(KERN_INFO "(scsi%d) Not resetting SCSI bus.  Note: Don't use "
8305              "the no_reset\n", p->host_no);
8306       printk(KERN_INFO "(scsi%d) option unless you have a verifiable need "
8307              "for it.\n", p->host_no);
8308     }
8309   }
8310   
8311   /*
8312    * Register IRQ with the kernel.  Only allow sharing IRQs with
8313    * PCI devices.
8314    */
8315   if (!(p->chip & AHC_PCI))
8316   {
8317     result = (request_irq(p->irq, do_aic7xxx_isr, 0, "aic7xxx", p));
8318   }
8319   else
8320   {
8321     result = (request_irq(p->irq, do_aic7xxx_isr, IRQF_SHARED,
8322               "aic7xxx", p));
8323     if (result < 0)
8324     {
8325       result = (request_irq(p->irq, do_aic7xxx_isr, IRQF_DISABLED | IRQF_SHARED,
8326               "aic7xxx", p));
8327     }
8328   }
8329   if (result < 0)
8330   {
8331     printk(KERN_WARNING "(scsi%d) Couldn't register IRQ %d, ignoring "
8332            "controller.\n", p->host_no, p->irq);
8333     aic_outb(p, 0, SIMODE1);
8334     p->irq = 0;
8335     return (0);
8336   }
8337
8338   if(aic_inb(p, INTSTAT) & INT_PEND)
8339     printk(INFO_LEAD "spurious interrupt during configuration, cleared.\n",
8340       p->host_no, -1, -1 , -1);
8341   aic7xxx_clear_intstat(p);
8342
8343   unpause_sequencer(p, /* unpause_always */ TRUE);
8344
8345   return (found);
8346 }
8347
8348 /*+F*************************************************************************
8349  * Function:
8350  *   aic7xxx_chip_reset
8351  *
8352  * Description:
8353  *   Perform a chip reset on the aic7xxx SCSI controller.  The controller
8354  *   is paused upon return.
8355  *-F*************************************************************************/
8356 static int
8357 aic7xxx_chip_reset(struct aic7xxx_host *p)
8358 {
8359   unsigned char sblkctl;
8360   int wait;
8361
8362   /*
8363    * For some 274x boards, we must clear the CHIPRST bit and pause
8364    * the sequencer. For some reason, this makes the driver work.
8365    */
8366   aic_outb(p, PAUSE | CHIPRST, HCNTRL);
8367
8368   /*
8369    * In the future, we may call this function as a last resort for
8370    * error handling.  Let's be nice and not do any unnecessary delays.
8371    */
8372   wait = 1000;  /* 1 msec (1000 * 1 msec) */
8373   while (--wait && !(aic_inb(p, HCNTRL) & CHIPRSTACK))
8374   {
8375     udelay(1);  /* 1 usec */
8376   }
8377
8378   pause_sequencer(p);
8379
8380   sblkctl = aic_inb(p, SBLKCTL) & (SELBUSB|SELWIDE);
8381   if (p->chip & AHC_PCI)
8382     sblkctl &= ~SELBUSB;
8383   switch( sblkctl )
8384   {
8385     case 0:  /* normal narrow card */
8386       break;
8387     case 2:  /* Wide card */
8388       p->features |= AHC_WIDE;
8389       break;
8390     case 8:  /* Twin card */
8391       p->features |= AHC_TWIN;
8392       p->flags |= AHC_MULTI_CHANNEL;
8393       break;
8394     default: /* hmmm...we don't know what this is */
8395       printk(KERN_WARNING "aic7xxx: Unsupported adapter type %d, ignoring.\n",
8396         aic_inb(p, SBLKCTL) & 0x0a);
8397       return(-1);
8398   }
8399   return(0);
8400 }
8401
8402 /*+F*************************************************************************
8403  * Function:
8404  *   aic7xxx_alloc
8405  *
8406  * Description:
8407  *   Allocate and initialize a host structure.  Returns NULL upon error
8408  *   and a pointer to a aic7xxx_host struct upon success.
8409  *-F*************************************************************************/
8410 static struct aic7xxx_host *
8411 aic7xxx_alloc(struct scsi_host_template *sht, struct aic7xxx_host *temp)
8412 {
8413   struct aic7xxx_host *p = NULL;
8414   struct Scsi_Host *host;
8415
8416   /*
8417    * Allocate a storage area by registering us with the mid-level
8418    * SCSI layer.
8419    */
8420   host = scsi_register(sht, sizeof(struct aic7xxx_host));
8421
8422   if (host != NULL)
8423   {
8424     p = (struct aic7xxx_host *) host->hostdata;
8425     memset(p, 0, sizeof(struct aic7xxx_host));
8426     *p = *temp;
8427     p->host = host;
8428
8429     p->scb_data = kmalloc(sizeof(scb_data_type), GFP_ATOMIC);
8430     if (p->scb_data != NULL)
8431     {
8432       memset(p->scb_data, 0, sizeof(scb_data_type));
8433       scbq_init (&p->scb_data->free_scbs);
8434     }
8435     else
8436     {
8437       /*
8438        * For some reason we don't have enough memory.  Free the
8439        * allocated memory for the aic7xxx_host struct, and return NULL.
8440        */
8441       release_region(p->base, MAXREG - MINREG);
8442       scsi_unregister(host);
8443       return(NULL);
8444     }
8445     p->host_no = host->host_no;
8446   }
8447   return (p);
8448 }
8449
8450 /*+F*************************************************************************
8451  * Function:
8452  *   aic7xxx_free
8453  *
8454  * Description:
8455  *   Frees and releases all resources associated with an instance of
8456  *   the driver (struct aic7xxx_host *).
8457  *-F*************************************************************************/
8458 static void
8459 aic7xxx_free(struct aic7xxx_host *p)
8460 {
8461   int i;
8462
8463   /*
8464    * Free the allocated hardware SCB space.
8465    */
8466   if (p->scb_data != NULL)
8467   {
8468     struct aic7xxx_scb_dma *scb_dma = NULL;
8469     if (p->scb_data->hscbs != NULL)
8470     {
8471       pci_free_consistent(p->pdev, p->scb_data->hscbs_dma_len,
8472                           p->scb_data->hscbs, p->scb_data->hscbs_dma);
8473       p->scb_data->hscbs = p->scb_data->hscb_kmalloc_ptr = NULL;
8474     }
8475     /*
8476      * Free the driver SCBs.  These were allocated on an as-need
8477      * basis.  We allocated these in groups depending on how many
8478      * we could fit into a given amount of RAM.  The tail SCB for
8479      * these allocations has a pointer to the alloced area.
8480      */
8481     for (i = 0; i < p->scb_data->numscbs; i++)
8482     {
8483       if (p->scb_data->scb_array[i]->scb_dma != scb_dma)
8484       {
8485         scb_dma = p->scb_data->scb_array[i]->scb_dma;
8486         pci_free_consistent(p->pdev, scb_dma->dma_len,
8487                             (void *)((unsigned long)scb_dma->dma_address
8488                                      - scb_dma->dma_offset),
8489                             scb_dma->dma_address);
8490       }
8491       kfree(p->scb_data->scb_array[i]->kmalloc_ptr);
8492       p->scb_data->scb_array[i] = NULL;
8493     }
8494   
8495     /*
8496      * Free the SCB data area.
8497      */
8498     kfree(p->scb_data);
8499   }
8500
8501   pci_free_consistent(p->pdev, 3*256, (void *)p->untagged_scbs, p->fifo_dma);
8502 }
8503
8504 /*+F*************************************************************************
8505  * Function:
8506  *   aic7xxx_load_seeprom
8507  *
8508  * Description:
8509  *   Load the seeprom and configure adapter and target settings.
8510  *   Returns 1 if the load was successful and 0 otherwise.
8511  *-F*************************************************************************/
8512 static void
8513 aic7xxx_load_seeprom(struct aic7xxx_host *p, unsigned char *sxfrctl1)
8514 {
8515   int have_seeprom = 0;
8516   int i, max_targets, mask;
8517   unsigned char scsirate, scsi_conf;
8518   unsigned short scarray[128];
8519   struct seeprom_config *sc = (struct seeprom_config *) scarray;
8520
8521   if (aic7xxx_verbose & VERBOSE_PROBE2)
8522   {
8523     printk(KERN_INFO "aic7xxx: Loading serial EEPROM...");
8524   }
8525   switch (p->chip)
8526   {
8527     case (AHC_AIC7770|AHC_EISA):  /* None of these adapters have seeproms. */
8528       if (aic_inb(p, SCSICONF) & TERM_ENB)
8529         p->flags |= AHC_TERM_ENB_A;
8530       if ( (p->features & AHC_TWIN) && (aic_inb(p, SCSICONF + 1) & TERM_ENB) )
8531         p->flags |= AHC_TERM_ENB_B;
8532       break;
8533
8534     case (AHC_AIC7770|AHC_VL):
8535       have_seeprom = read_284x_seeprom(p, (struct seeprom_config *) scarray);
8536       break;
8537
8538     default:
8539       have_seeprom = read_seeprom(p, (p->flags & (AHC_CHNLB|AHC_CHNLC)),
8540                                   scarray, p->sc_size, p->sc_type);
8541       if (!have_seeprom)
8542       {
8543         if(p->sc_type == C46)
8544           have_seeprom = read_seeprom(p, (p->flags & (AHC_CHNLB|AHC_CHNLC)),
8545                                       scarray, p->sc_size, C56_66);
8546         else
8547           have_seeprom = read_seeprom(p, (p->flags & (AHC_CHNLB|AHC_CHNLC)),
8548                                       scarray, p->sc_size, C46);
8549       }
8550       if (!have_seeprom)
8551       {
8552         p->sc_size = 128;
8553         have_seeprom = read_seeprom(p, 4*(p->flags & (AHC_CHNLB|AHC_CHNLC)),
8554                                     scarray, p->sc_size, p->sc_type);
8555         if (!have_seeprom)
8556         {
8557           if(p->sc_type == C46)
8558             have_seeprom = read_seeprom(p, 4*(p->flags & (AHC_CHNLB|AHC_CHNLC)),
8559                                         scarray, p->sc_size, C56_66);
8560           else
8561             have_seeprom = read_seeprom(p, 4*(p->flags & (AHC_CHNLB|AHC_CHNLC)),
8562                                         scarray, p->sc_size, C46);
8563         }
8564       }
8565       break;
8566   }
8567
8568   if (!have_seeprom)
8569   {
8570     if (aic7xxx_verbose & VERBOSE_PROBE2)
8571     {
8572       printk("\naic7xxx: No SEEPROM available.\n");
8573     }
8574     p->flags |= AHC_NEWEEPROM_FMT;
8575     if (aic_inb(p, SCSISEQ) == 0)
8576     {
8577       p->flags |= AHC_USEDEFAULTS;
8578       p->flags &= ~AHC_BIOS_ENABLED;
8579       p->scsi_id = p->scsi_id_b = 7;
8580       *sxfrctl1 |= STPWEN;
8581       if (aic7xxx_verbose & VERBOSE_PROBE2)
8582       {
8583         printk("aic7xxx: Using default values.\n");
8584       }
8585     }
8586     else if (aic7xxx_verbose & VERBOSE_PROBE2)
8587     {
8588       printk("aic7xxx: Using leftover BIOS values.\n");
8589     }
8590     if ( ((p->chip & ~AHC_CHIPID_MASK) == AHC_PCI) && (*sxfrctl1 & STPWEN) )
8591     {
8592       p->flags |= AHC_TERM_ENB_SE_LOW | AHC_TERM_ENB_SE_HIGH;
8593       sc->adapter_control &= ~CFAUTOTERM;
8594       sc->adapter_control |= CFSTERM | CFWSTERM | CFLVDSTERM;
8595     }
8596     if (aic7xxx_extended)
8597       p->flags |= (AHC_EXTEND_TRANS_A | AHC_EXTEND_TRANS_B);
8598     else
8599       p->flags &= ~(AHC_EXTEND_TRANS_A | AHC_EXTEND_TRANS_B);
8600   }
8601   else
8602   {
8603     if (aic7xxx_verbose & VERBOSE_PROBE2)
8604     {
8605       printk("done\n");
8606     }
8607
8608     /*
8609      * Note things in our flags
8610      */
8611     p->flags |= AHC_SEEPROM_FOUND;
8612
8613     /*
8614      * Update the settings in sxfrctl1 to match the termination settings.
8615      */
8616     *sxfrctl1 = 0;
8617
8618     /*
8619      * Get our SCSI ID from the SEEPROM setting...
8620      */
8621     p->scsi_id = (sc->brtime_id & CFSCSIID);
8622
8623     /*
8624      * First process the settings that are different between the VLB
8625      * and PCI adapter seeproms.
8626      */
8627     if ((p->chip & AHC_CHIPID_MASK) == AHC_AIC7770)
8628     {
8629       /* VLB adapter seeproms */
8630       if (sc->bios_control & CF284XEXTEND)
8631         p->flags |= AHC_EXTEND_TRANS_A;
8632
8633       if (sc->adapter_control & CF284XSTERM)
8634       {
8635         *sxfrctl1 |= STPWEN;
8636         p->flags |= AHC_TERM_ENB_SE_LOW | AHC_TERM_ENB_SE_HIGH;
8637       }
8638     }
8639     else
8640     {
8641       /* PCI adapter seeproms */
8642       if (sc->bios_control & CFEXTEND)
8643         p->flags |= AHC_EXTEND_TRANS_A;
8644       if (sc->bios_control & CFBIOSEN)
8645         p->flags |= AHC_BIOS_ENABLED;
8646       else
8647         p->flags &= ~AHC_BIOS_ENABLED;
8648
8649       if (sc->adapter_control & CFSTERM)
8650       {
8651         *sxfrctl1 |= STPWEN;
8652         p->flags |= AHC_TERM_ENB_SE_LOW | AHC_TERM_ENB_SE_HIGH;
8653       }
8654     }
8655     memcpy(&p->sc, sc, sizeof(struct seeprom_config));
8656   }
8657
8658   p->discenable = 0;
8659
8660   /*
8661    * Limit to 16 targets just in case.  The 2842 for one is known to
8662    * blow the max_targets setting, future cards might also.
8663    */
8664   max_targets = ((p->features & (AHC_TWIN | AHC_WIDE)) ? 16 : 8);
8665
8666   if (have_seeprom)
8667   {
8668     for (i = 0; i < max_targets; i++)
8669     {
8670       if( ((p->features & AHC_ULTRA) &&
8671           !(sc->adapter_control & CFULTRAEN) &&
8672            (sc->device_flags[i] & CFSYNCHISULTRA)) ||
8673           (sc->device_flags[i] & CFNEWULTRAFORMAT) )
8674       {
8675         p->flags |= AHC_NEWEEPROM_FMT;
8676         break;
8677       }
8678     }
8679   }
8680
8681   for (i = 0; i < max_targets; i++)
8682   {
8683     mask = (0x01 << i);
8684     if (!have_seeprom)
8685     {
8686       if (aic_inb(p, SCSISEQ) != 0)
8687       {
8688         /*
8689          * OK...the BIOS set things up and left behind the settings we need.
8690          * Just make our sc->device_flags[i] entry match what the card has
8691          * set for this device.
8692          */
8693         p->discenable =
8694           ~(aic_inb(p, DISC_DSB) | (aic_inb(p, DISC_DSB + 1) << 8) );
8695         p->ultraenb =
8696           (aic_inb(p, ULTRA_ENB) | (aic_inb(p, ULTRA_ENB + 1) << 8) );
8697         sc->device_flags[i] = (p->discenable & mask) ? CFDISC : 0;
8698         if (aic_inb(p, TARG_SCSIRATE + i) & WIDEXFER)
8699           sc->device_flags[i] |= CFWIDEB;
8700         if (p->features & AHC_ULTRA2)
8701         {
8702           if (aic_inb(p, TARG_OFFSET + i))
8703           {
8704             sc->device_flags[i] |= CFSYNCH;
8705             sc->device_flags[i] |= (aic_inb(p, TARG_SCSIRATE + i) & 0x07);
8706             if ( (aic_inb(p, TARG_SCSIRATE + i) & 0x18) == 0x18 )
8707               sc->device_flags[i] |= CFSYNCHISULTRA;
8708           }
8709         }
8710         else
8711         {
8712           if (aic_inb(p, TARG_SCSIRATE + i) & ~WIDEXFER)
8713           {
8714             sc->device_flags[i] |= CFSYNCH;
8715             if (p->features & AHC_ULTRA)
8716               sc->device_flags[i] |= ((p->ultraenb & mask) ?
8717                                       CFSYNCHISULTRA : 0);
8718           }
8719         }
8720       }
8721       else
8722       {
8723         /*
8724          * Assume the BIOS has NOT been run on this card and nothing between
8725          * the card and the devices is configured yet.
8726          */
8727         sc->device_flags[i] = CFDISC;
8728         if (p->features & AHC_WIDE)
8729           sc->device_flags[i] |= CFWIDEB;
8730         if (p->features & AHC_ULTRA3)
8731           sc->device_flags[i] |= 2;
8732         else if (p->features & AHC_ULTRA2)
8733           sc->device_flags[i] |= 3;
8734         else if (p->features & AHC_ULTRA)
8735           sc->device_flags[i] |= CFSYNCHISULTRA;
8736         sc->device_flags[i] |= CFSYNCH;
8737         aic_outb(p, 0, TARG_SCSIRATE + i);
8738         if (p->features & AHC_ULTRA2)
8739           aic_outb(p, 0, TARG_OFFSET + i);
8740       }
8741     }
8742     if (sc->device_flags[i] & CFDISC)
8743     {
8744       p->discenable |= mask;
8745     }
8746     if (p->flags & AHC_NEWEEPROM_FMT)
8747     {
8748       if ( !(p->features & AHC_ULTRA2) )
8749       {
8750         /*
8751          * I know of two different Ultra BIOSes that do this differently.
8752          * One on the Gigabyte 6BXU mb that wants flags[i] & CFXFER to
8753          * be == to 0x03 and SYNCHISULTRA to be true to mean 40MByte/s
8754          * while on the IBM Netfinity 5000 they want the same thing
8755          * to be something else, while flags[i] & CFXFER == 0x03 and
8756          * SYNCHISULTRA false should be 40MByte/s.  So, we set both to
8757          * 40MByte/s and the lower speeds be damned.  People will have
8758          * to select around the conversely mapped lower speeds in order
8759          * to select lower speeds on these boards.
8760          */
8761         if ( (sc->device_flags[i] & CFNEWULTRAFORMAT) &&
8762             ((sc->device_flags[i] & CFXFER) == 0x03) )
8763         {
8764           sc->device_flags[i] &= ~CFXFER;
8765           sc->device_flags[i] |= CFSYNCHISULTRA;
8766         }
8767         if (sc->device_flags[i] & CFSYNCHISULTRA)
8768         {
8769           p->ultraenb |= mask;
8770         }
8771       }
8772       else if ( !(sc->device_flags[i] & CFNEWULTRAFORMAT) &&
8773                  (p->features & AHC_ULTRA2) &&
8774                  (sc->device_flags[i] & CFSYNCHISULTRA) )
8775       {
8776         p->ultraenb |= mask;
8777       }
8778     }
8779     else if (sc->adapter_control & CFULTRAEN)
8780     {
8781       p->ultraenb |= mask;
8782     }
8783     if ( (sc->device_flags[i] & CFSYNCH) == 0)
8784     {
8785       sc->device_flags[i] &= ~CFXFER;
8786       p->ultraenb &= ~mask;
8787       p->user[i].offset = 0;
8788       p->user[i].period = 0;
8789       p->user[i].options = 0;
8790     }
8791     else
8792     {
8793       if (p->features & AHC_ULTRA3)
8794       {
8795         p->user[i].offset = MAX_OFFSET_ULTRA2;
8796         if( (sc->device_flags[i] & CFXFER) < 0x03 )
8797         {
8798           scsirate = (sc->device_flags[i] & CFXFER);
8799           p->user[i].options = MSG_EXT_PPR_OPTION_DT_CRC;
8800         }
8801         else
8802         {
8803           scsirate = (sc->device_flags[i] & CFXFER) |
8804                      ((p->ultraenb & mask) ? 0x18 : 0x10);
8805           p->user[i].options = 0;
8806         }
8807         p->user[i].period = aic7xxx_find_period(p, scsirate,
8808                                        AHC_SYNCRATE_ULTRA3);
8809       }
8810       else if (p->features & AHC_ULTRA2)
8811       {
8812         p->user[i].offset = MAX_OFFSET_ULTRA2;
8813         scsirate = (sc->device_flags[i] & CFXFER) |
8814                    ((p->ultraenb & mask) ? 0x18 : 0x10);
8815         p->user[i].options = 0;
8816         p->user[i].period = aic7xxx_find_period(p, scsirate,
8817                                        AHC_SYNCRATE_ULTRA2);
8818       }
8819       else
8820       {
8821         scsirate = (sc->device_flags[i] & CFXFER) << 4;
8822         p->user[i].options = 0;
8823         p->user[i].offset = MAX_OFFSET_8BIT;
8824         if (p->features & AHC_ULTRA)
8825         {
8826           short ultraenb;
8827           ultraenb = aic_inb(p, ULTRA_ENB) |
8828             (aic_inb(p, ULTRA_ENB + 1) << 8);
8829           p->user[i].period = aic7xxx_find_period(p, scsirate,
8830                                           (p->ultraenb & mask) ?
8831                                           AHC_SYNCRATE_ULTRA :
8832                                           AHC_SYNCRATE_FAST);
8833         }
8834         else
8835           p->user[i].period = aic7xxx_find_period(p, scsirate,
8836                                           AHC_SYNCRATE_FAST);
8837       }
8838     }
8839     if ( (sc->device_flags[i] & CFWIDEB) && (p->features & AHC_WIDE) )
8840     {
8841       p->user[i].width = MSG_EXT_WDTR_BUS_16_BIT;
8842     }
8843     else
8844     {
8845       p->user[i].width = MSG_EXT_WDTR_BUS_8_BIT;
8846     }
8847   }
8848   aic_outb(p, ~(p->discenable & 0xFF), DISC_DSB);
8849   aic_outb(p, ~((p->discenable >> 8) & 0xFF), DISC_DSB + 1);
8850
8851   /*
8852    * We set the p->ultraenb from the SEEPROM to begin with, but now we make
8853    * it match what is already down in the card.  If we are doing a reset
8854    * on the card then this will get put back to a default state anyway.
8855    * This allows us to not have to pre-emptively negotiate when using the
8856    * no_reset option.
8857    */
8858   if (p->features & AHC_ULTRA)
8859     p->ultraenb = aic_inb(p, ULTRA_ENB) | (aic_inb(p, ULTRA_ENB + 1) << 8);
8860
8861   
8862   scsi_conf = (p->scsi_id & HSCSIID);
8863
8864   if(have_seeprom)
8865   {
8866     p->adapter_control = sc->adapter_control;
8867     p->bios_control = sc->bios_control;
8868
8869     switch (p->chip & AHC_CHIPID_MASK)
8870     {
8871       case AHC_AIC7895:
8872       case AHC_AIC7896:
8873       case AHC_AIC7899:
8874         if (p->adapter_control & CFBPRIMARY)
8875           p->flags |= AHC_CHANNEL_B_PRIMARY;
8876       default:
8877         break;
8878     }
8879
8880     if (sc->adapter_control & CFSPARITY)
8881       scsi_conf |= ENSPCHK;
8882   }
8883   else
8884   {
8885     scsi_conf |= ENSPCHK | RESET_SCSI;
8886   }
8887
8888   /*
8889    * Only set the SCSICONF and SCSICONF + 1 registers if we are a PCI card.
8890    * The 2842 and 2742 cards already have these registers set and we don't
8891    * want to muck with them since we don't set all the bits they do.
8892    */
8893   if ( (p->chip & ~AHC_CHIPID_MASK) == AHC_PCI )
8894   {
8895     /* Set the host ID */
8896     aic_outb(p, scsi_conf, SCSICONF);
8897     /* In case we are a wide card */
8898     aic_outb(p, p->scsi_id, SCSICONF + 1);
8899   }
8900 }
8901
8902 /*+F*************************************************************************
8903  * Function:
8904  *   aic7xxx_configure_bugs
8905  *
8906  * Description:
8907  *   Take the card passed in and set the appropriate bug flags based upon
8908  *   the card model.  Also make any changes needed to device registers or
8909  *   PCI registers while we are here.
8910  *-F*************************************************************************/
8911 static void
8912 aic7xxx_configure_bugs(struct aic7xxx_host *p)
8913 {
8914   unsigned short tmp_word;
8915  
8916   switch(p->chip & AHC_CHIPID_MASK)
8917   {
8918     case AHC_AIC7860:
8919       p->bugs |= AHC_BUG_PCI_2_1_RETRY;
8920       /* fall through */
8921     case AHC_AIC7850:
8922     case AHC_AIC7870:
8923       p->bugs |= AHC_BUG_TMODE_WIDEODD | AHC_BUG_CACHETHEN | AHC_BUG_PCI_MWI;
8924       break;
8925     case AHC_AIC7880:
8926       p->bugs |= AHC_BUG_TMODE_WIDEODD | AHC_BUG_PCI_2_1_RETRY |
8927                  AHC_BUG_CACHETHEN | AHC_BUG_PCI_MWI;
8928       break;
8929     case AHC_AIC7890:
8930       p->bugs |= AHC_BUG_AUTOFLUSH | AHC_BUG_CACHETHEN;
8931       break;
8932     case AHC_AIC7892:
8933       p->bugs |= AHC_BUG_SCBCHAN_UPLOAD;
8934       break;
8935     case AHC_AIC7895:
8936       p->bugs |= AHC_BUG_TMODE_WIDEODD | AHC_BUG_PCI_2_1_RETRY |
8937                  AHC_BUG_CACHETHEN | AHC_BUG_PCI_MWI;
8938       break;
8939     case AHC_AIC7896:
8940       p->bugs |= AHC_BUG_CACHETHEN_DIS;
8941       break;
8942     case AHC_AIC7899:
8943       p->bugs |= AHC_BUG_SCBCHAN_UPLOAD;
8944       break;
8945     default:
8946       /* Nothing to do */
8947       break;
8948   }
8949
8950   /*
8951    * Now handle the bugs that require PCI register or card register tweaks
8952    */
8953   pci_read_config_word(p->pdev, PCI_COMMAND, &tmp_word);
8954   if(p->bugs & AHC_BUG_PCI_MWI)
8955   {
8956     tmp_word &= ~PCI_COMMAND_INVALIDATE;
8957   }
8958   else
8959   {
8960     tmp_word |= PCI_COMMAND_INVALIDATE;
8961   }
8962   pci_write_config_word(p->pdev, PCI_COMMAND, tmp_word);
8963
8964   if(p->bugs & AHC_BUG_CACHETHEN)
8965   {
8966     aic_outb(p, aic_inb(p, DSCOMMAND0) & ~CACHETHEN, DSCOMMAND0);
8967   }
8968   else if (p->bugs & AHC_BUG_CACHETHEN_DIS)
8969   {
8970     aic_outb(p, aic_inb(p, DSCOMMAND0) | CACHETHEN, DSCOMMAND0);
8971   }
8972
8973   return;
8974 }
8975
8976
8977 /*+F*************************************************************************
8978  * Function:
8979  *   aic7xxx_detect
8980  *
8981  * Description:
8982  *   Try to detect and register an Adaptec 7770 or 7870 SCSI controller.
8983  *
8984  * XXX - This should really be called aic7xxx_probe().  A sequence of
8985  *       probe(), attach()/detach(), and init() makes more sense than
8986  *       one do-it-all function.  This may be useful when (and if) the
8987  *       mid-level SCSI code is overhauled.
8988  *-F*************************************************************************/
8989 static int
8990 aic7xxx_detect(struct scsi_host_template *template)
8991 {
8992   struct aic7xxx_host *temp_p = NULL;
8993   struct aic7xxx_host *current_p = NULL;
8994   struct aic7xxx_host *list_p = NULL;
8995   int found = 0;
8996 #if defined(__i386__) || defined(__alpha__)
8997   ahc_flag_type flags = 0;
8998   int type;
8999 #endif
9000   unsigned char sxfrctl1;
9001 #if defined(__i386__) || defined(__alpha__)
9002   unsigned char hcntrl, hostconf;
9003   unsigned int slot, base;
9004 #endif
9005
9006 #ifdef MODULE
9007   /*
9008    * If we are called as a module, the aic7xxx pointer may not be null
9009    * and it would point to our bootup string, just like on the lilo
9010    * command line.  IF not NULL, then process this config string with
9011    * aic7xxx_setup
9012    */
9013   if(aic7xxx)
9014     aic7xxx_setup(aic7xxx);
9015 #endif
9016
9017   template->proc_name = "aic7xxx";
9018   template->sg_tablesize = AIC7XXX_MAX_SG;
9019
9020
9021 #ifdef CONFIG_PCI
9022   /*
9023    * PCI-bus probe.
9024    */
9025   {
9026     static struct
9027     {
9028       unsigned short      vendor_id;
9029       unsigned short      device_id;
9030       ahc_chip            chip;
9031       ahc_flag_type       flags;
9032       ahc_feature         features;
9033       int                 board_name_index;
9034       unsigned short      seeprom_size;
9035       unsigned short      seeprom_type;
9036     } const aic_pdevs[] = {
9037       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7810, AHC_NONE,
9038        AHC_FNONE, AHC_FENONE,                                1,
9039        32, C46 },
9040       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7850, AHC_AIC7850,
9041        AHC_PAGESCBS, AHC_AIC7850_FE,                         5,
9042        32, C46 },
9043       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7855, AHC_AIC7850,
9044        AHC_PAGESCBS, AHC_AIC7850_FE,                         6,
9045        32, C46 },
9046       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7821, AHC_AIC7860,
9047        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9048        AHC_AIC7860_FE,                                       7,
9049        32, C46 },
9050       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_3860, AHC_AIC7860,
9051        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9052        AHC_AIC7860_FE,                                       7,
9053        32, C46 },
9054       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_38602, AHC_AIC7860,
9055        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9056        AHC_AIC7860_FE,                                       7,
9057        32, C46 },
9058       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_38602, AHC_AIC7860,
9059        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9060        AHC_AIC7860_FE,                                       7,
9061        32, C46 },
9062       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7860, AHC_AIC7860,
9063        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MOTHERBOARD,
9064        AHC_AIC7860_FE,                                       7,
9065        32, C46 },
9066       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7861, AHC_AIC7860,
9067        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9068        AHC_AIC7860_FE,                                       8,
9069        32, C46 },
9070       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7870, AHC_AIC7870,
9071        AHC_PAGESCBS | AHC_BIOS_ENABLED | AHC_MOTHERBOARD,
9072        AHC_AIC7870_FE,                                       9,
9073        32, C46 },
9074       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7871, AHC_AIC7870,
9075        AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7870_FE,     10,
9076        32, C46 },
9077       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7872, AHC_AIC7870,
9078        AHC_PAGESCBS | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9079        AHC_AIC7870_FE,                                      11,
9080        32, C56_66 },
9081       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7873, AHC_AIC7870,
9082        AHC_PAGESCBS | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9083        AHC_AIC7870_FE,                                      12,
9084        32, C56_66 },
9085       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7874, AHC_AIC7870,
9086        AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7870_FE,     13,
9087        32, C46 },
9088       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7880, AHC_AIC7880,
9089        AHC_PAGESCBS | AHC_BIOS_ENABLED | AHC_MOTHERBOARD,
9090        AHC_AIC7880_FE,                                      14,
9091        32, C46 },
9092       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7881, AHC_AIC7880,
9093        AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7880_FE,     15,
9094        32, C46 },
9095       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7882, AHC_AIC7880,
9096        AHC_PAGESCBS | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9097        AHC_AIC7880_FE,                                      16,
9098        32, C56_66 },
9099       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7883, AHC_AIC7880,
9100        AHC_PAGESCBS | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9101        AHC_AIC7880_FE,                                      17,
9102        32, C56_66 },
9103       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7884, AHC_AIC7880,
9104        AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7880_FE,     18,
9105        32, C46 },
9106       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7885, AHC_AIC7880,
9107        AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7880_FE,     18,
9108        32, C46 },
9109       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7886, AHC_AIC7880,
9110        AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7880_FE,     18,
9111        32, C46 },
9112       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7887, AHC_AIC7880,
9113        AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7880_FE | AHC_NEW_AUTOTERM, 19,
9114        32, C46 },
9115       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7888, AHC_AIC7880,
9116        AHC_PAGESCBS | AHC_BIOS_ENABLED, AHC_AIC7880_FE,     18,
9117        32, C46 },
9118       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_7895, AHC_AIC7895,
9119        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9120        AHC_AIC7895_FE,                                      20,
9121        32, C56_66 },
9122       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7890, AHC_AIC7890,
9123        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9124        AHC_AIC7890_FE,                                      21,
9125        32, C46 },
9126       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7890B, AHC_AIC7890,
9127        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9128        AHC_AIC7890_FE,                                      21,
9129        32, C46 },
9130       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_2930U2, AHC_AIC7890,
9131        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9132        AHC_AIC7890_FE,                                      22,
9133        32, C46 },
9134       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_2940U2, AHC_AIC7890,
9135        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9136        AHC_AIC7890_FE,                                      23,
9137        32, C46 },
9138       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7896, AHC_AIC7896,
9139        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9140        AHC_AIC7896_FE,                                      24,
9141        32, C56_66 },
9142       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_3940U2, AHC_AIC7896,
9143        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9144        AHC_AIC7896_FE,                                      25,
9145        32, C56_66 },
9146       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_3950U2D, AHC_AIC7896,
9147        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9148        AHC_AIC7896_FE,                                      26,
9149        32, C56_66 },
9150       {PCI_VENDOR_ID_ADAPTEC, PCI_DEVICE_ID_ADAPTEC_1480A, AHC_AIC7860,
9151        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_NO_STPWEN,
9152        AHC_AIC7860_FE,                                      27,
9153        32, C46 },
9154       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7892A, AHC_AIC7892,
9155        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9156        AHC_AIC7892_FE,                                      28,
9157        32, C46 },
9158       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7892B, AHC_AIC7892,
9159        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9160        AHC_AIC7892_FE,                                      28,
9161        32, C46 },
9162       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7892D, AHC_AIC7892,
9163        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9164        AHC_AIC7892_FE,                                      28,
9165        32, C46 },
9166       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7892P, AHC_AIC7892,
9167        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED,
9168        AHC_AIC7892_FE,                                      28,
9169        32, C46 },
9170       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7899A, AHC_AIC7899,
9171        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9172        AHC_AIC7899_FE,                                      29,
9173        32, C56_66 },
9174       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7899B, AHC_AIC7899,
9175        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9176        AHC_AIC7899_FE,                                      29,
9177        32, C56_66 },
9178       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7899D, AHC_AIC7899,
9179        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9180        AHC_AIC7899_FE,                                      29,
9181        32, C56_66 },
9182       {PCI_VENDOR_ID_ADAPTEC2, PCI_DEVICE_ID_ADAPTEC2_7899P, AHC_AIC7899,
9183        AHC_PAGESCBS | AHC_NEWEEPROM_FMT | AHC_BIOS_ENABLED | AHC_MULTI_CHANNEL,
9184        AHC_AIC7899_FE,                                      29,
9185        32, C56_66 },
9186     };
9187
9188     unsigned short command;
9189     unsigned int  devconfig, i, oldverbose;
9190     struct pci_dev *pdev = NULL;
9191
9192     for (i = 0; i < ARRAY_SIZE(aic_pdevs); i++)
9193     {
9194       pdev = NULL;
9195       while ((pdev = pci_get_device(aic_pdevs[i].vendor_id,
9196                                      aic_pdevs[i].device_id,
9197                                      pdev))) {
9198         if (pci_enable_device(pdev))
9199                 continue;
9200         if ( i == 0 ) /* We found one, but it's the 7810 RAID cont. */
9201         {
9202           if (aic7xxx_verbose & (VERBOSE_PROBE|VERBOSE_PROBE2))
9203           {
9204             printk(KERN_INFO "aic7xxx: The 7810 RAID controller is not "
9205               "supported by\n");
9206             printk(KERN_INFO "         this driver, we are ignoring it.\n");
9207           }
9208         }
9209         else if ( (temp_p = kmalloc(sizeof(struct aic7xxx_host),
9210                                     GFP_ATOMIC)) != NULL )
9211         {
9212           memset(temp_p, 0, sizeof(struct aic7xxx_host));
9213           temp_p->chip = aic_pdevs[i].chip | AHC_PCI;
9214           temp_p->flags = aic_pdevs[i].flags;
9215           temp_p->features = aic_pdevs[i].features;
9216           temp_p->board_name_index = aic_pdevs[i].board_name_index;
9217           temp_p->sc_size = aic_pdevs[i].seeprom_size;
9218           temp_p->sc_type = aic_pdevs[i].seeprom_type;
9219
9220           /*
9221            * Read sundry information from PCI BIOS.
9222            */
9223           temp_p->irq = pdev->irq;
9224           temp_p->pdev = pdev;
9225           temp_p->pci_bus = pdev->bus->number;
9226           temp_p->pci_device_fn = pdev->devfn;
9227           temp_p->base = pci_resource_start(pdev, 0);
9228           temp_p->mbase = pci_resource_start(pdev, 1);
9229           current_p = list_p;
9230           while(current_p && temp_p)
9231           {
9232             if ( ((current_p->pci_bus == temp_p->pci_bus) &&
9233                   (current_p->pci_device_fn == temp_p->pci_device_fn)) ||
9234                  (temp_p->base && (current_p->base == temp_p->base)) ||
9235                  (temp_p->mbase && (current_p->mbase == temp_p->mbase)) )
9236             {
9237               /* duplicate PCI entry, skip it */
9238               kfree(temp_p);
9239               temp_p = NULL;
9240               continue;
9241             }
9242             current_p = current_p->next;
9243           }
9244           if(pci_request_regions(temp_p->pdev, "aic7xxx"))
9245           {
9246             printk("aic7xxx: <%s> at PCI %d/%d/%d\n", 
9247               board_names[aic_pdevs[i].board_name_index],
9248               temp_p->pci_bus,
9249               PCI_SLOT(temp_p->pci_device_fn),
9250               PCI_FUNC(temp_p->pci_device_fn));
9251             printk("aic7xxx: I/O ports already in use, ignoring.\n");
9252             kfree(temp_p);
9253             continue;
9254           }
9255
9256           if (aic7xxx_verbose & VERBOSE_PROBE2)
9257             printk("aic7xxx: <%s> at PCI %d/%d\n", 
9258               board_names[aic_pdevs[i].board_name_index],
9259               PCI_SLOT(pdev->devfn),
9260               PCI_FUNC(pdev->devfn));
9261           pci_read_config_word(pdev, PCI_COMMAND, &command);
9262           if (aic7xxx_verbose & VERBOSE_PROBE2)
9263           {
9264             printk("aic7xxx: Initial PCI_COMMAND value was 0x%x\n",
9265               (int)command);
9266           }
9267 #ifdef AIC7XXX_STRICT_PCI_SETUP
9268           command |= PCI_COMMAND_SERR | PCI_COMMAND_PARITY |
9269             PCI_COMMAND_MASTER | PCI_COMMAND_MEMORY | PCI_COMMAND_IO;
9270 #else
9271           command |= PCI_COMMAND_MASTER | PCI_COMMAND_MEMORY | PCI_COMMAND_IO;
9272 #endif
9273           command &= ~PCI_COMMAND_INVALIDATE;
9274           if (aic7xxx_pci_parity == 0)
9275             command &= ~(PCI_COMMAND_SERR | PCI_COMMAND_PARITY);
9276           pci_write_config_word(pdev, PCI_COMMAND, command);
9277 #ifdef AIC7XXX_STRICT_PCI_SETUP
9278           pci_read_config_dword(pdev, DEVCONFIG, &devconfig);
9279           if (aic7xxx_verbose & VERBOSE_PROBE2)
9280           {
9281             printk("aic7xxx: Initial DEVCONFIG value was 0x%x\n", devconfig);
9282           }
9283           devconfig |= 0x80000040;
9284           pci_write_config_dword(pdev, DEVCONFIG, devconfig);
9285 #endif /* AIC7XXX_STRICT_PCI_SETUP */
9286
9287           temp_p->unpause = INTEN;
9288           temp_p->pause = temp_p->unpause | PAUSE;
9289           if ( ((temp_p->base == 0) &&
9290                 (temp_p->mbase == 0)) ||
9291                (temp_p->irq == 0) )
9292           {
9293             printk("aic7xxx: <%s> at PCI %d/%d/%d\n", 
9294               board_names[aic_pdevs[i].board_name_index],
9295               temp_p->pci_bus,
9296               PCI_SLOT(temp_p->pci_device_fn),
9297               PCI_FUNC(temp_p->pci_device_fn));
9298             printk("aic7xxx: Controller disabled by BIOS, ignoring.\n");
9299             goto skip_pci_controller;
9300           }
9301
9302 #ifdef MMAPIO
9303           if ( !(temp_p->base) || !(temp_p->flags & AHC_MULTI_CHANNEL) ||
9304                ((temp_p->chip != (AHC_AIC7870 | AHC_PCI)) &&
9305                 (temp_p->chip != (AHC_AIC7880 | AHC_PCI))) )
9306           {
9307             temp_p->maddr = ioremap_nocache(temp_p->mbase, 256);
9308             if(temp_p->maddr)
9309             {
9310               /*
9311                * We need to check the I/O with the MMAPed address.  Some machines
9312                * simply fail to work with MMAPed I/O and certain controllers.
9313                */
9314               if(aic_inb(temp_p, HCNTRL) == 0xff)
9315               {
9316                 /*
9317                  * OK.....we failed our test....go back to programmed I/O
9318                  */
9319                 printk(KERN_INFO "aic7xxx: <%s> at PCI %d/%d/%d\n", 
9320                   board_names[aic_pdevs[i].board_name_index],
9321                   temp_p->pci_bus,
9322                   PCI_SLOT(temp_p->pci_device_fn),
9323                   PCI_FUNC(temp_p->pci_device_fn));
9324                 printk(KERN_INFO "aic7xxx: MMAPed I/O failed, reverting to "
9325                                  "Programmed I/O.\n");
9326                 iounmap(temp_p->maddr);
9327                 temp_p->maddr = NULL;
9328                 if(temp_p->base == 0)
9329                 {
9330                   printk("aic7xxx: <%s> at PCI %d/%d/%d\n", 
9331                     board_names[aic_pdevs[i].board_name_index],
9332                     temp_p->pci_bus,
9333                     PCI_SLOT(temp_p->pci_device_fn),
9334                     PCI_FUNC(temp_p->pci_device_fn));
9335                   printk("aic7xxx: Controller disabled by BIOS, ignoring.\n");
9336                   goto skip_pci_controller;
9337                 }
9338               }
9339             }
9340           }
9341 #endif
9342
9343           /*
9344            * We HAVE to make sure the first pause_sequencer() and all other
9345            * subsequent I/O that isn't PCI config space I/O takes place
9346            * after the MMAPed I/O region is configured and tested.  The
9347            * problem is the PowerPC architecture that doesn't support
9348            * programmed I/O at all, so we have to have the MMAP I/O set up
9349            * for this pause to even work on those machines.
9350            */
9351           pause_sequencer(temp_p);
9352
9353           /*
9354            * Clear out any pending PCI error status messages.  Also set
9355            * verbose to 0 so that we don't emit strange PCI error messages
9356            * while cleaning out the current status bits.
9357            */
9358           oldverbose = aic7xxx_verbose;
9359           aic7xxx_verbose = 0;
9360           aic7xxx_pci_intr(temp_p);
9361           aic7xxx_verbose = oldverbose;
9362
9363           temp_p->bios_address = 0;
9364
9365           /*
9366            * Remember how the card was setup in case there is no seeprom.
9367            */
9368           if (temp_p->features & AHC_ULTRA2)
9369             temp_p->scsi_id = aic_inb(temp_p, SCSIID_ULTRA2) & OID;
9370           else
9371             temp_p->scsi_id = aic_inb(temp_p, SCSIID) & OID;
9372           /*
9373            * Get current termination setting
9374            */
9375           sxfrctl1 = aic_inb(temp_p, SXFRCTL1);
9376
9377           if (aic7xxx_chip_reset(temp_p) == -1)
9378           {
9379             goto skip_pci_controller;
9380           }
9381           /*
9382            * Very quickly put the term setting back into the register since
9383            * the chip reset may cause odd things to happen.  This is to keep
9384            * LVD busses with lots of drives from draining the power out of
9385            * the diffsense line before we get around to running the
9386            * configure_termination() function.  Also restore the STPWLEVEL
9387            * bit of DEVCONFIG
9388            */
9389           aic_outb(temp_p, sxfrctl1, SXFRCTL1);
9390           pci_write_config_dword(temp_p->pdev, DEVCONFIG, devconfig);
9391           sxfrctl1 &= STPWEN;
9392
9393           /*
9394            * We need to set the CHNL? assignments before loading the SEEPROM
9395            * The 3940 and 3985 cards (original stuff, not any of the later
9396            * stuff) are 7870 and 7880 class chips.  The Ultra2 stuff falls
9397            * under 7896 and 7897.  The 7895 is in a class by itself :)
9398            */
9399           switch (temp_p->chip & AHC_CHIPID_MASK)
9400           {
9401             case AHC_AIC7870: /* 3840 / 3985 */
9402             case AHC_AIC7880: /* 3840 UW / 3985 UW */
9403               if(temp_p->flags & AHC_MULTI_CHANNEL)
9404               {
9405                 switch(PCI_SLOT(temp_p->pci_device_fn))
9406                 {
9407                   case 5:
9408                     temp_p->flags |= AHC_CHNLB;
9409                     break;
9410                   case 8:
9411                     temp_p->flags |= AHC_CHNLB;
9412                     break;
9413                   case 12:
9414                     temp_p->flags |= AHC_CHNLC;
9415                     break;
9416                   default:
9417                     break;
9418                 }
9419               }
9420               break;
9421
9422             case AHC_AIC7895: /* 7895 */
9423             case AHC_AIC7896: /* 7896/7 */
9424             case AHC_AIC7899: /* 7899 */
9425               if (PCI_FUNC(pdev->devfn) != 0)
9426               {
9427                 temp_p->flags |= AHC_CHNLB;
9428               }
9429               /*
9430                * The 7895 is the only chipset that sets the SCBSIZE32 param
9431                * in the DEVCONFIG register.  The Ultra2 chipsets use
9432                * the DSCOMMAND0 register instead.
9433                */
9434               if ((temp_p->chip & AHC_CHIPID_MASK) == AHC_AIC7895)
9435               {
9436                 pci_read_config_dword(pdev, DEVCONFIG, &devconfig);
9437                 devconfig |= SCBSIZE32;
9438                 pci_write_config_dword(pdev, DEVCONFIG, devconfig);
9439               }
9440               break;
9441             default:
9442               break;
9443           }
9444
9445           /*
9446            * Loading of the SEEPROM needs to come after we've set the flags
9447            * to indicate possible CHNLB and CHNLC assigments.  Otherwise,
9448            * on 394x and 398x cards we'll end up reading the wrong settings
9449            * for channels B and C
9450            */
9451           switch (temp_p->chip & AHC_CHIPID_MASK)
9452           {
9453             case AHC_AIC7892:
9454             case AHC_AIC7899:
9455               aic_outb(temp_p, 0, SCAMCTL);
9456               /*
9457                * Switch to the alt mode of the chip...
9458                */
9459               aic_outb(temp_p, aic_inb(temp_p, SFUNCT) | ALT_MODE, SFUNCT);
9460               /*
9461                * Set our options...the last two items set our CRC after x byte
9462                * count in target mode...
9463                */
9464               aic_outb(temp_p, AUTO_MSGOUT_DE | DIS_MSGIN_DUALEDGE, OPTIONMODE);
9465               aic_outb(temp_p, 0x00, 0x0b);
9466               aic_outb(temp_p, 0x10, 0x0a);
9467               /*
9468                * switch back to normal mode...
9469                */
9470               aic_outb(temp_p, aic_inb(temp_p, SFUNCT) & ~ALT_MODE, SFUNCT);
9471               aic_outb(temp_p, CRCVALCHKEN | CRCENDCHKEN | CRCREQCHKEN |
9472                                TARGCRCENDEN | TARGCRCCNTEN,
9473                        CRCCONTROL1);
9474               aic_outb(temp_p, ((aic_inb(temp_p, DSCOMMAND0) | USCBSIZE32 |
9475                                  MPARCKEN | CIOPARCKEN | CACHETHEN) & 
9476                                ~DPARCKEN), DSCOMMAND0);
9477               aic7xxx_load_seeprom(temp_p, &sxfrctl1);
9478               break;
9479             case AHC_AIC7890:
9480             case AHC_AIC7896:
9481               aic_outb(temp_p, 0, SCAMCTL);
9482               aic_outb(temp_p, (aic_inb(temp_p, DSCOMMAND0) |
9483                                 CACHETHEN | MPARCKEN | USCBSIZE32 |
9484                                 CIOPARCKEN) & ~DPARCKEN, DSCOMMAND0);
9485               aic7xxx_load_seeprom(temp_p, &sxfrctl1);
9486               break;
9487             case AHC_AIC7850:
9488             case AHC_AIC7860:
9489               /*
9490                * Set the DSCOMMAND0 register on these cards different from
9491                * on the 789x cards.  Also, read the SEEPROM as well.
9492                */
9493               aic_outb(temp_p, (aic_inb(temp_p, DSCOMMAND0) |
9494                                 CACHETHEN | MPARCKEN) & ~DPARCKEN,
9495                        DSCOMMAND0);
9496               /* FALLTHROUGH */
9497             default:
9498               aic7xxx_load_seeprom(temp_p, &sxfrctl1);
9499               break;
9500             case AHC_AIC7880:
9501               /*
9502                * Check the rev of the chipset before we change DSCOMMAND0
9503                */
9504               pci_read_config_dword(pdev, DEVCONFIG, &devconfig);
9505               if ((devconfig & 0xff) >= 1)
9506               {
9507                 aic_outb(temp_p, (aic_inb(temp_p, DSCOMMAND0) |
9508                                   CACHETHEN | MPARCKEN) & ~DPARCKEN,
9509                          DSCOMMAND0);
9510               }
9511               aic7xxx_load_seeprom(temp_p, &sxfrctl1);
9512               break;
9513           }
9514           
9515
9516           /*
9517            * and then we need another switch based on the type in order to
9518            * make sure the channel B primary flag is set properly on 7895
9519            * controllers....Arrrgggghhh!!!  We also have to catch the fact
9520            * that when you disable the BIOS on the 7895 on the Intel DK440LX
9521            * motherboard, and possibly others, it only sets the BIOS disabled
9522            * bit on the A channel...I think I'm starting to lean towards
9523            * going postal....
9524            */
9525           switch(temp_p->chip & AHC_CHIPID_MASK)
9526           {
9527             case AHC_AIC7895:
9528             case AHC_AIC7896:
9529             case AHC_AIC7899:
9530               current_p = list_p;
9531               while(current_p != NULL)
9532               {
9533                 if ( (current_p->pci_bus == temp_p->pci_bus) &&
9534                      (PCI_SLOT(current_p->pci_device_fn) ==
9535                       PCI_SLOT(temp_p->pci_device_fn)) )
9536                 {
9537                   if ( PCI_FUNC(current_p->pci_device_fn) == 0 )
9538                   {
9539                     temp_p->flags |= 
9540                       (current_p->flags & AHC_CHANNEL_B_PRIMARY);
9541                     temp_p->flags &= ~(AHC_BIOS_ENABLED|AHC_USEDEFAULTS);
9542                     temp_p->flags |=
9543                       (current_p->flags & (AHC_BIOS_ENABLED|AHC_USEDEFAULTS));
9544                   }
9545                   else
9546                   {
9547                     current_p->flags |=
9548                       (temp_p->flags & AHC_CHANNEL_B_PRIMARY);
9549                     current_p->flags &= ~(AHC_BIOS_ENABLED|AHC_USEDEFAULTS);
9550                     current_p->flags |=
9551                       (temp_p->flags & (AHC_BIOS_ENABLED|AHC_USEDEFAULTS));
9552                   }
9553                 }
9554                 current_p = current_p->next;
9555               }
9556               break;
9557             default:
9558               break;
9559           }
9560
9561           /*
9562            * We only support external SCB RAM on the 7895/6/7 chipsets.
9563            * We could support it on the 7890/1 easy enough, but I don't
9564            * know of any 7890/1 based cards that have it.  I do know
9565            * of 7895/6/7 cards that have it and they work properly.
9566            */
9567           switch(temp_p->chip & AHC_CHIPID_MASK)
9568           {
9569             default:
9570               break;
9571             case AHC_AIC7895:
9572             case AHC_AIC7896:
9573             case AHC_AIC7899:
9574               pci_read_config_dword(pdev, DEVCONFIG, &devconfig);
9575               if (temp_p->features & AHC_ULTRA2)
9576               {
9577                 if ( (aic_inb(temp_p, DSCOMMAND0) & RAMPSM_ULTRA2) &&
9578                      (aic7xxx_scbram) )
9579                 {
9580                   aic_outb(temp_p,
9581                            aic_inb(temp_p, DSCOMMAND0) & ~SCBRAMSEL_ULTRA2,
9582                            DSCOMMAND0);
9583                   temp_p->flags |= AHC_EXTERNAL_SRAM;
9584                   devconfig |= EXTSCBPEN;
9585                 }
9586                 else if (aic_inb(temp_p, DSCOMMAND0) & RAMPSM_ULTRA2)
9587                 {
9588                   printk(KERN_INFO "aic7xxx: <%s> at PCI %d/%d/%d\n", 
9589                     board_names[aic_pdevs[i].board_name_index],
9590                     temp_p->pci_bus,
9591                     PCI_SLOT(temp_p->pci_device_fn),
9592                     PCI_FUNC(temp_p->pci_device_fn));
9593                   printk("aic7xxx: external SCB RAM detected, "
9594                          "but not enabled\n");
9595                 }
9596               }
9597               else
9598               {
9599                 if ((devconfig & RAMPSM) && (aic7xxx_scbram))
9600                 {
9601                   devconfig &= ~SCBRAMSEL;
9602                   devconfig |= EXTSCBPEN;
9603                   temp_p->flags |= AHC_EXTERNAL_SRAM;
9604                 }
9605                 else if (devconfig & RAMPSM)
9606                 {
9607                   printk(KERN_INFO "aic7xxx: <%s> at PCI %d/%d/%d\n", 
9608                     board_names[aic_pdevs[i].board_name_index],
9609                     temp_p->pci_bus,
9610                     PCI_SLOT(temp_p->pci_device_fn),
9611                     PCI_FUNC(temp_p->pci_device_fn));
9612                   printk("aic7xxx: external SCB RAM detected, "
9613                          "but not enabled\n");
9614                 }
9615               }
9616               pci_write_config_dword(pdev, DEVCONFIG, devconfig);
9617               if ( (temp_p->flags & AHC_EXTERNAL_SRAM) &&
9618                    (temp_p->flags & AHC_CHNLB) )
9619                 aic_outb(temp_p, 1, CCSCBBADDR);
9620               break;
9621           }
9622
9623           /*
9624            * Take the LED out of diagnostic mode
9625            */
9626           aic_outb(temp_p, 
9627             (aic_inb(temp_p, SBLKCTL) & ~(DIAGLEDEN | DIAGLEDON)),
9628             SBLKCTL);
9629
9630           /*
9631            * We don't know where this is set in the SEEPROM or by the
9632            * BIOS, so we default to 100%.  On Ultra2 controllers, use 75%
9633            * instead.
9634            */
9635           if (temp_p->features & AHC_ULTRA2)
9636           {
9637             aic_outb(temp_p, RD_DFTHRSH_MAX | WR_DFTHRSH_MAX, DFF_THRSH);
9638           }
9639           else
9640           {
9641             aic_outb(temp_p, DFTHRSH_100, DSPCISTATUS);
9642           }
9643
9644           /*
9645            * Call our function to fixup any bugs that exist on this chipset.
9646            * This may muck with PCI settings and other device settings, so
9647            * make sure it's after all the other PCI and device register
9648            * tweaks so it can back out bad settings on specific broken cards.
9649            */
9650           aic7xxx_configure_bugs(temp_p);
9651
9652           /* Hold a pci device reference */
9653           pci_dev_get(temp_p->pdev);
9654
9655           if ( list_p == NULL )
9656           {
9657             list_p = current_p = temp_p;
9658           }
9659           else
9660           {
9661             current_p = list_p;
9662             while(current_p->next != NULL)
9663               current_p = current_p->next;
9664             current_p->next = temp_p;
9665           }
9666           temp_p->next = NULL;
9667           found++;
9668           continue;
9669 skip_pci_controller:
9670 #ifdef CONFIG_PCI
9671           pci_release_regions(temp_p->pdev);
9672 #endif
9673           kfree(temp_p);
9674         }  /* Found an Adaptec PCI device. */
9675         else /* Well, we found one, but we couldn't get any memory */
9676         {
9677           printk("aic7xxx: Found <%s>\n", 
9678             board_names[aic_pdevs[i].board_name_index]);
9679           printk(KERN_INFO "aic7xxx: Unable to allocate device memory, "
9680             "skipping.\n");
9681         }
9682       } /* while(pdev=....) */
9683     } /* for PCI_DEVICES */
9684   }
9685 #endif /* CONFIG_PCI */
9686
9687 #if defined(__i386__) || defined(__alpha__)
9688   /*
9689    * EISA/VL-bus card signature probe.
9690    */
9691   slot = MINSLOT;
9692   while ( (slot <= MAXSLOT) &&
9693          !(aic7xxx_no_probe) )
9694   {
9695     base = SLOTBASE(slot) + MINREG;
9696
9697     if (!request_region(base, MAXREG - MINREG, "aic7xxx"))
9698     {
9699       /*
9700        * Some other driver has staked a
9701        * claim to this i/o region already.
9702        */
9703       slot++;
9704       continue; /* back to the beginning of the for loop */
9705     }
9706     flags = 0;
9707     type = aic7xxx_probe(slot, base + AHC_HID0, &flags);
9708     if (type == -1)
9709     {
9710       release_region(base, MAXREG - MINREG);
9711       slot++;
9712       continue;
9713     }
9714     temp_p = kmalloc(sizeof(struct aic7xxx_host), GFP_ATOMIC);
9715     if (temp_p == NULL)
9716     {
9717       printk(KERN_WARNING "aic7xxx: Unable to allocate device space.\n");
9718       release_region(base, MAXREG - MINREG);
9719       slot++;
9720       continue; /* back to the beginning of the while loop */
9721     }
9722
9723     /*
9724      * Pause the card preserving the IRQ type.  Allow the operator
9725      * to override the IRQ trigger.
9726      */
9727     if (aic7xxx_irq_trigger == 1)
9728       hcntrl = IRQMS;  /* Level */
9729     else if (aic7xxx_irq_trigger == 0)
9730       hcntrl = 0;  /* Edge */
9731     else
9732       hcntrl = inb(base + HCNTRL) & IRQMS;  /* Default */
9733     memset(temp_p, 0, sizeof(struct aic7xxx_host));
9734     temp_p->unpause = hcntrl | INTEN;
9735     temp_p->pause = hcntrl | PAUSE | INTEN;
9736     temp_p->base = base;
9737     temp_p->mbase = 0;
9738     temp_p->maddr = NULL;
9739     temp_p->pci_bus = 0;
9740     temp_p->pci_device_fn = slot;
9741     aic_outb(temp_p, hcntrl | PAUSE, HCNTRL);
9742     while( (aic_inb(temp_p, HCNTRL) & PAUSE) == 0 ) ;
9743     if (aic7xxx_chip_reset(temp_p) == -1)
9744       temp_p->irq = 0;
9745     else
9746       temp_p->irq = aic_inb(temp_p, INTDEF) & 0x0F;
9747     temp_p->flags |= AHC_PAGESCBS;
9748
9749     switch (temp_p->irq)
9750     {
9751       case 9:
9752       case 10:
9753       case 11:
9754       case 12:
9755       case 14:
9756       case 15:
9757         break;
9758
9759       default:
9760         printk(KERN_WARNING "aic7xxx: Host adapter uses unsupported IRQ "
9761           "level %d, ignoring.\n", temp_p->irq);
9762         kfree(temp_p);
9763         release_region(base, MAXREG - MINREG);
9764         slot++;
9765         continue; /* back to the beginning of the while loop */
9766     }
9767
9768     /*
9769      * We are commited now, everything has been checked and this card
9770      * has been found, now we just set it up
9771      */
9772
9773     /*
9774      * Insert our new struct into the list at the end
9775      */
9776     if (list_p == NULL)
9777     {
9778       list_p = current_p = temp_p;
9779     }
9780     else
9781     {
9782       current_p = list_p;
9783       while (current_p->next != NULL)
9784         current_p = current_p->next;
9785       current_p->next = temp_p;
9786     }
9787
9788     switch (type)
9789     {
9790       case 0:
9791         temp_p->board_name_index = 2;
9792         if (aic7xxx_verbose & VERBOSE_PROBE2)
9793           printk("aic7xxx: <%s> at EISA %d\n",
9794                board_names[2], slot);
9795         /* FALLTHROUGH */
9796       case 1:
9797       {
9798         temp_p->chip = AHC_AIC7770 | AHC_EISA;
9799         temp_p->features |= AHC_AIC7770_FE;
9800         temp_p->bios_control = aic_inb(temp_p, HA_274_BIOSCTRL);
9801
9802         /*
9803          * Get the primary channel information.  Right now we don't
9804          * do anything with this, but someday we will be able to inform
9805          * the mid-level SCSI code which channel is primary.
9806          */
9807         if (temp_p->board_name_index == 0)
9808         {
9809           temp_p->board_name_index = 3;
9810           if (aic7xxx_verbose & VERBOSE_PROBE2)
9811             printk("aic7xxx: <%s> at EISA %d\n",
9812                  board_names[3], slot);
9813         }
9814         if (temp_p->bios_control & CHANNEL_B_PRIMARY)
9815         {
9816           temp_p->flags |= AHC_CHANNEL_B_PRIMARY;
9817         }
9818
9819         if ((temp_p->bios_control & BIOSMODE) == BIOSDISABLED)
9820         {
9821           temp_p->flags &= ~AHC_BIOS_ENABLED;
9822         }
9823         else
9824         {
9825           temp_p->flags &= ~AHC_USEDEFAULTS;
9826           temp_p->flags |= AHC_BIOS_ENABLED;
9827           if ( (temp_p->bios_control & 0x20) == 0 )
9828           {
9829             temp_p->bios_address = 0xcc000;
9830             temp_p->bios_address += (0x4000 * (temp_p->bios_control & 0x07));
9831           }
9832           else
9833           {
9834             temp_p->bios_address = 0xd0000;
9835             temp_p->bios_address += (0x8000 * (temp_p->bios_control & 0x06));
9836           }
9837         }
9838         temp_p->adapter_control = aic_inb(temp_p, SCSICONF) << 8;
9839         temp_p->adapter_control |= aic_inb(temp_p, SCSICONF + 1);
9840         if (temp_p->features & AHC_WIDE)
9841         {
9842           temp_p->scsi_id = temp_p->adapter_control & HWSCSIID;
9843           temp_p->scsi_id_b = temp_p->scsi_id;
9844         }
9845         else
9846         {
9847           temp_p->scsi_id = (temp_p->adapter_control >> 8) & HSCSIID;
9848           temp_p->scsi_id_b = temp_p->adapter_control & HSCSIID;
9849         }
9850         aic7xxx_load_seeprom(temp_p, &sxfrctl1);
9851         break;
9852       }
9853
9854       case 2:
9855       case 3:
9856         temp_p->chip = AHC_AIC7770 | AHC_VL;
9857         temp_p->features |= AHC_AIC7770_FE;
9858         if (type == 2)
9859           temp_p->flags |= AHC_BIOS_ENABLED;
9860         else
9861           temp_p->flags &= ~AHC_BIOS_ENABLED;
9862         if (aic_inb(temp_p, SCSICONF) & TERM_ENB)
9863           sxfrctl1 = STPWEN;
9864         aic7xxx_load_seeprom(temp_p, &sxfrctl1);
9865         temp_p->board_name_index = 4;
9866         if (aic7xxx_verbose & VERBOSE_PROBE2)
9867           printk("aic7xxx: <%s> at VLB %d\n",
9868                board_names[2], slot);
9869         switch( aic_inb(temp_p, STATUS_2840) & BIOS_SEL )
9870         {
9871           case 0x00:
9872             temp_p->bios_address = 0xe0000;
9873             break;
9874           case 0x20:
9875             temp_p->bios_address = 0xc8000;
9876             break;
9877           case 0x40:
9878             temp_p->bios_address = 0xd0000;
9879             break;
9880           case 0x60:
9881             temp_p->bios_address = 0xd8000;
9882             break;
9883           default:
9884             break; /* can't get here */
9885         }
9886         break;
9887
9888       default:  /* Won't get here. */
9889         break;
9890     }
9891     if (aic7xxx_verbose & VERBOSE_PROBE2)
9892     {
9893       printk(KERN_INFO "aic7xxx: BIOS %sabled, IO Port 0x%lx, IRQ %d (%s)\n",
9894         (temp_p->flags & AHC_USEDEFAULTS) ? "dis" : "en", temp_p->base,
9895         temp_p->irq,
9896         (temp_p->pause & IRQMS) ? "level sensitive" : "edge triggered");
9897       printk(KERN_INFO "aic7xxx: Extended translation %sabled.\n",
9898              (temp_p->flags & AHC_EXTEND_TRANS_A) ? "en" : "dis");
9899     }
9900
9901     /*
9902      * All the 7770 based chipsets have this bug
9903      */
9904     temp_p->bugs |= AHC_BUG_TMODE_WIDEODD;
9905
9906     /*
9907      * Set the FIFO threshold and the bus off time.
9908      */
9909     hostconf = aic_inb(temp_p, HOSTCONF);
9910     aic_outb(temp_p, hostconf & DFTHRSH, BUSSPD);
9911     aic_outb(temp_p, (hostconf << 2) & BOFF, BUSTIME);
9912     slot++;
9913     found++;
9914   }
9915
9916 #endif /* defined(__i386__) || defined(__alpha__) */
9917
9918   /*
9919    * Now, we re-order the probed devices by BIOS address and BUS class.
9920    * In general, we follow this algorithm to make the adapters show up
9921    * in the same order under linux that the computer finds them.
9922    *  1: All VLB/EISA cards with BIOS_ENABLED first, according to BIOS
9923    *     address, going from lowest to highest.
9924    *  2: All PCI controllers with BIOS_ENABLED next, according to BIOS
9925    *     address, going from lowest to highest.
9926    *  3: Remaining VLB/EISA controllers going in slot order.
9927    *  4: Remaining PCI controllers, going in PCI device order (reversable)
9928    */
9929
9930   {
9931     struct aic7xxx_host *sort_list[4] = { NULL, NULL, NULL, NULL };
9932     struct aic7xxx_host *vlb, *pci;
9933     struct aic7xxx_host *prev_p;
9934     struct aic7xxx_host *p;
9935     unsigned char left;
9936
9937     prev_p = vlb = pci = NULL;
9938
9939     temp_p = list_p;
9940     while (temp_p != NULL)
9941     {
9942       switch(temp_p->chip & ~AHC_CHIPID_MASK)
9943       {
9944         case AHC_EISA:
9945         case AHC_VL:
9946         {
9947           p = temp_p;
9948           if (p->flags & AHC_BIOS_ENABLED)
9949             vlb = sort_list[0];
9950           else
9951             vlb = sort_list[2];
9952
9953           if (vlb == NULL)
9954           {
9955             vlb = temp_p;
9956             temp_p = temp_p->next;
9957             vlb->next = NULL;
9958           }
9959           else
9960           {
9961             current_p = vlb;
9962             prev_p = NULL;
9963             while ( (current_p != NULL) &&
9964                     (current_p->bios_address < temp_p->bios_address))
9965             {
9966               prev_p = current_p;
9967               current_p = current_p->next;
9968             }
9969             if (prev_p != NULL)
9970             {
9971               prev_p->next = temp_p;
9972               temp_p = temp_p->next;
9973               prev_p->next->next = current_p;
9974             }
9975             else
9976             {
9977               vlb = temp_p;
9978               temp_p = temp_p->next;
9979               vlb->next = current_p;
9980             }
9981           }
9982           
9983           if (p->flags & AHC_BIOS_ENABLED)
9984             sort_list[0] = vlb;
9985           else
9986             sort_list[2] = vlb;
9987           
9988           break;
9989         }
9990         default:  /* All PCI controllers fall through to default */
9991         {
9992
9993           p = temp_p;
9994           if (p->flags & AHC_BIOS_ENABLED) 
9995             pci = sort_list[1];
9996           else
9997             pci = sort_list[3];
9998
9999           if (pci == NULL)
10000           {
10001             pci = temp_p;
10002             temp_p = temp_p->next;
10003             pci->next = NULL;
10004           }
10005           else
10006           {
10007             current_p = pci;
10008             prev_p = NULL;
10009             if (!aic7xxx_reverse_scan)
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             else
10022             {
10023               while ( (current_p != NULL) &&
10024                       ( (PCI_SLOT(current_p->pci_device_fn) |
10025                         (current_p->pci_bus << 8)) > 
10026                         (PCI_SLOT(temp_p->pci_device_fn) |
10027                         (temp_p->pci_bus << 8)) ) )
10028               {
10029                 prev_p = current_p;
10030                 current_p = current_p->next;
10031               }
10032             }
10033             /*
10034              * Are we dealing with a 7895/6/7/9 where we need to sort the
10035              * channels as well, if so, the bios_address values should
10036              * be the same
10037              */
10038             if ( (current_p) && (temp_p->flags & AHC_MULTI_CHANNEL) &&
10039                  (temp_p->pci_bus == current_p->pci_bus) &&
10040                  (PCI_SLOT(temp_p->pci_device_fn) ==
10041                   PCI_SLOT(current_p->pci_device_fn)) )
10042             {
10043               if (temp_p->flags & AHC_CHNLB)
10044               {
10045                 if ( !(temp_p->flags & AHC_CHANNEL_B_PRIMARY) )
10046                 {
10047                   prev_p = current_p;
10048                   current_p = current_p->next;
10049                 }
10050               }
10051               else
10052               {
10053                 if (temp_p->flags & AHC_CHANNEL_B_PRIMARY)
10054                 {
10055                   prev_p = current_p;
10056                   current_p = current_p->next;
10057                 }
10058               }
10059             }
10060             if (prev_p != NULL)
10061             {
10062               prev_p->next = temp_p;
10063               temp_p = temp_p->next;
10064               prev_p->next->next = current_p;
10065             }
10066             else
10067             {
10068               pci = temp_p;
10069               temp_p = temp_p->next;
10070               pci->next = current_p;
10071             }
10072           }
10073
10074           if (p->flags & AHC_BIOS_ENABLED)
10075             sort_list[1] = pci;
10076           else
10077             sort_list[3] = pci;
10078
10079           break;
10080         }
10081       }  /* End of switch(temp_p->type) */
10082     } /* End of while (temp_p != NULL) */
10083     /*
10084      * At this point, the cards have been broken into 4 sorted lists, now
10085      * we run through the lists in order and register each controller
10086      */
10087     {
10088       int i;
10089       
10090       left = found;
10091       for (i=0; i<ARRAY_SIZE(sort_list); i++)
10092       {
10093         temp_p = sort_list[i];
10094         while(temp_p != NULL)
10095         {
10096           template->name = board_names[temp_p->board_name_index];
10097           p = aic7xxx_alloc(template, temp_p);
10098           if (p != NULL)
10099           {
10100             p->instance = found - left;
10101             if (aic7xxx_register(template, p, (--left)) == 0)
10102             {
10103               found--;
10104               aic7xxx_release(p->host);
10105               scsi_unregister(p->host);
10106             }
10107             else if (aic7xxx_dump_card)
10108             {
10109               pause_sequencer(p);
10110               aic7xxx_print_card(p);
10111               aic7xxx_print_scratch_ram(p);
10112               unpause_sequencer(p, TRUE);
10113             }
10114           }
10115           current_p = temp_p;
10116           temp_p = (struct aic7xxx_host *)temp_p->next;
10117           kfree(current_p);
10118         }
10119       }
10120     }
10121   }
10122   return (found);
10123 }
10124
10125 /*+F*************************************************************************
10126  * Function:
10127  *   aic7xxx_buildscb
10128  *
10129  * Description:
10130  *   Build a SCB.
10131  *-F*************************************************************************/
10132 static void aic7xxx_buildscb(struct aic7xxx_host *p, struct scsi_cmnd *cmd,
10133                              struct aic7xxx_scb *scb)
10134 {
10135   unsigned short mask;
10136   struct aic7xxx_hwscb *hscb;
10137   struct aic_dev_data *aic_dev = cmd->device->hostdata;
10138   struct scsi_device *sdptr = cmd->device;
10139   unsigned char tindex = TARGET_INDEX(cmd);
10140   struct request *req = cmd->request;
10141
10142   mask = (0x01 << tindex);
10143   hscb = scb->hscb;
10144
10145   /*
10146    * Setup the control byte if we need negotiation and have not
10147    * already requested it.
10148    */
10149   hscb->control = 0;
10150   scb->tag_action = 0;
10151
10152   if (p->discenable & mask)
10153   {
10154     hscb->control |= DISCENB;
10155     /* We always force TEST_UNIT_READY to untagged */
10156     if (cmd->cmnd[0] != TEST_UNIT_READY && sdptr->simple_tags)
10157     {
10158       if (req->cmd_flags & REQ_HARDBARRIER)
10159       {
10160         if(sdptr->ordered_tags)
10161         {
10162           hscb->control |= MSG_ORDERED_Q_TAG;
10163           scb->tag_action = MSG_ORDERED_Q_TAG;
10164         }
10165       }
10166       else
10167       {
10168         hscb->control |= MSG_SIMPLE_Q_TAG;
10169         scb->tag_action = MSG_SIMPLE_Q_TAG;
10170       }
10171     }
10172   }
10173   if ( !(aic_dev->dtr_pending) &&
10174         (aic_dev->needppr || aic_dev->needwdtr || aic_dev->needsdtr) &&
10175         (aic_dev->flags & DEVICE_DTR_SCANNED) )
10176   {
10177     aic_dev->dtr_pending = 1;
10178     scb->tag_action = 0;
10179     hscb->control &= DISCENB;
10180     hscb->control |= MK_MESSAGE;
10181     if(aic_dev->needppr)
10182     {
10183       scb->flags |= SCB_MSGOUT_PPR;
10184     }
10185     else if(aic_dev->needwdtr)
10186     {
10187       scb->flags |= SCB_MSGOUT_WDTR;
10188     }
10189     else if(aic_dev->needsdtr)
10190     {
10191       scb->flags |= SCB_MSGOUT_SDTR;
10192     }
10193     scb->flags |= SCB_DTR_SCB;
10194   }
10195   hscb->target_channel_lun = ((cmd->device->id << 4) & 0xF0) |
10196         ((cmd->device->channel & 0x01) << 3) | (cmd->device->lun & 0x07);
10197
10198   /*
10199    * The interpretation of request_buffer and request_bufflen
10200    * changes depending on whether or not use_sg is zero; a
10201    * non-zero use_sg indicates the number of elements in the
10202    * scatter-gather array.
10203    */
10204
10205   /*
10206    * XXX - this relies on the host data being stored in a
10207    *       little-endian format.
10208    */
10209   hscb->SCSI_cmd_length = cmd->cmd_len;
10210   memcpy(scb->cmnd, cmd->cmnd, cmd->cmd_len);
10211   hscb->SCSI_cmd_pointer = cpu_to_le32(SCB_DMA_ADDR(scb, scb->cmnd));
10212
10213   if (cmd->use_sg)
10214   {
10215     struct scatterlist *sg;  /* Must be mid-level SCSI code scatterlist */
10216
10217     /*
10218      * We must build an SG list in adapter format, as the kernel's SG list
10219      * cannot be used directly because of data field size (__alpha__)
10220      * differences and the kernel SG list uses virtual addresses where
10221      * we need physical addresses.
10222      */
10223     int i, use_sg;
10224
10225     sg = (struct scatterlist *)cmd->request_buffer;
10226     scb->sg_length = 0;
10227     use_sg = pci_map_sg(p->pdev, sg, cmd->use_sg, cmd->sc_data_direction);
10228     /*
10229      * Copy the segments into the SG array.  NOTE!!! - We used to
10230      * have the first entry both in the data_pointer area and the first
10231      * SG element.  That has changed somewhat.  We still have the first
10232      * entry in both places, but now we download the address of
10233      * scb->sg_list[1] instead of 0 to the sg pointer in the hscb.
10234      */
10235     for (i = 0; i < use_sg; i++)
10236     {
10237       unsigned int len = sg_dma_len(sg+i);
10238       scb->sg_list[i].address = cpu_to_le32(sg_dma_address(sg+i));
10239       scb->sg_list[i].length = cpu_to_le32(len);
10240       scb->sg_length += len;
10241     }
10242     /* Copy the first SG into the data pointer area. */
10243     hscb->data_pointer = scb->sg_list[0].address;
10244     hscb->data_count = scb->sg_list[0].length;
10245     scb->sg_count = i;
10246     hscb->SG_segment_count = i;
10247     hscb->SG_list_pointer = cpu_to_le32(SCB_DMA_ADDR(scb, &scb->sg_list[1]));
10248   }
10249   else
10250   {
10251     if (cmd->request_bufflen)
10252     {
10253       unsigned int address = pci_map_single(p->pdev, cmd->request_buffer,
10254                                             cmd->request_bufflen,
10255                                             cmd->sc_data_direction);
10256       aic7xxx_mapping(cmd) = address;
10257       scb->sg_list[0].address = cpu_to_le32(address);
10258       scb->sg_list[0].length = cpu_to_le32(cmd->request_bufflen);
10259       scb->sg_count = 1;
10260       scb->sg_length = cmd->request_bufflen;
10261       hscb->SG_segment_count = 1;
10262       hscb->SG_list_pointer = cpu_to_le32(SCB_DMA_ADDR(scb, &scb->sg_list[0]));
10263       hscb->data_count = scb->sg_list[0].length;
10264       hscb->data_pointer = scb->sg_list[0].address;
10265     }
10266     else
10267     {
10268       scb->sg_count = 0;
10269       scb->sg_length = 0;
10270       hscb->SG_segment_count = 0;
10271       hscb->SG_list_pointer = 0;
10272       hscb->data_count = 0;
10273       hscb->data_pointer = 0;
10274     }
10275   }
10276 }
10277
10278 /*+F*************************************************************************
10279  * Function:
10280  *   aic7xxx_queue
10281  *
10282  * Description:
10283  *   Queue a SCB to the controller.
10284  *-F*************************************************************************/
10285 static int aic7xxx_queue(struct scsi_cmnd *cmd, void (*fn)(struct scsi_cmnd *))
10286 {
10287   struct aic7xxx_host *p;
10288   struct aic7xxx_scb *scb;
10289   struct aic_dev_data *aic_dev;
10290
10291   p = (struct aic7xxx_host *) cmd->device->host->hostdata;
10292
10293   aic_dev = cmd->device->hostdata;  
10294 #ifdef AIC7XXX_VERBOSE_DEBUGGING
10295   if (aic_dev->active_cmds > aic_dev->max_q_depth)
10296   {
10297     printk(WARN_LEAD "Commands queued exceeds queue "
10298            "depth, active=%d\n",
10299            p->host_no, CTL_OF_CMD(cmd), 
10300            aic_dev->active_cmds);
10301   }
10302 #endif
10303
10304   scb = scbq_remove_head(&p->scb_data->free_scbs);
10305   if (scb == NULL)
10306   {
10307     aic7xxx_allocate_scb(p);
10308     scb = scbq_remove_head(&p->scb_data->free_scbs);
10309     if(scb == NULL)
10310     {
10311       printk(WARN_LEAD "Couldn't get a free SCB.\n", p->host_no,
10312              CTL_OF_CMD(cmd));
10313       return 1;
10314     }
10315   }
10316   scb->cmd = cmd;
10317
10318         /*
10319         * Make sure the scsi_cmnd pointer is saved, the struct it points to
10320         * is set up properly, and the parity error flag is reset, then send
10321         * the SCB to the sequencer and watch the fun begin.
10322         */
10323   aic7xxx_position(cmd) = scb->hscb->tag;
10324   cmd->scsi_done = fn;
10325   cmd->result = DID_OK;
10326   memset(cmd->sense_buffer, 0, sizeof(cmd->sense_buffer));
10327   aic7xxx_error(cmd) = DID_OK;
10328   aic7xxx_status(cmd) = 0;
10329   cmd->host_scribble = NULL;
10330
10331   /*
10332    * Construct the SCB beforehand, so the sequencer is
10333    * paused a minimal amount of time.
10334    */
10335   aic7xxx_buildscb(p, cmd, scb);
10336
10337   scb->flags |= SCB_ACTIVE | SCB_WAITINGQ;
10338
10339   scbq_insert_tail(&p->waiting_scbs, scb);
10340   aic7xxx_run_waiting_queues(p);
10341   return (0);
10342 }
10343
10344 /*+F*************************************************************************
10345  * Function:
10346  *   aic7xxx_bus_device_reset
10347  *
10348  * Description:
10349  *   Abort or reset the current SCSI command(s).  If the scb has not
10350  *   previously been aborted, then we attempt to send a BUS_DEVICE_RESET
10351  *   message to the target.  If the scb has previously been unsuccessfully
10352  *   aborted, then we will reset the channel and have all devices renegotiate.
10353  *   Returns an enumerated type that indicates the status of the operation.
10354  *-F*************************************************************************/
10355 static int __aic7xxx_bus_device_reset(struct scsi_cmnd *cmd)
10356 {
10357   struct aic7xxx_host  *p;
10358   struct aic7xxx_scb   *scb;
10359   struct aic7xxx_hwscb *hscb;
10360   int channel;
10361   unsigned char saved_scbptr, lastphase;
10362   unsigned char hscb_index;
10363   int disconnected;
10364   struct aic_dev_data *aic_dev;
10365
10366   if(cmd == NULL)
10367   {
10368     printk(KERN_ERR "aic7xxx_bus_device_reset: called with NULL cmd!\n");
10369     return FAILED;
10370   }
10371   p = (struct aic7xxx_host *)cmd->device->host->hostdata;
10372   aic_dev = AIC_DEV(cmd);
10373   if(aic7xxx_position(cmd) < p->scb_data->numscbs)
10374     scb = (p->scb_data->scb_array[aic7xxx_position(cmd)]);
10375   else
10376     return FAILED;
10377
10378   hscb = scb->hscb;
10379
10380   aic7xxx_isr(p);
10381   aic7xxx_done_cmds_complete(p);
10382   /* If the command was already complete or just completed, then we didn't
10383    * do a reset, return FAILED */
10384   if(!(scb->flags & SCB_ACTIVE))
10385     return FAILED;
10386
10387   pause_sequencer(p);
10388   lastphase = aic_inb(p, LASTPHASE);
10389   if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
10390   {
10391     printk(INFO_LEAD "Bus Device reset, scb flags 0x%x, ",
10392          p->host_no, CTL_OF_SCB(scb), scb->flags);
10393     switch (lastphase)
10394     {
10395       case P_DATAOUT:
10396         printk("Data-Out phase\n");
10397         break;
10398       case P_DATAIN:
10399         printk("Data-In phase\n");
10400         break;
10401       case P_COMMAND:
10402         printk("Command phase\n");
10403         break;
10404       case P_MESGOUT:
10405         printk("Message-Out phase\n");
10406         break;
10407       case P_STATUS:
10408         printk("Status phase\n");
10409         break;
10410       case P_MESGIN:
10411         printk("Message-In phase\n");
10412         break;
10413       default:
10414       /*
10415        * We're not in a valid phase, so assume we're idle.
10416        */
10417         printk("while idle, LASTPHASE = 0x%x\n", lastphase);
10418         break;
10419     }
10420     printk(INFO_LEAD "SCSISIGI 0x%x, SEQADDR 0x%x, SSTAT0 0x%x, SSTAT1 "
10421          "0x%x\n", p->host_no, CTL_OF_SCB(scb),
10422          aic_inb(p, SCSISIGI),
10423          aic_inb(p, SEQADDR0) | (aic_inb(p, SEQADDR1) << 8),
10424          aic_inb(p, SSTAT0), aic_inb(p, SSTAT1));
10425     printk(INFO_LEAD "SG_CACHEPTR 0x%x, SSTAT2 0x%x, STCNT 0x%x\n", p->host_no,
10426          CTL_OF_SCB(scb),
10427          (p->features & AHC_ULTRA2) ? aic_inb(p, SG_CACHEPTR) : 0,
10428          aic_inb(p, SSTAT2),
10429          aic_inb(p, STCNT + 2) << 16 | aic_inb(p, STCNT + 1) << 8 |
10430          aic_inb(p, STCNT));
10431   }
10432
10433   channel = cmd->device->channel;
10434
10435     /*
10436      * Send a Device Reset Message:
10437      * The target that is holding up the bus may not be the same as
10438      * the one that triggered this timeout (different commands have
10439      * different timeout lengths).  Our strategy here is to queue an
10440      * abort message to the timed out target if it is disconnected.
10441      * Otherwise, if we have an active target we stuff the message buffer
10442      * with an abort message and assert ATN in the hopes that the target
10443      * will let go of the bus and go to the mesgout phase.  If this
10444      * fails, we'll get another timeout a few seconds later which will
10445      * attempt a bus reset.
10446      */
10447   saved_scbptr = aic_inb(p, SCBPTR);
10448   disconnected = FALSE;
10449
10450   if (lastphase != P_BUSFREE)
10451   {
10452     if (aic_inb(p, SCB_TAG) >= p->scb_data->numscbs)
10453     {
10454       printk(WARN_LEAD "Invalid SCB ID %d is active, "
10455              "SCB flags = 0x%x.\n", p->host_no,
10456             CTL_OF_CMD(cmd), scb->hscb->tag, scb->flags);
10457       unpause_sequencer(p, FALSE);
10458       return FAILED;
10459     }
10460     if (scb->hscb->tag == aic_inb(p, SCB_TAG))
10461     { 
10462       if ( (lastphase == P_MESGOUT) || (lastphase == P_MESGIN) )
10463       {
10464         printk(WARN_LEAD "Device reset, Message buffer "
10465                 "in use\n", p->host_no, CTL_OF_SCB(scb));
10466         unpause_sequencer(p, FALSE);
10467         return FAILED;
10468       }
10469         
10470       if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
10471         printk(INFO_LEAD "Device reset message in "
10472               "message buffer\n", p->host_no, CTL_OF_SCB(scb));
10473       scb->flags |= SCB_RESET | SCB_DEVICE_RESET;
10474       aic7xxx_error(cmd) = DID_RESET;
10475       aic_dev->flags |= BUS_DEVICE_RESET_PENDING;
10476       /* Send the abort message to the active SCB. */
10477       aic_outb(p, HOST_MSG, MSG_OUT);
10478       aic_outb(p, lastphase | ATNO, SCSISIGO);
10479       unpause_sequencer(p, FALSE);
10480       spin_unlock_irq(p->host->host_lock);
10481       ssleep(1);
10482       spin_lock_irq(p->host->host_lock);
10483       if(aic_dev->flags & BUS_DEVICE_RESET_PENDING)
10484         return FAILED;
10485       else
10486         return SUCCESS;
10487     }
10488   } /* if (last_phase != P_BUSFREE).....indicates we are idle and can work */
10489   /*
10490    * Simply set the MK_MESSAGE flag and the SEQINT handler will do
10491    * the rest on a reconnect/connect.
10492    */
10493   scb->hscb->control |= MK_MESSAGE;
10494   scb->flags |= SCB_RESET | SCB_DEVICE_RESET;
10495   aic_dev->flags |= BUS_DEVICE_RESET_PENDING;
10496   /*
10497    * Check to see if the command is on the qinfifo.  If it is, then we will
10498    * not need to queue the command again since the card should start it soon
10499    */
10500   if (aic7xxx_search_qinfifo(p, cmd->device->channel, cmd->device->id, cmd->device->lun, hscb->tag,
10501                           0, TRUE, NULL) == 0)
10502   {
10503     disconnected = TRUE;
10504     if ((hscb_index = aic7xxx_find_scb(p, scb)) != SCB_LIST_NULL)
10505     {
10506       unsigned char scb_control;
10507
10508       aic_outb(p, hscb_index, SCBPTR);
10509       scb_control = aic_inb(p, SCB_CONTROL);
10510       /*
10511        * If the DISCONNECTED bit is not set in SCB_CONTROL, then we are
10512        * actually on the waiting list, not disconnected, and we don't
10513        * need to requeue the command.
10514        */
10515       disconnected = (scb_control & DISCONNECTED);
10516       aic_outb(p, scb_control | MK_MESSAGE, SCB_CONTROL);
10517     }
10518     if (disconnected)
10519     {
10520       /*
10521        * Actually requeue this SCB in case we can select the
10522        * device before it reconnects.  This can result in the command
10523        * being on the qinfifo twice, but we don't care because it will
10524        * all get cleaned up if/when the reset takes place.
10525        */
10526       if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
10527         printk(INFO_LEAD "Queueing device reset command.\n", p->host_no,
10528                       CTL_OF_SCB(scb));
10529       p->qinfifo[p->qinfifonext++] = scb->hscb->tag;
10530       if (p->features & AHC_QUEUE_REGS)
10531         aic_outb(p, p->qinfifonext, HNSCB_QOFF);
10532       else
10533         aic_outb(p, p->qinfifonext, KERNEL_QINPOS);
10534       scb->flags |= SCB_QUEUED_ABORT;
10535     }
10536   }
10537   aic_outb(p, saved_scbptr, SCBPTR);
10538   unpause_sequencer(p, FALSE);
10539   spin_unlock_irq(p->host->host_lock);
10540   msleep(1000/4);
10541   spin_lock_irq(p->host->host_lock);
10542   if(aic_dev->flags & BUS_DEVICE_RESET_PENDING)
10543     return FAILED;
10544   else
10545     return SUCCESS;
10546 }
10547
10548 static int aic7xxx_bus_device_reset(struct scsi_cmnd *cmd)
10549 {
10550       int rc;
10551
10552       spin_lock_irq(cmd->device->host->host_lock);
10553       rc = __aic7xxx_bus_device_reset(cmd);
10554       spin_unlock_irq(cmd->device->host->host_lock);
10555
10556       return rc;
10557 }
10558
10559
10560 /*+F*************************************************************************
10561  * Function:
10562  *   aic7xxx_panic_abort
10563  *
10564  * Description:
10565  *   Abort the current SCSI command(s).
10566  *-F*************************************************************************/
10567 static void aic7xxx_panic_abort(struct aic7xxx_host *p, struct scsi_cmnd *cmd)
10568 {
10569
10570   printk("aic7xxx driver version %s\n", AIC7XXX_C_VERSION);
10571   printk("Controller type:\n    %s\n", board_names[p->board_name_index]);
10572   printk("p->flags=0x%lx, p->chip=0x%x, p->features=0x%x, "
10573          "sequencer %s paused\n",
10574      p->flags, p->chip, p->features,
10575     (aic_inb(p, HCNTRL) & PAUSE) ? "is" : "isn't" );
10576   pause_sequencer(p);
10577   disable_irq(p->irq);
10578   aic7xxx_print_card(p);
10579   aic7xxx_print_scratch_ram(p);
10580   spin_unlock_irq(p->host->host_lock);
10581   for(;;) barrier();
10582 }
10583
10584 /*+F*************************************************************************
10585  * Function:
10586  *   aic7xxx_abort
10587  *
10588  * Description:
10589  *   Abort the current SCSI command(s).
10590  *-F*************************************************************************/
10591 static int __aic7xxx_abort(struct scsi_cmnd *cmd)
10592 {
10593   struct aic7xxx_scb  *scb = NULL;
10594   struct aic7xxx_host *p;
10595   int    found=0, disconnected;
10596   unsigned char saved_hscbptr, hscbptr, scb_control;
10597   struct aic_dev_data *aic_dev;
10598
10599   if(cmd == NULL)
10600   {
10601     printk(KERN_ERR "aic7xxx_abort: called with NULL cmd!\n");
10602     return FAILED;
10603   }
10604   p = (struct aic7xxx_host *)cmd->device->host->hostdata;
10605   aic_dev = AIC_DEV(cmd);
10606   if(aic7xxx_position(cmd) < p->scb_data->numscbs)
10607     scb = (p->scb_data->scb_array[aic7xxx_position(cmd)]);
10608   else
10609     return FAILED;
10610
10611   aic7xxx_isr(p);
10612   aic7xxx_done_cmds_complete(p);
10613   /* If the command was already complete or just completed, then we didn't
10614    * do a reset, return FAILED */
10615   if(!(scb->flags & SCB_ACTIVE))
10616     return FAILED;
10617
10618   pause_sequencer(p);
10619
10620   /*
10621    * I added a new config option to the driver: "panic_on_abort" that will
10622    * cause the driver to panic and the machine to stop on the first abort
10623    * or reset call into the driver.  At that point, it prints out a lot of
10624    * useful information for me which I can then use to try and debug the
10625    * problem.  Simply enable the boot time prompt in order to activate this
10626    * code.
10627    */
10628   if (aic7xxx_panic_on_abort)
10629     aic7xxx_panic_abort(p, cmd);
10630
10631   if (aic7xxx_verbose & VERBOSE_ABORT)
10632   {
10633     printk(INFO_LEAD "Aborting scb %d, flags 0x%x, SEQADDR 0x%x, LASTPHASE "
10634            "0x%x\n",
10635          p->host_no, CTL_OF_SCB(scb), scb->hscb->tag, scb->flags,
10636          aic_inb(p, SEQADDR0) | (aic_inb(p, SEQADDR1) << 8),
10637          aic_inb(p, LASTPHASE));
10638     printk(INFO_LEAD "SG_CACHEPTR 0x%x, SG_COUNT %d, SCSISIGI 0x%x\n",
10639          p->host_no, CTL_OF_SCB(scb), (p->features & AHC_ULTRA2) ?
10640          aic_inb(p, SG_CACHEPTR) : 0, aic_inb(p, SG_COUNT),
10641          aic_inb(p, SCSISIGI));
10642     printk(INFO_LEAD "SSTAT0 0x%x, SSTAT1 0x%x, SSTAT2 0x%x\n",
10643          p->host_no, CTL_OF_SCB(scb), aic_inb(p, SSTAT0),
10644          aic_inb(p, SSTAT1), aic_inb(p, SSTAT2));
10645   }
10646
10647   if (scb->flags & SCB_WAITINGQ)
10648   {
10649     if (aic7xxx_verbose & VERBOSE_ABORT_PROCESS) 
10650       printk(INFO_LEAD "SCB found on waiting list and "
10651           "aborted.\n", p->host_no, CTL_OF_SCB(scb));
10652     scbq_remove(&p->waiting_scbs, scb);
10653     scbq_remove(&aic_dev->delayed_scbs, scb);
10654     aic_dev->active_cmds++;
10655     p->activescbs++;
10656     scb->flags &= ~(SCB_WAITINGQ | SCB_ACTIVE);
10657     scb->flags |= SCB_ABORT | SCB_QUEUED_FOR_DONE;
10658     goto success;
10659   }
10660
10661 /*
10662  *  We just checked the waiting_q, now for the QINFIFO
10663  */
10664   if ( ((found = aic7xxx_search_qinfifo(p, cmd->device->id, cmd->device->channel,
10665                      cmd->device->lun, scb->hscb->tag, SCB_ABORT | SCB_QUEUED_FOR_DONE,
10666                      FALSE, NULL)) != 0) &&
10667                     (aic7xxx_verbose & VERBOSE_ABORT_PROCESS))
10668   {
10669     printk(INFO_LEAD "SCB found in QINFIFO and aborted.\n", p->host_no,
10670                     CTL_OF_SCB(scb));
10671     goto success;
10672   }
10673
10674 /*
10675  *  QINFIFO, waitingq, completeq done.  Next, check WAITING_SCB list in card
10676  */
10677
10678   saved_hscbptr = aic_inb(p, SCBPTR);
10679   if ((hscbptr = aic7xxx_find_scb(p, scb)) != SCB_LIST_NULL)
10680   {
10681     aic_outb(p, hscbptr, SCBPTR);
10682     scb_control = aic_inb(p, SCB_CONTROL);
10683     disconnected = scb_control & DISCONNECTED;
10684     /*
10685      * If the DISCONNECTED bit is not set in SCB_CONTROL, then we are
10686      * either currently active or on the waiting list.
10687      */
10688     if(!disconnected && aic_inb(p, LASTPHASE) == P_BUSFREE) {
10689       if (aic7xxx_verbose & VERBOSE_ABORT_PROCESS)
10690         printk(INFO_LEAD "SCB found on hardware waiting"
10691           " list and aborted.\n", p->host_no, CTL_OF_SCB(scb));
10692       /* If we are the only waiting command, stop the selection engine */
10693       if (aic_inb(p, WAITING_SCBH) == hscbptr && aic_inb(p, SCB_NEXT) ==
10694                         SCB_LIST_NULL)
10695       {
10696         aic_outb(p, aic_inb(p, SCSISEQ) & ~ENSELO, SCSISEQ);
10697         aic_outb(p, CLRSELTIMEO, CLRSINT1);
10698         aic_outb(p, SCB_LIST_NULL, WAITING_SCBH);
10699       }
10700       else
10701       {
10702         unsigned char prev, next;
10703         prev = SCB_LIST_NULL;
10704         next = aic_inb(p, WAITING_SCBH);
10705         while(next != SCB_LIST_NULL)
10706         {
10707           aic_outb(p, next, SCBPTR);
10708           if (next == hscbptr)
10709           {
10710             next = aic_inb(p, SCB_NEXT);
10711             if (prev != SCB_LIST_NULL)
10712             {
10713               aic_outb(p, prev, SCBPTR);
10714               aic_outb(p, next, SCB_NEXT);
10715             }
10716             else
10717               aic_outb(p, next, WAITING_SCBH);
10718             aic_outb(p, hscbptr, SCBPTR);
10719             next = SCB_LIST_NULL;
10720           }
10721           else
10722           {
10723             prev = next;
10724             next = aic_inb(p, SCB_NEXT);
10725           }
10726         }
10727       }
10728       aic_outb(p, SCB_LIST_NULL, SCB_TAG);
10729       aic_outb(p, 0, SCB_CONTROL);
10730       aic7xxx_add_curscb_to_free_list(p);
10731       scb->flags = SCB_ABORT | SCB_QUEUED_FOR_DONE;
10732       goto success;
10733     }
10734     else if (!disconnected)
10735     {
10736       /*
10737        * We are the currently active command
10738        */
10739       if((aic_inb(p, LASTPHASE) == P_MESGIN) ||
10740          (aic_inb(p, LASTPHASE) == P_MESGOUT))
10741       {
10742         /*
10743          * Message buffer busy, unable to abort
10744          */
10745         printk(INFO_LEAD "message buffer busy, unable to abort.\n",
10746                           p->host_no, CTL_OF_SCB(scb));
10747         unpause_sequencer(p, FALSE);
10748         return FAILED;
10749       }
10750       /* Fallthrough to below, set ATNO after we set SCB_CONTROL */
10751     } 
10752     aic_outb(p,  scb_control | MK_MESSAGE, SCB_CONTROL);
10753     if(!disconnected)
10754     {
10755       aic_outb(p, HOST_MSG, MSG_OUT);
10756       aic_outb(p, aic_inb(p, SCSISIGI) | ATNO, SCSISIGO);
10757     }
10758     aic_outb(p, saved_hscbptr, SCBPTR);
10759   } 
10760   else
10761   {
10762     /*
10763      * The scb isn't in the card at all and it is active and it isn't in
10764      * any of the queues, so it must be disconnected and paged out.  Fall
10765      * through to the code below.
10766      */
10767     disconnected = 1;
10768   }
10769         
10770   p->flags |= AHC_ABORT_PENDING;
10771   scb->flags |= SCB_QUEUED_ABORT | SCB_ABORT | SCB_RECOVERY_SCB;
10772   scb->hscb->control |= MK_MESSAGE;
10773   if(disconnected)
10774   {
10775     if (aic7xxx_verbose & VERBOSE_ABORT_PROCESS)
10776       printk(INFO_LEAD "SCB disconnected.  Queueing Abort"
10777         " SCB.\n", p->host_no, CTL_OF_SCB(scb));
10778     p->qinfifo[p->qinfifonext++] = scb->hscb->tag;
10779     if (p->features & AHC_QUEUE_REGS)
10780       aic_outb(p, p->qinfifonext, HNSCB_QOFF);
10781     else
10782       aic_outb(p, p->qinfifonext, KERNEL_QINPOS);
10783   }
10784   unpause_sequencer(p, FALSE);
10785   spin_unlock_irq(p->host->host_lock);
10786   msleep(1000/4);
10787   spin_lock_irq(p->host->host_lock);
10788   if (p->flags & AHC_ABORT_PENDING)
10789   {
10790     if (aic7xxx_verbose & VERBOSE_ABORT_RETURN)
10791       printk(INFO_LEAD "Abort never delivered, returning FAILED\n", p->host_no,
10792                     CTL_OF_CMD(cmd));
10793     p->flags &= ~AHC_ABORT_PENDING;
10794     return FAILED;
10795   }
10796   if (aic7xxx_verbose & VERBOSE_ABORT_RETURN)
10797     printk(INFO_LEAD "Abort successful.\n", p->host_no, CTL_OF_CMD(cmd));
10798   return SUCCESS;
10799
10800 success:
10801   if (aic7xxx_verbose & VERBOSE_ABORT_RETURN)
10802     printk(INFO_LEAD "Abort successful.\n", p->host_no, CTL_OF_CMD(cmd));
10803   aic7xxx_run_done_queue(p, TRUE);
10804   unpause_sequencer(p, FALSE);
10805   return SUCCESS;
10806 }
10807
10808 static int aic7xxx_abort(struct scsi_cmnd *cmd)
10809 {
10810         int rc;
10811
10812         spin_lock_irq(cmd->device->host->host_lock);
10813         rc = __aic7xxx_abort(cmd);
10814         spin_unlock_irq(cmd->device->host->host_lock);
10815
10816         return rc;
10817 }
10818
10819
10820 /*+F*************************************************************************
10821  * Function:
10822  *   aic7xxx_reset
10823  *
10824  * Description:
10825  *   Resetting the bus always succeeds - is has to, otherwise the
10826  *   kernel will panic! Try a surgical technique - sending a BUS
10827  *   DEVICE RESET message - on the offending target before pulling
10828  *   the SCSI bus reset line.
10829  *-F*************************************************************************/
10830 static int aic7xxx_reset(struct scsi_cmnd *cmd)
10831 {
10832   struct aic7xxx_scb *scb;
10833   struct aic7xxx_host *p;
10834   struct aic_dev_data *aic_dev;
10835
10836   p = (struct aic7xxx_host *) cmd->device->host->hostdata;
10837   spin_lock_irq(p->host->host_lock);
10838
10839   aic_dev = AIC_DEV(cmd);
10840   if(aic7xxx_position(cmd) < p->scb_data->numscbs)
10841   {
10842     scb = (p->scb_data->scb_array[aic7xxx_position(cmd)]);
10843     if (scb->cmd != cmd)
10844       scb = NULL;
10845   }
10846   else
10847   {
10848     scb = NULL;
10849   }
10850
10851   /*
10852    * I added a new config option to the driver: "panic_on_abort" that will
10853    * cause the driver to panic and the machine to stop on the first abort
10854    * or reset call into the driver.  At that point, it prints out a lot of
10855    * useful information for me which I can then use to try and debug the
10856    * problem.  Simply enable the boot time prompt in order to activate this
10857    * code.
10858    */
10859   if (aic7xxx_panic_on_abort)
10860     aic7xxx_panic_abort(p, cmd);
10861
10862   pause_sequencer(p);
10863
10864   while((aic_inb(p, INTSTAT) & INT_PEND) && !(p->flags & AHC_IN_ISR))
10865   {
10866     aic7xxx_isr(p);
10867     pause_sequencer(p);
10868   }
10869   aic7xxx_done_cmds_complete(p);
10870
10871   if(scb && (scb->cmd == NULL))
10872   {
10873     /*
10874      * We just completed the command when we ran the isr stuff, so we no
10875      * longer have it.
10876      */
10877     unpause_sequencer(p, FALSE);
10878     spin_unlock_irq(p->host->host_lock);
10879     return SUCCESS;
10880   }
10881     
10882 /*
10883  *  By this point, we want to already know what we are going to do and
10884  *  only have the following code implement our course of action.
10885  */
10886   aic7xxx_reset_channel(p, cmd->device->channel, TRUE);
10887   if (p->features & AHC_TWIN)
10888   {
10889     aic7xxx_reset_channel(p, cmd->device->channel ^ 0x01, TRUE);
10890     restart_sequencer(p);
10891   }
10892   aic_outb(p,  aic_inb(p, SIMODE1) & ~(ENREQINIT|ENBUSFREE), SIMODE1);
10893   aic7xxx_clear_intstat(p);
10894   p->flags &= ~AHC_HANDLING_REQINITS;
10895   p->msg_type = MSG_TYPE_NONE;
10896   p->msg_index = 0;
10897   p->msg_len = 0;
10898   aic7xxx_run_done_queue(p, TRUE);
10899   unpause_sequencer(p, FALSE);
10900   spin_unlock_irq(p->host->host_lock);
10901   ssleep(2);
10902   return SUCCESS;
10903 }
10904
10905 /*+F*************************************************************************
10906  * Function:
10907  *   aic7xxx_biosparam
10908  *
10909  * Description:
10910  *   Return the disk geometry for the given SCSI device.
10911  *
10912  * Note:
10913  *   This function is broken for today's really large drives and needs
10914  *   fixed.
10915  *-F*************************************************************************/
10916 static int
10917 aic7xxx_biosparam(struct scsi_device *sdev, struct block_device *bdev,
10918                 sector_t capacity, int geom[])
10919 {
10920   sector_t heads, sectors, cylinders;
10921   int ret;
10922   struct aic7xxx_host *p;
10923   unsigned char *buf;
10924
10925   p = (struct aic7xxx_host *) sdev->host->hostdata;
10926   buf = scsi_bios_ptable(bdev);
10927
10928   if ( buf )
10929   {
10930     ret = scsi_partsize(buf, capacity, &geom[2], &geom[0], &geom[1]);
10931     kfree(buf);
10932     if ( ret != -1 )
10933       return(ret);
10934   }
10935   
10936   heads = 64;
10937   sectors = 32;
10938   cylinders = capacity >> 11;
10939
10940   if ((p->flags & AHC_EXTEND_TRANS_A) && (cylinders > 1024))
10941   {
10942     heads = 255;
10943     sectors = 63;
10944     cylinders = capacity >> 14;
10945     if(capacity > (65535 * heads * sectors))
10946       cylinders = 65535;
10947     else
10948       cylinders = ((unsigned int)capacity) / (unsigned int)(heads * sectors);
10949   }
10950
10951   geom[0] = (int)heads;
10952   geom[1] = (int)sectors;
10953   geom[2] = (int)cylinders;
10954
10955   return (0);
10956 }
10957
10958 /*+F*************************************************************************
10959  * Function:
10960  *   aic7xxx_release
10961  *
10962  * Description:
10963  *   Free the passed in Scsi_Host memory structures prior to unloading the
10964  *   module.
10965  *-F*************************************************************************/
10966 static int
10967 aic7xxx_release(struct Scsi_Host *host)
10968 {
10969   struct aic7xxx_host *p = (struct aic7xxx_host *) host->hostdata;
10970   struct aic7xxx_host *next, *prev;
10971
10972   if(p->irq)
10973     free_irq(p->irq, p);
10974 #ifdef MMAPIO
10975   if(p->maddr)
10976   {
10977     iounmap(p->maddr);
10978   }
10979 #endif /* MMAPIO */
10980   if(!p->pdev)
10981     release_region(p->base, MAXREG - MINREG);
10982 #ifdef CONFIG_PCI
10983   else {
10984     pci_release_regions(p->pdev);
10985     pci_dev_put(p->pdev);
10986   }
10987 #endif
10988   prev = NULL;
10989   next = first_aic7xxx;
10990   while(next != NULL)
10991   {
10992     if(next == p)
10993     {
10994       if(prev == NULL)
10995         first_aic7xxx = next->next;
10996       else
10997         prev->next = next->next;
10998     }
10999     else
11000     {
11001       prev = next;
11002     }
11003     next = next->next;
11004   }
11005   aic7xxx_free(p);
11006   return(0);
11007 }
11008
11009 /*+F*************************************************************************
11010  * Function:
11011  *   aic7xxx_print_card
11012  *
11013  * Description:
11014  *   Print out all of the control registers on the card
11015  *
11016  *   NOTE: This function is not yet safe for use on the VLB and EISA
11017  *   controllers, so it isn't used on those controllers at all.
11018  *-F*************************************************************************/
11019 static void
11020 aic7xxx_print_card(struct aic7xxx_host *p)
11021 {
11022   int i, j, k, chip;
11023   static struct register_ranges {
11024     int num_ranges;
11025     int range_val[32];
11026   } cards_ds[] = {
11027     { 0, {0,} }, /* none */
11028     {10, {0x00, 0x05, 0x08, 0x11, 0x18, 0x19, 0x1f, 0x1f, 0x60, 0x60, /*7771*/
11029           0x62, 0x66, 0x80, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9b, 0x9f} },
11030     { 9, {0x00, 0x05, 0x08, 0x11, 0x18, 0x1f, 0x60, 0x60, 0x62, 0x66, /*7850*/
11031           0x80, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9f} },
11032     { 9, {0x00, 0x05, 0x08, 0x11, 0x18, 0x1f, 0x60, 0x60, 0x62, 0x66, /*7860*/
11033           0x80, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9f} },
11034     {10, {0x00, 0x05, 0x08, 0x11, 0x18, 0x19, 0x1c, 0x1f, 0x60, 0x60, /*7870*/
11035           0x62, 0x66, 0x80, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9f} },
11036     {10, {0x00, 0x05, 0x08, 0x11, 0x18, 0x1a, 0x1c, 0x1f, 0x60, 0x60, /*7880*/
11037           0x62, 0x66, 0x80, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9f} },
11038     {16, {0x00, 0x05, 0x08, 0x11, 0x18, 0x1f, 0x60, 0x60, 0x62, 0x66, /*7890*/
11039           0x84, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9a, 0x9f, 0x9f,
11040           0xe0, 0xf1, 0xf4, 0xf4, 0xf6, 0xf6, 0xf8, 0xf8, 0xfa, 0xfc,
11041           0xfe, 0xff} },
11042     {12, {0x00, 0x05, 0x08, 0x11, 0x18, 0x19, 0x1b, 0x1f, 0x60, 0x60, /*7895*/
11043           0x62, 0x66, 0x80, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9a,
11044           0x9f, 0x9f, 0xe0, 0xf1} },
11045     {16, {0x00, 0x05, 0x08, 0x11, 0x18, 0x1f, 0x60, 0x60, 0x62, 0x66, /*7896*/
11046           0x84, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9a, 0x9f, 0x9f,
11047           0xe0, 0xf1, 0xf4, 0xf4, 0xf6, 0xf6, 0xf8, 0xf8, 0xfa, 0xfc,
11048           0xfe, 0xff} },
11049     {12, {0x00, 0x05, 0x08, 0x11, 0x18, 0x1f, 0x60, 0x60, 0x62, 0x66, /*7892*/
11050           0x84, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9a, 0x9c, 0x9f,
11051           0xe0, 0xf1, 0xf4, 0xfc} },
11052     {12, {0x00, 0x05, 0x08, 0x11, 0x18, 0x1f, 0x60, 0x60, 0x62, 0x66, /*7899*/
11053           0x84, 0x8e, 0x90, 0x95, 0x97, 0x97, 0x9a, 0x9a, 0x9c, 0x9f,
11054           0xe0, 0xf1, 0xf4, 0xfc} },
11055   };
11056   chip = p->chip & AHC_CHIPID_MASK;
11057   printk("%s at ",
11058          board_names[p->board_name_index]);
11059   switch(p->chip & ~AHC_CHIPID_MASK)
11060   {
11061     case AHC_VL:
11062       printk("VLB Slot %d.\n", p->pci_device_fn);
11063       break;
11064     case AHC_EISA:
11065       printk("EISA Slot %d.\n", p->pci_device_fn);
11066       break;
11067     case AHC_PCI:
11068     default:
11069       printk("PCI %d/%d/%d.\n", p->pci_bus, PCI_SLOT(p->pci_device_fn),
11070              PCI_FUNC(p->pci_device_fn));
11071       break;
11072   }
11073
11074   /*
11075    * the registers on the card....
11076    */
11077   printk("Card Dump:\n");
11078   k = 0;
11079   for(i=0; i<cards_ds[chip].num_ranges; i++)
11080   {
11081     for(j  = cards_ds[chip].range_val[ i * 2 ];
11082         j <= cards_ds[chip].range_val[ i * 2 + 1 ] ;
11083         j++)
11084     {
11085       printk("%02x:%02x ", j, aic_inb(p, j));
11086       if(++k == 13)
11087       {
11088         printk("\n");
11089         k=0;
11090       }
11091     }
11092   }
11093   if(k != 0)
11094     printk("\n");
11095
11096   /*
11097    * If this was an Ultra2 controller, then we just hosed the card in terms
11098    * of the QUEUE REGS.  This function is only called at init time or by
11099    * the panic_abort function, so it's safe to assume a generic init time
11100    * setting here
11101    */
11102
11103   if(p->features & AHC_QUEUE_REGS)
11104   {
11105     aic_outb(p, 0, SDSCB_QOFF);
11106     aic_outb(p, 0, SNSCB_QOFF);
11107     aic_outb(p, 0, HNSCB_QOFF);
11108   }
11109
11110 }
11111
11112 /*+F*************************************************************************
11113  * Function:
11114  *   aic7xxx_print_scratch_ram
11115  *
11116  * Description:
11117  *   Print out the scratch RAM values on the card.
11118  *-F*************************************************************************/
11119 static void
11120 aic7xxx_print_scratch_ram(struct aic7xxx_host *p)
11121 {
11122   int i, k;
11123
11124   k = 0;
11125   printk("Scratch RAM:\n");
11126   for(i = SRAM_BASE; i < SEQCTL; i++)
11127   {
11128     printk("%02x:%02x ", i, aic_inb(p, i));
11129     if(++k == 13)
11130     {
11131       printk("\n");
11132       k=0;
11133     }
11134   }
11135   if (p->features & AHC_MORE_SRAM)
11136   {
11137     for(i = TARG_OFFSET; i < 0x80; i++)
11138     {
11139       printk("%02x:%02x ", i, aic_inb(p, i));
11140       if(++k == 13)
11141       {
11142         printk("\n");
11143         k=0;
11144       }
11145     }
11146   }
11147   printk("\n");
11148 }
11149
11150
11151 #include "aic7xxx_old/aic7xxx_proc.c"
11152
11153 MODULE_LICENSE("Dual BSD/GPL");
11154 MODULE_VERSION(AIC7XXX_H_VERSION);
11155
11156
11157 static struct scsi_host_template driver_template = {
11158         .proc_info              = aic7xxx_proc_info,
11159         .detect                 = aic7xxx_detect,
11160         .release                = aic7xxx_release,
11161         .info                   = aic7xxx_info, 
11162         .queuecommand           = aic7xxx_queue,
11163         .slave_alloc            = aic7xxx_slave_alloc,
11164         .slave_configure        = aic7xxx_slave_configure,
11165         .slave_destroy          = aic7xxx_slave_destroy,
11166         .bios_param             = aic7xxx_biosparam,
11167         .eh_abort_handler       = aic7xxx_abort,
11168         .eh_device_reset_handler        = aic7xxx_bus_device_reset,
11169         .eh_host_reset_handler  = aic7xxx_reset,
11170         .can_queue              = 255,
11171         .this_id                = -1,
11172         .max_sectors            = 2048,
11173         .cmd_per_lun            = 3,
11174         .use_clustering         = ENABLE_CLUSTERING,
11175 };
11176
11177 #include "scsi_module.c"
11178
11179 /*
11180  * Overrides for Emacs so that we almost follow Linus's tabbing style.
11181  * Emacs will notice this stuff at the end of the file and automatically
11182  * adjust the settings for this buffer only.  This must remain at the end
11183  * of the file.
11184  * ---------------------------------------------------------------------------
11185  * Local variables:
11186  * c-indent-level: 2
11187  * c-brace-imaginary-offset: 0
11188  * c-brace-offset: -2
11189  * c-argdecl-indent: 2
11190  * c-label-offset: -2
11191  * c-continued-statement-offset: 2
11192  * c-continued-brace-offset: 0
11193  * indent-tabs-mode: nil
11194  * tab-width: 8
11195  * End:
11196  */