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