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