VServer 1.9.2 (patch-2.6.8.1-vs1.9.2.diff)
[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 = 0;
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         found = ahc_linux_pci_init();
895         if (!ahc_linux_eisa_init())
896                 found++;
897         
898         /*
899          * Register with the SCSI layer all
900          * controllers we've found.
901          */
902         TAILQ_FOREACH(ahc, &ahc_tailq, links) {
903
904                 if (ahc_linux_register_host(ahc, template) == 0)
905                         found++;
906         }
907
908 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
909         spin_lock_irq(&io_request_lock);
910 #endif
911         aic7xxx_detect_complete++;
912
913         return (found);
914 }
915
916 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
917 /*
918  * Free the passed in Scsi_Host memory structures prior to unloading the
919  * module.
920  */
921 int
922 ahc_linux_release(struct Scsi_Host * host)
923 {
924         struct ahc_softc *ahc;
925         u_long l;
926
927         ahc_list_lock(&l);
928         if (host != NULL) {
929
930                 /*
931                  * We should be able to just perform
932                  * the free directly, but check our
933                  * list for extra sanity.
934                  */
935                 ahc = ahc_find_softc(*(struct ahc_softc **)host->hostdata);
936                 if (ahc != NULL) {
937                         u_long s;
938
939                         ahc_lock(ahc, &s);
940                         ahc_intr_enable(ahc, FALSE);
941                         ahc_unlock(ahc, &s);
942                         ahc_free(ahc);
943                 }
944         }
945         ahc_list_unlock(&l);
946         return (0);
947 }
948 #endif
949
950 /*
951  * Return a string describing the driver.
952  */
953 static const char *
954 ahc_linux_info(struct Scsi_Host *host)
955 {
956         static char buffer[512];
957         char    ahc_info[256];
958         char   *bp;
959         struct ahc_softc *ahc;
960
961         bp = &buffer[0];
962         ahc = *(struct ahc_softc **)host->hostdata;
963         memset(bp, 0, sizeof(buffer));
964         strcpy(bp, "Adaptec AIC7XXX EISA/VLB/PCI SCSI HBA DRIVER, Rev ");
965         strcat(bp, AIC7XXX_DRIVER_VERSION);
966         strcat(bp, "\n");
967         strcat(bp, "        <");
968         strcat(bp, ahc->description);
969         strcat(bp, ">\n");
970         strcat(bp, "        ");
971         ahc_controller_info(ahc, ahc_info);
972         strcat(bp, ahc_info);
973         strcat(bp, "\n");
974
975         return (bp);
976 }
977
978 /*
979  * Queue an SCB to the controller.
980  */
981 static int
982 ahc_linux_queue(Scsi_Cmnd * cmd, void (*scsi_done) (Scsi_Cmnd *))
983 {
984         struct   ahc_softc *ahc;
985         struct   ahc_linux_device *dev;
986         u_long   flags;
987
988         ahc = *(struct ahc_softc **)cmd->device->host->hostdata;
989
990         /*
991          * Save the callback on completion function.
992          */
993         cmd->scsi_done = scsi_done;
994
995         ahc_midlayer_entrypoint_lock(ahc, &flags);
996
997         /*
998          * Close the race of a command that was in the process of
999          * being queued to us just as our simq was frozen.  Let
1000          * DV commands through so long as we are only frozen to
1001          * perform DV.
1002          */
1003         if (ahc->platform_data->qfrozen != 0
1004          && AHC_DV_CMD(cmd) == 0) {
1005
1006                 ahc_cmd_set_transaction_status(cmd, CAM_REQUEUE_REQ);
1007                 ahc_linux_queue_cmd_complete(ahc, cmd);
1008                 ahc_schedule_completeq(ahc);
1009                 ahc_midlayer_entrypoint_unlock(ahc, &flags);
1010                 return (0);
1011         }
1012         dev = ahc_linux_get_device(ahc, cmd->device->channel, cmd->device->id,
1013                                    cmd->device->lun, /*alloc*/TRUE);
1014         if (dev == NULL) {
1015                 ahc_cmd_set_transaction_status(cmd, CAM_RESRC_UNAVAIL);
1016                 ahc_linux_queue_cmd_complete(ahc, cmd);
1017                 ahc_schedule_completeq(ahc);
1018                 ahc_midlayer_entrypoint_unlock(ahc, &flags);
1019                 printf("%s: aic7xxx_linux_queue - Unable to allocate device!\n",
1020                        ahc_name(ahc));
1021                 return (0);
1022         }
1023         cmd->result = CAM_REQ_INPROG << 16;
1024         TAILQ_INSERT_TAIL(&dev->busyq, (struct ahc_cmd *)cmd, acmd_links.tqe);
1025         if ((dev->flags & AHC_DEV_ON_RUN_LIST) == 0) {
1026                 TAILQ_INSERT_TAIL(&ahc->platform_data->device_runq, dev, links);
1027                 dev->flags |= AHC_DEV_ON_RUN_LIST;
1028                 ahc_linux_run_device_queues(ahc);
1029         }
1030         ahc_midlayer_entrypoint_unlock(ahc, &flags);
1031         return (0);
1032 }
1033
1034 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
1035 static int
1036 ahc_linux_slave_alloc(Scsi_Device *device)
1037 {
1038         struct  ahc_softc *ahc;
1039
1040         ahc = *((struct ahc_softc **)device->host->hostdata);
1041         if (bootverbose)
1042                 printf("%s: Slave Alloc %d\n", ahc_name(ahc), device->id);
1043         return (0);
1044 }
1045
1046 static int
1047 ahc_linux_slave_configure(Scsi_Device *device)
1048 {
1049         struct  ahc_softc *ahc;
1050         struct  ahc_linux_device *dev;
1051         u_long  flags;
1052
1053         ahc = *((struct ahc_softc **)device->host->hostdata);
1054         if (bootverbose)
1055                 printf("%s: Slave Configure %d\n", ahc_name(ahc), device->id);
1056         ahc_midlayer_entrypoint_lock(ahc, &flags);
1057         /*
1058          * Since Linux has attached to the device, configure
1059          * it so we don't free and allocate the device
1060          * structure on every command.
1061          */
1062         dev = ahc_linux_get_device(ahc, device->channel,
1063                                    device->id, device->lun,
1064                                    /*alloc*/TRUE);
1065         if (dev != NULL) {
1066                 dev->flags &= ~AHC_DEV_UNCONFIGURED;
1067                 dev->scsi_device = device;
1068                 ahc_linux_device_queue_depth(ahc, dev);
1069         }
1070         ahc_midlayer_entrypoint_unlock(ahc, &flags);
1071         return (0);
1072 }
1073
1074 static void
1075 ahc_linux_slave_destroy(Scsi_Device *device)
1076 {
1077         struct  ahc_softc *ahc;
1078         struct  ahc_linux_device *dev;
1079         u_long  flags;
1080
1081         ahc = *((struct ahc_softc **)device->host->hostdata);
1082         if (bootverbose)
1083                 printf("%s: Slave Destroy %d\n", ahc_name(ahc), device->id);
1084         ahc_midlayer_entrypoint_lock(ahc, &flags);
1085         dev = ahc_linux_get_device(ahc, device->channel,
1086                                    device->id, device->lun,
1087                                            /*alloc*/FALSE);
1088         /*
1089          * Filter out "silly" deletions of real devices by only
1090          * deleting devices that have had slave_configure()
1091          * called on them.  All other devices that have not
1092          * been configured will automatically be deleted by
1093          * the refcounting process.
1094          */
1095         if (dev != NULL
1096          && (dev->flags & AHC_DEV_SLAVE_CONFIGURED) != 0) {
1097                 dev->flags |= AHC_DEV_UNCONFIGURED;
1098                 if (TAILQ_EMPTY(&dev->busyq)
1099                  && dev->active == 0
1100                  && (dev->flags & AHC_DEV_TIMER_ACTIVE) == 0)
1101                         ahc_linux_free_device(ahc, dev);
1102         }
1103         ahc_midlayer_entrypoint_unlock(ahc, &flags);
1104 }
1105 #else
1106 /*
1107  * Sets the queue depth for each SCSI device hanging
1108  * off the input host adapter.
1109  */
1110 static void
1111 ahc_linux_select_queue_depth(struct Scsi_Host *host, Scsi_Device *scsi_devs)
1112 {
1113         Scsi_Device *device;
1114         Scsi_Device *ldev;
1115         struct  ahc_softc *ahc;
1116         u_long  flags;
1117
1118         ahc = *((struct ahc_softc **)host->hostdata);
1119         ahc_lock(ahc, &flags);
1120         for (device = scsi_devs; device != NULL; device = device->next) {
1121
1122                 /*
1123                  * Watch out for duplicate devices.  This works around
1124                  * some quirks in how the SCSI scanning code does its
1125                  * device management.
1126                  */
1127                 for (ldev = scsi_devs; ldev != device; ldev = ldev->next) {
1128                         if (ldev->host == device->host
1129                          && ldev->channel == device->channel
1130                          && ldev->id == device->id
1131                          && ldev->lun == device->lun)
1132                                 break;
1133                 }
1134                 /* Skip duplicate. */
1135                 if (ldev != device)
1136                         continue;
1137
1138                 if (device->host == host) {
1139                         struct   ahc_linux_device *dev;
1140
1141                         /*
1142                          * Since Linux has attached to the device, configure
1143                          * it so we don't free and allocate the device
1144                          * structure on every command.
1145                          */
1146                         dev = ahc_linux_get_device(ahc, device->channel,
1147                                                    device->id, device->lun,
1148                                                    /*alloc*/TRUE);
1149                         if (dev != NULL) {
1150                                 dev->flags &= ~AHC_DEV_UNCONFIGURED;
1151                                 dev->scsi_device = device;
1152                                 ahc_linux_device_queue_depth(ahc, dev);
1153                                 device->queue_depth = dev->openings
1154                                                     + dev->active;
1155                                 if ((dev->flags & (AHC_DEV_Q_BASIC
1156                                                 | AHC_DEV_Q_TAGGED)) == 0) {
1157                                         /*
1158                                          * We allow the OS to queue 2 untagged
1159                                          * transactions to us at any time even
1160                                          * though we can only execute them
1161                                          * serially on the controller/device.
1162                                          * This should remove some latency.
1163                                          */
1164                                         device->queue_depth = 2;
1165                                 }
1166                         }
1167                 }
1168         }
1169         ahc_unlock(ahc, &flags);
1170 }
1171 #endif
1172
1173 #if defined(__i386__)
1174 /*
1175  * Return the disk geometry for the given SCSI device.
1176  */
1177 static int
1178 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
1179 ahc_linux_biosparam(struct scsi_device *sdev, struct block_device *bdev,
1180                     sector_t capacity, int geom[])
1181 {
1182         uint8_t *bh;
1183 #else
1184 ahc_linux_biosparam(Disk *disk, kdev_t dev, int geom[])
1185 {
1186         struct  scsi_device *sdev = disk->device;
1187         u_long  capacity = disk->capacity;
1188         struct  buffer_head *bh;
1189 #endif
1190         int      heads;
1191         int      sectors;
1192         int      cylinders;
1193         int      ret;
1194         int      extended;
1195         struct   ahc_softc *ahc;
1196         u_int    channel;
1197
1198         ahc = *((struct ahc_softc **)sdev->host->hostdata);
1199         channel = sdev->channel;
1200
1201 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
1202         bh = scsi_bios_ptable(bdev);
1203 #elif LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,17)
1204         bh = bread(MKDEV(MAJOR(dev), MINOR(dev) & ~0xf), 0, block_size(dev));
1205 #else
1206         bh = bread(MKDEV(MAJOR(dev), MINOR(dev) & ~0xf), 0, 1024);
1207 #endif
1208
1209         if (bh) {
1210                 ret = scsi_partsize(bh, capacity,
1211                                     &geom[2], &geom[0], &geom[1]);
1212 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
1213                 kfree(bh);
1214 #else
1215                 brelse(bh);
1216 #endif
1217                 if (ret != -1)
1218                         return (ret);
1219         }
1220         heads = 64;
1221         sectors = 32;
1222         cylinders = aic_sector_div(capacity, heads, sectors);
1223
1224         if (aic7xxx_extended != 0)
1225                 extended = 1;
1226         else if (channel == 0)
1227                 extended = (ahc->flags & AHC_EXTENDED_TRANS_A) != 0;
1228         else
1229                 extended = (ahc->flags & AHC_EXTENDED_TRANS_B) != 0;
1230         if (extended && cylinders >= 1024) {
1231                 heads = 255;
1232                 sectors = 63;
1233                 cylinders = aic_sector_div(capacity, heads, sectors);
1234         }
1235         geom[0] = heads;
1236         geom[1] = sectors;
1237         geom[2] = cylinders;
1238         return (0);
1239 }
1240 #endif
1241
1242 /*
1243  * Abort the current SCSI command(s).
1244  */
1245 static int
1246 ahc_linux_abort(Scsi_Cmnd *cmd)
1247 {
1248         int error;
1249
1250         error = ahc_linux_queue_recovery_cmd(cmd, SCB_ABORT);
1251         if (error != 0)
1252                 printf("aic7xxx_abort returns 0x%x\n", error);
1253         return (error);
1254 }
1255
1256 /*
1257  * Attempt to send a target reset message to the device that timed out.
1258  */
1259 static int
1260 ahc_linux_dev_reset(Scsi_Cmnd *cmd)
1261 {
1262         int error;
1263
1264         error = ahc_linux_queue_recovery_cmd(cmd, SCB_DEVICE_RESET);
1265         if (error != 0)
1266                 printf("aic7xxx_dev_reset returns 0x%x\n", error);
1267         return (error);
1268 }
1269
1270 /*
1271  * Reset the SCSI bus.
1272  */
1273 static int
1274 ahc_linux_bus_reset(Scsi_Cmnd *cmd)
1275 {
1276         struct ahc_softc *ahc;
1277         u_long s;
1278         int    found;
1279
1280         ahc = *(struct ahc_softc **)cmd->device->host->hostdata;
1281         ahc_midlayer_entrypoint_lock(ahc, &s);
1282         found = ahc_reset_channel(ahc, cmd->device->channel + 'A',
1283                                   /*initiate reset*/TRUE);
1284         ahc_linux_run_complete_queue(ahc);
1285         ahc_midlayer_entrypoint_unlock(ahc, &s);
1286
1287         if (bootverbose)
1288                 printf("%s: SCSI bus reset delivered. "
1289                        "%d SCBs aborted.\n", ahc_name(ahc), found);
1290
1291         return SUCCESS;
1292 }
1293
1294 Scsi_Host_Template aic7xxx_driver_template = {
1295         .module                 = THIS_MODULE,
1296         .name                   = "aic7xxx",
1297         .proc_info              = ahc_linux_proc_info,
1298         .info                   = ahc_linux_info,
1299         .queuecommand           = ahc_linux_queue,
1300         .eh_abort_handler       = ahc_linux_abort,
1301         .eh_device_reset_handler = ahc_linux_dev_reset,
1302         .eh_bus_reset_handler   = ahc_linux_bus_reset,
1303 #if defined(__i386__)
1304         .bios_param             = ahc_linux_biosparam,
1305 #endif
1306         .can_queue              = AHC_MAX_QUEUE,
1307         .this_id                = -1,
1308         .cmd_per_lun            = 2,
1309         .use_clustering         = ENABLE_CLUSTERING,
1310         .slave_alloc            = ahc_linux_slave_alloc,
1311         .slave_configure        = ahc_linux_slave_configure,
1312         .slave_destroy          = ahc_linux_slave_destroy,
1313 };
1314
1315 /**************************** Tasklet Handler *********************************/
1316
1317 /*
1318  * In 2.4.X and above, this routine is called from a tasklet,
1319  * so we must re-acquire our lock prior to executing this code.
1320  * In all prior kernels, ahc_schedule_runq() calls this routine
1321  * directly and ahc_schedule_runq() is called with our lock held.
1322  */
1323 static void
1324 ahc_runq_tasklet(unsigned long data)
1325 {
1326         struct ahc_softc* ahc;
1327         struct ahc_linux_device *dev;
1328 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0)
1329         u_long flags;
1330 #endif
1331
1332         ahc = (struct ahc_softc *)data;
1333 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0)
1334         ahc_lock(ahc, &flags);
1335 #endif
1336         while ((dev = ahc_linux_next_device_to_run(ahc)) != NULL) {
1337         
1338                 TAILQ_REMOVE(&ahc->platform_data->device_runq, dev, links);
1339                 dev->flags &= ~AHC_DEV_ON_RUN_LIST;
1340                 ahc_linux_check_device_queue(ahc, dev);
1341 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0)
1342                 /* Yeild to our interrupt handler */
1343                 ahc_unlock(ahc, &flags);
1344                 ahc_lock(ahc, &flags);
1345 #endif
1346         }
1347 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0)
1348         ahc_unlock(ahc, &flags);
1349 #endif
1350 }
1351
1352 /******************************** Macros **************************************/
1353 #define BUILD_SCSIID(ahc, cmd)                                              \
1354         ((((cmd)->device->id << TID_SHIFT) & TID)                           \
1355         | (((cmd)->device->channel == 0) ? (ahc)->our_id : (ahc)->our_id_b) \
1356         | (((cmd)->device->channel == 0) ? 0 : TWIN_CHNLB))
1357
1358 /******************************** Bus DMA *************************************/
1359 int
1360 ahc_dma_tag_create(struct ahc_softc *ahc, bus_dma_tag_t parent,
1361                    bus_size_t alignment, bus_size_t boundary,
1362                    bus_addr_t lowaddr, bus_addr_t highaddr,
1363                    bus_dma_filter_t *filter, void *filterarg,
1364                    bus_size_t maxsize, int nsegments,
1365                    bus_size_t maxsegsz, int flags, bus_dma_tag_t *ret_tag)
1366 {
1367         bus_dma_tag_t dmat;
1368
1369         dmat = malloc(sizeof(*dmat), M_DEVBUF, M_NOWAIT);
1370         if (dmat == NULL)
1371                 return (ENOMEM);
1372
1373         /*
1374          * Linux is very simplistic about DMA memory.  For now don't
1375          * maintain all specification information.  Once Linux supplies
1376          * better facilities for doing these operations, or the
1377          * needs of this particular driver change, we might need to do
1378          * more here.
1379          */
1380         dmat->alignment = alignment;
1381         dmat->boundary = boundary;
1382         dmat->maxsize = maxsize;
1383         *ret_tag = dmat;
1384         return (0);
1385 }
1386
1387 void
1388 ahc_dma_tag_destroy(struct ahc_softc *ahc, bus_dma_tag_t dmat)
1389 {
1390         free(dmat, M_DEVBUF);
1391 }
1392
1393 int
1394 ahc_dmamem_alloc(struct ahc_softc *ahc, bus_dma_tag_t dmat, void** vaddr,
1395                  int flags, bus_dmamap_t *mapp)
1396 {
1397         bus_dmamap_t map;
1398
1399 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,3,0)
1400         map = malloc(sizeof(*map), M_DEVBUF, M_NOWAIT);
1401         if (map == NULL)
1402                 return (ENOMEM);
1403         /*
1404          * Although we can dma data above 4GB, our
1405          * "consistent" memory is below 4GB for
1406          * space efficiency reasons (only need a 4byte
1407          * address).  For this reason, we have to reset
1408          * our dma mask when doing allocations.
1409          */
1410         if (ahc->dev_softc != NULL)
1411                 if (ahc_pci_set_dma_mask(ahc->dev_softc, 0xFFFFFFFF)) {
1412                         printk(KERN_WARNING "aic7xxx: No suitable DMA available.\n");
1413                         return (ENODEV);
1414                 }
1415         *vaddr = pci_alloc_consistent(ahc->dev_softc,
1416                                       dmat->maxsize, &map->bus_addr);
1417         if (ahc->dev_softc != NULL)
1418                 if (ahc_pci_set_dma_mask(ahc->dev_softc,
1419                                      ahc->platform_data->hw_dma_mask)) {
1420                         printk(KERN_WARNING "aic7xxx: No suitable DMA available.\n");
1421                         return (ENODEV);
1422                 }
1423 #else /* LINUX_VERSION_CODE < KERNEL_VERSION(2,3,0) */
1424         /*
1425          * At least in 2.2.14, malloc is a slab allocator so all
1426          * allocations are aligned.  We assume for these kernel versions
1427          * that all allocations will be bellow 4Gig, physically contiguous,
1428          * and accessible via DMA by the controller.
1429          */
1430         map = NULL; /* No additional information to store */
1431         *vaddr = malloc(dmat->maxsize, M_DEVBUF, M_NOWAIT);
1432 #endif
1433         if (*vaddr == NULL)
1434                 return (ENOMEM);
1435         *mapp = map;
1436         return(0);
1437 }
1438
1439 void
1440 ahc_dmamem_free(struct ahc_softc *ahc, bus_dma_tag_t dmat,
1441                 void* vaddr, bus_dmamap_t map)
1442 {
1443 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,3,0)
1444         pci_free_consistent(ahc->dev_softc, dmat->maxsize,
1445                             vaddr, map->bus_addr);
1446 #else
1447         free(vaddr, M_DEVBUF);
1448 #endif
1449 }
1450
1451 int
1452 ahc_dmamap_load(struct ahc_softc *ahc, bus_dma_tag_t dmat, bus_dmamap_t map,
1453                 void *buf, bus_size_t buflen, bus_dmamap_callback_t *cb,
1454                 void *cb_arg, int flags)
1455 {
1456         /*
1457          * Assume for now that this will only be used during
1458          * initialization and not for per-transaction buffer mapping.
1459          */
1460         bus_dma_segment_t stack_sg;
1461
1462 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,3,0)
1463         stack_sg.ds_addr = map->bus_addr;
1464 #else
1465 #define VIRT_TO_BUS(a) (uint32_t)virt_to_bus((void *)(a))
1466         stack_sg.ds_addr = VIRT_TO_BUS(buf);
1467 #endif
1468         stack_sg.ds_len = dmat->maxsize;
1469         cb(cb_arg, &stack_sg, /*nseg*/1, /*error*/0);
1470         return (0);
1471 }
1472
1473 void
1474 ahc_dmamap_destroy(struct ahc_softc *ahc, bus_dma_tag_t dmat, bus_dmamap_t map)
1475 {
1476         /*
1477          * The map may is NULL in our < 2.3.X implementation.
1478          */
1479         if (map != NULL)
1480                 free(map, M_DEVBUF);
1481 }
1482
1483 int
1484 ahc_dmamap_unload(struct ahc_softc *ahc, bus_dma_tag_t dmat, bus_dmamap_t map)
1485 {
1486         /* Nothing to do */
1487         return (0);
1488 }
1489
1490 /********************* Platform Dependent Functions ***************************/
1491 /*
1492  * Compare "left hand" softc with "right hand" softc, returning:
1493  * < 0 - lahc has a lower priority than rahc
1494  *   0 - Softcs are equal
1495  * > 0 - lahc has a higher priority than rahc
1496  */
1497 int
1498 ahc_softc_comp(struct ahc_softc *lahc, struct ahc_softc *rahc)
1499 {
1500         int     value;
1501         int     rvalue;
1502         int     lvalue;
1503
1504         /*
1505          * Under Linux, cards are ordered as follows:
1506          *      1) VLB/EISA BIOS enabled devices sorted by BIOS address.
1507          *      2) PCI devices with BIOS enabled sorted by bus/slot/func.
1508          *      3) All remaining VLB/EISA devices sorted by ioport.
1509          *      4) All remaining PCI devices sorted by bus/slot/func.
1510          */
1511         value = (lahc->flags & AHC_BIOS_ENABLED)
1512               - (rahc->flags & AHC_BIOS_ENABLED);
1513         if (value != 0)
1514                 /* Controllers with BIOS enabled have a *higher* priority */
1515                 return (value);
1516
1517         /*
1518          * Same BIOS setting, now sort based on bus type.
1519          * EISA and VL controllers sort together.  EISA/VL
1520          * have higher priority than PCI.
1521          */
1522         rvalue = (rahc->chip & AHC_BUS_MASK);
1523         if (rvalue == AHC_VL)
1524                 rvalue = AHC_EISA;
1525         lvalue = (lahc->chip & AHC_BUS_MASK);
1526         if (lvalue == AHC_VL)
1527                 lvalue = AHC_EISA;
1528         value = rvalue - lvalue;
1529         if (value != 0)
1530                 return (value);
1531
1532         /* Still equal.  Sort by BIOS address, ioport, or bus/slot/func. */
1533         switch (rvalue) {
1534 #ifdef CONFIG_PCI
1535         case AHC_PCI:
1536         {
1537                 char primary_channel;
1538
1539                 if (aic7xxx_reverse_scan != 0)
1540                         value = ahc_get_pci_bus(lahc->dev_softc)
1541                               - ahc_get_pci_bus(rahc->dev_softc);
1542                 else
1543                         value = ahc_get_pci_bus(rahc->dev_softc)
1544                               - ahc_get_pci_bus(lahc->dev_softc);
1545                 if (value != 0)
1546                         break;
1547                 if (aic7xxx_reverse_scan != 0)
1548                         value = ahc_get_pci_slot(lahc->dev_softc)
1549                               - ahc_get_pci_slot(rahc->dev_softc);
1550                 else
1551                         value = ahc_get_pci_slot(rahc->dev_softc)
1552                               - ahc_get_pci_slot(lahc->dev_softc);
1553                 if (value != 0)
1554                         break;
1555                 /*
1556                  * On multi-function devices, the user can choose
1557                  * to have function 1 probed before function 0.
1558                  * Give whichever channel is the primary channel
1559                  * the highest priority.
1560                  */
1561                 primary_channel = (lahc->flags & AHC_PRIMARY_CHANNEL) + 'A';
1562                 value = -1;
1563                 if (lahc->channel == primary_channel)
1564                         value = 1;
1565                 break;
1566         }
1567 #endif
1568         case AHC_EISA:
1569                 if ((rahc->flags & AHC_BIOS_ENABLED) != 0) {
1570                         value = rahc->platform_data->bios_address
1571                               - lahc->platform_data->bios_address; 
1572                 } else {
1573                         value = rahc->bsh.ioport
1574                               - lahc->bsh.ioport; 
1575                 }
1576                 break;
1577         default:
1578                 panic("ahc_softc_sort: invalid bus type");
1579         }
1580         return (value);
1581 }
1582
1583 static void
1584 ahc_linux_setup_tag_info_global(char *p)
1585 {
1586         int tags, i, j;
1587
1588         tags = simple_strtoul(p + 1, NULL, 0) & 0xff;
1589         printf("Setting Global Tags= %d\n", tags);
1590
1591         for (i = 0; i < NUM_ELEMENTS(aic7xxx_tag_info); i++) {
1592                 for (j = 0; j < AHC_NUM_TARGETS; j++) {
1593                         aic7xxx_tag_info[i].tag_commands[j] = tags;
1594                 }
1595         }
1596 }
1597
1598 static void
1599 ahc_linux_setup_tag_info(u_long arg, int instance, int targ, int32_t value)
1600 {
1601
1602         if ((instance >= 0) && (targ >= 0)
1603          && (instance < NUM_ELEMENTS(aic7xxx_tag_info))
1604          && (targ < AHC_NUM_TARGETS)) {
1605                 aic7xxx_tag_info[instance].tag_commands[targ] = value & 0xff;
1606                 if (bootverbose)
1607                         printf("tag_info[%d:%d] = %d\n", instance, targ, value);
1608         }
1609 }
1610
1611 static void
1612 ahc_linux_setup_dv(u_long arg, int instance, int targ, int32_t value)
1613 {
1614
1615         if ((instance >= 0)
1616          && (instance < NUM_ELEMENTS(aic7xxx_dv_settings))) {
1617                 aic7xxx_dv_settings[instance] = value;
1618                 if (bootverbose)
1619                         printf("dv[%d] = %d\n", instance, value);
1620         }
1621 }
1622
1623 /*
1624  * Handle Linux boot parameters. This routine allows for assigning a value
1625  * to a parameter with a ':' between the parameter and the value.
1626  * ie. aic7xxx=stpwlev:1,extended
1627  */
1628 static int
1629 aic7xxx_setup(char *s)
1630 {
1631         int     i, n;
1632         char   *p;
1633         char   *end;
1634
1635         static struct {
1636                 const char *name;
1637                 uint32_t *flag;
1638         } options[] = {
1639                 { "extended", &aic7xxx_extended },
1640                 { "no_reset", &aic7xxx_no_reset },
1641                 { "verbose", &aic7xxx_verbose },
1642                 { "allow_memio", &aic7xxx_allow_memio},
1643 #ifdef AHC_DEBUG
1644                 { "debug", &ahc_debug },
1645 #endif
1646                 { "reverse_scan", &aic7xxx_reverse_scan },
1647                 { "no_probe", &aic7xxx_probe_eisa_vl },
1648                 { "probe_eisa_vl", &aic7xxx_probe_eisa_vl },
1649                 { "periodic_otag", &aic7xxx_periodic_otag },
1650                 { "pci_parity", &aic7xxx_pci_parity },
1651                 { "seltime", &aic7xxx_seltime },
1652                 { "tag_info", NULL },
1653                 { "global_tag_depth", NULL },
1654                 { "dv", NULL }
1655         };
1656
1657         end = strchr(s, '\0');
1658
1659         /*
1660          * XXX ia64 gcc isn't smart enough to know that NUM_ELEMENTS
1661          * will never be 0 in this case.
1662          */
1663         n = 0;
1664
1665         while ((p = strsep(&s, ",.")) != NULL) {
1666                 if (*p == '\0')
1667                         continue;
1668                 for (i = 0; i < NUM_ELEMENTS(options); i++) {
1669
1670                         n = strlen(options[i].name);
1671                         if (strncmp(options[i].name, p, n) == 0)
1672                                 break;
1673                 }
1674                 if (i == NUM_ELEMENTS(options))
1675                         continue;
1676
1677                 if (strncmp(p, "global_tag_depth", n) == 0) {
1678                         ahc_linux_setup_tag_info_global(p + n);
1679                 } else if (strncmp(p, "tag_info", n) == 0) {
1680                         s = aic_parse_brace_option("tag_info", p + n, end,
1681                             2, ahc_linux_setup_tag_info, 0);
1682                 } else if (strncmp(p, "dv", n) == 0) {
1683                         s = aic_parse_brace_option("dv", p + n, end, 1,
1684                             ahc_linux_setup_dv, 0);
1685                 } else if (p[n] == ':') {
1686                         *(options[i].flag) = simple_strtoul(p + n + 1, NULL, 0);
1687                 } else if (strncmp(p, "verbose", n) == 0) {
1688                         *(options[i].flag) = 1;
1689                 } else {
1690                         *(options[i].flag) ^= 0xFFFFFFFF;
1691                 }
1692         }
1693         return 1;
1694 }
1695
1696 #if LINUX_VERSION_CODE > KERNEL_VERSION(2,3,0)
1697 __setup("aic7xxx=", aic7xxx_setup);
1698 #endif
1699
1700 uint32_t aic7xxx_verbose;
1701
1702 int
1703 ahc_linux_register_host(struct ahc_softc *ahc, Scsi_Host_Template *template)
1704 {
1705         char     buf[80];
1706         struct   Scsi_Host *host;
1707         char    *new_name;
1708         u_long   s;
1709         u_int    targ_offset;
1710
1711         template->name = ahc->description;
1712         host = scsi_host_alloc(template, sizeof(struct ahc_softc *));
1713         if (host == NULL)
1714                 return (ENOMEM);
1715
1716         *((struct ahc_softc **)host->hostdata) = ahc;
1717         ahc_lock(ahc, &s);
1718 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
1719         scsi_assign_lock(host, &ahc->platform_data->spin_lock);
1720 #elif AHC_SCSI_HAS_HOST_LOCK != 0
1721         host->lock = &ahc->platform_data->spin_lock;
1722 #endif
1723         ahc->platform_data->host = host;
1724         host->can_queue = AHC_MAX_QUEUE;
1725         host->cmd_per_lun = 2;
1726         /* XXX No way to communicate the ID for multiple channels */
1727         host->this_id = ahc->our_id;
1728         host->irq = ahc->platform_data->irq;
1729         host->max_id = (ahc->features & AHC_WIDE) ? 16 : 8;
1730         host->max_lun = AHC_NUM_LUNS;
1731         host->max_channel = (ahc->features & AHC_TWIN) ? 1 : 0;
1732         host->sg_tablesize = AHC_NSEG;
1733         ahc_set_unit(ahc, ahc_linux_next_unit());
1734         sprintf(buf, "scsi%d", host->host_no);
1735         new_name = malloc(strlen(buf) + 1, M_DEVBUF, M_NOWAIT);
1736         if (new_name != NULL) {
1737                 strcpy(new_name, buf);
1738                 ahc_set_name(ahc, new_name);
1739         }
1740         host->unique_id = ahc->unit;
1741 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,4) && \
1742     LINUX_VERSION_CODE  < KERNEL_VERSION(2,5,0)
1743         scsi_set_pci_device(host, ahc->dev_softc);
1744 #endif
1745         ahc_linux_initialize_scsi_bus(ahc);
1746         ahc_unlock(ahc, &s);
1747         ahc->platform_data->dv_pid = kernel_thread(ahc_linux_dv_thread, ahc, 0);
1748         ahc_lock(ahc, &s);
1749         if (ahc->platform_data->dv_pid < 0) {
1750                 printf("%s: Failed to create DV thread, error= %d\n",
1751                        ahc_name(ahc), ahc->platform_data->dv_pid);
1752                 return (-ahc->platform_data->dv_pid);
1753         }
1754         /*
1755          * Initially allocate *all* of our linux target objects
1756          * so that the DV thread will scan them all in parallel
1757          * just after driver initialization.  Any device that
1758          * does not exist will have its target object destroyed
1759          * by the selection timeout handler.  In the case of a
1760          * device that appears after the initial DV scan, async
1761          * negotiation will occur for the first command, and DV
1762          * will comence should that first command be successful.
1763          */
1764         for (targ_offset = 0;
1765              targ_offset < host->max_id * (host->max_channel + 1);
1766              targ_offset++) {
1767                 u_int channel;
1768                 u_int target;
1769
1770                 channel = 0;
1771                 target = targ_offset;
1772                 if (target > 7
1773                  && (ahc->features & AHC_TWIN) != 0) {
1774                         channel = 1;
1775                         target &= 0x7;
1776                 }
1777                 /*
1778                  * Skip our own ID.  Some Compaq/HP storage devices
1779                  * have enclosure management devices that respond to
1780                  * single bit selection (i.e. selecting ourselves).
1781                  * It is expected that either an external application
1782                  * or a modified kernel will be used to probe this
1783                  * ID if it is appropriate.  To accommodate these
1784                  * installations, ahc_linux_alloc_target() will allocate
1785                  * for our ID if asked to do so.
1786                  */
1787                 if ((channel == 0 && target == ahc->our_id)
1788                  || (channel == 1 && target == ahc->our_id_b))
1789                         continue;
1790
1791                 ahc_linux_alloc_target(ahc, channel, target);
1792         }
1793         ahc_intr_enable(ahc, TRUE);
1794         ahc_linux_start_dv(ahc);
1795         ahc_unlock(ahc, &s);
1796
1797 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
1798         scsi_add_host(host, (ahc->dev_softc ? &ahc->dev_softc->dev : NULL)); /* XXX handle failure */
1799         scsi_scan_host(host);
1800 #endif
1801         return (0);
1802 }
1803
1804 uint64_t
1805 ahc_linux_get_memsize(void)
1806 {
1807         struct sysinfo si;
1808
1809         si_meminfo(&si);
1810         return ((uint64_t)si.totalram << PAGE_SHIFT);
1811 }
1812
1813 /*
1814  * Find the smallest available unit number to use
1815  * for a new device.  We don't just use a static
1816  * count to handle the "repeated hot-(un)plug"
1817  * scenario.
1818  */
1819 static int
1820 ahc_linux_next_unit(void)
1821 {
1822         struct ahc_softc *ahc;
1823         int unit;
1824
1825         unit = 0;
1826 retry:
1827         TAILQ_FOREACH(ahc, &ahc_tailq, links) {
1828                 if (ahc->unit == unit) {
1829                         unit++;
1830                         goto retry;
1831                 }
1832         }
1833         return (unit);
1834 }
1835
1836 /*
1837  * Place the SCSI bus into a known state by either resetting it,
1838  * or forcing transfer negotiations on the next command to any
1839  * target.
1840  */
1841 void
1842 ahc_linux_initialize_scsi_bus(struct ahc_softc *ahc)
1843 {
1844         int i;
1845         int numtarg;
1846
1847         i = 0;
1848         numtarg = 0;
1849
1850         if (aic7xxx_no_reset != 0)
1851                 ahc->flags &= ~(AHC_RESET_BUS_A|AHC_RESET_BUS_B);
1852
1853         if ((ahc->flags & AHC_RESET_BUS_A) != 0)
1854                 ahc_reset_channel(ahc, 'A', /*initiate_reset*/TRUE);
1855         else
1856                 numtarg = (ahc->features & AHC_WIDE) ? 16 : 8;
1857
1858         if ((ahc->features & AHC_TWIN) != 0) {
1859
1860                 if ((ahc->flags & AHC_RESET_BUS_B) != 0) {
1861                         ahc_reset_channel(ahc, 'B', /*initiate_reset*/TRUE);
1862                 } else {
1863                         if (numtarg == 0)
1864                                 i = 8;
1865                         numtarg += 8;
1866                 }
1867         }
1868
1869         /*
1870          * Force negotiation to async for all targets that
1871          * will not see an initial bus reset.
1872          */
1873         for (; i < numtarg; i++) {
1874                 struct ahc_devinfo devinfo;
1875                 struct ahc_initiator_tinfo *tinfo;
1876                 struct ahc_tmode_tstate *tstate;
1877                 u_int our_id;
1878                 u_int target_id;
1879                 char channel;
1880
1881                 channel = 'A';
1882                 our_id = ahc->our_id;
1883                 target_id = i;
1884                 if (i > 7 && (ahc->features & AHC_TWIN) != 0) {
1885                         channel = 'B';
1886                         our_id = ahc->our_id_b;
1887                         target_id = i % 8;
1888                 }
1889                 tinfo = ahc_fetch_transinfo(ahc, channel, our_id,
1890                                             target_id, &tstate);
1891                 ahc_compile_devinfo(&devinfo, our_id, target_id,
1892                                     CAM_LUN_WILDCARD, channel, ROLE_INITIATOR);
1893                 ahc_update_neg_request(ahc, &devinfo, tstate,
1894                                        tinfo, AHC_NEG_ALWAYS);
1895         }
1896         /* Give the bus some time to recover */
1897         if ((ahc->flags & (AHC_RESET_BUS_A|AHC_RESET_BUS_B)) != 0) {
1898                 ahc_linux_freeze_simq(ahc);
1899                 init_timer(&ahc->platform_data->reset_timer);
1900                 ahc->platform_data->reset_timer.data = (u_long)ahc;
1901                 ahc->platform_data->reset_timer.expires =
1902                     jiffies + (AIC7XXX_RESET_DELAY * HZ)/1000;
1903                 ahc->platform_data->reset_timer.function =
1904                     ahc_linux_release_simq;
1905                 add_timer(&ahc->platform_data->reset_timer);
1906         }
1907 }
1908
1909 int
1910 ahc_platform_alloc(struct ahc_softc *ahc, void *platform_arg)
1911 {
1912
1913         ahc->platform_data =
1914             malloc(sizeof(struct ahc_platform_data), M_DEVBUF, M_NOWAIT);
1915         if (ahc->platform_data == NULL)
1916                 return (ENOMEM);
1917         memset(ahc->platform_data, 0, sizeof(struct ahc_platform_data));
1918         TAILQ_INIT(&ahc->platform_data->completeq);
1919         TAILQ_INIT(&ahc->platform_data->device_runq);
1920         ahc->platform_data->irq = AHC_LINUX_NOIRQ;
1921         ahc->platform_data->hw_dma_mask = 0xFFFFFFFF;
1922         ahc_lockinit(ahc);
1923         ahc_done_lockinit(ahc);
1924         init_timer(&ahc->platform_data->completeq_timer);
1925         ahc->platform_data->completeq_timer.data = (u_long)ahc;
1926         ahc->platform_data->completeq_timer.function =
1927             (ahc_linux_callback_t *)ahc_linux_thread_run_complete_queue;
1928 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,3,0)
1929         init_MUTEX_LOCKED(&ahc->platform_data->eh_sem);
1930         init_MUTEX_LOCKED(&ahc->platform_data->dv_sem);
1931         init_MUTEX_LOCKED(&ahc->platform_data->dv_cmd_sem);
1932 #else
1933         ahc->platform_data->eh_sem = MUTEX_LOCKED;
1934         ahc->platform_data->dv_sem = MUTEX_LOCKED;
1935         ahc->platform_data->dv_cmd_sem = MUTEX_LOCKED;
1936 #endif
1937 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0)
1938         tasklet_init(&ahc->platform_data->runq_tasklet, ahc_runq_tasklet,
1939                      (unsigned long)ahc);
1940 #endif
1941         ahc->seltime = (aic7xxx_seltime & 0x3) << 4;
1942         ahc->seltime_b = (aic7xxx_seltime & 0x3) << 4;
1943         if (aic7xxx_pci_parity == 0)
1944                 ahc->flags |= AHC_DISABLE_PCI_PERR;
1945
1946         return (0);
1947 }
1948
1949 void
1950 ahc_platform_free(struct ahc_softc *ahc)
1951 {
1952         struct ahc_linux_target *targ;
1953         struct ahc_linux_device *dev;
1954         int i, j;
1955
1956         if (ahc->platform_data != NULL) {
1957                 del_timer_sync(&ahc->platform_data->completeq_timer);
1958                 ahc_linux_kill_dv_thread(ahc);
1959 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0)
1960                 tasklet_kill(&ahc->platform_data->runq_tasklet);
1961 #endif
1962                 if (ahc->platform_data->host != NULL) {
1963 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
1964                         scsi_remove_host(ahc->platform_data->host);
1965 #endif
1966                         scsi_host_put(ahc->platform_data->host);
1967                 }
1968
1969                 /* destroy all of the device and target objects */
1970                 for (i = 0; i < AHC_NUM_TARGETS; i++) {
1971                         targ = ahc->platform_data->targets[i];
1972                         if (targ != NULL) {
1973                                 /* Keep target around through the loop. */
1974                                 targ->refcount++;
1975                                 for (j = 0; j < AHC_NUM_LUNS; j++) {
1976
1977                                         if (targ->devices[j] == NULL)
1978                                                 continue;
1979                                         dev = targ->devices[j];
1980                                         ahc_linux_free_device(ahc, dev);
1981                                 }
1982                                 /*
1983                                  * Forcibly free the target now that
1984                                  * all devices are gone.
1985                                  */
1986                                 ahc_linux_free_target(ahc, targ);
1987                         }
1988                 }
1989
1990                 if (ahc->platform_data->irq != AHC_LINUX_NOIRQ)
1991                         free_irq(ahc->platform_data->irq, ahc);
1992                 if (ahc->tag == BUS_SPACE_PIO
1993                  && ahc->bsh.ioport != 0)
1994                         release_region(ahc->bsh.ioport, 256);
1995                 if (ahc->tag == BUS_SPACE_MEMIO
1996                  && ahc->bsh.maddr != NULL) {
1997                         u_long base_addr;
1998
1999                         base_addr = (u_long)ahc->bsh.maddr;
2000                         base_addr &= PAGE_MASK;
2001                         iounmap((void *)base_addr);
2002 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0)
2003                         release_mem_region(ahc->platform_data->mem_busaddr,
2004                                            0x1000);
2005 #endif
2006                 }
2007 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0) && \
2008     LINUX_VERSION_CODE  < KERNEL_VERSION(2,5,0)
2009                 /*
2010                  * In 2.4 we detach from the scsi midlayer before the PCI
2011                  * layer invokes our remove callback.  No per-instance
2012                  * detach is provided, so we must reach inside the PCI
2013                  * subsystem's internals and detach our driver manually.
2014                  */
2015                 if (ahc->dev_softc != NULL)
2016                         ahc->dev_softc->driver = NULL;
2017 #endif
2018                 free(ahc->platform_data, M_DEVBUF);
2019         }
2020 }
2021
2022 void
2023 ahc_platform_freeze_devq(struct ahc_softc *ahc, struct scb *scb)
2024 {
2025         ahc_platform_abort_scbs(ahc, SCB_GET_TARGET(ahc, scb),
2026                                 SCB_GET_CHANNEL(ahc, scb),
2027                                 SCB_GET_LUN(scb), SCB_LIST_NULL,
2028                                 ROLE_UNKNOWN, CAM_REQUEUE_REQ);
2029 }
2030
2031 void
2032 ahc_platform_set_tags(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
2033                       ahc_queue_alg alg)
2034 {
2035         struct ahc_linux_device *dev;
2036         int was_queuing;
2037         int now_queuing;
2038
2039         dev = ahc_linux_get_device(ahc, devinfo->channel - 'A',
2040                                    devinfo->target,
2041                                    devinfo->lun, /*alloc*/FALSE);
2042         if (dev == NULL)
2043                 return;
2044         was_queuing = dev->flags & (AHC_DEV_Q_BASIC|AHC_DEV_Q_TAGGED);
2045         switch (alg) {
2046         default:
2047         case AHC_QUEUE_NONE:
2048                 now_queuing = 0;
2049                 break; 
2050         case AHC_QUEUE_BASIC:
2051                 now_queuing = AHC_DEV_Q_BASIC;
2052                 break;
2053         case AHC_QUEUE_TAGGED:
2054                 now_queuing = AHC_DEV_Q_TAGGED;
2055                 break;
2056         }
2057         if ((dev->flags & AHC_DEV_FREEZE_TIL_EMPTY) == 0
2058          && (was_queuing != now_queuing)
2059          && (dev->active != 0)) {
2060                 dev->flags |= AHC_DEV_FREEZE_TIL_EMPTY;
2061                 dev->qfrozen++;
2062         }
2063
2064         dev->flags &= ~(AHC_DEV_Q_BASIC|AHC_DEV_Q_TAGGED|AHC_DEV_PERIODIC_OTAG);
2065         if (now_queuing) {
2066                 u_int usertags;
2067
2068                 usertags = ahc_linux_user_tagdepth(ahc, devinfo);
2069                 if (!was_queuing) {
2070                         /*
2071                          * Start out agressively and allow our
2072                          * dynamic queue depth algorithm to take
2073                          * care of the rest.
2074                          */
2075                         dev->maxtags = usertags;
2076                         dev->openings = dev->maxtags - dev->active;
2077                 }
2078                 if (dev->maxtags == 0) {
2079                         /*
2080                          * Queueing is disabled by the user.
2081                          */
2082                         dev->openings = 1;
2083                 } else if (alg == AHC_QUEUE_TAGGED) {
2084                         dev->flags |= AHC_DEV_Q_TAGGED;
2085                         if (aic7xxx_periodic_otag != 0)
2086                                 dev->flags |= AHC_DEV_PERIODIC_OTAG;
2087                 } else
2088                         dev->flags |= AHC_DEV_Q_BASIC;
2089         } else {
2090                 /* We can only have one opening. */
2091                 dev->maxtags = 0;
2092                 dev->openings =  1 - dev->active;
2093         }
2094 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
2095         if (dev->scsi_device != NULL) {
2096                 switch ((dev->flags & (AHC_DEV_Q_BASIC|AHC_DEV_Q_TAGGED))) {
2097                 case AHC_DEV_Q_BASIC:
2098                         scsi_adjust_queue_depth(dev->scsi_device,
2099                                                 MSG_SIMPLE_TASK,
2100                                                 dev->openings + dev->active);
2101                         break;
2102                 case AHC_DEV_Q_TAGGED:
2103                         scsi_adjust_queue_depth(dev->scsi_device,
2104                                                 MSG_ORDERED_TASK,
2105                                                 dev->openings + dev->active);
2106                         break;
2107                 default:
2108                         /*
2109                          * We allow the OS to queue 2 untagged transactions to
2110                          * us at any time even though we can only execute them
2111                          * serially on the controller/device.  This should
2112                          * remove some latency.
2113                          */
2114                         scsi_adjust_queue_depth(dev->scsi_device,
2115                                                 /*NON-TAGGED*/0,
2116                                                 /*queue depth*/2);
2117                         break;
2118                 }
2119         }
2120 #endif
2121 }
2122
2123 int
2124 ahc_platform_abort_scbs(struct ahc_softc *ahc, int target, char channel,
2125                         int lun, u_int tag, role_t role, uint32_t status)
2126 {
2127         int chan;
2128         int maxchan;
2129         int targ;
2130         int maxtarg;
2131         int clun;
2132         int maxlun;
2133         int count;
2134
2135         if (tag != SCB_LIST_NULL)
2136                 return (0);
2137
2138         chan = 0;
2139         if (channel != ALL_CHANNELS) {
2140                 chan = channel - 'A';
2141                 maxchan = chan + 1;
2142         } else {
2143                 maxchan = (ahc->features & AHC_TWIN) ? 2 : 1;
2144         }
2145         targ = 0;
2146         if (target != CAM_TARGET_WILDCARD) {
2147                 targ = target;
2148                 maxtarg = targ + 1;
2149         } else {
2150                 maxtarg = (ahc->features & AHC_WIDE) ? 16 : 8;
2151         }
2152         clun = 0;
2153         if (lun != CAM_LUN_WILDCARD) {
2154                 clun = lun;
2155                 maxlun = clun + 1;
2156         } else {
2157                 maxlun = AHC_NUM_LUNS;
2158         }
2159
2160         count = 0;
2161         for (; chan < maxchan; chan++) {
2162
2163                 for (; targ < maxtarg; targ++) {
2164
2165                         for (; clun < maxlun; clun++) {
2166                                 struct ahc_linux_device *dev;
2167                                 struct ahc_busyq *busyq;
2168                                 struct ahc_cmd *acmd;
2169
2170                                 dev = ahc_linux_get_device(ahc, chan,
2171                                                            targ, clun,
2172                                                            /*alloc*/FALSE);
2173                                 if (dev == NULL)
2174                                         continue;
2175
2176                                 busyq = &dev->busyq;
2177                                 while ((acmd = TAILQ_FIRST(busyq)) != NULL) {
2178                                         Scsi_Cmnd *cmd;
2179
2180                                         cmd = &acmd_scsi_cmd(acmd);
2181                                         TAILQ_REMOVE(busyq, acmd,
2182                                                      acmd_links.tqe);
2183                                         count++;
2184                                         cmd->result = status << 16;
2185                                         ahc_linux_queue_cmd_complete(ahc, cmd);
2186                                 }
2187                         }
2188                 }
2189         }
2190
2191         return (count);
2192 }
2193
2194 static void
2195 ahc_linux_thread_run_complete_queue(struct ahc_softc *ahc)
2196 {
2197         u_long flags;
2198
2199         ahc_lock(ahc, &flags);
2200         del_timer(&ahc->platform_data->completeq_timer);
2201         ahc->platform_data->flags &= ~AHC_RUN_CMPLT_Q_TIMER;
2202         ahc_linux_run_complete_queue(ahc);
2203         ahc_unlock(ahc, &flags);
2204 }
2205
2206 static void
2207 ahc_linux_start_dv(struct ahc_softc *ahc)
2208 {
2209
2210         /*
2211          * Freeze the simq and signal ahc_linux_queue to not let any
2212          * more commands through.
2213          */
2214         if ((ahc->platform_data->flags & AHC_DV_ACTIVE) == 0) {
2215 #ifdef AHC_DEBUG
2216                 if (ahc_debug & AHC_SHOW_DV)
2217                         printf("%s: Waking DV thread\n", ahc_name(ahc));
2218 #endif
2219
2220                 ahc->platform_data->flags |= AHC_DV_ACTIVE;
2221                 ahc_linux_freeze_simq(ahc);
2222
2223                 /* Wake up the DV kthread */
2224                 up(&ahc->platform_data->dv_sem);
2225         }
2226 }
2227
2228 static void
2229 ahc_linux_kill_dv_thread(struct ahc_softc *ahc)
2230 {
2231         u_long s;
2232
2233         ahc_lock(ahc, &s);
2234         if (ahc->platform_data->dv_pid != 0) {
2235                 ahc->platform_data->flags |= AHC_DV_SHUTDOWN;
2236                 ahc_unlock(ahc, &s);
2237                 up(&ahc->platform_data->dv_sem);
2238
2239                 /*
2240                  * Use the eh_sem as an indicator that the
2241                  * dv thread is exiting.  Note that the dv
2242                  * thread must still return after performing
2243                  * the up on our semaphore before it has
2244                  * completely exited this module.  Unfortunately,
2245                  * there seems to be no easy way to wait for the
2246                  * exit of a thread for which you are not the
2247                  * parent (dv threads are parented by init).
2248                  * Cross your fingers...
2249                  */
2250                 down(&ahc->platform_data->eh_sem);
2251
2252                 /*
2253                  * Mark the dv thread as already dead.  This
2254                  * avoids attempting to kill it a second time.
2255                  * This is necessary because we must kill the
2256                  * DV thread before calling ahc_free() in the
2257                  * module shutdown case to avoid bogus locking
2258                  * in the SCSI mid-layer, but we ahc_free() is
2259                  * called without killing the DV thread in the
2260                  * instance detach case, so ahc_platform_free()
2261                  * calls us again to verify that the DV thread
2262                  * is dead.
2263                  */
2264                 ahc->platform_data->dv_pid = 0;
2265         } else {
2266                 ahc_unlock(ahc, &s);
2267         }
2268 }
2269
2270 static int
2271 ahc_linux_dv_thread(void *data)
2272 {
2273         struct  ahc_softc *ahc;
2274         int     target;
2275         u_long  s;
2276
2277         ahc = (struct ahc_softc *)data;
2278
2279 #ifdef AHC_DEBUG
2280         if (ahc_debug & AHC_SHOW_DV)
2281                 printf("Launching DV Thread\n");
2282 #endif
2283
2284         /*
2285          * Complete thread creation.
2286          */
2287         lock_kernel();
2288 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
2289         /*
2290          * Don't care about any signals.
2291          */
2292         siginitsetinv(&current->blocked, 0);
2293
2294         daemonize();
2295         sprintf(current->comm, "ahc_dv_%d", ahc->unit);
2296 #else
2297         daemonize("ahc_dv_%d", ahc->unit);
2298         current->flags |= PF_FREEZE;
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         targ = dev->target;
3977         targ->devices[dev->lun] = NULL;
3978         free(dev, M_DEVBUF);
3979         targ->refcount--;
3980         if (targ->refcount == 0
3981          && (targ->flags & AHC_DV_REQUIRED) == 0)
3982                 ahc_linux_free_target(ahc, targ);
3983 }
3984
3985 static void
3986 ahc_linux_free_device(struct ahc_softc *ahc, struct ahc_linux_device *dev)
3987 {
3988         del_timer_sync(&dev->timer);
3989         __ahc_linux_free_device(ahc, dev);
3990 }
3991
3992 void
3993 ahc_send_async(struct ahc_softc *ahc, char channel,
3994                u_int target, u_int lun, ac_code code, void *arg)
3995 {
3996         switch (code) {
3997         case AC_TRANSFER_NEG:
3998         {
3999                 char    buf[80];
4000                 struct  ahc_linux_target *targ;
4001                 struct  info_str info;
4002                 struct  ahc_initiator_tinfo *tinfo;
4003                 struct  ahc_tmode_tstate *tstate;
4004                 int     target_offset;
4005
4006                 info.buffer = buf;
4007                 info.length = sizeof(buf);
4008                 info.offset = 0;
4009                 info.pos = 0;
4010                 tinfo = ahc_fetch_transinfo(ahc, channel,
4011                                                 channel == 'A' ? ahc->our_id
4012                                                                : ahc->our_id_b,
4013                                                 target, &tstate);
4014
4015                 /*
4016                  * Don't bother reporting results while
4017                  * negotiations are still pending.
4018                  */
4019                 if (tinfo->curr.period != tinfo->goal.period
4020                  || tinfo->curr.width != tinfo->goal.width
4021                  || tinfo->curr.offset != tinfo->goal.offset
4022                  || tinfo->curr.ppr_options != tinfo->goal.ppr_options)
4023                         if (bootverbose == 0)
4024                                 break;
4025
4026                 /*
4027                  * Don't bother reporting results that
4028                  * are identical to those last reported.
4029                  */
4030                 target_offset = target;
4031                 if (channel == 'B')
4032                         target_offset += 8;
4033                 targ = ahc->platform_data->targets[target_offset];
4034                 if (targ == NULL)
4035                         break;
4036                 if (tinfo->curr.period == targ->last_tinfo.period
4037                  && tinfo->curr.width == targ->last_tinfo.width
4038                  && tinfo->curr.offset == targ->last_tinfo.offset
4039                  && tinfo->curr.ppr_options == targ->last_tinfo.ppr_options)
4040                         if (bootverbose == 0)
4041                                 break;
4042
4043                 targ->last_tinfo.period = tinfo->curr.period;
4044                 targ->last_tinfo.width = tinfo->curr.width;
4045                 targ->last_tinfo.offset = tinfo->curr.offset;
4046                 targ->last_tinfo.ppr_options = tinfo->curr.ppr_options;
4047
4048                 printf("(%s:%c:", ahc_name(ahc), channel);
4049                 if (target == CAM_TARGET_WILDCARD)
4050                         printf("*): ");
4051                 else
4052                         printf("%d): ", target);
4053                 ahc_format_transinfo(&info, &tinfo->curr);
4054                 if (info.pos < info.length)
4055                         *info.buffer = '\0';
4056                 else
4057                         buf[info.length - 1] = '\0';
4058                 printf("%s", buf);
4059                 break;
4060         }
4061         case AC_SENT_BDR:
4062         {
4063 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
4064                 WARN_ON(lun != CAM_LUN_WILDCARD);
4065                 scsi_report_device_reset(ahc->platform_data->host,
4066                                          channel - 'A', target);
4067 #elif LINUX_VERSION_CODE >= KERNEL_VERSION(2,3,0)
4068                 Scsi_Device *scsi_dev;
4069
4070                 /*
4071                  * Find the SCSI device associated with this
4072                  * request and indicate that a UA is expected.
4073                  */
4074                 for (scsi_dev = ahc->platform_data->host->host_queue;
4075                      scsi_dev != NULL; scsi_dev = scsi_dev->next) {
4076                         if (channel - 'A' == scsi_dev->channel
4077                          && target == scsi_dev->id
4078                          && (lun == CAM_LUN_WILDCARD
4079                           || lun == scsi_dev->lun)) {
4080                                 scsi_dev->was_reset = 1;
4081                                 scsi_dev->expecting_cc_ua = 1;
4082                         }
4083                 }
4084 #endif
4085                 break;
4086         }
4087         case AC_BUS_RESET:
4088 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,3,0)
4089                 if (ahc->platform_data->host != NULL) {
4090                         scsi_report_bus_reset(ahc->platform_data->host,
4091                                               channel - 'A');
4092                 }
4093 #endif
4094                 break;
4095         default:
4096                 panic("ahc_send_async: Unexpected async event");
4097         }
4098 }
4099
4100 /*
4101  * Calls the higher level scsi done function and frees the scb.
4102  */
4103 void
4104 ahc_done(struct ahc_softc *ahc, struct scb *scb)
4105 {
4106         Scsi_Cmnd *cmd;
4107         struct     ahc_linux_device *dev;
4108
4109         LIST_REMOVE(scb, pending_links);
4110         if ((scb->flags & SCB_UNTAGGEDQ) != 0) {
4111                 struct scb_tailq *untagged_q;
4112                 int target_offset;
4113
4114                 target_offset = SCB_GET_TARGET_OFFSET(ahc, scb);
4115                 untagged_q = &(ahc->untagged_queues[target_offset]);
4116                 TAILQ_REMOVE(untagged_q, scb, links.tqe);
4117                 ahc_run_untagged_queue(ahc, untagged_q);
4118         }
4119
4120         if ((scb->flags & SCB_ACTIVE) == 0) {
4121                 printf("SCB %d done'd twice\n", scb->hscb->tag);
4122                 ahc_dump_card_state(ahc);
4123                 panic("Stopping for safety");
4124         }
4125         cmd = scb->io_ctx;
4126         dev = scb->platform_data->dev;
4127         dev->active--;
4128         dev->openings++;
4129         if ((cmd->result & (CAM_DEV_QFRZN << 16)) != 0) {
4130                 cmd->result &= ~(CAM_DEV_QFRZN << 16);
4131                 dev->qfrozen--;
4132         }
4133         ahc_linux_unmap_scb(ahc, scb);
4134
4135         /*
4136          * Guard against stale sense data.
4137          * The Linux mid-layer assumes that sense
4138          * was retrieved anytime the first byte of
4139          * the sense buffer looks "sane".
4140          */
4141         cmd->sense_buffer[0] = 0;
4142         if (ahc_get_transaction_status(scb) == CAM_REQ_INPROG) {
4143                 uint32_t amount_xferred;
4144
4145                 amount_xferred =
4146                     ahc_get_transfer_length(scb) - ahc_get_residual(scb);
4147                 if ((scb->flags & SCB_TRANSMISSION_ERROR) != 0) {
4148 #ifdef AHC_DEBUG
4149                         if ((ahc_debug & AHC_SHOW_MISC) != 0) {
4150                                 ahc_print_path(ahc, scb);
4151                                 printf("Set CAM_UNCOR_PARITY\n");
4152                         }
4153 #endif
4154                         ahc_set_transaction_status(scb, CAM_UNCOR_PARITY);
4155 #ifdef AHC_REPORT_UNDERFLOWS
4156                 /*
4157                  * This code is disabled by default as some
4158                  * clients of the SCSI system do not properly
4159                  * initialize the underflow parameter.  This
4160                  * results in spurious termination of commands
4161                  * that complete as expected (e.g. underflow is
4162                  * allowed as command can return variable amounts
4163                  * of data.
4164                  */
4165                 } else if (amount_xferred < scb->io_ctx->underflow) {
4166                         u_int i;
4167
4168                         ahc_print_path(ahc, scb);
4169                         printf("CDB:");
4170                         for (i = 0; i < scb->io_ctx->cmd_len; i++)
4171                                 printf(" 0x%x", scb->io_ctx->cmnd[i]);
4172                         printf("\n");
4173                         ahc_print_path(ahc, scb);
4174                         printf("Saw underflow (%ld of %ld bytes). "
4175                                "Treated as error\n",
4176                                 ahc_get_residual(scb),
4177                                 ahc_get_transfer_length(scb));
4178                         ahc_set_transaction_status(scb, CAM_DATA_RUN_ERR);
4179 #endif
4180                 } else {
4181                         ahc_set_transaction_status(scb, CAM_REQ_CMP);
4182                 }
4183         } else if (ahc_get_transaction_status(scb) == CAM_SCSI_STATUS_ERROR) {
4184                 ahc_linux_handle_scsi_status(ahc, dev, scb);
4185         } else if (ahc_get_transaction_status(scb) == CAM_SEL_TIMEOUT) {
4186                 dev->flags |= AHC_DEV_UNCONFIGURED;
4187                 if (AHC_DV_CMD(cmd) == FALSE)
4188                         dev->target->flags &= ~AHC_DV_REQUIRED;
4189         }
4190         /*
4191          * Start DV for devices that require it assuming the first command
4192          * sent does not result in a selection timeout.
4193          */
4194         if (ahc_get_transaction_status(scb) != CAM_SEL_TIMEOUT
4195          && (dev->target->flags & AHC_DV_REQUIRED) != 0)
4196                 ahc_linux_start_dv(ahc);
4197
4198         if (dev->openings == 1
4199          && ahc_get_transaction_status(scb) == CAM_REQ_CMP
4200          && ahc_get_scsi_status(scb) != SCSI_STATUS_QUEUE_FULL)
4201                 dev->tag_success_count++;
4202         /*
4203          * Some devices deal with temporary internal resource
4204          * shortages by returning queue full.  When the queue
4205          * full occurrs, we throttle back.  Slowly try to get
4206          * back to our previous queue depth.
4207          */
4208         if ((dev->openings + dev->active) < dev->maxtags
4209          && dev->tag_success_count > AHC_TAG_SUCCESS_INTERVAL) {
4210                 dev->tag_success_count = 0;
4211                 dev->openings++;
4212         }
4213
4214         if (dev->active == 0)
4215                 dev->commands_since_idle_or_otag = 0;
4216
4217         if (TAILQ_EMPTY(&dev->busyq)) {
4218                 if ((dev->flags & AHC_DEV_UNCONFIGURED) != 0
4219                  && dev->active == 0
4220                  && (dev->flags & AHC_DEV_TIMER_ACTIVE) == 0)
4221                         ahc_linux_free_device(ahc, dev);
4222         } else if ((dev->flags & AHC_DEV_ON_RUN_LIST) == 0) {
4223                 TAILQ_INSERT_TAIL(&ahc->platform_data->device_runq, dev, links);
4224                 dev->flags |= AHC_DEV_ON_RUN_LIST;
4225         }
4226
4227         if ((scb->flags & SCB_RECOVERY_SCB) != 0) {
4228                 printf("Recovery SCB completes\n");
4229                 if (ahc_get_transaction_status(scb) == CAM_BDR_SENT
4230                  || ahc_get_transaction_status(scb) == CAM_REQ_ABORTED)
4231                         ahc_set_transaction_status(scb, CAM_CMD_TIMEOUT);
4232                 if ((ahc->platform_data->flags & AHC_UP_EH_SEMAPHORE) != 0) {
4233                         ahc->platform_data->flags &= ~AHC_UP_EH_SEMAPHORE;
4234                         up(&ahc->platform_data->eh_sem);
4235                 }
4236         }
4237
4238         ahc_free_scb(ahc, scb);
4239         ahc_linux_queue_cmd_complete(ahc, cmd);
4240
4241         if ((ahc->platform_data->flags & AHC_DV_WAIT_SIMQ_EMPTY) != 0
4242          && LIST_FIRST(&ahc->pending_scbs) == NULL) {
4243                 ahc->platform_data->flags &= ~AHC_DV_WAIT_SIMQ_EMPTY;
4244                 up(&ahc->platform_data->dv_sem);
4245         }
4246                 
4247 }
4248
4249 static void
4250 ahc_linux_handle_scsi_status(struct ahc_softc *ahc,
4251                              struct ahc_linux_device *dev, struct scb *scb)
4252 {
4253         struct  ahc_devinfo devinfo;
4254
4255         ahc_compile_devinfo(&devinfo,
4256                             ahc->our_id,
4257                             dev->target->target, dev->lun,
4258                             dev->target->channel == 0 ? 'A' : 'B',
4259                             ROLE_INITIATOR);
4260         
4261         /*
4262          * We don't currently trust the mid-layer to
4263          * properly deal with queue full or busy.  So,
4264          * when one occurs, we tell the mid-layer to
4265          * unconditionally requeue the command to us
4266          * so that we can retry it ourselves.  We also
4267          * implement our own throttling mechanism so
4268          * we don't clobber the device with too many
4269          * commands.
4270          */
4271         switch (ahc_get_scsi_status(scb)) {
4272         default:
4273                 break;
4274         case SCSI_STATUS_CHECK_COND:
4275         case SCSI_STATUS_CMD_TERMINATED:
4276         {
4277                 Scsi_Cmnd *cmd;
4278
4279                 /*
4280                  * Copy sense information to the OS's cmd
4281                  * structure if it is available.
4282                  */
4283                 cmd = scb->io_ctx;
4284                 if (scb->flags & SCB_SENSE) {
4285                         u_int sense_size;
4286
4287                         sense_size = MIN(sizeof(struct scsi_sense_data)
4288                                        - ahc_get_sense_residual(scb),
4289                                          sizeof(cmd->sense_buffer));
4290                         memcpy(cmd->sense_buffer,
4291                                ahc_get_sense_buf(ahc, scb), sense_size);
4292                         if (sense_size < sizeof(cmd->sense_buffer))
4293                                 memset(&cmd->sense_buffer[sense_size], 0,
4294                                        sizeof(cmd->sense_buffer) - sense_size);
4295                         cmd->result |= (DRIVER_SENSE << 24);
4296 #ifdef AHC_DEBUG
4297                         if (ahc_debug & AHC_SHOW_SENSE) {
4298                                 int i;
4299
4300                                 printf("Copied %d bytes of sense data:",
4301                                        sense_size);
4302                                 for (i = 0; i < sense_size; i++) {
4303                                         if ((i & 0xF) == 0)
4304                                                 printf("\n");
4305                                         printf("0x%x ", cmd->sense_buffer[i]);
4306                                 }
4307                                 printf("\n");
4308                         }
4309 #endif
4310                 }
4311                 break;
4312         }
4313         case SCSI_STATUS_QUEUE_FULL:
4314         {
4315                 /*
4316                  * By the time the core driver has returned this
4317                  * command, all other commands that were queued
4318                  * to us but not the device have been returned.
4319                  * This ensures that dev->active is equal to
4320                  * the number of commands actually queued to
4321                  * the device.
4322                  */
4323                 dev->tag_success_count = 0;
4324                 if (dev->active != 0) {
4325                         /*
4326                          * Drop our opening count to the number
4327                          * of commands currently outstanding.
4328                          */
4329                         dev->openings = 0;
4330 /*
4331                         ahc_print_path(ahc, scb);
4332                         printf("Dropping tag count to %d\n", dev->active);
4333  */
4334                         if (dev->active == dev->tags_on_last_queuefull) {
4335
4336                                 dev->last_queuefull_same_count++;
4337                                 /*
4338                                  * If we repeatedly see a queue full
4339                                  * at the same queue depth, this
4340                                  * device has a fixed number of tag
4341                                  * slots.  Lock in this tag depth
4342                                  * so we stop seeing queue fulls from
4343                                  * this device.
4344                                  */
4345                                 if (dev->last_queuefull_same_count
4346                                  == AHC_LOCK_TAGS_COUNT) {
4347                                         dev->maxtags = dev->active;
4348                                         ahc_print_path(ahc, scb);
4349                                         printf("Locking max tag count at %d\n",
4350                                                dev->active);
4351                                 }
4352                         } else {
4353                                 dev->tags_on_last_queuefull = dev->active;
4354                                 dev->last_queuefull_same_count = 0;
4355                         }
4356                         ahc_set_transaction_status(scb, CAM_REQUEUE_REQ);
4357                         ahc_set_scsi_status(scb, SCSI_STATUS_OK);
4358                         ahc_platform_set_tags(ahc, &devinfo,
4359                                      (dev->flags & AHC_DEV_Q_BASIC)
4360                                    ? AHC_QUEUE_BASIC : AHC_QUEUE_TAGGED);
4361                         break;
4362                 }
4363                 /*
4364                  * Drop down to a single opening, and treat this
4365                  * as if the target returned BUSY SCSI status.
4366                  */
4367                 dev->openings = 1;
4368                 ahc_set_scsi_status(scb, SCSI_STATUS_BUSY);
4369                 ahc_platform_set_tags(ahc, &devinfo,
4370                              (dev->flags & AHC_DEV_Q_BASIC)
4371                            ? AHC_QUEUE_BASIC : AHC_QUEUE_TAGGED);
4372                 /* FALLTHROUGH */
4373         }
4374         case SCSI_STATUS_BUSY:
4375         {
4376                 /*
4377                  * Set a short timer to defer sending commands for
4378                  * a bit since Linux will not delay in this case.
4379                  */
4380                 if ((dev->flags & AHC_DEV_TIMER_ACTIVE) != 0) {
4381                         printf("%s:%c:%d: Device Timer still active during "
4382                                "busy processing\n", ahc_name(ahc),
4383                                 dev->target->channel, dev->target->target);
4384                         break;
4385                 }
4386                 dev->flags |= AHC_DEV_TIMER_ACTIVE;
4387                 dev->qfrozen++;
4388                 init_timer(&dev->timer);
4389                 dev->timer.data = (u_long)dev;
4390                 dev->timer.expires = jiffies + (HZ/2);
4391                 dev->timer.function = ahc_linux_dev_timed_unfreeze;
4392                 add_timer(&dev->timer);
4393                 break;
4394         }
4395         }
4396 }
4397
4398 static void
4399 ahc_linux_queue_cmd_complete(struct ahc_softc *ahc, Scsi_Cmnd *cmd)
4400 {
4401         /*
4402          * Typically, the complete queue has very few entries
4403          * queued to it before the queue is emptied by
4404          * ahc_linux_run_complete_queue, so sorting the entries
4405          * by generation number should be inexpensive.
4406          * We perform the sort so that commands that complete
4407          * with an error are retuned in the order origionally
4408          * queued to the controller so that any subsequent retries
4409          * are performed in order.  The underlying ahc routines do
4410          * not guarantee the order that aborted commands will be
4411          * returned to us.
4412          */
4413         struct ahc_completeq *completeq;
4414         struct ahc_cmd *list_cmd;
4415         struct ahc_cmd *acmd;
4416
4417         /*
4418          * Map CAM error codes into Linux Error codes.  We
4419          * avoid the conversion so that the DV code has the
4420          * full error information available when making
4421          * state change decisions.
4422          */
4423         if (AHC_DV_CMD(cmd) == FALSE) {
4424                 u_int new_status;
4425
4426                 switch (ahc_cmd_get_transaction_status(cmd)) {
4427                 case CAM_REQ_INPROG:
4428                 case CAM_REQ_CMP:
4429                 case CAM_SCSI_STATUS_ERROR:
4430                         new_status = DID_OK;
4431                         break;
4432                 case CAM_REQ_ABORTED:
4433                         new_status = DID_ABORT;
4434                         break;
4435                 case CAM_BUSY:
4436                         new_status = DID_BUS_BUSY;
4437                         break;
4438                 case CAM_REQ_INVALID:
4439                 case CAM_PATH_INVALID:
4440                         new_status = DID_BAD_TARGET;
4441                         break;
4442                 case CAM_SEL_TIMEOUT:
4443                         new_status = DID_NO_CONNECT;
4444                         break;
4445                 case CAM_SCSI_BUS_RESET:
4446                 case CAM_BDR_SENT:
4447                         new_status = DID_RESET;
4448                         break;
4449                 case CAM_UNCOR_PARITY:
4450                         new_status = DID_PARITY;
4451                         break;
4452                 case CAM_CMD_TIMEOUT:
4453                         new_status = DID_TIME_OUT;
4454                         break;
4455                 case CAM_UA_ABORT:
4456                 case CAM_REQ_CMP_ERR:
4457                 case CAM_AUTOSENSE_FAIL:
4458                 case CAM_NO_HBA:
4459                 case CAM_DATA_RUN_ERR:
4460                 case CAM_UNEXP_BUSFREE:
4461                 case CAM_SEQUENCE_FAIL:
4462                 case CAM_CCB_LEN_ERR:
4463                 case CAM_PROVIDE_FAIL:
4464                 case CAM_REQ_TERMIO:
4465                 case CAM_UNREC_HBA_ERROR:
4466                 case CAM_REQ_TOO_BIG:
4467                         new_status = DID_ERROR;
4468                         break;
4469                 case CAM_REQUEUE_REQ:
4470                         /*
4471                          * If we want the request requeued, make sure there
4472                          * are sufficent retries.  In the old scsi error code,
4473                          * we used to be able to specify a result code that
4474                          * bypassed the retry count.  Now we must use this
4475                          * hack.  We also "fake" a check condition with
4476                          * a sense code of ABORTED COMMAND.  This seems to
4477                          * evoke a retry even if this command is being sent
4478                          * via the eh thread.  Ick!  Ick!  Ick!
4479                          */
4480                         if (cmd->retries > 0)
4481                                 cmd->retries--;
4482                         new_status = DID_OK;
4483                         ahc_cmd_set_scsi_status(cmd, SCSI_STATUS_CHECK_COND);
4484                         cmd->result |= (DRIVER_SENSE << 24);
4485                         memset(cmd->sense_buffer, 0,
4486                                sizeof(cmd->sense_buffer));
4487                         cmd->sense_buffer[0] = SSD_ERRCODE_VALID
4488                                              | SSD_CURRENT_ERROR;
4489                         cmd->sense_buffer[2] = SSD_KEY_ABORTED_COMMAND;
4490                         break;
4491                 default:
4492                         /* We should never get here */
4493                         new_status = DID_ERROR;
4494                         break;
4495                 }
4496
4497                 ahc_cmd_set_transaction_status(cmd, new_status);
4498         }
4499
4500         completeq = &ahc->platform_data->completeq;
4501         list_cmd = TAILQ_FIRST(completeq);
4502         acmd = (struct ahc_cmd *)cmd;
4503         while (list_cmd != NULL
4504             && acmd_scsi_cmd(list_cmd).serial_number
4505              < acmd_scsi_cmd(acmd).serial_number)
4506                 list_cmd = TAILQ_NEXT(list_cmd, acmd_links.tqe);
4507         if (list_cmd != NULL)
4508                 TAILQ_INSERT_BEFORE(list_cmd, acmd, acmd_links.tqe);
4509         else
4510                 TAILQ_INSERT_TAIL(completeq, acmd, acmd_links.tqe);
4511 }
4512
4513 static void
4514 ahc_linux_filter_inquiry(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
4515 {
4516         struct  scsi_inquiry_data *sid;
4517         struct  ahc_initiator_tinfo *tinfo;
4518         struct  ahc_transinfo *user;
4519         struct  ahc_transinfo *goal;
4520         struct  ahc_transinfo *curr;
4521         struct  ahc_tmode_tstate *tstate;
4522         struct  ahc_syncrate *syncrate;
4523         struct  ahc_linux_device *dev;
4524         u_int   maxsync;
4525         u_int   width;
4526         u_int   period;
4527         u_int   offset;
4528         u_int   ppr_options;
4529         u_int   trans_version;
4530         u_int   prot_version;
4531
4532         /*
4533          * Determine if this lun actually exists.  If so,
4534          * hold on to its corresponding device structure.
4535          * If not, make sure we release the device and
4536          * don't bother processing the rest of this inquiry
4537          * command.
4538          */
4539         dev = ahc_linux_get_device(ahc, devinfo->channel - 'A',
4540                                    devinfo->target, devinfo->lun,
4541                                    /*alloc*/TRUE);
4542
4543         sid = (struct scsi_inquiry_data *)dev->target->inq_data;
4544         if (SID_QUAL(sid) == SID_QUAL_LU_CONNECTED) {
4545
4546                 dev->flags &= ~AHC_DEV_UNCONFIGURED;
4547         } else {
4548                 dev->flags |= AHC_DEV_UNCONFIGURED;
4549                 return;
4550         }
4551
4552         /*
4553          * Update our notion of this device's transfer
4554          * negotiation capabilities.
4555          */
4556         tinfo = ahc_fetch_transinfo(ahc, devinfo->channel,
4557                                     devinfo->our_scsiid,
4558                                     devinfo->target, &tstate);
4559         user = &tinfo->user;
4560         goal = &tinfo->goal;
4561         curr = &tinfo->curr;
4562         width = user->width;
4563         period = user->period;
4564         offset = user->offset;
4565         ppr_options = user->ppr_options;
4566         trans_version = user->transport_version;
4567         prot_version = MIN(user->protocol_version, SID_ANSI_REV(sid));
4568
4569         /*
4570          * Only attempt SPI3/4 once we've verified that
4571          * the device claims to support SPI3/4 features.
4572          */
4573         if (prot_version < SCSI_REV_2)
4574                 trans_version = SID_ANSI_REV(sid);
4575         else
4576                 trans_version = SCSI_REV_2;
4577
4578         if ((sid->flags & SID_WBus16) == 0)
4579                 width = MSG_EXT_WDTR_BUS_8_BIT;
4580         if ((sid->flags & SID_Sync) == 0) {
4581                 period = 0;
4582                 offset = 0;
4583                 ppr_options = 0;
4584         }
4585         if ((sid->spi3data & SID_SPI_QAS) == 0)
4586                 ppr_options &= ~MSG_EXT_PPR_QAS_REQ;
4587         if ((sid->spi3data & SID_SPI_CLOCK_DT) == 0)
4588                 ppr_options &= MSG_EXT_PPR_QAS_REQ;
4589         if ((sid->spi3data & SID_SPI_IUS) == 0)
4590                 ppr_options &= (MSG_EXT_PPR_DT_REQ
4591                               | MSG_EXT_PPR_QAS_REQ);
4592
4593         if (prot_version > SCSI_REV_2
4594          && ppr_options != 0)
4595                 trans_version = user->transport_version;
4596
4597         ahc_validate_width(ahc, /*tinfo limit*/NULL, &width, ROLE_UNKNOWN);
4598         if ((ahc->features & AHC_ULTRA2) != 0)
4599                 maxsync = AHC_SYNCRATE_DT;
4600         else if ((ahc->features & AHC_ULTRA) != 0)
4601                 maxsync = AHC_SYNCRATE_ULTRA;
4602         else
4603                 maxsync = AHC_SYNCRATE_FAST;
4604
4605         syncrate = ahc_find_syncrate(ahc, &period, &ppr_options, maxsync);
4606         ahc_validate_offset(ahc, /*tinfo limit*/NULL, syncrate,
4607                             &offset, width, ROLE_UNKNOWN);
4608         if (offset == 0 || period == 0) {
4609                 period = 0;
4610                 offset = 0;
4611                 ppr_options = 0;
4612         }
4613         /* Apply our filtered user settings. */
4614         curr->transport_version = trans_version;
4615         curr->protocol_version = prot_version;
4616         ahc_set_width(ahc, devinfo, width, AHC_TRANS_GOAL, /*paused*/FALSE);
4617         ahc_set_syncrate(ahc, devinfo, syncrate, period,
4618                          offset, ppr_options, AHC_TRANS_GOAL,
4619                          /*paused*/FALSE);
4620 }
4621
4622 static void
4623 ahc_linux_sem_timeout(u_long arg)
4624 {
4625         struct  ahc_softc *ahc;
4626         u_long  s;
4627
4628         ahc = (struct ahc_softc *)arg;
4629
4630         ahc_lock(ahc, &s);
4631         if ((ahc->platform_data->flags & AHC_UP_EH_SEMAPHORE) != 0) {
4632                 ahc->platform_data->flags &= ~AHC_UP_EH_SEMAPHORE;
4633                 up(&ahc->platform_data->eh_sem);
4634         }
4635         ahc_unlock(ahc, &s);
4636 }
4637
4638 static void
4639 ahc_linux_freeze_simq(struct ahc_softc *ahc)
4640 {
4641         ahc->platform_data->qfrozen++;
4642         if (ahc->platform_data->qfrozen == 1) {
4643                 scsi_block_requests(ahc->platform_data->host);
4644
4645                 /* XXX What about Twin channels? */
4646                 ahc_platform_abort_scbs(ahc, CAM_TARGET_WILDCARD, ALL_CHANNELS,
4647                                         CAM_LUN_WILDCARD, SCB_LIST_NULL,
4648                                         ROLE_INITIATOR, CAM_REQUEUE_REQ);
4649         }
4650 }
4651
4652 static void
4653 ahc_linux_release_simq(u_long arg)
4654 {
4655         struct ahc_softc *ahc;
4656         u_long s;
4657         int    unblock_reqs;
4658
4659         ahc = (struct ahc_softc *)arg;
4660
4661         unblock_reqs = 0;
4662         ahc_lock(ahc, &s);
4663         if (ahc->platform_data->qfrozen > 0)
4664                 ahc->platform_data->qfrozen--;
4665         if (ahc->platform_data->qfrozen == 0)
4666                 unblock_reqs = 1;
4667         if (AHC_DV_SIMQ_FROZEN(ahc)
4668          && ((ahc->platform_data->flags & AHC_DV_WAIT_SIMQ_RELEASE) != 0)) {
4669                 ahc->platform_data->flags &= ~AHC_DV_WAIT_SIMQ_RELEASE;
4670                 up(&ahc->platform_data->dv_sem);
4671         }
4672         ahc_schedule_runq(ahc);
4673         ahc_unlock(ahc, &s);
4674         /*
4675          * There is still a race here.  The mid-layer
4676          * should keep its own freeze count and use
4677          * a bottom half handler to run the queues
4678          * so we can unblock with our own lock held.
4679          */
4680         if (unblock_reqs)
4681                 scsi_unblock_requests(ahc->platform_data->host);
4682 }
4683
4684 static void
4685 ahc_linux_dev_timed_unfreeze(u_long arg)
4686 {
4687         struct ahc_linux_device *dev;
4688         struct ahc_softc *ahc;
4689         u_long s;
4690
4691         dev = (struct ahc_linux_device *)arg;
4692         ahc = dev->target->ahc;
4693         ahc_lock(ahc, &s);
4694         dev->flags &= ~AHC_DEV_TIMER_ACTIVE;
4695         if (dev->qfrozen > 0)
4696                 dev->qfrozen--;
4697         if (dev->qfrozen == 0
4698          && (dev->flags & AHC_DEV_ON_RUN_LIST) == 0)
4699                 ahc_linux_run_device_queue(ahc, dev);
4700         if (TAILQ_EMPTY(&dev->busyq)
4701          && dev->active == 0)
4702                 __ahc_linux_free_device(ahc, dev);
4703         ahc_unlock(ahc, &s);
4704 }
4705
4706 static int
4707 ahc_linux_queue_recovery_cmd(Scsi_Cmnd *cmd, scb_flag flag)
4708 {
4709         struct ahc_softc *ahc;
4710         struct ahc_cmd *acmd;
4711         struct ahc_cmd *list_acmd;
4712         struct ahc_linux_device *dev;
4713         struct scb *pending_scb;
4714         u_long s;
4715         u_int  saved_scbptr;
4716         u_int  active_scb_index;
4717         u_int  last_phase;
4718         u_int  saved_scsiid;
4719         u_int  cdb_byte;
4720         int    retval;
4721         int    was_paused;
4722         int    paused;
4723         int    wait;
4724         int    disconnected;
4725
4726         pending_scb = NULL;
4727         paused = FALSE;
4728         wait = FALSE;
4729         ahc = *(struct ahc_softc **)cmd->device->host->hostdata;
4730         acmd = (struct ahc_cmd *)cmd;
4731
4732         printf("%s:%d:%d:%d: Attempting to queue a%s message\n",
4733                ahc_name(ahc), cmd->device->channel,
4734                cmd->device->id, cmd->device->lun,
4735                flag == SCB_ABORT ? "n ABORT" : " TARGET RESET");
4736
4737         printf("CDB:");
4738         for (cdb_byte = 0; cdb_byte < cmd->cmd_len; cdb_byte++)
4739                 printf(" 0x%x", cmd->cmnd[cdb_byte]);
4740         printf("\n");
4741
4742         /*
4743          * In all versions of Linux, we have to work around
4744          * a major flaw in how the mid-layer is locked down
4745          * if we are to sleep successfully in our error handler
4746          * while allowing our interrupt handler to run.  Since
4747          * the midlayer acquires either the io_request_lock or
4748          * our lock prior to calling us, we must use the
4749          * spin_unlock_irq() method for unlocking our lock.
4750          * This will force interrupts to be enabled on the
4751          * current CPU.  Since the EH thread should not have
4752          * been running with CPU interrupts disabled other than
4753          * by acquiring either the io_request_lock or our own
4754          * lock, this *should* be safe.
4755          */
4756         ahc_midlayer_entrypoint_lock(ahc, &s);
4757
4758         /*
4759          * First determine if we currently own this command.
4760          * Start by searching the device queue.  If not found
4761          * there, check the pending_scb list.  If not found
4762          * at all, and the system wanted us to just abort the
4763          * command, return success.
4764          */
4765         dev = ahc_linux_get_device(ahc, cmd->device->channel, cmd->device->id,
4766                                    cmd->device->lun, /*alloc*/FALSE);
4767
4768         if (dev == NULL) {
4769                 /*
4770                  * No target device for this command exists,
4771                  * so we must not still own the command.
4772                  */
4773                 printf("%s:%d:%d:%d: Is not an active device\n",
4774                        ahc_name(ahc), cmd->device->channel, cmd->device->id,
4775                        cmd->device->lun);
4776                 retval = SUCCESS;
4777                 goto no_cmd;
4778         }
4779
4780         TAILQ_FOREACH(list_acmd, &dev->busyq, acmd_links.tqe) {
4781                 if (list_acmd == acmd)
4782                         break;
4783         }
4784
4785         if (list_acmd != NULL) {
4786                 printf("%s:%d:%d:%d: Command found on device queue\n",
4787                        ahc_name(ahc), cmd->device->channel, cmd->device->id,
4788                        cmd->device->lun);
4789                 if (flag == SCB_ABORT) {
4790                         TAILQ_REMOVE(&dev->busyq, list_acmd, acmd_links.tqe);
4791                         cmd->result = DID_ABORT << 16;
4792                         ahc_linux_queue_cmd_complete(ahc, cmd);
4793                         retval = SUCCESS;
4794                         goto done;
4795                 }
4796         }
4797
4798         if ((dev->flags & (AHC_DEV_Q_BASIC|AHC_DEV_Q_TAGGED)) == 0
4799          && ahc_search_untagged_queues(ahc, cmd, cmd->device->id,
4800                                        cmd->device->channel + 'A',
4801                                        cmd->device->lun,
4802                                        CAM_REQ_ABORTED, SEARCH_COMPLETE) != 0) {
4803                 printf("%s:%d:%d:%d: Command found on untagged queue\n",
4804                        ahc_name(ahc), cmd->device->channel, cmd->device->id,
4805                        cmd->device->lun);
4806                 retval = SUCCESS;
4807                 goto done;
4808         }
4809
4810         /*
4811          * See if we can find a matching cmd in the pending list.
4812          */
4813         LIST_FOREACH(pending_scb, &ahc->pending_scbs, pending_links) {
4814                 if (pending_scb->io_ctx == cmd)
4815                         break;
4816         }
4817
4818         if (pending_scb == NULL && flag == SCB_DEVICE_RESET) {
4819
4820                 /* Any SCB for this device will do for a target reset */
4821                 LIST_FOREACH(pending_scb, &ahc->pending_scbs, pending_links) {
4822                         if (ahc_match_scb(ahc, pending_scb, cmd->device->id,
4823                                           cmd->device->channel + 'A',
4824                                           CAM_LUN_WILDCARD,
4825                                           SCB_LIST_NULL, ROLE_INITIATOR) == 0)
4826                                 break;
4827                 }
4828         }
4829
4830         if (pending_scb == NULL) {
4831                 printf("%s:%d:%d:%d: Command not found\n",
4832                        ahc_name(ahc), cmd->device->channel, cmd->device->id,
4833                        cmd->device->lun);
4834                 goto no_cmd;
4835         }
4836
4837         if ((pending_scb->flags & SCB_RECOVERY_SCB) != 0) {
4838                 /*
4839                  * We can't queue two recovery actions using the same SCB
4840                  */
4841                 retval = FAILED;
4842                 goto  done;
4843         }
4844
4845         /*
4846          * Ensure that the card doesn't do anything
4847          * behind our back and that we didn't "just" miss
4848          * an interrupt that would affect this cmd.
4849          */
4850         was_paused = ahc_is_paused(ahc);
4851         ahc_pause_and_flushwork(ahc);
4852         paused = TRUE;
4853
4854         if ((pending_scb->flags & SCB_ACTIVE) == 0) {
4855                 printf("%s:%d:%d:%d: Command already completed\n",
4856                        ahc_name(ahc), cmd->device->channel, cmd->device->id,
4857                        cmd->device->lun);
4858                 goto no_cmd;
4859         }
4860
4861         printf("%s: At time of recovery, card was %spaused\n",
4862                ahc_name(ahc), was_paused ? "" : "not ");
4863         ahc_dump_card_state(ahc);
4864
4865         disconnected = TRUE;
4866         if (flag == SCB_ABORT) {
4867                 if (ahc_search_qinfifo(ahc, cmd->device->id,
4868                                        cmd->device->channel + 'A',
4869                                        cmd->device->lun,
4870                                        pending_scb->hscb->tag,
4871                                        ROLE_INITIATOR, CAM_REQ_ABORTED,
4872                                        SEARCH_COMPLETE) > 0) {
4873                         printf("%s:%d:%d:%d: Cmd aborted from QINFIFO\n",
4874                                ahc_name(ahc), cmd->device->channel,
4875                                         cmd->device->id, cmd->device->lun);
4876                         retval = SUCCESS;
4877                         goto done;
4878                 }
4879         } else if (ahc_search_qinfifo(ahc, cmd->device->id,
4880                                       cmd->device->channel + 'A',
4881                                       cmd->device->lun, pending_scb->hscb->tag,
4882                                       ROLE_INITIATOR, /*status*/0,
4883                                       SEARCH_COUNT) > 0) {
4884                 disconnected = FALSE;
4885         }
4886
4887         if (disconnected && (ahc_inb(ahc, SEQ_FLAGS) & NOT_IDENTIFIED) == 0) {
4888                 struct scb *bus_scb;
4889
4890                 bus_scb = ahc_lookup_scb(ahc, ahc_inb(ahc, SCB_TAG));
4891                 if (bus_scb == pending_scb)
4892                         disconnected = FALSE;
4893                 else if (flag != SCB_ABORT
4894                       && ahc_inb(ahc, SAVED_SCSIID) == pending_scb->hscb->scsiid
4895                       && ahc_inb(ahc, SAVED_LUN) == SCB_GET_LUN(pending_scb))
4896                         disconnected = FALSE;
4897         }
4898
4899         /*
4900          * At this point, pending_scb is the scb associated with the
4901          * passed in command.  That command is currently active on the
4902          * bus, is in the disconnected state, or we're hoping to find
4903          * a command for the same target active on the bus to abuse to
4904          * send a BDR.  Queue the appropriate message based on which of
4905          * these states we are in.
4906          */
4907         last_phase = ahc_inb(ahc, LASTPHASE);
4908         saved_scbptr = ahc_inb(ahc, SCBPTR);
4909         active_scb_index = ahc_inb(ahc, SCB_TAG);
4910         saved_scsiid = ahc_inb(ahc, SAVED_SCSIID);
4911         if (last_phase != P_BUSFREE
4912          && (pending_scb->hscb->tag == active_scb_index
4913           || (flag == SCB_DEVICE_RESET
4914            && SCSIID_TARGET(ahc, saved_scsiid) == cmd->device->id))) {
4915
4916                 /*
4917                  * We're active on the bus, so assert ATN
4918                  * and hope that the target responds.
4919                  */
4920                 pending_scb = ahc_lookup_scb(ahc, active_scb_index);
4921                 pending_scb->flags |= SCB_RECOVERY_SCB|flag;
4922                 ahc_outb(ahc, MSG_OUT, HOST_MSG);
4923                 ahc_outb(ahc, SCSISIGO, last_phase|ATNO);
4924                 printf("%s:%d:%d:%d: Device is active, asserting ATN\n",
4925                        ahc_name(ahc), cmd->device->channel, cmd->device->id,
4926                        cmd->device->lun);
4927                 wait = TRUE;
4928         } else if (disconnected) {
4929
4930                 /*
4931                  * Actually re-queue this SCB in an attempt
4932                  * to select the device before it reconnects.
4933                  * In either case (selection or reselection),
4934                  * we will now issue the approprate message
4935                  * to the timed-out device.
4936                  *
4937                  * Set the MK_MESSAGE control bit indicating
4938                  * that we desire to send a message.  We
4939                  * also set the disconnected flag since
4940                  * in the paging case there is no guarantee
4941                  * that our SCB control byte matches the
4942                  * version on the card.  We don't want the
4943                  * sequencer to abort the command thinking
4944                  * an unsolicited reselection occurred.
4945                  */
4946                 pending_scb->hscb->control |= MK_MESSAGE|DISCONNECTED;
4947                 pending_scb->flags |= SCB_RECOVERY_SCB|flag;
4948
4949                 /*
4950                  * Remove any cached copy of this SCB in the
4951                  * disconnected list in preparation for the
4952                  * queuing of our abort SCB.  We use the
4953                  * same element in the SCB, SCB_NEXT, for
4954                  * both the qinfifo and the disconnected list.
4955                  */
4956                 ahc_search_disc_list(ahc, cmd->device->id,
4957                                      cmd->device->channel + 'A',
4958                                      cmd->device->lun, pending_scb->hscb->tag,
4959                                      /*stop_on_first*/TRUE,
4960                                      /*remove*/TRUE,
4961                                      /*save_state*/FALSE);
4962
4963                 /*
4964                  * In the non-paging case, the sequencer will
4965                  * never re-reference the in-core SCB.
4966                  * To make sure we are notified during
4967                  * reslection, set the MK_MESSAGE flag in
4968                  * the card's copy of the SCB.
4969                  */
4970                 if ((ahc->flags & AHC_PAGESCBS) == 0) {
4971                         ahc_outb(ahc, SCBPTR, pending_scb->hscb->tag);
4972                         ahc_outb(ahc, SCB_CONTROL,
4973                                  ahc_inb(ahc, SCB_CONTROL)|MK_MESSAGE);
4974                 }
4975
4976                 /*
4977                  * Clear out any entries in the QINFIFO first
4978                  * so we are the next SCB for this target
4979                  * to run.
4980                  */
4981                 ahc_search_qinfifo(ahc, cmd->device->id,
4982                                    cmd->device->channel + 'A',
4983                                    cmd->device->lun, SCB_LIST_NULL,
4984                                    ROLE_INITIATOR, CAM_REQUEUE_REQ,
4985                                    SEARCH_COMPLETE);
4986                 ahc_qinfifo_requeue_tail(ahc, pending_scb);
4987                 ahc_outb(ahc, SCBPTR, saved_scbptr);
4988                 ahc_print_path(ahc, pending_scb);
4989                 printf("Device is disconnected, re-queuing SCB\n");
4990                 wait = TRUE;
4991         } else {
4992                 printf("%s:%d:%d:%d: Unable to deliver message\n",
4993                        ahc_name(ahc), cmd->device->channel, cmd->device->id,
4994                        cmd->device->lun);
4995                 retval = FAILED;
4996                 goto done;
4997         }
4998
4999 no_cmd:
5000         /*
5001          * Our assumption is that if we don't have the command, no
5002          * recovery action was required, so we return success.  Again,
5003          * the semantics of the mid-layer recovery engine are not
5004          * well defined, so this may change in time.
5005          */
5006         retval = SUCCESS;
5007 done:
5008         if (paused)
5009                 ahc_unpause(ahc);
5010         if (wait) {
5011                 struct timer_list timer;
5012                 int ret;
5013
5014                 ahc->platform_data->flags |= AHC_UP_EH_SEMAPHORE;
5015                 spin_unlock_irq(&ahc->platform_data->spin_lock);
5016                 init_timer(&timer);
5017                 timer.data = (u_long)ahc;
5018                 timer.expires = jiffies + (5 * HZ);
5019                 timer.function = ahc_linux_sem_timeout;
5020                 add_timer(&timer);
5021                 printf("Recovery code sleeping\n");
5022                 down(&ahc->platform_data->eh_sem);
5023                 printf("Recovery code awake\n");
5024                 ret = del_timer_sync(&timer);
5025                 if (ret == 0) {
5026                         printf("Timer Expired\n");
5027                         retval = FAILED;
5028                 }
5029                 spin_lock_irq(&ahc->platform_data->spin_lock);
5030         }
5031         ahc_schedule_runq(ahc);
5032         ahc_linux_run_complete_queue(ahc);
5033         ahc_midlayer_entrypoint_unlock(ahc, &s);
5034         return (retval);
5035 }
5036
5037 void
5038 ahc_platform_dump_card_state(struct ahc_softc *ahc)
5039 {
5040         struct ahc_linux_device *dev;
5041         int channel;
5042         int maxchannel;
5043         int target;
5044         int maxtarget;
5045         int lun;
5046         int i;
5047
5048         maxchannel = (ahc->features & AHC_TWIN) ? 1 : 0;
5049         maxtarget = (ahc->features & AHC_WIDE) ? 15 : 7;
5050         for (channel = 0; channel <= maxchannel; channel++) {
5051
5052                 for (target = 0; target <=maxtarget; target++) {
5053
5054                         for (lun = 0; lun < AHC_NUM_LUNS; lun++) {
5055                                 struct ahc_cmd *acmd;
5056
5057                                 dev = ahc_linux_get_device(ahc, channel, target,
5058                                                            lun, /*alloc*/FALSE);
5059                                 if (dev == NULL)
5060                                         continue;
5061
5062                                 printf("DevQ(%d:%d:%d): ",
5063                                        channel, target, lun);
5064                                 i = 0;
5065                                 TAILQ_FOREACH(acmd, &dev->busyq,
5066                                               acmd_links.tqe) {
5067                                         if (i++ > AHC_SCB_MAX)
5068                                                 break;
5069                                 }
5070                                 printf("%d waiting\n", i);
5071                         }
5072                 }
5073         }
5074 }
5075
5076 static void ahc_linux_exit(void);
5077
5078 static int __init
5079 ahc_linux_init(void)
5080 {
5081 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)
5082         int rc = ahc_linux_detect(&aic7xxx_driver_template);
5083         if (rc)
5084                 return rc;
5085         ahc_linux_exit();
5086         return -ENODEV;
5087 #else
5088         scsi_register_module(MODULE_SCSI_HA, &aic7xxx_driver_template);
5089         if (aic7xxx_driver_template.present == 0) {
5090                 scsi_unregister_module(MODULE_SCSI_HA,
5091                                        &aic7xxx_driver_template);
5092                 return (-ENODEV);
5093         }
5094
5095         return (0);
5096 #endif
5097 }
5098
5099 static void
5100 ahc_linux_exit(void)
5101 {
5102         struct ahc_softc *ahc;
5103         u_long l;
5104
5105         /*
5106          * Shutdown DV threads before going into the SCSI mid-layer.
5107          * This avoids situations where the mid-layer locks the entire
5108          * kernel so that waiting for our DV threads to exit leads
5109          * to deadlock.
5110          */
5111         ahc_list_lock(&l);
5112         TAILQ_FOREACH(ahc, &ahc_tailq, links) {
5113
5114                 ahc_linux_kill_dv_thread(ahc);
5115         }
5116         ahc_list_unlock(&l);
5117
5118 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
5119         /*
5120          * In 2.4 we have to unregister from the PCI core _after_
5121          * unregistering from the scsi midlayer to avoid dangling
5122          * references.
5123          */
5124         scsi_unregister_module(MODULE_SCSI_HA, &aic7xxx_driver_template);
5125 #endif
5126         ahc_linux_pci_exit();
5127         ahc_linux_eisa_exit();
5128 }
5129
5130 module_init(ahc_linux_init);
5131 module_exit(ahc_linux_exit);