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