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