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