patch-2_6_7-vs1_9_1_12
[linux-2.6.git] / drivers / scsi / aic7xxx / aic7xxx_osm.c
1 /*
2  * Adaptec AIC7xxx device driver for Linux.
3  *
4  * $Id: //depot/aic7xxx/linux/drivers/scsi/aic7xxx/aic7xxx_osm.c#235 $
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-2000 Justin T. Gibbs.
42  * Copyright (c) 2000-2001 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. Redistributions in binary form must reproduce at minimum a disclaimer
52  *    substantially similar to the "NO WARRANTY" disclaimer below
53  *    ("Disclaimer") and any redistribution must be conditioned upon
54  *    including a substantially similar Disclaimer requirement for further
55  *    binary redistribution.
56  * 3. Neither the names of the above-listed copyright holders nor the names
57  *    of any contributors may be used to endorse or promote products derived
58  *    from this software without specific prior written permission.
59  *
60  * Alternatively, this software may be distributed under the terms of the
61  * GNU General Public License ("GPL") version 2 as published by the Free
62  * Software Foundation.
63  *
64  * NO WARRANTY
65  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
66  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
67  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
68  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
69  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
70  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
71  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
72  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
73  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
74  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
75  * POSSIBILITY OF SUCH DAMAGES.
76  *
77  *---------------------------------------------------------------------------
78  *
79  *  Thanks also go to (in alphabetical order) the following:
80  *
81  *    Rory Bolt     - Sequencer bug fixes
82  *    Jay Estabrook - Initial DEC Alpha support
83  *    Doug Ledford  - Much needed abort/reset bug fixes
84  *    Kai Makisara  - DMAing of SCBs
85  *
86  *  A Boot time option was also added for not resetting the scsi bus.
87  *
88  *    Form:  aic7xxx=extended
89  *           aic7xxx=no_reset
90  *           aic7xxx=verbose
91  *
92  *  Daniel M. Eischen, deischen@iworks.InterWorks.org, 1/23/97
93  *
94  *  Id: aic7xxx.c,v 4.1 1997/06/12 08:23:42 deang Exp
95  */
96
97 /*
98  * Further driver modifications made by Doug Ledford <dledford@redhat.com>
99  *
100  * Copyright (c) 1997-1999 Doug Ledford
101  *
102  * These changes are released under the same licensing terms as the FreeBSD
103  * driver written by Justin Gibbs.  Please see his Copyright notice above
104  * for the exact terms and conditions covering my changes as well as the
105  * warranty statement.
106  *
107  * Modifications made to the aic7xxx.c,v 4.1 driver from Dan Eischen include
108  * but are not limited to:
109  *
110  *  1: Import of the latest FreeBSD sequencer code for this driver
111  *  2: Modification of kernel code to accommodate different sequencer semantics
112  *  3: Extensive changes throughout kernel portion of driver to improve
113  *     abort/reset processing and error hanndling
114  *  4: Other work contributed by various people on the Internet
115  *  5: Changes to printk information and verbosity selection code
116  *  6: General reliability related changes, especially in IRQ management
117  *  7: Modifications to the default probe/attach order for supported cards
118  *  8: SMP friendliness has been improved
119  *
120  */
121
122 #include "aic7xxx_osm.h"
123 #include "aic7xxx_inline.h"
124 #include <scsi/scsicam.h>
125
126 /*
127  * Include aiclib.c as part of our
128  * "module dependencies are hard" work around.
129  */
130 #include "aiclib.c"
131
132 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,3,0)
133 #include <linux/init.h>         /* __setup */
134 #endif
135
136
137 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
138 #include "sd.h"                 /* For geometry detection */
139 #endif
140
141 #include <linux/mm.h>           /* For fetching system memory size */
142 #include <linux/blkdev.h>               /* For block_size() */
143
144 /*
145  * Lock protecting manipulation of the ahc softc list.
146  */
147 spinlock_t ahc_list_spinlock;
148
149 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
150 /* For dynamic sglist size calculation. */
151 u_int ahc_linux_nseg;
152 #endif
153
154 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,3,0)
155 struct proc_dir_entry proc_scsi_aic7xxx = {
156         PROC_SCSI_AIC7XXX, 7, "aic7xxx",
157         S_IFDIR | S_IRUGO | S_IXUGO, 2,
158         0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL
159 };
160 #endif
161
162 /*
163  * Set this to the delay in seconds after SCSI bus reset.
164  * Note, we honor this only for the initial bus reset.
165  * The scsi error recovery code performs its own bus settle
166  * delay handling for error recovery actions.
167  */
168 #ifdef CONFIG_AIC7XXX_RESET_DELAY_MS
169 #define AIC7XXX_RESET_DELAY CONFIG_AIC7XXX_RESET_DELAY_MS
170 #else
171 #define AIC7XXX_RESET_DELAY 5000
172 #endif
173
174 /*
175  * Control collection of SCSI transfer statistics for the /proc filesystem.
176  *
177  * NOTE: Do NOT enable this when running on kernels version 1.2.x and below.
178  * NOTE: This does affect performance since it has to maintain statistics.
179  */
180 #ifdef CONFIG_AIC7XXX_PROC_STATS
181 #define AIC7XXX_PROC_STATS
182 #endif
183
184 /*
185  * To change the default number of tagged transactions allowed per-device,
186  * add a line to the lilo.conf file like:
187  * append="aic7xxx=verbose,tag_info:{{32,32,32,32},{32,32,32,32}}"
188  * which will result in the first four devices on the first two
189  * controllers being set to a tagged queue depth of 32.
190  *
191  * The tag_commands is an array of 16 to allow for wide and twin adapters.
192  * Twin adapters will use indexes 0-7 for channel 0, and indexes 8-15
193  * for channel 1.
194  */
195 typedef struct {
196         uint8_t tag_commands[16];       /* Allow for wide/twin adapters. */
197 } adapter_tag_info_t;
198
199 /*
200  * Modify this as you see fit for your system.
201  *
202  * 0                    tagged queuing disabled
203  * 1 <= n <= 253        n == max tags ever dispatched.
204  *
205  * The driver will throttle the number of commands dispatched to a
206  * device if it returns queue full.  For devices with a fixed maximum
207  * queue depth, the driver will eventually determine this depth and
208  * lock it in (a console message is printed to indicate that a lock
209  * has occurred).  On some devices, queue full is returned for a temporary
210  * resource shortage.  These devices will return queue full at varying
211  * depths.  The driver will throttle back when the queue fulls occur and
212  * attempt to slowly increase the depth over time as the device recovers
213  * from the resource shortage.
214  *
215  * In this example, the first line will disable tagged queueing for all
216  * the devices on the first probed aic7xxx adapter.
217  *
218  * The second line enables tagged queueing with 4 commands/LUN for IDs
219  * (0, 2-11, 13-15), disables tagged queueing for ID 12, and tells the
220  * driver to attempt to use up to 64 tags for ID 1.
221  *
222  * The third line is the same as the first line.
223  *
224  * The fourth line disables tagged queueing for devices 0 and 3.  It
225  * enables tagged queueing for the other IDs, with 16 commands/LUN
226  * for IDs 1 and 4, 127 commands/LUN for ID 8, and 4 commands/LUN for
227  * IDs 2, 5-7, and 9-15.
228  */
229
230 /*
231  * NOTE: The below structure is for reference only, the actual structure
232  *       to modify in order to change things is just below this comment block.
233 adapter_tag_info_t aic7xxx_tag_info[] =
234 {
235         {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
236         {{4, 64, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 4, 4}},
237         {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
238         {{0, 16, 4, 0, 16, 4, 4, 4, 127, 4, 4, 4, 4, 4, 4, 4}}
239 };
240 */
241
242 #ifdef CONFIG_AIC7XXX_CMDS_PER_DEVICE
243 #define AIC7XXX_CMDS_PER_DEVICE CONFIG_AIC7XXX_CMDS_PER_DEVICE
244 #else
245 #define AIC7XXX_CMDS_PER_DEVICE AHC_MAX_QUEUE
246 #endif
247
248 #define AIC7XXX_CONFIGED_TAG_COMMANDS {                                 \
249         AIC7XXX_CMDS_PER_DEVICE, AIC7XXX_CMDS_PER_DEVICE,               \
250         AIC7XXX_CMDS_PER_DEVICE, AIC7XXX_CMDS_PER_DEVICE,               \
251         AIC7XXX_CMDS_PER_DEVICE, AIC7XXX_CMDS_PER_DEVICE,               \
252         AIC7XXX_CMDS_PER_DEVICE, AIC7XXX_CMDS_PER_DEVICE,               \
253         AIC7XXX_CMDS_PER_DEVICE, AIC7XXX_CMDS_PER_DEVICE,               \
254         AIC7XXX_CMDS_PER_DEVICE, AIC7XXX_CMDS_PER_DEVICE,               \
255         AIC7XXX_CMDS_PER_DEVICE, AIC7XXX_CMDS_PER_DEVICE,               \
256         AIC7XXX_CMDS_PER_DEVICE, AIC7XXX_CMDS_PER_DEVICE                \
257 }
258
259 /*
260  * By default, use the number of commands specified by
261  * the users kernel configuration.
262  */
263 static adapter_tag_info_t aic7xxx_tag_info[] =
264 {
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         {AIC7XXX_CONFIGED_TAG_COMMANDS},
272         {AIC7XXX_CONFIGED_TAG_COMMANDS},
273         {AIC7XXX_CONFIGED_TAG_COMMANDS},
274         {AIC7XXX_CONFIGED_TAG_COMMANDS},
275         {AIC7XXX_CONFIGED_TAG_COMMANDS},
276         {AIC7XXX_CONFIGED_TAG_COMMANDS},
277         {AIC7XXX_CONFIGED_TAG_COMMANDS},
278         {AIC7XXX_CONFIGED_TAG_COMMANDS},
279         {AIC7XXX_CONFIGED_TAG_COMMANDS},
280         {AIC7XXX_CONFIGED_TAG_COMMANDS}
281 };
282
283 /*
284  * DV option:
285  *
286  * positive value = DV Enabled
287  * zero           = DV Disabled
288  * negative value = DV Default for adapter type/seeprom
289  */
290 #ifdef CONFIG_AIC7XXX_DV_SETTING
291 #define AIC7XXX_CONFIGED_DV CONFIG_AIC7XXX_DV_SETTING
292 #else
293 #define AIC7XXX_CONFIGED_DV -1
294 #endif
295
296 static int8_t aic7xxx_dv_settings[] =
297 {
298         AIC7XXX_CONFIGED_DV,
299         AIC7XXX_CONFIGED_DV,
300         AIC7XXX_CONFIGED_DV,
301         AIC7XXX_CONFIGED_DV,
302         AIC7XXX_CONFIGED_DV,
303         AIC7XXX_CONFIGED_DV,
304         AIC7XXX_CONFIGED_DV,
305         AIC7XXX_CONFIGED_DV,
306         AIC7XXX_CONFIGED_DV,
307         AIC7XXX_CONFIGED_DV,
308         AIC7XXX_CONFIGED_DV,
309         AIC7XXX_CONFIGED_DV,
310         AIC7XXX_CONFIGED_DV,
311         AIC7XXX_CONFIGED_DV,
312         AIC7XXX_CONFIGED_DV,
313         AIC7XXX_CONFIGED_DV
314 };
315
316 /*
317  * There should be a specific return value for this in scsi.h, but
318  * it seems that most drivers ignore it.
319  */
320 #define DID_UNDERFLOW   DID_ERROR
321
322 void
323 ahc_print_path(struct ahc_softc *ahc, struct scb *scb)
324 {
325         printk("(scsi%d:%c:%d:%d): ",
326                ahc->platform_data->host->host_no,
327                scb != NULL ? SCB_GET_CHANNEL(ahc, scb) : 'X',
328                scb != NULL ? SCB_GET_TARGET(ahc, scb) : -1,
329                scb != NULL ? SCB_GET_LUN(scb) : -1);
330 }
331
332 /*
333  * XXX - these options apply unilaterally to _all_ 274x/284x/294x
334  *       cards in the system.  This should be fixed.  Exceptions to this
335  *       rule are noted in the comments.
336  */
337
338 /*
339  * Skip the scsi bus reset.  Non 0 make us skip the reset at startup.  This
340  * has no effect on any later resets that might occur due to things like
341  * SCSI bus timeouts.
342  */
343 static uint32_t aic7xxx_no_reset;
344
345 /*
346  * Certain PCI motherboards will scan PCI devices from highest to lowest,
347  * others scan from lowest to highest, and they tend to do all kinds of
348  * strange things when they come into contact with PCI bridge chips.  The
349  * net result of all this is that the PCI card that is actually used to boot
350  * the machine is very hard to detect.  Most motherboards go from lowest
351  * PCI slot number to highest, and the first SCSI controller found is the
352  * one you boot from.  The only exceptions to this are when a controller
353  * has its BIOS disabled.  So, we by default sort all of our SCSI controllers
354  * from lowest PCI slot number to highest PCI slot number.  We also force
355  * all controllers with their BIOS disabled to the end of the list.  This
356  * works on *almost* all computers.  Where it doesn't work, we have this
357  * option.  Setting this option to non-0 will reverse the order of the sort
358  * to highest first, then lowest, but will still leave cards with their BIOS
359  * disabled at the very end.  That should fix everyone up unless there are
360  * really strange cirumstances.
361  */
362 static uint32_t aic7xxx_reverse_scan;
363
364 /*
365  * Should we force EXTENDED translation on a controller.
366  *     0 == Use whatever is in the SEEPROM or default to off
367  *     1 == Use whatever is in the SEEPROM or default to on
368  */
369 static uint32_t aic7xxx_extended;
370
371 /*
372  * PCI bus parity checking of the Adaptec controllers.  This is somewhat
373  * dubious at best.  To my knowledge, this option has never actually
374  * solved a PCI parity problem, but on certain machines with broken PCI
375  * chipset configurations where stray PCI transactions with bad parity are
376  * the norm rather than the exception, the error messages can be overwelming.
377  * It's included in the driver for completeness.
378  *   0     = Shut off PCI parity check
379  *   non-0 = reverse polarity pci parity checking
380  */
381 static uint32_t aic7xxx_pci_parity = ~0;
382
383 /*
384  * Certain newer motherboards have put new PCI based devices into the
385  * IO spaces that used to typically be occupied by VLB or EISA cards.
386  * This overlap can cause these newer motherboards to lock up when scanned
387  * for older EISA and VLB devices.  Setting this option to non-0 will
388  * cause the driver to skip scanning for any VLB or EISA controllers and
389  * only support the PCI controllers.  NOTE: this means that if the kernel
390  * os compiled with PCI support disabled, then setting this to non-0
391  * would result in never finding any devices :)
392  */
393 #ifndef CONFIG_AIC7XXX_PROBE_EISA_VL
394 uint32_t aic7xxx_probe_eisa_vl;
395 #else
396 uint32_t aic7xxx_probe_eisa_vl = ~0;
397 #endif
398
399 /*
400  * There are lots of broken chipsets in the world.  Some of them will
401  * violate the PCI spec when we issue byte sized memory writes to our
402  * controller.  I/O mapped register access, if allowed by the given
403  * platform, will work in almost all cases.
404  */
405 uint32_t aic7xxx_allow_memio = ~0;
406
407 /*
408  * aic7xxx_detect() has been run, so register all device arrivals
409  * immediately with the system rather than deferring to the sorted
410  * attachment performed by aic7xxx_detect().
411  */
412 int aic7xxx_detect_complete;
413
414 /*
415  * So that we can set how long each device is given as a selection timeout.
416  * The table of values goes like this:
417  *   0 - 256ms
418  *   1 - 128ms
419  *   2 - 64ms
420  *   3 - 32ms
421  * We default to 256ms because some older devices need a longer time
422  * to respond to initial selection.
423  */
424 static uint32_t aic7xxx_seltime;
425
426 /*
427  * Certain devices do not perform any aging on commands.  Should the
428  * device be saturated by commands in one portion of the disk, it is
429  * possible for transactions on far away sectors to never be serviced.
430  * To handle these devices, we can periodically send an ordered tag to
431  * force all outstanding transactions to be serviced prior to a new
432  * transaction.
433  */
434 uint32_t aic7xxx_periodic_otag;
435
436 /*
437  * Module information and settable options.
438  */
439 #ifdef MODULE
440 static char *aic7xxx = NULL;
441 /*
442  * Just in case someone uses commas to separate items on the insmod
443  * command line, we define a dummy buffer here to avoid having insmod
444  * write wild stuff into our code segment
445  */
446 static char dummy_buffer[60] = "Please don't trounce on me insmod!!\n";
447
448 MODULE_AUTHOR("Maintainer: Justin T. Gibbs <gibbs@scsiguy.com>");
449 MODULE_DESCRIPTION("Adaptec Aic77XX/78XX SCSI Host Bus Adapter driver");
450 #ifdef MODULE_LICENSE
451 MODULE_LICENSE("Dual BSD/GPL");
452 #endif
453 MODULE_PARM(aic7xxx, "s");
454 MODULE_PARM_DESC(aic7xxx,
455 "period delimited, options string.\n"
456 "       verbose                 Enable verbose/diagnostic logging\n"
457 "       allow_memio             Allow device registers to be memory mapped\n"
458 "       debug                   Bitmask of debug values to enable\n"
459 "       no_probe                Toggle EISA/VLB controller probing\n"
460 "       probe_eisa_vl           Toggle EISA/VLB controller probing\n"
461 "       no_reset                Supress initial bus resets\n"
462 "       extended                Enable extended geometry on all controllers\n"
463 "       periodic_otag           Send an ordered tagged transaction\n"
464 "                               periodically to prevent tag starvation.\n"
465 "                               This may be required by some older disk\n"
466 "                               drives or RAID arrays.\n"
467 "       reverse_scan            Sort PCI devices highest Bus/Slot to lowest\n"
468 "       tag_info:<tag_str>      Set per-target tag depth\n"
469 "       global_tag_depth:<int>  Global tag depth for every target\n"
470 "                               on every bus\n"
471 "       dv:<dv_settings>        Set per-controller Domain Validation Setting.\n"
472 "       seltime:<int>           Selection Timeout\n"
473 "                               (0/256ms,1/128ms,2/64ms,3/32ms)\n"
474 "\n"
475 "       Sample /etc/modprobe.conf line:\n"
476 "               Toggle EISA/VLB probing\n"
477 "               Set tag depth on Controller 1/Target 1 to 10 tags\n"
478 "               Shorten the selection timeout to 128ms\n"
479 "\n"
480 "       options aic7xxx 'aic7xxx=probe_eisa_vl.tag_info:{{}.{.10}}.seltime:1'\n"
481 );
482 #endif
483
484 static void ahc_linux_handle_scsi_status(struct ahc_softc *,
485                                          struct ahc_linux_device *,
486                                          struct scb *);
487 static void ahc_linux_queue_cmd_complete(struct ahc_softc *ahc,
488                                          Scsi_Cmnd *cmd);
489 static void ahc_linux_filter_inquiry(struct ahc_softc*, struct ahc_devinfo*);
490 static void ahc_linux_sem_timeout(u_long arg);
491 static void ahc_linux_freeze_simq(struct ahc_softc *ahc);
492 static void ahc_linux_release_simq(u_long arg);
493 static void ahc_linux_dev_timed_unfreeze(u_long arg);
494 static int  ahc_linux_queue_recovery_cmd(Scsi_Cmnd *cmd, scb_flag flag);
495 static void ahc_linux_initialize_scsi_bus(struct ahc_softc *ahc);
496 static void ahc_linux_size_nseg(void);
497 static void ahc_linux_thread_run_complete_queue(struct ahc_softc *ahc);
498 static void ahc_linux_start_dv(struct ahc_softc *ahc);
499 static void ahc_linux_dv_timeout(struct scsi_cmnd *cmd);
500 static int  ahc_linux_dv_thread(void *data);
501 static void ahc_linux_kill_dv_thread(struct ahc_softc *ahc);
502 static void ahc_linux_dv_target(struct ahc_softc *ahc, u_int target);
503 static void ahc_linux_dv_transition(struct ahc_softc *ahc,
504                                     struct scsi_cmnd *cmd,
505                                     struct ahc_devinfo *devinfo,
506                                     struct ahc_linux_target *targ);
507 static void ahc_linux_dv_fill_cmd(struct ahc_softc *ahc,
508                                   struct scsi_cmnd *cmd,
509                                   struct ahc_devinfo *devinfo);
510 static void ahc_linux_dv_inq(struct ahc_softc *ahc,
511                              struct scsi_cmnd *cmd,
512                              struct ahc_devinfo *devinfo,
513                              struct ahc_linux_target *targ,
514                              u_int request_length);
515 static void ahc_linux_dv_tur(struct ahc_softc *ahc,
516                              struct scsi_cmnd *cmd,
517                              struct ahc_devinfo *devinfo);
518 static void ahc_linux_dv_rebd(struct ahc_softc *ahc,
519                               struct scsi_cmnd *cmd,
520                               struct ahc_devinfo *devinfo,
521                               struct ahc_linux_target *targ);
522 static void ahc_linux_dv_web(struct ahc_softc *ahc,
523                              struct scsi_cmnd *cmd,
524                              struct ahc_devinfo *devinfo,
525                              struct ahc_linux_target *targ);
526 static void ahc_linux_dv_reb(struct ahc_softc *ahc,
527                              struct scsi_cmnd *cmd,
528                              struct ahc_devinfo *devinfo,
529                              struct ahc_linux_target *targ);
530 static void ahc_linux_dv_su(struct ahc_softc *ahc,
531                             struct scsi_cmnd *cmd,
532                             struct ahc_devinfo *devinfo,
533                             struct ahc_linux_target *targ);
534 static int ahc_linux_fallback(struct ahc_softc *ahc,
535                               struct ahc_devinfo *devinfo);
536 static void ahc_linux_dv_complete(Scsi_Cmnd *cmd);
537 static void ahc_linux_generate_dv_pattern(struct ahc_linux_target *targ);
538 static u_int ahc_linux_user_tagdepth(struct ahc_softc *ahc,
539                                      struct ahc_devinfo *devinfo);
540 static u_int ahc_linux_user_dv_setting(struct ahc_softc *ahc);
541 static void ahc_linux_device_queue_depth(struct ahc_softc *ahc,
542                                          struct ahc_linux_device *dev);
543 static struct ahc_linux_target* ahc_linux_alloc_target(struct ahc_softc*,
544                                                        u_int, u_int);
545 static void                     ahc_linux_free_target(struct ahc_softc*,
546                                                       struct ahc_linux_target*);
547 static struct ahc_linux_device* ahc_linux_alloc_device(struct ahc_softc*,
548                                                        struct ahc_linux_target*,
549                                                        u_int);
550 static void                     ahc_linux_free_device(struct ahc_softc*,
551                                                       struct ahc_linux_device*);
552 static void ahc_linux_run_device_queue(struct ahc_softc*,
553                                        struct ahc_linux_device*);
554 static void ahc_linux_setup_tag_info_global(char *p);
555 static aic_option_callback_t ahc_linux_setup_tag_info;
556 static aic_option_callback_t ahc_linux_setup_dv;
557 static int  aic7xxx_setup(char *s);
558 static int  ahc_linux_next_unit(void);
559 static void ahc_runq_tasklet(unsigned long data);
560 static struct ahc_cmd *ahc_linux_run_complete_queue(struct ahc_softc *ahc);
561
562 /********************************* Inlines ************************************/
563 static __inline void ahc_schedule_runq(struct ahc_softc *ahc);
564 static __inline struct ahc_linux_device*
565                      ahc_linux_get_device(struct ahc_softc *ahc, u_int channel,
566                                           u_int target, u_int lun, int alloc);
567 static __inline void ahc_schedule_completeq(struct ahc_softc *ahc);
568 static __inline void ahc_linux_check_device_queue(struct ahc_softc *ahc,
569                                                   struct ahc_linux_device *dev);
570 static __inline struct ahc_linux_device *
571                      ahc_linux_next_device_to_run(struct ahc_softc *ahc);
572 static __inline void ahc_linux_run_device_queues(struct ahc_softc *ahc);
573 static __inline void ahc_linux_unmap_scb(struct ahc_softc*, struct scb*);
574
575 static __inline int ahc_linux_map_seg(struct ahc_softc *ahc, struct scb *scb,
576                                       struct ahc_dma_seg *sg,
577                                       bus_addr_t addr, bus_size_t len);
578
579 static __inline void
580 ahc_schedule_completeq(struct ahc_softc *ahc)
581 {
582         if ((ahc->platform_data->flags & AHC_RUN_CMPLT_Q_TIMER) == 0) {
583                 ahc->platform_data->flags |= AHC_RUN_CMPLT_Q_TIMER;
584                 ahc->platform_data->completeq_timer.expires = jiffies;
585                 add_timer(&ahc->platform_data->completeq_timer);
586         }
587 }
588
589 /*
590  * Must be called with our lock held.
591  */
592 static __inline void
593 ahc_schedule_runq(struct ahc_softc *ahc)
594 {
595 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0)
596         tasklet_schedule(&ahc->platform_data->runq_tasklet);
597 #else
598         /*
599          * Tasklets are not available, so run inline.
600          */
601         ahc_runq_tasklet((unsigned long)ahc);
602 #endif
603 }
604
605 static __inline struct ahc_linux_device*
606 ahc_linux_get_device(struct ahc_softc *ahc, u_int channel, u_int target,
607                      u_int lun, int alloc)
608 {
609         struct ahc_linux_target *targ;
610         struct ahc_linux_device *dev;
611         u_int target_offset;
612
613         target_offset = target;
614         if (channel != 0)
615                 target_offset += 8;
616         targ = ahc->platform_data->targets[target_offset];
617         if (targ == NULL) {
618                 if (alloc != 0) {
619                         targ = ahc_linux_alloc_target(ahc, channel, target);
620                         if (targ == NULL)
621                                 return (NULL);
622                 } else
623                         return (NULL);
624         }
625         dev = targ->devices[lun];
626         if (dev == NULL && alloc != 0)
627                 dev = ahc_linux_alloc_device(ahc, targ, lun);
628         return (dev);
629 }
630
631 #define AHC_LINUX_MAX_RETURNED_ERRORS 4
632 static struct ahc_cmd *
633 ahc_linux_run_complete_queue(struct ahc_softc *ahc)
634 {
635         struct  ahc_cmd *acmd;
636         u_long  done_flags;
637         int     with_errors;
638
639         with_errors = 0;
640         ahc_done_lock(ahc, &done_flags);
641         while ((acmd = TAILQ_FIRST(&ahc->platform_data->completeq)) != NULL) {
642                 Scsi_Cmnd *cmd;
643
644                 if (with_errors > AHC_LINUX_MAX_RETURNED_ERRORS) {
645                         /*
646                          * Linux uses stack recursion to requeue
647                          * commands that need to be retried.  Avoid
648                          * blowing out the stack by "spoon feeding"
649                          * commands that completed with error back
650                          * the operating system in case they are going
651                          * to be retried. "ick"
652                          */
653                         ahc_schedule_completeq(ahc);
654                         break;
655                 }
656                 TAILQ_REMOVE(&ahc->platform_data->completeq,
657                              acmd, acmd_links.tqe);
658                 cmd = &acmd_scsi_cmd(acmd);
659                 cmd->host_scribble = NULL;
660                 if (ahc_cmd_get_transaction_status(cmd) != DID_OK
661                  || (cmd->result & 0xFF) != SCSI_STATUS_OK)
662                         with_errors++;
663
664                 cmd->scsi_done(cmd);
665         }
666         ahc_done_unlock(ahc, &done_flags);
667         return (acmd);
668 }
669
670 static __inline void
671 ahc_linux_check_device_queue(struct ahc_softc *ahc,
672                              struct ahc_linux_device *dev)
673 {
674         if ((dev->flags & AHC_DEV_FREEZE_TIL_EMPTY) != 0
675          && dev->active == 0) {
676                 dev->flags &= ~AHC_DEV_FREEZE_TIL_EMPTY;
677                 dev->qfrozen--;
678         }
679
680         if (TAILQ_FIRST(&dev->busyq) == NULL
681          || dev->openings == 0 || dev->qfrozen != 0)
682                 return;
683
684         ahc_linux_run_device_queue(ahc, dev);
685 }
686
687 static __inline struct ahc_linux_device *
688 ahc_linux_next_device_to_run(struct ahc_softc *ahc)
689 {
690         
691         if ((ahc->flags & AHC_RESOURCE_SHORTAGE) != 0
692          || (ahc->platform_data->qfrozen != 0
693           && AHC_DV_SIMQ_FROZEN(ahc) == 0))
694                 return (NULL);
695         return (TAILQ_FIRST(&ahc->platform_data->device_runq));
696 }
697
698 static __inline void
699 ahc_linux_run_device_queues(struct ahc_softc *ahc)
700 {
701         struct ahc_linux_device *dev;
702
703         while ((dev = ahc_linux_next_device_to_run(ahc)) != NULL) {
704                 TAILQ_REMOVE(&ahc->platform_data->device_runq, dev, links);
705                 dev->flags &= ~AHC_DEV_ON_RUN_LIST;
706                 ahc_linux_check_device_queue(ahc, dev);
707         }
708 }
709
710 static __inline void
711 ahc_linux_unmap_scb(struct ahc_softc *ahc, struct scb *scb)
712 {
713         Scsi_Cmnd *cmd;
714
715         cmd = scb->io_ctx;
716         ahc_sync_sglist(ahc, scb, BUS_DMASYNC_POSTWRITE);
717         if (cmd->use_sg != 0) {
718                 struct scatterlist *sg;
719
720                 sg = (struct scatterlist *)cmd->request_buffer;
721                 pci_unmap_sg(ahc->dev_softc, sg, cmd->use_sg,
722                              scsi_to_pci_dma_dir(cmd->sc_data_direction));
723         } else if (cmd->request_bufflen != 0) {
724                 pci_unmap_single(ahc->dev_softc,
725                                  scb->platform_data->buf_busaddr,
726                                  cmd->request_bufflen,
727                                  scsi_to_pci_dma_dir(cmd->sc_data_direction));
728         }
729 }
730
731 static __inline int
732 ahc_linux_map_seg(struct ahc_softc *ahc, struct scb *scb,
733                   struct ahc_dma_seg *sg, bus_addr_t addr, bus_size_t len)
734 {
735         int      consumed;
736
737         if ((scb->sg_count + 1) > AHC_NSEG)
738                 panic("Too few segs for dma mapping.  "
739                       "Increase AHC_NSEG\n");
740
741         consumed = 1;
742         sg->addr = ahc_htole32(addr & 0xFFFFFFFF);
743         scb->platform_data->xfer_len += len;
744
745         if (sizeof(bus_addr_t) > 4
746          && (ahc->flags & AHC_39BIT_ADDRESSING) != 0)
747                 len |= (addr >> 8) & AHC_SG_HIGH_ADDR_MASK;
748
749         sg->len = ahc_htole32(len);
750         return (consumed);
751 }
752
753 /************************  Host template entry points *************************/
754 static int         ahc_linux_detect(Scsi_Host_Template *);
755 static int         ahc_linux_queue(Scsi_Cmnd *, void (*)(Scsi_Cmnd *));
756 static const char *ahc_linux_info(struct Scsi_Host *);
757 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
758 static int         ahc_linux_slave_alloc(Scsi_Device *);
759 static int         ahc_linux_slave_configure(Scsi_Device *);
760 static void        ahc_linux_slave_destroy(Scsi_Device *);
761 #if defined(__i386__)
762 static int         ahc_linux_biosparam(struct scsi_device*,
763                                        struct block_device*,
764                                        sector_t, int[]);
765 #endif
766 #else
767 static int         ahc_linux_release(struct Scsi_Host *);
768 static void        ahc_linux_select_queue_depth(struct Scsi_Host *host,
769                                                 Scsi_Device *scsi_devs);
770 #if defined(__i386__)
771 static int         ahc_linux_biosparam(Disk *, kdev_t, int[]);
772 #endif
773 #endif
774 static int         ahc_linux_bus_reset(Scsi_Cmnd *);
775 static int         ahc_linux_dev_reset(Scsi_Cmnd *);
776 static int         ahc_linux_abort(Scsi_Cmnd *);
777
778 /*
779  * Calculate a safe value for AHC_NSEG (as expressed through ahc_linux_nseg).
780  *
781  * In pre-2.5.X...
782  * The midlayer allocates an S/G array dynamically when a command is issued
783  * using SCSI malloc.  This array, which is in an OS dependent format that
784  * must later be copied to our private S/G list, is sized to house just the
785  * number of segments needed for the current transfer.  Since the code that
786  * sizes the SCSI malloc pool does not take into consideration fragmentation
787  * of the pool, executing transactions numbering just a fraction of our
788  * concurrent transaction limit with list lengths aproaching AHC_NSEG will
789  * quickly depleat the SCSI malloc pool of usable space.  Unfortunately, the
790  * mid-layer does not properly handle this scsi malloc failures for the S/G
791  * array and the result can be a lockup of the I/O subsystem.  We try to size
792  * our S/G list so that it satisfies our drivers allocation requirements in
793  * addition to avoiding fragmentation of the SCSI malloc pool.
794  */
795 static void
796 ahc_linux_size_nseg(void)
797 {
798 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
799         u_int cur_size;
800         u_int best_size;
801
802         /*
803          * The SCSI allocator rounds to the nearest 512 bytes
804          * an cannot allocate across a page boundary.  Our algorithm
805          * is to start at 1K of scsi malloc space per-command and
806          * loop through all factors of the PAGE_SIZE and pick the best.
807          */
808         best_size = 0;
809         for (cur_size = 1024; cur_size <= PAGE_SIZE; cur_size *= 2) {
810                 u_int nseg;
811
812                 nseg = cur_size / sizeof(struct scatterlist);
813                 if (nseg < AHC_LINUX_MIN_NSEG)
814                         continue;
815
816                 if (best_size == 0) {
817                         best_size = cur_size;
818                         ahc_linux_nseg = nseg;
819                 } else {
820                         u_int best_rem;
821                         u_int cur_rem;
822
823                         /*
824                          * Compare the traits of the current "best_size"
825                          * with the current size to determine if the
826                          * current size is a better size.
827                          */
828                         best_rem = best_size % sizeof(struct scatterlist);
829                         cur_rem = cur_size % sizeof(struct scatterlist);
830                         if (cur_rem < best_rem) {
831                                 best_size = cur_size;
832                                 ahc_linux_nseg = nseg;
833                         }
834                 }
835         }
836 #endif
837 }
838
839 /*
840  * Try to detect an Adaptec 7XXX controller.
841  */
842 static int
843 ahc_linux_detect(Scsi_Host_Template *template)
844 {
845         struct  ahc_softc *ahc;
846         int     found = 0;
847         int     eisa_err, pci_err;
848
849 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
850         /*
851          * It is a bug that the upper layer takes
852          * this lock just prior to calling us.
853          */
854         spin_unlock_irq(&io_request_lock);
855 #endif
856
857         /*
858          * Sanity checking of Linux SCSI data structures so
859          * that some of our hacks^H^H^H^H^Hassumptions aren't
860          * violated.
861          */
862         if (offsetof(struct ahc_cmd_internal, end)
863           > offsetof(struct scsi_cmnd, host_scribble)) {
864                 printf("ahc_linux_detect: SCSI data structures changed.\n");
865                 printf("ahc_linux_detect: Unable to attach\n");
866                 return (0);
867         }
868         ahc_linux_size_nseg();
869 #ifdef MODULE
870         /*
871          * If we've been passed any parameters, process them now.
872          */
873         if (aic7xxx)
874                 aic7xxx_setup(aic7xxx);
875         if (dummy_buffer[0] != 'P')
876                 printk(KERN_WARNING
877 "aic7xxx: Please read the file /usr/src/linux/drivers/scsi/README.aic7xxx\n"
878 "aic7xxx: to see the proper way to specify options to the aic7xxx module\n"
879 "aic7xxx: Specifically, don't use any commas when passing arguments to\n"
880 "aic7xxx: insmod or else it might trash certain memory areas.\n");
881 #endif
882
883 #if LINUX_VERSION_CODE > KERNEL_VERSION(2,3,0)
884         template->proc_name = "aic7xxx";
885 #else
886         template->proc_dir = &proc_scsi_aic7xxx;
887 #endif
888
889         /*
890          * Initialize our softc list lock prior to
891          * probing for any adapters.
892          */
893         ahc_list_lockinit();
894
895         pci_err = ahc_linux_pci_init();
896         eisa_err = ahc_linux_eisa_init();
897
898         if(pci_err && eisa_err)
899                 goto out;
900
901
902         /*
903          * Register with the SCSI layer all
904          * controllers we've found.
905          */
906         TAILQ_FOREACH(ahc, &ahc_tailq, links) {
907
908                 if (ahc_linux_register_host(ahc, template) == 0)
909                         found++;
910         }
911 out:
912
913 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
914         spin_lock_irq(&io_request_lock);
915 #endif
916         aic7xxx_detect_complete++;
917
918         return (found);
919 }
920
921 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
922 /*
923  * Free the passed in Scsi_Host memory structures prior to unloading the
924  * module.
925  */
926 int
927 ahc_linux_release(struct Scsi_Host * host)
928 {
929         struct ahc_softc *ahc;
930         u_long l;
931
932         ahc_list_lock(&l);
933         if (host != NULL) {
934
935                 /*
936                  * We should be able to just perform
937                  * the free directly, but check our
938                  * list for extra sanity.
939                  */
940                 ahc = ahc_find_softc(*(struct ahc_softc **)host->hostdata);
941                 if (ahc != NULL) {
942                         u_long s;
943
944                         ahc_lock(ahc, &s);
945                         ahc_intr_enable(ahc, FALSE);
946                         ahc_unlock(ahc, &s);
947                         ahc_free(ahc);
948                 }
949         }
950         ahc_list_unlock(&l);
951         return (0);
952 }
953 #endif
954
955 /*
956  * Return a string describing the driver.
957  */
958 static const char *
959 ahc_linux_info(struct Scsi_Host *host)
960 {
961         static char buffer[512];
962         char    ahc_info[256];
963         char   *bp;
964         struct ahc_softc *ahc;
965
966         bp = &buffer[0];
967         ahc = *(struct ahc_softc **)host->hostdata;
968         memset(bp, 0, sizeof(buffer));
969         strcpy(bp, "Adaptec AIC7XXX EISA/VLB/PCI SCSI HBA DRIVER, Rev ");
970         strcat(bp, AIC7XXX_DRIVER_VERSION);
971         strcat(bp, "\n");
972         strcat(bp, "        <");
973         strcat(bp, ahc->description);
974         strcat(bp, ">\n");
975         strcat(bp, "        ");
976         ahc_controller_info(ahc, ahc_info);
977         strcat(bp, ahc_info);
978         strcat(bp, "\n");
979
980         return (bp);
981 }
982
983 /*
984  * Queue an SCB to the controller.
985  */
986 static int
987 ahc_linux_queue(Scsi_Cmnd * cmd, void (*scsi_done) (Scsi_Cmnd *))
988 {
989         struct   ahc_softc *ahc;
990         struct   ahc_linux_device *dev;
991         u_long   flags;
992
993         ahc = *(struct ahc_softc **)cmd->device->host->hostdata;
994
995         /*
996          * Save the callback on completion function.
997          */
998         cmd->scsi_done = scsi_done;
999
1000         ahc_midlayer_entrypoint_lock(ahc, &flags);
1001
1002         /*
1003          * Close the race of a command that was in the process of
1004          * being queued to us just as our simq was frozen.  Let
1005          * DV commands through so long as we are only frozen to
1006          * perform DV.
1007          */
1008         if (ahc->platform_data->qfrozen != 0
1009          && AHC_DV_CMD(cmd) == 0) {
1010
1011                 ahc_cmd_set_transaction_status(cmd, CAM_REQUEUE_REQ);
1012                 ahc_linux_queue_cmd_complete(ahc, cmd);
1013                 ahc_schedule_completeq(ahc);
1014                 ahc_midlayer_entrypoint_unlock(ahc, &flags);
1015                 return (0);
1016         }
1017         dev = ahc_linux_get_device(ahc, cmd->device->channel, cmd->device->id,
1018                                    cmd->device->lun, /*alloc*/TRUE);
1019         if (dev == NULL) {
1020                 ahc_cmd_set_transaction_status(cmd, CAM_RESRC_UNAVAIL);
1021                 ahc_linux_queue_cmd_complete(ahc, cmd);
1022                 ahc_schedule_completeq(ahc);
1023                 ahc_midlayer_entrypoint_unlock(ahc, &flags);
1024                 printf("%s: aic7xxx_linux_queue - Unable to allocate device!\n",
1025                        ahc_name(ahc));
1026                 return (0);
1027         }
1028         cmd->result = CAM_REQ_INPROG << 16;
1029         TAILQ_INSERT_TAIL(&dev->busyq, (struct ahc_cmd *)cmd, acmd_links.tqe);
1030         if ((dev->flags & AHC_DEV_ON_RUN_LIST) == 0) {
1031                 TAILQ_INSERT_TAIL(&ahc->platform_data->device_runq, dev, links);
1032                 dev->flags |= AHC_DEV_ON_RUN_LIST;
1033                 ahc_linux_run_device_queues(ahc);
1034         }
1035         ahc_midlayer_entrypoint_unlock(ahc, &flags);
1036         return (0);
1037 }
1038
1039 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
1040 static int
1041 ahc_linux_slave_alloc(Scsi_Device *device)
1042 {
1043         struct  ahc_softc *ahc;
1044
1045         ahc = *((struct ahc_softc **)device->host->hostdata);
1046         if (bootverbose)
1047                 printf("%s: Slave Alloc %d\n", ahc_name(ahc), device->id);
1048         return (0);
1049 }
1050
1051 static int
1052 ahc_linux_slave_configure(Scsi_Device *device)
1053 {
1054         struct  ahc_softc *ahc;
1055         struct  ahc_linux_device *dev;
1056         u_long  flags;
1057
1058         ahc = *((struct ahc_softc **)device->host->hostdata);
1059         if (bootverbose)
1060                 printf("%s: Slave Configure %d\n", ahc_name(ahc), device->id);
1061         ahc_midlayer_entrypoint_lock(ahc, &flags);
1062         /*
1063          * Since Linux has attached to the device, configure
1064          * it so we don't free and allocate the device
1065          * structure on every command.
1066          */
1067         dev = ahc_linux_get_device(ahc, device->channel,
1068                                    device->id, device->lun,
1069                                    /*alloc*/TRUE);
1070         if (dev != NULL) {
1071                 dev->flags &= ~AHC_DEV_UNCONFIGURED;
1072                 dev->scsi_device = device;
1073                 ahc_linux_device_queue_depth(ahc, dev);
1074         }
1075         ahc_midlayer_entrypoint_unlock(ahc, &flags);
1076         return (0);
1077 }
1078
1079 static void
1080 ahc_linux_slave_destroy(Scsi_Device *device)
1081 {
1082         struct  ahc_softc *ahc;
1083         struct  ahc_linux_device *dev;
1084         u_long  flags;
1085
1086         ahc = *((struct ahc_softc **)device->host->hostdata);
1087         if (bootverbose)
1088                 printf("%s: Slave Destroy %d\n", ahc_name(ahc), device->id);
1089         ahc_midlayer_entrypoint_lock(ahc, &flags);
1090         dev = ahc_linux_get_device(ahc, device->channel,
1091                                    device->id, device->lun,
1092                                            /*alloc*/FALSE);
1093         /*
1094          * Filter out "silly" deletions of real devices by only
1095          * deleting devices that have had slave_configure()
1096          * called on them.  All other devices that have not
1097          * been configured will automatically be deleted by
1098          * the refcounting process.
1099          */
1100         if (dev != NULL
1101          && (dev->flags & AHC_DEV_SLAVE_CONFIGURED) != 0) {
1102                 dev->flags |= AHC_DEV_UNCONFIGURED;
1103                 if (TAILQ_EMPTY(&dev->busyq)
1104                  && dev->active == 0
1105                  && (dev->flags & AHC_DEV_TIMER_ACTIVE) == 0)
1106                         ahc_linux_free_device(ahc, dev);
1107         }
1108         ahc_midlayer_entrypoint_unlock(ahc, &flags);
1109 }
1110 #else
1111 /*
1112  * Sets the queue depth for each SCSI device hanging
1113  * off the input host adapter.
1114  */
1115 static void
1116 ahc_linux_select_queue_depth(struct Scsi_Host *host, Scsi_Device *scsi_devs)
1117 {
1118         Scsi_Device *device;
1119         Scsi_Device *ldev;
1120         struct  ahc_softc *ahc;
1121         u_long  flags;
1122
1123         ahc = *((struct ahc_softc **)host->hostdata);
1124         ahc_lock(ahc, &flags);
1125         for (device = scsi_devs; device != NULL; device = device->next) {
1126
1127                 /*
1128                  * Watch out for duplicate devices.  This works around
1129                  * some quirks in how the SCSI scanning code does its
1130                  * device management.
1131                  */
1132                 for (ldev = scsi_devs; ldev != device; ldev = ldev->next) {
1133                         if (ldev->host == device->host
1134                          && ldev->channel == device->channel
1135                          && ldev->id == device->id
1136                          && ldev->lun == device->lun)
1137                                 break;
1138                 }
1139                 /* Skip duplicate. */
1140                 if (ldev != device)
1141                         continue;
1142
1143                 if (device->host == host) {
1144                         struct   ahc_linux_device *dev;
1145
1146                         /*
1147                          * Since Linux has attached to the device, configure
1148                          * it so we don't free and allocate the device
1149                          * structure on every command.
1150                          */
1151                         dev = ahc_linux_get_device(ahc, device->channel,
1152                                                    device->id, device->lun,
1153                                                    /*alloc*/TRUE);
1154                         if (dev != NULL) {
1155                                 dev->flags &= ~AHC_DEV_UNCONFIGURED;
1156                                 dev->scsi_device = device;
1157                                 ahc_linux_device_queue_depth(ahc, dev);
1158                                 device->queue_depth = dev->openings
1159                                                     + dev->active;
1160                                 if ((dev->flags & (AHC_DEV_Q_BASIC
1161                                                 | AHC_DEV_Q_TAGGED)) == 0) {
1162                                         /*
1163                                          * We allow the OS to queue 2 untagged
1164                                          * transactions to us at any time even
1165                                          * though we can only execute them
1166                                          * serially on the controller/device.
1167                                          * This should remove some latency.
1168                                          */
1169                                         device->queue_depth = 2;
1170                                 }
1171                         }
1172                 }
1173         }
1174         ahc_unlock(ahc, &flags);
1175 }
1176 #endif
1177
1178 #if defined(__i386__)
1179 /*
1180  * Return the disk geometry for the given SCSI device.
1181  */
1182 static int
1183 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
1184 ahc_linux_biosparam(struct scsi_device *sdev, struct block_device *bdev,
1185                     sector_t capacity, int geom[])
1186 {
1187         uint8_t *bh;
1188 #else
1189 ahc_linux_biosparam(Disk *disk, kdev_t dev, int geom[])
1190 {
1191         struct  scsi_device *sdev = disk->device;
1192         u_long  capacity = disk->capacity;
1193         struct  buffer_head *bh;
1194 #endif
1195         int      heads;
1196         int      sectors;
1197         int      cylinders;
1198         int      ret;
1199         int      extended;
1200         struct   ahc_softc *ahc;
1201         u_int    channel;
1202
1203         ahc = *((struct ahc_softc **)sdev->host->hostdata);
1204         channel = sdev->channel;
1205
1206 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
1207         bh = scsi_bios_ptable(bdev);
1208 #elif LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,17)
1209         bh = bread(MKDEV(MAJOR(dev), MINOR(dev) & ~0xf), 0, block_size(dev));
1210 #else
1211         bh = bread(MKDEV(MAJOR(dev), MINOR(dev) & ~0xf), 0, 1024);
1212 #endif
1213
1214         if (bh) {
1215                 ret = scsi_partsize(bh, capacity,
1216                                     &geom[2], &geom[0], &geom[1]);
1217 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
1218                 kfree(bh);
1219 #else
1220                 brelse(bh);
1221 #endif
1222                 if (ret != -1)
1223                         return (ret);
1224         }
1225         heads = 64;
1226         sectors = 32;
1227         cylinders = aic_sector_div(capacity, heads, sectors);
1228
1229         if (aic7xxx_extended != 0)
1230                 extended = 1;
1231         else if (channel == 0)
1232                 extended = (ahc->flags & AHC_EXTENDED_TRANS_A) != 0;
1233         else
1234                 extended = (ahc->flags & AHC_EXTENDED_TRANS_B) != 0;
1235         if (extended && cylinders >= 1024) {
1236                 heads = 255;
1237                 sectors = 63;
1238                 cylinders = aic_sector_div(capacity, heads, sectors);
1239         }
1240         geom[0] = heads;
1241         geom[1] = sectors;
1242         geom[2] = cylinders;
1243         return (0);
1244 }
1245 #endif
1246
1247 /*
1248  * Abort the current SCSI command(s).
1249  */
1250 static int
1251 ahc_linux_abort(Scsi_Cmnd *cmd)
1252 {
1253         int error;
1254
1255         error = ahc_linux_queue_recovery_cmd(cmd, SCB_ABORT);
1256         if (error != 0)
1257                 printf("aic7xxx_abort returns 0x%x\n", error);
1258         return (error);
1259 }
1260
1261 /*
1262  * Attempt to send a target reset message to the device that timed out.
1263  */
1264 static int
1265 ahc_linux_dev_reset(Scsi_Cmnd *cmd)
1266 {
1267         int error;
1268
1269         error = ahc_linux_queue_recovery_cmd(cmd, SCB_DEVICE_RESET);
1270         if (error != 0)
1271                 printf("aic7xxx_dev_reset returns 0x%x\n", error);
1272         return (error);
1273 }
1274
1275 /*
1276  * Reset the SCSI bus.
1277  */
1278 static int
1279 ahc_linux_bus_reset(Scsi_Cmnd *cmd)
1280 {
1281         struct ahc_softc *ahc;
1282         u_long s;
1283         int    found;
1284
1285         ahc = *(struct ahc_softc **)cmd->device->host->hostdata;
1286         ahc_midlayer_entrypoint_lock(ahc, &s);
1287         found = ahc_reset_channel(ahc, cmd->device->channel + 'A',
1288                                   /*initiate reset*/TRUE);
1289         ahc_linux_run_complete_queue(ahc);
1290         ahc_midlayer_entrypoint_unlock(ahc, &s);
1291
1292         if (bootverbose)
1293                 printf("%s: SCSI bus reset delivered. "
1294                        "%d SCBs aborted.\n", ahc_name(ahc), found);
1295
1296         return SUCCESS;
1297 }
1298
1299 Scsi_Host_Template aic7xxx_driver_template = {
1300         .module                 = THIS_MODULE,
1301         .name                   = "aic7xxx",
1302         .proc_info              = ahc_linux_proc_info,
1303         .info                   = ahc_linux_info,
1304         .queuecommand           = ahc_linux_queue,
1305         .eh_abort_handler       = ahc_linux_abort,
1306         .eh_device_reset_handler = ahc_linux_dev_reset,
1307         .eh_bus_reset_handler   = ahc_linux_bus_reset,
1308 #if defined(__i386__)
1309         .bios_param             = ahc_linux_biosparam,
1310 #endif
1311         .can_queue              = AHC_MAX_QUEUE,
1312         .this_id                = -1,
1313         .cmd_per_lun            = 2,
1314         .use_clustering         = ENABLE_CLUSTERING,
1315         .slave_alloc            = ahc_linux_slave_alloc,
1316         .slave_configure        = ahc_linux_slave_configure,
1317         .slave_destroy          = ahc_linux_slave_destroy,
1318 };
1319
1320 /**************************** Tasklet Handler *********************************/
1321
1322 /*
1323  * In 2.4.X and above, this routine is called from a tasklet,
1324  * so we must re-acquire our lock prior to executing this code.
1325  * In all prior kernels, ahc_schedule_runq() calls this routine
1326  * directly and ahc_schedule_runq() is called with our lock held.
1327  */
1328 static void
1329 ahc_runq_tasklet(unsigned long data)
1330 {
1331         struct ahc_softc* ahc;
1332         struct ahc_linux_device *dev;
1333 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0)
1334         u_long flags;
1335 #endif
1336
1337         ahc = (struct ahc_softc *)data;
1338 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0)
1339         ahc_lock(ahc, &flags);
1340 #endif
1341         while ((dev = ahc_linux_next_device_to_run(ahc)) != NULL) {
1342         
1343                 TAILQ_REMOVE(&ahc->platform_data->device_runq, dev, links);
1344                 dev->flags &= ~AHC_DEV_ON_RUN_LIST;
1345                 ahc_linux_check_device_queue(ahc, dev);
1346 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0)
1347                 /* Yeild to our interrupt handler */
1348                 ahc_unlock(ahc, &flags);
1349                 ahc_lock(ahc, &flags);
1350 #endif
1351         }
1352 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0)
1353         ahc_unlock(ahc, &flags);
1354 #endif
1355 }
1356
1357 /******************************** Macros **************************************/
1358 #define BUILD_SCSIID(ahc, cmd)                                              \
1359         ((((cmd)->device->id << TID_SHIFT) & TID)                           \
1360         | (((cmd)->device->channel == 0) ? (ahc)->our_id : (ahc)->our_id_b) \
1361         | (((cmd)->device->channel == 0) ? 0 : TWIN_CHNLB))
1362
1363 /******************************** Bus DMA *************************************/
1364 int
1365 ahc_dma_tag_create(struct ahc_softc *ahc, bus_dma_tag_t parent,
1366                    bus_size_t alignment, bus_size_t boundary,
1367                    bus_addr_t lowaddr, bus_addr_t highaddr,
1368                    bus_dma_filter_t *filter, void *filterarg,
1369                    bus_size_t maxsize, int nsegments,
1370                    bus_size_t maxsegsz, int flags, bus_dma_tag_t *ret_tag)
1371 {
1372         bus_dma_tag_t dmat;
1373
1374         dmat = malloc(sizeof(*dmat), M_DEVBUF, M_NOWAIT);
1375         if (dmat == NULL)
1376                 return (ENOMEM);
1377
1378         /*
1379          * Linux is very simplistic about DMA memory.  For now don't
1380          * maintain all specification information.  Once Linux supplies
1381          * better facilities for doing these operations, or the
1382          * needs of this particular driver change, we might need to do
1383          * more here.
1384          */
1385         dmat->alignment = alignment;
1386         dmat->boundary = boundary;
1387         dmat->maxsize = maxsize;
1388         *ret_tag = dmat;
1389         return (0);
1390 }
1391
1392 void
1393 ahc_dma_tag_destroy(struct ahc_softc *ahc, bus_dma_tag_t dmat)
1394 {
1395         free(dmat, M_DEVBUF);
1396 }
1397
1398 int
1399 ahc_dmamem_alloc(struct ahc_softc *ahc, bus_dma_tag_t dmat, void** vaddr,
1400                  int flags, bus_dmamap_t *mapp)
1401 {
1402         bus_dmamap_t map;
1403
1404 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,3,0)
1405         map = malloc(sizeof(*map), M_DEVBUF, M_NOWAIT);
1406         if (map == NULL)
1407                 return (ENOMEM);
1408         /*
1409          * Although we can dma data above 4GB, our
1410          * "consistent" memory is below 4GB for
1411          * space efficiency reasons (only need a 4byte
1412          * address).  For this reason, we have to reset
1413          * our dma mask when doing allocations.
1414          */
1415         if (ahc->dev_softc != NULL)
1416                 if (ahc_pci_set_dma_mask(ahc->dev_softc, 0xFFFFFFFF)) {
1417                         printk(KERN_WARNING "aic7xxx: No suitable DMA available.\n");
1418                         return (ENODEV);
1419                 }
1420         *vaddr = pci_alloc_consistent(ahc->dev_softc,
1421                                       dmat->maxsize, &map->bus_addr);
1422         if (ahc->dev_softc != NULL)
1423                 if (ahc_pci_set_dma_mask(ahc->dev_softc,
1424                                      ahc->platform_data->hw_dma_mask)) {
1425                         printk(KERN_WARNING "aic7xxx: No suitable DMA available.\n");
1426                         return (ENODEV);
1427                 }
1428 #else /* LINUX_VERSION_CODE < KERNEL_VERSION(2,3,0) */
1429         /*
1430          * At least in 2.2.14, malloc is a slab allocator so all
1431          * allocations are aligned.  We assume for these kernel versions
1432          * that all allocations will be bellow 4Gig, physically contiguous,
1433          * and accessible via DMA by the controller.
1434          */
1435         map = NULL; /* No additional information to store */
1436         *vaddr = malloc(dmat->maxsize, M_DEVBUF, M_NOWAIT);
1437 #endif
1438         if (*vaddr == NULL)
1439                 return (ENOMEM);
1440         *mapp = map;
1441         return(0);
1442 }
1443
1444 void
1445 ahc_dmamem_free(struct ahc_softc *ahc, bus_dma_tag_t dmat,
1446                 void* vaddr, bus_dmamap_t map)
1447 {
1448 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,3,0)
1449         pci_free_consistent(ahc->dev_softc, dmat->maxsize,
1450                             vaddr, map->bus_addr);
1451 #else
1452         free(vaddr, M_DEVBUF);
1453 #endif
1454 }
1455
1456 int
1457 ahc_dmamap_load(struct ahc_softc *ahc, bus_dma_tag_t dmat, bus_dmamap_t map,
1458                 void *buf, bus_size_t buflen, bus_dmamap_callback_t *cb,
1459                 void *cb_arg, int flags)
1460 {
1461         /*
1462          * Assume for now that this will only be used during
1463          * initialization and not for per-transaction buffer mapping.
1464          */
1465         bus_dma_segment_t stack_sg;
1466
1467 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,3,0)
1468         stack_sg.ds_addr = map->bus_addr;
1469 #else
1470 #define VIRT_TO_BUS(a) (uint32_t)virt_to_bus((void *)(a))
1471         stack_sg.ds_addr = VIRT_TO_BUS(buf);
1472 #endif
1473         stack_sg.ds_len = dmat->maxsize;
1474         cb(cb_arg, &stack_sg, /*nseg*/1, /*error*/0);
1475         return (0);
1476 }
1477
1478 void
1479 ahc_dmamap_destroy(struct ahc_softc *ahc, bus_dma_tag_t dmat, bus_dmamap_t map)
1480 {
1481         /*
1482          * The map may is NULL in our < 2.3.X implementation.
1483          */
1484         if (map != NULL)
1485                 free(map, M_DEVBUF);
1486 }
1487
1488 int
1489 ahc_dmamap_unload(struct ahc_softc *ahc, bus_dma_tag_t dmat, bus_dmamap_t map)
1490 {
1491         /* Nothing to do */
1492         return (0);
1493 }
1494
1495 /********************* Platform Dependent Functions ***************************/
1496 /*
1497  * Compare "left hand" softc with "right hand" softc, returning:
1498  * < 0 - lahc has a lower priority than rahc
1499  *   0 - Softcs are equal
1500  * > 0 - lahc has a higher priority than rahc
1501  */
1502 int
1503 ahc_softc_comp(struct ahc_softc *lahc, struct ahc_softc *rahc)
1504 {
1505         int     value;
1506         int     rvalue;
1507         int     lvalue;
1508
1509         /*
1510          * Under Linux, cards are ordered as follows:
1511          *      1) VLB/EISA BIOS enabled devices sorted by BIOS address.
1512          *      2) PCI devices with BIOS enabled sorted by bus/slot/func.
1513          *      3) All remaining VLB/EISA devices sorted by ioport.
1514          *      4) All remaining PCI devices sorted by bus/slot/func.
1515          */
1516         value = (lahc->flags & AHC_BIOS_ENABLED)
1517               - (rahc->flags & AHC_BIOS_ENABLED);
1518         if (value != 0)
1519                 /* Controllers with BIOS enabled have a *higher* priority */
1520                 return (value);
1521
1522         /*
1523          * Same BIOS setting, now sort based on bus type.
1524          * EISA and VL controllers sort together.  EISA/VL
1525          * have higher priority than PCI.
1526          */
1527         rvalue = (rahc->chip & AHC_BUS_MASK);
1528         if (rvalue == AHC_VL)
1529                 rvalue = AHC_EISA;
1530         lvalue = (lahc->chip & AHC_BUS_MASK);
1531         if (lvalue == AHC_VL)
1532                 lvalue = AHC_EISA;
1533         value = rvalue - lvalue;
1534         if (value != 0)
1535                 return (value);
1536
1537         /* Still equal.  Sort by BIOS address, ioport, or bus/slot/func. */
1538         switch (rvalue) {
1539 #ifdef CONFIG_PCI
1540         case AHC_PCI:
1541         {
1542                 char primary_channel;
1543
1544                 if (aic7xxx_reverse_scan != 0)
1545                         value = ahc_get_pci_bus(lahc->dev_softc)
1546                               - ahc_get_pci_bus(rahc->dev_softc);
1547                 else
1548                         value = ahc_get_pci_bus(rahc->dev_softc)
1549                               - ahc_get_pci_bus(lahc->dev_softc);
1550                 if (value != 0)
1551                         break;
1552                 if (aic7xxx_reverse_scan != 0)
1553                         value = ahc_get_pci_slot(lahc->dev_softc)
1554                               - ahc_get_pci_slot(rahc->dev_softc);
1555                 else
1556                         value = ahc_get_pci_slot(rahc->dev_softc)
1557                               - ahc_get_pci_slot(lahc->dev_softc);
1558                 if (value != 0)
1559                         break;
1560                 /*
1561                  * On multi-function devices, the user can choose
1562                  * to have function 1 probed before function 0.
1563                  * Give whichever channel is the primary channel
1564                  * the highest priority.
1565                  */
1566                 primary_channel = (lahc->flags & AHC_PRIMARY_CHANNEL) + 'A';
1567                 value = -1;
1568                 if (lahc->channel == primary_channel)
1569                         value = 1;
1570                 break;
1571         }
1572 #endif
1573         case AHC_EISA:
1574                 if ((rahc->flags & AHC_BIOS_ENABLED) != 0) {
1575                         value = rahc->platform_data->bios_address
1576                               - lahc->platform_data->bios_address; 
1577                 } else {
1578                         value = rahc->bsh.ioport
1579                               - lahc->bsh.ioport; 
1580                 }
1581                 break;
1582         default:
1583                 panic("ahc_softc_sort: invalid bus type");
1584         }
1585         return (value);
1586 }
1587
1588 static void
1589 ahc_linux_setup_tag_info_global(char *p)
1590 {
1591         int tags, i, j;
1592
1593         tags = simple_strtoul(p + 1, NULL, 0) & 0xff;
1594         printf("Setting Global Tags= %d\n", tags);
1595
1596         for (i = 0; i < NUM_ELEMENTS(aic7xxx_tag_info); i++) {
1597                 for (j = 0; j < AHC_NUM_TARGETS; j++) {
1598                         aic7xxx_tag_info[i].tag_commands[j] = tags;
1599                 }
1600         }
1601 }
1602
1603 static void
1604 ahc_linux_setup_tag_info(u_long arg, int instance, int targ, int32_t value)
1605 {
1606
1607         if ((instance >= 0) && (targ >= 0)
1608          && (instance < NUM_ELEMENTS(aic7xxx_tag_info))
1609          && (targ < AHC_NUM_TARGETS)) {
1610                 aic7xxx_tag_info[instance].tag_commands[targ] = value & 0xff;
1611                 if (bootverbose)
1612                         printf("tag_info[%d:%d] = %d\n", instance, targ, value);
1613         }
1614 }
1615
1616 static void
1617 ahc_linux_setup_dv(u_long arg, int instance, int targ, int32_t value)
1618 {
1619
1620         if ((instance >= 0)
1621          && (instance < NUM_ELEMENTS(aic7xxx_dv_settings))) {
1622                 aic7xxx_dv_settings[instance] = value;
1623                 if (bootverbose)
1624                         printf("dv[%d] = %d\n", instance, value);
1625         }
1626 }
1627
1628 /*
1629  * Handle Linux boot parameters. This routine allows for assigning a value
1630  * to a parameter with a ':' between the parameter and the value.
1631  * ie. aic7xxx=stpwlev:1,extended
1632  */
1633 static int
1634 aic7xxx_setup(char *s)
1635 {
1636         int     i, n;
1637         char   *p;
1638         char   *end;
1639
1640         static struct {
1641                 const char *name;
1642                 uint32_t *flag;
1643         } options[] = {
1644                 { "extended", &aic7xxx_extended },
1645                 { "no_reset", &aic7xxx_no_reset },
1646                 { "verbose", &aic7xxx_verbose },
1647                 { "allow_memio", &aic7xxx_allow_memio},
1648 #ifdef AHC_DEBUG
1649                 { "debug", &ahc_debug },
1650 #endif
1651                 { "reverse_scan", &aic7xxx_reverse_scan },
1652                 { "no_probe", &aic7xxx_probe_eisa_vl },
1653                 { "probe_eisa_vl", &aic7xxx_probe_eisa_vl },
1654                 { "periodic_otag", &aic7xxx_periodic_otag },
1655                 { "pci_parity", &aic7xxx_pci_parity },
1656                 { "seltime", &aic7xxx_seltime },
1657                 { "tag_info", NULL },
1658                 { "global_tag_depth", NULL },
1659                 { "dv", NULL }
1660         };
1661
1662         end = strchr(s, '\0');
1663
1664         /*
1665          * XXX ia64 gcc isn't smart enough to know that NUM_ELEMENTS
1666          * will never be 0 in this case.
1667          */
1668         n = 0;
1669
1670         while ((p = strsep(&s, ",.")) != NULL) {
1671                 if (*p == '\0')
1672                         continue;
1673                 for (i = 0; i < NUM_ELEMENTS(options); i++) {
1674
1675                         n = strlen(options[i].name);
1676                         if (strncmp(options[i].name, p, n) == 0)
1677                                 break;
1678                 }
1679                 if (i == NUM_ELEMENTS(options))
1680                         continue;
1681
1682                 if (strncmp(p, "global_tag_depth", n) == 0) {
1683                         ahc_linux_setup_tag_info_global(p + n);
1684                 } else if (strncmp(p, "tag_info", n) == 0) {
1685                         s = aic_parse_brace_option("tag_info", p + n, end,
1686                             2, ahc_linux_setup_tag_info, 0);
1687                 } else if (strncmp(p, "dv", n) == 0) {
1688                         s = aic_parse_brace_option("dv", p + n, end, 1,
1689                             ahc_linux_setup_dv, 0);
1690                 } else if (p[n] == ':') {
1691                         *(options[i].flag) = simple_strtoul(p + n + 1, NULL, 0);
1692                 } else if (strncmp(p, "verbose", n) == 0) {
1693                         *(options[i].flag) = 1;
1694                 } else {
1695                         *(options[i].flag) ^= 0xFFFFFFFF;
1696                 }
1697         }
1698         return 1;
1699 }
1700
1701 #if LINUX_VERSION_CODE > KERNEL_VERSION(2,3,0)
1702 __setup("aic7xxx=", aic7xxx_setup);
1703 #endif
1704
1705 uint32_t aic7xxx_verbose;
1706
1707 int
1708 ahc_linux_register_host(struct ahc_softc *ahc, Scsi_Host_Template *template)
1709 {
1710         char     buf[80];
1711         struct   Scsi_Host *host;
1712         char    *new_name;
1713         u_long   s;
1714         u_int    targ_offset;
1715
1716         template->name = ahc->description;
1717         host = scsi_host_alloc(template, sizeof(struct ahc_softc *));
1718         if (host == NULL)
1719                 return (ENOMEM);
1720
1721         *((struct ahc_softc **)host->hostdata) = ahc;
1722         ahc_lock(ahc, &s);
1723 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
1724         scsi_assign_lock(host, &ahc->platform_data->spin_lock);
1725 #elif AHC_SCSI_HAS_HOST_LOCK != 0
1726         host->lock = &ahc->platform_data->spin_lock;
1727 #endif
1728         ahc->platform_data->host = host;
1729         host->can_queue = AHC_MAX_QUEUE;
1730         host->cmd_per_lun = 2;
1731         /* XXX No way to communicate the ID for multiple channels */
1732         host->this_id = ahc->our_id;
1733         host->irq = ahc->platform_data->irq;
1734         host->max_id = (ahc->features & AHC_WIDE) ? 16 : 8;
1735         host->max_lun = AHC_NUM_LUNS;
1736         host->max_channel = (ahc->features & AHC_TWIN) ? 1 : 0;
1737         host->sg_tablesize = AHC_NSEG;
1738         ahc_set_unit(ahc, ahc_linux_next_unit());
1739         sprintf(buf, "scsi%d", host->host_no);
1740         new_name = malloc(strlen(buf) + 1, M_DEVBUF, M_NOWAIT);
1741         if (new_name != NULL) {
1742                 strcpy(new_name, buf);
1743                 ahc_set_name(ahc, new_name);
1744         }
1745         host->unique_id = ahc->unit;
1746 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,4) && \
1747     LINUX_VERSION_CODE  < KERNEL_VERSION(2,5,0)
1748         scsi_set_pci_device(host, ahc->dev_softc);
1749 #endif
1750         ahc_linux_initialize_scsi_bus(ahc);
1751         ahc_unlock(ahc, &s);
1752         ahc->platform_data->dv_pid = kernel_thread(ahc_linux_dv_thread, ahc, 0);
1753         ahc_lock(ahc, &s);
1754         if (ahc->platform_data->dv_pid < 0) {
1755                 printf("%s: Failed to create DV thread, error= %d\n",
1756                        ahc_name(ahc), ahc->platform_data->dv_pid);
1757                 return (-ahc->platform_data->dv_pid);
1758         }
1759         /*
1760          * Initially allocate *all* of our linux target objects
1761          * so that the DV thread will scan them all in parallel
1762          * just after driver initialization.  Any device that
1763          * does not exist will have its target object destroyed
1764          * by the selection timeout handler.  In the case of a
1765          * device that appears after the initial DV scan, async
1766          * negotiation will occur for the first command, and DV
1767          * will comence should that first command be successful.
1768          */
1769         for (targ_offset = 0;
1770              targ_offset < host->max_id * (host->max_channel + 1);
1771              targ_offset++) {
1772                 u_int channel;
1773                 u_int target;
1774
1775                 channel = 0;
1776                 target = targ_offset;
1777                 if (target > 7
1778                  && (ahc->features & AHC_TWIN) != 0) {
1779                         channel = 1;
1780                         target &= 0x7;
1781                 }
1782                 /*
1783                  * Skip our own ID.  Some Compaq/HP storage devices
1784                  * have enclosure management devices that respond to
1785                  * single bit selection (i.e. selecting ourselves).
1786                  * It is expected that either an external application
1787                  * or a modified kernel will be used to probe this
1788                  * ID if it is appropriate.  To accommodate these
1789                  * installations, ahc_linux_alloc_target() will allocate
1790                  * for our ID if asked to do so.
1791                  */
1792                 if ((channel == 0 && target == ahc->our_id)
1793                  || (channel == 1 && target == ahc->our_id_b))
1794                         continue;
1795
1796                 ahc_linux_alloc_target(ahc, channel, target);
1797         }
1798         ahc_intr_enable(ahc, TRUE);
1799         ahc_linux_start_dv(ahc);
1800         ahc_unlock(ahc, &s);
1801
1802 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
1803         scsi_add_host(host, (ahc->dev_softc ? &ahc->dev_softc->dev : NULL)); /* XXX handle failure */
1804         scsi_scan_host(host);
1805 #endif
1806         return (0);
1807 }
1808
1809 uint64_t
1810 ahc_linux_get_memsize(void)
1811 {
1812         struct sysinfo si;
1813
1814         si_meminfo(&si);
1815         return ((uint64_t)si.totalram << PAGE_SHIFT);
1816 }
1817
1818 /*
1819  * Find the smallest available unit number to use
1820  * for a new device.  We don't just use a static
1821  * count to handle the "repeated hot-(un)plug"
1822  * scenario.
1823  */
1824 static int
1825 ahc_linux_next_unit(void)
1826 {
1827         struct ahc_softc *ahc;
1828         int unit;
1829
1830         unit = 0;
1831 retry:
1832         TAILQ_FOREACH(ahc, &ahc_tailq, links) {
1833                 if (ahc->unit == unit) {
1834                         unit++;
1835                         goto retry;
1836                 }
1837         }
1838         return (unit);
1839 }
1840
1841 /*
1842  * Place the SCSI bus into a known state by either resetting it,
1843  * or forcing transfer negotiations on the next command to any
1844  * target.
1845  */
1846 void
1847 ahc_linux_initialize_scsi_bus(struct ahc_softc *ahc)
1848 {
1849         int i;
1850         int numtarg;
1851
1852         i = 0;
1853         numtarg = 0;
1854
1855         if (aic7xxx_no_reset != 0)
1856                 ahc->flags &= ~(AHC_RESET_BUS_A|AHC_RESET_BUS_B);
1857
1858         if ((ahc->flags & AHC_RESET_BUS_A) != 0)
1859                 ahc_reset_channel(ahc, 'A', /*initiate_reset*/TRUE);
1860         else
1861                 numtarg = (ahc->features & AHC_WIDE) ? 16 : 8;
1862
1863         if ((ahc->features & AHC_TWIN) != 0) {
1864
1865                 if ((ahc->flags & AHC_RESET_BUS_B) != 0) {
1866                         ahc_reset_channel(ahc, 'B', /*initiate_reset*/TRUE);
1867                 } else {
1868                         if (numtarg == 0)
1869                                 i = 8;
1870                         numtarg += 8;
1871                 }
1872         }
1873
1874         /*
1875          * Force negotiation to async for all targets that
1876          * will not see an initial bus reset.
1877          */
1878         for (; i < numtarg; i++) {
1879                 struct ahc_devinfo devinfo;
1880                 struct ahc_initiator_tinfo *tinfo;
1881                 struct ahc_tmode_tstate *tstate;
1882                 u_int our_id;
1883                 u_int target_id;
1884                 char channel;
1885
1886                 channel = 'A';
1887                 our_id = ahc->our_id;
1888                 target_id = i;
1889                 if (i > 7 && (ahc->features & AHC_TWIN) != 0) {
1890                         channel = 'B';
1891                         our_id = ahc->our_id_b;
1892                         target_id = i % 8;
1893                 }
1894                 tinfo = ahc_fetch_transinfo(ahc, channel, our_id,
1895                                             target_id, &tstate);
1896                 ahc_compile_devinfo(&devinfo, our_id, target_id,
1897                                     CAM_LUN_WILDCARD, channel, ROLE_INITIATOR);
1898                 ahc_update_neg_request(ahc, &devinfo, tstate,
1899                                        tinfo, AHC_NEG_ALWAYS);
1900         }
1901         /* Give the bus some time to recover */
1902         if ((ahc->flags & (AHC_RESET_BUS_A|AHC_RESET_BUS_B)) != 0) {
1903                 ahc_linux_freeze_simq(ahc);
1904                 init_timer(&ahc->platform_data->reset_timer);
1905                 ahc->platform_data->reset_timer.data = (u_long)ahc;
1906                 ahc->platform_data->reset_timer.expires =
1907                     jiffies + (AIC7XXX_RESET_DELAY * HZ)/1000;
1908                 ahc->platform_data->reset_timer.function =
1909                     ahc_linux_release_simq;
1910                 add_timer(&ahc->platform_data->reset_timer);
1911         }
1912 }
1913
1914 int
1915 ahc_platform_alloc(struct ahc_softc *ahc, void *platform_arg)
1916 {
1917
1918         ahc->platform_data =
1919             malloc(sizeof(struct ahc_platform_data), M_DEVBUF, M_NOWAIT);
1920         if (ahc->platform_data == NULL)
1921                 return (ENOMEM);
1922         memset(ahc->platform_data, 0, sizeof(struct ahc_platform_data));
1923         TAILQ_INIT(&ahc->platform_data->completeq);
1924         TAILQ_INIT(&ahc->platform_data->device_runq);
1925         ahc->platform_data->irq = AHC_LINUX_NOIRQ;
1926         ahc->platform_data->hw_dma_mask = 0xFFFFFFFF;
1927         ahc_lockinit(ahc);
1928         ahc_done_lockinit(ahc);
1929         init_timer(&ahc->platform_data->completeq_timer);
1930         ahc->platform_data->completeq_timer.data = (u_long)ahc;
1931         ahc->platform_data->completeq_timer.function =
1932             (ahc_linux_callback_t *)ahc_linux_thread_run_complete_queue;
1933 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,3,0)
1934         init_MUTEX_LOCKED(&ahc->platform_data->eh_sem);
1935         init_MUTEX_LOCKED(&ahc->platform_data->dv_sem);
1936         init_MUTEX_LOCKED(&ahc->platform_data->dv_cmd_sem);
1937 #else
1938         ahc->platform_data->eh_sem = MUTEX_LOCKED;
1939         ahc->platform_data->dv_sem = MUTEX_LOCKED;
1940         ahc->platform_data->dv_cmd_sem = MUTEX_LOCKED;
1941 #endif
1942 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0)
1943         tasklet_init(&ahc->platform_data->runq_tasklet, ahc_runq_tasklet,
1944                      (unsigned long)ahc);
1945 #endif
1946         ahc->seltime = (aic7xxx_seltime & 0x3) << 4;
1947         ahc->seltime_b = (aic7xxx_seltime & 0x3) << 4;
1948         if (aic7xxx_pci_parity == 0)
1949                 ahc->flags |= AHC_DISABLE_PCI_PERR;
1950
1951         return (0);
1952 }
1953
1954 void
1955 ahc_platform_free(struct ahc_softc *ahc)
1956 {
1957         struct ahc_linux_target *targ;
1958         struct ahc_linux_device *dev;
1959         int i, j;
1960
1961         if (ahc->platform_data != NULL) {
1962                 del_timer_sync(&ahc->platform_data->completeq_timer);
1963                 ahc_linux_kill_dv_thread(ahc);
1964 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0)
1965                 tasklet_kill(&ahc->platform_data->runq_tasklet);
1966 #endif
1967                 if (ahc->platform_data->host != NULL) {
1968 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
1969                         scsi_remove_host(ahc->platform_data->host);
1970 #endif
1971                         scsi_host_put(ahc->platform_data->host);
1972                 }
1973
1974                 /* destroy all of the device and target objects */
1975                 for (i = 0; i < AHC_NUM_TARGETS; i++) {
1976                         targ = ahc->platform_data->targets[i];
1977                         if (targ != NULL) {
1978                                 /* Keep target around through the loop. */
1979                                 targ->refcount++;
1980                                 for (j = 0; j < AHC_NUM_LUNS; j++) {
1981
1982                                         if (targ->devices[j] == NULL)
1983                                                 continue;
1984                                         dev = targ->devices[j];
1985                                         ahc_linux_free_device(ahc, dev);
1986                                 }
1987                                 /*
1988                                  * Forcibly free the target now that
1989                                  * all devices are gone.
1990                                  */
1991                                 ahc_linux_free_target(ahc, targ);
1992                         }
1993                 }
1994
1995                 if (ahc->platform_data->irq != AHC_LINUX_NOIRQ)
1996                         free_irq(ahc->platform_data->irq, ahc);
1997                 if (ahc->tag == BUS_SPACE_PIO
1998                  && ahc->bsh.ioport != 0)
1999                         release_region(ahc->bsh.ioport, 256);
2000                 if (ahc->tag == BUS_SPACE_MEMIO
2001                  && ahc->bsh.maddr != NULL) {
2002                         u_long base_addr;
2003
2004                         base_addr = (u_long)ahc->bsh.maddr;
2005                         base_addr &= PAGE_MASK;
2006                         iounmap((void *)base_addr);
2007 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0)
2008                         release_mem_region(ahc->platform_data->mem_busaddr,
2009                                            0x1000);
2010 #endif
2011                 }
2012 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0) && \
2013     LINUX_VERSION_CODE  < KERNEL_VERSION(2,5,0)
2014                 /*
2015                  * In 2.4 we detach from the scsi midlayer before the PCI
2016                  * layer invokes our remove callback.  No per-instance
2017                  * detach is provided, so we must reach inside the PCI
2018                  * subsystem's internals and detach our driver manually.
2019                  */
2020                 if (ahc->dev_softc != NULL)
2021                         ahc->dev_softc->driver = NULL;
2022 #endif
2023                 free(ahc->platform_data, M_DEVBUF);
2024         }
2025 }
2026
2027 void
2028 ahc_platform_freeze_devq(struct ahc_softc *ahc, struct scb *scb)
2029 {
2030         ahc_platform_abort_scbs(ahc, SCB_GET_TARGET(ahc, scb),
2031                                 SCB_GET_CHANNEL(ahc, scb),
2032                                 SCB_GET_LUN(scb), SCB_LIST_NULL,
2033                                 ROLE_UNKNOWN, CAM_REQUEUE_REQ);
2034 }
2035
2036 void
2037 ahc_platform_set_tags(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
2038                       ahc_queue_alg alg)
2039 {
2040         struct ahc_linux_device *dev;
2041         int was_queuing;
2042         int now_queuing;
2043
2044         dev = ahc_linux_get_device(ahc, devinfo->channel - 'A',
2045                                    devinfo->target,
2046                                    devinfo->lun, /*alloc*/FALSE);
2047         if (dev == NULL)
2048                 return;
2049         was_queuing = dev->flags & (AHC_DEV_Q_BASIC|AHC_DEV_Q_TAGGED);
2050         switch (alg) {
2051         default:
2052         case AHC_QUEUE_NONE:
2053                 now_queuing = 0;
2054                 break; 
2055         case AHC_QUEUE_BASIC:
2056                 now_queuing = AHC_DEV_Q_BASIC;
2057                 break;
2058         case AHC_QUEUE_TAGGED:
2059                 now_queuing = AHC_DEV_Q_TAGGED;
2060                 break;
2061         }
2062         if ((dev->flags & AHC_DEV_FREEZE_TIL_EMPTY) == 0
2063          && (was_queuing != now_queuing)
2064          && (dev->active != 0)) {
2065                 dev->flags |= AHC_DEV_FREEZE_TIL_EMPTY;
2066                 dev->qfrozen++;
2067         }
2068
2069         dev->flags &= ~(AHC_DEV_Q_BASIC|AHC_DEV_Q_TAGGED|AHC_DEV_PERIODIC_OTAG);
2070         if (now_queuing) {
2071                 u_int usertags;
2072
2073                 usertags = ahc_linux_user_tagdepth(ahc, devinfo);
2074                 if (!was_queuing) {
2075                         /*
2076                          * Start out agressively and allow our
2077                          * dynamic queue depth algorithm to take
2078                          * care of the rest.
2079                          */
2080                         dev->maxtags = usertags;
2081                         dev->openings = dev->maxtags - dev->active;
2082                 }
2083                 if (dev->maxtags == 0) {
2084                         /*
2085                          * Queueing is disabled by the user.
2086                          */
2087                         dev->openings = 1;
2088                 } else if (alg == AHC_QUEUE_TAGGED) {
2089                         dev->flags |= AHC_DEV_Q_TAGGED;
2090                         if (aic7xxx_periodic_otag != 0)
2091                                 dev->flags |= AHC_DEV_PERIODIC_OTAG;
2092                 } else
2093                         dev->flags |= AHC_DEV_Q_BASIC;
2094         } else {
2095                 /* We can only have one opening. */
2096                 dev->maxtags = 0;
2097                 dev->openings =  1 - dev->active;
2098         }
2099 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
2100         if (dev->scsi_device != NULL) {
2101                 switch ((dev->flags & (AHC_DEV_Q_BASIC|AHC_DEV_Q_TAGGED))) {
2102                 case AHC_DEV_Q_BASIC:
2103                         scsi_adjust_queue_depth(dev->scsi_device,
2104                                                 MSG_SIMPLE_TASK,
2105                                                 dev->openings + dev->active);
2106                         break;
2107                 case AHC_DEV_Q_TAGGED:
2108                         scsi_adjust_queue_depth(dev->scsi_device,
2109                                                 MSG_ORDERED_TASK,
2110                                                 dev->openings + dev->active);
2111                         break;
2112                 default:
2113                         /*
2114                          * We allow the OS to queue 2 untagged transactions to
2115                          * us at any time even though we can only execute them
2116                          * serially on the controller/device.  This should
2117                          * remove some latency.
2118                          */
2119                         scsi_adjust_queue_depth(dev->scsi_device,
2120                                                 /*NON-TAGGED*/0,
2121                                                 /*queue depth*/2);
2122                         break;
2123                 }
2124         }
2125 #endif
2126 }
2127
2128 int
2129 ahc_platform_abort_scbs(struct ahc_softc *ahc, int target, char channel,
2130                         int lun, u_int tag, role_t role, uint32_t status)
2131 {
2132         int chan;
2133         int maxchan;
2134         int targ;
2135         int maxtarg;
2136         int clun;
2137         int maxlun;
2138         int count;
2139
2140         if (tag != SCB_LIST_NULL)
2141                 return (0);
2142
2143         chan = 0;
2144         if (channel != ALL_CHANNELS) {
2145                 chan = channel - 'A';
2146                 maxchan = chan + 1;
2147         } else {
2148                 maxchan = (ahc->features & AHC_TWIN) ? 2 : 1;
2149         }
2150         targ = 0;
2151         if (target != CAM_TARGET_WILDCARD) {
2152                 targ = target;
2153                 maxtarg = targ + 1;
2154         } else {
2155                 maxtarg = (ahc->features & AHC_WIDE) ? 16 : 8;
2156         }
2157         clun = 0;
2158         if (lun != CAM_LUN_WILDCARD) {
2159                 clun = lun;
2160                 maxlun = clun + 1;
2161         } else {
2162                 maxlun = AHC_NUM_LUNS;
2163         }
2164
2165         count = 0;
2166         for (; chan < maxchan; chan++) {
2167
2168                 for (; targ < maxtarg; targ++) {
2169
2170                         for (; clun < maxlun; clun++) {
2171                                 struct ahc_linux_device *dev;
2172                                 struct ahc_busyq *busyq;
2173                                 struct ahc_cmd *acmd;
2174
2175                                 dev = ahc_linux_get_device(ahc, chan,
2176                                                            targ, clun,
2177                                                            /*alloc*/FALSE);
2178                                 if (dev == NULL)
2179                                         continue;
2180
2181                                 busyq = &dev->busyq;
2182                                 while ((acmd = TAILQ_FIRST(busyq)) != NULL) {
2183                                         Scsi_Cmnd *cmd;
2184
2185                                         cmd = &acmd_scsi_cmd(acmd);
2186                                         TAILQ_REMOVE(busyq, acmd,
2187                                                      acmd_links.tqe);
2188                                         count++;
2189                                         cmd->result = status << 16;
2190                                         ahc_linux_queue_cmd_complete(ahc, cmd);
2191                                 }
2192                         }
2193                 }
2194         }
2195
2196         return (count);
2197 }
2198
2199 static void
2200 ahc_linux_thread_run_complete_queue(struct ahc_softc *ahc)
2201 {
2202         u_long flags;
2203
2204         ahc_lock(ahc, &flags);
2205         del_timer(&ahc->platform_data->completeq_timer);
2206         ahc->platform_data->flags &= ~AHC_RUN_CMPLT_Q_TIMER;
2207         ahc_linux_run_complete_queue(ahc);
2208         ahc_unlock(ahc, &flags);
2209 }
2210
2211 static void
2212 ahc_linux_start_dv(struct ahc_softc *ahc)
2213 {
2214
2215         /*
2216          * Freeze the simq and signal ahc_linux_queue to not let any
2217          * more commands through.
2218          */
2219         if ((ahc->platform_data->flags & AHC_DV_ACTIVE) == 0) {
2220 #ifdef AHC_DEBUG
2221                 if (ahc_debug & AHC_SHOW_DV)
2222                         printf("%s: Waking DV thread\n", ahc_name(ahc));
2223 #endif
2224
2225                 ahc->platform_data->flags |= AHC_DV_ACTIVE;
2226                 ahc_linux_freeze_simq(ahc);
2227
2228                 /* Wake up the DV kthread */
2229                 up(&ahc->platform_data->dv_sem);
2230         }
2231 }
2232
2233 static void
2234 ahc_linux_kill_dv_thread(struct ahc_softc *ahc)
2235 {
2236         u_long s;
2237
2238         ahc_lock(ahc, &s);
2239         if (ahc->platform_data->dv_pid != 0) {
2240                 ahc->platform_data->flags |= AHC_DV_SHUTDOWN;
2241                 ahc_unlock(ahc, &s);
2242                 up(&ahc->platform_data->dv_sem);
2243
2244                 /*
2245                  * Use the eh_sem as an indicator that the
2246                  * dv thread is exiting.  Note that the dv
2247                  * thread must still return after performing
2248                  * the up on our semaphore before it has
2249                  * completely exited this module.  Unfortunately,
2250                  * there seems to be no easy way to wait for the
2251                  * exit of a thread for which you are not the
2252                  * parent (dv threads are parented by init).
2253                  * Cross your fingers...
2254                  */
2255                 down(&ahc->platform_data->eh_sem);
2256
2257                 /*
2258                  * Mark the dv thread as already dead.  This
2259                  * avoids attempting to kill it a second time.
2260                  * This is necessary because we must kill the
2261                  * DV thread before calling ahc_free() in the
2262                  * module shutdown case to avoid bogus locking
2263                  * in the SCSI mid-layer, but we ahc_free() is
2264                  * called without killing the DV thread in the
2265                  * instance detach case, so ahc_platform_free()
2266                  * calls us again to verify that the DV thread
2267                  * is dead.
2268                  */
2269                 ahc->platform_data->dv_pid = 0;
2270         } else {
2271                 ahc_unlock(ahc, &s);
2272         }
2273 }
2274
2275 static int
2276 ahc_linux_dv_thread(void *data)
2277 {
2278         struct  ahc_softc *ahc;
2279         int     target;
2280         u_long  s;
2281
2282         ahc = (struct ahc_softc *)data;
2283
2284 #ifdef AHC_DEBUG
2285         if (ahc_debug & AHC_SHOW_DV)
2286                 printf("Launching DV Thread\n");
2287 #endif
2288
2289         /*
2290          * Complete thread creation.
2291          */
2292         lock_kernel();
2293 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
2294         /*
2295          * Don't care about any signals.
2296          */
2297         siginitsetinv(&current->blocked, 0);
2298
2299         daemonize();
2300         sprintf(current->comm, "ahc_dv_%d", ahc->unit);
2301 #else
2302         daemonize("ahc_dv_%d", ahc->unit);
2303         current->flags |= PF_FREEZE;
2304 #endif
2305         unlock_kernel();
2306
2307         while (1) {
2308                 /*
2309                  * Use down_interruptible() rather than down() to
2310                  * avoid inclusion in the load average.
2311                  */
2312                 down_interruptible(&ahc->platform_data->dv_sem);
2313
2314                 /* Check to see if we've been signaled to exit */
2315                 ahc_lock(ahc, &s);
2316                 if ((ahc->platform_data->flags & AHC_DV_SHUTDOWN) != 0) {
2317                         ahc_unlock(ahc, &s);
2318                         break;
2319                 }
2320                 ahc_unlock(ahc, &s);
2321
2322 #ifdef AHC_DEBUG
2323                 if (ahc_debug & AHC_SHOW_DV)
2324                         printf("%s: Beginning Domain Validation\n",
2325                                ahc_name(ahc));
2326 #endif
2327
2328                 /*
2329                  * Wait for any pending commands to drain before proceeding.
2330                  */
2331                 ahc_lock(ahc, &s);
2332                 while (LIST_FIRST(&ahc->pending_scbs) != NULL) {
2333                         ahc->platform_data->flags |= AHC_DV_WAIT_SIMQ_EMPTY;
2334                         ahc_unlock(ahc, &s);
2335                         down_interruptible(&ahc->platform_data->dv_sem);
2336                         ahc_lock(ahc, &s);
2337                 }
2338
2339                 /*
2340                  * Wait for the SIMQ to be released so that DV is the
2341                  * only reason the queue is frozen.
2342                  */
2343                 while (AHC_DV_SIMQ_FROZEN(ahc) == 0) {
2344                         ahc->platform_data->flags |= AHC_DV_WAIT_SIMQ_RELEASE;
2345                         ahc_unlock(ahc, &s);
2346                         down_interruptible(&ahc->platform_data->dv_sem);
2347                         ahc_lock(ahc, &s);
2348                 }
2349                 ahc_unlock(ahc, &s);
2350
2351                 for (target = 0; target < AHC_NUM_TARGETS; target++)
2352                         ahc_linux_dv_target(ahc, target);
2353
2354                 ahc_lock(ahc, &s);
2355                 ahc->platform_data->flags &= ~AHC_DV_ACTIVE;
2356                 ahc_unlock(ahc, &s);
2357
2358                 /*
2359                  * Release the SIMQ so that normal commands are
2360                  * allowed to continue on the bus.
2361                  */
2362                 ahc_linux_release_simq((u_long)ahc);
2363         }
2364         up(&ahc->platform_data->eh_sem);
2365         return (0);
2366 }
2367
2368 #define AHC_LINUX_DV_INQ_SHORT_LEN      36
2369 #define AHC_LINUX_DV_INQ_LEN            256
2370 #define AHC_LINUX_DV_TIMEOUT            (HZ / 4)
2371
2372 #define AHC_SET_DV_STATE(ahc, targ, newstate) \
2373         ahc_set_dv_state(ahc, targ, newstate, __LINE__)
2374
2375 static __inline void
2376 ahc_set_dv_state(struct ahc_softc *ahc, struct ahc_linux_target *targ,
2377                  ahc_dv_state newstate, u_int line)
2378 {
2379         ahc_dv_state oldstate;
2380
2381         oldstate = targ->dv_state;
2382 #ifdef AHC_DEBUG
2383         if (ahc_debug & AHC_SHOW_DV)
2384                 printf("%s:%d: Going from state %d to state %d\n",
2385                        ahc_name(ahc), line, oldstate, newstate);
2386 #endif
2387
2388         if (oldstate == newstate)
2389                 targ->dv_state_retry++;
2390         else
2391                 targ->dv_state_retry = 0;
2392         targ->dv_state = newstate;
2393 }
2394
2395 static void
2396 ahc_linux_dv_target(struct ahc_softc *ahc, u_int target_offset)
2397 {
2398         struct   ahc_devinfo devinfo;
2399         struct   ahc_linux_target *targ;
2400         struct   scsi_cmnd *cmd;
2401         struct   scsi_device *scsi_dev;
2402         struct   scsi_sense_data *sense;
2403         uint8_t *buffer;
2404         u_long   s;
2405         u_int    timeout;
2406         int      echo_size;
2407
2408         sense = NULL;
2409         buffer = NULL;
2410         echo_size = 0;
2411         ahc_lock(ahc, &s);
2412         targ = ahc->platform_data->targets[target_offset];
2413         if (targ == NULL || (targ->flags & AHC_DV_REQUIRED) == 0) {
2414                 ahc_unlock(ahc, &s);
2415                 return;
2416         }
2417         ahc_compile_devinfo(&devinfo,
2418                             targ->channel == 0 ? ahc->our_id : ahc->our_id_b,
2419                             targ->target, /*lun*/0, targ->channel + 'A',
2420                             ROLE_INITIATOR);
2421 #ifdef AHC_DEBUG
2422         if (ahc_debug & AHC_SHOW_DV) {
2423                 ahc_print_devinfo(ahc, &devinfo);
2424                 printf("Performing DV\n");
2425         }
2426 #endif
2427
2428         ahc_unlock(ahc, &s);
2429
2430         cmd = malloc(sizeof(struct scsi_cmnd), M_DEVBUF, M_WAITOK);
2431         scsi_dev = malloc(sizeof(struct scsi_device), M_DEVBUF, M_WAITOK);
2432         scsi_dev->host = ahc->platform_data->host;
2433         scsi_dev->id = devinfo.target;
2434         scsi_dev->lun = devinfo.lun;
2435         scsi_dev->channel = devinfo.channel - 'A';
2436         ahc->platform_data->dv_scsi_dev = scsi_dev;
2437
2438         AHC_SET_DV_STATE(ahc, targ, AHC_DV_STATE_INQ_SHORT_ASYNC);
2439
2440         while (targ->dv_state != AHC_DV_STATE_EXIT) {
2441                 timeout = AHC_LINUX_DV_TIMEOUT;
2442                 switch (targ->dv_state) {
2443                 case AHC_DV_STATE_INQ_SHORT_ASYNC:
2444                 case AHC_DV_STATE_INQ_ASYNC:
2445                 case AHC_DV_STATE_INQ_ASYNC_VERIFY:
2446                         /*
2447                          * Set things to async narrow to reduce the
2448                          * chance that the INQ will fail.
2449                          */
2450                         ahc_lock(ahc, &s);
2451                         ahc_set_syncrate(ahc, &devinfo, NULL, 0, 0, 0,
2452                                          AHC_TRANS_GOAL, /*paused*/FALSE);
2453                         ahc_set_width(ahc, &devinfo, MSG_EXT_WDTR_BUS_8_BIT,
2454                                       AHC_TRANS_GOAL, /*paused*/FALSE);
2455                         ahc_unlock(ahc, &s);
2456                         timeout = 10 * HZ;
2457                         targ->flags &= ~AHC_INQ_VALID;
2458                         /* FALLTHROUGH */
2459                 case AHC_DV_STATE_INQ_VERIFY:
2460                 {
2461                         u_int inq_len;
2462
2463                         if (targ->dv_state == AHC_DV_STATE_INQ_SHORT_ASYNC)
2464                                 inq_len = AHC_LINUX_DV_INQ_SHORT_LEN;
2465                         else
2466                                 inq_len = targ->inq_data->additional_length + 5;
2467                         ahc_linux_dv_inq(ahc, cmd, &devinfo, targ, inq_len);
2468                         break;
2469                 }
2470                 case AHC_DV_STATE_TUR:
2471                 case AHC_DV_STATE_BUSY:
2472                         timeout = 5 * HZ;
2473                         ahc_linux_dv_tur(ahc, cmd, &devinfo);
2474                         break;
2475                 case AHC_DV_STATE_REBD:
2476                         ahc_linux_dv_rebd(ahc, cmd, &devinfo, targ);
2477                         break;
2478                 case AHC_DV_STATE_WEB:
2479                         ahc_linux_dv_web(ahc, cmd, &devinfo, targ);
2480                         break;
2481
2482                 case AHC_DV_STATE_REB:
2483                         ahc_linux_dv_reb(ahc, cmd, &devinfo, targ);
2484                         break;
2485
2486                 case AHC_DV_STATE_SU:
2487                         ahc_linux_dv_su(ahc, cmd, &devinfo, targ);
2488                         timeout = 50 * HZ;
2489                         break;
2490
2491                 default:
2492                         ahc_print_devinfo(ahc, &devinfo);
2493                         printf("Unknown DV state %d\n", targ->dv_state);
2494                         goto out;
2495                 }
2496
2497                 /* Queue the command and wait for it to complete */
2498                 /* Abuse eh_timeout in the scsi_cmnd struct for our purposes */
2499                 init_timer(&cmd->eh_timeout);
2500 #ifdef AHC_DEBUG
2501                 if ((ahc_debug & AHC_SHOW_MESSAGES) != 0)
2502                         /*
2503                          * All of the printfs during negotiation
2504                          * really slow down the negotiation.
2505                          * Add a bit of time just to be safe.
2506                          */
2507                         timeout += HZ;
2508 #endif
2509                 scsi_add_timer(cmd, timeout, ahc_linux_dv_timeout);
2510                 /*
2511                  * In 2.5.X, it is assumed that all calls from the
2512                  * "midlayer" (which we are emulating) will have the
2513                  * ahc host lock held.  For other kernels, the
2514                  * io_request_lock must be held.
2515                  */
2516 #if AHC_SCSI_HAS_HOST_LOCK != 0
2517                 ahc_lock(ahc, &s);
2518 #else
2519                 spin_lock_irqsave(&io_request_lock, s);
2520 #endif
2521                 ahc_linux_queue(cmd, ahc_linux_dv_complete);
2522 #if AHC_SCSI_HAS_HOST_LOCK != 0
2523                 ahc_unlock(ahc, &s);
2524 #else
2525                 spin_unlock_irqrestore(&io_request_lock, s);
2526 #endif
2527                 down_interruptible(&ahc->platform_data->dv_cmd_sem);
2528                 /*
2529                  * Wait for the SIMQ to be released so that DV is the
2530                  * only reason the queue is frozen.
2531                  */
2532                 ahc_lock(ahc, &s);
2533                 while (AHC_DV_SIMQ_FROZEN(ahc) == 0) {
2534                         ahc->platform_data->flags |= AHC_DV_WAIT_SIMQ_RELEASE;
2535                         ahc_unlock(ahc, &s);
2536                         down_interruptible(&ahc->platform_data->dv_sem);
2537                         ahc_lock(ahc, &s);
2538                 }
2539                 ahc_unlock(ahc, &s);
2540
2541                 ahc_linux_dv_transition(ahc, cmd, &devinfo, targ);
2542         }
2543
2544 out:
2545         if ((targ->flags & AHC_INQ_VALID) != 0
2546          && ahc_linux_get_device(ahc, devinfo.channel - 'A',
2547                                  devinfo.target, devinfo.lun,
2548                                  /*alloc*/FALSE) == NULL) {
2549                 /*
2550                  * The DV state machine failed to configure this device.  
2551                  * This is normal if DV is disabled.  Since we have inquiry
2552                  * data, filter it and use the "optimistic" negotiation
2553                  * parameters found in the inquiry string.
2554                  */
2555                 ahc_linux_filter_inquiry(ahc, &devinfo);
2556                 if ((targ->flags & (AHC_BASIC_DV|AHC_ENHANCED_DV)) != 0) {
2557                         ahc_print_devinfo(ahc, &devinfo);
2558                         printf("DV failed to configure device.  "
2559                                "Please file a bug report against "
2560                                "this driver.\n");
2561                 }
2562         }
2563
2564         if (cmd != NULL)
2565                 free(cmd, M_DEVBUF);
2566
2567         if (ahc->platform_data->dv_scsi_dev != NULL) {
2568                 free(ahc->platform_data->dv_scsi_dev, M_DEVBUF);
2569                 ahc->platform_data->dv_scsi_dev = NULL;
2570         }
2571
2572         ahc_lock(ahc, &s);
2573         if (targ->dv_buffer != NULL) {
2574                 free(targ->dv_buffer, M_DEVBUF);
2575                 targ->dv_buffer = NULL;
2576         }
2577         if (targ->dv_buffer1 != NULL) {
2578                 free(targ->dv_buffer1, M_DEVBUF);
2579                 targ->dv_buffer1 = NULL;
2580         }
2581         targ->flags &= ~AHC_DV_REQUIRED;
2582         if (targ->refcount == 0)
2583                 ahc_linux_free_target(ahc, targ);
2584         ahc_unlock(ahc, &s);
2585 }
2586
2587 static void
2588 ahc_linux_dv_transition(struct ahc_softc *ahc, struct scsi_cmnd *cmd,
2589                         struct ahc_devinfo *devinfo,
2590                         struct ahc_linux_target *targ)
2591 {
2592         u_int32_t status;
2593
2594         status = aic_error_action(cmd, targ->inq_data,
2595                                   ahc_cmd_get_transaction_status(cmd),
2596                                   ahc_cmd_get_scsi_status(cmd));
2597         
2598 #ifdef AHC_DEBUG
2599         if (ahc_debug & AHC_SHOW_DV) {
2600                 ahc_print_devinfo(ahc, devinfo);
2601                 printf("Entering ahc_linux_dv_transition, state= %d, "
2602                        "status= 0x%x, cmd->result= 0x%x\n", targ->dv_state,
2603                        status, cmd->result);
2604         }
2605 #endif
2606
2607         switch (targ->dv_state) {
2608         case AHC_DV_STATE_INQ_SHORT_ASYNC:
2609         case AHC_DV_STATE_INQ_ASYNC:
2610                 switch (status & SS_MASK) {
2611                 case SS_NOP:
2612                 {
2613                         AHC_SET_DV_STATE(ahc, targ, targ->dv_state+1);
2614                         break;
2615                 }
2616                 case SS_INQ_REFRESH:
2617                         AHC_SET_DV_STATE(ahc, targ,
2618                                          AHC_DV_STATE_INQ_SHORT_ASYNC);
2619                         break;
2620                 case SS_TUR:
2621                 case SS_RETRY:
2622                         AHC_SET_DV_STATE(ahc, targ, targ->dv_state);
2623                         if (ahc_cmd_get_transaction_status(cmd)
2624                          == CAM_REQUEUE_REQ)
2625                                 targ->dv_state_retry--;
2626                         if ((status & SS_ERRMASK) == EBUSY)
2627                                 AHC_SET_DV_STATE(ahc, targ, AHC_DV_STATE_BUSY);
2628                         if (targ->dv_state_retry < 10)
2629                                 break;
2630                         /* FALLTHROUGH */
2631                 default:
2632                         AHC_SET_DV_STATE(ahc, targ, AHC_DV_STATE_EXIT);
2633 #ifdef AHC_DEBUG
2634                         if (ahc_debug & AHC_SHOW_DV) {
2635                                 ahc_print_devinfo(ahc, devinfo);
2636                                 printf("Failed DV inquiry, skipping\n");
2637                         }
2638 #endif
2639                         break;
2640                 }
2641                 break;
2642         case AHC_DV_STATE_INQ_ASYNC_VERIFY:
2643                 switch (status & SS_MASK) {
2644                 case SS_NOP:
2645                 {
2646                         u_int xportflags;
2647                         u_int spi3data;
2648
2649                         if (memcmp(targ->inq_data, targ->dv_buffer,
2650                                    AHC_LINUX_DV_INQ_LEN) != 0) {
2651                                 /*
2652                                  * Inquiry data must have changed.
2653                                  * Try from the top again.
2654                                  */
2655                                 AHC_SET_DV_STATE(ahc, targ,
2656                                                  AHC_DV_STATE_INQ_SHORT_ASYNC);
2657                                 break;
2658                         }
2659
2660                         AHC_SET_DV_STATE(ahc, targ, targ->dv_state+1);
2661                         targ->flags |= AHC_INQ_VALID;
2662                         if (ahc_linux_user_dv_setting(ahc) == 0)
2663                                 break;
2664
2665                         xportflags = targ->inq_data->flags;
2666                         if ((xportflags & (SID_Sync|SID_WBus16)) == 0)
2667                                 break;
2668
2669                         spi3data = targ->inq_data->spi3data;
2670                         switch (spi3data & SID_SPI_CLOCK_DT_ST) {
2671                         default:
2672                         case SID_SPI_CLOCK_ST:
2673                                 /* Assume only basic DV is supported. */
2674                                 targ->flags |= AHC_BASIC_DV;
2675                                 break;
2676                         case SID_SPI_CLOCK_DT:
2677                         case SID_SPI_CLOCK_DT_ST:
2678                                 targ->flags |= AHC_ENHANCED_DV;
2679                                 break;
2680                         }
2681                         break;
2682                 }
2683                 case SS_INQ_REFRESH:
2684                         AHC_SET_DV_STATE(ahc, targ,
2685                                          AHC_DV_STATE_INQ_SHORT_ASYNC);
2686                         break;
2687                 case SS_TUR:
2688                 case SS_RETRY:
2689                         AHC_SET_DV_STATE(ahc, targ, targ->dv_state);
2690                         if (ahc_cmd_get_transaction_status(cmd)
2691                          == CAM_REQUEUE_REQ)
2692                                 targ->dv_state_retry--;
2693
2694                         if ((status & SS_ERRMASK) == EBUSY)
2695                                 AHC_SET_DV_STATE(ahc, targ, AHC_DV_STATE_BUSY);
2696                         if (targ->dv_state_retry < 10)
2697                                 break;
2698                         /* FALLTHROUGH */
2699                 default:
2700                         AHC_SET_DV_STATE(ahc, targ, AHC_DV_STATE_EXIT);
2701 #ifdef AHC_DEBUG
2702                         if (ahc_debug & AHC_SHOW_DV) {
2703                                 ahc_print_devinfo(ahc, devinfo);
2704                                 printf("Failed DV inquiry, skipping\n");
2705                         }
2706 #endif
2707                         break;
2708                 }
2709                 break;
2710         case AHC_DV_STATE_INQ_VERIFY:
2711                 switch (status & SS_MASK) {
2712                 case SS_NOP:
2713                 {
2714
2715                         if (memcmp(targ->inq_data, targ->dv_buffer,
2716                                    AHC_LINUX_DV_INQ_LEN) == 0) {
2717                                 AHC_SET_DV_STATE(ahc, targ, AHC_DV_STATE_EXIT);
2718                                 break;
2719                         }
2720 #ifdef AHC_DEBUG
2721                         if (ahc_debug & AHC_SHOW_DV) {
2722                                 int i;
2723
2724                                 ahc_print_devinfo(ahc, devinfo);
2725                                 printf("Inquiry buffer mismatch:");
2726                                 for (i = 0; i < AHC_LINUX_DV_INQ_LEN; i++) {
2727                                         if ((i & 0xF) == 0)
2728                                                 printf("\n        ");
2729                                         printf("0x%x:0x0%x ",
2730                                                ((uint8_t *)targ->inq_data)[i], 
2731                                                targ->dv_buffer[i]);
2732                                 }
2733                                 printf("\n");
2734                         }
2735 #endif
2736
2737                         if (ahc_linux_fallback(ahc, devinfo) != 0) {
2738                                 AHC_SET_DV_STATE(ahc, targ, AHC_DV_STATE_EXIT);
2739                                 break;
2740                         }
2741                         /*
2742                          * Do not count "falling back"
2743                          * against our retries.
2744                          */
2745                         targ->dv_state_retry = 0;
2746                         AHC_SET_DV_STATE(ahc, targ, targ->dv_state);
2747                         break;
2748                 }
2749                 case SS_INQ_REFRESH:
2750                         AHC_SET_DV_STATE(ahc, targ,
2751                                          AHC_DV_STATE_INQ_SHORT_ASYNC);
2752                         break;
2753                 case SS_TUR:
2754                 case SS_RETRY:
2755                         AHC_SET_DV_STATE(ahc, targ, targ->dv_state);
2756                         if (ahc_cmd_get_transaction_status(cmd)
2757                          == CAM_REQUEUE_REQ) {
2758                                 targ->dv_state_retry--;
2759                         } else if ((status & SSQ_FALLBACK) != 0) {
2760                                 if (ahc_linux_fallback(ahc, devinfo) != 0) {
2761                                         AHC_SET_DV_STATE(ahc, targ,
2762                                                          AHC_DV_STATE_EXIT);
2763                                         break;
2764                                 }
2765                                 /*
2766                                  * Do not count "falling back"
2767                                  * against our retries.
2768                                  */
2769                                 targ->dv_state_retry = 0;
2770                         } else if ((status & SS_ERRMASK) == EBUSY)
2771                                 AHC_SET_DV_STATE(ahc, targ, AHC_DV_STATE_BUSY);
2772                         if (targ->dv_state_retry < 10)
2773                                 break;
2774                         /* FALLTHROUGH */
2775                 default:
2776                         AHC_SET_DV_STATE(ahc, targ, AHC_DV_STATE_EXIT);
2777 #ifdef AHC_DEBUG
2778                         if (ahc_debug & AHC_SHOW_DV) {
2779                                 ahc_print_devinfo(ahc, devinfo);
2780                                 printf("Failed DV inquiry, skipping\n");
2781                         }
2782 #endif
2783                         break;
2784                 }
2785                 break;
2786
2787         case AHC_DV_STATE_TUR:
2788                 switch (status & SS_MASK) {
2789                 case SS_NOP:
2790                         if ((targ->flags & AHC_BASIC_DV) != 0) {
2791                                 ahc_linux_filter_inquiry(ahc, devinfo);
2792                                 AHC_SET_DV_STATE(ahc, targ,
2793                                                  AHC_DV_STATE_INQ_VERIFY);
2794                         } else if ((targ->flags & AHC_ENHANCED_DV) != 0) {
2795                                 AHC_SET_DV_STATE(ahc, targ, AHC_DV_STATE_REBD);
2796                         } else {
2797                                 AHC_SET_DV_STATE(ahc, targ, AHC_DV_STATE_EXIT);
2798                         }
2799                         break;
2800                 case SS_RETRY:
2801                 case SS_TUR:
2802                         if ((status & SS_ERRMASK) == EBUSY) {
2803                                 AHC_SET_DV_STATE(ahc, targ, AHC_DV_STATE_BUSY);
2804                                 break;
2805                         }
2806                         AHC_SET_DV_STATE(ahc, targ, targ->dv_state);
2807                         if (ahc_cmd_get_transaction_status(cmd)
2808                          == CAM_REQUEUE_REQ) {
2809                                 targ->dv_state_retry--;
2810                         } else if ((status & SSQ_FALLBACK) != 0) {
2811                                 if (ahc_linux_fallback(ahc, devinfo) != 0) {
2812                                         AHC_SET_DV_STATE(ahc, targ,
2813                                                          AHC_DV_STATE_EXIT);
2814                                         break;
2815                                 }
2816                                 /*
2817                                  * Do not count "falling back"
2818                                  * against our retries.
2819                                  */
2820                                 targ->dv_state_retry = 0;
2821                         }
2822                         if (targ->dv_state_retry >= 10) {
2823 #ifdef AHC_DEBUG
2824                                 if (ahc_debug & AHC_SHOW_DV) {
2825                                         ahc_print_devinfo(ahc, devinfo);
2826                                         printf("DV TUR reties exhausted\n");
2827                                 }
2828 #endif
2829                                 AHC_SET_DV_STATE(ahc, targ, AHC_DV_STATE_EXIT);
2830                                 break;
2831                         }
2832                         if (status & SSQ_DELAY)
2833                                 scsi_sleep(1 * HZ);
2834
2835                         break;
2836                 case SS_START:
2837                         AHC_SET_DV_STATE(ahc, targ, AHC_DV_STATE_SU);
2838                         break;
2839                 case SS_INQ_REFRESH:
2840                         AHC_SET_DV_STATE(ahc, targ,
2841                                          AHC_DV_STATE_INQ_SHORT_ASYNC);
2842                         break;
2843                 default:
2844                         AHC_SET_DV_STATE(ahc, targ, AHC_DV_STATE_EXIT);
2845                         break;
2846                 }
2847                 break;
2848
2849         case AHC_DV_STATE_REBD:
2850                 switch (status & SS_MASK) {
2851                 case SS_NOP:
2852                 {
2853                         uint32_t echo_size;
2854
2855                         AHC_SET_DV_STATE(ahc, targ, AHC_DV_STATE_WEB);
2856                         echo_size = scsi_3btoul(&targ->dv_buffer[1]);
2857                         echo_size &= 0x1FFF;
2858 #ifdef AHC_DEBUG
2859                         if (ahc_debug & AHC_SHOW_DV) {
2860                                 ahc_print_devinfo(ahc, devinfo);
2861                                 printf("Echo buffer size= %d\n", echo_size);
2862                         }
2863 #endif
2864                         if (echo_size == 0) {
2865                                 AHC_SET_DV_STATE(ahc, targ, AHC_DV_STATE_EXIT);
2866                                 break;
2867                         }
2868
2869                         /* Generate the buffer pattern */
2870                         targ->dv_echo_size = echo_size;
2871                         ahc_linux_generate_dv_pattern(targ);
2872                         /*
2873                          * Setup initial negotiation values.
2874                          */
2875                         ahc_linux_filter_inquiry(ahc, devinfo);
2876                         break;
2877                 }
2878                 case SS_INQ_REFRESH:
2879                         AHC_SET_DV_STATE(ahc, targ,
2880                                          AHC_DV_STATE_INQ_SHORT_ASYNC);
2881                         break;
2882                 case SS_RETRY:
2883                         AHC_SET_DV_STATE(ahc, targ, targ->dv_state);
2884                         if (ahc_cmd_get_transaction_status(cmd)
2885                          == CAM_REQUEUE_REQ)
2886                                 targ->dv_state_retry--;
2887                         if (targ->dv_state_retry <= 10)
2888                                 break;
2889 #ifdef AHC_DEBUG
2890                         if (ahc_debug & AHC_SHOW_DV) {
2891                                 ahc_print_devinfo(ahc, devinfo);
2892                                 printf("DV REBD reties exhausted\n");
2893                         }
2894 #endif
2895                         /* FALLTHROUGH */
2896                 case SS_FATAL:
2897                 default:
2898                         /*
2899                          * Setup initial negotiation values
2900                          * and try level 1 DV.
2901                          */
2902                         ahc_linux_filter_inquiry(ahc, devinfo);
2903                         AHC_SET_DV_STATE(ahc, targ, AHC_DV_STATE_INQ_VERIFY);
2904                         targ->dv_echo_size = 0;
2905                         break;
2906                 }
2907                 break;
2908
2909         case AHC_DV_STATE_WEB:
2910                 switch (status & SS_MASK) {
2911                 case SS_NOP:
2912                         AHC_SET_DV_STATE(ahc, targ, AHC_DV_STATE_REB);
2913                         break;
2914                 case SS_INQ_REFRESH:
2915                         AHC_SET_DV_STATE(ahc, targ,
2916                                          AHC_DV_STATE_INQ_SHORT_ASYNC);
2917                         break;
2918                 case SS_RETRY:
2919                         AHC_SET_DV_STATE(ahc, targ, targ->dv_state);
2920                         if (ahc_cmd_get_transaction_status(cmd)
2921                          == CAM_REQUEUE_REQ) {
2922                                 targ->dv_state_retry--;
2923                         } else if ((status & SSQ_FALLBACK) != 0) {
2924                                 if (ahc_linux_fallback(ahc, devinfo) != 0) {
2925                                         AHC_SET_DV_STATE(ahc, targ,
2926                                                          AHC_DV_STATE_EXIT);
2927                                         break;
2928                                 }
2929                                 /*
2930                                  * Do not count "falling back"
2931                                  * against our retries.
2932                                  */
2933                                 targ->dv_state_retry = 0;
2934                         }
2935                         if (targ->dv_state_retry <= 10)
2936                                 break;
2937                         /* FALLTHROUGH */
2938 #ifdef AHC_DEBUG
2939                         if (ahc_debug & AHC_SHOW_DV) {
2940                                 ahc_print_devinfo(ahc, devinfo);
2941                                 printf("DV WEB reties exhausted\n");
2942                         }
2943 #endif
2944                 default:
2945                         AHC_SET_DV_STATE(ahc, targ, AHC_DV_STATE_EXIT);
2946                         break;
2947                 }
2948                 break;
2949
2950         case AHC_DV_STATE_REB:
2951                 switch (status & SS_MASK) {
2952                 case SS_NOP:
2953                         if (memcmp(targ->dv_buffer, targ->dv_buffer1,
2954                                    targ->dv_echo_size) != 0) {
2955                                 if (ahc_linux_fallback(ahc, devinfo) != 0)
2956                                         AHC_SET_DV_STATE(ahc, targ,
2957                                                          AHC_DV_STATE_EXIT);
2958                                 else
2959                                         AHC_SET_DV_STATE(ahc, targ,
2960                                                          AHC_DV_STATE_WEB);
2961                                 break;
2962                         }
2963                         
2964                         if (targ->dv_buffer != NULL) {
2965                                 free(targ->dv_buffer, M_DEVBUF);
2966                                 targ->dv_buffer = NULL;
2967                         }
2968                         if (targ->dv_buffer1 != NULL) {
2969                                 free(targ->dv_buffer1, M_DEVBUF);
2970                                 targ->dv_buffer1 = NULL;
2971                         }
2972                         AHC_SET_DV_STATE(ahc, targ, AHC_DV_STATE_EXIT);
2973                         break;
2974                 case SS_INQ_REFRESH:
2975                         AHC_SET_DV_STATE(ahc, targ,
2976                                          AHC_DV_STATE_INQ_SHORT_ASYNC);
2977                         break;
2978                 case SS_RETRY:
2979                         AHC_SET_DV_STATE(ahc, targ, targ->dv_state);
2980                         if (ahc_cmd_get_transaction_status(cmd)
2981                          == CAM_REQUEUE_REQ) {
2982                                 targ->dv_state_retry--;
2983                         } else if ((status & SSQ_FALLBACK) != 0) {
2984                                 if (ahc_linux_fallback(ahc, devinfo) != 0) {
2985                                         AHC_SET_DV_STATE(ahc, targ,
2986                                                          AHC_DV_STATE_EXIT);
2987                                         break;
2988                                 }
2989                                 AHC_SET_DV_STATE(ahc, targ, AHC_DV_STATE_WEB);
2990                         }
2991                         if (targ->dv_state_retry <= 10) {
2992                                 if ((status & (SSQ_DELAY_RANDOM|SSQ_DELAY))!= 0)
2993                                         scsi_sleep(ahc->our_id*HZ/10);
2994                                 break;
2995                         }
2996 #ifdef AHC_DEBUG
2997                         if (ahc_debug & AHC_SHOW_DV) {
2998                                 ahc_print_devinfo(ahc, devinfo);
2999                                 printf("DV REB reties exhausted\n");
3000                         }
3001 #endif
3002                         /* FALLTHROUGH */
3003                 default:
3004                         AHC_SET_DV_STATE(ahc, targ, AHC_DV_STATE_EXIT);
3005                         break;
3006                 }
3007                 break;
3008
3009         case AHC_DV_STATE_SU:
3010                 switch (status & SS_MASK) {
3011                 case SS_NOP:
3012                 case SS_INQ_REFRESH:
3013                         AHC_SET_DV_STATE(ahc, targ,
3014                                          AHC_DV_STATE_INQ_SHORT_ASYNC);
3015                         break;
3016                 default:
3017                         AHC_SET_DV_STATE(ahc, targ, AHC_DV_STATE_EXIT);
3018                         break;
3019                 }
3020                 break;
3021
3022         case AHC_DV_STATE_BUSY:
3023                 switch (status & SS_MASK) {
3024                 case SS_NOP:
3025                 case SS_INQ_REFRESH:
3026                         AHC_SET_DV_STATE(ahc, targ,
3027                                          AHC_DV_STATE_INQ_SHORT_ASYNC);
3028                         break;
3029                 case SS_TUR:
3030                 case SS_RETRY:
3031                         AHC_SET_DV_STATE(ahc, targ, targ->dv_state);
3032                         if (ahc_cmd_get_transaction_status(cmd)
3033                          == CAM_REQUEUE_REQ) {
3034                                 targ->dv_state_retry--;
3035                         } else if (targ->dv_state_retry < 60) {
3036                                 if ((status & SSQ_DELAY) != 0)
3037                                         scsi_sleep(1 * HZ);
3038                         } else {
3039 #ifdef AHC_DEBUG
3040                                 if (ahc_debug & AHC_SHOW_DV) {
3041                                         ahc_print_devinfo(ahc, devinfo);
3042                                         printf("DV BUSY reties exhausted\n");
3043                                 }
3044 #endif
3045                                 AHC_SET_DV_STATE(ahc, targ, AHC_DV_STATE_EXIT);
3046                         }
3047                         break;
3048                 default:
3049                         AHC_SET_DV_STATE(ahc, targ, AHC_DV_STATE_EXIT);
3050                         break;
3051                 }
3052                 break;
3053
3054         default:
3055                 printf("%s: Invalid DV completion state %d\n", ahc_name(ahc),
3056                        targ->dv_state);
3057                 AHC_SET_DV_STATE(ahc, targ, AHC_DV_STATE_EXIT);
3058                 break;
3059         }
3060 }
3061
3062 static void
3063 ahc_linux_dv_fill_cmd(struct ahc_softc *ahc, struct scsi_cmnd *cmd,
3064                       struct ahc_devinfo *devinfo)
3065 {
3066         memset(cmd, 0, sizeof(struct scsi_cmnd));
3067         cmd->device = ahc->platform_data->dv_scsi_dev;
3068         cmd->scsi_done = ahc_linux_dv_complete;
3069 }
3070
3071 /*
3072  * Synthesize an inquiry command.  On the return trip, it'll be
3073  * sniffed and the device transfer settings set for us.
3074  */
3075 static void
3076 ahc_linux_dv_inq(struct ahc_softc *ahc, struct scsi_cmnd *cmd,
3077                  struct ahc_devinfo *devinfo, struct ahc_linux_target *targ,
3078                  u_int request_length)
3079 {
3080
3081 #ifdef AHC_DEBUG
3082         if (ahc_debug & AHC_SHOW_DV) {
3083                 ahc_print_devinfo(ahc, devinfo);
3084                 printf("Sending INQ\n");
3085         }
3086 #endif
3087         if (targ->inq_data == NULL)
3088                 targ->inq_data = malloc(AHC_LINUX_DV_INQ_LEN,
3089                                         M_DEVBUF, M_WAITOK);
3090         if (targ->dv_state > AHC_DV_STATE_INQ_ASYNC) {
3091                 if (targ->dv_buffer != NULL)
3092                         free(targ->dv_buffer, M_DEVBUF);
3093                 targ->dv_buffer = malloc(AHC_LINUX_DV_INQ_LEN,
3094                                          M_DEVBUF, M_WAITOK);
3095         }
3096
3097         ahc_linux_dv_fill_cmd(ahc, cmd, devinfo);
3098         cmd->sc_data_direction = SCSI_DATA_READ;
3099         cmd->cmd_len = 6;
3100         cmd->cmnd[0] = INQUIRY;
3101         cmd->cmnd[4] = request_length;
3102         cmd->request_bufflen = request_length;
3103         if (targ->dv_state > AHC_DV_STATE_INQ_ASYNC)
3104                 cmd->request_buffer = targ->dv_buffer;
3105         else
3106                 cmd->request_buffer = targ->inq_data;
3107         memset(cmd->request_buffer, 0, AHC_LINUX_DV_INQ_LEN);
3108 }
3109
3110 static void
3111 ahc_linux_dv_tur(struct ahc_softc *ahc, struct scsi_cmnd *cmd,
3112                  struct ahc_devinfo *devinfo)
3113 {
3114
3115 #ifdef AHC_DEBUG
3116         if (ahc_debug & AHC_SHOW_DV) {
3117                 ahc_print_devinfo(ahc, devinfo);
3118                 printf("Sending TUR\n");
3119         }
3120 #endif
3121         /* Do a TUR to clear out any non-fatal transitional state */
3122         ahc_linux_dv_fill_cmd(ahc, cmd, devinfo);
3123         cmd->sc_data_direction = SCSI_DATA_NONE;
3124         cmd->cmd_len = 6;
3125         cmd->cmnd[0] = TEST_UNIT_READY;
3126 }
3127
3128 #define AHC_REBD_LEN 4
3129
3130 static void
3131 ahc_linux_dv_rebd(struct ahc_softc *ahc, struct scsi_cmnd *cmd,
3132                  struct ahc_devinfo *devinfo, struct ahc_linux_target *targ)
3133 {
3134
3135 #ifdef AHC_DEBUG
3136         if (ahc_debug & AHC_SHOW_DV) {
3137                 ahc_print_devinfo(ahc, devinfo);
3138                 printf("Sending REBD\n");
3139         }
3140 #endif
3141         if (targ->dv_buffer != NULL)
3142                 free(targ->dv_buffer, M_DEVBUF);
3143         targ->dv_buffer = malloc(AHC_REBD_LEN, M_DEVBUF, M_WAITOK);
3144         ahc_linux_dv_fill_cmd(ahc, cmd, devinfo);
3145         cmd->sc_data_direction = SCSI_DATA_READ;
3146         cmd->cmd_len = 10;
3147         cmd->cmnd[0] = READ_BUFFER;
3148         cmd->cmnd[1] = 0x0b;
3149         scsi_ulto3b(AHC_REBD_LEN, &cmd->cmnd[6]);
3150         cmd->request_bufflen = AHC_REBD_LEN;
3151         cmd->underflow = cmd->request_bufflen;
3152         cmd->request_buffer = targ->dv_buffer;
3153 }
3154
3155 static void
3156 ahc_linux_dv_web(struct ahc_softc *ahc, struct scsi_cmnd *cmd,
3157                  struct ahc_devinfo *devinfo, struct ahc_linux_target *targ)
3158 {
3159
3160 #ifdef AHC_DEBUG
3161         if (ahc_debug & AHC_SHOW_DV) {
3162                 ahc_print_devinfo(ahc, devinfo);
3163                 printf("Sending WEB\n");
3164         }
3165 #endif
3166         ahc_linux_dv_fill_cmd(ahc, cmd, devinfo);
3167         cmd->sc_data_direction = SCSI_DATA_WRITE;
3168         cmd->cmd_len = 10;
3169         cmd->cmnd[0] = WRITE_BUFFER;
3170         cmd->cmnd[1] = 0x0a;
3171         scsi_ulto3b(targ->dv_echo_size, &cmd->cmnd[6]);
3172         cmd->request_bufflen = targ->dv_echo_size;
3173         cmd->underflow = cmd->request_bufflen;
3174         cmd->request_buffer = targ->dv_buffer;
3175 }
3176
3177 static void
3178 ahc_linux_dv_reb(struct ahc_softc *ahc, struct scsi_cmnd *cmd,
3179                  struct ahc_devinfo *devinfo, struct ahc_linux_target *targ)
3180 {
3181
3182 #ifdef AHC_DEBUG
3183         if (ahc_debug & AHC_SHOW_DV) {
3184                 ahc_print_devinfo(ahc, devinfo);
3185                 printf("Sending REB\n");
3186         }
3187 #endif
3188         ahc_linux_dv_fill_cmd(ahc, cmd, devinfo);
3189         cmd->sc_data_direction = SCSI_DATA_READ;
3190         cmd->cmd_len = 10;
3191         cmd->cmnd[0] = READ_BUFFER;
3192         cmd->cmnd[1] = 0x0a;
3193         scsi_ulto3b(targ->dv_echo_size, &cmd->cmnd[6]);
3194         cmd->request_bufflen = targ->dv_echo_size;
3195         cmd->underflow = cmd->request_bufflen;
3196         cmd->request_buffer = targ->dv_buffer1;
3197 }
3198
3199 static void
3200 ahc_linux_dv_su(struct ahc_softc *ahc, struct scsi_cmnd *cmd,
3201                 struct ahc_devinfo *devinfo,
3202                 struct ahc_linux_target *targ)
3203 {
3204         u_int le;
3205
3206         le = SID_IS_REMOVABLE(targ->inq_data) ? SSS_LOEJ : 0;
3207
3208 #ifdef AHC_DEBUG
3209         if (ahc_debug & AHC_SHOW_DV) {
3210                 ahc_print_devinfo(ahc, devinfo);
3211                 printf("Sending SU\n");
3212         }
3213 #endif
3214         ahc_linux_dv_fill_cmd(ahc, cmd, devinfo);
3215         cmd->sc_data_direction = SCSI_DATA_NONE;
3216         cmd->cmd_len = 6;
3217         cmd->cmnd[0] = START_STOP_UNIT;
3218         cmd->cmnd[4] = le | SSS_START;
3219 }
3220
3221 static int
3222 ahc_linux_fallback(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
3223 {
3224         struct  ahc_linux_target *targ;
3225         struct  ahc_initiator_tinfo *tinfo;
3226         struct  ahc_transinfo *goal;
3227         struct  ahc_tmode_tstate *tstate;
3228         struct  ahc_syncrate *syncrate;
3229         u_long  s;
3230         u_int   width;
3231         u_int   period;
3232         u_int   offset;
3233         u_int   ppr_options;
3234         u_int   cur_speed;
3235         u_int   wide_speed;
3236         u_int   narrow_speed;
3237         u_int   fallback_speed;
3238
3239 #ifdef AHC_DEBUG
3240         if (ahc_debug & AHC_SHOW_DV) {
3241                 ahc_print_devinfo(ahc, devinfo);
3242                 printf("Trying to fallback\n");
3243         }
3244 #endif
3245         ahc_lock(ahc, &s);
3246         targ = ahc->platform_data->targets[devinfo->target_offset];
3247         tinfo = ahc_fetch_transinfo(ahc, devinfo->channel,
3248                                     devinfo->our_scsiid,
3249                                     devinfo->target, &tstate);
3250         goal = &tinfo->goal;
3251         width = goal->width;
3252         period = goal->period;
3253         offset = goal->offset;
3254         ppr_options = goal->ppr_options;
3255         if (offset == 0)
3256                 period = AHC_ASYNC_XFER_PERIOD;
3257         if (targ->dv_next_narrow_period == 0)
3258                 targ->dv_next_narrow_period = MAX(period, AHC_SYNCRATE_ULTRA2);
3259         if (targ->dv_next_wide_period == 0)
3260                 targ->dv_next_wide_period = period;
3261         if (targ->dv_max_width == 0)
3262                 targ->dv_max_width = width;
3263         if (targ->dv_max_ppr_options == 0)
3264                 targ->dv_max_ppr_options = ppr_options;
3265         if (targ->dv_last_ppr_options == 0)
3266                 targ->dv_last_ppr_options = ppr_options;
3267
3268         cur_speed = aic_calc_speed(width, period, offset, AHC_SYNCRATE_MIN);
3269         wide_speed = aic_calc_speed(MSG_EXT_WDTR_BUS_16_BIT,
3270                                           targ->dv_next_wide_period,
3271                                           MAX_OFFSET,
3272                                           AHC_SYNCRATE_MIN);
3273         narrow_speed = aic_calc_speed(MSG_EXT_WDTR_BUS_8_BIT,
3274                                             targ->dv_next_narrow_period,
3275                                             MAX_OFFSET,
3276                                             AHC_SYNCRATE_MIN);
3277         fallback_speed = aic_calc_speed(width, period+1, offset,
3278                                         AHC_SYNCRATE_MIN);
3279 #ifdef AHC_DEBUG
3280         if (ahc_debug & AHC_SHOW_DV) {
3281                 printf("cur_speed= %d, wide_speed= %d, narrow_speed= %d, "
3282                        "fallback_speed= %d\n", cur_speed, wide_speed,
3283                        narrow_speed, fallback_speed);
3284         }
3285 #endif
3286
3287         if (cur_speed > 160000) {
3288                 /*
3289                  * Paced/DT/IU_REQ only transfer speeds.  All we
3290                  * can do is fallback in terms of syncrate.
3291                  */
3292                 period++;
3293         } else if (cur_speed > 80000) {
3294                 if ((ppr_options & MSG_EXT_PPR_IU_REQ) != 0) {
3295                         /*
3296                          * Try without IU_REQ as it may be confusing
3297                          * an expander.
3298                          */
3299                         ppr_options &= ~MSG_EXT_PPR_IU_REQ;
3300                 } else {
3301                         /*
3302                          * Paced/DT only transfer speeds.  All we
3303                          * can do is fallback in terms of syncrate.
3304                          */
3305                         period++;
3306                         ppr_options = targ->dv_max_ppr_options;
3307                 }
3308         } else if (cur_speed > 3300) {
3309
3310                 /*
3311                  * In this range we the following
3312                  * options ordered from highest to
3313                  * lowest desireability:
3314                  *
3315                  * o Wide/DT
3316                  * o Wide/non-DT
3317                  * o Narrow at a potentally higher sync rate.
3318                  *
3319                  * All modes are tested with and without IU_REQ
3320                  * set since using IUs may confuse an expander.
3321                  */
3322                 if ((ppr_options & MSG_EXT_PPR_IU_REQ) != 0) {
3323
3324                         ppr_options &= ~MSG_EXT_PPR_IU_REQ;
3325                 } else if ((ppr_options & MSG_EXT_PPR_DT_REQ) != 0) {
3326                         /*
3327                          * Try going non-DT.
3328                          */
3329                         ppr_options = targ->dv_max_ppr_options;
3330                         ppr_options &= ~MSG_EXT_PPR_DT_REQ;
3331                 } else if (targ->dv_last_ppr_options != 0) {
3332                         /*
3333                          * Try without QAS or any other PPR options.
3334                          * We may need a non-PPR message to work with
3335                          * an expander.  We look at the "last PPR options"
3336                          * so we will perform this fallback even if the
3337                          * target responded to our PPR negotiation with
3338                          * no option bits set.
3339                          */
3340                         ppr_options = 0;
3341                 } else if (width == MSG_EXT_WDTR_BUS_16_BIT) {
3342                         /*
3343                          * If the next narrow speed is greater than
3344                          * the next wide speed, fallback to narrow.
3345                          * Otherwise fallback to the next DT/Wide setting.
3346                          * The narrow async speed will always be smaller
3347                          * than the wide async speed, so handle this case
3348                          * specifically.
3349                          */
3350                         ppr_options = targ->dv_max_ppr_options;
3351                         if (narrow_speed > fallback_speed
3352                          || period >= AHC_ASYNC_XFER_PERIOD) {
3353                                 targ->dv_next_wide_period = period+1;
3354                                 width = MSG_EXT_WDTR_BUS_8_BIT;
3355                                 period = targ->dv_next_narrow_period;
3356                         } else {
3357                                 period++;
3358                         }
3359                 } else if ((ahc->features & AHC_WIDE) != 0
3360                         && targ->dv_max_width != 0
3361                         && wide_speed >= fallback_speed
3362                         && (targ->dv_next_wide_period <= AHC_ASYNC_XFER_PERIOD
3363                          || period >= AHC_ASYNC_XFER_PERIOD)) {
3364
3365                         /*
3366                          * We are narrow.  Try falling back
3367                          * to the next wide speed with 
3368                          * all supported ppr options set.
3369                          */
3370                         targ->dv_next_narrow_period = period+1;
3371                         width = MSG_EXT_WDTR_BUS_16_BIT;
3372                         period = targ->dv_next_wide_period;
3373                         ppr_options = targ->dv_max_ppr_options;
3374                 } else {
3375                         /* Only narrow fallback is allowed. */
3376                         period++;
3377                         ppr_options = targ->dv_max_ppr_options;
3378                 }
3379         } else {
3380                 ahc_unlock(ahc, &s);
3381                 return (-1);
3382         }
3383         offset = MAX_OFFSET;
3384         syncrate = ahc_find_syncrate(ahc, &period, &ppr_options,
3385                                      AHC_SYNCRATE_DT);
3386         ahc_set_width(ahc, devinfo, width, AHC_TRANS_GOAL, FALSE);
3387         if (period == 0) {
3388                 period = 0;
3389                 offset = 0;
3390                 ppr_options = 0;
3391                 if (width == MSG_EXT_WDTR_BUS_8_BIT)
3392                         targ->dv_next_narrow_period = AHC_ASYNC_XFER_PERIOD;
3393                 else
3394                         targ->dv_next_wide_period = AHC_ASYNC_XFER_PERIOD;
3395         }
3396         ahc_set_syncrate(ahc, devinfo, syncrate, period, offset,
3397                          ppr_options, AHC_TRANS_GOAL, FALSE);
3398         targ->dv_last_ppr_options = ppr_options;
3399         ahc_unlock(ahc, &s);
3400         return (0);
3401 }
3402
3403 static void
3404 ahc_linux_dv_timeout(struct scsi_cmnd *cmd)
3405 {
3406         struct  ahc_softc *ahc;
3407         struct  scb *scb;
3408         u_long  flags;
3409
3410         ahc = *((struct ahc_softc **)cmd->device->host->hostdata);
3411         ahc_lock(ahc, &flags);
3412
3413 #ifdef AHC_DEBUG
3414         if (ahc_debug & AHC_SHOW_DV) {
3415                 printf("%s: Timeout while doing DV command %x.\n",
3416                        ahc_name(ahc), cmd->cmnd[0]);
3417                 ahc_dump_card_state(ahc);
3418         }
3419 #endif
3420         
3421         /*
3422          * Guard against "done race".  No action is
3423          * required if we just completed.
3424          */
3425         if ((scb = (struct scb *)cmd->host_scribble) == NULL) {
3426                 ahc_unlock(ahc, &flags);
3427                 return;
3428         }
3429
3430         /*
3431          * Command has not completed.  Mark this
3432          * SCB as having failing status prior to
3433          * resetting the bus, so we get the correct
3434          * error code.
3435          */
3436         if ((scb->flags & SCB_SENSE) != 0)
3437                 ahc_set_transaction_status(scb, CAM_AUTOSENSE_FAIL);
3438         else
3439                 ahc_set_transaction_status(scb, CAM_CMD_TIMEOUT);
3440         ahc_reset_channel(ahc, cmd->device->channel + 'A', /*initiate*/TRUE);
3441
3442         /*
3443          * Add a minimal bus settle delay for devices that are slow to
3444          * respond after bus resets.
3445          */
3446         ahc_linux_freeze_simq(ahc);
3447         init_timer(&ahc->platform_data->reset_timer);
3448         ahc->platform_data->reset_timer.data = (u_long)ahc;
3449         ahc->platform_data->reset_timer.expires = jiffies + HZ / 2;
3450         ahc->platform_data->reset_timer.function =
3451             (ahc_linux_callback_t *)ahc_linux_release_simq;
3452         add_timer(&ahc->platform_data->reset_timer);
3453         if (ahc_linux_next_device_to_run(ahc) != NULL)
3454                 ahc_schedule_runq(ahc);
3455         ahc_linux_run_complete_queue(ahc);
3456         ahc_unlock(ahc, &flags);
3457 }
3458
3459 static void
3460 ahc_linux_dv_complete(struct scsi_cmnd *cmd)
3461 {
3462         struct ahc_softc *ahc;
3463
3464         ahc = *((struct ahc_softc **)cmd->device->host->hostdata);
3465
3466         /* Delete the DV timer before it goes off! */
3467         scsi_delete_timer(cmd);
3468
3469 #ifdef AHC_DEBUG
3470         if (ahc_debug & AHC_SHOW_DV)
3471                 printf("%s:%d:%d: Command completed, status= 0x%x\n",
3472                        ahc_name(ahc), cmd->device->channel,
3473                        cmd->device->id, cmd->result);
3474 #endif
3475
3476         /* Wake up the state machine */
3477         up(&ahc->platform_data->dv_cmd_sem);
3478 }
3479
3480 static void
3481 ahc_linux_generate_dv_pattern(struct ahc_linux_target *targ)
3482 {
3483         uint16_t b;
3484         u_int    i;
3485         u_int    j;
3486
3487         if (targ->dv_buffer != NULL)
3488                 free(targ->dv_buffer, M_DEVBUF);
3489         targ->dv_buffer = malloc(targ->dv_echo_size, M_DEVBUF, M_WAITOK);
3490         if (targ->dv_buffer1 != NULL)
3491                 free(targ->dv_buffer1, M_DEVBUF);
3492         targ->dv_buffer1 = malloc(targ->dv_echo_size, M_DEVBUF, M_WAITOK);
3493
3494         i = 0;
3495         b = 0x0001;
3496         for (j = 0 ; i < targ->dv_echo_size; j++) {
3497                 if (j < 32) {
3498                         /*
3499                          * 32bytes of sequential numbers.
3500                          */
3501                         targ->dv_buffer[i++] = j & 0xff;
3502                 } else if (j < 48) {
3503                         /*
3504                          * 32bytes of repeating 0x0000, 0xffff.
3505                          */
3506                         targ->dv_buffer[i++] = (j & 0x02) ? 0xff : 0x00;
3507                 } else if (j < 64) {
3508                         /*
3509                          * 32bytes of repeating 0x5555, 0xaaaa.
3510                          */
3511                         targ->dv_buffer[i++] = (j & 0x02) ? 0xaa : 0x55;
3512                 } else {
3513                         /*
3514                          * Remaining buffer is filled with a repeating
3515                          * patter of:
3516                          *
3517                          *       0xffff
3518                          *      ~0x0001 << shifted once in each loop.
3519                          */
3520                         if (j & 0x02) {
3521                                 if (j & 0x01) {
3522                                         targ->dv_buffer[i++] = ~(b >> 8) & 0xff;
3523                                         b <<= 1;
3524                                         if (b == 0x0000)
3525                                                 b = 0x0001;
3526                                 } else {
3527                                         targ->dv_buffer[i++] = (~b & 0xff);
3528                                 }
3529                         } else {
3530                                 targ->dv_buffer[i++] = 0xff;
3531                         }
3532                 }
3533         }
3534 }
3535
3536 static u_int
3537 ahc_linux_user_tagdepth(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
3538 {
3539         static int warned_user;
3540         u_int tags;
3541
3542         tags = 0;
3543         if ((ahc->user_discenable & devinfo->target_mask) != 0) {
3544                 if (ahc->unit >= NUM_ELEMENTS(aic7xxx_tag_info)) {
3545                         if (warned_user == 0) {
3546
3547                                 printf(KERN_WARNING
3548 "aic7xxx: WARNING: Insufficient tag_info instances\n"
3549 "aic7xxx: for installed controllers. Using defaults\n"
3550 "aic7xxx: Please update the aic7xxx_tag_info array in\n"
3551 "aic7xxx: the aic7xxx_osm..c source file.\n");
3552                                 warned_user++;
3553                         }
3554                         tags = AHC_MAX_QUEUE;
3555                 } else {
3556                         adapter_tag_info_t *tag_info;
3557
3558                         tag_info = &aic7xxx_tag_info[ahc->unit];
3559                         tags = tag_info->tag_commands[devinfo->target_offset];
3560                         if (tags > AHC_MAX_QUEUE)
3561                                 tags = AHC_MAX_QUEUE;
3562                 }
3563         }
3564         return (tags);
3565 }
3566
3567 static u_int
3568 ahc_linux_user_dv_setting(struct ahc_softc *ahc)
3569 {
3570         static int warned_user;
3571         int dv;
3572
3573         if (ahc->unit >= NUM_ELEMENTS(aic7xxx_dv_settings)) {
3574                 if (warned_user == 0) {
3575
3576                         printf(KERN_WARNING
3577 "aic7xxx: WARNING: Insufficient dv settings instances\n"
3578 "aic7xxx: for installed controllers. Using defaults\n"
3579 "aic7xxx: Please update the aic7xxx_dv_settings array\n"
3580 "aic7xxx: in the aic7xxx_osm.c source file.\n");
3581                         warned_user++;
3582                 }
3583                 dv = -1;
3584         } else {
3585
3586                 dv = aic7xxx_dv_settings[ahc->unit];
3587         }
3588
3589         if (dv < 0) {
3590                 u_long s;
3591
3592                 /*
3593                  * Apply the default.
3594                  */
3595                 /*
3596                  * XXX - Enable DV on non-U160 controllers once it
3597                  *       has been tested there.
3598                  */
3599                 ahc_lock(ahc, &s);
3600                 dv = (ahc->features & AHC_DT);
3601                 if (ahc->seep_config != 0
3602                  && ahc->seep_config->signature >= CFSIGNATURE2)
3603                         dv = (ahc->seep_config->adapter_control & CFENABLEDV);
3604                 ahc_unlock(ahc, &s);
3605         }
3606         return (dv);
3607 }
3608
3609 /*
3610  * Determines the queue depth for a given device.
3611  */
3612 static void
3613 ahc_linux_device_queue_depth(struct ahc_softc *ahc,
3614                              struct ahc_linux_device *dev)
3615 {
3616         struct  ahc_devinfo devinfo;
3617         u_int   tags;
3618
3619         ahc_compile_devinfo(&devinfo,
3620                             dev->target->channel == 0
3621                           ? ahc->our_id : ahc->our_id_b,
3622                             dev->target->target, dev->lun,
3623                             dev->target->channel == 0 ? 'A' : 'B',
3624                             ROLE_INITIATOR);
3625         tags = ahc_linux_user_tagdepth(ahc, &devinfo);
3626         if (tags != 0
3627          && dev->scsi_device != NULL
3628          && dev->scsi_device->tagged_supported != 0) {
3629
3630                 ahc_set_tags(ahc, &devinfo, AHC_QUEUE_TAGGED);
3631                 ahc_print_devinfo(ahc, &devinfo);
3632                 printf("Tagged Queuing enabled.  Depth %d\n", tags);
3633         } else {
3634                 ahc_set_tags(ahc, &devinfo, AHC_QUEUE_NONE);
3635         }
3636 }
3637
3638 static void
3639 ahc_linux_run_device_queue(struct ahc_softc *ahc, struct ahc_linux_device *dev)
3640 {
3641         struct   ahc_cmd *acmd;
3642         struct   scsi_cmnd *cmd;
3643         struct   scb *scb;
3644         struct   hardware_scb *hscb;
3645         struct   ahc_initiator_tinfo *tinfo;
3646         struct   ahc_tmode_tstate *tstate;
3647         uint16_t mask;
3648
3649         if ((dev->flags & AHC_DEV_ON_RUN_LIST) != 0)
3650                 panic("running device on run list");
3651
3652         while ((acmd = TAILQ_FIRST(&dev->busyq)) != NULL
3653             && dev->openings > 0 && dev->qfrozen == 0) {
3654
3655                 /*
3656                  * Schedule us to run later.  The only reason we are not
3657                  * running is because the whole controller Q is frozen.
3658                  */
3659                 if (ahc->platform_data->qfrozen != 0
3660                  && AHC_DV_SIMQ_FROZEN(ahc) == 0) {
3661                         TAILQ_INSERT_TAIL(&ahc->platform_data->device_runq,
3662                                           dev, links);
3663                         dev->flags |= AHC_DEV_ON_RUN_LIST;
3664                         return;
3665                 }
3666                 /*
3667                  * Get an scb to use.
3668                  */
3669                 if ((scb = ahc_get_scb(ahc)) == NULL) {
3670                         TAILQ_INSERT_TAIL(&ahc->platform_data->device_runq,
3671                                          dev, links);
3672                         dev->flags |= AHC_DEV_ON_RUN_LIST;
3673                         ahc->flags |= AHC_RESOURCE_SHORTAGE;
3674                         return;
3675                 }
3676                 TAILQ_REMOVE(&dev->busyq, acmd, acmd_links.tqe);
3677                 cmd = &acmd_scsi_cmd(acmd);
3678                 scb->io_ctx = cmd;
3679                 scb->platform_data->dev = dev;
3680                 hscb = scb->hscb;
3681                 cmd->host_scribble = (char *)scb;
3682
3683                 /*
3684                  * Fill out basics of the HSCB.
3685                  */
3686                 hscb->control = 0;
3687                 hscb->scsiid = BUILD_SCSIID(ahc, cmd);
3688                 hscb->lun = cmd->device->lun;
3689                 mask = SCB_GET_TARGET_MASK(ahc, scb);
3690                 tinfo = ahc_fetch_transinfo(ahc, SCB_GET_CHANNEL(ahc, scb),
3691                                             SCB_GET_OUR_ID(scb),
3692                                             SCB_GET_TARGET(ahc, scb), &tstate);
3693                 hscb->scsirate = tinfo->scsirate;
3694                 hscb->scsioffset = tinfo->curr.offset;
3695                 if ((tstate->ultraenb & mask) != 0)
3696                         hscb->control |= ULTRAENB;
3697
3698                 if ((ahc->user_discenable & mask) != 0)
3699                         hscb->control |= DISCENB;
3700
3701                 if (AHC_DV_CMD(cmd) != 0)
3702                         scb->flags |= SCB_SILENT;
3703
3704                 if ((tstate->auto_negotiate & mask) != 0) {
3705                         scb->flags |= SCB_AUTO_NEGOTIATE;
3706                         scb->hscb->control |= MK_MESSAGE;
3707                 }
3708
3709                 if ((dev->flags & (AHC_DEV_Q_TAGGED|AHC_DEV_Q_BASIC)) != 0) {
3710 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
3711                         int     msg_bytes;
3712                         uint8_t tag_msgs[2];
3713
3714                         msg_bytes = scsi_populate_tag_msg(cmd, tag_msgs);
3715                         if (msg_bytes && tag_msgs[0] != MSG_SIMPLE_TASK) {
3716                                 hscb->control |= tag_msgs[0];
3717                                 if (tag_msgs[0] == MSG_ORDERED_TASK)
3718                                         dev->commands_since_idle_or_otag = 0;
3719                         } else
3720 #endif
3721                         if (dev->commands_since_idle_or_otag == AHC_OTAG_THRESH
3722                          && (dev->flags & AHC_DEV_Q_TAGGED) != 0) {
3723                                 hscb->control |= MSG_ORDERED_TASK;
3724                                 dev->commands_since_idle_or_otag = 0;
3725                         } else {
3726                                 hscb->control |= MSG_SIMPLE_TASK;
3727                         }
3728                 }
3729
3730                 hscb->cdb_len = cmd->cmd_len;
3731                 if (hscb->cdb_len <= 12) {
3732                         memcpy(hscb->shared_data.cdb, cmd->cmnd, hscb->cdb_len);
3733                 } else {
3734                         memcpy(hscb->cdb32, cmd->cmnd, hscb->cdb_len);
3735                         scb->flags |= SCB_CDB32_PTR;
3736                 }
3737
3738                 scb->platform_data->xfer_len = 0;
3739                 ahc_set_residual(scb, 0);
3740                 ahc_set_sense_residual(scb, 0);
3741                 scb->sg_count = 0;
3742                 if (cmd->use_sg != 0) {
3743                         struct  ahc_dma_seg *sg;
3744                         struct  scatterlist *cur_seg;
3745                         struct  scatterlist *end_seg;
3746                         int     nseg;
3747
3748                         cur_seg = (struct scatterlist *)cmd->request_buffer;
3749                         nseg = pci_map_sg(ahc->dev_softc, cur_seg, cmd->use_sg,
3750                             scsi_to_pci_dma_dir(cmd->sc_data_direction));
3751                         end_seg = cur_seg + nseg;
3752                         /* Copy the segments into the SG list. */
3753                         sg = scb->sg_list;
3754                         /*
3755                          * The sg_count may be larger than nseg if
3756                          * a transfer crosses a 32bit page.
3757                          */ 
3758                         while (cur_seg < end_seg) {
3759                                 bus_addr_t addr;
3760                                 bus_size_t len;
3761                                 int consumed;
3762
3763                                 addr = sg_dma_address(cur_seg);
3764                                 len = sg_dma_len(cur_seg);
3765                                 consumed = ahc_linux_map_seg(ahc, scb,
3766                                                              sg, addr, len);
3767                                 sg += consumed;
3768                                 scb->sg_count += consumed;
3769                                 cur_seg++;
3770                         }
3771                         sg--;
3772                         sg->len |= ahc_htole32(AHC_DMA_LAST_SEG);
3773
3774                         /*
3775                          * Reset the sg list pointer.
3776                          */
3777                         scb->hscb->sgptr =
3778                             ahc_htole32(scb->sg_list_phys | SG_FULL_RESID);
3779
3780                         /*
3781                          * Copy the first SG into the "current"
3782                          * data pointer area.
3783                          */
3784                         scb->hscb->dataptr = scb->sg_list->addr;
3785                         scb->hscb->datacnt = scb->sg_list->len;
3786                 } else if (cmd->request_bufflen != 0) {
3787                         struct   ahc_dma_seg *sg;
3788                         bus_addr_t addr;
3789
3790                         sg = scb->sg_list;
3791                         addr = pci_map_single(ahc->dev_softc,
3792                                cmd->request_buffer,
3793                                cmd->request_bufflen,
3794                                scsi_to_pci_dma_dir(cmd->sc_data_direction));
3795                         scb->platform_data->buf_busaddr = addr;
3796                         scb->sg_count = ahc_linux_map_seg(ahc, scb,
3797                                                           sg, addr,
3798                                                           cmd->request_bufflen);
3799                         sg->len |= ahc_htole32(AHC_DMA_LAST_SEG);
3800
3801                         /*
3802                          * Reset the sg list pointer.
3803                          */
3804                         scb->hscb->sgptr =
3805                             ahc_htole32(scb->sg_list_phys | SG_FULL_RESID);
3806
3807                         /*
3808                          * Copy the first SG into the "current"
3809                          * data pointer area.
3810                          */
3811                         scb->hscb->dataptr = sg->addr;
3812                         scb->hscb->datacnt = sg->len;
3813                 } else {
3814                         scb->hscb->sgptr = ahc_htole32(SG_LIST_NULL);
3815                         scb->hscb->dataptr = 0;
3816                         scb->hscb->datacnt = 0;
3817                         scb->sg_count = 0;
3818                 }
3819
3820                 ahc_sync_sglist(ahc, scb, BUS_DMASYNC_PREWRITE);
3821                 LIST_INSERT_HEAD(&ahc->pending_scbs, scb, pending_links);
3822                 dev->openings--;
3823                 dev->active++;
3824                 dev->commands_issued++;
3825                 if ((dev->flags & AHC_DEV_PERIODIC_OTAG) != 0)
3826                         dev->commands_since_idle_or_otag++;
3827
3828                 /*
3829                  * We only allow one untagged transaction
3830                  * per target in the initiator role unless
3831                  * we are storing a full busy target *lun*
3832                  * table in SCB space.
3833                  */
3834                 if ((scb->hscb->control & (TARGET_SCB|TAG_ENB)) == 0
3835                  && (ahc->features & AHC_SCB_BTT) == 0) {
3836                         struct scb_tailq *untagged_q;
3837                         int target_offset;
3838
3839                         target_offset = SCB_GET_TARGET_OFFSET(ahc, scb);
3840                         untagged_q = &(ahc->untagged_queues[target_offset]);
3841                         TAILQ_INSERT_TAIL(untagged_q, scb, links.tqe);
3842                         scb->flags |= SCB_UNTAGGEDQ;
3843                         if (TAILQ_FIRST(untagged_q) != scb)
3844                                 continue;
3845                 }
3846                 scb->flags |= SCB_ACTIVE;
3847                 ahc_queue_scb(ahc, scb);
3848         }
3849 }
3850
3851 /*
3852  * SCSI controller interrupt handler.
3853  */
3854 irqreturn_t
3855 ahc_linux_isr(int irq, void *dev_id, struct pt_regs * regs)
3856 {
3857         struct  ahc_softc *ahc;
3858         u_long  flags;
3859         int     ours;
3860
3861         ahc = (struct ahc_softc *) dev_id;
3862         ahc_lock(ahc, &flags); 
3863         ours = ahc_intr(ahc);
3864         if (ahc_linux_next_device_to_run(ahc) != NULL)
3865                 ahc_schedule_runq(ahc);
3866         ahc_linux_run_complete_queue(ahc);
3867         ahc_unlock(ahc, &flags);
3868         return IRQ_RETVAL(ours);
3869 }
3870
3871 void
3872 ahc_platform_flushwork(struct ahc_softc *ahc)
3873 {
3874
3875         while (ahc_linux_run_complete_queue(ahc) != NULL)
3876                 ;
3877 }
3878
3879 static struct ahc_linux_target*
3880 ahc_linux_alloc_target(struct ahc_softc *ahc, u_int channel, u_int target)
3881 {
3882         struct ahc_linux_target *targ;
3883         u_int target_offset;
3884
3885         target_offset = target;
3886         if (channel != 0)
3887                 target_offset += 8;
3888
3889         targ = malloc(sizeof(*targ), M_DEVBUG, M_NOWAIT);
3890         if (targ == NULL)
3891                 return (NULL);
3892         memset(targ, 0, sizeof(*targ));
3893         targ->channel = channel;
3894         targ->target = target;
3895         targ->ahc = ahc;
3896         targ->flags = AHC_DV_REQUIRED;
3897         ahc->platform_data->targets[target_offset] = targ;
3898         return (targ);
3899 }
3900
3901 static void
3902 ahc_linux_free_target(struct ahc_softc *ahc, struct ahc_linux_target *targ)
3903 {
3904         struct ahc_devinfo devinfo;
3905         struct ahc_initiator_tinfo *tinfo;
3906         struct ahc_tmode_tstate *tstate;
3907         u_int our_id;
3908         u_int target_offset;
3909         char channel;
3910
3911         /*
3912          * Force a negotiation to async/narrow on any
3913          * future command to this device unless a bus
3914          * reset occurs between now and that command.
3915          */
3916         channel = 'A' + targ->channel;
3917         our_id = ahc->our_id;
3918         target_offset = targ->target;
3919         if (targ->channel != 0) {
3920                 target_offset += 8;
3921                 our_id = ahc->our_id_b;
3922         }
3923         tinfo = ahc_fetch_transinfo(ahc, channel, our_id,
3924                                     targ->target, &tstate);
3925         ahc_compile_devinfo(&devinfo, our_id, targ->target, CAM_LUN_WILDCARD,
3926                             channel, ROLE_INITIATOR);
3927         ahc_set_syncrate(ahc, &devinfo, NULL, 0, 0, 0,
3928                          AHC_TRANS_GOAL, /*paused*/FALSE);
3929         ahc_set_width(ahc, &devinfo, MSG_EXT_WDTR_BUS_8_BIT,
3930                       AHC_TRANS_GOAL, /*paused*/FALSE);
3931         ahc_update_neg_request(ahc, &devinfo, tstate, tinfo, AHC_NEG_ALWAYS);
3932         ahc->platform_data->targets[target_offset] = NULL;
3933         if (targ->inq_data != NULL)
3934                 free(targ->inq_data, M_DEVBUF);
3935         if (targ->dv_buffer != NULL)
3936                 free(targ->dv_buffer, M_DEVBUF);
3937         if (targ->dv_buffer1 != NULL)
3938                 free(targ->dv_buffer1, M_DEVBUF);
3939         free(targ, M_DEVBUF);
3940 }
3941
3942 static struct ahc_linux_device*
3943 ahc_linux_alloc_device(struct ahc_softc *ahc,
3944                  struct ahc_linux_target *targ, u_int lun)
3945 {
3946         struct ahc_linux_device *dev;
3947
3948         dev = malloc(sizeof(*dev), M_DEVBUG, M_NOWAIT);
3949         if (dev == NULL)
3950                 return (NULL);
3951         memset(dev, 0, sizeof(*dev));
3952         init_timer(&dev->timer);
3953         TAILQ_INIT(&dev->busyq);
3954         dev->flags = AHC_DEV_UNCONFIGURED;
3955         dev->lun = lun;
3956         dev->target = targ;
3957
3958         /*
3959          * We start out life using untagged
3960          * transactions of which we allow one.
3961          */
3962         dev->openings = 1;
3963
3964         /*
3965          * Set maxtags to 0.  This will be changed if we
3966          * later determine that we are dealing with
3967          * a tagged queuing capable device.
3968          */
3969         dev->maxtags = 0;
3970         
3971         targ->refcount++;
3972         targ->devices[lun] = dev;
3973         return (dev);
3974 }
3975
3976 static void
3977 __ahc_linux_free_device(struct ahc_softc *ahc, struct ahc_linux_device *dev)
3978 {
3979         struct ahc_linux_target *targ;
3980
3981         targ = dev->target;
3982         targ->devices[dev->lun] = NULL;
3983         free(dev, M_DEVBUF);
3984         targ->refcount--;
3985         if (targ->refcount == 0
3986          && (targ->flags & AHC_DV_REQUIRED) == 0)
3987                 ahc_linux_free_target(ahc, targ);
3988 }
3989
3990 static void
3991 ahc_linux_free_device(struct ahc_softc *ahc, struct ahc_linux_device *dev)
3992 {
3993         del_timer_sync(&dev->timer);
3994         __ahc_linux_free_device(ahc, dev);
3995 }
3996
3997 void
3998 ahc_send_async(struct ahc_softc *ahc, char channel,
3999                u_int target, u_int lun, ac_code code, void *arg)
4000 {
4001         switch (code) {
4002         case AC_TRANSFER_NEG:
4003         {
4004                 char    buf[80];
4005                 struct  ahc_linux_target *targ;
4006                 struct  info_str info;
4007                 struct  ahc_initiator_tinfo *tinfo;
4008                 struct  ahc_tmode_tstate *tstate;
4009                 int     target_offset;
4010
4011                 info.buffer = buf;
4012                 info.length = sizeof(buf);
4013                 info.offset = 0;
4014                 info.pos = 0;
4015                 tinfo = ahc_fetch_transinfo(ahc, channel,
4016                                                 channel == 'A' ? ahc->our_id
4017                                                                : ahc->our_id_b,
4018                                                 target, &tstate);
4019
4020                 /*
4021                  * Don't bother reporting results while
4022                  * negotiations are still pending.
4023                  */
4024                 if (tinfo->curr.period != tinfo->goal.period
4025                  || tinfo->curr.width != tinfo->goal.width
4026                  || tinfo->curr.offset != tinfo->goal.offset
4027                  || tinfo->curr.ppr_options != tinfo->goal.ppr_options)
4028                         if (bootverbose == 0)
4029                                 break;
4030
4031                 /*
4032                  * Don't bother reporting results that
4033                  * are identical to those last reported.
4034                  */
4035                 target_offset = target;
4036                 if (channel == 'B')
4037                         target_offset += 8;
4038                 targ = ahc->platform_data->targets[target_offset];
4039                 if (targ == NULL)
4040                         break;
4041                 if (tinfo->curr.period == targ->last_tinfo.period
4042                  && tinfo->curr.width == targ->last_tinfo.width
4043                  && tinfo->curr.offset == targ->last_tinfo.offset
4044                  && tinfo->curr.ppr_options == targ->last_tinfo.ppr_options)
4045                         if (bootverbose == 0)
4046                                 break;
4047
4048                 targ->last_tinfo.period = tinfo->curr.period;
4049                 targ->last_tinfo.width = tinfo->curr.width;
4050                 targ->last_tinfo.offset = tinfo->curr.offset;
4051                 targ->last_tinfo.ppr_options = tinfo->curr.ppr_options;
4052
4053                 printf("(%s:%c:", ahc_name(ahc), channel);
4054                 if (target == CAM_TARGET_WILDCARD)
4055                         printf("*): ");
4056                 else
4057                         printf("%d): ", target);
4058                 ahc_format_transinfo(&info, &tinfo->curr);
4059                 if (info.pos < info.length)
4060                         *info.buffer = '\0';
4061                 else
4062                         buf[info.length - 1] = '\0';
4063                 printf("%s", buf);
4064                 break;
4065         }
4066         case AC_SENT_BDR:
4067         {
4068 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
4069                 WARN_ON(lun != CAM_LUN_WILDCARD);
4070                 scsi_report_device_reset(ahc->platform_data->host,
4071                                          channel - 'A', target);
4072 #elif LINUX_VERSION_CODE >= KERNEL_VERSION(2,3,0)
4073                 Scsi_Device *scsi_dev;
4074
4075                 /*
4076                  * Find the SCSI device associated with this
4077                  * request and indicate that a UA is expected.
4078                  */
4079                 for (scsi_dev = ahc->platform_data->host->host_queue;
4080                      scsi_dev != NULL; scsi_dev = scsi_dev->next) {
4081                         if (channel - 'A' == scsi_dev->channel
4082                          && target == scsi_dev->id
4083                          && (lun == CAM_LUN_WILDCARD
4084                           || lun == scsi_dev->lun)) {
4085                                 scsi_dev->was_reset = 1;
4086                                 scsi_dev->expecting_cc_ua = 1;
4087                         }
4088                 }
4089 #endif
4090                 break;
4091         }
4092         case AC_BUS_RESET:
4093 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,3,0)
4094                 if (ahc->platform_data->host != NULL) {
4095                         scsi_report_bus_reset(ahc->platform_data->host,
4096                                               channel - 'A');
4097                 }
4098 #endif
4099                 break;
4100         default:
4101                 panic("ahc_send_async: Unexpected async event");
4102         }
4103 }
4104
4105 /*
4106  * Calls the higher level scsi done function and frees the scb.
4107  */
4108 void
4109 ahc_done(struct ahc_softc *ahc, struct scb *scb)
4110 {
4111         Scsi_Cmnd *cmd;
4112         struct     ahc_linux_device *dev;
4113
4114         LIST_REMOVE(scb, pending_links);
4115         if ((scb->flags & SCB_UNTAGGEDQ) != 0) {
4116                 struct scb_tailq *untagged_q;
4117                 int target_offset;
4118
4119                 target_offset = SCB_GET_TARGET_OFFSET(ahc, scb);
4120                 untagged_q = &(ahc->untagged_queues[target_offset]);
4121                 TAILQ_REMOVE(untagged_q, scb, links.tqe);
4122                 ahc_run_untagged_queue(ahc, untagged_q);
4123         }
4124
4125         if ((scb->flags & SCB_ACTIVE) == 0) {
4126                 printf("SCB %d done'd twice\n", scb->hscb->tag);
4127                 ahc_dump_card_state(ahc);
4128                 panic("Stopping for safety");
4129         }
4130         cmd = scb->io_ctx;
4131         dev = scb->platform_data->dev;
4132         dev->active--;
4133         dev->openings++;
4134         if ((cmd->result & (CAM_DEV_QFRZN << 16)) != 0) {
4135                 cmd->result &= ~(CAM_DEV_QFRZN << 16);
4136                 dev->qfrozen--;
4137         }
4138         ahc_linux_unmap_scb(ahc, scb);
4139
4140         /*
4141          * Guard against stale sense data.
4142          * The Linux mid-layer assumes that sense
4143          * was retrieved anytime the first byte of
4144          * the sense buffer looks "sane".
4145          */
4146         cmd->sense_buffer[0] = 0;
4147         if (ahc_get_transaction_status(scb) == CAM_REQ_INPROG) {
4148                 uint32_t amount_xferred;
4149
4150                 amount_xferred =
4151                     ahc_get_transfer_length(scb) - ahc_get_residual(scb);
4152                 if ((scb->flags & SCB_TRANSMISSION_ERROR) != 0) {
4153 #ifdef AHC_DEBUG
4154                         if ((ahc_debug & AHC_SHOW_MISC) != 0) {
4155                                 ahc_print_path(ahc, scb);
4156                                 printf("Set CAM_UNCOR_PARITY\n");
4157                         }
4158 #endif
4159                         ahc_set_transaction_status(scb, CAM_UNCOR_PARITY);
4160 #ifdef AHC_REPORT_UNDERFLOWS
4161                 /*
4162                  * This code is disabled by default as some
4163                  * clients of the SCSI system do not properly
4164                  * initialize the underflow parameter.  This
4165                  * results in spurious termination of commands
4166                  * that complete as expected (e.g. underflow is
4167                  * allowed as command can return variable amounts
4168                  * of data.
4169                  */
4170                 } else if (amount_xferred < scb->io_ctx->underflow) {
4171                         u_int i;
4172
4173                         ahc_print_path(ahc, scb);
4174                         printf("CDB:");
4175                         for (i = 0; i < scb->io_ctx->cmd_len; i++)
4176                                 printf(" 0x%x", scb->io_ctx->cmnd[i]);
4177                         printf("\n");
4178                         ahc_print_path(ahc, scb);
4179                         printf("Saw underflow (%ld of %ld bytes). "
4180                                "Treated as error\n",
4181                                 ahc_get_residual(scb),
4182                                 ahc_get_transfer_length(scb));
4183                         ahc_set_transaction_status(scb, CAM_DATA_RUN_ERR);
4184 #endif
4185                 } else {
4186                         ahc_set_transaction_status(scb, CAM_REQ_CMP);
4187                 }
4188         } else if (ahc_get_transaction_status(scb) == CAM_SCSI_STATUS_ERROR) {
4189                 ahc_linux_handle_scsi_status(ahc, dev, scb);
4190         } else if (ahc_get_transaction_status(scb) == CAM_SEL_TIMEOUT) {
4191                 dev->flags |= AHC_DEV_UNCONFIGURED;
4192                 if (AHC_DV_CMD(cmd) == FALSE)
4193                         dev->target->flags &= ~AHC_DV_REQUIRED;
4194         }
4195         /*
4196          * Start DV for devices that require it assuming the first command
4197          * sent does not result in a selection timeout.
4198          */
4199         if (ahc_get_transaction_status(scb) != CAM_SEL_TIMEOUT
4200          && (dev->target->flags & AHC_DV_REQUIRED) != 0)
4201                 ahc_linux_start_dv(ahc);
4202
4203         if (dev->openings == 1
4204          && ahc_get_transaction_status(scb) == CAM_REQ_CMP
4205          && ahc_get_scsi_status(scb) != SCSI_STATUS_QUEUE_FULL)
4206                 dev->tag_success_count++;
4207         /*
4208          * Some devices deal with temporary internal resource
4209          * shortages by returning queue full.  When the queue
4210          * full occurrs, we throttle back.  Slowly try to get
4211          * back to our previous queue depth.
4212          */
4213         if ((dev->openings + dev->active) < dev->maxtags
4214          && dev->tag_success_count > AHC_TAG_SUCCESS_INTERVAL) {
4215                 dev->tag_success_count = 0;
4216                 dev->openings++;
4217         }
4218
4219         if (dev->active == 0)
4220                 dev->commands_since_idle_or_otag = 0;
4221
4222         if (TAILQ_EMPTY(&dev->busyq)) {
4223                 if ((dev->flags & AHC_DEV_UNCONFIGURED) != 0
4224                  && dev->active == 0
4225                  && (dev->flags & AHC_DEV_TIMER_ACTIVE) == 0)
4226                         ahc_linux_free_device(ahc, dev);
4227         } else if ((dev->flags & AHC_DEV_ON_RUN_LIST) == 0) {
4228                 TAILQ_INSERT_TAIL(&ahc->platform_data->device_runq, dev, links);
4229                 dev->flags |= AHC_DEV_ON_RUN_LIST;
4230         }
4231
4232         if ((scb->flags & SCB_RECOVERY_SCB) != 0) {
4233                 printf("Recovery SCB completes\n");
4234                 if (ahc_get_transaction_status(scb) == CAM_BDR_SENT
4235                  || ahc_get_transaction_status(scb) == CAM_REQ_ABORTED)
4236                         ahc_set_transaction_status(scb, CAM_CMD_TIMEOUT);
4237                 if ((ahc->platform_data->flags & AHC_UP_EH_SEMAPHORE) != 0) {
4238                         ahc->platform_data->flags &= ~AHC_UP_EH_SEMAPHORE;
4239                         up(&ahc->platform_data->eh_sem);
4240                 }
4241         }
4242
4243         ahc_free_scb(ahc, scb);
4244         ahc_linux_queue_cmd_complete(ahc, cmd);
4245
4246         if ((ahc->platform_data->flags & AHC_DV_WAIT_SIMQ_EMPTY) != 0
4247          && LIST_FIRST(&ahc->pending_scbs) == NULL) {
4248                 ahc->platform_data->flags &= ~AHC_DV_WAIT_SIMQ_EMPTY;
4249                 up(&ahc->platform_data->dv_sem);
4250         }
4251                 
4252 }
4253
4254 static void
4255 ahc_linux_handle_scsi_status(struct ahc_softc *ahc,
4256                              struct ahc_linux_device *dev, struct scb *scb)
4257 {
4258         struct  ahc_devinfo devinfo;
4259
4260         ahc_compile_devinfo(&devinfo,
4261                             ahc->our_id,
4262                             dev->target->target, dev->lun,
4263                             dev->target->channel == 0 ? 'A' : 'B',
4264                             ROLE_INITIATOR);
4265         
4266         /*
4267          * We don't currently trust the mid-layer to
4268          * properly deal with queue full or busy.  So,
4269          * when one occurs, we tell the mid-layer to
4270          * unconditionally requeue the command to us
4271          * so that we can retry it ourselves.  We also
4272          * implement our own throttling mechanism so
4273          * we don't clobber the device with too many
4274          * commands.
4275          */
4276         switch (ahc_get_scsi_status(scb)) {
4277         default:
4278                 break;
4279         case SCSI_STATUS_CHECK_COND:
4280         case SCSI_STATUS_CMD_TERMINATED:
4281         {
4282                 Scsi_Cmnd *cmd;
4283
4284                 /*
4285                  * Copy sense information to the OS's cmd
4286                  * structure if it is available.
4287                  */
4288                 cmd = scb->io_ctx;
4289                 if (scb->flags & SCB_SENSE) {
4290                         u_int sense_size;
4291
4292                         sense_size = MIN(sizeof(struct scsi_sense_data)
4293                                        - ahc_get_sense_residual(scb),
4294                                          sizeof(cmd->sense_buffer));
4295                         memcpy(cmd->sense_buffer,
4296                                ahc_get_sense_buf(ahc, scb), sense_size);
4297                         if (sense_size < sizeof(cmd->sense_buffer))
4298                                 memset(&cmd->sense_buffer[sense_size], 0,
4299                                        sizeof(cmd->sense_buffer) - sense_size);
4300                         cmd->result |= (DRIVER_SENSE << 24);
4301 #ifdef AHC_DEBUG
4302                         if (ahc_debug & AHC_SHOW_SENSE) {
4303                                 int i;
4304
4305                                 printf("Copied %d bytes of sense data:",
4306                                        sense_size);
4307                                 for (i = 0; i < sense_size; i++) {
4308                                         if ((i & 0xF) == 0)
4309                                                 printf("\n");
4310                                         printf("0x%x ", cmd->sense_buffer[i]);
4311                                 }
4312                                 printf("\n");
4313                         }
4314 #endif
4315                 }
4316                 break;
4317         }
4318         case SCSI_STATUS_QUEUE_FULL:
4319         {
4320                 /*
4321                  * By the time the core driver has returned this
4322                  * command, all other commands that were queued
4323                  * to us but not the device have been returned.
4324                  * This ensures that dev->active is equal to
4325                  * the number of commands actually queued to
4326                  * the device.
4327                  */
4328                 dev->tag_success_count = 0;
4329                 if (dev->active != 0) {
4330                         /*
4331                          * Drop our opening count to the number
4332                          * of commands currently outstanding.
4333                          */
4334                         dev->openings = 0;
4335 /*
4336                         ahc_print_path(ahc, scb);
4337                         printf("Dropping tag count to %d\n", dev->active);
4338  */
4339                         if (dev->active == dev->tags_on_last_queuefull) {
4340
4341                                 dev->last_queuefull_same_count++;
4342                                 /*
4343                                  * If we repeatedly see a queue full
4344                                  * at the same queue depth, this
4345                                  * device has a fixed number of tag
4346                                  * slots.  Lock in this tag depth
4347                                  * so we stop seeing queue fulls from
4348                                  * this device.
4349                                  */
4350                                 if (dev->last_queuefull_same_count
4351                                  == AHC_LOCK_TAGS_COUNT) {
4352                                         dev->maxtags = dev->active;
4353                                         ahc_print_path(ahc, scb);
4354                                         printf("Locking max tag count at %d\n",
4355                                                dev->active);
4356                                 }
4357                         } else {
4358                                 dev->tags_on_last_queuefull = dev->active;
4359                                 dev->last_queuefull_same_count = 0;
4360                         }
4361                         ahc_set_transaction_status(scb, CAM_REQUEUE_REQ);
4362                         ahc_set_scsi_status(scb, SCSI_STATUS_OK);
4363                         ahc_platform_set_tags(ahc, &devinfo,
4364                                      (dev->flags & AHC_DEV_Q_BASIC)
4365                                    ? AHC_QUEUE_BASIC : AHC_QUEUE_TAGGED);
4366                         break;
4367                 }
4368                 /*
4369                  * Drop down to a single opening, and treat this
4370                  * as if the target returned BUSY SCSI status.
4371                  */
4372                 dev->openings = 1;
4373                 ahc_set_scsi_status(scb, SCSI_STATUS_BUSY);
4374                 ahc_platform_set_tags(ahc, &devinfo,
4375                              (dev->flags & AHC_DEV_Q_BASIC)
4376                            ? AHC_QUEUE_BASIC : AHC_QUEUE_TAGGED);
4377                 /* FALLTHROUGH */
4378         }
4379         case SCSI_STATUS_BUSY:
4380         {
4381                 /*
4382                  * Set a short timer to defer sending commands for
4383                  * a bit since Linux will not delay in this case.
4384                  */
4385                 if ((dev->flags & AHC_DEV_TIMER_ACTIVE) != 0) {
4386                         printf("%s:%c:%d: Device Timer still active during "
4387                                "busy processing\n", ahc_name(ahc),
4388                                 dev->target->channel, dev->target->target);
4389                         break;
4390                 }
4391                 dev->flags |= AHC_DEV_TIMER_ACTIVE;
4392                 dev->qfrozen++;
4393                 init_timer(&dev->timer);
4394                 dev->timer.data = (u_long)dev;
4395                 dev->timer.expires = jiffies + (HZ/2);
4396                 dev->timer.function = ahc_linux_dev_timed_unfreeze;
4397                 add_timer(&dev->timer);
4398                 break;
4399         }
4400         }
4401 }
4402
4403 static void
4404 ahc_linux_queue_cmd_complete(struct ahc_softc *ahc, Scsi_Cmnd *cmd)
4405 {
4406         /*
4407          * Typically, the complete queue has very few entries
4408          * queued to it before the queue is emptied by
4409          * ahc_linux_run_complete_queue, so sorting the entries
4410          * by generation number should be inexpensive.
4411          * We perform the sort so that commands that complete
4412          * with an error are retuned in the order origionally
4413          * queued to the controller so that any subsequent retries
4414          * are performed in order.  The underlying ahc routines do
4415          * not guarantee the order that aborted commands will be
4416          * returned to us.
4417          */
4418         struct ahc_completeq *completeq;
4419         struct ahc_cmd *list_cmd;
4420         struct ahc_cmd *acmd;
4421
4422         /*
4423          * Map CAM error codes into Linux Error codes.  We
4424          * avoid the conversion so that the DV code has the
4425          * full error information available when making
4426          * state change decisions.
4427          */
4428         if (AHC_DV_CMD(cmd) == FALSE) {
4429                 u_int new_status;
4430
4431                 switch (ahc_cmd_get_transaction_status(cmd)) {
4432                 case CAM_REQ_INPROG:
4433                 case CAM_REQ_CMP:
4434                 case CAM_SCSI_STATUS_ERROR:
4435                         new_status = DID_OK;
4436                         break;
4437                 case CAM_REQ_ABORTED:
4438                         new_status = DID_ABORT;
4439                         break;
4440                 case CAM_BUSY:
4441                         new_status = DID_BUS_BUSY;
4442                         break;
4443                 case CAM_REQ_INVALID:
4444                 case CAM_PATH_INVALID:
4445                         new_status = DID_BAD_TARGET;
4446                         break;
4447                 case CAM_SEL_TIMEOUT:
4448                         new_status = DID_NO_CONNECT;
4449                         break;
4450                 case CAM_SCSI_BUS_RESET:
4451                 case CAM_BDR_SENT:
4452                         new_status = DID_RESET;
4453                         break;
4454                 case CAM_UNCOR_PARITY:
4455                         new_status = DID_PARITY;
4456                         break;
4457                 case CAM_CMD_TIMEOUT:
4458                         new_status = DID_TIME_OUT;
4459                         break;
4460                 case CAM_UA_ABORT:
4461                 case CAM_REQ_CMP_ERR:
4462                 case CAM_AUTOSENSE_FAIL:
4463                 case CAM_NO_HBA:
4464                 case CAM_DATA_RUN_ERR:
4465                 case CAM_UNEXP_BUSFREE:
4466                 case CAM_SEQUENCE_FAIL:
4467                 case CAM_CCB_LEN_ERR:
4468                 case CAM_PROVIDE_FAIL:
4469                 case CAM_REQ_TERMIO:
4470                 case CAM_UNREC_HBA_ERROR:
4471                 case CAM_REQ_TOO_BIG:
4472                         new_status = DID_ERROR;
4473                         break;
4474                 case CAM_REQUEUE_REQ:
4475                         /*
4476                          * If we want the request requeued, make sure there
4477                          * are sufficent retries.  In the old scsi error code,
4478                          * we used to be able to specify a result code that
4479                          * bypassed the retry count.  Now we must use this
4480                          * hack.  We also "fake" a check condition with
4481                          * a sense code of ABORTED COMMAND.  This seems to
4482                          * evoke a retry even if this command is being sent
4483                          * via the eh thread.  Ick!  Ick!  Ick!
4484                          */
4485                         if (cmd->retries > 0)
4486                                 cmd->retries--;
4487                         new_status = DID_OK;
4488                         ahc_cmd_set_scsi_status(cmd, SCSI_STATUS_CHECK_COND);
4489                         cmd->result |= (DRIVER_SENSE << 24);
4490                         memset(cmd->sense_buffer, 0,
4491                                sizeof(cmd->sense_buffer));
4492                         cmd->sense_buffer[0] = SSD_ERRCODE_VALID
4493                                              | SSD_CURRENT_ERROR;
4494                         cmd->sense_buffer[2] = SSD_KEY_ABORTED_COMMAND;
4495                         break;
4496                 default:
4497                         /* We should never get here */
4498                         new_status = DID_ERROR;
4499                         break;
4500                 }
4501
4502                 ahc_cmd_set_transaction_status(cmd, new_status);
4503         }
4504
4505         completeq = &ahc->platform_data->completeq;
4506         list_cmd = TAILQ_FIRST(completeq);
4507         acmd = (struct ahc_cmd *)cmd;
4508         while (list_cmd != NULL
4509             && acmd_scsi_cmd(list_cmd).serial_number
4510              < acmd_scsi_cmd(acmd).serial_number)
4511                 list_cmd = TAILQ_NEXT(list_cmd, acmd_links.tqe);
4512         if (list_cmd != NULL)
4513                 TAILQ_INSERT_BEFORE(list_cmd, acmd, acmd_links.tqe);
4514         else
4515                 TAILQ_INSERT_TAIL(completeq, acmd, acmd_links.tqe);
4516 }
4517
4518 static void
4519 ahc_linux_filter_inquiry(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
4520 {
4521         struct  scsi_inquiry_data *sid;
4522         struct  ahc_initiator_tinfo *tinfo;
4523         struct  ahc_transinfo *user;
4524         struct  ahc_transinfo *goal;
4525         struct  ahc_transinfo *curr;
4526         struct  ahc_tmode_tstate *tstate;
4527         struct  ahc_syncrate *syncrate;
4528         struct  ahc_linux_device *dev;
4529         u_int   maxsync;
4530         u_int   width;
4531         u_int   period;
4532         u_int   offset;
4533         u_int   ppr_options;
4534         u_int   trans_version;
4535         u_int   prot_version;
4536
4537         /*
4538          * Determine if this lun actually exists.  If so,
4539          * hold on to its corresponding device structure.
4540          * If not, make sure we release the device and
4541          * don't bother processing the rest of this inquiry
4542          * command.
4543          */
4544         dev = ahc_linux_get_device(ahc, devinfo->channel - 'A',
4545                                    devinfo->target, devinfo->lun,
4546                                    /*alloc*/TRUE);
4547
4548         sid = (struct scsi_inquiry_data *)dev->target->inq_data;
4549         if (SID_QUAL(sid) == SID_QUAL_LU_CONNECTED) {
4550
4551                 dev->flags &= ~AHC_DEV_UNCONFIGURED;
4552         } else {
4553                 dev->flags |= AHC_DEV_UNCONFIGURED;
4554                 return;
4555         }
4556
4557         /*
4558          * Update our notion of this device's transfer
4559          * negotiation capabilities.
4560          */
4561         tinfo = ahc_fetch_transinfo(ahc, devinfo->channel,
4562                                     devinfo->our_scsiid,
4563                                     devinfo->target, &tstate);
4564         user = &tinfo->user;
4565         goal = &tinfo->goal;
4566         curr = &tinfo->curr;
4567         width = user->width;
4568         period = user->period;
4569         offset = user->offset;
4570         ppr_options = user->ppr_options;
4571         trans_version = user->transport_version;
4572         prot_version = MIN(user->protocol_version, SID_ANSI_REV(sid));
4573
4574         /*
4575          * Only attempt SPI3/4 once we've verified that
4576          * the device claims to support SPI3/4 features.
4577          */
4578         if (prot_version < SCSI_REV_2)
4579                 trans_version = SID_ANSI_REV(sid);
4580         else
4581                 trans_version = SCSI_REV_2;
4582
4583         if ((sid->flags & SID_WBus16) == 0)
4584                 width = MSG_EXT_WDTR_BUS_8_BIT;
4585         if ((sid->flags & SID_Sync) == 0) {
4586                 period = 0;
4587                 offset = 0;
4588                 ppr_options = 0;
4589         }
4590         if ((sid->spi3data & SID_SPI_QAS) == 0)
4591                 ppr_options &= ~MSG_EXT_PPR_QAS_REQ;
4592         if ((sid->spi3data & SID_SPI_CLOCK_DT) == 0)
4593                 ppr_options &= MSG_EXT_PPR_QAS_REQ;
4594         if ((sid->spi3data & SID_SPI_IUS) == 0)
4595                 ppr_options &= (MSG_EXT_PPR_DT_REQ
4596                               | MSG_EXT_PPR_QAS_REQ);
4597
4598         if (prot_version > SCSI_REV_2
4599          && ppr_options != 0)
4600                 trans_version = user->transport_version;
4601
4602         ahc_validate_width(ahc, /*tinfo limit*/NULL, &width, ROLE_UNKNOWN);
4603         if ((ahc->features & AHC_ULTRA2) != 0)
4604                 maxsync = AHC_SYNCRATE_DT;
4605         else if ((ahc->features & AHC_ULTRA) != 0)
4606                 maxsync = AHC_SYNCRATE_ULTRA;
4607         else
4608                 maxsync = AHC_SYNCRATE_FAST;
4609
4610         syncrate = ahc_find_syncrate(ahc, &period, &ppr_options, maxsync);
4611         ahc_validate_offset(ahc, /*tinfo limit*/NULL, syncrate,
4612                             &offset, width, ROLE_UNKNOWN);
4613         if (offset == 0 || period == 0) {
4614                 period = 0;
4615                 offset = 0;
4616                 ppr_options = 0;
4617         }
4618         /* Apply our filtered user settings. */
4619         curr->transport_version = trans_version;
4620         curr->protocol_version = prot_version;
4621         ahc_set_width(ahc, devinfo, width, AHC_TRANS_GOAL, /*paused*/FALSE);
4622         ahc_set_syncrate(ahc, devinfo, syncrate, period,
4623                          offset, ppr_options, AHC_TRANS_GOAL,
4624                          /*paused*/FALSE);
4625 }
4626
4627 static void
4628 ahc_linux_sem_timeout(u_long arg)
4629 {
4630         struct  ahc_softc *ahc;
4631         u_long  s;
4632
4633         ahc = (struct ahc_softc *)arg;
4634
4635         ahc_lock(ahc, &s);
4636         if ((ahc->platform_data->flags & AHC_UP_EH_SEMAPHORE) != 0) {
4637                 ahc->platform_data->flags &= ~AHC_UP_EH_SEMAPHORE;
4638                 up(&ahc->platform_data->eh_sem);
4639         }
4640         ahc_unlock(ahc, &s);
4641 }
4642
4643 static void
4644 ahc_linux_freeze_simq(struct ahc_softc *ahc)
4645 {
4646         ahc->platform_data->qfrozen++;
4647         if (ahc->platform_data->qfrozen == 1) {
4648                 scsi_block_requests(ahc->platform_data->host);
4649
4650                 /* XXX What about Twin channels? */
4651                 ahc_platform_abort_scbs(ahc, CAM_TARGET_WILDCARD, ALL_CHANNELS,
4652                                         CAM_LUN_WILDCARD, SCB_LIST_NULL,
4653                                         ROLE_INITIATOR, CAM_REQUEUE_REQ);
4654         }
4655 }
4656
4657 static void
4658 ahc_linux_release_simq(u_long arg)
4659 {
4660         struct ahc_softc *ahc;
4661         u_long s;
4662         int    unblock_reqs;
4663
4664         ahc = (struct ahc_softc *)arg;
4665
4666         unblock_reqs = 0;
4667         ahc_lock(ahc, &s);
4668         if (ahc->platform_data->qfrozen > 0)
4669                 ahc->platform_data->qfrozen--;
4670         if (ahc->platform_data->qfrozen == 0)
4671                 unblock_reqs = 1;
4672         if (AHC_DV_SIMQ_FROZEN(ahc)
4673          && ((ahc->platform_data->flags & AHC_DV_WAIT_SIMQ_RELEASE) != 0)) {
4674                 ahc->platform_data->flags &= ~AHC_DV_WAIT_SIMQ_RELEASE;
4675                 up(&ahc->platform_data->dv_sem);
4676         }
4677         ahc_schedule_runq(ahc);
4678         ahc_unlock(ahc, &s);
4679         /*
4680          * There is still a race here.  The mid-layer
4681          * should keep its own freeze count and use
4682          * a bottom half handler to run the queues
4683          * so we can unblock with our own lock held.
4684          */
4685         if (unblock_reqs)
4686                 scsi_unblock_requests(ahc->platform_data->host);
4687 }
4688
4689 static void
4690 ahc_linux_dev_timed_unfreeze(u_long arg)
4691 {
4692         struct ahc_linux_device *dev;
4693         struct ahc_softc *ahc;
4694         u_long s;
4695
4696         dev = (struct ahc_linux_device *)arg;
4697         ahc = dev->target->ahc;
4698         ahc_lock(ahc, &s);
4699         dev->flags &= ~AHC_DEV_TIMER_ACTIVE;
4700         if (dev->qfrozen > 0)
4701                 dev->qfrozen--;
4702         if (dev->qfrozen == 0
4703          && (dev->flags & AHC_DEV_ON_RUN_LIST) == 0)
4704                 ahc_linux_run_device_queue(ahc, dev);
4705         if (TAILQ_EMPTY(&dev->busyq)
4706          && dev->active == 0)
4707                 __ahc_linux_free_device(ahc, dev);
4708         ahc_unlock(ahc, &s);
4709 }
4710
4711 static int
4712 ahc_linux_queue_recovery_cmd(Scsi_Cmnd *cmd, scb_flag flag)
4713 {
4714         struct ahc_softc *ahc;
4715         struct ahc_cmd *acmd;
4716         struct ahc_cmd *list_acmd;
4717         struct ahc_linux_device *dev;
4718         struct scb *pending_scb;
4719         u_long s;
4720         u_int  saved_scbptr;
4721         u_int  active_scb_index;
4722         u_int  last_phase;
4723         u_int  saved_scsiid;
4724         u_int  cdb_byte;
4725         int    retval;
4726         int    was_paused;
4727         int    paused;
4728         int    wait;
4729         int    disconnected;
4730
4731         pending_scb = NULL;
4732         paused = FALSE;
4733         wait = FALSE;
4734         ahc = *(struct ahc_softc **)cmd->device->host->hostdata;
4735         acmd = (struct ahc_cmd *)cmd;
4736
4737         printf("%s:%d:%d:%d: Attempting to queue a%s message\n",
4738                ahc_name(ahc), cmd->device->channel,
4739                cmd->device->id, cmd->device->lun,
4740                flag == SCB_ABORT ? "n ABORT" : " TARGET RESET");
4741
4742         printf("CDB:");
4743         for (cdb_byte = 0; cdb_byte < cmd->cmd_len; cdb_byte++)
4744                 printf(" 0x%x", cmd->cmnd[cdb_byte]);
4745         printf("\n");
4746
4747         /*
4748          * In all versions of Linux, we have to work around
4749          * a major flaw in how the mid-layer is locked down
4750          * if we are to sleep successfully in our error handler
4751          * while allowing our interrupt handler to run.  Since
4752          * the midlayer acquires either the io_request_lock or
4753          * our lock prior to calling us, we must use the
4754          * spin_unlock_irq() method for unlocking our lock.
4755          * This will force interrupts to be enabled on the
4756          * current CPU.  Since the EH thread should not have
4757          * been running with CPU interrupts disabled other than
4758          * by acquiring either the io_request_lock or our own
4759          * lock, this *should* be safe.
4760          */
4761         ahc_midlayer_entrypoint_lock(ahc, &s);
4762
4763         /*
4764          * First determine if we currently own this command.
4765          * Start by searching the device queue.  If not found
4766          * there, check the pending_scb list.  If not found
4767          * at all, and the system wanted us to just abort the
4768          * command, return success.
4769          */
4770         dev = ahc_linux_get_device(ahc, cmd->device->channel, cmd->device->id,
4771                                    cmd->device->lun, /*alloc*/FALSE);
4772
4773         if (dev == NULL) {
4774                 /*
4775                  * No target device for this command exists,
4776                  * so we must not still own the command.
4777                  */
4778                 printf("%s:%d:%d:%d: Is not an active device\n",
4779                        ahc_name(ahc), cmd->device->channel, cmd->device->id,
4780                        cmd->device->lun);
4781                 retval = SUCCESS;
4782                 goto no_cmd;
4783         }
4784
4785         TAILQ_FOREACH(list_acmd, &dev->busyq, acmd_links.tqe) {
4786                 if (list_acmd == acmd)
4787                         break;
4788         }
4789
4790         if (list_acmd != NULL) {
4791                 printf("%s:%d:%d:%d: Command found on device queue\n",
4792                        ahc_name(ahc), cmd->device->channel, cmd->device->id,
4793                        cmd->device->lun);
4794                 if (flag == SCB_ABORT) {
4795                         TAILQ_REMOVE(&dev->busyq, list_acmd, acmd_links.tqe);
4796                         cmd->result = DID_ABORT << 16;
4797                         ahc_linux_queue_cmd_complete(ahc, cmd);
4798                         retval = SUCCESS;
4799                         goto done;
4800                 }
4801         }
4802
4803         if ((dev->flags & (AHC_DEV_Q_BASIC|AHC_DEV_Q_TAGGED)) == 0
4804          && ahc_search_untagged_queues(ahc, cmd, cmd->device->id,
4805                                        cmd->device->channel + 'A',
4806                                        cmd->device->lun,
4807                                        CAM_REQ_ABORTED, SEARCH_COMPLETE) != 0) {
4808                 printf("%s:%d:%d:%d: Command found on untagged queue\n",
4809                        ahc_name(ahc), cmd->device->channel, cmd->device->id,
4810                        cmd->device->lun);
4811                 retval = SUCCESS;
4812                 goto done;
4813         }
4814
4815         /*
4816          * See if we can find a matching cmd in the pending list.
4817          */
4818         LIST_FOREACH(pending_scb, &ahc->pending_scbs, pending_links) {
4819                 if (pending_scb->io_ctx == cmd)
4820                         break;
4821         }
4822
4823         if (pending_scb == NULL && flag == SCB_DEVICE_RESET) {
4824
4825                 /* Any SCB for this device will do for a target reset */
4826                 LIST_FOREACH(pending_scb, &ahc->pending_scbs, pending_links) {
4827                         if (ahc_match_scb(ahc, pending_scb, cmd->device->id,
4828                                           cmd->device->channel + 'A',
4829                                           CAM_LUN_WILDCARD,
4830                                           SCB_LIST_NULL, ROLE_INITIATOR) == 0)
4831                                 break;
4832                 }
4833         }
4834
4835         if (pending_scb == NULL) {
4836                 printf("%s:%d:%d:%d: Command not found\n",
4837                        ahc_name(ahc), cmd->device->channel, cmd->device->id,
4838                        cmd->device->lun);
4839                 goto no_cmd;
4840         }
4841
4842         if ((pending_scb->flags & SCB_RECOVERY_SCB) != 0) {
4843                 /*
4844                  * We can't queue two recovery actions using the same SCB
4845                  */
4846                 retval = FAILED;
4847                 goto  done;
4848         }
4849
4850         /*
4851          * Ensure that the card doesn't do anything
4852          * behind our back and that we didn't "just" miss
4853          * an interrupt that would affect this cmd.
4854          */
4855         was_paused = ahc_is_paused(ahc);
4856         ahc_pause_and_flushwork(ahc);
4857         paused = TRUE;
4858
4859         if ((pending_scb->flags & SCB_ACTIVE) == 0) {
4860                 printf("%s:%d:%d:%d: Command already completed\n",
4861                        ahc_name(ahc), cmd->device->channel, cmd->device->id,
4862                        cmd->device->lun);
4863                 goto no_cmd;
4864         }
4865
4866         printf("%s: At time of recovery, card was %spaused\n",
4867                ahc_name(ahc), was_paused ? "" : "not ");
4868         ahc_dump_card_state(ahc);
4869
4870         disconnected = TRUE;
4871         if (flag == SCB_ABORT) {
4872                 if (ahc_search_qinfifo(ahc, cmd->device->id,
4873                                        cmd->device->channel + 'A',
4874                                        cmd->device->lun,
4875                                        pending_scb->hscb->tag,
4876                                        ROLE_INITIATOR, CAM_REQ_ABORTED,
4877                                        SEARCH_COMPLETE) > 0) {
4878                         printf("%s:%d:%d:%d: Cmd aborted from QINFIFO\n",
4879                                ahc_name(ahc), cmd->device->channel,
4880                                         cmd->device->id, cmd->device->lun);
4881                         retval = SUCCESS;
4882                         goto done;
4883                 }
4884         } else if (ahc_search_qinfifo(ahc, cmd->device->id,
4885                                       cmd->device->channel + 'A',
4886                                       cmd->device->lun, pending_scb->hscb->tag,
4887                                       ROLE_INITIATOR, /*status*/0,
4888                                       SEARCH_COUNT) > 0) {
4889                 disconnected = FALSE;
4890         }
4891
4892         if (disconnected && (ahc_inb(ahc, SEQ_FLAGS) & NOT_IDENTIFIED) == 0) {
4893                 struct scb *bus_scb;
4894
4895                 bus_scb = ahc_lookup_scb(ahc, ahc_inb(ahc, SCB_TAG));
4896                 if (bus_scb == pending_scb)
4897                         disconnected = FALSE;
4898                 else if (flag != SCB_ABORT
4899                       && ahc_inb(ahc, SAVED_SCSIID) == pending_scb->hscb->scsiid
4900                       && ahc_inb(ahc, SAVED_LUN) == SCB_GET_LUN(pending_scb))
4901                         disconnected = FALSE;
4902         }
4903
4904         /*
4905          * At this point, pending_scb is the scb associated with the
4906          * passed in command.  That command is currently active on the
4907          * bus, is in the disconnected state, or we're hoping to find
4908          * a command for the same target active on the bus to abuse to
4909          * send a BDR.  Queue the appropriate message based on which of
4910          * these states we are in.
4911          */
4912         last_phase = ahc_inb(ahc, LASTPHASE);
4913         saved_scbptr = ahc_inb(ahc, SCBPTR);
4914         active_scb_index = ahc_inb(ahc, SCB_TAG);
4915         saved_scsiid = ahc_inb(ahc, SAVED_SCSIID);
4916         if (last_phase != P_BUSFREE
4917          && (pending_scb->hscb->tag == active_scb_index
4918           || (flag == SCB_DEVICE_RESET
4919            && SCSIID_TARGET(ahc, saved_scsiid) == cmd->device->id))) {
4920
4921                 /*
4922                  * We're active on the bus, so assert ATN
4923                  * and hope that the target responds.
4924                  */
4925                 pending_scb = ahc_lookup_scb(ahc, active_scb_index);
4926                 pending_scb->flags |= SCB_RECOVERY_SCB|flag;
4927                 ahc_outb(ahc, MSG_OUT, HOST_MSG);
4928                 ahc_outb(ahc, SCSISIGO, last_phase|ATNO);
4929                 printf("%s:%d:%d:%d: Device is active, asserting ATN\n",
4930                        ahc_name(ahc), cmd->device->channel, cmd->device->id,
4931                        cmd->device->lun);
4932                 wait = TRUE;
4933         } else if (disconnected) {
4934
4935                 /*
4936                  * Actually re-queue this SCB in an attempt
4937                  * to select the device before it reconnects.
4938                  * In either case (selection or reselection),
4939                  * we will now issue the approprate message
4940                  * to the timed-out device.
4941                  *
4942                  * Set the MK_MESSAGE control bit indicating
4943                  * that we desire to send a message.  We
4944                  * also set the disconnected flag since
4945                  * in the paging case there is no guarantee
4946                  * that our SCB control byte matches the
4947                  * version on the card.  We don't want the
4948                  * sequencer to abort the command thinking
4949                  * an unsolicited reselection occurred.
4950                  */
4951                 pending_scb->hscb->control |= MK_MESSAGE|DISCONNECTED;
4952                 pending_scb->flags |= SCB_RECOVERY_SCB|flag;
4953
4954                 /*
4955                  * Remove any cached copy of this SCB in the
4956                  * disconnected list in preparation for the
4957                  * queuing of our abort SCB.  We use the
4958                  * same element in the SCB, SCB_NEXT, for
4959                  * both the qinfifo and the disconnected list.
4960                  */
4961                 ahc_search_disc_list(ahc, cmd->device->id,
4962                                      cmd->device->channel + 'A',
4963                                      cmd->device->lun, pending_scb->hscb->tag,
4964                                      /*stop_on_first*/TRUE,
4965                                      /*remove*/TRUE,
4966                                      /*save_state*/FALSE);
4967
4968                 /*
4969                  * In the non-paging case, the sequencer will
4970                  * never re-reference the in-core SCB.
4971                  * To make sure we are notified during
4972                  * reslection, set the MK_MESSAGE flag in
4973                  * the card's copy of the SCB.
4974                  */
4975                 if ((ahc->flags & AHC_PAGESCBS) == 0) {
4976                         ahc_outb(ahc, SCBPTR, pending_scb->hscb->tag);
4977                         ahc_outb(ahc, SCB_CONTROL,
4978                                  ahc_inb(ahc, SCB_CONTROL)|MK_MESSAGE);
4979                 }
4980
4981                 /*
4982                  * Clear out any entries in the QINFIFO first
4983                  * so we are the next SCB for this target
4984                  * to run.
4985                  */
4986                 ahc_search_qinfifo(ahc, cmd->device->id,
4987                                    cmd->device->channel + 'A',
4988                                    cmd->device->lun, SCB_LIST_NULL,
4989                                    ROLE_INITIATOR, CAM_REQUEUE_REQ,
4990                                    SEARCH_COMPLETE);
4991                 ahc_qinfifo_requeue_tail(ahc, pending_scb);
4992                 ahc_outb(ahc, SCBPTR, saved_scbptr);
4993                 ahc_print_path(ahc, pending_scb);
4994                 printf("Device is disconnected, re-queuing SCB\n");
4995                 wait = TRUE;
4996         } else {
4997                 printf("%s:%d:%d:%d: Unable to deliver message\n",
4998                        ahc_name(ahc), cmd->device->channel, cmd->device->id,
4999                        cmd->device->lun);
5000                 retval = FAILED;
5001                 goto done;
5002         }
5003
5004 no_cmd:
5005         /*
5006          * Our assumption is that if we don't have the command, no
5007          * recovery action was required, so we return success.  Again,
5008          * the semantics of the mid-layer recovery engine are not
5009          * well defined, so this may change in time.
5010          */
5011         retval = SUCCESS;
5012 done:
5013         if (paused)
5014                 ahc_unpause(ahc);
5015         if (wait) {
5016                 struct timer_list timer;
5017                 int ret;
5018
5019                 ahc->platform_data->flags |= AHC_UP_EH_SEMAPHORE;
5020                 spin_unlock_irq(&ahc->platform_data->spin_lock);
5021                 init_timer(&timer);
5022                 timer.data = (u_long)ahc;
5023                 timer.expires = jiffies + (5 * HZ);
5024                 timer.function = ahc_linux_sem_timeout;
5025                 add_timer(&timer);
5026                 printf("Recovery code sleeping\n");
5027                 down(&ahc->platform_data->eh_sem);
5028                 printf("Recovery code awake\n");
5029                 ret = del_timer_sync(&timer);
5030                 if (ret == 0) {
5031                         printf("Timer Expired\n");
5032                         retval = FAILED;
5033                 }
5034                 spin_lock_irq(&ahc->platform_data->spin_lock);
5035         }
5036         ahc_schedule_runq(ahc);
5037         ahc_linux_run_complete_queue(ahc);
5038         ahc_midlayer_entrypoint_unlock(ahc, &s);
5039         return (retval);
5040 }
5041
5042 void
5043 ahc_platform_dump_card_state(struct ahc_softc *ahc)
5044 {
5045         struct ahc_linux_device *dev;
5046         int channel;
5047         int maxchannel;
5048         int target;
5049         int maxtarget;
5050         int lun;
5051         int i;
5052
5053         maxchannel = (ahc->features & AHC_TWIN) ? 1 : 0;
5054         maxtarget = (ahc->features & AHC_WIDE) ? 15 : 7;
5055         for (channel = 0; channel <= maxchannel; channel++) {
5056
5057                 for (target = 0; target <=maxtarget; target++) {
5058
5059                         for (lun = 0; lun < AHC_NUM_LUNS; lun++) {
5060                                 struct ahc_cmd *acmd;
5061
5062                                 dev = ahc_linux_get_device(ahc, channel, target,
5063                                                            lun, /*alloc*/FALSE);
5064                                 if (dev == NULL)
5065                                         continue;
5066
5067                                 printf("DevQ(%d:%d:%d): ",
5068                                        channel, target, lun);
5069                                 i = 0;
5070                                 TAILQ_FOREACH(acmd, &dev->busyq,
5071                                               acmd_links.tqe) {
5072                                         if (i++ > AHC_SCB_MAX)
5073                                                 break;
5074                                 }
5075                                 printf("%d waiting\n", i);
5076                         }
5077                 }
5078         }
5079 }
5080
5081 static void ahc_linux_exit(void);
5082
5083 static int __init
5084 ahc_linux_init(void)
5085 {
5086 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
5087         int rc = ahc_linux_detect(&aic7xxx_driver_template);
5088         if (rc)
5089                 return rc;
5090         ahc_linux_exit();
5091         return -ENODEV;
5092 #else
5093         scsi_register_module(MODULE_SCSI_HA, &aic7xxx_driver_template);
5094         if (aic7xxx_driver_template.present == 0) {
5095                 scsi_unregister_module(MODULE_SCSI_HA,
5096                                        &aic7xxx_driver_template);
5097                 return (-ENODEV);
5098         }
5099
5100         return (0);
5101 #endif
5102 }
5103
5104 static void
5105 ahc_linux_exit(void)
5106 {
5107         struct ahc_softc *ahc;
5108         u_long l;
5109
5110         /*
5111          * Shutdown DV threads before going into the SCSI mid-layer.
5112          * This avoids situations where the mid-layer locks the entire
5113          * kernel so that waiting for our DV threads to exit leads
5114          * to deadlock.
5115          */
5116         ahc_list_lock(&l);
5117         TAILQ_FOREACH(ahc, &ahc_tailq, links) {
5118
5119                 ahc_linux_kill_dv_thread(ahc);
5120         }
5121         ahc_list_unlock(&l);
5122
5123 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
5124         /*
5125          * In 2.4 we have to unregister from the PCI core _after_
5126          * unregistering from the scsi midlayer to avoid dangling
5127          * references.
5128          */
5129         scsi_unregister_module(MODULE_SCSI_HA, &aic7xxx_driver_template);
5130 #endif
5131         ahc_linux_pci_exit();
5132         ahc_linux_eisa_exit();
5133 }
5134
5135 module_init(ahc_linux_init);
5136 module_exit(ahc_linux_exit);