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