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