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