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