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