]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/scsi/libata-eh.c
[PATCH] libata-hp-prep: implement followup softreset handling
[karo-tx-linux.git] / drivers / scsi / 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/config.h>
36 #include <linux/kernel.h>
37 #include <scsi/scsi.h>
38 #include <scsi/scsi_host.h>
39 #include <scsi/scsi_eh.h>
40 #include <scsi/scsi_device.h>
41 #include <scsi/scsi_cmnd.h>
42 #include "scsi_transport_api.h"
43
44 #include <linux/libata.h>
45
46 #include "libata.h"
47
48 static void __ata_port_freeze(struct ata_port *ap);
49
50 static void ata_ering_record(struct ata_ering *ering, int is_io,
51                              unsigned int err_mask)
52 {
53         struct ata_ering_entry *ent;
54
55         WARN_ON(!err_mask);
56
57         ering->cursor++;
58         ering->cursor %= ATA_ERING_SIZE;
59
60         ent = &ering->ring[ering->cursor];
61         ent->is_io = is_io;
62         ent->err_mask = err_mask;
63         ent->timestamp = get_jiffies_64();
64 }
65
66 static struct ata_ering_entry * ata_ering_top(struct ata_ering *ering)
67 {
68         struct ata_ering_entry *ent = &ering->ring[ering->cursor];
69         if (!ent->err_mask)
70                 return NULL;
71         return ent;
72 }
73
74 static int ata_ering_map(struct ata_ering *ering,
75                          int (*map_fn)(struct ata_ering_entry *, void *),
76                          void *arg)
77 {
78         int idx, rc = 0;
79         struct ata_ering_entry *ent;
80
81         idx = ering->cursor;
82         do {
83                 ent = &ering->ring[idx];
84                 if (!ent->err_mask)
85                         break;
86                 rc = map_fn(ent, arg);
87                 if (rc)
88                         break;
89                 idx = (idx - 1 + ATA_ERING_SIZE) % ATA_ERING_SIZE;
90         } while (idx != ering->cursor);
91
92         return rc;
93 }
94
95 /**
96  *      ata_scsi_timed_out - SCSI layer time out callback
97  *      @cmd: timed out SCSI command
98  *
99  *      Handles SCSI layer timeout.  We race with normal completion of
100  *      the qc for @cmd.  If the qc is already gone, we lose and let
101  *      the scsi command finish (EH_HANDLED).  Otherwise, the qc has
102  *      timed out and EH should be invoked.  Prevent ata_qc_complete()
103  *      from finishing it by setting EH_SCHEDULED and return
104  *      EH_NOT_HANDLED.
105  *
106  *      TODO: kill this function once old EH is gone.
107  *
108  *      LOCKING:
109  *      Called from timer context
110  *
111  *      RETURNS:
112  *      EH_HANDLED or EH_NOT_HANDLED
113  */
114 enum scsi_eh_timer_return ata_scsi_timed_out(struct scsi_cmnd *cmd)
115 {
116         struct Scsi_Host *host = cmd->device->host;
117         struct ata_port *ap = ata_shost_to_port(host);
118         unsigned long flags;
119         struct ata_queued_cmd *qc;
120         enum scsi_eh_timer_return ret;
121
122         DPRINTK("ENTER\n");
123
124         if (ap->ops->error_handler) {
125                 ret = EH_NOT_HANDLED;
126                 goto out;
127         }
128
129         ret = EH_HANDLED;
130         spin_lock_irqsave(&ap->host_set->lock, flags);
131         qc = ata_qc_from_tag(ap, ap->active_tag);
132         if (qc) {
133                 WARN_ON(qc->scsicmd != cmd);
134                 qc->flags |= ATA_QCFLAG_EH_SCHEDULED;
135                 qc->err_mask |= AC_ERR_TIMEOUT;
136                 ret = EH_NOT_HANDLED;
137         }
138         spin_unlock_irqrestore(&ap->host_set->lock, flags);
139
140  out:
141         DPRINTK("EXIT, ret=%d\n", ret);
142         return ret;
143 }
144
145 /**
146  *      ata_scsi_error - SCSI layer error handler callback
147  *      @host: SCSI host on which error occurred
148  *
149  *      Handles SCSI-layer-thrown error events.
150  *
151  *      LOCKING:
152  *      Inherited from SCSI layer (none, can sleep)
153  *
154  *      RETURNS:
155  *      Zero.
156  */
157 void ata_scsi_error(struct Scsi_Host *host)
158 {
159         struct ata_port *ap = ata_shost_to_port(host);
160         spinlock_t *hs_lock = &ap->host_set->lock;
161         int i, repeat_cnt = ATA_EH_MAX_REPEAT;
162         unsigned long flags;
163
164         DPRINTK("ENTER\n");
165
166         /* synchronize with port task */
167         ata_port_flush_task(ap);
168
169         /* synchronize with host_set lock and sort out timeouts */
170
171         /* For new EH, all qcs are finished in one of three ways -
172          * normal completion, error completion, and SCSI timeout.
173          * Both cmpletions can race against SCSI timeout.  When normal
174          * completion wins, the qc never reaches EH.  When error
175          * completion wins, the qc has ATA_QCFLAG_FAILED set.
176          *
177          * When SCSI timeout wins, things are a bit more complex.
178          * Normal or error completion can occur after the timeout but
179          * before this point.  In such cases, both types of
180          * completions are honored.  A scmd is determined to have
181          * timed out iff its associated qc is active and not failed.
182          */
183         if (ap->ops->error_handler) {
184                 struct scsi_cmnd *scmd, *tmp;
185                 int nr_timedout = 0;
186
187                 spin_lock_irqsave(hs_lock, flags);
188
189                 list_for_each_entry_safe(scmd, tmp, &host->eh_cmd_q, eh_entry) {
190                         struct ata_queued_cmd *qc;
191
192                         for (i = 0; i < ATA_MAX_QUEUE; i++) {
193                                 qc = __ata_qc_from_tag(ap, i);
194                                 if (qc->flags & ATA_QCFLAG_ACTIVE &&
195                                     qc->scsicmd == scmd)
196                                         break;
197                         }
198
199                         if (i < ATA_MAX_QUEUE) {
200                                 /* the scmd has an associated qc */
201                                 if (!(qc->flags & ATA_QCFLAG_FAILED)) {
202                                         /* which hasn't failed yet, timeout */
203                                         qc->err_mask |= AC_ERR_TIMEOUT;
204                                         qc->flags |= ATA_QCFLAG_FAILED;
205                                         nr_timedout++;
206                                 }
207                         } else {
208                                 /* Normal completion occurred after
209                                  * SCSI timeout but before this point.
210                                  * Successfully complete it.
211                                  */
212                                 scmd->retries = scmd->allowed;
213                                 scsi_eh_finish_cmd(scmd, &ap->eh_done_q);
214                         }
215                 }
216
217                 /* If we have timed out qcs.  They belong to EH from
218                  * this point but the state of the controller is
219                  * unknown.  Freeze the port to make sure the IRQ
220                  * handler doesn't diddle with those qcs.  This must
221                  * be done atomically w.r.t. setting QCFLAG_FAILED.
222                  */
223                 if (nr_timedout)
224                         __ata_port_freeze(ap);
225
226                 spin_unlock_irqrestore(hs_lock, flags);
227         } else
228                 spin_unlock_wait(hs_lock);
229
230  repeat:
231         /* invoke error handler */
232         if (ap->ops->error_handler) {
233                 /* fetch & clear EH info */
234                 spin_lock_irqsave(hs_lock, flags);
235
236                 memset(&ap->eh_context, 0, sizeof(ap->eh_context));
237                 ap->eh_context.i = ap->eh_info;
238                 memset(&ap->eh_info, 0, sizeof(ap->eh_info));
239
240                 ap->flags |= ATA_FLAG_EH_IN_PROGRESS;
241                 ap->flags &= ~ATA_FLAG_EH_PENDING;
242
243                 spin_unlock_irqrestore(hs_lock, flags);
244
245                 /* invoke EH */
246                 ap->ops->error_handler(ap);
247
248                 /* Exception might have happend after ->error_handler
249                  * recovered the port but before this point.  Repeat
250                  * EH in such case.
251                  */
252                 spin_lock_irqsave(hs_lock, flags);
253
254                 if (ap->flags & ATA_FLAG_EH_PENDING) {
255                         if (--repeat_cnt) {
256                                 ata_port_printk(ap, KERN_INFO,
257                                         "EH pending after completion, "
258                                         "repeating EH (cnt=%d)\n", repeat_cnt);
259                                 spin_unlock_irqrestore(hs_lock, flags);
260                                 goto repeat;
261                         }
262                         ata_port_printk(ap, KERN_ERR, "EH pending after %d "
263                                         "tries, giving up\n", ATA_EH_MAX_REPEAT);
264                 }
265
266                 /* this run is complete, make sure EH info is clear */
267                 memset(&ap->eh_info, 0, sizeof(ap->eh_info));
268
269                 /* Clear host_eh_scheduled while holding hs_lock such
270                  * that if exception occurs after this point but
271                  * before EH completion, SCSI midlayer will
272                  * re-initiate EH.
273                  */
274                 host->host_eh_scheduled = 0;
275
276                 spin_unlock_irqrestore(hs_lock, flags);
277         } else {
278                 WARN_ON(ata_qc_from_tag(ap, ap->active_tag) == NULL);
279                 ap->ops->eng_timeout(ap);
280         }
281
282         /* finish or retry handled scmd's and clean up */
283         WARN_ON(host->host_failed || !list_empty(&host->eh_cmd_q));
284
285         scsi_eh_flush_done_q(&ap->eh_done_q);
286
287         /* clean up */
288         spin_lock_irqsave(hs_lock, flags);
289
290         if (ap->flags & ATA_FLAG_RECOVERED)
291                 ata_port_printk(ap, KERN_INFO, "EH complete\n");
292         ap->flags &= ~ATA_FLAG_RECOVERED;
293
294         /* tell wait_eh that we're done */
295         ap->flags &= ~ATA_FLAG_EH_IN_PROGRESS;
296         wake_up_all(&ap->eh_wait_q);
297
298         spin_unlock_irqrestore(hs_lock, flags);
299
300         DPRINTK("EXIT\n");
301 }
302
303 /**
304  *      ata_port_wait_eh - Wait for the currently pending EH to complete
305  *      @ap: Port to wait EH for
306  *
307  *      Wait until the currently pending EH is complete.
308  *
309  *      LOCKING:
310  *      Kernel thread context (may sleep).
311  */
312 void ata_port_wait_eh(struct ata_port *ap)
313 {
314         unsigned long flags;
315         DEFINE_WAIT(wait);
316
317  retry:
318         spin_lock_irqsave(&ap->host_set->lock, flags);
319
320         while (ap->flags & (ATA_FLAG_EH_PENDING | ATA_FLAG_EH_IN_PROGRESS)) {
321                 prepare_to_wait(&ap->eh_wait_q, &wait, TASK_UNINTERRUPTIBLE);
322                 spin_unlock_irqrestore(&ap->host_set->lock, flags);
323                 schedule();
324                 spin_lock_irqsave(&ap->host_set->lock, flags);
325         }
326
327         spin_unlock_irqrestore(&ap->host_set->lock, flags);
328
329         /* make sure SCSI EH is complete */
330         if (scsi_host_in_recovery(ap->host)) {
331                 msleep(10);
332                 goto retry;
333         }
334 }
335
336 /**
337  *      ata_qc_timeout - Handle timeout of queued command
338  *      @qc: Command that timed out
339  *
340  *      Some part of the kernel (currently, only the SCSI layer)
341  *      has noticed that the active command on port @ap has not
342  *      completed after a specified length of time.  Handle this
343  *      condition by disabling DMA (if necessary) and completing
344  *      transactions, with error if necessary.
345  *
346  *      This also handles the case of the "lost interrupt", where
347  *      for some reason (possibly hardware bug, possibly driver bug)
348  *      an interrupt was not delivered to the driver, even though the
349  *      transaction completed successfully.
350  *
351  *      TODO: kill this function once old EH is gone.
352  *
353  *      LOCKING:
354  *      Inherited from SCSI layer (none, can sleep)
355  */
356 static void ata_qc_timeout(struct ata_queued_cmd *qc)
357 {
358         struct ata_port *ap = qc->ap;
359         struct ata_host_set *host_set = ap->host_set;
360         u8 host_stat = 0, drv_stat;
361         unsigned long flags;
362
363         DPRINTK("ENTER\n");
364
365         ap->hsm_task_state = HSM_ST_IDLE;
366
367         spin_lock_irqsave(&host_set->lock, flags);
368
369         switch (qc->tf.protocol) {
370
371         case ATA_PROT_DMA:
372         case ATA_PROT_ATAPI_DMA:
373                 host_stat = ap->ops->bmdma_status(ap);
374
375                 /* before we do anything else, clear DMA-Start bit */
376                 ap->ops->bmdma_stop(qc);
377
378                 /* fall through */
379
380         default:
381                 ata_altstatus(ap);
382                 drv_stat = ata_chk_status(ap);
383
384                 /* ack bmdma irq events */
385                 ap->ops->irq_clear(ap);
386
387                 ata_dev_printk(qc->dev, KERN_ERR, "command 0x%x timeout, "
388                                "stat 0x%x host_stat 0x%x\n",
389                                qc->tf.command, drv_stat, host_stat);
390
391                 /* complete taskfile transaction */
392                 qc->err_mask |= AC_ERR_TIMEOUT;
393                 break;
394         }
395
396         spin_unlock_irqrestore(&host_set->lock, flags);
397
398         ata_eh_qc_complete(qc);
399
400         DPRINTK("EXIT\n");
401 }
402
403 /**
404  *      ata_eng_timeout - Handle timeout of queued command
405  *      @ap: Port on which timed-out command is active
406  *
407  *      Some part of the kernel (currently, only the SCSI layer)
408  *      has noticed that the active command on port @ap has not
409  *      completed after a specified length of time.  Handle this
410  *      condition by disabling DMA (if necessary) and completing
411  *      transactions, with error if necessary.
412  *
413  *      This also handles the case of the "lost interrupt", where
414  *      for some reason (possibly hardware bug, possibly driver bug)
415  *      an interrupt was not delivered to the driver, even though the
416  *      transaction completed successfully.
417  *
418  *      TODO: kill this function once old EH is gone.
419  *
420  *      LOCKING:
421  *      Inherited from SCSI layer (none, can sleep)
422  */
423 void ata_eng_timeout(struct ata_port *ap)
424 {
425         DPRINTK("ENTER\n");
426
427         ata_qc_timeout(ata_qc_from_tag(ap, ap->active_tag));
428
429         DPRINTK("EXIT\n");
430 }
431
432 /**
433  *      ata_qc_schedule_eh - schedule qc for error handling
434  *      @qc: command to schedule error handling for
435  *
436  *      Schedule error handling for @qc.  EH will kick in as soon as
437  *      other commands are drained.
438  *
439  *      LOCKING:
440  *      spin_lock_irqsave(host_set lock)
441  */
442 void ata_qc_schedule_eh(struct ata_queued_cmd *qc)
443 {
444         struct ata_port *ap = qc->ap;
445
446         WARN_ON(!ap->ops->error_handler);
447
448         qc->flags |= ATA_QCFLAG_FAILED;
449         qc->ap->flags |= ATA_FLAG_EH_PENDING;
450
451         /* The following will fail if timeout has already expired.
452          * ata_scsi_error() takes care of such scmds on EH entry.
453          * Note that ATA_QCFLAG_FAILED is unconditionally set after
454          * this function completes.
455          */
456         scsi_req_abort_cmd(qc->scsicmd);
457 }
458
459 /**
460  *      ata_port_schedule_eh - schedule error handling without a qc
461  *      @ap: ATA port to schedule EH for
462  *
463  *      Schedule error handling for @ap.  EH will kick in as soon as
464  *      all commands are drained.
465  *
466  *      LOCKING:
467  *      spin_lock_irqsave(host_set lock)
468  */
469 void ata_port_schedule_eh(struct ata_port *ap)
470 {
471         WARN_ON(!ap->ops->error_handler);
472
473         ap->flags |= ATA_FLAG_EH_PENDING;
474         scsi_schedule_eh(ap->host);
475
476         DPRINTK("port EH scheduled\n");
477 }
478
479 /**
480  *      ata_port_abort - abort all qc's on the port
481  *      @ap: ATA port to abort qc's for
482  *
483  *      Abort all active qc's of @ap and schedule EH.
484  *
485  *      LOCKING:
486  *      spin_lock_irqsave(host_set lock)
487  *
488  *      RETURNS:
489  *      Number of aborted qc's.
490  */
491 int ata_port_abort(struct ata_port *ap)
492 {
493         int tag, nr_aborted = 0;
494
495         WARN_ON(!ap->ops->error_handler);
496
497         for (tag = 0; tag < ATA_MAX_QUEUE; tag++) {
498                 struct ata_queued_cmd *qc = ata_qc_from_tag(ap, tag);
499
500                 if (qc) {
501                         qc->flags |= ATA_QCFLAG_FAILED;
502                         ata_qc_complete(qc);
503                         nr_aborted++;
504                 }
505         }
506
507         if (!nr_aborted)
508                 ata_port_schedule_eh(ap);
509
510         return nr_aborted;
511 }
512
513 /**
514  *      __ata_port_freeze - freeze port
515  *      @ap: ATA port to freeze
516  *
517  *      This function is called when HSM violation or some other
518  *      condition disrupts normal operation of the port.  Frozen port
519  *      is not allowed to perform any operation until the port is
520  *      thawed, which usually follows a successful reset.
521  *
522  *      ap->ops->freeze() callback can be used for freezing the port
523  *      hardware-wise (e.g. mask interrupt and stop DMA engine).  If a
524  *      port cannot be frozen hardware-wise, the interrupt handler
525  *      must ack and clear interrupts unconditionally while the port
526  *      is frozen.
527  *
528  *      LOCKING:
529  *      spin_lock_irqsave(host_set lock)
530  */
531 static void __ata_port_freeze(struct ata_port *ap)
532 {
533         WARN_ON(!ap->ops->error_handler);
534
535         if (ap->ops->freeze)
536                 ap->ops->freeze(ap);
537
538         ap->flags |= ATA_FLAG_FROZEN;
539
540         DPRINTK("ata%u port frozen\n", ap->id);
541 }
542
543 /**
544  *      ata_port_freeze - abort & freeze port
545  *      @ap: ATA port to freeze
546  *
547  *      Abort and freeze @ap.
548  *
549  *      LOCKING:
550  *      spin_lock_irqsave(host_set lock)
551  *
552  *      RETURNS:
553  *      Number of aborted commands.
554  */
555 int ata_port_freeze(struct ata_port *ap)
556 {
557         int nr_aborted;
558
559         WARN_ON(!ap->ops->error_handler);
560
561         nr_aborted = ata_port_abort(ap);
562         __ata_port_freeze(ap);
563
564         return nr_aborted;
565 }
566
567 /**
568  *      ata_eh_freeze_port - EH helper to freeze port
569  *      @ap: ATA port to freeze
570  *
571  *      Freeze @ap.
572  *
573  *      LOCKING:
574  *      None.
575  */
576 void ata_eh_freeze_port(struct ata_port *ap)
577 {
578         unsigned long flags;
579
580         if (!ap->ops->error_handler)
581                 return;
582
583         spin_lock_irqsave(&ap->host_set->lock, flags);
584         __ata_port_freeze(ap);
585         spin_unlock_irqrestore(&ap->host_set->lock, flags);
586 }
587
588 /**
589  *      ata_port_thaw_port - EH helper to thaw port
590  *      @ap: ATA port to thaw
591  *
592  *      Thaw frozen port @ap.
593  *
594  *      LOCKING:
595  *      None.
596  */
597 void ata_eh_thaw_port(struct ata_port *ap)
598 {
599         unsigned long flags;
600
601         if (!ap->ops->error_handler)
602                 return;
603
604         spin_lock_irqsave(&ap->host_set->lock, flags);
605
606         ap->flags &= ~ATA_FLAG_FROZEN;
607
608         if (ap->ops->thaw)
609                 ap->ops->thaw(ap);
610
611         spin_unlock_irqrestore(&ap->host_set->lock, flags);
612
613         DPRINTK("ata%u port thawed\n", ap->id);
614 }
615
616 static void ata_eh_scsidone(struct scsi_cmnd *scmd)
617 {
618         /* nada */
619 }
620
621 static void __ata_eh_qc_complete(struct ata_queued_cmd *qc)
622 {
623         struct ata_port *ap = qc->ap;
624         struct scsi_cmnd *scmd = qc->scsicmd;
625         unsigned long flags;
626
627         spin_lock_irqsave(&ap->host_set->lock, flags);
628         qc->scsidone = ata_eh_scsidone;
629         __ata_qc_complete(qc);
630         WARN_ON(ata_tag_valid(qc->tag));
631         spin_unlock_irqrestore(&ap->host_set->lock, flags);
632
633         scsi_eh_finish_cmd(scmd, &ap->eh_done_q);
634 }
635
636 /**
637  *      ata_eh_qc_complete - Complete an active ATA command from EH
638  *      @qc: Command to complete
639  *
640  *      Indicate to the mid and upper layers that an ATA command has
641  *      completed.  To be used from EH.
642  */
643 void ata_eh_qc_complete(struct ata_queued_cmd *qc)
644 {
645         struct scsi_cmnd *scmd = qc->scsicmd;
646         scmd->retries = scmd->allowed;
647         __ata_eh_qc_complete(qc);
648 }
649
650 /**
651  *      ata_eh_qc_retry - Tell midlayer to retry an ATA command after EH
652  *      @qc: Command to retry
653  *
654  *      Indicate to the mid and upper layers that an ATA command
655  *      should be retried.  To be used from EH.
656  *
657  *      SCSI midlayer limits the number of retries to scmd->allowed.
658  *      scmd->retries is decremented for commands which get retried
659  *      due to unrelated failures (qc->err_mask is zero).
660  */
661 void ata_eh_qc_retry(struct ata_queued_cmd *qc)
662 {
663         struct scsi_cmnd *scmd = qc->scsicmd;
664         if (!qc->err_mask && scmd->retries)
665                 scmd->retries--;
666         __ata_eh_qc_complete(qc);
667 }
668
669 /**
670  *      ata_eh_about_to_do - about to perform eh_action
671  *      @ap: target ATA port
672  *      @action: action about to be performed
673  *
674  *      Called just before performing EH actions to clear related bits
675  *      in @ap->eh_info such that eh actions are not unnecessarily
676  *      repeated.
677  *
678  *      LOCKING:
679  *      None.
680  */
681 static void ata_eh_about_to_do(struct ata_port *ap, unsigned int action)
682 {
683         unsigned long flags;
684
685         spin_lock_irqsave(&ap->host_set->lock, flags);
686         ap->eh_info.action &= ~action;
687         ap->flags |= ATA_FLAG_RECOVERED;
688         spin_unlock_irqrestore(&ap->host_set->lock, flags);
689 }
690
691 /**
692  *      ata_err_string - convert err_mask to descriptive string
693  *      @err_mask: error mask to convert to string
694  *
695  *      Convert @err_mask to descriptive string.  Errors are
696  *      prioritized according to severity and only the most severe
697  *      error is reported.
698  *
699  *      LOCKING:
700  *      None.
701  *
702  *      RETURNS:
703  *      Descriptive string for @err_mask
704  */
705 static const char * ata_err_string(unsigned int err_mask)
706 {
707         if (err_mask & AC_ERR_HOST_BUS)
708                 return "host bus error";
709         if (err_mask & AC_ERR_ATA_BUS)
710                 return "ATA bus error";
711         if (err_mask & AC_ERR_TIMEOUT)
712                 return "timeout";
713         if (err_mask & AC_ERR_HSM)
714                 return "HSM violation";
715         if (err_mask & AC_ERR_SYSTEM)
716                 return "internal error";
717         if (err_mask & AC_ERR_MEDIA)
718                 return "media error";
719         if (err_mask & AC_ERR_INVALID)
720                 return "invalid argument";
721         if (err_mask & AC_ERR_DEV)
722                 return "device error";
723         return "unknown error";
724 }
725
726 /**
727  *      ata_read_log_page - read a specific log page
728  *      @dev: target device
729  *      @page: page to read
730  *      @buf: buffer to store read page
731  *      @sectors: number of sectors to read
732  *
733  *      Read log page using READ_LOG_EXT command.
734  *
735  *      LOCKING:
736  *      Kernel thread context (may sleep).
737  *
738  *      RETURNS:
739  *      0 on success, AC_ERR_* mask otherwise.
740  */
741 static unsigned int ata_read_log_page(struct ata_device *dev,
742                                       u8 page, void *buf, unsigned int sectors)
743 {
744         struct ata_taskfile tf;
745         unsigned int err_mask;
746
747         DPRINTK("read log page - page %d\n", page);
748
749         ata_tf_init(dev, &tf);
750         tf.command = ATA_CMD_READ_LOG_EXT;
751         tf.lbal = page;
752         tf.nsect = sectors;
753         tf.hob_nsect = sectors >> 8;
754         tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_LBA48 | ATA_TFLAG_DEVICE;
755         tf.protocol = ATA_PROT_PIO;
756
757         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_FROM_DEVICE,
758                                      buf, sectors * ATA_SECT_SIZE);
759
760         DPRINTK("EXIT, err_mask=%x\n", err_mask);
761         return err_mask;
762 }
763
764 /**
765  *      ata_eh_read_log_10h - Read log page 10h for NCQ error details
766  *      @dev: Device to read log page 10h from
767  *      @tag: Resulting tag of the failed command
768  *      @tf: Resulting taskfile registers of the failed command
769  *
770  *      Read log page 10h to obtain NCQ error details and clear error
771  *      condition.
772  *
773  *      LOCKING:
774  *      Kernel thread context (may sleep).
775  *
776  *      RETURNS:
777  *      0 on success, -errno otherwise.
778  */
779 static int ata_eh_read_log_10h(struct ata_device *dev,
780                                int *tag, struct ata_taskfile *tf)
781 {
782         u8 *buf = dev->ap->sector_buf;
783         unsigned int err_mask;
784         u8 csum;
785         int i;
786
787         err_mask = ata_read_log_page(dev, ATA_LOG_SATA_NCQ, buf, 1);
788         if (err_mask)
789                 return -EIO;
790
791         csum = 0;
792         for (i = 0; i < ATA_SECT_SIZE; i++)
793                 csum += buf[i];
794         if (csum)
795                 ata_dev_printk(dev, KERN_WARNING,
796                                "invalid checksum 0x%x on log page 10h\n", csum);
797
798         if (buf[0] & 0x80)
799                 return -ENOENT;
800
801         *tag = buf[0] & 0x1f;
802
803         tf->command = buf[2];
804         tf->feature = buf[3];
805         tf->lbal = buf[4];
806         tf->lbam = buf[5];
807         tf->lbah = buf[6];
808         tf->device = buf[7];
809         tf->hob_lbal = buf[8];
810         tf->hob_lbam = buf[9];
811         tf->hob_lbah = buf[10];
812         tf->nsect = buf[12];
813         tf->hob_nsect = buf[13];
814
815         return 0;
816 }
817
818 /**
819  *      atapi_eh_request_sense - perform ATAPI REQUEST_SENSE
820  *      @dev: device to perform REQUEST_SENSE to
821  *      @sense_buf: result sense data buffer (SCSI_SENSE_BUFFERSIZE bytes long)
822  *
823  *      Perform ATAPI REQUEST_SENSE after the device reported CHECK
824  *      SENSE.  This function is EH helper.
825  *
826  *      LOCKING:
827  *      Kernel thread context (may sleep).
828  *
829  *      RETURNS:
830  *      0 on success, AC_ERR_* mask on failure
831  */
832 static unsigned int atapi_eh_request_sense(struct ata_device *dev,
833                                            unsigned char *sense_buf)
834 {
835         struct ata_port *ap = dev->ap;
836         struct ata_taskfile tf;
837         u8 cdb[ATAPI_CDB_LEN];
838
839         DPRINTK("ATAPI request sense\n");
840
841         ata_tf_init(dev, &tf);
842
843         /* FIXME: is this needed? */
844         memset(sense_buf, 0, SCSI_SENSE_BUFFERSIZE);
845
846         /* XXX: why tf_read here? */
847         ap->ops->tf_read(ap, &tf);
848
849         /* fill these in, for the case where they are -not- overwritten */
850         sense_buf[0] = 0x70;
851         sense_buf[2] = tf.feature >> 4;
852
853         memset(cdb, 0, ATAPI_CDB_LEN);
854         cdb[0] = REQUEST_SENSE;
855         cdb[4] = SCSI_SENSE_BUFFERSIZE;
856
857         tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
858         tf.command = ATA_CMD_PACKET;
859
860         /* is it pointless to prefer PIO for "safety reasons"? */
861         if (ap->flags & ATA_FLAG_PIO_DMA) {
862                 tf.protocol = ATA_PROT_ATAPI_DMA;
863                 tf.feature |= ATAPI_PKT_DMA;
864         } else {
865                 tf.protocol = ATA_PROT_ATAPI;
866                 tf.lbam = (8 * 1024) & 0xff;
867                 tf.lbah = (8 * 1024) >> 8;
868         }
869
870         return ata_exec_internal(dev, &tf, cdb, DMA_FROM_DEVICE,
871                                  sense_buf, SCSI_SENSE_BUFFERSIZE);
872 }
873
874 /**
875  *      ata_eh_analyze_serror - analyze SError for a failed port
876  *      @ap: ATA port to analyze SError for
877  *
878  *      Analyze SError if available and further determine cause of
879  *      failure.
880  *
881  *      LOCKING:
882  *      None.
883  */
884 static void ata_eh_analyze_serror(struct ata_port *ap)
885 {
886         struct ata_eh_context *ehc = &ap->eh_context;
887         u32 serror = ehc->i.serror;
888         unsigned int err_mask = 0, action = 0;
889
890         if (serror & SERR_PERSISTENT) {
891                 err_mask |= AC_ERR_ATA_BUS;
892                 action |= ATA_EH_HARDRESET;
893         }
894         if (serror &
895             (SERR_DATA_RECOVERED | SERR_COMM_RECOVERED | SERR_DATA)) {
896                 err_mask |= AC_ERR_ATA_BUS;
897                 action |= ATA_EH_SOFTRESET;
898         }
899         if (serror & SERR_PROTOCOL) {
900                 err_mask |= AC_ERR_HSM;
901                 action |= ATA_EH_SOFTRESET;
902         }
903         if (serror & SERR_INTERNAL) {
904                 err_mask |= AC_ERR_SYSTEM;
905                 action |= ATA_EH_SOFTRESET;
906         }
907         if (serror & (SERR_PHYRDY_CHG | SERR_DEV_XCHG)) {
908                 err_mask |= AC_ERR_ATA_BUS;
909                 action |= ATA_EH_HARDRESET;
910         }
911
912         ehc->i.err_mask |= err_mask;
913         ehc->i.action |= action;
914 }
915
916 /**
917  *      ata_eh_analyze_ncq_error - analyze NCQ error
918  *      @ap: ATA port to analyze NCQ error for
919  *
920  *      Read log page 10h, determine the offending qc and acquire
921  *      error status TF.  For NCQ device errors, all LLDDs have to do
922  *      is setting AC_ERR_DEV in ehi->err_mask.  This function takes
923  *      care of the rest.
924  *
925  *      LOCKING:
926  *      Kernel thread context (may sleep).
927  */
928 static void ata_eh_analyze_ncq_error(struct ata_port *ap)
929 {
930         struct ata_eh_context *ehc = &ap->eh_context;
931         struct ata_device *dev = ap->device;
932         struct ata_queued_cmd *qc;
933         struct ata_taskfile tf;
934         int tag, rc;
935
936         /* if frozen, we can't do much */
937         if (ap->flags & ATA_FLAG_FROZEN)
938                 return;
939
940         /* is it NCQ device error? */
941         if (!ap->sactive || !(ehc->i.err_mask & AC_ERR_DEV))
942                 return;
943
944         /* has LLDD analyzed already? */
945         for (tag = 0; tag < ATA_MAX_QUEUE; tag++) {
946                 qc = __ata_qc_from_tag(ap, tag);
947
948                 if (!(qc->flags & ATA_QCFLAG_FAILED))
949                         continue;
950
951                 if (qc->err_mask)
952                         return;
953         }
954
955         /* okay, this error is ours */
956         rc = ata_eh_read_log_10h(dev, &tag, &tf);
957         if (rc) {
958                 ata_port_printk(ap, KERN_ERR, "failed to read log page 10h "
959                                 "(errno=%d)\n", rc);
960                 return;
961         }
962
963         if (!(ap->sactive & (1 << tag))) {
964                 ata_port_printk(ap, KERN_ERR, "log page 10h reported "
965                                 "inactive tag %d\n", tag);
966                 return;
967         }
968
969         /* we've got the perpetrator, condemn it */
970         qc = __ata_qc_from_tag(ap, tag);
971         memcpy(&qc->result_tf, &tf, sizeof(tf));
972         qc->err_mask |= AC_ERR_DEV;
973         ehc->i.err_mask &= ~AC_ERR_DEV;
974 }
975
976 /**
977  *      ata_eh_analyze_tf - analyze taskfile of a failed qc
978  *      @qc: qc to analyze
979  *      @tf: Taskfile registers to analyze
980  *
981  *      Analyze taskfile of @qc and further determine cause of
982  *      failure.  This function also requests ATAPI sense data if
983  *      avaliable.
984  *
985  *      LOCKING:
986  *      Kernel thread context (may sleep).
987  *
988  *      RETURNS:
989  *      Determined recovery action
990  */
991 static unsigned int ata_eh_analyze_tf(struct ata_queued_cmd *qc,
992                                       const struct ata_taskfile *tf)
993 {
994         unsigned int tmp, action = 0;
995         u8 stat = tf->command, err = tf->feature;
996
997         if ((stat & (ATA_BUSY | ATA_DRQ | ATA_DRDY)) != ATA_DRDY) {
998                 qc->err_mask |= AC_ERR_HSM;
999                 return ATA_EH_SOFTRESET;
1000         }
1001
1002         if (!(qc->err_mask & AC_ERR_DEV))
1003                 return 0;
1004
1005         switch (qc->dev->class) {
1006         case ATA_DEV_ATA:
1007                 if (err & ATA_ICRC)
1008                         qc->err_mask |= AC_ERR_ATA_BUS;
1009                 if (err & ATA_UNC)
1010                         qc->err_mask |= AC_ERR_MEDIA;
1011                 if (err & ATA_IDNF)
1012                         qc->err_mask |= AC_ERR_INVALID;
1013                 break;
1014
1015         case ATA_DEV_ATAPI:
1016                 tmp = atapi_eh_request_sense(qc->dev,
1017                                              qc->scsicmd->sense_buffer);
1018                 if (!tmp) {
1019                         /* ATA_QCFLAG_SENSE_VALID is used to tell
1020                          * atapi_qc_complete() that sense data is
1021                          * already valid.
1022                          *
1023                          * TODO: interpret sense data and set
1024                          * appropriate err_mask.
1025                          */
1026                         qc->flags |= ATA_QCFLAG_SENSE_VALID;
1027                 } else
1028                         qc->err_mask |= tmp;
1029         }
1030
1031         if (qc->err_mask & (AC_ERR_HSM | AC_ERR_TIMEOUT | AC_ERR_ATA_BUS))
1032                 action |= ATA_EH_SOFTRESET;
1033
1034         return action;
1035 }
1036
1037 static int ata_eh_categorize_ering_entry(struct ata_ering_entry *ent)
1038 {
1039         if (ent->err_mask & (AC_ERR_ATA_BUS | AC_ERR_TIMEOUT))
1040                 return 1;
1041
1042         if (ent->is_io) {
1043                 if (ent->err_mask & AC_ERR_HSM)
1044                         return 1;
1045                 if ((ent->err_mask &
1046                      (AC_ERR_DEV|AC_ERR_MEDIA|AC_ERR_INVALID)) == AC_ERR_DEV)
1047                         return 2;
1048         }
1049
1050         return 0;
1051 }
1052
1053 struct speed_down_needed_arg {
1054         u64 since;
1055         int nr_errors[3];
1056 };
1057
1058 static int speed_down_needed_cb(struct ata_ering_entry *ent, void *void_arg)
1059 {
1060         struct speed_down_needed_arg *arg = void_arg;
1061
1062         if (ent->timestamp < arg->since)
1063                 return -1;
1064
1065         arg->nr_errors[ata_eh_categorize_ering_entry(ent)]++;
1066         return 0;
1067 }
1068
1069 /**
1070  *      ata_eh_speed_down_needed - Determine wheter speed down is necessary
1071  *      @dev: Device of interest
1072  *
1073  *      This function examines error ring of @dev and determines
1074  *      whether speed down is necessary.  Speed down is necessary if
1075  *      there have been more than 3 of Cat-1 errors or 10 of Cat-2
1076  *      errors during last 15 minutes.
1077  *
1078  *      Cat-1 errors are ATA_BUS, TIMEOUT for any command and HSM
1079  *      violation for known supported commands.
1080  *
1081  *      Cat-2 errors are unclassified DEV error for known supported
1082  *      command.
1083  *
1084  *      LOCKING:
1085  *      Inherited from caller.
1086  *
1087  *      RETURNS:
1088  *      1 if speed down is necessary, 0 otherwise
1089  */
1090 static int ata_eh_speed_down_needed(struct ata_device *dev)
1091 {
1092         const u64 interval = 15LLU * 60 * HZ;
1093         static const int err_limits[3] = { -1, 3, 10 };
1094         struct speed_down_needed_arg arg;
1095         struct ata_ering_entry *ent;
1096         int err_cat;
1097         u64 j64;
1098
1099         ent = ata_ering_top(&dev->ering);
1100         if (!ent)
1101                 return 0;
1102
1103         err_cat = ata_eh_categorize_ering_entry(ent);
1104         if (err_cat == 0)
1105                 return 0;
1106
1107         memset(&arg, 0, sizeof(arg));
1108
1109         j64 = get_jiffies_64();
1110         if (j64 >= interval)
1111                 arg.since = j64 - interval;
1112         else
1113                 arg.since = 0;
1114
1115         ata_ering_map(&dev->ering, speed_down_needed_cb, &arg);
1116
1117         return arg.nr_errors[err_cat] > err_limits[err_cat];
1118 }
1119
1120 /**
1121  *      ata_eh_speed_down - record error and speed down if necessary
1122  *      @dev: Failed device
1123  *      @is_io: Did the device fail during normal IO?
1124  *      @err_mask: err_mask of the error
1125  *
1126  *      Record error and examine error history to determine whether
1127  *      adjusting transmission speed is necessary.  It also sets
1128  *      transmission limits appropriately if such adjustment is
1129  *      necessary.
1130  *
1131  *      LOCKING:
1132  *      Kernel thread context (may sleep).
1133  *
1134  *      RETURNS:
1135  *      0 on success, -errno otherwise
1136  */
1137 static int ata_eh_speed_down(struct ata_device *dev, int is_io,
1138                              unsigned int err_mask)
1139 {
1140         if (!err_mask)
1141                 return 0;
1142
1143         /* record error and determine whether speed down is necessary */
1144         ata_ering_record(&dev->ering, is_io, err_mask);
1145
1146         if (!ata_eh_speed_down_needed(dev))
1147                 return 0;
1148
1149         /* speed down SATA link speed if possible */
1150         if (sata_down_spd_limit(dev->ap) == 0)
1151                 return ATA_EH_HARDRESET;
1152
1153         /* lower transfer mode */
1154         if (ata_down_xfermask_limit(dev, 0) == 0)
1155                 return ATA_EH_SOFTRESET;
1156
1157         ata_dev_printk(dev, KERN_ERR,
1158                        "speed down requested but no transfer mode left\n");
1159         return 0;
1160 }
1161
1162 /**
1163  *      ata_eh_autopsy - analyze error and determine recovery action
1164  *      @ap: ATA port to perform autopsy on
1165  *
1166  *      Analyze why @ap failed and determine which recovery action is
1167  *      needed.  This function also sets more detailed AC_ERR_* values
1168  *      and fills sense data for ATAPI CHECK SENSE.
1169  *
1170  *      LOCKING:
1171  *      Kernel thread context (may sleep).
1172  */
1173 static void ata_eh_autopsy(struct ata_port *ap)
1174 {
1175         struct ata_eh_context *ehc = &ap->eh_context;
1176         unsigned int action = ehc->i.action;
1177         struct ata_device *failed_dev = NULL;
1178         unsigned int all_err_mask = 0;
1179         int tag, is_io = 0;
1180         u32 serror;
1181         int rc;
1182
1183         DPRINTK("ENTER\n");
1184
1185         /* obtain and analyze SError */
1186         rc = sata_scr_read(ap, SCR_ERROR, &serror);
1187         if (rc == 0) {
1188                 ehc->i.serror |= serror;
1189                 ata_eh_analyze_serror(ap);
1190         } else if (rc != -EOPNOTSUPP)
1191                 action |= ATA_EH_HARDRESET;
1192
1193         /* analyze NCQ failure */
1194         ata_eh_analyze_ncq_error(ap);
1195
1196         /* any real error trumps AC_ERR_OTHER */
1197         if (ehc->i.err_mask & ~AC_ERR_OTHER)
1198                 ehc->i.err_mask &= ~AC_ERR_OTHER;
1199
1200         all_err_mask |= ehc->i.err_mask;
1201
1202         for (tag = 0; tag < ATA_MAX_QUEUE; tag++) {
1203                 struct ata_queued_cmd *qc = __ata_qc_from_tag(ap, tag);
1204
1205                 if (!(qc->flags & ATA_QCFLAG_FAILED))
1206                         continue;
1207
1208                 /* inherit upper level err_mask */
1209                 qc->err_mask |= ehc->i.err_mask;
1210
1211                 /* analyze TF */
1212                 action |= ata_eh_analyze_tf(qc, &qc->result_tf);
1213
1214                 /* DEV errors are probably spurious in case of ATA_BUS error */
1215                 if (qc->err_mask & AC_ERR_ATA_BUS)
1216                         qc->err_mask &= ~(AC_ERR_DEV | AC_ERR_MEDIA |
1217                                           AC_ERR_INVALID);
1218
1219                 /* any real error trumps unknown error */
1220                 if (qc->err_mask & ~AC_ERR_OTHER)
1221                         qc->err_mask &= ~AC_ERR_OTHER;
1222
1223                 /* SENSE_VALID trumps dev/unknown error and revalidation */
1224                 if (qc->flags & ATA_QCFLAG_SENSE_VALID) {
1225                         qc->err_mask &= ~(AC_ERR_DEV | AC_ERR_OTHER);
1226                         action &= ~ATA_EH_REVALIDATE;
1227                 }
1228
1229                 /* accumulate error info */
1230                 failed_dev = qc->dev;
1231                 all_err_mask |= qc->err_mask;
1232                 if (qc->flags & ATA_QCFLAG_IO)
1233                         is_io = 1;
1234         }
1235
1236         /* speed down iff command was in progress */
1237         if (failed_dev)
1238                 action |= ata_eh_speed_down(failed_dev, is_io, all_err_mask);
1239
1240         /* enforce default EH actions */
1241         if (ap->flags & ATA_FLAG_FROZEN ||
1242             all_err_mask & (AC_ERR_HSM | AC_ERR_TIMEOUT))
1243                 action |= ATA_EH_SOFTRESET;
1244         else if (all_err_mask)
1245                 action |= ATA_EH_REVALIDATE;
1246
1247         /* record autopsy result */
1248         ehc->i.dev = failed_dev;
1249         ehc->i.action = action;
1250
1251         DPRINTK("EXIT\n");
1252 }
1253
1254 /**
1255  *      ata_eh_report - report error handling to user
1256  *      @ap: ATA port EH is going on
1257  *
1258  *      Report EH to user.
1259  *
1260  *      LOCKING:
1261  *      None.
1262  */
1263 static void ata_eh_report(struct ata_port *ap)
1264 {
1265         struct ata_eh_context *ehc = &ap->eh_context;
1266         const char *frozen, *desc;
1267         int tag, nr_failed = 0;
1268
1269         desc = NULL;
1270         if (ehc->i.desc[0] != '\0')
1271                 desc = ehc->i.desc;
1272
1273         for (tag = 0; tag < ATA_MAX_QUEUE; tag++) {
1274                 struct ata_queued_cmd *qc = __ata_qc_from_tag(ap, tag);
1275
1276                 if (!(qc->flags & ATA_QCFLAG_FAILED))
1277                         continue;
1278                 if (qc->flags & ATA_QCFLAG_SENSE_VALID && !qc->err_mask)
1279                         continue;
1280
1281                 nr_failed++;
1282         }
1283
1284         if (!nr_failed && !ehc->i.err_mask)
1285                 return;
1286
1287         frozen = "";
1288         if (ap->flags & ATA_FLAG_FROZEN)
1289                 frozen = " frozen";
1290
1291         if (ehc->i.dev) {
1292                 ata_dev_printk(ehc->i.dev, KERN_ERR, "exception Emask 0x%x "
1293                                "SAct 0x%x SErr 0x%x action 0x%x%s\n",
1294                                ehc->i.err_mask, ap->sactive, ehc->i.serror,
1295                                ehc->i.action, frozen);
1296                 if (desc)
1297                         ata_dev_printk(ehc->i.dev, KERN_ERR, "(%s)\n", desc);
1298         } else {
1299                 ata_port_printk(ap, KERN_ERR, "exception Emask 0x%x "
1300                                 "SAct 0x%x SErr 0x%x action 0x%x%s\n",
1301                                 ehc->i.err_mask, ap->sactive, ehc->i.serror,
1302                                 ehc->i.action, frozen);
1303                 if (desc)
1304                         ata_port_printk(ap, KERN_ERR, "(%s)\n", desc);
1305         }
1306
1307         for (tag = 0; tag < ATA_MAX_QUEUE; tag++) {
1308                 struct ata_queued_cmd *qc = __ata_qc_from_tag(ap, tag);
1309
1310                 if (!(qc->flags & ATA_QCFLAG_FAILED) || !qc->err_mask)
1311                         continue;
1312
1313                 ata_dev_printk(qc->dev, KERN_ERR, "tag %d cmd 0x%x "
1314                                "Emask 0x%x stat 0x%x err 0x%x (%s)\n",
1315                                qc->tag, qc->tf.command, qc->err_mask,
1316                                qc->result_tf.command, qc->result_tf.feature,
1317                                ata_err_string(qc->err_mask));
1318         }
1319 }
1320
1321 static int ata_eh_followup_srst_needed(int rc, int classify,
1322                                        const unsigned int *classes)
1323 {
1324         if (rc == -EAGAIN)
1325                 return 1;
1326         if (rc != 0)
1327                 return 0;
1328         if (classify && classes[0] == ATA_DEV_UNKNOWN)
1329                 return 1;
1330         return 0;
1331 }
1332
1333 static int ata_eh_reset(struct ata_port *ap, int classify,
1334                         ata_prereset_fn_t prereset, ata_reset_fn_t softreset,
1335                         ata_reset_fn_t hardreset, ata_postreset_fn_t postreset)
1336 {
1337         struct ata_eh_context *ehc = &ap->eh_context;
1338         unsigned int *classes = ehc->classes;
1339         int tries = ATA_EH_RESET_TRIES;
1340         unsigned int action;
1341         ata_reset_fn_t reset;
1342         int i, did_followup_srst, rc;
1343
1344         /* Determine which reset to use and record in ehc->i.action.
1345          * prereset() may examine and modify it.
1346          */
1347         action = ehc->i.action;
1348         ehc->i.action &= ~ATA_EH_RESET_MASK;
1349         if (softreset && (!hardreset || (!sata_set_spd_needed(ap) &&
1350                                          !(action & ATA_EH_HARDRESET))))
1351                 ehc->i.action |= ATA_EH_SOFTRESET;
1352         else
1353                 ehc->i.action |= ATA_EH_HARDRESET;
1354
1355         if (prereset) {
1356                 rc = prereset(ap);
1357                 if (rc) {
1358                         ata_port_printk(ap, KERN_ERR,
1359                                         "prereset failed (errno=%d)\n", rc);
1360                         return rc;
1361                 }
1362         }
1363
1364         /* prereset() might have modified ehc->i.action */
1365         if (ehc->i.action & ATA_EH_HARDRESET)
1366                 reset = hardreset;
1367         else if (ehc->i.action & ATA_EH_SOFTRESET)
1368                 reset = softreset;
1369         else {
1370                 /* prereset told us not to reset, bang classes and return */
1371                 for (i = 0; i < ATA_MAX_DEVICES; i++)
1372                         classes[i] = ATA_DEV_NONE;
1373                 return 0;
1374         }
1375
1376         /* did prereset() screw up?  if so, fix up to avoid oopsing */
1377         if (!reset) {
1378                 ata_port_printk(ap, KERN_ERR, "BUG: prereset() requested "
1379                                 "invalid reset type\n");
1380                 if (softreset)
1381                         reset = softreset;
1382                 else
1383                         reset = hardreset;
1384         }
1385
1386  retry:
1387         ata_port_printk(ap, KERN_INFO, "%s resetting port\n",
1388                         reset == softreset ? "soft" : "hard");
1389
1390         /* reset */
1391         ata_eh_about_to_do(ap, ATA_EH_RESET_MASK);
1392         ehc->i.flags |= ATA_EHI_DID_RESET;
1393
1394         rc = ata_do_reset(ap, reset, classes);
1395
1396         did_followup_srst = 0;
1397         if (reset == hardreset &&
1398             ata_eh_followup_srst_needed(rc, classify, classes)) {
1399                 /* okay, let's do follow-up softreset */
1400                 did_followup_srst = 1;
1401                 reset = softreset;
1402
1403                 if (!reset) {
1404                         ata_port_printk(ap, KERN_ERR,
1405                                         "follow-up softreset required "
1406                                         "but no softreset avaliable\n");
1407                         return -EINVAL;
1408                 }
1409
1410                 ata_eh_about_to_do(ap, ATA_EH_RESET_MASK);
1411                 rc = ata_do_reset(ap, reset, classes);
1412
1413                 if (rc == 0 && classify &&
1414                     classes[0] == ATA_DEV_UNKNOWN) {
1415                         ata_port_printk(ap, KERN_ERR,
1416                                         "classification failed\n");
1417                         return -EINVAL;
1418                 }
1419         }
1420
1421         if (rc && --tries) {
1422                 const char *type;
1423
1424                 if (reset == softreset) {
1425                         if (did_followup_srst)
1426                                 type = "follow-up soft";
1427                         else
1428                                 type = "soft";
1429                 } else
1430                         type = "hard";
1431
1432                 ata_port_printk(ap, KERN_WARNING,
1433                                 "%sreset failed, retrying in 5 secs\n", type);
1434                 ssleep(5);
1435
1436                 if (reset == hardreset)
1437                         sata_down_spd_limit(ap);
1438                 if (hardreset)
1439                         reset = hardreset;
1440                 goto retry;
1441         }
1442
1443         if (rc == 0) {
1444                 /* After the reset, the device state is PIO 0 and the
1445                  * controller state is undefined.  Record the mode.
1446                  */
1447                 for (i = 0; i < ATA_MAX_DEVICES; i++)
1448                         ap->device[i].pio_mode = XFER_PIO_0;
1449
1450                 if (postreset)
1451                         postreset(ap, classes);
1452
1453                 /* reset successful, schedule revalidation */
1454                 ehc->i.dev = NULL;
1455                 ehc->i.action &= ~ATA_EH_RESET_MASK;
1456                 ehc->i.action |= ATA_EH_REVALIDATE;
1457         }
1458
1459         return rc;
1460 }
1461
1462 static int ata_eh_revalidate(struct ata_port *ap,
1463                              struct ata_device **r_failed_dev)
1464 {
1465         struct ata_eh_context *ehc = &ap->eh_context;
1466         struct ata_device *dev;
1467         int i, rc = 0;
1468
1469         DPRINTK("ENTER\n");
1470
1471         for (i = 0; i < ATA_MAX_DEVICES; i++) {
1472                 dev = &ap->device[i];
1473
1474                 if (ehc->i.action & ATA_EH_REVALIDATE && ata_dev_enabled(dev) &&
1475                     (!ehc->i.dev || ehc->i.dev == dev)) {
1476                         if (ata_port_offline(ap)) {
1477                                 rc = -EIO;
1478                                 break;
1479                         }
1480
1481                         ata_eh_about_to_do(ap, ATA_EH_REVALIDATE);
1482                         rc = ata_dev_revalidate(dev,
1483                                         ehc->i.flags & ATA_EHI_DID_RESET);
1484                         if (rc)
1485                                 break;
1486
1487                         ehc->i.action &= ~ATA_EH_REVALIDATE;
1488                 }
1489         }
1490
1491         if (rc)
1492                 *r_failed_dev = dev;
1493
1494         DPRINTK("EXIT\n");
1495         return rc;
1496 }
1497
1498 static int ata_port_nr_enabled(struct ata_port *ap)
1499 {
1500         int i, cnt = 0;
1501
1502         for (i = 0; i < ATA_MAX_DEVICES; i++)
1503                 if (ata_dev_enabled(&ap->device[i]))
1504                         cnt++;
1505         return cnt;
1506 }
1507
1508 /**
1509  *      ata_eh_recover - recover host port after error
1510  *      @ap: host port to recover
1511  *      @prereset: prereset method (can be NULL)
1512  *      @softreset: softreset method (can be NULL)
1513  *      @hardreset: hardreset method (can be NULL)
1514  *      @postreset: postreset method (can be NULL)
1515  *
1516  *      This is the alpha and omega, eum and yang, heart and soul of
1517  *      libata exception handling.  On entry, actions required to
1518  *      recover each devices are recorded in eh_context.  This
1519  *      function executes all the operations with appropriate retrials
1520  *      and fallbacks to resurrect failed devices.
1521  *
1522  *      LOCKING:
1523  *      Kernel thread context (may sleep).
1524  *
1525  *      RETURNS:
1526  *      0 on success, -errno on failure.
1527  */
1528 static int ata_eh_recover(struct ata_port *ap, ata_prereset_fn_t prereset,
1529                           ata_reset_fn_t softreset, ata_reset_fn_t hardreset,
1530                           ata_postreset_fn_t postreset)
1531 {
1532         struct ata_eh_context *ehc = &ap->eh_context;
1533         struct ata_device *dev;
1534         int down_xfermask, i, rc;
1535
1536         DPRINTK("ENTER\n");
1537
1538         /* prep for recovery */
1539         for (i = 0; i < ATA_MAX_DEVICES; i++) {
1540                 dev = &ap->device[i];
1541
1542                 ehc->tries[dev->devno] = ATA_EH_DEV_TRIES;
1543         }
1544
1545  retry:
1546         down_xfermask = 0;
1547         rc = 0;
1548
1549         /* skip EH if possible. */
1550         if (!ata_port_nr_enabled(ap) && !(ap->flags & ATA_FLAG_FROZEN))
1551                 ehc->i.action = 0;
1552
1553         /* reset */
1554         if (ehc->i.action & ATA_EH_RESET_MASK) {
1555                 ata_eh_freeze_port(ap);
1556
1557                 rc = ata_eh_reset(ap, 0, prereset, softreset, hardreset,
1558                                   postreset);
1559                 if (rc) {
1560                         ata_port_printk(ap, KERN_ERR,
1561                                         "reset failed, giving up\n");
1562                         goto out;
1563                 }
1564
1565                 ata_eh_thaw_port(ap);
1566         }
1567
1568         /* revalidate existing devices */
1569         rc = ata_eh_revalidate(ap, &dev);
1570         if (rc)
1571                 goto dev_fail;
1572
1573         /* configure transfer mode if the port has been reset */
1574         if (ehc->i.flags & ATA_EHI_DID_RESET) {
1575                 rc = ata_set_mode(ap, &dev);
1576                 if (rc) {
1577                         down_xfermask = 1;
1578                         goto dev_fail;
1579                 }
1580         }
1581
1582         goto out;
1583
1584  dev_fail:
1585         switch (rc) {
1586         case -ENODEV:
1587         case -EINVAL:
1588                 ehc->tries[dev->devno] = 0;
1589                 break;
1590         case -EIO:
1591                 sata_down_spd_limit(ap);
1592         default:
1593                 ehc->tries[dev->devno]--;
1594                 if (down_xfermask &&
1595                     ata_down_xfermask_limit(dev, ehc->tries[dev->devno] == 1))
1596                         ehc->tries[dev->devno] = 0;
1597         }
1598
1599         /* disable device if it has used up all its chances */
1600         if (ata_dev_enabled(dev) && !ehc->tries[dev->devno])
1601                 ata_dev_disable(dev);
1602
1603         /* soft didn't work?  be haaaaard */
1604         if (ehc->i.flags & ATA_EHI_DID_RESET)
1605                 ehc->i.action |= ATA_EH_HARDRESET;
1606         else
1607                 ehc->i.action |= ATA_EH_SOFTRESET;
1608
1609         if (ata_port_nr_enabled(ap)) {
1610                 ata_port_printk(ap, KERN_WARNING, "failed to recover some "
1611                                 "devices, retrying in 5 secs\n");
1612                 ssleep(5);
1613         } else {
1614                 /* no device left, repeat fast */
1615                 msleep(500);
1616         }
1617
1618         goto retry;
1619
1620  out:
1621         if (rc) {
1622                 for (i = 0; i < ATA_MAX_DEVICES; i++)
1623                         ata_dev_disable(&ap->device[i]);
1624         }
1625
1626         DPRINTK("EXIT, rc=%d\n", rc);
1627         return rc;
1628 }
1629
1630 /**
1631  *      ata_eh_finish - finish up EH
1632  *      @ap: host port to finish EH for
1633  *
1634  *      Recovery is complete.  Clean up EH states and retry or finish
1635  *      failed qcs.
1636  *
1637  *      LOCKING:
1638  *      None.
1639  */
1640 static void ata_eh_finish(struct ata_port *ap)
1641 {
1642         int tag;
1643
1644         /* retry or finish qcs */
1645         for (tag = 0; tag < ATA_MAX_QUEUE; tag++) {
1646                 struct ata_queued_cmd *qc = __ata_qc_from_tag(ap, tag);
1647
1648                 if (!(qc->flags & ATA_QCFLAG_FAILED))
1649                         continue;
1650
1651                 if (qc->err_mask) {
1652                         /* FIXME: Once EH migration is complete,
1653                          * generate sense data in this function,
1654                          * considering both err_mask and tf.
1655                          */
1656                         if (qc->err_mask & AC_ERR_INVALID)
1657                                 ata_eh_qc_complete(qc);
1658                         else
1659                                 ata_eh_qc_retry(qc);
1660                 } else {
1661                         if (qc->flags & ATA_QCFLAG_SENSE_VALID) {
1662                                 ata_eh_qc_complete(qc);
1663                         } else {
1664                                 /* feed zero TF to sense generation */
1665                                 memset(&qc->result_tf, 0, sizeof(qc->result_tf));
1666                                 ata_eh_qc_retry(qc);
1667                         }
1668                 }
1669         }
1670 }
1671
1672 /**
1673  *      ata_do_eh - do standard error handling
1674  *      @ap: host port to handle error for
1675  *      @prereset: prereset method (can be NULL)
1676  *      @softreset: softreset method (can be NULL)
1677  *      @hardreset: hardreset method (can be NULL)
1678  *      @postreset: postreset method (can be NULL)
1679  *
1680  *      Perform standard error handling sequence.
1681  *
1682  *      LOCKING:
1683  *      Kernel thread context (may sleep).
1684  */
1685 void ata_do_eh(struct ata_port *ap, ata_prereset_fn_t prereset,
1686                ata_reset_fn_t softreset, ata_reset_fn_t hardreset,
1687                ata_postreset_fn_t postreset)
1688 {
1689         ata_eh_autopsy(ap);
1690         ata_eh_report(ap);
1691         ata_eh_recover(ap, prereset, softreset, hardreset, postreset);
1692         ata_eh_finish(ap);
1693 }