File: /usr/src/linux/drivers/scsi/aic7xxx/aic7xxx_linux.c

1     /*
2      * Adaptec AIC7xxx device driver for Linux.
3      *
4      * $Id: //depot/src/linux/drivers/scsi/aic7xxx/aic7xxx_linux.c#72 $
5      *
6      * Copyright (c) 1994 John Aycock
7      *   The University of Calgary Department of Computer Science.
8      *
9      * This program is free software; you can redistribute it and/or modify
10      * it under the terms of the GNU General Public License as published by
11      * the Free Software Foundation; either version 2, or (at your option)
12      * any later version.
13      *
14      * This program is distributed in the hope that it will be useful,
15      * but WITHOUT ANY WARRANTY; without even the implied warranty of
16      * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17      * GNU General Public License for more details.
18      *
19      * You should have received a copy of the GNU General Public License
20      * along with this program; see the file COPYING.  If not, write to
21      * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
22      *
23      * Sources include the Adaptec 1740 driver (aha1740.c), the Ultrastor 24F
24      * driver (ultrastor.c), various Linux kernel source, the Adaptec EISA
25      * config file (!adp7771.cfg), the Adaptec AHA-2740A Series User's Guide,
26      * the Linux Kernel Hacker's Guide, Writing a SCSI Device Driver for Linux,
27      * the Adaptec 1542 driver (aha1542.c), the Adaptec EISA overlay file
28      * (adp7770.ovl), the Adaptec AHA-2740 Series Technical Reference Manual,
29      * the Adaptec AIC-7770 Data Book, the ANSI SCSI specification, the
30      * ANSI SCSI-2 specification (draft 10c), ...
31      *
32      * --------------------------------------------------------------------------
33      *
34      *  Modifications by Daniel M. Eischen (deischen@iworks.InterWorks.org):
35      *
36      *  Substantially modified to include support for wide and twin bus
37      *  adapters, DMAing of SCBs, tagged queueing, IRQ sharing, bug fixes,
38      *  SCB paging, and other rework of the code.
39      *
40      * --------------------------------------------------------------------------
41      * Copyright (c) 1994, 1995, 1996, 1997, 1998, 1999, 2000 Justin T. Gibbs.
42      * Copyright (c) 2000 Adaptec Inc.
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.
51      * 2. The name of the author may not be used to endorse or promote products
52      *    derived from this software without specific prior written permission.
53      *
54      * Alternatively, this software may be distributed under the terms of the
55      * GNU General Public License ("GPL").
56      *
57      * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
58      * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
59      * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
60      * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
61      * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
62      * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
63      * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
64      * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
65      * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
66      * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
67      * SUCH DAMAGE.
68      *
69      *---------------------------------------------------------------------------
70      *
71      *  Thanks also go to (in alphabetical order) the following:
72      *
73      *    Rory Bolt     - Sequencer bug fixes
74      *    Jay Estabrook - Initial DEC Alpha support
75      *    Doug Ledford  - Much needed abort/reset bug fixes
76      *    Kai Makisara  - DMAing of SCBs
77      *
78      *  A Boot time option was also added for not resetting the scsi bus.
79      *
80      *    Form:  aic7xxx=extended
81      *           aic7xxx=no_reset
82      *           aic7xxx=ultra
83      *           aic7xxx=irq_trigger:[0,1]  # 0 edge, 1 level
84      *           aic7xxx=verbose
85      *
86      *  Daniel M. Eischen, deischen@iworks.InterWorks.org, 1/23/97
87      *
88      *  Id: aic7xxx.c,v 4.1 1997/06/12 08:23:42 deang Exp
89      */
90     
91     /*
92      * Further driver modifications made by Doug Ledford <dledford@redhat.com>
93      *
94      * Copyright (c) 1997-1999 Doug Ledford
95      *
96      * These changes are released under the same licensing terms as the FreeBSD
97      * driver written by Justin Gibbs.  Please see his Copyright notice above
98      * for the exact terms and conditions covering my changes as well as the
99      * warranty statement.
100      *
101      * Modifications made to the aic7xxx.c,v 4.1 driver from Dan Eischen include
102      * but are not limited to:
103      *
104      *  1: Import of the latest FreeBSD sequencer code for this driver
105      *  2: Modification of kernel code to accomodate different sequencer semantics
106      *  3: Extensive changes throughout kernel portion of driver to improve
107      *     abort/reset processing and error hanndling
108      *  4: Other work contributed by various people on the Internet
109      *  5: Changes to printk information and verbosity selection code
110      *  6: General reliability related changes, especially in IRQ management
111      *  7: Modifications to the default probe/attach order for supported cards
112      *  8: SMP friendliness has been improved
113      *
114      */
115     
116     /*
117      * The next three defines are user configurable.  These should be the only
118      * defines a user might need to get in here and change.  There are other
119      * defines buried deeper in the code, but those really shouldn't need touched
120      * under normal conditions.
121      */
122     
123     #if defined(MODULE)
124     #include <linux/module.h>
125     #endif
126     
127     #include "aic7xxx_osm.h"
128     #include "aic7xxx_inline.h"
129     
130     #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,3,0)
131     #include <linux/init.h>		/* __setup */
132     #endif
133     
134     #include "../sd.h"		/* For geometry detection */
135     
136     #include <linux/mm.h>		/* For fetching system memory size */
137     
138     /*
139      * To generate the correct addresses for the controller to issue
140      * on the bus.  Originally added for DEC Alpha support.
141      */
142     #define VIRT_TO_BUS(a) (uint32_t)virt_to_bus((void *)(a))
143     
144     #if LINUX_VERSION_CODE < KERNEL_VERSION(2,3,0)
145     struct proc_dir_entry proc_scsi_aic7xxx = {
146     	PROC_SCSI_AIC7XXX, 7, "aic7xxx",
147     	S_IFDIR | S_IRUGO | S_IXUGO, 2,
148     	0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL
149     };
150     #endif
151     
152     /*
153      * Set this to the delay in seconds after SCSI bus reset.
154      * Note, we honor this only for the initial bus reset.
155      * The scsi error recovery code performs its own bus settle
156      * delay handling for error recovery actions.
157      */
158     #ifdef CONFIG_AIC7XXX_RESET_DELAY_MS
159     #define AIC7XXX_RESET_DELAY CONFIG_AIC7XXX_RESET_DELAY_MS
160     #else
161     #define AIC7XXX_RESET_DELAY 5000
162     #endif
163     
164     /*
165      * Control collection of SCSI transfer statistics for the /proc filesystem.
166      *
167      * NOTE: Do NOT enable this when running on kernels version 1.2.x and below.
168      * NOTE: This does affect performance since it has to maintain statistics.
169      */
170     #ifdef CONFIG_AIC7XXX_PROC_STATS
171     #define AIC7XXX_PROC_STATS
172     #endif
173     
174     /*
175      * To change the default number of tagged transactions allowed per-device,
176      * add a line to the lilo.conf file like:
177      * append="aic7xxx=verbose,tag_info:{{32,32,32,32},{32,32,32,32}}"
178      * which will result in the first four devices on the first two
179      * controllers being set to a tagged queue depth of 32.
180      *
181      * The tag_commands is an array of 16 to allow for wide and twin adapters.
182      * Twin adapters will use indexes 0-7 for channel 0, and indexes 8-15
183      * for channel 1.
184      */
185     typedef struct {
186     	uint8_t tag_commands[16];	/* Allow for wide/twin adapters. */
187     } adapter_tag_info_t;
188     
189     /*
190      * Modify this as you see fit for your system.
191      *
192      * 0			tagged queuing disabled
193      * 1 <= n <= 253	n == max tags ever dispatched.
194      *
195      * The driver will throttle the number of commands dispatched to a
196      * device if it returns queue full.  For devices with a fixed maximum
197      * queue depth, the driver will eventually determine this depth and
198      * lock it in (a console message is printed to indicate that a lock
199      * has occurred).  On some devices, queue full is returned for a temporary
200      * resource shortage.  These devices will return queue full at varying
201      * depths.  The driver will throttle back when the queue fulls occur and
202      * attempt to slowly increase the depth over time as the device recovers
203      * from the resource shortage.
204      *
205      * In this example, the first line will disable tagged queueing for all
206      * the devices on the first probed aic7xxx adapter.
207      *
208      * The second line enables tagged queueing with 4 commands/LUN for IDs
209      * (0, 2-11, 13-15), disables tagged queueing for ID 12, and tells the
210      * driver to attempt to use up to 64 tags for ID 1.
211      *
212      * The third line is the same as the first line.
213      *
214      * The fourth line disables tagged queueing for devices 0 and 3.  It
215      * enables tagged queueing for the other IDs, with 16 commands/LUN
216      * for IDs 1 and 4, 127 commands/LUN for ID 8, and 4 commands/LUN for
217      * IDs 2, 5-7, and 9-15.
218      */
219     
220     /*
221      * NOTE: The below structure is for reference only, the actual structure
222      *       to modify in order to change things is just below this comment block.
223     adapter_tag_info_t aic7xxx_tag_info[] =
224     {
225     	{{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
226     	{{4, 64, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 4, 4}},
227     	{{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
228     	{{0, 16, 4, 0, 16, 4, 4, 4, 127, 4, 4, 4, 4, 4, 4, 4}}
229     };
230     */
231     
232     #ifdef CONFIG_AIC7XXX_CMDS_PER_DEVICE
233     #define AIC7XXX_CMDS_PER_DEVICE CONFIG_AIC7XXX_CMDS_PER_DEVICE
234     #else
235     #define AIC7XXX_CMDS_PER_DEVICE AHC_MAX_QUEUE
236     #endif
237     
238     #define AIC7XXX_CONFIGED_TAG_COMMANDS {					\
239     	AIC7XXX_CMDS_PER_DEVICE, AIC7XXX_CMDS_PER_DEVICE,		\
240     	AIC7XXX_CMDS_PER_DEVICE, AIC7XXX_CMDS_PER_DEVICE,		\
241     	AIC7XXX_CMDS_PER_DEVICE, AIC7XXX_CMDS_PER_DEVICE,		\
242     	AIC7XXX_CMDS_PER_DEVICE, AIC7XXX_CMDS_PER_DEVICE,		\
243     	AIC7XXX_CMDS_PER_DEVICE, AIC7XXX_CMDS_PER_DEVICE,		\
244     	AIC7XXX_CMDS_PER_DEVICE, AIC7XXX_CMDS_PER_DEVICE,		\
245     	AIC7XXX_CMDS_PER_DEVICE, AIC7XXX_CMDS_PER_DEVICE,		\
246     	AIC7XXX_CMDS_PER_DEVICE, AIC7XXX_CMDS_PER_DEVICE		\
247     }
248     
249     /*
250      * By default, use the number of commands specified by
251      * the users kernel configuration.
252      */
253     static adapter_tag_info_t aic7xxx_tag_info[] =
254     {
255     	{AIC7XXX_CONFIGED_TAG_COMMANDS},
256     	{AIC7XXX_CONFIGED_TAG_COMMANDS},
257     	{AIC7XXX_CONFIGED_TAG_COMMANDS},
258     	{AIC7XXX_CONFIGED_TAG_COMMANDS},
259     	{AIC7XXX_CONFIGED_TAG_COMMANDS},
260     	{AIC7XXX_CONFIGED_TAG_COMMANDS},
261     	{AIC7XXX_CONFIGED_TAG_COMMANDS},
262     	{AIC7XXX_CONFIGED_TAG_COMMANDS},
263     	{AIC7XXX_CONFIGED_TAG_COMMANDS},
264     	{AIC7XXX_CONFIGED_TAG_COMMANDS},
265     	{AIC7XXX_CONFIGED_TAG_COMMANDS},
266     	{AIC7XXX_CONFIGED_TAG_COMMANDS},
267     	{AIC7XXX_CONFIGED_TAG_COMMANDS},
268     	{AIC7XXX_CONFIGED_TAG_COMMANDS},
269     	{AIC7XXX_CONFIGED_TAG_COMMANDS},
270     	{AIC7XXX_CONFIGED_TAG_COMMANDS}
271     };
272     
273     /*
274      * There should be a specific return value for this in scsi.h, but
275      * it seems that most drivers ignore it.
276      */
277     #define DID_UNDERFLOW   DID_ERROR
278     
279     void
280     ahc_print_path(struct ahc_softc *ahc, struct scb *scb)
281     {
282     	printk("(scsi%d:%c:%d:%d): ",
283     	       ahc->platform_data->host->host_no,
284     	       scb != NULL ? SCB_GET_CHANNEL(ahc, scb) : 'X',
285     	       scb != NULL ? SCB_GET_TARGET(ahc, scb) : -1,
286     	       scb != NULL ? SCB_GET_LUN(scb) : -1);
287     }
288     
289     /*
290      * XXX - these options apply unilaterally to _all_ 274x/284x/294x
291      *       cards in the system.  This should be fixed.  Exceptions to this
292      *       rule are noted in the comments.
293      */
294     
295     /*
296      * Skip the scsi bus reset.  Non 0 make us skip the reset at startup.  This
297      * has no effect on any later resets that might occur due to things like
298      * SCSI bus timeouts.
299      */
300     static uint32_t aic7xxx_no_reset;
301     
302     /*
303      * Certain PCI motherboards will scan PCI devices from highest to lowest,
304      * others scan from lowest to highest, and they tend to do all kinds of
305      * strange things when they come into contact with PCI bridge chips.  The
306      * net result of all this is that the PCI card that is actually used to boot
307      * the machine is very hard to detect.  Most motherboards go from lowest
308      * PCI slot number to highest, and the first SCSI controller found is the
309      * one you boot from.  The only exceptions to this are when a controller
310      * has its BIOS disabled.  So, we by default sort all of our SCSI controllers
311      * from lowest PCI slot number to highest PCI slot number.  We also force
312      * all controllers with their BIOS disabled to the end of the list.  This
313      * works on *almost* all computers.  Where it doesn't work, we have this
314      * option.  Setting this option to non-0 will reverse the order of the sort
315      * to highest first, then lowest, but will still leave cards with their BIOS
316      * disabled at the very end.  That should fix everyone up unless there are
317      * really strange cirumstances.
318      */
319     static int aic7xxx_reverse_scan = 0;
320     
321     /*
322      * Should we force EXTENDED translation on a controller.
323      *     0 == Use whatever is in the SEEPROM or default to off
324      *     1 == Use whatever is in the SEEPROM or default to on
325      */
326     static uint32_t aic7xxx_extended = 0;
327     
328     /*
329      * The IRQ trigger method used on EISA controllers. Does not effect PCI cards.
330      *   -1 = Use detected settings.
331      *    0 = Force Edge triggered mode.
332      *    1 = Force Level triggered mode.
333      */
334     static int aic7xxx_irq_trigger = -1;
335     
336     /*
337      * This variable is used to override the termination settings on a controller.
338      * This should not be used under normal conditions.  However, in the case
339      * that a controller does not have a readable SEEPROM (so that we can't
340      * read the SEEPROM settings directly) and that a controller has a buggered
341      * version of the cable detection logic, this can be used to force the
342      * correct termination.  It is preferable to use the manual termination
343      * settings in the BIOS if possible, but some motherboard controllers store
344      * those settings in a format we can't read.  In other cases, auto term
345      * should also work, but the chipset was put together with no auto term
346      * logic (common on motherboard controllers).  In those cases, we have
347      * 32 bits here to work with.  That's good for 8 controllers/channels.  The
348      * bits are organized as 4 bits per channel, with scsi0 getting the lowest
349      * 4 bits in the int.  A 1 in a bit position indicates the termination setting
350      * that corresponds to that bit should be enabled, a 0 is disabled.
351      * It looks something like this:
352      *
353      *    0x0f =  1111-Single Ended Low Byte Termination on/off
354      *            ||\-Single Ended High Byte Termination on/off
355      *            |\-LVD Low Byte Termination on/off
356      *            \-LVD High Byte Termination on/off
357      *
358      * For non-Ultra2 controllers, the upper 2 bits are not important.  So, to
359      * enable both high byte and low byte termination on scsi0, I would need to
360      * make sure that the override_term variable was set to 0x03 (bits 0011).
361      * To make sure that all termination is enabled on an Ultra2 controller at
362      * scsi2 and only high byte termination on scsi1 and high and low byte
363      * termination on scsi0, I would set override_term=0xf23 (bits 1111 0010 0011)
364      *
365      * For the most part, users should never have to use this, that's why I
366      * left it fairly cryptic instead of easy to understand.  If you need it,
367      * most likely someone will be telling you what your's needs to be set to.
368      */
369     static int aic7xxx_override_term = -1;
370     
371     /*
372      * Certain motherboard chipset controllers tend to screw
373      * up the polarity of the term enable output pin.  Use this variable
374      * to force the correct polarity for your system.  This is a bitfield variable
375      * similar to the previous one, but this one has one bit per channel instead
376      * of four.
377      *    0 = Force the setting to active low.
378      *    1 = Force setting to active high.
379      * Most Adaptec cards are active high, several motherboards are active low.
380      * To force a 2940 card at SCSI 0 to active high and a motherboard 7895
381      * controller at scsi1 and scsi2 to active low, and a 2910 card at scsi3
382      * to active high, you would need to set stpwlev=0x9 (bits 1001).
383      *
384      * People shouldn't need to use this, but if you are experiencing lots of
385      * SCSI timeout problems, this may help.  There is one sure way to test what
386      * this option needs to be.  Using a boot floppy to boot the system, configure
387      * your system to enable all SCSI termination (in the Adaptec SCSI BIOS) and
388      * if needed then also pass a value to override_term to make sure that the
389      * driver is enabling SCSI termination, then set this variable to either 0
390      * or 1.  When the driver boots, make sure there are *NO* SCSI cables
391      * connected to your controller.  If it finds and inits the controller
392      * without problem, then the setting you passed to stpwlev was correct.  If
393      * the driver goes into a reset loop and hangs the system, then you need the
394      * other setting for this variable.  If neither setting lets the machine
395      * boot then you have definite termination problems that may not be fixable.
396      */
397     static int aic7xxx_stpwlev = -1;
398     
399     /*
400      * Set this to non-0 in order to force the driver to panic the kernel
401      * and print out debugging info on a SCSI abort or reset cycle.
402      */
403     static int aic7xxx_panic_on_abort = 0;
404     
405     /*
406      * PCI bus parity checking of the Adaptec controllers.  This is somewhat
407      * dubious at best.  To my knowledge, this option has never actually
408      * solved a PCI parity problem, but on certain machines with broken PCI
409      * chipset configurations, it can generate tons of false error messages.
410      * It's included in the driver for completeness.
411      *   0 = Shut off PCI parity check
412      *  -1 = Normal polarity pci parity checking
413      *   1 = reverse polarity pci parity checking
414      *
415      * NOTE: you can't actually pass -1 on the lilo prompt.  So, to set this
416      * variable to -1 you would actually want to simply pass the variable
417      * name without a number.  That will invert the 0 which will result in
418      * -1.
419      */
420     static int aic7xxx_pci_parity = 0;
421     
422     /*
423      * Set this to a non-0 value to make us dump out the 32 bit instruction
424      * registers on the card after completing the sequencer download.  This
425      * allows the actual sequencer download to be verified.  It is possible
426      * to use this option and still boot up and run your system.  This is
427      * only intended for debugging purposes.
428      */
429     static int aic7xxx_dump_sequencer = 0;
430     
431     /*
432      * Certain newer motherboards have put new PCI based devices into the
433      * IO spaces that used to typically be occupied by VLB or EISA cards.
434      * This overlap can cause these newer motherboards to lock up when scanned
435      * for older EISA and VLB devices.  Setting this option to non-0 will
436      * cause the driver to skip scanning for any VLB or EISA controllers and
437      * only support the PCI controllers.  NOTE: this means that if the kernel
438      * os compiled with PCI support disabled, then setting this to non-0
439      * would result in never finding any devices :)
440      */
441     int aic7xxx_no_probe;
442     
443     /*
444      * aic7xxx_detect() has been run, so register all device arrivals
445      * immediately with the system rather than deferring to the sorted
446      * attachment performed by aic7xxx_detect().
447      */
448     int aic7xxx_detect_complete;
449     
450     /*
451      * So that we can set how long each device is given as a selection timeout.
452      * The table of values goes like this:
453      *   0 - 256ms
454      *   1 - 128ms
455      *   2 - 64ms
456      *   3 - 32ms
457      * We default to 256ms because some older devices need a longer time
458      * to respond to initial selection.
459      */
460     static int aic7xxx_seltime = 0x00;
461     
462     /*
463      * So that insmod can find the variable and make it point to something
464      */
465     #ifdef MODULE
466     static char *aic7xxx = NULL;
467     
468     MODULE_PARM(aic7xxx, "s");
469     
470     /*
471      * Just in case someone uses commas to separate items on the insmod
472      * command line, we define a dummy buffer here to avoid having insmod
473      * write wild stuff into our code segment
474      */
475     static char dummy_buffer[60] = "Please don't trounce on me insmod!!\n";
476     
477     #endif
478     
479     static void ahc_linux_handle_scsi_status(struct ahc_softc *,
480     					 struct ahc_linux_device *,
481     					 struct scb *);
482     static void ahc_linux_filter_command(struct ahc_softc*, Scsi_Cmnd*,
483     				     struct scb*);
484     static void ahc_linux_sem_timeout(u_long arg);
485     static void ahc_linux_freeze_sim_queue(struct ahc_softc *ahc);
486     static void ahc_linux_release_sim_queue(u_long arg);
487     static int  ahc_linux_queue_recovery_cmd(Scsi_Cmnd *cmd, scb_flag flag);
488     static void ahc_linux_initialize_scsi_bus(struct ahc_softc *ahc);
489     static void ahc_linux_select_queue_depth(struct Scsi_Host *host,
490     					 Scsi_Device *scsi_devs);
491     static void ahc_linux_device_queue_depth(struct ahc_softc *ahc,
492     					 Scsi_Device *device);
493     static struct ahc_linux_target*	ahc_linux_alloc_target(struct ahc_softc*,
494     						       u_int, u_int);
495     static void			ahc_linux_free_target(struct ahc_softc*,
496     						      struct ahc_linux_target*);
497     static struct ahc_linux_device*	ahc_linux_alloc_device(struct ahc_softc*,
498     						       struct ahc_linux_target*,
499     						       u_int);
500     static void			ahc_linux_free_device(struct ahc_softc*,
501     						      struct ahc_linux_device*);
502     static void ahc_linux_run_device_queue(struct ahc_softc*,
503     				       struct ahc_linux_device*);
504     static void ahc_linux_setup_tag_info(char *p, char *end);
505     static int ahc_linux_next_unit(void);
506     static int ahc_linux_halt(struct notifier_block *nb, u_long event, void *buf);
507     
508     static __inline struct ahc_linux_device*
509     		     ahc_linux_get_device(struct ahc_softc *ahc, u_int channel,
510     					  u_int target, u_int lun, int alloc);
511     static __inline void ahc_linux_queue_cmd_complete(struct ahc_softc *ahc,
512     						  Scsi_Cmnd *cmd);
513     static __inline void ahc_linux_run_complete_queue(struct ahc_softc *ahc,
514     						  struct ahc_cmd *acmd);
515     static __inline void ahc_linux_check_device_queue(struct ahc_softc *ahc,
516     						  struct ahc_linux_device *dev);
517     static __inline void ahc_linux_sniff_command(struct ahc_softc*, Scsi_Cmnd*,
518     					     struct scb*);
519     static __inline void ahc_linux_unmap_scb(struct ahc_softc*, struct scb*);
520     
521     static __inline int ahc_linux_map_seg(struct ahc_softc *ahc, struct scb *scb,
522     		 		      struct ahc_dma_seg *sg,
523     				      bus_addr_t addr, bus_size_t len);
524     
525     static __inline struct ahc_linux_device*
526     ahc_linux_get_device(struct ahc_softc *ahc, u_int channel, u_int target,
527     	       u_int lun, int alloc)
528     {
529     	struct ahc_linux_target *targ;
530     	struct ahc_linux_device *dev;
531     	u_int target_offset;
532     
533     	target_offset = target;
534     	if (channel != 0)
535     		target_offset += 8;
536     	targ = ahc->platform_data->targets[target_offset];
537     	if (targ == NULL) {
538     		if (alloc != 0) {
539     			targ = ahc_linux_alloc_target(ahc, channel, target);
540     			if (targ == NULL)
541     				return (NULL);
542     		} else
543     			return (NULL);
544     	}
545     	dev = targ->devices[lun];
546     	if (dev == NULL && alloc != 0)
547     		dev = ahc_linux_alloc_device(ahc, targ, lun);
548     	return (dev);
549     }
550     
551     static __inline void
552     ahc_linux_queue_cmd_complete(struct ahc_softc *ahc, Scsi_Cmnd *cmd)
553     {
554     	/*
555     	 * Typically, the complete queue has very few entries
556     	 * queued to it before the queue is emptied by
557     	 * ahc_linux_run_complete_queue, so sorting the entries
558     	 * by generation number should be inexpensive.
559     	 * We perform the sort so that commands that complete
560     	 * with an error are retuned in the order origionally
561     	 * queued to the controller so that any subsequent retries
562     	 * are performed in order.  The underlying ahc routines do
563     	 * not guarantee the order that aborted commands will be
564     	 * returned to us.
565     	 */
566     	struct ahc_completeq *completeq;
567     	struct ahc_cmd *list_cmd;
568     	struct ahc_cmd *acmd;
569     
570     	/*
571     	 * If we want the request requeued, make sure there
572     	 * are sufficent retries.  In the old scsi error code,
573     	 * we used to be able to specify a result code that
574     	 * bypassed the retry count.  Now we must use this
575     	 * hack.
576     	 */
577     	if (cmd->result == (CAM_REQUEUE_REQ << 16))
578     		cmd->retries--;
579     	completeq = &ahc->platform_data->completeq;
580     	list_cmd = TAILQ_FIRST(completeq);
581     	acmd = (struct ahc_cmd *)cmd;
582     	while (list_cmd != NULL
583     	    && acmd_scsi_cmd(list_cmd).serial_number
584     	     < acmd_scsi_cmd(acmd).serial_number)
585     		list_cmd = TAILQ_NEXT(list_cmd, acmd_links.tqe);
586     	if (list_cmd != NULL)
587     		TAILQ_INSERT_BEFORE(list_cmd, acmd, acmd_links.tqe);
588     	else
589     		TAILQ_INSERT_TAIL(completeq, acmd, acmd_links.tqe);
590     }
591     
592     static __inline void
593     ahc_linux_run_complete_queue(struct ahc_softc *ahc, struct ahc_cmd *acmd)
594     {	
595     	u_long done_flags;
596     
597     	ahc_done_lock(ahc, &done_flags);
598     	while (acmd != NULL) {
599     		Scsi_Cmnd *cmd;
600     
601     		cmd = &acmd_scsi_cmd(acmd);
602     		acmd = TAILQ_NEXT(acmd, acmd_links.tqe);
603     		cmd->host_scribble = NULL;
604     		cmd->scsi_done(cmd);
605     	}
606     	ahc_done_unlock(ahc, &done_flags);
607     }
608     
609     static __inline void
610     ahc_linux_check_device_queue(struct ahc_softc *ahc,
611     			     struct ahc_linux_device *dev)
612     {
613     	if ((dev->flags & AHC_DEV_FREEZE_TIL_EMPTY) != 0
614     	 && dev->active == 0) {
615     		dev->flags &= ~AHC_DEV_FREEZE_TIL_EMPTY;
616     		dev->qfrozen--;
617     	}
618     
619     	if (TAILQ_FIRST(&dev->busyq) == NULL
620     	 || dev->openings == 0 || dev->qfrozen != 0)
621     		return;
622     
623     	ahc_linux_run_device_queue(ahc, dev);
624     }
625     
626     static __inline void
627     ahc_linux_run_device_queues(struct ahc_softc *ahc)
628     {
629     	struct ahc_linux_device *dev;
630     
631     	while ((ahc->flags & AHC_RESOURCE_SHORTAGE) == 0
632     	    && ahc->platform_data->qfrozen == 0
633     	    && (dev = TAILQ_FIRST(&ahc->platform_data->device_runq)) != NULL) {
634     		TAILQ_REMOVE(&ahc->platform_data->device_runq, dev, links);
635     		dev->flags &= ~AHC_DEV_ON_RUN_LIST;
636     		ahc_linux_check_device_queue(ahc, dev);
637     	}
638     }
639     
640     static __inline void
641     ahc_linux_sniff_command(struct ahc_softc *ahc, Scsi_Cmnd *cmd, struct scb *scb)
642     {
643     	/*
644     	 * Determine whether we care to filter
645     	 * information out of this command.  If so,
646     	 * pass it on to ahc_linux_filter_command() for more
647     	 * heavy weight processing.
648     	 */
649     	if (cmd->cmnd[0] == INQUIRY)
650     		ahc_linux_filter_command(ahc, cmd, scb);
651     }
652     
653     static __inline void
654     ahc_linux_unmap_scb(struct ahc_softc *ahc, struct scb *scb)
655     {
656     	Scsi_Cmnd *cmd;
657     
658     	cmd = scb->io_ctx;
659     	ahc_sync_sglist(ahc, scb, BUS_DMASYNC_POSTWRITE);
660     	if (cmd->use_sg != 0) {
661     		struct scatterlist *sg;
662     
663     		sg = (struct scatterlist *)cmd->request_buffer;
664     		pci_unmap_sg(ahc->dev_softc, sg, cmd->use_sg,
665     			     scsi_to_pci_dma_dir(cmd->sc_data_direction));
666     	} else if (cmd->request_bufflen != 0)
667     		pci_unmap_single(ahc->dev_softc,
668     				 ahc_le32toh(scb->sg_list[0].addr),
669     				 cmd->request_bufflen,
670     				 scsi_to_pci_dma_dir(cmd->sc_data_direction));
671     }
672     
673     static __inline int
674     ahc_linux_map_seg(struct ahc_softc *ahc, struct scb *scb,
675     		  struct ahc_dma_seg *sg, bus_addr_t addr, bus_size_t len)
676     {
677     	int	 consumed;
678     
679     	if ((scb->sg_count + 1) > AHC_NSEG)
680     		panic("Too few segs for dma mapping.  "
681     		      "Increase AHC_NSEG\n");
682     
683     	consumed = 1;
684     	sg->addr = ahc_htole32(addr & 0xFFFFFFFF);
685     	scb->platform_data->xfer_len += len;
686     	if (sizeof(bus_addr_t) > 4
687     	 && (ahc->flags & AHC_39BIT_ADDRESSING) != 0) {
688     		/*
689     		 * Due to DAC restrictions, we can't
690     		 * cross a 4GB boundary.
691     		 */
692     		if ((addr ^ (addr + len - 1)) & ~0xFFFFFFFF) {
693     			struct	 ahc_dma_seg *next_sg;
694     			uint32_t next_len;
695     
696     			printf("Crossed Seg\n");
697     			if ((scb->sg_count + 2) > AHC_NSEG)
698     				panic("Too few segs for dma mapping.  "
699     				      "Increase AHC_NSEG\n");
700     
701     			consumed++;
702     			next_sg = sg + 1;
703     			next_sg->addr = 0;
704     			next_len = 0x100000000 - (addr & 0xFFFFFFFF);
705     			len -= next_len;
706     			next_len |= ((addr >> 8) + 0x1000000) & 0x7F000000;
707     			next_sg->len = ahc_htole32(next_len);
708     		}
709     		len |= (addr >> 8) & 0x7F000000;
710     	}
711     	sg->len = ahc_htole32(len);
712     	return (consumed);
713     }
714     
715     /************************ Shutdown/halt/reboot hook ***************************/
716     #include <linux/notifier.h>
717     #include <linux/reboot.h>
718     
719     static struct notifier_block ahc_linux_notifier = {
720     	ahc_linux_halt, NULL, 0
721     };
722     
723     static int ahc_linux_halt(struct notifier_block *nb, u_long event, void *buf)
724     {
725     	struct ahc_softc *ahc;
726     
727     	TAILQ_FOREACH(ahc, &ahc_tailq, links) {
728     		ahc_shutdown(ahc);
729     	}
730     	return (NOTIFY_OK);
731     }
732     
733     /******************************** Macros **************************************/
734     #define BUILD_SCSIID(ahc, cmd)						\
735     	((((cmd)->target << TID_SHIFT) & TID)				\
736     	| (((cmd)->channel == 0) ? (ahc)->our_id : (ahc)->our_id_b)	\
737     	| (((cmd)->channel == 0) ? 0 : TWIN_CHNLB))
738     
739     /******************************** Bus DMA *************************************/
740     int
741     ahc_dma_tag_create(struct ahc_softc *ahc, bus_dma_tag_t parent,
742     		   bus_size_t alignment, bus_size_t boundary,
743     		   bus_addr_t lowaddr, bus_addr_t highaddr,
744     		   bus_dma_filter_t *filter, void *filterarg,
745     		   bus_size_t maxsize, int nsegments,
746     		   bus_size_t maxsegsz, int flags, bus_dma_tag_t *ret_tag)
747     {
748     	bus_dma_tag_t dmat;
749     
750     	dmat = malloc(sizeof(*dmat), M_DEVBUF, M_NOWAIT);
751     	if (dmat == NULL)
752     		return (ENOMEM);
753     
754     	/*
755     	 * Linux is very simplistic about DMA memory.  For now don't
756     	 * maintain all specification information.  Once Linux supplies
757     	 * better facilities for doing these operations, or the
758     	 * needs of this particular driver change, we might need to do
759     	 * more here.
760     	 */
761     	dmat->alignment = alignment;
762     	dmat->boundary = boundary;
763     	dmat->maxsize = maxsize;
764     	*ret_tag = dmat;
765     	return (0);
766     }
767     
768     void
769     ahc_dma_tag_destroy(struct ahc_softc *ahc, bus_dma_tag_t dmat)
770     {
771     	free(dmat, M_DEVBUF);
772     }
773     
774     int
775     ahc_dmamem_alloc(struct ahc_softc *ahc, bus_dma_tag_t dmat, void** vaddr,
776     		 int flags, bus_dmamap_t *mapp)
777     {
778     	bus_dmamap_t map;
779     
780     #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,3,0)
781     	map = malloc(sizeof(*map), M_DEVBUF, M_NOWAIT);
782     	if (map == NULL)
783     		return (ENOMEM);
784     	/*
785     	 * Although we can dma data above 4GB, our
786     	 * "consistent" memory is below 4GB for
787     	 * space efficiency reasons (only need a 4byte
788     	 * address).  For this reason, we have to reset
789     	 * our dma mask when doing allocations.
790     	 */
791     #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,3)
792     	pci_set_dma_mask(ahc->dev_softc, 0xFFFFFFFF);
793     #else
794     	ahc->dev_softc->dma_mask = 0xFFFFFFFF;
795     #endif
796     	*vaddr = pci_alloc_consistent(ahc->dev_softc,
797     				      dmat->maxsize, &map->bus_addr);
798     #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,3)
799     	pci_set_dma_mask(ahc->dev_softc, ahc->platform_data->hw_dma_mask);
800     #else
801     	ahc->dev_softc->dma_mask = ahc->platform_data->hw_dma_mask;
802     #endif
803     #else /* LINUX_VERSION_CODE < KERNEL_VERSION(2,3,0) */
804     	/*
805     	 * At least in 2.2.14, malloc is a slab allocator so all
806     	 * allocations are aligned.  We assume, for these kernel versions
807     	 * that all allocations will be bellow 4Gig, physically contiguous,
808     	 * and accessable via DMA by the controller.
809     	 */
810     	map = NULL; /* No additional information to store */
811     	*vaddr = malloc(dmat->maxsize, M_DEVBUF, M_NOWAIT);
812     #endif
813     	if (*vaddr == NULL)
814     		return (ENOMEM);
815     	*mapp = map;
816     	return(0);
817     }
818     
819     void
820     ahc_dmamem_free(struct ahc_softc *ahc, bus_dma_tag_t dmat,
821     		void* vaddr, bus_dmamap_t map)
822     {
823     #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,3,0)
824     	pci_free_consistent(ahc->dev_softc, dmat->maxsize,
825     			    vaddr, map->bus_addr);
826     #else
827     	free(vaddr, M_DEVBUF);
828     #endif
829     }
830     
831     int
832     ahc_dmamap_load(struct ahc_softc *ahc, bus_dma_tag_t dmat, bus_dmamap_t map,
833     		void *buf, bus_size_t buflen, bus_dmamap_callback_t *cb,
834     		void *cb_arg, int flags)
835     {
836     	/*
837     	 * Assume for now that this will only be used during
838     	 * initialization and not for per-transaction buffer mapping.
839     	 */
840     	bus_dma_segment_t stack_sg;
841     
842     #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,3,0)
843     	stack_sg.ds_addr = map->bus_addr;
844     #else
845     	stack_sg.ds_addr = VIRT_TO_BUS(buf);
846     #endif
847     	stack_sg.ds_len = dmat->maxsize;
848     	cb(cb_arg, &stack_sg, /*nseg*/1, /*error*/0);
849     	return (0);
850     }
851     
852     void
853     ahc_dmamap_destroy(struct ahc_softc *ahc, bus_dma_tag_t dmat, bus_dmamap_t map)
854     {
855     	/*
856     	 * The map may is NULL in our < 2.3.X implementation.
857     	 */
858     	if (map != NULL)
859     		free(map, M_DEVBUF);
860     }
861     
862     int
863     ahc_dmamap_unload(struct ahc_softc *ahc, bus_dma_tag_t dmat, bus_dmamap_t map)
864     {
865     	/* Nothing to do */
866     	return (0);
867     }
868     
869     /********************* Platform Dependent Functions ***************************/
870     int
871     ahc_softc_comp(struct ahc_softc *lahc, struct ahc_softc *rahc)
872     {
873     	int	value;
874     	int	rvalue;
875     	int	lvalue;
876     
877     	/*
878     	 * Under Linux, cards are ordered as follows:
879     	 *	1) VLB/EISA BIOS enabled devices sorted by BIOS address.
880     	 *	2) PCI devices with BIOS enabled sorted by bus/slot/func.
881     	 *	3) All remaining VLB/EISA devices sorted by ioport.
882     	 *	4) All remaining PCI devices sorted by bus/slot/func.
883     	 */
884     	value = (lahc->flags & AHC_BIOS_ENABLED)
885     	      - (rahc->flags & AHC_BIOS_ENABLED);
886     	if (value != 0)
887     		/* Controllers with BIOS enabled have a *higher* priority */
888     		return (-value);
889     
890     	/*
891     	 * Same BIOS setting, now sort based on bus type.
892     	 * EISA and VL controllers sort together.  EISA/VL
893     	 * have higher priority than PCI.
894     	 */
895     	rvalue = (rahc->chip & AHC_BUS_MASK);
896      	if (rvalue == AHC_VL)
897     		rvalue = AHC_EISA;
898     	lvalue = (lahc->chip & AHC_BUS_MASK);
899      	if (lvalue == AHC_VL)
900     		lvalue = AHC_EISA;
901     	value = lvalue - rvalue;
902     	if (value != 0)
903     		return (value);
904     
905     	/* Still equal.  Sort by BIOS address, ioport, or bus/slot/func. */
906     	switch (rvalue) {
907     	case AHC_PCI:
908     	{
909     		char primary_channel;
910     
911     		value = ahc_get_pci_bus(lahc->dev_softc)
912     		      - ahc_get_pci_bus(rahc->dev_softc);
913     		if (value != 0)
914     			break;
915     		value = ahc_get_pci_slot(lahc->dev_softc)
916     		      - ahc_get_pci_slot(rahc->dev_softc);
917     		if (value != 0)
918     			break;
919     		/*
920     		 * On multi-function devices, the user can choose
921     		 * to have function 1 probed before function 0.
922     		 * Give whichever channel is the primary channel
923     		 * the lowest priority.
924     		 */
925     		primary_channel = (lahc->flags & AHC_PRIMARY_CHANNEL) + 'A';
926     		value = 1;
927     		if (lahc->channel == primary_channel)
928     			value = -1;
929     		break;
930     	}
931     	case AHC_EISA:
932     		if ((rahc->flags & AHC_BIOS_ENABLED) != 0) {
933     			value = lahc->platform_data->bios_address
934     			      - rahc->platform_data->bios_address; 
935     		} else {
936     			value = lahc->bsh.ioport
937     			      - rahc->bsh.ioport; 
938     		}
939     		break;
940     	default:
941     		panic("ahc_softc_sort: invalid bus type");
942     	}
943     	return (value);
944     }
945     
946     static void
947     ahc_linux_setup_tag_info(char *p, char *end)
948     {
949     	char	*base;
950     	char	*tok;
951     	char	*tok_end;
952     	char	*tok_end2;
953     	int      i;
954     	int      instance;
955     	int	 targ;
956     	int	 done;
957     	char	 tok_list[] = {'.', ',', '{', '}', '\0'};
958     
959     	if (*p != ':')
960     		return;
961     
962     	instance = -1;
963     	targ = -1;
964     	done = FALSE;
965     	base = p;
966     	/* Forward us just past the ':' */
967     	tok = base + 1;
968     	tok_end = strchr(tok, '\0');
969     	if (tok_end < end)
970     		*tok_end = ',';
971     	while (!done) {
972     		switch (*tok) {
973     		case '{':
974     			if (instance == -1)
975     				instance = 0;
976     			else if (targ == -1)
977     				targ = 0;
978     			tok++;
979     			break;
980     		case '}':
981     			if (targ != -1)
982     				targ = -1;
983     			else if (instance != -1)
984     				instance = -1;
985     			tok++;
986     			break;
987     		case ',':
988     		case '.':
989     			if (instance == -1)
990     				done = TRUE;
991     			else if (targ >= 0)
992     				targ++;
993     			else if (instance >= 0)
994     				instance++;
995     			if ((targ >= AHC_NUM_TARGETS) ||
996     			    (instance >= NUM_ELEMENTS(aic7xxx_tag_info)))
997     				done = TRUE;
998     			tok++;
999     			if (!done) {
1000     				base = tok;
1001     			}
1002     			break;
1003     		case '\0':
1004     			done = TRUE;
1005     			break;
1006     		default:
1007     			done = TRUE;
1008     			tok_end = strchr(tok, '\0');
1009     			for (i = 0; tok_list[i]; i++) {
1010     				tok_end2 = strchr(tok, tok_list[i]);
1011     				if ((tok_end2) && (tok_end2 < tok_end)) {
1012     					tok_end = tok_end2;
1013     					done = FALSE;
1014     				}
1015     			}
1016     			if ((instance >= 0) && (targ >= 0)
1017     			 && (instance < NUM_ELEMENTS(aic7xxx_tag_info))
1018     			 && (targ < AHC_NUM_TARGETS)) {
1019     				aic7xxx_tag_info[instance].tag_commands[targ] =
1020     				    simple_strtoul(tok, NULL, 0) & 0xff;
1021     			}
1022     			tok = tok_end;
1023     			break;
1024     		}
1025     	}
1026     	while ((p != base) && (p != NULL))
1027     		p = strtok(NULL, ",.");
1028     }
1029     
1030     /*
1031      * Handle Linux boot parameters. This routine allows for assigning a value
1032      * to a parameter with a ':' between the parameter and the value.
1033      * ie. aic7xxx=unpause:0x0A,extended
1034      */
1035     int
1036     aic7xxx_setup(char *s)
1037     {
1038     	int	i, n;
1039     	char   *p;
1040     	char   *end;
1041     
1042     	static struct {
1043     		const char *name;
1044     		uint32_t *flag;
1045     	} options[] = {
1046     		{ "extended", &aic7xxx_extended },
1047     		{ "no_reset", &aic7xxx_no_reset },
1048     		{ "irq_trigger", &aic7xxx_irq_trigger },
1049     		{ "verbose", &aic7xxx_verbose },
1050     		{ "reverse_scan", &aic7xxx_reverse_scan },
1051     		{ "override_term", &aic7xxx_override_term },
1052     		{ "stpwlev", &aic7xxx_stpwlev },
1053     		{ "no_probe", &aic7xxx_no_probe },
1054     		{ "panic_on_abort", &aic7xxx_panic_on_abort },
1055     		{ "pci_parity", &aic7xxx_pci_parity },
1056     		{ "dump_sequencer", &aic7xxx_dump_sequencer },
1057     		{ "seltime", &aic7xxx_seltime },
1058     		{ "tag_info", NULL }
1059     	};
1060     
1061     	end = strchr(s, '\0');
1062     
1063     	for (p = strtok(s, ",."); p; p = strtok(NULL, ",.")) {
1064     		for (i = 0; i < NUM_ELEMENTS(options); i++) {
1065     			n = strlen(options[i].name);
1066     
1067     			if (strncmp(options[i].name, p, n) != 0)
1068     				continue;
1069     
1070     			if (strncmp(p, "tag_info", n) == 0) {
1071     				ahc_linux_setup_tag_info(p + n, end);
1072     			} else if (p[n] == ':') {
1073     				*(options[i].flag) =
1074     				    simple_strtoul(p + n + 1, NULL, 0);
1075     			} else if (!strncmp(p, "verbose", n)) {
1076     				*(options[i].flag) = 1;
1077     			} else {
1078     				*(options[i].flag) = ~(*(options[i].flag));
1079     			}
1080     			break;
1081     		}
1082     	}
1083     	register_reboot_notifier(&ahc_linux_notifier);
1084     	return 1;
1085     }
1086     
1087     #if LINUX_VERSION_CODE > KERNEL_VERSION(2,3,0)
1088     __setup("aic7xxx=", aic7xxx_setup);
1089     #endif
1090     
1091     int aic7xxx_verbose;
1092     
1093     /*
1094      * Try to detect an Adaptec 7XXX controller.
1095      */
1096     int
1097     ahc_linux_detect(Scsi_Host_Template *template)
1098     {
1099     	struct	ahc_softc *ahc;
1100     	int     found;
1101     
1102     	/*
1103     	 * Sanity checking of Linux SCSI data structures so
1104     	 * that some of our hacks^H^H^H^H^Hassumptions aren't
1105     	 * violated.
1106     	 */
1107     	if (offsetof(struct ahc_cmd_internal, end)
1108     	  > offsetof(struct scsi_cmnd, host_scribble)) {
1109     		printf("ahc_linux_detect: SCSI data structures changed.\n");
1110     		printf("ahc_linux_detect: Unable to attach\n");
1111     		return (0);
1112     	}
1113     #ifdef MODULE
1114     	/*
1115     	 * If we've been passed any parameters, process them now.
1116     	 */
1117     	if (aic7xxx)
1118     		aic7xxx_setup(aic7xxx);
1119     	if (dummy_buffer[0] != 'P')
1120     		printk(KERN_WARNING
1121     "aic7xxx: Please read the file /usr/src/linux/drivers/scsi/README.aic7xxx\n"
1122     "aic7xxx: to see the proper way to specify options to the aic7xxx module\n"
1123     "aic7xxx: Specifically, don't use any commas when passing arguments to\n"
1124     "aic7xxx: insmod or else it might trash certain memory areas.\n");
1125     #endif
1126     
1127     #if LINUX_VERSION_CODE > KERNEL_VERSION(2,3,0)
1128     	template->proc_name = "aic7xxx";
1129     #else
1130     	template->proc_dir = &proc_scsi_aic7xxx;
1131     #endif
1132     	template->sg_tablesize = AHC_NSEG;
1133     
1134     #ifdef CONFIG_PCI
1135     	ahc_linux_pci_probe(template);
1136     #endif
1137     
1138     	aic7770_linux_probe(template);
1139     
1140     	/*
1141     	 * Register with the SCSI layer all
1142     	 * controllers we've found.
1143     	 */
1144     	found = 0;
1145     	TAILQ_FOREACH(ahc, &ahc_tailq, links) {
1146     
1147     		if (ahc_linux_register_host(ahc, template) == 0)
1148     			found++;
1149     	}
1150     	aic7xxx_detect_complete++;
1151     	return (found);
1152     }
1153     
1154     int
1155     ahc_linux_register_host(struct ahc_softc *ahc, Scsi_Host_Template *template)
1156     {
1157     	char  buf[80];
1158     	struct Scsi_Host *host;
1159     	char *new_name;
1160     	u_long s;
1161     
1162     
1163     	template->name = ahc->description;
1164     	host = scsi_register(template, sizeof(struct ahc_softc *));
1165     	if (host == NULL)
1166     		return (ENOMEM);
1167     
1168     	ahc_lock(ahc, &s);
1169     	*((struct ahc_softc **)host->hostdata) = ahc;
1170     	ahc->platform_data->host = host;
1171     	host->can_queue = AHC_MAX_QUEUE;
1172     	host->cmd_per_lun = 2;
1173     	host->sg_tablesize = AHC_NSEG;
1174     	host->select_queue_depths = ahc_linux_select_queue_depth;
1175     	/* XXX No way to communicate the ID for multiple channels */
1176     	host->this_id = ahc->our_id;
1177     	host->irq = ahc->platform_data->irq;
1178     	host->max_id = (ahc->features & AHC_WIDE) ? 16 : 8;
1179     	host->max_channel = (ahc->features & AHC_TWIN) ? 1 : 0;
1180     	ahc_set_unit(ahc, ahc_linux_next_unit());
1181     	sprintf(buf, "scsi%d", host->host_no);
1182     	new_name = malloc(strlen(buf) + 1, M_DEVBUF, M_NOWAIT);
1183     	if (new_name != NULL) {
1184     		strcpy(new_name, buf);
1185     		ahc_set_name(ahc, new_name);
1186     	}
1187     	host->unique_id = ahc->unit;
1188     #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,4)
1189     	scsi_set_pci_device(host, ahc->dev_softc);
1190     #endif
1191     	ahc_linux_initialize_scsi_bus(ahc);
1192     	ahc_unlock(ahc, &s);
1193     	return (0);
1194     }
1195     
1196     uint64_t
1197     ahc_linux_get_memsize()
1198     {
1199     	struct sysinfo si;
1200     
1201     	si_meminfo(&si);
1202     	return (si.totalram << PAGE_SHIFT);
1203     }
1204     
1205     /*
1206      * Find the smallest available unit number to use
1207      * for a new device.  We don't just use a static
1208      * count to handle the "repeated hot-(un)plug"
1209      * scenario.
1210      */
1211     static int
1212     ahc_linux_next_unit()
1213     {
1214     	struct ahc_softc *ahc;
1215     	int unit;
1216     
1217     	unit = 0;
1218     retry:
1219     	TAILQ_FOREACH(ahc, &ahc_tailq, links) {
1220     		if (ahc->unit == unit) {
1221     			unit++;
1222     			goto retry;
1223     		}
1224     	}
1225     	return (unit);
1226     }
1227     
1228     /*
1229      * Place the SCSI bus into a known state by either resetting it,
1230      * or forcing transfer negotiations on the next command to any
1231      * target.
1232      */
1233     void
1234     ahc_linux_initialize_scsi_bus(struct ahc_softc *ahc)
1235     {
1236     	int i;
1237     	int numtarg;
1238     
1239     	i = 0;
1240     	numtarg = 0;
1241     
1242     	if (aic7xxx_no_reset != 0)
1243     		ahc->flags &= ~(AHC_RESET_BUS_A|AHC_RESET_BUS_B);
1244     
1245     	if ((ahc->flags & AHC_RESET_BUS_A) != 0)
1246     		ahc_reset_channel(ahc, 'A', /*initiate_reset*/TRUE);
1247     	else
1248     		numtarg = (ahc->features & AHC_WIDE) ? 16 : 8;
1249     
1250     	if ((ahc->features & AHC_TWIN) != 0) {
1251     
1252     		if ((ahc->flags & AHC_RESET_BUS_B) != 0) {
1253     			ahc_reset_channel(ahc, 'B', /*initiate_reset*/TRUE);
1254     		} else {
1255     			if (numtarg == 0)
1256     				i = 8;
1257     			numtarg += 8;
1258     		}
1259     	}
1260     
1261     	for (; i < numtarg; i++) {
1262     		struct ahc_devinfo devinfo;
1263     		struct ahc_initiator_tinfo *tinfo;
1264     		struct ahc_tmode_tstate *tstate;
1265     		u_int our_id;
1266     		u_int target_id;
1267     		char channel;
1268     
1269     		channel = 'A';
1270     		our_id = ahc->our_id;
1271     		target_id = i;
1272     		if (i > 7 && (ahc->features & AHC_TWIN) != 0) {
1273     			channel = 'B';
1274     			our_id = ahc->our_id_b;
1275     			target_id = i % 8;
1276     		}
1277     		tinfo = ahc_fetch_transinfo(ahc, channel, our_id,
1278     					    target_id, &tstate);
1279     		tinfo->goal = tinfo->user;
1280     		/*
1281     		 * Don't try negotiations that require PPR messages
1282     		 * until we successfully retrieve Inquiry data.
1283     		 */
1284     		tinfo->goal.ppr_options = 0;
1285     		if (tinfo->goal.transport_version > SCSI_REV_2)
1286     			tinfo->goal.transport_version = SCSI_REV_2;
1287     		ahc_compile_devinfo(&devinfo, our_id, target_id,
1288     				   CAM_LUN_WILDCARD, channel, ROLE_INITIATOR);
1289     		ahc_update_neg_request(ahc, &devinfo, tstate,
1290     				       tinfo, /*force*/FALSE);
1291     	}
1292     	/* Give the bus some time to recover */
1293     	if ((ahc->flags & (AHC_RESET_BUS_A|AHC_RESET_BUS_B)) != 0) {
1294     		ahc_linux_freeze_sim_queue(ahc);
1295     		init_timer(&ahc->platform_data->reset_timer);
1296     		ahc->platform_data->reset_timer.data = (u_long)ahc;
1297     		ahc->platform_data->reset_timer.expires =
1298     		    jiffies + (AIC7XXX_RESET_DELAY * HZ)/1000;
1299     		ahc->platform_data->reset_timer.function =
1300     		    ahc_linux_release_sim_queue;
1301     		add_timer(&ahc->platform_data->reset_timer);
1302     	}
1303     }
1304     
1305     int
1306     ahc_platform_alloc(struct ahc_softc *ahc, void *platform_arg)
1307     {
1308     	ahc->platform_data =
1309     	    malloc(sizeof(struct ahc_platform_data), M_DEVBUF, M_NOWAIT);
1310     	if (ahc->platform_data == NULL)
1311     		return (ENOMEM);
1312     	memset(ahc->platform_data, 0, sizeof(struct ahc_platform_data));
1313     	TAILQ_INIT(&ahc->platform_data->completeq);
1314     	TAILQ_INIT(&ahc->platform_data->device_runq);
1315     	ahc->platform_data->hw_dma_mask = 0xFFFFFFFF;
1316     	ahc_lockinit(ahc);
1317     	ahc_done_lockinit(ahc);
1318     #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,3,0)
1319     	init_MUTEX_LOCKED(&ahc->platform_data->eh_sem);
1320     #else
1321     	ahc->platform_data->eh_sem = MUTEX_LOCKED;
1322     #endif
1323     	ahc->seltime = (aic7xxx_seltime & 0x3) << 4;
1324     	ahc->seltime_b = (aic7xxx_seltime & 0x3) << 4;
1325     	return (0);
1326     }
1327     
1328     void
1329     ahc_platform_free(struct ahc_softc *ahc)
1330     {
1331     	if (ahc->platform_data != NULL) {
1332     		if (ahc->platform_data->host != NULL)
1333     			scsi_unregister(ahc->platform_data->host);
1334     		if (ahc->platform_data->irq)
1335     			free_irq(ahc->platform_data->irq, ahc);
1336     		if (ahc->tag == BUS_SPACE_PIO
1337     		 && ahc->bsh.ioport != 0)
1338     			release_region(ahc->bsh.ioport, 256);
1339     		if (ahc->tag == BUS_SPACE_MEMIO
1340     		 && ahc->bsh.maddr != NULL) {
1341     			u_long base_addr;
1342     
1343     			base_addr = (u_long)ahc->bsh.maddr;
1344     			base_addr &= PAGE_MASK;
1345     			iounmap((void *)base_addr);
1346     #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0)
1347     			release_mem_region(ahc->platform_data->mem_busaddr,
1348     					   0x1000);
1349     #endif
1350     		}
1351     #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0)
1352     		/* XXX Need an instance detach in the PCI code */
1353     		if (ahc->dev_softc != NULL)
1354     			ahc->dev_softc->driver = NULL;
1355     #endif
1356     		free(ahc->platform_data, M_DEVBUF);
1357     	}
1358     }
1359     
1360     void
1361     ahc_platform_freeze_devq(struct ahc_softc *ahc, struct scb *scb)
1362     {
1363     	ahc_platform_abort_scbs(ahc, SCB_GET_TARGET(ahc, scb),
1364     				SCB_GET_CHANNEL(ahc, scb),
1365     				SCB_GET_LUN(scb), SCB_LIST_NULL,
1366     				ROLE_UNKNOWN, CAM_REQUEUE_REQ);
1367     }
1368     
1369     void
1370     ahc_platform_set_tags(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
1371     		      ahc_queue_alg alg)
1372     {
1373     	struct ahc_linux_device *dev;
1374     	int was_queuing;
1375     	int now_queuing;
1376     
1377     	dev = ahc_linux_get_device(ahc, devinfo->channel - 'A',
1378     				   devinfo->target,
1379     				   devinfo->lun, /*alloc*/FALSE);
1380     	if (dev == NULL)
1381     		return;
1382     	was_queuing = dev->flags & (AHC_DEV_Q_BASIC|AHC_DEV_Q_TAGGED);
1383     	now_queuing = alg != AHC_QUEUE_NONE;
1384     	if ((dev->flags & AHC_DEV_FREEZE_TIL_EMPTY) == 0
1385     	 && (was_queuing != now_queuing)
1386     	 && (dev->active != 0)) {
1387     		dev->flags |= AHC_DEV_FREEZE_TIL_EMPTY;
1388     		dev->qfrozen++;
1389     	}
1390     
1391     	dev->flags &= ~(AHC_DEV_Q_BASIC|AHC_DEV_Q_TAGGED);
1392     	if (now_queuing) {
1393     
1394     		if (!was_queuing) {
1395     			/*
1396     			 * Start out agressively and allow our
1397     			 * dynamic queue depth algorithm to take
1398     			 * care of the rest.
1399     			 */
1400     			dev->maxtags = AHC_MAX_QUEUE;
1401     			dev->openings = dev->maxtags - dev->active;
1402     		}
1403     		if (alg == AHC_QUEUE_TAGGED)
1404     			dev->flags |= AHC_DEV_Q_TAGGED;
1405     		else
1406     			dev->flags |= AHC_DEV_Q_BASIC;
1407     	} else {
1408     		/* We can only have one opening */
1409     		dev->maxtags = 0;
1410     		dev->openings =  1 - dev->active;
1411     	}
1412     }
1413     
1414     int
1415     ahc_platform_abort_scbs(struct ahc_softc *ahc, int target, char channel,
1416     			int lun, u_int tag, role_t role, uint32_t status)
1417     {
1418     	int chan;
1419     	int maxchan;
1420     	int targ;
1421     	int maxtarg;
1422     	int clun;
1423     	int maxlun;
1424     	int count;
1425     
1426     	if (tag != SCB_LIST_NULL)
1427     		return (0);
1428     
1429     	chan = 0;
1430     	if (channel != ALL_CHANNELS) {
1431     		chan = channel - 'A';
1432     		maxchan = chan + 1;
1433     	} else {
1434     		maxchan = (ahc->features & AHC_TWIN) ? 2 : 1;
1435     	}
1436     	targ = 0;
1437     	if (target != CAM_TARGET_WILDCARD) {
1438     		targ = target;
1439     		maxtarg = targ + 1;
1440     	} else {
1441     		maxtarg = (ahc->features & AHC_WIDE) ? 16 : 8;
1442     	}
1443     	clun = 0;
1444     	if (lun != CAM_LUN_WILDCARD) {
1445     		clun = lun;
1446     		maxlun = clun + 1;
1447     	} else {
1448     		maxlun = 16;
1449     	}
1450     
1451     	count = 0;
1452     	for (; chan < maxchan; chan++) {
1453     		for (; targ < maxtarg; targ++) {
1454     			for (; clun < maxlun; clun++) {
1455     				struct ahc_linux_device *dev;
1456     				struct ahc_busyq *busyq;
1457     				struct ahc_cmd *acmd;
1458     
1459     				dev = ahc_linux_get_device(ahc, chan,
1460     							   targ, clun,
1461     							   /*alloc*/FALSE);
1462     				if (dev == NULL)
1463     					continue;
1464     
1465     				busyq = &dev->busyq;
1466     				while ((acmd = TAILQ_FIRST(busyq)) != NULL) {
1467     					Scsi_Cmnd *cmd;
1468     
1469     					cmd = &acmd_scsi_cmd(acmd);
1470     					TAILQ_REMOVE(busyq, acmd,
1471     						     acmd_links.tqe);
1472     					count++;
1473     					cmd->result = status << 16;
1474     					ahc_linux_queue_cmd_complete(ahc, cmd);
1475     				}
1476     			}
1477     		}
1478     	}
1479     
1480     	return (count);
1481     }
1482     
1483     /*
1484      * Sets the queue depth for each SCSI device hanging
1485      * off the input host adapter.
1486      */
1487     static void
1488     ahc_linux_select_queue_depth(struct Scsi_Host * host,
1489     			     Scsi_Device * scsi_devs)
1490     {
1491     	Scsi_Device *device;
1492     	struct	ahc_softc *ahc;
1493     	u_long	flags;
1494     	int	scbnum;
1495     
1496     	ahc = *((struct ahc_softc **)host->hostdata);
1497     	ahc_lock(ahc, &flags);
1498     	scbnum = 0;
1499     	for (device = scsi_devs; device != NULL; device = device->next) {
1500     		if (device->host == host) {
1501     			ahc_linux_device_queue_depth(ahc, device);
1502     			scbnum += device->queue_depth;
1503     		}
1504     	}
1505     	ahc_unlock(ahc, &flags);
1506     }
1507     
1508     /*
1509      * Determines the queue depth for a given device.
1510      */
1511     static void
1512     ahc_linux_device_queue_depth(struct ahc_softc *ahc, Scsi_Device * device)
1513     {
1514     	struct	ahc_devinfo devinfo;
1515     	struct	ahc_initiator_tinfo *targ_info;
1516     	struct	ahc_tmode_tstate *tstate;
1517     	uint8_t tags;
1518     
1519     	ahc_compile_devinfo(&devinfo,
1520     			    device->channel == 0 ? ahc->our_id : ahc->our_id_b,
1521     			    device->id, device->lun,
1522     			    device->channel == 0 ? 'A' : 'B',
1523     			    ROLE_INITIATOR);
1524     	targ_info = ahc_fetch_transinfo(ahc, devinfo.channel,
1525     					devinfo.our_scsiid,
1526     					devinfo.target, &tstate);
1527     
1528     	tags = 0;
1529     	if (device->tagged_supported != 0
1530     	 && (ahc->user_discenable & devinfo.target_mask) != 0) {
1531     		if (ahc->unit >= NUM_ELEMENTS(aic7xxx_tag_info)) {
1532     
1533     			printf("aic7xxx: WARNING, insufficient "
1534     			       "tag_info instances for installed "
1535     			       "controllers. Using defaults\n");
1536     			printf("aic7xxx: Please update the "
1537     			       "aic7xxx_tag_info array in the "
1538     			       "aic7xxx.c source file.\n");
1539     			tags = AHC_MAX_QUEUE;
1540     		} else {
1541     			adapter_tag_info_t *tag_info;
1542     
1543     			tag_info = &aic7xxx_tag_info[ahc->unit];
1544     			tags = tag_info->tag_commands[devinfo.target_offset];
1545     			if (tags > AHC_MAX_QUEUE)
1546     				tags = AHC_MAX_QUEUE;
1547     		}
1548     	}
1549     	if (tags != 0) {
1550     		device->queue_depth = tags;
1551     		ahc_set_tags(ahc, &devinfo, AHC_QUEUE_TAGGED);
1552     		printf("scsi%d:%d:%d:%d: Tagged Queuing enabled.  Depth %d\n",
1553     	       	       ahc->platform_data->host->host_no, device->channel,
1554     		       device->id, device->lun, tags);
1555     	} else {
1556     		/*
1557     		 * We allow the OS to queue 2 untagged transactions to
1558     		 * us at any time even though we can only execute them
1559     		 * serially on the controller/device.  This should remove
1560     		 * some latency.
1561     		 */
1562     		device->queue_depth = 2;
1563     	}
1564     }
1565     
1566     /*
1567      * Queue an SCB to the controller.
1568      */
1569     int
1570     ahc_linux_queue(Scsi_Cmnd * cmd, void (*scsi_done) (Scsi_Cmnd *))
1571     {
1572     	struct	 ahc_softc *ahc;
1573     	struct	 ahc_linux_device *dev;
1574     	u_long	 flags;
1575     
1576     	ahc = *(struct ahc_softc **)cmd->host->hostdata;
1577     
1578     	/*
1579     	 * Save the callback on completion function.
1580     	 */
1581     	cmd->scsi_done = scsi_done;
1582     
1583     	ahc_lock(ahc, &flags);
1584     	dev = ahc_linux_get_device(ahc, cmd->channel, cmd->target,
1585     				   cmd->lun, /*alloc*/TRUE);
1586     	if (dev == NULL) {
1587     		ahc_unlock(ahc, &flags);
1588     		printf("aic7xxx_linux_queue: Unable to allocate device!\n");
1589     		return (-ENOMEM);
1590     	}
1591     	cmd->result = CAM_REQ_INPROG << 16;
1592     	TAILQ_INSERT_TAIL(&dev->busyq, (struct ahc_cmd *)cmd, acmd_links.tqe);
1593     	if ((dev->flags & AHC_DEV_ON_RUN_LIST) == 0) {
1594     		TAILQ_INSERT_TAIL(&ahc->platform_data->device_runq, dev, links);
1595     		dev->flags |= AHC_DEV_ON_RUN_LIST;
1596     		ahc_linux_run_device_queues(ahc);
1597     	}
1598     	ahc_unlock(ahc, &flags);
1599     	return (0);
1600     }
1601     
1602     static void
1603     ahc_linux_run_device_queue(struct ahc_softc *ahc, struct ahc_linux_device *dev)
1604     {
1605     	struct	 ahc_cmd *acmd;
1606     	struct	 scsi_cmnd *cmd;
1607     	struct	 scb *scb;
1608     	struct	 hardware_scb *hscb;
1609     	struct	 ahc_initiator_tinfo *tinfo;
1610     	struct	 ahc_tmode_tstate *tstate;
1611     	uint16_t mask;
1612     
1613     	if ((dev->flags & AHC_DEV_ON_RUN_LIST) != 0)
1614     		panic("running device on run list");
1615     
1616     	while ((acmd = TAILQ_FIRST(&dev->busyq)) != NULL
1617     	    && dev->openings > 0 && dev->qfrozen == 0) {
1618     
1619     		/*
1620     		 * Schedule us to run later.  The only reason we are not
1621     		 * running is because the whole controller Q is frozen.
1622     		 */
1623     		if (ahc->platform_data->qfrozen != 0) {
1624     
1625     			TAILQ_INSERT_TAIL(&ahc->platform_data->device_runq,
1626     					  dev, links);
1627     			dev->flags |= AHC_DEV_ON_RUN_LIST;
1628     			return;
1629     		}
1630     		/*
1631     		 * Get an scb to use.
1632     		 */
1633     		if ((scb = ahc_get_scb(ahc)) == NULL) {
1634     			TAILQ_INSERT_TAIL(&ahc->platform_data->device_runq,
1635     					 dev, links);
1636     			dev->flags |= AHC_DEV_ON_RUN_LIST;
1637     			ahc->flags |= AHC_RESOURCE_SHORTAGE;
1638     			return;
1639     		}
1640     		TAILQ_REMOVE(&dev->busyq, acmd, acmd_links.tqe);
1641     		cmd = &acmd_scsi_cmd(acmd);
1642     		scb->io_ctx = cmd;
1643     		scb->platform_data->dev = dev;
1644     		hscb = scb->hscb;
1645     		cmd->host_scribble = (char *)scb;
1646     
1647     		/*
1648     		 * Fill out basics of the HSCB.
1649     		 */
1650     		hscb->control = 0;
1651     		hscb->scsiid = BUILD_SCSIID(ahc, cmd);
1652     		hscb->lun = cmd->lun;
1653     		mask = SCB_GET_TARGET_MASK(ahc, scb);
1654     		tinfo = ahc_fetch_transinfo(ahc, SCB_GET_CHANNEL(ahc, scb),
1655     					    SCB_GET_OUR_ID(scb),
1656     					    SCB_GET_TARGET(ahc, scb), &tstate);
1657     		hscb->scsirate = tinfo->scsirate;
1658     		hscb->scsioffset = tinfo->curr.offset;
1659     		if ((tstate->ultraenb & mask) != 0)
1660     			hscb->control |= ULTRAENB;
1661     
1662     		if ((ahc->user_discenable & mask) != 0)
1663     			hscb->control |= DISCENB;
1664     
1665     		if ((tstate->auto_negotiate & mask) != 0) {
1666     			scb->flags |= SCB_AUTO_NEGOTIATE;
1667     			scb->hscb->control |= MK_MESSAGE;
1668     		}
1669     
1670     		if ((dev->flags & (AHC_DEV_Q_TAGGED|AHC_DEV_Q_BASIC)) != 0) {
1671     			if (dev->commands_since_idle_or_otag == AHC_OTAG_THRESH
1672     			 && (dev->flags & AHC_DEV_Q_TAGGED) != 0) {
1673     				hscb->control |= MSG_ORDERED_TASK;
1674     				dev->commands_since_idle_or_otag = 0;
1675     			} else {
1676     				hscb->control |= MSG_SIMPLE_TASK;
1677     			}
1678     		}
1679     
1680     		hscb->cdb_len = cmd->cmd_len;
1681     		if (hscb->cdb_len <= 12) {
1682     			memcpy(hscb->shared_data.cdb, cmd->cmnd, hscb->cdb_len);
1683     		} else {
1684     			memcpy(hscb->cdb32, cmd->cmnd, hscb->cdb_len);
1685     			scb->flags |= SCB_CDB32_PTR;
1686     		}
1687     
1688     		scb->platform_data->xfer_len = 0;
1689     		ahc_set_residual(scb, 0);
1690     		ahc_set_sense_residual(scb, 0);
1691     		if (cmd->use_sg != 0) {
1692     			struct	ahc_dma_seg *sg;
1693     			struct	scatterlist *cur_seg;
1694     			struct	scatterlist *end_seg;
1695     			int	nseg;
1696     
1697     			cur_seg = (struct scatterlist *)cmd->request_buffer;
1698     			nseg = pci_map_sg(ahc->dev_softc, cur_seg, cmd->use_sg,
1699     				 scsi_to_pci_dma_dir(cmd ->sc_data_direction));
1700     			end_seg = cur_seg + nseg;
1701     			/* Copy the segments into the SG list. */
1702     			sg = scb->sg_list;
1703     			/*
1704     			 * The sg_count may be larger than nseg if
1705     			 * a transfer crosses a 32bit page.
1706     			 */ 
1707     			scb->sg_count = 0;
1708     			while(cur_seg < end_seg) {
1709     				bus_addr_t addr;
1710     				bus_size_t len;
1711     				int consumed;
1712     
1713     				addr = sg_dma_address(cur_seg);
1714     				len = sg_dma_len(cur_seg);
1715     				consumed = ahc_linux_map_seg(ahc, scb,
1716     							     sg, addr, len);
1717     				sg += consumed;
1718     				scb->sg_count += consumed;
1719     				cur_seg++;
1720     			}
1721     			sg--;
1722     			sg->len |= ahc_htole32(AHC_DMA_LAST_SEG);
1723     
1724     			/*
1725     			 * Reset the sg list pointer.
1726     			 */
1727     			scb->hscb->sgptr =
1728     			    ahc_htole32(scb->sg_list_phys | SG_FULL_RESID);
1729     
1730     			/*
1731     			 * Copy the first SG into the "current"
1732     			 * data pointer area.
1733     			 */
1734     			scb->hscb->dataptr = scb->sg_list->addr;
1735     			scb->hscb->datacnt = scb->sg_list->len;
1736     		} else if (cmd->request_bufflen != 0) {
1737     			struct	 ahc_dma_seg *sg;
1738     			bus_addr_t addr;
1739     
1740     			sg = scb->sg_list;
1741     			addr = pci_map_single(ahc->dev_softc,
1742     			       cmd->request_buffer,
1743     			       cmd->request_bufflen,
1744     			       scsi_to_pci_dma_dir(cmd->sc_data_direction));
1745     			scb->sg_count = ahc_linux_map_seg(ahc, scb,
1746     							  sg, addr,
1747     							  cmd->request_bufflen);
1748     			sg->len |= ahc_htole32(AHC_DMA_LAST_SEG);
1749     
1750     			/*
1751     			 * Reset the sg list pointer.
1752     			 */
1753     			scb->hscb->sgptr =
1754     			    ahc_htole32(scb->sg_list_phys | SG_FULL_RESID);
1755     
1756     			/*
1757     			 * Copy the first SG into the "current"
1758     			 * data pointer area.
1759     			 */
1760     			scb->hscb->dataptr = sg->addr;
1761     			scb->hscb->datacnt = sg->len;
1762     		} else {
1763     			scb->hscb->sgptr = ahc_htole32(SG_LIST_NULL);
1764     			scb->hscb->dataptr = 0;
1765     			scb->hscb->datacnt = 0;
1766     			scb->sg_count = 0;
1767     		}
1768     
1769     		ahc_sync_sglist(ahc, scb, BUS_DMASYNC_PREWRITE);
1770     		LIST_INSERT_HEAD(&ahc->pending_scbs, scb, pending_links);
1771     		dev->openings--;
1772     		dev->active++;
1773     		dev->commands_issued++;
1774     		dev->commands_since_idle_or_otag++;
1775     
1776     		/*
1777     		 * We only allow one untagged transaction
1778     		 * per target in the initiator role unless
1779     		 * we are storing a full busy target *lun*
1780     		 * table in SCB space.
1781     		 */
1782     		if ((scb->hscb->control & (TARGET_SCB|TAG_ENB)) == 0
1783     		 && (ahc->features & AHC_SCB_BTT) == 0) {
1784     			struct scb_tailq *untagged_q;
1785     			int target_offset;
1786     
1787     			target_offset = SCB_GET_TARGET_OFFSET(ahc, scb);
1788     			untagged_q = &(ahc->untagged_queues[target_offset]);
1789     			TAILQ_INSERT_TAIL(untagged_q, scb, links.tqe);
1790     			scb->flags |= SCB_UNTAGGEDQ;
1791     			if (TAILQ_FIRST(untagged_q) != scb)
1792     				continue;
1793     		}
1794     		scb->flags |= SCB_ACTIVE;
1795     		ahc_queue_scb(ahc, scb);
1796     	}
1797     }
1798     
1799     /*
1800      * SCSI controller interrupt handler.
1801      */
1802     void
1803     ahc_linux_isr(int irq, void *dev_id, struct pt_regs * regs)
1804     {
1805     	struct ahc_softc *ahc;
1806     	struct ahc_cmd *acmd;
1807     	u_long flags;
1808     
1809     	ahc = (struct ahc_softc *) dev_id;
1810     	ahc_lock(ahc, &flags); 
1811     	ahc_intr(ahc);
1812     	/*
1813     	 * It would be nice to run the device queues from a
1814     	 * bottom half handler, but as there is no way to
1815     	 * dynamically register one, we'll have to postpone
1816     	 * that until we get integrated into the kernel.
1817     	 */
1818     	ahc_linux_run_device_queues(ahc);
1819     	acmd = TAILQ_FIRST(&ahc->platform_data->completeq);
1820     	TAILQ_INIT(&ahc->platform_data->completeq);
1821     	ahc_unlock(ahc, &flags);
1822     	if (acmd != NULL)
1823     		ahc_linux_run_complete_queue(ahc, acmd);
1824     }
1825     
1826     void
1827     ahc_platform_flushwork(struct ahc_softc *ahc)
1828     {
1829     	struct ahc_cmd *acmd;
1830     
1831     	acmd = TAILQ_FIRST(&ahc->platform_data->completeq);
1832     	TAILQ_INIT(&ahc->platform_data->completeq);
1833     	if (acmd != NULL)
1834     		ahc_linux_run_complete_queue(ahc, acmd);
1835     }
1836     
1837     static struct ahc_linux_target*
1838     ahc_linux_alloc_target(struct ahc_softc *ahc, u_int channel, u_int target)
1839     {
1840     	struct ahc_linux_target *targ;
1841     	u_int target_offset;
1842     
1843     	targ = malloc(sizeof(*targ), M_DEVBUG, M_NOWAIT);
1844     	if (targ == NULL)
1845     		return (NULL);
1846     	memset(targ, 0, sizeof(*targ));
1847     	targ->channel = channel;
1848     	targ->target = target;
1849     	target_offset = target;
1850     	if (channel != 0)
1851     		target_offset += 8;
1852     	ahc->platform_data->targets[target_offset] = targ;
1853     	return (targ);
1854     }
1855     
1856     static void
1857     ahc_linux_free_target(struct ahc_softc *ahc, struct ahc_linux_target *targ)
1858     {
1859     	u_int target_offset;
1860     
1861     	target_offset = targ->target;
1862     	if (targ->channel != 0)
1863     		target_offset += 8;
1864     	ahc->platform_data->targets[target_offset] = NULL;
1865     	free(targ, M_DEVBUF);
1866     }
1867     
1868     static struct ahc_linux_device*
1869     ahc_linux_alloc_device(struct ahc_softc *ahc,
1870     		 struct ahc_linux_target *targ, u_int lun)
1871     {
1872     	struct ahc_linux_device *dev;
1873     
1874     	dev = malloc(sizeof(*dev), M_DEVBUG, M_NOWAIT);
1875     	if (dev == NULL)
1876     		return (NULL);
1877     	memset(dev, 0, sizeof(*dev));
1878     	TAILQ_INIT(&dev->busyq);
1879     	dev->flags = AHC_DEV_UNCONFIGURED;
1880     	dev->lun = lun;
1881     	dev->target = targ;
1882     
1883     	/*
1884     	 * We start out life using untagged
1885     	 * transactions of which we allow one.
1886     	 */
1887     	dev->openings = 1;
1888     
1889     	/*
1890     	 * Set maxtags to 0.  This will be changed if we
1891     	 * later determine that we are dealing with
1892     	 * a tagged queuing capable device.
1893     	 */
1894     	dev->maxtags = 0;
1895     	
1896     	targ->refcount++;
1897     	targ->devices[lun] = dev;
1898     	return (dev);
1899     }
1900     
1901     static void
1902     ahc_linux_free_device(struct ahc_softc *ahc, struct ahc_linux_device *dev)
1903     {
1904     	struct ahc_linux_target *targ;
1905     
1906     	targ = dev->target;
1907     	targ->devices[dev->lun] = NULL;
1908     	free(dev, M_DEVBUF);
1909     	targ->refcount--;
1910     	if (targ->refcount == 0)
1911     		ahc_linux_free_target(ahc, targ);
1912     }
1913     
1914     /*
1915      * Return a string describing the driver.
1916      */
1917     const char *
1918     ahc_linux_info(struct Scsi_Host *host)
1919     {
1920     	static char buffer[512];
1921     	char	ahc_info[256];
1922     	char   *bp;
1923     	struct ahc_softc *ahc;
1924     
1925     	bp = &buffer[0];
1926     	ahc = *(struct ahc_softc **)host->hostdata;
1927     	memset(bp, 0, sizeof(buffer));
1928     	strcpy(bp, "Adaptec AIC7XXX EISA/VLB/PCI SCSI HBA DRIVER, Rev ");
1929     	strcat(bp, AIC7XXX_DRIVER_VERSION);
1930     	strcat(bp, "\n");
1931     	strcat(bp, "        <");
1932     	strcat(bp, ahc->description);
1933     	strcat(bp, ">\n");
1934     	strcat(bp, "        ");
1935     	ahc_controller_info(ahc, ahc_info);
1936     	strcat(bp, ahc_info);
1937     	strcat(bp, "\n");
1938     
1939     	return (bp);
1940     }
1941     
1942     void
1943     ahc_send_async(struct ahc_softc *ahc, char channel,
1944     	       u_int target, u_int lun, ac_code code, void *arg)
1945     {
1946     	switch (code) {
1947     	case AC_TRANSFER_NEG:
1948     	{
1949     		char	buf[80];
1950     		struct	ahc_linux_target *targ;
1951     		struct	info_str info;
1952     		struct	ahc_initiator_tinfo *tinfo;
1953     		struct	ahc_tmode_tstate *tstate;
1954     		int	target_offset;
1955     
1956     		info.buffer = buf;
1957     		info.length = sizeof(buf);
1958     		info.offset = 0;
1959     		info.pos = 0;
1960     		tinfo = ahc_fetch_transinfo(ahc, channel,
1961     						channel == 'A' ? ahc->our_id
1962     							       : ahc->our_id_b,
1963     						target, &tstate);
1964     
1965     		/*
1966     		 * Don't bother reporting results while
1967     		 * negotiations are still pending.
1968     		 */
1969     		if (tinfo->curr.period != tinfo->goal.period
1970     		 || tinfo->curr.width != tinfo->goal.width
1971     		 || tinfo->curr.offset != tinfo->goal.offset
1972     		 || tinfo->curr.ppr_options != tinfo->goal.ppr_options)
1973     			if (bootverbose == 0)
1974     				break;
1975     
1976     		/*
1977     		 * Don't bother reporting results that
1978     		 * are identical to those last reported.
1979     		 */
1980     		target_offset = target;
1981     		if (channel == 'B')
1982     			target_offset += 8;
1983     		targ = ahc->platform_data->targets[target_offset];
1984     		if (targ != NULL
1985     		 && tinfo->curr.period == targ->last_tinfo.period
1986     		 && tinfo->curr.width == targ->last_tinfo.width
1987     		 && tinfo->curr.offset == targ->last_tinfo.offset
1988     		 && tinfo->curr.ppr_options == targ->last_tinfo.ppr_options)
1989     			if (bootverbose == 0)
1990     				break;
1991     
1992     		targ->last_tinfo.period = tinfo->curr.period;
1993     		targ->last_tinfo.width = tinfo->curr.width;
1994     		targ->last_tinfo.offset = tinfo->curr.offset;
1995     		targ->last_tinfo.ppr_options = tinfo->curr.ppr_options;
1996     
1997     		printf("(%s:%c:", ahc_name(ahc), channel);
1998     		if (target == CAM_TARGET_WILDCARD)
1999     			printf("*): ");
2000     		else
2001     			printf("%d): ", target);
2002     		ahc_format_transinfo(&info, &tinfo->curr);
2003     		if (info.pos < info.length)
2004     			*info.buffer = '\0';
2005     		else
2006     			buf[info.length - 1] = '\0';
2007     		printf("%s", buf);
2008     		break;
2009     	}
2010             case AC_SENT_BDR:
2011     		break;
2012             case AC_BUS_RESET:
2013     #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,3,0)
2014     		if (ahc->platform_data->host != NULL) {
2015     			scsi_report_bus_reset(ahc->platform_data->host,
2016     					      channel - 'A');
2017     		}
2018     #endif
2019                     break;
2020             default:
2021                     panic("ahc_send_async: Unexpected async event");
2022             }
2023     }
2024     
2025     /*
2026      * Calls the higher level scsi done function and frees the scb.
2027      */
2028     void
2029     ahc_done(struct ahc_softc *ahc, struct scb * scb)
2030     {
2031     	Scsi_Cmnd *cmd;
2032     	struct ahc_linux_device *dev;
2033     
2034     	LIST_REMOVE(scb, pending_links);
2035     	if ((scb->flags & SCB_UNTAGGEDQ) != 0) {
2036     		struct scb_tailq *untagged_q;
2037     		int target_offset;
2038     
2039     		target_offset = SCB_GET_TARGET_OFFSET(ahc, scb);
2040     		untagged_q = &(ahc->untagged_queues[target_offset]);
2041     		TAILQ_REMOVE(untagged_q, scb, links.tqe);
2042     		ahc_run_untagged_queue(ahc, untagged_q);
2043     	}
2044     
2045     	if ((scb->flags & SCB_ACTIVE) == 0) {
2046     		printf("SCB %d done'd twice\n", scb->hscb->tag);
2047     		ahc_dump_card_state(ahc);
2048     		panic("Stopping for safety");
2049     	}
2050     	cmd = scb->io_ctx;
2051     	dev = scb->platform_data->dev;
2052     	dev->active--;
2053     	dev->openings++;
2054     	ahc_linux_unmap_scb(ahc, scb);
2055     	if (scb->flags & SCB_SENSE) {
2056     		memcpy(cmd->sense_buffer, ahc_get_sense_buf(ahc, scb),
2057     		       MIN(sizeof(struct scsi_sense_data),
2058     			   sizeof(cmd->sense_buffer)));
2059     		cmd->result |= (DRIVER_SENSE << 24);
2060     	} else {
2061     		/*
2062     		 * Guard against stale sense data.
2063     		 * The Linux mid-layer assumes that sense
2064     		 * was retrieved anytime the first byte of
2065     		 * the sense buffer looks "sane".
2066     		 */
2067     		cmd->sense_buffer[0] = 0;
2068     	}
2069     	if (ahc_get_transaction_status(scb) == CAM_REQ_INPROG) {
2070     		uint32_t amount_xferred;
2071     
2072     		amount_xferred =
2073     		    ahc_get_transfer_length(scb) - ahc_get_residual(scb);
2074     		if (amount_xferred < scb->io_ctx->underflow) {
2075     			printf("Saw underflow (%ld of %ld bytes). "
2076     			       "Treated as error\n",
2077     				ahc_get_residual(scb),
2078     				ahc_get_transfer_length(scb));
2079     			ahc_set_transaction_status(scb, CAM_DATA_RUN_ERR);
2080     		} else {
2081     			ahc_set_transaction_status(scb, CAM_REQ_CMP);
2082     			ahc_linux_sniff_command(ahc, cmd, scb);
2083     		}
2084     	} else if (ahc_get_transaction_status(scb) == DID_OK) {
2085     		ahc_linux_handle_scsi_status(ahc, dev, scb);
2086     	} else if (ahc_get_transaction_status(scb) == DID_NO_CONNECT) {
2087     		/*
2088     		 * Should a selection timeout kill the device?
2089     		 * That depends on whether the selection timeout
2090     		 * is persistent.  Since we have no guarantee that
2091     		 * the mid-layer will issue an inquiry for this device
2092     		 * again, we can't just kill it off.
2093     		dev->flags |= AHC_DEV_UNCONFIGURED;
2094     		 */
2095     	}
2096     
2097     	if (dev->openings == 1
2098     	 && ahc_get_transaction_status(scb) == CAM_REQ_CMP
2099     	 && ahc_get_scsi_status(scb) != SCSI_STATUS_QUEUE_FULL)
2100     		dev->tag_success_count++;
2101     	/*
2102     	 * Some devices deal with temporary internal resource
2103     	 * shortages by returning queue full.  When the queue
2104     	 * full occurrs, we throttle back.  Slowly try to get
2105     	 * back to our previous queue depth.
2106     	 */
2107     	if ((dev->openings + dev->active) < dev->maxtags
2108     	 && dev->tag_success_count > AHC_TAG_SUCCESS_INTERVAL) {
2109     		dev->tag_success_count = 0;
2110     		dev->openings++;
2111     	}
2112     
2113     	if (dev->active == 0)
2114     		dev->commands_since_idle_or_otag = 0;
2115     
2116     	if (TAILQ_EMPTY(&dev->busyq)) {
2117     		if ((dev->flags & AHC_DEV_UNCONFIGURED) != 0
2118     		 && dev->active == 0)
2119     			ahc_linux_free_device(ahc, dev);
2120     	} else if ((dev->flags & AHC_DEV_ON_RUN_LIST) == 0) {
2121     		TAILQ_INSERT_TAIL(&ahc->platform_data->device_runq, dev, links);
2122     		dev->flags |= AHC_DEV_ON_RUN_LIST;
2123     	}
2124     
2125     	if ((scb->flags & SCB_RECOVERY_SCB) != 0) {
2126     		printf("Recovery SCB completes\n");
2127     		up(&ahc->platform_data->eh_sem);
2128     	}
2129     
2130     	ahc_free_scb(ahc, scb);
2131     	ahc_linux_queue_cmd_complete(ahc, cmd);
2132     }
2133     
2134     static void
2135     ahc_linux_handle_scsi_status(struct ahc_softc *ahc,
2136     			     struct ahc_linux_device *dev, struct scb *scb)
2137     {
2138     	/*
2139     	 * We don't currently trust the mid-layer to
2140     	 * properly deal with queue full or busy.  So,
2141     	 * when one occurs, we tell the mid-layer to
2142     	 * unconditionally requeue the command to us
2143     	 * so that we can retry it ourselves.  We also
2144     	 * implement our own throttling mechanism so
2145     	 * we don't clobber the device with too many
2146     	 * commands.
2147     	 */
2148     	switch (ahc_get_scsi_status(scb)) {
2149     	default:
2150     		break;
2151     	case SCSI_STATUS_QUEUE_FULL:
2152     	{
2153     		/*
2154     		 * By the time the core driver has returned this
2155     		 * command, all other commands that were queued
2156     		 * to us but not the device have been returned.
2157     		 * This ensures that dev->active is equal to
2158     		 * the number of commands actually queued to
2159     		 * the device.
2160     		 */
2161     		dev->tag_success_count = 0;
2162     		if (dev->active != 0) {
2163     			/*
2164     			 * Drop our opening count to the number
2165     			 * of commands currently outstanding.
2166     			 */
2167     			dev->openings = 0;
2168     /*
2169     			ahc_print_path(ahc, scb);
2170     			printf("Dropping tag count to %d\n", dev->active);
2171      */
2172     			if (dev->active == dev->tags_on_last_queuefull) {
2173     
2174     				dev->last_queuefull_same_count++;
2175     				/*
2176     				 * If we repeatedly see a queue full
2177     				 * at the same queue depth, this
2178     				 * device has a fixed number of tag
2179     				 * slots.  Lock in this tag depth
2180     				 * so we stop seeing queue fulls from
2181     				 * this device.
2182     				 */
2183     				if (dev->last_queuefull_same_count
2184     				 == AHC_LOCK_TAGS_COUNT) {
2185     					dev->maxtags = dev->active;
2186     					ahc_print_path(ahc, scb);
2187     					printf("Locking max tag count at %d\n",
2188     					       dev->active);
2189     				}
2190     			} else {
2191     				dev->tags_on_last_queuefull = dev->active;
2192     				dev->last_queuefull_same_count = 0;
2193     			}
2194     			ahc_set_transaction_status(scb, CAM_REQUEUE_REQ);
2195     			ahc_set_scsi_status(scb, SCSI_STATUS_OK);
2196     			break;
2197     		}
2198     		/*
2199     		 * Drop down to a single opening, and treat this
2200     		 * as if the target return BUSY SCSI status.
2201     		 */
2202     		dev->openings = 1;
2203     		/* FALLTHROUGH */
2204     	}
2205     	case SCSI_STATUS_BUSY:
2206     		/*
2207     		 * XXX Set a timer and handle ourselves????
2208     		 * For now we pray that the mid-layer does something
2209     		 * sane for devices that are busy.
2210     		 */
2211     		ahc_set_scsi_status(scb, SCSI_STATUS_BUSY);
2212     		break;
2213     	}
2214     }
2215     
2216     static void
2217     ahc_linux_filter_command(struct ahc_softc *ahc, Scsi_Cmnd *cmd, struct scb *scb)
2218     {
2219     	switch (cmd->cmnd[0]) {
2220     	case INQUIRY:
2221     	{
2222     		struct	ahc_devinfo devinfo;
2223     		struct	scsi_inquiry *inq;
2224     		struct	scsi_inquiry_data *sid;
2225     		struct	ahc_initiator_tinfo *targ_info;
2226     		struct	ahc_tmode_tstate *tstate;
2227     		struct	ahc_syncrate *syncrate;
2228     		struct	ahc_linux_device *dev;
2229     		u_int	scsiid;
2230     		u_int	maxsync;
2231     		int	transferred_len;
2232     		int	minlen;
2233     		u_int	width;
2234     		u_int	period;
2235     		u_int	offset;
2236     		u_int	ppr_options;
2237     
2238     		 /*
2239     		  * Validate the command.  We only want to filter
2240     		  * standard inquiry commands, not those querying
2241     		  * Vital Product Data.
2242     		  */
2243     		inq = (struct scsi_inquiry *)cmd->cmnd;
2244     		if ((inq->byte2 & SI_EVPD) != 0
2245     		 || inq->page_code != 0)
2246     			break;
2247     
2248     		if (cmd->use_sg != 0) {
2249     			printf("%s: SG Inquiry response ignored\n",
2250     			       ahc_name(ahc));
2251     			break;
2252     		}
2253     		transferred_len = ahc_get_transfer_length(scb)
2254     				- ahc_get_residual(scb);
2255     		sid = (struct scsi_inquiry_data *)cmd->request_buffer;
2256     
2257     		/*
2258     		 * Determine if this lun actually exists.  If so,
2259     		 * hold on to its corresponding device structure.
2260     		 * If not, make sure we release the device and
2261     		 * don't bother processing the rest of this inquiry
2262     		 * command.
2263     		 */
2264     		dev = ahc_linux_get_device(ahc, cmd->channel,
2265     					   cmd->target, cmd->lun,
2266     					   /*alloc*/FALSE);
2267     		if (transferred_len >= 1
2268     		 && SID_QUAL(sid) == SID_QUAL_LU_CONNECTED) {
2269     
2270     			dev->flags &= ~AHC_DEV_UNCONFIGURED;
2271     		} else {
2272     			dev->flags |= AHC_DEV_UNCONFIGURED;
2273     			break;
2274     		}
2275     
2276     		/*
2277     		 * Update our notion of this device's transfer
2278     		 * negotiation capabilities.
2279     		 */
2280     		scsiid = BUILD_SCSIID(ahc, cmd);
2281     		ahc_compile_devinfo(&devinfo, SCSIID_OUR_ID(scsiid),
2282     				    cmd->target, cmd->lun,
2283     				    SCSIID_CHANNEL(ahc, scsiid),
2284     				    ROLE_INITIATOR);
2285     		targ_info = ahc_fetch_transinfo(ahc, devinfo.channel,
2286     						devinfo.our_scsiid,
2287     						devinfo.target, &tstate);
2288     		width = targ_info->user.width;
2289     		period = targ_info->user.period;
2290     		offset = targ_info->user.offset;
2291     		ppr_options = targ_info->user.ppr_options;
2292     		minlen = offsetof(struct scsi_inquiry_data, version) + 1;
2293     		if (transferred_len >= minlen) {
2294     			targ_info->curr.protocol_version = SID_ANSI_REV(sid);
2295     
2296     			/*
2297     			 * Only attempt SPI3 once we've verified that
2298     			 * the device claims to support SPI3 features.
2299     			 */
2300     			if (targ_info->curr.protocol_version < SCSI_REV_2)
2301     				targ_info->curr.transport_version =
2302     				    SID_ANSI_REV(sid);
2303     			else
2304     				targ_info->curr.transport_version =
2305     				     SCSI_REV_2;
2306     		}
2307     
2308     		minlen = offsetof(struct scsi_inquiry_data, flags) + 1;
2309     		if (transferred_len >= minlen
2310     		 && (sid->additional_length + 4) >= minlen) {
2311     			if ((sid->flags & SID_WBus16) == 0)
2312     				width = MSG_EXT_WDTR_BUS_8_BIT;
2313     			if ((sid->flags & SID_Sync) == 0) {
2314     				period = 0;
2315     				offset = 0;
2316     				ppr_options = 0;
2317     			}
2318     		} else {
2319     			/* Keep current settings */
2320     			break;
2321     		}
2322     		minlen = offsetof(struct scsi_inquiry_data, spi3data) + 1;
2323     		/*
2324     		 * This is a kludge to deal with inquiry requests that
2325     		 * are not large enough for us to pull the spi3 bits.
2326     		 * In this case, we assume that a device that tells us
2327     		 * they can provide inquiry data that spans the SPI3
2328     		 * bits can handle a PPR request.  If the inquiry
2329     		 * request has sufficient buffer space to cover these
2330     		 * bits, we check them to see if any ppr options are
2331     		 * available.
2332     		 */
2333     		if ((sid->additional_length + 4) >= minlen) {
2334     			if (transferred_len >= minlen
2335     			 && (sid->spi3data & SID_SPI_CLOCK_DT) == 0)
2336     				ppr_options = 0;
2337     
2338     			if (targ_info->curr.protocol_version > SCSI_REV_2)
2339     				targ_info->curr.transport_version = 3;
2340     		} else {
2341     			ppr_options = 0;
2342     		}
2343     		ahc_validate_width(ahc, /*tinfo limit*/NULL, &width,
2344     				   ROLE_UNKNOWN);
2345     		if ((ahc->features & AHC_ULTRA2) != 0)
2346     			maxsync = AHC_SYNCRATE_DT;
2347     		else if ((ahc->features & AHC_ULTRA) != 0)
2348     			maxsync = AHC_SYNCRATE_ULTRA;
2349     		else
2350     			maxsync = AHC_SYNCRATE_FAST;
2351     
2352     		syncrate = ahc_find_syncrate(ahc, &period,
2353     					     &ppr_options, maxsync);
2354     		ahc_validate_offset(ahc, /*tinfo limit*/NULL, syncrate,
2355     				    &offset, width, ROLE_UNKNOWN);
2356     		if (offset == 0 || period == 0) {
2357     			period = 0;
2358     			offset = 0;
2359     			ppr_options = 0;
2360     		}
2361     		/* Apply our filtered user settings. */
2362     		ahc_set_width(ahc, &devinfo, width,
2363     			      AHC_TRANS_GOAL, /*paused*/FALSE);
2364     		ahc_set_syncrate(ahc, &devinfo, syncrate, period,
2365     				 offset, ppr_options, AHC_TRANS_GOAL,
2366     				 /*paused*/FALSE);
2367     		break;
2368     	}
2369     	default:
2370     		panic("ahc_linux_filter_command: Unexpected Command type  %x\n",
2371     		      cmd->cmnd[0]);
2372     		break;
2373     	}
2374     }
2375     
2376     static void
2377     ahc_linux_sem_timeout(u_long arg)
2378     {
2379     	struct semaphore *sem;
2380     
2381     	sem = (struct semaphore *)arg;
2382     	up(sem);
2383     }
2384     
2385     static void
2386     ahc_linux_freeze_sim_queue(struct ahc_softc *ahc)
2387     {
2388     	ahc->platform_data->qfrozen++;
2389     	if (ahc->platform_data->qfrozen == 1)
2390     		scsi_block_requests(ahc->platform_data->host);
2391     }
2392     
2393     static void
2394     ahc_linux_release_sim_queue(u_long arg)
2395     {
2396     	struct ahc_softc *ahc;
2397     	u_long s;
2398     	int    unblock_reqs;
2399     
2400     	ahc = (struct ahc_softc *)arg;
2401     	unblock_reqs = 0;
2402     	ahc_lock(ahc, &s);
2403     	if (ahc->platform_data->qfrozen > 0)
2404     		ahc->platform_data->qfrozen--;
2405     	if (ahc->platform_data->qfrozen == 0) {
2406     		unblock_reqs = 1;
2407     		ahc_linux_run_device_queues(ahc);
2408     	}
2409     	ahc_unlock(ahc, &s);
2410     	/*
2411     	 * There is still a race here.  The mid-layer
2412     	 * should keep its own freeze count and use
2413     	 * a bottom half handler to run the queues
2414     	 * so we can unblock with our own lock held.
2415     	 */
2416     	if (unblock_reqs)
2417     		scsi_unblock_requests(ahc->platform_data->host);
2418     }
2419     
2420     static int
2421     ahc_linux_queue_recovery_cmd(Scsi_Cmnd *cmd, scb_flag flag)
2422     {
2423     	struct ahc_softc *ahc;
2424     	struct ahc_cmd *acmd;
2425     	struct ahc_cmd *list_acmd;
2426     	struct ahc_linux_device *dev;
2427     	struct scb *pending_scb;
2428     	u_long s;
2429     	u_int  saved_scbptr;
2430     	u_int  active_scb_index;
2431     	u_int  last_phase;
2432     	int    retval;
2433     	int    paused;
2434     	int    wait;
2435     	int    disconnected;
2436     
2437     	paused = FALSE;
2438     	wait = FALSE;
2439     	ahc = *(struct ahc_softc **)cmd->host->hostdata;
2440     	acmd = (struct ahc_cmd *)cmd;
2441     
2442     	printf("%s:%d:%d:%d: Attempting to queue a%s message\n",
2443     	       ahc_name(ahc), cmd->channel, cmd->target, cmd->lun,
2444     	       flag == SCB_ABORT ? "n ABORT" : " TARGET RESET");
2445     
2446     	/*
2447     	 * It is a bug that the upper layer takes
2448     	 * this lock just prior to calling us.
2449     	 */
2450     	spin_unlock_irq(&io_request_lock);
2451     
2452     	ahc_lock(ahc, &s);
2453     
2454     	/*
2455     	 * First determine if we currently own this command.
2456     	 * Start by searching the device queue.  If not found
2457     	 * there, check the pending_scb list.  If not found
2458     	 * at all, and the system wanted us to just abort the
2459     	 * command return success.
2460     	 */
2461     	dev = ahc_linux_get_device(ahc, cmd->channel, cmd->target,
2462     				   cmd->lun, /*alloc*/FALSE);
2463     
2464     	if (dev == NULL) {
2465     		/*
2466     		 * No target device for this command exists,
2467     		 * so we must not still own the command.
2468     		 */
2469     		printf("%s:%d:%d:%d: Is not an active device\n",
2470     		       ahc_name(ahc), cmd->channel, cmd->target, cmd->lun);
2471     		retval = SUCCESS;
2472     		goto no_cmd;
2473     	}
2474     
2475     	TAILQ_FOREACH(list_acmd, &dev->busyq, acmd_links.tqe) {
2476     		if (list_acmd == acmd)
2477     			break;
2478     	}
2479     
2480     	if (list_acmd != NULL) {
2481     		printf("%s:%d:%d:%d: Command found on device queue\n",
2482     		       ahc_name(ahc), cmd->channel, cmd->target, cmd->lun);
2483     		if (flag == SCB_ABORT) {
2484     			TAILQ_REMOVE(&dev->busyq, list_acmd, acmd_links.tqe);
2485     			cmd->result = DID_ABORT << 16;
2486     			ahc_linux_queue_cmd_complete(ahc, cmd);
2487     			retval = SUCCESS;
2488     			goto done;
2489     		}
2490     	}
2491     
2492     	/*
2493     	 * See if we can find a matching cmd in the pending list.
2494     	 */
2495     	LIST_FOREACH(pending_scb, &ahc->pending_scbs, pending_links) {
2496     		if (pending_scb->io_ctx == cmd)
2497     			break;
2498     	}
2499     
2500     	if (pending_scb == NULL && flag == SCB_DEVICE_RESET) {
2501     
2502     		/* Any SCB for this device will do for a target reset */
2503     		LIST_FOREACH(pending_scb, &ahc->pending_scbs, pending_links) {
2504     		  	if (ahc_match_scb(ahc, pending_scb, cmd->target,
2505     					  cmd->channel, CAM_LUN_WILDCARD,
2506     					  SCB_LIST_NULL, ROLE_INITIATOR) == 0)
2507     				break;
2508     		}
2509     	}
2510     
2511     	if (pending_scb == NULL) {
2512     		printf("%s:%d:%d:%d: Command not found\n",
2513     		       ahc_name(ahc), cmd->channel, cmd->target, cmd->lun);
2514     		goto no_cmd;
2515     	}
2516     
2517     	if ((pending_scb->flags & SCB_RECOVERY_SCB) != 0) {
2518     		/*
2519     		 * We can't queue two recovery actions using the same SCB
2520     		 */
2521     		retval = FAILED;
2522     		goto  done;
2523     	}
2524     
2525     	/*
2526     	 * Ensure that the card doesn't do anything
2527     	 * behind our back.  Also make sure that we
2528     	 * didn't "just" miss an interrupt that would
2529     	 * affect this cmd.
2530     	 */
2531     	ahc->flags |= AHC_ALL_INTERRUPTS;
2532     	do {
2533     		ahc_intr(ahc);
2534     		ahc_pause(ahc);
2535     		ahc_clear_critical_section(ahc);
2536     	} while (ahc_inb(ahc, INTSTAT) & INT_PEND);
2537     	ahc->flags &= ~AHC_ALL_INTERRUPTS;
2538     	paused = TRUE;
2539     
2540     	if (bootverbose)
2541     		ahc_dump_card_state(ahc);
2542     
2543     	if ((pending_scb->flags & SCB_ACTIVE) == 0) {
2544     		printf("%s:%d:%d:%d: Command already completed\n",
2545     		       ahc_name(ahc), cmd->channel, cmd->target, cmd->lun);
2546     		goto no_cmd;
2547     	}
2548     
2549     	disconnected = TRUE;
2550     	if (flag == SCB_ABORT) {
2551     		if (ahc_search_qinfifo(ahc, cmd->target, cmd->channel + 'A',
2552     				       cmd->lun, pending_scb->hscb->tag,
2553     				       ROLE_INITIATOR, CAM_REQ_ABORTED,
2554     				       SEARCH_COMPLETE) > 0) {
2555     			printf("%s:%d:%d:%d: Cmd aborted from QINFIFO\n",
2556     			       ahc_name(ahc), cmd->channel, cmd->target,
2557     					cmd->lun);
2558     			retval = SUCCESS;
2559     			goto done;
2560     		}
2561     	} else if (ahc_search_qinfifo(ahc, cmd->target, cmd->channel + 'A',
2562     				      cmd->lun, pending_scb->hscb->tag,
2563     				      ROLE_INITIATOR, /*status*/0,
2564     				      SEARCH_COUNT) > 0) {
2565     		disconnected = FALSE;
2566     	}
2567     
2568     	/*
2569     	 * At this point, pending_scb is the scb associated with the
2570     	 * passed in command.  That command is currently active on the
2571     	 * bus, is in the disconnected state, or we're hoping to find
2572     	 * a command for the same target active on the bus to abuse to
2573     	 * send a BDR.  Queue the appropriate message based on which of
2574     	 * these states we are in.
2575     	 */
2576     	last_phase = ahc_inb(ahc, LASTPHASE);
2577     	saved_scbptr = ahc_inb(ahc, SCBPTR);
2578     	active_scb_index = ahc_inb(ahc, SCB_TAG);
2579     	if (last_phase != P_BUSFREE
2580     	 && (pending_scb->hscb->tag == active_scb_index
2581     	  || (flag == SCB_DEVICE_RESET
2582     	   && SCSIID_TARGET(ahc, ahc_inb(ahc, SAVED_SCSIID)) == cmd->target))) {
2583     
2584     		/*
2585     		 * We're active on the bus, so assert ATN
2586     		 * and hope that the target responds.
2587     		 */
2588     		pending_scb = ahc_lookup_scb(ahc, active_scb_index);
2589     		pending_scb->flags |= SCB_RECOVERY_SCB|flag;
2590     		ahc_outb(ahc, MSG_OUT, HOST_MSG);
2591     		ahc_outb(ahc, SCSISIGO, last_phase|ATNO);
2592     		printf("%s:%d:%d:%d: Device is active, asserting ATN\n",
2593     		       ahc_name(ahc), cmd->channel, cmd->target, cmd->lun);
2594     		wait = TRUE;
2595     	} else if (disconnected) {
2596     
2597     		/*
2598     		 * Actually re-queue this SCB in an attempt
2599     		 * to select the device before it reconnects.
2600     		 * In either case (selection or reselection),
2601     		 * we will now issue a the approprate message
2602     		 * to the timed-out device.
2603     		 *
2604     		 * Set the MK_MESSAGE control bit indicating
2605     		 * that we desire to send a message.  We
2606     		 * also set the disconnected flag since
2607     		 * in the paging case there is no guarantee
2608     		 * that our SCB control byte matches the
2609     		 * version on the card.  We don't want the
2610     		 * sequencer to abort the command thinking
2611     		 * an unsolicited reselection occurred.
2612     		 */
2613     		pending_scb->hscb->control |= MK_MESSAGE|DISCONNECTED;
2614     		pending_scb->flags |= SCB_RECOVERY_SCB|flag;
2615     
2616     		/*
2617     		 * Remove any cached copy of this SCB in the
2618     		 * disconnected list in preparation for the
2619     		 * queuing of our abort SCB.  We use the
2620     		 * same element in the SCB, SCB_NEXT, for
2621     		 * both the qinfifo and the disconnected list.
2622     		 */
2623     		ahc_search_disc_list(ahc, cmd->target, cmd->channel + 'A',
2624     				     cmd->lun, pending_scb->hscb->tag,
2625     				     /*stop_on_first*/TRUE,
2626     				     /*remove*/TRUE,
2627     				     /*save_state*/FALSE);
2628     
2629     		/*
2630     		 * In the non-paging case, the sequencer will
2631     		 * never re-reference the in-core SCB.
2632     		 * To make sure we are notified during
2633     		 * reslection, set the MK_MESSAGE flag in
2634     		 * the card's copy of the SCB.
2635     		 */
2636     		if ((ahc->flags & AHC_PAGESCBS) == 0) {
2637     			ahc_outb(ahc, SCBPTR, pending_scb->hscb->tag);
2638     			ahc_outb(ahc, SCB_CONTROL,
2639     				 ahc_inb(ahc, SCB_CONTROL)|MK_MESSAGE);
2640     		}
2641     
2642     		/*
2643     		 * Clear out any entries in the QINFIFO first
2644     		 * so we are the next SCB for this target
2645     		 * to run.
2646     		 */
2647     		ahc_search_qinfifo(ahc, cmd->target, cmd->channel + 'A',
2648     				   cmd->lun, SCB_LIST_NULL, ROLE_INITIATOR,
2649     				   CAM_REQUEUE_REQ, SEARCH_COMPLETE);
2650     		ahc_print_path(ahc, pending_scb);
2651     		printf("Queuing a recovery SCB\n");
2652     		ahc_qinfifo_requeue_tail(ahc, pending_scb);
2653     		ahc_outb(ahc, SCBPTR, saved_scbptr);
2654     		printf("%s:%d:%d:%d: Device is disconnected, re-queuing SCB\n",
2655     		       ahc_name(ahc), cmd->channel, cmd->target, cmd->lun);
2656     		wait = TRUE;
2657     	} else {
2658     		printf("%s:%d:%d:%d: Unable to deliver message\n",
2659     		       ahc_name(ahc), cmd->channel, cmd->target, cmd->lun);
2660     		retval = FAILED;
2661     		goto done;
2662     	}
2663     
2664     no_cmd:
2665     	/*
2666     	 * Our assumption is that if we don't have the command, no
2667     	 * recovery action was required, so we return success.  Again,
2668     	 * the semantics of the mid-layer recovery engine are not
2669     	 * well defined, so this may change in time.
2670     	 */
2671     	retval = SUCCESS;
2672     done:
2673     	if (paused)
2674     		ahc_unpause(ahc);
2675     	if (wait) {
2676         		struct timer_list timer;
2677     		int ret;
2678     
2679     		ahc_unlock(ahc, &s);
2680     		init_timer(&timer);
2681     		timer.data = (u_long)&ahc->platform_data->eh_sem;
2682     		timer.expires = jiffies + (5 * HZ);
2683     		timer.function = ahc_linux_sem_timeout;
2684     		add_timer(&timer);
2685     		printf("Recovery code sleeping\n");
2686     		down(&ahc->platform_data->eh_sem);
2687     		printf("Recovery code awake\n");
2688             	ret = del_timer(&timer);
2689     		if (ret == 0) {
2690     			printf("Timer Expired\n");
2691     			retval = FAILED;
2692     		}
2693     		ahc_lock(ahc, &s);
2694     	}
2695     	ahc_linux_run_device_queues(ahc);
2696     	acmd = TAILQ_FIRST(&ahc->platform_data->completeq);
2697     	TAILQ_INIT(&ahc->platform_data->completeq);
2698     	ahc_unlock(ahc, &s);
2699     	if (acmd != NULL)
2700     		ahc_linux_run_complete_queue(ahc, acmd);
2701     	spin_lock_irq(&io_request_lock);
2702     	return (retval);
2703     }
2704     
2705     /*
2706      * Abort the current SCSI command(s).
2707      */
2708     int
2709     ahc_linux_abort(Scsi_Cmnd *cmd)
2710     {
2711     	int error;
2712     
2713     	error = ahc_linux_queue_recovery_cmd(cmd, SCB_ABORT);
2714     	if (error != 0)
2715     		printf("aic7xxx_abort returns %d\n", error);
2716     	return (error);
2717     }
2718     
2719     /*
2720      * Attempt to send a target reset message to the device that timed out.
2721      */
2722     int
2723     ahc_linux_dev_reset(Scsi_Cmnd *cmd)
2724     {
2725     	int error;
2726     
2727     	error = ahc_linux_queue_recovery_cmd(cmd, SCB_DEVICE_RESET);
2728     	if (error != 0)
2729     		printf("aic7xxx_dev_reset returns %d\n", error);
2730     	return (error);
2731     }
2732     
2733     /*
2734      * Reset the SCSI bus.
2735      */
2736     int
2737     ahc_linux_bus_reset(Scsi_Cmnd *cmd)
2738     {
2739     	struct ahc_softc *ahc;
2740     	struct ahc_cmd *acmd;
2741     	u_long s;
2742     	int    found;
2743     
2744     	/*
2745     	 * It is a bug that the upper layer takes
2746     	 * this lock just prior to calling us.
2747     	 */
2748     	spin_unlock_irq(&io_request_lock);
2749     
2750     	ahc = *(struct ahc_softc **)cmd->host->hostdata;
2751     	ahc_lock(ahc, &s);
2752     	found = ahc_reset_channel(ahc, cmd->channel + 'A',
2753     				  /*initiate reset*/TRUE);
2754     	acmd = TAILQ_FIRST(&ahc->platform_data->completeq);
2755     	TAILQ_INIT(&ahc->platform_data->completeq);
2756     	ahc_unlock(ahc, &s);
2757     	if (bootverbose)
2758     		printf("%s: SCSI bus reset delivered. "
2759     		       "%d SCBs aborted.\n", ahc_name(ahc), found);
2760     
2761     	if (acmd != NULL)
2762     		ahc_linux_run_complete_queue(ahc, acmd);
2763     
2764     	spin_lock_irq(&io_request_lock);
2765     	return SUCCESS;
2766     }
2767     
2768     /*
2769      * Return the disk geometry for the given SCSI device.
2770      */
2771     int
2772     ahc_linux_biosparam(Disk *disk, kdev_t dev, int geom[])
2773     {
2774     	int	heads;
2775     	int	sectors;
2776     	int	cylinders;
2777     	int	ret;
2778     	int	extended;
2779     	struct	ahc_softc *ahc;
2780     	struct	buffer_head *bh;
2781     
2782     	ahc = *((struct ahc_softc **)disk->device->host->hostdata);
2783     	bh = bread(MKDEV(MAJOR(dev), MINOR(dev) & ~0xf), 0, 1024);
2784     
2785     	if (bh) {
2786     		ret = scsi_partsize(bh, disk->capacity,
2787     				    &geom[2], &geom[0], &geom[1]);
2788     		brelse(bh);
2789     		if (ret != -1)
2790     			return (ret);
2791     	}
2792     	heads = 64;
2793     	sectors = 32;
2794     	cylinders = disk->capacity / (heads * sectors);
2795     
2796     	if (disk->device->channel == 0)
2797     		extended = (ahc->flags & AHC_EXTENDED_TRANS_A) != 0;
2798     	else
2799     		extended = (ahc->flags & AHC_EXTENDED_TRANS_B) != 0;
2800     	if (extended && cylinders >= 1024) {
2801     		heads = 255;
2802     		sectors = 63;
2803     		cylinders = disk->capacity / (heads * sectors);
2804     	}
2805     	geom[0] = heads;
2806     	geom[1] = sectors;
2807     	geom[2] = cylinders;
2808     	return (0);
2809     }
2810     
2811     /*
2812      * Free the passed in Scsi_Host memory structures prior to unloading the
2813      * module.
2814      */
2815     int
2816     ahc_linux_release(struct Scsi_Host * host)
2817     {
2818     	struct ahc_softc *ahc;
2819     
2820     	if (host != NULL) {
2821     
2822     		ahc = *(struct ahc_softc **)host->hostdata;
2823     		ahc_free(ahc);
2824     	}
2825     	if (TAILQ_EMPTY(&ahc_tailq)) {
2826     		unregister_reboot_notifier(&ahc_linux_notifier);
2827     #ifdef CONFIG_PCI
2828     #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0)
2829     		pci_unregister_driver(&aic7xxx_pci_driver);
2830     #endif
2831     #endif
2832     	}
2833     	return (0);
2834     }
2835     
2836     void
2837     ahc_platform_dump_card_state(struct ahc_softc *ahc)
2838     {
2839     	struct ahc_linux_device *dev;
2840     	int channel;
2841     	int maxchannel;
2842     	int target;
2843     	int maxtarget;
2844     	int lun;
2845     	int i;
2846     
2847     	maxchannel = (ahc->features & AHC_TWIN) ? 1 : 0;
2848     	maxtarget = (ahc->features & AHC_WIDE) ? 15 : 7;
2849     	for (channel = 0; channel <= maxchannel; channel++) {
2850     		for (target = 0; target <=maxtarget; target++) {
2851     			for (lun = 0; lun < AHC_NUM_LUNS; lun++) {
2852     				struct ahc_cmd *acmd;
2853     
2854     				dev = ahc_linux_get_device(ahc, channel, target,
2855     							   lun, /*alloc*/FALSE);
2856     				if (dev == NULL)
2857     					continue;
2858     
2859     				printf("DevQ(%d:%d:%d): ",
2860     				       channel, target, lun);
2861     				i = 0;
2862     				TAILQ_FOREACH(acmd, &dev->busyq,
2863     					      acmd_links.tqe) {
2864     					if (i++ > 256)
2865     						break;
2866     				}
2867     				printf("%d waiting\n", i);
2868     			}
2869     		}
2870     	}
2871     }
2872     
2873     #if defined(MODULE) || LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0)
2874     static Scsi_Host_Template driver_template = AIC7XXX;
2875     Scsi_Host_Template *aic7xxx_driver_template = &driver_template;
2876     #include "../scsi_module.c"
2877     #endif
2878