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