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