Merge master.kernel.org:/pub/scm/linux/kernel/git/dwmw2/audit-2.6
[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                 if (ahd->platform_data->host != NULL) {
1196                         scsi_remove_host(ahd->platform_data->host);
1197                         scsi_host_put(ahd->platform_data->host);
1198                 }
1199
1200                 /* destroy all of the device and target objects */
1201                 for (i = 0; i < AHD_NUM_TARGETS; i++) {
1202                         starget = ahd->platform_data->starget[i];
1203                         if (starget != NULL) {
1204                                 for (j = 0; j < AHD_NUM_LUNS; j++) {
1205                                         struct ahd_linux_target *targ =
1206                                                 scsi_transport_target_data(starget);
1207                                         if (targ->sdev[j] == NULL)
1208                                                 continue;
1209                                         targ->sdev[j] = NULL;
1210                                 }
1211                                 ahd->platform_data->starget[i] = NULL;
1212                         }
1213                 }
1214
1215                 if (ahd->platform_data->irq != AHD_LINUX_NOIRQ)
1216                         free_irq(ahd->platform_data->irq, ahd);
1217                 if (ahd->tags[0] == BUS_SPACE_PIO
1218                  && ahd->bshs[0].ioport != 0)
1219                         release_region(ahd->bshs[0].ioport, 256);
1220                 if (ahd->tags[1] == BUS_SPACE_PIO
1221                  && ahd->bshs[1].ioport != 0)
1222                         release_region(ahd->bshs[1].ioport, 256);
1223                 if (ahd->tags[0] == BUS_SPACE_MEMIO
1224                  && ahd->bshs[0].maddr != NULL) {
1225                         iounmap(ahd->bshs[0].maddr);
1226                         release_mem_region(ahd->platform_data->mem_busaddr,
1227                                            0x1000);
1228                 }
1229                 free(ahd->platform_data, M_DEVBUF);
1230         }
1231 }
1232
1233 void
1234 ahd_platform_init(struct ahd_softc *ahd)
1235 {
1236         /*
1237          * Lookup and commit any modified IO Cell options.
1238          */
1239         if (ahd->unit < NUM_ELEMENTS(aic79xx_iocell_info)) {
1240                 struct ahd_linux_iocell_opts *iocell_opts;
1241
1242                 iocell_opts = &aic79xx_iocell_info[ahd->unit];
1243                 if (iocell_opts->precomp != AIC79XX_DEFAULT_PRECOMP)
1244                         AHD_SET_PRECOMP(ahd, iocell_opts->precomp);
1245                 if (iocell_opts->slewrate != AIC79XX_DEFAULT_SLEWRATE)
1246                         AHD_SET_SLEWRATE(ahd, iocell_opts->slewrate);
1247                 if (iocell_opts->amplitude != AIC79XX_DEFAULT_AMPLITUDE)
1248                         AHD_SET_AMPLITUDE(ahd, iocell_opts->amplitude);
1249         }
1250
1251 }
1252
1253 void
1254 ahd_platform_freeze_devq(struct ahd_softc *ahd, struct scb *scb)
1255 {
1256         ahd_platform_abort_scbs(ahd, SCB_GET_TARGET(ahd, scb),
1257                                 SCB_GET_CHANNEL(ahd, scb),
1258                                 SCB_GET_LUN(scb), SCB_LIST_NULL,
1259                                 ROLE_UNKNOWN, CAM_REQUEUE_REQ);
1260 }
1261
1262 void
1263 ahd_platform_set_tags(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
1264                       ahd_queue_alg alg)
1265 {
1266         struct scsi_target *starget;
1267         struct ahd_linux_target *targ;
1268         struct ahd_linux_device *dev;
1269         struct scsi_device *sdev;
1270         int was_queuing;
1271         int now_queuing;
1272
1273         starget = ahd->platform_data->starget[devinfo->target];
1274         targ = scsi_transport_target_data(starget);
1275         BUG_ON(targ == NULL);
1276         sdev = targ->sdev[devinfo->lun];
1277         if (sdev == NULL)
1278                 return;
1279
1280         dev = scsi_transport_device_data(sdev);
1281
1282         if (dev == NULL)
1283                 return;
1284         was_queuing = dev->flags & (AHD_DEV_Q_BASIC|AHD_DEV_Q_TAGGED);
1285         switch (alg) {
1286         default:
1287         case AHD_QUEUE_NONE:
1288                 now_queuing = 0;
1289                 break; 
1290         case AHD_QUEUE_BASIC:
1291                 now_queuing = AHD_DEV_Q_BASIC;
1292                 break;
1293         case AHD_QUEUE_TAGGED:
1294                 now_queuing = AHD_DEV_Q_TAGGED;
1295                 break;
1296         }
1297         if ((dev->flags & AHD_DEV_FREEZE_TIL_EMPTY) == 0
1298          && (was_queuing != now_queuing)
1299          && (dev->active != 0)) {
1300                 dev->flags |= AHD_DEV_FREEZE_TIL_EMPTY;
1301                 dev->qfrozen++;
1302         }
1303
1304         dev->flags &= ~(AHD_DEV_Q_BASIC|AHD_DEV_Q_TAGGED|AHD_DEV_PERIODIC_OTAG);
1305         if (now_queuing) {
1306                 u_int usertags;
1307
1308                 usertags = ahd_linux_user_tagdepth(ahd, devinfo);
1309                 if (!was_queuing) {
1310                         /*
1311                          * Start out agressively and allow our
1312                          * dynamic queue depth algorithm to take
1313                          * care of the rest.
1314                          */
1315                         dev->maxtags = usertags;
1316                         dev->openings = dev->maxtags - dev->active;
1317                 }
1318                 if (dev->maxtags == 0) {
1319                         /*
1320                          * Queueing is disabled by the user.
1321                          */
1322                         dev->openings = 1;
1323                 } else if (alg == AHD_QUEUE_TAGGED) {
1324                         dev->flags |= AHD_DEV_Q_TAGGED;
1325                         if (aic79xx_periodic_otag != 0)
1326                                 dev->flags |= AHD_DEV_PERIODIC_OTAG;
1327                 } else
1328                         dev->flags |= AHD_DEV_Q_BASIC;
1329         } else {
1330                 /* We can only have one opening. */
1331                 dev->maxtags = 0;
1332                 dev->openings =  1 - dev->active;
1333         }
1334
1335         switch ((dev->flags & (AHD_DEV_Q_BASIC|AHD_DEV_Q_TAGGED))) {
1336         case AHD_DEV_Q_BASIC:
1337                 scsi_adjust_queue_depth(sdev,
1338                                         MSG_SIMPLE_TASK,
1339                                         dev->openings + dev->active);
1340                 break;
1341         case AHD_DEV_Q_TAGGED:
1342                 scsi_adjust_queue_depth(sdev,
1343                                         MSG_ORDERED_TASK,
1344                                         dev->openings + dev->active);
1345                 break;
1346         default:
1347                 /*
1348                  * We allow the OS to queue 2 untagged transactions to
1349                  * us at any time even though we can only execute them
1350                  * serially on the controller/device.  This should
1351                  * remove some latency.
1352                  */
1353                 scsi_adjust_queue_depth(sdev,
1354                                         /*NON-TAGGED*/0,
1355                                         /*queue depth*/2);
1356                 break;
1357         }
1358 }
1359
1360 int
1361 ahd_platform_abort_scbs(struct ahd_softc *ahd, int target, char channel,
1362                         int lun, u_int tag, role_t role, uint32_t status)
1363 {
1364         return 0;
1365 }
1366
1367 static u_int
1368 ahd_linux_user_tagdepth(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
1369 {
1370         static int warned_user;
1371         u_int tags;
1372
1373         tags = 0;
1374         if ((ahd->user_discenable & devinfo->target_mask) != 0) {
1375                 if (ahd->unit >= NUM_ELEMENTS(aic79xx_tag_info)) {
1376
1377                         if (warned_user == 0) {
1378                                 printf(KERN_WARNING
1379 "aic79xx: WARNING: Insufficient tag_info instances\n"
1380 "aic79xx: for installed controllers.  Using defaults\n"
1381 "aic79xx: Please update the aic79xx_tag_info array in\n"
1382 "aic79xx: the aic79xx_osm.c source file.\n");
1383                                 warned_user++;
1384                         }
1385                         tags = AHD_MAX_QUEUE;
1386                 } else {
1387                         adapter_tag_info_t *tag_info;
1388
1389                         tag_info = &aic79xx_tag_info[ahd->unit];
1390                         tags = tag_info->tag_commands[devinfo->target_offset];
1391                         if (tags > AHD_MAX_QUEUE)
1392                                 tags = AHD_MAX_QUEUE;
1393                 }
1394         }
1395         return (tags);
1396 }
1397
1398 /*
1399  * Determines the queue depth for a given device.
1400  */
1401 static void
1402 ahd_linux_device_queue_depth(struct scsi_device *sdev)
1403 {
1404         struct  ahd_devinfo devinfo;
1405         u_int   tags;
1406         struct ahd_softc *ahd = *((struct ahd_softc **)sdev->host->hostdata);
1407
1408         ahd_compile_devinfo(&devinfo,
1409                             ahd->our_id,
1410                             sdev->sdev_target->id, sdev->lun,
1411                             sdev->sdev_target->channel == 0 ? 'A' : 'B',
1412                             ROLE_INITIATOR);
1413         tags = ahd_linux_user_tagdepth(ahd, &devinfo);
1414         if (tags != 0 && sdev->tagged_supported != 0) {
1415
1416                 ahd_set_tags(ahd, &devinfo, AHD_QUEUE_TAGGED);
1417                 ahd_print_devinfo(ahd, &devinfo);
1418                 printf("Tagged Queuing enabled.  Depth %d\n", tags);
1419         } else {
1420                 ahd_set_tags(ahd, &devinfo, AHD_QUEUE_NONE);
1421         }
1422 }
1423
1424 static int
1425 ahd_linux_run_command(struct ahd_softc *ahd, struct ahd_linux_device *dev,
1426                       struct scsi_cmnd *cmd)
1427 {
1428         struct   scb *scb;
1429         struct   hardware_scb *hscb;
1430         struct   ahd_initiator_tinfo *tinfo;
1431         struct   ahd_tmode_tstate *tstate;
1432         u_int    col_idx;
1433         uint16_t mask;
1434
1435         /*
1436          * Get an scb to use.
1437          */
1438         tinfo = ahd_fetch_transinfo(ahd, 'A', ahd->our_id,
1439                                     cmd->device->id, &tstate);
1440         if ((dev->flags & (AHD_DEV_Q_TAGGED|AHD_DEV_Q_BASIC)) == 0
1441          || (tinfo->curr.ppr_options & MSG_EXT_PPR_IU_REQ) != 0) {
1442                 col_idx = AHD_NEVER_COL_IDX;
1443         } else {
1444                 col_idx = AHD_BUILD_COL_IDX(cmd->device->id,
1445                                             cmd->device->lun);
1446         }
1447         if ((scb = ahd_get_scb(ahd, col_idx)) == NULL) {
1448                 ahd->flags |= AHD_RESOURCE_SHORTAGE;
1449                 return SCSI_MLQUEUE_HOST_BUSY;
1450         }
1451
1452         scb->io_ctx = cmd;
1453         scb->platform_data->dev = dev;
1454         hscb = scb->hscb;
1455         cmd->host_scribble = (char *)scb;
1456
1457         /*
1458          * Fill out basics of the HSCB.
1459          */
1460         hscb->control = 0;
1461         hscb->scsiid = BUILD_SCSIID(ahd, cmd);
1462         hscb->lun = cmd->device->lun;
1463         scb->hscb->task_management = 0;
1464         mask = SCB_GET_TARGET_MASK(ahd, scb);
1465
1466         if ((ahd->user_discenable & mask) != 0)
1467                 hscb->control |= DISCENB;
1468
1469         if ((tinfo->curr.ppr_options & MSG_EXT_PPR_IU_REQ) != 0)
1470                 scb->flags |= SCB_PACKETIZED;
1471
1472         if ((tstate->auto_negotiate & mask) != 0) {
1473                 scb->flags |= SCB_AUTO_NEGOTIATE;
1474                 scb->hscb->control |= MK_MESSAGE;
1475         }
1476
1477         if ((dev->flags & (AHD_DEV_Q_TAGGED|AHD_DEV_Q_BASIC)) != 0) {
1478                 int     msg_bytes;
1479                 uint8_t tag_msgs[2];
1480
1481                 msg_bytes = scsi_populate_tag_msg(cmd, tag_msgs);
1482                 if (msg_bytes && tag_msgs[0] != MSG_SIMPLE_TASK) {
1483                         hscb->control |= tag_msgs[0];
1484                         if (tag_msgs[0] == MSG_ORDERED_TASK)
1485                                 dev->commands_since_idle_or_otag = 0;
1486                 } else
1487                 if (dev->commands_since_idle_or_otag == AHD_OTAG_THRESH
1488                  && (dev->flags & AHD_DEV_Q_TAGGED) != 0) {
1489                         hscb->control |= MSG_ORDERED_TASK;
1490                         dev->commands_since_idle_or_otag = 0;
1491                 } else {
1492                         hscb->control |= MSG_SIMPLE_TASK;
1493                 }
1494         }
1495
1496         hscb->cdb_len = cmd->cmd_len;
1497         memcpy(hscb->shared_data.idata.cdb, cmd->cmnd, hscb->cdb_len);
1498
1499         scb->platform_data->xfer_len = 0;
1500         ahd_set_residual(scb, 0);
1501         ahd_set_sense_residual(scb, 0);
1502         scb->sg_count = 0;
1503         if (cmd->use_sg != 0) {
1504                 void    *sg;
1505                 struct   scatterlist *cur_seg;
1506                 u_int    nseg;
1507                 int      dir;
1508
1509                 cur_seg = (struct scatterlist *)cmd->request_buffer;
1510                 dir = cmd->sc_data_direction;
1511                 nseg = pci_map_sg(ahd->dev_softc, cur_seg,
1512                                   cmd->use_sg, dir);
1513                 scb->platform_data->xfer_len = 0;
1514                 for (sg = scb->sg_list; nseg > 0; nseg--, cur_seg++) {
1515                         dma_addr_t addr;
1516                         bus_size_t len;
1517
1518                         addr = sg_dma_address(cur_seg);
1519                         len = sg_dma_len(cur_seg);
1520                         scb->platform_data->xfer_len += len;
1521                         sg = ahd_sg_setup(ahd, scb, sg, addr, len,
1522                                           /*last*/nseg == 1);
1523                 }
1524         } else if (cmd->request_bufflen != 0) {
1525                 void *sg;
1526                 dma_addr_t addr;
1527                 int dir;
1528
1529                 sg = scb->sg_list;
1530                 dir = cmd->sc_data_direction;
1531                 addr = pci_map_single(ahd->dev_softc,
1532                                       cmd->request_buffer,
1533                                       cmd->request_bufflen, dir);
1534                 scb->platform_data->xfer_len = cmd->request_bufflen;
1535                 scb->platform_data->buf_busaddr = addr;
1536                 sg = ahd_sg_setup(ahd, scb, sg, addr,
1537                                   cmd->request_bufflen, /*last*/TRUE);
1538         }
1539
1540         LIST_INSERT_HEAD(&ahd->pending_scbs, scb, pending_links);
1541         dev->openings--;
1542         dev->active++;
1543         dev->commands_issued++;
1544
1545         if ((dev->flags & AHD_DEV_PERIODIC_OTAG) != 0)
1546                 dev->commands_since_idle_or_otag++;
1547         scb->flags |= SCB_ACTIVE;
1548         ahd_queue_scb(ahd, scb);
1549
1550         return 0;
1551 }
1552
1553 /*
1554  * SCSI controller interrupt handler.
1555  */
1556 irqreturn_t
1557 ahd_linux_isr(int irq, void *dev_id, struct pt_regs * regs)
1558 {
1559         struct  ahd_softc *ahd;
1560         u_long  flags;
1561         int     ours;
1562
1563         ahd = (struct ahd_softc *) dev_id;
1564         ahd_lock(ahd, &flags); 
1565         ours = ahd_intr(ahd);
1566         ahd_unlock(ahd, &flags);
1567         return IRQ_RETVAL(ours);
1568 }
1569
1570 void
1571 ahd_platform_flushwork(struct ahd_softc *ahd)
1572 {
1573
1574 }
1575
1576 void
1577 ahd_send_async(struct ahd_softc *ahd, char channel,
1578                u_int target, u_int lun, ac_code code, void *arg)
1579 {
1580         switch (code) {
1581         case AC_TRANSFER_NEG:
1582         {
1583                 char    buf[80];
1584                 struct  scsi_target *starget;
1585                 struct  ahd_linux_target *targ;
1586                 struct  info_str info;
1587                 struct  ahd_initiator_tinfo *tinfo;
1588                 struct  ahd_tmode_tstate *tstate;
1589                 unsigned int target_ppr_options;
1590
1591                 BUG_ON(target == CAM_TARGET_WILDCARD);
1592
1593                 info.buffer = buf;
1594                 info.length = sizeof(buf);
1595                 info.offset = 0;
1596                 info.pos = 0;
1597                 tinfo = ahd_fetch_transinfo(ahd, channel, ahd->our_id,
1598                                             target, &tstate);
1599
1600                 /*
1601                  * Don't bother reporting results while
1602                  * negotiations are still pending.
1603                  */
1604                 if (tinfo->curr.period != tinfo->goal.period
1605                  || tinfo->curr.width != tinfo->goal.width
1606                  || tinfo->curr.offset != tinfo->goal.offset
1607                  || tinfo->curr.ppr_options != tinfo->goal.ppr_options)
1608                         if (bootverbose == 0)
1609                                 break;
1610
1611                 /*
1612                  * Don't bother reporting results that
1613                  * are identical to those last reported.
1614                  */
1615                 starget = ahd->platform_data->starget[target];
1616                 if (starget == NULL)
1617                         break;
1618                 targ = scsi_transport_target_data(starget);
1619
1620                 target_ppr_options =
1621                         (spi_dt(starget) ? MSG_EXT_PPR_DT_REQ : 0)
1622                         + (spi_qas(starget) ? MSG_EXT_PPR_QAS_REQ : 0)
1623                         + (spi_iu(starget) ?  MSG_EXT_PPR_IU_REQ : 0)
1624                         + (spi_rd_strm(starget) ? MSG_EXT_PPR_RD_STRM : 0)
1625                         + (spi_pcomp_en(starget) ? MSG_EXT_PPR_PCOMP_EN : 0)
1626                         + (spi_rti(starget) ? MSG_EXT_PPR_RTI : 0)
1627                         + (spi_wr_flow(starget) ? MSG_EXT_PPR_WR_FLOW : 0)
1628                         + (spi_hold_mcs(starget) ? MSG_EXT_PPR_HOLD_MCS : 0);
1629
1630                 if (tinfo->curr.period == spi_period(starget)
1631                     && tinfo->curr.width == spi_width(starget)
1632                     && tinfo->curr.offset == spi_offset(starget)
1633                  && tinfo->curr.ppr_options == target_ppr_options)
1634                         if (bootverbose == 0)
1635                                 break;
1636
1637                 spi_period(starget) = tinfo->curr.period;
1638                 spi_width(starget) = tinfo->curr.width;
1639                 spi_offset(starget) = tinfo->curr.offset;
1640                 spi_dt(starget) = tinfo->curr.ppr_options & MSG_EXT_PPR_DT_REQ ? 1 : 0;
1641                 spi_qas(starget) = tinfo->curr.ppr_options & MSG_EXT_PPR_QAS_REQ ? 1 : 0;
1642                 spi_iu(starget) = tinfo->curr.ppr_options & MSG_EXT_PPR_IU_REQ ? 1 : 0;
1643                 spi_rd_strm(starget) = tinfo->curr.ppr_options & MSG_EXT_PPR_RD_STRM ? 1 : 0;
1644                 spi_pcomp_en(starget) =  tinfo->curr.ppr_options & MSG_EXT_PPR_PCOMP_EN ? 1 : 0;
1645                 spi_rti(starget) =  tinfo->curr.ppr_options &  MSG_EXT_PPR_RTI ? 1 : 0;
1646                 spi_wr_flow(starget) = tinfo->curr.ppr_options & MSG_EXT_PPR_WR_FLOW ? 1 : 0;
1647                 spi_hold_mcs(starget) = tinfo->curr.ppr_options & MSG_EXT_PPR_HOLD_MCS ? 1 : 0;
1648                 spi_display_xfer_agreement(starget);
1649                 break;
1650         }
1651         case AC_SENT_BDR:
1652         {
1653                 WARN_ON(lun != CAM_LUN_WILDCARD);
1654                 scsi_report_device_reset(ahd->platform_data->host,
1655                                          channel - 'A', target);
1656                 break;
1657         }
1658         case AC_BUS_RESET:
1659                 if (ahd->platform_data->host != NULL) {
1660                         scsi_report_bus_reset(ahd->platform_data->host,
1661                                               channel - 'A');
1662                 }
1663                 break;
1664         default:
1665                 panic("ahd_send_async: Unexpected async event");
1666         }
1667 }
1668
1669 /*
1670  * Calls the higher level scsi done function and frees the scb.
1671  */
1672 void
1673 ahd_done(struct ahd_softc *ahd, struct scb *scb)
1674 {
1675         struct scsi_cmnd *cmd;
1676         struct    ahd_linux_device *dev;
1677
1678         if ((scb->flags & SCB_ACTIVE) == 0) {
1679                 printf("SCB %d done'd twice\n", SCB_GET_TAG(scb));
1680                 ahd_dump_card_state(ahd);
1681                 panic("Stopping for safety");
1682         }
1683         LIST_REMOVE(scb, pending_links);
1684         cmd = scb->io_ctx;
1685         dev = scb->platform_data->dev;
1686         dev->active--;
1687         dev->openings++;
1688         if ((cmd->result & (CAM_DEV_QFRZN << 16)) != 0) {
1689                 cmd->result &= ~(CAM_DEV_QFRZN << 16);
1690                 dev->qfrozen--;
1691         }
1692         ahd_linux_unmap_scb(ahd, scb);
1693
1694         /*
1695          * Guard against stale sense data.
1696          * The Linux mid-layer assumes that sense
1697          * was retrieved anytime the first byte of
1698          * the sense buffer looks "sane".
1699          */
1700         cmd->sense_buffer[0] = 0;
1701         if (ahd_get_transaction_status(scb) == CAM_REQ_INPROG) {
1702                 uint32_t amount_xferred;
1703
1704                 amount_xferred =
1705                     ahd_get_transfer_length(scb) - ahd_get_residual(scb);
1706                 if ((scb->flags & SCB_TRANSMISSION_ERROR) != 0) {
1707 #ifdef AHD_DEBUG
1708                         if ((ahd_debug & AHD_SHOW_MISC) != 0) {
1709                                 ahd_print_path(ahd, scb);
1710                                 printf("Set CAM_UNCOR_PARITY\n");
1711                         }
1712 #endif
1713                         ahd_set_transaction_status(scb, CAM_UNCOR_PARITY);
1714 #ifdef AHD_REPORT_UNDERFLOWS
1715                 /*
1716                  * This code is disabled by default as some
1717                  * clients of the SCSI system do not properly
1718                  * initialize the underflow parameter.  This
1719                  * results in spurious termination of commands
1720                  * that complete as expected (e.g. underflow is
1721                  * allowed as command can return variable amounts
1722                  * of data.
1723                  */
1724                 } else if (amount_xferred < scb->io_ctx->underflow) {
1725                         u_int i;
1726
1727                         ahd_print_path(ahd, scb);
1728                         printf("CDB:");
1729                         for (i = 0; i < scb->io_ctx->cmd_len; i++)
1730                                 printf(" 0x%x", scb->io_ctx->cmnd[i]);
1731                         printf("\n");
1732                         ahd_print_path(ahd, scb);
1733                         printf("Saw underflow (%ld of %ld bytes). "
1734                                "Treated as error\n",
1735                                 ahd_get_residual(scb),
1736                                 ahd_get_transfer_length(scb));
1737                         ahd_set_transaction_status(scb, CAM_DATA_RUN_ERR);
1738 #endif
1739                 } else {
1740                         ahd_set_transaction_status(scb, CAM_REQ_CMP);
1741                 }
1742         } else if (ahd_get_transaction_status(scb) == CAM_SCSI_STATUS_ERROR) {
1743                 ahd_linux_handle_scsi_status(ahd, cmd->device, scb);
1744         }
1745
1746         if (dev->openings == 1
1747          && ahd_get_transaction_status(scb) == CAM_REQ_CMP
1748          && ahd_get_scsi_status(scb) != SCSI_STATUS_QUEUE_FULL)
1749                 dev->tag_success_count++;
1750         /*
1751          * Some devices deal with temporary internal resource
1752          * shortages by returning queue full.  When the queue
1753          * full occurrs, we throttle back.  Slowly try to get
1754          * back to our previous queue depth.
1755          */
1756         if ((dev->openings + dev->active) < dev->maxtags
1757          && dev->tag_success_count > AHD_TAG_SUCCESS_INTERVAL) {
1758                 dev->tag_success_count = 0;
1759                 dev->openings++;
1760         }
1761
1762         if (dev->active == 0)
1763                 dev->commands_since_idle_or_otag = 0;
1764
1765         if ((scb->flags & SCB_RECOVERY_SCB) != 0) {
1766                 printf("Recovery SCB completes\n");
1767                 if (ahd_get_transaction_status(scb) == CAM_BDR_SENT
1768                  || ahd_get_transaction_status(scb) == CAM_REQ_ABORTED)
1769                         ahd_set_transaction_status(scb, CAM_CMD_TIMEOUT);
1770                 if ((ahd->platform_data->flags & AHD_SCB_UP_EH_SEM) != 0) {
1771                         ahd->platform_data->flags &= ~AHD_SCB_UP_EH_SEM;
1772                         up(&ahd->platform_data->eh_sem);
1773                 }
1774         }
1775
1776         ahd_free_scb(ahd, scb);
1777         ahd_linux_queue_cmd_complete(ahd, cmd);
1778 }
1779
1780 static void
1781 ahd_linux_handle_scsi_status(struct ahd_softc *ahd,
1782                              struct scsi_device *sdev, struct scb *scb)
1783 {
1784         struct  ahd_devinfo devinfo;
1785         struct ahd_linux_device *dev = scsi_transport_device_data(sdev);
1786
1787         ahd_compile_devinfo(&devinfo,
1788                             ahd->our_id,
1789                             sdev->sdev_target->id, sdev->lun,
1790                             sdev->sdev_target->channel == 0 ? 'A' : 'B',
1791                             ROLE_INITIATOR);
1792         
1793         /*
1794          * We don't currently trust the mid-layer to
1795          * properly deal with queue full or busy.  So,
1796          * when one occurs, we tell the mid-layer to
1797          * unconditionally requeue the command to us
1798          * so that we can retry it ourselves.  We also
1799          * implement our own throttling mechanism so
1800          * we don't clobber the device with too many
1801          * commands.
1802          */
1803         switch (ahd_get_scsi_status(scb)) {
1804         default:
1805                 break;
1806         case SCSI_STATUS_CHECK_COND:
1807         case SCSI_STATUS_CMD_TERMINATED:
1808         {
1809                 struct scsi_cmnd *cmd;
1810
1811                 /*
1812                  * Copy sense information to the OS's cmd
1813                  * structure if it is available.
1814                  */
1815                 cmd = scb->io_ctx;
1816                 if ((scb->flags & (SCB_SENSE|SCB_PKT_SENSE)) != 0) {
1817                         struct scsi_status_iu_header *siu;
1818                         u_int sense_size;
1819                         u_int sense_offset;
1820
1821                         if (scb->flags & SCB_SENSE) {
1822                                 sense_size = MIN(sizeof(struct scsi_sense_data)
1823                                                - ahd_get_sense_residual(scb),
1824                                                  sizeof(cmd->sense_buffer));
1825                                 sense_offset = 0;
1826                         } else {
1827                                 /*
1828                                  * Copy only the sense data into the provided
1829                                  * buffer.
1830                                  */
1831                                 siu = (struct scsi_status_iu_header *)
1832                                     scb->sense_data;
1833                                 sense_size = MIN(scsi_4btoul(siu->sense_length),
1834                                                 sizeof(cmd->sense_buffer));
1835                                 sense_offset = SIU_SENSE_OFFSET(siu);
1836                         }
1837
1838                         memset(cmd->sense_buffer, 0, sizeof(cmd->sense_buffer));
1839                         memcpy(cmd->sense_buffer,
1840                                ahd_get_sense_buf(ahd, scb)
1841                                + sense_offset, sense_size);
1842                         cmd->result |= (DRIVER_SENSE << 24);
1843
1844 #ifdef AHD_DEBUG
1845                         if (ahd_debug & AHD_SHOW_SENSE) {
1846                                 int i;
1847
1848                                 printf("Copied %d bytes of sense data at %d:",
1849                                        sense_size, sense_offset);
1850                                 for (i = 0; i < sense_size; i++) {
1851                                         if ((i & 0xF) == 0)
1852                                                 printf("\n");
1853                                         printf("0x%x ", cmd->sense_buffer[i]);
1854                                 }
1855                                 printf("\n");
1856                         }
1857 #endif
1858                 }
1859                 break;
1860         }
1861         case SCSI_STATUS_QUEUE_FULL:
1862                 /*
1863                  * By the time the core driver has returned this
1864                  * command, all other commands that were queued
1865                  * to us but not the device have been returned.
1866                  * This ensures that dev->active is equal to
1867                  * the number of commands actually queued to
1868                  * the device.
1869                  */
1870                 dev->tag_success_count = 0;
1871                 if (dev->active != 0) {
1872                         /*
1873                          * Drop our opening count to the number
1874                          * of commands currently outstanding.
1875                          */
1876                         dev->openings = 0;
1877 #ifdef AHD_DEBUG
1878                         if ((ahd_debug & AHD_SHOW_QFULL) != 0) {
1879                                 ahd_print_path(ahd, scb);
1880                                 printf("Dropping tag count to %d\n",
1881                                        dev->active);
1882                         }
1883 #endif
1884                         if (dev->active == dev->tags_on_last_queuefull) {
1885
1886                                 dev->last_queuefull_same_count++;
1887                                 /*
1888                                  * If we repeatedly see a queue full
1889                                  * at the same queue depth, this
1890                                  * device has a fixed number of tag
1891                                  * slots.  Lock in this tag depth
1892                                  * so we stop seeing queue fulls from
1893                                  * this device.
1894                                  */
1895                                 if (dev->last_queuefull_same_count
1896                                  == AHD_LOCK_TAGS_COUNT) {
1897                                         dev->maxtags = dev->active;
1898                                         ahd_print_path(ahd, scb);
1899                                         printf("Locking max tag count at %d\n",
1900                                                dev->active);
1901                                 }
1902                         } else {
1903                                 dev->tags_on_last_queuefull = dev->active;
1904                                 dev->last_queuefull_same_count = 0;
1905                         }
1906                         ahd_set_transaction_status(scb, CAM_REQUEUE_REQ);
1907                         ahd_set_scsi_status(scb, SCSI_STATUS_OK);
1908                         ahd_platform_set_tags(ahd, &devinfo,
1909                                      (dev->flags & AHD_DEV_Q_BASIC)
1910                                    ? AHD_QUEUE_BASIC : AHD_QUEUE_TAGGED);
1911                         break;
1912                 }
1913                 /*
1914                  * Drop down to a single opening, and treat this
1915                  * as if the target returned BUSY SCSI status.
1916                  */
1917                 dev->openings = 1;
1918                 ahd_platform_set_tags(ahd, &devinfo,
1919                              (dev->flags & AHD_DEV_Q_BASIC)
1920                            ? AHD_QUEUE_BASIC : AHD_QUEUE_TAGGED);
1921                 ahd_set_scsi_status(scb, SCSI_STATUS_BUSY);
1922         }
1923 }
1924
1925 static void
1926 ahd_linux_queue_cmd_complete(struct ahd_softc *ahd, struct scsi_cmnd *cmd)
1927 {
1928         /*
1929          * Map CAM error codes into Linux Error codes.  We
1930          * avoid the conversion so that the DV code has the
1931          * full error information available when making
1932          * state change decisions.
1933          */
1934         {
1935                 uint32_t status;
1936                 u_int new_status;
1937
1938                 status = ahd_cmd_get_transaction_status(cmd);
1939                 switch (status) {
1940                 case CAM_REQ_INPROG:
1941                 case CAM_REQ_CMP:
1942                 case CAM_SCSI_STATUS_ERROR:
1943                         new_status = DID_OK;
1944                         break;
1945                 case CAM_REQ_ABORTED:
1946                         new_status = DID_ABORT;
1947                         break;
1948                 case CAM_BUSY:
1949                         new_status = DID_BUS_BUSY;
1950                         break;
1951                 case CAM_REQ_INVALID:
1952                 case CAM_PATH_INVALID:
1953                         new_status = DID_BAD_TARGET;
1954                         break;
1955                 case CAM_SEL_TIMEOUT:
1956                         new_status = DID_NO_CONNECT;
1957                         break;
1958                 case CAM_SCSI_BUS_RESET:
1959                 case CAM_BDR_SENT:
1960                         new_status = DID_RESET;
1961                         break;
1962                 case CAM_UNCOR_PARITY:
1963                         new_status = DID_PARITY;
1964                         break;
1965                 case CAM_CMD_TIMEOUT:
1966                         new_status = DID_TIME_OUT;
1967                         break;
1968                 case CAM_UA_ABORT:
1969                 case CAM_REQ_CMP_ERR:
1970                 case CAM_AUTOSENSE_FAIL:
1971                 case CAM_NO_HBA:
1972                 case CAM_DATA_RUN_ERR:
1973                 case CAM_UNEXP_BUSFREE:
1974                 case CAM_SEQUENCE_FAIL:
1975                 case CAM_CCB_LEN_ERR:
1976                 case CAM_PROVIDE_FAIL:
1977                 case CAM_REQ_TERMIO:
1978                 case CAM_UNREC_HBA_ERROR:
1979                 case CAM_REQ_TOO_BIG:
1980                         new_status = DID_ERROR;
1981                         break;
1982                 case CAM_REQUEUE_REQ:
1983                         new_status = DID_REQUEUE;
1984                         break;
1985                 default:
1986                         /* We should never get here */
1987                         new_status = DID_ERROR;
1988                         break;
1989                 }
1990
1991                 ahd_cmd_set_transaction_status(cmd, new_status);
1992         }
1993
1994         cmd->scsi_done(cmd);
1995 }
1996
1997 static void
1998 ahd_linux_sem_timeout(u_long arg)
1999 {
2000         struct  ahd_softc *ahd;
2001         u_long  s;
2002
2003         ahd = (struct ahd_softc *)arg;
2004
2005         ahd_lock(ahd, &s);
2006         if ((ahd->platform_data->flags & AHD_SCB_UP_EH_SEM) != 0) {
2007                 ahd->platform_data->flags &= ~AHD_SCB_UP_EH_SEM;
2008                 up(&ahd->platform_data->eh_sem);
2009         }
2010         ahd_unlock(ahd, &s);
2011 }
2012
2013 void
2014 ahd_freeze_simq(struct ahd_softc *ahd)
2015 {
2016         ahd->platform_data->qfrozen++;
2017         if (ahd->platform_data->qfrozen == 1) {
2018                 scsi_block_requests(ahd->platform_data->host);
2019                 ahd_platform_abort_scbs(ahd, CAM_TARGET_WILDCARD, ALL_CHANNELS,
2020                                         CAM_LUN_WILDCARD, SCB_LIST_NULL,
2021                                         ROLE_INITIATOR, CAM_REQUEUE_REQ);
2022         }
2023 }
2024
2025 void
2026 ahd_release_simq(struct ahd_softc *ahd)
2027 {
2028         u_long s;
2029         int    unblock_reqs;
2030
2031         unblock_reqs = 0;
2032         ahd_lock(ahd, &s);
2033         if (ahd->platform_data->qfrozen > 0)
2034                 ahd->platform_data->qfrozen--;
2035         if (ahd->platform_data->qfrozen == 0) {
2036                 unblock_reqs = 1;
2037         }
2038         ahd_unlock(ahd, &s);
2039         /*
2040          * There is still a race here.  The mid-layer
2041          * should keep its own freeze count and use
2042          * a bottom half handler to run the queues
2043          * so we can unblock with our own lock held.
2044          */
2045         if (unblock_reqs)
2046                 scsi_unblock_requests(ahd->platform_data->host);
2047 }
2048
2049 static int
2050 ahd_linux_queue_recovery_cmd(struct scsi_cmnd *cmd, scb_flag flag)
2051 {
2052         struct ahd_softc *ahd;
2053         struct ahd_linux_device *dev;
2054         struct scb *pending_scb;
2055         u_int  saved_scbptr;
2056         u_int  active_scbptr;
2057         u_int  last_phase;
2058         u_int  saved_scsiid;
2059         u_int  cdb_byte;
2060         int    retval;
2061         int    was_paused;
2062         int    paused;
2063         int    wait;
2064         int    disconnected;
2065         ahd_mode_state saved_modes;
2066
2067         pending_scb = NULL;
2068         paused = FALSE;
2069         wait = FALSE;
2070         ahd = *(struct ahd_softc **)cmd->device->host->hostdata;
2071
2072         printf("%s:%d:%d:%d: Attempting to queue a%s message:",
2073                ahd_name(ahd), cmd->device->channel,
2074                cmd->device->id, cmd->device->lun,
2075                flag == SCB_ABORT ? "n ABORT" : " TARGET RESET");
2076
2077         printf("CDB:");
2078         for (cdb_byte = 0; cdb_byte < cmd->cmd_len; cdb_byte++)
2079                 printf(" 0x%x", cmd->cmnd[cdb_byte]);
2080         printf("\n");
2081
2082         spin_lock_irq(&ahd->platform_data->spin_lock);
2083
2084         /*
2085          * First determine if we currently own this command.
2086          * Start by searching the device queue.  If not found
2087          * there, check the pending_scb list.  If not found
2088          * at all, and the system wanted us to just abort the
2089          * command, return success.
2090          */
2091         dev = scsi_transport_device_data(cmd->device);
2092
2093         if (dev == NULL) {
2094                 /*
2095                  * No target device for this command exists,
2096                  * so we must not still own the command.
2097                  */
2098                 printf("%s:%d:%d:%d: Is not an active device\n",
2099                        ahd_name(ahd), cmd->device->channel, cmd->device->id,
2100                        cmd->device->lun);
2101                 retval = SUCCESS;
2102                 goto no_cmd;
2103         }
2104
2105         /*
2106          * See if we can find a matching cmd in the pending list.
2107          */
2108         LIST_FOREACH(pending_scb, &ahd->pending_scbs, pending_links) {
2109                 if (pending_scb->io_ctx == cmd)
2110                         break;
2111         }
2112
2113         if (pending_scb == NULL && flag == SCB_DEVICE_RESET) {
2114
2115                 /* Any SCB for this device will do for a target reset */
2116                 LIST_FOREACH(pending_scb, &ahd->pending_scbs, pending_links) {
2117                         if (ahd_match_scb(ahd, pending_scb, cmd->device->id,
2118                                           cmd->device->channel + 'A',
2119                                           CAM_LUN_WILDCARD,
2120                                           SCB_LIST_NULL, ROLE_INITIATOR) == 0)
2121                                 break;
2122                 }
2123         }
2124
2125         if (pending_scb == NULL) {
2126                 printf("%s:%d:%d:%d: Command not found\n",
2127                        ahd_name(ahd), cmd->device->channel, cmd->device->id,
2128                        cmd->device->lun);
2129                 goto no_cmd;
2130         }
2131
2132         if ((pending_scb->flags & SCB_RECOVERY_SCB) != 0) {
2133                 /*
2134                  * We can't queue two recovery actions using the same SCB
2135                  */
2136                 retval = FAILED;
2137                 goto  done;
2138         }
2139
2140         /*
2141          * Ensure that the card doesn't do anything
2142          * behind our back.  Also make sure that we
2143          * didn't "just" miss an interrupt that would
2144          * affect this cmd.
2145          */
2146         was_paused = ahd_is_paused(ahd);
2147         ahd_pause_and_flushwork(ahd);
2148         paused = TRUE;
2149
2150         if ((pending_scb->flags & SCB_ACTIVE) == 0) {
2151                 printf("%s:%d:%d:%d: Command already completed\n",
2152                        ahd_name(ahd), cmd->device->channel, cmd->device->id,
2153                        cmd->device->lun);
2154                 goto no_cmd;
2155         }
2156
2157         printf("%s: At time of recovery, card was %spaused\n",
2158                ahd_name(ahd), was_paused ? "" : "not ");
2159         ahd_dump_card_state(ahd);
2160
2161         disconnected = TRUE;
2162         if (flag == SCB_ABORT) {
2163                 if (ahd_search_qinfifo(ahd, cmd->device->id, 
2164                                        cmd->device->channel + 'A',
2165                                        cmd->device->lun, 
2166                                        pending_scb->hscb->tag,
2167                                        ROLE_INITIATOR, CAM_REQ_ABORTED,
2168                                        SEARCH_COMPLETE) > 0) {
2169                         printf("%s:%d:%d:%d: Cmd aborted from QINFIFO\n",
2170                                ahd_name(ahd), cmd->device->channel, 
2171                                cmd->device->id, cmd->device->lun);
2172                         retval = SUCCESS;
2173                         goto done;
2174                 }
2175         } else if (ahd_search_qinfifo(ahd, cmd->device->id,
2176                                       cmd->device->channel + 'A',
2177                                       cmd->device->lun, pending_scb->hscb->tag,
2178                                       ROLE_INITIATOR, /*status*/0,
2179                                       SEARCH_COUNT) > 0) {
2180                 disconnected = FALSE;
2181         }
2182
2183         saved_modes = ahd_save_modes(ahd);
2184         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
2185         last_phase = ahd_inb(ahd, LASTPHASE);
2186         saved_scbptr = ahd_get_scbptr(ahd);
2187         active_scbptr = saved_scbptr;
2188         if (disconnected && (ahd_inb(ahd, SEQ_FLAGS) & NOT_IDENTIFIED) == 0) {
2189                 struct scb *bus_scb;
2190
2191                 bus_scb = ahd_lookup_scb(ahd, active_scbptr);
2192                 if (bus_scb == pending_scb)
2193                         disconnected = FALSE;
2194                 else if (flag != SCB_ABORT
2195                          && ahd_inb(ahd, SAVED_SCSIID) == pending_scb->hscb->scsiid
2196                          && ahd_inb(ahd, SAVED_LUN) == SCB_GET_LUN(pending_scb))
2197                         disconnected = FALSE;
2198         }
2199
2200         /*
2201          * At this point, pending_scb is the scb associated with the
2202          * passed in command.  That command is currently active on the
2203          * bus or is in the disconnected state.
2204          */
2205         saved_scsiid = ahd_inb(ahd, SAVED_SCSIID);
2206         if (last_phase != P_BUSFREE
2207          && (SCB_GET_TAG(pending_scb) == active_scbptr
2208              || (flag == SCB_DEVICE_RESET
2209                  && SCSIID_TARGET(ahd, saved_scsiid) == cmd->device->id))) {
2210
2211                 /*
2212                  * We're active on the bus, so assert ATN
2213                  * and hope that the target responds.
2214                  */
2215                 pending_scb = ahd_lookup_scb(ahd, active_scbptr);
2216                 pending_scb->flags |= SCB_RECOVERY_SCB|flag;
2217                 ahd_outb(ahd, MSG_OUT, HOST_MSG);
2218                 ahd_outb(ahd, SCSISIGO, last_phase|ATNO);
2219                 printf("%s:%d:%d:%d: Device is active, asserting ATN\n",
2220                        ahd_name(ahd), cmd->device->channel,
2221                        cmd->device->id, cmd->device->lun);
2222                 wait = TRUE;
2223         } else if (disconnected) {
2224
2225                 /*
2226                  * Actually re-queue this SCB in an attempt
2227                  * to select the device before it reconnects.
2228                  */
2229                 pending_scb->flags |= SCB_RECOVERY_SCB|SCB_ABORT;
2230                 ahd_set_scbptr(ahd, SCB_GET_TAG(pending_scb));
2231                 pending_scb->hscb->cdb_len = 0;
2232                 pending_scb->hscb->task_attribute = 0;
2233                 pending_scb->hscb->task_management = SIU_TASKMGMT_ABORT_TASK;
2234
2235                 if ((pending_scb->flags & SCB_PACKETIZED) != 0) {
2236                         /*
2237                          * Mark the SCB has having an outstanding
2238                          * task management function.  Should the command
2239                          * complete normally before the task management
2240                          * function can be sent, the host will be notified
2241                          * to abort our requeued SCB.
2242                          */
2243                         ahd_outb(ahd, SCB_TASK_MANAGEMENT,
2244                                  pending_scb->hscb->task_management);
2245                 } else {
2246                         /*
2247                          * If non-packetized, set the MK_MESSAGE control
2248                          * bit indicating that we desire to send a message.
2249                          * We also set the disconnected flag since there is
2250                          * no guarantee that our SCB control byte matches
2251                          * the version on the card.  We don't want the
2252                          * sequencer to abort the command thinking an
2253                          * unsolicited reselection occurred.
2254                          */
2255                         pending_scb->hscb->control |= MK_MESSAGE|DISCONNECTED;
2256
2257                         /*
2258                          * The sequencer will never re-reference the
2259                          * in-core SCB.  To make sure we are notified
2260                          * during reslection, set the MK_MESSAGE flag in
2261                          * the card's copy of the SCB.
2262                          */
2263                         ahd_outb(ahd, SCB_CONTROL,
2264                                  ahd_inb(ahd, SCB_CONTROL)|MK_MESSAGE);
2265                 }
2266
2267                 /*
2268                  * Clear out any entries in the QINFIFO first
2269                  * so we are the next SCB for this target
2270                  * to run.
2271                  */
2272                 ahd_search_qinfifo(ahd, cmd->device->id,
2273                                    cmd->device->channel + 'A', cmd->device->lun,
2274                                    SCB_LIST_NULL, ROLE_INITIATOR,
2275                                    CAM_REQUEUE_REQ, SEARCH_COMPLETE);
2276                 ahd_qinfifo_requeue_tail(ahd, pending_scb);
2277                 ahd_set_scbptr(ahd, saved_scbptr);
2278                 ahd_print_path(ahd, pending_scb);
2279                 printf("Device is disconnected, re-queuing SCB\n");
2280                 wait = TRUE;
2281         } else {
2282                 printf("%s:%d:%d:%d: Unable to deliver message\n",
2283                        ahd_name(ahd), cmd->device->channel,
2284                        cmd->device->id, cmd->device->lun);
2285                 retval = FAILED;
2286                 goto done;
2287         }
2288
2289 no_cmd:
2290         /*
2291          * Our assumption is that if we don't have the command, no
2292          * recovery action was required, so we return success.  Again,
2293          * the semantics of the mid-layer recovery engine are not
2294          * well defined, so this may change in time.
2295          */
2296         retval = SUCCESS;
2297 done:
2298         if (paused)
2299                 ahd_unpause(ahd);
2300         if (wait) {
2301                 struct timer_list timer;
2302                 int ret;
2303
2304                 ahd->platform_data->flags |= AHD_SCB_UP_EH_SEM;
2305                 spin_unlock_irq(&ahd->platform_data->spin_lock);
2306                 init_timer(&timer);
2307                 timer.data = (u_long)ahd;
2308                 timer.expires = jiffies + (5 * HZ);
2309                 timer.function = ahd_linux_sem_timeout;
2310                 add_timer(&timer);
2311                 printf("Recovery code sleeping\n");
2312                 down(&ahd->platform_data->eh_sem);
2313                 printf("Recovery code awake\n");
2314                 ret = del_timer_sync(&timer);
2315                 if (ret == 0) {
2316                         printf("Timer Expired\n");
2317                         retval = FAILED;
2318                 }
2319                 spin_lock_irq(&ahd->platform_data->spin_lock);
2320         }
2321         spin_unlock_irq(&ahd->platform_data->spin_lock);
2322         return (retval);
2323 }
2324
2325 static void ahd_linux_set_width(struct scsi_target *starget, int width)
2326 {
2327         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
2328         struct ahd_softc *ahd = *((struct ahd_softc **)shost->hostdata);
2329         struct ahd_devinfo devinfo;
2330         unsigned long flags;
2331
2332         ahd_compile_devinfo(&devinfo, shost->this_id, starget->id, 0,
2333                             starget->channel + 'A', ROLE_INITIATOR);
2334         ahd_lock(ahd, &flags);
2335         ahd_set_width(ahd, &devinfo, width, AHD_TRANS_GOAL, FALSE);
2336         ahd_unlock(ahd, &flags);
2337 }
2338
2339 static void ahd_linux_set_period(struct scsi_target *starget, int period)
2340 {
2341         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
2342         struct ahd_softc *ahd = *((struct ahd_softc **)shost->hostdata);
2343         struct ahd_tmode_tstate *tstate;
2344         struct ahd_initiator_tinfo *tinfo 
2345                 = ahd_fetch_transinfo(ahd,
2346                                       starget->channel + 'A',
2347                                       shost->this_id, starget->id, &tstate);
2348         struct ahd_devinfo devinfo;
2349         unsigned int ppr_options = tinfo->goal.ppr_options;
2350         unsigned int dt;
2351         unsigned long flags;
2352         unsigned long offset = tinfo->goal.offset;
2353
2354 #ifdef AHD_DEBUG
2355         if ((ahd_debug & AHD_SHOW_DV) != 0)
2356                 printf("%s: set period to %d\n", ahd_name(ahd), period);
2357 #endif
2358         if (offset == 0)
2359                 offset = MAX_OFFSET;
2360
2361         if (period < 8)
2362                 period = 8;
2363         if (period < 10) {
2364                 ppr_options |= MSG_EXT_PPR_DT_REQ;
2365                 if (period == 8)
2366                         ppr_options |= MSG_EXT_PPR_IU_REQ;
2367         }
2368
2369         dt = ppr_options & MSG_EXT_PPR_DT_REQ;
2370
2371         ahd_compile_devinfo(&devinfo, shost->this_id, starget->id, 0,
2372                             starget->channel + 'A', ROLE_INITIATOR);
2373
2374         /* all PPR requests apart from QAS require wide transfers */
2375         if (ppr_options & ~MSG_EXT_PPR_QAS_REQ) {
2376                 if (spi_width(starget) == 0)
2377                         ppr_options &= MSG_EXT_PPR_QAS_REQ;
2378         }
2379
2380         ahd_find_syncrate(ahd, &period, &ppr_options,
2381                           dt ? AHD_SYNCRATE_MAX : AHD_SYNCRATE_ULTRA2);
2382
2383         ahd_lock(ahd, &flags);
2384         ahd_set_syncrate(ahd, &devinfo, period, offset,
2385                          ppr_options, AHD_TRANS_GOAL, FALSE);
2386         ahd_unlock(ahd, &flags);
2387 }
2388
2389 static void ahd_linux_set_offset(struct scsi_target *starget, int offset)
2390 {
2391         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
2392         struct ahd_softc *ahd = *((struct ahd_softc **)shost->hostdata);
2393         struct ahd_tmode_tstate *tstate;
2394         struct ahd_initiator_tinfo *tinfo 
2395                 = ahd_fetch_transinfo(ahd,
2396                                       starget->channel + 'A',
2397                                       shost->this_id, starget->id, &tstate);
2398         struct ahd_devinfo devinfo;
2399         unsigned int ppr_options = 0;
2400         unsigned int period = 0;
2401         unsigned int dt = ppr_options & MSG_EXT_PPR_DT_REQ;
2402         unsigned long flags;
2403
2404 #ifdef AHD_DEBUG
2405         if ((ahd_debug & AHD_SHOW_DV) != 0)
2406                 printf("%s: set offset to %d\n", ahd_name(ahd), offset);
2407 #endif
2408
2409         ahd_compile_devinfo(&devinfo, shost->this_id, starget->id, 0,
2410                             starget->channel + 'A', ROLE_INITIATOR);
2411         if (offset != 0) {
2412                 period = tinfo->goal.period;
2413                 ppr_options = tinfo->goal.ppr_options;
2414                 ahd_find_syncrate(ahd, &period, &ppr_options, 
2415                                   dt ? AHD_SYNCRATE_MAX : AHD_SYNCRATE_ULTRA2);
2416         }
2417
2418         ahd_lock(ahd, &flags);
2419         ahd_set_syncrate(ahd, &devinfo, period, offset, ppr_options,
2420                          AHD_TRANS_GOAL, FALSE);
2421         ahd_unlock(ahd, &flags);
2422 }
2423
2424 static void ahd_linux_set_dt(struct scsi_target *starget, int dt)
2425 {
2426         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
2427         struct ahd_softc *ahd = *((struct ahd_softc **)shost->hostdata);
2428         struct ahd_tmode_tstate *tstate;
2429         struct ahd_initiator_tinfo *tinfo 
2430                 = ahd_fetch_transinfo(ahd,
2431                                       starget->channel + 'A',
2432                                       shost->this_id, starget->id, &tstate);
2433         struct ahd_devinfo devinfo;
2434         unsigned int ppr_options = tinfo->goal.ppr_options
2435                 & ~MSG_EXT_PPR_DT_REQ;
2436         unsigned int period = tinfo->goal.period;
2437         unsigned int width = tinfo->goal.width;
2438         unsigned long flags;
2439
2440 #ifdef AHD_DEBUG
2441         if ((ahd_debug & AHD_SHOW_DV) != 0)
2442                 printf("%s: %s DT\n", ahd_name(ahd), 
2443                        dt ? "enabling" : "disabling");
2444 #endif
2445         if (dt) {
2446                 ppr_options |= MSG_EXT_PPR_DT_REQ;
2447                 if (!width)
2448                         ahd_linux_set_width(starget, 1);
2449         } else {
2450                 if (period <= 9)
2451                         period = 10; /* If resetting DT, period must be >= 25ns */
2452                 /* IU is invalid without DT set */
2453                 ppr_options &= ~MSG_EXT_PPR_IU_REQ;
2454         }
2455         ahd_compile_devinfo(&devinfo, shost->this_id, starget->id, 0,
2456                             starget->channel + 'A', ROLE_INITIATOR);
2457         ahd_find_syncrate(ahd, &period, &ppr_options,
2458                           dt ? AHD_SYNCRATE_MAX : AHD_SYNCRATE_ULTRA2);
2459
2460         ahd_lock(ahd, &flags);
2461         ahd_set_syncrate(ahd, &devinfo, period, tinfo->goal.offset,
2462                          ppr_options, AHD_TRANS_GOAL, FALSE);
2463         ahd_unlock(ahd, &flags);
2464 }
2465
2466 static void ahd_linux_set_qas(struct scsi_target *starget, int qas)
2467 {
2468         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
2469         struct ahd_softc *ahd = *((struct ahd_softc **)shost->hostdata);
2470         struct ahd_tmode_tstate *tstate;
2471         struct ahd_initiator_tinfo *tinfo 
2472                 = ahd_fetch_transinfo(ahd,
2473                                       starget->channel + 'A',
2474                                       shost->this_id, starget->id, &tstate);
2475         struct ahd_devinfo devinfo;
2476         unsigned int ppr_options = tinfo->goal.ppr_options
2477                 & ~MSG_EXT_PPR_QAS_REQ;
2478         unsigned int period = tinfo->goal.period;
2479         unsigned int dt;
2480         unsigned long flags;
2481
2482 #ifdef AHD_DEBUG
2483         if ((ahd_debug & AHD_SHOW_DV) != 0)
2484                 printf("%s: %s QAS\n", ahd_name(ahd), 
2485                        qas ? "enabling" : "disabling");
2486 #endif
2487
2488         if (qas) {
2489                 ppr_options |= MSG_EXT_PPR_QAS_REQ; 
2490         }
2491
2492         dt = ppr_options & MSG_EXT_PPR_DT_REQ;
2493
2494         ahd_compile_devinfo(&devinfo, shost->this_id, starget->id, 0,
2495                             starget->channel + 'A', ROLE_INITIATOR);
2496         ahd_find_syncrate(ahd, &period, &ppr_options,
2497                           dt ? AHD_SYNCRATE_MAX : AHD_SYNCRATE_ULTRA2);
2498
2499         ahd_lock(ahd, &flags);
2500         ahd_set_syncrate(ahd, &devinfo, period, tinfo->goal.offset,
2501                          ppr_options, AHD_TRANS_GOAL, FALSE);
2502         ahd_unlock(ahd, &flags);
2503 }
2504
2505 static void ahd_linux_set_iu(struct scsi_target *starget, int iu)
2506 {
2507         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
2508         struct ahd_softc *ahd = *((struct ahd_softc **)shost->hostdata);
2509         struct ahd_tmode_tstate *tstate;
2510         struct ahd_initiator_tinfo *tinfo 
2511                 = ahd_fetch_transinfo(ahd,
2512                                       starget->channel + 'A',
2513                                       shost->this_id, starget->id, &tstate);
2514         struct ahd_devinfo devinfo;
2515         unsigned int ppr_options = tinfo->goal.ppr_options
2516                 & ~MSG_EXT_PPR_IU_REQ;
2517         unsigned int period = tinfo->goal.period;
2518         unsigned int dt;
2519         unsigned long flags;
2520
2521 #ifdef AHD_DEBUG
2522         if ((ahd_debug & AHD_SHOW_DV) != 0)
2523                 printf("%s: %s IU\n", ahd_name(ahd),
2524                        iu ? "enabling" : "disabling");
2525 #endif
2526
2527         if (iu) {
2528                 ppr_options |= MSG_EXT_PPR_IU_REQ;
2529                 ppr_options |= MSG_EXT_PPR_DT_REQ; /* IU requires DT */
2530         }
2531
2532         dt = ppr_options & MSG_EXT_PPR_DT_REQ;
2533
2534         ahd_compile_devinfo(&devinfo, shost->this_id, starget->id, 0,
2535                             starget->channel + 'A', ROLE_INITIATOR);
2536         ahd_find_syncrate(ahd, &period, &ppr_options,
2537                           dt ? AHD_SYNCRATE_MAX : AHD_SYNCRATE_ULTRA2);
2538
2539         ahd_lock(ahd, &flags);
2540         ahd_set_syncrate(ahd, &devinfo, period, tinfo->goal.offset,
2541                          ppr_options, AHD_TRANS_GOAL, FALSE);
2542         ahd_unlock(ahd, &flags);
2543 }
2544
2545 static void ahd_linux_set_rd_strm(struct scsi_target *starget, int rdstrm)
2546 {
2547         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
2548         struct ahd_softc *ahd = *((struct ahd_softc **)shost->hostdata);
2549         struct ahd_tmode_tstate *tstate;
2550         struct ahd_initiator_tinfo *tinfo 
2551                 = ahd_fetch_transinfo(ahd,
2552                                       starget->channel + 'A',
2553                                       shost->this_id, starget->id, &tstate);
2554         struct ahd_devinfo devinfo;
2555         unsigned int ppr_options = tinfo->goal.ppr_options
2556                 & ~MSG_EXT_PPR_RD_STRM;
2557         unsigned int period = tinfo->goal.period;
2558         unsigned int dt = ppr_options & MSG_EXT_PPR_DT_REQ;
2559         unsigned long flags;
2560
2561 #ifdef AHD_DEBUG
2562         if ((ahd_debug & AHD_SHOW_DV) != 0)
2563                 printf("%s: %s Read Streaming\n", ahd_name(ahd), 
2564                        rdstrm  ? "enabling" : "disabling");
2565 #endif
2566
2567         if (rdstrm)
2568                 ppr_options |= MSG_EXT_PPR_RD_STRM;
2569
2570         ahd_compile_devinfo(&devinfo, shost->this_id, starget->id, 0,
2571                             starget->channel + 'A', ROLE_INITIATOR);
2572         ahd_find_syncrate(ahd, &period, &ppr_options,
2573                           dt ? AHD_SYNCRATE_MAX : AHD_SYNCRATE_ULTRA2);
2574
2575         ahd_lock(ahd, &flags);
2576         ahd_set_syncrate(ahd, &devinfo, period, tinfo->goal.offset,
2577                          ppr_options, AHD_TRANS_GOAL, FALSE);
2578         ahd_unlock(ahd, &flags);
2579 }
2580
2581 static void ahd_linux_set_wr_flow(struct scsi_target *starget, int wrflow)
2582 {
2583         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
2584         struct ahd_softc *ahd = *((struct ahd_softc **)shost->hostdata);
2585         struct ahd_tmode_tstate *tstate;
2586         struct ahd_initiator_tinfo *tinfo 
2587                 = ahd_fetch_transinfo(ahd,
2588                                       starget->channel + 'A',
2589                                       shost->this_id, starget->id, &tstate);
2590         struct ahd_devinfo devinfo;
2591         unsigned int ppr_options = tinfo->goal.ppr_options
2592                 & ~MSG_EXT_PPR_WR_FLOW;
2593         unsigned int period = tinfo->goal.period;
2594         unsigned int dt = ppr_options & MSG_EXT_PPR_DT_REQ;
2595         unsigned long flags;
2596
2597 #ifdef AHD_DEBUG
2598         if ((ahd_debug & AHD_SHOW_DV) != 0)
2599                 printf("%s: %s Write Flow Control\n", ahd_name(ahd),
2600                        wrflow ? "enabling" : "disabling");
2601 #endif
2602
2603         if (wrflow)
2604                 ppr_options |= MSG_EXT_PPR_WR_FLOW;
2605
2606         ahd_compile_devinfo(&devinfo, shost->this_id, starget->id, 0,
2607                             starget->channel + 'A', ROLE_INITIATOR);
2608         ahd_find_syncrate(ahd, &period, &ppr_options,
2609                           dt ? AHD_SYNCRATE_MAX : AHD_SYNCRATE_ULTRA2);
2610
2611         ahd_lock(ahd, &flags);
2612         ahd_set_syncrate(ahd, &devinfo, period, tinfo->goal.offset,
2613                          ppr_options, AHD_TRANS_GOAL, FALSE);
2614         ahd_unlock(ahd, &flags);
2615 }
2616
2617 static void ahd_linux_set_rti(struct scsi_target *starget, int rti)
2618 {
2619         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
2620         struct ahd_softc *ahd = *((struct ahd_softc **)shost->hostdata);
2621         struct ahd_tmode_tstate *tstate;
2622         struct ahd_initiator_tinfo *tinfo 
2623                 = ahd_fetch_transinfo(ahd,
2624                                       starget->channel + 'A',
2625                                       shost->this_id, starget->id, &tstate);
2626         struct ahd_devinfo devinfo;
2627         unsigned int ppr_options = tinfo->goal.ppr_options
2628                 & ~MSG_EXT_PPR_RTI;
2629         unsigned int period = tinfo->goal.period;
2630         unsigned int dt = ppr_options & MSG_EXT_PPR_DT_REQ;
2631         unsigned long flags;
2632
2633         if ((ahd->features & AHD_RTI) == 0) {
2634 #ifdef AHD_DEBUG
2635                 if ((ahd_debug & AHD_SHOW_DV) != 0)
2636                         printf("%s: RTI not available\n", ahd_name(ahd));
2637 #endif
2638                 return;
2639         }
2640
2641 #ifdef AHD_DEBUG
2642         if ((ahd_debug & AHD_SHOW_DV) != 0)
2643                 printf("%s: %s RTI\n", ahd_name(ahd),
2644                        rti ? "enabling" : "disabling");
2645 #endif
2646
2647         if (rti)
2648                 ppr_options |= MSG_EXT_PPR_RTI;
2649
2650         ahd_compile_devinfo(&devinfo, shost->this_id, starget->id, 0,
2651                             starget->channel + 'A', ROLE_INITIATOR);
2652         ahd_find_syncrate(ahd, &period, &ppr_options,
2653                           dt ? AHD_SYNCRATE_MAX : AHD_SYNCRATE_ULTRA2);
2654
2655         ahd_lock(ahd, &flags);
2656         ahd_set_syncrate(ahd, &devinfo, period, tinfo->goal.offset,
2657                          ppr_options, AHD_TRANS_GOAL, FALSE);
2658         ahd_unlock(ahd, &flags);
2659 }
2660
2661 static void ahd_linux_set_pcomp_en(struct scsi_target *starget, int pcomp)
2662 {
2663         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
2664         struct ahd_softc *ahd = *((struct ahd_softc **)shost->hostdata);
2665         struct ahd_tmode_tstate *tstate;
2666         struct ahd_initiator_tinfo *tinfo 
2667                 = ahd_fetch_transinfo(ahd,
2668                                       starget->channel + 'A',
2669                                       shost->this_id, starget->id, &tstate);
2670         struct ahd_devinfo devinfo;
2671         unsigned int ppr_options = tinfo->goal.ppr_options
2672                 & ~MSG_EXT_PPR_PCOMP_EN;
2673         unsigned int period = tinfo->goal.period;
2674         unsigned int dt = ppr_options & MSG_EXT_PPR_DT_REQ;
2675         unsigned long flags;
2676
2677 #ifdef AHD_DEBUG
2678         if ((ahd_debug & AHD_SHOW_DV) != 0)
2679                 printf("%s: %s Precompensation\n", ahd_name(ahd), 
2680                        pcomp ? "Enable" : "Disable");
2681 #endif
2682
2683         if (pcomp)
2684                 ppr_options |= MSG_EXT_PPR_PCOMP_EN;
2685
2686         ahd_compile_devinfo(&devinfo, shost->this_id, starget->id, 0,
2687                             starget->channel + 'A', ROLE_INITIATOR);
2688         ahd_find_syncrate(ahd, &period, &ppr_options,
2689                           dt ? AHD_SYNCRATE_MAX : AHD_SYNCRATE_ULTRA2);
2690
2691         ahd_lock(ahd, &flags);
2692         ahd_set_syncrate(ahd, &devinfo, period, tinfo->goal.offset,
2693                          ppr_options, AHD_TRANS_GOAL, FALSE);
2694         ahd_unlock(ahd, &flags);
2695 }
2696
2697 static void ahd_linux_set_hold_mcs(struct scsi_target *starget, int hold)
2698 {
2699         struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
2700         struct ahd_softc *ahd = *((struct ahd_softc **)shost->hostdata);
2701         struct ahd_tmode_tstate *tstate;
2702         struct ahd_initiator_tinfo *tinfo 
2703                 = ahd_fetch_transinfo(ahd,
2704                                       starget->channel + 'A',
2705                                       shost->this_id, starget->id, &tstate);
2706         struct ahd_devinfo devinfo;
2707         unsigned int ppr_options = tinfo->goal.ppr_options
2708                 & ~MSG_EXT_PPR_HOLD_MCS;
2709         unsigned int period = tinfo->goal.period;
2710         unsigned int dt = ppr_options & MSG_EXT_PPR_DT_REQ;
2711         unsigned long flags;
2712
2713         if (hold)
2714                 ppr_options |= MSG_EXT_PPR_HOLD_MCS;
2715
2716         ahd_compile_devinfo(&devinfo, shost->this_id, starget->id, 0,
2717                             starget->channel + 'A', ROLE_INITIATOR);
2718         ahd_find_syncrate(ahd, &period, &ppr_options,
2719                           dt ? AHD_SYNCRATE_MAX : AHD_SYNCRATE_ULTRA2);
2720
2721         ahd_lock(ahd, &flags);
2722         ahd_set_syncrate(ahd, &devinfo, period, tinfo->goal.offset,
2723                          ppr_options, AHD_TRANS_GOAL, FALSE);
2724         ahd_unlock(ahd, &flags);
2725 }
2726
2727
2728
2729 static struct spi_function_template ahd_linux_transport_functions = {
2730         .set_offset     = ahd_linux_set_offset,
2731         .show_offset    = 1,
2732         .set_period     = ahd_linux_set_period,
2733         .show_period    = 1,
2734         .set_width      = ahd_linux_set_width,
2735         .show_width     = 1,
2736         .set_dt         = ahd_linux_set_dt,
2737         .show_dt        = 1,
2738         .set_iu         = ahd_linux_set_iu,
2739         .show_iu        = 1,
2740         .set_qas        = ahd_linux_set_qas,
2741         .show_qas       = 1,
2742         .set_rd_strm    = ahd_linux_set_rd_strm,
2743         .show_rd_strm   = 1,
2744         .set_wr_flow    = ahd_linux_set_wr_flow,
2745         .show_wr_flow   = 1,
2746         .set_rti        = ahd_linux_set_rti,
2747         .show_rti       = 1,
2748         .set_pcomp_en   = ahd_linux_set_pcomp_en,
2749         .show_pcomp_en  = 1,
2750         .set_hold_mcs   = ahd_linux_set_hold_mcs,
2751         .show_hold_mcs  = 1,
2752 };
2753
2754 static int __init
2755 ahd_linux_init(void)
2756 {
2757         int     error = 0;
2758
2759         /*
2760          * If we've been passed any parameters, process them now.
2761          */
2762         if (aic79xx)
2763                 aic79xx_setup(aic79xx);
2764
2765         ahd_linux_transport_template =
2766                 spi_attach_transport(&ahd_linux_transport_functions);
2767         if (!ahd_linux_transport_template)
2768                 return -ENODEV;
2769
2770         scsi_transport_reserve_target(ahd_linux_transport_template,
2771                                       sizeof(struct ahd_linux_target));
2772         scsi_transport_reserve_device(ahd_linux_transport_template,
2773                                       sizeof(struct ahd_linux_device));
2774
2775         error = ahd_linux_pci_init();
2776         if (error)
2777                 spi_release_transport(ahd_linux_transport_template);
2778         return error;
2779 }
2780
2781 static void __exit
2782 ahd_linux_exit(void)
2783 {
2784         ahd_linux_pci_exit();
2785         spi_release_transport(ahd_linux_transport_template);
2786 }
2787
2788 module_init(ahd_linux_init);
2789 module_exit(ahd_linux_exit);