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