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