Linux kernel & device driver programming

Cross-Referenced Linux and Device Driver Code

[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ]
Version: [ 2.6.11.8 ] [ 2.6.25 ] [ 2.6.25.8 ] [ 2.6.31.13 ] Architecture: [ i386 ]
  1 /*+M*************************************************************************
  2  * Adaptec AIC7xxx device driver for Linux.
  3  *
  4  * Copyright (c) 1994 John Aycock
  5  *   The University of Calgary Department of Computer Science.
  6  *
  7  * This program is free software; you can redistribute it and/or modify
  8  * it under the terms of the GNU General Public License as published by
  9  * the Free Software Foundation; either version 2, or (at your option)
 10  * any later version.
 11  *
 12  * This program is distributed in the hope that it will be useful,
 13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
 14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 15  * GNU General Public License for more details.
 16  *
 17  * You should have received a copy of the GNU General Public License
 18  * along with this program; see the file COPYING.  If not, write to
 19  * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
 20  *
 21  * Sources include the Adaptec 1740 driver (aha1740.c), the Ultrastor 24F
 22  * driver (ultrastor.c), various Linux kernel source, the Adaptec EISA
 23  * config file (!adp7771.cfg), the Adaptec AHA-2740A Series User's Guide,
 24  * the Linux Kernel Hacker's Guide, Writing a SCSI Device Driver for Linux,
 25  * the Adaptec 1542 driver (aha1542.c), the Adaptec EISA overlay file
 26  * (adp7770.ovl), the Adaptec AHA-2740 Series Technical Reference Manual,
 27  * the Adaptec AIC-7770 Data Book, the ANSI SCSI specification, the
 28  * ANSI SCSI-2 specification (draft 10c), ...
 29  *
 30  * --------------------------------------------------------------------------
 31  *
 32  *  Modifications by Daniel M. Eischen (deischen@iworks.InterWorks.org):
 33  *
 34  *  Substantially modified to include support for wide and twin bus
 35  *  adapters, DMAing of SCBs, tagged queueing, IRQ sharing, bug fixes,
 36  *  SCB paging, and other rework of the code.
 37  *
 38  *  Parts of this driver were also based on the FreeBSD driver by
 39  *  Justin T. Gibbs.  His copyright follows:
 40  *
 41  * --------------------------------------------------------------------------  
 42  * Copyright (c) 1994-1997 Justin Gibbs.
 43  * All rights reserved.
 44  *
 45  * Redistribution and use in source and binary forms, with or without
 46  * modification, are permitted provided that the following conditions
 47  * are met:
 48  * 1. Redistributions of source code must retain the above copyright
 49  *    notice, this list of conditions, and the following disclaimer,
 50  *    without modification, immediately at the beginning of the file.
 51  * 2. Redistributions in binary form must reproduce the above copyright
 52  *    notice, this list of conditions and the following disclaimer in the
 53  *    documentation and/or other materials provided with the distribution.
 54  * 3. The name of the author may not be used to endorse or promote products
 55  *    derived from this software without specific prior written permission.
 56  *
 57  * Where this Software is combined with software released under the terms of 
 58  * the GNU General Public License ("GPL") and the terms of the GPL would require the 
 59  * combined work to also be released under the terms of the GPL, the terms
 60  * and conditions of this License will apply in addition to those of the
 61  * GPL with the exception of any terms or conditions of this License that
 62  * conflict with, or are expressly prohibited by, the GPL.
 63  *
 64  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 65  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 66  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 67  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
 68  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 69  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 70  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 71  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 72  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 73  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 74  * SUCH DAMAGE.
 75  *
 76  *      $Id: aic7xxx.c,v 1.119 1997/06/27 19:39:18 gibbs Exp $
 77  *---------------------------------------------------------------------------
 78  *
 79  *  Thanks also go to (in alphabetical order) the following:
 80  *
 81  *    Rory Bolt     - Sequencer bug fixes
 82  *    Jay Estabrook - Initial DEC Alpha support
 83  *    Doug Ledford  - Much needed abort/reset bug fixes
 84  *    Kai Makisara  - DMAing of SCBs
 85  *
 86  *  A Boot time option was also added for not resetting the scsi bus.
 87  *
 88  *    Form:  aic7xxx=extended
 89  *           aic7xxx=no_reset
 90  *           aic7xxx=ultra
 91  *           aic7xxx=irq_trigger:[0,1]  # 0 edge, 1 level
 92  *           aic7xxx=verbose
 93  *
 94  *  Daniel M. Eischen, deischen@iworks.InterWorks.org, 1/23/97
 95  *
 96  *  $Id: aic7xxx.c,v 4.1 1997/06/12 08:23:42 deang Exp $
 97  *-M*************************************************************************/
 98 
 99 /*+M**************************************************************************
100  *
101  * Further driver modifications made by Doug Ledford <dledford@redhat.com>
102  *
103  * Copyright (c) 1997-1999 Doug Ledford
104  *
105  * These changes are released under the same licensing terms as the FreeBSD
106  * driver written by Justin Gibbs.  Please see his Copyright notice above
107  * for the exact terms and conditions covering my changes as well as the
108  * warranty statement.
109  *
110  * Modifications made to the aic7xxx.c,v 4.1 driver from Dan Eischen include
111  * but are not limited to:
112  *
113  *  1: Import of the latest FreeBSD sequencer code for this driver
114  *  2: Modification of kernel code to accommodate different sequencer semantics
115  *  3: Extensive changes throughout kernel portion of driver to improve
116  *     abort/reset processing and error hanndling
117  *  4: Other work contributed by various people on the Internet
118  *  5: Changes to printk information and verbosity selection code
119  *  6: General reliability related changes, especially in IRQ management
120  *  7: Modifications to the default probe/attach order for supported cards
121  *  8: SMP friendliness has been improved
122  *
123  * Overall, this driver represents a significant departure from the official
124  * aic7xxx driver released by Dan Eischen in two ways.  First, in the code
125  * itself.  A diff between the two version of the driver is now a several
126  * thousand line diff.  Second, in approach to solving the same problem.  The
127  * problem is importing the FreeBSD aic7xxx driver code to linux can be a
128  * difficult and time consuming process, that also can be error prone.  Dan
129  * Eischen's official driver uses the approach that the linux and FreeBSD
130  * drivers should be as identical as possible.  To that end, his next version
131  * of this driver will be using a mid-layer code library that he is developing
132  * to moderate communications between the linux mid-level SCSI code and the
133  * low level FreeBSD driver.  He intends to be able to essentially drop the
134  * FreeBSD driver into the linux kernel with only a few minor tweaks to some
135  * include files and the like and get things working, making for fast easy
136  * imports of the FreeBSD code into linux.
137  *
138  * I disagree with Dan's approach.  Not that I don't think his way of doing
139  * things would be nice, easy to maintain, and create a more uniform driver
140  * between FreeBSD and Linux.  I have no objection to those issues.  My
141  * disagreement is on the needed functionality.  There simply are certain
142  * things that are done differently in FreeBSD than linux that will cause
143  * problems for this driver regardless of any middle ware Dan implements.
144  * The biggest example of this at the moment is interrupt semantics.  Linux
145  * doesn't provide the same protection techniques as FreeBSD does, nor can
146  * they be easily implemented in any middle ware code since they would truly
147  * belong in the kernel proper and would effect all drivers.  For the time
148  * being, I see issues such as these as major stumbling blocks to the 
149  * reliability of code based upon such middle ware.  Therefore, I choose to
150  * use a different approach to importing the FreeBSD code that doesn't
151  * involve any middle ware type code.  My approach is to import the sequencer
152  * code from FreeBSD wholesale.  Then, to only make changes in the kernel
153  * portion of the driver as they are needed for the new sequencer semantics.
154  * In this way, the portion of the driver that speaks to the rest of the
155  * linux kernel is fairly static and can be changed/modified to solve
156  * any problems one might encounter without concern for the FreeBSD driver.
157  *
158  * Note: If time and experience should prove me wrong that the middle ware
159  * code Dan writes is reliable in its operation, then I'll retract my above
160  * statements.  But, for those that don't know, I'm from Missouri (in the US)
161  * and our state motto is "The Show-Me State".  Well, before I will put
162  * faith into it, you'll have to show me that it works :)
163  *
164  *_M*************************************************************************/
165 
166 /*
167  * The next three defines are user configurable.  These should be the only
168  * defines a user might need to get in here and change.  There are other
169  * defines buried deeper in the code, but those really shouldn't need touched
170  * under normal conditions.
171  */
172 
173 /*
174  * AIC7XXX_STRICT_PCI_SETUP
175  *   Should we assume the PCI config options on our controllers are set with
176  *   sane and proper values, or should we be anal about our PCI config
177  *   registers and force them to what we want?  The main advantage to
178  *   defining this option is on non-Intel hardware where the BIOS may not
179  *   have been run to set things up, or if you have one of the BIOSless
180  *   Adaptec controllers, such as a 2910, that don't get set up by the
181  *   BIOS.  However, keep in mind that we really do set the most important
182  *   items in the driver regardless of this setting, this only controls some
183  *   of the more esoteric PCI options on these cards.  In that sense, I
184  *   would default to leaving this off.  However, if people wish to try
185  *   things both ways, that would also help me to know if there are some
186  *   machines where it works one way but not another.
187  *
188  *   -- July 7, 17:09
189  *     OK...I need this on my machine for testing, so the default is to
190  *     leave it defined.
191  *
192  *   -- July 7, 18:49
193  *     I needed it for testing, but it didn't make any difference, so back
194  *     off she goes.
195  *
196  *   -- July 16, 23:04
197  *     I turned it back on to try and compensate for the 2.1.x PCI code
198  *     which no longer relies solely on the BIOS and now tries to set
199  *     things itself.
200  */
201 
202 #define AIC7XXX_STRICT_PCI_SETUP
203 
204 /*
205  * AIC7XXX_VERBOSE_DEBUGGING
206  *   This option enables a lot of extra printk();s in the code, surrounded
207  *   by if (aic7xxx_verbose ...) statements.  Executing all of those if
208  *   statements and the extra checks can get to where it actually does have
209  *   an impact on CPU usage and such, as well as code size.  Disabling this
210  *   define will keep some of those from becoming part of the code.
211  *
212  *   NOTE:  Currently, this option has no real effect, I will be adding the
213  *   various #ifdef's in the code later when I've decided a section is
214  *   complete and no longer needs debugging.  OK...a lot of things are now
215  *   surrounded by this define, so turning this off does have an impact.
216  */
217  
218 /*
219  * #define AIC7XXX_VERBOSE_DEBUGGING
220  */
221  
222 #include <linux/module.h>
223 #include <stdarg.h>
224 #include <asm/io.h>
225 #include <asm/irq.h>
226 #include <asm/byteorder.h>
227 #include <linux/string.h>
228 #include <linux/errno.h>
229 #include <linux/kernel.h>
230 #include <linux/ioport.h>
231 #include <linux/delay.h>
232 #include <linux/pci.h>
233 #include <linux/proc_fs.h>
234 #include <linux/blkdev.h>
235 #include <linux/init.h>
236 #include <linux/spinlock.h>
237 #include <linux/smp.h>
238 #include <linux/interrupt.h>
239 #include "scsi.h"
240 #include <scsi/scsi_host.h>
241 #include "aic7xxx_old/aic7xxx.h"
242 
243 #include "aic7xxx_old/sequencer.h"
244 #include "aic7xxx_old/scsi_message.h"
245 #include "aic7xxx_old/aic7xxx_reg.h"
246 #include <scsi/scsicam.h>
247 
248 #include <linux/stat.h>
249 #include <linux/slab.h>        /* for kmalloc() */
250 
251 #define AIC7XXX_C_VERSION  "5.2.6"
252 
253 #define ALL_TARGETS -1
254 #define ALL_CHANNELS -1
255 #define ALL_LUNS -1
256 #define MAX_TARGETS  16
257 #define MAX_LUNS     8
258 #ifndef TRUE
259 #  define TRUE 1
260 #endif
261 #ifndef FALSE
262 #  define FALSE 0
263 #endif
264 
265 #if defined(__powerpc__) || defined(__i386__) || defined(__x86_64__)
266 #  define MMAPIO
267 #endif
268 
269 /*
270  * You can try raising me for better performance or lowering me if you have
271  * flaky devices that go off the scsi bus when hit with too many tagged
272  * commands (like some IBM SCSI-3 LVD drives).
273  */
274 #define AIC7XXX_CMDS_PER_DEVICE 32
275 
276 typedef struct
277 {
278   unsigned char tag_commands[16];   /* Allow for wide/twin adapters. */
279 } adapter_tag_info_t;
280 
281 /*
282  * Make a define that will tell the driver not to the default tag depth
283  * everywhere.
284  */
285 #define DEFAULT_TAG_COMMANDS {0, 0, 0, 0, 0, 0, 0, 0,\
286                               0, 0, 0, 0, 0, 0, 0, 0}
287 
288 /*
289  * Modify this as you see fit for your system.  By setting tag_commands
290  * to 0, the driver will use it's own algorithm for determining the
291  * number of commands to use (see above).  When 255, the driver will
292  * not enable tagged queueing for that particular device.  When positive
293  * (> 0) and (< 255) the values in the array are used for the queue_depth.
294  * Note that the maximum value for an entry is 254, but you're insane if
295  * you try to use that many commands on one device.
296  *
297  * In this example, the first line will disable tagged queueing for all
298  * the devices on the first probed aic7xxx adapter.
299  *
300  * The second line enables tagged queueing with 4 commands/LUN for IDs
301  * (1, 2-11, 13-15), disables tagged queueing for ID 12, and tells the
302  * driver to use its own algorithm for ID 1.
303  *
304  * The third line is the same as the first line.
305  *
306  * The fourth line disables tagged queueing for devices 0 and 3.  It
307  * enables tagged queueing for the other IDs, with 16 commands/LUN
308  * for IDs 1 and 4, 127 commands/LUN for ID 8, and 4 commands/LUN for
309  * IDs 2, 5-7, and 9-15.
310  */
311 
312 /*
313  * NOTE: The below structure is for reference only, the actual structure
314  *       to modify in order to change things is found after this fake one.
315  *
316 adapter_tag_info_t aic7xxx_tag_info[] =
317 {
318   {DEFAULT_TAG_COMMANDS},
319   {{4, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 255, 4, 4, 4}},
320   {DEFAULT_TAG_COMMANDS},
321   {{255, 16, 4, 255, 16, 4, 4, 4, 127, 4, 4, 4, 4, 4, 4, 4}}
322 };
323 */
324 
325 static adapter_tag_info_t aic7xxx_tag_info[] =
326 {
327   {DEFAULT_TAG_COMMANDS},
328   {DEFAULT_TAG_COMMANDS},
329   {DEFAULT_TAG_COMMANDS},
330   {DEFAULT_TAG_COMMANDS},
331   {DEFAULT_TAG_COMMANDS},
332   {DEFAULT_TAG_COMMANDS},
333   {DEFAULT_TAG_COMMANDS},
334   {DEFAULT_TAG_COMMANDS},
335   {DEFAULT_TAG_COMMANDS},
336   {DEFAULT_TAG_COMMANDS},
337   {DEFAULT_TAG_COMMANDS},
338   {DEFAULT_TAG_COMMANDS},
339   {DEFAULT_TAG_COMMANDS},
340   {DEFAULT_TAG_COMMANDS},
341   {DEFAULT_TAG_COMMANDS},
342   {DEFAULT_TAG_COMMANDS}
343 };
344 
345 
346 /*
347  * Define an array of board names that can be indexed by aha_type.
348  * Don't forget to change this when changing the types!
349  */
350 static const char *board_names[] = {
351   "AIC-7xxx Unknown",                                   /* AIC_NONE */
352   "Adaptec AIC-7810 Hardware RAID Controller",          /* AIC_7810 */
353   "Adaptec AIC-7770 SCSI host adapter",                 /* AIC_7770 */
354   "Adaptec AHA-274X SCSI host adapter",                 /* AIC_7771 */
355   "Adaptec AHA-284X SCSI host adapter",                 /* AIC_284x */
356   "Adaptec AIC-7850 SCSI host adapter",                 /* AIC_7850 */
357   "Adaptec AIC-7855 SCSI host adapter",                 /* AIC_7855 */
358   "Adaptec AIC-7860 Ultra SCSI host adapter",           /* AIC_7860 */
359   "Adaptec AHA-2940A Ultra SCSI host adapter",          /* AIC_7861 */
360   "Adaptec AIC-7870 SCSI host adapter",                 /* AIC_7870 */
361   "Adaptec AHA-294X SCSI host adapter",                 /* AIC_7871 */
362   "Adaptec AHA-394X SCSI host adapter",                 /* AIC_7872 */
363   "Adaptec AHA-398X SCSI host adapter",                 /* AIC_7873 */
364   "Adaptec AHA-2944 SCSI host adapter",                 /* AIC_7874 */
365   "Adaptec AIC-7880 Ultra SCSI host adapter",           /* AIC_7880 */
366   "Adaptec AHA-294X Ultra SCSI host adapter",           /* AIC_7881 */
367   "Adaptec AHA-394X Ultra SCSI host adapter",           /* AIC_7882 */
368   "Adaptec AHA-398X Ultra SCSI host adapter",           /* AIC_7883 */
369   "Adaptec AHA-2944 Ultra SCSI host adapter",           /* AIC_7884 */
370   "Adaptec AHA-2940UW Pro Ultra SCSI host adapter",     /* AIC_7887 */
371   "Adaptec AIC-7895 Ultra SCSI host adapter",           /* AIC_7895 */
372   "Adaptec AIC-7890/1 Ultra2 SCSI host adapter",        /* AIC_7890 */
373   "Adaptec AHA-293X Ultra2 SCSI host adapter",          /* AIC_7890 */
374   "Adaptec AHA-294X Ultra2 SCSI host adapter",          /* AIC_7890 */
375   "Adaptec AIC-7896/7 Ultra2 SCSI host adapter",        /* AIC_7896 */
376   "Adaptec AHA-394X Ultra2 SCSI host adapter",          /* AIC_7897 */
377   "Adaptec AHA-395X Ultra2 SCSI host adapter",          /* AIC_7897 */
378   "Adaptec PCMCIA SCSI controller",                     /* card bus stuff */
379   "Adaptec AIC-7892 Ultra 160/m SCSI host adapter",     /* AIC_7892 */
380   "Adaptec AIC-7899 Ultra 160/m SCSI host adapter",     /* AIC_7899 */
381 };
382 
383 /*
384  * There should be a specific return value for this in scsi.h, but
385  * it seems that most drivers ignore it.
386  */
387 #define DID_UNDERFLOW   DID_ERROR
388 
389 /*
390  *  What we want to do is have the higher level scsi driver requeue
391  *  the command to us. There is no specific driver status for this
392  *  condition, but the higher level scsi driver will requeue the
393  *  command on a DID_BUS_BUSY error.
394  *
395  *  Upon further inspection and testing, it seems that DID_BUS_BUSY
396  *  will *always* retry the command.  We can get into an infinite loop
397  *  if this happens when we really want some sort of counter that
398  *  will automatically abort/reset the command after so many retries.
399  *  Using DID_ERROR will do just that.  (Made by a suggestion by
400  *  Doug Ledford 8/1/96)
401  */
402 #define DID_RETRY_COMMAND DID_ERROR
403 
404 #define HSCSIID        0x07
405 #define SCSI_RESET     0x040
406 
407 /*
408  * EISA/VL-bus stuff
409  */
410 #define MINSLOT                1
411 #define MAXSLOT                15
412 #define SLOTBASE(x)        ((x) << 12)
413 #define BASE_TO_SLOT(x) ((x) >> 12)
414 
415 /*
416  * Standard EISA Host ID regs  (Offset from slot base)
417  */
418 #define AHC_HID0              0x80   /* 0,1: msb of ID2, 2-7: ID1      */
419 #define AHC_HID1              0x81   /* 0-4: ID3, 5-7: LSB ID2         */
420 #define AHC_HID2              0x82   /* product                        */
421 #define AHC_HID3              0x83   /* firmware revision              */
422 
423 /*
424  * AIC-7770 I/O range to reserve for a card
425  */
426 #define MINREG                0xC00
427 #define MAXREG                0xCFF
428 
429 #define INTDEF                0x5C      /* Interrupt Definition Register */
430 
431 /*
432  * AIC-78X0 PCI registers
433  */
434 #define        CLASS_PROGIF_REVID        0x08
435 #define                DEVREVID        0x000000FFul
436 #define                PROGINFC        0x0000FF00ul
437 #define                SUBCLASS        0x00FF0000ul
438 #define                BASECLASS        0xFF000000ul
439 
440 #define        CSIZE_LATTIME                0x0C
441 #define                CACHESIZE        0x0000003Ful        /* only 5 bits */
442 #define                LATTIME                0x0000FF00ul
443 
444 #define        DEVCONFIG                0x40
445 #define                SCBSIZE32        0x00010000ul        /* aic789X only */
446 #define                MPORTMODE        0x00000400ul        /* aic7870 only */
447 #define                RAMPSM           0x00000200ul        /* aic7870 only */
448 #define                RAMPSM_ULTRA2    0x00000004
449 #define                VOLSENSE         0x00000100ul
450 #define                SCBRAMSEL        0x00000080ul
451 #define                SCBRAMSEL_ULTRA2 0x00000008
452 #define                MRDCEN           0x00000040ul
453 #define                EXTSCBTIME       0x00000020ul        /* aic7870 only */
454 #define                EXTSCBPEN        0x00000010ul        /* aic7870 only */
455 #define                BERREN           0x00000008ul
456 #define                DACEN            0x00000004ul
457 #define                STPWLEVEL        0x00000002ul
458 #define                DIFACTNEGEN      0x00000001ul        /* aic7870 only */
459 
460 #define        SCAMCTL                  0x1a                /* Ultra2 only  */
461 #define        CCSCBBADDR               0xf0                /* aic7895/6/7  */
462 
463 /*
464  * Define the different types of SEEPROMs on aic7xxx adapters
465  * and make it also represent the address size used in accessing
466  * its registers.  The 93C46 chips have 1024 bits organized into
467  * 64 16-bit words, while the 93C56 chips have 2048 bits organized
468  * into 128 16-bit words.  The C46 chips use 6 bits to address
469  * each word, while the C56 and C66 (4096 bits) use 8 bits to
470  * address each word.
471  */
472 typedef enum {C46 = 6, C56_66 = 8} seeprom_chip_type;
473 
474 /*
475  *
476  * Define the format of the SEEPROM registers (16 bits).
477  *
478  */
479 struct seeprom_config {
480 
481 /*
482  * SCSI ID Configuration Flags
483  */
484 #define CFXFER                0x0007      /* synchronous transfer rate */
485 #define CFSYNCH               0x0008      /* enable synchronous transfer */
486 #define CFDISC                0x0010      /* enable disconnection */
487 #define CFWIDEB               0x0020      /* wide bus device (wide card) */
488 #define CFSYNCHISULTRA        0x0040      /* CFSYNC is an ultra offset */
489 #define CFNEWULTRAFORMAT      0x0080      /* Use the Ultra2 SEEPROM format */
490 #define CFSTART               0x0100      /* send start unit SCSI command */
491 #define CFINCBIOS             0x0200      /* include in BIOS scan */
492 #define CFRNFOUND             0x0400      /* report even if not found */
493 #define CFMULTILUN            0x0800      /* probe mult luns in BIOS scan */
494 #define CFWBCACHEYES          0x4000      /* Enable W-Behind Cache on drive */
495 #define CFWBCACHENC           0xc000      /* Don't change W-Behind Cache */
496 /* UNUSED                0x3000 */
497   unsigned short device_flags[16];        /* words 0-15 */
498 
499 /*
500  * BIOS Control Bits
501  */
502 #define CFSUPREM        0x0001  /* support all removable drives */
503 #define CFSUPREMB       0x0002  /* support removable drives for boot only */
504 #define CFBIOSEN        0x0004  /* BIOS enabled */
505 /* UNUSED                0x0008 */
506 #define CFSM2DRV        0x0010  /* support more than two drives */
507 #define CF284XEXTEND    0x0020  /* extended translation (284x cards) */
508 /* UNUSED                0x0040 */
509 #define CFEXTEND        0x0080  /* extended translation enabled */
510 /* UNUSED                0xFF00 */
511   unsigned short bios_control;  /* word 16 */
512 
513 /*
514  * Host Adapter Control Bits
515  */
516 #define CFAUTOTERM      0x0001  /* Perform Auto termination */
517 #define CFULTRAEN       0x0002  /* Ultra SCSI speed enable (Ultra cards) */
518 #define CF284XSELTO     0x0003  /* Selection timeout (284x cards) */
519 #define CF284XFIFO      0x000C  /* FIFO Threshold (284x cards) */
520 #define CFSTERM         0x0004  /* SCSI low byte termination */
521 #define CFWSTERM        0x0008  /* SCSI high byte termination (wide card) */
522 #define CFSPARITY       0x0010  /* SCSI parity */
523 #define CF284XSTERM     0x0020  /* SCSI low byte termination (284x cards) */
524 #define CFRESETB        0x0040  /* reset SCSI bus at boot */
525 #define CFBPRIMARY      0x0100  /* Channel B primary on 7895 chipsets */
526 #define CFSEAUTOTERM    0x0400  /* aic7890 Perform SE Auto Term */
527 #define CFLVDSTERM      0x0800  /* aic7890 LVD Termination */
528 /* UNUSED                0xF280 */
529   unsigned short adapter_control;        /* word 17 */
530 
531 /*
532  * Bus Release, Host Adapter ID
533  */
534 #define CFSCSIID        0x000F                /* host adapter SCSI ID */
535 /* UNUSED                0x00F0 */
536 #define CFBRTIME        0xFF00                /* bus release time */
537   unsigned short brtime_id;                /* word 18 */
538 
539 /*
540  * Maximum targets
541  */
542 #define CFMAXTARG        0x00FF        /* maximum targets */
543 /* UNUSED                0xFF00 */
544   unsigned short max_targets;                /* word 19 */
545 
546   unsigned short res_1[11];                /* words 20-30 */
547   unsigned short checksum;                /* word 31 */
548 };
549 
550 #define SELBUS_MASK                0x0a
551 #define         SELNARROW        0x00
552 #define         SELBUSB                0x08
553 #define SINGLE_BUS                0x00
554 
555 #define SCB_TARGET(scb)         \
556        (((scb)->hscb->target_channel_lun & TID) >> 4)
557 #define SCB_LUN(scb)            \
558        ((scb)->hscb->target_channel_lun & LID)
559 #define SCB_IS_SCSIBUS_B(scb)   \
560        (((scb)->hscb->target_channel_lun & SELBUSB) != 0)
561 
562 /*
563  * If an error occurs during a data transfer phase, run the command
564  * to completion - it's easier that way - making a note of the error
565  * condition in this location. This then will modify a DID_OK status
566  * into an appropriate error for the higher-level SCSI code.
567  */
568 #define aic7xxx_error(cmd)        ((cmd)->SCp.Status)
569 
570 /*
571  * Keep track of the targets returned status.
572  */
573 #define aic7xxx_status(cmd)        ((cmd)->SCp.sent_command)
574 
575 /*
576  * The position of the SCSI commands scb within the scb array.
577  */
578 #define aic7xxx_position(cmd)        ((cmd)->SCp.have_data_in)
579 
580 /*
581  * The stored DMA mapping for single-buffer data transfers.
582  */
583 #define aic7xxx_mapping(cmd)         ((cmd)->SCp.phase)
584 
585 /*
586  * Get out private data area from a scsi cmd pointer
587  */
588 #define AIC_DEV(cmd)    ((struct aic_dev_data *)(cmd)->device->hostdata)
589 
590 /*
591  * So we can keep track of our host structs
592  */
593 static struct aic7xxx_host *first_aic7xxx = NULL;
594 
595 /*
596  * As of Linux 2.1, the mid-level SCSI code uses virtual addresses
597  * in the scatter-gather lists.  We need to convert the virtual
598  * addresses to physical addresses.
599  */
600 struct hw_scatterlist {
601   unsigned int address;
602   unsigned int length;
603 };
604 
605 /*
606  * Maximum number of SG segments these cards can support.
607  */
608 #define        AIC7XXX_MAX_SG 128
609 
610 /*
611  * The maximum number of SCBs we could have for ANY type
612  * of card. DON'T FORGET TO CHANGE THE SCB MASK IN THE
613  * SEQUENCER CODE IF THIS IS MODIFIED!
614  */
615 #define AIC7XXX_MAXSCB        255
616 
617 
618 struct aic7xxx_hwscb {
619 /* ------------    Begin hardware supported fields    ---------------- */
620 /* 0*/  unsigned char control;
621 /* 1*/  unsigned char target_channel_lun;       /* 4/1/3 bits */
622 /* 2*/  unsigned char target_status;
623 /* 3*/  unsigned char SG_segment_count;
624 /* 4*/  unsigned int  SG_list_pointer;
625 /* 8*/  unsigned char residual_SG_segment_count;
626 /* 9*/  unsigned char residual_data_count[3];
627 /*12*/  unsigned int  data_pointer;
628 /*16*/  unsigned int  data_count;
629 /*20*/  unsigned int  SCSI_cmd_pointer;
630 /*24*/  unsigned char SCSI_cmd_length;
631 /*25*/  unsigned char tag;          /* Index into our kernel SCB array.
632                                      * Also used as the tag for tagged I/O
633                                      */
634 #define SCB_PIO_TRANSFER_SIZE  26   /* amount we need to upload/download
635                                      * via PIO to initialize a transaction.
636                                      */
637 /*26*/  unsigned char next;         /* Used to thread SCBs awaiting selection
638                                      * or disconnected down in the sequencer.
639                                      */
640 /*27*/  unsigned char prev;
641 /*28*/  unsigned int pad;           /*
642                                      * Unused by the kernel, but we require
643                                      * the padding so that the array of
644                                      * hardware SCBs is aligned on 32 byte
645                                      * boundaries so the sequencer can index
646                                      */
647 };
648 
649 typedef enum {
650         SCB_FREE                = 0x0000,
651         SCB_DTR_SCB             = 0x0001,
652         SCB_WAITINGQ            = 0x0002,
653         SCB_ACTIVE              = 0x0004,
654         SCB_SENSE               = 0x0008,
655         SCB_ABORT               = 0x0010,
656         SCB_DEVICE_RESET        = 0x0020,
657         SCB_RESET               = 0x0040,
658         SCB_RECOVERY_SCB        = 0x0080,
659         SCB_MSGOUT_PPR          = 0x0100,
660         SCB_MSGOUT_SENT         = 0x0200,
661         SCB_MSGOUT_SDTR         = 0x0400,
662         SCB_MSGOUT_WDTR         = 0x0800,
663         SCB_MSGOUT_BITS         = SCB_MSGOUT_PPR |
664                                   SCB_MSGOUT_SENT | 
665                                   SCB_MSGOUT_SDTR |
666                                   SCB_MSGOUT_WDTR,
667         SCB_QUEUED_ABORT        = 0x1000,
668         SCB_QUEUED_FOR_DONE     = 0x2000,
669         SCB_WAS_BUSY            = 0x4000,
670         SCB_QUEUE_FULL          = 0x8000
671 } scb_flag_type;
672 
673 typedef enum {
674         AHC_FNONE                 = 0x00000000,
675         AHC_PAGESCBS              = 0x00000001,
676         AHC_CHANNEL_B_PRIMARY     = 0x00000002,
677         AHC_USEDEFAULTS           = 0x00000004,
678         AHC_INDIRECT_PAGING       = 0x00000008,
679         AHC_CHNLB                 = 0x00000020,
680         AHC_CHNLC                 = 0x00000040,
681         AHC_EXTEND_TRANS_A        = 0x00000100,
682         AHC_EXTEND_TRANS_B        = 0x00000200,
683         AHC_TERM_ENB_A            = 0x00000400,
684         AHC_TERM_ENB_SE_LOW       = 0x00000400,
685         AHC_TERM_ENB_B            = 0x00000800,
686         AHC_TERM_ENB_SE_HIGH      = 0x00000800,
687         AHC_HANDLING_REQINITS     = 0x00001000,
688         AHC_TARGETMODE            = 0x00002000,
689         AHC_NEWEEPROM_FMT         = 0x00004000,
690  /*
691   *  Here ends the FreeBSD defined flags and here begins the linux defined
692   *  flags.  NOTE: I did not preserve the old flag name during this change
693   *  specifically to force me to evaluate what flags were being used properly
694   *  and what flags weren't.  This way, I could clean up the flag usage on
695   *  a use by use basis.  Doug Ledford
696   */
697         AHC_MOTHERBOARD           = 0x00020000,
698         AHC_NO_STPWEN             = 0x00040000,
699         AHC_RESET_DELAY           = 0x00080000,
700         AHC_A_SCANNED             = 0x00100000,
701         AHC_B_SCANNED             = 0x00200000,
702         AHC_MULTI_CHANNEL         = 0x00400000,
703         AHC_BIOS_ENABLED          = 0x00800000,
704         AHC_SEEPROM_FOUND         = 0x01000000,
705         AHC_TERM_ENB_LVD          = 0x02000000,
706         AHC_ABORT_PENDING         = 0x04000000,
707         AHC_RESET_PENDING         = 0x08000000,
708 #define AHC_IN_ISR_BIT              28
709         AHC_IN_ISR                = 0x10000000,
710         AHC_IN_ABORT              = 0x20000000,
711         AHC_IN_RESET              = 0x40000000,
712         AHC_EXTERNAL_SRAM         = 0x80000000
713 } ahc_flag_type;
714 
715 typedef enum {
716   AHC_NONE             = 0x0000,
717   AHC_CHIPID_MASK      = 0x00ff,
718   AHC_AIC7770          = 0x0001,
719   AHC_AIC7850          = 0x0002,
720   AHC_AIC7860          = 0x0003,
721   AHC_AIC7870          = 0x0004,
722   AHC_AIC7880          = 0x0005,
723   AHC_AIC7890          = 0x0006,
724   AHC_AIC7895          = 0x0007,
725   AHC_AIC7896          = 0x0008,
726   AHC_AIC7892          = 0x0009,
727   AHC_AIC7899          = 0x000a,
728   AHC_VL               = 0x0100,
729   AHC_EISA             = 0x0200,
730   AHC_PCI              = 0x0400,
731 } ahc_chip;
732 
733 typedef enum {
734   AHC_FENONE           = 0x0000,
735   AHC_ULTRA            = 0x0001,
736   AHC_ULTRA2           = 0x0002,
737   AHC_WIDE             = 0x0004,
738   AHC_TWIN             = 0x0008,
739   AHC_MORE_SRAM        = 0x0010,
740   AHC_CMD_CHAN         = 0x0020,
741   AHC_QUEUE_REGS       = 0x0040,
742   AHC_SG_PRELOAD       = 0x0080,
743   AHC_SPIOCAP          = 0x0100,
744   AHC_ULTRA3           = 0x0200,
745   AHC_NEW_AUTOTERM     = 0x0400,
746   AHC_AIC7770_FE       = AHC_FENONE,
747   AHC_AIC7850_FE       = AHC_SPIOCAP,
748   AHC_AIC7860_FE       = AHC_ULTRA|AHC_SPIOCAP,
749   AHC_AIC7870_FE       = AHC_FENONE,
750   AHC_AIC7880_FE       = AHC_ULTRA,
751   AHC_AIC7890_FE       = AHC_MORE_SRAM|AHC_CMD_CHAN|AHC_ULTRA2|
752                          AHC_QUEUE_REGS|AHC_SG_PRELOAD|AHC_NEW_AUTOTERM,
753   AHC_AIC7895_FE       = AHC_MORE_SRAM|AHC_CMD_CHAN|AHC_ULTRA,
754   AHC_AIC7896_FE       = AHC_AIC7890_FE,
755   AHC_AIC7892_FE       = AHC_AIC7890_FE|AHC_ULTRA3,
756   AHC_AIC7899_FE       = AHC_AIC7890_FE|AHC_ULTRA3,
757 } ahc_feature;
758 
759 #define SCB_DMA_ADDR(scb, addr) ((unsigned long)(addr) + (scb)->scb_dma->dma_offset)
760 
761 struct aic7xxx_scb_dma {
762         unsigned long          dma_offset;    /* Correction you have to add
763                                                * to virtual address to get
764                                                * dma handle in this region */
765         dma_addr_t             dma_address;   /* DMA handle of the start,
766                                                * for unmap */
767         unsigned int           dma_len;       /* DMA length */
768 };
769 
770 typedef enum {
771   AHC_BUG_NONE            = 0x0000,
772   AHC_BUG_TMODE_WIDEODD   = 0x0001,
773   AHC_BUG_AUTOFLUSH       = 0x0002,
774   AHC_BUG_CACHETHEN       = 0x0004,
775   AHC_BUG_CACHETHEN_DIS   = 0x0008,
776   AHC_BUG_PCI_2_1_RETRY   = 0x0010,
777   AHC_BUG_PCI_MWI         = 0x0020,
778   AHC_BUG_SCBCHAN_UPLOAD  = 0x0040,
779 } ahc_bugs;
780 
781 struct aic7xxx_scb {
782         struct aic7xxx_hwscb    *hscb;          /* corresponding hardware scb */
783         struct scsi_cmnd        *cmd;           /* scsi_cmnd for this scb */
784         struct aic7xxx_scb      *q_next;        /* next scb in queue */
785         volatile scb_flag_type  flags;          /* current state of scb */
786         struct hw_scatterlist   *sg_list;       /* SG list in adapter format */
787         unsigned char           tag_action;
788         unsigned char           sg_count;
789         unsigned char           *sense_cmd;     /*
790                                                  * Allocate 6 characters for
791                                                  * sense command.
792                                                  */
793         unsigned char           *cmnd;
794         unsigned int            sg_length;      /*
795                                                  * We init this during
796                                                  * buildscb so we don't have
797                                                  * to calculate anything during
798                                                  * underflow/overflow/stat code
799                                                  */
800         void                    *kmalloc_ptr;
801         struct aic7xxx_scb_dma  *scb_dma;
802 };
803 
804 /*
805  * Define a linked list of SCBs.
806  */
807 typedef struct {
808   struct aic7xxx_scb *head;
809   struct aic7xxx_scb *tail;
810 } scb_queue_type;
811 
812 static struct {
813   unsigned char errno;
814   const char *errmesg;
815 } hard_error[] = {
816   { ILLHADDR,  "Illegal Host Access" },
817   { ILLSADDR,  "Illegal Sequencer Address referenced" },
818   { ILLOPCODE, "Illegal Opcode in sequencer program" },
819   { SQPARERR,  "Sequencer Ram Parity Error" },
820   { DPARERR,   "Data-Path Ram Parity Error" },
821   { MPARERR,   "Scratch Ram/SCB Array Ram Parity Error" },
822   { PCIERRSTAT,"PCI Error detected" },
823   { CIOPARERR, "CIOBUS Parity Error" }
824 };
825 
826 static unsigned char
827 generic_sense[] = { REQUEST_SENSE, 0, 0, 0, 255, 0 };
828 
829 typedef struct {
830   scb_queue_type free_scbs;        /*
831                                     * SCBs assigned to free slot on
832                                     * card (no paging required)
833                                     */
834   struct aic7xxx_scb   *scb_array[AIC7XXX_MAXSCB];
835   struct aic7xxx_hwscb *hscbs;
836   unsigned char  numscbs;          /* current number of scbs */
837   unsigned char  maxhscbs;         /* hardware scbs */
838   unsigned char  maxscbs;          /* max scbs including pageable scbs */
839   dma_addr_t     hscbs_dma;        /* DMA handle to hscbs */
840   unsigned int   hscbs_dma_len;    /* length of the above DMA area */
841   void          *hscb_kmalloc_ptr;
842 } scb_data_type;
843 
844 struct target_cmd {
845   unsigned char mesg_bytes[4];
846   unsigned char command[28];
847 };
848 
849 #define AHC_TRANS_CUR    0x0001
850 #define AHC_TRANS_ACTIVE 0x0002
851 #define AHC_TRANS_GOAL   0x0004
852 #define AHC_TRANS_USER   0x0008
853 #define AHC_TRANS_QUITE  0x0010
854 typedef struct {
855   unsigned char width;
856   unsigned char period;
857   unsigned char offset;
858   unsigned char options;
859 } transinfo_type;
860 
861 struct aic_dev_data {
862   volatile scb_queue_type  delayed_scbs;
863   volatile unsigned short  temp_q_depth;
864   unsigned short           max_q_depth;
865   volatile unsigned char   active_cmds;
866   /*
867    * Statistics Kept:
868    *
869    * Total Xfers (count for each command that has a data xfer),
870    * broken down by reads && writes.
871    *
872    * Further sorted into a few bins for keeping tabs on how many commands
873    * we get of various sizes.
874    *
875    */
876   long w_total;                          /* total writes */
877   long r_total;                          /* total reads */
878   long barrier_total;                    /* total num of REQ_BARRIER commands */
879   long ordered_total;                    /* How many REQ_BARRIER commands we
880                                             used ordered tags to satisfy */
881   long w_bins[6];                       /* binned write */
882   long r_bins[6];                       /* binned reads */
883   transinfo_type        cur;
884   transinfo_type        goal;
885 #define  BUS_DEVICE_RESET_PENDING       0x01
886 #define  DEVICE_RESET_DELAY             0x02
887 #define  DEVICE_PRINT_DTR               0x04
888 #define  DEVICE_WAS_BUSY                0x08
889 #define  DEVICE_DTR_SCANNED             0x10
890 #define  DEVICE_SCSI_3                  0x20
891   volatile unsigned char   flags;
892   unsigned needppr:1;
893   unsigned needppr_copy:1;
894   unsigned needsdtr:1;
895   unsigned needsdtr_copy:1;
896   unsigned needwdtr:1;
897   unsigned needwdtr_copy:1;
898   unsigned dtr_pending:1;
899   struct scsi_device *SDptr;
900   struct list_head list;
901 };
902 
903 /*
904  * Define a structure used for each host adapter.  Note, in order to avoid
905  * problems with architectures I can't test on (because I don't have one,
906  * such as the Alpha based systems) which happen to give faults for
907  * non-aligned memory accesses, care was taken to align this structure
908  * in a way that gauranteed all accesses larger than 8 bits were aligned
909  * on the appropriate boundary.  It's also organized to try and be more
910  * cache line efficient.  Be careful when changing this lest you might hurt
911  * overall performance and bring down the wrath of the masses.
912  */
913 struct aic7xxx_host {
914   /*
915    *  This is the first 64 bytes in the host struct
916    */
917 
918   /*
919    * We are grouping things here....first, items that get either read or
920    * written with nearly every interrupt
921    */
922         volatile long   flags;
923         ahc_feature     features;       /* chip features */
924         unsigned long   base;           /* card base address */
925         volatile unsigned char  __iomem *maddr; /* memory mapped address */
926         unsigned long   isr_count;      /* Interrupt count */
927         unsigned long   spurious_int;
928         scb_data_type   *scb_data;
929         struct aic7xxx_cmd_queue {
930                 struct scsi_cmnd *head;
931                 struct scsi_cmnd *tail;
932         } completeq;
933 
934         /*
935         * Things read/written on nearly every entry into aic7xxx_queue()
936         */
937         volatile scb_queue_type waiting_scbs;
938         unsigned char   unpause;        /* unpause value for HCNTRL */
939         unsigned char   pause;          /* pause value for HCNTRL */
940         volatile unsigned char  qoutfifonext;
941         volatile unsigned char  activescbs;     /* active scbs */
942         volatile unsigned char  max_activescbs;
943         volatile unsigned char  qinfifonext;
944         volatile unsigned char  *untagged_scbs;
945         volatile unsigned char  *qoutfifo;
946         volatile unsigned char  *qinfifo;
947 
948         unsigned char   dev_last_queue_full[MAX_TARGETS];
949         unsigned char   dev_last_queue_full_count[MAX_TARGETS];
950         unsigned short  ultraenb; /* Gets downloaded to card as a bitmap */
951         unsigned short  discenable; /* Gets downloaded to card as a bitmap */
952         transinfo_type  user[MAX_TARGETS];
953 
954         unsigned char   msg_buf[13];    /* The message for the target */
955         unsigned char   msg_type;
956 #define MSG_TYPE_NONE              0x00
957 #define MSG_TYPE_INITIATOR_MSGOUT  0x01
958 #define MSG_TYPE_INITIATOR_MSGIN   0x02
959         unsigned char   msg_len;        /* Length of message */
960         unsigned char   msg_index;      /* Index into msg_buf array */
961 
962 
963         /*
964          * We put the less frequently used host structure items
965          * after the more frequently used items to try and ease
966          * the burden on the cache subsystem.
967          * These entries are not *commonly* accessed, whereas
968          * the preceding entries are accessed very often.
969          */
970 
971         unsigned int    irq;            /* IRQ for this adapter */
972         int             instance;       /* aic7xxx instance number */
973         int             scsi_id;        /* host adapter SCSI ID */
974         int             scsi_id_b;      /* channel B for twin adapters */
975         unsigned int    bios_address;
976         int             board_name_index;
977         unsigned short  bios_control;           /* bios control - SEEPROM */
978         unsigned short  adapter_control;        /* adapter control - SEEPROM */
979         struct pci_dev  *pdev;
980         unsigned char   pci_bus;
981         unsigned char   pci_device_fn;
982         struct seeprom_config   sc;
983         unsigned short  sc_type;
984         unsigned short  sc_size;
985         struct aic7xxx_host     *next;  /* allow for multiple IRQs */
986         struct Scsi_Host        *host;  /* pointer to scsi host */
987         struct list_head         aic_devs; /* all aic_dev structs on host */
988         int             host_no;        /* SCSI host number */
989         unsigned long   mbase;          /* I/O memory address */
990         ahc_chip        chip;           /* chip type */
991         ahc_bugs        bugs;
992         dma_addr_t      fifo_dma;       /* DMA handle for fifo arrays */
993 };
994 
995 /*
996  * Valid SCSIRATE values. (p. 3-17)
997  * Provides a mapping of transfer periods in ns/4 to the proper value to
998  * stick in the SCSIRATE reg to use that transfer rate.
999  */
1000 #define AHC_SYNCRATE_ULTRA3 0
1001 #define AHC_SYNCRATE_ULTRA2 1
1002 #define AHC_SYNCRATE_ULTRA  3
1003 #define AHC_SYNCRATE_FAST   6
1004 #define AHC_SYNCRATE_CRC 0x40
1005 #define AHC_SYNCRATE_SE  0x10
1006 static struct aic7xxx_syncrate {
1007   /* Rates in Ultra mode have bit 8 of sxfr set */
1008 #define                ULTRA_SXFR 0x100
1009   int sxfr_ultra2;
1010   int sxfr;
1011   unsigned char period;
1012   const char *rate[2];
1013 } aic7xxx_syncrates[] = {
1014   { 0x42,  0x000,   9,  {"80.0", "160.0"} },
1015   { 0x13,  0x000,  10,  {"40.0", "80.0"} },
1016   { 0x14,  0x000,  11,  {"33.0", "66.6"} },
1017   { 0x15,  0x100,  12,  {"20.0", "40.0"} },
1018   { 0x16,  0x110,  15,  {"16.0", "32.0"} },
1019   { 0x17,  0x120,  18,  {"13.4", "26.8"} },
1020   { 0x18,  0x000,  25,  {"10.0", "20.0"} },
1021   { 0x19,  0x010,  31,  {"8.0",  "16.0"} },
1022   { 0x1a,  0x020,  37,  {"6.67", "13.3"} },
1023   { 0x1b,  0x030,  43,  {"5.7",  "11.4"} },
1024   { 0x10,  0x040,  50,  {"5.0",  "10.0"} },
1025   { 0x00,  0x050,  56,  {"4.4",  "8.8" } },
1026   { 0x00,  0x060,  62,  {"4.0",  "8.0" } },
1027   { 0x00,  0x070,  68,  {"3.6",  "7.2" } },
1028   { 0x00,  0x000,  0,   {NULL, NULL}   },
1029 };
1030 
1031 #define CTL_OF_SCB(scb) (((scb->hscb)->target_channel_lun >> 3) & 0x1),  \
1032                         (((scb->hscb)->target_channel_lun >> 4) & 0xf), \
1033                         ((scb->hscb)->target_channel_lun & 0x07)
1034 
1035 #define CTL_OF_CMD(cmd) ((cmd->device->channel) & 0x01),  \
1036                         ((cmd->device->id) & 0x0f), \
1037                         ((cmd->device->lun) & 0x07)
1038 
1039 #define TARGET_INDEX(cmd)  ((cmd)->device->id | ((cmd)->device->channel << 3))
1040 
1041 /*
1042  * A nice little define to make doing our printks a little easier
1043  */
1044 
1045 #define WARN_LEAD KERN_WARNING "(scsi%d:%d:%d:%d) "
1046 #define INFO_LEAD KERN_INFO "(scsi%d:%d:%d:%d) "
1047 
1048 /*
1049  * XXX - these options apply unilaterally to _all_ 274x/284x/294x
1050  *       cards in the system.  This should be fixed.  Exceptions to this
1051  *       rule are noted in the comments.
1052  */
1053 
1054 /*
1055  * Use this as the default queue depth when setting tagged queueing on.
1056  */
1057 static unsigned int aic7xxx_default_queue_depth = AIC7XXX_CMDS_PER_DEVICE;
1058 
1059 /*
1060  * Skip the scsi bus reset.  Non 0 make us skip the reset at startup.  This
1061  * has no effect on any later resets that might occur due to things like
1062  * SCSI bus timeouts.
1063  */
1064 static unsigned int aic7xxx_no_reset = 0;
1065 /*
1066  * Certain PCI motherboards will scan PCI devices from highest to lowest,
1067  * others scan from lowest to highest, and they tend to do all kinds of
1068  * strange things when they come into contact with PCI bridge chips.  The
1069  * net result of all this is that the PCI card that is actually used to boot
1070  * the machine is very hard to detect.  Most motherboards go from lowest
1071  * PCI slot number to highest, and the first SCSI controller found is the
1072  * one you boot from.  The only exceptions to this are when a controller
1073  * has its BIOS disabled.  So, we by default sort all of our SCSI controllers
1074  * from lowest PCI slot number to highest PCI slot number.  We also force
1075  * all controllers with their BIOS disabled to the end of the list.  This
1076  * works on *almost* all computers.  Where it doesn't work, we have this
1077  * option.  Setting this option to non-0 will reverse the order of the sort
1078  * to highest first, then lowest, but will still leave cards with their BIOS
1079  * disabled at the very end.  That should fix everyone up unless there are
1080  * really strange cirumstances.
1081  */
1082 static int aic7xxx_reverse_scan = 0;
1083 /*
1084  * Should we force EXTENDED translation on a controller.
1085  *     0 == Use whatever is in the SEEPROM or default to off
1086  *     1 == Use whatever is in the SEEPROM or default to on
1087  */
1088 static unsigned int aic7xxx_extended = 0;
1089 /*
1090  * The IRQ trigger method used on EISA controllers. Does not effect PCI cards.
1091  *   -1 = Use detected settings.
1092  *    0 = Force Edge triggered mode.
1093  *    1 = Force Level triggered mode.
1094  */
1095 static int aic7xxx_irq_trigger = -1;
1096 /*
1097  * This variable is used to override the termination settings on a controller.
1098  * This should not be used under normal conditions.  However, in the case
1099  * that a controller does not have a readable SEEPROM (so that we can't
1100  * read the SEEPROM settings directly) and that a controller has a buggered
1101  * version of the cable detection logic, this can be used to force the 
1102  * correct termination.  It is preferable to use the manual termination
1103  * settings in the BIOS if possible, but some motherboard controllers store
1104  * those settings in a format we can't read.  In other cases, auto term
1105  * should also work, but the chipset was put together with no auto term
1106  * logic (common on motherboard controllers).  In those cases, we have
1107  * 32 bits here to work with.  That's good for 8 controllers/channels.  The
1108  * bits are organized as 4 bits per channel, with scsi0 getting the lowest
1109  * 4 bits in the int.  A 1 in a bit position indicates the termination setting
1110  * that corresponds to that bit should be enabled, a 0 is disabled.
1111  * It looks something like this:
1112  *
1113  *    0x0f =  1111-Single Ended Low Byte Termination on/off
1114  *            ||\-Single Ended High Byte Termination on/off
1115  *            |\-LVD Low Byte Termination on/off
1116  *            \-LVD High Byte Termination on/off
1117  *
1118  * For non-Ultra2 controllers, the upper 2 bits are not important.  So, to
1119  * enable both high byte and low byte termination on scsi0, I would need to
1120  * make sure that the override_term variable was set to 0x03 (bits 0011).
1121  * To make sure that all termination is enabled on an Ultra2 controller at
1122  * scsi2 and only high byte termination on scsi1 and high and low byte
1123  * termination on scsi0, I would set override_term=0xf23 (bits 1111 0010 0011)
1124  *
1125  * For the most part, users should never have to use this, that's why I
1126  * left it fairly cryptic instead of easy to understand.  If you need it,
1127  * most likely someone will be telling you what your's needs to be set to.
1128  */
1129 static int aic7xxx_override_term = -1;
1130 /*
1131  * Certain motherboard chipset controllers tend to screw
1132  * up the polarity of the term enable output pin.  Use this variable
1133  * to force the correct polarity for your system.  This is a bitfield variable
1134  * similar to the previous one, but this one has one bit per channel instead
1135  * of four.
1136  *    0 = Force the setting to active low.
1137  *    1 = Force setting to active high.
1138  * Most Adaptec cards are active high, several motherboards are active low.
1139  * To force a 2940 card at SCSI 0 to active high and a motherboard 7895
1140  * controller at scsi1 and scsi2 to active low, and a 2910 card at scsi3
1141  * to active high, you would need to set stpwlev=0x9 (bits 1001).
1142  *
1143  * People shouldn't need to use this, but if you are experiencing lots of
1144  * SCSI timeout problems, this may help.  There is one sure way to test what
1145  * this option needs to be.  Using a boot floppy to boot the system, configure
1146  * your system to enable all SCSI termination (in the Adaptec SCSI BIOS) and
1147  * if needed then also pass a value to override_term to make sure that the
1148  * driver is enabling SCSI termination, then set this variable to either 0
1149  * or 1.  When the driver boots, make sure there are *NO* SCSI cables
1150  * connected to your controller.  If it finds and inits the controller
1151  * without problem, then the setting you passed to stpwlev was correct.  If
1152  * the driver goes into a reset loop and hangs the system, then you need the
1153  * other setting for this variable.  If neither setting lets the machine
1154  * boot then you have definite termination problems that may not be fixable.
1155  */
1156 static int aic7xxx_stpwlev = -1;
1157 /*
1158  * Set this to non-0 in order to force the driver to panic the kernel
1159  * and print out debugging info on a SCSI abort or reset cycle.
1160  */
1161 static int aic7xxx_panic_on_abort = 0;
1162 /*
1163  * PCI bus parity checking of the Adaptec controllers.  This is somewhat
1164  * dubious at best.  To my knowledge, this option has never actually
1165  * solved a PCI parity problem, but on certain machines with broken PCI
1166  * chipset configurations, it can generate tons of false error messages.
1167  * It's included in the driver for completeness.
1168  *   0 = Shut off PCI parity check
1169  *  -1 = Normal polarity pci parity checking
1170  *   1 = reverse polarity pci parity checking
1171  *
1172  * NOTE: you can't actually pass -1 on the lilo prompt.  So, to set this
1173  * variable to -1 you would actually want to simply pass the variable
1174  * name without a number.  That will invert the 0 which will result in
1175  * -1.
1176  */
1177 static int aic7xxx_pci_parity = 0;
1178 /*
1179  * Set this to any non-0 value to cause us to dump the contents of all
1180  * the card's registers in a hex dump format tailored to each model of
1181  * controller.
1182  * 
1183  * NOTE: THE CONTROLLER IS LEFT IN AN UNUSEABLE STATE BY THIS OPTION.
1184  *       YOU CANNOT BOOT UP WITH THIS OPTION, IT IS FOR DEBUGGING PURPOSES
1185  *       ONLY
1186  */
1187 static int aic7xxx_dump_card = 0;
1188 /*
1189  * Set this to a non-0 value to make us dump out the 32 bit instruction
1190  * registers on the card after completing the sequencer download.  This
1191  * allows the actual sequencer download to be verified.  It is possible
1192  * to use this option and still boot up and run your system.  This is
1193  * only intended for debugging purposes.
1194  */
1195 static int aic7xxx_dump_sequencer = 0;
1196 /*
1197  * Certain newer motherboards have put new PCI based devices into the
1198  * IO spaces that used to typically be occupied by VLB or EISA cards.
1199  * This overlap can cause these newer motherboards to lock up when scanned
1200  * for older EISA and VLB devices.  Setting this option to non-0 will
1201  * cause the driver to skip scanning for any VLB or EISA controllers and
1202  * only support the PCI controllers.  NOTE: this means that if the kernel
1203  * os compiled with PCI support disabled, then setting this to non-0
1204  * would result in never finding any devices :)
1205  */
1206 static int aic7xxx_no_probe = 0;
1207 /*
1208  * On some machines, enabling the external SCB RAM isn't reliable yet.  I
1209  * haven't had time to make test patches for things like changing the
1210  * timing mode on that external RAM either.  Some of those changes may
1211  * fix the problem.  Until then though, we default to external SCB RAM
1212  * off and give a command line option to enable it.
1213  */
1214 static int aic7xxx_scbram = 0;
1215 /*
1216  * So that we can set how long each device is given as a selection timeout.
1217  * The table of values goes like this:
1218  *   0 - 256ms
1219  *   1 - 128ms
1220  *   2 - 64ms
1221  *   3 - 32ms
1222  * We default to 64ms because it's fast.  Some old SCSI-I devices need a
1223  * longer time.  The final value has to be left shifted by 3, hence 0x10
1224  * is the final value.
1225  */
1226 static int aic7xxx_seltime = 0x10;
1227 /*
1228  * So that insmod can find the variable and make it point to something
1229  */
1230 #ifdef MODULE
1231 static char * aic7xxx = NULL;
1232 module_param(aic7xxx, charp, 0);
1233 #endif
1234 
1235 #define VERBOSE_NORMAL         0x0000
1236 #define VERBOSE_NEGOTIATION    0x0001
1237 #define VERBOSE_SEQINT         0x0002
1238 #define VERBOSE_SCSIINT        0x0004
1239 #define VERBOSE_PROBE          0x0008
1240 #define VERBOSE_PROBE2         0x0010
1241 #define VERBOSE_NEGOTIATION2   0x0020
1242 #define VERBOSE_MINOR_ERROR    0x0040
1243 #define VERBOSE_TRACING        0x0080
1244 #define VERBOSE_ABORT          0x0f00
1245 #define VERBOSE_ABORT_MID      0x0100
1246 #define VERBOSE_ABORT_FIND     0x0200
1247 #define VERBOSE_ABORT_PROCESS  0x0400
1248 #define VERBOSE_ABORT_RETURN   0x0800
1249 #define VERBOSE_RESET          0xf000
1250 #define VERBOSE_RESET_MID      0x1000
1251 #define VERBOSE_RESET_FIND     0x2000
1252 #define VERBOSE_RESET_PROCESS  0x4000
1253 #define VERBOSE_RESET_RETURN   0x8000
1254 static int aic7xxx_verbose = VERBOSE_NORMAL | VERBOSE_NEGOTIATION |
1255            VERBOSE_PROBE;                     /* verbose messages */
1256 
1257 
1258 /****************************************************************************
1259  *
1260  * We're going to start putting in function declarations so that order of
1261  * functions is no longer important.  As needed, they are added here.
1262  *
1263  ***************************************************************************/
1264 
1265 static int aic7xxx_release(struct Scsi_Host *host);
1266 static void aic7xxx_set_syncrate(struct aic7xxx_host *p, 
1267                 struct aic7xxx_syncrate *syncrate, int target, int channel,
1268                 unsigned int period, unsigned int offset, unsigned char options,
1269                 unsigned int type, struct aic_dev_data *aic_dev);
1270 static void aic7xxx_set_width(struct aic7xxx_host *p, int target, int channel,
1271                 int lun, unsigned int width, unsigned int type,
1272                 struct aic_dev_data *aic_dev);
1273 static void aic7xxx_panic_abort(struct aic7xxx_host *p, struct scsi_cmnd *cmd);
1274 static void aic7xxx_print_card(struct aic7xxx_host *p);
1275 static void aic7xxx_print_scratch_ram(struct aic7xxx_host *p);
1276 static void aic7xxx_print_sequencer(struct aic7xxx_host *p, int downloaded);
1277 #ifdef AIC7XXX_VERBOSE_DEBUGGING
1278 static void aic7xxx_check_scbs(struct aic7xxx_host *p, char *buffer);
1279 #endif
1280 
1281 /****************************************************************************
1282  *
1283  * These functions are now used.  They happen to be wrapped in useless
1284  * inb/outb port read/writes around the real reads and writes because it
1285  * seems that certain very fast CPUs have a problem dealing with us when
1286  * going at full speed.
1287  *
1288  ***************************************************************************/
1289 
1290 static unsigned char
1291 aic_inb(struct aic7xxx_host *p, long port)
1292 {
1293 #ifdef MMAPIO
1294   unsigned char x;
1295   if(p->maddr)
1296   {
1297     x = readb(p->maddr + port);
1298   }
1299   else
1300   {
1301     x = inb(p->base + port);
1302   }
1303   return(x);
1304 #else
1305   return(inb(p->base + port));
1306 #endif
1307 }
1308 
1309 static void
1310 aic_outb(struct aic7xxx_host *p, unsigned char val, long port)
1311 {
1312 #ifdef MMAPIO
1313   if(p->maddr)
1314   {
1315     writeb(val, p->maddr + port);
1316     mb(); /* locked operation in order to force CPU ordering */
1317     readb(p->maddr + HCNTRL); /* dummy read to flush the PCI write */
1318   }
1319   else
1320   {
1321     outb(val, p->base + port);
1322     mb(); /* locked operation in order to force CPU ordering */
1323   }
1324 #else
1325   outb(val, p->base + port);
1326   mb(); /* locked operation in order to force CPU ordering */
1327 #endif
1328 }
1329 
1330 /*+F*************************************************************************
1331  * Function:
1332  *   aic7xxx_setup
1333  *
1334  * Description:
1335  *   Handle Linux boot parameters. This routine allows for assigning a value
1336  *   to a parameter with a ':' between the parameter and the value.
1337  *   ie. aic7xxx=unpause:0x0A,extended
1338  *-F*************************************************************************/
1339 static int
1340 aic7xxx_setup(char *s)
1341 {
1342   int   i, n;
1343   char *p;
1344   char *end;
1345 
1346   static struct {
1347     const char *name;
1348     unsigned int *flag;
1349   } options[] = {
1350     { "extended",    &aic7xxx_extended },
1351     { "no_reset",    &aic7xxx_no_reset },
1352     { "irq_trigger", &aic7xxx_irq_trigger },
1353     { "verbose",     &aic7xxx_verbose },
1354     { "reverse_scan",&aic7xxx_reverse_scan },
1355     { "override_term", &aic7xxx_override_term },
1356     { "stpwlev", &aic7xxx_stpwlev },
1357     { "no_probe", &aic7xxx_no_probe },
1358     { "panic_on_abort", &aic7xxx_panic_on_abort },
1359     { "pci_parity", &aic7xxx_pci_parity },
1360     { "dump_card", &aic7xxx_dump_card },
1361     { "dump_sequencer", &aic7xxx_dump_sequencer },
1362     { "default_queue_depth", &aic7xxx_default_queue_depth },
1363     { "scbram", &aic7xxx_scbram },
1364     { "seltime", &aic7xxx_seltime },
1365     { "tag_info",    NULL }
1366   };
1367 
1368   end = strchr(s, '\0');
1369 
1370   while ((p = strsep(&s, ",.")) != NULL)
1371   {
1372     for (i = 0; i < ARRAY_SIZE(options); i++)
1373     {
1374       n = strlen(options[i].name);
1375       if (!strncmp(options[i].name, p, n))
1376       {
1377         if (!strncmp(p, "tag_info", n))
1378         {
1379           if (p[n] == ':')
1380           {
1381             char *base;
1382             char *tok, *tok_end, *tok_end2;
1383             char tok_list[] = { '.', ',', '{', '}', '\0' };
1384             int i, instance = -1, device = -1;
1385             unsigned char done = FALSE;
1386 
1387             base = p;
1388             tok = base + n + 1;  /* Forward us just past the ':' */
1389             tok_end = strchr(tok, '\0');
1390             if (tok_end < end)
1391               *tok_end = ',';
1392             while(!done)
1393             {
1394               switch(*tok)
1395               {
1396                 case '{':
1397                   if (instance == -1)
1398                     instance = 0;
1399                   else if (device == -1)
1400                     device = 0;
1401                   tok++;
1402                   break;
1403                 case '}':
1404                   if (device != -1)
1405                     device = -1;
1406                   else if (instance != -1)
1407                     instance = -1;
1408                   tok++;
1409                   break;
1410                 case ',':
1411                 case '.':
1412                   if (instance == -1)
1413                     done = TRUE;
1414                   else if (device >= 0)
1415                     device++;
1416                   else if (instance >= 0)
1417                     instance++;
1418                   if ( (device >= MAX_TARGETS) || 
1419                        (instance >= ARRAY_SIZE(aic7xxx_tag_info)) )
1420                     done = TRUE;
1421                   tok++;
1422                   if (!done)
1423                   {
1424                     base = tok;
1425                   }
1426                   break;
1427                 case '\0':
1428                   done = TRUE;
1429                   break;
1430                 default:
1431                   done = TRUE;
1432                   tok_end = strchr(tok, '\0');
1433                   for(i=0; tok_list[i]; i++)
1434                   {
1435                     tok_end2 = strchr(tok, tok_list[i]);
1436                     if ( (tok_end2) && (tok_end2 < tok_end) )
1437                     {
1438                       tok_end = tok_end2;
1439                       done = FALSE;
1440                     }
1441                   }
1442                   if ( (instance >= 0) && (device >= 0) &&
1443                        (instance < ARRAY_SIZE(aic7xxx_tag_info)) &&
1444                        (device < MAX_TARGETS) )
1445                     aic7xxx_tag_info[instance].tag_commands[device] =
1446                       simple_strtoul(tok, NULL, 0) & 0xff;
1447                   tok = tok_end;
1448                   break;
1449               }
1450             }
1451             while((p != base) && (p != NULL))
1452               p = strsep(&s, ",.");
1453           }
1454         }
1455         else if (p[n] == ':')
1456         {
1457           *(options[i].flag) = simple_strtoul(p + n + 1, NULL, 0);
1458           if(!strncmp(p, "seltime", n))
1459           {
1460             *(options[i].flag) = (*(options[i].flag) % 4) << 3;
1461           }
1462         }
1463         else if (!strncmp(p, "verbose", n))
1464         {
1465           *(options[i].flag) = 0xff29;
1466         }
1467         else
1468         {
1469           *(options[i].flag) = ~(*(options[i].flag));
1470           if(!strncmp(p, "seltime", n))
1471           {
1472             *(options[i].flag) = (*(options[i].flag) % 4) << 3;
1473           }
1474         }
1475       }
1476     }
1477   }
1478   return 1;
1479 }
1480 
1481 __setup("aic7xxx=", aic7xxx_setup);
1482 
1483 /*+F*************************************************************************
1484  * Function:
1485  *   pause_sequencer
1486  *
1487  * Description:
1488  *   Pause the sequencer and wait for it to actually stop - this
1489  *   is important since the sequencer can disable pausing for critical
1490  *   sections.
1491  *-F*************************************************************************/
1492 static void
1493 pause_sequencer(struct aic7xxx_host *p)
1494 {
1495   aic_outb(p, p->pause, HCNTRL);
1496   while ((aic_inb(p, HCNTRL) & PAUSE) == 0)
1497   {
1498     ;
1499   }
1500   if(p->features & AHC_ULTRA2)
1501   {
1502     aic_inb(p, CCSCBCTL);
1503   }
1504 }
1505 
1506 /*+F*************************************************************************
1507  * Function:
1508  *   unpause_sequencer
1509  *
1510  * Description:
1511  *   Unpause the sequencer. Unremarkable, yet done often enough to
1512  *   warrant an easy way to do it.
1513  *-F*************************************************************************/
1514 static void
1515 unpause_sequencer(struct aic7xxx_host *p, int unpause_always)
1516 {
1517   if (unpause_always ||
1518       ( !(aic_inb(p, INTSTAT) & (SCSIINT | SEQINT | BRKADRINT)) &&
1519         !(p->flags & AHC_HANDLING_REQINITS) ) )
1520   {
1521     aic_outb(p, p->unpause, HCNTRL);
1522   }
1523 }
1524 
1525 /*+F*************************************************************************
1526  * Function:
1527  *   restart_sequencer
1528  *
1529  * Description:
1530  *   Restart the sequencer program from address zero.  This assumes
1531  *   that the sequencer is already paused.
1532  *-F*************************************************************************/
1533 static void
1534 restart_sequencer(struct aic7xxx_host *p)
1535 {
1536   aic_outb(p, 0, SEQADDR0);
1537   aic_outb(p, 0, SEQADDR1);
1538   aic_outb(p, FASTMODE, SEQCTL);
1539 }
1540 
1541 /*
1542  * We include the aic7xxx_seq.c file here so that the other defines have
1543  * already been made, and so that it comes before the code that actually
1544  * downloads the instructions (since we don't typically use function
1545  * prototype, our code has to be ordered that way, it's a left-over from
1546  * the original driver days.....I should fix it some time DL).
1547  */
1548 #include "aic7xxx_old/aic7xxx_seq.c"
1549 
1550 /*+F*************************************************************************
1551  * Function:
1552  *   aic7xxx_check_patch
1553  *
1554  * Description:
1555  *   See if the next patch to download should be downloaded.
1556  *-F*************************************************************************/
1557 static int
1558 aic7xxx_check_patch(struct aic7xxx_host *p,
1559   struct sequencer_patch **start_patch, int start_instr, int *skip_addr)
1560 {
1561   struct sequencer_patch *cur_patch;
1562   struct sequencer_patch *last_patch;
1563   int num_patches;
1564 
1565   num_patches = ARRAY_SIZE(sequencer_patches);
1566   last_patch = &sequencer_patches[num_patches];
1567   cur_patch = *start_patch;
1568 
1569   while ((cur_patch < last_patch) && (start_instr == cur_patch->begin))
1570   {
1571     if (cur_patch->patch_func(p) == 0)
1572     {
1573       /*
1574        * Start rejecting code.
1575        */
1576       *skip_addr = start_instr + cur_patch->skip_instr;
1577       cur_patch += cur_patch->skip_patch;
1578     }
1579     else
1580     {
1581       /*
1582        * Found an OK patch.  Advance the patch pointer to the next patch
1583        * and wait for our instruction pointer to get here.
1584        */
1585       cur_patch++;
1586     }
1587   }
1588 
1589   *start_patch = cur_patch;
1590   if (start_instr < *skip_addr)
1591     /*
1592      * Still skipping
1593      */
1594     return (0);
1595   return(1);
1596 }
1597 
1598 
1599 /*+F*************************************************************************
1600  * Function:
1601  *   aic7xxx_download_instr
1602  *
1603  * Description:
1604  *   Find the next patch to download.
1605  *-F*************************************************************************/
1606 static void
1607 aic7xxx_download_instr(struct aic7xxx_host *p, int instrptr,
1608   unsigned char *dconsts)
1609 {
1610   union ins_formats instr;
1611   struct ins_format1 *fmt1_ins;
1612   struct ins_format3 *fmt3_ins;
1613   unsigned char opcode;
1614 
1615   instr = *(union ins_formats*) &seqprog[instrptr * 4];
1616 
1617   instr.integer = le32_to_cpu(instr.integer);
1618   
1619   fmt1_ins = &instr.format1;
1620   fmt3_ins = NULL;
1621 
1622   /* Pull the opcode */
1623   opcode = instr.format1.opcode;
1624   switch (opcode)
1625   {
1626     case AIC_OP_JMP:
1627     case AIC_OP_JC:
1628     case AIC_OP_JNC:
1629     case AIC_OP_CALL:
1630     case AIC_OP_JNE:
1631     case AIC_OP_JNZ:
1632     case AIC_OP_JE:
1633     case AIC_OP_JZ:
1634     {
1635       struct sequencer_patch *cur_patch;
1636       int address_offset;
1637       unsigned int address;
1638       int skip_addr;
1639       int i;
1640 
1641       fmt3_ins = &instr.format3;
1642       address_offset = 0;
1643       address = fmt3_ins->address;
1644       cur_patch = sequencer_patches;
1645       skip_addr = 0;
1646 
1647       for (i = 0; i < address;)
1648       {
1649         aic7xxx_check_patch(p, &cur_patch, i, &skip_addr);
1650         if (skip_addr > i)
1651         {
1652           int end_addr;
1653 
1654           end_addr = min_t(int, address, skip_addr);
1655           address_offset += end_addr - i;
1656           i = skip_addr;
1657         }
1658         else
1659         {
1660           i++;
1661         }
1662       }
1663       address -= address_offset;
1664       fmt3_ins->address = address;
1665       /* Fall Through to the next code section */
1666     }
1667     case AIC_OP_OR:
1668     case AIC_OP_AND:
1669     case AIC_OP_XOR:
1670     case AIC_OP_ADD:
1671     case AIC_OP_ADC:
1672     case AIC_OP_BMOV:
1673       if (fmt1_ins->parity != 0)
1674       {
1675         fmt1_ins->immediate = dconsts[fmt1_ins->immediate];
1676       }
1677       fmt1_ins->parity = 0;
1678       /* Fall Through to the next code section */
1679     case AIC_OP_ROL:
1680       if ((p->features & AHC_ULTRA2) != 0)
1681       {
1682         int i, count;
1683 
1684         /* Calculate odd parity for the instruction */
1685         for ( i=0, count=0; i < 31; i++)
1686         {
1687           unsigned int mask;
1688 
1689           mask = 0x01 << i;
1690           if ((instr.integer & mask) != 0)
1691             count++;
1692         }
1693         if (!(count & 0x01))
1694           instr.format1.parity = 1;
1695       }
1696       else
1697       {
1698         if (fmt3_ins != NULL)
1699         {
1700           instr.integer =  fmt3_ins->immediate |
1701                           (fmt3_ins->source << 8) |
1702                           (fmt3_ins->address << 16) |
1703                           (fmt3_ins->opcode << 25);
1704         }
1705         else
1706         {
1707           instr.integer =  fmt1_ins->immediate |
1708                           (fmt1_ins->source << 8) |
1709                           (fmt1_ins->destination << 16) |
1710                           (fmt1_ins->ret << 24) |
1711                           (fmt1_ins->opcode << 25);
1712         }
1713       }
1714       aic_outb(p, (instr.integer & 0xff), SEQRAM);
1715       aic_outb(p, ((instr.integer >> 8) & 0xff), SEQRAM);
1716       aic_outb(p, ((instr.integer >> 16) & 0xff), SEQRAM);
1717       aic_outb(p, ((instr.integer >> 24) & 0xff), SEQRAM);
1718       udelay(10);
1719       break;
1720 
1721     default:
1722       panic("aic7xxx: Unknown opcode encountered in sequencer program.");
1723       break;
1724   }
1725 }
1726 
1727 
1728 /*+F*************************************************************************
1729  * Function:
1730  *   aic7xxx_loadseq
1731  *
1732  * Description:
1733  *   Load the sequencer code into the controller memory.
1734  *-F*************************************************************************/
1735 static void
1736 aic7xxx_loadseq(struct aic7xxx_host *p)
1737 {
1738   struct sequencer_patch *cur_patch;
1739   int i;
1740   int downloaded;
1741   int skip_addr;
1742   unsigned char download_consts[4] = {0, 0, 0, 0};
1743 
1744   if (aic7xxx_verbose & VERBOSE_PROBE)
1745   {
1746     printk(KERN_INFO "(scsi%d) Downloading sequencer code...", p->host_no);
1747   }
1748 #if 0
1749   download_consts[TMODE_NUMCMDS] = p->num_targetcmds;
1750 #endif
1751   download_consts[TMODE_NUMCMDS] = 0;
1752   cur_patch = &sequencer_patches[0];
1753   downloaded = 0;
1754   skip_addr = 0;
1755 
1756   aic_outb(p, PERRORDIS|LOADRAM|FAILDIS|FASTMODE, SEQCTL);
1757   aic_outb(p, 0, SEQADDR0);
1758   aic_outb(p, 0, SEQADDR1);
1759 
1760   for (i = 0; i < sizeof(seqprog) / 4;  i++)
1761   {
1762     if (aic7xxx_check_patch(p, &cur_patch, i, &skip_addr) == 0)
1763     {
1764       /* Skip this instruction for this configuration. */
1765       continue;
1766     }
1767     aic7xxx_download_instr(p, i, &download_consts[0]);
1768     downloaded++;
1769   }
1770 
1771   aic_outb(p, 0, SEQADDR0);
1772   aic_outb(p, 0, SEQADDR1);
1773   aic_outb(p, FASTMODE | FAILDIS, SEQCTL);
1774   unpause_sequencer(p, TRUE);
1775   mdelay(1);
1776   pause_sequencer(p);
1777   aic_outb(p, FASTMODE, SEQCTL);
1778   if (aic7xxx_verbose & VERBOSE_PROBE)
1779   {
1780     printk(" %d instructions downloaded\n", downloaded);
1781   }
1782   if (aic7xxx_dump_sequencer)
1783     aic7xxx_print_sequencer(p, downloaded);
1784 }
1785 
1786 /*+F*************************************************************************
1787  * Function:
1788  *   aic7xxx_print_sequencer
1789  *
1790  * Description:
1791  *   Print the contents of the sequencer memory to the screen.
1792  *-F*************************************************************************/
1793 static void
1794 aic7xxx_print_sequencer(struct aic7xxx_host *p, int downloaded)
1795 {
1796   int i, k, temp;
1797   
1798   aic_outb(p, PERRORDIS|LOADRAM|FAILDIS|FASTMODE, SEQCTL);
1799   aic_outb(p, 0, SEQADDR0);
1800   aic_outb(p, 0, SEQADDR1);
1801 
1802   k = 0;
1803   for (i=0; i < downloaded; i++)
1804   {
1805     if ( k == 0 )
1806       printk("%03x: ", i);
1807     temp = aic_inb(p, SEQRAM);
1808     temp |= (aic_inb(p, SEQRAM) << 8);
1809     temp |= (aic_inb(p, SEQRAM) << 16);
1810     temp |= (aic_inb(p, SEQRAM) << 24);
1811     printk("%08x", temp);
1812     if ( ++k == 8 )
1813     {
1814       printk("\n");
1815       k = 0;
1816     }
1817     else
1818       printk(" ");
1819   }
1820   aic_outb(p, 0, SEQADDR0);
1821   aic_outb(p, 0, SEQADDR1);
1822   aic_outb(p, FASTMODE | FAILDIS, SEQCTL);
1823   unpause_sequencer(p, TRUE);
1824   mdelay(1);
1825   pause_sequencer(p);
1826   aic_outb(p, FASTMODE, SEQCTL);
1827   printk("\n");
1828 }
1829 
1830 /*+F*************************************************************************
1831  * Function:
1832  *   aic7xxx_info
1833  *
1834  * Description:
1835  *   Return a string describing the driver.
1836  *-F*************************************************************************/
1837 static const char *
1838 aic7xxx_info(struct Scsi_Host *dooh)
1839 {
1840   static char buffer[256];
1841   char *bp;
1842   struct aic7xxx_host *p;
1843 
1844   bp = &buffer[0];
1845   p = (struct aic7xxx_host *)dooh->hostdata;
1846   memset(bp, 0, sizeof(buffer));
1847   strcpy(bp, "Adaptec AHA274x/284x/294x (EISA/VLB/PCI-Fast SCSI) ");
1848   strcat(bp, AIC7XXX_C_VERSION);
1849   strcat(bp, "/");
1850   strcat(bp, AIC7XXX_H_VERSION);
1851   strcat(bp, "\n");
1852   strcat(bp, "       <");
1853   strcat(bp, board_names[p->board_name_index]);
1854   strcat(bp, ">");
1855 
1856   return(bp);
1857 }
1858 
1859 /*+F*************************************************************************
1860  * Function:
1861  *   aic7xxx_find_syncrate
1862  *
1863  * Description:
1864  *   Look up the valid period to SCSIRATE conversion in our table
1865  *-F*************************************************************************/
1866 static struct aic7xxx_syncrate *
1867 aic7xxx_find_syncrate(struct aic7xxx_host *p, unsigned int *period,
1868   unsigned int maxsync, unsigned char *options)
1869 {
1870   struct aic7xxx_syncrate *syncrate;
1871   int done = FALSE;
1872 
1873   switch(*options)
1874   {
1875     case MSG_EXT_PPR_OPTION_DT_CRC:
1876     case MSG_EXT_PPR_OPTION_DT_UNITS:
1877       if(!(p->features & AHC_ULTRA3))
1878       {
1879         *options = 0;
1880         maxsync = max_t(unsigned int, maxsync, AHC_SYNCRATE_ULTRA2);
1881       }
1882       break;
1883     case MSG_EXT_PPR_OPTION_DT_CRC_QUICK:
1884     case MSG_EXT_PPR_OPTION_DT_UNITS_QUICK:
1885       if(!(p->features & AHC_ULTRA3))
1886       {
1887         *options = 0;
1888         maxsync = max_t(unsigned int, maxsync, AHC_SYNCRATE_ULTRA2);
1889       }
1890       else
1891       {
1892         /*
1893          * we don't support the Quick Arbitration variants of dual edge
1894          * clocking.  As it turns out, we want to send back the
1895          * same basic option, but without the QA attribute.
1896          * We know that we are responding because we would never set
1897          * these options ourself, we would only respond to them.
1898          */
1899         switch(*options)
1900         {
1901           case MSG_EXT_PPR_OPTION_DT_CRC_QUICK:
1902             *options = MSG_EXT_PPR_OPTION_DT_CRC;
1903             break;
1904           case MSG_EXT_PPR_OPTION_DT_UNITS_QUICK:
1905             *options = MSG_EXT_PPR_OPTION_DT_UNITS;
1906             break;
1907         }
1908       }
1909       break;
1910     default:
1911       *options = 0;
1912       maxsync = max_t(unsigned int, maxsync, AHC_SYNCRATE_ULTRA2);
1913       break;
1914   }
1915   syncrate = &aic7xxx_syncrates[maxsync];
1916   while ( (syncrate->rate[0] != NULL) &&
1917          (!(p->features & AHC_ULTRA2) || syncrate->sxfr_ultra2) )
1918   {
1919     if (*period <= syncrate->period) 
1920     {
1921       switch(*options)
1922       {
1923         case MSG_EXT_PPR_OPTION_DT_CRC:
1924         case MSG_EXT_PPR_OPTION_DT_UNITS:
1925           if(!(syncrate->sxfr_ultra2 & AHC_SYNCRATE_CRC))
1926           {
1927             done = TRUE;
1928             /*
1929              * oops, we went too low for the CRC/DualEdge signalling, so
1930              * clear the options byte
1931              */
1932             *options = 0;
1933             /*
1934              * We'll be sending a reply to this packet to set the options
1935              * properly, so unilaterally set the period as well.
1936              */
1937             *period = syncrate->period;
1938           }
1939           else
1940           {
1941             done = TRUE;
1942             if(syncrate == &aic7xxx_syncrates[maxsync])
1943             {
1944               *period = syncrate->period;
1945             }
1946           }
1947           break;
1948         default:
1949           if(!(syncrate->sxfr_ultra2 & AHC_SYNCRATE_CRC))
1950           {
1951             done = TRUE;
1952             if(syncrate == &aic7xxx_syncrates[maxsync])
1953             {
1954               *period = syncrate->period;
1955             }
1956           }
1957           break;
1958       }
1959       if(done)
1960       {
1961         break;
1962       }
1963     }
1964     syncrate++;
1965   }
1966   if ( (*period == 0) || (syncrate->rate[0] == NULL) ||
1967        ((p->features & AHC_ULTRA2) && (syncrate->sxfr_ultra2 == 0)) )
1968   {
1969     /*
1970      * Use async transfers for this target
1971      */
1972     *options = 0;
1973     *period = 255;
1974     syncrate = NULL;
1975   }
1976   return (syncrate);
1977 }
1978 
1979 
1980 /*+F*************************************************************************
1981  * Function:
1982  *   aic7xxx_find_period
1983  *
1984  * Description:
1985  *   Look up the valid SCSIRATE to period conversion in our table
1986  *-F*************************************************************************/
1987 static unsigned int
1988 aic7xxx_find_period(struct aic7xxx_host *p, unsigned int scsirate,
1989   unsigned int maxsync)
1990 {
1991   struct aic7xxx_syncrate *syncrate;
1992 
1993   if (p->features & AHC_ULTRA2)
1994   {
1995     scsirate &= SXFR_ULTRA2;
1996   }
1997   else
1998   {
1999     scsirate &= SXFR;
2000   }
2001 
2002   syncrate = &aic7xxx_syncrates[maxsync];
2003   while (syncrate->rate[0] != NULL)
2004   {
2005     if (p->features & AHC_ULTRA2)
2006     {
2007       if (syncrate->sxfr_ultra2 == 0)
2008         break;
2009       else if (scsirate == syncrate->sxfr_ultra2)
2010         return (syncrate->period);
2011       else if (scsirate == (syncrate->sxfr_ultra2 & ~AHC_SYNCRATE_CRC))
2012         return (syncrate->period);
2013     }
2014     else if (scsirate == (syncrate->sxfr & ~ULTRA_SXFR))
2015     {
2016       return (syncrate->period);
2017     }
2018     syncrate++;
2019   }
2020   return (0); /* async */
2021 }
2022 
2023 /*+F*************************************************************************
2024  * Function:
2025  *   aic7xxx_validate_offset
2026  *
2027  * Description:
2028  *   Set a valid offset value for a particular card in use and transfer
2029  *   settings in use.
2030  *-F*************************************************************************/
2031 static void
2032 aic7xxx_validate_offset(struct aic7xxx_host *p,
2033   struct aic7xxx_syncrate *syncrate, unsigned int *offset, int wide)
2034 {
2035   unsigned int maxoffset;
2036 
2037   /* Limit offset to what the card (and device) can do */
2038   if (syncrate == NULL)
2039   {
2040     maxoffset = 0;
2041   }
2042   else if (p->features & AHC_ULTRA2)
2043   {
2044     maxoffset = MAX_OFFSET_ULTRA2;
2045   }
2046   else
2047   {
2048     if (wide)
2049       maxoffset = MAX_OFFSET_16BIT;
2050     else
2051       maxoffset = MAX_OFFSET_8BIT;
2052   }
2053   *offset = min(*offset, maxoffset);
2054 }
2055 
2056 /*+F*************************************************************************
2057  * Function:
2058  *   aic7xxx_set_syncrate
2059  *
2060  * Description:
2061  *   Set the actual syncrate down in the card and in our host structs
2062  *-F*************************************************************************/
2063 static void
2064 aic7xxx_set_syncrate(struct aic7xxx_host *p, struct aic7xxx_syncrate *syncrate,
2065     int target, int channel, unsigned int period, unsigned int offset,
2066     unsigned char options, unsigned int type, struct aic_dev_data *aic_dev)
2067 {
2068   unsigned char tindex;
2069   unsigned short target_mask;
2070   unsigned char lun, old_options;
2071   unsigned int old_period, old_offset;
2072 
2073   tindex = target | (channel << 3);
2074   target_mask = 0x01 << tindex;
2075   lun = aic_inb(p, SCB_TCL) & 0x07;
2076 
2077   if (syncrate == NULL)
2078   {
2079     period = 0;
2080     offset = 0;
2081   }
2082 
2083   old_period = aic_dev->cur.period;
2084   old_offset = aic_dev->cur.offset;
2085   old_options = aic_dev->cur.options;
2086 
2087   
2088   if (type & AHC_TRANS_CUR)
2089   {
2090     unsigned int scsirate;
2091 
2092     scsirate = aic_inb(p, TARG_SCSIRATE + tindex);
2093     if (p->features & AHC_ULTRA2)
2094     {
2095       scsirate &= ~SXFR_ULTRA2;
2096       if (syncrate != NULL)
2097       {
2098         switch(options)
2099         {
2100           case MSG_EXT_PPR_OPTION_DT_UNITS:
2101             /*
2102              * mask off the CRC bit in the xfer settings
2103              */
2104             scsirate |= (syncrate->sxfr_ultra2 & ~AHC_SYNCRATE_CRC);
2105             break;
2106           default:
2107             scsirate |= syncrate->sxfr_ultra2;
2108             break;
2109         }
2110       }
2111       if (type & AHC_TRANS_ACTIVE)
2112       {
2113         aic_outb(p, offset, SCSIOFFSET);
2114       }
2115       aic_outb(p, offset, TARG_OFFSET + tindex);
2116     }
2117     else /* Not an Ultra2 controller */
2118     {
2119       scsirate &= ~(SXFR|SOFS);
2120       p->ultraenb &= ~target_mask;
2121       if (syncrate != NULL)
2122       {
2123         if (syncrate->sxfr & ULTRA_SXFR)
2124         {
2125           p->ultraenb |= target_mask;
2126         }
2127         scsirate |= (syncrate->sxfr & SXFR);
2128         scsirate |= (offset & SOFS);
2129       }
2130       if (type & AHC_TRANS_ACTIVE)
2131       {
2132         unsigned char sxfrctl0;
2133 
2134         sxfrctl0 = aic_inb(p, SXFRCTL0);
2135         sxfrctl0 &= ~FAST20;
2136         if (p->ultraenb & target_mask)
2137           sxfrctl0 |= FAST20;
2138         aic_outb(p, sxfrctl0, SXFRCTL0);
2139       }
2140       aic_outb(p, p->ultraenb & 0xff, ULTRA_ENB);
2141       aic_outb(p, (p->ultraenb >> 8) & 0xff, ULTRA_ENB + 1 );
2142     }
2143     if (type & AHC_TRANS_ACTIVE)
2144     {
2145       aic_outb(p, scsirate, SCSIRATE);
2146     }
2147     aic_outb(p, scsirate, TARG_SCSIRATE + tindex);
2148     aic_dev->cur.period = period;
2149     aic_dev->cur.offset = offset;
2150     aic_dev->cur.options = options;
2151     if ( !(type & AHC_TRANS_QUITE) &&
2152          (aic7xxx_verbose & VERBOSE_NEGOTIATION) &&
2153          (aic_dev->flags & DEVICE_PRINT_DTR) )
2154     {
2155       if (offset)
2156       {
2157         int rate_mod = (scsirate & WIDEXFER) ? 1 : 0;
2158       
2159         printk(INFO_LEAD "Synchronous at %s Mbyte/sec, "
2160                "offset %d.\n", p->host_no, channel, target, lun,
2161                syncrate->rate[rate_mod], offset);
2162       }
2163       else
2164       {
2165         printk(INFO_LEAD "Using asynchronous transfers.\n",
2166                p->host_no, channel, target, lun);
2167       }
2168       aic_dev->flags &= ~DEVICE_PRINT_DTR;
2169     }
2170   }
2171 
2172   if (type & AHC_TRANS_GOAL)
2173   {
2174     aic_dev->goal.period = period;
2175     aic_dev->goal.offset = offset;
2176     aic_dev->goal.options = options;
2177   }
2178 
2179   if (type & AHC_TRANS_USER)
2180   {
2181     p->user[tindex].period = period;
2182     p->user[tindex].offset = offset;
2183     p->user[tindex].options = options;
2184   }
2185 }
2186 
2187 /*+F*************************************************************************
2188  * Function:
2189  *   aic7xxx_set_width
2190  *
2191  * Description:
2192  *   Set the actual width down in the card and in our host structs
2193  *-F*************************************************************************/
2194 static void
2195 aic7xxx_set_width(struct aic7xxx_host *p, int target, int channel, int lun,
2196     unsigned int width, unsigned int type, struct aic_dev_data *aic_dev)
2197 {
2198   unsigned char tindex;
2199   unsigned short target_mask;
2200   unsigned int old_width;
2201 
2202   tindex = target | (channel << 3);
2203   target_mask = 1 << tindex;
2204   
2205   old_width = aic_dev->cur.width;
2206 
2207   if (type & AHC_TRANS_CUR) 
2208   {
2209     unsigned char scsirate;
2210 
2211     scsirate = aic_inb(p, TARG_SCSIRATE + tindex);
2212 
2213     scsirate &= ~WIDEXFER;
2214     if (width == MSG_EXT_WDTR_BUS_16_BIT)
2215       scsirate |= WIDEXFER;
2216 
2217     aic_outb(p, scsirate, TARG_SCSIRATE + tindex);
2218 
2219     if (type & AHC_TRANS_ACTIVE)
2220       aic_outb(p, scsirate, SCSIRATE);
2221 
2222     aic_dev->cur.width = width;
2223 
2224     if ( !(type & AHC_TRANS_QUITE) &&
2225           (aic7xxx_verbose & VERBOSE_NEGOTIATION2) && 
2226           (aic_dev->flags & DEVICE_PRINT_DTR) )
2227     {
2228       printk(INFO_LEAD "Using %s transfers\n", p->host_no, channel, target,
2229         lun, (scsirate & WIDEXFER) ? "Wide(16bit)" : "Narrow(8bit)" );
2230     }
2231   }
2232 
2233   if (type & AHC_TRANS_GOAL)
2234     aic_dev->goal.width = width;
2235   if (type & AHC_TRANS_USER)
2236     p->user[tindex].width = width;
2237 
2238   if (aic_dev->goal.offset)
2239   {
2240     if (p->features & AHC_ULTRA2)
2241     {
2242       aic_dev->goal.offset = MAX_OFFSET_ULTRA2;
2243     }
2244     else if (width == MSG_EXT_WDTR_BUS_16_BIT)
2245     {
2246       aic_dev->goal.offset = MAX_OFFSET_16BIT;
2247     }
2248     else
2249     {
2250       aic_dev->goal.offset = MAX_OFFSET_8BIT;
2251     }
2252   }
2253 }
2254       
2255 /*+F*************************************************************************
2256  * Function:
2257  *   scbq_init
2258  *
2259  * Description:
2260  *   SCB queue initialization.
2261  *
2262  *-F*************************************************************************/
2263 static void
2264 scbq_init(volatile scb_queue_type *queue)
2265 {
2266   queue->head = NULL;
2267   queue->tail = NULL;
2268 }
2269 
2270 /*+F*************************************************************************
2271  * Function:
2272  *   scbq_insert_head
2273  *
2274  * Description:
2275  *   Add an SCB to the head of the list.
2276  *
2277  *-F*************************************************************************/
2278 static inline void
2279 scbq_insert_head(volatile scb_queue_type *queue, struct aic7xxx_scb *scb)
2280 {
2281   scb->q_next = queue->head;
2282   queue->head = scb;
2283   if (queue->tail == NULL)       /* If list was empty, update tail. */
2284     queue->tail = queue->head;
2285 }
2286 
2287 /*+F*************************************************************************
2288  * Function:
2289  *   scbq_remove_head
2290  *
2291  * Description:
2292  *   Remove an SCB from the head of the list.
2293  *
2294  *-F*************************************************************************/
2295 static inline struct aic7xxx_scb *
2296 scbq_remove_head(volatile scb_queue_type *queue)
2297 {
2298   struct aic7xxx_scb * scbp;
2299 
2300   scbp = queue->head;
2301   if (queue->head != NULL)
2302     queue->head = queue->head->q_next;
2303   if (queue->head == NULL)       /* If list is now empty, update tail. */
2304     queue->tail = NULL;
2305   return(scbp);
2306 }
2307 
2308 /*+F*************************************************************************
2309  * Function:
2310  *   scbq_remove
2311  *
2312  * Description:
2313  *   Removes an SCB from the list.
2314  *
2315  *-F*************************************************************************/
2316 static inline void
2317 scbq_remove(volatile scb_queue_type *queue, struct aic7xxx_scb *scb)
2318 {
2319   if (queue->head == scb)
2320   {
2321     /* At beginning of queue, remove from head. */
2322     scbq_remove_head(queue);
2323   }
2324   else
2325   {
2326     struct aic7xxx_scb *curscb = queue->head;
2327 
2328     /*
2329      * Search until the next scb is the one we're looking for, or
2330      * we run out of queue.
2331      */
2332     while ((curscb != NULL) && (curscb->q_next != scb))
2333     {
2334       curscb = curscb->q_next;
2335     }
2336     if (curscb != NULL)
2337     {
2338       /* Found it. */
2339       curscb->q_next = scb->q_next;
2340       if (scb->q_next == NULL)
2341       {
2342         /* Update the tail when removing the tail. */
2343         queue->tail = curscb;
2344       }
2345     }
2346   }
2347 }
2348 
2349 /*+F*************************************************************************
2350  * Function:
2351  *   scbq_insert_tail
2352  *
2353  * Description:
2354  *   Add an SCB at the tail of the list.
2355  *
2356  *-F*************************************************************************/
2357 static inline void
2358 scbq_insert_tail(volatile scb_queue_type *queue, struct aic7xxx_scb *scb)
2359 {
2360   scb->q_next = NULL;
2361   if (queue->tail != NULL)       /* Add the scb at the end of the list. */
2362     queue->tail->q_next = scb;
2363   queue->tail = scb;             /* Update the tail. */
2364   if (queue->head == NULL)       /* If list was empty, update head. */
2365     queue->head = queue->tail;
2366 }
2367 
2368 /*+F*************************************************************************
2369  * Function:
2370  *   aic7xxx_match_scb
2371  *
2372  * Description:
2373  *   Checks to see if an scb matches the target/channel as specified.
2374  *   If target is ALL_TARGETS (-1), then we're looking for any device
2375  *   on the specified channel; this happens when a channel is going
2376  *   to be reset and all devices on that channel must be aborted.
2377  *-F*************************************************************************/
2378 static int
2379 aic7xxx_match_scb(struct aic7xxx_host *p, struct aic7xxx_scb *scb,
2380     int target, int channel, int lun, unsigned char tag)
2381 {
2382   int targ = (scb->hscb->target_channel_lun >> 4) & 0x0F;
2383   int chan = (scb->hscb->target_channel_lun >> 3) & 0x01;
2384   int slun = scb->hscb->target_channel_lun & 0x07;
2385   int match;
2386 
2387   match = ((chan == channel) || (channel == ALL_CHANNELS));
2388   if (match != 0)
2389     match = ((targ == target) || (target == ALL_TARGETS));
2390   if (match != 0)
2391     match = ((lun == slun) || (lun == ALL_LUNS));
2392   if (match != 0)
2393     match = ((tag == scb->hscb->tag) || (tag == SCB_LIST_NULL));
2394 
2395   return (match);
2396 }
2397 
2398 /*+F*************************************************************************
2399  * Function:
2400  *   aic7xxx_add_curscb_to_free_list
2401  *
2402  * Description:
2403  *   Adds the current scb (in SCBPTR) to the list of free SCBs.
2404  *-F*************************************************************************/
2405 static void
2406 aic7xxx_add_curscb_to_free_list(struct aic7xxx_host *p)
2407 {
2408   /*
2409    * Invalidate the tag so that aic7xxx_find_scb doesn't think
2410    * it's active
2411    */
2412   aic_outb(p, SCB_LIST_NULL, SCB_TAG);
2413   aic_outb(p, 0, SCB_CONTROL);
2414 
2415   aic_outb(p, aic_inb(p, FREE_SCBH), SCB_NEXT);
2416   aic_outb(p, aic_inb(p, SCBPTR), FREE_SCBH);
2417 }
2418 
2419 /*+F*************************************************************************
2420  * Function:
2421  *   aic7xxx_rem_scb_from_disc_list
2422  *
2423  * Description:
2424  *   Removes the current SCB from the disconnected list and adds it
2425  *   to the free list.
2426  *-F*************************************************************************/
2427 static unsigned char
2428 aic7xxx_rem_scb_from_disc_list(struct aic7xxx_host *p, unsigned char scbptr,
2429                                unsigned char prev)
2430 {
2431   unsigned char next;
2432 
2433   aic_outb(p, scbptr, SCBPTR);
2434   next = aic_inb(p, SCB_NEXT);
2435   aic7xxx_add_curscb_to_free_list(p);
2436 
2437   if (prev != SCB_LIST_NULL)
2438   {
2439     aic_outb(p, prev, SCBPTR);
2440     aic_outb(p, next, SCB_NEXT);
2441   }
2442   else
2443   {
2444     aic_outb(p, next, DISCONNECTED_SCBH);
2445   }
2446 
2447   return next;
2448 }
2449 
2450 /*+F*************************************************************************
2451  * Function:
2452  *   aic7xxx_busy_target
2453  *
2454  * Description:
2455  *   Set the specified target busy.
2456  *-F*************************************************************************/
2457 static inline void
2458 aic7xxx_busy_target(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
2459 {
2460   p->untagged_scbs[scb->hscb->target_channel_lun] = scb->hscb->tag;
2461 }
2462 
2463 /*+F*************************************************************************
2464  * Function:
2465  *   aic7xxx_index_busy_target
2466  *
2467  * Description:
2468  *   Returns the index of the busy target, and optionally sets the
2469  *   target inactive.
2470  *-F*************************************************************************/
2471 static inline unsigned char
2472 aic7xxx_index_busy_target(struct aic7xxx_host *p, unsigned char tcl,
2473     int unbusy)
2474 {
2475   unsigned char busy_scbid;
2476 
2477   busy_scbid = p->untagged_scbs[tcl];
2478   if (unbusy)
2479   {
2480     p->untagged_scbs[tcl] = SCB_LIST_NULL;
2481   }
2482   return (busy_scbid);
2483 }
2484 
2485 /*+F*************************************************************************
2486  * Function:
2487  *   aic7xxx_find_scb
2488  *
2489  * Description:
2490  *   Look through the SCB array of the card and attempt to find the
2491  *   hardware SCB that corresponds to the passed in SCB.  Return
2492  *   SCB_LIST_NULL if unsuccessful.  This routine assumes that the
2493  *   card is already paused.
2494  *-F*************************************************************************/
2495 static unsigned char
2496 aic7xxx_find_scb(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
2497 {
2498   unsigned char saved_scbptr;
2499   unsigned char curindex;
2500 
2501   saved_scbptr = aic_inb(p, SCBPTR);
2502   curindex = 0;
2503   for (curindex = 0; curindex < p->scb_data->maxhscbs; curindex++)
2504   {
2505     aic_outb(p, curindex, SCBPTR);
2506     if (aic_inb(p, SCB_TAG) == scb->hscb->tag)
2507     {
2508       break;
2509     }
2510   }
2511   aic_outb(p, saved_scbptr, SCBPTR);
2512   if (curindex >= p->scb_data->maxhscbs)
2513   {
2514     curindex = SCB_LIST_NULL;
2515   }
2516 
2517   return (curindex);
2518 }
2519 
2520 /*+F*************************************************************************
2521  * Function:
2522  *   aic7xxx_allocate_scb
2523  *
2524  * Description:
2525  *   Get an SCB from the free list or by allocating a new one.
2526  *-F*************************************************************************/
2527 static int
2528 aic7xxx_allocate_scb(struct aic7xxx_host *p)
2529 {
2530   struct aic7xxx_scb   *scbp = NULL;
2531   int scb_size = (sizeof (struct hw_scatterlist) * AIC7XXX_MAX_SG) + 12 + 6;
2532   int i;
2533   int step = PAGE_SIZE / 1024;
2534   unsigned long scb_count = 0;
2535   struct hw_scatterlist *hsgp;
2536   struct aic7xxx_scb *scb_ap;
2537   struct aic7xxx_scb_dma *scb_dma;
2538   unsigned char *bufs;
2539 
2540   if (p->scb_data->numscbs < p->scb_data->maxscbs)
2541   {
2542     /*
2543      * Calculate the optimal number of SCBs to allocate.
2544      *
2545      * NOTE: This formula works because the sizeof(sg_array) is always
2546      * 1024.  Therefore, scb_size * i would always be > PAGE_SIZE *
2547      * (i/step).  The (i-1) allows the left hand side of the equation
2548      * to grow into the right hand side to a point of near perfect
2549      * efficiency since scb_size * (i -1) is growing slightly faster
2550      * than the right hand side.  If the number of SG array elements
2551      * is changed, this function may not be near so efficient any more.
2552      *
2553      * Since the DMA'able buffers are now allocated in a separate
2554      * chunk this algorithm has been modified to match.  The '12'
2555      * and '6' factors in scb_size are for the DMA'able command byte
2556      * and sensebuffers respectively.  -DaveM
2557      */
2558     for ( i=step;; i *= 2 )
2559     {
2560       if ( (scb_size * (i-1)) >= ( (PAGE_SIZE * (i/step)) - 64 ) )
2561       {
2562         i /= 2;
2563         break;
2564       }
2565     }
2566     scb_count = min( (i-1), p->scb_data->maxscbs - p->scb_data->numscbs);
2567     scb_ap = kmalloc(sizeof (struct aic7xxx_scb) * scb_count
2568                                            + sizeof(struct aic7xxx_scb_dma), GFP_ATOMIC);
2569     if (scb_ap == NULL)
2570       return(0);
2571     scb_dma = (struct aic7xxx_scb_dma *)&scb_ap[scb_count];
2572     hsgp = (struct hw_scatterlist *)
2573       pci_alloc_consistent(p->pdev, scb_size * scb_count,
2574                            &scb_dma->dma_address);
2575     if (hsgp == NULL)
2576     {
2577       kfree(scb_ap);
2578       return(0);
2579     }
2580     bufs = (unsigned char *)&hsgp[scb_count * AIC7XXX_MAX_SG];
2581 #ifdef AIC7XXX_VERBOSE_DEBUGGING
2582     if (aic7xxx_verbose > 0xffff)
2583     {
2584       if (p->scb_data->numscbs == 0)
2585         printk(INFO_LEAD "Allocating initial %ld SCB structures.\n",
2586           p->host_no, -1, -1, -1, scb_count);
2587       else
2588         printk(INFO_LEAD "Allocating %ld additional SCB structures.\n",
2589           p->host_no, -1, -1, -1, scb_count);
2590     }
2591 #endif
2592     memset(scb_ap, 0, sizeof (struct aic7xxx_scb) * scb_count);
2593     scb_dma->dma_offset = (unsigned long)scb_dma->dma_address
2594                           - (unsigned long)hsgp;
2595     scb_dma->dma_len = scb_size * scb_count;
2596     for (i=0; i < scb_count; i++)
2597     {
2598       scbp = &scb_ap[i];
2599       scbp->hscb = &p->scb_data->hscbs[p->scb_data->numscbs];
2600       scbp->sg_list = &hsgp[i * AIC7XXX_MAX_SG];
2601       scbp->sense_cmd = bufs;
2602       scbp->cmnd = bufs + 6;
2603       bufs += 12 + 6;
2604       scbp->scb_dma = scb_dma;
2605       memset(scbp->hscb, 0, sizeof(struct aic7xxx_hwscb));
2606       scbp->hscb->tag = p->scb_data->numscbs;
2607       /*
2608        * Place in the scb array; never is removed
2609        */
2610       p->scb_data->scb_array[p->scb_data->numscbs++] = scbp;
2611       scbq_insert_tail(&p->scb_data->free_scbs, scbp);
2612     }
2613     scbp->kmalloc_ptr = scb_ap;
2614   }
2615   return(scb_count);
2616 }
2617 
2618 /*+F*************************************************************************
2619  * Function:
2620  *   aic7xxx_queue_cmd_complete
2621  *
2622  * Description:
2623  *   Due to race conditions present in the SCSI subsystem, it is easier
2624  *   to queue completed commands, then call scsi_done() on them when
2625  *   we're finished.  This function queues the completed commands.
2626  *-F*************************************************************************/
2627 static void
2628 aic7xxx_queue_cmd_complete(struct aic7xxx_host *p, struct scsi_cmnd *cmd)
2629 {
2630   aic7xxx_position(cmd) = SCB_LIST_NULL;
2631   cmd->host_scribble = (char *)p->completeq.head;
2632   p->completeq.head = cmd;
2633 }
2634 
2635 /*+F*************************************************************************
2636  * Function:
2637  *   aic7xxx_done_cmds_complete
2638  *
2639  * Description:
2640  *   Process the completed command queue.
2641  *-F*************************************************************************/
2642 static void aic7xxx_done_cmds_complete(struct aic7xxx_host *p)
2643 {
2644         struct scsi_cmnd *cmd;
2645 
2646         while (p->completeq.head != NULL) {
2647                 cmd = p->completeq.head;
2648                 p->completeq.head = (struct scsi_cmnd *) cmd->host_scribble;
2649                 cmd->host_scribble = NULL;
2650                 cmd->scsi_done(cmd);
2651         }
2652 }
2653 
2654 /*+F*************************************************************************
2655  * Function:
2656  *   aic7xxx_free_scb
2657  *
2658  * Description:
2659  *   Free the scb and insert into the free scb list.
2660  *-F*************************************************************************/
2661 static void
2662 aic7xxx_free_scb(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
2663 {
2664 
2665   scb->flags = SCB_FREE;
2666   scb->cmd = NULL;
2667   scb->sg_count = 0;
2668   scb->sg_length = 0;
2669   scb->tag_action = 0;
2670   scb->hscb->control = 0;
2671   scb->hscb->target_status = 0;
2672   scb->hscb->target_channel_lun = SCB_LIST_NULL;
2673 
2674   scbq_insert_head(&p->scb_data->free_scbs, scb);
2675 }
2676 
2677 /*+F*************************************************************************
2678  * Function:
2679  *   aic7xxx_done
2680  *
2681  * Description:
2682  *   Calls the higher level scsi done function and frees the scb.
2683  *-F*************************************************************************/
2684 static void
2685 aic7xxx_done(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
2686 {
2687         struct scsi_cmnd *cmd = scb->cmd;
2688         struct aic_dev_data *aic_dev = cmd->device->hostdata;
2689         int tindex = TARGET_INDEX(cmd);
2690         struct aic7xxx_scb *scbp;
2691         unsigned char queue_depth;
2692 
2693         scsi_dma_unmap(cmd);
2694 
2695   if (scb->flags & SCB_SENSE)
2696   {
2697     pci_unmap_single(p->pdev,
2698                      le32_to_cpu(scb->sg_list[0].address),
2699                      SCSI_SENSE_BUFFERSIZE,
2700                      PCI_DMA_FROMDEVICE);
2701   }
2702   if (scb->flags & SCB_RECOVERY_SCB)
2703   {
2704     p->flags &= ~AHC_ABORT_PENDING;
2705   }
2706   if (scb->flags & (SCB_RESET|SCB_ABORT))
2707   {
2708     cmd->result |= (DID_RESET << 16);
2709   }
2710 
2711   if ((scb->flags & SCB_MSGOUT_BITS) != 0)
2712   {
2713     unsigned short mask;
2714     int message_error = FALSE;
2715 
2716     mask = 0x01 << tindex;
2717  
2718     /*
2719      * Check to see if we get an invalid message or a message error
2720      * after failing to negotiate a wide or sync transfer message.
2721      */
2722     if ((scb->flags & SCB_SENSE) && 
2723           ((scb->cmd->sense_buffer[12] == 0x43) ||  /* INVALID_MESSAGE */
2724           (scb->cmd->sense_buffer[12] == 0x49))) /* MESSAGE_ERROR  */
2725     {
2726       message_error = TRUE;
2727     }
2728 
2729     if (scb->flags & SCB_MSGOUT_WDTR)
2730     {
2731       if (message_error)
2732       {
2733         if ( (aic7xxx_verbose & VERBOSE_NEGOTIATION2) &&
2734              (aic_dev->flags & DEVICE_PRINT_DTR) )
2735         {
2736           printk(INFO_LEAD "Device failed to complete Wide Negotiation "
2737             "processing and\n", p->host_no, CTL_OF_SCB(scb));
2738           printk(INFO_LEAD "returned a sense error code for invalid message, "
2739             "disabling future\n", p->host_no, CTL_OF_SCB(scb));
2740           printk(INFO_LEAD "Wide negotiation to this device.\n", p->host_no,
2741             CTL_OF_SCB(scb));
2742         }
2743         aic_dev->needwdtr = aic_dev->needwdtr_copy = 0;
2744       }
2745     }
2746     if (scb->flags & SCB_MSGOUT_SDTR)
2747     {
2748       if (message_error)
2749       {
2750         if ( (aic7xxx_verbose & VERBOSE_NEGOTIATION2) &&
2751              (aic_dev->flags & DEVICE_PRINT_DTR) )
2752         {
2753           printk(INFO_LEAD "Device failed to complete Sync Negotiation "
2754             "processing and\n", p->host_no, CTL_OF_SCB(scb));
2755           printk(INFO_LEAD "returned a sense error code for invalid message, "
2756             "disabling future\n", p->host_no, CTL_OF_SCB(scb));
2757           printk(INFO_LEAD "Sync negotiation to this device.\n", p->host_no,
2758             CTL_OF_SCB(scb));
2759           aic_dev->flags &= ~DEVICE_PRINT_DTR;
2760         }
2761         aic_dev->needsdtr = aic_dev->needsdtr_copy = 0;
2762       }
2763     }
2764     if (scb->flags & SCB_MSGOUT_PPR)
2765     {
2766       if(message_error)
2767       {
2768         if ( (aic7xxx_verbose & VERBOSE_NEGOTIATION2) &&
2769              (aic_dev->flags & DEVICE_PRINT_DTR) )
2770         {
2771           printk(INFO_LEAD "Device failed to complete Parallel Protocol "
2772             "Request processing and\n", p->host_no, CTL_OF_SCB(scb));
2773           printk(INFO_LEAD "returned a sense error code for invalid message, "
2774             "disabling future\n", p->host_no, CTL_OF_SCB(scb));
2775           printk(INFO_LEAD "Parallel Protocol Request negotiation to this "
2776             "device.\n", p->host_no, CTL_OF_SCB(scb));
2777         }
2778         /*
2779          * Disable PPR negotiation and revert back to WDTR and SDTR setup
2780          */
2781         aic_dev->needppr = aic_dev->needppr_copy = 0;
2782         aic_dev->needsdtr = aic_dev->needsdtr_copy = 1;
2783         aic_dev->needwdtr = aic_dev->needwdtr_copy = 1;
2784       }
2785     }
2786   }
2787 
2788   queue_depth = aic_dev->temp_q_depth;
2789   if (queue_depth >= aic_dev->active_cmds)
2790   {
2791     scbp = scbq_remove_head(&aic_dev->delayed_scbs);
2792     if (scbp)
2793     {
2794       if (queue_depth == 1)
2795       {
2796         /*
2797          * Give extra preference to untagged devices, such as CD-R devices
2798          * This makes it more likely that a drive *won't* stuff up while
2799          * waiting on data at a critical time, such as CD-R writing and
2800          * audio CD ripping operations.  Should also benefit tape drives.
2801          */
2802         scbq_insert_head(&p->waiting_scbs, scbp);
2803       }
2804       else
2805       {
2806         scbq_insert_tail(&p->waiting_scbs, scbp);
2807       }
2808 #ifdef AIC7XXX_VERBOSE_DEBUGGING
2809       if (aic7xxx_verbose > 0xffff)
2810         printk(INFO_LEAD "Moving SCB from delayed to waiting queue.\n",
2811                p->host_no, CTL_OF_SCB(scbp));
2812 #endif
2813       if (queue_depth > aic_dev->active_cmds)
2814       {
2815         scbp = scbq_remove_head(&aic_dev->delayed_scbs);
2816         if (scbp)
2817           scbq_insert_tail(&p->waiting_scbs, scbp);
2818       }
2819     }
2820   }
2821   if (!(scb->tag_action))
2822   {
2823     aic7xxx_index_busy_target(p, scb->hscb->target_channel_lun,
2824                               /* unbusy */ TRUE);
2825     if (cmd->device->simple_tags)
2826     {
2827       aic_dev->temp_q_depth = aic_dev->max_q_depth;
2828     }
2829   }
2830   if(scb->flags & SCB_DTR_SCB)
2831   {
2832     aic_dev->dtr_pending = 0;
2833   }
2834   aic_dev->active_cmds--;
2835   p->activescbs--;
2836 
2837   if ((scb->sg_length >= 512) && (((cmd->result >> 16) & 0xf) == DID_OK))
2838   {
2839     long *ptr;
2840     int x, i;
2841 
2842 
2843     if (rq_data_dir(cmd->request) == WRITE)
2844     {
2845       aic_dev->w_total++;
2846       ptr = aic_dev->w_bins;
2847     }
2848     else
2849     {
2850       aic_dev->r_total++;
2851       ptr = aic_dev->r_bins;
2852     }
2853     if(cmd->device->simple_tags && cmd->request->cmd_flags & REQ_HARDBARRIER)
2854     {
2855       aic_dev->barrier_total++;
2856       if(scb->tag_action == MSG_ORDERED_Q_TAG)
2857         aic_dev->ordered_total++;
2858     }
2859     x = scb->sg_length;
2860     x >>= 10;
2861     for(i=0; i<6; i++)
2862     {
2863       x >>= 2;
2864       if(!x) {
2865         ptr[i]++;
2866         break;
2867       }
2868     }
2869     if(i == 6 && x)
2870       ptr[5]++;
2871   }
2872   aic7xxx_free_scb(p, scb);
2873   aic7xxx_queue_cmd_complete(p, cmd);
2874 
2875 }
2876 
2877 /*+F*************************************************************************
2878  * Function:
2879  *   aic7xxx_run_done_queue
2880  *
2881  * Description:
2882  *   Calls the aic7xxx_done() for the scsi_cmnd of each scb in the
2883  *   aborted list, and adds each scb to the free list.  If complete
2884  *   is TRUE, we also process the commands complete list.
2885  *-F*************************************************************************/
2886 static void
2887 aic7xxx_run_done_queue(struct aic7xxx_host *p, /*complete*/ int complete)
2888 {
2889   struct aic7xxx_scb *scb;
2890   int i, found = 0;
2891 
2892   for (i = 0; i < p->scb_data->numscbs; i++)
2893   {
2894     scb = p->scb_data->scb_array[i];
2895     if (scb->flags & SCB_QUEUED_FOR_DONE)
2896     {
2897       if (scb->flags & SCB_QUEUE_FULL)
2898       {
2899         scb->cmd->result = QUEUE_FULL << 1;
2900       }
2901       else
2902       {
2903         if (aic7xxx_verbose & (VERBOSE_ABORT_PROCESS | VERBOSE_RESET_PROCESS))
2904           printk(INFO_LEAD "Aborting scb %d\n",
2905                p->host_no, CTL_OF_SCB(scb), scb->hscb->tag);
2906         /*
2907          * Clear any residual information since the normal aic7xxx_done() path
2908          * doesn't touch the residuals.
2909          */
2910         scb->hscb->residual_SG_segment_count = 0;
2911         scb->hscb->residual_data_count[0] = 0;
2912         scb->hscb->residual_data_count[1] = 0;
2913         scb->hscb->residual_data_count[2] = 0;
2914       }
2915       found++;
2916       aic7xxx_done(p, scb);
2917     }
2918   }
2919   if (aic7xxx_verbose & (VERBOSE_ABORT_RETURN | VERBOSE_RESET_RETURN))
2920   {
2921     printk(INFO_LEAD "%d commands found and queued for "
2922         "completion.\n", p->host_no, -1, -1, -1, found);
2923   }
2924   if (complete)
2925   {
2926     aic7xxx_done_cmds_complete(p);
2927   }
2928 }
2929 
2930 /*+F*************************************************************************
2931  * Function:
2932  *   aic7xxx_abort_waiting_scb
2933  *
2934  * Description:
2935  *   Manipulate the waiting for selection list and return the
2936  *   scb that follows the one that we remove.
2937  *-F*************************************************************************/
2938 static unsigned char
2939 aic7xxx_abort_waiting_scb(struct aic7xxx_host *p, struct aic7xxx_scb *scb,
2940     unsigned char scbpos, unsigned char prev)
2941 {
2942   unsigned char curscb, next;
2943 
2944   /*
2945    * Select the SCB we want to abort and pull the next pointer out of it.
2946    */
2947   curscb = aic_inb(p, SCBPTR);
2948   aic_outb(p, scbpos, SCBPTR);
2949   next = aic_inb(p, SCB_NEXT);
2950 
2951   aic7xxx_add_curscb_to_free_list(p);
2952 
2953   /*
2954    * Update the waiting list
2955    */
2956   if (prev == SCB_LIST_NULL)
2957   {
2958     /*
2959      * First in the list
2960      */
2961     aic_outb(p, next, WAITING_SCBH);
2962   }
2963   else
2964   {
2965     /*
2966      * Select the scb that pointed to us and update its next pointer.
2967      */
2968     aic_outb(p, prev, SCBPTR);
2969     aic_outb(p, next, SCB_NEXT);
2970   }
2971   /*
2972    * Point us back at the original scb position and inform the SCSI
2973    * system that the command has been aborted.
2974    */
2975   aic_outb(p, curscb, SCBPTR);
2976   return (next);
2977 }
2978 
2979 /*+F*************************************************************************
2980  * Function:
2981  *   aic7xxx_search_qinfifo
2982  *
2983  * Description:
2984  *   Search the queue-in FIFO for matching SCBs and conditionally
2985  *   requeue.  Returns the number of matching SCBs.
2986  *-F*************************************************************************/
2987 static int
2988 aic7xxx_search_qinfifo(struct aic7xxx_host *p, int target, int channel,
2989     int lun, unsigned char tag, int flags, int requeue,
2990     volatile scb_queue_type *queue)
2991 {
2992   int      found;
2993   unsigned char qinpos, qintail;
2994   struct aic7xxx_scb *scbp;
2995 
2996   found = 0;
2997   qinpos = aic_inb(p, QINPOS);
2998   qintail = p->qinfifonext;
2999 
3000   p->qinfifonext = qinpos;
3001 
3002   while (qinpos != qintail)
3003   {
3004     scbp = p->scb_data->scb_array[p->qinfifo[qinpos++]];
3005     if (aic7xxx_match_scb(p, scbp, target, channel, lun, tag))
3006     {
3007        /*
3008         * We found an scb that needs to be removed.
3009         */
3010        if (requeue && (queue != NULL))
3011        {
3012          if (scbp->flags & SCB_WAITINGQ)
3013          {
3014            scbq_remove(queue, scbp);
3015            scbq_remove(&p->waiting_scbs, scbp);
3016            scbq_remove(&AIC_DEV(scbp->cmd)->delayed_scbs, scbp);
3017            AIC_DEV(scbp->cmd)->active_cmds++;
3018            p->activescbs++;
3019          }
3020          scbq_insert_tail(queue, scbp);
3021          AIC_DEV(scbp->cmd)->active_cmds--;
3022          p->activescbs--;
3023          scbp->flags |= SCB_WAITINGQ;
3024          if ( !(scbp->tag_action & TAG_ENB) )
3025          {
3026            aic7xxx_index_busy_target(p, scbp->hscb->target_channel_lun,
3027              TRUE);
3028          }
3029        }
3030        else if (requeue)
3031        {
3032          p->qinfifo[p->qinfifonext++] = scbp->hscb->tag;
3033        }
3034        else
3035        {
3036         /*
3037          * Preserve any SCB_RECOVERY_SCB flags on this scb then set the
3038          * flags we were called with, presumeably so aic7xxx_run_done_queue
3039          * can find this scb
3040          */
3041          scbp->flags = flags | (scbp->flags & SCB_RECOVERY_SCB);
3042          if (aic7xxx_index_busy_target(p, scbp->hscb->target_channel_lun,
3043                                        FALSE) == scbp->hscb->tag)
3044          {
3045            aic7xxx_index_busy_target(p, scbp->hscb->target_channel_lun,
3046              TRUE);
3047          }
3048        }
3049        found++;
3050     }
3051     else
3052     {
3053       p->qinfifo[p->qinfifonext++] = scbp->hscb->tag;
3054     }
3055   }
3056   /*
3057    * Now that we've done the work, clear out any left over commands in the
3058    * qinfifo and update the KERNEL_QINPOS down on the card.
3059    *
3060    *  NOTE: This routine expect the sequencer to already be paused when
3061    *        it is run....make sure it's that way!
3062    */
3063   qinpos = p->qinfifonext;
3064   while(qinpos != qintail)
3065   {
3066     p->qinfifo[qinpos++] = SCB_LIST_NULL;
3067   }
3068   if (p->features & AHC_QUEUE_REGS)
3069     aic_outb(p, p->qinfifonext, HNSCB_QOFF);
3070   else
3071     aic_outb(p, p->qinfifonext, KERNEL_QINPOS);
3072 
3073   return (found);
3074 }
3075 
3076 /*+F*************************************************************************
3077  * Function:
3078  *   aic7xxx_scb_on_qoutfifo
3079  *
3080  * Description:
3081  *   Is the scb that was passed to us currently on the qoutfifo?
3082  *-F*************************************************************************/
3083 static int
3084 aic7xxx_scb_on_qoutfifo(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
3085 {
3086   int i=0;
3087 
3088   while(p->qoutfifo[(p->qoutfifonext + i) & 0xff ] != SCB_LIST_NULL)
3089   {
3090     if(p->qoutfifo[(p->qoutfifonext + i) & 0xff ] == scb->hscb->tag)
3091       return TRUE;
3092     else
3093       i++;
3094   }
3095   return FALSE;
3096 }
3097 
3098 
3099 /*+F*************************************************************************
3100  * Function:
3101  *   aic7xxx_reset_device
3102  *
3103  * Description:
3104  *   The device at the given target/channel has been reset.  Abort
3105  *   all active and queued scbs for that target/channel.  This function
3106  *   need not worry about linked next pointers because if was a MSG_ABORT_TAG
3107  *   then we had a tagged command (no linked next), if it was MSG_ABORT or
3108  *   MSG_BUS_DEV_RESET then the device won't know about any commands any more
3109  *   and no busy commands will exist, and if it was a bus reset, then nothing
3110  *   knows about any linked next commands any more.  In all cases, we don't
3111  *   need to worry about the linked next or busy scb, we just need to clear
3112  *   them.
3113  *-F*************************************************************************/
3114 static void
3115 aic7xxx_reset_device(struct aic7xxx_host *p, int target, int channel,
3116                      int lun, unsigned char tag)
3117 {
3118   struct aic7xxx_scb *scbp, *prev_scbp;
3119   struct scsi_device *sd;
3120   unsigned char active_scb, tcl, scb_tag;
3121   int i = 0, init_lists = FALSE;
3122   struct aic_dev_data *aic_dev;
3123 
3124   /*
3125    * Restore this when we're done
3126    */
3127   active_scb = aic_inb(p, SCBPTR);
3128   scb_tag = aic_inb(p, SCB_TAG);
3129 
3130   if (aic7xxx_verbose & (VERBOSE_RESET_PROCESS | VERBOSE_ABORT_PROCESS))
3131   {
3132     printk(INFO_LEAD "Reset device, hardware_scb %d,\n",
3133          p->host_no, channel, target, lun, active_scb);
3134     printk(INFO_LEAD "Current scb %d, SEQADDR 0x%x, LASTPHASE "
3135            "0x%x\n",
3136          p->host_no, channel, target, lun, scb_tag,
3137          aic_inb(p, SEQADDR0) | (aic_inb(p, SEQADDR1) << 8),
3138          aic_inb(p, LASTPHASE));
3139     printk(INFO_LEAD "SG_CACHEPTR 0x%x, SG_COUNT %d, SCSISIGI 0x%x\n",
3140          p->host_no, channel, target, lun,
3141          (p->features & AHC_ULTRA2) ?  aic_inb(p, SG_CACHEPTR) : 0,
3142          aic_inb(p, SG_COUNT), aic_inb(p, SCSISIGI));
3143     printk(INFO_LEAD "SSTAT0 0x%x, SSTAT1 0x%x, SSTAT2 0x%x\n",
3144          p->host_no, channel, target, lun, aic_inb(p, SSTAT0),
3145          aic_inb(p, SSTAT1), aic_inb(p, SSTAT2));
3146   }
3147 
3148   /*
3149    * Deal with the busy target and linked next issues.
3150    */
3151   list_for_each_entry(aic_dev, &p->aic_devs, list)
3152   {
3153     if (aic7xxx_verbose & (VERBOSE_RESET_PROCESS | VERBOSE_ABORT_PROCESS))
3154       printk(INFO_LEAD "processing aic_dev %p\n", p->host_no, channel, target,
3155                     lun, aic_dev);
3156     sd = aic_dev->SDptr;
3157 
3158     if((target != ALL_TARGETS && target != sd->id) ||
3159        (channel != ALL_CHANNELS && channel != sd->channel))
3160       continue;
3161     if (aic7xxx_verbose & (VERBOSE_ABORT_PROCESS | VERBOSE_RESET_PROCESS))
3162         printk(INFO_LEAD "Cleaning up status information "
3163           "and delayed_scbs.\n", p->host_no, sd->channel, sd->id, sd->lun);
3164     aic_dev->flags &= ~BUS_DEVICE_RESET_PENDING;
3165     if ( tag == SCB_LIST_NULL )
3166     {
3167       aic_dev->dtr_pending = 0;
3168       aic_dev->needppr = aic_dev->needppr_copy;
3169       aic_dev->needsdtr = aic_dev->needsdtr_copy;
3170       aic_dev->needwdtr = aic_dev->needwdtr_copy;
3171       aic_dev->flags = DEVICE_PRINT_DTR;
3172       aic_dev->temp_q_depth = aic_dev->max_q_depth;
3173     }
3174     tcl = (sd->id << 4) | (sd->channel << 3) | sd->lun;
3175     if ( (aic7xxx_index_busy_target(p, tcl, FALSE) == tag) ||
3176          (tag == SCB_LIST_NULL) )
3177       aic7xxx_index_busy_target(p, tcl, /* unbusy */ TRUE);
3178     prev_scbp = NULL; 
3179     scbp = aic_dev->delayed_scbs.head;
3180     while (scbp != NULL)
3181     {
3182       prev_scbp = scbp;
3183       scbp = scbp->q_next;
3184       if (aic7xxx_match_scb(p, prev_scbp, target, channel, lun, tag))
3185       {
3186         scbq_remove(&aic_dev->delayed_scbs, prev_scbp);
3187         if (prev_scbp->flags & SCB_WAITINGQ)
3188         {
3189           aic_dev->active_cmds++;
3190           p->activescbs++;
3191         }
3192         prev_scbp->flags &= ~(SCB_ACTIVE | SCB_WAITINGQ);
3193         prev_scbp->flags |= SCB_RESET | SCB_QUEUED_FOR_DONE;
3194       }
3195     }
3196   }
3197 
3198   if (aic7xxx_verbose & (VERBOSE_ABORT_PROCESS | VERBOSE_RESET_PROCESS))
3199     printk(INFO_LEAD "Cleaning QINFIFO.\n", p->host_no, channel, target, lun );
3200   aic7xxx_search_qinfifo(p, target, channel, lun, tag,
3201       SCB_RESET | SCB_QUEUED_FOR_DONE, /* requeue */ FALSE, NULL);
3202 
3203 /*
3204  *  Search the waiting_scbs queue for matches, this catches any SCB_QUEUED
3205  *  ABORT/RESET commands.
3206  */
3207   if (aic7xxx_verbose & (VERBOSE_ABORT_PROCESS | VERBOSE_RESET_PROCESS))
3208     printk(INFO_LEAD "Cleaning waiting_scbs.\n", p->host_no, channel,
3209       target, lun );
3210   {
3211     struct aic7xxx_scb *scbp, *prev_scbp;
3212 
3213     prev_scbp = NULL; 
3214     scbp = p->waiting_scbs.head;
3215     while (scbp != NULL)
3216     {
3217       prev_scbp = scbp;
3218       scbp = scbp->q_next;
3219       if (aic7xxx_match_scb(p, prev_scbp, target, channel, lun, tag))
3220       {
3221         scbq_remove(&p->waiting_scbs, prev_scbp);
3222         if (prev_scbp->flags & SCB_WAITINGQ)
3223         {
3224           AIC_DEV(prev_scbp->cmd)->active_cmds++;
3225           p->activescbs++;
3226         }
3227         prev_scbp->flags &= ~(SCB_ACTIVE | SCB_WAITINGQ);
3228         prev_scbp->flags |= SCB_RESET | SCB_QUEUED_FOR_DONE;
3229       }
3230     }
3231   }
3232 
3233 
3234   /*
3235    * Search waiting for selection list.
3236    */
3237   if (aic7xxx_verbose & (VERBOSE_ABORT_PROCESS | VERBOSE_RESET_PROCESS))
3238     printk(INFO_LEAD "Cleaning waiting for selection "
3239       "list.\n", p->host_no, channel, target, lun);
3240   {
3241     unsigned char next, prev, scb_index;
3242 
3243     next = aic_inb(p, WAITING_SCBH);  /* Start at head of list. */
3244     prev = SCB_LIST_NULL;
3245     while (next != SCB_LIST_NULL)
3246     {
3247       aic_outb(p, next, SCBPTR);
3248       scb_index = aic_inb(p, SCB_TAG);
3249       if (scb_index >= p->scb_data->numscbs)
3250       {
3251        /*
3252         * No aic7xxx_verbose check here.....we want to see this since it
3253         * means either the kernel driver or the sequencer screwed things up
3254         */
3255         printk(WARN_LEAD "Waiting List inconsistency; SCB index=%d, "
3256           "numscbs=%d\n", p->host_no, channel, target, lun, scb_index,
3257           p->scb_data->numscbs);
3258         next = aic_inb(p, SCB_NEXT);
3259         aic7xxx_add_curscb_to_free_list(p);
3260       }
3261       else
3262       {
3263         scbp = p->scb_data->scb_array[scb_index];
3264         if (aic7xxx_match_scb(p, scbp, target, channel, lun, tag))
3265         {
3266           next = aic7xxx_abort_waiting_scb(p, scbp, next, prev);
3267           if (scbp->flags & SCB_WAITINGQ)
3268           {
3269             AIC_DEV(scbp->cmd)->active_cmds++;
3270             p->activescbs++;
3271           }
3272           scbp->flags &= ~(SCB_ACTIVE | SCB_WAITINGQ);
3273           scbp->flags |= SCB_RESET | SCB_QUEUED_FOR_DONE;
3274           if (prev == SCB_LIST_NULL)
3275           {
3276             /*
3277              * This is either the first scb on the waiting list, or we
3278              * have already yanked the first and haven't left any behind.
3279              * Either way, we need to turn off the selection hardware if
3280              * it isn't already off.
3281              */
3282             aic_outb(p, aic_inb(p, SCSISEQ) & ~ENSELO, SCSISEQ);
3283             aic_outb(p, CLRSELTIMEO, CLRSINT1);
3284           }
3285         }
3286         else
3287         {
3288           prev = next;
3289           next = aic_inb(p, SCB_NEXT);
3290         }
3291       }
3292     }
3293   }
3294 
3295   /*
3296    * Go through disconnected list and remove any entries we have queued
3297    * for completion, zeroing their control byte too.
3298    */
3299   if (aic7xxx_verbose & (VERBOSE_ABORT_PROCESS | VERBOSE_RESET_PROCESS))
3300     printk(INFO_LEAD "Cleaning disconnected scbs "
3301       "list.\n", p->host_no, channel, target, lun);
3302   if (p->flags & AHC_PAGESCBS)
3303   {
3304     unsigned char next, prev, scb_index;
3305 
3306     next = aic_inb(p, DISCONNECTED_SCBH);
3307     prev = SCB_LIST_NULL;
3308     while (next != SCB_LIST_NULL)
3309     {
3310       aic_outb(p, next, SCBPTR);
3311       scb_index = aic_inb(p, SCB_TAG);
3312       if (scb_index > p->scb_data->numscbs)
3313       {
3314         printk(WARN_LEAD "Disconnected List inconsistency; SCB index=%d, "
3315           "numscbs=%d\n", p->host_no, channel, target, lun, scb_index,
3316           p->scb_data->numscbs);
3317         next = aic7xxx_rem_scb_from_disc_list(p, next, prev);
3318       }
3319       else
3320       {
3321         scbp = p->scb_data->scb_array[scb_index];
3322         if (aic7xxx_match_scb(p, scbp, target, channel, lun, tag))
3323         {
3324           next = aic7xxx_rem_scb_from_disc_list(p, next, prev);
3325           if (scbp->flags & SCB_WAITINGQ)
3326           {
3327             AIC_DEV(scbp->cmd)->active_cmds++;
3328             p->activescbs++;
3329           }
3330           scbp->flags &= ~(SCB_ACTIVE | SCB_WAITINGQ);
3331           scbp->flags |= SCB_RESET | SCB_QUEUED_FOR_DONE;
3332           scbp->hscb->control = 0;
3333         }
3334         else
3335         {
3336           prev = next;
3337           next = aic_inb(p, SCB_NEXT);
3338         }
3339       }
3340     }
3341   }
3342 
3343   /*
3344    * Walk the free list making sure no entries on the free list have
3345    * a valid SCB_TAG value or SCB_CONTROL byte.
3346    */
3347   if (p->flags & AHC_PAGESCBS)
3348   {
3349     unsigned char next;
3350 
3351     next = aic_inb(p, FREE_SCBH);
3352     while (next != SCB_LIST_NULL)
3353     {
3354       aic_outb(p, next, SCBPTR);
3355       if (aic_inb(p, SCB_TAG) < p->scb_data->numscbs)
3356       {
3357         printk(WARN_LEAD "Free list inconsistency!.\n", p->host_no, channel,
3358           target, lun);
3359         init_lists = TRUE;
3360         next = SCB_LIST_NULL;
3361       }
3362       else
3363       {
3364         aic_outb(p, SCB_LIST_NULL, SCB_TAG);
3365         aic_outb(p, 0, SCB_CONTROL);
3366         next = aic_inb(p, SCB_NEXT);
3367       }
3368     }
3369   }
3370 
3371   /*
3372    * Go through the hardware SCB array looking for commands that
3373    * were active but not on any list.
3374    */
3375   if (init_lists)
3376   {
3377     aic_outb(p, SCB_LIST_NULL, FREE_SCBH);
3378     aic_outb(p, SCB_LIST_NULL, WAITING_SCBH);
3379     aic_outb(p, SCB_LIST_NULL, DISCONNECTED_SCBH);
3380   }
3381   for (i = p->scb_data->maxhscbs - 1; i >= 0; i--)
3382   {
3383     unsigned char scbid;
3384 
3385     aic_outb(p, i, SCBPTR);
3386     if (init_lists)
3387     {
3388       aic_outb(p, SCB_LIST_NULL, SCB_TAG);
3389       aic_outb(p, SCB_LIST_NULL, SCB_NEXT);
3390       aic_outb(p, 0, SCB_CONTROL);
3391       aic7xxx_add_curscb_to_free_list(p);
3392     }
3393     else
3394     {
3395       scbid = aic_inb(p, SCB_TAG);
3396       if (scbid < p->scb_data->numscbs)
3397       {
3398         scbp = p->scb_data->scb_array[scbid];
3399         if (aic7xxx_match_scb(p, scbp, target, channel, lun, tag))
3400         {
3401           aic_outb(p, 0, SCB_CONTROL);
3402           aic_outb(p, SCB_LIST_NULL, SCB_TAG);
3403           aic7xxx_add_curscb_to_free_list(p);
3404         }
3405       }
3406     }
3407   }
3408 
3409   /*
3410    * Go through the entire SCB array now and look for commands for
3411    * for this target that are stillactive.  These are other (most likely
3412    * tagged) commands that were disconnected when the reset occurred.
3413    * Any commands we find here we know this about, it wasn't on any queue,
3414    * it wasn't in the qinfifo, it wasn't in the disconnected or waiting
3415    * lists, so it really must have been a paged out SCB.  In that case,
3416    * we shouldn't need to bother with updating any counters, just mark
3417    * the correct flags and go on.
3418    */
3419   for (i = 0; i < p->scb_data->numscbs; i++)
3420   {
3421     scbp = p->scb_data->scb_array[i];
3422     if ((scbp->flags & SCB_ACTIVE) &&
3423         aic7xxx_match_scb(p, scbp, target, channel, lun, tag) &&
3424         !aic7xxx_scb_on_qoutfifo(p, scbp))
3425     {
3426       if (scbp->flags & SCB_WAITINGQ)
3427       {
3428         scbq_remove(&p->waiting_scbs, scbp);
3429         scbq_remove(&AIC_DEV(scbp->cmd)->delayed_scbs, scbp);
3430         AIC_DEV(scbp->cmd)->active_cmds++;
3431         p->activescbs++;
3432       }
3433       scbp->flags |= SCB_RESET | SCB_QUEUED_FOR_DONE;
3434       scbp->flags &= ~(SCB_ACTIVE | SCB_WAITINGQ);
3435     }
3436   }
3437 
3438   aic_outb(p, active_scb, SCBPTR);
3439 }
3440 
3441 
3442 /*+F*************************************************************************
3443  * Function:
3444  *   aic7xxx_clear_intstat
3445  *
3446  * Description:
3447  *   Clears the interrupt status.
3448  *-F*************************************************************************/
3449 static void
3450 aic7xxx_clear_intstat(struct aic7xxx_host *p)
3451 {
3452   /* Clear any interrupt conditions this may have caused. */
3453   aic_outb(p, CLRSELDO | CLRSELDI | CLRSELINGO, CLRSINT0);
3454   aic_outb(p, CLRSELTIMEO | CLRATNO | CLRSCSIRSTI | CLRBUSFREE | CLRSCSIPERR |
3455        CLRPHASECHG | CLRREQINIT, CLRSINT1);
3456   aic_outb(p, CLRSCSIINT | CLRSEQINT | CLRBRKADRINT | CLRPARERR, CLRINT);
3457 }
3458 
3459 /*+F*************************************************************************
3460  * Function:
3461  *   aic7xxx_reset_current_bus
3462  *
3463  * Description:
3464  *   Reset the current SCSI bus.
3465  *-F*************************************************************************/
3466 static void
3467 aic7xxx_reset_current_bus(struct aic7xxx_host *p)
3468 {
3469 
3470   /* Disable reset interrupts. */
3471   aic_outb(p, aic_inb(p, SIMODE1) & ~ENSCSIRST, SIMODE1);
3472 
3473   /* Turn off the bus' current operations, after all, we shouldn't have any
3474    * valid commands left to cause a RSELI and SELO once we've tossed the
3475    * bus away with this reset, so we might as well shut down the sequencer
3476    * until the bus is restarted as oppossed to saving the current settings
3477    * and restoring them (which makes no sense to me). */
3478 
3479   /* Turn on the bus reset. */
3480   aic_outb(p, aic_inb(p, SCSISEQ) | SCSIRSTO, SCSISEQ);
3481   while ( (aic_inb(p, SCSISEQ) & SCSIRSTO) == 0)
3482     mdelay(5);
3483 
3484   /*
3485    * Some of the new Ultra2 chipsets need a longer delay after a chip
3486    * reset than just the init setup creates, so we have to delay here
3487    * before we go into a reset in order to make the chips happy.
3488    */
3489   if (p->features & AHC_ULTRA2)
3490     mdelay(250);
3491   else
3492     mdelay(50);
3493 
3494   /* Turn off the bus reset. */
3495   aic_outb(p, 0, SCSISEQ);
3496   mdelay(10);
3497 
3498   aic7xxx_clear_intstat(p);
3499   /* Re-enable reset interrupts. */
3500   aic_outb(p, aic_inb(p, SIMODE1) | ENSCSIRST, SIMODE1);
3501 
3502 }
3503 
3504 /*+F*************************************************************************
3505  * Function:
3506  *   aic7xxx_reset_channel
3507  *
3508  * Description:
3509  *   Reset the channel.
3510  *-F*************************************************************************/
3511 static void
3512 aic7xxx_reset_channel(struct aic7xxx_host *p, int channel, int initiate_reset)
3513 {
3514   unsigned long offset_min, offset_max;
3515   unsigned char sblkctl;
3516   int cur_channel;
3517 
3518   if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
3519     printk(INFO_LEAD "Reset channel called, %s initiate reset.\n",
3520       p->host_no, channel, -1, -1, (initiate_reset==TRUE) ? "will" : "won't" );
3521 
3522 
3523   if (channel == 1)
3524   {
3525     offset_min = 8;
3526     offset_max = 16;
3527   }
3528   else
3529   {
3530     if (p->features & AHC_TWIN)
3531     {
3532       /* Channel A */
3533       offset_min = 0;
3534       offset_max = 8;
3535     }
3536     else
3537     {
3538       offset_min = 0;
3539       if (p->features & AHC_WIDE)
3540       {
3541         offset_max = 16;
3542       }
3543       else
3544       {
3545         offset_max = 8;
3546       }
3547     }
3548   }
3549 
3550   while (offset_min < offset_max)
3551   {
3552     /*
3553      * Revert to async/narrow transfers until we renegotiate.
3554      */
3555     aic_outb(p, 0, TARG_SCSIRATE + offset_min);
3556     if (p->features & AHC_ULTRA2)
3557     {
3558       aic_outb(p, 0, TARG_OFFSET + offset_min);
3559     }
3560     offset_min++;
3561   }
3562 
3563   /*
3564    * Reset the bus and unpause/restart the controller
3565    */
3566   sblkctl = aic_inb(p, SBLKCTL);
3567   if ( (p->chip & AHC_CHIPID_MASK) == AHC_AIC7770 )
3568     cur_channel = (sblkctl & SELBUSB) >> 3;
3569   else
3570     cur_channel = 0;
3571   if ( (cur_channel != channel) && (p->features & AHC_TWIN) )
3572   {
3573     /*
3574      * Case 1: Command for another bus is active
3575      */
3576     if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
3577       printk(INFO_LEAD "Stealthily resetting idle channel.\n", p->host_no,
3578         channel, -1, -1);
3579     /*
3580      * Stealthily reset the other bus without upsetting the current bus.
3581      */
3582     aic_outb(p, sblkctl ^ SELBUSB, SBLKCTL);
3583     aic_outb(p, aic_inb(p, SIMODE1) & ~ENBUSFREE, SIMODE1);
3584     if (initiate_reset)
3585     {
3586       aic7xxx_reset_current_bus(p);
3587     }
3588     aic_outb(p, aic_inb(p, SCSISEQ) & (ENSELI|ENRSELI|ENAUTOATNP), SCSISEQ);
3589     aic7xxx_clear_intstat(p);
3590     aic_outb(p, sblkctl, SBLKCTL);
3591   }
3592   else
3593   {
3594     /*
3595      * Case 2: A command from this bus is active or we're idle.
3596      */
3597     if (aic7xxx_verbose & VERBOSE_RESET_PROCESS)
3598       printk(INFO_LEAD "Resetting currently active channel.\n", p->host_no,
3599         channel, -1, -1);
3600     aic_outb(p, aic_inb(p, SIMODE1) & ~(ENBUSFREE|ENREQINIT),
3601       SIMODE1);
3602     p->flags &= ~AHC_HANDLING_REQINITS;
3603     p->msg_type = MSG_TYPE_NONE;
3604     p->msg_len = 0;
3605     if (initiate_reset)
3606     {
3607       aic7xxx_reset_current_bus(p);
3608     }
3609     aic_outb(p, aic_inb(p, SCSISEQ) & (ENSELI|ENRSELI|ENAUTOATNP), SCSISEQ);
3610     aic7xxx_clear_intstat(p);
3611   }
3612   if (aic7xxx_verbose & VERBOSE_RESET_RETURN)
3613     printk(INFO_LEAD "Channel reset\n", p->host_no, channel, -1, -1);
3614   /*
3615    * Clean up all the state information for the pending transactions
3616    * on this bus.
3617    */
3618   aic7xxx_reset_device(p, ALL_TARGETS, channel, ALL_LUNS, SCB_LIST_NULL);
3619 
3620   if ( !(p->features & AHC_TWIN) )
3621   {
3622     restart_sequencer(p);
3623   }
3624 
3625   return;
3626 }
3627 
3628 /*+F*************************************************************************
3629  * Function:
3630  *   aic7xxx_run_waiting_queues
3631  *
3632  * Description:
3633  *   Scan the awaiting_scbs queue downloading and starting as many
3634  *   scbs as we can.
3635  *-F*************************************************************************/
3636 static void
3637 aic7xxx_run_waiting_queues(struct aic7xxx_host *p)
3638 {
3639   struct aic7xxx_scb *scb;
3640   struct aic_dev_data *aic_dev;
3641   int sent;
3642 
3643 
3644   if (p->waiting_scbs.head == NULL)
3645     return;
3646 
3647   sent = 0;
3648 
3649   /*
3650    * First handle SCBs that are waiting but have been assigned a slot.
3651    */
3652   while ((scb = scbq_remove_head(&p->waiting_scbs)) != NULL)
3653   {
3654     aic_dev = scb->cmd->device->hostdata;
3655     if ( !scb->tag_action )
3656     {
3657       aic_dev->temp_q_depth = 1;
3658     }
3659     if ( aic_dev->active_cmds >= aic_dev->temp_q_depth)
3660     {
3661       scbq_insert_tail(&aic_dev->delayed_scbs, scb);
3662     }
3663     else
3664     {
3665         scb->flags &= ~SCB_WAITINGQ;
3666         aic_dev->active_cmds++;
3667         p->activescbs++;
3668         if ( !(scb->tag_action) )
3669         {
3670           aic7xxx_busy_target(p, scb);
3671         }
3672         p->qinfifo[p->qinfifonext++] = scb->hscb->tag;
3673         sent++;
3674     }
3675   }
3676   if (sent)
3677   {
3678     if (p->features & AHC_QUEUE_REGS)
3679       aic_outb(p, p->qinfifonext, HNSCB_QOFF);
3680     else
3681     {
3682       pause_sequencer(p);
3683       aic_outb(p, p->qinfifonext, KERNEL_QINPOS);
3684       unpause_sequencer(p, FALSE);
3685     }
3686     if (p->activescbs > p->max_activescbs)
3687       p->max_activescbs = p->activescbs;
3688   }
3689 }
3690 
3691 #ifdef CONFIG_PCI
3692 
3693 #define  DPE 0x80
3694 #define  SSE 0x40
3695 #define  RMA 0x20
3696 #define  RTA 0x10
3697 #define  STA 0x08
3698 #define  DPR 0x01
3699 
3700 /*+F*************************************************************************
3701  * Function:
3702  *   aic7xxx_pci_intr
3703  *
3704  * Description:
3705  *   Check the scsi card for PCI errors and clear the interrupt
3706  *
3707  *   NOTE: If you don't have this function and a 2940 card encounters
3708  *         a PCI error condition, the machine will end up locked as the
3709  *         interrupt handler gets slammed with non-stop PCI error interrupts
3710  *-F*************************************************************************/
3711 static void
3712 aic7xxx_pci_intr(struct aic7xxx_host *p)
3713 {
3714   unsigned char status1;
3715 
3716   pci_read_config_byte(p->pdev, PCI_STATUS + 1, &status1);
3717 
3718   if ( (status1 & DPE) && (aic7xxx_verbose & VERBOSE_MINOR_ERROR) )
3719     printk(WARN_LEAD "Data Parity Error during PCI address or PCI write"
3720       "phase.\n", p->host_no, -1, -1, -1);
3721   if ( (status1 & SSE) && (aic7xxx_verbose & VERBOSE_MINOR_ERROR) )
3722     printk(WARN_LEAD "Signal System Error Detected\n", p->host_no,
3723       -1, -1, -1);
3724   if ( (status1 & RMA) && (aic7xxx_verbose & VERBOSE_MINOR_ERROR) )
3725     printk(WARN_LEAD "Received a PCI Master Abort\n", p->host_no,
3726       -1, -1, -1);
3727   if ( (status1 & RTA) && (aic7xxx_verbose & VERBOSE_MINOR_ERROR) )
3728     printk(WARN_LEAD "Received a PCI Target Abort\n", p->host_no,
3729       -1, -1, -1);
3730   if ( (status1 & STA) && (aic7xxx_verbose & VERBOSE_MINOR_ERROR) )
3731     printk(WARN_LEAD "Signaled a PCI Target Abort\n", p->host_no,
3732       -1, -1, -1);
3733   if ( (status1 & DPR) && (aic7xxx_verbose & VERBOSE_MINOR_ERROR) )
3734     printk(WARN_LEAD "Data Parity Error has been reported via PCI pin "
3735       "PERR#\n", p->host_no, -1, -1, -1);
3736   
3737   pci_write_config_byte(p->pdev, PCI_STATUS + 1, status1);
3738   if (status1 & (DPR|RMA|RTA))
3739     aic_outb(p,  CLRPARERR, CLRINT);
3740 
3741   if ( (aic7xxx_panic_on_abort) && (p->spurious_int > 500) )
3742     aic7xxx_panic_abort(p, NULL);
3743 
3744 }
3745 #endif /* CONFIG_PCI */
3746 
3747 /*+F*************************************************************************
3748  * Function:
3749  *   aic7xxx_construct_ppr
3750  *
3751  * Description:
3752  *   Build up a Parallel Protocol Request message for use with SCSI-3
3753  *   devices.
3754  *-F*************************************************************************/
3755 static void
3756 aic7xxx_construct_ppr(struct aic7xxx_host *p, struct aic7xxx_scb *scb)
3757 {
3758   p->msg_buf[p->msg_index++] = MSG_EXTENDED;
3759   p->msg_buf[p->msg_index++] = MSG_EXT_PPR_LEN;
3760   p->msg_buf[p->msg_index++] = MSG_EXT_PPR;
3761   p->msg_buf[p->msg_index++] = AIC_DEV(scb->cmd)->goal.period;
3762   p->msg_buf[p->msg_index++] = 0;
3763   p->msg_buf[p->msg_index++] = AIC_DEV(scb->cmd)->goal.offset;
3764   p->msg_buf[p->msg_index++] = AIC_DEV(scb->cmd)->goal.width;
3765   p->msg_buf[p->msg_index++] = AIC_DEV(scb->cmd)->goal.options;
3766   p->msg_len += 8;
3767 }
3768 
3769 /*+F*************************************************************************
3770  * Function:
3771  *   aic7xxx_construct_sdtr
3772  *
3773  * Description:
3774  *   Constucts a synchronous data transfer message in the message
3775  *   buffer on the sequencer.
3776  *-F*************************************************************************/
3777 static void
3778 aic7xxx_construct_sdtr(struct aic7xxx_host *p, unsigned char period,
3779         unsigned char offset)
3780 {
3781   p->msg_buf[p->msg_index++] = MSG_EXTENDED;
3782   p->msg_buf[p->msg_index++] = MSG_EXT_SDTR_LEN;
3783   p->msg_buf[p->msg_index++] = MSG_EXT_SDTR;
3784   p->msg_buf[p->msg_index++] = period;
3785   p->msg_buf[p->msg_index++] = offset;
3786   p->msg_len += 5;
3787 }
3788 
3789 /*+F*************************************************************************
3790  * Function:
3791  *   aic7xxx_construct_wdtr
3792  *
3793  * Description:
3794  *   Constucts a wide data transfer message in the message buffer
3795  *   on the sequencer.
3796  *-F*************************************************************************/
3797 static void
3798 aic7xxx_construct_wdtr(struct aic7xxx_host *p, unsigned char bus_width)
3799 {
3800   p->msg_buf[p->msg_index++] = MSG_EXTENDED;
3801   p->msg_buf[p->msg_index++] = MSG_EXT_WDTR_LEN;
3802   p->msg_buf[p->msg_index++] = MSG_EXT_WDTR;
3803   p->msg_buf[p->msg_index++] = bus_width;
3804   p->msg_len += 4;
3805 }
3806