GNU Linux-libre 4.14.328-gnu1
[releases.git] / drivers / ata / libata-core.c
1 /*
2  *  libata-core.c - helper library for ATA
3  *
4  *  Maintained by:  Tejun Heo <tj@kernel.org>
5  *                  Please ALWAYS copy linux-ide@vger.kernel.org
6  *                  on emails.
7  *
8  *  Copyright 2003-2004 Red Hat, Inc.  All rights reserved.
9  *  Copyright 2003-2004 Jeff Garzik
10  *
11  *
12  *  This program is free software; you can redistribute it and/or modify
13  *  it under the terms of the GNU General Public License as published by
14  *  the Free Software Foundation; either version 2, or (at your option)
15  *  any later version.
16  *
17  *  This program is distributed in the hope that it will be useful,
18  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
19  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  *  GNU General Public License for more details.
21  *
22  *  You should have received a copy of the GNU General Public License
23  *  along with this program; see the file COPYING.  If not, write to
24  *  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
25  *
26  *
27  *  libata documentation is available via 'make {ps|pdf}docs',
28  *  as Documentation/driver-api/libata.rst
29  *
30  *  Hardware documentation available from http://www.t13.org/ and
31  *  http://www.sata-io.org/
32  *
33  *  Standards documents from:
34  *      http://www.t13.org (ATA standards, PCI DMA IDE spec)
35  *      http://www.t10.org (SCSI MMC - for ATAPI MMC)
36  *      http://www.sata-io.org (SATA)
37  *      http://www.compactflash.org (CF)
38  *      http://www.qic.org (QIC157 - Tape and DSC)
39  *      http://www.ce-ata.org (CE-ATA: not supported)
40  *
41  */
42
43 #include <linux/kernel.h>
44 #include <linux/module.h>
45 #include <linux/pci.h>
46 #include <linux/init.h>
47 #include <linux/list.h>
48 #include <linux/mm.h>
49 #include <linux/spinlock.h>
50 #include <linux/blkdev.h>
51 #include <linux/delay.h>
52 #include <linux/timer.h>
53 #include <linux/time.h>
54 #include <linux/interrupt.h>
55 #include <linux/completion.h>
56 #include <linux/suspend.h>
57 #include <linux/workqueue.h>
58 #include <linux/scatterlist.h>
59 #include <linux/io.h>
60 #include <linux/log2.h>
61 #include <linux/slab.h>
62 #include <linux/glob.h>
63 #include <scsi/scsi.h>
64 #include <scsi/scsi_cmnd.h>
65 #include <scsi/scsi_host.h>
66 #include <linux/libata.h>
67 #include <asm/byteorder.h>
68 #include <asm/unaligned.h>
69 #include <linux/cdrom.h>
70 #include <linux/ratelimit.h>
71 #include <linux/leds.h>
72 #include <linux/pm_runtime.h>
73 #include <linux/platform_device.h>
74
75 #define CREATE_TRACE_POINTS
76 #include <trace/events/libata.h>
77
78 #include "libata.h"
79 #include "libata-transport.h"
80
81 /* debounce timing parameters in msecs { interval, duration, timeout } */
82 const unsigned long sata_deb_timing_normal[]            = {   5,  100, 2000 };
83 const unsigned long sata_deb_timing_hotplug[]           = {  25,  500, 2000 };
84 const unsigned long sata_deb_timing_long[]              = { 100, 2000, 5000 };
85
86 const struct ata_port_operations ata_base_port_ops = {
87         .prereset               = ata_std_prereset,
88         .postreset              = ata_std_postreset,
89         .error_handler          = ata_std_error_handler,
90         .sched_eh               = ata_std_sched_eh,
91         .end_eh                 = ata_std_end_eh,
92 };
93
94 const struct ata_port_operations sata_port_ops = {
95         .inherits               = &ata_base_port_ops,
96
97         .qc_defer               = ata_std_qc_defer,
98         .hardreset              = sata_std_hardreset,
99 };
100
101 static unsigned int ata_dev_init_params(struct ata_device *dev,
102                                         u16 heads, u16 sectors);
103 static unsigned int ata_dev_set_xfermode(struct ata_device *dev);
104 static void ata_dev_xfermask(struct ata_device *dev);
105 static unsigned long ata_dev_blacklisted(const struct ata_device *dev);
106
107 atomic_t ata_print_id = ATOMIC_INIT(0);
108
109 struct ata_force_param {
110         const char      *name;
111         unsigned int    cbl;
112         int             spd_limit;
113         unsigned long   xfer_mask;
114         unsigned int    horkage_on;
115         unsigned int    horkage_off;
116         unsigned int    lflags;
117 };
118
119 struct ata_force_ent {
120         int                     port;
121         int                     device;
122         struct ata_force_param  param;
123 };
124
125 static struct ata_force_ent *ata_force_tbl;
126 static int ata_force_tbl_size;
127
128 static char ata_force_param_buf[PAGE_SIZE] __initdata;
129 /* param_buf is thrown away after initialization, disallow read */
130 module_param_string(force, ata_force_param_buf, sizeof(ata_force_param_buf), 0);
131 MODULE_PARM_DESC(force, "Force ATA configurations including cable type, link speed and transfer mode (see Documentation/admin-guide/kernel-parameters.rst for details)");
132
133 static int atapi_enabled = 1;
134 module_param(atapi_enabled, int, 0444);
135 MODULE_PARM_DESC(atapi_enabled, "Enable discovery of ATAPI devices (0=off, 1=on [default])");
136
137 static int atapi_dmadir = 0;
138 module_param(atapi_dmadir, int, 0444);
139 MODULE_PARM_DESC(atapi_dmadir, "Enable ATAPI DMADIR bridge support (0=off [default], 1=on)");
140
141 int atapi_passthru16 = 1;
142 module_param(atapi_passthru16, int, 0444);
143 MODULE_PARM_DESC(atapi_passthru16, "Enable ATA_16 passthru for ATAPI devices (0=off, 1=on [default])");
144
145 int libata_fua = 0;
146 module_param_named(fua, libata_fua, int, 0444);
147 MODULE_PARM_DESC(fua, "FUA support (0=off [default], 1=on)");
148
149 static int ata_ignore_hpa;
150 module_param_named(ignore_hpa, ata_ignore_hpa, int, 0644);
151 MODULE_PARM_DESC(ignore_hpa, "Ignore HPA limit (0=keep BIOS limits, 1=ignore limits, using full disk)");
152
153 static int libata_dma_mask = ATA_DMA_MASK_ATA|ATA_DMA_MASK_ATAPI|ATA_DMA_MASK_CFA;
154 module_param_named(dma, libata_dma_mask, int, 0444);
155 MODULE_PARM_DESC(dma, "DMA enable/disable (0x1==ATA, 0x2==ATAPI, 0x4==CF)");
156
157 static int ata_probe_timeout;
158 module_param(ata_probe_timeout, int, 0444);
159 MODULE_PARM_DESC(ata_probe_timeout, "Set ATA probing timeout (seconds)");
160
161 int libata_noacpi = 0;
162 module_param_named(noacpi, libata_noacpi, int, 0444);
163 MODULE_PARM_DESC(noacpi, "Disable the use of ACPI in probe/suspend/resume (0=off [default], 1=on)");
164
165 int libata_allow_tpm = 0;
166 module_param_named(allow_tpm, libata_allow_tpm, int, 0444);
167 MODULE_PARM_DESC(allow_tpm, "Permit the use of TPM commands (0=off [default], 1=on)");
168
169 static int atapi_an;
170 module_param(atapi_an, int, 0444);
171 MODULE_PARM_DESC(atapi_an, "Enable ATAPI AN media presence notification (0=0ff [default], 1=on)");
172
173 MODULE_AUTHOR("Jeff Garzik");
174 MODULE_DESCRIPTION("Library module for ATA devices");
175 MODULE_LICENSE("GPL");
176 MODULE_VERSION(DRV_VERSION);
177
178
179 static bool ata_sstatus_online(u32 sstatus)
180 {
181         return (sstatus & 0xf) == 0x3;
182 }
183
184 /**
185  *      ata_link_next - link iteration helper
186  *      @link: the previous link, NULL to start
187  *      @ap: ATA port containing links to iterate
188  *      @mode: iteration mode, one of ATA_LITER_*
189  *
190  *      LOCKING:
191  *      Host lock or EH context.
192  *
193  *      RETURNS:
194  *      Pointer to the next link.
195  */
196 struct ata_link *ata_link_next(struct ata_link *link, struct ata_port *ap,
197                                enum ata_link_iter_mode mode)
198 {
199         BUG_ON(mode != ATA_LITER_EDGE &&
200                mode != ATA_LITER_PMP_FIRST && mode != ATA_LITER_HOST_FIRST);
201
202         /* NULL link indicates start of iteration */
203         if (!link)
204                 switch (mode) {
205                 case ATA_LITER_EDGE:
206                 case ATA_LITER_PMP_FIRST:
207                         if (sata_pmp_attached(ap))
208                                 return ap->pmp_link;
209                         /* fall through */
210                 case ATA_LITER_HOST_FIRST:
211                         return &ap->link;
212                 }
213
214         /* we just iterated over the host link, what's next? */
215         if (link == &ap->link)
216                 switch (mode) {
217                 case ATA_LITER_HOST_FIRST:
218                         if (sata_pmp_attached(ap))
219                                 return ap->pmp_link;
220                         /* fall through */
221                 case ATA_LITER_PMP_FIRST:
222                         if (unlikely(ap->slave_link))
223                                 return ap->slave_link;
224                         /* fall through */
225                 case ATA_LITER_EDGE:
226                         return NULL;
227                 }
228
229         /* slave_link excludes PMP */
230         if (unlikely(link == ap->slave_link))
231                 return NULL;
232
233         /* we were over a PMP link */
234         if (++link < ap->pmp_link + ap->nr_pmp_links)
235                 return link;
236
237         if (mode == ATA_LITER_PMP_FIRST)
238                 return &ap->link;
239
240         return NULL;
241 }
242
243 /**
244  *      ata_dev_next - device iteration helper
245  *      @dev: the previous device, NULL to start
246  *      @link: ATA link containing devices to iterate
247  *      @mode: iteration mode, one of ATA_DITER_*
248  *
249  *      LOCKING:
250  *      Host lock or EH context.
251  *
252  *      RETURNS:
253  *      Pointer to the next device.
254  */
255 struct ata_device *ata_dev_next(struct ata_device *dev, struct ata_link *link,
256                                 enum ata_dev_iter_mode mode)
257 {
258         BUG_ON(mode != ATA_DITER_ENABLED && mode != ATA_DITER_ENABLED_REVERSE &&
259                mode != ATA_DITER_ALL && mode != ATA_DITER_ALL_REVERSE);
260
261         /* NULL dev indicates start of iteration */
262         if (!dev)
263                 switch (mode) {
264                 case ATA_DITER_ENABLED:
265                 case ATA_DITER_ALL:
266                         dev = link->device;
267                         goto check;
268                 case ATA_DITER_ENABLED_REVERSE:
269                 case ATA_DITER_ALL_REVERSE:
270                         dev = link->device + ata_link_max_devices(link) - 1;
271                         goto check;
272                 }
273
274  next:
275         /* move to the next one */
276         switch (mode) {
277         case ATA_DITER_ENABLED:
278         case ATA_DITER_ALL:
279                 if (++dev < link->device + ata_link_max_devices(link))
280                         goto check;
281                 return NULL;
282         case ATA_DITER_ENABLED_REVERSE:
283         case ATA_DITER_ALL_REVERSE:
284                 if (--dev >= link->device)
285                         goto check;
286                 return NULL;
287         }
288
289  check:
290         if ((mode == ATA_DITER_ENABLED || mode == ATA_DITER_ENABLED_REVERSE) &&
291             !ata_dev_enabled(dev))
292                 goto next;
293         return dev;
294 }
295
296 /**
297  *      ata_dev_phys_link - find physical link for a device
298  *      @dev: ATA device to look up physical link for
299  *
300  *      Look up physical link which @dev is attached to.  Note that
301  *      this is different from @dev->link only when @dev is on slave
302  *      link.  For all other cases, it's the same as @dev->link.
303  *
304  *      LOCKING:
305  *      Don't care.
306  *
307  *      RETURNS:
308  *      Pointer to the found physical link.
309  */
310 struct ata_link *ata_dev_phys_link(struct ata_device *dev)
311 {
312         struct ata_port *ap = dev->link->ap;
313
314         if (!ap->slave_link)
315                 return dev->link;
316         if (!dev->devno)
317                 return &ap->link;
318         return ap->slave_link;
319 }
320
321 /**
322  *      ata_force_cbl - force cable type according to libata.force
323  *      @ap: ATA port of interest
324  *
325  *      Force cable type according to libata.force and whine about it.
326  *      The last entry which has matching port number is used, so it
327  *      can be specified as part of device force parameters.  For
328  *      example, both "a:40c,1.00:udma4" and "1.00:40c,udma4" have the
329  *      same effect.
330  *
331  *      LOCKING:
332  *      EH context.
333  */
334 void ata_force_cbl(struct ata_port *ap)
335 {
336         int i;
337
338         for (i = ata_force_tbl_size - 1; i >= 0; i--) {
339                 const struct ata_force_ent *fe = &ata_force_tbl[i];
340
341                 if (fe->port != -1 && fe->port != ap->print_id)
342                         continue;
343
344                 if (fe->param.cbl == ATA_CBL_NONE)
345                         continue;
346
347                 ap->cbl = fe->param.cbl;
348                 ata_port_notice(ap, "FORCE: cable set to %s\n", fe->param.name);
349                 return;
350         }
351 }
352
353 /**
354  *      ata_force_link_limits - force link limits according to libata.force
355  *      @link: ATA link of interest
356  *
357  *      Force link flags and SATA spd limit according to libata.force
358  *      and whine about it.  When only the port part is specified
359  *      (e.g. 1:), the limit applies to all links connected to both
360  *      the host link and all fan-out ports connected via PMP.  If the
361  *      device part is specified as 0 (e.g. 1.00:), it specifies the
362  *      first fan-out link not the host link.  Device number 15 always
363  *      points to the host link whether PMP is attached or not.  If the
364  *      controller has slave link, device number 16 points to it.
365  *
366  *      LOCKING:
367  *      EH context.
368  */
369 static void ata_force_link_limits(struct ata_link *link)
370 {
371         bool did_spd = false;
372         int linkno = link->pmp;
373         int i;
374
375         if (ata_is_host_link(link))
376                 linkno += 15;
377
378         for (i = ata_force_tbl_size - 1; i >= 0; i--) {
379                 const struct ata_force_ent *fe = &ata_force_tbl[i];
380
381                 if (fe->port != -1 && fe->port != link->ap->print_id)
382                         continue;
383
384                 if (fe->device != -1 && fe->device != linkno)
385                         continue;
386
387                 /* only honor the first spd limit */
388                 if (!did_spd && fe->param.spd_limit) {
389                         link->hw_sata_spd_limit = (1 << fe->param.spd_limit) - 1;
390                         ata_link_notice(link, "FORCE: PHY spd limit set to %s\n",
391                                         fe->param.name);
392                         did_spd = true;
393                 }
394
395                 /* let lflags stack */
396                 if (fe->param.lflags) {
397                         link->flags |= fe->param.lflags;
398                         ata_link_notice(link,
399                                         "FORCE: link flag 0x%x forced -> 0x%x\n",
400                                         fe->param.lflags, link->flags);
401                 }
402         }
403 }
404
405 /**
406  *      ata_force_xfermask - force xfermask according to libata.force
407  *      @dev: ATA device of interest
408  *
409  *      Force xfer_mask according to libata.force and whine about it.
410  *      For consistency with link selection, device number 15 selects
411  *      the first device connected to the host link.
412  *
413  *      LOCKING:
414  *      EH context.
415  */
416 static void ata_force_xfermask(struct ata_device *dev)
417 {
418         int devno = dev->link->pmp + dev->devno;
419         int alt_devno = devno;
420         int i;
421
422         /* allow n.15/16 for devices attached to host port */
423         if (ata_is_host_link(dev->link))
424                 alt_devno += 15;
425
426         for (i = ata_force_tbl_size - 1; i >= 0; i--) {
427                 const struct ata_force_ent *fe = &ata_force_tbl[i];
428                 unsigned long pio_mask, mwdma_mask, udma_mask;
429
430                 if (fe->port != -1 && fe->port != dev->link->ap->print_id)
431                         continue;
432
433                 if (fe->device != -1 && fe->device != devno &&
434                     fe->device != alt_devno)
435                         continue;
436
437                 if (!fe->param.xfer_mask)
438                         continue;
439
440                 ata_unpack_xfermask(fe->param.xfer_mask,
441                                     &pio_mask, &mwdma_mask, &udma_mask);
442                 if (udma_mask)
443                         dev->udma_mask = udma_mask;
444                 else if (mwdma_mask) {
445                         dev->udma_mask = 0;
446                         dev->mwdma_mask = mwdma_mask;
447                 } else {
448                         dev->udma_mask = 0;
449                         dev->mwdma_mask = 0;
450                         dev->pio_mask = pio_mask;
451                 }
452
453                 ata_dev_notice(dev, "FORCE: xfer_mask set to %s\n",
454                                fe->param.name);
455                 return;
456         }
457 }
458
459 /**
460  *      ata_force_horkage - force horkage according to libata.force
461  *      @dev: ATA device of interest
462  *
463  *      Force horkage according to libata.force and whine about it.
464  *      For consistency with link selection, device number 15 selects
465  *      the first device connected to the host link.
466  *
467  *      LOCKING:
468  *      EH context.
469  */
470 static void ata_force_horkage(struct ata_device *dev)
471 {
472         int devno = dev->link->pmp + dev->devno;
473         int alt_devno = devno;
474         int i;
475
476         /* allow n.15/16 for devices attached to host port */
477         if (ata_is_host_link(dev->link))
478                 alt_devno += 15;
479
480         for (i = 0; i < ata_force_tbl_size; i++) {
481                 const struct ata_force_ent *fe = &ata_force_tbl[i];
482
483                 if (fe->port != -1 && fe->port != dev->link->ap->print_id)
484                         continue;
485
486                 if (fe->device != -1 && fe->device != devno &&
487                     fe->device != alt_devno)
488                         continue;
489
490                 if (!(~dev->horkage & fe->param.horkage_on) &&
491                     !(dev->horkage & fe->param.horkage_off))
492                         continue;
493
494                 dev->horkage |= fe->param.horkage_on;
495                 dev->horkage &= ~fe->param.horkage_off;
496
497                 ata_dev_notice(dev, "FORCE: horkage modified (%s)\n",
498                                fe->param.name);
499         }
500 }
501
502 /**
503  *      atapi_cmd_type - Determine ATAPI command type from SCSI opcode
504  *      @opcode: SCSI opcode
505  *
506  *      Determine ATAPI command type from @opcode.
507  *
508  *      LOCKING:
509  *      None.
510  *
511  *      RETURNS:
512  *      ATAPI_{READ|WRITE|READ_CD|PASS_THRU|MISC}
513  */
514 int atapi_cmd_type(u8 opcode)
515 {
516         switch (opcode) {
517         case GPCMD_READ_10:
518         case GPCMD_READ_12:
519                 return ATAPI_READ;
520
521         case GPCMD_WRITE_10:
522         case GPCMD_WRITE_12:
523         case GPCMD_WRITE_AND_VERIFY_10:
524                 return ATAPI_WRITE;
525
526         case GPCMD_READ_CD:
527         case GPCMD_READ_CD_MSF:
528                 return ATAPI_READ_CD;
529
530         case ATA_16:
531         case ATA_12:
532                 if (atapi_passthru16)
533                         return ATAPI_PASS_THRU;
534                 /* fall thru */
535         default:
536                 return ATAPI_MISC;
537         }
538 }
539
540 /**
541  *      ata_tf_to_fis - Convert ATA taskfile to SATA FIS structure
542  *      @tf: Taskfile to convert
543  *      @pmp: Port multiplier port
544  *      @is_cmd: This FIS is for command
545  *      @fis: Buffer into which data will output
546  *
547  *      Converts a standard ATA taskfile to a Serial ATA
548  *      FIS structure (Register - Host to Device).
549  *
550  *      LOCKING:
551  *      Inherited from caller.
552  */
553 void ata_tf_to_fis(const struct ata_taskfile *tf, u8 pmp, int is_cmd, u8 *fis)
554 {
555         fis[0] = 0x27;                  /* Register - Host to Device FIS */
556         fis[1] = pmp & 0xf;             /* Port multiplier number*/
557         if (is_cmd)
558                 fis[1] |= (1 << 7);     /* bit 7 indicates Command FIS */
559
560         fis[2] = tf->command;
561         fis[3] = tf->feature;
562
563         fis[4] = tf->lbal;
564         fis[5] = tf->lbam;
565         fis[6] = tf->lbah;
566         fis[7] = tf->device;
567
568         fis[8] = tf->hob_lbal;
569         fis[9] = tf->hob_lbam;
570         fis[10] = tf->hob_lbah;
571         fis[11] = tf->hob_feature;
572
573         fis[12] = tf->nsect;
574         fis[13] = tf->hob_nsect;
575         fis[14] = 0;
576         fis[15] = tf->ctl;
577
578         fis[16] = tf->auxiliary & 0xff;
579         fis[17] = (tf->auxiliary >> 8) & 0xff;
580         fis[18] = (tf->auxiliary >> 16) & 0xff;
581         fis[19] = (tf->auxiliary >> 24) & 0xff;
582 }
583
584 /**
585  *      ata_tf_from_fis - Convert SATA FIS to ATA taskfile
586  *      @fis: Buffer from which data will be input
587  *      @tf: Taskfile to output
588  *
589  *      Converts a serial ATA FIS structure to a standard ATA taskfile.
590  *
591  *      LOCKING:
592  *      Inherited from caller.
593  */
594
595 void ata_tf_from_fis(const u8 *fis, struct ata_taskfile *tf)
596 {
597         tf->command     = fis[2];       /* status */
598         tf->feature     = fis[3];       /* error */
599
600         tf->lbal        = fis[4];
601         tf->lbam        = fis[5];
602         tf->lbah        = fis[6];
603         tf->device      = fis[7];
604
605         tf->hob_lbal    = fis[8];
606         tf->hob_lbam    = fis[9];
607         tf->hob_lbah    = fis[10];
608
609         tf->nsect       = fis[12];
610         tf->hob_nsect   = fis[13];
611 }
612
613 static const u8 ata_rw_cmds[] = {
614         /* pio multi */
615         ATA_CMD_READ_MULTI,
616         ATA_CMD_WRITE_MULTI,
617         ATA_CMD_READ_MULTI_EXT,
618         ATA_CMD_WRITE_MULTI_EXT,
619         0,
620         0,
621         0,
622         ATA_CMD_WRITE_MULTI_FUA_EXT,
623         /* pio */
624         ATA_CMD_PIO_READ,
625         ATA_CMD_PIO_WRITE,
626         ATA_CMD_PIO_READ_EXT,
627         ATA_CMD_PIO_WRITE_EXT,
628         0,
629         0,
630         0,
631         0,
632         /* dma */
633         ATA_CMD_READ,
634         ATA_CMD_WRITE,
635         ATA_CMD_READ_EXT,
636         ATA_CMD_WRITE_EXT,
637         0,
638         0,
639         0,
640         ATA_CMD_WRITE_FUA_EXT
641 };
642
643 /**
644  *      ata_rwcmd_protocol - set taskfile r/w commands and protocol
645  *      @tf: command to examine and configure
646  *      @dev: device tf belongs to
647  *
648  *      Examine the device configuration and tf->flags to calculate
649  *      the proper read/write commands and protocol to use.
650  *
651  *      LOCKING:
652  *      caller.
653  */
654 static int ata_rwcmd_protocol(struct ata_taskfile *tf, struct ata_device *dev)
655 {
656         u8 cmd;
657
658         int index, fua, lba48, write;
659
660         fua = (tf->flags & ATA_TFLAG_FUA) ? 4 : 0;
661         lba48 = (tf->flags & ATA_TFLAG_LBA48) ? 2 : 0;
662         write = (tf->flags & ATA_TFLAG_WRITE) ? 1 : 0;
663
664         if (dev->flags & ATA_DFLAG_PIO) {
665                 tf->protocol = ATA_PROT_PIO;
666                 index = dev->multi_count ? 0 : 8;
667         } else if (lba48 && (dev->link->ap->flags & ATA_FLAG_PIO_LBA48)) {
668                 /* Unable to use DMA due to host limitation */
669                 tf->protocol = ATA_PROT_PIO;
670                 index = dev->multi_count ? 0 : 8;
671         } else {
672                 tf->protocol = ATA_PROT_DMA;
673                 index = 16;
674         }
675
676         cmd = ata_rw_cmds[index + fua + lba48 + write];
677         if (cmd) {
678                 tf->command = cmd;
679                 return 0;
680         }
681         return -1;
682 }
683
684 /**
685  *      ata_tf_read_block - Read block address from ATA taskfile
686  *      @tf: ATA taskfile of interest
687  *      @dev: ATA device @tf belongs to
688  *
689  *      LOCKING:
690  *      None.
691  *
692  *      Read block address from @tf.  This function can handle all
693  *      three address formats - LBA, LBA48 and CHS.  tf->protocol and
694  *      flags select the address format to use.
695  *
696  *      RETURNS:
697  *      Block address read from @tf.
698  */
699 u64 ata_tf_read_block(const struct ata_taskfile *tf, struct ata_device *dev)
700 {
701         u64 block = 0;
702
703         if (tf->flags & ATA_TFLAG_LBA) {
704                 if (tf->flags & ATA_TFLAG_LBA48) {
705                         block |= (u64)tf->hob_lbah << 40;
706                         block |= (u64)tf->hob_lbam << 32;
707                         block |= (u64)tf->hob_lbal << 24;
708                 } else
709                         block |= (tf->device & 0xf) << 24;
710
711                 block |= tf->lbah << 16;
712                 block |= tf->lbam << 8;
713                 block |= tf->lbal;
714         } else {
715                 u32 cyl, head, sect;
716
717                 cyl = tf->lbam | (tf->lbah << 8);
718                 head = tf->device & 0xf;
719                 sect = tf->lbal;
720
721                 if (!sect) {
722                         ata_dev_warn(dev,
723                                      "device reported invalid CHS sector 0\n");
724                         return U64_MAX;
725                 }
726
727                 block = (cyl * dev->heads + head) * dev->sectors + sect - 1;
728         }
729
730         return block;
731 }
732
733 /**
734  *      ata_build_rw_tf - Build ATA taskfile for given read/write request
735  *      @tf: Target ATA taskfile
736  *      @dev: ATA device @tf belongs to
737  *      @block: Block address
738  *      @n_block: Number of blocks
739  *      @tf_flags: RW/FUA etc...
740  *      @tag: tag
741  *      @class: IO priority class
742  *
743  *      LOCKING:
744  *      None.
745  *
746  *      Build ATA taskfile @tf for read/write request described by
747  *      @block, @n_block, @tf_flags and @tag on @dev.
748  *
749  *      RETURNS:
750  *
751  *      0 on success, -ERANGE if the request is too large for @dev,
752  *      -EINVAL if the request is invalid.
753  */
754 int ata_build_rw_tf(struct ata_taskfile *tf, struct ata_device *dev,
755                     u64 block, u32 n_block, unsigned int tf_flags,
756                     unsigned int tag, int class)
757 {
758         tf->flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
759         tf->flags |= tf_flags;
760
761         if (ata_ncq_enabled(dev) && likely(tag != ATA_TAG_INTERNAL)) {
762                 /* yay, NCQ */
763                 if (!lba_48_ok(block, n_block))
764                         return -ERANGE;
765
766                 tf->protocol = ATA_PROT_NCQ;
767                 tf->flags |= ATA_TFLAG_LBA | ATA_TFLAG_LBA48;
768
769                 if (tf->flags & ATA_TFLAG_WRITE)
770                         tf->command = ATA_CMD_FPDMA_WRITE;
771                 else
772                         tf->command = ATA_CMD_FPDMA_READ;
773
774                 tf->nsect = tag << 3;
775                 tf->hob_feature = (n_block >> 8) & 0xff;
776                 tf->feature = n_block & 0xff;
777
778                 tf->hob_lbah = (block >> 40) & 0xff;
779                 tf->hob_lbam = (block >> 32) & 0xff;
780                 tf->hob_lbal = (block >> 24) & 0xff;
781                 tf->lbah = (block >> 16) & 0xff;
782                 tf->lbam = (block >> 8) & 0xff;
783                 tf->lbal = block & 0xff;
784
785                 tf->device = ATA_LBA;
786                 if (tf->flags & ATA_TFLAG_FUA)
787                         tf->device |= 1 << 7;
788
789                 if (dev->flags & ATA_DFLAG_NCQ_PRIO) {
790                         if (class == IOPRIO_CLASS_RT)
791                                 tf->hob_nsect |= ATA_PRIO_HIGH <<
792                                                  ATA_SHIFT_PRIO;
793                 }
794         } else if (dev->flags & ATA_DFLAG_LBA) {
795                 tf->flags |= ATA_TFLAG_LBA;
796
797                 if (lba_28_ok(block, n_block)) {
798                         /* use LBA28 */
799                         tf->device |= (block >> 24) & 0xf;
800                 } else if (lba_48_ok(block, n_block)) {
801                         if (!(dev->flags & ATA_DFLAG_LBA48))
802                                 return -ERANGE;
803
804                         /* use LBA48 */
805                         tf->flags |= ATA_TFLAG_LBA48;
806
807                         tf->hob_nsect = (n_block >> 8) & 0xff;
808
809                         tf->hob_lbah = (block >> 40) & 0xff;
810                         tf->hob_lbam = (block >> 32) & 0xff;
811                         tf->hob_lbal = (block >> 24) & 0xff;
812                 } else
813                         /* request too large even for LBA48 */
814                         return -ERANGE;
815
816                 if (unlikely(ata_rwcmd_protocol(tf, dev) < 0))
817                         return -EINVAL;
818
819                 tf->nsect = n_block & 0xff;
820
821                 tf->lbah = (block >> 16) & 0xff;
822                 tf->lbam = (block >> 8) & 0xff;
823                 tf->lbal = block & 0xff;
824
825                 tf->device |= ATA_LBA;
826         } else {
827                 /* CHS */
828                 u32 sect, head, cyl, track;
829
830                 /* The request -may- be too large for CHS addressing. */
831                 if (!lba_28_ok(block, n_block))
832                         return -ERANGE;
833
834                 if (unlikely(ata_rwcmd_protocol(tf, dev) < 0))
835                         return -EINVAL;
836
837                 /* Convert LBA to CHS */
838                 track = (u32)block / dev->sectors;
839                 cyl   = track / dev->heads;
840                 head  = track % dev->heads;
841                 sect  = (u32)block % dev->sectors + 1;
842
843                 DPRINTK("block %u track %u cyl %u head %u sect %u\n",
844                         (u32)block, track, cyl, head, sect);
845
846                 /* Check whether the converted CHS can fit.
847                    Cylinder: 0-65535
848                    Head: 0-15
849                    Sector: 1-255*/
850                 if ((cyl >> 16) || (head >> 4) || (sect >> 8) || (!sect))
851                         return -ERANGE;
852
853                 tf->nsect = n_block & 0xff; /* Sector count 0 means 256 sectors */
854                 tf->lbal = sect;
855                 tf->lbam = cyl;
856                 tf->lbah = cyl >> 8;
857                 tf->device |= head;
858         }
859
860         return 0;
861 }
862
863 /**
864  *      ata_pack_xfermask - Pack pio, mwdma and udma masks into xfer_mask
865  *      @pio_mask: pio_mask
866  *      @mwdma_mask: mwdma_mask
867  *      @udma_mask: udma_mask
868  *
869  *      Pack @pio_mask, @mwdma_mask and @udma_mask into a single
870  *      unsigned int xfer_mask.
871  *
872  *      LOCKING:
873  *      None.
874  *
875  *      RETURNS:
876  *      Packed xfer_mask.
877  */
878 unsigned long ata_pack_xfermask(unsigned long pio_mask,
879                                 unsigned long mwdma_mask,
880                                 unsigned long udma_mask)
881 {
882         return ((pio_mask << ATA_SHIFT_PIO) & ATA_MASK_PIO) |
883                 ((mwdma_mask << ATA_SHIFT_MWDMA) & ATA_MASK_MWDMA) |
884                 ((udma_mask << ATA_SHIFT_UDMA) & ATA_MASK_UDMA);
885 }
886
887 /**
888  *      ata_unpack_xfermask - Unpack xfer_mask into pio, mwdma and udma masks
889  *      @xfer_mask: xfer_mask to unpack
890  *      @pio_mask: resulting pio_mask
891  *      @mwdma_mask: resulting mwdma_mask
892  *      @udma_mask: resulting udma_mask
893  *
894  *      Unpack @xfer_mask into @pio_mask, @mwdma_mask and @udma_mask.
895  *      Any NULL destination masks will be ignored.
896  */
897 void ata_unpack_xfermask(unsigned long xfer_mask, unsigned long *pio_mask,
898                          unsigned long *mwdma_mask, unsigned long *udma_mask)
899 {
900         if (pio_mask)
901                 *pio_mask = (xfer_mask & ATA_MASK_PIO) >> ATA_SHIFT_PIO;
902         if (mwdma_mask)
903                 *mwdma_mask = (xfer_mask & ATA_MASK_MWDMA) >> ATA_SHIFT_MWDMA;
904         if (udma_mask)
905                 *udma_mask = (xfer_mask & ATA_MASK_UDMA) >> ATA_SHIFT_UDMA;
906 }
907
908 static const struct ata_xfer_ent {
909         int shift, bits;
910         u8 base;
911 } ata_xfer_tbl[] = {
912         { ATA_SHIFT_PIO, ATA_NR_PIO_MODES, XFER_PIO_0 },
913         { ATA_SHIFT_MWDMA, ATA_NR_MWDMA_MODES, XFER_MW_DMA_0 },
914         { ATA_SHIFT_UDMA, ATA_NR_UDMA_MODES, XFER_UDMA_0 },
915         { -1, },
916 };
917
918 /**
919  *      ata_xfer_mask2mode - Find matching XFER_* for the given xfer_mask
920  *      @xfer_mask: xfer_mask of interest
921  *
922  *      Return matching XFER_* value for @xfer_mask.  Only the highest
923  *      bit of @xfer_mask is considered.
924  *
925  *      LOCKING:
926  *      None.
927  *
928  *      RETURNS:
929  *      Matching XFER_* value, 0xff if no match found.
930  */
931 u8 ata_xfer_mask2mode(unsigned long xfer_mask)
932 {
933         int highbit = fls(xfer_mask) - 1;
934         const struct ata_xfer_ent *ent;
935
936         for (ent = ata_xfer_tbl; ent->shift >= 0; ent++)
937                 if (highbit >= ent->shift && highbit < ent->shift + ent->bits)
938                         return ent->base + highbit - ent->shift;
939         return 0xff;
940 }
941
942 /**
943  *      ata_xfer_mode2mask - Find matching xfer_mask for XFER_*
944  *      @xfer_mode: XFER_* of interest
945  *
946  *      Return matching xfer_mask for @xfer_mode.
947  *
948  *      LOCKING:
949  *      None.
950  *
951  *      RETURNS:
952  *      Matching xfer_mask, 0 if no match found.
953  */
954 unsigned long ata_xfer_mode2mask(u8 xfer_mode)
955 {
956         const struct ata_xfer_ent *ent;
957
958         for (ent = ata_xfer_tbl; ent->shift >= 0; ent++)
959                 if (xfer_mode >= ent->base && xfer_mode < ent->base + ent->bits)
960                         return ((2 << (ent->shift + xfer_mode - ent->base)) - 1)
961                                 & ~((1 << ent->shift) - 1);
962         return 0;
963 }
964
965 /**
966  *      ata_xfer_mode2shift - Find matching xfer_shift for XFER_*
967  *      @xfer_mode: XFER_* of interest
968  *
969  *      Return matching xfer_shift for @xfer_mode.
970  *
971  *      LOCKING:
972  *      None.
973  *
974  *      RETURNS:
975  *      Matching xfer_shift, -1 if no match found.
976  */
977 int ata_xfer_mode2shift(unsigned long xfer_mode)
978 {
979         const struct ata_xfer_ent *ent;
980
981         for (ent = ata_xfer_tbl; ent->shift >= 0; ent++)
982                 if (xfer_mode >= ent->base && xfer_mode < ent->base + ent->bits)
983                         return ent->shift;
984         return -1;
985 }
986
987 /**
988  *      ata_mode_string - convert xfer_mask to string
989  *      @xfer_mask: mask of bits supported; only highest bit counts.
990  *
991  *      Determine string which represents the highest speed
992  *      (highest bit in @modemask).
993  *
994  *      LOCKING:
995  *      None.
996  *
997  *      RETURNS:
998  *      Constant C string representing highest speed listed in
999  *      @mode_mask, or the constant C string "<n/a>".
1000  */
1001 const char *ata_mode_string(unsigned long xfer_mask)
1002 {
1003         static const char * const xfer_mode_str[] = {
1004                 "PIO0",
1005                 "PIO1",
1006                 "PIO2",
1007                 "PIO3",
1008                 "PIO4",
1009                 "PIO5",
1010                 "PIO6",
1011                 "MWDMA0",
1012                 "MWDMA1",
1013                 "MWDMA2",
1014                 "MWDMA3",
1015                 "MWDMA4",
1016                 "UDMA/16",
1017                 "UDMA/25",
1018                 "UDMA/33",
1019                 "UDMA/44",
1020                 "UDMA/66",
1021                 "UDMA/100",
1022                 "UDMA/133",
1023                 "UDMA7",
1024         };
1025         int highbit;
1026
1027         highbit = fls(xfer_mask) - 1;
1028         if (highbit >= 0 && highbit < ARRAY_SIZE(xfer_mode_str))
1029                 return xfer_mode_str[highbit];
1030         return "<n/a>";
1031 }
1032
1033 const char *sata_spd_string(unsigned int spd)
1034 {
1035         static const char * const spd_str[] = {
1036                 "1.5 Gbps",
1037                 "3.0 Gbps",
1038                 "6.0 Gbps",
1039         };
1040
1041         if (spd == 0 || (spd - 1) >= ARRAY_SIZE(spd_str))
1042                 return "<unknown>";
1043         return spd_str[spd - 1];
1044 }
1045
1046 /**
1047  *      ata_dev_classify - determine device type based on ATA-spec signature
1048  *      @tf: ATA taskfile register set for device to be identified
1049  *
1050  *      Determine from taskfile register contents whether a device is
1051  *      ATA or ATAPI, as per "Signature and persistence" section
1052  *      of ATA/PI spec (volume 1, sect 5.14).
1053  *
1054  *      LOCKING:
1055  *      None.
1056  *
1057  *      RETURNS:
1058  *      Device type, %ATA_DEV_ATA, %ATA_DEV_ATAPI, %ATA_DEV_PMP,
1059  *      %ATA_DEV_ZAC, or %ATA_DEV_UNKNOWN the event of failure.
1060  */
1061 unsigned int ata_dev_classify(const struct ata_taskfile *tf)
1062 {
1063         /* Apple's open source Darwin code hints that some devices only
1064          * put a proper signature into the LBA mid/high registers,
1065          * So, we only check those.  It's sufficient for uniqueness.
1066          *
1067          * ATA/ATAPI-7 (d1532v1r1: Feb. 19, 2003) specified separate
1068          * signatures for ATA and ATAPI devices attached on SerialATA,
1069          * 0x3c/0xc3 and 0x69/0x96 respectively.  However, SerialATA
1070          * spec has never mentioned about using different signatures
1071          * for ATA/ATAPI devices.  Then, Serial ATA II: Port
1072          * Multiplier specification began to use 0x69/0x96 to identify
1073          * port multpliers and 0x3c/0xc3 to identify SEMB device.
1074          * ATA/ATAPI-7 dropped descriptions about 0x3c/0xc3 and
1075          * 0x69/0x96 shortly and described them as reserved for
1076          * SerialATA.
1077          *
1078          * We follow the current spec and consider that 0x69/0x96
1079          * identifies a port multiplier and 0x3c/0xc3 a SEMB device.
1080          * Unfortunately, WDC WD1600JS-62MHB5 (a hard drive) reports
1081          * SEMB signature.  This is worked around in
1082          * ata_dev_read_id().
1083          */
1084         if ((tf->lbam == 0) && (tf->lbah == 0)) {
1085                 DPRINTK("found ATA device by sig\n");
1086                 return ATA_DEV_ATA;
1087         }
1088
1089         if ((tf->lbam == 0x14) && (tf->lbah == 0xeb)) {
1090                 DPRINTK("found ATAPI device by sig\n");
1091                 return ATA_DEV_ATAPI;
1092         }
1093
1094         if ((tf->lbam == 0x69) && (tf->lbah == 0x96)) {
1095                 DPRINTK("found PMP device by sig\n");
1096                 return ATA_DEV_PMP;
1097         }
1098
1099         if ((tf->lbam == 0x3c) && (tf->lbah == 0xc3)) {
1100                 DPRINTK("found SEMB device by sig (could be ATA device)\n");
1101                 return ATA_DEV_SEMB;
1102         }
1103
1104         if ((tf->lbam == 0xcd) && (tf->lbah == 0xab)) {
1105                 DPRINTK("found ZAC device by sig\n");
1106                 return ATA_DEV_ZAC;
1107         }
1108
1109         DPRINTK("unknown device\n");
1110         return ATA_DEV_UNKNOWN;
1111 }
1112
1113 /**
1114  *      ata_id_string - Convert IDENTIFY DEVICE page into string
1115  *      @id: IDENTIFY DEVICE results we will examine
1116  *      @s: string into which data is output
1117  *      @ofs: offset into identify device page
1118  *      @len: length of string to return. must be an even number.
1119  *
1120  *      The strings in the IDENTIFY DEVICE page are broken up into
1121  *      16-bit chunks.  Run through the string, and output each
1122  *      8-bit chunk linearly, regardless of platform.
1123  *
1124  *      LOCKING:
1125  *      caller.
1126  */
1127
1128 void ata_id_string(const u16 *id, unsigned char *s,
1129                    unsigned int ofs, unsigned int len)
1130 {
1131         unsigned int c;
1132
1133         BUG_ON(len & 1);
1134
1135         while (len > 0) {
1136                 c = id[ofs] >> 8;
1137                 *s = c;
1138                 s++;
1139
1140                 c = id[ofs] & 0xff;
1141                 *s = c;
1142                 s++;
1143
1144                 ofs++;
1145                 len -= 2;
1146         }
1147 }
1148
1149 /**
1150  *      ata_id_c_string - Convert IDENTIFY DEVICE page into C string
1151  *      @id: IDENTIFY DEVICE results we will examine
1152  *      @s: string into which data is output
1153  *      @ofs: offset into identify device page
1154  *      @len: length of string to return. must be an odd number.
1155  *
1156  *      This function is identical to ata_id_string except that it
1157  *      trims trailing spaces and terminates the resulting string with
1158  *      null.  @len must be actual maximum length (even number) + 1.
1159  *
1160  *      LOCKING:
1161  *      caller.
1162  */
1163 void ata_id_c_string(const u16 *id, unsigned char *s,
1164                      unsigned int ofs, unsigned int len)
1165 {
1166         unsigned char *p;
1167
1168         ata_id_string(id, s, ofs, len - 1);
1169
1170         p = s + strnlen(s, len - 1);
1171         while (p > s && p[-1] == ' ')
1172                 p--;
1173         *p = '\0';
1174 }
1175
1176 static u64 ata_id_n_sectors(const u16 *id)
1177 {
1178         if (ata_id_has_lba(id)) {
1179                 if (ata_id_has_lba48(id))
1180                         return ata_id_u64(id, ATA_ID_LBA_CAPACITY_2);
1181                 else
1182                         return ata_id_u32(id, ATA_ID_LBA_CAPACITY);
1183         } else {
1184                 if (ata_id_current_chs_valid(id))
1185                         return id[ATA_ID_CUR_CYLS] * id[ATA_ID_CUR_HEADS] *
1186                                id[ATA_ID_CUR_SECTORS];
1187                 else
1188                         return id[ATA_ID_CYLS] * id[ATA_ID_HEADS] *
1189                                id[ATA_ID_SECTORS];
1190         }
1191 }
1192
1193 u64 ata_tf_to_lba48(const struct ata_taskfile *tf)
1194 {
1195         u64 sectors = 0;
1196
1197         sectors |= ((u64)(tf->hob_lbah & 0xff)) << 40;
1198         sectors |= ((u64)(tf->hob_lbam & 0xff)) << 32;
1199         sectors |= ((u64)(tf->hob_lbal & 0xff)) << 24;
1200         sectors |= (tf->lbah & 0xff) << 16;
1201         sectors |= (tf->lbam & 0xff) << 8;
1202         sectors |= (tf->lbal & 0xff);
1203
1204         return sectors;
1205 }
1206
1207 u64 ata_tf_to_lba(const struct ata_taskfile *tf)
1208 {
1209         u64 sectors = 0;
1210
1211         sectors |= (tf->device & 0x0f) << 24;
1212         sectors |= (tf->lbah & 0xff) << 16;
1213         sectors |= (tf->lbam & 0xff) << 8;
1214         sectors |= (tf->lbal & 0xff);
1215
1216         return sectors;
1217 }
1218
1219 /**
1220  *      ata_read_native_max_address - Read native max address
1221  *      @dev: target device
1222  *      @max_sectors: out parameter for the result native max address
1223  *
1224  *      Perform an LBA48 or LBA28 native size query upon the device in
1225  *      question.
1226  *
1227  *      RETURNS:
1228  *      0 on success, -EACCES if command is aborted by the drive.
1229  *      -EIO on other errors.
1230  */
1231 static int ata_read_native_max_address(struct ata_device *dev, u64 *max_sectors)
1232 {
1233         unsigned int err_mask;
1234         struct ata_taskfile tf;
1235         int lba48 = ata_id_has_lba48(dev->id);
1236
1237         ata_tf_init(dev, &tf);
1238
1239         /* always clear all address registers */
1240         tf.flags |= ATA_TFLAG_DEVICE | ATA_TFLAG_ISADDR;
1241
1242         if (lba48) {
1243                 tf.command = ATA_CMD_READ_NATIVE_MAX_EXT;
1244                 tf.flags |= ATA_TFLAG_LBA48;
1245         } else
1246                 tf.command = ATA_CMD_READ_NATIVE_MAX;
1247
1248         tf.protocol = ATA_PROT_NODATA;
1249         tf.device |= ATA_LBA;
1250
1251         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
1252         if (err_mask) {
1253                 ata_dev_warn(dev,
1254                              "failed to read native max address (err_mask=0x%x)\n",
1255                              err_mask);
1256                 if (err_mask == AC_ERR_DEV && (tf.feature & ATA_ABORTED))
1257                         return -EACCES;
1258                 return -EIO;
1259         }
1260
1261         if (lba48)
1262                 *max_sectors = ata_tf_to_lba48(&tf) + 1;
1263         else
1264                 *max_sectors = ata_tf_to_lba(&tf) + 1;
1265         if (dev->horkage & ATA_HORKAGE_HPA_SIZE)
1266                 (*max_sectors)--;
1267         return 0;
1268 }
1269
1270 /**
1271  *      ata_set_max_sectors - Set max sectors
1272  *      @dev: target device
1273  *      @new_sectors: new max sectors value to set for the device
1274  *
1275  *      Set max sectors of @dev to @new_sectors.
1276  *
1277  *      RETURNS:
1278  *      0 on success, -EACCES if command is aborted or denied (due to
1279  *      previous non-volatile SET_MAX) by the drive.  -EIO on other
1280  *      errors.
1281  */
1282 static int ata_set_max_sectors(struct ata_device *dev, u64 new_sectors)
1283 {
1284         unsigned int err_mask;
1285         struct ata_taskfile tf;
1286         int lba48 = ata_id_has_lba48(dev->id);
1287
1288         new_sectors--;
1289
1290         ata_tf_init(dev, &tf);
1291
1292         tf.flags |= ATA_TFLAG_DEVICE | ATA_TFLAG_ISADDR;
1293
1294         if (lba48) {
1295                 tf.command = ATA_CMD_SET_MAX_EXT;
1296                 tf.flags |= ATA_TFLAG_LBA48;
1297
1298                 tf.hob_lbal = (new_sectors >> 24) & 0xff;
1299                 tf.hob_lbam = (new_sectors >> 32) & 0xff;
1300                 tf.hob_lbah = (new_sectors >> 40) & 0xff;
1301         } else {
1302                 tf.command = ATA_CMD_SET_MAX;
1303
1304                 tf.device |= (new_sectors >> 24) & 0xf;
1305         }
1306
1307         tf.protocol = ATA_PROT_NODATA;
1308         tf.device |= ATA_LBA;
1309
1310         tf.lbal = (new_sectors >> 0) & 0xff;
1311         tf.lbam = (new_sectors >> 8) & 0xff;
1312         tf.lbah = (new_sectors >> 16) & 0xff;
1313
1314         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
1315         if (err_mask) {
1316                 ata_dev_warn(dev,
1317                              "failed to set max address (err_mask=0x%x)\n",
1318                              err_mask);
1319                 if (err_mask == AC_ERR_DEV &&
1320                     (tf.feature & (ATA_ABORTED | ATA_IDNF)))
1321                         return -EACCES;
1322                 return -EIO;
1323         }
1324
1325         return 0;
1326 }
1327
1328 /**
1329  *      ata_hpa_resize          -       Resize a device with an HPA set
1330  *      @dev: Device to resize
1331  *
1332  *      Read the size of an LBA28 or LBA48 disk with HPA features and resize
1333  *      it if required to the full size of the media. The caller must check
1334  *      the drive has the HPA feature set enabled.
1335  *
1336  *      RETURNS:
1337  *      0 on success, -errno on failure.
1338  */
1339 static int ata_hpa_resize(struct ata_device *dev)
1340 {
1341         struct ata_eh_context *ehc = &dev->link->eh_context;
1342         int print_info = ehc->i.flags & ATA_EHI_PRINTINFO;
1343         bool unlock_hpa = ata_ignore_hpa || dev->flags & ATA_DFLAG_UNLOCK_HPA;
1344         u64 sectors = ata_id_n_sectors(dev->id);
1345         u64 native_sectors;
1346         int rc;
1347
1348         /* do we need to do it? */
1349         if ((dev->class != ATA_DEV_ATA && dev->class != ATA_DEV_ZAC) ||
1350             !ata_id_has_lba(dev->id) || !ata_id_hpa_enabled(dev->id) ||
1351             (dev->horkage & ATA_HORKAGE_BROKEN_HPA))
1352                 return 0;
1353
1354         /* read native max address */
1355         rc = ata_read_native_max_address(dev, &native_sectors);
1356         if (rc) {
1357                 /* If device aborted the command or HPA isn't going to
1358                  * be unlocked, skip HPA resizing.
1359                  */
1360                 if (rc == -EACCES || !unlock_hpa) {
1361                         ata_dev_warn(dev,
1362                                      "HPA support seems broken, skipping HPA handling\n");
1363                         dev->horkage |= ATA_HORKAGE_BROKEN_HPA;
1364
1365                         /* we can continue if device aborted the command */
1366                         if (rc == -EACCES)
1367                                 rc = 0;
1368                 }
1369
1370                 return rc;
1371         }
1372         dev->n_native_sectors = native_sectors;
1373
1374         /* nothing to do? */
1375         if (native_sectors <= sectors || !unlock_hpa) {
1376                 if (!print_info || native_sectors == sectors)
1377                         return 0;
1378
1379                 if (native_sectors > sectors)
1380                         ata_dev_info(dev,
1381                                 "HPA detected: current %llu, native %llu\n",
1382                                 (unsigned long long)sectors,
1383                                 (unsigned long long)native_sectors);
1384                 else if (native_sectors < sectors)
1385                         ata_dev_warn(dev,
1386                                 "native sectors (%llu) is smaller than sectors (%llu)\n",
1387                                 (unsigned long long)native_sectors,
1388                                 (unsigned long long)sectors);
1389                 return 0;
1390         }
1391
1392         /* let's unlock HPA */
1393         rc = ata_set_max_sectors(dev, native_sectors);
1394         if (rc == -EACCES) {
1395                 /* if device aborted the command, skip HPA resizing */
1396                 ata_dev_warn(dev,
1397                              "device aborted resize (%llu -> %llu), skipping HPA handling\n",
1398                              (unsigned long long)sectors,
1399                              (unsigned long long)native_sectors);
1400                 dev->horkage |= ATA_HORKAGE_BROKEN_HPA;
1401                 return 0;
1402         } else if (rc)
1403                 return rc;
1404
1405         /* re-read IDENTIFY data */
1406         rc = ata_dev_reread_id(dev, 0);
1407         if (rc) {
1408                 ata_dev_err(dev,
1409                             "failed to re-read IDENTIFY data after HPA resizing\n");
1410                 return rc;
1411         }
1412
1413         if (print_info) {
1414                 u64 new_sectors = ata_id_n_sectors(dev->id);
1415                 ata_dev_info(dev,
1416                         "HPA unlocked: %llu -> %llu, native %llu\n",
1417                         (unsigned long long)sectors,
1418                         (unsigned long long)new_sectors,
1419                         (unsigned long long)native_sectors);
1420         }
1421
1422         return 0;
1423 }
1424
1425 /**
1426  *      ata_dump_id - IDENTIFY DEVICE info debugging output
1427  *      @id: IDENTIFY DEVICE page to dump
1428  *
1429  *      Dump selected 16-bit words from the given IDENTIFY DEVICE
1430  *      page.
1431  *
1432  *      LOCKING:
1433  *      caller.
1434  */
1435
1436 static inline void ata_dump_id(const u16 *id)
1437 {
1438         DPRINTK("49==0x%04x  "
1439                 "53==0x%04x  "
1440                 "63==0x%04x  "
1441                 "64==0x%04x  "
1442                 "75==0x%04x  \n",
1443                 id[49],
1444                 id[53],
1445                 id[63],
1446                 id[64],
1447                 id[75]);
1448         DPRINTK("80==0x%04x  "
1449                 "81==0x%04x  "
1450                 "82==0x%04x  "
1451                 "83==0x%04x  "
1452                 "84==0x%04x  \n",
1453                 id[80],
1454                 id[81],
1455                 id[82],
1456                 id[83],
1457                 id[84]);
1458         DPRINTK("88==0x%04x  "
1459                 "93==0x%04x\n",
1460                 id[88],
1461                 id[93]);
1462 }
1463
1464 /**
1465  *      ata_id_xfermask - Compute xfermask from the given IDENTIFY data
1466  *      @id: IDENTIFY data to compute xfer mask from
1467  *
1468  *      Compute the xfermask for this device. This is not as trivial
1469  *      as it seems if we must consider early devices correctly.
1470  *
1471  *      FIXME: pre IDE drive timing (do we care ?).
1472  *
1473  *      LOCKING:
1474  *      None.
1475  *
1476  *      RETURNS:
1477  *      Computed xfermask
1478  */
1479 unsigned long ata_id_xfermask(const u16 *id)
1480 {
1481         unsigned long pio_mask, mwdma_mask, udma_mask;
1482
1483         /* Usual case. Word 53 indicates word 64 is valid */
1484         if (id[ATA_ID_FIELD_VALID] & (1 << 1)) {
1485                 pio_mask = id[ATA_ID_PIO_MODES] & 0x03;
1486                 pio_mask <<= 3;
1487                 pio_mask |= 0x7;
1488         } else {
1489                 /* If word 64 isn't valid then Word 51 high byte holds
1490                  * the PIO timing number for the maximum. Turn it into
1491                  * a mask.
1492                  */
1493                 u8 mode = (id[ATA_ID_OLD_PIO_MODES] >> 8) & 0xFF;
1494                 if (mode < 5)   /* Valid PIO range */
1495                         pio_mask = (2 << mode) - 1;
1496                 else
1497                         pio_mask = 1;
1498
1499                 /* But wait.. there's more. Design your standards by
1500                  * committee and you too can get a free iordy field to
1501                  * process. However its the speeds not the modes that
1502                  * are supported... Note drivers using the timing API
1503                  * will get this right anyway
1504                  */
1505         }
1506
1507         mwdma_mask = id[ATA_ID_MWDMA_MODES] & 0x07;
1508
1509         if (ata_id_is_cfa(id)) {
1510                 /*
1511                  *      Process compact flash extended modes
1512                  */
1513                 int pio = (id[ATA_ID_CFA_MODES] >> 0) & 0x7;
1514                 int dma = (id[ATA_ID_CFA_MODES] >> 3) & 0x7;
1515
1516                 if (pio)
1517                         pio_mask |= (1 << 5);
1518                 if (pio > 1)
1519                         pio_mask |= (1 << 6);
1520                 if (dma)
1521                         mwdma_mask |= (1 << 3);
1522                 if (dma > 1)
1523                         mwdma_mask |= (1 << 4);
1524         }
1525
1526         udma_mask = 0;
1527         if (id[ATA_ID_FIELD_VALID] & (1 << 2))
1528                 udma_mask = id[ATA_ID_UDMA_MODES] & 0xff;
1529
1530         return ata_pack_xfermask(pio_mask, mwdma_mask, udma_mask);
1531 }
1532
1533 static void ata_qc_complete_internal(struct ata_queued_cmd *qc)
1534 {
1535         struct completion *waiting = qc->private_data;
1536
1537         complete(waiting);
1538 }
1539
1540 /**
1541  *      ata_exec_internal_sg - execute libata internal command
1542  *      @dev: Device to which the command is sent
1543  *      @tf: Taskfile registers for the command and the result
1544  *      @cdb: CDB for packet command
1545  *      @dma_dir: Data transfer direction of the command
1546  *      @sgl: sg list for the data buffer of the command
1547  *      @n_elem: Number of sg entries
1548  *      @timeout: Timeout in msecs (0 for default)
1549  *
1550  *      Executes libata internal command with timeout.  @tf contains
1551  *      command on entry and result on return.  Timeout and error
1552  *      conditions are reported via return value.  No recovery action
1553  *      is taken after a command times out.  It's caller's duty to
1554  *      clean up after timeout.
1555  *
1556  *      LOCKING:
1557  *      None.  Should be called with kernel context, might sleep.
1558  *
1559  *      RETURNS:
1560  *      Zero on success, AC_ERR_* mask on failure
1561  */
1562 unsigned ata_exec_internal_sg(struct ata_device *dev,
1563                               struct ata_taskfile *tf, const u8 *cdb,
1564                               int dma_dir, struct scatterlist *sgl,
1565                               unsigned int n_elem, unsigned long timeout)
1566 {
1567         struct ata_link *link = dev->link;
1568         struct ata_port *ap = link->ap;
1569         u8 command = tf->command;
1570         int auto_timeout = 0;
1571         struct ata_queued_cmd *qc;
1572         unsigned int tag, preempted_tag;
1573         u32 preempted_sactive, preempted_qc_active;
1574         int preempted_nr_active_links;
1575         DECLARE_COMPLETION_ONSTACK(wait);
1576         unsigned long flags;
1577         unsigned int err_mask;
1578         int rc;
1579
1580         spin_lock_irqsave(ap->lock, flags);
1581
1582         /* no internal command while frozen */
1583         if (ap->pflags & ATA_PFLAG_FROZEN) {
1584                 spin_unlock_irqrestore(ap->lock, flags);
1585                 return AC_ERR_SYSTEM;
1586         }
1587
1588         /* initialize internal qc */
1589
1590         /* XXX: Tag 0 is used for drivers with legacy EH as some
1591          * drivers choke if any other tag is given.  This breaks
1592          * ata_tag_internal() test for those drivers.  Don't use new
1593          * EH stuff without converting to it.
1594          */
1595         if (ap->ops->error_handler)
1596                 tag = ATA_TAG_INTERNAL;
1597         else
1598                 tag = 0;
1599
1600         qc = __ata_qc_from_tag(ap, tag);
1601
1602         qc->tag = tag;
1603         qc->scsicmd = NULL;
1604         qc->ap = ap;
1605         qc->dev = dev;
1606         ata_qc_reinit(qc);
1607
1608         preempted_tag = link->active_tag;
1609         preempted_sactive = link->sactive;
1610         preempted_qc_active = ap->qc_active;
1611         preempted_nr_active_links = ap->nr_active_links;
1612         link->active_tag = ATA_TAG_POISON;
1613         link->sactive = 0;
1614         ap->qc_active = 0;
1615         ap->nr_active_links = 0;
1616
1617         /* prepare & issue qc */
1618         qc->tf = *tf;
1619         if (cdb)
1620                 memcpy(qc->cdb, cdb, ATAPI_CDB_LEN);
1621
1622         /* some SATA bridges need us to indicate data xfer direction */
1623         if (tf->protocol == ATAPI_PROT_DMA && (dev->flags & ATA_DFLAG_DMADIR) &&
1624             dma_dir == DMA_FROM_DEVICE)
1625                 qc->tf.feature |= ATAPI_DMADIR;
1626
1627         qc->flags |= ATA_QCFLAG_RESULT_TF;
1628         qc->dma_dir = dma_dir;
1629         if (dma_dir != DMA_NONE) {
1630                 unsigned int i, buflen = 0;
1631                 struct scatterlist *sg;
1632
1633                 for_each_sg(sgl, sg, n_elem, i)
1634                         buflen += sg->length;
1635
1636                 ata_sg_init(qc, sgl, n_elem);
1637                 qc->nbytes = buflen;
1638         }
1639
1640         qc->private_data = &wait;
1641         qc->complete_fn = ata_qc_complete_internal;
1642
1643         ata_qc_issue(qc);
1644
1645         spin_unlock_irqrestore(ap->lock, flags);
1646
1647         if (!timeout) {
1648                 if (ata_probe_timeout)
1649                         timeout = ata_probe_timeout * 1000;
1650                 else {
1651                         timeout = ata_internal_cmd_timeout(dev, command);
1652                         auto_timeout = 1;
1653                 }
1654         }
1655
1656         if (ap->ops->error_handler)
1657                 ata_eh_release(ap);
1658
1659         rc = wait_for_completion_timeout(&wait, msecs_to_jiffies(timeout));
1660
1661         if (ap->ops->error_handler)
1662                 ata_eh_acquire(ap);
1663
1664         ata_sff_flush_pio_task(ap);
1665
1666         if (!rc) {
1667                 spin_lock_irqsave(ap->lock, flags);
1668
1669                 /* We're racing with irq here.  If we lose, the
1670                  * following test prevents us from completing the qc
1671                  * twice.  If we win, the port is frozen and will be
1672                  * cleaned up by ->post_internal_cmd().
1673                  */
1674                 if (qc->flags & ATA_QCFLAG_ACTIVE) {
1675                         qc->err_mask |= AC_ERR_TIMEOUT;
1676
1677                         if (ap->ops->error_handler)
1678                                 ata_port_freeze(ap);
1679                         else
1680                                 ata_qc_complete(qc);
1681
1682                         if (ata_msg_warn(ap))
1683                                 ata_dev_warn(dev, "qc timeout (cmd 0x%x)\n",
1684                                              command);
1685                 }
1686
1687                 spin_unlock_irqrestore(ap->lock, flags);
1688         }
1689
1690         /* do post_internal_cmd */
1691         if (ap->ops->post_internal_cmd)
1692                 ap->ops->post_internal_cmd(qc);
1693
1694         /* perform minimal error analysis */
1695         if (qc->flags & ATA_QCFLAG_FAILED) {
1696                 if (qc->result_tf.command & (ATA_ERR | ATA_DF))
1697                         qc->err_mask |= AC_ERR_DEV;
1698
1699                 if (!qc->err_mask)
1700                         qc->err_mask |= AC_ERR_OTHER;
1701
1702                 if (qc->err_mask & ~AC_ERR_OTHER)
1703                         qc->err_mask &= ~AC_ERR_OTHER;
1704         } else if (qc->tf.command == ATA_CMD_REQ_SENSE_DATA) {
1705                 qc->result_tf.command |= ATA_SENSE;
1706         }
1707
1708         /* finish up */
1709         spin_lock_irqsave(ap->lock, flags);
1710
1711         *tf = qc->result_tf;
1712         err_mask = qc->err_mask;
1713
1714         ata_qc_free(qc);
1715         link->active_tag = preempted_tag;
1716         link->sactive = preempted_sactive;
1717         ap->qc_active = preempted_qc_active;
1718         ap->nr_active_links = preempted_nr_active_links;
1719
1720         spin_unlock_irqrestore(ap->lock, flags);
1721
1722         if ((err_mask & AC_ERR_TIMEOUT) && auto_timeout)
1723                 ata_internal_cmd_timed_out(dev, command);
1724
1725         return err_mask;
1726 }
1727
1728 /**
1729  *      ata_exec_internal - execute libata internal command
1730  *      @dev: Device to which the command is sent
1731  *      @tf: Taskfile registers for the command and the result
1732  *      @cdb: CDB for packet command
1733  *      @dma_dir: Data transfer direction of the command
1734  *      @buf: Data buffer of the command
1735  *      @buflen: Length of data buffer
1736  *      @timeout: Timeout in msecs (0 for default)
1737  *
1738  *      Wrapper around ata_exec_internal_sg() which takes simple
1739  *      buffer instead of sg list.
1740  *
1741  *      LOCKING:
1742  *      None.  Should be called with kernel context, might sleep.
1743  *
1744  *      RETURNS:
1745  *      Zero on success, AC_ERR_* mask on failure
1746  */
1747 unsigned ata_exec_internal(struct ata_device *dev,
1748                            struct ata_taskfile *tf, const u8 *cdb,
1749                            int dma_dir, void *buf, unsigned int buflen,
1750                            unsigned long timeout)
1751 {
1752         struct scatterlist *psg = NULL, sg;
1753         unsigned int n_elem = 0;
1754
1755         if (dma_dir != DMA_NONE) {
1756                 WARN_ON(!buf);
1757                 sg_init_one(&sg, buf, buflen);
1758                 psg = &sg;
1759                 n_elem++;
1760         }
1761
1762         return ata_exec_internal_sg(dev, tf, cdb, dma_dir, psg, n_elem,
1763                                     timeout);
1764 }
1765
1766 /**
1767  *      ata_pio_need_iordy      -       check if iordy needed
1768  *      @adev: ATA device
1769  *
1770  *      Check if the current speed of the device requires IORDY. Used
1771  *      by various controllers for chip configuration.
1772  */
1773 unsigned int ata_pio_need_iordy(const struct ata_device *adev)
1774 {
1775         /* Don't set IORDY if we're preparing for reset.  IORDY may
1776          * lead to controller lock up on certain controllers if the
1777          * port is not occupied.  See bko#11703 for details.
1778          */
1779         if (adev->link->ap->pflags & ATA_PFLAG_RESETTING)
1780                 return 0;
1781         /* Controller doesn't support IORDY.  Probably a pointless
1782          * check as the caller should know this.
1783          */
1784         if (adev->link->ap->flags & ATA_FLAG_NO_IORDY)
1785                 return 0;
1786         /* CF spec. r4.1 Table 22 says no iordy on PIO5 and PIO6.  */
1787         if (ata_id_is_cfa(adev->id)
1788             && (adev->pio_mode == XFER_PIO_5 || adev->pio_mode == XFER_PIO_6))
1789                 return 0;
1790         /* PIO3 and higher it is mandatory */
1791         if (adev->pio_mode > XFER_PIO_2)
1792                 return 1;
1793         /* We turn it on when possible */
1794         if (ata_id_has_iordy(adev->id))
1795                 return 1;
1796         return 0;
1797 }
1798
1799 /**
1800  *      ata_pio_mask_no_iordy   -       Return the non IORDY mask
1801  *      @adev: ATA device
1802  *
1803  *      Compute the highest mode possible if we are not using iordy. Return
1804  *      -1 if no iordy mode is available.
1805  */
1806 static u32 ata_pio_mask_no_iordy(const struct ata_device *adev)
1807 {
1808         /* If we have no drive specific rule, then PIO 2 is non IORDY */
1809         if (adev->id[ATA_ID_FIELD_VALID] & 2) { /* EIDE */
1810                 u16 pio = adev->id[ATA_ID_EIDE_PIO];
1811                 /* Is the speed faster than the drive allows non IORDY ? */
1812                 if (pio) {
1813                         /* This is cycle times not frequency - watch the logic! */
1814                         if (pio > 240)  /* PIO2 is 240nS per cycle */
1815                                 return 3 << ATA_SHIFT_PIO;
1816                         return 7 << ATA_SHIFT_PIO;
1817                 }
1818         }
1819         return 3 << ATA_SHIFT_PIO;
1820 }
1821
1822 /**
1823  *      ata_do_dev_read_id              -       default ID read method
1824  *      @dev: device
1825  *      @tf: proposed taskfile
1826  *      @id: data buffer
1827  *
1828  *      Issue the identify taskfile and hand back the buffer containing
1829  *      identify data. For some RAID controllers and for pre ATA devices
1830  *      this function is wrapped or replaced by the driver
1831  */
1832 unsigned int ata_do_dev_read_id(struct ata_device *dev,
1833                                         struct ata_taskfile *tf, u16 *id)
1834 {
1835         return ata_exec_internal(dev, tf, NULL, DMA_FROM_DEVICE,
1836                                      id, sizeof(id[0]) * ATA_ID_WORDS, 0);
1837 }
1838
1839 /**
1840  *      ata_dev_read_id - Read ID data from the specified device
1841  *      @dev: target device
1842  *      @p_class: pointer to class of the target device (may be changed)
1843  *      @flags: ATA_READID_* flags
1844  *      @id: buffer to read IDENTIFY data into
1845  *
1846  *      Read ID data from the specified device.  ATA_CMD_ID_ATA is
1847  *      performed on ATA devices and ATA_CMD_ID_ATAPI on ATAPI
1848  *      devices.  This function also issues ATA_CMD_INIT_DEV_PARAMS
1849  *      for pre-ATA4 drives.
1850  *
1851  *      FIXME: ATA_CMD_ID_ATA is optional for early drives and right
1852  *      now we abort if we hit that case.
1853  *
1854  *      LOCKING:
1855  *      Kernel thread context (may sleep)
1856  *
1857  *      RETURNS:
1858  *      0 on success, -errno otherwise.
1859  */
1860 int ata_dev_read_id(struct ata_device *dev, unsigned int *p_class,
1861                     unsigned int flags, u16 *id)
1862 {
1863         struct ata_port *ap = dev->link->ap;
1864         unsigned int class = *p_class;
1865         struct ata_taskfile tf;
1866         unsigned int err_mask = 0;
1867         const char *reason;
1868         bool is_semb = class == ATA_DEV_SEMB;
1869         int may_fallback = 1, tried_spinup = 0;
1870         int rc;
1871
1872         if (ata_msg_ctl(ap))
1873                 ata_dev_dbg(dev, "%s: ENTER\n", __func__);
1874
1875 retry:
1876         ata_tf_init(dev, &tf);
1877
1878         switch (class) {
1879         case ATA_DEV_SEMB:
1880                 class = ATA_DEV_ATA;    /* some hard drives report SEMB sig */
1881         case ATA_DEV_ATA:
1882         case ATA_DEV_ZAC:
1883                 tf.command = ATA_CMD_ID_ATA;
1884                 break;
1885         case ATA_DEV_ATAPI:
1886                 tf.command = ATA_CMD_ID_ATAPI;
1887                 break;
1888         default:
1889                 rc = -ENODEV;
1890                 reason = "unsupported class";
1891                 goto err_out;
1892         }
1893
1894         tf.protocol = ATA_PROT_PIO;
1895
1896         /* Some devices choke if TF registers contain garbage.  Make
1897          * sure those are properly initialized.
1898          */
1899         tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
1900
1901         /* Device presence detection is unreliable on some
1902          * controllers.  Always poll IDENTIFY if available.
1903          */
1904         tf.flags |= ATA_TFLAG_POLLING;
1905
1906         if (ap->ops->read_id)
1907                 err_mask = ap->ops->read_id(dev, &tf, id);
1908         else
1909                 err_mask = ata_do_dev_read_id(dev, &tf, id);
1910
1911         if (err_mask) {
1912                 if (err_mask & AC_ERR_NODEV_HINT) {
1913                         ata_dev_dbg(dev, "NODEV after polling detection\n");
1914                         return -ENOENT;
1915                 }
1916
1917                 if (is_semb) {
1918                         ata_dev_info(dev,
1919                      "IDENTIFY failed on device w/ SEMB sig, disabled\n");
1920                         /* SEMB is not supported yet */
1921                         *p_class = ATA_DEV_SEMB_UNSUP;
1922                         return 0;
1923                 }
1924
1925                 if ((err_mask == AC_ERR_DEV) && (tf.feature & ATA_ABORTED)) {
1926                         /* Device or controller might have reported
1927                          * the wrong device class.  Give a shot at the
1928                          * other IDENTIFY if the current one is
1929                          * aborted by the device.
1930                          */
1931                         if (may_fallback) {
1932                                 may_fallback = 0;
1933
1934                                 if (class == ATA_DEV_ATA)
1935                                         class = ATA_DEV_ATAPI;
1936                                 else
1937                                         class = ATA_DEV_ATA;
1938                                 goto retry;
1939                         }
1940
1941                         /* Control reaches here iff the device aborted
1942                          * both flavors of IDENTIFYs which happens
1943                          * sometimes with phantom devices.
1944                          */
1945                         ata_dev_dbg(dev,
1946                                     "both IDENTIFYs aborted, assuming NODEV\n");
1947                         return -ENOENT;
1948                 }
1949
1950                 rc = -EIO;
1951                 reason = "I/O error";
1952                 goto err_out;
1953         }
1954
1955         if (dev->horkage & ATA_HORKAGE_DUMP_ID) {
1956                 ata_dev_dbg(dev, "dumping IDENTIFY data, "
1957                             "class=%d may_fallback=%d tried_spinup=%d\n",
1958                             class, may_fallback, tried_spinup);
1959                 print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET,
1960                                16, 2, id, ATA_ID_WORDS * sizeof(*id), true);
1961         }
1962
1963         /* Falling back doesn't make sense if ID data was read
1964          * successfully at least once.
1965          */
1966         may_fallback = 0;
1967
1968         swap_buf_le16(id, ATA_ID_WORDS);
1969
1970         /* sanity check */
1971         rc = -EINVAL;
1972         reason = "device reports invalid type";
1973
1974         if (class == ATA_DEV_ATA || class == ATA_DEV_ZAC) {
1975                 if (!ata_id_is_ata(id) && !ata_id_is_cfa(id))
1976                         goto err_out;
1977                 if (ap->host->flags & ATA_HOST_IGNORE_ATA &&
1978                                                         ata_id_is_ata(id)) {
1979                         ata_dev_dbg(dev,
1980                                 "host indicates ignore ATA devices, ignored\n");
1981                         return -ENOENT;
1982                 }
1983         } else {
1984                 if (ata_id_is_ata(id))
1985                         goto err_out;
1986         }
1987
1988         if (!tried_spinup && (id[2] == 0x37c8 || id[2] == 0x738c)) {
1989                 tried_spinup = 1;
1990                 /*
1991                  * Drive powered-up in standby mode, and requires a specific
1992                  * SET_FEATURES spin-up subcommand before it will accept
1993                  * anything other than the original IDENTIFY command.
1994                  */
1995                 err_mask = ata_dev_set_feature(dev, SETFEATURES_SPINUP, 0);
1996                 if (err_mask && id[2] != 0x738c) {
1997                         rc = -EIO;
1998                         reason = "SPINUP failed";
1999                         goto err_out;
2000                 }
2001                 /*
2002                  * If the drive initially returned incomplete IDENTIFY info,
2003                  * we now must reissue the IDENTIFY command.
2004                  */
2005                 if (id[2] == 0x37c8)
2006                         goto retry;
2007         }
2008
2009         if ((flags & ATA_READID_POSTRESET) &&
2010             (class == ATA_DEV_ATA || class == ATA_DEV_ZAC)) {
2011                 /*
2012                  * The exact sequence expected by certain pre-ATA4 drives is:
2013                  * SRST RESET
2014                  * IDENTIFY (optional in early ATA)
2015                  * INITIALIZE DEVICE PARAMETERS (later IDE and ATA)
2016                  * anything else..
2017                  * Some drives were very specific about that exact sequence.
2018                  *
2019                  * Note that ATA4 says lba is mandatory so the second check
2020                  * should never trigger.
2021                  */
2022                 if (ata_id_major_version(id) < 4 || !ata_id_has_lba(id)) {
2023                         err_mask = ata_dev_init_params(dev, id[3], id[6]);
2024                         if (err_mask) {
2025                                 rc = -EIO;
2026                                 reason = "INIT_DEV_PARAMS failed";
2027                                 goto err_out;
2028                         }
2029
2030                         /* current CHS translation info (id[53-58]) might be
2031                          * changed. reread the identify device info.
2032                          */
2033                         flags &= ~ATA_READID_POSTRESET;
2034                         goto retry;
2035                 }
2036         }
2037
2038         *p_class = class;
2039
2040         return 0;
2041
2042  err_out:
2043         if (ata_msg_warn(ap))
2044                 ata_dev_warn(dev, "failed to IDENTIFY (%s, err_mask=0x%x)\n",
2045                              reason, err_mask);
2046         return rc;
2047 }
2048
2049 /**
2050  *      ata_read_log_page - read a specific log page
2051  *      @dev: target device
2052  *      @log: log to read
2053  *      @page: page to read
2054  *      @buf: buffer to store read page
2055  *      @sectors: number of sectors to read
2056  *
2057  *      Read log page using READ_LOG_EXT command.
2058  *
2059  *      LOCKING:
2060  *      Kernel thread context (may sleep).
2061  *
2062  *      RETURNS:
2063  *      0 on success, AC_ERR_* mask otherwise.
2064  */
2065 unsigned int ata_read_log_page(struct ata_device *dev, u8 log,
2066                                u8 page, void *buf, unsigned int sectors)
2067 {
2068         unsigned long ap_flags = dev->link->ap->flags;
2069         struct ata_taskfile tf;
2070         unsigned int err_mask;
2071         bool dma = false;
2072
2073         DPRINTK("read log page - log 0x%x, page 0x%x\n", log, page);
2074
2075         /*
2076          * Return error without actually issuing the command on controllers
2077          * which e.g. lockup on a read log page.
2078          */
2079         if (ap_flags & ATA_FLAG_NO_LOG_PAGE)
2080                 return AC_ERR_DEV;
2081
2082 retry:
2083         ata_tf_init(dev, &tf);
2084         if (ata_dma_enabled(dev) && ata_id_has_read_log_dma_ext(dev->id) &&
2085             !(dev->horkage & ATA_HORKAGE_NO_DMA_LOG)) {
2086                 tf.command = ATA_CMD_READ_LOG_DMA_EXT;
2087                 tf.protocol = ATA_PROT_DMA;
2088                 dma = true;
2089         } else {
2090                 tf.command = ATA_CMD_READ_LOG_EXT;
2091                 tf.protocol = ATA_PROT_PIO;
2092                 dma = false;
2093         }
2094         tf.lbal = log;
2095         tf.lbam = page;
2096         tf.nsect = sectors;
2097         tf.hob_nsect = sectors >> 8;
2098         tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_LBA48 | ATA_TFLAG_DEVICE;
2099
2100         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_FROM_DEVICE,
2101                                      buf, sectors * ATA_SECT_SIZE, 0);
2102
2103         if (err_mask && dma) {
2104                 dev->horkage |= ATA_HORKAGE_NO_DMA_LOG;
2105                 ata_dev_warn(dev, "READ LOG DMA EXT failed, trying PIO\n");
2106                 goto retry;
2107         }
2108
2109         DPRINTK("EXIT, err_mask=%x\n", err_mask);
2110         return err_mask;
2111 }
2112
2113 static bool ata_log_supported(struct ata_device *dev, u8 log)
2114 {
2115         struct ata_port *ap = dev->link->ap;
2116
2117         if (ata_read_log_page(dev, ATA_LOG_DIRECTORY, 0, ap->sector_buf, 1))
2118                 return false;
2119         return get_unaligned_le16(&ap->sector_buf[log * 2]) ? true : false;
2120 }
2121
2122 static bool ata_identify_page_supported(struct ata_device *dev, u8 page)
2123 {
2124         struct ata_port *ap = dev->link->ap;
2125         unsigned int err, i;
2126
2127         if (!ata_log_supported(dev, ATA_LOG_IDENTIFY_DEVICE)) {
2128                 ata_dev_warn(dev, "ATA Identify Device Log not supported\n");
2129                 return false;
2130         }
2131
2132         /*
2133          * Read IDENTIFY DEVICE data log, page 0, to figure out if the page is
2134          * supported.
2135          */
2136         err = ata_read_log_page(dev, ATA_LOG_IDENTIFY_DEVICE, 0, ap->sector_buf,
2137                                 1);
2138         if (err) {
2139                 ata_dev_info(dev,
2140                              "failed to get Device Identify Log Emask 0x%x\n",
2141                              err);
2142                 return false;
2143         }
2144
2145         for (i = 0; i < ap->sector_buf[8]; i++) {
2146                 if (ap->sector_buf[9 + i] == page)
2147                         return true;
2148         }
2149
2150         return false;
2151 }
2152
2153 static int ata_do_link_spd_horkage(struct ata_device *dev)
2154 {
2155         struct ata_link *plink = ata_dev_phys_link(dev);
2156         u32 target, target_limit;
2157
2158         if (!sata_scr_valid(plink))
2159                 return 0;
2160
2161         if (dev->horkage & ATA_HORKAGE_1_5_GBPS)
2162                 target = 1;
2163         else
2164                 return 0;
2165
2166         target_limit = (1 << target) - 1;
2167
2168         /* if already on stricter limit, no need to push further */
2169         if (plink->sata_spd_limit <= target_limit)
2170                 return 0;
2171
2172         plink->sata_spd_limit = target_limit;
2173
2174         /* Request another EH round by returning -EAGAIN if link is
2175          * going faster than the target speed.  Forward progress is
2176          * guaranteed by setting sata_spd_limit to target_limit above.
2177          */
2178         if (plink->sata_spd > target) {
2179                 ata_dev_info(dev, "applying link speed limit horkage to %s\n",
2180                              sata_spd_string(target));
2181                 return -EAGAIN;
2182         }
2183         return 0;
2184 }
2185
2186 static inline u8 ata_dev_knobble(struct ata_device *dev)
2187 {
2188         struct ata_port *ap = dev->link->ap;
2189
2190         if (ata_dev_blacklisted(dev) & ATA_HORKAGE_BRIDGE_OK)
2191                 return 0;
2192
2193         return ((ap->cbl == ATA_CBL_SATA) && (!ata_id_is_sata(dev->id)));
2194 }
2195
2196 static void ata_dev_config_ncq_send_recv(struct ata_device *dev)
2197 {
2198         struct ata_port *ap = dev->link->ap;
2199         unsigned int err_mask;
2200
2201         if (!ata_log_supported(dev, ATA_LOG_NCQ_SEND_RECV)) {
2202                 ata_dev_warn(dev, "NCQ Send/Recv Log not supported\n");
2203                 return;
2204         }
2205         err_mask = ata_read_log_page(dev, ATA_LOG_NCQ_SEND_RECV,
2206                                      0, ap->sector_buf, 1);
2207         if (err_mask) {
2208                 ata_dev_dbg(dev,
2209                             "failed to get NCQ Send/Recv Log Emask 0x%x\n",
2210                             err_mask);
2211         } else {
2212                 u8 *cmds = dev->ncq_send_recv_cmds;
2213
2214                 dev->flags |= ATA_DFLAG_NCQ_SEND_RECV;
2215                 memcpy(cmds, ap->sector_buf, ATA_LOG_NCQ_SEND_RECV_SIZE);
2216
2217                 if (dev->horkage & ATA_HORKAGE_NO_NCQ_TRIM) {
2218                         ata_dev_dbg(dev, "disabling queued TRIM support\n");
2219                         cmds[ATA_LOG_NCQ_SEND_RECV_DSM_OFFSET] &=
2220                                 ~ATA_LOG_NCQ_SEND_RECV_DSM_TRIM;
2221                 }
2222         }
2223 }
2224
2225 static void ata_dev_config_ncq_non_data(struct ata_device *dev)
2226 {
2227         struct ata_port *ap = dev->link->ap;
2228         unsigned int err_mask;
2229
2230         if (!ata_log_supported(dev, ATA_LOG_NCQ_NON_DATA)) {
2231                 ata_dev_warn(dev,
2232                              "NCQ Send/Recv Log not supported\n");
2233                 return;
2234         }
2235         err_mask = ata_read_log_page(dev, ATA_LOG_NCQ_NON_DATA,
2236                                      0, ap->sector_buf, 1);
2237         if (err_mask) {
2238                 ata_dev_dbg(dev,
2239                             "failed to get NCQ Non-Data Log Emask 0x%x\n",
2240                             err_mask);
2241         } else {
2242                 u8 *cmds = dev->ncq_non_data_cmds;
2243
2244                 memcpy(cmds, ap->sector_buf, ATA_LOG_NCQ_NON_DATA_SIZE);
2245         }
2246 }
2247
2248 static void ata_dev_config_ncq_prio(struct ata_device *dev)
2249 {
2250         struct ata_port *ap = dev->link->ap;
2251         unsigned int err_mask;
2252
2253         if (!(dev->flags & ATA_DFLAG_NCQ_PRIO_ENABLE)) {
2254                 dev->flags &= ~ATA_DFLAG_NCQ_PRIO;
2255                 return;
2256         }
2257
2258         err_mask = ata_read_log_page(dev,
2259                                      ATA_LOG_IDENTIFY_DEVICE,
2260                                      ATA_LOG_SATA_SETTINGS,
2261                                      ap->sector_buf,
2262                                      1);
2263         if (err_mask) {
2264                 ata_dev_dbg(dev,
2265                             "failed to get Identify Device data, Emask 0x%x\n",
2266                             err_mask);
2267                 return;
2268         }
2269
2270         if (ap->sector_buf[ATA_LOG_NCQ_PRIO_OFFSET] & BIT(3)) {
2271                 dev->flags |= ATA_DFLAG_NCQ_PRIO;
2272         } else {
2273                 dev->flags &= ~ATA_DFLAG_NCQ_PRIO;
2274                 ata_dev_dbg(dev, "SATA page does not support priority\n");
2275         }
2276
2277 }
2278
2279 static bool ata_dev_check_adapter(struct ata_device *dev,
2280                                   unsigned short vendor_id)
2281 {
2282         struct pci_dev *pcidev = NULL;
2283         struct device *parent_dev = NULL;
2284
2285         for (parent_dev = dev->tdev.parent; parent_dev != NULL;
2286              parent_dev = parent_dev->parent) {
2287                 if (dev_is_pci(parent_dev)) {
2288                         pcidev = to_pci_dev(parent_dev);
2289                         if (pcidev->vendor == vendor_id)
2290                                 return true;
2291                         break;
2292                 }
2293         }
2294
2295         return false;
2296 }
2297
2298 static int ata_dev_config_ncq(struct ata_device *dev,
2299                                char *desc, size_t desc_sz)
2300 {
2301         struct ata_port *ap = dev->link->ap;
2302         int hdepth = 0, ddepth = ata_id_queue_depth(dev->id);
2303         unsigned int err_mask;
2304         char *aa_desc = "";
2305
2306         if (!ata_id_has_ncq(dev->id)) {
2307                 desc[0] = '\0';
2308                 return 0;
2309         }
2310         if (dev->horkage & ATA_HORKAGE_NONCQ) {
2311                 snprintf(desc, desc_sz, "NCQ (not used)");
2312                 return 0;
2313         }
2314
2315         if (dev->horkage & ATA_HORKAGE_NO_NCQ_ON_ATI &&
2316             ata_dev_check_adapter(dev, PCI_VENDOR_ID_ATI)) {
2317                 snprintf(desc, desc_sz, "NCQ (not used)");
2318                 return 0;
2319         }
2320
2321         if (ap->flags & ATA_FLAG_NCQ) {
2322                 hdepth = min(ap->scsi_host->can_queue, ATA_MAX_QUEUE - 1);
2323                 dev->flags |= ATA_DFLAG_NCQ;
2324         }
2325
2326         if (!(dev->horkage & ATA_HORKAGE_BROKEN_FPDMA_AA) &&
2327                 (ap->flags & ATA_FLAG_FPDMA_AA) &&
2328                 ata_id_has_fpdma_aa(dev->id)) {
2329                 err_mask = ata_dev_set_feature(dev, SETFEATURES_SATA_ENABLE,
2330                         SATA_FPDMA_AA);
2331                 if (err_mask) {
2332                         ata_dev_err(dev,
2333                                     "failed to enable AA (error_mask=0x%x)\n",
2334                                     err_mask);
2335                         if (err_mask != AC_ERR_DEV) {
2336                                 dev->horkage |= ATA_HORKAGE_BROKEN_FPDMA_AA;
2337                                 return -EIO;
2338                         }
2339                 } else
2340                         aa_desc = ", AA";
2341         }
2342
2343         if (hdepth >= ddepth)
2344                 snprintf(desc, desc_sz, "NCQ (depth %d)%s", ddepth, aa_desc);
2345         else
2346                 snprintf(desc, desc_sz, "NCQ (depth %d/%d)%s", hdepth,
2347                         ddepth, aa_desc);
2348
2349         if ((ap->flags & ATA_FLAG_FPDMA_AUX)) {
2350                 if (ata_id_has_ncq_send_and_recv(dev->id))
2351                         ata_dev_config_ncq_send_recv(dev);
2352                 if (ata_id_has_ncq_non_data(dev->id))
2353                         ata_dev_config_ncq_non_data(dev);
2354                 if (ata_id_has_ncq_prio(dev->id))
2355                         ata_dev_config_ncq_prio(dev);
2356         }
2357
2358         return 0;
2359 }
2360
2361 static void ata_dev_config_sense_reporting(struct ata_device *dev)
2362 {
2363         unsigned int err_mask;
2364
2365         if (!ata_id_has_sense_reporting(dev->id))
2366                 return;
2367
2368         if (ata_id_sense_reporting_enabled(dev->id))
2369                 return;
2370
2371         err_mask = ata_dev_set_feature(dev, SETFEATURE_SENSE_DATA, 0x1);
2372         if (err_mask) {
2373                 ata_dev_dbg(dev,
2374                             "failed to enable Sense Data Reporting, Emask 0x%x\n",
2375                             err_mask);
2376         }
2377 }
2378
2379 static void ata_dev_config_zac(struct ata_device *dev)
2380 {
2381         struct ata_port *ap = dev->link->ap;
2382         unsigned int err_mask;
2383         u8 *identify_buf = ap->sector_buf;
2384
2385         dev->zac_zones_optimal_open = U32_MAX;
2386         dev->zac_zones_optimal_nonseq = U32_MAX;
2387         dev->zac_zones_max_open = U32_MAX;
2388
2389         /*
2390          * Always set the 'ZAC' flag for Host-managed devices.
2391          */
2392         if (dev->class == ATA_DEV_ZAC)
2393                 dev->flags |= ATA_DFLAG_ZAC;
2394         else if (ata_id_zoned_cap(dev->id) == 0x01)
2395                 /*
2396                  * Check for host-aware devices.
2397                  */
2398                 dev->flags |= ATA_DFLAG_ZAC;
2399
2400         if (!(dev->flags & ATA_DFLAG_ZAC))
2401                 return;
2402
2403         if (!ata_identify_page_supported(dev, ATA_LOG_ZONED_INFORMATION)) {
2404                 ata_dev_warn(dev,
2405                              "ATA Zoned Information Log not supported\n");
2406                 return;
2407         }
2408
2409         /*
2410          * Read IDENTIFY DEVICE data log, page 9 (Zoned-device information)
2411          */
2412         err_mask = ata_read_log_page(dev, ATA_LOG_IDENTIFY_DEVICE,
2413                                      ATA_LOG_ZONED_INFORMATION,
2414                                      identify_buf, 1);
2415         if (!err_mask) {
2416                 u64 zoned_cap, opt_open, opt_nonseq, max_open;
2417
2418                 zoned_cap = get_unaligned_le64(&identify_buf[8]);
2419                 if ((zoned_cap >> 63))
2420                         dev->zac_zoned_cap = (zoned_cap & 1);
2421                 opt_open = get_unaligned_le64(&identify_buf[24]);
2422                 if ((opt_open >> 63))
2423                         dev->zac_zones_optimal_open = (u32)opt_open;
2424                 opt_nonseq = get_unaligned_le64(&identify_buf[32]);
2425                 if ((opt_nonseq >> 63))
2426                         dev->zac_zones_optimal_nonseq = (u32)opt_nonseq;
2427                 max_open = get_unaligned_le64(&identify_buf[40]);
2428                 if ((max_open >> 63))
2429                         dev->zac_zones_max_open = (u32)max_open;
2430         }
2431 }
2432
2433 static void ata_dev_config_trusted(struct ata_device *dev)
2434 {
2435         struct ata_port *ap = dev->link->ap;
2436         u64 trusted_cap;
2437         unsigned int err;
2438
2439         if (!ata_id_has_trusted(dev->id))
2440                 return;
2441
2442         if (!ata_identify_page_supported(dev, ATA_LOG_SECURITY)) {
2443                 ata_dev_warn(dev,
2444                              "Security Log not supported\n");
2445                 return;
2446         }
2447
2448         err = ata_read_log_page(dev, ATA_LOG_IDENTIFY_DEVICE, ATA_LOG_SECURITY,
2449                         ap->sector_buf, 1);
2450         if (err) {
2451                 ata_dev_dbg(dev,
2452                             "failed to read Security Log, Emask 0x%x\n", err);
2453                 return;
2454         }
2455
2456         trusted_cap = get_unaligned_le64(&ap->sector_buf[40]);
2457         if (!(trusted_cap & (1ULL << 63))) {
2458                 ata_dev_dbg(dev,
2459                             "Trusted Computing capability qword not valid!\n");
2460                 return;
2461         }
2462
2463         if (trusted_cap & (1 << 0))
2464                 dev->flags |= ATA_DFLAG_TRUSTED;
2465 }
2466
2467 /**
2468  *      ata_dev_configure - Configure the specified ATA/ATAPI device
2469  *      @dev: Target device to configure
2470  *
2471  *      Configure @dev according to @dev->id.  Generic and low-level
2472  *      driver specific fixups are also applied.
2473  *
2474  *      LOCKING:
2475  *      Kernel thread context (may sleep)
2476  *
2477  *      RETURNS:
2478  *      0 on success, -errno otherwise
2479  */
2480 int ata_dev_configure(struct ata_device *dev)
2481 {
2482         struct ata_port *ap = dev->link->ap;
2483         struct ata_eh_context *ehc = &dev->link->eh_context;
2484         int print_info = ehc->i.flags & ATA_EHI_PRINTINFO;
2485         const u16 *id = dev->id;
2486         unsigned long xfer_mask;
2487         unsigned int err_mask;
2488         char revbuf[7];         /* XYZ-99\0 */
2489         char fwrevbuf[ATA_ID_FW_REV_LEN+1];
2490         char modelbuf[ATA_ID_PROD_LEN+1];
2491         int rc;
2492
2493         if (!ata_dev_enabled(dev) && ata_msg_info(ap)) {
2494                 ata_dev_info(dev, "%s: ENTER/EXIT -- nodev\n", __func__);
2495                 return 0;
2496         }
2497
2498         if (ata_msg_probe(ap))
2499                 ata_dev_dbg(dev, "%s: ENTER\n", __func__);
2500
2501         /* set horkage */
2502         dev->horkage |= ata_dev_blacklisted(dev);
2503         ata_force_horkage(dev);
2504
2505         if (dev->horkage & ATA_HORKAGE_DISABLE) {
2506                 ata_dev_info(dev, "unsupported device, disabling\n");
2507                 ata_dev_disable(dev);
2508                 return 0;
2509         }
2510
2511         if ((!atapi_enabled || (ap->flags & ATA_FLAG_NO_ATAPI)) &&
2512             dev->class == ATA_DEV_ATAPI) {
2513                 ata_dev_warn(dev, "WARNING: ATAPI is %s, device ignored\n",
2514                              atapi_enabled ? "not supported with this driver"
2515                              : "disabled");
2516                 ata_dev_disable(dev);
2517                 return 0;
2518         }
2519
2520         rc = ata_do_link_spd_horkage(dev);
2521         if (rc)
2522                 return rc;
2523
2524         /* some WD SATA-1 drives have issues with LPM, turn on NOLPM for them */
2525         if ((dev->horkage & ATA_HORKAGE_WD_BROKEN_LPM) &&
2526             (id[ATA_ID_SATA_CAPABILITY] & 0xe) == 0x2)
2527                 dev->horkage |= ATA_HORKAGE_NOLPM;
2528
2529         if (ap->flags & ATA_FLAG_NO_LPM)
2530                 dev->horkage |= ATA_HORKAGE_NOLPM;
2531
2532         if (dev->horkage & ATA_HORKAGE_NOLPM) {
2533                 ata_dev_warn(dev, "LPM support broken, forcing max_power\n");
2534                 dev->link->ap->target_lpm_policy = ATA_LPM_MAX_POWER;
2535         }
2536
2537         /* let ACPI work its magic */
2538         rc = ata_acpi_on_devcfg(dev);
2539         if (rc)
2540                 return rc;
2541
2542         /* massage HPA, do it early as it might change IDENTIFY data */
2543         rc = ata_hpa_resize(dev);
2544         if (rc)
2545                 return rc;
2546
2547         /* print device capabilities */
2548         if (ata_msg_probe(ap))
2549                 ata_dev_dbg(dev,
2550                             "%s: cfg 49:%04x 82:%04x 83:%04x 84:%04x "
2551                             "85:%04x 86:%04x 87:%04x 88:%04x\n",
2552                             __func__,
2553                             id[49], id[82], id[83], id[84],
2554                             id[85], id[86], id[87], id[88]);
2555
2556         /* initialize to-be-configured parameters */
2557         dev->flags &= ~ATA_DFLAG_CFG_MASK;
2558         dev->max_sectors = 0;
2559         dev->cdb_len = 0;
2560         dev->n_sectors = 0;
2561         dev->cylinders = 0;
2562         dev->heads = 0;
2563         dev->sectors = 0;
2564         dev->multi_count = 0;
2565
2566         /*
2567          * common ATA, ATAPI feature tests
2568          */
2569
2570         /* find max transfer mode; for printk only */
2571         xfer_mask = ata_id_xfermask(id);
2572
2573         if (ata_msg_probe(ap))
2574                 ata_dump_id(id);
2575
2576         /* SCSI only uses 4-char revisions, dump full 8 chars from ATA */
2577         ata_id_c_string(dev->id, fwrevbuf, ATA_ID_FW_REV,
2578                         sizeof(fwrevbuf));
2579
2580         ata_id_c_string(dev->id, modelbuf, ATA_ID_PROD,
2581                         sizeof(modelbuf));
2582
2583         /* ATA-specific feature tests */
2584         if (dev->class == ATA_DEV_ATA || dev->class == ATA_DEV_ZAC) {
2585                 if (ata_id_is_cfa(id)) {
2586                         /* CPRM may make this media unusable */
2587                         if (id[ATA_ID_CFA_KEY_MGMT] & 1)
2588                                 ata_dev_warn(dev,
2589         "supports DRM functions and may not be fully accessible\n");
2590                         snprintf(revbuf, 7, "CFA");
2591                 } else {
2592                         snprintf(revbuf, 7, "ATA-%d", ata_id_major_version(id));
2593                         /* Warn the user if the device has TPM extensions */
2594                         if (ata_id_has_tpm(id))
2595                                 ata_dev_warn(dev,
2596         "supports DRM functions and may not be fully accessible\n");
2597                 }
2598
2599                 dev->n_sectors = ata_id_n_sectors(id);
2600
2601                 /* get current R/W Multiple count setting */
2602                 if ((dev->id[47] >> 8) == 0x80 && (dev->id[59] & 0x100)) {
2603                         unsigned int max = dev->id[47] & 0xff;
2604                         unsigned int cnt = dev->id[59] & 0xff;
2605                         /* only recognize/allow powers of two here */
2606                         if (is_power_of_2(max) && is_power_of_2(cnt))
2607                                 if (cnt <= max)
2608                                         dev->multi_count = cnt;
2609                 }
2610
2611                 if (ata_id_has_lba(id)) {
2612                         const char *lba_desc;
2613                         char ncq_desc[24];
2614
2615                         lba_desc = "LBA";
2616                         dev->flags |= ATA_DFLAG_LBA;
2617                         if (ata_id_has_lba48(id)) {
2618                                 dev->flags |= ATA_DFLAG_LBA48;
2619                                 lba_desc = "LBA48";
2620
2621                                 if (dev->n_sectors >= (1UL << 28) &&
2622                                     ata_id_has_flush_ext(id))
2623                                         dev->flags |= ATA_DFLAG_FLUSH_EXT;
2624                         }
2625
2626                         /* config NCQ */
2627                         rc = ata_dev_config_ncq(dev, ncq_desc, sizeof(ncq_desc));
2628                         if (rc)
2629                                 return rc;
2630
2631                         /* print device info to dmesg */
2632                         if (ata_msg_drv(ap) && print_info) {
2633                                 ata_dev_info(dev, "%s: %s, %s, max %s\n",
2634                                              revbuf, modelbuf, fwrevbuf,
2635                                              ata_mode_string(xfer_mask));
2636                                 ata_dev_info(dev,
2637                                              "%llu sectors, multi %u: %s %s\n",
2638                                         (unsigned long long)dev->n_sectors,
2639                                         dev->multi_count, lba_desc, ncq_desc);
2640                         }
2641                 } else {
2642                         /* CHS */
2643
2644                         /* Default translation */
2645                         dev->cylinders  = id[1];
2646                         dev->heads      = id[3];
2647                         dev->sectors    = id[6];
2648
2649                         if (ata_id_current_chs_valid(id)) {
2650                                 /* Current CHS translation is valid. */
2651                                 dev->cylinders = id[54];
2652                                 dev->heads     = id[55];
2653                                 dev->sectors   = id[56];
2654                         }
2655
2656                         /* print device info to dmesg */
2657                         if (ata_msg_drv(ap) && print_info) {
2658                                 ata_dev_info(dev, "%s: %s, %s, max %s\n",
2659                                              revbuf,    modelbuf, fwrevbuf,
2660                                              ata_mode_string(xfer_mask));
2661                                 ata_dev_info(dev,
2662                                              "%llu sectors, multi %u, CHS %u/%u/%u\n",
2663                                              (unsigned long long)dev->n_sectors,
2664                                              dev->multi_count, dev->cylinders,
2665                                              dev->heads, dev->sectors);
2666                         }
2667                 }
2668
2669                 /* Check and mark DevSlp capability. Get DevSlp timing variables
2670                  * from SATA Settings page of Identify Device Data Log.
2671                  */
2672                 if (ata_id_has_devslp(dev->id)) {
2673                         u8 *sata_setting = ap->sector_buf;
2674                         int i, j;
2675
2676                         dev->flags |= ATA_DFLAG_DEVSLP;
2677                         err_mask = ata_read_log_page(dev,
2678                                                      ATA_LOG_IDENTIFY_DEVICE,
2679                                                      ATA_LOG_SATA_SETTINGS,
2680                                                      sata_setting,
2681                                                      1);
2682                         if (err_mask)
2683                                 ata_dev_dbg(dev,
2684                                             "failed to get Identify Device Data, Emask 0x%x\n",
2685                                             err_mask);
2686                         else
2687                                 for (i = 0; i < ATA_LOG_DEVSLP_SIZE; i++) {
2688                                         j = ATA_LOG_DEVSLP_OFFSET + i;
2689                                         dev->devslp_timing[i] = sata_setting[j];
2690                                 }
2691                 }
2692                 ata_dev_config_sense_reporting(dev);
2693                 ata_dev_config_zac(dev);
2694                 ata_dev_config_trusted(dev);
2695                 dev->cdb_len = 32;
2696         }
2697
2698         /* ATAPI-specific feature tests */
2699         else if (dev->class == ATA_DEV_ATAPI) {
2700                 const char *cdb_intr_string = "";
2701                 const char *atapi_an_string = "";
2702                 const char *dma_dir_string = "";
2703                 u32 sntf;
2704
2705                 rc = atapi_cdb_len(id);
2706                 if ((rc < 12) || (rc > ATAPI_CDB_LEN)) {
2707                         if (ata_msg_warn(ap))
2708                                 ata_dev_warn(dev, "unsupported CDB len\n");
2709                         rc = -EINVAL;
2710                         goto err_out_nosup;
2711                 }
2712                 dev->cdb_len = (unsigned int) rc;
2713
2714                 /* Enable ATAPI AN if both the host and device have
2715                  * the support.  If PMP is attached, SNTF is required
2716                  * to enable ATAPI AN to discern between PHY status
2717                  * changed notifications and ATAPI ANs.
2718                  */
2719                 if (atapi_an &&
2720                     (ap->flags & ATA_FLAG_AN) && ata_id_has_atapi_AN(id) &&
2721                     (!sata_pmp_attached(ap) ||
2722                      sata_scr_read(&ap->link, SCR_NOTIFICATION, &sntf) == 0)) {
2723                         /* issue SET feature command to turn this on */
2724                         err_mask = ata_dev_set_feature(dev,
2725                                         SETFEATURES_SATA_ENABLE, SATA_AN);
2726                         if (err_mask)
2727                                 ata_dev_err(dev,
2728                                             "failed to enable ATAPI AN (err_mask=0x%x)\n",
2729                                             err_mask);
2730                         else {
2731                                 dev->flags |= ATA_DFLAG_AN;
2732                                 atapi_an_string = ", ATAPI AN";
2733                         }
2734                 }
2735
2736                 if (ata_id_cdb_intr(dev->id)) {
2737                         dev->flags |= ATA_DFLAG_CDB_INTR;
2738                         cdb_intr_string = ", CDB intr";
2739                 }
2740
2741                 if (atapi_dmadir || (dev->horkage & ATA_HORKAGE_ATAPI_DMADIR) || atapi_id_dmadir(dev->id)) {
2742                         dev->flags |= ATA_DFLAG_DMADIR;
2743                         dma_dir_string = ", DMADIR";
2744                 }
2745
2746                 if (ata_id_has_da(dev->id)) {
2747                         dev->flags |= ATA_DFLAG_DA;
2748                         zpodd_init(dev);
2749                 }
2750
2751                 /* print device info to dmesg */
2752                 if (ata_msg_drv(ap) && print_info)
2753                         ata_dev_info(dev,
2754                                      "ATAPI: %s, %s, max %s%s%s%s\n",
2755                                      modelbuf, fwrevbuf,
2756                                      ata_mode_string(xfer_mask),
2757                                      cdb_intr_string, atapi_an_string,
2758                                      dma_dir_string);
2759         }
2760
2761         /* determine max_sectors */
2762         dev->max_sectors = ATA_MAX_SECTORS;
2763         if (dev->flags & ATA_DFLAG_LBA48)
2764                 dev->max_sectors = ATA_MAX_SECTORS_LBA48;
2765
2766         /* Limit PATA drive on SATA cable bridge transfers to udma5,
2767            200 sectors */
2768         if (ata_dev_knobble(dev)) {
2769                 if (ata_msg_drv(ap) && print_info)
2770                         ata_dev_info(dev, "applying bridge limits\n");
2771                 dev->udma_mask &= ATA_UDMA5;
2772                 dev->max_sectors = ATA_MAX_SECTORS;
2773         }
2774
2775         if ((dev->class == ATA_DEV_ATAPI) &&
2776             (atapi_command_packet_set(id) == TYPE_TAPE)) {
2777                 dev->max_sectors = ATA_MAX_SECTORS_TAPE;
2778                 dev->horkage |= ATA_HORKAGE_STUCK_ERR;
2779         }
2780
2781         if (dev->horkage & ATA_HORKAGE_MAX_SEC_128)
2782                 dev->max_sectors = min_t(unsigned int, ATA_MAX_SECTORS_128,
2783                                          dev->max_sectors);
2784
2785         if (dev->horkage & ATA_HORKAGE_MAX_SEC_1024)
2786                 dev->max_sectors = min_t(unsigned int, ATA_MAX_SECTORS_1024,
2787                                          dev->max_sectors);
2788
2789         if (dev->horkage & ATA_HORKAGE_MAX_SEC_LBA48)
2790                 dev->max_sectors = ATA_MAX_SECTORS_LBA48;
2791
2792         if (ap->ops->dev_config)
2793                 ap->ops->dev_config(dev);
2794
2795         if (dev->horkage & ATA_HORKAGE_DIAGNOSTIC) {
2796                 /* Let the user know. We don't want to disallow opens for
2797                    rescue purposes, or in case the vendor is just a blithering
2798                    idiot. Do this after the dev_config call as some controllers
2799                    with buggy firmware may want to avoid reporting false device
2800                    bugs */
2801
2802                 if (print_info) {
2803                         ata_dev_warn(dev,
2804 "Drive reports diagnostics failure. This may indicate a drive\n");
2805                         ata_dev_warn(dev,
2806 "fault or invalid emulation. Contact drive vendor for information.\n");
2807                 }
2808         }
2809
2810         if ((dev->horkage & ATA_HORKAGE_FIRMWARE_WARN) && print_info) {
2811                 ata_dev_warn(dev, "WARNING: device requires firmware update to be fully functional\n");
2812                 ata_dev_warn(dev, "         contact the vendor or visit http://ata.wiki.kernel.org\n");
2813         }
2814
2815         return 0;
2816
2817 err_out_nosup:
2818         if (ata_msg_probe(ap))
2819                 ata_dev_dbg(dev, "%s: EXIT, err\n", __func__);
2820         return rc;
2821 }
2822
2823 /**
2824  *      ata_cable_40wire        -       return 40 wire cable type
2825  *      @ap: port
2826  *
2827  *      Helper method for drivers which want to hardwire 40 wire cable
2828  *      detection.
2829  */
2830
2831 int ata_cable_40wire(struct ata_port *ap)
2832 {
2833         return ATA_CBL_PATA40;
2834 }
2835
2836 /**
2837  *      ata_cable_80wire        -       return 80 wire cable type
2838  *      @ap: port
2839  *
2840  *      Helper method for drivers which want to hardwire 80 wire cable
2841  *      detection.
2842  */
2843
2844 int ata_cable_80wire(struct ata_port *ap)
2845 {
2846         return ATA_CBL_PATA80;
2847 }
2848
2849 /**
2850  *      ata_cable_unknown       -       return unknown PATA cable.
2851  *      @ap: port
2852  *
2853  *      Helper method for drivers which have no PATA cable detection.
2854  */
2855
2856 int ata_cable_unknown(struct ata_port *ap)
2857 {
2858         return ATA_CBL_PATA_UNK;
2859 }
2860
2861 /**
2862  *      ata_cable_ignore        -       return ignored PATA cable.
2863  *      @ap: port
2864  *
2865  *      Helper method for drivers which don't use cable type to limit
2866  *      transfer mode.
2867  */
2868 int ata_cable_ignore(struct ata_port *ap)
2869 {
2870         return ATA_CBL_PATA_IGN;
2871 }
2872
2873 /**
2874  *      ata_cable_sata  -       return SATA cable type
2875  *      @ap: port
2876  *
2877  *      Helper method for drivers which have SATA cables
2878  */
2879
2880 int ata_cable_sata(struct ata_port *ap)
2881 {
2882         return ATA_CBL_SATA;
2883 }
2884
2885 /**
2886  *      ata_bus_probe - Reset and probe ATA bus
2887  *      @ap: Bus to probe
2888  *
2889  *      Master ATA bus probing function.  Initiates a hardware-dependent
2890  *      bus reset, then attempts to identify any devices found on
2891  *      the bus.
2892  *
2893  *      LOCKING:
2894  *      PCI/etc. bus probe sem.
2895  *
2896  *      RETURNS:
2897  *      Zero on success, negative errno otherwise.
2898  */
2899
2900 int ata_bus_probe(struct ata_port *ap)
2901 {
2902         unsigned int classes[ATA_MAX_DEVICES];
2903         int tries[ATA_MAX_DEVICES];
2904         int rc;
2905         struct ata_device *dev;
2906
2907         ata_for_each_dev(dev, &ap->link, ALL)
2908                 tries[dev->devno] = ATA_PROBE_MAX_TRIES;
2909
2910  retry:
2911         ata_for_each_dev(dev, &ap->link, ALL) {
2912                 /* If we issue an SRST then an ATA drive (not ATAPI)
2913                  * may change configuration and be in PIO0 timing. If
2914                  * we do a hard reset (or are coming from power on)
2915                  * this is true for ATA or ATAPI. Until we've set a
2916                  * suitable controller mode we should not touch the
2917                  * bus as we may be talking too fast.
2918                  */
2919                 dev->pio_mode = XFER_PIO_0;
2920                 dev->dma_mode = 0xff;
2921
2922                 /* If the controller has a pio mode setup function
2923                  * then use it to set the chipset to rights. Don't
2924                  * touch the DMA setup as that will be dealt with when
2925                  * configuring devices.
2926                  */
2927                 if (ap->ops->set_piomode)
2928                         ap->ops->set_piomode(ap, dev);
2929         }
2930
2931         /* reset and determine device classes */
2932         ap->ops->phy_reset(ap);
2933
2934         ata_for_each_dev(dev, &ap->link, ALL) {
2935                 if (dev->class != ATA_DEV_UNKNOWN)
2936                         classes[dev->devno] = dev->class;
2937                 else
2938                         classes[dev->devno] = ATA_DEV_NONE;
2939
2940                 dev->class = ATA_DEV_UNKNOWN;
2941         }
2942
2943         /* read IDENTIFY page and configure devices. We have to do the identify
2944            specific sequence bass-ackwards so that PDIAG- is released by
2945            the slave device */
2946
2947         ata_for_each_dev(dev, &ap->link, ALL_REVERSE) {
2948                 if (tries[dev->devno])
2949                         dev->class = classes[dev->devno];
2950
2951                 if (!ata_dev_enabled(dev))
2952                         continue;
2953
2954                 rc = ata_dev_read_id(dev, &dev->class, ATA_READID_POSTRESET,
2955                                      dev->id);
2956                 if (rc)
2957                         goto fail;
2958         }
2959
2960         /* Now ask for the cable type as PDIAG- should have been released */
2961         if (ap->ops->cable_detect)
2962                 ap->cbl = ap->ops->cable_detect(ap);
2963
2964         /* We may have SATA bridge glue hiding here irrespective of
2965          * the reported cable types and sensed types.  When SATA
2966          * drives indicate we have a bridge, we don't know which end
2967          * of the link the bridge is which is a problem.
2968          */
2969         ata_for_each_dev(dev, &ap->link, ENABLED)
2970                 if (ata_id_is_sata(dev->id))
2971                         ap->cbl = ATA_CBL_SATA;
2972
2973         /* After the identify sequence we can now set up the devices. We do
2974            this in the normal order so that the user doesn't get confused */
2975
2976         ata_for_each_dev(dev, &ap->link, ENABLED) {
2977                 ap->link.eh_context.i.flags |= ATA_EHI_PRINTINFO;
2978                 rc = ata_dev_configure(dev);
2979                 ap->link.eh_context.i.flags &= ~ATA_EHI_PRINTINFO;
2980                 if (rc)
2981                         goto fail;
2982         }
2983
2984         /* configure transfer mode */
2985         rc = ata_set_mode(&ap->link, &dev);
2986         if (rc)
2987                 goto fail;
2988
2989         ata_for_each_dev(dev, &ap->link, ENABLED)
2990                 return 0;
2991
2992         return -ENODEV;
2993
2994  fail:
2995         tries[dev->devno]--;
2996
2997         switch (rc) {
2998         case -EINVAL:
2999                 /* eeek, something went very wrong, give up */
3000                 tries[dev->devno] = 0;
3001                 break;
3002
3003         case -ENODEV:
3004                 /* give it just one more chance */
3005                 tries[dev->devno] = min(tries[dev->devno], 1);
3006         case -EIO:
3007                 if (tries[dev->devno] == 1) {
3008                         /* This is the last chance, better to slow
3009                          * down than lose it.
3010                          */
3011                         sata_down_spd_limit(&ap->link, 0);
3012                         ata_down_xfermask_limit(dev, ATA_DNXFER_PIO);
3013                 }
3014         }
3015
3016         if (!tries[dev->devno])
3017                 ata_dev_disable(dev);
3018
3019         goto retry;
3020 }
3021
3022 /**
3023  *      sata_print_link_status - Print SATA link status
3024  *      @link: SATA link to printk link status about
3025  *
3026  *      This function prints link speed and status of a SATA link.
3027  *
3028  *      LOCKING:
3029  *      None.
3030  */
3031 static void sata_print_link_status(struct ata_link *link)
3032 {
3033         u32 sstatus, scontrol, tmp;
3034
3035         if (sata_scr_read(link, SCR_STATUS, &sstatus))
3036                 return;
3037         sata_scr_read(link, SCR_CONTROL, &scontrol);
3038
3039         if (ata_phys_link_online(link)) {
3040                 tmp = (sstatus >> 4) & 0xf;
3041                 ata_link_info(link, "SATA link up %s (SStatus %X SControl %X)\n",
3042                               sata_spd_string(tmp), sstatus, scontrol);
3043         } else {
3044                 ata_link_info(link, "SATA link down (SStatus %X SControl %X)\n",
3045                               sstatus, scontrol);
3046         }
3047 }
3048
3049 /**
3050  *      ata_dev_pair            -       return other device on cable
3051  *      @adev: device
3052  *
3053  *      Obtain the other device on the same cable, or if none is
3054  *      present NULL is returned
3055  */
3056
3057 struct ata_device *ata_dev_pair(struct ata_device *adev)
3058 {
3059         struct ata_link *link = adev->link;
3060         struct ata_device *pair = &link->device[1 - adev->devno];
3061         if (!ata_dev_enabled(pair))
3062                 return NULL;
3063         return pair;
3064 }
3065
3066 /**
3067  *      sata_down_spd_limit - adjust SATA spd limit downward
3068  *      @link: Link to adjust SATA spd limit for
3069  *      @spd_limit: Additional limit
3070  *
3071  *      Adjust SATA spd limit of @link downward.  Note that this
3072  *      function only adjusts the limit.  The change must be applied
3073  *      using sata_set_spd().
3074  *
3075  *      If @spd_limit is non-zero, the speed is limited to equal to or
3076  *      lower than @spd_limit if such speed is supported.  If
3077  *      @spd_limit is slower than any supported speed, only the lowest
3078  *      supported speed is allowed.
3079  *
3080  *      LOCKING:
3081  *      Inherited from caller.
3082  *
3083  *      RETURNS:
3084  *      0 on success, negative errno on failure
3085  */
3086 int sata_down_spd_limit(struct ata_link *link, u32 spd_limit)
3087 {
3088         u32 sstatus, spd, mask;
3089         int rc, bit;
3090
3091         if (!sata_scr_valid(link))
3092                 return -EOPNOTSUPP;
3093
3094         /* If SCR can be read, use it to determine the current SPD.
3095          * If not, use cached value in link->sata_spd.
3096          */
3097         rc = sata_scr_read(link, SCR_STATUS, &sstatus);
3098         if (rc == 0 && ata_sstatus_online(sstatus))
3099                 spd = (sstatus >> 4) & 0xf;
3100         else
3101                 spd = link->sata_spd;
3102
3103         mask = link->sata_spd_limit;
3104         if (mask <= 1)
3105                 return -EINVAL;
3106
3107         /* unconditionally mask off the highest bit */
3108         bit = fls(mask) - 1;
3109         mask &= ~(1 << bit);
3110
3111         /* Mask off all speeds higher than or equal to the current
3112          * one.  Force 1.5Gbps if current SPD is not available.
3113          */
3114         if (spd > 1)
3115                 mask &= (1 << (spd - 1)) - 1;
3116         else
3117                 mask &= 1;
3118
3119         /* were we already at the bottom? */
3120         if (!mask)
3121                 return -EINVAL;
3122
3123         if (spd_limit) {
3124                 if (mask & ((1 << spd_limit) - 1))
3125                         mask &= (1 << spd_limit) - 1;
3126                 else {
3127                         bit = ffs(mask) - 1;
3128                         mask = 1 << bit;
3129                 }
3130         }
3131
3132         link->sata_spd_limit = mask;
3133
3134         ata_link_warn(link, "limiting SATA link speed to %s\n",
3135                       sata_spd_string(fls(mask)));
3136
3137         return 0;
3138 }
3139
3140 static int __sata_set_spd_needed(struct ata_link *link, u32 *scontrol)
3141 {
3142         struct ata_link *host_link = &link->ap->link;
3143         u32 limit, target, spd;
3144
3145         limit = link->sata_spd_limit;
3146
3147         /* Don't configure downstream link faster than upstream link.
3148          * It doesn't speed up anything and some PMPs choke on such
3149          * configuration.
3150          */
3151         if (!ata_is_host_link(link) && host_link->sata_spd)
3152                 limit &= (1 << host_link->sata_spd) - 1;
3153
3154         if (limit == UINT_MAX)
3155                 target = 0;
3156         else
3157                 target = fls(limit);
3158
3159         spd = (*scontrol >> 4) & 0xf;
3160         *scontrol = (*scontrol & ~0xf0) | ((target & 0xf) << 4);
3161
3162         return spd != target;
3163 }
3164
3165 /**
3166  *      sata_set_spd_needed - is SATA spd configuration needed
3167  *      @link: Link in question
3168  *
3169  *      Test whether the spd limit in SControl matches
3170  *      @link->sata_spd_limit.  This function is used to determine
3171  *      whether hardreset is necessary to apply SATA spd
3172  *      configuration.
3173  *
3174  *      LOCKING:
3175  *      Inherited from caller.
3176  *
3177  *      RETURNS:
3178  *      1 if SATA spd configuration is needed, 0 otherwise.
3179  */
3180 static int sata_set_spd_needed(struct ata_link *link)
3181 {
3182         u32 scontrol;
3183
3184         if (sata_scr_read(link, SCR_CONTROL, &scontrol))
3185                 return 1;
3186
3187         return __sata_set_spd_needed(link, &scontrol);
3188 }
3189
3190 /**
3191  *      sata_set_spd - set SATA spd according to spd limit
3192  *      @link: Link to set SATA spd for
3193  *
3194  *      Set SATA spd of @link according to sata_spd_limit.
3195  *
3196  *      LOCKING:
3197  *      Inherited from caller.
3198  *
3199  *      RETURNS:
3200  *      0 if spd doesn't need to be changed, 1 if spd has been
3201  *      changed.  Negative errno if SCR registers are inaccessible.
3202  */
3203 int sata_set_spd(struct ata_link *link)
3204 {
3205         u32 scontrol;
3206         int rc;
3207
3208         if ((rc = sata_scr_read(link, SCR_CONTROL, &scontrol)))
3209                 return rc;
3210
3211         if (!__sata_set_spd_needed(link, &scontrol))
3212                 return 0;
3213
3214         if ((rc = sata_scr_write(link, SCR_CONTROL, scontrol)))
3215                 return rc;
3216
3217         return 1;
3218 }
3219
3220 /*
3221  * This mode timing computation functionality is ported over from
3222  * drivers/ide/ide-timing.h and was originally written by Vojtech Pavlik
3223  */
3224 /*
3225  * PIO 0-4, MWDMA 0-2 and UDMA 0-6 timings (in nanoseconds).
3226  * These were taken from ATA/ATAPI-6 standard, rev 0a, except
3227  * for UDMA6, which is currently supported only by Maxtor drives.
3228  *
3229  * For PIO 5/6 MWDMA 3/4 see the CFA specification 3.0.
3230  */
3231
3232 static const struct ata_timing ata_timing[] = {
3233 /*      { XFER_PIO_SLOW, 120, 290, 240, 960, 290, 240, 0,  960,   0 }, */
3234         { XFER_PIO_0,     70, 290, 240, 600, 165, 150, 0,  600,   0 },
3235         { XFER_PIO_1,     50, 290,  93, 383, 125, 100, 0,  383,   0 },
3236         { XFER_PIO_2,     30, 290,  40, 330, 100,  90, 0,  240,   0 },
3237         { XFER_PIO_3,     30,  80,  70, 180,  80,  70, 0,  180,   0 },
3238         { XFER_PIO_4,     25,  70,  25, 120,  70,  25, 0,  120,   0 },
3239         { XFER_PIO_5,     15,  65,  25, 100,  65,  25, 0,  100,   0 },
3240         { XFER_PIO_6,     10,  55,  20,  80,  55,  20, 0,   80,   0 },
3241
3242         { XFER_SW_DMA_0, 120,   0,   0,   0, 480, 480, 50, 960,   0 },
3243         { XFER_SW_DMA_1,  90,   0,   0,   0, 240, 240, 30, 480,   0 },
3244         { XFER_SW_DMA_2,  60,   0,   0,   0, 120, 120, 20, 240,   0 },
3245
3246         { XFER_MW_DMA_0,  60,   0,   0,   0, 215, 215, 20, 480,   0 },
3247         { XFER_MW_DMA_1,  45,   0,   0,   0,  80,  50, 5,  150,   0 },
3248         { XFER_MW_DMA_2,  25,   0,   0,   0,  70,  25, 5,  120,   0 },
3249         { XFER_MW_DMA_3,  25,   0,   0,   0,  65,  25, 5,  100,   0 },
3250         { XFER_MW_DMA_4,  25,   0,   0,   0,  55,  20, 5,   80,   0 },
3251
3252 /*      { XFER_UDMA_SLOW,  0,   0,   0,   0,   0,   0, 0,    0, 150 }, */
3253         { XFER_UDMA_0,     0,   0,   0,   0,   0,   0, 0,    0, 120 },
3254         { XFER_UDMA_1,     0,   0,   0,   0,   0,   0, 0,    0,  80 },
3255         { XFER_UDMA_2,     0,   0,   0,   0,   0,   0, 0,    0,  60 },
3256         { XFER_UDMA_3,     0,   0,   0,   0,   0,   0, 0,    0,  45 },
3257         { XFER_UDMA_4,     0,   0,   0,   0,   0,   0, 0,    0,  30 },
3258         { XFER_UDMA_5,     0,   0,   0,   0,   0,   0, 0,    0,  20 },
3259         { XFER_UDMA_6,     0,   0,   0,   0,   0,   0, 0,    0,  15 },
3260
3261         { 0xFF }
3262 };
3263
3264 #define ENOUGH(v, unit)         (((v)-1)/(unit)+1)
3265 #define EZ(v, unit)             ((v)?ENOUGH(((v) * 1000), unit):0)
3266
3267 static void ata_timing_quantize(const struct ata_timing *t, struct ata_timing *q, int T, int UT)
3268 {
3269         q->setup        = EZ(t->setup,       T);
3270         q->act8b        = EZ(t->act8b,       T);
3271         q->rec8b        = EZ(t->rec8b,       T);
3272         q->cyc8b        = EZ(t->cyc8b,       T);
3273         q->active       = EZ(t->active,      T);
3274         q->recover      = EZ(t->recover,     T);
3275         q->dmack_hold   = EZ(t->dmack_hold,  T);
3276         q->cycle        = EZ(t->cycle,       T);
3277         q->udma         = EZ(t->udma,       UT);
3278 }
3279
3280 void ata_timing_merge(const struct ata_timing *a, const struct ata_timing *b,
3281                       struct ata_timing *m, unsigned int what)
3282 {
3283         if (what & ATA_TIMING_SETUP  ) m->setup   = max(a->setup,   b->setup);
3284         if (what & ATA_TIMING_ACT8B  ) m->act8b   = max(a->act8b,   b->act8b);
3285         if (what & ATA_TIMING_REC8B  ) m->rec8b   = max(a->rec8b,   b->rec8b);
3286         if (what & ATA_TIMING_CYC8B  ) m->cyc8b   = max(a->cyc8b,   b->cyc8b);
3287         if (what & ATA_TIMING_ACTIVE ) m->active  = max(a->active,  b->active);
3288         if (what & ATA_TIMING_RECOVER) m->recover = max(a->recover, b->recover);
3289         if (what & ATA_TIMING_DMACK_HOLD) m->dmack_hold = max(a->dmack_hold, b->dmack_hold);
3290         if (what & ATA_TIMING_CYCLE  ) m->cycle   = max(a->cycle,   b->cycle);
3291         if (what & ATA_TIMING_UDMA   ) m->udma    = max(a->udma,    b->udma);
3292 }
3293
3294 const struct ata_timing *ata_timing_find_mode(u8 xfer_mode)
3295 {
3296         const struct ata_timing *t = ata_timing;
3297
3298         while (xfer_mode > t->mode)
3299                 t++;
3300
3301         if (xfer_mode == t->mode)
3302                 return t;
3303
3304         WARN_ONCE(true, "%s: unable to find timing for xfer_mode 0x%x\n",
3305                         __func__, xfer_mode);
3306
3307         return NULL;
3308 }
3309
3310 int ata_timing_compute(struct ata_device *adev, unsigned short speed,
3311                        struct ata_timing *t, int T, int UT)
3312 {
3313         const u16 *id = adev->id;
3314         const struct ata_timing *s;
3315         struct ata_timing p;
3316
3317         /*
3318          * Find the mode.
3319          */
3320
3321         if (!(s = ata_timing_find_mode(speed)))
3322                 return -EINVAL;
3323
3324         memcpy(t, s, sizeof(*s));
3325
3326         /*
3327          * If the drive is an EIDE drive, it can tell us it needs extended
3328          * PIO/MW_DMA cycle timing.
3329          */
3330
3331         if (id[ATA_ID_FIELD_VALID] & 2) {       /* EIDE drive */
3332                 memset(&p, 0, sizeof(p));
3333
3334                 if (speed >= XFER_PIO_0 && speed < XFER_SW_DMA_0) {
3335                         if (speed <= XFER_PIO_2)
3336                                 p.cycle = p.cyc8b = id[ATA_ID_EIDE_PIO];
3337                         else if ((speed <= XFER_PIO_4) ||
3338                                  (speed == XFER_PIO_5 && !ata_id_is_cfa(id)))
3339                                 p.cycle = p.cyc8b = id[ATA_ID_EIDE_PIO_IORDY];
3340                 } else if (speed >= XFER_MW_DMA_0 && speed <= XFER_MW_DMA_2)
3341                         p.cycle = id[ATA_ID_EIDE_DMA_MIN];
3342
3343                 ata_timing_merge(&p, t, t, ATA_TIMING_CYCLE | ATA_TIMING_CYC8B);
3344         }
3345
3346         /*
3347          * Convert the timing to bus clock counts.
3348          */
3349
3350         ata_timing_quantize(t, t, T, UT);
3351
3352         /*
3353          * Even in DMA/UDMA modes we still use PIO access for IDENTIFY,
3354          * S.M.A.R.T * and some other commands. We have to ensure that the
3355          * DMA cycle timing is slower/equal than the fastest PIO timing.
3356          */
3357
3358         if (speed > XFER_PIO_6) {
3359                 ata_timing_compute(adev, adev->pio_mode, &p, T, UT);
3360                 ata_timing_merge(&p, t, t, ATA_TIMING_ALL);
3361         }
3362
3363         /*
3364          * Lengthen active & recovery time so that cycle time is correct.
3365          */
3366
3367         if (t->act8b + t->rec8b < t->cyc8b) {
3368                 t->act8b += (t->cyc8b - (t->act8b + t->rec8b)) / 2;
3369                 t->rec8b = t->cyc8b - t->act8b;
3370         }
3371
3372         if (t->active + t->recover < t->cycle) {
3373                 t->active += (t->cycle - (t->active + t->recover)) / 2;
3374                 t->recover = t->cycle - t->active;
3375         }
3376
3377         /* In a few cases quantisation may produce enough errors to
3378            leave t->cycle too low for the sum of active and recovery
3379            if so we must correct this */
3380         if (t->active + t->recover > t->cycle)
3381                 t->cycle = t->active + t->recover;
3382
3383         return 0;
3384 }
3385
3386 /**
3387  *      ata_timing_cycle2mode - find xfer mode for the specified cycle duration
3388  *      @xfer_shift: ATA_SHIFT_* value for transfer type to examine.
3389  *      @cycle: cycle duration in ns
3390  *
3391  *      Return matching xfer mode for @cycle.  The returned mode is of
3392  *      the transfer type specified by @xfer_shift.  If @cycle is too
3393  *      slow for @xfer_shift, 0xff is returned.  If @cycle is faster
3394  *      than the fastest known mode, the fasted mode is returned.
3395  *
3396  *      LOCKING:
3397  *      None.
3398  *
3399  *      RETURNS:
3400  *      Matching xfer_mode, 0xff if no match found.
3401  */
3402 u8 ata_timing_cycle2mode(unsigned int xfer_shift, int cycle)
3403 {
3404         u8 base_mode = 0xff, last_mode = 0xff;
3405         const struct ata_xfer_ent *ent;
3406         const struct ata_timing *t;
3407
3408         for (ent = ata_xfer_tbl; ent->shift >= 0; ent++)
3409                 if (ent->shift == xfer_shift)
3410                         base_mode = ent->base;
3411
3412         for (t = ata_timing_find_mode(base_mode);
3413              t && ata_xfer_mode2shift(t->mode) == xfer_shift; t++) {
3414                 unsigned short this_cycle;
3415
3416                 switch (xfer_shift) {
3417                 case ATA_SHIFT_PIO:
3418                 case ATA_SHIFT_MWDMA:
3419                         this_cycle = t->cycle;
3420                         break;
3421                 case ATA_SHIFT_UDMA:
3422                         this_cycle = t->udma;
3423                         break;
3424                 default:
3425                         return 0xff;
3426                 }
3427
3428                 if (cycle > this_cycle)
3429                         break;
3430
3431                 last_mode = t->mode;
3432         }
3433
3434         return last_mode;
3435 }
3436
3437 /**
3438  *      ata_down_xfermask_limit - adjust dev xfer masks downward
3439  *      @dev: Device to adjust xfer masks
3440  *      @sel: ATA_DNXFER_* selector
3441  *
3442  *      Adjust xfer masks of @dev downward.  Note that this function
3443  *      does not apply the change.  Invoking ata_set_mode() afterwards
3444  *      will apply the limit.
3445  *
3446  *      LOCKING:
3447  *      Inherited from caller.
3448  *
3449  *      RETURNS:
3450  *      0 on success, negative errno on failure
3451  */
3452 int ata_down_xfermask_limit(struct ata_device *dev, unsigned int sel)
3453 {
3454         char buf[32];
3455         unsigned long orig_mask, xfer_mask;
3456         unsigned long pio_mask, mwdma_mask, udma_mask;
3457         int quiet, highbit;
3458
3459         quiet = !!(sel & ATA_DNXFER_QUIET);
3460         sel &= ~ATA_DNXFER_QUIET;
3461
3462         xfer_mask = orig_mask = ata_pack_xfermask(dev->pio_mask,
3463                                                   dev->mwdma_mask,
3464                                                   dev->udma_mask);
3465         ata_unpack_xfermask(xfer_mask, &pio_mask, &mwdma_mask, &udma_mask);
3466
3467         switch (sel) {
3468         case ATA_DNXFER_PIO:
3469                 highbit = fls(pio_mask) - 1;
3470                 pio_mask &= ~(1 << highbit);
3471                 break;
3472
3473         case ATA_DNXFER_DMA:
3474                 if (udma_mask) {
3475                         highbit = fls(udma_mask) - 1;
3476                         udma_mask &= ~(1 << highbit);
3477                         if (!udma_mask)
3478                                 return -ENOENT;
3479                 } else if (mwdma_mask) {
3480                         highbit = fls(mwdma_mask) - 1;
3481                         mwdma_mask &= ~(1 << highbit);
3482                         if (!mwdma_mask)
3483                                 return -ENOENT;
3484                 }
3485                 break;
3486
3487         case ATA_DNXFER_40C:
3488                 udma_mask &= ATA_UDMA_MASK_40C;
3489                 break;
3490
3491         case ATA_DNXFER_FORCE_PIO0:
3492                 pio_mask &= 1;
3493         case ATA_DNXFER_FORCE_PIO:
3494                 mwdma_mask = 0;
3495                 udma_mask = 0;
3496                 break;
3497
3498         default:
3499                 BUG();
3500         }
3501
3502         xfer_mask &= ata_pack_xfermask(pio_mask, mwdma_mask, udma_mask);
3503
3504         if (!(xfer_mask & ATA_MASK_PIO) || xfer_mask == orig_mask)
3505                 return -ENOENT;
3506
3507         if (!quiet) {
3508                 if (xfer_mask & (ATA_MASK_MWDMA | ATA_MASK_UDMA))
3509                         snprintf(buf, sizeof(buf), "%s:%s",
3510                                  ata_mode_string(xfer_mask),
3511                                  ata_mode_string(xfer_mask & ATA_MASK_PIO));
3512                 else
3513                         snprintf(buf, sizeof(buf), "%s",
3514                                  ata_mode_string(xfer_mask));
3515
3516                 ata_dev_warn(dev, "limiting speed to %s\n", buf);
3517         }
3518
3519         ata_unpack_xfermask(xfer_mask, &dev->pio_mask, &dev->mwdma_mask,
3520                             &dev->udma_mask);
3521
3522         return 0;
3523 }
3524
3525 static int ata_dev_set_mode(struct ata_device *dev)
3526 {
3527         struct ata_port *ap = dev->link->ap;
3528         struct ata_eh_context *ehc = &dev->link->eh_context;
3529         const bool nosetxfer = dev->horkage & ATA_HORKAGE_NOSETXFER;
3530         const char *dev_err_whine = "";
3531         int ign_dev_err = 0;
3532         unsigned int err_mask = 0;
3533         int rc;
3534
3535         dev->flags &= ~ATA_DFLAG_PIO;
3536         if (dev->xfer_shift == ATA_SHIFT_PIO)
3537                 dev->flags |= ATA_DFLAG_PIO;
3538
3539         if (nosetxfer && ap->flags & ATA_FLAG_SATA && ata_id_is_sata(dev->id))
3540                 dev_err_whine = " (SET_XFERMODE skipped)";
3541         else {
3542                 if (nosetxfer)
3543                         ata_dev_warn(dev,
3544                                      "NOSETXFER but PATA detected - can't "
3545                                      "skip SETXFER, might malfunction\n");
3546                 err_mask = ata_dev_set_xfermode(dev);
3547         }
3548
3549         if (err_mask & ~AC_ERR_DEV)
3550                 goto fail;
3551
3552         /* revalidate */
3553         ehc->i.flags |= ATA_EHI_POST_SETMODE;
3554         rc = ata_dev_revalidate(dev, ATA_DEV_UNKNOWN, 0);
3555         ehc->i.flags &= ~ATA_EHI_POST_SETMODE;
3556         if (rc)
3557                 return rc;
3558
3559         if (dev->xfer_shift == ATA_SHIFT_PIO) {
3560                 /* Old CFA may refuse this command, which is just fine */
3561                 if (ata_id_is_cfa(dev->id))
3562                         ign_dev_err = 1;
3563                 /* Catch several broken garbage emulations plus some pre
3564                    ATA devices */
3565                 if (ata_id_major_version(dev->id) == 0 &&
3566                                         dev->pio_mode <= XFER_PIO_2)
3567                         ign_dev_err = 1;
3568                 /* Some very old devices and some bad newer ones fail
3569                    any kind of SET_XFERMODE request but support PIO0-2
3570                    timings and no IORDY */
3571                 if (!ata_id_has_iordy(dev->id) && dev->pio_mode <= XFER_PIO_2)
3572                         ign_dev_err = 1;
3573         }
3574         /* Early MWDMA devices do DMA but don't allow DMA mode setting.
3575            Don't fail an MWDMA0 set IFF the device indicates it is in MWDMA0 */
3576         if (dev->xfer_shift == ATA_SHIFT_MWDMA &&
3577             dev->dma_mode == XFER_MW_DMA_0 &&
3578             (dev->id[63] >> 8) & 1)
3579                 ign_dev_err = 1;
3580
3581         /* if the device is actually configured correctly, ignore dev err */
3582         if (dev->xfer_mode == ata_xfer_mask2mode(ata_id_xfermask(dev->id)))
3583                 ign_dev_err = 1;
3584
3585         if (err_mask & AC_ERR_DEV) {
3586                 if (!ign_dev_err)
3587                         goto fail;
3588                 else
3589                         dev_err_whine = " (device error ignored)";
3590         }
3591
3592         DPRINTK("xfer_shift=%u, xfer_mode=0x%x\n",
3593                 dev->xfer_shift, (int)dev->xfer_mode);
3594
3595         ata_dev_info(dev, "configured for %s%s\n",
3596                      ata_mode_string(ata_xfer_mode2mask(dev->xfer_mode)),
3597                      dev_err_whine);
3598
3599         return 0;
3600
3601  fail:
3602         ata_dev_err(dev, "failed to set xfermode (err_mask=0x%x)\n", err_mask);
3603         return -EIO;
3604 }
3605
3606 /**
3607  *      ata_do_set_mode - Program timings and issue SET FEATURES - XFER
3608  *      @link: link on which timings will be programmed
3609  *      @r_failed_dev: out parameter for failed device
3610  *
3611  *      Standard implementation of the function used to tune and set
3612  *      ATA device disk transfer mode (PIO3, UDMA6, etc.).  If
3613  *      ata_dev_set_mode() fails, pointer to the failing device is
3614  *      returned in @r_failed_dev.
3615  *
3616  *      LOCKING:
3617  *      PCI/etc. bus probe sem.
3618  *
3619  *      RETURNS:
3620  *      0 on success, negative errno otherwise
3621  */
3622
3623 int ata_do_set_mode(struct ata_link *link, struct ata_device **r_failed_dev)
3624 {
3625         struct ata_port *ap = link->ap;
3626         struct ata_device *dev;
3627         int rc = 0, used_dma = 0, found = 0;
3628
3629         /* step 1: calculate xfer_mask */
3630         ata_for_each_dev(dev, link, ENABLED) {
3631                 unsigned long pio_mask, dma_mask;
3632                 unsigned int mode_mask;
3633
3634                 mode_mask = ATA_DMA_MASK_ATA;
3635                 if (dev->class == ATA_DEV_ATAPI)
3636                         mode_mask = ATA_DMA_MASK_ATAPI;
3637                 else if (ata_id_is_cfa(dev->id))
3638                         mode_mask = ATA_DMA_MASK_CFA;
3639
3640                 ata_dev_xfermask(dev);
3641                 ata_force_xfermask(dev);
3642
3643                 pio_mask = ata_pack_xfermask(dev->pio_mask, 0, 0);
3644
3645                 if (libata_dma_mask & mode_mask)
3646                         dma_mask = ata_pack_xfermask(0, dev->mwdma_mask,
3647                                                      dev->udma_mask);
3648                 else
3649                         dma_mask = 0;
3650
3651                 dev->pio_mode = ata_xfer_mask2mode(pio_mask);
3652                 dev->dma_mode = ata_xfer_mask2mode(dma_mask);
3653
3654                 found = 1;
3655                 if (ata_dma_enabled(dev))
3656                         used_dma = 1;
3657         }
3658         if (!found)
3659                 goto out;
3660
3661         /* step 2: always set host PIO timings */
3662         ata_for_each_dev(dev, link, ENABLED) {
3663                 if (dev->pio_mode == 0xff) {
3664                         ata_dev_warn(dev, "no PIO support\n");
3665                         rc = -EINVAL;
3666                         goto out;
3667                 }
3668
3669                 dev->xfer_mode = dev->pio_mode;
3670                 dev->xfer_shift = ATA_SHIFT_PIO;
3671                 if (ap->ops->set_piomode)
3672                         ap->ops->set_piomode(ap, dev);
3673         }
3674
3675         /* step 3: set host DMA timings */
3676         ata_for_each_dev(dev, link, ENABLED) {
3677                 if (!ata_dma_enabled(dev))
3678                         continue;
3679
3680                 dev->xfer_mode = dev->dma_mode;
3681                 dev->xfer_shift = ata_xfer_mode2shift(dev->dma_mode);
3682                 if (ap->ops->set_dmamode)
3683                         ap->ops->set_dmamode(ap, dev);
3684         }
3685
3686         /* step 4: update devices' xfer mode */
3687         ata_for_each_dev(dev, link, ENABLED) {
3688                 rc = ata_dev_set_mode(dev);
3689                 if (rc)
3690                         goto out;
3691         }
3692
3693         /* Record simplex status. If we selected DMA then the other
3694          * host channels are not permitted to do so.
3695          */
3696         if (used_dma && (ap->host->flags & ATA_HOST_SIMPLEX))
3697                 ap->host->simplex_claimed = ap;
3698
3699  out:
3700         if (rc)
3701                 *r_failed_dev = dev;
3702         return rc;
3703 }
3704
3705 /**
3706  *      ata_wait_ready - wait for link to become ready
3707  *      @link: link to be waited on
3708  *      @deadline: deadline jiffies for the operation
3709  *      @check_ready: callback to check link readiness
3710  *
3711  *      Wait for @link to become ready.  @check_ready should return
3712  *      positive number if @link is ready, 0 if it isn't, -ENODEV if
3713  *      link doesn't seem to be occupied, other errno for other error
3714  *      conditions.
3715  *
3716  *      Transient -ENODEV conditions are allowed for
3717  *      ATA_TMOUT_FF_WAIT.
3718  *
3719  *      LOCKING:
3720  *      EH context.
3721  *
3722  *      RETURNS:
3723  *      0 if @link is ready before @deadline; otherwise, -errno.
3724  */
3725 int ata_wait_ready(struct ata_link *link, unsigned long deadline,
3726                    int (*check_ready)(struct ata_link *link))
3727 {
3728         unsigned long start = jiffies;
3729         unsigned long nodev_deadline;
3730         int warned = 0;
3731
3732         /* choose which 0xff timeout to use, read comment in libata.h */
3733         if (link->ap->host->flags & ATA_HOST_PARALLEL_SCAN)
3734                 nodev_deadline = ata_deadline(start, ATA_TMOUT_FF_WAIT_LONG);
3735         else
3736                 nodev_deadline = ata_deadline(start, ATA_TMOUT_FF_WAIT);
3737
3738         /* Slave readiness can't be tested separately from master.  On
3739          * M/S emulation configuration, this function should be called
3740          * only on the master and it will handle both master and slave.
3741          */
3742         WARN_ON(link == link->ap->slave_link);
3743
3744         if (time_after(nodev_deadline, deadline))
3745                 nodev_deadline = deadline;
3746
3747         while (1) {
3748                 unsigned long now = jiffies;
3749                 int ready, tmp;
3750
3751                 ready = tmp = check_ready(link);
3752                 if (ready > 0)
3753                         return 0;
3754
3755                 /*
3756                  * -ENODEV could be transient.  Ignore -ENODEV if link
3757                  * is online.  Also, some SATA devices take a long
3758                  * time to clear 0xff after reset.  Wait for
3759                  * ATA_TMOUT_FF_WAIT[_LONG] on -ENODEV if link isn't
3760                  * offline.
3761                  *
3762                  * Note that some PATA controllers (pata_ali) explode
3763                  * if status register is read more than once when
3764                  * there's no device attached.
3765                  */
3766                 if (ready == -ENODEV) {
3767                         if (ata_link_online(link))
3768                                 ready = 0;
3769                         else if ((link->ap->flags & ATA_FLAG_SATA) &&
3770                                  !ata_link_offline(link) &&
3771                                  time_before(now, nodev_deadline))
3772                                 ready = 0;
3773                 }
3774
3775                 if (ready)
3776                         return ready;
3777                 if (time_after(now, deadline))
3778                         return -EBUSY;
3779
3780                 if (!warned && time_after(now, start + 5 * HZ) &&
3781                     (deadline - now > 3 * HZ)) {
3782                         ata_link_warn(link,
3783                                 "link is slow to respond, please be patient "
3784                                 "(ready=%d)\n", tmp);
3785                         warned = 1;
3786                 }
3787
3788                 ata_msleep(link->ap, 50);
3789         }
3790 }
3791
3792 /**
3793  *      ata_wait_after_reset - wait for link to become ready after reset
3794  *      @link: link to be waited on
3795  *      @deadline: deadline jiffies for the operation
3796  *      @check_ready: callback to check link readiness
3797  *
3798  *      Wait for @link to become ready after reset.
3799  *
3800  *      LOCKING:
3801  *      EH context.
3802  *
3803  *      RETURNS:
3804  *      0 if @link is ready before @deadline; otherwise, -errno.
3805  */
3806 int ata_wait_after_reset(struct ata_link *link, unsigned long deadline,
3807                                 int (*check_ready)(struct ata_link *link))
3808 {
3809         ata_msleep(link->ap, ATA_WAIT_AFTER_RESET);
3810
3811         return ata_wait_ready(link, deadline, check_ready);
3812 }
3813
3814 /**
3815  *      sata_link_debounce - debounce SATA phy status
3816  *      @link: ATA link to debounce SATA phy status for
3817  *      @params: timing parameters { interval, duration, timeout } in msec
3818  *      @deadline: deadline jiffies for the operation
3819  *
3820  *      Make sure SStatus of @link reaches stable state, determined by
3821  *      holding the same value where DET is not 1 for @duration polled
3822  *      every @interval, before @timeout.  Timeout constraints the
3823  *      beginning of the stable state.  Because DET gets stuck at 1 on
3824  *      some controllers after hot unplugging, this functions waits
3825  *      until timeout then returns 0 if DET is stable at 1.
3826  *
3827  *      @timeout is further limited by @deadline.  The sooner of the
3828  *      two is used.
3829  *
3830  *      LOCKING:
3831  *      Kernel thread context (may sleep)
3832  *
3833  *      RETURNS:
3834  *      0 on success, -errno on failure.
3835  */
3836 int sata_link_debounce(struct ata_link *link, const unsigned long *params,
3837                        unsigned long deadline)
3838 {
3839         unsigned long interval = params[0];
3840         unsigned long duration = params[1];
3841         unsigned long last_jiffies, t;
3842         u32 last, cur;
3843         int rc;
3844
3845         t = ata_deadline(jiffies, params[2]);
3846         if (time_before(t, deadline))
3847                 deadline = t;
3848
3849         if ((rc = sata_scr_read(link, SCR_STATUS, &cur)))
3850                 return rc;
3851         cur &= 0xf;
3852
3853         last = cur;
3854         last_jiffies = jiffies;
3855
3856         while (1) {
3857                 ata_msleep(link->ap, interval);
3858                 if ((rc = sata_scr_read(link, SCR_STATUS, &cur)))
3859                         return rc;
3860                 cur &= 0xf;
3861
3862                 /* DET stable? */
3863                 if (cur == last) {
3864                         if (cur == 1 && time_before(jiffies, deadline))
3865                                 continue;
3866                         if (time_after(jiffies,
3867                                        ata_deadline(last_jiffies, duration)))
3868                                 return 0;
3869                         continue;
3870                 }
3871
3872                 /* unstable, start over */
3873                 last = cur;
3874                 last_jiffies = jiffies;
3875
3876                 /* Check deadline.  If debouncing failed, return
3877                  * -EPIPE to tell upper layer to lower link speed.
3878                  */
3879                 if (time_after(jiffies, deadline))
3880                         return -EPIPE;
3881         }
3882 }
3883
3884 /**
3885  *      sata_link_resume - resume SATA link
3886  *      @link: ATA link to resume SATA
3887  *      @params: timing parameters { interval, duration, timeout } in msec
3888  *      @deadline: deadline jiffies for the operation
3889  *
3890  *      Resume SATA phy @link and debounce it.
3891  *
3892  *      LOCKING:
3893  *      Kernel thread context (may sleep)
3894  *
3895  *      RETURNS:
3896  *      0 on success, -errno on failure.
3897  */
3898 int sata_link_resume(struct ata_link *link, const unsigned long *params,
3899                      unsigned long deadline)
3900 {
3901         int tries = ATA_LINK_RESUME_TRIES;
3902         u32 scontrol, serror;
3903         int rc;
3904
3905         if ((rc = sata_scr_read(link, SCR_CONTROL, &scontrol)))
3906                 return rc;
3907
3908         /*
3909          * Writes to SControl sometimes get ignored under certain
3910          * controllers (ata_piix SIDPR).  Make sure DET actually is
3911          * cleared.
3912          */
3913         do {
3914                 scontrol = (scontrol & 0x0f0) | 0x300;
3915                 if ((rc = sata_scr_write(link, SCR_CONTROL, scontrol)))
3916                         return rc;
3917                 /*
3918                  * Some PHYs react badly if SStatus is pounded
3919                  * immediately after resuming.  Delay 200ms before
3920                  * debouncing.
3921                  */
3922                 if (!(link->flags & ATA_LFLAG_NO_DB_DELAY))
3923                         ata_msleep(link->ap, 200);
3924
3925                 /* is SControl restored correctly? */
3926                 if ((rc = sata_scr_read(link, SCR_CONTROL, &scontrol)))
3927                         return rc;
3928         } while ((scontrol & 0xf0f) != 0x300 && --tries);
3929
3930         if ((scontrol & 0xf0f) != 0x300) {
3931                 ata_link_warn(link, "failed to resume link (SControl %X)\n",
3932                              scontrol);
3933                 return 0;
3934         }
3935
3936         if (tries < ATA_LINK_RESUME_TRIES)
3937                 ata_link_warn(link, "link resume succeeded after %d retries\n",
3938                               ATA_LINK_RESUME_TRIES - tries);
3939
3940         if ((rc = sata_link_debounce(link, params, deadline)))
3941                 return rc;
3942
3943         /* clear SError, some PHYs require this even for SRST to work */
3944         if (!(rc = sata_scr_read(link, SCR_ERROR, &serror)))
3945                 rc = sata_scr_write(link, SCR_ERROR, serror);
3946
3947         return rc != -EINVAL ? rc : 0;
3948 }
3949
3950 /**
3951  *      sata_link_scr_lpm - manipulate SControl IPM and SPM fields
3952  *      @link: ATA link to manipulate SControl for
3953  *      @policy: LPM policy to configure
3954  *      @spm_wakeup: initiate LPM transition to active state
3955  *
3956  *      Manipulate the IPM field of the SControl register of @link
3957  *      according to @policy.  If @policy is ATA_LPM_MAX_POWER and
3958  *      @spm_wakeup is %true, the SPM field is manipulated to wake up
3959  *      the link.  This function also clears PHYRDY_CHG before
3960  *      returning.
3961  *
3962  *      LOCKING:
3963  *      EH context.
3964  *
3965  *      RETURNS:
3966  *      0 on success, -errno otherwise.
3967  */
3968 int sata_link_scr_lpm(struct ata_link *link, enum ata_lpm_policy policy,
3969                       bool spm_wakeup)
3970 {
3971         struct ata_eh_context *ehc = &link->eh_context;
3972         bool woken_up = false;
3973         u32 scontrol;
3974         int rc;
3975
3976         rc = sata_scr_read(link, SCR_CONTROL, &scontrol);
3977         if (rc)
3978                 return rc;
3979
3980         switch (policy) {
3981         case ATA_LPM_MAX_POWER:
3982                 /* disable all LPM transitions */
3983                 scontrol |= (0x7 << 8);
3984                 /* initiate transition to active state */
3985                 if (spm_wakeup) {
3986                         scontrol |= (0x4 << 12);
3987                         woken_up = true;
3988                 }
3989                 break;
3990         case ATA_LPM_MED_POWER:
3991                 /* allow LPM to PARTIAL */
3992                 scontrol &= ~(0x1 << 8);
3993                 scontrol |= (0x6 << 8);
3994                 break;
3995         case ATA_LPM_MIN_POWER:
3996                 if (ata_link_nr_enabled(link) > 0) {
3997                         /* assume no restrictions on LPM transitions */
3998                         scontrol &= ~(0x7 << 8);
3999
4000                         /*
4001                          * If the controller does not support partial, slumber,
4002                          * or devsleep, then disallow these transitions.
4003                          */
4004                         if (link->ap->host->flags & ATA_HOST_NO_PART)
4005                                 scontrol |= (0x1 << 8);
4006
4007                         if (link->ap->host->flags & ATA_HOST_NO_SSC)
4008                                 scontrol |= (0x2 << 8);
4009
4010                         if (link->ap->host->flags & ATA_HOST_NO_DEVSLP)
4011                                 scontrol |= (0x4 << 8);
4012                 } else {
4013                         /* empty port, power off */
4014                         scontrol &= ~0xf;
4015                         scontrol |= (0x1 << 2);
4016                 }
4017                 break;
4018         default:
4019                 WARN_ON(1);
4020         }
4021
4022         rc = sata_scr_write(link, SCR_CONTROL, scontrol);
4023         if (rc)
4024                 return rc;
4025
4026         /* give the link time to transit out of LPM state */
4027         if (woken_up)
4028                 msleep(10);
4029
4030         /* clear PHYRDY_CHG from SError */
4031         ehc->i.serror &= ~SERR_PHYRDY_CHG;
4032         return sata_scr_write(link, SCR_ERROR, SERR_PHYRDY_CHG);
4033 }
4034
4035 /**
4036  *      ata_std_prereset - prepare for reset
4037  *      @link: ATA link to be reset
4038  *      @deadline: deadline jiffies for the operation
4039  *
4040  *      @link is about to be reset.  Initialize it.  Failure from
4041  *      prereset makes libata abort whole reset sequence and give up
4042  *      that port, so prereset should be best-effort.  It does its
4043  *      best to prepare for reset sequence but if things go wrong, it
4044  *      should just whine, not fail.
4045  *
4046  *      LOCKING:
4047  *      Kernel thread context (may sleep)
4048  *
4049  *      RETURNS:
4050  *      0 on success, -errno otherwise.
4051  */
4052 int ata_std_prereset(struct ata_link *link, unsigned long deadline)
4053 {
4054         struct ata_port *ap = link->ap;
4055         struct ata_eh_context *ehc = &link->eh_context;
4056         const unsigned long *timing = sata_ehc_deb_timing(ehc);
4057         int rc;
4058
4059         /* if we're about to do hardreset, nothing more to do */
4060         if (ehc->i.action & ATA_EH_HARDRESET)
4061                 return 0;
4062
4063         /* if SATA, resume link */
4064         if (ap->flags & ATA_FLAG_SATA) {
4065                 rc = sata_link_resume(link, timing, deadline);
4066                 /* whine about phy resume failure but proceed */
4067                 if (rc && rc != -EOPNOTSUPP)
4068                         ata_link_warn(link,
4069                                       "failed to resume link for reset (errno=%d)\n",
4070                                       rc);
4071         }
4072
4073         /* no point in trying softreset on offline link */
4074         if (ata_phys_link_offline(link))
4075                 ehc->i.action &= ~ATA_EH_SOFTRESET;
4076
4077         return 0;
4078 }
4079
4080 /**
4081  *      sata_link_hardreset - reset link via SATA phy reset
4082  *      @link: link to reset
4083  *      @timing: timing parameters { interval, duration, timeout } in msec
4084  *      @deadline: deadline jiffies for the operation
4085  *      @online: optional out parameter indicating link onlineness
4086  *      @check_ready: optional callback to check link readiness
4087  *
4088  *      SATA phy-reset @link using DET bits of SControl register.
4089  *      After hardreset, link readiness is waited upon using
4090  *      ata_wait_ready() if @check_ready is specified.  LLDs are
4091  *      allowed to not specify @check_ready and wait itself after this
4092  *      function returns.  Device classification is LLD's
4093  *      responsibility.
4094  *
4095  *      *@online is set to one iff reset succeeded and @link is online
4096  *      after reset.
4097  *
4098  *      LOCKING:
4099  *      Kernel thread context (may sleep)
4100  *
4101  *      RETURNS:
4102  *      0 on success, -errno otherwise.
4103  */
4104 int sata_link_hardreset(struct ata_link *link, const unsigned long *timing,
4105                         unsigned long deadline,
4106                         bool *online, int (*check_ready)(struct ata_link *))
4107 {
4108         u32 scontrol;
4109         int rc;
4110
4111         DPRINTK("ENTER\n");
4112
4113         if (online)
4114                 *online = false;
4115
4116         if (sata_set_spd_needed(link)) {
4117                 /* SATA spec says nothing about how to reconfigure
4118                  * spd.  To be on the safe side, turn off phy during
4119                  * reconfiguration.  This works for at least ICH7 AHCI
4120                  * and Sil3124.
4121                  */
4122                 if ((rc = sata_scr_read(link, SCR_CONTROL, &scontrol)))
4123                         goto out;
4124
4125                 scontrol = (scontrol & 0x0f0) | 0x304;
4126
4127                 if ((rc = sata_scr_write(link, SCR_CONTROL, scontrol)))
4128                         goto out;
4129
4130                 sata_set_spd(link);
4131         }
4132
4133         /* issue phy wake/reset */
4134         if ((rc = sata_scr_read(link, SCR_CONTROL, &scontrol)))
4135                 goto out;
4136
4137         scontrol = (scontrol & 0x0f0) | 0x301;
4138
4139         if ((rc = sata_scr_write_flush(link, SCR_CONTROL, scontrol)))
4140                 goto out;
4141
4142         /* Couldn't find anything in SATA I/II specs, but AHCI-1.1
4143          * 10.4.2 says at least 1 ms.
4144          */
4145         ata_msleep(link->ap, 1);
4146
4147         /* bring link back */
4148         rc = sata_link_resume(link, timing, deadline);
4149         if (rc)
4150                 goto out;
4151         /* if link is offline nothing more to do */
4152         if (ata_phys_link_offline(link))
4153                 goto out;
4154
4155         /* Link is online.  From this point, -ENODEV too is an error. */
4156         if (online)
4157                 *online = true;
4158
4159         if (sata_pmp_supported(link->ap) && ata_is_host_link(link)) {
4160                 /* If PMP is supported, we have to do follow-up SRST.
4161                  * Some PMPs don't send D2H Reg FIS after hardreset if
4162                  * the first port is empty.  Wait only for
4163                  * ATA_TMOUT_PMP_SRST_WAIT.
4164                  */
4165                 if (check_ready) {
4166                         unsigned long pmp_deadline;
4167
4168                         pmp_deadline = ata_deadline(jiffies,
4169                                                     ATA_TMOUT_PMP_SRST_WAIT);
4170                         if (time_after(pmp_deadline, deadline))
4171                                 pmp_deadline = deadline;
4172                         ata_wait_ready(link, pmp_deadline, check_ready);
4173                 }
4174                 rc = -EAGAIN;
4175                 goto out;
4176         }
4177
4178         rc = 0;
4179         if (check_ready)
4180                 rc = ata_wait_ready(link, deadline, check_ready);
4181  out:
4182         if (rc && rc != -EAGAIN) {
4183                 /* online is set iff link is online && reset succeeded */
4184                 if (online)
4185                         *online = false;
4186                 ata_link_err(link, "COMRESET failed (errno=%d)\n", rc);
4187         }
4188         DPRINTK("EXIT, rc=%d\n", rc);
4189         return rc;
4190 }
4191
4192 /**
4193  *      sata_std_hardreset - COMRESET w/o waiting or classification
4194  *      @link: link to reset
4195  *      @class: resulting class of attached device
4196  *      @deadline: deadline jiffies for the operation
4197  *
4198  *      Standard SATA COMRESET w/o waiting or classification.
4199  *
4200  *      LOCKING:
4201  *      Kernel thread context (may sleep)
4202  *
4203  *      RETURNS:
4204  *      0 if link offline, -EAGAIN if link online, -errno on errors.
4205  */
4206 int sata_std_hardreset(struct ata_link *link, unsigned int *class,
4207                        unsigned long deadline)
4208 {
4209         const unsigned long *timing = sata_ehc_deb_timing(&link->eh_context);
4210         bool online;
4211         int rc;
4212
4213         /* do hardreset */
4214         rc = sata_link_hardreset(link, timing, deadline, &online, NULL);
4215         return online ? -EAGAIN : rc;
4216 }
4217
4218 /**
4219  *      ata_std_postreset - standard postreset callback
4220  *      @link: the target ata_link
4221  *      @classes: classes of attached devices
4222  *
4223  *      This function is invoked after a successful reset.  Note that
4224  *      the device might have been reset more than once using
4225  *      different reset methods before postreset is invoked.
4226  *
4227  *      LOCKING:
4228  *      Kernel thread context (may sleep)
4229  */
4230 void ata_std_postreset(struct ata_link *link, unsigned int *classes)
4231 {
4232         u32 serror;
4233
4234         DPRINTK("ENTER\n");
4235
4236         /* reset complete, clear SError */
4237         if (!sata_scr_read(link, SCR_ERROR, &serror))
4238                 sata_scr_write(link, SCR_ERROR, serror);
4239
4240         /* print link status */
4241         sata_print_link_status(link);
4242
4243         DPRINTK("EXIT\n");
4244 }
4245
4246 /**
4247  *      ata_dev_same_device - Determine whether new ID matches configured device
4248  *      @dev: device to compare against
4249  *      @new_class: class of the new device
4250  *      @new_id: IDENTIFY page of the new device
4251  *
4252  *      Compare @new_class and @new_id against @dev and determine
4253  *      whether @dev is the device indicated by @new_class and
4254  *      @new_id.
4255  *
4256  *      LOCKING:
4257  *      None.
4258  *
4259  *      RETURNS:
4260  *      1 if @dev matches @new_class and @new_id, 0 otherwise.
4261  */
4262 static int ata_dev_same_device(struct ata_device *dev, unsigned int new_class,
4263                                const u16 *new_id)
4264 {
4265         const u16 *old_id = dev->id;
4266         unsigned char model[2][ATA_ID_PROD_LEN + 1];
4267         unsigned char serial[2][ATA_ID_SERNO_LEN + 1];
4268
4269         if (dev->class != new_class) {
4270                 ata_dev_info(dev, "class mismatch %d != %d\n",
4271                              dev->class, new_class);
4272                 return 0;
4273         }
4274
4275         ata_id_c_string(old_id, model[0], ATA_ID_PROD, sizeof(model[0]));
4276         ata_id_c_string(new_id, model[1], ATA_ID_PROD, sizeof(model[1]));
4277         ata_id_c_string(old_id, serial[0], ATA_ID_SERNO, sizeof(serial[0]));
4278         ata_id_c_string(new_id, serial[1], ATA_ID_SERNO, sizeof(serial[1]));
4279
4280         if (strcmp(model[0], model[1])) {
4281                 ata_dev_info(dev, "model number mismatch '%s' != '%s'\n",
4282                              model[0], model[1]);
4283                 return 0;
4284         }
4285
4286         if (strcmp(serial[0], serial[1])) {
4287                 ata_dev_info(dev, "serial number mismatch '%s' != '%s'\n",
4288                              serial[0], serial[1]);
4289                 return 0;
4290         }
4291
4292         return 1;
4293 }
4294
4295 /**
4296  *      ata_dev_reread_id - Re-read IDENTIFY data
4297  *      @dev: target ATA device
4298  *      @readid_flags: read ID flags
4299  *
4300  *      Re-read IDENTIFY page and make sure @dev is still attached to
4301  *      the port.
4302  *
4303  *      LOCKING:
4304  *      Kernel thread context (may sleep)
4305  *
4306  *      RETURNS:
4307  *      0 on success, negative errno otherwise
4308  */
4309 int ata_dev_reread_id(struct ata_device *dev, unsigned int readid_flags)
4310 {
4311         unsigned int class = dev->class;
4312         u16 *id = (void *)dev->link->ap->sector_buf;
4313         int rc;
4314
4315         /* read ID data */
4316         rc = ata_dev_read_id(dev, &class, readid_flags, id);
4317         if (rc)
4318                 return rc;
4319
4320         /* is the device still there? */
4321         if (!ata_dev_same_device(dev, class, id))
4322                 return -ENODEV;
4323
4324         memcpy(dev->id, id, sizeof(id[0]) * ATA_ID_WORDS);
4325         return 0;
4326 }
4327
4328 /**
4329  *      ata_dev_revalidate - Revalidate ATA device
4330  *      @dev: device to revalidate
4331  *      @new_class: new class code
4332  *      @readid_flags: read ID flags
4333  *
4334  *      Re-read IDENTIFY page, make sure @dev is still attached to the
4335  *      port and reconfigure it according to the new IDENTIFY page.
4336  *
4337  *      LOCKING:
4338  *      Kernel thread context (may sleep)
4339  *
4340  *      RETURNS:
4341  *      0 on success, negative errno otherwise
4342  */
4343 int ata_dev_revalidate(struct ata_device *dev, unsigned int new_class,
4344                        unsigned int readid_flags)
4345 {
4346         u64 n_sectors = dev->n_sectors;
4347         u64 n_native_sectors = dev->n_native_sectors;
4348         int rc;
4349
4350         if (!ata_dev_enabled(dev))
4351                 return -ENODEV;
4352
4353         /* fail early if !ATA && !ATAPI to avoid issuing [P]IDENTIFY to PMP */
4354         if (ata_class_enabled(new_class) &&
4355             new_class != ATA_DEV_ATA &&
4356             new_class != ATA_DEV_ATAPI &&
4357             new_class != ATA_DEV_ZAC &&
4358             new_class != ATA_DEV_SEMB) {
4359                 ata_dev_info(dev, "class mismatch %u != %u\n",
4360                              dev->class, new_class);
4361                 rc = -ENODEV;
4362                 goto fail;
4363         }
4364
4365         /* re-read ID */
4366         rc = ata_dev_reread_id(dev, readid_flags);
4367         if (rc)
4368                 goto fail;
4369
4370         /* configure device according to the new ID */
4371         rc = ata_dev_configure(dev);
4372         if (rc)
4373                 goto fail;
4374
4375         /* verify n_sectors hasn't changed */
4376         if (dev->class != ATA_DEV_ATA || !n_sectors ||
4377             dev->n_sectors == n_sectors)
4378                 return 0;
4379
4380         /* n_sectors has changed */
4381         ata_dev_warn(dev, "n_sectors mismatch %llu != %llu\n",
4382                      (unsigned long long)n_sectors,
4383                      (unsigned long long)dev->n_sectors);
4384
4385         /*
4386          * Something could have caused HPA to be unlocked
4387          * involuntarily.  If n_native_sectors hasn't changed and the
4388          * new size matches it, keep the device.
4389          */
4390         if (dev->n_native_sectors == n_native_sectors &&
4391             dev->n_sectors > n_sectors && dev->n_sectors == n_native_sectors) {
4392                 ata_dev_warn(dev,
4393                              "new n_sectors matches native, probably "
4394                              "late HPA unlock, n_sectors updated\n");
4395                 /* use the larger n_sectors */
4396                 return 0;
4397         }
4398
4399         /*
4400          * Some BIOSes boot w/o HPA but resume w/ HPA locked.  Try
4401          * unlocking HPA in those cases.
4402          *
4403          * https://bugzilla.kernel.org/show_bug.cgi?id=15396
4404          */
4405         if (dev->n_native_sectors == n_native_sectors &&
4406             dev->n_sectors < n_sectors && n_sectors == n_native_sectors &&
4407             !(dev->horkage & ATA_HORKAGE_BROKEN_HPA)) {
4408                 ata_dev_warn(dev,
4409                              "old n_sectors matches native, probably "
4410                              "late HPA lock, will try to unlock HPA\n");
4411                 /* try unlocking HPA */
4412                 dev->flags |= ATA_DFLAG_UNLOCK_HPA;
4413                 rc = -EIO;
4414         } else
4415                 rc = -ENODEV;
4416
4417         /* restore original n_[native_]sectors and fail */
4418         dev->n_native_sectors = n_native_sectors;
4419         dev->n_sectors = n_sectors;
4420  fail:
4421         ata_dev_err(dev, "revalidation failed (errno=%d)\n", rc);
4422         return rc;
4423 }
4424
4425 struct ata_blacklist_entry {
4426         const char *model_num;
4427         const char *model_rev;
4428         unsigned long horkage;
4429 };
4430
4431 static const struct ata_blacklist_entry ata_device_blacklist [] = {
4432         /* Devices with DMA related problems under Linux */
4433         { "WDC AC11000H",       NULL,           ATA_HORKAGE_NODMA },
4434         { "WDC AC22100H",       NULL,           ATA_HORKAGE_NODMA },
4435         { "WDC AC32500H",       NULL,           ATA_HORKAGE_NODMA },
4436         { "WDC AC33100H",       NULL,           ATA_HORKAGE_NODMA },
4437         { "WDC AC31600H",       NULL,           ATA_HORKAGE_NODMA },
4438         { "WDC AC32100H",       "24.09P07",     ATA_HORKAGE_NODMA },
4439         { "WDC AC23200L",       "21.10N21",     ATA_HORKAGE_NODMA },
4440         { "Compaq CRD-8241B",   NULL,           ATA_HORKAGE_NODMA },
4441         { "CRD-8400B",          NULL,           ATA_HORKAGE_NODMA },
4442         { "CRD-848[02]B",       NULL,           ATA_HORKAGE_NODMA },
4443         { "CRD-84",             NULL,           ATA_HORKAGE_NODMA },
4444         { "SanDisk SDP3B",      NULL,           ATA_HORKAGE_NODMA },
4445         { "SanDisk SDP3B-64",   NULL,           ATA_HORKAGE_NODMA },
4446         { "SANYO CD-ROM CRD",   NULL,           ATA_HORKAGE_NODMA },
4447         { "HITACHI CDR-8",      NULL,           ATA_HORKAGE_NODMA },
4448         { "HITACHI CDR-8[34]35",NULL,           ATA_HORKAGE_NODMA },
4449         { "Toshiba CD-ROM XM-6202B", NULL,      ATA_HORKAGE_NODMA },
4450         { "TOSHIBA CD-ROM XM-1702BC", NULL,     ATA_HORKAGE_NODMA },
4451         { "CD-532E-A",          NULL,           ATA_HORKAGE_NODMA },
4452         { "E-IDE CD-ROM CR-840",NULL,           ATA_HORKAGE_NODMA },
4453         { "CD-ROM Drive/F5A",   NULL,           ATA_HORKAGE_NODMA },
4454         { "WPI CDD-820",        NULL,           ATA_HORKAGE_NODMA },
4455         { "SAMSUNG CD-ROM SC-148C", NULL,       ATA_HORKAGE_NODMA },
4456         { "SAMSUNG CD-ROM SC",  NULL,           ATA_HORKAGE_NODMA },
4457         { "ATAPI CD-ROM DRIVE 40X MAXIMUM",NULL,ATA_HORKAGE_NODMA },
4458         { "_NEC DV5800A",       NULL,           ATA_HORKAGE_NODMA },
4459         { "SAMSUNG CD-ROM SN-124", "N001",      ATA_HORKAGE_NODMA },
4460         { "Seagate STT20000A", NULL,            ATA_HORKAGE_NODMA },
4461         { " 2GB ATA Flash Disk", "ADMA428M",    ATA_HORKAGE_NODMA },
4462         { "VRFDFC22048UCHC-TE*", NULL,          ATA_HORKAGE_NODMA },
4463         /* Odd clown on sil3726/4726 PMPs */
4464         { "Config  Disk",       NULL,           ATA_HORKAGE_DISABLE },
4465         /* Similar story with ASMedia 1092 */
4466         { "ASMT109x- Config",   NULL,           ATA_HORKAGE_DISABLE },
4467
4468         /* Weird ATAPI devices */
4469         { "TORiSAN DVD-ROM DRD-N216", NULL,     ATA_HORKAGE_MAX_SEC_128 },
4470         { "QUANTUM DAT    DAT72-000", NULL,     ATA_HORKAGE_ATAPI_MOD16_DMA },
4471         { "Slimtype DVD A  DS8A8SH", NULL,      ATA_HORKAGE_MAX_SEC_LBA48 },
4472         { "Slimtype DVD A  DS8A9SH", NULL,      ATA_HORKAGE_MAX_SEC_LBA48 },
4473
4474         /*
4475          * Causes silent data corruption with higher max sects.
4476          * http://lkml.kernel.org/g/x49wpy40ysk.fsf@segfault.boston.devel.redhat.com
4477          */
4478         { "ST380013AS",         "3.20",         ATA_HORKAGE_MAX_SEC_1024 },
4479
4480         /*
4481          * These devices time out with higher max sects.
4482          * https://bugzilla.kernel.org/show_bug.cgi?id=121671
4483          */
4484         { "LITEON CX1-JB*-HP",  NULL,           ATA_HORKAGE_MAX_SEC_1024 },
4485         { "LITEON EP1-*",       NULL,           ATA_HORKAGE_MAX_SEC_1024 },
4486
4487         /* Devices we expect to fail diagnostics */
4488
4489         /* Devices where NCQ should be avoided */
4490         /* NCQ is slow */
4491         { "WDC WD740ADFD-00",   NULL,           ATA_HORKAGE_NONCQ },
4492         { "WDC WD740ADFD-00NLR1", NULL,         ATA_HORKAGE_NONCQ, },
4493         /* http://thread.gmane.org/gmane.linux.ide/14907 */
4494         { "FUJITSU MHT2060BH",  NULL,           ATA_HORKAGE_NONCQ },
4495         /* NCQ is broken */
4496         { "Maxtor *",           "BANC*",        ATA_HORKAGE_NONCQ },
4497         { "Maxtor 7V300F0",     "VA111630",     ATA_HORKAGE_NONCQ },
4498         { "ST380817AS",         "3.42",         ATA_HORKAGE_NONCQ },
4499         { "ST3160023AS",        "3.42",         ATA_HORKAGE_NONCQ },
4500         { "OCZ CORE_SSD",       "02.10104",     ATA_HORKAGE_NONCQ },
4501
4502         /* Seagate NCQ + FLUSH CACHE firmware bug */
4503         { "ST31500341AS",       "SD1[5-9]",     ATA_HORKAGE_NONCQ |
4504                                                 ATA_HORKAGE_FIRMWARE_WARN },
4505
4506         { "ST31000333AS",       "SD1[5-9]",     ATA_HORKAGE_NONCQ |
4507                                                 ATA_HORKAGE_FIRMWARE_WARN },
4508
4509         { "ST3640[36]23AS",     "SD1[5-9]",     ATA_HORKAGE_NONCQ |
4510                                                 ATA_HORKAGE_FIRMWARE_WARN },
4511
4512         { "ST3320[68]13AS",     "SD1[5-9]",     ATA_HORKAGE_NONCQ |
4513                                                 ATA_HORKAGE_FIRMWARE_WARN },
4514
4515         /* drives which fail FPDMA_AA activation (some may freeze afterwards)
4516            the ST disks also have LPM issues */
4517         { "ST1000LM024 HN-M101MBB", "2AR10001", ATA_HORKAGE_BROKEN_FPDMA_AA |
4518                                                 ATA_HORKAGE_NOLPM, },
4519         { "ST1000LM024 HN-M101MBB", "2BA30001", ATA_HORKAGE_BROKEN_FPDMA_AA |
4520                                                 ATA_HORKAGE_NOLPM, },
4521         { "VB0250EAVER",        "HPG7",         ATA_HORKAGE_BROKEN_FPDMA_AA },
4522
4523         /* Blacklist entries taken from Silicon Image 3124/3132
4524            Windows driver .inf file - also several Linux problem reports */
4525         { "HTS541060G9SA00",    "MB3OC60D",     ATA_HORKAGE_NONCQ, },
4526         { "HTS541080G9SA00",    "MB4OC60D",     ATA_HORKAGE_NONCQ, },
4527         { "HTS541010G9SA00",    "MBZOC60D",     ATA_HORKAGE_NONCQ, },
4528
4529         /* https://bugzilla.kernel.org/show_bug.cgi?id=15573 */
4530         { "C300-CTFDDAC128MAG", "0001",         ATA_HORKAGE_NONCQ, },
4531
4532         /* Sandisk SD7/8/9s lock up hard on large trims */
4533         { "SanDisk SD[789]*",   NULL,           ATA_HORKAGE_MAX_TRIM_128M, },
4534
4535         /* devices which puke on READ_NATIVE_MAX */
4536         { "HDS724040KLSA80",    "KFAOA20N",     ATA_HORKAGE_BROKEN_HPA, },
4537         { "WDC WD3200JD-00KLB0", "WD-WCAMR1130137", ATA_HORKAGE_BROKEN_HPA },
4538         { "WDC WD2500JD-00HBB0", "WD-WMAL71490727", ATA_HORKAGE_BROKEN_HPA },
4539         { "MAXTOR 6L080L4",     "A93.0500",     ATA_HORKAGE_BROKEN_HPA },
4540
4541         /* this one allows HPA unlocking but fails IOs on the area */
4542         { "OCZ-VERTEX",             "1.30",     ATA_HORKAGE_BROKEN_HPA },
4543
4544         /* Devices which report 1 sector over size HPA */
4545         { "ST340823A",          NULL,           ATA_HORKAGE_HPA_SIZE, },
4546         { "ST320413A",          NULL,           ATA_HORKAGE_HPA_SIZE, },
4547         { "ST310211A",          NULL,           ATA_HORKAGE_HPA_SIZE, },
4548
4549         /* Devices which get the IVB wrong */
4550         { "QUANTUM FIREBALLlct10 05", "A03.0900", ATA_HORKAGE_IVB, },
4551         /* Maybe we should just blacklist TSSTcorp... */
4552         { "TSSTcorp CDDVDW SH-S202[HJN]", "SB0[01]",  ATA_HORKAGE_IVB, },
4553
4554         /* Devices that do not need bridging limits applied */
4555         { "MTRON MSP-SATA*",            NULL,   ATA_HORKAGE_BRIDGE_OK, },
4556         { "BUFFALO HD-QSU2/R5",         NULL,   ATA_HORKAGE_BRIDGE_OK, },
4557
4558         /* Devices which aren't very happy with higher link speeds */
4559         { "WD My Book",                 NULL,   ATA_HORKAGE_1_5_GBPS, },
4560         { "Seagate FreeAgent GoFlex",   NULL,   ATA_HORKAGE_1_5_GBPS, },
4561
4562         /*
4563          * Devices which choke on SETXFER.  Applies only if both the
4564          * device and controller are SATA.
4565          */
4566         { "PIONEER DVD-RW  DVRTD08",    NULL,   ATA_HORKAGE_NOSETXFER },
4567         { "PIONEER DVD-RW  DVRTD08A",   NULL,   ATA_HORKAGE_NOSETXFER },
4568         { "PIONEER DVD-RW  DVR-215",    NULL,   ATA_HORKAGE_NOSETXFER },
4569         { "PIONEER DVD-RW  DVR-212D",   NULL,   ATA_HORKAGE_NOSETXFER },
4570         { "PIONEER DVD-RW  DVR-216D",   NULL,   ATA_HORKAGE_NOSETXFER },
4571
4572         /* Crucial BX100 SSD 500GB has broken LPM support */
4573         { "CT500BX100SSD1",             NULL,   ATA_HORKAGE_NOLPM },
4574
4575         /* 512GB MX100 with MU01 firmware has both queued TRIM and LPM issues */
4576         { "Crucial_CT512MX100*",        "MU01", ATA_HORKAGE_NO_NCQ_TRIM |
4577                                                 ATA_HORKAGE_ZERO_AFTER_TRIM |
4578                                                 ATA_HORKAGE_NOLPM, },
4579         /* 512GB MX100 with newer firmware has only LPM issues */
4580         { "Crucial_CT512MX100*",        NULL,   ATA_HORKAGE_ZERO_AFTER_TRIM |
4581                                                 ATA_HORKAGE_NOLPM, },
4582
4583         /* 480GB+ M500 SSDs have both queued TRIM and LPM issues */
4584         { "Crucial_CT480M500*",         NULL,   ATA_HORKAGE_NO_NCQ_TRIM |
4585                                                 ATA_HORKAGE_ZERO_AFTER_TRIM |
4586                                                 ATA_HORKAGE_NOLPM, },
4587         { "Crucial_CT960M500*",         NULL,   ATA_HORKAGE_NO_NCQ_TRIM |
4588                                                 ATA_HORKAGE_ZERO_AFTER_TRIM |
4589                                                 ATA_HORKAGE_NOLPM, },
4590
4591         /* devices that don't properly handle queued TRIM commands */
4592         { "Micron_M500IT_*",            "MU01", ATA_HORKAGE_NO_NCQ_TRIM |
4593                                                 ATA_HORKAGE_ZERO_AFTER_TRIM, },
4594         { "Micron_M500_*",              NULL,   ATA_HORKAGE_NO_NCQ_TRIM |
4595                                                 ATA_HORKAGE_ZERO_AFTER_TRIM, },
4596         { "Crucial_CT*M500*",           NULL,   ATA_HORKAGE_NO_NCQ_TRIM |
4597                                                 ATA_HORKAGE_ZERO_AFTER_TRIM, },
4598         { "Micron_M5[15]0_*",           "MU01", ATA_HORKAGE_NO_NCQ_TRIM |
4599                                                 ATA_HORKAGE_ZERO_AFTER_TRIM, },
4600         { "Crucial_CT*M550*",           "MU01", ATA_HORKAGE_NO_NCQ_TRIM |
4601                                                 ATA_HORKAGE_ZERO_AFTER_TRIM, },
4602         { "Crucial_CT*MX100*",          "MU01", ATA_HORKAGE_NO_NCQ_TRIM |
4603                                                 ATA_HORKAGE_ZERO_AFTER_TRIM, },
4604         { "Samsung SSD 840 EVO*",       NULL,   ATA_HORKAGE_NO_NCQ_TRIM |
4605                                                 ATA_HORKAGE_NO_DMA_LOG |
4606                                                 ATA_HORKAGE_ZERO_AFTER_TRIM, },
4607         { "Samsung SSD 840*",           NULL,   ATA_HORKAGE_NO_NCQ_TRIM |
4608                                                 ATA_HORKAGE_ZERO_AFTER_TRIM, },
4609         { "Samsung SSD 850*",           NULL,   ATA_HORKAGE_NO_NCQ_TRIM |
4610                                                 ATA_HORKAGE_ZERO_AFTER_TRIM, },
4611         { "Samsung SSD 860*",           NULL,   ATA_HORKAGE_NO_NCQ_TRIM |
4612                                                 ATA_HORKAGE_ZERO_AFTER_TRIM |
4613                                                 ATA_HORKAGE_NO_NCQ_ON_ATI, },
4614         { "Samsung SSD 870*",           NULL,   ATA_HORKAGE_NO_NCQ_TRIM |
4615                                                 ATA_HORKAGE_ZERO_AFTER_TRIM |
4616                                                 ATA_HORKAGE_NO_NCQ_ON_ATI, },
4617         { "FCCT*M500*",                 NULL,   ATA_HORKAGE_NO_NCQ_TRIM |
4618                                                 ATA_HORKAGE_ZERO_AFTER_TRIM, },
4619
4620         /* devices that don't properly handle TRIM commands */
4621         { "SuperSSpeed S238*",          NULL,   ATA_HORKAGE_NOTRIM, },
4622         { "M88V29*",                    NULL,   ATA_HORKAGE_NOTRIM, },
4623
4624         /*
4625          * As defined, the DRAT (Deterministic Read After Trim) and RZAT
4626          * (Return Zero After Trim) flags in the ATA Command Set are
4627          * unreliable in the sense that they only define what happens if
4628          * the device successfully executed the DSM TRIM command. TRIM
4629          * is only advisory, however, and the device is free to silently
4630          * ignore all or parts of the request.
4631          *
4632          * Whitelist drives that are known to reliably return zeroes
4633          * after TRIM.
4634          */
4635
4636         /*
4637          * The intel 510 drive has buggy DRAT/RZAT. Explicitly exclude
4638          * that model before whitelisting all other intel SSDs.
4639          */
4640         { "INTEL*SSDSC2MH*",            NULL,   0, },
4641
4642         { "Micron*",                    NULL,   ATA_HORKAGE_ZERO_AFTER_TRIM, },
4643         { "Crucial*",                   NULL,   ATA_HORKAGE_ZERO_AFTER_TRIM, },
4644         { "INTEL*SSD*",                 NULL,   ATA_HORKAGE_ZERO_AFTER_TRIM, },
4645         { "SSD*INTEL*",                 NULL,   ATA_HORKAGE_ZERO_AFTER_TRIM, },
4646         { "Samsung*SSD*",               NULL,   ATA_HORKAGE_ZERO_AFTER_TRIM, },
4647         { "SAMSUNG*SSD*",               NULL,   ATA_HORKAGE_ZERO_AFTER_TRIM, },
4648         { "SAMSUNG*MZ7KM*",             NULL,   ATA_HORKAGE_ZERO_AFTER_TRIM, },
4649         { "ST[1248][0248]0[FH]*",       NULL,   ATA_HORKAGE_ZERO_AFTER_TRIM, },
4650
4651         /*
4652          * Some WD SATA-I drives spin up and down erratically when the link
4653          * is put into the slumber mode.  We don't have full list of the
4654          * affected devices.  Disable LPM if the device matches one of the
4655          * known prefixes and is SATA-1.  As a side effect LPM partial is
4656          * lost too.
4657          *
4658          * https://bugzilla.kernel.org/show_bug.cgi?id=57211
4659          */
4660         { "WDC WD800JD-*",              NULL,   ATA_HORKAGE_WD_BROKEN_LPM },
4661         { "WDC WD1200JD-*",             NULL,   ATA_HORKAGE_WD_BROKEN_LPM },
4662         { "WDC WD1600JD-*",             NULL,   ATA_HORKAGE_WD_BROKEN_LPM },
4663         { "WDC WD2000JD-*",             NULL,   ATA_HORKAGE_WD_BROKEN_LPM },
4664         { "WDC WD2500JD-*",             NULL,   ATA_HORKAGE_WD_BROKEN_LPM },
4665         { "WDC WD3000JD-*",             NULL,   ATA_HORKAGE_WD_BROKEN_LPM },
4666         { "WDC WD3200JD-*",             NULL,   ATA_HORKAGE_WD_BROKEN_LPM },
4667
4668         /* End Marker */
4669         { }
4670 };
4671
4672 static unsigned long ata_dev_blacklisted(const struct ata_device *dev)
4673 {
4674         unsigned char model_num[ATA_ID_PROD_LEN + 1];
4675         unsigned char model_rev[ATA_ID_FW_REV_LEN + 1];
4676         const struct ata_blacklist_entry *ad = ata_device_blacklist;
4677
4678         ata_id_c_string(dev->id, model_num, ATA_ID_PROD, sizeof(model_num));
4679         ata_id_c_string(dev->id, model_rev, ATA_ID_FW_REV, sizeof(model_rev));
4680
4681         while (ad->model_num) {
4682                 if (glob_match(ad->model_num, model_num)) {
4683                         if (ad->model_rev == NULL)
4684                                 return ad->horkage;
4685                         if (glob_match(ad->model_rev, model_rev))
4686                                 return ad->horkage;
4687                 }
4688                 ad++;
4689         }
4690         return 0;
4691 }
4692
4693 static int ata_dma_blacklisted(const struct ata_device *dev)
4694 {
4695         /* We don't support polling DMA.
4696          * DMA blacklist those ATAPI devices with CDB-intr (and use PIO)
4697          * if the LLDD handles only interrupts in the HSM_ST_LAST state.
4698          */
4699         if ((dev->link->ap->flags & ATA_FLAG_PIO_POLLING) &&
4700             (dev->flags & ATA_DFLAG_CDB_INTR))
4701                 return 1;
4702         return (dev->horkage & ATA_HORKAGE_NODMA) ? 1 : 0;
4703 }
4704
4705 /**
4706  *      ata_is_40wire           -       check drive side detection
4707  *      @dev: device
4708  *
4709  *      Perform drive side detection decoding, allowing for device vendors
4710  *      who can't follow the documentation.
4711  */
4712
4713 static int ata_is_40wire(struct ata_device *dev)
4714 {
4715         if (dev->horkage & ATA_HORKAGE_IVB)
4716                 return ata_drive_40wire_relaxed(dev->id);
4717         return ata_drive_40wire(dev->id);
4718 }
4719
4720 /**
4721  *      cable_is_40wire         -       40/80/SATA decider
4722  *      @ap: port to consider
4723  *
4724  *      This function encapsulates the policy for speed management
4725  *      in one place. At the moment we don't cache the result but
4726  *      there is a good case for setting ap->cbl to the result when
4727  *      we are called with unknown cables (and figuring out if it
4728  *      impacts hotplug at all).
4729  *
4730  *      Return 1 if the cable appears to be 40 wire.
4731  */
4732
4733 static int cable_is_40wire(struct ata_port *ap)
4734 {
4735         struct ata_link *link;
4736         struct ata_device *dev;
4737
4738         /* If the controller thinks we are 40 wire, we are. */
4739         if (ap->cbl == ATA_CBL_PATA40)
4740                 return 1;
4741
4742         /* If the controller thinks we are 80 wire, we are. */
4743         if (ap->cbl == ATA_CBL_PATA80 || ap->cbl == ATA_CBL_SATA)
4744                 return 0;
4745
4746         /* If the system is known to be 40 wire short cable (eg
4747          * laptop), then we allow 80 wire modes even if the drive
4748          * isn't sure.
4749          */
4750         if (ap->cbl == ATA_CBL_PATA40_SHORT)
4751                 return 0;
4752
4753         /* If the controller doesn't know, we scan.
4754          *
4755          * Note: We look for all 40 wire detects at this point.  Any
4756          *       80 wire detect is taken to be 80 wire cable because
4757          * - in many setups only the one drive (slave if present) will
4758          *   give a valid detect
4759          * - if you have a non detect capable drive you don't want it
4760          *   to colour the choice
4761          */
4762         ata_for_each_link(link, ap, EDGE) {
4763                 ata_for_each_dev(dev, link, ENABLED) {
4764                         if (!ata_is_40wire(dev))
4765                                 return 0;
4766                 }
4767         }
4768         return 1;
4769 }
4770
4771 /**
4772  *      ata_dev_xfermask - Compute supported xfermask of the given device
4773  *      @dev: Device to compute xfermask for
4774  *
4775  *      Compute supported xfermask of @dev and store it in
4776  *      dev->*_mask.  This function is responsible for applying all
4777  *      known limits including host controller limits, device
4778  *      blacklist, etc...
4779  *
4780  *      LOCKING:
4781  *      None.
4782  */
4783 static void ata_dev_xfermask(struct ata_device *dev)
4784 {
4785         struct ata_link *link = dev->link;
4786         struct ata_port *ap = link->ap;
4787         struct ata_host *host = ap->host;
4788         unsigned long xfer_mask;
4789
4790         /* controller modes available */
4791         xfer_mask = ata_pack_xfermask(ap->pio_mask,
4792                                       ap->mwdma_mask, ap->udma_mask);
4793
4794         /* drive modes available */
4795         xfer_mask &= ata_pack_xfermask(dev->pio_mask,
4796                                        dev->mwdma_mask, dev->udma_mask);
4797         xfer_mask &= ata_id_xfermask(dev->id);
4798
4799         /*
4800          *      CFA Advanced TrueIDE timings are not allowed on a shared
4801          *      cable
4802          */
4803         if (ata_dev_pair(dev)) {
4804                 /* No PIO5 or PIO6 */
4805                 xfer_mask &= ~(0x03 << (ATA_SHIFT_PIO + 5));
4806                 /* No MWDMA3 or MWDMA 4 */
4807                 xfer_mask &= ~(0x03 << (ATA_SHIFT_MWDMA + 3));
4808         }
4809
4810         if (ata_dma_blacklisted(dev)) {
4811                 xfer_mask &= ~(ATA_MASK_MWDMA | ATA_MASK_UDMA);
4812                 ata_dev_warn(dev,
4813                              "device is on DMA blacklist, disabling DMA\n");
4814         }
4815
4816         if ((host->flags & ATA_HOST_SIMPLEX) &&
4817             host->simplex_claimed && host->simplex_claimed != ap) {
4818                 xfer_mask &= ~(ATA_MASK_MWDMA | ATA_MASK_UDMA);
4819                 ata_dev_warn(dev,
4820                              "simplex DMA is claimed by other device, disabling DMA\n");
4821         }
4822
4823         if (ap->flags & ATA_FLAG_NO_IORDY)
4824                 xfer_mask &= ata_pio_mask_no_iordy(dev);
4825
4826         if (ap->ops->mode_filter)
4827                 xfer_mask = ap->ops->mode_filter(dev, xfer_mask);
4828
4829         /* Apply cable rule here.  Don't apply it early because when
4830          * we handle hot plug the cable type can itself change.
4831          * Check this last so that we know if the transfer rate was
4832          * solely limited by the cable.
4833          * Unknown or 80 wire cables reported host side are checked
4834          * drive side as well. Cases where we know a 40wire cable
4835          * is used safely for 80 are not checked here.
4836          */
4837         if (xfer_mask & (0xF8 << ATA_SHIFT_UDMA))
4838                 /* UDMA/44 or higher would be available */
4839                 if (cable_is_40wire(ap)) {
4840                         ata_dev_warn(dev,
4841                                      "limited to UDMA/33 due to 40-wire cable\n");
4842                         xfer_mask &= ~(0xF8 << ATA_SHIFT_UDMA);
4843                 }
4844
4845         ata_unpack_xfermask(xfer_mask, &dev->pio_mask,
4846                             &dev->mwdma_mask, &dev->udma_mask);
4847 }
4848
4849 /**
4850  *      ata_dev_set_xfermode - Issue SET FEATURES - XFER MODE command
4851  *      @dev: Device to which command will be sent
4852  *
4853  *      Issue SET FEATURES - XFER MODE command to device @dev
4854  *      on port @ap.
4855  *
4856  *      LOCKING:
4857  *      PCI/etc. bus probe sem.
4858  *
4859  *      RETURNS:
4860  *      0 on success, AC_ERR_* mask otherwise.
4861  */
4862
4863 static unsigned int ata_dev_set_xfermode(struct ata_device *dev)
4864 {
4865         struct ata_taskfile tf;
4866         unsigned int err_mask;
4867
4868         /* set up set-features taskfile */
4869         DPRINTK("set features - xfer mode\n");
4870
4871         /* Some controllers and ATAPI devices show flaky interrupt
4872          * behavior after setting xfer mode.  Use polling instead.
4873          */
4874         ata_tf_init(dev, &tf);
4875         tf.command = ATA_CMD_SET_FEATURES;
4876         tf.feature = SETFEATURES_XFER;
4877         tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE | ATA_TFLAG_POLLING;
4878         tf.protocol = ATA_PROT_NODATA;
4879         /* If we are using IORDY we must send the mode setting command */
4880         if (ata_pio_need_iordy(dev))
4881                 tf.nsect = dev->xfer_mode;
4882         /* If the device has IORDY and the controller does not - turn it off */
4883         else if (ata_id_has_iordy(dev->id))
4884                 tf.nsect = 0x01;
4885         else /* In the ancient relic department - skip all of this */
4886                 return 0;
4887
4888         /* On some disks, this command causes spin-up, so we need longer timeout */
4889         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 15000);
4890
4891         DPRINTK("EXIT, err_mask=%x\n", err_mask);
4892         return err_mask;
4893 }
4894
4895 /**
4896  *      ata_dev_set_feature - Issue SET FEATURES - SATA FEATURES
4897  *      @dev: Device to which command will be sent
4898  *      @enable: Whether to enable or disable the feature
4899  *      @feature: The sector count represents the feature to set
4900  *
4901  *      Issue SET FEATURES - SATA FEATURES command to device @dev
4902  *      on port @ap with sector count
4903  *
4904  *      LOCKING:
4905  *      PCI/etc. bus probe sem.
4906  *
4907  *      RETURNS:
4908  *      0 on success, AC_ERR_* mask otherwise.
4909  */
4910 unsigned int ata_dev_set_feature(struct ata_device *dev, u8 enable, u8 feature)
4911 {
4912         struct ata_taskfile tf;
4913         unsigned int err_mask;
4914         unsigned long timeout = 0;
4915
4916         /* set up set-features taskfile */
4917         DPRINTK("set features - SATA features\n");
4918
4919         ata_tf_init(dev, &tf);
4920         tf.command = ATA_CMD_SET_FEATURES;
4921         tf.feature = enable;
4922         tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
4923         tf.protocol = ATA_PROT_NODATA;
4924         tf.nsect = feature;
4925
4926         if (enable == SETFEATURES_SPINUP)
4927                 timeout = ata_probe_timeout ?
4928                           ata_probe_timeout * 1000 : SETFEATURES_SPINUP_TIMEOUT;
4929         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, timeout);
4930
4931         DPRINTK("EXIT, err_mask=%x\n", err_mask);
4932         return err_mask;
4933 }
4934 EXPORT_SYMBOL_GPL(ata_dev_set_feature);
4935
4936 /**
4937  *      ata_dev_init_params - Issue INIT DEV PARAMS command
4938  *      @dev: Device to which command will be sent
4939  *      @heads: Number of heads (taskfile parameter)
4940  *      @sectors: Number of sectors (taskfile parameter)
4941  *
4942  *      LOCKING:
4943  *      Kernel thread context (may sleep)
4944  *
4945  *      RETURNS:
4946  *      0 on success, AC_ERR_* mask otherwise.
4947  */
4948 static unsigned int ata_dev_init_params(struct ata_device *dev,
4949                                         u16 heads, u16 sectors)
4950 {
4951         struct ata_taskfile tf;
4952         unsigned int err_mask;
4953
4954         /* Number of sectors per track 1-255. Number of heads 1-16 */
4955         if (sectors < 1 || sectors > 255 || heads < 1 || heads > 16)
4956                 return AC_ERR_INVALID;
4957
4958         /* set up init dev params taskfile */
4959         DPRINTK("init dev params \n");
4960
4961         ata_tf_init(dev, &tf);
4962         tf.command = ATA_CMD_INIT_DEV_PARAMS;
4963         tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
4964         tf.protocol = ATA_PROT_NODATA;
4965         tf.nsect = sectors;
4966         tf.device |= (heads - 1) & 0x0f; /* max head = num. of heads - 1 */
4967
4968         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
4969         /* A clean abort indicates an original or just out of spec drive
4970            and we should continue as we issue the setup based on the
4971            drive reported working geometry */
4972         if (err_mask == AC_ERR_DEV && (tf.feature & ATA_ABORTED))
4973                 err_mask = 0;
4974
4975         DPRINTK("EXIT, err_mask=%x\n", err_mask);
4976         return err_mask;
4977 }
4978
4979 /**
4980  *      atapi_check_dma - Check whether ATAPI DMA can be supported
4981  *      @qc: Metadata associated with taskfile to check
4982  *
4983  *      Allow low-level driver to filter ATA PACKET commands, returning
4984  *      a status indicating whether or not it is OK to use DMA for the
4985  *      supplied PACKET command.
4986  *
4987  *      LOCKING:
4988  *      spin_lock_irqsave(host lock)
4989  *
4990  *      RETURNS: 0 when ATAPI DMA can be used
4991  *               nonzero otherwise
4992  */
4993 int atapi_check_dma(struct ata_queued_cmd *qc)
4994 {
4995         struct ata_port *ap = qc->ap;
4996
4997         /* Don't allow DMA if it isn't multiple of 16 bytes.  Quite a
4998          * few ATAPI devices choke on such DMA requests.
4999          */
5000         if (!(qc->dev->horkage & ATA_HORKAGE_ATAPI_MOD16_DMA) &&
5001             unlikely(qc->nbytes & 15))
5002                 return 1;
5003
5004         if (ap->ops->check_atapi_dma)
5005                 return ap->ops->check_atapi_dma(qc);
5006
5007         return 0;
5008 }
5009
5010 /**
5011  *      ata_std_qc_defer - Check whether a qc needs to be deferred
5012  *      @qc: ATA command in question
5013  *
5014  *      Non-NCQ commands cannot run with any other command, NCQ or
5015  *      not.  As upper layer only knows the queue depth, we are
5016  *      responsible for maintaining exclusion.  This function checks
5017  *      whether a new command @qc can be issued.
5018  *
5019  *      LOCKING:
5020  *      spin_lock_irqsave(host lock)
5021  *
5022  *      RETURNS:
5023  *      ATA_DEFER_* if deferring is needed, 0 otherwise.
5024  */
5025 int ata_std_qc_defer(struct ata_queued_cmd *qc)
5026 {
5027         struct ata_link *link = qc->dev->link;
5028
5029         if (ata_is_ncq(qc->tf.protocol)) {
5030                 if (!ata_tag_valid(link->active_tag))
5031                         return 0;
5032         } else {
5033                 if (!ata_tag_valid(link->active_tag) && !link->sactive)
5034                         return 0;
5035         }
5036
5037         return ATA_DEFER_LINK;
5038 }
5039
5040 enum ata_completion_errors ata_noop_qc_prep(struct ata_queued_cmd *qc)
5041 {
5042         return AC_ERR_OK;
5043 }
5044
5045 /**
5046  *      ata_sg_init - Associate command with scatter-gather table.
5047  *      @qc: Command to be associated
5048  *      @sg: Scatter-gather table.
5049  *      @n_elem: Number of elements in s/g table.
5050  *
5051  *      Initialize the data-related elements of queued_cmd @qc
5052  *      to point to a scatter-gather table @sg, containing @n_elem
5053  *      elements.
5054  *
5055  *      LOCKING:
5056  *      spin_lock_irqsave(host lock)
5057  */
5058 void ata_sg_init(struct ata_queued_cmd *qc, struct scatterlist *sg,
5059                  unsigned int n_elem)
5060 {
5061         qc->sg = sg;
5062         qc->n_elem = n_elem;
5063         qc->cursg = qc->sg;
5064 }
5065
5066 #ifdef CONFIG_HAS_DMA
5067
5068 /**
5069  *      ata_sg_clean - Unmap DMA memory associated with command
5070  *      @qc: Command containing DMA memory to be released
5071  *
5072  *      Unmap all mapped DMA memory associated with this command.
5073  *
5074  *      LOCKING:
5075  *      spin_lock_irqsave(host lock)
5076  */
5077 static void ata_sg_clean(struct ata_queued_cmd *qc)
5078 {
5079         struct ata_port *ap = qc->ap;
5080         struct scatterlist *sg = qc->sg;
5081         int dir = qc->dma_dir;
5082
5083         WARN_ON_ONCE(sg == NULL);
5084
5085         VPRINTK("unmapping %u sg elements\n", qc->n_elem);
5086
5087         if (qc->n_elem)
5088                 dma_unmap_sg(ap->dev, sg, qc->orig_n_elem, dir);
5089
5090         qc->flags &= ~ATA_QCFLAG_DMAMAP;
5091         qc->sg = NULL;
5092 }
5093
5094 /**
5095  *      ata_sg_setup - DMA-map the scatter-gather table associated with a command.
5096  *      @qc: Command with scatter-gather table to be mapped.
5097  *
5098  *      DMA-map the scatter-gather table associated with queued_cmd @qc.
5099  *
5100  *      LOCKING:
5101  *      spin_lock_irqsave(host lock)
5102  *
5103  *      RETURNS:
5104  *      Zero on success, negative on error.
5105  *
5106  */
5107 static int ata_sg_setup(struct ata_queued_cmd *qc)
5108 {
5109         struct ata_port *ap = qc->ap;
5110         unsigned int n_elem;
5111
5112         VPRINTK("ENTER, ata%u\n", ap->print_id);
5113
5114         n_elem = dma_map_sg(ap->dev, qc->sg, qc->n_elem, qc->dma_dir);
5115         if (n_elem < 1)
5116                 return -1;
5117
5118         DPRINTK("%d sg elements mapped\n", n_elem);
5119         qc->orig_n_elem = qc->n_elem;
5120         qc->n_elem = n_elem;
5121         qc->flags |= ATA_QCFLAG_DMAMAP;
5122
5123         return 0;
5124 }
5125
5126 #else /* !CONFIG_HAS_DMA */
5127
5128 static inline void ata_sg_clean(struct ata_queued_cmd *qc) {}
5129 static inline int ata_sg_setup(struct ata_queued_cmd *qc) { return -1; }
5130
5131 #endif /* !CONFIG_HAS_DMA */
5132
5133 /**
5134  *      swap_buf_le16 - swap halves of 16-bit words in place
5135  *      @buf:  Buffer to swap
5136  *      @buf_words:  Number of 16-bit words in buffer.
5137  *
5138  *      Swap halves of 16-bit words if needed to convert from
5139  *      little-endian byte order to native cpu byte order, or
5140  *      vice-versa.
5141  *
5142  *      LOCKING:
5143  *      Inherited from caller.
5144  */
5145 void swap_buf_le16(u16 *buf, unsigned int buf_words)
5146 {
5147 #ifdef __BIG_ENDIAN
5148         unsigned int i;
5149
5150         for (i = 0; i < buf_words; i++)
5151                 buf[i] = le16_to_cpu(buf[i]);
5152 #endif /* __BIG_ENDIAN */
5153 }
5154
5155 /**
5156  *      ata_qc_new_init - Request an available ATA command, and initialize it
5157  *      @dev: Device from whom we request an available command structure
5158  *      @tag: tag
5159  *
5160  *      LOCKING:
5161  *      None.
5162  */
5163
5164 struct ata_queued_cmd *ata_qc_new_init(struct ata_device *dev, int tag)
5165 {
5166         struct ata_port *ap = dev->link->ap;
5167         struct ata_queued_cmd *qc;
5168
5169         /* no command while frozen */
5170         if (unlikely(ap->pflags & ATA_PFLAG_FROZEN))
5171                 return NULL;
5172
5173         /* libsas case */
5174         if (ap->flags & ATA_FLAG_SAS_HOST) {
5175                 tag = ata_sas_allocate_tag(ap);
5176                 if (tag < 0)
5177                         return NULL;
5178         }
5179
5180         qc = __ata_qc_from_tag(ap, tag);
5181         qc->tag = tag;
5182         qc->scsicmd = NULL;
5183         qc->ap = ap;
5184         qc->dev = dev;
5185
5186         ata_qc_reinit(qc);
5187
5188         return qc;
5189 }
5190
5191 /**
5192  *      ata_qc_free - free unused ata_queued_cmd
5193  *      @qc: Command to complete
5194  *
5195  *      Designed to free unused ata_queued_cmd object
5196  *      in case something prevents using it.
5197  *
5198  *      LOCKING:
5199  *      spin_lock_irqsave(host lock)
5200  */
5201 void ata_qc_free(struct ata_queued_cmd *qc)
5202 {
5203         struct ata_port *ap;
5204         unsigned int tag;
5205
5206         WARN_ON_ONCE(qc == NULL); /* ata_qc_from_tag _might_ return NULL */
5207         ap = qc->ap;
5208
5209         qc->flags = 0;
5210         tag = qc->tag;
5211         if (likely(ata_tag_valid(tag))) {
5212                 qc->tag = ATA_TAG_POISON;
5213                 if (ap->flags & ATA_FLAG_SAS_HOST)
5214                         ata_sas_free_tag(tag, ap);
5215         }
5216 }
5217
5218 void __ata_qc_complete(struct ata_queued_cmd *qc)
5219 {
5220         struct ata_port *ap;
5221         struct ata_link *link;
5222
5223         WARN_ON_ONCE(qc == NULL); /* ata_qc_from_tag _might_ return NULL */
5224         WARN_ON_ONCE(!(qc->flags & ATA_QCFLAG_ACTIVE));
5225         ap = qc->ap;
5226         link = qc->dev->link;
5227
5228         if (likely(qc->flags & ATA_QCFLAG_DMAMAP))
5229                 ata_sg_clean(qc);
5230
5231         /* command should be marked inactive atomically with qc completion */
5232         if (ata_is_ncq(qc->tf.protocol)) {
5233                 link->sactive &= ~(1 << qc->tag);
5234                 if (!link->sactive)
5235                         ap->nr_active_links--;
5236         } else {
5237                 link->active_tag = ATA_TAG_POISON;
5238                 ap->nr_active_links--;
5239         }
5240
5241         /* clear exclusive status */
5242         if (unlikely(qc->flags & ATA_QCFLAG_CLEAR_EXCL &&
5243                      ap->excl_link == link))
5244                 ap->excl_link = NULL;
5245
5246         /* atapi: mark qc as inactive to prevent the interrupt handler
5247          * from completing the command twice later, before the error handler
5248          * is called. (when rc != 0 and atapi request sense is needed)
5249          */
5250         qc->flags &= ~ATA_QCFLAG_ACTIVE;
5251         ap->qc_active &= ~(1 << qc->tag);
5252
5253         /* call completion callback */
5254         qc->complete_fn(qc);
5255 }
5256
5257 static void fill_result_tf(struct ata_queued_cmd *qc)
5258 {
5259         struct ata_port *ap = qc->ap;
5260
5261         qc->result_tf.flags = qc->tf.flags;
5262         ap->ops->qc_fill_rtf(qc);
5263 }
5264
5265 static void ata_verify_xfer(struct ata_queued_cmd *qc)
5266 {
5267         struct ata_device *dev = qc->dev;
5268
5269         if (!ata_is_data(qc->tf.protocol))
5270                 return;
5271
5272         if ((dev->mwdma_mask || dev->udma_mask) && ata_is_pio(qc->tf.protocol))
5273                 return;
5274
5275         dev->flags &= ~ATA_DFLAG_DUBIOUS_XFER;
5276 }
5277
5278 /**
5279  *      ata_qc_complete - Complete an active ATA command
5280  *      @qc: Command to complete
5281  *
5282  *      Indicate to the mid and upper layers that an ATA command has
5283  *      completed, with either an ok or not-ok status.
5284  *
5285  *      Refrain from calling this function multiple times when
5286  *      successfully completing multiple NCQ commands.
5287  *      ata_qc_complete_multiple() should be used instead, which will
5288  *      properly update IRQ expect state.
5289  *
5290  *      LOCKING:
5291  *      spin_lock_irqsave(host lock)
5292  */
5293 void ata_qc_complete(struct ata_queued_cmd *qc)
5294 {
5295         struct ata_port *ap = qc->ap;
5296
5297         /* Trigger the LED (if available) */
5298         ledtrig_disk_activity();
5299
5300         /* XXX: New EH and old EH use different mechanisms to
5301          * synchronize EH with regular execution path.
5302          *
5303          * In new EH, a failed qc is marked with ATA_QCFLAG_FAILED.
5304          * Normal execution path is responsible for not accessing a
5305          * failed qc.  libata core enforces the rule by returning NULL
5306          * from ata_qc_from_tag() for failed qcs.
5307          *
5308          * Old EH depends on ata_qc_complete() nullifying completion
5309          * requests if ATA_QCFLAG_EH_SCHEDULED is set.  Old EH does
5310          * not synchronize with interrupt handler.  Only PIO task is
5311          * taken care of.
5312          */
5313         if (ap->ops->error_handler) {
5314                 struct ata_device *dev = qc->dev;
5315                 struct ata_eh_info *ehi = &dev->link->eh_info;
5316
5317                 if (unlikely(qc->err_mask))
5318                         qc->flags |= ATA_QCFLAG_FAILED;
5319
5320                 /*
5321                  * Finish internal commands without any further processing
5322                  * and always with the result TF filled.
5323                  */
5324                 if (unlikely(ata_tag_internal(qc->tag))) {
5325                         fill_result_tf(qc);
5326                         trace_ata_qc_complete_internal(qc);
5327                         __ata_qc_complete(qc);
5328                         return;
5329                 }
5330
5331                 /*
5332                  * Non-internal qc has failed.  Fill the result TF and
5333                  * summon EH.
5334                  */
5335                 if (unlikely(qc->flags & ATA_QCFLAG_FAILED)) {
5336                         fill_result_tf(qc);
5337                         trace_ata_qc_complete_failed(qc);
5338                         ata_qc_schedule_eh(qc);
5339                         return;
5340                 }
5341
5342                 WARN_ON_ONCE(ap->pflags & ATA_PFLAG_FROZEN);
5343
5344                 /* read result TF if requested */
5345                 if (qc->flags & ATA_QCFLAG_RESULT_TF)
5346                         fill_result_tf(qc);
5347
5348                 trace_ata_qc_complete_done(qc);
5349                 /* Some commands need post-processing after successful
5350                  * completion.
5351                  */
5352                 switch (qc->tf.command) {
5353                 case ATA_CMD_SET_FEATURES:
5354                         if (qc->tf.feature != SETFEATURES_WC_ON &&
5355                             qc->tf.feature != SETFEATURES_WC_OFF &&
5356                             qc->tf.feature != SETFEATURES_RA_ON &&
5357                             qc->tf.feature != SETFEATURES_RA_OFF)
5358                                 break;
5359                         /* fall through */
5360                 case ATA_CMD_INIT_DEV_PARAMS: /* CHS translation changed */
5361                 case ATA_CMD_SET_MULTI: /* multi_count changed */
5362                         /* revalidate device */
5363                         ehi->dev_action[dev->devno] |= ATA_EH_REVALIDATE;
5364                         ata_port_schedule_eh(ap);
5365                         break;
5366
5367                 case ATA_CMD_SLEEP:
5368                         dev->flags |= ATA_DFLAG_SLEEPING;
5369                         break;
5370                 }
5371
5372                 if (unlikely(dev->flags & ATA_DFLAG_DUBIOUS_XFER))
5373                         ata_verify_xfer(qc);
5374
5375                 __ata_qc_complete(qc);
5376         } else {
5377                 if (qc->flags & ATA_QCFLAG_EH_SCHEDULED)
5378                         return;
5379
5380                 /* read result TF if failed or requested */
5381                 if (qc->err_mask || qc->flags & ATA_QCFLAG_RESULT_TF)
5382                         fill_result_tf(qc);
5383
5384                 __ata_qc_complete(qc);
5385         }
5386 }
5387
5388 /**
5389  *      ata_qc_complete_multiple - Complete multiple qcs successfully
5390  *      @ap: port in question
5391  *      @qc_active: new qc_active mask
5392  *
5393  *      Complete in-flight commands.  This functions is meant to be
5394  *      called from low-level driver's interrupt routine to complete
5395  *      requests normally.  ap->qc_active and @qc_active is compared
5396  *      and commands are completed accordingly.
5397  *
5398  *      Always use this function when completing multiple NCQ commands
5399  *      from IRQ handlers instead of calling ata_qc_complete()
5400  *      multiple times to keep IRQ expect status properly in sync.
5401  *
5402  *      LOCKING:
5403  *      spin_lock_irqsave(host lock)
5404  *
5405  *      RETURNS:
5406  *      Number of completed commands on success, -errno otherwise.
5407  */
5408 int ata_qc_complete_multiple(struct ata_port *ap, u32 qc_active)
5409 {
5410         int nr_done = 0;
5411         u32 done_mask;
5412
5413         done_mask = ap->qc_active ^ qc_active;
5414
5415         if (unlikely(done_mask & qc_active)) {
5416                 ata_port_err(ap, "illegal qc_active transition (%08x->%08x)\n",
5417                              ap->qc_active, qc_active);
5418                 return -EINVAL;
5419         }
5420
5421         while (done_mask) {
5422                 struct ata_queued_cmd *qc;
5423                 unsigned int tag = __ffs(done_mask);
5424
5425                 qc = ata_qc_from_tag(ap, tag);
5426                 if (qc) {
5427                         ata_qc_complete(qc);
5428                         nr_done++;
5429                 }
5430                 done_mask &= ~(1 << tag);
5431         }
5432
5433         return nr_done;
5434 }
5435
5436 /**
5437  *      ata_qc_issue - issue taskfile to device
5438  *      @qc: command to issue to device
5439  *
5440  *      Prepare an ATA command to submission to device.
5441  *      This includes mapping the data into a DMA-able
5442  *      area, filling in the S/G table, and finally
5443  *      writing the taskfile to hardware, starting the command.
5444  *
5445  *      LOCKING:
5446  *      spin_lock_irqsave(host lock)
5447  */
5448 void ata_qc_issue(struct ata_queued_cmd *qc)
5449 {
5450         struct ata_port *ap = qc->ap;
5451         struct ata_link *link = qc->dev->link;
5452         u8 prot = qc->tf.protocol;
5453
5454         /* Make sure only one non-NCQ command is outstanding.  The
5455          * check is skipped for old EH because it reuses active qc to
5456          * request ATAPI sense.
5457          */
5458         WARN_ON_ONCE(ap->ops->error_handler && ata_tag_valid(link->active_tag));
5459
5460         if (ata_is_ncq(prot)) {
5461                 WARN_ON_ONCE(link->sactive & (1 << qc->tag));
5462
5463                 if (!link->sactive)
5464                         ap->nr_active_links++;
5465                 link->sactive |= 1 << qc->tag;
5466         } else {
5467                 WARN_ON_ONCE(link->sactive);
5468
5469                 ap->nr_active_links++;
5470                 link->active_tag = qc->tag;
5471         }
5472
5473         qc->flags |= ATA_QCFLAG_ACTIVE;
5474         ap->qc_active |= 1 << qc->tag;
5475
5476         /*
5477          * We guarantee to LLDs that they will have at least one
5478          * non-zero sg if the command is a data command.
5479          */
5480         if (ata_is_data(prot) && (!qc->sg || !qc->n_elem || !qc->nbytes))
5481                 goto sys_err;
5482
5483         if (ata_is_dma(prot) || (ata_is_pio(prot) &&
5484                                  (ap->flags & ATA_FLAG_PIO_DMA)))
5485                 if (ata_sg_setup(qc))
5486                         goto sys_err;
5487
5488         /* if device is sleeping, schedule reset and abort the link */
5489         if (unlikely(qc->dev->flags & ATA_DFLAG_SLEEPING)) {
5490                 link->eh_info.action |= ATA_EH_RESET;
5491                 ata_ehi_push_desc(&link->eh_info, "waking up from sleep");
5492                 ata_link_abort(link);
5493                 return;
5494         }
5495
5496         qc->err_mask |= ap->ops->qc_prep(qc);
5497         if (unlikely(qc->err_mask))
5498                 goto err;
5499         trace_ata_qc_issue(qc);
5500         qc->err_mask |= ap->ops->qc_issue(qc);
5501         if (unlikely(qc->err_mask))
5502                 goto err;
5503         return;
5504
5505 sys_err:
5506         qc->err_mask |= AC_ERR_SYSTEM;
5507 err:
5508         ata_qc_complete(qc);
5509 }
5510
5511 /**
5512  *      sata_scr_valid - test whether SCRs are accessible
5513  *      @link: ATA link to test SCR accessibility for
5514  *
5515  *      Test whether SCRs are accessible for @link.
5516  *
5517  *      LOCKING:
5518  *      None.
5519  *
5520  *      RETURNS:
5521  *      1 if SCRs are accessible, 0 otherwise.
5522  */
5523 int sata_scr_valid(struct ata_link *link)
5524 {
5525         struct ata_port *ap = link->ap;
5526
5527         return (ap->flags & ATA_FLAG_SATA) && ap->ops->scr_read;
5528 }
5529
5530 /**
5531  *      sata_scr_read - read SCR register of the specified port
5532  *      @link: ATA link to read SCR for
5533  *      @reg: SCR to read
5534  *      @val: Place to store read value
5535  *
5536  *      Read SCR register @reg of @link into *@val.  This function is
5537  *      guaranteed to succeed if @link is ap->link, the cable type of
5538  *      the port is SATA and the port implements ->scr_read.
5539  *
5540  *      LOCKING:
5541  *      None if @link is ap->link.  Kernel thread context otherwise.
5542  *
5543  *      RETURNS:
5544  *      0 on success, negative errno on failure.
5545  */
5546 int sata_scr_read(struct ata_link *link, int reg, u32 *val)
5547 {
5548         if (ata_is_host_link(link)) {
5549                 if (sata_scr_valid(link))
5550                         return link->ap->ops->scr_read(link, reg, val);
5551                 return -EOPNOTSUPP;
5552         }
5553
5554         return sata_pmp_scr_read(link, reg, val);
5555 }
5556
5557 /**
5558  *      sata_scr_write - write SCR register of the specified port
5559  *      @link: ATA link to write SCR for
5560  *      @reg: SCR to write
5561  *      @val: value to write
5562  *
5563  *      Write @val to SCR register @reg of @link.  This function is
5564  *      guaranteed to succeed if @link is ap->link, the cable type of
5565  *      the port is SATA and the port implements ->scr_read.
5566  *
5567  *      LOCKING:
5568  *      None if @link is ap->link.  Kernel thread context otherwise.
5569  *
5570  *      RETURNS:
5571  *      0 on success, negative errno on failure.
5572  */
5573 int sata_scr_write(struct ata_link *link, int reg, u32 val)
5574 {
5575         if (ata_is_host_link(link)) {
5576                 if (sata_scr_valid(link))
5577                         return link->ap->ops->scr_write(link, reg, val);
5578                 return -EOPNOTSUPP;
5579         }
5580
5581         return sata_pmp_scr_write(link, reg, val);
5582 }
5583
5584 /**
5585  *      sata_scr_write_flush - write SCR register of the specified port and flush
5586  *      @link: ATA link to write SCR for
5587  *      @reg: SCR to write
5588  *      @val: value to write
5589  *
5590  *      This function is identical to sata_scr_write() except that this
5591  *      function performs flush after writing to the register.
5592  *
5593  *      LOCKING:
5594  *      None if @link is ap->link.  Kernel thread context otherwise.
5595  *
5596  *      RETURNS:
5597  *      0 on success, negative errno on failure.
5598  */
5599 int sata_scr_write_flush(struct ata_link *link, int reg, u32 val)
5600 {
5601         if (ata_is_host_link(link)) {
5602                 int rc;
5603
5604                 if (sata_scr_valid(link)) {
5605                         rc = link->ap->ops->scr_write(link, reg, val);
5606                         if (rc == 0)
5607                                 rc = link->ap->ops->scr_read(link, reg, &val);
5608                         return rc;
5609                 }
5610                 return -EOPNOTSUPP;
5611         }
5612
5613         return sata_pmp_scr_write(link, reg, val);
5614 }
5615
5616 /**
5617  *      ata_phys_link_online - test whether the given link is online
5618  *      @link: ATA link to test
5619  *
5620  *      Test whether @link is online.  Note that this function returns
5621  *      0 if online status of @link cannot be obtained, so
5622  *      ata_link_online(link) != !ata_link_offline(link).
5623  *
5624  *      LOCKING:
5625  *      None.
5626  *
5627  *      RETURNS:
5628  *      True if the port online status is available and online.
5629  */
5630 bool ata_phys_link_online(struct ata_link *link)
5631 {
5632         u32 sstatus;
5633
5634         if (sata_scr_read(link, SCR_STATUS, &sstatus) == 0 &&
5635             ata_sstatus_online(sstatus))
5636                 return true;
5637         return false;
5638 }
5639
5640 /**
5641  *      ata_phys_link_offline - test whether the given link is offline
5642  *      @link: ATA link to test
5643  *
5644  *      Test whether @link is offline.  Note that this function
5645  *      returns 0 if offline status of @link cannot be obtained, so
5646  *      ata_link_online(link) != !ata_link_offline(link).
5647  *
5648  *      LOCKING:
5649  *      None.
5650  *
5651  *      RETURNS:
5652  *      True if the port offline status is available and offline.
5653  */
5654 bool ata_phys_link_offline(struct ata_link *link)
5655 {
5656         u32 sstatus;
5657
5658         if (sata_scr_read(link, SCR_STATUS, &sstatus) == 0 &&
5659             !ata_sstatus_online(sstatus))
5660                 return true;
5661         return false;
5662 }
5663
5664 /**
5665  *      ata_link_online - test whether the given link is online
5666  *      @link: ATA link to test
5667  *
5668  *      Test whether @link is online.  This is identical to
5669  *      ata_phys_link_online() when there's no slave link.  When
5670  *      there's a slave link, this function should only be called on
5671  *      the master link and will return true if any of M/S links is
5672  *      online.
5673  *
5674  *      LOCKING:
5675  *      None.
5676  *
5677  *      RETURNS:
5678  *      True if the port online status is available and online.
5679  */
5680 bool ata_link_online(struct ata_link *link)
5681 {
5682         struct ata_link *slave = link->ap->slave_link;
5683
5684         WARN_ON(link == slave); /* shouldn't be called on slave link */
5685
5686         return ata_phys_link_online(link) ||
5687                 (slave && ata_phys_link_online(slave));
5688 }
5689
5690 /**
5691  *      ata_link_offline - test whether the given link is offline
5692  *      @link: ATA link to test
5693  *
5694  *      Test whether @link is offline.  This is identical to
5695  *      ata_phys_link_offline() when there's no slave link.  When
5696  *      there's a slave link, this function should only be called on
5697  *      the master link and will return true if both M/S links are
5698  *      offline.
5699  *
5700  *      LOCKING:
5701  *      None.
5702  *
5703  *      RETURNS:
5704  *      True if the port offline status is available and offline.
5705  */
5706 bool ata_link_offline(struct ata_link *link)
5707 {
5708         struct ata_link *slave = link->ap->slave_link;
5709
5710         WARN_ON(link == slave); /* shouldn't be called on slave link */
5711
5712         return ata_phys_link_offline(link) &&
5713                 (!slave || ata_phys_link_offline(slave));
5714 }
5715
5716 #ifdef CONFIG_PM
5717 static void ata_port_request_pm(struct ata_port *ap, pm_message_t mesg,
5718                                 unsigned int action, unsigned int ehi_flags,
5719                                 bool async)
5720 {
5721         struct ata_link *link;
5722         unsigned long flags;
5723
5724         spin_lock_irqsave(ap->lock, flags);
5725
5726         /*
5727          * A previous PM operation might still be in progress. Wait for
5728          * ATA_PFLAG_PM_PENDING to clear.
5729          */
5730         if (ap->pflags & ATA_PFLAG_PM_PENDING) {
5731                 spin_unlock_irqrestore(ap->lock, flags);
5732                 ata_port_wait_eh(ap);
5733                 spin_lock_irqsave(ap->lock, flags);
5734         }
5735
5736         /* Request PM operation to EH */
5737         ap->pm_mesg = mesg;
5738         ap->pflags |= ATA_PFLAG_PM_PENDING;
5739         ata_for_each_link(link, ap, HOST_FIRST) {
5740                 link->eh_info.action |= action;
5741                 link->eh_info.flags |= ehi_flags;
5742         }
5743
5744         ata_port_schedule_eh(ap);
5745
5746         spin_unlock_irqrestore(ap->lock, flags);
5747
5748         if (!async)
5749                 ata_port_wait_eh(ap);
5750 }
5751
5752 /*
5753  * On some hardware, device fails to respond after spun down for suspend.  As
5754  * the device won't be used before being resumed, we don't need to touch the
5755  * device.  Ask EH to skip the usual stuff and proceed directly to suspend.
5756  *
5757  * http://thread.gmane.org/gmane.linux.ide/46764
5758  */
5759 static const unsigned int ata_port_suspend_ehi = ATA_EHI_QUIET
5760                                                  | ATA_EHI_NO_AUTOPSY
5761                                                  | ATA_EHI_NO_RECOVERY;
5762
5763 static void ata_port_suspend(struct ata_port *ap, pm_message_t mesg)
5764 {
5765         ata_port_request_pm(ap, mesg, 0, ata_port_suspend_ehi, false);
5766 }
5767
5768 static void ata_port_suspend_async(struct ata_port *ap, pm_message_t mesg)
5769 {
5770         ata_port_request_pm(ap, mesg, 0, ata_port_suspend_ehi, true);
5771 }
5772
5773 static int ata_port_pm_suspend(struct device *dev)
5774 {
5775         struct ata_port *ap = to_ata_port(dev);
5776
5777         if (pm_runtime_suspended(dev))
5778                 return 0;
5779
5780         ata_port_suspend(ap, PMSG_SUSPEND);
5781         return 0;
5782 }
5783
5784 static int ata_port_pm_freeze(struct device *dev)
5785 {
5786         struct ata_port *ap = to_ata_port(dev);
5787
5788         if (pm_runtime_suspended(dev))
5789                 return 0;
5790
5791         ata_port_suspend(ap, PMSG_FREEZE);
5792         return 0;
5793 }
5794
5795 static int ata_port_pm_poweroff(struct device *dev)
5796 {
5797         ata_port_suspend(to_ata_port(dev), PMSG_HIBERNATE);
5798         return 0;
5799 }
5800
5801 static const unsigned int ata_port_resume_ehi = ATA_EHI_NO_AUTOPSY
5802                                                 | ATA_EHI_QUIET;
5803
5804 static void ata_port_resume(struct ata_port *ap, pm_message_t mesg)
5805 {
5806         ata_port_request_pm(ap, mesg, ATA_EH_RESET, ata_port_resume_ehi, false);
5807 }
5808
5809 static void ata_port_resume_async(struct ata_port *ap, pm_message_t mesg)
5810 {
5811         ata_port_request_pm(ap, mesg, ATA_EH_RESET, ata_port_resume_ehi, true);
5812 }
5813
5814 static int ata_port_pm_resume(struct device *dev)
5815 {
5816         ata_port_resume_async(to_ata_port(dev), PMSG_RESUME);
5817         pm_runtime_disable(dev);
5818         pm_runtime_set_active(dev);
5819         pm_runtime_enable(dev);
5820         return 0;
5821 }
5822
5823 /*
5824  * For ODDs, the upper layer will poll for media change every few seconds,
5825  * which will make it enter and leave suspend state every few seconds. And
5826  * as each suspend will cause a hard/soft reset, the gain of runtime suspend
5827  * is very little and the ODD may malfunction after constantly being reset.
5828  * So the idle callback here will not proceed to suspend if a non-ZPODD capable
5829  * ODD is attached to the port.
5830  */
5831 static int ata_port_runtime_idle(struct device *dev)
5832 {
5833         struct ata_port *ap = to_ata_port(dev);
5834         struct ata_link *link;
5835         struct ata_device *adev;
5836
5837         ata_for_each_link(link, ap, HOST_FIRST) {
5838                 ata_for_each_dev(adev, link, ENABLED)
5839                         if (adev->class == ATA_DEV_ATAPI &&
5840                             !zpodd_dev_enabled(adev))
5841                                 return -EBUSY;
5842         }
5843
5844         return 0;
5845 }
5846
5847 static int ata_port_runtime_suspend(struct device *dev)
5848 {
5849         ata_port_suspend(to_ata_port(dev), PMSG_AUTO_SUSPEND);
5850         return 0;
5851 }
5852
5853 static int ata_port_runtime_resume(struct device *dev)
5854 {
5855         ata_port_resume(to_ata_port(dev), PMSG_AUTO_RESUME);
5856         return 0;
5857 }
5858
5859 static const struct dev_pm_ops ata_port_pm_ops = {
5860         .suspend = ata_port_pm_suspend,
5861         .resume = ata_port_pm_resume,
5862         .freeze = ata_port_pm_freeze,
5863         .thaw = ata_port_pm_resume,
5864         .poweroff = ata_port_pm_poweroff,
5865         .restore = ata_port_pm_resume,
5866
5867         .runtime_suspend = ata_port_runtime_suspend,
5868         .runtime_resume = ata_port_runtime_resume,
5869         .runtime_idle = ata_port_runtime_idle,
5870 };
5871
5872 /* sas ports don't participate in pm runtime management of ata_ports,
5873  * and need to resume ata devices at the domain level, not the per-port
5874  * level. sas suspend/resume is async to allow parallel port recovery
5875  * since sas has multiple ata_port instances per Scsi_Host.
5876  */
5877 void ata_sas_port_suspend(struct ata_port *ap)
5878 {
5879         ata_port_suspend_async(ap, PMSG_SUSPEND);
5880 }
5881 EXPORT_SYMBOL_GPL(ata_sas_port_suspend);
5882
5883 void ata_sas_port_resume(struct ata_port *ap)
5884 {
5885         ata_port_resume_async(ap, PMSG_RESUME);
5886 }
5887 EXPORT_SYMBOL_GPL(ata_sas_port_resume);
5888
5889 /**
5890  *      ata_host_suspend - suspend host
5891  *      @host: host to suspend
5892  *      @mesg: PM message
5893  *
5894  *      Suspend @host.  Actual operation is performed by port suspend.
5895  */
5896 int ata_host_suspend(struct ata_host *host, pm_message_t mesg)
5897 {
5898         host->dev->power.power_state = mesg;
5899         return 0;
5900 }
5901
5902 /**
5903  *      ata_host_resume - resume host
5904  *      @host: host to resume
5905  *
5906  *      Resume @host.  Actual operation is performed by port resume.
5907  */
5908 void ata_host_resume(struct ata_host *host)
5909 {
5910         host->dev->power.power_state = PMSG_ON;
5911 }
5912 #endif
5913
5914 struct device_type ata_port_type = {
5915         .name = "ata_port",
5916 #ifdef CONFIG_PM
5917         .pm = &ata_port_pm_ops,
5918 #endif
5919 };
5920
5921 /**
5922  *      ata_dev_init - Initialize an ata_device structure
5923  *      @dev: Device structure to initialize
5924  *
5925  *      Initialize @dev in preparation for probing.
5926  *
5927  *      LOCKING:
5928  *      Inherited from caller.
5929  */
5930 void ata_dev_init(struct ata_device *dev)
5931 {
5932         struct ata_link *link = ata_dev_phys_link(dev);
5933         struct ata_port *ap = link->ap;
5934         unsigned long flags;
5935
5936         /* SATA spd limit is bound to the attached device, reset together */
5937         link->sata_spd_limit = link->hw_sata_spd_limit;
5938         link->sata_spd = 0;
5939
5940         /* High bits of dev->flags are used to record warm plug
5941          * requests which occur asynchronously.  Synchronize using
5942          * host lock.
5943          */
5944         spin_lock_irqsave(ap->lock, flags);
5945         dev->flags &= ~ATA_DFLAG_INIT_MASK;
5946         dev->horkage = 0;
5947         spin_unlock_irqrestore(ap->lock, flags);
5948
5949         memset((void *)dev + ATA_DEVICE_CLEAR_BEGIN, 0,
5950                ATA_DEVICE_CLEAR_END - ATA_DEVICE_CLEAR_BEGIN);
5951         dev->pio_mask = UINT_MAX;
5952         dev->mwdma_mask = UINT_MAX;
5953         dev->udma_mask = UINT_MAX;
5954 }
5955
5956 /**
5957  *      ata_link_init - Initialize an ata_link structure
5958  *      @ap: ATA port link is attached to
5959  *      @link: Link structure to initialize
5960  *      @pmp: Port multiplier port number
5961  *
5962  *      Initialize @link.
5963  *
5964  *      LOCKING:
5965  *      Kernel thread context (may sleep)
5966  */
5967 void ata_link_init(struct ata_port *ap, struct ata_link *link, int pmp)
5968 {
5969         int i;
5970
5971         /* clear everything except for devices */
5972         memset((void *)link + ATA_LINK_CLEAR_BEGIN, 0,
5973                ATA_LINK_CLEAR_END - ATA_LINK_CLEAR_BEGIN);
5974
5975         link->ap = ap;
5976         link->pmp = pmp;
5977         link->active_tag = ATA_TAG_POISON;
5978         link->hw_sata_spd_limit = UINT_MAX;
5979
5980         /* can't use iterator, ap isn't initialized yet */
5981         for (i = 0; i < ATA_MAX_DEVICES; i++) {
5982                 struct ata_device *dev = &link->device[i];
5983
5984                 dev->link = link;
5985                 dev->devno = dev - link->device;
5986 #ifdef CONFIG_ATA_ACPI
5987                 dev->gtf_filter = ata_acpi_gtf_filter;
5988 #endif
5989                 ata_dev_init(dev);
5990         }
5991 }
5992
5993 /**
5994  *      sata_link_init_spd - Initialize link->sata_spd_limit
5995  *      @link: Link to configure sata_spd_limit for
5996  *
5997  *      Initialize @link->[hw_]sata_spd_limit to the currently
5998  *      configured value.
5999  *
6000  *      LOCKING:
6001  *      Kernel thread context (may sleep).
6002  *
6003  *      RETURNS:
6004  *      0 on success, -errno on failure.
6005  */
6006 int sata_link_init_spd(struct ata_link *link)
6007 {
6008         u8 spd;
6009         int rc;
6010
6011         rc = sata_scr_read(link, SCR_CONTROL, &link->saved_scontrol);
6012         if (rc)
6013                 return rc;
6014
6015         spd = (link->saved_scontrol >> 4) & 0xf;
6016         if (spd)
6017                 link->hw_sata_spd_limit &= (1 << spd) - 1;
6018
6019         ata_force_link_limits(link);
6020
6021         link->sata_spd_limit = link->hw_sata_spd_limit;
6022
6023         return 0;
6024 }
6025
6026 /**
6027  *      ata_port_alloc - allocate and initialize basic ATA port resources
6028  *      @host: ATA host this allocated port belongs to
6029  *
6030  *      Allocate and initialize basic ATA port resources.
6031  *
6032  *      RETURNS:
6033  *      Allocate ATA port on success, NULL on failure.
6034  *
6035  *      LOCKING:
6036  *      Inherited from calling layer (may sleep).
6037  */
6038 struct ata_port *ata_port_alloc(struct ata_host *host)
6039 {
6040         struct ata_port *ap;
6041
6042         DPRINTK("ENTER\n");
6043
6044         ap = kzalloc(sizeof(*ap), GFP_KERNEL);
6045         if (!ap)
6046                 return NULL;
6047
6048         ap->pflags |= ATA_PFLAG_INITIALIZING | ATA_PFLAG_FROZEN;
6049         ap->lock = &host->lock;
6050         ap->print_id = -1;
6051         ap->local_port_no = -1;
6052         ap->host = host;
6053         ap->dev = host->dev;
6054
6055 #if defined(ATA_VERBOSE_DEBUG)
6056         /* turn on all debugging levels */
6057         ap->msg_enable = 0x00FF;
6058 #elif defined(ATA_DEBUG)
6059         ap->msg_enable = ATA_MSG_DRV | ATA_MSG_INFO | ATA_MSG_CTL | ATA_MSG_WARN | ATA_MSG_ERR;
6060 #else
6061         ap->msg_enable = ATA_MSG_DRV | ATA_MSG_ERR | ATA_MSG_WARN;
6062 #endif
6063
6064         mutex_init(&ap->scsi_scan_mutex);
6065         INIT_DELAYED_WORK(&ap->hotplug_task, ata_scsi_hotplug);
6066         INIT_WORK(&ap->scsi_rescan_task, ata_scsi_dev_rescan);
6067         INIT_LIST_HEAD(&ap->eh_done_q);
6068         init_waitqueue_head(&ap->eh_wait_q);
6069         init_completion(&ap->park_req_pending);
6070         setup_deferrable_timer(&ap->fastdrain_timer,
6071                                ata_eh_fastdrain_timerfn,
6072                                (unsigned long)ap);
6073
6074         ap->cbl = ATA_CBL_NONE;
6075
6076         ata_link_init(ap, &ap->link, 0);
6077
6078 #ifdef ATA_IRQ_TRAP
6079         ap->stats.unhandled_irq = 1;
6080         ap->stats.idle_irq = 1;
6081 #endif
6082         ata_sff_port_init(ap);
6083
6084         return ap;
6085 }
6086
6087 static void ata_host_release(struct device *gendev, void *res)
6088 {
6089         struct ata_host *host = dev_get_drvdata(gendev);
6090         int i;
6091
6092         for (i = 0; i < host->n_ports; i++) {
6093                 struct ata_port *ap = host->ports[i];
6094
6095                 if (!ap)
6096                         continue;
6097
6098                 if (ap->scsi_host)
6099                         scsi_host_put(ap->scsi_host);
6100
6101                 kfree(ap->pmp_link);
6102                 kfree(ap->slave_link);
6103                 kfree(ap);
6104                 host->ports[i] = NULL;
6105         }
6106
6107         dev_set_drvdata(gendev, NULL);
6108 }
6109
6110 /**
6111  *      ata_host_alloc - allocate and init basic ATA host resources
6112  *      @dev: generic device this host is associated with
6113  *      @max_ports: maximum number of ATA ports associated with this host
6114  *
6115  *      Allocate and initialize basic ATA host resources.  LLD calls
6116  *      this function to allocate a host, initializes it fully and
6117  *      attaches it using ata_host_register().
6118  *
6119  *      @max_ports ports are allocated and host->n_ports is
6120  *      initialized to @max_ports.  The caller is allowed to decrease
6121  *      host->n_ports before calling ata_host_register().  The unused
6122  *      ports will be automatically freed on registration.
6123  *
6124  *      RETURNS:
6125  *      Allocate ATA host on success, NULL on failure.
6126  *
6127  *      LOCKING:
6128  *      Inherited from calling layer (may sleep).
6129  */
6130 struct ata_host *ata_host_alloc(struct device *dev, int max_ports)
6131 {
6132         struct ata_host *host;
6133         size_t sz;
6134         int i;
6135
6136         DPRINTK("ENTER\n");
6137
6138         if (!devres_open_group(dev, NULL, GFP_KERNEL))
6139                 return NULL;
6140
6141         /* alloc a container for our list of ATA ports (buses) */
6142         sz = sizeof(struct ata_host) + (max_ports + 1) * sizeof(void *);
6143         /* alloc a container for our list of ATA ports (buses) */
6144         host = devres_alloc(ata_host_release, sz, GFP_KERNEL);
6145         if (!host)
6146                 goto err_out;
6147
6148         devres_add(dev, host);
6149         dev_set_drvdata(dev, host);
6150
6151         spin_lock_init(&host->lock);
6152         mutex_init(&host->eh_mutex);
6153         host->dev = dev;
6154         host->n_ports = max_ports;
6155
6156         /* allocate ports bound to this host */
6157         for (i = 0; i < max_ports; i++) {
6158                 struct ata_port *ap;
6159
6160                 ap = ata_port_alloc(host);
6161                 if (!ap)
6162                         goto err_out;
6163
6164                 ap->port_no = i;
6165                 host->ports[i] = ap;
6166         }
6167
6168         devres_remove_group(dev, NULL);
6169         return host;
6170
6171  err_out:
6172         devres_release_group(dev, NULL);
6173         return NULL;
6174 }
6175
6176 /**
6177  *      ata_host_alloc_pinfo - alloc host and init with port_info array
6178  *      @dev: generic device this host is associated with
6179  *      @ppi: array of ATA port_info to initialize host with
6180  *      @n_ports: number of ATA ports attached to this host
6181  *
6182  *      Allocate ATA host and initialize with info from @ppi.  If NULL
6183  *      terminated, @ppi may contain fewer entries than @n_ports.  The
6184  *      last entry will be used for the remaining ports.
6185  *
6186  *      RETURNS:
6187  *      Allocate ATA host on success, NULL on failure.
6188  *
6189  *      LOCKING:
6190  *      Inherited from calling layer (may sleep).
6191  */
6192 struct ata_host *ata_host_alloc_pinfo(struct device *dev,
6193                                       const struct ata_port_info * const * ppi,
6194                                       int n_ports)
6195 {
6196         const struct ata_port_info *pi = &ata_dummy_port_info;
6197         struct ata_host *host;
6198         int i, j;
6199
6200         host = ata_host_alloc(dev, n_ports);
6201         if (!host)
6202                 return NULL;
6203
6204         for (i = 0, j = 0; i < host->n_ports; i++) {
6205                 struct ata_port *ap = host->ports[i];
6206
6207                 if (ppi[j])
6208                         pi = ppi[j++];
6209
6210                 ap->pio_mask = pi->pio_mask;
6211                 ap->mwdma_mask = pi->mwdma_mask;
6212                 ap->udma_mask = pi->udma_mask;
6213                 ap->flags |= pi->flags;
6214                 ap->link.flags |= pi->link_flags;
6215                 ap->ops = pi->port_ops;
6216
6217                 if (!host->ops && (pi->port_ops != &ata_dummy_port_ops))
6218                         host->ops = pi->port_ops;
6219         }
6220
6221         return host;
6222 }
6223
6224 /**
6225  *      ata_slave_link_init - initialize slave link
6226  *      @ap: port to initialize slave link for
6227  *
6228  *      Create and initialize slave link for @ap.  This enables slave
6229  *      link handling on the port.
6230  *
6231  *      In libata, a port contains links and a link contains devices.
6232  *      There is single host link but if a PMP is attached to it,
6233  *      there can be multiple fan-out links.  On SATA, there's usually
6234  *      a single device connected to a link but PATA and SATA
6235  *      controllers emulating TF based interface can have two - master
6236  *      and slave.
6237  *
6238  *      However, there are a few controllers which don't fit into this
6239  *      abstraction too well - SATA controllers which emulate TF
6240  *      interface with both master and slave devices but also have
6241  *      separate SCR register sets for each device.  These controllers
6242  *      need separate links for physical link handling
6243  *      (e.g. onlineness, link speed) but should be treated like a
6244  *      traditional M/S controller for everything else (e.g. command
6245  *      issue, softreset).
6246  *
6247  *      slave_link is libata's way of handling this class of
6248  *      controllers without impacting core layer too much.  For
6249  *      anything other than physical link handling, the default host
6250  *      link is used for both master and slave.  For physical link
6251  *      handling, separate @ap->slave_link is used.  All dirty details
6252  *      are implemented inside libata core layer.  From LLD's POV, the
6253  *      only difference is that prereset, hardreset and postreset are
6254  *      called once more for the slave link, so the reset sequence
6255  *      looks like the following.
6256  *
6257  *      prereset(M) -> prereset(S) -> hardreset(M) -> hardreset(S) ->
6258  *      softreset(M) -> postreset(M) -> postreset(S)
6259  *
6260  *      Note that softreset is called only for the master.  Softreset
6261  *      resets both M/S by definition, so SRST on master should handle
6262  *      both (the standard method will work just fine).
6263  *
6264  *      LOCKING:
6265  *      Should be called before host is registered.
6266  *
6267  *      RETURNS:
6268  *      0 on success, -errno on failure.
6269  */
6270 int ata_slave_link_init(struct ata_port *ap)
6271 {
6272         struct ata_link *link;
6273
6274         WARN_ON(ap->slave_link);
6275         WARN_ON(ap->flags & ATA_FLAG_PMP);
6276
6277         link = kzalloc(sizeof(*link), GFP_KERNEL);
6278         if (!link)
6279                 return -ENOMEM;
6280
6281         ata_link_init(ap, link, 1);
6282         ap->slave_link = link;
6283         return 0;
6284 }
6285
6286 static void ata_host_stop(struct device *gendev, void *res)
6287 {
6288         struct ata_host *host = dev_get_drvdata(gendev);
6289         int i;
6290
6291         WARN_ON(!(host->flags & ATA_HOST_STARTED));
6292
6293         for (i = 0; i < host->n_ports; i++) {
6294                 struct ata_port *ap = host->ports[i];
6295
6296                 if (ap->ops->port_stop)
6297                         ap->ops->port_stop(ap);
6298         }
6299
6300         if (host->ops->host_stop)
6301                 host->ops->host_stop(host);
6302 }
6303
6304 /**
6305  *      ata_finalize_port_ops - finalize ata_port_operations
6306  *      @ops: ata_port_operations to finalize
6307  *
6308  *      An ata_port_operations can inherit from another ops and that
6309  *      ops can again inherit from another.  This can go on as many
6310  *      times as necessary as long as there is no loop in the
6311  *      inheritance chain.
6312  *
6313  *      Ops tables are finalized when the host is started.  NULL or
6314  *      unspecified entries are inherited from the closet ancestor
6315  *      which has the method and the entry is populated with it.
6316  *      After finalization, the ops table directly points to all the
6317  *      methods and ->inherits is no longer necessary and cleared.
6318  *
6319  *      Using ATA_OP_NULL, inheriting ops can force a method to NULL.
6320  *
6321  *      LOCKING:
6322  *      None.
6323  */
6324 static void ata_finalize_port_ops(struct ata_port_operations *ops)
6325 {
6326         static DEFINE_SPINLOCK(lock);
6327         const struct ata_port_operations *cur;
6328         void **begin = (void **)ops;
6329         void **end = (void **)&ops->inherits;
6330         void **pp;
6331
6332         if (!ops || !ops->inherits)
6333                 return;
6334
6335         spin_lock(&lock);
6336
6337         for (cur = ops->inherits; cur; cur = cur->inherits) {
6338                 void **inherit = (void **)cur;
6339
6340                 for (pp = begin; pp < end; pp++, inherit++)
6341                         if (!*pp)
6342                                 *pp = *inherit;
6343         }
6344
6345         for (pp = begin; pp < end; pp++)
6346                 if (IS_ERR(*pp))
6347                         *pp = NULL;
6348
6349         ops->inherits = NULL;
6350
6351         spin_unlock(&lock);
6352 }
6353
6354 /**
6355  *      ata_host_start - start and freeze ports of an ATA host
6356  *      @host: ATA host to start ports for
6357  *
6358  *      Start and then freeze ports of @host.  Started status is
6359  *      recorded in host->flags, so this function can be called
6360  *      multiple times.  Ports are guaranteed to get started only
6361  *      once.  If host->ops isn't initialized yet, its set to the
6362  *      first non-dummy port ops.
6363  *
6364  *      LOCKING:
6365  *      Inherited from calling layer (may sleep).
6366  *
6367  *      RETURNS:
6368  *      0 if all ports are started successfully, -errno otherwise.
6369  */
6370 int ata_host_start(struct ata_host *host)
6371 {
6372         int have_stop = 0;
6373         void *start_dr = NULL;
6374         int i, rc;
6375
6376         if (host->flags & ATA_HOST_STARTED)
6377                 return 0;
6378
6379         ata_finalize_port_ops(host->ops);
6380
6381         for (i = 0; i < host->n_ports; i++) {
6382                 struct ata_port *ap = host->ports[i];
6383
6384                 ata_finalize_port_ops(ap->ops);
6385
6386                 if (!host->ops && !ata_port_is_dummy(ap))
6387                         host->ops = ap->ops;
6388
6389                 if (ap->ops->port_stop)
6390                         have_stop = 1;
6391         }
6392
6393         if (host->ops && host->ops->host_stop)
6394                 have_stop = 1;
6395
6396         if (have_stop) {
6397                 start_dr = devres_alloc(ata_host_stop, 0, GFP_KERNEL);
6398                 if (!start_dr)
6399                         return -ENOMEM;
6400         }
6401
6402         for (i = 0; i < host->n_ports; i++) {
6403                 struct ata_port *ap = host->ports[i];
6404
6405                 if (ap->ops->port_start) {
6406                         rc = ap->ops->port_start(ap);
6407                         if (rc) {
6408                                 if (rc != -ENODEV)
6409                                         dev_err(host->dev,
6410                                                 "failed to start port %d (errno=%d)\n",
6411                                                 i, rc);
6412                                 goto err_out;
6413                         }
6414                 }
6415                 ata_eh_freeze_port(ap);
6416         }
6417
6418         if (start_dr)
6419                 devres_add(host->dev, start_dr);
6420         host->flags |= ATA_HOST_STARTED;
6421         return 0;
6422
6423  err_out:
6424         while (--i >= 0) {
6425                 struct ata_port *ap = host->ports[i];
6426
6427                 if (ap->ops->port_stop)
6428                         ap->ops->port_stop(ap);
6429         }
6430         devres_free(start_dr);
6431         return rc;
6432 }
6433
6434 /**
6435  *      ata_sas_host_init - Initialize a host struct for sas (ipr, libsas)
6436  *      @host:  host to initialize
6437  *      @dev:   device host is attached to
6438  *      @ops:   port_ops
6439  *
6440  */
6441 void ata_host_init(struct ata_host *host, struct device *dev,
6442                    struct ata_port_operations *ops)
6443 {
6444         spin_lock_init(&host->lock);
6445         mutex_init(&host->eh_mutex);
6446         host->n_tags = ATA_MAX_QUEUE - 1;
6447         host->dev = dev;
6448         host->ops = ops;
6449 }
6450
6451 void __ata_port_probe(struct ata_port *ap)
6452 {
6453         struct ata_eh_info *ehi = &ap->link.eh_info;
6454         unsigned long flags;
6455
6456         /* kick EH for boot probing */
6457         spin_lock_irqsave(ap->lock, flags);
6458
6459         ehi->probe_mask |= ATA_ALL_DEVICES;
6460         ehi->action |= ATA_EH_RESET;
6461         ehi->flags |= ATA_EHI_NO_AUTOPSY | ATA_EHI_QUIET;
6462
6463         ap->pflags &= ~ATA_PFLAG_INITIALIZING;
6464         ap->pflags |= ATA_PFLAG_LOADING;
6465         ata_port_schedule_eh(ap);
6466
6467         spin_unlock_irqrestore(ap->lock, flags);
6468 }
6469
6470 int ata_port_probe(struct ata_port *ap)
6471 {
6472         int rc = 0;
6473
6474         if (ap->ops->error_handler) {
6475                 __ata_port_probe(ap);
6476                 ata_port_wait_eh(ap);
6477         } else {
6478                 DPRINTK("ata%u: bus probe begin\n", ap->print_id);
6479                 rc = ata_bus_probe(ap);
6480                 DPRINTK("ata%u: bus probe end\n", ap->print_id);
6481         }
6482         return rc;
6483 }
6484
6485
6486 static void async_port_probe(void *data, async_cookie_t cookie)
6487 {
6488         struct ata_port *ap = data;
6489
6490         /*
6491          * If we're not allowed to scan this host in parallel,
6492          * we need to wait until all previous scans have completed
6493          * before going further.
6494          * Jeff Garzik says this is only within a controller, so we
6495          * don't need to wait for port 0, only for later ports.
6496          */
6497         if (!(ap->host->flags & ATA_HOST_PARALLEL_SCAN) && ap->port_no != 0)
6498                 async_synchronize_cookie(cookie);
6499
6500         (void)ata_port_probe(ap);
6501
6502         /* in order to keep device order, we need to synchronize at this point */
6503         async_synchronize_cookie(cookie);
6504
6505         ata_scsi_scan_host(ap, 1);
6506 }
6507
6508 /**
6509  *      ata_host_register - register initialized ATA host
6510  *      @host: ATA host to register
6511  *      @sht: template for SCSI host
6512  *
6513  *      Register initialized ATA host.  @host is allocated using
6514  *      ata_host_alloc() and fully initialized by LLD.  This function
6515  *      starts ports, registers @host with ATA and SCSI layers and
6516  *      probe registered devices.
6517  *
6518  *      LOCKING:
6519  *      Inherited from calling layer (may sleep).
6520  *
6521  *      RETURNS:
6522  *      0 on success, -errno otherwise.
6523  */
6524 int ata_host_register(struct ata_host *host, struct scsi_host_template *sht)
6525 {
6526         int i, rc;
6527
6528         host->n_tags = clamp(sht->can_queue, 1, ATA_MAX_QUEUE - 1);
6529
6530         /* host must have been started */
6531         if (!(host->flags & ATA_HOST_STARTED)) {
6532                 dev_err(host->dev, "BUG: trying to register unstarted host\n");
6533                 WARN_ON(1);
6534                 return -EINVAL;
6535         }
6536
6537         /* Blow away unused ports.  This happens when LLD can't
6538          * determine the exact number of ports to allocate at
6539          * allocation time.
6540          */
6541         for (i = host->n_ports; host->ports[i]; i++)
6542                 kfree(host->ports[i]);
6543
6544         /* give ports names and add SCSI hosts */
6545         for (i = 0; i < host->n_ports; i++) {
6546                 host->ports[i]->print_id = atomic_inc_return(&ata_print_id);
6547                 host->ports[i]->local_port_no = i + 1;
6548         }
6549
6550         /* Create associated sysfs transport objects  */
6551         for (i = 0; i < host->n_ports; i++) {
6552                 rc = ata_tport_add(host->dev,host->ports[i]);
6553                 if (rc) {
6554                         goto err_tadd;
6555                 }
6556         }
6557
6558         rc = ata_scsi_add_hosts(host, sht);
6559         if (rc)
6560                 goto err_tadd;
6561
6562         /* set cable, sata_spd_limit and report */
6563         for (i = 0; i < host->n_ports; i++) {
6564                 struct ata_port *ap = host->ports[i];
6565                 unsigned long xfer_mask;
6566
6567                 /* set SATA cable type if still unset */
6568                 if (ap->cbl == ATA_CBL_NONE && (ap->flags & ATA_FLAG_SATA))
6569                         ap->cbl = ATA_CBL_SATA;
6570
6571                 /* init sata_spd_limit to the current value */
6572                 sata_link_init_spd(&ap->link);
6573                 if (ap->slave_link)
6574                         sata_link_init_spd(ap->slave_link);
6575
6576                 /* print per-port info to dmesg */
6577                 xfer_mask = ata_pack_xfermask(ap->pio_mask, ap->mwdma_mask,
6578                                               ap->udma_mask);
6579
6580                 if (!ata_port_is_dummy(ap)) {
6581                         ata_port_info(ap, "%cATA max %s %s\n",
6582                                       (ap->flags & ATA_FLAG_SATA) ? 'S' : 'P',
6583                                       ata_mode_string(xfer_mask),
6584                                       ap->link.eh_info.desc);
6585                         ata_ehi_clear_desc(&ap->link.eh_info);
6586                 } else
6587                         ata_port_info(ap, "DUMMY\n");
6588         }
6589
6590         /* perform each probe asynchronously */
6591         for (i = 0; i < host->n_ports; i++) {
6592                 struct ata_port *ap = host->ports[i];
6593                 ap->cookie = async_schedule(async_port_probe, ap);
6594         }
6595
6596         return 0;
6597
6598  err_tadd:
6599         while (--i >= 0) {
6600                 ata_tport_delete(host->ports[i]);
6601         }
6602         return rc;
6603
6604 }
6605
6606 /**
6607  *      ata_host_activate - start host, request IRQ and register it
6608  *      @host: target ATA host
6609  *      @irq: IRQ to request
6610  *      @irq_handler: irq_handler used when requesting IRQ
6611  *      @irq_flags: irq_flags used when requesting IRQ
6612  *      @sht: scsi_host_template to use when registering the host
6613  *
6614  *      After allocating an ATA host and initializing it, most libata
6615  *      LLDs perform three steps to activate the host - start host,
6616  *      request IRQ and register it.  This helper takes necessary
6617  *      arguments and performs the three steps in one go.
6618  *
6619  *      An invalid IRQ skips the IRQ registration and expects the host to
6620  *      have set polling mode on the port. In this case, @irq_handler
6621  *      should be NULL.
6622  *
6623  *      LOCKING:
6624  *      Inherited from calling layer (may sleep).
6625  *
6626  *      RETURNS:
6627  *      0 on success, -errno otherwise.
6628  */
6629 int ata_host_activate(struct ata_host *host, int irq,
6630                       irq_handler_t irq_handler, unsigned long irq_flags,
6631                       struct scsi_host_template *sht)
6632 {
6633         int i, rc;
6634         char *irq_desc;
6635
6636         rc = ata_host_start(host);
6637         if (rc)
6638                 return rc;
6639
6640         /* Special case for polling mode */
6641         if (!irq) {
6642                 WARN_ON(irq_handler);
6643                 return ata_host_register(host, sht);
6644         }
6645
6646         irq_desc = devm_kasprintf(host->dev, GFP_KERNEL, "%s[%s]",
6647                                   dev_driver_string(host->dev),
6648                                   dev_name(host->dev));
6649         if (!irq_desc)
6650                 return -ENOMEM;
6651
6652         rc = devm_request_irq(host->dev, irq, irq_handler, irq_flags,
6653                               irq_desc, host);
6654         if (rc)
6655                 return rc;
6656
6657         for (i = 0; i < host->n_ports; i++)
6658                 ata_port_desc(host->ports[i], "irq %d", irq);
6659
6660         rc = ata_host_register(host, sht);
6661         /* if failed, just free the IRQ and leave ports alone */
6662         if (rc)
6663                 devm_free_irq(host->dev, irq, host);
6664
6665         return rc;
6666 }
6667
6668 /**
6669  *      ata_port_detach - Detach ATA port in preparation of device removal
6670  *      @ap: ATA port to be detached
6671  *
6672  *      Detach all ATA devices and the associated SCSI devices of @ap;
6673  *      then, remove the associated SCSI host.  @ap is guaranteed to
6674  *      be quiescent on return from this function.
6675  *
6676  *      LOCKING:
6677  *      Kernel thread context (may sleep).
6678  */
6679 static void ata_port_detach(struct ata_port *ap)
6680 {
6681         unsigned long flags;
6682         struct ata_link *link;
6683         struct ata_device *dev;
6684
6685         if (!ap->ops->error_handler)
6686                 goto skip_eh;
6687
6688         /* Wait for any ongoing EH */
6689         ata_port_wait_eh(ap);
6690
6691         mutex_lock(&ap->scsi_scan_mutex);
6692         spin_lock_irqsave(ap->lock, flags);
6693
6694         /* Remove scsi devices */
6695         ata_for_each_link(link, ap, HOST_FIRST) {
6696                 ata_for_each_dev(dev, link, ALL) {
6697                         if (dev->sdev) {
6698                                 spin_unlock_irqrestore(ap->lock, flags);
6699                                 scsi_remove_device(dev->sdev);
6700                                 spin_lock_irqsave(ap->lock, flags);
6701                                 dev->sdev = NULL;
6702                         }
6703                 }
6704         }
6705
6706         /* Tell EH to disable all devices */
6707         ap->pflags |= ATA_PFLAG_UNLOADING;
6708         ata_port_schedule_eh(ap);
6709
6710         spin_unlock_irqrestore(ap->lock, flags);
6711         mutex_unlock(&ap->scsi_scan_mutex);
6712
6713         /* wait till EH commits suicide */
6714         ata_port_wait_eh(ap);
6715
6716         /* it better be dead now */
6717         WARN_ON(!(ap->pflags & ATA_PFLAG_UNLOADED));
6718
6719         cancel_delayed_work_sync(&ap->hotplug_task);
6720
6721  skip_eh:
6722         /* clean up zpodd on port removal */
6723         ata_for_each_link(link, ap, HOST_FIRST) {
6724                 ata_for_each_dev(dev, link, ALL) {
6725                         if (zpodd_dev_enabled(dev))
6726                                 zpodd_exit(dev);
6727                 }
6728         }
6729         if (ap->pmp_link) {
6730                 int i;
6731                 for (i = 0; i < SATA_PMP_MAX_PORTS; i++)
6732                         ata_tlink_delete(&ap->pmp_link[i]);
6733         }
6734         /* remove the associated SCSI host */
6735         scsi_remove_host(ap->scsi_host);
6736         ata_tport_delete(ap);
6737 }
6738
6739 /**
6740  *      ata_host_detach - Detach all ports of an ATA host
6741  *      @host: Host to detach
6742  *
6743  *      Detach all ports of @host.
6744  *
6745  *      LOCKING:
6746  *      Kernel thread context (may sleep).
6747  */
6748 void ata_host_detach(struct ata_host *host)
6749 {
6750         int i;
6751
6752         for (i = 0; i < host->n_ports; i++) {
6753                 /* Ensure ata_port probe has completed */
6754                 async_synchronize_cookie(host->ports[i]->cookie + 1);
6755                 ata_port_detach(host->ports[i]);
6756         }
6757
6758         /* the host is dead now, dissociate ACPI */
6759         ata_acpi_dissociate(host);
6760 }
6761
6762 #ifdef CONFIG_PCI
6763
6764 /**
6765  *      ata_pci_remove_one - PCI layer callback for device removal
6766  *      @pdev: PCI device that was removed
6767  *
6768  *      PCI layer indicates to libata via this hook that hot-unplug or
6769  *      module unload event has occurred.  Detach all ports.  Resource
6770  *      release is handled via devres.
6771  *
6772  *      LOCKING:
6773  *      Inherited from PCI layer (may sleep).
6774  */
6775 void ata_pci_remove_one(struct pci_dev *pdev)
6776 {
6777         struct ata_host *host = pci_get_drvdata(pdev);
6778
6779         ata_host_detach(host);
6780 }
6781
6782 void ata_pci_shutdown_one(struct pci_dev *pdev)
6783 {
6784         struct ata_host *host = pci_get_drvdata(pdev);
6785         int i;
6786
6787         for (i = 0; i < host->n_ports; i++) {
6788                 struct ata_port *ap = host->ports[i];
6789
6790                 ap->pflags |= ATA_PFLAG_FROZEN;
6791
6792                 /* Disable port interrupts */
6793                 if (ap->ops->freeze)
6794                         ap->ops->freeze(ap);
6795
6796                 /* Stop the port DMA engines */
6797                 if (ap->ops->port_stop)
6798                         ap->ops->port_stop(ap);
6799         }
6800 }
6801
6802 /* move to PCI subsystem */
6803 int pci_test_config_bits(struct pci_dev *pdev, const struct pci_bits *bits)
6804 {
6805         unsigned long tmp = 0;
6806
6807         switch (bits->width) {
6808         case 1: {
6809                 u8 tmp8 = 0;
6810                 pci_read_config_byte(pdev, bits->reg, &tmp8);
6811                 tmp = tmp8;
6812                 break;
6813         }
6814         case 2: {
6815                 u16 tmp16 = 0;
6816                 pci_read_config_word(pdev, bits->reg, &tmp16);
6817                 tmp = tmp16;
6818                 break;
6819         }
6820         case 4: {
6821                 u32 tmp32 = 0;
6822                 pci_read_config_dword(pdev, bits->reg, &tmp32);
6823                 tmp = tmp32;
6824                 break;
6825         }
6826
6827         default:
6828                 return -EINVAL;
6829         }
6830
6831         tmp &= bits->mask;
6832
6833         return (tmp == bits->val) ? 1 : 0;
6834 }
6835
6836 #ifdef CONFIG_PM
6837 void ata_pci_device_do_suspend(struct pci_dev *pdev, pm_message_t mesg)
6838 {
6839         pci_save_state(pdev);
6840         pci_disable_device(pdev);
6841
6842         if (mesg.event & PM_EVENT_SLEEP)
6843                 pci_set_power_state(pdev, PCI_D3hot);
6844 }
6845
6846 int ata_pci_device_do_resume(struct pci_dev *pdev)
6847 {
6848         int rc;
6849
6850         pci_set_power_state(pdev, PCI_D0);
6851         pci_restore_state(pdev);
6852
6853         rc = pcim_enable_device(pdev);
6854         if (rc) {
6855                 dev_err(&pdev->dev,
6856                         "failed to enable device after resume (%d)\n", rc);
6857                 return rc;
6858         }
6859
6860         pci_set_master(pdev);
6861         return 0;
6862 }
6863
6864 int ata_pci_device_suspend(struct pci_dev *pdev, pm_message_t mesg)
6865 {
6866         struct ata_host *host = pci_get_drvdata(pdev);
6867         int rc = 0;
6868
6869         rc = ata_host_suspend(host, mesg);
6870         if (rc)
6871                 return rc;
6872
6873         ata_pci_device_do_suspend(pdev, mesg);
6874
6875         return 0;
6876 }
6877
6878 int ata_pci_device_resume(struct pci_dev *pdev)
6879 {
6880         struct ata_host *host = pci_get_drvdata(pdev);
6881         int rc;
6882
6883         rc = ata_pci_device_do_resume(pdev);
6884         if (rc == 0)
6885                 ata_host_resume(host);
6886         return rc;
6887 }
6888 #endif /* CONFIG_PM */
6889
6890 #endif /* CONFIG_PCI */
6891
6892 /**
6893  *      ata_platform_remove_one - Platform layer callback for device removal
6894  *      @pdev: Platform device that was removed
6895  *
6896  *      Platform layer indicates to libata via this hook that hot-unplug or
6897  *      module unload event has occurred.  Detach all ports.  Resource
6898  *      release is handled via devres.
6899  *
6900  *      LOCKING:
6901  *      Inherited from platform layer (may sleep).
6902  */
6903 int ata_platform_remove_one(struct platform_device *pdev)
6904 {
6905         struct ata_host *host = platform_get_drvdata(pdev);
6906
6907         ata_host_detach(host);
6908
6909         return 0;
6910 }
6911
6912 static int __init ata_parse_force_one(char **cur,
6913                                       struct ata_force_ent *force_ent,
6914                                       const char **reason)
6915 {
6916         static const struct ata_force_param force_tbl[] __initconst = {
6917                 { "40c",        .cbl            = ATA_CBL_PATA40 },
6918                 { "80c",        .cbl            = ATA_CBL_PATA80 },
6919                 { "short40c",   .cbl            = ATA_CBL_PATA40_SHORT },
6920                 { "unk",        .cbl            = ATA_CBL_PATA_UNK },
6921                 { "ign",        .cbl            = ATA_CBL_PATA_IGN },
6922                 { "sata",       .cbl            = ATA_CBL_SATA },
6923                 { "1.5Gbps",    .spd_limit      = 1 },
6924                 { "3.0Gbps",    .spd_limit      = 2 },
6925                 { "noncq",      .horkage_on     = ATA_HORKAGE_NONCQ },
6926                 { "ncq",        .horkage_off    = ATA_HORKAGE_NONCQ },
6927                 { "noncqtrim",  .horkage_on     = ATA_HORKAGE_NO_NCQ_TRIM },
6928                 { "ncqtrim",    .horkage_off    = ATA_HORKAGE_NO_NCQ_TRIM },
6929                 { "noncqati",   .horkage_on     = ATA_HORKAGE_NO_NCQ_ON_ATI },
6930                 { "ncqati",     .horkage_off    = ATA_HORKAGE_NO_NCQ_ON_ATI },
6931                 { "dump_id",    .horkage_on     = ATA_HORKAGE_DUMP_ID },
6932                 { "pio0",       .xfer_mask      = 1 << (ATA_SHIFT_PIO + 0) },
6933                 { "pio1",       .xfer_mask      = 1 << (ATA_SHIFT_PIO + 1) },
6934                 { "pio2",       .xfer_mask      = 1 << (ATA_SHIFT_PIO + 2) },
6935                 { "pio3",       .xfer_mask      = 1 << (ATA_SHIFT_PIO + 3) },
6936                 { "pio4",       .xfer_mask      = 1 << (ATA_SHIFT_PIO + 4) },
6937                 { "pio5",       .xfer_mask      = 1 << (ATA_SHIFT_PIO + 5) },
6938                 { "pio6",       .xfer_mask      = 1 << (ATA_SHIFT_PIO + 6) },
6939                 { "mwdma0",     .xfer_mask      = 1 << (ATA_SHIFT_MWDMA + 0) },
6940                 { "mwdma1",     .xfer_mask      = 1 << (ATA_SHIFT_MWDMA + 1) },
6941                 { "mwdma2",     .xfer_mask      = 1 << (ATA_SHIFT_MWDMA + 2) },
6942                 { "mwdma3",     .xfer_mask      = 1 << (ATA_SHIFT_MWDMA + 3) },
6943                 { "mwdma4",     .xfer_mask      = 1 << (ATA_SHIFT_MWDMA + 4) },
6944                 { "udma0",      .xfer_mask      = 1 << (ATA_SHIFT_UDMA + 0) },
6945                 { "udma16",     .xfer_mask      = 1 << (ATA_SHIFT_UDMA + 0) },
6946                 { "udma/16",    .xfer_mask      = 1 << (ATA_SHIFT_UDMA + 0) },
6947                 { "udma1",      .xfer_mask      = 1 << (ATA_SHIFT_UDMA + 1) },
6948                 { "udma25",     .xfer_mask      = 1 << (ATA_SHIFT_UDMA + 1) },
6949                 { "udma/25",    .xfer_mask      = 1 << (ATA_SHIFT_UDMA + 1) },
6950                 { "udma2",      .xfer_mask      = 1 << (ATA_SHIFT_UDMA + 2) },
6951                 { "udma33",     .xfer_mask      = 1 << (ATA_SHIFT_UDMA + 2) },
6952                 { "udma/33",    .xfer_mask      = 1 << (ATA_SHIFT_UDMA + 2) },
6953                 { "udma3",      .xfer_mask      = 1 << (ATA_SHIFT_UDMA + 3) },
6954                 { "udma44",     .xfer_mask      = 1 << (ATA_SHIFT_UDMA + 3) },
6955                 { "udma/44",    .xfer_mask      = 1 << (ATA_SHIFT_UDMA + 3) },
6956                 { "udma4",      .xfer_mask      = 1 << (ATA_SHIFT_UDMA + 4) },
6957                 { "udma66",     .xfer_mask      = 1 << (ATA_SHIFT_UDMA + 4) },
6958                 { "udma/66",    .xfer_mask      = 1 << (ATA_SHIFT_UDMA + 4) },
6959                 { "udma5",      .xfer_mask      = 1 << (ATA_SHIFT_UDMA + 5) },
6960                 { "udma100",    .xfer_mask      = 1 << (ATA_SHIFT_UDMA + 5) },
6961                 { "udma/100",   .xfer_mask      = 1 << (ATA_SHIFT_UDMA + 5) },
6962                 { "udma6",      .xfer_mask      = 1 << (ATA_SHIFT_UDMA + 6) },
6963                 { "udma133",    .xfer_mask      = 1 << (ATA_SHIFT_UDMA + 6) },
6964                 { "udma/133",   .xfer_mask      = 1 << (ATA_SHIFT_UDMA + 6) },
6965                 { "udma7",      .xfer_mask      = 1 << (ATA_SHIFT_UDMA + 7) },
6966                 { "nohrst",     .lflags         = ATA_LFLAG_NO_HRST },
6967                 { "nosrst",     .lflags         = ATA_LFLAG_NO_SRST },
6968                 { "norst",      .lflags         = ATA_LFLAG_NO_HRST | ATA_LFLAG_NO_SRST },
6969                 { "rstonce",    .lflags         = ATA_LFLAG_RST_ONCE },
6970                 { "atapi_dmadir", .horkage_on   = ATA_HORKAGE_ATAPI_DMADIR },
6971                 { "disable",    .horkage_on     = ATA_HORKAGE_DISABLE },
6972         };
6973         char *start = *cur, *p = *cur;
6974         char *id, *val, *endp;
6975         const struct ata_force_param *match_fp = NULL;
6976         int nr_matches = 0, i;
6977
6978         /* find where this param ends and update *cur */
6979         while (*p != '\0' && *p != ',')
6980                 p++;
6981
6982         if (*p == '\0')
6983                 *cur = p;
6984         else
6985                 *cur = p + 1;
6986
6987         *p = '\0';
6988
6989         /* parse */
6990         p = strchr(start, ':');
6991         if (!p) {
6992                 val = strstrip(start);
6993                 goto parse_val;
6994         }
6995         *p = '\0';
6996
6997         id = strstrip(start);
6998         val = strstrip(p + 1);
6999
7000         /* parse id */
7001         p = strchr(id, '.');
7002         if (p) {
7003                 *p++ = '\0';
7004                 force_ent->device = simple_strtoul(p, &endp, 10);
7005                 if (p == endp || *endp != '\0') {
7006                         *reason = "invalid device";
7007                         return -EINVAL;
7008                 }
7009         }
7010
7011         force_ent->port = simple_strtoul(id, &endp, 10);
7012         if (id == endp || *endp != '\0') {
7013                 *reason = "invalid port/link";
7014                 return -EINVAL;
7015         }
7016
7017  parse_val:
7018         /* parse val, allow shortcuts so that both 1.5 and 1.5Gbps work */
7019         for (i = 0; i < ARRAY_SIZE(force_tbl); i++) {
7020                 const struct ata_force_param *fp = &force_tbl[i];
7021
7022                 if (strncasecmp(val, fp->name, strlen(val)))
7023                         continue;
7024
7025                 nr_matches++;
7026                 match_fp = fp;
7027
7028                 if (strcasecmp(val, fp->name) == 0) {
7029                         nr_matches = 1;
7030                         break;
7031                 }
7032         }
7033
7034         if (!nr_matches) {
7035                 *reason = "unknown value";
7036                 return -EINVAL;
7037         }
7038         if (nr_matches > 1) {
7039                 *reason = "ambigious value";
7040                 return -EINVAL;
7041         }
7042
7043         force_ent->param = *match_fp;
7044
7045         return 0;
7046 }
7047
7048 static void __init ata_parse_force_param(void)
7049 {
7050         int idx = 0, size = 1;
7051         int last_port = -1, last_device = -1;
7052         char *p, *cur, *next;
7053
7054         /* calculate maximum number of params and allocate force_tbl */
7055         for (p = ata_force_param_buf; *p; p++)
7056                 if (*p == ',')
7057                         size++;
7058
7059         ata_force_tbl = kzalloc(sizeof(ata_force_tbl[0]) * size, GFP_KERNEL);
7060         if (!ata_force_tbl) {
7061                 printk(KERN_WARNING "ata: failed to extend force table, "
7062                        "libata.force ignored\n");
7063                 return;
7064         }
7065
7066         /* parse and populate the table */
7067         for (cur = ata_force_param_buf; *cur != '\0'; cur = next) {
7068                 const char *reason = "";
7069                 struct ata_force_ent te = { .port = -1, .device = -1 };
7070
7071                 next = cur;
7072                 if (ata_parse_force_one(&next, &te, &reason)) {
7073                         printk(KERN_WARNING "ata: failed to parse force "
7074                                "parameter \"%s\" (%s)\n",
7075                                cur, reason);
7076                         continue;
7077                 }
7078
7079                 if (te.port == -1) {
7080                         te.port = last_port;
7081                         te.device = last_device;
7082                 }
7083
7084                 ata_force_tbl[idx++] = te;
7085
7086                 last_port = te.port;
7087                 last_device = te.device;
7088         }
7089
7090         ata_force_tbl_size = idx;
7091 }
7092
7093 static int __init ata_init(void)
7094 {
7095         int rc;
7096
7097         ata_parse_force_param();
7098
7099         rc = ata_sff_init();
7100         if (rc) {
7101                 kfree(ata_force_tbl);
7102                 return rc;
7103         }
7104
7105         libata_transport_init();
7106         ata_scsi_transport_template = ata_attach_transport();
7107         if (!ata_scsi_transport_template) {
7108                 ata_sff_exit();
7109                 rc = -ENOMEM;
7110                 goto err_out;
7111         }
7112
7113         printk(KERN_DEBUG "libata version " DRV_VERSION " loaded.\n");
7114         return 0;
7115
7116 err_out:
7117         return rc;
7118 }
7119
7120 static void __exit ata_exit(void)
7121 {
7122         ata_release_transport(ata_scsi_transport_template);
7123         libata_transport_exit();
7124         ata_sff_exit();
7125         kfree(ata_force_tbl);
7126 }
7127
7128 subsys_initcall(ata_init);
7129 module_exit(ata_exit);
7130
7131 static DEFINE_RATELIMIT_STATE(ratelimit, HZ / 5, 1);
7132
7133 int ata_ratelimit(void)
7134 {
7135         return __ratelimit(&ratelimit);
7136 }
7137
7138 /**
7139  *      ata_msleep - ATA EH owner aware msleep
7140  *      @ap: ATA port to attribute the sleep to
7141  *      @msecs: duration to sleep in milliseconds
7142  *
7143  *      Sleeps @msecs.  If the current task is owner of @ap's EH, the
7144  *      ownership is released before going to sleep and reacquired
7145  *      after the sleep is complete.  IOW, other ports sharing the
7146  *      @ap->host will be allowed to own the EH while this task is
7147  *      sleeping.
7148  *
7149  *      LOCKING:
7150  *      Might sleep.
7151  */
7152 void ata_msleep(struct ata_port *ap, unsigned int msecs)
7153 {
7154         bool owns_eh = ap && ap->host->eh_owner == current;
7155
7156         if (owns_eh)
7157                 ata_eh_release(ap);
7158
7159         if (msecs < 20) {
7160                 unsigned long usecs = msecs * USEC_PER_MSEC;
7161                 usleep_range(usecs, usecs + 50);
7162         } else {
7163                 msleep(msecs);
7164         }
7165
7166         if (owns_eh)
7167                 ata_eh_acquire(ap);
7168 }
7169
7170 /**
7171  *      ata_wait_register - wait until register value changes
7172  *      @ap: ATA port to wait register for, can be NULL
7173  *      @reg: IO-mapped register
7174  *      @mask: Mask to apply to read register value
7175  *      @val: Wait condition
7176  *      @interval: polling interval in milliseconds
7177  *      @timeout: timeout in milliseconds
7178  *
7179  *      Waiting for some bits of register to change is a common
7180  *      operation for ATA controllers.  This function reads 32bit LE
7181  *      IO-mapped register @reg and tests for the following condition.
7182  *
7183  *      (*@reg & mask) != val
7184  *
7185  *      If the condition is met, it returns; otherwise, the process is
7186  *      repeated after @interval_msec until timeout.
7187  *
7188  *      LOCKING:
7189  *      Kernel thread context (may sleep)
7190  *
7191  *      RETURNS:
7192  *      The final register value.
7193  */
7194 u32 ata_wait_register(struct ata_port *ap, void __iomem *reg, u32 mask, u32 val,
7195                       unsigned long interval, unsigned long timeout)
7196 {
7197         unsigned long deadline;
7198         u32 tmp;
7199
7200         tmp = ioread32(reg);
7201
7202         /* Calculate timeout _after_ the first read to make sure
7203          * preceding writes reach the controller before starting to
7204          * eat away the timeout.
7205          */
7206         deadline = ata_deadline(jiffies, timeout);
7207
7208         while ((tmp & mask) == val && time_before(jiffies, deadline)) {
7209                 ata_msleep(ap, interval);
7210                 tmp = ioread32(reg);
7211         }
7212
7213         return tmp;
7214 }
7215
7216 /**
7217  *      sata_lpm_ignore_phy_events - test if PHY event should be ignored
7218  *      @link: Link receiving the event
7219  *
7220  *      Test whether the received PHY event has to be ignored or not.
7221  *
7222  *      LOCKING:
7223  *      None:
7224  *
7225  *      RETURNS:
7226  *      True if the event has to be ignored.
7227  */
7228 bool sata_lpm_ignore_phy_events(struct ata_link *link)
7229 {
7230         unsigned long lpm_timeout = link->last_lpm_change +
7231                                     msecs_to_jiffies(ATA_TMOUT_SPURIOUS_PHY);
7232
7233         /* if LPM is enabled, PHYRDY doesn't mean anything */
7234         if (link->lpm_policy > ATA_LPM_MAX_POWER)
7235                 return true;
7236
7237         /* ignore the first PHY event after the LPM policy changed
7238          * as it is might be spurious
7239          */
7240         if ((link->flags & ATA_LFLAG_CHANGED) &&
7241             time_before(jiffies, lpm_timeout))
7242                 return true;
7243
7244         return false;
7245 }
7246 EXPORT_SYMBOL_GPL(sata_lpm_ignore_phy_events);
7247
7248 /*
7249  * Dummy port_ops
7250  */
7251 static unsigned int ata_dummy_qc_issue(struct ata_queued_cmd *qc)
7252 {
7253         return AC_ERR_SYSTEM;
7254 }
7255
7256 static void ata_dummy_error_handler(struct ata_port *ap)
7257 {
7258         /* truly dummy */
7259 }
7260
7261 struct ata_port_operations ata_dummy_port_ops = {
7262         .qc_prep                = ata_noop_qc_prep,
7263         .qc_issue               = ata_dummy_qc_issue,
7264         .error_handler          = ata_dummy_error_handler,
7265         .sched_eh               = ata_std_sched_eh,
7266         .end_eh                 = ata_std_end_eh,
7267 };
7268
7269 const struct ata_port_info ata_dummy_port_info = {
7270         .port_ops               = &ata_dummy_port_ops,
7271 };
7272
7273 /*
7274  * Utility print functions
7275  */
7276 void ata_port_printk(const struct ata_port *ap, const char *level,
7277                      const char *fmt, ...)
7278 {
7279         struct va_format vaf;
7280         va_list args;
7281
7282         va_start(args, fmt);
7283
7284         vaf.fmt = fmt;
7285         vaf.va = &args;
7286
7287         printk("%sata%u: %pV", level, ap->print_id, &vaf);
7288
7289         va_end(args);
7290 }
7291 EXPORT_SYMBOL(ata_port_printk);
7292
7293 void ata_link_printk(const struct ata_link *link, const char *level,
7294                      const char *fmt, ...)
7295 {
7296         struct va_format vaf;
7297         va_list args;
7298
7299         va_start(args, fmt);
7300
7301         vaf.fmt = fmt;
7302         vaf.va = &args;
7303
7304         if (sata_pmp_attached(link->ap) || link->ap->slave_link)
7305                 printk("%sata%u.%02u: %pV",
7306                        level, link->ap->print_id, link->pmp, &vaf);
7307         else
7308                 printk("%sata%u: %pV",
7309                        level, link->ap->print_id, &vaf);
7310
7311         va_end(args);
7312 }
7313 EXPORT_SYMBOL(ata_link_printk);
7314
7315 void ata_dev_printk(const struct ata_device *dev, const char *level,
7316                     const char *fmt, ...)
7317 {
7318         struct va_format vaf;
7319         va_list args;
7320
7321         va_start(args, fmt);
7322
7323         vaf.fmt = fmt;
7324         vaf.va = &args;
7325
7326         printk("%sata%u.%02u: %pV",
7327                level, dev->link->ap->print_id, dev->link->pmp + dev->devno,
7328                &vaf);
7329
7330         va_end(args);
7331 }
7332 EXPORT_SYMBOL(ata_dev_printk);
7333
7334 void ata_print_version(const struct device *dev, const char *version)
7335 {
7336         dev_printk(KERN_DEBUG, dev, "version %s\n", version);
7337 }
7338 EXPORT_SYMBOL(ata_print_version);
7339
7340 /*
7341  * libata is essentially a library of internal helper functions for
7342  * low-level ATA host controller drivers.  As such, the API/ABI is
7343  * likely to change as new drivers are added and updated.
7344  * Do not depend on ABI/API stability.
7345  */
7346 EXPORT_SYMBOL_GPL(sata_deb_timing_normal);
7347 EXPORT_SYMBOL_GPL(sata_deb_timing_hotplug);
7348 EXPORT_SYMBOL_GPL(sata_deb_timing_long);
7349 EXPORT_SYMBOL_GPL(ata_base_port_ops);
7350 EXPORT_SYMBOL_GPL(sata_port_ops);
7351 EXPORT_SYMBOL_GPL(ata_dummy_port_ops);
7352 EXPORT_SYMBOL_GPL(ata_dummy_port_info);
7353 EXPORT_SYMBOL_GPL(ata_link_next);
7354 EXPORT_SYMBOL_GPL(ata_dev_next);
7355 EXPORT_SYMBOL_GPL(ata_std_bios_param);
7356 EXPORT_SYMBOL_GPL(ata_scsi_unlock_native_capacity);
7357 EXPORT_SYMBOL_GPL(ata_host_init);
7358 EXPORT_SYMBOL_GPL(ata_host_alloc);
7359 EXPORT_SYMBOL_GPL(ata_host_alloc_pinfo);
7360 EXPORT_SYMBOL_GPL(ata_slave_link_init);
7361 EXPORT_SYMBOL_GPL(ata_host_start);
7362 EXPORT_SYMBOL_GPL(ata_host_register);
7363 EXPORT_SYMBOL_GPL(ata_host_activate);
7364 EXPORT_SYMBOL_GPL(ata_host_detach);
7365 EXPORT_SYMBOL_GPL(ata_sg_init);
7366 EXPORT_SYMBOL_GPL(ata_qc_complete);
7367 EXPORT_SYMBOL_GPL(ata_qc_complete_multiple);
7368 EXPORT_SYMBOL_GPL(atapi_cmd_type);
7369 EXPORT_SYMBOL_GPL(ata_tf_to_fis);
7370 EXPORT_SYMBOL_GPL(ata_tf_from_fis);
7371 EXPORT_SYMBOL_GPL(ata_pack_xfermask);
7372 EXPORT_SYMBOL_GPL(ata_unpack_xfermask);
7373 EXPORT_SYMBOL_GPL(ata_xfer_mask2mode);
7374 EXPORT_SYMBOL_GPL(ata_xfer_mode2mask);
7375 EXPORT_SYMBOL_GPL(ata_xfer_mode2shift);
7376 EXPORT_SYMBOL_GPL(ata_mode_string);
7377 EXPORT_SYMBOL_GPL(ata_id_xfermask);
7378 EXPORT_SYMBOL_GPL(ata_do_set_mode);
7379 EXPORT_SYMBOL_GPL(ata_std_qc_defer);
7380 EXPORT_SYMBOL_GPL(ata_noop_qc_prep);
7381 EXPORT_SYMBOL_GPL(ata_dev_disable);
7382 EXPORT_SYMBOL_GPL(sata_set_spd);
7383 EXPORT_SYMBOL_GPL(ata_wait_after_reset);
7384 EXPORT_SYMBOL_GPL(sata_link_debounce);
7385 EXPORT_SYMBOL_GPL(sata_link_resume);
7386 EXPORT_SYMBOL_GPL(sata_link_scr_lpm);
7387 EXPORT_SYMBOL_GPL(ata_std_prereset);
7388 EXPORT_SYMBOL_GPL(sata_link_hardreset);
7389 EXPORT_SYMBOL_GPL(sata_std_hardreset);
7390 EXPORT_SYMBOL_GPL(ata_std_postreset);
7391 EXPORT_SYMBOL_GPL(ata_dev_classify);
7392 EXPORT_SYMBOL_GPL(ata_dev_pair);
7393 EXPORT_SYMBOL_GPL(ata_ratelimit);
7394 EXPORT_SYMBOL_GPL(ata_msleep);
7395 EXPORT_SYMBOL_GPL(ata_wait_register);
7396 EXPORT_SYMBOL_GPL(ata_scsi_queuecmd);
7397 EXPORT_SYMBOL_GPL(ata_scsi_slave_config);
7398 EXPORT_SYMBOL_GPL(ata_scsi_slave_destroy);
7399 EXPORT_SYMBOL_GPL(ata_scsi_change_queue_depth);
7400 EXPORT_SYMBOL_GPL(__ata_change_queue_depth);
7401 EXPORT_SYMBOL_GPL(sata_scr_valid);
7402 EXPORT_SYMBOL_GPL(sata_scr_read);
7403 EXPORT_SYMBOL_GPL(sata_scr_write);
7404 EXPORT_SYMBOL_GPL(sata_scr_write_flush);
7405 EXPORT_SYMBOL_GPL(ata_link_online);
7406 EXPORT_SYMBOL_GPL(ata_link_offline);
7407 #ifdef CONFIG_PM
7408 EXPORT_SYMBOL_GPL(ata_host_suspend);
7409 EXPORT_SYMBOL_GPL(ata_host_resume);
7410 #endif /* CONFIG_PM */
7411 EXPORT_SYMBOL_GPL(ata_id_string);
7412 EXPORT_SYMBOL_GPL(ata_id_c_string);
7413 EXPORT_SYMBOL_GPL(ata_do_dev_read_id);
7414 EXPORT_SYMBOL_GPL(ata_scsi_simulate);
7415
7416 EXPORT_SYMBOL_GPL(ata_pio_need_iordy);
7417 EXPORT_SYMBOL_GPL(ata_timing_find_mode);
7418 EXPORT_SYMBOL_GPL(ata_timing_compute);
7419 EXPORT_SYMBOL_GPL(ata_timing_merge);
7420 EXPORT_SYMBOL_GPL(ata_timing_cycle2mode);
7421
7422 #ifdef CONFIG_PCI
7423 EXPORT_SYMBOL_GPL(pci_test_config_bits);
7424 EXPORT_SYMBOL_GPL(ata_pci_shutdown_one);
7425 EXPORT_SYMBOL_GPL(ata_pci_remove_one);
7426 #ifdef CONFIG_PM
7427 EXPORT_SYMBOL_GPL(ata_pci_device_do_suspend);
7428 EXPORT_SYMBOL_GPL(ata_pci_device_do_resume);
7429 EXPORT_SYMBOL_GPL(ata_pci_device_suspend);
7430 EXPORT_SYMBOL_GPL(ata_pci_device_resume);
7431 #endif /* CONFIG_PM */
7432 #endif /* CONFIG_PCI */
7433
7434 EXPORT_SYMBOL_GPL(ata_platform_remove_one);
7435
7436 EXPORT_SYMBOL_GPL(__ata_ehi_push_desc);
7437 EXPORT_SYMBOL_GPL(ata_ehi_push_desc);
7438 EXPORT_SYMBOL_GPL(ata_ehi_clear_desc);
7439 EXPORT_SYMBOL_GPL(ata_port_desc);
7440 #ifdef CONFIG_PCI
7441 EXPORT_SYMBOL_GPL(ata_port_pbar_desc);
7442 #endif /* CONFIG_PCI */
7443 EXPORT_SYMBOL_GPL(ata_port_schedule_eh);
7444 EXPORT_SYMBOL_GPL(ata_link_abort);
7445 EXPORT_SYMBOL_GPL(ata_port_abort);
7446 EXPORT_SYMBOL_GPL(ata_port_freeze);
7447 EXPORT_SYMBOL_GPL(sata_async_notification);
7448 EXPORT_SYMBOL_GPL(ata_eh_freeze_port);
7449 EXPORT_SYMBOL_GPL(ata_eh_thaw_port);
7450 EXPORT_SYMBOL_GPL(ata_eh_qc_complete);
7451 EXPORT_SYMBOL_GPL(ata_eh_qc_retry);
7452 EXPORT_SYMBOL_GPL(ata_eh_analyze_ncq_error);
7453 EXPORT_SYMBOL_GPL(ata_do_eh);
7454 EXPORT_SYMBOL_GPL(ata_std_error_handler);
7455
7456 EXPORT_SYMBOL_GPL(ata_cable_40wire);
7457 EXPORT_SYMBOL_GPL(ata_cable_80wire);
7458 EXPORT_SYMBOL_GPL(ata_cable_unknown);
7459 EXPORT_SYMBOL_GPL(ata_cable_ignore);
7460 EXPORT_SYMBOL_GPL(ata_cable_sata);