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