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