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