ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[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 #endif
2595         unlock_kernel();
2596
2597         while (1) {
2598                 /*
2599                  * Use down_interruptible() rather than down() to
2600                  * avoid inclusion in the load average.
2601                  */
2602                 down_interruptible(&ahd->platform_data->dv_sem);
2603
2604                 /* Check to see if we've been signaled to exit */
2605                 ahd_lock(ahd, &s);
2606                 if ((ahd->platform_data->flags & AHD_DV_SHUTDOWN) != 0) {
2607                         ahd_unlock(ahd, &s);
2608                         break;
2609                 }
2610                 ahd_unlock(ahd, &s);
2611
2612 #ifdef AHD_DEBUG
2613                 if (ahd_debug & AHD_SHOW_DV)
2614                         printf("%s: Beginning Domain Validation\n",
2615                                ahd_name(ahd));
2616 #endif
2617
2618                 /*
2619                  * Wait for any pending commands to drain before proceeding.
2620                  */
2621                 ahd_lock(ahd, &s);
2622                 while (LIST_FIRST(&ahd->pending_scbs) != NULL) {
2623                         ahd->platform_data->flags |= AHD_DV_WAIT_SIMQ_EMPTY;
2624                         ahd_unlock(ahd, &s);
2625                         down_interruptible(&ahd->platform_data->dv_sem);
2626                         ahd_lock(ahd, &s);
2627                 }
2628
2629                 /*
2630                  * Wait for the SIMQ to be released so that DV is the
2631                  * only reason the queue is frozen.
2632                  */
2633                 while (AHD_DV_SIMQ_FROZEN(ahd) == 0) {
2634                         ahd->platform_data->flags |= AHD_DV_WAIT_SIMQ_RELEASE;
2635                         ahd_unlock(ahd, &s);
2636                         down_interruptible(&ahd->platform_data->dv_sem);
2637                         ahd_lock(ahd, &s);
2638                 }
2639                 ahd_unlock(ahd, &s);
2640
2641                 for (target = 0; target < AHD_NUM_TARGETS; target++)
2642                         ahd_linux_dv_target(ahd, target);
2643
2644                 ahd_lock(ahd, &s);
2645                 ahd->platform_data->flags &= ~AHD_DV_ACTIVE;
2646                 ahd_unlock(ahd, &s);
2647
2648                 /*
2649                  * Release the SIMQ so that normal commands are
2650                  * allowed to continue on the bus.
2651                  */
2652                 ahd_release_simq(ahd);
2653         }
2654         up(&ahd->platform_data->eh_sem);
2655         return (0);
2656 }
2657
2658 static void
2659 ahd_linux_kill_dv_thread(struct ahd_softc *ahd)
2660 {
2661         u_long s;
2662
2663         ahd_lock(ahd, &s);
2664         if (ahd->platform_data->dv_pid != 0) {
2665                 ahd->platform_data->flags |= AHD_DV_SHUTDOWN;
2666                 ahd_unlock(ahd, &s);
2667                 up(&ahd->platform_data->dv_sem);
2668
2669                 /*
2670                  * Use the eh_sem as an indicator that the
2671                  * dv thread is exiting.  Note that the dv
2672                  * thread must still return after performing
2673                  * the up on our semaphore before it has
2674                  * completely exited this module.  Unfortunately,
2675                  * there seems to be no easy way to wait for the
2676                  * exit of a thread for which you are not the
2677                  * parent (dv threads are parented by init).
2678                  * Cross your fingers...
2679                  */
2680                 down(&ahd->platform_data->eh_sem);
2681
2682                 /*
2683                  * Mark the dv thread as already dead.  This
2684                  * avoids attempting to kill it a second time.
2685                  * This is necessary because we must kill the
2686                  * DV thread before calling ahd_free() in the
2687                  * module shutdown case to avoid bogus locking
2688                  * in the SCSI mid-layer, but we ahd_free() is
2689                  * called without killing the DV thread in the
2690                  * instance detach case, so ahd_platform_free()
2691                  * calls us again to verify that the DV thread
2692                  * is dead.
2693                  */
2694                 ahd->platform_data->dv_pid = 0;
2695         } else {
2696                 ahd_unlock(ahd, &s);
2697         }
2698 }
2699
2700 #define AHD_LINUX_DV_INQ_SHORT_LEN      36
2701 #define AHD_LINUX_DV_INQ_LEN            256
2702 #define AHD_LINUX_DV_TIMEOUT            (HZ / 4)
2703
2704 #define AHD_SET_DV_STATE(ahd, targ, newstate) \
2705         ahd_set_dv_state(ahd, targ, newstate, __LINE__)
2706
2707 static __inline void
2708 ahd_set_dv_state(struct ahd_softc *ahd, struct ahd_linux_target *targ,
2709                  ahd_dv_state newstate, u_int line)
2710 {
2711         ahd_dv_state oldstate;
2712
2713         oldstate = targ->dv_state;
2714 #ifdef AHD_DEBUG
2715         if (ahd_debug & AHD_SHOW_DV)
2716                 printf("%s:%d: Going from state %d to state %d\n",
2717                        ahd_name(ahd), line, oldstate, newstate);
2718 #endif
2719
2720         if (oldstate == newstate)
2721                 targ->dv_state_retry++;
2722         else
2723                 targ->dv_state_retry = 0;
2724         targ->dv_state = newstate;
2725 }
2726
2727 static void
2728 ahd_linux_dv_target(struct ahd_softc *ahd, u_int target_offset)
2729 {
2730         struct   ahd_devinfo devinfo;
2731         struct   ahd_linux_target *targ;
2732         struct   scsi_cmnd *cmd;
2733         struct   scsi_device *scsi_dev;
2734         struct   scsi_sense_data *sense;
2735         uint8_t *buffer;
2736         u_long   s;
2737         u_int    timeout;
2738         int      echo_size;
2739
2740         sense = NULL;
2741         buffer = NULL;
2742         echo_size = 0;
2743         ahd_lock(ahd, &s);
2744         targ = ahd->platform_data->targets[target_offset];
2745         if (targ == NULL || (targ->flags & AHD_DV_REQUIRED) == 0) {
2746                 ahd_unlock(ahd, &s);
2747                 return;
2748         }
2749         ahd_compile_devinfo(&devinfo, ahd->our_id, targ->target, /*lun*/0,
2750                             targ->channel + 'A', ROLE_INITIATOR);
2751 #ifdef AHD_DEBUG
2752         if (ahd_debug & AHD_SHOW_DV) {
2753                 ahd_print_devinfo(ahd, &devinfo);
2754                 printf("Performing DV\n");
2755         }
2756 #endif
2757
2758         ahd_unlock(ahd, &s);
2759
2760         cmd = malloc(sizeof(struct scsi_cmnd), M_DEVBUF, M_WAITOK);
2761         scsi_dev = malloc(sizeof(struct scsi_device), M_DEVBUF, M_WAITOK);
2762         scsi_dev->host = ahd->platform_data->host;
2763         scsi_dev->id = devinfo.target;
2764         scsi_dev->lun = devinfo.lun;
2765         scsi_dev->channel = devinfo.channel - 'A';
2766         ahd->platform_data->dv_scsi_dev = scsi_dev;
2767
2768         AHD_SET_DV_STATE(ahd, targ, AHD_DV_STATE_INQ_SHORT_ASYNC);
2769
2770         while (targ->dv_state != AHD_DV_STATE_EXIT) {
2771                 timeout = AHD_LINUX_DV_TIMEOUT;
2772                 switch (targ->dv_state) {
2773                 case AHD_DV_STATE_INQ_SHORT_ASYNC:
2774                 case AHD_DV_STATE_INQ_ASYNC:
2775                 case AHD_DV_STATE_INQ_ASYNC_VERIFY:
2776                         /*
2777                          * Set things to async narrow to reduce the
2778                          * chance that the INQ will fail.
2779                          */
2780                         ahd_lock(ahd, &s);
2781                         ahd_set_syncrate(ahd, &devinfo, 0, 0, 0,
2782                                          AHD_TRANS_GOAL, /*paused*/FALSE);
2783                         ahd_set_width(ahd, &devinfo, MSG_EXT_WDTR_BUS_8_BIT,
2784                                       AHD_TRANS_GOAL, /*paused*/FALSE);
2785                         ahd_unlock(ahd, &s);
2786                         timeout = 10 * HZ;
2787                         targ->flags &= ~AHD_INQ_VALID;
2788                         /* FALLTHROUGH */
2789                 case AHD_DV_STATE_INQ_VERIFY:
2790                 {
2791                         u_int inq_len;
2792
2793                         if (targ->dv_state == AHD_DV_STATE_INQ_SHORT_ASYNC)
2794                                 inq_len = AHD_LINUX_DV_INQ_SHORT_LEN;
2795                         else
2796                                 inq_len = targ->inq_data->additional_length + 5;
2797                         ahd_linux_dv_inq(ahd, cmd, &devinfo, targ, inq_len);
2798                         break;
2799                 }
2800                 case AHD_DV_STATE_TUR:
2801                 case AHD_DV_STATE_BUSY:
2802                         timeout = 5 * HZ;
2803                         ahd_linux_dv_tur(ahd, cmd, &devinfo);
2804                         break;
2805                 case AHD_DV_STATE_REBD:
2806                         ahd_linux_dv_rebd(ahd, cmd, &devinfo, targ);
2807                         break;
2808                 case AHD_DV_STATE_WEB:
2809                         ahd_linux_dv_web(ahd, cmd, &devinfo, targ);
2810                         break;
2811
2812                 case AHD_DV_STATE_REB:
2813                         ahd_linux_dv_reb(ahd, cmd, &devinfo, targ);
2814                         break;
2815
2816                 case AHD_DV_STATE_SU:
2817                         ahd_linux_dv_su(ahd, cmd, &devinfo, targ);
2818                         timeout = 50 * HZ;
2819                         break;
2820
2821                 default:
2822                         ahd_print_devinfo(ahd, &devinfo);
2823                         printf("Unknown DV state %d\n", targ->dv_state);
2824                         goto out;
2825                 }
2826
2827                 /* Queue the command and wait for it to complete */
2828                 /* Abuse eh_timeout in the scsi_cmnd struct for our purposes */
2829                 init_timer(&cmd->eh_timeout);
2830 #ifdef AHD_DEBUG
2831                 if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
2832                         /*
2833                          * All of the printfs during negotiation
2834                          * really slow down the negotiation.
2835                          * Add a bit of time just to be safe.
2836                          */
2837                         timeout += HZ;
2838 #endif
2839                 scsi_add_timer(cmd, timeout, ahd_linux_dv_timeout);
2840                 /*
2841                  * In 2.5.X, it is assumed that all calls from the
2842                  * "midlayer" (which we are emulating) will have the
2843                  * ahd host lock held.  For other kernels, the
2844                  * io_request_lock must be held.
2845                  */
2846 #if AHD_SCSI_HAS_HOST_LOCK != 0
2847                 ahd_lock(ahd, &s);
2848 #else
2849                 spin_lock_irqsave(&io_request_lock, s);
2850 #endif
2851                 ahd_linux_queue(cmd, ahd_linux_dv_complete);
2852 #if AHD_SCSI_HAS_HOST_LOCK != 0
2853                 ahd_unlock(ahd, &s);
2854 #else
2855                 spin_unlock_irqrestore(&io_request_lock, s);
2856 #endif
2857                 down_interruptible(&ahd->platform_data->dv_cmd_sem);
2858                 /*
2859                  * Wait for the SIMQ to be released so that DV is the
2860                  * only reason the queue is frozen.
2861                  */
2862                 ahd_lock(ahd, &s);
2863                 while (AHD_DV_SIMQ_FROZEN(ahd) == 0) {
2864                         ahd->platform_data->flags |= AHD_DV_WAIT_SIMQ_RELEASE;
2865                         ahd_unlock(ahd, &s);
2866                         down_interruptible(&ahd->platform_data->dv_sem);
2867                         ahd_lock(ahd, &s);
2868                 }
2869                 ahd_unlock(ahd, &s);
2870
2871                 ahd_linux_dv_transition(ahd, cmd, &devinfo, targ);
2872         }
2873
2874 out:
2875         if ((targ->flags & AHD_INQ_VALID) != 0
2876          && ahd_linux_get_device(ahd, devinfo.channel - 'A',
2877                                  devinfo.target, devinfo.lun,
2878                                  /*alloc*/FALSE) == NULL) {
2879                 /*
2880                  * The DV state machine failed to configure this device.  
2881                  * This is normal if DV is disabled.  Since we have inquiry
2882                  * data, filter it and use the "optimistic" negotiation
2883                  * parameters found in the inquiry string.
2884                  */
2885                 ahd_linux_filter_inquiry(ahd, &devinfo);
2886                 if ((targ->flags & (AHD_BASIC_DV|AHD_ENHANCED_DV)) != 0) {
2887                         ahd_print_devinfo(ahd, &devinfo);
2888                         printf("DV failed to configure device.  "
2889                                "Please file a bug report against "
2890                                "this driver.\n");
2891                 }
2892         }
2893
2894         if (cmd != NULL)
2895                 free(cmd, M_DEVBUF);
2896
2897         if (ahd->platform_data->dv_scsi_dev != NULL) {
2898                 free(ahd->platform_data->dv_scsi_dev, M_DEVBUF);
2899                 ahd->platform_data->dv_scsi_dev = NULL;
2900         }
2901
2902         ahd_lock(ahd, &s);
2903         if (targ->dv_buffer != NULL) {
2904                 free(targ->dv_buffer, M_DEVBUF);
2905                 targ->dv_buffer = NULL;
2906         }
2907         if (targ->dv_buffer1 != NULL) {
2908                 free(targ->dv_buffer1, M_DEVBUF);
2909                 targ->dv_buffer1 = NULL;
2910         }
2911         targ->flags &= ~AHD_DV_REQUIRED;
2912         if (targ->refcount == 0)
2913                 ahd_linux_free_target(ahd, targ);
2914         ahd_unlock(ahd, &s);
2915 }
2916
2917 static void
2918 ahd_linux_dv_transition(struct ahd_softc *ahd, struct scsi_cmnd *cmd,
2919                         struct ahd_devinfo *devinfo,
2920                         struct ahd_linux_target *targ)
2921 {
2922         u_int32_t status;
2923
2924         status = aic_error_action(cmd, targ->inq_data,
2925                                   ahd_cmd_get_transaction_status(cmd),
2926                                   ahd_cmd_get_scsi_status(cmd));
2927
2928         
2929 #ifdef AHD_DEBUG
2930         if (ahd_debug & AHD_SHOW_DV) {
2931                 ahd_print_devinfo(ahd, devinfo);
2932                 printf("Entering ahd_linux_dv_transition, state= %d, "
2933                        "status= 0x%x, cmd->result= 0x%x\n", targ->dv_state,
2934                        status, cmd->result);
2935         }
2936 #endif
2937
2938         switch (targ->dv_state) {
2939         case AHD_DV_STATE_INQ_SHORT_ASYNC:
2940         case AHD_DV_STATE_INQ_ASYNC:
2941                 switch (status & SS_MASK) {
2942                 case SS_NOP:
2943                 {
2944                         AHD_SET_DV_STATE(ahd, targ, targ->dv_state+1);
2945                         break;
2946                 }
2947                 case SS_INQ_REFRESH:
2948                         AHD_SET_DV_STATE(ahd, targ,
2949                                          AHD_DV_STATE_INQ_SHORT_ASYNC);
2950                         break;
2951                 case SS_TUR:
2952                 case SS_RETRY:
2953                         AHD_SET_DV_STATE(ahd, targ, targ->dv_state);
2954                         if (ahd_cmd_get_transaction_status(cmd)
2955                          == CAM_REQUEUE_REQ)
2956                                 targ->dv_state_retry--;
2957                         if ((status & SS_ERRMASK) == EBUSY)
2958                                 AHD_SET_DV_STATE(ahd, targ, AHD_DV_STATE_BUSY);
2959                         if (targ->dv_state_retry < 10)
2960                                 break;
2961                         /* FALLTHROUGH */
2962                 default:
2963                         AHD_SET_DV_STATE(ahd, targ, AHD_DV_STATE_EXIT);
2964 #ifdef AHD_DEBUG
2965                         if (ahd_debug & AHD_SHOW_DV) {
2966                                 ahd_print_devinfo(ahd, devinfo);
2967                                 printf("Failed DV inquiry, skipping\n");
2968                         }
2969 #endif
2970                         break;
2971                 }
2972                 break;
2973         case AHD_DV_STATE_INQ_ASYNC_VERIFY:
2974                 switch (status & SS_MASK) {
2975                 case SS_NOP:
2976                 {
2977                         u_int xportflags;
2978                         u_int spi3data;
2979
2980                         if (memcmp(targ->inq_data, targ->dv_buffer,
2981                                    AHD_LINUX_DV_INQ_LEN) != 0) {
2982                                 /*
2983                                  * Inquiry data must have changed.
2984                                  * Try from the top again.
2985                                  */
2986                                 AHD_SET_DV_STATE(ahd, targ,
2987                                                  AHD_DV_STATE_INQ_SHORT_ASYNC);
2988                                 break;
2989                         }
2990
2991                         AHD_SET_DV_STATE(ahd, targ, targ->dv_state+1);
2992                         targ->flags |= AHD_INQ_VALID;
2993                         if (ahd_linux_user_dv_setting(ahd) == 0)
2994                                 break;
2995
2996                         xportflags = targ->inq_data->flags;
2997                         if ((xportflags & (SID_Sync|SID_WBus16)) == 0)
2998                                 break;
2999
3000                         spi3data = targ->inq_data->spi3data;
3001                         switch (spi3data & SID_SPI_CLOCK_DT_ST) {
3002                         default:
3003                         case SID_SPI_CLOCK_ST:
3004                                 /* Assume only basic DV is supported. */
3005                                 targ->flags |= AHD_BASIC_DV;
3006                                 break;
3007                         case SID_SPI_CLOCK_DT:
3008                         case SID_SPI_CLOCK_DT_ST:
3009                                 targ->flags |= AHD_ENHANCED_DV;
3010                                 break;
3011                         }
3012                         break;
3013                 }
3014                 case SS_INQ_REFRESH:
3015                         AHD_SET_DV_STATE(ahd, targ,
3016                                          AHD_DV_STATE_INQ_SHORT_ASYNC);
3017                         break;
3018                 case SS_TUR:
3019                 case SS_RETRY:
3020                         AHD_SET_DV_STATE(ahd, targ, targ->dv_state);
3021                         if (ahd_cmd_get_transaction_status(cmd)
3022                          == CAM_REQUEUE_REQ)
3023                                 targ->dv_state_retry--;
3024
3025                         if ((status & SS_ERRMASK) == EBUSY)
3026                                 AHD_SET_DV_STATE(ahd, targ, AHD_DV_STATE_BUSY);
3027                         if (targ->dv_state_retry < 10)
3028                                 break;
3029                         /* FALLTHROUGH */
3030                 default:
3031                         AHD_SET_DV_STATE(ahd, targ, AHD_DV_STATE_EXIT);
3032 #ifdef AHD_DEBUG
3033                         if (ahd_debug & AHD_SHOW_DV) {
3034                                 ahd_print_devinfo(ahd, devinfo);
3035                                 printf("Failed DV inquiry, skipping\n");
3036                         }
3037 #endif
3038                         break;
3039                 }
3040                 break;
3041         case AHD_DV_STATE_INQ_VERIFY:
3042                 switch (status & SS_MASK) {
3043                 case SS_NOP:
3044                 {
3045
3046                         if (memcmp(targ->inq_data, targ->dv_buffer,
3047                                    AHD_LINUX_DV_INQ_LEN) == 0) {
3048                                 AHD_SET_DV_STATE(ahd, targ, AHD_DV_STATE_EXIT);
3049                                 break;
3050                         }
3051
3052 #ifdef AHD_DEBUG
3053                         if (ahd_debug & AHD_SHOW_DV) {
3054                                 int i;
3055
3056                                 ahd_print_devinfo(ahd, devinfo);
3057                                 printf("Inquiry buffer mismatch:");
3058                                 for (i = 0; i < AHD_LINUX_DV_INQ_LEN; i++) {
3059                                         if ((i & 0xF) == 0)
3060                                                 printf("\n        ");
3061                                         printf("0x%x:0x0%x ",
3062                                                ((uint8_t *)targ->inq_data)[i], 
3063                                                targ->dv_buffer[i]);
3064                                 }
3065                                 printf("\n");
3066                         }
3067 #endif
3068
3069                         if (ahd_linux_dv_fallback(ahd, devinfo) != 0) {
3070                                 AHD_SET_DV_STATE(ahd, targ, AHD_DV_STATE_EXIT);
3071                                 break;
3072                         }
3073                         /*
3074                          * Do not count "falling back"
3075                          * against our retries.
3076                          */
3077                         targ->dv_state_retry = 0;
3078                         AHD_SET_DV_STATE(ahd, targ, targ->dv_state);
3079                         break;
3080                 }
3081                 case SS_INQ_REFRESH:
3082                         AHD_SET_DV_STATE(ahd, targ,
3083                                          AHD_DV_STATE_INQ_SHORT_ASYNC);
3084                         break;
3085                 case SS_TUR:
3086                 case SS_RETRY:
3087                         AHD_SET_DV_STATE(ahd, targ, targ->dv_state);
3088                         if (ahd_cmd_get_transaction_status(cmd)
3089                          == CAM_REQUEUE_REQ) {
3090                                 targ->dv_state_retry--;
3091                         } else if ((status & SSQ_FALLBACK) != 0) {
3092                                 if (ahd_linux_dv_fallback(ahd, devinfo) != 0) {
3093                                         AHD_SET_DV_STATE(ahd, targ,
3094                                                          AHD_DV_STATE_EXIT);
3095                                         break;
3096                                 }
3097                                 /*
3098                                  * Do not count "falling back"
3099                                  * against our retries.
3100                                  */
3101                                 targ->dv_state_retry = 0;
3102                         } else if ((status & SS_ERRMASK) == EBUSY)
3103                                 AHD_SET_DV_STATE(ahd, targ, AHD_DV_STATE_BUSY);
3104                         if (targ->dv_state_retry < 10)
3105                                 break;
3106                         /* FALLTHROUGH */
3107                 default:
3108                         AHD_SET_DV_STATE(ahd, targ, AHD_DV_STATE_EXIT);
3109 #ifdef AHD_DEBUG
3110                         if (ahd_debug & AHD_SHOW_DV) {
3111                                 ahd_print_devinfo(ahd, devinfo);
3112                                 printf("Failed DV inquiry, skipping\n");
3113                         }
3114 #endif
3115                         break;
3116                 }
3117                 break;
3118
3119         case AHD_DV_STATE_TUR:
3120                 switch (status & SS_MASK) {
3121                 case SS_NOP:
3122                         if ((targ->flags & AHD_BASIC_DV) != 0) {
3123                                 ahd_linux_filter_inquiry(ahd, devinfo);
3124                                 AHD_SET_DV_STATE(ahd, targ,
3125                                                  AHD_DV_STATE_INQ_VERIFY);
3126                         } else if ((targ->flags & AHD_ENHANCED_DV) != 0) {
3127                                 AHD_SET_DV_STATE(ahd, targ, AHD_DV_STATE_REBD);
3128                         } else {
3129                                 AHD_SET_DV_STATE(ahd, targ, AHD_DV_STATE_EXIT);
3130                         }
3131                         break;
3132                 case SS_RETRY:
3133                 case SS_TUR:
3134                         if ((status & SS_ERRMASK) == EBUSY) {
3135                                 AHD_SET_DV_STATE(ahd, targ, AHD_DV_STATE_BUSY);
3136                                 break;
3137                         }
3138                         AHD_SET_DV_STATE(ahd, targ, targ->dv_state);
3139                         if (ahd_cmd_get_transaction_status(cmd)
3140                          == CAM_REQUEUE_REQ) {
3141                                 targ->dv_state_retry--;
3142                         } else if ((status & SSQ_FALLBACK) != 0) {
3143                                 if (ahd_linux_dv_fallback(ahd, devinfo) != 0) {
3144                                         AHD_SET_DV_STATE(ahd, targ,
3145                                                          AHD_DV_STATE_EXIT);
3146                                         break;
3147                                 }
3148                                 /*
3149                                  * Do not count "falling back"
3150                                  * against our retries.
3151                                  */
3152                                 targ->dv_state_retry = 0;
3153                         }
3154                         if (targ->dv_state_retry >= 10) {
3155 #ifdef AHD_DEBUG
3156                                 if (ahd_debug & AHD_SHOW_DV) {
3157                                         ahd_print_devinfo(ahd, devinfo);
3158                                         printf("DV TUR reties exhausted\n");
3159                                 }
3160 #endif
3161                                 AHD_SET_DV_STATE(ahd, targ, AHD_DV_STATE_EXIT);
3162                                 break;
3163                         }
3164                         if (status & SSQ_DELAY)
3165                                 scsi_sleep(1 * HZ);
3166
3167                         break;
3168                 case SS_START:
3169                         AHD_SET_DV_STATE(ahd, targ, AHD_DV_STATE_SU);
3170                         break;
3171                 case SS_INQ_REFRESH:
3172                         AHD_SET_DV_STATE(ahd, targ,
3173                                          AHD_DV_STATE_INQ_SHORT_ASYNC);
3174                         break;
3175                 default:
3176                         AHD_SET_DV_STATE(ahd, targ, AHD_DV_STATE_EXIT);
3177                         break;
3178                 }
3179                 break;
3180
3181         case AHD_DV_STATE_REBD:
3182                 switch (status & SS_MASK) {
3183                 case SS_NOP:
3184                 {
3185                         uint32_t echo_size;
3186
3187                         AHD_SET_DV_STATE(ahd, targ, AHD_DV_STATE_WEB);
3188                         echo_size = scsi_3btoul(&targ->dv_buffer[1]);
3189                         echo_size &= 0x1FFF;
3190 #ifdef AHD_DEBUG
3191                         if (ahd_debug & AHD_SHOW_DV) {
3192                                 ahd_print_devinfo(ahd, devinfo);
3193                                 printf("Echo buffer size= %d\n", echo_size);
3194                         }
3195 #endif
3196                         if (echo_size == 0) {
3197                                 AHD_SET_DV_STATE(ahd, targ, AHD_DV_STATE_EXIT);
3198                                 break;
3199                         }
3200
3201                         /* Generate the buffer pattern */
3202                         targ->dv_echo_size = echo_size;
3203                         ahd_linux_generate_dv_pattern(targ);
3204                         /*
3205                          * Setup initial negotiation values.
3206                          */
3207                         ahd_linux_filter_inquiry(ahd, devinfo);
3208                         break;
3209                 }
3210                 case SS_INQ_REFRESH:
3211                         AHD_SET_DV_STATE(ahd, targ,
3212                                          AHD_DV_STATE_INQ_SHORT_ASYNC);
3213                         break;
3214                 case SS_RETRY:
3215                         AHD_SET_DV_STATE(ahd, targ, targ->dv_state);
3216                         if (ahd_cmd_get_transaction_status(cmd)
3217                          == CAM_REQUEUE_REQ)
3218                                 targ->dv_state_retry--;
3219                         if (targ->dv_state_retry <= 10)
3220                                 break;
3221 #ifdef AHD_DEBUG
3222                         if (ahd_debug & AHD_SHOW_DV) {
3223                                 ahd_print_devinfo(ahd, devinfo);
3224                                 printf("DV REBD reties exhausted\n");
3225                         }
3226 #endif
3227                         /* FALLTHROUGH */
3228                 case SS_FATAL:
3229                 default:
3230                         /*
3231                          * Setup initial negotiation values
3232                          * and try level 1 DV.
3233                          */
3234                         ahd_linux_filter_inquiry(ahd, devinfo);
3235                         AHD_SET_DV_STATE(ahd, targ, AHD_DV_STATE_INQ_VERIFY);
3236                         targ->dv_echo_size = 0;
3237                         break;
3238                 }
3239                 break;
3240
3241         case AHD_DV_STATE_WEB:
3242                 switch (status & SS_MASK) {
3243                 case SS_NOP:
3244                         AHD_SET_DV_STATE(ahd, targ, AHD_DV_STATE_REB);
3245                         break;
3246                 case SS_INQ_REFRESH:
3247                         AHD_SET_DV_STATE(ahd, targ,
3248                                          AHD_DV_STATE_INQ_SHORT_ASYNC);
3249                         break;
3250                 case SS_RETRY:
3251                         AHD_SET_DV_STATE(ahd, targ, targ->dv_state);
3252                         if (ahd_cmd_get_transaction_status(cmd)
3253                          == CAM_REQUEUE_REQ) {
3254                                 targ->dv_state_retry--;
3255                         } else if ((status & SSQ_FALLBACK) != 0) {
3256                                 if (ahd_linux_dv_fallback(ahd, devinfo) != 0) {
3257                                         AHD_SET_DV_STATE(ahd, targ,
3258                                                          AHD_DV_STATE_EXIT);
3259                                         break;
3260                                 }
3261                                 /*
3262                                  * Do not count "falling back"
3263                                  * against our retries.
3264                                  */
3265                                 targ->dv_state_retry = 0;
3266                         }
3267                         if (targ->dv_state_retry <= 10)
3268                                 break;
3269                         /* FALLTHROUGH */
3270 #ifdef AHD_DEBUG
3271                         if (ahd_debug & AHD_SHOW_DV) {
3272                                 ahd_print_devinfo(ahd, devinfo);
3273                                 printf("DV WEB reties exhausted\n");
3274                         }
3275 #endif
3276                 default:
3277                         AHD_SET_DV_STATE(ahd, targ, AHD_DV_STATE_EXIT);
3278                         break;
3279                 }
3280                 break;
3281
3282         case AHD_DV_STATE_REB:
3283                 switch (status & SS_MASK) {
3284                 case SS_NOP:
3285                         if (memcmp(targ->dv_buffer, targ->dv_buffer1,
3286                                    targ->dv_echo_size) != 0) {
3287                                 if (ahd_linux_dv_fallback(ahd, devinfo) != 0)
3288                                         AHD_SET_DV_STATE(ahd, targ,
3289                                                          AHD_DV_STATE_EXIT);
3290                                 else
3291                                         AHD_SET_DV_STATE(ahd, targ,
3292                                                          AHD_DV_STATE_WEB);
3293                                 break;
3294                         }
3295                         
3296                         if (targ->dv_buffer != NULL) {
3297                                 free(targ->dv_buffer, M_DEVBUF);
3298                                 targ->dv_buffer = NULL;
3299                         }
3300                         if (targ->dv_buffer1 != NULL) {
3301                                 free(targ->dv_buffer1, M_DEVBUF);
3302                                 targ->dv_buffer1 = NULL;
3303                         }
3304                         AHD_SET_DV_STATE(ahd, targ, AHD_DV_STATE_EXIT);
3305                         break;
3306                 case SS_INQ_REFRESH:
3307                         AHD_SET_DV_STATE(ahd, targ,
3308                                          AHD_DV_STATE_INQ_SHORT_ASYNC);
3309                         break;
3310                 case SS_RETRY:
3311                         AHD_SET_DV_STATE(ahd, targ, targ->dv_state);
3312                         if (ahd_cmd_get_transaction_status(cmd)
3313                          == CAM_REQUEUE_REQ) {
3314                                 targ->dv_state_retry--;
3315                         } else if ((status & SSQ_FALLBACK) != 0) {
3316                                 if (ahd_linux_dv_fallback(ahd, devinfo) != 0) {
3317                                         AHD_SET_DV_STATE(ahd, targ,
3318                                                          AHD_DV_STATE_EXIT);
3319                                         break;
3320                                 }
3321                                 AHD_SET_DV_STATE(ahd, targ, AHD_DV_STATE_WEB);
3322                         }
3323                         if (targ->dv_state_retry <= 10) {
3324                                 if ((status & (SSQ_DELAY_RANDOM|SSQ_DELAY))!= 0)
3325                                         scsi_sleep(ahd->our_id*HZ/10);
3326                                 break;
3327                         }
3328 #ifdef AHD_DEBUG
3329                         if (ahd_debug & AHD_SHOW_DV) {
3330                                 ahd_print_devinfo(ahd, devinfo);
3331                                 printf("DV REB reties exhausted\n");
3332                         }
3333 #endif
3334                         /* FALLTHROUGH */
3335                 default:
3336                         AHD_SET_DV_STATE(ahd, targ, AHD_DV_STATE_EXIT);
3337                         break;
3338                 }
3339                 break;
3340
3341         case AHD_DV_STATE_SU:
3342                 switch (status & SS_MASK) {
3343                 case SS_NOP:
3344                 case SS_INQ_REFRESH:
3345                         AHD_SET_DV_STATE(ahd, targ,
3346                                          AHD_DV_STATE_INQ_SHORT_ASYNC);
3347                         break;
3348                 default:
3349                         AHD_SET_DV_STATE(ahd, targ, AHD_DV_STATE_EXIT);
3350                         break;
3351                 }
3352                 break;
3353
3354         case AHD_DV_STATE_BUSY:
3355                 switch (status & SS_MASK) {
3356                 case SS_NOP:
3357                 case SS_INQ_REFRESH:
3358                         AHD_SET_DV_STATE(ahd, targ,
3359                                          AHD_DV_STATE_INQ_SHORT_ASYNC);
3360                         break;
3361                 case SS_TUR:
3362                 case SS_RETRY:
3363                         AHD_SET_DV_STATE(ahd, targ, targ->dv_state);
3364                         if (ahd_cmd_get_transaction_status(cmd)
3365                          == CAM_REQUEUE_REQ) {
3366                                 targ->dv_state_retry--;
3367                         } else if (targ->dv_state_retry < 60) {
3368                                 if ((status & SSQ_DELAY) != 0)
3369                                         scsi_sleep(1 * HZ);
3370                         } else {
3371 #ifdef AHD_DEBUG
3372                                 if (ahd_debug & AHD_SHOW_DV) {
3373                                         ahd_print_devinfo(ahd, devinfo);
3374                                         printf("DV BUSY reties exhausted\n");
3375                                 }
3376 #endif
3377                                 AHD_SET_DV_STATE(ahd, targ, AHD_DV_STATE_EXIT);
3378                         }
3379                         break;
3380                 default:
3381                         AHD_SET_DV_STATE(ahd, targ, AHD_DV_STATE_EXIT);
3382                         break;
3383                 }
3384                 break;
3385
3386         default:
3387                 printf("%s: Invalid DV completion state %d\n", ahd_name(ahd),
3388                        targ->dv_state);
3389                 AHD_SET_DV_STATE(ahd, targ, AHD_DV_STATE_EXIT);
3390                 break;
3391         }
3392 }
3393
3394 static void
3395 ahd_linux_dv_fill_cmd(struct ahd_softc *ahd, struct scsi_cmnd *cmd,
3396                       struct ahd_devinfo *devinfo)
3397 {
3398         memset(cmd, 0, sizeof(struct scsi_cmnd));
3399         cmd->device = ahd->platform_data->dv_scsi_dev;
3400         cmd->scsi_done = ahd_linux_dv_complete;
3401 }
3402
3403 /*
3404  * Synthesize an inquiry command.  On the return trip, it'll be
3405  * sniffed and the device transfer settings set for us.
3406  */
3407 static void
3408 ahd_linux_dv_inq(struct ahd_softc *ahd, struct scsi_cmnd *cmd,
3409                  struct ahd_devinfo *devinfo, struct ahd_linux_target *targ,
3410                  u_int request_length)
3411 {
3412
3413 #ifdef AHD_DEBUG
3414         if (ahd_debug & AHD_SHOW_DV) {
3415                 ahd_print_devinfo(ahd, devinfo);
3416                 printf("Sending INQ\n");
3417         }
3418 #endif
3419         if (targ->inq_data == NULL)
3420                 targ->inq_data = malloc(AHD_LINUX_DV_INQ_LEN,
3421                                         M_DEVBUF, M_WAITOK);
3422         if (targ->dv_state > AHD_DV_STATE_INQ_ASYNC) {
3423                 if (targ->dv_buffer != NULL)
3424                         free(targ->dv_buffer, M_DEVBUF);
3425                 targ->dv_buffer = malloc(AHD_LINUX_DV_INQ_LEN,
3426                                          M_DEVBUF, M_WAITOK);
3427         }
3428
3429         ahd_linux_dv_fill_cmd(ahd, cmd, devinfo);
3430         cmd->sc_data_direction = SCSI_DATA_READ;
3431         cmd->cmd_len = 6;
3432         cmd->cmnd[0] = INQUIRY;
3433         cmd->cmnd[4] = request_length;
3434         cmd->request_bufflen = request_length;
3435         if (targ->dv_state > AHD_DV_STATE_INQ_ASYNC)
3436                 cmd->request_buffer = targ->dv_buffer;
3437         else
3438                 cmd->request_buffer = targ->inq_data;
3439         memset(cmd->request_buffer, 0, AHD_LINUX_DV_INQ_LEN);
3440 }
3441
3442 static void
3443 ahd_linux_dv_tur(struct ahd_softc *ahd, struct scsi_cmnd *cmd,
3444                  struct ahd_devinfo *devinfo)
3445 {
3446
3447 #ifdef AHD_DEBUG
3448         if (ahd_debug & AHD_SHOW_DV) {
3449                 ahd_print_devinfo(ahd, devinfo);
3450                 printf("Sending TUR\n");
3451         }
3452 #endif
3453         /* Do a TUR to clear out any non-fatal transitional state */
3454         ahd_linux_dv_fill_cmd(ahd, cmd, devinfo);
3455         cmd->sc_data_direction = SCSI_DATA_NONE;
3456         cmd->cmd_len = 6;
3457         cmd->cmnd[0] = TEST_UNIT_READY;
3458 }
3459
3460 #define AHD_REBD_LEN 4
3461
3462 static void
3463 ahd_linux_dv_rebd(struct ahd_softc *ahd, struct scsi_cmnd *cmd,
3464                  struct ahd_devinfo *devinfo, struct ahd_linux_target *targ)
3465 {
3466
3467 #ifdef AHD_DEBUG
3468         if (ahd_debug & AHD_SHOW_DV) {
3469                 ahd_print_devinfo(ahd, devinfo);
3470                 printf("Sending REBD\n");
3471         }
3472 #endif
3473         if (targ->dv_buffer != NULL)
3474                 free(targ->dv_buffer, M_DEVBUF);
3475         targ->dv_buffer = malloc(AHD_REBD_LEN, M_DEVBUF, M_WAITOK);
3476         ahd_linux_dv_fill_cmd(ahd, cmd, devinfo);
3477         cmd->sc_data_direction = SCSI_DATA_READ;
3478         cmd->cmd_len = 10;
3479         cmd->cmnd[0] = READ_BUFFER;
3480         cmd->cmnd[1] = 0x0b;
3481         scsi_ulto3b(AHD_REBD_LEN, &cmd->cmnd[6]);
3482         cmd->request_bufflen = AHD_REBD_LEN;
3483         cmd->underflow = cmd->request_bufflen;
3484         cmd->request_buffer = targ->dv_buffer;
3485 }
3486
3487 static void
3488 ahd_linux_dv_web(struct ahd_softc *ahd, struct scsi_cmnd *cmd,
3489                  struct ahd_devinfo *devinfo, struct ahd_linux_target *targ)
3490 {
3491
3492 #ifdef AHD_DEBUG
3493         if (ahd_debug & AHD_SHOW_DV) {
3494                 ahd_print_devinfo(ahd, devinfo);
3495                 printf("Sending WEB\n");
3496         }
3497 #endif
3498         ahd_linux_dv_fill_cmd(ahd, cmd, devinfo);
3499         cmd->sc_data_direction = SCSI_DATA_WRITE;
3500         cmd->cmd_len = 10;
3501         cmd->cmnd[0] = WRITE_BUFFER;
3502         cmd->cmnd[1] = 0x0a;
3503         scsi_ulto3b(targ->dv_echo_size, &cmd->cmnd[6]);
3504         cmd->request_bufflen = targ->dv_echo_size;
3505         cmd->underflow = cmd->request_bufflen;
3506         cmd->request_buffer = targ->dv_buffer;
3507 }
3508
3509 static void
3510 ahd_linux_dv_reb(struct ahd_softc *ahd, struct scsi_cmnd *cmd,
3511                  struct ahd_devinfo *devinfo, struct ahd_linux_target *targ)
3512 {
3513
3514 #ifdef AHD_DEBUG
3515         if (ahd_debug & AHD_SHOW_DV) {
3516                 ahd_print_devinfo(ahd, devinfo);
3517                 printf("Sending REB\n");
3518         }
3519 #endif
3520         ahd_linux_dv_fill_cmd(ahd, cmd, devinfo);
3521         cmd->sc_data_direction = SCSI_DATA_READ;
3522         cmd->cmd_len = 10;
3523         cmd->cmnd[0] = READ_BUFFER;
3524         cmd->cmnd[1] = 0x0a;
3525         scsi_ulto3b(targ->dv_echo_size, &cmd->cmnd[6]);
3526         cmd->request_bufflen = targ->dv_echo_size;
3527         cmd->underflow = cmd->request_bufflen;
3528         cmd->request_buffer = targ->dv_buffer1;
3529 }
3530
3531 static void
3532 ahd_linux_dv_su(struct ahd_softc *ahd, struct scsi_cmnd *cmd,
3533                 struct ahd_devinfo *devinfo,
3534                 struct ahd_linux_target *targ)
3535 {
3536         u_int le;
3537
3538         le = SID_IS_REMOVABLE(targ->inq_data) ? SSS_LOEJ : 0;
3539
3540 #ifdef AHD_DEBUG
3541         if (ahd_debug & AHD_SHOW_DV) {
3542                 ahd_print_devinfo(ahd, devinfo);
3543                 printf("Sending SU\n");
3544         }
3545 #endif
3546         ahd_linux_dv_fill_cmd(ahd, cmd, devinfo);
3547         cmd->sc_data_direction = SCSI_DATA_NONE;
3548         cmd->cmd_len = 6;
3549         cmd->cmnd[0] = START_STOP_UNIT;
3550         cmd->cmnd[4] = le | SSS_START;
3551 }
3552
3553 static __inline int
3554 ahd_linux_dv_fallback(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
3555 {
3556         u_long s;
3557         int retval;
3558
3559         ahd_lock(ahd, &s);
3560         retval = ahd_linux_fallback(ahd, devinfo);
3561         ahd_unlock(ahd, &s);
3562
3563         return (retval);
3564 }
3565
3566 static int
3567 ahd_linux_fallback(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
3568 {
3569         struct  ahd_linux_target *targ;
3570         struct  ahd_initiator_tinfo *tinfo;
3571         struct  ahd_transinfo *goal;
3572         struct  ahd_tmode_tstate *tstate;
3573         u_int   width;
3574         u_int   period;
3575         u_int   offset;
3576         u_int   ppr_options;
3577         u_int   cur_speed;
3578         u_int   wide_speed;
3579         u_int   narrow_speed;
3580         u_int   fallback_speed;
3581
3582 #ifdef AHD_DEBUG
3583         if (ahd_debug & AHD_SHOW_DV) {
3584                 ahd_print_devinfo(ahd, devinfo);
3585                 printf("Trying to fallback\n");
3586         }
3587 #endif
3588         targ = ahd->platform_data->targets[devinfo->target_offset];
3589         tinfo = ahd_fetch_transinfo(ahd, devinfo->channel,
3590                                     devinfo->our_scsiid,
3591                                     devinfo->target, &tstate);
3592         goal = &tinfo->goal;
3593         width = goal->width;
3594         period = goal->period;
3595         offset = goal->offset;
3596         ppr_options = goal->ppr_options;
3597         if (offset == 0)
3598                 period = AHD_ASYNC_XFER_PERIOD;
3599         if (targ->dv_next_narrow_period == 0)
3600                 targ->dv_next_narrow_period = MAX(period, AHD_SYNCRATE_ULTRA2);
3601         if (targ->dv_next_wide_period == 0)
3602                 targ->dv_next_wide_period = period;
3603         if (targ->dv_max_width == 0)
3604                 targ->dv_max_width = width;
3605         if (targ->dv_max_ppr_options == 0)
3606                 targ->dv_max_ppr_options = ppr_options;
3607         if (targ->dv_last_ppr_options == 0)
3608                 targ->dv_last_ppr_options = ppr_options;
3609
3610         cur_speed = aic_calc_speed(width, period, offset, AHD_SYNCRATE_MIN);
3611         wide_speed = aic_calc_speed(MSG_EXT_WDTR_BUS_16_BIT,
3612                                           targ->dv_next_wide_period,
3613                                           MAX_OFFSET, AHD_SYNCRATE_MIN);
3614         narrow_speed = aic_calc_speed(MSG_EXT_WDTR_BUS_8_BIT,
3615                                             targ->dv_next_narrow_period,
3616                                             MAX_OFFSET, AHD_SYNCRATE_MIN);
3617         fallback_speed = aic_calc_speed(width, period+1, offset,
3618                                               AHD_SYNCRATE_MIN);
3619 #ifdef AHD_DEBUG
3620         if (ahd_debug & AHD_SHOW_DV) {
3621                 printf("cur_speed= %d, wide_speed= %d, narrow_speed= %d, "
3622                        "fallback_speed= %d\n", cur_speed, wide_speed,
3623                        narrow_speed, fallback_speed);
3624         }
3625 #endif
3626
3627         if (cur_speed > 160000) {
3628                 /*
3629                  * Paced/DT/IU_REQ only transfer speeds.  All we
3630                  * can do is fallback in terms of syncrate.
3631                  */
3632                 period++;
3633         } else if (cur_speed > 80000) {
3634                 if ((ppr_options & MSG_EXT_PPR_IU_REQ) != 0) {
3635                         /*
3636                          * Try without IU_REQ as it may be confusing
3637                          * an expander.
3638                          */
3639                         ppr_options &= ~MSG_EXT_PPR_IU_REQ;
3640                 } else {
3641                         /*
3642                          * Paced/DT only transfer speeds.  All we
3643                          * can do is fallback in terms of syncrate.
3644                          */
3645                         period++;
3646                         ppr_options = targ->dv_max_ppr_options;
3647                 }
3648         } else if (cur_speed > 3300) {
3649
3650                 /*
3651                  * In this range we the following
3652                  * options ordered from highest to
3653                  * lowest desireability:
3654                  *
3655                  * o Wide/DT
3656                  * o Wide/non-DT
3657                  * o Narrow at a potentally higher sync rate.
3658                  *
3659                  * All modes are tested with and without IU_REQ
3660                  * set since using IUs may confuse an expander.
3661                  */
3662                 if ((ppr_options & MSG_EXT_PPR_IU_REQ) != 0) {
3663
3664                         ppr_options &= ~MSG_EXT_PPR_IU_REQ;
3665                 } else if ((ppr_options & MSG_EXT_PPR_DT_REQ) != 0) {
3666                         /*
3667                          * Try going non-DT.
3668                          */
3669                         ppr_options = targ->dv_max_ppr_options;
3670                         ppr_options &= ~MSG_EXT_PPR_DT_REQ;
3671                 } else if (targ->dv_last_ppr_options != 0) {
3672                         /*
3673                          * Try without QAS or any other PPR options.
3674                          * We may need a non-PPR message to work with
3675                          * an expander.  We look at the "last PPR options"
3676                          * so we will perform this fallback even if the
3677                          * target responded to our PPR negotiation with
3678                          * no option bits set.
3679                          */
3680                         ppr_options = 0;
3681                 } else if (width == MSG_EXT_WDTR_BUS_16_BIT) {
3682                         /*
3683                          * If the next narrow speed is greater than
3684                          * the next wide speed, fallback to narrow.
3685                          * Otherwise fallback to the next DT/Wide setting.
3686                          * The narrow async speed will always be smaller
3687                          * than the wide async speed, so handle this case
3688                          * specifically.
3689                          */
3690                         ppr_options = targ->dv_max_ppr_options;
3691                         if (narrow_speed > fallback_speed
3692                          || period >= AHD_ASYNC_XFER_PERIOD) {
3693                                 targ->dv_next_wide_period = period+1;
3694                                 width = MSG_EXT_WDTR_BUS_8_BIT;
3695                                 period = targ->dv_next_narrow_period;
3696                         } else {
3697                                 period++;
3698                         }
3699                 } else if ((ahd->features & AHD_WIDE) != 0
3700                         && targ->dv_max_width != 0
3701                         && wide_speed >= fallback_speed
3702                         && (targ->dv_next_wide_period <= AHD_ASYNC_XFER_PERIOD
3703                          || period >= AHD_ASYNC_XFER_PERIOD)) {
3704
3705                         /*
3706                          * We are narrow.  Try falling back
3707                          * to the next wide speed with 
3708                          * all supported ppr options set.
3709                          */
3710                         targ->dv_next_narrow_period = period+1;
3711                         width = MSG_EXT_WDTR_BUS_16_BIT;
3712                         period = targ->dv_next_wide_period;
3713                         ppr_options = targ->dv_max_ppr_options;
3714                 } else {
3715                         /* Only narrow fallback is allowed. */
3716                         period++;
3717                         ppr_options = targ->dv_max_ppr_options;
3718                 }
3719         } else {
3720                 return (-1);
3721         }
3722         offset = MAX_OFFSET;
3723         ahd_find_syncrate(ahd, &period, &ppr_options, AHD_SYNCRATE_PACED);
3724         ahd_set_width(ahd, devinfo, width, AHD_TRANS_GOAL, FALSE);
3725         if (period == 0) {
3726                 period = 0;
3727                 offset = 0;
3728                 ppr_options = 0;
3729                 if (width == MSG_EXT_WDTR_BUS_8_BIT)
3730                         targ->dv_next_narrow_period = AHD_ASYNC_XFER_PERIOD;
3731                 else
3732                         targ->dv_next_wide_period = AHD_ASYNC_XFER_PERIOD;
3733         }
3734         ahd_set_syncrate(ahd, devinfo, period, offset,
3735                          ppr_options, AHD_TRANS_GOAL, FALSE);
3736         targ->dv_last_ppr_options = ppr_options;
3737         return (0);
3738 }
3739
3740 static void
3741 ahd_linux_dv_timeout(struct scsi_cmnd *cmd)
3742 {
3743         struct  ahd_softc *ahd;
3744         struct  scb *scb;
3745         u_long  flags;
3746
3747         ahd = *((struct ahd_softc **)cmd->device->host->hostdata);
3748         ahd_lock(ahd, &flags);
3749
3750 #ifdef AHD_DEBUG
3751         if (ahd_debug & AHD_SHOW_DV) {
3752                 printf("%s: Timeout while doing DV command %x.\n",
3753                        ahd_name(ahd), cmd->cmnd[0]);
3754                 ahd_dump_card_state(ahd);
3755         }
3756 #endif
3757         
3758         /*
3759          * Guard against "done race".  No action is
3760          * required if we just completed.
3761          */
3762         if ((scb = (struct scb *)cmd->host_scribble) == NULL) {
3763                 ahd_unlock(ahd, &flags);
3764                 return;
3765         }
3766
3767         /*
3768          * Command has not completed.  Mark this
3769          * SCB as having failing status prior to
3770          * resetting the bus, so we get the correct
3771          * error code.
3772          */
3773         if ((scb->flags & SCB_SENSE) != 0)
3774                 ahd_set_transaction_status(scb, CAM_AUTOSENSE_FAIL);
3775         else
3776                 ahd_set_transaction_status(scb, CAM_CMD_TIMEOUT);
3777         ahd_reset_channel(ahd, cmd->device->channel + 'A', /*initiate*/TRUE);
3778
3779         /*
3780          * Add a minimal bus settle delay for devices that are slow to
3781          * respond after bus resets.
3782          */
3783         ahd_freeze_simq(ahd);
3784         init_timer(&ahd->platform_data->reset_timer);
3785         ahd->platform_data->reset_timer.data = (u_long)ahd;
3786         ahd->platform_data->reset_timer.expires = jiffies + HZ / 2;
3787         ahd->platform_data->reset_timer.function =
3788             (ahd_linux_callback_t *)ahd_release_simq;
3789         add_timer(&ahd->platform_data->reset_timer);
3790         if (ahd_linux_next_device_to_run(ahd) != NULL)
3791                 ahd_schedule_runq(ahd);
3792         ahd_linux_run_complete_queue(ahd);
3793         ahd_unlock(ahd, &flags);
3794 }
3795
3796 static void
3797 ahd_linux_dv_complete(struct scsi_cmnd *cmd)
3798 {
3799         struct ahd_softc *ahd;
3800
3801         ahd = *((struct ahd_softc **)cmd->device->host->hostdata);
3802
3803         /* Delete the DV timer before it goes off! */
3804         scsi_delete_timer(cmd);
3805
3806 #ifdef AHD_DEBUG
3807         if (ahd_debug & AHD_SHOW_DV)
3808                 printf("%s:%c:%d: Command completed, status= 0x%x\n",
3809                        ahd_name(ahd), cmd->device->channel, cmd->device->id,
3810                        cmd->result);
3811 #endif
3812
3813         /* Wake up the state machine */
3814         up(&ahd->platform_data->dv_cmd_sem);
3815 }
3816
3817 static void
3818 ahd_linux_generate_dv_pattern(struct ahd_linux_target *targ)
3819 {
3820         uint16_t b;
3821         u_int    i;
3822         u_int    j;
3823
3824         if (targ->dv_buffer != NULL)
3825                 free(targ->dv_buffer, M_DEVBUF);
3826         targ->dv_buffer = malloc(targ->dv_echo_size, M_DEVBUF, M_WAITOK);
3827         if (targ->dv_buffer1 != NULL)
3828                 free(targ->dv_buffer1, M_DEVBUF);
3829         targ->dv_buffer1 = malloc(targ->dv_echo_size, M_DEVBUF, M_WAITOK);
3830
3831         i = 0;
3832
3833         b = 0x0001;
3834         for (j = 0 ; i < targ->dv_echo_size; j++) {
3835                 if (j < 32) {
3836                         /*
3837                          * 32bytes of sequential numbers.
3838                          */
3839                         targ->dv_buffer[i++] = j & 0xff;
3840                 } else if (j < 48) {
3841                         /*
3842                          * 32bytes of repeating 0x0000, 0xffff.
3843                          */
3844                         targ->dv_buffer[i++] = (j & 0x02) ? 0xff : 0x00;
3845                 } else if (j < 64) {
3846                         /*
3847                          * 32bytes of repeating 0x5555, 0xaaaa.
3848                          */
3849                         targ->dv_buffer[i++] = (j & 0x02) ? 0xaa : 0x55;
3850                 } else {
3851                         /*
3852                          * Remaining buffer is filled with a repeating
3853                          * patter of:
3854                          *
3855                          *       0xffff
3856                          *      ~0x0001 << shifted once in each loop.
3857                          */
3858                         if (j & 0x02) {
3859                                 if (j & 0x01) {
3860                                         targ->dv_buffer[i++] = ~(b >> 8) & 0xff;
3861                                         b <<= 1;
3862                                         if (b == 0x0000)
3863                                                 b = 0x0001;
3864                                 } else {
3865                                         targ->dv_buffer[i++] = (~b & 0xff);
3866                                 }
3867                         } else {
3868                                 targ->dv_buffer[i++] = 0xff;
3869                         }
3870                 }
3871         }
3872 }
3873
3874 static u_int
3875 ahd_linux_user_tagdepth(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
3876 {
3877         static int warned_user;
3878         u_int tags;
3879
3880         tags = 0;
3881         if ((ahd->user_discenable & devinfo->target_mask) != 0) {
3882                 if (ahd->unit >= NUM_ELEMENTS(aic79xx_tag_info)) {
3883
3884                         if (warned_user == 0) {
3885                                 printf(KERN_WARNING
3886 "aic79xx: WARNING: Insufficient tag_info instances\n"
3887 "aic79xx: for installed controllers.  Using defaults\n"
3888 "aic79xx: Please update the aic79xx_tag_info array in\n"
3889 "aic79xx: the aic79xx_osm.c source file.\n");
3890                                 warned_user++;
3891                         }
3892                         tags = AHD_MAX_QUEUE;
3893                 } else {
3894                         adapter_tag_info_t *tag_info;
3895
3896                         tag_info = &aic79xx_tag_info[ahd->unit];
3897                         tags = tag_info->tag_commands[devinfo->target_offset];
3898                         if (tags > AHD_MAX_QUEUE)
3899                                 tags = AHD_MAX_QUEUE;
3900                 }
3901         }
3902         return (tags);
3903 }
3904
3905 static u_int
3906 ahd_linux_user_dv_setting(struct ahd_softc *ahd)
3907 {
3908         static int warned_user;
3909         int dv;
3910
3911         if (ahd->unit >= NUM_ELEMENTS(aic79xx_dv_settings)) {
3912
3913                 if (warned_user == 0) {
3914                         printf(KERN_WARNING
3915 "aic79xx: WARNING: Insufficient dv settings instances\n"
3916 "aic79xx: for installed controllers. Using defaults\n"
3917 "aic79xx: Please update the aic79xx_dv_settings array in"
3918 "aic79xx: the aic79xx_osm.c source file.\n");
3919                         warned_user++;
3920                 }
3921                 dv = -1;
3922         } else {
3923
3924                 dv = aic79xx_dv_settings[ahd->unit];
3925         }
3926
3927         if (dv < 0) {
3928                 /*
3929                  * Apply the default.
3930                  */
3931                 dv = 1;
3932                 if (ahd->seep_config != 0)
3933                         dv = (ahd->seep_config->bios_control & CFENABLEDV);
3934         }
3935         return (dv);
3936 }
3937
3938 static void
3939 ahd_linux_setup_user_rd_strm_settings(struct ahd_softc *ahd)
3940 {
3941         static  int warned_user;
3942         u_int   rd_strm_mask;
3943         u_int   target_id;
3944
3945         /*
3946          * If we have specific read streaming info for this controller,
3947          * apply it.  Otherwise use the defaults.
3948          */
3949          if (ahd->unit >= NUM_ELEMENTS(aic79xx_rd_strm_info)) {
3950
3951                 if (warned_user == 0) {
3952
3953                         printf(KERN_WARNING
3954 "aic79xx: WARNING: Insufficient rd_strm instances\n"
3955 "aic79xx: for installed controllers. Using defaults\n"
3956 "aic79xx: Please update the aic79xx_rd_strm_info array\n"
3957 "aic79xx: in the aic79xx_osm.c source file.\n");
3958                         warned_user++;
3959                 }
3960                 rd_strm_mask = AIC79XX_CONFIGED_RD_STRM;
3961         } else {
3962
3963                 rd_strm_mask = aic79xx_rd_strm_info[ahd->unit];
3964         }
3965         for (target_id = 0; target_id < 16; target_id++) {
3966                 struct ahd_devinfo devinfo;
3967                 struct ahd_initiator_tinfo *tinfo;
3968                 struct ahd_tmode_tstate *tstate;
3969
3970                 tinfo = ahd_fetch_transinfo(ahd, 'A', ahd->our_id,
3971                                             target_id, &tstate);
3972                 ahd_compile_devinfo(&devinfo, ahd->our_id, target_id,
3973                                     CAM_LUN_WILDCARD, 'A', ROLE_INITIATOR);
3974                 tinfo->user.ppr_options &= ~MSG_EXT_PPR_RD_STRM;
3975                 if ((rd_strm_mask & devinfo.target_mask) != 0)
3976                         tinfo->user.ppr_options |= MSG_EXT_PPR_RD_STRM;
3977         }
3978 }
3979
3980 /*
3981  * Determines the queue depth for a given device.
3982  */
3983 static void
3984 ahd_linux_device_queue_depth(struct ahd_softc *ahd,
3985                              struct ahd_linux_device *dev)
3986 {
3987         struct  ahd_devinfo devinfo;
3988         u_int   tags;
3989
3990         ahd_compile_devinfo(&devinfo,
3991                             ahd->our_id,
3992                             dev->target->target, dev->lun,
3993                             dev->target->channel == 0 ? 'A' : 'B',
3994                             ROLE_INITIATOR);
3995         tags = ahd_linux_user_tagdepth(ahd, &devinfo);
3996         if (tags != 0
3997          && dev->scsi_device != NULL
3998          && dev->scsi_device->tagged_supported != 0) {
3999
4000                 ahd_set_tags(ahd, &devinfo, AHD_QUEUE_TAGGED);
4001                 ahd_print_devinfo(ahd, &devinfo);
4002                 printf("Tagged Queuing enabled.  Depth %d\n", tags);
4003         } else {
4004                 ahd_set_tags(ahd, &devinfo, AHD_QUEUE_NONE);
4005         }
4006 }
4007
4008 static void
4009 ahd_linux_run_device_queue(struct ahd_softc *ahd, struct ahd_linux_device *dev)
4010 {
4011         struct   ahd_cmd *acmd;
4012         struct   scsi_cmnd *cmd;
4013         struct   scb *scb;
4014         struct   hardware_scb *hscb;
4015         struct   ahd_initiator_tinfo *tinfo;
4016         struct   ahd_tmode_tstate *tstate;
4017         u_int    col_idx;
4018         uint16_t mask;
4019
4020         if ((dev->flags & AHD_DEV_ON_RUN_LIST) != 0)
4021                 panic("running device on run list");
4022
4023         while ((acmd = TAILQ_FIRST(&dev->busyq)) != NULL
4024             && dev->openings > 0 && dev->qfrozen == 0) {
4025
4026                 /*
4027                  * Schedule us to run later.  The only reason we are not
4028                  * running is because the whole controller Q is frozen.
4029                  */
4030                 if (ahd->platform_data->qfrozen != 0
4031                  && AHD_DV_SIMQ_FROZEN(ahd) == 0) {
4032
4033                         TAILQ_INSERT_TAIL(&ahd->platform_data->device_runq,
4034                                           dev, links);
4035                         dev->flags |= AHD_DEV_ON_RUN_LIST;
4036                         return;
4037                 }
4038
4039                 cmd = &acmd_scsi_cmd(acmd);
4040
4041                 /*
4042                  * Get an scb to use.
4043                  */
4044                 tinfo = ahd_fetch_transinfo(ahd, 'A', ahd->our_id,
4045                                             cmd->device->id, &tstate);
4046                 if ((dev->flags & (AHD_DEV_Q_TAGGED|AHD_DEV_Q_BASIC)) == 0
4047                  || (tinfo->curr.ppr_options & MSG_EXT_PPR_IU_REQ) != 0) {
4048                         col_idx = AHD_NEVER_COL_IDX;
4049                 } else {
4050                         col_idx = AHD_BUILD_COL_IDX(cmd->device->id,
4051                                                     cmd->device->lun);
4052                 }
4053                 if ((scb = ahd_get_scb(ahd, col_idx)) == NULL) {
4054                         TAILQ_INSERT_TAIL(&ahd->platform_data->device_runq,
4055                                          dev, links);
4056                         dev->flags |= AHD_DEV_ON_RUN_LIST;
4057                         ahd->flags |= AHD_RESOURCE_SHORTAGE;
4058                         return;
4059                 }
4060                 TAILQ_REMOVE(&dev->busyq, acmd, acmd_links.tqe);
4061                 scb->io_ctx = cmd;
4062                 scb->platform_data->dev = dev;
4063                 hscb = scb->hscb;
4064                 cmd->host_scribble = (char *)scb;
4065
4066                 /*
4067                  * Fill out basics of the HSCB.
4068                  */
4069                 hscb->control = 0;
4070                 hscb->scsiid = BUILD_SCSIID(ahd, cmd);
4071                 hscb->lun = cmd->device->lun;
4072                 scb->hscb->task_management = 0;
4073                 mask = SCB_GET_TARGET_MASK(ahd, scb);
4074
4075                 if ((ahd->user_discenable & mask) != 0)
4076                         hscb->control |= DISCENB;
4077
4078                 if (AHD_DV_CMD(cmd) != 0)
4079                         scb->flags |= SCB_SILENT;
4080
4081                 if ((tinfo->curr.ppr_options & MSG_EXT_PPR_IU_REQ) != 0)
4082                         scb->flags |= SCB_PACKETIZED;
4083
4084                 if ((tstate->auto_negotiate & mask) != 0) {
4085                         scb->flags |= SCB_AUTO_NEGOTIATE;
4086                         scb->hscb->control |= MK_MESSAGE;
4087                 }
4088
4089                 if ((dev->flags & (AHD_DEV_Q_TAGGED|AHD_DEV_Q_BASIC)) != 0) {
4090 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
4091                         int     msg_bytes;
4092                         uint8_t tag_msgs[2];
4093
4094                         msg_bytes = scsi_populate_tag_msg(cmd, tag_msgs);
4095                         if (msg_bytes && tag_msgs[0] != MSG_SIMPLE_TASK) {
4096                                 hscb->control |= tag_msgs[0];
4097                                 if (tag_msgs[0] == MSG_ORDERED_TASK)
4098                                         dev->commands_since_idle_or_otag = 0;
4099                         } else
4100 #endif
4101                         if (dev->commands_since_idle_or_otag == AHD_OTAG_THRESH
4102                          && (dev->flags & AHD_DEV_Q_TAGGED) != 0) {
4103                                 hscb->control |= MSG_ORDERED_TASK;
4104                                 dev->commands_since_idle_or_otag = 0;
4105                         } else {
4106                                 hscb->control |= MSG_SIMPLE_TASK;
4107                         }
4108                 }
4109
4110                 hscb->cdb_len = cmd->cmd_len;
4111                 memcpy(hscb->shared_data.idata.cdb, cmd->cmnd, hscb->cdb_len);
4112
4113                 scb->sg_count = 0;
4114                 ahd_set_residual(scb, 0);
4115                 ahd_set_sense_residual(scb, 0);
4116                 if (cmd->use_sg != 0) {
4117                         void    *sg;
4118                         struct   scatterlist *cur_seg;
4119                         u_int    nseg;
4120                         int      dir;
4121
4122                         cur_seg = (struct scatterlist *)cmd->request_buffer;
4123                         dir = scsi_to_pci_dma_dir(cmd->sc_data_direction);
4124                         nseg = pci_map_sg(ahd->dev_softc, cur_seg,
4125                                           cmd->use_sg, dir);
4126                         scb->platform_data->xfer_len = 0;
4127                         for (sg = scb->sg_list; nseg > 0; nseg--, cur_seg++) {
4128                                 bus_addr_t addr;
4129                                 bus_size_t len;
4130
4131                                 addr = sg_dma_address(cur_seg);
4132                                 len = sg_dma_len(cur_seg);
4133                                 scb->platform_data->xfer_len += len;
4134                                 sg = ahd_sg_setup(ahd, scb, sg, addr, len,
4135                                                   /*last*/nseg == 1);
4136                         }
4137                 } else if (cmd->request_bufflen != 0) {
4138                         void *sg;
4139                         bus_addr_t addr;
4140                         int dir;
4141
4142                         sg = scb->sg_list;
4143                         dir = scsi_to_pci_dma_dir(cmd->sc_data_direction);
4144                         addr = pci_map_single(ahd->dev_softc,
4145                                               cmd->request_buffer,
4146                                               cmd->request_bufflen, dir);
4147                         scb->platform_data->xfer_len = cmd->request_bufflen;
4148                         scb->platform_data->buf_busaddr = addr;
4149                         sg = ahd_sg_setup(ahd, scb, sg, addr,
4150                                           cmd->request_bufflen, /*last*/TRUE);
4151                 }
4152
4153                 LIST_INSERT_HEAD(&ahd->pending_scbs, scb, pending_links);
4154                 dev->openings--;
4155                 dev->active++;
4156                 dev->commands_issued++;
4157
4158                 /* Update the error counting bucket and dump if needed */
4159                 if (dev->target->cmds_since_error) {
4160                         dev->target->cmds_since_error++;
4161                         if (dev->target->cmds_since_error >
4162                             AHD_LINUX_ERR_THRESH)
4163                                 dev->target->cmds_since_error = 0;
4164                 }
4165
4166                 if ((dev->flags & AHD_DEV_PERIODIC_OTAG) != 0)
4167                         dev->commands_since_idle_or_otag++;
4168                 scb->flags |= SCB_ACTIVE;
4169                 ahd_queue_scb(ahd, scb);
4170         }
4171 }
4172
4173 /*
4174  * SCSI controller interrupt handler.
4175  */
4176 irqreturn_t
4177 ahd_linux_isr(int irq, void *dev_id, struct pt_regs * regs)
4178 {
4179         struct  ahd_softc *ahd;
4180         u_long  flags;
4181         int     ours;
4182
4183         ahd = (struct ahd_softc *) dev_id;
4184         ahd_lock(ahd, &flags); 
4185         ours = ahd_intr(ahd);
4186         if (ahd_linux_next_device_to_run(ahd) != NULL)
4187                 ahd_schedule_runq(ahd);
4188         ahd_linux_run_complete_queue(ahd);
4189         ahd_unlock(ahd, &flags);
4190         return IRQ_RETVAL(ours);
4191 }
4192
4193 void
4194 ahd_platform_flushwork(struct ahd_softc *ahd)
4195 {
4196
4197         while (ahd_linux_run_complete_queue(ahd) != NULL)
4198                 ;
4199 }
4200
4201 static struct ahd_linux_target*
4202 ahd_linux_alloc_target(struct ahd_softc *ahd, u_int channel, u_int target)
4203 {
4204         struct ahd_linux_target *targ;
4205
4206         targ = malloc(sizeof(*targ), M_DEVBUF, M_NOWAIT);
4207         if (targ == NULL)
4208                 return (NULL);
4209         memset(targ, 0, sizeof(*targ));
4210         targ->channel = channel;
4211         targ->target = target;
4212         targ->ahd = ahd;
4213         targ->flags = AHD_DV_REQUIRED;
4214         ahd->platform_data->targets[target] = targ;
4215         return (targ);
4216 }
4217
4218 static void
4219 ahd_linux_free_target(struct ahd_softc *ahd, struct ahd_linux_target *targ)
4220 {
4221         struct ahd_devinfo devinfo;
4222         struct ahd_initiator_tinfo *tinfo;
4223         struct ahd_tmode_tstate *tstate;
4224         u_int our_id;
4225         u_int target_offset;
4226         char channel;
4227
4228         /*
4229          * Force a negotiation to async/narrow on any
4230          * future command to this device unless a bus
4231          * reset occurs between now and that command.
4232          */
4233         channel = 'A' + targ->channel;
4234         our_id = ahd->our_id;
4235         target_offset = targ->target;
4236         tinfo = ahd_fetch_transinfo(ahd, channel, our_id,
4237                                     targ->target, &tstate);
4238         ahd_compile_devinfo(&devinfo, our_id, targ->target, CAM_LUN_WILDCARD,
4239                             channel, ROLE_INITIATOR);
4240         ahd_set_syncrate(ahd, &devinfo, 0, 0, 0,
4241                          AHD_TRANS_GOAL, /*paused*/FALSE);
4242         ahd_set_width(ahd, &devinfo, MSG_EXT_WDTR_BUS_8_BIT,
4243                       AHD_TRANS_GOAL, /*paused*/FALSE);
4244         ahd_update_neg_request(ahd, &devinfo, tstate, tinfo, AHD_NEG_ALWAYS);
4245         ahd->platform_data->targets[target_offset] = NULL;
4246         if (targ->inq_data != NULL)
4247                 free(targ->inq_data, M_DEVBUF);
4248         if (targ->dv_buffer != NULL)
4249                 free(targ->dv_buffer, M_DEVBUF);
4250         if (targ->dv_buffer1 != NULL)
4251                 free(targ->dv_buffer1, M_DEVBUF);
4252         free(targ, M_DEVBUF);
4253 }
4254
4255 static struct ahd_linux_device*
4256 ahd_linux_alloc_device(struct ahd_softc *ahd,
4257                  struct ahd_linux_target *targ, u_int lun)
4258 {
4259         struct ahd_linux_device *dev;
4260
4261         dev = malloc(sizeof(*dev), M_DEVBUG, M_NOWAIT);
4262         if (dev == NULL)
4263                 return (NULL);
4264         memset(dev, 0, sizeof(*dev));
4265         init_timer(&dev->timer);
4266         TAILQ_INIT(&dev->busyq);
4267         dev->flags = AHD_DEV_UNCONFIGURED;
4268         dev->lun = lun;
4269         dev->target = targ;
4270
4271         /*
4272          * We start out life using untagged
4273          * transactions of which we allow one.
4274          */
4275         dev->openings = 1;
4276
4277         /*
4278          * Set maxtags to 0.  This will be changed if we
4279          * later determine that we are dealing with
4280          * a tagged queuing capable device.
4281          */
4282         dev->maxtags = 0;
4283         
4284         targ->refcount++;
4285         targ->devices[lun] = dev;
4286         return (dev);
4287 }
4288
4289 static void
4290 ahd_linux_free_device(struct ahd_softc *ahd, struct ahd_linux_device *dev)
4291 {
4292         struct ahd_linux_target *targ;
4293
4294         del_timer(&dev->timer);
4295         targ = dev->target;
4296         targ->devices[dev->lun] = NULL;
4297         free(dev, M_DEVBUF);
4298         targ->refcount--;
4299         if (targ->refcount == 0
4300          && (targ->flags & AHD_DV_REQUIRED) == 0)
4301                 ahd_linux_free_target(ahd, targ);
4302 }
4303
4304 void
4305 ahd_send_async(struct ahd_softc *ahd, char channel,
4306                u_int target, u_int lun, ac_code code, void *arg)
4307 {
4308         switch (code) {
4309         case AC_TRANSFER_NEG:
4310         {
4311                 char    buf[80];
4312                 struct  ahd_linux_target *targ;
4313                 struct  info_str info;
4314                 struct  ahd_initiator_tinfo *tinfo;
4315                 struct  ahd_tmode_tstate *tstate;
4316
4317                 info.buffer = buf;
4318                 info.length = sizeof(buf);
4319                 info.offset = 0;
4320                 info.pos = 0;
4321                 tinfo = ahd_fetch_transinfo(ahd, channel, ahd->our_id,
4322                                             target, &tstate);
4323
4324                 /*
4325                  * Don't bother reporting results while
4326                  * negotiations are still pending.
4327                  */
4328                 if (tinfo->curr.period != tinfo->goal.period
4329                  || tinfo->curr.width != tinfo->goal.width
4330                  || tinfo->curr.offset != tinfo->goal.offset
4331                  || tinfo->curr.ppr_options != tinfo->goal.ppr_options)
4332                         if (bootverbose == 0)
4333                                 break;
4334
4335                 /*
4336                  * Don't bother reporting results that
4337                  * are identical to those last reported.
4338                  */
4339                 targ = ahd->platform_data->targets[target];
4340                 if (targ == NULL)
4341                         break;
4342                 if (tinfo->curr.period == targ->last_tinfo.period
4343                  && tinfo->curr.width == targ->last_tinfo.width
4344                  && tinfo->curr.offset == targ->last_tinfo.offset
4345                  && tinfo->curr.ppr_options == targ->last_tinfo.ppr_options)
4346                         if (bootverbose == 0)
4347                                 break;
4348
4349                 targ->last_tinfo.period = tinfo->curr.period;
4350                 targ->last_tinfo.width = tinfo->curr.width;
4351                 targ->last_tinfo.offset = tinfo->curr.offset;
4352                 targ->last_tinfo.ppr_options = tinfo->curr.ppr_options;
4353
4354                 printf("(%s:%c:", ahd_name(ahd), channel);
4355                 if (target == CAM_TARGET_WILDCARD)
4356                         printf("*): ");
4357                 else
4358                         printf("%d): ", target);
4359                 ahd_format_transinfo(&info, &tinfo->curr);
4360                 if (info.pos < info.length)
4361                         *info.buffer = '\0';
4362                 else
4363                         buf[info.length - 1] = '\0';
4364                 printf("%s", buf);
4365                 break;
4366         }
4367         case AC_SENT_BDR:
4368         {
4369 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
4370                 WARN_ON(lun != CAM_LUN_WILDCARD);
4371                 scsi_report_device_reset(ahd->platform_data->host,
4372                                          channel - 'A', target);
4373 #elif LINUX_VERSION_CODE >= KERNEL_VERSION(2,3,0)
4374                 Scsi_Device *scsi_dev;
4375
4376                 /*
4377                  * Find the SCSI device associated with this
4378                  * request and indicate that a UA is expected.
4379                  */
4380                 for (scsi_dev = ahd->platform_data->host->host_queue;
4381                      scsi_dev != NULL; scsi_dev = scsi_dev->next) {
4382                         if (channel - 'A' == scsi_dev->channel
4383                          && target == scsi_dev->id
4384                          && (lun == CAM_LUN_WILDCARD
4385                           || lun == scsi_dev->lun)) {
4386                                 scsi_dev->was_reset = 1;
4387                                 scsi_dev->expecting_cc_ua = 1;
4388                         }
4389                 }
4390 #endif
4391                 break;
4392         }
4393         case AC_BUS_RESET:
4394 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,3,0)
4395                 if (ahd->platform_data->host != NULL) {
4396                         scsi_report_bus_reset(ahd->platform_data->host,
4397                                               channel - 'A');
4398                 }
4399 #endif
4400                 break;
4401         default:
4402                 panic("ahd_send_async: Unexpected async event");
4403         }
4404 }
4405
4406 /*
4407  * Calls the higher level scsi done function and frees the scb.
4408  */
4409 void
4410 ahd_done(struct ahd_softc *ahd, struct scb *scb)
4411 {
4412         Scsi_Cmnd *cmd;
4413         struct    ahd_linux_device *dev;
4414
4415         if ((scb->flags & SCB_ACTIVE) == 0) {
4416                 printf("SCB %d done'd twice\n", SCB_GET_TAG(scb));
4417                 ahd_dump_card_state(ahd);
4418                 panic("Stopping for safety");
4419         }
4420         LIST_REMOVE(scb, pending_links);
4421         cmd = scb->io_ctx;
4422         dev = scb->platform_data->dev;
4423         dev->active--;
4424         dev->openings++;
4425         if ((cmd->result & (CAM_DEV_QFRZN << 16)) != 0) {
4426                 cmd->result &= ~(CAM_DEV_QFRZN << 16);
4427                 dev->qfrozen--;
4428         }
4429         ahd_linux_unmap_scb(ahd, scb);
4430
4431         /*
4432          * Guard against stale sense data.
4433          * The Linux mid-layer assumes that sense
4434          * was retrieved anytime the first byte of
4435          * the sense buffer looks "sane".
4436          */
4437         cmd->sense_buffer[0] = 0;
4438         if (ahd_get_transaction_status(scb) == CAM_REQ_INPROG) {
4439                 uint32_t amount_xferred;
4440
4441                 amount_xferred =
4442                     ahd_get_transfer_length(scb) - ahd_get_residual(scb);
4443                 if ((scb->flags & SCB_TRANSMISSION_ERROR) != 0) {
4444 #ifdef AHD_DEBUG
4445                         if ((ahd_debug & AHD_SHOW_MISC) != 0) {
4446                                 ahd_print_path(ahd, scb);
4447                                 printf("Set CAM_UNCOR_PARITY\n");
4448                         }
4449 #endif
4450                         ahd_set_transaction_status(scb, CAM_UNCOR_PARITY);
4451 #ifdef AHD_REPORT_UNDERFLOWS
4452                 /*
4453                  * This code is disabled by default as some
4454                  * clients of the SCSI system do not properly
4455                  * initialize the underflow parameter.  This
4456                  * results in spurious termination of commands
4457                  * that complete as expected (e.g. underflow is
4458                  * allowed as command can return variable amounts
4459                  * of data.
4460                  */
4461                 } else if (amount_xferred < scb->io_ctx->underflow) {
4462                         u_int i;
4463
4464                         ahd_print_path(ahd, scb);
4465                         printf("CDB:");
4466                         for (i = 0; i < scb->io_ctx->cmd_len; i++)
4467                                 printf(" 0x%x", scb->io_ctx->cmnd[i]);
4468                         printf("\n");
4469                         ahd_print_path(ahd, scb);
4470                         printf("Saw underflow (%ld of %ld bytes). "
4471                                "Treated as error\n",
4472                                 ahd_get_residual(scb),
4473                                 ahd_get_transfer_length(scb));
4474                         ahd_set_transaction_status(scb, CAM_DATA_RUN_ERR);
4475 #endif
4476                 } else {
4477                         ahd_set_transaction_status(scb, CAM_REQ_CMP);
4478                 }
4479         } else if (ahd_get_transaction_status(scb) == CAM_SCSI_STATUS_ERROR) {
4480                 ahd_linux_handle_scsi_status(ahd, dev, scb);
4481         } else if (ahd_get_transaction_status(scb) == CAM_SEL_TIMEOUT) {
4482                 dev->flags |= AHD_DEV_UNCONFIGURED;
4483                 if (AHD_DV_CMD(cmd) == FALSE)
4484                         dev->target->flags &= ~AHD_DV_REQUIRED;
4485         }
4486         /*
4487          * Start DV for devices that require it assuming the first command
4488          * sent does not result in a selection timeout.
4489          */
4490         if (ahd_get_transaction_status(scb) != CAM_SEL_TIMEOUT
4491          && (dev->target->flags & AHD_DV_REQUIRED) != 0)
4492                 ahd_linux_start_dv(ahd);
4493
4494         if (dev->openings == 1
4495          && ahd_get_transaction_status(scb) == CAM_REQ_CMP
4496          && ahd_get_scsi_status(scb) != SCSI_STATUS_QUEUE_FULL)
4497                 dev->tag_success_count++;
4498         /*
4499          * Some devices deal with temporary internal resource
4500          * shortages by returning queue full.  When the queue
4501          * full occurrs, we throttle back.  Slowly try to get
4502          * back to our previous queue depth.
4503          */
4504         if ((dev->openings + dev->active) < dev->maxtags
4505          && dev->tag_success_count > AHD_TAG_SUCCESS_INTERVAL) {
4506                 dev->tag_success_count = 0;
4507                 dev->openings++;
4508         }
4509
4510         if (dev->active == 0)
4511                 dev->commands_since_idle_or_otag = 0;
4512
4513         if (TAILQ_EMPTY(&dev->busyq)) {
4514                 if ((dev->flags & AHD_DEV_UNCONFIGURED) != 0
4515                  && dev->active == 0
4516                  && (dev->flags & AHD_DEV_TIMER_ACTIVE) == 0)
4517                         ahd_linux_free_device(ahd, dev);
4518         } else if ((dev->flags & AHD_DEV_ON_RUN_LIST) == 0) {
4519                 TAILQ_INSERT_TAIL(&ahd->platform_data->device_runq, dev, links);
4520                 dev->flags |= AHD_DEV_ON_RUN_LIST;
4521         }
4522
4523         if ((scb->flags & SCB_RECOVERY_SCB) != 0) {
4524                 printf("Recovery SCB completes\n");
4525                 if (ahd_get_transaction_status(scb) == CAM_BDR_SENT
4526                  || ahd_get_transaction_status(scb) == CAM_REQ_ABORTED)
4527                         ahd_set_transaction_status(scb, CAM_CMD_TIMEOUT);
4528                 if ((scb->platform_data->flags & AHD_SCB_UP_EH_SEM) != 0) {
4529                         scb->platform_data->flags &= ~AHD_SCB_UP_EH_SEM;
4530                         up(&ahd->platform_data->eh_sem);
4531                 }
4532         }
4533
4534         ahd_free_scb(ahd, scb);
4535         ahd_linux_queue_cmd_complete(ahd, cmd);
4536
4537         if ((ahd->platform_data->flags & AHD_DV_WAIT_SIMQ_EMPTY) != 0
4538          && LIST_FIRST(&ahd->pending_scbs) == NULL) {
4539                 ahd->platform_data->flags &= ~AHD_DV_WAIT_SIMQ_EMPTY;
4540                 up(&ahd->platform_data->dv_sem);
4541         }
4542 }
4543
4544 static void
4545 ahd_linux_handle_scsi_status(struct ahd_softc *ahd,
4546                              struct ahd_linux_device *dev, struct scb *scb)
4547 {
4548         struct  ahd_devinfo devinfo;
4549
4550         ahd_compile_devinfo(&devinfo,
4551                             ahd->our_id,
4552                             dev->target->target, dev->lun,
4553                             dev->target->channel == 0 ? 'A' : 'B',
4554                             ROLE_INITIATOR);
4555         
4556         /*
4557          * We don't currently trust the mid-layer to
4558          * properly deal with queue full or busy.  So,
4559          * when one occurs, we tell the mid-layer to
4560          * unconditionally requeue the command to us
4561          * so that we can retry it ourselves.  We also
4562          * implement our own throttling mechanism so
4563          * we don't clobber the device with too many
4564          * commands.
4565          */
4566         switch (ahd_get_scsi_status(scb)) {
4567         default:
4568                 break;
4569         case SCSI_STATUS_CHECK_COND:
4570         case SCSI_STATUS_CMD_TERMINATED:
4571         {
4572                 Scsi_Cmnd *cmd;
4573
4574                 /*
4575                  * Copy sense information to the OS's cmd
4576                  * structure if it is available.
4577                  */
4578                 cmd = scb->io_ctx;
4579                 if ((scb->flags & (SCB_SENSE|SCB_PKT_SENSE)) != 0) {
4580                         struct scsi_status_iu_header *siu;
4581                         u_int sense_size;
4582                         u_int sense_offset;
4583
4584                         if (scb->flags & SCB_SENSE) {
4585                                 sense_size = MIN(sizeof(struct scsi_sense_data)
4586                                                - ahd_get_sense_residual(scb),
4587                                                  sizeof(cmd->sense_buffer));
4588                                 sense_offset = 0;
4589                         } else {
4590                                 /*
4591                                  * Copy only the sense data into the provided
4592                                  * buffer.
4593                                  */
4594                                 siu = (struct scsi_status_iu_header *)
4595                                     scb->sense_data;
4596                                 sense_size = MIN(scsi_4btoul(siu->sense_length),
4597                                                 sizeof(cmd->sense_buffer));
4598                                 sense_offset = SIU_SENSE_OFFSET(siu);
4599                         }
4600
4601                         memset(cmd->sense_buffer, 0, sizeof(cmd->sense_buffer));
4602                         memcpy(cmd->sense_buffer,
4603                                ahd_get_sense_buf(ahd, scb)
4604                                + sense_offset, sense_size);
4605                         cmd->result |= (DRIVER_SENSE << 24);
4606
4607 #ifdef AHD_DEBUG
4608                         if (ahd_debug & AHD_SHOW_SENSE) {
4609                                 int i;
4610
4611                                 printf("Copied %d bytes of sense data at %d:",
4612                                        sense_size, sense_offset);
4613                                 for (i = 0; i < sense_size; i++) {
4614                                         if ((i & 0xF) == 0)
4615                                                 printf("\n");
4616                                         printf("0x%x ", cmd->sense_buffer[i]);
4617                                 }
4618                                 printf("\n");
4619                         }
4620 #endif
4621                 }
4622                 break;
4623         }
4624         case SCSI_STATUS_QUEUE_FULL:
4625         {
4626                 /*
4627                  * By the time the core driver has returned this
4628                  * command, all other commands that were queued
4629                  * to us but not the device have been returned.
4630                  * This ensures that dev->active is equal to
4631                  * the number of commands actually queued to
4632                  * the device.
4633                  */
4634                 dev->tag_success_count = 0;
4635                 if (dev->active != 0) {
4636                         /*
4637                          * Drop our opening count to the number
4638                          * of commands currently outstanding.
4639                          */
4640                         dev->openings = 0;
4641 #ifdef AHD_DEBUG
4642                         if ((ahd_debug & AHD_SHOW_QFULL) != 0) {
4643                                 ahd_print_path(ahd, scb);
4644                                 printf("Dropping tag count to %d\n",
4645                                        dev->active);
4646                         }
4647 #endif
4648                         if (dev->active == dev->tags_on_last_queuefull) {
4649
4650                                 dev->last_queuefull_same_count++;
4651                                 /*
4652                                  * If we repeatedly see a queue full
4653                                  * at the same queue depth, this
4654                                  * device has a fixed number of tag
4655                                  * slots.  Lock in this tag depth
4656                                  * so we stop seeing queue fulls from
4657                                  * this device.
4658                                  */
4659                                 if (dev->last_queuefull_same_count
4660                                  == AHD_LOCK_TAGS_COUNT) {
4661                                         dev->maxtags = dev->active;
4662                                         ahd_print_path(ahd, scb);
4663                                         printf("Locking max tag count at %d\n",
4664                                                dev->active);
4665                                 }
4666                         } else {
4667                                 dev->tags_on_last_queuefull = dev->active;
4668                                 dev->last_queuefull_same_count = 0;
4669                         }
4670                         ahd_set_transaction_status(scb, CAM_REQUEUE_REQ);
4671                         ahd_set_scsi_status(scb, SCSI_STATUS_OK);
4672                         ahd_platform_set_tags(ahd, &devinfo,
4673                                      (dev->flags & AHD_DEV_Q_BASIC)
4674                                    ? AHD_QUEUE_BASIC : AHD_QUEUE_TAGGED);
4675                         break;
4676                 }
4677                 /*
4678                  * Drop down to a single opening, and treat this
4679                  * as if the target returned BUSY SCSI status.
4680                  */
4681                 dev->openings = 1;
4682                 ahd_platform_set_tags(ahd, &devinfo,
4683                              (dev->flags & AHD_DEV_Q_BASIC)
4684                            ? AHD_QUEUE_BASIC : AHD_QUEUE_TAGGED);
4685                 ahd_set_scsi_status(scb, SCSI_STATUS_BUSY);
4686                 /* FALLTHROUGH */
4687         }
4688         case SCSI_STATUS_BUSY:
4689                 /*
4690                  * Set a short timer to defer sending commands for
4691                  * a bit since Linux will not delay in this case.
4692                  */
4693                 if ((dev->flags & AHD_DEV_TIMER_ACTIVE) != 0) {
4694                         printf("%s:%c:%d: Device Timer still active during "
4695                                "busy processing\n", ahd_name(ahd),
4696                                 dev->target->channel, dev->target->target);
4697                         break;
4698                 }
4699                 dev->flags |= AHD_DEV_TIMER_ACTIVE;
4700                 dev->qfrozen++;
4701                 init_timer(&dev->timer);
4702                 dev->timer.data = (u_long)dev;
4703                 dev->timer.expires = jiffies + (HZ/2);
4704                 dev->timer.function = ahd_linux_dev_timed_unfreeze;
4705                 add_timer(&dev->timer);
4706                 break;
4707         }
4708 }
4709
4710 static void
4711 ahd_linux_queue_cmd_complete(struct ahd_softc *ahd, Scsi_Cmnd *cmd)
4712 {
4713         /*
4714          * Typically, the complete queue has very few entries
4715          * queued to it before the queue is emptied by
4716          * ahd_linux_run_complete_queue, so sorting the entries
4717          * by generation number should be inexpensive.
4718          * We perform the sort so that commands that complete
4719          * with an error are retuned in the order origionally
4720          * queued to the controller so that any subsequent retries
4721          * are performed in order.  The underlying ahd routines do
4722          * not guarantee the order that aborted commands will be
4723          * returned to us.
4724          */
4725         struct ahd_completeq *completeq;
4726         struct ahd_cmd *list_cmd;
4727         struct ahd_cmd *acmd;
4728
4729         /*
4730          * Map CAM error codes into Linux Error codes.  We
4731          * avoid the conversion so that the DV code has the
4732          * full error information available when making
4733          * state change decisions.
4734          */
4735         if (AHD_DV_CMD(cmd) == FALSE) {
4736                 uint32_t status;
4737                 u_int new_status;
4738
4739                 status = ahd_cmd_get_transaction_status(cmd);
4740                 if (status != CAM_REQ_CMP) {
4741                         struct ahd_linux_device *dev;
4742                         struct ahd_devinfo devinfo;
4743                         cam_status cam_status;
4744                         uint32_t action;
4745                         u_int scsi_status;
4746
4747                         dev = ahd_linux_get_device(ahd, cmd->device->channel,
4748                                                    cmd->device->id,
4749                                                    cmd->device->lun,
4750                                                    /*alloc*/FALSE);
4751
4752                         if (dev == NULL)
4753                                 goto no_fallback;
4754
4755                         ahd_compile_devinfo(&devinfo,
4756                                             ahd->our_id,
4757                                             dev->target->target, dev->lun,
4758                                             dev->target->channel == 0 ? 'A':'B',
4759                                             ROLE_INITIATOR);
4760
4761                         scsi_status = ahd_cmd_get_scsi_status(cmd);
4762                         cam_status = ahd_cmd_get_transaction_status(cmd);
4763                         action = aic_error_action(cmd, dev->target->inq_data,
4764                                                   cam_status, scsi_status);
4765                         if ((action & SSQ_FALLBACK) != 0) {
4766
4767                                 /* Update stats */
4768                                 dev->target->errors_detected++;
4769                                 if (dev->target->cmds_since_error == 0)
4770                                         dev->target->cmds_since_error++;
4771                                 else {
4772                                         dev->target->cmds_since_error = 0;
4773                                         ahd_linux_fallback(ahd, &devinfo);
4774                                 }
4775                         }
4776                 }
4777 no_fallback:
4778                 switch (status) {
4779                 case CAM_REQ_INPROG:
4780                 case CAM_REQ_CMP:
4781                 case CAM_SCSI_STATUS_ERROR:
4782                         new_status = DID_OK;
4783                         break;
4784                 case CAM_REQ_ABORTED:
4785                         new_status = DID_ABORT;
4786                         break;
4787                 case CAM_BUSY:
4788                         new_status = DID_BUS_BUSY;
4789                         break;
4790                 case CAM_REQ_INVALID:
4791                 case CAM_PATH_INVALID:
4792                         new_status = DID_BAD_TARGET;
4793                         break;
4794                 case CAM_SEL_TIMEOUT:
4795                         new_status = DID_NO_CONNECT;
4796                         break;
4797                 case CAM_SCSI_BUS_RESET:
4798                 case CAM_BDR_SENT:
4799                         new_status = DID_RESET;
4800                         break;
4801                 case CAM_UNCOR_PARITY:
4802                         new_status = DID_PARITY;
4803                         break;
4804                 case CAM_CMD_TIMEOUT:
4805                         new_status = DID_TIME_OUT;
4806                         break;
4807                 case CAM_UA_ABORT:
4808                 case CAM_REQ_CMP_ERR:
4809                 case CAM_AUTOSENSE_FAIL:
4810                 case CAM_NO_HBA:
4811                 case CAM_DATA_RUN_ERR:
4812                 case CAM_UNEXP_BUSFREE:
4813                 case CAM_SEQUENCE_FAIL:
4814                 case CAM_CCB_LEN_ERR:
4815                 case CAM_PROVIDE_FAIL:
4816                 case CAM_REQ_TERMIO:
4817                 case CAM_UNREC_HBA_ERROR:
4818                 case CAM_REQ_TOO_BIG:
4819                         new_status = DID_ERROR;
4820                         break;
4821                 case CAM_REQUEUE_REQ:
4822                         /*
4823                          * If we want the request requeued, make sure there
4824                          * are sufficent retries.  In the old scsi error code,
4825                          * we used to be able to specify a result code that
4826                          * bypassed the retry count.  Now we must use this
4827                          * hack.  We also "fake" a check condition with
4828                          * a sense code of ABORTED COMMAND.  This seems to
4829                          * evoke a retry even if this command is being sent
4830                          * via the eh thread.  Ick!  Ick!  Ick!
4831                          */
4832                         if (cmd->retries > 0)
4833                                 cmd->retries--;
4834                         new_status = DID_OK;
4835                         ahd_cmd_set_scsi_status(cmd, SCSI_STATUS_CHECK_COND);
4836                         cmd->result |= (DRIVER_SENSE << 24);
4837                         memset(cmd->sense_buffer, 0,
4838                                sizeof(cmd->sense_buffer));
4839                         cmd->sense_buffer[0] = SSD_ERRCODE_VALID
4840                                              | SSD_CURRENT_ERROR;
4841                         cmd->sense_buffer[2] = SSD_KEY_ABORTED_COMMAND;
4842                         break;
4843                 default:
4844                         /* We should never get here */
4845                         new_status = DID_ERROR;
4846                         break;
4847                 }
4848
4849                 ahd_cmd_set_transaction_status(cmd, new_status);
4850         }
4851
4852         completeq = &ahd->platform_data->completeq;
4853         list_cmd = TAILQ_FIRST(completeq);
4854         acmd = (struct ahd_cmd *)cmd;
4855         while (list_cmd != NULL
4856             && acmd_scsi_cmd(list_cmd).serial_number
4857              < acmd_scsi_cmd(acmd).serial_number)
4858                 list_cmd = TAILQ_NEXT(list_cmd, acmd_links.tqe);
4859         if (list_cmd != NULL)
4860                 TAILQ_INSERT_BEFORE(list_cmd, acmd, acmd_links.tqe);
4861         else
4862                 TAILQ_INSERT_TAIL(completeq, acmd, acmd_links.tqe);
4863 }
4864
4865 static void
4866 ahd_linux_filter_inquiry(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
4867 {
4868         struct  scsi_inquiry_data *sid;
4869         struct  ahd_initiator_tinfo *tinfo;
4870         struct  ahd_transinfo *user;
4871         struct  ahd_transinfo *goal;
4872         struct  ahd_transinfo *curr;
4873         struct  ahd_tmode_tstate *tstate;
4874         struct  ahd_linux_device *dev;
4875         u_int   width;
4876         u_int   period;
4877         u_int   offset;
4878         u_int   ppr_options;
4879         u_int   trans_version;
4880         u_int   prot_version;
4881
4882         /*
4883          * Determine if this lun actually exists.  If so,
4884          * hold on to its corresponding device structure.
4885          * If not, make sure we release the device and
4886          * don't bother processing the rest of this inquiry
4887          * command.
4888          */
4889         dev = ahd_linux_get_device(ahd, devinfo->channel - 'A',
4890                                    devinfo->target, devinfo->lun,
4891                                    /*alloc*/TRUE);
4892
4893         sid = (struct scsi_inquiry_data *)dev->target->inq_data;
4894         if (SID_QUAL(sid) == SID_QUAL_LU_CONNECTED) {
4895
4896                 dev->flags &= ~AHD_DEV_UNCONFIGURED;
4897         } else {
4898                 dev->flags |= AHD_DEV_UNCONFIGURED;
4899                 return;
4900         }
4901
4902         /*
4903          * Update our notion of this device's transfer
4904          * negotiation capabilities.
4905          */
4906         tinfo = ahd_fetch_transinfo(ahd, devinfo->channel,
4907                                     devinfo->our_scsiid,
4908                                     devinfo->target, &tstate);
4909         user = &tinfo->user;
4910         goal = &tinfo->goal;
4911         curr = &tinfo->curr;
4912         width = user->width;
4913         period = user->period;
4914         offset = user->offset;
4915         ppr_options = user->ppr_options;
4916         trans_version = user->transport_version;
4917         prot_version = MIN(user->protocol_version, SID_ANSI_REV(sid));
4918
4919         /*
4920          * Only attempt SPI3/4 once we've verified that
4921          * the device claims to support SPI3/4 features.
4922          */
4923         if (prot_version < SCSI_REV_2)
4924                 trans_version = SID_ANSI_REV(sid);
4925         else
4926                 trans_version = SCSI_REV_2;
4927
4928         if ((sid->flags & SID_WBus16) == 0)
4929                 width = MSG_EXT_WDTR_BUS_8_BIT;
4930         if ((sid->flags & SID_Sync) == 0) {
4931                 period = 0;
4932                 offset = 0;
4933                 ppr_options = 0;
4934         }
4935         if ((sid->spi3data & SID_SPI_QAS) == 0)
4936                 ppr_options &= ~MSG_EXT_PPR_QAS_REQ;
4937         if ((sid->spi3data & SID_SPI_CLOCK_DT) == 0)
4938                 ppr_options &= MSG_EXT_PPR_QAS_REQ;
4939         if ((sid->spi3data & SID_SPI_IUS) == 0)
4940                 ppr_options &= (MSG_EXT_PPR_DT_REQ
4941                               | MSG_EXT_PPR_QAS_REQ);
4942
4943         if (prot_version > SCSI_REV_2
4944          && ppr_options != 0)
4945                 trans_version = user->transport_version;
4946
4947         ahd_validate_width(ahd, /*tinfo limit*/NULL, &width, ROLE_UNKNOWN);
4948         ahd_find_syncrate(ahd, &period, &ppr_options, AHD_SYNCRATE_MAX);
4949         ahd_validate_offset(ahd, /*tinfo limit*/NULL, period,
4950                             &offset, width, ROLE_UNKNOWN);
4951         if (offset == 0 || period == 0) {
4952                 period = 0;
4953                 offset = 0;
4954                 ppr_options = 0;
4955         }
4956         /* Apply our filtered user settings. */
4957         curr->transport_version = trans_version;
4958         curr->protocol_version = prot_version;
4959         ahd_set_width(ahd, devinfo, width, AHD_TRANS_GOAL, /*paused*/FALSE);
4960         ahd_set_syncrate(ahd, devinfo, period, offset, ppr_options,
4961                          AHD_TRANS_GOAL, /*paused*/FALSE);
4962 }
4963
4964 void
4965 ahd_freeze_simq(struct ahd_softc *ahd)
4966 {
4967         ahd->platform_data->qfrozen++;
4968         if (ahd->platform_data->qfrozen == 1) {
4969                 scsi_block_requests(ahd->platform_data->host);
4970                 ahd_platform_abort_scbs(ahd, CAM_TARGET_WILDCARD, ALL_CHANNELS,
4971                                         CAM_LUN_WILDCARD, SCB_LIST_NULL,
4972                                         ROLE_INITIATOR, CAM_REQUEUE_REQ);
4973         }
4974 }
4975
4976 void
4977 ahd_release_simq(struct ahd_softc *ahd)
4978 {
4979         u_long s;
4980         int    unblock_reqs;
4981
4982         unblock_reqs = 0;
4983         ahd_lock(ahd, &s);
4984         if (ahd->platform_data->qfrozen > 0)
4985                 ahd->platform_data->qfrozen--;
4986         if (ahd->platform_data->qfrozen == 0) {
4987                 unblock_reqs = 1;
4988         }
4989         if (AHD_DV_SIMQ_FROZEN(ahd)
4990          && ((ahd->platform_data->flags & AHD_DV_WAIT_SIMQ_RELEASE) != 0)) {
4991                 ahd->platform_data->flags &= ~AHD_DV_WAIT_SIMQ_RELEASE;
4992                 up(&ahd->platform_data->dv_sem);
4993         }
4994         ahd_schedule_runq(ahd);
4995         ahd_unlock(ahd, &s);
4996         /*
4997          * There is still a race here.  The mid-layer
4998          * should keep its own freeze count and use
4999          * a bottom half handler to run the queues
5000          * so we can unblock with our own lock held.
5001          */
5002         if (unblock_reqs)
5003                 scsi_unblock_requests(ahd->platform_data->host);
5004 }
5005
5006 static void
5007 ahd_linux_sem_timeout(u_long arg)
5008 {
5009         struct  scb *scb;
5010         struct  ahd_softc *ahd;
5011         u_long  s;
5012
5013         scb = (struct scb *)arg;
5014         ahd = scb->ahd_softc;
5015         ahd_lock(ahd, &s);
5016         if ((scb->platform_data->flags & AHD_SCB_UP_EH_SEM) != 0) {
5017                 scb->platform_data->flags &= ~AHD_SCB_UP_EH_SEM;
5018                 up(&ahd->platform_data->eh_sem);
5019         }
5020         ahd_unlock(ahd, &s);
5021 }
5022
5023 static void
5024 ahd_linux_dev_timed_unfreeze(u_long arg)
5025 {
5026         struct ahd_linux_device *dev;
5027         struct ahd_softc *ahd;
5028         u_long s;
5029
5030         dev = (struct ahd_linux_device *)arg;
5031         ahd = dev->target->ahd;
5032         ahd_lock(ahd, &s);
5033         dev->flags &= ~AHD_DEV_TIMER_ACTIVE;
5034         if (dev->qfrozen > 0)
5035                 dev->qfrozen--;
5036         if (dev->qfrozen == 0
5037          && (dev->flags & AHD_DEV_ON_RUN_LIST) == 0)
5038                 ahd_linux_run_device_queue(ahd, dev);
5039         if ((dev->flags & AHD_DEV_UNCONFIGURED) != 0
5040          && dev->active == 0)
5041                 ahd_linux_free_device(ahd, dev);
5042         ahd_unlock(ahd, &s);
5043 }
5044
5045 void
5046 ahd_platform_dump_card_state(struct ahd_softc *ahd)
5047 {
5048         struct ahd_linux_device *dev;
5049         int target;
5050         int maxtarget;
5051         int lun;
5052         int i;
5053
5054         maxtarget = (ahd->features & AHD_WIDE) ? 15 : 7;
5055         for (target = 0; target <=maxtarget; target++) {
5056
5057                 for (lun = 0; lun < AHD_NUM_LUNS; lun++) {
5058                         struct ahd_cmd *acmd;
5059
5060                         dev = ahd_linux_get_device(ahd, 0, target,
5061                                                    lun, /*alloc*/FALSE);
5062                         if (dev == NULL)
5063                                 continue;
5064
5065                         printf("DevQ(%d:%d:%d): ", 0, target, lun);
5066                         i = 0;
5067                         TAILQ_FOREACH(acmd, &dev->busyq, acmd_links.tqe) {
5068                                 if (i++ > AHD_SCB_MAX)
5069                                         break;
5070                         }
5071                         printf("%d waiting\n", i);
5072                 }
5073         }
5074 }
5075
5076 static int __init
5077 ahd_linux_init(void)
5078 {
5079 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
5080        return (ahd_linux_detect(&aic79xx_driver_template) ? 0 : -ENODEV);
5081 #else
5082         scsi_register_module(MODULE_SCSI_HA, &aic79xx_driver_template);
5083         if (aic79xx_driver_template.present == 0) {
5084                 scsi_unregister_module(MODULE_SCSI_HA,
5085                                        &aic79xx_driver_template);
5086                 return (-ENODEV);
5087         }
5088
5089         return (0);
5090 #endif
5091 }
5092
5093 static void __exit
5094 ahd_linux_exit(void)
5095 {
5096         struct ahd_softc *ahd;
5097         u_long l;
5098
5099         /*
5100          * Shutdown DV threads before going into the SCSI mid-layer.
5101          * This avoids situations where the mid-layer locks the entire
5102          * kernel so that waiting for our DV threads to exit leads
5103          * to deadlock.
5104          */
5105         ahd_list_lock(&l);
5106         TAILQ_FOREACH(ahd, &ahd_tailq, links) {
5107
5108                 ahd_linux_kill_dv_thread(ahd);
5109         }
5110         ahd_list_unlock(&l);
5111 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
5112         /*
5113          * In 2.4 we have to unregister from the PCI core _after_
5114          * unregistering from the scsi midlayer to avoid dangling
5115          * references.
5116          */
5117         scsi_unregister_module(MODULE_SCSI_HA, &aic79xx_driver_template);
5118 #endif
5119         ahd_linux_pci_exit();
5120 }
5121
5122 module_init(ahd_linux_init);
5123 module_exit(ahd_linux_exit);