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