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