Merge git://git.kernel.org/pub/scm/linux/kernel/git/pkl/squashfs-linus
[sfrench/cifs-2.6.git] / drivers / ata / libata-core.c
1 /*
2  *  libata-core.c - helper library for ATA
3  *
4  *  Maintained by:  Jeff Garzik <jgarzik@pobox.com>
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 <scsi/scsi.h>
61 #include <scsi/scsi_cmnd.h>
62 #include <scsi/scsi_host.h>
63 #include <linux/libata.h>
64 #include <asm/byteorder.h>
65 #include <linux/cdrom.h>
66
67 #include "libata.h"
68
69
70 /* debounce timing parameters in msecs { interval, duration, timeout } */
71 const unsigned long sata_deb_timing_normal[]            = {   5,  100, 2000 };
72 const unsigned long sata_deb_timing_hotplug[]           = {  25,  500, 2000 };
73 const unsigned long sata_deb_timing_long[]              = { 100, 2000, 5000 };
74
75 const struct ata_port_operations ata_base_port_ops = {
76         .prereset               = ata_std_prereset,
77         .postreset              = ata_std_postreset,
78         .error_handler          = ata_std_error_handler,
79 };
80
81 const struct ata_port_operations sata_port_ops = {
82         .inherits               = &ata_base_port_ops,
83
84         .qc_defer               = ata_std_qc_defer,
85         .hardreset              = sata_std_hardreset,
86 };
87
88 static unsigned int ata_dev_init_params(struct ata_device *dev,
89                                         u16 heads, u16 sectors);
90 static unsigned int ata_dev_set_xfermode(struct ata_device *dev);
91 static unsigned int ata_dev_set_feature(struct ata_device *dev,
92                                         u8 enable, u8 feature);
93 static void ata_dev_xfermask(struct ata_device *dev);
94 static unsigned long ata_dev_blacklisted(const struct ata_device *dev);
95
96 unsigned int ata_print_id = 1;
97 static struct workqueue_struct *ata_wq;
98
99 struct workqueue_struct *ata_aux_wq;
100
101 struct ata_force_param {
102         const char      *name;
103         unsigned int    cbl;
104         int             spd_limit;
105         unsigned long   xfer_mask;
106         unsigned int    horkage_on;
107         unsigned int    horkage_off;
108         unsigned int    lflags;
109 };
110
111 struct ata_force_ent {
112         int                     port;
113         int                     device;
114         struct ata_force_param  param;
115 };
116
117 static struct ata_force_ent *ata_force_tbl;
118 static int ata_force_tbl_size;
119
120 static char ata_force_param_buf[PAGE_SIZE] __initdata;
121 /* param_buf is thrown away after initialization, disallow read */
122 module_param_string(force, ata_force_param_buf, sizeof(ata_force_param_buf), 0);
123 MODULE_PARM_DESC(force, "Force ATA configurations including cable type, link speed and transfer mode (see Documentation/kernel-parameters.txt for details)");
124
125 static int atapi_enabled = 1;
126 module_param(atapi_enabled, int, 0444);
127 MODULE_PARM_DESC(atapi_enabled, "Enable discovery of ATAPI devices (0=off, 1=on)");
128
129 static int atapi_dmadir = 0;
130 module_param(atapi_dmadir, int, 0444);
131 MODULE_PARM_DESC(atapi_dmadir, "Enable ATAPI DMADIR bridge support (0=off, 1=on)");
132
133 int atapi_passthru16 = 1;
134 module_param(atapi_passthru16, int, 0444);
135 MODULE_PARM_DESC(atapi_passthru16, "Enable ATA_16 passthru for ATAPI devices; on by default (0=off, 1=on)");
136
137 int libata_fua = 0;
138 module_param_named(fua, libata_fua, int, 0444);
139 MODULE_PARM_DESC(fua, "FUA support (0=off, 1=on)");
140
141 static int ata_ignore_hpa;
142 module_param_named(ignore_hpa, ata_ignore_hpa, int, 0644);
143 MODULE_PARM_DESC(ignore_hpa, "Ignore HPA limit (0=keep BIOS limits, 1=ignore limits, using full disk)");
144
145 static int libata_dma_mask = ATA_DMA_MASK_ATA|ATA_DMA_MASK_ATAPI|ATA_DMA_MASK_CFA;
146 module_param_named(dma, libata_dma_mask, int, 0444);
147 MODULE_PARM_DESC(dma, "DMA enable/disable (0x1==ATA, 0x2==ATAPI, 0x4==CF)");
148
149 static int ata_probe_timeout;
150 module_param(ata_probe_timeout, int, 0444);
151 MODULE_PARM_DESC(ata_probe_timeout, "Set ATA probing timeout (seconds)");
152
153 int libata_noacpi = 0;
154 module_param_named(noacpi, libata_noacpi, int, 0444);
155 MODULE_PARM_DESC(noacpi, "Disables the use of ACPI in probe/suspend/resume when set");
156
157 int libata_allow_tpm = 0;
158 module_param_named(allow_tpm, libata_allow_tpm, int, 0444);
159 MODULE_PARM_DESC(allow_tpm, "Permit the use of TPM commands");
160
161 MODULE_AUTHOR("Jeff Garzik");
162 MODULE_DESCRIPTION("Library module for ATA devices");
163 MODULE_LICENSE("GPL");
164 MODULE_VERSION(DRV_VERSION);
165
166
167 static bool ata_sstatus_online(u32 sstatus)
168 {
169         return (sstatus & 0xf) == 0x3;
170 }
171
172 /**
173  *      ata_link_next - link iteration helper
174  *      @link: the previous link, NULL to start
175  *      @ap: ATA port containing links to iterate
176  *      @mode: iteration mode, one of ATA_LITER_*
177  *
178  *      LOCKING:
179  *      Host lock or EH context.
180  *
181  *      RETURNS:
182  *      Pointer to the next link.
183  */
184 struct ata_link *ata_link_next(struct ata_link *link, struct ata_port *ap,
185                                enum ata_link_iter_mode mode)
186 {
187         BUG_ON(mode != ATA_LITER_EDGE &&
188                mode != ATA_LITER_PMP_FIRST && mode != ATA_LITER_HOST_FIRST);
189
190         /* NULL link indicates start of iteration */
191         if (!link)
192                 switch (mode) {
193                 case ATA_LITER_EDGE:
194                 case ATA_LITER_PMP_FIRST:
195                         if (sata_pmp_attached(ap))
196                                 return ap->pmp_link;
197                         /* fall through */
198                 case ATA_LITER_HOST_FIRST:
199                         return &ap->link;
200                 }
201
202         /* we just iterated over the host link, what's next? */
203         if (link == &ap->link)
204                 switch (mode) {
205                 case ATA_LITER_HOST_FIRST:
206                         if (sata_pmp_attached(ap))
207                                 return ap->pmp_link;
208                         /* fall through */
209                 case ATA_LITER_PMP_FIRST:
210                         if (unlikely(ap->slave_link))
211                                 return ap->slave_link;
212                         /* fall through */
213                 case ATA_LITER_EDGE:
214                         return NULL;
215                 }
216
217         /* slave_link excludes PMP */
218         if (unlikely(link == ap->slave_link))
219                 return NULL;
220
221         /* we were over a PMP link */
222         if (++link < ap->pmp_link + ap->nr_pmp_links)
223                 return link;
224
225         if (mode == ATA_LITER_PMP_FIRST)
226                 return &ap->link;
227
228         return NULL;
229 }
230
231 /**
232  *      ata_dev_next - device iteration helper
233  *      @dev: the previous device, NULL to start
234  *      @link: ATA link containing devices to iterate
235  *      @mode: iteration mode, one of ATA_DITER_*
236  *
237  *      LOCKING:
238  *      Host lock or EH context.
239  *
240  *      RETURNS:
241  *      Pointer to the next device.
242  */
243 struct ata_device *ata_dev_next(struct ata_device *dev, struct ata_link *link,
244                                 enum ata_dev_iter_mode mode)
245 {
246         BUG_ON(mode != ATA_DITER_ENABLED && mode != ATA_DITER_ENABLED_REVERSE &&
247                mode != ATA_DITER_ALL && mode != ATA_DITER_ALL_REVERSE);
248
249         /* NULL dev indicates start of iteration */
250         if (!dev)
251                 switch (mode) {
252                 case ATA_DITER_ENABLED:
253                 case ATA_DITER_ALL:
254                         dev = link->device;
255                         goto check;
256                 case ATA_DITER_ENABLED_REVERSE:
257                 case ATA_DITER_ALL_REVERSE:
258                         dev = link->device + ata_link_max_devices(link) - 1;
259                         goto check;
260                 }
261
262  next:
263         /* move to the next one */
264         switch (mode) {
265         case ATA_DITER_ENABLED:
266         case ATA_DITER_ALL:
267                 if (++dev < link->device + ata_link_max_devices(link))
268                         goto check;
269                 return NULL;
270         case ATA_DITER_ENABLED_REVERSE:
271         case ATA_DITER_ALL_REVERSE:
272                 if (--dev >= link->device)
273                         goto check;
274                 return NULL;
275         }
276
277  check:
278         if ((mode == ATA_DITER_ENABLED || mode == ATA_DITER_ENABLED_REVERSE) &&
279             !ata_dev_enabled(dev))
280                 goto next;
281         return dev;
282 }
283
284 /**
285  *      ata_dev_phys_link - find physical link for a device
286  *      @dev: ATA device to look up physical link for
287  *
288  *      Look up physical link which @dev is attached to.  Note that
289  *      this is different from @dev->link only when @dev is on slave
290  *      link.  For all other cases, it's the same as @dev->link.
291  *
292  *      LOCKING:
293  *      Don't care.
294  *
295  *      RETURNS:
296  *      Pointer to the found physical link.
297  */
298 struct ata_link *ata_dev_phys_link(struct ata_device *dev)
299 {
300         struct ata_port *ap = dev->link->ap;
301
302         if (!ap->slave_link)
303                 return dev->link;
304         if (!dev->devno)
305                 return &ap->link;
306         return ap->slave_link;
307 }
308
309 /**
310  *      ata_force_cbl - force cable type according to libata.force
311  *      @ap: ATA port of interest
312  *
313  *      Force cable type according to libata.force and whine about it.
314  *      The last entry which has matching port number is used, so it
315  *      can be specified as part of device force parameters.  For
316  *      example, both "a:40c,1.00:udma4" and "1.00:40c,udma4" have the
317  *      same effect.
318  *
319  *      LOCKING:
320  *      EH context.
321  */
322 void ata_force_cbl(struct ata_port *ap)
323 {
324         int i;
325
326         for (i = ata_force_tbl_size - 1; i >= 0; i--) {
327                 const struct ata_force_ent *fe = &ata_force_tbl[i];
328
329                 if (fe->port != -1 && fe->port != ap->print_id)
330                         continue;
331
332                 if (fe->param.cbl == ATA_CBL_NONE)
333                         continue;
334
335                 ap->cbl = fe->param.cbl;
336                 ata_port_printk(ap, KERN_NOTICE,
337                                 "FORCE: cable set to %s\n", fe->param.name);
338                 return;
339         }
340 }
341
342 /**
343  *      ata_force_link_limits - force link limits according to libata.force
344  *      @link: ATA link of interest
345  *
346  *      Force link flags and SATA spd limit according to libata.force
347  *      and whine about it.  When only the port part is specified
348  *      (e.g. 1:), the limit applies to all links connected to both
349  *      the host link and all fan-out ports connected via PMP.  If the
350  *      device part is specified as 0 (e.g. 1.00:), it specifies the
351  *      first fan-out link not the host link.  Device number 15 always
352  *      points to the host link whether PMP is attached or not.  If the
353  *      controller has slave link, device number 16 points to it.
354  *
355  *      LOCKING:
356  *      EH context.
357  */
358 static void ata_force_link_limits(struct ata_link *link)
359 {
360         bool did_spd = false;
361         int linkno = link->pmp;
362         int i;
363
364         if (ata_is_host_link(link))
365                 linkno += 15;
366
367         for (i = ata_force_tbl_size - 1; i >= 0; i--) {
368                 const struct ata_force_ent *fe = &ata_force_tbl[i];
369
370                 if (fe->port != -1 && fe->port != link->ap->print_id)
371                         continue;
372
373                 if (fe->device != -1 && fe->device != linkno)
374                         continue;
375
376                 /* only honor the first spd limit */
377                 if (!did_spd && fe->param.spd_limit) {
378                         link->hw_sata_spd_limit = (1 << fe->param.spd_limit) - 1;
379                         ata_link_printk(link, KERN_NOTICE,
380                                         "FORCE: PHY spd limit set to %s\n",
381                                         fe->param.name);
382                         did_spd = true;
383                 }
384
385                 /* let lflags stack */
386                 if (fe->param.lflags) {
387                         link->flags |= fe->param.lflags;
388                         ata_link_printk(link, KERN_NOTICE,
389                                         "FORCE: link flag 0x%x forced -> 0x%x\n",
390                                         fe->param.lflags, link->flags);
391                 }
392         }
393 }
394
395 /**
396  *      ata_force_xfermask - force xfermask according to libata.force
397  *      @dev: ATA device of interest
398  *
399  *      Force xfer_mask according to libata.force and whine about it.
400  *      For consistency with link selection, device number 15 selects
401  *      the first device connected to the host link.
402  *
403  *      LOCKING:
404  *      EH context.
405  */
406 static void ata_force_xfermask(struct ata_device *dev)
407 {
408         int devno = dev->link->pmp + dev->devno;
409         int alt_devno = devno;
410         int i;
411
412         /* allow n.15/16 for devices attached to host port */
413         if (ata_is_host_link(dev->link))
414                 alt_devno += 15;
415
416         for (i = ata_force_tbl_size - 1; i >= 0; i--) {
417                 const struct ata_force_ent *fe = &ata_force_tbl[i];
418                 unsigned long pio_mask, mwdma_mask, udma_mask;
419
420                 if (fe->port != -1 && fe->port != dev->link->ap->print_id)
421                         continue;
422
423                 if (fe->device != -1 && fe->device != devno &&
424                     fe->device != alt_devno)
425                         continue;
426
427                 if (!fe->param.xfer_mask)
428                         continue;
429
430                 ata_unpack_xfermask(fe->param.xfer_mask,
431                                     &pio_mask, &mwdma_mask, &udma_mask);
432                 if (udma_mask)
433                         dev->udma_mask = udma_mask;
434                 else if (mwdma_mask) {
435                         dev->udma_mask = 0;
436                         dev->mwdma_mask = mwdma_mask;
437                 } else {
438                         dev->udma_mask = 0;
439                         dev->mwdma_mask = 0;
440                         dev->pio_mask = pio_mask;
441                 }
442
443                 ata_dev_printk(dev, KERN_NOTICE,
444                         "FORCE: xfer_mask set to %s\n", fe->param.name);
445                 return;
446         }
447 }
448
449 /**
450  *      ata_force_horkage - force horkage according to libata.force
451  *      @dev: ATA device of interest
452  *
453  *      Force horkage according to libata.force and whine about it.
454  *      For consistency with link selection, device number 15 selects
455  *      the first device connected to the host link.
456  *
457  *      LOCKING:
458  *      EH context.
459  */
460 static void ata_force_horkage(struct ata_device *dev)
461 {
462         int devno = dev->link->pmp + dev->devno;
463         int alt_devno = devno;
464         int i;
465
466         /* allow n.15/16 for devices attached to host port */
467         if (ata_is_host_link(dev->link))
468                 alt_devno += 15;
469
470         for (i = 0; i < ata_force_tbl_size; i++) {
471                 const struct ata_force_ent *fe = &ata_force_tbl[i];
472
473                 if (fe->port != -1 && fe->port != dev->link->ap->print_id)
474                         continue;
475
476                 if (fe->device != -1 && fe->device != devno &&
477                     fe->device != alt_devno)
478                         continue;
479
480                 if (!(~dev->horkage & fe->param.horkage_on) &&
481                     !(dev->horkage & fe->param.horkage_off))
482                         continue;
483
484                 dev->horkage |= fe->param.horkage_on;
485                 dev->horkage &= ~fe->param.horkage_off;
486
487                 ata_dev_printk(dev, KERN_NOTICE,
488                         "FORCE: horkage modified (%s)\n", fe->param.name);
489         }
490 }
491
492 /**
493  *      atapi_cmd_type - Determine ATAPI command type from SCSI opcode
494  *      @opcode: SCSI opcode
495  *
496  *      Determine ATAPI command type from @opcode.
497  *
498  *      LOCKING:
499  *      None.
500  *
501  *      RETURNS:
502  *      ATAPI_{READ|WRITE|READ_CD|PASS_THRU|MISC}
503  */
504 int atapi_cmd_type(u8 opcode)
505 {
506         switch (opcode) {
507         case GPCMD_READ_10:
508         case GPCMD_READ_12:
509                 return ATAPI_READ;
510
511         case GPCMD_WRITE_10:
512         case GPCMD_WRITE_12:
513         case GPCMD_WRITE_AND_VERIFY_10:
514                 return ATAPI_WRITE;
515
516         case GPCMD_READ_CD:
517         case GPCMD_READ_CD_MSF:
518                 return ATAPI_READ_CD;
519
520         case ATA_16:
521         case ATA_12:
522                 if (atapi_passthru16)
523                         return ATAPI_PASS_THRU;
524                 /* fall thru */
525         default:
526                 return ATAPI_MISC;
527         }
528 }
529
530 /**
531  *      ata_tf_to_fis - Convert ATA taskfile to SATA FIS structure
532  *      @tf: Taskfile to convert
533  *      @pmp: Port multiplier port
534  *      @is_cmd: This FIS is for command
535  *      @fis: Buffer into which data will output
536  *
537  *      Converts a standard ATA taskfile to a Serial ATA
538  *      FIS structure (Register - Host to Device).
539  *
540  *      LOCKING:
541  *      Inherited from caller.
542  */
543 void ata_tf_to_fis(const struct ata_taskfile *tf, u8 pmp, int is_cmd, u8 *fis)
544 {
545         fis[0] = 0x27;                  /* Register - Host to Device FIS */
546         fis[1] = pmp & 0xf;             /* Port multiplier number*/
547         if (is_cmd)
548                 fis[1] |= (1 << 7);     /* bit 7 indicates Command FIS */
549
550         fis[2] = tf->command;
551         fis[3] = tf->feature;
552
553         fis[4] = tf->lbal;
554         fis[5] = tf->lbam;
555         fis[6] = tf->lbah;
556         fis[7] = tf->device;
557
558         fis[8] = tf->hob_lbal;
559         fis[9] = tf->hob_lbam;
560         fis[10] = tf->hob_lbah;
561         fis[11] = tf->hob_feature;
562
563         fis[12] = tf->nsect;
564         fis[13] = tf->hob_nsect;
565         fis[14] = 0;
566         fis[15] = tf->ctl;
567
568         fis[16] = 0;
569         fis[17] = 0;
570         fis[18] = 0;
571         fis[19] = 0;
572 }
573
574 /**
575  *      ata_tf_from_fis - Convert SATA FIS to ATA taskfile
576  *      @fis: Buffer from which data will be input
577  *      @tf: Taskfile to output
578  *
579  *      Converts a serial ATA FIS structure to a standard ATA taskfile.
580  *
581  *      LOCKING:
582  *      Inherited from caller.
583  */
584
585 void ata_tf_from_fis(const u8 *fis, struct ata_taskfile *tf)
586 {
587         tf->command     = fis[2];       /* status */
588         tf->feature     = fis[3];       /* error */
589
590         tf->lbal        = fis[4];
591         tf->lbam        = fis[5];
592         tf->lbah        = fis[6];
593         tf->device      = fis[7];
594
595         tf->hob_lbal    = fis[8];
596         tf->hob_lbam    = fis[9];
597         tf->hob_lbah    = fis[10];
598
599         tf->nsect       = fis[12];
600         tf->hob_nsect   = fis[13];
601 }
602
603 static const u8 ata_rw_cmds[] = {
604         /* pio multi */
605         ATA_CMD_READ_MULTI,
606         ATA_CMD_WRITE_MULTI,
607         ATA_CMD_READ_MULTI_EXT,
608         ATA_CMD_WRITE_MULTI_EXT,
609         0,
610         0,
611         0,
612         ATA_CMD_WRITE_MULTI_FUA_EXT,
613         /* pio */
614         ATA_CMD_PIO_READ,
615         ATA_CMD_PIO_WRITE,
616         ATA_CMD_PIO_READ_EXT,
617         ATA_CMD_PIO_WRITE_EXT,
618         0,
619         0,
620         0,
621         0,
622         /* dma */
623         ATA_CMD_READ,
624         ATA_CMD_WRITE,
625         ATA_CMD_READ_EXT,
626         ATA_CMD_WRITE_EXT,
627         0,
628         0,
629         0,
630         ATA_CMD_WRITE_FUA_EXT
631 };
632
633 /**
634  *      ata_rwcmd_protocol - set taskfile r/w commands and protocol
635  *      @tf: command to examine and configure
636  *      @dev: device tf belongs to
637  *
638  *      Examine the device configuration and tf->flags to calculate
639  *      the proper read/write commands and protocol to use.
640  *
641  *      LOCKING:
642  *      caller.
643  */
644 static int ata_rwcmd_protocol(struct ata_taskfile *tf, struct ata_device *dev)
645 {
646         u8 cmd;
647
648         int index, fua, lba48, write;
649
650         fua = (tf->flags & ATA_TFLAG_FUA) ? 4 : 0;
651         lba48 = (tf->flags & ATA_TFLAG_LBA48) ? 2 : 0;
652         write = (tf->flags & ATA_TFLAG_WRITE) ? 1 : 0;
653
654         if (dev->flags & ATA_DFLAG_PIO) {
655                 tf->protocol = ATA_PROT_PIO;
656                 index = dev->multi_count ? 0 : 8;
657         } else if (lba48 && (dev->link->ap->flags & ATA_FLAG_PIO_LBA48)) {
658                 /* Unable to use DMA due to host limitation */
659                 tf->protocol = ATA_PROT_PIO;
660                 index = dev->multi_count ? 0 : 8;
661         } else {
662                 tf->protocol = ATA_PROT_DMA;
663                 index = 16;
664         }
665
666         cmd = ata_rw_cmds[index + fua + lba48 + write];
667         if (cmd) {
668                 tf->command = cmd;
669                 return 0;
670         }
671         return -1;
672 }
673
674 /**
675  *      ata_tf_read_block - Read block address from ATA taskfile
676  *      @tf: ATA taskfile of interest
677  *      @dev: ATA device @tf belongs to
678  *
679  *      LOCKING:
680  *      None.
681  *
682  *      Read block address from @tf.  This function can handle all
683  *      three address formats - LBA, LBA48 and CHS.  tf->protocol and
684  *      flags select the address format to use.
685  *
686  *      RETURNS:
687  *      Block address read from @tf.
688  */
689 u64 ata_tf_read_block(struct ata_taskfile *tf, struct ata_device *dev)
690 {
691         u64 block = 0;
692
693         if (tf->flags & ATA_TFLAG_LBA) {
694                 if (tf->flags & ATA_TFLAG_LBA48) {
695                         block |= (u64)tf->hob_lbah << 40;
696                         block |= (u64)tf->hob_lbam << 32;
697                         block |= (u64)tf->hob_lbal << 24;
698                 } else
699                         block |= (tf->device & 0xf) << 24;
700
701                 block |= tf->lbah << 16;
702                 block |= tf->lbam << 8;
703                 block |= tf->lbal;
704         } else {
705                 u32 cyl, head, sect;
706
707                 cyl = tf->lbam | (tf->lbah << 8);
708                 head = tf->device & 0xf;
709                 sect = tf->lbal;
710
711                 block = (cyl * dev->heads + head) * dev->sectors + sect;
712         }
713
714         return block;
715 }
716
717 /**
718  *      ata_build_rw_tf - Build ATA taskfile for given read/write request
719  *      @tf: Target ATA taskfile
720  *      @dev: ATA device @tf belongs to
721  *      @block: Block address
722  *      @n_block: Number of blocks
723  *      @tf_flags: RW/FUA etc...
724  *      @tag: tag
725  *
726  *      LOCKING:
727  *      None.
728  *
729  *      Build ATA taskfile @tf for read/write request described by
730  *      @block, @n_block, @tf_flags and @tag on @dev.
731  *
732  *      RETURNS:
733  *
734  *      0 on success, -ERANGE if the request is too large for @dev,
735  *      -EINVAL if the request is invalid.
736  */
737 int ata_build_rw_tf(struct ata_taskfile *tf, struct ata_device *dev,
738                     u64 block, u32 n_block, unsigned int tf_flags,
739                     unsigned int tag)
740 {
741         tf->flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
742         tf->flags |= tf_flags;
743
744         if (ata_ncq_enabled(dev) && likely(tag != ATA_TAG_INTERNAL)) {
745                 /* yay, NCQ */
746                 if (!lba_48_ok(block, n_block))
747                         return -ERANGE;
748
749                 tf->protocol = ATA_PROT_NCQ;
750                 tf->flags |= ATA_TFLAG_LBA | ATA_TFLAG_LBA48;
751
752                 if (tf->flags & ATA_TFLAG_WRITE)
753                         tf->command = ATA_CMD_FPDMA_WRITE;
754                 else
755                         tf->command = ATA_CMD_FPDMA_READ;
756
757                 tf->nsect = tag << 3;
758                 tf->hob_feature = (n_block >> 8) & 0xff;
759                 tf->feature = n_block & 0xff;
760
761                 tf->hob_lbah = (block >> 40) & 0xff;
762                 tf->hob_lbam = (block >> 32) & 0xff;
763                 tf->hob_lbal = (block >> 24) & 0xff;
764                 tf->lbah = (block >> 16) & 0xff;
765                 tf->lbam = (block >> 8) & 0xff;
766                 tf->lbal = block & 0xff;
767
768                 tf->device = 1 << 6;
769                 if (tf->flags & ATA_TFLAG_FUA)
770                         tf->device |= 1 << 7;
771         } else if (dev->flags & ATA_DFLAG_LBA) {
772                 tf->flags |= ATA_TFLAG_LBA;
773
774                 if (lba_28_ok(block, n_block)) {
775                         /* use LBA28 */
776                         tf->device |= (block >> 24) & 0xf;
777                 } else if (lba_48_ok(block, n_block)) {
778                         if (!(dev->flags & ATA_DFLAG_LBA48))
779                                 return -ERANGE;
780
781                         /* use LBA48 */
782                         tf->flags |= ATA_TFLAG_LBA48;
783
784                         tf->hob_nsect = (n_block >> 8) & 0xff;
785
786                         tf->hob_lbah = (block >> 40) & 0xff;
787                         tf->hob_lbam = (block >> 32) & 0xff;
788                         tf->hob_lbal = (block >> 24) & 0xff;
789                 } else
790                         /* request too large even for LBA48 */
791                         return -ERANGE;
792
793                 if (unlikely(ata_rwcmd_protocol(tf, dev) < 0))
794                         return -EINVAL;
795
796                 tf->nsect = n_block & 0xff;
797
798                 tf->lbah = (block >> 16) & 0xff;
799                 tf->lbam = (block >> 8) & 0xff;
800                 tf->lbal = block & 0xff;
801
802                 tf->device |= ATA_LBA;
803         } else {
804                 /* CHS */
805                 u32 sect, head, cyl, track;
806
807                 /* The request -may- be too large for CHS addressing. */
808                 if (!lba_28_ok(block, n_block))
809                         return -ERANGE;
810
811                 if (unlikely(ata_rwcmd_protocol(tf, dev) < 0))
812                         return -EINVAL;
813
814                 /* Convert LBA to CHS */
815                 track = (u32)block / dev->sectors;
816                 cyl   = track / dev->heads;
817                 head  = track % dev->heads;
818                 sect  = (u32)block % dev->sectors + 1;
819
820                 DPRINTK("block %u track %u cyl %u head %u sect %u\n",
821                         (u32)block, track, cyl, head, sect);
822
823                 /* Check whether the converted CHS can fit.
824                    Cylinder: 0-65535
825                    Head: 0-15
826                    Sector: 1-255*/
827                 if ((cyl >> 16) || (head >> 4) || (sect >> 8) || (!sect))
828                         return -ERANGE;
829
830                 tf->nsect = n_block & 0xff; /* Sector count 0 means 256 sectors */
831                 tf->lbal = sect;
832                 tf->lbam = cyl;
833                 tf->lbah = cyl >> 8;
834                 tf->device |= head;
835         }
836
837         return 0;
838 }
839
840 /**
841  *      ata_pack_xfermask - Pack pio, mwdma and udma masks into xfer_mask
842  *      @pio_mask: pio_mask
843  *      @mwdma_mask: mwdma_mask
844  *      @udma_mask: udma_mask
845  *
846  *      Pack @pio_mask, @mwdma_mask and @udma_mask into a single
847  *      unsigned int xfer_mask.
848  *
849  *      LOCKING:
850  *      None.
851  *
852  *      RETURNS:
853  *      Packed xfer_mask.
854  */
855 unsigned long ata_pack_xfermask(unsigned long pio_mask,
856                                 unsigned long mwdma_mask,
857                                 unsigned long udma_mask)
858 {
859         return ((pio_mask << ATA_SHIFT_PIO) & ATA_MASK_PIO) |
860                 ((mwdma_mask << ATA_SHIFT_MWDMA) & ATA_MASK_MWDMA) |
861                 ((udma_mask << ATA_SHIFT_UDMA) & ATA_MASK_UDMA);
862 }
863
864 /**
865  *      ata_unpack_xfermask - Unpack xfer_mask into pio, mwdma and udma masks
866  *      @xfer_mask: xfer_mask to unpack
867  *      @pio_mask: resulting pio_mask
868  *      @mwdma_mask: resulting mwdma_mask
869  *      @udma_mask: resulting udma_mask
870  *
871  *      Unpack @xfer_mask into @pio_mask, @mwdma_mask and @udma_mask.
872  *      Any NULL distination masks will be ignored.
873  */
874 void ata_unpack_xfermask(unsigned long xfer_mask, unsigned long *pio_mask,
875                          unsigned long *mwdma_mask, unsigned long *udma_mask)
876 {
877         if (pio_mask)
878                 *pio_mask = (xfer_mask & ATA_MASK_PIO) >> ATA_SHIFT_PIO;
879         if (mwdma_mask)
880                 *mwdma_mask = (xfer_mask & ATA_MASK_MWDMA) >> ATA_SHIFT_MWDMA;
881         if (udma_mask)
882                 *udma_mask = (xfer_mask & ATA_MASK_UDMA) >> ATA_SHIFT_UDMA;
883 }
884
885 static const struct ata_xfer_ent {
886         int shift, bits;
887         u8 base;
888 } ata_xfer_tbl[] = {
889         { ATA_SHIFT_PIO, ATA_NR_PIO_MODES, XFER_PIO_0 },
890         { ATA_SHIFT_MWDMA, ATA_NR_MWDMA_MODES, XFER_MW_DMA_0 },
891         { ATA_SHIFT_UDMA, ATA_NR_UDMA_MODES, XFER_UDMA_0 },
892         { -1, },
893 };
894
895 /**
896  *      ata_xfer_mask2mode - Find matching XFER_* for the given xfer_mask
897  *      @xfer_mask: xfer_mask of interest
898  *
899  *      Return matching XFER_* value for @xfer_mask.  Only the highest
900  *      bit of @xfer_mask is considered.
901  *
902  *      LOCKING:
903  *      None.
904  *
905  *      RETURNS:
906  *      Matching XFER_* value, 0xff if no match found.
907  */
908 u8 ata_xfer_mask2mode(unsigned long xfer_mask)
909 {
910         int highbit = fls(xfer_mask) - 1;
911         const struct ata_xfer_ent *ent;
912
913         for (ent = ata_xfer_tbl; ent->shift >= 0; ent++)
914                 if (highbit >= ent->shift && highbit < ent->shift + ent->bits)
915                         return ent->base + highbit - ent->shift;
916         return 0xff;
917 }
918
919 /**
920  *      ata_xfer_mode2mask - Find matching xfer_mask for XFER_*
921  *      @xfer_mode: XFER_* of interest
922  *
923  *      Return matching xfer_mask for @xfer_mode.
924  *
925  *      LOCKING:
926  *      None.
927  *
928  *      RETURNS:
929  *      Matching xfer_mask, 0 if no match found.
930  */
931 unsigned long ata_xfer_mode2mask(u8 xfer_mode)
932 {
933         const struct ata_xfer_ent *ent;
934
935         for (ent = ata_xfer_tbl; ent->shift >= 0; ent++)
936                 if (xfer_mode >= ent->base && xfer_mode < ent->base + ent->bits)
937                         return ((2 << (ent->shift + xfer_mode - ent->base)) - 1)
938                                 & ~((1 << ent->shift) - 1);
939         return 0;
940 }
941
942 /**
943  *      ata_xfer_mode2shift - Find matching xfer_shift for XFER_*
944  *      @xfer_mode: XFER_* of interest
945  *
946  *      Return matching xfer_shift for @xfer_mode.
947  *
948  *      LOCKING:
949  *      None.
950  *
951  *      RETURNS:
952  *      Matching xfer_shift, -1 if no match found.
953  */
954 int ata_xfer_mode2shift(unsigned long xfer_mode)
955 {
956         const struct ata_xfer_ent *ent;
957
958         for (ent = ata_xfer_tbl; ent->shift >= 0; ent++)
959                 if (xfer_mode >= ent->base && xfer_mode < ent->base + ent->bits)
960                         return ent->shift;
961         return -1;
962 }
963
964 /**
965  *      ata_mode_string - convert xfer_mask to string
966  *      @xfer_mask: mask of bits supported; only highest bit counts.
967  *
968  *      Determine string which represents the highest speed
969  *      (highest bit in @modemask).
970  *
971  *      LOCKING:
972  *      None.
973  *
974  *      RETURNS:
975  *      Constant C string representing highest speed listed in
976  *      @mode_mask, or the constant C string "<n/a>".
977  */
978 const char *ata_mode_string(unsigned long xfer_mask)
979 {
980         static const char * const xfer_mode_str[] = {
981                 "PIO0",
982                 "PIO1",
983                 "PIO2",
984                 "PIO3",
985                 "PIO4",
986                 "PIO5",
987                 "PIO6",
988                 "MWDMA0",
989                 "MWDMA1",
990                 "MWDMA2",
991                 "MWDMA3",
992                 "MWDMA4",
993                 "UDMA/16",
994                 "UDMA/25",
995                 "UDMA/33",
996                 "UDMA/44",
997                 "UDMA/66",
998                 "UDMA/100",
999                 "UDMA/133",
1000                 "UDMA7",
1001         };
1002         int highbit;
1003
1004         highbit = fls(xfer_mask) - 1;
1005         if (highbit >= 0 && highbit < ARRAY_SIZE(xfer_mode_str))
1006                 return xfer_mode_str[highbit];
1007         return "<n/a>";
1008 }
1009
1010 static const char *sata_spd_string(unsigned int spd)
1011 {
1012         static const char * const spd_str[] = {
1013                 "1.5 Gbps",
1014                 "3.0 Gbps",
1015                 "6.0 Gbps",
1016         };
1017
1018         if (spd == 0 || (spd - 1) >= ARRAY_SIZE(spd_str))
1019                 return "<unknown>";
1020         return spd_str[spd - 1];
1021 }
1022
1023 static int ata_dev_set_dipm(struct ata_device *dev, enum link_pm policy)
1024 {
1025         struct ata_link *link = dev->link;
1026         struct ata_port *ap = link->ap;
1027         u32 scontrol;
1028         unsigned int err_mask;
1029         int rc;
1030
1031         /*
1032          * disallow DIPM for drivers which haven't set
1033          * ATA_FLAG_IPM.  This is because when DIPM is enabled,
1034          * phy ready will be set in the interrupt status on
1035          * state changes, which will cause some drivers to
1036          * think there are errors - additionally drivers will
1037          * need to disable hot plug.
1038          */
1039         if (!(ap->flags & ATA_FLAG_IPM) || !ata_dev_enabled(dev)) {
1040                 ap->pm_policy = NOT_AVAILABLE;
1041                 return -EINVAL;
1042         }
1043
1044         /*
1045          * For DIPM, we will only enable it for the
1046          * min_power setting.
1047          *
1048          * Why?  Because Disks are too stupid to know that
1049          * If the host rejects a request to go to SLUMBER
1050          * they should retry at PARTIAL, and instead it
1051          * just would give up.  So, for medium_power to
1052          * work at all, we need to only allow HIPM.
1053          */
1054         rc = sata_scr_read(link, SCR_CONTROL, &scontrol);
1055         if (rc)
1056                 return rc;
1057
1058         switch (policy) {
1059         case MIN_POWER:
1060                 /* no restrictions on IPM transitions */
1061                 scontrol &= ~(0x3 << 8);
1062                 rc = sata_scr_write(link, SCR_CONTROL, scontrol);
1063                 if (rc)
1064                         return rc;
1065
1066                 /* enable DIPM */
1067                 if (dev->flags & ATA_DFLAG_DIPM)
1068                         err_mask = ata_dev_set_feature(dev,
1069                                         SETFEATURES_SATA_ENABLE, SATA_DIPM);
1070                 break;
1071         case MEDIUM_POWER:
1072                 /* allow IPM to PARTIAL */
1073                 scontrol &= ~(0x1 << 8);
1074                 scontrol |= (0x2 << 8);
1075                 rc = sata_scr_write(link, SCR_CONTROL, scontrol);
1076                 if (rc)
1077                         return rc;
1078
1079                 /*
1080                  * we don't have to disable DIPM since IPM flags
1081                  * disallow transitions to SLUMBER, which effectively
1082                  * disable DIPM if it does not support PARTIAL
1083                  */
1084                 break;
1085         case NOT_AVAILABLE:
1086         case MAX_PERFORMANCE:
1087                 /* disable all IPM transitions */
1088                 scontrol |= (0x3 << 8);
1089                 rc = sata_scr_write(link, SCR_CONTROL, scontrol);
1090                 if (rc)
1091                         return rc;
1092
1093                 /*
1094                  * we don't have to disable DIPM since IPM flags
1095                  * disallow all transitions which effectively
1096                  * disable DIPM anyway.
1097                  */
1098                 break;
1099         }
1100
1101         /* FIXME: handle SET FEATURES failure */
1102         (void) err_mask;
1103
1104         return 0;
1105 }
1106
1107 /**
1108  *      ata_dev_enable_pm - enable SATA interface power management
1109  *      @dev:  device to enable power management
1110  *      @policy: the link power management policy
1111  *
1112  *      Enable SATA Interface power management.  This will enable
1113  *      Device Interface Power Management (DIPM) for min_power
1114  *      policy, and then call driver specific callbacks for
1115  *      enabling Host Initiated Power management.
1116  *
1117  *      Locking: Caller.
1118  *      Returns: -EINVAL if IPM is not supported, 0 otherwise.
1119  */
1120 void ata_dev_enable_pm(struct ata_device *dev, enum link_pm policy)
1121 {
1122         int rc = 0;
1123         struct ata_port *ap = dev->link->ap;
1124
1125         /* set HIPM first, then DIPM */
1126         if (ap->ops->enable_pm)
1127                 rc = ap->ops->enable_pm(ap, policy);
1128         if (rc)
1129                 goto enable_pm_out;
1130         rc = ata_dev_set_dipm(dev, policy);
1131
1132 enable_pm_out:
1133         if (rc)
1134                 ap->pm_policy = MAX_PERFORMANCE;
1135         else
1136                 ap->pm_policy = policy;
1137         return /* rc */;        /* hopefully we can use 'rc' eventually */
1138 }
1139
1140 #ifdef CONFIG_PM
1141 /**
1142  *      ata_dev_disable_pm - disable SATA interface power management
1143  *      @dev: device to disable power management
1144  *
1145  *      Disable SATA Interface power management.  This will disable
1146  *      Device Interface Power Management (DIPM) without changing
1147  *      policy,  call driver specific callbacks for disabling Host
1148  *      Initiated Power management.
1149  *
1150  *      Locking: Caller.
1151  *      Returns: void
1152  */
1153 static void ata_dev_disable_pm(struct ata_device *dev)
1154 {
1155         struct ata_port *ap = dev->link->ap;
1156
1157         ata_dev_set_dipm(dev, MAX_PERFORMANCE);
1158         if (ap->ops->disable_pm)
1159                 ap->ops->disable_pm(ap);
1160 }
1161 #endif  /* CONFIG_PM */
1162
1163 void ata_lpm_schedule(struct ata_port *ap, enum link_pm policy)
1164 {
1165         ap->pm_policy = policy;
1166         ap->link.eh_info.action |= ATA_EH_LPM;
1167         ap->link.eh_info.flags |= ATA_EHI_NO_AUTOPSY;
1168         ata_port_schedule_eh(ap);
1169 }
1170
1171 #ifdef CONFIG_PM
1172 static void ata_lpm_enable(struct ata_host *host)
1173 {
1174         struct ata_link *link;
1175         struct ata_port *ap;
1176         struct ata_device *dev;
1177         int i;
1178
1179         for (i = 0; i < host->n_ports; i++) {
1180                 ap = host->ports[i];
1181                 ata_for_each_link(link, ap, EDGE) {
1182                         ata_for_each_dev(dev, link, ALL)
1183                                 ata_dev_disable_pm(dev);
1184                 }
1185         }
1186 }
1187
1188 static void ata_lpm_disable(struct ata_host *host)
1189 {
1190         int i;
1191
1192         for (i = 0; i < host->n_ports; i++) {
1193                 struct ata_port *ap = host->ports[i];
1194                 ata_lpm_schedule(ap, ap->pm_policy);
1195         }
1196 }
1197 #endif  /* CONFIG_PM */
1198
1199 /**
1200  *      ata_dev_classify - determine device type based on ATA-spec signature
1201  *      @tf: ATA taskfile register set for device to be identified
1202  *
1203  *      Determine from taskfile register contents whether a device is
1204  *      ATA or ATAPI, as per "Signature and persistence" section
1205  *      of ATA/PI spec (volume 1, sect 5.14).
1206  *
1207  *      LOCKING:
1208  *      None.
1209  *
1210  *      RETURNS:
1211  *      Device type, %ATA_DEV_ATA, %ATA_DEV_ATAPI, %ATA_DEV_PMP or
1212  *      %ATA_DEV_UNKNOWN the event of failure.
1213  */
1214 unsigned int ata_dev_classify(const struct ata_taskfile *tf)
1215 {
1216         /* Apple's open source Darwin code hints that some devices only
1217          * put a proper signature into the LBA mid/high registers,
1218          * So, we only check those.  It's sufficient for uniqueness.
1219          *
1220          * ATA/ATAPI-7 (d1532v1r1: Feb. 19, 2003) specified separate
1221          * signatures for ATA and ATAPI devices attached on SerialATA,
1222          * 0x3c/0xc3 and 0x69/0x96 respectively.  However, SerialATA
1223          * spec has never mentioned about using different signatures
1224          * for ATA/ATAPI devices.  Then, Serial ATA II: Port
1225          * Multiplier specification began to use 0x69/0x96 to identify
1226          * port multpliers and 0x3c/0xc3 to identify SEMB device.
1227          * ATA/ATAPI-7 dropped descriptions about 0x3c/0xc3 and
1228          * 0x69/0x96 shortly and described them as reserved for
1229          * SerialATA.
1230          *
1231          * We follow the current spec and consider that 0x69/0x96
1232          * identifies a port multiplier and 0x3c/0xc3 a SEMB device.
1233          */
1234         if ((tf->lbam == 0) && (tf->lbah == 0)) {
1235                 DPRINTK("found ATA device by sig\n");
1236                 return ATA_DEV_ATA;
1237         }
1238
1239         if ((tf->lbam == 0x14) && (tf->lbah == 0xeb)) {
1240                 DPRINTK("found ATAPI device by sig\n");
1241                 return ATA_DEV_ATAPI;
1242         }
1243
1244         if ((tf->lbam == 0x69) && (tf->lbah == 0x96)) {
1245                 DPRINTK("found PMP device by sig\n");
1246                 return ATA_DEV_PMP;
1247         }
1248
1249         if ((tf->lbam == 0x3c) && (tf->lbah == 0xc3)) {
1250                 printk(KERN_INFO "ata: SEMB device ignored\n");
1251                 return ATA_DEV_SEMB_UNSUP; /* not yet */
1252         }
1253
1254         DPRINTK("unknown device\n");
1255         return ATA_DEV_UNKNOWN;
1256 }
1257
1258 /**
1259  *      ata_id_string - Convert IDENTIFY DEVICE page into string
1260  *      @id: IDENTIFY DEVICE results we will examine
1261  *      @s: string into which data is output
1262  *      @ofs: offset into identify device page
1263  *      @len: length of string to return. must be an even number.
1264  *
1265  *      The strings in the IDENTIFY DEVICE page are broken up into
1266  *      16-bit chunks.  Run through the string, and output each
1267  *      8-bit chunk linearly, regardless of platform.
1268  *
1269  *      LOCKING:
1270  *      caller.
1271  */
1272
1273 void ata_id_string(const u16 *id, unsigned char *s,
1274                    unsigned int ofs, unsigned int len)
1275 {
1276         unsigned int c;
1277
1278         BUG_ON(len & 1);
1279
1280         while (len > 0) {
1281                 c = id[ofs] >> 8;
1282                 *s = c;
1283                 s++;
1284
1285                 c = id[ofs] & 0xff;
1286                 *s = c;
1287                 s++;
1288
1289                 ofs++;
1290                 len -= 2;
1291         }
1292 }
1293
1294 /**
1295  *      ata_id_c_string - Convert IDENTIFY DEVICE page into C string
1296  *      @id: IDENTIFY DEVICE results we will examine
1297  *      @s: string into which data is output
1298  *      @ofs: offset into identify device page
1299  *      @len: length of string to return. must be an odd number.
1300  *
1301  *      This function is identical to ata_id_string except that it
1302  *      trims trailing spaces and terminates the resulting string with
1303  *      null.  @len must be actual maximum length (even number) + 1.
1304  *
1305  *      LOCKING:
1306  *      caller.
1307  */
1308 void ata_id_c_string(const u16 *id, unsigned char *s,
1309                      unsigned int ofs, unsigned int len)
1310 {
1311         unsigned char *p;
1312
1313         ata_id_string(id, s, ofs, len - 1);
1314
1315         p = s + strnlen(s, len - 1);
1316         while (p > s && p[-1] == ' ')
1317                 p--;
1318         *p = '\0';
1319 }
1320
1321 static u64 ata_id_n_sectors(const u16 *id)
1322 {
1323         if (ata_id_has_lba(id)) {
1324                 if (ata_id_has_lba48(id))
1325                         return ata_id_u64(id, 100);
1326                 else
1327                         return ata_id_u32(id, 60);
1328         } else {
1329                 if (ata_id_current_chs_valid(id))
1330                         return ata_id_u32(id, 57);
1331                 else
1332                         return id[1] * id[3] * id[6];
1333         }
1334 }
1335
1336 u64 ata_tf_to_lba48(const struct ata_taskfile *tf)
1337 {
1338         u64 sectors = 0;
1339
1340         sectors |= ((u64)(tf->hob_lbah & 0xff)) << 40;
1341         sectors |= ((u64)(tf->hob_lbam & 0xff)) << 32;
1342         sectors |= ((u64)(tf->hob_lbal & 0xff)) << 24;
1343         sectors |= (tf->lbah & 0xff) << 16;
1344         sectors |= (tf->lbam & 0xff) << 8;
1345         sectors |= (tf->lbal & 0xff);
1346
1347         return sectors;
1348 }
1349
1350 u64 ata_tf_to_lba(const struct ata_taskfile *tf)
1351 {
1352         u64 sectors = 0;
1353
1354         sectors |= (tf->device & 0x0f) << 24;
1355         sectors |= (tf->lbah & 0xff) << 16;
1356         sectors |= (tf->lbam & 0xff) << 8;
1357         sectors |= (tf->lbal & 0xff);
1358
1359         return sectors;
1360 }
1361
1362 /**
1363  *      ata_read_native_max_address - Read native max address
1364  *      @dev: target device
1365  *      @max_sectors: out parameter for the result native max address
1366  *
1367  *      Perform an LBA48 or LBA28 native size query upon the device in
1368  *      question.
1369  *
1370  *      RETURNS:
1371  *      0 on success, -EACCES if command is aborted by the drive.
1372  *      -EIO on other errors.
1373  */
1374 static int ata_read_native_max_address(struct ata_device *dev, u64 *max_sectors)
1375 {
1376         unsigned int err_mask;
1377         struct ata_taskfile tf;
1378         int lba48 = ata_id_has_lba48(dev->id);
1379
1380         ata_tf_init(dev, &tf);
1381
1382         /* always clear all address registers */
1383         tf.flags |= ATA_TFLAG_DEVICE | ATA_TFLAG_ISADDR;
1384
1385         if (lba48) {
1386                 tf.command = ATA_CMD_READ_NATIVE_MAX_EXT;
1387                 tf.flags |= ATA_TFLAG_LBA48;
1388         } else
1389                 tf.command = ATA_CMD_READ_NATIVE_MAX;
1390
1391         tf.protocol |= ATA_PROT_NODATA;
1392         tf.device |= ATA_LBA;
1393
1394         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
1395         if (err_mask) {
1396                 ata_dev_printk(dev, KERN_WARNING, "failed to read native "
1397                                "max address (err_mask=0x%x)\n", err_mask);
1398                 if (err_mask == AC_ERR_DEV && (tf.feature & ATA_ABORTED))
1399                         return -EACCES;
1400                 return -EIO;
1401         }
1402
1403         if (lba48)
1404                 *max_sectors = ata_tf_to_lba48(&tf) + 1;
1405         else
1406                 *max_sectors = ata_tf_to_lba(&tf) + 1;
1407         if (dev->horkage & ATA_HORKAGE_HPA_SIZE)
1408                 (*max_sectors)--;
1409         return 0;
1410 }
1411
1412 /**
1413  *      ata_set_max_sectors - Set max sectors
1414  *      @dev: target device
1415  *      @new_sectors: new max sectors value to set for the device
1416  *
1417  *      Set max sectors of @dev to @new_sectors.
1418  *
1419  *      RETURNS:
1420  *      0 on success, -EACCES if command is aborted or denied (due to
1421  *      previous non-volatile SET_MAX) by the drive.  -EIO on other
1422  *      errors.
1423  */
1424 static int ata_set_max_sectors(struct ata_device *dev, u64 new_sectors)
1425 {
1426         unsigned int err_mask;
1427         struct ata_taskfile tf;
1428         int lba48 = ata_id_has_lba48(dev->id);
1429
1430         new_sectors--;
1431
1432         ata_tf_init(dev, &tf);
1433
1434         tf.flags |= ATA_TFLAG_DEVICE | ATA_TFLAG_ISADDR;
1435
1436         if (lba48) {
1437                 tf.command = ATA_CMD_SET_MAX_EXT;
1438                 tf.flags |= ATA_TFLAG_LBA48;
1439
1440                 tf.hob_lbal = (new_sectors >> 24) & 0xff;
1441                 tf.hob_lbam = (new_sectors >> 32) & 0xff;
1442                 tf.hob_lbah = (new_sectors >> 40) & 0xff;
1443         } else {
1444                 tf.command = ATA_CMD_SET_MAX;
1445
1446                 tf.device |= (new_sectors >> 24) & 0xf;
1447         }
1448
1449         tf.protocol |= ATA_PROT_NODATA;
1450         tf.device |= ATA_LBA;
1451
1452         tf.lbal = (new_sectors >> 0) & 0xff;
1453         tf.lbam = (new_sectors >> 8) & 0xff;
1454         tf.lbah = (new_sectors >> 16) & 0xff;
1455
1456         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
1457         if (err_mask) {
1458                 ata_dev_printk(dev, KERN_WARNING, "failed to set "
1459                                "max address (err_mask=0x%x)\n", err_mask);
1460                 if (err_mask == AC_ERR_DEV &&
1461                     (tf.feature & (ATA_ABORTED | ATA_IDNF)))
1462                         return -EACCES;
1463                 return -EIO;
1464         }
1465
1466         return 0;
1467 }
1468
1469 /**
1470  *      ata_hpa_resize          -       Resize a device with an HPA set
1471  *      @dev: Device to resize
1472  *
1473  *      Read the size of an LBA28 or LBA48 disk with HPA features and resize
1474  *      it if required to the full size of the media. The caller must check
1475  *      the drive has the HPA feature set enabled.
1476  *
1477  *      RETURNS:
1478  *      0 on success, -errno on failure.
1479  */
1480 static int ata_hpa_resize(struct ata_device *dev)
1481 {
1482         struct ata_eh_context *ehc = &dev->link->eh_context;
1483         int print_info = ehc->i.flags & ATA_EHI_PRINTINFO;
1484         u64 sectors = ata_id_n_sectors(dev->id);
1485         u64 native_sectors;
1486         int rc;
1487
1488         /* do we need to do it? */
1489         if (dev->class != ATA_DEV_ATA ||
1490             !ata_id_has_lba(dev->id) || !ata_id_hpa_enabled(dev->id) ||
1491             (dev->horkage & ATA_HORKAGE_BROKEN_HPA))
1492                 return 0;
1493
1494         /* read native max address */
1495         rc = ata_read_native_max_address(dev, &native_sectors);
1496         if (rc) {
1497                 /* If device aborted the command or HPA isn't going to
1498                  * be unlocked, skip HPA resizing.
1499                  */
1500                 if (rc == -EACCES || !ata_ignore_hpa) {
1501                         ata_dev_printk(dev, KERN_WARNING, "HPA support seems "
1502                                        "broken, skipping HPA handling\n");
1503                         dev->horkage |= ATA_HORKAGE_BROKEN_HPA;
1504
1505                         /* we can continue if device aborted the command */
1506                         if (rc == -EACCES)
1507                                 rc = 0;
1508                 }
1509
1510                 return rc;
1511         }
1512
1513         /* nothing to do? */
1514         if (native_sectors <= sectors || !ata_ignore_hpa) {
1515                 if (!print_info || native_sectors == sectors)
1516                         return 0;
1517
1518                 if (native_sectors > sectors)
1519                         ata_dev_printk(dev, KERN_INFO,
1520                                 "HPA detected: current %llu, native %llu\n",
1521                                 (unsigned long long)sectors,
1522                                 (unsigned long long)native_sectors);
1523                 else if (native_sectors < sectors)
1524                         ata_dev_printk(dev, KERN_WARNING,
1525                                 "native sectors (%llu) is smaller than "
1526                                 "sectors (%llu)\n",
1527                                 (unsigned long long)native_sectors,
1528                                 (unsigned long long)sectors);
1529                 return 0;
1530         }
1531
1532         /* let's unlock HPA */
1533         rc = ata_set_max_sectors(dev, native_sectors);
1534         if (rc == -EACCES) {
1535                 /* if device aborted the command, skip HPA resizing */
1536                 ata_dev_printk(dev, KERN_WARNING, "device aborted resize "
1537                                "(%llu -> %llu), skipping HPA handling\n",
1538                                (unsigned long long)sectors,
1539                                (unsigned long long)native_sectors);
1540                 dev->horkage |= ATA_HORKAGE_BROKEN_HPA;
1541                 return 0;
1542         } else if (rc)
1543                 return rc;
1544
1545         /* re-read IDENTIFY data */
1546         rc = ata_dev_reread_id(dev, 0);
1547         if (rc) {
1548                 ata_dev_printk(dev, KERN_ERR, "failed to re-read IDENTIFY "
1549                                "data after HPA resizing\n");
1550                 return rc;
1551         }
1552
1553         if (print_info) {
1554                 u64 new_sectors = ata_id_n_sectors(dev->id);
1555                 ata_dev_printk(dev, KERN_INFO,
1556                         "HPA unlocked: %llu -> %llu, native %llu\n",
1557                         (unsigned long long)sectors,
1558                         (unsigned long long)new_sectors,
1559                         (unsigned long long)native_sectors);
1560         }
1561
1562         return 0;
1563 }
1564
1565 /**
1566  *      ata_dump_id - IDENTIFY DEVICE info debugging output
1567  *      @id: IDENTIFY DEVICE page to dump
1568  *
1569  *      Dump selected 16-bit words from the given IDENTIFY DEVICE
1570  *      page.
1571  *
1572  *      LOCKING:
1573  *      caller.
1574  */
1575
1576 static inline void ata_dump_id(const u16 *id)
1577 {
1578         DPRINTK("49==0x%04x  "
1579                 "53==0x%04x  "
1580                 "63==0x%04x  "
1581                 "64==0x%04x  "
1582                 "75==0x%04x  \n",
1583                 id[49],
1584                 id[53],
1585                 id[63],
1586                 id[64],
1587                 id[75]);
1588         DPRINTK("80==0x%04x  "
1589                 "81==0x%04x  "
1590                 "82==0x%04x  "
1591                 "83==0x%04x  "
1592                 "84==0x%04x  \n",
1593                 id[80],
1594                 id[81],
1595                 id[82],
1596                 id[83],
1597                 id[84]);
1598         DPRINTK("88==0x%04x  "
1599                 "93==0x%04x\n",
1600                 id[88],
1601                 id[93]);
1602 }
1603
1604 /**
1605  *      ata_id_xfermask - Compute xfermask from the given IDENTIFY data
1606  *      @id: IDENTIFY data to compute xfer mask from
1607  *
1608  *      Compute the xfermask for this device. This is not as trivial
1609  *      as it seems if we must consider early devices correctly.
1610  *
1611  *      FIXME: pre IDE drive timing (do we care ?).
1612  *
1613  *      LOCKING:
1614  *      None.
1615  *
1616  *      RETURNS:
1617  *      Computed xfermask
1618  */
1619 unsigned long ata_id_xfermask(const u16 *id)
1620 {
1621         unsigned long pio_mask, mwdma_mask, udma_mask;
1622
1623         /* Usual case. Word 53 indicates word 64 is valid */
1624         if (id[ATA_ID_FIELD_VALID] & (1 << 1)) {
1625                 pio_mask = id[ATA_ID_PIO_MODES] & 0x03;
1626                 pio_mask <<= 3;
1627                 pio_mask |= 0x7;
1628         } else {
1629                 /* If word 64 isn't valid then Word 51 high byte holds
1630                  * the PIO timing number for the maximum. Turn it into
1631                  * a mask.
1632                  */
1633                 u8 mode = (id[ATA_ID_OLD_PIO_MODES] >> 8) & 0xFF;
1634                 if (mode < 5)   /* Valid PIO range */
1635                         pio_mask = (2 << mode) - 1;
1636                 else
1637                         pio_mask = 1;
1638
1639                 /* But wait.. there's more. Design your standards by
1640                  * committee and you too can get a free iordy field to
1641                  * process. However its the speeds not the modes that
1642                  * are supported... Note drivers using the timing API
1643                  * will get this right anyway
1644                  */
1645         }
1646
1647         mwdma_mask = id[ATA_ID_MWDMA_MODES] & 0x07;
1648
1649         if (ata_id_is_cfa(id)) {
1650                 /*
1651                  *      Process compact flash extended modes
1652                  */
1653                 int pio = id[163] & 0x7;
1654                 int dma = (id[163] >> 3) & 7;
1655
1656                 if (pio)
1657                         pio_mask |= (1 << 5);
1658                 if (pio > 1)
1659                         pio_mask |= (1 << 6);
1660                 if (dma)
1661                         mwdma_mask |= (1 << 3);
1662                 if (dma > 1)
1663                         mwdma_mask |= (1 << 4);
1664         }
1665
1666         udma_mask = 0;
1667         if (id[ATA_ID_FIELD_VALID] & (1 << 2))
1668                 udma_mask = id[ATA_ID_UDMA_MODES] & 0xff;
1669
1670         return ata_pack_xfermask(pio_mask, mwdma_mask, udma_mask);
1671 }
1672
1673 /**
1674  *      ata_pio_queue_task - Queue port_task
1675  *      @ap: The ata_port to queue port_task for
1676  *      @data: data for @fn to use
1677  *      @delay: delay time in msecs for workqueue function
1678  *
1679  *      Schedule @fn(@data) for execution after @delay jiffies using
1680  *      port_task.  There is one port_task per port and it's the
1681  *      user(low level driver)'s responsibility to make sure that only
1682  *      one task is active at any given time.
1683  *
1684  *      libata core layer takes care of synchronization between
1685  *      port_task and EH.  ata_pio_queue_task() may be ignored for EH
1686  *      synchronization.
1687  *
1688  *      LOCKING:
1689  *      Inherited from caller.
1690  */
1691 void ata_pio_queue_task(struct ata_port *ap, void *data, unsigned long delay)
1692 {
1693         ap->port_task_data = data;
1694
1695         /* may fail if ata_port_flush_task() in progress */
1696         queue_delayed_work(ata_wq, &ap->port_task, msecs_to_jiffies(delay));
1697 }
1698
1699 /**
1700  *      ata_port_flush_task - Flush port_task
1701  *      @ap: The ata_port to flush port_task for
1702  *
1703  *      After this function completes, port_task is guranteed not to
1704  *      be running or scheduled.
1705  *
1706  *      LOCKING:
1707  *      Kernel thread context (may sleep)
1708  */
1709 void ata_port_flush_task(struct ata_port *ap)
1710 {
1711         DPRINTK("ENTER\n");
1712
1713         cancel_rearming_delayed_work(&ap->port_task);
1714
1715         if (ata_msg_ctl(ap))
1716                 ata_port_printk(ap, KERN_DEBUG, "%s: EXIT\n", __func__);
1717 }
1718
1719 static void ata_qc_complete_internal(struct ata_queued_cmd *qc)
1720 {
1721         struct completion *waiting = qc->private_data;
1722
1723         complete(waiting);
1724 }
1725
1726 /**
1727  *      ata_exec_internal_sg - execute libata internal command
1728  *      @dev: Device to which the command is sent
1729  *      @tf: Taskfile registers for the command and the result
1730  *      @cdb: CDB for packet command
1731  *      @dma_dir: Data tranfer direction of the command
1732  *      @sgl: sg list for the data buffer of the command
1733  *      @n_elem: Number of sg entries
1734  *      @timeout: Timeout in msecs (0 for default)
1735  *
1736  *      Executes libata internal command with timeout.  @tf contains
1737  *      command on entry and result on return.  Timeout and error
1738  *      conditions are reported via return value.  No recovery action
1739  *      is taken after a command times out.  It's caller's duty to
1740  *      clean up after timeout.
1741  *
1742  *      LOCKING:
1743  *      None.  Should be called with kernel context, might sleep.
1744  *
1745  *      RETURNS:
1746  *      Zero on success, AC_ERR_* mask on failure
1747  */
1748 unsigned ata_exec_internal_sg(struct ata_device *dev,
1749                               struct ata_taskfile *tf, const u8 *cdb,
1750                               int dma_dir, struct scatterlist *sgl,
1751                               unsigned int n_elem, unsigned long timeout)
1752 {
1753         struct ata_link *link = dev->link;
1754         struct ata_port *ap = link->ap;
1755         u8 command = tf->command;
1756         int auto_timeout = 0;
1757         struct ata_queued_cmd *qc;
1758         unsigned int tag, preempted_tag;
1759         u32 preempted_sactive, preempted_qc_active;
1760         int preempted_nr_active_links;
1761         DECLARE_COMPLETION_ONSTACK(wait);
1762         unsigned long flags;
1763         unsigned int err_mask;
1764         int rc;
1765
1766         spin_lock_irqsave(ap->lock, flags);
1767
1768         /* no internal command while frozen */
1769         if (ap->pflags & ATA_PFLAG_FROZEN) {
1770                 spin_unlock_irqrestore(ap->lock, flags);
1771                 return AC_ERR_SYSTEM;
1772         }
1773
1774         /* initialize internal qc */
1775
1776         /* XXX: Tag 0 is used for drivers with legacy EH as some
1777          * drivers choke if any other tag is given.  This breaks
1778          * ata_tag_internal() test for those drivers.  Don't use new
1779          * EH stuff without converting to it.
1780          */
1781         if (ap->ops->error_handler)
1782                 tag = ATA_TAG_INTERNAL;
1783         else
1784                 tag = 0;
1785
1786         if (test_and_set_bit(tag, &ap->qc_allocated))
1787                 BUG();
1788         qc = __ata_qc_from_tag(ap, tag);
1789
1790         qc->tag = tag;
1791         qc->scsicmd = NULL;
1792         qc->ap = ap;
1793         qc->dev = dev;
1794         ata_qc_reinit(qc);
1795
1796         preempted_tag = link->active_tag;
1797         preempted_sactive = link->sactive;
1798         preempted_qc_active = ap->qc_active;
1799         preempted_nr_active_links = ap->nr_active_links;
1800         link->active_tag = ATA_TAG_POISON;
1801         link->sactive = 0;
1802         ap->qc_active = 0;
1803         ap->nr_active_links = 0;
1804
1805         /* prepare & issue qc */
1806         qc->tf = *tf;
1807         if (cdb)
1808                 memcpy(qc->cdb, cdb, ATAPI_CDB_LEN);
1809         qc->flags |= ATA_QCFLAG_RESULT_TF;
1810         qc->dma_dir = dma_dir;
1811         if (dma_dir != DMA_NONE) {
1812                 unsigned int i, buflen = 0;
1813                 struct scatterlist *sg;
1814
1815                 for_each_sg(sgl, sg, n_elem, i)
1816                         buflen += sg->length;
1817
1818                 ata_sg_init(qc, sgl, n_elem);
1819                 qc->nbytes = buflen;
1820         }
1821
1822         qc->private_data = &wait;
1823         qc->complete_fn = ata_qc_complete_internal;
1824
1825         ata_qc_issue(qc);
1826
1827         spin_unlock_irqrestore(ap->lock, flags);
1828
1829         if (!timeout) {
1830                 if (ata_probe_timeout)
1831                         timeout = ata_probe_timeout * 1000;
1832                 else {
1833                         timeout = ata_internal_cmd_timeout(dev, command);
1834                         auto_timeout = 1;
1835                 }
1836         }
1837
1838         rc = wait_for_completion_timeout(&wait, msecs_to_jiffies(timeout));
1839
1840         ata_port_flush_task(ap);
1841
1842         if (!rc) {
1843                 spin_lock_irqsave(ap->lock, flags);
1844
1845                 /* We're racing with irq here.  If we lose, the
1846                  * following test prevents us from completing the qc
1847                  * twice.  If we win, the port is frozen and will be
1848                  * cleaned up by ->post_internal_cmd().
1849                  */
1850                 if (qc->flags & ATA_QCFLAG_ACTIVE) {
1851                         qc->err_mask |= AC_ERR_TIMEOUT;
1852
1853                         if (ap->ops->error_handler)
1854                                 ata_port_freeze(ap);
1855                         else
1856                                 ata_qc_complete(qc);
1857
1858                         if (ata_msg_warn(ap))
1859                                 ata_dev_printk(dev, KERN_WARNING,
1860                                         "qc timeout (cmd 0x%x)\n", command);
1861                 }
1862
1863                 spin_unlock_irqrestore(ap->lock, flags);
1864         }
1865
1866         /* do post_internal_cmd */
1867         if (ap->ops->post_internal_cmd)
1868                 ap->ops->post_internal_cmd(qc);
1869
1870         /* perform minimal error analysis */
1871         if (qc->flags & ATA_QCFLAG_FAILED) {
1872                 if (qc->result_tf.command & (ATA_ERR | ATA_DF))
1873                         qc->err_mask |= AC_ERR_DEV;
1874
1875                 if (!qc->err_mask)
1876                         qc->err_mask |= AC_ERR_OTHER;
1877
1878                 if (qc->err_mask & ~AC_ERR_OTHER)
1879                         qc->err_mask &= ~AC_ERR_OTHER;
1880         }
1881
1882         /* finish up */
1883         spin_lock_irqsave(ap->lock, flags);
1884
1885         *tf = qc->result_tf;
1886         err_mask = qc->err_mask;
1887
1888         ata_qc_free(qc);
1889         link->active_tag = preempted_tag;
1890         link->sactive = preempted_sactive;
1891         ap->qc_active = preempted_qc_active;
1892         ap->nr_active_links = preempted_nr_active_links;
1893
1894         /* XXX - Some LLDDs (sata_mv) disable port on command failure.
1895          * Until those drivers are fixed, we detect the condition
1896          * here, fail the command with AC_ERR_SYSTEM and reenable the
1897          * port.
1898          *
1899          * Note that this doesn't change any behavior as internal
1900          * command failure results in disabling the device in the
1901          * higher layer for LLDDs without new reset/EH callbacks.
1902          *
1903          * Kill the following code as soon as those drivers are fixed.
1904          */
1905         if (ap->flags & ATA_FLAG_DISABLED) {
1906                 err_mask |= AC_ERR_SYSTEM;
1907                 ata_port_probe(ap);
1908         }
1909
1910         spin_unlock_irqrestore(ap->lock, flags);
1911
1912         if ((err_mask & AC_ERR_TIMEOUT) && auto_timeout)
1913                 ata_internal_cmd_timed_out(dev, command);
1914
1915         return err_mask;
1916 }
1917
1918 /**
1919  *      ata_exec_internal - execute libata internal command
1920  *      @dev: Device to which the command is sent
1921  *      @tf: Taskfile registers for the command and the result
1922  *      @cdb: CDB for packet command
1923  *      @dma_dir: Data tranfer direction of the command
1924  *      @buf: Data buffer of the command
1925  *      @buflen: Length of data buffer
1926  *      @timeout: Timeout in msecs (0 for default)
1927  *
1928  *      Wrapper around ata_exec_internal_sg() which takes simple
1929  *      buffer instead of sg list.
1930  *
1931  *      LOCKING:
1932  *      None.  Should be called with kernel context, might sleep.
1933  *
1934  *      RETURNS:
1935  *      Zero on success, AC_ERR_* mask on failure
1936  */
1937 unsigned ata_exec_internal(struct ata_device *dev,
1938                            struct ata_taskfile *tf, const u8 *cdb,
1939                            int dma_dir, void *buf, unsigned int buflen,
1940                            unsigned long timeout)
1941 {
1942         struct scatterlist *psg = NULL, sg;
1943         unsigned int n_elem = 0;
1944
1945         if (dma_dir != DMA_NONE) {
1946                 WARN_ON(!buf);
1947                 sg_init_one(&sg, buf, buflen);
1948                 psg = &sg;
1949                 n_elem++;
1950         }
1951
1952         return ata_exec_internal_sg(dev, tf, cdb, dma_dir, psg, n_elem,
1953                                     timeout);
1954 }
1955
1956 /**
1957  *      ata_do_simple_cmd - execute simple internal command
1958  *      @dev: Device to which the command is sent
1959  *      @cmd: Opcode to execute
1960  *
1961  *      Execute a 'simple' command, that only consists of the opcode
1962  *      'cmd' itself, without filling any other registers
1963  *
1964  *      LOCKING:
1965  *      Kernel thread context (may sleep).
1966  *
1967  *      RETURNS:
1968  *      Zero on success, AC_ERR_* mask on failure
1969  */
1970 unsigned int ata_do_simple_cmd(struct ata_device *dev, u8 cmd)
1971 {
1972         struct ata_taskfile tf;
1973
1974         ata_tf_init(dev, &tf);
1975
1976         tf.command = cmd;
1977         tf.flags |= ATA_TFLAG_DEVICE;
1978         tf.protocol = ATA_PROT_NODATA;
1979
1980         return ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
1981 }
1982
1983 /**
1984  *      ata_pio_need_iordy      -       check if iordy needed
1985  *      @adev: ATA device
1986  *
1987  *      Check if the current speed of the device requires IORDY. Used
1988  *      by various controllers for chip configuration.
1989  */
1990
1991 unsigned int ata_pio_need_iordy(const struct ata_device *adev)
1992 {
1993         /* Controller doesn't support  IORDY. Probably a pointless check
1994            as the caller should know this */
1995         if (adev->link->ap->flags & ATA_FLAG_NO_IORDY)
1996                 return 0;
1997         /* CF spec. r4.1 Table 22 says no iordy on PIO5 and PIO6.  */
1998         if (ata_id_is_cfa(adev->id)
1999             && (adev->pio_mode == XFER_PIO_5 || adev->pio_mode == XFER_PIO_6))
2000                 return 0;
2001         /* PIO3 and higher it is mandatory */
2002         if (adev->pio_mode > XFER_PIO_2)
2003                 return 1;
2004         /* We turn it on when possible */
2005         if (ata_id_has_iordy(adev->id))
2006                 return 1;
2007         return 0;
2008 }
2009
2010 /**
2011  *      ata_pio_mask_no_iordy   -       Return the non IORDY mask
2012  *      @adev: ATA device
2013  *
2014  *      Compute the highest mode possible if we are not using iordy. Return
2015  *      -1 if no iordy mode is available.
2016  */
2017
2018 static u32 ata_pio_mask_no_iordy(const struct ata_device *adev)
2019 {
2020         /* If we have no drive specific rule, then PIO 2 is non IORDY */
2021         if (adev->id[ATA_ID_FIELD_VALID] & 2) { /* EIDE */
2022                 u16 pio = adev->id[ATA_ID_EIDE_PIO];
2023                 /* Is the speed faster than the drive allows non IORDY ? */
2024                 if (pio) {
2025                         /* This is cycle times not frequency - watch the logic! */
2026                         if (pio > 240)  /* PIO2 is 240nS per cycle */
2027                                 return 3 << ATA_SHIFT_PIO;
2028                         return 7 << ATA_SHIFT_PIO;
2029                 }
2030         }
2031         return 3 << ATA_SHIFT_PIO;
2032 }
2033
2034 /**
2035  *      ata_do_dev_read_id              -       default ID read method
2036  *      @dev: device
2037  *      @tf: proposed taskfile
2038  *      @id: data buffer
2039  *
2040  *      Issue the identify taskfile and hand back the buffer containing
2041  *      identify data. For some RAID controllers and for pre ATA devices
2042  *      this function is wrapped or replaced by the driver
2043  */
2044 unsigned int ata_do_dev_read_id(struct ata_device *dev,
2045                                         struct ata_taskfile *tf, u16 *id)
2046 {
2047         return ata_exec_internal(dev, tf, NULL, DMA_FROM_DEVICE,
2048                                      id, sizeof(id[0]) * ATA_ID_WORDS, 0);
2049 }
2050
2051 /**
2052  *      ata_dev_read_id - Read ID data from the specified device
2053  *      @dev: target device
2054  *      @p_class: pointer to class of the target device (may be changed)
2055  *      @flags: ATA_READID_* flags
2056  *      @id: buffer to read IDENTIFY data into
2057  *
2058  *      Read ID data from the specified device.  ATA_CMD_ID_ATA is
2059  *      performed on ATA devices and ATA_CMD_ID_ATAPI on ATAPI
2060  *      devices.  This function also issues ATA_CMD_INIT_DEV_PARAMS
2061  *      for pre-ATA4 drives.
2062  *
2063  *      FIXME: ATA_CMD_ID_ATA is optional for early drives and right
2064  *      now we abort if we hit that case.
2065  *
2066  *      LOCKING:
2067  *      Kernel thread context (may sleep)
2068  *
2069  *      RETURNS:
2070  *      0 on success, -errno otherwise.
2071  */
2072 int ata_dev_read_id(struct ata_device *dev, unsigned int *p_class,
2073                     unsigned int flags, u16 *id)
2074 {
2075         struct ata_port *ap = dev->link->ap;
2076         unsigned int class = *p_class;
2077         struct ata_taskfile tf;
2078         unsigned int err_mask = 0;
2079         const char *reason;
2080         int may_fallback = 1, tried_spinup = 0;
2081         int rc;
2082
2083         if (ata_msg_ctl(ap))
2084                 ata_dev_printk(dev, KERN_DEBUG, "%s: ENTER\n", __func__);
2085
2086 retry:
2087         ata_tf_init(dev, &tf);
2088
2089         switch (class) {
2090         case ATA_DEV_ATA:
2091                 tf.command = ATA_CMD_ID_ATA;
2092                 break;
2093         case ATA_DEV_ATAPI:
2094                 tf.command = ATA_CMD_ID_ATAPI;
2095                 break;
2096         default:
2097                 rc = -ENODEV;
2098                 reason = "unsupported class";
2099                 goto err_out;
2100         }
2101
2102         tf.protocol = ATA_PROT_PIO;
2103
2104         /* Some devices choke if TF registers contain garbage.  Make
2105          * sure those are properly initialized.
2106          */
2107         tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
2108
2109         /* Device presence detection is unreliable on some
2110          * controllers.  Always poll IDENTIFY if available.
2111          */
2112         tf.flags |= ATA_TFLAG_POLLING;
2113
2114         if (ap->ops->read_id)
2115                 err_mask = ap->ops->read_id(dev, &tf, id);
2116         else
2117                 err_mask = ata_do_dev_read_id(dev, &tf, id);
2118
2119         if (err_mask) {
2120                 if (err_mask & AC_ERR_NODEV_HINT) {
2121                         ata_dev_printk(dev, KERN_DEBUG,
2122                                        "NODEV after polling detection\n");
2123                         return -ENOENT;
2124                 }
2125
2126                 if ((err_mask == AC_ERR_DEV) && (tf.feature & ATA_ABORTED)) {
2127                         /* Device or controller might have reported
2128                          * the wrong device class.  Give a shot at the
2129                          * other IDENTIFY if the current one is
2130                          * aborted by the device.
2131                          */
2132                         if (may_fallback) {
2133                                 may_fallback = 0;
2134
2135                                 if (class == ATA_DEV_ATA)
2136                                         class = ATA_DEV_ATAPI;
2137                                 else
2138                                         class = ATA_DEV_ATA;
2139                                 goto retry;
2140                         }
2141
2142                         /* Control reaches here iff the device aborted
2143                          * both flavors of IDENTIFYs which happens
2144                          * sometimes with phantom devices.
2145                          */
2146                         ata_dev_printk(dev, KERN_DEBUG,
2147                                        "both IDENTIFYs aborted, assuming NODEV\n");
2148                         return -ENOENT;
2149                 }
2150
2151                 rc = -EIO;
2152                 reason = "I/O error";
2153                 goto err_out;
2154         }
2155
2156         /* Falling back doesn't make sense if ID data was read
2157          * successfully at least once.
2158          */
2159         may_fallback = 0;
2160
2161         swap_buf_le16(id, ATA_ID_WORDS);
2162
2163         /* sanity check */
2164         rc = -EINVAL;
2165         reason = "device reports invalid type";
2166
2167         if (class == ATA_DEV_ATA) {
2168                 if (!ata_id_is_ata(id) && !ata_id_is_cfa(id))
2169                         goto err_out;
2170         } else {
2171                 if (ata_id_is_ata(id))
2172                         goto err_out;
2173         }
2174
2175         if (!tried_spinup && (id[2] == 0x37c8 || id[2] == 0x738c)) {
2176                 tried_spinup = 1;
2177                 /*
2178                  * Drive powered-up in standby mode, and requires a specific
2179                  * SET_FEATURES spin-up subcommand before it will accept
2180                  * anything other than the original IDENTIFY command.
2181                  */
2182                 err_mask = ata_dev_set_feature(dev, SETFEATURES_SPINUP, 0);
2183                 if (err_mask && id[2] != 0x738c) {
2184                         rc = -EIO;
2185                         reason = "SPINUP failed";
2186                         goto err_out;
2187                 }
2188                 /*
2189                  * If the drive initially returned incomplete IDENTIFY info,
2190                  * we now must reissue the IDENTIFY command.
2191                  */
2192                 if (id[2] == 0x37c8)
2193                         goto retry;
2194         }
2195
2196         if ((flags & ATA_READID_POSTRESET) && class == ATA_DEV_ATA) {
2197                 /*
2198                  * The exact sequence expected by certain pre-ATA4 drives is:
2199                  * SRST RESET
2200                  * IDENTIFY (optional in early ATA)
2201                  * INITIALIZE DEVICE PARAMETERS (later IDE and ATA)
2202                  * anything else..
2203                  * Some drives were very specific about that exact sequence.
2204                  *
2205                  * Note that ATA4 says lba is mandatory so the second check
2206                  * shoud never trigger.
2207                  */
2208                 if (ata_id_major_version(id) < 4 || !ata_id_has_lba(id)) {
2209                         err_mask = ata_dev_init_params(dev, id[3], id[6]);
2210                         if (err_mask) {
2211                                 rc = -EIO;
2212                                 reason = "INIT_DEV_PARAMS failed";
2213                                 goto err_out;
2214                         }
2215
2216                         /* current CHS translation info (id[53-58]) might be
2217                          * changed. reread the identify device info.
2218                          */
2219                         flags &= ~ATA_READID_POSTRESET;
2220                         goto retry;
2221                 }
2222         }
2223
2224         *p_class = class;
2225
2226         return 0;
2227
2228  err_out:
2229         if (ata_msg_warn(ap))
2230                 ata_dev_printk(dev, KERN_WARNING, "failed to IDENTIFY "
2231                                "(%s, err_mask=0x%x)\n", reason, err_mask);
2232         return rc;
2233 }
2234
2235 static int ata_do_link_spd_horkage(struct ata_device *dev)
2236 {
2237         struct ata_link *plink = ata_dev_phys_link(dev);
2238         u32 target, target_limit;
2239
2240         if (!sata_scr_valid(plink))
2241                 return 0;
2242
2243         if (dev->horkage & ATA_HORKAGE_1_5_GBPS)
2244                 target = 1;
2245         else
2246                 return 0;
2247
2248         target_limit = (1 << target) - 1;
2249
2250         /* if already on stricter limit, no need to push further */
2251         if (plink->sata_spd_limit <= target_limit)
2252                 return 0;
2253
2254         plink->sata_spd_limit = target_limit;
2255
2256         /* Request another EH round by returning -EAGAIN if link is
2257          * going faster than the target speed.  Forward progress is
2258          * guaranteed by setting sata_spd_limit to target_limit above.
2259          */
2260         if (plink->sata_spd > target) {
2261                 ata_dev_printk(dev, KERN_INFO,
2262                                "applying link speed limit horkage to %s\n",
2263                                sata_spd_string(target));
2264                 return -EAGAIN;
2265         }
2266         return 0;
2267 }
2268
2269 static inline u8 ata_dev_knobble(struct ata_device *dev)
2270 {
2271         struct ata_port *ap = dev->link->ap;
2272
2273         if (ata_dev_blacklisted(dev) & ATA_HORKAGE_BRIDGE_OK)
2274                 return 0;
2275
2276         return ((ap->cbl == ATA_CBL_SATA) && (!ata_id_is_sata(dev->id)));
2277 }
2278
2279 static void ata_dev_config_ncq(struct ata_device *dev,
2280                                char *desc, size_t desc_sz)
2281 {
2282         struct ata_port *ap = dev->link->ap;
2283         int hdepth = 0, ddepth = ata_id_queue_depth(dev->id);
2284
2285         if (!ata_id_has_ncq(dev->id)) {
2286                 desc[0] = '\0';
2287                 return;
2288         }
2289         if (dev->horkage & ATA_HORKAGE_NONCQ) {
2290                 snprintf(desc, desc_sz, "NCQ (not used)");
2291                 return;
2292         }
2293         if (ap->flags & ATA_FLAG_NCQ) {
2294                 hdepth = min(ap->scsi_host->can_queue, ATA_MAX_QUEUE - 1);
2295                 dev->flags |= ATA_DFLAG_NCQ;
2296         }
2297
2298         if (hdepth >= ddepth)
2299                 snprintf(desc, desc_sz, "NCQ (depth %d)", ddepth);
2300         else
2301                 snprintf(desc, desc_sz, "NCQ (depth %d/%d)", hdepth, ddepth);
2302 }
2303
2304 /**
2305  *      ata_dev_configure - Configure the specified ATA/ATAPI device
2306  *      @dev: Target device to configure
2307  *
2308  *      Configure @dev according to @dev->id.  Generic and low-level
2309  *      driver specific fixups are also applied.
2310  *
2311  *      LOCKING:
2312  *      Kernel thread context (may sleep)
2313  *
2314  *      RETURNS:
2315  *      0 on success, -errno otherwise
2316  */
2317 int ata_dev_configure(struct ata_device *dev)
2318 {
2319         struct ata_port *ap = dev->link->ap;
2320         struct ata_eh_context *ehc = &dev->link->eh_context;
2321         int print_info = ehc->i.flags & ATA_EHI_PRINTINFO;
2322         const u16 *id = dev->id;
2323         unsigned long xfer_mask;
2324         char revbuf[7];         /* XYZ-99\0 */
2325         char fwrevbuf[ATA_ID_FW_REV_LEN+1];
2326         char modelbuf[ATA_ID_PROD_LEN+1];
2327         int rc;
2328
2329         if (!ata_dev_enabled(dev) && ata_msg_info(ap)) {
2330                 ata_dev_printk(dev, KERN_INFO, "%s: ENTER/EXIT -- nodev\n",
2331                                __func__);
2332                 return 0;
2333         }
2334
2335         if (ata_msg_probe(ap))
2336                 ata_dev_printk(dev, KERN_DEBUG, "%s: ENTER\n", __func__);
2337
2338         /* set horkage */
2339         dev->horkage |= ata_dev_blacklisted(dev);
2340         ata_force_horkage(dev);
2341
2342         if (dev->horkage & ATA_HORKAGE_DISABLE) {
2343                 ata_dev_printk(dev, KERN_INFO,
2344                                "unsupported device, disabling\n");
2345                 ata_dev_disable(dev);
2346                 return 0;
2347         }
2348
2349         if ((!atapi_enabled || (ap->flags & ATA_FLAG_NO_ATAPI)) &&
2350             dev->class == ATA_DEV_ATAPI) {
2351                 ata_dev_printk(dev, KERN_WARNING,
2352                         "WARNING: ATAPI is %s, device ignored.\n",
2353                         atapi_enabled ? "not supported with this driver"
2354                                       : "disabled");
2355                 ata_dev_disable(dev);
2356                 return 0;
2357         }
2358
2359         rc = ata_do_link_spd_horkage(dev);
2360         if (rc)
2361                 return rc;
2362
2363         /* let ACPI work its magic */
2364         rc = ata_acpi_on_devcfg(dev);
2365         if (rc)
2366                 return rc;
2367
2368         /* massage HPA, do it early as it might change IDENTIFY data */
2369         rc = ata_hpa_resize(dev);
2370         if (rc)
2371                 return rc;
2372
2373         /* print device capabilities */
2374         if (ata_msg_probe(ap))
2375                 ata_dev_printk(dev, KERN_DEBUG,
2376                                "%s: cfg 49:%04x 82:%04x 83:%04x 84:%04x "
2377                                "85:%04x 86:%04x 87:%04x 88:%04x\n",
2378                                __func__,
2379                                id[49], id[82], id[83], id[84],
2380                                id[85], id[86], id[87], id[88]);
2381
2382         /* initialize to-be-configured parameters */
2383         dev->flags &= ~ATA_DFLAG_CFG_MASK;
2384         dev->max_sectors = 0;
2385         dev->cdb_len = 0;
2386         dev->n_sectors = 0;
2387         dev->cylinders = 0;
2388         dev->heads = 0;
2389         dev->sectors = 0;
2390
2391         /*
2392          * common ATA, ATAPI feature tests
2393          */
2394
2395         /* find max transfer mode; for printk only */
2396         xfer_mask = ata_id_xfermask(id);
2397
2398         if (ata_msg_probe(ap))
2399                 ata_dump_id(id);
2400
2401         /* SCSI only uses 4-char revisions, dump full 8 chars from ATA */
2402         ata_id_c_string(dev->id, fwrevbuf, ATA_ID_FW_REV,
2403                         sizeof(fwrevbuf));
2404
2405         ata_id_c_string(dev->id, modelbuf, ATA_ID_PROD,
2406                         sizeof(modelbuf));
2407
2408         /* ATA-specific feature tests */
2409         if (dev->class == ATA_DEV_ATA) {
2410                 if (ata_id_is_cfa(id)) {
2411                         if (id[162] & 1) /* CPRM may make this media unusable */
2412                                 ata_dev_printk(dev, KERN_WARNING,
2413                                                "supports DRM functions and may "
2414                                                "not be fully accessable.\n");
2415                         snprintf(revbuf, 7, "CFA");
2416                 } else {
2417                         snprintf(revbuf, 7, "ATA-%d", ata_id_major_version(id));
2418                         /* Warn the user if the device has TPM extensions */
2419                         if (ata_id_has_tpm(id))
2420                                 ata_dev_printk(dev, KERN_WARNING,
2421                                                "supports DRM functions and may "
2422                                                "not be fully accessable.\n");
2423                 }
2424
2425                 dev->n_sectors = ata_id_n_sectors(id);
2426
2427                 if (dev->id[59] & 0x100)
2428                         dev->multi_count = dev->id[59] & 0xff;
2429
2430                 if (ata_id_has_lba(id)) {
2431                         const char *lba_desc;
2432                         char ncq_desc[20];
2433
2434                         lba_desc = "LBA";
2435                         dev->flags |= ATA_DFLAG_LBA;
2436                         if (ata_id_has_lba48(id)) {
2437                                 dev->flags |= ATA_DFLAG_LBA48;
2438                                 lba_desc = "LBA48";
2439
2440                                 if (dev->n_sectors >= (1UL << 28) &&
2441                                     ata_id_has_flush_ext(id))
2442                                         dev->flags |= ATA_DFLAG_FLUSH_EXT;
2443                         }
2444
2445                         /* config NCQ */
2446                         ata_dev_config_ncq(dev, ncq_desc, sizeof(ncq_desc));
2447
2448                         /* print device info to dmesg */
2449                         if (ata_msg_drv(ap) && print_info) {
2450                                 ata_dev_printk(dev, KERN_INFO,
2451                                         "%s: %s, %s, max %s\n",
2452                                         revbuf, modelbuf, fwrevbuf,
2453                                         ata_mode_string(xfer_mask));
2454                                 ata_dev_printk(dev, KERN_INFO,
2455                                         "%Lu sectors, multi %u: %s %s\n",
2456                                         (unsigned long long)dev->n_sectors,
2457                                         dev->multi_count, lba_desc, ncq_desc);
2458                         }
2459                 } else {
2460                         /* CHS */
2461
2462                         /* Default translation */
2463                         dev->cylinders  = id[1];
2464                         dev->heads      = id[3];
2465                         dev->sectors    = id[6];
2466
2467                         if (ata_id_current_chs_valid(id)) {
2468                                 /* Current CHS translation is valid. */
2469                                 dev->cylinders = id[54];
2470                                 dev->heads     = id[55];
2471                                 dev->sectors   = id[56];
2472                         }
2473
2474                         /* print device info to dmesg */
2475                         if (ata_msg_drv(ap) && print_info) {
2476                                 ata_dev_printk(dev, KERN_INFO,
2477                                         "%s: %s, %s, max %s\n",
2478                                         revbuf, modelbuf, fwrevbuf,
2479                                         ata_mode_string(xfer_mask));
2480                                 ata_dev_printk(dev, KERN_INFO,
2481                                         "%Lu sectors, multi %u, CHS %u/%u/%u\n",
2482                                         (unsigned long long)dev->n_sectors,
2483                                         dev->multi_count, dev->cylinders,
2484                                         dev->heads, dev->sectors);
2485                         }
2486                 }
2487
2488                 dev->cdb_len = 16;
2489         }
2490
2491         /* ATAPI-specific feature tests */
2492         else if (dev->class == ATA_DEV_ATAPI) {
2493                 const char *cdb_intr_string = "";
2494                 const char *atapi_an_string = "";
2495                 const char *dma_dir_string = "";
2496                 u32 sntf;
2497
2498                 rc = atapi_cdb_len(id);
2499                 if ((rc < 12) || (rc > ATAPI_CDB_LEN)) {
2500                         if (ata_msg_warn(ap))
2501                                 ata_dev_printk(dev, KERN_WARNING,
2502                                                "unsupported CDB len\n");
2503                         rc = -EINVAL;
2504                         goto err_out_nosup;
2505                 }
2506                 dev->cdb_len = (unsigned int) rc;
2507
2508                 /* Enable ATAPI AN if both the host and device have
2509                  * the support.  If PMP is attached, SNTF is required
2510                  * to enable ATAPI AN to discern between PHY status
2511                  * changed notifications and ATAPI ANs.
2512                  */
2513                 if ((ap->flags & ATA_FLAG_AN) && ata_id_has_atapi_AN(id) &&
2514                     (!sata_pmp_attached(ap) ||
2515                      sata_scr_read(&ap->link, SCR_NOTIFICATION, &sntf) == 0)) {
2516                         unsigned int err_mask;
2517
2518                         /* issue SET feature command to turn this on */
2519                         err_mask = ata_dev_set_feature(dev,
2520                                         SETFEATURES_SATA_ENABLE, SATA_AN);
2521                         if (err_mask)
2522                                 ata_dev_printk(dev, KERN_ERR,
2523                                         "failed to enable ATAPI AN "
2524                                         "(err_mask=0x%x)\n", err_mask);
2525                         else {
2526                                 dev->flags |= ATA_DFLAG_AN;
2527                                 atapi_an_string = ", ATAPI AN";
2528                         }
2529                 }
2530
2531                 if (ata_id_cdb_intr(dev->id)) {
2532                         dev->flags |= ATA_DFLAG_CDB_INTR;
2533                         cdb_intr_string = ", CDB intr";
2534                 }
2535
2536                 if (atapi_dmadir || atapi_id_dmadir(dev->id)) {
2537                         dev->flags |= ATA_DFLAG_DMADIR;
2538                         dma_dir_string = ", DMADIR";
2539                 }
2540
2541                 /* print device info to dmesg */
2542                 if (ata_msg_drv(ap) && print_info)
2543                         ata_dev_printk(dev, KERN_INFO,
2544                                        "ATAPI: %s, %s, max %s%s%s%s\n",
2545                                        modelbuf, fwrevbuf,
2546                                        ata_mode_string(xfer_mask),
2547                                        cdb_intr_string, atapi_an_string,
2548                                        dma_dir_string);
2549         }
2550
2551         /* determine max_sectors */
2552         dev->max_sectors = ATA_MAX_SECTORS;
2553         if (dev->flags & ATA_DFLAG_LBA48)
2554                 dev->max_sectors = ATA_MAX_SECTORS_LBA48;
2555
2556         if (!(dev->horkage & ATA_HORKAGE_IPM)) {
2557                 if (ata_id_has_hipm(dev->id))
2558                         dev->flags |= ATA_DFLAG_HIPM;
2559                 if (ata_id_has_dipm(dev->id))
2560                         dev->flags |= ATA_DFLAG_DIPM;
2561         }
2562
2563         /* Limit PATA drive on SATA cable bridge transfers to udma5,
2564            200 sectors */
2565         if (ata_dev_knobble(dev)) {
2566                 if (ata_msg_drv(ap) && print_info)
2567                         ata_dev_printk(dev, KERN_INFO,
2568                                        "applying bridge limits\n");
2569                 dev->udma_mask &= ATA_UDMA5;
2570                 dev->max_sectors = ATA_MAX_SECTORS;
2571         }
2572
2573         if ((dev->class == ATA_DEV_ATAPI) &&
2574             (atapi_command_packet_set(id) == TYPE_TAPE)) {
2575                 dev->max_sectors = ATA_MAX_SECTORS_TAPE;
2576                 dev->horkage |= ATA_HORKAGE_STUCK_ERR;
2577         }
2578
2579         if (dev->horkage & ATA_HORKAGE_MAX_SEC_128)
2580                 dev->max_sectors = min_t(unsigned int, ATA_MAX_SECTORS_128,
2581                                          dev->max_sectors);
2582
2583         if (ata_dev_blacklisted(dev) & ATA_HORKAGE_IPM) {
2584                 dev->horkage |= ATA_HORKAGE_IPM;
2585
2586                 /* reset link pm_policy for this port to no pm */
2587                 ap->pm_policy = MAX_PERFORMANCE;
2588         }
2589
2590         if (ap->ops->dev_config)
2591                 ap->ops->dev_config(dev);
2592
2593         if (dev->horkage & ATA_HORKAGE_DIAGNOSTIC) {
2594                 /* Let the user know. We don't want to disallow opens for
2595                    rescue purposes, or in case the vendor is just a blithering
2596                    idiot. Do this after the dev_config call as some controllers
2597                    with buggy firmware may want to avoid reporting false device
2598                    bugs */
2599
2600                 if (print_info) {
2601                         ata_dev_printk(dev, KERN_WARNING,
2602 "Drive reports diagnostics failure. This may indicate a drive\n");
2603                         ata_dev_printk(dev, KERN_WARNING,
2604 "fault or invalid emulation. Contact drive vendor for information.\n");
2605                 }
2606         }
2607
2608         if ((dev->horkage & ATA_HORKAGE_FIRMWARE_WARN) && print_info) {
2609                 ata_dev_printk(dev, KERN_WARNING, "WARNING: device requires "
2610                                "firmware update to be fully functional.\n");
2611                 ata_dev_printk(dev, KERN_WARNING, "         contact the vendor "
2612                                "or visit http://ata.wiki.kernel.org.\n");
2613         }
2614
2615         return 0;
2616
2617 err_out_nosup:
2618         if (ata_msg_probe(ap))
2619                 ata_dev_printk(dev, KERN_DEBUG,
2620                                "%s: EXIT, err\n", __func__);
2621         return rc;
2622 }
2623
2624 /**
2625  *      ata_cable_40wire        -       return 40 wire cable type
2626  *      @ap: port
2627  *
2628  *      Helper method for drivers which want to hardwire 40 wire cable
2629  *      detection.
2630  */
2631
2632 int ata_cable_40wire(struct ata_port *ap)
2633 {
2634         return ATA_CBL_PATA40;
2635 }
2636
2637 /**
2638  *      ata_cable_80wire        -       return 80 wire cable type
2639  *      @ap: port
2640  *
2641  *      Helper method for drivers which want to hardwire 80 wire cable
2642  *      detection.
2643  */
2644
2645 int ata_cable_80wire(struct ata_port *ap)
2646 {
2647         return ATA_CBL_PATA80;
2648 }
2649
2650 /**
2651  *      ata_cable_unknown       -       return unknown PATA cable.
2652  *      @ap: port
2653  *
2654  *      Helper method for drivers which have no PATA cable detection.
2655  */
2656
2657 int ata_cable_unknown(struct ata_port *ap)
2658 {
2659         return ATA_CBL_PATA_UNK;
2660 }
2661
2662 /**
2663  *      ata_cable_ignore        -       return ignored PATA cable.
2664  *      @ap: port
2665  *
2666  *      Helper method for drivers which don't use cable type to limit
2667  *      transfer mode.
2668  */
2669 int ata_cable_ignore(struct ata_port *ap)
2670 {
2671         return ATA_CBL_PATA_IGN;
2672 }
2673
2674 /**
2675  *      ata_cable_sata  -       return SATA cable type
2676  *      @ap: port
2677  *
2678  *      Helper method for drivers which have SATA cables
2679  */
2680
2681 int ata_cable_sata(struct ata_port *ap)
2682 {
2683         return ATA_CBL_SATA;
2684 }
2685
2686 /**
2687  *      ata_bus_probe - Reset and probe ATA bus
2688  *      @ap: Bus to probe
2689  *
2690  *      Master ATA bus probing function.  Initiates a hardware-dependent
2691  *      bus reset, then attempts to identify any devices found on
2692  *      the bus.
2693  *
2694  *      LOCKING:
2695  *      PCI/etc. bus probe sem.
2696  *
2697  *      RETURNS:
2698  *      Zero on success, negative errno otherwise.
2699  */
2700
2701 int ata_bus_probe(struct ata_port *ap)
2702 {
2703         unsigned int classes[ATA_MAX_DEVICES];
2704         int tries[ATA_MAX_DEVICES];
2705         int rc;
2706         struct ata_device *dev;
2707
2708         ata_port_probe(ap);
2709
2710         ata_for_each_dev(dev, &ap->link, ALL)
2711                 tries[dev->devno] = ATA_PROBE_MAX_TRIES;
2712
2713  retry:
2714         ata_for_each_dev(dev, &ap->link, ALL) {
2715                 /* If we issue an SRST then an ATA drive (not ATAPI)
2716                  * may change configuration and be in PIO0 timing. If
2717                  * we do a hard reset (or are coming from power on)
2718                  * this is true for ATA or ATAPI. Until we've set a
2719                  * suitable controller mode we should not touch the
2720                  * bus as we may be talking too fast.
2721                  */
2722                 dev->pio_mode = XFER_PIO_0;
2723
2724                 /* If the controller has a pio mode setup function
2725                  * then use it to set the chipset to rights. Don't
2726                  * touch the DMA setup as that will be dealt with when
2727                  * configuring devices.
2728                  */
2729                 if (ap->ops->set_piomode)
2730                         ap->ops->set_piomode(ap, dev);
2731         }
2732
2733         /* reset and determine device classes */
2734         ap->ops->phy_reset(ap);
2735
2736         ata_for_each_dev(dev, &ap->link, ALL) {
2737                 if (!(ap->flags & ATA_FLAG_DISABLED) &&
2738                     dev->class != ATA_DEV_UNKNOWN)
2739                         classes[dev->devno] = dev->class;
2740                 else
2741                         classes[dev->devno] = ATA_DEV_NONE;
2742
2743                 dev->class = ATA_DEV_UNKNOWN;
2744         }
2745
2746         ata_port_probe(ap);
2747
2748         /* read IDENTIFY page and configure devices. We have to do the identify
2749            specific sequence bass-ackwards so that PDIAG- is released by
2750            the slave device */
2751
2752         ata_for_each_dev(dev, &ap->link, ALL_REVERSE) {
2753                 if (tries[dev->devno])
2754                         dev->class = classes[dev->devno];
2755
2756                 if (!ata_dev_enabled(dev))
2757                         continue;
2758
2759                 rc = ata_dev_read_id(dev, &dev->class, ATA_READID_POSTRESET,
2760                                      dev->id);
2761                 if (rc)
2762                         goto fail;
2763         }
2764
2765         /* Now ask for the cable type as PDIAG- should have been released */
2766         if (ap->ops->cable_detect)
2767                 ap->cbl = ap->ops->cable_detect(ap);
2768
2769         /* We may have SATA bridge glue hiding here irrespective of
2770          * the reported cable types and sensed types.  When SATA
2771          * drives indicate we have a bridge, we don't know which end
2772          * of the link the bridge is which is a problem.
2773          */
2774         ata_for_each_dev(dev, &ap->link, ENABLED)
2775                 if (ata_id_is_sata(dev->id))
2776                         ap->cbl = ATA_CBL_SATA;
2777
2778         /* After the identify sequence we can now set up the devices. We do
2779            this in the normal order so that the user doesn't get confused */
2780
2781         ata_for_each_dev(dev, &ap->link, ENABLED) {
2782                 ap->link.eh_context.i.flags |= ATA_EHI_PRINTINFO;
2783                 rc = ata_dev_configure(dev);
2784                 ap->link.eh_context.i.flags &= ~ATA_EHI_PRINTINFO;
2785                 if (rc)
2786                         goto fail;
2787         }
2788
2789         /* configure transfer mode */
2790         rc = ata_set_mode(&ap->link, &dev);
2791         if (rc)
2792                 goto fail;
2793
2794         ata_for_each_dev(dev, &ap->link, ENABLED)
2795                 return 0;
2796
2797         /* no device present, disable port */
2798         ata_port_disable(ap);
2799         return -ENODEV;
2800
2801  fail:
2802         tries[dev->devno]--;
2803
2804         switch (rc) {
2805         case -EINVAL:
2806                 /* eeek, something went very wrong, give up */
2807                 tries[dev->devno] = 0;
2808                 break;
2809
2810         case -ENODEV:
2811                 /* give it just one more chance */
2812                 tries[dev->devno] = min(tries[dev->devno], 1);
2813         case -EIO:
2814                 if (tries[dev->devno] == 1) {
2815                         /* This is the last chance, better to slow
2816                          * down than lose it.
2817                          */
2818                         sata_down_spd_limit(&ap->link, 0);
2819                         ata_down_xfermask_limit(dev, ATA_DNXFER_PIO);
2820                 }
2821         }
2822
2823         if (!tries[dev->devno])
2824                 ata_dev_disable(dev);
2825
2826         goto retry;
2827 }
2828
2829 /**
2830  *      ata_port_probe - Mark port as enabled
2831  *      @ap: Port for which we indicate enablement
2832  *
2833  *      Modify @ap data structure such that the system
2834  *      thinks that the entire port is enabled.
2835  *
2836  *      LOCKING: host lock, or some other form of
2837  *      serialization.
2838  */
2839
2840 void ata_port_probe(struct ata_port *ap)
2841 {
2842         ap->flags &= ~ATA_FLAG_DISABLED;
2843 }
2844
2845 /**
2846  *      sata_print_link_status - Print SATA link status
2847  *      @link: SATA link to printk link status about
2848  *
2849  *      This function prints link speed and status of a SATA link.
2850  *
2851  *      LOCKING:
2852  *      None.
2853  */
2854 static void sata_print_link_status(struct ata_link *link)
2855 {
2856         u32 sstatus, scontrol, tmp;
2857
2858         if (sata_scr_read(link, SCR_STATUS, &sstatus))
2859                 return;
2860         sata_scr_read(link, SCR_CONTROL, &scontrol);
2861
2862         if (ata_phys_link_online(link)) {
2863                 tmp = (sstatus >> 4) & 0xf;
2864                 ata_link_printk(link, KERN_INFO,
2865                                 "SATA link up %s (SStatus %X SControl %X)\n",
2866                                 sata_spd_string(tmp), sstatus, scontrol);
2867         } else {
2868                 ata_link_printk(link, KERN_INFO,
2869                                 "SATA link down (SStatus %X SControl %X)\n",
2870                                 sstatus, scontrol);
2871         }
2872 }
2873
2874 /**
2875  *      ata_dev_pair            -       return other device on cable
2876  *      @adev: device
2877  *
2878  *      Obtain the other device on the same cable, or if none is
2879  *      present NULL is returned
2880  */
2881
2882 struct ata_device *ata_dev_pair(struct ata_device *adev)
2883 {
2884         struct ata_link *link = adev->link;
2885         struct ata_device *pair = &link->device[1 - adev->devno];
2886         if (!ata_dev_enabled(pair))
2887                 return NULL;
2888         return pair;
2889 }
2890
2891 /**
2892  *      ata_port_disable - Disable port.
2893  *      @ap: Port to be disabled.
2894  *
2895  *      Modify @ap data structure such that the system
2896  *      thinks that the entire port is disabled, and should
2897  *      never attempt to probe or communicate with devices
2898  *      on this port.
2899  *
2900  *      LOCKING: host lock, or some other form of
2901  *      serialization.
2902  */
2903
2904 void ata_port_disable(struct ata_port *ap)
2905 {
2906         ap->link.device[0].class = ATA_DEV_NONE;
2907         ap->link.device[1].class = ATA_DEV_NONE;
2908         ap->flags |= ATA_FLAG_DISABLED;
2909 }
2910
2911 /**
2912  *      sata_down_spd_limit - adjust SATA spd limit downward
2913  *      @link: Link to adjust SATA spd limit for
2914  *      @spd_limit: Additional limit
2915  *
2916  *      Adjust SATA spd limit of @link downward.  Note that this
2917  *      function only adjusts the limit.  The change must be applied
2918  *      using sata_set_spd().
2919  *
2920  *      If @spd_limit is non-zero, the speed is limited to equal to or
2921  *      lower than @spd_limit if such speed is supported.  If
2922  *      @spd_limit is slower than any supported speed, only the lowest
2923  *      supported speed is allowed.
2924  *
2925  *      LOCKING:
2926  *      Inherited from caller.
2927  *
2928  *      RETURNS:
2929  *      0 on success, negative errno on failure
2930  */
2931 int sata_down_spd_limit(struct ata_link *link, u32 spd_limit)
2932 {
2933         u32 sstatus, spd, mask;
2934         int rc, bit;
2935
2936         if (!sata_scr_valid(link))
2937                 return -EOPNOTSUPP;
2938
2939         /* If SCR can be read, use it to determine the current SPD.
2940          * If not, use cached value in link->sata_spd.
2941          */
2942         rc = sata_scr_read(link, SCR_STATUS, &sstatus);
2943         if (rc == 0 && ata_sstatus_online(sstatus))
2944                 spd = (sstatus >> 4) & 0xf;
2945         else
2946                 spd = link->sata_spd;
2947
2948         mask = link->sata_spd_limit;
2949         if (mask <= 1)
2950                 return -EINVAL;
2951
2952         /* unconditionally mask off the highest bit */
2953         bit = fls(mask) - 1;
2954         mask &= ~(1 << bit);
2955
2956         /* Mask off all speeds higher than or equal to the current
2957          * one.  Force 1.5Gbps if current SPD is not available.
2958          */
2959         if (spd > 1)
2960                 mask &= (1 << (spd - 1)) - 1;
2961         else
2962                 mask &= 1;
2963
2964         /* were we already at the bottom? */
2965         if (!mask)
2966                 return -EINVAL;
2967
2968         if (spd_limit) {
2969                 if (mask & ((1 << spd_limit) - 1))
2970                         mask &= (1 << spd_limit) - 1;
2971                 else {
2972                         bit = ffs(mask) - 1;
2973                         mask = 1 << bit;
2974                 }
2975         }
2976
2977         link->sata_spd_limit = mask;
2978
2979         ata_link_printk(link, KERN_WARNING, "limiting SATA link speed to %s\n",
2980                         sata_spd_string(fls(mask)));
2981
2982         return 0;
2983 }
2984
2985 static int __sata_set_spd_needed(struct ata_link *link, u32 *scontrol)
2986 {
2987         struct ata_link *host_link = &link->ap->link;
2988         u32 limit, target, spd;
2989
2990         limit = link->sata_spd_limit;
2991
2992         /* Don't configure downstream link faster than upstream link.
2993          * It doesn't speed up anything and some PMPs choke on such
2994          * configuration.
2995          */
2996         if (!ata_is_host_link(link) && host_link->sata_spd)
2997                 limit &= (1 << host_link->sata_spd) - 1;
2998
2999         if (limit == UINT_MAX)
3000                 target = 0;
3001         else
3002                 target = fls(limit);
3003
3004         spd = (*scontrol >> 4) & 0xf;
3005         *scontrol = (*scontrol & ~0xf0) | ((target & 0xf) << 4);
3006
3007         return spd != target;
3008 }
3009
3010 /**
3011  *      sata_set_spd_needed - is SATA spd configuration needed
3012  *      @link: Link in question
3013  *
3014  *      Test whether the spd limit in SControl matches
3015  *      @link->sata_spd_limit.  This function is used to determine
3016  *      whether hardreset is necessary to apply SATA spd
3017  *      configuration.
3018  *
3019  *      LOCKING:
3020  *      Inherited from caller.
3021  *
3022  *      RETURNS:
3023  *      1 if SATA spd configuration is needed, 0 otherwise.
3024  */
3025 static int sata_set_spd_needed(struct ata_link *link)
3026 {
3027         u32 scontrol;
3028
3029         if (sata_scr_read(link, SCR_CONTROL, &scontrol))
3030                 return 1;
3031
3032         return __sata_set_spd_needed(link, &scontrol);
3033 }
3034
3035 /**
3036  *      sata_set_spd - set SATA spd according to spd limit
3037  *      @link: Link to set SATA spd for
3038  *
3039  *      Set SATA spd of @link according to sata_spd_limit.
3040  *
3041  *      LOCKING:
3042  *      Inherited from caller.
3043  *
3044  *      RETURNS:
3045  *      0 if spd doesn't need to be changed, 1 if spd has been
3046  *      changed.  Negative errno if SCR registers are inaccessible.
3047  */
3048 int sata_set_spd(struct ata_link *link)
3049 {
3050         u32 scontrol;
3051         int rc;
3052
3053         if ((rc = sata_scr_read(link, SCR_CONTROL, &scontrol)))
3054                 return rc;
3055
3056         if (!__sata_set_spd_needed(link, &scontrol))
3057                 return 0;
3058
3059         if ((rc = sata_scr_write(link, SCR_CONTROL, scontrol)))
3060                 return rc;
3061
3062         return 1;
3063 }
3064
3065 /*
3066  * This mode timing computation functionality is ported over from
3067  * drivers/ide/ide-timing.h and was originally written by Vojtech Pavlik
3068  */
3069 /*
3070  * PIO 0-4, MWDMA 0-2 and UDMA 0-6 timings (in nanoseconds).
3071  * These were taken from ATA/ATAPI-6 standard, rev 0a, except
3072  * for UDMA6, which is currently supported only by Maxtor drives.
3073  *
3074  * For PIO 5/6 MWDMA 3/4 see the CFA specification 3.0.
3075  */
3076
3077 static const struct ata_timing ata_timing[] = {
3078 /*      { XFER_PIO_SLOW, 120, 290, 240, 960, 290, 240, 0,  960,   0 }, */
3079         { XFER_PIO_0,     70, 290, 240, 600, 165, 150, 0,  600,   0 },
3080         { XFER_PIO_1,     50, 290,  93, 383, 125, 100, 0,  383,   0 },
3081         { XFER_PIO_2,     30, 290,  40, 330, 100,  90, 0,  240,   0 },
3082         { XFER_PIO_3,     30,  80,  70, 180,  80,  70, 0,  180,   0 },
3083         { XFER_PIO_4,     25,  70,  25, 120,  70,  25, 0,  120,   0 },
3084         { XFER_PIO_5,     15,  65,  25, 100,  65,  25, 0,  100,   0 },
3085         { XFER_PIO_6,     10,  55,  20,  80,  55,  20, 0,   80,   0 },
3086
3087         { XFER_SW_DMA_0, 120,   0,   0,   0, 480, 480, 50, 960,   0 },
3088         { XFER_SW_DMA_1,  90,   0,   0,   0, 240, 240, 30, 480,   0 },
3089         { XFER_SW_DMA_2,  60,   0,   0,   0, 120, 120, 20, 240,   0 },
3090
3091         { XFER_MW_DMA_0,  60,   0,   0,   0, 215, 215, 20, 480,   0 },
3092         { XFER_MW_DMA_1,  45,   0,   0,   0,  80,  50, 5,  150,   0 },
3093         { XFER_MW_DMA_2,  25,   0,   0,   0,  70,  25, 5,  120,   0 },
3094         { XFER_MW_DMA_3,  25,   0,   0,   0,  65,  25, 5,  100,   0 },
3095         { XFER_MW_DMA_4,  25,   0,   0,   0,  55,  20, 5,   80,   0 },
3096
3097 /*      { XFER_UDMA_SLOW,  0,   0,   0,   0,   0,   0, 0,    0, 150 }, */
3098         { XFER_UDMA_0,     0,   0,   0,   0,   0,   0, 0,    0, 120 },
3099         { XFER_UDMA_1,     0,   0,   0,   0,   0,   0, 0,    0,  80 },
3100         { XFER_UDMA_2,     0,   0,   0,   0,   0,   0, 0,    0,  60 },
3101         { XFER_UDMA_3,     0,   0,   0,   0,   0,   0, 0,    0,  45 },
3102         { XFER_UDMA_4,     0,   0,   0,   0,   0,   0, 0,    0,  30 },
3103         { XFER_UDMA_5,     0,   0,   0,   0,   0,   0, 0,    0,  20 },
3104         { XFER_UDMA_6,     0,   0,   0,   0,   0,   0, 0,    0,  15 },
3105
3106         { 0xFF }
3107 };
3108
3109 #define ENOUGH(v, unit)         (((v)-1)/(unit)+1)
3110 #define EZ(v, unit)             ((v)?ENOUGH(v, unit):0)
3111
3112 static void ata_timing_quantize(const struct ata_timing *t, struct ata_timing *q, int T, int UT)
3113 {
3114         q->setup        = EZ(t->setup      * 1000,  T);
3115         q->act8b        = EZ(t->act8b      * 1000,  T);
3116         q->rec8b        = EZ(t->rec8b      * 1000,  T);
3117         q->cyc8b        = EZ(t->cyc8b      * 1000,  T);
3118         q->active       = EZ(t->active     * 1000,  T);
3119         q->recover      = EZ(t->recover    * 1000,  T);
3120         q->dmack_hold   = EZ(t->dmack_hold * 1000,  T);
3121         q->cycle        = EZ(t->cycle      * 1000,  T);
3122         q->udma         = EZ(t->udma       * 1000, UT);
3123 }
3124
3125 void ata_timing_merge(const struct ata_timing *a, const struct ata_timing *b,
3126                       struct ata_timing *m, unsigned int what)
3127 {
3128         if (what & ATA_TIMING_SETUP  ) m->setup   = max(a->setup,   b->setup);
3129         if (what & ATA_TIMING_ACT8B  ) m->act8b   = max(a->act8b,   b->act8b);
3130         if (what & ATA_TIMING_REC8B  ) m->rec8b   = max(a->rec8b,   b->rec8b);
3131         if (what & ATA_TIMING_CYC8B  ) m->cyc8b   = max(a->cyc8b,   b->cyc8b);
3132         if (what & ATA_TIMING_ACTIVE ) m->active  = max(a->active,  b->active);
3133         if (what & ATA_TIMING_RECOVER) m->recover = max(a->recover, b->recover);
3134         if (what & ATA_TIMING_DMACK_HOLD) m->dmack_hold = max(a->dmack_hold, b->dmack_hold);
3135         if (what & ATA_TIMING_CYCLE  ) m->cycle   = max(a->cycle,   b->cycle);
3136         if (what & ATA_TIMING_UDMA   ) m->udma    = max(a->udma,    b->udma);
3137 }
3138
3139 const struct ata_timing *ata_timing_find_mode(u8 xfer_mode)
3140 {
3141         const struct ata_timing *t = ata_timing;
3142
3143         while (xfer_mode > t->mode)
3144                 t++;
3145
3146         if (xfer_mode == t->mode)
3147                 return t;
3148         return NULL;
3149 }
3150
3151 int ata_timing_compute(struct ata_device *adev, unsigned short speed,
3152                        struct ata_timing *t, int T, int UT)
3153 {
3154         const struct ata_timing *s;
3155         struct ata_timing p;
3156
3157         /*
3158          * Find the mode.
3159          */
3160
3161         if (!(s = ata_timing_find_mode(speed)))
3162                 return -EINVAL;
3163
3164         memcpy(t, s, sizeof(*s));
3165
3166         /*
3167          * If the drive is an EIDE drive, it can tell us it needs extended
3168          * PIO/MW_DMA cycle timing.
3169          */
3170
3171         if (adev->id[ATA_ID_FIELD_VALID] & 2) { /* EIDE drive */
3172                 memset(&p, 0, sizeof(p));
3173                 if (speed >= XFER_PIO_0 && speed <= XFER_SW_DMA_0) {
3174                         if (speed <= XFER_PIO_2) p.cycle = p.cyc8b = adev->id[ATA_ID_EIDE_PIO];
3175                                             else p.cycle = p.cyc8b = adev->id[ATA_ID_EIDE_PIO_IORDY];
3176                 } else if (speed >= XFER_MW_DMA_0 && speed <= XFER_MW_DMA_2) {
3177                         p.cycle = adev->id[ATA_ID_EIDE_DMA_MIN];
3178                 }
3179                 ata_timing_merge(&p, t, t, ATA_TIMING_CYCLE | ATA_TIMING_CYC8B);
3180         }
3181
3182         /*
3183          * Convert the timing to bus clock counts.
3184          */
3185
3186         ata_timing_quantize(t, t, T, UT);
3187
3188         /*
3189          * Even in DMA/UDMA modes we still use PIO access for IDENTIFY,
3190          * S.M.A.R.T * and some other commands. We have to ensure that the
3191          * DMA cycle timing is slower/equal than the fastest PIO timing.
3192          */
3193
3194         if (speed > XFER_PIO_6) {
3195                 ata_timing_compute(adev, adev->pio_mode, &p, T, UT);
3196                 ata_timing_merge(&p, t, t, ATA_TIMING_ALL);
3197         }
3198
3199         /*
3200          * Lengthen active & recovery time so that cycle time is correct.
3201          */
3202
3203         if (t->act8b + t->rec8b < t->cyc8b) {
3204                 t->act8b += (t->cyc8b - (t->act8b + t->rec8b)) / 2;
3205                 t->rec8b = t->cyc8b - t->act8b;
3206         }
3207
3208         if (t->active + t->recover < t->cycle) {
3209                 t->active += (t->cycle - (t->active + t->recover)) / 2;
3210                 t->recover = t->cycle - t->active;
3211         }
3212
3213         /* In a few cases quantisation may produce enough errors to