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