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