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