File Index
Files and directories
Sign in
FILE

libata-eh.c

File preview with syntax highlighting.

linux-6.19.14/drivers/ata/libata-eh.c C
   1// SPDX-License-Identifier: GPL-2.0-or-later
   2/*
   3 *  libata-eh.c - libata error handling
   4 *
   5 *  Copyright 2006 Tejun Heo <htejun@gmail.com>
   6 *
   7 *  libata documentation is available via 'make {ps|pdf}docs',
   8 *  as Documentation/driver-api/libata.rst
   9 *
  10 *  Hardware documentation available from http://www.t13.org/ and
  11 *  http://www.sata-io.org/
  12 */
  13
  14#include <linux/kernel.h>
  15#include <linux/blkdev.h>
  16#include <linux/export.h>
  17#include <linux/pci.h>
  18#include <scsi/scsi.h>
  19#include <scsi/scsi_host.h>
  20#include <scsi/scsi_eh.h>
  21#include <scsi/scsi_device.h>
  22#include <scsi/scsi_cmnd.h>
  23#include <scsi/scsi_dbg.h>
  24#include "../scsi/scsi_transport_api.h"
  25
  26#include <linux/libata.h>
  27
  28#include <trace/events/libata.h>
  29#include "libata.h"
  30
  31enum {
  32	/* speed down verdicts */
  33	ATA_EH_SPDN_NCQ_OFF		= (1 << 0),
  34	ATA_EH_SPDN_SPEED_DOWN		= (1 << 1),
  35	ATA_EH_SPDN_FALLBACK_TO_PIO	= (1 << 2),
  36	ATA_EH_SPDN_KEEP_ERRORS		= (1 << 3),
  37
  38	/* error flags */
  39	ATA_EFLAG_IS_IO			= (1 << 0),
  40	ATA_EFLAG_DUBIOUS_XFER		= (1 << 1),
  41	ATA_EFLAG_OLD_ER                = (1 << 31),
  42
  43	/* error categories */
  44	ATA_ECAT_NONE			= 0,
  45	ATA_ECAT_ATA_BUS		= 1,
  46	ATA_ECAT_TOUT_HSM		= 2,
  47	ATA_ECAT_UNK_DEV		= 3,
  48	ATA_ECAT_DUBIOUS_NONE		= 4,
  49	ATA_ECAT_DUBIOUS_ATA_BUS	= 5,
  50	ATA_ECAT_DUBIOUS_TOUT_HSM	= 6,
  51	ATA_ECAT_DUBIOUS_UNK_DEV	= 7,
  52	ATA_ECAT_NR			= 8,
  53
  54	ATA_EH_CMD_DFL_TIMEOUT		=  5000,
  55
  56	/* always put at least this amount of time between resets */
  57	ATA_EH_RESET_COOL_DOWN		=  5000,
  58
  59	/* Waiting in ->prereset can never be reliable.  It's
  60	 * sometimes nice to wait there but it can't be depended upon;
  61	 * otherwise, we wouldn't be resetting.  Just give it enough
  62	 * time for most drives to spin up.
  63	 */
  64	ATA_EH_PRERESET_TIMEOUT		= 10000,
  65	ATA_EH_FASTDRAIN_INTERVAL	=  3000,
  66
  67	ATA_EH_UA_TRIES			= 5,
  68
  69	/* probe speed down parameters, see ata_eh_schedule_probe() */
  70	ATA_EH_PROBE_TRIAL_INTERVAL	= 60000,	/* 1 min */
  71	ATA_EH_PROBE_TRIALS		= 2,
  72};
  73
  74/* The following table determines how we sequence resets.  Each entry
  75 * represents timeout for that try.  The first try can be soft or
  76 * hardreset.  All others are hardreset if available.  In most cases
  77 * the first reset w/ 10sec timeout should succeed.  Following entries
  78 * are mostly for error handling, hotplug and those outlier devices that
  79 * take an exceptionally long time to recover from reset.
  80 */
  81static const unsigned int ata_eh_reset_timeouts[] = {
  82	10000,	/* most drives spin up by 10sec */
  83	10000,	/* > 99% working drives spin up before 20sec */
  84	35000,	/* give > 30 secs of idleness for outlier devices */
  85	 5000,	/* and sweet one last chance */
  86	UINT_MAX, /* > 1 min has elapsed, give up */
  87};
  88
  89static const unsigned int ata_eh_identify_timeouts[] = {
  90	 5000,	/* covers > 99% of successes and not too boring on failures */
  91	10000,  /* combined time till here is enough even for media access */
  92	30000,	/* for true idiots */
  93	UINT_MAX,
  94};
  95
  96static const unsigned int ata_eh_revalidate_timeouts[] = {
  97	15000,	/* Some drives are slow to read log pages when waking-up */
  98	15000,  /* combined time till here is enough even for media access */
  99	UINT_MAX,
 100};
 101
 102static const unsigned int ata_eh_flush_timeouts[] = {
 103	15000,	/* be generous with flush */
 104	15000,  /* ditto */
 105	30000,	/* and even more generous */
 106	UINT_MAX,
 107};
 108
 109static const unsigned int ata_eh_other_timeouts[] = {
 110	 5000,	/* same rationale as identify timeout */
 111	10000,	/* ditto */
 112	/* but no merciful 30sec for other commands, it just isn't worth it */
 113	UINT_MAX,
 114};
 115
 116struct ata_eh_cmd_timeout_ent {
 117	const u8		*commands;
 118	const unsigned int	*timeouts;
 119};
 120
 121/* The following table determines timeouts to use for EH internal
 122 * commands.  Each table entry is a command class and matches the
 123 * commands the entry applies to and the timeout table to use.
 124 *
 125 * On the retry after a command timed out, the next timeout value from
 126 * the table is used.  If the table doesn't contain further entries,
 127 * the last value is used.
 128 *
 129 * ehc->cmd_timeout_idx keeps track of which timeout to use per
 130 * command class, so if SET_FEATURES times out on the first try, the
 131 * next try will use the second timeout value only for that class.
 132 */
 133#define CMDS(cmds...)	(const u8 []){ cmds, 0 }
 134static const struct ata_eh_cmd_timeout_ent
 135ata_eh_cmd_timeout_table[ATA_EH_CMD_TIMEOUT_TABLE_SIZE] = {
 136	{ .commands = CMDS(ATA_CMD_ID_ATA, ATA_CMD_ID_ATAPI),
 137	  .timeouts = ata_eh_identify_timeouts, },
 138	{ .commands = CMDS(ATA_CMD_READ_LOG_EXT, ATA_CMD_READ_LOG_DMA_EXT),
 139	  .timeouts = ata_eh_revalidate_timeouts, },
 140	{ .commands = CMDS(ATA_CMD_READ_NATIVE_MAX, ATA_CMD_READ_NATIVE_MAX_EXT),
 141	  .timeouts = ata_eh_other_timeouts, },
 142	{ .commands = CMDS(ATA_CMD_SET_MAX, ATA_CMD_SET_MAX_EXT),
 143	  .timeouts = ata_eh_other_timeouts, },
 144	{ .commands = CMDS(ATA_CMD_SET_FEATURES),
 145	  .timeouts = ata_eh_other_timeouts, },
 146	{ .commands = CMDS(ATA_CMD_INIT_DEV_PARAMS),
 147	  .timeouts = ata_eh_other_timeouts, },
 148	{ .commands = CMDS(ATA_CMD_FLUSH, ATA_CMD_FLUSH_EXT),
 149	  .timeouts = ata_eh_flush_timeouts },
 150	{ .commands = CMDS(ATA_CMD_VERIFY),
 151	  .timeouts = ata_eh_reset_timeouts },
 152};
 153#undef CMDS
 154
 155static void __ata_port_freeze(struct ata_port *ap);
 156#ifdef CONFIG_PM
 157static void ata_eh_handle_port_suspend(struct ata_port *ap);
 158static void ata_eh_handle_port_resume(struct ata_port *ap);
 159#else /* CONFIG_PM */
 160static void ata_eh_handle_port_suspend(struct ata_port *ap)
 161{ }
 162
 163static void ata_eh_handle_port_resume(struct ata_port *ap)
 164{ }
 165#endif /* CONFIG_PM */
 166
 167static __printf(2, 0) void __ata_ehi_pushv_desc(struct ata_eh_info *ehi,
 168				 const char *fmt, va_list args)
 169{
 170	ehi->desc_len += vscnprintf(ehi->desc + ehi->desc_len,
 171				     ATA_EH_DESC_LEN - ehi->desc_len,
 172				     fmt, args);
 173}
 174
 175/**
 176 *	__ata_ehi_push_desc - push error description without adding separator
 177 *	@ehi: target EHI
 178 *	@fmt: printf format string
 179 *
 180 *	Format string according to @fmt and append it to @ehi->desc.
 181 *
 182 *	LOCKING:
 183 *	spin_lock_irqsave(host lock)
 184 */
 185void __ata_ehi_push_desc(struct ata_eh_info *ehi, const char *fmt, ...)
 186{
 187	va_list args;
 188
 189	va_start(args, fmt);
 190	__ata_ehi_pushv_desc(ehi, fmt, args);
 191	va_end(args);
 192}
 193EXPORT_SYMBOL_GPL(__ata_ehi_push_desc);
 194
 195/**
 196 *	ata_ehi_push_desc - push error description with separator
 197 *	@ehi: target EHI
 198 *	@fmt: printf format string
 199 *
 200 *	Format string according to @fmt and append it to @ehi->desc.
 201 *	If @ehi->desc is not empty, ", " is added in-between.
 202 *
 203 *	LOCKING:
 204 *	spin_lock_irqsave(host lock)
 205 */
 206void ata_ehi_push_desc(struct ata_eh_info *ehi, const char *fmt, ...)
 207{
 208	va_list args;
 209
 210	if (ehi->desc_len)
 211		__ata_ehi_push_desc(ehi, ", ");
 212
 213	va_start(args, fmt);
 214	__ata_ehi_pushv_desc(ehi, fmt, args);
 215	va_end(args);
 216}
 217EXPORT_SYMBOL_GPL(ata_ehi_push_desc);
 218
 219/**
 220 *	ata_ehi_clear_desc - clean error description
 221 *	@ehi: target EHI
 222 *
 223 *	Clear @ehi->desc.
 224 *
 225 *	LOCKING:
 226 *	spin_lock_irqsave(host lock)
 227 */
 228void ata_ehi_clear_desc(struct ata_eh_info *ehi)
 229{
 230	ehi->desc[0] = '\0';
 231	ehi->desc_len = 0;
 232}
 233EXPORT_SYMBOL_GPL(ata_ehi_clear_desc);
 234
 235/**
 236 *	ata_port_desc - append port description
 237 *	@ap: target ATA port
 238 *	@fmt: printf format string
 239 *
 240 *	Format string according to @fmt and append it to port
 241 *	description.  If port description is not empty, " " is added
 242 *	in-between.  This function is to be used while initializing
 243 *	ata_host.  The description is printed on host registration.
 244 *
 245 *	LOCKING:
 246 *	None.
 247 */
 248void ata_port_desc(struct ata_port *ap, const char *fmt, ...)
 249{
 250	va_list args;
 251
 252	WARN_ON(!(ap->pflags & ATA_PFLAG_INITIALIZING));
 253
 254	if (ap->link.eh_info.desc_len)
 255		__ata_ehi_push_desc(&ap->link.eh_info, " ");
 256
 257	va_start(args, fmt);
 258	__ata_ehi_pushv_desc(&ap->link.eh_info, fmt, args);
 259	va_end(args);
 260}
 261EXPORT_SYMBOL_GPL(ata_port_desc);
 262
 263#ifdef CONFIG_PCI
 264/**
 265 *	ata_port_pbar_desc - append PCI BAR description
 266 *	@ap: target ATA port
 267 *	@bar: target PCI BAR
 268 *	@offset: offset into PCI BAR
 269 *	@name: name of the area
 270 *
 271 *	If @offset is negative, this function formats a string which
 272 *	contains the name, address, size and type of the BAR and
 273 *	appends it to the port description.  If @offset is zero or
 274 *	positive, only name and offsetted address is appended.
 275 *
 276 *	LOCKING:
 277 *	None.
 278 */
 279void ata_port_pbar_desc(struct ata_port *ap, int bar, ssize_t offset,
 280			const char *name)
 281{
 282	struct pci_dev *pdev = to_pci_dev(ap->host->dev);
 283	char *type = "";
 284	unsigned long long start, len;
 285
 286	if (pci_resource_flags(pdev, bar) & IORESOURCE_MEM)
 287		type = "m";
 288	else if (pci_resource_flags(pdev, bar) & IORESOURCE_IO)
 289		type = "i";
 290
 291	start = (unsigned long long)pci_resource_start(pdev, bar);
 292	len = (unsigned long long)pci_resource_len(pdev, bar);
 293
 294	if (offset < 0)
 295		ata_port_desc(ap, "%s %s%llu@0x%llx", name, type, len, start);
 296	else
 297		ata_port_desc(ap, "%s 0x%llx", name,
 298				start + (unsigned long long)offset);
 299}
 300EXPORT_SYMBOL_GPL(ata_port_pbar_desc);
 301#endif /* CONFIG_PCI */
 302
 303static int ata_lookup_timeout_table(u8 cmd)
 304{
 305	int i;
 306
 307	for (i = 0; i < ATA_EH_CMD_TIMEOUT_TABLE_SIZE; i++) {
 308		const u8 *cur;
 309
 310		for (cur = ata_eh_cmd_timeout_table[i].commands; *cur; cur++)
 311			if (*cur == cmd)
 312				return i;
 313	}
 314
 315	return -1;
 316}
 317
 318/**
 319 *	ata_internal_cmd_timeout - determine timeout for an internal command
 320 *	@dev: target device
 321 *	@cmd: internal command to be issued
 322 *
 323 *	Determine timeout for internal command @cmd for @dev.
 324 *
 325 *	LOCKING:
 326 *	EH context.
 327 *
 328 *	RETURNS:
 329 *	Determined timeout.
 330 */
 331unsigned int ata_internal_cmd_timeout(struct ata_device *dev, u8 cmd)
 332{
 333	struct ata_eh_context *ehc = &dev->link->eh_context;
 334	int ent = ata_lookup_timeout_table(cmd);
 335	int idx;
 336
 337	if (ent < 0)
 338		return ATA_EH_CMD_DFL_TIMEOUT;
 339
 340	idx = ehc->cmd_timeout_idx[dev->devno][ent];
 341	return ata_eh_cmd_timeout_table[ent].timeouts[idx];
 342}
 343
 344/**
 345 *	ata_internal_cmd_timed_out - notification for internal command timeout
 346 *	@dev: target device
 347 *	@cmd: internal command which timed out
 348 *
 349 *	Notify EH that internal command @cmd for @dev timed out.  This
 350 *	function should be called only for commands whose timeouts are
 351 *	determined using ata_internal_cmd_timeout().
 352 *
 353 *	LOCKING:
 354 *	EH context.
 355 */
 356void ata_internal_cmd_timed_out(struct ata_device *dev, u8 cmd)
 357{
 358	struct ata_eh_context *ehc = &dev->link->eh_context;
 359	int ent = ata_lookup_timeout_table(cmd);
 360	int idx;
 361
 362	if (ent < 0)
 363		return;
 364
 365	idx = ehc->cmd_timeout_idx[dev->devno][ent];
 366	if (ata_eh_cmd_timeout_table[ent].timeouts[idx + 1] != UINT_MAX)
 367		ehc->cmd_timeout_idx[dev->devno][ent]++;
 368}
 369
 370static void ata_ering_record(struct ata_ering *ering, unsigned int eflags,
 371			     unsigned int err_mask)
 372{
 373	struct ata_ering_entry *ent;
 374
 375	WARN_ON(!err_mask);
 376
 377	ering->cursor++;
 378	ering->cursor %= ATA_ERING_SIZE;
 379
 380	ent = &ering->ring[ering->cursor];
 381	ent->eflags = eflags;
 382	ent->err_mask = err_mask;
 383	ent->timestamp = get_jiffies_64();
 384}
 385
 386static struct ata_ering_entry *ata_ering_top(struct ata_ering *ering)
 387{
 388	struct ata_ering_entry *ent = &ering->ring[ering->cursor];
 389
 390	if (ent->err_mask)
 391		return ent;
 392	return NULL;
 393}
 394
 395int ata_ering_map(struct ata_ering *ering,
 396		  int (*map_fn)(struct ata_ering_entry *, void *),
 397		  void *arg)
 398{
 399	int idx, rc = 0;
 400	struct ata_ering_entry *ent;
 401
 402	idx = ering->cursor;
 403	do {
 404		ent = &ering->ring[idx];
 405		if (!ent->err_mask)
 406			break;
 407		rc = map_fn(ent, arg);
 408		if (rc)
 409			break;
 410		idx = (idx - 1 + ATA_ERING_SIZE) % ATA_ERING_SIZE;
 411	} while (idx != ering->cursor);
 412
 413	return rc;
 414}
 415
 416static int ata_ering_clear_cb(struct ata_ering_entry *ent, void *void_arg)
 417{
 418	ent->eflags |= ATA_EFLAG_OLD_ER;
 419	return 0;
 420}
 421
 422static void ata_ering_clear(struct ata_ering *ering)
 423{
 424	ata_ering_map(ering, ata_ering_clear_cb, NULL);
 425}
 426
 427static unsigned int ata_eh_dev_action(struct ata_device *dev)
 428{
 429	struct ata_eh_context *ehc = &dev->link->eh_context;
 430
 431	return ehc->i.action | ehc->i.dev_action[dev->devno];
 432}
 433
 434static void ata_eh_clear_action(struct ata_link *link, struct ata_device *dev,
 435				struct ata_eh_info *ehi, unsigned int action)
 436{
 437	struct ata_device *tdev;
 438
 439	if (!dev) {
 440		ehi->action &= ~action;
 441		ata_for_each_dev(tdev, link, ALL)
 442			ehi->dev_action[tdev->devno] &= ~action;
 443	} else {
 444		/* doesn't make sense for port-wide EH actions */
 445		WARN_ON(!(action & ATA_EH_PERDEV_MASK));
 446
 447		/* break ehi->action into ehi->dev_action */
 448		if (ehi->action & action) {
 449			ata_for_each_dev(tdev, link, ALL)
 450				ehi->dev_action[tdev->devno] |=
 451					ehi->action & action;
 452			ehi->action &= ~action;
 453		}
 454
 455		/* turn off the specified per-dev action */
 456		ehi->dev_action[dev->devno] &= ~action;
 457	}
 458}
 459
 460/**
 461 *	ata_eh_acquire - acquire EH ownership
 462 *	@ap: ATA port to acquire EH ownership for
 463 *
 464 *	Acquire EH ownership for @ap.  This is the basic exclusion
 465 *	mechanism for ports sharing a host.  Only one port hanging off
 466 *	the same host can claim the ownership of EH.
 467 *
 468 *	LOCKING:
 469 *	EH context.
 470 */
 471void ata_eh_acquire(struct ata_port *ap)
 472{
 473	mutex_lock(&ap->host->eh_mutex);
 474	WARN_ON_ONCE(ap->host->eh_owner);
 475	ap->host->eh_owner = current;
 476}
 477
 478/**
 479 *	ata_eh_release - release EH ownership
 480 *	@ap: ATA port to release EH ownership for
 481 *
 482 *	Release EH ownership for @ap if the caller.  The caller must
 483 *	have acquired EH ownership using ata_eh_acquire() previously.
 484 *
 485 *	LOCKING:
 486 *	EH context.
 487 */
 488void ata_eh_release(struct ata_port *ap)
 489{
 490	WARN_ON_ONCE(ap->host->eh_owner != current);
 491	ap->host->eh_owner = NULL;
 492	mutex_unlock(&ap->host->eh_mutex);
 493}
 494
 495static void ata_eh_dev_disable(struct ata_device *dev)
 496{
 497	ata_acpi_on_disable(dev);
 498	ata_down_xfermask_limit(dev, ATA_DNXFER_FORCE_PIO0 | ATA_DNXFER_QUIET);
 499	dev->class++;
 500
 501	/*
 502	 * From now till the next successful probe, ering is used to
 503	 * track probe failures.  Clear accumulated device error info.
 504	 */
 505	ata_ering_clear(&dev->ering);
 506
 507	ata_dev_free_resources(dev);
 508}
 509
 510static void ata_eh_unload(struct ata_port *ap)
 511{
 512	struct ata_link *link;
 513	struct ata_device *dev;
 514	unsigned long flags;
 515
 516	/*
 517	 * Unless we are restarting, transition all enabled devices to
 518	 * standby power mode.
 519	 */
 520	if (system_state != SYSTEM_RESTART) {
 521		ata_for_each_link(link, ap, PMP_FIRST) {
 522			ata_for_each_dev(dev, link, ENABLED)
 523				ata_dev_power_set_standby(dev);
 524		}
 525	}
 526
 527	/*
 528	 * Restore SControl IPM and SPD for the next driver and
 529	 * disable attached devices.
 530	 */
 531	ata_for_each_link(link, ap, PMP_FIRST) {
 532		sata_scr_write(link, SCR_CONTROL, link->saved_scontrol & 0xff0);
 533		ata_for_each_dev(dev, link, ENABLED)
 534			ata_eh_dev_disable(dev);
 535	}
 536
 537	/* freeze and set UNLOADED */
 538	spin_lock_irqsave(ap->lock, flags);
 539
 540	ata_port_freeze(ap);			/* won't be thawed */
 541	ap->pflags &= ~ATA_PFLAG_EH_PENDING;	/* clear pending from freeze */
 542	ap->pflags |= ATA_PFLAG_UNLOADED;
 543
 544	spin_unlock_irqrestore(ap->lock, flags);
 545}
 546
 547/**
 548 *	ata_scsi_error - SCSI layer error handler callback
 549 *	@host: SCSI host on which error occurred
 550 *
 551 *	Handles SCSI-layer-thrown error events.
 552 *
 553 *	LOCKING:
 554 *	Inherited from SCSI layer (none, can sleep)
 555 *
 556 *	RETURNS:
 557 *	Zero.
 558 */
 559void ata_scsi_error(struct Scsi_Host *host)
 560{
 561	struct ata_port *ap = ata_shost_to_port(host);
 562	unsigned long flags;
 563	LIST_HEAD(eh_work_q);
 564
 565	spin_lock_irqsave(host->host_lock, flags);
 566	list_splice_init(&host->eh_cmd_q, &eh_work_q);
 567	spin_unlock_irqrestore(host->host_lock, flags);
 568
 569	ata_scsi_cmd_error_handler(host, ap, &eh_work_q);
 570
 571	/* If we timed raced normal completion and there is nothing to
 572	   recover nr_timedout == 0 why exactly are we doing error recovery ? */
 573	ata_scsi_port_error_handler(host, ap);
 574
 575	/* finish or retry handled scmd's and clean up */
 576	WARN_ON(!list_empty(&eh_work_q));
 577
 578}
 579
 580/**
 581 * ata_scsi_cmd_error_handler - error callback for a list of commands
 582 * @host:	scsi host containing the port
 583 * @ap:		ATA port within the host
 584 * @eh_work_q:	list of commands to process
 585 *
 586 * process the given list of commands and return those finished to the
 587 * ap->eh_done_q.  This function is the first part of the libata error
 588 * handler which processes a given list of failed commands.
 589 */
 590void ata_scsi_cmd_error_handler(struct Scsi_Host *host, struct ata_port *ap,
 591				struct list_head *eh_work_q)
 592{
 593	int i;
 594	unsigned long flags;
 595	struct scsi_cmnd *scmd, *tmp;
 596	int nr_timedout = 0;
 597
 598	/* make sure sff pio task is not running */
 599	ata_sff_flush_pio_task(ap);
 600
 601	/* synchronize with host lock and sort out timeouts */
 602
 603	/*
 604	 * For EH, all qcs are finished in one of three ways -
 605	 * normal completion, error completion, and SCSI timeout.
 606	 * Both completions can race against SCSI timeout.  When normal
 607	 * completion wins, the qc never reaches EH.  When error
 608	 * completion wins, the qc has ATA_QCFLAG_EH set.
 609	 *
 610	 * When SCSI timeout wins, things are a bit more complex.
 611	 * Normal or error completion can occur after the timeout but
 612	 * before this point.  In such cases, both types of
 613	 * completions are honored.  A scmd is determined to have
 614	 * timed out iff its associated qc is active and not failed.
 615	 */
 616	spin_lock_irqsave(ap->lock, flags);
 617
 618	/*
 619	 * This must occur under the ap->lock as we don't want
 620	 * a polled recovery to race the real interrupt handler
 621	 *
 622	 * The lost_interrupt handler checks for any completed but
 623	 * non-notified command and completes much like an IRQ handler.
 624	 *
 625	 * We then fall into the error recovery code which will treat
 626	 * this as if normal completion won the race
 627	 */
 628	if (ap->ops->lost_interrupt)
 629		ap->ops->lost_interrupt(ap);
 630
 631	list_for_each_entry_safe(scmd, tmp, eh_work_q, eh_entry) {
 632		struct ata_queued_cmd *qc;
 633
 634		/*
 635		 * If the scmd was added to EH, via ata_qc_schedule_eh() ->
 636		 * scsi_timeout() -> scsi_eh_scmd_add(), scsi_timeout() will
 637		 * have set DID_TIME_OUT (since libata does not have an abort
 638		 * handler). Thus, to clear DID_TIME_OUT, clear the host byte.
 639		 */
 640		set_host_byte(scmd, DID_OK);
 641
 642		ata_qc_for_each_raw(ap, qc, i) {
 643			if (qc->scsicmd != scmd)
 644				continue;
 645			if ((qc->flags & ATA_QCFLAG_ACTIVE) ||
 646			    qc == ap->deferred_qc)
 647				break;
 648		}
 649
 650		if (i < ATA_MAX_QUEUE && qc == ap->deferred_qc) {
 651			/*
 652			 * This is a deferred command that timed out while
 653			 * waiting for the command queue to drain. Since the qc
 654			 * is not active yet (deferred_qc is still set, so the
 655			 * deferred qc work has not issued the command yet),
 656			 * simply signal the timeout by finishing the SCSI
 657			 * command and clear the deferred qc to prevent the
 658			 * deferred qc work from issuing this qc.
 659			 */
 660			WARN_ON_ONCE(qc->flags & ATA_QCFLAG_ACTIVE);
 661			ap->deferred_qc = NULL;
 662			cancel_work(&ap->deferred_qc_work);
 663			set_host_byte(scmd, DID_TIME_OUT);
 664			scsi_eh_finish_cmd(scmd, &ap->eh_done_q);
 665		} else if (i < ATA_MAX_QUEUE) {
 666			/* the scmd has an associated qc */
 667			if (!(qc->flags & ATA_QCFLAG_EH)) {
 668				/* which hasn't failed yet, timeout */
 669				set_host_byte(scmd, DID_TIME_OUT);
 670				qc->err_mask |= AC_ERR_TIMEOUT;
 671				qc->flags |= ATA_QCFLAG_EH;
 672				nr_timedout++;
 673			}
 674		} else {
 675			/* Normal completion occurred after
 676			 * SCSI timeout but before this point.
 677			 * Successfully complete it.
 678			 */
 679			scmd->retries = scmd->allowed;
 680			scsi_eh_finish_cmd(scmd, &ap->eh_done_q);
 681		}
 682	}
 683
 684	/*
 685	 * If we have timed out qcs.  They belong to EH from
 686	 * this point but the state of the controller is
 687	 * unknown.  Freeze the port to make sure the IRQ
 688	 * handler doesn't diddle with those qcs.  This must
 689	 * be done atomically w.r.t. setting ATA_QCFLAG_EH.
 690	 */
 691	if (nr_timedout)
 692		__ata_port_freeze(ap);
 693
 694	/* initialize eh_tries */
 695	ap->eh_tries = ATA_EH_MAX_TRIES;
 696
 697	spin_unlock_irqrestore(ap->lock, flags);
 698}
 699EXPORT_SYMBOL(ata_scsi_cmd_error_handler);
 700
 701/**
 702 * ata_scsi_port_error_handler - recover the port after the commands
 703 * @host:	SCSI host containing the port
 704 * @ap:		the ATA port
 705 *
 706 * Handle the recovery of the port @ap after all the commands
 707 * have been recovered.
 708 */
 709void ata_scsi_port_error_handler(struct Scsi_Host *host, struct ata_port *ap)
 710{
 711	unsigned long flags;
 712	struct ata_link *link;
 713
 714	/* acquire EH ownership */
 715	ata_eh_acquire(ap);
 716 repeat:
 717	/* kill fast drain timer */
 718	timer_delete_sync(&ap->fastdrain_timer);
 719
 720	/* process port resume request */
 721	ata_eh_handle_port_resume(ap);
 722
 723	/* fetch & clear EH info */
 724	spin_lock_irqsave(ap->lock, flags);
 725
 726	ata_for_each_link(link, ap, HOST_FIRST) {
 727		struct ata_eh_context *ehc = &link->eh_context;
 728		struct ata_device *dev;
 729
 730		memset(&link->eh_context, 0, sizeof(link->eh_context));
 731		link->eh_context.i = link->eh_info;
 732		memset(&link->eh_info, 0, sizeof(link->eh_info));
 733
 734		ata_for_each_dev(dev, link, ENABLED) {
 735			int devno = dev->devno;
 736
 737			ehc->saved_xfer_mode[devno] = dev->xfer_mode;
 738			if (ata_ncq_enabled(dev))
 739				ehc->saved_ncq_enabled |= 1 << devno;
 740
 741			/* If we are resuming, wake up the device */
 742			if (ap->pflags & ATA_PFLAG_RESUMING) {
 743				dev->flags |= ATA_DFLAG_RESUMING;
 744				ehc->i.dev_action[devno] |= ATA_EH_SET_ACTIVE;
 745			}
 746		}
 747	}
 748
 749	ap->pflags |= ATA_PFLAG_EH_IN_PROGRESS;
 750	ap->pflags &= ~ATA_PFLAG_EH_PENDING;
 751	ap->excl_link = NULL;	/* don't maintain exclusion over EH */
 752
 753	spin_unlock_irqrestore(ap->lock, flags);
 754
 755	/* invoke EH, skip if unloading or suspended */
 756	if (!(ap->pflags & (ATA_PFLAG_UNLOADING | ATA_PFLAG_SUSPENDED)) &&
 757	    ata_adapter_is_online(ap))
 758		ap->ops->error_handler(ap);
 759	else {
 760		/* if unloading, commence suicide */
 761		if ((ap->pflags & ATA_PFLAG_UNLOADING) &&
 762		    !(ap->pflags & ATA_PFLAG_UNLOADED))
 763			ata_eh_unload(ap);
 764		ata_eh_finish(ap);
 765	}
 766
 767	/* process port suspend request */
 768	ata_eh_handle_port_suspend(ap);
 769
 770	/*
 771	 * Exception might have happened after ->error_handler recovered the
 772	 * port but before this point.  Repeat EH in such case.
 773	 */
 774	spin_lock_irqsave(ap->lock, flags);
 775
 776	if (ap->pflags & ATA_PFLAG_EH_PENDING) {
 777		if (--ap->eh_tries) {
 778			spin_unlock_irqrestore(ap->lock, flags);
 779			goto repeat;
 780		}
 781		ata_port_err(ap,
 782			     "EH pending after %d tries, giving up\n",
 783			     ATA_EH_MAX_TRIES);
 784		ap->pflags &= ~ATA_PFLAG_EH_PENDING;
 785	}
 786
 787	/* this run is complete, make sure EH info is clear */
 788	ata_for_each_link(link, ap, HOST_FIRST)
 789		memset(&link->eh_info, 0, sizeof(link->eh_info));
 790
 791	/*
 792	 * end eh (clear host_eh_scheduled) while holding ap->lock such that if
 793	 * exception occurs after this point but before EH completion, SCSI
 794	 * midlayer will re-initiate EH.
 795	 */
 796	ap->ops->end_eh(ap);
 797
 798	spin_unlock_irqrestore(ap->lock, flags);
 799	ata_eh_release(ap);
 800
 801	scsi_eh_flush_done_q(&ap->eh_done_q);
 802
 803	/* clean up */
 804	spin_lock_irqsave(ap->lock, flags);
 805
 806	ap->pflags &= ~ATA_PFLAG_RESUMING;
 807
 808	if (ap->pflags & ATA_PFLAG_LOADING)
 809		ap->pflags &= ~ATA_PFLAG_LOADING;
 810	else if ((ap->pflags & ATA_PFLAG_SCSI_HOTPLUG) &&
 811		!(ap->flags & ATA_FLAG_SAS_HOST))
 812		schedule_delayed_work(&ap->hotplug_task, 0);
 813
 814	if (ap->pflags & ATA_PFLAG_RECOVERED)
 815		ata_port_info(ap, "EH complete\n");
 816
 817	ap->pflags &= ~(ATA_PFLAG_SCSI_HOTPLUG | ATA_PFLAG_RECOVERED);
 818
 819	/* tell wait_eh that we're done */
 820	ap->pflags &= ~ATA_PFLAG_EH_IN_PROGRESS;
 821	wake_up_all(&ap->eh_wait_q);
 822
 823	spin_unlock_irqrestore(ap->lock, flags);
 824}
 825EXPORT_SYMBOL_GPL(ata_scsi_port_error_handler);
 826
 827/**
 828 *	ata_port_wait_eh - Wait for the currently pending EH to complete
 829 *	@ap: Port to wait EH for
 830 *
 831 *	Wait until the currently pending EH is complete.
 832 *
 833 *	LOCKING:
 834 *	Kernel thread context (may sleep).
 835 */
 836void ata_port_wait_eh(struct ata_port *ap)
 837{
 838	unsigned long flags;
 839	DEFINE_WAIT(wait);
 840
 841 retry:
 842	spin_lock_irqsave(ap->lock, flags);
 843
 844	while (ata_port_eh_scheduled(ap)) {
 845		prepare_to_wait(&ap->eh_wait_q, &wait, TASK_UNINTERRUPTIBLE);
 846		spin_unlock_irqrestore(ap->lock, flags);
 847		schedule();
 848		spin_lock_irqsave(ap->lock, flags);
 849	}
 850	finish_wait(&ap->eh_wait_q, &wait);
 851
 852	spin_unlock_irqrestore(ap->lock, flags);
 853
 854	/* make sure SCSI EH is complete */
 855	if (scsi_host_in_recovery(ap->scsi_host)) {
 856		ata_msleep(ap, 10);
 857		goto retry;
 858	}
 859}
 860EXPORT_SYMBOL_GPL(ata_port_wait_eh);
 861
 862static unsigned int ata_eh_nr_in_flight(struct ata_port *ap)
 863{
 864	struct ata_queued_cmd *qc;
 865	unsigned int tag;
 866	unsigned int nr = 0;
 867
 868	/* count only non-internal commands */
 869	ata_qc_for_each(ap, qc, tag) {
 870		if (qc)
 871			nr++;
 872	}
 873
 874	return nr;
 875}
 876
 877void ata_eh_fastdrain_timerfn(struct timer_list *t)
 878{
 879	struct ata_port *ap = timer_container_of(ap, t, fastdrain_timer);
 880	unsigned long flags;
 881	unsigned int cnt;
 882
 883	spin_lock_irqsave(ap->lock, flags);
 884
 885	cnt = ata_eh_nr_in_flight(ap);
 886
 887	/* are we done? */
 888	if (!cnt)
 889		goto out_unlock;
 890
 891	if (cnt == ap->fastdrain_cnt) {
 892		struct ata_queued_cmd *qc;
 893		unsigned int tag;
 894
 895		/* No progress during the last interval, tag all
 896		 * in-flight qcs as timed out and freeze the port.
 897		 */
 898		ata_qc_for_each(ap, qc, tag) {
 899			if (qc)
 900				qc->err_mask |= AC_ERR_TIMEOUT;
 901		}
 902
 903		ata_port_freeze(ap);
 904	} else {
 905		/* some qcs have finished, give it another chance */
 906		ap->fastdrain_cnt = cnt;
 907		ap->fastdrain_timer.expires =
 908			ata_deadline(jiffies, ATA_EH_FASTDRAIN_INTERVAL);
 909		add_timer(&ap->fastdrain_timer);
 910	}
 911
 912 out_unlock:
 913	spin_unlock_irqrestore(ap->lock, flags);
 914}
 915
 916/**
 917 *	ata_eh_set_pending - set ATA_PFLAG_EH_PENDING and activate fast drain
 918 *	@ap: target ATA port
 919 *	@fastdrain: activate fast drain
 920 *
 921 *	Set ATA_PFLAG_EH_PENDING and activate fast drain if @fastdrain
 922 *	is non-zero and EH wasn't pending before.  Fast drain ensures
 923 *	that EH kicks in in timely manner.
 924 *
 925 *	LOCKING:
 926 *	spin_lock_irqsave(host lock)
 927 */
 928static void ata_eh_set_pending(struct ata_port *ap, bool fastdrain)
 929{
 930	unsigned int cnt;
 931
 932	/* already scheduled? */
 933	if (ap->pflags & ATA_PFLAG_EH_PENDING)
 934		return;
 935
 936	ap->pflags |= ATA_PFLAG_EH_PENDING;
 937
 938	/*
 939	 * If we have a deferred qc, requeue it so that it is retried once EH
 940	 * completes.
 941	 */
 942	ata_scsi_requeue_deferred_qc(ap);
 943
 944	if (!fastdrain)
 945		return;
 946
 947	/* do we have in-flight qcs? */
 948	cnt = ata_eh_nr_in_flight(ap);
 949	if (!cnt)
 950		return;
 951
 952	/* activate fast drain */
 953	ap->fastdrain_cnt = cnt;
 954	ap->fastdrain_timer.expires =
 955		ata_deadline(jiffies, ATA_EH_FASTDRAIN_INTERVAL);
 956	add_timer(&ap->fastdrain_timer);
 957}
 958
 959/**
 960 *	ata_qc_schedule_eh - schedule qc for error handling
 961 *	@qc: command to schedule error handling for
 962 *
 963 *	Schedule error handling for @qc.  EH will kick in as soon as
 964 *	other commands are drained.
 965 *
 966 *	LOCKING:
 967 *	spin_lock_irqsave(host lock)
 968 */
 969void ata_qc_schedule_eh(struct ata_queued_cmd *qc)
 970{
 971	struct ata_port *ap = qc->ap;
 972
 973	qc->flags |= ATA_QCFLAG_EH;
 974	ata_eh_set_pending(ap, true);
 975
 976	/* The following will fail if timeout has already expired.
 977	 * ata_scsi_error() takes care of such scmds on EH entry.
 978	 * Note that ATA_QCFLAG_EH is unconditionally set after
 979	 * this function completes.
 980	 */
 981	blk_abort_request(scsi_cmd_to_rq(qc->scsicmd));
 982}
 983
 984/**
 985 * ata_std_sched_eh - non-libsas ata_ports issue eh with this common routine
 986 * @ap: ATA port to schedule EH for
 987 *
 988 *	LOCKING: inherited from ata_port_schedule_eh
 989 *	spin_lock_irqsave(host lock)
 990 */
 991void ata_std_sched_eh(struct ata_port *ap)
 992{
 993	if (ap->pflags & ATA_PFLAG_INITIALIZING)
 994		return;
 995
 996	ata_eh_set_pending(ap, true);
 997	scsi_schedule_eh(ap->scsi_host);
 998
 999	trace_ata_std_sched_eh(ap);
1000}
1001EXPORT_SYMBOL_GPL(ata_std_sched_eh);
1002
1003/**
1004 * ata_std_end_eh - non-libsas ata_ports complete eh with this common routine
1005 * @ap: ATA port to end EH for
1006 *
1007 * In the libata object model there is a 1:1 mapping of ata_port to
1008 * shost, so host fields can be directly manipulated under ap->lock, in
1009 * the libsas case we need to hold a lock at the ha->level to coordinate
1010 * these events.
1011 *
1012 *	LOCKING:
1013 *	spin_lock_irqsave(host lock)
1014 */
1015void ata_std_end_eh(struct ata_port *ap)
1016{
1017	struct Scsi_Host *host = ap->scsi_host;
1018
1019	host->host_eh_scheduled = 0;
1020}
1021EXPORT_SYMBOL(ata_std_end_eh);
1022
1023
1024/**
1025 *	ata_port_schedule_eh - schedule error handling without a qc
1026 *	@ap: ATA port to schedule EH for
1027 *
1028 *	Schedule error handling for @ap.  EH will kick in as soon as
1029 *	all commands are drained.
1030 *
1031 *	LOCKING:
1032 *	spin_lock_irqsave(host lock)
1033 */
1034void ata_port_schedule_eh(struct ata_port *ap)
1035{
1036	/* see: ata_std_sched_eh, unless you know better */
1037	ap->ops->sched_eh(ap);
1038}
1039EXPORT_SYMBOL_GPL(ata_port_schedule_eh);
1040
1041static int ata_do_link_abort(struct ata_port *ap, struct ata_link *link)
1042{
1043	struct ata_queued_cmd *qc;
1044	int tag, nr_aborted = 0;
1045
1046	/* we're gonna abort all commands, no need for fast drain */
1047	ata_eh_set_pending(ap, false);
1048
1049	/* include internal tag in iteration */
1050	ata_qc_for_each_with_internal(ap, qc, tag) {
1051		if (qc && (!link || qc->dev->link == link)) {
1052			qc->flags |= ATA_QCFLAG_EH;
1053			ata_qc_complete(qc);
1054			nr_aborted++;
1055		}
1056	}
1057
1058	if (!nr_aborted)
1059		ata_port_schedule_eh(ap);
1060
1061	return nr_aborted;
1062}
1063
1064/**
1065 *	ata_link_abort - abort all qc's on the link
1066 *	@link: ATA link to abort qc's for
1067 *
1068 *	Abort all active qc's active on @link and schedule EH.
1069 *
1070 *	LOCKING:
1071 *	spin_lock_irqsave(host lock)
1072 *
1073 *	RETURNS:
1074 *	Number of aborted qc's.
1075 */
1076int ata_link_abort(struct ata_link *link)
1077{
1078	return ata_do_link_abort(link->ap, link);
1079}
1080EXPORT_SYMBOL_GPL(ata_link_abort);
1081
1082/**
1083 *	ata_port_abort - abort all qc's on the port
1084 *	@ap: ATA port to abort qc's for
1085 *
1086 *	Abort all active qc's of @ap and schedule EH.
1087 *
1088 *	LOCKING:
1089 *	spin_lock_irqsave(host_set lock)
1090 *
1091 *	RETURNS:
1092 *	Number of aborted qc's.
1093 */
1094int ata_port_abort(struct ata_port *ap)
1095{
1096	return ata_do_link_abort(ap, NULL);
1097}
1098EXPORT_SYMBOL_GPL(ata_port_abort);
1099
1100/**
1101 *	__ata_port_freeze - freeze port
1102 *	@ap: ATA port to freeze
1103 *
1104 *	This function is called when HSM violation or some other
1105 *	condition disrupts normal operation of the port.  Frozen port
1106 *	is not allowed to perform any operation until the port is
1107 *	thawed, which usually follows a successful reset.
1108 *
1109 *	ap->ops->freeze() callback can be used for freezing the port
1110 *	hardware-wise (e.g. mask interrupt and stop DMA engine).  If a
1111 *	port cannot be frozen hardware-wise, the interrupt handler
1112 *	must ack and clear interrupts unconditionally while the port
1113 *	is frozen.
1114 *
1115 *	LOCKING:
1116 *	spin_lock_irqsave(host lock)
1117 */
1118static void __ata_port_freeze(struct ata_port *ap)
1119{
1120	if (ap->ops->freeze)
1121		ap->ops->freeze(ap);
1122
1123	ap->pflags |= ATA_PFLAG_FROZEN;
1124
1125	trace_ata_port_freeze(ap);
1126}
1127
1128/**
1129 *	ata_port_freeze - abort & freeze port
1130 *	@ap: ATA port to freeze
1131 *
1132 *	Abort and freeze @ap.  The freeze operation must be called
1133 *	first, because some hardware requires special operations
1134 *	before the taskfile registers are accessible.
1135 *
1136 *	LOCKING:
1137 *	spin_lock_irqsave(host lock)
1138 *
1139 *	RETURNS:
1140 *	Number of aborted commands.
1141 */
1142int ata_port_freeze(struct ata_port *ap)
1143{
1144	__ata_port_freeze(ap);
1145
1146	return ata_port_abort(ap);
1147}
1148EXPORT_SYMBOL_GPL(ata_port_freeze);
1149
1150/**
1151 *	ata_eh_freeze_port - EH helper to freeze port
1152 *	@ap: ATA port to freeze
1153 *
1154 *	Freeze @ap.
1155 *
1156 *	LOCKING:
1157 *	None.
1158 */
1159void ata_eh_freeze_port(struct ata_port *ap)
1160{
1161	unsigned long flags;
1162
1163	spin_lock_irqsave(ap->lock, flags);
1164	__ata_port_freeze(ap);
1165	spin_unlock_irqrestore(ap->lock, flags);
1166}
1167EXPORT_SYMBOL_GPL(ata_eh_freeze_port);
1168
1169/**
1170 *	ata_eh_thaw_port - EH helper to thaw port
1171 *	@ap: ATA port to thaw
1172 *
1173 *	Thaw frozen port @ap.
1174 *
1175 *	LOCKING:
1176 *	None.
1177 */
1178void ata_eh_thaw_port(struct ata_port *ap)
1179{
1180	unsigned long flags;
1181
1182	spin_lock_irqsave(ap->lock, flags);
1183
1184	ap->pflags &= ~ATA_PFLAG_FROZEN;
1185
1186	if (ap->ops->thaw)
1187		ap->ops->thaw(ap);
1188
1189	spin_unlock_irqrestore(ap->lock, flags);
1190
1191	trace_ata_port_thaw(ap);
1192}
1193
1194static void ata_eh_scsidone(struct scsi_cmnd *scmd)
1195{
1196	/* nada */
1197}
1198
1199static void __ata_eh_qc_complete(struct ata_queued_cmd *qc)
1200{
1201	struct ata_port *ap = qc->ap;
1202	struct scsi_cmnd *scmd = qc->scsicmd;
1203	unsigned long flags;
1204
1205	spin_lock_irqsave(ap->lock, flags);
1206	qc->scsidone = ata_eh_scsidone;
1207	__ata_qc_complete(qc);
1208	WARN_ON(ata_tag_valid(qc->tag));
1209	spin_unlock_irqrestore(ap->lock, flags);
1210
1211	scsi_eh_finish_cmd(scmd, &ap->eh_done_q);
1212}
1213
1214/**
1215 *	ata_eh_qc_complete - Complete an active ATA command from EH
1216 *	@qc: Command to complete
1217 *
1218 *	Indicate to the mid and upper layers that an ATA command has
1219 *	completed.  To be used from EH.
1220 */
1221void ata_eh_qc_complete(struct ata_queued_cmd *qc)
1222{
1223	struct scsi_cmnd *scmd = qc->scsicmd;
1224	scmd->retries = scmd->allowed;
1225	__ata_eh_qc_complete(qc);
1226}
1227
1228/**
1229 *	ata_eh_qc_retry - Tell midlayer to retry an ATA command after EH
1230 *	@qc: Command to retry
1231 *
1232 *	Indicate to the mid and upper layers that an ATA command
1233 *	should be retried.  To be used from EH.
1234 *
1235 *	SCSI midlayer limits the number of retries to scmd->allowed.
1236 *	scmd->allowed is incremented for commands which get retried
1237 *	due to unrelated failures (qc->err_mask is zero).
1238 */
1239void ata_eh_qc_retry(struct ata_queued_cmd *qc)
1240{
1241	struct scsi_cmnd *scmd = qc->scsicmd;
1242	if (!qc->err_mask)
1243		scmd->allowed++;
1244	__ata_eh_qc_complete(qc);
1245}
1246
1247/**
1248 *	ata_dev_disable - disable ATA device
1249 *	@dev: ATA device to disable
1250 *
1251 *	Disable @dev.
1252 *
1253 *	Locking:
1254 *	EH context.
1255 */
1256void ata_dev_disable(struct ata_device *dev)
1257{
1258	if (!ata_dev_enabled(dev))
1259		return;
1260
1261	ata_dev_warn(dev, "disable device\n");
1262
1263	ata_eh_dev_disable(dev);
1264}
1265EXPORT_SYMBOL_GPL(ata_dev_disable);
1266
1267/**
1268 *	ata_eh_detach_dev - detach ATA device
1269 *	@dev: ATA device to detach
1270 *
1271 *	Detach @dev.
1272 *
1273 *	LOCKING:
1274 *	None.
1275 */
1276void ata_eh_detach_dev(struct ata_device *dev)
1277{
1278	struct ata_link *link = dev->link;
1279	struct ata_port *ap = link->ap;
1280	struct ata_eh_context *ehc = &link->eh_context;
1281	unsigned long flags;
1282
1283	/*
1284	 * If the device is still enabled, transition it to standby power mode
1285	 * (i.e. spin down HDDs) and disable it.
1286	 */
1287	if (ata_dev_enabled(dev)) {
1288		ata_dev_power_set_standby(dev);
1289		ata_eh_dev_disable(dev);
1290	}
1291
1292	spin_lock_irqsave(ap->lock, flags);
1293
1294	dev->flags &= ~ATA_DFLAG_DETACH;
1295
1296	if (ata_scsi_offline_dev(dev)) {
1297		dev->flags |= ATA_DFLAG_DETACHED;
1298		ap->pflags |= ATA_PFLAG_SCSI_HOTPLUG;
1299	}
1300
1301	/* clear per-dev EH info */
1302	ata_eh_clear_action(link, dev, &link->eh_info, ATA_EH_PERDEV_MASK);
1303	ata_eh_clear_action(link, dev, &link->eh_context.i, ATA_EH_PERDEV_MASK);
1304	ehc->saved_xfer_mode[dev->devno] = 0;
1305	ehc->saved_ncq_enabled &= ~(1 << dev->devno);
1306
1307	spin_unlock_irqrestore(ap->lock, flags);
1308}
1309
1310/**
1311 *	ata_eh_about_to_do - about to perform eh_action
1312 *	@link: target ATA link
1313 *	@dev: target ATA dev for per-dev action (can be NULL)
1314 *	@action: action about to be performed
1315 *
1316 *	Called just before performing EH actions to clear related bits
1317 *	in @link->eh_info such that eh actions are not unnecessarily
1318 *	repeated.
1319 *
1320 *	LOCKING:
1321 *	None.
1322 */
1323void ata_eh_about_to_do(struct ata_link *link, struct ata_device *dev,
1324			unsigned int action)
1325{
1326	struct ata_port *ap = link->ap;
1327	struct ata_eh_info *ehi = &link->eh_info;
1328	struct ata_eh_context *ehc = &link->eh_context;
1329	unsigned long flags;
1330
1331	trace_ata_eh_about_to_do(link, dev ? dev->devno : 0, action);
1332
1333	spin_lock_irqsave(ap->lock, flags);
1334
1335	ata_eh_clear_action(link, dev, ehi, action);
1336
1337	/* About to take EH action, set RECOVERED.  Ignore actions on
1338	 * slave links as master will do them again.
1339	 */
1340	if (!(ehc->i.flags & ATA_EHI_QUIET) && link != ap->slave_link)
1341		ap->pflags |= ATA_PFLAG_RECOVERED;
1342
1343	spin_unlock_irqrestore(ap->lock, flags);
1344}
1345
1346/**
1347 *	ata_eh_done - EH action complete
1348 *	@link: ATA link for which EH actions are complete
1349 *	@dev: target ATA dev for per-dev action (can be NULL)
1350 *	@action: action just completed
1351 *
1352 *	Called right after performing EH actions to clear related bits
1353 *	in @link->eh_context.
1354 *
1355 *	LOCKING:
1356 *	None.
1357 */
1358void ata_eh_done(struct ata_link *link, struct ata_device *dev,
1359		 unsigned int action)
1360{
1361	struct ata_eh_context *ehc = &link->eh_context;
1362
1363	trace_ata_eh_done(link, dev ? dev->devno : 0, action);
1364
1365	ata_eh_clear_action(link, dev, &ehc->i, action);
1366}
1367
1368/**
1369 *	ata_err_string - convert err_mask to descriptive string
1370 *	@err_mask: error mask to convert to string
1371 *
1372 *	Convert @err_mask to descriptive string.  Errors are
1373 *	prioritized according to severity and only the most severe
1374 *	error is reported.
1375 *
1376 *	LOCKING:
1377 *	None.
1378 *
1379 *	RETURNS:
1380 *	Descriptive string for @err_mask
1381 */
1382static const char *ata_err_string(unsigned int err_mask)
1383{
1384	if (err_mask & AC_ERR_HOST_BUS)
1385		return "host bus error";
1386	if (err_mask & AC_ERR_ATA_BUS)
1387		return "ATA bus error";
1388	if (err_mask & AC_ERR_TIMEOUT)
1389		return "timeout";
1390	if (err_mask & AC_ERR_HSM)
1391		return "HSM violation";
1392	if (err_mask & AC_ERR_SYSTEM)
1393		return "internal error";
1394	if (err_mask & AC_ERR_MEDIA)
1395		return "media error";
1396	if (err_mask & AC_ERR_INVALID)
1397		return "invalid argument";
1398	if (err_mask & AC_ERR_DEV)
1399		return "device error";
1400	if (err_mask & AC_ERR_NCQ)
1401		return "NCQ error";
1402	if (err_mask & AC_ERR_NODEV_HINT)
1403		return "Polling detection error";
1404	return "unknown error";
1405}
1406
1407/**
1408 *	atapi_eh_tur - perform ATAPI TEST_UNIT_READY
1409 *	@dev: target ATAPI device
1410 *	@r_sense_key: out parameter for sense_key
1411 *
1412 *	Perform ATAPI TEST_UNIT_READY.
1413 *
1414 *	LOCKING:
1415 *	EH context (may sleep).
1416 *
1417 *	RETURNS:
1418 *	0 on success, AC_ERR_* mask on failure.
1419 */
1420unsigned int atapi_eh_tur(struct ata_device *dev, u8 *r_sense_key)
1421{
1422	u8 cdb[ATAPI_CDB_LEN] = { TEST_UNIT_READY, 0, 0, 0, 0, 0 };
1423	struct ata_taskfile tf;
1424	unsigned int err_mask;
1425
1426	ata_tf_init(dev, &tf);
1427
1428	tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
1429	tf.command = ATA_CMD_PACKET;
1430	tf.protocol = ATAPI_PROT_NODATA;
1431
1432	err_mask = ata_exec_internal(dev, &tf, cdb, DMA_NONE, NULL, 0, 0);
1433	if (err_mask == AC_ERR_DEV)
1434		*r_sense_key = tf.error >> 4;
1435	return err_mask;
1436}
1437
1438/**
1439 *	ata_eh_decide_disposition - Disposition a qc based on sense data
1440 *	@qc: qc to examine
1441 *
1442 *	For a regular SCSI command, the SCSI completion callback (scsi_done())
1443 *	will call scsi_complete(), which will call scsi_decide_disposition(),
1444 *	which will call scsi_check_sense(). scsi_complete() finally calls
1445 *	scsi_finish_command(). This is fine for SCSI, since any eventual sense
1446 *	data is usually returned in the completion itself (without invoking SCSI
1447 *	EH). However, for a QC, we always need to fetch the sense data
1448 *	explicitly using SCSI EH.
1449 *
1450 *	A command that is completed via SCSI EH will instead be completed using
1451 *	scsi_eh_flush_done_q(), which will call scsi_finish_command() directly
1452 *	(without ever calling scsi_check_sense()).
1453 *
1454 *	For a command that went through SCSI EH, it is the responsibility of the
1455 *	SCSI EH strategy handler to call scsi_decide_disposition(), see e.g. how
1456 *	scsi_eh_get_sense() calls scsi_decide_disposition() for SCSI LLDDs that
1457 *	do not get the sense data as part of the completion.
1458 *
1459 *	Thus, for QC commands that went via SCSI EH, we need to call
1460 *	scsi_check_sense() ourselves, similar to how scsi_eh_get_sense() calls
1461 *	scsi_decide_disposition(), which calls scsi_check_sense(), in order to
1462 *	set the correct SCSI ML byte (if any).
1463 *
1464 *	LOCKING:
1465 *	EH context.
1466 *
1467 *	RETURNS:
1468 *	SUCCESS or FAILED or NEEDS_RETRY or ADD_TO_MLQUEUE
1469 */
1470enum scsi_disposition ata_eh_decide_disposition(struct ata_queued_cmd *qc)
1471{
1472	return scsi_check_sense(qc->scsicmd);
1473}
1474
1475/**
1476 *	ata_eh_request_sense - perform REQUEST_SENSE_DATA_EXT
1477 *	@qc: qc to perform REQUEST_SENSE_SENSE_DATA_EXT to
1478 *
1479 *	Perform REQUEST_SENSE_DATA_EXT after the device reported CHECK
1480 *	SENSE.  This function is an EH helper.
1481 *
1482 *	LOCKING:
1483 *	Kernel thread context (may sleep).
1484 *
1485 *	RETURNS:
1486 *	true if sense data could be fetched, false otherwise.
1487 */
1488static bool ata_eh_request_sense(struct ata_queued_cmd *qc)
1489{
1490	struct scsi_cmnd *cmd = qc->scsicmd;
1491	struct ata_device *dev = qc->dev;
1492	struct ata_taskfile tf;
1493	unsigned int err_mask;
1494
1495	if (ata_port_is_frozen(qc->ap)) {
1496		ata_dev_warn(dev, "sense data available but port frozen\n");
1497		return false;
1498	}
1499
1500	if (!ata_id_sense_reporting_enabled(dev->id)) {
1501		ata_dev_warn(qc->dev, "sense data reporting disabled\n");
1502		return false;
1503	}
1504
1505	ata_tf_init(dev, &tf);
1506	tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
1507	tf.flags |= ATA_TFLAG_LBA | ATA_TFLAG_LBA48;
1508	tf.command = ATA_CMD_REQ_SENSE_DATA;
1509	tf.protocol = ATA_PROT_NODATA;
1510
1511	err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
1512	/* Ignore err_mask; ATA_ERR might be set */
1513	if (tf.status & ATA_SENSE) {
1514		if (ata_scsi_sense_is_valid(tf.lbah, tf.lbam, tf.lbal)) {
1515			/* Set sense without also setting scsicmd->result */
1516			scsi_build_sense_buffer(dev->flags & ATA_DFLAG_D_SENSE,
1517						cmd->sense_buffer, tf.lbah,
1518						tf.lbam, tf.lbal);
1519			qc->flags |= ATA_QCFLAG_SENSE_VALID;
1520			return true;
1521		}
1522	} else {
1523		ata_dev_warn(dev, "request sense failed stat %02x emask %x\n",
1524			     tf.status, err_mask);
1525	}
1526
1527	return false;
1528}
1529
1530/**
1531 *	atapi_eh_request_sense - perform ATAPI REQUEST_SENSE
1532 *	@dev: device to perform REQUEST_SENSE to
1533 *	@sense_buf: result sense data buffer (SCSI_SENSE_BUFFERSIZE bytes long)
1534 *	@dfl_sense_key: default sense key to use
1535 *
1536 *	Perform ATAPI REQUEST_SENSE after the device reported CHECK
1537 *	SENSE.  This function is EH helper.
1538 *
1539 *	LOCKING:
1540 *	Kernel thread context (may sleep).
1541 *
1542 *	RETURNS:
1543 *	0 on success, AC_ERR_* mask on failure
1544 */
1545unsigned int atapi_eh_request_sense(struct ata_device *dev,
1546					   u8 *sense_buf, u8 dfl_sense_key)
1547{
1548	u8 cdb[ATAPI_CDB_LEN] =
1549		{ REQUEST_SENSE, 0, 0, 0, SCSI_SENSE_BUFFERSIZE, 0 };
1550	struct ata_port *ap = dev->link->ap;
1551	struct ata_taskfile tf;
1552
1553	memset(sense_buf, 0, SCSI_SENSE_BUFFERSIZE);
1554
1555	/* initialize sense_buf with the error register,
1556	 * for the case where they are -not- overwritten
1557	 */
1558	sense_buf[0] = 0x70;
1559	sense_buf[2] = dfl_sense_key;
1560
1561	/* some devices time out if garbage left in tf */
1562	ata_tf_init(dev, &tf);
1563
1564	tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
1565	tf.command = ATA_CMD_PACKET;
1566
1567	/*
1568	 * Do not use DMA if the connected device only supports PIO, even if the
1569	 * port prefers PIO commands via DMA.
1570	 *
1571	 * Ideally, we should call atapi_check_dma() to check if it is safe for
1572	 * the LLD to use DMA for REQUEST_SENSE, but we don't have a qc.
1573	 * Since we can't check the command, perhaps we should only use pio?
1574	 */
1575	if ((ap->flags & ATA_FLAG_PIO_DMA) && !(dev->flags & ATA_DFLAG_PIO)) {
1576		tf.protocol = ATAPI_PROT_DMA;
1577		tf.feature |= ATAPI_PKT_DMA;
1578	} else {
1579		tf.protocol = ATAPI_PROT_PIO;
1580		tf.lbam = SCSI_SENSE_BUFFERSIZE;
1581		tf.lbah = 0;
1582	}
1583
1584	return ata_exec_internal(dev, &tf, cdb, DMA_FROM_DEVICE,
1585				 sense_buf, SCSI_SENSE_BUFFERSIZE, 0);
1586}
1587
1588/**
1589 *	ata_eh_analyze_serror - analyze SError for a failed port
1590 *	@link: ATA link to analyze SError for
1591 *
1592 *	Analyze SError if available and further determine cause of
1593 *	failure.
1594 *
1595 *	LOCKING:
1596 *	None.
1597 */
1598static void ata_eh_analyze_serror(struct ata_link *link)
1599{
1600	struct ata_eh_context *ehc = &link->eh_context;
1601	u32 serror = ehc->i.serror;
1602	unsigned int err_mask = 0, action = 0;
1603	u32 hotplug_mask;
1604
1605	if (serror & (SERR_PERSISTENT | SERR_DATA)) {
1606		err_mask |= AC_ERR_ATA_BUS;
1607		action |= ATA_EH_RESET;
1608	}
1609	if (serror & SERR_PROTOCOL) {
1610		err_mask |= AC_ERR_HSM;
1611		action |= ATA_EH_RESET;
1612	}
1613	if (serror & SERR_INTERNAL) {
1614		err_mask |= AC_ERR_SYSTEM;
1615		action |= ATA_EH_RESET;
1616	}
1617
1618	/* Determine whether a hotplug event has occurred.  Both
1619	 * SError.N/X are considered hotplug events for enabled or
1620	 * host links.  For disabled PMP links, only N bit is
1621	 * considered as X bit is left at 1 for link plugging.
1622	 */
1623	if (link->lpm_policy > ATA_LPM_MAX_POWER)
1624		hotplug_mask = 0;	/* hotplug doesn't work w/ LPM */
1625	else if (!(link->flags & ATA_LFLAG_DISABLED) || ata_is_host_link(link))
1626		hotplug_mask = SERR_PHYRDY_CHG | SERR_DEV_XCHG;
1627	else
1628		hotplug_mask = SERR_PHYRDY_CHG;
1629
1630	if (serror & hotplug_mask)
1631		ata_ehi_hotplugged(&ehc->i);
1632
1633	ehc->i.err_mask |= err_mask;
1634	ehc->i.action |= action;
1635}
1636
1637/**
1638 *	ata_eh_analyze_tf - analyze taskfile of a failed qc
1639 *	@qc: qc to analyze
1640 *
1641 *	Analyze taskfile of @qc and further determine cause of
1642 *	failure.  This function also requests ATAPI sense data if
1643 *	available.
1644 *
1645 *	LOCKING:
1646 *	Kernel thread context (may sleep).
1647 *
1648 *	RETURNS:
1649 *	Determined recovery action
1650 */
1651static unsigned int ata_eh_analyze_tf(struct ata_queued_cmd *qc)
1652{
1653	const struct ata_taskfile *tf = &qc->result_tf;
1654	unsigned int tmp, action = 0;
1655	u8 stat = tf->status, err = tf->error;
1656
1657	if ((stat & (ATA_BUSY | ATA_DRQ | ATA_DRDY)) != ATA_DRDY) {
1658		qc->err_mask |= AC_ERR_HSM;
1659		return ATA_EH_RESET;
1660	}
1661
1662	if (stat & (ATA_ERR | ATA_DF)) {
1663		qc->err_mask |= AC_ERR_DEV;
1664		/*
1665		 * Sense data reporting does not work if the
1666		 * device fault bit is set.
1667		 */
1668		if (stat & ATA_DF)
1669			stat &= ~ATA_SENSE;
1670	} else {
1671		return 0;
1672	}
1673
1674	switch (qc->dev->class) {
1675	case ATA_DEV_ATA:
1676	case ATA_DEV_ZAC:
1677		/*
1678		 * Fetch the sense data explicitly if:
1679		 * -It was a non-NCQ command that failed, or
1680		 * -It was a NCQ command that failed, but the sense data
1681		 *  was not included in the NCQ command error log
1682		 *  (i.e. NCQ autosense is not supported by the device).
1683		 */
1684		if (!(qc->flags & ATA_QCFLAG_SENSE_VALID) &&
1685		    (stat & ATA_SENSE) && ata_eh_request_sense(qc))
1686			set_status_byte(qc->scsicmd, SAM_STAT_CHECK_CONDITION);
1687		if (err & ATA_ICRC)
1688			qc->err_mask |= AC_ERR_ATA_BUS;
1689		if (err & (ATA_UNC | ATA_AMNF))
1690			qc->err_mask |= AC_ERR_MEDIA;
1691		if (err & ATA_IDNF)
1692			qc->err_mask |= AC_ERR_INVALID;
1693		break;
1694
1695	case ATA_DEV_ATAPI:
1696		if (!ata_port_is_frozen(qc->ap)) {
1697			tmp = atapi_eh_request_sense(qc->dev,
1698						qc->scsicmd->sense_buffer,
1699						qc->result_tf.error >> 4);
1700			if (!tmp)
1701				qc->flags |= ATA_QCFLAG_SENSE_VALID;
1702			else
1703				qc->err_mask |= tmp;
1704		}
1705	}
1706
1707	if (qc->flags & ATA_QCFLAG_SENSE_VALID) {
1708		enum scsi_disposition ret = ata_eh_decide_disposition(qc);
1709
1710		/*
1711		 * SUCCESS here means that the sense code could be
1712		 * evaluated and should be passed to the upper layers
1713		 * for correct evaluation.
1714		 * FAILED means the sense code could not be interpreted
1715		 * and the device would need to be reset.
1716		 * NEEDS_RETRY and ADD_TO_MLQUEUE means that the
1717		 * command would need to be retried.
1718		 */
1719		if (ret == NEEDS_RETRY || ret == ADD_TO_MLQUEUE) {
1720			qc->flags |= ATA_QCFLAG_RETRY;
1721			qc->err_mask |= AC_ERR_OTHER;
1722		} else if (ret != SUCCESS) {
1723			qc->err_mask |= AC_ERR_HSM;
1724		}
1725	}
1726	if (qc->err_mask & (AC_ERR_HSM | AC_ERR_TIMEOUT | AC_ERR_ATA_BUS))
1727		action |= ATA_EH_RESET;
1728
1729	return action;
1730}
1731
1732static int ata_eh_categorize_error(unsigned int eflags, unsigned int err_mask,
1733				   int *xfer_ok)
1734{
1735	int base = 0;
1736
1737	if (!(eflags & ATA_EFLAG_DUBIOUS_XFER))
1738		*xfer_ok = 1;
1739
1740	if (!*xfer_ok)
1741		base = ATA_ECAT_DUBIOUS_NONE;
1742
1743	if (err_mask & AC_ERR_ATA_BUS)
1744		return base + ATA_ECAT_ATA_BUS;
1745
1746	if (err_mask & AC_ERR_TIMEOUT)
1747		return base + ATA_ECAT_TOUT_HSM;
1748
1749	if (eflags & ATA_EFLAG_IS_IO) {
1750		if (err_mask & AC_ERR_HSM)
1751			return base + ATA_ECAT_TOUT_HSM;
1752		if ((err_mask &
1753		     (AC_ERR_DEV|AC_ERR_MEDIA|AC_ERR_INVALID)) == AC_ERR_DEV)
1754			return base + ATA_ECAT_UNK_DEV;
1755	}
1756
1757	return 0;
1758}
1759
1760struct speed_down_verdict_arg {
1761	u64 since;
1762	int xfer_ok;
1763	int nr_errors[ATA_ECAT_NR];
1764};
1765
1766static int speed_down_verdict_cb(struct ata_ering_entry *ent, void *void_arg)
1767{
1768	struct speed_down_verdict_arg *arg = void_arg;
1769	int cat;
1770
1771	if ((ent->eflags & ATA_EFLAG_OLD_ER) || (ent->timestamp < arg->since))
1772		return -1;
1773
1774	cat = ata_eh_categorize_error(ent->eflags, ent->err_mask,
1775				      &arg->xfer_ok);
1776	arg->nr_errors[cat]++;
1777
1778	return 0;
1779}
1780
1781/**
1782 *	ata_eh_speed_down_verdict - Determine speed down verdict
1783 *	@dev: Device of interest
1784 *
1785 *	This function examines error ring of @dev and determines
1786 *	whether NCQ needs to be turned off, transfer speed should be
1787 *	stepped down, or falling back to PIO is necessary.
1788 *
1789 *	ECAT_ATA_BUS	: ATA_BUS error for any command
1790 *
1791 *	ECAT_TOUT_HSM	: TIMEOUT for any command or HSM violation for
1792 *			  IO commands
1793 *
1794 *	ECAT_UNK_DEV	: Unknown DEV error for IO commands
1795 *
1796 *	ECAT_DUBIOUS_*	: Identical to above three but occurred while
1797 *			  data transfer hasn't been verified.
1798 *
1799 *	Verdicts are
1800 *
1801 *	NCQ_OFF		: Turn off NCQ.
1802 *
1803 *	SPEED_DOWN	: Speed down transfer speed but don't fall back
1804 *			  to PIO.
1805 *
1806 *	FALLBACK_TO_PIO	: Fall back to PIO.
1807 *
1808 *	Even if multiple verdicts are returned, only one action is
1809 *	taken per error.  An action triggered by non-DUBIOUS errors
1810 *	clears ering, while one triggered by DUBIOUS_* errors doesn't.
1811 *	This is to expedite speed down decisions right after device is
1812 *	initially configured.
1813 *
1814 *	The following are speed down rules.  #1 and #2 deal with
1815 *	DUBIOUS errors.
1816 *
1817 *	1. If more than one DUBIOUS_ATA_BUS or DUBIOUS_TOUT_HSM errors
1818 *	   occurred during last 5 mins, SPEED_DOWN and FALLBACK_TO_PIO.
1819 *
1820 *	2. If more than one DUBIOUS_TOUT_HSM or DUBIOUS_UNK_DEV errors
1821 *	   occurred during last 5 mins, NCQ_OFF.
1822 *
1823 *	3. If more than 8 ATA_BUS, TOUT_HSM or UNK_DEV errors
1824 *	   occurred during last 5 mins, FALLBACK_TO_PIO
1825 *
1826 *	4. If more than 3 TOUT_HSM or UNK_DEV errors occurred
1827 *	   during last 10 mins, NCQ_OFF.
1828 *
1829 *	5. If more than 3 ATA_BUS or TOUT_HSM errors, or more than 6
1830 *	   UNK_DEV errors occurred during last 10 mins, SPEED_DOWN.
1831 *
1832 *	LOCKING:
1833 *	Inherited from caller.
1834 *
1835 *	RETURNS:
1836 *	OR of ATA_EH_SPDN_* flags.
1837 */
1838static unsigned int ata_eh_speed_down_verdict(struct ata_device *dev)
1839{
1840	const u64 j5mins = 5LLU * 60 * HZ, j10mins = 10LLU * 60 * HZ;
1841	u64 j64 = get_jiffies_64();
1842	struct speed_down_verdict_arg arg;
1843	unsigned int verdict = 0;
1844
1845	/* scan past 5 mins of error history */
1846	memset(&arg, 0, sizeof(arg));
1847	arg.since = j64 - min(j64, j5mins);
1848	ata_ering_map(&dev->ering, speed_down_verdict_cb, &arg);
1849
1850	if (arg.nr_errors[ATA_ECAT_DUBIOUS_ATA_BUS] +
1851	    arg.nr_errors[ATA_ECAT_DUBIOUS_TOUT_HSM] > 1)
1852		verdict |= ATA_EH_SPDN_SPEED_DOWN |
1853			ATA_EH_SPDN_FALLBACK_TO_PIO | ATA_EH_SPDN_KEEP_ERRORS;
1854
1855	if (arg.nr_errors[ATA_ECAT_DUBIOUS_TOUT_HSM] +
1856	    arg.nr_errors[ATA_ECAT_DUBIOUS_UNK_DEV] > 1)
1857		verdict |= ATA_EH_SPDN_NCQ_OFF | ATA_EH_SPDN_KEEP_ERRORS;
1858
1859	if (arg.nr_errors[ATA_ECAT_ATA_BUS] +
1860	    arg.nr_errors[ATA_ECAT_TOUT_HSM] +
1861	    arg.nr_errors[ATA_ECAT_UNK_DEV] > 6)
1862		verdict |= ATA_EH_SPDN_FALLBACK_TO_PIO;
1863
1864	/* scan past 10 mins of error history */
1865	memset(&arg, 0, sizeof(arg));
1866	arg.since = j64 - min(j64, j10mins);
1867	ata_ering_map(&dev->ering, speed_down_verdict_cb, &arg);
1868
1869	if (arg.nr_errors[ATA_ECAT_TOUT_HSM] +
1870	    arg.nr_errors[ATA_ECAT_UNK_DEV] > 3)
1871		verdict |= ATA_EH_SPDN_NCQ_OFF;
1872
1873	if (arg.nr_errors[ATA_ECAT_ATA_BUS] +
1874	    arg.nr_errors[ATA_ECAT_TOUT_HSM] > 3 ||
1875	    arg.nr_errors[ATA_ECAT_UNK_DEV] > 6)
1876		verdict |= ATA_EH_SPDN_SPEED_DOWN;
1877
1878	return verdict;
1879}
1880
1881/**
1882 *	ata_eh_speed_down - record error and speed down if necessary
1883 *	@dev: Failed device
1884 *	@eflags: mask of ATA_EFLAG_* flags
1885 *	@err_mask: err_mask of the error
1886 *
1887 *	Record error and examine error history to determine whether
1888 *	adjusting transmission speed is necessary.  It also sets
1889 *	transmission limits appropriately if such adjustment is
1890 *	necessary.
1891 *
1892 *	LOCKING:
1893 *	Kernel thread context (may sleep).
1894 *
1895 *	RETURNS:
1896 *	Determined recovery action.
1897 */
1898static unsigned int ata_eh_speed_down(struct ata_device *dev,
1899				unsigned int eflags, unsigned int err_mask)
1900{
1901	struct ata_link *link = ata_dev_phys_link(dev);
1902	int xfer_ok = 0;
1903	unsigned int verdict;
1904	unsigned int action = 0;
1905
1906	/* don't bother if Cat-0 error */
1907	if (ata_eh_categorize_error(eflags, err_mask, &xfer_ok) == 0)
1908		return 0;
1909
1910	/* record error and determine whether speed down is necessary */
1911	ata_ering_record(&dev->ering, eflags, err_mask);
1912	verdict = ata_eh_speed_down_verdict(dev);
1913
1914	/* turn off NCQ? */
1915	if ((verdict & ATA_EH_SPDN_NCQ_OFF) && ata_ncq_enabled(dev)) {
1916		dev->flags |= ATA_DFLAG_NCQ_OFF;
1917		ata_dev_warn(dev, "NCQ disabled due to excessive errors\n");
1918		goto done;
1919	}
1920
1921	/* speed down? */
1922	if (verdict & ATA_EH_SPDN_SPEED_DOWN) {
1923		/* speed down SATA link speed if possible */
1924		if (sata_down_spd_limit(link, 0) == 0) {
1925			action |= ATA_EH_RESET;
1926			goto done;
1927		}
1928
1929		/* lower transfer mode */
1930		if (dev->spdn_cnt < 2) {
1931			static const int dma_dnxfer_sel[] =
1932				{ ATA_DNXFER_DMA, ATA_DNXFER_40C };
1933			static const int pio_dnxfer_sel[] =
1934				{ ATA_DNXFER_PIO, ATA_DNXFER_FORCE_PIO0 };
1935			int sel;
1936
1937			if (dev->xfer_shift != ATA_SHIFT_PIO)
1938				sel = dma_dnxfer_sel[dev->spdn_cnt];
1939			else
1940				sel = pio_dnxfer_sel[dev->spdn_cnt];
1941
1942			dev->spdn_cnt++;
1943
1944			if (ata_down_xfermask_limit(dev, sel) == 0) {
1945				action |= ATA_EH_RESET;
1946				goto done;
1947			}
1948		}
1949	}
1950
1951	/* Fall back to PIO?  Slowing down to PIO is meaningless for
1952	 * SATA ATA devices.  Consider it only for PATA and SATAPI.
1953	 */
1954	if ((verdict & ATA_EH_SPDN_FALLBACK_TO_PIO) && (dev->spdn_cnt >= 2) &&
1955	    (link->ap->cbl != ATA_CBL_SATA || dev->class == ATA_DEV_ATAPI) &&
1956	    (dev->xfer_shift != ATA_SHIFT_PIO)) {
1957		if (ata_down_xfermask_limit(dev, ATA_DNXFER_FORCE_PIO) == 0) {
1958			dev->spdn_cnt = 0;
1959			action |= ATA_EH_RESET;
1960			goto done;
1961		}
1962	}
1963
1964	return 0;
1965 done:
1966	/* device has been slowed down, blow error history */
1967	if (!(verdict & ATA_EH_SPDN_KEEP_ERRORS))
1968		ata_ering_clear(&dev->ering);
1969	return action;
1970}
1971
1972/**
1973 *	ata_eh_worth_retry - analyze error and decide whether to retry
1974 *	@qc: qc to possibly retry
1975 *
1976 *	Look at the cause of the error and decide if a retry
1977 * 	might be useful or not.  We don't want to retry media errors
1978 *	because the drive itself has probably already taken 10-30 seconds
1979 *	doing its own internal retries before reporting the failure.
1980 */
1981static inline int ata_eh_worth_retry(struct ata_queued_cmd *qc)
1982{
1983	if (qc->err_mask & AC_ERR_MEDIA)
1984		return 0;	/* don't retry media errors */
1985	if (qc->flags & ATA_QCFLAG_IO)
1986		return 1;	/* otherwise retry anything from fs stack */
1987	if (qc->err_mask & AC_ERR_INVALID)
1988		return 0;	/* don't retry these */
1989	return qc->err_mask != AC_ERR_DEV;  /* retry if not dev error */
1990}
1991
1992/**
1993 *      ata_eh_quiet - check if we need to be quiet about a command error
1994 *      @qc: qc to check
1995 *
1996 *      Look at the qc flags anbd its scsi command request flags to determine
1997 *      if we need to be quiet about the command failure.
1998 */
1999static inline bool ata_eh_quiet(struct ata_queued_cmd *qc)
2000{
2001	if (qc->scsicmd && scsi_cmd_to_rq(qc->scsicmd)->rq_flags & RQF_QUIET)
2002		qc->flags |= ATA_QCFLAG_QUIET;
2003	return qc->flags & ATA_QCFLAG_QUIET;
2004}
2005
2006static int ata_eh_get_non_ncq_success_sense(struct ata_link *link)
2007{
2008	struct ata_port *ap = link->ap;
2009	struct ata_queued_cmd *qc;
2010
2011	qc = __ata_qc_from_tag(ap, link->active_tag);
2012	if (!qc)
2013		return -EIO;
2014
2015	if (!(qc->flags & ATA_QCFLAG_EH) ||
2016	    !(qc->flags & ATA_QCFLAG_EH_SUCCESS_CMD) ||
2017	    qc->err_mask)
2018		return -EIO;
2019
2020	if (!ata_eh_request_sense(qc))
2021		return -EIO;
2022
2023	/*
2024	 * No point in checking the return value, since the command has already
2025	 * completed successfully.
2026	 */
2027	ata_eh_decide_disposition(qc);
2028
2029	return 0;
2030}
2031
2032static void ata_eh_get_success_sense(struct ata_link *link)
2033{
2034	struct ata_eh_context *ehc = &link->eh_context;
2035	struct ata_device *dev = link->device;
2036	struct ata_port *ap = link->ap;
2037	struct ata_queued_cmd *qc;
2038	int tag, ret = 0;
2039
2040	if (!(ehc->i.dev_action[dev->devno] & ATA_EH_GET_SUCCESS_SENSE))
2041		return;
2042
2043	/* if frozen, we can't do much */
2044	if (ata_port_is_frozen(ap)) {
2045		ata_dev_warn(dev,
2046			"successful sense data available but port frozen\n");
2047		goto out;
2048	}
2049
2050	/*
2051	 * If the link has sactive set, then we have outstanding NCQ commands
2052	 * and have to read the Successful NCQ Commands log to get the sense
2053	 * data. Otherwise, we are dealing with a non-NCQ command and use
2054	 * request sense ext command to retrieve the sense data.
2055	 */
2056	if (link->sactive)
2057		ret = ata_eh_get_ncq_success_sense(link);
2058	else
2059		ret = ata_eh_get_non_ncq_success_sense(link);
2060	if (ret)
2061		goto out;
2062
2063	ata_eh_done(link, dev, ATA_EH_GET_SUCCESS_SENSE);
2064	return;
2065
2066out:
2067	/*
2068	 * If we failed to get sense data for a successful command that ought to
2069	 * have sense data, we cannot simply return BLK_STS_OK to user space.
2070	 * This is because we can't know if the sense data that we couldn't get
2071	 * was actually "DATA CURRENTLY UNAVAILABLE". Reporting such a command
2072	 * as success to user space would result in a silent data corruption.
2073	 * Thus, add a bogus ABORTED_COMMAND sense data to such commands, such
2074	 * that SCSI will report these commands as BLK_STS_IOERR to user space.
2075	 */
2076	ata_qc_for_each_raw(ap, qc, tag) {
2077		if (!(qc->flags & ATA_QCFLAG_EH) ||
2078		    !(qc->flags & ATA_QCFLAG_EH_SUCCESS_CMD) ||
2079		    qc->err_mask ||
2080		    ata_dev_phys_link(qc->dev) != link)
2081			continue;
2082
2083		/* We managed to get sense for this success command, skip. */
2084		if (qc->flags & ATA_QCFLAG_SENSE_VALID)
2085			continue;
2086
2087		/* This success command did not have any sense data, skip. */
2088		if (!(qc->result_tf.status & ATA_SENSE))
2089			continue;
2090
2091		/* This success command had sense data, but we failed to get. */
2092		ata_scsi_set_sense(dev, qc->scsicmd, ABORTED_COMMAND, 0, 0);
2093		qc->flags |= ATA_QCFLAG_SENSE_VALID;
2094	}
2095	ata_eh_done(link, dev, ATA_EH_GET_SUCCESS_SENSE);
2096}
2097
2098/*
2099 * Check if a link is established. This is a relaxed version of
2100 * ata_phys_link_online() which accounts for the fact that this is potentially
2101 * called after changing the link power management policy, which may not be
2102 * reflected immediately in the SStatus register (e.g., we may still be seeing
2103 * the PHY in partial, slumber or devsleep Partial power management state.
2104 * So check that:
2105 * - A device is still present, that is, DET is 1h (Device presence detected
2106 *   but Phy communication not established) or 3h (Device presence detected and
2107 *   Phy communication established)
2108 * - Communication is established, that is, IPM is not 0h, indicating that PHY
2109 *   is online or in a low power state.
2110 */
2111static bool ata_eh_link_established(struct ata_link *link)
2112{
2113	u32 sstatus;
2114	u8 det, ipm;
2115
2116	/*
2117	 * For old IDE/PATA adapters that do not have a valid scr_read method,
2118	 * or if reading the SStatus register fails, assume that the device is
2119	 * present. Device probe will determine if that is really the case.
2120	 */
2121	if (sata_scr_read(link, SCR_STATUS, &sstatus))
2122		return true;
2123
2124	det = sstatus & 0x0f;
2125	ipm = (sstatus >> 8) & 0x0f;
2126
2127	return (det & 0x01) && ipm;
2128}
2129
2130/**
2131 *	ata_eh_link_set_lpm - configure SATA interface power management
2132 *	@link: link to configure
2133 *	@policy: the link power management policy
2134 *	@r_failed_dev: out parameter for failed device
2135 *
2136 *	Enable SATA Interface power management.  This will enable
2137 *	Device Interface Power Management (DIPM) for min_power and
2138 *	medium_power_with_dipm policies, and then call driver specific
2139 *	callbacks for enabling Host Initiated Power management.
2140 *
2141 *	LOCKING:
2142 *	EH context.
2143 *
2144 *	RETURNS:
2145 *	0 on success, -errno on failure.
2146 */
2147static int ata_eh_link_set_lpm(struct ata_link *link,
2148			       enum ata_lpm_policy policy,
2149			       struct ata_device **r_failed_dev)
2150{
2151	struct ata_port *ap = ata_is_host_link(link) ? link->ap : NULL;
2152	struct ata_eh_context *ehc = &link->eh_context;
2153	struct ata_device *dev, *link_dev = NULL, *lpm_dev = NULL;
2154	enum ata_lpm_policy old_policy = link->lpm_policy;
2155	bool host_has_dipm = !(link->ap->flags & ATA_FLAG_NO_DIPM);
2156	unsigned int hints = ATA_LPM_EMPTY | ATA_LPM_HIPM;
2157	unsigned int err_mask;
2158	int rc;
2159
2160	/* if the link or host doesn't do LPM, noop */
2161	if (!IS_ENABLED(CONFIG_SATA_HOST) ||
2162	    (link->flags & ATA_LFLAG_NO_LPM) || (ap && !ap->ops->set_lpm))
2163		return 0;
2164
2165	/*
2166	 * This function currently assumes that it will never be supplied policy
2167	 * ATA_LPM_UNKNOWN.
2168	 */
2169	if (WARN_ON_ONCE(policy == ATA_LPM_UNKNOWN))
2170		return 0;
2171
2172	ata_link_dbg(link, "Set LPM policy: %d -> %d\n", old_policy, policy);
2173
2174	/*
2175	 * DIPM is enabled only for ATA_LPM_MIN_POWER,
2176	 * ATA_LPM_MIN_POWER_WITH_PARTIAL, and ATA_LPM_MED_POWER_WITH_DIPM, as
2177	 * some devices misbehave when the host NACKs transition to SLUMBER.
2178	 */
2179	ata_for_each_dev(dev, link, ENABLED) {
2180		bool dev_has_hipm = ata_id_has_hipm(dev->id);
2181		bool dev_has_dipm = ata_id_has_dipm(dev->id);
2182
2183		/* find the first enabled and LPM enabled devices */
2184		if (!link_dev)
2185			link_dev = dev;
2186
2187		if (!lpm_dev &&
2188		    (dev_has_hipm || (dev_has_dipm && host_has_dipm)))
2189			lpm_dev = dev;
2190
2191		hints &= ~ATA_LPM_EMPTY;
2192		if (!dev_has_hipm)
2193			hints &= ~ATA_LPM_HIPM;
2194
2195		/* disable DIPM before changing link config */
2196		if (dev_has_dipm) {
2197			err_mask = ata_dev_set_feature(dev,
2198					SETFEATURES_SATA_DISABLE, SATA_DIPM);
2199			if (err_mask && err_mask != AC_ERR_DEV) {
2200				ata_dev_warn(dev,
2201					     "failed to disable DIPM, Emask 0x%x\n",
2202					     err_mask);
2203				rc = -EIO;
2204				goto fail;
2205			}
2206		}
2207	}
2208
2209	if (ap) {
2210		rc = ap->ops->set_lpm(link, policy, hints);
2211		if (!rc && ap->slave_link)
2212			rc = ap->ops->set_lpm(ap->slave_link, policy, hints);
2213	} else
2214		rc = sata_pmp_set_lpm(link, policy, hints);
2215
2216	/*
2217	 * Attribute link config failure to the first (LPM) enabled
2218	 * device on the link.
2219	 */
2220	if (rc) {
2221		if (rc == -EOPNOTSUPP) {
2222			link->flags |= ATA_LFLAG_NO_LPM;
2223			return 0;
2224		}
2225		dev = lpm_dev ? lpm_dev : link_dev;
2226		goto fail;
2227	}
2228
2229	/*
2230	 * Low level driver acked the transition.  Issue DIPM command
2231	 * with the new policy set.
2232	 */
2233	link->lpm_policy = policy;
2234	if (ap && ap->slave_link)
2235		ap->slave_link->lpm_policy = policy;
2236
2237	/*
2238	 * Host config updated, enable DIPM if transitioning to
2239	 * ATA_LPM_MIN_POWER, ATA_LPM_MIN_POWER_WITH_PARTIAL, or
2240	 * ATA_LPM_MED_POWER_WITH_DIPM.
2241	 */
2242	ata_for_each_dev(dev, link, ENABLED) {
2243		bool dev_has_dipm = ata_id_has_dipm(dev->id);
2244
2245		if (policy >= ATA_LPM_MED_POWER_WITH_DIPM && host_has_dipm &&
2246		    dev_has_dipm) {
2247			err_mask = ata_dev_set_feature(dev,
2248					SETFEATURES_SATA_ENABLE, SATA_DIPM);
2249			if (err_mask && err_mask != AC_ERR_DEV) {
2250				ata_dev_warn(dev,
2251					"failed to enable DIPM, Emask 0x%x\n",
2252					err_mask);
2253				rc = -EIO;
2254				goto fail;
2255			}
2256		}
2257	}
2258
2259	link->last_lpm_change = jiffies;
2260	link->flags |= ATA_LFLAG_CHANGED;
2261
2262	return 0;
2263
2264fail:
2265	/* restore the old policy */
2266	link->lpm_policy = old_policy;
2267	if (ap && ap->slave_link)
2268		ap->slave_link->lpm_policy = old_policy;
2269
2270	/* if no device or only one more chance is left, disable LPM */
2271	if (!dev || ehc->tries[dev->devno] <= 2) {
2272		ata_link_warn(link, "disabling LPM on the link\n");
2273		link->flags |= ATA_LFLAG_NO_LPM;
2274	}
2275	if (r_failed_dev)
2276		*r_failed_dev = dev;
2277	return rc;
2278}
2279
2280/**
2281 *	ata_eh_link_autopsy - analyze error and determine recovery action
2282 *	@link: host link to perform autopsy on
2283 *
2284 *	Analyze why @link failed and determine which recovery actions
2285 *	are needed.  This function also sets more detailed AC_ERR_*
2286 *	values and fills sense data for ATAPI CHECK SENSE.
2287 *
2288 *	LOCKING:
2289 *	Kernel thread context (may sleep).
2290 */
2291static void ata_eh_link_autopsy(struct ata_link *link)
2292{
2293	struct ata_port *ap = link->ap;
2294	struct ata_eh_context *ehc = &link->eh_context;
2295	struct ata_queued_cmd *qc;
2296	struct ata_device *dev;
2297	unsigned int all_err_mask = 0, eflags = 0;
2298	int tag, nr_failed = 0, nr_quiet = 0;
2299	u32 serror;
2300	int rc;
2301
2302	if (ehc->i.flags & ATA_EHI_NO_AUTOPSY)
2303		return;
2304
2305	/* obtain and analyze SError */
2306	rc = sata_scr_read(link, SCR_ERROR, &serror);
2307	if (rc == 0) {
2308		ehc->i.serror |= serror;
2309		ata_eh_analyze_serror(link);
2310	} else if (rc != -EOPNOTSUPP) {
2311		/* SError read failed, force reset and probing */
2312		ehc->i.probe_mask |= ATA_ALL_DEVICES;
2313		ehc->i.action |= ATA_EH_RESET;
2314		ehc->i.err_mask |= AC_ERR_OTHER;
2315	}
2316
2317	/* analyze NCQ failure */
2318	ata_eh_analyze_ncq_error(link);
2319
2320	/*
2321	 * Check if this was a successful command that simply needs sense data.
2322	 * Since the sense data is not part of the completion, we need to fetch
2323	 * it using an additional command. Since this can't be done from irq
2324	 * context, the sense data for successful commands are fetched by EH.
2325	 */
2326	ata_eh_get_success_sense(link);
2327
2328	/* any real error trumps AC_ERR_OTHER */
2329	if (ehc->i.err_mask & ~AC_ERR_OTHER)
2330		ehc->i.err_mask &= ~AC_ERR_OTHER;
2331
2332	all_err_mask |= ehc->i.err_mask;
2333
2334	ata_qc_for_each_raw(ap, qc, tag) {
2335		if (!(qc->flags & ATA_QCFLAG_EH) ||
2336		    qc->flags & ATA_QCFLAG_RETRY ||
2337		    qc->flags & ATA_QCFLAG_EH_SUCCESS_CMD ||
2338		    ata_dev_phys_link(qc->dev) != link)
2339			continue;
2340
2341		/* inherit upper level err_mask */
2342		qc->err_mask |= ehc->i.err_mask;
2343
2344		/* analyze TF */
2345		ehc->i.action |= ata_eh_analyze_tf(qc);
2346
2347		/* DEV errors are probably spurious in case of ATA_BUS error */
2348		if (qc->err_mask & AC_ERR_ATA_BUS)
2349			qc->err_mask &= ~(AC_ERR_DEV | AC_ERR_MEDIA |
2350					  AC_ERR_INVALID);
2351
2352		/* any real error trumps unknown error */
2353		if (qc->err_mask & ~AC_ERR_OTHER)
2354			qc->err_mask &= ~AC_ERR_OTHER;
2355
2356		/*
2357		 * SENSE_VALID trumps dev/unknown error and revalidation. Upper
2358		 * layers will determine whether the command is worth retrying
2359		 * based on the sense data and device class/type. Otherwise,
2360		 * determine directly if the command is worth retrying using its
2361		 * error mask and flags.
2362		 */
2363		if (qc->flags & ATA_QCFLAG_SENSE_VALID)
2364			qc->err_mask &= ~(AC_ERR_DEV | AC_ERR_OTHER);
2365		else if (ata_eh_worth_retry(qc))
2366			qc->flags |= ATA_QCFLAG_RETRY;
2367
2368		/* accumulate error info */
2369		ehc->i.dev = qc->dev;
2370		all_err_mask |= qc->err_mask;
2371		if (qc->flags & ATA_QCFLAG_IO)
2372			eflags |= ATA_EFLAG_IS_IO;
2373		trace_ata_eh_link_autopsy_qc(qc);
2374
2375		/* Count quiet errors */
2376		if (ata_eh_quiet(qc))
2377			nr_quiet++;
2378		nr_failed++;
2379	}
2380
2381	/* If all failed commands requested silence, then be quiet */
2382	if (nr_quiet == nr_failed)
2383		ehc->i.flags |= ATA_EHI_QUIET;
2384
2385	/* enforce default EH actions */
2386	if (ata_port_is_frozen(ap) ||
2387	    all_err_mask & (AC_ERR_HSM | AC_ERR_TIMEOUT))
2388		ehc->i.action |= ATA_EH_RESET;
2389	else if (((eflags & ATA_EFLAG_IS_IO) && all_err_mask) ||
2390		 (!(eflags & ATA_EFLAG_IS_IO) && (all_err_mask & ~AC_ERR_DEV)))
2391		ehc->i.action |= ATA_EH_REVALIDATE;
2392
2393	/* If we have offending qcs and the associated failed device,
2394	 * perform per-dev EH action only on the offending device.
2395	 */
2396	if (ehc->i.dev) {
2397		ehc->i.dev_action[ehc->i.dev->devno] |=
2398			ehc->i.action & ATA_EH_PERDEV_MASK;
2399		ehc->i.action &= ~ATA_EH_PERDEV_MASK;
2400	}
2401
2402	/* propagate timeout to host link */
2403	if ((all_err_mask & AC_ERR_TIMEOUT) && !ata_is_host_link(link))
2404		ap->link.eh_context.i.err_mask |= AC_ERR_TIMEOUT;
2405
2406	/* record error and consider speeding down */
2407	dev = ehc->i.dev;
2408	if (!dev && ((ata_link_max_devices(link) == 1 &&
2409		      ata_dev_enabled(link->device))))
2410	    dev = link->device;
2411
2412	if (dev) {
2413		if (dev->flags & ATA_DFLAG_DUBIOUS_XFER)
2414			eflags |= ATA_EFLAG_DUBIOUS_XFER;
2415		ehc->i.action |= ata_eh_speed_down(dev, eflags, all_err_mask);
2416		trace_ata_eh_link_autopsy(dev, ehc->i.action, all_err_mask);
2417	}
2418}
2419
2420/**
2421 *	ata_eh_autopsy - analyze error and determine recovery action
2422 *	@ap: host port to perform autopsy on
2423 *
2424 *	Analyze all links of @ap and determine why they failed and
2425 *	which recovery actions are needed.
2426 *
2427 *	LOCKING:
2428 *	Kernel thread context (may sleep).
2429 */
2430void ata_eh_autopsy(struct ata_port *ap)
2431{
2432	struct ata_link *link;
2433
2434	ata_for_each_link(link, ap, EDGE)
2435		ata_eh_link_autopsy(link);
2436
2437	/* Handle the frigging slave link.  Autopsy is done similarly
2438	 * but actions and flags are transferred over to the master
2439	 * link and handled from there.
2440	 */
2441	if (ap->slave_link) {
2442		struct ata_eh_context *mehc = &ap->link.eh_context;
2443		struct ata_eh_context *sehc = &ap->slave_link->eh_context;
2444
2445		/* transfer control flags from master to slave */
2446		sehc->i.flags |= mehc->i.flags & ATA_EHI_TO_SLAVE_MASK;
2447
2448		/* perform autopsy on the slave link */
2449		ata_eh_link_autopsy(ap->slave_link);
2450
2451		/* transfer actions from slave to master and clear slave */
2452		ata_eh_about_to_do(ap->slave_link, NULL, ATA_EH_ALL_ACTIONS);
2453		mehc->i.action		|= sehc->i.action;
2454		mehc->i.dev_action[1]	|= sehc->i.dev_action[1];
2455		mehc->i.flags		|= sehc->i.flags;
2456		ata_eh_done(ap->slave_link, NULL, ATA_EH_ALL_ACTIONS);
2457	}
2458
2459	/* Autopsy of fanout ports can affect host link autopsy.
2460	 * Perform host link autopsy last.
2461	 */
2462	if (sata_pmp_attached(ap))
2463		ata_eh_link_autopsy(&ap->link);
2464}
2465
2466/**
2467 *	ata_get_cmd_name - get name for ATA command
2468 *	@command: ATA command code to get name for
2469 *
2470 *	Return a textual name of the given command or "unknown"
2471 *
2472 *	LOCKING:
2473 *	None
2474 */
2475const char *ata_get_cmd_name(u8 command)
2476{
2477#ifdef CONFIG_ATA_VERBOSE_ERROR
2478	static const struct
2479	{
2480		u8 command;
2481		const char *text;
2482	} cmd_descr[] = {
2483		{ ATA_CMD_DEV_RESET,		"DEVICE RESET" },
2484		{ ATA_CMD_CHK_POWER,		"CHECK POWER MODE" },
2485		{ ATA_CMD_STANDBY,		"STANDBY" },
2486		{ ATA_CMD_IDLE,			"IDLE" },
2487		{ ATA_CMD_EDD,			"EXECUTE DEVICE DIAGNOSTIC" },
2488		{ ATA_CMD_DOWNLOAD_MICRO,	"DOWNLOAD MICROCODE" },
2489		{ ATA_CMD_DOWNLOAD_MICRO_DMA,	"DOWNLOAD MICROCODE DMA" },
2490		{ ATA_CMD_NOP,			"NOP" },
2491		{ ATA_CMD_FLUSH,		"FLUSH CACHE" },
2492		{ ATA_CMD_FLUSH_EXT,		"FLUSH CACHE EXT" },
2493		{ ATA_CMD_ID_ATA,		"IDENTIFY DEVICE" },
2494		{ ATA_CMD_ID_ATAPI,		"IDENTIFY PACKET DEVICE" },
2495		{ ATA_CMD_SERVICE,		"SERVICE" },
2496		{ ATA_CMD_READ,			"READ DMA" },
2497		{ ATA_CMD_READ_EXT,		"READ DMA EXT" },
2498		{ ATA_CMD_READ_QUEUED,		"READ DMA QUEUED" },
2499		{ ATA_CMD_READ_STREAM_EXT,	"READ STREAM EXT" },
2500		{ ATA_CMD_READ_STREAM_DMA_EXT,  "READ STREAM DMA EXT" },
2501		{ ATA_CMD_WRITE,		"WRITE DMA" },
2502		{ ATA_CMD_WRITE_EXT,		"WRITE DMA EXT" },
2503		{ ATA_CMD_WRITE_QUEUED,		"WRITE DMA QUEUED EXT" },
2504		{ ATA_CMD_WRITE_STREAM_EXT,	"WRITE STREAM EXT" },
2505		{ ATA_CMD_WRITE_STREAM_DMA_EXT, "WRITE STREAM DMA EXT" },
2506		{ ATA_CMD_WRITE_FUA_EXT,	"WRITE DMA FUA EXT" },
2507		{ ATA_CMD_WRITE_QUEUED_FUA_EXT, "WRITE DMA QUEUED FUA EXT" },
2508		{ ATA_CMD_FPDMA_READ,		"READ FPDMA QUEUED" },
2509		{ ATA_CMD_FPDMA_WRITE,		"WRITE FPDMA QUEUED" },
2510		{ ATA_CMD_NCQ_NON_DATA,		"NCQ NON-DATA" },
2511		{ ATA_CMD_FPDMA_SEND,		"SEND FPDMA QUEUED" },
2512		{ ATA_CMD_FPDMA_RECV,		"RECEIVE FPDMA QUEUED" },
2513		{ ATA_CMD_PIO_READ,		"READ SECTOR(S)" },
2514		{ ATA_CMD_PIO_READ_EXT,		"READ SECTOR(S) EXT" },
2515		{ ATA_CMD_PIO_WRITE,		"WRITE SECTOR(S)" },
2516		{ ATA_CMD_PIO_WRITE_EXT,	"WRITE SECTOR(S) EXT" },
2517		{ ATA_CMD_READ_MULTI,		"READ MULTIPLE" },
2518		{ ATA_CMD_READ_MULTI_EXT,	"READ MULTIPLE EXT" },
2519		{ ATA_CMD_WRITE_MULTI,		"WRITE MULTIPLE" },
2520		{ ATA_CMD_WRITE_MULTI_EXT,	"WRITE MULTIPLE EXT" },
2521		{ ATA_CMD_WRITE_MULTI_FUA_EXT,	"WRITE MULTIPLE FUA EXT" },
2522		{ ATA_CMD_SET_FEATURES,		"SET FEATURES" },
2523		{ ATA_CMD_SET_MULTI,		"SET MULTIPLE MODE" },
2524		{ ATA_CMD_VERIFY,		"READ VERIFY SECTOR(S)" },
2525		{ ATA_CMD_VERIFY_EXT,		"READ VERIFY SECTOR(S) EXT" },
2526		{ ATA_CMD_WRITE_UNCORR_EXT,	"WRITE UNCORRECTABLE EXT" },
2527		{ ATA_CMD_STANDBYNOW1,		"STANDBY IMMEDIATE" },
2528		{ ATA_CMD_IDLEIMMEDIATE,	"IDLE IMMEDIATE" },
2529		{ ATA_CMD_SLEEP,		"SLEEP" },
2530		{ ATA_CMD_INIT_DEV_PARAMS,	"INITIALIZE DEVICE PARAMETERS" },
2531		{ ATA_CMD_READ_NATIVE_MAX,	"READ NATIVE MAX ADDRESS" },
2532		{ ATA_CMD_READ_NATIVE_MAX_EXT,	"READ NATIVE MAX ADDRESS EXT" },
2533		{ ATA_CMD_SET_MAX,		"SET MAX ADDRESS" },
2534		{ ATA_CMD_SET_MAX_EXT,		"SET MAX ADDRESS EXT" },
2535		{ ATA_CMD_READ_LOG_EXT,		"READ LOG EXT" },
2536		{ ATA_CMD_WRITE_LOG_EXT,	"WRITE LOG EXT" },
2537		{ ATA_CMD_READ_LOG_DMA_EXT,	"READ LOG DMA EXT" },
2538		{ ATA_CMD_WRITE_LOG_DMA_EXT,	"WRITE LOG DMA EXT" },
2539		{ ATA_CMD_TRUSTED_NONDATA,	"TRUSTED NON-DATA" },
2540		{ ATA_CMD_TRUSTED_RCV,		"TRUSTED RECEIVE" },
2541		{ ATA_CMD_TRUSTED_RCV_DMA,	"TRUSTED RECEIVE DMA" },
2542		{ ATA_CMD_TRUSTED_SND,		"TRUSTED SEND" },
2543		{ ATA_CMD_TRUSTED_SND_DMA,	"TRUSTED SEND DMA" },
2544		{ ATA_CMD_PMP_READ,		"READ BUFFER" },
2545		{ ATA_CMD_PMP_READ_DMA,		"READ BUFFER DMA" },
2546		{ ATA_CMD_PMP_WRITE,		"WRITE BUFFER" },
2547		{ ATA_CMD_PMP_WRITE_DMA,	"WRITE BUFFER DMA" },
2548		{ ATA_CMD_CONF_OVERLAY,		"DEVICE CONFIGURATION OVERLAY" },
2549		{ ATA_CMD_SEC_SET_PASS,		"SECURITY SET PASSWORD" },
2550		{ ATA_CMD_SEC_UNLOCK,		"SECURITY UNLOCK" },
2551		{ ATA_CMD_SEC_ERASE_PREP,	"SECURITY ERASE PREPARE" },
2552		{ ATA_CMD_SEC_ERASE_UNIT,	"SECURITY ERASE UNIT" },
2553		{ ATA_CMD_SEC_FREEZE_LOCK,	"SECURITY FREEZE LOCK" },
2554		{ ATA_CMD_SEC_DISABLE_PASS,	"SECURITY DISABLE PASSWORD" },
2555		{ ATA_CMD_CONFIG_STREAM,	"CONFIGURE STREAM" },
2556		{ ATA_CMD_SMART,		"SMART" },
2557		{ ATA_CMD_MEDIA_LOCK,		"DOOR LOCK" },
2558		{ ATA_CMD_MEDIA_UNLOCK,		"DOOR UNLOCK" },
2559		{ ATA_CMD_DSM,			"DATA SET MANAGEMENT" },
2560		{ ATA_CMD_CHK_MED_CRD_TYP,	"CHECK MEDIA CARD TYPE" },
2561		{ ATA_CMD_CFA_REQ_EXT_ERR,	"CFA REQUEST EXTENDED ERROR" },
2562		{ ATA_CMD_CFA_WRITE_NE,		"CFA WRITE SECTORS WITHOUT ERASE" },
2563		{ ATA_CMD_CFA_TRANS_SECT,	"CFA TRANSLATE SECTOR" },
2564		{ ATA_CMD_CFA_ERASE,		"CFA ERASE SECTORS" },
2565		{ ATA_CMD_CFA_WRITE_MULT_NE,	"CFA WRITE MULTIPLE WITHOUT ERASE" },
2566		{ ATA_CMD_REQ_SENSE_DATA,	"REQUEST SENSE DATA EXT" },
2567		{ ATA_CMD_SANITIZE_DEVICE,	"SANITIZE DEVICE" },
2568		{ ATA_CMD_ZAC_MGMT_IN,		"ZAC MANAGEMENT IN" },
2569		{ ATA_CMD_ZAC_MGMT_OUT,		"ZAC MANAGEMENT OUT" },
2570		{ ATA_CMD_READ_LONG,		"READ LONG (with retries)" },
2571		{ ATA_CMD_READ_LONG_ONCE,	"READ LONG (without retries)" },
2572		{ ATA_CMD_WRITE_LONG,		"WRITE LONG (with retries)" },
2573		{ ATA_CMD_WRITE_LONG_ONCE,	"WRITE LONG (without retries)" },
2574		{ ATA_CMD_RESTORE,		"RECALIBRATE" },
2575		{ 0,				NULL } /* terminate list */
2576	};
2577
2578	unsigned int i;
2579	for (i = 0; cmd_descr[i].text; i++)
2580		if (cmd_descr[i].command == command)
2581			return cmd_descr[i].text;
2582#endif
2583
2584	return "unknown";
2585}
2586EXPORT_SYMBOL_GPL(ata_get_cmd_name);
2587
2588/**
2589 *	ata_eh_link_report - report error handling to user
2590 *	@link: ATA link EH is going on
2591 *
2592 *	Report EH to user.
2593 *
2594 *	LOCKING:
2595 *	None.
2596 */
2597static void ata_eh_link_report(struct ata_link *link)
2598{
2599	struct ata_port *ap = link->ap;
2600	struct ata_eh_context *ehc = &link->eh_context;
2601	struct ata_queued_cmd *qc;
2602	const char *frozen, *desc;
2603	char tries_buf[16] = "";
2604	int tag, nr_failed = 0;
2605
2606	if (ehc->i.flags & ATA_EHI_QUIET)
2607		return;
2608
2609	desc = NULL;
2610	if (ehc->i.desc[0] != '\0')
2611		desc = ehc->i.desc;
2612
2613	ata_qc_for_each_raw(ap, qc, tag) {
2614		if (!(qc->flags & ATA_QCFLAG_EH) ||
2615		    ata_dev_phys_link(qc->dev) != link ||
2616		    ((qc->flags & ATA_QCFLAG_QUIET) &&
2617		     qc->err_mask == AC_ERR_DEV))
2618			continue;
2619		if (qc->flags & ATA_QCFLAG_SENSE_VALID && !qc->err_mask)
2620			continue;
2621
2622		nr_failed++;
2623	}
2624
2625	if (!nr_failed && !ehc->i.err_mask)
2626		return;
2627
2628	frozen = "";
2629	if (ata_port_is_frozen(ap))
2630		frozen = " frozen";
2631
2632	if (ap->eh_tries < ATA_EH_MAX_TRIES)
2633		snprintf(tries_buf, sizeof(tries_buf), " t%d",
2634			 ap->eh_tries);
2635
2636	if (ehc->i.dev) {
2637		ata_dev_err(ehc->i.dev, "exception Emask 0x%x "
2638			    "SAct 0x%x SErr 0x%x action 0x%x%s%s\n",
2639			    ehc->i.err_mask, link->sactive, ehc->i.serror,
2640			    ehc->i.action, frozen, tries_buf);
2641		if (desc)
2642			ata_dev_err(ehc->i.dev, "%s\n", desc);
2643	} else {
2644		ata_link_err(link, "exception Emask 0x%x "
2645			     "SAct 0x%x SErr 0x%x action 0x%x%s%s\n",
2646			     ehc->i.err_mask, link->sactive, ehc->i.serror,
2647			     ehc->i.action, frozen, tries_buf);
2648		if (desc)
2649			ata_link_err(link, "%s\n", desc);
2650	}
2651
2652#ifdef CONFIG_ATA_VERBOSE_ERROR
2653	if (ehc->i.serror)
2654		ata_link_err(link,
2655		  "SError: { %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s}\n",
2656		  ehc->i.serror & SERR_DATA_RECOVERED ? "RecovData " : "",
2657		  ehc->i.serror & SERR_COMM_RECOVERED ? "RecovComm " : "",
2658		  ehc->i.serror & SERR_DATA ? "UnrecovData " : "",
2659		  ehc->i.serror & SERR_PERSISTENT ? "Persist " : "",
2660		  ehc->i.serror & SERR_PROTOCOL ? "Proto " : "",
2661		  ehc->i.serror & SERR_INTERNAL ? "HostInt " : "",
2662		  ehc->i.serror & SERR_PHYRDY_CHG ? "PHYRdyChg " : "",
2663		  ehc->i.serror & SERR_PHY_INT_ERR ? "PHYInt " : "",
2664		  ehc->i.serror & SERR_COMM_WAKE ? "CommWake " : "",
2665		  ehc->i.serror & SERR_10B_8B_ERR ? "10B8B " : "",
2666		  ehc->i.serror & SERR_DISPARITY ? "Dispar " : "",
2667		  ehc->i.serror & SERR_CRC ? "BadCRC " : "",
2668		  ehc->i.serror & SERR_HANDSHAKE ? "Handshk " : "",
2669		  ehc->i.serror & SERR_LINK_SEQ_ERR ? "LinkSeq " : "",
2670		  ehc->i.serror & SERR_TRANS_ST_ERROR ? "TrStaTrns " : "",
2671		  ehc->i.serror & SERR_UNRECOG_FIS ? "UnrecFIS " : "",
2672		  ehc->i.serror & SERR_DEV_XCHG ? "DevExch " : "");
2673#endif
2674
2675	ata_qc_for_each_raw(ap, qc, tag) {
2676		struct ata_taskfile *cmd = &qc->tf, *res = &qc->result_tf;
2677		char data_buf[20] = "";
2678		char cdb_buf[70] = "";
2679
2680		if (!(qc->flags & ATA_QCFLAG_EH) ||
2681		    ata_dev_phys_link(qc->dev) != link || !qc->err_mask)
2682			continue;
2683
2684		if (qc->dma_dir != DMA_NONE) {
2685			static const char *dma_str[] = {
2686				[DMA_BIDIRECTIONAL]	= "bidi",
2687				[DMA_TO_DEVICE]		= "out",
2688				[DMA_FROM_DEVICE]	= "in",
2689			};
2690			const char *prot_str = NULL;
2691
2692			switch (qc->tf.protocol) {
2693			case ATA_PROT_UNKNOWN:
2694				prot_str = "unknown";
2695				break;
2696			case ATA_PROT_NODATA:
2697				prot_str = "nodata";
2698				break;
2699			case ATA_PROT_PIO:
2700				prot_str = "pio";
2701				break;
2702			case ATA_PROT_DMA:
2703				prot_str = "dma";
2704				break;
2705			case ATA_PROT_NCQ:
2706				prot_str = "ncq dma";
2707				break;
2708			case ATA_PROT_NCQ_NODATA:
2709				prot_str = "ncq nodata";
2710				break;
2711			case ATAPI_PROT_NODATA:
2712				prot_str = "nodata";
2713				break;
2714			case ATAPI_PROT_PIO:
2715				prot_str = "pio";
2716				break;
2717			case ATAPI_PROT_DMA:
2718				prot_str = "dma";
2719				break;
2720			}
2721			snprintf(data_buf, sizeof(data_buf), " %s %u %s",
2722				 prot_str, qc->nbytes, dma_str[qc->dma_dir]);
2723		}
2724
2725		if (ata_is_atapi(qc->tf.protocol)) {
2726			const u8 *cdb = qc->cdb;
2727			size_t cdb_len = qc->dev->cdb_len;
2728
2729			if (qc->scsicmd) {
2730				cdb = qc->scsicmd->cmnd;
2731				cdb_len = qc->scsicmd->cmd_len;
2732			}
2733			__scsi_format_command(cdb_buf, sizeof(cdb_buf),
2734					      cdb, cdb_len);
2735		} else
2736			ata_dev_err(qc->dev, "failed command: %s\n",
2737				    ata_get_cmd_name(cmd->command));
2738
2739		ata_dev_err(qc->dev,
2740			"cmd %02x/%02x:%02x:%02x:%02x:%02x/%02x:%02x:%02x:%02x:%02x/%02x "
2741			"tag %d%s\n         %s"
2742			"res %02x/%02x:%02x:%02x:%02x:%02x/%02x:%02x:%02x:%02x:%02x/%02x "
2743			"Emask 0x%x (%s)%s\n",
2744			cmd->command, cmd->feature, cmd->nsect,
2745			cmd->lbal, cmd->lbam, cmd->lbah,
2746			cmd->hob_feature, cmd->hob_nsect,
2747			cmd->hob_lbal, cmd->hob_lbam, cmd->hob_lbah,
2748			cmd->device, qc->tag, data_buf, cdb_buf,
2749			res->status, res->error, res->nsect,
2750			res->lbal, res->lbam, res->lbah,
2751			res->hob_feature, res->hob_nsect,
2752			res->hob_lbal, res->hob_lbam, res->hob_lbah,
2753			res->device, qc->err_mask, ata_err_string(qc->err_mask),
2754			qc->err_mask & AC_ERR_NCQ ? " <F>" : "");
2755
2756#ifdef CONFIG_ATA_VERBOSE_ERROR
2757		if (res->status & (ATA_BUSY | ATA_DRDY | ATA_DF | ATA_DRQ |
2758				   ATA_SENSE | ATA_ERR)) {
2759			if (res->status & ATA_BUSY)
2760				ata_dev_err(qc->dev, "status: { Busy }\n");
2761			else
2762				ata_dev_err(qc->dev, "status: { %s%s%s%s%s}\n",
2763				  res->status & ATA_DRDY ? "DRDY " : "",
2764				  res->status & ATA_DF ? "DF " : "",
2765				  res->status & ATA_DRQ ? "DRQ " : "",
2766				  res->status & ATA_SENSE ? "SENSE " : "",
2767				  res->status & ATA_ERR ? "ERR " : "");
2768		}
2769
2770		if (cmd->command != ATA_CMD_PACKET &&
2771		    (res->error & (ATA_ICRC | ATA_UNC | ATA_AMNF | ATA_IDNF |
2772				   ATA_ABORTED)))
2773			ata_dev_err(qc->dev, "error: { %s%s%s%s%s}\n",
2774				    res->error & ATA_ICRC ? "ICRC " : "",
2775				    res->error & ATA_UNC ? "UNC " : "",
2776				    res->error & ATA_AMNF ? "AMNF " : "",
2777				    res->error & ATA_IDNF ? "IDNF " : "",
2778				    res->error & ATA_ABORTED ? "ABRT " : "");
2779#endif
2780	}
2781}
2782
2783/**
2784 *	ata_eh_report - report error handling to user
2785 *	@ap: ATA port to report EH about
2786 *
2787 *	Report EH to user.
2788 *
2789 *	LOCKING:
2790 *	None.
2791 */
2792void ata_eh_report(struct ata_port *ap)
2793{
2794	struct ata_link *link;
2795
2796	ata_for_each_link(link, ap, HOST_FIRST)
2797		ata_eh_link_report(link);
2798}
2799
2800static int ata_do_reset(struct ata_link *link, ata_reset_fn_t reset,
2801			unsigned int *classes, unsigned long deadline,
2802			bool clear_classes)
2803{
2804	struct ata_device *dev;
2805
2806	if (clear_classes)
2807		ata_for_each_dev(dev, link, ALL)
2808			classes[dev->devno] = ATA_DEV_UNKNOWN;
2809
2810	return reset(link, classes, deadline);
2811}
2812
2813static bool ata_eh_followup_srst_needed(struct ata_link *link, int rc)
2814{
2815	if ((link->flags & ATA_LFLAG_NO_SRST) || ata_link_offline(link))
2816		return false;
2817	if (rc == -EAGAIN)
2818		return true;
2819	if (sata_pmp_supported(link->ap) && ata_is_host_link(link))
2820		return true;
2821	return false;
2822}
2823
2824int ata_eh_reset(struct ata_link *link, int classify,
2825		 struct ata_reset_operations *reset_ops)
2826{
2827	struct ata_port *ap = link->ap;
2828	struct ata_link *slave = ap->slave_link;
2829	struct ata_eh_context *ehc = &link->eh_context;
2830	struct ata_eh_context *sehc = slave ? &slave->eh_context : NULL;
2831	ata_reset_fn_t hardreset = reset_ops->hardreset;
2832	ata_reset_fn_t softreset = reset_ops->softreset;
2833	ata_prereset_fn_t prereset = reset_ops->prereset;
2834	ata_postreset_fn_t postreset = reset_ops->postreset;
2835	unsigned int *classes = ehc->classes;
2836	unsigned int lflags = link->flags;
2837	int verbose = !(ehc->i.flags & ATA_EHI_QUIET);
2838	int max_tries = 0, try = 0;
2839	struct ata_link *failed_link;
2840	struct ata_device *dev;
2841	unsigned long deadline, now;
2842	ata_reset_fn_t reset;
2843	unsigned long flags;
2844	u32 sstatus;
2845	int nr_unknown, rc;
2846
2847	/*
2848	 * Prepare to reset
2849	 */
2850	while (ata_eh_reset_timeouts[max_tries] != UINT_MAX)
2851		max_tries++;
2852	if (link->flags & ATA_LFLAG_RST_ONCE)
2853		max_tries = 1;
2854	if (link->flags & ATA_LFLAG_NO_HRST)
2855		hardreset = NULL;
2856	if (link->flags & ATA_LFLAG_NO_SRST)
2857		softreset = NULL;
2858
2859	/* make sure each reset attempt is at least COOL_DOWN apart */
2860	if (ehc->i.flags & ATA_EHI_DID_RESET) {
2861		now = jiffies;
2862		WARN_ON(time_after(ehc->last_reset, now));
2863		deadline = ata_deadline(ehc->last_reset,
2864					ATA_EH_RESET_COOL_DOWN);
2865		if (time_before(now, deadline))
2866			schedule_timeout_uninterruptible(deadline - now);
2867	}
2868
2869	spin_lock_irqsave(ap->lock, flags);
2870	ap->pflags |= ATA_PFLAG_RESETTING;
2871	spin_unlock_irqrestore(ap->lock, flags);
2872
2873	ata_eh_about_to_do(link, NULL, ATA_EH_RESET);
2874
2875	ata_for_each_dev(dev, link, ALL) {
2876		/* If we issue an SRST then an ATA drive (not ATAPI)
2877		 * may change configuration and be in PIO0 timing. If
2878		 * we do a hard reset (or are coming from power on)
2879		 * this is true for ATA or ATAPI. Until we've set a
2880		 * suitable controller mode we should not touch the
2881		 * bus as we may be talking too fast.
2882		 */
2883		dev->pio_mode = XFER_PIO_0;
2884		dev->dma_mode = 0xff;
2885
2886		/* If the controller has a pio mode setup function
2887		 * then use it to set the chipset to rights. Don't
2888		 * touch the DMA setup as that will be dealt with when
2889		 * configuring devices.
2890		 */
2891		if (ap->ops->set_piomode)
2892			ap->ops->set_piomode(ap, dev);
2893	}
2894
2895	/* prefer hardreset */
2896	reset = NULL;
2897	ehc->i.action &= ~ATA_EH_RESET;
2898	if (hardreset) {
2899		reset = hardreset;
2900		ehc->i.action |= ATA_EH_HARDRESET;
2901	} else if (softreset) {
2902		reset = softreset;
2903		ehc->i.action |= ATA_EH_SOFTRESET;
2904	}
2905
2906	if (prereset) {
2907		unsigned long deadline = ata_deadline(jiffies,
2908						      ATA_EH_PRERESET_TIMEOUT);
2909
2910		if (slave) {
2911			sehc->i.action &= ~ATA_EH_RESET;
2912			sehc->i.action |= ehc->i.action;
2913		}
2914
2915		rc = prereset(link, deadline);
2916
2917		/* If present, do prereset on slave link too.  Reset
2918		 * is skipped iff both master and slave links report
2919		 * -ENOENT or clear ATA_EH_RESET.
2920		 */
2921		if (slave && (rc == 0 || rc == -ENOENT)) {
2922			int tmp;
2923
2924			tmp = prereset(slave, deadline);
2925			if (tmp != -ENOENT)
2926				rc = tmp;
2927
2928			ehc->i.action |= sehc->i.action;
2929		}
2930
2931		if (rc) {
2932			if (rc == -ENOENT) {
2933				ata_link_dbg(link, "port disabled--ignoring\n");
2934				ehc->i.action &= ~ATA_EH_RESET;
2935
2936				ata_for_each_dev(dev, link, ALL)
2937					classes[dev->devno] = ATA_DEV_NONE;
2938
2939				rc = 0;
2940			} else
2941				ata_link_err(link,
2942					     "prereset failed (errno=%d)\n",
2943					     rc);
2944			goto out;
2945		}
2946
2947		/* prereset() might have cleared ATA_EH_RESET.  If so,
2948		 * bang classes, thaw and return.
2949		 */
2950		if (reset && !(ehc->i.action & ATA_EH_RESET)) {
2951			ata_for_each_dev(dev, link, ALL)
2952				classes[dev->devno] = ATA_DEV_NONE;
2953			if (ata_port_is_frozen(ap) && ata_is_host_link(link))
2954				ata_eh_thaw_port(ap);
2955			rc = 0;
2956			goto out;
2957		}
2958	}
2959
2960 retry:
2961	/*
2962	 * Perform reset
2963	 */
2964	if (ata_is_host_link(link))
2965		ata_eh_freeze_port(ap);
2966
2967	deadline = ata_deadline(jiffies, ata_eh_reset_timeouts[try++]);
2968
2969	if (reset) {
2970		if (verbose)
2971			ata_link_info(link, "%s resetting link\n",
2972				      reset == softreset ? "soft" : "hard");
2973
2974		/* mark that this EH session started with reset */
2975		ehc->last_reset = jiffies;
2976		if (reset == hardreset) {
2977			ehc->i.flags |= ATA_EHI_DID_HARDRESET;
2978			trace_ata_link_hardreset_begin(link, classes, deadline);
2979		} else {
2980			ehc->i.flags |= ATA_EHI_DID_SOFTRESET;
2981			trace_ata_link_softreset_begin(link, classes, deadline);
2982		}
2983
2984		rc = ata_do_reset(link, reset, classes, deadline, true);
2985		if (reset == hardreset)
2986			trace_ata_link_hardreset_end(link, classes, rc);
2987		else
2988			trace_ata_link_softreset_end(link, classes, rc);
2989		if (rc && rc != -EAGAIN) {
2990			failed_link = link;
2991			goto fail;
2992		}
2993
2994		/* hardreset slave link if existent */
2995		if (slave && reset == hardreset) {
2996			int tmp;
2997
2998			if (verbose)
2999				ata_link_info(slave, "hard resetting link\n");
3000
3001			ata_eh_about_to_do(slave, NULL, ATA_EH_RESET);
3002			trace_ata_slave_hardreset_begin(slave, classes,
3003							deadline);
3004			tmp = ata_do_reset(slave, reset, classes, deadline,
3005					   false);
3006			trace_ata_slave_hardreset_end(slave, classes, tmp);
3007			switch (tmp) {
3008			case -EAGAIN:
3009				rc = -EAGAIN;
3010				break;
3011			case 0:
3012				break;
3013			default:
3014				failed_link = slave;
3015				rc = tmp;
3016				goto fail;
3017			}
3018		}
3019
3020		/* perform follow-up SRST if necessary */
3021		if (reset == hardreset &&
3022		    ata_eh_followup_srst_needed(link, rc)) {
3023			reset = softreset;
3024
3025			if (!reset) {
3026				ata_link_err(link,
3027	     "follow-up softreset required but no softreset available\n");
3028				failed_link = link;
3029				rc = -EINVAL;
3030				goto fail;
3031			}
3032
3033			ata_eh_about_to_do(link, NULL, ATA_EH_RESET);
3034			trace_ata_link_softreset_begin(link, classes, deadline);
3035			rc = ata_do_reset(link, reset, classes, deadline, true);
3036			trace_ata_link_softreset_end(link, classes, rc);
3037			if (rc) {
3038				failed_link = link;
3039				goto fail;
3040			}
3041		}
3042	} else {
3043		if (verbose)
3044			ata_link_info(link,
3045	"no reset method available, skipping reset\n");
3046		if (!(lflags & ATA_LFLAG_ASSUME_CLASS))
3047			lflags |= ATA_LFLAG_ASSUME_ATA;
3048	}
3049
3050	/*
3051	 * Post-reset processing
3052	 */
3053	ata_for_each_dev(dev, link, ALL) {
3054		/* After the reset, the device state is PIO 0 and the
3055		 * controller state is undefined.  Reset also wakes up
3056		 * drives from sleeping mode.
3057		 */
3058		dev->pio_mode = XFER_PIO_0;
3059		dev->flags &= ~ATA_DFLAG_SLEEPING;
3060
3061		if (ata_phys_link_offline(ata_dev_phys_link(dev)))
3062			continue;
3063
3064		/* apply class override */
3065		if (lflags & ATA_LFLAG_ASSUME_ATA)
3066			classes[dev->devno] = ATA_DEV_ATA;
3067		else if (lflags & ATA_LFLAG_ASSUME_SEMB)
3068			classes[dev->devno] = ATA_DEV_SEMB_UNSUP;
3069	}
3070
3071	/* record current link speed */
3072	if (sata_scr_read(link, SCR_STATUS, &sstatus) == 0)
3073		link->sata_spd = (sstatus >> 4) & 0xf;
3074	if (slave && sata_scr_read(slave, SCR_STATUS, &sstatus) == 0)
3075		slave->sata_spd = (sstatus >> 4) & 0xf;
3076
3077	/* thaw the port */
3078	if (ata_is_host_link(link))
3079		ata_eh_thaw_port(ap);
3080
3081	/* postreset() should clear hardware SError.  Although SError
3082	 * is cleared during link resume, clearing SError here is
3083	 * necessary as some PHYs raise hotplug events after SRST.
3084	 * This introduces race condition where hotplug occurs between
3085	 * reset and here.  This race is mediated by cross checking
3086	 * link onlineness and classification result later.
3087	 */
3088	if (postreset) {
3089		postreset(link, classes);
3090		trace_ata_link_postreset(link, classes, rc);
3091		if (slave) {
3092			postreset(slave, classes);
3093			trace_ata_slave_postreset(slave, classes, rc);
3094		}
3095	}
3096
3097	/* clear cached SError */
3098	spin_lock_irqsave(link->ap->lock, flags);
3099	link->eh_info.serror = 0;
3100	if (slave)
3101		slave->eh_info.serror = 0;
3102	spin_unlock_irqrestore(link->ap->lock, flags);
3103
3104	/*
3105	 * Make sure onlineness and classification result correspond.
3106	 * Hotplug could have happened during reset and some
3107	 * controllers fail to wait while a drive is spinning up after
3108	 * being hotplugged causing misdetection.  By cross checking
3109	 * link on/offlineness and classification result, those
3110	 * conditions can be reliably detected and retried.
3111	 */
3112	nr_unknown = 0;
3113	ata_for_each_dev(dev, link, ALL) {
3114		if (ata_phys_link_online(ata_dev_phys_link(dev))) {
3115			if (classes[dev->devno] == ATA_DEV_UNKNOWN) {
3116				ata_dev_dbg(dev, "link online but device misclassified\n");
3117				classes[dev->devno] = ATA_DEV_NONE;
3118				nr_unknown++;
3119			}
3120		} else if (ata_phys_link_offline(ata_dev_phys_link(dev))) {
3121			if (ata_class_enabled(classes[dev->devno]))
3122				ata_dev_dbg(dev,
3123					    "link offline, clearing class %d to NONE\n",
3124					    classes[dev->devno]);
3125			classes[dev->devno] = ATA_DEV_NONE;
3126		} else if (classes[dev->devno] == ATA_DEV_UNKNOWN) {
3127			ata_dev_dbg(dev,
3128				    "link status unknown, clearing UNKNOWN to NONE\n");
3129			classes[dev->devno] = ATA_DEV_NONE;
3130		}
3131	}
3132
3133	if (classify && nr_unknown) {
3134		if (try < max_tries) {
3135			ata_link_warn(link,
3136				      "link online but %d devices misclassified, retrying\n",
3137				      nr_unknown);
3138			failed_link = link;
3139			rc = -EAGAIN;
3140			goto fail;
3141		}
3142		ata_link_warn(link,
3143			      "link online but %d devices misclassified, "
3144			      "device detection might fail\n", nr_unknown);
3145	}
3146
3147	/* reset successful, schedule revalidation */
3148	ata_eh_done(link, NULL, ATA_EH_RESET);
3149	if (slave)
3150		ata_eh_done(slave, NULL, ATA_EH_RESET);
3151	ehc->last_reset = jiffies;		/* update to completion time */
3152	ehc->i.action |= ATA_EH_REVALIDATE;
3153	link->lpm_policy = ATA_LPM_UNKNOWN;	/* reset LPM state */
3154
3155	rc = 0;
3156 out:
3157	/* clear hotplug flag */
3158	ehc->i.flags &= ~ATA_EHI_HOTPLUGGED;
3159	if (slave)
3160		sehc->i.flags &= ~ATA_EHI_HOTPLUGGED;
3161
3162	spin_lock_irqsave(ap->lock, flags);
3163	ap->pflags &= ~ATA_PFLAG_RESETTING;
3164	spin_unlock_irqrestore(ap->lock, flags);
3165
3166	return rc;
3167
3168 fail:
3169	/* if SCR isn't accessible on a fan-out port, PMP needs to be reset */
3170	if (!ata_is_host_link(link) &&
3171	    sata_scr_read(link, SCR_STATUS, &sstatus))
3172		rc = -ERESTART;
3173
3174	if (try >= max_tries) {
3175		/*
3176		 * Thaw host port even if reset failed, so that the port
3177		 * can be retried on the next phy event.  This risks
3178		 * repeated EH runs but seems to be a better tradeoff than
3179		 * shutting down a port after a botched hotplug attempt.
3180		 */
3181		if (ata_is_host_link(link))
3182			ata_eh_thaw_port(ap);
3183		ata_link_warn(link, "%s failed\n",
3184			      reset == hardreset ? "hardreset" : "softreset");
3185		goto out;
3186	}
3187
3188	now = jiffies;
3189	if (time_before(now, deadline)) {
3190		unsigned long delta = deadline - now;
3191
3192		ata_link_warn(failed_link,
3193			"reset failed (errno=%d), retrying in %u secs\n",
3194			rc, DIV_ROUND_UP(jiffies_to_msecs(delta), 1000));
3195
3196		ata_eh_release(ap);
3197		while (delta)
3198			delta = schedule_timeout_uninterruptible(delta);
3199		ata_eh_acquire(ap);
3200	}
3201
3202	/*
3203	 * While disks spinup behind PMP, some controllers fail sending SRST.
3204	 * They need to be reset - as well as the PMP - before retrying.
3205	 */
3206	if (rc == -ERESTART) {
3207		if (ata_is_host_link(link))
3208			ata_eh_thaw_port(ap);
3209		goto out;
3210	}
3211
3212	if (try == max_tries - 1) {
3213		sata_down_spd_limit(link, 0);
3214		if (slave)
3215			sata_down_spd_limit(slave, 0);
3216	} else if (rc == -EPIPE)
3217		sata_down_spd_limit(failed_link, 0);
3218
3219	if (hardreset)
3220		reset = hardreset;
3221	goto retry;
3222}
3223
3224static inline void ata_eh_pull_park_action(struct ata_port *ap)
3225{
3226	struct ata_link *link;
3227	struct ata_device *dev;
3228	unsigned long flags;
3229
3230	/*
3231	 * This function can be thought of as an extended version of
3232	 * ata_eh_about_to_do() specially crafted to accommodate the
3233	 * requirements of ATA_EH_PARK handling. Since the EH thread
3234	 * does not leave the do {} while () loop in ata_eh_recover as
3235	 * long as the timeout for a park request to *one* device on
3236	 * the port has not expired, and since we still want to pick
3237	 * up park requests to other devices on the same port or
3238	 * timeout updates for the same device, we have to pull
3239	 * ATA_EH_PARK actions from eh_info into eh_context.i
3240	 * ourselves at the beginning of each pass over the loop.
3241	 *
3242	 * Additionally, all write accesses to &ap->park_req_pending
3243	 * through reinit_completion() (see below) or complete_all()
3244	 * (see ata_scsi_park_store()) are protected by the host lock.
3245	 * As a result we have that park_req_pending.done is zero on
3246	 * exit from this function, i.e. when ATA_EH_PARK actions for
3247	 * *all* devices on port ap have been pulled into the
3248	 * respective eh_context structs. If, and only if,
3249	 * park_req_pending.done is non-zero by the time we reach
3250	 * wait_for_completion_timeout(), another ATA_EH_PARK action
3251	 * has been scheduled for at least one of the devices on port
3252	 * ap and we have to cycle over the do {} while () loop in
3253	 * ata_eh_recover() again.
3254	 */
3255
3256	spin_lock_irqsave(ap->lock, flags);
3257	reinit_completion(&ap->park_req_pending);
3258	ata_for_each_link(link, ap, EDGE) {
3259		ata_for_each_dev(dev, link, ALL) {
3260			struct ata_eh_info *ehi = &link->eh_info;
3261
3262			link->eh_context.i.dev_action[dev->devno] |=
3263				ehi->dev_action[dev->devno] & ATA_EH_PARK;
3264			ata_eh_clear_action(link, dev, ehi, ATA_EH_PARK);
3265		}
3266	}
3267	spin_unlock_irqrestore(ap->lock, flags);
3268}
3269
3270static void ata_eh_park_issue_cmd(struct ata_device *dev, int park)
3271{
3272	struct ata_eh_context *ehc = &dev->link->eh_context;
3273	struct ata_taskfile tf;
3274	unsigned int err_mask;
3275
3276	ata_tf_init(dev, &tf);
3277	if (park) {
3278		ehc->unloaded_mask |= 1 << dev->devno;
3279		tf.command = ATA_CMD_IDLEIMMEDIATE;
3280		tf.feature = 0x44;
3281		tf.lbal = 0x4c;
3282		tf.lbam = 0x4e;
3283		tf.lbah = 0x55;
3284	} else {
3285		ehc->unloaded_mask &= ~(1 << dev->devno);
3286		tf.command = ATA_CMD_CHK_POWER;
3287	}
3288
3289	tf.flags |= ATA_TFLAG_DEVICE | ATA_TFLAG_ISADDR;
3290	tf.protocol = ATA_PROT_NODATA;
3291	err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
3292	if (park && (err_mask || tf.lbal != 0xc4)) {
3293		ata_dev_err(dev, "head unload failed!\n");
3294		ehc->unloaded_mask &= ~(1 << dev->devno);
3295	}
3296}
3297
3298static int ata_eh_revalidate_and_attach(struct ata_link *link,
3299					struct ata_device **r_failed_dev)
3300{
3301	struct ata_port *ap = link->ap;
3302	struct ata_eh_context *ehc = &link->eh_context;
3303	struct ata_device *dev;
3304	unsigned int new_mask = 0;
3305	unsigned long flags;
3306	int rc = 0;
3307
3308	/* For PATA drive side cable detection to work, IDENTIFY must
3309	 * be done backwards such that PDIAG- is released by the slave
3310	 * device before the master device is identified.
3311	 */
3312	ata_for_each_dev(dev, link, ALL_REVERSE) {
3313		unsigned int action = ata_eh_dev_action(dev);
3314		unsigned int readid_flags = 0;
3315
3316		if (ehc->i.flags & ATA_EHI_DID_RESET)
3317			readid_flags |= ATA_READID_POSTRESET;
3318
3319		if ((action & ATA_EH_REVALIDATE) && ata_dev_enabled(dev)) {
3320			WARN_ON(dev->class == ATA_DEV_PMP);
3321
3322			/*
3323			 * The link may be in a deep sleep, wake it up.
3324			 *
3325			 * If the link is in deep sleep, ata_phys_link_offline()
3326			 * will return true, causing the revalidation to fail,
3327			 * which leads to a (potentially) needless hard reset.
3328			 *
3329			 * ata_eh_recover() will later restore the link policy
3330			 * to ap->target_lpm_policy after revalidation is done.
3331			 */
3332			if (link->lpm_policy > ATA_LPM_MAX_POWER) {
3333				rc = ata_eh_link_set_lpm(link, ATA_LPM_MAX_POWER,
3334							 r_failed_dev);
3335				if (rc)
3336					goto err;
3337			}
3338
3339			if (!ata_eh_link_established(ata_dev_phys_link(dev))) {
3340				rc = -EIO;
3341				goto err;
3342			}
3343
3344			ata_eh_about_to_do(link, dev, ATA_EH_REVALIDATE);
3345			rc = ata_dev_revalidate(dev, ehc->classes[dev->devno],
3346						readid_flags);
3347			if (rc)
3348				goto err;
3349
3350			ata_eh_done(link, dev, ATA_EH_REVALIDATE);
3351
3352			/* Configuration may have changed, reconfigure
3353			 * transfer mode.
3354			 */
3355			ehc->i.flags |= ATA_EHI_SETMODE;
3356
3357			/* schedule the scsi_rescan_device() here */
3358			schedule_delayed_work(&ap->scsi_rescan_task, 0);
3359		} else if (dev->class == ATA_DEV_UNKNOWN &&
3360			   ehc->tries[dev->devno] &&
3361			   ata_class_enabled(ehc->classes[dev->devno])) {
3362			/* Temporarily set dev->class, it will be
3363			 * permanently set once all configurations are
3364			 * complete.  This is necessary because new
3365			 * device configuration is done in two
3366			 * separate loops.
3367			 */
3368			dev->class = ehc->classes[dev->devno];
3369
3370			if (dev->class == ATA_DEV_PMP)
3371				rc = sata_pmp_attach(dev);
3372			else
3373				rc = ata_dev_read_id(dev, &dev->class,
3374						     readid_flags, dev->id);
3375
3376			/* read_id might have changed class, store and reset */
3377			ehc->classes[dev->devno] = dev->class;
3378			dev->class = ATA_DEV_UNKNOWN;
3379
3380			switch (rc) {
3381			case 0:
3382				/* clear error info accumulated during probe */
3383				ata_ering_clear(&dev->ering);
3384				new_mask |= 1 << dev->devno;
3385				break;
3386			case -ENOENT:
3387				/* IDENTIFY was issued to non-existent
3388				 * device.  No need to reset.  Just
3389				 * thaw and ignore the device.
3390				 */
3391				ata_eh_thaw_port(ap);
3392				break;
3393			default:
3394				goto err;
3395			}
3396		}
3397	}
3398
3399	/* PDIAG- should have been released, ask cable type if post-reset */
3400	if ((ehc->i.flags & ATA_EHI_DID_RESET) && ata_is_host_link(link)) {
3401		if (ap->ops->cable_detect)
3402			ap->cbl = ap->ops->cable_detect(ap);
3403		ata_force_cbl(ap);
3404	}
3405
3406	/* Configure new devices forward such that user doesn't see
3407	 * device detection messages backwards.
3408	 */
3409	ata_for_each_dev(dev, link, ALL) {
3410		if (!(new_mask & (1 << dev->devno)))
3411			continue;
3412
3413		dev->class = ehc->classes[dev->devno];
3414
3415		if (dev->class == ATA_DEV_PMP)
3416			continue;
3417
3418		ehc->i.flags |= ATA_EHI_PRINTINFO;
3419		rc = ata_dev_configure(dev);
3420		ehc->i.flags &= ~ATA_EHI_PRINTINFO;
3421		if (rc) {
3422			dev->class = ATA_DEV_UNKNOWN;
3423			goto err;
3424		}
3425
3426		spin_lock_irqsave(ap->lock, flags);
3427		ap->pflags |= ATA_PFLAG_SCSI_HOTPLUG;
3428		spin_unlock_irqrestore(ap->lock, flags);
3429
3430		/* new device discovered, configure xfermode */
3431		ehc->i.flags |= ATA_EHI_SETMODE;
3432	}
3433
3434	return 0;
3435
3436 err:
3437	dev->flags &= ~ATA_DFLAG_RESUMING;
3438	*r_failed_dev = dev;
3439	return rc;
3440}
3441
3442/**
3443 *	ata_eh_set_mode - Program timings and issue SET FEATURES - XFER
3444 *	@link: link on which timings will be programmed
3445 *	@r_failed_dev: out parameter for failed device
3446 *
3447 *	Set ATA device disk transfer mode (PIO3, UDMA6, etc.).  If
3448 *	ata_eh_set_mode() fails, pointer to the failing device is
3449 *	returned in @r_failed_dev.
3450 *
3451 *	LOCKING:
3452 *	PCI/etc. bus probe sem.
3453 *
3454 *	RETURNS:
3455 *	0 on success, negative errno otherwise
3456 */
3457static int ata_eh_set_mode(struct ata_link *link,
3458			   struct ata_device **r_failed_dev)
3459{
3460	struct ata_port *ap = link->ap;
3461	struct ata_device *dev;
3462	int rc;
3463
3464	/* if data transfer is verified, clear DUBIOUS_XFER on ering top */
3465	ata_for_each_dev(dev, link, ENABLED) {
3466		if (!(dev->flags & ATA_DFLAG_DUBIOUS_XFER)) {
3467			struct ata_ering_entry *ent;
3468
3469			ent = ata_ering_top(&dev->ering);
3470			if (ent)
3471				ent->eflags &= ~ATA_EFLAG_DUBIOUS_XFER;
3472		}
3473	}
3474
3475	/* has private set_mode? */
3476	if (ap->ops->set_mode)
3477		rc = ap->ops->set_mode(link, r_failed_dev);
3478	else
3479		rc = ata_set_mode(link, r_failed_dev);
3480
3481	/* if transfer mode has changed, set DUBIOUS_XFER on device */
3482	ata_for_each_dev(dev, link, ENABLED) {
3483		struct ata_eh_context *ehc = &link->eh_context;
3484		u8 saved_xfer_mode = ehc->saved_xfer_mode[dev->devno];
3485		u8 saved_ncq = !!(ehc->saved_ncq_enabled & (1 << dev->devno));
3486
3487		if (dev->xfer_mode != saved_xfer_mode ||
3488		    ata_ncq_enabled(dev) != saved_ncq)
3489			dev->flags |= ATA_DFLAG_DUBIOUS_XFER;
3490	}
3491
3492	return rc;
3493}
3494
3495/**
3496 *	atapi_eh_clear_ua - Clear ATAPI UNIT ATTENTION after reset
3497 *	@dev: ATAPI device to clear UA for
3498 *
3499 *	Resets and other operations can make an ATAPI device raise
3500 *	UNIT ATTENTION which causes the next operation to fail.  This
3501 *	function clears UA.
3502 *
3503 *	LOCKING:
3504 *	EH context (may sleep).
3505 *
3506 *	RETURNS:
3507 *	0 on success, -errno on failure.
3508 */
3509static int atapi_eh_clear_ua(struct ata_device *dev)
3510{
3511	int i;
3512
3513	for (i = 0; i < ATA_EH_UA_TRIES; i++) {
3514		u8 *sense_buffer = dev->sector_buf;
3515		u8 sense_key = 0;
3516		unsigned int err_mask;
3517
3518		err_mask = atapi_eh_tur(dev, &sense_key);
3519		if (err_mask != 0 && err_mask != AC_ERR_DEV) {
3520			ata_dev_warn(dev,
3521				     "TEST_UNIT_READY failed (err_mask=0x%x)\n",
3522				     err_mask);
3523			return -EIO;
3524		}
3525
3526		if (!err_mask || sense_key != UNIT_ATTENTION)
3527			return 0;
3528
3529		err_mask = atapi_eh_request_sense(dev, sense_buffer, sense_key);
3530		if (err_mask) {
3531			ata_dev_warn(dev, "failed to clear "
3532				"UNIT ATTENTION (err_mask=0x%x)\n", err_mask);
3533			return -EIO;
3534		}
3535	}
3536
3537	ata_dev_warn(dev, "UNIT ATTENTION persists after %d tries\n",
3538		     ATA_EH_UA_TRIES);
3539
3540	return 0;
3541}
3542
3543/**
3544 *	ata_eh_maybe_retry_flush - Retry FLUSH if necessary
3545 *	@dev: ATA device which may need FLUSH retry
3546 *
3547 *	If @dev failed FLUSH, it needs to be reported upper layer
3548 *	immediately as it means that @dev failed to remap and already
3549 *	lost at least a sector and further FLUSH retrials won't make
3550 *	any difference to the lost sector.  However, if FLUSH failed
3551 *	for other reasons, for example transmission error, FLUSH needs
3552 *	to be retried.
3553 *
3554 *	This function determines whether FLUSH failure retry is
3555 *	necessary and performs it if so.
3556 *
3557 *	RETURNS:
3558 *	0 if EH can continue, -errno if EH needs to be repeated.
3559 */
3560static int ata_eh_maybe_retry_flush(struct ata_device *dev)
3561{
3562	struct ata_link *link = dev->link;
3563	struct ata_port *ap = link->ap;
3564	struct ata_queued_cmd *qc;
3565	struct ata_taskfile tf;
3566	unsigned int err_mask;
3567	int rc = 0;
3568
3569	/* did flush fail for this device? */
3570	if (!ata_tag_valid(link->active_tag))
3571		return 0;
3572
3573	qc = __ata_qc_from_tag(ap, link->active_tag);
3574	if (qc->dev != dev || (qc->tf.command != ATA_CMD_FLUSH_EXT &&
3575			       qc->tf.command != ATA_CMD_FLUSH))
3576		return 0;
3577
3578	/* if the device failed it, it should be reported to upper layers */
3579	if (qc->err_mask & AC_ERR_DEV)
3580		return 0;
3581
3582	/* flush failed for some other reason, give it another shot */
3583	ata_tf_init(dev, &tf);
3584
3585	tf.command = qc->tf.command;
3586	tf.flags |= ATA_TFLAG_DEVICE;
3587	tf.protocol = ATA_PROT_NODATA;
3588
3589	ata_dev_warn(dev, "retrying FLUSH 0x%x Emask 0x%x\n",
3590		       tf.command, qc->err_mask);
3591
3592	err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
3593	if (!err_mask) {
3594		/*
3595		 * FLUSH is complete but there's no way to
3596		 * successfully complete a failed command from EH.
3597		 * Making sure retry is allowed at least once and
3598		 * retrying it should do the trick - whatever was in
3599		 * the cache is already on the platter and this won't
3600		 * cause infinite loop.
3601		 */
3602		qc->scsicmd->allowed = max(qc->scsicmd->allowed, 1);
3603	} else {
3604		ata_dev_warn(dev, "FLUSH failed Emask 0x%x\n",
3605			       err_mask);
3606		rc = -EIO;
3607
3608		/* if device failed it, report it to upper layers */
3609		if (err_mask & AC_ERR_DEV) {
3610			qc->err_mask |= AC_ERR_DEV;
3611			qc->result_tf = tf;
3612			if (!ata_port_is_frozen(ap))
3613				rc = 0;
3614		}
3615	}
3616	return rc;
3617}
3618
3619int ata_link_nr_enabled(struct ata_link *link)
3620{
3621	struct ata_device *dev;
3622	int cnt = 0;
3623
3624	ata_for_each_dev(dev, link, ENABLED)
3625		cnt++;
3626	return cnt;
3627}
3628
3629static int ata_link_nr_vacant(struct ata_link *link)
3630{
3631	struct ata_device *dev;
3632	int cnt = 0;
3633
3634	ata_for_each_dev(dev, link, ALL)
3635		if (dev->class == ATA_DEV_UNKNOWN)
3636			cnt++;
3637	return cnt;
3638}
3639
3640static int ata_eh_skip_recovery(struct ata_link *link)
3641{
3642	struct ata_port *ap = link->ap;
3643	struct ata_eh_context *ehc = &link->eh_context;
3644	struct ata_device *dev;
3645
3646	/* skip disabled links */
3647	if (link->flags & ATA_LFLAG_DISABLED)
3648		return 1;
3649
3650	/* skip if explicitly requested */
3651	if (ehc->i.flags & ATA_EHI_NO_RECOVERY)
3652		return 1;
3653
3654	/* thaw frozen port and recover failed devices */
3655	if (ata_port_is_frozen(ap) || ata_link_nr_enabled(link))
3656		return 0;
3657
3658	/* reset at least once if reset is requested */
3659	if ((ehc->i.action & ATA_EH_RESET) &&
3660	    !(ehc->i.flags & ATA_EHI_DID_RESET))
3661		return 0;
3662
3663	/* skip if class codes for all vacant slots are ATA_DEV_NONE */
3664	ata_for_each_dev(dev, link, ALL) {
3665		if (dev->class == ATA_DEV_UNKNOWN &&
3666		    ehc->classes[dev->devno] != ATA_DEV_NONE)
3667			return 0;
3668	}
3669
3670	return 1;
3671}
3672
3673static int ata_count_probe_trials_cb(struct ata_ering_entry *ent, void *void_arg)
3674{
3675	u64 interval = msecs_to_jiffies(ATA_EH_PROBE_TRIAL_INTERVAL);
3676	u64 now = get_jiffies_64();
3677	int *trials = void_arg;
3678
3679	if ((ent->eflags & ATA_EFLAG_OLD_ER) ||
3680	    (ent->timestamp < now - min(now, interval)))
3681		return -1;
3682
3683	(*trials)++;
3684	return 0;
3685}
3686
3687static int ata_eh_schedule_probe(struct ata_device *dev)
3688{
3689	struct ata_eh_context *ehc = &dev->link->eh_context;
3690	struct ata_link *link = ata_dev_phys_link(dev);
3691	int trials = 0;
3692
3693	if (!(ehc->i.probe_mask & (1 << dev->devno)) ||
3694	    (ehc->did_probe_mask & (1 << dev->devno)))
3695		return 0;
3696
3697	ata_eh_detach_dev(dev);
3698	ata_dev_init(dev);
3699	ehc->did_probe_mask |= (1 << dev->devno);
3700	ehc->i.action |= ATA_EH_RESET;
3701	ehc->saved_xfer_mode[dev->devno] = 0;
3702	ehc->saved_ncq_enabled &= ~(1 << dev->devno);
3703
3704	/* the link maybe in a deep sleep, wake it up */
3705	if (link->lpm_policy > ATA_LPM_MAX_POWER) {
3706		if (ata_is_host_link(link))
3707			link->ap->ops->set_lpm(link, ATA_LPM_MAX_POWER,
3708					       ATA_LPM_EMPTY);
3709		else
3710			sata_pmp_set_lpm(link, ATA_LPM_MAX_POWER,
3711					 ATA_LPM_EMPTY);
3712	}
3713
3714	/* Record and count probe trials on the ering.  The specific
3715	 * error mask used is irrelevant.  Because a successful device
3716	 * detection clears the ering, this count accumulates only if
3717	 * there are consecutive failed probes.
3718	 *
3719	 * If the count is equal to or higher than ATA_EH_PROBE_TRIALS
3720	 * in the last ATA_EH_PROBE_TRIAL_INTERVAL, link speed is
3721	 * forced to 1.5Gbps.
3722	 *
3723	 * This is to work around cases where failed link speed
3724	 * negotiation results in device misdetection leading to
3725	 * infinite DEVXCHG or PHRDY CHG events.
3726	 */
3727	ata_ering_record(&dev->ering, 0, AC_ERR_OTHER);
3728	ata_ering_map(&dev->ering, ata_count_probe_trials_cb, &trials);
3729
3730	if (trials > ATA_EH_PROBE_TRIALS)
3731		sata_down_spd_limit(link, 1);
3732
3733	return 1;
3734}
3735
3736static int ata_eh_handle_dev_fail(struct ata_device *dev, int err)
3737{
3738	struct ata_eh_context *ehc = &dev->link->eh_context;
3739
3740	/* -EAGAIN from EH routine indicates retry without prejudice.
3741	 * The requester is responsible for ensuring forward progress.
3742	 */
3743	if (err != -EAGAIN)
3744		ehc->tries[dev->devno]--;
3745
3746	switch (err) {
3747	case -ENODEV:
3748		/* device missing or wrong IDENTIFY data, schedule probing */
3749		ehc->i.probe_mask |= (1 << dev->devno);
3750		fallthrough;
3751	case -EINVAL:
3752		/* give it just one more chance */
3753		ehc->tries[dev->devno] = min(ehc->tries[dev->devno], 1);
3754		fallthrough;
3755	case -EIO:
3756		if (ehc->tries[dev->devno] == 1) {
3757			/* This is the last chance, better to slow
3758			 * down than lose it.
3759			 */
3760			sata_down_spd_limit(ata_dev_phys_link(dev), 0);
3761			if (dev->pio_mode > XFER_PIO_0)
3762				ata_down_xfermask_limit(dev, ATA_DNXFER_PIO);
3763		}
3764	}
3765
3766	if (ata_dev_enabled(dev) && !ehc->tries[dev->devno]) {
3767		/* disable device if it has used up all its chances */
3768		ata_dev_disable(dev);
3769
3770		/* detach if offline */
3771		if (ata_phys_link_offline(ata_dev_phys_link(dev)))
3772			ata_eh_detach_dev(dev);
3773
3774		/* schedule probe if necessary */
3775		if (ata_eh_schedule_probe(dev)) {
3776			ehc->tries[dev->devno] = ATA_EH_DEV_TRIES;
3777			memset(ehc->cmd_timeout_idx[dev->devno], 0,
3778			       sizeof(ehc->cmd_timeout_idx[dev->devno]));
3779		}
3780
3781		return 1;
3782	} else {
3783		ehc->i.action |= ATA_EH_RESET;
3784		return 0;
3785	}
3786}
3787
3788/**
3789 *	ata_eh_recover - recover host port after error
3790 *	@ap: host port to recover
3791 *	@reset_ops: The set of reset operations to use
3792 *	@r_failed_link: out parameter for failed link
3793 *
3794 *	This is the alpha and omega, eum and yang, heart and soul of
3795 *	libata exception handling.  On entry, actions required to
3796 *	recover each link and hotplug requests are recorded in the
3797 *	link's eh_context.  This function executes all the operations
3798 *	with appropriate retrials and fallbacks to resurrect failed
3799 *	devices, detach goners and greet newcomers.
3800 *
3801 *	LOCKING:
3802 *	Kernel thread context (may sleep).
3803 *
3804 *	RETURNS:
3805 *	0 on success, -errno on failure.
3806 */
3807int ata_eh_recover(struct ata_port *ap, struct ata_reset_operations *reset_ops,
3808		   struct ata_link **r_failed_link)
3809{
3810	struct ata_link *link;
3811	struct ata_device *dev;
3812	int rc, nr_fails;
3813	unsigned long flags, deadline;
3814
3815	/* prep for recovery */
3816	ata_for_each_link(link, ap, EDGE) {
3817		struct ata_eh_context *ehc = &link->eh_context;
3818
3819		/* re-enable link? */
3820		if (ehc->i.action & ATA_EH_ENABLE_LINK) {
3821			ata_eh_about_to_do(link, NULL, ATA_EH_ENABLE_LINK);
3822			spin_lock_irqsave(ap->lock, flags);
3823			link->flags &= ~ATA_LFLAG_DISABLED;
3824			spin_unlock_irqrestore(ap->lock, flags);
3825			ata_eh_done(link, NULL, ATA_EH_ENABLE_LINK);
3826		}
3827
3828		ata_for_each_dev(dev, link, ALL) {
3829			if (link->flags & ATA_LFLAG_NO_RETRY)
3830				ehc->tries[dev->devno] = 1;
3831			else
3832				ehc->tries[dev->devno] = ATA_EH_DEV_TRIES;
3833
3834			/* collect port action mask recorded in dev actions */
3835			ehc->i.action |= ehc->i.dev_action[dev->devno] &
3836					 ~ATA_EH_PERDEV_MASK;
3837			ehc->i.dev_action[dev->devno] &= ATA_EH_PERDEV_MASK;
3838
3839			/* process hotplug request */
3840			if (dev->flags & ATA_DFLAG_DETACH)
3841				ata_eh_detach_dev(dev);
3842
3843			/* schedule probe if necessary */
3844			if (!ata_dev_enabled(dev))
3845				ata_eh_schedule_probe(dev);
3846		}
3847	}
3848
3849 retry:
3850	rc = 0;
3851
3852	/* if UNLOADING, finish immediately */
3853	if (ap->pflags & ATA_PFLAG_UNLOADING)
3854		goto out;
3855
3856	/* prep for EH */
3857	ata_for_each_link(link, ap, EDGE) {
3858		struct ata_eh_context *ehc = &link->eh_context;
3859
3860		/* skip EH if possible. */
3861		if (ata_eh_skip_recovery(link))
3862			ehc->i.action = 0;
3863
3864		ata_for_each_dev(dev, link, ALL)
3865			ehc->classes[dev->devno] = ATA_DEV_UNKNOWN;
3866	}
3867
3868	/* reset */
3869	ata_for_each_link(link, ap, EDGE) {
3870		struct ata_eh_context *ehc = &link->eh_context;
3871
3872		if (!(ehc->i.action & ATA_EH_RESET))
3873			continue;
3874
3875		rc = ata_eh_reset(link, ata_link_nr_vacant(link), reset_ops);
3876		if (rc) {
3877			ata_link_err(link, "reset failed, giving up\n");
3878			goto out;
3879		}
3880	}
3881
3882	do {
3883		unsigned long now;
3884
3885		/*
3886		 * clears ATA_EH_PARK in eh_info and resets
3887		 * ap->park_req_pending
3888		 */
3889		ata_eh_pull_park_action(ap);
3890
3891		deadline = jiffies;
3892		ata_for_each_link(link, ap, EDGE) {
3893			ata_for_each_dev(dev, link, ALL) {
3894				struct ata_eh_context *ehc = &link->eh_context;
3895				unsigned long tmp;
3896
3897				if (dev->class != ATA_DEV_ATA &&
3898				    dev->class != ATA_DEV_ZAC)
3899					continue;
3900				if (!(ehc->i.dev_action[dev->devno] &
3901				      ATA_EH_PARK))
3902					continue;
3903				tmp = dev->unpark_deadline;
3904				if (time_before(deadline, tmp))
3905					deadline = tmp;
3906				else if (time_before_eq(tmp, jiffies))
3907					continue;
3908				if (ehc->unloaded_mask & (1 << dev->devno))
3909					continue;
3910
3911				ata_eh_park_issue_cmd(dev, 1);
3912			}
3913		}
3914
3915		now = jiffies;
3916		if (time_before_eq(deadline, now))
3917			break;
3918
3919		ata_eh_release(ap);
3920		deadline = wait_for_completion_timeout(&ap->park_req_pending,
3921						       deadline - now);
3922		ata_eh_acquire(ap);
3923	} while (deadline);
3924	ata_for_each_link(link, ap, EDGE) {
3925		ata_for_each_dev(dev, link, ALL) {
3926			if (!(link->eh_context.unloaded_mask &
3927			      (1 << dev->devno)))
3928				continue;
3929
3930			ata_eh_park_issue_cmd(dev, 0);
3931			ata_eh_done(link, dev, ATA_EH_PARK);
3932		}
3933	}
3934
3935	/* the rest */
3936	nr_fails = 0;
3937	ata_for_each_link(link, ap, PMP_FIRST) {
3938		struct ata_eh_context *ehc = &link->eh_context;
3939
3940		if (sata_pmp_attached(ap) && ata_is_host_link(link))
3941			goto config_lpm;
3942
3943		/* revalidate existing devices and attach new ones */
3944		rc = ata_eh_revalidate_and_attach(link, &dev);
3945		if (rc)
3946			goto rest_fail;
3947
3948		/* if PMP got attached, return, pmp EH will take care of it */
3949		if (link->device->class == ATA_DEV_PMP) {
3950			ehc->i.action = 0;
3951			return 0;
3952		}
3953
3954		/* configure transfer mode if necessary */
3955		if (ehc->i.flags & ATA_EHI_SETMODE) {
3956			rc = ata_eh_set_mode(link, &dev);
3957			if (rc)
3958				goto rest_fail;
3959			ehc->i.flags &= ~ATA_EHI_SETMODE;
3960		}
3961
3962		/* If reset has been issued, clear UA to avoid
3963		 * disrupting the current users of the device.
3964		 */
3965		if (ehc->i.flags & ATA_EHI_DID_RESET) {
3966			ata_for_each_dev(dev, link, ALL) {
3967				if (dev->class != ATA_DEV_ATAPI)
3968					continue;
3969				rc = atapi_eh_clear_ua(dev);
3970				if (rc)
3971					goto rest_fail;
3972				if (zpodd_dev_enabled(dev))
3973					zpodd_post_poweron(dev);
3974			}
3975		}
3976
3977		/*
3978		 * Make sure to transition devices to the active power mode
3979		 * if needed (e.g. if we were scheduled on system resume).
3980		 */
3981		ata_for_each_dev(dev, link, ENABLED) {
3982			if (ehc->i.dev_action[dev->devno] & ATA_EH_SET_ACTIVE) {
3983				ata_dev_power_set_active(dev);
3984				ata_eh_done(link, dev, ATA_EH_SET_ACTIVE);
3985			}
3986		}
3987
3988		/* retry flush if necessary */
3989		ata_for_each_dev(dev, link, ALL) {
3990			if (dev->class != ATA_DEV_ATA &&
3991			    dev->class != ATA_DEV_ZAC)
3992				continue;
3993			rc = ata_eh_maybe_retry_flush(dev);
3994			if (rc)
3995				goto rest_fail;
3996		}
3997
3998	config_lpm:
3999		/* configure link power saving */
4000		if (link->lpm_policy != ap->target_lpm_policy) {
4001			rc = ata_eh_link_set_lpm(link, ap->target_lpm_policy,
4002						 &dev);
4003			if (rc)
4004				goto rest_fail;
4005		}
4006
4007		/* this link is okay now */
4008		ehc->i.flags = 0;
4009		continue;
4010
4011	rest_fail:
4012		nr_fails++;
4013		if (dev)
4014			ata_eh_handle_dev_fail(dev, rc);
4015
4016		if (ata_port_is_frozen(ap)) {
4017			/* PMP reset requires working host port.
4018			 * Can't retry if it's frozen.
4019			 */
4020			if (sata_pmp_attached(ap))
4021				goto out;
4022			break;
4023		}
4024	}
4025
4026	if (nr_fails)
4027		goto retry;
4028
4029 out:
4030	if (rc && r_failed_link)
4031		*r_failed_link = link;
4032
4033	return rc;
4034}
4035
4036/**
4037 *	ata_eh_finish - finish up EH
4038 *	@ap: host port to finish EH for
4039 *
4040 *	Recovery is complete.  Clean up EH states and retry or finish
4041 *	failed qcs.
4042 *
4043 *	LOCKING:
4044 *	None.
4045 */
4046void ata_eh_finish(struct ata_port *ap)
4047{
4048	struct ata_queued_cmd *qc;
4049	int tag;
4050
4051	/* retry or finish qcs */
4052	ata_qc_for_each_raw(ap, qc, tag) {
4053		if (!(qc->flags & ATA_QCFLAG_EH))
4054			continue;
4055
4056		if (qc->err_mask) {
4057			/* FIXME: Once EH migration is complete,
4058			 * generate sense data in this function,
4059			 * considering both err_mask and tf.
4060			 */
4061			if (qc->flags & ATA_QCFLAG_RETRY) {
4062				/*
4063				 * Since qc->err_mask is set, ata_eh_qc_retry()
4064				 * will not increment scmd->allowed, so upper
4065				 * layer will only retry the command if it has
4066				 * not already been retried too many times.
4067				 */
4068				ata_eh_qc_retry(qc);
4069			} else {
4070				ata_eh_qc_complete(qc);
4071			}
4072		} else {
4073			if (qc->flags & ATA_QCFLAG_SENSE_VALID ||
4074			    qc->flags & ATA_QCFLAG_EH_SUCCESS_CMD) {
4075				ata_eh_qc_complete(qc);
4076			} else {
4077				/* feed zero TF to sense generation */
4078				memset(&qc->result_tf, 0, sizeof(qc->result_tf));
4079				/*
4080				 * Since qc->err_mask is not set,
4081				 * ata_eh_qc_retry() will increment
4082				 * scmd->allowed, so upper layer is guaranteed
4083				 * to retry the command.
4084				 */
4085				ata_eh_qc_retry(qc);
4086			}
4087		}
4088	}
4089
4090	/* make sure nr_active_links is zero after EH */
4091	WARN_ON(ap->nr_active_links);
4092	ap->nr_active_links = 0;
4093}
4094
4095/**
4096 *	ata_std_error_handler - standard error handler
4097 *	@ap: host port to handle error for
4098 *
4099 *	Perform standard error handling sequence.
4100 *
4101 *	LOCKING:
4102 *	Kernel thread context (may sleep).
4103 */
4104void ata_std_error_handler(struct ata_port *ap)
4105{
4106	struct ata_reset_operations *reset_ops = &ap->ops->reset;
4107	struct ata_link *link = &ap->link;
4108	int rc;
4109
4110	/* Ignore built-in hardresets if SCR access is not available */
4111	if ((reset_ops->hardreset == sata_std_hardreset ||
4112	     reset_ops->hardreset == sata_sff_hardreset) &&
4113	    !sata_scr_valid(link))
4114		link->flags |= ATA_LFLAG_NO_HRST;
4115
4116	ata_eh_autopsy(ap);
4117	ata_eh_report(ap);
4118
4119	rc = ata_eh_recover(ap, reset_ops, NULL);
4120	if (rc) {
4121		struct ata_device *dev;
4122
4123		ata_for_each_dev(dev, link, ALL)
4124			ata_dev_disable(dev);
4125	}
4126
4127	ata_eh_finish(ap);
4128}
4129EXPORT_SYMBOL_GPL(ata_std_error_handler);
4130
4131#ifdef CONFIG_PM
4132/**
4133 *	ata_eh_handle_port_suspend - perform port suspend operation
4134 *	@ap: port to suspend
4135 *
4136 *	Suspend @ap.
4137 *
4138 *	LOCKING:
4139 *	Kernel thread context (may sleep).
4140 */
4141static void ata_eh_handle_port_suspend(struct ata_port *ap)
4142{
4143	unsigned long flags;
4144	int rc = 0;
4145	struct ata_device *dev;
4146	struct ata_link *link;
4147
4148	/* are we suspending? */
4149	spin_lock_irqsave(ap->lock, flags);
4150	if (!(ap->pflags & ATA_PFLAG_PM_PENDING) ||
4151	    ap->pm_mesg.event & PM_EVENT_RESUME) {
4152		spin_unlock_irqrestore(ap->lock, flags);
4153		return;
4154	}
4155	spin_unlock_irqrestore(ap->lock, flags);
4156
4157	WARN_ON(ap->pflags & ATA_PFLAG_SUSPENDED);
4158
4159	/*
4160	 * We will reach this point for all of the PM events:
4161	 * PM_EVENT_SUSPEND (if runtime pm, PM_EVENT_AUTO will also be set)
4162	 * PM_EVENT_FREEZE, and PM_EVENT_HIBERNATE.
4163	 *
4164	 * We do not want to perform disk spin down for PM_EVENT_FREEZE.
4165	 * (Spin down will be performed by the subsequent PM_EVENT_HIBERNATE.)
4166	 */
4167	if (!(ap->pm_mesg.event & PM_EVENT_FREEZE)) {
4168		/* Set all devices attached to the port in standby mode */
4169		ata_for_each_link(link, ap, HOST_FIRST) {
4170			ata_for_each_dev(dev, link, ENABLED)
4171				ata_dev_power_set_standby(dev);
4172		}
4173	}
4174
4175	/*
4176	 * If we have a ZPODD attached, check its zero
4177	 * power ready status before the port is frozen.
4178	 * Only needed for runtime suspend.
4179	 */
4180	if (PMSG_IS_AUTO(ap->pm_mesg)) {
4181		ata_for_each_dev(dev, &ap->link, ENABLED) {
4182			if (zpodd_dev_enabled(dev))
4183				zpodd_on_suspend(dev);
4184		}
4185	}
4186
4187	/* suspend */
4188	ata_eh_freeze_port(ap);
4189
4190	if (ap->ops->port_suspend)
4191		rc = ap->ops->port_suspend(ap, ap->pm_mesg);
4192
4193	ata_acpi_set_state(ap, ap->pm_mesg);
4194
4195	/* update the flags */
4196	spin_lock_irqsave(ap->lock, flags);
4197
4198	ap->pflags &= ~ATA_PFLAG_PM_PENDING;
4199	if (rc == 0)
4200		ap->pflags |= ATA_PFLAG_SUSPENDED;
4201	else if (ata_port_is_frozen(ap))
4202		ata_port_schedule_eh(ap);
4203
4204	spin_unlock_irqrestore(ap->lock, flags);
4205
4206	return;
4207}
4208
4209/**
4210 *	ata_eh_handle_port_resume - perform port resume operation
4211 *	@ap: port to resume
4212 *
4213 *	Resume @ap.
4214 *
4215 *	LOCKING:
4216 *	Kernel thread context (may sleep).
4217 */
4218static void ata_eh_handle_port_resume(struct ata_port *ap)
4219{
4220	struct ata_link *link;
4221	struct ata_device *dev;
4222	unsigned long flags;
4223
4224	/* are we resuming? */
4225	spin_lock_irqsave(ap->lock, flags);
4226	if (!(ap->pflags & ATA_PFLAG_PM_PENDING) ||
4227	    !(ap->pm_mesg.event & PM_EVENT_RESUME)) {
4228		spin_unlock_irqrestore(ap->lock, flags);
4229		return;
4230	}
4231	spin_unlock_irqrestore(ap->lock, flags);
4232
4233	WARN_ON(!(ap->pflags & ATA_PFLAG_SUSPENDED));
4234
4235	/*
4236	 * Error timestamps are in jiffies which doesn't run while
4237	 * suspended and PHY events during resume isn't too uncommon.
4238	 * When the two are combined, it can lead to unnecessary speed
4239	 * downs if the machine is suspended and resumed repeatedly.
4240	 * Clear error history.
4241	 */
4242	ata_for_each_link(link, ap, HOST_FIRST)
4243		ata_for_each_dev(dev, link, ALL)
4244			ata_ering_clear(&dev->ering);
4245
4246	ata_acpi_set_state(ap, ap->pm_mesg);
4247
4248	if (ap->ops->port_resume)
4249		ap->ops->port_resume(ap);
4250
4251	/* tell ACPI that we're resuming */
4252	ata_acpi_on_resume(ap);
4253
4254	/* update the flags */
4255	spin_lock_irqsave(ap->lock, flags);
4256	ap->pflags &= ~(ATA_PFLAG_PM_PENDING | ATA_PFLAG_SUSPENDED);
4257	ap->pflags |= ATA_PFLAG_RESUMING;
4258	spin_unlock_irqrestore(ap->lock, flags);
4259}
4260#endif /* CONFIG_PM */
~/ Read-only file preview.