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