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