v2.4.10.4 -> v2.4.10.5
[linux-flexiantxendom0-3.2.10.git] / drivers / scsi / aic7xxx / aic7xxx_linux.c
1 /*
2  * Adaptec AIC7xxx device driver for Linux.
3  *
4  * $Id: //depot/src/linux/drivers/scsi/aic7xxx/aic7xxx_linux.c#72 $
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, 1995, 1996, 1997, 1998, 1999, 2000 Justin T. Gibbs.
42  * Copyright (c) 2000 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. The name of the author may not be used to endorse or promote products
52  *    derived from this software without specific prior written permission.
53  *
54  * Alternatively, this software may be distributed under the terms of the
55  * GNU General Public License ("GPL").
56  *
57  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
58  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
59  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
60  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
61  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
62  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
63  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
64  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
65  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
66  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
67  * SUCH DAMAGE.
68  *
69  *---------------------------------------------------------------------------
70  *
71  *  Thanks also go to (in alphabetical order) the following:
72  *
73  *    Rory Bolt     - Sequencer bug fixes
74  *    Jay Estabrook - Initial DEC Alpha support
75  *    Doug Ledford  - Much needed abort/reset bug fixes
76  *    Kai Makisara  - DMAing of SCBs
77  *
78  *  A Boot time option was also added for not resetting the scsi bus.
79  *
80  *    Form:  aic7xxx=extended
81  *           aic7xxx=no_reset
82  *           aic7xxx=ultra
83  *           aic7xxx=irq_trigger:[0,1]  # 0 edge, 1 level
84  *           aic7xxx=verbose
85  *
86  *  Daniel M. Eischen, deischen@iworks.InterWorks.org, 1/23/97
87  *
88  *  Id: aic7xxx.c,v 4.1 1997/06/12 08:23:42 deang Exp
89  */
90
91 /*
92  * Further driver modifications made by Doug Ledford <dledford@redhat.com>
93  *
94  * Copyright (c) 1997-1999 Doug Ledford
95  *
96  * These changes are released under the same licensing terms as the FreeBSD
97  * driver written by Justin Gibbs.  Please see his Copyright notice above
98  * for the exact terms and conditions covering my changes as well as the
99  * warranty statement.
100  *
101  * Modifications made to the aic7xxx.c,v 4.1 driver from Dan Eischen include
102  * but are not limited to:
103  *
104  *  1: Import of the latest FreeBSD sequencer code for this driver
105  *  2: Modification of kernel code to accomodate different sequencer semantics
106  *  3: Extensive changes throughout kernel portion of driver to improve
107  *     abort/reset processing and error hanndling
108  *  4: Other work contributed by various people on the Internet
109  *  5: Changes to printk information and verbosity selection code
110  *  6: General reliability related changes, especially in IRQ management
111  *  7: Modifications to the default probe/attach order for supported cards
112  *  8: SMP friendliness has been improved
113  *
114  */
115
116 /*
117  * The next three defines are user configurable.  These should be the only
118  * defines a user might need to get in here and change.  There are other
119  * defines buried deeper in the code, but those really shouldn't need touched
120  * under normal conditions.
121  */
122
123 #include <linux/module.h>
124
125 #include "aic7xxx_osm.h"
126 #include "aic7xxx_inline.h"
127
128 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,3,0)
129 #include <linux/init.h>         /* __setup */
130 #endif
131
132 #include "../sd.h"              /* For geometry detection */
133
134 #include <linux/mm.h>           /* For fetching system memory size */
135
136 /*
137  * To generate the correct addresses for the controller to issue
138  * on the bus.  Originally added for DEC Alpha support.
139  */
140 #define VIRT_TO_BUS(a) (uint32_t)virt_to_bus((void *)(a))
141
142 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,3,0)
143 struct proc_dir_entry proc_scsi_aic7xxx = {
144         PROC_SCSI_AIC7XXX, 7, "aic7xxx",
145         S_IFDIR | S_IRUGO | S_IXUGO, 2,
146         0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL
147 };
148 #endif
149
150 /*
151  * Set this to the delay in seconds after SCSI bus reset.
152  * Note, we honor this only for the initial bus reset.
153  * The scsi error recovery code performs its own bus settle
154  * delay handling for error recovery actions.
155  */
156 #ifdef CONFIG_AIC7XXX_RESET_DELAY_MS
157 #define AIC7XXX_RESET_DELAY CONFIG_AIC7XXX_RESET_DELAY_MS
158 #else
159 #define AIC7XXX_RESET_DELAY 5000
160 #endif
161
162 /*
163  * Control collection of SCSI transfer statistics for the /proc filesystem.
164  *
165  * NOTE: Do NOT enable this when running on kernels version 1.2.x and below.
166  * NOTE: This does affect performance since it has to maintain statistics.
167  */
168 #ifdef CONFIG_AIC7XXX_PROC_STATS
169 #define AIC7XXX_PROC_STATS
170 #endif
171
172 /*
173  * To change the default number of tagged transactions allowed per-device,
174  * add a line to the lilo.conf file like:
175  * append="aic7xxx=verbose,tag_info:{{32,32,32,32},{32,32,32,32}}"
176  * which will result in the first four devices on the first two
177  * controllers being set to a tagged queue depth of 32.
178  *
179  * The tag_commands is an array of 16 to allow for wide and twin adapters.
180  * Twin adapters will use indexes 0-7 for channel 0, and indexes 8-15
181  * for channel 1.
182  */
183 typedef struct {
184         uint8_t tag_commands[16];       /* Allow for wide/twin adapters. */
185 } adapter_tag_info_t;
186
187 /*
188  * Modify this as you see fit for your system.
189  *
190  * 0                    tagged queuing disabled
191  * 1 <= n <= 253        n == max tags ever dispatched.
192  *
193  * The driver will throttle the number of commands dispatched to a
194  * device if it returns queue full.  For devices with a fixed maximum
195  * queue depth, the driver will eventually determine this depth and
196  * lock it in (a console message is printed to indicate that a lock
197  * has occurred).  On some devices, queue full is returned for a temporary
198  * resource shortage.  These devices will return queue full at varying
199  * depths.  The driver will throttle back when the queue fulls occur and
200  * attempt to slowly increase the depth over time as the device recovers
201  * from the resource shortage.
202  *
203  * In this example, the first line will disable tagged queueing for all
204  * the devices on the first probed aic7xxx adapter.
205  *
206  * The second line enables tagged queueing with 4 commands/LUN for IDs
207  * (0, 2-11, 13-15), disables tagged queueing for ID 12, and tells the
208  * driver to attempt to use up to 64 tags for ID 1.
209  *
210  * The third line is the same as the first line.
211  *
212  * The fourth line disables tagged queueing for devices 0 and 3.  It
213  * enables tagged queueing for the other IDs, with 16 commands/LUN
214  * for IDs 1 and 4, 127 commands/LUN for ID 8, and 4 commands/LUN for
215  * IDs 2, 5-7, and 9-15.
216  */
217
218 /*
219  * NOTE: The below structure is for reference only, the actual structure
220  *       to modify in order to change things is just below this comment block.
221 adapter_tag_info_t aic7xxx_tag_info[] =
222 {
223         {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
224         {{4, 64, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 4, 4}},
225         {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
226         {{0, 16, 4, 0, 16, 4, 4, 4, 127, 4, 4, 4, 4, 4, 4, 4}}
227 };
228 */
229
230 #ifdef CONFIG_AIC7XXX_CMDS_PER_DEVICE
231 #define AIC7XXX_CMDS_PER_DEVICE CONFIG_AIC7XXX_CMDS_PER_DEVICE
232 #else
233 #define AIC7XXX_CMDS_PER_DEVICE AHC_MAX_QUEUE
234 #endif
235
236 #define AIC7XXX_CONFIGED_TAG_COMMANDS {                                 \
237         AIC7XXX_CMDS_PER_DEVICE, AIC7XXX_CMDS_PER_DEVICE,               \
238         AIC7XXX_CMDS_PER_DEVICE, AIC7XXX_CMDS_PER_DEVICE,               \
239         AIC7XXX_CMDS_PER_DEVICE, AIC7XXX_CMDS_PER_DEVICE,               \
240         AIC7XXX_CMDS_PER_DEVICE, AIC7XXX_CMDS_PER_DEVICE,               \
241         AIC7XXX_CMDS_PER_DEVICE, AIC7XXX_CMDS_PER_DEVICE,               \
242         AIC7XXX_CMDS_PER_DEVICE, AIC7XXX_CMDS_PER_DEVICE,               \
243         AIC7XXX_CMDS_PER_DEVICE, AIC7XXX_CMDS_PER_DEVICE,               \
244         AIC7XXX_CMDS_PER_DEVICE, AIC7XXX_CMDS_PER_DEVICE                \
245 }
246
247 /*
248  * By default, use the number of commands specified by
249  * the users kernel configuration.
250  */
251 static adapter_tag_info_t aic7xxx_tag_info[] =
252 {
253         {AIC7XXX_CONFIGED_TAG_COMMANDS},
254         {AIC7XXX_CONFIGED_TAG_COMMANDS},
255         {AIC7XXX_CONFIGED_TAG_COMMANDS},
256         {AIC7XXX_CONFIGED_TAG_COMMANDS},
257         {AIC7XXX_CONFIGED_TAG_COMMANDS},
258         {AIC7XXX_CONFIGED_TAG_COMMANDS},
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 };
270
271 /*
272  * There should be a specific return value for this in scsi.h, but
273  * it seems that most drivers ignore it.
274  */
275 #define DID_UNDERFLOW   DID_ERROR
276
277 void
278 ahc_print_path(struct ahc_softc *ahc, struct scb *scb)
279 {
280         printk("(scsi%d:%c:%d:%d): ",
281                ahc->platform_data->host->host_no,
282                scb != NULL ? SCB_GET_CHANNEL(ahc, scb) : 'X',
283                scb != NULL ? SCB_GET_TARGET(ahc, scb) : -1,
284                scb != NULL ? SCB_GET_LUN(scb) : -1);
285 }
286
287 /*
288  * XXX - these options apply unilaterally to _all_ 274x/284x/294x
289  *       cards in the system.  This should be fixed.  Exceptions to this
290  *       rule are noted in the comments.
291  */
292
293 /*
294  * Skip the scsi bus reset.  Non 0 make us skip the reset at startup.  This
295  * has no effect on any later resets that might occur due to things like
296  * SCSI bus timeouts.
297  */
298 static uint32_t aic7xxx_no_reset;
299
300 /*
301  * Certain PCI motherboards will scan PCI devices from highest to lowest,
302  * others scan from lowest to highest, and they tend to do all kinds of
303  * strange things when they come into contact with PCI bridge chips.  The
304  * net result of all this is that the PCI card that is actually used to boot
305  * the machine is very hard to detect.  Most motherboards go from lowest
306  * PCI slot number to highest, and the first SCSI controller found is the
307  * one you boot from.  The only exceptions to this are when a controller
308  * has its BIOS disabled.  So, we by default sort all of our SCSI controllers
309  * from lowest PCI slot number to highest PCI slot number.  We also force
310  * all controllers with their BIOS disabled to the end of the list.  This
311  * works on *almost* all computers.  Where it doesn't work, we have this
312  * option.  Setting this option to non-0 will reverse the order of the sort
313  * to highest first, then lowest, but will still leave cards with their BIOS
314  * disabled at the very end.  That should fix everyone up unless there are
315  * really strange cirumstances.
316  */
317 static int aic7xxx_reverse_scan = 0;
318
319 /*
320  * Should we force EXTENDED translation on a controller.
321  *     0 == Use whatever is in the SEEPROM or default to off
322  *     1 == Use whatever is in the SEEPROM or default to on
323  */
324 static uint32_t aic7xxx_extended = 0;
325
326 /*
327  * The IRQ trigger method used on EISA controllers. Does not effect PCI cards.
328  *   -1 = Use detected settings.
329  *    0 = Force Edge triggered mode.
330  *    1 = Force Level triggered mode.
331  */
332 static int aic7xxx_irq_trigger = -1;
333
334 /*
335  * This variable is used to override the termination settings on a controller.
336  * This should not be used under normal conditions.  However, in the case
337  * that a controller does not have a readable SEEPROM (so that we can't
338  * read the SEEPROM settings directly) and that a controller has a buggered
339  * version of the cable detection logic, this can be used to force the
340  * correct termination.  It is preferable to use the manual termination
341  * settings in the BIOS if possible, but some motherboard controllers store
342  * those settings in a format we can't read.  In other cases, auto term
343  * should also work, but the chipset was put together with no auto term
344  * logic (common on motherboard controllers).  In those cases, we have
345  * 32 bits here to work with.  That's good for 8 controllers/channels.  The
346  * bits are organized as 4 bits per channel, with scsi0 getting the lowest
347  * 4 bits in the int.  A 1 in a bit position indicates the termination setting
348  * that corresponds to that bit should be enabled, a 0 is disabled.
349  * It looks something like this:
350  *
351  *    0x0f =  1111-Single Ended Low Byte Termination on/off
352  *            ||\-Single Ended High Byte Termination on/off
353  *            |\-LVD Low Byte Termination on/off
354  *            \-LVD High Byte Termination on/off
355  *
356  * For non-Ultra2 controllers, the upper 2 bits are not important.  So, to
357  * enable both high byte and low byte termination on scsi0, I would need to
358  * make sure that the override_term variable was set to 0x03 (bits 0011).
359  * To make sure that all termination is enabled on an Ultra2 controller at
360  * scsi2 and only high byte termination on scsi1 and high and low byte
361  * termination on scsi0, I would set override_term=0xf23 (bits 1111 0010 0011)
362  *
363  * For the most part, users should never have to use this, that's why I
364  * left it fairly cryptic instead of easy to understand.  If you need it,
365  * most likely someone will be telling you what your's needs to be set to.
366  */
367 static int aic7xxx_override_term = -1;
368
369 /*
370  * Certain motherboard chipset controllers tend to screw
371  * up the polarity of the term enable output pin.  Use this variable
372  * to force the correct polarity for your system.  This is a bitfield variable
373  * similar to the previous one, but this one has one bit per channel instead
374  * of four.
375  *    0 = Force the setting to active low.
376  *    1 = Force setting to active high.
377  * Most Adaptec cards are active high, several motherboards are active low.
378  * To force a 2940 card at SCSI 0 to active high and a motherboard 7895
379  * controller at scsi1 and scsi2 to active low, and a 2910 card at scsi3
380  * to active high, you would need to set stpwlev=0x9 (bits 1001).
381  *
382  * People shouldn't need to use this, but if you are experiencing lots of
383  * SCSI timeout problems, this may help.  There is one sure way to test what
384  * this option needs to be.  Using a boot floppy to boot the system, configure
385  * your system to enable all SCSI termination (in the Adaptec SCSI BIOS) and
386  * if needed then also pass a value to override_term to make sure that the
387  * driver is enabling SCSI termination, then set this variable to either 0
388  * or 1.  When the driver boots, make sure there are *NO* SCSI cables
389  * connected to your controller.  If it finds and inits the controller
390  * without problem, then the setting you passed to stpwlev was correct.  If
391  * the driver goes into a reset loop and hangs the system, then you need the
392  * other setting for this variable.  If neither setting lets the machine
393  * boot then you have definite termination problems that may not be fixable.
394  */
395 static int aic7xxx_stpwlev = -1;
396
397 /*
398  * Set this to non-0 in order to force the driver to panic the kernel
399  * and print out debugging info on a SCSI abort or reset cycle.
400  */
401 static int aic7xxx_panic_on_abort = 0;
402
403 /*
404  * PCI bus parity checking of the Adaptec controllers.  This is somewhat
405  * dubious at best.  To my knowledge, this option has never actually
406  * solved a PCI parity problem, but on certain machines with broken PCI
407  * chipset configurations, it can generate tons of false error messages.
408  * It's included in the driver for completeness.
409  *   0 = Shut off PCI parity check
410  *  -1 = Normal polarity pci parity checking
411  *   1 = reverse polarity pci parity checking
412  *
413  * NOTE: you can't actually pass -1 on the lilo prompt.  So, to set this
414  * variable to -1 you would actually want to simply pass the variable
415  * name without a number.  That will invert the 0 which will result in
416  * -1.
417  */
418 static int aic7xxx_pci_parity = 0;
419
420 /*
421  * Set this to a non-0 value to make us dump out the 32 bit instruction
422  * registers on the card after completing the sequencer download.  This
423  * allows the actual sequencer download to be verified.  It is possible
424  * to use this option and still boot up and run your system.  This is
425  * only intended for debugging purposes.
426  */
427 static int aic7xxx_dump_sequencer = 0;
428
429 /*
430  * Certain newer motherboards have put new PCI based devices into the
431  * IO spaces that used to typically be occupied by VLB or EISA cards.
432  * This overlap can cause these newer motherboards to lock up when scanned
433  * for older EISA and VLB devices.  Setting this option to non-0 will
434  * cause the driver to skip scanning for any VLB or EISA controllers and
435  * only support the PCI controllers.  NOTE: this means that if the kernel
436  * os compiled with PCI support disabled, then setting this to non-0
437  * would result in never finding any devices :)
438  */
439 int aic7xxx_no_probe;
440
441 /*
442  * aic7xxx_detect() has been run, so register all device arrivals
443  * immediately with the system rather than deferring to the sorted
444  * attachment performed by aic7xxx_detect().
445  */
446 int aic7xxx_detect_complete;
447
448 /*
449  * So that we can set how long each device is given as a selection timeout.
450  * The table of values goes like this:
451  *   0 - 256ms
452  *   1 - 128ms
453  *   2 - 64ms
454  *   3 - 32ms
455  * We default to 256ms because some older devices need a longer time
456  * to respond to initial selection.
457  */
458 static int aic7xxx_seltime = 0x00;
459
460 /*
461  * So that insmod can find the variable and make it point to something
462  */
463 #ifdef MODULE
464 static char *aic7xxx = NULL;
465
466 MODULE_PARM(aic7xxx, "s");
467
468 /*
469  * Just in case someone uses commas to separate items on the insmod
470  * command line, we define a dummy buffer here to avoid having insmod
471  * write wild stuff into our code segment
472  */
473 static char dummy_buffer[60] = "Please don't trounce on me insmod!!\n";
474
475 #endif
476
477 static void ahc_linux_handle_scsi_status(struct ahc_softc *,
478                                          struct ahc_linux_device *,
479                                          struct scb *);
480 static void ahc_linux_filter_command(struct ahc_softc*, Scsi_Cmnd*,
481                                      struct scb*);
482 static void ahc_linux_sem_timeout(u_long arg);
483 static void ahc_linux_freeze_sim_queue(struct ahc_softc *ahc);
484 static void ahc_linux_release_sim_queue(u_long arg);
485 static int  ahc_linux_queue_recovery_cmd(Scsi_Cmnd *cmd, scb_flag flag);
486 static void ahc_linux_initialize_scsi_bus(struct ahc_softc *ahc);
487 static void ahc_linux_select_queue_depth(struct Scsi_Host *host,
488                                          Scsi_Device *scsi_devs);
489 static void ahc_linux_device_queue_depth(struct ahc_softc *ahc,
490                                          Scsi_Device *device);
491 static struct ahc_linux_target* ahc_linux_alloc_target(struct ahc_softc*,
492                                                        u_int, u_int);
493 static void                     ahc_linux_free_target(struct ahc_softc*,
494                                                       struct ahc_linux_target*);
495 static struct ahc_linux_device* ahc_linux_alloc_device(struct ahc_softc*,
496                                                        struct ahc_linux_target*,
497                                                        u_int);
498 static void                     ahc_linux_free_device(struct ahc_softc*,
499                                                       struct ahc_linux_device*);
500 static void ahc_linux_run_device_queue(struct ahc_softc*,
501                                        struct ahc_linux_device*);
502 static void ahc_linux_setup_tag_info(char *p, char *end);
503 static int ahc_linux_next_unit(void);
504 static int ahc_linux_halt(struct notifier_block *nb, u_long event, void *buf);
505
506 static __inline struct ahc_linux_device*
507                      ahc_linux_get_device(struct ahc_softc *ahc, u_int channel,
508                                           u_int target, u_int lun, int alloc);
509 static __inline void ahc_linux_queue_cmd_complete(struct ahc_softc *ahc,
510                                                   Scsi_Cmnd *cmd);
511 static __inline void ahc_linux_run_complete_queue(struct ahc_softc *ahc,
512                                                   struct ahc_cmd *acmd);
513 static __inline void ahc_linux_check_device_queue(struct ahc_softc *ahc,
514                                                   struct ahc_linux_device *dev);
515 static __inline void ahc_linux_sniff_command(struct ahc_softc*, Scsi_Cmnd*,
516                                              struct scb*);
517 static __inline void ahc_linux_unmap_scb(struct ahc_softc*, struct scb*);
518
519 static __inline int ahc_linux_map_seg(struct ahc_softc *ahc, struct scb *scb,
520                                       struct ahc_dma_seg *sg,
521                                       bus_addr_t addr, bus_size_t len);
522
523 static __inline struct ahc_linux_device*
524 ahc_linux_get_device(struct ahc_softc *ahc, u_int channel, u_int target,
525                u_int lun, int alloc)
526 {
527         struct ahc_linux_target *targ;
528         struct ahc_linux_device *dev;
529         u_int target_offset;
530
531         target_offset = target;
532         if (channel != 0)
533                 target_offset += 8;
534         targ = ahc->platform_data->targets[target_offset];
535         if (targ == NULL) {
536                 if (alloc != 0) {
537                         targ = ahc_linux_alloc_target(ahc, channel, target);
538                         if (targ == NULL)
539                                 return (NULL);
540                 } else
541                         return (NULL);
542         }
543         dev = targ->devices[lun];
544         if (dev == NULL && alloc != 0)
545                 dev = ahc_linux_alloc_device(ahc, targ, lun);
546         return (dev);
547 }
548
549 static __inline void
550 ahc_linux_queue_cmd_complete(struct ahc_softc *ahc, Scsi_Cmnd *cmd)
551 {
552         /*
553          * Typically, the complete queue has very few entries
554          * queued to it before the queue is emptied by
555          * ahc_linux_run_complete_queue, so sorting the entries
556          * by generation number should be inexpensive.
557          * We perform the sort so that commands that complete
558          * with an error are retuned in the order origionally
559          * queued to the controller so that any subsequent retries
560          * are performed in order.  The underlying ahc routines do
561          * not guarantee the order that aborted commands will be
562          * returned to us.
563          */
564         struct ahc_completeq *completeq;
565         struct ahc_cmd *list_cmd;
566         struct ahc_cmd *acmd;
567
568         /*
569          * If we want the request requeued, make sure there
570          * are sufficent retries.  In the old scsi error code,
571          * we used to be able to specify a result code that
572          * bypassed the retry count.  Now we must use this
573          * hack.
574          */
575         if (cmd->result == (CAM_REQUEUE_REQ << 16))
576                 cmd->retries--;
577         completeq = &ahc->platform_data->completeq;
578         list_cmd = TAILQ_FIRST(completeq);
579         acmd = (struct ahc_cmd *)cmd;
580         while (list_cmd != NULL
581             && acmd_scsi_cmd(list_cmd).serial_number
582              < acmd_scsi_cmd(acmd).serial_number)
583                 list_cmd = TAILQ_NEXT(list_cmd, acmd_links.tqe);
584         if (list_cmd != NULL)
585                 TAILQ_INSERT_BEFORE(list_cmd, acmd, acmd_links.tqe);
586         else
587                 TAILQ_INSERT_TAIL(completeq, acmd, acmd_links.tqe);
588 }
589
590 static __inline void
591 ahc_linux_run_complete_queue(struct ahc_softc *ahc, struct ahc_cmd *acmd)
592 {       
593         u_long done_flags;
594
595         ahc_done_lock(ahc, &done_flags);
596         while (acmd != NULL) {
597                 Scsi_Cmnd *cmd;
598
599                 cmd = &acmd_scsi_cmd(acmd);
600                 acmd = TAILQ_NEXT(acmd, acmd_links.tqe);
601                 cmd->host_scribble = NULL;
602                 cmd->scsi_done(cmd);
603         }
604         ahc_done_unlock(ahc, &done_flags);
605 }
606
607 static __inline void
608 ahc_linux_check_device_queue(struct ahc_softc *ahc,
609                              struct ahc_linux_device *dev)
610 {
611         if ((dev->flags & AHC_DEV_FREEZE_TIL_EMPTY) != 0
612          && dev->active == 0) {
613                 dev->flags &= ~AHC_DEV_FREEZE_TIL_EMPTY;
614                 dev->qfrozen--;
615         }
616
617         if (TAILQ_FIRST(&dev->busyq) == NULL
618          || dev->openings == 0 || dev->qfrozen != 0)
619                 return;
620
621         ahc_linux_run_device_queue(ahc, dev);
622 }
623
624 static __inline void
625 ahc_linux_run_device_queues(struct ahc_softc *ahc)
626 {
627         struct ahc_linux_device *dev;
628
629         while ((ahc->flags & AHC_RESOURCE_SHORTAGE) == 0
630             && ahc->platform_data->qfrozen == 0
631             && (dev = TAILQ_FIRST(&ahc->platform_data->device_runq)) != NULL) {
632                 TAILQ_REMOVE(&ahc->platform_data->device_runq, dev, links);
633                 dev->flags &= ~AHC_DEV_ON_RUN_LIST;
634                 ahc_linux_check_device_queue(ahc, dev);
635         }
636 }
637
638 static __inline void
639 ahc_linux_sniff_command(struct ahc_softc *ahc, Scsi_Cmnd *cmd, struct scb *scb)
640 {
641         /*
642          * Determine whether we care to filter
643          * information out of this command.  If so,
644          * pass it on to ahc_linux_filter_command() for more
645          * heavy weight processing.
646          */
647         if (cmd->cmnd[0] == INQUIRY)
648                 ahc_linux_filter_command(ahc, cmd, scb);
649 }
650
651 static __inline void
652 ahc_linux_unmap_scb(struct ahc_softc *ahc, struct scb *scb)
653 {
654         Scsi_Cmnd *cmd;
655
656         cmd = scb->io_ctx;
657         ahc_sync_sglist(ahc, scb, BUS_DMASYNC_POSTWRITE);
658         if (cmd->use_sg != 0) {
659                 struct scatterlist *sg;
660
661                 sg = (struct scatterlist *)cmd->request_buffer;
662                 pci_unmap_sg(ahc->dev_softc, sg, cmd->use_sg,
663                              scsi_to_pci_dma_dir(cmd->sc_data_direction));
664         } else if (cmd->request_bufflen != 0)
665                 pci_unmap_single(ahc->dev_softc,
666                                  ahc_le32toh(scb->sg_list[0].addr),
667                                  cmd->request_bufflen,
668                                  scsi_to_pci_dma_dir(cmd->sc_data_direction));
669 }
670
671 static __inline int
672 ahc_linux_map_seg(struct ahc_softc *ahc, struct scb *scb,
673                   struct ahc_dma_seg *sg, bus_addr_t addr, bus_size_t len)
674 {
675         int      consumed;
676
677         if ((scb->sg_count + 1) > AHC_NSEG)
678                 panic("Too few segs for dma mapping.  "
679                       "Increase AHC_NSEG\n");
680
681         consumed = 1;
682         sg->addr = ahc_htole32(addr & 0xFFFFFFFF);
683         scb->platform_data->xfer_len += len;
684         if (sizeof(bus_addr_t) > 4
685          && (ahc->flags & AHC_39BIT_ADDRESSING) != 0) {
686                 /*
687                  * Due to DAC restrictions, we can't
688                  * cross a 4GB boundary.
689                  */
690                 if ((addr ^ (addr + len - 1)) & ~0xFFFFFFFF) {
691                         struct   ahc_dma_seg *next_sg;
692                         uint32_t next_len;
693
694                         printf("Crossed Seg\n");
695                         if ((scb->sg_count + 2) > AHC_NSEG)
696                                 panic("Too few segs for dma mapping.  "
697                                       "Increase AHC_NSEG\n");
698
699                         consumed++;
700                         next_sg = sg + 1;
701                         next_sg->addr = 0;
702                         next_len = 0x100000000 - (addr & 0xFFFFFFFF);
703                         len -= next_len;
704                         next_len |= ((addr >> 8) + 0x1000000) & 0x7F000000;
705                         next_sg->len = ahc_htole32(next_len);
706                 }
707                 len |= (addr >> 8) & 0x7F000000;
708         }
709         sg->len = ahc_htole32(len);
710         return (consumed);
711 }
712
713 /************************ Shutdown/halt/reboot hook ***************************/
714 #include <linux/notifier.h>
715 #include <linux/reboot.h>
716
717 static struct notifier_block ahc_linux_notifier = {
718         ahc_linux_halt, NULL, 0
719 };
720
721 static int ahc_linux_halt(struct notifier_block *nb, u_long event, void *buf)
722 {
723         struct ahc_softc *ahc;
724
725         TAILQ_FOREACH(ahc, &ahc_tailq, links) {
726                 ahc_shutdown(ahc);
727         }
728         return (NOTIFY_OK);
729 }
730
731 /******************************** Macros **************************************/
732 #define BUILD_SCSIID(ahc, cmd)                                          \
733         ((((cmd)->target << TID_SHIFT) & TID)                           \
734         | (((cmd)->channel == 0) ? (ahc)->our_id : (ahc)->our_id_b)     \
735         | (((cmd)->channel == 0) ? 0 : TWIN_CHNLB))
736
737 /******************************** Bus DMA *************************************/
738 int
739 ahc_dma_tag_create(struct ahc_softc *ahc, bus_dma_tag_t parent,
740                    bus_size_t alignment, bus_size_t boundary,
741                    bus_addr_t lowaddr, bus_addr_t highaddr,
742                    bus_dma_filter_t *filter, void *filterarg,
743                    bus_size_t maxsize, int nsegments,
744                    bus_size_t maxsegsz, int flags, bus_dma_tag_t *ret_tag)
745 {
746         bus_dma_tag_t dmat;
747
748         dmat = malloc(sizeof(*dmat), M_DEVBUF, M_NOWAIT);
749         if (dmat == NULL)
750                 return (ENOMEM);
751
752         /*
753          * Linux is very simplistic about DMA memory.  For now don't
754          * maintain all specification information.  Once Linux supplies
755          * better facilities for doing these operations, or the
756          * needs of this particular driver change, we might need to do
757          * more here.
758          */
759         dmat->alignment = alignment;
760         dmat->boundary = boundary;
761         dmat->maxsize = maxsize;
762         *ret_tag = dmat;
763         return (0);
764 }
765
766 void
767 ahc_dma_tag_destroy(struct ahc_softc *ahc, bus_dma_tag_t dmat)
768 {
769         free(dmat, M_DEVBUF);
770 }
771
772 int
773 ahc_dmamem_alloc(struct ahc_softc *ahc, bus_dma_tag_t dmat, void** vaddr,
774                  int flags, bus_dmamap_t *mapp)
775 {
776         bus_dmamap_t map;
777
778 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,3,0)
779         map = malloc(sizeof(*map), M_DEVBUF, M_NOWAIT);
780         if (map == NULL)
781                 return (ENOMEM);
782         /*
783          * Although we can dma data above 4GB, our
784          * "consistent" memory is below 4GB for
785          * space efficiency reasons (only need a 4byte
786          * address).  For this reason, we have to reset
787          * our dma mask when doing allocations.
788          */
789 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,3)
790         pci_set_dma_mask(ahc->dev_softc, 0xFFFFFFFF);
791 #else
792         ahc->dev_softc->dma_mask = 0xFFFFFFFF;
793 #endif
794         *vaddr = pci_alloc_consistent(ahc->dev_softc,
795                                       dmat->maxsize, &map->bus_addr);
796 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,3)
797         pci_set_dma_mask(ahc->dev_softc, ahc->platform_data->hw_dma_mask);
798 #else
799         ahc->dev_softc->dma_mask = ahc->platform_data->hw_dma_mask;
800 #endif
801 #else /* LINUX_VERSION_CODE < KERNEL_VERSION(2,3,0) */
802         /*
803          * At least in 2.2.14, malloc is a slab allocator so all
804          * allocations are aligned.  We assume, for these kernel versions
805          * that all allocations will be bellow 4Gig, physically contiguous,
806          * and accessable via DMA by the controller.
807          */
808         map = NULL; /* No additional information to store */
809         *vaddr = malloc(dmat->maxsize, M_DEVBUF, M_NOWAIT);
810 #endif
811         if (*vaddr == NULL)
812                 return (ENOMEM);
813         *mapp = map;
814         return(0);
815 }
816
817 void
818 ahc_dmamem_free(struct ahc_softc *ahc, bus_dma_tag_t dmat,
819                 void* vaddr, bus_dmamap_t map)
820 {
821 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,3,0)
822         pci_free_consistent(ahc->dev_softc, dmat->maxsize,
823                             vaddr, map->bus_addr);
824 #else
825         free(vaddr, M_DEVBUF);
826 #endif
827 }
828
829 int
830 ahc_dmamap_load(struct ahc_softc *ahc, bus_dma_tag_t dmat, bus_dmamap_t map,
831                 void *buf, bus_size_t buflen, bus_dmamap_callback_t *cb,
832                 void *cb_arg, int flags)
833 {
834         /*
835          * Assume for now that this will only be used during
836          * initialization and not for per-transaction buffer mapping.
837          */
838         bus_dma_segment_t stack_sg;
839
840 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,3,0)
841         stack_sg.ds_addr = map->bus_addr;
842 #else
843         stack_sg.ds_addr = VIRT_TO_BUS(buf);
844 #endif
845         stack_sg.ds_len = dmat->maxsize;
846         cb(cb_arg, &stack_sg, /*nseg*/1, /*error*/0);
847         return (0);
848 }
849
850 void
851 ahc_dmamap_destroy(struct ahc_softc *ahc, bus_dma_tag_t dmat, bus_dmamap_t map)
852 {
853         /*
854          * The map may is NULL in our < 2.3.X implementation.
855          */
856         if (map != NULL)
857                 free(map, M_DEVBUF);
858 }
859
860 int
861 ahc_dmamap_unload(struct ahc_softc *ahc, bus_dma_tag_t dmat, bus_dmamap_t map)
862 {
863         /* Nothing to do */
864         return (0);
865 }
866
867 /********************* Platform Dependent Functions ***************************/
868 int
869 ahc_softc_comp(struct ahc_softc *lahc, struct ahc_softc *rahc)
870 {
871         int     value;
872         int     rvalue;
873         int     lvalue;
874
875         /*
876          * Under Linux, cards are ordered as follows:
877          *      1) VLB/EISA BIOS enabled devices sorted by BIOS address.
878          *      2) PCI devices with BIOS enabled sorted by bus/slot/func.
879          *      3) All remaining VLB/EISA devices sorted by ioport.
880          *      4) All remaining PCI devices sorted by bus/slot/func.
881          */
882         value = (lahc->flags & AHC_BIOS_ENABLED)
883               - (rahc->flags & AHC_BIOS_ENABLED);
884         if (value != 0)
885                 /* Controllers with BIOS enabled have a *higher* priority */
886                 return (-value);
887
888         /*
889          * Same BIOS setting, now sort based on bus type.
890          * EISA and VL controllers sort together.  EISA/VL
891          * have higher priority than PCI.
892          */
893         rvalue = (rahc->chip & AHC_BUS_MASK);
894         if (rvalue == AHC_VL)
895                 rvalue = AHC_EISA;
896         lvalue = (lahc->chip & AHC_BUS_MASK);
897         if (lvalue == AHC_VL)
898                 lvalue = AHC_EISA;
899         value = lvalue - rvalue;
900         if (value != 0)
901                 return (value);
902
903         /* Still equal.  Sort by BIOS address, ioport, or bus/slot/func. */
904         switch (rvalue) {
905         case AHC_PCI:
906         {
907                 char primary_channel;
908
909                 value = ahc_get_pci_bus(lahc->dev_softc)
910                       - ahc_get_pci_bus(rahc->dev_softc);
911                 if (value != 0)
912                         break;
913                 value = ahc_get_pci_slot(lahc->dev_softc)
914                       - ahc_get_pci_slot(rahc->dev_softc);
915                 if (value != 0)
916                         break;
917                 /*
918                  * On multi-function devices, the user can choose
919                  * to have function 1 probed before function 0.
920                  * Give whichever channel is the primary channel
921                  * the lowest priority.
922                  */
923                 primary_channel = (lahc->flags & AHC_PRIMARY_CHANNEL) + 'A';
924                 value = 1;
925                 if (lahc->channel == primary_channel)
926                         value = -1;
927                 break;
928         }
929         case AHC_EISA:
930                 if ((rahc->flags & AHC_BIOS_ENABLED) != 0) {
931                         value = lahc->platform_data->bios_address
932                               - rahc->platform_data->bios_address; 
933                 } else {
934                         value = lahc->bsh.ioport
935                               - rahc->bsh.ioport; 
936                 }
937                 break;
938         default:
939                 panic("ahc_softc_sort: invalid bus type");
940         }
941         return (value);
942 }
943
944 static void
945 ahc_linux_setup_tag_info(char *p, char *end)
946 {
947         char    *base;
948         char    *tok;
949         char    *tok_end;
950         char    *tok_end2;
951         int      i;
952         int      instance;
953         int      targ;
954         int      done;
955         char     tok_list[] = {'.', ',', '{', '}', '\0'};
956
957         if (*p != ':')
958                 return;
959
960         instance = -1;
961         targ = -1;
962         done = FALSE;
963         base = p;
964         /* Forward us just past the ':' */
965         tok = base + 1;
966         tok_end = strchr(tok, '\0');
967         if (tok_end < end)
968                 *tok_end = ',';
969         while (!done) {
970                 switch (*tok) {
971                 case '{':
972                         if (instance == -1)
973                                 instance = 0;
974                         else if (targ == -1)
975                                 targ = 0;
976                         tok++;
977                         break;
978                 case '}':
979                         if (targ != -1)
980                                 targ = -1;
981                         else if (instance != -1)
982                                 instance = -1;
983                         tok++;
984                         break;
985                 case ',':
986                 case '.':
987                         if (instance == -1)
988                                 done = TRUE;
989                         else if (targ >= 0)
990                                 targ++;
991                         else if (instance >= 0)
992                                 instance++;
993                         if ((targ >= AHC_NUM_TARGETS) ||
994                             (instance >= NUM_ELEMENTS(aic7xxx_tag_info)))
995                                 done = TRUE;
996                         tok++;
997                         if (!done) {
998                                 base = tok;
999                         }
1000                         break;
1001                 case '\0':
1002                         done = TRUE;
1003                         break;
1004                 default:
1005                         done = TRUE;
1006                         tok_end = strchr(tok, '\0');
1007                         for (i = 0; tok_list[i]; i++) {
1008                                 tok_end2 = strchr(tok, tok_list[i]);
1009                                 if ((tok_end2) && (tok_end2 < tok_end)) {
1010                                         tok_end = tok_end2;
1011                                         done = FALSE;
1012                                 }
1013                         }
1014                         if ((instance >= 0) && (targ >= 0)
1015                          && (instance < NUM_ELEMENTS(aic7xxx_tag_info))
1016                          && (targ < AHC_NUM_TARGETS)) {
1017                                 aic7xxx_tag_info[instance].tag_commands[targ] =
1018                                     simple_strtoul(tok, NULL, 0) & 0xff;
1019                         }
1020                         tok = tok_end;
1021                         break;
1022                 }
1023         }
1024         while ((p != base) && (p != NULL))
1025                 p = strtok(NULL, ",.");
1026 }
1027
1028 /*
1029  * Handle Linux boot parameters. This routine allows for assigning a value
1030  * to a parameter with a ':' between the parameter and the value.
1031  * ie. aic7xxx=unpause:0x0A,extended
1032  */
1033 int
1034 aic7xxx_setup(char *s)
1035 {
1036         int     i, n;
1037         char   *p;
1038         char   *end;
1039
1040         static struct {
1041                 const char *name;
1042                 uint32_t *flag;
1043         } options[] = {
1044                 { "extended", &aic7xxx_extended },
1045                 { "no_reset", &aic7xxx_no_reset },
1046                 { "irq_trigger", &aic7xxx_irq_trigger },
1047                 { "verbose", &aic7xxx_verbose },
1048                 { "reverse_scan", &aic7xxx_reverse_scan },
1049                 { "override_term", &aic7xxx_override_term },
1050                 { "stpwlev", &aic7xxx_stpwlev },
1051                 { "no_probe", &aic7xxx_no_probe },
1052                 { "panic_on_abort", &aic7xxx_panic_on_abort },
1053                 { "pci_parity", &aic7xxx_pci_parity },
1054                 { "dump_sequencer", &aic7xxx_dump_sequencer },
1055                 { "seltime", &aic7xxx_seltime },
1056                 { "tag_info", NULL }
1057         };
1058
1059         end = strchr(s, '\0');
1060
1061         for (p = strtok(s, ",."); p; p = strtok(NULL, ",.")) {
1062                 for (i = 0; i < NUM_ELEMENTS(options); i++) {
1063                         n = strlen(options[i].name);
1064
1065                         if (strncmp(options[i].name, p, n) != 0)
1066                                 continue;
1067
1068                         if (strncmp(p, "tag_info", n) == 0) {
1069                                 ahc_linux_setup_tag_info(p + n, end);
1070                         } else if (p[n] == ':') {
1071                                 *(options[i].flag) =
1072                                     simple_strtoul(p + n + 1, NULL, 0);
1073                         } else if (!strncmp(p, "verbose", n)) {
1074                                 *(options[i].flag) = 1;
1075                         } else {
1076                                 *(options[i].flag) = ~(*(options[i].flag));
1077                         }
1078                         break;
1079                 }
1080         }
1081         register_reboot_notifier(&ahc_linux_notifier);
1082         return 1;
1083 }
1084
1085 #if LINUX_VERSION_CODE > KERNEL_VERSION(2,3,0)
1086 __setup("aic7xxx=", aic7xxx_setup);
1087 #endif
1088
1089 int aic7xxx_verbose;
1090
1091 /*
1092  * Try to detect an Adaptec 7XXX controller.
1093  */
1094 int
1095 ahc_linux_detect(Scsi_Host_Template *template)
1096 {
1097         struct  ahc_softc *ahc;
1098         int     found;
1099
1100         /*
1101          * Sanity checking of Linux SCSI data structures so
1102          * that some of our hacks^H^H^H^H^Hassumptions aren't
1103          * violated.
1104          */
1105         if (offsetof(struct ahc_cmd_internal, end)
1106           > offsetof(struct scsi_cmnd, host_scribble)) {
1107                 printf("ahc_linux_detect: SCSI data structures changed.\n");
1108                 printf("ahc_linux_detect: Unable to attach\n");
1109                 return (0);
1110         }
1111 #ifdef MODULE
1112         /*
1113          * If we've been passed any parameters, process them now.
1114          */
1115         if (aic7xxx)
1116                 aic7xxx_setup(aic7xxx);
1117         if (dummy_buffer[0] != 'P')
1118                 printk(KERN_WARNING
1119 "aic7xxx: Please read the file /usr/src/linux/drivers/scsi/README.aic7xxx\n"
1120 "aic7xxx: to see the proper way to specify options to the aic7xxx module\n"
1121 "aic7xxx: Specifically, don't use any commas when passing arguments to\n"
1122 "aic7xxx: insmod or else it might trash certain memory areas.\n");
1123 #endif
1124
1125 #if LINUX_VERSION_CODE > KERNEL_VERSION(2,3,0)
1126         template->proc_name = "aic7xxx";
1127 #else
1128         template->proc_dir = &proc_scsi_aic7xxx;
1129 #endif
1130         template->sg_tablesize = AHC_NSEG;
1131
1132 #ifdef CONFIG_PCI
1133         ahc_linux_pci_probe(template);
1134 #endif
1135
1136         aic7770_linux_probe(template);
1137
1138         /*
1139          * Register with the SCSI layer all
1140          * controllers we've found.
1141          */
1142         found = 0;
1143         TAILQ_FOREACH(ahc, &ahc_tailq, links) {
1144
1145                 if (ahc_linux_register_host(ahc, template) == 0)
1146                         found++;
1147         }
1148         aic7xxx_detect_complete++;
1149         return (found);
1150 }
1151
1152 int
1153 ahc_linux_register_host(struct ahc_softc *ahc, Scsi_Host_Template *template)
1154 {
1155         char  buf[80];
1156         struct Scsi_Host *host;
1157         char *new_name;
1158         u_long s;
1159
1160
1161         template->name = ahc->description;
1162         host = scsi_register(template, sizeof(struct ahc_softc *));
1163         if (host == NULL)
1164                 return (ENOMEM);
1165
1166         ahc_lock(ahc, &s);
1167         *((struct ahc_softc **)host->hostdata) = ahc;
1168         ahc->platform_data->host = host;
1169         host->can_queue = AHC_MAX_QUEUE;
1170         host->cmd_per_lun = 2;
1171         host->sg_tablesize = AHC_NSEG;
1172         host->select_queue_depths = ahc_linux_select_queue_depth;
1173         /* XXX No way to communicate the ID for multiple channels */
1174         host->this_id = ahc->our_id;
1175         host->irq = ahc->platform_data->irq;
1176         host->max_id = (ahc->features & AHC_WIDE) ? 16 : 8;
1177         host->max_channel = (ahc->features & AHC_TWIN) ? 1 : 0;
1178         host->max_lun = AHC_NUM_LUNS;
1179         ahc_set_unit(ahc, ahc_linux_next_unit());
1180         sprintf(buf, "scsi%d", host->host_no);
1181         new_name = malloc(strlen(buf) + 1, M_DEVBUF, M_NOWAIT);
1182         if (new_name != NULL) {
1183                 strcpy(new_name, buf);
1184                 ahc_set_name(ahc, new_name);
1185         }
1186         host->unique_id = ahc->unit;
1187 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,4)
1188         scsi_set_pci_device(host, ahc->dev_softc);
1189 #endif
1190         ahc_linux_initialize_scsi_bus(ahc);
1191         ahc_unlock(ahc, &s);
1192         return (0);
1193 }
1194
1195 uint64_t
1196 ahc_linux_get_memsize()
1197 {
1198         struct sysinfo si;
1199
1200         si_meminfo(&si);
1201         return (si.totalram << PAGE_SHIFT);
1202 }
1203
1204 /*
1205  * Find the smallest available unit number to use
1206  * for a new device.  We don't just use a static
1207  * count to handle the "repeated hot-(un)plug"
1208  * scenario.
1209  */
1210 static int
1211 ahc_linux_next_unit()
1212 {
1213         struct ahc_softc *ahc;
1214         int unit;
1215
1216         unit = 0;
1217 retry:
1218         TAILQ_FOREACH(ahc, &ahc_tailq, links) {
1219                 if (ahc->unit == unit) {
1220                         unit++;
1221                         goto retry;
1222                 }
1223         }
1224         return (unit);
1225 }
1226
1227 /*
1228  * Place the SCSI bus into a known state by either resetting it,
1229  * or forcing transfer negotiations on the next command to any
1230  * target.
1231  */
1232 void
1233 ahc_linux_initialize_scsi_bus(struct ahc_softc *ahc)
1234 {
1235         int i;
1236         int numtarg;
1237
1238         i = 0;
1239         numtarg = 0;
1240
1241         if (aic7xxx_no_reset != 0)
1242                 ahc->flags &= ~(AHC_RESET_BUS_A|AHC_RESET_BUS_B);
1243
1244         if ((ahc->flags & AHC_RESET_BUS_A) != 0)
1245                 ahc_reset_channel(ahc, 'A', /*initiate_reset*/TRUE);
1246         else
1247                 numtarg = (ahc->features & AHC_WIDE) ? 16 : 8;
1248
1249         if ((ahc->features & AHC_TWIN) != 0) {
1250
1251                 if ((ahc->flags & AHC_RESET_BUS_B) != 0) {
1252                         ahc_reset_channel(ahc, 'B', /*initiate_reset*/TRUE);
1253                 } else {
1254                         if (numtarg == 0)
1255                                 i = 8;
1256                         numtarg += 8;
1257                 }
1258         }
1259
1260         for (; i < numtarg; i++) {
1261                 struct ahc_devinfo devinfo;
1262                 struct ahc_initiator_tinfo *tinfo;
1263                 struct ahc_tmode_tstate *tstate;
1264                 u_int our_id;
1265                 u_int target_id;
1266                 char channel;
1267
1268                 channel = 'A';
1269                 our_id = ahc->our_id;
1270                 target_id = i;
1271                 if (i > 7 && (ahc->features & AHC_TWIN) != 0) {
1272                         channel = 'B';
1273                         our_id = ahc->our_id_b;
1274                         target_id = i % 8;
1275                 }
1276                 tinfo = ahc_fetch_transinfo(ahc, channel, our_id,
1277                                             target_id, &tstate);
1278                 tinfo->goal = tinfo->user;
1279                 /*
1280                  * Don't try negotiations that require PPR messages
1281                  * until we successfully retrieve Inquiry data.
1282                  */
1283                 tinfo->goal.ppr_options = 0;
1284                 if (tinfo->goal.transport_version > SCSI_REV_2)
1285                         tinfo->goal.transport_version = SCSI_REV_2;
1286                 ahc_compile_devinfo(&devinfo, our_id, target_id,
1287                                    CAM_LUN_WILDCARD, channel, ROLE_INITIATOR);
1288                 ahc_update_neg_request(ahc, &devinfo, tstate,
1289                                        tinfo, /*force*/FALSE);
1290         }
1291         /* Give the bus some time to recover */
1292         if ((ahc->flags & (AHC_RESET_BUS_A|AHC_RESET_BUS_B)) != 0) {
1293                 ahc_linux_freeze_sim_queue(ahc);
1294                 init_timer(&ahc->platform_data->reset_timer);
1295                 ahc->platform_data->reset_timer.data = (u_long)ahc;
1296                 ahc->platform_data->reset_timer.expires =
1297                     jiffies + (AIC7XXX_RESET_DELAY * HZ)/1000;
1298                 ahc->platform_data->reset_timer.function =
1299                     ahc_linux_release_sim_queue;
1300                 add_timer(&ahc->platform_data->reset_timer);
1301         }
1302 }
1303
1304 int
1305 ahc_platform_alloc(struct ahc_softc *ahc, void *platform_arg)
1306 {
1307         ahc->platform_data =
1308             malloc(sizeof(struct ahc_platform_data), M_DEVBUF, M_NOWAIT);
1309         if (ahc->platform_data == NULL)
1310                 return (ENOMEM);
1311         memset(ahc->platform_data, 0, sizeof(struct ahc_platform_data));
1312         TAILQ_INIT(&ahc->platform_data->completeq);
1313         TAILQ_INIT(&ahc->platform_data->device_runq);
1314         ahc->platform_data->hw_dma_mask = 0xFFFFFFFF;
1315         ahc_lockinit(ahc);
1316         ahc_done_lockinit(ahc);
1317 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,3,0)
1318         init_MUTEX_LOCKED(&ahc->platform_data->eh_sem);
1319 #else
1320         ahc->platform_data->eh_sem = MUTEX_LOCKED;
1321 #endif
1322         ahc->seltime = (aic7xxx_seltime & 0x3) << 4;
1323         ahc->seltime_b = (aic7xxx_seltime & 0x3) << 4;
1324         return (0);
1325 }
1326
1327 void
1328 ahc_platform_free(struct ahc_softc *ahc)
1329 {
1330         if (ahc->platform_data != NULL) {
1331                 if (ahc->platform_data->host != NULL)
1332                         scsi_unregister(ahc->platform_data->host);
1333                 if (ahc->platform_data->irq)
1334                         free_irq(ahc->platform_data->irq, ahc);
1335                 if (ahc->tag == BUS_SPACE_PIO
1336                  && ahc->bsh.ioport != 0)
1337                         release_region(ahc->bsh.ioport, 256);
1338                 if (ahc->tag == BUS_SPACE_MEMIO
1339                  && ahc->bsh.maddr != NULL) {
1340                         u_long base_addr;
1341
1342                         base_addr = (u_long)ahc->bsh.maddr;
1343                         base_addr &= PAGE_MASK;
1344                         iounmap((void *)base_addr);
1345 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0)
1346                         release_mem_region(ahc->platform_data->mem_busaddr,
1347                                            0x1000);
1348 #endif
1349                 }
1350 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0)
1351                 /* XXX Need an instance detach in the PCI code */
1352                 if (ahc->dev_softc != NULL)
1353                         ahc->dev_softc->driver = NULL;
1354 #endif
1355                 free(ahc->platform_data, M_DEVBUF);
1356         }
1357 }
1358
1359 void
1360 ahc_platform_freeze_devq(struct ahc_softc *ahc, struct scb *scb)
1361 {
1362         ahc_platform_abort_scbs(ahc, SCB_GET_TARGET(ahc, scb),
1363                                 SCB_GET_CHANNEL(ahc, scb),
1364                                 SCB_GET_LUN(scb), SCB_LIST_NULL,
1365                                 ROLE_UNKNOWN, CAM_REQUEUE_REQ);
1366 }
1367
1368 void
1369 ahc_platform_set_tags(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
1370                       ahc_queue_alg alg)
1371 {
1372         struct ahc_linux_device *dev;
1373         int was_queuing;
1374         int now_queuing;
1375
1376         dev = ahc_linux_get_device(ahc, devinfo->channel - 'A',
1377                                    devinfo->target,
1378                                    devinfo->lun, /*alloc*/FALSE);
1379         if (dev == NULL)
1380                 return;
1381         was_queuing = dev->flags & (AHC_DEV_Q_BASIC|AHC_DEV_Q_TAGGED);
1382         now_queuing = alg != AHC_QUEUE_NONE;
1383         if ((dev->flags & AHC_DEV_FREEZE_TIL_EMPTY) == 0
1384          && (was_queuing != now_queuing)
1385          && (dev->active != 0)) {
1386                 dev->flags |= AHC_DEV_FREEZE_TIL_EMPTY;
1387                 dev->qfrozen++;
1388         }
1389
1390         dev->flags &= ~(AHC_DEV_Q_BASIC|AHC_DEV_Q_TAGGED);
1391         if (now_queuing) {
1392
1393                 if (!was_queuing) {
1394                         /*
1395                          * Start out agressively and allow our
1396                          * dynamic queue depth algorithm to take
1397                          * care of the rest.
1398                          */
1399                         dev->maxtags = AHC_MAX_QUEUE;
1400                         dev->openings = dev->maxtags - dev->active;
1401                 }
1402                 if (alg == AHC_QUEUE_TAGGED)
1403                         dev->flags |= AHC_DEV_Q_TAGGED;
1404                 else
1405                         dev->flags |= AHC_DEV_Q_BASIC;
1406         } else {
1407                 /* We can only have one opening */
1408                 dev->maxtags = 0;
1409                 dev->openings =  1 - dev->active;
1410         }
1411 }
1412
1413 int
1414 ahc_platform_abort_scbs(struct ahc_softc *ahc, int target, char channel,
1415                         int lun, u_int tag, role_t role, uint32_t status)
1416 {
1417         int chan;
1418         int maxchan;
1419         int targ;
1420         int maxtarg;
1421         int clun;
1422         int maxlun;
1423         int count;
1424
1425         if (tag != SCB_LIST_NULL)
1426                 return (0);
1427
1428         chan = 0;
1429         if (channel != ALL_CHANNELS) {
1430                 chan = channel - 'A';
1431                 maxchan = chan + 1;
1432         } else {
1433                 maxchan = (ahc->features & AHC_TWIN) ? 2 : 1;
1434         }
1435         targ = 0;
1436         if (target != CAM_TARGET_WILDCARD) {
1437                 targ = target;
1438                 maxtarg = targ + 1;
1439         } else {
1440                 maxtarg = (ahc->features & AHC_WIDE) ? 16 : 8;
1441         }
1442         clun = 0;
1443         if (lun != CAM_LUN_WILDCARD) {
1444                 clun = lun;
1445                 maxlun = clun + 1;
1446         } else {
1447                 maxlun = 16;
1448         }
1449
1450         count = 0;
1451         for (; chan < maxchan; chan++) {
1452                 for (; targ < maxtarg; targ++) {
1453                         for (; clun < maxlun; clun++) {
1454                                 struct ahc_linux_device *dev;
1455                                 struct ahc_busyq *busyq;
1456                                 struct ahc_cmd *acmd;
1457
1458                                 dev = ahc_linux_get_device(ahc, chan,
1459                                                            targ, clun,
1460                                                            /*alloc*/FALSE);
1461                                 if (dev == NULL)
1462                                         continue;
1463
1464                                 busyq = &dev->busyq;
1465                                 while ((acmd = TAILQ_FIRST(busyq)) != NULL) {
1466                                         Scsi_Cmnd *cmd;
1467
1468                                         cmd = &acmd_scsi_cmd(acmd);
1469                                         TAILQ_REMOVE(busyq, acmd,
1470                                                      acmd_links.tqe);
1471                                         count++;
1472                                         cmd->result = status << 16;
1473                                         ahc_linux_queue_cmd_complete(ahc, cmd);
1474                                 }
1475                         }
1476                 }
1477         }
1478
1479         return (count);
1480 }
1481
1482 /*
1483  * Sets the queue depth for each SCSI device hanging
1484  * off the input host adapter.
1485  */
1486 static void
1487 ahc_linux_select_queue_depth(struct Scsi_Host * host,
1488                              Scsi_Device * scsi_devs)
1489 {
1490         Scsi_Device *device;
1491         struct  ahc_softc *ahc;
1492         u_long  flags;
1493         int     scbnum;
1494
1495         ahc = *((struct ahc_softc **)host->hostdata);
1496         ahc_lock(ahc, &flags);
1497         scbnum = 0;
1498         for (device = scsi_devs; device != NULL; device = device->next) {
1499                 if (device->host == host) {
1500                         ahc_linux_device_queue_depth(ahc, device);
1501                         scbnum += device->queue_depth;
1502                 }
1503         }
1504         ahc_unlock(ahc, &flags);
1505 }
1506
1507 /*
1508  * Determines the queue depth for a given device.
1509  */
1510 static void
1511 ahc_linux_device_queue_depth(struct ahc_softc *ahc, Scsi_Device * device)
1512 {
1513         struct  ahc_devinfo devinfo;
1514         struct  ahc_initiator_tinfo *targ_info;
1515         struct  ahc_tmode_tstate *tstate;
1516         uint8_t tags;
1517
1518         ahc_compile_devinfo(&devinfo,
1519                             device->channel == 0 ? ahc->our_id : ahc->our_id_b,
1520                             device->id, device->lun,
1521                             device->channel == 0 ? 'A' : 'B',
1522                             ROLE_INITIATOR);
1523         targ_info = ahc_fetch_transinfo(ahc, devinfo.channel,
1524                                         devinfo.our_scsiid,
1525                                         devinfo.target, &tstate);
1526
1527         tags = 0;
1528         if (device->tagged_supported != 0
1529          && (ahc->user_discenable & devinfo.target_mask) != 0) {
1530                 if (ahc->unit >= NUM_ELEMENTS(aic7xxx_tag_info)) {
1531
1532                         printf("aic7xxx: WARNING, insufficient "
1533                                "tag_info instances for installed "
1534                                "controllers. Using defaults\n");
1535                         printf("aic7xxx: Please update the "
1536                                "aic7xxx_tag_info array in the "
1537                                "aic7xxx.c source file.\n");
1538                         tags = AHC_MAX_QUEUE;
1539                 } else {
1540                         adapter_tag_info_t *tag_info;
1541
1542                         tag_info = &aic7xxx_tag_info[ahc->unit];
1543                         tags = tag_info->tag_commands[devinfo.target_offset];
1544                         if (tags > AHC_MAX_QUEUE)
1545                                 tags = AHC_MAX_QUEUE;
1546                 }
1547         }
1548         if (tags != 0) {
1549                 device->queue_depth = tags;
1550                 ahc_set_tags(ahc, &devinfo, AHC_QUEUE_TAGGED);
1551                 printf("scsi%d:%d:%d:%d: Tagged Queuing enabled.  Depth %d\n",
1552                        ahc->platform_data->host->host_no, device->channel,
1553                        device->id, device->lun, tags);
1554         } else {
1555                 /*
1556                  * We allow the OS to queue 2 untagged transactions to
1557                  * us at any time even though we can only execute them
1558                  * serially on the controller/device.  This should remove
1559                  * some latency.
1560                  */
1561                 device->queue_depth = 2;
1562         }
1563 }
1564
1565 /*
1566  * Queue an SCB to the controller.
1567  */
1568 int
1569 ahc_linux_queue(Scsi_Cmnd * cmd, void (*scsi_done) (Scsi_Cmnd *))
1570 {
1571         struct   ahc_softc *ahc;
1572         struct   ahc_linux_device *dev;
1573         u_long   flags;
1574
1575         ahc = *(struct ahc_softc **)cmd->host->hostdata;
1576
1577         /*
1578          * Save the callback on completion function.
1579          */
1580         cmd->scsi_done = scsi_done;
1581
1582         ahc_lock(ahc, &flags);
1583         dev = ahc_linux_get_device(ahc, cmd->channel, cmd->target,
1584                                    cmd->lun, /*alloc*/TRUE);
1585         if (dev == NULL) {
1586                 ahc_unlock(ahc, &flags);
1587                 printf("aic7xxx_linux_queue: Unable to allocate device!\n");
1588                 return (-ENOMEM);
1589         }
1590         cmd->result = CAM_REQ_INPROG << 16;
1591         TAILQ_INSERT_TAIL(&dev->busyq, (struct ahc_cmd *)cmd, acmd_links.tqe);
1592         if ((dev->flags & AHC_DEV_ON_RUN_LIST) == 0) {
1593                 TAILQ_INSERT_TAIL(&ahc->platform_data->device_runq, dev, links);
1594                 dev->flags |= AHC_DEV_ON_RUN_LIST;
1595                 ahc_linux_run_device_queues(ahc);
1596         }
1597         ahc_unlock(ahc, &flags);
1598         return (0);
1599 }
1600
1601 static void
1602 ahc_linux_run_device_queue(struct ahc_softc *ahc, struct ahc_linux_device *dev)
1603 {
1604         struct   ahc_cmd *acmd;
1605         struct   scsi_cmnd *cmd;
1606         struct   scb *scb;
1607         struct   hardware_scb *hscb;
1608         struct   ahc_initiator_tinfo *tinfo;
1609         struct   ahc_tmode_tstate *tstate;
1610         uint16_t mask;
1611
1612         if ((dev->flags & AHC_DEV_ON_RUN_LIST) != 0)
1613                 panic("running device on run list");
1614
1615         while ((acmd = TAILQ_FIRST(&dev->busyq)) != NULL
1616             && dev->openings > 0 && dev->qfrozen == 0) {
1617
1618                 /*
1619                  * Schedule us to run later.  The only reason we are not
1620                  * running is because the whole controller Q is frozen.
1621                  */
1622                 if (ahc->platform_data->qfrozen != 0) {
1623
1624                         TAILQ_INSERT_TAIL(&ahc->platform_data->device_runq,
1625                                           dev, links);
1626                         dev->flags |= AHC_DEV_ON_RUN_LIST;
1627                         return;
1628                 }
1629                 /*
1630                  * Get an scb to use.
1631                  */
1632                 if ((scb = ahc_get_scb(ahc)) == NULL) {
1633                         TAILQ_INSERT_TAIL(&ahc->platform_data->device_runq,
1634                                          dev, links);
1635                         dev->flags |= AHC_DEV_ON_RUN_LIST;
1636                         ahc->flags |= AHC_RESOURCE_SHORTAGE;
1637                         return;
1638                 }
1639                 TAILQ_REMOVE(&dev->busyq, acmd, acmd_links.tqe);
1640                 cmd = &acmd_scsi_cmd(acmd);
1641                 scb->io_ctx = cmd;
1642                 scb->platform_data->dev = dev;
1643                 hscb = scb->hscb;
1644                 cmd->host_scribble = (char *)scb;
1645
1646                 /*
1647                  * Fill out basics of the HSCB.
1648                  */
1649                 hscb->control = 0;
1650                 hscb->scsiid = BUILD_SCSIID(ahc, cmd);
1651                 hscb->lun = cmd->lun;
1652                 mask = SCB_GET_TARGET_MASK(ahc, scb);
1653                 tinfo = ahc_fetch_transinfo(ahc, SCB_GET_CHANNEL(ahc, scb),
1654                                             SCB_GET_OUR_ID(scb),
1655                                             SCB_GET_TARGET(ahc, scb), &tstate);
1656                 hscb->scsirate = tinfo->scsirate;
1657                 hscb->scsioffset = tinfo->curr.offset;
1658                 if ((tstate->ultraenb & mask) != 0)
1659                         hscb->control |= ULTRAENB;
1660
1661                 if ((ahc->user_discenable & mask) != 0)
1662                         hscb->control |= DISCENB;
1663
1664                 if ((tstate->auto_negotiate & mask) != 0) {
1665                         scb->flags |= SCB_AUTO_NEGOTIATE;
1666                         scb->hscb->control |= MK_MESSAGE;
1667                 }
1668
1669                 if ((dev->flags & (AHC_DEV_Q_TAGGED|AHC_DEV_Q_BASIC)) != 0) {
1670                         if (dev->commands_since_idle_or_otag == AHC_OTAG_THRESH
1671                          && (dev->flags & AHC_DEV_Q_TAGGED) != 0) {
1672                                 hscb->control |= MSG_ORDERED_TASK;
1673                                 dev->commands_since_idle_or_otag = 0;
1674                         } else {
1675                                 hscb->control |= MSG_SIMPLE_TASK;
1676                         }
1677                 }
1678
1679                 hscb->cdb_len = cmd->cmd_len;
1680                 if (hscb->cdb_len <= 12) {
1681                         memcpy(hscb->shared_data.cdb, cmd->cmnd, hscb->cdb_len);
1682                 } else {
1683                         memcpy(hscb->cdb32, cmd->cmnd, hscb->cdb_len);
1684                         scb->flags |= SCB_CDB32_PTR;
1685                 }
1686
1687                 scb->platform_data->xfer_len = 0;
1688                 ahc_set_residual(scb, 0);
1689                 ahc_set_sense_residual(scb, 0);
1690                 if (cmd->use_sg != 0) {
1691                         struct  ahc_dma_seg *sg;
1692                         struct  scatterlist *cur_seg;
1693                         struct  scatterlist *end_seg;
1694                         int     nseg;
1695
1696                         cur_seg = (struct scatterlist *)cmd->request_buffer;
1697                         nseg = pci_map_sg(ahc->dev_softc, cur_seg, cmd->use_sg,
1698                                  scsi_to_pci_dma_dir(cmd ->sc_data_direction));
1699                         end_seg = cur_seg + nseg;
1700                         /* Copy the segments into the SG list. */
1701                         sg = scb->sg_list;
1702                         /*
1703                          * The sg_count may be larger than nseg if
1704                          * a transfer crosses a 32bit page.
1705                          */ 
1706                         scb->sg_count = 0;
1707                         while(cur_seg < end_seg) {
1708                                 bus_addr_t addr;
1709                                 bus_size_t len;
1710                                 int consumed;
1711
1712                                 addr = sg_dma_address(cur_seg);
1713                                 len = sg_dma_len(cur_seg);
1714                                 consumed = ahc_linux_map_seg(ahc, scb,
1715                                                              sg, addr, len);
1716                                 sg += consumed;
1717                                 scb->sg_count += consumed;
1718                                 cur_seg++;
1719                         }
1720                         sg--;
1721                         sg->len |= ahc_htole32(AHC_DMA_LAST_SEG);
1722
1723                         /*
1724                          * Reset the sg list pointer.
1725                          */
1726                         scb->hscb->sgptr =
1727                             ahc_htole32(scb->sg_list_phys | SG_FULL_RESID);
1728
1729                         /*
1730                          * Copy the first SG into the "current"
1731                          * data pointer area.
1732                          */
1733                         scb->hscb->dataptr = scb->sg_list->addr;
1734                         scb->hscb->datacnt = scb->sg_list->len;
1735                 } else if (cmd->request_bufflen != 0) {
1736                         struct   ahc_dma_seg *sg;
1737                         bus_addr_t addr;
1738
1739                         sg = scb->sg_list;
1740                         addr = pci_map_single(ahc->dev_softc,
1741                                cmd->request_buffer,
1742                                cmd->request_bufflen,
1743                                scsi_to_pci_dma_dir(cmd->sc_data_direction));
1744                         scb->sg_count = ahc_linux_map_seg(ahc, scb,
1745                                                           sg, addr,
1746                                                           cmd->request_bufflen);
1747                         sg->len |= ahc_htole32(AHC_DMA_LAST_SEG);
1748
1749                         /*
1750                          * Reset the sg list pointer.
1751                          */
1752                         scb->hscb->sgptr =
1753                             ahc_htole32(scb->sg_list_phys | SG_FULL_RESID);
1754
1755                         /*
1756                          * Copy the first SG into the "current"
1757                          * data pointer area.
1758                          */
1759                         scb->hscb->dataptr = sg->addr;
1760                         scb->hscb->datacnt = sg->len;
1761                 } else {
1762                         scb->hscb->sgptr = ahc_htole32(SG_LIST_NULL);
1763                         scb->hscb->dataptr = 0;
1764                         scb->hscb->datacnt = 0;
1765                         scb->sg_count = 0;
1766                 }
1767
1768                 ahc_sync_sglist(ahc, scb, BUS_DMASYNC_PREWRITE);
1769                 LIST_INSERT_HEAD(&ahc->pending_scbs, scb, pending_links);
1770                 dev->openings--;
1771                 dev->active++;
1772                 dev->commands_issued++;
1773                 dev->commands_since_idle_or_otag++;
1774
1775                 /*
1776                  * We only allow one untagged transaction
1777                  * per target in the initiator role unless
1778                  * we are storing a full busy target *lun*
1779                  * table in SCB space.
1780                  */
1781                 if ((scb->hscb->control & (TARGET_SCB|TAG_ENB)) == 0
1782                  && (ahc->features & AHC_SCB_BTT) == 0) {
1783                         struct scb_tailq *untagged_q;
1784                         int target_offset;
1785
1786                         target_offset = SCB_GET_TARGET_OFFSET(ahc, scb);
1787                         untagged_q = &(ahc->untagged_queues[target_offset]);
1788                         TAILQ_INSERT_TAIL(untagged_q, scb, links.tqe);
1789                         scb->flags |= SCB_UNTAGGEDQ;
1790                         if (TAILQ_FIRST(untagged_q) != scb)
1791                                 continue;
1792                 }
1793                 scb->flags |= SCB_ACTIVE;
1794                 ahc_queue_scb(ahc, scb);
1795         }
1796 }
1797
1798 /*
1799  * SCSI controller interrupt handler.
1800  */
1801 void
1802 ahc_linux_isr(int irq, void *dev_id, struct pt_regs * regs)
1803 {
1804         struct ahc_softc *ahc;
1805         struct ahc_cmd *acmd;
1806         u_long flags;
1807
1808         ahc = (struct ahc_softc *) dev_id;
1809         ahc_lock(ahc, &flags); 
1810         ahc_intr(ahc);
1811         /*
1812          * It would be nice to run the device queues from a
1813          * bottom half handler, but as there is no way to
1814          * dynamically register one, we'll have to postpone
1815          * that until we get integrated into the kernel.
1816          */
1817         ahc_linux_run_device_queues(ahc);
1818         acmd = TAILQ_FIRST(&ahc->platform_data->completeq);
1819         TAILQ_INIT(&ahc->platform_data->completeq);
1820         ahc_unlock(ahc, &flags);
1821         if (acmd != NULL)
1822                 ahc_linux_run_complete_queue(ahc, acmd);
1823 }
1824
1825 void
1826 ahc_platform_flushwork(struct ahc_softc *ahc)
1827 {
1828         struct ahc_cmd *acmd;
1829
1830         acmd = TAILQ_FIRST(&ahc->platform_data->completeq);
1831         TAILQ_INIT(&ahc->platform_data->completeq);
1832         if (acmd != NULL)
1833                 ahc_linux_run_complete_queue(ahc, acmd);
1834 }
1835
1836 static struct ahc_linux_target*
1837 ahc_linux_alloc_target(struct ahc_softc *ahc, u_int channel, u_int target)
1838 {
1839         struct ahc_linux_target *targ;
1840         u_int target_offset;
1841
1842         targ = malloc(sizeof(*targ), M_DEVBUG, M_NOWAIT);
1843         if (targ == NULL)
1844                 return (NULL);
1845         memset(targ, 0, sizeof(*targ));
1846         targ->channel = channel;
1847         targ->target = target;
1848         target_offset = target;
1849         if (channel != 0)
1850                 target_offset += 8;
1851         ahc->platform_data->targets[target_offset] = targ;
1852         return (targ);
1853 }
1854
1855 static void
1856 ahc_linux_free_target(struct ahc_softc *ahc, struct ahc_linux_target *targ)
1857 {
1858         u_int target_offset;
1859
1860         target_offset = targ->target;
1861         if (targ->channel != 0)
1862                 target_offset += 8;
1863         ahc->platform_data->targets[target_offset] = NULL;
1864         free(targ, M_DEVBUF);
1865 }
1866
1867 static struct ahc_linux_device*
1868 ahc_linux_alloc_device(struct ahc_softc *ahc,
1869                  struct ahc_linux_target *targ, u_int lun)
1870 {
1871         struct ahc_linux_device *dev;
1872
1873         dev = malloc(sizeof(*dev), M_DEVBUG, M_NOWAIT);
1874         if (dev == NULL)
1875                 return (NULL);
1876         memset(dev, 0, sizeof(*dev));
1877         TAILQ_INIT(&dev->busyq);
1878         dev->flags = AHC_DEV_UNCONFIGURED;
1879         dev->lun = lun;
1880         dev->target = targ;
1881
1882         /*
1883          * We start out life using untagged
1884          * transactions of which we allow one.
1885          */
1886         dev->openings = 1;
1887
1888         /*
1889          * Set maxtags to 0.  This will be changed if we
1890          * later determine that we are dealing with
1891          * a tagged queuing capable device.
1892          */
1893         dev->maxtags = 0;
1894         
1895         targ->refcount++;
1896         targ->devices[lun] = dev;
1897         return (dev);
1898 }
1899
1900 static void
1901 ahc_linux_free_device(struct ahc_softc *ahc, struct ahc_linux_device *dev)
1902 {
1903         struct ahc_linux_target *targ;
1904
1905         targ = dev->target;
1906         targ->devices[dev->lun] = NULL;
1907         free(dev, M_DEVBUF);
1908         targ->refcount--;
1909         if (targ->refcount == 0)
1910                 ahc_linux_free_target(ahc, targ);
1911 }
1912
1913 /*
1914  * Return a string describing the driver.
1915  */
1916 const char *
1917 ahc_linux_info(struct Scsi_Host *host)
1918 {
1919         static char buffer[512];
1920         char    ahc_info[256];
1921         char   *bp;
1922         struct ahc_softc *ahc;
1923
1924         bp = &buffer[0];
1925         ahc = *(struct ahc_softc **)host->hostdata;
1926         memset(bp, 0, sizeof(buffer));
1927         strcpy(bp, "Adaptec AIC7XXX EISA/VLB/PCI SCSI HBA DRIVER, Rev ");
1928         strcat(bp, AIC7XXX_DRIVER_VERSION);
1929         strcat(bp, "\n");
1930         strcat(bp, "        <");
1931         strcat(bp, ahc->description);
1932         strcat(bp, ">\n");
1933         strcat(bp, "        ");
1934         ahc_controller_info(ahc, ahc_info);
1935         strcat(bp, ahc_info);
1936         strcat(bp, "\n");
1937
1938         return (bp);
1939 }
1940
1941 void
1942 ahc_send_async(struct ahc_softc *ahc, char channel,
1943                u_int target, u_int lun, ac_code code, void *arg)
1944 {
1945         switch (code) {
1946         case AC_TRANSFER_NEG:
1947         {
1948                 char    buf[80];
1949                 struct  ahc_linux_target *targ;
1950                 struct  info_str info;
1951                 struct  ahc_initiator_tinfo *tinfo;
1952                 struct  ahc_tmode_tstate *tstate;
1953                 int     target_offset;
1954
1955                 info.buffer = buf;
1956                 info.length = sizeof(buf);
1957                 info.offset = 0;
1958                 info.pos = 0;
1959                 tinfo = ahc_fetch_transinfo(ahc, channel,
1960                                                 channel == 'A' ? ahc->our_id
1961                                                                : ahc->our_id_b,
1962                                                 target, &tstate);
1963
1964                 /*
1965                  * Don't bother reporting results while
1966                  * negotiations are still pending.
1967                  */
1968                 if (tinfo->curr.period != tinfo->goal.period
1969                  || tinfo->curr.width != tinfo->goal.width
1970                  || tinfo->curr.offset != tinfo->goal.offset
1971                  || tinfo->curr.ppr_options != tinfo->goal.ppr_options)
1972                         if (bootverbose == 0)
1973                                 break;
1974
1975                 /*
1976                  * Don't bother reporting results that
1977                  * are identical to those last reported.
1978                  */
1979                 target_offset = target;
1980                 if (channel == 'B')
1981                         target_offset += 8;
1982                 targ = ahc->platform_data->targets[target_offset];
1983                 if (targ != NULL
1984                  && tinfo->curr.period == targ->last_tinfo.period
1985                  && tinfo->curr.width == targ->last_tinfo.width
1986                  && tinfo->curr.offset == targ->last_tinfo.offset
1987                  && tinfo->curr.ppr_options == targ->last_tinfo.ppr_options)
1988                         if (bootverbose == 0)
1989                                 break;
1990
1991                 targ->last_tinfo.period = tinfo->curr.period;
1992                 targ->last_tinfo.width = tinfo->curr.width;
1993                 targ->last_tinfo.offset = tinfo->curr.offset;
1994                 targ->last_tinfo.ppr_options = tinfo->curr.ppr_options;
1995
1996                 printf("(%s:%c:", ahc_name(ahc), channel);
1997                 if (target == CAM_TARGET_WILDCARD)
1998                         printf("*): ");
1999                 else
2000                         printf("%d): ", target);
2001                 ahc_format_transinfo(&info, &tinfo->curr);
2002                 if (info.pos < info.length)
2003                         *info.buffer = '\0';
2004                 else
2005                         buf[info.length - 1] = '\0';
2006                 printf("%s", buf);
2007                 break;
2008         }
2009         case AC_SENT_BDR:
2010                 break;
2011         case AC_BUS_RESET:
2012 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,3,0)
2013                 if (ahc->platform_data->host != NULL) {
2014                         scsi_report_bus_reset(ahc->platform_data->host,
2015                                               channel - 'A');
2016                 }
2017 #endif
2018                 break;
2019         default:
2020                 panic("ahc_send_async: Unexpected async event");
2021         }
2022 }
2023
2024 /*
2025  * Calls the higher level scsi done function and frees the scb.
2026  */
2027 void
2028 ahc_done(struct ahc_softc *ahc, struct scb * scb)
2029 {
2030         Scsi_Cmnd *cmd;
2031         struct ahc_linux_device *dev;
2032
2033         LIST_REMOVE(scb, pending_links);
2034         if ((scb->flags & SCB_UNTAGGEDQ) != 0) {
2035                 struct scb_tailq *untagged_q;
2036                 int target_offset;
2037
2038                 target_offset = SCB_GET_TARGET_OFFSET(ahc, scb);
2039                 untagged_q = &(ahc->untagged_queues[target_offset]);
2040                 TAILQ_REMOVE(untagged_q, scb, links.tqe);
2041                 ahc_run_untagged_queue(ahc, untagged_q);
2042         }
2043
2044         if ((scb->flags & SCB_ACTIVE) == 0) {
2045                 printf("SCB %d done'd twice\n", scb->hscb->tag);
2046                 ahc_dump_card_state(ahc);
2047                 panic("Stopping for safety");
2048         }
2049         cmd = scb->io_ctx;
2050         dev = scb->platform_data->dev;
2051         dev->active--;
2052         dev->openings++;
2053         ahc_linux_unmap_scb(ahc, scb);
2054         if (scb->flags & SCB_SENSE) {
2055                 memcpy(cmd->sense_buffer, ahc_get_sense_buf(ahc, scb),
2056                        MIN(sizeof(struct scsi_sense_data),
2057                            sizeof(cmd->sense_buffer)));
2058                 cmd->result |= (DRIVER_SENSE << 24);
2059         } else {
2060                 /*
2061                  * Guard against stale sense data.
2062                  * The Linux mid-layer assumes that sense
2063                  * was retrieved anytime the first byte of
2064                  * the sense buffer looks "sane".
2065                  */
2066                 cmd->sense_buffer[0] = 0;
2067         }
2068         if (ahc_get_transaction_status(scb) == CAM_REQ_INPROG) {
2069                 uint32_t amount_xferred;
2070
2071                 amount_xferred =
2072                     ahc_get_transfer_length(scb) - ahc_get_residual(scb);
2073                 if (amount_xferred < scb->io_ctx->underflow) {
2074                         printf("Saw underflow (%ld of %ld bytes). "
2075                                "Treated as error\n",
2076                                 ahc_get_residual(scb),
2077                                 ahc_get_transfer_length(scb));
2078                         ahc_set_transaction_status(scb, CAM_DATA_RUN_ERR);
2079                 } else {
2080                         ahc_set_transaction_status(scb, CAM_REQ_CMP);
2081                         ahc_linux_sniff_command(ahc, cmd, scb);
2082                 }
2083         } else if (ahc_get_transaction_status(scb) == DID_OK) {
2084                 ahc_linux_handle_scsi_status(ahc, dev, scb);
2085         } else if (ahc_get_transaction_status(scb) == DID_NO_CONNECT) {
2086                 /*
2087                  * Should a selection timeout kill the device?
2088                  * That depends on whether the selection timeout
2089                  * is persistent.  Since we have no guarantee that
2090                  * the mid-layer will issue an inquiry for this device
2091                  * again, we can't just kill it off.
2092                 dev->flags |= AHC_DEV_UNCONFIGURED;
2093                  */
2094         }
2095
2096         if (dev->openings == 1
2097          && ahc_get_transaction_status(scb) == CAM_REQ_CMP
2098          && ahc_get_scsi_status(scb) != SCSI_STATUS_QUEUE_FULL)
2099                 dev->tag_success_count++;
2100         /*
2101          * Some devices deal with temporary internal resource
2102          * shortages by returning queue full.  When the queue
2103          * full occurrs, we throttle back.  Slowly try to get
2104          * back to our previous queue depth.
2105          */
2106         if ((dev->openings + dev->active) < dev->maxtags
2107          && dev->tag_success_count > AHC_TAG_SUCCESS_INTERVAL) {
2108                 dev->tag_success_count = 0;
2109                 dev->openings++;
2110         }
2111
2112         if (dev->active == 0)
2113                 dev->commands_since_idle_or_otag = 0;
2114
2115         if (TAILQ_EMPTY(&dev->busyq)) {
2116                 if ((dev->flags & AHC_DEV_UNCONFIGURED) != 0
2117                  && dev->active == 0)
2118                         ahc_linux_free_device(ahc, dev);
2119         } else if ((dev->flags & AHC_DEV_ON_RUN_LIST) == 0) {
2120                 TAILQ_INSERT_TAIL(&ahc->platform_data->device_runq, dev, links);
2121                 dev->flags |= AHC_DEV_ON_RUN_LIST;
2122         }
2123
2124         if ((scb->flags & SCB_RECOVERY_SCB) != 0) {
2125                 printf("Recovery SCB completes\n");
2126                 up(&ahc->platform_data->eh_sem);
2127         }
2128
2129         ahc_free_scb(ahc, scb);
2130         ahc_linux_queue_cmd_complete(ahc, cmd);
2131 }
2132
2133 static void
2134 ahc_linux_handle_scsi_status(struct ahc_softc *ahc,
2135                              struct ahc_linux_device *dev, struct scb *scb)
2136 {
2137         /*
2138          * We don't currently trust the mid-layer to
2139          * properly deal with queue full or busy.  So,
2140          * when one occurs, we tell the mid-layer to
2141          * unconditionally requeue the command to us
2142          * so that we can retry it ourselves.  We also
2143          * implement our own throttling mechanism so
2144          * we don't clobber the device with too many
2145          * commands.
2146          */
2147         switch (ahc_get_scsi_status(scb)) {
2148         default:
2149                 break;
2150         case SCSI_STATUS_QUEUE_FULL:
2151         {
2152                 /*
2153                  * By the time the core driver has returned this
2154                  * command, all other commands that were queued
2155                  * to us but not the device have been returned.
2156                  * This ensures that dev->active is equal to
2157                  * the number of commands actually queued to
2158                  * the device.
2159                  */
2160                 dev->tag_success_count = 0;
2161                 if (dev->active != 0) {
2162                         /*
2163                          * Drop our opening count to the number
2164                          * of commands currently outstanding.
2165                          */
2166                         dev->openings = 0;
2167 /*
2168                         ahc_print_path(ahc, scb);
2169                         printf("Dropping tag count to %d\n", dev->active);
2170  */
2171                         if (dev->active == dev->tags_on_last_queuefull) {
2172
2173                                 dev->last_queuefull_same_count++;
2174                                 /*
2175                                  * If we repeatedly see a queue full
2176                                  * at the same queue depth, this
2177                                  * device has a fixed number of tag
2178                                  * slots.  Lock in this tag depth
2179                                  * so we stop seeing queue fulls from
2180                                  * this device.
2181                                  */
2182                                 if (dev->last_queuefull_same_count
2183                                  == AHC_LOCK_TAGS_COUNT) {
2184                                         dev->maxtags = dev->active;
2185                                         ahc_print_path(ahc, scb);
2186                                         printf("Locking max tag count at %d\n",
2187                                                dev->active);
2188                                 }
2189                         } else {
2190                                 dev->tags_on_last_queuefull = dev->active;
2191                                 dev->last_queuefull_same_count = 0;
2192                         }
2193                         ahc_set_transaction_status(scb, CAM_REQUEUE_REQ);
2194                         ahc_set_scsi_status(scb, SCSI_STATUS_OK);
2195                         break;
2196                 }
2197                 /*
2198                  * Drop down to a single opening, and treat this
2199                  * as if the target return BUSY SCSI status.
2200                  */
2201                 dev->openings = 1;
2202                 /* FALLTHROUGH */
2203         }
2204         case SCSI_STATUS_BUSY:
2205                 /*
2206                  * XXX Set a timer and handle ourselves????
2207                  * For now we pray that the mid-layer does something
2208                  * sane for devices that are busy.
2209                  */
2210                 ahc_set_scsi_status(scb, SCSI_STATUS_BUSY);
2211                 break;
2212         }
2213 }
2214
2215 static void
2216 ahc_linux_filter_command(struct ahc_softc *ahc, Scsi_Cmnd *cmd, struct scb *scb)
2217 {
2218         switch (cmd->cmnd[0]) {
2219         case INQUIRY:
2220         {
2221                 struct  ahc_devinfo devinfo;
2222                 struct  scsi_inquiry *inq;
2223                 struct  scsi_inquiry_data *sid;
2224                 struct  ahc_initiator_tinfo *targ_info;
2225                 struct  ahc_tmode_tstate *tstate;
2226                 struct  ahc_syncrate *syncrate;
2227                 struct  ahc_linux_device *dev;
2228                 u_int   scsiid;
2229                 u_int   maxsync;
2230                 int     transferred_len;
2231                 int     minlen;
2232                 u_int   width;
2233                 u_int   period;
2234                 u_int   offset;
2235                 u_int   ppr_options;
2236
2237                  /*
2238                   * Validate the command.  We only want to filter
2239                   * standard inquiry commands, not those querying
2240                   * Vital Product Data.
2241                   */
2242                 inq = (struct scsi_inquiry *)cmd->cmnd;
2243                 if ((inq->byte2 & SI_EVPD) != 0
2244                  || inq->page_code != 0)
2245                         break;
2246
2247                 if (cmd->use_sg != 0) {
2248                         printf("%s: SG Inquiry response ignored\n",
2249                                ahc_name(ahc));
2250                         break;
2251                 }
2252                 transferred_len = ahc_get_transfer_length(scb)
2253                                 - ahc_get_residual(scb);
2254                 sid = (struct scsi_inquiry_data *)cmd->request_buffer;
2255
2256                 /*
2257                  * Determine if this lun actually exists.  If so,
2258                  * hold on to its corresponding device structure.
2259                  * If not, make sure we release the device and
2260                  * don't bother processing the rest of this inquiry
2261                  * command.
2262                  */
2263                 dev = ahc_linux_get_device(ahc, cmd->channel,
2264                                            cmd->target, cmd->lun,
2265                                            /*alloc*/FALSE);
2266                 if (transferred_len >= 1
2267                  && SID_QUAL(sid) == SID_QUAL_LU_CONNECTED) {
2268
2269                         dev->flags &= ~AHC_DEV_UNCONFIGURED;
2270                 } else {
2271                         dev->flags |= AHC_DEV_UNCONFIGURED;
2272                         break;
2273                 }
2274
2275                 /*
2276                  * Update our notion of this device's transfer
2277                  * negotiation capabilities.
2278                  */
2279                 scsiid = BUILD_SCSIID(ahc, cmd);
2280                 ahc_compile_devinfo(&devinfo, SCSIID_OUR_ID(scsiid),
2281                                     cmd->target, cmd->lun,
2282                                     SCSIID_CHANNEL(ahc, scsiid),
2283                                     ROLE_INITIATOR);
2284                 targ_info = ahc_fetch_transinfo(ahc, devinfo.channel,
2285                                                 devinfo.our_scsiid,
2286                                                 devinfo.target, &tstate);
2287                 width = targ_info->user.width;
2288                 period = targ_info->user.period;
2289                 offset = targ_info->user.offset;
2290                 ppr_options = targ_info->user.ppr_options;
2291                 minlen = offsetof(struct scsi_inquiry_data, version) + 1;
2292                 if (transferred_len >= minlen) {
2293                         targ_info->curr.protocol_version = SID_ANSI_REV(sid);
2294
2295                         /*
2296                          * Only attempt SPI3 once we've verified that
2297                          * the device claims to support SPI3 features.
2298                          */
2299                         if (targ_info->curr.protocol_version < SCSI_REV_2)
2300                                 targ_info->curr.transport_version =
2301                                     SID_ANSI_REV(sid);
2302                         else
2303                                 targ_info->curr.transport_version =
2304                                      SCSI_REV_2;
2305                 }
2306
2307                 minlen = offsetof(struct scsi_inquiry_data, flags) + 1;
2308                 if (transferred_len >= minlen
2309                  && (sid->additional_length + 4) >= minlen) {
2310                         if ((sid->flags & SID_WBus16) == 0)
2311                                 width = MSG_EXT_WDTR_BUS_8_BIT;
2312                         if ((sid->flags & SID_Sync) == 0) {
2313                                 period = 0;
2314                                 offset = 0;
2315                                 ppr_options = 0;
2316                         }
2317                 } else {
2318                         /* Keep current settings */
2319                         break;
2320                 }
2321                 minlen = offsetof(struct scsi_inquiry_data, spi3data) + 1;
2322                 /*
2323                  * This is a kludge to deal with inquiry requests that
2324                  * are not large enough for us to pull the spi3 bits.
2325                  * In this case, we assume that a device that tells us
2326                  * they can provide inquiry data that spans the SPI3
2327                  * bits can handle a PPR request.  If the inquiry
2328                  * request has sufficient buffer space to cover these
2329                  * bits, we check them to see if any ppr options are
2330                  * available.
2331                  */
2332                 if ((sid->additional_length + 4) >= minlen) {
2333                         if (transferred_len >= minlen
2334                          && (sid->spi3data & SID_SPI_CLOCK_DT) == 0)
2335                                 ppr_options = 0;
2336
2337                         if (targ_info->curr.protocol_version > SCSI_REV_2)
2338                                 targ_info->curr.transport_version = 3;
2339                 } else {
2340                         ppr_options = 0;
2341                 }
2342                 ahc_validate_width(ahc, /*tinfo limit*/NULL, &width,
2343                                    ROLE_UNKNOWN);
2344                 if ((ahc->features & AHC_ULTRA2) != 0)
2345                         maxsync = AHC_SYNCRATE_DT;
2346                 else if ((ahc->features & AHC_ULTRA) != 0)
2347                         maxsync = AHC_SYNCRATE_ULTRA;
2348                 else
2349                         maxsync = AHC_SYNCRATE_FAST;
2350
2351                 syncrate = ahc_find_syncrate(ahc, &period,
2352                                              &ppr_options, maxsync);
2353                 ahc_validate_offset(ahc, /*tinfo limit*/NULL, syncrate,
2354                                     &offset, width, ROLE_UNKNOWN);
2355                 if (offset == 0 || period == 0) {
2356                         period = 0;
2357                         offset = 0;
2358                         ppr_options = 0;
2359                 }
2360                 /* Apply our filtered user settings. */
2361                 ahc_set_width(ahc, &devinfo, width,
2362                               AHC_TRANS_GOAL, /*paused*/FALSE);
2363                 ahc_set_syncrate(ahc, &devinfo, syncrate, period,
2364                                  offset, ppr_options, AHC_TRANS_GOAL,
2365                                  /*paused*/FALSE);
2366                 break;
2367         }
2368         default:
2369                 panic("ahc_linux_filter_command: Unexpected Command type  %x\n",
2370                       cmd->cmnd[0]);
2371                 break;
2372         }
2373 }
2374
2375 static void
2376 ahc_linux_sem_timeout(u_long arg)
2377 {
2378         struct semaphore *sem;
2379
2380         sem = (struct semaphore *)arg;
2381         up(sem);
2382 }
2383
2384 static void
2385 ahc_linux_freeze_sim_queue(struct ahc_softc *ahc)
2386 {
2387         ahc->platform_data->qfrozen++;
2388         if (ahc->platform_data->qfrozen == 1)
2389                 scsi_block_requests(ahc->platform_data->host);
2390 }
2391
2392 static void
2393 ahc_linux_release_sim_queue(u_long arg)
2394 {
2395         struct ahc_softc *ahc;
2396         u_long s;
2397         int    unblock_reqs;
2398
2399         ahc = (struct ahc_softc *)arg;
2400         unblock_reqs = 0;
2401         ahc_lock(ahc, &s);
2402         if (ahc->platform_data->qfrozen > 0)
2403                 ahc->platform_data->qfrozen--;
2404         if (ahc->platform_data->qfrozen == 0) {
2405                 unblock_reqs = 1;
2406                 ahc_linux_run_device_queues(ahc);
2407         }
2408         ahc_unlock(ahc, &s);
2409         /*
2410          * There is still a race here.  The mid-layer
2411          * should keep its own freeze count and use
2412          * a bottom half handler to run the queues
2413          * so we can unblock with our own lock held.
2414          */
2415         if (unblock_reqs)
2416                 scsi_unblock_requests(ahc->platform_data->host);
2417 }
2418
2419 static int
2420 ahc_linux_queue_recovery_cmd(Scsi_Cmnd *cmd, scb_flag flag)
2421 {
2422         struct ahc_softc *ahc;
2423         struct ahc_cmd *acmd;
2424         struct ahc_cmd *list_acmd;
2425         struct ahc_linux_device *dev;
2426         struct scb *pending_scb;
2427         u_long s;
2428         u_int  saved_scbptr;
2429         u_int  active_scb_index;
2430         u_int  last_phase;
2431         int    retval;
2432         int    paused;
2433         int    wait;
2434         int    disconnected;
2435
2436         paused = FALSE;
2437         wait = FALSE;
2438         ahc = *(struct ahc_softc **)cmd->host->hostdata;
2439         acmd = (struct ahc_cmd *)cmd;
2440
2441         printf("%s:%d:%d:%d: Attempting to queue a%s message\n",
2442                ahc_name(ahc), cmd->channel, cmd->target, cmd->lun,
2443                flag == SCB_ABORT ? "n ABORT" : " TARGET RESET");
2444
2445         /*
2446          * It is a bug that the upper layer takes
2447          * this lock just prior to calling us.
2448          */
2449         spin_unlock_irq(&io_request_lock);
2450
2451         ahc_lock(ahc, &s);
2452
2453         /*
2454          * First determine if we currently own this command.
2455          * Start by searching the device queue.  If not found
2456          * there, check the pending_scb list.  If not found
2457          * at all, and the system wanted us to just abort the
2458          * command return success.
2459          */
2460         dev = ahc_linux_get_device(ahc, cmd->channel, cmd->target,
2461                                    cmd->lun, /*alloc*/FALSE);
2462
2463         if (dev == NULL) {
2464                 /*
2465                  * No target device for this command exists,
2466                  * so we must not still own the command.
2467                  */
2468                 printf("%s:%d:%d:%d: Is not an active device\n",
2469                        ahc_name(ahc), cmd->channel, cmd->target, cmd->lun);
2470                 retval = SUCCESS;
2471                 goto no_cmd;
2472         }
2473
2474         TAILQ_FOREACH(list_acmd, &dev->busyq, acmd_links.tqe) {
2475                 if (list_acmd == acmd)
2476                         break;
2477         }
2478
2479         if (list_acmd != NULL) {
2480                 printf("%s:%d:%d:%d: Command found on device queue\n",
2481                        ahc_name(ahc), cmd->channel, cmd->target, cmd->lun);
2482                 if (flag == SCB_ABORT) {
2483                         TAILQ_REMOVE(&dev->busyq, list_acmd, acmd_links.tqe);
2484                         cmd->result = DID_ABORT << 16;
2485                         ahc_linux_queue_cmd_complete(ahc, cmd);
2486                         retval = SUCCESS;
2487                         goto done;
2488                 }
2489         }
2490
2491         /*
2492          * See if we can find a matching cmd in the pending list.
2493          */
2494         LIST_FOREACH(pending_scb, &ahc->pending_scbs, pending_links) {
2495                 if (pending_scb->io_ctx == cmd)
2496                         break;
2497         }
2498
2499         if (pending_scb == NULL && flag == SCB_DEVICE_RESET) {
2500
2501                 /* Any SCB for this device will do for a target reset */
2502                 LIST_FOREACH(pending_scb, &ahc->pending_scbs, pending_links) {
2503                         if (ahc_match_scb(ahc, pending_scb, cmd->target,
2504                                           cmd->channel, CAM_LUN_WILDCARD,
2505                                           SCB_LIST_NULL, ROLE_INITIATOR) == 0)
2506                                 break;
2507                 }
2508         }
2509
2510         if (pending_scb == NULL) {
2511                 printf("%s:%d:%d:%d: Command not found\n",
2512                        ahc_name(ahc), cmd->channel, cmd->target, cmd->lun);
2513                 goto no_cmd;
2514         }
2515
2516         if ((pending_scb->flags & SCB_RECOVERY_SCB) != 0) {
2517                 /*
2518                  * We can't queue two recovery actions using the same SCB
2519                  */
2520                 retval = FAILED;
2521                 goto  done;
2522         }
2523
2524         /*
2525          * Ensure that the card doesn't do anything
2526          * behind our back.  Also make sure that we
2527          * didn't "just" miss an interrupt that would
2528          * affect this cmd.
2529          */
2530         ahc->flags |= AHC_ALL_INTERRUPTS;
2531         do {
2532                 ahc_intr(ahc);
2533                 ahc_pause(ahc);
2534                 ahc_clear_critical_section(ahc);
2535         } while (ahc_inb(ahc, INTSTAT) & INT_PEND);
2536         ahc->flags &= ~AHC_ALL_INTERRUPTS;
2537         paused = TRUE;
2538
2539         if (bootverbose)
2540                 ahc_dump_card_state(ahc);
2541
2542         if ((pending_scb->flags & SCB_ACTIVE) == 0) {
2543                 printf("%s:%d:%d:%d: Command already completed\n",
2544                        ahc_name(ahc), cmd->channel, cmd->target, cmd->lun);
2545                 goto no_cmd;
2546         }
2547
2548         disconnected = TRUE;
2549         if (flag == SCB_ABORT) {
2550                 if (ahc_search_qinfifo(ahc, cmd->target, cmd->channel + 'A',
2551                                        cmd->lun, pending_scb->hscb->tag,
2552                                        ROLE_INITIATOR, CAM_REQ_ABORTED,
2553                                        SEARCH_COMPLETE) > 0) {
2554                         printf("%s:%d:%d:%d: Cmd aborted from QINFIFO\n",
2555                                ahc_name(ahc), cmd->channel, cmd->target,
2556                                         cmd->lun);
2557                         retval = SUCCESS;
2558                         goto done;
2559                 }
2560         } else if (ahc_search_qinfifo(ahc, cmd->target, cmd->channel + 'A',
2561                                       cmd->lun, pending_scb->hscb->tag,
2562                                       ROLE_INITIATOR, /*status*/0,
2563                                       SEARCH_COUNT) > 0) {
2564                 disconnected = FALSE;
2565         }
2566
2567         /*
2568          * At this point, pending_scb is the scb associated with the
2569          * passed in command.  That command is currently active on the
2570          * bus, is in the disconnected state, or we're hoping to find
2571          * a command for the same target active on the bus to abuse to
2572          * send a BDR.  Queue the appropriate message based on which of
2573          * these states we are in.
2574          */
2575         last_phase = ahc_inb(ahc, LASTPHASE);
2576         saved_scbptr = ahc_inb(ahc, SCBPTR);
2577         active_scb_index = ahc_inb(ahc, SCB_TAG);
2578         if (last_phase != P_BUSFREE
2579          && (pending_scb->hscb->tag == active_scb_index
2580           || (flag == SCB_DEVICE_RESET
2581            && SCSIID_TARGET(ahc, ahc_inb(ahc, SAVED_SCSIID)) == cmd->target))) {
2582
2583                 /*
2584                  * We're active on the bus, so assert ATN
2585                  * and hope that the target responds.
2586                  */
2587                 pending_scb = ahc_lookup_scb(ahc, active_scb_index);
2588                 pending_scb->flags |= SCB_RECOVERY_SCB|flag;
2589                 ahc_outb(ahc, MSG_OUT, HOST_MSG);
2590                 ahc_outb(ahc, SCSISIGO, last_phase|ATNO);
2591                 printf("%s:%d:%d:%d: Device is active, asserting ATN\n",
2592                        ahc_name(ahc), cmd->channel, cmd->target, cmd->lun);
2593                 wait = TRUE;
2594         } else if (disconnected) {
2595
2596                 /*
2597                  * Actually re-queue this SCB in an attempt
2598                  * to select the device before it reconnects.
2599                  * In either case (selection or reselection),
2600                  * we will now issue a the approprate message
2601                  * to the timed-out device.
2602                  *
2603                  * Set the MK_MESSAGE control bit indicating
2604                  * that we desire to send a message.  We
2605                  * also set the disconnected flag since
2606                  * in the paging case there is no guarantee
2607                  * that our SCB control byte matches the
2608                  * version on the card.  We don't want the
2609                  * sequencer to abort the command thinking
2610                  * an unsolicited reselection occurred.
2611                  */
2612                 pending_scb->hscb->control |= MK_MESSAGE|DISCONNECTED;
2613                 pending_scb->flags |= SCB_RECOVERY_SCB|flag;
2614
2615                 /*
2616                  * Remove any cached copy of this SCB in the
2617                  * disconnected list in preparation for the
2618                  * queuing of our abort SCB.  We use the
2619                  * same element in the SCB, SCB_NEXT, for
2620                  * both the qinfifo and the disconnected list.
2621                  */
2622                 ahc_search_disc_list(ahc, cmd->target, cmd->channel + 'A',
2623                                      cmd->lun, pending_scb->hscb->tag,
2624                                      /*stop_on_first*/TRUE,
2625                                      /*remove*/TRUE,
2626                                      /*save_state*/FALSE);
2627
2628                 /*
2629                  * In the non-paging case, the sequencer will
2630                  * never re-reference the in-core SCB.
2631                  * To make sure we are notified during
2632                  * reslection, set the MK_MESSAGE flag in
2633                  * the card's copy of the SCB.
2634                  */
2635                 if ((ahc->flags & AHC_PAGESCBS) == 0) {
2636                         ahc_outb(ahc, SCBPTR, pending_scb->hscb->tag);
2637                         ahc_outb(ahc, SCB_CONTROL,
2638                                  ahc_inb(ahc, SCB_CONTROL)|MK_MESSAGE);
2639                 }
2640
2641                 /*
2642                  * Clear out any entries in the QINFIFO first
2643                  * so we are the next SCB for this target
2644                  * to run.
2645                  */
2646                 ahc_search_qinfifo(ahc, cmd->target, cmd->channel + 'A',
2647                                    cmd->lun, SCB_LIST_NULL, ROLE_INITIATOR,
2648                                    CAM_REQUEUE_REQ, SEARCH_COMPLETE);
2649                 ahc_print_path(ahc, pending_scb);
2650                 printf("Queuing a recovery SCB\n");
2651                 ahc_qinfifo_requeue_tail(ahc, pending_scb);
2652                 ahc_outb(ahc, SCBPTR, saved_scbptr);
2653                 printf("%s:%d:%d:%d: Device is disconnected, re-queuing SCB\n",
2654                        ahc_name(ahc), cmd->channel, cmd->target, cmd->lun);
2655                 wait = TRUE;
2656         } else {
2657                 printf("%s:%d:%d:%d: Unable to deliver message\n",
2658                        ahc_name(ahc), cmd->channel, cmd->target, cmd->lun);
2659                 retval = FAILED;
2660                 goto done;
2661         }
2662
2663 no_cmd:
2664         /*
2665          * Our assumption is that if we don't have the command, no
2666          * recovery action was required, so we return success.  Again,
2667          * the semantics of the mid-layer recovery engine are not
2668          * well defined, so this may change in time.
2669          */
2670         retval = SUCCESS;
2671 done:
2672         if (paused)
2673                 ahc_unpause(ahc);
2674         if (wait) {
2675                 struct timer_list timer;
2676                 int ret;
2677
2678                 ahc_unlock(ahc, &s);
2679                 init_timer(&timer);
2680                 timer.data = (u_long)&ahc->platform_data->eh_sem;
2681                 timer.expires = jiffies + (5 * HZ);
2682                 timer.function = ahc_linux_sem_timeout;
2683                 add_timer(&timer);
2684                 printf("Recovery code sleeping\n");
2685                 down(&ahc->platform_data->eh_sem);
2686                 printf("Recovery code awake\n");
2687                 ret = del_timer(&timer);
2688                 if (ret == 0) {
2689                         printf("Timer Expired\n");
2690                         retval = FAILED;
2691                 }
2692                 ahc_lock(ahc, &s);
2693         }
2694         ahc_linux_run_device_queues(ahc);
2695         acmd = TAILQ_FIRST(&ahc->platform_data->completeq);
2696         TAILQ_INIT(&ahc->platform_data->completeq);
2697         ahc_unlock(ahc, &s);
2698         if (acmd != NULL)
2699                 ahc_linux_run_complete_queue(ahc, acmd);
2700         spin_lock_irq(&io_request_lock);
2701         return (retval);
2702 }
2703
2704 /*
2705  * Abort the current SCSI command(s).
2706  */
2707 int
2708 ahc_linux_abort(Scsi_Cmnd *cmd)
2709 {
2710         int error;
2711
2712         error = ahc_linux_queue_recovery_cmd(cmd, SCB_ABORT);
2713         if (error != 0)
2714                 printf("aic7xxx_abort returns %d\n", error);
2715         return (error);
2716 }
2717
2718 /*
2719  * Attempt to send a target reset message to the device that timed out.
2720  */
2721 int
2722 ahc_linux_dev_reset(Scsi_Cmnd *cmd)
2723 {
2724         int error;
2725
2726         error = ahc_linux_queue_recovery_cmd(cmd, SCB_DEVICE_RESET);
2727         if (error != 0)
2728                 printf("aic7xxx_dev_reset returns %d\n", error);
2729         return (error);
2730 }
2731
2732 /*
2733  * Reset the SCSI bus.
2734  */
2735 int
2736 ahc_linux_bus_reset(Scsi_Cmnd *cmd)
2737 {
2738         struct ahc_softc *ahc;
2739         struct ahc_cmd *acmd;
2740         u_long s;
2741         int    found;
2742
2743         /*
2744          * It is a bug that the upper layer takes
2745          * this lock just prior to calling us.
2746          */
2747         spin_unlock_irq(&io_request_lock);
2748
2749         ahc = *(struct ahc_softc **)cmd->host->hostdata;
2750         ahc_lock(ahc, &s);
2751         found = ahc_reset_channel(ahc, cmd->channel + 'A',
2752                                   /*initiate reset*/TRUE);
2753         acmd = TAILQ_FIRST(&ahc->platform_data->completeq);
2754         TAILQ_INIT(&ahc->platform_data->completeq);
2755         ahc_unlock(ahc, &s);
2756         if (bootverbose)
2757                 printf("%s: SCSI bus reset delivered. "
2758                        "%d SCBs aborted.\n", ahc_name(ahc), found);
2759
2760         if (acmd != NULL)
2761                 ahc_linux_run_complete_queue(ahc, acmd);
2762
2763         spin_lock_irq(&io_request_lock);
2764         return SUCCESS;
2765 }
2766
2767 /*
2768  * Return the disk geometry for the given SCSI device.
2769  */
2770 int
2771 ahc_linux_biosparam(Disk *disk, kdev_t dev, int geom[])
2772 {
2773         int     heads;
2774         int     sectors;
2775         int     cylinders;
2776         int     ret;
2777         int     extended;
2778         struct  ahc_softc *ahc;
2779         struct  buffer_head *bh;
2780
2781         ahc = *((struct ahc_softc **)disk->device->host->hostdata);
2782         bh = bread(MKDEV(MAJOR(dev), MINOR(dev) & ~0xf), 0, 1024);
2783
2784         if (bh) {
2785                 ret = scsi_partsize(bh, disk->capacity,
2786                                     &geom[2], &geom[0], &geom[1]);
2787                 brelse(bh);
2788                 if (ret != -1)
2789                         return (ret);
2790         }
2791         heads = 64;
2792         sectors = 32;
2793         cylinders = disk->capacity / (heads * sectors);
2794
2795         if (disk->device->channel == 0)
2796                 extended = (ahc->flags & AHC_EXTENDED_TRANS_A) != 0;
2797         else
2798                 extended = (ahc->flags & AHC_EXTENDED_TRANS_B) != 0;
2799         if (extended && cylinders >= 1024) {
2800                 heads = 255;
2801                 sectors = 63;
2802                 cylinders = disk->capacity / (heads * sectors);
2803         }
2804         geom[0] = heads;
2805         geom[1] = sectors;
2806         geom[2] = cylinders;
2807         return (0);
2808 }
2809
2810 /*
2811  * Free the passed in Scsi_Host memory structures prior to unloading the
2812  * module.
2813  */
2814 int
2815 ahc_linux_release(struct Scsi_Host * host)
2816 {
2817         struct ahc_softc *ahc;
2818
2819         if (host != NULL) {
2820
2821                 ahc = *(struct ahc_softc **)host->hostdata;
2822                 ahc_free(ahc);
2823         }
2824         if (TAILQ_EMPTY(&ahc_tailq)) {
2825                 unregister_reboot_notifier(&ahc_linux_notifier);
2826 #ifdef CONFIG_PCI
2827 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0)
2828                 pci_unregister_driver(&aic7xxx_pci_driver);
2829 #endif
2830 #endif
2831         }
2832         return (0);
2833 }
2834
2835 void
2836 ahc_platform_dump_card_state(struct ahc_softc *ahc)
2837 {
2838         struct ahc_linux_device *dev;
2839         int channel;
2840         int maxchannel;
2841         int target;
2842         int maxtarget;
2843         int lun;
2844         int i;
2845
2846         maxchannel = (ahc->features & AHC_TWIN) ? 1 : 0;
2847         maxtarget = (ahc->features & AHC_WIDE) ? 15 : 7;
2848         for (channel = 0; channel <= maxchannel; channel++) {
2849                 for (target = 0; target <=maxtarget; target++) {
2850                         for (lun = 0; lun < AHC_NUM_LUNS; lun++) {
2851                                 struct ahc_cmd *acmd;
2852
2853                                 dev = ahc_linux_get_device(ahc, channel, target,
2854                                                            lun, /*alloc*/FALSE);
2855                                 if (dev == NULL)
2856                                         continue;
2857
2858                                 printf("DevQ(%d:%d:%d): ",
2859                                        channel, target, lun);
2860                                 i = 0;
2861                                 TAILQ_FOREACH(acmd, &dev->busyq,
2862                                               acmd_links.tqe) {
2863                                         if (i++ > 256)
2864                                                 break;
2865                                 }
2866                                 printf("%d waiting\n", i);
2867                         }
2868                 }
2869         }
2870 }
2871
2872 MODULE_LICENSE("Dual BSD/GPL");
2873
2874 #if defined(MODULE) || LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0)
2875 static Scsi_Host_Template driver_template = AIC7XXX;
2876 Scsi_Host_Template *aic7xxx_driver_template = &driver_template;
2877 #include "../scsi_module.c"
2878 #endif