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