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