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