xref: /linux/drivers/ata/libata-core.c (revision 2c75a8d92cf173113d1e43a41cb472cd93561bf8)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  libata-core.c - helper library for ATA
4  *
5  *  Copyright 2003-2004 Red Hat, Inc.  All rights reserved.
6  *  Copyright 2003-2004 Jeff Garzik
7  *
8  *  libata documentation is available via 'make {ps|pdf}docs',
9  *  as Documentation/driver-api/libata.rst
10  *
11  *  Hardware documentation available from http://www.t13.org/ and
12  *  http://www.sata-io.org/
13  *
14  *  Standards documents from:
15  *	http://www.t13.org (ATA standards, PCI DMA IDE spec)
16  *	http://www.t10.org (SCSI MMC - for ATAPI MMC)
17  *	http://www.sata-io.org (SATA)
18  *	http://www.compactflash.org (CF)
19  *	http://www.qic.org (QIC157 - Tape and DSC)
20  *	http://www.ce-ata.org (CE-ATA: not supported)
21  *
22  * libata is essentially a library of internal helper functions for
23  * low-level ATA host controller drivers.  As such, the API/ABI is
24  * likely to change as new drivers are added and updated.
25  * Do not depend on ABI/API stability.
26  */
27 
28 #include <linux/kernel.h>
29 #include <linux/module.h>
30 #include <linux/pci.h>
31 #include <linux/init.h>
32 #include <linux/list.h>
33 #include <linux/mm.h>
34 #include <linux/spinlock.h>
35 #include <linux/blkdev.h>
36 #include <linux/delay.h>
37 #include <linux/timer.h>
38 #include <linux/time.h>
39 #include <linux/interrupt.h>
40 #include <linux/completion.h>
41 #include <linux/suspend.h>
42 #include <linux/workqueue.h>
43 #include <linux/scatterlist.h>
44 #include <linux/io.h>
45 #include <linux/log2.h>
46 #include <linux/slab.h>
47 #include <linux/glob.h>
48 #include <scsi/scsi.h>
49 #include <scsi/scsi_cmnd.h>
50 #include <scsi/scsi_host.h>
51 #include <linux/libata.h>
52 #include <asm/byteorder.h>
53 #include <linux/unaligned.h>
54 #include <linux/cdrom.h>
55 #include <linux/ratelimit.h>
56 #include <linux/leds.h>
57 #include <linux/pm_runtime.h>
58 #include <linux/platform_device.h>
59 #include <asm/setup.h>
60 
61 #define CREATE_TRACE_POINTS
62 #include <trace/events/libata.h>
63 
64 #include "libata.h"
65 #include "libata-transport.h"
66 
67 const struct ata_port_operations ata_base_port_ops = {
68 	.reset.prereset		= ata_std_prereset,
69 	.reset.postreset	= ata_std_postreset,
70 	.error_handler		= ata_std_error_handler,
71 	.sched_eh		= ata_std_sched_eh,
72 	.end_eh			= ata_std_end_eh,
73 };
74 
75 static unsigned int ata_dev_init_params(struct ata_device *dev,
76 					u16 heads, u16 sectors);
77 static unsigned int ata_dev_set_xfermode(struct ata_device *dev);
78 static void ata_dev_xfermask(struct ata_device *dev);
79 static u64 ata_dev_quirks(const struct ata_device *dev);
80 static u64 ata_dev_get_quirk_value(struct ata_device *dev, u64 quirk);
81 
82 static DEFINE_IDA(ata_ida);
83 
84 #ifdef CONFIG_ATA_FORCE
85 struct ata_force_param {
86 	const char	*name;
87 	u64		value;
88 	u8		cbl;
89 	u8		spd_limit;
90 	unsigned int	xfer_mask;
91 	u64		quirk_on;
92 	u64		quirk_off;
93 	unsigned int	pflags_on;
94 	u16		lflags_on;
95 	u16		lflags_off;
96 };
97 
98 struct ata_force_ent {
99 	int			port;
100 	int			device;
101 	struct ata_force_param	param;
102 };
103 
104 static struct ata_force_ent *ata_force_tbl;
105 static int ata_force_tbl_size;
106 
107 static char ata_force_param_buf[COMMAND_LINE_SIZE] __initdata;
108 /* param_buf is thrown away after initialization, disallow read */
109 module_param_string(force, ata_force_param_buf, sizeof(ata_force_param_buf), 0);
110 MODULE_PARM_DESC(force, "Force ATA configurations including cable type, link speed and transfer mode (see Documentation/admin-guide/kernel-parameters.rst for details)");
111 #endif
112 
113 static int atapi_enabled = 1;
114 module_param(atapi_enabled, int, 0444);
115 MODULE_PARM_DESC(atapi_enabled, "Enable discovery of ATAPI devices (0=off, 1=on [default])");
116 
117 static int atapi_dmadir = 0;
118 module_param(atapi_dmadir, int, 0444);
119 MODULE_PARM_DESC(atapi_dmadir, "Enable ATAPI DMADIR bridge support (0=off [default], 1=on)");
120 
121 int atapi_passthru16 = 1;
122 module_param(atapi_passthru16, int, 0444);
123 MODULE_PARM_DESC(atapi_passthru16, "Enable ATA_16 passthru for ATAPI devices (0=off, 1=on [default])");
124 
125 int libata_fua = 0;
126 module_param_named(fua, libata_fua, int, 0444);
127 MODULE_PARM_DESC(fua, "FUA support (0=off [default], 1=on)");
128 
129 static int ata_ignore_hpa;
130 module_param_named(ignore_hpa, ata_ignore_hpa, int, 0644);
131 MODULE_PARM_DESC(ignore_hpa, "Ignore HPA limit (0=keep BIOS limits, 1=ignore limits, using full disk)");
132 
133 static int libata_dma_mask = ATA_DMA_MASK_ATA|ATA_DMA_MASK_ATAPI|ATA_DMA_MASK_CFA;
134 module_param_named(dma, libata_dma_mask, int, 0444);
135 MODULE_PARM_DESC(dma, "DMA enable/disable (0x1==ATA, 0x2==ATAPI, 0x4==CF)");
136 
137 static int ata_probe_timeout;
138 module_param(ata_probe_timeout, int, 0444);
139 MODULE_PARM_DESC(ata_probe_timeout, "Set ATA probing timeout (seconds)");
140 
141 int libata_noacpi = 0;
142 module_param_named(noacpi, libata_noacpi, int, 0444);
143 MODULE_PARM_DESC(noacpi, "Disable the use of ACPI in probe/suspend/resume (0=off [default], 1=on)");
144 
145 int libata_allow_tpm = 0;
146 module_param_named(allow_tpm, libata_allow_tpm, int, 0444);
147 MODULE_PARM_DESC(allow_tpm, "Permit the use of TPM commands (0=off [default], 1=on)");
148 
149 static int atapi_an;
150 module_param(atapi_an, int, 0444);
151 MODULE_PARM_DESC(atapi_an, "Enable ATAPI AN media presence notification (0=0ff [default], 1=on)");
152 
153 MODULE_AUTHOR("Jeff Garzik");
154 MODULE_DESCRIPTION("Library module for ATA devices");
155 MODULE_LICENSE("GPL");
156 MODULE_VERSION(DRV_VERSION);
157 
158 static inline bool ata_dev_print_info(const struct ata_device *dev)
159 {
160 	struct ata_eh_context *ehc = &dev->link->eh_context;
161 
162 	return ehc->i.flags & ATA_EHI_PRINTINFO;
163 }
164 
165 /**
166  *	ata_link_next - link iteration helper
167  *	@link: the previous link, NULL to start
168  *	@ap: ATA port containing links to iterate
169  *	@mode: iteration mode, one of ATA_LITER_*
170  *
171  *	LOCKING:
172  *	Host lock or EH context.
173  *
174  *	RETURNS:
175  *	Pointer to the next link.
176  */
177 struct ata_link *ata_link_next(struct ata_link *link, struct ata_port *ap,
178 			       enum ata_link_iter_mode mode)
179 {
180 	BUG_ON(mode != ATA_LITER_EDGE &&
181 	       mode != ATA_LITER_PMP_FIRST && mode != ATA_LITER_HOST_FIRST);
182 
183 	/* NULL link indicates start of iteration */
184 	if (!link)
185 		switch (mode) {
186 		case ATA_LITER_EDGE:
187 		case ATA_LITER_PMP_FIRST:
188 			if (sata_pmp_attached(ap))
189 				return ap->pmp_link;
190 			fallthrough;
191 		case ATA_LITER_HOST_FIRST:
192 			return &ap->link;
193 		}
194 
195 	/* we just iterated over the host link, what's next? */
196 	if (link == &ap->link)
197 		switch (mode) {
198 		case ATA_LITER_HOST_FIRST:
199 			if (sata_pmp_attached(ap))
200 				return ap->pmp_link;
201 			fallthrough;
202 		case ATA_LITER_PMP_FIRST:
203 			if (unlikely(ap->slave_link))
204 				return ap->slave_link;
205 			fallthrough;
206 		case ATA_LITER_EDGE:
207 			return NULL;
208 		}
209 
210 	/* slave_link excludes PMP */
211 	if (unlikely(link == ap->slave_link))
212 		return NULL;
213 
214 	/* we were over a PMP link */
215 	if (++link < ap->pmp_link + ap->nr_pmp_links)
216 		return link;
217 
218 	if (mode == ATA_LITER_PMP_FIRST)
219 		return &ap->link;
220 
221 	return NULL;
222 }
223 EXPORT_SYMBOL_GPL(ata_link_next);
224 
225 /**
226  *	ata_dev_next - device iteration helper
227  *	@dev: the previous device, NULL to start
228  *	@link: ATA link containing devices to iterate
229  *	@mode: iteration mode, one of ATA_DITER_*
230  *
231  *	LOCKING:
232  *	Host lock or EH context.
233  *
234  *	RETURNS:
235  *	Pointer to the next device.
236  */
237 struct ata_device *ata_dev_next(struct ata_device *dev, struct ata_link *link,
238 				enum ata_dev_iter_mode mode)
239 {
240 	BUG_ON(mode != ATA_DITER_ENABLED && mode != ATA_DITER_ENABLED_REVERSE &&
241 	       mode != ATA_DITER_ALL && mode != ATA_DITER_ALL_REVERSE);
242 
243 	/* NULL dev indicates start of iteration */
244 	if (!dev)
245 		switch (mode) {
246 		case ATA_DITER_ENABLED:
247 		case ATA_DITER_ALL:
248 			dev = link->device;
249 			goto check;
250 		case ATA_DITER_ENABLED_REVERSE:
251 		case ATA_DITER_ALL_REVERSE:
252 			dev = link->device + ata_link_max_devices(link) - 1;
253 			goto check;
254 		}
255 
256  next:
257 	/* move to the next one */
258 	switch (mode) {
259 	case ATA_DITER_ENABLED:
260 	case ATA_DITER_ALL:
261 		if (++dev < link->device + ata_link_max_devices(link))
262 			goto check;
263 		return NULL;
264 	case ATA_DITER_ENABLED_REVERSE:
265 	case ATA_DITER_ALL_REVERSE:
266 		if (--dev >= link->device)
267 			goto check;
268 		return NULL;
269 	}
270 
271  check:
272 	if ((mode == ATA_DITER_ENABLED || mode == ATA_DITER_ENABLED_REVERSE) &&
273 	    !ata_dev_enabled(dev))
274 		goto next;
275 	return dev;
276 }
277 EXPORT_SYMBOL_GPL(ata_dev_next);
278 
279 /**
280  *	ata_dev_phys_link - find physical link for a device
281  *	@dev: ATA device to look up physical link for
282  *
283  *	Look up physical link which @dev is attached to.  Note that
284  *	this is different from @dev->link only when @dev is on slave
285  *	link.  For all other cases, it's the same as @dev->link.
286  *
287  *	LOCKING:
288  *	Don't care.
289  *
290  *	RETURNS:
291  *	Pointer to the found physical link.
292  */
293 struct ata_link *ata_dev_phys_link(struct ata_device *dev)
294 {
295 	struct ata_port *ap = dev->link->ap;
296 
297 	if (!ap->slave_link)
298 		return dev->link;
299 	if (!dev->devno)
300 		return &ap->link;
301 	return ap->slave_link;
302 }
303 
304 #ifdef CONFIG_ATA_FORCE
305 /**
306  *	ata_force_cbl - force cable type according to libata.force
307  *	@ap: ATA port of interest
308  *
309  *	Force cable type according to libata.force and whine about it.
310  *	The last entry which has matching port number is used, so it
311  *	can be specified as part of device force parameters.  For
312  *	example, both "a:40c,1.00:udma4" and "1.00:40c,udma4" have the
313  *	same effect.
314  *
315  *	LOCKING:
316  *	EH context.
317  */
318 void ata_force_cbl(struct ata_port *ap)
319 {
320 	int i;
321 
322 	for (i = ata_force_tbl_size - 1; i >= 0; i--) {
323 		const struct ata_force_ent *fe = &ata_force_tbl[i];
324 
325 		if (fe->port != -1 && fe->port != ap->print_id)
326 			continue;
327 
328 		if (fe->param.cbl == ATA_CBL_NONE)
329 			continue;
330 
331 		ap->cbl = fe->param.cbl;
332 		ata_port_notice(ap, "FORCE: cable set to %s\n", fe->param.name);
333 		return;
334 	}
335 }
336 
337 /**
338  *	ata_force_pflags - force port flags according to libata.force
339  *	@ap: ATA port of interest
340  *
341  *	Force port flags according to libata.force and whine about it.
342  *
343  *	LOCKING:
344  *	EH context.
345  */
346 static void ata_force_pflags(struct ata_port *ap)
347 {
348 	int i;
349 
350 	for (i = ata_force_tbl_size - 1; i >= 0; i--) {
351 		const struct ata_force_ent *fe = &ata_force_tbl[i];
352 
353 		if (fe->port != -1 && fe->port != ap->print_id)
354 			continue;
355 
356 		/* let pflags stack */
357 		if (fe->param.pflags_on) {
358 			ap->pflags |= fe->param.pflags_on;
359 			ata_port_notice(ap,
360 					"FORCE: port flag 0x%x forced -> 0x%x\n",
361 					fe->param.pflags_on, ap->pflags);
362 		}
363 	}
364 }
365 
366 /**
367  *	ata_force_link_limits - force link limits according to libata.force
368  *	@link: ATA link of interest
369  *
370  *	Force link flags and SATA spd limit according to libata.force
371  *	and whine about it.  When only the port part is specified
372  *	(e.g. 1:), the limit applies to all links connected to both
373  *	the host link and all fan-out ports connected via PMP.  If the
374  *	device part is specified as 0 (e.g. 1.00:), it specifies the
375  *	first fan-out link not the host link.  Device number 15 always
376  *	points to the host link whether PMP is attached or not.  If the
377  *	controller has slave link, device number 16 points to it.
378  *
379  *	LOCKING:
380  *	EH context.
381  */
382 static void ata_force_link_limits(struct ata_link *link)
383 {
384 	bool did_spd = false;
385 	int linkno = link->pmp;
386 	int i;
387 
388 	if (ata_is_host_link(link))
389 		linkno += 15;
390 
391 	for (i = ata_force_tbl_size - 1; i >= 0; i--) {
392 		const struct ata_force_ent *fe = &ata_force_tbl[i];
393 
394 		if (fe->port != -1 && fe->port != link->ap->print_id)
395 			continue;
396 
397 		if (fe->device != -1 && fe->device != linkno)
398 			continue;
399 
400 		/* only honor the first spd limit */
401 		if (!did_spd && fe->param.spd_limit) {
402 			link->hw_sata_spd_limit = (1 << fe->param.spd_limit) - 1;
403 			ata_link_notice(link, "FORCE: PHY spd limit set to %s\n",
404 					fe->param.name);
405 			did_spd = true;
406 		}
407 
408 		/* let lflags stack */
409 		if (fe->param.lflags_on) {
410 			link->flags |= fe->param.lflags_on;
411 			ata_link_notice(link,
412 					"FORCE: link flag 0x%x forced -> 0x%x\n",
413 					fe->param.lflags_on, link->flags);
414 		}
415 		if (fe->param.lflags_off) {
416 			link->flags &= ~fe->param.lflags_off;
417 			ata_link_notice(link,
418 				"FORCE: link flag 0x%x cleared -> 0x%x\n",
419 				fe->param.lflags_off, link->flags);
420 		}
421 	}
422 }
423 
424 /**
425  *	ata_force_xfermask - force xfermask according to libata.force
426  *	@dev: ATA device of interest
427  *
428  *	Force xfer_mask according to libata.force and whine about it.
429  *	For consistency with link selection, device number 15 selects
430  *	the first device connected to the host link.
431  *
432  *	LOCKING:
433  *	EH context.
434  */
435 static void ata_force_xfermask(struct ata_device *dev)
436 {
437 	int devno = dev->link->pmp + dev->devno;
438 	int alt_devno = devno;
439 	int i;
440 
441 	/* allow n.15/16 for devices attached to host port */
442 	if (ata_is_host_link(dev->link))
443 		alt_devno += 15;
444 
445 	for (i = ata_force_tbl_size - 1; i >= 0; i--) {
446 		const struct ata_force_ent *fe = &ata_force_tbl[i];
447 		unsigned int pio_mask, mwdma_mask, udma_mask;
448 
449 		if (fe->port != -1 && fe->port != dev->link->ap->print_id)
450 			continue;
451 
452 		if (fe->device != -1 && fe->device != devno &&
453 		    fe->device != alt_devno)
454 			continue;
455 
456 		if (!fe->param.xfer_mask)
457 			continue;
458 
459 		ata_unpack_xfermask(fe->param.xfer_mask,
460 				    &pio_mask, &mwdma_mask, &udma_mask);
461 		if (udma_mask)
462 			dev->udma_mask = udma_mask;
463 		else if (mwdma_mask) {
464 			dev->udma_mask = 0;
465 			dev->mwdma_mask = mwdma_mask;
466 		} else {
467 			dev->udma_mask = 0;
468 			dev->mwdma_mask = 0;
469 			dev->pio_mask = pio_mask;
470 		}
471 
472 		ata_dev_notice(dev, "FORCE: xfer_mask set to %s\n",
473 			       fe->param.name);
474 		return;
475 	}
476 }
477 
478 static const struct ata_force_ent *
479 ata_force_get_fe_for_dev(struct ata_device *dev)
480 {
481 	const struct ata_force_ent *fe;
482 	int devno = dev->link->pmp + dev->devno;
483 	int alt_devno = devno;
484 	int i;
485 
486 	/* allow n.15/16 for devices attached to host port */
487 	if (ata_is_host_link(dev->link))
488 		alt_devno += 15;
489 
490 	for (i = 0; i < ata_force_tbl_size; i++) {
491 		fe = &ata_force_tbl[i];
492 		if (fe->port != -1 && fe->port != dev->link->ap->print_id)
493 			continue;
494 
495 		if (fe->device != -1 && fe->device != devno &&
496 		    fe->device != alt_devno)
497 			continue;
498 
499 		return fe;
500 	}
501 
502 	return NULL;
503 }
504 
505 /**
506  *	ata_force_quirks - force quirks according to libata.force
507  *	@dev: ATA device of interest
508  *
509  *	Force quirks according to libata.force and whine about it.
510  *	For consistency with link selection, device number 15 selects
511  *	the first device connected to the host link.
512  *
513  *	LOCKING:
514  *	EH context.
515  */
516 static void ata_force_quirks(struct ata_device *dev)
517 {
518 	const struct ata_force_ent *fe = ata_force_get_fe_for_dev(dev);
519 
520 	if (!fe)
521 		return;
522 
523 	if (!(~dev->quirks & fe->param.quirk_on) &&
524 	    !(dev->quirks & fe->param.quirk_off))
525 		return;
526 
527 	dev->quirks |= fe->param.quirk_on;
528 	dev->quirks &= ~fe->param.quirk_off;
529 
530 	ata_dev_notice(dev, "FORCE: modified (%s)\n", fe->param.name);
531 }
532 #else
533 static inline void ata_force_pflags(struct ata_port *ap) { }
534 static inline void ata_force_link_limits(struct ata_link *link) { }
535 static inline void ata_force_xfermask(struct ata_device *dev) { }
536 static inline void ata_force_quirks(struct ata_device *dev) { }
537 #endif
538 
539 /**
540  *	atapi_cmd_type - Determine ATAPI command type from SCSI opcode
541  *	@opcode: SCSI opcode
542  *
543  *	Determine ATAPI command type from @opcode.
544  *
545  *	LOCKING:
546  *	None.
547  *
548  *	RETURNS:
549  *	ATAPI_{READ|WRITE|READ_CD|PASS_THRU|MISC}
550  */
551 int atapi_cmd_type(u8 opcode)
552 {
553 	switch (opcode) {
554 	case GPCMD_READ_10:
555 	case GPCMD_READ_12:
556 		return ATAPI_READ;
557 
558 	case GPCMD_WRITE_10:
559 	case GPCMD_WRITE_12:
560 	case GPCMD_WRITE_AND_VERIFY_10:
561 		return ATAPI_WRITE;
562 
563 	case GPCMD_READ_CD:
564 	case GPCMD_READ_CD_MSF:
565 		return ATAPI_READ_CD;
566 
567 	case ATA_16:
568 	case ATA_12:
569 		if (atapi_passthru16)
570 			return ATAPI_PASS_THRU;
571 		fallthrough;
572 	default:
573 		return ATAPI_MISC;
574 	}
575 }
576 EXPORT_SYMBOL_GPL(atapi_cmd_type);
577 
578 static const u8 ata_rw_cmds[] = {
579 	/* pio multi */
580 	ATA_CMD_READ_MULTI,
581 	ATA_CMD_WRITE_MULTI,
582 	ATA_CMD_READ_MULTI_EXT,
583 	ATA_CMD_WRITE_MULTI_EXT,
584 	0,
585 	0,
586 	0,
587 	0,
588 	/* pio */
589 	ATA_CMD_PIO_READ,
590 	ATA_CMD_PIO_WRITE,
591 	ATA_CMD_PIO_READ_EXT,
592 	ATA_CMD_PIO_WRITE_EXT,
593 	0,
594 	0,
595 	0,
596 	0,
597 	/* dma */
598 	ATA_CMD_READ,
599 	ATA_CMD_WRITE,
600 	ATA_CMD_READ_EXT,
601 	ATA_CMD_WRITE_EXT,
602 	0,
603 	0,
604 	0,
605 	ATA_CMD_WRITE_FUA_EXT
606 };
607 
608 /**
609  *	ata_set_rwcmd_protocol - set taskfile r/w command and protocol
610  *	@dev: target device for the taskfile
611  *	@tf: taskfile to examine and configure
612  *
613  *	Examine the device configuration and tf->flags to determine
614  *	the proper read/write command and protocol to use for @tf.
615  *
616  *	LOCKING:
617  *	caller.
618  */
619 static bool ata_set_rwcmd_protocol(struct ata_device *dev,
620 				   struct ata_taskfile *tf)
621 {
622 	u8 cmd;
623 
624 	int index, fua, lba48, write;
625 
626 	fua = (tf->flags & ATA_TFLAG_FUA) ? 4 : 0;
627 	lba48 = (tf->flags & ATA_TFLAG_LBA48) ? 2 : 0;
628 	write = (tf->flags & ATA_TFLAG_WRITE) ? 1 : 0;
629 
630 	if (dev->flags & ATA_DFLAG_PIO) {
631 		tf->protocol = ATA_PROT_PIO;
632 		index = dev->multi_count ? 0 : 8;
633 	} else if (lba48 && (dev->link->ap->flags & ATA_FLAG_PIO_LBA48)) {
634 		/* Unable to use DMA due to host limitation */
635 		tf->protocol = ATA_PROT_PIO;
636 		index = dev->multi_count ? 0 : 8;
637 	} else {
638 		tf->protocol = ATA_PROT_DMA;
639 		index = 16;
640 	}
641 
642 	cmd = ata_rw_cmds[index + fua + lba48 + write];
643 	if (!cmd)
644 		return false;
645 
646 	tf->command = cmd;
647 
648 	return true;
649 }
650 
651 /**
652  *	ata_tf_read_block - Read block address from ATA taskfile
653  *	@tf: ATA taskfile of interest
654  *	@dev: ATA device @tf belongs to
655  *
656  *	LOCKING:
657  *	None.
658  *
659  *	Read block address from @tf.  This function can handle all
660  *	three address formats - LBA, LBA48 and CHS.  tf->protocol and
661  *	flags select the address format to use.
662  *
663  *	RETURNS:
664  *	Block address read from @tf.
665  */
666 u64 ata_tf_read_block(const struct ata_taskfile *tf, struct ata_device *dev)
667 {
668 	u64 block = 0;
669 
670 	if (tf->flags & ATA_TFLAG_LBA) {
671 		if (tf->flags & ATA_TFLAG_LBA48) {
672 			block |= (u64)tf->hob_lbah << 40;
673 			block |= (u64)tf->hob_lbam << 32;
674 			block |= (u64)tf->hob_lbal << 24;
675 		} else
676 			block |= (tf->device & 0xf) << 24;
677 
678 		block |= tf->lbah << 16;
679 		block |= tf->lbam << 8;
680 		block |= tf->lbal;
681 	} else {
682 		u32 cyl, head, sect;
683 
684 		cyl = tf->lbam | (tf->lbah << 8);
685 		head = tf->device & 0xf;
686 		sect = tf->lbal;
687 
688 		if (!sect) {
689 			ata_dev_warn(dev,
690 				     "device reported invalid CHS sector 0\n");
691 			return U64_MAX;
692 		}
693 
694 		block = (cyl * dev->heads + head) * dev->sectors + sect - 1;
695 	}
696 
697 	return block;
698 }
699 
700 /*
701  * Set a taskfile command duration limit index.
702  */
703 static inline void ata_set_tf_cdl(struct ata_queued_cmd *qc, int cdl)
704 {
705 	struct ata_taskfile *tf = &qc->tf;
706 
707 	if (tf->protocol == ATA_PROT_NCQ)
708 		tf->auxiliary |= cdl;
709 	else
710 		tf->feature |= cdl;
711 
712 	/*
713 	 * Mark this command as having a CDL and request the result
714 	 * task file so that we can inspect the sense data available
715 	 * bit on completion.
716 	 */
717 	qc->flags |= ATA_QCFLAG_HAS_CDL | ATA_QCFLAG_RESULT_TF;
718 }
719 
720 /**
721  *	ata_build_rw_tf - Build ATA taskfile for given read/write request
722  *	@qc: Metadata associated with the taskfile to build
723  *	@block: Block address
724  *	@n_block: Number of blocks
725  *	@tf_flags: RW/FUA etc...
726  *	@cdl: Command duration limit index
727  *	@class: IO priority class
728  *
729  *	LOCKING:
730  *	None.
731  *
732  *	Build ATA taskfile for the command @qc for read/write request described
733  *	by @block, @n_block, @tf_flags and @class.
734  *
735  *	RETURNS:
736  *
737  *	0 on success, -ERANGE if the request is too large for @dev,
738  *	-EINVAL if the request is invalid.
739  */
740 int ata_build_rw_tf(struct ata_queued_cmd *qc, u64 block, u32 n_block,
741 		    unsigned int tf_flags, int cdl, int class)
742 {
743 	struct ata_taskfile *tf = &qc->tf;
744 	struct ata_device *dev = qc->dev;
745 
746 	tf->flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
747 	tf->flags |= tf_flags;
748 
749 	if (ata_ncq_enabled(dev)) {
750 		/* yay, NCQ */
751 		if (!lba_48_ok(block, n_block))
752 			return -ERANGE;
753 
754 		tf->protocol = ATA_PROT_NCQ;
755 		tf->flags |= ATA_TFLAG_LBA | ATA_TFLAG_LBA48;
756 
757 		if (tf->flags & ATA_TFLAG_WRITE)
758 			tf->command = ATA_CMD_FPDMA_WRITE;
759 		else
760 			tf->command = ATA_CMD_FPDMA_READ;
761 
762 		tf->nsect = qc->hw_tag << 3;
763 		tf->hob_feature = (n_block >> 8) & 0xff;
764 		tf->feature = n_block & 0xff;
765 
766 		tf->hob_lbah = (block >> 40) & 0xff;
767 		tf->hob_lbam = (block >> 32) & 0xff;
768 		tf->hob_lbal = (block >> 24) & 0xff;
769 		tf->lbah = (block >> 16) & 0xff;
770 		tf->lbam = (block >> 8) & 0xff;
771 		tf->lbal = block & 0xff;
772 
773 		tf->device = ATA_LBA;
774 		if (tf->flags & ATA_TFLAG_FUA)
775 			tf->device |= 1 << 7;
776 
777 		if (dev->flags & ATA_DFLAG_NCQ_PRIO_ENABLED &&
778 		    class == IOPRIO_CLASS_RT)
779 			tf->hob_nsect |= ATA_PRIO_HIGH << ATA_SHIFT_PRIO;
780 
781 		if ((dev->flags & ATA_DFLAG_CDL_ENABLED) && cdl)
782 			ata_set_tf_cdl(qc, cdl);
783 
784 	} else if (dev->flags & ATA_DFLAG_LBA) {
785 		tf->flags |= ATA_TFLAG_LBA;
786 
787 		if ((dev->flags & ATA_DFLAG_CDL_ENABLED) && cdl)
788 			ata_set_tf_cdl(qc, cdl);
789 
790 		/* Both FUA writes and a CDL index require 48-bit commands */
791 		if (!(tf->flags & ATA_TFLAG_FUA) &&
792 		    !(qc->flags & ATA_QCFLAG_HAS_CDL) &&
793 		    lba_28_ok(block, n_block)) {
794 			/* use LBA28 */
795 			tf->device |= (block >> 24) & 0xf;
796 		} else if (lba_48_ok(block, n_block)) {
797 			if (!(dev->flags & ATA_DFLAG_LBA48))
798 				return -ERANGE;
799 
800 			/* use LBA48 */
801 			tf->flags |= ATA_TFLAG_LBA48;
802 
803 			tf->hob_nsect = (n_block >> 8) & 0xff;
804 
805 			tf->hob_lbah = (block >> 40) & 0xff;
806 			tf->hob_lbam = (block >> 32) & 0xff;
807 			tf->hob_lbal = (block >> 24) & 0xff;
808 		} else {
809 			/* request too large even for LBA48 */
810 			return -ERANGE;
811 		}
812 
813 		if (unlikely(!ata_set_rwcmd_protocol(dev, tf)))
814 			return -EINVAL;
815 
816 		tf->nsect = n_block & 0xff;
817 
818 		tf->lbah = (block >> 16) & 0xff;
819 		tf->lbam = (block >> 8) & 0xff;
820 		tf->lbal = block & 0xff;
821 
822 		tf->device |= ATA_LBA;
823 	} else {
824 		/* CHS */
825 		u32 sect, head, cyl, track;
826 
827 		/* The request -may- be too large for CHS addressing. */
828 		if (!lba_28_ok(block, n_block))
829 			return -ERANGE;
830 
831 		if (unlikely(!ata_set_rwcmd_protocol(dev, tf)))
832 			return -EINVAL;
833 
834 		/* Convert LBA to CHS */
835 		track = (u32)block / dev->sectors;
836 		cyl   = track / dev->heads;
837 		head  = track % dev->heads;
838 		sect  = (u32)block % dev->sectors + 1;
839 
840 		/* Check whether the converted CHS can fit.
841 		   Cylinder: 0-65535
842 		   Head: 0-15
843 		   Sector: 1-255*/
844 		if ((cyl >> 16) || (head >> 4) || (sect >> 8) || (!sect))
845 			return -ERANGE;
846 
847 		tf->nsect = n_block & 0xff; /* Sector count 0 means 256 sectors */
848 		tf->lbal = sect;
849 		tf->lbam = cyl;
850 		tf->lbah = cyl >> 8;
851 		tf->device |= head;
852 	}
853 
854 	return 0;
855 }
856 
857 /**
858  *	ata_pack_xfermask - Pack pio, mwdma and udma masks into xfer_mask
859  *	@pio_mask: pio_mask
860  *	@mwdma_mask: mwdma_mask
861  *	@udma_mask: udma_mask
862  *
863  *	Pack @pio_mask, @mwdma_mask and @udma_mask into a single
864  *	unsigned int xfer_mask.
865  *
866  *	LOCKING:
867  *	None.
868  *
869  *	RETURNS:
870  *	Packed xfer_mask.
871  */
872 unsigned int ata_pack_xfermask(unsigned int pio_mask,
873 			       unsigned int mwdma_mask,
874 			       unsigned int udma_mask)
875 {
876 	return	((pio_mask << ATA_SHIFT_PIO) & ATA_MASK_PIO) |
877 		((mwdma_mask << ATA_SHIFT_MWDMA) & ATA_MASK_MWDMA) |
878 		((udma_mask << ATA_SHIFT_UDMA) & ATA_MASK_UDMA);
879 }
880 EXPORT_SYMBOL_GPL(ata_pack_xfermask);
881 
882 /**
883  *	ata_unpack_xfermask - Unpack xfer_mask into pio, mwdma and udma masks
884  *	@xfer_mask: xfer_mask to unpack
885  *	@pio_mask: resulting pio_mask
886  *	@mwdma_mask: resulting mwdma_mask
887  *	@udma_mask: resulting udma_mask
888  *
889  *	Unpack @xfer_mask into @pio_mask, @mwdma_mask and @udma_mask.
890  *	Any NULL destination masks will be ignored.
891  */
892 void ata_unpack_xfermask(unsigned int xfer_mask, unsigned int *pio_mask,
893 			 unsigned int *mwdma_mask, unsigned int *udma_mask)
894 {
895 	if (pio_mask)
896 		*pio_mask = (xfer_mask & ATA_MASK_PIO) >> ATA_SHIFT_PIO;
897 	if (mwdma_mask)
898 		*mwdma_mask = (xfer_mask & ATA_MASK_MWDMA) >> ATA_SHIFT_MWDMA;
899 	if (udma_mask)
900 		*udma_mask = (xfer_mask & ATA_MASK_UDMA) >> ATA_SHIFT_UDMA;
901 }
902 
903 static const struct ata_xfer_ent {
904 	int shift, bits;
905 	u8 base;
906 } ata_xfer_tbl[] = {
907 	{ ATA_SHIFT_PIO, ATA_NR_PIO_MODES, XFER_PIO_0 },
908 	{ ATA_SHIFT_MWDMA, ATA_NR_MWDMA_MODES, XFER_MW_DMA_0 },
909 	{ ATA_SHIFT_UDMA, ATA_NR_UDMA_MODES, XFER_UDMA_0 },
910 	{ -1, },
911 };
912 
913 /**
914  *	ata_xfer_mask2mode - Find matching XFER_* for the given xfer_mask
915  *	@xfer_mask: xfer_mask of interest
916  *
917  *	Return matching XFER_* value for @xfer_mask.  Only the highest
918  *	bit of @xfer_mask is considered.
919  *
920  *	LOCKING:
921  *	None.
922  *
923  *	RETURNS:
924  *	Matching XFER_* value, 0xff if no match found.
925  */
926 u8 ata_xfer_mask2mode(unsigned int xfer_mask)
927 {
928 	int highbit = fls(xfer_mask) - 1;
929 	const struct ata_xfer_ent *ent;
930 
931 	for (ent = ata_xfer_tbl; ent->shift >= 0; ent++)
932 		if (highbit >= ent->shift && highbit < ent->shift + ent->bits)
933 			return ent->base + highbit - ent->shift;
934 	return 0xff;
935 }
936 EXPORT_SYMBOL_GPL(ata_xfer_mask2mode);
937 
938 /**
939  *	ata_xfer_mode2mask - Find matching xfer_mask for XFER_*
940  *	@xfer_mode: XFER_* of interest
941  *
942  *	Return matching xfer_mask for @xfer_mode.
943  *
944  *	LOCKING:
945  *	None.
946  *
947  *	RETURNS:
948  *	Matching xfer_mask, 0 if no match found.
949  */
950 unsigned int ata_xfer_mode2mask(u8 xfer_mode)
951 {
952 	const struct ata_xfer_ent *ent;
953 
954 	for (ent = ata_xfer_tbl; ent->shift >= 0; ent++)
955 		if (xfer_mode >= ent->base && xfer_mode < ent->base + ent->bits)
956 			return ((2 << (ent->shift + xfer_mode - ent->base)) - 1)
957 				& ~((1 << ent->shift) - 1);
958 	return 0;
959 }
960 EXPORT_SYMBOL_GPL(ata_xfer_mode2mask);
961 
962 /**
963  *	ata_xfer_mode2shift - Find matching xfer_shift for XFER_*
964  *	@xfer_mode: XFER_* of interest
965  *
966  *	Return matching xfer_shift for @xfer_mode.
967  *
968  *	LOCKING:
969  *	None.
970  *
971  *	RETURNS:
972  *	Matching xfer_shift, -1 if no match found.
973  */
974 int ata_xfer_mode2shift(u8 xfer_mode)
975 {
976 	const struct ata_xfer_ent *ent;
977 
978 	for (ent = ata_xfer_tbl; ent->shift >= 0; ent++)
979 		if (xfer_mode >= ent->base && xfer_mode < ent->base + ent->bits)
980 			return ent->shift;
981 	return -1;
982 }
983 EXPORT_SYMBOL_GPL(ata_xfer_mode2shift);
984 
985 /**
986  *	ata_mode_string - convert xfer_mask to string
987  *	@xfer_mask: mask of bits supported; only highest bit counts.
988  *
989  *	Determine string which represents the highest speed
990  *	(highest bit in @modemask).
991  *
992  *	LOCKING:
993  *	None.
994  *
995  *	RETURNS:
996  *	Constant C string representing highest speed listed in
997  *	@mode_mask, or the constant C string "<n/a>".
998  */
999 const char *ata_mode_string(unsigned int xfer_mask)
1000 {
1001 	static const char * const xfer_mode_str[] = {
1002 		"PIO0",
1003 		"PIO1",
1004 		"PIO2",
1005 		"PIO3",
1006 		"PIO4",
1007 		"PIO5",
1008 		"PIO6",
1009 		"MWDMA0",
1010 		"MWDMA1",
1011 		"MWDMA2",
1012 		"MWDMA3",
1013 		"MWDMA4",
1014 		"UDMA/16",
1015 		"UDMA/25",
1016 		"UDMA/33",
1017 		"UDMA/44",
1018 		"UDMA/66",
1019 		"UDMA/100",
1020 		"UDMA/133",
1021 		"UDMA7",
1022 	};
1023 	int highbit;
1024 
1025 	highbit = fls(xfer_mask) - 1;
1026 	if (highbit >= 0 && highbit < ARRAY_SIZE(xfer_mode_str))
1027 		return xfer_mode_str[highbit];
1028 	return "<n/a>";
1029 }
1030 EXPORT_SYMBOL_GPL(ata_mode_string);
1031 
1032 const char *sata_spd_string(unsigned int spd)
1033 {
1034 	static const char * const spd_str[] = {
1035 		"1.5 Gbps",
1036 		"3.0 Gbps",
1037 		"6.0 Gbps",
1038 	};
1039 
1040 	if (spd == 0 || (spd - 1) >= ARRAY_SIZE(spd_str))
1041 		return "<unknown>";
1042 	return spd_str[spd - 1];
1043 }
1044 
1045 /**
1046  *	ata_dev_classify - determine device type based on ATA-spec signature
1047  *	@tf: ATA taskfile register set for device to be identified
1048  *
1049  *	Determine from taskfile register contents whether a device is
1050  *	ATA or ATAPI, as per "Signature and persistence" section
1051  *	of ATA/PI spec (volume 1, sect 5.14).
1052  *
1053  *	LOCKING:
1054  *	None.
1055  *
1056  *	RETURNS:
1057  *	Device type, %ATA_DEV_ATA, %ATA_DEV_ATAPI, %ATA_DEV_PMP,
1058  *	%ATA_DEV_ZAC, or %ATA_DEV_UNKNOWN the event of failure.
1059  */
1060 unsigned int ata_dev_classify(const struct ata_taskfile *tf)
1061 {
1062 	/* Apple's open source Darwin code hints that some devices only
1063 	 * put a proper signature into the LBA mid/high registers,
1064 	 * So, we only check those.  It's sufficient for uniqueness.
1065 	 *
1066 	 * ATA/ATAPI-7 (d1532v1r1: Feb. 19, 2003) specified separate
1067 	 * signatures for ATA and ATAPI devices attached on SerialATA,
1068 	 * 0x3c/0xc3 and 0x69/0x96 respectively.  However, SerialATA
1069 	 * spec has never mentioned about using different signatures
1070 	 * for ATA/ATAPI devices.  Then, Serial ATA II: Port
1071 	 * Multiplier specification began to use 0x69/0x96 to identify
1072 	 * port multpliers and 0x3c/0xc3 to identify SEMB device.
1073 	 * ATA/ATAPI-7 dropped descriptions about 0x3c/0xc3 and
1074 	 * 0x69/0x96 shortly and described them as reserved for
1075 	 * SerialATA.
1076 	 *
1077 	 * We follow the current spec and consider that 0x69/0x96
1078 	 * identifies a port multiplier and 0x3c/0xc3 a SEMB device.
1079 	 * Unfortunately, WDC WD1600JS-62MHB5 (a hard drive) reports
1080 	 * SEMB signature.  This is worked around in
1081 	 * ata_dev_read_id().
1082 	 */
1083 	if (tf->lbam == 0 && tf->lbah == 0)
1084 		return ATA_DEV_ATA;
1085 
1086 	if (tf->lbam == 0x14 && tf->lbah == 0xeb)
1087 		return ATA_DEV_ATAPI;
1088 
1089 	if (tf->lbam == 0x69 && tf->lbah == 0x96)
1090 		return ATA_DEV_PMP;
1091 
1092 	if (tf->lbam == 0x3c && tf->lbah == 0xc3)
1093 		return ATA_DEV_SEMB;
1094 
1095 	if (tf->lbam == 0xcd && tf->lbah == 0xab)
1096 		return ATA_DEV_ZAC;
1097 
1098 	return ATA_DEV_UNKNOWN;
1099 }
1100 EXPORT_SYMBOL_GPL(ata_dev_classify);
1101 
1102 /**
1103  *	ata_id_string - Convert IDENTIFY DEVICE page into string
1104  *	@id: IDENTIFY DEVICE results we will examine
1105  *	@s: string into which data is output
1106  *	@ofs: offset into identify device page
1107  *	@len: length of string to return. must be an even number.
1108  *
1109  *	The strings in the IDENTIFY DEVICE page are broken up into
1110  *	16-bit chunks.  Run through the string, and output each
1111  *	8-bit chunk linearly, regardless of platform.
1112  *
1113  *	LOCKING:
1114  *	caller.
1115  */
1116 
1117 void ata_id_string(const u16 *id, unsigned char *s,
1118 		   unsigned int ofs, unsigned int len)
1119 {
1120 	unsigned int c;
1121 
1122 	BUG_ON(len & 1);
1123 
1124 	while (len > 0) {
1125 		c = id[ofs] >> 8;
1126 		*s = c;
1127 		s++;
1128 
1129 		c = id[ofs] & 0xff;
1130 		*s = c;
1131 		s++;
1132 
1133 		ofs++;
1134 		len -= 2;
1135 	}
1136 }
1137 EXPORT_SYMBOL_GPL(ata_id_string);
1138 
1139 /**
1140  *	ata_id_c_string - Convert IDENTIFY DEVICE page into C string
1141  *	@id: IDENTIFY DEVICE results we will examine
1142  *	@s: string into which data is output
1143  *	@ofs: offset into identify device page
1144  *	@len: length of string to return. must be an odd number.
1145  *
1146  *	This function is identical to ata_id_string except that it
1147  *	trims trailing spaces and terminates the resulting string with
1148  *	null.  @len must be actual maximum length (even number) + 1.
1149  *
1150  *	LOCKING:
1151  *	caller.
1152  */
1153 void ata_id_c_string(const u16 *id, unsigned char *s,
1154 		     unsigned int ofs, unsigned int len)
1155 {
1156 	unsigned char *p;
1157 
1158 	ata_id_string(id, s, ofs, len - 1);
1159 
1160 	p = s + strnlen(s, len - 1);
1161 	while (p > s && p[-1] == ' ')
1162 		p--;
1163 	*p = '\0';
1164 }
1165 EXPORT_SYMBOL_GPL(ata_id_c_string);
1166 
1167 static u64 ata_id_n_sectors(const u16 *id)
1168 {
1169 	if (ata_id_has_lba(id)) {
1170 		if (ata_id_has_lba48(id))
1171 			return ata_id_u64(id, ATA_ID_LBA_CAPACITY_2);
1172 
1173 		return ata_id_u32(id, ATA_ID_LBA_CAPACITY);
1174 	}
1175 
1176 	if (ata_id_current_chs_valid(id))
1177 		return (u32)id[ATA_ID_CUR_CYLS] * (u32)id[ATA_ID_CUR_HEADS] *
1178 		       (u32)id[ATA_ID_CUR_SECTORS];
1179 
1180 	return (u32)id[ATA_ID_CYLS] * (u32)id[ATA_ID_HEADS] *
1181 	       (u32)id[ATA_ID_SECTORS];
1182 }
1183 
1184 u64 ata_tf_to_lba48(const struct ata_taskfile *tf)
1185 {
1186 	u64 sectors = 0;
1187 
1188 	sectors |= ((u64)(tf->hob_lbah & 0xff)) << 40;
1189 	sectors |= ((u64)(tf->hob_lbam & 0xff)) << 32;
1190 	sectors |= ((u64)(tf->hob_lbal & 0xff)) << 24;
1191 	sectors |= (tf->lbah & 0xff) << 16;
1192 	sectors |= (tf->lbam & 0xff) << 8;
1193 	sectors |= (tf->lbal & 0xff);
1194 
1195 	return sectors;
1196 }
1197 
1198 u64 ata_tf_to_lba(const struct ata_taskfile *tf)
1199 {
1200 	u64 sectors = 0;
1201 
1202 	sectors |= (tf->device & 0x0f) << 24;
1203 	sectors |= (tf->lbah & 0xff) << 16;
1204 	sectors |= (tf->lbam & 0xff) << 8;
1205 	sectors |= (tf->lbal & 0xff);
1206 
1207 	return sectors;
1208 }
1209 
1210 /**
1211  *	ata_read_native_max_address - Read native max address
1212  *	@dev: target device
1213  *	@max_sectors: out parameter for the result native max address
1214  *
1215  *	Perform an LBA48 or LBA28 native size query upon the device in
1216  *	question.
1217  *
1218  *	RETURNS:
1219  *	0 on success, -EACCES if command is aborted by the drive.
1220  *	-EIO on other errors.
1221  */
1222 static int ata_read_native_max_address(struct ata_device *dev, u64 *max_sectors)
1223 {
1224 	unsigned int err_mask;
1225 	struct ata_taskfile tf;
1226 	int lba48 = ata_id_has_lba48(dev->id);
1227 
1228 	ata_tf_init(dev, &tf);
1229 
1230 	/* always clear all address registers */
1231 	tf.flags |= ATA_TFLAG_DEVICE | ATA_TFLAG_ISADDR;
1232 
1233 	if (lba48) {
1234 		tf.command = ATA_CMD_READ_NATIVE_MAX_EXT;
1235 		tf.flags |= ATA_TFLAG_LBA48;
1236 	} else
1237 		tf.command = ATA_CMD_READ_NATIVE_MAX;
1238 
1239 	tf.protocol = ATA_PROT_NODATA;
1240 	tf.device |= ATA_LBA;
1241 
1242 	err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
1243 	if (err_mask) {
1244 		ata_dev_warn(dev,
1245 			     "failed to read native max address (err_mask=0x%x)\n",
1246 			     err_mask);
1247 		if (err_mask == AC_ERR_DEV && (tf.error & ATA_ABORTED))
1248 			return -EACCES;
1249 		return -EIO;
1250 	}
1251 
1252 	if (lba48)
1253 		*max_sectors = ata_tf_to_lba48(&tf) + 1;
1254 	else
1255 		*max_sectors = ata_tf_to_lba(&tf) + 1;
1256 	if (dev->quirks & ATA_QUIRK_HPA_SIZE)
1257 		(*max_sectors)--;
1258 	return 0;
1259 }
1260 
1261 /**
1262  *	ata_set_max_sectors - Set max sectors
1263  *	@dev: target device
1264  *	@new_sectors: new max sectors value to set for the device
1265  *
1266  *	Set max sectors of @dev to @new_sectors.
1267  *
1268  *	RETURNS:
1269  *	0 on success, -EACCES if command is aborted or denied (due to
1270  *	previous non-volatile SET_MAX) by the drive.  -EIO on other
1271  *	errors.
1272  */
1273 static int ata_set_max_sectors(struct ata_device *dev, u64 new_sectors)
1274 {
1275 	unsigned int err_mask;
1276 	struct ata_taskfile tf;
1277 	int lba48 = ata_id_has_lba48(dev->id);
1278 
1279 	new_sectors--;
1280 
1281 	ata_tf_init(dev, &tf);
1282 
1283 	tf.flags |= ATA_TFLAG_DEVICE | ATA_TFLAG_ISADDR;
1284 
1285 	if (lba48) {
1286 		tf.command = ATA_CMD_SET_MAX_EXT;
1287 		tf.flags |= ATA_TFLAG_LBA48;
1288 
1289 		tf.hob_lbal = (new_sectors >> 24) & 0xff;
1290 		tf.hob_lbam = (new_sectors >> 32) & 0xff;
1291 		tf.hob_lbah = (new_sectors >> 40) & 0xff;
1292 	} else {
1293 		tf.command = ATA_CMD_SET_MAX;
1294 
1295 		tf.device |= (new_sectors >> 24) & 0xf;
1296 	}
1297 
1298 	tf.protocol = ATA_PROT_NODATA;
1299 	tf.device |= ATA_LBA;
1300 
1301 	tf.lbal = (new_sectors >> 0) & 0xff;
1302 	tf.lbam = (new_sectors >> 8) & 0xff;
1303 	tf.lbah = (new_sectors >> 16) & 0xff;
1304 
1305 	err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
1306 	if (err_mask) {
1307 		ata_dev_warn(dev,
1308 			     "failed to set max address (err_mask=0x%x)\n",
1309 			     err_mask);
1310 		if (err_mask == AC_ERR_DEV &&
1311 		    (tf.error & (ATA_ABORTED | ATA_IDNF)))
1312 			return -EACCES;
1313 		return -EIO;
1314 	}
1315 
1316 	return 0;
1317 }
1318 
1319 /**
1320  *	ata_hpa_resize		-	Resize a device with an HPA set
1321  *	@dev: Device to resize
1322  *
1323  *	Read the size of an LBA28 or LBA48 disk with HPA features and resize
1324  *	it if required to the full size of the media. The caller must check
1325  *	the drive has the HPA feature set enabled.
1326  *
1327  *	RETURNS:
1328  *	0 on success, -errno on failure.
1329  */
1330 static int ata_hpa_resize(struct ata_device *dev)
1331 {
1332 	bool print_info = ata_dev_print_info(dev);
1333 	bool unlock_hpa = ata_ignore_hpa || dev->flags & ATA_DFLAG_UNLOCK_HPA;
1334 	u64 sectors = ata_id_n_sectors(dev->id);
1335 	u64 native_sectors;
1336 	int rc;
1337 
1338 	/* do we need to do it? */
1339 	if ((dev->class != ATA_DEV_ATA && dev->class != ATA_DEV_ZAC) ||
1340 	    !ata_id_has_lba(dev->id) || !ata_id_hpa_enabled(dev->id) ||
1341 	    (dev->quirks & ATA_QUIRK_BROKEN_HPA))
1342 		return 0;
1343 
1344 	/* read native max address */
1345 	rc = ata_read_native_max_address(dev, &native_sectors);
1346 	if (rc) {
1347 		/* If device aborted the command or HPA isn't going to
1348 		 * be unlocked, skip HPA resizing.
1349 		 */
1350 		if (rc == -EACCES || !unlock_hpa) {
1351 			ata_dev_warn(dev,
1352 				     "HPA support seems broken, skipping HPA handling\n");
1353 			dev->quirks |= ATA_QUIRK_BROKEN_HPA;
1354 
1355 			/* we can continue if device aborted the command */
1356 			if (rc == -EACCES)
1357 				rc = 0;
1358 		}
1359 
1360 		return rc;
1361 	}
1362 	dev->n_native_sectors = native_sectors;
1363 
1364 	/* nothing to do? */
1365 	if (native_sectors <= sectors || !unlock_hpa) {
1366 		if (!print_info || native_sectors == sectors)
1367 			return 0;
1368 
1369 		if (native_sectors > sectors)
1370 			ata_dev_info(dev,
1371 				"HPA detected: current %llu, native %llu\n",
1372 				(unsigned long long)sectors,
1373 				(unsigned long long)native_sectors);
1374 		else if (native_sectors < sectors)
1375 			ata_dev_warn(dev,
1376 				"native sectors (%llu) is smaller than sectors (%llu)\n",
1377 				(unsigned long long)native_sectors,
1378 				(unsigned long long)sectors);
1379 		return 0;
1380 	}
1381 
1382 	/* let's unlock HPA */
1383 	rc = ata_set_max_sectors(dev, native_sectors);
1384 	if (rc == -EACCES) {
1385 		/* if device aborted the command, skip HPA resizing */
1386 		ata_dev_warn(dev,
1387 			     "device aborted resize (%llu -> %llu), skipping HPA handling\n",
1388 			     (unsigned long long)sectors,
1389 			     (unsigned long long)native_sectors);
1390 		dev->quirks |= ATA_QUIRK_BROKEN_HPA;
1391 		return 0;
1392 	} else if (rc)
1393 		return rc;
1394 
1395 	/* re-read IDENTIFY data */
1396 	rc = ata_dev_reread_id(dev, 0);
1397 	if (rc) {
1398 		ata_dev_err(dev,
1399 			    "failed to re-read IDENTIFY data after HPA resizing\n");
1400 		return rc;
1401 	}
1402 
1403 	if (print_info) {
1404 		u64 new_sectors = ata_id_n_sectors(dev->id);
1405 		ata_dev_info(dev,
1406 			"HPA unlocked: %llu -> %llu, native %llu\n",
1407 			(unsigned long long)sectors,
1408 			(unsigned long long)new_sectors,
1409 			(unsigned long long)native_sectors);
1410 	}
1411 
1412 	return 0;
1413 }
1414 
1415 /**
1416  *	ata_dump_id - IDENTIFY DEVICE info debugging output
1417  *	@dev: device from which the information is fetched
1418  *	@id: IDENTIFY DEVICE page to dump
1419  *
1420  *	Dump selected 16-bit words from the given IDENTIFY DEVICE
1421  *	page.
1422  *
1423  *	LOCKING:
1424  *	caller.
1425  */
1426 
1427 static inline void ata_dump_id(struct ata_device *dev, const u16 *id)
1428 {
1429 	ata_dev_dbg(dev,
1430 		"49==0x%04x  53==0x%04x  63==0x%04x  64==0x%04x  75==0x%04x\n"
1431 		"80==0x%04x  81==0x%04x  82==0x%04x  83==0x%04x  84==0x%04x\n"
1432 		"88==0x%04x  93==0x%04x\n",
1433 		id[49], id[53], id[63], id[64], id[75], id[80],
1434 		id[81], id[82], id[83], id[84], id[88], id[93]);
1435 }
1436 
1437 /**
1438  *	ata_id_xfermask - Compute xfermask from the given IDENTIFY data
1439  *	@id: IDENTIFY data to compute xfer mask from
1440  *
1441  *	Compute the xfermask for this device. This is not as trivial
1442  *	as it seems if we must consider early devices correctly.
1443  *
1444  *	FIXME: pre IDE drive timing (do we care ?).
1445  *
1446  *	LOCKING:
1447  *	None.
1448  *
1449  *	RETURNS:
1450  *	Computed xfermask
1451  */
1452 unsigned int ata_id_xfermask(const u16 *id)
1453 {
1454 	unsigned int pio_mask, mwdma_mask, udma_mask;
1455 
1456 	/* Usual case. Word 53 indicates word 64 is valid */
1457 	if (id[ATA_ID_FIELD_VALID] & (1 << 1)) {
1458 		pio_mask = id[ATA_ID_PIO_MODES] & 0x03;
1459 		pio_mask <<= 3;
1460 		pio_mask |= 0x7;
1461 	} else {
1462 		/* If word 64 isn't valid then Word 51 high byte holds
1463 		 * the PIO timing number for the maximum. Turn it into
1464 		 * a mask.
1465 		 */
1466 		u8 mode = (id[ATA_ID_OLD_PIO_MODES] >> 8) & 0xFF;
1467 		if (mode < 5)	/* Valid PIO range */
1468 			pio_mask = (2 << mode) - 1;
1469 		else
1470 			pio_mask = 1;
1471 
1472 		/* But wait.. there's more. Design your standards by
1473 		 * committee and you too can get a free iordy field to
1474 		 * process. However it is the speeds not the modes that
1475 		 * are supported... Note drivers using the timing API
1476 		 * will get this right anyway
1477 		 */
1478 	}
1479 
1480 	mwdma_mask = id[ATA_ID_MWDMA_MODES] & 0x07;
1481 
1482 	if (ata_id_is_cfa(id)) {
1483 		/*
1484 		 *	Process compact flash extended modes
1485 		 */
1486 		int pio = (id[ATA_ID_CFA_MODES] >> 0) & 0x7;
1487 		int dma = (id[ATA_ID_CFA_MODES] >> 3) & 0x7;
1488 
1489 		if (pio)
1490 			pio_mask |= (1 << 5);
1491 		if (pio > 1)
1492 			pio_mask |= (1 << 6);
1493 		if (dma)
1494 			mwdma_mask |= (1 << 3);
1495 		if (dma > 1)
1496 			mwdma_mask |= (1 << 4);
1497 	}
1498 
1499 	udma_mask = 0;
1500 	if (id[ATA_ID_FIELD_VALID] & (1 << 2))
1501 		udma_mask = id[ATA_ID_UDMA_MODES] & 0xff;
1502 
1503 	return ata_pack_xfermask(pio_mask, mwdma_mask, udma_mask);
1504 }
1505 EXPORT_SYMBOL_GPL(ata_id_xfermask);
1506 
1507 static void ata_qc_complete_internal(struct ata_queued_cmd *qc)
1508 {
1509 	struct completion *waiting = qc->private_data;
1510 
1511 	complete(waiting);
1512 }
1513 
1514 /**
1515  *	ata_exec_internal - execute libata internal command
1516  *	@dev: Device to which the command is sent
1517  *	@tf: Taskfile registers for the command and the result
1518  *	@cdb: CDB for packet command
1519  *	@dma_dir: Data transfer direction of the command
1520  *	@buf: Data buffer of the command
1521  *	@buflen: Length of data buffer
1522  *	@timeout: Timeout in msecs (0 for default)
1523  *
1524  *	Executes libata internal command with timeout. @tf contains
1525  *	the command on entry and the result on return. Timeout and error
1526  *	conditions are reported via the return value. No recovery action
1527  *	is taken after a command times out. It is the caller's duty to
1528  *	clean up after timeout.
1529  *
1530  *	LOCKING:
1531  *	None.  Should be called with kernel context, might sleep.
1532  *
1533  *	RETURNS:
1534  *	Zero on success, AC_ERR_* mask on failure
1535  */
1536 unsigned int ata_exec_internal(struct ata_device *dev, struct ata_taskfile *tf,
1537 			       const u8 *cdb, enum dma_data_direction dma_dir,
1538 			       void *buf, unsigned int buflen,
1539 			       unsigned int timeout)
1540 {
1541 	struct ata_link *link = dev->link;
1542 	struct ata_port *ap = link->ap;
1543 	u8 command = tf->command;
1544 	struct ata_queued_cmd *qc;
1545 	struct scatterlist sgl;
1546 	unsigned int preempted_tag;
1547 	u32 preempted_sactive;
1548 	u64 preempted_qc_active;
1549 	int preempted_nr_active_links;
1550 	bool auto_timeout = false;
1551 	DECLARE_COMPLETION_ONSTACK(wait);
1552 	unsigned long flags;
1553 	unsigned int err_mask;
1554 	int rc;
1555 
1556 	if (WARN_ON(dma_dir != DMA_NONE && !buf))
1557 		return AC_ERR_INVALID;
1558 
1559 	spin_lock_irqsave(ap->lock, flags);
1560 
1561 	/* No internal command while frozen */
1562 	if (ata_port_is_frozen(ap)) {
1563 		spin_unlock_irqrestore(ap->lock, flags);
1564 		return AC_ERR_SYSTEM;
1565 	}
1566 
1567 	/* Initialize internal qc */
1568 	qc = __ata_qc_from_tag(ap, ATA_TAG_INTERNAL);
1569 
1570 	qc->tag = ATA_TAG_INTERNAL;
1571 	qc->hw_tag = 0;
1572 	qc->scsicmd = NULL;
1573 	qc->ap = ap;
1574 	qc->dev = dev;
1575 	ata_qc_reinit(qc);
1576 
1577 	preempted_tag = link->active_tag;
1578 	preempted_sactive = link->sactive;
1579 	preempted_qc_active = ap->qc_active;
1580 	preempted_nr_active_links = ap->nr_active_links;
1581 	link->active_tag = ATA_TAG_POISON;
1582 	link->sactive = 0;
1583 	ap->qc_active = 0;
1584 	ap->nr_active_links = 0;
1585 
1586 	/* Prepare and issue qc */
1587 	qc->tf = *tf;
1588 	if (cdb)
1589 		memcpy(qc->cdb, cdb, ATAPI_CDB_LEN);
1590 
1591 	/* Some SATA bridges need us to indicate data xfer direction */
1592 	if (tf->protocol == ATAPI_PROT_DMA && (dev->flags & ATA_DFLAG_DMADIR) &&
1593 	    dma_dir == DMA_FROM_DEVICE)
1594 		qc->tf.feature |= ATAPI_DMADIR;
1595 
1596 	qc->flags |= ATA_QCFLAG_RESULT_TF;
1597 	qc->dma_dir = dma_dir;
1598 	if (dma_dir != DMA_NONE) {
1599 		sg_init_one(&sgl, buf, buflen);
1600 		ata_sg_init(qc, &sgl, 1);
1601 		qc->nbytes = buflen;
1602 	}
1603 
1604 	qc->private_data = &wait;
1605 	qc->complete_fn = ata_qc_complete_internal;
1606 
1607 	ata_qc_issue(qc);
1608 
1609 	spin_unlock_irqrestore(ap->lock, flags);
1610 
1611 	if (!timeout) {
1612 		if (ata_probe_timeout) {
1613 			timeout = ata_probe_timeout * 1000;
1614 		} else {
1615 			timeout = ata_internal_cmd_timeout(dev, command);
1616 			auto_timeout = true;
1617 		}
1618 	}
1619 
1620 	ata_eh_release(ap);
1621 
1622 	rc = wait_for_completion_timeout(&wait, msecs_to_jiffies(timeout));
1623 
1624 	ata_eh_acquire(ap);
1625 
1626 	ata_sff_flush_pio_task(ap);
1627 
1628 	if (!rc) {
1629 		/*
1630 		 * We are racing with irq here. If we lose, the following test
1631 		 * prevents us from completing the qc twice. If we win, the port
1632 		 * is frozen and will be cleaned up by ->post_internal_cmd().
1633 		 */
1634 		spin_lock_irqsave(ap->lock, flags);
1635 		if (qc->flags & ATA_QCFLAG_ACTIVE) {
1636 			qc->err_mask |= AC_ERR_TIMEOUT;
1637 			ata_port_freeze(ap);
1638 			ata_dev_warn(dev, "qc timeout after %u msecs (cmd 0x%x)\n",
1639 				     timeout, command);
1640 		}
1641 		spin_unlock_irqrestore(ap->lock, flags);
1642 	}
1643 
1644 	if (ap->ops->post_internal_cmd)
1645 		ap->ops->post_internal_cmd(qc);
1646 
1647 	/* Perform minimal error analysis */
1648 	if (qc->flags & ATA_QCFLAG_EH) {
1649 		if (qc->result_tf.status & (ATA_ERR | ATA_DF))
1650 			qc->err_mask |= AC_ERR_DEV;
1651 
1652 		if (!qc->err_mask)
1653 			qc->err_mask |= AC_ERR_OTHER;
1654 
1655 		if (qc->err_mask & ~AC_ERR_OTHER)
1656 			qc->err_mask &= ~AC_ERR_OTHER;
1657 	} else if (qc->tf.command == ATA_CMD_REQ_SENSE_DATA) {
1658 		qc->result_tf.status |= ATA_SENSE;
1659 	}
1660 
1661 	/* Finish up */
1662 	spin_lock_irqsave(ap->lock, flags);
1663 
1664 	*tf = qc->result_tf;
1665 	err_mask = qc->err_mask;
1666 
1667 	ata_qc_free(qc);
1668 	link->active_tag = preempted_tag;
1669 	link->sactive = preempted_sactive;
1670 	ap->qc_active = preempted_qc_active;
1671 	ap->nr_active_links = preempted_nr_active_links;
1672 
1673 	spin_unlock_irqrestore(ap->lock, flags);
1674 
1675 	if ((err_mask & AC_ERR_TIMEOUT) && auto_timeout)
1676 		ata_internal_cmd_timed_out(dev, command);
1677 
1678 	return err_mask;
1679 }
1680 
1681 /**
1682  *	ata_pio_need_iordy	-	check if iordy needed
1683  *	@adev: ATA device
1684  *
1685  *	Check if the current speed of the device requires IORDY. Used
1686  *	by various controllers for chip configuration.
1687  */
1688 unsigned int ata_pio_need_iordy(const struct ata_device *adev)
1689 {
1690 	/* Don't set IORDY if we're preparing for reset.  IORDY may
1691 	 * lead to controller lock up on certain controllers if the
1692 	 * port is not occupied.  See bko#11703 for details.
1693 	 */
1694 	if (adev->link->ap->pflags & ATA_PFLAG_RESETTING)
1695 		return 0;
1696 	/* Controller doesn't support IORDY.  Probably a pointless
1697 	 * check as the caller should know this.
1698 	 */
1699 	if (adev->link->ap->flags & ATA_FLAG_NO_IORDY)
1700 		return 0;
1701 	/* CF spec. r4.1 Table 22 says no iordy on PIO5 and PIO6.  */
1702 	if (ata_id_is_cfa(adev->id)
1703 	    && (adev->pio_mode == XFER_PIO_5 || adev->pio_mode == XFER_PIO_6))
1704 		return 0;
1705 	/* PIO3 and higher it is mandatory */
1706 	if (adev->pio_mode > XFER_PIO_2)
1707 		return 1;
1708 	/* We turn it on when possible */
1709 	if (ata_id_has_iordy(adev->id))
1710 		return 1;
1711 	return 0;
1712 }
1713 EXPORT_SYMBOL_GPL(ata_pio_need_iordy);
1714 
1715 /**
1716  *	ata_pio_mask_no_iordy	-	Return the non IORDY mask
1717  *	@adev: ATA device
1718  *
1719  *	Compute the highest mode possible if we are not using iordy. Return
1720  *	-1 if no iordy mode is available.
1721  */
1722 static u32 ata_pio_mask_no_iordy(const struct ata_device *adev)
1723 {
1724 	/* If we have no drive specific rule, then PIO 2 is non IORDY */
1725 	if (adev->id[ATA_ID_FIELD_VALID] & 2) {	/* EIDE */
1726 		u16 pio = adev->id[ATA_ID_EIDE_PIO];
1727 		/* Is the speed faster than the drive allows non IORDY ? */
1728 		if (pio) {
1729 			/* This is cycle times not frequency - watch the logic! */
1730 			if (pio > 240)	/* PIO2 is 240nS per cycle */
1731 				return 3 << ATA_SHIFT_PIO;
1732 			return 7 << ATA_SHIFT_PIO;
1733 		}
1734 	}
1735 	return 3 << ATA_SHIFT_PIO;
1736 }
1737 
1738 /**
1739  *	ata_do_dev_read_id		-	default ID read method
1740  *	@dev: device
1741  *	@tf: proposed taskfile
1742  *	@id: data buffer
1743  *
1744  *	Issue the identify taskfile and hand back the buffer containing
1745  *	identify data. For some RAID controllers and for pre ATA devices
1746  *	this function is wrapped or replaced by the driver
1747  */
1748 unsigned int ata_do_dev_read_id(struct ata_device *dev,
1749 				struct ata_taskfile *tf, __le16 *id)
1750 {
1751 	return ata_exec_internal(dev, tf, NULL, DMA_FROM_DEVICE,
1752 				     id, sizeof(id[0]) * ATA_ID_WORDS, 0);
1753 }
1754 EXPORT_SYMBOL_GPL(ata_do_dev_read_id);
1755 
1756 /**
1757  *	ata_dev_read_id - Read ID data from the specified device
1758  *	@dev: target device
1759  *	@p_class: pointer to class of the target device (may be changed)
1760  *	@flags: ATA_READID_* flags
1761  *	@id: buffer to read IDENTIFY data into
1762  *
1763  *	Read ID data from the specified device.  ATA_CMD_ID_ATA is
1764  *	performed on ATA devices and ATA_CMD_ID_ATAPI on ATAPI
1765  *	devices.  This function also issues ATA_CMD_INIT_DEV_PARAMS
1766  *	for pre-ATA4 drives.
1767  *
1768  *	FIXME: ATA_CMD_ID_ATA is optional for early drives and right
1769  *	now we abort if we hit that case.
1770  *
1771  *	LOCKING:
1772  *	Kernel thread context (may sleep)
1773  *
1774  *	RETURNS:
1775  *	0 on success, -errno otherwise.
1776  */
1777 int ata_dev_read_id(struct ata_device *dev, unsigned int *p_class,
1778 		    unsigned int flags, u16 *id)
1779 {
1780 	struct ata_port *ap = dev->link->ap;
1781 	unsigned int class = *p_class;
1782 	struct ata_taskfile tf;
1783 	unsigned int err_mask = 0;
1784 	const char *reason;
1785 	bool is_semb = class == ATA_DEV_SEMB;
1786 	int may_fallback = 1, tried_spinup = 0;
1787 	int rc;
1788 
1789 retry:
1790 	ata_tf_init(dev, &tf);
1791 
1792 	switch (class) {
1793 	case ATA_DEV_SEMB:
1794 		class = ATA_DEV_ATA;	/* some hard drives report SEMB sig */
1795 		fallthrough;
1796 	case ATA_DEV_ATA:
1797 	case ATA_DEV_ZAC:
1798 		tf.command = ATA_CMD_ID_ATA;
1799 		break;
1800 	case ATA_DEV_ATAPI:
1801 		tf.command = ATA_CMD_ID_ATAPI;
1802 		break;
1803 	default:
1804 		rc = -ENODEV;
1805 		reason = "unsupported class";
1806 		goto err_out;
1807 	}
1808 
1809 	tf.protocol = ATA_PROT_PIO;
1810 
1811 	/* Some devices choke if TF registers contain garbage.  Make
1812 	 * sure those are properly initialized.
1813 	 */
1814 	tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
1815 
1816 	/* Device presence detection is unreliable on some
1817 	 * controllers.  Always poll IDENTIFY if available.
1818 	 */
1819 	tf.flags |= ATA_TFLAG_POLLING;
1820 
1821 	if (ap->ops->read_id)
1822 		err_mask = ap->ops->read_id(dev, &tf, (__le16 *)id);
1823 	else
1824 		err_mask = ata_do_dev_read_id(dev, &tf, (__le16 *)id);
1825 
1826 	if (err_mask) {
1827 		if (err_mask & AC_ERR_NODEV_HINT) {
1828 			ata_dev_dbg(dev, "NODEV after polling detection\n");
1829 			return -ENOENT;
1830 		}
1831 
1832 		if (is_semb) {
1833 			ata_dev_info(dev,
1834 		     "IDENTIFY failed on device w/ SEMB sig, disabled\n");
1835 			/* SEMB is not supported yet */
1836 			*p_class = ATA_DEV_SEMB_UNSUP;
1837 			return 0;
1838 		}
1839 
1840 		if ((err_mask == AC_ERR_DEV) && (tf.error & ATA_ABORTED)) {
1841 			/* Device or controller might have reported
1842 			 * the wrong device class.  Give a shot at the
1843 			 * other IDENTIFY if the current one is
1844 			 * aborted by the device.
1845 			 */
1846 			if (may_fallback) {
1847 				may_fallback = 0;
1848 
1849 				if (class == ATA_DEV_ATA)
1850 					class = ATA_DEV_ATAPI;
1851 				else
1852 					class = ATA_DEV_ATA;
1853 				goto retry;
1854 			}
1855 
1856 			/* Control reaches here iff the device aborted
1857 			 * both flavors of IDENTIFYs which happens
1858 			 * sometimes with phantom devices.
1859 			 */
1860 			ata_dev_dbg(dev,
1861 				    "both IDENTIFYs aborted, assuming NODEV\n");
1862 			return -ENOENT;
1863 		}
1864 
1865 		rc = -EIO;
1866 		reason = "I/O error";
1867 		goto err_out;
1868 	}
1869 
1870 	if (dev->quirks & ATA_QUIRK_DUMP_ID) {
1871 		ata_dev_info(dev, "dumping IDENTIFY data, "
1872 			    "class=%d may_fallback=%d tried_spinup=%d\n",
1873 			    class, may_fallback, tried_spinup);
1874 		print_hex_dump(KERN_INFO, "", DUMP_PREFIX_OFFSET,
1875 			       16, 2, id, ATA_ID_WORDS * sizeof(*id), true);
1876 	}
1877 
1878 	/* Falling back doesn't make sense if ID data was read
1879 	 * successfully at least once.
1880 	 */
1881 	may_fallback = 0;
1882 
1883 	swap_buf_le16(id, ATA_ID_WORDS);
1884 
1885 	/* sanity check */
1886 	rc = -EINVAL;
1887 	reason = "device reports invalid type";
1888 
1889 	if (class == ATA_DEV_ATA || class == ATA_DEV_ZAC) {
1890 		if (!ata_id_is_ata(id) && !ata_id_is_cfa(id))
1891 			goto err_out;
1892 		if (ap->host->flags & ATA_HOST_IGNORE_ATA &&
1893 							ata_id_is_ata(id)) {
1894 			ata_dev_dbg(dev,
1895 				"host indicates ignore ATA devices, ignored\n");
1896 			return -ENOENT;
1897 		}
1898 	} else {
1899 		if (ata_id_is_ata(id))
1900 			goto err_out;
1901 	}
1902 
1903 	if (!tried_spinup && (id[2] == 0x37c8 || id[2] == 0x738c)) {
1904 		tried_spinup = 1;
1905 		/*
1906 		 * Drive powered-up in standby mode, and requires a specific
1907 		 * SET_FEATURES spin-up subcommand before it will accept
1908 		 * anything other than the original IDENTIFY command.
1909 		 */
1910 		err_mask = ata_dev_set_feature(dev, SETFEATURES_SPINUP, 0);
1911 		if (err_mask && id[2] != 0x738c) {
1912 			rc = -EIO;
1913 			reason = "SPINUP failed";
1914 			goto err_out;
1915 		}
1916 		/*
1917 		 * If the drive initially returned incomplete IDENTIFY info,
1918 		 * we now must reissue the IDENTIFY command.
1919 		 */
1920 		if (id[2] == 0x37c8)
1921 			goto retry;
1922 	}
1923 
1924 	if ((flags & ATA_READID_POSTRESET) &&
1925 	    (class == ATA_DEV_ATA || class == ATA_DEV_ZAC)) {
1926 		/*
1927 		 * The exact sequence expected by certain pre-ATA4 drives is:
1928 		 * SRST RESET
1929 		 * IDENTIFY (optional in early ATA)
1930 		 * INITIALIZE DEVICE PARAMETERS (later IDE and ATA)
1931 		 * anything else..
1932 		 * Some drives were very specific about that exact sequence.
1933 		 *
1934 		 * Note that ATA4 says lba is mandatory so the second check
1935 		 * should never trigger.
1936 		 */
1937 		if (ata_id_major_version(id) < 4 || !ata_id_has_lba(id)) {
1938 			err_mask = ata_dev_init_params(dev, id[3], id[6]);
1939 			if (err_mask) {
1940 				rc = -EIO;
1941 				reason = "INIT_DEV_PARAMS failed";
1942 				goto err_out;
1943 			}
1944 
1945 			/* current CHS translation info (id[53-58]) might be
1946 			 * changed. reread the identify device info.
1947 			 */
1948 			flags &= ~ATA_READID_POSTRESET;
1949 			goto retry;
1950 		}
1951 	}
1952 
1953 	*p_class = class;
1954 
1955 	return 0;
1956 
1957  err_out:
1958 	ata_dev_warn(dev, "failed to IDENTIFY (%s, err_mask=0x%x)\n",
1959 		     reason, err_mask);
1960 	return rc;
1961 }
1962 
1963 bool ata_dev_power_init_tf(struct ata_device *dev, struct ata_taskfile *tf,
1964 			   bool set_active)
1965 {
1966 	/* Only applies to ATA and ZAC devices */
1967 	if (dev->class != ATA_DEV_ATA && dev->class != ATA_DEV_ZAC)
1968 		return false;
1969 
1970 	ata_tf_init(dev, tf);
1971 	tf->flags |= ATA_TFLAG_DEVICE | ATA_TFLAG_ISADDR;
1972 	tf->protocol = ATA_PROT_NODATA;
1973 
1974 	if (set_active) {
1975 		/* VERIFY for 1 sector at lba=0 */
1976 		tf->command = ATA_CMD_VERIFY;
1977 		tf->nsect = 1;
1978 		if (dev->flags & ATA_DFLAG_LBA) {
1979 			tf->flags |= ATA_TFLAG_LBA;
1980 			tf->device |= ATA_LBA;
1981 		} else {
1982 			/* CHS */
1983 			tf->lbal = 0x1; /* sect */
1984 		}
1985 	} else {
1986 		tf->command = ATA_CMD_STANDBYNOW1;
1987 	}
1988 
1989 	return true;
1990 }
1991 
1992 static bool ata_dev_power_is_active(struct ata_device *dev)
1993 {
1994 	struct ata_taskfile tf;
1995 	unsigned int err_mask;
1996 
1997 	ata_tf_init(dev, &tf);
1998 	tf.flags |= ATA_TFLAG_DEVICE | ATA_TFLAG_ISADDR;
1999 	tf.protocol = ATA_PROT_NODATA;
2000 	tf.command = ATA_CMD_CHK_POWER;
2001 
2002 	err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
2003 	if (err_mask) {
2004 		ata_dev_err(dev, "Check power mode failed (err_mask=0x%x)\n",
2005 			    err_mask);
2006 		/*
2007 		 * Assume we are in standby mode so that we always force a
2008 		 * spinup in ata_dev_power_set_active().
2009 		 */
2010 		return false;
2011 	}
2012 
2013 	ata_dev_dbg(dev, "Power mode: 0x%02x\n", tf.nsect);
2014 
2015 	/* Active or idle */
2016 	return tf.nsect == 0xff;
2017 }
2018 
2019 /**
2020  *	ata_dev_power_set_standby - Set a device power mode to standby
2021  *	@dev: target device
2022  *
2023  *	Issue a STANDBY IMMEDIATE command to set a device power mode to standby.
2024  *	For an HDD device, this spins down the disks.
2025  *
2026  *	LOCKING:
2027  *	Kernel thread context (may sleep).
2028  */
2029 void ata_dev_power_set_standby(struct ata_device *dev)
2030 {
2031 	unsigned long ap_flags = dev->link->ap->flags;
2032 	struct ata_taskfile tf;
2033 	unsigned int err_mask;
2034 
2035 	/* If the device is already sleeping or in standby, do nothing. */
2036 	if ((dev->flags & ATA_DFLAG_SLEEPING) ||
2037 	    !ata_dev_power_is_active(dev))
2038 		return;
2039 
2040 	/*
2041 	 * Some odd clown BIOSes issue spindown on power off (ACPI S4 or S5)
2042 	 * causing some drives to spin up and down again. For these, do nothing
2043 	 * if we are being called on shutdown.
2044 	 */
2045 	if ((ap_flags & ATA_FLAG_NO_POWEROFF_SPINDOWN) &&
2046 	    system_state == SYSTEM_POWER_OFF)
2047 		return;
2048 
2049 	if ((ap_flags & ATA_FLAG_NO_HIBERNATE_SPINDOWN) &&
2050 	    system_entering_hibernation())
2051 		return;
2052 
2053 	/* Issue STANDBY IMMEDIATE command only if supported by the device */
2054 	if (!ata_dev_power_init_tf(dev, &tf, false))
2055 		return;
2056 
2057 	ata_dev_notice(dev, "Entering standby power mode\n");
2058 
2059 	err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
2060 	if (err_mask)
2061 		ata_dev_err(dev, "STANDBY IMMEDIATE failed (err_mask=0x%x)\n",
2062 			    err_mask);
2063 }
2064 
2065 /**
2066  *	ata_dev_power_set_active -  Set a device power mode to active
2067  *	@dev: target device
2068  *
2069  *	Issue a VERIFY command to enter to ensure that the device is in the
2070  *	active power mode. For a spun-down HDD (standby or idle power mode),
2071  *	the VERIFY command will complete after the disk spins up.
2072  *
2073  *	LOCKING:
2074  *	Kernel thread context (may sleep).
2075  */
2076 void ata_dev_power_set_active(struct ata_device *dev)
2077 {
2078 	struct ata_taskfile tf;
2079 	unsigned int err_mask;
2080 
2081 	/*
2082 	 * Issue READ VERIFY SECTORS command for 1 sector at lba=0 only
2083 	 * if supported by the device.
2084 	 */
2085 	if (!ata_dev_power_init_tf(dev, &tf, true))
2086 		return;
2087 
2088 	/*
2089 	 * Check the device power state & condition and force a spinup with
2090 	 * VERIFY command only if the drive is not already ACTIVE or IDLE.
2091 	 */
2092 	if (ata_dev_power_is_active(dev))
2093 		return;
2094 
2095 	ata_dev_notice(dev, "Entering active power mode\n");
2096 
2097 	err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
2098 	if (err_mask)
2099 		ata_dev_err(dev, "VERIFY failed (err_mask=0x%x)\n",
2100 			    err_mask);
2101 }
2102 
2103 /**
2104  *	ata_read_log_page - read a specific log page
2105  *	@dev: target device
2106  *	@log: log to read
2107  *	@page: page to read
2108  *	@buf: buffer to store read page
2109  *	@sectors: number of sectors to read
2110  *
2111  *	Read log page using READ_LOG_EXT command.
2112  *
2113  *	LOCKING:
2114  *	Kernel thread context (may sleep).
2115  *
2116  *	RETURNS:
2117  *	0 on success, AC_ERR_* mask otherwise.
2118  */
2119 unsigned int ata_read_log_page(struct ata_device *dev, u8 log,
2120 			       u8 page, void *buf, unsigned int sectors)
2121 {
2122 	unsigned long ap_flags = dev->link->ap->flags;
2123 	struct ata_taskfile tf;
2124 	unsigned int err_mask;
2125 	bool dma = false;
2126 
2127 	ata_dev_dbg(dev, "read log page - log 0x%x, page 0x%x\n", log, page);
2128 
2129 	/*
2130 	 * Return error without actually issuing the command on controllers
2131 	 * which e.g. lockup on a read log page.
2132 	 */
2133 	if (ap_flags & ATA_FLAG_NO_LOG_PAGE)
2134 		return AC_ERR_DEV;
2135 
2136 retry:
2137 	ata_tf_init(dev, &tf);
2138 	if (ata_dma_enabled(dev) && ata_id_has_read_log_dma_ext(dev->id) &&
2139 	    !(dev->quirks & ATA_QUIRK_NO_DMA_LOG)) {
2140 		tf.command = ATA_CMD_READ_LOG_DMA_EXT;
2141 		tf.protocol = ATA_PROT_DMA;
2142 		dma = true;
2143 	} else {
2144 		tf.command = ATA_CMD_READ_LOG_EXT;
2145 		tf.protocol = ATA_PROT_PIO;
2146 		dma = false;
2147 	}
2148 	tf.lbal = log;
2149 	tf.lbam = page;
2150 	tf.nsect = sectors;
2151 	tf.hob_nsect = sectors >> 8;
2152 	tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_LBA48 | ATA_TFLAG_DEVICE;
2153 
2154 	err_mask = ata_exec_internal(dev, &tf, NULL, DMA_FROM_DEVICE,
2155 				     buf, sectors * ATA_SECT_SIZE, 0);
2156 
2157 	if (err_mask) {
2158 		if (dma) {
2159 			dev->quirks |= ATA_QUIRK_NO_DMA_LOG;
2160 			if (!ata_port_is_frozen(dev->link->ap))
2161 				goto retry;
2162 		}
2163 		ata_dev_err(dev,
2164 			    "Read log 0x%02x page 0x%02x failed, Emask 0x%x\n",
2165 			    (unsigned int)log, (unsigned int)page, err_mask);
2166 	}
2167 
2168 	return err_mask;
2169 }
2170 
2171 static inline void ata_clear_log_directory(struct ata_device *dev)
2172 {
2173 	memset(dev->gp_log_dir, 0, ATA_SECT_SIZE);
2174 }
2175 
2176 static int ata_read_log_directory(struct ata_device *dev)
2177 {
2178 	u16 version;
2179 
2180 	/* If the log page is already cached, do nothing. */
2181 	version = get_unaligned_le16(&dev->gp_log_dir[0]);
2182 	if (version == 0x0001)
2183 		return 0;
2184 
2185 	if (ata_read_log_page(dev, ATA_LOG_DIRECTORY, 0, dev->gp_log_dir, 1)) {
2186 		ata_clear_log_directory(dev);
2187 		return -EIO;
2188 	}
2189 
2190 	version = get_unaligned_le16(&dev->gp_log_dir[0]);
2191 	if (version != 0x0001)
2192 		ata_dev_warn_once(dev,
2193 				  "Invalid log directory version 0x%04x\n",
2194 				  version);
2195 
2196 	return 0;
2197 }
2198 
2199 static int ata_log_supported(struct ata_device *dev, u8 log)
2200 {
2201 	if (dev->quirks & ATA_QUIRK_NO_LOG_DIR)
2202 		return 0;
2203 
2204 	if (ata_read_log_directory(dev))
2205 		return 0;
2206 
2207 	return get_unaligned_le16(&dev->gp_log_dir[log * 2]);
2208 }
2209 
2210 static bool ata_identify_page_supported(struct ata_device *dev, u8 page)
2211 {
2212 	unsigned int err, i;
2213 
2214 	if (dev->quirks & ATA_QUIRK_NO_ID_DEV_LOG)
2215 		return false;
2216 
2217 	if (!ata_log_supported(dev, ATA_LOG_IDENTIFY_DEVICE)) {
2218 		/*
2219 		 * IDENTIFY DEVICE data log is defined as mandatory starting
2220 		 * with ACS-3 (ATA version 10). Warn about the missing log
2221 		 * for drives which implement this ATA level or above.
2222 		 */
2223 		if (ata_id_major_version(dev->id) >= 10)
2224 			ata_dev_warn(dev,
2225 				"ATA Identify Device Log not supported\n");
2226 		dev->quirks |= ATA_QUIRK_NO_ID_DEV_LOG;
2227 		return false;
2228 	}
2229 
2230 	/*
2231 	 * Read IDENTIFY DEVICE data log, page 0, to figure out if the page is
2232 	 * supported.
2233 	 */
2234 	err = ata_read_log_page(dev, ATA_LOG_IDENTIFY_DEVICE, 0,
2235 				dev->sector_buf, 1);
2236 	if (err)
2237 		return false;
2238 
2239 	for (i = 0; i < dev->sector_buf[8]; i++) {
2240 		if (dev->sector_buf[9 + i] == page)
2241 			return true;
2242 	}
2243 
2244 	return false;
2245 }
2246 
2247 static int ata_do_link_spd_quirk(struct ata_device *dev)
2248 {
2249 	struct ata_link *plink = ata_dev_phys_link(dev);
2250 	u32 target, target_limit;
2251 
2252 	if (!sata_scr_valid(plink))
2253 		return 0;
2254 
2255 	if (dev->quirks & ATA_QUIRK_1_5_GBPS)
2256 		target = 1;
2257 	else
2258 		return 0;
2259 
2260 	target_limit = (1 << target) - 1;
2261 
2262 	/* if already on stricter limit, no need to push further */
2263 	if (plink->sata_spd_limit <= target_limit)
2264 		return 0;
2265 
2266 	plink->sata_spd_limit = target_limit;
2267 
2268 	/* Request another EH round by returning -EAGAIN if link is
2269 	 * going faster than the target speed.  Forward progress is
2270 	 * guaranteed by setting sata_spd_limit to target_limit above.
2271 	 */
2272 	if (plink->sata_spd > target) {
2273 		ata_dev_info(dev, "applying link speed limit quirk to %s\n",
2274 			     sata_spd_string(target));
2275 		return -EAGAIN;
2276 	}
2277 	return 0;
2278 }
2279 
2280 static inline bool ata_dev_knobble(struct ata_device *dev)
2281 {
2282 	struct ata_port *ap = dev->link->ap;
2283 
2284 	if (ata_dev_quirks(dev) & ATA_QUIRK_BRIDGE_OK)
2285 		return false;
2286 
2287 	return ((ap->cbl == ATA_CBL_SATA) && (!ata_id_is_sata(dev->id)));
2288 }
2289 
2290 static void ata_dev_config_ncq_send_recv(struct ata_device *dev)
2291 {
2292 	unsigned int err_mask;
2293 
2294 	if (!ata_log_supported(dev, ATA_LOG_NCQ_SEND_RECV)) {
2295 		ata_dev_warn(dev, "NCQ Send/Recv Log not supported\n");
2296 		return;
2297 	}
2298 	err_mask = ata_read_log_page(dev, ATA_LOG_NCQ_SEND_RECV,
2299 				     0, dev->sector_buf, 1);
2300 	if (!err_mask) {
2301 		u8 *cmds = dev->ncq_send_recv_cmds;
2302 
2303 		dev->flags |= ATA_DFLAG_NCQ_SEND_RECV;
2304 		memcpy(cmds, dev->sector_buf, ATA_LOG_NCQ_SEND_RECV_SIZE);
2305 
2306 		if (dev->quirks & ATA_QUIRK_NO_NCQ_TRIM) {
2307 			ata_dev_dbg(dev, "disabling queued TRIM support\n");
2308 			cmds[ATA_LOG_NCQ_SEND_RECV_DSM_OFFSET] &=
2309 				~ATA_LOG_NCQ_SEND_RECV_DSM_TRIM;
2310 		}
2311 	}
2312 }
2313 
2314 static void ata_dev_config_ncq_non_data(struct ata_device *dev)
2315 {
2316 	unsigned int err_mask;
2317 
2318 	if (!ata_log_supported(dev, ATA_LOG_NCQ_NON_DATA)) {
2319 		ata_dev_warn(dev,
2320 			     "NCQ Non-Data Log not supported\n");
2321 		return;
2322 	}
2323 	err_mask = ata_read_log_page(dev, ATA_LOG_NCQ_NON_DATA,
2324 				     0, dev->sector_buf, 1);
2325 	if (!err_mask)
2326 		memcpy(dev->ncq_non_data_cmds, dev->sector_buf,
2327 		       ATA_LOG_NCQ_NON_DATA_SIZE);
2328 }
2329 
2330 static void ata_dev_config_ncq_prio(struct ata_device *dev)
2331 {
2332 	unsigned int err_mask;
2333 
2334 	if (!ata_identify_page_supported(dev, ATA_LOG_SATA_SETTINGS))
2335 		return;
2336 
2337 	err_mask = ata_read_log_page(dev,
2338 				     ATA_LOG_IDENTIFY_DEVICE,
2339 				     ATA_LOG_SATA_SETTINGS,
2340 				     dev->sector_buf, 1);
2341 	if (err_mask)
2342 		goto not_supported;
2343 
2344 	if (!(dev->sector_buf[ATA_LOG_NCQ_PRIO_OFFSET] & BIT(3)))
2345 		goto not_supported;
2346 
2347 	dev->flags |= ATA_DFLAG_NCQ_PRIO;
2348 
2349 	return;
2350 
2351 not_supported:
2352 	dev->flags &= ~ATA_DFLAG_NCQ_PRIO_ENABLED;
2353 	dev->flags &= ~ATA_DFLAG_NCQ_PRIO;
2354 }
2355 
2356 static bool ata_dev_check_adapter(struct ata_device *dev,
2357 				  unsigned short vendor_id)
2358 {
2359 	struct pci_dev *pcidev = NULL;
2360 	struct device *parent_dev = NULL;
2361 
2362 	for (parent_dev = dev->tdev.parent; parent_dev != NULL;
2363 	     parent_dev = parent_dev->parent) {
2364 		if (dev_is_pci(parent_dev)) {
2365 			pcidev = to_pci_dev(parent_dev);
2366 			if (pcidev->vendor == vendor_id)
2367 				return true;
2368 			break;
2369 		}
2370 	}
2371 
2372 	return false;
2373 }
2374 
2375 bool ata_adapter_is_online(struct ata_port *ap)
2376 {
2377 	struct device *dev;
2378 
2379 	if (!ap || !ap->host)
2380 		return false;
2381 
2382 	dev = ap->host->dev;
2383 	if (!dev)
2384 		return false;
2385 
2386 	if (dev_is_pci(dev) &&
2387 	    pci_channel_offline(to_pci_dev(dev)))
2388 		return false;
2389 
2390 	return true;
2391 }
2392 
2393 static int ata_dev_config_ncq(struct ata_device *dev,
2394 			       char *desc, size_t desc_sz)
2395 {
2396 	struct ata_port *ap = dev->link->ap;
2397 	int hdepth = 0, ddepth = ata_id_queue_depth(dev->id);
2398 	unsigned int err_mask;
2399 	char *aa_desc = "";
2400 
2401 	if (!ata_id_has_ncq(dev->id)) {
2402 		desc[0] = '\0';
2403 		return 0;
2404 	}
2405 	if (!IS_ENABLED(CONFIG_SATA_HOST))
2406 		return 0;
2407 	if (dev->quirks & ATA_QUIRK_NONCQ) {
2408 		snprintf(desc, desc_sz, "NCQ (not used)");
2409 		return 0;
2410 	}
2411 
2412 	if (dev->quirks & ATA_QUIRK_NO_NCQ_ON_ATI &&
2413 	    ata_dev_check_adapter(dev, PCI_VENDOR_ID_ATI)) {
2414 		snprintf(desc, desc_sz, "NCQ (not used)");
2415 		return 0;
2416 	}
2417 
2418 	if (ap->flags & ATA_FLAG_NCQ) {
2419 		hdepth = min(ap->scsi_host->can_queue, ATA_MAX_QUEUE);
2420 		dev->flags |= ATA_DFLAG_NCQ;
2421 	}
2422 
2423 	if (!(dev->quirks & ATA_QUIRK_BROKEN_FPDMA_AA) &&
2424 		(ap->flags & ATA_FLAG_FPDMA_AA) &&
2425 		ata_id_has_fpdma_aa(dev->id)) {
2426 		err_mask = ata_dev_set_feature(dev, SETFEATURES_SATA_ENABLE,
2427 			SATA_FPDMA_AA);
2428 		if (err_mask) {
2429 			ata_dev_err(dev,
2430 				    "failed to enable AA (error_mask=0x%x)\n",
2431 				    err_mask);
2432 			if (err_mask != AC_ERR_DEV) {
2433 				dev->quirks |= ATA_QUIRK_BROKEN_FPDMA_AA;
2434 				return -EIO;
2435 			}
2436 		} else
2437 			aa_desc = ", AA";
2438 	}
2439 
2440 	if (hdepth >= ddepth)
2441 		snprintf(desc, desc_sz, "NCQ (depth %d)%s", ddepth, aa_desc);
2442 	else
2443 		snprintf(desc, desc_sz, "NCQ (depth %d/%d)%s", hdepth,
2444 			ddepth, aa_desc);
2445 
2446 	if ((ap->flags & ATA_FLAG_FPDMA_AUX)) {
2447 		if (ata_id_has_ncq_send_and_recv(dev->id))
2448 			ata_dev_config_ncq_send_recv(dev);
2449 		if (ata_id_has_ncq_non_data(dev->id))
2450 			ata_dev_config_ncq_non_data(dev);
2451 		if (ata_id_has_ncq_prio(dev->id))
2452 			ata_dev_config_ncq_prio(dev);
2453 	}
2454 
2455 	return 0;
2456 }
2457 
2458 static void ata_dev_config_sense_reporting(struct ata_device *dev)
2459 {
2460 	unsigned int err_mask;
2461 
2462 	if (!ata_id_has_sense_reporting(dev->id))
2463 		return;
2464 
2465 	if (ata_id_sense_reporting_enabled(dev->id))
2466 		return;
2467 
2468 	err_mask = ata_dev_set_feature(dev, SETFEATURE_SENSE_DATA, 0x1);
2469 	if (err_mask) {
2470 		ata_dev_dbg(dev,
2471 			    "failed to enable Sense Data Reporting, Emask 0x%x\n",
2472 			    err_mask);
2473 	}
2474 }
2475 
2476 static void ata_dev_config_zac(struct ata_device *dev)
2477 {
2478 	unsigned int err_mask;
2479 	u8 *identify_buf = dev->sector_buf;
2480 
2481 	dev->zac_zones_optimal_open = U32_MAX;
2482 	dev->zac_zones_optimal_nonseq = U32_MAX;
2483 	dev->zac_zones_max_open = U32_MAX;
2484 
2485 	if (!ata_dev_is_zac(dev))
2486 		return;
2487 
2488 	if (!ata_identify_page_supported(dev, ATA_LOG_ZONED_INFORMATION)) {
2489 		ata_dev_warn(dev,
2490 			     "ATA Zoned Information Log not supported\n");
2491 		return;
2492 	}
2493 
2494 	/*
2495 	 * Read IDENTIFY DEVICE data log, page 9 (Zoned-device information)
2496 	 */
2497 	err_mask = ata_read_log_page(dev, ATA_LOG_IDENTIFY_DEVICE,
2498 				     ATA_LOG_ZONED_INFORMATION,
2499 				     identify_buf, 1);
2500 	if (!err_mask) {
2501 		u64 zoned_cap, opt_open, opt_nonseq, max_open;
2502 
2503 		zoned_cap = get_unaligned_le64(&identify_buf[8]);
2504 		if ((zoned_cap >> 63))
2505 			dev->zac_zoned_cap = (zoned_cap & 1);
2506 		opt_open = get_unaligned_le64(&identify_buf[24]);
2507 		if ((opt_open >> 63))
2508 			dev->zac_zones_optimal_open = (u32)opt_open;
2509 		opt_nonseq = get_unaligned_le64(&identify_buf[32]);
2510 		if ((opt_nonseq >> 63))
2511 			dev->zac_zones_optimal_nonseq = (u32)opt_nonseq;
2512 		max_open = get_unaligned_le64(&identify_buf[40]);
2513 		if ((max_open >> 63))
2514 			dev->zac_zones_max_open = (u32)max_open;
2515 	}
2516 }
2517 
2518 static void ata_dev_config_trusted(struct ata_device *dev)
2519 {
2520 	u64 trusted_cap;
2521 	unsigned int err;
2522 
2523 	if (!ata_id_has_trusted(dev->id))
2524 		return;
2525 
2526 	if (!ata_identify_page_supported(dev, ATA_LOG_SECURITY)) {
2527 		ata_dev_warn(dev,
2528 			     "Security Log not supported\n");
2529 		return;
2530 	}
2531 
2532 	err = ata_read_log_page(dev, ATA_LOG_IDENTIFY_DEVICE, ATA_LOG_SECURITY,
2533 				dev->sector_buf, 1);
2534 	if (err)
2535 		return;
2536 
2537 	trusted_cap = get_unaligned_le64(&dev->sector_buf[40]);
2538 	if (!(trusted_cap & (1ULL << 63))) {
2539 		ata_dev_dbg(dev,
2540 			    "Trusted Computing capability qword not valid!\n");
2541 		return;
2542 	}
2543 
2544 	if (trusted_cap & (1 << 0))
2545 		dev->flags |= ATA_DFLAG_TRUSTED;
2546 }
2547 
2548 static void ata_dev_cleanup_cdl_resources(struct ata_device *dev)
2549 {
2550 	kfree(dev->cdl);
2551 	dev->cdl = NULL;
2552 }
2553 
2554 static int ata_dev_init_cdl_resources(struct ata_device *dev)
2555 {
2556 	struct ata_cdl *cdl = dev->cdl;
2557 	unsigned int err_mask;
2558 
2559 	if (!cdl) {
2560 		cdl = kzalloc(sizeof(*cdl), GFP_KERNEL);
2561 		if (!cdl)
2562 			return -ENOMEM;
2563 		dev->cdl = cdl;
2564 	}
2565 
2566 	err_mask = ata_read_log_page(dev, ATA_LOG_CDL, 0, cdl->desc_log_buf,
2567 				     ATA_LOG_CDL_SIZE / ATA_SECT_SIZE);
2568 	if (err_mask) {
2569 		ata_dev_warn(dev, "Read Command Duration Limits log failed\n");
2570 		ata_dev_cleanup_cdl_resources(dev);
2571 		return -EIO;
2572 	}
2573 
2574 	return 0;
2575 }
2576 
2577 static void ata_dev_config_cdl(struct ata_device *dev)
2578 {
2579 	unsigned int err_mask;
2580 	bool cdl_enabled;
2581 	u64 val;
2582 	int ret;
2583 
2584 	if (ata_id_major_version(dev->id) < 11)
2585 		goto not_supported;
2586 
2587 	if (!ata_log_supported(dev, ATA_LOG_IDENTIFY_DEVICE) ||
2588 	    !ata_identify_page_supported(dev, ATA_LOG_SUPPORTED_CAPABILITIES) ||
2589 	    !ata_identify_page_supported(dev, ATA_LOG_CURRENT_SETTINGS))
2590 		goto not_supported;
2591 
2592 	err_mask = ata_read_log_page(dev, ATA_LOG_IDENTIFY_DEVICE,
2593 				     ATA_LOG_SUPPORTED_CAPABILITIES,
2594 				     dev->sector_buf, 1);
2595 	if (err_mask)
2596 		goto not_supported;
2597 
2598 	/* Check Command Duration Limit Supported bits */
2599 	val = get_unaligned_le64(&dev->sector_buf[168]);
2600 	if (!(val & BIT_ULL(63)) || !(val & BIT_ULL(0)))
2601 		goto not_supported;
2602 
2603 	/* Warn the user if command duration guideline is not supported */
2604 	if (!(val & BIT_ULL(1)))
2605 		ata_dev_warn(dev,
2606 			"Command duration guideline is not supported\n");
2607 
2608 	/*
2609 	 * We must have support for the sense data for successful NCQ commands
2610 	 * log indicated by the successful NCQ command sense data supported bit.
2611 	 */
2612 	val = get_unaligned_le64(&dev->sector_buf[8]);
2613 	if (!(val & BIT_ULL(63)) || !(val & BIT_ULL(47))) {
2614 		ata_dev_warn(dev,
2615 			"CDL supported but Successful NCQ Command Sense Data is not supported\n");
2616 		goto not_supported;
2617 	}
2618 
2619 	/* Without NCQ autosense, the successful NCQ commands log is useless. */
2620 	if (!ata_id_has_ncq_autosense(dev->id)) {
2621 		ata_dev_warn(dev,
2622 			"CDL supported but NCQ autosense is not supported\n");
2623 		goto not_supported;
2624 	}
2625 
2626 	/*
2627 	 * If CDL is marked as enabled, make sure the feature is enabled too.
2628 	 * Conversely, if CDL is disabled, make sure the feature is turned off.
2629 	 */
2630 	err_mask = ata_read_log_page(dev, ATA_LOG_IDENTIFY_DEVICE,
2631 				     ATA_LOG_CURRENT_SETTINGS,
2632 				     dev->sector_buf, 1);
2633 	if (err_mask)
2634 		goto not_supported;
2635 
2636 	val = get_unaligned_le64(&dev->sector_buf[8]);
2637 	cdl_enabled = val & BIT_ULL(63) && val & BIT_ULL(21);
2638 	if (dev->flags & ATA_DFLAG_CDL_ENABLED) {
2639 		if (!cdl_enabled) {
2640 			/* Enable CDL on the device */
2641 			err_mask = ata_dev_set_feature(dev, SETFEATURES_CDL, 1);
2642 			if (err_mask) {
2643 				ata_dev_err(dev,
2644 					    "Enable CDL feature failed\n");
2645 				goto not_supported;
2646 			}
2647 		}
2648 	} else {
2649 		if (cdl_enabled) {
2650 			/* Disable CDL on the device */
2651 			err_mask = ata_dev_set_feature(dev, SETFEATURES_CDL, 0);
2652 			if (err_mask) {
2653 				ata_dev_err(dev,
2654 					    "Disable CDL feature failed\n");
2655 				goto not_supported;
2656 			}
2657 		}
2658 	}
2659 
2660 	/*
2661 	 * While CDL itself has to be enabled using sysfs, CDL requires that
2662 	 * sense data for successful NCQ commands is enabled to work properly.
2663 	 * Just like ata_dev_config_sense_reporting(), enable it unconditionally
2664 	 * if supported.
2665 	 */
2666 	if (!(val & BIT_ULL(63)) || !(val & BIT_ULL(18))) {
2667 		err_mask = ata_dev_set_feature(dev,
2668 					SETFEATURE_SENSE_DATA_SUCC_NCQ, 0x1);
2669 		if (err_mask) {
2670 			ata_dev_warn(dev,
2671 				     "failed to enable Sense Data for successful NCQ commands, Emask 0x%x\n",
2672 				     err_mask);
2673 			goto not_supported;
2674 		}
2675 	}
2676 
2677 	/* CDL is supported: allocate and initialize needed resources. */
2678 	ret = ata_dev_init_cdl_resources(dev);
2679 	if (ret) {
2680 		ata_dev_warn(dev, "Initialize CDL resources failed\n");
2681 		goto not_supported;
2682 	}
2683 
2684 	dev->flags |= ATA_DFLAG_CDL;
2685 
2686 	return;
2687 
2688 not_supported:
2689 	dev->flags &= ~(ATA_DFLAG_CDL | ATA_DFLAG_CDL_ENABLED);
2690 	ata_dev_cleanup_cdl_resources(dev);
2691 }
2692 
2693 static int ata_dev_config_lba(struct ata_device *dev)
2694 {
2695 	const u16 *id = dev->id;
2696 	const char *lba_desc;
2697 	char ncq_desc[32];
2698 	int ret;
2699 
2700 	dev->flags |= ATA_DFLAG_LBA;
2701 
2702 	if (ata_id_has_lba48(id)) {
2703 		lba_desc = "LBA48";
2704 		dev->flags |= ATA_DFLAG_LBA48;
2705 		if (dev->n_sectors >= (1UL << 28) &&
2706 		    ata_id_has_flush_ext(id))
2707 			dev->flags |= ATA_DFLAG_FLUSH_EXT;
2708 	} else {
2709 		lba_desc = "LBA";
2710 	}
2711 
2712 	/* config NCQ */
2713 	ret = ata_dev_config_ncq(dev, ncq_desc, sizeof(ncq_desc));
2714 
2715 	/* print device info to dmesg */
2716 	if (ata_dev_print_info(dev))
2717 		ata_dev_info(dev,
2718 			     "%llu sectors, multi %u: %s %s\n",
2719 			     (unsigned long long)dev->n_sectors,
2720 			     dev->multi_count, lba_desc, ncq_desc);
2721 
2722 	return ret;
2723 }
2724 
2725 static void ata_dev_config_chs(struct ata_device *dev)
2726 {
2727 	const u16 *id = dev->id;
2728 
2729 	if (ata_id_current_chs_valid(id)) {
2730 		/* Current CHS translation is valid. */
2731 		dev->cylinders = id[54];
2732 		dev->heads     = id[55];
2733 		dev->sectors   = id[56];
2734 	} else {
2735 		/* Default translation */
2736 		dev->cylinders	= id[1];
2737 		dev->heads	= id[3];
2738 		dev->sectors	= id[6];
2739 	}
2740 
2741 	/* print device info to dmesg */
2742 	if (ata_dev_print_info(dev))
2743 		ata_dev_info(dev,
2744 			     "%llu sectors, multi %u, CHS %u/%u/%u\n",
2745 			     (unsigned long long)dev->n_sectors,
2746 			     dev->multi_count, dev->cylinders,
2747 			     dev->heads, dev->sectors);
2748 }
2749 
2750 static void ata_dev_config_fua(struct ata_device *dev)
2751 {
2752 	/* Ignore FUA support if its use is disabled globally */
2753 	if (!libata_fua)
2754 		goto nofua;
2755 
2756 	/* Ignore devices without support for WRITE DMA FUA EXT */
2757 	if (!(dev->flags & ATA_DFLAG_LBA48) || !ata_id_has_fua(dev->id))
2758 		goto nofua;
2759 
2760 	/* Ignore known bad devices and devices that lack NCQ support */
2761 	if (!ata_ncq_supported(dev) || (dev->quirks & ATA_QUIRK_NO_FUA))
2762 		goto nofua;
2763 
2764 	dev->flags |= ATA_DFLAG_FUA;
2765 
2766 	return;
2767 
2768 nofua:
2769 	dev->flags &= ~ATA_DFLAG_FUA;
2770 }
2771 
2772 static void ata_dev_config_devslp(struct ata_device *dev)
2773 {
2774 	u8 *sata_setting = dev->sector_buf;
2775 	unsigned int err_mask;
2776 	int i, j;
2777 
2778 	/*
2779 	 * Check device sleep capability. Get DevSlp timing variables
2780 	 * from SATA Settings page of Identify Device Data Log.
2781 	 */
2782 	if (!ata_id_has_devslp(dev->id) ||
2783 	    !ata_identify_page_supported(dev, ATA_LOG_SATA_SETTINGS))
2784 		return;
2785 
2786 	err_mask = ata_read_log_page(dev,
2787 				     ATA_LOG_IDENTIFY_DEVICE,
2788 				     ATA_LOG_SATA_SETTINGS,
2789 				     sata_setting, 1);
2790 	if (err_mask)
2791 		return;
2792 
2793 	dev->flags |= ATA_DFLAG_DEVSLP;
2794 	for (i = 0; i < ATA_LOG_DEVSLP_SIZE; i++) {
2795 		j = ATA_LOG_DEVSLP_OFFSET + i;
2796 		dev->devslp_timing[i] = sata_setting[j];
2797 	}
2798 }
2799 
2800 static void ata_dev_config_cpr(struct ata_device *dev)
2801 {
2802 	unsigned int err_mask;
2803 	size_t buf_len;
2804 	int i, nr_cpr = 0;
2805 	struct ata_cpr_log *cpr_log = NULL;
2806 	u8 *desc, *buf = NULL;
2807 
2808 	if (ata_id_major_version(dev->id) < 11)
2809 		goto out;
2810 
2811 	buf_len = ata_log_supported(dev, ATA_LOG_CONCURRENT_POSITIONING_RANGES);
2812 	if (buf_len == 0)
2813 		goto out;
2814 
2815 	/*
2816 	 * Read the concurrent positioning ranges log (0x47). We can have at
2817 	 * most 255 32B range descriptors plus a 64B header. This log varies in
2818 	 * size, so use the size reported in the GPL directory. Reading beyond
2819 	 * the supported length will result in an error.
2820 	 */
2821 	buf_len <<= 9;
2822 	buf = kzalloc(buf_len, GFP_KERNEL);
2823 	if (!buf)
2824 		goto out;
2825 
2826 	err_mask = ata_read_log_page(dev, ATA_LOG_CONCURRENT_POSITIONING_RANGES,
2827 				     0, buf, buf_len >> 9);
2828 	if (err_mask)
2829 		goto out;
2830 
2831 	nr_cpr = buf[0];
2832 	if (!nr_cpr)
2833 		goto out;
2834 
2835 	cpr_log = kzalloc(struct_size(cpr_log, cpr, nr_cpr), GFP_KERNEL);
2836 	if (!cpr_log)
2837 		goto out;
2838 
2839 	cpr_log->nr_cpr = nr_cpr;
2840 	desc = &buf[64];
2841 	for (i = 0; i < nr_cpr; i++, desc += 32) {
2842 		cpr_log->cpr[i].num = desc[0];
2843 		cpr_log->cpr[i].num_storage_elements = desc[1];
2844 		cpr_log->cpr[i].start_lba = get_unaligned_le64(&desc[8]);
2845 		cpr_log->cpr[i].num_lbas = get_unaligned_le64(&desc[16]);
2846 	}
2847 
2848 out:
2849 	swap(dev->cpr_log, cpr_log);
2850 	kfree(cpr_log);
2851 	kfree(buf);
2852 }
2853 
2854 /*
2855  * Configure features related to link power management.
2856  */
2857 static void ata_dev_config_lpm(struct ata_device *dev)
2858 {
2859 	struct ata_port *ap = dev->link->ap;
2860 	unsigned int err_mask;
2861 
2862 	if (ap->flags & ATA_FLAG_NO_LPM) {
2863 		/*
2864 		 * When the port does not support LPM, we cannot support it on
2865 		 * the device either.
2866 		 */
2867 		dev->quirks |= ATA_QUIRK_NOLPM;
2868 	} else {
2869 		/*
2870 		 * Some WD SATA-1 drives have issues with LPM, turn on NOLPM for
2871 		 * them.
2872 		 */
2873 		if ((dev->quirks & ATA_QUIRK_WD_BROKEN_LPM) &&
2874 		    (dev->id[ATA_ID_SATA_CAPABILITY] & 0xe) == 0x2)
2875 			dev->quirks |= ATA_QUIRK_NOLPM;
2876 
2877 		/* ATI specific quirk */
2878 		if ((dev->quirks & ATA_QUIRK_NO_LPM_ON_ATI) &&
2879 		    ata_dev_check_adapter(dev, PCI_VENDOR_ID_ATI))
2880 			dev->quirks |= ATA_QUIRK_NOLPM;
2881 	}
2882 
2883 	if (dev->quirks & ATA_QUIRK_NOLPM &&
2884 	    ap->target_lpm_policy != ATA_LPM_MAX_POWER) {
2885 		ata_dev_warn(dev, "LPM support broken, forcing max_power\n");
2886 		ap->target_lpm_policy = ATA_LPM_MAX_POWER;
2887 	}
2888 
2889 	/*
2890 	 * Device Initiated Power Management (DIPM) is normally disabled by
2891 	 * default on a device. However, DIPM may have been enabled and that
2892 	 * setting kept even after COMRESET because of the Software Settings
2893 	 * Preservation feature. So if the port does not support DIPM and the
2894 	 * device does, disable DIPM on the device.
2895 	 */
2896 	if (ap->flags & ATA_FLAG_NO_DIPM && ata_id_has_dipm(dev->id)) {
2897 		err_mask = ata_dev_set_feature(dev,
2898 					SETFEATURES_SATA_DISABLE, SATA_DIPM);
2899 		if (err_mask && err_mask != AC_ERR_DEV)
2900 			ata_dev_err(dev, "Disable DIPM failed, Emask 0x%x\n",
2901 				    err_mask);
2902 	}
2903 }
2904 
2905 static void ata_dev_print_features(struct ata_device *dev)
2906 {
2907 	if (!(dev->flags & ATA_DFLAG_FEATURES_MASK) && !dev->cpr_log &&
2908 	    !ata_id_has_hipm(dev->id) && !ata_id_has_dipm(dev->id))
2909 		return;
2910 
2911 	ata_dev_info(dev,
2912 		     "Features:%s%s%s%s%s%s%s%s%s%s\n",
2913 		     dev->flags & ATA_DFLAG_FUA ? " FUA" : "",
2914 		     dev->flags & ATA_DFLAG_TRUSTED ? " Trust" : "",
2915 		     dev->flags & ATA_DFLAG_DA ? " Dev-Attention" : "",
2916 		     dev->flags & ATA_DFLAG_DEVSLP ? " Dev-Sleep" : "",
2917 		     ata_id_has_hipm(dev->id) ? " HIPM" : "",
2918 		     ata_id_has_dipm(dev->id) ? " DIPM" : "",
2919 		     dev->flags & ATA_DFLAG_NCQ_SEND_RECV ? " NCQ-sndrcv" : "",
2920 		     dev->flags & ATA_DFLAG_NCQ_PRIO ? " NCQ-prio" : "",
2921 		     dev->flags & ATA_DFLAG_CDL ? " CDL" : "",
2922 		     dev->cpr_log ? " CPR" : "");
2923 }
2924 
2925 /**
2926  *	ata_dev_configure - Configure the specified ATA/ATAPI device
2927  *	@dev: Target device to configure
2928  *
2929  *	Configure @dev according to @dev->id.  Generic and low-level
2930  *	driver specific fixups are also applied.
2931  *
2932  *	LOCKING:
2933  *	Kernel thread context (may sleep)
2934  *
2935  *	RETURNS:
2936  *	0 on success, -errno otherwise
2937  */
2938 int ata_dev_configure(struct ata_device *dev)
2939 {
2940 	struct ata_port *ap = dev->link->ap;
2941 	bool print_info = ata_dev_print_info(dev);
2942 	const u16 *id = dev->id;
2943 	unsigned int xfer_mask;
2944 	unsigned int err_mask;
2945 	char revbuf[7];		/* XYZ-99\0 */
2946 	char fwrevbuf[ATA_ID_FW_REV_LEN+1];
2947 	char modelbuf[ATA_ID_PROD_LEN+1];
2948 	int rc;
2949 
2950 	if (!ata_dev_enabled(dev)) {
2951 		ata_dev_dbg(dev, "no device\n");
2952 		return 0;
2953 	}
2954 
2955 	/* Clear the general purpose log directory cache. */
2956 	ata_clear_log_directory(dev);
2957 
2958 	/* Set quirks */
2959 	dev->quirks |= ata_dev_quirks(dev);
2960 	ata_force_quirks(dev);
2961 
2962 	if (dev->quirks & ATA_QUIRK_DISABLE) {
2963 		ata_dev_info(dev, "unsupported device, disabling\n");
2964 		ata_dev_disable(dev);
2965 		return 0;
2966 	}
2967 
2968 	if ((!atapi_enabled || (ap->flags & ATA_FLAG_NO_ATAPI)) &&
2969 	    dev->class == ATA_DEV_ATAPI) {
2970 		ata_dev_warn(dev, "WARNING: ATAPI is %s, device ignored\n",
2971 			     atapi_enabled ? "not supported with this driver"
2972 			     : "disabled");
2973 		ata_dev_disable(dev);
2974 		return 0;
2975 	}
2976 
2977 	rc = ata_do_link_spd_quirk(dev);
2978 	if (rc)
2979 		return rc;
2980 
2981 	/* let ACPI work its magic */
2982 	rc = ata_acpi_on_devcfg(dev);
2983 	if (rc)
2984 		return rc;
2985 
2986 	/* massage HPA, do it early as it might change IDENTIFY data */
2987 	rc = ata_hpa_resize(dev);
2988 	if (rc)
2989 		return rc;
2990 
2991 	/* print device capabilities */
2992 	ata_dev_dbg(dev,
2993 		    "%s: cfg 49:%04x 82:%04x 83:%04x 84:%04x "
2994 		    "85:%04x 86:%04x 87:%04x 88:%04x\n",
2995 		    __func__,
2996 		    id[49], id[82], id[83], id[84],
2997 		    id[85], id[86], id[87], id[88]);
2998 
2999 	/* initialize to-be-configured parameters */
3000 	dev->flags &= ~ATA_DFLAG_CFG_MASK;
3001 	dev->max_sectors = 0;
3002 	dev->cdb_len = 0;
3003 	dev->n_sectors = 0;
3004 	dev->cylinders = 0;
3005 	dev->heads = 0;
3006 	dev->sectors = 0;
3007 	dev->multi_count = 0;
3008 
3009 	/*
3010 	 * common ATA, ATAPI feature tests
3011 	 */
3012 
3013 	/* find max transfer mode; for printk only */
3014 	xfer_mask = ata_id_xfermask(id);
3015 
3016 	ata_dump_id(dev, id);
3017 
3018 	/* SCSI only uses 4-char revisions, dump full 8 chars from ATA */
3019 	ata_id_c_string(dev->id, fwrevbuf, ATA_ID_FW_REV,
3020 			sizeof(fwrevbuf));
3021 
3022 	ata_id_c_string(dev->id, modelbuf, ATA_ID_PROD,
3023 			sizeof(modelbuf));
3024 
3025 	/* ATA-specific feature tests */
3026 	if (dev->class == ATA_DEV_ATA || dev->class == ATA_DEV_ZAC) {
3027 		if (ata_id_is_cfa(id)) {
3028 			/* CPRM may make this media unusable */
3029 			if (id[ATA_ID_CFA_KEY_MGMT] & 1)
3030 				ata_dev_warn(dev,
3031 	"supports DRM functions and may not be fully accessible\n");
3032 			snprintf(revbuf, 7, "CFA");
3033 		} else {
3034 			snprintf(revbuf, 7, "ATA-%d", ata_id_major_version(id));
3035 			/* Warn the user if the device has TPM extensions */
3036 			if (ata_id_has_tpm(id))
3037 				ata_dev_warn(dev,
3038 	"supports DRM functions and may not be fully accessible\n");
3039 		}
3040 
3041 		dev->n_sectors = ata_id_n_sectors(id);
3042 		if (ata_id_is_locked(id)) {
3043 			/*
3044 			 * If Security locked, set capacity to zero to prevent
3045 			 * any I/O, e.g. partition scanning, as any I/O to a
3046 			 * locked drive will result in user visible errors.
3047 			 */
3048 			ata_dev_info(dev,
3049 				"Security locked, setting capacity to zero\n");
3050 			dev->n_sectors = 0;
3051 		}
3052 
3053 		/* get current R/W Multiple count setting */
3054 		if ((dev->id[47] >> 8) == 0x80 && (dev->id[59] & 0x100)) {
3055 			unsigned int max = dev->id[47] & 0xff;
3056 			unsigned int cnt = dev->id[59] & 0xff;
3057 			/* only recognize/allow powers of two here */
3058 			if (is_power_of_2(max) && is_power_of_2(cnt))
3059 				if (cnt <= max)
3060 					dev->multi_count = cnt;
3061 		}
3062 
3063 		/* print device info to dmesg */
3064 		if (print_info)
3065 			ata_dev_info(dev, "%s: %s, %s, max %s\n",
3066 				     revbuf, modelbuf, fwrevbuf,
3067 				     ata_mode_string(xfer_mask));
3068 
3069 		if (ata_id_has_lba(id)) {
3070 			rc = ata_dev_config_lba(dev);
3071 			if (rc)
3072 				return rc;
3073 		} else {
3074 			ata_dev_config_chs(dev);
3075 		}
3076 
3077 		ata_dev_config_lpm(dev);
3078 		ata_dev_config_fua(dev);
3079 		ata_dev_config_devslp(dev);
3080 		ata_dev_config_sense_reporting(dev);
3081 		ata_dev_config_zac(dev);
3082 		ata_dev_config_trusted(dev);
3083 		ata_dev_config_cpr(dev);
3084 		ata_dev_config_cdl(dev);
3085 		dev->cdb_len = 32;
3086 
3087 		if (print_info)
3088 			ata_dev_print_features(dev);
3089 	}
3090 
3091 	/* ATAPI-specific feature tests */
3092 	else if (dev->class == ATA_DEV_ATAPI) {
3093 		const char *cdb_intr_string = "";
3094 		const char *atapi_an_string = "";
3095 		const char *dma_dir_string = "";
3096 		u32 sntf;
3097 
3098 		rc = atapi_cdb_len(id);
3099 		if ((rc < 12) || (rc > ATAPI_CDB_LEN)) {
3100 			ata_dev_warn(dev, "unsupported CDB len %d\n", rc);
3101 			rc = -EINVAL;
3102 			goto err_out_nosup;
3103 		}
3104 		dev->cdb_len = (unsigned int) rc;
3105 
3106 		/* Enable ATAPI AN if both the host and device have
3107 		 * the support.  If PMP is attached, SNTF is required
3108 		 * to enable ATAPI AN to discern between PHY status
3109 		 * changed notifications and ATAPI ANs.
3110 		 */
3111 		if (atapi_an &&
3112 		    (ap->flags & ATA_FLAG_AN) && ata_id_has_atapi_AN(id) &&
3113 		    (!sata_pmp_attached(ap) ||
3114 		     sata_scr_read(&ap->link, SCR_NOTIFICATION, &sntf) == 0)) {
3115 			/* issue SET feature command to turn this on */
3116 			err_mask = ata_dev_set_feature(dev,
3117 					SETFEATURES_SATA_ENABLE, SATA_AN);
3118 			if (err_mask)
3119 				ata_dev_err(dev,
3120 					    "failed to enable ATAPI AN (err_mask=0x%x)\n",
3121 					    err_mask);
3122 			else {
3123 				dev->flags |= ATA_DFLAG_AN;
3124 				atapi_an_string = ", ATAPI AN";
3125 			}
3126 		}
3127 
3128 		if (ata_id_cdb_intr(dev->id)) {
3129 			dev->flags |= ATA_DFLAG_CDB_INTR;
3130 			cdb_intr_string = ", CDB intr";
3131 		}
3132 
3133 		if (atapi_dmadir || (dev->quirks & ATA_QUIRK_ATAPI_DMADIR) ||
3134 		    atapi_id_dmadir(dev->id)) {
3135 			dev->flags |= ATA_DFLAG_DMADIR;
3136 			dma_dir_string = ", DMADIR";
3137 		}
3138 
3139 		if (ata_id_has_da(dev->id)) {
3140 			dev->flags |= ATA_DFLAG_DA;
3141 			zpodd_init(dev);
3142 		}
3143 
3144 		/* print device info to dmesg */
3145 		if (print_info)
3146 			ata_dev_info(dev,
3147 				     "ATAPI: %s, %s, max %s%s%s%s\n",
3148 				     modelbuf, fwrevbuf,
3149 				     ata_mode_string(xfer_mask),
3150 				     cdb_intr_string, atapi_an_string,
3151 				     dma_dir_string);
3152 
3153 		ata_dev_config_lpm(dev);
3154 
3155 		if (print_info)
3156 			ata_dev_print_features(dev);
3157 	}
3158 
3159 	/* determine max_sectors */
3160 	dev->max_sectors = ATA_MAX_SECTORS;
3161 	if (dev->flags & ATA_DFLAG_LBA48)
3162 		dev->max_sectors = ATA_MAX_SECTORS_LBA48;
3163 
3164 	/* Limit PATA drive on SATA cable bridge transfers to udma5,
3165 	   200 sectors */
3166 	if (ata_dev_knobble(dev)) {
3167 		if (print_info)
3168 			ata_dev_info(dev, "applying bridge limits\n");
3169 		dev->udma_mask &= ATA_UDMA5;
3170 		dev->max_sectors = ATA_MAX_SECTORS;
3171 	}
3172 
3173 	if ((dev->class == ATA_DEV_ATAPI) &&
3174 	    (atapi_command_packet_set(id) == TYPE_TAPE)) {
3175 		dev->max_sectors = ATA_MAX_SECTORS_TAPE;
3176 		dev->quirks |= ATA_QUIRK_STUCK_ERR;
3177 	}
3178 
3179 	if (dev->quirks & ATA_QUIRK_MAX_SEC)
3180 		dev->max_sectors = min_t(unsigned int, dev->max_sectors,
3181 					 ata_dev_get_quirk_value(dev,
3182 							 ATA_QUIRK_MAX_SEC));
3183 
3184 	if (dev->quirks & ATA_QUIRK_MAX_SEC_LBA48)
3185 		dev->max_sectors = ATA_MAX_SECTORS_LBA48;
3186 
3187 	if (ap->ops->dev_config)
3188 		ap->ops->dev_config(dev);
3189 
3190 	if (dev->quirks & ATA_QUIRK_DIAGNOSTIC) {
3191 		/* Let the user know. We don't want to disallow opens for
3192 		   rescue purposes, or in case the vendor is just a blithering
3193 		   idiot. Do this after the dev_config call as some controllers
3194 		   with buggy firmware may want to avoid reporting false device
3195 		   bugs */
3196 
3197 		if (print_info) {
3198 			ata_dev_warn(dev,
3199 "Drive reports diagnostics failure. This may indicate a drive\n");
3200 			ata_dev_warn(dev,
3201 "fault or invalid emulation. Contact drive vendor for information.\n");
3202 		}
3203 	}
3204 
3205 	if ((dev->quirks & ATA_QUIRK_FIRMWARE_WARN) && print_info) {
3206 		ata_dev_warn(dev, "WARNING: device requires firmware update to be fully functional\n");
3207 		ata_dev_warn(dev, "         contact the vendor or visit http://ata.wiki.kernel.org\n");
3208 	}
3209 
3210 	return 0;
3211 
3212 err_out_nosup:
3213 	return rc;
3214 }
3215 
3216 /**
3217  *	ata_cable_40wire	-	return 40 wire cable type
3218  *	@ap: port
3219  *
3220  *	Helper method for drivers which want to hardwire 40 wire cable
3221  *	detection.
3222  */
3223 
3224 int ata_cable_40wire(struct ata_port *ap)
3225 {
3226 	return ATA_CBL_PATA40;
3227 }
3228 EXPORT_SYMBOL_GPL(ata_cable_40wire);
3229 
3230 /**
3231  *	ata_cable_80wire	-	return 80 wire cable type
3232  *	@ap: port
3233  *
3234  *	Helper method for drivers which want to hardwire 80 wire cable
3235  *	detection.
3236  */
3237 
3238 int ata_cable_80wire(struct ata_port *ap)
3239 {
3240 	return ATA_CBL_PATA80;
3241 }
3242 EXPORT_SYMBOL_GPL(ata_cable_80wire);
3243 
3244 /**
3245  *	ata_cable_unknown	-	return unknown PATA cable.
3246  *	@ap: port
3247  *
3248  *	Helper method for drivers which have no PATA cable detection.
3249  */
3250 
3251 int ata_cable_unknown(struct ata_port *ap)
3252 {
3253 	return ATA_CBL_PATA_UNK;
3254 }
3255 EXPORT_SYMBOL_GPL(ata_cable_unknown);
3256 
3257 /**
3258  *	ata_cable_ignore	-	return ignored PATA cable.
3259  *	@ap: port
3260  *
3261  *	Helper method for drivers which don't use cable type to limit
3262  *	transfer mode.
3263  */
3264 int ata_cable_ignore(struct ata_port *ap)
3265 {
3266 	return ATA_CBL_PATA_IGN;
3267 }
3268 EXPORT_SYMBOL_GPL(ata_cable_ignore);
3269 
3270 /**
3271  *	ata_cable_sata	-	return SATA cable type
3272  *	@ap: port
3273  *
3274  *	Helper method for drivers which have SATA cables
3275  */
3276 
3277 int ata_cable_sata(struct ata_port *ap)
3278 {
3279 	return ATA_CBL_SATA;
3280 }
3281 EXPORT_SYMBOL_GPL(ata_cable_sata);
3282 
3283 /**
3284  *	sata_print_link_status - Print SATA link status
3285  *	@link: SATA link to printk link status about
3286  *
3287  *	This function prints link speed and status of a SATA link.
3288  *
3289  *	LOCKING:
3290  *	None.
3291  */
3292 static void sata_print_link_status(struct ata_link *link)
3293 {
3294 	u32 sstatus, scontrol, tmp;
3295 
3296 	if (sata_scr_read(link, SCR_STATUS, &sstatus))
3297 		return;
3298 	if (sata_scr_read(link, SCR_CONTROL, &scontrol))
3299 		return;
3300 
3301 	if (ata_phys_link_online(link)) {
3302 		tmp = (sstatus >> 4) & 0xf;
3303 		ata_link_info(link, "SATA link up %s (SStatus %X SControl %X)\n",
3304 			      sata_spd_string(tmp), sstatus, scontrol);
3305 	} else {
3306 		ata_link_info(link, "SATA link down (SStatus %X SControl %X)\n",
3307 			      sstatus, scontrol);
3308 	}
3309 }
3310 
3311 /**
3312  *	ata_dev_pair		-	return other device on cable
3313  *	@adev: device
3314  *
3315  *	Obtain the other device on the same cable, or if none is
3316  *	present NULL is returned
3317  */
3318 
3319 struct ata_device *ata_dev_pair(struct ata_device *adev)
3320 {
3321 	struct ata_link *link = adev->link;
3322 	struct ata_device *pair = &link->device[1 - adev->devno];
3323 	if (!ata_dev_enabled(pair))
3324 		return NULL;
3325 	return pair;
3326 }
3327 EXPORT_SYMBOL_GPL(ata_dev_pair);
3328 
3329 #ifdef CONFIG_ATA_ACPI
3330 /**
3331  *	ata_timing_cycle2mode - find xfer mode for the specified cycle duration
3332  *	@xfer_shift: ATA_SHIFT_* value for transfer type to examine.
3333  *	@cycle: cycle duration in ns
3334  *
3335  *	Return matching xfer mode for @cycle.  The returned mode is of
3336  *	the transfer type specified by @xfer_shift.  If @cycle is too
3337  *	slow for @xfer_shift, 0xff is returned.  If @cycle is faster
3338  *	than the fastest known mode, the fasted mode is returned.
3339  *
3340  *	LOCKING:
3341  *	None.
3342  *
3343  *	RETURNS:
3344  *	Matching xfer_mode, 0xff if no match found.
3345  */
3346 u8 ata_timing_cycle2mode(unsigned int xfer_shift, int cycle)
3347 {
3348 	u8 base_mode = 0xff, last_mode = 0xff;
3349 	const struct ata_xfer_ent *ent;
3350 	const struct ata_timing *t;
3351 
3352 	for (ent = ata_xfer_tbl; ent->shift >= 0; ent++)
3353 		if (ent->shift == xfer_shift)
3354 			base_mode = ent->base;
3355 
3356 	for (t = ata_timing_find_mode(base_mode);
3357 	     t && ata_xfer_mode2shift(t->mode) == xfer_shift; t++) {
3358 		unsigned short this_cycle;
3359 
3360 		switch (xfer_shift) {
3361 		case ATA_SHIFT_PIO:
3362 		case ATA_SHIFT_MWDMA:
3363 			this_cycle = t->cycle;
3364 			break;
3365 		case ATA_SHIFT_UDMA:
3366 			this_cycle = t->udma;
3367 			break;
3368 		default:
3369 			return 0xff;
3370 		}
3371 
3372 		if (cycle > this_cycle)
3373 			break;
3374 
3375 		last_mode = t->mode;
3376 	}
3377 
3378 	return last_mode;
3379 }
3380 #endif
3381 
3382 /**
3383  *	ata_down_xfermask_limit - adjust dev xfer masks downward
3384  *	@dev: Device to adjust xfer masks
3385  *	@sel: ATA_DNXFER_* selector
3386  *
3387  *	Adjust xfer masks of @dev downward.  Note that this function
3388  *	does not apply the change.  Invoking ata_set_mode() afterwards
3389  *	will apply the limit.
3390  *
3391  *	LOCKING:
3392  *	Inherited from caller.
3393  *
3394  *	RETURNS:
3395  *	0 on success, negative errno on failure
3396  */
3397 int ata_down_xfermask_limit(struct ata_device *dev, unsigned int sel)
3398 {
3399 	char buf[32];
3400 	unsigned int orig_mask, xfer_mask;
3401 	unsigned int pio_mask, mwdma_mask, udma_mask;
3402 	int quiet, highbit;
3403 
3404 	quiet = !!(sel & ATA_DNXFER_QUIET);
3405 	sel &= ~ATA_DNXFER_QUIET;
3406 
3407 	xfer_mask = orig_mask = ata_pack_xfermask(dev->pio_mask,
3408 						  dev->mwdma_mask,
3409 						  dev->udma_mask);
3410 	ata_unpack_xfermask(xfer_mask, &pio_mask, &mwdma_mask, &udma_mask);
3411 
3412 	switch (sel) {
3413 	case ATA_DNXFER_PIO:
3414 		highbit = fls(pio_mask) - 1;
3415 		pio_mask &= ~(1 << highbit);
3416 		break;
3417 
3418 	case ATA_DNXFER_DMA:
3419 		if (udma_mask) {
3420 			highbit = fls(udma_mask) - 1;
3421 			udma_mask &= ~(1 << highbit);
3422 			if (!udma_mask)
3423 				return -ENOENT;
3424 		} else if (mwdma_mask) {
3425 			highbit = fls(mwdma_mask) - 1;
3426 			mwdma_mask &= ~(1 << highbit);
3427 			if (!mwdma_mask)
3428 				return -ENOENT;
3429 		}
3430 		break;
3431 
3432 	case ATA_DNXFER_40C:
3433 		udma_mask &= ATA_UDMA_MASK_40C;
3434 		break;
3435 
3436 	case ATA_DNXFER_FORCE_PIO0:
3437 		pio_mask &= 1;
3438 		fallthrough;
3439 	case ATA_DNXFER_FORCE_PIO:
3440 		mwdma_mask = 0;
3441 		udma_mask = 0;
3442 		break;
3443 
3444 	default:
3445 		BUG();
3446 	}
3447 
3448 	xfer_mask &= ata_pack_xfermask(pio_mask, mwdma_mask, udma_mask);
3449 
3450 	if (!(xfer_mask & ATA_MASK_PIO) || xfer_mask == orig_mask)
3451 		return -ENOENT;
3452 
3453 	if (!quiet) {
3454 		if (xfer_mask & (ATA_MASK_MWDMA | ATA_MASK_UDMA))
3455 			snprintf(buf, sizeof(buf), "%s:%s",
3456 				 ata_mode_string(xfer_mask),
3457 				 ata_mode_string(xfer_mask & ATA_MASK_PIO));
3458 		else
3459 			snprintf(buf, sizeof(buf), "%s",
3460 				 ata_mode_string(xfer_mask));
3461 
3462 		ata_dev_warn(dev, "limiting speed to %s\n", buf);
3463 	}
3464 
3465 	ata_unpack_xfermask(xfer_mask, &dev->pio_mask, &dev->mwdma_mask,
3466 			    &dev->udma_mask);
3467 
3468 	return 0;
3469 }
3470 
3471 static int ata_dev_set_mode(struct ata_device *dev)
3472 {
3473 	struct ata_port *ap = dev->link->ap;
3474 	struct ata_eh_context *ehc = &dev->link->eh_context;
3475 	const bool nosetxfer = dev->quirks & ATA_QUIRK_NOSETXFER;
3476 	const char *dev_err_whine = "";
3477 	int ign_dev_err = 0;
3478 	unsigned int err_mask = 0;
3479 	int rc;
3480 
3481 	dev->flags &= ~ATA_DFLAG_PIO;
3482 	if (dev->xfer_shift == ATA_SHIFT_PIO)
3483 		dev->flags |= ATA_DFLAG_PIO;
3484 
3485 	if (nosetxfer && ap->flags & ATA_FLAG_SATA && ata_id_is_sata(dev->id))
3486 		dev_err_whine = " (SET_XFERMODE skipped)";
3487 	else {
3488 		if (nosetxfer)
3489 			ata_dev_warn(dev,
3490 				     "NOSETXFER but PATA detected - can't "
3491 				     "skip SETXFER, might malfunction\n");
3492 		err_mask = ata_dev_set_xfermode(dev);
3493 	}
3494 
3495 	if (err_mask & ~AC_ERR_DEV)
3496 		goto fail;
3497 
3498 	/* revalidate */
3499 	ehc->i.flags |= ATA_EHI_POST_SETMODE;
3500 	rc = ata_dev_revalidate(dev, ATA_DEV_UNKNOWN, 0);
3501 	ehc->i.flags &= ~ATA_EHI_POST_SETMODE;
3502 	if (rc)
3503 		return rc;
3504 
3505 	if (dev->xfer_shift == ATA_SHIFT_PIO) {
3506 		/* Old CFA may refuse this command, which is just fine */
3507 		if (ata_id_is_cfa(dev->id))
3508 			ign_dev_err = 1;
3509 		/* Catch several broken garbage emulations plus some pre
3510 		   ATA devices */
3511 		if (ata_id_major_version(dev->id) == 0 &&
3512 					dev->pio_mode <= XFER_PIO_2)
3513 			ign_dev_err = 1;
3514 		/* Some very old devices and some bad newer ones fail
3515 		   any kind of SET_XFERMODE request but support PIO0-2
3516 		   timings and no IORDY */
3517 		if (!ata_id_has_iordy(dev->id) && dev->pio_mode <= XFER_PIO_2)
3518 			ign_dev_err = 1;
3519 	}
3520 	/* Early MWDMA devices do DMA but don't allow DMA mode setting.
3521 	   Don't fail an MWDMA0 set IFF the device indicates it is in MWDMA0 */
3522 	if (dev->xfer_shift == ATA_SHIFT_MWDMA &&
3523 	    dev->dma_mode == XFER_MW_DMA_0 &&
3524 	    (dev->id[63] >> 8) & 1)
3525 		ign_dev_err = 1;
3526 
3527 	/* if the device is actually configured correctly, ignore dev err */
3528 	if (dev->xfer_mode == ata_xfer_mask2mode(ata_id_xfermask(dev->id)))
3529 		ign_dev_err = 1;
3530 
3531 	if (err_mask & AC_ERR_DEV) {
3532 		if (!ign_dev_err)
3533 			goto fail;
3534 		else
3535 			dev_err_whine = " (device error ignored)";
3536 	}
3537 
3538 	ata_dev_dbg(dev, "xfer_shift=%u, xfer_mode=0x%x\n",
3539 		    dev->xfer_shift, (int)dev->xfer_mode);
3540 
3541 	if (!(ehc->i.flags & ATA_EHI_QUIET) ||
3542 	    ehc->i.flags & ATA_EHI_DID_HARDRESET)
3543 		ata_dev_info(dev, "configured for %s%s\n",
3544 			     ata_mode_string(ata_xfer_mode2mask(dev->xfer_mode)),
3545 			     dev_err_whine);
3546 
3547 	return 0;
3548 
3549  fail:
3550 	ata_dev_err(dev, "failed to set xfermode (err_mask=0x%x)\n", err_mask);
3551 	return -EIO;
3552 }
3553 
3554 /**
3555  *	ata_set_mode - Program timings and issue SET FEATURES - XFER
3556  *	@link: link on which timings will be programmed
3557  *	@r_failed_dev: out parameter for failed device
3558  *
3559  *	Standard implementation of the function used to tune and set
3560  *	ATA device disk transfer mode (PIO3, UDMA6, etc.).  If
3561  *	ata_dev_set_mode() fails, pointer to the failing device is
3562  *	returned in @r_failed_dev.
3563  *
3564  *	LOCKING:
3565  *	PCI/etc. bus probe sem.
3566  *
3567  *	RETURNS:
3568  *	0 on success, negative errno otherwise
3569  */
3570 
3571 int ata_set_mode(struct ata_link *link, struct ata_device **r_failed_dev)
3572 {
3573 	struct ata_port *ap = link->ap;
3574 	struct ata_device *dev;
3575 	int rc = 0, used_dma = 0, found = 0;
3576 
3577 	/* step 1: calculate xfer_mask */
3578 	ata_for_each_dev(dev, link, ENABLED) {
3579 		unsigned int pio_mask, dma_mask;
3580 		unsigned int mode_mask;
3581 
3582 		mode_mask = ATA_DMA_MASK_ATA;
3583 		if (dev->class == ATA_DEV_ATAPI)
3584 			mode_mask = ATA_DMA_MASK_ATAPI;
3585 		else if (ata_id_is_cfa(dev->id))
3586 			mode_mask = ATA_DMA_MASK_CFA;
3587 
3588 		ata_dev_xfermask(dev);
3589 		ata_force_xfermask(dev);
3590 
3591 		pio_mask = ata_pack_xfermask(dev->pio_mask, 0, 0);
3592 
3593 		if (libata_dma_mask & mode_mask)
3594 			dma_mask = ata_pack_xfermask(0, dev->mwdma_mask,
3595 						     dev->udma_mask);
3596 		else
3597 			dma_mask = 0;
3598 
3599 		dev->pio_mode = ata_xfer_mask2mode(pio_mask);
3600 		dev->dma_mode = ata_xfer_mask2mode(dma_mask);
3601 
3602 		found = 1;
3603 		if (ata_dma_enabled(dev))
3604 			used_dma = 1;
3605 	}
3606 	if (!found)
3607 		goto out;
3608 
3609 	/* step 2: always set host PIO timings */
3610 	ata_for_each_dev(dev, link, ENABLED) {
3611 		if (dev->pio_mode == 0xff) {
3612 			ata_dev_warn(dev, "no PIO support\n");
3613 			rc = -EINVAL;
3614 			goto out;
3615 		}
3616 
3617 		dev->xfer_mode = dev->pio_mode;
3618 		dev->xfer_shift = ATA_SHIFT_PIO;
3619 		if (ap->ops->set_piomode)
3620 			ap->ops->set_piomode(ap, dev);
3621 	}
3622 
3623 	/* step 3: set host DMA timings */
3624 	ata_for_each_dev(dev, link, ENABLED) {
3625 		if (!ata_dma_enabled(dev))
3626 			continue;
3627 
3628 		dev->xfer_mode = dev->dma_mode;
3629 		dev->xfer_shift = ata_xfer_mode2shift(dev->dma_mode);
3630 		if (ap->ops->set_dmamode)
3631 			ap->ops->set_dmamode(ap, dev);
3632 	}
3633 
3634 	/* step 4: update devices' xfer mode */
3635 	ata_for_each_dev(dev, link, ENABLED) {
3636 		rc = ata_dev_set_mode(dev);
3637 		if (rc)
3638 			goto out;
3639 	}
3640 
3641 	/* Record simplex status. If we selected DMA then the other
3642 	 * host channels are not permitted to do so.
3643 	 */
3644 	if (used_dma && (ap->host->flags & ATA_HOST_SIMPLEX))
3645 		ap->host->simplex_claimed = ap;
3646 
3647  out:
3648 	if (rc)
3649 		*r_failed_dev = dev;
3650 	return rc;
3651 }
3652 EXPORT_SYMBOL_GPL(ata_set_mode);
3653 
3654 /**
3655  *	ata_wait_ready - wait for link to become ready
3656  *	@link: link to be waited on
3657  *	@deadline: deadline jiffies for the operation
3658  *	@check_ready: callback to check link readiness
3659  *
3660  *	Wait for @link to become ready.  @check_ready should return
3661  *	positive number if @link is ready, 0 if it isn't, -ENODEV if
3662  *	link doesn't seem to be occupied, other errno for other error
3663  *	conditions.
3664  *
3665  *	Transient -ENODEV conditions are allowed for
3666  *	ATA_TMOUT_FF_WAIT.
3667  *
3668  *	LOCKING:
3669  *	EH context.
3670  *
3671  *	RETURNS:
3672  *	0 if @link is ready before @deadline; otherwise, -errno.
3673  */
3674 int ata_wait_ready(struct ata_link *link, unsigned long deadline,
3675 		   int (*check_ready)(struct ata_link *link))
3676 {
3677 	unsigned long start = jiffies;
3678 	unsigned long nodev_deadline;
3679 	int warned = 0;
3680 
3681 	/* choose which 0xff timeout to use, read comment in libata.h */
3682 	if (link->ap->host->flags & ATA_HOST_PARALLEL_SCAN)
3683 		nodev_deadline = ata_deadline(start, ATA_TMOUT_FF_WAIT_LONG);
3684 	else
3685 		nodev_deadline = ata_deadline(start, ATA_TMOUT_FF_WAIT);
3686 
3687 	/* Slave readiness can't be tested separately from master.  On
3688 	 * M/S emulation configuration, this function should be called
3689 	 * only on the master and it will handle both master and slave.
3690 	 */
3691 	WARN_ON(link == link->ap->slave_link);
3692 
3693 	if (time_after(nodev_deadline, deadline))
3694 		nodev_deadline = deadline;
3695 
3696 	while (1) {
3697 		unsigned long now = jiffies;
3698 		int ready, tmp;
3699 
3700 		ready = tmp = check_ready(link);
3701 		if (ready > 0)
3702 			return 0;
3703 
3704 		/*
3705 		 * -ENODEV could be transient.  Ignore -ENODEV if link
3706 		 * is online.  Also, some SATA devices take a long
3707 		 * time to clear 0xff after reset.  Wait for
3708 		 * ATA_TMOUT_FF_WAIT[_LONG] on -ENODEV if link isn't
3709 		 * offline.
3710 		 *
3711 		 * Note that some PATA controllers (pata_ali) explode
3712 		 * if status register is read more than once when
3713 		 * there's no device attached.
3714 		 */
3715 		if (ready == -ENODEV) {
3716 			if (ata_link_online(link))
3717 				ready = 0;
3718 			else if ((link->ap->flags & ATA_FLAG_SATA) &&
3719 				 !ata_link_offline(link) &&
3720 				 time_before(now, nodev_deadline))
3721 				ready = 0;
3722 		}
3723 
3724 		if (ready)
3725 			return ready;
3726 		if (time_after(now, deadline))
3727 			return -EBUSY;
3728 
3729 		if (!warned && time_after(now, start + 5 * HZ) &&
3730 		    (deadline - now > 3 * HZ)) {
3731 			ata_link_warn(link,
3732 				"link is slow to respond, please be patient "
3733 				"(ready=%d)\n", tmp);
3734 			warned = 1;
3735 		}
3736 
3737 		ata_msleep(link->ap, 50);
3738 	}
3739 }
3740 
3741 /**
3742  *	ata_wait_after_reset - wait for link to become ready after reset
3743  *	@link: link to be waited on
3744  *	@deadline: deadline jiffies for the operation
3745  *	@check_ready: callback to check link readiness
3746  *
3747  *	Wait for @link to become ready after reset.
3748  *
3749  *	LOCKING:
3750  *	EH context.
3751  *
3752  *	RETURNS:
3753  *	0 if @link is ready before @deadline; otherwise, -errno.
3754  */
3755 int ata_wait_after_reset(struct ata_link *link, unsigned long deadline,
3756 				int (*check_ready)(struct ata_link *link))
3757 {
3758 	ata_msleep(link->ap, ATA_WAIT_AFTER_RESET);
3759 
3760 	return ata_wait_ready(link, deadline, check_ready);
3761 }
3762 EXPORT_SYMBOL_GPL(ata_wait_after_reset);
3763 
3764 /**
3765  *	ata_std_prereset - prepare for reset
3766  *	@link: ATA link to be reset
3767  *	@deadline: deadline jiffies for the operation
3768  *
3769  *	@link is about to be reset.  Initialize it.  Failure from
3770  *	prereset makes libata abort whole reset sequence and give up
3771  *	that port, so prereset should be best-effort.  It does its
3772  *	best to prepare for reset sequence but if things go wrong, it
3773  *	should just whine, not fail.
3774  *
3775  *	LOCKING:
3776  *	Kernel thread context (may sleep)
3777  *
3778  *	RETURNS:
3779  *	Always 0.
3780  */
3781 int ata_std_prereset(struct ata_link *link, unsigned long deadline)
3782 {
3783 	struct ata_port *ap = link->ap;
3784 	struct ata_eh_context *ehc = &link->eh_context;
3785 	const unsigned int *timing = sata_ehc_deb_timing(ehc);
3786 	int rc;
3787 
3788 	/* if we're about to do hardreset, nothing more to do */
3789 	if (ehc->i.action & ATA_EH_HARDRESET)
3790 		return 0;
3791 
3792 	/* if SATA, resume link */
3793 	if (ap->flags & ATA_FLAG_SATA) {
3794 		rc = sata_link_resume(link, timing, deadline);
3795 		/* whine about phy resume failure but proceed */
3796 		if (rc && rc != -EOPNOTSUPP)
3797 			ata_link_warn(link,
3798 				      "failed to resume link for reset (errno=%d)\n",
3799 				      rc);
3800 	}
3801 
3802 	/* no point in trying softreset on offline link */
3803 	if (ata_phys_link_offline(link))
3804 		ehc->i.action &= ~ATA_EH_SOFTRESET;
3805 
3806 	return 0;
3807 }
3808 EXPORT_SYMBOL_GPL(ata_std_prereset);
3809 
3810 /**
3811  *	ata_std_postreset - standard postreset callback
3812  *	@link: the target ata_link
3813  *	@classes: classes of attached devices
3814  *
3815  *	This function is invoked after a successful reset.  Note that
3816  *	the device might have been reset more than once using
3817  *	different reset methods before postreset is invoked.
3818  *
3819  *	LOCKING:
3820  *	Kernel thread context (may sleep)
3821  */
3822 void ata_std_postreset(struct ata_link *link, unsigned int *classes)
3823 {
3824 	u32 serror;
3825 
3826 	/* reset complete, clear SError */
3827 	if (!sata_scr_read(link, SCR_ERROR, &serror))
3828 		sata_scr_write(link, SCR_ERROR, serror);
3829 
3830 	/* print link status */
3831 	sata_print_link_status(link);
3832 }
3833 EXPORT_SYMBOL_GPL(ata_std_postreset);
3834 
3835 /**
3836  *	ata_dev_same_device - Determine whether new ID matches configured device
3837  *	@dev: device to compare against
3838  *	@new_class: class of the new device
3839  *	@new_id: IDENTIFY page of the new device
3840  *
3841  *	Compare @new_class and @new_id against @dev and determine
3842  *	whether @dev is the device indicated by @new_class and
3843  *	@new_id.
3844  *
3845  *	LOCKING:
3846  *	None.
3847  *
3848  *	RETURNS:
3849  *	1 if @dev matches @new_class and @new_id, 0 otherwise.
3850  */
3851 static int ata_dev_same_device(struct ata_device *dev, unsigned int new_class,
3852 			       const u16 *new_id)
3853 {
3854 	const u16 *old_id = dev->id;
3855 	unsigned char model[2][ATA_ID_PROD_LEN + 1];
3856 	unsigned char serial[2][ATA_ID_SERNO_LEN + 1];
3857 
3858 	if (dev->class != new_class) {
3859 		ata_dev_info(dev, "class mismatch %d != %d\n",
3860 			     dev->class, new_class);
3861 		return 0;
3862 	}
3863 
3864 	ata_id_c_string(old_id, model[0], ATA_ID_PROD, sizeof(model[0]));
3865 	ata_id_c_string(new_id, model[1], ATA_ID_PROD, sizeof(model[1]));
3866 	ata_id_c_string(old_id, serial[0], ATA_ID_SERNO, sizeof(serial[0]));
3867 	ata_id_c_string(new_id, serial[1], ATA_ID_SERNO, sizeof(serial[1]));
3868 
3869 	if (strcmp(model[0], model[1])) {
3870 		ata_dev_info(dev, "model number mismatch '%s' != '%s'\n",
3871 			     model[0], model[1]);
3872 		return 0;
3873 	}
3874 
3875 	if (strcmp(serial[0], serial[1])) {
3876 		ata_dev_info(dev, "serial number mismatch '%s' != '%s'\n",
3877 			     serial[0], serial[1]);
3878 		return 0;
3879 	}
3880 
3881 	return 1;
3882 }
3883 
3884 /**
3885  *	ata_dev_reread_id - Re-read IDENTIFY data
3886  *	@dev: target ATA device
3887  *	@readid_flags: read ID flags
3888  *
3889  *	Re-read IDENTIFY page and make sure @dev is still attached to
3890  *	the port.
3891  *
3892  *	LOCKING:
3893  *	Kernel thread context (may sleep)
3894  *
3895  *	RETURNS:
3896  *	0 on success, negative errno otherwise
3897  */
3898 int ata_dev_reread_id(struct ata_device *dev, unsigned int readid_flags)
3899 {
3900 	unsigned int class = dev->class;
3901 	u16 *id = (void *)dev->sector_buf;
3902 	int rc;
3903 
3904 	/* read ID data */
3905 	rc = ata_dev_read_id(dev, &class, readid_flags, id);
3906 	if (rc)
3907 		return rc;
3908 
3909 	/* is the device still there? */
3910 	if (!ata_dev_same_device(dev, class, id))
3911 		return -ENODEV;
3912 
3913 	memcpy(dev->id, id, sizeof(id[0]) * ATA_ID_WORDS);
3914 	return 0;
3915 }
3916 
3917 /**
3918  *	ata_dev_revalidate - Revalidate ATA device
3919  *	@dev: device to revalidate
3920  *	@new_class: new class code
3921  *	@readid_flags: read ID flags
3922  *
3923  *	Re-read IDENTIFY page, make sure @dev is still attached to the
3924  *	port and reconfigure it according to the new IDENTIFY page.
3925  *
3926  *	LOCKING:
3927  *	Kernel thread context (may sleep)
3928  *
3929  *	RETURNS:
3930  *	0 on success, negative errno otherwise
3931  */
3932 int ata_dev_revalidate(struct ata_device *dev, unsigned int new_class,
3933 		       unsigned int readid_flags)
3934 {
3935 	u64 n_sectors = dev->n_sectors;
3936 	u64 n_native_sectors = dev->n_native_sectors;
3937 	int rc;
3938 
3939 	if (!ata_dev_enabled(dev))
3940 		return -ENODEV;
3941 
3942 	/* fail early if !ATA && !ATAPI to avoid issuing [P]IDENTIFY to PMP */
3943 	if (ata_class_enabled(new_class) && new_class == ATA_DEV_PMP) {
3944 		ata_dev_info(dev, "class mismatch %u != %u\n",
3945 			     dev->class, new_class);
3946 		rc = -ENODEV;
3947 		goto fail;
3948 	}
3949 
3950 	/* re-read ID */
3951 	rc = ata_dev_reread_id(dev, readid_flags);
3952 	if (rc)
3953 		goto fail;
3954 
3955 	/* configure device according to the new ID */
3956 	rc = ata_dev_configure(dev);
3957 	if (rc)
3958 		goto fail;
3959 
3960 	/* verify n_sectors hasn't changed */
3961 	if (dev->class != ATA_DEV_ATA || !n_sectors ||
3962 	    dev->n_sectors == n_sectors)
3963 		return 0;
3964 
3965 	/* n_sectors has changed */
3966 	ata_dev_warn(dev, "n_sectors mismatch %llu != %llu\n",
3967 		     (unsigned long long)n_sectors,
3968 		     (unsigned long long)dev->n_sectors);
3969 
3970 	/*
3971 	 * Something could have caused HPA to be unlocked
3972 	 * involuntarily.  If n_native_sectors hasn't changed and the
3973 	 * new size matches it, keep the device.
3974 	 */
3975 	if (dev->n_native_sectors == n_native_sectors &&
3976 	    dev->n_sectors > n_sectors && dev->n_sectors == n_native_sectors) {
3977 		ata_dev_warn(dev,
3978 			     "new n_sectors matches native, probably "
3979 			     "late HPA unlock, n_sectors updated\n");
3980 		/* use the larger n_sectors */
3981 		return 0;
3982 	}
3983 
3984 	/*
3985 	 * Some BIOSes boot w/o HPA but resume w/ HPA locked.  Try
3986 	 * unlocking HPA in those cases.
3987 	 *
3988 	 * https://bugzilla.kernel.org/show_bug.cgi?id=15396
3989 	 */
3990 	if (dev->n_native_sectors == n_native_sectors &&
3991 	    dev->n_sectors < n_sectors && n_sectors == n_native_sectors &&
3992 	    !(dev->quirks & ATA_QUIRK_BROKEN_HPA)) {
3993 		ata_dev_warn(dev,
3994 			     "old n_sectors matches native, probably "
3995 			     "late HPA lock, will try to unlock HPA\n");
3996 		/* try unlocking HPA */
3997 		dev->flags |= ATA_DFLAG_UNLOCK_HPA;
3998 		rc = -EIO;
3999 	} else
4000 		rc = -ENODEV;
4001 
4002 	/* restore original n_[native_]sectors and fail */
4003 	dev->n_native_sectors = n_native_sectors;
4004 	dev->n_sectors = n_sectors;
4005  fail:
4006 	ata_dev_err(dev, "revalidation failed (errno=%d)\n", rc);
4007 	return rc;
4008 }
4009 
4010 static const char * const ata_quirk_names[] = {
4011 	[__ATA_QUIRK_DIAGNOSTIC]	= "diagnostic",
4012 	[__ATA_QUIRK_NODMA]		= "nodma",
4013 	[__ATA_QUIRK_NONCQ]		= "noncq",
4014 	[__ATA_QUIRK_BROKEN_HPA]	= "brokenhpa",
4015 	[__ATA_QUIRK_DISABLE]		= "disable",
4016 	[__ATA_QUIRK_HPA_SIZE]		= "hpasize",
4017 	[__ATA_QUIRK_IVB]		= "ivb",
4018 	[__ATA_QUIRK_STUCK_ERR]		= "stuckerr",
4019 	[__ATA_QUIRK_BRIDGE_OK]		= "bridgeok",
4020 	[__ATA_QUIRK_ATAPI_MOD16_DMA]	= "atapimod16dma",
4021 	[__ATA_QUIRK_FIRMWARE_WARN]	= "firmwarewarn",
4022 	[__ATA_QUIRK_1_5_GBPS]		= "1.5gbps",
4023 	[__ATA_QUIRK_NOSETXFER]		= "nosetxfer",
4024 	[__ATA_QUIRK_BROKEN_FPDMA_AA]	= "brokenfpdmaaa",
4025 	[__ATA_QUIRK_DUMP_ID]		= "dumpid",
4026 	[__ATA_QUIRK_MAX_SEC_LBA48]	= "maxseclba48",
4027 	[__ATA_QUIRK_ATAPI_DMADIR]	= "atapidmadir",
4028 	[__ATA_QUIRK_NO_NCQ_TRIM]	= "noncqtrim",
4029 	[__ATA_QUIRK_NOLPM]		= "nolpm",
4030 	[__ATA_QUIRK_WD_BROKEN_LPM]	= "wdbrokenlpm",
4031 	[__ATA_QUIRK_ZERO_AFTER_TRIM]	= "zeroaftertrim",
4032 	[__ATA_QUIRK_NO_DMA_LOG]	= "nodmalog",
4033 	[__ATA_QUIRK_NOTRIM]		= "notrim",
4034 	[__ATA_QUIRK_MAX_SEC]		= "maxsec",
4035 	[__ATA_QUIRK_MAX_TRIM_128M]	= "maxtrim128m",
4036 	[__ATA_QUIRK_NO_NCQ_ON_ATI]	= "noncqonati",
4037 	[__ATA_QUIRK_NO_LPM_ON_ATI]	= "nolpmonati",
4038 	[__ATA_QUIRK_NO_ID_DEV_LOG]	= "noiddevlog",
4039 	[__ATA_QUIRK_NO_LOG_DIR]	= "nologdir",
4040 	[__ATA_QUIRK_NO_FUA]		= "nofua",
4041 };
4042 
4043 static void ata_dev_print_quirks(const struct ata_device *dev,
4044 				 const char *model, const char *rev,
4045 				 unsigned int quirks)
4046 {
4047 	struct ata_eh_context *ehc = &dev->link->eh_context;
4048 	int n = 0, i;
4049 	size_t sz;
4050 	char *str;
4051 
4052 	if (!ata_dev_print_info(dev) || ehc->i.flags & ATA_EHI_DID_PRINT_QUIRKS)
4053 		return;
4054 
4055 	ehc->i.flags |= ATA_EHI_DID_PRINT_QUIRKS;
4056 
4057 	if (!quirks)
4058 		return;
4059 
4060 	sz = 64 + ARRAY_SIZE(ata_quirk_names) * 16;
4061 	str = kmalloc(sz, GFP_KERNEL);
4062 	if (!str)
4063 		return;
4064 
4065 	n = snprintf(str, sz, "Model '%s', rev '%s', applying quirks:",
4066 		     model, rev);
4067 
4068 	for (i = 0; i < ARRAY_SIZE(ata_quirk_names); i++) {
4069 		if (quirks & (1U << i))
4070 			n += snprintf(str + n, sz - n,
4071 				      " %s", ata_quirk_names[i]);
4072 	}
4073 
4074 	ata_dev_warn(dev, "%s\n", str);
4075 
4076 	kfree(str);
4077 }
4078 
4079 struct ata_dev_quirk_value {
4080 	const char	*model_num;
4081 	const char	*model_rev;
4082 	u64		val;
4083 };
4084 
4085 static const struct ata_dev_quirk_value __ata_dev_max_sec_quirks[] = {
4086 	{ "TORiSAN DVD-ROM DRD-N216",	NULL,		128 },
4087 	{ "ST380013AS",			"3.20",		1024 },
4088 	{ "LITEON CX1-JB*-HP",		NULL,		1024 },
4089 	{ "LITEON EP1-*",		NULL,		1024 },
4090 	{ "DELLBOSS VD",		"MV.R00-0",	8191 },
4091 	{ "INTEL SSDSC2KG480G8",	"XCV10120",	8191 },
4092 	{ },
4093 };
4094 
4095 struct ata_dev_quirks_entry {
4096 	const char *model_num;
4097 	const char *model_rev;
4098 	u64 quirks;
4099 };
4100 
4101 static const struct ata_dev_quirks_entry __ata_dev_quirks[] = {
4102 	/* Devices with DMA related problems under Linux */
4103 	{ "WDC AC11000H",	NULL,		ATA_QUIRK_NODMA },
4104 	{ "WDC AC22100H",	NULL,		ATA_QUIRK_NODMA },
4105 	{ "WDC AC32500H",	NULL,		ATA_QUIRK_NODMA },
4106 	{ "WDC AC33100H",	NULL,		ATA_QUIRK_NODMA },
4107 	{ "WDC AC31600H",	NULL,		ATA_QUIRK_NODMA },
4108 	{ "WDC AC32100H",	"24.09P07",	ATA_QUIRK_NODMA },
4109 	{ "WDC AC23200L",	"21.10N21",	ATA_QUIRK_NODMA },
4110 	{ "Compaq CRD-8241B",	NULL,		ATA_QUIRK_NODMA },
4111 	{ "CRD-8400B",		NULL,		ATA_QUIRK_NODMA },
4112 	{ "CRD-848[02]B",	NULL,		ATA_QUIRK_NODMA },
4113 	{ "CRD-84",		NULL,		ATA_QUIRK_NODMA },
4114 	{ "SanDisk SDP3B",	NULL,		ATA_QUIRK_NODMA },
4115 	{ "SanDisk SDP3B-64",	NULL,		ATA_QUIRK_NODMA },
4116 	{ "SANYO CD-ROM CRD",	NULL,		ATA_QUIRK_NODMA },
4117 	{ "HITACHI CDR-8",	NULL,		ATA_QUIRK_NODMA },
4118 	{ "HITACHI CDR-8[34]35", NULL,		ATA_QUIRK_NODMA },
4119 	{ "Toshiba CD-ROM XM-6202B", NULL,	ATA_QUIRK_NODMA },
4120 	{ "TOSHIBA CD-ROM XM-1702BC", NULL,	ATA_QUIRK_NODMA },
4121 	{ "CD-532E-A",		NULL,		ATA_QUIRK_NODMA },
4122 	{ "E-IDE CD-ROM CR-840", NULL,		ATA_QUIRK_NODMA },
4123 	{ "CD-ROM Drive/F5A",	NULL,		ATA_QUIRK_NODMA },
4124 	{ "WPI CDD-820",	NULL,		ATA_QUIRK_NODMA },
4125 	{ "SAMSUNG CD-ROM SC-148C", NULL,	ATA_QUIRK_NODMA },
4126 	{ "SAMSUNG CD-ROM SC",	NULL,		ATA_QUIRK_NODMA },
4127 	{ "ATAPI CD-ROM DRIVE 40X MAXIMUM", NULL, ATA_QUIRK_NODMA },
4128 	{ "_NEC DV5800A",	NULL,		ATA_QUIRK_NODMA },
4129 	{ "SAMSUNG CD-ROM SN-124", "N001",	ATA_QUIRK_NODMA },
4130 	{ "Seagate STT20000A", NULL,		ATA_QUIRK_NODMA },
4131 	{ " 2GB ATA Flash Disk", "ADMA428M",	ATA_QUIRK_NODMA },
4132 	{ "VRFDFC22048UCHC-TE*", NULL,		ATA_QUIRK_NODMA },
4133 	/* Odd clown on sil3726/4726 PMPs */
4134 	{ "Config  Disk",	NULL,		ATA_QUIRK_DISABLE },
4135 	/* Similar story with ASMedia 1092 */
4136 	{ "ASMT109x- Config",	NULL,		ATA_QUIRK_DISABLE },
4137 
4138 	/* Weird ATAPI devices */
4139 	{ "TORiSAN DVD-ROM DRD-N216", NULL,	ATA_QUIRK_MAX_SEC },
4140 	{ "QUANTUM DAT    DAT72-000", NULL,	ATA_QUIRK_ATAPI_MOD16_DMA },
4141 	{ "Slimtype DVD A  DS8A8SH", NULL,	ATA_QUIRK_MAX_SEC_LBA48 },
4142 	{ "Slimtype DVD A  DS8A9SH", NULL,	ATA_QUIRK_MAX_SEC_LBA48 },
4143 
4144 	/*
4145 	 * Causes silent data corruption with higher max sects.
4146 	 * http://lkml.kernel.org/g/x49wpy40ysk.fsf@segfault.boston.devel.redhat.com
4147 	 */
4148 	{ "ST380013AS",		"3.20",		ATA_QUIRK_MAX_SEC },
4149 
4150 	/*
4151 	 * These devices time out with higher max sects.
4152 	 * https://bugzilla.kernel.org/show_bug.cgi?id=121671
4153 	 */
4154 	{ "LITEON CX1-JB*-HP",	NULL,		ATA_QUIRK_MAX_SEC },
4155 	{ "LITEON EP1-*",	NULL,		ATA_QUIRK_MAX_SEC },
4156 
4157 	/*
4158 	 * These devices time out with higher max sects.
4159 	 * https://bugzilla.kernel.org/show_bug.cgi?id=220693
4160 	 */
4161 	{ "DELLBOSS VD",	"MV.R00-0",	ATA_QUIRK_MAX_SEC },
4162 
4163 	/* Devices we expect to fail diagnostics */
4164 
4165 	/* Devices where NCQ should be avoided */
4166 	/* NCQ is slow */
4167 	{ "WDC WD740ADFD-00",	NULL,		ATA_QUIRK_NONCQ },
4168 	{ "WDC WD740ADFD-00NLR1", NULL,		ATA_QUIRK_NONCQ },
4169 	/* http://thread.gmane.org/gmane.linux.ide/14907 */
4170 	{ "FUJITSU MHT2060BH",	NULL,		ATA_QUIRK_NONCQ },
4171 	/* NCQ is broken */
4172 	{ "Maxtor *",		"BANC*",	ATA_QUIRK_NONCQ },
4173 	{ "Maxtor 7V300F0",	"VA111630",	ATA_QUIRK_NONCQ },
4174 	{ "ST380817AS",		"3.42",		ATA_QUIRK_NONCQ },
4175 	{ "ST3160023AS",	"3.42",		ATA_QUIRK_NONCQ },
4176 	{ "OCZ CORE_SSD",	"02.10104",	ATA_QUIRK_NONCQ },
4177 
4178 	/* Seagate NCQ + FLUSH CACHE firmware bug */
4179 	{ "ST31500341AS",	"SD1[5-9]",	ATA_QUIRK_NONCQ |
4180 						ATA_QUIRK_FIRMWARE_WARN },
4181 
4182 	{ "ST31000333AS",	"SD1[5-9]",	ATA_QUIRK_NONCQ |
4183 						ATA_QUIRK_FIRMWARE_WARN },
4184 
4185 	{ "ST3640[36]23AS",	"SD1[5-9]",	ATA_QUIRK_NONCQ |
4186 						ATA_QUIRK_FIRMWARE_WARN },
4187 
4188 	{ "ST3320[68]13AS",	"SD1[5-9]",	ATA_QUIRK_NONCQ |
4189 						ATA_QUIRK_FIRMWARE_WARN },
4190 
4191 	/* Seagate disks with LPM issues */
4192 	{ "ST2000DM008-2FR102",	NULL,		ATA_QUIRK_NOLPM },
4193 
4194 	/* drives which fail FPDMA_AA activation (some may freeze afterwards)
4195 	   the ST disks also have LPM issues */
4196 	{ "ST1000LM024 HN-M101MBB", NULL,	ATA_QUIRK_BROKEN_FPDMA_AA |
4197 						ATA_QUIRK_NOLPM },
4198 	{ "VB0250EAVER",	"HPG7",		ATA_QUIRK_BROKEN_FPDMA_AA },
4199 
4200 	/* Blacklist entries taken from Silicon Image 3124/3132
4201 	   Windows driver .inf file - also several Linux problem reports */
4202 	{ "HTS541060G9SA00",    "MB3OC60D",     ATA_QUIRK_NONCQ },
4203 	{ "HTS541080G9SA00",    "MB4OC60D",     ATA_QUIRK_NONCQ },
4204 	{ "HTS541010G9SA00",    "MBZOC60D",     ATA_QUIRK_NONCQ },
4205 
4206 	/* https://bugzilla.kernel.org/show_bug.cgi?id=15573 */
4207 	{ "C300-CTFDDAC128MAG",	"0001",		ATA_QUIRK_NONCQ },
4208 
4209 	/* Sandisk SD7/8/9s lock up hard on large trims */
4210 	{ "SanDisk SD[789]*",	NULL,		ATA_QUIRK_MAX_TRIM_128M },
4211 
4212 	/* devices which puke on READ_NATIVE_MAX */
4213 	{ "HDS724040KLSA80",	"KFAOA20N",	ATA_QUIRK_BROKEN_HPA },
4214 	{ "WDC WD3200JD-00KLB0", "WD-WCAMR1130137", ATA_QUIRK_BROKEN_HPA },
4215 	{ "WDC WD2500JD-00HBB0", "WD-WMAL71490727", ATA_QUIRK_BROKEN_HPA },
4216 	{ "MAXTOR 6L080L4",	"A93.0500",	ATA_QUIRK_BROKEN_HPA },
4217 
4218 	/* this one allows HPA unlocking but fails IOs on the area */
4219 	{ "OCZ-VERTEX",		    "1.30",	ATA_QUIRK_BROKEN_HPA },
4220 
4221 	/* Devices which report 1 sector over size HPA */
4222 	{ "ST340823A",		NULL,		ATA_QUIRK_HPA_SIZE },
4223 	{ "ST320413A",		NULL,		ATA_QUIRK_HPA_SIZE },
4224 	{ "ST310211A",		NULL,		ATA_QUIRK_HPA_SIZE },
4225 
4226 	/* Devices which get the IVB wrong */
4227 	{ "QUANTUM FIREBALLlct10 05", "A03.0900", ATA_QUIRK_IVB },
4228 	/* Maybe we should just add all TSSTcorp devices... */
4229 	{ "TSSTcorp CDDVDW SH-S202[HJN]", "SB0[01]",  ATA_QUIRK_IVB },
4230 
4231 	/* Devices that do not need bridging limits applied */
4232 	{ "MTRON MSP-SATA*",		NULL,	ATA_QUIRK_BRIDGE_OK },
4233 	{ "BUFFALO HD-QSU2/R5",		NULL,	ATA_QUIRK_BRIDGE_OK },
4234 
4235 	/* Devices which aren't very happy with higher link speeds */
4236 	{ "WD My Book",			NULL,	ATA_QUIRK_1_5_GBPS },
4237 	{ "Seagate FreeAgent GoFlex",	NULL,	ATA_QUIRK_1_5_GBPS },
4238 
4239 	/*
4240 	 * Devices which choke on SETXFER.  Applies only if both the
4241 	 * device and controller are SATA.
4242 	 */
4243 	{ "PIONEER DVD-RW  DVRTD08",	NULL,	ATA_QUIRK_NOSETXFER },
4244 	{ "PIONEER DVD-RW  DVRTD08A",	NULL,	ATA_QUIRK_NOSETXFER },
4245 	{ "PIONEER DVD-RW  DVR-215",	NULL,	ATA_QUIRK_NOSETXFER },
4246 	{ "PIONEER DVD-RW  DVR-212D",	NULL,	ATA_QUIRK_NOSETXFER },
4247 	{ "PIONEER DVD-RW  DVR-216D",	NULL,	ATA_QUIRK_NOSETXFER },
4248 
4249 	/* These specific Pioneer models have LPM issues */
4250 	{ "PIONEER BD-RW   BDR-207M",	NULL,	ATA_QUIRK_NOLPM },
4251 	{ "PIONEER BD-RW   BDR-205",	NULL,	ATA_QUIRK_NOLPM },
4252 
4253 	/* Crucial devices with broken LPM support */
4254 	{ "CT*0BX*00SSD1",		NULL,	ATA_QUIRK_NOLPM },
4255 
4256 	/* 512GB MX100 with MU01 firmware has both queued TRIM and LPM issues */
4257 	{ "Crucial_CT512MX100*",	"MU01",	ATA_QUIRK_NO_NCQ_TRIM |
4258 						ATA_QUIRK_ZERO_AFTER_TRIM |
4259 						ATA_QUIRK_NOLPM },
4260 	/* 512GB MX100 with newer firmware has only LPM issues */
4261 	{ "Crucial_CT512MX100*",	NULL,	ATA_QUIRK_ZERO_AFTER_TRIM |
4262 						ATA_QUIRK_NOLPM },
4263 
4264 	/* 480GB+ M500 SSDs have both queued TRIM and LPM issues */
4265 	{ "Crucial_CT480M500*",		NULL,	ATA_QUIRK_NO_NCQ_TRIM |
4266 						ATA_QUIRK_ZERO_AFTER_TRIM |
4267 						ATA_QUIRK_NOLPM },
4268 	{ "Crucial_CT960M500*",		NULL,	ATA_QUIRK_NO_NCQ_TRIM |
4269 						ATA_QUIRK_ZERO_AFTER_TRIM |
4270 						ATA_QUIRK_NOLPM },
4271 
4272 	/* AMD Radeon devices with broken LPM support */
4273 	{ "R3SL240G",			NULL,	ATA_QUIRK_NOLPM },
4274 
4275 	/* Apacer models with LPM issues */
4276 	{ "Apacer AS340*",		NULL,	ATA_QUIRK_NOLPM },
4277 
4278 	/* Silicon Motion models with LPM issues */
4279 	{ "MD619HXCLDE3TC",		"TCVAID", ATA_QUIRK_NOLPM },
4280 	{ "MD619GXCLDE3TC",		"TCV35D", ATA_QUIRK_NOLPM },
4281 
4282 	/* These specific Samsung models/firmware-revs do not handle LPM well */
4283 	{ "SAMSUNG MZMPC128HBFU-000MV", "CXM14M1Q", ATA_QUIRK_NOLPM },
4284 	{ "SAMSUNG SSD PM830 mSATA *",  "CXM13D1Q", ATA_QUIRK_NOLPM },
4285 	{ "SAMSUNG MZ7TD256HAFV-000L9", NULL,       ATA_QUIRK_NOLPM },
4286 	{ "SAMSUNG MZ7TE512HMHP-000L1", "EXT06L0Q", ATA_QUIRK_NOLPM },
4287 
4288 	/* devices that don't properly handle queued TRIM commands */
4289 	{ "Micron_M500IT_*",		"MU01",	ATA_QUIRK_NO_NCQ_TRIM |
4290 						ATA_QUIRK_ZERO_AFTER_TRIM },
4291 	{ "Micron_M500_*",		NULL,	ATA_QUIRK_NO_NCQ_TRIM |
4292 						ATA_QUIRK_ZERO_AFTER_TRIM },
4293 	{ "Micron_M5[15]0_*",		"MU01",	ATA_QUIRK_NO_NCQ_TRIM |
4294 						ATA_QUIRK_ZERO_AFTER_TRIM },
4295 	{ "Micron_1100_*",		NULL,	ATA_QUIRK_NO_NCQ_TRIM |
4296 						ATA_QUIRK_ZERO_AFTER_TRIM, },
4297 	{ "Crucial_CT*M500*",		NULL,	ATA_QUIRK_NO_NCQ_TRIM |
4298 						ATA_QUIRK_ZERO_AFTER_TRIM },
4299 	{ "Crucial_CT*M550*",		"MU01",	ATA_QUIRK_NO_NCQ_TRIM |
4300 						ATA_QUIRK_ZERO_AFTER_TRIM },
4301 	{ "Crucial_CT*MX100*",		"MU01",	ATA_QUIRK_NO_NCQ_TRIM |
4302 						ATA_QUIRK_ZERO_AFTER_TRIM },
4303 	{ "Samsung SSD 840 EVO*",	NULL,	ATA_QUIRK_NO_NCQ_TRIM |
4304 						ATA_QUIRK_NO_DMA_LOG |
4305 						ATA_QUIRK_ZERO_AFTER_TRIM },
4306 	{ "Samsung SSD 840*",		NULL,	ATA_QUIRK_NO_NCQ_TRIM |
4307 						ATA_QUIRK_ZERO_AFTER_TRIM },
4308 	{ "Samsung SSD 850*",		NULL,	ATA_QUIRK_NO_NCQ_TRIM |
4309 						ATA_QUIRK_ZERO_AFTER_TRIM },
4310 	{ "Samsung SSD 860*",		NULL,	ATA_QUIRK_NO_NCQ_TRIM |
4311 						ATA_QUIRK_ZERO_AFTER_TRIM |
4312 						ATA_QUIRK_NO_NCQ_ON_ATI |
4313 						ATA_QUIRK_NO_LPM_ON_ATI },
4314 	{ "Samsung SSD 870*",		NULL,	ATA_QUIRK_NO_NCQ_TRIM |
4315 						ATA_QUIRK_ZERO_AFTER_TRIM |
4316 						ATA_QUIRK_NO_NCQ_ON_ATI |
4317 						ATA_QUIRK_NO_LPM_ON_ATI },
4318 	{ "SAMSUNG*MZ7LH*",		NULL,	ATA_QUIRK_NO_NCQ_TRIM |
4319 						ATA_QUIRK_ZERO_AFTER_TRIM |
4320 						ATA_QUIRK_NO_NCQ_ON_ATI |
4321 						ATA_QUIRK_NO_LPM_ON_ATI },
4322 	{ "FCCT*M500*",			NULL,	ATA_QUIRK_NO_NCQ_TRIM |
4323 						ATA_QUIRK_ZERO_AFTER_TRIM },
4324 
4325 	/* devices that don't properly handle TRIM commands */
4326 	{ "SuperSSpeed S238*",		NULL,	ATA_QUIRK_NOTRIM },
4327 	{ "M88V29*",			NULL,	ATA_QUIRK_NOTRIM },
4328 
4329 	/*
4330 	 * As defined, the DRAT (Deterministic Read After Trim) and RZAT
4331 	 * (Return Zero After Trim) flags in the ATA Command Set are
4332 	 * unreliable in the sense that they only define what happens if
4333 	 * the device successfully executed the DSM TRIM command. TRIM
4334 	 * is only advisory, however, and the device is free to silently
4335 	 * ignore all or parts of the request.
4336 	 *
4337 	 * Whitelist drives that are known to reliably return zeroes
4338 	 * after TRIM.
4339 	 */
4340 
4341 	/*
4342 	 * The intel 510 drive has buggy DRAT/RZAT. Explicitly exclude
4343 	 * that model before whitelisting all other intel SSDs.
4344 	 */
4345 	{ "INTEL*SSDSC2MH*",		NULL,	0 },
4346 
4347 	{ "Micron*",			NULL,	ATA_QUIRK_ZERO_AFTER_TRIM },
4348 	{ "Crucial*",			NULL,	ATA_QUIRK_ZERO_AFTER_TRIM },
4349 	{ "INTEL SSDSC2KG480G8", "XCV10120",	ATA_QUIRK_ZERO_AFTER_TRIM |
4350 						ATA_QUIRK_MAX_SEC },
4351 	{ "INTEL*SSD*",			NULL,	ATA_QUIRK_ZERO_AFTER_TRIM },
4352 	{ "SSD*INTEL*",			NULL,	ATA_QUIRK_ZERO_AFTER_TRIM },
4353 	{ "Samsung*SSD*",		NULL,	ATA_QUIRK_ZERO_AFTER_TRIM },
4354 	{ "SAMSUNG*SSD*",		NULL,	ATA_QUIRK_ZERO_AFTER_TRIM },
4355 	{ "SAMSUNG*MZ7KM*",		NULL,	ATA_QUIRK_ZERO_AFTER_TRIM },
4356 	{ "ST[1248][0248]0[FH]*",	NULL,	ATA_QUIRK_ZERO_AFTER_TRIM },
4357 
4358 	/*
4359 	 * Some WD SATA-I drives spin up and down erratically when the link
4360 	 * is put into the slumber mode.  We don't have full list of the
4361 	 * affected devices.  Disable LPM if the device matches one of the
4362 	 * known prefixes and is SATA-1.  As a side effect LPM partial is
4363 	 * lost too.
4364 	 *
4365 	 * https://bugzilla.kernel.org/show_bug.cgi?id=57211
4366 	 */
4367 	{ "WDC WD800JD-*",		NULL,	ATA_QUIRK_WD_BROKEN_LPM },
4368 	{ "WDC WD1200JD-*",		NULL,	ATA_QUIRK_WD_BROKEN_LPM },
4369 	{ "WDC WD1600JD-*",		NULL,	ATA_QUIRK_WD_BROKEN_LPM },
4370 	{ "WDC WD2000JD-*",		NULL,	ATA_QUIRK_WD_BROKEN_LPM },
4371 	{ "WDC WD2500JD-*",		NULL,	ATA_QUIRK_WD_BROKEN_LPM },
4372 	{ "WDC WD3000JD-*",		NULL,	ATA_QUIRK_WD_BROKEN_LPM },
4373 	{ "WDC WD3200JD-*",		NULL,	ATA_QUIRK_WD_BROKEN_LPM },
4374 
4375 	/*
4376 	 * This sata dom device goes on a walkabout when the ATA_LOG_DIRECTORY
4377 	 * log page is accessed. Ensure we never ask for this log page with
4378 	 * these devices.
4379 	 */
4380 	{ "SATADOM-ML 3ME",		NULL,	ATA_QUIRK_NO_LOG_DIR },
4381 
4382 	/* Buggy FUA */
4383 	{ "Maxtor",		"BANC1G10",	ATA_QUIRK_NO_FUA },
4384 	{ "WDC*WD2500J*",	NULL,		ATA_QUIRK_NO_FUA },
4385 	{ "OCZ-VERTEX*",	NULL,		ATA_QUIRK_NO_FUA },
4386 	{ "INTEL*SSDSC2CT*",	NULL,		ATA_QUIRK_NO_FUA },
4387 
4388 	/* End Marker */
4389 	{ }
4390 };
4391 
4392 static u64 ata_dev_quirks(const struct ata_device *dev)
4393 {
4394 	unsigned char model_num[ATA_ID_PROD_LEN + 1];
4395 	unsigned char model_rev[ATA_ID_FW_REV_LEN + 1];
4396 	const struct ata_dev_quirks_entry *ad = __ata_dev_quirks;
4397 
4398 	/* dev->quirks is an u64. */
4399 	BUILD_BUG_ON(__ATA_QUIRK_MAX > 64);
4400 
4401 	ata_id_c_string(dev->id, model_num, ATA_ID_PROD, sizeof(model_num));
4402 	ata_id_c_string(dev->id, model_rev, ATA_ID_FW_REV, sizeof(model_rev));
4403 
4404 	while (ad->model_num) {
4405 		if (glob_match(ad->model_num, model_num) &&
4406 		    (!ad->model_rev || glob_match(ad->model_rev, model_rev))) {
4407 			ata_dev_print_quirks(dev, model_num, model_rev,
4408 					     ad->quirks);
4409 			return ad->quirks;
4410 		}
4411 		ad++;
4412 	}
4413 	return 0;
4414 }
4415 
4416 static u64 ata_dev_get_max_sec_quirk_value(struct ata_device *dev)
4417 {
4418 	unsigned char model_num[ATA_ID_PROD_LEN + 1];
4419 	unsigned char model_rev[ATA_ID_FW_REV_LEN + 1];
4420 	const struct ata_dev_quirk_value *ad = __ata_dev_max_sec_quirks;
4421 	u64 val = 0;
4422 
4423 #ifdef CONFIG_ATA_FORCE
4424 	const struct ata_force_ent *fe = ata_force_get_fe_for_dev(dev);
4425 	if (fe && (fe->param.quirk_on & ATA_QUIRK_MAX_SEC) && fe->param.value)
4426 		val = fe->param.value;
4427 #endif
4428 	if (val)
4429 		goto out;
4430 
4431 	ata_id_c_string(dev->id, model_num, ATA_ID_PROD, sizeof(model_num));
4432 	ata_id_c_string(dev->id, model_rev, ATA_ID_FW_REV, sizeof(model_rev));
4433 
4434 	while (ad->model_num) {
4435 		if (glob_match(ad->model_num, model_num) &&
4436 		    (!ad->model_rev || glob_match(ad->model_rev, model_rev))) {
4437 			val = ad->val;
4438 			break;
4439 		}
4440 		ad++;
4441 	}
4442 
4443 out:
4444 	ata_dev_warn(dev, "%s quirk is using value: %llu\n",
4445 		     ata_quirk_names[__ATA_QUIRK_MAX_SEC], val);
4446 
4447 	return val;
4448 }
4449 
4450 static u64 ata_dev_get_quirk_value(struct ata_device *dev, u64 quirk)
4451 {
4452 	if (quirk == ATA_QUIRK_MAX_SEC)
4453 		return ata_dev_get_max_sec_quirk_value(dev);
4454 
4455 	return 0;
4456 }
4457 
4458 static bool ata_dev_nodma(const struct ata_device *dev)
4459 {
4460 	/*
4461 	 * We do not support polling DMA. Deny DMA for those ATAPI devices
4462 	 * with CDB-intr (and use PIO) if the LLDD handles only interrupts in
4463 	 * the HSM_ST_LAST state.
4464 	 */
4465 	if ((dev->link->ap->flags & ATA_FLAG_PIO_POLLING) &&
4466 	    (dev->flags & ATA_DFLAG_CDB_INTR))
4467 		return true;
4468 	return dev->quirks & ATA_QUIRK_NODMA;
4469 }
4470 
4471 /**
4472  *	ata_is_40wire		-	check drive side detection
4473  *	@dev: device
4474  *
4475  *	Perform drive side detection decoding, allowing for device vendors
4476  *	who can't follow the documentation.
4477  */
4478 
4479 static int ata_is_40wire(struct ata_device *dev)
4480 {
4481 	if (dev->quirks & ATA_QUIRK_IVB)
4482 		return ata_drive_40wire_relaxed(dev->id);
4483 	return ata_drive_40wire(dev->id);
4484 }
4485 
4486 /**
4487  *	cable_is_40wire		-	40/80/SATA decider
4488  *	@ap: port to consider
4489  *
4490  *	This function encapsulates the policy for speed management
4491  *	in one place. At the moment we don't cache the result but
4492  *	there is a good case for setting ap->cbl to the result when
4493  *	we are called with unknown cables (and figuring out if it
4494  *	impacts hotplug at all).
4495  *
4496  *	Return 1 if the cable appears to be 40 wire.
4497  */
4498 
4499 static int cable_is_40wire(struct ata_port *ap)
4500 {
4501 	struct ata_link *link;
4502 	struct ata_device *dev;
4503 
4504 	/* If the controller thinks we are 40 wire, we are. */
4505 	if (ap->cbl == ATA_CBL_PATA40)
4506 		return 1;
4507 
4508 	/* If the controller thinks we are 80 wire, we are. */
4509 	if (ap->cbl == ATA_CBL_PATA80 || ap->cbl == ATA_CBL_SATA)
4510 		return 0;
4511 
4512 	/* If the system is known to be 40 wire short cable (eg
4513 	 * laptop), then we allow 80 wire modes even if the drive
4514 	 * isn't sure.
4515 	 */
4516 	if (ap->cbl == ATA_CBL_PATA40_SHORT)
4517 		return 0;
4518 
4519 	/* If the controller doesn't know, we scan.
4520 	 *
4521 	 * Note: We look for all 40 wire detects at this point.  Any
4522 	 *       80 wire detect is taken to be 80 wire cable because
4523 	 * - in many setups only the one drive (slave if present) will
4524 	 *   give a valid detect
4525 	 * - if you have a non detect capable drive you don't want it
4526 	 *   to colour the choice
4527 	 */
4528 	ata_for_each_link(link, ap, EDGE) {
4529 		ata_for_each_dev(dev, link, ENABLED) {
4530 			if (!ata_is_40wire(dev))
4531 				return 0;
4532 		}
4533 	}
4534 	return 1;
4535 }
4536 
4537 /**
4538  *	ata_dev_xfermask - Compute supported xfermask of the given device
4539  *	@dev: Device to compute xfermask for
4540  *
4541  *	Compute supported xfermask of @dev and store it in
4542  *	dev->*_mask.  This function is responsible for applying all
4543  *	known limits including host controller limits, device quirks, etc...
4544  *
4545  *	LOCKING:
4546  *	None.
4547  */
4548 static void ata_dev_xfermask(struct ata_device *dev)
4549 {
4550 	struct ata_link *link = dev->link;
4551 	struct ata_port *ap = link->ap;
4552 	struct ata_host *host = ap->host;
4553 	unsigned int xfer_mask;
4554 
4555 	/* controller modes available */
4556 	xfer_mask = ata_pack_xfermask(ap->pio_mask,
4557 				      ap->mwdma_mask, ap->udma_mask);
4558 
4559 	/* drive modes available */
4560 	xfer_mask &= ata_pack_xfermask(dev->pio_mask,
4561 				       dev->mwdma_mask, dev->udma_mask);
4562 	xfer_mask &= ata_id_xfermask(dev->id);
4563 
4564 	/*
4565 	 *	CFA Advanced TrueIDE timings are not allowed on a shared
4566 	 *	cable
4567 	 */
4568 	if (ata_dev_pair(dev)) {
4569 		/* No PIO5 or PIO6 */
4570 		xfer_mask &= ~(0x03 << (ATA_SHIFT_PIO + 5));
4571 		/* No MWDMA3 or MWDMA 4 */
4572 		xfer_mask &= ~(0x03 << (ATA_SHIFT_MWDMA + 3));
4573 	}
4574 
4575 	if (ata_dev_nodma(dev)) {
4576 		xfer_mask &= ~(ATA_MASK_MWDMA | ATA_MASK_UDMA);
4577 		ata_dev_warn(dev,
4578 			     "device does not support DMA, disabling DMA\n");
4579 	}
4580 
4581 	if ((host->flags & ATA_HOST_SIMPLEX) &&
4582 	    host->simplex_claimed && host->simplex_claimed != ap) {
4583 		xfer_mask &= ~(ATA_MASK_MWDMA | ATA_MASK_UDMA);
4584 		ata_dev_warn(dev,
4585 			     "simplex DMA is claimed by other device, disabling DMA\n");
4586 	}
4587 
4588 	if (ap->flags & ATA_FLAG_NO_IORDY)
4589 		xfer_mask &= ata_pio_mask_no_iordy(dev);
4590 
4591 	if (ap->ops->mode_filter)
4592 		xfer_mask = ap->ops->mode_filter(dev, xfer_mask);
4593 
4594 	/* Apply cable rule here.  Don't apply it early because when
4595 	 * we handle hot plug the cable type can itself change.
4596 	 * Check this last so that we know if the transfer rate was
4597 	 * solely limited by the cable.
4598 	 * Unknown or 80 wire cables reported host side are checked
4599 	 * drive side as well. Cases where we know a 40wire cable
4600 	 * is used safely for 80 are not checked here.
4601 	 */
4602 	if (xfer_mask & (0xF8 << ATA_SHIFT_UDMA))
4603 		/* UDMA/44 or higher would be available */
4604 		if (cable_is_40wire(ap)) {
4605 			ata_dev_warn(dev,
4606 				     "limited to UDMA/33 due to 40-wire cable\n");
4607 			xfer_mask &= ~(0xF8 << ATA_SHIFT_UDMA);
4608 		}
4609 
4610 	ata_unpack_xfermask(xfer_mask, &dev->pio_mask,
4611 			    &dev->mwdma_mask, &dev->udma_mask);
4612 }
4613 
4614 /**
4615  *	ata_dev_set_xfermode - Issue SET FEATURES - XFER MODE command
4616  *	@dev: Device to which command will be sent
4617  *
4618  *	Issue SET FEATURES - XFER MODE command to device @dev
4619  *	on port @ap.
4620  *
4621  *	LOCKING:
4622  *	PCI/etc. bus probe sem.
4623  *
4624  *	RETURNS:
4625  *	0 on success, AC_ERR_* mask otherwise.
4626  */
4627 
4628 static unsigned int ata_dev_set_xfermode(struct ata_device *dev)
4629 {
4630 	struct ata_taskfile tf;
4631 
4632 	/* set up set-features taskfile */
4633 	ata_dev_dbg(dev, "set features - xfer mode\n");
4634 
4635 	/* Some controllers and ATAPI devices show flaky interrupt
4636 	 * behavior after setting xfer mode.  Use polling instead.
4637 	 */
4638 	ata_tf_init(dev, &tf);
4639 	tf.command = ATA_CMD_SET_FEATURES;
4640 	tf.feature = SETFEATURES_XFER;
4641 	tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE | ATA_TFLAG_POLLING;
4642 	tf.protocol = ATA_PROT_NODATA;
4643 	/* If we are using IORDY we must send the mode setting command */
4644 	if (ata_pio_need_iordy(dev))
4645 		tf.nsect = dev->xfer_mode;
4646 	/* If the device has IORDY and the controller does not - turn it off */
4647  	else if (ata_id_has_iordy(dev->id))
4648 		tf.nsect = 0x01;
4649 	else /* In the ancient relic department - skip all of this */
4650 		return 0;
4651 
4652 	/*
4653 	 * On some disks, this command causes spin-up, so we need longer
4654 	 * timeout.
4655 	 */
4656 	return ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 15000);
4657 }
4658 
4659 /**
4660  *	ata_dev_set_feature - Issue SET FEATURES
4661  *	@dev: Device to which command will be sent
4662  *	@subcmd: The SET FEATURES subcommand to be sent
4663  *	@action: The sector count represents a subcommand specific action
4664  *
4665  *	Issue SET FEATURES command to device @dev on port @ap with sector count
4666  *
4667  *	LOCKING:
4668  *	PCI/etc. bus probe sem.
4669  *
4670  *	RETURNS:
4671  *	0 on success, AC_ERR_* mask otherwise.
4672  */
4673 unsigned int ata_dev_set_feature(struct ata_device *dev, u8 subcmd, u8 action)
4674 {
4675 	struct ata_taskfile tf;
4676 	unsigned int timeout = 0;
4677 
4678 	/* set up set-features taskfile */
4679 	ata_dev_dbg(dev, "set features\n");
4680 
4681 	ata_tf_init(dev, &tf);
4682 	tf.command = ATA_CMD_SET_FEATURES;
4683 	tf.feature = subcmd;
4684 	tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
4685 	tf.protocol = ATA_PROT_NODATA;
4686 	tf.nsect = action;
4687 
4688 	if (subcmd == SETFEATURES_SPINUP)
4689 		timeout = ata_probe_timeout ?
4690 			  ata_probe_timeout * 1000 : SETFEATURES_SPINUP_TIMEOUT;
4691 
4692 	return ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, timeout);
4693 }
4694 EXPORT_SYMBOL_GPL(ata_dev_set_feature);
4695 
4696 /**
4697  *	ata_dev_init_params - Issue INIT DEV PARAMS command
4698  *	@dev: Device to which command will be sent
4699  *	@heads: Number of heads (taskfile parameter)
4700  *	@sectors: Number of sectors (taskfile parameter)
4701  *
4702  *	LOCKING:
4703  *	Kernel thread context (may sleep)
4704  *
4705  *	RETURNS:
4706  *	0 on success, AC_ERR_* mask otherwise.
4707  */
4708 static unsigned int ata_dev_init_params(struct ata_device *dev,
4709 					u16 heads, u16 sectors)
4710 {
4711 	struct ata_taskfile tf;
4712 	unsigned int err_mask;
4713 
4714 	/* Number of sectors per track 1-255. Number of heads 1-16 */
4715 	if (sectors < 1 || sectors > 255 || heads < 1 || heads > 16)
4716 		return AC_ERR_INVALID;
4717 
4718 	/* set up init dev params taskfile */
4719 	ata_dev_dbg(dev, "init dev params\n");
4720 
4721 	ata_tf_init(dev, &tf);
4722 	tf.command = ATA_CMD_INIT_DEV_PARAMS;
4723 	tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
4724 	tf.protocol = ATA_PROT_NODATA;
4725 	tf.nsect = sectors;
4726 	tf.device |= (heads - 1) & 0x0f; /* max head = num. of heads - 1 */
4727 
4728 	err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
4729 	/* A clean abort indicates an original or just out of spec drive
4730 	   and we should continue as we issue the setup based on the
4731 	   drive reported working geometry */
4732 	if (err_mask == AC_ERR_DEV && (tf.error & ATA_ABORTED))
4733 		err_mask = 0;
4734 
4735 	return err_mask;
4736 }
4737 
4738 /**
4739  *	atapi_check_dma - Check whether ATAPI DMA can be supported
4740  *	@qc: Metadata associated with taskfile to check
4741  *
4742  *	Allow low-level driver to filter ATA PACKET commands, returning
4743  *	a status indicating whether or not it is OK to use DMA for the
4744  *	supplied PACKET command.
4745  *
4746  *	LOCKING:
4747  *	spin_lock_irqsave(host lock)
4748  *
4749  *	RETURNS: 0 when ATAPI DMA can be used
4750  *               nonzero otherwise
4751  */
4752 int atapi_check_dma(struct ata_queued_cmd *qc)
4753 {
4754 	struct ata_port *ap = qc->ap;
4755 
4756 	/* Don't allow DMA if it isn't multiple of 16 bytes.  Quite a
4757 	 * few ATAPI devices choke on such DMA requests.
4758 	 */
4759 	if (!(qc->dev->quirks & ATA_QUIRK_ATAPI_MOD16_DMA) &&
4760 	    unlikely(qc->nbytes & 15))
4761 		return -EOPNOTSUPP;
4762 
4763 	if (ap->ops->check_atapi_dma)
4764 		return ap->ops->check_atapi_dma(qc);
4765 
4766 	return 0;
4767 }
4768 
4769 /**
4770  *	ata_std_qc_defer - Check whether a qc needs to be deferred
4771  *	@qc: ATA command in question
4772  *
4773  *	Non-NCQ commands cannot run with any other command, NCQ or
4774  *	not.  As upper layer only knows the queue depth, we are
4775  *	responsible for maintaining exclusion.  This function checks
4776  *	whether a new command @qc can be issued.
4777  *
4778  *	LOCKING:
4779  *	spin_lock_irqsave(host lock)
4780  *
4781  *	RETURNS:
4782  *	ATA_DEFER_* if deferring is needed, 0 otherwise.
4783  */
4784 int ata_std_qc_defer(struct ata_queued_cmd *qc)
4785 {
4786 	struct ata_link *link = qc->dev->link;
4787 
4788 	if (ata_is_ncq(qc->tf.protocol)) {
4789 		if (!ata_tag_valid(link->active_tag))
4790 			return 0;
4791 	} else {
4792 		if (!ata_tag_valid(link->active_tag) && !link->sactive)
4793 			return 0;
4794 	}
4795 
4796 	return ATA_DEFER_LINK;
4797 }
4798 EXPORT_SYMBOL_GPL(ata_std_qc_defer);
4799 
4800 /**
4801  *	ata_sg_init - Associate command with scatter-gather table.
4802  *	@qc: Command to be associated
4803  *	@sg: Scatter-gather table.
4804  *	@n_elem: Number of elements in s/g table.
4805  *
4806  *	Initialize the data-related elements of queued_cmd @qc
4807  *	to point to a scatter-gather table @sg, containing @n_elem
4808  *	elements.
4809  *
4810  *	LOCKING:
4811  *	spin_lock_irqsave(host lock)
4812  */
4813 void ata_sg_init(struct ata_queued_cmd *qc, struct scatterlist *sg,
4814 		 unsigned int n_elem)
4815 {
4816 	qc->sg = sg;
4817 	qc->n_elem = n_elem;
4818 	qc->cursg = qc->sg;
4819 }
4820 
4821 #ifdef CONFIG_HAS_DMA
4822 
4823 /**
4824  *	ata_sg_clean - Unmap DMA memory associated with command
4825  *	@qc: Command containing DMA memory to be released
4826  *
4827  *	Unmap all mapped DMA memory associated with this command.
4828  *
4829  *	LOCKING:
4830  *	spin_lock_irqsave(host lock)
4831  */
4832 static void ata_sg_clean(struct ata_queued_cmd *qc)
4833 {
4834 	struct ata_port *ap = qc->ap;
4835 	struct scatterlist *sg = qc->sg;
4836 	int dir = qc->dma_dir;
4837 
4838 	WARN_ON_ONCE(sg == NULL);
4839 
4840 	if (qc->n_elem)
4841 		dma_unmap_sg(ap->dev, sg, qc->orig_n_elem, dir);
4842 
4843 	qc->flags &= ~ATA_QCFLAG_DMAMAP;
4844 	qc->sg = NULL;
4845 }
4846 
4847 /**
4848  *	ata_sg_setup - DMA-map the scatter-gather table associated with a command.
4849  *	@qc: Command with scatter-gather table to be mapped.
4850  *
4851  *	DMA-map the scatter-gather table associated with queued_cmd @qc.
4852  *
4853  *	LOCKING:
4854  *	spin_lock_irqsave(host lock)
4855  *
4856  *	RETURNS:
4857  *	Zero on success, negative on error.
4858  *
4859  */
4860 static int ata_sg_setup(struct ata_queued_cmd *qc)
4861 {
4862 	struct ata_port *ap = qc->ap;
4863 	unsigned int n_elem;
4864 
4865 	n_elem = dma_map_sg(ap->dev, qc->sg, qc->n_elem, qc->dma_dir);
4866 	if (n_elem < 1)
4867 		return -1;
4868 
4869 	qc->orig_n_elem = qc->n_elem;
4870 	qc->n_elem = n_elem;
4871 	qc->flags |= ATA_QCFLAG_DMAMAP;
4872 
4873 	return 0;
4874 }
4875 
4876 #else /* !CONFIG_HAS_DMA */
4877 
4878 static inline void ata_sg_clean(struct ata_queued_cmd *qc) {}
4879 static inline int ata_sg_setup(struct ata_queued_cmd *qc) { return -1; }
4880 
4881 #endif /* !CONFIG_HAS_DMA */
4882 
4883 /**
4884  *	swap_buf_le16 - swap halves of 16-bit words in place
4885  *	@buf:  Buffer to swap
4886  *	@buf_words:  Number of 16-bit words in buffer.
4887  *
4888  *	Swap halves of 16-bit words if needed to convert from
4889  *	little-endian byte order to native cpu byte order, or
4890  *	vice-versa.
4891  *
4892  *	LOCKING:
4893  *	Inherited from caller.
4894  */
4895 void swap_buf_le16(u16 *buf, unsigned int buf_words)
4896 {
4897 #ifdef __BIG_ENDIAN
4898 	unsigned int i;
4899 
4900 	for (i = 0; i < buf_words; i++)
4901 		buf[i] = le16_to_cpu(buf[i]);
4902 #endif /* __BIG_ENDIAN */
4903 }
4904 
4905 /**
4906  *	ata_qc_free - free unused ata_queued_cmd
4907  *	@qc: Command to complete
4908  *
4909  *	Designed to free unused ata_queued_cmd object
4910  *	in case something prevents using it.
4911  *
4912  *	LOCKING:
4913  *	spin_lock_irqsave(host lock)
4914  */
4915 void ata_qc_free(struct ata_queued_cmd *qc)
4916 {
4917 	qc->flags = 0;
4918 	if (ata_tag_valid(qc->tag))
4919 		qc->tag = ATA_TAG_POISON;
4920 }
4921 
4922 void __ata_qc_complete(struct ata_queued_cmd *qc)
4923 {
4924 	struct ata_port *ap;
4925 	struct ata_link *link;
4926 
4927 	if (WARN_ON_ONCE(!(qc->flags & ATA_QCFLAG_ACTIVE)))
4928 		return;
4929 
4930 	ap = qc->ap;
4931 	link = qc->dev->link;
4932 
4933 	if (likely(qc->flags & ATA_QCFLAG_DMAMAP))
4934 		ata_sg_clean(qc);
4935 
4936 	/* command should be marked inactive atomically with qc completion */
4937 	if (ata_is_ncq(qc->tf.protocol)) {
4938 		link->sactive &= ~(1 << qc->hw_tag);
4939 		if (!link->sactive)
4940 			ap->nr_active_links--;
4941 	} else {
4942 		link->active_tag = ATA_TAG_POISON;
4943 		ap->nr_active_links--;
4944 	}
4945 
4946 	/* clear exclusive status */
4947 	if (unlikely(qc->flags & ATA_QCFLAG_CLEAR_EXCL &&
4948 		     ap->excl_link == link))
4949 		ap->excl_link = NULL;
4950 
4951 	/*
4952 	 * Mark qc as inactive to prevent the port interrupt handler from
4953 	 * completing the command twice later, before the error handler is
4954 	 * called.
4955 	 */
4956 	qc->flags &= ~ATA_QCFLAG_ACTIVE;
4957 	ap->qc_active &= ~(1ULL << qc->tag);
4958 
4959 	/* call completion callback */
4960 	qc->complete_fn(qc);
4961 }
4962 
4963 static void fill_result_tf(struct ata_queued_cmd *qc)
4964 {
4965 	struct ata_port *ap = qc->ap;
4966 
4967 	/*
4968 	 * rtf may already be filled (e.g. for successful NCQ commands).
4969 	 * If that is the case, we have nothing to do.
4970 	 */
4971 	if (qc->flags & ATA_QCFLAG_RTF_FILLED)
4972 		return;
4973 
4974 	qc->result_tf.flags = qc->tf.flags;
4975 	ap->ops->qc_fill_rtf(qc);
4976 	qc->flags |= ATA_QCFLAG_RTF_FILLED;
4977 }
4978 
4979 static void ata_verify_xfer(struct ata_queued_cmd *qc)
4980 {
4981 	struct ata_device *dev = qc->dev;
4982 
4983 	if (!ata_is_data(qc->tf.protocol))
4984 		return;
4985 
4986 	if ((dev->mwdma_mask || dev->udma_mask) && ata_is_pio(qc->tf.protocol))
4987 		return;
4988 
4989 	dev->flags &= ~ATA_DFLAG_DUBIOUS_XFER;
4990 }
4991 
4992 /**
4993  *	ata_qc_complete - Complete an active ATA command
4994  *	@qc: Command to complete
4995  *
4996  *	Indicate to the mid and upper layers that an ATA command has
4997  *	completed, with either an ok or not-ok status.
4998  *
4999  *	Refrain from calling this function multiple times when
5000  *	successfully completing multiple NCQ commands.
5001  *	ata_qc_complete_multiple() should be used instead, which will
5002  *	properly update IRQ expect state.
5003  *
5004  *	LOCKING:
5005  *	spin_lock_irqsave(host lock)
5006  */
5007 void ata_qc_complete(struct ata_queued_cmd *qc)
5008 {
5009 	struct ata_port *ap = qc->ap;
5010 	struct ata_device *dev = qc->dev;
5011 	struct ata_eh_info *ehi = &dev->link->eh_info;
5012 
5013 	/* Trigger the LED (if available) */
5014 	ledtrig_disk_activity(!!(qc->tf.flags & ATA_TFLAG_WRITE));
5015 
5016 	/*
5017 	 * In order to synchronize EH with the regular execution path, a qc that
5018 	 * is owned by EH is marked with ATA_QCFLAG_EH.
5019 	 *
5020 	 * The normal execution path is responsible for not accessing a qc owned
5021 	 * by EH.  libata core enforces the rule by returning NULL from
5022 	 * ata_qc_from_tag() for qcs owned by EH.
5023 	 */
5024 	if (unlikely(qc->err_mask))
5025 		qc->flags |= ATA_QCFLAG_EH;
5026 
5027 	/*
5028 	 * Finish internal commands without any further processing and always
5029 	 * with the result TF filled.
5030 	 */
5031 	if (unlikely(ata_tag_internal(qc->tag))) {
5032 		fill_result_tf(qc);
5033 		trace_ata_qc_complete_internal(qc);
5034 		__ata_qc_complete(qc);
5035 		return;
5036 	}
5037 
5038 	/* Non-internal qc has failed.  Fill the result TF and summon EH. */
5039 	if (unlikely(qc->flags & ATA_QCFLAG_EH)) {
5040 		fill_result_tf(qc);
5041 		trace_ata_qc_complete_failed(qc);
5042 		ata_qc_schedule_eh(qc);
5043 		return;
5044 	}
5045 
5046 	WARN_ON_ONCE(ata_port_is_frozen(ap));
5047 
5048 	/* read result TF if requested */
5049 	if (qc->flags & ATA_QCFLAG_RESULT_TF)
5050 		fill_result_tf(qc);
5051 
5052 	trace_ata_qc_complete_done(qc);
5053 
5054 	/*
5055 	 * For CDL commands that completed without an error, check if we have
5056 	 * sense data (ATA_SENSE is set). If we do, then the command may have
5057 	 * been aborted by the device due to a limit timeout using the policy
5058 	 * 0xD. For these commands, invoke EH to get the command sense data.
5059 	 */
5060 	if (qc->flags & ATA_QCFLAG_HAS_CDL &&
5061 	    qc->result_tf.status & ATA_SENSE) {
5062 		/*
5063 		 * Tell SCSI EH to not overwrite scmd->result even if this
5064 		 * command is finished with result SAM_STAT_GOOD.
5065 		 */
5066 		qc->scsicmd->flags |= SCMD_FORCE_EH_SUCCESS;
5067 		qc->flags |= ATA_QCFLAG_EH_SUCCESS_CMD;
5068 		ehi->dev_action[dev->devno] |= ATA_EH_GET_SUCCESS_SENSE;
5069 
5070 		/*
5071 		 * set pending so that ata_qc_schedule_eh() does not trigger
5072 		 * fast drain, and freeze the port.
5073 		 */
5074 		ap->pflags |= ATA_PFLAG_EH_PENDING;
5075 		ata_qc_schedule_eh(qc);
5076 		return;
5077 	}
5078 
5079 	/* Some commands need post-processing after successful completion. */
5080 	switch (qc->tf.command) {
5081 	case ATA_CMD_SET_FEATURES:
5082 		if (qc->tf.feature != SETFEATURES_WC_ON &&
5083 		    qc->tf.feature != SETFEATURES_WC_OFF &&
5084 		    qc->tf.feature != SETFEATURES_RA_ON &&
5085 		    qc->tf.feature != SETFEATURES_RA_OFF)
5086 			break;
5087 		fallthrough;
5088 	case ATA_CMD_INIT_DEV_PARAMS: /* CHS translation changed */
5089 	case ATA_CMD_SET_MULTI: /* multi_count changed */
5090 		/* revalidate device */
5091 		ehi->dev_action[dev->devno] |= ATA_EH_REVALIDATE;
5092 		ata_port_schedule_eh(ap);
5093 		break;
5094 
5095 	case ATA_CMD_SLEEP:
5096 		dev->flags |= ATA_DFLAG_SLEEPING;
5097 		break;
5098 	}
5099 
5100 	if (unlikely(dev->flags & ATA_DFLAG_DUBIOUS_XFER))
5101 		ata_verify_xfer(qc);
5102 
5103 	__ata_qc_complete(qc);
5104 }
5105 EXPORT_SYMBOL_GPL(ata_qc_complete);
5106 
5107 /**
5108  *	ata_qc_get_active - get bitmask of active qcs
5109  *	@ap: port in question
5110  *
5111  *	LOCKING:
5112  *	spin_lock_irqsave(host lock)
5113  *
5114  *	RETURNS:
5115  *	Bitmask of active qcs
5116  */
5117 u64 ata_qc_get_active(struct ata_port *ap)
5118 {
5119 	u64 qc_active = ap->qc_active;
5120 
5121 	/* ATA_TAG_INTERNAL is sent to hw as tag 0 */
5122 	if (qc_active & (1ULL << ATA_TAG_INTERNAL)) {
5123 		qc_active |= (1 << 0);
5124 		qc_active &= ~(1ULL << ATA_TAG_INTERNAL);
5125 	}
5126 
5127 	return qc_active;
5128 }
5129 EXPORT_SYMBOL_GPL(ata_qc_get_active);
5130 
5131 /**
5132  *	ata_qc_issue - issue taskfile to device
5133  *	@qc: command to issue to device
5134  *
5135  *	Prepare an ATA command to submission to device.
5136  *	This includes mapping the data into a DMA-able
5137  *	area, filling in the S/G table, and finally
5138  *	writing the taskfile to hardware, starting the command.
5139  *
5140  *	LOCKING:
5141  *	spin_lock_irqsave(host lock)
5142  */
5143 void ata_qc_issue(struct ata_queued_cmd *qc)
5144 {
5145 	struct ata_port *ap = qc->ap;
5146 	struct ata_link *link = qc->dev->link;
5147 	u8 prot = qc->tf.protocol;
5148 
5149 	/* Make sure only one non-NCQ command is outstanding. */
5150 	WARN_ON_ONCE(ata_tag_valid(link->active_tag));
5151 
5152 	if (ata_is_ncq(prot)) {
5153 		WARN_ON_ONCE(link->sactive & (1 << qc->hw_tag));
5154 
5155 		if (!link->sactive)
5156 			ap->nr_active_links++;
5157 		link->sactive |= 1 << qc->hw_tag;
5158 	} else {
5159 		WARN_ON_ONCE(link->sactive);
5160 
5161 		ap->nr_active_links++;
5162 		link->active_tag = qc->tag;
5163 	}
5164 
5165 	qc->flags |= ATA_QCFLAG_ACTIVE;
5166 	ap->qc_active |= 1ULL << qc->tag;
5167 
5168 	/* Make sure the device is still accessible. */
5169 	if (!ata_adapter_is_online(ap)) {
5170 		qc->err_mask |= AC_ERR_HOST_BUS;
5171 		goto sys_err;
5172 	}
5173 
5174 	/*
5175 	 * We guarantee to LLDs that they will have at least one
5176 	 * non-zero sg if the command is a data command.
5177 	 */
5178 	if (ata_is_data(prot) && (!qc->sg || !qc->n_elem || !qc->nbytes))
5179 		goto sys_err;
5180 
5181 	if (ata_is_dma(prot) || (ata_is_pio(prot) &&
5182 				 (ap->flags & ATA_FLAG_PIO_DMA)))
5183 		if (ata_sg_setup(qc))
5184 			goto sys_err;
5185 
5186 	/* if device is sleeping, schedule reset and abort the link */
5187 	if (unlikely(qc->dev->flags & ATA_DFLAG_SLEEPING)) {
5188 		link->eh_info.action |= ATA_EH_RESET;
5189 		ata_ehi_push_desc(&link->eh_info, "waking up from sleep");
5190 		ata_link_abort(link);
5191 		return;
5192 	}
5193 
5194 	if (ap->ops->qc_prep) {
5195 		trace_ata_qc_prep(qc);
5196 		qc->err_mask |= ap->ops->qc_prep(qc);
5197 		if (unlikely(qc->err_mask))
5198 			goto err;
5199 	}
5200 
5201 	trace_ata_qc_issue(qc);
5202 	qc->err_mask |= ap->ops->qc_issue(qc);
5203 	if (unlikely(qc->err_mask))
5204 		goto err;
5205 	return;
5206 
5207 sys_err:
5208 	qc->err_mask |= AC_ERR_SYSTEM;
5209 err:
5210 	ata_qc_complete(qc);
5211 }
5212 
5213 /**
5214  *	ata_phys_link_online - test whether the given link is online
5215  *	@link: ATA link to test
5216  *
5217  *	Test whether @link is online.  Note that this function returns
5218  *	0 if online status of @link cannot be obtained, so
5219  *	ata_link_online(link) != !ata_link_offline(link).
5220  *
5221  *	LOCKING:
5222  *	None.
5223  *
5224  *	RETURNS:
5225  *	True if the port online status is available and online.
5226  */
5227 bool ata_phys_link_online(struct ata_link *link)
5228 {
5229 	u32 sstatus;
5230 
5231 	if (sata_scr_read(link, SCR_STATUS, &sstatus) == 0 &&
5232 	    ata_sstatus_online(sstatus))
5233 		return true;
5234 	return false;
5235 }
5236 
5237 /**
5238  *	ata_phys_link_offline - test whether the given link is offline
5239  *	@link: ATA link to test
5240  *
5241  *	Test whether @link is offline.  Note that this function
5242  *	returns 0 if offline status of @link cannot be obtained, so
5243  *	ata_link_online(link) != !ata_link_offline(link).
5244  *
5245  *	LOCKING:
5246  *	None.
5247  *
5248  *	RETURNS:
5249  *	True if the port offline status is available and offline.
5250  */
5251 bool ata_phys_link_offline(struct ata_link *link)
5252 {
5253 	u32 sstatus;
5254 
5255 	if (sata_scr_read(link, SCR_STATUS, &sstatus) == 0 &&
5256 	    !ata_sstatus_online(sstatus))
5257 		return true;
5258 	return false;
5259 }
5260 
5261 /**
5262  *	ata_link_online - test whether the given link is online
5263  *	@link: ATA link to test
5264  *
5265  *	Test whether @link is online.  This is identical to
5266  *	ata_phys_link_online() when there's no slave link.  When
5267  *	there's a slave link, this function should only be called on
5268  *	the master link and will return true if any of M/S links is
5269  *	online.
5270  *
5271  *	LOCKING:
5272  *	None.
5273  *
5274  *	RETURNS:
5275  *	True if the port online status is available and online.
5276  */
5277 bool ata_link_online(struct ata_link *link)
5278 {
5279 	struct ata_link *slave = link->ap->slave_link;
5280 
5281 	WARN_ON(link == slave);	/* shouldn't be called on slave link */
5282 
5283 	return ata_phys_link_online(link) ||
5284 		(slave && ata_phys_link_online(slave));
5285 }
5286 EXPORT_SYMBOL_GPL(ata_link_online);
5287 
5288 /**
5289  *	ata_link_offline - test whether the given link is offline
5290  *	@link: ATA link to test
5291  *
5292  *	Test whether @link is offline.  This is identical to
5293  *	ata_phys_link_offline() when there's no slave link.  When
5294  *	there's a slave link, this function should only be called on
5295  *	the master link and will return true if both M/S links are
5296  *	offline.
5297  *
5298  *	LOCKING:
5299  *	None.
5300  *
5301  *	RETURNS:
5302  *	True if the port offline status is available and offline.
5303  */
5304 bool ata_link_offline(struct ata_link *link)
5305 {
5306 	struct ata_link *slave = link->ap->slave_link;
5307 
5308 	WARN_ON(link == slave);	/* shouldn't be called on slave link */
5309 
5310 	return ata_phys_link_offline(link) &&
5311 		(!slave || ata_phys_link_offline(slave));
5312 }
5313 EXPORT_SYMBOL_GPL(ata_link_offline);
5314 
5315 #ifdef CONFIG_PM
5316 static void ata_port_request_pm(struct ata_port *ap, pm_message_t mesg,
5317 				unsigned int action, unsigned int ehi_flags,
5318 				bool async)
5319 {
5320 	struct ata_link *link;
5321 	unsigned long flags;
5322 
5323 	spin_lock_irqsave(ap->lock, flags);
5324 
5325 	/*
5326 	 * A previous PM operation might still be in progress. Wait for
5327 	 * ATA_PFLAG_PM_PENDING to clear.
5328 	 */
5329 	if (ap->pflags & ATA_PFLAG_PM_PENDING) {
5330 		spin_unlock_irqrestore(ap->lock, flags);
5331 		ata_port_wait_eh(ap);
5332 		spin_lock_irqsave(ap->lock, flags);
5333 	}
5334 
5335 	/* Request PM operation to EH */
5336 	ap->pm_mesg = mesg;
5337 	ap->pflags |= ATA_PFLAG_PM_PENDING;
5338 	ata_for_each_link(link, ap, HOST_FIRST) {
5339 		link->eh_info.action |= action;
5340 		link->eh_info.flags |= ehi_flags;
5341 	}
5342 
5343 	ata_port_schedule_eh(ap);
5344 
5345 	spin_unlock_irqrestore(ap->lock, flags);
5346 
5347 	if (!async)
5348 		ata_port_wait_eh(ap);
5349 }
5350 
5351 static void ata_port_suspend(struct ata_port *ap, pm_message_t mesg,
5352 			     bool async)
5353 {
5354 	/*
5355 	 * We are about to suspend the port, so we do not care about
5356 	 * scsi_rescan_device() calls scheduled by previous resume operations.
5357 	 * The next resume will schedule the rescan again. So cancel any rescan
5358 	 * that is not done yet.
5359 	 */
5360 	cancel_delayed_work_sync(&ap->scsi_rescan_task);
5361 
5362 	/*
5363 	 * On some hardware, device fails to respond after spun down for
5364 	 * suspend. As the device will not be used until being resumed, we
5365 	 * do not need to touch the device. Ask EH to skip the usual stuff
5366 	 * and proceed directly to suspend.
5367 	 *
5368 	 * http://thread.gmane.org/gmane.linux.ide/46764
5369 	 */
5370 	ata_port_request_pm(ap, mesg, 0,
5371 			    ATA_EHI_QUIET | ATA_EHI_NO_AUTOPSY |
5372 			    ATA_EHI_NO_RECOVERY,
5373 			    async);
5374 }
5375 
5376 static int ata_port_pm_suspend(struct device *dev)
5377 {
5378 	struct ata_port *ap = to_ata_port(dev);
5379 
5380 	if (pm_runtime_suspended(dev))
5381 		return 0;
5382 
5383 	ata_port_suspend(ap, PMSG_SUSPEND, false);
5384 	return 0;
5385 }
5386 
5387 static int ata_port_pm_freeze(struct device *dev)
5388 {
5389 	struct ata_port *ap = to_ata_port(dev);
5390 
5391 	if (pm_runtime_suspended(dev))
5392 		return 0;
5393 
5394 	ata_port_suspend(ap, PMSG_FREEZE, false);
5395 	return 0;
5396 }
5397 
5398 static int ata_port_pm_poweroff(struct device *dev)
5399 {
5400 	if (!pm_runtime_suspended(dev))
5401 		ata_port_suspend(to_ata_port(dev), PMSG_HIBERNATE, false);
5402 	return 0;
5403 }
5404 
5405 static void ata_port_resume(struct ata_port *ap, pm_message_t mesg,
5406 			    bool async)
5407 {
5408 	ata_port_request_pm(ap, mesg, ATA_EH_RESET,
5409 			    ATA_EHI_NO_AUTOPSY | ATA_EHI_QUIET,
5410 			    async);
5411 }
5412 
5413 static int ata_port_pm_resume(struct device *dev)
5414 {
5415 	if (!pm_runtime_suspended(dev))
5416 		ata_port_resume(to_ata_port(dev), PMSG_RESUME, true);
5417 	return 0;
5418 }
5419 
5420 /*
5421  * For ODDs, the upper layer will poll for media change every few seconds,
5422  * which will make it enter and leave suspend state every few seconds. And
5423  * as each suspend will cause a hard/soft reset, the gain of runtime suspend
5424  * is very little and the ODD may malfunction after constantly being reset.
5425  * So the idle callback here will not proceed to suspend if a non-ZPODD capable
5426  * ODD is attached to the port.
5427  */
5428 static int ata_port_runtime_idle(struct device *dev)
5429 {
5430 	struct ata_port *ap = to_ata_port(dev);
5431 	struct ata_link *link;
5432 	struct ata_device *adev;
5433 
5434 	ata_for_each_link(link, ap, HOST_FIRST) {
5435 		ata_for_each_dev(adev, link, ENABLED)
5436 			if (adev->class == ATA_DEV_ATAPI &&
5437 			    !zpodd_dev_enabled(adev))
5438 				return -EBUSY;
5439 	}
5440 
5441 	return 0;
5442 }
5443 
5444 static int ata_port_runtime_suspend(struct device *dev)
5445 {
5446 	ata_port_suspend(to_ata_port(dev), PMSG_AUTO_SUSPEND, false);
5447 	return 0;
5448 }
5449 
5450 static int ata_port_runtime_resume(struct device *dev)
5451 {
5452 	ata_port_resume(to_ata_port(dev), PMSG_AUTO_RESUME, false);
5453 	return 0;
5454 }
5455 
5456 static const struct dev_pm_ops ata_port_pm_ops = {
5457 	.suspend = ata_port_pm_suspend,
5458 	.resume = ata_port_pm_resume,
5459 	.freeze = ata_port_pm_freeze,
5460 	.thaw = ata_port_pm_resume,
5461 	.poweroff = ata_port_pm_poweroff,
5462 	.restore = ata_port_pm_resume,
5463 
5464 	.runtime_suspend = ata_port_runtime_suspend,
5465 	.runtime_resume = ata_port_runtime_resume,
5466 	.runtime_idle = ata_port_runtime_idle,
5467 };
5468 
5469 /* sas ports don't participate in pm runtime management of ata_ports,
5470  * and need to resume ata devices at the domain level, not the per-port
5471  * level. sas suspend/resume is async to allow parallel port recovery
5472  * since sas has multiple ata_port instances per Scsi_Host.
5473  */
5474 void ata_sas_port_suspend(struct ata_port *ap)
5475 {
5476 	ata_port_suspend(ap, PMSG_SUSPEND, true);
5477 }
5478 EXPORT_SYMBOL_GPL(ata_sas_port_suspend);
5479 
5480 void ata_sas_port_resume(struct ata_port *ap)
5481 {
5482 	ata_port_resume(ap, PMSG_RESUME, true);
5483 }
5484 EXPORT_SYMBOL_GPL(ata_sas_port_resume);
5485 
5486 /**
5487  *	ata_host_suspend - suspend host
5488  *	@host: host to suspend
5489  *	@mesg: PM message
5490  *
5491  *	Suspend @host.  Actual operation is performed by port suspend.
5492  */
5493 void ata_host_suspend(struct ata_host *host, pm_message_t mesg)
5494 {
5495 	host->dev->power.power_state = mesg;
5496 }
5497 EXPORT_SYMBOL_GPL(ata_host_suspend);
5498 
5499 /**
5500  *	ata_host_resume - resume host
5501  *	@host: host to resume
5502  *
5503  *	Resume @host.  Actual operation is performed by port resume.
5504  */
5505 void ata_host_resume(struct ata_host *host)
5506 {
5507 	host->dev->power.power_state = PMSG_ON;
5508 }
5509 EXPORT_SYMBOL_GPL(ata_host_resume);
5510 #endif
5511 
5512 const struct device_type ata_port_type = {
5513 	.name = ATA_PORT_TYPE_NAME,
5514 #ifdef CONFIG_PM
5515 	.pm = &ata_port_pm_ops,
5516 #endif
5517 };
5518 
5519 /**
5520  *	ata_dev_init - Initialize an ata_device structure
5521  *	@dev: Device structure to initialize
5522  *
5523  *	Initialize @dev in preparation for probing.
5524  *
5525  *	LOCKING:
5526  *	Inherited from caller.
5527  */
5528 void ata_dev_init(struct ata_device *dev)
5529 {
5530 	struct ata_link *link = ata_dev_phys_link(dev);
5531 	struct ata_port *ap = link->ap;
5532 	unsigned long flags;
5533 
5534 	/* SATA spd limit is bound to the attached device, reset together */
5535 	link->sata_spd_limit = link->hw_sata_spd_limit;
5536 	link->sata_spd = 0;
5537 
5538 	/* High bits of dev->flags are used to record warm plug
5539 	 * requests which occur asynchronously.  Synchronize using
5540 	 * host lock.
5541 	 */
5542 	spin_lock_irqsave(ap->lock, flags);
5543 	dev->flags &= ~ATA_DFLAG_INIT_MASK;
5544 	dev->quirks = 0;
5545 	spin_unlock_irqrestore(ap->lock, flags);
5546 
5547 	memset((void *)dev + ATA_DEVICE_CLEAR_BEGIN, 0,
5548 	       ATA_DEVICE_CLEAR_END - ATA_DEVICE_CLEAR_BEGIN);
5549 	dev->pio_mask = UINT_MAX;
5550 	dev->mwdma_mask = UINT_MAX;
5551 	dev->udma_mask = UINT_MAX;
5552 }
5553 
5554 /**
5555  *	ata_link_init - Initialize an ata_link structure
5556  *	@ap: ATA port link is attached to
5557  *	@link: Link structure to initialize
5558  *	@pmp: Port multiplier port number
5559  *
5560  *	Initialize @link.
5561  *
5562  *	LOCKING:
5563  *	Kernel thread context (may sleep)
5564  */
5565 void ata_link_init(struct ata_port *ap, struct ata_link *link, int pmp)
5566 {
5567 	int i;
5568 
5569 	/* clear everything except for devices */
5570 	memset((void *)link + ATA_LINK_CLEAR_BEGIN, 0,
5571 	       ATA_LINK_CLEAR_END - ATA_LINK_CLEAR_BEGIN);
5572 
5573 	link->ap = ap;
5574 	link->pmp = pmp;
5575 	link->active_tag = ATA_TAG_POISON;
5576 	link->hw_sata_spd_limit = UINT_MAX;
5577 
5578 	/* can't use iterator, ap isn't initialized yet */
5579 	for (i = 0; i < ATA_MAX_DEVICES; i++) {
5580 		struct ata_device *dev = &link->device[i];
5581 
5582 		dev->link = link;
5583 		dev->devno = dev - link->device;
5584 #ifdef CONFIG_ATA_ACPI
5585 		dev->gtf_filter = ata_acpi_gtf_filter;
5586 #endif
5587 		ata_dev_init(dev);
5588 	}
5589 }
5590 
5591 /**
5592  *	sata_link_init_spd - Initialize link->sata_spd_limit
5593  *	@link: Link to configure sata_spd_limit for
5594  *
5595  *	Initialize ``link->[hw_]sata_spd_limit`` to the currently
5596  *	configured value.
5597  *
5598  *	LOCKING:
5599  *	Kernel thread context (may sleep).
5600  *
5601  *	RETURNS:
5602  *	0 on success, -errno on failure.
5603  */
5604 int sata_link_init_spd(struct ata_link *link)
5605 {
5606 	u8 spd;
5607 	int rc;
5608 
5609 	rc = sata_scr_read(link, SCR_CONTROL, &link->saved_scontrol);
5610 	if (rc)
5611 		return rc;
5612 
5613 	spd = (link->saved_scontrol >> 4) & 0xf;
5614 	if (spd)
5615 		link->hw_sata_spd_limit &= (1 << spd) - 1;
5616 
5617 	ata_force_link_limits(link);
5618 
5619 	link->sata_spd_limit = link->hw_sata_spd_limit;
5620 
5621 	return 0;
5622 }
5623 
5624 /**
5625  *	ata_port_alloc - allocate and initialize basic ATA port resources
5626  *	@host: ATA host this allocated port belongs to
5627  *
5628  *	Allocate and initialize basic ATA port resources.
5629  *
5630  *	RETURNS:
5631  *	Allocate ATA port on success, NULL on failure.
5632  *
5633  *	LOCKING:
5634  *	Inherited from calling layer (may sleep).
5635  */
5636 struct ata_port *ata_port_alloc(struct ata_host *host)
5637 {
5638 	struct ata_port *ap;
5639 	int id;
5640 
5641 	ap = kzalloc(sizeof(*ap), GFP_KERNEL);
5642 	if (!ap)
5643 		return NULL;
5644 
5645 	ap->pflags |= ATA_PFLAG_INITIALIZING | ATA_PFLAG_FROZEN;
5646 	ap->lock = &host->lock;
5647 	id = ida_alloc_min(&ata_ida, 1, GFP_KERNEL);
5648 	if (id < 0) {
5649 		kfree(ap);
5650 		return NULL;
5651 	}
5652 	ap->print_id = id;
5653 	ap->host = host;
5654 	ap->dev = host->dev;
5655 
5656 	mutex_init(&ap->scsi_scan_mutex);
5657 	INIT_DELAYED_WORK(&ap->hotplug_task, ata_scsi_hotplug);
5658 	INIT_DELAYED_WORK(&ap->scsi_rescan_task, ata_scsi_dev_rescan);
5659 	INIT_WORK(&ap->deferred_qc_work, ata_scsi_deferred_qc_work);
5660 	INIT_LIST_HEAD(&ap->eh_done_q);
5661 	init_waitqueue_head(&ap->eh_wait_q);
5662 	init_completion(&ap->park_req_pending);
5663 	timer_setup(&ap->fastdrain_timer, ata_eh_fastdrain_timerfn,
5664 		    TIMER_DEFERRABLE);
5665 
5666 	ap->cbl = ATA_CBL_NONE;
5667 
5668 	ata_link_init(ap, &ap->link, 0);
5669 
5670 #ifdef ATA_IRQ_TRAP
5671 	ap->stats.unhandled_irq = 1;
5672 	ap->stats.idle_irq = 1;
5673 #endif
5674 	ata_sff_port_init(ap);
5675 
5676 	ata_force_pflags(ap);
5677 
5678 	return ap;
5679 }
5680 EXPORT_SYMBOL_GPL(ata_port_alloc);
5681 
5682 void ata_port_free(struct ata_port *ap)
5683 {
5684 	if (!ap)
5685 		return;
5686 
5687 	kfree(ap->pmp_link);
5688 	kfree(ap->slave_link);
5689 	ida_free(&ata_ida, ap->print_id);
5690 	kfree(ap);
5691 }
5692 EXPORT_SYMBOL_GPL(ata_port_free);
5693 
5694 static void ata_devres_release(struct device *gendev, void *res)
5695 {
5696 	struct ata_host *host = dev_get_drvdata(gendev);
5697 	int i;
5698 
5699 	for (i = 0; i < host->n_ports; i++) {
5700 		struct ata_port *ap = host->ports[i];
5701 
5702 		if (!ap)
5703 			continue;
5704 
5705 		if (ap->scsi_host)
5706 			scsi_host_put(ap->scsi_host);
5707 
5708 	}
5709 
5710 	dev_set_drvdata(gendev, NULL);
5711 	ata_host_put(host);
5712 }
5713 
5714 static void ata_host_release(struct kref *kref)
5715 {
5716 	struct ata_host *host = container_of(kref, struct ata_host, kref);
5717 	int i;
5718 
5719 	for (i = 0; i < host->n_ports; i++) {
5720 		ata_port_free(host->ports[i]);
5721 		host->ports[i] = NULL;
5722 	}
5723 	kfree(host);
5724 }
5725 
5726 void ata_host_get(struct ata_host *host)
5727 {
5728 	kref_get(&host->kref);
5729 }
5730 
5731 void ata_host_put(struct ata_host *host)
5732 {
5733 	kref_put(&host->kref, ata_host_release);
5734 }
5735 EXPORT_SYMBOL_GPL(ata_host_put);
5736 
5737 /**
5738  *	ata_host_alloc - allocate and init basic ATA host resources
5739  *	@dev: generic device this host is associated with
5740  *	@n_ports: the number of ATA ports associated with this host
5741  *
5742  *	Allocate and initialize basic ATA host resources.  LLD calls
5743  *	this function to allocate a host, initializes it fully and
5744  *	attaches it using ata_host_register().
5745  *
5746  *	RETURNS:
5747  *	Allocate ATA host on success, NULL on failure.
5748  *
5749  *	LOCKING:
5750  *	Inherited from calling layer (may sleep).
5751  */
5752 struct ata_host *ata_host_alloc(struct device *dev, int n_ports)
5753 {
5754 	struct ata_host *host;
5755 	size_t sz;
5756 	int i;
5757 	void *dr;
5758 
5759 	/* alloc a container for our list of ATA ports (buses) */
5760 	sz = sizeof(struct ata_host) + n_ports * sizeof(void *);
5761 	host = kzalloc(sz, GFP_KERNEL);
5762 	if (!host)
5763 		return NULL;
5764 
5765 	if (!devres_open_group(dev, NULL, GFP_KERNEL)) {
5766 		kfree(host);
5767 		return NULL;
5768 	}
5769 
5770 	dr = devres_alloc(ata_devres_release, 0, GFP_KERNEL);
5771 	if (!dr) {
5772 		kfree(host);
5773 		goto err_out;
5774 	}
5775 
5776 	devres_add(dev, dr);
5777 	dev_set_drvdata(dev, host);
5778 
5779 	spin_lock_init(&host->lock);
5780 	mutex_init(&host->eh_mutex);
5781 	host->dev = dev;
5782 	host->n_ports = n_ports;
5783 	kref_init(&host->kref);
5784 
5785 	/* allocate ports bound to this host */
5786 	for (i = 0; i < n_ports; i++) {
5787 		struct ata_port *ap;
5788 
5789 		ap = ata_port_alloc(host);
5790 		if (!ap)
5791 			goto err_out;
5792 
5793 		ap->port_no = i;
5794 		host->ports[i] = ap;
5795 	}
5796 
5797 	devres_remove_group(dev, NULL);
5798 	return host;
5799 
5800  err_out:
5801 	devres_release_group(dev, NULL);
5802 	return NULL;
5803 }
5804 EXPORT_SYMBOL_GPL(ata_host_alloc);
5805 
5806 /**
5807  *	ata_host_alloc_pinfo - alloc host and init with port_info array
5808  *	@dev: generic device this host is associated with
5809  *	@ppi: array of ATA port_info to initialize host with
5810  *	@n_ports: number of ATA ports attached to this host
5811  *
5812  *	Allocate ATA host and initialize with info from @ppi.  If NULL
5813  *	terminated, @ppi may contain fewer entries than @n_ports.  The
5814  *	last entry will be used for the remaining ports.
5815  *
5816  *	RETURNS:
5817  *	Allocate ATA host on success, NULL on failure.
5818  *
5819  *	LOCKING:
5820  *	Inherited from calling layer (may sleep).
5821  */
5822 struct ata_host *ata_host_alloc_pinfo(struct device *dev,
5823 				      const struct ata_port_info * const * ppi,
5824 				      int n_ports)
5825 {
5826 	const struct ata_port_info *pi = &ata_dummy_port_info;
5827 	struct ata_host *host;
5828 	int i, j;
5829 
5830 	host = ata_host_alloc(dev, n_ports);
5831 	if (!host)
5832 		return NULL;
5833 
5834 	for (i = 0, j = 0; i < host->n_ports; i++) {
5835 		struct ata_port *ap = host->ports[i];
5836 
5837 		if (ppi[j])
5838 			pi = ppi[j++];
5839 
5840 		ap->pio_mask = pi->pio_mask;
5841 		ap->mwdma_mask = pi->mwdma_mask;
5842 		ap->udma_mask = pi->udma_mask;
5843 		ap->flags |= pi->flags;
5844 		ap->link.flags |= pi->link_flags;
5845 		ap->ops = pi->port_ops;
5846 
5847 		if (!host->ops && (pi->port_ops != &ata_dummy_port_ops))
5848 			host->ops = pi->port_ops;
5849 	}
5850 
5851 	return host;
5852 }
5853 EXPORT_SYMBOL_GPL(ata_host_alloc_pinfo);
5854 
5855 static void ata_host_stop(struct device *gendev, void *res)
5856 {
5857 	struct ata_host *host = dev_get_drvdata(gendev);
5858 	int i;
5859 
5860 	WARN_ON(!(host->flags & ATA_HOST_STARTED));
5861 
5862 	for (i = 0; i < host->n_ports; i++) {
5863 		struct ata_port *ap = host->ports[i];
5864 
5865 		if (ap->ops->port_stop)
5866 			ap->ops->port_stop(ap);
5867 	}
5868 
5869 	if (host->ops->host_stop)
5870 		host->ops->host_stop(host);
5871 }
5872 
5873 /**
5874  *	ata_finalize_port_ops - finalize ata_port_operations
5875  *	@ops: ata_port_operations to finalize
5876  *
5877  *	An ata_port_operations can inherit from another ops and that
5878  *	ops can again inherit from another.  This can go on as many
5879  *	times as necessary as long as there is no loop in the
5880  *	inheritance chain.
5881  *
5882  *	Ops tables are finalized when the host is started.  NULL or
5883  *	unspecified entries are inherited from the closet ancestor
5884  *	which has the method and the entry is populated with it.
5885  *	After finalization, the ops table directly points to all the
5886  *	methods and ->inherits is no longer necessary and cleared.
5887  *
5888  *	Using ATA_OP_NULL, inheriting ops can force a method to NULL.
5889  *
5890  *	LOCKING:
5891  *	None.
5892  */
5893 static void ata_finalize_port_ops(struct ata_port_operations *ops)
5894 {
5895 	static DEFINE_SPINLOCK(lock);
5896 	const struct ata_port_operations *cur;
5897 	void **begin = (void **)ops;
5898 	void **end = (void **)&ops->inherits;
5899 	void **pp;
5900 
5901 	if (!ops || !ops->inherits)
5902 		return;
5903 
5904 	spin_lock(&lock);
5905 
5906 	for (cur = ops->inherits; cur; cur = cur->inherits) {
5907 		void **inherit = (void **)cur;
5908 
5909 		for (pp = begin; pp < end; pp++, inherit++)
5910 			if (!*pp)
5911 				*pp = *inherit;
5912 	}
5913 
5914 	for (pp = begin; pp < end; pp++)
5915 		if (IS_ERR(*pp))
5916 			*pp = NULL;
5917 
5918 	ops->inherits = NULL;
5919 
5920 	spin_unlock(&lock);
5921 }
5922 
5923 /**
5924  *	ata_host_start - start and freeze ports of an ATA host
5925  *	@host: ATA host to start ports for
5926  *
5927  *	Start and then freeze ports of @host.  Started status is
5928  *	recorded in host->flags, so this function can be called
5929  *	multiple times.  Ports are guaranteed to get started only
5930  *	once.  If host->ops is not initialized yet, it is set to the
5931  *	first non-dummy port ops.
5932  *
5933  *	LOCKING:
5934  *	Inherited from calling layer (may sleep).
5935  *
5936  *	RETURNS:
5937  *	0 if all ports are started successfully, -errno otherwise.
5938  */
5939 int ata_host_start(struct ata_host *host)
5940 {
5941 	int have_stop = 0;
5942 	void *start_dr = NULL;
5943 	int i, rc;
5944 
5945 	if (host->flags & ATA_HOST_STARTED)
5946 		return 0;
5947 
5948 	ata_finalize_port_ops(host->ops);
5949 
5950 	for (i = 0; i < host->n_ports; i++) {
5951 		struct ata_port *ap = host->ports[i];
5952 
5953 		ata_finalize_port_ops(ap->ops);
5954 
5955 		if (!host->ops && !ata_port_is_dummy(ap))
5956 			host->ops = ap->ops;
5957 
5958 		if (ap->ops->port_stop)
5959 			have_stop = 1;
5960 	}
5961 
5962 	if (host->ops && host->ops->host_stop)
5963 		have_stop = 1;
5964 
5965 	if (have_stop) {
5966 		start_dr = devres_alloc(ata_host_stop, 0, GFP_KERNEL);
5967 		if (!start_dr)
5968 			return -ENOMEM;
5969 	}
5970 
5971 	for (i = 0; i < host->n_ports; i++) {
5972 		struct ata_port *ap = host->ports[i];
5973 
5974 		if (ap->ops->port_start) {
5975 			rc = ap->ops->port_start(ap);
5976 			if (rc) {
5977 				if (rc != -ENODEV)
5978 					dev_err(host->dev,
5979 						"failed to start port %d (errno=%d)\n",
5980 						i, rc);
5981 				goto err_out;
5982 			}
5983 		}
5984 		ata_eh_freeze_port(ap);
5985 	}
5986 
5987 	if (start_dr)
5988 		devres_add(host->dev, start_dr);
5989 	host->flags |= ATA_HOST_STARTED;
5990 	return 0;
5991 
5992  err_out:
5993 	while (--i >= 0) {
5994 		struct ata_port *ap = host->ports[i];
5995 
5996 		if (ap->ops->port_stop)
5997 			ap->ops->port_stop(ap);
5998 	}
5999 	devres_free(start_dr);
6000 	return rc;
6001 }
6002 EXPORT_SYMBOL_GPL(ata_host_start);
6003 
6004 /**
6005  *	ata_host_init - Initialize a host struct for sas (ipr, libsas)
6006  *	@host:	host to initialize
6007  *	@dev:	device host is attached to
6008  *	@ops:	port_ops
6009  *
6010  */
6011 void ata_host_init(struct ata_host *host, struct device *dev,
6012 		   struct ata_port_operations *ops)
6013 {
6014 	spin_lock_init(&host->lock);
6015 	mutex_init(&host->eh_mutex);
6016 	host->n_tags = ATA_MAX_QUEUE;
6017 	host->dev = dev;
6018 	host->ops = ops;
6019 	kref_init(&host->kref);
6020 }
6021 EXPORT_SYMBOL_GPL(ata_host_init);
6022 
6023 void ata_port_probe(struct ata_port *ap)
6024 {
6025 	struct ata_eh_info *ehi = &ap->link.eh_info;
6026 	unsigned long flags;
6027 
6028 	ata_acpi_port_power_on(ap);
6029 
6030 	/* kick EH for boot probing */
6031 	spin_lock_irqsave(ap->lock, flags);
6032 
6033 	ehi->probe_mask |= ATA_ALL_DEVICES;
6034 	ehi->action |= ATA_EH_RESET;
6035 	ehi->flags |= ATA_EHI_NO_AUTOPSY | ATA_EHI_QUIET;
6036 
6037 	ap->pflags &= ~ATA_PFLAG_INITIALIZING;
6038 	ap->pflags |= ATA_PFLAG_LOADING;
6039 	ata_port_schedule_eh(ap);
6040 
6041 	spin_unlock_irqrestore(ap->lock, flags);
6042 }
6043 EXPORT_SYMBOL_GPL(ata_port_probe);
6044 
6045 static void async_port_probe(void *data, async_cookie_t cookie)
6046 {
6047 	struct ata_port *ap = data;
6048 
6049 	/*
6050 	 * If we're not allowed to scan this host in parallel,
6051 	 * we need to wait until all previous scans have completed
6052 	 * before going further.
6053 	 * Jeff Garzik says this is only within a controller, so we
6054 	 * don't need to wait for port 0, only for later ports.
6055 	 */
6056 	if (!(ap->host->flags & ATA_HOST_PARALLEL_SCAN) && ap->port_no != 0)
6057 		async_synchronize_cookie(cookie);
6058 
6059 	ata_port_probe(ap);
6060 	ata_port_wait_eh(ap);
6061 
6062 	/* in order to keep device order, we need to synchronize at this point */
6063 	async_synchronize_cookie(cookie);
6064 
6065 	ata_scsi_scan_host(ap, 1);
6066 }
6067 
6068 /**
6069  *	ata_host_register - register initialized ATA host
6070  *	@host: ATA host to register
6071  *	@sht: template for SCSI host
6072  *
6073  *	Register initialized ATA host.  @host is allocated using
6074  *	ata_host_alloc() and fully initialized by LLD.  This function
6075  *	starts ports, registers @host with ATA and SCSI layers and
6076  *	probe registered devices.
6077  *
6078  *	LOCKING:
6079  *	Inherited from calling layer (may sleep).
6080  *
6081  *	RETURNS:
6082  *	0 on success, -errno otherwise.
6083  */
6084 int ata_host_register(struct ata_host *host, const struct scsi_host_template *sht)
6085 {
6086 	int i, rc;
6087 
6088 	host->n_tags = clamp(sht->can_queue, 1, ATA_MAX_QUEUE);
6089 
6090 	/* host must have been started */
6091 	if (!(host->flags & ATA_HOST_STARTED)) {
6092 		dev_err(host->dev, "BUG: trying to register unstarted host\n");
6093 		WARN_ON(1);
6094 		return -EINVAL;
6095 	}
6096 
6097 	/* Create associated sysfs transport objects  */
6098 	for (i = 0; i < host->n_ports; i++) {
6099 		rc = ata_tport_add(host->dev,host->ports[i]);
6100 		if (rc) {
6101 			goto err_tadd;
6102 		}
6103 	}
6104 
6105 	rc = ata_scsi_add_hosts(host, sht);
6106 	if (rc)
6107 		goto err_tadd;
6108 
6109 	/* set cable, sata_spd_limit and report */
6110 	for (i = 0; i < host->n_ports; i++) {
6111 		struct ata_port *ap = host->ports[i];
6112 		unsigned int xfer_mask;
6113 
6114 		/* set SATA cable type if still unset */
6115 		if (ap->cbl == ATA_CBL_NONE && (ap->flags & ATA_FLAG_SATA))
6116 			ap->cbl = ATA_CBL_SATA;
6117 
6118 		/* init sata_spd_limit to the current value */
6119 		sata_link_init_spd(&ap->link);
6120 		if (ap->slave_link)
6121 			sata_link_init_spd(ap->slave_link);
6122 
6123 		/* print per-port info to dmesg */
6124 		xfer_mask = ata_pack_xfermask(ap->pio_mask, ap->mwdma_mask,
6125 					      ap->udma_mask);
6126 
6127 		if (!ata_port_is_dummy(ap)) {
6128 			ata_port_info(ap, "%cATA max %s %s\n",
6129 				      (ap->flags & ATA_FLAG_SATA) ? 'S' : 'P',
6130 				      ata_mode_string(xfer_mask),
6131 				      ap->link.eh_info.desc);
6132 			ata_ehi_clear_desc(&ap->link.eh_info);
6133 		} else
6134 			ata_port_info(ap, "DUMMY\n");
6135 	}
6136 
6137 	/* perform each probe asynchronously */
6138 	for (i = 0; i < host->n_ports; i++) {
6139 		struct ata_port *ap = host->ports[i];
6140 		ap->cookie = async_schedule(async_port_probe, ap);
6141 	}
6142 
6143 	return 0;
6144 
6145  err_tadd:
6146 	while (--i >= 0) {
6147 		ata_tport_delete(host->ports[i]);
6148 	}
6149 	return rc;
6150 
6151 }
6152 EXPORT_SYMBOL_GPL(ata_host_register);
6153 
6154 /**
6155  *	ata_host_activate - start host, request IRQ and register it
6156  *	@host: target ATA host
6157  *	@irq: IRQ to request
6158  *	@irq_handler: irq_handler used when requesting IRQ
6159  *	@irq_flags: irq_flags used when requesting IRQ
6160  *	@sht: scsi_host_template to use when registering the host
6161  *
6162  *	After allocating an ATA host and initializing it, most libata
6163  *	LLDs perform three steps to activate the host - start host,
6164  *	request IRQ and register it.  This helper takes necessary
6165  *	arguments and performs the three steps in one go.
6166  *
6167  *	An invalid IRQ skips the IRQ registration and expects the host to
6168  *	have set polling mode on the port. In this case, @irq_handler
6169  *	should be NULL.
6170  *
6171  *	LOCKING:
6172  *	Inherited from calling layer (may sleep).
6173  *
6174  *	RETURNS:
6175  *	0 on success, -errno otherwise.
6176  */
6177 int ata_host_activate(struct ata_host *host, int irq,
6178 		      irq_handler_t irq_handler, unsigned long irq_flags,
6179 		      const struct scsi_host_template *sht)
6180 {
6181 	int i, rc;
6182 	char *irq_desc;
6183 
6184 	rc = ata_host_start(host);
6185 	if (rc)
6186 		return rc;
6187 
6188 	/* Special case for polling mode */
6189 	if (!irq) {
6190 		WARN_ON(irq_handler);
6191 		return ata_host_register(host, sht);
6192 	}
6193 
6194 	irq_desc = devm_kasprintf(host->dev, GFP_KERNEL, "%s[%s]",
6195 				  dev_driver_string(host->dev),
6196 				  dev_name(host->dev));
6197 	if (!irq_desc)
6198 		return -ENOMEM;
6199 
6200 	rc = devm_request_irq(host->dev, irq, irq_handler, irq_flags,
6201 			      irq_desc, host);
6202 	if (rc)
6203 		return rc;
6204 
6205 	for (i = 0; i < host->n_ports; i++)
6206 		ata_port_desc_misc(host->ports[i], irq);
6207 
6208 	rc = ata_host_register(host, sht);
6209 	/* if failed, just free the IRQ and leave ports alone */
6210 	if (rc)
6211 		devm_free_irq(host->dev, irq, host);
6212 
6213 	return rc;
6214 }
6215 EXPORT_SYMBOL_GPL(ata_host_activate);
6216 
6217 /**
6218  *	ata_dev_free_resources - Free a device resources
6219  *	@dev: Target ATA device
6220  *
6221  *	Free resources allocated to support a device features.
6222  *
6223  *	LOCKING:
6224  *	Kernel thread context (may sleep).
6225  */
6226 void ata_dev_free_resources(struct ata_device *dev)
6227 {
6228 	if (zpodd_dev_enabled(dev))
6229 		zpodd_exit(dev);
6230 
6231 	ata_dev_cleanup_cdl_resources(dev);
6232 }
6233 
6234 /**
6235  *	ata_port_detach - Detach ATA port in preparation of device removal
6236  *	@ap: ATA port to be detached
6237  *
6238  *	Detach all ATA devices and the associated SCSI devices of @ap;
6239  *	then, remove the associated SCSI host.  @ap is guaranteed to
6240  *	be quiescent on return from this function.
6241  *
6242  *	LOCKING:
6243  *	Kernel thread context (may sleep).
6244  */
6245 static void ata_port_detach(struct ata_port *ap)
6246 {
6247 	unsigned long flags;
6248 	struct ata_link *link;
6249 	struct ata_device *dev;
6250 
6251 	/* Ensure ata_port probe has completed */
6252 	async_synchronize_cookie(ap->cookie + 1);
6253 
6254 	/* Wait for any ongoing EH */
6255 	ata_port_wait_eh(ap);
6256 
6257 	mutex_lock(&ap->scsi_scan_mutex);
6258 	spin_lock_irqsave(ap->lock, flags);
6259 
6260 	/* Remove scsi devices */
6261 	ata_for_each_link(link, ap, HOST_FIRST) {
6262 		ata_for_each_dev(dev, link, ALL) {
6263 			if (dev->sdev) {
6264 				spin_unlock_irqrestore(ap->lock, flags);
6265 				scsi_remove_device(dev->sdev);
6266 				spin_lock_irqsave(ap->lock, flags);
6267 				dev->sdev = NULL;
6268 			}
6269 		}
6270 	}
6271 
6272 	/* Make sure the deferred qc work finished. */
6273 	cancel_work_sync(&ap->deferred_qc_work);
6274 	WARN_ON(ap->deferred_qc);
6275 
6276 	/* Tell EH to disable all devices */
6277 	ap->pflags |= ATA_PFLAG_UNLOADING;
6278 	ata_port_schedule_eh(ap);
6279 
6280 	spin_unlock_irqrestore(ap->lock, flags);
6281 	mutex_unlock(&ap->scsi_scan_mutex);
6282 
6283 	/* wait till EH commits suicide */
6284 	ata_port_wait_eh(ap);
6285 
6286 	/* it better be dead now */
6287 	WARN_ON(!(ap->pflags & ATA_PFLAG_UNLOADED));
6288 
6289 	cancel_delayed_work_sync(&ap->hotplug_task);
6290 	cancel_delayed_work_sync(&ap->scsi_rescan_task);
6291 
6292 	/* Delete port multiplier link transport devices */
6293 	if (ap->pmp_link) {
6294 		int i;
6295 
6296 		for (i = 0; i < SATA_PMP_MAX_PORTS; i++)
6297 			ata_tlink_delete(&ap->pmp_link[i]);
6298 	}
6299 
6300 	/* Remove the associated SCSI host */
6301 	scsi_remove_host(ap->scsi_host);
6302 	ata_tport_delete(ap);
6303 }
6304 
6305 /**
6306  *	ata_host_detach - Detach all ports of an ATA host
6307  *	@host: Host to detach
6308  *
6309  *	Detach all ports of @host.
6310  *
6311  *	LOCKING:
6312  *	Kernel thread context (may sleep).
6313  */
6314 void ata_host_detach(struct ata_host *host)
6315 {
6316 	int i;
6317 
6318 	for (i = 0; i < host->n_ports; i++)
6319 		ata_port_detach(host->ports[i]);
6320 
6321 	/* the host is dead now, dissociate ACPI */
6322 	ata_acpi_dissociate(host);
6323 }
6324 EXPORT_SYMBOL_GPL(ata_host_detach);
6325 
6326 #ifdef CONFIG_PCI
6327 
6328 /**
6329  *	ata_pci_remove_one - PCI layer callback for device removal
6330  *	@pdev: PCI device that was removed
6331  *
6332  *	PCI layer indicates to libata via this hook that hot-unplug or
6333  *	module unload event has occurred.  Detach all ports.  Resource
6334  *	release is handled via devres.
6335  *
6336  *	LOCKING:
6337  *	Inherited from PCI layer (may sleep).
6338  */
6339 void ata_pci_remove_one(struct pci_dev *pdev)
6340 {
6341 	struct ata_host *host = pci_get_drvdata(pdev);
6342 
6343 	ata_host_detach(host);
6344 }
6345 EXPORT_SYMBOL_GPL(ata_pci_remove_one);
6346 
6347 void ata_pci_shutdown_one(struct pci_dev *pdev)
6348 {
6349 	struct ata_host *host = pci_get_drvdata(pdev);
6350 	int i;
6351 
6352 	for (i = 0; i < host->n_ports; i++) {
6353 		struct ata_port *ap = host->ports[i];
6354 
6355 		ap->pflags |= ATA_PFLAG_FROZEN;
6356 
6357 		/* Disable port interrupts */
6358 		if (ap->ops->freeze)
6359 			ap->ops->freeze(ap);
6360 
6361 		/* Stop the port DMA engines */
6362 		if (ap->ops->port_stop)
6363 			ap->ops->port_stop(ap);
6364 	}
6365 }
6366 EXPORT_SYMBOL_GPL(ata_pci_shutdown_one);
6367 
6368 /* move to PCI subsystem */
6369 int pci_test_config_bits(struct pci_dev *pdev, const struct pci_bits *bits)
6370 {
6371 	unsigned long tmp = 0;
6372 
6373 	switch (bits->width) {
6374 	case 1: {
6375 		u8 tmp8 = 0;
6376 		pci_read_config_byte(pdev, bits->reg, &tmp8);
6377 		tmp = tmp8;
6378 		break;
6379 	}
6380 	case 2: {
6381 		u16 tmp16 = 0;
6382 		pci_read_config_word(pdev, bits->reg, &tmp16);
6383 		tmp = tmp16;
6384 		break;
6385 	}
6386 	case 4: {
6387 		u32 tmp32 = 0;
6388 		pci_read_config_dword(pdev, bits->reg, &tmp32);
6389 		tmp = tmp32;
6390 		break;
6391 	}
6392 
6393 	default:
6394 		return -EINVAL;
6395 	}
6396 
6397 	tmp &= bits->mask;
6398 
6399 	return (tmp == bits->val) ? 1 : 0;
6400 }
6401 EXPORT_SYMBOL_GPL(pci_test_config_bits);
6402 
6403 #ifdef CONFIG_PM
6404 void ata_pci_device_do_suspend(struct pci_dev *pdev, pm_message_t mesg)
6405 {
6406 	pci_save_state(pdev);
6407 	pci_disable_device(pdev);
6408 
6409 	if (mesg.event & PM_EVENT_SLEEP)
6410 		pci_set_power_state(pdev, PCI_D3hot);
6411 }
6412 EXPORT_SYMBOL_GPL(ata_pci_device_do_suspend);
6413 
6414 int ata_pci_device_do_resume(struct pci_dev *pdev)
6415 {
6416 	int rc;
6417 
6418 	pci_set_power_state(pdev, PCI_D0);
6419 	pci_restore_state(pdev);
6420 
6421 	rc = pcim_enable_device(pdev);
6422 	if (rc) {
6423 		dev_err(&pdev->dev,
6424 			"failed to enable device after resume (%d)\n", rc);
6425 		return rc;
6426 	}
6427 
6428 	pci_set_master(pdev);
6429 	return 0;
6430 }
6431 EXPORT_SYMBOL_GPL(ata_pci_device_do_resume);
6432 
6433 int ata_pci_device_suspend(struct pci_dev *pdev, pm_message_t mesg)
6434 {
6435 	struct ata_host *host = pci_get_drvdata(pdev);
6436 
6437 	ata_host_suspend(host, mesg);
6438 
6439 	ata_pci_device_do_suspend(pdev, mesg);
6440 
6441 	return 0;
6442 }
6443 EXPORT_SYMBOL_GPL(ata_pci_device_suspend);
6444 
6445 int ata_pci_device_resume(struct pci_dev *pdev)
6446 {
6447 	struct ata_host *host = pci_get_drvdata(pdev);
6448 	int rc;
6449 
6450 	rc = ata_pci_device_do_resume(pdev);
6451 	if (rc == 0)
6452 		ata_host_resume(host);
6453 	return rc;
6454 }
6455 EXPORT_SYMBOL_GPL(ata_pci_device_resume);
6456 #endif /* CONFIG_PM */
6457 #endif /* CONFIG_PCI */
6458 
6459 /**
6460  *	ata_platform_remove_one - Platform layer callback for device removal
6461  *	@pdev: Platform device that was removed
6462  *
6463  *	Platform layer indicates to libata via this hook that hot-unplug or
6464  *	module unload event has occurred.  Detach all ports.  Resource
6465  *	release is handled via devres.
6466  *
6467  *	LOCKING:
6468  *	Inherited from platform layer (may sleep).
6469  */
6470 void ata_platform_remove_one(struct platform_device *pdev)
6471 {
6472 	struct ata_host *host = platform_get_drvdata(pdev);
6473 
6474 	ata_host_detach(host);
6475 }
6476 EXPORT_SYMBOL_GPL(ata_platform_remove_one);
6477 
6478 #ifdef CONFIG_ATA_FORCE
6479 
6480 #define force_cbl(name, flag)				\
6481 	{ #name,	.cbl		= (flag) }
6482 
6483 #define force_spd_limit(spd, val)			\
6484 	{ #spd,	.spd_limit		= (val) }
6485 
6486 #define force_xfer(mode, shift)				\
6487 	{ #mode,	.xfer_mask	= (1UL << (shift)) }
6488 
6489 #define force_lflag_on(name, flags)			\
6490 	{ #name,	.lflags_on	= (flags) }
6491 
6492 #define force_lflag_onoff(name, flags)			\
6493 	{ "no" #name,	.lflags_on	= (flags) },	\
6494 	{ #name,	.lflags_off	= (flags) }
6495 
6496 #define force_pflag_on(name, flags)			\
6497 	{ #name,	.pflags_on	= (flags) }
6498 
6499 #define force_quirk_on(name, flag)			\
6500 	{ #name,	.quirk_on	= (flag) }
6501 
6502 #define force_quirk_val(name, flag, val)		\
6503 	{ #name,	.quirk_on	= (flag),	\
6504 			.value		= (val) }
6505 
6506 #define force_quirk_onoff(name, flag)			\
6507 	{ "no" #name,	.quirk_on	= (flag) },	\
6508 	{ #name,	.quirk_off	= (flag) }
6509 
6510 /*
6511  * If the ata_force_param struct member 'name' ends with '=', then the value
6512  * after the equal sign will be parsed as an u64, and will be saved in the
6513  * ata_force_param struct member 'value'. This works because each libata.force
6514  * entry (struct ata_force_ent) is separated by commas, so each entry represents
6515  * a single quirk, and can thus only have a single value.
6516  */
6517 static const struct ata_force_param force_tbl[] __initconst = {
6518 	force_cbl(40c,			ATA_CBL_PATA40),
6519 	force_cbl(80c,			ATA_CBL_PATA80),
6520 	force_cbl(short40c,		ATA_CBL_PATA40_SHORT),
6521 	force_cbl(unk,			ATA_CBL_PATA_UNK),
6522 	force_cbl(ign,			ATA_CBL_PATA_IGN),
6523 	force_cbl(sata,			ATA_CBL_SATA),
6524 
6525 	force_spd_limit(1.5Gbps,	1),
6526 	force_spd_limit(3.0Gbps,	2),
6527 
6528 	force_xfer(pio0,		ATA_SHIFT_PIO + 0),
6529 	force_xfer(pio1,		ATA_SHIFT_PIO + 1),
6530 	force_xfer(pio2,		ATA_SHIFT_PIO + 2),
6531 	force_xfer(pio3,		ATA_SHIFT_PIO + 3),
6532 	force_xfer(pio4,		ATA_SHIFT_PIO + 4),
6533 	force_xfer(pio5,		ATA_SHIFT_PIO + 5),
6534 	force_xfer(pio6,		ATA_SHIFT_PIO + 6),
6535 	force_xfer(mwdma0,		ATA_SHIFT_MWDMA + 0),
6536 	force_xfer(mwdma1,		ATA_SHIFT_MWDMA + 1),
6537 	force_xfer(mwdma2,		ATA_SHIFT_MWDMA + 2),
6538 	force_xfer(mwdma3,		ATA_SHIFT_MWDMA + 3),
6539 	force_xfer(mwdma4,		ATA_SHIFT_MWDMA + 4),
6540 	force_xfer(udma0,		ATA_SHIFT_UDMA + 0),
6541 	force_xfer(udma16,		ATA_SHIFT_UDMA + 0),
6542 	force_xfer(udma/16,		ATA_SHIFT_UDMA + 0),
6543 	force_xfer(udma1,		ATA_SHIFT_UDMA + 1),
6544 	force_xfer(udma25,		ATA_SHIFT_UDMA + 1),
6545 	force_xfer(udma/25,		ATA_SHIFT_UDMA + 1),
6546 	force_xfer(udma2,		ATA_SHIFT_UDMA + 2),
6547 	force_xfer(udma33,		ATA_SHIFT_UDMA + 2),
6548 	force_xfer(udma/33,		ATA_SHIFT_UDMA + 2),
6549 	force_xfer(udma3,		ATA_SHIFT_UDMA + 3),
6550 	force_xfer(udma44,		ATA_SHIFT_UDMA + 3),
6551 	force_xfer(udma/44,		ATA_SHIFT_UDMA + 3),
6552 	force_xfer(udma4,		ATA_SHIFT_UDMA + 4),
6553 	force_xfer(udma66,		ATA_SHIFT_UDMA + 4),
6554 	force_xfer(udma/66,		ATA_SHIFT_UDMA + 4),
6555 	force_xfer(udma5,		ATA_SHIFT_UDMA + 5),
6556 	force_xfer(udma100,		ATA_SHIFT_UDMA + 5),
6557 	force_xfer(udma/100,		ATA_SHIFT_UDMA + 5),
6558 	force_xfer(udma6,		ATA_SHIFT_UDMA + 6),
6559 	force_xfer(udma133,		ATA_SHIFT_UDMA + 6),
6560 	force_xfer(udma/133,		ATA_SHIFT_UDMA + 6),
6561 	force_xfer(udma7,		ATA_SHIFT_UDMA + 7),
6562 
6563 	force_lflag_on(nohrst,		ATA_LFLAG_NO_HRST),
6564 	force_lflag_on(nosrst,		ATA_LFLAG_NO_SRST),
6565 	force_lflag_on(norst,		ATA_LFLAG_NO_HRST | ATA_LFLAG_NO_SRST),
6566 	force_lflag_on(rstonce,		ATA_LFLAG_RST_ONCE),
6567 	force_lflag_onoff(dbdelay,	ATA_LFLAG_NO_DEBOUNCE_DELAY),
6568 
6569 	force_pflag_on(external,	ATA_PFLAG_EXTERNAL),
6570 
6571 	force_quirk_onoff(ncq,		ATA_QUIRK_NONCQ),
6572 	force_quirk_onoff(ncqtrim,	ATA_QUIRK_NO_NCQ_TRIM),
6573 	force_quirk_onoff(ncqati,	ATA_QUIRK_NO_NCQ_ON_ATI),
6574 
6575 	force_quirk_onoff(trim,		ATA_QUIRK_NOTRIM),
6576 	force_quirk_on(trim_zero,	ATA_QUIRK_ZERO_AFTER_TRIM),
6577 	force_quirk_on(max_trim_128m,	ATA_QUIRK_MAX_TRIM_128M),
6578 
6579 	force_quirk_onoff(dma,		ATA_QUIRK_NODMA),
6580 	force_quirk_on(atapi_dmadir,	ATA_QUIRK_ATAPI_DMADIR),
6581 	force_quirk_on(atapi_mod16_dma,	ATA_QUIRK_ATAPI_MOD16_DMA),
6582 
6583 	force_quirk_onoff(dmalog,	ATA_QUIRK_NO_DMA_LOG),
6584 	force_quirk_onoff(iddevlog,	ATA_QUIRK_NO_ID_DEV_LOG),
6585 	force_quirk_onoff(logdir,	ATA_QUIRK_NO_LOG_DIR),
6586 
6587 	force_quirk_val(max_sec_128,	ATA_QUIRK_MAX_SEC,	128),
6588 	force_quirk_val(max_sec_1024,	ATA_QUIRK_MAX_SEC,	1024),
6589 	force_quirk_on(max_sec=,	ATA_QUIRK_MAX_SEC),
6590 	force_quirk_on(max_sec_lba48,	ATA_QUIRK_MAX_SEC_LBA48),
6591 
6592 	force_quirk_onoff(lpm,		ATA_QUIRK_NOLPM),
6593 	force_quirk_onoff(setxfer,	ATA_QUIRK_NOSETXFER),
6594 	force_quirk_on(dump_id,		ATA_QUIRK_DUMP_ID),
6595 	force_quirk_onoff(fua,		ATA_QUIRK_NO_FUA),
6596 
6597 	force_quirk_on(disable,		ATA_QUIRK_DISABLE),
6598 };
6599 
6600 static int __init ata_parse_force_one(char **cur,
6601 				      struct ata_force_ent *force_ent,
6602 				      const char **reason)
6603 {
6604 	char *start = *cur, *p = *cur;
6605 	char *id, *val, *endp, *equalsign, *char_after_equalsign;
6606 	const struct ata_force_param *match_fp = NULL;
6607 	u64 val_after_equalsign;
6608 	int nr_matches = 0, i;
6609 
6610 	/* find where this param ends and update *cur */
6611 	while (*p != '\0' && *p != ',')
6612 		p++;
6613 
6614 	if (*p == '\0')
6615 		*cur = p;
6616 	else
6617 		*cur = p + 1;
6618 
6619 	*p = '\0';
6620 
6621 	/* parse */
6622 	p = strchr(start, ':');
6623 	if (!p) {
6624 		val = strstrip(start);
6625 		goto parse_val;
6626 	}
6627 	*p = '\0';
6628 
6629 	id = strstrip(start);
6630 	val = strstrip(p + 1);
6631 
6632 	/* parse id */
6633 	p = strchr(id, '.');
6634 	if (p) {
6635 		*p++ = '\0';
6636 		force_ent->device = simple_strtoul(p, &endp, 10);
6637 		if (p == endp || *endp != '\0') {
6638 			*reason = "invalid device";
6639 			return -EINVAL;
6640 		}
6641 	}
6642 
6643 	force_ent->port = simple_strtoul(id, &endp, 10);
6644 	if (id == endp || *endp != '\0') {
6645 		*reason = "invalid port/link";
6646 		return -EINVAL;
6647 	}
6648 
6649  parse_val:
6650 	equalsign = strchr(val, '=');
6651 	if (equalsign) {
6652 		char_after_equalsign = equalsign + 1;
6653 		if (!strlen(char_after_equalsign) ||
6654 		    kstrtoull(char_after_equalsign, 10, &val_after_equalsign)) {
6655 			*reason = "invalid value after equal sign";
6656 			return -EINVAL;
6657 		}
6658 	}
6659 
6660 	/* Parse the parameter value. */
6661 	for (i = 0; i < ARRAY_SIZE(force_tbl); i++) {
6662 		const struct ata_force_param *fp = &force_tbl[i];
6663 
6664 		/*
6665 		 * If val contains equal sign, match has to be exact, i.e.
6666 		 * shortcuts are not supported.
6667 		 */
6668 		if (equalsign &&
6669 		    (strncasecmp(val, fp->name,
6670 				 char_after_equalsign - val) == 0)) {
6671 			force_ent->param = *fp;
6672 			force_ent->param.value = val_after_equalsign;
6673 			return 0;
6674 		}
6675 
6676 		/*
6677 		 * If val does not contain equal sign, allow shortcuts so that
6678 		 * both 1.5 and 1.5Gbps work.
6679 		 */
6680 		if (strncasecmp(val, fp->name, strlen(val)))
6681 			continue;
6682 
6683 		nr_matches++;
6684 		match_fp = fp;
6685 
6686 		if (strcasecmp(val, fp->name) == 0) {
6687 			nr_matches = 1;
6688 			break;
6689 		}
6690 	}
6691 
6692 	if (!nr_matches) {
6693 		*reason = "unknown value";
6694 		return -EINVAL;
6695 	}
6696 	if (nr_matches > 1) {
6697 		*reason = "ambiguous value";
6698 		return -EINVAL;
6699 	}
6700 
6701 	force_ent->param = *match_fp;
6702 
6703 	return 0;
6704 }
6705 
6706 static void __init ata_parse_force_param(void)
6707 {
6708 	int idx = 0, size = 1;
6709 	int last_port = -1, last_device = -1;
6710 	char *p, *cur, *next;
6711 
6712 	/* Calculate maximum number of params and allocate ata_force_tbl */
6713 	for (p = ata_force_param_buf; *p; p++)
6714 		if (*p == ',')
6715 			size++;
6716 
6717 	ata_force_tbl = kcalloc(size, sizeof(ata_force_tbl[0]), GFP_KERNEL);
6718 	if (!ata_force_tbl) {
6719 		printk(KERN_WARNING "ata: failed to extend force table, "
6720 		       "libata.force ignored\n");
6721 		return;
6722 	}
6723 
6724 	/* parse and populate the table */
6725 	for (cur = ata_force_param_buf; *cur != '\0'; cur = next) {
6726 		const char *reason = "";
6727 		struct ata_force_ent te = { .port = -1, .device = -1 };
6728 
6729 		next = cur;
6730 		if (ata_parse_force_one(&next, &te, &reason)) {
6731 			printk(KERN_WARNING "ata: failed to parse force "
6732 			       "parameter \"%s\" (%s)\n",
6733 			       cur, reason);
6734 			continue;
6735 		}
6736 
6737 		if (te.port == -1) {
6738 			te.port = last_port;
6739 			te.device = last_device;
6740 		}
6741 
6742 		ata_force_tbl[idx++] = te;
6743 
6744 		last_port = te.port;
6745 		last_device = te.device;
6746 	}
6747 
6748 	ata_force_tbl_size = idx;
6749 }
6750 
6751 static void ata_free_force_param(void)
6752 {
6753 	kfree(ata_force_tbl);
6754 }
6755 #else
6756 static inline void ata_parse_force_param(void) { }
6757 static inline void ata_free_force_param(void) { }
6758 #endif
6759 
6760 static int __init ata_init(void)
6761 {
6762 	int rc;
6763 
6764 	ata_parse_force_param();
6765 
6766 	rc = ata_sff_init();
6767 	if (rc) {
6768 		ata_free_force_param();
6769 		return rc;
6770 	}
6771 
6772 	libata_transport_init();
6773 	ata_scsi_transport_template = ata_attach_transport();
6774 	if (!ata_scsi_transport_template) {
6775 		ata_sff_exit();
6776 		rc = -ENOMEM;
6777 		goto err_out;
6778 	}
6779 
6780 	printk(KERN_DEBUG "libata version " DRV_VERSION " loaded.\n");
6781 	return 0;
6782 
6783 err_out:
6784 	return rc;
6785 }
6786 
6787 static void __exit ata_exit(void)
6788 {
6789 	ata_release_transport(ata_scsi_transport_template);
6790 	libata_transport_exit();
6791 	ata_sff_exit();
6792 	ata_free_force_param();
6793 }
6794 
6795 subsys_initcall(ata_init);
6796 module_exit(ata_exit);
6797 
6798 static DEFINE_RATELIMIT_STATE(ratelimit, HZ / 5, 1);
6799 
6800 int ata_ratelimit(void)
6801 {
6802 	return __ratelimit(&ratelimit);
6803 }
6804 EXPORT_SYMBOL_GPL(ata_ratelimit);
6805 
6806 /**
6807  *	ata_msleep - ATA EH owner aware msleep
6808  *	@ap: ATA port to attribute the sleep to
6809  *	@msecs: duration to sleep in milliseconds
6810  *
6811  *	Sleeps @msecs.  If the current task is owner of @ap's EH, the
6812  *	ownership is released before going to sleep and reacquired
6813  *	after the sleep is complete.  IOW, other ports sharing the
6814  *	@ap->host will be allowed to own the EH while this task is
6815  *	sleeping.
6816  *
6817  *	LOCKING:
6818  *	Might sleep.
6819  */
6820 void ata_msleep(struct ata_port *ap, unsigned int msecs)
6821 {
6822 	bool owns_eh = ap && ap->host->eh_owner == current;
6823 
6824 	if (owns_eh)
6825 		ata_eh_release(ap);
6826 
6827 	if (msecs < 20) {
6828 		unsigned long usecs = msecs * USEC_PER_MSEC;
6829 		usleep_range(usecs, usecs + 50);
6830 	} else {
6831 		msleep(msecs);
6832 	}
6833 
6834 	if (owns_eh)
6835 		ata_eh_acquire(ap);
6836 }
6837 EXPORT_SYMBOL_GPL(ata_msleep);
6838 
6839 /**
6840  *	ata_wait_register - wait until register value changes
6841  *	@ap: ATA port to wait register for, can be NULL
6842  *	@reg: IO-mapped register
6843  *	@mask: Mask to apply to read register value
6844  *	@val: Wait condition
6845  *	@interval: polling interval in milliseconds
6846  *	@timeout: timeout in milliseconds
6847  *
6848  *	Waiting for some bits of register to change is a common
6849  *	operation for ATA controllers.  This function reads 32bit LE
6850  *	IO-mapped register @reg and tests for the following condition.
6851  *
6852  *	(*@reg & mask) != val
6853  *
6854  *	If the condition is met, it returns; otherwise, the process is
6855  *	repeated after @interval_msec until timeout.
6856  *
6857  *	LOCKING:
6858  *	Kernel thread context (may sleep)
6859  *
6860  *	RETURNS:
6861  *	The final register value.
6862  */
6863 u32 ata_wait_register(struct ata_port *ap, void __iomem *reg, u32 mask, u32 val,
6864 		      unsigned int interval, unsigned int timeout)
6865 {
6866 	unsigned long deadline;
6867 	u32 tmp;
6868 
6869 	tmp = ioread32(reg);
6870 
6871 	/* Calculate timeout _after_ the first read to make sure
6872 	 * preceding writes reach the controller before starting to
6873 	 * eat away the timeout.
6874 	 */
6875 	deadline = ata_deadline(jiffies, timeout);
6876 
6877 	while ((tmp & mask) == val && time_before(jiffies, deadline)) {
6878 		ata_msleep(ap, interval);
6879 		tmp = ioread32(reg);
6880 	}
6881 
6882 	return tmp;
6883 }
6884 EXPORT_SYMBOL_GPL(ata_wait_register);
6885 
6886 /*
6887  * Dummy port_ops
6888  */
6889 static unsigned int ata_dummy_qc_issue(struct ata_queued_cmd *qc)
6890 {
6891 	return AC_ERR_SYSTEM;
6892 }
6893 
6894 static void ata_dummy_error_handler(struct ata_port *ap)
6895 {
6896 	/* truly dummy */
6897 }
6898 
6899 struct ata_port_operations ata_dummy_port_ops = {
6900 	.qc_issue		= ata_dummy_qc_issue,
6901 	.error_handler		= ata_dummy_error_handler,
6902 	.sched_eh		= ata_std_sched_eh,
6903 	.end_eh			= ata_std_end_eh,
6904 };
6905 EXPORT_SYMBOL_GPL(ata_dummy_port_ops);
6906 
6907 const struct ata_port_info ata_dummy_port_info = {
6908 	.port_ops		= &ata_dummy_port_ops,
6909 };
6910 EXPORT_SYMBOL_GPL(ata_dummy_port_info);
6911 
6912 EXPORT_TRACEPOINT_SYMBOL_GPL(ata_tf_load);
6913 EXPORT_TRACEPOINT_SYMBOL_GPL(ata_exec_command);
6914 EXPORT_TRACEPOINT_SYMBOL_GPL(ata_bmdma_setup);
6915 EXPORT_TRACEPOINT_SYMBOL_GPL(ata_bmdma_start);
6916 EXPORT_TRACEPOINT_SYMBOL_GPL(ata_bmdma_status);
6917