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