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