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