2eb11443887146f6070c7be84835b11d199fbbb8
[linux-2.6.git] / drivers / scsi / aic7xxx / aic79xx_osm.c
1 /*
2  * Adaptec AIC79xx device driver for Linux.
3  *
4  * $Id: //depot/aic7xxx/linux/drivers/scsi/aic7xxx/aic79xx_osm.c#171 $
5  *
6  * --------------------------------------------------------------------------
7  * Copyright (c) 1994-2000 Justin T. Gibbs.
8  * Copyright (c) 1997-1999 Doug Ledford
9  * Copyright (c) 2000-2003 Adaptec Inc.
10  * All rights reserved.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions, and the following disclaimer,
17  *    without modification.
18  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
19  *    substantially similar to the "NO WARRANTY" disclaimer below
20  *    ("Disclaimer") and any redistribution must be conditioned upon
21  *    including a substantially similar Disclaimer requirement for further
22  *    binary redistribution.
23  * 3. Neither the names of the above-listed copyright holders nor the names
24  *    of any contributors may be used to endorse or promote products derived
25  *    from this software without specific prior written permission.
26  *
27  * Alternatively, this software may be distributed under the terms of the
28  * GNU General Public License ("GPL") version 2 as published by the Free
29  * Software Foundation.
30  *
31  * NO WARRANTY
32  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
33  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
34  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
35  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
36  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
37  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
38  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
39  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
40  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
41  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
42  * POSSIBILITY OF SUCH DAMAGES.
43  */
44
45 #include "aic79xx_osm.h"
46 #include "aic79xx_inline.h"
47 #include <scsi/scsicam.h>
48
49 static struct scsi_transport_template *ahd_linux_transport_template = NULL;
50
51 #include <linux/init.h>         /* __setup */
52 #include <linux/mm.h>           /* For fetching system memory size */
53 #include <linux/blkdev.h>               /* For block_size() */
54 #include <linux/delay.h>        /* For ssleep/msleep */
55 #include <linux/device.h>
56
57 /*
58  * Bucket size for counting good commands in between bad ones.
59  */
60 #define AHD_LINUX_ERR_THRESH    1000
61
62 /*
63  * Set this to the delay in seconds after SCSI bus reset.
64  * Note, we honor this only for the initial bus reset.
65  * The scsi error recovery code performs its own bus settle
66  * delay handling for error recovery actions.
67  */
68 #ifdef CONFIG_AIC79XX_RESET_DELAY_MS
69 #define AIC79XX_RESET_DELAY CONFIG_AIC79XX_RESET_DELAY_MS
70 #else
71 #define AIC79XX_RESET_DELAY 5000
72 #endif
73
74 /*
75  * To change the default number of tagged transactions allowed per-device,
76  * add a line to the lilo.conf file like:
77  * append="aic79xx=verbose,tag_info:{{32,32,32,32},{32,32,32,32}}"
78  * which will result in the first four devices on the first two
79  * controllers being set to a tagged queue depth of 32.
80  *
81  * The tag_commands is an array of 16 to allow for wide and twin adapters.
82  * Twin adapters will use indexes 0-7 for channel 0, and indexes 8-15
83  * for channel 1.
84  */
85 typedef struct {
86         uint16_t tag_commands[16];      /* Allow for wide/twin adapters. */
87 } adapter_tag_info_t;
88
89 /*
90  * Modify this as you see fit for your system.
91  *
92  * 0                    tagged queuing disabled
93  * 1 <= n <= 253        n == max tags ever dispatched.
94  *
95  * The driver will throttle the number of commands dispatched to a
96  * device if it returns queue full.  For devices with a fixed maximum
97  * queue depth, the driver will eventually determine this depth and
98  * lock it in (a console message is printed to indicate that a lock
99  * has occurred).  On some devices, queue full is returned for a temporary
100  * resource shortage.  These devices will return queue full at varying
101  * depths.  The driver will throttle back when the queue fulls occur and
102  * attempt to slowly increase the depth over time as the device recovers
103  * from the resource shortage.
104  *
105  * In this example, the first line will disable tagged queueing for all
106  * the devices on the first probed aic79xx adapter.
107  *
108  * The second line enables tagged queueing with 4 commands/LUN for IDs
109  * (0, 2-11, 13-15), disables tagged queueing for ID 12, and tells the
110  * driver to attempt to use up to 64 tags for ID 1.
111  *
112  * The third line is the same as the first line.
113  *
114  * The fourth line disables tagged queueing for devices 0 and 3.  It
115  * enables tagged queueing for the other IDs, with 16 commands/LUN
116  * for IDs 1 and 4, 127 commands/LUN for ID 8, and 4 commands/LUN for
117  * IDs 2, 5-7, and 9-15.
118  */
119
120 /*
121  * NOTE: The below structure is for reference only, the actual structure
122  *       to modify in order to change things is just below this comment block.
123 adapter_tag_info_t aic79xx_tag_info[] =
124 {
125         {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
126         {{4, 64, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 4, 4}},
127         {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
128         {{0, 16, 4, 0, 16, 4, 4, 4, 127, 4, 4, 4, 4, 4, 4, 4}}
129 };
130 */
131
132 #ifdef CONFIG_AIC79XX_CMDS_PER_DEVICE
133 #define AIC79XX_CMDS_PER_DEVICE CONFIG_AIC79XX_CMDS_PER_DEVICE
134 #else
135 #define AIC79XX_CMDS_PER_DEVICE AHD_MAX_QUEUE
136 #endif
137
138 #define AIC79XX_CONFIGED_TAG_COMMANDS {                                 \
139         AIC79XX_CMDS_PER_DEVICE, AIC79XX_CMDS_PER_DEVICE,               \
140         AIC79XX_CMDS_PER_DEVICE, AIC79XX_CMDS_PER_DEVICE,               \
141         AIC79XX_CMDS_PER_DEVICE, AIC79XX_CMDS_PER_DEVICE,               \
142         AIC79XX_CMDS_PER_DEVICE, AIC79XX_CMDS_PER_DEVICE,               \
143         AIC79XX_CMDS_PER_DEVICE, AIC79XX_CMDS_PER_DEVICE,               \
144         AIC79XX_CMDS_PER_DEVICE, AIC79XX_CMDS_PER_DEVICE,               \
145         AIC79XX_CMDS_PER_DEVICE, AIC79XX_CMDS_PER_DEVICE,               \
146         AIC79XX_CMDS_PER_DEVICE, AIC79XX_CMDS_PER_DEVICE                \
147 }
148
149 /*
150  * By default, use the number of commands specified by
151  * the users kernel configuration.
152  */
153 static adapter_tag_info_t aic79xx_tag_info[] =
154 {
155         {AIC79XX_CONFIGED_TAG_COMMANDS},
156         {AIC79XX_CONFIGED_TAG_COMMANDS},
157         {AIC79XX_CONFIGED_TAG_COMMANDS},
158         {AIC79XX_CONFIGED_TAG_COMMANDS},
159         {AIC79XX_CONFIGED_TAG_COMMANDS},
160         {AIC79XX_CONFIGED_TAG_COMMANDS},
161         {AIC79XX_CONFIGED_TAG_COMMANDS},
162         {AIC79XX_CONFIGED_TAG_COMMANDS},
163         {AIC79XX_CONFIGED_TAG_COMMANDS},
164         {AIC79XX_CONFIGED_TAG_COMMANDS},
165         {AIC79XX_CONFIGED_TAG_COMMANDS},
166         {AIC79XX_CONFIGED_TAG_COMMANDS},
167         {AIC79XX_CONFIGED_TAG_COMMANDS},
168         {AIC79XX_CONFIGED_TAG_COMMANDS},
169         {AIC79XX_CONFIGED_TAG_COMMANDS},
170         {AIC79XX_CONFIGED_TAG_COMMANDS}
171 };
172
173 /*
174  * The I/O cell on the chip is very configurable in respect to its analog
175  * characteristics.  Set the defaults here; they can be overriden with
176  * the proper insmod parameters.
177  */
178 struct ahd_linux_iocell_opts
179 {
180         uint8_t precomp;
181         uint8_t slewrate;
182         uint8_t amplitude;
183 };
184 #define AIC79XX_DEFAULT_PRECOMP         0xFF
185 #define AIC79XX_DEFAULT_SLEWRATE        0xFF
186 #define AIC79XX_DEFAULT_AMPLITUDE       0xFF
187 #define AIC79XX_DEFAULT_IOOPTS                  \
188 {                                               \
189         AIC79XX_DEFAULT_PRECOMP,                \
190         AIC79XX_DEFAULT_SLEWRATE,               \
191         AIC79XX_DEFAULT_AMPLITUDE               \
192 }
193 #define AIC79XX_PRECOMP_INDEX   0
194 #define AIC79XX_SLEWRATE_INDEX  1
195 #define AIC79XX_AMPLITUDE_INDEX 2
196 static struct ahd_linux_iocell_opts aic79xx_iocell_info[] =
197 {
198         AIC79XX_DEFAULT_IOOPTS,
199         AIC79XX_DEFAULT_IOOPTS,
200         AIC79XX_DEFAULT_IOOPTS,
201         AIC79XX_DEFAULT_IOOPTS,
202         AIC79XX_DEFAULT_IOOPTS,
203         AIC79XX_DEFAULT_IOOPTS,
204         AIC79XX_DEFAULT_IOOPTS,
205         AIC79XX_DEFAULT_IOOPTS,
206         AIC79XX_DEFAULT_IOOPTS,
207         AIC79XX_DEFAULT_IOOPTS,
208         AIC79XX_DEFAULT_IOOPTS,
209         AIC79XX_DEFAULT_IOOPTS,
210         AIC79XX_DEFAULT_IOOPTS,
211         AIC79XX_DEFAULT_IOOPTS,
212         AIC79XX_DEFAULT_IOOPTS,
213         AIC79XX_DEFAULT_IOOPTS
214 };
215
216 /*
217  * There should be a specific return value for this in scsi.h, but
218  * it seems that most drivers ignore it.
219  */
220 #define DID_UNDERFLOW   DID_ERROR
221
222 void
223 ahd_print_path(struct ahd_softc *ahd, struct scb *scb)
224 {
225         printk("(scsi%d:%c:%d:%d): ",
226                ahd->platform_data->host->host_no,
227                scb != NULL ? SCB_GET_CHANNEL(ahd, scb) : 'X',
228                scb != NULL ? SCB_GET_TARGET(ahd, scb) : -1,
229                scb != NULL ? SCB_GET_LUN(scb) : -1);
230 }
231
232 /*
233  * XXX - these options apply unilaterally to _all_ adapters
234  *       cards in the system.  This should be fixed.  Exceptions to this
235  *       rule are noted in the comments.
236  */
237
238 /*
239  * Skip the scsi bus reset.  Non 0 make us skip the reset at startup.  This
240  * has no effect on any later resets that might occur due to things like
241  * SCSI bus timeouts.
242  */
243 static uint32_t aic79xx_no_reset;
244
245 /*
246  * Certain PCI motherboards will scan PCI devices from highest to lowest,
247  * others scan from lowest to highest, and they tend to do all kinds of
248  * strange things when they come into contact with PCI bridge chips.  The
249  * net result of all this is that the PCI card that is actually used to boot
250  * the machine is very hard to detect.  Most motherboards go from lowest
251  * PCI slot number to highest, and the first SCSI controller found is the
252  * one you boot from.  The only exceptions to this are when a controller
253  * has its BIOS disabled.  So, we by default sort all of our SCSI controllers
254  * from lowest PCI slot number to highest PCI slot number.  We also force
255  * all controllers with their BIOS disabled to the end of the list.  This
256  * works on *almost* all computers.  Where it doesn't work, we have this
257  * option.  Setting this option to non-0 will reverse the order of the sort
258  * to highest first, then lowest, but will still leave cards with their BIOS
259  * disabled at the very end.  That should fix everyone up unless there are
260  * really strange cirumstances.
261  */
262 static uint32_t aic79xx_reverse_scan;
263
264 /*
265  * Should we force EXTENDED translation on a controller.
266  *     0 == Use whatever is in the SEEPROM or default to off
267  *     1 == Use whatever is in the SEEPROM or default to on
268  */
269 static uint32_t aic79xx_extended;
270
271 /*
272  * PCI bus parity checking of the Adaptec controllers.  This is somewhat
273  * dubious at best.  To my knowledge, this option has never actually
274  * solved a PCI parity problem, but on certain machines with broken PCI
275  * chipset configurations, it can generate tons of false error messages.
276  * It's included in the driver for completeness.
277  *   0     = Shut off PCI parity check
278  *   non-0 = Enable PCI parity check
279  *
280  * NOTE: you can't actually pass -1 on the lilo prompt.  So, to set this
281  * variable to -1 you would actually want to simply pass the variable
282  * name without a number.  That will invert the 0 which will result in
283  * -1.
284  */
285 static uint32_t aic79xx_pci_parity = ~0;
286
287 /*
288  * There are lots of broken chipsets in the world.  Some of them will
289  * violate the PCI spec when we issue byte sized memory writes to our
290  * controller.  I/O mapped register access, if allowed by the given
291  * platform, will work in almost all cases.
292  */
293 uint32_t aic79xx_allow_memio = ~0;
294
295 /*
296  * So that we can set how long each device is given as a selection timeout.
297  * The table of values goes like this:
298  *   0 - 256ms
299  *   1 - 128ms
300  *   2 - 64ms
301  *   3 - 32ms
302  * We default to 256ms because some older devices need a longer time
303  * to respond to initial selection.
304  */
305 static uint32_t aic79xx_seltime;
306
307 /*
308  * Certain devices do not perform any aging on commands.  Should the
309  * device be saturated by commands in one portion of the disk, it is
310  * possible for transactions on far away sectors to never be serviced.
311  * To handle these devices, we can periodically send an ordered tag to
312  * force all outstanding transactions to be serviced prior to a new
313  * transaction.
314  */
315 uint32_t aic79xx_periodic_otag;
316
317 /* Some storage boxes are using an LSI chip which has a bug making it
318  * impossible to use aic79xx Rev B chip in 320 speeds.  The following
319  * storage boxes have been reported to be buggy:
320  * EonStor 3U 16-Bay: U16U-G3A3
321  * EonStor 2U 12-Bay: U12U-G3A3
322  * SentinelRAID: 2500F R5 / R6
323  * SentinelRAID: 2500F R1
324  * SentinelRAID: 2500F/1500F
325  * SentinelRAID: 150F
326  * 
327  * To get around this LSI bug, you can set your board to 160 mode
328  * or you can enable the SLOWCRC bit.
329  */
330 uint32_t aic79xx_slowcrc;
331
332 /*
333  * Module information and settable options.
334  */
335 static char *aic79xx = NULL;
336
337 MODULE_AUTHOR("Maintainer: Justin T. Gibbs <gibbs@scsiguy.com>");
338 MODULE_DESCRIPTION("Adaptec Aic790X U320 SCSI Host Bus Adapter driver");
339 MODULE_LICENSE("Dual BSD/GPL");
340 MODULE_VERSION(AIC79XX_DRIVER_VERSION);
341 module_param(aic79xx, charp, 0444);
342 MODULE_PARM_DESC(aic79xx,
343 "period delimited, options string.\n"
344 "       verbose                 Enable verbose/diagnostic logging\n"
345 "       allow_memio             Allow device registers to be memory mapped\n"
346 "       debug                   Bitmask of debug values to enable\n"
347 "       no_reset                Supress initial bus resets\n"
348 "       extended                Enable extended geometry on all controllers\n"
349 "       periodic_otag           Send an ordered tagged transaction\n"
350 "                               periodically to prevent tag starvation.\n"
351 "                               This may be required by some older disk\n"
352 "                               or drives/RAID arrays.\n"
353 "       reverse_scan            Sort PCI devices highest Bus/Slot to lowest\n"
354 "       tag_info:<tag_str>      Set per-target tag depth\n"
355 "       global_tag_depth:<int>  Global tag depth for all targets on all buses\n"
356 "       slewrate:<slewrate_list>Set the signal slew rate (0-15).\n"
357 "       precomp:<pcomp_list>    Set the signal precompensation (0-7).\n"
358 "       amplitude:<int>         Set the signal amplitude (0-7).\n"
359 "       seltime:<int>           Selection Timeout:\n"
360 "                               (0/256ms,1/128ms,2/64ms,3/32ms)\n"
361 "       slowcrc                 Turn on the SLOWCRC bit (Rev B only)\n"          
362 "\n"
363 "       Sample /etc/modprobe.conf line:\n"
364 "               Enable verbose logging\n"
365 "               Set tag depth on Controller 2/Target 2 to 10 tags\n"
366 "               Shorten the selection timeout to 128ms\n"
367 "\n"
368 "       options aic79xx 'aic79xx=verbose.tag_info:{{}.{}.{..10}}.seltime:1'\n"
369 "\n");
370
371 static void ahd_linux_handle_scsi_status(struct ahd_softc *,
372                                          struct scsi_device *,
373                                          struct scb *);
374 static void ahd_linux_queue_cmd_complete(struct ahd_softc *ahd,
375                                          struct scsi_cmnd *cmd);
376 static void ahd_linux_sem_timeout(u_long arg);
377 static int  ahd_linux_queue_recovery_cmd(struct scsi_cmnd *cmd, scb_flag flag);
378 static void ahd_linux_initialize_scsi_bus(struct ahd_softc *ahd);
379 static u_int ahd_linux_user_tagdepth(struct ahd_softc *ahd,
380                                      struct ahd_devinfo *devinfo);
381 static void ahd_linux_device_queue_depth(struct scsi_device *);
382 static int ahd_linux_run_command(struct ahd_softc*,
383                                  struct ahd_linux_device *,
384                                  struct scsi_cmnd *);
385 static void ahd_linux_setup_tag_info_global(char *p);
386 static int  aic79xx_setup(char *c);
387
388 static int ahd_linux_unit;
389
390
391 /****************************** Inlines ***************************************/
392 static __inline void ahd_linux_unmap_scb(struct ahd_softc*, struct scb*);
393
394 static __inline void
395 ahd_linux_unmap_scb(struct ahd_softc *ahd, struct scb *scb)
396 {
397         struct scsi_cmnd *cmd;
398         int direction;
399
400         cmd = scb->io_ctx;
401         direction = cmd->sc_data_direction;
402         ahd_sync_sglist(ahd, scb, BUS_DMASYNC_POSTWRITE);
403         if (cmd->use_sg != 0) {
404                 struct scatterlist *sg;
405
406                 sg = (struct scatterlist *)cmd->request_buffer;
407                 pci_unmap_sg(ahd->dev_softc, sg, cmd->use_sg, direction);
408         } else if (cmd->request_bufflen != 0) {
409                 pci_unmap_single(ahd->dev_softc,
410                                  scb->platform_data->buf_busaddr,
411                                  cmd->request_bufflen, direction);
412         }
413 }
414
415 /******************************** Macros **************************************/
416 #define BUILD_SCSIID(ahd, cmd)                                          \
417         (((scmd_id(cmd) << TID_SHIFT) & TID) | (ahd)->our_id)
418
419 /*
420  * Return a string describing the driver.
421  */
422 static const char *
423 ahd_linux_info(struct Scsi_Host *host)
424 {
425         static char buffer[512];
426         char    ahd_info[256];
427         char   *bp;
428         struct ahd_softc *ahd;
429
430         bp = &buffer[0];
431         ahd = *(struct ahd_softc **)host->hostdata;
432         memset(bp, 0, sizeof(buffer));
433         strcpy(bp, "Adaptec AIC79XX PCI-X SCSI HBA DRIVER, Rev ");
434         strcat(bp, AIC79XX_DRIVER_VERSION);
435         strcat(bp, "\n");
436         strcat(bp, "        <");
437         strcat(bp, ahd->description);
438         strcat(bp, ">\n");
439         strcat(bp, "        ");
440         ahd_controller_info(ahd, ahd_info);
441         strcat(bp, ahd_info);
442         strcat(bp, "\n");
443
444         return (bp);
445 }
446
447 /*
448  * Queue an SCB to the controller.
449  */
450 static int
451 ahd_linux_queue(struct scsi_cmnd * cmd, void (*scsi_done) (struct scsi_cmnd *))
452 {
453         struct   ahd_softc *ahd;
454         struct   ahd_linux_device *dev = scsi_transport_device_data(cmd->device);
455         int rtn = SCSI_MLQUEUE_HOST_BUSY;
456         unsigned long flags;
457
458         ahd = *(struct ahd_softc **)cmd->device->host->hostdata;
459
460         ahd_lock(ahd, &flags);
461         if (ahd->platform_data->qfrozen == 0) {
462                 cmd->scsi_done = scsi_done;
463                 cmd->result = CAM_REQ_INPROG << 16;
464                 rtn = ahd_linux_run_command(ahd, dev, cmd);
465
466         }
467         ahd_unlock(ahd, &flags);
468         return rtn;
469 }
470
471 static inline struct scsi_target **
472 ahd_linux_target_in_softc(struct scsi_target *starget)
473 {
474         struct  ahd_softc *ahd =
475                 *((struct ahd_softc **)dev_to_shost(&starget->dev)->hostdata);
476         unsigned int target_offset;
477
478         target_offset = starget->id;
479         if (starget->channel != 0)
480                 target_offset += 8;
481
482         return &ahd->platform_data->starget[target_offset];
483 }
484
485 static int
486 ahd_linux_target_alloc(struct scsi_target *starget)
487 {
488         struct  ahd_softc *ahd =
489                 *((struct ahd_softc **)dev_to_shost(&starget->dev)->hostdata);
490         struct seeprom_config *sc = ahd->seep_config;
491         unsigned long flags;
492         struct scsi_target **ahd_targp = ahd_linux_target_in_softc(starget);
493         struct ahd_linux_target *targ = scsi_transport_target_data(starget);
494         struct ahd_devinfo devinfo;
495         struct ahd_initiator_tinfo *tinfo;
496         struct ahd_tmode_tstate *tstate;
497         char channel = starget->channel + 'A';
498
499         ahd_lock(ahd, &flags);
500
501         BUG_ON(*ahd_targp != NULL);
502
503         *ahd_targp = starget;
504         memset(targ, 0, sizeof(*targ));
505
506         if (sc) {
507                 int flags = sc->device_flags[starget->id];
508
509                 tinfo = ahd_fetch_transinfo(ahd, 'A', ahd->our_id,
510                                             starget->id, &tstate);
511
512                 if ((flags  & CFPACKETIZED) == 0) {
513                         /* Do not negotiate packetized transfers */
514                         spi_rd_strm(starget) = 0;
515                         spi_pcomp_en(starget) = 0;
516                         spi_rti(starget) = 0;
517                         spi_wr_flow(starget) = 0;
518                         spi_hold_mcs(starget) = 0;
519                 } else {
520                         if ((ahd->features & AHD_RTI) == 0)
521                                 spi_rti(starget) = 0;
522                 }
523
524                 if ((flags & CFQAS) == 0)
525                         spi_qas(starget) = 0;
526
527                 /* Transinfo values have been set to BIOS settings */
528                 spi_max_width(starget) = (flags & CFWIDEB) ? 1 : 0;
529                 spi_min_period(starget) = tinfo->user.period;
530                 spi_max_offset(starget) = tinfo->user.offset;
531         }
532
533         tinfo = ahd_fetch_transinfo(ahd, channel, ahd->our_id,
534                                     starget->id, &tstate);
535         ahd_compile_devinfo(&devinfo, ahd->our_id, starget->id,
536                             CAM_LUN_WILDCARD, channel,
537                             ROLE_INITIATOR);
538         ahd_set_syncrate(ahd, &devinfo, 0, 0, 0,
539                          AHD_TRANS_GOAL, /*paused*/FALSE);
540         ahd_set_width(ahd, &devinfo, MSG_EXT_WDTR_BUS_8_BIT,
541                       AHD_TRANS_GOAL, /*paused*/FALSE);
542         ahd_unlock(ahd, &flags);
543
544         return 0;
545 }
546
547 static void
548 ahd_linux_target_destroy(struct scsi_target *starget)
549 {
550         struct scsi_target **ahd_targp = ahd_linux_target_in_softc(starget);
551
552         *ahd_targp = NULL;
553 }
554
555 static int
556 ahd_linux_slave_alloc(struct scsi_device *sdev)
557 {
558         struct  ahd_softc *ahd =
559                 *((struct ahd_softc **)sdev->host->hostdata);
560         struct scsi_target *starget = sdev->sdev_target;
561         struct ahd_linux_target *targ = scsi_transport_target_data(starget);
562         struct ahd_linux_device *dev;
563
564         if (bootverbose)
565                 printf("%s: Slave Alloc %d\n", ahd_name(ahd), sdev->id);
566
567         BUG_ON(targ->sdev[sdev->lun] != NULL);
568
569         dev = scsi_transport_device_data(sdev);
570         memset(dev, 0, sizeof(*dev));
571
572         /*
573          * We start out life using untagged
574          * transactions of which we allow one.
575          */
576         dev->openings = 1;
577
578         /*
579          * Set maxtags to 0.  This will be changed if we
580          * later determine that we are dealing with
581          * a tagged queuing capable device.
582          */
583         dev->maxtags = 0;
584         
585         targ->sdev[sdev->lun] = sdev;
586
587         return (0);
588 }
589
590 static int
591 ahd_linux_slave_configure(struct scsi_device *sdev)
592 {
593         struct  ahd_softc *ahd;
594
595         ahd = *((struct ahd_softc **)sdev->host->hostdata);
596         if (bootverbose)
597                 sdev_printk(KERN_INFO, sdev, "Slave Configure\n");
598
599         ahd_linux_device_queue_depth(sdev);
600
601         /* Initial Domain Validation */
602         if (!spi_initial_dv(sdev->sdev_target))
603                 spi_dv_device(sdev);
604
605         return 0;
606 }
607
608 static void
609 ahd_linux_slave_destroy(struct scsi_device *sdev)
610 {
611         struct  ahd_softc *ahd;
612         struct  ahd_linux_device *dev = scsi_transport_device_data(sdev);
613         struct  ahd_linux_target *targ = scsi_transport_target_data(sdev->sdev_target);
614
615         ahd = *((struct ahd_softc **)sdev->host->hostdata);
616         if (bootverbose)
617                 printf("%s: Slave Destroy %d\n", ahd_name(ahd), sdev->id);
618
619         BUG_ON(dev->active);
620
621         targ->sdev[sdev->lun] = NULL;
622
623 }
624
625 #if defined(__i386__)
626 /*
627  * Return the disk geometry for the given SCSI device.
628  */
629 static int
630 ahd_linux_biosparam(struct scsi_device *sdev, struct block_device *bdev,
631                     sector_t capacity, int geom[])
632 {
633         uint8_t *bh;
634         int      heads;
635         int      sectors;
636         int      cylinders;
637         int      ret;
638         int      extended;
639         struct   ahd_softc *ahd;
640
641         ahd = *((struct ahd_softc **)sdev->host->hostdata);
642
643         bh = scsi_bios_ptable(bdev);
644         if (bh) {
645                 ret = scsi_partsize(bh, capacity,
646                                     &geom[2], &geom[0], &geom[1]);
647                 kfree(bh);
648                 if (ret != -1)
649                         return (ret);
650         }
651         heads = 64;
652         sectors = 32;
653         cylinders = aic_sector_div(capacity, heads, sectors);
654
655         if (aic79xx_extended != 0)
656                 extended = 1;
657         else
658                 extended = (ahd->flags & AHD_EXTENDED_TRANS_A) != 0;
659         if (extended && cylinders >= 1024) {
660                 heads = 255;
661                 sectors = 63;
662                 cylinders = aic_sector_div(capacity, heads, sectors);
663         }
664         geom[0] = heads;
665         geom[1] = sectors;
666         geom[2] = cylinders;
667         return (0);
668 }
669 #endif
670
671 /*
672  * Abort the current SCSI command(s).
673  */
674 static int
675 ahd_linux_abort(struct scsi_cmnd *cmd)
676 {
677         int error;
678
679         error = ahd_linux_queue_recovery_cmd(cmd, SCB_ABORT);
680         if (error != 0)
681                 printf("aic79xx_abort returns 0x%x\n", error);
682         return error;
683 }
684
685 /*
686  * Attempt to send a target reset message to the device that timed out.
687  */
688 static int
689 ahd_linux_dev_reset(struct scsi_cmnd *cmd)
690 {
691         int error;
692
693         error = ahd_linux_queue_recovery_cmd(cmd, SCB_DEVICE_RESET);
694         if (error != 0)
695                 printf("aic79xx_dev_reset returns 0x%x\n", error);
696         return error;
697 }
698
699 /*
700  * Reset the SCSI bus.
701  */
702 static int
703 ahd_linux_bus_reset(struct scsi_cmnd *cmd)
704 {
705         struct ahd_softc *ahd;
706         u_long s;
707         int    found;
708
709         ahd = *(struct ahd_softc **)cmd->device->host->hostdata;
710 #ifdef AHD_DEBUG
711         if ((ahd_debug & AHD_SHOW_RECOVERY) != 0)
712                 printf("%s: Bus reset called for cmd %p\n",
713                        ahd_name(ahd), cmd);
714 #endif
715         ahd_lock(ahd, &s);
716         found = ahd_reset_channel(ahd, scmd_channel(cmd) + 'A',
717                                   /*initiate reset*/TRUE);
718         ahd_unlock(ahd, &s);
719
720         if (bootverbose)
721                 printf("%s: SCSI bus reset delivered. "
722                        "%d SCBs aborted.\n", ahd_name(ahd), found);
723
724         return (SUCCESS);
725 }
726
727 struct scsi_host_template aic79xx_driver_template = {
728         .module                 = THIS_MODULE,
729         .name                   = "aic79xx",
730         .proc_name              = "aic79xx",
731         .proc_info              = ahd_linux_proc_info,
732         .info                   = ahd_linux_info,
733         .queuecommand           = ahd_linux_queue,
734         .eh_abort_handler       = ahd_linux_abort,
735         .eh_device_reset_handler = ahd_linux_dev_reset,
736         .eh_bus_reset_handler   = ahd_linux_bus_reset,
737 #if defined(__i386__)
738         .bios_param             = ahd_linux_biosparam,
739 #endif
740         .can_queue              = AHD_MAX_QUEUE,
741         .this_id                = -1,
742         .cmd_per_lun            = 2,
743         .use_clustering         = ENABLE_CLUSTERING,
744         .slave_alloc            = ahd_linux_slave_alloc,
745         .slave_configure        = ahd_linux_slave_configure,
746         .slave_destroy          = ahd_linux_slave_destroy,
747         .target_alloc           = ahd_linux_target_alloc,
748         .target_destroy         = ahd_linux_target_destroy,
749 };
750
751 /******************************** Bus DMA *************************************/
752 int
753 ahd_dma_tag_create(struct ahd_softc *ahd, bus_dma_tag_t parent,
754                    bus_size_t alignment, bus_size_t boundary,
755                    dma_addr_t lowaddr, dma_addr_t highaddr,
756                    bus_dma_filter_t *filter, void *filterarg,
757                    bus_size_t maxsize, int nsegments,
758                    bus_size_t maxsegsz, int flags, bus_dma_tag_t *ret_tag)
759 {
760         bus_dma_tag_t dmat;
761
762         dmat = malloc(sizeof(*dmat), M_DEVBUF, M_NOWAIT);
763         if (dmat == NULL)
764                 return (ENOMEM);
765
766         /*
767          * Linux is very simplistic about DMA memory.  For now don't
768          * maintain all specification information.  Once Linux supplies
769          * better facilities for doing these operations, or the
770          * needs of this particular driver change, we might need to do
771          * more here.
772          */
773         dmat->alignment = alignment;
774         dmat->boundary = boundary;
775         dmat->maxsize = maxsize;
776         *ret_tag = dmat;
777         return (0);
778 }
779
780 void
781 ahd_dma_tag_destroy(struct ahd_softc *ahd, bus_dma_tag_t dmat)
782 {
783         free(dmat, M_DEVBUF);
784 }
785
786 int
787 ahd_dmamem_alloc(struct ahd_softc *ahd, bus_dma_tag_t dmat, void** vaddr,
788                  int flags, bus_dmamap_t *mapp)
789 {
790         *vaddr = pci_alloc_consistent(ahd->dev_softc,
791                                       dmat->maxsize, mapp);
792         if (*vaddr == NULL)
793                 return (ENOMEM);
794         return(0);
795 }
796
797 void
798 ahd_dmamem_free(struct ahd_softc *ahd, bus_dma_tag_t dmat,
799                 void* vaddr, bus_dmamap_t map)
800 {
801         pci_free_consistent(ahd->dev_softc, dmat->maxsize,
802                             vaddr, map);
803 }
804
805 int
806 ahd_dmamap_load(struct ahd_softc *ahd, bus_dma_tag_t dmat, bus_dmamap_t map,
807                 void *buf, bus_size_t buflen, bus_dmamap_callback_t *cb,
808                 void *cb_arg, int flags)
809 {
810         /*
811          * Assume for now that this will only be used during
812          * initialization and not for per-transaction buffer mapping.
813          */
814         bus_dma_segment_t stack_sg;
815
816         stack_sg.ds_addr = map;
817         stack_sg.ds_len = dmat->maxsize;
818         cb(cb_arg, &stack_sg, /*nseg*/1, /*error*/0);
819         return (0);
820 }
821
822 void
823 ahd_dmamap_destroy(struct ahd_softc *ahd, bus_dma_tag_t dmat, bus_dmamap_t map)
824 {
825 }
826
827 int
828 ahd_dmamap_unload(struct ahd_softc *ahd, bus_dma_tag_t dmat, bus_dmamap_t map)
829 {
830         /* Nothing to do */
831         return (0);
832 }
833
834 /********************* Platform Dependent Functions ***************************/
835 /*
836  * Compare "left hand" softc with "right hand" softc, returning:
837  * < 0 - lahd has a lower priority than rahd
838  *   0 - Softcs are equal
839  * > 0 - lahd has a higher priority than rahd
840  */
841 int
842 ahd_softc_comp(struct ahd_softc *lahd, struct ahd_softc *rahd)
843 {
844         int     value;
845
846         /*
847          * Under Linux, cards are ordered as follows:
848          *      1) PCI devices that are marked as the boot controller.
849          *      2) PCI devices with BIOS enabled sorted by bus/slot/func.
850          *      3) All remaining PCI devices sorted by bus/slot/func.
851          */
852 #if 0
853         value = (lahd->flags & AHD_BOOT_CHANNEL)
854               - (rahd->flags & AHD_BOOT_CHANNEL);
855         if (value != 0)
856                 /* Controllers set for boot have a *higher* priority */
857                 return (value);
858 #endif
859
860         value = (lahd->flags & AHD_BIOS_ENABLED)
861               - (rahd->flags & AHD_BIOS_ENABLED);
862         if (value != 0)
863                 /* Controllers with BIOS enabled have a *higher* priority */
864                 return (value);
865
866         /* Still equal.  Sort by bus/slot/func. */
867         if (aic79xx_reverse_scan != 0)
868                 value = ahd_get_pci_bus(lahd->dev_softc)
869                       - ahd_get_pci_bus(rahd->dev_softc);
870         else
871                 value = ahd_get_pci_bus(rahd->dev_softc)
872                       - ahd_get_pci_bus(lahd->dev_softc);
873         if (value != 0)
874                 return (value);
875         if (aic79xx_reverse_scan != 0)
876                 value = ahd_get_pci_slot(lahd->dev_softc)
877                       - ahd_get_pci_slot(rahd->dev_softc);
878         else
879                 value = ahd_get_pci_slot(rahd->dev_softc)
880                       - ahd_get_pci_slot(lahd->dev_softc);
881         if (value != 0)
882                 return (value);
883
884         value = rahd->channel - lahd->channel;
885         return (value);
886 }
887
888 static void
889 ahd_linux_setup_iocell_info(u_long index, int instance, int targ, int32_t value)
890 {
891
892         if ((instance >= 0)
893          && (instance < NUM_ELEMENTS(aic79xx_iocell_info))) {
894                 uint8_t *iocell_info;
895
896                 iocell_info = (uint8_t*)&aic79xx_iocell_info[instance];
897                 iocell_info[index] = value & 0xFFFF;
898                 if (bootverbose)
899                         printf("iocell[%d:%ld] = %d\n", instance, index, value);
900         }
901 }
902
903 static void
904 ahd_linux_setup_tag_info_global(char *p)
905 {
906         int tags, i, j;
907
908         tags = simple_strtoul(p + 1, NULL, 0) & 0xff;
909         printf("Setting Global Tags= %d\n", tags);
910
911         for (i = 0; i < NUM_ELEMENTS(aic79xx_tag_info); i++) {
912                 for (j = 0; j < AHD_NUM_TARGETS; j++) {
913                         aic79xx_tag_info[i].tag_commands[j] = tags;
914                 }
915         }
916 }
917
918 static void
919 ahd_linux_setup_tag_info(u_long arg, int instance, int targ, int32_t value)
920 {
921
922         if ((instance >= 0) && (targ >= 0)
923          && (instance < NUM_ELEMENTS(aic79xx_tag_info))
924          && (targ < AHD_NUM_TARGETS)) {
925                 aic79xx_tag_info[instance].tag_commands[targ] = value & 0x1FF;
926                 if (bootverbose)
927                         printf("tag_info[%d:%d] = %d\n", instance, targ, value);
928         }
929 }
930
931 static char *
932 ahd_parse_brace_option(char *opt_name, char *opt_arg, char *end, int depth,
933                        void (*callback)(u_long, int, int, int32_t),
934                        u_long callback_arg)
935 {
936         char    *tok_end;
937         char    *tok_end2;
938         int      i;
939         int      instance;
940         int      targ;
941         int      done;
942         char     tok_list[] = {'.', ',', '{', '}', '\0'};
943
944         /* All options use a ':' name/arg separator */
945         if (*opt_arg != ':')
946                 return (opt_arg);
947         opt_arg++;
948         instance = -1;
949         targ = -1;
950         done = FALSE;
951         /*
952          * Restore separator that may be in
953          * the middle of our option argument.
954          */
955         tok_end = strchr(opt_arg, '\0');
956         if (tok_end < end)
957                 *tok_end = ',';
958         while (!done) {
959                 switch (*opt_arg) {
960                 case '{':
961                         if (instance == -1) {
962                                 instance = 0;
963                         } else {
964                                 if (depth > 1) {
965                                         if (targ == -1)
966                                                 targ = 0;
967                                 } else {
968                                         printf("Malformed Option %s\n",
969                                                opt_name);
970                                         done = TRUE;
971                                 }
972                         }
973                         opt_arg++;
974                         break;
975                 case '}':
976                         if (targ != -1)
977                                 targ = -1;
978                         else if (instance != -1)
979                                 instance = -1;
980                         opt_arg++;
981                         break;
982                 case ',':
983                 case '.':
984                         if (instance == -1)
985                                 done = TRUE;
986                         else if (targ >= 0)
987                                 targ++;
988                         else if (instance >= 0)
989                                 instance++;
990                         opt_arg++;
991                         break;
992                 case '\0':
993                         done = TRUE;
994                         break;
995                 default:
996                         tok_end = end;
997                         for (i = 0; tok_list[i]; i++) {
998                                 tok_end2 = strchr(opt_arg, tok_list[i]);
999                                 if ((tok_end2) && (tok_end2 < tok_end))
1000                                         tok_end = tok_end2;
1001                         }
1002                         callback(callback_arg, instance, targ,
1003                                  simple_strtol(opt_arg, NULL, 0));
1004                         opt_arg = tok_end;
1005                         break;
1006                 }
1007         }
1008         return (opt_arg);
1009 }
1010
1011 /*
1012  * Handle Linux boot parameters. This routine allows for assigning a value
1013  * to a parameter with a ':' between the parameter and the value.
1014  * ie. aic79xx=stpwlev:1,extended
1015  */
1016 static int
1017 aic79xx_setup(char *s)
1018 {
1019         int     i, n;
1020         char   *p;
1021         char   *end;
1022
1023         static struct {
1024                 const char *name;
1025                 uint32_t *flag;
1026         } options[] = {
1027                 { "extended", &aic79xx_extended },
1028                 { "no_reset", &aic79xx_no_reset },
1029                 { "verbose", &aic79xx_verbose },
1030                 { "allow_memio", &aic79xx_allow_memio},
1031 #ifdef AHD_DEBUG
1032                 { "debug", &ahd_debug },
1033 #endif
1034                 { "reverse_scan", &aic79xx_reverse_scan },
1035                 { "periodic_otag", &aic79xx_periodic_otag },
1036                 { "pci_parity", &aic79xx_pci_parity },
1037                 { "seltime", &aic79xx_seltime },
1038                 { "tag_info", NULL },
1039                 { "global_tag_depth", NULL},
1040                 { "slewrate", NULL },
1041                 { "precomp", NULL },
1042                 { "amplitude", NULL },
1043                 { "slowcrc", &aic79xx_slowcrc },
1044         };
1045
1046         end = strchr(s, '\0');
1047
1048         /*
1049          * XXX ia64 gcc isn't smart enough to know that NUM_ELEMENTS
1050          * will never be 0 in this case.
1051          */      
1052         n = 0;  
1053
1054         while ((p = strsep(&s, ",.")) != NULL) {
1055                 if (*p == '\0')
1056                         continue;
1057                 for (i = 0; i < NUM_ELEMENTS(options); i++) {
1058
1059                         n = strlen(options[i].name);
1060                         if (strncmp(options[i].name, p, n) == 0)
1061                                 break;
1062                 }
1063                 if (i == NUM_ELEMENTS(options))
1064                         continue;
1065
1066                 if (strncmp(p, "global_tag_depth", n) == 0) {
1067                         ahd_linux_setup_tag_info_global(p + n);
1068                 } else if (strncmp(p, "tag_info", n) == 0) {
1069                         s = ahd_parse_brace_option("tag_info", p + n, end,
1070                             2, ahd_linux_setup_tag_info, 0);
1071                 } else if (strncmp(p, "slewrate", n) == 0) {
1072                         s = ahd_parse_brace_option("slewrate",
1073                             p + n, end, 1, ahd_linux_setup_iocell_info,
1074                             AIC79XX_SLEWRATE_INDEX);
1075                 } else if (strncmp(p, "precomp", n) == 0) {
1076                         s = ahd_parse_brace_option("precomp",
1077                             p + n, end, 1, ahd_linux_setup_iocell_info,
1078                             AIC79XX_PRECOMP_INDEX);
1079                 } else if (strncmp(p, "amplitude", n) == 0) {
1080                         s = ahd_parse_brace_option("amplitude",
1081                             p + n, end, 1, ahd_linux_setup_iocell_info,
1082                             AIC79XX_AMPLITUDE_INDEX);
1083                 } else if (p[n] == ':') {
1084                         *(options[i].flag) = simple_strtoul(p + n + 1, NULL, 0);
1085                 } else if (!strncmp(p, "verbose", n)) {
1086                         *(options[i].flag) = 1;
1087                 } else {
1088                         *(options[i].flag) ^= 0xFFFFFFFF;
1089                 }
1090         }
1091         return 1;
1092 }
1093
1094 __setup("aic79xx=", aic79xx_setup);
1095
1096 uint32_t aic79xx_verbose;
1097
1098 int
1099 ahd_linux_register_host(struct ahd_softc *ahd, struct scsi_host_template *template)
1100 {
1101         char    buf[80];
1102         struct  Scsi_Host *host;
1103         char    *new_name;
1104         u_long  s;
1105         int     retval;
1106
1107         template->name = ahd->description;
1108         host = scsi_host_alloc(template, sizeof(struct ahd_softc *));
1109         if (host == NULL)
1110                 return (ENOMEM);
1111
1112         *((struct ahd_softc **)host->hostdata) = ahd;
1113         ahd->platform_data->host = host;
1114         host->can_queue = AHD_MAX_QUEUE;
1115         host->cmd_per_lun = 2;
1116         host->sg_tablesize = AHD_NSEG;
1117         host->this_id = ahd->our_id;
1118         host->irq = ahd->platform_data->irq;
1119         host->max_id = (ahd->features & AHD_WIDE) ? 16 : 8;
1120         host->max_lun = AHD_NUM_LUNS;
1121         host->max_channel = 0;
1122         host->sg_tablesize = AHD_NSEG;
1123         ahd_lock(ahd, &s);
1124         ahd_set_unit(ahd, ahd_linux_unit++);
1125         ahd_unlock(ahd, &s);
1126         sprintf(buf, "scsi%d", host->host_no);
1127         new_name = malloc(strlen(buf) + 1, M_DEVBUF, M_NOWAIT);
1128         if (new_name != NULL) {
1129                 strcpy(new_name, buf);
1130                 ahd_set_name(ahd, new_name);
1131         }
1132         host->unique_id = ahd->unit;
1133         ahd_linux_initialize_scsi_bus(ahd);
1134         ahd_intr_enable(ahd, TRUE);
1135
1136         host->transportt = ahd_linux_transport_template;
1137
1138         retval = scsi_add_host(host, &ahd->dev_softc->dev);
1139         if (retval) {
1140                 printk(KERN_WARNING "aic79xx: scsi_add_host failed\n");
1141                 scsi_host_put(host);
1142                 return retval;
1143         }
1144
1145         scsi_scan_host(host);
1146         return 0;
1147 }
1148
1149 uint64_t
1150 ahd_linux_get_memsize(void)
1151 {
1152         struct sysinfo si;
1153
1154         si_meminfo(&si);
1155         return ((uint64_t)si.totalram << PAGE_SHIFT);
1156 }
1157
1158 /*
1159  * Place the SCSI bus into a known state by either resetting it,
1160  * or forcing transfer negotiations on the next command to any
1161  * target.
1162  */
1163 static void
1164 ahd_linux_initialize_scsi_bus(struct ahd_softc *ahd)
1165 {
1166         u_int target_id;
1167         u_int numtarg;
1168         unsigned long s;
1169
1170         target_id = 0;
1171         numtarg = 0;
1172
1173         if (aic79xx_no_reset != 0)
1174                 ahd->flags &= ~AHD_RESET_BUS_A;
1175
1176         if ((ahd->flags & AHD_RESET_BUS_A) != 0)
1177                 ahd_reset_channel(ahd, 'A', /*initiate_reset*/TRUE);
1178         else
1179                 numtarg = (ahd->features & AHD_WIDE) ? 16 : 8;
1180
1181         ahd_lock(ahd, &s);
1182
1183         /*
1184          * Force negotiation to async for all targets that
1185          * will not see an initial bus reset.
1186          */
1187         for (; target_id < numtarg; target_id++) {
1188                 struct ahd_devinfo devinfo;
1189                 struct ahd_initiator_tinfo *tinfo;
1190                 struct ahd_tmode_tstate *tstate;
1191
1192                 tinfo = ahd_fetch_transinfo(ahd, 'A', ahd->our_id,
1193                                             target_id, &tstate);
1194                 ahd_compile_devinfo(&devinfo, ahd->our_id, target_id,
1195                                     CAM_LUN_WILDCARD, 'A', ROLE_INITIATOR);
1196                 ahd_update_neg_request(ahd, &devinfo, tstate,
1197                                        tinfo, AHD_NEG_ALWAYS);
1198         }
1199         ahd_unlock(ahd, &s);
1200         /* Give the bus some time to recover */
1201         if ((ahd->flags & AHD_RESET_BUS_A) != 0) {
1202                 ahd_freeze_simq(ahd);
1203                 msleep(AIC79XX_RESET_DELAY);
1204                 ahd_release_simq(ahd);
1205         }
1206 }
1207
1208 int
1209 ahd_platform_alloc(struct ahd_softc *ahd, void *platform_arg)
1210 {
1211         ahd->platform_data =
1212             malloc(sizeof(struct ahd_platform_data), M_DEVBUF, M_NOWAIT);
1213         if (ahd->platform_data == NULL)
1214                 return (ENOMEM);
1215         memset(ahd->platform_data, 0, sizeof(struct ahd_platform_data));
1216         ahd->platform_data->irq = AHD_LINUX_NOIRQ;
1217         ahd_lockinit(ahd);
1218         init_MUTEX_LOCKED(&ahd->platform_data->eh_sem);
1219         ahd->seltime = (aic79xx_seltime & 0x3) << 4;
1220         return (0);
1221 }
1222
1223 void
1224 ahd_platform_free(struct ahd_softc *ahd)
1225 {
1226         struct scsi_target *starget;
1227         int i, j;
1228
1229         if (ahd->platform_data != NULL) {
1230                 /* destroy all of the device and target objects */
1231                 for (i = 0; i < AHD_NUM_TARGETS; i++) {
1232                         starget = ahd->platform_data->starget[i];
1233                         if (starget != NULL) {
1234                                 for (j = 0; j < AHD_NUM_LUNS; j++) {
1235                                         struct ahd_linux_target *targ =
1236                                                 scsi_transport_target_data(starget);
1237                                         if (targ->sdev[j] == NULL)
1238                                                 continue;
1239                                         targ->sdev[j] = NULL;
1240                                 }
1241                                 ahd->platform_data->starget[i] = NULL;
1242                         }
1243                 }
1244
1245                 if (ahd->platform_data->irq != AHD_LINUX_NOIRQ)
1246                         free_irq(ahd->platform_data->irq, ahd);
1247                 if (ahd->tags[0] == BUS_SPACE_PIO
1248                  && ahd->bshs[0].ioport != 0)
1249                         release_region(ahd->bshs[0].ioport, 256);
1250                 if (ahd->tags[1] == BUS_SPACE_PIO
1251                  && ahd->bshs[1].ioport != 0)
1252                         release_region(ahd->bshs[1].ioport, 256);
1253                 if (ahd->tags[0] == BUS_SPACE_MEMIO
1254                  && ahd->bshs[0].maddr != NULL) {
1255                         iounmap(ahd->bshs[0].maddr);
1256                         release_mem_region(ahd->platform_data->mem_busaddr,
1257                                            0x1000);
1258                 }
1259                 if (ahd->platform_data->host)
1260                         scsi_host_put(ahd->platform_data->host);
1261
1262                 free(ahd->platform_data, M_DEVBUF);
1263         }
1264 }
1265
1266 void
1267 ahd_platform_init(struct ahd_softc *ahd)
1268 {
1269         /*
1270          * Lookup and commit any modified IO Cell options.
1271          */
1272         if (ahd->unit < NUM_ELEMENTS(aic79xx_iocell_info)) {
1273                 struct ahd_linux_iocell_opts *iocell_opts;
1274
1275                 iocell_opts = &aic79xx_iocell_info[ahd->unit];
1276                 if (iocell_opts->precomp != AIC79XX_DEFAULT_PRECOMP)
1277                         AHD_SET_PRECOMP(ahd, iocell_opts->precomp);
1278                 if (iocell_opts->slewrate != AIC79XX_DEFAULT_SLEWRATE)
1279                         AHD_SET_SLEWRATE(ahd, iocell_opts->slewrate);
1280                 if (iocell_opts->amplitude != AIC79XX_DEFAULT_AMPLITUDE)
1281                         AHD_SET_AMPLITUDE(ahd, iocell_opts->amplitude);
1282         }
1283
1284 }
1285
1286 void
1287 ahd_platform_freeze_devq(struct ahd_softc *ahd, struct scb *scb)
1288 {
1289         ahd_platform_abort_scbs(ahd, SCB_GET_TARGET(ahd, scb),
1290                                 SCB_GET_CHANNEL(ahd, scb),
1291                                 SCB_GET_LUN(scb), SCB_LIST_NULL,
1292                                 ROLE_UNKNOWN, CAM_REQUEUE_REQ);
1293 }
1294
1295 void
1296 ahd_platform_set_tags(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
1297                       ahd_queue_alg alg)
1298 {
1299         struct scsi_target *starget;
1300         struct ahd_linux_target *targ;
1301         struct ahd_linux_device *dev;
1302         struct scsi_device *sdev;
1303         int was_queuing;
1304         int now_queuing;
1305
1306         starget = ahd->platform_data->starget[devinfo->target];
1307         targ = scsi_transport_target_data(starget);
1308         BUG_ON(targ == NULL);
1309         sdev = targ->sdev[devinfo->lun];
1310         if (sdev == NULL)
1311                 return;
1312
1313         dev = scsi_transport_device_data(sdev);
1314
1315         if (dev == NULL)
1316                 return;
1317         was_queuing = dev->flags & (AHD_DEV_Q_BASIC|AHD_DEV_Q_TAGGED);
1318         switch (alg) {
1319         default:
1320         case AHD_QUEUE_NONE:
1321                 now_queuing = 0;
1322                 break; 
1323         case AHD_QUEUE_BASIC:
1324                 now_queuing = AHD_DEV_Q_BASIC;
1325                 break;
1326         case AHD_QUEUE_TAGGED:
1327                 now_queuing = AHD_DEV_Q_TAGGED;
1328                 break;
1329         }
1330         if ((dev->flags & AHD_DEV_FREEZE_TIL_EMPTY) == 0
1331          && (was_queuing != now_queuing)
1332          && (dev->active != 0)) {
1333                 dev->flags |= AHD_DEV_FREEZE_TIL_EMPTY;
1334                 dev->qfrozen++;
1335         }
1336
1337         dev->flags &= ~(AHD_DEV_Q_BASIC|AHD_DEV_Q_TAGGED|AHD_DEV_PERIODIC_OTAG);
1338         if (now_queuing) {
1339                 u_int usertags;
1340
1341                 usertags = ahd_linux_user_tagdepth(ahd, devinfo);
1342                 if (!was_queuing) {
1343                         /*
1344                          * Start out agressively and allow our
1345                          * dynamic queue depth algorithm to take
1346                          * care of the rest.
1347                          */
1348                         dev->maxtags = usertags;
1349                         dev->openings = dev->maxtags - dev->active;
1350                 }
1351                 if (dev->maxtags == 0) {
1352                         /*
1353                          * Queueing is disabled by the user.
1354                          */
1355                         dev->openings = 1;
1356                 } else if (alg == AHD_QUEUE_TAGGED) {
1357                         dev->flags |= AHD_DEV_Q_TAGGED;
1358                         if (aic79xx_periodic_otag != 0)
1359                                 dev->flags |= AHD_DEV_PERIODIC_OTAG;
1360                 } else
1361                         dev->flags |= AHD_DEV_Q_BASIC;
1362         } else {
1363                 /* We can only have one opening. */
1364                 dev->maxtags = 0;
1365                 dev->openings =  1 - dev->active;
1366         }
1367
1368         switch ((dev->flags & (AHD_DEV_Q_BASIC|AHD_DEV_Q_TAGGED))) {
1369         case AHD_DEV_Q_BASIC:
1370                 scsi_adjust_queue_depth(sdev,
1371                                         MSG_SIMPLE_TASK,
1372                                         dev->openings + dev->active);
1373                 break;
1374         case AHD_DEV_Q_TAGGED:
1375                 scsi_adjust_queue_depth(sdev,
1376                                         MSG_ORDERED_TASK,
1377                                         dev->openings + dev->active);
1378                 break;
1379         default:
1380                 /*
1381                  * We allow the OS to queue 2 untagged transactions to
1382                  * us at any time even though we can only execute them
1383                  * serially on the controller/device.  This should
1384                  * remove some latency.
1385                  */
1386                 scsi_adjust_queue_depth(sdev,
1387                                         /*NON-TAGGED*/0,
1388                                         /*queue depth*/2);
1389                 break;
1390         }
1391 }
1392
1393 int
1394 ahd_platform_abort_scbs(struct ahd_softc *ahd, int target, char channel,
1395                         int lun, u_int tag, role_t role, uint32_t status)
1396 {
1397         return 0;
1398 }
1399
1400 static u_int
1401 ahd_linux_user_tagdepth(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
1402 {
1403         static int warned_user;
1404         u_int tags;
1405
1406         tags = 0;
1407         if ((ahd->user_discenable & devinfo->target_mask) != 0) {
1408                 if (ahd->unit >= NUM_ELEMENTS(aic79xx_tag_info)) {
1409
1410                         if (warned_user == 0) {
1411                                 printf(KERN_WARNING
1412 "aic79xx: WARNING: Insufficient tag_info instances\n"
1413 "aic79xx: for installed controllers.  Using defaults\n"
1414 "aic79xx: Please update the aic79xx_tag_info array in\n"
1415 "aic79xx: the aic79xx_osm.c source file.\n");
1416                                 warned_user++;
1417                         }
1418                         tags = AHD_MAX_QUEUE;
1419                 } else {
1420                         adapter_tag_info_t *tag_info;
1421
1422                         tag_info = &aic79xx_tag_info[ahd->unit];
1423                         tags = tag_info->tag_commands[devinfo->target_offset];
1424                         if (tags > AHD_MAX_QUEUE)
1425                                 tags = AHD_MAX_QUEUE;
1426                 }
1427         }
1428         return (tags);
1429 }
1430
1431 /*
1432  * Determines the queue depth for a given device.
1433  */
1434 static void
1435 ahd_linux_device_queue_depth(struct scsi_device *sdev)
1436 {
1437         struct  ahd_devinfo devinfo;
1438         u_int   tags;
1439         struct ahd_softc *ahd = *((struct ahd_softc **)sdev->host->hostdata);
1440
1441         ahd_compile_devinfo(&devinfo,
1442                             ahd->our_id,
1443                             sdev->sdev_target->id, sdev->lun,
1444                             sdev->sdev_target->channel == 0 ? 'A' : 'B',
1445                             ROLE_INITIATOR);
1446         tags = ahd_linux_user_tagdepth(ahd, &devinfo);
1447         if (tags != 0 && sdev->tagged_supported != 0) {
1448
1449                 ahd_set_tags(ahd, &devinfo, AHD_QUEUE_TAGGED);
1450                 ahd_print_devinfo(ahd, &devinfo);
1451                 printf("Tagged Queuing enabled.  Depth %d\n", tags);
1452         } else {
1453                 ahd_set_tags(ahd, &devinfo, AHD_QUEUE_NONE);
1454         }
1455 }
1456
1457 static int
1458 ahd_linux_run_command(struct ahd_softc *ahd, struct ahd_linux_device *dev,
1459                       struct scsi_cmnd *cmd)
1460 {
1461         struct   scb *scb;
1462         struct   hardware_scb *hscb;
1463         struct   ahd_initiator_tinfo *tinfo;
1464         struct   ahd_tmode_tstate *tstate;
1465         u_int    col_idx;
1466         uint16_t mask;
1467
1468         /*
1469          * Get an scb to use.
1470          */
1471         tinfo = ahd_fetch_transinfo(ahd, 'A', ahd->our_id,
1472                                     cmd->device->id, &tstate);
1473         if ((dev->flags & (AHD_DEV_Q_TAGGED|AHD_DEV_Q_BASIC)) == 0
1474          || (tinfo->curr.ppr_options & MSG_EXT_PPR_IU_REQ) != 0) {
1475                 col_idx = AHD_NEVER_COL_IDX;
1476         } else {
1477                 col_idx = AHD_BUILD_COL_IDX(cmd->device->id,
1478                                             cmd->device->lun);
1479         }
1480         if ((scb = ahd_get_scb(ahd, col_idx)) == NULL) {
1481                 ahd->flags |= AHD_RESOURCE_SHORTAGE;
1482                 return SCSI_MLQUEUE_HOST_BUSY;
1483         }
1484
1485         scb->io_ctx = cmd;
1486         scb->platform_data->dev = dev;
1487         hscb = scb->hscb;
1488         cmd->host_scribble = (char *)scb;
1489
1490         /*
1491          * Fill out basics of the HSCB.
1492          */
1493         hscb->control = 0;
1494         hscb->scsiid = BUILD_SCSIID(ahd, cmd);
1495         hscb->lun = cmd->device->lun;
1496         scb->hscb->task_management = 0;
1497         mask = SCB_GET_TARGET_MASK(ahd, scb);
1498
1499         if ((ahd->user_discenable & mask) != 0)
1500                 hscb->control |= DISCENB;
1501
1502         if ((tinfo->curr.ppr_options & MSG_EXT_PPR_IU_REQ) != 0)
1503                 scb->flags |= SCB_PACKETIZED;
1504
1505         if ((tstate->auto_negotiate & mask) != 0) {
1506                 scb->flags |= SCB_AUTO_NEGOTIATE;
1507                 scb->hscb->control |= MK_MESSAGE;
1508                 } else if (cmd->cmnd[0] == INQUIRY
1509                         && (tinfo->curr.offset != 0
1510                          || tinfo->curr.width != MSG_EXT_WDTR_BUS_8_BIT
1511                          || tinfo->curr.ppr_options != 0)
1512                         && (tinfo->curr.ppr_options & MSG_EXT_PPR_IU_REQ)==0) {
1513                         /*
1514                          * The SCSI spec requires inquiry
1515                          * commands to complete without
1516                          * reporting unit attention conditions.
1517                          * Because of this, an inquiry command
1518                          * that occurs just after a device is
1519                          * reset will result in a data phase
1520                          * with mismatched negotiated rates.
1521                          * The core already forces a renegotiation
1522                          * for reset events that are visible to
1523                          * our controller or that we initiate,
1524                          * but a third party device reset or a
1525                          * hot-plug insertion can still cause this
1526                          * issue.  Therefore, we force a re-negotiation
1527                          * for every inquiry command unless we
1528                          * are async.
1529                          */
1530                         scb->flags |= SCB_NEGOTIATE;
1531                         scb->hscb->control |= MK_MESSAGE;
1532         }
1533
1534         if ((dev->flags & (AHD_DEV_Q_TAGGED|AHD_DEV_Q_BASIC)) != 0) {
1535                 int     msg_bytes;
1536                 uint8_t tag_msgs[2];
1537
1538                 msg_bytes = scsi_populate_tag_msg(cmd, tag_msgs);
1539                 if (msg_bytes && tag_msgs[0] != MSG_SIMPLE_TASK) {
1540                         hscb->control |= tag_msgs[0];
1541                         if (tag_msgs[0] == MSG_ORDERED_TASK)
1542                                 dev->commands_since_idle_or_otag = 0;
1543                 } else
1544                 if (dev->commands_since_idle_or_otag == AHD_OTAG_THRESH
1545                  && (dev->flags & AHD_DEV_Q_TAGGED) != 0) {
1546                         hscb->control |= MSG_ORDERED_TASK;
1547                         dev->commands_since_idle_or_otag = 0;
1548                 } else {
1549                         hscb->control |= MSG_SIMPLE_TASK;
1550                 }
1551         }
1552
1553         hscb->cdb_len = cmd->cmd_len;
1554         memcpy(hscb->shared_data.idata.cdb, cmd->cmnd, hscb->cdb_len);
1555
1556         scb->platform_data->xfer_len = 0;
1557         ahd_set_residual(scb, 0);
1558         ahd_set_sense_residual(scb, 0);
1559         scb->sg_count = 0;
1560         if (cmd->use_sg != 0) {
1561                 void    *sg;
1562                 struct   scatterlist *cur_seg;
1563                 u_int    nseg;
1564                 int      dir;
1565
1566                 cur_seg = (struct scatterlist *)cmd->request_buffer;
1567                 dir = cmd->sc_data_direction;
1568                 nseg = pci_map_sg(ahd->dev_softc, cur_seg,
1569                                   cmd->use_sg, dir);
1570                 scb->platform_data->xfer_len = 0;
1571                 for (sg = scb->sg_list; nseg > 0; nseg--, cur_seg++) {
1572                         dma_addr_t addr;
1573                         bus_size_t len;
1574
1575                         addr = sg_dma_address(cur_seg);
1576                         len = sg_dma_len(cur_seg);
1577                         scb->platform_data->xfer_len += len;
1578                         sg = ahd_sg_setup(ahd, scb, sg, addr, len,
1579                                           /*last*/nseg == 1);
1580                 }
1581         } else if (cmd->request_bufflen != 0) {
1582                 void *sg;
1583                 dma_addr_t addr;
1584                 int dir;
1585
1586                 sg = scb->sg_list;
1587                 dir = cmd->sc_data_direction;
1588                 addr = pci_map_single(ahd->dev_softc,
1589                                       cmd->request_buffer,
1590                                       cmd->request_bufflen, dir);
1591                 scb->platform_data->xfer_len = cmd->request_bufflen;
1592                 scb->platform_data->buf_busaddr = addr;
1593                 sg = ahd_sg_setup(ahd, scb, sg, addr,
1594                                   cmd->request_bufflen, /*last*/TRUE);
1595         }
1596
1597         LIST_INSERT_HEAD(&ahd->pending_scbs, scb, pending_links);
1598         dev->openings--;
1599         dev->active++;
1600         dev->commands_issued++;
1601
1602         if ((dev->flags & AHD_DEV_PERIODIC_OTAG) != 0)
1603                 dev->commands_since_idle_or_otag++;
1604         scb->flags |= SCB_ACTIVE;
1605         ahd_queue_scb(ahd, scb);
1606
1607         return 0;
1608 }
1609
1610 /*
1611  * SCSI controller interrupt handler.
1612  */
1613 irqreturn_t
1614 ahd_linux_isr(int irq, void *dev_id, struct pt_regs * regs)
1615 {
1616         struct  ahd_softc *ahd;
1617         u_long  flags;
1618         int     ours;
1619
1620         ahd = (struct ahd_softc *) dev_id;
1621         ahd_lock(ahd, &flags); 
1622         ours = ahd_intr(ahd);
1623         ahd_unlock(ahd, &flags);
1624         return IRQ_RETVAL(ours);
1625 }
1626
1627 void
1628 ahd_platform_flushwork(struct ahd_softc *ahd)
1629 {
1630
1631 }
1632
1633 void
1634 ahd_send_async(struct ahd_softc *ahd, char channel,
1635                u_int target, u_int lun, ac_code code, void *arg)
1636 {
1637         switch (code) {
1638         case AC_TRANSFER_NEG:
1639         {
1640                 char    buf[80];
1641                 struct  scsi_target *starget;
1642                 struct  ahd_linux_target *targ;
1643                 struct  info_str info;
1644                 struct  ahd_initiator_tinfo *tinfo;
1645                 struct  ahd_tmode_tstate *tstate;
1646                 unsigned int target_ppr_options;
1647
1648                 BUG_ON(target == CAM_TARGET_WILDCARD);
1649
1650                 info.buffer = buf;
1651                 info.length = sizeof(buf);
1652                 info.offset = 0;
1653                 info.pos = 0;
1654                 tinfo = ahd_fetch_transinfo(ahd, channel, ahd->our_id,
1655                                             target, &tstate);
1656
1657                 /*
1658                  * Don't bother reporting results while
1659                  * negotiations are still pending.
1660                  */
1661                 if (tinfo->curr.period != tinfo->goal.period
1662                  || tinfo->curr.width != tinfo->goal.width
1663                  || tinfo->curr.offset != tinfo->goal.offset
1664                  || tinfo->curr.ppr_options != tinfo->goal.ppr_options)
1665                         if (bootverbose == 0)
1666                                 break;
1667
1668                 /*
1669                  * Don't bother reporting results that
1670                  * are identical to those last reported.
1671                  */
1672                 starget = ahd->platform_data->starget[target];
1673                 if (starget == NULL)
1674                         break;
1675                 targ = scsi_transport_target_data(starget);
1676
1677                 target_ppr_options =
1678                         (spi_dt(starget) ? MSG_EXT_PPR_DT_REQ : 0)
1679                         + (spi_qas(starget) ? MSG_EXT_PPR_QAS_REQ : 0)
1680                         + (spi_iu(starget) ?  MSG_EXT_PPR_IU_REQ : 0)
1681                         + (spi_rd_strm(starget) ? MSG_EXT_PPR_RD_STRM : 0)
1682                         + (spi_pcomp_en(starget) ? MSG_EXT_PPR_PCOMP_EN : 0)
1683                         + (spi_rti(starget) ? MSG_EXT_PPR_RTI : 0)
1684                         + (spi_wr_flow(starget) ? MSG_EXT_PPR_WR_FLOW : 0)
1685                         + (spi_hold_mcs(starget) ? MSG_EXT_PPR_HOLD_MCS : 0);
1686
1687                 if (tinfo->curr.period == spi_period(starget)
1688                     && tinfo->curr.width == spi_width(starget)
1689                     && tinfo->curr.offset == spi_offset(starget)
1690                  && tinfo->curr.ppr_options == target_ppr_options)
1691                         if (bootverbose == 0)
1692                                 break;
1693
1694                 spi_period(starget) = tinfo->curr.period;
1695                 spi_width(starget) = tinfo->curr.width;
1696                 spi_offset(starget) = tinfo->curr.offset;
1697                 spi_dt(starget) = tinfo->curr.ppr_options & MSG_EXT_PPR_DT_REQ ? 1 : 0;
1698                 spi_qas(starget) = tinfo->curr.ppr_options & MSG_EXT_PPR_QAS_REQ ? 1 : 0;
1699                 spi_iu(starget) = tinfo->curr.ppr_options & MSG_EXT_PPR_IU_REQ ? 1 : 0;
1700                 spi_rd_strm(starget) = tinfo->curr.ppr_options & MSG_EXT_PPR_RD_STRM ? 1 : 0;
1701                 spi_pcomp_en(starget) =  tinfo->curr.ppr_options & MSG_EXT_PPR_PCOMP_EN ? 1 : 0;
1702                 spi_rti(starget) =  tinfo->curr.ppr_options &  MSG_EXT_PPR_RTI ? 1 : 0;
1703                 spi_wr_flow(starget) = tinfo->curr.ppr_options & MSG_EXT_PPR_WR_FLOW ? 1 : 0;
1704                 spi_hold_mcs(starget) = tinfo->curr.ppr_options & MSG_EXT_PPR_HOLD_MCS ? 1 : 0;
1705                 spi_display_xfer_agreement(starget);
1706                 break;
1707         }
1708         case AC_SENT_BDR:
1709         {
1710                 WARN_ON(lun != CAM_LUN_WILDCARD);
1711                 scsi_report_device_reset(ahd->platform_data->host,
1712                                          channel - 'A', target);
1713                 break;
1714         }
1715         case AC_BUS_RESET:
1716                 if (ahd->platform_data->host != NULL) {
1717                         scsi_report_bus_reset(ahd->platform_data->host,
1718                                               channel - 'A');
1719                 }
1720                 break;
1721         default:
1722                 panic("ahd_send_async: Unexpected async event");
1723         }
1724 }
1725
1726 /*
1727  * Calls the higher level scsi done function and frees the scb.
1728  */
1729 void
1730 ahd_done(struct ahd_softc *ahd, struct scb *scb)
1731 {
1732         struct scsi_cmnd *cmd;
1733         struct    ahd_linux_device *dev;
1734
1735         if ((scb->flags & SCB_ACTIVE) == 0) {
1736                 printf("SCB %d done'd twice\n", SCB_GET_TAG(scb));
1737                 ahd_dump_card_state(ahd);
1738                 panic("Stopping for safety");
1739         }
1740         LIST_REMOVE(scb, pending_links);
1741         cmd = scb->io_ctx;
1742         dev = scb->platform_data->dev;
1743         dev->active--;
1744         dev->openings++;
1745         if ((cmd->result & (CAM_DEV_QFRZN << 16)) != 0) {
1746                 cmd->result &= ~(CAM_DEV_QFRZN << 16);
1747                 dev->qfrozen--;
1748         }
1749         ahd_linux_unmap_scb(ahd, scb);
1750
1751         /*
1752          * Guard against stale sense data.
1753          * The Linux mid-layer assumes that sense
1754          * was retrieved anytime the first byte of
1755          * the sense buffer looks "sane".
1756          */
1757         cmd->sense_buffer[0] = 0;
1758         if (ahd_get_transaction_status(scb) == CAM_REQ_INPROG) {
1759                 uint32_t amount_xferred;
1760
1761                 amount_xferred =
1762                     ahd_get_transfer_length(scb) - ahd_get_residual(scb);
1763                 if ((scb->flags & SCB_TRANSMISSION_ERROR) != 0) {
1764 #ifdef AHD_DEBUG
1765                         if ((ahd_debug & AHD_SHOW_MISC) != 0) {
1766                                 ahd_print_path(ahd, scb);
1767                                 printf("Set CAM_UNCOR_PARITY\n");
1768                         }
1769 #endif
1770                         ahd_set_transaction_status(scb, CAM_UNCOR_PARITY);
1771 #ifdef AHD_REPORT_UNDERFLOWS
1772                 /*
1773                  * This code is disabled by default as some
1774                  * clients of the SCSI system do not properly
1775                  * initialize the underflow parameter.  This
1776                  * results in spurious termination of commands
1777                  * that complete as expected (e.g. underflow is
1778                  * allowed as command can return variable amounts
1779                  * of data.
1780                  */
1781                 } else if (amount_xferred < scb->io_ctx->underflow) {
1782                         u_int i;
1783
1784                         ahd_print_path(ahd, scb);
1785                         printf("CDB:");
1786                         for (i = 0; i < scb->io_ctx->cmd_len; i++)
1787                                 printf(" 0x%x", scb->io_ctx->cmnd[i]);
1788                         printf("\n");
1789                         ahd_print_path(ahd, scb);
1790                         printf("Saw underflow (%ld of %ld bytes). "
1791                                "Treated as error\n",
1792                                 ahd_get_residual(scb),
1793                                 ahd_get_transfer_length(scb));
1794                         ahd_set_transaction_status(scb, CAM_DATA_RUN_ERR);
1795 #endif
1796                 } else {
1797                         ahd_set_transaction_status(scb, CAM_REQ_CMP);
1798                 }
1799         } else if (ahd_get_transaction_status(scb) == CAM_SCSI_STATUS_ERROR) {
1800                 ahd_linux_handle_scsi_status(ahd, cmd->device, scb);
1801         }
1802
1803         if (dev->openings == 1
1804          && ahd_get_transaction_status(scb) == CAM_REQ_CMP
1805          && ahd_get_scsi_status(scb) != SCSI_STATUS_QUEUE_FULL)
1806                 dev->tag_success_count++;
1807         /*
1808          * Some devices deal with temporary internal resource
1809          * shortages by returning queue full.  When the queue
1810          * full occurrs, we throttle back.  Slowly try to get
1811          * back to our previous queue depth.
1812          */
1813         if ((dev->openings + dev->active) < dev->maxtags
1814          && dev->tag_success_count > AHD_TAG_SUCCESS_INTERVAL) {
1815                 dev->tag_success_count = 0;
1816                 dev->openings++;
1817         }
1818
1819         if (dev->active == 0)
1820                 dev->commands_since_idle_or_otag = 0;
1821
1822         if ((scb->flags & SCB_RECOVERY_SCB) != 0) {
1823                 printf("Recovery SCB completes\n");
1824                 if (ahd_get_transaction_status(scb) == CAM_BDR_SENT
1825                  || ahd_get_transaction_status(scb) == CAM_REQ_ABORTED)
1826                         ahd_set_transaction_status(scb, CAM_CMD_TIMEOUT);
1827                 if ((ahd->platform_data->flags & AHD_SCB_UP_EH_SEM) != 0) {
1828                         ahd->platform_data->flags &= ~AHD_SCB_UP_EH_SEM;
1829                         up(&ahd->platform_data->eh_sem);
1830                 }
1831         }
1832
1833         ahd_free_scb(ahd, scb);
1834         ahd_linux_queue_cmd_complete(ahd, cmd);
1835 }
1836
1837 static void
1838 ahd_linux_handle_scsi_status(struct ahd_softc *ahd,
1839                              struct scsi_device *sdev, struct scb *scb)
1840 {
1841         struct  ahd_devinfo devinfo;
1842         struct ahd_linux_device *dev = scsi_transport_device_data(sdev);
1843
1844         ahd_compile_devinfo(&devinfo,
1845                             ahd->our_id,
1846                             sdev->sdev_target->id, sdev->lun,
1847                             sdev->sdev_target->channel == 0 ? 'A' : 'B',
1848                             ROLE_INITIATOR);
1849         
1850         /*
1851          * We don't currently trust the mid-layer to
1852          * properly deal with queue full or busy.  So,
1853          * when one occurs, we tell the mid-layer to
1854          * unconditionally requeue the command to us
1855          * so that we can retry it ourselves.  We also
1856          * implement our own throttling mechanism so
1857          * we don't clobber the device with too many
1858          * commands.
1859          */
1860         switch (ahd_get_scsi_status(scb)) {
1861         default:
1862                 break;
1863         case SCSI_STATUS_CHECK_COND:
1864         case SCSI_STATUS_CMD_TERMINATED:
1865         {
1866                 struct scsi_cmnd *cmd;
1867
1868                 /*
1869                  * Copy sense information to the OS's cmd
1870                  * structure if it is available.
1871                  */
1872                 cmd = scb->io_ctx;
1873                 if ((scb->flags & (SCB_SENSE|SCB_PKT_SENSE)) != 0) {
1874                         struct scsi_status_iu_header *siu;
1875                         u_int sense_size;
1876                         u_int sense_offset;
1877
1878                         if (scb->flags & SCB_SENSE) {
1879                                 sense_size = MIN(sizeof(struct scsi_sense_data)
1880                                                - ahd_get_sense_residual(scb),
1881                                                  sizeof(cmd->sense_buffer));
1882                                 sense_offset = 0;
1883                         } else {
1884                                 /*
1885                                  * Copy only the sense data into the provided
1886                                  * buffer.
1887                                  */
1888                                 siu = (struct scsi_status_iu_header *)
1889                                     scb->sense_data;
1890                                 sense_size = MIN(scsi_4btoul(siu->sense_length),
1891                                                 sizeof(cmd->sense_buffer));
1892                                 sense_offset = SIU_SENSE_OFFSET(siu);
1893                         }
1894
1895                         memset(cmd->sense_buffer, 0, sizeof(cmd->sense_buffer));
1896                         memcpy(cmd->sense_buffer,
1897                                ahd_get_sense_buf(ahd, scb)
1898                                + sense_offset, sense_size);
1899                         cmd->result |= (DRIVER_SENSE << 24);
1900
1901 #ifdef AHD_DEBUG
1902                         if (ahd_debug & AHD_SHOW_SENSE) {
1903                                 int i;
1904
1905                                 printf("Copied %d bytes of sense data at %d:",
1906                                        sense_size, sense_offset);
1907                                 for (i = 0; i < sense_size; i++) {
1908                                         if ((i & 0xF) == 0)
1909                                                 printf("\n");
1910                                         printf("0x%x ", cmd->sense_buffer[i]);
1911                                 }
1912                                 printf("\n");
1913                         }
1914 #endif
1915                 }
1916                 break;
1917         }
1918         case SCSI_STATUS_QUEUE_FULL:
1919                 /*
1920                  * By the time the core driver has returned this
1921                  * command, all other commands that were queued
1922                  * to us but not the device have been returned.
1923                  * This ensures that dev->active is equal to
1924                  * the number of commands actually queued to
1925                  * the device.
1926                  */
1927                 dev->tag_success_count = 0;
1928                 if (dev->active != 0) {
1929                         /*
1930                          * Drop our opening count to the number
1931                          * of commands currently outstanding.
1932                          */
1933                         dev->openings = 0;
1934 #ifdef AHD_DEBUG
1935                         if ((ahd_debug & AHD_SHOW_QFULL) != 0) {
1936                                 ahd_print_path(ahd, scb);
1937                                 printf("Dropping tag count to %d\n",
1938                                        dev->active);
1939                         }
1940 #endif
1941                         if (dev->active == dev->tags_on_last_queuefull) {
1942
1943                                 dev->last_queuefull_same_count++;
1944                                 /*
1945                                  * If we repeatedly see a queue full
1946                                  * at the same queue depth, this
1947                                  * device has a fixed number of tag
1948                                  * slots.  Lock in this tag depth
1949                                  * so we stop seeing queue fulls from
1950                                  * this device.
1951                                  */
1952                                 if (dev->last_queuefull_same_count
1953                                  == AHD_LOCK_TAGS_COUNT) {
1954                                         dev->maxtags = dev->active;
1955                                         ahd_print_path(ahd, scb);
1956                                         printf("Locking max tag count at %d\n",
1957                                                dev->active);
1958                                 }
1959                         } else {
1960                                 dev->tags_on_last_queuefull = dev->active;
1961                                 dev->last_queuefull_same_count = 0;
1962                         }
1963                         ahd_set_transaction_status(scb, CAM_REQUEUE_REQ);
1964                         ahd_set_scsi_status(scb, SCSI_STATUS_OK);
1965                         ahd_platform_set_tags(ahd, &devinfo,
1966                                      (dev->flags & AHD_DEV_Q_BASIC)
1967                                    ? AHD_QUEUE_BASIC : AHD_QUEUE_TAGGED);
1968                         break;
1969                 }
1970                 /*
1971                  * Drop down to a single opening, and treat this
1972                  * as if the target returned BUSY SCSI status.
1973                  */
1974                 dev->openings = 1;
1975                 ahd_platform_set_tags(ahd, &devinfo,
1976                              (dev->flags & AHD_DEV_Q_BASIC)
1977                            ? AHD_QUEUE_BASIC : AHD_QUEUE_TAGGED);
1978                 ahd_set_scsi_status(scb, SCSI_STATUS_BUSY);
1979         }
1980 }
1981
1982 static void
1983 ahd_linux_queue_cmd_complete(struct ahd_softc *ahd, struct scsi_cmnd *cmd)
1984 {
1985         /*
1986          * Map CAM error codes into Linux Error codes.  We
1987          * avoid the conversion so that the DV code has the
1988          * full error information available when making
1989          * state change decisions.
1990          */
1991         {
1992                 uint32_t status;
1993                 u_int new_status;
1994
1995                 status = ahd_cmd_get_transaction_status(cmd);
1996                 switch (status) {
1997                 case CAM_REQ_INPROG:
1998                 case CAM_REQ_CMP:
1999                 case CAM_SCSI_STATUS_ERROR:
2000                         new_status = DID_OK;
2001                         break;
2002                 case CAM_REQ_ABORTED:
2003                         new_status = DID_ABORT;
2004                         break;
2005                 case CAM_BUSY:
2006                         new_status = DID_BUS_BUSY;
2007                         break;
2008                 case CAM_REQ_INVALID:
2009                 case CAM_PATH_INVALID:
2010                         new_status = DID_BAD_TARGET;
2011                         break;
2012                 case CAM_SEL_TIMEOUT:
2013                         new_status = DID_NO_CONNECT;
2014                         break;
2015                 case CAM_SCSI_BUS_RESET:
2016                 case CAM_BDR_SENT:
2017                         new_status = DID_RESET;
2018                         break;
2019                 case CAM_UNCOR_PARITY:
2020                         new_status = DID_PARITY;
2021                         break;
2022                 case CAM_CMD_TIMEOUT:
2023                         new_status = DID_TIME_OUT;
2024                         break;
2025                 case CAM_UA_ABORT:
2026                 case CAM_REQ_CMP_ERR:
2027                 case CAM_AUTOSENSE_FAIL:
2028                 case CAM_NO_HBA:
2029                 case CAM_DATA_RUN_ERR:
2030                 case CAM_UNEXP_BUSFREE:
2031                 case CAM_SEQUENCE_FAIL:
2032                 case CAM_CCB_LEN_ERR:
2033                 case CAM_PROVIDE_FAIL:
2034                 case CAM_REQ_TERMIO:
2035                 case CAM_UNREC_HBA_ERROR:
2036                 case CAM_REQ_TOO_BIG:
2037                         new_status = DID_ERROR;
2038                         break;
2039                 case CAM_REQUEUE_REQ:
2040                         new_status = DID_REQUEUE;
2041                         break;
2042                 default:
2043                         /* We should never get here */
2044                         new_status = DID_ERROR;
2045                         break;
2046                 }
2047
2048                 ahd_cmd_set_transaction_status(cmd, new_status);
2049         }
2050
2051         cmd->scsi_done(cmd);
2052 }
2053
2054 static void
2055 ahd_linux_sem_timeout(u_long arg)
2056 {
2057         struct  ahd_softc *ahd;
2058         u_long  s;
2059
2060         ahd = (struct ahd_softc *)arg;
2061
2062         ahd_lock(ahd, &s);
2063         if ((ahd->platform_data->flags & AHD_SCB_UP_EH_SEM) != 0) {
2064                 ahd->platform_data->flags &= ~AHD_SCB_UP_EH_SEM;
2065                 up(&ahd->platform_data->eh_sem);
2066         }
2067         ahd_unlock(ahd, &s);
2068 }
2069
2070 void
2071 ahd_freeze_simq(struct ahd_softc *ahd)
2072 {
2073         unsigned long s;
2074
2075         ahd_lock(ahd, &s);
2076         ahd->platform_data->qfrozen++;
2077         if (ahd->platform_data->qfrozen == 1) {
2078                 scsi_block_requests(ahd->platform_data->host);
2079                 ahd_platform_abort_scbs(ahd, CAM_TARGET_WILDCARD, ALL_CHANNELS,
2080                                         CAM_LUN_WILDCARD, SCB_LIST_NULL,
2081                                         ROLE_INITIATOR, CAM_REQUEUE_REQ);
2082         }
2083         ahd_unlock(ahd, &s);
2084 }
2085
2086 void
2087 ahd_release_simq(struct ahd_softc *ahd)
2088 {
2089         u_long s;
2090         int    unblock_reqs;
2091
2092         unblock_reqs = 0;
2093         ahd_lock(ahd, &s);
2094         if (ahd->platform_data->qfrozen > 0)
2095                 ahd->platform_data->qfrozen--;
2096         if (ahd->platform_data->qfrozen == 0) {
2097                 unblock_reqs = 1;
2098         }
2099         ahd_unlock(ahd, &s);
2100         /*
2101          * There is still a race here.  The mid-layer
2102          * should keep its own freeze count and use
2103          * a bottom half handler to run the queues
2104          * so we can unblock with our own lock held.
2105          */
2106         if (unblock_reqs)
2107                 scsi_unblock_requests(ahd->platform_data->host);
2108 }
2109
2110 static int
2111 ahd_linux_queue_recovery_cmd(struct scsi_cmnd *cmd, scb_flag flag)
2112 {
2113         struct ahd_softc *ahd;
2114         struct ahd_linux_device *dev;
2115         struct scb *pending_scb;
2116         u_int  saved_scbptr;
2117         u_int  active_scbptr;
2118         u_int  last_phase;
2119         u_int  saved_scsiid;
2120         u_int  cdb_byte;
2121         int    retval;
2122         int    was_paused;
2123         int    paused;
2124         int    wait;
2125         int    disconnected;
2126         int    found;
2127         ahd_mode_state saved_modes;
2128         unsigned long flags;
2129
2130         pending_scb = NULL;
2131         paused = FALSE;
2132         wait = FALSE;
2133         ahd = *(struct ahd_softc **)cmd->device->host->hostdata;
2134
2135         scmd_printk(KERN_INFO, cmd,
2136                "Attempting to queue a%s message:",
2137                flag == SCB_ABORT ? "n ABORT" : " TARGET RESET");
2138
2139         printf("CDB:");
2140         for (cdb_byte = 0; cdb_byte < cmd->cmd_len; cdb_byte++)
2141                 printf(" 0x%x", cmd->cmnd[cdb_byte]);
2142         printf("\n");
2143
2144         ahd_lock(ahd, &flags);
2145
2146         /*
2147          * First determine if we currently own this command.
2148          * Start by searching the device queue.  If not found
2149          * there, check the pending_scb list.  If not found
2150          * at all, and the system wanted us to just abort the
2151          * command, return success.
2152          */
2153         dev = scsi_transport_device_data(cmd->device);
2154
2155         if (dev == NULL) {
2156                 /*
2157                  * No target device for this command exists,
2158                  * so we must not still own the command.
2159                  */
2160                 scmd_printk(KERN_INFO, cmd, "Is not an active device\n");
2161                 retval = SUCCESS;
2162                 goto no_cmd;
2163         }
2164
2165         /*
2166          * See if we can find a matching cmd in the pending list.
2167          */
2168         LIST_FOREACH(pending_scb, &ahd->pending_scbs, pending_links) {
2169                 if (pending_scb->io_ctx == cmd)
2170                         break;
2171         }
2172
2173         if (pending_scb == NULL && flag == SCB_DEVICE_RESET) {
2174
2175                 /* Any SCB for this device will do for a target reset */
2176                 LIST_FOREACH(pending_scb, &ahd->pending_scbs, pending_links) {
2177                         if (ahd_match_scb(ahd, pending_scb,
2178                                           scmd_id(cmd),
2179                                           scmd_channel(cmd) + 'A',
2180                                           CAM_LUN_WILDCARD,
2181                                           SCB_LIST_NULL, ROLE_INITIATOR))
2182                                 break;
2183                 }
2184         }
2185
2186         if (pending_scb == NULL) {
2187                 scmd_printk(KERN_INFO, cmd, "Command not found\n");
2188                 goto no_cmd;
2189         }
2190
2191         if ((pending_scb->flags & SCB_RECOVERY_SCB) != 0) {
2192                 /*
2193                  * We can't queue two recovery actions using the same SCB
2194                  */
2195                 retval = FAILED;
2196                 goto  done;
2197         }
2198
2199         /*
2200          * Ensure that the card doesn't do anything
2201          * behind our back.  Also make sure that we
2202          * didn't "just" miss an interrupt that would
2203          * affect this cmd.
2204          */
2205         was_paused = ahd_is_paused(ahd);
2206         ahd_pause_and_flushwork(ahd);
2207         paused = TRUE;
2208
2209         if ((pending_scb->flags & SCB_ACTIVE) == 0) {
2210                 scmd_printk(KERN_INFO, cmd, "Command already completed\n");
2211                 goto no_cmd;
2212         }
2213
2214         printf("%s: At time of recovery, card was %spaused\n",
2215                ahd_name(ahd), was_paused ? "" : "not ");
2216         ahd_dump_card_state(ahd);
2217
2218         disconnected = TRUE;
2219         if (flag == SCB_ABORT) {
2220                 if (ahd_search_qinfifo(ahd, cmd->device->id, 
2221                                        cmd->device->channel + 'A',
2222                                        cmd->device->lun, 
2223                                        pending_scb->hscb->tag,
2224                                        ROLE_INITIATOR, CAM_REQ_ABORTED,
2225                                        SEARCH_COMPLETE) > 0) {
2226                         printf("%s:%d:%d:%d: Cmd aborted from QINFIFO\n",
2227                                ahd_name(ahd), cmd->device->channel, 
2228                                cmd->device->id, cmd->device->lun);
2229                         retval = SUCCESS;
2230                         goto done;
2231                 }
2232         } else if (ahd_search_qinfifo(ahd, cmd->device->id,
2233                                       cmd->device->channel + 'A',
2234                                       cmd->device->lun, pending_scb->hscb->tag,
2235                                       ROLE_INITIATOR, /*status*/0,
2236                                       SEARCH_COUNT) > 0) {
2237                 disconnected = FALSE;
2238         }
2239
2240         saved_modes = ahd_save_modes(ahd);
2241         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
2242         last_phase = ahd_inb(ahd, LASTPHASE);
2243         saved_scbptr = ahd_get_scbptr(ahd);
2244         active_scbptr = saved_scbptr;
2245         if (disconnected && ((last_phase != P_BUSFREE) || 
2246                              (ahd_inb(ahd, SEQ_FLAGS) & NOT_IDENTIFIED) == 0)) {
2247                 struct scb *bus_scb;
2248
2249                 bus_scb = ahd_lookup_scb(ahd, active_scbptr);
2250                 if (bus_scb == pending_scb)
2251                         disconnected = FALSE;
2252                 else if (flag != SCB_ABORT
2253                          && ahd_inb(ahd, SAVED_SCSIID) == pending_scb->hscb->scsiid
2254                          && ahd_inb(ahd, SAVED_LUN) == SCB_GET_LUN(pending_scb))
2255                         disconnected = FALSE;
2256         }
2257
2258         /*
2259          * At this point, pending_scb is the scb associated with the
2260          * passed in command.  That command is currently active on the
2261          * bus or is in the disconnected state.
2262          */
2263         saved_scsiid = ahd_inb(ahd, SAVED_SCSIID);
2264         if (SCB_GET_TAG(pending_scb) == active_scbptr
2265              || (flag == SCB_DEVICE_RESET
2266                  && SCSIID_TARGET(ahd, saved_scsiid) == scmd_id(cmd))) {
2267
2268                 /*
2269                  * We're active on the bus, so assert ATN
2270                  * and hope that the target responds.
2271                  */
2272                 pending_scb = ahd_lookup_scb(ahd, active_scbptr);
2273                 pending_scb->flags |= SCB_RECOVERY_SCB|SCB_DEVICE_RESET;
2274                 ahd_outb(ahd, MSG_OUT, HOST_MSG);
2275                 ahd_outb(ahd, SCSISIGO, last_phase|ATNO);
2276                 scmd_printk(KERN_INFO, cmd, "BDR message in message buffer\n");
2277                 wait = TRUE;
2278         } else if (last_phase != P_BUSFREE
2279                    && ahd_inb(ahd, SCSIPHASE) == 0) {
2280                 /*
2281                  * SCB is not identified, there
2282                  * is no pending REQ, and the sequencer
2283                  * has not seen a busfree.  Looks like
2284                  * a stuck connection waiting to
2285                  * go busfree.  Reset the bus.
2286                  */
2287                 found = ahd_reset_channel(ahd, cmd->device->channel + 'A',
2288                                           /*Initiate Reset*/TRUE);
2289                 printf("%s: Issued Channel %c Bus Reset. "
2290                        "%d SCBs aborted\n", ahd_name(ahd),
2291                        cmd->device->channel + 'A', found);
2292         } else if (disconnected) {
2293
2294                 /*
2295                  * Actually re-queue this SCB in an attempt
2296                  * to select the device before it reconnects.
2297                  */
2298                 pending_scb->flags |= SCB_RECOVERY_SCB|flag;
2299                 ahd_set_scbptr(ahd, SCB_GET_TAG(pending_scb));
2300                 pending_scb->hscb->cdb_len = 0;
2301                 pending_scb->hscb->task_attribute = 0;
2302                 pending_scb->hscb->task_management = SIU_TASKMGMT_ABORT_TASK;
2303
2304                 if ((pending_scb->flags & SCB_PACKETIZED) != 0) {
2305                         /*
2306                          * Mark the SCB has having an outstanding
2307                          * task management function.  Should the command
2308                          * complete normally before the task management
2309                          * function can be sent, the host will be notified
2310                          * to abort our requeued SCB.
2311                          */
2312                         ahd_outb(ahd, SCB_TASK_MANAGEMENT,
2313                                  pending_scb->hscb->task_management);
2314                 } else {
2315                         /*
2316                          * If non-packetized, set the MK_MESSAGE control
2317                          * bit indicating that we desire to send a message.
2318                          * We also set the disconnected flag since there is
2319                          * no guarantee that our SCB control byte matches
2320                          * the version on the card.  We don't want the
2321                          * sequencer to abort the command thinking an
2322                          * unsolicited reselection occurred.
2323                          */
2324                         pending_scb->hscb->control |= MK_MESSAGE|DISCONNECTED;
2325
2326                         /*
2327                          * The sequencer will never re-reference the
2328                          * in-core SCB.  To make sure we are notified
2329                          * during reslection, set the MK_MESSAGE flag in
2330                          * the card's copy of the SCB.
2331                          */
2332                         ahd_outb(ahd, SCB_CONTROL,
2333                                  ahd_inb(ahd, SCB_CONTROL)|MK_MESSAGE);
2334                 }
2335
2336                 /*
2337                  * Clear out any entries in the QINFIFO first
2338                  * so we are the next SCB for this target
2339                  * to run.
2340                  */
2341                 ahd_search_qinfifo(ahd, cmd->device->id,
2342                                    cmd->device->channel + 'A', cmd->device->lun,
2343                                    SCB_LIST_NULL, ROLE_INITIATOR,
2344                                    CAM_REQUEUE_REQ, SEARCH_COMPLETE);
2345                 ahd_qinfifo_requeue_tail(ahd, pending_scb);
2346                 ahd_set_scbptr(ahd, saved_scbptr);
2347                 ahd_print_path(ahd, pending_scb);
2348                 printf("Device is disconnected, re-queuing SCB\n");
2349                 wait = TRUE;
2350         } else {
2351                 scmd_printk(KERN_INFO, cmd, "Unable to deliver message\n");
2352                 retval = FAILED;
2353                 goto done;
2354         }
2355
2356 no_cmd:
2357         /*
2358          * Our assumption is that if we don't have the command, no
2359          * recovery action was required, so we return success.  Again,
2360          * the semantics of the mid-layer recovery engine are not
2361          * well defined, so this may change in time.
2362          */
2363         retval = SUCCESS;
2364 done:
2365         if (paused)
2366                 ahd_unpause(ahd);
2367         if (wait) {
2368                 struct timer_list timer;
2369                 int ret;
2370
2371                 ahd->platform_data->flags |= AHD_SCB_UP_EH_SEM;
2372                 ahd_unlock(ahd, &flags);
2373
2374                 init_timer(&timer);
2375                 timer.data = (u_long)ahd;
2376                 timer.expires = jiffies + (5 * HZ);
2377                 timer.function = ahd_linux_sem_timeout;
2378                 add_timer(&timer);
2379                 printf("%s: Recovery code sleeping\n", ahd_name(ahd));
2380                 down(&ahd->platform_data->eh_sem);
2381                 printf("%s: Recovery code awake\n", ahd_name(ahd));
2382                 ret = del_timer_sync(&timer);
2383                 if (ret == 0) {
2384                         printf("%s: Timer Expired (active %d)\n",
2385                                ahd_name(ahd), dev->active);
2386                         retval = FAILED;
2387                 }
2388         } else
2389                 ahd_unlock(ahd, &flags);
2390
2391         return (retval);
2392 }
2393
2394 static void ahd_linux_set_width(struct scsi_target *starget, int width)
2395 {
2396         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
2397         struct ahd_softc *ahd = *((struct ahd_softc **)shost->hostdata);
2398         struct ahd_devinfo devinfo;
2399         unsigned long flags;
2400
2401         ahd_compile_devinfo(&devinfo, shost->this_id, starget->id, 0,
2402                             starget->channel + 'A', ROLE_INITIATOR);
2403         ahd_lock(ahd, &flags);
2404         ahd_set_width(ahd, &devinfo, width, AHD_TRANS_GOAL, FALSE);
2405         ahd_unlock(ahd, &flags);
2406 }
2407
2408 static void ahd_linux_set_period(struct scsi_target *starget, int period)
2409 {
2410         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
2411         struct ahd_softc *ahd = *((struct ahd_softc **)shost->hostdata);
2412         struct ahd_tmode_tstate *tstate;
2413         struct ahd_initiator_tinfo *tinfo 
2414                 = ahd_fetch_transinfo(ahd,
2415                                       starget->channel + 'A',
2416                                       shost->this_id, starget->id, &tstate);
2417         struct ahd_devinfo devinfo;
2418         unsigned int ppr_options = tinfo->goal.ppr_options;
2419         unsigned int dt;
2420         unsigned long flags;
2421         unsigned long offset = tinfo->goal.offset;
2422
2423 #ifdef AHD_DEBUG
2424         if ((ahd_debug & AHD_SHOW_DV) != 0)
2425                 printf("%s: set period to %d\n", ahd_name(ahd), period);
2426 #endif
2427         if (offset == 0)
2428                 offset = MAX_OFFSET;
2429
2430         if (period < 8)
2431                 period = 8;
2432         if (period < 10) {
2433                 ppr_options |= MSG_EXT_PPR_DT_REQ;
2434                 if (period == 8)
2435                         ppr_options |= MSG_EXT_PPR_IU_REQ;
2436         }
2437
2438         dt = ppr_options & MSG_EXT_PPR_DT_REQ;
2439
2440         ahd_compile_devinfo(&devinfo, shost->this_id, starget->id, 0,
2441                             starget->channel + 'A', ROLE_INITIATOR);
2442
2443         /* all PPR requests apart from QAS require wide transfers */
2444         if (ppr_options & ~MSG_EXT_PPR_QAS_REQ) {
2445                 if (spi_width(starget) == 0)
2446                         ppr_options &= MSG_EXT_PPR_QAS_REQ;
2447         }
2448
2449         ahd_find_syncrate(ahd, &period, &ppr_options,
2450                           dt ? AHD_SYNCRATE_MAX : AHD_SYNCRATE_ULTRA2);
2451
2452         ahd_lock(ahd, &flags);
2453         ahd_set_syncrate(ahd, &devinfo, period, offset,
2454                          ppr_options, AHD_TRANS_GOAL, FALSE);
2455         ahd_unlock(ahd, &flags);
2456 }
2457
2458 static void ahd_linux_set_offset(struct scsi_target *starget, int offset)
2459 {
2460         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
2461         struct ahd_softc *ahd = *((struct ahd_softc **)shost->hostdata);
2462         struct ahd_tmode_tstate *tstate;
2463         struct ahd_initiator_tinfo *tinfo 
2464                 = ahd_fetch_transinfo(ahd,
2465                                       starget->channel + 'A',
2466                                       shost->this_id, starget->id, &tstate);
2467         struct ahd_devinfo devinfo;
2468         unsigned int ppr_options = 0;
2469         unsigned int period = 0;
2470         unsigned int dt = ppr_options & MSG_EXT_PPR_DT_REQ;
2471         unsigned long flags;
2472
2473 #ifdef AHD_DEBUG
2474         if ((ahd_debug & AHD_SHOW_DV) != 0)
2475                 printf("%s: set offset to %d\n", ahd_name(ahd), offset);
2476 #endif
2477
2478         ahd_compile_devinfo(&devinfo, shost->this_id, starget->id, 0,
2479                             starget->channel + 'A', ROLE_INITIATOR);
2480         if (offset != 0) {
2481                 period = tinfo->goal.period;
2482                 ppr_options = tinfo->goal.ppr_options;
2483                 ahd_find_syncrate(ahd, &period, &ppr_options, 
2484                                   dt ? AHD_SYNCRATE_MAX : AHD_SYNCRATE_ULTRA2);
2485         }
2486
2487         ahd_lock(ahd, &flags);
2488         ahd_set_syncrate(ahd, &devinfo, period, offset, ppr_options,
2489                          AHD_TRANS_GOAL, FALSE);
2490         ahd_unlock(ahd, &flags);
2491 }
2492
2493 static void ahd_linux_set_dt(struct scsi_target *starget, int dt)
2494 {
2495         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
2496         struct ahd_softc *ahd = *((struct ahd_softc **)shost->hostdata);
2497         struct ahd_tmode_tstate *tstate;
2498         struct ahd_initiator_tinfo *tinfo 
2499                 = ahd_fetch_transinfo(ahd,
2500                                       starget->channel + 'A',
2501                                       shost->this_id, starget->id, &tstate);
2502         struct ahd_devinfo devinfo;
2503         unsigned int ppr_options = tinfo->goal.ppr_options
2504                 & ~MSG_EXT_PPR_DT_REQ;
2505         unsigned int period = tinfo->goal.period;
2506         unsigned int width = tinfo->goal.width;
2507         unsigned long flags;
2508
2509 #ifdef AHD_DEBUG
2510         if ((ahd_debug & AHD_SHOW_DV) != 0)
2511                 printf("%s: %s DT\n", ahd_name(ahd), 
2512                        dt ? "enabling" : "disabling");
2513 #endif
2514         if (dt) {
2515                 ppr_options |= MSG_EXT_PPR_DT_REQ;
2516                 if (!width)
2517                         ahd_linux_set_width(starget, 1);
2518         } else {
2519                 if (period <= 9)
2520                         period = 10; /* If resetting DT, period must be >= 25ns */
2521                 /* IU is invalid without DT set */
2522                 ppr_options &= ~MSG_EXT_PPR_IU_REQ;
2523         }
2524         ahd_compile_devinfo(&devinfo, shost->this_id, starget->id, 0,
2525                             starget->channel + 'A', ROLE_INITIATOR);
2526         ahd_find_syncrate(ahd, &period, &ppr_options,
2527                           dt ? AHD_SYNCRATE_MAX : AHD_SYNCRATE_ULTRA2);
2528
2529         ahd_lock(ahd, &flags);
2530         ahd_set_syncrate(ahd, &devinfo, period, tinfo->goal.offset,
2531                          ppr_options, AHD_TRANS_GOAL, FALSE);
2532         ahd_unlock(ahd, &flags);
2533 }
2534
2535 static void ahd_linux_set_qas(struct scsi_target *starget, int qas)
2536 {
2537         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
2538         struct ahd_softc *ahd = *((struct ahd_softc **)shost->hostdata);
2539         struct ahd_tmode_tstate *tstate;
2540         struct ahd_initiator_tinfo *tinfo 
2541                 = ahd_fetch_transinfo(ahd,
2542                                       starget->channel + 'A',
2543                                       shost->this_id, starget->id, &tstate);
2544         struct ahd_devinfo devinfo;
2545         unsigned int ppr_options = tinfo->goal.ppr_options
2546                 & ~MSG_EXT_PPR_QAS_REQ;
2547         unsigned int period = tinfo->goal.period;
2548         unsigned int dt;
2549         unsigned long flags;
2550
2551 #ifdef AHD_DEBUG
2552         if ((ahd_debug & AHD_SHOW_DV) != 0)
2553                 printf("%s: %s QAS\n", ahd_name(ahd), 
2554                        qas ? "enabling" : "disabling");
2555 #endif
2556
2557         if (qas) {
2558                 ppr_options |= MSG_EXT_PPR_QAS_REQ; 
2559         }
2560
2561         dt = ppr_options & MSG_EXT_PPR_DT_REQ;
2562
2563         ahd_compile_devinfo(&devinfo, shost->this_id, starget->id, 0,
2564                             starget->channel + 'A', ROLE_INITIATOR);
2565         ahd_find_syncrate(ahd, &period, &ppr_options,
2566                           dt ? AHD_SYNCRATE_MAX : AHD_SYNCRATE_ULTRA2);
2567
2568         ahd_lock(ahd, &flags);
2569         ahd_set_syncrate(ahd, &devinfo, period, tinfo->goal.offset,
2570                          ppr_options, AHD_TRANS_GOAL, FALSE);
2571         ahd_unlock(ahd, &flags);
2572 }
2573
2574 static void ahd_linux_set_iu(struct scsi_target *starget, int iu)
2575 {
2576         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
2577         struct ahd_softc *ahd = *((struct ahd_softc **)shost->hostdata);
2578         struct ahd_tmode_tstate *tstate;
2579         struct ahd_initiator_tinfo *tinfo 
2580                 = ahd_fetch_transinfo(ahd,
2581                                       starget->channel + 'A',
2582                                       shost->this_id, starget->id, &tstate);
2583         struct ahd_devinfo devinfo;
2584         unsigned int ppr_options = tinfo->goal.ppr_options
2585                 & ~MSG_EXT_PPR_IU_REQ;
2586         unsigned int period = tinfo->goal.period;
2587         unsigned int dt;
2588         unsigned long flags;
2589
2590 #ifdef AHD_DEBUG
2591         if ((ahd_debug & AHD_SHOW_DV) != 0)
2592                 printf("%s: %s IU\n", ahd_name(ahd),
2593                        iu ? "enabling" : "disabling");
2594 #endif
2595
2596         if (iu) {
2597                 ppr_options |= MSG_EXT_PPR_IU_REQ;
2598                 ppr_options |= MSG_EXT_PPR_DT_REQ; /* IU requires DT */
2599         }
2600
2601         dt = ppr_options & MSG_EXT_PPR_DT_REQ;
2602
2603         ahd_compile_devinfo(&devinfo, shost->this_id, starget->id, 0,
2604                             starget->channel + 'A', ROLE_INITIATOR);
2605         ahd_find_syncrate(ahd, &period, &ppr_options,
2606                           dt ? AHD_SYNCRATE_MAX : AHD_SYNCRATE_ULTRA2);
2607
2608         ahd_lock(ahd, &flags);
2609         ahd_set_syncrate(ahd, &devinfo, period, tinfo->goal.offset,
2610                          ppr_options, AHD_TRANS_GOAL, FALSE);
2611         ahd_unlock(ahd, &flags);
2612 }
2613
2614 static void ahd_linux_set_rd_strm(struct scsi_target *starget, int rdstrm)
2615 {
2616         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
2617         struct ahd_softc *ahd = *((struct ahd_softc **)shost->hostdata);
2618         struct ahd_tmode_tstate *tstate;
2619         struct ahd_initiator_tinfo *tinfo 
2620                 = ahd_fetch_transinfo(ahd,
2621                                       starget->channel + 'A',
2622                                       shost->this_id, starget->id, &tstate);
2623         struct ahd_devinfo devinfo;
2624         unsigned int ppr_options = tinfo->goal.ppr_options
2625                 & ~MSG_EXT_PPR_RD_STRM;
2626         unsigned int period = tinfo->goal.period;
2627         unsigned int dt = ppr_options & MSG_EXT_PPR_DT_REQ;
2628         unsigned long flags;
2629
2630 #ifdef AHD_DEBUG
2631         if ((ahd_debug & AHD_SHOW_DV) != 0)
2632                 printf("%s: %s Read Streaming\n", ahd_name(ahd), 
2633                        rdstrm  ? "enabling" : "disabling");
2634 #endif
2635
2636         if (rdstrm)
2637                 ppr_options |= MSG_EXT_PPR_RD_STRM;
2638
2639         ahd_compile_devinfo(&devinfo, shost->this_id, starget->id, 0,
2640                             starget->channel + 'A', ROLE_INITIATOR);
2641         ahd_find_syncrate(ahd, &period, &ppr_options,
2642                           dt ? AHD_SYNCRATE_MAX : AHD_SYNCRATE_ULTRA2);
2643
2644         ahd_lock(ahd, &flags);
2645         ahd_set_syncrate(ahd, &devinfo, period, tinfo->goal.offset,
2646                          ppr_options, AHD_TRANS_GOAL, FALSE);
2647         ahd_unlock(ahd, &flags);
2648 }
2649
2650 static void ahd_linux_set_wr_flow(struct scsi_target *starget, int wrflow)
2651 {
2652         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
2653         struct ahd_softc *ahd = *((struct ahd_softc **)shost->hostdata);
2654         struct ahd_tmode_tstate *tstate;
2655         struct ahd_initiator_tinfo *tinfo 
2656                 = ahd_fetch_transinfo(ahd,
2657                                       starget->channel + 'A',
2658                                       shost->this_id, starget->id, &tstate);
2659         struct ahd_devinfo devinfo;
2660         unsigned int ppr_options = tinfo->goal.ppr_options
2661                 & ~MSG_EXT_PPR_WR_FLOW;
2662         unsigned int period = tinfo->goal.period;
2663         unsigned int dt = ppr_options & MSG_EXT_PPR_DT_REQ;
2664         unsigned long flags;
2665
2666 #ifdef AHD_DEBUG
2667         if ((ahd_debug & AHD_SHOW_DV) != 0)
2668                 printf("%s: %s Write Flow Control\n", ahd_name(ahd),
2669                        wrflow ? "enabling" : "disabling");
2670 #endif
2671
2672         if (wrflow)
2673                 ppr_options |= MSG_EXT_PPR_WR_FLOW;
2674
2675         ahd_compile_devinfo(&devinfo, shost->this_id, starget->id, 0,
2676                             starget->channel + 'A', ROLE_INITIATOR);
2677         ahd_find_syncrate(ahd, &period, &ppr_options,
2678                           dt ? AHD_SYNCRATE_MAX : AHD_SYNCRATE_ULTRA2);
2679
2680         ahd_lock(ahd, &flags);
2681         ahd_set_syncrate(ahd, &devinfo, period, tinfo->goal.offset,
2682                          ppr_options, AHD_TRANS_GOAL, FALSE);
2683         ahd_unlock(ahd, &flags);
2684 }
2685
2686 static void ahd_linux_set_rti(struct scsi_target *starget, int rti)
2687 {
2688         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
2689         struct ahd_softc *ahd = *((struct ahd_softc **)shost->hostdata);
2690         struct ahd_tmode_tstate *tstate;
2691         struct ahd_initiator_tinfo *tinfo 
2692                 = ahd_fetch_transinfo(ahd,
2693                                       starget->channel + 'A',
2694                                       shost->this_id, starget->id, &tstate);
2695         struct ahd_devinfo devinfo;
2696         unsigned int ppr_options = tinfo->goal.ppr_options
2697                 & ~MSG_EXT_PPR_RTI;
2698         unsigned int period = tinfo->goal.period;
2699         unsigned int dt = ppr_options & MSG_EXT_PPR_DT_REQ;
2700         unsigned long flags;
2701
2702         if ((ahd->features & AHD_RTI) == 0) {
2703 #ifdef AHD_DEBUG
2704                 if ((ahd_debug & AHD_SHOW_DV) != 0)
2705                         printf("%s: RTI not available\n", ahd_name(ahd));
2706 #endif
2707                 return;
2708         }
2709
2710 #ifdef AHD_DEBUG
2711         if ((ahd_debug & AHD_SHOW_DV) != 0)
2712                 printf("%s: %s RTI\n", ahd_name(ahd),
2713                        rti ? "enabling" : "disabling");
2714 #endif
2715
2716         if (rti)
2717                 ppr_options |= MSG_EXT_PPR_RTI;
2718
2719         ahd_compile_devinfo(&devinfo, shost->this_id, starget->id, 0,
2720                             starget->channel + 'A', ROLE_INITIATOR);
2721         ahd_find_syncrate(ahd, &period, &ppr_options,
2722                           dt ? AHD_SYNCRATE_MAX : AHD_SYNCRATE_ULTRA2);
2723
2724         ahd_lock(ahd, &flags);
2725         ahd_set_syncrate(ahd, &devinfo, period, tinfo->goal.offset,
2726                          ppr_options, AHD_TRANS_GOAL, FALSE);
2727         ahd_unlock(ahd, &flags);
2728 }
2729
2730 static void ahd_linux_set_pcomp_en(struct scsi_target *starget, int pcomp)
2731 {
2732         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
2733         struct ahd_softc *ahd = *((struct ahd_softc **)shost->hostdata);
2734         struct ahd_tmode_tstate *tstate;
2735         struct ahd_initiator_tinfo *tinfo 
2736                 = ahd_fetch_transinfo(ahd,
2737                                       starget->channel + 'A',
2738                                       shost->this_id, starget->id, &tstate);
2739         struct ahd_devinfo devinfo;
2740         unsigned int ppr_options = tinfo->goal.ppr_options
2741                 & ~MSG_EXT_PPR_PCOMP_EN;
2742         unsigned int period = tinfo->goal.period;
2743         unsigned int dt = ppr_options & MSG_EXT_PPR_DT_REQ;
2744         unsigned long flags;
2745
2746 #ifdef AHD_DEBUG
2747         if ((ahd_debug & AHD_SHOW_DV) != 0)
2748                 printf("%s: %s Precompensation\n", ahd_name(ahd), 
2749                        pcomp ? "Enable" : "Disable");
2750 #endif
2751
2752         if (pcomp)
2753                 ppr_options |= MSG_EXT_PPR_PCOMP_EN;
2754
2755         ahd_compile_devinfo(&devinfo, shost->this_id, starget->id, 0,
2756                             starget->channel + 'A', ROLE_INITIATOR);
2757         ahd_find_syncrate(ahd, &period, &ppr_options,
2758                           dt ? AHD_SYNCRATE_MAX : AHD_SYNCRATE_ULTRA2);
2759
2760         ahd_lock(ahd, &flags);
2761         ahd_set_syncrate(ahd, &devinfo, period, tinfo->goal.offset,
2762                          ppr_options, AHD_TRANS_GOAL, FALSE);
2763         ahd_unlock(ahd, &flags);
2764 }
2765
2766 static void ahd_linux_set_hold_mcs(struct scsi_target *starget, int hold)
2767 {
2768         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
2769         struct ahd_softc *ahd = *((struct ahd_softc **)shost->hostdata);
2770         struct ahd_tmode_tstate *tstate;
2771         struct ahd_initiator_tinfo *tinfo 
2772                 = ahd_fetch_transinfo(ahd,
2773                                       starget->channel + 'A',
2774                                       shost->this_id, starget->id, &tstate);
2775         struct ahd_devinfo devinfo;
2776         unsigned int ppr_options = tinfo->goal.ppr_options
2777                 & ~MSG_EXT_PPR_HOLD_MCS;
2778         unsigned int period = tinfo->goal.period;
2779         unsigned int dt = ppr_options & MSG_EXT_PPR_DT_REQ;
2780         unsigned long flags;
2781
2782         if (hold)
2783                 ppr_options |= MSG_EXT_PPR_HOLD_MCS;
2784
2785         ahd_compile_devinfo(&devinfo, shost->this_id, starget->id, 0,
2786                             starget->channel + 'A', ROLE_INITIATOR);
2787         ahd_find_syncrate(ahd, &period, &ppr_options,
2788                           dt ? AHD_SYNCRATE_MAX : AHD_SYNCRATE_ULTRA2);
2789
2790         ahd_lock(ahd, &flags);
2791         ahd_set_syncrate(ahd, &devinfo, period, tinfo->goal.offset,
2792                          ppr_options, AHD_TRANS_GOAL, FALSE);
2793         ahd_unlock(ahd, &flags);
2794 }
2795
2796
2797
2798 static struct spi_function_template ahd_linux_transport_functions = {
2799         .set_offset     = ahd_linux_set_offset,
2800         .show_offset    = 1,
2801         .set_period     = ahd_linux_set_period,
2802         .show_period    = 1,
2803         .set_width      = ahd_linux_set_width,
2804         .show_width     = 1,
2805         .set_dt         = ahd_linux_set_dt,
2806         .show_dt        = 1,
2807         .set_iu         = ahd_linux_set_iu,
2808         .show_iu        = 1,
2809         .set_qas        = ahd_linux_set_qas,
2810         .show_qas       = 1,
2811         .set_rd_strm    = ahd_linux_set_rd_strm,
2812         .show_rd_strm   = 1,
2813         .set_wr_flow    = ahd_linux_set_wr_flow,
2814         .show_wr_flow   = 1,
2815         .set_rti        = ahd_linux_set_rti,
2816         .show_rti       = 1,
2817         .set_pcomp_en   = ahd_linux_set_pcomp_en,
2818         .show_pcomp_en  = 1,
2819         .set_hold_mcs   = ahd_linux_set_hold_mcs,
2820         .show_hold_mcs  = 1,
2821 };
2822
2823 static int __init
2824 ahd_linux_init(void)
2825 {
2826         int     error = 0;
2827
2828         /*
2829          * If we've been passed any parameters, process them now.
2830          */
2831         if (aic79xx)
2832                 aic79xx_setup(aic79xx);
2833
2834         ahd_linux_transport_template =
2835                 spi_attach_transport(&ahd_linux_transport_functions);
2836         if (!ahd_linux_transport_template)
2837                 return -ENODEV;
2838
2839         scsi_transport_reserve_target(ahd_linux_transport_template,
2840                                       sizeof(struct ahd_linux_target));
2841         scsi_transport_reserve_device(ahd_linux_transport_template,
2842                                       sizeof(struct ahd_linux_device));
2843
2844         error = ahd_linux_pci_init();
2845         if (error)
2846                 spi_release_transport(ahd_linux_transport_template);
2847         return error;
2848 }
2849
2850 static void __exit
2851 ahd_linux_exit(void)
2852 {
2853         ahd_linux_pci_exit();
2854         spi_release_transport(ahd_linux_transport_template);
2855 }
2856
2857 module_init(ahd_linux_init);
2858 module_exit(ahd_linux_exit);