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