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