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