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