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