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