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