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