libata-eh: clear UNIT ATTENTION after reset
[safe/jmp/linux-2.6] / drivers / ata / libata-eh.c
1 /*
2  *  libata-eh.c - libata error handling
3  *
4  *  Maintained by:  Jeff Garzik <jgarzik@pobox.com>
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/DocBook/libata.*
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/pci.h>
37 #include <scsi/scsi.h>
38 #include <scsi/scsi_host.h>
39 #include <scsi/scsi_eh.h>
40 #include <scsi/scsi_device.h>
41 #include <scsi/scsi_cmnd.h>
42 #include "../scsi/scsi_transport_api.h"
43
44 #include <linux/libata.h>
45
46 #include "libata.h"
47
48 enum {
49         /* speed down verdicts */
50         ATA_EH_SPDN_NCQ_OFF             = (1 << 0),
51         ATA_EH_SPDN_SPEED_DOWN          = (1 << 1),
52         ATA_EH_SPDN_FALLBACK_TO_PIO     = (1 << 2),
53         ATA_EH_SPDN_KEEP_ERRORS         = (1 << 3),
54
55         /* error flags */
56         ATA_EFLAG_IS_IO                 = (1 << 0),
57         ATA_EFLAG_DUBIOUS_XFER          = (1 << 1),
58
59         /* error categories */
60         ATA_ECAT_NONE                   = 0,
61         ATA_ECAT_ATA_BUS                = 1,
62         ATA_ECAT_TOUT_HSM               = 2,
63         ATA_ECAT_UNK_DEV                = 3,
64         ATA_ECAT_DUBIOUS_NONE           = 4,
65         ATA_ECAT_DUBIOUS_ATA_BUS        = 5,
66         ATA_ECAT_DUBIOUS_TOUT_HSM       = 6,
67         ATA_ECAT_DUBIOUS_UNK_DEV        = 7,
68         ATA_ECAT_NR                     = 8,
69
70         ATA_EH_CMD_DFL_TIMEOUT          =  5000,
71
72         /* always put at least this amount of time between resets */
73         ATA_EH_RESET_COOL_DOWN          =  5000,
74
75         /* Waiting in ->prereset can never be reliable.  It's
76          * sometimes nice to wait there but it can't be depended upon;
77          * otherwise, we wouldn't be resetting.  Just give it enough
78          * time for most drives to spin up.
79          */
80         ATA_EH_PRERESET_TIMEOUT         = 10000,
81         ATA_EH_FASTDRAIN_INTERVAL       =  3000,
82
83         ATA_EH_UA_TRIES                 = 5,
84 };
85
86 /* The following table determines how we sequence resets.  Each entry
87  * represents timeout for that try.  The first try can be soft or
88  * hardreset.  All others are hardreset if available.  In most cases
89  * the first reset w/ 10sec timeout should succeed.  Following entries
90  * are mostly for error handling, hotplug and retarded devices.
91  */
92 static const unsigned long ata_eh_reset_timeouts[] = {
93         10000,  /* most drives spin up by 10sec */
94         10000,  /* > 99% working drives spin up before 20sec */
95         35000,  /* give > 30 secs of idleness for retarded devices */
96          5000,  /* and sweet one last chance */
97         ULONG_MAX, /* > 1 min has elapsed, give up */
98 };
99
100 static const unsigned long ata_eh_identify_timeouts[] = {
101          5000,  /* covers > 99% of successes and not too boring on failures */
102         10000,  /* combined time till here is enough even for media access */
103         30000,  /* for true idiots */
104         ULONG_MAX,
105 };
106
107 static const unsigned long ata_eh_other_timeouts[] = {
108          5000,  /* same rationale as identify timeout */
109         10000,  /* ditto */
110         /* but no merciful 30sec for other commands, it just isn't worth it */
111         ULONG_MAX,
112 };
113
114 struct ata_eh_cmd_timeout_ent {
115         const u8                *commands;
116         const unsigned long     *timeouts;
117 };
118
119 /* The following table determines timeouts to use for EH internal
120  * commands.  Each table entry is a command class and matches the
121  * commands the entry applies to and the timeout table to use.
122  *
123  * On the retry after a command timed out, the next timeout value from
124  * the table is used.  If the table doesn't contain further entries,
125  * the last value is used.
126  *
127  * ehc->cmd_timeout_idx keeps track of which timeout to use per
128  * command class, so if SET_FEATURES times out on the first try, the
129  * next try will use the second timeout value only for that class.
130  */
131 #define CMDS(cmds...)   (const u8 []){ cmds, 0 }
132 static const struct ata_eh_cmd_timeout_ent
133 ata_eh_cmd_timeout_table[ATA_EH_CMD_TIMEOUT_TABLE_SIZE] = {
134         { .commands = CMDS(ATA_CMD_ID_ATA, ATA_CMD_ID_ATAPI),
135           .timeouts = ata_eh_identify_timeouts, },
136         { .commands = CMDS(ATA_CMD_READ_NATIVE_MAX, ATA_CMD_READ_NATIVE_MAX_EXT),
137           .timeouts = ata_eh_other_timeouts, },
138         { .commands = CMDS(ATA_CMD_SET_MAX, ATA_CMD_SET_MAX_EXT),
139           .timeouts = ata_eh_other_timeouts, },
140         { .commands = CMDS(ATA_CMD_SET_FEATURES),
141           .timeouts = ata_eh_other_timeouts, },
142         { .commands = CMDS(ATA_CMD_INIT_DEV_PARAMS),
143           .timeouts = ata_eh_other_timeouts, },
144 };
145 #undef CMDS
146
147 static void __ata_port_freeze(struct ata_port *ap);
148 #ifdef CONFIG_PM
149 static void ata_eh_handle_port_suspend(struct ata_port *ap);
150 static void ata_eh_handle_port_resume(struct ata_port *ap);
151 #else /* CONFIG_PM */
152 static void ata_eh_handle_port_suspend(struct ata_port *ap)
153 { }
154
155 static void ata_eh_handle_port_resume(struct ata_port *ap)
156 { }
157 #endif /* CONFIG_PM */
158
159 static void __ata_ehi_pushv_desc(struct ata_eh_info *ehi, const char *fmt,
160                                  va_list args)
161 {
162         ehi->desc_len += vscnprintf(ehi->desc + ehi->desc_len,
163                                      ATA_EH_DESC_LEN - ehi->desc_len,
164                                      fmt, args);
165 }
166
167 /**
168  *      __ata_ehi_push_desc - push error description without adding separator
169  *      @ehi: target EHI
170  *      @fmt: printf format string
171  *
172  *      Format string according to @fmt and append it to @ehi->desc.
173  *
174  *      LOCKING:
175  *      spin_lock_irqsave(host lock)
176  */
177 void __ata_ehi_push_desc(struct ata_eh_info *ehi, const char *fmt, ...)
178 {
179         va_list args;
180
181         va_start(args, fmt);
182         __ata_ehi_pushv_desc(ehi, fmt, args);
183         va_end(args);
184 }
185
186 /**
187  *      ata_ehi_push_desc - push error description with separator
188  *      @ehi: target EHI
189  *      @fmt: printf format string
190  *
191  *      Format string according to @fmt and append it to @ehi->desc.
192  *      If @ehi->desc is not empty, ", " is added in-between.
193  *
194  *      LOCKING:
195  *      spin_lock_irqsave(host lock)
196  */
197 void ata_ehi_push_desc(struct ata_eh_info *ehi, const char *fmt, ...)
198 {
199         va_list args;
200
201         if (ehi->desc_len)
202                 __ata_ehi_push_desc(ehi, ", ");
203
204         va_start(args, fmt);
205         __ata_ehi_pushv_desc(ehi, fmt, args);
206         va_end(args);
207 }
208
209 /**
210  *      ata_ehi_clear_desc - clean error description
211  *      @ehi: target EHI
212  *
213  *      Clear @ehi->desc.
214  *
215  *      LOCKING:
216  *      spin_lock_irqsave(host lock)
217  */
218 void ata_ehi_clear_desc(struct ata_eh_info *ehi)
219 {
220         ehi->desc[0] = '\0';
221         ehi->desc_len = 0;
222 }
223
224 /**
225  *      ata_port_desc - append port description
226  *      @ap: target ATA port
227  *      @fmt: printf format string
228  *
229  *      Format string according to @fmt and append it to port
230  *      description.  If port description is not empty, " " is added
231  *      in-between.  This function is to be used while initializing
232  *      ata_host.  The description is printed on host registration.
233  *
234  *      LOCKING:
235  *      None.
236  */
237 void ata_port_desc(struct ata_port *ap, const char *fmt, ...)
238 {
239         va_list args;
240
241         WARN_ON(!(ap->pflags & ATA_PFLAG_INITIALIZING));
242
243         if (ap->link.eh_info.desc_len)
244                 __ata_ehi_push_desc(&ap->link.eh_info, " ");
245
246         va_start(args, fmt);
247         __ata_ehi_pushv_desc(&ap->link.eh_info, fmt, args);
248         va_end(args);
249 }
250
251 #ifdef CONFIG_PCI
252
253 /**
254  *      ata_port_pbar_desc - append PCI BAR description
255  *      @ap: target ATA port
256  *      @bar: target PCI BAR
257  *      @offset: offset into PCI BAR
258  *      @name: name of the area
259  *
260  *      If @offset is negative, this function formats a string which
261  *      contains the name, address, size and type of the BAR and
262  *      appends it to the port description.  If @offset is zero or
263  *      positive, only name and offsetted address is appended.
264  *
265  *      LOCKING:
266  *      None.
267  */
268 void ata_port_pbar_desc(struct ata_port *ap, int bar, ssize_t offset,
269                         const char *name)
270 {
271         struct pci_dev *pdev = to_pci_dev(ap->host->dev);
272         char *type = "";
273         unsigned long long start, len;
274
275         if (pci_resource_flags(pdev, bar) & IORESOURCE_MEM)
276                 type = "m";
277         else if (pci_resource_flags(pdev, bar) & IORESOURCE_IO)
278                 type = "i";
279
280         start = (unsigned long long)pci_resource_start(pdev, bar);
281         len = (unsigned long long)pci_resource_len(pdev, bar);
282
283         if (offset < 0)
284                 ata_port_desc(ap, "%s %s%llu@0x%llx", name, type, len, start);
285         else
286                 ata_port_desc(ap, "%s 0x%llx", name,
287                                 start + (unsigned long long)offset);
288 }
289
290 #endif /* CONFIG_PCI */
291
292 static int ata_lookup_timeout_table(u8 cmd)
293 {
294         int i;
295
296         for (i = 0; i < ATA_EH_CMD_TIMEOUT_TABLE_SIZE; i++) {
297                 const u8 *cur;
298
299                 for (cur = ata_eh_cmd_timeout_table[i].commands; *cur; cur++)
300                         if (*cur == cmd)
301                                 return i;
302         }
303
304         return -1;
305 }
306
307 /**
308  *      ata_internal_cmd_timeout - determine timeout for an internal command
309  *      @dev: target device
310  *      @cmd: internal command to be issued
311  *
312  *      Determine timeout for internal command @cmd for @dev.
313  *
314  *      LOCKING:
315  *      EH context.
316  *
317  *      RETURNS:
318  *      Determined timeout.
319  */
320 unsigned long ata_internal_cmd_timeout(struct ata_device *dev, u8 cmd)
321 {
322         struct ata_eh_context *ehc = &dev->link->eh_context;
323         int ent = ata_lookup_timeout_table(cmd);
324         int idx;
325
326         if (ent < 0)
327                 return ATA_EH_CMD_DFL_TIMEOUT;
328
329         idx = ehc->cmd_timeout_idx[dev->devno][ent];
330         return ata_eh_cmd_timeout_table[ent].timeouts[idx];
331 }
332
333 /**
334  *      ata_internal_cmd_timed_out - notification for internal command timeout
335  *      @dev: target device
336  *      @cmd: internal command which timed out
337  *
338  *      Notify EH that internal command @cmd for @dev timed out.  This
339  *      function should be called only for commands whose timeouts are
340  *      determined using ata_internal_cmd_timeout().
341  *
342  *      LOCKING:
343  *      EH context.
344  */
345 void ata_internal_cmd_timed_out(struct ata_device *dev, u8 cmd)
346 {
347         struct ata_eh_context *ehc = &dev->link->eh_context;
348         int ent = ata_lookup_timeout_table(cmd);
349         int idx;
350
351         if (ent < 0)
352                 return;
353
354         idx = ehc->cmd_timeout_idx[dev->devno][ent];
355         if (ata_eh_cmd_timeout_table[ent].timeouts[idx + 1] != ULONG_MAX)
356                 ehc->cmd_timeout_idx[dev->devno][ent]++;
357 }
358
359 static void ata_ering_record(struct ata_ering *ering, unsigned int eflags,
360                              unsigned int err_mask)
361 {
362         struct ata_ering_entry *ent;
363
364         WARN_ON(!err_mask);
365
366         ering->cursor++;
367         ering->cursor %= ATA_ERING_SIZE;
368
369         ent = &ering->ring[ering->cursor];
370         ent->eflags = eflags;
371         ent->err_mask = err_mask;
372         ent->timestamp = get_jiffies_64();
373 }
374
375 static struct ata_ering_entry *ata_ering_top(struct ata_ering *ering)
376 {
377         struct ata_ering_entry *ent = &ering->ring[ering->cursor];
378
379         if (ent->err_mask)
380                 return ent;
381         return NULL;
382 }
383
384 static void ata_ering_clear(struct ata_ering *ering)
385 {
386         memset(ering, 0, sizeof(*ering));
387 }
388
389 static int ata_ering_map(struct ata_ering *ering,
390                          int (*map_fn)(struct ata_ering_entry *, void *),
391                          void *arg)
392 {
393         int idx, rc = 0;
394         struct ata_ering_entry *ent;
395
396         idx = ering->cursor;
397         do {
398                 ent = &ering->ring[idx];
399                 if (!ent->err_mask)
400                         break;
401                 rc = map_fn(ent, arg);
402                 if (rc)
403                         break;
404                 idx = (idx - 1 + ATA_ERING_SIZE) % ATA_ERING_SIZE;
405         } while (idx != ering->cursor);
406
407         return rc;
408 }
409
410 static unsigned int ata_eh_dev_action(struct ata_device *dev)
411 {
412         struct ata_eh_context *ehc = &dev->link->eh_context;
413
414         return ehc->i.action | ehc->i.dev_action[dev->devno];
415 }
416
417 static void ata_eh_clear_action(struct ata_link *link, struct ata_device *dev,
418                                 struct ata_eh_info *ehi, unsigned int action)
419 {
420         struct ata_device *tdev;
421
422         if (!dev) {
423                 ehi->action &= ~action;
424                 ata_link_for_each_dev(tdev, link)
425                         ehi->dev_action[tdev->devno] &= ~action;
426         } else {
427                 /* doesn't make sense for port-wide EH actions */
428                 WARN_ON(!(action & ATA_EH_PERDEV_MASK));
429
430                 /* break ehi->action into ehi->dev_action */
431                 if (ehi->action & action) {
432                         ata_link_for_each_dev(tdev, link)
433                                 ehi->dev_action[tdev->devno] |=
434                                         ehi->action & action;
435                         ehi->action &= ~action;
436                 }
437
438                 /* turn off the specified per-dev action */
439                 ehi->dev_action[dev->devno] &= ~action;
440         }
441 }
442
443 /**
444  *      ata_scsi_timed_out - SCSI layer time out callback
445  *      @cmd: timed out SCSI command
446  *
447  *      Handles SCSI layer timeout.  We race with normal completion of
448  *      the qc for @cmd.  If the qc is already gone, we lose and let
449  *      the scsi command finish (EH_HANDLED).  Otherwise, the qc has
450  *      timed out and EH should be invoked.  Prevent ata_qc_complete()
451  *      from finishing it by setting EH_SCHEDULED and return
452  *      EH_NOT_HANDLED.
453  *
454  *      TODO: kill this function once old EH is gone.
455  *
456  *      LOCKING:
457  *      Called from timer context
458  *
459  *      RETURNS:
460  *      EH_HANDLED or EH_NOT_HANDLED
461  */
462 enum scsi_eh_timer_return ata_scsi_timed_out(struct scsi_cmnd *cmd)
463 {
464         struct Scsi_Host *host = cmd->device->host;
465         struct ata_port *ap = ata_shost_to_port(host);
466         unsigned long flags;
467         struct ata_queued_cmd *qc;
468         enum scsi_eh_timer_return ret;
469
470         DPRINTK("ENTER\n");
471
472         if (ap->ops->error_handler) {
473                 ret = EH_NOT_HANDLED;
474                 goto out;
475         }
476
477         ret = EH_HANDLED;
478         spin_lock_irqsave(ap->lock, flags);
479         qc = ata_qc_from_tag(ap, ap->link.active_tag);
480         if (qc) {
481                 WARN_ON(qc->scsicmd != cmd);
482                 qc->flags |= ATA_QCFLAG_EH_SCHEDULED;
483                 qc->err_mask |= AC_ERR_TIMEOUT;
484                 ret = EH_NOT_HANDLED;
485         }
486         spin_unlock_irqrestore(ap->lock, flags);
487
488  out:
489         DPRINTK("EXIT, ret=%d\n", ret);
490         return ret;
491 }
492
493 /**
494  *      ata_scsi_error - SCSI layer error handler callback
495  *      @host: SCSI host on which error occurred
496  *
497  *      Handles SCSI-layer-thrown error events.
498  *
499  *      LOCKING:
500  *      Inherited from SCSI layer (none, can sleep)
501  *
502  *      RETURNS:
503  *      Zero.
504  */
505 void ata_scsi_error(struct Scsi_Host *host)
506 {
507         struct ata_port *ap = ata_shost_to_port(host);
508         int i;
509         unsigned long flags;
510
511         DPRINTK("ENTER\n");
512
513         /* synchronize with port task */
514         ata_port_flush_task(ap);
515
516         /* synchronize with host lock and sort out timeouts */
517
518         /* For new EH, all qcs are finished in one of three ways -
519          * normal completion, error completion, and SCSI timeout.
520          * Both cmpletions can race against SCSI timeout.  When normal
521          * completion wins, the qc never reaches EH.  When error
522          * completion wins, the qc has ATA_QCFLAG_FAILED set.
523          *
524          * When SCSI timeout wins, things are a bit more complex.
525          * Normal or error completion can occur after the timeout but
526          * before this point.  In such cases, both types of
527          * completions are honored.  A scmd is determined to have
528          * timed out iff its associated qc is active and not failed.
529          */
530         if (ap->ops->error_handler) {
531                 struct scsi_cmnd *scmd, *tmp;
532                 int nr_timedout = 0;
533
534                 spin_lock_irqsave(ap->lock, flags);
535
536                 list_for_each_entry_safe(scmd, tmp, &host->eh_cmd_q, eh_entry) {
537                         struct ata_queued_cmd *qc;
538
539                         for (i = 0; i < ATA_MAX_QUEUE; i++) {
540                                 qc = __ata_qc_from_tag(ap, i);
541                                 if (qc->flags & ATA_QCFLAG_ACTIVE &&
542                                     qc->scsicmd == scmd)
543                                         break;
544                         }
545
546                         if (i < ATA_MAX_QUEUE) {
547                                 /* the scmd has an associated qc */
548                                 if (!(qc->flags & ATA_QCFLAG_FAILED)) {
549                                         /* which hasn't failed yet, timeout */
550                                         qc->err_mask |= AC_ERR_TIMEOUT;
551                                         qc->flags |= ATA_QCFLAG_FAILED;
552                                         nr_timedout++;
553                                 }
554                         } else {
555                                 /* Normal completion occurred after
556                                  * SCSI timeout but before this point.
557                                  * Successfully complete it.
558                                  */
559                                 scmd->retries = scmd->allowed;
560                                 scsi_eh_finish_cmd(scmd, &ap->eh_done_q);
561                         }
562                 }
563
564                 /* If we have timed out qcs.  They belong to EH from
565                  * this point but the state of the controller is
566                  * unknown.  Freeze the port to make sure the IRQ
567                  * handler doesn't diddle with those qcs.  This must
568                  * be done atomically w.r.t. setting QCFLAG_FAILED.
569                  */
570                 if (nr_timedout)
571                         __ata_port_freeze(ap);
572
573                 spin_unlock_irqrestore(ap->lock, flags);
574
575                 /* initialize eh_tries */
576                 ap->eh_tries = ATA_EH_MAX_TRIES;
577         } else
578                 spin_unlock_wait(ap->lock);
579
580  repeat:
581         /* invoke error handler */
582         if (ap->ops->error_handler) {
583                 struct ata_link *link;
584
585                 /* kill fast drain timer */
586                 del_timer_sync(&ap->fastdrain_timer);
587
588                 /* process port resume request */
589                 ata_eh_handle_port_resume(ap);
590
591                 /* fetch & clear EH info */
592                 spin_lock_irqsave(ap->lock, flags);
593
594                 __ata_port_for_each_link(link, ap) {
595                         struct ata_eh_context *ehc = &link->eh_context;
596                         struct ata_device *dev;
597
598                         memset(&link->eh_context, 0, sizeof(link->eh_context));
599                         link->eh_context.i = link->eh_info;
600                         memset(&link->eh_info, 0, sizeof(link->eh_info));
601
602                         ata_link_for_each_dev(dev, link) {
603                                 int devno = dev->devno;
604
605                                 ehc->saved_xfer_mode[devno] = dev->xfer_mode;
606                                 if (ata_ncq_enabled(dev))
607                                         ehc->saved_ncq_enabled |= 1 << devno;
608                         }
609
610                         /* set last reset timestamp to some time in the past */
611                         ehc->last_reset = jiffies - 60 * HZ;
612                 }
613
614                 ap->pflags |= ATA_PFLAG_EH_IN_PROGRESS;
615                 ap->pflags &= ~ATA_PFLAG_EH_PENDING;
616                 ap->excl_link = NULL;   /* don't maintain exclusion over EH */
617
618                 spin_unlock_irqrestore(ap->lock, flags);
619
620                 /* invoke EH, skip if unloading or suspended */
621                 if (!(ap->pflags & (ATA_PFLAG_UNLOADING | ATA_PFLAG_SUSPENDED)))
622                         ap->ops->error_handler(ap);
623                 else
624                         ata_eh_finish(ap);
625
626                 /* process port suspend request */
627                 ata_eh_handle_port_suspend(ap);
628
629                 /* Exception might have happend after ->error_handler
630                  * recovered the port but before this point.  Repeat
631                  * EH in such case.
632                  */
633                 spin_lock_irqsave(ap->lock, flags);
634
635                 if (ap->pflags & ATA_PFLAG_EH_PENDING) {
636                         if (--ap->eh_tries) {
637                                 spin_unlock_irqrestore(ap->lock, flags);
638                                 goto repeat;
639                         }
640                         ata_port_printk(ap, KERN_ERR, "EH pending after %d "
641                                         "tries, giving up\n", ATA_EH_MAX_TRIES);
642                         ap->pflags &= ~ATA_PFLAG_EH_PENDING;
643                 }
644
645                 /* this run is complete, make sure EH info is clear */
646                 __ata_port_for_each_link(link, ap)
647                         memset(&link->eh_info, 0, sizeof(link->eh_info));
648
649                 /* Clear host_eh_scheduled while holding ap->lock such
650                  * that if exception occurs after this point but
651                  * before EH completion, SCSI midlayer will
652                  * re-initiate EH.
653                  */
654                 host->host_eh_scheduled = 0;
655
656                 spin_unlock_irqrestore(ap->lock, flags);
657         } else {
658                 WARN_ON(ata_qc_from_tag(ap, ap->link.active_tag) == NULL);
659                 ap->ops->eng_timeout(ap);
660         }
661
662         /* finish or retry handled scmd's and clean up */
663         WARN_ON(host->host_failed || !list_empty(&host->eh_cmd_q));
664
665         scsi_eh_flush_done_q(&ap->eh_done_q);
666
667         /* clean up */
668         spin_lock_irqsave(ap->lock, flags);
669
670         if (ap->pflags & ATA_PFLAG_LOADING)
671                 ap->pflags &= ~ATA_PFLAG_LOADING;
672         else if (ap->pflags & ATA_PFLAG_SCSI_HOTPLUG)
673                 queue_delayed_work(ata_aux_wq, &ap->hotplug_task, 0);
674
675         if (ap->pflags & ATA_PFLAG_RECOVERED)
676                 ata_port_printk(ap, KERN_INFO, "EH complete\n");
677
678         ap->pflags &= ~(ATA_PFLAG_SCSI_HOTPLUG | ATA_PFLAG_RECOVERED);
679
680         /* tell wait_eh that we're done */
681         ap->pflags &= ~ATA_PFLAG_EH_IN_PROGRESS;
682         wake_up_all(&ap->eh_wait_q);
683
684         spin_unlock_irqrestore(ap->lock, flags);
685
686         DPRINTK("EXIT\n");
687 }
688
689 /**
690  *      ata_port_wait_eh - Wait for the currently pending EH to complete
691  *      @ap: Port to wait EH for
692  *
693  *      Wait until the currently pending EH is complete.
694  *
695  *      LOCKING:
696  *      Kernel thread context (may sleep).
697  */
698 void ata_port_wait_eh(struct ata_port *ap)
699 {
700         unsigned long flags;
701         DEFINE_WAIT(wait);
702
703  retry:
704         spin_lock_irqsave(ap->lock, flags);
705
706         while (ap->pflags & (ATA_PFLAG_EH_PENDING | ATA_PFLAG_EH_IN_PROGRESS)) {
707                 prepare_to_wait(&ap->eh_wait_q, &wait, TASK_UNINTERRUPTIBLE);
708                 spin_unlock_irqrestore(ap->lock, flags);
709                 schedule();
710                 spin_lock_irqsave(ap->lock, flags);
711         }
712         finish_wait(&ap->eh_wait_q, &wait);
713
714         spin_unlock_irqrestore(ap->lock, flags);
715
716         /* make sure SCSI EH is complete */
717         if (scsi_host_in_recovery(ap->scsi_host)) {
718                 msleep(10);
719                 goto retry;
720         }
721 }
722
723 static int ata_eh_nr_in_flight(struct ata_port *ap)
724 {
725         unsigned int tag;
726         int nr = 0;
727
728         /* count only non-internal commands */
729         for (tag = 0; tag < ATA_MAX_QUEUE - 1; tag++)
730                 if (ata_qc_from_tag(ap, tag))
731                         nr++;
732
733         return nr;
734 }
735
736 void ata_eh_fastdrain_timerfn(unsigned long arg)
737 {
738         struct ata_port *ap = (void *)arg;
739         unsigned long flags;
740         int cnt;
741
742         spin_lock_irqsave(ap->lock, flags);
743
744         cnt = ata_eh_nr_in_flight(ap);
745
746         /* are we done? */
747         if (!cnt)
748                 goto out_unlock;
749
750         if (cnt == ap->fastdrain_cnt) {
751                 unsigned int tag;
752
753                 /* No progress during the last interval, tag all
754                  * in-flight qcs as timed out and freeze the port.
755                  */
756                 for (tag = 0; tag < ATA_MAX_QUEUE - 1; tag++) {
757                         struct ata_queued_cmd *qc = ata_qc_from_tag(ap, tag);
758                         if (qc)
759                                 qc->err_mask |= AC_ERR_TIMEOUT;
760                 }
761
762                 ata_port_freeze(ap);
763         } else {
764                 /* some qcs have finished, give it another chance */
765                 ap->fastdrain_cnt = cnt;
766                 ap->fastdrain_timer.expires =
767                         ata_deadline(jiffies, ATA_EH_FASTDRAIN_INTERVAL);
768                 add_timer(&ap->fastdrain_timer);
769         }
770
771  out_unlock:
772         spin_unlock_irqrestore(ap->lock, flags);
773 }
774
775 /**
776  *      ata_eh_set_pending - set ATA_PFLAG_EH_PENDING and activate fast drain
777  *      @ap: target ATA port
778  *      @fastdrain: activate fast drain
779  *
780  *      Set ATA_PFLAG_EH_PENDING and activate fast drain if @fastdrain
781  *      is non-zero and EH wasn't pending before.  Fast drain ensures
782  *      that EH kicks in in timely manner.
783  *
784  *      LOCKING:
785  *      spin_lock_irqsave(host lock)
786  */
787 static void ata_eh_set_pending(struct ata_port *ap, int fastdrain)
788 {
789         int cnt;
790
791         /* already scheduled? */
792         if (ap->pflags & ATA_PFLAG_EH_PENDING)
793                 return;
794
795         ap->pflags |= ATA_PFLAG_EH_PENDING;
796
797         if (!fastdrain)
798                 return;
799
800         /* do we have in-flight qcs? */
801         cnt = ata_eh_nr_in_flight(ap);
802         if (!cnt)
803                 return;
804
805         /* activate fast drain */
806         ap->fastdrain_cnt = cnt;
807         ap->fastdrain_timer.expires =
808                 ata_deadline(jiffies, ATA_EH_FASTDRAIN_INTERVAL);
809         add_timer(&ap->fastdrain_timer);
810 }
811
812 /**
813  *      ata_qc_schedule_eh - schedule qc for error handling
814  *      @qc: command to schedule error handling for
815  *
816  *      Schedule error handling for @qc.  EH will kick in as soon as
817  *      other commands are drained.
818  *
819  *      LOCKING:
820  *      spin_lock_irqsave(host lock)
821  */
822 void ata_qc_schedule_eh(struct ata_queued_cmd *qc)
823 {
824         struct ata_port *ap = qc->ap;
825
826         WARN_ON(!ap->ops->error_handler);
827
828         qc->flags |= ATA_QCFLAG_FAILED;
829         ata_eh_set_pending(ap, 1);
830
831         /* The following will fail if timeout has already expired.
832          * ata_scsi_error() takes care of such scmds on EH entry.
833          * Note that ATA_QCFLAG_FAILED is unconditionally set after
834          * this function completes.
835          */
836         scsi_req_abort_cmd(qc->scsicmd);
837 }
838
839 /**
840  *      ata_port_schedule_eh - schedule error handling without a qc
841  *      @ap: ATA port to schedule EH for
842  *
843  *      Schedule error handling for @ap.  EH will kick in as soon as
844  *      all commands are drained.
845  *
846  *      LOCKING:
847  *      spin_lock_irqsave(host lock)
848  */
849 void ata_port_schedule_eh(struct ata_port *ap)
850 {
851         WARN_ON(!ap->ops->error_handler);
852
853         if (ap->pflags & ATA_PFLAG_INITIALIZING)
854                 return;
855
856         ata_eh_set_pending(ap, 1);
857         scsi_schedule_eh(ap->scsi_host);
858
859         DPRINTK("port EH scheduled\n");
860 }
861
862 static int ata_do_link_abort(struct ata_port *ap, struct ata_link *link)
863 {
864         int tag, nr_aborted = 0;
865
866         WARN_ON(!ap->ops->error_handler);
867
868         /* we're gonna abort all commands, no need for fast drain */
869         ata_eh_set_pending(ap, 0);
870
871         for (tag = 0; tag < ATA_MAX_QUEUE; tag++) {
872                 struct ata_queued_cmd *qc = ata_qc_from_tag(ap, tag);
873
874                 if (qc && (!link || qc->dev->link == link)) {
875                         qc->flags |= ATA_QCFLAG_FAILED;
876                         ata_qc_complete(qc);
877                         nr_aborted++;
878                 }
879         }
880
881         if (!nr_aborted)
882                 ata_port_schedule_eh(ap);
883
884         return nr_aborted;
885 }
886
887 /**
888  *      ata_link_abort - abort all qc's on the link
889  *      @link: ATA link to abort qc's for
890  *
891  *      Abort all active qc's active on @link and schedule EH.
892  *
893  *      LOCKING:
894  *      spin_lock_irqsave(host lock)
895  *
896  *      RETURNS:
897  *      Number of aborted qc's.
898  */
899 int ata_link_abort(struct ata_link *link)
900 {
901         return ata_do_link_abort(link->ap, link);
902 }
903
904 /**
905  *      ata_port_abort - abort all qc's on the port
906  *      @ap: ATA port to abort qc's for
907  *
908  *      Abort all active qc's of @ap and schedule EH.
909  *
910  *      LOCKING:
911  *      spin_lock_irqsave(host_set lock)
912  *
913  *      RETURNS:
914  *      Number of aborted qc's.
915  */
916 int ata_port_abort(struct ata_port *ap)
917 {
918         return ata_do_link_abort(ap, NULL);
919 }
920
921 /**
922  *      __ata_port_freeze - freeze port
923  *      @ap: ATA port to freeze
924  *
925  *      This function is called when HSM violation or some other
926  *      condition disrupts normal operation of the port.  Frozen port
927  *      is not allowed to perform any operation until the port is
928  *      thawed, which usually follows a successful reset.
929  *
930  *      ap->ops->freeze() callback can be used for freezing the port
931  *      hardware-wise (e.g. mask interrupt and stop DMA engine).  If a
932  *      port cannot be frozen hardware-wise, the interrupt handler
933  *      must ack and clear interrupts unconditionally while the port
934  *      is frozen.
935  *
936  *      LOCKING:
937  *      spin_lock_irqsave(host lock)
938  */
939 static void __ata_port_freeze(struct ata_port *ap)
940 {
941         WARN_ON(!ap->ops->error_handler);
942
943         if (ap->ops->freeze)
944                 ap->ops->freeze(ap);
945
946         ap->pflags |= ATA_PFLAG_FROZEN;
947
948         DPRINTK("ata%u port frozen\n", ap->print_id);
949 }
950
951 /**
952  *      ata_port_freeze - abort & freeze port
953  *      @ap: ATA port to freeze
954  *
955  *      Abort and freeze @ap.
956  *
957  *      LOCKING:
958  *      spin_lock_irqsave(host lock)
959  *
960  *      RETURNS:
961  *      Number of aborted commands.
962  */
963 int ata_port_freeze(struct ata_port *ap)
964 {
965         int nr_aborted;
966
967         WARN_ON(!ap->ops->error_handler);
968
969         nr_aborted = ata_port_abort(ap);
970         __ata_port_freeze(ap);
971
972         return nr_aborted;
973 }
974
975 /**
976  *      sata_async_notification - SATA async notification handler
977  *      @ap: ATA port where async notification is received
978  *
979  *      Handler to be called when async notification via SDB FIS is
980  *      received.  This function schedules EH if necessary.
981  *
982  *      LOCKING:
983  *      spin_lock_irqsave(host lock)
984  *
985  *      RETURNS:
986  *      1 if EH is scheduled, 0 otherwise.
987  */
988 int sata_async_notification(struct ata_port *ap)
989 {
990         u32 sntf;
991         int rc;
992
993         if (!(ap->flags & ATA_FLAG_AN))
994                 return 0;
995
996         rc = sata_scr_read(&ap->link, SCR_NOTIFICATION, &sntf);
997         if (rc == 0)
998                 sata_scr_write(&ap->link, SCR_NOTIFICATION, sntf);
999
1000         if (!sata_pmp_attached(ap) || rc) {
1001                 /* PMP is not attached or SNTF is not available */
1002                 if (!sata_pmp_attached(ap)) {
1003                         /* PMP is not attached.  Check whether ATAPI
1004                          * AN is configured.  If so, notify media
1005                          * change.
1006                          */
1007                         struct ata_device *dev = ap->link.device;
1008
1009                         if ((dev->class == ATA_DEV_ATAPI) &&
1010                             (dev->flags & ATA_DFLAG_AN))
1011                                 ata_scsi_media_change_notify(dev);
1012                         return 0;
1013                 } else {
1014                         /* PMP is attached but SNTF is not available.
1015                          * ATAPI async media change notification is
1016                          * not used.  The PMP must be reporting PHY
1017                          * status change, schedule EH.
1018                          */
1019                         ata_port_schedule_eh(ap);
1020                         return 1;
1021                 }
1022         } else {
1023                 /* PMP is attached and SNTF is available */
1024                 struct ata_link *link;
1025
1026                 /* check and notify ATAPI AN */
1027                 ata_port_for_each_link(link, ap) {
1028                         if (!(sntf & (1 << link->pmp)))
1029                                 continue;
1030
1031                         if ((link->device->class == ATA_DEV_ATAPI) &&
1032                             (link->device->flags & ATA_DFLAG_AN))
1033                                 ata_scsi_media_change_notify(link->device);
1034                 }
1035
1036                 /* If PMP is reporting that PHY status of some
1037                  * downstream ports has changed, schedule EH.
1038                  */
1039                 if (sntf & (1 << SATA_PMP_CTRL_PORT)) {
1040                         ata_port_schedule_eh(ap);
1041                         return 1;
1042                 }
1043
1044                 return 0;
1045         }
1046 }
1047
1048 /**
1049  *      ata_eh_freeze_port - EH helper to freeze port
1050  *      @ap: ATA port to freeze
1051  *
1052  *      Freeze @ap.
1053  *
1054  *      LOCKING:
1055  *      None.
1056  */
1057 void ata_eh_freeze_port(struct ata_port *ap)
1058 {
1059         unsigned long flags;
1060
1061         if (!ap->ops->error_handler)
1062                 return;
1063
1064         spin_lock_irqsave(ap->lock, flags);
1065         __ata_port_freeze(ap);
1066         spin_unlock_irqrestore(ap->lock, flags);
1067 }
1068
1069 /**
1070  *      ata_port_thaw_port - EH helper to thaw port
1071  *      @ap: ATA port to thaw
1072  *
1073  *      Thaw frozen port @ap.
1074  *
1075  *      LOCKING:
1076  *      None.
1077  */
1078 void ata_eh_thaw_port(struct ata_port *ap)
1079 {
1080         unsigned long flags;
1081
1082         if (!ap->ops->error_handler)
1083                 return;
1084
1085         spin_lock_irqsave(ap->lock, flags);
1086
1087         ap->pflags &= ~ATA_PFLAG_FROZEN;
1088
1089         if (ap->ops->thaw)
1090                 ap->ops->thaw(ap);
1091
1092         spin_unlock_irqrestore(ap->lock, flags);
1093
1094         DPRINTK("ata%u port thawed\n", ap->print_id);
1095 }
1096
1097 static void ata_eh_scsidone(struct scsi_cmnd *scmd)
1098 {
1099         /* nada */
1100 }
1101
1102 static void __ata_eh_qc_complete(struct ata_queued_cmd *qc)
1103 {
1104         struct ata_port *ap = qc->ap;
1105         struct scsi_cmnd *scmd = qc->scsicmd;
1106         unsigned long flags;
1107
1108         spin_lock_irqsave(ap->lock, flags);
1109         qc->scsidone = ata_eh_scsidone;
1110         __ata_qc_complete(qc);
1111         WARN_ON(ata_tag_valid(qc->tag));
1112         spin_unlock_irqrestore(ap->lock, flags);
1113
1114         scsi_eh_finish_cmd(scmd, &ap->eh_done_q);
1115 }
1116
1117 /**
1118  *      ata_eh_qc_complete - Complete an active ATA command from EH
1119  *      @qc: Command to complete
1120  *
1121  *      Indicate to the mid and upper layers that an ATA command has
1122  *      completed.  To be used from EH.
1123  */
1124 void ata_eh_qc_complete(struct ata_queued_cmd *qc)
1125 {
1126         struct scsi_cmnd *scmd = qc->scsicmd;
1127         scmd->retries = scmd->allowed;
1128         __ata_eh_qc_complete(qc);
1129 }
1130
1131 /**
1132  *      ata_eh_qc_retry - Tell midlayer to retry an ATA command after EH
1133  *      @qc: Command to retry
1134  *
1135  *      Indicate to the mid and upper layers that an ATA command
1136  *      should be retried.  To be used from EH.
1137  *
1138  *      SCSI midlayer limits the number of retries to scmd->allowed.
1139  *      scmd->retries is decremented for commands which get retried
1140  *      due to unrelated failures (qc->err_mask is zero).
1141  */
1142 void ata_eh_qc_retry(struct ata_queued_cmd *qc)
1143 {
1144         struct scsi_cmnd *scmd = qc->scsicmd;
1145         if (!qc->err_mask && scmd->retries)
1146                 scmd->retries--;
1147         __ata_eh_qc_complete(qc);
1148 }
1149
1150 /**
1151  *      ata_eh_detach_dev - detach ATA device
1152  *      @dev: ATA device to detach
1153  *
1154  *      Detach @dev.
1155  *
1156  *      LOCKING:
1157  *      None.
1158  */
1159 void ata_eh_detach_dev(struct ata_device *dev)
1160 {
1161         struct ata_link *link = dev->link;
1162         struct ata_port *ap = link->ap;
1163         unsigned long flags;
1164
1165         ata_dev_disable(dev);
1166
1167         spin_lock_irqsave(ap->lock, flags);
1168
1169         dev->flags &= ~ATA_DFLAG_DETACH;
1170
1171         if (ata_scsi_offline_dev(dev)) {
1172                 dev->flags |= ATA_DFLAG_DETACHED;
1173                 ap->pflags |= ATA_PFLAG_SCSI_HOTPLUG;
1174         }
1175
1176         /* clear per-dev EH actions */
1177         ata_eh_clear_action(link, dev, &link->eh_info, ATA_EH_PERDEV_MASK);
1178         ata_eh_clear_action(link, dev, &link->eh_context.i, ATA_EH_PERDEV_MASK);
1179
1180         spin_unlock_irqrestore(ap->lock, flags);
1181 }
1182
1183 /**
1184  *      ata_eh_about_to_do - about to perform eh_action
1185  *      @link: target ATA link
1186  *      @dev: target ATA dev for per-dev action (can be NULL)
1187  *      @action: action about to be performed
1188  *
1189  *      Called just before performing EH actions to clear related bits
1190  *      in @link->eh_info such that eh actions are not unnecessarily
1191  *      repeated.
1192  *
1193  *      LOCKING:
1194  *      None.
1195  */
1196 void ata_eh_about_to_do(struct ata_link *link, struct ata_device *dev,
1197                         unsigned int action)
1198 {
1199         struct ata_port *ap = link->ap;
1200         struct ata_eh_info *ehi = &link->eh_info;
1201         struct ata_eh_context *ehc = &link->eh_context;
1202         unsigned long flags;
1203
1204         spin_lock_irqsave(ap->lock, flags);
1205
1206         ata_eh_clear_action(link, dev, ehi, action);
1207
1208         if (!(ehc->i.flags & ATA_EHI_QUIET))
1209                 ap->pflags |= ATA_PFLAG_RECOVERED;
1210
1211         spin_unlock_irqrestore(ap->lock, flags);
1212 }
1213
1214 /**
1215  *      ata_eh_done - EH action complete
1216 *       @ap: target ATA port
1217  *      @dev: target ATA dev for per-dev action (can be NULL)
1218  *      @action: action just completed
1219  *
1220  *      Called right after performing EH actions to clear related bits
1221  *      in @link->eh_context.
1222  *
1223  *      LOCKING:
1224  *      None.
1225  */
1226 void ata_eh_done(struct ata_link *link, struct ata_device *dev,
1227                  unsigned int action)
1228 {
1229         struct ata_eh_context *ehc = &link->eh_context;
1230
1231         ata_eh_clear_action(link, dev, &ehc->i, action);
1232 }
1233
1234 /**
1235  *      ata_err_string - convert err_mask to descriptive string
1236  *      @err_mask: error mask to convert to string
1237  *
1238  *      Convert @err_mask to descriptive string.  Errors are
1239  *      prioritized according to severity and only the most severe
1240  *      error is reported.
1241  *
1242  *      LOCKING:
1243  *      None.
1244  *
1245  *      RETURNS:
1246  *      Descriptive string for @err_mask
1247  */
1248 static const char *ata_err_string(unsigned int err_mask)
1249 {
1250         if (err_mask & AC_ERR_HOST_BUS)
1251                 return "host bus error";
1252         if (err_mask & AC_ERR_ATA_BUS)
1253                 return "ATA bus error";
1254         if (err_mask & AC_ERR_TIMEOUT)
1255                 return "timeout";
1256         if (err_mask & AC_ERR_HSM)
1257                 return "HSM violation";
1258         if (err_mask & AC_ERR_SYSTEM)
1259                 return "internal error";
1260         if (err_mask & AC_ERR_MEDIA)
1261                 return "media error";
1262         if (err_mask & AC_ERR_INVALID)
1263                 return "invalid argument";
1264         if (err_mask & AC_ERR_DEV)
1265                 return "device error";
1266         return "unknown error";
1267 }
1268
1269 /**
1270  *      ata_read_log_page - read a specific log page
1271  *      @dev: target device
1272  *      @page: page to read
1273  *      @buf: buffer to store read page
1274  *      @sectors: number of sectors to read
1275  *
1276  *      Read log page using READ_LOG_EXT command.
1277  *
1278  *      LOCKING:
1279  *      Kernel thread context (may sleep).
1280  *
1281  *      RETURNS:
1282  *      0 on success, AC_ERR_* mask otherwise.
1283  */
1284 static unsigned int ata_read_log_page(struct ata_device *dev,
1285                                       u8 page, void *buf, unsigned int sectors)
1286 {
1287         struct ata_taskfile tf;
1288         unsigned int err_mask;
1289
1290         DPRINTK("read log page - page %d\n", page);
1291
1292         ata_tf_init(dev, &tf);
1293         tf.command = ATA_CMD_READ_LOG_EXT;
1294         tf.lbal = page;
1295         tf.nsect = sectors;
1296         tf.hob_nsect = sectors >> 8;
1297         tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_LBA48 | ATA_TFLAG_DEVICE;
1298         tf.protocol = ATA_PROT_PIO;
1299
1300         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_FROM_DEVICE,
1301                                      buf, sectors * ATA_SECT_SIZE, 0);
1302
1303         DPRINTK("EXIT, err_mask=%x\n", err_mask);
1304         return err_mask;
1305 }
1306
1307 /**
1308  *      ata_eh_read_log_10h - Read log page 10h for NCQ error details
1309  *      @dev: Device to read log page 10h from
1310  *      @tag: Resulting tag of the failed command
1311  *      @tf: Resulting taskfile registers of the failed command
1312  *
1313  *      Read log page 10h to obtain NCQ error details and clear error
1314  *      condition.
1315  *
1316  *      LOCKING:
1317  *      Kernel thread context (may sleep).
1318  *
1319  *      RETURNS:
1320  *      0 on success, -errno otherwise.
1321  */
1322 static int ata_eh_read_log_10h(struct ata_device *dev,
1323                                int *tag, struct ata_taskfile *tf)
1324 {
1325         u8 *buf = dev->link->ap->sector_buf;
1326         unsigned int err_mask;
1327         u8 csum;
1328         int i;
1329
1330         err_mask = ata_read_log_page(dev, ATA_LOG_SATA_NCQ, buf, 1);
1331         if (err_mask)
1332                 return -EIO;
1333
1334         csum = 0;
1335         for (i = 0; i < ATA_SECT_SIZE; i++)
1336                 csum += buf[i];
1337         if (csum)
1338                 ata_dev_printk(dev, KERN_WARNING,
1339                                "invalid checksum 0x%x on log page 10h\n", csum);
1340
1341         if (buf[0] & 0x80)
1342                 return -ENOENT;
1343
1344         *tag = buf[0] & 0x1f;
1345
1346         tf->command = buf[2];
1347         tf->feature = buf[3];
1348         tf->lbal = buf[4];
1349         tf->lbam = buf[5];
1350         tf->lbah = buf[6];
1351         tf->device = buf[7];
1352         tf->hob_lbal = buf[8];
1353         tf->hob_lbam = buf[9];
1354         tf->hob_lbah = buf[10];
1355         tf->nsect = buf[12];
1356         tf->hob_nsect = buf[13];
1357
1358         return 0;
1359 }
1360
1361 /**
1362  *      atapi_eh_tur - perform ATAPI TEST_UNIT_READY
1363  *      @dev: target ATAPI device
1364  *      @r_sense_key: out parameter for sense_key
1365  *
1366  *      Perform ATAPI TEST_UNIT_READY.
1367  *
1368  *      LOCKING:
1369  *      EH context (may sleep).
1370  *
1371  *      RETURNS:
1372  *      0 on success, AC_ERR_* mask on failure.
1373  */
1374 static unsigned int atapi_eh_tur(struct ata_device *dev, u8 *r_sense_key)
1375 {
1376         u8 cdb[ATAPI_CDB_LEN] = { TEST_UNIT_READY, 0, 0, 0, 0, 0 };
1377         struct ata_taskfile tf;
1378         unsigned int err_mask;
1379
1380         ata_tf_init(dev, &tf);
1381
1382         tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
1383         tf.command = ATA_CMD_PACKET;
1384         tf.protocol = ATAPI_PROT_NODATA;
1385
1386         err_mask = ata_exec_internal(dev, &tf, cdb, DMA_NONE, NULL, 0, 0);
1387         if (err_mask == AC_ERR_DEV)
1388                 *r_sense_key = tf.feature >> 4;
1389         return err_mask;
1390 }
1391
1392 /**
1393  *      atapi_eh_request_sense - perform ATAPI REQUEST_SENSE
1394  *      @dev: device to perform REQUEST_SENSE to
1395  *      @sense_buf: result sense data buffer (SCSI_SENSE_BUFFERSIZE bytes long)
1396  *      @dfl_sense_key: default sense key to use
1397  *
1398  *      Perform ATAPI REQUEST_SENSE after the device reported CHECK
1399  *      SENSE.  This function is EH helper.
1400  *
1401  *      LOCKING:
1402  *      Kernel thread context (may sleep).
1403  *
1404  *      RETURNS:
1405  *      0 on success, AC_ERR_* mask on failure
1406  */
1407 static unsigned int atapi_eh_request_sense(struct ata_device *dev,
1408                                            u8 *sense_buf, u8 dfl_sense_key)
1409 {
1410         u8 cdb[ATAPI_CDB_LEN] =
1411                 { REQUEST_SENSE, 0, 0, 0, SCSI_SENSE_BUFFERSIZE, 0 };
1412         struct ata_port *ap = dev->link->ap;
1413         struct ata_taskfile tf;
1414
1415         DPRINTK("ATAPI request sense\n");
1416
1417         /* FIXME: is this needed? */
1418         memset(sense_buf, 0, SCSI_SENSE_BUFFERSIZE);
1419
1420         /* initialize sense_buf with the error register,
1421          * for the case where they are -not- overwritten
1422          */
1423         sense_buf[0] = 0x70;
1424         sense_buf[2] = dfl_sense_key;
1425
1426         /* some devices time out if garbage left in tf */
1427         ata_tf_init(dev, &tf);
1428
1429         tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
1430         tf.command = ATA_CMD_PACKET;
1431
1432         /* is it pointless to prefer PIO for "safety reasons"? */
1433         if (ap->flags & ATA_FLAG_PIO_DMA) {
1434                 tf.protocol = ATAPI_PROT_DMA;
1435                 tf.feature |= ATAPI_PKT_DMA;
1436         } else {
1437                 tf.protocol = ATAPI_PROT_PIO;
1438                 tf.lbam = SCSI_SENSE_BUFFERSIZE;
1439                 tf.lbah = 0;
1440         }
1441
1442         return ata_exec_internal(dev, &tf, cdb, DMA_FROM_DEVICE,
1443                                  sense_buf, SCSI_SENSE_BUFFERSIZE, 0);
1444 }
1445
1446 /**
1447  *      ata_eh_analyze_serror - analyze SError for a failed port
1448  *      @link: ATA link to analyze SError for
1449  *
1450  *      Analyze SError if available and further determine cause of
1451  *      failure.
1452  *
1453  *      LOCKING:
1454  *      None.
1455  */
1456 static void ata_eh_analyze_serror(struct ata_link *link)
1457 {
1458         struct ata_eh_context *ehc = &link->eh_context;
1459         u32 serror = ehc->i.serror;
1460         unsigned int err_mask = 0, action = 0;
1461         u32 hotplug_mask;
1462
1463         if (serror & (SERR_PERSISTENT | SERR_DATA)) {
1464                 err_mask |= AC_ERR_ATA_BUS;
1465                 action |= ATA_EH_RESET;
1466         }
1467         if (serror & SERR_PROTOCOL) {
1468                 err_mask |= AC_ERR_HSM;
1469                 action |= ATA_EH_RESET;
1470         }
1471         if (serror & SERR_INTERNAL) {
1472                 err_mask |= AC_ERR_SYSTEM;
1473                 action |= ATA_EH_RESET;
1474         }
1475
1476         /* Determine whether a hotplug event has occurred.  Both
1477          * SError.N/X are considered hotplug events for enabled or
1478          * host links.  For disabled PMP links, only N bit is
1479          * considered as X bit is left at 1 for link plugging.
1480          */
1481         hotplug_mask = 0;
1482
1483         if (!(link->flags & ATA_LFLAG_DISABLED) || ata_is_host_link(link))
1484                 hotplug_mask = SERR_PHYRDY_CHG | SERR_DEV_XCHG;
1485         else
1486                 hotplug_mask = SERR_PHYRDY_CHG;
1487
1488         if (serror & hotplug_mask)
1489                 ata_ehi_hotplugged(&ehc->i);
1490
1491         ehc->i.err_mask |= err_mask;
1492         ehc->i.action |= action;
1493 }
1494
1495 /**
1496  *      ata_eh_analyze_ncq_error - analyze NCQ error
1497  *      @link: ATA link to analyze NCQ error for
1498  *
1499  *      Read log page 10h, determine the offending qc and acquire
1500  *      error status TF.  For NCQ device errors, all LLDDs have to do
1501  *      is setting AC_ERR_DEV in ehi->err_mask.  This function takes
1502  *      care of the rest.
1503  *
1504  *      LOCKING:
1505  *      Kernel thread context (may sleep).
1506  */
1507 void ata_eh_analyze_ncq_error(struct ata_link *link)
1508 {
1509         struct ata_port *ap = link->ap;
1510         struct ata_eh_context *ehc = &link->eh_context;
1511         struct ata_device *dev = link->device;
1512         struct ata_queued_cmd *qc;
1513         struct ata_taskfile tf;
1514         int tag, rc;
1515
1516         /* if frozen, we can't do much */
1517         if (ap->pflags & ATA_PFLAG_FROZEN)
1518                 return;
1519
1520         /* is it NCQ device error? */
1521         if (!link->sactive || !(ehc->i.err_mask & AC_ERR_DEV))
1522                 return;
1523
1524         /* has LLDD analyzed already? */
1525         for (tag = 0; tag < ATA_MAX_QUEUE; tag++) {
1526                 qc = __ata_qc_from_tag(ap, tag);
1527
1528                 if (!(qc->flags & ATA_QCFLAG_FAILED))
1529                         continue;
1530
1531                 if (qc->err_mask)
1532                         return;
1533         }
1534
1535         /* okay, this error is ours */
1536         rc = ata_eh_read_log_10h(dev, &tag, &tf);
1537         if (rc) {
1538                 ata_link_printk(link, KERN_ERR, "failed to read log page 10h "
1539                                 "(errno=%d)\n", rc);
1540                 return;
1541         }
1542
1543         if (!(link->sactive & (1 << tag))) {
1544                 ata_link_printk(link, KERN_ERR, "log page 10h reported "
1545                                 "inactive tag %d\n", tag);
1546                 return;
1547         }
1548
1549         /* we've got the perpetrator, condemn it */
1550         qc = __ata_qc_from_tag(ap, tag);
1551         memcpy(&qc->result_tf, &tf, sizeof(tf));
1552         qc->result_tf.flags = ATA_TFLAG_ISADDR | ATA_TFLAG_LBA | ATA_TFLAG_LBA48;
1553         qc->err_mask |= AC_ERR_DEV | AC_ERR_NCQ;
1554         ehc->i.err_mask &= ~AC_ERR_DEV;
1555 }
1556
1557 /**
1558  *      ata_eh_analyze_tf - analyze taskfile of a failed qc
1559  *      @qc: qc to analyze
1560  *      @tf: Taskfile registers to analyze
1561  *
1562  *      Analyze taskfile of @qc and further determine cause of
1563  *      failure.  This function also requests ATAPI sense data if
1564  *      avaliable.
1565  *
1566  *      LOCKING:
1567  *      Kernel thread context (may sleep).
1568  *
1569  *      RETURNS:
1570  *      Determined recovery action
1571  */
1572 static unsigned int ata_eh_analyze_tf(struct ata_queued_cmd *qc,
1573                                       const struct ata_taskfile *tf)
1574 {
1575         unsigned int tmp, action = 0;
1576         u8 stat = tf->command, err = tf->feature;
1577
1578         if ((stat & (ATA_BUSY | ATA_DRQ | ATA_DRDY)) != ATA_DRDY) {
1579                 qc->err_mask |= AC_ERR_HSM;
1580                 return ATA_EH_RESET;
1581         }
1582
1583         if (stat & (ATA_ERR | ATA_DF))
1584                 qc->err_mask |= AC_ERR_DEV;
1585         else
1586                 return 0;
1587
1588         switch (qc->dev->class) {
1589         case ATA_DEV_ATA:
1590                 if (err & ATA_ICRC)
1591                         qc->err_mask |= AC_ERR_ATA_BUS;
1592                 if (err & ATA_UNC)
1593                         qc->err_mask |= AC_ERR_MEDIA;
1594                 if (err & ATA_IDNF)
1595                         qc->err_mask |= AC_ERR_INVALID;
1596                 break;
1597
1598         case ATA_DEV_ATAPI:
1599                 if (!(qc->ap->pflags & ATA_PFLAG_FROZEN)) {
1600                         tmp = atapi_eh_request_sense(qc->dev,
1601                                                 qc->scsicmd->sense_buffer,
1602                                                 qc->result_tf.feature >> 4);
1603                         if (!tmp) {
1604                                 /* ATA_QCFLAG_SENSE_VALID is used to
1605                                  * tell atapi_qc_complete() that sense
1606                                  * data is already valid.
1607                                  *
1608                                  * TODO: interpret sense data and set
1609                                  * appropriate err_mask.
1610                                  */
1611                                 qc->flags |= ATA_QCFLAG_SENSE_VALID;
1612                         } else
1613                                 qc->err_mask |= tmp;
1614                 }
1615         }
1616
1617         if (qc->err_mask & (AC_ERR_HSM | AC_ERR_TIMEOUT | AC_ERR_ATA_BUS))
1618                 action |= ATA_EH_RESET;
1619
1620         return action;
1621 }
1622
1623 static int ata_eh_categorize_error(unsigned int eflags, unsigned int err_mask,
1624                                    int *xfer_ok)
1625 {
1626         int base = 0;
1627
1628         if (!(eflags & ATA_EFLAG_DUBIOUS_XFER))
1629                 *xfer_ok = 1;
1630
1631         if (!*xfer_ok)
1632                 base = ATA_ECAT_DUBIOUS_NONE;
1633
1634         if (err_mask & AC_ERR_ATA_BUS)
1635                 return base + ATA_ECAT_ATA_BUS;
1636
1637         if (err_mask & AC_ERR_TIMEOUT)
1638                 return base + ATA_ECAT_TOUT_HSM;
1639
1640         if (eflags & ATA_EFLAG_IS_IO) {
1641                 if (err_mask & AC_ERR_HSM)
1642                         return base + ATA_ECAT_TOUT_HSM;
1643                 if ((err_mask &
1644                      (AC_ERR_DEV|AC_ERR_MEDIA|AC_ERR_INVALID)) == AC_ERR_DEV)
1645                         return base + ATA_ECAT_UNK_DEV;
1646         }
1647
1648         return 0;
1649 }
1650
1651 struct speed_down_verdict_arg {
1652         u64 since;
1653         int xfer_ok;
1654         int nr_errors[ATA_ECAT_NR];
1655 };
1656
1657 static int speed_down_verdict_cb(struct ata_ering_entry *ent, void *void_arg)
1658 {
1659         struct speed_down_verdict_arg *arg = void_arg;
1660         int cat;
1661
1662         if (ent->timestamp < arg->since)
1663                 return -1;
1664
1665         cat = ata_eh_categorize_error(ent->eflags, ent->err_mask,
1666                                       &arg->xfer_ok);
1667         arg->nr_errors[cat]++;
1668
1669         return 0;
1670 }
1671
1672 /**
1673  *      ata_eh_speed_down_verdict - Determine speed down verdict
1674  *      @dev: Device of interest
1675  *
1676  *      This function examines error ring of @dev and determines
1677  *      whether NCQ needs to be turned off, transfer speed should be
1678  *      stepped down, or falling back to PIO is necessary.
1679  *
1680  *      ECAT_ATA_BUS    : ATA_BUS error for any command
1681  *
1682  *      ECAT_TOUT_HSM   : TIMEOUT for any command or HSM violation for
1683  *                        IO commands
1684  *
1685  *      ECAT_UNK_DEV    : Unknown DEV error for IO commands
1686  *
1687  *      ECAT_DUBIOUS_*  : Identical to above three but occurred while
1688  *                        data transfer hasn't been verified.
1689  *
1690  *      Verdicts are
1691  *
1692  *      NCQ_OFF         : Turn off NCQ.
1693  *
1694  *      SPEED_DOWN      : Speed down transfer speed but don't fall back
1695  *                        to PIO.
1696  *
1697  *      FALLBACK_TO_PIO : Fall back to PIO.
1698  *
1699  *      Even if multiple verdicts are returned, only one action is
1700  *      taken per error.  An action triggered by non-DUBIOUS errors
1701  *      clears ering, while one triggered by DUBIOUS_* errors doesn't.
1702  *      This is to expedite speed down decisions right after device is
1703  *      initially configured.
1704  *
1705  *      The followings are speed down rules.  #1 and #2 deal with
1706  *      DUBIOUS errors.
1707  *
1708  *      1. If more than one DUBIOUS_ATA_BUS or DUBIOUS_TOUT_HSM errors
1709  *         occurred during last 5 mins, SPEED_DOWN and FALLBACK_TO_PIO.
1710  *
1711  *      2. If more than one DUBIOUS_TOUT_HSM or DUBIOUS_UNK_DEV errors
1712  *         occurred during last 5 mins, NCQ_OFF.
1713  *
1714  *      3. If more than 8 ATA_BUS, TOUT_HSM or UNK_DEV errors
1715  *         ocurred during last 5 mins, FALLBACK_TO_PIO
1716  *
1717  *      4. If more than 3 TOUT_HSM or UNK_DEV errors occurred
1718  *         during last 10 mins, NCQ_OFF.
1719  *
1720  *      5. If more than 3 ATA_BUS or TOUT_HSM errors, or more than 6
1721  *         UNK_DEV errors occurred during last 10 mins, SPEED_DOWN.
1722  *
1723  *      LOCKING:
1724  *      Inherited from caller.
1725  *
1726  *      RETURNS:
1727  *      OR of ATA_EH_SPDN_* flags.
1728  */
1729 static unsigned int ata_eh_speed_down_verdict(struct ata_device *dev)
1730 {
1731         const u64 j5mins = 5LLU * 60 * HZ, j10mins = 10LLU * 60 * HZ;
1732         u64 j64 = get_jiffies_64();
1733         struct speed_down_verdict_arg arg;
1734         unsigned int verdict = 0;
1735
1736         /* scan past 5 mins of error history */
1737         memset(&arg, 0, sizeof(arg));
1738         arg.since = j64 - min(j64, j5mins);
1739         ata_ering_map(&dev->ering, speed_down_verdict_cb, &arg);
1740
1741         if (arg.nr_errors[ATA_ECAT_DUBIOUS_ATA_BUS] +
1742             arg.nr_errors[ATA_ECAT_DUBIOUS_TOUT_HSM] > 1)
1743                 verdict |= ATA_EH_SPDN_SPEED_DOWN |
1744                         ATA_EH_SPDN_FALLBACK_TO_PIO | ATA_EH_SPDN_KEEP_ERRORS;
1745
1746         if (arg.nr_errors[ATA_ECAT_DUBIOUS_TOUT_HSM] +
1747             arg.nr_errors[ATA_ECAT_DUBIOUS_UNK_DEV] > 1)
1748                 verdict |= ATA_EH_SPDN_NCQ_OFF | ATA_EH_SPDN_KEEP_ERRORS;
1749
1750         if (arg.nr_errors[ATA_ECAT_ATA_BUS] +
1751             arg.nr_errors[ATA_ECAT_TOUT_HSM] +
1752             arg.nr_errors[ATA_ECAT_UNK_DEV] > 6)
1753                 verdict |= ATA_EH_SPDN_FALLBACK_TO_PIO;
1754
1755         /* scan past 10 mins of error history */
1756         memset(&arg, 0, sizeof(arg));
1757         arg.since = j64 - min(j64, j10mins);
1758         ata_ering_map(&dev->ering, speed_down_verdict_cb, &arg);
1759
1760         if (arg.nr_errors[ATA_ECAT_TOUT_HSM] +
1761             arg.nr_errors[ATA_ECAT_UNK_DEV] > 3)
1762                 verdict |= ATA_EH_SPDN_NCQ_OFF;
1763
1764         if (arg.nr_errors[ATA_ECAT_ATA_BUS] +
1765             arg.nr_errors[ATA_ECAT_TOUT_HSM] > 3 ||
1766             arg.nr_errors[ATA_ECAT_UNK_DEV] > 6)
1767                 verdict |= ATA_EH_SPDN_SPEED_DOWN;
1768
1769         return verdict;
1770 }
1771
1772 /**
1773  *      ata_eh_speed_down - record error and speed down if necessary
1774  *      @dev: Failed device
1775  *      @eflags: mask of ATA_EFLAG_* flags
1776  *      @err_mask: err_mask of the error
1777  *
1778  *      Record error and examine error history to determine whether
1779  *      adjusting transmission speed is necessary.  It also sets
1780  *      transmission limits appropriately if such adjustment is
1781  *      necessary.
1782  *
1783  *      LOCKING:
1784  *      Kernel thread context (may sleep).
1785  *
1786  *      RETURNS:
1787  *      Determined recovery action.
1788  */
1789 static unsigned int ata_eh_speed_down(struct ata_device *dev,
1790                                 unsigned int eflags, unsigned int err_mask)
1791 {
1792         struct ata_link *link = ata_dev_phys_link(dev);
1793         int xfer_ok = 0;
1794         unsigned int verdict;
1795         unsigned int action = 0;
1796
1797         /* don't bother if Cat-0 error */
1798         if (ata_eh_categorize_error(eflags, err_mask, &xfer_ok) == 0)
1799                 return 0;
1800
1801         /* record error and determine whether speed down is necessary */
1802         ata_ering_record(&dev->ering, eflags, err_mask);
1803         verdict = ata_eh_speed_down_verdict(dev);
1804
1805         /* turn off NCQ? */
1806         if ((verdict & ATA_EH_SPDN_NCQ_OFF) &&
1807             (dev->flags & (ATA_DFLAG_PIO | ATA_DFLAG_NCQ |
1808                            ATA_DFLAG_NCQ_OFF)) == ATA_DFLAG_NCQ) {
1809                 dev->flags |= ATA_DFLAG_NCQ_OFF;
1810                 ata_dev_printk(dev, KERN_WARNING,
1811                                "NCQ disabled due to excessive errors\n");
1812                 goto done;
1813         }
1814
1815         /* speed down? */
1816         if (verdict & ATA_EH_SPDN_SPEED_DOWN) {
1817                 /* speed down SATA link speed if possible */
1818                 if (sata_down_spd_limit(link) == 0) {
1819                         action |= ATA_EH_RESET;
1820                         goto done;
1821                 }
1822
1823                 /* lower transfer mode */
1824                 if (dev->spdn_cnt < 2) {
1825                         static const int dma_dnxfer_sel[] =
1826                                 { ATA_DNXFER_DMA, ATA_DNXFER_40C };
1827                         static const int pio_dnxfer_sel[] =
1828                                 { ATA_DNXFER_PIO, ATA_DNXFER_FORCE_PIO0 };
1829                         int sel;
1830
1831                         if (dev->xfer_shift != ATA_SHIFT_PIO)
1832                                 sel = dma_dnxfer_sel[dev->spdn_cnt];
1833                         else
1834                                 sel = pio_dnxfer_sel[dev->spdn_cnt];
1835
1836                         dev->spdn_cnt++;
1837
1838                         if (ata_down_xfermask_limit(dev, sel) == 0) {
1839                                 action |= ATA_EH_RESET;
1840                                 goto done;
1841                         }
1842                 }
1843         }
1844
1845         /* Fall back to PIO?  Slowing down to PIO is meaningless for
1846          * SATA ATA devices.  Consider it only for PATA and SATAPI.
1847          */
1848         if ((verdict & ATA_EH_SPDN_FALLBACK_TO_PIO) && (dev->spdn_cnt >= 2) &&
1849             (link->ap->cbl != ATA_CBL_SATA || dev->class == ATA_DEV_ATAPI) &&
1850             (dev->xfer_shift != ATA_SHIFT_PIO)) {
1851                 if (ata_down_xfermask_limit(dev, ATA_DNXFER_FORCE_PIO) == 0) {
1852                         dev->spdn_cnt = 0;
1853                         action |= ATA_EH_RESET;
1854                         goto done;
1855                 }
1856         }
1857
1858         return 0;
1859  done:
1860         /* device has been slowed down, blow error history */
1861         if (!(verdict & ATA_EH_SPDN_KEEP_ERRORS))
1862                 ata_ering_clear(&dev->ering);
1863         return action;
1864 }
1865
1866 /**
1867  *      ata_eh_link_autopsy - analyze error and determine recovery action
1868  *      @link: host link to perform autopsy on
1869  *
1870  *      Analyze why @link failed and determine which recovery actions
1871  *      are needed.  This function also sets more detailed AC_ERR_*
1872  *      values and fills sense data for ATAPI CHECK SENSE.
1873  *
1874  *      LOCKING:
1875  *      Kernel thread context (may sleep).
1876  */
1877 static void ata_eh_link_autopsy(struct ata_link *link)
1878 {
1879         struct ata_port *ap = link->ap;
1880         struct ata_eh_context *ehc = &link->eh_context;
1881         struct ata_device *dev;
1882         unsigned int all_err_mask = 0, eflags = 0;
1883         int tag;
1884         u32 serror;
1885         int rc;
1886
1887         DPRINTK("ENTER\n");
1888
1889         if (ehc->i.flags & ATA_EHI_NO_AUTOPSY)
1890                 return;
1891
1892         /* obtain and analyze SError */
1893         rc = sata_scr_read(link, SCR_ERROR, &serror);
1894         if (rc == 0) {
1895                 ehc->i.serror |= serror;
1896                 ata_eh_analyze_serror(link);
1897         } else if (rc != -EOPNOTSUPP) {
1898                 /* SError read failed, force reset and probing */
1899                 ehc->i.probe_mask |= ATA_ALL_DEVICES;
1900                 ehc->i.action |= ATA_EH_RESET;
1901                 ehc->i.err_mask |= AC_ERR_OTHER;
1902         }
1903
1904         /* analyze NCQ failure */
1905         ata_eh_analyze_ncq_error(link);
1906
1907         /* any real error trumps AC_ERR_OTHER */
1908         if (ehc->i.err_mask & ~AC_ERR_OTHER)
1909                 ehc->i.err_mask &= ~AC_ERR_OTHER;
1910
1911         all_err_mask |= ehc->i.err_mask;
1912
1913         for (tag = 0; tag < ATA_MAX_QUEUE; tag++) {
1914                 struct ata_queued_cmd *qc = __ata_qc_from_tag(ap, tag);
1915
1916                 if (!(qc->flags & ATA_QCFLAG_FAILED) ||
1917                     ata_dev_phys_link(qc->dev) != link)
1918                         continue;
1919
1920                 /* inherit upper level err_mask */
1921                 qc->err_mask |= ehc->i.err_mask;
1922
1923                 /* analyze TF */
1924                 ehc->i.action |= ata_eh_analyze_tf(qc, &qc->result_tf);
1925
1926                 /* DEV errors are probably spurious in case of ATA_BUS error */
1927                 if (qc->err_mask & AC_ERR_ATA_BUS)
1928                         qc->err_mask &= ~(AC_ERR_DEV | AC_ERR_MEDIA |
1929                                           AC_ERR_INVALID);
1930
1931                 /* any real error trumps unknown error */
1932                 if (qc->err_mask & ~AC_ERR_OTHER)
1933                         qc->err_mask &= ~AC_ERR_OTHER;
1934
1935                 /* SENSE_VALID trumps dev/unknown error and revalidation */
1936                 if (qc->flags & ATA_QCFLAG_SENSE_VALID)
1937                         qc->err_mask &= ~(AC_ERR_DEV | AC_ERR_OTHER);
1938
1939                 /* determine whether the command is worth retrying */
1940                 if (!(qc->err_mask & AC_ERR_INVALID) &&
1941                     ((qc->flags & ATA_QCFLAG_IO) || qc->err_mask != AC_ERR_DEV))
1942                         qc->flags |= ATA_QCFLAG_RETRY;
1943
1944                 /* accumulate error info */
1945                 ehc->i.dev = qc->dev;
1946                 all_err_mask |= qc->err_mask;
1947                 if (qc->flags & ATA_QCFLAG_IO)
1948                         eflags |= ATA_EFLAG_IS_IO;
1949         }
1950
1951         /* enforce default EH actions */
1952         if (ap->pflags & ATA_PFLAG_FROZEN ||
1953             all_err_mask & (AC_ERR_HSM | AC_ERR_TIMEOUT))
1954                 ehc->i.action |= ATA_EH_RESET;
1955         else if (((eflags & ATA_EFLAG_IS_IO) && all_err_mask) ||
1956                  (!(eflags & ATA_EFLAG_IS_IO) && (all_err_mask & ~AC_ERR_DEV)))
1957                 ehc->i.action |= ATA_EH_REVALIDATE;
1958
1959         /* If we have offending qcs and the associated failed device,
1960          * perform per-dev EH action only on the offending device.
1961          */
1962         if (ehc->i.dev) {
1963                 ehc->i.dev_action[ehc->i.dev->devno] |=
1964                         ehc->i.action & ATA_EH_PERDEV_MASK;
1965                 ehc->i.action &= ~ATA_EH_PERDEV_MASK;
1966         }
1967
1968         /* propagate timeout to host link */
1969         if ((all_err_mask & AC_ERR_TIMEOUT) && !ata_is_host_link(link))
1970                 ap->link.eh_context.i.err_mask |= AC_ERR_TIMEOUT;
1971
1972         /* record error and consider speeding down */
1973         dev = ehc->i.dev;
1974         if (!dev && ((ata_link_max_devices(link) == 1 &&
1975                       ata_dev_enabled(link->device))))
1976             dev = link->device;
1977
1978         if (dev) {
1979                 if (dev->flags & ATA_DFLAG_DUBIOUS_XFER)
1980                         eflags |= ATA_EFLAG_DUBIOUS_XFER;
1981                 ehc->i.action |= ata_eh_speed_down(dev, eflags, all_err_mask);
1982         }
1983
1984         DPRINTK("EXIT\n");
1985 }
1986
1987 /**
1988  *      ata_eh_autopsy - analyze error and determine recovery action
1989  *      @ap: host port to perform autopsy on
1990  *
1991  *      Analyze all links of @ap and determine why they failed and
1992  *      which recovery actions are needed.
1993  *
1994  *      LOCKING:
1995  *      Kernel thread context (may sleep).
1996  */
1997 void ata_eh_autopsy(struct ata_port *ap)
1998 {
1999         struct ata_link *link;
2000
2001         ata_port_for_each_link(link, ap)
2002                 ata_eh_link_autopsy(link);
2003
2004         /* Handle the frigging slave link.  Autopsy is done similarly
2005          * but actions and flags are transferred over to the master
2006          * link and handled from there.
2007          */
2008         if (ap->slave_link) {
2009                 struct ata_eh_context *mehc = &ap->link.eh_context;
2010                 struct ata_eh_context *sehc = &ap->slave_link->eh_context;
2011
2012                 ata_eh_link_autopsy(ap->slave_link);
2013
2014                 ata_eh_about_to_do(ap->slave_link, NULL, ATA_EH_ALL_ACTIONS);
2015                 mehc->i.action          |= sehc->i.action;
2016                 mehc->i.dev_action[1]   |= sehc->i.dev_action[1];
2017                 mehc->i.flags           |= sehc->i.flags;
2018                 ata_eh_done(ap->slave_link, NULL, ATA_EH_ALL_ACTIONS);
2019         }
2020
2021         /* Autopsy of fanout ports can affect host link autopsy.
2022          * Perform host link autopsy last.
2023          */
2024         if (sata_pmp_attached(ap))
2025                 ata_eh_link_autopsy(&ap->link);
2026 }
2027
2028 /**
2029  *      ata_eh_link_report - report error handling to user
2030  *      @link: ATA link EH is going on
2031  *
2032  *      Report EH to user.
2033  *
2034  *      LOCKING:
2035  *      None.
2036  */
2037 static void ata_eh_link_report(struct ata_link *link)
2038 {
2039         struct ata_port *ap = link->ap;
2040         struct ata_eh_context *ehc = &link->eh_context;
2041         const char *frozen, *desc;
2042         char tries_buf[6];
2043         int tag, nr_failed = 0;
2044
2045         if (ehc->i.flags & ATA_EHI_QUIET)
2046                 return;
2047
2048         desc = NULL;
2049         if (ehc->i.desc[0] != '\0')
2050                 desc = ehc->i.desc;
2051
2052         for (tag = 0; tag < ATA_MAX_QUEUE; tag++) {
2053                 struct ata_queued_cmd *qc = __ata_qc_from_tag(ap, tag);
2054
2055                 if (!(qc->flags & ATA_QCFLAG_FAILED) ||
2056                     ata_dev_phys_link(qc->dev) != link ||
2057                     ((qc->flags & ATA_QCFLAG_QUIET) &&
2058                      qc->err_mask == AC_ERR_DEV))
2059                         continue;
2060                 if (qc->flags & ATA_QCFLAG_SENSE_VALID && !qc->err_mask)
2061                         continue;
2062
2063                 nr_failed++;
2064         }
2065
2066         if (!nr_failed && !ehc->i.err_mask)
2067                 return;
2068
2069         frozen = "";
2070         if (ap->pflags & ATA_PFLAG_FROZEN)
2071                 frozen = " frozen";
2072
2073         memset(tries_buf, 0, sizeof(tries_buf));
2074         if (ap->eh_tries < ATA_EH_MAX_TRIES)
2075                 snprintf(tries_buf, sizeof(tries_buf) - 1, " t%d",
2076                          ap->eh_tries);
2077
2078         if (ehc->i.dev) {
2079                 ata_dev_printk(ehc->i.dev, KERN_ERR, "exception Emask 0x%x "
2080                                "SAct 0x%x SErr 0x%x action 0x%x%s%s\n",
2081                                ehc->i.err_mask, link->sactive, ehc->i.serror,
2082                                ehc->i.action, frozen, tries_buf);
2083                 if (desc)
2084                         ata_dev_printk(ehc->i.dev, KERN_ERR, "%s\n", desc);
2085         } else {
2086                 ata_link_printk(link, KERN_ERR, "exception Emask 0x%x "
2087                                 "SAct 0x%x SErr 0x%x action 0x%x%s%s\n",
2088                                 ehc->i.err_mask, link->sactive, ehc->i.serror,
2089                                 ehc->i.action, frozen, tries_buf);
2090                 if (desc)
2091                         ata_link_printk(link, KERN_ERR, "%s\n", desc);
2092         }
2093
2094         if (ehc->i.serror)
2095                 ata_link_printk(link, KERN_ERR,
2096                   "SError: { %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s}\n",
2097                   ehc->i.serror & SERR_DATA_RECOVERED ? "RecovData " : "",
2098                   ehc->i.serror & SERR_COMM_RECOVERED ? "RecovComm " : "",
2099                   ehc->i.serror & SERR_DATA ? "UnrecovData " : "",
2100                   ehc->i.serror & SERR_PERSISTENT ? "Persist " : "",
2101                   ehc->i.serror & SERR_PROTOCOL ? "Proto " : "",
2102                   ehc->i.serror & SERR_INTERNAL ? "HostInt " : "",
2103                   ehc->i.serror & SERR_PHYRDY_CHG ? "PHYRdyChg " : "",
2104                   ehc->i.serror & SERR_PHY_INT_ERR ? "PHYInt " : "",
2105                   ehc->i.serror & SERR_COMM_WAKE ? "CommWake " : "",
2106                   ehc->i.serror & SERR_10B_8B_ERR ? "10B8B " : "",
2107                   ehc->i.serror & SERR_DISPARITY ? "Dispar " : "",
2108                   ehc->i.serror & SERR_CRC ? "BadCRC " : "",
2109                   ehc->i.serror & SERR_HANDSHAKE ? "Handshk " : "",
2110                   ehc->i.serror & SERR_LINK_SEQ_ERR ? "LinkSeq " : "",
2111                   ehc->i.serror & SERR_TRANS_ST_ERROR ? "TrStaTrns " : "",
2112                   ehc->i.serror & SERR_UNRECOG_FIS ? "UnrecFIS " : "",
2113                   ehc->i.serror & SERR_DEV_XCHG ? "DevExch " : "");
2114
2115         for (tag = 0; tag < ATA_MAX_QUEUE; tag++) {
2116                 struct ata_queued_cmd *qc = __ata_qc_from_tag(ap, tag);
2117                 struct ata_taskfile *cmd = &qc->tf, *res = &qc->result_tf;
2118                 const u8 *cdb = qc->cdb;
2119                 char data_buf[20] = "";
2120                 char cdb_buf[70] = "";
2121
2122                 if (!(qc->flags & ATA_QCFLAG_FAILED) ||
2123                     ata_dev_phys_link(qc->dev) != link || !qc->err_mask)
2124                         continue;
2125
2126                 if (qc->dma_dir != DMA_NONE) {
2127                         static const char *dma_str[] = {
2128                                 [DMA_BIDIRECTIONAL]     = "bidi",
2129                                 [DMA_TO_DEVICE]         = "out",
2130                                 [DMA_FROM_DEVICE]       = "in",
2131                         };
2132                         static const char *prot_str[] = {
2133                                 [ATA_PROT_PIO]          = "pio",
2134                                 [ATA_PROT_DMA]          = "dma",
2135                                 [ATA_PROT_NCQ]          = "ncq",
2136                                 [ATAPI_PROT_PIO]        = "pio",
2137                                 [ATAPI_PROT_DMA]        = "dma",
2138                         };
2139
2140                         snprintf(data_buf, sizeof(data_buf), " %s %u %s",
2141                                  prot_str[qc->tf.protocol], qc->nbytes,
2142                                  dma_str[qc->dma_dir]);
2143                 }
2144
2145                 if (ata_is_atapi(qc->tf.protocol))
2146                         snprintf(cdb_buf, sizeof(cdb_buf),
2147                                  "cdb %02x %02x %02x %02x %02x %02x %02x %02x  "
2148                                  "%02x %02x %02x %02x %02x %02x %02x %02x\n         ",
2149                                  cdb[0], cdb[1], cdb[2], cdb[3],
2150                                  cdb[4], cdb[5], cdb[6], cdb[7],
2151                                  cdb[8], cdb[9], cdb[10], cdb[11],
2152                                  cdb[12], cdb[13], cdb[14], cdb[15]);
2153
2154                 ata_dev_printk(qc->dev, KERN_ERR,
2155                         "cmd %02x/%02x:%02x:%02x:%02x:%02x/%02x:%02x:%02x:%02x:%02x/%02x "
2156                         "tag %d%s\n         %s"
2157                         "res %02x/%02x:%02x:%02x:%02x:%02x/%02x:%02x:%02x:%02x:%02x/%02x "
2158                         "Emask 0x%x (%s)%s\n",
2159                         cmd->command, cmd->feature, cmd->nsect,
2160                         cmd->lbal, cmd->lbam, cmd->lbah,
2161                         cmd->hob_feature, cmd->hob_nsect,
2162                         cmd->hob_lbal, cmd->hob_lbam, cmd->hob_lbah,
2163                         cmd->device, qc->tag, data_buf, cdb_buf,
2164                         res->command, res->feature, res->nsect,
2165                         res->lbal, res->lbam, res->lbah,
2166                         res->hob_feature, res->hob_nsect,
2167                         res->hob_lbal, res->hob_lbam, res->hob_lbah,
2168                         res->device, qc->err_mask, ata_err_string(qc->err_mask),
2169                         qc->err_mask & AC_ERR_NCQ ? " <F>" : "");
2170
2171                 if (res->command & (ATA_BUSY | ATA_DRDY | ATA_DF | ATA_DRQ |
2172                                     ATA_ERR)) {
2173                         if (res->command & ATA_BUSY)
2174                                 ata_dev_printk(qc->dev, KERN_ERR,
2175                                   "status: { Busy }\n");
2176                         else
2177                                 ata_dev_printk(qc->dev, KERN_ERR,
2178                                   "status: { %s%s%s%s}\n",
2179                                   res->command & ATA_DRDY ? "DRDY " : "",
2180                                   res->command & ATA_DF ? "DF " : "",
2181                                   res->command & ATA_DRQ ? "DRQ " : "",
2182                                   res->command & ATA_ERR ? "ERR " : "");
2183                 }
2184
2185                 if (cmd->command != ATA_CMD_PACKET &&
2186                     (res->feature & (ATA_ICRC | ATA_UNC | ATA_IDNF |
2187                                      ATA_ABORTED)))
2188                         ata_dev_printk(qc->dev, KERN_ERR,
2189                           "error: { %s%s%s%s}\n",
2190                           res->feature & ATA_ICRC ? "ICRC " : "",
2191                           res->feature & ATA_UNC ? "UNC " : "",
2192                           res->feature & ATA_IDNF ? "IDNF " : "",
2193                           res->feature & ATA_ABORTED ? "ABRT " : "");
2194         }
2195 }
2196
2197 /**
2198  *      ata_eh_report - report error handling to user
2199  *      @ap: ATA port to report EH about
2200  *
2201  *      Report EH to user.
2202  *
2203  *      LOCKING:
2204  *      None.
2205  */
2206 void ata_eh_report(struct ata_port *ap)
2207 {
2208         struct ata_link *link;
2209
2210         __ata_port_for_each_link(link, ap)
2211                 ata_eh_link_report(link);
2212 }
2213
2214 static int ata_do_reset(struct ata_link *link, ata_reset_fn_t reset,
2215                         unsigned int *classes, unsigned long deadline,
2216                         bool clear_classes)
2217 {
2218         struct ata_device *dev;
2219
2220         if (clear_classes)
2221                 ata_link_for_each_dev(dev, link)
2222                         classes[dev->devno] = ATA_DEV_UNKNOWN;
2223
2224         return reset(link, classes, deadline);
2225 }
2226
2227 static int ata_eh_followup_srst_needed(struct ata_link *link,
2228                                        int rc, const unsigned int *classes)
2229 {
2230         if ((link->flags & ATA_LFLAG_NO_SRST) || ata_link_offline(link))
2231                 return 0;
2232         if (rc == -EAGAIN)
2233                 return 1;
2234         if (sata_pmp_supported(link->ap) && ata_is_host_link(link))
2235                 return 1;
2236         return 0;
2237 }
2238
2239 int ata_eh_reset(struct ata_link *link, int classify,
2240                  ata_prereset_fn_t prereset, ata_reset_fn_t softreset,
2241                  ata_reset_fn_t hardreset, ata_postreset_fn_t postreset)
2242 {
2243         struct ata_port *ap = link->ap;
2244         struct ata_link *slave = ap->slave_link;
2245         struct ata_eh_context *ehc = &link->eh_context;
2246         struct ata_eh_context *sehc = &slave->eh_context;
2247         unsigned int *classes = ehc->classes;
2248         unsigned int lflags = link->flags;
2249         int verbose = !(ehc->i.flags & ATA_EHI_QUIET);
2250         int max_tries = 0, try = 0;
2251         struct ata_link *failed_link;
2252         struct ata_device *dev;
2253         unsigned long deadline, now;
2254         ata_reset_fn_t reset;
2255         unsigned long flags;
2256         u32 sstatus;
2257         int nr_unknown, rc;
2258
2259         /*
2260          * Prepare to reset
2261          */
2262         while (ata_eh_reset_timeouts[max_tries] != ULONG_MAX)
2263                 max_tries++;
2264         if (link->flags & ATA_LFLAG_NO_HRST)
2265                 hardreset = NULL;
2266         if (link->flags & ATA_LFLAG_NO_SRST)
2267                 softreset = NULL;
2268
2269         now = jiffies;
2270         deadline = ata_deadline(ehc->last_reset, ATA_EH_RESET_COOL_DOWN);
2271         if (time_before(now, deadline))
2272                 schedule_timeout_uninterruptible(deadline - now);
2273
2274         spin_lock_irqsave(ap->lock, flags);
2275         ap->pflags |= ATA_PFLAG_RESETTING;
2276         spin_unlock_irqrestore(ap->lock, flags);
2277
2278         ata_eh_about_to_do(link, NULL, ATA_EH_RESET);
2279         ehc->last_reset = jiffies;
2280
2281         ata_link_for_each_dev(dev, link) {
2282                 /* If we issue an SRST then an ATA drive (not ATAPI)
2283                  * may change configuration and be in PIO0 timing. If
2284                  * we do a hard reset (or are coming from power on)
2285                  * this is true for ATA or ATAPI. Until we've set a
2286                  * suitable controller mode we should not touch the
2287                  * bus as we may be talking too fast.
2288                  */
2289                 dev->pio_mode = XFER_PIO_0;
2290
2291                 /* If the controller has a pio mode setup function
2292                  * then use it to set the chipset to rights. Don't
2293                  * touch the DMA setup as that will be dealt with when
2294                  * configuring devices.
2295                  */
2296                 if (ap->ops->set_piomode)
2297                         ap->ops->set_piomode(ap, dev);
2298         }
2299
2300         /* prefer hardreset */
2301         reset = NULL;
2302         ehc->i.action &= ~ATA_EH_RESET;
2303         if (hardreset) {
2304                 reset = hardreset;
2305                 ehc->i.action |= ATA_EH_HARDRESET;
2306         } else if (softreset) {
2307                 reset = softreset;
2308                 ehc->i.action |= ATA_EH_SOFTRESET;
2309         }
2310
2311         if (prereset) {
2312                 unsigned long deadline = ata_deadline(jiffies,
2313                                                       ATA_EH_PRERESET_TIMEOUT);
2314
2315                 if (slave) {
2316                         sehc->i.action &= ~ATA_EH_RESET;
2317                         sehc->i.action |= ehc->i.action;
2318                 }
2319
2320                 rc = prereset(link, deadline);
2321
2322                 /* If present, do prereset on slave link too.  Reset
2323                  * is skipped iff both master and slave links report
2324                  * -ENOENT or clear ATA_EH_RESET.
2325                  */
2326                 if (slave && (rc == 0 || rc == -ENOENT)) {
2327                         int tmp;
2328
2329                         tmp = prereset(slave, deadline);
2330                         if (tmp != -ENOENT)
2331                                 rc = tmp;
2332
2333                         ehc->i.action |= sehc->i.action;
2334                 }
2335
2336                 if (rc) {
2337                         if (rc == -ENOENT) {
2338                                 ata_link_printk(link, KERN_DEBUG,
2339                                                 "port disabled. ignoring.\n");
2340                                 ehc->i.action &= ~ATA_EH_RESET;
2341
2342                                 ata_link_for_each_dev(dev, link)
2343                                         classes[dev->devno] = ATA_DEV_NONE;
2344
2345                                 rc = 0;
2346                         } else
2347                                 ata_link_printk(link, KERN_ERR,
2348                                         "prereset failed (errno=%d)\n", rc);
2349                         goto out;
2350                 }
2351
2352                 /* prereset() might have cleared ATA_EH_RESET.  If so,
2353                  * bang classes and return.
2354                  */
2355                 if (reset && !(ehc->i.action & ATA_EH_RESET)) {
2356                         ata_link_for_each_dev(dev, link)
2357                                 classes[dev->devno] = ATA_DEV_NONE;
2358                         rc = 0;
2359                         goto out;
2360                 }
2361         }
2362
2363  retry:
2364         /*
2365          * Perform reset
2366          */
2367         ehc->last_reset = jiffies;
2368         if (ata_is_host_link(link))
2369                 ata_eh_freeze_port(ap);
2370
2371         deadline = ata_deadline(jiffies, ata_eh_reset_timeouts[try++]);
2372
2373         if (reset) {
2374                 if (verbose)
2375                         ata_link_printk(link, KERN_INFO, "%s resetting link\n",
2376                                         reset == softreset ? "soft" : "hard");
2377
2378                 /* mark that this EH session started with reset */
2379                 if (reset == hardreset)
2380                         ehc->i.flags |= ATA_EHI_DID_HARDRESET;
2381                 else
2382                         ehc->i.flags |= ATA_EHI_DID_SOFTRESET;
2383
2384                 rc = ata_do_reset(link, reset, classes, deadline, true);
2385                 if (rc && rc != -EAGAIN) {
2386                         failed_link = link;
2387                         goto fail;
2388                 }
2389
2390                 /* hardreset slave link if existent */
2391                 if (slave && reset == hardreset) {
2392                         int tmp;
2393
2394                         if (verbose)
2395                                 ata_link_printk(slave, KERN_INFO,
2396                                                 "hard resetting link\n");
2397
2398                         ata_eh_about_to_do(slave, NULL, ATA_EH_RESET);
2399                         tmp = ata_do_reset(slave, reset, classes, deadline,
2400                                            false);
2401                         switch (tmp) {
2402                         case -EAGAIN:
2403                                 rc = -EAGAIN;
2404                         case 0:
2405                                 break;
2406                         default:
2407                                 failed_link = slave;
2408                                 rc = tmp;
2409                                 goto fail;
2410                         }
2411                 }
2412
2413                 /* perform follow-up SRST if necessary */
2414                 if (reset == hardreset &&
2415                     ata_eh_followup_srst_needed(link, rc, classes)) {
2416                         reset = softreset;
2417
2418                         if (!reset) {
2419                                 ata_link_printk(link, KERN_ERR,
2420                                                 "follow-up softreset required "
2421                                                 "but no softreset avaliable\n");
2422                                 failed_link = link;
2423                                 rc = -EINVAL;
2424                                 goto fail;
2425                         }
2426
2427                         ata_eh_about_to_do(link, NULL, ATA_EH_RESET);
2428                         rc = ata_do_reset(link, reset, classes, deadline, true);
2429                 }
2430         } else {
2431                 if (verbose)
2432                         ata_link_printk(link, KERN_INFO, "no reset method "
2433                                         "available, skipping reset\n");
2434                 if (!(lflags & ATA_LFLAG_ASSUME_CLASS))
2435                         lflags |= ATA_LFLAG_ASSUME_ATA;
2436         }
2437
2438         /*
2439          * Post-reset processing
2440          */
2441         ata_link_for_each_dev(dev, link) {
2442                 /* After the reset, the device state is PIO 0 and the
2443                  * controller state is undefined.  Reset also wakes up
2444                  * drives from sleeping mode.
2445                  */
2446                 dev->pio_mode = XFER_PIO_0;
2447                 dev->flags &= ~ATA_DFLAG_SLEEPING;
2448
2449                 if (ata_phys_link_offline(ata_dev_phys_link(dev)))
2450                         continue;
2451
2452                 /* apply class override */
2453                 if (lflags & ATA_LFLAG_ASSUME_ATA)
2454                         classes[dev->devno] = ATA_DEV_ATA;
2455                 else if (lflags & ATA_LFLAG_ASSUME_SEMB)
2456                         classes[dev->devno] = ATA_DEV_SEMB_UNSUP; /* not yet */
2457         }
2458
2459         /* record current link speed */
2460         if (sata_scr_read(link, SCR_STATUS, &sstatus) == 0)
2461                 link->sata_spd = (sstatus >> 4) & 0xf;
2462         if (slave && sata_scr_read(slave, SCR_STATUS, &sstatus) == 0)
2463                 slave->sata_spd = (sstatus >> 4) & 0xf;
2464
2465         /* thaw the port */
2466         if (ata_is_host_link(link))
2467                 ata_eh_thaw_port(ap);
2468
2469         /* postreset() should clear hardware SError.  Although SError
2470          * is cleared during link resume, clearing SError here is
2471          * necessary as some PHYs raise hotplug events after SRST.
2472          * This introduces race condition where hotplug occurs between
2473          * reset and here.  This race is mediated by cross checking
2474          * link onlineness and classification result later.
2475          */
2476         if (postreset) {
2477                 postreset(link, classes);
2478                 if (slave)
2479                         postreset(slave, classes);
2480         }
2481
2482         /* clear cached SError */
2483         spin_lock_irqsave(link->ap->lock, flags);
2484         link->eh_info.serror = 0;
2485         if (slave)
2486                 slave->eh_info.serror = 0;
2487         spin_unlock_irqrestore(link->ap->lock, flags);
2488
2489         /* Make sure onlineness and classification result correspond.
2490          * Hotplug could have happened during reset and some
2491          * controllers fail to wait while a drive is spinning up after
2492          * being hotplugged causing misdetection.  By cross checking
2493          * link onlineness and classification result, those conditions
2494          * can be reliably detected and retried.
2495          */
2496         nr_unknown = 0;
2497         ata_link_for_each_dev(dev, link) {
2498                 /* convert all ATA_DEV_UNKNOWN to ATA_DEV_NONE */
2499                 if (classes[dev->devno] == ATA_DEV_UNKNOWN) {
2500                         classes[dev->devno] = ATA_DEV_NONE;
2501                         if (ata_phys_link_online(ata_dev_phys_link(dev)))
2502                                 nr_unknown++;
2503                 }
2504         }
2505
2506         if (classify && nr_unknown) {
2507                 if (try < max_tries) {
2508                         ata_link_printk(link, KERN_WARNING, "link online but "
2509                                        "device misclassified, retrying\n");
2510                         failed_link = link;
2511                         rc = -EAGAIN;
2512                         goto fail;
2513                 }
2514                 ata_link_printk(link, KERN_WARNING,
2515                                "link online but device misclassified, "
2516                                "device detection might fail\n");
2517         }
2518
2519         /* reset successful, schedule revalidation */
2520         ata_eh_done(link, NULL, ATA_EH_RESET);
2521         if (slave)
2522                 ata_eh_done(slave, NULL, ATA_EH_RESET);
2523         ehc->last_reset = jiffies;
2524         ehc->i.action |= ATA_EH_REVALIDATE;
2525
2526         rc = 0;
2527  out:
2528         /* clear hotplug flag */
2529         ehc->i.flags &= ~ATA_EHI_HOTPLUGGED;
2530         if (slave)
2531                 sehc->i.flags &= ~ATA_EHI_HOTPLUGGED;
2532
2533         spin_lock_irqsave(ap->lock, flags);
2534         ap->pflags &= ~ATA_PFLAG_RESETTING;
2535         spin_unlock_irqrestore(ap->lock, flags);
2536
2537         return rc;
2538
2539  fail:
2540         /* if SCR isn't accessible on a fan-out port, PMP needs to be reset */
2541         if (!ata_is_host_link(link) &&
2542             sata_scr_read(link, SCR_STATUS, &sstatus))
2543                 rc = -ERESTART;
2544
2545         if (rc == -ERESTART || try >= max_tries)
2546                 goto out;
2547
2548         now = jiffies;
2549         if (time_before(now, deadline)) {
2550                 unsigned long delta = deadline - now;
2551
2552                 ata_link_printk(failed_link, KERN_WARNING,
2553                         "reset failed (errno=%d), retrying in %u secs\n",
2554                         rc, DIV_ROUND_UP(jiffies_to_msecs(delta), 1000));
2555
2556                 while (delta)
2557                         delta = schedule_timeout_uninterruptible(delta);
2558         }
2559
2560         if (try == max_tries - 1) {
2561                 sata_down_spd_limit(link);
2562                 if (slave)
2563                         sata_down_spd_limit(slave);
2564         } else if (rc == -EPIPE)
2565                 sata_down_spd_limit(failed_link);
2566
2567         if (hardreset)
2568                 reset = hardreset;
2569         goto retry;
2570 }
2571
2572 static inline void ata_eh_pull_park_action(struct ata_port *ap)
2573 {
2574         struct ata_link *link;
2575         struct ata_device *dev;
2576         unsigned long flags;
2577
2578         /*
2579          * This function can be thought of as an extended version of
2580          * ata_eh_about_to_do() specially crafted to accommodate the
2581          * requirements of ATA_EH_PARK handling. Since the EH thread
2582          * does not leave the do {} while () loop in ata_eh_recover as
2583          * long as the timeout for a park request to *one* device on
2584          * the port has not expired, and since we still want to pick
2585          * up park requests to other devices on the same port or
2586          * timeout updates for the same device, we have to pull
2587          * ATA_EH_PARK actions from eh_info into eh_context.i
2588          * ourselves at the beginning of each pass over the loop.
2589          *
2590          * Additionally, all write accesses to &ap->park_req_pending
2591          * through INIT_COMPLETION() (see below) or complete_all()
2592          * (see ata_scsi_park_store()) are protected by the host lock.
2593          * As a result we have that park_req_pending.done is zero on
2594          * exit from this function, i.e. when ATA_EH_PARK actions for
2595          * *all* devices on port ap have been pulled into the
2596          * respective eh_context structs. If, and only if,
2597          * park_req_pending.done is non-zero by the time we reach
2598          * wait_for_completion_timeout(), another ATA_EH_PARK action
2599          * has been scheduled for at least one of the devices on port
2600          * ap and we have to cycle over the do {} while () loop in
2601          * ata_eh_recover() again.
2602          */
2603
2604         spin_lock_irqsave(ap->lock, flags);
2605         INIT_COMPLETION(ap->park_req_pending);
2606         ata_port_for_each_link(link, ap) {
2607                 ata_link_for_each_dev(dev, link) {
2608                         struct ata_eh_info *ehi = &link->eh_info;
2609
2610                         link->eh_context.i.dev_action[dev->devno] |=
2611                                 ehi->dev_action[dev->devno] & ATA_EH_PARK;
2612                         ata_eh_clear_action(link, dev, ehi, ATA_EH_PARK);
2613                 }
2614         }
2615         spin_unlock_irqrestore(ap->lock, flags);
2616 }
2617
2618 static void ata_eh_park_issue_cmd(struct ata_device *dev, int park)
2619 {
2620         struct ata_eh_context *ehc = &dev->link->eh_context;
2621         struct ata_taskfile tf;
2622         unsigned int err_mask;
2623
2624         ata_tf_init(dev, &tf);
2625         if (park) {
2626                 ehc->unloaded_mask |= 1 << dev->devno;
2627                 tf.command = ATA_CMD_IDLEIMMEDIATE;
2628                 tf.feature = 0x44;
2629                 tf.lbal = 0x4c;
2630                 tf.lbam = 0x4e;
2631                 tf.lbah = 0x55;
2632         } else {
2633                 ehc->unloaded_mask &= ~(1 << dev->devno);
2634                 tf.command = ATA_CMD_CHK_POWER;
2635         }
2636
2637         tf.flags |= ATA_TFLAG_DEVICE | ATA_TFLAG_ISADDR;
2638         tf.protocol |= ATA_PROT_NODATA;
2639         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
2640         if (park && (err_mask || tf.lbal != 0xc4)) {
2641                 ata_dev_printk(dev, KERN_ERR, "head unload failed!\n");
2642                 ehc->unloaded_mask &= ~(1 << dev->devno);
2643         }
2644 }
2645
2646 static int ata_eh_revalidate_and_attach(struct ata_link *link,
2647                                         struct ata_device **r_failed_dev)
2648 {
2649         struct ata_port *ap = link->ap;
2650         struct ata_eh_context *ehc = &link->eh_context;
2651         struct ata_device *dev;
2652         unsigned int new_mask = 0;
2653         unsigned long flags;
2654         int rc = 0;
2655
2656         DPRINTK("ENTER\n");
2657
2658         /* For PATA drive side cable detection to work, IDENTIFY must
2659          * be done backwards such that PDIAG- is released by the slave
2660          * device before the master device is identified.
2661          */
2662         ata_link_for_each_dev_reverse(dev, link) {
2663                 unsigned int action = ata_eh_dev_action(dev);
2664                 unsigned int readid_flags = 0;
2665
2666                 if (ehc->i.flags & ATA_EHI_DID_RESET)
2667                         readid_flags |= ATA_READID_POSTRESET;
2668
2669                 if ((action & ATA_EH_REVALIDATE) && ata_dev_enabled(dev)) {
2670                         WARN_ON(dev->class == ATA_DEV_PMP);
2671
2672                         if (ata_phys_link_offline(ata_dev_phys_link(dev))) {
2673                                 rc = -EIO;
2674                                 goto err;
2675                         }
2676
2677                         ata_eh_about_to_do(link, dev, ATA_EH_REVALIDATE);
2678                         rc = ata_dev_revalidate(dev, ehc->classes[dev->devno],
2679                                                 readid_flags);
2680                         if (rc)
2681                                 goto err;
2682
2683                         ata_eh_done(link, dev, ATA_EH_REVALIDATE);
2684
2685                         /* Configuration may have changed, reconfigure
2686                          * transfer mode.
2687                          */
2688                         ehc->i.flags |= ATA_EHI_SETMODE;
2689
2690                         /* schedule the scsi_rescan_device() here */
2691                         queue_work(ata_aux_wq, &(ap->scsi_rescan_task));
2692                 } else if (dev->class == ATA_DEV_UNKNOWN &&
2693                            ehc->tries[dev->devno] &&
2694                            ata_class_enabled(ehc->classes[dev->devno])) {
2695                         dev->class = ehc->classes[dev->devno];
2696
2697                         if (dev->class == ATA_DEV_PMP)
2698                                 rc = sata_pmp_attach(dev);
2699                         else
2700                                 rc = ata_dev_read_id(dev, &dev->class,
2701                                                      readid_flags, dev->id);
2702                         switch (rc) {
2703                         case 0:
2704                                 new_mask |= 1 << dev->devno;
2705                                 break;
2706                         case -ENOENT:
2707                                 /* IDENTIFY was issued to non-existent
2708                                  * device.  No need to reset.  Just
2709                                  * thaw and kill the device.
2710                                  */
2711                                 ata_eh_thaw_port(ap);
2712                                 dev->class = ATA_DEV_UNKNOWN;
2713                                 break;
2714                         default:
2715                                 dev->class = ATA_DEV_UNKNOWN;
2716                                 goto err;
2717                         }
2718                 }
2719         }
2720
2721         /* PDIAG- should have been released, ask cable type if post-reset */
2722         if ((ehc->i.flags & ATA_EHI_DID_RESET) && ata_is_host_link(link)) {
2723                 if (ap->ops->cable_detect)
2724                         ap->cbl = ap->ops->cable_detect(ap);
2725                 ata_force_cbl(ap);
2726         }
2727
2728         /* Configure new devices forward such that user doesn't see
2729          * device detection messages backwards.
2730          */
2731         ata_link_for_each_dev(dev, link) {
2732                 if (!(new_mask & (1 << dev->devno)) ||
2733                     dev->class == ATA_DEV_PMP)
2734                         continue;
2735
2736                 ehc->i.flags |= ATA_EHI_PRINTINFO;
2737                 rc = ata_dev_configure(dev);
2738                 ehc->i.flags &= ~ATA_EHI_PRINTINFO;
2739                 if (rc)
2740                         goto err;
2741
2742                 spin_lock_irqsave(ap->lock, flags);
2743                 ap->pflags |= ATA_PFLAG_SCSI_HOTPLUG;
2744                 spin_unlock_irqrestore(ap->lock, flags);
2745
2746                 /* new device discovered, configure xfermode */
2747                 ehc->i.flags |= ATA_EHI_SETMODE;
2748         }
2749
2750         return 0;
2751
2752  err:
2753         *r_failed_dev = dev;
2754         DPRINTK("EXIT rc=%d\n", rc);
2755         return rc;
2756 }
2757
2758 /**
2759  *      ata_set_mode - Program timings and issue SET FEATURES - XFER
2760  *      @link: link on which timings will be programmed
2761  *      @r_failed_dev: out paramter for failed device
2762  *
2763  *      Set ATA device disk transfer mode (PIO3, UDMA6, etc.).  If
2764  *      ata_set_mode() fails, pointer to the failing device is
2765  *      returned in @r_failed_dev.
2766  *
2767  *      LOCKING:
2768  *      PCI/etc. bus probe sem.
2769  *
2770  *      RETURNS:
2771  *      0 on success, negative errno otherwise
2772  */
2773 int ata_set_mode(struct ata_link *link, struct ata_device **r_failed_dev)
2774 {
2775         struct ata_port *ap = link->ap;
2776         struct ata_device *dev;
2777         int rc;
2778
2779         /* if data transfer is verified, clear DUBIOUS_XFER on ering top */
2780         ata_link_for_each_dev(dev, link) {
2781                 if (!(dev->flags & ATA_DFLAG_DUBIOUS_XFER)) {
2782                         struct ata_ering_entry *ent;
2783
2784                         ent = ata_ering_top(&dev->ering);
2785                         if (ent)
2786                                 ent->eflags &= ~ATA_EFLAG_DUBIOUS_XFER;
2787                 }
2788         }
2789
2790         /* has private set_mode? */
2791         if (ap->ops->set_mode)
2792                 rc = ap->ops->set_mode(link, r_failed_dev);
2793         else
2794                 rc = ata_do_set_mode(link, r_failed_dev);
2795
2796         /* if transfer mode has changed, set DUBIOUS_XFER on device */
2797         ata_link_for_each_dev(dev, link) {
2798                 struct ata_eh_context *ehc = &link->eh_context;
2799                 u8 saved_xfer_mode = ehc->saved_xfer_mode[dev->devno];
2800                 u8 saved_ncq = !!(ehc->saved_ncq_enabled & (1 << dev->devno));
2801
2802                 if (dev->xfer_mode != saved_xfer_mode ||
2803                     ata_ncq_enabled(dev) != saved_ncq)
2804                         dev->flags |= ATA_DFLAG_DUBIOUS_XFER;
2805         }
2806
2807         return rc;
2808 }
2809
2810 /**
2811  *      atapi_eh_clear_ua - Clear ATAPI UNIT ATTENTION after reset
2812  *      @dev: ATAPI device to clear UA for
2813  *
2814  *      Resets and other operations can make an ATAPI device raise
2815  *      UNIT ATTENTION which causes the next operation to fail.  This
2816  *      function clears UA.
2817  *
2818  *      LOCKING:
2819  *      EH context (may sleep).
2820  *
2821  *      RETURNS:
2822  *      0 on success, -errno on failure.
2823  */
2824 static int atapi_eh_clear_ua(struct ata_device *dev)
2825 {
2826         int i;
2827
2828         for (i = 0; i < ATA_EH_UA_TRIES; i++) {
2829                 u8 sense_buffer[SCSI_SENSE_BUFFERSIZE];
2830                 u8 sense_key = 0;
2831                 unsigned int err_mask;
2832
2833                 err_mask = atapi_eh_tur(dev, &sense_key);
2834                 if (err_mask != 0 && err_mask != AC_ERR_DEV) {
2835                         ata_dev_printk(dev, KERN_WARNING, "TEST_UNIT_READY "
2836                                 "failed (err_mask=0x%x)\n", err_mask);
2837                         return -EIO;
2838                 }
2839
2840                 if (!err_mask || sense_key != UNIT_ATTENTION)
2841                         return 0;
2842
2843                 err_mask = atapi_eh_request_sense(dev, sense_buffer, sense_key);
2844                 if (err_mask) {
2845                         ata_dev_printk(dev, KERN_WARNING, "failed to clear "
2846                                 "UNIT ATTENTION (err_mask=0x%x)\n", err_mask);
2847                         return -EIO;
2848                 }
2849         }
2850
2851         ata_dev_printk(dev, KERN_WARNING,
2852                 "UNIT ATTENTION persists after %d tries\n", ATA_EH_UA_TRIES);
2853
2854         return 0;
2855 }
2856
2857 static int ata_link_nr_enabled(struct ata_link *link)
2858 {
2859         struct ata_device *dev;
2860         int cnt = 0;
2861
2862         ata_link_for_each_dev(dev, link)
2863                 if (ata_dev_enabled(dev))
2864                         cnt++;
2865         return cnt;
2866 }
2867
2868 static int ata_link_nr_vacant(struct ata_link *link)
2869 {
2870         struct ata_device *dev;
2871         int cnt = 0;
2872
2873         ata_link_for_each_dev(dev, link)
2874                 if (dev->class == ATA_DEV_UNKNOWN)
2875                         cnt++;
2876         return cnt;
2877 }
2878
2879 static int ata_eh_skip_recovery(struct ata_link *link)
2880 {
2881         struct ata_port *ap = link->ap;
2882         struct ata_eh_context *ehc = &link->eh_context;
2883         struct ata_device *dev;
2884
2885         /* skip disabled links */
2886         if (link->flags & ATA_LFLAG_DISABLED)
2887                 return 1;
2888
2889         /* thaw frozen port and recover failed devices */
2890         if ((ap->pflags & ATA_PFLAG_FROZEN) || ata_link_nr_enabled(link))
2891                 return 0;
2892
2893         /* reset at least once if reset is requested */
2894         if ((ehc->i.action & ATA_EH_RESET) &&
2895             !(ehc->i.flags & ATA_EHI_DID_RESET))
2896                 return 0;
2897
2898         /* skip if class codes for all vacant slots are ATA_DEV_NONE */
2899         ata_link_for_each_dev(dev, link) {
2900                 if (dev->class == ATA_DEV_UNKNOWN &&
2901                     ehc->classes[dev->devno] != ATA_DEV_NONE)
2902                         return 0;
2903         }
2904
2905         return 1;
2906 }
2907
2908 static int ata_eh_schedule_probe(struct ata_device *dev)
2909 {
2910         struct ata_eh_context *ehc = &dev->link->eh_context;
2911
2912         if (!(ehc->i.probe_mask & (1 << dev->devno)) ||
2913             (ehc->did_probe_mask & (1 << dev->devno)))
2914                 return 0;
2915
2916         ata_eh_detach_dev(dev);
2917         ata_dev_init(dev);
2918         ehc->did_probe_mask |= (1 << dev->devno);
2919         ehc->i.action |= ATA_EH_RESET;
2920         ehc->saved_xfer_mode[dev->devno] = 0;
2921         ehc->saved_ncq_enabled &= ~(1 << dev->devno);
2922
2923         return 1;
2924 }
2925
2926 static int ata_eh_handle_dev_fail(struct ata_device *dev, int err)
2927 {
2928         struct ata_eh_context *ehc = &dev->link->eh_context;
2929
2930         ehc->tries[dev->devno]--;
2931
2932         switch (err) {
2933         case -ENODEV:
2934                 /* device missing or wrong IDENTIFY data, schedule probing */
2935                 ehc->i.probe_mask |= (1 << dev->devno);
2936         case -EINVAL:
2937                 /* give it just one more chance */
2938                 ehc->tries[dev->devno] = min(ehc->tries[dev->devno], 1);
2939         case -EIO:
2940                 if (ehc->tries[dev->devno] == 1 && dev->pio_mode > XFER_PIO_0) {
2941                         /* This is the last chance, better to slow
2942                          * down than lose it.
2943                          */
2944                         sata_down_spd_limit(ata_dev_phys_link(dev));
2945                         ata_down_xfermask_limit(dev, ATA_DNXFER_PIO);
2946                 }
2947         }
2948
2949         if (ata_dev_enabled(dev) && !ehc->tries[dev->devno]) {
2950                 /* disable device if it has used up all its chances */
2951                 ata_dev_disable(dev);
2952
2953                 /* detach if offline */
2954                 if (ata_phys_link_offline(ata_dev_phys_link(dev)))
2955                         ata_eh_detach_dev(dev);
2956
2957                 /* schedule probe if necessary */
2958                 if (ata_eh_schedule_probe(dev)) {
2959                         ehc->tries[dev->devno] = ATA_EH_DEV_TRIES;
2960                         memset(ehc->cmd_timeout_idx[dev->devno], 0,
2961                                sizeof(ehc->cmd_timeout_idx[dev->devno]));
2962                 }
2963
2964                 return 1;
2965         } else {
2966                 ehc->i.action |= ATA_EH_RESET;
2967                 return 0;
2968         }
2969 }
2970
2971 /**
2972  *      ata_eh_recover - recover host port after error
2973  *      @ap: host port to recover
2974  *      @prereset: prereset method (can be NULL)
2975  *      @softreset: softreset method (can be NULL)
2976  *      @hardreset: hardreset method (can be NULL)
2977  *      @postreset: postreset method (can be NULL)
2978  *      @r_failed_link: out parameter for failed link
2979  *
2980  *      This is the alpha and omega, eum and yang, heart and soul of
2981  *      libata exception handling.  On entry, actions required to
2982  *      recover each link and hotplug requests are recorded in the
2983  *      link's eh_context.  This function executes all the operations
2984  *      with appropriate retrials and fallbacks to resurrect failed
2985  *      devices, detach goners and greet newcomers.
2986  *
2987  *      LOCKING:
2988  *      Kernel thread context (may sleep).
2989  *
2990  *      RETURNS:
2991  *      0 on success, -errno on failure.
2992  */
2993 int ata_eh_recover(struct ata_port *ap, ata_prereset_fn_t prereset,
2994                    ata_reset_fn_t softreset, ata_reset_fn_t hardreset,
2995                    ata_postreset_fn_t postreset,
2996                    struct ata_link **r_failed_link)
2997 {
2998         struct ata_link *link;
2999         struct ata_device *dev;
3000         int nr_failed_devs;
3001         int rc;
3002         unsigned long flags, deadline;
3003
3004         DPRINTK("ENTER\n");
3005
3006         /* prep for recovery */
3007         ata_port_for_each_link(link, ap) {
3008                 struct ata_eh_context *ehc = &link->eh_context;
3009
3010                 /* re-enable link? */
3011                 if (ehc->i.action & ATA_EH_ENABLE_LINK) {
3012                         ata_eh_about_to_do(link, NULL, ATA_EH_ENABLE_LINK);
3013                         spin_lock_irqsave(ap->lock, flags);
3014                         link->flags &= ~ATA_LFLAG_DISABLED;
3015                         spin_unlock_irqrestore(ap->lock, flags);
3016                         ata_eh_done(link, NULL, ATA_EH_ENABLE_LINK);
3017                 }
3018
3019                 ata_link_for_each_dev(dev, link) {
3020                         if (link->flags & ATA_LFLAG_NO_RETRY)
3021                                 ehc->tries[dev->devno] = 1;
3022                         else
3023                                 ehc->tries[dev->devno] = ATA_EH_DEV_TRIES;
3024
3025                         /* collect port action mask recorded in dev actions */
3026                         ehc->i.action |= ehc->i.dev_action[dev->devno] &
3027                                          ~ATA_EH_PERDEV_MASK;
3028                         ehc->i.dev_action[dev->devno] &= ATA_EH_PERDEV_MASK;
3029
3030                         /* process hotplug request */
3031                         if (dev->flags & ATA_DFLAG_DETACH)
3032                                 ata_eh_detach_dev(dev);
3033
3034                         /* schedule probe if necessary */
3035                         if (!ata_dev_enabled(dev))
3036                                 ata_eh_schedule_probe(dev);
3037                 }
3038         }
3039
3040  retry:
3041         rc = 0;
3042         nr_failed_devs = 0;
3043
3044         /* if UNLOADING, finish immediately */
3045         if (ap->pflags & ATA_PFLAG_UNLOADING)
3046                 goto out;
3047
3048         /* prep for EH */
3049         ata_port_for_each_link(link, ap) {
3050                 struct ata_eh_context *ehc = &link->eh_context;
3051
3052                 /* skip EH if possible. */
3053                 if (ata_eh_skip_recovery(link))
3054                         ehc->i.action = 0;
3055
3056                 ata_link_for_each_dev(dev, link)
3057                         ehc->classes[dev->devno] = ATA_DEV_UNKNOWN;
3058         }
3059
3060         /* reset */
3061         ata_port_for_each_link(link, ap) {
3062                 struct ata_eh_context *ehc = &link->eh_context;
3063
3064                 if (!(ehc->i.action & ATA_EH_RESET))
3065                         continue;
3066
3067                 rc = ata_eh_reset(link, ata_link_nr_vacant(link),
3068                                   prereset, softreset, hardreset, postreset);
3069                 if (rc) {
3070                         ata_link_printk(link, KERN_ERR,
3071                                         "reset failed, giving up\n");
3072                         goto out;
3073                 }
3074         }
3075
3076         do {
3077                 unsigned long now;
3078
3079                 /*
3080                  * clears ATA_EH_PARK in eh_info and resets
3081                  * ap->park_req_pending
3082                  */
3083                 ata_eh_pull_park_action(ap);
3084
3085                 deadline = jiffies;
3086                 ata_port_for_each_link(link, ap) {
3087                         ata_link_for_each_dev(dev, link) {
3088                                 struct ata_eh_context *ehc = &link->eh_context;
3089                                 unsigned long tmp;
3090
3091                                 if (dev->class != ATA_DEV_ATA)
3092                                         continue;
3093                                 if (!(ehc->i.dev_action[dev->devno] &
3094                                       ATA_EH_PARK))
3095                                         continue;
3096                                 tmp = dev->unpark_deadline;
3097                                 if (time_before(deadline, tmp))
3098                                         deadline = tmp;
3099                                 else if (time_before_eq(tmp, jiffies))
3100                                         continue;
3101                                 if (ehc->unloaded_mask & (1 << dev->devno))
3102                                         continue;
3103
3104                                 ata_eh_park_issue_cmd(dev, 1);
3105                         }
3106                 }
3107
3108                 now = jiffies;
3109                 if (time_before_eq(deadline, now))
3110                         break;
3111
3112                 deadline = wait_for_completion_timeout(&ap->park_req_pending,
3113                                                        deadline - now);
3114         } while (deadline);
3115         ata_port_for_each_link(link, ap) {
3116                 ata_link_for_each_dev(dev, link) {
3117                         if (!(link->eh_context.unloaded_mask &
3118                               (1 << dev->devno)))
3119                                 continue;
3120
3121                         ata_eh_park_issue_cmd(dev, 0);
3122                         ata_eh_done(link, dev, ATA_EH_PARK);
3123                 }
3124         }
3125
3126         /* the rest */
3127         ata_port_for_each_link(link, ap) {
3128                 struct ata_eh_context *ehc = &link->eh_context;
3129
3130                 /* revalidate existing devices and attach new ones */
3131                 rc = ata_eh_revalidate_and_attach(link, &dev);
3132                 if (rc)
3133                         goto dev_fail;
3134
3135                 /* if PMP got attached, return, pmp EH will take care of it */
3136                 if (link->device->class == ATA_DEV_PMP) {
3137                         ehc->i.action = 0;
3138                         return 0;
3139                 }
3140
3141                 /* configure transfer mode if necessary */
3142                 if (ehc->i.flags & ATA_EHI_SETMODE) {
3143                         rc = ata_set_mode(link, &dev);
3144                         if (rc)
3145                                 goto dev_fail;
3146                         ehc->i.flags &= ~ATA_EHI_SETMODE;
3147                 }
3148
3149                 /* If reset has been issued, clear UA to avoid
3150                  * disrupting the current users of the device.
3151                  */
3152                 if (ehc->i.flags & ATA_EHI_DID_RESET) {
3153                         ata_link_for_each_dev(dev, link) {
3154                                 if (dev->class != ATA_DEV_ATAPI)
3155                                         continue;
3156                                 rc = atapi_eh_clear_ua(dev);
3157                                 if (rc)
3158                                         goto dev_fail;
3159                         }
3160                 }
3161
3162                 /* configure link power saving */
3163                 if (ehc->i.action & ATA_EH_LPM)
3164                         ata_link_for_each_dev(dev, link)
3165                                 ata_dev_enable_pm(dev, ap->pm_policy);
3166
3167                 /* this link is okay now */
3168                 ehc->i.flags = 0;
3169                 continue;
3170
3171 dev_fail:
3172                 nr_failed_devs++;
3173                 ata_eh_handle_dev_fail(dev, rc);
3174
3175                 if (ap->pflags & ATA_PFLAG_FROZEN) {
3176                         /* PMP reset requires working host port.
3177                          * Can't retry if it's frozen.
3178                          */
3179                         if (sata_pmp_attached(ap))
3180                                 goto out;
3181                         break;
3182                 }
3183         }
3184
3185         if (nr_failed_devs)
3186                 goto retry;
3187
3188  out:
3189         if (rc && r_failed_link)
3190                 *r_failed_link = link;
3191
3192         DPRINTK("EXIT, rc=%d\n", rc);
3193         return rc;
3194 }
3195
3196 /**
3197  *      ata_eh_finish - finish up EH
3198  *      @ap: host port to finish EH for
3199  *
3200  *      Recovery is complete.  Clean up EH states and retry or finish
3201  *      failed qcs.
3202  *
3203  *      LOCKING:
3204  *      None.
3205  */
3206 void ata_eh_finish(struct ata_port *ap)
3207 {
3208         int tag;
3209
3210         /* retry or finish qcs */
3211         for (tag = 0; tag < ATA_MAX_QUEUE; tag++) {
3212                 struct ata_queued_cmd *qc = __ata_qc_from_tag(ap, tag);
3213
3214                 if (!(qc->flags & ATA_QCFLAG_FAILED))
3215                         continue;
3216
3217                 if (qc->err_mask) {
3218                         /* FIXME: Once EH migration is complete,
3219                          * generate sense data in this function,
3220                          * considering both err_mask and tf.
3221                          */
3222                         if (qc->flags & ATA_QCFLAG_RETRY)
3223                                 ata_eh_qc_retry(qc);
3224                         else
3225                                 ata_eh_qc_complete(qc);
3226                 } else {
3227                         if (qc->flags & ATA_QCFLAG_SENSE_VALID) {
3228                                 ata_eh_qc_complete(qc);
3229                         } else {
3230                                 /* feed zero TF to sense generation */
3231                                 memset(&qc->result_tf, 0, sizeof(qc->result_tf));
3232                                 ata_eh_qc_retry(qc);
3233                         }
3234                 }
3235         }
3236
3237         /* make sure nr_active_links is zero after EH */
3238         WARN_ON(ap->nr_active_links);
3239         ap->nr_active_links = 0;
3240 }
3241
3242 /**
3243  *      ata_do_eh - do standard error handling
3244  *      @ap: host port to handle error for
3245  *
3246  *      @prereset: prereset method (can be NULL)
3247  *      @softreset: softreset method (can be NULL)
3248  *      @hardreset: hardreset method (can be NULL)
3249  *      @postreset: postreset method (can be NULL)
3250  *
3251  *      Perform standard error handling sequence.
3252  *
3253  *      LOCKING:
3254  *      Kernel thread context (may sleep).
3255  */
3256 void ata_do_eh(struct ata_port *ap, ata_prereset_fn_t prereset,
3257                ata_reset_fn_t softreset, ata_reset_fn_t hardreset,
3258                ata_postreset_fn_t postreset)
3259 {
3260         struct ata_device *dev;
3261         int rc;
3262
3263         ata_eh_autopsy(ap);
3264         ata_eh_report(ap);
3265
3266         rc = ata_eh_recover(ap, prereset, softreset, hardreset, postreset,
3267                             NULL);
3268         if (rc) {
3269                 ata_link_for_each_dev(dev, &ap->link)
3270                         ata_dev_disable(dev);
3271         }
3272
3273         ata_eh_finish(ap);
3274 }
3275
3276 /**
3277  *      ata_std_error_handler - standard error handler
3278  *      @ap: host port to handle error for
3279  *
3280  *      Standard error handler
3281  *
3282  *      LOCKING:
3283  *      Kernel thread context (may sleep).
3284  */
3285 void ata_std_error_handler(struct ata_port *ap)
3286 {
3287         struct ata_port_operations *ops = ap->ops;
3288         ata_reset_fn_t hardreset = ops->hardreset;
3289
3290         /* ignore built-in hardreset if SCR access is not available */
3291         if (ata_is_builtin_hardreset(hardreset) && !sata_scr_valid(&ap->link))
3292                 hardreset = NULL;
3293
3294         ata_do_eh(ap, ops->prereset, ops->softreset, hardreset, ops->postreset);
3295 }
3296
3297 #ifdef CONFIG_PM
3298 /**
3299  *      ata_eh_handle_port_suspend - perform port suspend operation
3300  *      @ap: port to suspend
3301  *
3302  *      Suspend @ap.
3303  *
3304  *      LOCKING:
3305  *      Kernel thread context (may sleep).
3306  */
3307 static void ata_eh_handle_port_suspend(struct ata_port *ap)
3308 {
3309         unsigned long flags;
3310         int rc = 0;
3311
3312         /* are we suspending? */
3313         spin_lock_irqsave(ap->lock, flags);
3314         if (!(ap->pflags & ATA_PFLAG_PM_PENDING) ||
3315             ap->pm_mesg.event == PM_EVENT_ON) {
3316                 spin_unlock_irqrestore(ap->lock, flags);
3317                 return;
3318         }
3319         spin_unlock_irqrestore(ap->lock, flags);
3320
3321         WARN_ON(ap->pflags & ATA_PFLAG_SUSPENDED);
3322
3323         /* tell ACPI we're suspending */
3324         rc = ata_acpi_on_suspend(ap);
3325         if (rc)
3326                 goto out;
3327
3328         /* suspend */
3329         ata_eh_freeze_port(ap);
3330
3331         if (ap->ops->port_suspend)
3332                 rc = ap->ops->port_suspend(ap, ap->pm_mesg);
3333
3334         ata_acpi_set_state(ap, PMSG_SUSPEND);
3335  out:
3336         /* report result */
3337         spin_lock_irqsave(ap->lock, flags);
3338
3339         ap->pflags &= ~ATA_PFLAG_PM_PENDING;
3340         if (rc == 0)
3341                 ap->pflags |= ATA_PFLAG_SUSPENDED;
3342         else if (ap->pflags & ATA_PFLAG_FROZEN)
3343                 ata_port_schedule_eh(ap);
3344
3345         if (ap->pm_result) {
3346                 *ap->pm_result = rc;
3347                 ap->pm_result = NULL;
3348         }
3349
3350         spin_unlock_irqrestore(ap->lock, flags);
3351
3352         return;
3353 }
3354
3355 /**
3356  *      ata_eh_handle_port_resume - perform port resume operation
3357  *      @ap: port to resume
3358  *
3359  *      Resume @ap.
3360  *
3361  *      LOCKING:
3362  *      Kernel thread context (may sleep).
3363  */
3364 static void ata_eh_handle_port_resume(struct ata_port *ap)
3365 {
3366         unsigned long flags;
3367         int rc = 0;
3368
3369         /* are we resuming? */
3370         spin_lock_irqsave(ap->lock, flags);
3371         if (!(ap->pflags & ATA_PFLAG_PM_PENDING) ||
3372             ap->pm_mesg.event != PM_EVENT_ON) {
3373                 spin_unlock_irqrestore(ap->lock, flags);
3374                 return;
3375         }
3376         spin_unlock_irqrestore(ap->lock, flags);
3377
3378         WARN_ON(!(ap->pflags & ATA_PFLAG_SUSPENDED));
3379
3380         ata_acpi_set_state(ap, PMSG_ON);
3381
3382         if (ap->ops->port_resume)
3383                 rc = ap->ops->port_resume(ap);
3384
3385         /* tell ACPI that we're resuming */
3386         ata_acpi_on_resume(ap);
3387
3388         /* report result */
3389         spin_lock_irqsave(ap->lock, flags);
3390         ap->pflags &= ~(ATA_PFLAG_PM_PENDING | ATA_PFLAG_SUSPENDED);
3391         if (ap->pm_result) {
3392                 *ap->pm_result = rc;
3393                 ap->pm_result = NULL;
3394         }
3395         spin_unlock_irqrestore(ap->lock, flags);
3396 }
3397 #endif /* CONFIG_PM */