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