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