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