Linux-libre 2.6.32.58-gnu1
[librecmc/linux-libre.git] / drivers / ata / libata-eh.c
1 /*
2  *  libata-eh.c - libata error handling
3  *
4  *  Maintained by:  Jeff Garzik <jgarzik@pobox.com>
5  *                  Please ALWAYS copy linux-ide@vger.kernel.org
6  *                  on emails.
7  *
8  *  Copyright 2006 Tejun Heo <htejun@gmail.com>
9  *
10  *
11  *  This program is free software; you can redistribute it and/or
12  *  modify it under the terms of the GNU General Public License as
13  *  published by the Free Software Foundation; either version 2, or
14  *  (at your option) any later version.
15  *
16  *  This program is distributed in the hope that it will be useful,
17  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
18  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  *  General Public License for more details.
20  *
21  *  You should have received a copy of the GNU General Public License
22  *  along with this program; see the file COPYING.  If not, write to
23  *  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139,
24  *  USA.
25  *
26  *
27  *  libata documentation is available via 'make {ps|pdf}docs',
28  *  as Documentation/DocBook/libata.*
29  *
30  *  Hardware documentation available from http://www.t13.org/ and
31  *  http://www.sata-io.org/
32  *
33  */
34
35 #include <linux/kernel.h>
36 #include <linux/blkdev.h>
37 #include <linux/pci.h>
38 #include <scsi/scsi.h>
39 #include <scsi/scsi_host.h>
40 #include <scsi/scsi_eh.h>
41 #include <scsi/scsi_device.h>
42 #include <scsi/scsi_cmnd.h>
43 #include <scsi/scsi_dbg.h>
44 #include "../scsi/scsi_transport_api.h"
45
46 #include <linux/libata.h>
47
48 #include "libata.h"
49
50 enum {
51         /* speed down verdicts */
52         ATA_EH_SPDN_NCQ_OFF             = (1 << 0),
53         ATA_EH_SPDN_SPEED_DOWN          = (1 << 1),
54         ATA_EH_SPDN_FALLBACK_TO_PIO     = (1 << 2),
55         ATA_EH_SPDN_KEEP_ERRORS         = (1 << 3),
56
57         /* error flags */
58         ATA_EFLAG_IS_IO                 = (1 << 0),
59         ATA_EFLAG_DUBIOUS_XFER          = (1 << 1),
60
61         /* error categories */
62         ATA_ECAT_NONE                   = 0,
63         ATA_ECAT_ATA_BUS                = 1,
64         ATA_ECAT_TOUT_HSM               = 2,
65         ATA_ECAT_UNK_DEV                = 3,
66         ATA_ECAT_DUBIOUS_NONE           = 4,
67         ATA_ECAT_DUBIOUS_ATA_BUS        = 5,
68         ATA_ECAT_DUBIOUS_TOUT_HSM       = 6,
69         ATA_ECAT_DUBIOUS_UNK_DEV        = 7,
70         ATA_ECAT_NR                     = 8,
71
72         ATA_EH_CMD_DFL_TIMEOUT          =  5000,
73
74         /* always put at least this amount of time between resets */
75         ATA_EH_RESET_COOL_DOWN          =  5000,
76
77         /* Waiting in ->prereset can never be reliable.  It's
78          * sometimes nice to wait there but it can't be depended upon;
79          * otherwise, we wouldn't be resetting.  Just give it enough
80          * time for most drives to spin up.
81          */
82         ATA_EH_PRERESET_TIMEOUT         = 10000,
83         ATA_EH_FASTDRAIN_INTERVAL       =  3000,
84
85         ATA_EH_UA_TRIES                 = 5,
86
87         /* probe speed down parameters, see ata_eh_schedule_probe() */
88         ATA_EH_PROBE_TRIAL_INTERVAL     = 60000,        /* 1 min */
89         ATA_EH_PROBE_TRIALS             = 2,
90 };
91
92 /* The following table determines how we sequence resets.  Each entry
93  * represents timeout for that try.  The first try can be soft or
94  * hardreset.  All others are hardreset if available.  In most cases
95  * the first reset w/ 10sec timeout should succeed.  Following entries
96  * are mostly for error handling, hotplug and retarded devices.
97  */
98 static const unsigned long ata_eh_reset_timeouts[] = {
99         10000,  /* most drives spin up by 10sec */
100         10000,  /* > 99% working drives spin up before 20sec */
101         35000,  /* give > 30 secs of idleness for retarded devices */
102          5000,  /* and sweet one last chance */
103         ULONG_MAX, /* > 1 min has elapsed, give up */
104 };
105
106 static const unsigned long ata_eh_identify_timeouts[] = {
107          5000,  /* covers > 99% of successes and not too boring on failures */
108         10000,  /* combined time till here is enough even for media access */
109         30000,  /* for true idiots */
110         ULONG_MAX,
111 };
112
113 static const unsigned long ata_eh_other_timeouts[] = {
114          5000,  /* same rationale as identify timeout */
115         10000,  /* ditto */
116         /* but no merciful 30sec for other commands, it just isn't worth it */
117         ULONG_MAX,
118 };
119
120 struct ata_eh_cmd_timeout_ent {
121         const u8                *commands;
122         const unsigned long     *timeouts;
123 };
124
125 /* The following table determines timeouts to use for EH internal
126  * commands.  Each table entry is a command class and matches the
127  * commands the entry applies to and the timeout table to use.
128  *
129  * On the retry after a command timed out, the next timeout value from
130  * the table is used.  If the table doesn't contain further entries,
131  * the last value is used.
132  *
133  * ehc->cmd_timeout_idx keeps track of which timeout to use per
134  * command class, so if SET_FEATURES times out on the first try, the
135  * next try will use the second timeout value only for that class.
136  */
137 #define CMDS(cmds...)   (const u8 []){ cmds, 0 }
138 static const struct ata_eh_cmd_timeout_ent
139 ata_eh_cmd_timeout_table[ATA_EH_CMD_TIMEOUT_TABLE_SIZE] = {
140         { .commands = CMDS(ATA_CMD_ID_ATA, ATA_CMD_ID_ATAPI),
141           .timeouts = ata_eh_identify_timeouts, },
142         { .commands = CMDS(ATA_CMD_READ_NATIVE_MAX, ATA_CMD_READ_NATIVE_MAX_EXT),
143           .timeouts = ata_eh_other_timeouts, },
144         { .commands = CMDS(ATA_CMD_SET_MAX, ATA_CMD_SET_MAX_EXT),
145           .timeouts = ata_eh_other_timeouts, },
146         { .commands = CMDS(ATA_CMD_SET_FEATURES),
147           .timeouts = ata_eh_other_timeouts, },
148         { .commands = CMDS(ATA_CMD_INIT_DEV_PARAMS),
149           .timeouts = ata_eh_other_timeouts, },
150 };
151 #undef CMDS
152
153 static void __ata_port_freeze(struct ata_port *ap);
154 #ifdef CONFIG_PM
155 static void ata_eh_handle_port_suspend(struct ata_port *ap);
156 static void ata_eh_handle_port_resume(struct ata_port *ap);
157 #else /* CONFIG_PM */
158 static void ata_eh_handle_port_suspend(struct ata_port *ap)
159 { }
160
161 static void ata_eh_handle_port_resume(struct ata_port *ap)
162 { }
163 #endif /* CONFIG_PM */
164
165 static void __ata_ehi_pushv_desc(struct ata_eh_info *ehi, const char *fmt,
166                                  va_list args)
167 {
168         ehi->desc_len += vscnprintf(ehi->desc + ehi->desc_len,
169                                      ATA_EH_DESC_LEN - ehi->desc_len,
170                                      fmt, args);
171 }
172
173 /**
174  *      __ata_ehi_push_desc - push error description without adding separator
175  *      @ehi: target EHI
176  *      @fmt: printf format string
177  *
178  *      Format string according to @fmt and append it to @ehi->desc.
179  *
180  *      LOCKING:
181  *      spin_lock_irqsave(host lock)
182  */
183 void __ata_ehi_push_desc(struct ata_eh_info *ehi, const char *fmt, ...)
184 {
185         va_list args;
186
187         va_start(args, fmt);
188         __ata_ehi_pushv_desc(ehi, fmt, args);
189         va_end(args);
190 }
191
192 /**
193  *      ata_ehi_push_desc - push error description with separator
194  *      @ehi: target EHI
195  *      @fmt: printf format string
196  *
197  *      Format string according to @fmt and append it to @ehi->desc.
198  *      If @ehi->desc is not empty, ", " is added in-between.
199  *
200  *      LOCKING:
201  *      spin_lock_irqsave(host lock)
202  */
203 void ata_ehi_push_desc(struct ata_eh_info *ehi, const char *fmt, ...)
204 {
205         va_list args;
206
207         if (ehi->desc_len)
208                 __ata_ehi_push_desc(ehi, ", ");
209
210         va_start(args, fmt);
211         __ata_ehi_pushv_desc(ehi, fmt, args);
212         va_end(args);
213 }
214
215 /**
216  *      ata_ehi_clear_desc - clean error description
217  *      @ehi: target EHI
218  *
219  *      Clear @ehi->desc.
220  *
221  *      LOCKING:
222  *      spin_lock_irqsave(host lock)
223  */
224 void ata_ehi_clear_desc(struct ata_eh_info *ehi)
225 {
226         ehi->desc[0] = '\0';
227         ehi->desc_len = 0;
228 }
229
230 /**
231  *      ata_port_desc - append port description
232  *      @ap: target ATA port
233  *      @fmt: printf format string
234  *
235  *      Format string according to @fmt and append it to port
236  *      description.  If port description is not empty, " " is added
237  *      in-between.  This function is to be used while initializing
238  *      ata_host.  The description is printed on host registration.
239  *
240  *      LOCKING:
241  *      None.
242  */
243 void ata_port_desc(struct ata_port *ap, const char *fmt, ...)
244 {
245         va_list args;
246
247         WARN_ON(!(ap->pflags & ATA_PFLAG_INITIALIZING));
248
249         if (ap->link.eh_info.desc_len)
250                 __ata_ehi_push_desc(&ap->link.eh_info, " ");
251
252         va_start(args, fmt);
253         __ata_ehi_pushv_desc(&ap->link.eh_info, fmt, args);
254         va_end(args);
255 }
256
257 #ifdef CONFIG_PCI
258
259 /**
260  *      ata_port_pbar_desc - append PCI BAR description
261  *      @ap: target ATA port
262  *      @bar: target PCI BAR
263  *      @offset: offset into PCI BAR
264  *      @name: name of the area
265  *
266  *      If @offset is negative, this function formats a string which
267  *      contains the name, address, size and type of the BAR and
268  *      appends it to the port description.  If @offset is zero or
269  *      positive, only name and offsetted address is appended.
270  *
271  *      LOCKING:
272  *      None.
273  */
274 void ata_port_pbar_desc(struct ata_port *ap, int bar, ssize_t offset,
275                         const char *name)
276 {
277         struct pci_dev *pdev = to_pci_dev(ap->host->dev);
278         char *type = "";
279         unsigned long long start, len;
280
281         if (pci_resource_flags(pdev, bar) & IORESOURCE_MEM)
282                 type = "m";
283         else if (pci_resource_flags(pdev, bar) & IORESOURCE_IO)
284                 type = "i";
285
286         start = (unsigned long long)pci_resource_start(pdev, bar);
287         len = (unsigned long long)pci_resource_len(pdev, bar);
288
289         if (offset < 0)
290                 ata_port_desc(ap, "%s %s%llu@0x%llx", name, type, len, start);
291         else
292                 ata_port_desc(ap, "%s 0x%llx", name,
293                                 start + (unsigned long long)offset);
294 }
295
296 #endif /* CONFIG_PCI */
297
298 static int ata_lookup_timeout_table(u8 cmd)
299 {
300         int i;
301
302         for (i = 0; i < ATA_EH_CMD_TIMEOUT_TABLE_SIZE; i++) {
303                 const u8 *cur;
304
305                 for (cur = ata_eh_cmd_timeout_table[i].commands; *cur; cur++)
306                         if (*cur == cmd)
307                                 return i;
308         }
309
310         return -1;
311 }
312
313 /**
314  *      ata_internal_cmd_timeout - determine timeout for an internal command
315  *      @dev: target device
316  *      @cmd: internal command to be issued
317  *
318  *      Determine timeout for internal command @cmd for @dev.
319  *
320  *      LOCKING:
321  *      EH context.
322  *
323  *      RETURNS:
324  *      Determined timeout.
325  */
326 unsigned long ata_internal_cmd_timeout(struct ata_device *dev, u8 cmd)
327 {
328         struct ata_eh_context *ehc = &dev->link->eh_context;
329         int ent = ata_lookup_timeout_table(cmd);
330         int idx;
331
332         if (ent < 0)
333                 return ATA_EH_CMD_DFL_TIMEOUT;
334
335         idx = ehc->cmd_timeout_idx[dev->devno][ent];
336         return ata_eh_cmd_timeout_table[ent].timeouts[idx];
337 }
338
339 /**
340  *      ata_internal_cmd_timed_out - notification for internal command timeout
341  *      @dev: target device
342  *      @cmd: internal command which timed out
343  *
344  *      Notify EH that internal command @cmd for @dev timed out.  This
345  *      function should be called only for commands whose timeouts are
346  *      determined using ata_internal_cmd_timeout().
347  *
348  *      LOCKING:
349  *      EH context.
350  */
351 void ata_internal_cmd_timed_out(struct ata_device *dev, u8 cmd)
352 {
353         struct ata_eh_context *ehc = &dev->link->eh_context;
354         int ent = ata_lookup_timeout_table(cmd);
355         int idx;
356
357         if (ent < 0)
358                 return;
359
360         idx = ehc->cmd_timeout_idx[dev->devno][ent];
361         if (ata_eh_cmd_timeout_table[ent].timeouts[idx + 1] != ULONG_MAX)
362                 ehc->cmd_timeout_idx[dev->devno][ent]++;
363 }
364
365 static void ata_ering_record(struct ata_ering *ering, unsigned int eflags,
366                              unsigned int err_mask)
367 {
368         struct ata_ering_entry *ent;
369
370         WARN_ON(!err_mask);
371
372         ering->cursor++;
373         ering->cursor %= ATA_ERING_SIZE;
374
375         ent = &ering->ring[ering->cursor];
376         ent->eflags = eflags;
377         ent->err_mask = err_mask;
378         ent->timestamp = get_jiffies_64();
379 }
380
381 static struct ata_ering_entry *ata_ering_top(struct ata_ering *ering)
382 {
383         struct ata_ering_entry *ent = &ering->ring[ering->cursor];
384
385         if (ent->err_mask)
386                 return ent;
387         return NULL;
388 }
389
390 static void ata_ering_clear(struct ata_ering *ering)
391 {
392         memset(ering, 0, sizeof(*ering));
393 }
394
395 static int ata_ering_map(struct ata_ering *ering,
396                          int (*map_fn)(struct ata_ering_entry *, void *),
397                          void *arg)
398 {
399         int idx, rc = 0;
400         struct ata_ering_entry *ent;
401
402         idx = ering->cursor;
403         do {
404                 ent = &ering->ring[idx];
405                 if (!ent->err_mask)
406                         break;
407                 rc = map_fn(ent, arg);
408                 if (rc)
409                         break;
410                 idx = (idx - 1 + ATA_ERING_SIZE) % ATA_ERING_SIZE;
411         } while (idx != ering->cursor);
412
413         return rc;
414 }
415
416 static unsigned int ata_eh_dev_action(struct ata_device *dev)
417 {
418         struct ata_eh_context *ehc = &dev->link->eh_context;
419
420         return ehc->i.action | ehc->i.dev_action[dev->devno];
421 }
422
423 static void ata_eh_clear_action(struct ata_link *link, struct ata_device *dev,
424                                 struct ata_eh_info *ehi, unsigned int action)
425 {
426         struct ata_device *tdev;
427
428         if (!dev) {
429                 ehi->action &= ~action;
430                 ata_for_each_dev(tdev, link, ALL)
431                         ehi->dev_action[tdev->devno] &= ~action;
432         } else {
433                 /* doesn't make sense for port-wide EH actions */
434                 WARN_ON(!(action & ATA_EH_PERDEV_MASK));
435
436                 /* break ehi->action into ehi->dev_action */
437                 if (ehi->action & action) {
438                         ata_for_each_dev(tdev, link, ALL)
439                                 ehi->dev_action[tdev->devno] |=
440                                         ehi->action & action;
441                         ehi->action &= ~action;
442                 }
443
444                 /* turn off the specified per-dev action */
445                 ehi->dev_action[dev->devno] &= ~action;
446         }
447 }
448
449 /**
450  *      ata_scsi_timed_out - SCSI layer time out callback
451  *      @cmd: timed out SCSI command
452  *
453  *      Handles SCSI layer timeout.  We race with normal completion of
454  *      the qc for @cmd.  If the qc is already gone, we lose and let
455  *      the scsi command finish (EH_HANDLED).  Otherwise, the qc has
456  *      timed out and EH should be invoked.  Prevent ata_qc_complete()
457  *      from finishing it by setting EH_SCHEDULED and return
458  *      EH_NOT_HANDLED.
459  *
460  *      TODO: kill this function once old EH is gone.
461  *
462  *      LOCKING:
463  *      Called from timer context
464  *
465  *      RETURNS:
466  *      EH_HANDLED or EH_NOT_HANDLED
467  */
468 enum blk_eh_timer_return ata_scsi_timed_out(struct scsi_cmnd *cmd)
469 {
470         struct Scsi_Host *host = cmd->device->host;
471         struct ata_port *ap = ata_shost_to_port(host);
472         unsigned long flags;
473         struct ata_queued_cmd *qc;
474         enum blk_eh_timer_return ret;
475
476         DPRINTK("ENTER\n");
477
478         if (ap->ops->error_handler) {
479                 ret = BLK_EH_NOT_HANDLED;
480                 goto out;
481         }
482
483         ret = BLK_EH_HANDLED;
484         spin_lock_irqsave(ap->lock, flags);
485         qc = ata_qc_from_tag(ap, ap->link.active_tag);
486         if (qc) {
487                 WARN_ON(qc->scsicmd != cmd);
488                 qc->flags |= ATA_QCFLAG_EH_SCHEDULED;
489                 qc->err_mask |= AC_ERR_TIMEOUT;
490                 ret = BLK_EH_NOT_HANDLED;
491         }
492         spin_unlock_irqrestore(ap->lock, flags);
493
494  out:
495         DPRINTK("EXIT, ret=%d\n", ret);
496         return ret;
497 }
498
499 static void ata_eh_unload(struct ata_port *ap)
500 {
501         struct ata_link *link;
502         struct ata_device *dev;
503         unsigned long flags;
504
505         /* Restore SControl IPM and SPD for the next driver and
506          * disable attached devices.
507          */
508         ata_for_each_link(link, ap, PMP_FIRST) {
509                 sata_scr_write(link, SCR_CONTROL, link->saved_scontrol & 0xff0);
510                 ata_for_each_dev(dev, link, ALL)
511                         ata_dev_disable(dev);
512         }
513
514         /* freeze and set UNLOADED */
515         spin_lock_irqsave(ap->lock, flags);
516
517         ata_port_freeze(ap);                    /* won't be thawed */
518         ap->pflags &= ~ATA_PFLAG_EH_PENDING;    /* clear pending from freeze */
519         ap->pflags |= ATA_PFLAG_UNLOADED;
520
521         spin_unlock_irqrestore(ap->lock, flags);
522 }
523
524 /**
525  *      ata_scsi_error - SCSI layer error handler callback
526  *      @host: SCSI host on which error occurred
527  *
528  *      Handles SCSI-layer-thrown error events.
529  *
530  *      LOCKING:
531  *      Inherited from SCSI layer (none, can sleep)
532  *
533  *      RETURNS:
534  *      Zero.
535  */
536 void ata_scsi_error(struct Scsi_Host *host)
537 {
538         struct ata_port *ap = ata_shost_to_port(host);
539         int i;
540         unsigned long flags;
541
542         DPRINTK("ENTER\n");
543
544         /* synchronize with port task */
545         ata_port_flush_task(ap);
546
547         /* synchronize with host lock and sort out timeouts */
548
549         /* For new EH, all qcs are finished in one of three ways -
550          * normal completion, error completion, and SCSI timeout.
551          * Both completions can race against SCSI timeout.  When normal
552          * completion wins, the qc never reaches EH.  When error
553          * completion wins, the qc has ATA_QCFLAG_FAILED set.
554          *
555          * When SCSI timeout wins, things are a bit more complex.
556          * Normal or error completion can occur after the timeout but
557          * before this point.  In such cases, both types of
558          * completions are honored.  A scmd is determined to have
559          * timed out iff its associated qc is active and not failed.
560          */
561         if (ap->ops->error_handler) {
562                 struct scsi_cmnd *scmd, *tmp;
563                 int nr_timedout = 0;
564
565                 spin_lock_irqsave(ap->lock, flags);
566                 
567                 /* This must occur under the ap->lock as we don't want
568                    a polled recovery to race the real interrupt handler
569                    
570                    The lost_interrupt handler checks for any completed but
571                    non-notified command and completes much like an IRQ handler.
572                    
573                    We then fall into the error recovery code which will treat
574                    this as if normal completion won the race */
575
576                 if (ap->ops->lost_interrupt)
577                         ap->ops->lost_interrupt(ap);
578                         
579                 list_for_each_entry_safe(scmd, tmp, &host->eh_cmd_q, eh_entry) {
580                         struct ata_queued_cmd *qc;
581
582                         for (i = 0; i < ATA_MAX_QUEUE; i++) {
583                                 qc = __ata_qc_from_tag(ap, i);
584                                 if (qc->flags & ATA_QCFLAG_ACTIVE &&
585                                     qc->scsicmd == scmd)
586                                         break;
587                         }
588
589                         if (i < ATA_MAX_QUEUE) {
590                                 /* the scmd has an associated qc */
591                                 if (!(qc->flags & ATA_QCFLAG_FAILED)) {
592                                         /* which hasn't failed yet, timeout */
593                                         qc->err_mask |= AC_ERR_TIMEOUT;
594                                         qc->flags |= ATA_QCFLAG_FAILED;
595                                         nr_timedout++;
596                                 }
597                         } else {
598                                 /* Normal completion occurred after
599                                  * SCSI timeout but before this point.
600                                  * Successfully complete it.
601                                  */
602                                 scmd->retries = scmd->allowed;
603                                 scsi_eh_finish_cmd(scmd, &ap->eh_done_q);
604                         }
605                 }
606
607                 /* If we have timed out qcs.  They belong to EH from
608                  * this point but the state of the controller is
609                  * unknown.  Freeze the port to make sure the IRQ
610                  * handler doesn't diddle with those qcs.  This must
611                  * be done atomically w.r.t. setting QCFLAG_FAILED.
612                  */
613                 if (nr_timedout)
614                         __ata_port_freeze(ap);
615
616                 spin_unlock_irqrestore(ap->lock, flags);
617
618                 /* initialize eh_tries */
619                 ap->eh_tries = ATA_EH_MAX_TRIES;
620         } else
621                 spin_unlock_wait(ap->lock);
622                 
623         /* If we timed raced normal completion and there is nothing to
624            recover nr_timedout == 0 why exactly are we doing error recovery ? */
625
626  repeat:
627         /* invoke error handler */
628         if (ap->ops->error_handler) {
629                 struct ata_link *link;
630
631                 /* kill fast drain timer */
632                 del_timer_sync(&ap->fastdrain_timer);
633
634                 /* process port resume request */
635                 ata_eh_handle_port_resume(ap);
636
637                 /* fetch & clear EH info */
638                 spin_lock_irqsave(ap->lock, flags);
639
640                 ata_for_each_link(link, ap, HOST_FIRST) {
641                         struct ata_eh_context *ehc = &link->eh_context;
642                         struct ata_device *dev;
643
644                         memset(&link->eh_context, 0, sizeof(link->eh_context));
645                         link->eh_context.i = link->eh_info;
646                         memset(&link->eh_info, 0, sizeof(link->eh_info));
647
648                         ata_for_each_dev(dev, link, ENABLED) {
649                                 int devno = dev->devno;
650
651                                 ehc->saved_xfer_mode[devno] = dev->xfer_mode;
652                                 if (ata_ncq_enabled(dev))
653                                         ehc->saved_ncq_enabled |= 1 << devno;
654                         }
655                 }
656
657                 ap->pflags |= ATA_PFLAG_EH_IN_PROGRESS;
658                 ap->pflags &= ~ATA_PFLAG_EH_PENDING;
659                 ap->excl_link = NULL;   /* don't maintain exclusion over EH */
660
661                 spin_unlock_irqrestore(ap->lock, flags);
662
663                 /* invoke EH, skip if unloading or suspended */
664                 if (!(ap->pflags & (ATA_PFLAG_UNLOADING | ATA_PFLAG_SUSPENDED)))
665                         ap->ops->error_handler(ap);
666                 else {
667                         /* if unloading, commence suicide */
668                         if ((ap->pflags & ATA_PFLAG_UNLOADING) &&
669                             !(ap->pflags & ATA_PFLAG_UNLOADED))
670                                 ata_eh_unload(ap);
671                         ata_eh_finish(ap);
672                 }
673
674                 /* process port suspend request */
675                 ata_eh_handle_port_suspend(ap);
676
677                 /* Exception might have happend after ->error_handler
678                  * recovered the port but before this point.  Repeat
679                  * EH in such case.
680                  */
681                 spin_lock_irqsave(ap->lock, flags);
682
683                 if (ap->pflags & ATA_PFLAG_EH_PENDING) {
684                         if (--ap->eh_tries) {
685                                 spin_unlock_irqrestore(ap->lock, flags);
686                                 goto repeat;
687                         }
688                         ata_port_printk(ap, KERN_ERR, "EH pending after %d "
689                                         "tries, giving up\n", ATA_EH_MAX_TRIES);
690                         ap->pflags &= ~ATA_PFLAG_EH_PENDING;
691                 }
692
693                 /* this run is complete, make sure EH info is clear */
694                 ata_for_each_link(link, ap, HOST_FIRST)
695                         memset(&link->eh_info, 0, sizeof(link->eh_info));
696
697                 /* Clear host_eh_scheduled while holding ap->lock such
698                  * that if exception occurs after this point but
699                  * before EH completion, SCSI midlayer will
700                  * re-initiate EH.
701                  */
702                 host->host_eh_scheduled = 0;
703
704                 spin_unlock_irqrestore(ap->lock, flags);
705         } else {
706                 WARN_ON(ata_qc_from_tag(ap, ap->link.active_tag) == NULL);
707                 ap->ops->eng_timeout(ap);
708         }
709
710         /* finish or retry handled scmd's and clean up */
711         WARN_ON(host->host_failed || !list_empty(&host->eh_cmd_q));
712
713         scsi_eh_flush_done_q(&ap->eh_done_q);
714
715         /* clean up */
716         spin_lock_irqsave(ap->lock, flags);
717
718         if (ap->pflags & ATA_PFLAG_LOADING)
719                 ap->pflags &= ~ATA_PFLAG_LOADING;
720         else if (ap->pflags & ATA_PFLAG_SCSI_HOTPLUG)
721                 queue_delayed_work(ata_aux_wq, &ap->hotplug_task, 0);
722
723         if (ap->pflags & ATA_PFLAG_RECOVERED)
724                 ata_port_printk(ap, KERN_INFO, "EH complete\n");
725
726         ap->pflags &= ~(ATA_PFLAG_SCSI_HOTPLUG | ATA_PFLAG_RECOVERED);
727
728         /* tell wait_eh that we're done */
729         ap->pflags &= ~ATA_PFLAG_EH_IN_PROGRESS;
730         wake_up_all(&ap->eh_wait_q);
731
732         spin_unlock_irqrestore(ap->lock, flags);
733
734         DPRINTK("EXIT\n");
735 }
736
737 /**
738  *      ata_port_wait_eh - Wait for the currently pending EH to complete
739  *      @ap: Port to wait EH for
740  *
741  *      Wait until the currently pending EH is complete.
742  *
743  *      LOCKING:
744  *      Kernel thread context (may sleep).
745  */
746 void ata_port_wait_eh(struct ata_port *ap)
747 {
748         unsigned long flags;
749         DEFINE_WAIT(wait);
750
751  retry:
752         spin_lock_irqsave(ap->lock, flags);
753
754         while (ap->pflags & (ATA_PFLAG_EH_PENDING | ATA_PFLAG_EH_IN_PROGRESS)) {
755                 prepare_to_wait(&ap->eh_wait_q, &wait, TASK_UNINTERRUPTIBLE);
756                 spin_unlock_irqrestore(ap->lock, flags);
757                 schedule();
758                 spin_lock_irqsave(ap->lock, flags);
759         }
760         finish_wait(&ap->eh_wait_q, &wait);
761
762         spin_unlock_irqrestore(ap->lock, flags);
763
764         /* make sure SCSI EH is complete */
765         if (scsi_host_in_recovery(ap->scsi_host)) {
766                 msleep(10);
767                 goto retry;
768         }
769 }
770
771 static int ata_eh_nr_in_flight(struct ata_port *ap)
772 {
773         unsigned int tag;
774         int nr = 0;
775
776         /* count only non-internal commands */
777         for (tag = 0; tag < ATA_MAX_QUEUE - 1; tag++)
778                 if (ata_qc_from_tag(ap, tag))
779                         nr++;
780
781         return nr;
782 }
783
784 void ata_eh_fastdrain_timerfn(unsigned long arg)
785 {
786         struct ata_port *ap = (void *)arg;
787         unsigned long flags;
788         int cnt;
789
790         spin_lock_irqsave(ap->lock, flags);
791
792         cnt = ata_eh_nr_in_flight(ap);
793
794         /* are we done? */
795         if (!cnt)
796                 goto out_unlock;
797
798         if (cnt == ap->fastdrain_cnt) {
799                 unsigned int tag;
800
801                 /* No progress during the last interval, tag all
802                  * in-flight qcs as timed out and freeze the port.
803                  */
804                 for (tag = 0; tag < ATA_MAX_QUEUE - 1; tag++) {
805                         struct ata_queued_cmd *qc = ata_qc_from_tag(ap, tag);
806                         if (qc)
807                                 qc->err_mask |= AC_ERR_TIMEOUT;
808                 }
809
810                 ata_port_freeze(ap);
811         } else {
812                 /* some qcs have finished, give it another chance */
813                 ap->fastdrain_cnt = cnt;
814                 ap->fastdrain_timer.expires =
815                         ata_deadline(jiffies, ATA_EH_FASTDRAIN_INTERVAL);
816                 add_timer(&ap->fastdrain_timer);
817         }
818
819  out_unlock:
820         spin_unlock_irqrestore(ap->lock, flags);
821 }
822
823 /**
824  *      ata_eh_set_pending - set ATA_PFLAG_EH_PENDING and activate fast drain
825  *      @ap: target ATA port
826  *      @fastdrain: activate fast drain
827  *
828  *      Set ATA_PFLAG_EH_PENDING and activate fast drain if @fastdrain
829  *      is non-zero and EH wasn't pending before.  Fast drain ensures
830  *      that EH kicks in in timely manner.
831  *
832  *      LOCKING:
833  *      spin_lock_irqsave(host lock)
834  */
835 static void ata_eh_set_pending(struct ata_port *ap, int fastdrain)
836 {
837         int cnt;
838
839         /* already scheduled? */
840         if (ap->pflags & ATA_PFLAG_EH_PENDING)
841                 return;
842
843         ap->pflags |= ATA_PFLAG_EH_PENDING;
844
845         if (!fastdrain)
846                 return;
847
848         /* do we have in-flight qcs? */
849         cnt = ata_eh_nr_in_flight(ap);
850         if (!cnt)
851                 return;
852
853         /* activate fast drain */
854         ap->fastdrain_cnt = cnt;
855         ap->fastdrain_timer.expires =
856                 ata_deadline(jiffies, ATA_EH_FASTDRAIN_INTERVAL);
857         add_timer(&ap->fastdrain_timer);
858 }
859
860 /**
861  *      ata_qc_schedule_eh - schedule qc for error handling
862  *      @qc: command to schedule error handling for
863  *
864  *      Schedule error handling for @qc.  EH will kick in as soon as
865  *      other commands are drained.
866  *
867  *      LOCKING:
868  *      spin_lock_irqsave(host lock)
869  */
870 void ata_qc_schedule_eh(struct ata_queued_cmd *qc)
871 {
872         struct ata_port *ap = qc->ap;
873         struct request_queue *q = qc->scsicmd->device->request_queue;
874         unsigned long flags;
875
876         WARN_ON(!ap->ops->error_handler);
877
878         qc->flags |= ATA_QCFLAG_FAILED;
879         ata_eh_set_pending(ap, 1);
880
881         /* The following will fail if timeout has already expired.
882          * ata_scsi_error() takes care of such scmds on EH entry.
883          * Note that ATA_QCFLAG_FAILED is unconditionally set after
884          * this function completes.
885          */
886         spin_lock_irqsave(q->queue_lock, flags);
887         blk_abort_request(qc->scsicmd->request);
888         spin_unlock_irqrestore(q->queue_lock, flags);
889 }
890
891 /**
892  *      ata_port_schedule_eh - schedule error handling without a qc
893  *      @ap: ATA port to schedule EH for
894  *
895  *      Schedule error handling for @ap.  EH will kick in as soon as
896  *      all commands are drained.
897  *
898  *      LOCKING:
899  *      spin_lock_irqsave(host lock)
900  */
901 void ata_port_schedule_eh(struct ata_port *ap)
902 {
903         WARN_ON(!ap->ops->error_handler);
904
905         if (ap->pflags & ATA_PFLAG_INITIALIZING)
906                 return;
907
908         ata_eh_set_pending(ap, 1);
909         scsi_schedule_eh(ap->scsi_host);
910
911         DPRINTK("port EH scheduled\n");
912 }
913
914 static int ata_do_link_abort(struct ata_port *ap, struct ata_link *link)
915 {
916         int tag, nr_aborted = 0;
917
918         WARN_ON(!ap->ops->error_handler);
919
920         /* we're gonna abort all commands, no need for fast drain */
921         ata_eh_set_pending(ap, 0);
922
923         for (tag = 0; tag < ATA_MAX_QUEUE; tag++) {
924                 struct ata_queued_cmd *qc = ata_qc_from_tag(ap, tag);
925
926                 if (qc && (!link || qc->dev->link == link)) {
927                         qc->flags |= ATA_QCFLAG_FAILED;
928                         ata_qc_complete(qc);
929                         nr_aborted++;
930                 }
931         }
932
933         if (!nr_aborted)
934                 ata_port_schedule_eh(ap);
935
936         return nr_aborted;
937 }
938
939 /**
940  *      ata_link_abort - abort all qc's on the link
941  *      @link: ATA link to abort qc's for
942  *
943  *      Abort all active qc's active on @link and schedule EH.
944  *
945  *      LOCKING:
946  *      spin_lock_irqsave(host lock)
947  *
948  *      RETURNS:
949  *      Number of aborted qc's.
950  */
951 int ata_link_abort(struct ata_link *link)
952 {
953         return ata_do_link_abort(link->ap, link);
954 }
955
956 /**
957  *      ata_port_abort - abort all qc's on the port
958  *      @ap: ATA port to abort qc's for
959  *
960  *      Abort all active qc's of @ap and schedule EH.
961  *
962  *      LOCKING:
963  *      spin_lock_irqsave(host_set lock)
964  *
965  *      RETURNS:
966  *      Number of aborted qc's.
967  */
968 int ata_port_abort(struct ata_port *ap)
969 {
970         return ata_do_link_abort(ap, NULL);
971 }
972
973 /**
974  *      __ata_port_freeze - freeze port
975  *      @ap: ATA port to freeze
976  *
977  *      This function is called when HSM violation or some other
978  *      condition disrupts normal operation of the port.  Frozen port
979  *      is not allowed to perform any operation until the port is
980  *      thawed, which usually follows a successful reset.
981  *
982  *      ap->ops->freeze() callback can be used for freezing the port
983  *      hardware-wise (e.g. mask interrupt and stop DMA engine).  If a
984  *      port cannot be frozen hardware-wise, the interrupt handler
985  *      must ack and clear interrupts unconditionally while the port
986  *      is frozen.
987  *
988  *      LOCKING:
989  *      spin_lock_irqsave(host lock)
990  */
991 static void __ata_port_freeze(struct ata_port *ap)
992 {
993         WARN_ON(!ap->ops->error_handler);
994
995         if (ap->ops->freeze)
996                 ap->ops->freeze(ap);
997
998         ap->pflags |= ATA_PFLAG_FROZEN;
999
1000         DPRINTK("ata%u port frozen\n", ap->print_id);
1001 }
1002
1003 /**
1004  *      ata_port_freeze - abort & freeze port
1005  *      @ap: ATA port to freeze
1006  *
1007  *      Abort and freeze @ap.  The freeze operation must be called
1008  *      first, because some hardware requires special operations
1009  *      before the taskfile registers are accessible.
1010  *
1011  *      LOCKING:
1012  *      spin_lock_irqsave(host lock)
1013  *
1014  *      RETURNS:
1015  *      Number of aborted commands.
1016  */
1017 int ata_port_freeze(struct ata_port *ap)
1018 {
1019         int nr_aborted;
1020
1021         WARN_ON(!ap->ops->error_handler);
1022
1023         __ata_port_freeze(ap);
1024         nr_aborted = ata_port_abort(ap);
1025
1026         return nr_aborted;
1027 }
1028
1029 /**
1030  *      sata_async_notification - SATA async notification handler
1031  *      @ap: ATA port where async notification is received
1032  *
1033  *      Handler to be called when async notification via SDB FIS is
1034  *      received.  This function schedules EH if necessary.
1035  *
1036  *      LOCKING:
1037  *      spin_lock_irqsave(host lock)
1038  *
1039  *      RETURNS:
1040  *      1 if EH is scheduled, 0 otherwise.
1041  */
1042 int sata_async_notification(struct ata_port *ap)
1043 {
1044         u32 sntf;
1045         int rc;
1046
1047         if (!(ap->flags & ATA_FLAG_AN))
1048                 return 0;
1049
1050         rc = sata_scr_read(&ap->link, SCR_NOTIFICATION, &sntf);
1051         if (rc == 0)
1052                 sata_scr_write(&ap->link, SCR_NOTIFICATION, sntf);
1053
1054         if (!sata_pmp_attached(ap) || rc) {
1055                 /* PMP is not attached or SNTF is not available */
1056                 if (!sata_pmp_attached(ap)) {
1057                         /* PMP is not attached.  Check whether ATAPI
1058                          * AN is configured.  If so, notify media
1059                          * change.
1060                          */
1061                         struct ata_device *dev = ap->link.device;
1062
1063                         if ((dev->class == ATA_DEV_ATAPI) &&
1064                             (dev->flags & ATA_DFLAG_AN))
1065                                 ata_scsi_media_change_notify(dev);
1066                         return 0;
1067                 } else {
1068                         /* PMP is attached but SNTF is not available.
1069                          * ATAPI async media change notification is
1070                          * not used.  The PMP must be reporting PHY
1071                          * status change, schedule EH.
1072                          */
1073                         ata_port_schedule_eh(ap);
1074                         return 1;
1075                 }
1076         } else {
1077                 /* PMP is attached and SNTF is available */
1078                 struct ata_link *link;
1079
1080                 /* check and notify ATAPI AN */
1081                 ata_for_each_link(link, ap, EDGE) {
1082                         if (!(sntf & (1 << link->pmp)))
1083                                 continue;
1084
1085                         if ((link->device->class == ATA_DEV_ATAPI) &&
1086                             (link->device->flags & ATA_DFLAG_AN))
1087                                 ata_scsi_media_change_notify(link->device);
1088                 }
1089
1090                 /* If PMP is reporting that PHY status of some
1091                  * downstream ports has changed, schedule EH.
1092                  */
1093                 if (sntf & (1 << SATA_PMP_CTRL_PORT)) {
1094                         ata_port_schedule_eh(ap);
1095                         return 1;
1096                 }
1097
1098                 return 0;
1099         }
1100 }
1101
1102 /**
1103  *      ata_eh_freeze_port - EH helper to freeze port
1104  *      @ap: ATA port to freeze
1105  *
1106  *      Freeze @ap.
1107  *
1108  *      LOCKING:
1109  *      None.
1110  */
1111 void ata_eh_freeze_port(struct ata_port *ap)
1112 {
1113         unsigned long flags;
1114
1115         if (!ap->ops->error_handler)
1116                 return;
1117
1118         spin_lock_irqsave(ap->lock, flags);
1119         __ata_port_freeze(ap);
1120         spin_unlock_irqrestore(ap->lock, flags);
1121 }
1122
1123 /**
1124  *      ata_port_thaw_port - EH helper to thaw port
1125  *      @ap: ATA port to thaw
1126  *
1127  *      Thaw frozen port @ap.
1128  *
1129  *      LOCKING:
1130  *      None.
1131  */
1132 void ata_eh_thaw_port(struct ata_port *ap)
1133 {
1134         unsigned long flags;
1135
1136         if (!ap->ops->error_handler)
1137                 return;
1138
1139         spin_lock_irqsave(ap->lock, flags);
1140
1141         ap->pflags &= ~ATA_PFLAG_FROZEN;
1142
1143         if (ap->ops->thaw)
1144                 ap->ops->thaw(ap);
1145
1146         spin_unlock_irqrestore(ap->lock, flags);
1147
1148         DPRINTK("ata%u port thawed\n", ap->print_id);
1149 }
1150
1151 static void ata_eh_scsidone(struct scsi_cmnd *scmd)
1152 {
1153         /* nada */
1154 }
1155
1156 static void __ata_eh_qc_complete(struct ata_queued_cmd *qc)
1157 {
1158         struct ata_port *ap = qc->ap;
1159         struct scsi_cmnd *scmd = qc->scsicmd;
1160         unsigned long flags;
1161
1162         spin_lock_irqsave(ap->lock, flags);
1163         qc->scsidone = ata_eh_scsidone;
1164         __ata_qc_complete(qc);
1165         WARN_ON(ata_tag_valid(qc->tag));
1166         spin_unlock_irqrestore(ap->lock, flags);
1167
1168         scsi_eh_finish_cmd(scmd, &ap->eh_done_q);
1169 }
1170
1171 /**
1172  *      ata_eh_qc_complete - Complete an active ATA command from EH
1173  *      @qc: Command to complete
1174  *
1175  *      Indicate to the mid and upper layers that an ATA command has
1176  *      completed.  To be used from EH.
1177  */
1178 void ata_eh_qc_complete(struct ata_queued_cmd *qc)
1179 {
1180         struct scsi_cmnd *scmd = qc->scsicmd;
1181         scmd->retries = scmd->allowed;
1182         __ata_eh_qc_complete(qc);
1183 }
1184
1185 /**
1186  *      ata_eh_qc_retry - Tell midlayer to retry an ATA command after EH
1187  *      @qc: Command to retry
1188  *
1189  *      Indicate to the mid and upper layers that an ATA command
1190  *      should be retried.  To be used from EH.
1191  *
1192  *      SCSI midlayer limits the number of retries to scmd->allowed.
1193  *      scmd->retries is decremented for commands which get retried
1194  *      due to unrelated failures (qc->err_mask is zero).
1195  */
1196 void ata_eh_qc_retry(struct ata_queued_cmd *qc)
1197 {
1198         struct scsi_cmnd *scmd = qc->scsicmd;
1199         if (!qc->err_mask && scmd->retries)
1200                 scmd->retries--;
1201         __ata_eh_qc_complete(qc);
1202 }
1203
1204 /**
1205  *      ata_dev_disable - disable ATA device
1206  *      @dev: ATA device to disable
1207  *
1208  *      Disable @dev.
1209  *
1210  *      Locking:
1211  *      EH context.
1212  */
1213 void ata_dev_disable(struct ata_device *dev)
1214 {
1215         if (!ata_dev_enabled(dev))
1216                 return;
1217
1218         if (ata_msg_drv(dev->link->ap))
1219                 ata_dev_printk(dev, KERN_WARNING, "disabled\n");
1220         ata_acpi_on_disable(dev);
1221         ata_down_xfermask_limit(dev, ATA_DNXFER_FORCE_PIO0 | ATA_DNXFER_QUIET);
1222         dev->class++;
1223
1224         /* From now till the next successful probe, ering is used to
1225          * track probe failures.  Clear accumulated device error info.
1226          */
1227         ata_ering_clear(&dev->ering);
1228 }
1229
1230 /**
1231  *      ata_eh_detach_dev - detach ATA device
1232  *      @dev: ATA device to detach
1233  *
1234  *      Detach @dev.
1235  *
1236  *      LOCKING:
1237  *      None.
1238  */
1239 void ata_eh_detach_dev(struct ata_device *dev)
1240 {
1241         struct ata_link *link = dev->link;
1242         struct ata_port *ap = link->ap;
1243         struct ata_eh_context *ehc = &link->eh_context;
1244         unsigned long flags;
1245
1246         ata_dev_disable(dev);
1247
1248         spin_lock_irqsave(ap->lock, flags);
1249
1250         dev->flags &= ~ATA_DFLAG_DETACH;
1251
1252         if (ata_scsi_offline_dev(dev)) {
1253                 dev->flags |= ATA_DFLAG_DETACHED;
1254                 ap->pflags |= ATA_PFLAG_SCSI_HOTPLUG;
1255         }
1256
1257         /* clear per-dev EH info */
1258         ata_eh_clear_action(link, dev, &link->eh_info, ATA_EH_PERDEV_MASK);
1259         ata_eh_clear_action(link, dev, &link->eh_context.i, ATA_EH_PERDEV_MASK);
1260         ehc->saved_xfer_mode[dev->devno] = 0;
1261         ehc->saved_ncq_enabled &= ~(1 << dev->devno);
1262
1263         spin_unlock_irqrestore(ap->lock, flags);
1264 }
1265
1266 /**
1267  *      ata_eh_about_to_do - about to perform eh_action
1268  *      @link: target ATA link
1269  *      @dev: target ATA dev for per-dev action (can be NULL)
1270  *      @action: action about to be performed
1271  *
1272  *      Called just before performing EH actions to clear related bits
1273  *      in @link->eh_info such that eh actions are not unnecessarily
1274  *      repeated.
1275  *
1276  *      LOCKING:
1277  *      None.
1278  */
1279 void ata_eh_about_to_do(struct ata_link *link, struct ata_device *dev,
1280                         unsigned int action)
1281 {
1282         struct ata_port *ap = link->ap;
1283         struct ata_eh_info *ehi = &link->eh_info;
1284         struct ata_eh_context *ehc = &link->eh_context;
1285         unsigned long flags;
1286
1287         spin_lock_irqsave(ap->lock, flags);
1288
1289         ata_eh_clear_action(link, dev, ehi, action);
1290
1291         /* About to take EH action, set RECOVERED.  Ignore actions on
1292          * slave links as master will do them again.
1293          */
1294         if (!(ehc->i.flags & ATA_EHI_QUIET) && link != ap->slave_link)
1295                 ap->pflags |= ATA_PFLAG_RECOVERED;
1296
1297         spin_unlock_irqrestore(ap->lock, flags);
1298 }
1299
1300 /**
1301  *      ata_eh_done - EH action complete
1302 *       @ap: target ATA port
1303  *      @dev: target ATA dev for per-dev action (can be NULL)
1304  *      @action: action just completed
1305  *
1306  *      Called right after performing EH actions to clear related bits
1307  *      in @link->eh_context.
1308  *
1309  *      LOCKING:
1310  *      None.
1311  */
1312 void ata_eh_done(struct ata_link *link, struct ata_device *dev,
1313                  unsigned int action)
1314 {
1315         struct ata_eh_context *ehc = &link->eh_context;
1316
1317         ata_eh_clear_action(link, dev, &ehc->i, action);
1318 }
1319
1320 /**
1321  *      ata_err_string - convert err_mask to descriptive string
1322  *      @err_mask: error mask to convert to string
1323  *
1324  *      Convert @err_mask to descriptive string.  Errors are
1325  *      prioritized according to severity and only the most severe
1326  *      error is reported.
1327  *
1328  *      LOCKING:
1329  *      None.
1330  *
1331  *      RETURNS:
1332  *      Descriptive string for @err_mask
1333  */
1334 static const char *ata_err_string(unsigned int err_mask)
1335 {
1336         if (err_mask & AC_ERR_HOST_BUS)
1337                 return "host bus error";
1338         if (err_mask & AC_ERR_ATA_BUS)
1339                 return "ATA bus error";
1340         if (err_mask & AC_ERR_TIMEOUT)
1341                 return "timeout";
1342         if (err_mask & AC_ERR_HSM)
1343                 return "HSM violation";
1344         if (err_mask & AC_ERR_SYSTEM)
1345                 return "internal error";
1346         if (err_mask & AC_ERR_MEDIA)
1347                 return "media error";
1348         if (err_mask & AC_ERR_INVALID)
1349                 return "invalid argument";
1350         if (err_mask & AC_ERR_DEV)
1351                 return "device error";
1352         return "unknown error";
1353 }
1354
1355 /**
1356  *      ata_read_log_page - read a specific log page
1357  *      @dev: target device
1358  *      @page: page to read
1359  *      @buf: buffer to store read page
1360  *      @sectors: number of sectors to read
1361  *
1362  *      Read log page using READ_LOG_EXT command.
1363  *
1364  *      LOCKING:
1365  *      Kernel thread context (may sleep).
1366  *
1367  *      RETURNS:
1368  *      0 on success, AC_ERR_* mask otherwise.
1369  */
1370 static unsigned int ata_read_log_page(struct ata_device *dev,
1371                                       u8 page, void *buf, unsigned int sectors)
1372 {
1373         struct ata_taskfile tf;
1374         unsigned int err_mask;
1375
1376         DPRINTK("read log page - page %d\n", page);
1377
1378         ata_tf_init(dev, &tf);
1379         tf.command = ATA_CMD_READ_LOG_EXT;
1380         tf.lbal = page;
1381         tf.nsect = sectors;
1382         tf.hob_nsect = sectors >> 8;
1383         tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_LBA48 | ATA_TFLAG_DEVICE;
1384         tf.protocol = ATA_PROT_PIO;
1385
1386         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_FROM_DEVICE,
1387                                      buf, sectors * ATA_SECT_SIZE, 0);
1388
1389         DPRINTK("EXIT, err_mask=%x\n", err_mask);
1390         return err_mask;
1391 }
1392
1393 /**
1394  *      ata_eh_read_log_10h - Read log page 10h for NCQ error details
1395  *      @dev: Device to read log page 10h from
1396  *      @tag: Resulting tag of the failed command
1397  *      @tf: Resulting taskfile registers of the failed command
1398  *
1399  *      Read log page 10h to obtain NCQ error details and clear error
1400  *      condition.
1401  *
1402  *      LOCKING:
1403  *      Kernel thread context (may sleep).
1404  *
1405  *      RETURNS:
1406  *      0 on success, -errno otherwise.
1407  */
1408 static int ata_eh_read_log_10h(struct ata_device *dev,
1409                                int *tag, struct ata_taskfile *tf)
1410 {
1411         u8 *buf = dev->link->ap->sector_buf;
1412         unsigned int err_mask;
1413         u8 csum;
1414         int i;
1415
1416         err_mask = ata_read_log_page(dev, ATA_LOG_SATA_NCQ, buf, 1);
1417         if (err_mask)
1418                 return -EIO;
1419
1420         csum = 0;
1421         for (i = 0; i < ATA_SECT_SIZE; i++)
1422                 csum += buf[i];
1423         if (csum)
1424                 ata_dev_printk(dev, KERN_WARNING,
1425                                "invalid checksum 0x%x on log page 10h\n", csum);
1426
1427         if (buf[0] & 0x80)
1428                 return -ENOENT;
1429
1430         *tag = buf[0] & 0x1f;
1431
1432         tf->command = buf[2];
1433         tf->feature = buf[3];
1434         tf->lbal = buf[4];
1435         tf->lbam = buf[5];
1436         tf->lbah = buf[6];
1437         tf->device = buf[7];
1438         tf->hob_lbal = buf[8];
1439         tf->hob_lbam = buf[9];
1440         tf->hob_lbah = buf[10];
1441         tf->nsect = buf[12];
1442         tf->hob_nsect = buf[13];
1443
1444         return 0;
1445 }
1446
1447 /**
1448  *      atapi_eh_tur - perform ATAPI TEST_UNIT_READY
1449  *      @dev: target ATAPI device
1450  *      @r_sense_key: out parameter for sense_key
1451  *
1452  *      Perform ATAPI TEST_UNIT_READY.
1453  *
1454  *      LOCKING:
1455  *      EH context (may sleep).
1456  *
1457  *      RETURNS:
1458  *      0 on success, AC_ERR_* mask on failure.
1459  */
1460 static unsigned int atapi_eh_tur(struct ata_device *dev, u8 *r_sense_key)
1461 {
1462         u8 cdb[ATAPI_CDB_LEN] = { TEST_UNIT_READY, 0, 0, 0, 0, 0 };
1463         struct ata_taskfile tf;
1464         unsigned int err_mask;
1465
1466         ata_tf_init(dev, &tf);
1467
1468         tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
1469         tf.command = ATA_CMD_PACKET;
1470         tf.protocol = ATAPI_PROT_NODATA;
1471
1472         err_mask = ata_exec_internal(dev, &tf, cdb, DMA_NONE, NULL, 0, 0);
1473         if (err_mask == AC_ERR_DEV)
1474                 *r_sense_key = tf.feature >> 4;
1475         return err_mask;
1476 }
1477
1478 /**
1479  *      atapi_eh_request_sense - perform ATAPI REQUEST_SENSE
1480  *      @dev: device to perform REQUEST_SENSE to
1481  *      @sense_buf: result sense data buffer (SCSI_SENSE_BUFFERSIZE bytes long)
1482  *      @dfl_sense_key: default sense key to use
1483  *
1484  *      Perform ATAPI REQUEST_SENSE after the device reported CHECK
1485  *      SENSE.  This function is EH helper.
1486  *
1487  *      LOCKING:
1488  *      Kernel thread context (may sleep).
1489  *
1490  *      RETURNS:
1491  *      0 on success, AC_ERR_* mask on failure
1492  */
1493 static unsigned int atapi_eh_request_sense(struct ata_device *dev,
1494                                            u8 *sense_buf, u8 dfl_sense_key)
1495 {
1496         u8 cdb[ATAPI_CDB_LEN] =
1497                 { REQUEST_SENSE, 0, 0, 0, SCSI_SENSE_BUFFERSIZE, 0 };
1498         struct ata_port *ap = dev->link->ap;
1499         struct ata_taskfile tf;
1500
1501         DPRINTK("ATAPI request sense\n");
1502
1503         /* FIXME: is this needed? */
1504         memset(sense_buf, 0, SCSI_SENSE_BUFFERSIZE);
1505
1506         /* initialize sense_buf with the error register,
1507          * for the case where they are -not- overwritten
1508          */
1509         sense_buf[0] = 0x70;
1510         sense_buf[2] = dfl_sense_key;
1511
1512         /* some devices time out if garbage left in tf */
1513         ata_tf_init(dev, &tf);
1514
1515         tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
1516         tf.command = ATA_CMD_PACKET;
1517
1518         /* is it pointless to prefer PIO for "safety reasons"? */
1519         if (ap->flags & ATA_FLAG_PIO_DMA) {
1520                 tf.protocol = ATAPI_PROT_DMA;
1521                 tf.feature |= ATAPI_PKT_DMA;
1522         } else {
1523                 tf.protocol = ATAPI_PROT_PIO;
1524                 tf.lbam = SCSI_SENSE_BUFFERSIZE;
1525                 tf.lbah = 0;
1526         }
1527
1528         return ata_exec_internal(dev, &tf, cdb, DMA_FROM_DEVICE,
1529                                  sense_buf, SCSI_SENSE_BUFFERSIZE, 0);
1530 }
1531
1532 /**
1533  *      ata_eh_analyze_serror - analyze SError for a failed port
1534  *      @link: ATA link to analyze SError for
1535  *
1536  *      Analyze SError if available and further determine cause of
1537  *      failure.
1538  *
1539  *      LOCKING:
1540  *      None.
1541  */
1542 static void ata_eh_analyze_serror(struct ata_link *link)
1543 {
1544         struct ata_eh_context *ehc = &link->eh_context;
1545         u32 serror = ehc->i.serror;
1546         unsigned int err_mask = 0, action = 0;
1547         u32 hotplug_mask;
1548
1549         if (serror & (SERR_PERSISTENT | SERR_DATA)) {
1550                 err_mask |= AC_ERR_ATA_BUS;
1551                 action |= ATA_EH_RESET;
1552         }
1553         if (serror & SERR_PROTOCOL) {
1554                 err_mask |= AC_ERR_HSM;
1555                 action |= ATA_EH_RESET;
1556         }
1557         if (serror & SERR_INTERNAL) {
1558                 err_mask |= AC_ERR_SYSTEM;
1559                 action |= ATA_EH_RESET;
1560         }
1561
1562         /* Determine whether a hotplug event has occurred.  Both
1563          * SError.N/X are considered hotplug events for enabled or
1564          * host links.  For disabled PMP links, only N bit is
1565          * considered as X bit is left at 1 for link plugging.
1566          */
1567         hotplug_mask = 0;
1568
1569         if (!(link->flags & ATA_LFLAG_DISABLED) || ata_is_host_link(link))
1570                 hotplug_mask = SERR_PHYRDY_CHG | SERR_DEV_XCHG;
1571         else
1572                 hotplug_mask = SERR_PHYRDY_CHG;
1573
1574         if (serror & hotplug_mask)
1575                 ata_ehi_hotplugged(&ehc->i);
1576
1577         ehc->i.err_mask |= err_mask;
1578         ehc->i.action |= action;
1579 }
1580
1581 /**
1582  *      ata_eh_analyze_ncq_error - analyze NCQ error
1583  *      @link: ATA link to analyze NCQ error for
1584  *
1585  *      Read log page 10h, determine the offending qc and acquire
1586  *      error status TF.  For NCQ device errors, all LLDDs have to do
1587  *      is setting AC_ERR_DEV in ehi->err_mask.  This function takes
1588  *      care of the rest.
1589  *
1590  *      LOCKING:
1591  *      Kernel thread context (may sleep).
1592  */
1593 void ata_eh_analyze_ncq_error(struct ata_link *link)
1594 {
1595         struct ata_port *ap = link->ap;
1596         struct ata_eh_context *ehc = &link->eh_context;
1597         struct ata_device *dev = link->device;
1598         struct ata_queued_cmd *qc;
1599         struct ata_taskfile tf;
1600         int tag, rc;
1601
1602         /* if frozen, we can't do much */
1603         if (ap->pflags & ATA_PFLAG_FROZEN)
1604                 return;
1605
1606         /* is it NCQ device error? */
1607         if (!link->sactive || !(ehc->i.err_mask & AC_ERR_DEV))
1608                 return;
1609
1610         /* has LLDD analyzed already? */
1611         for (tag = 0; tag < ATA_MAX_QUEUE; tag++) {
1612                 qc = __ata_qc_from_tag(ap, tag);
1613
1614                 if (!(qc->flags & ATA_QCFLAG_FAILED))
1615                         continue;
1616
1617                 if (qc->err_mask)
1618                         return;
1619         }
1620
1621         /* okay, this error is ours */
1622         memset(&tf, 0, sizeof(tf));
1623         rc = ata_eh_read_log_10h(dev, &tag, &tf);
1624         if (rc) {
1625                 ata_link_printk(link, KERN_ERR, "failed to read log page 10h "
1626                                 "(errno=%d)\n", rc);
1627                 return;
1628         }
1629
1630         if (!(link->sactive & (1 << tag))) {
1631                 ata_link_printk(link, KERN_ERR, "log page 10h reported "
1632                                 "inactive tag %d\n", tag);
1633                 return;
1634         }
1635
1636         /* we've got the perpetrator, condemn it */
1637         qc = __ata_qc_from_tag(ap, tag);
1638         memcpy(&qc->result_tf, &tf, sizeof(tf));
1639         qc->result_tf.flags = ATA_TFLAG_ISADDR | ATA_TFLAG_LBA | ATA_TFLAG_LBA48;
1640         qc->err_mask |= AC_ERR_DEV | AC_ERR_NCQ;
1641         ehc->i.err_mask &= ~AC_ERR_DEV;
1642 }
1643
1644 /**
1645  *      ata_eh_analyze_tf - analyze taskfile of a failed qc
1646  *      @qc: qc to analyze
1647  *      @tf: Taskfile registers to analyze
1648  *
1649  *      Analyze taskfile of @qc and further determine cause of
1650  *      failure.  This function also requests ATAPI sense data if
1651  *      avaliable.
1652  *
1653  *      LOCKING:
1654  *      Kernel thread context (may sleep).
1655  *
1656  *      RETURNS:
1657  *      Determined recovery action
1658  */
1659 static unsigned int ata_eh_analyze_tf(struct ata_queued_cmd *qc,
1660                                       const struct ata_taskfile *tf)
1661 {
1662         unsigned int tmp, action = 0;
1663         u8 stat = tf->command, err = tf->feature;
1664
1665         if ((stat & (ATA_BUSY | ATA_DRQ | ATA_DRDY)) != ATA_DRDY) {
1666                 qc->err_mask |= AC_ERR_HSM;
1667                 return ATA_EH_RESET;
1668         }
1669
1670         if (stat & (ATA_ERR | ATA_DF))
1671                 qc->err_mask |= AC_ERR_DEV;
1672         else
1673                 return 0;
1674
1675         switch (qc->dev->class) {
1676         case ATA_DEV_ATA:
1677                 if (err & ATA_ICRC)
1678                         qc->err_mask |= AC_ERR_ATA_BUS;
1679                 if (err & ATA_UNC)
1680                         qc->err_mask |= AC_ERR_MEDIA;
1681                 if (err & ATA_IDNF)
1682                         qc->err_mask |= AC_ERR_INVALID;
1683                 break;
1684
1685         case ATA_DEV_ATAPI:
1686                 if (!(qc->ap->pflags & ATA_PFLAG_FROZEN)) {
1687                         tmp = atapi_eh_request_sense(qc->dev,
1688                                                 qc->scsicmd->sense_buffer,
1689                                                 qc->result_tf.feature >> 4);
1690                         if (!tmp) {
1691                                 /* ATA_QCFLAG_SENSE_VALID is used to
1692                                  * tell atapi_qc_complete() that sense
1693                                  * data is already valid.
1694                                  *
1695                                  * TODO: interpret sense data and set
1696                                  * appropriate err_mask.
1697                                  */
1698                                 qc->flags |= ATA_QCFLAG_SENSE_VALID;
1699                         } else
1700                                 qc->err_mask |= tmp;
1701                 }
1702         }
1703
1704         if (qc->err_mask & (AC_ERR_HSM | AC_ERR_TIMEOUT | AC_ERR_ATA_BUS))
1705                 action |= ATA_EH_RESET;
1706
1707         return action;
1708 }
1709
1710 static int ata_eh_categorize_error(unsigned int eflags, unsigned int err_mask,
1711                                    int *xfer_ok)
1712 {
1713         int base = 0;
1714
1715         if (!(eflags & ATA_EFLAG_DUBIOUS_XFER))
1716                 *xfer_ok = 1;
1717
1718         if (!*xfer_ok)
1719                 base = ATA_ECAT_DUBIOUS_NONE;
1720
1721         if (err_mask & AC_ERR_ATA_BUS)
1722                 return base + ATA_ECAT_ATA_BUS;
1723
1724         if (err_mask & AC_ERR_TIMEOUT)
1725                 return base + ATA_ECAT_TOUT_HSM;
1726
1727         if (eflags & ATA_EFLAG_IS_IO) {
1728                 if (err_mask & AC_ERR_HSM)
1729                         return base + ATA_ECAT_TOUT_HSM;
1730                 if ((err_mask &
1731                      (AC_ERR_DEV|AC_ERR_MEDIA|AC_ERR_INVALID)) == AC_ERR_DEV)
1732                         return base + ATA_ECAT_UNK_DEV;
1733         }
1734
1735         return 0;
1736 }
1737
1738 struct speed_down_verdict_arg {
1739         u64 since;
1740         int xfer_ok;
1741         int nr_errors[ATA_ECAT_NR];
1742 };
1743
1744 static int speed_down_verdict_cb(struct ata_ering_entry *ent, void *void_arg)
1745 {
1746         struct speed_down_verdict_arg *arg = void_arg;
1747         int cat;
1748
1749         if (ent->timestamp < arg->since)
1750                 return -1;
1751
1752         cat = ata_eh_categorize_error(ent->eflags, ent->err_mask,
1753                                       &arg->xfer_ok);
1754         arg->nr_errors[cat]++;
1755
1756         return 0;
1757 }
1758
1759 /**
1760  *      ata_eh_speed_down_verdict - Determine speed down verdict
1761  *      @dev: Device of interest
1762  *
1763  *      This function examines error ring of @dev and determines
1764  *      whether NCQ needs to be turned off, transfer speed should be
1765  *      stepped down, or falling back to PIO is necessary.
1766  *
1767  *      ECAT_ATA_BUS    : ATA_BUS error for any command
1768  *
1769  *      ECAT_TOUT_HSM   : TIMEOUT for any command or HSM violation for
1770  *                        IO commands
1771  *
1772  *      ECAT_UNK_DEV    : Unknown DEV error for IO commands
1773  *
1774  *      ECAT_DUBIOUS_*  : Identical to above three but occurred while
1775  *                        data transfer hasn't been verified.
1776  *
1777  *      Verdicts are
1778  *
1779  *      NCQ_OFF         : Turn off NCQ.
1780  *
1781  *      SPEED_DOWN      : Speed down transfer speed but don't fall back
1782  *                        to PIO.
1783  *
1784  *      FALLBACK_TO_PIO : Fall back to PIO.
1785  *
1786  *      Even if multiple verdicts are returned, only one action is
1787  *      taken per error.  An action triggered by non-DUBIOUS errors
1788  *      clears ering, while one triggered by DUBIOUS_* errors doesn't.
1789  *      This is to expedite speed down decisions right after device is
1790  *      initially configured.
1791  *
1792  *      The followings are speed down rules.  #1 and #2 deal with
1793  *      DUBIOUS errors.
1794  *
1795  *      1. If more than one DUBIOUS_ATA_BUS or DUBIOUS_TOUT_HSM errors
1796  *         occurred during last 5 mins, SPEED_DOWN and FALLBACK_TO_PIO.
1797  *
1798  *      2. If more than one DUBIOUS_TOUT_HSM or DUBIOUS_UNK_DEV errors
1799  *         occurred during last 5 mins, NCQ_OFF.
1800  *
1801  *      3. If more than 8 ATA_BUS, TOUT_HSM or UNK_DEV errors
1802  *         ocurred during last 5 mins, FALLBACK_TO_PIO
1803  *
1804  *      4. If more than 3 TOUT_HSM or UNK_DEV errors occurred
1805  *         during last 10 mins, NCQ_OFF.
1806  *
1807  *      5. If more than 3 ATA_BUS or TOUT_HSM errors, or more than 6
1808  *         UNK_DEV errors occurred during last 10 mins, SPEED_DOWN.
1809  *
1810  *      LOCKING:
1811  *      Inherited from caller.
1812  *
1813  *      RETURNS:
1814  *      OR of ATA_EH_SPDN_* flags.
1815  */
1816 static unsigned int ata_eh_speed_down_verdict(struct ata_device *dev)
1817 {
1818         const u64 j5mins = 5LLU * 60 * HZ, j10mins = 10LLU * 60 * HZ;
1819         u64 j64 = get_jiffies_64();
1820         struct speed_down_verdict_arg arg;
1821         unsigned int verdict = 0;
1822
1823         /* scan past 5 mins of error history */
1824         memset(&arg, 0, sizeof(arg));
1825         arg.since = j64 - min(j64, j5mins);
1826         ata_ering_map(&dev->ering, speed_down_verdict_cb, &arg);
1827
1828         if (arg.nr_errors[ATA_ECAT_DUBIOUS_ATA_BUS] +
1829             arg.nr_errors[ATA_ECAT_DUBIOUS_TOUT_HSM] > 1)
1830                 verdict |= ATA_EH_SPDN_SPEED_DOWN |
1831                         ATA_EH_SPDN_FALLBACK_TO_PIO | ATA_EH_SPDN_KEEP_ERRORS;
1832
1833         if (arg.nr_errors[ATA_ECAT_DUBIOUS_TOUT_HSM] +
1834             arg.nr_errors[ATA_ECAT_DUBIOUS_UNK_DEV] > 1)
1835                 verdict |= ATA_EH_SPDN_NCQ_OFF | ATA_EH_SPDN_KEEP_ERRORS;
1836
1837         if (arg.nr_errors[ATA_ECAT_ATA_BUS] +
1838             arg.nr_errors[ATA_ECAT_TOUT_HSM] +
1839             arg.nr_errors[ATA_ECAT_UNK_DEV] > 6)
1840                 verdict |= ATA_EH_SPDN_FALLBACK_TO_PIO;
1841
1842         /* scan past 10 mins of error history */
1843         memset(&arg, 0, sizeof(arg));
1844         arg.since = j64 - min(j64, j10mins);
1845         ata_ering_map(&dev->ering, speed_down_verdict_cb, &arg);
1846
1847         if (arg.nr_errors[ATA_ECAT_TOUT_HSM] +
1848             arg.nr_errors[ATA_ECAT_UNK_DEV] > 3)
1849                 verdict |= ATA_EH_SPDN_NCQ_OFF;
1850
1851         if (arg.nr_errors[ATA_ECAT_ATA_BUS] +
1852             arg.nr_errors[ATA_ECAT_TOUT_HSM] > 3 ||
1853             arg.nr_errors[ATA_ECAT_UNK_DEV] > 6)
1854                 verdict |= ATA_EH_SPDN_SPEED_DOWN;
1855
1856         return verdict;
1857 }
1858
1859 /**
1860  *      ata_eh_speed_down - record error and speed down if necessary
1861  *      @dev: Failed device
1862  *      @eflags: mask of ATA_EFLAG_* flags
1863  *      @err_mask: err_mask of the error
1864  *
1865  *      Record error and examine error history to determine whether
1866  *      adjusting transmission speed is necessary.  It also sets
1867  *      transmission limits appropriately if such adjustment is
1868  *      necessary.
1869  *
1870  *      LOCKING:
1871  *      Kernel thread context (may sleep).
1872  *
1873  *      RETURNS:
1874  *      Determined recovery action.
1875  */
1876 static unsigned int ata_eh_speed_down(struct ata_device *dev,
1877                                 unsigned int eflags, unsigned int err_mask)
1878 {
1879         struct ata_link *link = ata_dev_phys_link(dev);
1880         int xfer_ok = 0;
1881         unsigned int verdict;
1882         unsigned int action = 0;
1883
1884         /* don't bother if Cat-0 error */
1885         if (ata_eh_categorize_error(eflags, err_mask, &xfer_ok) == 0)
1886                 return 0;
1887
1888         /* record error and determine whether speed down is necessary */
1889         ata_ering_record(&dev->ering, eflags, err_mask);
1890         verdict = ata_eh_speed_down_verdict(dev);
1891
1892         /* turn off NCQ? */
1893         if ((verdict & ATA_EH_SPDN_NCQ_OFF) &&
1894             (dev->flags & (ATA_DFLAG_PIO | ATA_DFLAG_NCQ |
1895                            ATA_DFLAG_NCQ_OFF)) == ATA_DFLAG_NCQ) {
1896                 dev->flags |= ATA_DFLAG_NCQ_OFF;
1897                 ata_dev_printk(dev, KERN_WARNING,
1898                                "NCQ disabled due to excessive errors\n");
1899                 goto done;
1900         }
1901
1902         /* speed down? */
1903         if (verdict & ATA_EH_SPDN_SPEED_DOWN) {
1904                 /* speed down SATA link speed if possible */
1905                 if (sata_down_spd_limit(link, 0) == 0) {
1906                         action |= ATA_EH_RESET;
1907                         goto done;
1908                 }
1909
1910                 /* lower transfer mode */
1911                 if (dev->spdn_cnt < 2) {
1912                         static const int dma_dnxfer_sel[] =
1913                                 { ATA_DNXFER_DMA, ATA_DNXFER_40C };
1914                         static const int pio_dnxfer_sel[] =
1915                                 { ATA_DNXFER_PIO, ATA_DNXFER_FORCE_PIO0 };
1916                         int sel;
1917
1918                         if (dev->xfer_shift != ATA_SHIFT_PIO)
1919                                 sel = dma_dnxfer_sel[dev->spdn_cnt];
1920                         else
1921                                 sel = pio_dnxfer_sel[dev->spdn_cnt];
1922
1923                         dev->spdn_cnt++;
1924
1925                         if (ata_down_xfermask_limit(dev, sel) == 0) {
1926                                 action |= ATA_EH_RESET;
1927                                 goto done;
1928                         }
1929                 }
1930         }
1931
1932         /* Fall back to PIO?  Slowing down to PIO is meaningless for
1933          * SATA ATA devices.  Consider it only for PATA and SATAPI.
1934          */
1935         if ((verdict & ATA_EH_SPDN_FALLBACK_TO_PIO) && (dev->spdn_cnt >= 2) &&
1936             (link->ap->cbl != ATA_CBL_SATA || dev->class == ATA_DEV_ATAPI) &&
1937             (dev->xfer_shift != ATA_SHIFT_PIO)) {
1938                 if (ata_down_xfermask_limit(dev, ATA_DNXFER_FORCE_PIO) == 0) {
1939                         dev->spdn_cnt = 0;
1940                         action |= ATA_EH_RESET;
1941                         goto done;
1942                 }
1943         }
1944
1945         return 0;
1946  done:
1947         /* device has been slowed down, blow error history */
1948         if (!(verdict & ATA_EH_SPDN_KEEP_ERRORS))
1949                 ata_ering_clear(&dev->ering);
1950         return action;
1951 }
1952
1953 /**
1954  *      ata_eh_link_autopsy - analyze error and determine recovery action
1955  *      @link: host link to perform autopsy on
1956  *
1957  *      Analyze why @link failed and determine which recovery actions
1958  *      are needed.  This function also sets more detailed AC_ERR_*
1959  *      values and fills sense data for ATAPI CHECK SENSE.
1960  *
1961  *      LOCKING:
1962  *      Kernel thread context (may sleep).
1963  */
1964 static void ata_eh_link_autopsy(struct ata_link *link)
1965 {
1966         struct ata_port *ap = link->ap;
1967         struct ata_eh_context *ehc = &link->eh_context;
1968         struct ata_device *dev;
1969         unsigned int all_err_mask = 0, eflags = 0;
1970         int tag;
1971         u32 serror;
1972         int rc;
1973
1974         DPRINTK("ENTER\n");
1975
1976         if (ehc->i.flags & ATA_EHI_NO_AUTOPSY)
1977                 return;
1978
1979         /* obtain and analyze SError */
1980         rc = sata_scr_read(link, SCR_ERROR, &serror);
1981         if (rc == 0) {
1982                 ehc->i.serror |= serror;
1983                 ata_eh_analyze_serror(link);
1984         } else if (rc != -EOPNOTSUPP) {
1985                 /* SError read failed, force reset and probing */
1986                 ehc->i.probe_mask |= ATA_ALL_DEVICES;
1987                 ehc->i.action |= ATA_EH_RESET;
1988                 ehc->i.err_mask |= AC_ERR_OTHER;
1989         }
1990
1991         /* analyze NCQ failure */
1992         ata_eh_analyze_ncq_error(link);
1993
1994         /* any real error trumps AC_ERR_OTHER */
1995         if (ehc->i.err_mask & ~AC_ERR_OTHER)
1996                 ehc->i.err_mask &= ~AC_ERR_OTHER;
1997
1998         all_err_mask |= ehc->i.err_mask;
1999
2000         for (tag = 0; tag < ATA_MAX_QUEUE; tag++) {
2001                 struct ata_queued_cmd *qc = __ata_qc_from_tag(ap, tag);
2002
2003                 if (!(qc->flags & ATA_QCFLAG_FAILED) ||
2004                     ata_dev_phys_link(qc->dev) != link)
2005                         continue;
2006
2007                 /* inherit upper level err_mask */
2008                 qc->err_mask |= ehc->i.err_mask;
2009
2010                 /* analyze TF */
2011                 ehc->i.action |= ata_eh_analyze_tf(qc, &qc->result_tf);
2012
2013                 /* DEV errors are probably spurious in case of ATA_BUS error */
2014                 if (qc->err_mask & AC_ERR_ATA_BUS)
2015                         qc->err_mask &= ~(AC_ERR_DEV | AC_ERR_MEDIA |
2016                                           AC_ERR_INVALID);
2017
2018                 /* any real error trumps unknown error */
2019                 if (qc->err_mask & ~AC_ERR_OTHER)
2020                         qc->err_mask &= ~AC_ERR_OTHER;
2021
2022                 /* SENSE_VALID trumps dev/unknown error and revalidation */
2023                 if (qc->flags & ATA_QCFLAG_SENSE_VALID)
2024                         qc->err_mask &= ~(AC_ERR_DEV | AC_ERR_OTHER);
2025
2026                 /* determine whether the command is worth retrying */
2027                 if (qc->flags & ATA_QCFLAG_IO ||
2028                     (!(qc->err_mask & AC_ERR_INVALID) &&
2029                      qc->err_mask != AC_ERR_DEV))
2030                         qc->flags |= ATA_QCFLAG_RETRY;
2031
2032                 /* accumulate error info */
2033                 ehc->i.dev = qc->dev;
2034                 all_err_mask |= qc->err_mask;
2035                 if (qc->flags & ATA_QCFLAG_IO)
2036                         eflags |= ATA_EFLAG_IS_IO;
2037         }
2038
2039         /* enforce default EH actions */
2040         if (ap->pflags & ATA_PFLAG_FROZEN ||
2041             all_err_mask & (AC_ERR_HSM | AC_ERR_TIMEOUT))
2042                 ehc->i.action |= ATA_EH_RESET;
2043         else if (((eflags & ATA_EFLAG_IS_IO) && all_err_mask) ||
2044                  (!(eflags & ATA_EFLAG_IS_IO) && (all_err_mask & ~AC_ERR_DEV)))
2045                 ehc->i.action |= ATA_EH_REVALIDATE;
2046
2047         /* If we have offending qcs and the associated failed device,
2048          * perform per-dev EH action only on the offending device.
2049          */
2050         if (ehc->i.dev) {
2051                 ehc->i.dev_action[ehc->i.dev->devno] |=
2052                         ehc->i.action & ATA_EH_PERDEV_MASK;
2053                 ehc->i.action &= ~ATA_EH_PERDEV_MASK;
2054         }
2055
2056         /* propagate timeout to host link */
2057         if ((all_err_mask & AC_ERR_TIMEOUT) && !ata_is_host_link(link))
2058                 ap->link.eh_context.i.err_mask |= AC_ERR_TIMEOUT;
2059
2060         /* record error and consider speeding down */
2061         dev = ehc->i.dev;
2062         if (!dev && ((ata_link_max_devices(link) == 1 &&
2063                       ata_dev_enabled(link->device))))
2064             dev = link->device;
2065
2066         if (dev) {
2067                 if (dev->flags & ATA_DFLAG_DUBIOUS_XFER)
2068                         eflags |= ATA_EFLAG_DUBIOUS_XFER;
2069                 ehc->i.action |= ata_eh_speed_down(dev, eflags, all_err_mask);
2070         }
2071
2072         DPRINTK("EXIT\n");
2073 }
2074
2075 /**
2076  *      ata_eh_autopsy - analyze error and determine recovery action
2077  *      @ap: host port to perform autopsy on
2078  *
2079  *      Analyze all links of @ap and determine why they failed and
2080  *      which recovery actions are needed.
2081  *
2082  *      LOCKING:
2083  *      Kernel thread context (may sleep).
2084  */
2085 void ata_eh_autopsy(struct ata_port *ap)
2086 {
2087         struct ata_link *link;
2088
2089         ata_for_each_link(link, ap, EDGE)
2090                 ata_eh_link_autopsy(link);
2091
2092         /* Handle the frigging slave link.  Autopsy is done similarly
2093          * but actions and flags are transferred over to the master
2094          * link and handled from there.
2095          */
2096         if (ap->slave_link) {
2097                 struct ata_eh_context *mehc = &ap->link.eh_context;
2098                 struct ata_eh_context *sehc = &ap->slave_link->eh_context;
2099
2100                 /* transfer control flags from master to slave */
2101                 sehc->i.flags |= mehc->i.flags & ATA_EHI_TO_SLAVE_MASK;
2102
2103                 /* perform autopsy on the slave link */
2104                 ata_eh_link_autopsy(ap->slave_link);
2105
2106                 /* transfer actions from slave to master and clear slave */
2107                 ata_eh_about_to_do(ap->slave_link, NULL, ATA_EH_ALL_ACTIONS);
2108                 mehc->i.action          |= sehc->i.action;
2109                 mehc->i.dev_action[1]   |= sehc->i.dev_action[1];
2110                 mehc->i.flags           |= sehc->i.flags;
2111                 ata_eh_done(ap->slave_link, NULL, ATA_EH_ALL_ACTIONS);
2112         }
2113
2114         /* Autopsy of fanout ports can affect host link autopsy.
2115          * Perform host link autopsy last.
2116          */
2117         if (sata_pmp_attached(ap))
2118                 ata_eh_link_autopsy(&ap->link);
2119 }
2120
2121 /**
2122  *      ata_get_cmd_descript - get description for ATA command
2123  *      @command: ATA command code to get description for
2124  *
2125  *      Return a textual description of the given command, or NULL if the
2126  *      command is not known.
2127  *
2128  *      LOCKING:
2129  *      None
2130  */
2131 const char *ata_get_cmd_descript(u8 command)
2132 {
2133 #ifdef CONFIG_ATA_VERBOSE_ERROR
2134         static const struct
2135         {
2136                 u8 command;
2137                 const char *text;
2138         } cmd_descr[] = {
2139                 { ATA_CMD_DEV_RESET,            "DEVICE RESET" },
2140                 { ATA_CMD_CHK_POWER,            "CHECK POWER MODE" },
2141                 { ATA_CMD_STANDBY,              "STANDBY" },
2142                 { ATA_CMD_IDLE,                 "IDLE" },
2143                 { ATA_CMD_EDD,                  "EXECUTE DEVICE DIAGNOSTIC" },
2144                 { ATA_CMD_DOWNLOAD_MICRO,       "DOWNLOAD MICROCODE" },
2145                 { ATA_CMD_NOP,                  "NOP" },
2146                 { ATA_CMD_FLUSH,                "FLUSH CACHE" },
2147                 { ATA_CMD_FLUSH_EXT,            "FLUSH CACHE EXT" },
2148                 { ATA_CMD_ID_ATA,               "IDENTIFY DEVICE" },
2149                 { ATA_CMD_ID_ATAPI,             "IDENTIFY PACKET DEVICE" },
2150                 { ATA_CMD_SERVICE,              "SERVICE" },
2151                 { ATA_CMD_READ,                 "READ DMA" },
2152                 { ATA_CMD_READ_EXT,             "READ DMA EXT" },
2153                 { ATA_CMD_READ_QUEUED,          "READ DMA QUEUED" },
2154                 { ATA_CMD_READ_STREAM_EXT,      "READ STREAM EXT" },
2155                 { ATA_CMD_READ_STREAM_DMA_EXT,  "READ STREAM DMA EXT" },
2156                 { ATA_CMD_WRITE,                "WRITE DMA" },
2157                 { ATA_CMD_WRITE_EXT,            "WRITE DMA EXT" },
2158                 { ATA_CMD_WRITE_QUEUED,         "WRITE DMA QUEUED EXT" },
2159                 { ATA_CMD_WRITE_STREAM_EXT,     "WRITE STREAM EXT" },
2160                 { ATA_CMD_WRITE_STREAM_DMA_EXT, "WRITE STREAM DMA EXT" },
2161                 { ATA_CMD_WRITE_FUA_EXT,        "WRITE DMA FUA EXT" },
2162                 { ATA_CMD_WRITE_QUEUED_FUA_EXT, "WRITE DMA QUEUED FUA EXT" },
2163                 { ATA_CMD_FPDMA_READ,           "READ FPDMA QUEUED" },
2164                 { ATA_CMD_FPDMA_WRITE,          "WRITE FPDMA QUEUED" },
2165                 { ATA_CMD_PIO_READ,             "READ SECTOR(S)" },
2166                 { ATA_CMD_PIO_READ_EXT,         "READ SECTOR(S) EXT" },
2167                 { ATA_CMD_PIO_WRITE,            "WRITE SECTOR(S)" },
2168                 { ATA_CMD_PIO_WRITE_EXT,        "WRITE SECTOR(S) EXT" },
2169                 { ATA_CMD_READ_MULTI,           "READ MULTIPLE" },
2170                 { ATA_CMD_READ_MULTI_EXT,       "READ MULTIPLE EXT" },
2171                 { ATA_CMD_WRITE_MULTI,          "WRITE MULTIPLE" },
2172                 { ATA_CMD_WRITE_MULTI_EXT,      "WRITE MULTIPLE EXT" },
2173                 { ATA_CMD_WRITE_MULTI_FUA_EXT,  "WRITE MULTIPLE FUA EXT" },
2174                 { ATA_CMD_SET_FEATURES,         "SET FEATURES" },
2175                 { ATA_CMD_SET_MULTI,            "SET MULTIPLE MODE" },
2176                 { ATA_CMD_VERIFY,               "READ VERIFY SECTOR(S)" },
2177                 { ATA_CMD_VERIFY_EXT,           "READ VERIFY SECTOR(S) EXT" },
2178                 { ATA_CMD_WRITE_UNCORR_EXT,     "WRITE UNCORRECTABLE EXT" },
2179                 { ATA_CMD_STANDBYNOW1,          "STANDBY IMMEDIATE" },
2180                 { ATA_CMD_IDLEIMMEDIATE,        "IDLE IMMEDIATE" },
2181                 { ATA_CMD_SLEEP,                "SLEEP" },
2182                 { ATA_CMD_INIT_DEV_PARAMS,      "INITIALIZE DEVICE PARAMETERS" },
2183                 { ATA_CMD_READ_NATIVE_MAX,      "READ NATIVE MAX ADDRESS" },
2184                 { ATA_CMD_READ_NATIVE_MAX_EXT,  "READ NATIVE MAX ADDRESS EXT" },
2185                 { ATA_CMD_SET_MAX,              "SET MAX ADDRESS" },
2186                 { ATA_CMD_SET_MAX_EXT,          "SET MAX ADDRESS EXT" },
2187                 { ATA_CMD_READ_LOG_EXT,         "READ LOG EXT" },
2188                 { ATA_CMD_WRITE_LOG_EXT,        "WRITE LOG EXT" },
2189                 { ATA_CMD_READ_LOG_DMA_EXT,     "READ LOG DMA EXT" },
2190                 { ATA_CMD_WRITE_LOG_DMA_EXT,    "WRITE LOG DMA EXT" },
2191                 { ATA_CMD_TRUSTED_RCV,          "TRUSTED RECEIVE" },
2192                 { ATA_CMD_TRUSTED_RCV_DMA,      "TRUSTED RECEIVE DMA" },
2193                 { ATA_CMD_TRUSTED_SND,          "TRUSTED SEND" },
2194                 { ATA_CMD_TRUSTED_SND_DMA,      "TRUSTED SEND DMA" },
2195                 { ATA_CMD_PMP_READ,             "READ BUFFER" },
2196                 { ATA_CMD_PMP_WRITE,            "WRITE BUFFER" },
2197                 { ATA_CMD_CONF_OVERLAY,         "DEVICE CONFIGURATION OVERLAY" },
2198                 { ATA_CMD_SEC_SET_PASS,         "SECURITY SET PASSWORD" },
2199                 { ATA_CMD_SEC_UNLOCK,           "SECURITY UNLOCK" },
2200                 { ATA_CMD_SEC_ERASE_PREP,       "SECURITY ERASE PREPARE" },
2201                 { ATA_CMD_SEC_ERASE_UNIT,       "SECURITY ERASE UNIT" },
2202                 { ATA_CMD_SEC_FREEZE_LOCK,      "SECURITY FREEZE LOCK" },
2203                 { ATA_CMD_SEC_DISABLE_PASS,     "SECURITY DISABLE PASSWORD" },
2204                 { ATA_CMD_CONFIG_STREAM,        "CONFIGURE STREAM" },
2205                 { ATA_CMD_SMART,                "SMART" },
2206                 { ATA_CMD_MEDIA_LOCK,           "DOOR LOCK" },
2207                 { ATA_CMD_MEDIA_UNLOCK,         "DOOR UNLOCK" },
2208                 { ATA_CMD_CHK_MED_CRD_TYP,      "CHECK MEDIA CARD TYPE" },
2209                 { ATA_CMD_CFA_REQ_EXT_ERR,      "CFA REQUEST EXTENDED ERROR" },
2210                 { ATA_CMD_CFA_WRITE_NE,         "CFA WRITE SECTORS WITHOUT ERASE" },
2211                 { ATA_CMD_CFA_TRANS_SECT,       "CFA TRANSLATE SECTOR" },
2212                 { ATA_CMD_CFA_ERASE,            "CFA ERASE SECTORS" },
2213                 { ATA_CMD_CFA_WRITE_MULT_NE,    "CFA WRITE MULTIPLE WITHOUT ERASE" },
2214                 { ATA_CMD_READ_LONG,            "READ LONG (with retries)" },
2215                 { ATA_CMD_READ_LONG_ONCE,       "READ LONG (without retries)" },
2216                 { ATA_CMD_WRITE_LONG,           "WRITE LONG (with retries)" },
2217                 { ATA_CMD_WRITE_LONG_ONCE,      "WRITE LONG (without retries)" },
2218                 { ATA_CMD_RESTORE,              "RECALIBRATE" },
2219                 { 0,                            NULL } /* terminate list */
2220         };
2221
2222         unsigned int i;
2223         for (i = 0; cmd_descr[i].text; i++)
2224                 if (cmd_descr[i].command == command)
2225                         return cmd_descr[i].text;
2226 #endif
2227
2228         return NULL;
2229 }
2230
2231 /**
2232  *      ata_eh_link_report - report error handling to user
2233  *      @link: ATA link EH is going on
2234  *
2235  *      Report EH to user.
2236  *
2237  *      LOCKING:
2238  *      None.
2239  */
2240 static void ata_eh_link_report(struct ata_link *link)
2241 {
2242         struct ata_port *ap = link->ap;
2243         struct ata_eh_context *ehc = &link->eh_context;
2244         const char *frozen, *desc;
2245         char tries_buf[6];
2246         int tag, nr_failed = 0;
2247
2248         if (ehc->i.flags & ATA_EHI_QUIET)
2249                 return;
2250
2251         desc = NULL;
2252         if (ehc->i.desc[0] != '\0')
2253                 desc = ehc->i.desc;
2254
2255         for (tag = 0; tag < ATA_MAX_QUEUE; tag++) {
2256                 struct ata_queued_cmd *qc = __ata_qc_from_tag(ap, tag);
2257
2258                 if (!(qc->flags & ATA_QCFLAG_FAILED) ||
2259                     ata_dev_phys_link(qc->dev) != link ||
2260                     ((qc->flags & ATA_QCFLAG_QUIET) &&
2261                      qc->err_mask == AC_ERR_DEV))
2262                         continue;
2263                 if (qc->flags & ATA_QCFLAG_SENSE_VALID && !qc->err_mask)
2264                         continue;
2265
2266                 nr_failed++;
2267         }
2268
2269         if (!nr_failed && !ehc->i.err_mask)
2270                 return;
2271
2272         frozen = "";
2273         if (ap->pflags & ATA_PFLAG_FROZEN)
2274                 frozen = " frozen";
2275
2276         memset(tries_buf, 0, sizeof(tries_buf));
2277         if (ap->eh_tries < ATA_EH_MAX_TRIES)
2278                 snprintf(tries_buf, sizeof(tries_buf) - 1, " t%d",
2279                          ap->eh_tries);
2280
2281         if (ehc->i.dev) {
2282                 ata_dev_printk(ehc->i.dev, KERN_ERR, "exception Emask 0x%x "
2283                                "SAct 0x%x SErr 0x%x action 0x%x%s%s\n",
2284                                ehc->i.err_mask, link->sactive, ehc->i.serror,
2285                                ehc->i.action, frozen, tries_buf);
2286                 if (desc)
2287                         ata_dev_printk(ehc->i.dev, KERN_ERR, "%s\n", desc);
2288         } else {
2289                 ata_link_printk(link, KERN_ERR, "exception Emask 0x%x "
2290                                 "SAct 0x%x SErr 0x%x action 0x%x%s%s\n",
2291                                 ehc->i.err_mask, link->sactive, ehc->i.serror,
2292                                 ehc->i.action, frozen, tries_buf);
2293                 if (desc)
2294                         ata_link_printk(link, KERN_ERR, "%s\n", desc);
2295         }
2296
2297 #ifdef CONFIG_ATA_VERBOSE_ERROR
2298         if (ehc->i.serror)
2299                 ata_link_printk(link, KERN_ERR,
2300                   "SError: { %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s}\n",
2301                   ehc->i.serror & SERR_DATA_RECOVERED ? "RecovData " : "",
2302                   ehc->i.serror & SERR_COMM_RECOVERED ? "RecovComm " : "",
2303                   ehc->i.serror & SERR_DATA ? "UnrecovData " : "",
2304                   ehc->i.serror & SERR_PERSISTENT ? "Persist " : "",
2305                   ehc->i.serror & SERR_PROTOCOL ? "Proto " : "",
2306                   ehc->i.serror & SERR_INTERNAL ? "HostInt " : "",
2307                   ehc->i.serror & SERR_PHYRDY_CHG ? "PHYRdyChg " : "",
2308                   ehc->i.serror & SERR_PHY_INT_ERR ? "PHYInt " : "",
2309                   ehc->i.serror & SERR_COMM_WAKE ? "CommWake " : "",
2310                   ehc->i.serror & SERR_10B_8B_ERR ? "10B8B " : "",
2311                   ehc->i.serror & SERR_DISPARITY ? "Dispar " : "",
2312                   ehc->i.serror & SERR_CRC ? "BadCRC " : "",
2313                   ehc->i.serror & SERR_HANDSHAKE ? "Handshk " : "",
2314                   ehc->i.serror & SERR_LINK_SEQ_ERR ? "LinkSeq " : "",
2315                   ehc->i.serror & SERR_TRANS_ST_ERROR ? "TrStaTrns " : "",
2316                   ehc->i.serror & SERR_UNRECOG_FIS ? "UnrecFIS " : "",
2317                   ehc->i.serror & SERR_DEV_XCHG ? "DevExch " : "");
2318 #endif
2319
2320         for (tag = 0; tag < ATA_MAX_QUEUE; tag++) {
2321                 struct ata_queued_cmd *qc = __ata_qc_from_tag(ap, tag);
2322                 struct ata_taskfile *cmd = &qc->tf, *res = &qc->result_tf;
2323                 const u8 *cdb = qc->cdb;
2324                 char data_buf[20] = "";
2325                 char cdb_buf[70] = "";
2326
2327                 if (!(qc->flags & ATA_QCFLAG_FAILED) ||
2328                     ata_dev_phys_link(qc->dev) != link || !qc->err_mask)
2329                         continue;
2330
2331                 if (qc->dma_dir != DMA_NONE) {
2332                         static const char *dma_str[] = {
2333                                 [DMA_BIDIRECTIONAL]     = "bidi",
2334                                 [DMA_TO_DEVICE]         = "out",
2335                                 [DMA_FROM_DEVICE]       = "in",
2336                         };
2337                         static const char *prot_str[] = {
2338                                 [ATA_PROT_PIO]          = "pio",
2339                                 [ATA_PROT_DMA]          = "dma",
2340                                 [ATA_PROT_NCQ]          = "ncq",
2341                                 [ATAPI_PROT_PIO]        = "pio",
2342                                 [ATAPI_PROT_DMA]        = "dma",
2343                         };
2344
2345                         snprintf(data_buf, sizeof(data_buf), " %s %u %s",
2346                                  prot_str[qc->tf.protocol], qc->nbytes,
2347                                  dma_str[qc->dma_dir]);
2348                 }
2349
2350                 if (ata_is_atapi(qc->tf.protocol)) {
2351                         if (qc->scsicmd)
2352                                 scsi_print_command(qc->scsicmd);
2353                         else
2354                                 snprintf(cdb_buf, sizeof(cdb_buf),
2355                                  "cdb %02x %02x %02x %02x %02x %02x %02x %02x  "
2356                                  "%02x %02x %02x %02x %02x %02x %02x %02x\n         ",
2357                                  cdb[0], cdb[1], cdb[2], cdb[3],
2358                                  cdb[4], cdb[5], cdb[6], cdb[7],
2359                                  cdb[8], cdb[9], cdb[10], cdb[11],
2360                                  cdb[12], cdb[13], cdb[14], cdb[15]);
2361                 } else {
2362                         const char *descr = ata_get_cmd_descript(cmd->command);
2363                         if (descr)
2364                                 ata_dev_printk(qc->dev, KERN_ERR,
2365                                         "failed command: %s\n", descr);
2366                 }
2367
2368                 ata_dev_printk(qc->dev, KERN_ERR,
2369                         "cmd %02x/%02x:%02x:%02x:%02x:%02x/%02x:%02x:%02x:%02x:%02x/%02x "
2370                         "tag %d%s\n         %s"
2371                         "res %02x/%02x:%02x:%02x:%02x:%02x/%02x:%02x:%02x:%02x:%02x/%02x "
2372                         "Emask 0x%x (%s)%s\n",
2373                         cmd->command, cmd->feature, cmd->nsect,
2374                         cmd->lbal, cmd->lbam, cmd->lbah,
2375                         cmd->hob_feature, cmd->hob_nsect,
2376                         cmd->hob_lbal, cmd->hob_lbam, cmd->hob_lbah,
2377                         cmd->device, qc->tag, data_buf, cdb_buf,
2378                         res->command, res->feature, res->nsect,
2379                         res->lbal, res->lbam, res->lbah,
2380                         res->hob_feature, res->hob_nsect,
2381                         res->hob_lbal, res->hob_lbam, res->hob_lbah,
2382                         res->device, qc->err_mask, ata_err_string(qc->err_mask),
2383                         qc->err_mask & AC_ERR_NCQ ? " <F>" : "");
2384
2385 #ifdef CONFIG_ATA_VERBOSE_ERROR
2386                 if (res->command & (ATA_BUSY | ATA_DRDY | ATA_DF | ATA_DRQ |
2387                                     ATA_ERR)) {
2388                         if (res->command & ATA_BUSY)
2389                                 ata_dev_printk(qc->dev, KERN_ERR,
2390                                   "status: { Busy }\n");
2391                         else
2392                                 ata_dev_printk(qc->dev, KERN_ERR,
2393                                   "status: { %s%s%s%s}\n",
2394                                   res->command & ATA_DRDY ? "DRDY " : "",
2395                                   res->command & ATA_DF ? "DF " : "",
2396                                   res->command & ATA_DRQ ? "DRQ " : "",
2397                                   res->command & ATA_ERR ? "ERR " : "");
2398                 }
2399
2400                 if (cmd->command != ATA_CMD_PACKET &&
2401                     (res->feature & (ATA_ICRC | ATA_UNC | ATA_IDNF |
2402                                      ATA_ABORTED)))
2403                         ata_dev_printk(qc->dev, KERN_ERR,
2404                           "error: { %s%s%s%s}\n",
2405                           res->feature & ATA_ICRC ? "ICRC " : "",
2406                           res->feature & ATA_UNC ? "UNC " : "",
2407                           res->feature & ATA_IDNF ? "IDNF " : "",
2408                           res->feature & ATA_ABORTED ? "ABRT " : "");
2409 #endif
2410         }
2411 }
2412
2413 /**
2414  *      ata_eh_report - report error handling to user
2415  *      @ap: ATA port to report EH about
2416  *
2417  *      Report EH to user.
2418  *
2419  *      LOCKING:
2420  *      None.
2421  */
2422 void ata_eh_report(struct ata_port *ap)
2423 {
2424         struct ata_link *link;
2425
2426         ata_for_each_link(link, ap, HOST_FIRST)
2427                 ata_eh_link_report(link);
2428 }
2429
2430 static int ata_do_reset(struct ata_link *link, ata_reset_fn_t reset,
2431                         unsigned int *classes, unsigned long deadline,
2432                         bool clear_classes)
2433 {
2434         struct ata_device *dev;
2435
2436         if (clear_classes)
2437                 ata_for_each_dev(dev, link, ALL)
2438                         classes[dev->devno] = ATA_DEV_UNKNOWN;
2439
2440         return reset(link, classes, deadline);
2441 }
2442
2443 static int ata_eh_followup_srst_needed(struct ata_link *link,
2444                                        int rc, const unsigned int *classes)
2445 {
2446         if ((link->flags & ATA_LFLAG_NO_SRST) || ata_link_offline(link))
2447                 return 0;
2448         if (rc == -EAGAIN)
2449                 return 1;
2450         if (sata_pmp_supported(link->ap) && ata_is_host_link(link))
2451                 return 1;
2452         return 0;
2453 }
2454
2455 int ata_eh_reset(struct ata_link *link, int classify,
2456                  ata_prereset_fn_t prereset, ata_reset_fn_t softreset,
2457                  ata_reset_fn_t hardreset, ata_postreset_fn_t postreset)
2458 {
2459         struct ata_port *ap = link->ap;
2460         struct ata_link *slave = ap->slave_link;
2461         struct ata_eh_context *ehc = &link->eh_context;
2462         struct ata_eh_context *sehc = slave ? &slave->eh_context : NULL;
2463         unsigned int *classes = ehc->classes;
2464         unsigned int lflags = link->flags;
2465         int verbose = !(ehc->i.flags & ATA_EHI_QUIET);
2466         int max_tries = 0, try = 0;
2467         struct ata_link *failed_link;
2468         struct ata_device *dev;
2469         unsigned long deadline, now;
2470         ata_reset_fn_t reset;
2471         unsigned long flags;
2472         u32 sstatus;
2473         int nr_unknown, rc;
2474
2475         /*
2476          * Prepare to reset
2477          */
2478         while (ata_eh_reset_timeouts[max_tries] != ULONG_MAX)
2479                 max_tries++;
2480         if (link->flags & ATA_LFLAG_NO_HRST)
2481                 hardreset = NULL;
2482         if (link->flags & ATA_LFLAG_NO_SRST)
2483                 softreset = NULL;
2484
2485         /* make sure each reset attemp is at least COOL_DOWN apart */
2486         if (ehc->i.flags & ATA_EHI_DID_RESET) {
2487                 now = jiffies;
2488                 WARN_ON(time_after(ehc->last_reset, now));
2489                 deadline = ata_deadline(ehc->last_reset,
2490                                         ATA_EH_RESET_COOL_DOWN);
2491                 if (time_before(now, deadline))
2492                         schedule_timeout_uninterruptible(deadline - now);
2493         }
2494
2495         spin_lock_irqsave(ap->lock, flags);
2496         ap->pflags |= ATA_PFLAG_RESETTING;
2497         spin_unlock_irqrestore(ap->lock, flags);
2498
2499         ata_eh_about_to_do(link, NULL, ATA_EH_RESET);
2500
2501         ata_for_each_dev(dev, link, ALL) {
2502                 /* If we issue an SRST then an ATA drive (not ATAPI)
2503                  * may change configuration and be in PIO0 timing. If
2504                  * we do a hard reset (or are coming from power on)
2505                  * this is true for ATA or ATAPI. Until we've set a
2506                  * suitable controller mode we should not touch the
2507                  * bus as we may be talking too fast.
2508                  */
2509                 dev->pio_mode = XFER_PIO_0;
2510
2511                 /* If the controller has a pio mode setup function
2512                  * then use it to set the chipset to rights. Don't
2513                  * touch the DMA setup as that will be dealt with when
2514                  * configuring devices.
2515                  */
2516                 if (ap->ops->set_piomode)
2517                         ap->ops->set_piomode(ap, dev);
2518         }
2519
2520         /* prefer hardreset */
2521         reset = NULL;
2522         ehc->i.action &= ~ATA_EH_RESET;
2523         if (hardreset) {
2524                 reset = hardreset;
2525                 ehc->i.action |= ATA_EH_HARDRESET;
2526         } else if (softreset) {
2527                 reset = softreset;
2528                 ehc->i.action |= ATA_EH_SOFTRESET;
2529         }
2530
2531         if (prereset) {
2532                 unsigned long deadline = ata_deadline(jiffies,
2533                                                       ATA_EH_PRERESET_TIMEOUT);
2534
2535                 if (slave) {
2536                         sehc->i.action &= ~ATA_EH_RESET;
2537                         sehc->i.action |= ehc->i.action;
2538                 }
2539
2540                 rc = prereset(link, deadline);
2541
2542                 /* If present, do prereset on slave link too.  Reset
2543                  * is skipped iff both master and slave links report
2544                  * -ENOENT or clear ATA_EH_RESET.
2545                  */
2546                 if (slave && (rc == 0 || rc == -ENOENT)) {
2547                         int tmp;
2548
2549                         tmp = prereset(slave, deadline);
2550                         if (tmp != -ENOENT)
2551                                 rc = tmp;
2552
2553                         ehc->i.action |= sehc->i.action;
2554                 }
2555
2556                 if (rc) {
2557                         if (rc == -ENOENT) {
2558                                 ata_link_printk(link, KERN_DEBUG,
2559                                                 "port disabled. ignoring.\n");
2560                                 ehc->i.action &= ~ATA_EH_RESET;
2561
2562                                 ata_for_each_dev(dev, link, ALL)
2563                                         classes[dev->devno] = ATA_DEV_NONE;
2564
2565                                 rc = 0;
2566                         } else
2567                                 ata_link_printk(link, KERN_ERR,
2568                                         "prereset failed (errno=%d)\n", rc);
2569                         goto out;
2570                 }
2571
2572                 /* prereset() might have cleared ATA_EH_RESET.  If so,
2573                  * bang classes, thaw and return.
2574                  */
2575                 if (reset && !(ehc->i.action & ATA_EH_RESET)) {
2576                         ata_for_each_dev(dev, link, ALL)
2577                                 classes[dev->devno] = ATA_DEV_NONE;
2578                         if ((ap->pflags & ATA_PFLAG_FROZEN) &&
2579                             ata_is_host_link(link))
2580                                 ata_eh_thaw_port(ap);
2581                         rc = 0;
2582                         goto out;
2583                 }
2584         }
2585
2586  retry:
2587         /*
2588          * Perform reset
2589          */
2590         if (ata_is_host_link(link))
2591                 ata_eh_freeze_port(ap);
2592
2593         deadline = ata_deadline(jiffies, ata_eh_reset_timeouts[try++]);
2594
2595         if (reset) {
2596                 if (verbose)
2597                         ata_link_printk(link, KERN_INFO, "%s resetting link\n",
2598                                         reset == softreset ? "soft" : "hard");
2599
2600                 /* mark that this EH session started with reset */
2601                 ehc->last_reset = jiffies;
2602                 if (reset == hardreset)
2603                         ehc->i.flags |= ATA_EHI_DID_HARDRESET;
2604                 else
2605                         ehc->i.flags |= ATA_EHI_DID_SOFTRESET;
2606
2607                 rc = ata_do_reset(link, reset, classes, deadline, true);
2608                 if (rc && rc != -EAGAIN) {
2609                         failed_link = link;
2610                         goto fail;
2611                 }
2612
2613                 /* hardreset slave link if existent */
2614                 if (slave && reset == hardreset) {
2615                         int tmp;
2616
2617                         if (verbose)
2618                                 ata_link_printk(slave, KERN_INFO,
2619                                                 "hard resetting link\n");
2620
2621                         ata_eh_about_to_do(slave, NULL, ATA_EH_RESET);
2622                         tmp = ata_do_reset(slave, reset, classes, deadline,
2623                                            false);
2624                         switch (tmp) {
2625                         case -EAGAIN:
2626                                 rc = -EAGAIN;
2627                         case 0:
2628                                 break;
2629                         default:
2630                                 failed_link = slave;
2631                                 rc = tmp;
2632                                 goto fail;
2633                         }
2634                 }
2635
2636                 /* perform follow-up SRST if necessary */
2637                 if (reset == hardreset &&
2638                     ata_eh_followup_srst_needed(link, rc, classes)) {
2639                         reset = softreset;
2640
2641                         if (!reset) {
2642                                 ata_link_printk(link, KERN_ERR,
2643                                                 "follow-up softreset required "
2644                                                 "but no softreset avaliable\n");
2645                                 failed_link = link;
2646                                 rc = -EINVAL;
2647                                 goto fail;
2648                         }
2649
2650                         ata_eh_about_to_do(link, NULL, ATA_EH_RESET);
2651                         rc = ata_do_reset(link, reset, classes, deadline, true);
2652                         if (rc) {
2653                                 failed_link = link;
2654                                 goto fail;
2655                         }
2656                 }
2657         } else {
2658                 if (verbose)
2659                         ata_link_printk(link, KERN_INFO, "no reset method "
2660                                         "available, skipping reset\n");
2661                 if (!(lflags & ATA_LFLAG_ASSUME_CLASS))
2662                         lflags |= ATA_LFLAG_ASSUME_ATA;
2663         }
2664
2665         /*
2666          * Post-reset processing
2667          */
2668         ata_for_each_dev(dev, link, ALL) {
2669                 /* After the reset, the device state is PIO 0 and the
2670                  * controller state is undefined.  Reset also wakes up
2671                  * drives from sleeping mode.
2672                  */
2673                 dev->pio_mode = XFER_PIO_0;
2674                 dev->flags &= ~ATA_DFLAG_SLEEPING;
2675
2676                 if (ata_phys_link_offline(ata_dev_phys_link(dev)))
2677                         continue;
2678
2679                 /* apply class override */
2680                 if (lflags & ATA_LFLAG_ASSUME_ATA)
2681                         classes[dev->devno] = ATA_DEV_ATA;
2682                 else if (lflags & ATA_LFLAG_ASSUME_SEMB)
2683                         classes[dev->devno] = ATA_DEV_SEMB_UNSUP;
2684         }
2685
2686         /* record current link speed */
2687         if (sata_scr_read(link, SCR_STATUS, &sstatus) == 0)
2688                 link->sata_spd = (sstatus >> 4) & 0xf;
2689         if (slave && sata_scr_read(slave, SCR_STATUS, &sstatus) == 0)
2690                 slave->sata_spd = (sstatus >> 4) & 0xf;
2691
2692         /* thaw the port */
2693         if (ata_is_host_link(link))
2694                 ata_eh_thaw_port(ap);
2695
2696         /* postreset() should clear hardware SError.  Although SError
2697          * is cleared during link resume, clearing SError here is
2698          * necessary as some PHYs raise hotplug events after SRST.
2699          * This introduces race condition where hotplug occurs between
2700          * reset and here.  This race is mediated by cross checking
2701          * link onlineness and classification result later.
2702          */
2703         if (postreset) {
2704                 postreset(link, classes);
2705                 if (slave)
2706                         postreset(slave, classes);
2707         }
2708
2709         /*
2710          * Some controllers can't be frozen very well and may set spurious
2711          * error conditions during reset.  Clear accumulated error
2712          * information and re-thaw the port if frozen.  As reset is the
2713          * final recovery action and we cross check link onlineness against
2714          * device classification later, no hotplug event is lost by this.
2715          */
2716         spin_lock_irqsave(link->ap->lock, flags);
2717         memset(&link->eh_info, 0, sizeof(link->eh_info));
2718         if (slave)
2719                 memset(&slave->eh_info, 0, sizeof(link->eh_info));
2720         ap->pflags &= ~ATA_PFLAG_EH_PENDING;
2721         spin_unlock_irqrestore(link->ap->lock, flags);
2722
2723         if (ap->pflags & ATA_PFLAG_FROZEN)
2724                 ata_eh_thaw_port(ap);
2725
2726         /*
2727          * Make sure onlineness and classification result correspond.
2728          * Hotplug could have happened during reset and some
2729          * controllers fail to wait while a drive is spinning up after
2730          * being hotplugged causing misdetection.  By cross checking
2731          * link on/offlineness and classification result, those
2732          * conditions can be reliably detected and retried.
2733          */
2734         nr_unknown = 0;
2735         ata_for_each_dev(dev, link, ALL) {
2736                 if (ata_phys_link_online(ata_dev_phys_link(dev))) {
2737                         if (classes[dev->devno] == ATA_DEV_UNKNOWN) {
2738                                 ata_dev_printk(dev, KERN_DEBUG, "link online "
2739                                                "but device misclassifed\n");
2740                                 classes[dev->devno] = ATA_DEV_NONE;
2741                                 nr_unknown++;
2742                         }
2743                 } else if (ata_phys_link_offline(ata_dev_phys_link(dev))) {
2744                         if (ata_class_enabled(classes[dev->devno]))
2745                                 ata_dev_printk(dev, KERN_DEBUG, "link offline, "
2746                                                "clearing class %d to NONE\n",
2747                                                classes[dev->devno]);
2748                         classes[dev->devno] = ATA_DEV_NONE;
2749                 } else if (classes[dev->devno] == ATA_DEV_UNKNOWN) {
2750                         ata_dev_printk(dev, KERN_DEBUG, "link status unknown, "
2751                                        "clearing UNKNOWN to NONE\n");
2752                         classes[dev->devno] = ATA_DEV_NONE;
2753                 }
2754         }
2755
2756         if (classify && nr_unknown) {
2757                 if (try < max_tries) {
2758                         ata_link_printk(link, KERN_WARNING, "link online but "
2759                                         "%d devices misclassified, retrying\n",
2760                                         nr_unknown);
2761                         failed_link = link;
2762                         rc = -EAGAIN;
2763                         goto fail;
2764                 }
2765                 ata_link_printk(link, KERN_WARNING,
2766                                 "link online but %d devices misclassified, "
2767                                 "device detection might fail\n", nr_unknown);
2768         }
2769
2770         /* reset successful, schedule revalidation */
2771         ata_eh_done(link, NULL, ATA_EH_RESET);
2772         if (slave)
2773                 ata_eh_done(slave, NULL, ATA_EH_RESET);
2774         ehc->last_reset = jiffies;      /* update to completion time */
2775         ehc->i.action |= ATA_EH_REVALIDATE;
2776
2777         rc = 0;
2778  out:
2779         /* clear hotplug flag */
2780         ehc->i.flags &= ~ATA_EHI_HOTPLUGGED;
2781         if (slave)
2782                 sehc->i.flags &= ~ATA_EHI_HOTPLUGGED;
2783
2784         spin_lock_irqsave(ap->lock, flags);
2785         ap->pflags &= ~ATA_PFLAG_RESETTING;
2786         spin_unlock_irqrestore(ap->lock, flags);
2787
2788         return rc;
2789
2790  fail:
2791         /* if SCR isn't accessible on a fan-out port, PMP needs to be reset */
2792         if (!ata_is_host_link(link) &&
2793             sata_scr_read(link, SCR_STATUS, &sstatus))
2794                 rc = -ERESTART;
2795
2796         if (rc == -ERESTART || try >= max_tries)
2797                 goto out;
2798
2799         now = jiffies;
2800         if (time_before(now, deadline)) {
2801                 unsigned long delta = deadline - now;
2802
2803                 ata_link_printk(failed_link, KERN_WARNING,
2804                         "reset failed (errno=%d), retrying in %u secs\n",
2805                         rc, DIV_ROUND_UP(jiffies_to_msecs(delta), 1000));
2806
2807                 while (delta)
2808                         delta = schedule_timeout_uninterruptible(delta);
2809         }
2810
2811         if (try == max_tries - 1) {
2812                 sata_down_spd_limit(link, 0);
2813                 if (slave)
2814                         sata_down_spd_limit(slave, 0);
2815         } else if (rc == -EPIPE)
2816                 sata_down_spd_limit(failed_link, 0);
2817
2818         if (hardreset)
2819                 reset = hardreset;
2820         goto retry;
2821 }
2822
2823 static inline void ata_eh_pull_park_action(struct ata_port *ap)
2824 {
2825         struct ata_link *link;
2826         struct ata_device *dev;
2827         unsigned long flags;
2828
2829         /*
2830          * This function can be thought of as an extended version of
2831          * ata_eh_about_to_do() specially crafted to accommodate the
2832          * requirements of ATA_EH_PARK handling. Since the EH thread
2833          * does not leave the do {} while () loop in ata_eh_recover as
2834          * long as the timeout for a park request to *one* device on
2835          * the port has not expired, and since we still want to pick
2836          * up park requests to other devices on the same port or
2837          * timeout updates for the same device, we have to pull
2838          * ATA_EH_PARK actions from eh_info into eh_context.i
2839          * ourselves at the beginning of each pass over the loop.
2840          *
2841          * Additionally, all write accesses to &ap->park_req_pending
2842          * through INIT_COMPLETION() (see below) or complete_all()
2843          * (see ata_scsi_park_store()) are protected by the host lock.
2844          * As a result we have that park_req_pending.done is zero on
2845          * exit from this function, i.e. when ATA_EH_PARK actions for
2846          * *all* devices on port ap have been pulled into the
2847          * respective eh_context structs. If, and only if,
2848          * park_req_pending.done is non-zero by the time we reach
2849          * wait_for_completion_timeout(), another ATA_EH_PARK action
2850          * has been scheduled for at least one of the devices on port
2851          * ap and we have to cycle over the do {} while () loop in
2852          * ata_eh_recover() again.
2853          */
2854
2855         spin_lock_irqsave(ap->lock, flags);
2856         INIT_COMPLETION(ap->park_req_pending);
2857         ata_for_each_link(link, ap, EDGE) {
2858                 ata_for_each_dev(dev, link, ALL) {
2859                         struct ata_eh_info *ehi = &link->eh_info;
2860
2861                         link->eh_context.i.dev_action[dev->devno] |=
2862                                 ehi->dev_action[dev->devno] & ATA_EH_PARK;
2863                         ata_eh_clear_action(link, dev, ehi, ATA_EH_PARK);
2864                 }
2865         }
2866         spin_unlock_irqrestore(ap->lock, flags);
2867 }
2868
2869 static void ata_eh_park_issue_cmd(struct ata_device *dev, int park)
2870 {
2871         struct ata_eh_context *ehc = &dev->link->eh_context;
2872         struct ata_taskfile tf;
2873         unsigned int err_mask;
2874
2875         ata_tf_init(dev, &tf);
2876         if (park) {
2877                 ehc->unloaded_mask |= 1 << dev->devno;
2878                 tf.command = ATA_CMD_IDLEIMMEDIATE;
2879                 tf.feature = 0x44;
2880                 tf.lbal = 0x4c;
2881                 tf.lbam = 0x4e;
2882                 tf.lbah = 0x55;
2883         } else {
2884                 ehc->unloaded_mask &= ~(1 << dev->devno);
2885                 tf.command = ATA_CMD_CHK_POWER;
2886         }
2887
2888         tf.flags |= ATA_TFLAG_DEVICE | ATA_TFLAG_ISADDR;
2889         tf.protocol |= ATA_PROT_NODATA;
2890         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
2891         if (park && (err_mask || tf.lbal != 0xc4)) {
2892                 ata_dev_printk(dev, KERN_ERR, "head unload failed!\n");
2893                 ehc->unloaded_mask &= ~(1 << dev->devno);
2894         }
2895 }
2896
2897 static int ata_eh_revalidate_and_attach(struct ata_link *link,
2898                                         struct ata_device **r_failed_dev)
2899 {
2900         struct ata_port *ap = link->ap;
2901         struct ata_eh_context *ehc = &link->eh_context;
2902         struct ata_device *dev;
2903         unsigned int new_mask = 0;
2904         unsigned long flags;
2905         int rc = 0;
2906
2907         DPRINTK("ENTER\n");
2908
2909         /* For PATA drive side cable detection to work, IDENTIFY must
2910          * be done backwards such that PDIAG- is released by the slave
2911          * device before the master device is identified.
2912          */
2913         ata_for_each_dev(dev, link, ALL_REVERSE) {
2914                 unsigned int action = ata_eh_dev_action(dev);
2915                 unsigned int readid_flags = 0;
2916
2917                 if (ehc->i.flags & ATA_EHI_DID_RESET)
2918                         readid_flags |= ATA_READID_POSTRESET;
2919
2920                 if ((action & ATA_EH_REVALIDATE) && ata_dev_enabled(dev)) {
2921                         WARN_ON(dev->class == ATA_DEV_PMP);
2922
2923                         if (ata_phys_link_offline(ata_dev_phys_link(dev))) {
2924                                 rc = -EIO;
2925                                 goto err;
2926                         }
2927
2928                         ata_eh_about_to_do(link, dev, ATA_EH_REVALIDATE);
2929                         rc = ata_dev_revalidate(dev, ehc->classes[dev->devno],
2930                                                 readid_flags);
2931                         if (rc)
2932                                 goto err;
2933
2934                         ata_eh_done(link, dev, ATA_EH_REVALIDATE);
2935
2936                         /* Configuration may have changed, reconfigure
2937                          * transfer mode.
2938                          */
2939                         ehc->i.flags |= ATA_EHI_SETMODE;
2940
2941                         /* schedule the scsi_rescan_device() here */
2942                         queue_work(ata_aux_wq, &(ap->scsi_rescan_task));
2943                 } else if (dev->class == ATA_DEV_UNKNOWN &&
2944                            ehc->tries[dev->devno] &&
2945                            ata_class_enabled(ehc->classes[dev->devno])) {
2946                         /* Temporarily set dev->class, it will be
2947                          * permanently set once all configurations are
2948                          * complete.  This is necessary because new
2949                          * device configuration is done in two
2950                          * separate loops.
2951                          */
2952                         dev->class = ehc->classes[dev->devno];
2953
2954                         if (dev->class == ATA_DEV_PMP)
2955                                 rc = sata_pmp_attach(dev);
2956                         else
2957                                 rc = ata_dev_read_id(dev, &dev->class,
2958                                                      readid_flags, dev->id);
2959
2960                         /* read_id might have changed class, store and reset */
2961                         ehc->classes[dev->devno] = dev->class;
2962                         dev->class = ATA_DEV_UNKNOWN;
2963
2964                         switch (rc) {
2965                         case 0:
2966                                 /* clear error info accumulated during probe */
2967                                 ata_ering_clear(&dev->ering);
2968                                 new_mask |= 1 << dev->devno;
2969                                 break;
2970                         case -ENOENT:
2971                                 /* IDENTIFY was issued to non-existent
2972                                  * device.  No need to reset.  Just
2973                                  * thaw and ignore the device.
2974                                  */
2975                                 ata_eh_thaw_port(ap);
2976                                 break;
2977                         default:
2978                                 goto err;
2979                         }
2980                 }
2981         }
2982
2983         /* PDIAG- should have been released, ask cable type if post-reset */
2984         if ((ehc->i.flags & ATA_EHI_DID_RESET) && ata_is_host_link(link)) {
2985                 if (ap->ops->cable_detect)
2986                         ap->cbl = ap->ops->cable_detect(ap);
2987                 ata_force_cbl(ap);
2988         }
2989
2990         /* Configure new devices forward such that user doesn't see
2991          * device detection messages backwards.
2992          */
2993         ata_for_each_dev(dev, link, ALL) {
2994                 if (!(new_mask & (1 << dev->devno)))
2995                         continue;
2996
2997                 dev->class = ehc->classes[dev->devno];
2998
2999                 if (dev->class == ATA_DEV_PMP)
3000                         continue;
3001
3002                 ehc->i.flags |= ATA_EHI_PRINTINFO;
3003                 rc = ata_dev_configure(dev);
3004                 ehc->i.flags &= ~ATA_EHI_PRINTINFO;
3005                 if (rc) {
3006                         dev->class = ATA_DEV_UNKNOWN;
3007                         goto err;
3008                 }
3009
3010                 spin_lock_irqsave(ap->lock, flags);
3011                 ap->pflags |= ATA_PFLAG_SCSI_HOTPLUG;
3012                 spin_unlock_irqrestore(ap->lock, flags);
3013
3014                 /* new device discovered, configure xfermode */
3015                 ehc->i.flags |= ATA_EHI_SETMODE;
3016         }
3017
3018         return 0;
3019
3020  err:
3021         *r_failed_dev = dev;
3022         DPRINTK("EXIT rc=%d\n", rc);
3023         return rc;
3024 }
3025
3026 /**
3027  *      ata_set_mode - Program timings and issue SET FEATURES - XFER
3028  *      @link: link on which timings will be programmed
3029  *      @r_failed_dev: out parameter for failed device
3030  *
3031  *      Set ATA device disk transfer mode (PIO3, UDMA6, etc.).  If
3032  *      ata_set_mode() fails, pointer to the failing device is
3033  *      returned in @r_failed_dev.
3034  *
3035  *      LOCKING:
3036  *      PCI/etc. bus probe sem.
3037  *
3038  *      RETURNS:
3039  *      0 on success, negative errno otherwise
3040  */
3041 int ata_set_mode(struct ata_link *link, struct ata_device **r_failed_dev)
3042 {
3043         struct ata_port *ap = link->ap;
3044         struct ata_device *dev;
3045         int rc;
3046
3047         /* if data transfer is verified, clear DUBIOUS_XFER on ering top */
3048         ata_for_each_dev(dev, link, ENABLED) {
3049                 if (!(dev->flags & ATA_DFLAG_DUBIOUS_XFER)) {
3050                         struct ata_ering_entry *ent;
3051
3052                         ent = ata_ering_top(&dev->ering);
3053                         if (ent)
3054                                 ent->eflags &= ~ATA_EFLAG_DUBIOUS_XFER;
3055                 }
3056         }
3057
3058         /* has private set_mode? */
3059         if (ap->ops->set_mode)
3060                 rc = ap->ops->set_mode(link, r_failed_dev);
3061         else
3062                 rc = ata_do_set_mode(link, r_failed_dev);
3063
3064         /* if transfer mode has changed, set DUBIOUS_XFER on device */
3065         ata_for_each_dev(dev, link, ENABLED) {
3066                 struct ata_eh_context *ehc = &link->eh_context;
3067                 u8 saved_xfer_mode = ehc->saved_xfer_mode[dev->devno];
3068                 u8 saved_ncq = !!(ehc->saved_ncq_enabled & (1 << dev->devno));
3069
3070                 if (dev->xfer_mode != saved_xfer_mode ||
3071                     ata_ncq_enabled(dev) != saved_ncq)
3072                         dev->flags |= ATA_DFLAG_DUBIOUS_XFER;
3073         }
3074
3075         return rc;
3076 }
3077
3078 /**
3079  *      atapi_eh_clear_ua - Clear ATAPI UNIT ATTENTION after reset
3080  *      @dev: ATAPI device to clear UA for
3081  *
3082  *      Resets and other operations can make an ATAPI device raise
3083  *      UNIT ATTENTION which causes the next operation to fail.  This
3084  *      function clears UA.
3085  *
3086  *      LOCKING:
3087  *      EH context (may sleep).
3088  *
3089  *      RETURNS:
3090  *      0 on success, -errno on failure.
3091  */
3092 static int atapi_eh_clear_ua(struct ata_device *dev)
3093 {
3094         int i;
3095
3096         for (i = 0; i < ATA_EH_UA_TRIES; i++) {
3097                 u8 *sense_buffer = dev->link->ap->sector_buf;
3098                 u8 sense_key = 0;
3099                 unsigned int err_mask;
3100
3101                 err_mask = atapi_eh_tur(dev, &sense_key);
3102                 if (err_mask != 0 && err_mask != AC_ERR_DEV) {
3103                         ata_dev_printk(dev, KERN_WARNING, "TEST_UNIT_READY "
3104                                 "failed (err_mask=0x%x)\n", err_mask);
3105                         return -EIO;
3106                 }
3107
3108                 if (!err_mask || sense_key != UNIT_ATTENTION)
3109                         return 0;
3110
3111                 err_mask = atapi_eh_request_sense(dev, sense_buffer, sense_key);
3112                 if (err_mask) {
3113                         ata_dev_printk(dev, KERN_WARNING, "failed to clear "
3114                                 "UNIT ATTENTION (err_mask=0x%x)\n", err_mask);
3115                         return -EIO;
3116                 }
3117         }
3118
3119         ata_dev_printk(dev, KERN_WARNING,
3120                 "UNIT ATTENTION persists after %d tries\n", ATA_EH_UA_TRIES);
3121
3122         return 0;
3123 }
3124
3125 static int ata_link_nr_enabled(struct ata_link *link)
3126 {
3127         struct ata_device *dev;
3128         int cnt = 0;
3129
3130         ata_for_each_dev(dev, link, ENABLED)
3131                 cnt++;
3132         return cnt;
3133 }
3134
3135 static int ata_link_nr_vacant(struct ata_link *link)
3136 {
3137         struct ata_device *dev;
3138         int cnt = 0;
3139
3140         ata_for_each_dev(dev, link, ALL)
3141                 if (dev->class == ATA_DEV_UNKNOWN)
3142                         cnt++;
3143         return cnt;
3144 }
3145
3146 static int ata_eh_skip_recovery(struct ata_link *link)
3147 {
3148         struct ata_port *ap = link->ap;
3149         struct ata_eh_context *ehc = &link->eh_context;
3150         struct ata_device *dev;
3151
3152         /* skip disabled links */
3153         if (link->flags & ATA_LFLAG_DISABLED)
3154                 return 1;
3155
3156         /* skip if explicitly requested */
3157         if (ehc->i.flags & ATA_EHI_NO_RECOVERY)
3158                 return 1;
3159
3160         /* thaw frozen port and recover failed devices */
3161         if ((ap->pflags & ATA_PFLAG_FROZEN) || ata_link_nr_enabled(link))
3162                 return 0;
3163
3164         /* reset at least once if reset is requested */
3165         if ((ehc->i.action & ATA_EH_RESET) &&
3166             !(ehc->i.flags & ATA_EHI_DID_RESET))
3167                 return 0;
3168
3169         /* skip if class codes for all vacant slots are ATA_DEV_NONE */
3170         ata_for_each_dev(dev, link, ALL) {
3171                 if (dev->class == ATA_DEV_UNKNOWN &&
3172                     ehc->classes[dev->devno] != ATA_DEV_NONE)
3173                         return 0;
3174         }
3175
3176         return 1;
3177 }
3178
3179 static int ata_count_probe_trials_cb(struct ata_ering_entry *ent, void *void_arg)
3180 {
3181         u64 interval = msecs_to_jiffies(ATA_EH_PROBE_TRIAL_INTERVAL);
3182         u64 now = get_jiffies_64();
3183         int *trials = void_arg;
3184
3185         if (ent->timestamp < now - min(now, interval))
3186                 return -1;
3187
3188         (*trials)++;
3189         return 0;
3190 }
3191
3192 static int ata_eh_schedule_probe(struct ata_device *dev)
3193 {
3194         struct ata_eh_context *ehc = &dev->link->eh_context;
3195         struct ata_link *link = ata_dev_phys_link(dev);
3196         int trials = 0;
3197
3198         if (!(ehc->i.probe_mask & (1 << dev->devno)) ||
3199             (ehc->did_probe_mask & (1 << dev->devno)))
3200                 return 0;
3201
3202         ata_eh_detach_dev(dev);
3203         ata_dev_init(dev);
3204         ehc->did_probe_mask |= (1 << dev->devno);
3205         ehc->i.action |= ATA_EH_RESET;
3206         ehc->saved_xfer_mode[dev->devno] = 0;
3207         ehc->saved_ncq_enabled &= ~(1 << dev->devno);
3208
3209         /* Record and count probe trials on the ering.  The specific
3210          * error mask used is irrelevant.  Because a successful device
3211          * detection clears the ering, this count accumulates only if
3212          * there are consecutive failed probes.
3213          *
3214          * If the count is equal to or higher than ATA_EH_PROBE_TRIALS
3215          * in the last ATA_EH_PROBE_TRIAL_INTERVAL, link speed is
3216          * forced to 1.5Gbps.
3217          *
3218          * This is to work around cases where failed link speed
3219          * negotiation results in device misdetection leading to
3220          * infinite DEVXCHG or PHRDY CHG events.
3221          */
3222         ata_ering_record(&dev->ering, 0, AC_ERR_OTHER);
3223         ata_ering_map(&dev->ering, ata_count_probe_trials_cb, &trials);
3224
3225         if (trials > ATA_EH_PROBE_TRIALS)
3226                 sata_down_spd_limit(link, 1);
3227
3228         return 1;
3229 }
3230
3231 static int ata_eh_handle_dev_fail(struct ata_device *dev, int err)
3232 {
3233         struct ata_eh_context *ehc = &dev->link->eh_context;
3234
3235         /* -EAGAIN from EH routine indicates retry without prejudice.
3236          * The requester is responsible for ensuring forward progress.
3237          */
3238         if (err != -EAGAIN)
3239                 ehc->tries[dev->devno]--;
3240
3241         switch (err) {
3242         case -ENODEV:
3243                 /* device missing or wrong IDENTIFY data, schedule probing */
3244                 ehc->i.probe_mask |= (1 << dev->devno);
3245         case -EINVAL:
3246                 /* give it just one more chance */
3247                 ehc->tries[dev->devno] = min(ehc->tries[dev->devno], 1);
3248         case -EIO:
3249                 if (ehc->tries[dev->devno] == 1) {
3250                         /* This is the last chance, better to slow
3251                          * down than lose it.
3252                          */
3253                         sata_down_spd_limit(ata_dev_phys_link(dev), 0);
3254                         if (dev->pio_mode > XFER_PIO_0)
3255                                 ata_down_xfermask_limit(dev, ATA_DNXFER_PIO);
3256                 }
3257         }
3258
3259         if (ata_dev_enabled(dev) && !ehc->tries[dev->devno]) {
3260                 /* disable device if it has used up all its chances */
3261                 ata_dev_disable(dev);
3262
3263                 /* detach if offline */
3264                 if (ata_phys_link_offline(ata_dev_phys_link(dev)))
3265                         ata_eh_detach_dev(dev);
3266
3267                 /* schedule probe if necessary */
3268                 if (ata_eh_schedule_probe(dev)) {
3269                         ehc->tries[dev->devno] = ATA_EH_DEV_TRIES;
3270                         memset(ehc->cmd_timeout_idx[dev->devno], 0,
3271                                sizeof(ehc->cmd_timeout_idx[dev->devno]));
3272                 }
3273
3274                 return 1;
3275         } else {
3276                 ehc->i.action |= ATA_EH_RESET;
3277                 return 0;
3278         }
3279 }
3280
3281 /**
3282  *      ata_eh_recover - recover host port after error
3283  *      @ap: host port to recover
3284  *      @prereset: prereset method (can be NULL)
3285  *      @softreset: softreset method (can be NULL)
3286  *      @hardreset: hardreset method (can be NULL)
3287  *      @postreset: postreset method (can be NULL)
3288  *      @r_failed_link: out parameter for failed link
3289  *
3290  *      This is the alpha and omega, eum and yang, heart and soul of
3291  *      libata exception handling.  On entry, actions required to
3292  *      recover each link and hotplug requests are recorded in the
3293  *      link's eh_context.  This function executes all the operations
3294  *      with appropriate retrials and fallbacks to resurrect failed
3295  *      devices, detach goners and greet newcomers.
3296  *
3297  *      LOCKING:
3298  *      Kernel thread context (may sleep).
3299  *
3300  *      RETURNS:
3301  *      0 on success, -errno on failure.
3302  */
3303 int ata_eh_recover(struct ata_port *ap, ata_prereset_fn_t prereset,
3304                    ata_reset_fn_t softreset, ata_reset_fn_t hardreset,
3305                    ata_postreset_fn_t postreset,
3306                    struct ata_link **r_failed_link)
3307 {
3308         struct ata_link *link;
3309         struct ata_device *dev;
3310         int nr_failed_devs;
3311         int rc;
3312         unsigned long flags, deadline;
3313
3314         DPRINTK("ENTER\n");
3315
3316         /* prep for recovery */
3317         ata_for_each_link(link, ap, EDGE) {
3318                 struct ata_eh_context *ehc = &link->eh_context;
3319
3320                 /* re-enable link? */
3321                 if (ehc->i.action & ATA_EH_ENABLE_LINK) {
3322                         ata_eh_about_to_do(link, NULL, ATA_EH_ENABLE_LINK);
3323                         spin_lock_irqsave(ap->lock, flags);
3324                         link->flags &= ~ATA_LFLAG_DISABLED;
3325                         spin_unlock_irqrestore(ap->lock, flags);
3326                         ata_eh_done(link, NULL, ATA_EH_ENABLE_LINK);
3327                 }
3328
3329                 ata_for_each_dev(dev, link, ALL) {
3330                         if (link->flags & ATA_LFLAG_NO_RETRY)
3331                                 ehc->tries[dev->devno] = 1;
3332                         else
3333                                 ehc->tries[dev->devno] = ATA_EH_DEV_TRIES;
3334
3335                         /* collect port action mask recorded in dev actions */
3336                         ehc->i.action |= ehc->i.dev_action[dev->devno] &
3337                                          ~ATA_EH_PERDEV_MASK;
3338                         ehc->i.dev_action[dev->devno] &= ATA_EH_PERDEV_MASK;
3339
3340                         /* process hotplug request */
3341                         if (dev->flags & ATA_DFLAG_DETACH)
3342                                 ata_eh_detach_dev(dev);
3343
3344                         /* schedule probe if necessary */
3345                         if (!ata_dev_enabled(dev))
3346                                 ata_eh_schedule_probe(dev);
3347                 }
3348         }
3349
3350  retry:
3351         rc = 0;
3352         nr_failed_devs = 0;
3353
3354         /* if UNLOADING, finish immediately */
3355         if (ap->pflags & ATA_PFLAG_UNLOADING)
3356                 goto out;
3357
3358         /* prep for EH */
3359         ata_for_each_link(link, ap, EDGE) {
3360                 struct ata_eh_context *ehc = &link->eh_context;
3361
3362                 /* skip EH if possible. */
3363                 if (ata_eh_skip_recovery(link))
3364                         ehc->i.action = 0;
3365
3366                 ata_for_each_dev(dev, link, ALL)
3367                         ehc->classes[dev->devno] = ATA_DEV_UNKNOWN;
3368         }
3369
3370         /* reset */
3371         ata_for_each_link(link, ap, EDGE) {
3372                 struct ata_eh_context *ehc = &link->eh_context;
3373
3374                 if (!(ehc->i.action & ATA_EH_RESET))
3375                         continue;
3376
3377                 rc = ata_eh_reset(link, ata_link_nr_vacant(link),
3378                                   prereset, softreset, hardreset, postreset);
3379                 if (rc) {
3380                         ata_link_printk(link, KERN_ERR,
3381                                         "reset failed, giving up\n");
3382                         goto out;
3383                 }
3384         }
3385
3386         do {
3387                 unsigned long now;
3388
3389                 /*
3390                  * clears ATA_EH_PARK in eh_info and resets
3391                  * ap->park_req_pending
3392                  */
3393                 ata_eh_pull_park_action(ap);
3394
3395                 deadline = jiffies;
3396                 ata_for_each_link(link, ap, EDGE) {
3397                         ata_for_each_dev(dev, link, ALL) {
3398                                 struct ata_eh_context *ehc = &link->eh_context;
3399                                 unsigned long tmp;
3400
3401                                 if (dev->class != ATA_DEV_ATA)
3402                                         continue;
3403                                 if (!(ehc->i.dev_action[dev->devno] &
3404                                       ATA_EH_PARK))
3405                                         continue;
3406                                 tmp = dev->unpark_deadline;
3407                                 if (time_before(deadline, tmp))
3408                                         deadline = tmp;
3409                                 else if (time_before_eq(tmp, jiffies))
3410                                         continue;
3411                                 if (ehc->unloaded_mask & (1 << dev->devno))
3412                                         continue;
3413
3414                                 ata_eh_park_issue_cmd(dev, 1);
3415                         }
3416                 }
3417
3418                 now = jiffies;
3419                 if (time_before_eq(deadline, now))
3420                         break;
3421
3422                 deadline = wait_for_completion_timeout(&ap->park_req_pending,
3423                                                        deadline - now);
3424         } while (deadline);
3425         ata_for_each_link(link, ap, EDGE) {
3426                 ata_for_each_dev(dev, link, ALL) {
3427                         if (!(link->eh_context.unloaded_mask &
3428                               (1 << dev->devno)))
3429                                 continue;
3430
3431                         ata_eh_park_issue_cmd(dev, 0);
3432                         ata_eh_done(link, dev, ATA_EH_PARK);
3433                 }
3434         }
3435
3436         /* the rest */
3437         ata_for_each_link(link, ap, EDGE) {
3438                 struct ata_eh_context *ehc = &link->eh_context;
3439
3440                 /* revalidate existing devices and attach new ones */
3441                 rc = ata_eh_revalidate_and_attach(link, &dev);
3442                 if (rc)
3443                         goto dev_fail;
3444
3445                 /* if PMP got attached, return, pmp EH will take care of it */
3446                 if (link->device->class == ATA_DEV_PMP) {
3447                         ehc->i.action = 0;
3448                         return 0;
3449                 }
3450
3451                 /* configure transfer mode if necessary */
3452                 if (ehc->i.flags & ATA_EHI_SETMODE) {
3453                         rc = ata_set_mode(link, &dev);
3454                         if (rc)
3455                                 goto dev_fail;
3456                         ehc->i.flags &= ~ATA_EHI_SETMODE;
3457                 }
3458
3459                 /* If reset has been issued, clear UA to avoid
3460                  * disrupting the current users of the device.
3461                  */
3462                 if (ehc->i.flags & ATA_EHI_DID_RESET) {
3463                         ata_for_each_dev(dev, link, ALL) {
3464                                 if (dev->class != ATA_DEV_ATAPI)
3465                                         continue;
3466                                 rc = atapi_eh_clear_ua(dev);
3467                                 if (rc)
3468                                         goto dev_fail;
3469                         }
3470                 }
3471
3472                 /* configure link power saving */
3473                 if (ehc->i.action & ATA_EH_LPM)
3474                         ata_for_each_dev(dev, link, ALL)
3475                                 ata_dev_enable_pm(dev, ap->pm_policy);
3476
3477                 /* this link is okay now */
3478                 ehc->i.flags = 0;
3479                 continue;
3480
3481 dev_fail:
3482                 nr_failed_devs++;
3483                 ata_eh_handle_dev_fail(dev, rc);
3484
3485                 if (ap->pflags & ATA_PFLAG_FROZEN) {
3486                         /* PMP reset requires working host port.
3487                          * Can't retry if it's frozen.
3488                          */
3489                         if (sata_pmp_attached(ap))
3490                                 goto out;
3491                         break;
3492                 }
3493         }
3494
3495         if (nr_failed_devs)
3496                 goto retry;
3497
3498  out:
3499         if (rc && r_failed_link)
3500                 *r_failed_link = link;
3501
3502         DPRINTK("EXIT, rc=%d\n", rc);
3503         return rc;
3504 }
3505
3506 /**
3507  *      ata_eh_finish - finish up EH
3508  *      @ap: host port to finish EH for
3509  *
3510  *      Recovery is complete.  Clean up EH states and retry or finish
3511  *      failed qcs.
3512  *
3513  *      LOCKING:
3514  *      None.
3515  */
3516 void ata_eh_finish(struct ata_port *ap)
3517 {
3518         int tag;
3519
3520         /* retry or finish qcs */
3521         for (tag = 0; tag < ATA_MAX_QUEUE; tag++) {
3522                 struct ata_queued_cmd *qc = __ata_qc_from_tag(ap, tag);
3523
3524                 if (!(qc->flags & ATA_QCFLAG_FAILED))
3525                         continue;
3526
3527                 if (qc->err_mask) {
3528                         /* FIXME: Once EH migration is complete,
3529                          * generate sense data in this function,
3530                          * considering both err_mask and tf.
3531                          */
3532                         if (qc->flags & ATA_QCFLAG_RETRY)
3533                                 ata_eh_qc_retry(qc);
3534                         else
3535                                 ata_eh_qc_complete(qc);
3536                 } else {
3537                         if (qc->flags & ATA_QCFLAG_SENSE_VALID) {
3538                                 ata_eh_qc_complete(qc);
3539                         } else {
3540                                 /* feed zero TF to sense generation */
3541                                 memset(&qc->result_tf, 0, sizeof(qc->result_tf));
3542                                 ata_eh_qc_retry(qc);
3543                         }
3544                 }
3545         }
3546
3547         /* make sure nr_active_links is zero after EH */
3548         WARN_ON(ap->nr_active_links);
3549         ap->nr_active_links = 0;
3550 }
3551
3552 /**
3553  *      ata_do_eh - do standard error handling
3554  *      @ap: host port to handle error for
3555  *
3556  *      @prereset: prereset method (can be NULL)
3557  *      @softreset: softreset method (can be NULL)
3558  *      @hardreset: hardreset method (can be NULL)
3559  *      @postreset: postreset method (can be NULL)
3560  *
3561  *      Perform standard error handling sequence.
3562  *
3563  *      LOCKING:
3564  *      Kernel thread context (may sleep).
3565  */
3566 void ata_do_eh(struct ata_port *ap, ata_prereset_fn_t prereset,
3567                ata_reset_fn_t softreset, ata_reset_fn_t hardreset,
3568                ata_postreset_fn_t postreset)
3569 {
3570         struct ata_device *dev;
3571         int rc;
3572
3573         ata_eh_autopsy(ap);
3574         ata_eh_report(ap);
3575
3576         rc = ata_eh_recover(ap, prereset, softreset, hardreset, postreset,
3577                             NULL);
3578         if (rc) {
3579                 ata_for_each_dev(dev, &ap->link, ALL)
3580                         ata_dev_disable(dev);
3581         }
3582
3583         ata_eh_finish(ap);
3584 }
3585
3586 /**
3587  *      ata_std_error_handler - standard error handler
3588  *      @ap: host port to handle error for
3589  *
3590  *      Standard error handler
3591  *
3592  *      LOCKING:
3593  *      Kernel thread context (may sleep).
3594  */
3595 void ata_std_error_handler(struct ata_port *ap)
3596 {
3597         struct ata_port_operations *ops = ap->ops;
3598         ata_reset_fn_t hardreset = ops->hardreset;
3599
3600         /* ignore built-in hardreset if SCR access is not available */
3601         if (ata_is_builtin_hardreset(hardreset) && !sata_scr_valid(&ap->link))
3602                 hardreset = NULL;
3603
3604         ata_do_eh(ap, ops->prereset, ops->softreset, hardreset, ops->postreset);
3605 }
3606
3607 #ifdef CONFIG_PM
3608 /**
3609  *      ata_eh_handle_port_suspend - perform port suspend operation
3610  *      @ap: port to suspend
3611  *
3612  *      Suspend @ap.
3613  *
3614  *      LOCKING:
3615  *      Kernel thread context (may sleep).
3616  */
3617 static void ata_eh_handle_port_suspend(struct ata_port *ap)
3618 {
3619         unsigned long flags;
3620         int rc = 0;
3621
3622         /* are we suspending? */
3623         spin_lock_irqsave(ap->lock, flags);
3624         if (!(ap->pflags & ATA_PFLAG_PM_PENDING) ||
3625             ap->pm_mesg.event == PM_EVENT_ON) {
3626                 spin_unlock_irqrestore(ap->lock, flags);
3627                 return;
3628         }
3629         spin_unlock_irqrestore(ap->lock, flags);
3630
3631         WARN_ON(ap->pflags & ATA_PFLAG_SUSPENDED);
3632
3633         /* tell ACPI we're suspending */
3634         rc = ata_acpi_on_suspend(ap);
3635         if (rc)
3636                 goto out;
3637
3638         /* suspend */
3639         ata_eh_freeze_port(ap);
3640
3641         if (ap->ops->port_suspend)
3642                 rc = ap->ops->port_suspend(ap, ap->pm_mesg);
3643
3644         ata_acpi_set_state(ap, PMSG_SUSPEND);
3645  out:
3646         /* report result */
3647         spin_lock_irqsave(ap->lock, flags);
3648
3649         ap->pflags &= ~ATA_PFLAG_PM_PENDING;
3650         if (rc == 0)
3651                 ap->pflags |= ATA_PFLAG_SUSPENDED;
3652         else if (ap->pflags & ATA_PFLAG_FROZEN)
3653                 ata_port_schedule_eh(ap);
3654
3655         if (ap->pm_result) {
3656                 *ap->pm_result = rc;
3657                 ap->pm_result = NULL;
3658         }
3659
3660         spin_unlock_irqrestore(ap->lock, flags);
3661
3662         return;
3663 }
3664
3665 /**
3666  *      ata_eh_handle_port_resume - perform port resume operation
3667  *      @ap: port to resume
3668  *
3669  *      Resume @ap.
3670  *
3671  *      LOCKING:
3672  *      Kernel thread context (may sleep).
3673  */
3674 static void ata_eh_handle_port_resume(struct ata_port *ap)
3675 {
3676         struct ata_link *link;
3677         struct ata_device *dev;
3678         unsigned long flags;
3679         int rc = 0;
3680
3681         /* are we resuming? */
3682         spin_lock_irqsave(ap->lock, flags);
3683         if (!(ap->pflags & ATA_PFLAG_PM_PENDING) ||
3684             ap->pm_mesg.event != PM_EVENT_ON) {
3685                 spin_unlock_irqrestore(ap->lock, flags);
3686                 return;
3687         }
3688         spin_unlock_irqrestore(ap->lock, flags);
3689
3690         WARN_ON(!(ap->pflags & ATA_PFLAG_SUSPENDED));
3691
3692         /*
3693          * Error timestamps are in jiffies which doesn't run while
3694          * suspended and PHY events during resume isn't too uncommon.
3695          * When the two are combined, it can lead to unnecessary speed
3696          * downs if the machine is suspended and resumed repeatedly.
3697          * Clear error history.
3698          */
3699         ata_for_each_link(link, ap, HOST_FIRST)
3700                 ata_for_each_dev(dev, link, ALL)
3701                         ata_ering_clear(&dev->ering);
3702
3703         ata_acpi_set_state(ap, PMSG_ON);
3704
3705         if (ap->ops->port_resume)
3706                 rc = ap->ops->port_resume(ap);
3707
3708         /* tell ACPI that we're resuming */
3709         ata_acpi_on_resume(ap);
3710
3711         /* report result */
3712         spin_lock_irqsave(ap->lock, flags);
3713         ap->pflags &= ~(ATA_PFLAG_PM_PENDING | ATA_PFLAG_SUSPENDED);
3714         if (ap->pm_result) {
3715                 *ap->pm_result = rc;
3716                 ap->pm_result = NULL;
3717         }
3718         spin_unlock_irqrestore(ap->lock, flags);
3719 }
3720 #endif /* CONFIG_PM */