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