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