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