GNU Linux-libre 4.19.245-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_FPDMA_SEND,           "SEND FPDMA QUEUED" },
2354                 { ATA_CMD_FPDMA_RECV,           "RECEIVE FPDMA QUEUED" },
2355                 { ATA_CMD_PIO_READ,             "READ SECTOR(S)" },
2356                 { ATA_CMD_PIO_READ_EXT,         "READ SECTOR(S) EXT" },
2357                 { ATA_CMD_PIO_WRITE,            "WRITE SECTOR(S)" },
2358                 { ATA_CMD_PIO_WRITE_EXT,        "WRITE SECTOR(S) EXT" },
2359                 { ATA_CMD_READ_MULTI,           "READ MULTIPLE" },
2360                 { ATA_CMD_READ_MULTI_EXT,       "READ MULTIPLE EXT" },
2361                 { ATA_CMD_WRITE_MULTI,          "WRITE MULTIPLE" },
2362                 { ATA_CMD_WRITE_MULTI_EXT,      "WRITE MULTIPLE EXT" },
2363                 { ATA_CMD_WRITE_MULTI_FUA_EXT,  "WRITE MULTIPLE FUA EXT" },
2364                 { ATA_CMD_SET_FEATURES,         "SET FEATURES" },
2365                 { ATA_CMD_SET_MULTI,            "SET MULTIPLE MODE" },
2366                 { ATA_CMD_VERIFY,               "READ VERIFY SECTOR(S)" },
2367                 { ATA_CMD_VERIFY_EXT,           "READ VERIFY SECTOR(S) EXT" },
2368                 { ATA_CMD_WRITE_UNCORR_EXT,     "WRITE UNCORRECTABLE EXT" },
2369                 { ATA_CMD_STANDBYNOW1,          "STANDBY IMMEDIATE" },
2370                 { ATA_CMD_IDLEIMMEDIATE,        "IDLE IMMEDIATE" },
2371                 { ATA_CMD_SLEEP,                "SLEEP" },
2372                 { ATA_CMD_INIT_DEV_PARAMS,      "INITIALIZE DEVICE PARAMETERS" },
2373                 { ATA_CMD_READ_NATIVE_MAX,      "READ NATIVE MAX ADDRESS" },
2374                 { ATA_CMD_READ_NATIVE_MAX_EXT,  "READ NATIVE MAX ADDRESS EXT" },
2375                 { ATA_CMD_SET_MAX,              "SET MAX ADDRESS" },
2376                 { ATA_CMD_SET_MAX_EXT,          "SET MAX ADDRESS EXT" },
2377                 { ATA_CMD_READ_LOG_EXT,         "READ LOG EXT" },
2378                 { ATA_CMD_WRITE_LOG_EXT,        "WRITE LOG EXT" },
2379                 { ATA_CMD_READ_LOG_DMA_EXT,     "READ LOG DMA EXT" },
2380                 { ATA_CMD_WRITE_LOG_DMA_EXT,    "WRITE LOG DMA EXT" },
2381                 { ATA_CMD_TRUSTED_NONDATA,      "TRUSTED NON-DATA" },
2382                 { ATA_CMD_TRUSTED_RCV,          "TRUSTED RECEIVE" },
2383                 { ATA_CMD_TRUSTED_RCV_DMA,      "TRUSTED RECEIVE DMA" },
2384                 { ATA_CMD_TRUSTED_SND,          "TRUSTED SEND" },
2385                 { ATA_CMD_TRUSTED_SND_DMA,      "TRUSTED SEND DMA" },
2386                 { ATA_CMD_PMP_READ,             "READ BUFFER" },
2387                 { ATA_CMD_PMP_READ_DMA,         "READ BUFFER DMA" },
2388                 { ATA_CMD_PMP_WRITE,            "WRITE BUFFER" },
2389                 { ATA_CMD_PMP_WRITE_DMA,        "WRITE BUFFER DMA" },
2390                 { ATA_CMD_CONF_OVERLAY,         "DEVICE CONFIGURATION OVERLAY" },
2391                 { ATA_CMD_SEC_SET_PASS,         "SECURITY SET PASSWORD" },
2392                 { ATA_CMD_SEC_UNLOCK,           "SECURITY UNLOCK" },
2393                 { ATA_CMD_SEC_ERASE_PREP,       "SECURITY ERASE PREPARE" },
2394                 { ATA_CMD_SEC_ERASE_UNIT,       "SECURITY ERASE UNIT" },
2395                 { ATA_CMD_SEC_FREEZE_LOCK,      "SECURITY FREEZE LOCK" },
2396                 { ATA_CMD_SEC_DISABLE_PASS,     "SECURITY DISABLE PASSWORD" },
2397                 { ATA_CMD_CONFIG_STREAM,        "CONFIGURE STREAM" },
2398                 { ATA_CMD_SMART,                "SMART" },
2399                 { ATA_CMD_MEDIA_LOCK,           "DOOR LOCK" },
2400                 { ATA_CMD_MEDIA_UNLOCK,         "DOOR UNLOCK" },
2401                 { ATA_CMD_DSM,                  "DATA SET MANAGEMENT" },
2402                 { ATA_CMD_CHK_MED_CRD_TYP,      "CHECK MEDIA CARD TYPE" },
2403                 { ATA_CMD_CFA_REQ_EXT_ERR,      "CFA REQUEST EXTENDED ERROR" },
2404                 { ATA_CMD_CFA_WRITE_NE,         "CFA WRITE SECTORS WITHOUT ERASE" },
2405                 { ATA_CMD_CFA_TRANS_SECT,       "CFA TRANSLATE SECTOR" },
2406                 { ATA_CMD_CFA_ERASE,            "CFA ERASE SECTORS" },
2407                 { ATA_CMD_CFA_WRITE_MULT_NE,    "CFA WRITE MULTIPLE WITHOUT ERASE" },
2408                 { ATA_CMD_REQ_SENSE_DATA,       "REQUEST SENSE DATA EXT" },
2409                 { ATA_CMD_SANITIZE_DEVICE,      "SANITIZE DEVICE" },
2410                 { ATA_CMD_ZAC_MGMT_IN,          "ZAC MANAGEMENT IN" },
2411                 { ATA_CMD_ZAC_MGMT_OUT,         "ZAC MANAGEMENT OUT" },
2412                 { ATA_CMD_READ_LONG,            "READ LONG (with retries)" },
2413                 { ATA_CMD_READ_LONG_ONCE,       "READ LONG (without retries)" },
2414                 { ATA_CMD_WRITE_LONG,           "WRITE LONG (with retries)" },
2415                 { ATA_CMD_WRITE_LONG_ONCE,      "WRITE LONG (without retries)" },
2416                 { ATA_CMD_RESTORE,              "RECALIBRATE" },
2417                 { 0,                            NULL } /* terminate list */
2418         };
2419
2420         unsigned int i;
2421         for (i = 0; cmd_descr[i].text; i++)
2422                 if (cmd_descr[i].command == command)
2423                         return cmd_descr[i].text;
2424 #endif
2425
2426         return NULL;
2427 }
2428 EXPORT_SYMBOL_GPL(ata_get_cmd_descript);
2429
2430 /**
2431  *      ata_eh_link_report - report error handling to user
2432  *      @link: ATA link EH is going on
2433  *
2434  *      Report EH to user.
2435  *
2436  *      LOCKING:
2437  *      None.
2438  */
2439 static void ata_eh_link_report(struct ata_link *link)
2440 {
2441         struct ata_port *ap = link->ap;
2442         struct ata_eh_context *ehc = &link->eh_context;
2443         struct ata_queued_cmd *qc;
2444         const char *frozen, *desc;
2445         char tries_buf[6] = "";
2446         int tag, nr_failed = 0;
2447
2448         if (ehc->i.flags & ATA_EHI_QUIET)
2449                 return;
2450
2451         desc = NULL;
2452         if (ehc->i.desc[0] != '\0')
2453                 desc = ehc->i.desc;
2454
2455         ata_qc_for_each_raw(ap, qc, tag) {
2456                 if (!(qc->flags & ATA_QCFLAG_FAILED) ||
2457                     ata_dev_phys_link(qc->dev) != link ||
2458                     ((qc->flags & ATA_QCFLAG_QUIET) &&
2459                      qc->err_mask == AC_ERR_DEV))
2460                         continue;
2461                 if (qc->flags & ATA_QCFLAG_SENSE_VALID && !qc->err_mask)
2462                         continue;
2463
2464                 nr_failed++;
2465         }
2466
2467         if (!nr_failed && !ehc->i.err_mask)
2468                 return;
2469
2470         frozen = "";
2471         if (ap->pflags & ATA_PFLAG_FROZEN)
2472                 frozen = " frozen";
2473
2474         if (ap->eh_tries < ATA_EH_MAX_TRIES)
2475                 snprintf(tries_buf, sizeof(tries_buf), " t%d",
2476                          ap->eh_tries);
2477
2478         if (ehc->i.dev) {
2479                 ata_dev_err(ehc->i.dev, "exception Emask 0x%x "
2480                             "SAct 0x%x SErr 0x%x action 0x%x%s%s\n",
2481                             ehc->i.err_mask, link->sactive, ehc->i.serror,
2482                             ehc->i.action, frozen, tries_buf);
2483                 if (desc)
2484                         ata_dev_err(ehc->i.dev, "%s\n", desc);
2485         } else {
2486                 ata_link_err(link, "exception Emask 0x%x "
2487                              "SAct 0x%x SErr 0x%x action 0x%x%s%s\n",
2488                              ehc->i.err_mask, link->sactive, ehc->i.serror,
2489                              ehc->i.action, frozen, tries_buf);
2490                 if (desc)
2491                         ata_link_err(link, "%s\n", desc);
2492         }
2493
2494 #ifdef CONFIG_ATA_VERBOSE_ERROR
2495         if (ehc->i.serror)
2496                 ata_link_err(link,
2497                   "SError: { %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s}\n",
2498                   ehc->i.serror & SERR_DATA_RECOVERED ? "RecovData " : "",
2499                   ehc->i.serror & SERR_COMM_RECOVERED ? "RecovComm " : "",
2500                   ehc->i.serror & SERR_DATA ? "UnrecovData " : "",
2501                   ehc->i.serror & SERR_PERSISTENT ? "Persist " : "",
2502                   ehc->i.serror & SERR_PROTOCOL ? "Proto " : "",
2503                   ehc->i.serror & SERR_INTERNAL ? "HostInt " : "",
2504                   ehc->i.serror & SERR_PHYRDY_CHG ? "PHYRdyChg " : "",
2505                   ehc->i.serror & SERR_PHY_INT_ERR ? "PHYInt " : "",
2506                   ehc->i.serror & SERR_COMM_WAKE ? "CommWake " : "",
2507                   ehc->i.serror & SERR_10B_8B_ERR ? "10B8B " : "",
2508                   ehc->i.serror & SERR_DISPARITY ? "Dispar " : "",
2509                   ehc->i.serror & SERR_CRC ? "BadCRC " : "",
2510                   ehc->i.serror & SERR_HANDSHAKE ? "Handshk " : "",
2511                   ehc->i.serror & SERR_LINK_SEQ_ERR ? "LinkSeq " : "",
2512                   ehc->i.serror & SERR_TRANS_ST_ERROR ? "TrStaTrns " : "",
2513                   ehc->i.serror & SERR_UNRECOG_FIS ? "UnrecFIS " : "",
2514                   ehc->i.serror & SERR_DEV_XCHG ? "DevExch " : "");
2515 #endif
2516
2517         ata_qc_for_each_raw(ap, qc, tag) {
2518                 struct ata_taskfile *cmd = &qc->tf, *res = &qc->result_tf;
2519                 char data_buf[20] = "";
2520                 char cdb_buf[70] = "";
2521
2522                 if (!(qc->flags & ATA_QCFLAG_FAILED) ||
2523                     ata_dev_phys_link(qc->dev) != link || !qc->err_mask)
2524                         continue;
2525
2526                 if (qc->dma_dir != DMA_NONE) {
2527                         static const char *dma_str[] = {
2528                                 [DMA_BIDIRECTIONAL]     = "bidi",
2529                                 [DMA_TO_DEVICE]         = "out",
2530                                 [DMA_FROM_DEVICE]       = "in",
2531                         };
2532                         const char *prot_str = NULL;
2533
2534                         switch (qc->tf.protocol) {
2535                         case ATA_PROT_UNKNOWN:
2536                                 prot_str = "unknown";
2537                                 break;
2538                         case ATA_PROT_NODATA:
2539                                 prot_str = "nodata";
2540                                 break;
2541                         case ATA_PROT_PIO:
2542                                 prot_str = "pio";
2543                                 break;
2544                         case ATA_PROT_DMA:
2545                                 prot_str = "dma";
2546                                 break;
2547                         case ATA_PROT_NCQ:
2548                                 prot_str = "ncq dma";
2549                                 break;
2550                         case ATA_PROT_NCQ_NODATA:
2551                                 prot_str = "ncq nodata";
2552                                 break;
2553                         case ATAPI_PROT_NODATA:
2554                                 prot_str = "nodata";
2555                                 break;
2556                         case ATAPI_PROT_PIO:
2557                                 prot_str = "pio";
2558                                 break;
2559                         case ATAPI_PROT_DMA:
2560                                 prot_str = "dma";
2561                                 break;
2562                         }
2563                         snprintf(data_buf, sizeof(data_buf), " %s %u %s",
2564                                  prot_str, qc->nbytes, dma_str[qc->dma_dir]);
2565                 }
2566
2567                 if (ata_is_atapi(qc->tf.protocol)) {
2568                         const u8 *cdb = qc->cdb;
2569                         size_t cdb_len = qc->dev->cdb_len;
2570
2571                         if (qc->scsicmd) {
2572                                 cdb = qc->scsicmd->cmnd;
2573                                 cdb_len = qc->scsicmd->cmd_len;
2574                         }
2575                         __scsi_format_command(cdb_buf, sizeof(cdb_buf),
2576                                               cdb, cdb_len);
2577                 } else {
2578                         const char *descr = ata_get_cmd_descript(cmd->command);
2579                         if (descr)
2580                                 ata_dev_err(qc->dev, "failed command: %s\n",
2581                                             descr);
2582                 }
2583
2584                 ata_dev_err(qc->dev,
2585                         "cmd %02x/%02x:%02x:%02x:%02x:%02x/%02x:%02x:%02x:%02x:%02x/%02x "
2586                         "tag %d%s\n         %s"
2587                         "res %02x/%02x:%02x:%02x:%02x:%02x/%02x:%02x:%02x:%02x:%02x/%02x "
2588                         "Emask 0x%x (%s)%s\n",
2589                         cmd->command, cmd->feature, cmd->nsect,
2590                         cmd->lbal, cmd->lbam, cmd->lbah,
2591                         cmd->hob_feature, cmd->hob_nsect,
2592                         cmd->hob_lbal, cmd->hob_lbam, cmd->hob_lbah,
2593                         cmd->device, qc->tag, data_buf, cdb_buf,
2594                         res->command, res->feature, res->nsect,
2595                         res->lbal, res->lbam, res->lbah,
2596                         res->hob_feature, res->hob_nsect,
2597                         res->hob_lbal, res->hob_lbam, res->hob_lbah,
2598                         res->device, qc->err_mask, ata_err_string(qc->err_mask),
2599                         qc->err_mask & AC_ERR_NCQ ? " <F>" : "");
2600
2601 #ifdef CONFIG_ATA_VERBOSE_ERROR
2602                 if (res->command & (ATA_BUSY | ATA_DRDY | ATA_DF | ATA_DRQ |
2603                                     ATA_SENSE | ATA_ERR)) {
2604                         if (res->command & ATA_BUSY)
2605                                 ata_dev_err(qc->dev, "status: { Busy }\n");
2606                         else
2607                                 ata_dev_err(qc->dev, "status: { %s%s%s%s%s}\n",
2608                                   res->command & ATA_DRDY ? "DRDY " : "",
2609                                   res->command & ATA_DF ? "DF " : "",
2610                                   res->command & ATA_DRQ ? "DRQ " : "",
2611                                   res->command & ATA_SENSE ? "SENSE " : "",
2612                                   res->command & ATA_ERR ? "ERR " : "");
2613                 }
2614
2615                 if (cmd->command != ATA_CMD_PACKET &&
2616                     (res->feature & (ATA_ICRC | ATA_UNC | ATA_AMNF |
2617                                      ATA_IDNF | ATA_ABORTED)))
2618                         ata_dev_err(qc->dev, "error: { %s%s%s%s%s}\n",
2619                           res->feature & ATA_ICRC ? "ICRC " : "",
2620                           res->feature & ATA_UNC ? "UNC " : "",
2621                           res->feature & ATA_AMNF ? "AMNF " : "",
2622                           res->feature & ATA_IDNF ? "IDNF " : "",
2623                           res->feature & ATA_ABORTED ? "ABRT " : "");
2624 #endif
2625         }
2626 }
2627
2628 /**
2629  *      ata_eh_report - report error handling to user
2630  *      @ap: ATA port to report EH about
2631  *
2632  *      Report EH to user.
2633  *
2634  *      LOCKING:
2635  *      None.
2636  */
2637 void ata_eh_report(struct ata_port *ap)
2638 {
2639         struct ata_link *link;
2640
2641         ata_for_each_link(link, ap, HOST_FIRST)
2642                 ata_eh_link_report(link);
2643 }
2644
2645 static int ata_do_reset(struct ata_link *link, ata_reset_fn_t reset,
2646                         unsigned int *classes, unsigned long deadline,
2647                         bool clear_classes)
2648 {
2649         struct ata_device *dev;
2650
2651         if (clear_classes)
2652                 ata_for_each_dev(dev, link, ALL)
2653                         classes[dev->devno] = ATA_DEV_UNKNOWN;
2654
2655         return reset(link, classes, deadline);
2656 }
2657
2658 static int ata_eh_followup_srst_needed(struct ata_link *link, int rc)
2659 {
2660         if ((link->flags & ATA_LFLAG_NO_SRST) || ata_link_offline(link))
2661                 return 0;
2662         if (rc == -EAGAIN)
2663                 return 1;
2664         if (sata_pmp_supported(link->ap) && ata_is_host_link(link))
2665                 return 1;
2666         return 0;
2667 }
2668
2669 int ata_eh_reset(struct ata_link *link, int classify,
2670                  ata_prereset_fn_t prereset, ata_reset_fn_t softreset,
2671                  ata_reset_fn_t hardreset, ata_postreset_fn_t postreset)
2672 {
2673         struct ata_port *ap = link->ap;
2674         struct ata_link *slave = ap->slave_link;
2675         struct ata_eh_context *ehc = &link->eh_context;
2676         struct ata_eh_context *sehc = slave ? &slave->eh_context : NULL;
2677         unsigned int *classes = ehc->classes;
2678         unsigned int lflags = link->flags;
2679         int verbose = !(ehc->i.flags & ATA_EHI_QUIET);
2680         int max_tries = 0, try = 0;
2681         struct ata_link *failed_link;
2682         struct ata_device *dev;
2683         unsigned long deadline, now;
2684         ata_reset_fn_t reset;
2685         unsigned long flags;
2686         u32 sstatus;
2687         int nr_unknown, rc;
2688
2689         /*
2690          * Prepare to reset
2691          */
2692         while (ata_eh_reset_timeouts[max_tries] != ULONG_MAX)
2693                 max_tries++;
2694         if (link->flags & ATA_LFLAG_RST_ONCE)
2695                 max_tries = 1;
2696         if (link->flags & ATA_LFLAG_NO_HRST)
2697                 hardreset = NULL;
2698         if (link->flags & ATA_LFLAG_NO_SRST)
2699                 softreset = NULL;
2700
2701         /* make sure each reset attempt is at least COOL_DOWN apart */
2702         if (ehc->i.flags & ATA_EHI_DID_RESET) {
2703                 now = jiffies;
2704                 WARN_ON(time_after(ehc->last_reset, now));
2705                 deadline = ata_deadline(ehc->last_reset,
2706                                         ATA_EH_RESET_COOL_DOWN);
2707                 if (time_before(now, deadline))
2708                         schedule_timeout_uninterruptible(deadline - now);
2709         }
2710
2711         spin_lock_irqsave(ap->lock, flags);
2712         ap->pflags |= ATA_PFLAG_RESETTING;
2713         spin_unlock_irqrestore(ap->lock, flags);
2714
2715         ata_eh_about_to_do(link, NULL, ATA_EH_RESET);
2716
2717         ata_for_each_dev(dev, link, ALL) {
2718                 /* If we issue an SRST then an ATA drive (not ATAPI)
2719                  * may change configuration and be in PIO0 timing. If
2720                  * we do a hard reset (or are coming from power on)
2721                  * this is true for ATA or ATAPI. Until we've set a
2722                  * suitable controller mode we should not touch the
2723                  * bus as we may be talking too fast.
2724                  */
2725                 dev->pio_mode = XFER_PIO_0;
2726                 dev->dma_mode = 0xff;
2727
2728                 /* If the controller has a pio mode setup function
2729                  * then use it to set the chipset to rights. Don't
2730                  * touch the DMA setup as that will be dealt with when
2731                  * configuring devices.
2732                  */
2733                 if (ap->ops->set_piomode)
2734                         ap->ops->set_piomode(ap, dev);
2735         }
2736
2737         /* prefer hardreset */
2738         reset = NULL;
2739         ehc->i.action &= ~ATA_EH_RESET;
2740         if (hardreset) {
2741                 reset = hardreset;
2742                 ehc->i.action |= ATA_EH_HARDRESET;
2743         } else if (softreset) {
2744                 reset = softreset;
2745                 ehc->i.action |= ATA_EH_SOFTRESET;
2746         }
2747
2748         if (prereset) {
2749                 unsigned long deadline = ata_deadline(jiffies,
2750                                                       ATA_EH_PRERESET_TIMEOUT);
2751
2752                 if (slave) {
2753                         sehc->i.action &= ~ATA_EH_RESET;
2754                         sehc->i.action |= ehc->i.action;
2755                 }
2756
2757                 rc = prereset(link, deadline);
2758
2759                 /* If present, do prereset on slave link too.  Reset
2760                  * is skipped iff both master and slave links report
2761                  * -ENOENT or clear ATA_EH_RESET.
2762                  */
2763                 if (slave && (rc == 0 || rc == -ENOENT)) {
2764                         int tmp;
2765
2766                         tmp = prereset(slave, deadline);
2767                         if (tmp != -ENOENT)
2768                                 rc = tmp;
2769
2770                         ehc->i.action |= sehc->i.action;
2771                 }
2772
2773                 if (rc) {
2774                         if (rc == -ENOENT) {
2775                                 ata_link_dbg(link, "port disabled--ignoring\n");
2776                                 ehc->i.action &= ~ATA_EH_RESET;
2777
2778                                 ata_for_each_dev(dev, link, ALL)
2779                                         classes[dev->devno] = ATA_DEV_NONE;
2780
2781                                 rc = 0;
2782                         } else
2783                                 ata_link_err(link,
2784                                              "prereset failed (errno=%d)\n",
2785                                              rc);
2786                         goto out;
2787                 }
2788
2789                 /* prereset() might have cleared ATA_EH_RESET.  If so,
2790                  * bang classes, thaw and return.
2791                  */
2792                 if (reset && !(ehc->i.action & ATA_EH_RESET)) {
2793                         ata_for_each_dev(dev, link, ALL)
2794                                 classes[dev->devno] = ATA_DEV_NONE;
2795                         if ((ap->pflags & ATA_PFLAG_FROZEN) &&
2796                             ata_is_host_link(link))
2797                                 ata_eh_thaw_port(ap);
2798                         rc = 0;
2799                         goto out;
2800                 }
2801         }
2802
2803  retry:
2804         /*
2805          * Perform reset
2806          */
2807         if (ata_is_host_link(link))
2808                 ata_eh_freeze_port(ap);
2809
2810         deadline = ata_deadline(jiffies, ata_eh_reset_timeouts[try++]);
2811
2812         if (reset) {
2813                 if (verbose)
2814                         ata_link_info(link, "%s resetting link\n",
2815                                       reset == softreset ? "soft" : "hard");
2816
2817                 /* mark that this EH session started with reset */
2818                 ehc->last_reset = jiffies;
2819                 if (reset == hardreset)
2820                         ehc->i.flags |= ATA_EHI_DID_HARDRESET;
2821                 else
2822                         ehc->i.flags |= ATA_EHI_DID_SOFTRESET;
2823
2824                 rc = ata_do_reset(link, reset, classes, deadline, true);
2825                 if (rc && rc != -EAGAIN) {
2826                         failed_link = link;
2827                         goto fail;
2828                 }
2829
2830                 /* hardreset slave link if existent */
2831                 if (slave && reset == hardreset) {
2832                         int tmp;
2833
2834                         if (verbose)
2835                                 ata_link_info(slave, "hard resetting link\n");
2836
2837                         ata_eh_about_to_do(slave, NULL, ATA_EH_RESET);
2838                         tmp = ata_do_reset(slave, reset, classes, deadline,
2839                                            false);
2840                         switch (tmp) {
2841                         case -EAGAIN:
2842                                 rc = -EAGAIN;
2843                         case 0:
2844                                 break;
2845                         default:
2846                                 failed_link = slave;
2847                                 rc = tmp;
2848                                 goto fail;
2849                         }
2850                 }
2851
2852                 /* perform follow-up SRST if necessary */
2853                 if (reset == hardreset &&
2854                     ata_eh_followup_srst_needed(link, rc)) {
2855                         reset = softreset;
2856
2857                         if (!reset) {
2858                                 ata_link_err(link,
2859              "follow-up softreset required but no softreset available\n");
2860                                 failed_link = link;
2861                                 rc = -EINVAL;
2862                                 goto fail;
2863                         }
2864
2865                         ata_eh_about_to_do(link, NULL, ATA_EH_RESET);
2866                         rc = ata_do_reset(link, reset, classes, deadline, true);
2867                         if (rc) {
2868                                 failed_link = link;
2869                                 goto fail;
2870                         }
2871                 }
2872         } else {
2873                 if (verbose)
2874                         ata_link_info(link,
2875         "no reset method available, skipping reset\n");
2876                 if (!(lflags & ATA_LFLAG_ASSUME_CLASS))
2877                         lflags |= ATA_LFLAG_ASSUME_ATA;
2878         }
2879
2880         /*
2881          * Post-reset processing
2882          */
2883         ata_for_each_dev(dev, link, ALL) {
2884                 /* After the reset, the device state is PIO 0 and the
2885                  * controller state is undefined.  Reset also wakes up
2886                  * drives from sleeping mode.
2887                  */
2888                 dev->pio_mode = XFER_PIO_0;
2889                 dev->flags &= ~ATA_DFLAG_SLEEPING;
2890
2891                 if (ata_phys_link_offline(ata_dev_phys_link(dev)))
2892                         continue;
2893
2894                 /* apply class override */
2895                 if (lflags & ATA_LFLAG_ASSUME_ATA)
2896                         classes[dev->devno] = ATA_DEV_ATA;
2897                 else if (lflags & ATA_LFLAG_ASSUME_SEMB)
2898                         classes[dev->devno] = ATA_DEV_SEMB_UNSUP;
2899         }
2900
2901         /* record current link speed */
2902         if (sata_scr_read(link, SCR_STATUS, &sstatus) == 0)
2903                 link->sata_spd = (sstatus >> 4) & 0xf;
2904         if (slave && sata_scr_read(slave, SCR_STATUS, &sstatus) == 0)
2905                 slave->sata_spd = (sstatus >> 4) & 0xf;
2906
2907         /* thaw the port */
2908         if (ata_is_host_link(link))
2909                 ata_eh_thaw_port(ap);
2910
2911         /* postreset() should clear hardware SError.  Although SError
2912          * is cleared during link resume, clearing SError here is
2913          * necessary as some PHYs raise hotplug events after SRST.
2914          * This introduces race condition where hotplug occurs between
2915          * reset and here.  This race is mediated by cross checking
2916          * link onlineness and classification result later.
2917          */
2918         if (postreset) {
2919                 postreset(link, classes);
2920                 if (slave)
2921                         postreset(slave, classes);
2922         }
2923
2924         /*
2925          * Some controllers can't be frozen very well and may set spurious
2926          * error conditions during reset.  Clear accumulated error
2927          * information and re-thaw the port if frozen.  As reset is the
2928          * final recovery action and we cross check link onlineness against
2929          * device classification later, no hotplug event is lost by this.
2930          */
2931         spin_lock_irqsave(link->ap->lock, flags);
2932         memset(&link->eh_info, 0, sizeof(link->eh_info));
2933         if (slave)
2934                 memset(&slave->eh_info, 0, sizeof(link->eh_info));
2935         ap->pflags &= ~ATA_PFLAG_EH_PENDING;
2936         spin_unlock_irqrestore(link->ap->lock, flags);
2937
2938         if (ap->pflags & ATA_PFLAG_FROZEN)
2939                 ata_eh_thaw_port(ap);
2940
2941         /*
2942          * Make sure onlineness and classification result correspond.
2943          * Hotplug could have happened during reset and some
2944          * controllers fail to wait while a drive is spinning up after
2945          * being hotplugged causing misdetection.  By cross checking
2946          * link on/offlineness and classification result, those
2947          * conditions can be reliably detected and retried.
2948          */
2949         nr_unknown = 0;
2950         ata_for_each_dev(dev, link, ALL) {
2951                 if (ata_phys_link_online(ata_dev_phys_link(dev))) {
2952                         if (classes[dev->devno] == ATA_DEV_UNKNOWN) {
2953                                 ata_dev_dbg(dev, "link online but device misclassified\n");
2954                                 classes[dev->devno] = ATA_DEV_NONE;
2955                                 nr_unknown++;
2956                         }
2957                 } else if (ata_phys_link_offline(ata_dev_phys_link(dev))) {
2958                         if (ata_class_enabled(classes[dev->devno]))
2959                                 ata_dev_dbg(dev,
2960                                             "link offline, clearing class %d to NONE\n",
2961                                             classes[dev->devno]);
2962                         classes[dev->devno] = ATA_DEV_NONE;
2963                 } else if (classes[dev->devno] == ATA_DEV_UNKNOWN) {
2964                         ata_dev_dbg(dev,
2965                                     "link status unknown, clearing UNKNOWN to NONE\n");
2966                         classes[dev->devno] = ATA_DEV_NONE;
2967                 }
2968         }
2969
2970         if (classify && nr_unknown) {
2971                 if (try < max_tries) {
2972                         ata_link_warn(link,
2973                                       "link online but %d devices misclassified, retrying\n",
2974                                       nr_unknown);
2975                         failed_link = link;
2976                         rc = -EAGAIN;
2977                         goto fail;
2978                 }
2979                 ata_link_warn(link,
2980                               "link online but %d devices misclassified, "
2981                               "device detection might fail\n", nr_unknown);
2982         }
2983
2984         /* reset successful, schedule revalidation */
2985         ata_eh_done(link, NULL, ATA_EH_RESET);
2986         if (slave)
2987                 ata_eh_done(slave, NULL, ATA_EH_RESET);
2988         ehc->last_reset = jiffies;              /* update to completion time */
2989         ehc->i.action |= ATA_EH_REVALIDATE;
2990         link->lpm_policy = ATA_LPM_UNKNOWN;     /* reset LPM state */
2991
2992         rc = 0;
2993  out:
2994         /* clear hotplug flag */
2995         ehc->i.flags &= ~ATA_EHI_HOTPLUGGED;
2996         if (slave)
2997                 sehc->i.flags &= ~ATA_EHI_HOTPLUGGED;
2998
2999         spin_lock_irqsave(ap->lock, flags);
3000         ap->pflags &= ~ATA_PFLAG_RESETTING;
3001         spin_unlock_irqrestore(ap->lock, flags);
3002
3003         return rc;
3004
3005  fail:
3006         /* if SCR isn't accessible on a fan-out port, PMP needs to be reset */
3007         if (!ata_is_host_link(link) &&
3008             sata_scr_read(link, SCR_STATUS, &sstatus))
3009                 rc = -ERESTART;
3010
3011         if (try >= max_tries) {
3012                 /*
3013                  * Thaw host port even if reset failed, so that the port
3014                  * can be retried on the next phy event.  This risks
3015                  * repeated EH runs but seems to be a better tradeoff than
3016                  * shutting down a port after a botched hotplug attempt.
3017                  */
3018                 if (ata_is_host_link(link))
3019                         ata_eh_thaw_port(ap);
3020                 goto out;
3021         }
3022
3023         now = jiffies;
3024         if (time_before(now, deadline)) {
3025                 unsigned long delta = deadline - now;
3026
3027                 ata_link_warn(failed_link,
3028                         "reset failed (errno=%d), retrying in %u secs\n",
3029                         rc, DIV_ROUND_UP(jiffies_to_msecs(delta), 1000));
3030
3031                 ata_eh_release(ap);
3032                 while (delta)
3033                         delta = schedule_timeout_uninterruptible(delta);
3034                 ata_eh_acquire(ap);
3035         }
3036
3037         /*
3038          * While disks spinup behind PMP, some controllers fail sending SRST.
3039          * They need to be reset - as well as the PMP - before retrying.
3040          */
3041         if (rc == -ERESTART) {
3042                 if (ata_is_host_link(link))
3043                         ata_eh_thaw_port(ap);
3044                 goto out;
3045         }
3046
3047         if (try == max_tries - 1) {
3048                 sata_down_spd_limit(link, 0);
3049                 if (slave)
3050                         sata_down_spd_limit(slave, 0);
3051         } else if (rc == -EPIPE)
3052                 sata_down_spd_limit(failed_link, 0);
3053
3054         if (hardreset)
3055                 reset = hardreset;
3056         goto retry;
3057 }
3058
3059 static inline void ata_eh_pull_park_action(struct ata_port *ap)
3060 {
3061         struct ata_link *link;
3062         struct ata_device *dev;
3063         unsigned long flags;
3064
3065         /*
3066          * This function can be thought of as an extended version of
3067          * ata_eh_about_to_do() specially crafted to accommodate the
3068          * requirements of ATA_EH_PARK handling. Since the EH thread
3069          * does not leave the do {} while () loop in ata_eh_recover as
3070          * long as the timeout for a park request to *one* device on
3071          * the port has not expired, and since we still want to pick
3072          * up park requests to other devices on the same port or
3073          * timeout updates for the same device, we have to pull
3074          * ATA_EH_PARK actions from eh_info into eh_context.i
3075          * ourselves at the beginning of each pass over the loop.
3076          *
3077          * Additionally, all write accesses to &ap->park_req_pending
3078          * through reinit_completion() (see below) or complete_all()
3079          * (see ata_scsi_park_store()) are protected by the host lock.
3080          * As a result we have that park_req_pending.done is zero on
3081          * exit from this function, i.e. when ATA_EH_PARK actions for
3082          * *all* devices on port ap have been pulled into the
3083          * respective eh_context structs. If, and only if,
3084          * park_req_pending.done is non-zero by the time we reach
3085          * wait_for_completion_timeout(), another ATA_EH_PARK action
3086          * has been scheduled for at least one of the devices on port
3087          * ap and we have to cycle over the do {} while () loop in
3088          * ata_eh_recover() again.
3089          */
3090
3091         spin_lock_irqsave(ap->lock, flags);
3092         reinit_completion(&ap->park_req_pending);
3093         ata_for_each_link(link, ap, EDGE) {
3094                 ata_for_each_dev(dev, link, ALL) {
3095                         struct ata_eh_info *ehi = &link->eh_info;
3096
3097                         link->eh_context.i.dev_action[dev->devno] |=
3098                                 ehi->dev_action[dev->devno] & ATA_EH_PARK;
3099                         ata_eh_clear_action(link, dev, ehi, ATA_EH_PARK);
3100                 }
3101         }
3102         spin_unlock_irqrestore(ap->lock, flags);
3103 }
3104
3105 static void ata_eh_park_issue_cmd(struct ata_device *dev, int park)
3106 {
3107         struct ata_eh_context *ehc = &dev->link->eh_context;
3108         struct ata_taskfile tf;
3109         unsigned int err_mask;
3110
3111         ata_tf_init(dev, &tf);
3112         if (park) {
3113                 ehc->unloaded_mask |= 1 << dev->devno;
3114                 tf.command = ATA_CMD_IDLEIMMEDIATE;
3115                 tf.feature = 0x44;
3116                 tf.lbal = 0x4c;
3117                 tf.lbam = 0x4e;
3118                 tf.lbah = 0x55;
3119         } else {
3120                 ehc->unloaded_mask &= ~(1 << dev->devno);
3121                 tf.command = ATA_CMD_CHK_POWER;
3122         }
3123
3124         tf.flags |= ATA_TFLAG_DEVICE | ATA_TFLAG_ISADDR;
3125         tf.protocol = ATA_PROT_NODATA;
3126         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
3127         if (park && (err_mask || tf.lbal != 0xc4)) {
3128                 ata_dev_err(dev, "head unload failed!\n");
3129                 ehc->unloaded_mask &= ~(1 << dev->devno);
3130         }
3131 }
3132
3133 static int ata_eh_revalidate_and_attach(struct ata_link *link,
3134                                         struct ata_device **r_failed_dev)
3135 {
3136         struct ata_port *ap = link->ap;
3137         struct ata_eh_context *ehc = &link->eh_context;
3138         struct ata_device *dev;
3139         unsigned int new_mask = 0;
3140         unsigned long flags;
3141         int rc = 0;
3142
3143         DPRINTK("ENTER\n");
3144
3145         /* For PATA drive side cable detection to work, IDENTIFY must
3146          * be done backwards such that PDIAG- is released by the slave
3147          * device before the master device is identified.
3148          */
3149         ata_for_each_dev(dev, link, ALL_REVERSE) {
3150                 unsigned int action = ata_eh_dev_action(dev);
3151                 unsigned int readid_flags = 0;
3152
3153                 if (ehc->i.flags & ATA_EHI_DID_RESET)
3154                         readid_flags |= ATA_READID_POSTRESET;
3155
3156                 if ((action & ATA_EH_REVALIDATE) && ata_dev_enabled(dev)) {
3157                         WARN_ON(dev->class == ATA_DEV_PMP);
3158
3159                         if (ata_phys_link_offline(ata_dev_phys_link(dev))) {
3160                                 rc = -EIO;
3161                                 goto err;
3162                         }
3163
3164                         ata_eh_about_to_do(link, dev, ATA_EH_REVALIDATE);
3165                         rc = ata_dev_revalidate(dev, ehc->classes[dev->devno],
3166                                                 readid_flags);
3167                         if (rc)
3168                                 goto err;
3169
3170                         ata_eh_done(link, dev, ATA_EH_REVALIDATE);
3171
3172                         /* Configuration may have changed, reconfigure
3173                          * transfer mode.
3174                          */
3175                         ehc->i.flags |= ATA_EHI_SETMODE;
3176
3177                         /* schedule the scsi_rescan_device() here */
3178                         schedule_work(&(ap->scsi_rescan_task));
3179                 } else if (dev->class == ATA_DEV_UNKNOWN &&
3180                            ehc->tries[dev->devno] &&
3181                            ata_class_enabled(ehc->classes[dev->devno])) {
3182                         /* Temporarily set dev->class, it will be
3183                          * permanently set once all configurations are
3184                          * complete.  This is necessary because new
3185                          * device configuration is done in two
3186                          * separate loops.
3187                          */
3188                         dev->class = ehc->classes[dev->devno];
3189
3190                         if (dev->class == ATA_DEV_PMP)
3191                                 rc = sata_pmp_attach(dev);
3192                         else
3193                                 rc = ata_dev_read_id(dev, &dev->class,
3194                                                      readid_flags, dev->id);
3195
3196                         /* read_id might have changed class, store and reset */
3197                         ehc->classes[dev->devno] = dev->class;
3198                         dev->class = ATA_DEV_UNKNOWN;
3199
3200                         switch (rc) {
3201                         case 0:
3202                                 /* clear error info accumulated during probe */
3203                                 ata_ering_clear(&dev->ering);
3204                                 new_mask |= 1 << dev->devno;
3205                                 break;
3206                         case -ENOENT:
3207                                 /* IDENTIFY was issued to non-existent
3208                                  * device.  No need to reset.  Just
3209                                  * thaw and ignore the device.
3210                                  */
3211                                 ata_eh_thaw_port(ap);
3212                                 break;
3213                         default:
3214                                 goto err;
3215                         }
3216                 }
3217         }
3218
3219         /* PDIAG- should have been released, ask cable type if post-reset */
3220         if ((ehc->i.flags & ATA_EHI_DID_RESET) && ata_is_host_link(link)) {
3221                 if (ap->ops->cable_detect)
3222                         ap->cbl = ap->ops->cable_detect(ap);
3223                 ata_force_cbl(ap);
3224         }
3225
3226         /* Configure new devices forward such that user doesn't see
3227          * device detection messages backwards.
3228          */
3229         ata_for_each_dev(dev, link, ALL) {
3230                 if (!(new_mask & (1 << dev->devno)))
3231                         continue;
3232
3233                 dev->class = ehc->classes[dev->devno];
3234
3235                 if (dev->class == ATA_DEV_PMP)
3236                         continue;
3237
3238                 ehc->i.flags |= ATA_EHI_PRINTINFO;
3239                 rc = ata_dev_configure(dev);
3240                 ehc->i.flags &= ~ATA_EHI_PRINTINFO;
3241                 if (rc) {
3242                         dev->class = ATA_DEV_UNKNOWN;
3243                         goto err;
3244                 }
3245
3246                 spin_lock_irqsave(ap->lock, flags);
3247                 ap->pflags |= ATA_PFLAG_SCSI_HOTPLUG;
3248                 spin_unlock_irqrestore(ap->lock, flags);
3249
3250                 /* new device discovered, configure xfermode */
3251                 ehc->i.flags |= ATA_EHI_SETMODE;
3252         }
3253
3254         return 0;
3255
3256  err:
3257         *r_failed_dev = dev;
3258         DPRINTK("EXIT rc=%d\n", rc);
3259         return rc;
3260 }
3261
3262 /**
3263  *      ata_set_mode - Program timings and issue SET FEATURES - XFER
3264  *      @link: link on which timings will be programmed
3265  *      @r_failed_dev: out parameter for failed device
3266  *
3267  *      Set ATA device disk transfer mode (PIO3, UDMA6, etc.).  If
3268  *      ata_set_mode() fails, pointer to the failing device is
3269  *      returned in @r_failed_dev.
3270  *
3271  *      LOCKING:
3272  *      PCI/etc. bus probe sem.
3273  *
3274  *      RETURNS:
3275  *      0 on success, negative errno otherwise
3276  */
3277 int ata_set_mode(struct ata_link *link, struct ata_device **r_failed_dev)
3278 {
3279         struct ata_port *ap = link->ap;
3280         struct ata_device *dev;
3281         int rc;
3282
3283         /* if data transfer is verified, clear DUBIOUS_XFER on ering top */
3284         ata_for_each_dev(dev, link, ENABLED) {
3285                 if (!(dev->flags & ATA_DFLAG_DUBIOUS_XFER)) {
3286                         struct ata_ering_entry *ent;
3287
3288                         ent = ata_ering_top(&dev->ering);
3289                         if (ent)
3290                                 ent->eflags &= ~ATA_EFLAG_DUBIOUS_XFER;
3291                 }
3292         }
3293
3294         /* has private set_mode? */
3295         if (ap->ops->set_mode)
3296                 rc = ap->ops->set_mode(link, r_failed_dev);
3297         else
3298                 rc = ata_do_set_mode(link, r_failed_dev);
3299
3300         /* if transfer mode has changed, set DUBIOUS_XFER on device */
3301         ata_for_each_dev(dev, link, ENABLED) {
3302                 struct ata_eh_context *ehc = &link->eh_context;
3303                 u8 saved_xfer_mode = ehc->saved_xfer_mode[dev->devno];
3304                 u8 saved_ncq = !!(ehc->saved_ncq_enabled & (1 << dev->devno));
3305
3306                 if (dev->xfer_mode != saved_xfer_mode ||
3307                     ata_ncq_enabled(dev) != saved_ncq)
3308                         dev->flags |= ATA_DFLAG_DUBIOUS_XFER;
3309         }
3310
3311         return rc;
3312 }
3313
3314 /**
3315  *      atapi_eh_clear_ua - Clear ATAPI UNIT ATTENTION after reset
3316  *      @dev: ATAPI device to clear UA for
3317  *
3318  *      Resets and other operations can make an ATAPI device raise
3319  *      UNIT ATTENTION which causes the next operation to fail.  This
3320  *      function clears UA.
3321  *
3322  *      LOCKING:
3323  *      EH context (may sleep).
3324  *
3325  *      RETURNS:
3326  *      0 on success, -errno on failure.
3327  */
3328 static int atapi_eh_clear_ua(struct ata_device *dev)
3329 {
3330         int i;
3331
3332         for (i = 0; i < ATA_EH_UA_TRIES; i++) {
3333                 u8 *sense_buffer = dev->link->ap->sector_buf;
3334                 u8 sense_key = 0;
3335                 unsigned int err_mask;
3336
3337                 err_mask = atapi_eh_tur(dev, &sense_key);
3338                 if (err_mask != 0 && err_mask != AC_ERR_DEV) {
3339                         ata_dev_warn(dev,
3340                                      "TEST_UNIT_READY failed (err_mask=0x%x)\n",
3341                                      err_mask);
3342                         return -EIO;
3343                 }
3344
3345                 if (!err_mask || sense_key != UNIT_ATTENTION)
3346                         return 0;
3347
3348                 err_mask = atapi_eh_request_sense(dev, sense_buffer, sense_key);
3349                 if (err_mask) {
3350                         ata_dev_warn(dev, "failed to clear "
3351                                 "UNIT ATTENTION (err_mask=0x%x)\n", err_mask);
3352                         return -EIO;
3353                 }
3354         }
3355
3356         ata_dev_warn(dev, "UNIT ATTENTION persists after %d tries\n",
3357                      ATA_EH_UA_TRIES);
3358
3359         return 0;
3360 }
3361
3362 /**
3363  *      ata_eh_maybe_retry_flush - Retry FLUSH if necessary
3364  *      @dev: ATA device which may need FLUSH retry
3365  *
3366  *      If @dev failed FLUSH, it needs to be reported upper layer
3367  *      immediately as it means that @dev failed to remap and already
3368  *      lost at least a sector and further FLUSH retrials won't make
3369  *      any difference to the lost sector.  However, if FLUSH failed
3370  *      for other reasons, for example transmission error, FLUSH needs
3371  *      to be retried.
3372  *
3373  *      This function determines whether FLUSH failure retry is
3374  *      necessary and performs it if so.
3375  *
3376  *      RETURNS:
3377  *      0 if EH can continue, -errno if EH needs to be repeated.
3378  */
3379 static int ata_eh_maybe_retry_flush(struct ata_device *dev)
3380 {
3381         struct ata_link *link = dev->link;
3382         struct ata_port *ap = link->ap;
3383         struct ata_queued_cmd *qc;
3384         struct ata_taskfile tf;
3385         unsigned int err_mask;
3386         int rc = 0;
3387
3388         /* did flush fail for this device? */
3389         if (!ata_tag_valid(link->active_tag))
3390                 return 0;
3391
3392         qc = __ata_qc_from_tag(ap, link->active_tag);
3393         if (qc->dev != dev || (qc->tf.command != ATA_CMD_FLUSH_EXT &&
3394                                qc->tf.command != ATA_CMD_FLUSH))
3395                 return 0;
3396
3397         /* if the device failed it, it should be reported to upper layers */
3398         if (qc->err_mask & AC_ERR_DEV)
3399                 return 0;
3400
3401         /* flush failed for some other reason, give it another shot */
3402         ata_tf_init(dev, &tf);
3403
3404         tf.command = qc->tf.command;
3405         tf.flags |= ATA_TFLAG_DEVICE;
3406         tf.protocol = ATA_PROT_NODATA;
3407
3408         ata_dev_warn(dev, "retrying FLUSH 0x%x Emask 0x%x\n",
3409                        tf.command, qc->err_mask);
3410
3411         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
3412         if (!err_mask) {
3413                 /*
3414                  * FLUSH is complete but there's no way to
3415                  * successfully complete a failed command from EH.
3416                  * Making sure retry is allowed at least once and
3417                  * retrying it should do the trick - whatever was in
3418                  * the cache is already on the platter and this won't
3419                  * cause infinite loop.
3420                  */
3421                 qc->scsicmd->allowed = max(qc->scsicmd->allowed, 1);
3422         } else {
3423                 ata_dev_warn(dev, "FLUSH failed Emask 0x%x\n",
3424                                err_mask);
3425                 rc = -EIO;
3426
3427                 /* if device failed it, report it to upper layers */
3428                 if (err_mask & AC_ERR_DEV) {
3429                         qc->err_mask |= AC_ERR_DEV;
3430                         qc->result_tf = tf;
3431                         if (!(ap->pflags & ATA_PFLAG_FROZEN))
3432                                 rc = 0;
3433                 }
3434         }
3435         return rc;
3436 }
3437
3438 /**
3439  *      ata_eh_set_lpm - configure SATA interface power management
3440  *      @link: link to configure power management
3441  *      @policy: the link power management policy
3442  *      @r_failed_dev: out parameter for failed device
3443  *
3444  *      Enable SATA Interface power management.  This will enable
3445  *      Device Interface Power Management (DIPM) for min_power and
3446  *      medium_power_with_dipm policies, and then call driver specific
3447  *      callbacks for enabling Host Initiated Power management.
3448  *
3449  *      LOCKING:
3450  *      EH context.
3451  *
3452  *      RETURNS:
3453  *      0 on success, -errno on failure.
3454  */
3455 static int ata_eh_set_lpm(struct ata_link *link, enum ata_lpm_policy policy,
3456                           struct ata_device **r_failed_dev)
3457 {
3458         struct ata_port *ap = ata_is_host_link(link) ? link->ap : NULL;
3459         struct ata_eh_context *ehc = &link->eh_context;
3460         struct ata_device *dev, *link_dev = NULL, *lpm_dev = NULL;
3461         enum ata_lpm_policy old_policy = link->lpm_policy;
3462         bool no_dipm = link->ap->flags & ATA_FLAG_NO_DIPM;
3463         unsigned int hints = ATA_LPM_EMPTY | ATA_LPM_HIPM;
3464         unsigned int err_mask;
3465         int rc;
3466
3467         /* if the link or host doesn't do LPM, noop */
3468         if ((link->flags & ATA_LFLAG_NO_LPM) || (ap && !ap->ops->set_lpm))
3469                 return 0;
3470
3471         /*
3472          * DIPM is enabled only for MIN_POWER as some devices
3473          * misbehave when the host NACKs transition to SLUMBER.  Order
3474          * device and link configurations such that the host always
3475          * allows DIPM requests.
3476          */
3477         ata_for_each_dev(dev, link, ENABLED) {
3478                 bool hipm = ata_id_has_hipm(dev->id);
3479                 bool dipm = ata_id_has_dipm(dev->id) && !no_dipm;
3480
3481                 /* find the first enabled and LPM enabled devices */
3482                 if (!link_dev)
3483                         link_dev = dev;
3484
3485                 if (!lpm_dev && (hipm || dipm))
3486                         lpm_dev = dev;
3487
3488                 hints &= ~ATA_LPM_EMPTY;
3489                 if (!hipm)
3490                         hints &= ~ATA_LPM_HIPM;
3491
3492                 /* disable DIPM before changing link config */
3493                 if (policy < ATA_LPM_MED_POWER_WITH_DIPM && dipm) {
3494                         err_mask = ata_dev_set_feature(dev,
3495                                         SETFEATURES_SATA_DISABLE, SATA_DIPM);
3496                         if (err_mask && err_mask != AC_ERR_DEV) {
3497                                 ata_dev_warn(dev,
3498                                              "failed to disable DIPM, Emask 0x%x\n",
3499                                              err_mask);
3500                                 rc = -EIO;
3501                                 goto fail;
3502                         }
3503                 }
3504         }
3505
3506         if (ap) {
3507                 rc = ap->ops->set_lpm(link, policy, hints);
3508                 if (!rc && ap->slave_link)
3509                         rc = ap->ops->set_lpm(ap->slave_link, policy, hints);
3510         } else
3511                 rc = sata_pmp_set_lpm(link, policy, hints);
3512
3513         /*
3514          * Attribute link config failure to the first (LPM) enabled
3515          * device on the link.
3516          */
3517         if (rc) {
3518                 if (rc == -EOPNOTSUPP) {
3519                         link->flags |= ATA_LFLAG_NO_LPM;
3520                         return 0;
3521                 }
3522                 dev = lpm_dev ? lpm_dev : link_dev;
3523                 goto fail;
3524         }
3525
3526         /*
3527          * Low level driver acked the transition.  Issue DIPM command
3528          * with the new policy set.
3529          */
3530         link->lpm_policy = policy;
3531         if (ap && ap->slave_link)
3532                 ap->slave_link->lpm_policy = policy;
3533
3534         /* host config updated, enable DIPM if transitioning to MIN_POWER */
3535         ata_for_each_dev(dev, link, ENABLED) {
3536                 if (policy >= ATA_LPM_MED_POWER_WITH_DIPM && !no_dipm &&
3537                     ata_id_has_dipm(dev->id)) {
3538                         err_mask = ata_dev_set_feature(dev,
3539                                         SETFEATURES_SATA_ENABLE, SATA_DIPM);
3540                         if (err_mask && err_mask != AC_ERR_DEV) {
3541                                 ata_dev_warn(dev,
3542                                         "failed to enable DIPM, Emask 0x%x\n",
3543                                         err_mask);
3544                                 rc = -EIO;
3545                                 goto fail;
3546                         }
3547                 }
3548         }
3549
3550         link->last_lpm_change = jiffies;
3551         link->flags |= ATA_LFLAG_CHANGED;
3552
3553         return 0;
3554
3555 fail:
3556         /* restore the old policy */
3557         link->lpm_policy = old_policy;
3558         if (ap && ap->slave_link)
3559                 ap->slave_link->lpm_policy = old_policy;
3560
3561         /* if no device or only one more chance is left, disable LPM */
3562         if (!dev || ehc->tries[dev->devno] <= 2) {
3563                 ata_link_warn(link, "disabling LPM on the link\n");
3564                 link->flags |= ATA_LFLAG_NO_LPM;
3565         }
3566         if (r_failed_dev)
3567                 *r_failed_dev = dev;
3568         return rc;
3569 }
3570
3571 int ata_link_nr_enabled(struct ata_link *link)
3572 {
3573         struct ata_device *dev;
3574         int cnt = 0;
3575
3576         ata_for_each_dev(dev, link, ENABLED)
3577                 cnt++;
3578         return cnt;
3579 }
3580
3581 static int ata_link_nr_vacant(struct ata_link *link)
3582 {
3583         struct ata_device *dev;
3584         int cnt = 0;
3585
3586         ata_for_each_dev(dev, link, ALL)
3587                 if (dev->class == ATA_DEV_UNKNOWN)
3588                         cnt++;
3589         return cnt;
3590 }
3591
3592 static int ata_eh_skip_recovery(struct ata_link *link)
3593 {
3594         struct ata_port *ap = link->ap;
3595         struct ata_eh_context *ehc = &link->eh_context;
3596         struct ata_device *dev;
3597
3598         /* skip disabled links */
3599         if (link->flags & ATA_LFLAG_DISABLED)
3600                 return 1;
3601
3602         /* skip if explicitly requested */
3603         if (ehc->i.flags & ATA_EHI_NO_RECOVERY)
3604                 return 1;
3605
3606         /* thaw frozen port and recover failed devices */
3607         if ((ap->pflags & ATA_PFLAG_FROZEN) || ata_link_nr_enabled(link))
3608                 return 0;
3609
3610         /* reset at least once if reset is requested */
3611         if ((ehc->i.action & ATA_EH_RESET) &&
3612             !(ehc->i.flags & ATA_EHI_DID_RESET))
3613                 return 0;
3614
3615         /* skip if class codes for all vacant slots are ATA_DEV_NONE */
3616         ata_for_each_dev(dev, link, ALL) {
3617                 if (dev->class == ATA_DEV_UNKNOWN &&
3618                     ehc->classes[dev->devno] != ATA_DEV_NONE)
3619                         return 0;
3620         }
3621
3622         return 1;
3623 }
3624
3625 static int ata_count_probe_trials_cb(struct ata_ering_entry *ent, void *void_arg)
3626 {
3627         u64 interval = msecs_to_jiffies(ATA_EH_PROBE_TRIAL_INTERVAL);
3628         u64 now = get_jiffies_64();
3629         int *trials = void_arg;
3630
3631         if ((ent->eflags & ATA_EFLAG_OLD_ER) ||
3632             (ent->timestamp < now - min(now, interval)))
3633                 return -1;
3634
3635         (*trials)++;
3636         return 0;
3637 }
3638
3639 static int ata_eh_schedule_probe(struct ata_device *dev)
3640 {
3641         struct ata_eh_context *ehc = &dev->link->eh_context;
3642         struct ata_link *link = ata_dev_phys_link(dev);
3643         int trials = 0;
3644
3645         if (!(ehc->i.probe_mask & (1 << dev->devno)) ||
3646             (ehc->did_probe_mask & (1 << dev->devno)))
3647                 return 0;
3648
3649         ata_eh_detach_dev(dev);
3650         ata_dev_init(dev);
3651         ehc->did_probe_mask |= (1 << dev->devno);
3652         ehc->i.action |= ATA_EH_RESET;
3653         ehc->saved_xfer_mode[dev->devno] = 0;
3654         ehc->saved_ncq_enabled &= ~(1 << dev->devno);
3655
3656         /* the link maybe in a deep sleep, wake it up */
3657         if (link->lpm_policy > ATA_LPM_MAX_POWER) {
3658                 if (ata_is_host_link(link))
3659                         link->ap->ops->set_lpm(link, ATA_LPM_MAX_POWER,
3660                                                ATA_LPM_EMPTY);
3661                 else
3662                         sata_pmp_set_lpm(link, ATA_LPM_MAX_POWER,
3663                                          ATA_LPM_EMPTY);
3664         }
3665
3666         /* Record and count probe trials on the ering.  The specific
3667          * error mask used is irrelevant.  Because a successful device
3668          * detection clears the ering, this count accumulates only if
3669          * there are consecutive failed probes.
3670          *
3671          * If the count is equal to or higher than ATA_EH_PROBE_TRIALS
3672          * in the last ATA_EH_PROBE_TRIAL_INTERVAL, link speed is
3673          * forced to 1.5Gbps.
3674          *
3675          * This is to work around cases where failed link speed
3676          * negotiation results in device misdetection leading to
3677          * infinite DEVXCHG or PHRDY CHG events.
3678          */
3679         ata_ering_record(&dev->ering, 0, AC_ERR_OTHER);
3680         ata_ering_map(&dev->ering, ata_count_probe_trials_cb, &trials);
3681
3682         if (trials > ATA_EH_PROBE_TRIALS)
3683                 sata_down_spd_limit(link, 1);
3684
3685         return 1;
3686 }
3687
3688 static int ata_eh_handle_dev_fail(struct ata_device *dev, int err)
3689 {
3690         struct ata_eh_context *ehc = &dev->link->eh_context;
3691
3692         /* -EAGAIN from EH routine indicates retry without prejudice.
3693          * The requester is responsible for ensuring forward progress.
3694          */
3695         if (err != -EAGAIN)
3696                 ehc->tries[dev->devno]--;
3697
3698         switch (err) {
3699         case -ENODEV:
3700                 /* device missing or wrong IDENTIFY data, schedule probing */
3701                 ehc->i.probe_mask |= (1 << dev->devno);
3702                 /* fall through */
3703         case -EINVAL:
3704                 /* give it just one more chance */
3705                 ehc->tries[dev->devno] = min(ehc->tries[dev->devno], 1);
3706                 /* fall through */
3707         case -EIO:
3708                 if (ehc->tries[dev->devno] == 1) {
3709                         /* This is the last chance, better to slow
3710                          * down than lose it.
3711                          */
3712                         sata_down_spd_limit(ata_dev_phys_link(dev), 0);
3713                         if (dev->pio_mode > XFER_PIO_0)
3714                                 ata_down_xfermask_limit(dev, ATA_DNXFER_PIO);
3715                 }
3716         }
3717
3718         if (ata_dev_enabled(dev) && !ehc->tries[dev->devno]) {
3719                 /* disable device if it has used up all its chances */
3720                 ata_dev_disable(dev);
3721
3722                 /* detach if offline */
3723                 if (ata_phys_link_offline(ata_dev_phys_link(dev)))
3724                         ata_eh_detach_dev(dev);
3725
3726                 /* schedule probe if necessary */
3727                 if (ata_eh_schedule_probe(dev)) {
3728                         ehc->tries[dev->devno] = ATA_EH_DEV_TRIES;
3729                         memset(ehc->cmd_timeout_idx[dev->devno], 0,
3730                                sizeof(ehc->cmd_timeout_idx[dev->devno]));
3731                 }
3732
3733                 return 1;
3734         } else {
3735                 ehc->i.action |= ATA_EH_RESET;
3736                 return 0;
3737         }
3738 }
3739
3740 /**
3741  *      ata_eh_recover - recover host port after error
3742  *      @ap: host port to recover
3743  *      @prereset: prereset method (can be NULL)
3744  *      @softreset: softreset method (can be NULL)
3745  *      @hardreset: hardreset method (can be NULL)
3746  *      @postreset: postreset method (can be NULL)
3747  *      @r_failed_link: out parameter for failed link
3748  *
3749  *      This is the alpha and omega, eum and yang, heart and soul of
3750  *      libata exception handling.  On entry, actions required to
3751  *      recover each link and hotplug requests are recorded in the
3752  *      link's eh_context.  This function executes all the operations
3753  *      with appropriate retrials and fallbacks to resurrect failed
3754  *      devices, detach goners and greet newcomers.
3755  *
3756  *      LOCKING:
3757  *      Kernel thread context (may sleep).
3758  *
3759  *      RETURNS:
3760  *      0 on success, -errno on failure.
3761  */
3762 int ata_eh_recover(struct ata_port *ap, ata_prereset_fn_t prereset,
3763                    ata_reset_fn_t softreset, ata_reset_fn_t hardreset,
3764                    ata_postreset_fn_t postreset,
3765                    struct ata_link **r_failed_link)
3766 {
3767         struct ata_link *link;
3768         struct ata_device *dev;
3769         int rc, nr_fails;
3770         unsigned long flags, deadline;
3771
3772         DPRINTK("ENTER\n");
3773
3774         /* prep for recovery */
3775         ata_for_each_link(link, ap, EDGE) {
3776                 struct ata_eh_context *ehc = &link->eh_context;
3777
3778                 /* re-enable link? */
3779                 if (ehc->i.action & ATA_EH_ENABLE_LINK) {
3780                         ata_eh_about_to_do(link, NULL, ATA_EH_ENABLE_LINK);
3781                         spin_lock_irqsave(ap->lock, flags);
3782                         link->flags &= ~ATA_LFLAG_DISABLED;
3783                         spin_unlock_irqrestore(ap->lock, flags);
3784                         ata_eh_done(link, NULL, ATA_EH_ENABLE_LINK);
3785                 }
3786
3787                 ata_for_each_dev(dev, link, ALL) {
3788                         if (link->flags & ATA_LFLAG_NO_RETRY)
3789                                 ehc->tries[dev->devno] = 1;
3790                         else
3791                                 ehc->tries[dev->devno] = ATA_EH_DEV_TRIES;
3792
3793                         /* collect port action mask recorded in dev actions */
3794                         ehc->i.action |= ehc->i.dev_action[dev->devno] &
3795                                          ~ATA_EH_PERDEV_MASK;
3796                         ehc->i.dev_action[dev->devno] &= ATA_EH_PERDEV_MASK;
3797
3798                         /* process hotplug request */
3799                         if (dev->flags & ATA_DFLAG_DETACH)
3800                                 ata_eh_detach_dev(dev);
3801
3802                         /* schedule probe if necessary */
3803                         if (!ata_dev_enabled(dev))
3804                                 ata_eh_schedule_probe(dev);
3805                 }
3806         }
3807
3808  retry:
3809         rc = 0;
3810
3811         /* if UNLOADING, finish immediately */
3812         if (ap->pflags & ATA_PFLAG_UNLOADING)
3813                 goto out;
3814
3815         /* prep for EH */
3816         ata_for_each_link(link, ap, EDGE) {
3817                 struct ata_eh_context *ehc = &link->eh_context;
3818
3819                 /* skip EH if possible. */
3820                 if (ata_eh_skip_recovery(link))
3821                         ehc->i.action = 0;
3822
3823                 ata_for_each_dev(dev, link, ALL)
3824                         ehc->classes[dev->devno] = ATA_DEV_UNKNOWN;
3825         }
3826
3827         /* reset */
3828         ata_for_each_link(link, ap, EDGE) {
3829                 struct ata_eh_context *ehc = &link->eh_context;
3830
3831                 if (!(ehc->i.action & ATA_EH_RESET))
3832                         continue;
3833
3834                 rc = ata_eh_reset(link, ata_link_nr_vacant(link),
3835                                   prereset, softreset, hardreset, postreset);
3836                 if (rc) {
3837                         ata_link_err(link, "reset failed, giving up\n");
3838                         goto out;
3839                 }
3840         }
3841
3842         do {
3843                 unsigned long now;
3844
3845                 /*
3846                  * clears ATA_EH_PARK in eh_info and resets
3847                  * ap->park_req_pending
3848                  */
3849                 ata_eh_pull_park_action(ap);
3850
3851                 deadline = jiffies;
3852                 ata_for_each_link(link, ap, EDGE) {
3853                         ata_for_each_dev(dev, link, ALL) {
3854                                 struct ata_eh_context *ehc = &link->eh_context;
3855                                 unsigned long tmp;
3856
3857                                 if (dev->class != ATA_DEV_ATA &&
3858                                     dev->class != ATA_DEV_ZAC)
3859                                         continue;
3860                                 if (!(ehc->i.dev_action[dev->devno] &
3861                                       ATA_EH_PARK))
3862                                         continue;
3863                                 tmp = dev->unpark_deadline;
3864                                 if (time_before(deadline, tmp))
3865                                         deadline = tmp;
3866                                 else if (time_before_eq(tmp, jiffies))
3867                                         continue;
3868                                 if (ehc->unloaded_mask & (1 << dev->devno))
3869                                         continue;
3870
3871                                 ata_eh_park_issue_cmd(dev, 1);
3872                         }
3873                 }
3874
3875                 now = jiffies;
3876                 if (time_before_eq(deadline, now))
3877                         break;
3878
3879                 ata_eh_release(ap);
3880                 deadline = wait_for_completion_timeout(&ap->park_req_pending,
3881                                                        deadline - now);
3882                 ata_eh_acquire(ap);
3883         } while (deadline);
3884         ata_for_each_link(link, ap, EDGE) {
3885                 ata_for_each_dev(dev, link, ALL) {
3886                         if (!(link->eh_context.unloaded_mask &
3887                               (1 << dev->devno)))
3888                                 continue;
3889
3890                         ata_eh_park_issue_cmd(dev, 0);
3891                         ata_eh_done(link, dev, ATA_EH_PARK);
3892                 }
3893         }
3894
3895         /* the rest */
3896         nr_fails = 0;
3897         ata_for_each_link(link, ap, PMP_FIRST) {
3898                 struct ata_eh_context *ehc = &link->eh_context;
3899
3900                 if (sata_pmp_attached(ap) && ata_is_host_link(link))
3901                         goto config_lpm;
3902
3903                 /* revalidate existing devices and attach new ones */
3904                 rc = ata_eh_revalidate_and_attach(link, &dev);
3905                 if (rc)
3906                         goto rest_fail;
3907
3908                 /* if PMP got attached, return, pmp EH will take care of it */
3909                 if (link->device->class == ATA_DEV_PMP) {
3910                         ehc->i.action = 0;
3911                         return 0;
3912                 }
3913
3914                 /* configure transfer mode if necessary */
3915                 if (ehc->i.flags & ATA_EHI_SETMODE) {
3916                         rc = ata_set_mode(link, &dev);
3917                         if (rc)
3918                                 goto rest_fail;
3919                         ehc->i.flags &= ~ATA_EHI_SETMODE;
3920                 }
3921
3922                 /* If reset has been issued, clear UA to avoid
3923                  * disrupting the current users of the device.
3924                  */
3925                 if (ehc->i.flags & ATA_EHI_DID_RESET) {
3926                         ata_for_each_dev(dev, link, ALL) {
3927                                 if (dev->class != ATA_DEV_ATAPI)
3928                                         continue;
3929                                 rc = atapi_eh_clear_ua(dev);
3930                                 if (rc)
3931                                         goto rest_fail;
3932                                 if (zpodd_dev_enabled(dev))
3933                                         zpodd_post_poweron(dev);
3934                         }
3935                 }
3936
3937                 /* retry flush if necessary */
3938                 ata_for_each_dev(dev, link, ALL) {
3939                         if (dev->class != ATA_DEV_ATA &&
3940                             dev->class != ATA_DEV_ZAC)
3941                                 continue;
3942                         rc = ata_eh_maybe_retry_flush(dev);
3943                         if (rc)
3944                                 goto rest_fail;
3945                 }
3946
3947         config_lpm:
3948                 /* configure link power saving */
3949                 if (link->lpm_policy != ap->target_lpm_policy) {
3950                         rc = ata_eh_set_lpm(link, ap->target_lpm_policy, &dev);
3951                         if (rc)
3952                                 goto rest_fail;
3953                 }
3954
3955                 /* this link is okay now */
3956                 ehc->i.flags = 0;
3957                 continue;
3958
3959         rest_fail:
3960                 nr_fails++;
3961                 if (dev)
3962                         ata_eh_handle_dev_fail(dev, rc);
3963
3964                 if (ap->pflags & ATA_PFLAG_FROZEN) {
3965                         /* PMP reset requires working host port.
3966                          * Can't retry if it's frozen.
3967                          */
3968                         if (sata_pmp_attached(ap))
3969                                 goto out;
3970                         break;
3971                 }
3972         }
3973
3974         if (nr_fails)
3975                 goto retry;
3976
3977  out:
3978         if (rc && r_failed_link)
3979                 *r_failed_link = link;
3980
3981         DPRINTK("EXIT, rc=%d\n", rc);
3982         return rc;
3983 }
3984
3985 /**
3986  *      ata_eh_finish - finish up EH
3987  *      @ap: host port to finish EH for
3988  *
3989  *      Recovery is complete.  Clean up EH states and retry or finish
3990  *      failed qcs.
3991  *
3992  *      LOCKING:
3993  *      None.
3994  */
3995 void ata_eh_finish(struct ata_port *ap)
3996 {
3997         struct ata_queued_cmd *qc;
3998         int tag;
3999
4000         /* retry or finish qcs */
4001         ata_qc_for_each_raw(ap, qc, tag) {
4002                 if (!(qc->flags & ATA_QCFLAG_FAILED))
4003                         continue;
4004
4005                 if (qc->err_mask) {
4006                         /* FIXME: Once EH migration is complete,
4007                          * generate sense data in this function,
4008                          * considering both err_mask and tf.
4009                          */
4010                         if (qc->flags & ATA_QCFLAG_RETRY)
4011                                 ata_eh_qc_retry(qc);
4012                         else
4013                                 ata_eh_qc_complete(qc);
4014                 } else {
4015                         if (qc->flags & ATA_QCFLAG_SENSE_VALID) {
4016                                 ata_eh_qc_complete(qc);
4017                         } else {
4018                                 /* feed zero TF to sense generation */
4019                                 memset(&qc->result_tf, 0, sizeof(qc->result_tf));
4020                                 ata_eh_qc_retry(qc);
4021                         }
4022                 }
4023         }
4024
4025         /* make sure nr_active_links is zero after EH */
4026         WARN_ON(ap->nr_active_links);
4027         ap->nr_active_links = 0;
4028 }
4029
4030 /**
4031  *      ata_do_eh - do standard error handling
4032  *      @ap: host port to handle error for
4033  *
4034  *      @prereset: prereset method (can be NULL)
4035  *      @softreset: softreset method (can be NULL)
4036  *      @hardreset: hardreset method (can be NULL)
4037  *      @postreset: postreset method (can be NULL)
4038  *
4039  *      Perform standard error handling sequence.
4040  *
4041  *      LOCKING:
4042  *      Kernel thread context (may sleep).
4043  */
4044 void ata_do_eh(struct ata_port *ap, ata_prereset_fn_t prereset,
4045                ata_reset_fn_t softreset, ata_reset_fn_t hardreset,
4046                ata_postreset_fn_t postreset)
4047 {
4048         struct ata_device *dev;
4049         int rc;
4050
4051         ata_eh_autopsy(ap);
4052         ata_eh_report(ap);
4053
4054         rc = ata_eh_recover(ap, prereset, softreset, hardreset, postreset,
4055                             NULL);
4056         if (rc) {
4057                 ata_for_each_dev(dev, &ap->link, ALL)
4058                         ata_dev_disable(dev);
4059         }
4060
4061         ata_eh_finish(ap);
4062 }
4063
4064 /**
4065  *      ata_std_error_handler - standard error handler
4066  *      @ap: host port to handle error for
4067  *
4068  *      Standard error handler
4069  *
4070  *      LOCKING:
4071  *      Kernel thread context (may sleep).
4072  */
4073 void ata_std_error_handler(struct ata_port *ap)
4074 {
4075         struct ata_port_operations *ops = ap->ops;
4076         ata_reset_fn_t hardreset = ops->hardreset;
4077
4078         /* ignore built-in hardreset if SCR access is not available */
4079         if (hardreset == sata_std_hardreset && !sata_scr_valid(&ap->link))
4080                 hardreset = NULL;
4081
4082         ata_do_eh(ap, ops->prereset, ops->softreset, hardreset, ops->postreset);
4083 }
4084
4085 #ifdef CONFIG_PM
4086 /**
4087  *      ata_eh_handle_port_suspend - perform port suspend operation
4088  *      @ap: port to suspend
4089  *
4090  *      Suspend @ap.
4091  *
4092  *      LOCKING:
4093  *      Kernel thread context (may sleep).
4094  */
4095 static void ata_eh_handle_port_suspend(struct ata_port *ap)
4096 {
4097         unsigned long flags;
4098         int rc = 0;
4099         struct ata_device *dev;
4100
4101         /* are we suspending? */
4102         spin_lock_irqsave(ap->lock, flags);
4103         if (!(ap->pflags & ATA_PFLAG_PM_PENDING) ||
4104             ap->pm_mesg.event & PM_EVENT_RESUME) {
4105                 spin_unlock_irqrestore(ap->lock, flags);
4106                 return;
4107         }
4108         spin_unlock_irqrestore(ap->lock, flags);
4109
4110         WARN_ON(ap->pflags & ATA_PFLAG_SUSPENDED);
4111
4112         /*
4113          * If we have a ZPODD attached, check its zero
4114          * power ready status before the port is frozen.
4115          * Only needed for runtime suspend.
4116          */
4117         if (PMSG_IS_AUTO(ap->pm_mesg)) {
4118                 ata_for_each_dev(dev, &ap->link, ENABLED) {
4119                         if (zpodd_dev_enabled(dev))
4120                                 zpodd_on_suspend(dev);
4121                 }
4122         }
4123
4124         /* tell ACPI we're suspending */
4125         rc = ata_acpi_on_suspend(ap);
4126         if (rc)
4127                 goto out;
4128
4129         /* suspend */
4130         ata_eh_freeze_port(ap);
4131
4132         if (ap->ops->port_suspend)
4133                 rc = ap->ops->port_suspend(ap, ap->pm_mesg);
4134
4135         ata_acpi_set_state(ap, ap->pm_mesg);
4136  out:
4137         /* update the flags */
4138         spin_lock_irqsave(ap->lock, flags);
4139
4140         ap->pflags &= ~ATA_PFLAG_PM_PENDING;
4141         if (rc == 0)
4142                 ap->pflags |= ATA_PFLAG_SUSPENDED;
4143         else if (ap->pflags & ATA_PFLAG_FROZEN)
4144                 ata_port_schedule_eh(ap);
4145
4146         spin_unlock_irqrestore(ap->lock, flags);
4147
4148         return;
4149 }
4150
4151 /**
4152  *      ata_eh_handle_port_resume - perform port resume operation
4153  *      @ap: port to resume
4154  *
4155  *      Resume @ap.
4156  *
4157  *      LOCKING:
4158  *      Kernel thread context (may sleep).
4159  */
4160 static void ata_eh_handle_port_resume(struct ata_port *ap)
4161 {
4162         struct ata_link *link;
4163         struct ata_device *dev;
4164         unsigned long flags;
4165
4166         /* are we resuming? */
4167         spin_lock_irqsave(ap->lock, flags);
4168         if (!(ap->pflags & ATA_PFLAG_PM_PENDING) ||
4169             !(ap->pm_mesg.event & PM_EVENT_RESUME)) {
4170                 spin_unlock_irqrestore(ap->lock, flags);
4171                 return;
4172         }
4173         spin_unlock_irqrestore(ap->lock, flags);
4174
4175         WARN_ON(!(ap->pflags & ATA_PFLAG_SUSPENDED));
4176
4177         /*
4178          * Error timestamps are in jiffies which doesn't run while
4179          * suspended and PHY events during resume isn't too uncommon.
4180          * When the two are combined, it can lead to unnecessary speed
4181          * downs if the machine is suspended and resumed repeatedly.
4182          * Clear error history.
4183          */
4184         ata_for_each_link(link, ap, HOST_FIRST)
4185                 ata_for_each_dev(dev, link, ALL)
4186                         ata_ering_clear(&dev->ering);
4187
4188         ata_acpi_set_state(ap, ap->pm_mesg);
4189
4190         if (ap->ops->port_resume)
4191                 ap->ops->port_resume(ap);
4192
4193         /* tell ACPI that we're resuming */
4194         ata_acpi_on_resume(ap);
4195
4196         /* update the flags */
4197         spin_lock_irqsave(ap->lock, flags);
4198         ap->pflags &= ~(ATA_PFLAG_PM_PENDING | ATA_PFLAG_SUSPENDED);
4199         spin_unlock_irqrestore(ap->lock, flags);
4200 }
4201 #endif /* CONFIG_PM */