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