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