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