xref: /linux/drivers/ata/libata-core.c (revision 2b8232ce512105e28453f301d1510de8363bccd1)
1 /*
2  *  libata-core.c - helper library for ATA
3  *
4  *  Maintained by:  Jeff Garzik <jgarzik@pobox.com>
5  *    		    Please ALWAYS copy linux-ide@vger.kernel.org
6  *		    on emails.
7  *
8  *  Copyright 2003-2004 Red Hat, Inc.  All rights reserved.
9  *  Copyright 2003-2004 Jeff Garzik
10  *
11  *
12  *  This program is free software; you can redistribute it and/or modify
13  *  it under the terms of the GNU General Public License as published by
14  *  the Free Software Foundation; either version 2, or (at your option)
15  *  any later version.
16  *
17  *  This program is distributed in the hope that it will be useful,
18  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
19  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  *  GNU General Public License for more details.
21  *
22  *  You should have received a copy of the GNU General Public License
23  *  along with this program; see the file COPYING.  If not, write to
24  *  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
25  *
26  *
27  *  libata documentation is available via 'make {ps|pdf}docs',
28  *  as Documentation/DocBook/libata.*
29  *
30  *  Hardware documentation available from http://www.t13.org/ and
31  *  http://www.sata-io.org/
32  *
33  */
34 
35 #include <linux/kernel.h>
36 #include <linux/module.h>
37 #include <linux/pci.h>
38 #include <linux/init.h>
39 #include <linux/list.h>
40 #include <linux/mm.h>
41 #include <linux/highmem.h>
42 #include <linux/spinlock.h>
43 #include <linux/blkdev.h>
44 #include <linux/delay.h>
45 #include <linux/timer.h>
46 #include <linux/interrupt.h>
47 #include <linux/completion.h>
48 #include <linux/suspend.h>
49 #include <linux/workqueue.h>
50 #include <linux/jiffies.h>
51 #include <linux/scatterlist.h>
52 #include <scsi/scsi.h>
53 #include <scsi/scsi_cmnd.h>
54 #include <scsi/scsi_host.h>
55 #include <linux/libata.h>
56 #include <asm/io.h>
57 #include <asm/semaphore.h>
58 #include <asm/byteorder.h>
59 
60 #include "libata.h"
61 
62 
63 /* debounce timing parameters in msecs { interval, duration, timeout } */
64 const unsigned long sata_deb_timing_normal[]		= {   5,  100, 2000 };
65 const unsigned long sata_deb_timing_hotplug[]		= {  25,  500, 2000 };
66 const unsigned long sata_deb_timing_long[]		= { 100, 2000, 5000 };
67 
68 static unsigned int ata_dev_init_params(struct ata_device *dev,
69 					u16 heads, u16 sectors);
70 static unsigned int ata_dev_set_xfermode(struct ata_device *dev);
71 static unsigned int ata_dev_set_AN(struct ata_device *dev, u8 enable);
72 static void ata_dev_xfermask(struct ata_device *dev);
73 static unsigned long ata_dev_blacklisted(const struct ata_device *dev);
74 
75 unsigned int ata_print_id = 1;
76 static struct workqueue_struct *ata_wq;
77 
78 struct workqueue_struct *ata_aux_wq;
79 
80 int atapi_enabled = 1;
81 module_param(atapi_enabled, int, 0444);
82 MODULE_PARM_DESC(atapi_enabled, "Enable discovery of ATAPI devices (0=off, 1=on)");
83 
84 int atapi_dmadir = 0;
85 module_param(atapi_dmadir, int, 0444);
86 MODULE_PARM_DESC(atapi_dmadir, "Enable ATAPI DMADIR bridge support (0=off, 1=on)");
87 
88 int atapi_passthru16 = 1;
89 module_param(atapi_passthru16, int, 0444);
90 MODULE_PARM_DESC(atapi_passthru16, "Enable ATA_16 passthru for ATAPI devices; on by default (0=off, 1=on)");
91 
92 int libata_fua = 0;
93 module_param_named(fua, libata_fua, int, 0444);
94 MODULE_PARM_DESC(fua, "FUA support (0=off, 1=on)");
95 
96 static int ata_ignore_hpa = 0;
97 module_param_named(ignore_hpa, ata_ignore_hpa, int, 0644);
98 MODULE_PARM_DESC(ignore_hpa, "Ignore HPA limit (0=keep BIOS limits, 1=ignore limits, using full disk)");
99 
100 static int libata_dma_mask = ATA_DMA_MASK_ATA|ATA_DMA_MASK_ATAPI|ATA_DMA_MASK_CFA;
101 module_param_named(dma, libata_dma_mask, int, 0444);
102 MODULE_PARM_DESC(dma, "DMA enable/disable (0x1==ATA, 0x2==ATAPI, 0x4==CF)");
103 
104 static int ata_probe_timeout = ATA_TMOUT_INTERNAL / HZ;
105 module_param(ata_probe_timeout, int, 0444);
106 MODULE_PARM_DESC(ata_probe_timeout, "Set ATA probing timeout (seconds)");
107 
108 int libata_noacpi = 0;
109 module_param_named(noacpi, libata_noacpi, int, 0444);
110 MODULE_PARM_DESC(noacpi, "Disables the use of ACPI in probe/suspend/resume when set");
111 
112 MODULE_AUTHOR("Jeff Garzik");
113 MODULE_DESCRIPTION("Library module for ATA devices");
114 MODULE_LICENSE("GPL");
115 MODULE_VERSION(DRV_VERSION);
116 
117 
118 /**
119  *	ata_tf_to_fis - Convert ATA taskfile to SATA FIS structure
120  *	@tf: Taskfile to convert
121  *	@pmp: Port multiplier port
122  *	@is_cmd: This FIS is for command
123  *	@fis: Buffer into which data will output
124  *
125  *	Converts a standard ATA taskfile to a Serial ATA
126  *	FIS structure (Register - Host to Device).
127  *
128  *	LOCKING:
129  *	Inherited from caller.
130  */
131 void ata_tf_to_fis(const struct ata_taskfile *tf, u8 pmp, int is_cmd, u8 *fis)
132 {
133 	fis[0] = 0x27;			/* Register - Host to Device FIS */
134 	fis[1] = pmp & 0xf;		/* Port multiplier number*/
135 	if (is_cmd)
136 		fis[1] |= (1 << 7);	/* bit 7 indicates Command FIS */
137 
138 	fis[2] = tf->command;
139 	fis[3] = tf->feature;
140 
141 	fis[4] = tf->lbal;
142 	fis[5] = tf->lbam;
143 	fis[6] = tf->lbah;
144 	fis[7] = tf->device;
145 
146 	fis[8] = tf->hob_lbal;
147 	fis[9] = tf->hob_lbam;
148 	fis[10] = tf->hob_lbah;
149 	fis[11] = tf->hob_feature;
150 
151 	fis[12] = tf->nsect;
152 	fis[13] = tf->hob_nsect;
153 	fis[14] = 0;
154 	fis[15] = tf->ctl;
155 
156 	fis[16] = 0;
157 	fis[17] = 0;
158 	fis[18] = 0;
159 	fis[19] = 0;
160 }
161 
162 /**
163  *	ata_tf_from_fis - Convert SATA FIS to ATA taskfile
164  *	@fis: Buffer from which data will be input
165  *	@tf: Taskfile to output
166  *
167  *	Converts a serial ATA FIS structure to a standard ATA taskfile.
168  *
169  *	LOCKING:
170  *	Inherited from caller.
171  */
172 
173 void ata_tf_from_fis(const u8 *fis, struct ata_taskfile *tf)
174 {
175 	tf->command	= fis[2];	/* status */
176 	tf->feature	= fis[3];	/* error */
177 
178 	tf->lbal	= fis[4];
179 	tf->lbam	= fis[5];
180 	tf->lbah	= fis[6];
181 	tf->device	= fis[7];
182 
183 	tf->hob_lbal	= fis[8];
184 	tf->hob_lbam	= fis[9];
185 	tf->hob_lbah	= fis[10];
186 
187 	tf->nsect	= fis[12];
188 	tf->hob_nsect	= fis[13];
189 }
190 
191 static const u8 ata_rw_cmds[] = {
192 	/* pio multi */
193 	ATA_CMD_READ_MULTI,
194 	ATA_CMD_WRITE_MULTI,
195 	ATA_CMD_READ_MULTI_EXT,
196 	ATA_CMD_WRITE_MULTI_EXT,
197 	0,
198 	0,
199 	0,
200 	ATA_CMD_WRITE_MULTI_FUA_EXT,
201 	/* pio */
202 	ATA_CMD_PIO_READ,
203 	ATA_CMD_PIO_WRITE,
204 	ATA_CMD_PIO_READ_EXT,
205 	ATA_CMD_PIO_WRITE_EXT,
206 	0,
207 	0,
208 	0,
209 	0,
210 	/* dma */
211 	ATA_CMD_READ,
212 	ATA_CMD_WRITE,
213 	ATA_CMD_READ_EXT,
214 	ATA_CMD_WRITE_EXT,
215 	0,
216 	0,
217 	0,
218 	ATA_CMD_WRITE_FUA_EXT
219 };
220 
221 /**
222  *	ata_rwcmd_protocol - set taskfile r/w commands and protocol
223  *	@tf: command to examine and configure
224  *	@dev: device tf belongs to
225  *
226  *	Examine the device configuration and tf->flags to calculate
227  *	the proper read/write commands and protocol to use.
228  *
229  *	LOCKING:
230  *	caller.
231  */
232 static int ata_rwcmd_protocol(struct ata_taskfile *tf, struct ata_device *dev)
233 {
234 	u8 cmd;
235 
236 	int index, fua, lba48, write;
237 
238 	fua = (tf->flags & ATA_TFLAG_FUA) ? 4 : 0;
239 	lba48 = (tf->flags & ATA_TFLAG_LBA48) ? 2 : 0;
240 	write = (tf->flags & ATA_TFLAG_WRITE) ? 1 : 0;
241 
242 	if (dev->flags & ATA_DFLAG_PIO) {
243 		tf->protocol = ATA_PROT_PIO;
244 		index = dev->multi_count ? 0 : 8;
245 	} else if (lba48 && (dev->link->ap->flags & ATA_FLAG_PIO_LBA48)) {
246 		/* Unable to use DMA due to host limitation */
247 		tf->protocol = ATA_PROT_PIO;
248 		index = dev->multi_count ? 0 : 8;
249 	} else {
250 		tf->protocol = ATA_PROT_DMA;
251 		index = 16;
252 	}
253 
254 	cmd = ata_rw_cmds[index + fua + lba48 + write];
255 	if (cmd) {
256 		tf->command = cmd;
257 		return 0;
258 	}
259 	return -1;
260 }
261 
262 /**
263  *	ata_tf_read_block - Read block address from ATA taskfile
264  *	@tf: ATA taskfile of interest
265  *	@dev: ATA device @tf belongs to
266  *
267  *	LOCKING:
268  *	None.
269  *
270  *	Read block address from @tf.  This function can handle all
271  *	three address formats - LBA, LBA48 and CHS.  tf->protocol and
272  *	flags select the address format to use.
273  *
274  *	RETURNS:
275  *	Block address read from @tf.
276  */
277 u64 ata_tf_read_block(struct ata_taskfile *tf, struct ata_device *dev)
278 {
279 	u64 block = 0;
280 
281 	if (tf->flags & ATA_TFLAG_LBA) {
282 		if (tf->flags & ATA_TFLAG_LBA48) {
283 			block |= (u64)tf->hob_lbah << 40;
284 			block |= (u64)tf->hob_lbam << 32;
285 			block |= tf->hob_lbal << 24;
286 		} else
287 			block |= (tf->device & 0xf) << 24;
288 
289 		block |= tf->lbah << 16;
290 		block |= tf->lbam << 8;
291 		block |= tf->lbal;
292 	} else {
293 		u32 cyl, head, sect;
294 
295 		cyl = tf->lbam | (tf->lbah << 8);
296 		head = tf->device & 0xf;
297 		sect = tf->lbal;
298 
299 		block = (cyl * dev->heads + head) * dev->sectors + sect;
300 	}
301 
302 	return block;
303 }
304 
305 /**
306  *	ata_build_rw_tf - Build ATA taskfile for given read/write request
307  *	@tf: Target ATA taskfile
308  *	@dev: ATA device @tf belongs to
309  *	@block: Block address
310  *	@n_block: Number of blocks
311  *	@tf_flags: RW/FUA etc...
312  *	@tag: tag
313  *
314  *	LOCKING:
315  *	None.
316  *
317  *	Build ATA taskfile @tf for read/write request described by
318  *	@block, @n_block, @tf_flags and @tag on @dev.
319  *
320  *	RETURNS:
321  *
322  *	0 on success, -ERANGE if the request is too large for @dev,
323  *	-EINVAL if the request is invalid.
324  */
325 int ata_build_rw_tf(struct ata_taskfile *tf, struct ata_device *dev,
326 		    u64 block, u32 n_block, unsigned int tf_flags,
327 		    unsigned int tag)
328 {
329 	tf->flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
330 	tf->flags |= tf_flags;
331 
332 	if (ata_ncq_enabled(dev) && likely(tag != ATA_TAG_INTERNAL)) {
333 		/* yay, NCQ */
334 		if (!lba_48_ok(block, n_block))
335 			return -ERANGE;
336 
337 		tf->protocol = ATA_PROT_NCQ;
338 		tf->flags |= ATA_TFLAG_LBA | ATA_TFLAG_LBA48;
339 
340 		if (tf->flags & ATA_TFLAG_WRITE)
341 			tf->command = ATA_CMD_FPDMA_WRITE;
342 		else
343 			tf->command = ATA_CMD_FPDMA_READ;
344 
345 		tf->nsect = tag << 3;
346 		tf->hob_feature = (n_block >> 8) & 0xff;
347 		tf->feature = n_block & 0xff;
348 
349 		tf->hob_lbah = (block >> 40) & 0xff;
350 		tf->hob_lbam = (block >> 32) & 0xff;
351 		tf->hob_lbal = (block >> 24) & 0xff;
352 		tf->lbah = (block >> 16) & 0xff;
353 		tf->lbam = (block >> 8) & 0xff;
354 		tf->lbal = block & 0xff;
355 
356 		tf->device = 1 << 6;
357 		if (tf->flags & ATA_TFLAG_FUA)
358 			tf->device |= 1 << 7;
359 	} else if (dev->flags & ATA_DFLAG_LBA) {
360 		tf->flags |= ATA_TFLAG_LBA;
361 
362 		if (lba_28_ok(block, n_block)) {
363 			/* use LBA28 */
364 			tf->device |= (block >> 24) & 0xf;
365 		} else if (lba_48_ok(block, n_block)) {
366 			if (!(dev->flags & ATA_DFLAG_LBA48))
367 				return -ERANGE;
368 
369 			/* use LBA48 */
370 			tf->flags |= ATA_TFLAG_LBA48;
371 
372 			tf->hob_nsect = (n_block >> 8) & 0xff;
373 
374 			tf->hob_lbah = (block >> 40) & 0xff;
375 			tf->hob_lbam = (block >> 32) & 0xff;
376 			tf->hob_lbal = (block >> 24) & 0xff;
377 		} else
378 			/* request too large even for LBA48 */
379 			return -ERANGE;
380 
381 		if (unlikely(ata_rwcmd_protocol(tf, dev) < 0))
382 			return -EINVAL;
383 
384 		tf->nsect = n_block & 0xff;
385 
386 		tf->lbah = (block >> 16) & 0xff;
387 		tf->lbam = (block >> 8) & 0xff;
388 		tf->lbal = block & 0xff;
389 
390 		tf->device |= ATA_LBA;
391 	} else {
392 		/* CHS */
393 		u32 sect, head, cyl, track;
394 
395 		/* The request -may- be too large for CHS addressing. */
396 		if (!lba_28_ok(block, n_block))
397 			return -ERANGE;
398 
399 		if (unlikely(ata_rwcmd_protocol(tf, dev) < 0))
400 			return -EINVAL;
401 
402 		/* Convert LBA to CHS */
403 		track = (u32)block / dev->sectors;
404 		cyl   = track / dev->heads;
405 		head  = track % dev->heads;
406 		sect  = (u32)block % dev->sectors + 1;
407 
408 		DPRINTK("block %u track %u cyl %u head %u sect %u\n",
409 			(u32)block, track, cyl, head, sect);
410 
411 		/* Check whether the converted CHS can fit.
412 		   Cylinder: 0-65535
413 		   Head: 0-15
414 		   Sector: 1-255*/
415 		if ((cyl >> 16) || (head >> 4) || (sect >> 8) || (!sect))
416 			return -ERANGE;
417 
418 		tf->nsect = n_block & 0xff; /* Sector count 0 means 256 sectors */
419 		tf->lbal = sect;
420 		tf->lbam = cyl;
421 		tf->lbah = cyl >> 8;
422 		tf->device |= head;
423 	}
424 
425 	return 0;
426 }
427 
428 /**
429  *	ata_pack_xfermask - Pack pio, mwdma and udma masks into xfer_mask
430  *	@pio_mask: pio_mask
431  *	@mwdma_mask: mwdma_mask
432  *	@udma_mask: udma_mask
433  *
434  *	Pack @pio_mask, @mwdma_mask and @udma_mask into a single
435  *	unsigned int xfer_mask.
436  *
437  *	LOCKING:
438  *	None.
439  *
440  *	RETURNS:
441  *	Packed xfer_mask.
442  */
443 static unsigned int ata_pack_xfermask(unsigned int pio_mask,
444 				      unsigned int mwdma_mask,
445 				      unsigned int udma_mask)
446 {
447 	return ((pio_mask << ATA_SHIFT_PIO) & ATA_MASK_PIO) |
448 		((mwdma_mask << ATA_SHIFT_MWDMA) & ATA_MASK_MWDMA) |
449 		((udma_mask << ATA_SHIFT_UDMA) & ATA_MASK_UDMA);
450 }
451 
452 /**
453  *	ata_unpack_xfermask - Unpack xfer_mask into pio, mwdma and udma masks
454  *	@xfer_mask: xfer_mask to unpack
455  *	@pio_mask: resulting pio_mask
456  *	@mwdma_mask: resulting mwdma_mask
457  *	@udma_mask: resulting udma_mask
458  *
459  *	Unpack @xfer_mask into @pio_mask, @mwdma_mask and @udma_mask.
460  *	Any NULL distination masks will be ignored.
461  */
462 static void ata_unpack_xfermask(unsigned int xfer_mask,
463 				unsigned int *pio_mask,
464 				unsigned int *mwdma_mask,
465 				unsigned int *udma_mask)
466 {
467 	if (pio_mask)
468 		*pio_mask = (xfer_mask & ATA_MASK_PIO) >> ATA_SHIFT_PIO;
469 	if (mwdma_mask)
470 		*mwdma_mask = (xfer_mask & ATA_MASK_MWDMA) >> ATA_SHIFT_MWDMA;
471 	if (udma_mask)
472 		*udma_mask = (xfer_mask & ATA_MASK_UDMA) >> ATA_SHIFT_UDMA;
473 }
474 
475 static const struct ata_xfer_ent {
476 	int shift, bits;
477 	u8 base;
478 } ata_xfer_tbl[] = {
479 	{ ATA_SHIFT_PIO, ATA_BITS_PIO, XFER_PIO_0 },
480 	{ ATA_SHIFT_MWDMA, ATA_BITS_MWDMA, XFER_MW_DMA_0 },
481 	{ ATA_SHIFT_UDMA, ATA_BITS_UDMA, XFER_UDMA_0 },
482 	{ -1, },
483 };
484 
485 /**
486  *	ata_xfer_mask2mode - Find matching XFER_* for the given xfer_mask
487  *	@xfer_mask: xfer_mask of interest
488  *
489  *	Return matching XFER_* value for @xfer_mask.  Only the highest
490  *	bit of @xfer_mask is considered.
491  *
492  *	LOCKING:
493  *	None.
494  *
495  *	RETURNS:
496  *	Matching XFER_* value, 0 if no match found.
497  */
498 static u8 ata_xfer_mask2mode(unsigned int xfer_mask)
499 {
500 	int highbit = fls(xfer_mask) - 1;
501 	const struct ata_xfer_ent *ent;
502 
503 	for (ent = ata_xfer_tbl; ent->shift >= 0; ent++)
504 		if (highbit >= ent->shift && highbit < ent->shift + ent->bits)
505 			return ent->base + highbit - ent->shift;
506 	return 0;
507 }
508 
509 /**
510  *	ata_xfer_mode2mask - Find matching xfer_mask for XFER_*
511  *	@xfer_mode: XFER_* of interest
512  *
513  *	Return matching xfer_mask for @xfer_mode.
514  *
515  *	LOCKING:
516  *	None.
517  *
518  *	RETURNS:
519  *	Matching xfer_mask, 0 if no match found.
520  */
521 static unsigned int ata_xfer_mode2mask(u8 xfer_mode)
522 {
523 	const struct ata_xfer_ent *ent;
524 
525 	for (ent = ata_xfer_tbl; ent->shift >= 0; ent++)
526 		if (xfer_mode >= ent->base && xfer_mode < ent->base + ent->bits)
527 			return 1 << (ent->shift + xfer_mode - ent->base);
528 	return 0;
529 }
530 
531 /**
532  *	ata_xfer_mode2shift - Find matching xfer_shift for XFER_*
533  *	@xfer_mode: XFER_* of interest
534  *
535  *	Return matching xfer_shift for @xfer_mode.
536  *
537  *	LOCKING:
538  *	None.
539  *
540  *	RETURNS:
541  *	Matching xfer_shift, -1 if no match found.
542  */
543 static int ata_xfer_mode2shift(unsigned int xfer_mode)
544 {
545 	const struct ata_xfer_ent *ent;
546 
547 	for (ent = ata_xfer_tbl; ent->shift >= 0; ent++)
548 		if (xfer_mode >= ent->base && xfer_mode < ent->base + ent->bits)
549 			return ent->shift;
550 	return -1;
551 }
552 
553 /**
554  *	ata_mode_string - convert xfer_mask to string
555  *	@xfer_mask: mask of bits supported; only highest bit counts.
556  *
557  *	Determine string which represents the highest speed
558  *	(highest bit in @modemask).
559  *
560  *	LOCKING:
561  *	None.
562  *
563  *	RETURNS:
564  *	Constant C string representing highest speed listed in
565  *	@mode_mask, or the constant C string "<n/a>".
566  */
567 static const char *ata_mode_string(unsigned int xfer_mask)
568 {
569 	static const char * const xfer_mode_str[] = {
570 		"PIO0",
571 		"PIO1",
572 		"PIO2",
573 		"PIO3",
574 		"PIO4",
575 		"PIO5",
576 		"PIO6",
577 		"MWDMA0",
578 		"MWDMA1",
579 		"MWDMA2",
580 		"MWDMA3",
581 		"MWDMA4",
582 		"UDMA/16",
583 		"UDMA/25",
584 		"UDMA/33",
585 		"UDMA/44",
586 		"UDMA/66",
587 		"UDMA/100",
588 		"UDMA/133",
589 		"UDMA7",
590 	};
591 	int highbit;
592 
593 	highbit = fls(xfer_mask) - 1;
594 	if (highbit >= 0 && highbit < ARRAY_SIZE(xfer_mode_str))
595 		return xfer_mode_str[highbit];
596 	return "<n/a>";
597 }
598 
599 static const char *sata_spd_string(unsigned int spd)
600 {
601 	static const char * const spd_str[] = {
602 		"1.5 Gbps",
603 		"3.0 Gbps",
604 	};
605 
606 	if (spd == 0 || (spd - 1) >= ARRAY_SIZE(spd_str))
607 		return "<unknown>";
608 	return spd_str[spd - 1];
609 }
610 
611 void ata_dev_disable(struct ata_device *dev)
612 {
613 	if (ata_dev_enabled(dev)) {
614 		if (ata_msg_drv(dev->link->ap))
615 			ata_dev_printk(dev, KERN_WARNING, "disabled\n");
616 		ata_down_xfermask_limit(dev, ATA_DNXFER_FORCE_PIO0 |
617 					     ATA_DNXFER_QUIET);
618 		dev->class++;
619 	}
620 }
621 
622 /**
623  *	ata_devchk - PATA device presence detection
624  *	@ap: ATA channel to examine
625  *	@device: Device to examine (starting at zero)
626  *
627  *	This technique was originally described in
628  *	Hale Landis's ATADRVR (www.ata-atapi.com), and
629  *	later found its way into the ATA/ATAPI spec.
630  *
631  *	Write a pattern to the ATA shadow registers,
632  *	and if a device is present, it will respond by
633  *	correctly storing and echoing back the
634  *	ATA shadow register contents.
635  *
636  *	LOCKING:
637  *	caller.
638  */
639 
640 static unsigned int ata_devchk(struct ata_port *ap, unsigned int device)
641 {
642 	struct ata_ioports *ioaddr = &ap->ioaddr;
643 	u8 nsect, lbal;
644 
645 	ap->ops->dev_select(ap, device);
646 
647 	iowrite8(0x55, ioaddr->nsect_addr);
648 	iowrite8(0xaa, ioaddr->lbal_addr);
649 
650 	iowrite8(0xaa, ioaddr->nsect_addr);
651 	iowrite8(0x55, ioaddr->lbal_addr);
652 
653 	iowrite8(0x55, ioaddr->nsect_addr);
654 	iowrite8(0xaa, ioaddr->lbal_addr);
655 
656 	nsect = ioread8(ioaddr->nsect_addr);
657 	lbal = ioread8(ioaddr->lbal_addr);
658 
659 	if ((nsect == 0x55) && (lbal == 0xaa))
660 		return 1;	/* we found a device */
661 
662 	return 0;		/* nothing found */
663 }
664 
665 /**
666  *	ata_dev_classify - determine device type based on ATA-spec signature
667  *	@tf: ATA taskfile register set for device to be identified
668  *
669  *	Determine from taskfile register contents whether a device is
670  *	ATA or ATAPI, as per "Signature and persistence" section
671  *	of ATA/PI spec (volume 1, sect 5.14).
672  *
673  *	LOCKING:
674  *	None.
675  *
676  *	RETURNS:
677  *	Device type, %ATA_DEV_ATA, %ATA_DEV_ATAPI, %ATA_DEV_PMP or
678  *	%ATA_DEV_UNKNOWN the event of failure.
679  */
680 unsigned int ata_dev_classify(const struct ata_taskfile *tf)
681 {
682 	/* Apple's open source Darwin code hints that some devices only
683 	 * put a proper signature into the LBA mid/high registers,
684 	 * So, we only check those.  It's sufficient for uniqueness.
685 	 *
686 	 * ATA/ATAPI-7 (d1532v1r1: Feb. 19, 2003) specified separate
687 	 * signatures for ATA and ATAPI devices attached on SerialATA,
688 	 * 0x3c/0xc3 and 0x69/0x96 respectively.  However, SerialATA
689 	 * spec has never mentioned about using different signatures
690 	 * for ATA/ATAPI devices.  Then, Serial ATA II: Port
691 	 * Multiplier specification began to use 0x69/0x96 to identify
692 	 * port multpliers and 0x3c/0xc3 to identify SEMB device.
693 	 * ATA/ATAPI-7 dropped descriptions about 0x3c/0xc3 and
694 	 * 0x69/0x96 shortly and described them as reserved for
695 	 * SerialATA.
696 	 *
697 	 * We follow the current spec and consider that 0x69/0x96
698 	 * identifies a port multiplier and 0x3c/0xc3 a SEMB device.
699 	 */
700 	if ((tf->lbam == 0) && (tf->lbah == 0)) {
701 		DPRINTK("found ATA device by sig\n");
702 		return ATA_DEV_ATA;
703 	}
704 
705 	if ((tf->lbam == 0x14) && (tf->lbah == 0xeb)) {
706 		DPRINTK("found ATAPI device by sig\n");
707 		return ATA_DEV_ATAPI;
708 	}
709 
710 	if ((tf->lbam == 0x69) && (tf->lbah == 0x96)) {
711 		DPRINTK("found PMP device by sig\n");
712 		return ATA_DEV_PMP;
713 	}
714 
715 	if ((tf->lbam == 0x3c) && (tf->lbah == 0xc3)) {
716 		printk("ata: SEMB device ignored\n");
717 		return ATA_DEV_SEMB_UNSUP; /* not yet */
718 	}
719 
720 	DPRINTK("unknown device\n");
721 	return ATA_DEV_UNKNOWN;
722 }
723 
724 /**
725  *	ata_dev_try_classify - Parse returned ATA device signature
726  *	@dev: ATA device to classify (starting at zero)
727  *	@present: device seems present
728  *	@r_err: Value of error register on completion
729  *
730  *	After an event -- SRST, E.D.D., or SATA COMRESET -- occurs,
731  *	an ATA/ATAPI-defined set of values is placed in the ATA
732  *	shadow registers, indicating the results of device detection
733  *	and diagnostics.
734  *
735  *	Select the ATA device, and read the values from the ATA shadow
736  *	registers.  Then parse according to the Error register value,
737  *	and the spec-defined values examined by ata_dev_classify().
738  *
739  *	LOCKING:
740  *	caller.
741  *
742  *	RETURNS:
743  *	Device type - %ATA_DEV_ATA, %ATA_DEV_ATAPI or %ATA_DEV_NONE.
744  */
745 unsigned int ata_dev_try_classify(struct ata_device *dev, int present,
746 				  u8 *r_err)
747 {
748 	struct ata_port *ap = dev->link->ap;
749 	struct ata_taskfile tf;
750 	unsigned int class;
751 	u8 err;
752 
753 	ap->ops->dev_select(ap, dev->devno);
754 
755 	memset(&tf, 0, sizeof(tf));
756 
757 	ap->ops->tf_read(ap, &tf);
758 	err = tf.feature;
759 	if (r_err)
760 		*r_err = err;
761 
762 	/* see if device passed diags: if master then continue and warn later */
763 	if (err == 0 && dev->devno == 0)
764 		/* diagnostic fail : do nothing _YET_ */
765 		dev->horkage |= ATA_HORKAGE_DIAGNOSTIC;
766 	else if (err == 1)
767 		/* do nothing */ ;
768 	else if ((dev->devno == 0) && (err == 0x81))
769 		/* do nothing */ ;
770 	else
771 		return ATA_DEV_NONE;
772 
773 	/* determine if device is ATA or ATAPI */
774 	class = ata_dev_classify(&tf);
775 
776 	if (class == ATA_DEV_UNKNOWN) {
777 		/* If the device failed diagnostic, it's likely to
778 		 * have reported incorrect device signature too.
779 		 * Assume ATA device if the device seems present but
780 		 * device signature is invalid with diagnostic
781 		 * failure.
782 		 */
783 		if (present && (dev->horkage & ATA_HORKAGE_DIAGNOSTIC))
784 			class = ATA_DEV_ATA;
785 		else
786 			class = ATA_DEV_NONE;
787 	} else if ((class == ATA_DEV_ATA) && (ata_chk_status(ap) == 0))
788 		class = ATA_DEV_NONE;
789 
790 	return class;
791 }
792 
793 /**
794  *	ata_id_string - Convert IDENTIFY DEVICE page into string
795  *	@id: IDENTIFY DEVICE results we will examine
796  *	@s: string into which data is output
797  *	@ofs: offset into identify device page
798  *	@len: length of string to return. must be an even number.
799  *
800  *	The strings in the IDENTIFY DEVICE page are broken up into
801  *	16-bit chunks.  Run through the string, and output each
802  *	8-bit chunk linearly, regardless of platform.
803  *
804  *	LOCKING:
805  *	caller.
806  */
807 
808 void ata_id_string(const u16 *id, unsigned char *s,
809 		   unsigned int ofs, unsigned int len)
810 {
811 	unsigned int c;
812 
813 	while (len > 0) {
814 		c = id[ofs] >> 8;
815 		*s = c;
816 		s++;
817 
818 		c = id[ofs] & 0xff;
819 		*s = c;
820 		s++;
821 
822 		ofs++;
823 		len -= 2;
824 	}
825 }
826 
827 /**
828  *	ata_id_c_string - Convert IDENTIFY DEVICE page into C string
829  *	@id: IDENTIFY DEVICE results we will examine
830  *	@s: string into which data is output
831  *	@ofs: offset into identify device page
832  *	@len: length of string to return. must be an odd number.
833  *
834  *	This function is identical to ata_id_string except that it
835  *	trims trailing spaces and terminates the resulting string with
836  *	null.  @len must be actual maximum length (even number) + 1.
837  *
838  *	LOCKING:
839  *	caller.
840  */
841 void ata_id_c_string(const u16 *id, unsigned char *s,
842 		     unsigned int ofs, unsigned int len)
843 {
844 	unsigned char *p;
845 
846 	WARN_ON(!(len & 1));
847 
848 	ata_id_string(id, s, ofs, len - 1);
849 
850 	p = s + strnlen(s, len - 1);
851 	while (p > s && p[-1] == ' ')
852 		p--;
853 	*p = '\0';
854 }
855 
856 static u64 ata_id_n_sectors(const u16 *id)
857 {
858 	if (ata_id_has_lba(id)) {
859 		if (ata_id_has_lba48(id))
860 			return ata_id_u64(id, 100);
861 		else
862 			return ata_id_u32(id, 60);
863 	} else {
864 		if (ata_id_current_chs_valid(id))
865 			return ata_id_u32(id, 57);
866 		else
867 			return id[1] * id[3] * id[6];
868 	}
869 }
870 
871 static u64 ata_tf_to_lba48(struct ata_taskfile *tf)
872 {
873 	u64 sectors = 0;
874 
875 	sectors |= ((u64)(tf->hob_lbah & 0xff)) << 40;
876 	sectors |= ((u64)(tf->hob_lbam & 0xff)) << 32;
877 	sectors |= (tf->hob_lbal & 0xff) << 24;
878 	sectors |= (tf->lbah & 0xff) << 16;
879 	sectors |= (tf->lbam & 0xff) << 8;
880 	sectors |= (tf->lbal & 0xff);
881 
882 	return ++sectors;
883 }
884 
885 static u64 ata_tf_to_lba(struct ata_taskfile *tf)
886 {
887 	u64 sectors = 0;
888 
889 	sectors |= (tf->device & 0x0f) << 24;
890 	sectors |= (tf->lbah & 0xff) << 16;
891 	sectors |= (tf->lbam & 0xff) << 8;
892 	sectors |= (tf->lbal & 0xff);
893 
894 	return ++sectors;
895 }
896 
897 /**
898  *	ata_read_native_max_address - Read native max address
899  *	@dev: target device
900  *	@max_sectors: out parameter for the result native max address
901  *
902  *	Perform an LBA48 or LBA28 native size query upon the device in
903  *	question.
904  *
905  *	RETURNS:
906  *	0 on success, -EACCES if command is aborted by the drive.
907  *	-EIO on other errors.
908  */
909 static int ata_read_native_max_address(struct ata_device *dev, u64 *max_sectors)
910 {
911 	unsigned int err_mask;
912 	struct ata_taskfile tf;
913 	int lba48 = ata_id_has_lba48(dev->id);
914 
915 	ata_tf_init(dev, &tf);
916 
917 	/* always clear all address registers */
918 	tf.flags |= ATA_TFLAG_DEVICE | ATA_TFLAG_ISADDR;
919 
920 	if (lba48) {
921 		tf.command = ATA_CMD_READ_NATIVE_MAX_EXT;
922 		tf.flags |= ATA_TFLAG_LBA48;
923 	} else
924 		tf.command = ATA_CMD_READ_NATIVE_MAX;
925 
926 	tf.protocol |= ATA_PROT_NODATA;
927 	tf.device |= ATA_LBA;
928 
929 	err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
930 	if (err_mask) {
931 		ata_dev_printk(dev, KERN_WARNING, "failed to read native "
932 			       "max address (err_mask=0x%x)\n", err_mask);
933 		if (err_mask == AC_ERR_DEV && (tf.feature & ATA_ABORTED))
934 			return -EACCES;
935 		return -EIO;
936 	}
937 
938 	if (lba48)
939 		*max_sectors = ata_tf_to_lba48(&tf);
940 	else
941 		*max_sectors = ata_tf_to_lba(&tf);
942         if (dev->horkage & ATA_HORKAGE_HPA_SIZE)
943 		(*max_sectors)--;
944 	return 0;
945 }
946 
947 /**
948  *	ata_set_max_sectors - Set max sectors
949  *	@dev: target device
950  *	@new_sectors: new max sectors value to set for the device
951  *
952  *	Set max sectors of @dev to @new_sectors.
953  *
954  *	RETURNS:
955  *	0 on success, -EACCES if command is aborted or denied (due to
956  *	previous non-volatile SET_MAX) by the drive.  -EIO on other
957  *	errors.
958  */
959 static int ata_set_max_sectors(struct ata_device *dev, u64 new_sectors)
960 {
961 	unsigned int err_mask;
962 	struct ata_taskfile tf;
963 	int lba48 = ata_id_has_lba48(dev->id);
964 
965 	new_sectors--;
966 
967 	ata_tf_init(dev, &tf);
968 
969 	tf.flags |= ATA_TFLAG_DEVICE | ATA_TFLAG_ISADDR;
970 
971 	if (lba48) {
972 		tf.command = ATA_CMD_SET_MAX_EXT;
973 		tf.flags |= ATA_TFLAG_LBA48;
974 
975 		tf.hob_lbal = (new_sectors >> 24) & 0xff;
976 		tf.hob_lbam = (new_sectors >> 32) & 0xff;
977 		tf.hob_lbah = (new_sectors >> 40) & 0xff;
978 	} else {
979 		tf.command = ATA_CMD_SET_MAX;
980 
981 		tf.device |= (new_sectors >> 24) & 0xf;
982 	}
983 
984 	tf.protocol |= ATA_PROT_NODATA;
985 	tf.device |= ATA_LBA;
986 
987 	tf.lbal = (new_sectors >> 0) & 0xff;
988 	tf.lbam = (new_sectors >> 8) & 0xff;
989 	tf.lbah = (new_sectors >> 16) & 0xff;
990 
991 	err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
992 	if (err_mask) {
993 		ata_dev_printk(dev, KERN_WARNING, "failed to set "
994 			       "max address (err_mask=0x%x)\n", err_mask);
995 		if (err_mask == AC_ERR_DEV &&
996 		    (tf.feature & (ATA_ABORTED | ATA_IDNF)))
997 			return -EACCES;
998 		return -EIO;
999 	}
1000 
1001 	return 0;
1002 }
1003 
1004 /**
1005  *	ata_hpa_resize		-	Resize a device with an HPA set
1006  *	@dev: Device to resize
1007  *
1008  *	Read the size of an LBA28 or LBA48 disk with HPA features and resize
1009  *	it if required to the full size of the media. The caller must check
1010  *	the drive has the HPA feature set enabled.
1011  *
1012  *	RETURNS:
1013  *	0 on success, -errno on failure.
1014  */
1015 static int ata_hpa_resize(struct ata_device *dev)
1016 {
1017 	struct ata_eh_context *ehc = &dev->link->eh_context;
1018 	int print_info = ehc->i.flags & ATA_EHI_PRINTINFO;
1019 	u64 sectors = ata_id_n_sectors(dev->id);
1020 	u64 native_sectors;
1021 	int rc;
1022 
1023 	/* do we need to do it? */
1024 	if (dev->class != ATA_DEV_ATA ||
1025 	    !ata_id_has_lba(dev->id) || !ata_id_hpa_enabled(dev->id) ||
1026 	    (dev->horkage & ATA_HORKAGE_BROKEN_HPA))
1027 		return 0;
1028 
1029 	/* read native max address */
1030 	rc = ata_read_native_max_address(dev, &native_sectors);
1031 	if (rc) {
1032 		/* If HPA isn't going to be unlocked, skip HPA
1033 		 * resizing from the next try.
1034 		 */
1035 		if (!ata_ignore_hpa) {
1036 			ata_dev_printk(dev, KERN_WARNING, "HPA support seems "
1037 				       "broken, will skip HPA handling\n");
1038 			dev->horkage |= ATA_HORKAGE_BROKEN_HPA;
1039 
1040 			/* we can continue if device aborted the command */
1041 			if (rc == -EACCES)
1042 				rc = 0;
1043 		}
1044 
1045 		return rc;
1046 	}
1047 
1048 	/* nothing to do? */
1049 	if (native_sectors <= sectors || !ata_ignore_hpa) {
1050 		if (!print_info || native_sectors == sectors)
1051 			return 0;
1052 
1053 		if (native_sectors > sectors)
1054 			ata_dev_printk(dev, KERN_INFO,
1055 				"HPA detected: current %llu, native %llu\n",
1056 				(unsigned long long)sectors,
1057 				(unsigned long long)native_sectors);
1058 		else if (native_sectors < sectors)
1059 			ata_dev_printk(dev, KERN_WARNING,
1060 				"native sectors (%llu) is smaller than "
1061 				"sectors (%llu)\n",
1062 				(unsigned long long)native_sectors,
1063 				(unsigned long long)sectors);
1064 		return 0;
1065 	}
1066 
1067 	/* let's unlock HPA */
1068 	rc = ata_set_max_sectors(dev, native_sectors);
1069 	if (rc == -EACCES) {
1070 		/* if device aborted the command, skip HPA resizing */
1071 		ata_dev_printk(dev, KERN_WARNING, "device aborted resize "
1072 			       "(%llu -> %llu), skipping HPA handling\n",
1073 			       (unsigned long long)sectors,
1074 			       (unsigned long long)native_sectors);
1075 		dev->horkage |= ATA_HORKAGE_BROKEN_HPA;
1076 		return 0;
1077 	} else if (rc)
1078 		return rc;
1079 
1080 	/* re-read IDENTIFY data */
1081 	rc = ata_dev_reread_id(dev, 0);
1082 	if (rc) {
1083 		ata_dev_printk(dev, KERN_ERR, "failed to re-read IDENTIFY "
1084 			       "data after HPA resizing\n");
1085 		return rc;
1086 	}
1087 
1088 	if (print_info) {
1089 		u64 new_sectors = ata_id_n_sectors(dev->id);
1090 		ata_dev_printk(dev, KERN_INFO,
1091 			"HPA unlocked: %llu -> %llu, native %llu\n",
1092 			(unsigned long long)sectors,
1093 			(unsigned long long)new_sectors,
1094 			(unsigned long long)native_sectors);
1095 	}
1096 
1097 	return 0;
1098 }
1099 
1100 /**
1101  *	ata_id_to_dma_mode	-	Identify DMA mode from id block
1102  *	@dev: device to identify
1103  *	@unknown: mode to assume if we cannot tell
1104  *
1105  *	Set up the timing values for the device based upon the identify
1106  *	reported values for the DMA mode. This function is used by drivers
1107  *	which rely upon firmware configured modes, but wish to report the
1108  *	mode correctly when possible.
1109  *
1110  *	In addition we emit similarly formatted messages to the default
1111  *	ata_dev_set_mode handler, in order to provide consistency of
1112  *	presentation.
1113  */
1114 
1115 void ata_id_to_dma_mode(struct ata_device *dev, u8 unknown)
1116 {
1117 	unsigned int mask;
1118 	u8 mode;
1119 
1120 	/* Pack the DMA modes */
1121 	mask = ((dev->id[63] >> 8) << ATA_SHIFT_MWDMA) & ATA_MASK_MWDMA;
1122 	if (dev->id[53] & 0x04)
1123 		mask |= ((dev->id[88] >> 8) << ATA_SHIFT_UDMA) & ATA_MASK_UDMA;
1124 
1125 	/* Select the mode in use */
1126 	mode = ata_xfer_mask2mode(mask);
1127 
1128 	if (mode != 0) {
1129 		ata_dev_printk(dev, KERN_INFO, "configured for %s\n",
1130 		       ata_mode_string(mask));
1131 	} else {
1132 		/* SWDMA perhaps ? */
1133 		mode = unknown;
1134 		ata_dev_printk(dev, KERN_INFO, "configured for DMA\n");
1135 	}
1136 
1137 	/* Configure the device reporting */
1138 	dev->xfer_mode = mode;
1139 	dev->xfer_shift = ata_xfer_mode2shift(mode);
1140 }
1141 
1142 /**
1143  *	ata_noop_dev_select - Select device 0/1 on ATA bus
1144  *	@ap: ATA channel to manipulate
1145  *	@device: ATA device (numbered from zero) to select
1146  *
1147  *	This function performs no actual function.
1148  *
1149  *	May be used as the dev_select() entry in ata_port_operations.
1150  *
1151  *	LOCKING:
1152  *	caller.
1153  */
1154 void ata_noop_dev_select (struct ata_port *ap, unsigned int device)
1155 {
1156 }
1157 
1158 
1159 /**
1160  *	ata_std_dev_select - Select device 0/1 on ATA bus
1161  *	@ap: ATA channel to manipulate
1162  *	@device: ATA device (numbered from zero) to select
1163  *
1164  *	Use the method defined in the ATA specification to
1165  *	make either device 0, or device 1, active on the
1166  *	ATA channel.  Works with both PIO and MMIO.
1167  *
1168  *	May be used as the dev_select() entry in ata_port_operations.
1169  *
1170  *	LOCKING:
1171  *	caller.
1172  */
1173 
1174 void ata_std_dev_select (struct ata_port *ap, unsigned int device)
1175 {
1176 	u8 tmp;
1177 
1178 	if (device == 0)
1179 		tmp = ATA_DEVICE_OBS;
1180 	else
1181 		tmp = ATA_DEVICE_OBS | ATA_DEV1;
1182 
1183 	iowrite8(tmp, ap->ioaddr.device_addr);
1184 	ata_pause(ap);		/* needed; also flushes, for mmio */
1185 }
1186 
1187 /**
1188  *	ata_dev_select - Select device 0/1 on ATA bus
1189  *	@ap: ATA channel to manipulate
1190  *	@device: ATA device (numbered from zero) to select
1191  *	@wait: non-zero to wait for Status register BSY bit to clear
1192  *	@can_sleep: non-zero if context allows sleeping
1193  *
1194  *	Use the method defined in the ATA specification to
1195  *	make either device 0, or device 1, active on the
1196  *	ATA channel.
1197  *
1198  *	This is a high-level version of ata_std_dev_select(),
1199  *	which additionally provides the services of inserting
1200  *	the proper pauses and status polling, where needed.
1201  *
1202  *	LOCKING:
1203  *	caller.
1204  */
1205 
1206 void ata_dev_select(struct ata_port *ap, unsigned int device,
1207 			   unsigned int wait, unsigned int can_sleep)
1208 {
1209 	if (ata_msg_probe(ap))
1210 		ata_port_printk(ap, KERN_INFO, "ata_dev_select: ENTER, "
1211 				"device %u, wait %u\n", device, wait);
1212 
1213 	if (wait)
1214 		ata_wait_idle(ap);
1215 
1216 	ap->ops->dev_select(ap, device);
1217 
1218 	if (wait) {
1219 		if (can_sleep && ap->link.device[device].class == ATA_DEV_ATAPI)
1220 			msleep(150);
1221 		ata_wait_idle(ap);
1222 	}
1223 }
1224 
1225 /**
1226  *	ata_dump_id - IDENTIFY DEVICE info debugging output
1227  *	@id: IDENTIFY DEVICE page to dump
1228  *
1229  *	Dump selected 16-bit words from the given IDENTIFY DEVICE
1230  *	page.
1231  *
1232  *	LOCKING:
1233  *	caller.
1234  */
1235 
1236 static inline void ata_dump_id(const u16 *id)
1237 {
1238 	DPRINTK("49==0x%04x  "
1239 		"53==0x%04x  "
1240 		"63==0x%04x  "
1241 		"64==0x%04x  "
1242 		"75==0x%04x  \n",
1243 		id[49],
1244 		id[53],
1245 		id[63],
1246 		id[64],
1247 		id[75]);
1248 	DPRINTK("80==0x%04x  "
1249 		"81==0x%04x  "
1250 		"82==0x%04x  "
1251 		"83==0x%04x  "
1252 		"84==0x%04x  \n",
1253 		id[80],
1254 		id[81],
1255 		id[82],
1256 		id[83],
1257 		id[84]);
1258 	DPRINTK("88==0x%04x  "
1259 		"93==0x%04x\n",
1260 		id[88],
1261 		id[93]);
1262 }
1263 
1264 /**
1265  *	ata_id_xfermask - Compute xfermask from the given IDENTIFY data
1266  *	@id: IDENTIFY data to compute xfer mask from
1267  *
1268  *	Compute the xfermask for this device. This is not as trivial
1269  *	as it seems if we must consider early devices correctly.
1270  *
1271  *	FIXME: pre IDE drive timing (do we care ?).
1272  *
1273  *	LOCKING:
1274  *	None.
1275  *
1276  *	RETURNS:
1277  *	Computed xfermask
1278  */
1279 static unsigned int ata_id_xfermask(const u16 *id)
1280 {
1281 	unsigned int pio_mask, mwdma_mask, udma_mask;
1282 
1283 	/* Usual case. Word 53 indicates word 64 is valid */
1284 	if (id[ATA_ID_FIELD_VALID] & (1 << 1)) {
1285 		pio_mask = id[ATA_ID_PIO_MODES] & 0x03;
1286 		pio_mask <<= 3;
1287 		pio_mask |= 0x7;
1288 	} else {
1289 		/* If word 64 isn't valid then Word 51 high byte holds
1290 		 * the PIO timing number for the maximum. Turn it into
1291 		 * a mask.
1292 		 */
1293 		u8 mode = (id[ATA_ID_OLD_PIO_MODES] >> 8) & 0xFF;
1294 		if (mode < 5)	/* Valid PIO range */
1295                 	pio_mask = (2 << mode) - 1;
1296 		else
1297 			pio_mask = 1;
1298 
1299 		/* But wait.. there's more. Design your standards by
1300 		 * committee and you too can get a free iordy field to
1301 		 * process. However its the speeds not the modes that
1302 		 * are supported... Note drivers using the timing API
1303 		 * will get this right anyway
1304 		 */
1305 	}
1306 
1307 	mwdma_mask = id[ATA_ID_MWDMA_MODES] & 0x07;
1308 
1309 	if (ata_id_is_cfa(id)) {
1310 		/*
1311 		 *	Process compact flash extended modes
1312 		 */
1313 		int pio = id[163] & 0x7;
1314 		int dma = (id[163] >> 3) & 7;
1315 
1316 		if (pio)
1317 			pio_mask |= (1 << 5);
1318 		if (pio > 1)
1319 			pio_mask |= (1 << 6);
1320 		if (dma)
1321 			mwdma_mask |= (1 << 3);
1322 		if (dma > 1)
1323 			mwdma_mask |= (1 << 4);
1324 	}
1325 
1326 	udma_mask = 0;
1327 	if (id[ATA_ID_FIELD_VALID] & (1 << 2))
1328 		udma_mask = id[ATA_ID_UDMA_MODES] & 0xff;
1329 
1330 	return ata_pack_xfermask(pio_mask, mwdma_mask, udma_mask);
1331 }
1332 
1333 /**
1334  *	ata_port_queue_task - Queue port_task
1335  *	@ap: The ata_port to queue port_task for
1336  *	@fn: workqueue function to be scheduled
1337  *	@data: data for @fn to use
1338  *	@delay: delay time for workqueue function
1339  *
1340  *	Schedule @fn(@data) for execution after @delay jiffies using
1341  *	port_task.  There is one port_task per port and it's the
1342  *	user(low level driver)'s responsibility to make sure that only
1343  *	one task is active at any given time.
1344  *
1345  *	libata core layer takes care of synchronization between
1346  *	port_task and EH.  ata_port_queue_task() may be ignored for EH
1347  *	synchronization.
1348  *
1349  *	LOCKING:
1350  *	Inherited from caller.
1351  */
1352 void ata_port_queue_task(struct ata_port *ap, work_func_t fn, void *data,
1353 			 unsigned long delay)
1354 {
1355 	PREPARE_DELAYED_WORK(&ap->port_task, fn);
1356 	ap->port_task_data = data;
1357 
1358 	/* may fail if ata_port_flush_task() in progress */
1359 	queue_delayed_work(ata_wq, &ap->port_task, delay);
1360 }
1361 
1362 /**
1363  *	ata_port_flush_task - Flush port_task
1364  *	@ap: The ata_port to flush port_task for
1365  *
1366  *	After this function completes, port_task is guranteed not to
1367  *	be running or scheduled.
1368  *
1369  *	LOCKING:
1370  *	Kernel thread context (may sleep)
1371  */
1372 void ata_port_flush_task(struct ata_port *ap)
1373 {
1374 	DPRINTK("ENTER\n");
1375 
1376 	cancel_rearming_delayed_work(&ap->port_task);
1377 
1378 	if (ata_msg_ctl(ap))
1379 		ata_port_printk(ap, KERN_DEBUG, "%s: EXIT\n", __FUNCTION__);
1380 }
1381 
1382 static void ata_qc_complete_internal(struct ata_queued_cmd *qc)
1383 {
1384 	struct completion *waiting = qc->private_data;
1385 
1386 	complete(waiting);
1387 }
1388 
1389 /**
1390  *	ata_exec_internal_sg - execute libata internal command
1391  *	@dev: Device to which the command is sent
1392  *	@tf: Taskfile registers for the command and the result
1393  *	@cdb: CDB for packet command
1394  *	@dma_dir: Data tranfer direction of the command
1395  *	@sg: sg list for the data buffer of the command
1396  *	@n_elem: Number of sg entries
1397  *	@timeout: Timeout in msecs (0 for default)
1398  *
1399  *	Executes libata internal command with timeout.  @tf contains
1400  *	command on entry and result on return.  Timeout and error
1401  *	conditions are reported via return value.  No recovery action
1402  *	is taken after a command times out.  It's caller's duty to
1403  *	clean up after timeout.
1404  *
1405  *	LOCKING:
1406  *	None.  Should be called with kernel context, might sleep.
1407  *
1408  *	RETURNS:
1409  *	Zero on success, AC_ERR_* mask on failure
1410  */
1411 unsigned ata_exec_internal_sg(struct ata_device *dev,
1412 			      struct ata_taskfile *tf, const u8 *cdb,
1413 			      int dma_dir, struct scatterlist *sg,
1414 			      unsigned int n_elem, unsigned long timeout)
1415 {
1416 	struct ata_link *link = dev->link;
1417 	struct ata_port *ap = link->ap;
1418 	u8 command = tf->command;
1419 	struct ata_queued_cmd *qc;
1420 	unsigned int tag, preempted_tag;
1421 	u32 preempted_sactive, preempted_qc_active;
1422 	int preempted_nr_active_links;
1423 	DECLARE_COMPLETION_ONSTACK(wait);
1424 	unsigned long flags;
1425 	unsigned int err_mask;
1426 	int rc;
1427 
1428 	spin_lock_irqsave(ap->lock, flags);
1429 
1430 	/* no internal command while frozen */
1431 	if (ap->pflags & ATA_PFLAG_FROZEN) {
1432 		spin_unlock_irqrestore(ap->lock, flags);
1433 		return AC_ERR_SYSTEM;
1434 	}
1435 
1436 	/* initialize internal qc */
1437 
1438 	/* XXX: Tag 0 is used for drivers with legacy EH as some
1439 	 * drivers choke if any other tag is given.  This breaks
1440 	 * ata_tag_internal() test for those drivers.  Don't use new
1441 	 * EH stuff without converting to it.
1442 	 */
1443 	if (ap->ops->error_handler)
1444 		tag = ATA_TAG_INTERNAL;
1445 	else
1446 		tag = 0;
1447 
1448 	if (test_and_set_bit(tag, &ap->qc_allocated))
1449 		BUG();
1450 	qc = __ata_qc_from_tag(ap, tag);
1451 
1452 	qc->tag = tag;
1453 	qc->scsicmd = NULL;
1454 	qc->ap = ap;
1455 	qc->dev = dev;
1456 	ata_qc_reinit(qc);
1457 
1458 	preempted_tag = link->active_tag;
1459 	preempted_sactive = link->sactive;
1460 	preempted_qc_active = ap->qc_active;
1461 	preempted_nr_active_links = ap->nr_active_links;
1462 	link->active_tag = ATA_TAG_POISON;
1463 	link->sactive = 0;
1464 	ap->qc_active = 0;
1465 	ap->nr_active_links = 0;
1466 
1467 	/* prepare & issue qc */
1468 	qc->tf = *tf;
1469 	if (cdb)
1470 		memcpy(qc->cdb, cdb, ATAPI_CDB_LEN);
1471 	qc->flags |= ATA_QCFLAG_RESULT_TF;
1472 	qc->dma_dir = dma_dir;
1473 	if (dma_dir != DMA_NONE) {
1474 		unsigned int i, buflen = 0;
1475 
1476 		for (i = 0; i < n_elem; i++)
1477 			buflen += sg[i].length;
1478 
1479 		ata_sg_init(qc, sg, n_elem);
1480 		qc->nbytes = buflen;
1481 	}
1482 
1483 	qc->private_data = &wait;
1484 	qc->complete_fn = ata_qc_complete_internal;
1485 
1486 	ata_qc_issue(qc);
1487 
1488 	spin_unlock_irqrestore(ap->lock, flags);
1489 
1490 	if (!timeout)
1491 		timeout = ata_probe_timeout * 1000 / HZ;
1492 
1493 	rc = wait_for_completion_timeout(&wait, msecs_to_jiffies(timeout));
1494 
1495 	ata_port_flush_task(ap);
1496 
1497 	if (!rc) {
1498 		spin_lock_irqsave(ap->lock, flags);
1499 
1500 		/* We're racing with irq here.  If we lose, the
1501 		 * following test prevents us from completing the qc
1502 		 * twice.  If we win, the port is frozen and will be
1503 		 * cleaned up by ->post_internal_cmd().
1504 		 */
1505 		if (qc->flags & ATA_QCFLAG_ACTIVE) {
1506 			qc->err_mask |= AC_ERR_TIMEOUT;
1507 
1508 			if (ap->ops->error_handler)
1509 				ata_port_freeze(ap);
1510 			else
1511 				ata_qc_complete(qc);
1512 
1513 			if (ata_msg_warn(ap))
1514 				ata_dev_printk(dev, KERN_WARNING,
1515 					"qc timeout (cmd 0x%x)\n", command);
1516 		}
1517 
1518 		spin_unlock_irqrestore(ap->lock, flags);
1519 	}
1520 
1521 	/* do post_internal_cmd */
1522 	if (ap->ops->post_internal_cmd)
1523 		ap->ops->post_internal_cmd(qc);
1524 
1525 	/* perform minimal error analysis */
1526 	if (qc->flags & ATA_QCFLAG_FAILED) {
1527 		if (qc->result_tf.command & (ATA_ERR | ATA_DF))
1528 			qc->err_mask |= AC_ERR_DEV;
1529 
1530 		if (!qc->err_mask)
1531 			qc->err_mask |= AC_ERR_OTHER;
1532 
1533 		if (qc->err_mask & ~AC_ERR_OTHER)
1534 			qc->err_mask &= ~AC_ERR_OTHER;
1535 	}
1536 
1537 	/* finish up */
1538 	spin_lock_irqsave(ap->lock, flags);
1539 
1540 	*tf = qc->result_tf;
1541 	err_mask = qc->err_mask;
1542 
1543 	ata_qc_free(qc);
1544 	link->active_tag = preempted_tag;
1545 	link->sactive = preempted_sactive;
1546 	ap->qc_active = preempted_qc_active;
1547 	ap->nr_active_links = preempted_nr_active_links;
1548 
1549 	/* XXX - Some LLDDs (sata_mv) disable port on command failure.
1550 	 * Until those drivers are fixed, we detect the condition
1551 	 * here, fail the command with AC_ERR_SYSTEM and reenable the
1552 	 * port.
1553 	 *
1554 	 * Note that this doesn't change any behavior as internal
1555 	 * command failure results in disabling the device in the
1556 	 * higher layer for LLDDs without new reset/EH callbacks.
1557 	 *
1558 	 * Kill the following code as soon as those drivers are fixed.
1559 	 */
1560 	if (ap->flags & ATA_FLAG_DISABLED) {
1561 		err_mask |= AC_ERR_SYSTEM;
1562 		ata_port_probe(ap);
1563 	}
1564 
1565 	spin_unlock_irqrestore(ap->lock, flags);
1566 
1567 	return err_mask;
1568 }
1569 
1570 /**
1571  *	ata_exec_internal - execute libata internal command
1572  *	@dev: Device to which the command is sent
1573  *	@tf: Taskfile registers for the command and the result
1574  *	@cdb: CDB for packet command
1575  *	@dma_dir: Data tranfer direction of the command
1576  *	@buf: Data buffer of the command
1577  *	@buflen: Length of data buffer
1578  *	@timeout: Timeout in msecs (0 for default)
1579  *
1580  *	Wrapper around ata_exec_internal_sg() which takes simple
1581  *	buffer instead of sg list.
1582  *
1583  *	LOCKING:
1584  *	None.  Should be called with kernel context, might sleep.
1585  *
1586  *	RETURNS:
1587  *	Zero on success, AC_ERR_* mask on failure
1588  */
1589 unsigned ata_exec_internal(struct ata_device *dev,
1590 			   struct ata_taskfile *tf, const u8 *cdb,
1591 			   int dma_dir, void *buf, unsigned int buflen,
1592 			   unsigned long timeout)
1593 {
1594 	struct scatterlist *psg = NULL, sg;
1595 	unsigned int n_elem = 0;
1596 
1597 	if (dma_dir != DMA_NONE) {
1598 		WARN_ON(!buf);
1599 		sg_init_one(&sg, buf, buflen);
1600 		psg = &sg;
1601 		n_elem++;
1602 	}
1603 
1604 	return ata_exec_internal_sg(dev, tf, cdb, dma_dir, psg, n_elem,
1605 				    timeout);
1606 }
1607 
1608 /**
1609  *	ata_do_simple_cmd - execute simple internal command
1610  *	@dev: Device to which the command is sent
1611  *	@cmd: Opcode to execute
1612  *
1613  *	Execute a 'simple' command, that only consists of the opcode
1614  *	'cmd' itself, without filling any other registers
1615  *
1616  *	LOCKING:
1617  *	Kernel thread context (may sleep).
1618  *
1619  *	RETURNS:
1620  *	Zero on success, AC_ERR_* mask on failure
1621  */
1622 unsigned int ata_do_simple_cmd(struct ata_device *dev, u8 cmd)
1623 {
1624 	struct ata_taskfile tf;
1625 
1626 	ata_tf_init(dev, &tf);
1627 
1628 	tf.command = cmd;
1629 	tf.flags |= ATA_TFLAG_DEVICE;
1630 	tf.protocol = ATA_PROT_NODATA;
1631 
1632 	return ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
1633 }
1634 
1635 /**
1636  *	ata_pio_need_iordy	-	check if iordy needed
1637  *	@adev: ATA device
1638  *
1639  *	Check if the current speed of the device requires IORDY. Used
1640  *	by various controllers for chip configuration.
1641  */
1642 
1643 unsigned int ata_pio_need_iordy(const struct ata_device *adev)
1644 {
1645 	/* Controller doesn't support  IORDY. Probably a pointless check
1646 	   as the caller should know this */
1647 	if (adev->link->ap->flags & ATA_FLAG_NO_IORDY)
1648 		return 0;
1649 	/* PIO3 and higher it is mandatory */
1650 	if (adev->pio_mode > XFER_PIO_2)
1651 		return 1;
1652 	/* We turn it on when possible */
1653 	if (ata_id_has_iordy(adev->id))
1654 		return 1;
1655 	return 0;
1656 }
1657 
1658 /**
1659  *	ata_pio_mask_no_iordy	-	Return the non IORDY mask
1660  *	@adev: ATA device
1661  *
1662  *	Compute the highest mode possible if we are not using iordy. Return
1663  *	-1 if no iordy mode is available.
1664  */
1665 
1666 static u32 ata_pio_mask_no_iordy(const struct ata_device *adev)
1667 {
1668 	/* If we have no drive specific rule, then PIO 2 is non IORDY */
1669 	if (adev->id[ATA_ID_FIELD_VALID] & 2) {	/* EIDE */
1670 		u16 pio = adev->id[ATA_ID_EIDE_PIO];
1671 		/* Is the speed faster than the drive allows non IORDY ? */
1672 		if (pio) {
1673 			/* This is cycle times not frequency - watch the logic! */
1674 			if (pio > 240)	/* PIO2 is 240nS per cycle */
1675 				return 3 << ATA_SHIFT_PIO;
1676 			return 7 << ATA_SHIFT_PIO;
1677 		}
1678 	}
1679 	return 3 << ATA_SHIFT_PIO;
1680 }
1681 
1682 /**
1683  *	ata_dev_read_id - Read ID data from the specified device
1684  *	@dev: target device
1685  *	@p_class: pointer to class of the target device (may be changed)
1686  *	@flags: ATA_READID_* flags
1687  *	@id: buffer to read IDENTIFY data into
1688  *
1689  *	Read ID data from the specified device.  ATA_CMD_ID_ATA is
1690  *	performed on ATA devices and ATA_CMD_ID_ATAPI on ATAPI
1691  *	devices.  This function also issues ATA_CMD_INIT_DEV_PARAMS
1692  *	for pre-ATA4 drives.
1693  *
1694  *	FIXME: ATA_CMD_ID_ATA is optional for early drives and right
1695  *	now we abort if we hit that case.
1696  *
1697  *	LOCKING:
1698  *	Kernel thread context (may sleep)
1699  *
1700  *	RETURNS:
1701  *	0 on success, -errno otherwise.
1702  */
1703 int ata_dev_read_id(struct ata_device *dev, unsigned int *p_class,
1704 		    unsigned int flags, u16 *id)
1705 {
1706 	struct ata_port *ap = dev->link->ap;
1707 	unsigned int class = *p_class;
1708 	struct ata_taskfile tf;
1709 	unsigned int err_mask = 0;
1710 	const char *reason;
1711 	int may_fallback = 1, tried_spinup = 0;
1712 	int rc;
1713 
1714 	if (ata_msg_ctl(ap))
1715 		ata_dev_printk(dev, KERN_DEBUG, "%s: ENTER\n", __FUNCTION__);
1716 
1717 	ata_dev_select(ap, dev->devno, 1, 1); /* select device 0/1 */
1718  retry:
1719 	ata_tf_init(dev, &tf);
1720 
1721 	switch (class) {
1722 	case ATA_DEV_ATA:
1723 		tf.command = ATA_CMD_ID_ATA;
1724 		break;
1725 	case ATA_DEV_ATAPI:
1726 		tf.command = ATA_CMD_ID_ATAPI;
1727 		break;
1728 	default:
1729 		rc = -ENODEV;
1730 		reason = "unsupported class";
1731 		goto err_out;
1732 	}
1733 
1734 	tf.protocol = ATA_PROT_PIO;
1735 
1736 	/* Some devices choke if TF registers contain garbage.  Make
1737 	 * sure those are properly initialized.
1738 	 */
1739 	tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
1740 
1741 	/* Device presence detection is unreliable on some
1742 	 * controllers.  Always poll IDENTIFY if available.
1743 	 */
1744 	tf.flags |= ATA_TFLAG_POLLING;
1745 
1746 	err_mask = ata_exec_internal(dev, &tf, NULL, DMA_FROM_DEVICE,
1747 				     id, sizeof(id[0]) * ATA_ID_WORDS, 0);
1748 	if (err_mask) {
1749 		if (err_mask & AC_ERR_NODEV_HINT) {
1750 			DPRINTK("ata%u.%d: NODEV after polling detection\n",
1751 				ap->print_id, dev->devno);
1752 			return -ENOENT;
1753 		}
1754 
1755 		/* Device or controller might have reported the wrong
1756 		 * device class.  Give a shot at the other IDENTIFY if
1757 		 * the current one is aborted by the device.
1758 		 */
1759 		if (may_fallback &&
1760 		    (err_mask == AC_ERR_DEV) && (tf.feature & ATA_ABORTED)) {
1761 			may_fallback = 0;
1762 
1763 			if (class == ATA_DEV_ATA)
1764 				class = ATA_DEV_ATAPI;
1765 			else
1766 				class = ATA_DEV_ATA;
1767 			goto retry;
1768 		}
1769 
1770 		rc = -EIO;
1771 		reason = "I/O error";
1772 		goto err_out;
1773 	}
1774 
1775 	/* Falling back doesn't make sense if ID data was read
1776 	 * successfully at least once.
1777 	 */
1778 	may_fallback = 0;
1779 
1780 	swap_buf_le16(id, ATA_ID_WORDS);
1781 
1782 	/* sanity check */
1783 	rc = -EINVAL;
1784 	reason = "device reports invalid type";
1785 
1786 	if (class == ATA_DEV_ATA) {
1787 		if (!ata_id_is_ata(id) && !ata_id_is_cfa(id))
1788 			goto err_out;
1789 	} else {
1790 		if (ata_id_is_ata(id))
1791 			goto err_out;
1792 	}
1793 
1794 	if (!tried_spinup && (id[2] == 0x37c8 || id[2] == 0x738c)) {
1795 		tried_spinup = 1;
1796 		/*
1797 		 * Drive powered-up in standby mode, and requires a specific
1798 		 * SET_FEATURES spin-up subcommand before it will accept
1799 		 * anything other than the original IDENTIFY command.
1800 		 */
1801 		ata_tf_init(dev, &tf);
1802 		tf.command = ATA_CMD_SET_FEATURES;
1803 		tf.feature = SETFEATURES_SPINUP;
1804 		tf.protocol = ATA_PROT_NODATA;
1805 		tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
1806 		err_mask = ata_exec_internal(dev, &tf, NULL,
1807 					     DMA_NONE, NULL, 0, 0);
1808 		if (err_mask && id[2] != 0x738c) {
1809 			rc = -EIO;
1810 			reason = "SPINUP failed";
1811 			goto err_out;
1812 		}
1813 		/*
1814 		 * If the drive initially returned incomplete IDENTIFY info,
1815 		 * we now must reissue the IDENTIFY command.
1816 		 */
1817 		if (id[2] == 0x37c8)
1818 			goto retry;
1819 	}
1820 
1821 	if ((flags & ATA_READID_POSTRESET) && class == ATA_DEV_ATA) {
1822 		/*
1823 		 * The exact sequence expected by certain pre-ATA4 drives is:
1824 		 * SRST RESET
1825 		 * IDENTIFY (optional in early ATA)
1826 		 * INITIALIZE DEVICE PARAMETERS (later IDE and ATA)
1827 		 * anything else..
1828 		 * Some drives were very specific about that exact sequence.
1829 		 *
1830 		 * Note that ATA4 says lba is mandatory so the second check
1831 		 * shoud never trigger.
1832 		 */
1833 		if (ata_id_major_version(id) < 4 || !ata_id_has_lba(id)) {
1834 			err_mask = ata_dev_init_params(dev, id[3], id[6]);
1835 			if (err_mask) {
1836 				rc = -EIO;
1837 				reason = "INIT_DEV_PARAMS failed";
1838 				goto err_out;
1839 			}
1840 
1841 			/* current CHS translation info (id[53-58]) might be
1842 			 * changed. reread the identify device info.
1843 			 */
1844 			flags &= ~ATA_READID_POSTRESET;
1845 			goto retry;
1846 		}
1847 	}
1848 
1849 	*p_class = class;
1850 
1851 	return 0;
1852 
1853  err_out:
1854 	if (ata_msg_warn(ap))
1855 		ata_dev_printk(dev, KERN_WARNING, "failed to IDENTIFY "
1856 			       "(%s, err_mask=0x%x)\n", reason, err_mask);
1857 	return rc;
1858 }
1859 
1860 static inline u8 ata_dev_knobble(struct ata_device *dev)
1861 {
1862 	struct ata_port *ap = dev->link->ap;
1863 	return ((ap->cbl == ATA_CBL_SATA) && (!ata_id_is_sata(dev->id)));
1864 }
1865 
1866 static void ata_dev_config_ncq(struct ata_device *dev,
1867 			       char *desc, size_t desc_sz)
1868 {
1869 	struct ata_port *ap = dev->link->ap;
1870 	int hdepth = 0, ddepth = ata_id_queue_depth(dev->id);
1871 
1872 	if (!ata_id_has_ncq(dev->id)) {
1873 		desc[0] = '\0';
1874 		return;
1875 	}
1876 	if (dev->horkage & ATA_HORKAGE_NONCQ) {
1877 		snprintf(desc, desc_sz, "NCQ (not used)");
1878 		return;
1879 	}
1880 	if (ap->flags & ATA_FLAG_NCQ) {
1881 		hdepth = min(ap->scsi_host->can_queue, ATA_MAX_QUEUE - 1);
1882 		dev->flags |= ATA_DFLAG_NCQ;
1883 	}
1884 
1885 	if (hdepth >= ddepth)
1886 		snprintf(desc, desc_sz, "NCQ (depth %d)", ddepth);
1887 	else
1888 		snprintf(desc, desc_sz, "NCQ (depth %d/%d)", hdepth, ddepth);
1889 }
1890 
1891 /**
1892  *	ata_dev_configure - Configure the specified ATA/ATAPI device
1893  *	@dev: Target device to configure
1894  *
1895  *	Configure @dev according to @dev->id.  Generic and low-level
1896  *	driver specific fixups are also applied.
1897  *
1898  *	LOCKING:
1899  *	Kernel thread context (may sleep)
1900  *
1901  *	RETURNS:
1902  *	0 on success, -errno otherwise
1903  */
1904 int ata_dev_configure(struct ata_device *dev)
1905 {
1906 	struct ata_port *ap = dev->link->ap;
1907 	struct ata_eh_context *ehc = &dev->link->eh_context;
1908 	int print_info = ehc->i.flags & ATA_EHI_PRINTINFO;
1909 	const u16 *id = dev->id;
1910 	unsigned int xfer_mask;
1911 	char revbuf[7];		/* XYZ-99\0 */
1912 	char fwrevbuf[ATA_ID_FW_REV_LEN+1];
1913 	char modelbuf[ATA_ID_PROD_LEN+1];
1914 	int rc;
1915 
1916 	if (!ata_dev_enabled(dev) && ata_msg_info(ap)) {
1917 		ata_dev_printk(dev, KERN_INFO, "%s: ENTER/EXIT -- nodev\n",
1918 			       __FUNCTION__);
1919 		return 0;
1920 	}
1921 
1922 	if (ata_msg_probe(ap))
1923 		ata_dev_printk(dev, KERN_DEBUG, "%s: ENTER\n", __FUNCTION__);
1924 
1925 	/* set horkage */
1926 	dev->horkage |= ata_dev_blacklisted(dev);
1927 
1928 	/* let ACPI work its magic */
1929 	rc = ata_acpi_on_devcfg(dev);
1930 	if (rc)
1931 		return rc;
1932 
1933 	/* massage HPA, do it early as it might change IDENTIFY data */
1934 	rc = ata_hpa_resize(dev);
1935 	if (rc)
1936 		return rc;
1937 
1938 	/* print device capabilities */
1939 	if (ata_msg_probe(ap))
1940 		ata_dev_printk(dev, KERN_DEBUG,
1941 			       "%s: cfg 49:%04x 82:%04x 83:%04x 84:%04x "
1942 			       "85:%04x 86:%04x 87:%04x 88:%04x\n",
1943 			       __FUNCTION__,
1944 			       id[49], id[82], id[83], id[84],
1945 			       id[85], id[86], id[87], id[88]);
1946 
1947 	/* initialize to-be-configured parameters */
1948 	dev->flags &= ~ATA_DFLAG_CFG_MASK;
1949 	dev->max_sectors = 0;
1950 	dev->cdb_len = 0;
1951 	dev->n_sectors = 0;
1952 	dev->cylinders = 0;
1953 	dev->heads = 0;
1954 	dev->sectors = 0;
1955 
1956 	/*
1957 	 * common ATA, ATAPI feature tests
1958 	 */
1959 
1960 	/* find max transfer mode; for printk only */
1961 	xfer_mask = ata_id_xfermask(id);
1962 
1963 	if (ata_msg_probe(ap))
1964 		ata_dump_id(id);
1965 
1966 	/* SCSI only uses 4-char revisions, dump full 8 chars from ATA */
1967 	ata_id_c_string(dev->id, fwrevbuf, ATA_ID_FW_REV,
1968 			sizeof(fwrevbuf));
1969 
1970 	ata_id_c_string(dev->id, modelbuf, ATA_ID_PROD,
1971 			sizeof(modelbuf));
1972 
1973 	/* ATA-specific feature tests */
1974 	if (dev->class == ATA_DEV_ATA) {
1975 		if (ata_id_is_cfa(id)) {
1976 			if (id[162] & 1) /* CPRM may make this media unusable */
1977 				ata_dev_printk(dev, KERN_WARNING,
1978 					       "supports DRM functions and may "
1979 					       "not be fully accessable.\n");
1980 			snprintf(revbuf, 7, "CFA");
1981 		}
1982 		else
1983 			snprintf(revbuf, 7, "ATA-%d",  ata_id_major_version(id));
1984 
1985 		dev->n_sectors = ata_id_n_sectors(id);
1986 
1987 		if (dev->id[59] & 0x100)
1988 			dev->multi_count = dev->id[59] & 0xff;
1989 
1990 		if (ata_id_has_lba(id)) {
1991 			const char *lba_desc;
1992 			char ncq_desc[20];
1993 
1994 			lba_desc = "LBA";
1995 			dev->flags |= ATA_DFLAG_LBA;
1996 			if (ata_id_has_lba48(id)) {
1997 				dev->flags |= ATA_DFLAG_LBA48;
1998 				lba_desc = "LBA48";
1999 
2000 				if (dev->n_sectors >= (1UL << 28) &&
2001 				    ata_id_has_flush_ext(id))
2002 					dev->flags |= ATA_DFLAG_FLUSH_EXT;
2003 			}
2004 
2005 			/* config NCQ */
2006 			ata_dev_config_ncq(dev, ncq_desc, sizeof(ncq_desc));
2007 
2008 			/* print device info to dmesg */
2009 			if (ata_msg_drv(ap) && print_info) {
2010 				ata_dev_printk(dev, KERN_INFO,
2011 					"%s: %s, %s, max %s\n",
2012 					revbuf, modelbuf, fwrevbuf,
2013 					ata_mode_string(xfer_mask));
2014 				ata_dev_printk(dev, KERN_INFO,
2015 					"%Lu sectors, multi %u: %s %s\n",
2016 					(unsigned long long)dev->n_sectors,
2017 					dev->multi_count, lba_desc, ncq_desc);
2018 			}
2019 		} else {
2020 			/* CHS */
2021 
2022 			/* Default translation */
2023 			dev->cylinders	= id[1];
2024 			dev->heads	= id[3];
2025 			dev->sectors	= id[6];
2026 
2027 			if (ata_id_current_chs_valid(id)) {
2028 				/* Current CHS translation is valid. */
2029 				dev->cylinders = id[54];
2030 				dev->heads     = id[55];
2031 				dev->sectors   = id[56];
2032 			}
2033 
2034 			/* print device info to dmesg */
2035 			if (ata_msg_drv(ap) && print_info) {
2036 				ata_dev_printk(dev, KERN_INFO,
2037 					"%s: %s, %s, max %s\n",
2038 					revbuf,	modelbuf, fwrevbuf,
2039 					ata_mode_string(xfer_mask));
2040 				ata_dev_printk(dev, KERN_INFO,
2041 					"%Lu sectors, multi %u, CHS %u/%u/%u\n",
2042 					(unsigned long long)dev->n_sectors,
2043 					dev->multi_count, dev->cylinders,
2044 					dev->heads, dev->sectors);
2045 			}
2046 		}
2047 
2048 		dev->cdb_len = 16;
2049 	}
2050 
2051 	/* ATAPI-specific feature tests */
2052 	else if (dev->class == ATA_DEV_ATAPI) {
2053 		const char *cdb_intr_string = "";
2054 		const char *atapi_an_string = "";
2055 		u32 sntf;
2056 
2057 		rc = atapi_cdb_len(id);
2058 		if ((rc < 12) || (rc > ATAPI_CDB_LEN)) {
2059 			if (ata_msg_warn(ap))
2060 				ata_dev_printk(dev, KERN_WARNING,
2061 					       "unsupported CDB len\n");
2062 			rc = -EINVAL;
2063 			goto err_out_nosup;
2064 		}
2065 		dev->cdb_len = (unsigned int) rc;
2066 
2067 		/* Enable ATAPI AN if both the host and device have
2068 		 * the support.  If PMP is attached, SNTF is required
2069 		 * to enable ATAPI AN to discern between PHY status
2070 		 * changed notifications and ATAPI ANs.
2071 		 */
2072 		if ((ap->flags & ATA_FLAG_AN) && ata_id_has_atapi_AN(id) &&
2073 		    (!ap->nr_pmp_links ||
2074 		     sata_scr_read(&ap->link, SCR_NOTIFICATION, &sntf) == 0)) {
2075 			unsigned int err_mask;
2076 
2077 			/* issue SET feature command to turn this on */
2078 			err_mask = ata_dev_set_AN(dev, SETFEATURES_SATA_ENABLE);
2079 			if (err_mask)
2080 				ata_dev_printk(dev, KERN_ERR,
2081 					"failed to enable ATAPI AN "
2082 					"(err_mask=0x%x)\n", err_mask);
2083 			else {
2084 				dev->flags |= ATA_DFLAG_AN;
2085 				atapi_an_string = ", ATAPI AN";
2086 			}
2087 		}
2088 
2089 		if (ata_id_cdb_intr(dev->id)) {
2090 			dev->flags |= ATA_DFLAG_CDB_INTR;
2091 			cdb_intr_string = ", CDB intr";
2092 		}
2093 
2094 		/* print device info to dmesg */
2095 		if (ata_msg_drv(ap) && print_info)
2096 			ata_dev_printk(dev, KERN_INFO,
2097 				       "ATAPI: %s, %s, max %s%s%s\n",
2098 				       modelbuf, fwrevbuf,
2099 				       ata_mode_string(xfer_mask),
2100 				       cdb_intr_string, atapi_an_string);
2101 	}
2102 
2103 	/* determine max_sectors */
2104 	dev->max_sectors = ATA_MAX_SECTORS;
2105 	if (dev->flags & ATA_DFLAG_LBA48)
2106 		dev->max_sectors = ATA_MAX_SECTORS_LBA48;
2107 
2108 	if (dev->horkage & ATA_HORKAGE_DIAGNOSTIC) {
2109 		/* Let the user know. We don't want to disallow opens for
2110 		   rescue purposes, or in case the vendor is just a blithering
2111 		   idiot */
2112                 if (print_info) {
2113 			ata_dev_printk(dev, KERN_WARNING,
2114 "Drive reports diagnostics failure. This may indicate a drive\n");
2115 			ata_dev_printk(dev, KERN_WARNING,
2116 "fault or invalid emulation. Contact drive vendor for information.\n");
2117 		}
2118 	}
2119 
2120 	/* limit bridge transfers to udma5, 200 sectors */
2121 	if (ata_dev_knobble(dev)) {
2122 		if (ata_msg_drv(ap) && print_info)
2123 			ata_dev_printk(dev, KERN_INFO,
2124 				       "applying bridge limits\n");
2125 		dev->udma_mask &= ATA_UDMA5;
2126 		dev->max_sectors = ATA_MAX_SECTORS;
2127 	}
2128 
2129 	if (dev->horkage & ATA_HORKAGE_MAX_SEC_128)
2130 		dev->max_sectors = min_t(unsigned int, ATA_MAX_SECTORS_128,
2131 					 dev->max_sectors);
2132 
2133 	if (ap->ops->dev_config)
2134 		ap->ops->dev_config(dev);
2135 
2136 	if (ata_msg_probe(ap))
2137 		ata_dev_printk(dev, KERN_DEBUG, "%s: EXIT, drv_stat = 0x%x\n",
2138 			__FUNCTION__, ata_chk_status(ap));
2139 	return 0;
2140 
2141 err_out_nosup:
2142 	if (ata_msg_probe(ap))
2143 		ata_dev_printk(dev, KERN_DEBUG,
2144 			       "%s: EXIT, err\n", __FUNCTION__);
2145 	return rc;
2146 }
2147 
2148 /**
2149  *	ata_cable_40wire	-	return 40 wire cable type
2150  *	@ap: port
2151  *
2152  *	Helper method for drivers which want to hardwire 40 wire cable
2153  *	detection.
2154  */
2155 
2156 int ata_cable_40wire(struct ata_port *ap)
2157 {
2158 	return ATA_CBL_PATA40;
2159 }
2160 
2161 /**
2162  *	ata_cable_80wire	-	return 80 wire cable type
2163  *	@ap: port
2164  *
2165  *	Helper method for drivers which want to hardwire 80 wire cable
2166  *	detection.
2167  */
2168 
2169 int ata_cable_80wire(struct ata_port *ap)
2170 {
2171 	return ATA_CBL_PATA80;
2172 }
2173 
2174 /**
2175  *	ata_cable_unknown	-	return unknown PATA cable.
2176  *	@ap: port
2177  *
2178  *	Helper method for drivers which have no PATA cable detection.
2179  */
2180 
2181 int ata_cable_unknown(struct ata_port *ap)
2182 {
2183 	return ATA_CBL_PATA_UNK;
2184 }
2185 
2186 /**
2187  *	ata_cable_sata	-	return SATA cable type
2188  *	@ap: port
2189  *
2190  *	Helper method for drivers which have SATA cables
2191  */
2192 
2193 int ata_cable_sata(struct ata_port *ap)
2194 {
2195 	return ATA_CBL_SATA;
2196 }
2197 
2198 /**
2199  *	ata_bus_probe - Reset and probe ATA bus
2200  *	@ap: Bus to probe
2201  *
2202  *	Master ATA bus probing function.  Initiates a hardware-dependent
2203  *	bus reset, then attempts to identify any devices found on
2204  *	the bus.
2205  *
2206  *	LOCKING:
2207  *	PCI/etc. bus probe sem.
2208  *
2209  *	RETURNS:
2210  *	Zero on success, negative errno otherwise.
2211  */
2212 
2213 int ata_bus_probe(struct ata_port *ap)
2214 {
2215 	unsigned int classes[ATA_MAX_DEVICES];
2216 	int tries[ATA_MAX_DEVICES];
2217 	int rc;
2218 	struct ata_device *dev;
2219 
2220 	ata_port_probe(ap);
2221 
2222 	ata_link_for_each_dev(dev, &ap->link)
2223 		tries[dev->devno] = ATA_PROBE_MAX_TRIES;
2224 
2225  retry:
2226 	/* reset and determine device classes */
2227 	ap->ops->phy_reset(ap);
2228 
2229 	ata_link_for_each_dev(dev, &ap->link) {
2230 		if (!(ap->flags & ATA_FLAG_DISABLED) &&
2231 		    dev->class != ATA_DEV_UNKNOWN)
2232 			classes[dev->devno] = dev->class;
2233 		else
2234 			classes[dev->devno] = ATA_DEV_NONE;
2235 
2236 		dev->class = ATA_DEV_UNKNOWN;
2237 	}
2238 
2239 	ata_port_probe(ap);
2240 
2241 	/* after the reset the device state is PIO 0 and the controller
2242 	   state is undefined. Record the mode */
2243 
2244 	ata_link_for_each_dev(dev, &ap->link)
2245 		dev->pio_mode = XFER_PIO_0;
2246 
2247 	/* read IDENTIFY page and configure devices. We have to do the identify
2248 	   specific sequence bass-ackwards so that PDIAG- is released by
2249 	   the slave device */
2250 
2251 	ata_link_for_each_dev(dev, &ap->link) {
2252 		if (tries[dev->devno])
2253 			dev->class = classes[dev->devno];
2254 
2255 		if (!ata_dev_enabled(dev))
2256 			continue;
2257 
2258 		rc = ata_dev_read_id(dev, &dev->class, ATA_READID_POSTRESET,
2259 				     dev->id);
2260 		if (rc)
2261 			goto fail;
2262 	}
2263 
2264 	/* Now ask for the cable type as PDIAG- should have been released */
2265 	if (ap->ops->cable_detect)
2266 		ap->cbl = ap->ops->cable_detect(ap);
2267 
2268 	/* We may have SATA bridge glue hiding here irrespective of the
2269 	   reported cable types and sensed types */
2270 	ata_link_for_each_dev(dev, &ap->link) {
2271 		if (!ata_dev_enabled(dev))
2272 			continue;
2273 		/* SATA drives indicate we have a bridge. We don't know which
2274 		   end of the link the bridge is which is a problem */
2275 		if (ata_id_is_sata(dev->id))
2276 			ap->cbl = ATA_CBL_SATA;
2277 	}
2278 
2279 	/* After the identify sequence we can now set up the devices. We do
2280 	   this in the normal order so that the user doesn't get confused */
2281 
2282 	ata_link_for_each_dev(dev, &ap->link) {
2283 		if (!ata_dev_enabled(dev))
2284 			continue;
2285 
2286 		ap->link.eh_context.i.flags |= ATA_EHI_PRINTINFO;
2287 		rc = ata_dev_configure(dev);
2288 		ap->link.eh_context.i.flags &= ~ATA_EHI_PRINTINFO;
2289 		if (rc)
2290 			goto fail;
2291 	}
2292 
2293 	/* configure transfer mode */
2294 	rc = ata_set_mode(&ap->link, &dev);
2295 	if (rc)
2296 		goto fail;
2297 
2298 	ata_link_for_each_dev(dev, &ap->link)
2299 		if (ata_dev_enabled(dev))
2300 			return 0;
2301 
2302 	/* no device present, disable port */
2303 	ata_port_disable(ap);
2304 	return -ENODEV;
2305 
2306  fail:
2307 	tries[dev->devno]--;
2308 
2309 	switch (rc) {
2310 	case -EINVAL:
2311 		/* eeek, something went very wrong, give up */
2312 		tries[dev->devno] = 0;
2313 		break;
2314 
2315 	case -ENODEV:
2316 		/* give it just one more chance */
2317 		tries[dev->devno] = min(tries[dev->devno], 1);
2318 	case -EIO:
2319 		if (tries[dev->devno] == 1) {
2320 			/* This is the last chance, better to slow
2321 			 * down than lose it.
2322 			 */
2323 			sata_down_spd_limit(&ap->link);
2324 			ata_down_xfermask_limit(dev, ATA_DNXFER_PIO);
2325 		}
2326 	}
2327 
2328 	if (!tries[dev->devno])
2329 		ata_dev_disable(dev);
2330 
2331 	goto retry;
2332 }
2333 
2334 /**
2335  *	ata_port_probe - Mark port as enabled
2336  *	@ap: Port for which we indicate enablement
2337  *
2338  *	Modify @ap data structure such that the system
2339  *	thinks that the entire port is enabled.
2340  *
2341  *	LOCKING: host lock, or some other form of
2342  *	serialization.
2343  */
2344 
2345 void ata_port_probe(struct ata_port *ap)
2346 {
2347 	ap->flags &= ~ATA_FLAG_DISABLED;
2348 }
2349 
2350 /**
2351  *	sata_print_link_status - Print SATA link status
2352  *	@link: SATA link to printk link status about
2353  *
2354  *	This function prints link speed and status of a SATA link.
2355  *
2356  *	LOCKING:
2357  *	None.
2358  */
2359 void sata_print_link_status(struct ata_link *link)
2360 {
2361 	u32 sstatus, scontrol, tmp;
2362 
2363 	if (sata_scr_read(link, SCR_STATUS, &sstatus))
2364 		return;
2365 	sata_scr_read(link, SCR_CONTROL, &scontrol);
2366 
2367 	if (ata_link_online(link)) {
2368 		tmp = (sstatus >> 4) & 0xf;
2369 		ata_link_printk(link, KERN_INFO,
2370 				"SATA link up %s (SStatus %X SControl %X)\n",
2371 				sata_spd_string(tmp), sstatus, scontrol);
2372 	} else {
2373 		ata_link_printk(link, KERN_INFO,
2374 				"SATA link down (SStatus %X SControl %X)\n",
2375 				sstatus, scontrol);
2376 	}
2377 }
2378 
2379 /**
2380  *	__sata_phy_reset - Wake/reset a low-level SATA PHY
2381  *	@ap: SATA port associated with target SATA PHY.
2382  *
2383  *	This function issues commands to standard SATA Sxxx
2384  *	PHY registers, to wake up the phy (and device), and
2385  *	clear any reset condition.
2386  *
2387  *	LOCKING:
2388  *	PCI/etc. bus probe sem.
2389  *
2390  */
2391 void __sata_phy_reset(struct ata_port *ap)
2392 {
2393 	struct ata_link *link = &ap->link;
2394 	unsigned long timeout = jiffies + (HZ * 5);
2395 	u32 sstatus;
2396 
2397 	if (ap->flags & ATA_FLAG_SATA_RESET) {
2398 		/* issue phy wake/reset */
2399 		sata_scr_write_flush(link, SCR_CONTROL, 0x301);
2400 		/* Couldn't find anything in SATA I/II specs, but
2401 		 * AHCI-1.1 10.4.2 says at least 1 ms. */
2402 		mdelay(1);
2403 	}
2404 	/* phy wake/clear reset */
2405 	sata_scr_write_flush(link, SCR_CONTROL, 0x300);
2406 
2407 	/* wait for phy to become ready, if necessary */
2408 	do {
2409 		msleep(200);
2410 		sata_scr_read(link, SCR_STATUS, &sstatus);
2411 		if ((sstatus & 0xf) != 1)
2412 			break;
2413 	} while (time_before(jiffies, timeout));
2414 
2415 	/* print link status */
2416 	sata_print_link_status(link);
2417 
2418 	/* TODO: phy layer with polling, timeouts, etc. */
2419 	if (!ata_link_offline(link))
2420 		ata_port_probe(ap);
2421 	else
2422 		ata_port_disable(ap);
2423 
2424 	if (ap->flags & ATA_FLAG_DISABLED)
2425 		return;
2426 
2427 	if (ata_busy_sleep(ap, ATA_TMOUT_BOOT_QUICK, ATA_TMOUT_BOOT)) {
2428 		ata_port_disable(ap);
2429 		return;
2430 	}
2431 
2432 	ap->cbl = ATA_CBL_SATA;
2433 }
2434 
2435 /**
2436  *	sata_phy_reset - Reset SATA bus.
2437  *	@ap: SATA port associated with target SATA PHY.
2438  *
2439  *	This function resets the SATA bus, and then probes
2440  *	the bus for devices.
2441  *
2442  *	LOCKING:
2443  *	PCI/etc. bus probe sem.
2444  *
2445  */
2446 void sata_phy_reset(struct ata_port *ap)
2447 {
2448 	__sata_phy_reset(ap);
2449 	if (ap->flags & ATA_FLAG_DISABLED)
2450 		return;
2451 	ata_bus_reset(ap);
2452 }
2453 
2454 /**
2455  *	ata_dev_pair		-	return other device on cable
2456  *	@adev: device
2457  *
2458  *	Obtain the other device on the same cable, or if none is
2459  *	present NULL is returned
2460  */
2461 
2462 struct ata_device *ata_dev_pair(struct ata_device *adev)
2463 {
2464 	struct ata_link *link = adev->link;
2465 	struct ata_device *pair = &link->device[1 - adev->devno];
2466 	if (!ata_dev_enabled(pair))
2467 		return NULL;
2468 	return pair;
2469 }
2470 
2471 /**
2472  *	ata_port_disable - Disable port.
2473  *	@ap: Port to be disabled.
2474  *
2475  *	Modify @ap data structure such that the system
2476  *	thinks that the entire port is disabled, and should
2477  *	never attempt to probe or communicate with devices
2478  *	on this port.
2479  *
2480  *	LOCKING: host lock, or some other form of
2481  *	serialization.
2482  */
2483 
2484 void ata_port_disable(struct ata_port *ap)
2485 {
2486 	ap->link.device[0].class = ATA_DEV_NONE;
2487 	ap->link.device[1].class = ATA_DEV_NONE;
2488 	ap->flags |= ATA_FLAG_DISABLED;
2489 }
2490 
2491 /**
2492  *	sata_down_spd_limit - adjust SATA spd limit downward
2493  *	@link: Link to adjust SATA spd limit for
2494  *
2495  *	Adjust SATA spd limit of @link downward.  Note that this
2496  *	function only adjusts the limit.  The change must be applied
2497  *	using sata_set_spd().
2498  *
2499  *	LOCKING:
2500  *	Inherited from caller.
2501  *
2502  *	RETURNS:
2503  *	0 on success, negative errno on failure
2504  */
2505 int sata_down_spd_limit(struct ata_link *link)
2506 {
2507 	u32 sstatus, spd, mask;
2508 	int rc, highbit;
2509 
2510 	if (!sata_scr_valid(link))
2511 		return -EOPNOTSUPP;
2512 
2513 	/* If SCR can be read, use it to determine the current SPD.
2514 	 * If not, use cached value in link->sata_spd.
2515 	 */
2516 	rc = sata_scr_read(link, SCR_STATUS, &sstatus);
2517 	if (rc == 0)
2518 		spd = (sstatus >> 4) & 0xf;
2519 	else
2520 		spd = link->sata_spd;
2521 
2522 	mask = link->sata_spd_limit;
2523 	if (mask <= 1)
2524 		return -EINVAL;
2525 
2526 	/* unconditionally mask off the highest bit */
2527 	highbit = fls(mask) - 1;
2528 	mask &= ~(1 << highbit);
2529 
2530 	/* Mask off all speeds higher than or equal to the current
2531 	 * one.  Force 1.5Gbps if current SPD is not available.
2532 	 */
2533 	if (spd > 1)
2534 		mask &= (1 << (spd - 1)) - 1;
2535 	else
2536 		mask &= 1;
2537 
2538 	/* were we already at the bottom? */
2539 	if (!mask)
2540 		return -EINVAL;
2541 
2542 	link->sata_spd_limit = mask;
2543 
2544 	ata_link_printk(link, KERN_WARNING, "limiting SATA link speed to %s\n",
2545 			sata_spd_string(fls(mask)));
2546 
2547 	return 0;
2548 }
2549 
2550 static int __sata_set_spd_needed(struct ata_link *link, u32 *scontrol)
2551 {
2552 	u32 spd, limit;
2553 
2554 	if (link->sata_spd_limit == UINT_MAX)
2555 		limit = 0;
2556 	else
2557 		limit = fls(link->sata_spd_limit);
2558 
2559 	spd = (*scontrol >> 4) & 0xf;
2560 	*scontrol = (*scontrol & ~0xf0) | ((limit & 0xf) << 4);
2561 
2562 	return spd != limit;
2563 }
2564 
2565 /**
2566  *	sata_set_spd_needed - is SATA spd configuration needed
2567  *	@link: Link in question
2568  *
2569  *	Test whether the spd limit in SControl matches
2570  *	@link->sata_spd_limit.  This function is used to determine
2571  *	whether hardreset is necessary to apply SATA spd
2572  *	configuration.
2573  *
2574  *	LOCKING:
2575  *	Inherited from caller.
2576  *
2577  *	RETURNS:
2578  *	1 if SATA spd configuration is needed, 0 otherwise.
2579  */
2580 int sata_set_spd_needed(struct ata_link *link)
2581 {
2582 	u32 scontrol;
2583 
2584 	if (sata_scr_read(link, SCR_CONTROL, &scontrol))
2585 		return 0;
2586 
2587 	return __sata_set_spd_needed(link, &scontrol);
2588 }
2589 
2590 /**
2591  *	sata_set_spd - set SATA spd according to spd limit
2592  *	@link: Link to set SATA spd for
2593  *
2594  *	Set SATA spd of @link according to sata_spd_limit.
2595  *
2596  *	LOCKING:
2597  *	Inherited from caller.
2598  *
2599  *	RETURNS:
2600  *	0 if spd doesn't need to be changed, 1 if spd has been
2601  *	changed.  Negative errno if SCR registers are inaccessible.
2602  */
2603 int sata_set_spd(struct ata_link *link)
2604 {
2605 	u32 scontrol;
2606 	int rc;
2607 
2608 	if ((rc = sata_scr_read(link, SCR_CONTROL, &scontrol)))
2609 		return rc;
2610 
2611 	if (!__sata_set_spd_needed(link, &scontrol))
2612 		return 0;
2613 
2614 	if ((rc = sata_scr_write(link, SCR_CONTROL, scontrol)))
2615 		return rc;
2616 
2617 	return 1;
2618 }
2619 
2620 /*
2621  * This mode timing computation functionality is ported over from
2622  * drivers/ide/ide-timing.h and was originally written by Vojtech Pavlik
2623  */
2624 /*
2625  * PIO 0-4, MWDMA 0-2 and UDMA 0-6 timings (in nanoseconds).
2626  * These were taken from ATA/ATAPI-6 standard, rev 0a, except
2627  * for UDMA6, which is currently supported only by Maxtor drives.
2628  *
2629  * For PIO 5/6 MWDMA 3/4 see the CFA specification 3.0.
2630  */
2631 
2632 static const struct ata_timing ata_timing[] = {
2633 
2634 	{ XFER_UDMA_6,     0,   0,   0,   0,   0,   0,   0,  15 },
2635 	{ XFER_UDMA_5,     0,   0,   0,   0,   0,   0,   0,  20 },
2636 	{ XFER_UDMA_4,     0,   0,   0,   0,   0,   0,   0,  30 },
2637 	{ XFER_UDMA_3,     0,   0,   0,   0,   0,   0,   0,  45 },
2638 
2639 	{ XFER_MW_DMA_4,  25,   0,   0,   0,  55,  20,  80,   0 },
2640 	{ XFER_MW_DMA_3,  25,   0,   0,   0,  65,  25, 100,   0 },
2641 	{ XFER_UDMA_2,     0,   0,   0,   0,   0,   0,   0,  60 },
2642 	{ XFER_UDMA_1,     0,   0,   0,   0,   0,   0,   0,  80 },
2643 	{ XFER_UDMA_0,     0,   0,   0,   0,   0,   0,   0, 120 },
2644 
2645 /*	{ XFER_UDMA_SLOW,  0,   0,   0,   0,   0,   0,   0, 150 }, */
2646 
2647 	{ XFER_MW_DMA_2,  25,   0,   0,   0,  70,  25, 120,   0 },
2648 	{ XFER_MW_DMA_1,  45,   0,   0,   0,  80,  50, 150,   0 },
2649 	{ XFER_MW_DMA_0,  60,   0,   0,   0, 215, 215, 480,   0 },
2650 
2651 	{ XFER_SW_DMA_2,  60,   0,   0,   0, 120, 120, 240,   0 },
2652 	{ XFER_SW_DMA_1,  90,   0,   0,   0, 240, 240, 480,   0 },
2653 	{ XFER_SW_DMA_0, 120,   0,   0,   0, 480, 480, 960,   0 },
2654 
2655 	{ XFER_PIO_6,     10,  55,  20,  80,  55,  20,  80,   0 },
2656 	{ XFER_PIO_5,     15,  65,  25, 100,  65,  25, 100,   0 },
2657 	{ XFER_PIO_4,     25,  70,  25, 120,  70,  25, 120,   0 },
2658 	{ XFER_PIO_3,     30,  80,  70, 180,  80,  70, 180,   0 },
2659 
2660 	{ XFER_PIO_2,     30, 290,  40, 330, 100,  90, 240,   0 },
2661 	{ XFER_PIO_1,     50, 290,  93, 383, 125, 100, 383,   0 },
2662 	{ XFER_PIO_0,     70, 290, 240, 600, 165, 150, 600,   0 },
2663 
2664 /*	{ XFER_PIO_SLOW, 120, 290, 240, 960, 290, 240, 960,   0 }, */
2665 
2666 	{ 0xFF }
2667 };
2668 
2669 #define ENOUGH(v,unit)		(((v)-1)/(unit)+1)
2670 #define EZ(v,unit)		((v)?ENOUGH(v,unit):0)
2671 
2672 static void ata_timing_quantize(const struct ata_timing *t, struct ata_timing *q, int T, int UT)
2673 {
2674 	q->setup   = EZ(t->setup   * 1000,  T);
2675 	q->act8b   = EZ(t->act8b   * 1000,  T);
2676 	q->rec8b   = EZ(t->rec8b   * 1000,  T);
2677 	q->cyc8b   = EZ(t->cyc8b   * 1000,  T);
2678 	q->active  = EZ(t->active  * 1000,  T);
2679 	q->recover = EZ(t->recover * 1000,  T);
2680 	q->cycle   = EZ(t->cycle   * 1000,  T);
2681 	q->udma    = EZ(t->udma    * 1000, UT);
2682 }
2683 
2684 void ata_timing_merge(const struct ata_timing *a, const struct ata_timing *b,
2685 		      struct ata_timing *m, unsigned int what)
2686 {
2687 	if (what & ATA_TIMING_SETUP  ) m->setup   = max(a->setup,   b->setup);
2688 	if (what & ATA_TIMING_ACT8B  ) m->act8b   = max(a->act8b,   b->act8b);
2689 	if (what & ATA_TIMING_REC8B  ) m->rec8b   = max(a->rec8b,   b->rec8b);
2690 	if (what & ATA_TIMING_CYC8B  ) m->cyc8b   = max(a->cyc8b,   b->cyc8b);
2691 	if (what & ATA_TIMING_ACTIVE ) m->active  = max(a->active,  b->active);
2692 	if (what & ATA_TIMING_RECOVER) m->recover = max(a->recover, b->recover);
2693 	if (what & ATA_TIMING_CYCLE  ) m->cycle   = max(a->cycle,   b->cycle);
2694 	if (what & ATA_TIMING_UDMA   ) m->udma    = max(a->udma,    b->udma);
2695 }
2696 
2697 static const struct ata_timing* ata_timing_find_mode(unsigned short speed)
2698 {
2699 	const struct ata_timing *t;
2700 
2701 	for (t = ata_timing; t->mode != speed; t++)
2702 		if (t->mode == 0xFF)
2703 			return NULL;
2704 	return t;
2705 }
2706 
2707 int ata_timing_compute(struct ata_device *adev, unsigned short speed,
2708 		       struct ata_timing *t, int T, int UT)
2709 {
2710 	const struct ata_timing *s;
2711 	struct ata_timing p;
2712 
2713 	/*
2714 	 * Find the mode.
2715 	 */
2716 
2717 	if (!(s = ata_timing_find_mode(speed)))
2718 		return -EINVAL;
2719 
2720 	memcpy(t, s, sizeof(*s));
2721 
2722 	/*
2723 	 * If the drive is an EIDE drive, it can tell us it needs extended
2724 	 * PIO/MW_DMA cycle timing.
2725 	 */
2726 
2727 	if (adev->id[ATA_ID_FIELD_VALID] & 2) {	/* EIDE drive */
2728 		memset(&p, 0, sizeof(p));
2729 		if(speed >= XFER_PIO_0 && speed <= XFER_SW_DMA_0) {
2730 			if (speed <= XFER_PIO_2) p.cycle = p.cyc8b = adev->id[ATA_ID_EIDE_PIO];
2731 					    else p.cycle = p.cyc8b = adev->id[ATA_ID_EIDE_PIO_IORDY];
2732 		} else if(speed >= XFER_MW_DMA_0 && speed <= XFER_MW_DMA_2) {
2733 			p.cycle = adev->id[ATA_ID_EIDE_DMA_MIN];
2734 		}
2735 		ata_timing_merge(&p, t, t, ATA_TIMING_CYCLE | ATA_TIMING_CYC8B);
2736 	}
2737 
2738 	/*
2739 	 * Convert the timing to bus clock counts.
2740 	 */
2741 
2742 	ata_timing_quantize(t, t, T, UT);
2743 
2744 	/*
2745 	 * Even in DMA/UDMA modes we still use PIO access for IDENTIFY,
2746 	 * S.M.A.R.T * and some other commands. We have to ensure that the
2747 	 * DMA cycle timing is slower/equal than the fastest PIO timing.
2748 	 */
2749 
2750 	if (speed > XFER_PIO_6) {
2751 		ata_timing_compute(adev, adev->pio_mode, &p, T, UT);
2752 		ata_timing_merge(&p, t, t, ATA_TIMING_ALL);
2753 	}
2754 
2755 	/*
2756 	 * Lengthen active & recovery time so that cycle time is correct.
2757 	 */
2758 
2759 	if (t->act8b + t->rec8b < t->cyc8b) {
2760 		t->act8b += (t->cyc8b - (t->act8b + t->rec8b)) / 2;
2761 		t->rec8b = t->cyc8b - t->act8b;
2762 	}
2763 
2764 	if (t->active + t->recover < t->cycle) {
2765 		t->active += (t->cycle - (t->active + t->recover)) / 2;
2766 		t->recover = t->cycle - t->active;
2767 	}
2768 
2769 	/* In a few cases quantisation may produce enough errors to
2770 	   leave t->cycle too low for the sum of active and recovery
2771 	   if so we must correct this */
2772 	if (t->active + t->recover > t->cycle)
2773 		t->cycle = t->active + t->recover;
2774 
2775 	return 0;
2776 }
2777 
2778 /**
2779  *	ata_down_xfermask_limit - adjust dev xfer masks downward
2780  *	@dev: Device to adjust xfer masks
2781  *	@sel: ATA_DNXFER_* selector
2782  *
2783  *	Adjust xfer masks of @dev downward.  Note that this function
2784  *	does not apply the change.  Invoking ata_set_mode() afterwards
2785  *	will apply the limit.
2786  *
2787  *	LOCKING:
2788  *	Inherited from caller.
2789  *
2790  *	RETURNS:
2791  *	0 on success, negative errno on failure
2792  */
2793 int ata_down_xfermask_limit(struct ata_device *dev, unsigned int sel)
2794 {
2795 	char buf[32];
2796 	unsigned int orig_mask, xfer_mask;
2797 	unsigned int pio_mask, mwdma_mask, udma_mask;
2798 	int quiet, highbit;
2799 
2800 	quiet = !!(sel & ATA_DNXFER_QUIET);
2801 	sel &= ~ATA_DNXFER_QUIET;
2802 
2803 	xfer_mask = orig_mask = ata_pack_xfermask(dev->pio_mask,
2804 						  dev->mwdma_mask,
2805 						  dev->udma_mask);
2806 	ata_unpack_xfermask(xfer_mask, &pio_mask, &mwdma_mask, &udma_mask);
2807 
2808 	switch (sel) {
2809 	case ATA_DNXFER_PIO:
2810 		highbit = fls(pio_mask) - 1;
2811 		pio_mask &= ~(1 << highbit);
2812 		break;
2813 
2814 	case ATA_DNXFER_DMA:
2815 		if (udma_mask) {
2816 			highbit = fls(udma_mask) - 1;
2817 			udma_mask &= ~(1 << highbit);
2818 			if (!udma_mask)
2819 				return -ENOENT;
2820 		} else if (mwdma_mask) {
2821 			highbit = fls(mwdma_mask) - 1;
2822 			mwdma_mask &= ~(1 << highbit);
2823 			if (!mwdma_mask)
2824 				return -ENOENT;
2825 		}
2826 		break;
2827 
2828 	case ATA_DNXFER_40C:
2829 		udma_mask &= ATA_UDMA_MASK_40C;
2830 		break;
2831 
2832 	case ATA_DNXFER_FORCE_PIO0:
2833 		pio_mask &= 1;
2834 	case ATA_DNXFER_FORCE_PIO:
2835 		mwdma_mask = 0;
2836 		udma_mask = 0;
2837 		break;
2838 
2839 	default:
2840 		BUG();
2841 	}
2842 
2843 	xfer_mask &= ata_pack_xfermask(pio_mask, mwdma_mask, udma_mask);
2844 
2845 	if (!(xfer_mask & ATA_MASK_PIO) || xfer_mask == orig_mask)
2846 		return -ENOENT;
2847 
2848 	if (!quiet) {
2849 		if (xfer_mask & (ATA_MASK_MWDMA | ATA_MASK_UDMA))
2850 			snprintf(buf, sizeof(buf), "%s:%s",
2851 				 ata_mode_string(xfer_mask),
2852 				 ata_mode_string(xfer_mask & ATA_MASK_PIO));
2853 		else
2854 			snprintf(buf, sizeof(buf), "%s",
2855 				 ata_mode_string(xfer_mask));
2856 
2857 		ata_dev_printk(dev, KERN_WARNING,
2858 			       "limiting speed to %s\n", buf);
2859 	}
2860 
2861 	ata_unpack_xfermask(xfer_mask, &dev->pio_mask, &dev->mwdma_mask,
2862 			    &dev->udma_mask);
2863 
2864 	return 0;
2865 }
2866 
2867 static int ata_dev_set_mode(struct ata_device *dev)
2868 {
2869 	struct ata_eh_context *ehc = &dev->link->eh_context;
2870 	unsigned int err_mask;
2871 	int rc;
2872 
2873 	dev->flags &= ~ATA_DFLAG_PIO;
2874 	if (dev->xfer_shift == ATA_SHIFT_PIO)
2875 		dev->flags |= ATA_DFLAG_PIO;
2876 
2877 	err_mask = ata_dev_set_xfermode(dev);
2878 	/* Old CFA may refuse this command, which is just fine */
2879 	if (dev->xfer_shift == ATA_SHIFT_PIO && ata_id_is_cfa(dev->id))
2880         	err_mask &= ~AC_ERR_DEV;
2881 	/* Some very old devices and some bad newer ones fail any kind of
2882 	   SET_XFERMODE request but support PIO0-2 timings and no IORDY */
2883 	if (dev->xfer_shift == ATA_SHIFT_PIO && !ata_id_has_iordy(dev->id) &&
2884 			dev->pio_mode <= XFER_PIO_2)
2885 		err_mask &= ~AC_ERR_DEV;
2886 	if (err_mask) {
2887 		ata_dev_printk(dev, KERN_ERR, "failed to set xfermode "
2888 			       "(err_mask=0x%x)\n", err_mask);
2889 		return -EIO;
2890 	}
2891 
2892 	ehc->i.flags |= ATA_EHI_POST_SETMODE;
2893 	rc = ata_dev_revalidate(dev, ATA_DEV_UNKNOWN, 0);
2894 	ehc->i.flags &= ~ATA_EHI_POST_SETMODE;
2895 	if (rc)
2896 		return rc;
2897 
2898 	DPRINTK("xfer_shift=%u, xfer_mode=0x%x\n",
2899 		dev->xfer_shift, (int)dev->xfer_mode);
2900 
2901 	ata_dev_printk(dev, KERN_INFO, "configured for %s\n",
2902 		       ata_mode_string(ata_xfer_mode2mask(dev->xfer_mode)));
2903 	return 0;
2904 }
2905 
2906 /**
2907  *	ata_do_set_mode - Program timings and issue SET FEATURES - XFER
2908  *	@link: link on which timings will be programmed
2909  *	@r_failed_dev: out paramter for failed device
2910  *
2911  *	Standard implementation of the function used to tune and set
2912  *	ATA device disk transfer mode (PIO3, UDMA6, etc.).  If
2913  *	ata_dev_set_mode() fails, pointer to the failing device is
2914  *	returned in @r_failed_dev.
2915  *
2916  *	LOCKING:
2917  *	PCI/etc. bus probe sem.
2918  *
2919  *	RETURNS:
2920  *	0 on success, negative errno otherwise
2921  */
2922 
2923 int ata_do_set_mode(struct ata_link *link, struct ata_device **r_failed_dev)
2924 {
2925 	struct ata_port *ap = link->ap;
2926 	struct ata_device *dev;
2927 	int rc = 0, used_dma = 0, found = 0;
2928 
2929 	/* step 1: calculate xfer_mask */
2930 	ata_link_for_each_dev(dev, link) {
2931 		unsigned int pio_mask, dma_mask;
2932 		unsigned int mode_mask;
2933 
2934 		if (!ata_dev_enabled(dev))
2935 			continue;
2936 
2937 		mode_mask = ATA_DMA_MASK_ATA;
2938 		if (dev->class == ATA_DEV_ATAPI)
2939 			mode_mask = ATA_DMA_MASK_ATAPI;
2940 		else if (ata_id_is_cfa(dev->id))
2941 			mode_mask = ATA_DMA_MASK_CFA;
2942 
2943 		ata_dev_xfermask(dev);
2944 
2945 		pio_mask = ata_pack_xfermask(dev->pio_mask, 0, 0);
2946 		dma_mask = ata_pack_xfermask(0, dev->mwdma_mask, dev->udma_mask);
2947 
2948 		if (libata_dma_mask & mode_mask)
2949 			dma_mask = ata_pack_xfermask(0, dev->mwdma_mask, dev->udma_mask);
2950 		else
2951 			dma_mask = 0;
2952 
2953 		dev->pio_mode = ata_xfer_mask2mode(pio_mask);
2954 		dev->dma_mode = ata_xfer_mask2mode(dma_mask);
2955 
2956 		found = 1;
2957 		if (dev->dma_mode)
2958 			used_dma = 1;
2959 	}
2960 	if (!found)
2961 		goto out;
2962 
2963 	/* step 2: always set host PIO timings */
2964 	ata_link_for_each_dev(dev, link) {
2965 		if (!ata_dev_enabled(dev))
2966 			continue;
2967 
2968 		if (!dev->pio_mode) {
2969 			ata_dev_printk(dev, KERN_WARNING, "no PIO support\n");
2970 			rc = -EINVAL;
2971 			goto out;
2972 		}
2973 
2974 		dev->xfer_mode = dev->pio_mode;
2975 		dev->xfer_shift = ATA_SHIFT_PIO;
2976 		if (ap->ops->set_piomode)
2977 			ap->ops->set_piomode(ap, dev);
2978 	}
2979 
2980 	/* step 3: set host DMA timings */
2981 	ata_link_for_each_dev(dev, link) {
2982 		if (!ata_dev_enabled(dev) || !dev->dma_mode)
2983 			continue;
2984 
2985 		dev->xfer_mode = dev->dma_mode;
2986 		dev->xfer_shift = ata_xfer_mode2shift(dev->dma_mode);
2987 		if (ap->ops->set_dmamode)
2988 			ap->ops->set_dmamode(ap, dev);
2989 	}
2990 
2991 	/* step 4: update devices' xfer mode */
2992 	ata_link_for_each_dev(dev, link) {
2993 		/* don't update suspended devices' xfer mode */
2994 		if (!ata_dev_enabled(dev))
2995 			continue;
2996 
2997 		rc = ata_dev_set_mode(dev);
2998 		if (rc)
2999 			goto out;
3000 	}
3001 
3002 	/* Record simplex status. If we selected DMA then the other
3003 	 * host channels are not permitted to do so.
3004 	 */
3005 	if (used_dma && (ap->host->flags & ATA_HOST_SIMPLEX))
3006 		ap->host->simplex_claimed = ap;
3007 
3008  out:
3009 	if (rc)
3010 		*r_failed_dev = dev;
3011 	return rc;
3012 }
3013 
3014 /**
3015  *	ata_set_mode - Program timings and issue SET FEATURES - XFER
3016  *	@link: link on which timings will be programmed
3017  *	@r_failed_dev: out paramter for failed device
3018  *
3019  *	Set ATA device disk transfer mode (PIO3, UDMA6, etc.).  If
3020  *	ata_set_mode() fails, pointer to the failing device is
3021  *	returned in @r_failed_dev.
3022  *
3023  *	LOCKING:
3024  *	PCI/etc. bus probe sem.
3025  *
3026  *	RETURNS:
3027  *	0 on success, negative errno otherwise
3028  */
3029 int ata_set_mode(struct ata_link *link, struct ata_device **r_failed_dev)
3030 {
3031 	struct ata_port *ap = link->ap;
3032 
3033 	/* has private set_mode? */
3034 	if (ap->ops->set_mode)
3035 		return ap->ops->set_mode(link, r_failed_dev);
3036 	return ata_do_set_mode(link, r_failed_dev);
3037 }
3038 
3039 /**
3040  *	ata_tf_to_host - issue ATA taskfile to host controller
3041  *	@ap: port to which command is being issued
3042  *	@tf: ATA taskfile register set
3043  *
3044  *	Issues ATA taskfile register set to ATA host controller,
3045  *	with proper synchronization with interrupt handler and
3046  *	other threads.
3047  *
3048  *	LOCKING:
3049  *	spin_lock_irqsave(host lock)
3050  */
3051 
3052 static inline void ata_tf_to_host(struct ata_port *ap,
3053 				  const struct ata_taskfile *tf)
3054 {
3055 	ap->ops->tf_load(ap, tf);
3056 	ap->ops->exec_command(ap, tf);
3057 }
3058 
3059 /**
3060  *	ata_busy_sleep - sleep until BSY clears, or timeout
3061  *	@ap: port containing status register to be polled
3062  *	@tmout_pat: impatience timeout
3063  *	@tmout: overall timeout
3064  *
3065  *	Sleep until ATA Status register bit BSY clears,
3066  *	or a timeout occurs.
3067  *
3068  *	LOCKING:
3069  *	Kernel thread context (may sleep).
3070  *
3071  *	RETURNS:
3072  *	0 on success, -errno otherwise.
3073  */
3074 int ata_busy_sleep(struct ata_port *ap,
3075 		   unsigned long tmout_pat, unsigned long tmout)
3076 {
3077 	unsigned long timer_start, timeout;
3078 	u8 status;
3079 
3080 	status = ata_busy_wait(ap, ATA_BUSY, 300);
3081 	timer_start = jiffies;
3082 	timeout = timer_start + tmout_pat;
3083 	while (status != 0xff && (status & ATA_BUSY) &&
3084 	       time_before(jiffies, timeout)) {
3085 		msleep(50);
3086 		status = ata_busy_wait(ap, ATA_BUSY, 3);
3087 	}
3088 
3089 	if (status != 0xff && (status & ATA_BUSY))
3090 		ata_port_printk(ap, KERN_WARNING,
3091 				"port is slow to respond, please be patient "
3092 				"(Status 0x%x)\n", status);
3093 
3094 	timeout = timer_start + tmout;
3095 	while (status != 0xff && (status & ATA_BUSY) &&
3096 	       time_before(jiffies, timeout)) {
3097 		msleep(50);
3098 		status = ata_chk_status(ap);
3099 	}
3100 
3101 	if (status == 0xff)
3102 		return -ENODEV;
3103 
3104 	if (status & ATA_BUSY) {
3105 		ata_port_printk(ap, KERN_ERR, "port failed to respond "
3106 				"(%lu secs, Status 0x%x)\n",
3107 				tmout / HZ, status);
3108 		return -EBUSY;
3109 	}
3110 
3111 	return 0;
3112 }
3113 
3114 /**
3115  *	ata_wait_ready - sleep until BSY clears, or timeout
3116  *	@ap: port containing status register to be polled
3117  *	@deadline: deadline jiffies for the operation
3118  *
3119  *	Sleep until ATA Status register bit BSY clears, or timeout
3120  *	occurs.
3121  *
3122  *	LOCKING:
3123  *	Kernel thread context (may sleep).
3124  *
3125  *	RETURNS:
3126  *	0 on success, -errno otherwise.
3127  */
3128 int ata_wait_ready(struct ata_port *ap, unsigned long deadline)
3129 {
3130 	unsigned long start = jiffies;
3131 	int warned = 0;
3132 
3133 	while (1) {
3134 		u8 status = ata_chk_status(ap);
3135 		unsigned long now = jiffies;
3136 
3137 		if (!(status & ATA_BUSY))
3138 			return 0;
3139 		if (!ata_link_online(&ap->link) && status == 0xff)
3140 			return -ENODEV;
3141 		if (time_after(now, deadline))
3142 			return -EBUSY;
3143 
3144 		if (!warned && time_after(now, start + 5 * HZ) &&
3145 		    (deadline - now > 3 * HZ)) {
3146 			ata_port_printk(ap, KERN_WARNING,
3147 				"port is slow to respond, please be patient "
3148 				"(Status 0x%x)\n", status);
3149 			warned = 1;
3150 		}
3151 
3152 		msleep(50);
3153 	}
3154 }
3155 
3156 static int ata_bus_post_reset(struct ata_port *ap, unsigned int devmask,
3157 			      unsigned long deadline)
3158 {
3159 	struct ata_ioports *ioaddr = &ap->ioaddr;
3160 	unsigned int dev0 = devmask & (1 << 0);
3161 	unsigned int dev1 = devmask & (1 << 1);
3162 	int rc, ret = 0;
3163 
3164 	/* if device 0 was found in ata_devchk, wait for its
3165 	 * BSY bit to clear
3166 	 */
3167 	if (dev0) {
3168 		rc = ata_wait_ready(ap, deadline);
3169 		if (rc) {
3170 			if (rc != -ENODEV)
3171 				return rc;
3172 			ret = rc;
3173 		}
3174 	}
3175 
3176 	/* if device 1 was found in ata_devchk, wait for register
3177 	 * access briefly, then wait for BSY to clear.
3178 	 */
3179 	if (dev1) {
3180 		int i;
3181 
3182 		ap->ops->dev_select(ap, 1);
3183 
3184 		/* Wait for register access.  Some ATAPI devices fail
3185 		 * to set nsect/lbal after reset, so don't waste too
3186 		 * much time on it.  We're gonna wait for !BSY anyway.
3187 		 */
3188 		for (i = 0; i < 2; i++) {
3189 			u8 nsect, lbal;
3190 
3191 			nsect = ioread8(ioaddr->nsect_addr);
3192 			lbal = ioread8(ioaddr->lbal_addr);
3193 			if ((nsect == 1) && (lbal == 1))
3194 				break;
3195 			msleep(50);	/* give drive a breather */
3196 		}
3197 
3198 		rc = ata_wait_ready(ap, deadline);
3199 		if (rc) {
3200 			if (rc != -ENODEV)
3201 				return rc;
3202 			ret = rc;
3203 		}
3204 	}
3205 
3206 	/* is all this really necessary? */
3207 	ap->ops->dev_select(ap, 0);
3208 	if (dev1)
3209 		ap->ops->dev_select(ap, 1);
3210 	if (dev0)
3211 		ap->ops->dev_select(ap, 0);
3212 
3213 	return ret;
3214 }
3215 
3216 static int ata_bus_softreset(struct ata_port *ap, unsigned int devmask,
3217 			     unsigned long deadline)
3218 {
3219 	struct ata_ioports *ioaddr = &ap->ioaddr;
3220 	struct ata_device *dev;
3221 	int i = 0;
3222 
3223 	DPRINTK("ata%u: bus reset via SRST\n", ap->print_id);
3224 
3225 	/* software reset.  causes dev0 to be selected */
3226 	iowrite8(ap->ctl, ioaddr->ctl_addr);
3227 	udelay(20);	/* FIXME: flush */
3228 	iowrite8(ap->ctl | ATA_SRST, ioaddr->ctl_addr);
3229 	udelay(20);	/* FIXME: flush */
3230 	iowrite8(ap->ctl, ioaddr->ctl_addr);
3231 
3232 	/* If we issued an SRST then an ATA drive (not ATAPI)
3233 	 * may have changed configuration and be in PIO0 timing. If
3234 	 * we did a hard reset (or are coming from power on) this is
3235 	 * true for ATA or ATAPI. Until we've set a suitable controller
3236 	 * mode we should not touch the bus as we may be talking too fast.
3237 	 */
3238 
3239 	ata_link_for_each_dev(dev, &ap->link)
3240 		dev->pio_mode = XFER_PIO_0;
3241 
3242 	/* If the controller has a pio mode setup function then use
3243 	   it to set the chipset to rights. Don't touch the DMA setup
3244 	   as that will be dealt with when revalidating */
3245 	if (ap->ops->set_piomode) {
3246 		ata_link_for_each_dev(dev, &ap->link)
3247 			if (devmask & (1 << i++))
3248 				ap->ops->set_piomode(ap, dev);
3249 	}
3250 
3251 	/* spec mandates ">= 2ms" before checking status.
3252 	 * We wait 150ms, because that was the magic delay used for
3253 	 * ATAPI devices in Hale Landis's ATADRVR, for the period of time
3254 	 * between when the ATA command register is written, and then
3255 	 * status is checked.  Because waiting for "a while" before
3256 	 * checking status is fine, post SRST, we perform this magic
3257 	 * delay here as well.
3258 	 *
3259 	 * Old drivers/ide uses the 2mS rule and then waits for ready
3260 	 */
3261 	msleep(150);
3262 
3263 	/* Before we perform post reset processing we want to see if
3264 	 * the bus shows 0xFF because the odd clown forgets the D7
3265 	 * pulldown resistor.
3266 	 */
3267 	if (ata_check_status(ap) == 0xFF)
3268 		return -ENODEV;
3269 
3270 	return ata_bus_post_reset(ap, devmask, deadline);
3271 }
3272 
3273 /**
3274  *	ata_bus_reset - reset host port and associated ATA channel
3275  *	@ap: port to reset
3276  *
3277  *	This is typically the first time we actually start issuing
3278  *	commands to the ATA channel.  We wait for BSY to clear, then
3279  *	issue EXECUTE DEVICE DIAGNOSTIC command, polling for its
3280  *	result.  Determine what devices, if any, are on the channel
3281  *	by looking at the device 0/1 error register.  Look at the signature
3282  *	stored in each device's taskfile registers, to determine if
3283  *	the device is ATA or ATAPI.
3284  *
3285  *	LOCKING:
3286  *	PCI/etc. bus probe sem.
3287  *	Obtains host lock.
3288  *
3289  *	SIDE EFFECTS:
3290  *	Sets ATA_FLAG_DISABLED if bus reset fails.
3291  */
3292 
3293 void ata_bus_reset(struct ata_port *ap)
3294 {
3295 	struct ata_device *device = ap->link.device;
3296 	struct ata_ioports *ioaddr = &ap->ioaddr;
3297 	unsigned int slave_possible = ap->flags & ATA_FLAG_SLAVE_POSS;
3298 	u8 err;
3299 	unsigned int dev0, dev1 = 0, devmask = 0;
3300 	int rc;
3301 
3302 	DPRINTK("ENTER, host %u, port %u\n", ap->print_id, ap->port_no);
3303 
3304 	/* determine if device 0/1 are present */
3305 	if (ap->flags & ATA_FLAG_SATA_RESET)
3306 		dev0 = 1;
3307 	else {
3308 		dev0 = ata_devchk(ap, 0);
3309 		if (slave_possible)
3310 			dev1 = ata_devchk(ap, 1);
3311 	}
3312 
3313 	if (dev0)
3314 		devmask |= (1 << 0);
3315 	if (dev1)
3316 		devmask |= (1 << 1);
3317 
3318 	/* select device 0 again */
3319 	ap->ops->dev_select(ap, 0);
3320 
3321 	/* issue bus reset */
3322 	if (ap->flags & ATA_FLAG_SRST) {
3323 		rc = ata_bus_softreset(ap, devmask, jiffies + 40 * HZ);
3324 		if (rc && rc != -ENODEV)
3325 			goto err_out;
3326 	}
3327 
3328 	/*
3329 	 * determine by signature whether we have ATA or ATAPI devices
3330 	 */
3331 	device[0].class = ata_dev_try_classify(&device[0], dev0, &err);
3332 	if ((slave_possible) && (err != 0x81))
3333 		device[1].class = ata_dev_try_classify(&device[1], dev1, &err);
3334 
3335 	/* is double-select really necessary? */
3336 	if (device[1].class != ATA_DEV_NONE)
3337 		ap->ops->dev_select(ap, 1);
3338 	if (device[0].class != ATA_DEV_NONE)
3339 		ap->ops->dev_select(ap, 0);
3340 
3341 	/* if no devices were detected, disable this port */
3342 	if ((device[0].class == ATA_DEV_NONE) &&
3343 	    (device[1].class == ATA_DEV_NONE))
3344 		goto err_out;
3345 
3346 	if (ap->flags & (ATA_FLAG_SATA_RESET | ATA_FLAG_SRST)) {
3347 		/* set up device control for ATA_FLAG_SATA_RESET */
3348 		iowrite8(ap->ctl, ioaddr->ctl_addr);
3349 	}
3350 
3351 	DPRINTK("EXIT\n");
3352 	return;
3353 
3354 err_out:
3355 	ata_port_printk(ap, KERN_ERR, "disabling port\n");
3356 	ata_port_disable(ap);
3357 
3358 	DPRINTK("EXIT\n");
3359 }
3360 
3361 /**
3362  *	sata_link_debounce - debounce SATA phy status
3363  *	@link: ATA link to debounce SATA phy status for
3364  *	@params: timing parameters { interval, duratinon, timeout } in msec
3365  *	@deadline: deadline jiffies for the operation
3366  *
3367 *	Make sure SStatus of @link reaches stable state, determined by
3368  *	holding the same value where DET is not 1 for @duration polled
3369  *	every @interval, before @timeout.  Timeout constraints the
3370  *	beginning of the stable state.  Because DET gets stuck at 1 on
3371  *	some controllers after hot unplugging, this functions waits
3372  *	until timeout then returns 0 if DET is stable at 1.
3373  *
3374  *	@timeout is further limited by @deadline.  The sooner of the
3375  *	two is used.
3376  *
3377  *	LOCKING:
3378  *	Kernel thread context (may sleep)
3379  *
3380  *	RETURNS:
3381  *	0 on success, -errno on failure.
3382  */
3383 int sata_link_debounce(struct ata_link *link, const unsigned long *params,
3384 		       unsigned long deadline)
3385 {
3386 	unsigned long interval_msec = params[0];
3387 	unsigned long duration = msecs_to_jiffies(params[1]);
3388 	unsigned long last_jiffies, t;
3389 	u32 last, cur;
3390 	int rc;
3391 
3392 	t = jiffies + msecs_to_jiffies(params[2]);
3393 	if (time_before(t, deadline))
3394 		deadline = t;
3395 
3396 	if ((rc = sata_scr_read(link, SCR_STATUS, &cur)))
3397 		return rc;
3398 	cur &= 0xf;
3399 
3400 	last = cur;
3401 	last_jiffies = jiffies;
3402 
3403 	while (1) {
3404 		msleep(interval_msec);
3405 		if ((rc = sata_scr_read(link, SCR_STATUS, &cur)))
3406 			return rc;
3407 		cur &= 0xf;
3408 
3409 		/* DET stable? */
3410 		if (cur == last) {
3411 			if (cur == 1 && time_before(jiffies, deadline))
3412 				continue;
3413 			if (time_after(jiffies, last_jiffies + duration))
3414 				return 0;
3415 			continue;
3416 		}
3417 
3418 		/* unstable, start over */
3419 		last = cur;
3420 		last_jiffies = jiffies;
3421 
3422 		/* Check deadline.  If debouncing failed, return
3423 		 * -EPIPE to tell upper layer to lower link speed.
3424 		 */
3425 		if (time_after(jiffies, deadline))
3426 			return -EPIPE;
3427 	}
3428 }
3429 
3430 /**
3431  *	sata_link_resume - resume SATA link
3432  *	@link: ATA link to resume SATA
3433  *	@params: timing parameters { interval, duratinon, timeout } in msec
3434  *	@deadline: deadline jiffies for the operation
3435  *
3436  *	Resume SATA phy @link and debounce it.
3437  *
3438  *	LOCKING:
3439  *	Kernel thread context (may sleep)
3440  *
3441  *	RETURNS:
3442  *	0 on success, -errno on failure.
3443  */
3444 int sata_link_resume(struct ata_link *link, const unsigned long *params,
3445 		     unsigned long deadline)
3446 {
3447 	u32 scontrol;
3448 	int rc;
3449 
3450 	if ((rc = sata_scr_read(link, SCR_CONTROL, &scontrol)))
3451 		return rc;
3452 
3453 	scontrol = (scontrol & 0x0f0) | 0x300;
3454 
3455 	if ((rc = sata_scr_write(link, SCR_CONTROL, scontrol)))
3456 		return rc;
3457 
3458 	/* Some PHYs react badly if SStatus is pounded immediately
3459 	 * after resuming.  Delay 200ms before debouncing.
3460 	 */
3461 	msleep(200);
3462 
3463 	return sata_link_debounce(link, params, deadline);
3464 }
3465 
3466 /**
3467  *	ata_std_prereset - prepare for reset
3468  *	@link: ATA link to be reset
3469  *	@deadline: deadline jiffies for the operation
3470  *
3471  *	@link is about to be reset.  Initialize it.  Failure from
3472  *	prereset makes libata abort whole reset sequence and give up
3473  *	that port, so prereset should be best-effort.  It does its
3474  *	best to prepare for reset sequence but if things go wrong, it
3475  *	should just whine, not fail.
3476  *
3477  *	LOCKING:
3478  *	Kernel thread context (may sleep)
3479  *
3480  *	RETURNS:
3481  *	0 on success, -errno otherwise.
3482  */
3483 int ata_std_prereset(struct ata_link *link, unsigned long deadline)
3484 {
3485 	struct ata_port *ap = link->ap;
3486 	struct ata_eh_context *ehc = &link->eh_context;
3487 	const unsigned long *timing = sata_ehc_deb_timing(ehc);
3488 	int rc;
3489 
3490 	/* handle link resume */
3491 	if ((ehc->i.flags & ATA_EHI_RESUME_LINK) &&
3492 	    (link->flags & ATA_LFLAG_HRST_TO_RESUME))
3493 		ehc->i.action |= ATA_EH_HARDRESET;
3494 
3495 	/* Some PMPs don't work with only SRST, force hardreset if PMP
3496 	 * is supported.
3497 	 */
3498 	if (ap->flags & ATA_FLAG_PMP)
3499 		ehc->i.action |= ATA_EH_HARDRESET;
3500 
3501 	/* if we're about to do hardreset, nothing more to do */
3502 	if (ehc->i.action & ATA_EH_HARDRESET)
3503 		return 0;
3504 
3505 	/* if SATA, resume link */
3506 	if (ap->flags & ATA_FLAG_SATA) {
3507 		rc = sata_link_resume(link, timing, deadline);
3508 		/* whine about phy resume failure but proceed */
3509 		if (rc && rc != -EOPNOTSUPP)
3510 			ata_link_printk(link, KERN_WARNING, "failed to resume "
3511 					"link for reset (errno=%d)\n", rc);
3512 	}
3513 
3514 	/* Wait for !BSY if the controller can wait for the first D2H
3515 	 * Reg FIS and we don't know that no device is attached.
3516 	 */
3517 	if (!(link->flags & ATA_LFLAG_SKIP_D2H_BSY) && !ata_link_offline(link)) {
3518 		rc = ata_wait_ready(ap, deadline);
3519 		if (rc && rc != -ENODEV) {
3520 			ata_link_printk(link, KERN_WARNING, "device not ready "
3521 					"(errno=%d), forcing hardreset\n", rc);
3522 			ehc->i.action |= ATA_EH_HARDRESET;
3523 		}
3524 	}
3525 
3526 	return 0;
3527 }
3528 
3529 /**
3530  *	ata_std_softreset - reset host port via ATA SRST
3531  *	@link: ATA link to reset
3532  *	@classes: resulting classes of attached devices
3533  *	@deadline: deadline jiffies for the operation
3534  *
3535  *	Reset host port using ATA SRST.
3536  *
3537  *	LOCKING:
3538  *	Kernel thread context (may sleep)
3539  *
3540  *	RETURNS:
3541  *	0 on success, -errno otherwise.
3542  */
3543 int ata_std_softreset(struct ata_link *link, unsigned int *classes,
3544 		      unsigned long deadline)
3545 {
3546 	struct ata_port *ap = link->ap;
3547 	unsigned int slave_possible = ap->flags & ATA_FLAG_SLAVE_POSS;
3548 	unsigned int devmask = 0;
3549 	int rc;
3550 	u8 err;
3551 
3552 	DPRINTK("ENTER\n");
3553 
3554 	if (ata_link_offline(link)) {
3555 		classes[0] = ATA_DEV_NONE;
3556 		goto out;
3557 	}
3558 
3559 	/* determine if device 0/1 are present */
3560 	if (ata_devchk(ap, 0))
3561 		devmask |= (1 << 0);
3562 	if (slave_possible && ata_devchk(ap, 1))
3563 		devmask |= (1 << 1);
3564 
3565 	/* select device 0 again */
3566 	ap->ops->dev_select(ap, 0);
3567 
3568 	/* issue bus reset */
3569 	DPRINTK("about to softreset, devmask=%x\n", devmask);
3570 	rc = ata_bus_softreset(ap, devmask, deadline);
3571 	/* if link is occupied, -ENODEV too is an error */
3572 	if (rc && (rc != -ENODEV || sata_scr_valid(link))) {
3573 		ata_link_printk(link, KERN_ERR, "SRST failed (errno=%d)\n", rc);
3574 		return rc;
3575 	}
3576 
3577 	/* determine by signature whether we have ATA or ATAPI devices */
3578 	classes[0] = ata_dev_try_classify(&link->device[0],
3579 					  devmask & (1 << 0), &err);
3580 	if (slave_possible && err != 0x81)
3581 		classes[1] = ata_dev_try_classify(&link->device[1],
3582 						  devmask & (1 << 1), &err);
3583 
3584  out:
3585 	DPRINTK("EXIT, classes[0]=%u [1]=%u\n", classes[0], classes[1]);
3586 	return 0;
3587 }
3588 
3589 /**
3590  *	sata_link_hardreset - reset link via SATA phy reset
3591  *	@link: link to reset
3592  *	@timing: timing parameters { interval, duratinon, timeout } in msec
3593  *	@deadline: deadline jiffies for the operation
3594  *
3595  *	SATA phy-reset @link using DET bits of SControl register.
3596  *
3597  *	LOCKING:
3598  *	Kernel thread context (may sleep)
3599  *
3600  *	RETURNS:
3601  *	0 on success, -errno otherwise.
3602  */
3603 int sata_link_hardreset(struct ata_link *link, const unsigned long *timing,
3604 			unsigned long deadline)
3605 {
3606 	u32 scontrol;
3607 	int rc;
3608 
3609 	DPRINTK("ENTER\n");
3610 
3611 	if (sata_set_spd_needed(link)) {
3612 		/* SATA spec says nothing about how to reconfigure
3613 		 * spd.  To be on the safe side, turn off phy during
3614 		 * reconfiguration.  This works for at least ICH7 AHCI
3615 		 * and Sil3124.
3616 		 */
3617 		if ((rc = sata_scr_read(link, SCR_CONTROL, &scontrol)))
3618 			goto out;
3619 
3620 		scontrol = (scontrol & 0x0f0) | 0x304;
3621 
3622 		if ((rc = sata_scr_write(link, SCR_CONTROL, scontrol)))
3623 			goto out;
3624 
3625 		sata_set_spd(link);
3626 	}
3627 
3628 	/* issue phy wake/reset */
3629 	if ((rc = sata_scr_read(link, SCR_CONTROL, &scontrol)))
3630 		goto out;
3631 
3632 	scontrol = (scontrol & 0x0f0) | 0x301;
3633 
3634 	if ((rc = sata_scr_write_flush(link, SCR_CONTROL, scontrol)))
3635 		goto out;
3636 
3637 	/* Couldn't find anything in SATA I/II specs, but AHCI-1.1
3638 	 * 10.4.2 says at least 1 ms.
3639 	 */
3640 	msleep(1);
3641 
3642 	/* bring link back */
3643 	rc = sata_link_resume(link, timing, deadline);
3644  out:
3645 	DPRINTK("EXIT, rc=%d\n", rc);
3646 	return rc;
3647 }
3648 
3649 /**
3650  *	sata_std_hardreset - reset host port via SATA phy reset
3651  *	@link: link to reset
3652  *	@class: resulting class of attached device
3653  *	@deadline: deadline jiffies for the operation
3654  *
3655  *	SATA phy-reset host port using DET bits of SControl register,
3656  *	wait for !BSY and classify the attached device.
3657  *
3658  *	LOCKING:
3659  *	Kernel thread context (may sleep)
3660  *
3661  *	RETURNS:
3662  *	0 on success, -errno otherwise.
3663  */
3664 int sata_std_hardreset(struct ata_link *link, unsigned int *class,
3665 		       unsigned long deadline)
3666 {
3667 	struct ata_port *ap = link->ap;
3668 	const unsigned long *timing = sata_ehc_deb_timing(&link->eh_context);
3669 	int rc;
3670 
3671 	DPRINTK("ENTER\n");
3672 
3673 	/* do hardreset */
3674 	rc = sata_link_hardreset(link, timing, deadline);
3675 	if (rc) {
3676 		ata_link_printk(link, KERN_ERR,
3677 				"COMRESET failed (errno=%d)\n", rc);
3678 		return rc;
3679 	}
3680 
3681 	/* TODO: phy layer with polling, timeouts, etc. */
3682 	if (ata_link_offline(link)) {
3683 		*class = ATA_DEV_NONE;
3684 		DPRINTK("EXIT, link offline\n");
3685 		return 0;
3686 	}
3687 
3688 	/* wait a while before checking status, see SRST for more info */
3689 	msleep(150);
3690 
3691 	/* If PMP is supported, we have to do follow-up SRST.  Note
3692 	 * that some PMPs don't send D2H Reg FIS after hardreset at
3693 	 * all if the first port is empty.  Wait for it just for a
3694 	 * second and request follow-up SRST.
3695 	 */
3696 	if (ap->flags & ATA_FLAG_PMP) {
3697 		ata_wait_ready(ap, jiffies + HZ);
3698 		return -EAGAIN;
3699 	}
3700 
3701 	rc = ata_wait_ready(ap, deadline);
3702 	/* link occupied, -ENODEV too is an error */
3703 	if (rc) {
3704 		ata_link_printk(link, KERN_ERR,
3705 				"COMRESET failed (errno=%d)\n", rc);
3706 		return rc;
3707 	}
3708 
3709 	ap->ops->dev_select(ap, 0);	/* probably unnecessary */
3710 
3711 	*class = ata_dev_try_classify(link->device, 1, NULL);
3712 
3713 	DPRINTK("EXIT, class=%u\n", *class);
3714 	return 0;
3715 }
3716 
3717 /**
3718  *	ata_std_postreset - standard postreset callback
3719  *	@link: the target ata_link
3720  *	@classes: classes of attached devices
3721  *
3722  *	This function is invoked after a successful reset.  Note that
3723  *	the device might have been reset more than once using
3724  *	different reset methods before postreset is invoked.
3725  *
3726  *	LOCKING:
3727  *	Kernel thread context (may sleep)
3728  */
3729 void ata_std_postreset(struct ata_link *link, unsigned int *classes)
3730 {
3731 	struct ata_port *ap = link->ap;
3732 	u32 serror;
3733 
3734 	DPRINTK("ENTER\n");
3735 
3736 	/* print link status */
3737 	sata_print_link_status(link);
3738 
3739 	/* clear SError */
3740 	if (sata_scr_read(link, SCR_ERROR, &serror) == 0)
3741 		sata_scr_write(link, SCR_ERROR, serror);
3742 
3743 	/* is double-select really necessary? */
3744 	if (classes[0] != ATA_DEV_NONE)
3745 		ap->ops->dev_select(ap, 1);
3746 	if (classes[1] != ATA_DEV_NONE)
3747 		ap->ops->dev_select(ap, 0);
3748 
3749 	/* bail out if no device is present */
3750 	if (classes[0] == ATA_DEV_NONE && classes[1] == ATA_DEV_NONE) {
3751 		DPRINTK("EXIT, no device\n");
3752 		return;
3753 	}
3754 
3755 	/* set up device control */
3756 	if (ap->ioaddr.ctl_addr)
3757 		iowrite8(ap->ctl, ap->ioaddr.ctl_addr);
3758 
3759 	DPRINTK("EXIT\n");
3760 }
3761 
3762 /**
3763  *	ata_dev_same_device - Determine whether new ID matches configured device
3764  *	@dev: device to compare against
3765  *	@new_class: class of the new device
3766  *	@new_id: IDENTIFY page of the new device
3767  *
3768  *	Compare @new_class and @new_id against @dev and determine
3769  *	whether @dev is the device indicated by @new_class and
3770  *	@new_id.
3771  *
3772  *	LOCKING:
3773  *	None.
3774  *
3775  *	RETURNS:
3776  *	1 if @dev matches @new_class and @new_id, 0 otherwise.
3777  */
3778 static int ata_dev_same_device(struct ata_device *dev, unsigned int new_class,
3779 			       const u16 *new_id)
3780 {
3781 	const u16 *old_id = dev->id;
3782 	unsigned char model[2][ATA_ID_PROD_LEN + 1];
3783 	unsigned char serial[2][ATA_ID_SERNO_LEN + 1];
3784 
3785 	if (dev->class != new_class) {
3786 		ata_dev_printk(dev, KERN_INFO, "class mismatch %d != %d\n",
3787 			       dev->class, new_class);
3788 		return 0;
3789 	}
3790 
3791 	ata_id_c_string(old_id, model[0], ATA_ID_PROD, sizeof(model[0]));
3792 	ata_id_c_string(new_id, model[1], ATA_ID_PROD, sizeof(model[1]));
3793 	ata_id_c_string(old_id, serial[0], ATA_ID_SERNO, sizeof(serial[0]));
3794 	ata_id_c_string(new_id, serial[1], ATA_ID_SERNO, sizeof(serial[1]));
3795 
3796 	if (strcmp(model[0], model[1])) {
3797 		ata_dev_printk(dev, KERN_INFO, "model number mismatch "
3798 			       "'%s' != '%s'\n", model[0], model[1]);
3799 		return 0;
3800 	}
3801 
3802 	if (strcmp(serial[0], serial[1])) {
3803 		ata_dev_printk(dev, KERN_INFO, "serial number mismatch "
3804 			       "'%s' != '%s'\n", serial[0], serial[1]);
3805 		return 0;
3806 	}
3807 
3808 	return 1;
3809 }
3810 
3811 /**
3812  *	ata_dev_reread_id - Re-read IDENTIFY data
3813  *	@dev: target ATA device
3814  *	@readid_flags: read ID flags
3815  *
3816  *	Re-read IDENTIFY page and make sure @dev is still attached to
3817  *	the port.
3818  *
3819  *	LOCKING:
3820  *	Kernel thread context (may sleep)
3821  *
3822  *	RETURNS:
3823  *	0 on success, negative errno otherwise
3824  */
3825 int ata_dev_reread_id(struct ata_device *dev, unsigned int readid_flags)
3826 {
3827 	unsigned int class = dev->class;
3828 	u16 *id = (void *)dev->link->ap->sector_buf;
3829 	int rc;
3830 
3831 	/* read ID data */
3832 	rc = ata_dev_read_id(dev, &class, readid_flags, id);
3833 	if (rc)
3834 		return rc;
3835 
3836 	/* is the device still there? */
3837 	if (!ata_dev_same_device(dev, class, id))
3838 		return -ENODEV;
3839 
3840 	memcpy(dev->id, id, sizeof(id[0]) * ATA_ID_WORDS);
3841 	return 0;
3842 }
3843 
3844 /**
3845  *	ata_dev_revalidate - Revalidate ATA device
3846  *	@dev: device to revalidate
3847  *	@new_class: new class code
3848  *	@readid_flags: read ID flags
3849  *
3850  *	Re-read IDENTIFY page, make sure @dev is still attached to the
3851  *	port and reconfigure it according to the new IDENTIFY page.
3852  *
3853  *	LOCKING:
3854  *	Kernel thread context (may sleep)
3855  *
3856  *	RETURNS:
3857  *	0 on success, negative errno otherwise
3858  */
3859 int ata_dev_revalidate(struct ata_device *dev, unsigned int new_class,
3860 		       unsigned int readid_flags)
3861 {
3862 	u64 n_sectors = dev->n_sectors;
3863 	int rc;
3864 
3865 	if (!ata_dev_enabled(dev))
3866 		return -ENODEV;
3867 
3868 	/* fail early if !ATA && !ATAPI to avoid issuing [P]IDENTIFY to PMP */
3869 	if (ata_class_enabled(new_class) &&
3870 	    new_class != ATA_DEV_ATA && new_class != ATA_DEV_ATAPI) {
3871 		ata_dev_printk(dev, KERN_INFO, "class mismatch %u != %u\n",
3872 			       dev->class, new_class);
3873 		rc = -ENODEV;
3874 		goto fail;
3875 	}
3876 
3877 	/* re-read ID */
3878 	rc = ata_dev_reread_id(dev, readid_flags);
3879 	if (rc)
3880 		goto fail;
3881 
3882 	/* configure device according to the new ID */
3883 	rc = ata_dev_configure(dev);
3884 	if (rc)
3885 		goto fail;
3886 
3887 	/* verify n_sectors hasn't changed */
3888 	if (dev->class == ATA_DEV_ATA && n_sectors &&
3889 	    dev->n_sectors != n_sectors) {
3890 		ata_dev_printk(dev, KERN_INFO, "n_sectors mismatch "
3891 			       "%llu != %llu\n",
3892 			       (unsigned long long)n_sectors,
3893 			       (unsigned long long)dev->n_sectors);
3894 
3895 		/* restore original n_sectors */
3896 		dev->n_sectors = n_sectors;
3897 
3898 		rc = -ENODEV;
3899 		goto fail;
3900 	}
3901 
3902 	return 0;
3903 
3904  fail:
3905 	ata_dev_printk(dev, KERN_ERR, "revalidation failed (errno=%d)\n", rc);
3906 	return rc;
3907 }
3908 
3909 struct ata_blacklist_entry {
3910 	const char *model_num;
3911 	const char *model_rev;
3912 	unsigned long horkage;
3913 };
3914 
3915 static const struct ata_blacklist_entry ata_device_blacklist [] = {
3916 	/* Devices with DMA related problems under Linux */
3917 	{ "WDC AC11000H",	NULL,		ATA_HORKAGE_NODMA },
3918 	{ "WDC AC22100H",	NULL,		ATA_HORKAGE_NODMA },
3919 	{ "WDC AC32500H",	NULL,		ATA_HORKAGE_NODMA },
3920 	{ "WDC AC33100H",	NULL,		ATA_HORKAGE_NODMA },
3921 	{ "WDC AC31600H",	NULL,		ATA_HORKAGE_NODMA },
3922 	{ "WDC AC32100H",	"24.09P07",	ATA_HORKAGE_NODMA },
3923 	{ "WDC AC23200L",	"21.10N21",	ATA_HORKAGE_NODMA },
3924 	{ "Compaq CRD-8241B", 	NULL,		ATA_HORKAGE_NODMA },
3925 	{ "CRD-8400B",		NULL, 		ATA_HORKAGE_NODMA },
3926 	{ "CRD-8480B",		NULL,		ATA_HORKAGE_NODMA },
3927 	{ "CRD-8482B",		NULL,		ATA_HORKAGE_NODMA },
3928 	{ "CRD-84",		NULL,		ATA_HORKAGE_NODMA },
3929 	{ "SanDisk SDP3B",	NULL,		ATA_HORKAGE_NODMA },
3930 	{ "SanDisk SDP3B-64",	NULL,		ATA_HORKAGE_NODMA },
3931 	{ "SANYO CD-ROM CRD",	NULL,		ATA_HORKAGE_NODMA },
3932 	{ "HITACHI CDR-8",	NULL,		ATA_HORKAGE_NODMA },
3933 	{ "HITACHI CDR-8335",	NULL,		ATA_HORKAGE_NODMA },
3934 	{ "HITACHI CDR-8435",	NULL,		ATA_HORKAGE_NODMA },
3935 	{ "Toshiba CD-ROM XM-6202B", NULL,	ATA_HORKAGE_NODMA },
3936 	{ "TOSHIBA CD-ROM XM-1702BC", NULL,	ATA_HORKAGE_NODMA },
3937 	{ "CD-532E-A", 		NULL,		ATA_HORKAGE_NODMA },
3938 	{ "E-IDE CD-ROM CR-840",NULL,		ATA_HORKAGE_NODMA },
3939 	{ "CD-ROM Drive/F5A",	NULL,		ATA_HORKAGE_NODMA },
3940 	{ "WPI CDD-820", 	NULL,		ATA_HORKAGE_NODMA },
3941 	{ "SAMSUNG CD-ROM SC-148C", NULL,	ATA_HORKAGE_NODMA },
3942 	{ "SAMSUNG CD-ROM SC",	NULL,		ATA_HORKAGE_NODMA },
3943 	{ "ATAPI CD-ROM DRIVE 40X MAXIMUM",NULL,ATA_HORKAGE_NODMA },
3944 	{ "_NEC DV5800A", 	NULL,		ATA_HORKAGE_NODMA },
3945 	{ "SAMSUNG CD-ROM SN-124","N001",	ATA_HORKAGE_NODMA },
3946 	{ "Seagate STT20000A", NULL,		ATA_HORKAGE_NODMA },
3947 	{ "IOMEGA  ZIP 250       ATAPI", NULL,	ATA_HORKAGE_NODMA }, /* temporary fix */
3948 	{ "IOMEGA  ZIP 250       ATAPI       Floppy",
3949 				NULL,		ATA_HORKAGE_NODMA },
3950 	/* Odd clown on sil3726/4726 PMPs */
3951 	{ "Config  Disk",	NULL,		ATA_HORKAGE_NODMA |
3952 						ATA_HORKAGE_SKIP_PM },
3953 
3954 	/* Weird ATAPI devices */
3955 	{ "TORiSAN DVD-ROM DRD-N216", NULL,	ATA_HORKAGE_MAX_SEC_128 },
3956 
3957 	/* Devices we expect to fail diagnostics */
3958 
3959 	/* Devices where NCQ should be avoided */
3960 	/* NCQ is slow */
3961         { "WDC WD740ADFD-00",   NULL,		ATA_HORKAGE_NONCQ },
3962 	/* http://thread.gmane.org/gmane.linux.ide/14907 */
3963 	{ "FUJITSU MHT2060BH",	NULL,		ATA_HORKAGE_NONCQ },
3964 	/* NCQ is broken */
3965 	{ "Maxtor *",		"BANC*",	ATA_HORKAGE_NONCQ },
3966 	{ "Maxtor 7V300F0",	"VA111630",	ATA_HORKAGE_NONCQ },
3967 	{ "HITACHI HDS7250SASUN500G*", NULL,    ATA_HORKAGE_NONCQ },
3968 	{ "HITACHI HDS7225SBSUN250G*", NULL,    ATA_HORKAGE_NONCQ },
3969 	{ "ST380817AS",		"3.42",		ATA_HORKAGE_NONCQ },
3970 
3971 	/* Blacklist entries taken from Silicon Image 3124/3132
3972 	   Windows driver .inf file - also several Linux problem reports */
3973 	{ "HTS541060G9SA00",    "MB3OC60D",     ATA_HORKAGE_NONCQ, },
3974 	{ "HTS541080G9SA00",    "MB4OC60D",     ATA_HORKAGE_NONCQ, },
3975 	{ "HTS541010G9SA00",    "MBZOC60D",     ATA_HORKAGE_NONCQ, },
3976 	/* Drives which do spurious command completion */
3977 	{ "HTS541680J9SA00",	"SB2IC7EP",	ATA_HORKAGE_NONCQ, },
3978 	{ "HTS541612J9SA00",	"SBDIC7JP",	ATA_HORKAGE_NONCQ, },
3979 	{ "HDT722516DLA380",	"V43OA96A",	ATA_HORKAGE_NONCQ, },
3980 	{ "Hitachi HTS541616J9SA00", "SB4OC70P", ATA_HORKAGE_NONCQ, },
3981 	{ "WDC WD740ADFD-00NLR1", NULL,		ATA_HORKAGE_NONCQ, },
3982 	{ "WDC WD3200AAJS-00RYA0", "12.01B01",	ATA_HORKAGE_NONCQ, },
3983 	{ "FUJITSU MHV2080BH",	"00840028",	ATA_HORKAGE_NONCQ, },
3984 	{ "ST9120822AS",	"3.CLF",	ATA_HORKAGE_NONCQ, },
3985 	{ "ST9160821AS",	"3.CLF",	ATA_HORKAGE_NONCQ, },
3986 	{ "ST9160821AS",	"3.ALD",	ATA_HORKAGE_NONCQ, },
3987 	{ "ST3160812AS",	"3.ADJ",	ATA_HORKAGE_NONCQ, },
3988 	{ "ST980813AS",		"3.ADB",	ATA_HORKAGE_NONCQ, },
3989 	{ "SAMSUNG HD401LJ",	"ZZ100-15",	ATA_HORKAGE_NONCQ, },
3990 
3991 	/* devices which puke on READ_NATIVE_MAX */
3992 	{ "HDS724040KLSA80",	"KFAOA20N",	ATA_HORKAGE_BROKEN_HPA, },
3993 	{ "WDC WD3200JD-00KLB0", "WD-WCAMR1130137", ATA_HORKAGE_BROKEN_HPA },
3994 	{ "WDC WD2500JD-00HBB0", "WD-WMAL71490727", ATA_HORKAGE_BROKEN_HPA },
3995 	{ "MAXTOR 6L080L4",	"A93.0500",	ATA_HORKAGE_BROKEN_HPA },
3996 
3997 	/* Devices which report 1 sector over size HPA */
3998 	{ "ST340823A",		NULL,		ATA_HORKAGE_HPA_SIZE, },
3999 	{ "ST320413A",		NULL,		ATA_HORKAGE_HPA_SIZE, },
4000 
4001 	/* End Marker */
4002 	{ }
4003 };
4004 
4005 int strn_pattern_cmp(const char *patt, const char *name, int wildchar)
4006 {
4007 	const char *p;
4008 	int len;
4009 
4010 	/*
4011 	 * check for trailing wildcard: *\0
4012 	 */
4013 	p = strchr(patt, wildchar);
4014 	if (p && ((*(p + 1)) == 0))
4015 		len = p - patt;
4016 	else
4017 		len = strlen(name);
4018 
4019 	return strncmp(patt, name, len);
4020 }
4021 
4022 static unsigned long ata_dev_blacklisted(const struct ata_device *dev)
4023 {
4024 	unsigned char model_num[ATA_ID_PROD_LEN + 1];
4025 	unsigned char model_rev[ATA_ID_FW_REV_LEN + 1];
4026 	const struct ata_blacklist_entry *ad = ata_device_blacklist;
4027 
4028 	ata_id_c_string(dev->id, model_num, ATA_ID_PROD, sizeof(model_num));
4029 	ata_id_c_string(dev->id, model_rev, ATA_ID_FW_REV, sizeof(model_rev));
4030 
4031 	while (ad->model_num) {
4032 		if (!strn_pattern_cmp(ad->model_num, model_num, '*')) {
4033 			if (ad->model_rev == NULL)
4034 				return ad->horkage;
4035 			if (!strn_pattern_cmp(ad->model_rev, model_rev, '*'))
4036 				return ad->horkage;
4037 		}
4038 		ad++;
4039 	}
4040 	return 0;
4041 }
4042 
4043 static int ata_dma_blacklisted(const struct ata_device *dev)
4044 {
4045 	/* We don't support polling DMA.
4046 	 * DMA blacklist those ATAPI devices with CDB-intr (and use PIO)
4047 	 * if the LLDD handles only interrupts in the HSM_ST_LAST state.
4048 	 */
4049 	if ((dev->link->ap->flags & ATA_FLAG_PIO_POLLING) &&
4050 	    (dev->flags & ATA_DFLAG_CDB_INTR))
4051 		return 1;
4052 	return (dev->horkage & ATA_HORKAGE_NODMA) ? 1 : 0;
4053 }
4054 
4055 /**
4056  *	ata_dev_xfermask - Compute supported xfermask of the given device
4057  *	@dev: Device to compute xfermask for
4058  *
4059  *	Compute supported xfermask of @dev and store it in
4060  *	dev->*_mask.  This function is responsible for applying all
4061  *	known limits including host controller limits, device
4062  *	blacklist, etc...
4063  *
4064  *	LOCKING:
4065  *	None.
4066  */
4067 static void ata_dev_xfermask(struct ata_device *dev)
4068 {
4069 	struct ata_link *link = dev->link;
4070 	struct ata_port *ap = link->ap;
4071 	struct ata_host *host = ap->host;
4072 	unsigned long xfer_mask;
4073 
4074 	/* controller modes available */
4075 	xfer_mask = ata_pack_xfermask(ap->pio_mask,
4076 				      ap->mwdma_mask, ap->udma_mask);
4077 
4078 	/* drive modes available */
4079 	xfer_mask &= ata_pack_xfermask(dev->pio_mask,
4080 				       dev->mwdma_mask, dev->udma_mask);
4081 	xfer_mask &= ata_id_xfermask(dev->id);
4082 
4083 	/*
4084 	 *	CFA Advanced TrueIDE timings are not allowed on a shared
4085 	 *	cable
4086 	 */
4087 	if (ata_dev_pair(dev)) {
4088 		/* No PIO5 or PIO6 */
4089 		xfer_mask &= ~(0x03 << (ATA_SHIFT_PIO + 5));
4090 		/* No MWDMA3 or MWDMA 4 */
4091 		xfer_mask &= ~(0x03 << (ATA_SHIFT_MWDMA + 3));
4092 	}
4093 
4094 	if (ata_dma_blacklisted(dev)) {
4095 		xfer_mask &= ~(ATA_MASK_MWDMA | ATA_MASK_UDMA);
4096 		ata_dev_printk(dev, KERN_WARNING,
4097 			       "device is on DMA blacklist, disabling DMA\n");
4098 	}
4099 
4100 	if ((host->flags & ATA_HOST_SIMPLEX) &&
4101             host->simplex_claimed && host->simplex_claimed != ap) {
4102 		xfer_mask &= ~(ATA_MASK_MWDMA | ATA_MASK_UDMA);
4103 		ata_dev_printk(dev, KERN_WARNING, "simplex DMA is claimed by "
4104 			       "other device, disabling DMA\n");
4105 	}
4106 
4107 	if (ap->flags & ATA_FLAG_NO_IORDY)
4108 		xfer_mask &= ata_pio_mask_no_iordy(dev);
4109 
4110 	if (ap->ops->mode_filter)
4111 		xfer_mask = ap->ops->mode_filter(dev, xfer_mask);
4112 
4113 	/* Apply cable rule here.  Don't apply it early because when
4114 	 * we handle hot plug the cable type can itself change.
4115 	 * Check this last so that we know if the transfer rate was
4116 	 * solely limited by the cable.
4117 	 * Unknown or 80 wire cables reported host side are checked
4118 	 * drive side as well. Cases where we know a 40wire cable
4119 	 * is used safely for 80 are not checked here.
4120 	 */
4121 	if (xfer_mask & (0xF8 << ATA_SHIFT_UDMA))
4122 		/* UDMA/44 or higher would be available */
4123 		if((ap->cbl == ATA_CBL_PATA40) ||
4124    		    (ata_drive_40wire(dev->id) &&
4125 		     (ap->cbl == ATA_CBL_PATA_UNK ||
4126                      ap->cbl == ATA_CBL_PATA80))) {
4127 		      	ata_dev_printk(dev, KERN_WARNING,
4128 				 "limited to UDMA/33 due to 40-wire cable\n");
4129 			xfer_mask &= ~(0xF8 << ATA_SHIFT_UDMA);
4130 		}
4131 
4132 	ata_unpack_xfermask(xfer_mask, &dev->pio_mask,
4133 			    &dev->mwdma_mask, &dev->udma_mask);
4134 }
4135 
4136 /**
4137  *	ata_dev_set_xfermode - Issue SET FEATURES - XFER MODE command
4138  *	@dev: Device to which command will be sent
4139  *
4140  *	Issue SET FEATURES - XFER MODE command to device @dev
4141  *	on port @ap.
4142  *
4143  *	LOCKING:
4144  *	PCI/etc. bus probe sem.
4145  *
4146  *	RETURNS:
4147  *	0 on success, AC_ERR_* mask otherwise.
4148  */
4149 
4150 static unsigned int ata_dev_set_xfermode(struct ata_device *dev)
4151 {
4152 	struct ata_taskfile tf;
4153 	unsigned int err_mask;
4154 
4155 	/* set up set-features taskfile */
4156 	DPRINTK("set features - xfer mode\n");
4157 
4158 	/* Some controllers and ATAPI devices show flaky interrupt
4159 	 * behavior after setting xfer mode.  Use polling instead.
4160 	 */
4161 	ata_tf_init(dev, &tf);
4162 	tf.command = ATA_CMD_SET_FEATURES;
4163 	tf.feature = SETFEATURES_XFER;
4164 	tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE | ATA_TFLAG_POLLING;
4165 	tf.protocol = ATA_PROT_NODATA;
4166 	tf.nsect = dev->xfer_mode;
4167 
4168 	err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
4169 
4170 	DPRINTK("EXIT, err_mask=%x\n", err_mask);
4171 	return err_mask;
4172 }
4173 
4174 /**
4175  *	ata_dev_set_AN - Issue SET FEATURES - SATA FEATURES
4176  *	@dev: Device to which command will be sent
4177  *	@enable: Whether to enable or disable the feature
4178  *
4179  *	Issue SET FEATURES - SATA FEATURES command to device @dev
4180  *	on port @ap with sector count set to indicate Asynchronous
4181  *	Notification feature
4182  *
4183  *	LOCKING:
4184  *	PCI/etc. bus probe sem.
4185  *
4186  *	RETURNS:
4187  *	0 on success, AC_ERR_* mask otherwise.
4188  */
4189 static unsigned int ata_dev_set_AN(struct ata_device *dev, u8 enable)
4190 {
4191 	struct ata_taskfile tf;
4192 	unsigned int err_mask;
4193 
4194 	/* set up set-features taskfile */
4195 	DPRINTK("set features - SATA features\n");
4196 
4197 	ata_tf_init(dev, &tf);
4198 	tf.command = ATA_CMD_SET_FEATURES;
4199 	tf.feature = enable;
4200 	tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
4201 	tf.protocol = ATA_PROT_NODATA;
4202 	tf.nsect = SATA_AN;
4203 
4204 	err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
4205 
4206 	DPRINTK("EXIT, err_mask=%x\n", err_mask);
4207 	return err_mask;
4208 }
4209 
4210 /**
4211  *	ata_dev_init_params - Issue INIT DEV PARAMS command
4212  *	@dev: Device to which command will be sent
4213  *	@heads: Number of heads (taskfile parameter)
4214  *	@sectors: Number of sectors (taskfile parameter)
4215  *
4216  *	LOCKING:
4217  *	Kernel thread context (may sleep)
4218  *
4219  *	RETURNS:
4220  *	0 on success, AC_ERR_* mask otherwise.
4221  */
4222 static unsigned int ata_dev_init_params(struct ata_device *dev,
4223 					u16 heads, u16 sectors)
4224 {
4225 	struct ata_taskfile tf;
4226 	unsigned int err_mask;
4227 
4228 	/* Number of sectors per track 1-255. Number of heads 1-16 */
4229 	if (sectors < 1 || sectors > 255 || heads < 1 || heads > 16)
4230 		return AC_ERR_INVALID;
4231 
4232 	/* set up init dev params taskfile */
4233 	DPRINTK("init dev params \n");
4234 
4235 	ata_tf_init(dev, &tf);
4236 	tf.command = ATA_CMD_INIT_DEV_PARAMS;
4237 	tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
4238 	tf.protocol = ATA_PROT_NODATA;
4239 	tf.nsect = sectors;
4240 	tf.device |= (heads - 1) & 0x0f; /* max head = num. of heads - 1 */
4241 
4242 	err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
4243 	/* A clean abort indicates an original or just out of spec drive
4244 	   and we should continue as we issue the setup based on the
4245 	   drive reported working geometry */
4246 	if (err_mask == AC_ERR_DEV && (tf.feature & ATA_ABORTED))
4247 		err_mask = 0;
4248 
4249 	DPRINTK("EXIT, err_mask=%x\n", err_mask);
4250 	return err_mask;
4251 }
4252 
4253 /**
4254  *	ata_sg_clean - Unmap DMA memory associated with command
4255  *	@qc: Command containing DMA memory to be released
4256  *
4257  *	Unmap all mapped DMA memory associated with this command.
4258  *
4259  *	LOCKING:
4260  *	spin_lock_irqsave(host lock)
4261  */
4262 void ata_sg_clean(struct ata_queued_cmd *qc)
4263 {
4264 	struct ata_port *ap = qc->ap;
4265 	struct scatterlist *sg = qc->__sg;
4266 	int dir = qc->dma_dir;
4267 	void *pad_buf = NULL;
4268 
4269 	WARN_ON(!(qc->flags & ATA_QCFLAG_DMAMAP));
4270 	WARN_ON(sg == NULL);
4271 
4272 	if (qc->flags & ATA_QCFLAG_SINGLE)
4273 		WARN_ON(qc->n_elem > 1);
4274 
4275 	VPRINTK("unmapping %u sg elements\n", qc->n_elem);
4276 
4277 	/* if we padded the buffer out to 32-bit bound, and data
4278 	 * xfer direction is from-device, we must copy from the
4279 	 * pad buffer back into the supplied buffer
4280 	 */
4281 	if (qc->pad_len && !(qc->tf.flags & ATA_TFLAG_WRITE))
4282 		pad_buf = ap->pad + (qc->tag * ATA_DMA_PAD_SZ);
4283 
4284 	if (qc->flags & ATA_QCFLAG_SG) {
4285 		if (qc->n_elem)
4286 			dma_unmap_sg(ap->dev, sg, qc->n_elem, dir);
4287 		/* restore last sg */
4288 		sg[qc->orig_n_elem - 1].length += qc->pad_len;
4289 		if (pad_buf) {
4290 			struct scatterlist *psg = &qc->pad_sgent;
4291 			void *addr = kmap_atomic(psg->page, KM_IRQ0);
4292 			memcpy(addr + psg->offset, pad_buf, qc->pad_len);
4293 			kunmap_atomic(addr, KM_IRQ0);
4294 		}
4295 	} else {
4296 		if (qc->n_elem)
4297 			dma_unmap_single(ap->dev,
4298 				sg_dma_address(&sg[0]), sg_dma_len(&sg[0]),
4299 				dir);
4300 		/* restore sg */
4301 		sg->length += qc->pad_len;
4302 		if (pad_buf)
4303 			memcpy(qc->buf_virt + sg->length - qc->pad_len,
4304 			       pad_buf, qc->pad_len);
4305 	}
4306 
4307 	qc->flags &= ~ATA_QCFLAG_DMAMAP;
4308 	qc->__sg = NULL;
4309 }
4310 
4311 /**
4312  *	ata_fill_sg - Fill PCI IDE PRD table
4313  *	@qc: Metadata associated with taskfile to be transferred
4314  *
4315  *	Fill PCI IDE PRD (scatter-gather) table with segments
4316  *	associated with the current disk command.
4317  *
4318  *	LOCKING:
4319  *	spin_lock_irqsave(host lock)
4320  *
4321  */
4322 static void ata_fill_sg(struct ata_queued_cmd *qc)
4323 {
4324 	struct ata_port *ap = qc->ap;
4325 	struct scatterlist *sg;
4326 	unsigned int idx;
4327 
4328 	WARN_ON(qc->__sg == NULL);
4329 	WARN_ON(qc->n_elem == 0 && qc->pad_len == 0);
4330 
4331 	idx = 0;
4332 	ata_for_each_sg(sg, qc) {
4333 		u32 addr, offset;
4334 		u32 sg_len, len;
4335 
4336 		/* determine if physical DMA addr spans 64K boundary.
4337 		 * Note h/w doesn't support 64-bit, so we unconditionally
4338 		 * truncate dma_addr_t to u32.
4339 		 */
4340 		addr = (u32) sg_dma_address(sg);
4341 		sg_len = sg_dma_len(sg);
4342 
4343 		while (sg_len) {
4344 			offset = addr & 0xffff;
4345 			len = sg_len;
4346 			if ((offset + sg_len) > 0x10000)
4347 				len = 0x10000 - offset;
4348 
4349 			ap->prd[idx].addr = cpu_to_le32(addr);
4350 			ap->prd[idx].flags_len = cpu_to_le32(len & 0xffff);
4351 			VPRINTK("PRD[%u] = (0x%X, 0x%X)\n", idx, addr, len);
4352 
4353 			idx++;
4354 			sg_len -= len;
4355 			addr += len;
4356 		}
4357 	}
4358 
4359 	if (idx)
4360 		ap->prd[idx - 1].flags_len |= cpu_to_le32(ATA_PRD_EOT);
4361 }
4362 
4363 /**
4364  *	ata_fill_sg_dumb - Fill PCI IDE PRD table
4365  *	@qc: Metadata associated with taskfile to be transferred
4366  *
4367  *	Fill PCI IDE PRD (scatter-gather) table with segments
4368  *	associated with the current disk command. Perform the fill
4369  *	so that we avoid writing any length 64K records for
4370  *	controllers that don't follow the spec.
4371  *
4372  *	LOCKING:
4373  *	spin_lock_irqsave(host lock)
4374  *
4375  */
4376 static void ata_fill_sg_dumb(struct ata_queued_cmd *qc)
4377 {
4378 	struct ata_port *ap = qc->ap;
4379 	struct scatterlist *sg;
4380 	unsigned int idx;
4381 
4382 	WARN_ON(qc->__sg == NULL);
4383 	WARN_ON(qc->n_elem == 0 && qc->pad_len == 0);
4384 
4385 	idx = 0;
4386 	ata_for_each_sg(sg, qc) {
4387 		u32 addr, offset;
4388 		u32 sg_len, len, blen;
4389 
4390  		/* determine if physical DMA addr spans 64K boundary.
4391 		 * Note h/w doesn't support 64-bit, so we unconditionally
4392 		 * truncate dma_addr_t to u32.
4393 		 */
4394 		addr = (u32) sg_dma_address(sg);
4395 		sg_len = sg_dma_len(sg);
4396 
4397 		while (sg_len) {
4398 			offset = addr & 0xffff;
4399 			len = sg_len;
4400 			if ((offset + sg_len) > 0x10000)
4401 				len = 0x10000 - offset;
4402 
4403 			blen = len & 0xffff;
4404 			ap->prd[idx].addr = cpu_to_le32(addr);
4405 			if (blen == 0) {
4406 			   /* Some PATA chipsets like the CS5530 can't
4407 			      cope with 0x0000 meaning 64K as the spec says */
4408 				ap->prd[idx].flags_len = cpu_to_le32(0x8000);
4409 				blen = 0x8000;
4410 				ap->prd[++idx].addr = cpu_to_le32(addr + 0x8000);
4411 			}
4412 			ap->prd[idx].flags_len = cpu_to_le32(blen);
4413 			VPRINTK("PRD[%u] = (0x%X, 0x%X)\n", idx, addr, len);
4414 
4415 			idx++;
4416 			sg_len -= len;
4417 			addr += len;
4418 		}
4419 	}
4420 
4421 	if (idx)
4422 		ap->prd[idx - 1].flags_len |= cpu_to_le32(ATA_PRD_EOT);
4423 }
4424 
4425 /**
4426  *	ata_check_atapi_dma - Check whether ATAPI DMA can be supported
4427  *	@qc: Metadata associated with taskfile to check
4428  *
4429  *	Allow low-level driver to filter ATA PACKET commands, returning
4430  *	a status indicating whether or not it is OK to use DMA for the
4431  *	supplied PACKET command.
4432  *
4433  *	LOCKING:
4434  *	spin_lock_irqsave(host lock)
4435  *
4436  *	RETURNS: 0 when ATAPI DMA can be used
4437  *               nonzero otherwise
4438  */
4439 int ata_check_atapi_dma(struct ata_queued_cmd *qc)
4440 {
4441 	struct ata_port *ap = qc->ap;
4442 
4443 	/* Don't allow DMA if it isn't multiple of 16 bytes.  Quite a
4444 	 * few ATAPI devices choke on such DMA requests.
4445 	 */
4446 	if (unlikely(qc->nbytes & 15))
4447 		return 1;
4448 
4449 	if (ap->ops->check_atapi_dma)
4450 		return ap->ops->check_atapi_dma(qc);
4451 
4452 	return 0;
4453 }
4454 
4455 /**
4456  *	ata_std_qc_defer - Check whether a qc needs to be deferred
4457  *	@qc: ATA command in question
4458  *
4459  *	Non-NCQ commands cannot run with any other command, NCQ or
4460  *	not.  As upper layer only knows the queue depth, we are
4461  *	responsible for maintaining exclusion.  This function checks
4462  *	whether a new command @qc can be issued.
4463  *
4464  *	LOCKING:
4465  *	spin_lock_irqsave(host lock)
4466  *
4467  *	RETURNS:
4468  *	ATA_DEFER_* if deferring is needed, 0 otherwise.
4469  */
4470 int ata_std_qc_defer(struct ata_queued_cmd *qc)
4471 {
4472 	struct ata_link *link = qc->dev->link;
4473 
4474 	if (qc->tf.protocol == ATA_PROT_NCQ) {
4475 		if (!ata_tag_valid(link->active_tag))
4476 			return 0;
4477 	} else {
4478 		if (!ata_tag_valid(link->active_tag) && !link->sactive)
4479 			return 0;
4480 	}
4481 
4482 	return ATA_DEFER_LINK;
4483 }
4484 
4485 /**
4486  *	ata_qc_prep - Prepare taskfile for submission
4487  *	@qc: Metadata associated with taskfile to be prepared
4488  *
4489  *	Prepare ATA taskfile for submission.
4490  *
4491  *	LOCKING:
4492  *	spin_lock_irqsave(host lock)
4493  */
4494 void ata_qc_prep(struct ata_queued_cmd *qc)
4495 {
4496 	if (!(qc->flags & ATA_QCFLAG_DMAMAP))
4497 		return;
4498 
4499 	ata_fill_sg(qc);
4500 }
4501 
4502 /**
4503  *	ata_dumb_qc_prep - Prepare taskfile for submission
4504  *	@qc: Metadata associated with taskfile to be prepared
4505  *
4506  *	Prepare ATA taskfile for submission.
4507  *
4508  *	LOCKING:
4509  *	spin_lock_irqsave(host lock)
4510  */
4511 void ata_dumb_qc_prep(struct ata_queued_cmd *qc)
4512 {
4513 	if (!(qc->flags & ATA_QCFLAG_DMAMAP))
4514 		return;
4515 
4516 	ata_fill_sg_dumb(qc);
4517 }
4518 
4519 void ata_noop_qc_prep(struct ata_queued_cmd *qc) { }
4520 
4521 /**
4522  *	ata_sg_init_one - Associate command with memory buffer
4523  *	@qc: Command to be associated
4524  *	@buf: Memory buffer
4525  *	@buflen: Length of memory buffer, in bytes.
4526  *
4527  *	Initialize the data-related elements of queued_cmd @qc
4528  *	to point to a single memory buffer, @buf of byte length @buflen.
4529  *
4530  *	LOCKING:
4531  *	spin_lock_irqsave(host lock)
4532  */
4533 
4534 void ata_sg_init_one(struct ata_queued_cmd *qc, void *buf, unsigned int buflen)
4535 {
4536 	qc->flags |= ATA_QCFLAG_SINGLE;
4537 
4538 	qc->__sg = &qc->sgent;
4539 	qc->n_elem = 1;
4540 	qc->orig_n_elem = 1;
4541 	qc->buf_virt = buf;
4542 	qc->nbytes = buflen;
4543 
4544 	sg_init_one(&qc->sgent, buf, buflen);
4545 }
4546 
4547 /**
4548  *	ata_sg_init - Associate command with scatter-gather table.
4549  *	@qc: Command to be associated
4550  *	@sg: Scatter-gather table.
4551  *	@n_elem: Number of elements in s/g table.
4552  *
4553  *	Initialize the data-related elements of queued_cmd @qc
4554  *	to point to a scatter-gather table @sg, containing @n_elem
4555  *	elements.
4556  *
4557  *	LOCKING:
4558  *	spin_lock_irqsave(host lock)
4559  */
4560 
4561 void ata_sg_init(struct ata_queued_cmd *qc, struct scatterlist *sg,
4562 		 unsigned int n_elem)
4563 {
4564 	qc->flags |= ATA_QCFLAG_SG;
4565 	qc->__sg = sg;
4566 	qc->n_elem = n_elem;
4567 	qc->orig_n_elem = n_elem;
4568 }
4569 
4570 /**
4571  *	ata_sg_setup_one - DMA-map the memory buffer associated with a command.
4572  *	@qc: Command with memory buffer to be mapped.
4573  *
4574  *	DMA-map the memory buffer associated with queued_cmd @qc.
4575  *
4576  *	LOCKING:
4577  *	spin_lock_irqsave(host lock)
4578  *
4579  *	RETURNS:
4580  *	Zero on success, negative on error.
4581  */
4582 
4583 static int ata_sg_setup_one(struct ata_queued_cmd *qc)
4584 {
4585 	struct ata_port *ap = qc->ap;
4586 	int dir = qc->dma_dir;
4587 	struct scatterlist *sg = qc->__sg;
4588 	dma_addr_t dma_address;
4589 	int trim_sg = 0;
4590 
4591 	/* we must lengthen transfers to end on a 32-bit boundary */
4592 	qc->pad_len = sg->length & 3;
4593 	if (qc->pad_len) {
4594 		void *pad_buf = ap->pad + (qc->tag * ATA_DMA_PAD_SZ);
4595 		struct scatterlist *psg = &qc->pad_sgent;
4596 
4597 		WARN_ON(qc->dev->class != ATA_DEV_ATAPI);
4598 
4599 		memset(pad_buf, 0, ATA_DMA_PAD_SZ);
4600 
4601 		if (qc->tf.flags & ATA_TFLAG_WRITE)
4602 			memcpy(pad_buf, qc->buf_virt + sg->length - qc->pad_len,
4603 			       qc->pad_len);
4604 
4605 		sg_dma_address(psg) = ap->pad_dma + (qc->tag * ATA_DMA_PAD_SZ);
4606 		sg_dma_len(psg) = ATA_DMA_PAD_SZ;
4607 		/* trim sg */
4608 		sg->length -= qc->pad_len;
4609 		if (sg->length == 0)
4610 			trim_sg = 1;
4611 
4612 		DPRINTK("padding done, sg->length=%u pad_len=%u\n",
4613 			sg->length, qc->pad_len);
4614 	}
4615 
4616 	if (trim_sg) {
4617 		qc->n_elem--;
4618 		goto skip_map;
4619 	}
4620 
4621 	dma_address = dma_map_single(ap->dev, qc->buf_virt,
4622 				     sg->length, dir);
4623 	if (dma_mapping_error(dma_address)) {
4624 		/* restore sg */
4625 		sg->length += qc->pad_len;
4626 		return -1;
4627 	}
4628 
4629 	sg_dma_address(sg) = dma_address;
4630 	sg_dma_len(sg) = sg->length;
4631 
4632 skip_map:
4633 	DPRINTK("mapped buffer of %d bytes for %s\n", sg_dma_len(sg),
4634 		qc->tf.flags & ATA_TFLAG_WRITE ? "write" : "read");
4635 
4636 	return 0;
4637 }
4638 
4639 /**
4640  *	ata_sg_setup - DMA-map the scatter-gather table associated with a command.
4641  *	@qc: Command with scatter-gather table to be mapped.
4642  *
4643  *	DMA-map the scatter-gather table associated with queued_cmd @qc.
4644  *
4645  *	LOCKING:
4646  *	spin_lock_irqsave(host lock)
4647  *
4648  *	RETURNS:
4649  *	Zero on success, negative on error.
4650  *
4651  */
4652 
4653 static int ata_sg_setup(struct ata_queued_cmd *qc)
4654 {
4655 	struct ata_port *ap = qc->ap;
4656 	struct scatterlist *sg = qc->__sg;
4657 	struct scatterlist *lsg = &sg[qc->n_elem - 1];
4658 	int n_elem, pre_n_elem, dir, trim_sg = 0;
4659 
4660 	VPRINTK("ENTER, ata%u\n", ap->print_id);
4661 	WARN_ON(!(qc->flags & ATA_QCFLAG_SG));
4662 
4663 	/* we must lengthen transfers to end on a 32-bit boundary */
4664 	qc->pad_len = lsg->length & 3;
4665 	if (qc->pad_len) {
4666 		void *pad_buf = ap->pad + (qc->tag * ATA_DMA_PAD_SZ);
4667 		struct scatterlist *psg = &qc->pad_sgent;
4668 		unsigned int offset;
4669 
4670 		WARN_ON(qc->dev->class != ATA_DEV_ATAPI);
4671 
4672 		memset(pad_buf, 0, ATA_DMA_PAD_SZ);
4673 
4674 		/*
4675 		 * psg->page/offset are used to copy to-be-written
4676 		 * data in this function or read data in ata_sg_clean.
4677 		 */
4678 		offset = lsg->offset + lsg->length - qc->pad_len;
4679 		psg->page = nth_page(lsg->page, offset >> PAGE_SHIFT);
4680 		psg->offset = offset_in_page(offset);
4681 
4682 		if (qc->tf.flags & ATA_TFLAG_WRITE) {
4683 			void *addr = kmap_atomic(psg->page, KM_IRQ0);
4684 			memcpy(pad_buf, addr + psg->offset, qc->pad_len);
4685 			kunmap_atomic(addr, KM_IRQ0);
4686 		}
4687 
4688 		sg_dma_address(psg) = ap->pad_dma + (qc->tag * ATA_DMA_PAD_SZ);
4689 		sg_dma_len(psg) = ATA_DMA_PAD_SZ;
4690 		/* trim last sg */
4691 		lsg->length -= qc->pad_len;
4692 		if (lsg->length == 0)
4693 			trim_sg = 1;
4694 
4695 		DPRINTK("padding done, sg[%d].length=%u pad_len=%u\n",
4696 			qc->n_elem - 1, lsg->length, qc->pad_len);
4697 	}
4698 
4699 	pre_n_elem = qc->n_elem;
4700 	if (trim_sg && pre_n_elem)
4701 		pre_n_elem--;
4702 
4703 	if (!pre_n_elem) {
4704 		n_elem = 0;
4705 		goto skip_map;
4706 	}
4707 
4708 	dir = qc->dma_dir;
4709 	n_elem = dma_map_sg(ap->dev, sg, pre_n_elem, dir);
4710 	if (n_elem < 1) {
4711 		/* restore last sg */
4712 		lsg->length += qc->pad_len;
4713 		return -1;
4714 	}
4715 
4716 	DPRINTK("%d sg elements mapped\n", n_elem);
4717 
4718 skip_map:
4719 	qc->n_elem = n_elem;
4720 
4721 	return 0;
4722 }
4723 
4724 /**
4725  *	swap_buf_le16 - swap halves of 16-bit words in place
4726  *	@buf:  Buffer to swap
4727  *	@buf_words:  Number of 16-bit words in buffer.
4728  *
4729  *	Swap halves of 16-bit words if needed to convert from
4730  *	little-endian byte order to native cpu byte order, or
4731  *	vice-versa.
4732  *
4733  *	LOCKING:
4734  *	Inherited from caller.
4735  */
4736 void swap_buf_le16(u16 *buf, unsigned int buf_words)
4737 {
4738 #ifdef __BIG_ENDIAN
4739 	unsigned int i;
4740 
4741 	for (i = 0; i < buf_words; i++)
4742 		buf[i] = le16_to_cpu(buf[i]);
4743 #endif /* __BIG_ENDIAN */
4744 }
4745 
4746 /**
4747  *	ata_data_xfer - Transfer data by PIO
4748  *	@adev: device to target
4749  *	@buf: data buffer
4750  *	@buflen: buffer length
4751  *	@write_data: read/write
4752  *
4753  *	Transfer data from/to the device data register by PIO.
4754  *
4755  *	LOCKING:
4756  *	Inherited from caller.
4757  */
4758 void ata_data_xfer(struct ata_device *adev, unsigned char *buf,
4759 		   unsigned int buflen, int write_data)
4760 {
4761 	struct ata_port *ap = adev->link->ap;
4762 	unsigned int words = buflen >> 1;
4763 
4764 	/* Transfer multiple of 2 bytes */
4765 	if (write_data)
4766 		iowrite16_rep(ap->ioaddr.data_addr, buf, words);
4767 	else
4768 		ioread16_rep(ap->ioaddr.data_addr, buf, words);
4769 
4770 	/* Transfer trailing 1 byte, if any. */
4771 	if (unlikely(buflen & 0x01)) {
4772 		u16 align_buf[1] = { 0 };
4773 		unsigned char *trailing_buf = buf + buflen - 1;
4774 
4775 		if (write_data) {
4776 			memcpy(align_buf, trailing_buf, 1);
4777 			iowrite16(le16_to_cpu(align_buf[0]), ap->ioaddr.data_addr);
4778 		} else {
4779 			align_buf[0] = cpu_to_le16(ioread16(ap->ioaddr.data_addr));
4780 			memcpy(trailing_buf, align_buf, 1);
4781 		}
4782 	}
4783 }
4784 
4785 /**
4786  *	ata_data_xfer_noirq - Transfer data by PIO
4787  *	@adev: device to target
4788  *	@buf: data buffer
4789  *	@buflen: buffer length
4790  *	@write_data: read/write
4791  *
4792  *	Transfer data from/to the device data register by PIO. Do the
4793  *	transfer with interrupts disabled.
4794  *
4795  *	LOCKING:
4796  *	Inherited from caller.
4797  */
4798 void ata_data_xfer_noirq(struct ata_device *adev, unsigned char *buf,
4799 			 unsigned int buflen, int write_data)
4800 {
4801 	unsigned long flags;
4802 	local_irq_save(flags);
4803 	ata_data_xfer(adev, buf, buflen, write_data);
4804 	local_irq_restore(flags);
4805 }
4806 
4807 
4808 /**
4809  *	ata_pio_sector - Transfer a sector of data.
4810  *	@qc: Command on going
4811  *
4812  *	Transfer qc->sect_size bytes of data from/to the ATA device.
4813  *
4814  *	LOCKING:
4815  *	Inherited from caller.
4816  */
4817 
4818 static void ata_pio_sector(struct ata_queued_cmd *qc)
4819 {
4820 	int do_write = (qc->tf.flags & ATA_TFLAG_WRITE);
4821 	struct scatterlist *sg = qc->__sg;
4822 	struct ata_port *ap = qc->ap;
4823 	struct page *page;
4824 	unsigned int offset;
4825 	unsigned char *buf;
4826 
4827 	if (qc->curbytes == qc->nbytes - qc->sect_size)
4828 		ap->hsm_task_state = HSM_ST_LAST;
4829 
4830 	page = sg[qc->cursg].page;
4831 	offset = sg[qc->cursg].offset + qc->cursg_ofs;
4832 
4833 	/* get the current page and offset */
4834 	page = nth_page(page, (offset >> PAGE_SHIFT));
4835 	offset %= PAGE_SIZE;
4836 
4837 	DPRINTK("data %s\n", qc->tf.flags & ATA_TFLAG_WRITE ? "write" : "read");
4838 
4839 	if (PageHighMem(page)) {
4840 		unsigned long flags;
4841 
4842 		/* FIXME: use a bounce buffer */
4843 		local_irq_save(flags);
4844 		buf = kmap_atomic(page, KM_IRQ0);
4845 
4846 		/* do the actual data transfer */
4847 		ap->ops->data_xfer(qc->dev, buf + offset, qc->sect_size, do_write);
4848 
4849 		kunmap_atomic(buf, KM_IRQ0);
4850 		local_irq_restore(flags);
4851 	} else {
4852 		buf = page_address(page);
4853 		ap->ops->data_xfer(qc->dev, buf + offset, qc->sect_size, do_write);
4854 	}
4855 
4856 	qc->curbytes += qc->sect_size;
4857 	qc->cursg_ofs += qc->sect_size;
4858 
4859 	if (qc->cursg_ofs == (&sg[qc->cursg])->length) {
4860 		qc->cursg++;
4861 		qc->cursg_ofs = 0;
4862 	}
4863 }
4864 
4865 /**
4866  *	ata_pio_sectors - Transfer one or many sectors.
4867  *	@qc: Command on going
4868  *
4869  *	Transfer one or many sectors of data from/to the
4870  *	ATA device for the DRQ request.
4871  *
4872  *	LOCKING:
4873  *	Inherited from caller.
4874  */
4875 
4876 static void ata_pio_sectors(struct ata_queued_cmd *qc)
4877 {
4878 	if (is_multi_taskfile(&qc->tf)) {
4879 		/* READ/WRITE MULTIPLE */
4880 		unsigned int nsect;
4881 
4882 		WARN_ON(qc->dev->multi_count == 0);
4883 
4884 		nsect = min((qc->nbytes - qc->curbytes) / qc->sect_size,
4885 			    qc->dev->multi_count);
4886 		while (nsect--)
4887 			ata_pio_sector(qc);
4888 	} else
4889 		ata_pio_sector(qc);
4890 
4891 	ata_altstatus(qc->ap); /* flush */
4892 }
4893 
4894 /**
4895  *	atapi_send_cdb - Write CDB bytes to hardware
4896  *	@ap: Port to which ATAPI device is attached.
4897  *	@qc: Taskfile currently active
4898  *
4899  *	When device has indicated its readiness to accept
4900  *	a CDB, this function is called.  Send the CDB.
4901  *
4902  *	LOCKING:
4903  *	caller.
4904  */
4905 
4906 static void atapi_send_cdb(struct ata_port *ap, struct ata_queued_cmd *qc)
4907 {
4908 	/* send SCSI cdb */
4909 	DPRINTK("send cdb\n");
4910 	WARN_ON(qc->dev->cdb_len < 12);
4911 
4912 	ap->ops->data_xfer(qc->dev, qc->cdb, qc->dev->cdb_len, 1);
4913 	ata_altstatus(ap); /* flush */
4914 
4915 	switch (qc->tf.protocol) {
4916 	case ATA_PROT_ATAPI:
4917 		ap->hsm_task_state = HSM_ST;
4918 		break;
4919 	case ATA_PROT_ATAPI_NODATA:
4920 		ap->hsm_task_state = HSM_ST_LAST;
4921 		break;
4922 	case ATA_PROT_ATAPI_DMA:
4923 		ap->hsm_task_state = HSM_ST_LAST;
4924 		/* initiate bmdma */
4925 		ap->ops->bmdma_start(qc);
4926 		break;
4927 	}
4928 }
4929 
4930 /**
4931  *	__atapi_pio_bytes - Transfer data from/to the ATAPI device.
4932  *	@qc: Command on going
4933  *	@bytes: number of bytes
4934  *
4935  *	Transfer Transfer data from/to the ATAPI device.
4936  *
4937  *	LOCKING:
4938  *	Inherited from caller.
4939  *
4940  */
4941 
4942 static void __atapi_pio_bytes(struct ata_queued_cmd *qc, unsigned int bytes)
4943 {
4944 	int do_write = (qc->tf.flags & ATA_TFLAG_WRITE);
4945 	struct scatterlist *sg = qc->__sg;
4946 	struct ata_port *ap = qc->ap;
4947 	struct page *page;
4948 	unsigned char *buf;
4949 	unsigned int offset, count;
4950 
4951 	if (qc->curbytes + bytes >= qc->nbytes)
4952 		ap->hsm_task_state = HSM_ST_LAST;
4953 
4954 next_sg:
4955 	if (unlikely(qc->cursg >= qc->n_elem)) {
4956 		/*
4957 		 * The end of qc->sg is reached and the device expects
4958 		 * more data to transfer. In order not to overrun qc->sg
4959 		 * and fulfill length specified in the byte count register,
4960 		 *    - for read case, discard trailing data from the device
4961 		 *    - for write case, padding zero data to the device
4962 		 */
4963 		u16 pad_buf[1] = { 0 };
4964 		unsigned int words = bytes >> 1;
4965 		unsigned int i;
4966 
4967 		if (words) /* warning if bytes > 1 */
4968 			ata_dev_printk(qc->dev, KERN_WARNING,
4969 				       "%u bytes trailing data\n", bytes);
4970 
4971 		for (i = 0; i < words; i++)
4972 			ap->ops->data_xfer(qc->dev, (unsigned char*)pad_buf, 2, do_write);
4973 
4974 		ap->hsm_task_state = HSM_ST_LAST;
4975 		return;
4976 	}
4977 
4978 	sg = &qc->__sg[qc->cursg];
4979 
4980 	page = sg->page;
4981 	offset = sg->offset + qc->cursg_ofs;
4982 
4983 	/* get the current page and offset */
4984 	page = nth_page(page, (offset >> PAGE_SHIFT));
4985 	offset %= PAGE_SIZE;
4986 
4987 	/* don't overrun current sg */
4988 	count = min(sg->length - qc->cursg_ofs, bytes);
4989 
4990 	/* don't cross page boundaries */
4991 	count = min(count, (unsigned int)PAGE_SIZE - offset);
4992 
4993 	DPRINTK("data %s\n", qc->tf.flags & ATA_TFLAG_WRITE ? "write" : "read");
4994 
4995 	if (PageHighMem(page)) {
4996 		unsigned long flags;
4997 
4998 		/* FIXME: use bounce buffer */
4999 		local_irq_save(flags);
5000 		buf = kmap_atomic(page, KM_IRQ0);
5001 
5002 		/* do the actual data transfer */
5003 		ap->ops->data_xfer(qc->dev,  buf + offset, count, do_write);
5004 
5005 		kunmap_atomic(buf, KM_IRQ0);
5006 		local_irq_restore(flags);
5007 	} else {
5008 		buf = page_address(page);
5009 		ap->ops->data_xfer(qc->dev,  buf + offset, count, do_write);
5010 	}
5011 
5012 	bytes -= count;
5013 	qc->curbytes += count;
5014 	qc->cursg_ofs += count;
5015 
5016 	if (qc->cursg_ofs == sg->length) {
5017 		qc->cursg++;
5018 		qc->cursg_ofs = 0;
5019 	}
5020 
5021 	if (bytes)
5022 		goto next_sg;
5023 }
5024 
5025 /**
5026  *	atapi_pio_bytes - Transfer data from/to the ATAPI device.
5027  *	@qc: Command on going
5028  *
5029  *	Transfer Transfer data from/to the ATAPI device.
5030  *
5031  *	LOCKING:
5032  *	Inherited from caller.
5033  */
5034 
5035 static void atapi_pio_bytes(struct ata_queued_cmd *qc)
5036 {
5037 	struct ata_port *ap = qc->ap;
5038 	struct ata_device *dev = qc->dev;
5039 	unsigned int ireason, bc_lo, bc_hi, bytes;
5040 	int i_write, do_write = (qc->tf.flags & ATA_TFLAG_WRITE) ? 1 : 0;
5041 
5042 	/* Abuse qc->result_tf for temp storage of intermediate TF
5043 	 * here to save some kernel stack usage.
5044 	 * For normal completion, qc->result_tf is not relevant. For
5045 	 * error, qc->result_tf is later overwritten by ata_qc_complete().
5046 	 * So, the correctness of qc->result_tf is not affected.
5047 	 */
5048 	ap->ops->tf_read(ap, &qc->result_tf);
5049 	ireason = qc->result_tf.nsect;
5050 	bc_lo = qc->result_tf.lbam;
5051 	bc_hi = qc->result_tf.lbah;
5052 	bytes = (bc_hi << 8) | bc_lo;
5053 
5054 	/* shall be cleared to zero, indicating xfer of data */
5055 	if (ireason & (1 << 0))
5056 		goto err_out;
5057 
5058 	/* make sure transfer direction matches expected */
5059 	i_write = ((ireason & (1 << 1)) == 0) ? 1 : 0;
5060 	if (do_write != i_write)
5061 		goto err_out;
5062 
5063 	VPRINTK("ata%u: xfering %d bytes\n", ap->print_id, bytes);
5064 
5065 	__atapi_pio_bytes(qc, bytes);
5066 	ata_altstatus(ap); /* flush */
5067 
5068 	return;
5069 
5070 err_out:
5071 	ata_dev_printk(dev, KERN_INFO, "ATAPI check failed\n");
5072 	qc->err_mask |= AC_ERR_HSM;
5073 	ap->hsm_task_state = HSM_ST_ERR;
5074 }
5075 
5076 /**
5077  *	ata_hsm_ok_in_wq - Check if the qc can be handled in the workqueue.
5078  *	@ap: the target ata_port
5079  *	@qc: qc on going
5080  *
5081  *	RETURNS:
5082  *	1 if ok in workqueue, 0 otherwise.
5083  */
5084 
5085 static inline int ata_hsm_ok_in_wq(struct ata_port *ap, struct ata_queued_cmd *qc)
5086 {
5087 	if (qc->tf.flags & ATA_TFLAG_POLLING)
5088 		return 1;
5089 
5090 	if (ap->hsm_task_state == HSM_ST_FIRST) {
5091 		if (qc->tf.protocol == ATA_PROT_PIO &&
5092 		    (qc->tf.flags & ATA_TFLAG_WRITE))
5093 		    return 1;
5094 
5095 		if (is_atapi_taskfile(&qc->tf) &&
5096 		    !(qc->dev->flags & ATA_DFLAG_CDB_INTR))
5097 			return 1;
5098 	}
5099 
5100 	return 0;
5101 }
5102 
5103 /**
5104  *	ata_hsm_qc_complete - finish a qc running on standard HSM
5105  *	@qc: Command to complete
5106  *	@in_wq: 1 if called from workqueue, 0 otherwise
5107  *
5108  *	Finish @qc which is running on standard HSM.
5109  *
5110  *	LOCKING:
5111  *	If @in_wq is zero, spin_lock_irqsave(host lock).
5112  *	Otherwise, none on entry and grabs host lock.
5113  */
5114 static void ata_hsm_qc_complete(struct ata_queued_cmd *qc, int in_wq)
5115 {
5116 	struct ata_port *ap = qc->ap;
5117 	unsigned long flags;
5118 
5119 	if (ap->ops->error_handler) {
5120 		if (in_wq) {
5121 			spin_lock_irqsave(ap->lock, flags);
5122 
5123 			/* EH might have kicked in while host lock is
5124 			 * released.
5125 			 */
5126 			qc = ata_qc_from_tag(ap, qc->tag);
5127 			if (qc) {
5128 				if (likely(!(qc->err_mask & AC_ERR_HSM))) {
5129 					ap->ops->irq_on(ap);
5130 					ata_qc_complete(qc);
5131 				} else
5132 					ata_port_freeze(ap);
5133 			}
5134 
5135 			spin_unlock_irqrestore(ap->lock, flags);
5136 		} else {
5137 			if (likely(!(qc->err_mask & AC_ERR_HSM)))
5138 				ata_qc_complete(qc);
5139 			else
5140 				ata_port_freeze(ap);
5141 		}
5142 	} else {
5143 		if (in_wq) {
5144 			spin_lock_irqsave(ap->lock, flags);
5145 			ap->ops->irq_on(ap);
5146 			ata_qc_complete(qc);
5147 			spin_unlock_irqrestore(ap->lock, flags);
5148 		} else
5149 			ata_qc_complete(qc);
5150 	}
5151 }
5152 
5153 /**
5154  *	ata_hsm_move - move the HSM to the next state.
5155  *	@ap: the target ata_port
5156  *	@qc: qc on going
5157  *	@status: current device status
5158  *	@in_wq: 1 if called from workqueue, 0 otherwise
5159  *
5160  *	RETURNS:
5161  *	1 when poll next status needed, 0 otherwise.
5162  */
5163 int ata_hsm_move(struct ata_port *ap, struct ata_queued_cmd *qc,
5164 		 u8 status, int in_wq)
5165 {
5166 	unsigned long flags = 0;
5167 	int poll_next;
5168 
5169 	WARN_ON((qc->flags & ATA_QCFLAG_ACTIVE) == 0);
5170 
5171 	/* Make sure ata_qc_issue_prot() does not throw things
5172 	 * like DMA polling into the workqueue. Notice that
5173 	 * in_wq is not equivalent to (qc->tf.flags & ATA_TFLAG_POLLING).
5174 	 */
5175 	WARN_ON(in_wq != ata_hsm_ok_in_wq(ap, qc));
5176 
5177 fsm_start:
5178 	DPRINTK("ata%u: protocol %d task_state %d (dev_stat 0x%X)\n",
5179 		ap->print_id, qc->tf.protocol, ap->hsm_task_state, status);
5180 
5181 	switch (ap->hsm_task_state) {
5182 	case HSM_ST_FIRST:
5183 		/* Send first data block or PACKET CDB */
5184 
5185 		/* If polling, we will stay in the work queue after
5186 		 * sending the data. Otherwise, interrupt handler
5187 		 * takes over after sending the data.
5188 		 */
5189 		poll_next = (qc->tf.flags & ATA_TFLAG_POLLING);
5190 
5191 		/* check device status */
5192 		if (unlikely((status & ATA_DRQ) == 0)) {
5193 			/* handle BSY=0, DRQ=0 as error */
5194 			if (likely(status & (ATA_ERR | ATA_DF)))
5195 				/* device stops HSM for abort/error */
5196 				qc->err_mask |= AC_ERR_DEV;
5197 			else
5198 				/* HSM violation. Let EH handle this */
5199 				qc->err_mask |= AC_ERR_HSM;
5200 
5201 			ap->hsm_task_state = HSM_ST_ERR;
5202 			goto fsm_start;
5203 		}
5204 
5205 		/* Device should not ask for data transfer (DRQ=1)
5206 		 * when it finds something wrong.
5207 		 * We ignore DRQ here and stop the HSM by
5208 		 * changing hsm_task_state to HSM_ST_ERR and
5209 		 * let the EH abort the command or reset the device.
5210 		 */
5211 		if (unlikely(status & (ATA_ERR | ATA_DF))) {
5212 			ata_port_printk(ap, KERN_WARNING, "DRQ=1 with device "
5213 					"error, dev_stat 0x%X\n", status);
5214 			qc->err_mask |= AC_ERR_HSM;
5215 			ap->hsm_task_state = HSM_ST_ERR;
5216 			goto fsm_start;
5217 		}
5218 
5219 		/* Send the CDB (atapi) or the first data block (ata pio out).
5220 		 * During the state transition, interrupt handler shouldn't
5221 		 * be invoked before the data transfer is complete and
5222 		 * hsm_task_state is changed. Hence, the following locking.
5223 		 */
5224 		if (in_wq)
5225 			spin_lock_irqsave(ap->lock, flags);
5226 
5227 		if (qc->tf.protocol == ATA_PROT_PIO) {
5228 			/* PIO data out protocol.
5229 			 * send first data block.
5230 			 */
5231 
5232 			/* ata_pio_sectors() might change the state
5233 			 * to HSM_ST_LAST. so, the state is changed here
5234 			 * before ata_pio_sectors().
5235 			 */
5236 			ap->hsm_task_state = HSM_ST;
5237 			ata_pio_sectors(qc);
5238 		} else
5239 			/* send CDB */
5240 			atapi_send_cdb(ap, qc);
5241 
5242 		if (in_wq)
5243 			spin_unlock_irqrestore(ap->lock, flags);
5244 
5245 		/* if polling, ata_pio_task() handles the rest.
5246 		 * otherwise, interrupt handler takes over from here.
5247 		 */
5248 		break;
5249 
5250 	case HSM_ST:
5251 		/* complete command or read/write the data register */
5252 		if (qc->tf.protocol == ATA_PROT_ATAPI) {
5253 			/* ATAPI PIO protocol */
5254 			if ((status & ATA_DRQ) == 0) {
5255 				/* No more data to transfer or device error.
5256 				 * Device error will be tagged in HSM_ST_LAST.
5257 				 */
5258 				ap->hsm_task_state = HSM_ST_LAST;
5259 				goto fsm_start;
5260 			}
5261 
5262 			/* Device should not ask for data transfer (DRQ=1)
5263 			 * when it finds something wrong.
5264 			 * We ignore DRQ here and stop the HSM by
5265 			 * changing hsm_task_state to HSM_ST_ERR and
5266 			 * let the EH abort the command or reset the device.
5267 			 */
5268 			if (unlikely(status & (ATA_ERR | ATA_DF))) {
5269 				ata_port_printk(ap, KERN_WARNING, "DRQ=1 with "
5270 						"device error, dev_stat 0x%X\n",
5271 						status);
5272 				qc->err_mask |= AC_ERR_HSM;
5273 				ap->hsm_task_state = HSM_ST_ERR;
5274 				goto fsm_start;
5275 			}
5276 
5277 			atapi_pio_bytes(qc);
5278 
5279 			if (unlikely(ap->hsm_task_state == HSM_ST_ERR))
5280 				/* bad ireason reported by device */
5281 				goto fsm_start;
5282 
5283 		} else {
5284 			/* ATA PIO protocol */
5285 			if (unlikely((status & ATA_DRQ) == 0)) {
5286 				/* handle BSY=0, DRQ=0 as error */
5287 				if (likely(status & (ATA_ERR | ATA_DF)))
5288 					/* device stops HSM for abort/error */
5289 					qc->err_mask |= AC_ERR_DEV;
5290 				else
5291 					/* HSM violation. Let EH handle this.
5292 					 * Phantom devices also trigger this
5293 					 * condition.  Mark hint.
5294 					 */
5295 					qc->err_mask |= AC_ERR_HSM |
5296 							AC_ERR_NODEV_HINT;
5297 
5298 				ap->hsm_task_state = HSM_ST_ERR;
5299 				goto fsm_start;
5300 			}
5301 
5302 			/* For PIO reads, some devices may ask for
5303 			 * data transfer (DRQ=1) alone with ERR=1.
5304 			 * We respect DRQ here and transfer one
5305 			 * block of junk data before changing the
5306 			 * hsm_task_state to HSM_ST_ERR.
5307 			 *
5308 			 * For PIO writes, ERR=1 DRQ=1 doesn't make
5309 			 * sense since the data block has been
5310 			 * transferred to the device.
5311 			 */
5312 			if (unlikely(status & (ATA_ERR | ATA_DF))) {
5313 				/* data might be corrputed */
5314 				qc->err_mask |= AC_ERR_DEV;
5315 
5316 				if (!(qc->tf.flags & ATA_TFLAG_WRITE)) {
5317 					ata_pio_sectors(qc);
5318 					status = ata_wait_idle(ap);
5319 				}
5320 
5321 				if (status & (ATA_BUSY | ATA_DRQ))
5322 					qc->err_mask |= AC_ERR_HSM;
5323 
5324 				/* ata_pio_sectors() might change the
5325 				 * state to HSM_ST_LAST. so, the state
5326 				 * is changed after ata_pio_sectors().
5327 				 */
5328 				ap->hsm_task_state = HSM_ST_ERR;
5329 				goto fsm_start;
5330 			}
5331 
5332 			ata_pio_sectors(qc);
5333 
5334 			if (ap->hsm_task_state == HSM_ST_LAST &&
5335 			    (!(qc->tf.flags & ATA_TFLAG_WRITE))) {
5336 				/* all data read */
5337 				status = ata_wait_idle(ap);
5338 				goto fsm_start;
5339 			}
5340 		}
5341 
5342 		poll_next = 1;
5343 		break;
5344 
5345 	case HSM_ST_LAST:
5346 		if (unlikely(!ata_ok(status))) {
5347 			qc->err_mask |= __ac_err_mask(status);
5348 			ap->hsm_task_state = HSM_ST_ERR;
5349 			goto fsm_start;
5350 		}
5351 
5352 		/* no more data to transfer */
5353 		DPRINTK("ata%u: dev %u command complete, drv_stat 0x%x\n",
5354 			ap->print_id, qc->dev->devno, status);
5355 
5356 		WARN_ON(qc->err_mask);
5357 
5358 		ap->hsm_task_state = HSM_ST_IDLE;
5359 
5360 		/* complete taskfile transaction */
5361 		ata_hsm_qc_complete(qc, in_wq);
5362 
5363 		poll_next = 0;
5364 		break;
5365 
5366 	case HSM_ST_ERR:
5367 		/* make sure qc->err_mask is available to
5368 		 * know what's wrong and recover
5369 		 */
5370 		WARN_ON(qc->err_mask == 0);
5371 
5372 		ap->hsm_task_state = HSM_ST_IDLE;
5373 
5374 		/* complete taskfile transaction */
5375 		ata_hsm_qc_complete(qc, in_wq);
5376 
5377 		poll_next = 0;
5378 		break;
5379 	default:
5380 		poll_next = 0;
5381 		BUG();
5382 	}
5383 
5384 	return poll_next;
5385 }
5386 
5387 static void ata_pio_task(struct work_struct *work)
5388 {
5389 	struct ata_port *ap =
5390 		container_of(work, struct ata_port, port_task.work);
5391 	struct ata_queued_cmd *qc = ap->port_task_data;
5392 	u8 status;
5393 	int poll_next;
5394 
5395 fsm_start:
5396 	WARN_ON(ap->hsm_task_state == HSM_ST_IDLE);
5397 
5398 	/*
5399 	 * This is purely heuristic.  This is a fast path.
5400 	 * Sometimes when we enter, BSY will be cleared in
5401 	 * a chk-status or two.  If not, the drive is probably seeking
5402 	 * or something.  Snooze for a couple msecs, then
5403 	 * chk-status again.  If still busy, queue delayed work.
5404 	 */
5405 	status = ata_busy_wait(ap, ATA_BUSY, 5);
5406 	if (status & ATA_BUSY) {
5407 		msleep(2);
5408 		status = ata_busy_wait(ap, ATA_BUSY, 10);
5409 		if (status & ATA_BUSY) {
5410 			ata_port_queue_task(ap, ata_pio_task, qc, ATA_SHORT_PAUSE);
5411 			return;
5412 		}
5413 	}
5414 
5415 	/* move the HSM */
5416 	poll_next = ata_hsm_move(ap, qc, status, 1);
5417 
5418 	/* another command or interrupt handler
5419 	 * may be running at this point.
5420 	 */
5421 	if (poll_next)
5422 		goto fsm_start;
5423 }
5424 
5425 /**
5426  *	ata_qc_new - Request an available ATA command, for queueing
5427  *	@ap: Port associated with device @dev
5428  *	@dev: Device from whom we request an available command structure
5429  *
5430  *	LOCKING:
5431  *	None.
5432  */
5433 
5434 static struct ata_queued_cmd *ata_qc_new(struct ata_port *ap)
5435 {
5436 	struct ata_queued_cmd *qc = NULL;
5437 	unsigned int i;
5438 
5439 	/* no command while frozen */
5440 	if (unlikely(ap->pflags & ATA_PFLAG_FROZEN))
5441 		return NULL;
5442 
5443 	/* the last tag is reserved for internal command. */
5444 	for (i = 0; i < ATA_MAX_QUEUE - 1; i++)
5445 		if (!test_and_set_bit(i, &ap->qc_allocated)) {
5446 			qc = __ata_qc_from_tag(ap, i);
5447 			break;
5448 		}
5449 
5450 	if (qc)
5451 		qc->tag = i;
5452 
5453 	return qc;
5454 }
5455 
5456 /**
5457  *	ata_qc_new_init - Request an available ATA command, and initialize it
5458  *	@dev: Device from whom we request an available command structure
5459  *
5460  *	LOCKING:
5461  *	None.
5462  */
5463 
5464 struct ata_queued_cmd *ata_qc_new_init(struct ata_device *dev)
5465 {
5466 	struct ata_port *ap = dev->link->ap;
5467 	struct ata_queued_cmd *qc;
5468 
5469 	qc = ata_qc_new(ap);
5470 	if (qc) {
5471 		qc->scsicmd = NULL;
5472 		qc->ap = ap;
5473 		qc->dev = dev;
5474 
5475 		ata_qc_reinit(qc);
5476 	}
5477 
5478 	return qc;
5479 }
5480 
5481 /**
5482  *	ata_qc_free - free unused ata_queued_cmd
5483  *	@qc: Command to complete
5484  *
5485  *	Designed to free unused ata_queued_cmd object
5486  *	in case something prevents using it.
5487  *
5488  *	LOCKING:
5489  *	spin_lock_irqsave(host lock)
5490  */
5491 void ata_qc_free(struct ata_queued_cmd *qc)
5492 {
5493 	struct ata_port *ap = qc->ap;
5494 	unsigned int tag;
5495 
5496 	WARN_ON(qc == NULL);	/* ata_qc_from_tag _might_ return NULL */
5497 
5498 	qc->flags = 0;
5499 	tag = qc->tag;
5500 	if (likely(ata_tag_valid(tag))) {
5501 		qc->tag = ATA_TAG_POISON;
5502 		clear_bit(tag, &ap->qc_allocated);
5503 	}
5504 }
5505 
5506 void __ata_qc_complete(struct ata_queued_cmd *qc)
5507 {
5508 	struct ata_port *ap = qc->ap;
5509 	struct ata_link *link = qc->dev->link;
5510 
5511 	WARN_ON(qc == NULL);	/* ata_qc_from_tag _might_ return NULL */
5512 	WARN_ON(!(qc->flags & ATA_QCFLAG_ACTIVE));
5513 
5514 	if (likely(qc->flags & ATA_QCFLAG_DMAMAP))
5515 		ata_sg_clean(qc);
5516 
5517 	/* command should be marked inactive atomically with qc completion */
5518 	if (qc->tf.protocol == ATA_PROT_NCQ) {
5519 		link->sactive &= ~(1 << qc->tag);
5520 		if (!link->sactive)
5521 			ap->nr_active_links--;
5522 	} else {
5523 		link->active_tag = ATA_TAG_POISON;
5524 		ap->nr_active_links--;
5525 	}
5526 
5527 	/* clear exclusive status */
5528 	if (unlikely(qc->flags & ATA_QCFLAG_CLEAR_EXCL &&
5529 		     ap->excl_link == link))
5530 		ap->excl_link = NULL;
5531 
5532 	/* atapi: mark qc as inactive to prevent the interrupt handler
5533 	 * from completing the command twice later, before the error handler
5534 	 * is called. (when rc != 0 and atapi request sense is needed)
5535 	 */
5536 	qc->flags &= ~ATA_QCFLAG_ACTIVE;
5537 	ap->qc_active &= ~(1 << qc->tag);
5538 
5539 	/* call completion callback */
5540 	qc->complete_fn(qc);
5541 }
5542 
5543 static void fill_result_tf(struct ata_queued_cmd *qc)
5544 {
5545 	struct ata_port *ap = qc->ap;
5546 
5547 	qc->result_tf.flags = qc->tf.flags;
5548 	ap->ops->tf_read(ap, &qc->result_tf);
5549 }
5550 
5551 /**
5552  *	ata_qc_complete - Complete an active ATA command
5553  *	@qc: Command to complete
5554  *	@err_mask: ATA Status register contents
5555  *
5556  *	Indicate to the mid and upper layers that an ATA
5557  *	command has completed, with either an ok or not-ok status.
5558  *
5559  *	LOCKING:
5560  *	spin_lock_irqsave(host lock)
5561  */
5562 void ata_qc_complete(struct ata_queued_cmd *qc)
5563 {
5564 	struct ata_port *ap = qc->ap;
5565 
5566 	/* XXX: New EH and old EH use different mechanisms to
5567 	 * synchronize EH with regular execution path.
5568 	 *
5569 	 * In new EH, a failed qc is marked with ATA_QCFLAG_FAILED.
5570 	 * Normal execution path is responsible for not accessing a
5571 	 * failed qc.  libata core enforces the rule by returning NULL
5572 	 * from ata_qc_from_tag() for failed qcs.
5573 	 *
5574 	 * Old EH depends on ata_qc_complete() nullifying completion
5575 	 * requests if ATA_QCFLAG_EH_SCHEDULED is set.  Old EH does
5576 	 * not synchronize with interrupt handler.  Only PIO task is
5577 	 * taken care of.
5578 	 */
5579 	if (ap->ops->error_handler) {
5580 		WARN_ON(ap->pflags & ATA_PFLAG_FROZEN);
5581 
5582 		if (unlikely(qc->err_mask))
5583 			qc->flags |= ATA_QCFLAG_FAILED;
5584 
5585 		if (unlikely(qc->flags & ATA_QCFLAG_FAILED)) {
5586 			if (!ata_tag_internal(qc->tag)) {
5587 				/* always fill result TF for failed qc */
5588 				fill_result_tf(qc);
5589 				ata_qc_schedule_eh(qc);
5590 				return;
5591 			}
5592 		}
5593 
5594 		/* read result TF if requested */
5595 		if (qc->flags & ATA_QCFLAG_RESULT_TF)
5596 			fill_result_tf(qc);
5597 
5598 		__ata_qc_complete(qc);
5599 	} else {
5600 		if (qc->flags & ATA_QCFLAG_EH_SCHEDULED)
5601 			return;
5602 
5603 		/* read result TF if failed or requested */
5604 		if (qc->err_mask || qc->flags & ATA_QCFLAG_RESULT_TF)
5605 			fill_result_tf(qc);
5606 
5607 		__ata_qc_complete(qc);
5608 	}
5609 }
5610 
5611 /**
5612  *	ata_qc_complete_multiple - Complete multiple qcs successfully
5613  *	@ap: port in question
5614  *	@qc_active: new qc_active mask
5615  *	@finish_qc: LLDD callback invoked before completing a qc
5616  *
5617  *	Complete in-flight commands.  This functions is meant to be
5618  *	called from low-level driver's interrupt routine to complete
5619  *	requests normally.  ap->qc_active and @qc_active is compared
5620  *	and commands are completed accordingly.
5621  *
5622  *	LOCKING:
5623  *	spin_lock_irqsave(host lock)
5624  *
5625  *	RETURNS:
5626  *	Number of completed commands on success, -errno otherwise.
5627  */
5628 int ata_qc_complete_multiple(struct ata_port *ap, u32 qc_active,
5629 			     void (*finish_qc)(struct ata_queued_cmd *))
5630 {
5631 	int nr_done = 0;
5632 	u32 done_mask;
5633 	int i;
5634 
5635 	done_mask = ap->qc_active ^ qc_active;
5636 
5637 	if (unlikely(done_mask & qc_active)) {
5638 		ata_port_printk(ap, KERN_ERR, "illegal qc_active transition "
5639 				"(%08x->%08x)\n", ap->qc_active, qc_active);
5640 		return -EINVAL;
5641 	}
5642 
5643 	for (i = 0; i < ATA_MAX_QUEUE; i++) {
5644 		struct ata_queued_cmd *qc;
5645 
5646 		if (!(done_mask & (1 << i)))
5647 			continue;
5648 
5649 		if ((qc = ata_qc_from_tag(ap, i))) {
5650 			if (finish_qc)
5651 				finish_qc(qc);
5652 			ata_qc_complete(qc);
5653 			nr_done++;
5654 		}
5655 	}
5656 
5657 	return nr_done;
5658 }
5659 
5660 static inline int ata_should_dma_map(struct ata_queued_cmd *qc)
5661 {
5662 	struct ata_port *ap = qc->ap;
5663 
5664 	switch (qc->tf.protocol) {
5665 	case ATA_PROT_NCQ:
5666 	case ATA_PROT_DMA:
5667 	case ATA_PROT_ATAPI_DMA:
5668 		return 1;
5669 
5670 	case ATA_PROT_ATAPI:
5671 	case ATA_PROT_PIO:
5672 		if (ap->flags & ATA_FLAG_PIO_DMA)
5673 			return 1;
5674 
5675 		/* fall through */
5676 
5677 	default:
5678 		return 0;
5679 	}
5680 
5681 	/* never reached */
5682 }
5683 
5684 /**
5685  *	ata_qc_issue - issue taskfile to device
5686  *	@qc: command to issue to device
5687  *
5688  *	Prepare an ATA command to submission to device.
5689  *	This includes mapping the data into a DMA-able
5690  *	area, filling in the S/G table, and finally
5691  *	writing the taskfile to hardware, starting the command.
5692  *
5693  *	LOCKING:
5694  *	spin_lock_irqsave(host lock)
5695  */
5696 void ata_qc_issue(struct ata_queued_cmd *qc)
5697 {
5698 	struct ata_port *ap = qc->ap;
5699 	struct ata_link *link = qc->dev->link;
5700 
5701 	/* Make sure only one non-NCQ command is outstanding.  The
5702 	 * check is skipped for old EH because it reuses active qc to
5703 	 * request ATAPI sense.
5704 	 */
5705 	WARN_ON(ap->ops->error_handler && ata_tag_valid(link->active_tag));
5706 
5707 	if (qc->tf.protocol == ATA_PROT_NCQ) {
5708 		WARN_ON(link->sactive & (1 << qc->tag));
5709 
5710 		if (!link->sactive)
5711 			ap->nr_active_links++;
5712 		link->sactive |= 1 << qc->tag;
5713 	} else {
5714 		WARN_ON(link->sactive);
5715 
5716 		ap->nr_active_links++;
5717 		link->active_tag = qc->tag;
5718 	}
5719 
5720 	qc->flags |= ATA_QCFLAG_ACTIVE;
5721 	ap->qc_active |= 1 << qc->tag;
5722 
5723 	if (ata_should_dma_map(qc)) {
5724 		if (qc->flags & ATA_QCFLAG_SG) {
5725 			if (ata_sg_setup(qc))
5726 				goto sg_err;
5727 		} else if (qc->flags & ATA_QCFLAG_SINGLE) {
5728 			if (ata_sg_setup_one(qc))
5729 				goto sg_err;
5730 		}
5731 	} else {
5732 		qc->flags &= ~ATA_QCFLAG_DMAMAP;
5733 	}
5734 
5735 	ap->ops->qc_prep(qc);
5736 
5737 	qc->err_mask |= ap->ops->qc_issue(qc);
5738 	if (unlikely(qc->err_mask))
5739 		goto err;
5740 	return;
5741 
5742 sg_err:
5743 	qc->flags &= ~ATA_QCFLAG_DMAMAP;
5744 	qc->err_mask |= AC_ERR_SYSTEM;
5745 err:
5746 	ata_qc_complete(qc);
5747 }
5748 
5749 /**
5750  *	ata_qc_issue_prot - issue taskfile to device in proto-dependent manner
5751  *	@qc: command to issue to device
5752  *
5753  *	Using various libata functions and hooks, this function
5754  *	starts an ATA command.  ATA commands are grouped into
5755  *	classes called "protocols", and issuing each type of protocol
5756  *	is slightly different.
5757  *
5758  *	May be used as the qc_issue() entry in ata_port_operations.
5759  *
5760  *	LOCKING:
5761  *	spin_lock_irqsave(host lock)
5762  *
5763  *	RETURNS:
5764  *	Zero on success, AC_ERR_* mask on failure
5765  */
5766 
5767 unsigned int ata_qc_issue_prot(struct ata_queued_cmd *qc)
5768 {
5769 	struct ata_port *ap = qc->ap;
5770 
5771 	/* Use polling pio if the LLD doesn't handle
5772 	 * interrupt driven pio and atapi CDB interrupt.
5773 	 */
5774 	if (ap->flags & ATA_FLAG_PIO_POLLING) {
5775 		switch (qc->tf.protocol) {
5776 		case ATA_PROT_PIO:
5777 		case ATA_PROT_NODATA:
5778 		case ATA_PROT_ATAPI:
5779 		case ATA_PROT_ATAPI_NODATA:
5780 			qc->tf.flags |= ATA_TFLAG_POLLING;
5781 			break;
5782 		case ATA_PROT_ATAPI_DMA:
5783 			if (qc->dev->flags & ATA_DFLAG_CDB_INTR)
5784 				/* see ata_dma_blacklisted() */
5785 				BUG();
5786 			break;
5787 		default:
5788 			break;
5789 		}
5790 	}
5791 
5792 	/* select the device */
5793 	ata_dev_select(ap, qc->dev->devno, 1, 0);
5794 
5795 	/* start the command */
5796 	switch (qc->tf.protocol) {
5797 	case ATA_PROT_NODATA:
5798 		if (qc->tf.flags & ATA_TFLAG_POLLING)
5799 			ata_qc_set_polling(qc);
5800 
5801 		ata_tf_to_host(ap, &qc->tf);
5802 		ap->hsm_task_state = HSM_ST_LAST;
5803 
5804 		if (qc->tf.flags & ATA_TFLAG_POLLING)
5805 			ata_port_queue_task(ap, ata_pio_task, qc, 0);
5806 
5807 		break;
5808 
5809 	case ATA_PROT_DMA:
5810 		WARN_ON(qc->tf.flags & ATA_TFLAG_POLLING);
5811 
5812 		ap->ops->tf_load(ap, &qc->tf);	 /* load tf registers */
5813 		ap->ops->bmdma_setup(qc);	    /* set up bmdma */
5814 		ap->ops->bmdma_start(qc);	    /* initiate bmdma */
5815 		ap->hsm_task_state = HSM_ST_LAST;
5816 		break;
5817 
5818 	case ATA_PROT_PIO:
5819 		if (qc->tf.flags & ATA_TFLAG_POLLING)
5820 			ata_qc_set_polling(qc);
5821 
5822 		ata_tf_to_host(ap, &qc->tf);
5823 
5824 		if (qc->tf.flags & ATA_TFLAG_WRITE) {
5825 			/* PIO data out protocol */
5826 			ap->hsm_task_state = HSM_ST_FIRST;
5827 			ata_port_queue_task(ap, ata_pio_task, qc, 0);
5828 
5829 			/* always send first data block using
5830 			 * the ata_pio_task() codepath.
5831 			 */
5832 		} else {
5833 			/* PIO data in protocol */
5834 			ap->hsm_task_state = HSM_ST;
5835 
5836 			if (qc->tf.flags & ATA_TFLAG_POLLING)
5837 				ata_port_queue_task(ap, ata_pio_task, qc, 0);
5838 
5839 			/* if polling, ata_pio_task() handles the rest.
5840 			 * otherwise, interrupt handler takes over from here.
5841 			 */
5842 		}
5843 
5844 		break;
5845 
5846 	case ATA_PROT_ATAPI:
5847 	case ATA_PROT_ATAPI_NODATA:
5848 		if (qc->tf.flags & ATA_TFLAG_POLLING)
5849 			ata_qc_set_polling(qc);
5850 
5851 		ata_tf_to_host(ap, &qc->tf);
5852 
5853 		ap->hsm_task_state = HSM_ST_FIRST;
5854 
5855 		/* send cdb by polling if no cdb interrupt */
5856 		if ((!(qc->dev->flags & ATA_DFLAG_CDB_INTR)) ||
5857 		    (qc->tf.flags & ATA_TFLAG_POLLING))
5858 			ata_port_queue_task(ap, ata_pio_task, qc, 0);
5859 		break;
5860 
5861 	case ATA_PROT_ATAPI_DMA:
5862 		WARN_ON(qc->tf.flags & ATA_TFLAG_POLLING);
5863 
5864 		ap->ops->tf_load(ap, &qc->tf);	 /* load tf registers */
5865 		ap->ops->bmdma_setup(qc);	    /* set up bmdma */
5866 		ap->hsm_task_state = HSM_ST_FIRST;
5867 
5868 		/* send cdb by polling if no cdb interrupt */
5869 		if (!(qc->dev->flags & ATA_DFLAG_CDB_INTR))
5870 			ata_port_queue_task(ap, ata_pio_task, qc, 0);
5871 		break;
5872 
5873 	default:
5874 		WARN_ON(1);
5875 		return AC_ERR_SYSTEM;
5876 	}
5877 
5878 	return 0;
5879 }
5880 
5881 /**
5882  *	ata_host_intr - Handle host interrupt for given (port, task)
5883  *	@ap: Port on which interrupt arrived (possibly...)
5884  *	@qc: Taskfile currently active in engine
5885  *
5886  *	Handle host interrupt for given queued command.  Currently,
5887  *	only DMA interrupts are handled.  All other commands are
5888  *	handled via polling with interrupts disabled (nIEN bit).
5889  *
5890  *	LOCKING:
5891  *	spin_lock_irqsave(host lock)
5892  *
5893  *	RETURNS:
5894  *	One if interrupt was handled, zero if not (shared irq).
5895  */
5896 
5897 inline unsigned int ata_host_intr (struct ata_port *ap,
5898 				   struct ata_queued_cmd *qc)
5899 {
5900 	struct ata_eh_info *ehi = &ap->link.eh_info;
5901 	u8 status, host_stat = 0;
5902 
5903 	VPRINTK("ata%u: protocol %d task_state %d\n",
5904 		ap->print_id, qc->tf.protocol, ap->hsm_task_state);
5905 
5906 	/* Check whether we are expecting interrupt in this state */
5907 	switch (ap->hsm_task_state) {
5908 	case HSM_ST_FIRST:
5909 		/* Some pre-ATAPI-4 devices assert INTRQ
5910 		 * at this state when ready to receive CDB.
5911 		 */
5912 
5913 		/* Check the ATA_DFLAG_CDB_INTR flag is enough here.
5914 		 * The flag was turned on only for atapi devices.
5915 		 * No need to check is_atapi_taskfile(&qc->tf) again.
5916 		 */
5917 		if (!(qc->dev->flags & ATA_DFLAG_CDB_INTR))
5918 			goto idle_irq;
5919 		break;
5920 	case HSM_ST_LAST:
5921 		if (qc->tf.protocol == ATA_PROT_DMA ||
5922 		    qc->tf.protocol == ATA_PROT_ATAPI_DMA) {
5923 			/* check status of DMA engine */
5924 			host_stat = ap->ops->bmdma_status(ap);
5925 			VPRINTK("ata%u: host_stat 0x%X\n",
5926 				ap->print_id, host_stat);
5927 
5928 			/* if it's not our irq... */
5929 			if (!(host_stat & ATA_DMA_INTR))
5930 				goto idle_irq;
5931 
5932 			/* before we do anything else, clear DMA-Start bit */
5933 			ap->ops->bmdma_stop(qc);
5934 
5935 			if (unlikely(host_stat & ATA_DMA_ERR)) {
5936 				/* error when transfering data to/from memory */
5937 				qc->err_mask |= AC_ERR_HOST_BUS;
5938 				ap->hsm_task_state = HSM_ST_ERR;
5939 			}
5940 		}
5941 		break;
5942 	case HSM_ST:
5943 		break;
5944 	default:
5945 		goto idle_irq;
5946 	}
5947 
5948 	/* check altstatus */
5949 	status = ata_altstatus(ap);
5950 	if (status & ATA_BUSY)
5951 		goto idle_irq;
5952 
5953 	/* check main status, clearing INTRQ */
5954 	status = ata_chk_status(ap);
5955 	if (unlikely(status & ATA_BUSY))
5956 		goto idle_irq;
5957 
5958 	/* ack bmdma irq events */
5959 	ap->ops->irq_clear(ap);
5960 
5961 	ata_hsm_move(ap, qc, status, 0);
5962 
5963 	if (unlikely(qc->err_mask) && (qc->tf.protocol == ATA_PROT_DMA ||
5964 				       qc->tf.protocol == ATA_PROT_ATAPI_DMA))
5965 		ata_ehi_push_desc(ehi, "BMDMA stat 0x%x", host_stat);
5966 
5967 	return 1;	/* irq handled */
5968 
5969 idle_irq:
5970 	ap->stats.idle_irq++;
5971 
5972 #ifdef ATA_IRQ_TRAP
5973 	if ((ap->stats.idle_irq % 1000) == 0) {
5974 		ata_chk_status(ap);
5975 		ap->ops->irq_clear(ap);
5976 		ata_port_printk(ap, KERN_WARNING, "irq trap\n");
5977 		return 1;
5978 	}
5979 #endif
5980 	return 0;	/* irq not handled */
5981 }
5982 
5983 /**
5984  *	ata_interrupt - Default ATA host interrupt handler
5985  *	@irq: irq line (unused)
5986  *	@dev_instance: pointer to our ata_host information structure
5987  *
5988  *	Default interrupt handler for PCI IDE devices.  Calls
5989  *	ata_host_intr() for each port that is not disabled.
5990  *
5991  *	LOCKING:
5992  *	Obtains host lock during operation.
5993  *
5994  *	RETURNS:
5995  *	IRQ_NONE or IRQ_HANDLED.
5996  */
5997 
5998 irqreturn_t ata_interrupt (int irq, void *dev_instance)
5999 {
6000 	struct ata_host *host = dev_instance;
6001 	unsigned int i;
6002 	unsigned int handled = 0;
6003 	unsigned long flags;
6004 
6005 	/* TODO: make _irqsave conditional on x86 PCI IDE legacy mode */
6006 	spin_lock_irqsave(&host->lock, flags);
6007 
6008 	for (i = 0; i < host->n_ports; i++) {
6009 		struct ata_port *ap;
6010 
6011 		ap = host->ports[i];
6012 		if (ap &&
6013 		    !(ap->flags & ATA_FLAG_DISABLED)) {
6014 			struct ata_queued_cmd *qc;
6015 
6016 			qc = ata_qc_from_tag(ap, ap->link.active_tag);
6017 			if (qc && (!(qc->tf.flags & ATA_TFLAG_POLLING)) &&
6018 			    (qc->flags & ATA_QCFLAG_ACTIVE))
6019 				handled |= ata_host_intr(ap, qc);
6020 		}
6021 	}
6022 
6023 	spin_unlock_irqrestore(&host->lock, flags);
6024 
6025 	return IRQ_RETVAL(handled);
6026 }
6027 
6028 /**
6029  *	sata_scr_valid - test whether SCRs are accessible
6030  *	@link: ATA link to test SCR accessibility for
6031  *
6032  *	Test whether SCRs are accessible for @link.
6033  *
6034  *	LOCKING:
6035  *	None.
6036  *
6037  *	RETURNS:
6038  *	1 if SCRs are accessible, 0 otherwise.
6039  */
6040 int sata_scr_valid(struct ata_link *link)
6041 {
6042 	struct ata_port *ap = link->ap;
6043 
6044 	return (ap->flags & ATA_FLAG_SATA) && ap->ops->scr_read;
6045 }
6046 
6047 /**
6048  *	sata_scr_read - read SCR register of the specified port
6049  *	@link: ATA link to read SCR for
6050  *	@reg: SCR to read
6051  *	@val: Place to store read value
6052  *
6053  *	Read SCR register @reg of @link into *@val.  This function is
6054  *	guaranteed to succeed if @link is ap->link, the cable type of
6055  *	the port is SATA and the port implements ->scr_read.
6056  *
6057  *	LOCKING:
6058  *	None if @link is ap->link.  Kernel thread context otherwise.
6059  *
6060  *	RETURNS:
6061  *	0 on success, negative errno on failure.
6062  */
6063 int sata_scr_read(struct ata_link *link, int reg, u32 *val)
6064 {
6065 	if (ata_is_host_link(link)) {
6066 		struct ata_port *ap = link->ap;
6067 
6068 		if (sata_scr_valid(link))
6069 			return ap->ops->scr_read(ap, reg, val);
6070 		return -EOPNOTSUPP;
6071 	}
6072 
6073 	return sata_pmp_scr_read(link, reg, val);
6074 }
6075 
6076 /**
6077  *	sata_scr_write - write SCR register of the specified port
6078  *	@link: ATA link to write SCR for
6079  *	@reg: SCR to write
6080  *	@val: value to write
6081  *
6082  *	Write @val to SCR register @reg of @link.  This function is
6083  *	guaranteed to succeed if @link is ap->link, the cable type of
6084  *	the port is SATA and the port implements ->scr_read.
6085  *
6086  *	LOCKING:
6087  *	None if @link is ap->link.  Kernel thread context otherwise.
6088  *
6089  *	RETURNS:
6090  *	0 on success, negative errno on failure.
6091  */
6092 int sata_scr_write(struct ata_link *link, int reg, u32 val)
6093 {
6094 	if (ata_is_host_link(link)) {
6095 		struct ata_port *ap = link->ap;
6096 
6097 		if (sata_scr_valid(link))
6098 			return ap->ops->scr_write(ap, reg, val);
6099 		return -EOPNOTSUPP;
6100 	}
6101 
6102 	return sata_pmp_scr_write(link, reg, val);
6103 }
6104 
6105 /**
6106  *	sata_scr_write_flush - write SCR register of the specified port and flush
6107  *	@link: ATA link to write SCR for
6108  *	@reg: SCR to write
6109  *	@val: value to write
6110  *
6111  *	This function is identical to sata_scr_write() except that this
6112  *	function performs flush after writing to the register.
6113  *
6114  *	LOCKING:
6115  *	None if @link is ap->link.  Kernel thread context otherwise.
6116  *
6117  *	RETURNS:
6118  *	0 on success, negative errno on failure.
6119  */
6120 int sata_scr_write_flush(struct ata_link *link, int reg, u32 val)
6121 {
6122 	if (ata_is_host_link(link)) {
6123 		struct ata_port *ap = link->ap;
6124 		int rc;
6125 
6126 		if (sata_scr_valid(link)) {
6127 			rc = ap->ops->scr_write(ap, reg, val);
6128 			if (rc == 0)
6129 				rc = ap->ops->scr_read(ap, reg, &val);
6130 			return rc;
6131 		}
6132 		return -EOPNOTSUPP;
6133 	}
6134 
6135 	return sata_pmp_scr_write(link, reg, val);
6136 }
6137 
6138 /**
6139  *	ata_link_online - test whether the given link is online
6140  *	@link: ATA link to test
6141  *
6142  *	Test whether @link is online.  Note that this function returns
6143  *	0 if online status of @link cannot be obtained, so
6144  *	ata_link_online(link) != !ata_link_offline(link).
6145  *
6146  *	LOCKING:
6147  *	None.
6148  *
6149  *	RETURNS:
6150  *	1 if the port online status is available and online.
6151  */
6152 int ata_link_online(struct ata_link *link)
6153 {
6154 	u32 sstatus;
6155 
6156 	if (sata_scr_read(link, SCR_STATUS, &sstatus) == 0 &&
6157 	    (sstatus & 0xf) == 0x3)
6158 		return 1;
6159 	return 0;
6160 }
6161 
6162 /**
6163  *	ata_link_offline - test whether the given link is offline
6164  *	@link: ATA link to test
6165  *
6166  *	Test whether @link is offline.  Note that this function
6167  *	returns 0 if offline status of @link cannot be obtained, so
6168  *	ata_link_online(link) != !ata_link_offline(link).
6169  *
6170  *	LOCKING:
6171  *	None.
6172  *
6173  *	RETURNS:
6174  *	1 if the port offline status is available and offline.
6175  */
6176 int ata_link_offline(struct ata_link *link)
6177 {
6178 	u32 sstatus;
6179 
6180 	if (sata_scr_read(link, SCR_STATUS, &sstatus) == 0 &&
6181 	    (sstatus & 0xf) != 0x3)
6182 		return 1;
6183 	return 0;
6184 }
6185 
6186 int ata_flush_cache(struct ata_device *dev)
6187 {
6188 	unsigned int err_mask;
6189 	u8 cmd;
6190 
6191 	if (!ata_try_flush_cache(dev))
6192 		return 0;
6193 
6194 	if (dev->flags & ATA_DFLAG_FLUSH_EXT)
6195 		cmd = ATA_CMD_FLUSH_EXT;
6196 	else
6197 		cmd = ATA_CMD_FLUSH;
6198 
6199 	/* This is wrong. On a failed flush we get back the LBA of the lost
6200 	   sector and we should (assuming it wasn't aborted as unknown) issue
6201 	   a further flush command to continue the writeback until it
6202 	   does not error */
6203 	err_mask = ata_do_simple_cmd(dev, cmd);
6204 	if (err_mask) {
6205 		ata_dev_printk(dev, KERN_ERR, "failed to flush cache\n");
6206 		return -EIO;
6207 	}
6208 
6209 	return 0;
6210 }
6211 
6212 #ifdef CONFIG_PM
6213 static int ata_host_request_pm(struct ata_host *host, pm_message_t mesg,
6214 			       unsigned int action, unsigned int ehi_flags,
6215 			       int wait)
6216 {
6217 	unsigned long flags;
6218 	int i, rc;
6219 
6220 	for (i = 0; i < host->n_ports; i++) {
6221 		struct ata_port *ap = host->ports[i];
6222 		struct ata_link *link;
6223 
6224 		/* Previous resume operation might still be in
6225 		 * progress.  Wait for PM_PENDING to clear.
6226 		 */
6227 		if (ap->pflags & ATA_PFLAG_PM_PENDING) {
6228 			ata_port_wait_eh(ap);
6229 			WARN_ON(ap->pflags & ATA_PFLAG_PM_PENDING);
6230 		}
6231 
6232 		/* request PM ops to EH */
6233 		spin_lock_irqsave(ap->lock, flags);
6234 
6235 		ap->pm_mesg = mesg;
6236 		if (wait) {
6237 			rc = 0;
6238 			ap->pm_result = &rc;
6239 		}
6240 
6241 		ap->pflags |= ATA_PFLAG_PM_PENDING;
6242 		__ata_port_for_each_link(link, ap) {
6243 			link->eh_info.action |= action;
6244 			link->eh_info.flags |= ehi_flags;
6245 		}
6246 
6247 		ata_port_schedule_eh(ap);
6248 
6249 		spin_unlock_irqrestore(ap->lock, flags);
6250 
6251 		/* wait and check result */
6252 		if (wait) {
6253 			ata_port_wait_eh(ap);
6254 			WARN_ON(ap->pflags & ATA_PFLAG_PM_PENDING);
6255 			if (rc)
6256 				return rc;
6257 		}
6258 	}
6259 
6260 	return 0;
6261 }
6262 
6263 /**
6264  *	ata_host_suspend - suspend host
6265  *	@host: host to suspend
6266  *	@mesg: PM message
6267  *
6268  *	Suspend @host.  Actual operation is performed by EH.  This
6269  *	function requests EH to perform PM operations and waits for EH
6270  *	to finish.
6271  *
6272  *	LOCKING:
6273  *	Kernel thread context (may sleep).
6274  *
6275  *	RETURNS:
6276  *	0 on success, -errno on failure.
6277  */
6278 int ata_host_suspend(struct ata_host *host, pm_message_t mesg)
6279 {
6280 	int rc;
6281 
6282 	rc = ata_host_request_pm(host, mesg, 0, ATA_EHI_QUIET, 1);
6283 	if (rc == 0)
6284 		host->dev->power.power_state = mesg;
6285 	return rc;
6286 }
6287 
6288 /**
6289  *	ata_host_resume - resume host
6290  *	@host: host to resume
6291  *
6292  *	Resume @host.  Actual operation is performed by EH.  This
6293  *	function requests EH to perform PM operations and returns.
6294  *	Note that all resume operations are performed parallely.
6295  *
6296  *	LOCKING:
6297  *	Kernel thread context (may sleep).
6298  */
6299 void ata_host_resume(struct ata_host *host)
6300 {
6301 	ata_host_request_pm(host, PMSG_ON, ATA_EH_SOFTRESET,
6302 			    ATA_EHI_NO_AUTOPSY | ATA_EHI_QUIET, 0);
6303 	host->dev->power.power_state = PMSG_ON;
6304 }
6305 #endif
6306 
6307 /**
6308  *	ata_port_start - Set port up for dma.
6309  *	@ap: Port to initialize
6310  *
6311  *	Called just after data structures for each port are
6312  *	initialized.  Allocates space for PRD table.
6313  *
6314  *	May be used as the port_start() entry in ata_port_operations.
6315  *
6316  *	LOCKING:
6317  *	Inherited from caller.
6318  */
6319 int ata_port_start(struct ata_port *ap)
6320 {
6321 	struct device *dev = ap->dev;
6322 	int rc;
6323 
6324 	ap->prd = dmam_alloc_coherent(dev, ATA_PRD_TBL_SZ, &ap->prd_dma,
6325 				      GFP_KERNEL);
6326 	if (!ap->prd)
6327 		return -ENOMEM;
6328 
6329 	rc = ata_pad_alloc(ap, dev);
6330 	if (rc)
6331 		return rc;
6332 
6333 	DPRINTK("prd alloc, virt %p, dma %llx\n", ap->prd,
6334 		(unsigned long long)ap->prd_dma);
6335 	return 0;
6336 }
6337 
6338 /**
6339  *	ata_dev_init - Initialize an ata_device structure
6340  *	@dev: Device structure to initialize
6341  *
6342  *	Initialize @dev in preparation for probing.
6343  *
6344  *	LOCKING:
6345  *	Inherited from caller.
6346  */
6347 void ata_dev_init(struct ata_device *dev)
6348 {
6349 	struct ata_link *link = dev->link;
6350 	struct ata_port *ap = link->ap;
6351 	unsigned long flags;
6352 
6353 	/* SATA spd limit is bound to the first device */
6354 	link->sata_spd_limit = link->hw_sata_spd_limit;
6355 	link->sata_spd = 0;
6356 
6357 	/* High bits of dev->flags are used to record warm plug
6358 	 * requests which occur asynchronously.  Synchronize using
6359 	 * host lock.
6360 	 */
6361 	spin_lock_irqsave(ap->lock, flags);
6362 	dev->flags &= ~ATA_DFLAG_INIT_MASK;
6363 	dev->horkage = 0;
6364 	spin_unlock_irqrestore(ap->lock, flags);
6365 
6366 	memset((void *)dev + ATA_DEVICE_CLEAR_OFFSET, 0,
6367 	       sizeof(*dev) - ATA_DEVICE_CLEAR_OFFSET);
6368 	dev->pio_mask = UINT_MAX;
6369 	dev->mwdma_mask = UINT_MAX;
6370 	dev->udma_mask = UINT_MAX;
6371 }
6372 
6373 /**
6374  *	ata_link_init - Initialize an ata_link structure
6375  *	@ap: ATA port link is attached to
6376  *	@link: Link structure to initialize
6377  *	@pmp: Port multiplier port number
6378  *
6379  *	Initialize @link.
6380  *
6381  *	LOCKING:
6382  *	Kernel thread context (may sleep)
6383  */
6384 void ata_link_init(struct ata_port *ap, struct ata_link *link, int pmp)
6385 {
6386 	int i;
6387 
6388 	/* clear everything except for devices */
6389 	memset(link, 0, offsetof(struct ata_link, device[0]));
6390 
6391 	link->ap = ap;
6392 	link->pmp = pmp;
6393 	link->active_tag = ATA_TAG_POISON;
6394 	link->hw_sata_spd_limit = UINT_MAX;
6395 
6396 	/* can't use iterator, ap isn't initialized yet */
6397 	for (i = 0; i < ATA_MAX_DEVICES; i++) {
6398 		struct ata_device *dev = &link->device[i];
6399 
6400 		dev->link = link;
6401 		dev->devno = dev - link->device;
6402 		ata_dev_init(dev);
6403 	}
6404 }
6405 
6406 /**
6407  *	sata_link_init_spd - Initialize link->sata_spd_limit
6408  *	@link: Link to configure sata_spd_limit for
6409  *
6410  *	Initialize @link->[hw_]sata_spd_limit to the currently
6411  *	configured value.
6412  *
6413  *	LOCKING:
6414  *	Kernel thread context (may sleep).
6415  *
6416  *	RETURNS:
6417  *	0 on success, -errno on failure.
6418  */
6419 int sata_link_init_spd(struct ata_link *link)
6420 {
6421 	u32 scontrol, spd;
6422 	int rc;
6423 
6424 	rc = sata_scr_read(link, SCR_CONTROL, &scontrol);
6425 	if (rc)
6426 		return rc;
6427 
6428 	spd = (scontrol >> 4) & 0xf;
6429 	if (spd)
6430 		link->hw_sata_spd_limit &= (1 << spd) - 1;
6431 
6432 	link->sata_spd_limit = link->hw_sata_spd_limit;
6433 
6434 	return 0;
6435 }
6436 
6437 /**
6438  *	ata_port_alloc - allocate and initialize basic ATA port resources
6439  *	@host: ATA host this allocated port belongs to
6440  *
6441  *	Allocate and initialize basic ATA port resources.
6442  *
6443  *	RETURNS:
6444  *	Allocate ATA port on success, NULL on failure.
6445  *
6446  *	LOCKING:
6447  *	Inherited from calling layer (may sleep).
6448  */
6449 struct ata_port *ata_port_alloc(struct ata_host *host)
6450 {
6451 	struct ata_port *ap;
6452 
6453 	DPRINTK("ENTER\n");
6454 
6455 	ap = kzalloc(sizeof(*ap), GFP_KERNEL);
6456 	if (!ap)
6457 		return NULL;
6458 
6459 	ap->pflags |= ATA_PFLAG_INITIALIZING;
6460 	ap->lock = &host->lock;
6461 	ap->flags = ATA_FLAG_DISABLED;
6462 	ap->print_id = -1;
6463 	ap->ctl = ATA_DEVCTL_OBS;
6464 	ap->host = host;
6465 	ap->dev = host->dev;
6466 	ap->last_ctl = 0xFF;
6467 
6468 #if defined(ATA_VERBOSE_DEBUG)
6469 	/* turn on all debugging levels */
6470 	ap->msg_enable = 0x00FF;
6471 #elif defined(ATA_DEBUG)
6472 	ap->msg_enable = ATA_MSG_DRV | ATA_MSG_INFO | ATA_MSG_CTL | ATA_MSG_WARN | ATA_MSG_ERR;
6473 #else
6474 	ap->msg_enable = ATA_MSG_DRV | ATA_MSG_ERR | ATA_MSG_WARN;
6475 #endif
6476 
6477 	INIT_DELAYED_WORK(&ap->port_task, NULL);
6478 	INIT_DELAYED_WORK(&ap->hotplug_task, ata_scsi_hotplug);
6479 	INIT_WORK(&ap->scsi_rescan_task, ata_scsi_dev_rescan);
6480 	INIT_LIST_HEAD(&ap->eh_done_q);
6481 	init_waitqueue_head(&ap->eh_wait_q);
6482 	init_timer_deferrable(&ap->fastdrain_timer);
6483 	ap->fastdrain_timer.function = ata_eh_fastdrain_timerfn;
6484 	ap->fastdrain_timer.data = (unsigned long)ap;
6485 
6486 	ap->cbl = ATA_CBL_NONE;
6487 
6488 	ata_link_init(ap, &ap->link, 0);
6489 
6490 #ifdef ATA_IRQ_TRAP
6491 	ap->stats.unhandled_irq = 1;
6492 	ap->stats.idle_irq = 1;
6493 #endif
6494 	return ap;
6495 }
6496 
6497 static void ata_host_release(struct device *gendev, void *res)
6498 {
6499 	struct ata_host *host = dev_get_drvdata(gendev);
6500 	int i;
6501 
6502 	for (i = 0; i < host->n_ports; i++) {
6503 		struct ata_port *ap = host->ports[i];
6504 
6505 		if (!ap)
6506 			continue;
6507 
6508 		if ((host->flags & ATA_HOST_STARTED) && ap->ops->port_stop)
6509 			ap->ops->port_stop(ap);
6510 	}
6511 
6512 	if ((host->flags & ATA_HOST_STARTED) && host->ops->host_stop)
6513 		host->ops->host_stop(host);
6514 
6515 	for (i = 0; i < host->n_ports; i++) {
6516 		struct ata_port *ap = host->ports[i];
6517 
6518 		if (!ap)
6519 			continue;
6520 
6521 		if (ap->scsi_host)
6522 			scsi_host_put(ap->scsi_host);
6523 
6524 		kfree(ap->pmp_link);
6525 		kfree(ap);
6526 		host->ports[i] = NULL;
6527 	}
6528 
6529 	dev_set_drvdata(gendev, NULL);
6530 }
6531 
6532 /**
6533  *	ata_host_alloc - allocate and init basic ATA host resources
6534  *	@dev: generic device this host is associated with
6535  *	@max_ports: maximum number of ATA ports associated with this host
6536  *
6537  *	Allocate and initialize basic ATA host resources.  LLD calls
6538  *	this function to allocate a host, initializes it fully and
6539  *	attaches it using ata_host_register().
6540  *
6541  *	@max_ports ports are allocated and host->n_ports is
6542  *	initialized to @max_ports.  The caller is allowed to decrease
6543  *	host->n_ports before calling ata_host_register().  The unused
6544  *	ports will be automatically freed on registration.
6545  *
6546  *	RETURNS:
6547  *	Allocate ATA host on success, NULL on failure.
6548  *
6549  *	LOCKING:
6550  *	Inherited from calling layer (may sleep).
6551  */
6552 struct ata_host *ata_host_alloc(struct device *dev, int max_ports)
6553 {
6554 	struct ata_host *host;
6555 	size_t sz;
6556 	int i;
6557 
6558 	DPRINTK("ENTER\n");
6559 
6560 	if (!devres_open_group(dev, NULL, GFP_KERNEL))
6561 		return NULL;
6562 
6563 	/* alloc a container for our list of ATA ports (buses) */
6564 	sz = sizeof(struct ata_host) + (max_ports + 1) * sizeof(void *);
6565 	/* alloc a container for our list of ATA ports (buses) */
6566 	host = devres_alloc(ata_host_release, sz, GFP_KERNEL);
6567 	if (!host)
6568 		goto err_out;
6569 
6570 	devres_add(dev, host);
6571 	dev_set_drvdata(dev, host);
6572 
6573 	spin_lock_init(&host->lock);
6574 	host->dev = dev;
6575 	host->n_ports = max_ports;
6576 
6577 	/* allocate ports bound to this host */
6578 	for (i = 0; i < max_ports; i++) {
6579 		struct ata_port *ap;
6580 
6581 		ap = ata_port_alloc(host);
6582 		if (!ap)
6583 			goto err_out;
6584 
6585 		ap->port_no = i;
6586 		host->ports[i] = ap;
6587 	}
6588 
6589 	devres_remove_group(dev, NULL);
6590 	return host;
6591 
6592  err_out:
6593 	devres_release_group(dev, NULL);
6594 	return NULL;
6595 }
6596 
6597 /**
6598  *	ata_host_alloc_pinfo - alloc host and init with port_info array
6599  *	@dev: generic device this host is associated with
6600  *	@ppi: array of ATA port_info to initialize host with
6601  *	@n_ports: number of ATA ports attached to this host
6602  *
6603  *	Allocate ATA host and initialize with info from @ppi.  If NULL
6604  *	terminated, @ppi may contain fewer entries than @n_ports.  The
6605  *	last entry will be used for the remaining ports.
6606  *
6607  *	RETURNS:
6608  *	Allocate ATA host on success, NULL on failure.
6609  *
6610  *	LOCKING:
6611  *	Inherited from calling layer (may sleep).
6612  */
6613 struct ata_host *ata_host_alloc_pinfo(struct device *dev,
6614 				      const struct ata_port_info * const * ppi,
6615 				      int n_ports)
6616 {
6617 	const struct ata_port_info *pi;
6618 	struct ata_host *host;
6619 	int i, j;
6620 
6621 	host = ata_host_alloc(dev, n_ports);
6622 	if (!host)
6623 		return NULL;
6624 
6625 	for (i = 0, j = 0, pi = NULL; i < host->n_ports; i++) {
6626 		struct ata_port *ap = host->ports[i];
6627 
6628 		if (ppi[j])
6629 			pi = ppi[j++];
6630 
6631 		ap->pio_mask = pi->pio_mask;
6632 		ap->mwdma_mask = pi->mwdma_mask;
6633 		ap->udma_mask = pi->udma_mask;
6634 		ap->flags |= pi->flags;
6635 		ap->link.flags |= pi->link_flags;
6636 		ap->ops = pi->port_ops;
6637 
6638 		if (!host->ops && (pi->port_ops != &ata_dummy_port_ops))
6639 			host->ops = pi->port_ops;
6640 		if (!host->private_data && pi->private_data)
6641 			host->private_data = pi->private_data;
6642 	}
6643 
6644 	return host;
6645 }
6646 
6647 /**
6648  *	ata_host_start - start and freeze ports of an ATA host
6649  *	@host: ATA host to start ports for
6650  *
6651  *	Start and then freeze ports of @host.  Started status is
6652  *	recorded in host->flags, so this function can be called
6653  *	multiple times.  Ports are guaranteed to get started only
6654  *	once.  If host->ops isn't initialized yet, its set to the
6655  *	first non-dummy port ops.
6656  *
6657  *	LOCKING:
6658  *	Inherited from calling layer (may sleep).
6659  *
6660  *	RETURNS:
6661  *	0 if all ports are started successfully, -errno otherwise.
6662  */
6663 int ata_host_start(struct ata_host *host)
6664 {
6665 	int i, rc;
6666 
6667 	if (host->flags & ATA_HOST_STARTED)
6668 		return 0;
6669 
6670 	for (i = 0; i < host->n_ports; i++) {
6671 		struct ata_port *ap = host->ports[i];
6672 
6673 		if (!host->ops && !ata_port_is_dummy(ap))
6674 			host->ops = ap->ops;
6675 
6676 		if (ap->ops->port_start) {
6677 			rc = ap->ops->port_start(ap);
6678 			if (rc) {
6679 				ata_port_printk(ap, KERN_ERR, "failed to "
6680 						"start port (errno=%d)\n", rc);
6681 				goto err_out;
6682 			}
6683 		}
6684 
6685 		ata_eh_freeze_port(ap);
6686 	}
6687 
6688 	host->flags |= ATA_HOST_STARTED;
6689 	return 0;
6690 
6691  err_out:
6692 	while (--i >= 0) {
6693 		struct ata_port *ap = host->ports[i];
6694 
6695 		if (ap->ops->port_stop)
6696 			ap->ops->port_stop(ap);
6697 	}
6698 	return rc;
6699 }
6700 
6701 /**
6702  *	ata_sas_host_init - Initialize a host struct
6703  *	@host:	host to initialize
6704  *	@dev:	device host is attached to
6705  *	@flags:	host flags
6706  *	@ops:	port_ops
6707  *
6708  *	LOCKING:
6709  *	PCI/etc. bus probe sem.
6710  *
6711  */
6712 /* KILLME - the only user left is ipr */
6713 void ata_host_init(struct ata_host *host, struct device *dev,
6714 		   unsigned long flags, const struct ata_port_operations *ops)
6715 {
6716 	spin_lock_init(&host->lock);
6717 	host->dev = dev;
6718 	host->flags = flags;
6719 	host->ops = ops;
6720 }
6721 
6722 /**
6723  *	ata_host_register - register initialized ATA host
6724  *	@host: ATA host to register
6725  *	@sht: template for SCSI host
6726  *
6727  *	Register initialized ATA host.  @host is allocated using
6728  *	ata_host_alloc() and fully initialized by LLD.  This function
6729  *	starts ports, registers @host with ATA and SCSI layers and
6730  *	probe registered devices.
6731  *
6732  *	LOCKING:
6733  *	Inherited from calling layer (may sleep).
6734  *
6735  *	RETURNS:
6736  *	0 on success, -errno otherwise.
6737  */
6738 int ata_host_register(struct ata_host *host, struct scsi_host_template *sht)
6739 {
6740 	int i, rc;
6741 
6742 	/* host must have been started */
6743 	if (!(host->flags & ATA_HOST_STARTED)) {
6744 		dev_printk(KERN_ERR, host->dev,
6745 			   "BUG: trying to register unstarted host\n");
6746 		WARN_ON(1);
6747 		return -EINVAL;
6748 	}
6749 
6750 	/* Blow away unused ports.  This happens when LLD can't
6751 	 * determine the exact number of ports to allocate at
6752 	 * allocation time.
6753 	 */
6754 	for (i = host->n_ports; host->ports[i]; i++)
6755 		kfree(host->ports[i]);
6756 
6757 	/* give ports names and add SCSI hosts */
6758 	for (i = 0; i < host->n_ports; i++)
6759 		host->ports[i]->print_id = ata_print_id++;
6760 
6761 	rc = ata_scsi_add_hosts(host, sht);
6762 	if (rc)
6763 		return rc;
6764 
6765 	/* associate with ACPI nodes */
6766 	ata_acpi_associate(host);
6767 
6768 	/* set cable, sata_spd_limit and report */
6769 	for (i = 0; i < host->n_ports; i++) {
6770 		struct ata_port *ap = host->ports[i];
6771 		unsigned long xfer_mask;
6772 
6773 		/* set SATA cable type if still unset */
6774 		if (ap->cbl == ATA_CBL_NONE && (ap->flags & ATA_FLAG_SATA))
6775 			ap->cbl = ATA_CBL_SATA;
6776 
6777 		/* init sata_spd_limit to the current value */
6778 		sata_link_init_spd(&ap->link);
6779 
6780 		/* print per-port info to dmesg */
6781 		xfer_mask = ata_pack_xfermask(ap->pio_mask, ap->mwdma_mask,
6782 					      ap->udma_mask);
6783 
6784 		if (!ata_port_is_dummy(ap)) {
6785 			ata_port_printk(ap, KERN_INFO,
6786 					"%cATA max %s %s\n",
6787 					(ap->flags & ATA_FLAG_SATA) ? 'S' : 'P',
6788 					ata_mode_string(xfer_mask),
6789 					ap->link.eh_info.desc);
6790 			ata_ehi_clear_desc(&ap->link.eh_info);
6791 		} else
6792 			ata_port_printk(ap, KERN_INFO, "DUMMY\n");
6793 	}
6794 
6795 	/* perform each probe synchronously */
6796 	DPRINTK("probe begin\n");
6797 	for (i = 0; i < host->n_ports; i++) {
6798 		struct ata_port *ap = host->ports[i];
6799 		int rc;
6800 
6801 		/* probe */
6802 		if (ap->ops->error_handler) {
6803 			struct ata_eh_info *ehi = &ap->link.eh_info;
6804 			unsigned long flags;
6805 
6806 			ata_port_probe(ap);
6807 
6808 			/* kick EH for boot probing */
6809 			spin_lock_irqsave(ap->lock, flags);
6810 
6811 			ehi->probe_mask =
6812 				(1 << ata_link_max_devices(&ap->link)) - 1;
6813 			ehi->action |= ATA_EH_SOFTRESET;
6814 			ehi->flags |= ATA_EHI_NO_AUTOPSY | ATA_EHI_QUIET;
6815 
6816 			ap->pflags &= ~ATA_PFLAG_INITIALIZING;
6817 			ap->pflags |= ATA_PFLAG_LOADING;
6818 			ata_port_schedule_eh(ap);
6819 
6820 			spin_unlock_irqrestore(ap->lock, flags);
6821 
6822 			/* wait for EH to finish */
6823 			ata_port_wait_eh(ap);
6824 		} else {
6825 			DPRINTK("ata%u: bus probe begin\n", ap->print_id);
6826 			rc = ata_bus_probe(ap);
6827 			DPRINTK("ata%u: bus probe end\n", ap->print_id);
6828 
6829 			if (rc) {
6830 				/* FIXME: do something useful here?
6831 				 * Current libata behavior will
6832 				 * tear down everything when
6833 				 * the module is removed
6834 				 * or the h/w is unplugged.
6835 				 */
6836 			}
6837 		}
6838 	}
6839 
6840 	/* probes are done, now scan each port's disk(s) */
6841 	DPRINTK("host probe begin\n");
6842 	for (i = 0; i < host->n_ports; i++) {
6843 		struct ata_port *ap = host->ports[i];
6844 
6845 		ata_scsi_scan_host(ap, 1);
6846 	}
6847 
6848 	return 0;
6849 }
6850 
6851 /**
6852  *	ata_host_activate - start host, request IRQ and register it
6853  *	@host: target ATA host
6854  *	@irq: IRQ to request
6855  *	@irq_handler: irq_handler used when requesting IRQ
6856  *	@irq_flags: irq_flags used when requesting IRQ
6857  *	@sht: scsi_host_template to use when registering the host
6858  *
6859  *	After allocating an ATA host and initializing it, most libata
6860  *	LLDs perform three steps to activate the host - start host,
6861  *	request IRQ and register it.  This helper takes necessasry
6862  *	arguments and performs the three steps in one go.
6863  *
6864  *	LOCKING:
6865  *	Inherited from calling layer (may sleep).
6866  *
6867  *	RETURNS:
6868  *	0 on success, -errno otherwise.
6869  */
6870 int ata_host_activate(struct ata_host *host, int irq,
6871 		      irq_handler_t irq_handler, unsigned long irq_flags,
6872 		      struct scsi_host_template *sht)
6873 {
6874 	int i, rc;
6875 
6876 	rc = ata_host_start(host);
6877 	if (rc)
6878 		return rc;
6879 
6880 	rc = devm_request_irq(host->dev, irq, irq_handler, irq_flags,
6881 			      dev_driver_string(host->dev), host);
6882 	if (rc)
6883 		return rc;
6884 
6885 	for (i = 0; i < host->n_ports; i++)
6886 		ata_port_desc(host->ports[i], "irq %d", irq);
6887 
6888 	rc = ata_host_register(host, sht);
6889 	/* if failed, just free the IRQ and leave ports alone */
6890 	if (rc)
6891 		devm_free_irq(host->dev, irq, host);
6892 
6893 	return rc;
6894 }
6895 
6896 /**
6897  *	ata_port_detach - Detach ATA port in prepration of device removal
6898  *	@ap: ATA port to be detached
6899  *
6900  *	Detach all ATA devices and the associated SCSI devices of @ap;
6901  *	then, remove the associated SCSI host.  @ap is guaranteed to
6902  *	be quiescent on return from this function.
6903  *
6904  *	LOCKING:
6905  *	Kernel thread context (may sleep).
6906  */
6907 void ata_port_detach(struct ata_port *ap)
6908 {
6909 	unsigned long flags;
6910 	struct ata_link *link;
6911 	struct ata_device *dev;
6912 
6913 	if (!ap->ops->error_handler)
6914 		goto skip_eh;
6915 
6916 	/* tell EH we're leaving & flush EH */
6917 	spin_lock_irqsave(ap->lock, flags);
6918 	ap->pflags |= ATA_PFLAG_UNLOADING;
6919 	spin_unlock_irqrestore(ap->lock, flags);
6920 
6921 	ata_port_wait_eh(ap);
6922 
6923 	/* EH is now guaranteed to see UNLOADING, so no new device
6924 	 * will be attached.  Disable all existing devices.
6925 	 */
6926 	spin_lock_irqsave(ap->lock, flags);
6927 
6928 	ata_port_for_each_link(link, ap) {
6929 		ata_link_for_each_dev(dev, link)
6930 			ata_dev_disable(dev);
6931 	}
6932 
6933 	spin_unlock_irqrestore(ap->lock, flags);
6934 
6935 	/* Final freeze & EH.  All in-flight commands are aborted.  EH
6936 	 * will be skipped and retrials will be terminated with bad
6937 	 * target.
6938 	 */
6939 	spin_lock_irqsave(ap->lock, flags);
6940 	ata_port_freeze(ap);	/* won't be thawed */
6941 	spin_unlock_irqrestore(ap->lock, flags);
6942 
6943 	ata_port_wait_eh(ap);
6944 	cancel_rearming_delayed_work(&ap->hotplug_task);
6945 
6946  skip_eh:
6947 	/* remove the associated SCSI host */
6948 	scsi_remove_host(ap->scsi_host);
6949 }
6950 
6951 /**
6952  *	ata_host_detach - Detach all ports of an ATA host
6953  *	@host: Host to detach
6954  *
6955  *	Detach all ports of @host.
6956  *
6957  *	LOCKING:
6958  *	Kernel thread context (may sleep).
6959  */
6960 void ata_host_detach(struct ata_host *host)
6961 {
6962 	int i;
6963 
6964 	for (i = 0; i < host->n_ports; i++)
6965 		ata_port_detach(host->ports[i]);
6966 }
6967 
6968 /**
6969  *	ata_std_ports - initialize ioaddr with standard port offsets.
6970  *	@ioaddr: IO address structure to be initialized
6971  *
6972  *	Utility function which initializes data_addr, error_addr,
6973  *	feature_addr, nsect_addr, lbal_addr, lbam_addr, lbah_addr,
6974  *	device_addr, status_addr, and command_addr to standard offsets
6975  *	relative to cmd_addr.
6976  *
6977  *	Does not set ctl_addr, altstatus_addr, bmdma_addr, or scr_addr.
6978  */
6979 
6980 void ata_std_ports(struct ata_ioports *ioaddr)
6981 {
6982 	ioaddr->data_addr = ioaddr->cmd_addr + ATA_REG_DATA;
6983 	ioaddr->error_addr = ioaddr->cmd_addr + ATA_REG_ERR;
6984 	ioaddr->feature_addr = ioaddr->cmd_addr + ATA_REG_FEATURE;
6985 	ioaddr->nsect_addr = ioaddr->cmd_addr + ATA_REG_NSECT;
6986 	ioaddr->lbal_addr = ioaddr->cmd_addr + ATA_REG_LBAL;
6987 	ioaddr->lbam_addr = ioaddr->cmd_addr + ATA_REG_LBAM;
6988 	ioaddr->lbah_addr = ioaddr->cmd_addr + ATA_REG_LBAH;
6989 	ioaddr->device_addr = ioaddr->cmd_addr + ATA_REG_DEVICE;
6990 	ioaddr->status_addr = ioaddr->cmd_addr + ATA_REG_STATUS;
6991 	ioaddr->command_addr = ioaddr->cmd_addr + ATA_REG_CMD;
6992 }
6993 
6994 
6995 #ifdef CONFIG_PCI
6996 
6997 /**
6998  *	ata_pci_remove_one - PCI layer callback for device removal
6999  *	@pdev: PCI device that was removed
7000  *
7001  *	PCI layer indicates to libata via this hook that hot-unplug or
7002  *	module unload event has occurred.  Detach all ports.  Resource
7003  *	release is handled via devres.
7004  *
7005  *	LOCKING:
7006  *	Inherited from PCI layer (may sleep).
7007  */
7008 void ata_pci_remove_one(struct pci_dev *pdev)
7009 {
7010 	struct device *dev = &pdev->dev;
7011 	struct ata_host *host = dev_get_drvdata(dev);
7012 
7013 	ata_host_detach(host);
7014 }
7015 
7016 /* move to PCI subsystem */
7017 int pci_test_config_bits(struct pci_dev *pdev, const struct pci_bits *bits)
7018 {
7019 	unsigned long tmp = 0;
7020 
7021 	switch (bits->width) {
7022 	case 1: {
7023 		u8 tmp8 = 0;
7024 		pci_read_config_byte(pdev, bits->reg, &tmp8);
7025 		tmp = tmp8;
7026 		break;
7027 	}
7028 	case 2: {
7029 		u16 tmp16 = 0;
7030 		pci_read_config_word(pdev, bits->reg, &tmp16);
7031 		tmp = tmp16;
7032 		break;
7033 	}
7034 	case 4: {
7035 		u32 tmp32 = 0;
7036 		pci_read_config_dword(pdev, bits->reg, &tmp32);
7037 		tmp = tmp32;
7038 		break;
7039 	}
7040 
7041 	default:
7042 		return -EINVAL;
7043 	}
7044 
7045 	tmp &= bits->mask;
7046 
7047 	return (tmp == bits->val) ? 1 : 0;
7048 }
7049 
7050 #ifdef CONFIG_PM
7051 void ata_pci_device_do_suspend(struct pci_dev *pdev, pm_message_t mesg)
7052 {
7053 	pci_save_state(pdev);
7054 	pci_disable_device(pdev);
7055 
7056 	if (mesg.event == PM_EVENT_SUSPEND)
7057 		pci_set_power_state(pdev, PCI_D3hot);
7058 }
7059 
7060 int ata_pci_device_do_resume(struct pci_dev *pdev)
7061 {
7062 	int rc;
7063 
7064 	pci_set_power_state(pdev, PCI_D0);
7065 	pci_restore_state(pdev);
7066 
7067 	rc = pcim_enable_device(pdev);
7068 	if (rc) {
7069 		dev_printk(KERN_ERR, &pdev->dev,
7070 			   "failed to enable device after resume (%d)\n", rc);
7071 		return rc;
7072 	}
7073 
7074 	pci_set_master(pdev);
7075 	return 0;
7076 }
7077 
7078 int ata_pci_device_suspend(struct pci_dev *pdev, pm_message_t mesg)
7079 {
7080 	struct ata_host *host = dev_get_drvdata(&pdev->dev);
7081 	int rc = 0;
7082 
7083 	rc = ata_host_suspend(host, mesg);
7084 	if (rc)
7085 		return rc;
7086 
7087 	ata_pci_device_do_suspend(pdev, mesg);
7088 
7089 	return 0;
7090 }
7091 
7092 int ata_pci_device_resume(struct pci_dev *pdev)
7093 {
7094 	struct ata_host *host = dev_get_drvdata(&pdev->dev);
7095 	int rc;
7096 
7097 	rc = ata_pci_device_do_resume(pdev);
7098 	if (rc == 0)
7099 		ata_host_resume(host);
7100 	return rc;
7101 }
7102 #endif /* CONFIG_PM */
7103 
7104 #endif /* CONFIG_PCI */
7105 
7106 
7107 static int __init ata_init(void)
7108 {
7109 	ata_probe_timeout *= HZ;
7110 	ata_wq = create_workqueue("ata");
7111 	if (!ata_wq)
7112 		return -ENOMEM;
7113 
7114 	ata_aux_wq = create_singlethread_workqueue("ata_aux");
7115 	if (!ata_aux_wq) {
7116 		destroy_workqueue(ata_wq);
7117 		return -ENOMEM;
7118 	}
7119 
7120 	printk(KERN_DEBUG "libata version " DRV_VERSION " loaded.\n");
7121 	return 0;
7122 }
7123 
7124 static void __exit ata_exit(void)
7125 {
7126 	destroy_workqueue(ata_wq);
7127 	destroy_workqueue(ata_aux_wq);
7128 }
7129 
7130 subsys_initcall(ata_init);
7131 module_exit(ata_exit);
7132 
7133 static unsigned long ratelimit_time;
7134 static DEFINE_SPINLOCK(ata_ratelimit_lock);
7135 
7136 int ata_ratelimit(void)
7137 {
7138 	int rc;
7139 	unsigned long flags;
7140 
7141 	spin_lock_irqsave(&ata_ratelimit_lock, flags);
7142 
7143 	if (time_after(jiffies, ratelimit_time)) {
7144 		rc = 1;
7145 		ratelimit_time = jiffies + (HZ/5);
7146 	} else
7147 		rc = 0;
7148 
7149 	spin_unlock_irqrestore(&ata_ratelimit_lock, flags);
7150 
7151 	return rc;
7152 }
7153 
7154 /**
7155  *	ata_wait_register - wait until register value changes
7156  *	@reg: IO-mapped register
7157  *	@mask: Mask to apply to read register value
7158  *	@val: Wait condition
7159  *	@interval_msec: polling interval in milliseconds
7160  *	@timeout_msec: timeout in milliseconds
7161  *
7162  *	Waiting for some bits of register to change is a common
7163  *	operation for ATA controllers.  This function reads 32bit LE
7164  *	IO-mapped register @reg and tests for the following condition.
7165  *
7166  *	(*@reg & mask) != val
7167  *
7168  *	If the condition is met, it returns; otherwise, the process is
7169  *	repeated after @interval_msec until timeout.
7170  *
7171  *	LOCKING:
7172  *	Kernel thread context (may sleep)
7173  *
7174  *	RETURNS:
7175  *	The final register value.
7176  */
7177 u32 ata_wait_register(void __iomem *reg, u32 mask, u32 val,
7178 		      unsigned long interval_msec,
7179 		      unsigned long timeout_msec)
7180 {
7181 	unsigned long timeout;
7182 	u32 tmp;
7183 
7184 	tmp = ioread32(reg);
7185 
7186 	/* Calculate timeout _after_ the first read to make sure
7187 	 * preceding writes reach the controller before starting to
7188 	 * eat away the timeout.
7189 	 */
7190 	timeout = jiffies + (timeout_msec * HZ) / 1000;
7191 
7192 	while ((tmp & mask) == val && time_before(jiffies, timeout)) {
7193 		msleep(interval_msec);
7194 		tmp = ioread32(reg);
7195 	}
7196 
7197 	return tmp;
7198 }
7199 
7200 /*
7201  * Dummy port_ops
7202  */
7203 static void ata_dummy_noret(struct ata_port *ap)	{ }
7204 static int ata_dummy_ret0(struct ata_port *ap)		{ return 0; }
7205 static void ata_dummy_qc_noret(struct ata_queued_cmd *qc) { }
7206 
7207 static u8 ata_dummy_check_status(struct ata_port *ap)
7208 {
7209 	return ATA_DRDY;
7210 }
7211 
7212 static unsigned int ata_dummy_qc_issue(struct ata_queued_cmd *qc)
7213 {
7214 	return AC_ERR_SYSTEM;
7215 }
7216 
7217 const struct ata_port_operations ata_dummy_port_ops = {
7218 	.check_status		= ata_dummy_check_status,
7219 	.check_altstatus	= ata_dummy_check_status,
7220 	.dev_select		= ata_noop_dev_select,
7221 	.qc_prep		= ata_noop_qc_prep,
7222 	.qc_issue		= ata_dummy_qc_issue,
7223 	.freeze			= ata_dummy_noret,
7224 	.thaw			= ata_dummy_noret,
7225 	.error_handler		= ata_dummy_noret,
7226 	.post_internal_cmd	= ata_dummy_qc_noret,
7227 	.irq_clear		= ata_dummy_noret,
7228 	.port_start		= ata_dummy_ret0,
7229 	.port_stop		= ata_dummy_noret,
7230 };
7231 
7232 const struct ata_port_info ata_dummy_port_info = {
7233 	.port_ops		= &ata_dummy_port_ops,
7234 };
7235 
7236 /*
7237  * libata is essentially a library of internal helper functions for
7238  * low-level ATA host controller drivers.  As such, the API/ABI is
7239  * likely to change as new drivers are added and updated.
7240  * Do not depend on ABI/API stability.
7241  */
7242 
7243 EXPORT_SYMBOL_GPL(sata_deb_timing_normal);
7244 EXPORT_SYMBOL_GPL(sata_deb_timing_hotplug);
7245 EXPORT_SYMBOL_GPL(sata_deb_timing_long);
7246 EXPORT_SYMBOL_GPL(ata_dummy_port_ops);
7247 EXPORT_SYMBOL_GPL(ata_dummy_port_info);
7248 EXPORT_SYMBOL_GPL(ata_std_bios_param);
7249 EXPORT_SYMBOL_GPL(ata_std_ports);
7250 EXPORT_SYMBOL_GPL(ata_host_init);
7251 EXPORT_SYMBOL_GPL(ata_host_alloc);
7252 EXPORT_SYMBOL_GPL(ata_host_alloc_pinfo);
7253 EXPORT_SYMBOL_GPL(ata_host_start);
7254 EXPORT_SYMBOL_GPL(ata_host_register);
7255 EXPORT_SYMBOL_GPL(ata_host_activate);
7256 EXPORT_SYMBOL_GPL(ata_host_detach);
7257 EXPORT_SYMBOL_GPL(ata_sg_init);
7258 EXPORT_SYMBOL_GPL(ata_sg_init_one);
7259 EXPORT_SYMBOL_GPL(ata_hsm_move);
7260 EXPORT_SYMBOL_GPL(ata_qc_complete);
7261 EXPORT_SYMBOL_GPL(ata_qc_complete_multiple);
7262 EXPORT_SYMBOL_GPL(ata_qc_issue_prot);
7263 EXPORT_SYMBOL_GPL(ata_tf_load);
7264 EXPORT_SYMBOL_GPL(ata_tf_read);
7265 EXPORT_SYMBOL_GPL(ata_noop_dev_select);
7266 EXPORT_SYMBOL_GPL(ata_std_dev_select);
7267 EXPORT_SYMBOL_GPL(sata_print_link_status);
7268 EXPORT_SYMBOL_GPL(ata_tf_to_fis);
7269 EXPORT_SYMBOL_GPL(ata_tf_from_fis);
7270 EXPORT_SYMBOL_GPL(ata_check_status);
7271 EXPORT_SYMBOL_GPL(ata_altstatus);
7272 EXPORT_SYMBOL_GPL(ata_exec_command);
7273 EXPORT_SYMBOL_GPL(ata_port_start);
7274 EXPORT_SYMBOL_GPL(ata_sff_port_start);
7275 EXPORT_SYMBOL_GPL(ata_interrupt);
7276 EXPORT_SYMBOL_GPL(ata_do_set_mode);
7277 EXPORT_SYMBOL_GPL(ata_data_xfer);
7278 EXPORT_SYMBOL_GPL(ata_data_xfer_noirq);
7279 EXPORT_SYMBOL_GPL(ata_std_qc_defer);
7280 EXPORT_SYMBOL_GPL(ata_qc_prep);
7281 EXPORT_SYMBOL_GPL(ata_dumb_qc_prep);
7282 EXPORT_SYMBOL_GPL(ata_noop_qc_prep);
7283 EXPORT_SYMBOL_GPL(ata_bmdma_setup);
7284 EXPORT_SYMBOL_GPL(ata_bmdma_start);
7285 EXPORT_SYMBOL_GPL(ata_bmdma_irq_clear);
7286 EXPORT_SYMBOL_GPL(ata_bmdma_status);
7287 EXPORT_SYMBOL_GPL(ata_bmdma_stop);
7288 EXPORT_SYMBOL_GPL(ata_bmdma_freeze);
7289 EXPORT_SYMBOL_GPL(ata_bmdma_thaw);
7290 EXPORT_SYMBOL_GPL(ata_bmdma_drive_eh);
7291 EXPORT_SYMBOL_GPL(ata_bmdma_error_handler);
7292 EXPORT_SYMBOL_GPL(ata_bmdma_post_internal_cmd);
7293 EXPORT_SYMBOL_GPL(ata_port_probe);
7294 EXPORT_SYMBOL_GPL(ata_dev_disable);
7295 EXPORT_SYMBOL_GPL(sata_set_spd);
7296 EXPORT_SYMBOL_GPL(sata_link_debounce);
7297 EXPORT_SYMBOL_GPL(sata_link_resume);
7298 EXPORT_SYMBOL_GPL(sata_phy_reset);
7299 EXPORT_SYMBOL_GPL(__sata_phy_reset);
7300 EXPORT_SYMBOL_GPL(ata_bus_reset);
7301 EXPORT_SYMBOL_GPL(ata_std_prereset);
7302 EXPORT_SYMBOL_GPL(ata_std_softreset);
7303 EXPORT_SYMBOL_GPL(sata_link_hardreset);
7304 EXPORT_SYMBOL_GPL(sata_std_hardreset);
7305 EXPORT_SYMBOL_GPL(ata_std_postreset);
7306 EXPORT_SYMBOL_GPL(ata_dev_classify);
7307 EXPORT_SYMBOL_GPL(ata_dev_pair);
7308 EXPORT_SYMBOL_GPL(ata_port_disable);
7309 EXPORT_SYMBOL_GPL(ata_ratelimit);
7310 EXPORT_SYMBOL_GPL(ata_wait_register);
7311 EXPORT_SYMBOL_GPL(ata_busy_sleep);
7312 EXPORT_SYMBOL_GPL(ata_wait_ready);
7313 EXPORT_SYMBOL_GPL(ata_port_queue_task);
7314 EXPORT_SYMBOL_GPL(ata_scsi_ioctl);
7315 EXPORT_SYMBOL_GPL(ata_scsi_queuecmd);
7316 EXPORT_SYMBOL_GPL(ata_scsi_slave_config);
7317 EXPORT_SYMBOL_GPL(ata_scsi_slave_destroy);
7318 EXPORT_SYMBOL_GPL(ata_scsi_change_queue_depth);
7319 EXPORT_SYMBOL_GPL(ata_host_intr);
7320 EXPORT_SYMBOL_GPL(sata_scr_valid);
7321 EXPORT_SYMBOL_GPL(sata_scr_read);
7322 EXPORT_SYMBOL_GPL(sata_scr_write);
7323 EXPORT_SYMBOL_GPL(sata_scr_write_flush);
7324 EXPORT_SYMBOL_GPL(ata_link_online);
7325 EXPORT_SYMBOL_GPL(ata_link_offline);
7326 #ifdef CONFIG_PM
7327 EXPORT_SYMBOL_GPL(ata_host_suspend);
7328 EXPORT_SYMBOL_GPL(ata_host_resume);
7329 #endif /* CONFIG_PM */
7330 EXPORT_SYMBOL_GPL(ata_id_string);
7331 EXPORT_SYMBOL_GPL(ata_id_c_string);
7332 EXPORT_SYMBOL_GPL(ata_id_to_dma_mode);
7333 EXPORT_SYMBOL_GPL(ata_scsi_simulate);
7334 
7335 EXPORT_SYMBOL_GPL(ata_pio_need_iordy);
7336 EXPORT_SYMBOL_GPL(ata_timing_compute);
7337 EXPORT_SYMBOL_GPL(ata_timing_merge);
7338 
7339 #ifdef CONFIG_PCI
7340 EXPORT_SYMBOL_GPL(pci_test_config_bits);
7341 EXPORT_SYMBOL_GPL(ata_pci_init_sff_host);
7342 EXPORT_SYMBOL_GPL(ata_pci_init_bmdma);
7343 EXPORT_SYMBOL_GPL(ata_pci_prepare_sff_host);
7344 EXPORT_SYMBOL_GPL(ata_pci_init_one);
7345 EXPORT_SYMBOL_GPL(ata_pci_remove_one);
7346 #ifdef CONFIG_PM
7347 EXPORT_SYMBOL_GPL(ata_pci_device_do_suspend);
7348 EXPORT_SYMBOL_GPL(ata_pci_device_do_resume);
7349 EXPORT_SYMBOL_GPL(ata_pci_device_suspend);
7350 EXPORT_SYMBOL_GPL(ata_pci_device_resume);
7351 #endif /* CONFIG_PM */
7352 EXPORT_SYMBOL_GPL(ata_pci_default_filter);
7353 EXPORT_SYMBOL_GPL(ata_pci_clear_simplex);
7354 #endif /* CONFIG_PCI */
7355 
7356 EXPORT_SYMBOL_GPL(sata_pmp_qc_defer_cmd_switch);
7357 EXPORT_SYMBOL_GPL(sata_pmp_std_prereset);
7358 EXPORT_SYMBOL_GPL(sata_pmp_std_hardreset);
7359 EXPORT_SYMBOL_GPL(sata_pmp_std_postreset);
7360 EXPORT_SYMBOL_GPL(sata_pmp_do_eh);
7361 
7362 EXPORT_SYMBOL_GPL(__ata_ehi_push_desc);
7363 EXPORT_SYMBOL_GPL(ata_ehi_push_desc);
7364 EXPORT_SYMBOL_GPL(ata_ehi_clear_desc);
7365 EXPORT_SYMBOL_GPL(ata_port_desc);
7366 #ifdef CONFIG_PCI
7367 EXPORT_SYMBOL_GPL(ata_port_pbar_desc);
7368 #endif /* CONFIG_PCI */
7369 EXPORT_SYMBOL_GPL(ata_eng_timeout);
7370 EXPORT_SYMBOL_GPL(ata_port_schedule_eh);
7371 EXPORT_SYMBOL_GPL(ata_link_abort);
7372 EXPORT_SYMBOL_GPL(ata_port_abort);
7373 EXPORT_SYMBOL_GPL(ata_port_freeze);
7374 EXPORT_SYMBOL_GPL(sata_async_notification);
7375 EXPORT_SYMBOL_GPL(ata_eh_freeze_port);
7376 EXPORT_SYMBOL_GPL(ata_eh_thaw_port);
7377 EXPORT_SYMBOL_GPL(ata_eh_qc_complete);
7378 EXPORT_SYMBOL_GPL(ata_eh_qc_retry);
7379 EXPORT_SYMBOL_GPL(ata_do_eh);
7380 EXPORT_SYMBOL_GPL(ata_irq_on);
7381 EXPORT_SYMBOL_GPL(ata_dev_try_classify);
7382 
7383 EXPORT_SYMBOL_GPL(ata_cable_40wire);
7384 EXPORT_SYMBOL_GPL(ata_cable_80wire);
7385 EXPORT_SYMBOL_GPL(ata_cable_unknown);
7386 EXPORT_SYMBOL_GPL(ata_cable_sata);
7387