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