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