Merge ../linux-2.6/
[sfrench/cifs-2.6.git] / drivers / scsi / 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  */
34
35 #include <linux/config.h>
36 #include <linux/kernel.h>
37 #include <linux/module.h>
38 #include <linux/pci.h>
39 #include <linux/init.h>
40 #include <linux/list.h>
41 #include <linux/mm.h>
42 #include <linux/highmem.h>
43 #include <linux/spinlock.h>
44 #include <linux/blkdev.h>
45 #include <linux/delay.h>
46 #include <linux/timer.h>
47 #include <linux/interrupt.h>
48 #include <linux/completion.h>
49 #include <linux/suspend.h>
50 #include <linux/workqueue.h>
51 #include <linux/jiffies.h>
52 #include <linux/scatterlist.h>
53 #include <scsi/scsi.h>
54 #include "scsi_priv.h"
55 #include <scsi/scsi_cmnd.h>
56 #include <scsi/scsi_host.h>
57 #include <linux/libata.h>
58 #include <asm/io.h>
59 #include <asm/semaphore.h>
60 #include <asm/byteorder.h>
61
62 #include "libata.h"
63
64 /* debounce timing parameters in msecs { interval, duration, timeout } */
65 const unsigned long sata_deb_timing_boot[]              = {   5,  100, 2000 };
66 const unsigned long sata_deb_timing_eh[]                = {  25,  500, 2000 };
67 const unsigned long sata_deb_timing_before_fsrst[]      = { 100, 2000, 5000 };
68
69 static unsigned int ata_dev_init_params(struct ata_device *dev,
70                                         u16 heads, u16 sectors);
71 static unsigned int ata_dev_set_xfermode(struct ata_device *dev);
72 static void ata_dev_xfermask(struct ata_device *dev);
73
74 static unsigned int ata_unique_id = 1;
75 static struct workqueue_struct *ata_wq;
76
77 struct workqueue_struct *ata_aux_wq;
78
79 int atapi_enabled = 1;
80 module_param(atapi_enabled, int, 0444);
81 MODULE_PARM_DESC(atapi_enabled, "Enable discovery of ATAPI devices (0=off, 1=on)");
82
83 int atapi_dmadir = 0;
84 module_param(atapi_dmadir, int, 0444);
85 MODULE_PARM_DESC(atapi_dmadir, "Enable ATAPI DMADIR bridge support (0=off, 1=on)");
86
87 int libata_fua = 0;
88 module_param_named(fua, libata_fua, int, 0444);
89 MODULE_PARM_DESC(fua, "FUA support (0=off, 1=on)");
90
91 static int ata_probe_timeout = ATA_TMOUT_INTERNAL / HZ;
92 module_param(ata_probe_timeout, int, 0444);
93 MODULE_PARM_DESC(ata_probe_timeout, "Set ATA probing timeout (seconds)");
94
95 MODULE_AUTHOR("Jeff Garzik");
96 MODULE_DESCRIPTION("Library module for ATA devices");
97 MODULE_LICENSE("GPL");
98 MODULE_VERSION(DRV_VERSION);
99
100
101 /**
102  *      ata_tf_to_fis - Convert ATA taskfile to SATA FIS structure
103  *      @tf: Taskfile to convert
104  *      @fis: Buffer into which data will output
105  *      @pmp: Port multiplier port
106  *
107  *      Converts a standard ATA taskfile to a Serial ATA
108  *      FIS structure (Register - Host to Device).
109  *
110  *      LOCKING:
111  *      Inherited from caller.
112  */
113
114 void ata_tf_to_fis(const struct ata_taskfile *tf, u8 *fis, u8 pmp)
115 {
116         fis[0] = 0x27;  /* Register - Host to Device FIS */
117         fis[1] = (pmp & 0xf) | (1 << 7); /* Port multiplier number,
118                                             bit 7 indicates Command FIS */
119         fis[2] = tf->command;
120         fis[3] = tf->feature;
121
122         fis[4] = tf->lbal;
123         fis[5] = tf->lbam;
124         fis[6] = tf->lbah;
125         fis[7] = tf->device;
126
127         fis[8] = tf->hob_lbal;
128         fis[9] = tf->hob_lbam;
129         fis[10] = tf->hob_lbah;
130         fis[11] = tf->hob_feature;
131
132         fis[12] = tf->nsect;
133         fis[13] = tf->hob_nsect;
134         fis[14] = 0;
135         fis[15] = tf->ctl;
136
137         fis[16] = 0;
138         fis[17] = 0;
139         fis[18] = 0;
140         fis[19] = 0;
141 }
142
143 /**
144  *      ata_tf_from_fis - Convert SATA FIS to ATA taskfile
145  *      @fis: Buffer from which data will be input
146  *      @tf: Taskfile to output
147  *
148  *      Converts a serial ATA FIS structure to a standard ATA taskfile.
149  *
150  *      LOCKING:
151  *      Inherited from caller.
152  */
153
154 void ata_tf_from_fis(const u8 *fis, struct ata_taskfile *tf)
155 {
156         tf->command     = fis[2];       /* status */
157         tf->feature     = fis[3];       /* error */
158
159         tf->lbal        = fis[4];
160         tf->lbam        = fis[5];
161         tf->lbah        = fis[6];
162         tf->device      = fis[7];
163
164         tf->hob_lbal    = fis[8];
165         tf->hob_lbam    = fis[9];
166         tf->hob_lbah    = fis[10];
167
168         tf->nsect       = fis[12];
169         tf->hob_nsect   = fis[13];
170 }
171
172 static const u8 ata_rw_cmds[] = {
173         /* pio multi */
174         ATA_CMD_READ_MULTI,
175         ATA_CMD_WRITE_MULTI,
176         ATA_CMD_READ_MULTI_EXT,
177         ATA_CMD_WRITE_MULTI_EXT,
178         0,
179         0,
180         0,
181         ATA_CMD_WRITE_MULTI_FUA_EXT,
182         /* pio */
183         ATA_CMD_PIO_READ,
184         ATA_CMD_PIO_WRITE,
185         ATA_CMD_PIO_READ_EXT,
186         ATA_CMD_PIO_WRITE_EXT,
187         0,
188         0,
189         0,
190         0,
191         /* dma */
192         ATA_CMD_READ,
193         ATA_CMD_WRITE,
194         ATA_CMD_READ_EXT,
195         ATA_CMD_WRITE_EXT,
196         0,
197         0,
198         0,
199         ATA_CMD_WRITE_FUA_EXT
200 };
201
202 /**
203  *      ata_rwcmd_protocol - set taskfile r/w commands and protocol
204  *      @qc: command to examine and configure
205  *
206  *      Examine the device configuration and tf->flags to calculate
207  *      the proper read/write commands and protocol to use.
208  *
209  *      LOCKING:
210  *      caller.
211  */
212 int ata_rwcmd_protocol(struct ata_queued_cmd *qc)
213 {
214         struct ata_taskfile *tf = &qc->tf;
215         struct ata_device *dev = qc->dev;
216         u8 cmd;
217
218         int index, fua, lba48, write;
219
220         fua = (tf->flags & ATA_TFLAG_FUA) ? 4 : 0;
221         lba48 = (tf->flags & ATA_TFLAG_LBA48) ? 2 : 0;
222         write = (tf->flags & ATA_TFLAG_WRITE) ? 1 : 0;
223
224         if (dev->flags & ATA_DFLAG_PIO) {
225                 tf->protocol = ATA_PROT_PIO;
226                 index = dev->multi_count ? 0 : 8;
227         } else if (lba48 && (qc->ap->flags & ATA_FLAG_PIO_LBA48)) {
228                 /* Unable to use DMA due to host limitation */
229                 tf->protocol = ATA_PROT_PIO;
230                 index = dev->multi_count ? 0 : 8;
231         } else {
232                 tf->protocol = ATA_PROT_DMA;
233                 index = 16;
234         }
235
236         cmd = ata_rw_cmds[index + fua + lba48 + write];
237         if (cmd) {
238                 tf->command = cmd;
239                 return 0;
240         }
241         return -1;
242 }
243
244 /**
245  *      ata_pack_xfermask - Pack pio, mwdma and udma masks into xfer_mask
246  *      @pio_mask: pio_mask
247  *      @mwdma_mask: mwdma_mask
248  *      @udma_mask: udma_mask
249  *
250  *      Pack @pio_mask, @mwdma_mask and @udma_mask into a single
251  *      unsigned int xfer_mask.
252  *
253  *      LOCKING:
254  *      None.
255  *
256  *      RETURNS:
257  *      Packed xfer_mask.
258  */
259 static unsigned int ata_pack_xfermask(unsigned int pio_mask,
260                                       unsigned int mwdma_mask,
261                                       unsigned int udma_mask)
262 {
263         return ((pio_mask << ATA_SHIFT_PIO) & ATA_MASK_PIO) |
264                 ((mwdma_mask << ATA_SHIFT_MWDMA) & ATA_MASK_MWDMA) |
265                 ((udma_mask << ATA_SHIFT_UDMA) & ATA_MASK_UDMA);
266 }
267
268 /**
269  *      ata_unpack_xfermask - Unpack xfer_mask into pio, mwdma and udma masks
270  *      @xfer_mask: xfer_mask to unpack
271  *      @pio_mask: resulting pio_mask
272  *      @mwdma_mask: resulting mwdma_mask
273  *      @udma_mask: resulting udma_mask
274  *
275  *      Unpack @xfer_mask into @pio_mask, @mwdma_mask and @udma_mask.
276  *      Any NULL distination masks will be ignored.
277  */
278 static void ata_unpack_xfermask(unsigned int xfer_mask,
279                                 unsigned int *pio_mask,
280                                 unsigned int *mwdma_mask,
281                                 unsigned int *udma_mask)
282 {
283         if (pio_mask)
284                 *pio_mask = (xfer_mask & ATA_MASK_PIO) >> ATA_SHIFT_PIO;
285         if (mwdma_mask)
286                 *mwdma_mask = (xfer_mask & ATA_MASK_MWDMA) >> ATA_SHIFT_MWDMA;
287         if (udma_mask)
288                 *udma_mask = (xfer_mask & ATA_MASK_UDMA) >> ATA_SHIFT_UDMA;
289 }
290
291 static const struct ata_xfer_ent {
292         int shift, bits;
293         u8 base;
294 } ata_xfer_tbl[] = {
295         { ATA_SHIFT_PIO, ATA_BITS_PIO, XFER_PIO_0 },
296         { ATA_SHIFT_MWDMA, ATA_BITS_MWDMA, XFER_MW_DMA_0 },
297         { ATA_SHIFT_UDMA, ATA_BITS_UDMA, XFER_UDMA_0 },
298         { -1, },
299 };
300
301 /**
302  *      ata_xfer_mask2mode - Find matching XFER_* for the given xfer_mask
303  *      @xfer_mask: xfer_mask of interest
304  *
305  *      Return matching XFER_* value for @xfer_mask.  Only the highest
306  *      bit of @xfer_mask is considered.
307  *
308  *      LOCKING:
309  *      None.
310  *
311  *      RETURNS:
312  *      Matching XFER_* value, 0 if no match found.
313  */
314 static u8 ata_xfer_mask2mode(unsigned int xfer_mask)
315 {
316         int highbit = fls(xfer_mask) - 1;
317         const struct ata_xfer_ent *ent;
318
319         for (ent = ata_xfer_tbl; ent->shift >= 0; ent++)
320                 if (highbit >= ent->shift && highbit < ent->shift + ent->bits)
321                         return ent->base + highbit - ent->shift;
322         return 0;
323 }
324
325 /**
326  *      ata_xfer_mode2mask - Find matching xfer_mask for XFER_*
327  *      @xfer_mode: XFER_* of interest
328  *
329  *      Return matching xfer_mask for @xfer_mode.
330  *
331  *      LOCKING:
332  *      None.
333  *
334  *      RETURNS:
335  *      Matching xfer_mask, 0 if no match found.
336  */
337 static unsigned int ata_xfer_mode2mask(u8 xfer_mode)
338 {
339         const struct ata_xfer_ent *ent;
340
341         for (ent = ata_xfer_tbl; ent->shift >= 0; ent++)
342                 if (xfer_mode >= ent->base && xfer_mode < ent->base + ent->bits)
343                         return 1 << (ent->shift + xfer_mode - ent->base);
344         return 0;
345 }
346
347 /**
348  *      ata_xfer_mode2shift - Find matching xfer_shift for XFER_*
349  *      @xfer_mode: XFER_* of interest
350  *
351  *      Return matching xfer_shift for @xfer_mode.
352  *
353  *      LOCKING:
354  *      None.
355  *
356  *      RETURNS:
357  *      Matching xfer_shift, -1 if no match found.
358  */
359 static int ata_xfer_mode2shift(unsigned int xfer_mode)
360 {
361         const struct ata_xfer_ent *ent;
362
363         for (ent = ata_xfer_tbl; ent->shift >= 0; ent++)
364                 if (xfer_mode >= ent->base && xfer_mode < ent->base + ent->bits)
365                         return ent->shift;
366         return -1;
367 }
368
369 /**
370  *      ata_mode_string - convert xfer_mask to string
371  *      @xfer_mask: mask of bits supported; only highest bit counts.
372  *
373  *      Determine string which represents the highest speed
374  *      (highest bit in @modemask).
375  *
376  *      LOCKING:
377  *      None.
378  *
379  *      RETURNS:
380  *      Constant C string representing highest speed listed in
381  *      @mode_mask, or the constant C string "<n/a>".
382  */
383 static const char *ata_mode_string(unsigned int xfer_mask)
384 {
385         static const char * const xfer_mode_str[] = {
386                 "PIO0",
387                 "PIO1",
388                 "PIO2",
389                 "PIO3",
390                 "PIO4",
391                 "MWDMA0",
392                 "MWDMA1",
393                 "MWDMA2",
394                 "UDMA/16",
395                 "UDMA/25",
396                 "UDMA/33",
397                 "UDMA/44",
398                 "UDMA/66",
399                 "UDMA/100",
400                 "UDMA/133",
401                 "UDMA7",
402         };
403         int highbit;
404
405         highbit = fls(xfer_mask) - 1;
406         if (highbit >= 0 && highbit < ARRAY_SIZE(xfer_mode_str))
407                 return xfer_mode_str[highbit];
408         return "<n/a>";
409 }
410
411 static const char *sata_spd_string(unsigned int spd)
412 {
413         static const char * const spd_str[] = {
414                 "1.5 Gbps",
415                 "3.0 Gbps",
416         };
417
418         if (spd == 0 || (spd - 1) >= ARRAY_SIZE(spd_str))
419                 return "<unknown>";
420         return spd_str[spd - 1];
421 }
422
423 void ata_dev_disable(struct ata_device *dev)
424 {
425         if (ata_dev_enabled(dev) && ata_msg_drv(dev->ap)) {
426                 ata_dev_printk(dev, KERN_WARNING, "disabled\n");
427                 dev->class++;
428         }
429 }
430
431 /**
432  *      ata_pio_devchk - PATA device presence detection
433  *      @ap: ATA channel to examine
434  *      @device: Device to examine (starting at zero)
435  *
436  *      This technique was originally described in
437  *      Hale Landis's ATADRVR (www.ata-atapi.com), and
438  *      later found its way into the ATA/ATAPI spec.
439  *
440  *      Write a pattern to the ATA shadow registers,
441  *      and if a device is present, it will respond by
442  *      correctly storing and echoing back the
443  *      ATA shadow register contents.
444  *
445  *      LOCKING:
446  *      caller.
447  */
448
449 static unsigned int ata_pio_devchk(struct ata_port *ap,
450                                    unsigned int device)
451 {
452         struct ata_ioports *ioaddr = &ap->ioaddr;
453         u8 nsect, lbal;
454
455         ap->ops->dev_select(ap, device);
456
457         outb(0x55, ioaddr->nsect_addr);
458         outb(0xaa, ioaddr->lbal_addr);
459
460         outb(0xaa, ioaddr->nsect_addr);
461         outb(0x55, ioaddr->lbal_addr);
462
463         outb(0x55, ioaddr->nsect_addr);
464         outb(0xaa, ioaddr->lbal_addr);
465
466         nsect = inb(ioaddr->nsect_addr);
467         lbal = inb(ioaddr->lbal_addr);
468
469         if ((nsect == 0x55) && (lbal == 0xaa))
470                 return 1;       /* we found a device */
471
472         return 0;               /* nothing found */
473 }
474
475 /**
476  *      ata_mmio_devchk - PATA device presence detection
477  *      @ap: ATA channel to examine
478  *      @device: Device to examine (starting at zero)
479  *
480  *      This technique was originally described in
481  *      Hale Landis's ATADRVR (www.ata-atapi.com), and
482  *      later found its way into the ATA/ATAPI spec.
483  *
484  *      Write a pattern to the ATA shadow registers,
485  *      and if a device is present, it will respond by
486  *      correctly storing and echoing back the
487  *      ATA shadow register contents.
488  *
489  *      LOCKING:
490  *      caller.
491  */
492
493 static unsigned int ata_mmio_devchk(struct ata_port *ap,
494                                     unsigned int device)
495 {
496         struct ata_ioports *ioaddr = &ap->ioaddr;
497         u8 nsect, lbal;
498
499         ap->ops->dev_select(ap, device);
500
501         writeb(0x55, (void __iomem *) ioaddr->nsect_addr);
502         writeb(0xaa, (void __iomem *) ioaddr->lbal_addr);
503
504         writeb(0xaa, (void __iomem *) ioaddr->nsect_addr);
505         writeb(0x55, (void __iomem *) ioaddr->lbal_addr);
506
507         writeb(0x55, (void __iomem *) ioaddr->nsect_addr);
508         writeb(0xaa, (void __iomem *) ioaddr->lbal_addr);
509
510         nsect = readb((void __iomem *) ioaddr->nsect_addr);
511         lbal = readb((void __iomem *) ioaddr->lbal_addr);
512
513         if ((nsect == 0x55) && (lbal == 0xaa))
514                 return 1;       /* we found a device */
515
516         return 0;               /* nothing found */
517 }
518
519 /**
520  *      ata_devchk - PATA device presence detection
521  *      @ap: ATA channel to examine
522  *      @device: Device to examine (starting at zero)
523  *
524  *      Dispatch ATA device presence detection, depending
525  *      on whether we are using PIO or MMIO to talk to the
526  *      ATA shadow registers.
527  *
528  *      LOCKING:
529  *      caller.
530  */
531
532 static unsigned int ata_devchk(struct ata_port *ap,
533                                     unsigned int device)
534 {
535         if (ap->flags & ATA_FLAG_MMIO)
536                 return ata_mmio_devchk(ap, device);
537         return ata_pio_devchk(ap, device);
538 }
539
540 /**
541  *      ata_dev_classify - determine device type based on ATA-spec signature
542  *      @tf: ATA taskfile register set for device to be identified
543  *
544  *      Determine from taskfile register contents whether a device is
545  *      ATA or ATAPI, as per "Signature and persistence" section
546  *      of ATA/PI spec (volume 1, sect 5.14).
547  *
548  *      LOCKING:
549  *      None.
550  *
551  *      RETURNS:
552  *      Device type, %ATA_DEV_ATA, %ATA_DEV_ATAPI, or %ATA_DEV_UNKNOWN
553  *      the event of failure.
554  */
555
556 unsigned int ata_dev_classify(const struct ata_taskfile *tf)
557 {
558         /* Apple's open source Darwin code hints that some devices only
559          * put a proper signature into the LBA mid/high registers,
560          * So, we only check those.  It's sufficient for uniqueness.
561          */
562
563         if (((tf->lbam == 0) && (tf->lbah == 0)) ||
564             ((tf->lbam == 0x3c) && (tf->lbah == 0xc3))) {
565                 DPRINTK("found ATA device by sig\n");
566                 return ATA_DEV_ATA;
567         }
568
569         if (((tf->lbam == 0x14) && (tf->lbah == 0xeb)) ||
570             ((tf->lbam == 0x69) && (tf->lbah == 0x96))) {
571                 DPRINTK("found ATAPI device by sig\n");
572                 return ATA_DEV_ATAPI;
573         }
574
575         DPRINTK("unknown device\n");
576         return ATA_DEV_UNKNOWN;
577 }
578
579 /**
580  *      ata_dev_try_classify - Parse returned ATA device signature
581  *      @ap: ATA channel to examine
582  *      @device: Device to examine (starting at zero)
583  *      @r_err: Value of error register on completion
584  *
585  *      After an event -- SRST, E.D.D., or SATA COMRESET -- occurs,
586  *      an ATA/ATAPI-defined set of values is placed in the ATA
587  *      shadow registers, indicating the results of device detection
588  *      and diagnostics.
589  *
590  *      Select the ATA device, and read the values from the ATA shadow
591  *      registers.  Then parse according to the Error register value,
592  *      and the spec-defined values examined by ata_dev_classify().
593  *
594  *      LOCKING:
595  *      caller.
596  *
597  *      RETURNS:
598  *      Device type - %ATA_DEV_ATA, %ATA_DEV_ATAPI or %ATA_DEV_NONE.
599  */
600
601 static unsigned int
602 ata_dev_try_classify(struct ata_port *ap, unsigned int device, u8 *r_err)
603 {
604         struct ata_taskfile tf;
605         unsigned int class;
606         u8 err;
607
608         ap->ops->dev_select(ap, device);
609
610         memset(&tf, 0, sizeof(tf));
611
612         ap->ops->tf_read(ap, &tf);
613         err = tf.feature;
614         if (r_err)
615                 *r_err = err;
616
617         /* see if device passed diags */
618         if (err == 1)
619                 /* do nothing */ ;
620         else if ((device == 0) && (err == 0x81))
621                 /* do nothing */ ;
622         else
623                 return ATA_DEV_NONE;
624
625         /* determine if device is ATA or ATAPI */
626         class = ata_dev_classify(&tf);
627
628         if (class == ATA_DEV_UNKNOWN)
629                 return ATA_DEV_NONE;
630         if ((class == ATA_DEV_ATA) && (ata_chk_status(ap) == 0))
631                 return ATA_DEV_NONE;
632         return class;
633 }
634
635 /**
636  *      ata_id_string - Convert IDENTIFY DEVICE page into string
637  *      @id: IDENTIFY DEVICE results we will examine
638  *      @s: string into which data is output
639  *      @ofs: offset into identify device page
640  *      @len: length of string to return. must be an even number.
641  *
642  *      The strings in the IDENTIFY DEVICE page are broken up into
643  *      16-bit chunks.  Run through the string, and output each
644  *      8-bit chunk linearly, regardless of platform.
645  *
646  *      LOCKING:
647  *      caller.
648  */
649
650 void ata_id_string(const u16 *id, unsigned char *s,
651                    unsigned int ofs, unsigned int len)
652 {
653         unsigned int c;
654
655         while (len > 0) {
656                 c = id[ofs] >> 8;
657                 *s = c;
658                 s++;
659
660                 c = id[ofs] & 0xff;
661                 *s = c;
662                 s++;
663
664                 ofs++;
665                 len -= 2;
666         }
667 }
668
669 /**
670  *      ata_id_c_string - Convert IDENTIFY DEVICE page into C string
671  *      @id: IDENTIFY DEVICE results we will examine
672  *      @s: string into which data is output
673  *      @ofs: offset into identify device page
674  *      @len: length of string to return. must be an odd number.
675  *
676  *      This function is identical to ata_id_string except that it
677  *      trims trailing spaces and terminates the resulting string with
678  *      null.  @len must be actual maximum length (even number) + 1.
679  *
680  *      LOCKING:
681  *      caller.
682  */
683 void ata_id_c_string(const u16 *id, unsigned char *s,
684                      unsigned int ofs, unsigned int len)
685 {
686         unsigned char *p;
687
688         WARN_ON(!(len & 1));
689
690         ata_id_string(id, s, ofs, len - 1);
691
692         p = s + strnlen(s, len - 1);
693         while (p > s && p[-1] == ' ')
694                 p--;
695         *p = '\0';
696 }
697
698 static u64 ata_id_n_sectors(const u16 *id)
699 {
700         if (ata_id_has_lba(id)) {
701                 if (ata_id_has_lba48(id))
702                         return ata_id_u64(id, 100);
703                 else
704                         return ata_id_u32(id, 60);
705         } else {
706                 if (ata_id_current_chs_valid(id))
707                         return ata_id_u32(id, 57);
708                 else
709                         return id[1] * id[3] * id[6];
710         }
711 }
712
713 /**
714  *      ata_noop_dev_select - Select device 0/1 on ATA bus
715  *      @ap: ATA channel to manipulate
716  *      @device: ATA device (numbered from zero) to select
717  *
718  *      This function performs no actual function.
719  *
720  *      May be used as the dev_select() entry in ata_port_operations.
721  *
722  *      LOCKING:
723  *      caller.
724  */
725 void ata_noop_dev_select (struct ata_port *ap, unsigned int device)
726 {
727 }
728
729
730 /**
731  *      ata_std_dev_select - Select device 0/1 on ATA bus
732  *      @ap: ATA channel to manipulate
733  *      @device: ATA device (numbered from zero) to select
734  *
735  *      Use the method defined in the ATA specification to
736  *      make either device 0, or device 1, active on the
737  *      ATA channel.  Works with both PIO and MMIO.
738  *
739  *      May be used as the dev_select() entry in ata_port_operations.
740  *
741  *      LOCKING:
742  *      caller.
743  */
744
745 void ata_std_dev_select (struct ata_port *ap, unsigned int device)
746 {
747         u8 tmp;
748
749         if (device == 0)
750                 tmp = ATA_DEVICE_OBS;
751         else
752                 tmp = ATA_DEVICE_OBS | ATA_DEV1;
753
754         if (ap->flags & ATA_FLAG_MMIO) {
755                 writeb(tmp, (void __iomem *) ap->ioaddr.device_addr);
756         } else {
757                 outb(tmp, ap->ioaddr.device_addr);
758         }
759         ata_pause(ap);          /* needed; also flushes, for mmio */
760 }
761
762 /**
763  *      ata_dev_select - Select device 0/1 on ATA bus
764  *      @ap: ATA channel to manipulate
765  *      @device: ATA device (numbered from zero) to select
766  *      @wait: non-zero to wait for Status register BSY bit to clear
767  *      @can_sleep: non-zero if context allows sleeping
768  *
769  *      Use the method defined in the ATA specification to
770  *      make either device 0, or device 1, active on the
771  *      ATA channel.
772  *
773  *      This is a high-level version of ata_std_dev_select(),
774  *      which additionally provides the services of inserting
775  *      the proper pauses and status polling, where needed.
776  *
777  *      LOCKING:
778  *      caller.
779  */
780
781 void ata_dev_select(struct ata_port *ap, unsigned int device,
782                            unsigned int wait, unsigned int can_sleep)
783 {
784         if (ata_msg_probe(ap))
785                 ata_port_printk(ap, KERN_INFO, "ata_dev_select: ENTER, ata%u: "
786                                 "device %u, wait %u\n", ap->id, device, wait);
787
788         if (wait)
789                 ata_wait_idle(ap);
790
791         ap->ops->dev_select(ap, device);
792
793         if (wait) {
794                 if (can_sleep && ap->device[device].class == ATA_DEV_ATAPI)
795                         msleep(150);
796                 ata_wait_idle(ap);
797         }
798 }
799
800 /**
801  *      ata_dump_id - IDENTIFY DEVICE info debugging output
802  *      @id: IDENTIFY DEVICE page to dump
803  *
804  *      Dump selected 16-bit words from the given IDENTIFY DEVICE
805  *      page.
806  *
807  *      LOCKING:
808  *      caller.
809  */
810
811 static inline void ata_dump_id(const u16 *id)
812 {
813         DPRINTK("49==0x%04x  "
814                 "53==0x%04x  "
815                 "63==0x%04x  "
816                 "64==0x%04x  "
817                 "75==0x%04x  \n",
818                 id[49],
819                 id[53],
820                 id[63],
821                 id[64],
822                 id[75]);
823         DPRINTK("80==0x%04x  "
824                 "81==0x%04x  "
825                 "82==0x%04x  "
826                 "83==0x%04x  "
827                 "84==0x%04x  \n",
828                 id[80],
829                 id[81],
830                 id[82],
831                 id[83],
832                 id[84]);
833         DPRINTK("88==0x%04x  "
834                 "93==0x%04x\n",
835                 id[88],
836                 id[93]);
837 }
838
839 /**
840  *      ata_id_xfermask - Compute xfermask from the given IDENTIFY data
841  *      @id: IDENTIFY data to compute xfer mask from
842  *
843  *      Compute the xfermask for this device. This is not as trivial
844  *      as it seems if we must consider early devices correctly.
845  *
846  *      FIXME: pre IDE drive timing (do we care ?).
847  *
848  *      LOCKING:
849  *      None.
850  *
851  *      RETURNS:
852  *      Computed xfermask
853  */
854 static unsigned int ata_id_xfermask(const u16 *id)
855 {
856         unsigned int pio_mask, mwdma_mask, udma_mask;
857
858         /* Usual case. Word 53 indicates word 64 is valid */
859         if (id[ATA_ID_FIELD_VALID] & (1 << 1)) {
860                 pio_mask = id[ATA_ID_PIO_MODES] & 0x03;
861                 pio_mask <<= 3;
862                 pio_mask |= 0x7;
863         } else {
864                 /* If word 64 isn't valid then Word 51 high byte holds
865                  * the PIO timing number for the maximum. Turn it into
866                  * a mask.
867                  */
868                 pio_mask = (2 << (id[ATA_ID_OLD_PIO_MODES] & 0xFF)) - 1 ;
869
870                 /* But wait.. there's more. Design your standards by
871                  * committee and you too can get a free iordy field to
872                  * process. However its the speeds not the modes that
873                  * are supported... Note drivers using the timing API
874                  * will get this right anyway
875                  */
876         }
877
878         mwdma_mask = id[ATA_ID_MWDMA_MODES] & 0x07;
879
880         udma_mask = 0;
881         if (id[ATA_ID_FIELD_VALID] & (1 << 2))
882                 udma_mask = id[ATA_ID_UDMA_MODES] & 0xff;
883
884         return ata_pack_xfermask(pio_mask, mwdma_mask, udma_mask);
885 }
886
887 /**
888  *      ata_port_queue_task - Queue port_task
889  *      @ap: The ata_port to queue port_task for
890  *      @fn: workqueue function to be scheduled
891  *      @data: data value to pass to workqueue function
892  *      @delay: delay time for workqueue function
893  *
894  *      Schedule @fn(@data) for execution after @delay jiffies using
895  *      port_task.  There is one port_task per port and it's the
896  *      user(low level driver)'s responsibility to make sure that only
897  *      one task is active at any given time.
898  *
899  *      libata core layer takes care of synchronization between
900  *      port_task and EH.  ata_port_queue_task() may be ignored for EH
901  *      synchronization.
902  *
903  *      LOCKING:
904  *      Inherited from caller.
905  */
906 void ata_port_queue_task(struct ata_port *ap, void (*fn)(void *), void *data,
907                          unsigned long delay)
908 {
909         int rc;
910
911         if (ap->flags & ATA_FLAG_FLUSH_PORT_TASK)
912                 return;
913
914         PREPARE_WORK(&ap->port_task, fn, data);
915
916         if (!delay)
917                 rc = queue_work(ata_wq, &ap->port_task);
918         else
919                 rc = queue_delayed_work(ata_wq, &ap->port_task, delay);
920
921         /* rc == 0 means that another user is using port task */
922         WARN_ON(rc == 0);
923 }
924
925 /**
926  *      ata_port_flush_task - Flush port_task
927  *      @ap: The ata_port to flush port_task for
928  *
929  *      After this function completes, port_task is guranteed not to
930  *      be running or scheduled.
931  *
932  *      LOCKING:
933  *      Kernel thread context (may sleep)
934  */
935 void ata_port_flush_task(struct ata_port *ap)
936 {
937         unsigned long flags;
938
939         DPRINTK("ENTER\n");
940
941         spin_lock_irqsave(ap->lock, flags);
942         ap->flags |= ATA_FLAG_FLUSH_PORT_TASK;
943         spin_unlock_irqrestore(ap->lock, flags);
944
945         DPRINTK("flush #1\n");
946         flush_workqueue(ata_wq);
947
948         /*
949          * At this point, if a task is running, it's guaranteed to see
950          * the FLUSH flag; thus, it will never queue pio tasks again.
951          * Cancel and flush.
952          */
953         if (!cancel_delayed_work(&ap->port_task)) {
954                 if (ata_msg_ctl(ap))
955                         ata_port_printk(ap, KERN_DEBUG, "%s: flush #2\n",
956                                         __FUNCTION__);
957                 flush_workqueue(ata_wq);
958         }
959
960         spin_lock_irqsave(ap->lock, flags);
961         ap->flags &= ~ATA_FLAG_FLUSH_PORT_TASK;
962         spin_unlock_irqrestore(ap->lock, flags);
963
964         if (ata_msg_ctl(ap))
965                 ata_port_printk(ap, KERN_DEBUG, "%s: EXIT\n", __FUNCTION__);
966 }
967
968 void ata_qc_complete_internal(struct ata_queued_cmd *qc)
969 {
970         struct completion *waiting = qc->private_data;
971
972         complete(waiting);
973 }
974
975 /**
976  *      ata_exec_internal - execute libata internal command
977  *      @dev: Device to which the command is sent
978  *      @tf: Taskfile registers for the command and the result
979  *      @cdb: CDB for packet command
980  *      @dma_dir: Data tranfer direction of the command
981  *      @buf: Data buffer of the command
982  *      @buflen: Length of data buffer
983  *
984  *      Executes libata internal command with timeout.  @tf contains
985  *      command on entry and result on return.  Timeout and error
986  *      conditions are reported via return value.  No recovery action
987  *      is taken after a command times out.  It's caller's duty to
988  *      clean up after timeout.
989  *
990  *      LOCKING:
991  *      None.  Should be called with kernel context, might sleep.
992  *
993  *      RETURNS:
994  *      Zero on success, AC_ERR_* mask on failure
995  */
996 unsigned ata_exec_internal(struct ata_device *dev,
997                            struct ata_taskfile *tf, const u8 *cdb,
998                            int dma_dir, void *buf, unsigned int buflen)
999 {
1000         struct ata_port *ap = dev->ap;
1001         u8 command = tf->command;
1002         struct ata_queued_cmd *qc;
1003         unsigned int tag, preempted_tag;
1004         u32 preempted_sactive, preempted_qc_active;
1005         DECLARE_COMPLETION(wait);
1006         unsigned long flags;
1007         unsigned int err_mask;
1008         int rc;
1009
1010         spin_lock_irqsave(ap->lock, flags);
1011
1012         /* no internal command while frozen */
1013         if (ap->flags & ATA_FLAG_FROZEN) {
1014                 spin_unlock_irqrestore(ap->lock, flags);
1015                 return AC_ERR_SYSTEM;
1016         }
1017
1018         /* initialize internal qc */
1019
1020         /* XXX: Tag 0 is used for drivers with legacy EH as some
1021          * drivers choke if any other tag is given.  This breaks
1022          * ata_tag_internal() test for those drivers.  Don't use new
1023          * EH stuff without converting to it.
1024          */
1025         if (ap->ops->error_handler)
1026                 tag = ATA_TAG_INTERNAL;
1027         else
1028                 tag = 0;
1029
1030         if (test_and_set_bit(tag, &ap->qc_allocated))
1031                 BUG();
1032         qc = __ata_qc_from_tag(ap, tag);
1033
1034         qc->tag = tag;
1035         qc->scsicmd = NULL;
1036         qc->ap = ap;
1037         qc->dev = dev;
1038         ata_qc_reinit(qc);
1039
1040         preempted_tag = ap->active_tag;
1041         preempted_sactive = ap->sactive;
1042         preempted_qc_active = ap->qc_active;
1043         ap->active_tag = ATA_TAG_POISON;
1044         ap->sactive = 0;
1045         ap->qc_active = 0;
1046
1047         /* prepare & issue qc */
1048         qc->tf = *tf;
1049         if (cdb)
1050                 memcpy(qc->cdb, cdb, ATAPI_CDB_LEN);
1051         qc->flags |= ATA_QCFLAG_RESULT_TF;
1052         qc->dma_dir = dma_dir;
1053         if (dma_dir != DMA_NONE) {
1054                 ata_sg_init_one(qc, buf, buflen);
1055                 qc->nsect = buflen / ATA_SECT_SIZE;
1056         }
1057
1058         qc->private_data = &wait;
1059         qc->complete_fn = ata_qc_complete_internal;
1060
1061         ata_qc_issue(qc);
1062
1063         spin_unlock_irqrestore(ap->lock, flags);
1064
1065         rc = wait_for_completion_timeout(&wait, ata_probe_timeout);
1066
1067         ata_port_flush_task(ap);
1068
1069         if (!rc) {
1070                 spin_lock_irqsave(ap->lock, flags);
1071
1072                 /* We're racing with irq here.  If we lose, the
1073                  * following test prevents us from completing the qc
1074                  * twice.  If we win, the port is frozen and will be
1075                  * cleaned up by ->post_internal_cmd().
1076                  */
1077                 if (qc->flags & ATA_QCFLAG_ACTIVE) {
1078                         qc->err_mask |= AC_ERR_TIMEOUT;
1079
1080                         if (ap->ops->error_handler)
1081                                 ata_port_freeze(ap);
1082                         else
1083                                 ata_qc_complete(qc);
1084
1085                         if (ata_msg_warn(ap))
1086                                 ata_dev_printk(dev, KERN_WARNING,
1087                                         "qc timeout (cmd 0x%x)\n", command);
1088                 }
1089
1090                 spin_unlock_irqrestore(ap->lock, flags);
1091         }
1092
1093         /* do post_internal_cmd */
1094         if (ap->ops->post_internal_cmd)
1095                 ap->ops->post_internal_cmd(qc);
1096
1097         if (qc->flags & ATA_QCFLAG_FAILED && !qc->err_mask) {
1098                 if (ata_msg_warn(ap))
1099                         ata_dev_printk(dev, KERN_WARNING,
1100                                 "zero err_mask for failed "
1101                                 "internal command, assuming AC_ERR_OTHER\n");
1102                 qc->err_mask |= AC_ERR_OTHER;
1103         }
1104
1105         /* finish up */
1106         spin_lock_irqsave(ap->lock, flags);
1107
1108         *tf = qc->result_tf;
1109         err_mask = qc->err_mask;
1110
1111         ata_qc_free(qc);
1112         ap->active_tag = preempted_tag;
1113         ap->sactive = preempted_sactive;
1114         ap->qc_active = preempted_qc_active;
1115
1116         /* XXX - Some LLDDs (sata_mv) disable port on command failure.
1117          * Until those drivers are fixed, we detect the condition
1118          * here, fail the command with AC_ERR_SYSTEM and reenable the
1119          * port.
1120          *
1121          * Note that this doesn't change any behavior as internal
1122          * command failure results in disabling the device in the
1123          * higher layer for LLDDs without new reset/EH callbacks.
1124          *
1125          * Kill the following code as soon as those drivers are fixed.
1126          */
1127         if (ap->flags & ATA_FLAG_DISABLED) {
1128                 err_mask |= AC_ERR_SYSTEM;
1129                 ata_port_probe(ap);
1130         }
1131
1132         spin_unlock_irqrestore(ap->lock, flags);
1133
1134         return err_mask;
1135 }
1136
1137 /**
1138  *      ata_do_simple_cmd - execute simple internal command
1139  *      @dev: Device to which the command is sent
1140  *      @cmd: Opcode to execute
1141  *
1142  *      Execute a 'simple' command, that only consists of the opcode
1143  *      'cmd' itself, without filling any other registers
1144  *
1145  *      LOCKING:
1146  *      Kernel thread context (may sleep).
1147  *
1148  *      RETURNS:
1149  *      Zero on success, AC_ERR_* mask on failure
1150  */
1151 unsigned int ata_do_simple_cmd(struct ata_device *dev, u8 cmd)
1152 {
1153         struct ata_taskfile tf;
1154
1155         ata_tf_init(dev, &tf);
1156
1157         tf.command = cmd;
1158         tf.flags |= ATA_TFLAG_DEVICE;
1159         tf.protocol = ATA_PROT_NODATA;
1160
1161         return ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0);
1162 }
1163
1164 /**
1165  *      ata_pio_need_iordy      -       check if iordy needed
1166  *      @adev: ATA device
1167  *
1168  *      Check if the current speed of the device requires IORDY. Used
1169  *      by various controllers for chip configuration.
1170  */
1171
1172 unsigned int ata_pio_need_iordy(const struct ata_device *adev)
1173 {
1174         int pio;
1175         int speed = adev->pio_mode - XFER_PIO_0;
1176
1177         if (speed < 2)
1178                 return 0;
1179         if (speed > 2)
1180                 return 1;
1181
1182         /* If we have no drive specific rule, then PIO 2 is non IORDY */
1183
1184         if (adev->id[ATA_ID_FIELD_VALID] & 2) { /* EIDE */
1185                 pio = adev->id[ATA_ID_EIDE_PIO];
1186                 /* Is the speed faster than the drive allows non IORDY ? */
1187                 if (pio) {
1188                         /* This is cycle times not frequency - watch the logic! */
1189                         if (pio > 240)  /* PIO2 is 240nS per cycle */
1190                                 return 1;
1191                         return 0;
1192                 }
1193         }
1194         return 0;
1195 }
1196
1197 /**
1198  *      ata_dev_read_id - Read ID data from the specified device
1199  *      @dev: target device
1200  *      @p_class: pointer to class of the target device (may be changed)
1201  *      @post_reset: is this read ID post-reset?
1202  *      @id: buffer to read IDENTIFY data into
1203  *
1204  *      Read ID data from the specified device.  ATA_CMD_ID_ATA is
1205  *      performed on ATA devices and ATA_CMD_ID_ATAPI on ATAPI
1206  *      devices.  This function also issues ATA_CMD_INIT_DEV_PARAMS
1207  *      for pre-ATA4 drives.
1208  *
1209  *      LOCKING:
1210  *      Kernel thread context (may sleep)
1211  *
1212  *      RETURNS:
1213  *      0 on success, -errno otherwise.
1214  */
1215 int ata_dev_read_id(struct ata_device *dev, unsigned int *p_class,
1216                     int post_reset, u16 *id)
1217 {
1218         struct ata_port *ap = dev->ap;
1219         unsigned int class = *p_class;
1220         struct ata_taskfile tf;
1221         unsigned int err_mask = 0;
1222         const char *reason;
1223         int rc;
1224
1225         if (ata_msg_ctl(ap))
1226                 ata_dev_printk(dev, KERN_DEBUG, "%s: ENTER, host %u, dev %u\n",
1227                                __FUNCTION__, ap->id, dev->devno);
1228
1229         ata_dev_select(ap, dev->devno, 1, 1); /* select device 0/1 */
1230
1231  retry:
1232         ata_tf_init(dev, &tf);
1233
1234         switch (class) {
1235         case ATA_DEV_ATA:
1236                 tf.command = ATA_CMD_ID_ATA;
1237                 break;
1238         case ATA_DEV_ATAPI:
1239                 tf.command = ATA_CMD_ID_ATAPI;
1240                 break;
1241         default:
1242                 rc = -ENODEV;
1243                 reason = "unsupported class";
1244                 goto err_out;
1245         }
1246
1247         tf.protocol = ATA_PROT_PIO;
1248
1249         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_FROM_DEVICE,
1250                                      id, sizeof(id[0]) * ATA_ID_WORDS);
1251         if (err_mask) {
1252                 rc = -EIO;
1253                 reason = "I/O error";
1254                 goto err_out;
1255         }
1256
1257         swap_buf_le16(id, ATA_ID_WORDS);
1258
1259         /* sanity check */
1260         if ((class == ATA_DEV_ATA) != (ata_id_is_ata(id) | ata_id_is_cfa(id))) {
1261                 rc = -EINVAL;
1262                 reason = "device reports illegal type";
1263                 goto err_out;
1264         }
1265
1266         if (post_reset && class == ATA_DEV_ATA) {
1267                 /*
1268                  * The exact sequence expected by certain pre-ATA4 drives is:
1269                  * SRST RESET
1270                  * IDENTIFY
1271                  * INITIALIZE DEVICE PARAMETERS
1272                  * anything else..
1273                  * Some drives were very specific about that exact sequence.
1274                  */
1275                 if (ata_id_major_version(id) < 4 || !ata_id_has_lba(id)) {
1276                         err_mask = ata_dev_init_params(dev, id[3], id[6]);
1277                         if (err_mask) {
1278                                 rc = -EIO;
1279                                 reason = "INIT_DEV_PARAMS failed";
1280                                 goto err_out;
1281                         }
1282
1283                         /* current CHS translation info (id[53-58]) might be
1284                          * changed. reread the identify device info.
1285                          */
1286                         post_reset = 0;
1287                         goto retry;
1288                 }
1289         }
1290
1291         *p_class = class;
1292
1293         return 0;
1294
1295  err_out:
1296         if (ata_msg_warn(ap))
1297                 ata_dev_printk(dev, KERN_WARNING, "failed to IDENTIFY "
1298                                "(%s, err_mask=0x%x)\n", reason, err_mask);
1299         return rc;
1300 }
1301
1302 static inline u8 ata_dev_knobble(struct ata_device *dev)
1303 {
1304         return ((dev->ap->cbl == ATA_CBL_SATA) && (!ata_id_is_sata(dev->id)));
1305 }
1306
1307 static void ata_dev_config_ncq(struct ata_device *dev,
1308                                char *desc, size_t desc_sz)
1309 {
1310         struct ata_port *ap = dev->ap;
1311         int hdepth = 0, ddepth = ata_id_queue_depth(dev->id);
1312
1313         if (!ata_id_has_ncq(dev->id)) {
1314                 desc[0] = '\0';
1315                 return;
1316         }
1317
1318         if (ap->flags & ATA_FLAG_NCQ) {
1319                 hdepth = min(ap->host->can_queue, ATA_MAX_QUEUE - 1);
1320                 dev->flags |= ATA_DFLAG_NCQ;
1321         }
1322
1323         if (hdepth >= ddepth)
1324                 snprintf(desc, desc_sz, "NCQ (depth %d)", ddepth);
1325         else
1326                 snprintf(desc, desc_sz, "NCQ (depth %d/%d)", hdepth, ddepth);
1327 }
1328
1329 /**
1330  *      ata_dev_configure - Configure the specified ATA/ATAPI device
1331  *      @dev: Target device to configure
1332  *      @print_info: Enable device info printout
1333  *
1334  *      Configure @dev according to @dev->id.  Generic and low-level
1335  *      driver specific fixups are also applied.
1336  *
1337  *      LOCKING:
1338  *      Kernel thread context (may sleep)
1339  *
1340  *      RETURNS:
1341  *      0 on success, -errno otherwise
1342  */
1343 int ata_dev_configure(struct ata_device *dev, int print_info)
1344 {
1345         struct ata_port *ap = dev->ap;
1346         const u16 *id = dev->id;
1347         unsigned int xfer_mask;
1348         int i, rc;
1349
1350         if (!ata_dev_enabled(dev) && ata_msg_info(ap)) {
1351                 ata_dev_printk(dev, KERN_INFO,
1352                                "%s: ENTER/EXIT (host %u, dev %u) -- nodev\n",
1353                                __FUNCTION__, ap->id, dev->devno);
1354                 return 0;
1355         }
1356
1357         if (ata_msg_probe(ap))
1358                 ata_dev_printk(dev, KERN_DEBUG, "%s: ENTER, host %u, dev %u\n",
1359                                __FUNCTION__, ap->id, dev->devno);
1360
1361         /* print device capabilities */
1362         if (ata_msg_probe(ap))
1363                 ata_dev_printk(dev, KERN_DEBUG,
1364                                "%s: cfg 49:%04x 82:%04x 83:%04x 84:%04x "
1365                                "85:%04x 86:%04x 87:%04x 88:%04x\n",
1366                                __FUNCTION__,
1367                                id[49], id[82], id[83], id[84],
1368                                id[85], id[86], id[87], id[88]);
1369
1370         /* initialize to-be-configured parameters */
1371         dev->flags &= ~ATA_DFLAG_CFG_MASK;
1372         dev->max_sectors = 0;
1373         dev->cdb_len = 0;
1374         dev->n_sectors = 0;
1375         dev->cylinders = 0;
1376         dev->heads = 0;
1377         dev->sectors = 0;
1378
1379         /*
1380          * common ATA, ATAPI feature tests
1381          */
1382
1383         /* find max transfer mode; for printk only */
1384         xfer_mask = ata_id_xfermask(id);
1385
1386         if (ata_msg_probe(ap))
1387                 ata_dump_id(id);
1388
1389         /* ATA-specific feature tests */
1390         if (dev->class == ATA_DEV_ATA) {
1391                 dev->n_sectors = ata_id_n_sectors(id);
1392
1393                 if (ata_id_has_lba(id)) {
1394                         const char *lba_desc;
1395                         char ncq_desc[20];
1396
1397                         lba_desc = "LBA";
1398                         dev->flags |= ATA_DFLAG_LBA;
1399                         if (ata_id_has_lba48(id)) {
1400                                 dev->flags |= ATA_DFLAG_LBA48;
1401                                 lba_desc = "LBA48";
1402                         }
1403
1404                         /* config NCQ */
1405                         ata_dev_config_ncq(dev, ncq_desc, sizeof(ncq_desc));
1406
1407                         /* print device info to dmesg */
1408                         if (ata_msg_info(ap))
1409                                 ata_dev_printk(dev, KERN_INFO, "ATA-%d, "
1410                                         "max %s, %Lu sectors: %s %s\n",
1411                                         ata_id_major_version(id),
1412                                         ata_mode_string(xfer_mask),
1413                                         (unsigned long long)dev->n_sectors,
1414                                         lba_desc, ncq_desc);
1415                 } else {
1416                         /* CHS */
1417
1418                         /* Default translation */
1419                         dev->cylinders  = id[1];
1420                         dev->heads      = id[3];
1421                         dev->sectors    = id[6];
1422
1423                         if (ata_id_current_chs_valid(id)) {
1424                                 /* Current CHS translation is valid. */
1425                                 dev->cylinders = id[54];
1426                                 dev->heads     = id[55];
1427                                 dev->sectors   = id[56];
1428                         }
1429
1430                         /* print device info to dmesg */
1431                         if (ata_msg_info(ap))
1432                                 ata_dev_printk(dev, KERN_INFO, "ATA-%d, "
1433                                         "max %s, %Lu sectors: CHS %u/%u/%u\n",
1434                                         ata_id_major_version(id),
1435                                         ata_mode_string(xfer_mask),
1436                                         (unsigned long long)dev->n_sectors,
1437                                         dev->cylinders, dev->heads,
1438                                         dev->sectors);
1439                 }
1440
1441                 if (dev->id[59] & 0x100) {
1442                         dev->multi_count = dev->id[59] & 0xff;
1443                         if (ata_msg_info(ap))
1444                                 ata_dev_printk(dev, KERN_INFO,
1445                                         "ata%u: dev %u multi count %u\n",
1446                                         ap->id, dev->devno, dev->multi_count);
1447                 }
1448
1449                 dev->cdb_len = 16;
1450         }
1451
1452         /* ATAPI-specific feature tests */
1453         else if (dev->class == ATA_DEV_ATAPI) {
1454                 char *cdb_intr_string = "";
1455
1456                 rc = atapi_cdb_len(id);
1457                 if ((rc < 12) || (rc > ATAPI_CDB_LEN)) {
1458                         if (ata_msg_warn(ap))
1459                                 ata_dev_printk(dev, KERN_WARNING,
1460                                                "unsupported CDB len\n");
1461                         rc = -EINVAL;
1462                         goto err_out_nosup;
1463                 }
1464                 dev->cdb_len = (unsigned int) rc;
1465
1466                 if (ata_id_cdb_intr(dev->id)) {
1467                         dev->flags |= ATA_DFLAG_CDB_INTR;
1468                         cdb_intr_string = ", CDB intr";
1469                 }
1470
1471                 /* print device info to dmesg */
1472                 if (ata_msg_info(ap))
1473                         ata_dev_printk(dev, KERN_INFO, "ATAPI, max %s%s\n",
1474                                        ata_mode_string(xfer_mask),
1475                                        cdb_intr_string);
1476         }
1477
1478         ap->host->max_cmd_len = 0;
1479         for (i = 0; i < ATA_MAX_DEVICES; i++)
1480                 ap->host->max_cmd_len = max_t(unsigned int,
1481                                               ap->host->max_cmd_len,
1482                                               ap->device[i].cdb_len);
1483
1484         /* limit bridge transfers to udma5, 200 sectors */
1485         if (ata_dev_knobble(dev)) {
1486                 if (ata_msg_info(ap))
1487                         ata_dev_printk(dev, KERN_INFO,
1488                                        "applying bridge limits\n");
1489                 dev->udma_mask &= ATA_UDMA5;
1490                 dev->max_sectors = ATA_MAX_SECTORS;
1491         }
1492
1493         if (ap->ops->dev_config)
1494                 ap->ops->dev_config(ap, dev);
1495
1496         if (ata_msg_probe(ap))
1497                 ata_dev_printk(dev, KERN_DEBUG, "%s: EXIT, drv_stat = 0x%x\n",
1498                         __FUNCTION__, ata_chk_status(ap));
1499         return 0;
1500
1501 err_out_nosup:
1502         if (ata_msg_probe(ap))
1503                 ata_dev_printk(dev, KERN_DEBUG,
1504                                "%s: EXIT, err\n", __FUNCTION__);
1505         return rc;
1506 }
1507
1508 /**
1509  *      ata_bus_probe - Reset and probe ATA bus
1510  *      @ap: Bus to probe
1511  *
1512  *      Master ATA bus probing function.  Initiates a hardware-dependent
1513  *      bus reset, then attempts to identify any devices found on
1514  *      the bus.
1515  *
1516  *      LOCKING:
1517  *      PCI/etc. bus probe sem.
1518  *
1519  *      RETURNS:
1520  *      Zero on success, negative errno otherwise.
1521  */
1522
1523 static int ata_bus_probe(struct ata_port *ap)
1524 {
1525         unsigned int classes[ATA_MAX_DEVICES];
1526         int tries[ATA_MAX_DEVICES];
1527         int i, rc, down_xfermask;
1528         struct ata_device *dev;
1529
1530         ata_port_probe(ap);
1531
1532         for (i = 0; i < ATA_MAX_DEVICES; i++)
1533                 tries[i] = ATA_PROBE_MAX_TRIES;
1534
1535  retry:
1536         down_xfermask = 0;
1537
1538         /* reset and determine device classes */
1539         ap->ops->phy_reset(ap);
1540
1541         for (i = 0; i < ATA_MAX_DEVICES; i++) {
1542                 dev = &ap->device[i];
1543
1544                 if (!(ap->flags & ATA_FLAG_DISABLED) &&
1545                     dev->class != ATA_DEV_UNKNOWN)
1546                         classes[dev->devno] = dev->class;
1547                 else
1548                         classes[dev->devno] = ATA_DEV_NONE;
1549
1550                 dev->class = ATA_DEV_UNKNOWN;
1551         }
1552
1553         ata_port_probe(ap);
1554
1555         /* after the reset the device state is PIO 0 and the controller
1556            state is undefined. Record the mode */
1557
1558         for (i = 0; i < ATA_MAX_DEVICES; i++)
1559                 ap->device[i].pio_mode = XFER_PIO_0;
1560
1561         /* read IDENTIFY page and configure devices */
1562         for (i = 0; i < ATA_MAX_DEVICES; i++) {
1563                 dev = &ap->device[i];
1564
1565                 if (tries[i])
1566                         dev->class = classes[i];
1567
1568                 if (!ata_dev_enabled(dev))
1569                         continue;
1570
1571                 rc = ata_dev_read_id(dev, &dev->class, 1, dev->id);
1572                 if (rc)
1573                         goto fail;
1574
1575                 rc = ata_dev_configure(dev, 1);
1576                 if (rc)
1577                         goto fail;
1578         }
1579
1580         /* configure transfer mode */
1581         rc = ata_set_mode(ap, &dev);
1582         if (rc) {
1583                 down_xfermask = 1;
1584                 goto fail;
1585         }
1586
1587         for (i = 0; i < ATA_MAX_DEVICES; i++)
1588                 if (ata_dev_enabled(&ap->device[i]))
1589                         return 0;
1590
1591         /* no device present, disable port */
1592         ata_port_disable(ap);
1593         ap->ops->port_disable(ap);
1594         return -ENODEV;
1595
1596  fail:
1597         switch (rc) {
1598         case -EINVAL:
1599         case -ENODEV:
1600                 tries[dev->devno] = 0;
1601                 break;
1602         case -EIO:
1603                 sata_down_spd_limit(ap);
1604                 /* fall through */
1605         default:
1606                 tries[dev->devno]--;
1607                 if (down_xfermask &&
1608                     ata_down_xfermask_limit(dev, tries[dev->devno] == 1))
1609                         tries[dev->devno] = 0;
1610         }
1611
1612         if (!tries[dev->devno]) {
1613                 ata_down_xfermask_limit(dev, 1);
1614                 ata_dev_disable(dev);
1615         }
1616
1617         goto retry;
1618 }
1619
1620 /**
1621  *      ata_port_probe - Mark port as enabled
1622  *      @ap: Port for which we indicate enablement
1623  *
1624  *      Modify @ap data structure such that the system
1625  *      thinks that the entire port is enabled.
1626  *
1627  *      LOCKING: host_set lock, or some other form of
1628  *      serialization.
1629  */
1630
1631 void ata_port_probe(struct ata_port *ap)
1632 {
1633         ap->flags &= ~ATA_FLAG_DISABLED;
1634 }
1635
1636 /**
1637  *      sata_print_link_status - Print SATA link status
1638  *      @ap: SATA port to printk link status about
1639  *
1640  *      This function prints link speed and status of a SATA link.
1641  *
1642  *      LOCKING:
1643  *      None.
1644  */
1645 static void sata_print_link_status(struct ata_port *ap)
1646 {
1647         u32 sstatus, scontrol, tmp;
1648
1649         if (sata_scr_read(ap, SCR_STATUS, &sstatus))
1650                 return;
1651         sata_scr_read(ap, SCR_CONTROL, &scontrol);
1652
1653         if (ata_port_online(ap)) {
1654                 tmp = (sstatus >> 4) & 0xf;
1655                 ata_port_printk(ap, KERN_INFO,
1656                                 "SATA link up %s (SStatus %X SControl %X)\n",
1657                                 sata_spd_string(tmp), sstatus, scontrol);
1658         } else {
1659                 ata_port_printk(ap, KERN_INFO,
1660                                 "SATA link down (SStatus %X SControl %X)\n",
1661                                 sstatus, scontrol);
1662         }
1663 }
1664
1665 /**
1666  *      __sata_phy_reset - Wake/reset a low-level SATA PHY
1667  *      @ap: SATA port associated with target SATA PHY.
1668  *
1669  *      This function issues commands to standard SATA Sxxx
1670  *      PHY registers, to wake up the phy (and device), and
1671  *      clear any reset condition.
1672  *
1673  *      LOCKING:
1674  *      PCI/etc. bus probe sem.
1675  *
1676  */
1677 void __sata_phy_reset(struct ata_port *ap)
1678 {
1679         u32 sstatus;
1680         unsigned long timeout = jiffies + (HZ * 5);
1681
1682         if (ap->flags & ATA_FLAG_SATA_RESET) {
1683                 /* issue phy wake/reset */
1684                 sata_scr_write_flush(ap, SCR_CONTROL, 0x301);
1685                 /* Couldn't find anything in SATA I/II specs, but
1686                  * AHCI-1.1 10.4.2 says at least 1 ms. */
1687                 mdelay(1);
1688         }
1689         /* phy wake/clear reset */
1690         sata_scr_write_flush(ap, SCR_CONTROL, 0x300);
1691
1692         /* wait for phy to become ready, if necessary */
1693         do {
1694                 msleep(200);
1695                 sata_scr_read(ap, SCR_STATUS, &sstatus);
1696                 if ((sstatus & 0xf) != 1)
1697                         break;
1698         } while (time_before(jiffies, timeout));
1699
1700         /* print link status */
1701         sata_print_link_status(ap);
1702
1703         /* TODO: phy layer with polling, timeouts, etc. */
1704         if (!ata_port_offline(ap))
1705                 ata_port_probe(ap);
1706         else
1707                 ata_port_disable(ap);
1708
1709         if (ap->flags & ATA_FLAG_DISABLED)
1710                 return;
1711
1712         if (ata_busy_sleep(ap, ATA_TMOUT_BOOT_QUICK, ATA_TMOUT_BOOT)) {
1713                 ata_port_disable(ap);
1714                 return;
1715         }
1716
1717         ap->cbl = ATA_CBL_SATA;
1718 }
1719
1720 /**
1721  *      sata_phy_reset - Reset SATA bus.
1722  *      @ap: SATA port associated with target SATA PHY.
1723  *
1724  *      This function resets the SATA bus, and then probes
1725  *      the bus for devices.
1726  *
1727  *      LOCKING:
1728  *      PCI/etc. bus probe sem.
1729  *
1730  */
1731 void sata_phy_reset(struct ata_port *ap)
1732 {
1733         __sata_phy_reset(ap);
1734         if (ap->flags & ATA_FLAG_DISABLED)
1735                 return;
1736         ata_bus_reset(ap);
1737 }
1738
1739 /**
1740  *      ata_dev_pair            -       return other device on cable
1741  *      @adev: device
1742  *
1743  *      Obtain the other device on the same cable, or if none is
1744  *      present NULL is returned
1745  */
1746
1747 struct ata_device *ata_dev_pair(struct ata_device *adev)
1748 {
1749         struct ata_port *ap = adev->ap;
1750         struct ata_device *pair = &ap->device[1 - adev->devno];
1751         if (!ata_dev_enabled(pair))
1752                 return NULL;
1753         return pair;
1754 }
1755
1756 /**
1757  *      ata_port_disable - Disable port.
1758  *      @ap: Port to be disabled.
1759  *
1760  *      Modify @ap data structure such that the system
1761  *      thinks that the entire port is disabled, and should
1762  *      never attempt to probe or communicate with devices
1763  *      on this port.
1764  *
1765  *      LOCKING: host_set lock, or some other form of
1766  *      serialization.
1767  */
1768
1769 void ata_port_disable(struct ata_port *ap)
1770 {
1771         ap->device[0].class = ATA_DEV_NONE;
1772         ap->device[1].class = ATA_DEV_NONE;
1773         ap->flags |= ATA_FLAG_DISABLED;
1774 }
1775
1776 /**
1777  *      sata_down_spd_limit - adjust SATA spd limit downward
1778  *      @ap: Port to adjust SATA spd limit for
1779  *
1780  *      Adjust SATA spd limit of @ap downward.  Note that this
1781  *      function only adjusts the limit.  The change must be applied
1782  *      using sata_set_spd().
1783  *
1784  *      LOCKING:
1785  *      Inherited from caller.
1786  *
1787  *      RETURNS:
1788  *      0 on success, negative errno on failure
1789  */
1790 int sata_down_spd_limit(struct ata_port *ap)
1791 {
1792         u32 sstatus, spd, mask;
1793         int rc, highbit;
1794
1795         rc = sata_scr_read(ap, SCR_STATUS, &sstatus);
1796         if (rc)
1797                 return rc;
1798
1799         mask = ap->sata_spd_limit;
1800         if (mask <= 1)
1801                 return -EINVAL;
1802         highbit = fls(mask) - 1;
1803         mask &= ~(1 << highbit);
1804
1805         spd = (sstatus >> 4) & 0xf;
1806         if (spd <= 1)
1807                 return -EINVAL;
1808         spd--;
1809         mask &= (1 << spd) - 1;
1810         if (!mask)
1811                 return -EINVAL;
1812
1813         ap->sata_spd_limit = mask;
1814
1815         ata_port_printk(ap, KERN_WARNING, "limiting SATA link speed to %s\n",
1816                         sata_spd_string(fls(mask)));
1817
1818         return 0;
1819 }
1820
1821 static int __sata_set_spd_needed(struct ata_port *ap, u32 *scontrol)
1822 {
1823         u32 spd, limit;
1824
1825         if (ap->sata_spd_limit == UINT_MAX)
1826                 limit = 0;
1827         else
1828                 limit = fls(ap->sata_spd_limit);
1829
1830         spd = (*scontrol >> 4) & 0xf;
1831         *scontrol = (*scontrol & ~0xf0) | ((limit & 0xf) << 4);
1832
1833         return spd != limit;
1834 }
1835
1836 /**
1837  *      sata_set_spd_needed - is SATA spd configuration needed
1838  *      @ap: Port in question
1839  *
1840  *      Test whether the spd limit in SControl matches
1841  *      @ap->sata_spd_limit.  This function is used to determine
1842  *      whether hardreset is necessary to apply SATA spd
1843  *      configuration.
1844  *
1845  *      LOCKING:
1846  *      Inherited from caller.
1847  *
1848  *      RETURNS:
1849  *      1 if SATA spd configuration is needed, 0 otherwise.
1850  */
1851 int sata_set_spd_needed(struct ata_port *ap)
1852 {
1853         u32 scontrol;
1854
1855         if (sata_scr_read(ap, SCR_CONTROL, &scontrol))
1856                 return 0;
1857
1858         return __sata_set_spd_needed(ap, &scontrol);
1859 }
1860
1861 /**
1862  *      sata_set_spd - set SATA spd according to spd limit
1863  *      @ap: Port to set SATA spd for
1864  *
1865  *      Set SATA spd of @ap according to sata_spd_limit.
1866  *
1867  *      LOCKING:
1868  *      Inherited from caller.
1869  *
1870  *      RETURNS:
1871  *      0 if spd doesn't need to be changed, 1 if spd has been
1872  *      changed.  Negative errno if SCR registers are inaccessible.
1873  */
1874 int sata_set_spd(struct ata_port *ap)
1875 {
1876         u32 scontrol;
1877         int rc;
1878
1879         if ((rc = sata_scr_read(ap, SCR_CONTROL, &scontrol)))
1880                 return rc;
1881
1882         if (!__sata_set_spd_needed(ap, &scontrol))
1883                 return 0;
1884
1885         if ((rc = sata_scr_write(ap, SCR_CONTROL, scontrol)))
1886                 return rc;
1887
1888         return 1;
1889 }
1890
1891 /*
1892  * This mode timing computation functionality is ported over from
1893  * drivers/ide/ide-timing.h and was originally written by Vojtech Pavlik
1894  */
1895 /*
1896  * PIO 0-5, MWDMA 0-2 and UDMA 0-6 timings (in nanoseconds).
1897  * These were taken from ATA/ATAPI-6 standard, rev 0a, except
1898  * for PIO 5, which is a nonstandard extension and UDMA6, which
1899  * is currently supported only by Maxtor drives.
1900  */
1901
1902 static const struct ata_timing ata_timing[] = {
1903
1904         { XFER_UDMA_6,     0,   0,   0,   0,   0,   0,   0,  15 },
1905         { XFER_UDMA_5,     0,   0,   0,   0,   0,   0,   0,  20 },
1906         { XFER_UDMA_4,     0,   0,   0,   0,   0,   0,   0,  30 },
1907         { XFER_UDMA_3,     0,   0,   0,   0,   0,   0,   0,  45 },
1908
1909         { XFER_UDMA_2,     0,   0,   0,   0,   0,   0,   0,  60 },
1910         { XFER_UDMA_1,     0,   0,   0,   0,   0,   0,   0,  80 },
1911         { XFER_UDMA_0,     0,   0,   0,   0,   0,   0,   0, 120 },
1912
1913 /*      { XFER_UDMA_SLOW,  0,   0,   0,   0,   0,   0,   0, 150 }, */
1914
1915         { XFER_MW_DMA_2,  25,   0,   0,   0,  70,  25, 120,   0 },
1916         { XFER_MW_DMA_1,  45,   0,   0,   0,  80,  50, 150,   0 },
1917         { XFER_MW_DMA_0,  60,   0,   0,   0, 215, 215, 480,   0 },
1918
1919         { XFER_SW_DMA_2,  60,   0,   0,   0, 120, 120, 240,   0 },
1920         { XFER_SW_DMA_1,  90,   0,   0,   0, 240, 240, 480,   0 },
1921         { XFER_SW_DMA_0, 120,   0,   0,   0, 480, 480, 960,   0 },
1922
1923 /*      { XFER_PIO_5,     20,  50,  30, 100,  50,  30, 100,   0 }, */
1924         { XFER_PIO_4,     25,  70,  25, 120,  70,  25, 120,   0 },
1925         { XFER_PIO_3,     30,  80,  70, 180,  80,  70, 180,   0 },
1926
1927         { XFER_PIO_2,     30, 290,  40, 330, 100,  90, 240,   0 },
1928         { XFER_PIO_1,     50, 290,  93, 383, 125, 100, 383,   0 },
1929         { XFER_PIO_0,     70, 290, 240, 600, 165, 150, 600,   0 },
1930
1931 /*      { XFER_PIO_SLOW, 120, 290, 240, 960, 290, 240, 960,   0 }, */
1932
1933         { 0xFF }
1934 };
1935
1936 #define ENOUGH(v,unit)          (((v)-1)/(unit)+1)
1937 #define EZ(v,unit)              ((v)?ENOUGH(v,unit):0)
1938
1939 static void ata_timing_quantize(const struct ata_timing *t, struct ata_timing *q, int T, int UT)
1940 {
1941         q->setup   = EZ(t->setup   * 1000,  T);
1942         q->act8b   = EZ(t->act8b   * 1000,  T);
1943         q->rec8b   = EZ(t->rec8b   * 1000,  T);
1944         q->cyc8b   = EZ(t->cyc8b   * 1000,  T);
1945         q->active  = EZ(t->active  * 1000,  T);
1946         q->recover = EZ(t->recover * 1000,  T);
1947         q->cycle   = EZ(t->cycle   * 1000,  T);
1948         q->udma    = EZ(t->udma    * 1000, UT);
1949 }
1950
1951 void ata_timing_merge(const struct ata_timing *a, const struct ata_timing *b,
1952                       struct ata_timing *m, unsigned int what)
1953 {
1954         if (what & ATA_TIMING_SETUP  ) m->setup   = max(a->setup,   b->setup);
1955         if (what & ATA_TIMING_ACT8B  ) m->act8b   = max(a->act8b,   b->act8b);
1956         if (what & ATA_TIMING_REC8B  ) m->rec8b   = max(a->rec8b,   b->rec8b);
1957         if (what & ATA_TIMING_CYC8B  ) m->cyc8b   = max(a->cyc8b,   b->cyc8b);
1958         if (what & ATA_TIMING_ACTIVE ) m->active  = max(a->active,  b->active);
1959         if (what & ATA_TIMING_RECOVER) m->recover = max(a->recover, b->recover);
1960         if (what & ATA_TIMING_CYCLE  ) m->cycle   = max(a->cycle,   b->cycle);
1961         if (what & ATA_TIMING_UDMA   ) m->udma    = max(a->udma,    b->udma);
1962 }
1963
1964 static const struct ata_timing* ata_timing_find_mode(unsigned short speed)
1965 {
1966         const struct ata_timing *t;
1967
1968         for (t = ata_timing; t->mode != speed; t++)
1969                 if (t->mode == 0xFF)
1970                         return NULL;
1971         return t;
1972 }
1973
1974 int ata_timing_compute(struct ata_device *adev, unsigned short speed,
1975                        struct ata_timing *t, int T, int UT)
1976 {
1977         const struct ata_timing *s;
1978         struct ata_timing p;
1979
1980         /*
1981          * Find the mode.
1982          */
1983
1984         if (!(s = ata_timing_find_mode(speed)))
1985                 return -EINVAL;
1986
1987         memcpy(t, s, sizeof(*s));
1988
1989         /*
1990          * If the drive is an EIDE drive, it can tell us it needs extended
1991          * PIO/MW_DMA cycle timing.
1992          */
1993
1994         if (adev->id[ATA_ID_FIELD_VALID] & 2) { /* EIDE drive */
1995                 memset(&p, 0, sizeof(p));
1996                 if(speed >= XFER_PIO_0 && speed <= XFER_SW_DMA_0) {
1997                         if (speed <= XFER_PIO_2) p.cycle = p.cyc8b = adev->id[ATA_ID_EIDE_PIO];
1998                                             else p.cycle = p.cyc8b = adev->id[ATA_ID_EIDE_PIO_IORDY];
1999                 } else if(speed >= XFER_MW_DMA_0 && speed <= XFER_MW_DMA_2) {
2000                         p.cycle = adev->id[ATA_ID_EIDE_DMA_MIN];
2001                 }
2002                 ata_timing_merge(&p, t, t, ATA_TIMING_CYCLE | ATA_TIMING_CYC8B);
2003         }
2004
2005         /*
2006          * Convert the timing to bus clock counts.
2007          */
2008
2009         ata_timing_quantize(t, t, T, UT);
2010
2011         /*
2012          * Even in DMA/UDMA modes we still use PIO access for IDENTIFY,
2013          * S.M.A.R.T * and some other commands. We have to ensure that the
2014          * DMA cycle timing is slower/equal than the fastest PIO timing.
2015          */
2016
2017         if (speed > XFER_PIO_4) {
2018                 ata_timing_compute(adev, adev->pio_mode, &p, T, UT);
2019                 ata_timing_merge(&p, t, t, ATA_TIMING_ALL);
2020         }
2021
2022         /*
2023          * Lengthen active & recovery time so that cycle time is correct.
2024          */
2025
2026         if (t->act8b + t->rec8b < t->cyc8b) {
2027                 t->act8b += (t->cyc8b - (t->act8b + t->rec8b)) / 2;
2028                 t->rec8b = t->cyc8b - t->act8b;
2029         }
2030
2031         if (t->active + t->recover < t->cycle) {
2032                 t->active += (t->cycle - (t->active + t->recover)) / 2;
2033                 t->recover = t->cycle - t->active;
2034         }
2035
2036         return 0;
2037 }
2038
2039 /**
2040  *      ata_down_xfermask_limit - adjust dev xfer masks downward
2041  *      @dev: Device to adjust xfer masks
2042  *      @force_pio0: Force PIO0
2043  *
2044  *      Adjust xfer masks of @dev downward.  Note that this function
2045  *      does not apply the change.  Invoking ata_set_mode() afterwards
2046  *      will apply the limit.
2047  *
2048  *      LOCKING:
2049  *      Inherited from caller.
2050  *
2051  *      RETURNS:
2052  *      0 on success, negative errno on failure
2053  */
2054 int ata_down_xfermask_limit(struct ata_device *dev, int force_pio0)
2055 {
2056         unsigned long xfer_mask;
2057         int highbit;
2058
2059         xfer_mask = ata_pack_xfermask(dev->pio_mask, dev->mwdma_mask,
2060                                       dev->udma_mask);
2061
2062         if (!xfer_mask)
2063                 goto fail;
2064         /* don't gear down to MWDMA from UDMA, go directly to PIO */
2065         if (xfer_mask & ATA_MASK_UDMA)
2066                 xfer_mask &= ~ATA_MASK_MWDMA;
2067
2068         highbit = fls(xfer_mask) - 1;
2069         xfer_mask &= ~(1 << highbit);
2070         if (force_pio0)
2071                 xfer_mask &= 1 << ATA_SHIFT_PIO;
2072         if (!xfer_mask)
2073                 goto fail;
2074
2075         ata_unpack_xfermask(xfer_mask, &dev->pio_mask, &dev->mwdma_mask,
2076                             &dev->udma_mask);
2077
2078         ata_dev_printk(dev, KERN_WARNING, "limiting speed to %s\n",
2079                        ata_mode_string(xfer_mask));
2080
2081         return 0;
2082
2083  fail:
2084         return -EINVAL;
2085 }
2086
2087 static int ata_dev_set_mode(struct ata_device *dev)
2088 {
2089         unsigned int err_mask;
2090         int rc;
2091
2092         dev->flags &= ~ATA_DFLAG_PIO;
2093         if (dev->xfer_shift == ATA_SHIFT_PIO)
2094                 dev->flags |= ATA_DFLAG_PIO;
2095
2096         err_mask = ata_dev_set_xfermode(dev);
2097         if (err_mask) {
2098                 ata_dev_printk(dev, KERN_ERR, "failed to set xfermode "
2099                                "(err_mask=0x%x)\n", err_mask);
2100                 return -EIO;
2101         }
2102
2103         rc = ata_dev_revalidate(dev, 0);
2104         if (rc)
2105                 return rc;
2106
2107         DPRINTK("xfer_shift=%u, xfer_mode=0x%x\n",
2108                 dev->xfer_shift, (int)dev->xfer_mode);
2109
2110         ata_dev_printk(dev, KERN_INFO, "configured for %s\n",
2111                        ata_mode_string(ata_xfer_mode2mask(dev->xfer_mode)));
2112         return 0;
2113 }
2114
2115 /**
2116  *      ata_set_mode - Program timings and issue SET FEATURES - XFER
2117  *      @ap: port on which timings will be programmed
2118  *      @r_failed_dev: out paramter for failed device
2119  *
2120  *      Set ATA device disk transfer mode (PIO3, UDMA6, etc.).  If
2121  *      ata_set_mode() fails, pointer to the failing device is
2122  *      returned in @r_failed_dev.
2123  *
2124  *      LOCKING:
2125  *      PCI/etc. bus probe sem.
2126  *
2127  *      RETURNS:
2128  *      0 on success, negative errno otherwise
2129  */
2130 int ata_set_mode(struct ata_port *ap, struct ata_device **r_failed_dev)
2131 {
2132         struct ata_device *dev;
2133         int i, rc = 0, used_dma = 0, found = 0;
2134
2135         /* has private set_mode? */
2136         if (ap->ops->set_mode) {
2137                 /* FIXME: make ->set_mode handle no device case and
2138                  * return error code and failing device on failure.
2139                  */
2140                 for (i = 0; i < ATA_MAX_DEVICES; i++) {
2141                         if (ata_dev_enabled(&ap->device[i])) {
2142                                 ap->ops->set_mode(ap);
2143                                 break;
2144                         }
2145                 }
2146                 return 0;
2147         }
2148
2149         /* step 1: calculate xfer_mask */
2150         for (i = 0; i < ATA_MAX_DEVICES; i++) {
2151                 unsigned int pio_mask, dma_mask;
2152
2153                 dev = &ap->device[i];
2154
2155                 if (!ata_dev_enabled(dev))
2156                         continue;
2157
2158                 ata_dev_xfermask(dev);
2159
2160                 pio_mask = ata_pack_xfermask(dev->pio_mask, 0, 0);
2161                 dma_mask = ata_pack_xfermask(0, dev->mwdma_mask, dev->udma_mask);
2162                 dev->pio_mode = ata_xfer_mask2mode(pio_mask);
2163                 dev->dma_mode = ata_xfer_mask2mode(dma_mask);
2164
2165                 found = 1;
2166                 if (dev->dma_mode)
2167                         used_dma = 1;
2168         }
2169         if (!found)
2170                 goto out;
2171
2172         /* step 2: always set host PIO timings */
2173         for (i = 0; i < ATA_MAX_DEVICES; i++) {
2174                 dev = &ap->device[i];
2175                 if (!ata_dev_enabled(dev))
2176                         continue;
2177
2178                 if (!dev->pio_mode) {
2179                         ata_dev_printk(dev, KERN_WARNING, "no PIO support\n");
2180                         rc = -EINVAL;
2181                         goto out;
2182                 }
2183
2184                 dev->xfer_mode = dev->pio_mode;
2185                 dev->xfer_shift = ATA_SHIFT_PIO;
2186                 if (ap->ops->set_piomode)
2187                         ap->ops->set_piomode(ap, dev);
2188         }
2189
2190         /* step 3: set host DMA timings */
2191         for (i = 0; i < ATA_MAX_DEVICES; i++) {
2192                 dev = &ap->device[i];
2193
2194                 if (!ata_dev_enabled(dev) || !dev->dma_mode)
2195                         continue;
2196
2197                 dev->xfer_mode = dev->dma_mode;
2198                 dev->xfer_shift = ata_xfer_mode2shift(dev->dma_mode);
2199                 if (ap->ops->set_dmamode)
2200                         ap->ops->set_dmamode(ap, dev);
2201         }
2202
2203         /* step 4: update devices' xfer mode */
2204         for (i = 0; i < ATA_MAX_DEVICES; i++) {
2205                 dev = &ap->device[i];
2206
2207                 if (!ata_dev_enabled(dev))
2208                         continue;
2209
2210                 rc = ata_dev_set_mode(dev);
2211                 if (rc)
2212                         goto out;
2213         }
2214
2215         /* Record simplex status. If we selected DMA then the other
2216          * host channels are not permitted to do so.
2217          */
2218         if (used_dma && (ap->host_set->flags & ATA_HOST_SIMPLEX))
2219                 ap->host_set->simplex_claimed = 1;
2220
2221         /* step5: chip specific finalisation */
2222         if (ap->ops->post_set_mode)
2223                 ap->ops->post_set_mode(ap);
2224
2225  out:
2226         if (rc)
2227                 *r_failed_dev = dev;
2228         return rc;
2229 }
2230
2231 /**
2232  *      ata_tf_to_host - issue ATA taskfile to host controller
2233  *      @ap: port to which command is being issued
2234  *      @tf: ATA taskfile register set
2235  *
2236  *      Issues ATA taskfile register set to ATA host controller,
2237  *      with proper synchronization with interrupt handler and
2238  *      other threads.
2239  *
2240  *      LOCKING:
2241  *      spin_lock_irqsave(host_set lock)
2242  */
2243
2244 static inline void ata_tf_to_host(struct ata_port *ap,
2245                                   const struct ata_taskfile *tf)
2246 {
2247         ap->ops->tf_load(ap, tf);
2248         ap->ops->exec_command(ap, tf);
2249 }
2250
2251 /**
2252  *      ata_busy_sleep - sleep until BSY clears, or timeout
2253  *      @ap: port containing status register to be polled
2254  *      @tmout_pat: impatience timeout
2255  *      @tmout: overall timeout
2256  *
2257  *      Sleep until ATA Status register bit BSY clears,
2258  *      or a timeout occurs.
2259  *
2260  *      LOCKING: None.
2261  */
2262
2263 unsigned int ata_busy_sleep (struct ata_port *ap,
2264                              unsigned long tmout_pat, unsigned long tmout)
2265 {
2266         unsigned long timer_start, timeout;
2267         u8 status;
2268
2269         status = ata_busy_wait(ap, ATA_BUSY, 300);
2270         timer_start = jiffies;
2271         timeout = timer_start + tmout_pat;
2272         while ((status & ATA_BUSY) && (time_before(jiffies, timeout))) {
2273                 msleep(50);
2274                 status = ata_busy_wait(ap, ATA_BUSY, 3);
2275         }
2276
2277         if (status & ATA_BUSY)
2278                 ata_port_printk(ap, KERN_WARNING,
2279                                 "port is slow to respond, please be patient\n");
2280
2281         timeout = timer_start + tmout;
2282         while ((status & ATA_BUSY) && (time_before(jiffies, timeout))) {
2283                 msleep(50);
2284                 status = ata_chk_status(ap);
2285         }
2286
2287         if (status & ATA_BUSY) {
2288                 ata_port_printk(ap, KERN_ERR, "port failed to respond "
2289                                 "(%lu secs)\n", tmout / HZ);
2290                 return 1;
2291         }
2292
2293         return 0;
2294 }
2295
2296 static void ata_bus_post_reset(struct ata_port *ap, unsigned int devmask)
2297 {
2298         struct ata_ioports *ioaddr = &ap->ioaddr;
2299         unsigned int dev0 = devmask & (1 << 0);
2300         unsigned int dev1 = devmask & (1 << 1);
2301         unsigned long timeout;
2302
2303         /* if device 0 was found in ata_devchk, wait for its
2304          * BSY bit to clear
2305          */
2306         if (dev0)
2307                 ata_busy_sleep(ap, ATA_TMOUT_BOOT_QUICK, ATA_TMOUT_BOOT);
2308
2309         /* if device 1 was found in ata_devchk, wait for
2310          * register access, then wait for BSY to clear
2311          */
2312         timeout = jiffies + ATA_TMOUT_BOOT;
2313         while (dev1) {
2314                 u8 nsect, lbal;
2315
2316                 ap->ops->dev_select(ap, 1);
2317                 if (ap->flags & ATA_FLAG_MMIO) {
2318                         nsect = readb((void __iomem *) ioaddr->nsect_addr);
2319                         lbal = readb((void __iomem *) ioaddr->lbal_addr);
2320                 } else {
2321                         nsect = inb(ioaddr->nsect_addr);
2322                         lbal = inb(ioaddr->lbal_addr);
2323                 }
2324                 if ((nsect == 1) && (lbal == 1))
2325                         break;
2326                 if (time_after(jiffies, timeout)) {
2327                         dev1 = 0;
2328                         break;
2329                 }
2330                 msleep(50);     /* give drive a breather */
2331         }
2332         if (dev1)
2333                 ata_busy_sleep(ap, ATA_TMOUT_BOOT_QUICK, ATA_TMOUT_BOOT);
2334
2335         /* is all this really necessary? */
2336         ap->ops->dev_select(ap, 0);
2337         if (dev1)
2338                 ap->ops->dev_select(ap, 1);
2339         if (dev0)
2340                 ap->ops->dev_select(ap, 0);
2341 }
2342
2343 static unsigned int ata_bus_softreset(struct ata_port *ap,
2344                                       unsigned int devmask)
2345 {
2346         struct ata_ioports *ioaddr = &ap->ioaddr;
2347
2348         DPRINTK("ata%u: bus reset via SRST\n", ap->id);
2349
2350         /* software reset.  causes dev0 to be selected */
2351         if (ap->flags & ATA_FLAG_MMIO) {
2352                 writeb(ap->ctl, (void __iomem *) ioaddr->ctl_addr);
2353                 udelay(20);     /* FIXME: flush */
2354                 writeb(ap->ctl | ATA_SRST, (void __iomem *) ioaddr->ctl_addr);
2355                 udelay(20);     /* FIXME: flush */
2356                 writeb(ap->ctl, (void __iomem *) ioaddr->ctl_addr);
2357         } else {
2358                 outb(ap->ctl, ioaddr->ctl_addr);
2359                 udelay(10);
2360                 outb(ap->ctl | ATA_SRST, ioaddr->ctl_addr);
2361                 udelay(10);
2362                 outb(ap->ctl, ioaddr->ctl_addr);
2363         }
2364
2365         /* spec mandates ">= 2ms" before checking status.
2366          * We wait 150ms, because that was the magic delay used for
2367          * ATAPI devices in Hale Landis's ATADRVR, for the period of time
2368          * between when the ATA command register is written, and then
2369          * status is checked.  Because waiting for "a while" before
2370          * checking status is fine, post SRST, we perform this magic
2371          * delay here as well.
2372          *
2373          * Old drivers/ide uses the 2mS rule and then waits for ready
2374          */
2375         msleep(150);
2376
2377         /* Before we perform post reset processing we want to see if
2378          * the bus shows 0xFF because the odd clown forgets the D7
2379          * pulldown resistor.
2380          */
2381         if (ata_check_status(ap) == 0xFF) {
2382                 ata_port_printk(ap, KERN_ERR, "SRST failed (status 0xFF)\n");
2383                 return AC_ERR_OTHER;
2384         }
2385
2386         ata_bus_post_reset(ap, devmask);
2387
2388         return 0;
2389 }
2390
2391 /**
2392  *      ata_bus_reset - reset host port and associated ATA channel
2393  *      @ap: port to reset
2394  *
2395  *      This is typically the first time we actually start issuing
2396  *      commands to the ATA channel.  We wait for BSY to clear, then
2397  *      issue EXECUTE DEVICE DIAGNOSTIC command, polling for its
2398  *      result.  Determine what devices, if any, are on the channel
2399  *      by looking at the device 0/1 error register.  Look at the signature
2400  *      stored in each device's taskfile registers, to determine if
2401  *      the device is ATA or ATAPI.
2402  *
2403  *      LOCKING:
2404  *      PCI/etc. bus probe sem.
2405  *      Obtains host_set lock.
2406  *
2407  *      SIDE EFFECTS:
2408  *      Sets ATA_FLAG_DISABLED if bus reset fails.
2409  */
2410
2411 void ata_bus_reset(struct ata_port *ap)
2412 {
2413         struct ata_ioports *ioaddr = &ap->ioaddr;
2414         unsigned int slave_possible = ap->flags & ATA_FLAG_SLAVE_POSS;
2415         u8 err;
2416         unsigned int dev0, dev1 = 0, devmask = 0;
2417
2418         DPRINTK("ENTER, host %u, port %u\n", ap->id, ap->port_no);
2419
2420         /* determine if device 0/1 are present */
2421         if (ap->flags & ATA_FLAG_SATA_RESET)
2422                 dev0 = 1;
2423         else {
2424                 dev0 = ata_devchk(ap, 0);
2425                 if (slave_possible)
2426                         dev1 = ata_devchk(ap, 1);
2427         }
2428
2429         if (dev0)
2430                 devmask |= (1 << 0);
2431         if (dev1)
2432                 devmask |= (1 << 1);
2433
2434         /* select device 0 again */
2435         ap->ops->dev_select(ap, 0);
2436
2437         /* issue bus reset */
2438         if (ap->flags & ATA_FLAG_SRST)
2439                 if (ata_bus_softreset(ap, devmask))
2440                         goto err_out;
2441
2442         /*
2443          * determine by signature whether we have ATA or ATAPI devices
2444          */
2445         ap->device[0].class = ata_dev_try_classify(ap, 0, &err);
2446         if ((slave_possible) && (err != 0x81))
2447                 ap->device[1].class = ata_dev_try_classify(ap, 1, &err);
2448
2449         /* re-enable interrupts */
2450         if (ap->ioaddr.ctl_addr)        /* FIXME: hack. create a hook instead */
2451                 ata_irq_on(ap);
2452
2453         /* is double-select really necessary? */
2454         if (ap->device[1].class != ATA_DEV_NONE)
2455                 ap->ops->dev_select(ap, 1);
2456         if (ap->device[0].class != ATA_DEV_NONE)
2457                 ap->ops->dev_select(ap, 0);
2458
2459         /* if no devices were detected, disable this port */
2460         if ((ap->device[0].class == ATA_DEV_NONE) &&
2461             (ap->device[1].class == ATA_DEV_NONE))
2462                 goto err_out;
2463
2464         if (ap->flags & (ATA_FLAG_SATA_RESET | ATA_FLAG_SRST)) {
2465                 /* set up device control for ATA_FLAG_SATA_RESET */
2466                 if (ap->flags & ATA_FLAG_MMIO)
2467                         writeb(ap->ctl, (void __iomem *) ioaddr->ctl_addr);
2468                 else
2469                         outb(ap->ctl, ioaddr->ctl_addr);
2470         }
2471
2472         DPRINTK("EXIT\n");
2473         return;
2474
2475 err_out:
2476         ata_port_printk(ap, KERN_ERR, "disabling port\n");
2477         ap->ops->port_disable(ap);
2478
2479         DPRINTK("EXIT\n");
2480 }
2481
2482 /**
2483  *      sata_phy_debounce - debounce SATA phy status
2484  *      @ap: ATA port to debounce SATA phy status for
2485  *      @params: timing parameters { interval, duratinon, timeout } in msec
2486  *
2487  *      Make sure SStatus of @ap reaches stable state, determined by
2488  *      holding the same value where DET is not 1 for @duration polled
2489  *      every @interval, before @timeout.  Timeout constraints the
2490  *      beginning of the stable state.  Because, after hot unplugging,
2491  *      DET gets stuck at 1 on some controllers, this functions waits
2492  *      until timeout then returns 0 if DET is stable at 1.
2493  *
2494  *      LOCKING:
2495  *      Kernel thread context (may sleep)
2496  *
2497  *      RETURNS:
2498  *      0 on success, -errno on failure.
2499  */
2500 int sata_phy_debounce(struct ata_port *ap, const unsigned long *params)
2501 {
2502         unsigned long interval_msec = params[0];
2503         unsigned long duration = params[1] * HZ / 1000;
2504         unsigned long timeout = jiffies + params[2] * HZ / 1000;
2505         unsigned long last_jiffies;
2506         u32 last, cur;
2507         int rc;
2508
2509         if ((rc = sata_scr_read(ap, SCR_STATUS, &cur)))
2510                 return rc;
2511         cur &= 0xf;
2512
2513         last = cur;
2514         last_jiffies = jiffies;
2515
2516         while (1) {
2517                 msleep(interval_msec);
2518                 if ((rc = sata_scr_read(ap, SCR_STATUS, &cur)))
2519                         return rc;
2520                 cur &= 0xf;
2521
2522                 /* DET stable? */
2523                 if (cur == last) {
2524                         if (cur == 1 && time_before(jiffies, timeout))
2525                                 continue;
2526                         if (time_after(jiffies, last_jiffies + duration))
2527                                 return 0;
2528                         continue;
2529                 }
2530
2531                 /* unstable, start over */
2532                 last = cur;
2533                 last_jiffies = jiffies;
2534
2535                 /* check timeout */
2536                 if (time_after(jiffies, timeout))
2537                         return -EBUSY;
2538         }
2539 }
2540
2541 /**
2542  *      sata_phy_resume - resume SATA phy
2543  *      @ap: ATA port to resume SATA phy for
2544  *      @params: timing parameters { interval, duratinon, timeout } in msec
2545  *
2546  *      Resume SATA phy of @ap and debounce it.
2547  *
2548  *      LOCKING:
2549  *      Kernel thread context (may sleep)
2550  *
2551  *      RETURNS:
2552  *      0 on success, -errno on failure.
2553  */
2554 int sata_phy_resume(struct ata_port *ap, const unsigned long *params)
2555 {
2556         u32 scontrol;
2557         int rc;
2558
2559         if ((rc = sata_scr_read(ap, SCR_CONTROL, &scontrol)))
2560                 return rc;
2561
2562         scontrol = (scontrol & 0x0f0) | 0x300;
2563
2564         if ((rc = sata_scr_write(ap, SCR_CONTROL, scontrol)))
2565                 return rc;
2566
2567         /* Some PHYs react badly if SStatus is pounded immediately
2568          * after resuming.  Delay 200ms before debouncing.
2569          */
2570         msleep(200);
2571
2572         return sata_phy_debounce(ap, params);
2573 }
2574
2575 static void ata_wait_spinup(struct ata_port *ap)
2576 {
2577         struct ata_eh_context *ehc = &ap->eh_context;
2578         unsigned long end, secs;
2579         int rc;
2580
2581         /* first, debounce phy if SATA */
2582         if (ap->cbl == ATA_CBL_SATA) {
2583                 rc = sata_phy_debounce(ap, sata_deb_timing_eh);
2584
2585                 /* if debounced successfully and offline, no need to wait */
2586                 if ((rc == 0 || rc == -EOPNOTSUPP) && ata_port_offline(ap))
2587                         return;
2588         }
2589
2590         /* okay, let's give the drive time to spin up */
2591         end = ehc->i.hotplug_timestamp + ATA_SPINUP_WAIT * HZ / 1000;
2592         secs = ((end - jiffies) + HZ - 1) / HZ;
2593
2594         if (time_after(jiffies, end))
2595                 return;
2596
2597         if (secs > 5)
2598                 ata_port_printk(ap, KERN_INFO, "waiting for device to spin up "
2599                                 "(%lu secs)\n", secs);
2600
2601         schedule_timeout_uninterruptible(end - jiffies);
2602 }
2603
2604 /**
2605  *      ata_std_prereset - prepare for reset
2606  *      @ap: ATA port to be reset
2607  *
2608  *      @ap is about to be reset.  Initialize it.
2609  *
2610  *      LOCKING:
2611  *      Kernel thread context (may sleep)
2612  *
2613  *      RETURNS:
2614  *      0 on success, -errno otherwise.
2615  */
2616 int ata_std_prereset(struct ata_port *ap)
2617 {
2618         struct ata_eh_context *ehc = &ap->eh_context;
2619         const unsigned long *timing;
2620         int rc;
2621
2622         /* hotplug? */
2623         if (ehc->i.flags & ATA_EHI_HOTPLUGGED) {
2624                 if (ap->flags & ATA_FLAG_HRST_TO_RESUME)
2625                         ehc->i.action |= ATA_EH_HARDRESET;
2626                 if (ap->flags & ATA_FLAG_SKIP_D2H_BSY)
2627                         ata_wait_spinup(ap);
2628         }
2629
2630         /* if we're about to do hardreset, nothing more to do */
2631         if (ehc->i.action & ATA_EH_HARDRESET)
2632                 return 0;
2633
2634         /* if SATA, resume phy */
2635         if (ap->cbl == ATA_CBL_SATA) {
2636                 if (ap->flags & ATA_FLAG_LOADING)
2637                         timing = sata_deb_timing_boot;
2638                 else
2639                         timing = sata_deb_timing_eh;
2640
2641                 rc = sata_phy_resume(ap, timing);
2642                 if (rc && rc != -EOPNOTSUPP) {
2643                         /* phy resume failed */
2644                         ata_port_printk(ap, KERN_WARNING, "failed to resume "
2645                                         "link for reset (errno=%d)\n", rc);
2646                         return rc;
2647                 }
2648         }
2649
2650         /* Wait for !BSY if the controller can wait for the first D2H
2651          * Reg FIS and we don't know that no device is attached.
2652          */
2653         if (!(ap->flags & ATA_FLAG_SKIP_D2H_BSY) && !ata_port_offline(ap))
2654                 ata_busy_sleep(ap, ATA_TMOUT_BOOT_QUICK, ATA_TMOUT_BOOT);
2655
2656         return 0;
2657 }
2658
2659 /**
2660  *      ata_std_softreset - reset host port via ATA SRST
2661  *      @ap: port to reset
2662  *      @classes: resulting classes of attached devices
2663  *
2664  *      Reset host port using ATA SRST.
2665  *
2666  *      LOCKING:
2667  *      Kernel thread context (may sleep)
2668  *
2669  *      RETURNS:
2670  *      0 on success, -errno otherwise.
2671  */
2672 int ata_std_softreset(struct ata_port *ap, unsigned int *classes)
2673 {
2674         unsigned int slave_possible = ap->flags & ATA_FLAG_SLAVE_POSS;
2675         unsigned int devmask = 0, err_mask;
2676         u8 err;
2677
2678         DPRINTK("ENTER\n");
2679
2680         if (ata_port_offline(ap)) {
2681                 classes[0] = ATA_DEV_NONE;
2682                 goto out;
2683         }
2684
2685         /* determine if device 0/1 are present */
2686         if (ata_devchk(ap, 0))
2687                 devmask |= (1 << 0);
2688         if (slave_possible && ata_devchk(ap, 1))
2689                 devmask |= (1 << 1);
2690
2691         /* select device 0 again */
2692         ap->ops->dev_select(ap, 0);
2693
2694         /* issue bus reset */
2695         DPRINTK("about to softreset, devmask=%x\n", devmask);
2696         err_mask = ata_bus_softreset(ap, devmask);
2697         if (err_mask) {
2698                 ata_port_printk(ap, KERN_ERR, "SRST failed (err_mask=0x%x)\n",
2699                                 err_mask);
2700                 return -EIO;
2701         }
2702
2703         /* determine by signature whether we have ATA or ATAPI devices */
2704         classes[0] = ata_dev_try_classify(ap, 0, &err);
2705         if (slave_possible && err != 0x81)
2706                 classes[1] = ata_dev_try_classify(ap, 1, &err);
2707
2708  out:
2709         DPRINTK("EXIT, classes[0]=%u [1]=%u\n", classes[0], classes[1]);
2710         return 0;
2711 }
2712
2713 /**
2714  *      sata_std_hardreset - reset host port via SATA phy reset
2715  *      @ap: port to reset
2716  *      @class: resulting class of attached device
2717  *
2718  *      SATA phy-reset host port using DET bits of SControl register.
2719  *
2720  *      LOCKING:
2721  *      Kernel thread context (may sleep)
2722  *
2723  *      RETURNS:
2724  *      0 on success, -errno otherwise.
2725  */
2726 int sata_std_hardreset(struct ata_port *ap, unsigned int *class)
2727 {
2728         u32 scontrol;
2729         int rc;
2730
2731         DPRINTK("ENTER\n");
2732
2733         if (sata_set_spd_needed(ap)) {
2734                 /* SATA spec says nothing about how to reconfigure
2735                  * spd.  To be on the safe side, turn off phy during
2736                  * reconfiguration.  This works for at least ICH7 AHCI
2737                  * and Sil3124.
2738                  */
2739                 if ((rc = sata_scr_read(ap, SCR_CONTROL, &scontrol)))
2740                         return rc;
2741
2742                 scontrol = (scontrol & 0x0f0) | 0x302;
2743
2744                 if ((rc = sata_scr_write(ap, SCR_CONTROL, scontrol)))
2745                         return rc;
2746
2747                 sata_set_spd(ap);
2748         }
2749
2750         /* issue phy wake/reset */
2751         if ((rc = sata_scr_read(ap, SCR_CONTROL, &scontrol)))
2752                 return rc;
2753
2754         scontrol = (scontrol & 0x0f0) | 0x301;
2755
2756         if ((rc = sata_scr_write_flush(ap, SCR_CONTROL, scontrol)))
2757                 return rc;
2758
2759         /* Couldn't find anything in SATA I/II specs, but AHCI-1.1
2760          * 10.4.2 says at least 1 ms.
2761          */
2762         msleep(1);
2763
2764         /* bring phy back */
2765         sata_phy_resume(ap, sata_deb_timing_eh);
2766
2767         /* TODO: phy layer with polling, timeouts, etc. */
2768         if (ata_port_offline(ap)) {
2769                 *class = ATA_DEV_NONE;
2770                 DPRINTK("EXIT, link offline\n");
2771                 return 0;
2772         }
2773
2774         if (ata_busy_sleep(ap, ATA_TMOUT_BOOT_QUICK, ATA_TMOUT_BOOT)) {
2775                 ata_port_printk(ap, KERN_ERR,
2776                                 "COMRESET failed (device not ready)\n");
2777                 return -EIO;
2778         }
2779
2780         ap->ops->dev_select(ap, 0);     /* probably unnecessary */
2781
2782         *class = ata_dev_try_classify(ap, 0, NULL);
2783
2784         DPRINTK("EXIT, class=%u\n", *class);
2785         return 0;
2786 }
2787
2788 /**
2789  *      ata_std_postreset - standard postreset callback
2790  *      @ap: the target ata_port
2791  *      @classes: classes of attached devices
2792  *
2793  *      This function is invoked after a successful reset.  Note that
2794  *      the device might have been reset more than once using
2795  *      different reset methods before postreset is invoked.
2796  *
2797  *      LOCKING:
2798  *      Kernel thread context (may sleep)
2799  */
2800 void ata_std_postreset(struct ata_port *ap, unsigned int *classes)
2801 {
2802         u32 serror;
2803
2804         DPRINTK("ENTER\n");
2805
2806         /* print link status */
2807         sata_print_link_status(ap);
2808
2809         /* clear SError */
2810         if (sata_scr_read(ap, SCR_ERROR, &serror) == 0)
2811                 sata_scr_write(ap, SCR_ERROR, serror);
2812
2813         /* re-enable interrupts */
2814         if (!ap->ops->error_handler) {
2815                 /* FIXME: hack. create a hook instead */
2816                 if (ap->ioaddr.ctl_addr)
2817                         ata_irq_on(ap);
2818         }
2819
2820         /* is double-select really necessary? */
2821         if (classes[0] != ATA_DEV_NONE)
2822                 ap->ops->dev_select(ap, 1);
2823         if (classes[1] != ATA_DEV_NONE)
2824                 ap->ops->dev_select(ap, 0);
2825
2826         /* bail out if no device is present */
2827         if (classes[0] == ATA_DEV_NONE && classes[1] == ATA_DEV_NONE) {
2828                 DPRINTK("EXIT, no device\n");
2829                 return;
2830         }
2831
2832         /* set up device control */
2833         if (ap->ioaddr.ctl_addr) {
2834                 if (ap->flags & ATA_FLAG_MMIO)
2835                         writeb(ap->ctl, (void __iomem *) ap->ioaddr.ctl_addr);
2836                 else
2837                         outb(ap->ctl, ap->ioaddr.ctl_addr);
2838         }
2839
2840         DPRINTK("EXIT\n");
2841 }
2842
2843 /**
2844  *      ata_dev_same_device - Determine whether new ID matches configured device
2845  *      @dev: device to compare against
2846  *      @new_class: class of the new device
2847  *      @new_id: IDENTIFY page of the new device
2848  *
2849  *      Compare @new_class and @new_id against @dev and determine
2850  *      whether @dev is the device indicated by @new_class and
2851  *      @new_id.
2852  *
2853  *      LOCKING:
2854  *      None.
2855  *
2856  *      RETURNS:
2857  *      1 if @dev matches @new_class and @new_id, 0 otherwise.
2858  */
2859 static int ata_dev_same_device(struct ata_device *dev, unsigned int new_class,
2860                                const u16 *new_id)
2861 {
2862         const u16 *old_id = dev->id;
2863         unsigned char model[2][41], serial[2][21];
2864         u64 new_n_sectors;
2865
2866         if (dev->class != new_class) {
2867                 ata_dev_printk(dev, KERN_INFO, "class mismatch %d != %d\n",
2868                                dev->class, new_class);
2869                 return 0;
2870         }
2871
2872         ata_id_c_string(old_id, model[0], ATA_ID_PROD_OFS, sizeof(model[0]));
2873         ata_id_c_string(new_id, model[1], ATA_ID_PROD_OFS, sizeof(model[1]));
2874         ata_id_c_string(old_id, serial[0], ATA_ID_SERNO_OFS, sizeof(serial[0]));
2875         ata_id_c_string(new_id, serial[1], ATA_ID_SERNO_OFS, sizeof(serial[1]));
2876         new_n_sectors = ata_id_n_sectors(new_id);
2877
2878         if (strcmp(model[0], model[1])) {
2879                 ata_dev_printk(dev, KERN_INFO, "model number mismatch "
2880                                "'%s' != '%s'\n", model[0], model[1]);
2881                 return 0;
2882         }
2883
2884         if (strcmp(serial[0], serial[1])) {
2885                 ata_dev_printk(dev, KERN_INFO, "serial number mismatch "
2886                                "'%s' != '%s'\n", serial[0], serial[1]);
2887                 return 0;
2888         }
2889
2890         if (dev->class == ATA_DEV_ATA && dev->n_sectors != new_n_sectors) {
2891                 ata_dev_printk(dev, KERN_INFO, "n_sectors mismatch "
2892                                "%llu != %llu\n",
2893                                (unsigned long long)dev->n_sectors,
2894                                (unsigned long long)new_n_sectors);
2895                 return 0;
2896         }
2897
2898         return 1;
2899 }
2900
2901 /**
2902  *      ata_dev_revalidate - Revalidate ATA device
2903  *      @dev: device to revalidate
2904  *      @post_reset: is this revalidation after reset?
2905  *
2906  *      Re-read IDENTIFY page and make sure @dev is still attached to
2907  *      the port.
2908  *
2909  *      LOCKING:
2910  *      Kernel thread context (may sleep)
2911  *
2912  *      RETURNS:
2913  *      0 on success, negative errno otherwise
2914  */
2915 int ata_dev_revalidate(struct ata_device *dev, int post_reset)
2916 {
2917         unsigned int class = dev->class;
2918         u16 *id = (void *)dev->ap->sector_buf;
2919         int rc;
2920
2921         if (!ata_dev_enabled(dev)) {
2922                 rc = -ENODEV;
2923                 goto fail;
2924         }
2925
2926         /* read ID data */
2927         rc = ata_dev_read_id(dev, &class, post_reset, id);
2928         if (rc)
2929                 goto fail;
2930
2931         /* is the device still there? */
2932         if (!ata_dev_same_device(dev, class, id)) {
2933                 rc = -ENODEV;
2934                 goto fail;
2935         }
2936
2937         memcpy(dev->id, id, sizeof(id[0]) * ATA_ID_WORDS);
2938
2939         /* configure device according to the new ID */
2940         rc = ata_dev_configure(dev, 0);
2941         if (rc == 0)
2942                 return 0;
2943
2944  fail:
2945         ata_dev_printk(dev, KERN_ERR, "revalidation failed (errno=%d)\n", rc);
2946         return rc;
2947 }
2948
2949 static const char * const ata_dma_blacklist [] = {
2950         "WDC AC11000H", NULL,
2951         "WDC AC22100H", NULL,
2952         "WDC AC32500H", NULL,
2953         "WDC AC33100H", NULL,
2954         "WDC AC31600H", NULL,
2955         "WDC AC32100H", "24.09P07",
2956         "WDC AC23200L", "21.10N21",
2957         "Compaq CRD-8241B",  NULL,
2958         "CRD-8400B", NULL,
2959         "CRD-8480B", NULL,
2960         "CRD-8482B", NULL,
2961         "CRD-84", NULL,
2962         "SanDisk SDP3B", NULL,
2963         "SanDisk SDP3B-64", NULL,
2964         "SANYO CD-ROM CRD", NULL,
2965         "HITACHI CDR-8", NULL,
2966         "HITACHI CDR-8335", NULL,
2967         "HITACHI CDR-8435", NULL,
2968         "Toshiba CD-ROM XM-6202B", NULL,
2969         "TOSHIBA CD-ROM XM-1702BC", NULL,
2970         "CD-532E-A", NULL,
2971         "E-IDE CD-ROM CR-840", NULL,
2972         "CD-ROM Drive/F5A", NULL,
2973         "WPI CDD-820", NULL,
2974         "SAMSUNG CD-ROM SC-148C", NULL,
2975         "SAMSUNG CD-ROM SC", NULL,
2976         "SanDisk SDP3B-64", NULL,
2977         "ATAPI CD-ROM DRIVE 40X MAXIMUM",NULL,
2978         "_NEC DV5800A", NULL,
2979         "SAMSUNG CD-ROM SN-124", "N001"
2980 };
2981
2982 static int ata_strim(char *s, size_t len)
2983 {
2984         len = strnlen(s, len);
2985
2986         /* ATAPI specifies that empty space is blank-filled; remove blanks */
2987         while ((len > 0) && (s[len - 1] == ' ')) {
2988                 len--;
2989                 s[len] = 0;
2990         }
2991         return len;
2992 }
2993
2994 static int ata_dma_blacklisted(const struct ata_device *dev)
2995 {
2996         unsigned char model_num[40];
2997         unsigned char model_rev[16];
2998         unsigned int nlen, rlen;
2999         int i;
3000
3001         /* We don't support polling DMA.
3002          * DMA blacklist those ATAPI devices with CDB-intr (and use PIO)
3003          * if the LLDD handles only interrupts in the HSM_ST_LAST state.
3004          */
3005         if ((dev->ap->flags & ATA_FLAG_PIO_POLLING) &&
3006             (dev->flags & ATA_DFLAG_CDB_INTR))
3007                 return 1;
3008
3009         ata_id_string(dev->id, model_num, ATA_ID_PROD_OFS,
3010                           sizeof(model_num));
3011         ata_id_string(dev->id, model_rev, ATA_ID_FW_REV_OFS,
3012                           sizeof(model_rev));
3013         nlen = ata_strim(model_num, sizeof(model_num));
3014         rlen = ata_strim(model_rev, sizeof(model_rev));
3015
3016         for (i = 0; i < ARRAY_SIZE(ata_dma_blacklist); i += 2) {
3017                 if (!strncmp(ata_dma_blacklist[i], model_num, nlen)) {
3018                         if (ata_dma_blacklist[i+1] == NULL)
3019                                 return 1;
3020                         if (!strncmp(ata_dma_blacklist[i], model_rev, rlen))
3021                                 return 1;
3022                 }
3023         }
3024         return 0;
3025 }
3026
3027 /**
3028  *      ata_dev_xfermask - Compute supported xfermask of the given device
3029  *      @dev: Device to compute xfermask for
3030  *
3031  *      Compute supported xfermask of @dev and store it in
3032  *      dev->*_mask.  This function is responsible for applying all
3033  *      known limits including host controller limits, device
3034  *      blacklist, etc...
3035  *
3036  *      FIXME: The current implementation limits all transfer modes to
3037  *      the fastest of the lowested device on the port.  This is not
3038  *      required on most controllers.
3039  *
3040  *      LOCKING:
3041  *      None.
3042  */
3043 static void ata_dev_xfermask(struct ata_device *dev)
3044 {
3045         struct ata_port *ap = dev->ap;
3046         struct ata_host_set *hs = ap->host_set;
3047         unsigned long xfer_mask;
3048         int i;
3049
3050         xfer_mask = ata_pack_xfermask(ap->pio_mask,
3051                                       ap->mwdma_mask, ap->udma_mask);
3052
3053         /* Apply cable rule here.  Don't apply it early because when
3054          * we handle hot plug the cable type can itself change.
3055          */
3056         if (ap->cbl == ATA_CBL_PATA40)
3057                 xfer_mask &= ~(0xF8 << ATA_SHIFT_UDMA);
3058
3059         /* FIXME: Use port-wide xfermask for now */
3060         for (i = 0; i < ATA_MAX_DEVICES; i++) {
3061                 struct ata_device *d = &ap->device[i];
3062
3063                 if (ata_dev_absent(d))
3064                         continue;
3065
3066                 if (ata_dev_disabled(d)) {
3067                         /* to avoid violating device selection timing */
3068                         xfer_mask &= ata_pack_xfermask(d->pio_mask,
3069                                                        UINT_MAX, UINT_MAX);
3070                         continue;
3071                 }
3072
3073                 xfer_mask &= ata_pack_xfermask(d->pio_mask,
3074                                                d->mwdma_mask, d->udma_mask);
3075                 xfer_mask &= ata_id_xfermask(d->id);
3076                 if (ata_dma_blacklisted(d))
3077                         xfer_mask &= ~(ATA_MASK_MWDMA | ATA_MASK_UDMA);
3078         }
3079
3080         if (ata_dma_blacklisted(dev))
3081                 ata_dev_printk(dev, KERN_WARNING,
3082                                "device is on DMA blacklist, disabling DMA\n");
3083
3084         if (hs->flags & ATA_HOST_SIMPLEX) {
3085                 if (hs->simplex_claimed)
3086                         xfer_mask &= ~(ATA_MASK_MWDMA | ATA_MASK_UDMA);
3087         }
3088
3089         if (ap->ops->mode_filter)
3090                 xfer_mask = ap->ops->mode_filter(ap, dev, xfer_mask);
3091
3092         ata_unpack_xfermask(xfer_mask, &dev->pio_mask,
3093                             &dev->mwdma_mask, &dev->udma_mask);
3094 }
3095
3096 /**
3097  *      ata_dev_set_xfermode - Issue SET FEATURES - XFER MODE command
3098  *      @dev: Device to which command will be sent
3099  *
3100  *      Issue SET FEATURES - XFER MODE command to device @dev
3101  *      on port @ap.
3102  *
3103  *      LOCKING:
3104  *      PCI/etc. bus probe sem.
3105  *
3106  *      RETURNS:
3107  *      0 on success, AC_ERR_* mask otherwise.
3108  */
3109
3110 static unsigned int ata_dev_set_xfermode(struct ata_device *dev)
3111 {
3112         struct ata_taskfile tf;
3113         unsigned int err_mask;
3114
3115         /* set up set-features taskfile */
3116         DPRINTK("set features - xfer mode\n");
3117
3118         ata_tf_init(dev, &tf);
3119         tf.command = ATA_CMD_SET_FEATURES;
3120         tf.feature = SETFEATURES_XFER;
3121         tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
3122         tf.protocol = ATA_PROT_NODATA;
3123         tf.nsect = dev->xfer_mode;
3124
3125         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0);
3126
3127         DPRINTK("EXIT, err_mask=%x\n", err_mask);
3128         return err_mask;
3129 }
3130
3131 /**
3132  *      ata_dev_init_params - Issue INIT DEV PARAMS command
3133  *      @dev: Device to which command will be sent
3134  *      @heads: Number of heads (taskfile parameter)
3135  *      @sectors: Number of sectors (taskfile parameter)
3136  *
3137  *      LOCKING:
3138  *      Kernel thread context (may sleep)
3139  *
3140  *      RETURNS:
3141  *      0 on success, AC_ERR_* mask otherwise.
3142  */
3143 static unsigned int ata_dev_init_params(struct ata_device *dev,
3144                                         u16 heads, u16 sectors)
3145 {
3146         struct ata_taskfile tf;
3147         unsigned int err_mask;
3148
3149         /* Number of sectors per track 1-255. Number of heads 1-16 */
3150         if (sectors < 1 || sectors > 255 || heads < 1 || heads > 16)
3151                 return AC_ERR_INVALID;
3152
3153         /* set up init dev params taskfile */
3154         DPRINTK("init dev params \n");
3155
3156         ata_tf_init(dev, &tf);
3157         tf.command = ATA_CMD_INIT_DEV_PARAMS;
3158         tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
3159         tf.protocol = ATA_PROT_NODATA;
3160         tf.nsect = sectors;
3161         tf.device |= (heads - 1) & 0x0f; /* max head = num. of heads - 1 */
3162
3163         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0);
3164
3165         DPRINTK("EXIT, err_mask=%x\n", err_mask);
3166         return err_mask;
3167 }
3168
3169 /**
3170  *      ata_sg_clean - Unmap DMA memory associated with command
3171  *      @qc: Command containing DMA memory to be released
3172  *
3173  *      Unmap all mapped DMA memory associated with this command.
3174  *
3175  *      LOCKING:
3176  *      spin_lock_irqsave(host_set lock)
3177  */
3178
3179 static void ata_sg_clean(struct ata_queued_cmd *qc)
3180 {
3181         struct ata_port *ap = qc->ap;
3182         struct scatterlist *sg = qc->__sg;
3183         int dir = qc->dma_dir;
3184         void *pad_buf = NULL;
3185
3186         WARN_ON(!(qc->flags & ATA_QCFLAG_DMAMAP));
3187         WARN_ON(sg == NULL);
3188
3189         if (qc->flags & ATA_QCFLAG_SINGLE)
3190                 WARN_ON(qc->n_elem > 1);
3191
3192         VPRINTK("unmapping %u sg elements\n", qc->n_elem);
3193
3194         /* if we padded the buffer out to 32-bit bound, and data
3195          * xfer direction is from-device, we must copy from the
3196          * pad buffer back into the supplied buffer
3197          */
3198         if (qc->pad_len && !(qc->tf.flags & ATA_TFLAG_WRITE))
3199                 pad_buf = ap->pad + (qc->tag * ATA_DMA_PAD_SZ);
3200
3201         if (qc->flags & ATA_QCFLAG_SG) {
3202                 if (qc->n_elem)
3203                         dma_unmap_sg(ap->dev, sg, qc->n_elem, dir);
3204                 /* restore last sg */
3205                 sg[qc->orig_n_elem - 1].length += qc->pad_len;
3206                 if (pad_buf) {
3207                         struct scatterlist *psg = &qc->pad_sgent;
3208                         void *addr = kmap_atomic(psg->page, KM_IRQ0);
3209                         memcpy(addr + psg->offset, pad_buf, qc->pad_len);
3210                         kunmap_atomic(addr, KM_IRQ0);
3211                 }
3212         } else {
3213                 if (qc->n_elem)
3214                         dma_unmap_single(ap->dev,
3215                                 sg_dma_address(&sg[0]), sg_dma_len(&sg[0]),
3216                                 dir);
3217                 /* restore sg */
3218                 sg->length += qc->pad_len;
3219                 if (pad_buf)
3220                         memcpy(qc->buf_virt + sg->length - qc->pad_len,
3221                                pad_buf, qc->pad_len);
3222         }
3223
3224         qc->flags &= ~ATA_QCFLAG_DMAMAP;
3225         qc->__sg = NULL;
3226 }
3227
3228 /**
3229  *      ata_fill_sg - Fill PCI IDE PRD table
3230  *      @qc: Metadata associated with taskfile to be transferred
3231  *
3232  *      Fill PCI IDE PRD (scatter-gather) table with segments
3233  *      associated with the current disk command.
3234  *
3235  *      LOCKING:
3236  *      spin_lock_irqsave(host_set lock)
3237  *
3238  */
3239 static void ata_fill_sg(struct ata_queued_cmd *qc)
3240 {
3241         struct ata_port *ap = qc->ap;
3242         struct scatterlist *sg;
3243         unsigned int idx;
3244
3245         WARN_ON(qc->__sg == NULL);
3246         WARN_ON(qc->n_elem == 0 && qc->pad_len == 0);
3247
3248         idx = 0;
3249         ata_for_each_sg(sg, qc) {
3250                 u32 addr, offset;
3251                 u32 sg_len, len;
3252
3253                 /* determine if physical DMA addr spans 64K boundary.
3254                  * Note h/w doesn't support 64-bit, so we unconditionally
3255                  * truncate dma_addr_t to u32.
3256                  */
3257                 addr = (u32) sg_dma_address(sg);
3258                 sg_len = sg_dma_len(sg);
3259
3260                 while (sg_len) {
3261                         offset = addr & 0xffff;
3262                         len = sg_len;
3263                         if ((offset + sg_len) > 0x10000)
3264                                 len = 0x10000 - offset;
3265
3266                         ap->prd[idx].addr = cpu_to_le32(addr);
3267                         ap->prd[idx].flags_len = cpu_to_le32(len & 0xffff);
3268                         VPRINTK("PRD[%u] = (0x%X, 0x%X)\n", idx, addr, len);
3269
3270                         idx++;
3271                         sg_len -= len;
3272                         addr += len;
3273                 }
3274         }
3275
3276         if (idx)
3277                 ap->prd[idx - 1].flags_len |= cpu_to_le32(ATA_PRD_EOT);
3278 }
3279 /**
3280  *      ata_check_atapi_dma - Check whether ATAPI DMA can be supported
3281  *      @qc: Metadata associated with taskfile to check
3282  *
3283  *      Allow low-level driver to filter ATA PACKET commands, returning
3284  *      a status indicating whether or not it is OK to use DMA for the
3285  *      supplied PACKET command.
3286  *
3287  *      LOCKING:
3288  *      spin_lock_irqsave(host_set lock)
3289  *
3290  *      RETURNS: 0 when ATAPI DMA can be used
3291  *               nonzero otherwise
3292  */
3293 int ata_check_atapi_dma(struct ata_queued_cmd *qc)
3294 {
3295         struct ata_port *ap = qc->ap;
3296         int rc = 0; /* Assume ATAPI DMA is OK by default */
3297
3298         if (ap->ops->check_atapi_dma)
3299                 rc = ap->ops->check_atapi_dma(qc);
3300
3301         return rc;
3302 }
3303 /**
3304  *      ata_qc_prep - Prepare taskfile for submission
3305  *      @qc: Metadata associated with taskfile to be prepared
3306  *
3307  *      Prepare ATA taskfile for submission.
3308  *
3309  *      LOCKING:
3310  *      spin_lock_irqsave(host_set lock)
3311  */
3312 void ata_qc_prep(struct ata_queued_cmd *qc)
3313 {
3314         if (!(qc->flags & ATA_QCFLAG_DMAMAP))
3315                 return;
3316
3317         ata_fill_sg(qc);
3318 }
3319
3320 void ata_noop_qc_prep(struct ata_queued_cmd *qc) { }
3321
3322 /**
3323  *      ata_sg_init_one - Associate command with memory buffer
3324  *      @qc: Command to be associated
3325  *      @buf: Memory buffer
3326  *      @buflen: Length of memory buffer, in bytes.
3327  *
3328  *      Initialize the data-related elements of queued_cmd @qc
3329  *      to point to a single memory buffer, @buf of byte length @buflen.
3330  *
3331  *      LOCKING:
3332  *      spin_lock_irqsave(host_set lock)
3333  */
3334
3335 void ata_sg_init_one(struct ata_queued_cmd *qc, void *buf, unsigned int buflen)
3336 {
3337         struct scatterlist *sg;
3338
3339         qc->flags |= ATA_QCFLAG_SINGLE;
3340
3341         memset(&qc->sgent, 0, sizeof(qc->sgent));
3342         qc->__sg = &qc->sgent;
3343         qc->n_elem = 1;
3344         qc->orig_n_elem = 1;
3345         qc->buf_virt = buf;
3346         qc->nbytes = buflen;
3347
3348         sg = qc->__sg;
3349         sg_init_one(sg, buf, buflen);
3350 }
3351
3352 /**
3353  *      ata_sg_init - Associate command with scatter-gather table.
3354  *      @qc: Command to be associated
3355  *      @sg: Scatter-gather table.
3356  *      @n_elem: Number of elements in s/g table.
3357  *
3358  *      Initialize the data-related elements of queued_cmd @qc
3359  *      to point to a scatter-gather table @sg, containing @n_elem
3360  *      elements.
3361  *
3362  *      LOCKING:
3363  *      spin_lock_irqsave(host_set lock)
3364  */
3365
3366 void ata_sg_init(struct ata_queued_cmd *qc, struct scatterlist *sg,
3367                  unsigned int n_elem)
3368 {
3369         qc->flags |= ATA_QCFLAG_SG;
3370         qc->__sg = sg;
3371         qc->n_elem = n_elem;
3372         qc->orig_n_elem = n_elem;
3373 }
3374
3375 /**
3376  *      ata_sg_setup_one - DMA-map the memory buffer associated with a command.
3377  *      @qc: Command with memory buffer to be mapped.
3378  *
3379  *      DMA-map the memory buffer associated with queued_cmd @qc.
3380  *
3381  *      LOCKING:
3382  *      spin_lock_irqsave(host_set lock)
3383  *
3384  *      RETURNS:
3385  *      Zero on success, negative on error.
3386  */
3387
3388 static int ata_sg_setup_one(struct ata_queued_cmd *qc)
3389 {
3390         struct ata_port *ap = qc->ap;
3391         int dir = qc->dma_dir;
3392         struct scatterlist *sg = qc->__sg;
3393         dma_addr_t dma_address;
3394         int trim_sg = 0;
3395
3396         /* we must lengthen transfers to end on a 32-bit boundary */
3397         qc->pad_len = sg->length & 3;
3398         if (qc->pad_len) {
3399                 void *pad_buf = ap->pad + (qc->tag * ATA_DMA_PAD_SZ);
3400                 struct scatterlist *psg = &qc->pad_sgent;
3401
3402                 WARN_ON(qc->dev->class != ATA_DEV_ATAPI);
3403
3404                 memset(pad_buf, 0, ATA_DMA_PAD_SZ);
3405
3406                 if (qc->tf.flags & ATA_TFLAG_WRITE)
3407                         memcpy(pad_buf, qc->buf_virt + sg->length - qc->pad_len,
3408                                qc->pad_len);
3409
3410                 sg_dma_address(psg) = ap->pad_dma + (qc->tag * ATA_DMA_PAD_SZ);
3411                 sg_dma_len(psg) = ATA_DMA_PAD_SZ;
3412                 /* trim sg */
3413                 sg->length -= qc->pad_len;
3414                 if (sg->length == 0)
3415                         trim_sg = 1;
3416
3417                 DPRINTK("padding done, sg->length=%u pad_len=%u\n",
3418                         sg->length, qc->pad_len);
3419         }
3420
3421         if (trim_sg) {
3422                 qc->n_elem--;
3423                 goto skip_map;
3424         }
3425
3426         dma_address = dma_map_single(ap->dev, qc->buf_virt,
3427                                      sg->length, dir);
3428         if (dma_mapping_error(dma_address)) {
3429                 /* restore sg */
3430                 sg->length += qc->pad_len;
3431                 return -1;
3432         }
3433
3434         sg_dma_address(sg) = dma_address;
3435         sg_dma_len(sg) = sg->length;
3436
3437 skip_map:
3438         DPRINTK("mapped buffer of %d bytes for %s\n", sg_dma_len(sg),
3439                 qc->tf.flags & ATA_TFLAG_WRITE ? "write" : "read");
3440
3441         return 0;
3442 }
3443
3444 /**
3445  *      ata_sg_setup - DMA-map the scatter-gather table associated with a command.
3446  *      @qc: Command with scatter-gather table to be mapped.
3447  *
3448  *      DMA-map the scatter-gather table associated with queued_cmd @qc.
3449  *
3450  *      LOCKING:
3451  *      spin_lock_irqsave(host_set lock)
3452  *
3453  *      RETURNS:
3454  *      Zero on success, negative on error.
3455  *
3456  */
3457
3458 static int ata_sg_setup(struct ata_queued_cmd *qc)
3459 {
3460         struct ata_port *ap = qc->ap;
3461         struct scatterlist *sg = qc->__sg;
3462         struct scatterlist *lsg = &sg[qc->n_elem - 1];
3463         int n_elem, pre_n_elem, dir, trim_sg = 0;
3464
3465         VPRINTK("ENTER, ata%u\n", ap->id);
3466         WARN_ON(!(qc->flags & ATA_QCFLAG_SG));
3467
3468         /* we must lengthen transfers to end on a 32-bit boundary */
3469         qc->pad_len = lsg->length & 3;
3470         if (qc->pad_len) {
3471                 void *pad_buf = ap->pad + (qc->tag * ATA_DMA_PAD_SZ);
3472                 struct scatterlist *psg = &qc->pad_sgent;
3473                 unsigned int offset;
3474
3475                 WARN_ON(qc->dev->class != ATA_DEV_ATAPI);
3476
3477                 memset(pad_buf, 0, ATA_DMA_PAD_SZ);
3478
3479                 /*
3480                  * psg->page/offset are used to copy to-be-written
3481                  * data in this function or read data in ata_sg_clean.
3482                  */
3483                 offset = lsg->offset + lsg->length - qc->pad_len;
3484                 psg->page = nth_page(lsg->page, offset >> PAGE_SHIFT);
3485                 psg->offset = offset_in_page(offset);
3486
3487                 if (qc->tf.flags & ATA_TFLAG_WRITE) {
3488                         void *addr = kmap_atomic(psg->page, KM_IRQ0);
3489                         memcpy(pad_buf, addr + psg->offset, qc->pad_len);
3490                         kunmap_atomic(addr, KM_IRQ0);
3491                 }
3492
3493                 sg_dma_address(psg) = ap->pad_dma + (qc->tag * ATA_DMA_PAD_SZ);
3494                 sg_dma_len(psg) = ATA_DMA_PAD_SZ;
3495                 /* trim last sg */
3496                 lsg->length -= qc->pad_len;
3497                 if (lsg->length == 0)
3498                         trim_sg = 1;
3499
3500                 DPRINTK("padding done, sg[%d].length=%u pad_len=%u\n",
3501                         qc->n_elem - 1, lsg->length, qc->pad_len);
3502         }
3503
3504         pre_n_elem = qc->n_elem;
3505         if (trim_sg && pre_n_elem)
3506                 pre_n_elem--;
3507
3508         if (!pre_n_elem) {
3509                 n_elem = 0;
3510                 goto skip_map;
3511         }
3512
3513         dir = qc->dma_dir;
3514         n_elem = dma_map_sg(ap->dev, sg, pre_n_elem, dir);
3515         if (n_elem < 1) {
3516                 /* restore last sg */
3517                 lsg->length += qc->pad_len;
3518                 return -1;
3519         }
3520
3521         DPRINTK("%d sg elements mapped\n", n_elem);
3522
3523 skip_map:
3524         qc->n_elem = n_elem;
3525
3526         return 0;
3527 }
3528
3529 /**
3530  *      swap_buf_le16 - swap halves of 16-bit words in place
3531  *      @buf:  Buffer to swap
3532  *      @buf_words:  Number of 16-bit words in buffer.
3533  *
3534  *      Swap halves of 16-bit words if needed to convert from
3535  *      little-endian byte order to native cpu byte order, or
3536  *      vice-versa.
3537  *
3538  *      LOCKING:
3539  *      Inherited from caller.
3540  */
3541 void swap_buf_le16(u16 *buf, unsigned int buf_words)
3542 {
3543 #ifdef __BIG_ENDIAN
3544         unsigned int i;
3545
3546         for (i = 0; i < buf_words; i++)
3547                 buf[i] = le16_to_cpu(buf[i]);
3548 #endif /* __BIG_ENDIAN */
3549 }
3550
3551 /**
3552  *      ata_mmio_data_xfer - Transfer data by MMIO
3553  *      @adev: device for this I/O
3554  *      @buf: data buffer
3555  *      @buflen: buffer length
3556  *      @write_data: read/write
3557  *
3558  *      Transfer data from/to the device data register by MMIO.
3559  *
3560  *      LOCKING:
3561  *      Inherited from caller.
3562  */
3563
3564 void ata_mmio_data_xfer(struct ata_device *adev, unsigned char *buf,
3565                         unsigned int buflen, int write_data)
3566 {
3567         struct ata_port *ap = adev->ap;
3568         unsigned int i;
3569         unsigned int words = buflen >> 1;
3570         u16 *buf16 = (u16 *) buf;
3571         void __iomem *mmio = (void __iomem *)ap->ioaddr.data_addr;
3572
3573         /* Transfer multiple of 2 bytes */
3574         if (write_data) {
3575                 for (i = 0; i < words; i++)
3576                         writew(le16_to_cpu(buf16[i]), mmio);
3577         } else {
3578                 for (i = 0; i < words; i++)
3579                         buf16[i] = cpu_to_le16(readw(mmio));
3580         }
3581
3582         /* Transfer trailing 1 byte, if any. */
3583         if (unlikely(buflen & 0x01)) {
3584                 u16 align_buf[1] = { 0 };
3585                 unsigned char *trailing_buf = buf + buflen - 1;
3586
3587                 if (write_data) {
3588                         memcpy(align_buf, trailing_buf, 1);
3589                         writew(le16_to_cpu(align_buf[0]), mmio);
3590                 } else {
3591                         align_buf[0] = cpu_to_le16(readw(mmio));
3592                         memcpy(trailing_buf, align_buf, 1);
3593                 }
3594         }
3595 }
3596
3597 /**
3598  *      ata_pio_data_xfer - Transfer data by PIO
3599  *      @adev: device to target
3600  *      @buf: data buffer
3601  *      @buflen: buffer length
3602  *      @write_data: read/write
3603  *
3604  *      Transfer data from/to the device data register by PIO.
3605  *
3606  *      LOCKING:
3607  *      Inherited from caller.
3608  */
3609
3610 void ata_pio_data_xfer(struct ata_device *adev, unsigned char *buf,
3611                        unsigned int buflen, int write_data)
3612 {
3613         struct ata_port *ap = adev->ap;
3614         unsigned int words = buflen >> 1;
3615
3616         /* Transfer multiple of 2 bytes */
3617         if (write_data)
3618                 outsw(ap->ioaddr.data_addr, buf, words);
3619         else
3620                 insw(ap->ioaddr.data_addr, buf, words);
3621
3622         /* Transfer trailing 1 byte, if any. */
3623         if (unlikely(buflen & 0x01)) {
3624                 u16 align_buf[1] = { 0 };
3625                 unsigned char *trailing_buf = buf + buflen - 1;
3626
3627                 if (write_data) {
3628                         memcpy(align_buf, trailing_buf, 1);
3629                         outw(le16_to_cpu(align_buf[0]), ap->ioaddr.data_addr);
3630                 } else {
3631                         align_buf[0] = cpu_to_le16(inw(ap->ioaddr.data_addr));
3632                         memcpy(trailing_buf, align_buf, 1);
3633                 }
3634         }
3635 }
3636
3637 /**
3638  *      ata_pio_data_xfer_noirq - Transfer data by PIO
3639  *      @adev: device to target
3640  *      @buf: data buffer
3641  *      @buflen: buffer length
3642  *      @write_data: read/write
3643  *
3644  *      Transfer data from/to the device data register by PIO. Do the
3645  *      transfer with interrupts disabled.
3646  *
3647  *      LOCKING:
3648  *      Inherited from caller.
3649  */
3650
3651 void ata_pio_data_xfer_noirq(struct ata_device *adev, unsigned char *buf,
3652                                     unsigned int buflen, int write_data)
3653 {
3654         unsigned long flags;
3655         local_irq_save(flags);
3656         ata_pio_data_xfer(adev, buf, buflen, write_data);
3657         local_irq_restore(flags);
3658 }
3659
3660
3661 /**
3662  *      ata_pio_sector - Transfer ATA_SECT_SIZE (512 bytes) of data.
3663  *      @qc: Command on going
3664  *
3665  *      Transfer ATA_SECT_SIZE of data from/to the ATA device.
3666  *
3667  *      LOCKING:
3668  *      Inherited from caller.
3669  */
3670
3671 static void ata_pio_sector(struct ata_queued_cmd *qc)
3672 {
3673         int do_write = (qc->tf.flags & ATA_TFLAG_WRITE);
3674         struct scatterlist *sg = qc->__sg;
3675         struct ata_port *ap = qc->ap;
3676         struct page *page;
3677         unsigned int offset;
3678         unsigned char *buf;
3679
3680         if (qc->cursect == (qc->nsect - 1))
3681                 ap->hsm_task_state = HSM_ST_LAST;
3682
3683         page = sg[qc->cursg].page;
3684         offset = sg[qc->cursg].offset + qc->cursg_ofs * ATA_SECT_SIZE;
3685
3686         /* get the current page and offset */
3687         page = nth_page(page, (offset >> PAGE_SHIFT));
3688         offset %= PAGE_SIZE;
3689
3690         DPRINTK("data %s\n", qc->tf.flags & ATA_TFLAG_WRITE ? "write" : "read");
3691
3692         if (PageHighMem(page)) {
3693                 unsigned long flags;
3694
3695                 /* FIXME: use a bounce buffer */
3696                 local_irq_save(flags);
3697                 buf = kmap_atomic(page, KM_IRQ0);
3698
3699                 /* do the actual data transfer */
3700                 ap->ops->data_xfer(qc->dev, buf + offset, ATA_SECT_SIZE, do_write);
3701
3702                 kunmap_atomic(buf, KM_IRQ0);
3703                 local_irq_restore(flags);
3704         } else {
3705                 buf = page_address(page);
3706                 ap->ops->data_xfer(qc->dev, buf + offset, ATA_SECT_SIZE, do_write);
3707         }
3708
3709         qc->cursect++;
3710         qc->cursg_ofs++;
3711
3712         if ((qc->cursg_ofs * ATA_SECT_SIZE) == (&sg[qc->cursg])->length) {
3713                 qc->cursg++;
3714                 qc->cursg_ofs = 0;
3715         }
3716 }
3717
3718 /**
3719  *      ata_pio_sectors - Transfer one or many 512-byte sectors.
3720  *      @qc: Command on going
3721  *
3722  *      Transfer one or many ATA_SECT_SIZE of data from/to the
3723  *      ATA device for the DRQ request.
3724  *
3725  *      LOCKING:
3726  *      Inherited from caller.
3727  */
3728
3729 static void ata_pio_sectors(struct ata_queued_cmd *qc)
3730 {
3731         if (is_multi_taskfile(&qc->tf)) {
3732                 /* READ/WRITE MULTIPLE */
3733                 unsigned int nsect;
3734
3735                 WARN_ON(qc->dev->multi_count == 0);
3736
3737                 nsect = min(qc->nsect - qc->cursect, qc->dev->multi_count);
3738                 while (nsect--)
3739                         ata_pio_sector(qc);
3740         } else
3741                 ata_pio_sector(qc);
3742 }
3743
3744 /**
3745  *      atapi_send_cdb - Write CDB bytes to hardware
3746  *      @ap: Port to which ATAPI device is attached.
3747  *      @qc: Taskfile currently active
3748  *
3749  *      When device has indicated its readiness to accept
3750  *      a CDB, this function is called.  Send the CDB.
3751  *
3752  *      LOCKING:
3753  *      caller.
3754  */
3755
3756 static void atapi_send_cdb(struct ata_port *ap, struct ata_queued_cmd *qc)
3757 {
3758         /* send SCSI cdb */
3759         DPRINTK("send cdb\n");
3760         WARN_ON(qc->dev->cdb_len < 12);
3761
3762         ap->ops->data_xfer(qc->dev, qc->cdb, qc->dev->cdb_len, 1);
3763         ata_altstatus(ap); /* flush */
3764
3765         switch (qc->tf.protocol) {
3766         case ATA_PROT_ATAPI:
3767                 ap->hsm_task_state = HSM_ST;
3768                 break;
3769         case ATA_PROT_ATAPI_NODATA:
3770                 ap->hsm_task_state = HSM_ST_LAST;
3771                 break;
3772         case ATA_PROT_ATAPI_DMA:
3773                 ap->hsm_task_state = HSM_ST_LAST;
3774                 /* initiate bmdma */
3775                 ap->ops->bmdma_start(qc);
3776                 break;
3777         }
3778 }
3779
3780 /**
3781  *      __atapi_pio_bytes - Transfer data from/to the ATAPI device.
3782  *      @qc: Command on going
3783  *      @bytes: number of bytes
3784  *
3785  *      Transfer Transfer data from/to the ATAPI device.
3786  *
3787  *      LOCKING:
3788  *      Inherited from caller.
3789  *
3790  */
3791
3792 static void __atapi_pio_bytes(struct ata_queued_cmd *qc, unsigned int bytes)
3793 {
3794         int do_write = (qc->tf.flags & ATA_TFLAG_WRITE);
3795         struct scatterlist *sg = qc->__sg;
3796         struct ata_port *ap = qc->ap;
3797         struct page *page;
3798         unsigned char *buf;
3799         unsigned int offset, count;
3800
3801         if (qc->curbytes + bytes >= qc->nbytes)
3802                 ap->hsm_task_state = HSM_ST_LAST;
3803
3804 next_sg:
3805         if (unlikely(qc->cursg >= qc->n_elem)) {
3806                 /*
3807                  * The end of qc->sg is reached and the device expects
3808                  * more data to transfer. In order not to overrun qc->sg
3809                  * and fulfill length specified in the byte count register,
3810                  *    - for read case, discard trailing data from the device
3811                  *    - for write case, padding zero data to the device
3812                  */
3813                 u16 pad_buf[1] = { 0 };
3814                 unsigned int words = bytes >> 1;
3815                 unsigned int i;
3816
3817                 if (words) /* warning if bytes > 1 */
3818                         ata_dev_printk(qc->dev, KERN_WARNING,
3819                                        "%u bytes trailing data\n", bytes);
3820
3821                 for (i = 0; i < words; i++)
3822                         ap->ops->data_xfer(qc->dev, (unsigned char*)pad_buf, 2, do_write);
3823
3824                 ap->hsm_task_state = HSM_ST_LAST;
3825                 return;
3826         }
3827
3828         sg = &qc->__sg[qc->cursg];
3829
3830         page = sg->page;
3831         offset = sg->offset + qc->cursg_ofs;
3832
3833         /* get the current page and offset */
3834         page = nth_page(page, (offset >> PAGE_SHIFT));
3835         offset %= PAGE_SIZE;
3836
3837         /* don't overrun current sg */
3838         count = min(sg->length - qc->cursg_ofs, bytes);
3839
3840         /* don't cross page boundaries */
3841         count = min(count, (unsigned int)PAGE_SIZE - offset);
3842
3843         DPRINTK("data %s\n", qc->tf.flags & ATA_TFLAG_WRITE ? "write" : "read");
3844
3845         if (PageHighMem(page)) {
3846                 unsigned long flags;
3847
3848                 /* FIXME: use bounce buffer */
3849                 local_irq_save(flags);
3850                 buf = kmap_atomic(page, KM_IRQ0);
3851
3852                 /* do the actual data transfer */
3853                 ap->ops->data_xfer(qc->dev,  buf + offset, count, do_write);
3854
3855                 kunmap_atomic(buf, KM_IRQ0);
3856                 local_irq_restore(flags);
3857         } else {
3858                 buf = page_address(page);
3859                 ap->ops->data_xfer(qc->dev,  buf + offset, count, do_write);
3860         }
3861
3862         bytes -= count;
3863         qc->curbytes += count;
3864         qc->cursg_ofs += count;
3865
3866         if (qc->cursg_ofs == sg->length) {
3867                 qc->cursg++;
3868                 qc->cursg_ofs = 0;
3869         }
3870
3871         if (bytes)
3872                 goto next_sg;
3873 }
3874
3875 /**
3876  *      atapi_pio_bytes - Transfer data from/to the ATAPI device.
3877  *      @qc: Command on going
3878  *
3879  *      Transfer Transfer data from/to the ATAPI device.
3880  *
3881  *      LOCKING:
3882  *      Inherited from caller.
3883  */
3884
3885 static void atapi_pio_bytes(struct ata_queued_cmd *qc)
3886 {
3887         struct ata_port *ap = qc->ap;
3888         struct ata_device *dev = qc->dev;
3889         unsigned int ireason, bc_lo, bc_hi, bytes;
3890         int i_write, do_write = (qc->tf.flags & ATA_TFLAG_WRITE) ? 1 : 0;
3891
3892         /* Abuse qc->result_tf for temp storage of intermediate TF
3893          * here to save some kernel stack usage.
3894          * For normal completion, qc->result_tf is not relevant. For
3895          * error, qc->result_tf is later overwritten by ata_qc_complete().
3896          * So, the correctness of qc->result_tf is not affected.
3897          */
3898         ap->ops->tf_read(ap, &qc->result_tf);
3899         ireason = qc->result_tf.nsect;
3900         bc_lo = qc->result_tf.lbam;
3901         bc_hi = qc->result_tf.lbah;
3902         bytes = (bc_hi << 8) | bc_lo;
3903
3904         /* shall be cleared to zero, indicating xfer of data */
3905         if (ireason & (1 << 0))
3906                 goto err_out;
3907
3908         /* make sure transfer direction matches expected */
3909         i_write = ((ireason & (1 << 1)) == 0) ? 1 : 0;
3910         if (do_write != i_write)
3911                 goto err_out;
3912
3913         VPRINTK("ata%u: xfering %d bytes\n", ap->id, bytes);
3914
3915         __atapi_pio_bytes(qc, bytes);
3916
3917         return;
3918
3919 err_out:
3920         ata_dev_printk(dev, KERN_INFO, "ATAPI check failed\n");
3921         qc->err_mask |= AC_ERR_HSM;
3922         ap->hsm_task_state = HSM_ST_ERR;
3923 }
3924
3925 /**
3926  *      ata_hsm_ok_in_wq - Check if the qc can be handled in the workqueue.
3927  *      @ap: the target ata_port
3928  *      @qc: qc on going
3929  *
3930  *      RETURNS:
3931  *      1 if ok in workqueue, 0 otherwise.
3932  */
3933
3934 static inline int ata_hsm_ok_in_wq(struct ata_port *ap, struct ata_queued_cmd *qc)
3935 {
3936         if (qc->tf.flags & ATA_TFLAG_POLLING)
3937                 return 1;
3938
3939         if (ap->hsm_task_state == HSM_ST_FIRST) {
3940                 if (qc->tf.protocol == ATA_PROT_PIO &&
3941                     (qc->tf.flags & ATA_TFLAG_WRITE))
3942                     return 1;
3943
3944                 if (is_atapi_taskfile(&qc->tf) &&
3945                     !(qc->dev->flags & ATA_DFLAG_CDB_INTR))
3946                         return 1;
3947         }
3948
3949         return 0;
3950 }
3951
3952 /**
3953  *      ata_hsm_qc_complete - finish a qc running on standard HSM
3954  *      @qc: Command to complete
3955  *      @in_wq: 1 if called from workqueue, 0 otherwise
3956  *
3957  *      Finish @qc which is running on standard HSM.
3958  *
3959  *      LOCKING:
3960  *      If @in_wq is zero, spin_lock_irqsave(host_set lock).
3961  *      Otherwise, none on entry and grabs host lock.
3962  */
3963 static void ata_hsm_qc_complete(struct ata_queued_cmd *qc, int in_wq)
3964 {
3965         struct ata_port *ap = qc->ap;
3966         unsigned long flags;
3967
3968         if (ap->ops->error_handler) {
3969                 if (in_wq) {
3970                         spin_lock_irqsave(ap->lock, flags);
3971
3972                         /* EH might have kicked in while host_set lock
3973                          * is released.
3974                          */
3975                         qc = ata_qc_from_tag(ap, qc->tag);
3976                         if (qc) {
3977                                 if (likely(!(qc->err_mask & AC_ERR_HSM))) {
3978                                         ata_irq_on(ap);
3979                                         ata_qc_complete(qc);
3980                                 } else
3981                                         ata_port_freeze(ap);
3982                         }
3983
3984                         spin_unlock_irqrestore(ap->lock, flags);
3985                 } else {
3986                         if (likely(!(qc->err_mask & AC_ERR_HSM)))
3987                                 ata_qc_complete(qc);
3988                         else
3989                                 ata_port_freeze(ap);
3990                 }
3991         } else {
3992                 if (in_wq) {
3993                         spin_lock_irqsave(ap->lock, flags);
3994                         ata_irq_on(ap);
3995                         ata_qc_complete(qc);
3996                         spin_unlock_irqrestore(ap->lock, flags);
3997                 } else
3998                         ata_qc_complete(qc);
3999         }
4000
4001         ata_altstatus(ap); /* flush */
4002 }
4003
4004 /**
4005  *      ata_hsm_move - move the HSM to the next state.
4006  *      @ap: the target ata_port
4007  *      @qc: qc on going
4008  *      @status: current device status
4009  *      @in_wq: 1 if called from workqueue, 0 otherwise
4010  *
4011  *      RETURNS:
4012  *      1 when poll next status needed, 0 otherwise.
4013  */
4014 int ata_hsm_move(struct ata_port *ap, struct ata_queued_cmd *qc,
4015                  u8 status, int in_wq)
4016 {
4017         unsigned long flags = 0;
4018         int poll_next;
4019
4020         WARN_ON((qc->flags & ATA_QCFLAG_ACTIVE) == 0);
4021
4022         /* Make sure ata_qc_issue_prot() does not throw things
4023          * like DMA polling into the workqueue. Notice that
4024          * in_wq is not equivalent to (qc->tf.flags & ATA_TFLAG_POLLING).
4025          */
4026         WARN_ON(in_wq != ata_hsm_ok_in_wq(ap, qc));
4027
4028 fsm_start:
4029         DPRINTK("ata%u: protocol %d task_state %d (dev_stat 0x%X)\n",
4030                 ap->id, qc->tf.protocol, ap->hsm_task_state, status);
4031
4032         switch (ap->hsm_task_state) {
4033         case HSM_ST_FIRST:
4034                 /* Send first data block or PACKET CDB */
4035
4036                 /* If polling, we will stay in the work queue after
4037                  * sending the data. Otherwise, interrupt handler
4038                  * takes over after sending the data.
4039                  */
4040                 poll_next = (qc->tf.flags & ATA_TFLAG_POLLING);
4041
4042                 /* check device status */
4043                 if (unlikely((status & ATA_DRQ) == 0)) {
4044                         /* handle BSY=0, DRQ=0 as error */
4045                         if (likely(status & (ATA_ERR | ATA_DF)))
4046                                 /* device stops HSM for abort/error */
4047                                 qc->err_mask |= AC_ERR_DEV;
4048                         else
4049                                 /* HSM violation. Let EH handle this */
4050                                 qc->err_mask |= AC_ERR_HSM;
4051
4052                         ap->hsm_task_state = HSM_ST_ERR;
4053                         goto fsm_start;
4054                 }
4055
4056                 /* Device should not ask for data transfer (DRQ=1)
4057                  * when it finds something wrong.
4058                  * We ignore DRQ here and stop the HSM by
4059                  * changing hsm_task_state to HSM_ST_ERR and
4060                  * let the EH abort the command or reset the device.
4061                  */
4062                 if (unlikely(status & (ATA_ERR | ATA_DF))) {
4063                         printk(KERN_WARNING "ata%d: DRQ=1 with device error, dev_stat 0x%X\n",
4064                                ap->id, status);
4065                         qc->err_mask |= AC_ERR_HSM;
4066                         ap->hsm_task_state = HSM_ST_ERR;
4067                         goto fsm_start;
4068                 }
4069
4070                 /* Send the CDB (atapi) or the first data block (ata pio out).
4071                  * During the state transition, interrupt handler shouldn't
4072                  * be invoked before the data transfer is complete and
4073                  * hsm_task_state is changed. Hence, the following locking.
4074                  */
4075                 if (in_wq)
4076                         spin_lock_irqsave(ap->lock, flags);
4077
4078                 if (qc->tf.protocol == ATA_PROT_PIO) {
4079                         /* PIO data out protocol.
4080                          * send first data block.
4081                          */
4082
4083                         /* ata_pio_sectors() might change the state
4084                          * to HSM_ST_LAST. so, the state is changed here
4085                          * before ata_pio_sectors().
4086                          */
4087                         ap->hsm_task_state = HSM_ST;
4088                         ata_pio_sectors(qc);
4089                         ata_altstatus(ap); /* flush */
4090                 } else
4091                         /* send CDB */
4092                         atapi_send_cdb(ap, qc);
4093
4094                 if (in_wq)
4095                         spin_unlock_irqrestore(ap->lock, flags);
4096
4097                 /* if polling, ata_pio_task() handles the rest.
4098                  * otherwise, interrupt handler takes over from here.
4099                  */
4100                 break;
4101
4102         case HSM_ST:
4103                 /* complete command or read/write the data register */
4104                 if (qc->tf.protocol == ATA_PROT_ATAPI) {
4105                         /* ATAPI PIO protocol */
4106                         if ((status & ATA_DRQ) == 0) {
4107                                 /* No more data to transfer or device error.
4108                                  * Device error will be tagged in HSM_ST_LAST.
4109                                  */
4110                                 ap->hsm_task_state = HSM_ST_LAST;
4111                                 goto fsm_start;
4112                         }
4113
4114                         /* Device should not ask for data transfer (DRQ=1)
4115                          * when it finds something wrong.
4116                          * We ignore DRQ here and stop the HSM by
4117                          * changing hsm_task_state to HSM_ST_ERR and
4118                          * let the EH abort the command or reset the device.
4119                          */
4120                         if (unlikely(status & (ATA_ERR | ATA_DF))) {
4121                                 printk(KERN_WARNING "ata%d: DRQ=1 with device error, dev_stat 0x%X\n",
4122                                        ap->id, status);
4123                                 qc->err_mask |= AC_ERR_HSM;
4124                                 ap->hsm_task_state = HSM_ST_ERR;
4125                                 goto fsm_start;
4126                         }
4127
4128                         atapi_pio_bytes(qc);
4129
4130                         if (unlikely(ap->hsm_task_state == HSM_ST_ERR))
4131                                 /* bad ireason reported by device */
4132                                 goto fsm_start;
4133
4134                 } else {
4135                         /* ATA PIO protocol */
4136                         if (unlikely((status & ATA_DRQ) == 0)) {
4137                                 /* handle BSY=0, DRQ=0 as error */
4138                                 if (likely(status & (ATA_ERR | ATA_DF)))
4139                                         /* device stops HSM for abort/error */
4140                                         qc->err_mask |= AC_ERR_DEV;
4141                                 else
4142                                         /* HSM violation. Let EH handle this */
4143                                         qc->err_mask |= AC_ERR_HSM;
4144
4145                                 ap->hsm_task_state = HSM_ST_ERR;
4146                                 goto fsm_start;
4147                         }
4148
4149                         /* For PIO reads, some devices may ask for
4150                          * data transfer (DRQ=1) alone with ERR=1.
4151                          * We respect DRQ here and transfer one
4152                          * block of junk data before changing the
4153                          * hsm_task_state to HSM_ST_ERR.
4154                          *
4155                          * For PIO writes, ERR=1 DRQ=1 doesn't make
4156                          * sense since the data block has been
4157                          * transferred to the device.
4158                          */
4159                         if (unlikely(status & (ATA_ERR | ATA_DF))) {
4160                                 /* data might be corrputed */
4161                                 qc->err_mask |= AC_ERR_DEV;
4162
4163                                 if (!(qc->tf.flags & ATA_TFLAG_WRITE)) {
4164                                         ata_pio_sectors(qc);
4165                                         ata_altstatus(ap);
4166                                         status = ata_wait_idle(ap);
4167                                 }
4168
4169                                 if (status & (ATA_BUSY | ATA_DRQ))
4170                                         qc->err_mask |= AC_ERR_HSM;
4171
4172                                 /* ata_pio_sectors() might change the
4173                                  * state to HSM_ST_LAST. so, the state
4174                                  * is changed after ata_pio_sectors().
4175                                  */
4176                                 ap->hsm_task_state = HSM_ST_ERR;
4177                                 goto fsm_start;
4178                         }
4179
4180                         ata_pio_sectors(qc);
4181
4182                         if (ap->hsm_task_state == HSM_ST_LAST &&
4183                             (!(qc->tf.flags & ATA_TFLAG_WRITE))) {
4184                                 /* all data read */
4185                                 ata_altstatus(ap);
4186                                 status = ata_wait_idle(ap);
4187                                 goto fsm_start;
4188                         }
4189                 }
4190
4191                 ata_altstatus(ap); /* flush */
4192                 poll_next = 1;
4193                 break;
4194
4195         case HSM_ST_LAST:
4196                 if (unlikely(!ata_ok(status))) {
4197                         qc->err_mask |= __ac_err_mask(status);
4198                         ap->hsm_task_state = HSM_ST_ERR;
4199                         goto fsm_start;
4200                 }
4201
4202                 /* no more data to transfer */
4203                 DPRINTK("ata%u: dev %u command complete, drv_stat 0x%x\n",
4204                         ap->id, qc->dev->devno, status);
4205
4206                 WARN_ON(qc->err_mask);
4207
4208                 ap->hsm_task_state = HSM_ST_IDLE;
4209
4210                 /* complete taskfile transaction */
4211                 ata_hsm_qc_complete(qc, in_wq);
4212
4213                 poll_next = 0;
4214                 break;
4215
4216         case HSM_ST_ERR:
4217                 /* make sure qc->err_mask is available to
4218                  * know what's wrong and recover
4219                  */
4220                 WARN_ON(qc->err_mask == 0);
4221
4222                 ap->hsm_task_state = HSM_ST_IDLE;
4223
4224                 /* complete taskfile transaction */
4225                 ata_hsm_qc_complete(qc, in_wq);
4226
4227                 poll_next = 0;
4228                 break;
4229         default:
4230                 poll_next = 0;
4231                 BUG();
4232         }
4233
4234         return poll_next;
4235 }
4236
4237 static void ata_pio_task(void *_data)
4238 {
4239         struct ata_queued_cmd *qc = _data;
4240         struct ata_port *ap = qc->ap;
4241         u8 status;
4242         int poll_next;
4243
4244 fsm_start:
4245         WARN_ON(ap->hsm_task_state == HSM_ST_IDLE);
4246
4247         /*
4248          * This is purely heuristic.  This is a fast path.
4249          * Sometimes when we enter, BSY will be cleared in
4250          * a chk-status or two.  If not, the drive is probably seeking
4251          * or something.  Snooze for a couple msecs, then
4252          * chk-status again.  If still busy, queue delayed work.
4253          */
4254         status = ata_busy_wait(ap, ATA_BUSY, 5);
4255         if (status & ATA_BUSY) {
4256                 msleep(2);
4257                 status = ata_busy_wait(ap, ATA_BUSY, 10);
4258                 if (status & ATA_BUSY) {
4259                         ata_port_queue_task(ap, ata_pio_task, qc, ATA_SHORT_PAUSE);
4260                         return;
4261                 }
4262         }
4263
4264         /* move the HSM */
4265         poll_next = ata_hsm_move(ap, qc, status, 1);
4266
4267         /* another command or interrupt handler
4268          * may be running at this point.
4269          */
4270         if (poll_next)
4271                 goto fsm_start;
4272 }
4273
4274 /**
4275  *      ata_qc_new - Request an available ATA command, for queueing
4276  *      @ap: Port associated with device @dev
4277  *      @dev: Device from whom we request an available command structure
4278  *
4279  *      LOCKING:
4280  *      None.
4281  */
4282
4283 static struct ata_queued_cmd *ata_qc_new(struct ata_port *ap)
4284 {
4285         struct ata_queued_cmd *qc = NULL;
4286         unsigned int i;
4287
4288         /* no command while frozen */
4289         if (unlikely(ap->flags & ATA_FLAG_FROZEN))
4290                 return NULL;
4291
4292         /* the last tag is reserved for internal command. */
4293         for (i = 0; i < ATA_MAX_QUEUE - 1; i++)
4294                 if (!test_and_set_bit(i, &ap->qc_allocated)) {
4295                         qc = __ata_qc_from_tag(ap, i);
4296                         break;
4297                 }
4298
4299         if (qc)
4300                 qc->tag = i;
4301
4302         return qc;
4303 }
4304
4305 /**
4306  *      ata_qc_new_init - Request an available ATA command, and initialize it
4307  *      @dev: Device from whom we request an available command structure
4308  *
4309  *      LOCKING:
4310  *      None.
4311  */
4312
4313 struct ata_queued_cmd *ata_qc_new_init(struct ata_device *dev)
4314 {
4315         struct ata_port *ap = dev->ap;
4316         struct ata_queued_cmd *qc;
4317
4318         qc = ata_qc_new(ap);
4319         if (qc) {
4320                 qc->scsicmd = NULL;
4321                 qc->ap = ap;
4322                 qc->dev = dev;
4323
4324                 ata_qc_reinit(qc);
4325         }
4326
4327         return qc;
4328 }
4329
4330 /**
4331  *      ata_qc_free - free unused ata_queued_cmd
4332  *      @qc: Command to complete
4333  *
4334  *      Designed to free unused ata_queued_cmd object
4335  *      in case something prevents using it.
4336  *
4337  *      LOCKING:
4338  *      spin_lock_irqsave(host_set lock)
4339  */
4340 void ata_qc_free(struct ata_queued_cmd *qc)
4341 {
4342         struct ata_port *ap = qc->ap;
4343         unsigned int tag;
4344
4345         WARN_ON(qc == NULL);    /* ata_qc_from_tag _might_ return NULL */
4346
4347         qc->flags = 0;
4348         tag = qc->tag;
4349         if (likely(ata_tag_valid(tag))) {
4350                 qc->tag = ATA_TAG_POISON;
4351                 clear_bit(tag, &ap->qc_allocated);
4352         }
4353 }
4354
4355 void __ata_qc_complete(struct ata_queued_cmd *qc)
4356 {
4357         struct ata_port *ap = qc->ap;
4358
4359         WARN_ON(qc == NULL);    /* ata_qc_from_tag _might_ return NULL */
4360         WARN_ON(!(qc->flags & ATA_QCFLAG_ACTIVE));
4361
4362         if (likely(qc->flags & ATA_QCFLAG_DMAMAP))
4363                 ata_sg_clean(qc);
4364
4365         /* command should be marked inactive atomically with qc completion */
4366         if (qc->tf.protocol == ATA_PROT_NCQ)
4367                 ap->sactive &= ~(1 << qc->tag);
4368         else
4369                 ap->active_tag = ATA_TAG_POISON;
4370
4371         /* atapi: mark qc as inactive to prevent the interrupt handler
4372          * from completing the command twice later, before the error handler
4373          * is called. (when rc != 0 and atapi request sense is needed)
4374          */
4375         qc->flags &= ~ATA_QCFLAG_ACTIVE;
4376         ap->qc_active &= ~(1 << qc->tag);
4377
4378         /* call completion callback */
4379         qc->complete_fn(qc);
4380 }
4381
4382 /**
4383  *      ata_qc_complete - Complete an active ATA command
4384  *      @qc: Command to complete
4385  *      @err_mask: ATA Status register contents
4386  *
4387  *      Indicate to the mid and upper layers that an ATA
4388  *      command has completed, with either an ok or not-ok status.
4389  *
4390  *      LOCKING:
4391  *      spin_lock_irqsave(host_set lock)
4392  */
4393 void ata_qc_complete(struct ata_queued_cmd *qc)
4394 {
4395         struct ata_port *ap = qc->ap;
4396
4397         /* XXX: New EH and old EH use different mechanisms to
4398          * synchronize EH with regular execution path.
4399          *
4400          * In new EH, a failed qc is marked with ATA_QCFLAG_FAILED.
4401          * Normal execution path is responsible for not accessing a
4402          * failed qc.  libata core enforces the rule by returning NULL
4403          * from ata_qc_from_tag() for failed qcs.
4404          *
4405          * Old EH depends on ata_qc_complete() nullifying completion
4406          * requests if ATA_QCFLAG_EH_SCHEDULED is set.  Old EH does
4407          * not synchronize with interrupt handler.  Only PIO task is
4408          * taken care of.
4409          */
4410         if (ap->ops->error_handler) {
4411                 WARN_ON(ap->flags & ATA_FLAG_FROZEN);
4412
4413                 if (unlikely(qc->err_mask))
4414                         qc->flags |= ATA_QCFLAG_FAILED;
4415
4416                 if (unlikely(qc->flags & ATA_QCFLAG_FAILED)) {
4417                         if (!ata_tag_internal(qc->tag)) {
4418                                 /* always fill result TF for failed qc */
4419                                 ap->ops->tf_read(ap, &qc->result_tf);
4420                                 ata_qc_schedule_eh(qc);
4421                                 return;
4422                         }
4423                 }
4424
4425                 /* read result TF if requested */
4426                 if (qc->flags & ATA_QCFLAG_RESULT_TF)
4427                         ap->ops->tf_read(ap, &qc->result_tf);
4428
4429                 __ata_qc_complete(qc);
4430         } else {
4431                 if (qc->flags & ATA_QCFLAG_EH_SCHEDULED)
4432                         return;
4433
4434                 /* read result TF if failed or requested */
4435                 if (qc->err_mask || qc->flags & ATA_QCFLAG_RESULT_TF)
4436                         ap->ops->tf_read(ap, &qc->result_tf);
4437
4438                 __ata_qc_complete(qc);
4439         }
4440 }
4441
4442 /**
4443  *      ata_qc_complete_multiple - Complete multiple qcs successfully
4444  *      @ap: port in question
4445  *      @qc_active: new qc_active mask
4446  *      @finish_qc: LLDD callback invoked before completing a qc
4447  *
4448  *      Complete in-flight commands.  This functions is meant to be
4449  *      called from low-level driver's interrupt routine to complete
4450  *      requests normally.  ap->qc_active and @qc_active is compared
4451  *      and commands are completed accordingly.
4452  *
4453  *      LOCKING:
4454  *      spin_lock_irqsave(host_set lock)
4455  *
4456  *      RETURNS:
4457  *      Number of completed commands on success, -errno otherwise.
4458  */
4459 int ata_qc_complete_multiple(struct ata_port *ap, u32 qc_active,
4460                              void (*finish_qc)(struct ata_queued_cmd *))
4461 {
4462         int nr_done = 0;
4463         u32 done_mask;
4464         int i;
4465
4466         done_mask = ap->qc_active ^ qc_active;
4467
4468         if (unlikely(done_mask & qc_active)) {
4469                 ata_port_printk(ap, KERN_ERR, "illegal qc_active transition "
4470                                 "(%08x->%08x)\n", ap->qc_active, qc_active);
4471                 return -EINVAL;
4472         }
4473
4474         for (i = 0; i < ATA_MAX_QUEUE; i++) {
4475                 struct ata_queued_cmd *qc;
4476
4477                 if (!(done_mask & (1 << i)))
4478                         continue;
4479
4480                 if ((qc = ata_qc_from_tag(ap, i))) {
4481                         if (finish_qc)
4482                                 finish_qc(qc);
4483                         ata_qc_complete(qc);
4484                         nr_done++;
4485                 }
4486         }
4487
4488         return nr_done;
4489 }
4490
4491 static inline int ata_should_dma_map(struct ata_queued_cmd *qc)
4492 {
4493         struct ata_port *ap = qc->ap;
4494
4495         switch (qc->tf.protocol) {
4496         case ATA_PROT_NCQ:
4497         case ATA_PROT_DMA:
4498         case ATA_PROT_ATAPI_DMA:
4499                 return 1;
4500
4501         case ATA_PROT_ATAPI:
4502         case ATA_PROT_PIO:
4503                 if (ap->flags & ATA_FLAG_PIO_DMA)
4504                         return 1;
4505
4506                 /* fall through */
4507
4508         default:
4509                 return 0;
4510         }
4511
4512         /* never reached */
4513 }
4514
4515 /**
4516  *      ata_qc_issue - issue taskfile to device
4517  *      @qc: command to issue to device
4518  *
4519  *      Prepare an ATA command to submission to device.
4520  *      This includes mapping the data into a DMA-able
4521  *      area, filling in the S/G table, and finally
4522  *      writing the taskfile to hardware, starting the command.
4523  *
4524  *      LOCKING:
4525  *      spin_lock_irqsave(host_set lock)
4526  */
4527 void ata_qc_issue(struct ata_queued_cmd *qc)
4528 {
4529         struct ata_port *ap = qc->ap;
4530
4531         /* Make sure only one non-NCQ command is outstanding.  The
4532          * check is skipped for old EH because it reuses active qc to
4533          * request ATAPI sense.
4534          */
4535         WARN_ON(ap->ops->error_handler && ata_tag_valid(ap->active_tag));
4536
4537         if (qc->tf.protocol == ATA_PROT_NCQ) {
4538                 WARN_ON(ap->sactive & (1 << qc->tag));
4539                 ap->sactive |= 1 << qc->tag;
4540         } else {
4541                 WARN_ON(ap->sactive);
4542                 ap->active_tag = qc->tag;
4543         }
4544
4545         qc->flags |= ATA_QCFLAG_ACTIVE;
4546         ap->qc_active |= 1 << qc->tag;
4547
4548         if (ata_should_dma_map(qc)) {
4549                 if (qc->flags & ATA_QCFLAG_SG) {
4550                         if (ata_sg_setup(qc))
4551                                 goto sg_err;
4552                 } else if (qc->flags & ATA_QCFLAG_SINGLE) {
4553                         if (ata_sg_setup_one(qc))
4554                                 goto sg_err;
4555                 }
4556         } else {
4557                 qc->flags &= ~ATA_QCFLAG_DMAMAP;
4558         }
4559
4560         ap->ops->qc_prep(qc);
4561
4562         qc->err_mask |= ap->ops->qc_issue(qc);
4563         if (unlikely(qc->err_mask))
4564                 goto err;
4565         return;
4566
4567 sg_err:
4568         qc->flags &= ~ATA_QCFLAG_DMAMAP;
4569         qc->err_mask |= AC_ERR_SYSTEM;
4570 err:
4571         ata_qc_complete(qc);
4572 }
4573
4574 /**
4575  *      ata_qc_issue_prot - issue taskfile to device in proto-dependent manner
4576  *      @qc: command to issue to device
4577  *
4578  *      Using various libata functions and hooks, this function
4579  *      starts an ATA command.  ATA commands are grouped into
4580  *      classes called "protocols", and issuing each type of protocol
4581  *      is slightly different.
4582  *
4583  *      May be used as the qc_issue() entry in ata_port_operations.
4584  *
4585  *      LOCKING:
4586  *      spin_lock_irqsave(host_set lock)
4587  *
4588  *      RETURNS:
4589  *      Zero on success, AC_ERR_* mask on failure
4590  */
4591
4592 unsigned int ata_qc_issue_prot(struct ata_queued_cmd *qc)
4593 {
4594         struct ata_port *ap = qc->ap;
4595
4596         /* Use polling pio if the LLD doesn't handle
4597          * interrupt driven pio and atapi CDB interrupt.
4598          */
4599         if (ap->flags & ATA_FLAG_PIO_POLLING) {
4600                 switch (qc->tf.protocol) {
4601                 case ATA_PROT_PIO:
4602                 case ATA_PROT_ATAPI:
4603                 case ATA_PROT_ATAPI_NODATA:
4604                         qc->tf.flags |= ATA_TFLAG_POLLING;
4605                         break;
4606                 case ATA_PROT_ATAPI_DMA:
4607                         if (qc->dev->flags & ATA_DFLAG_CDB_INTR)
4608                                 /* see ata_dma_blacklisted() */
4609                                 BUG();
4610                         break;
4611                 default:
4612                         break;
4613                 }
4614         }
4615
4616         /* select the device */
4617         ata_dev_select(ap, qc->dev->devno, 1, 0);
4618
4619         /* start the command */
4620         switch (qc->tf.protocol) {
4621         case ATA_PROT_NODATA:
4622                 if (qc->tf.flags & ATA_TFLAG_POLLING)
4623                         ata_qc_set_polling(qc);
4624
4625                 ata_tf_to_host(ap, &qc->tf);
4626                 ap->hsm_task_state = HSM_ST_LAST;
4627
4628                 if (qc->tf.flags & ATA_TFLAG_POLLING)
4629                         ata_port_queue_task(ap, ata_pio_task, qc, 0);
4630
4631                 break;
4632
4633         case ATA_PROT_DMA:
4634                 WARN_ON(qc->tf.flags & ATA_TFLAG_POLLING);
4635
4636                 ap->ops->tf_load(ap, &qc->tf);   /* load tf registers */
4637                 ap->ops->bmdma_setup(qc);           /* set up bmdma */
4638                 ap->ops->bmdma_start(qc);           /* initiate bmdma */
4639                 ap->hsm_task_state = HSM_ST_LAST;
4640                 break;
4641
4642         case ATA_PROT_PIO:
4643                 if (qc->tf.flags & ATA_TFLAG_POLLING)
4644                         ata_qc_set_polling(qc);
4645
4646                 ata_tf_to_host(ap, &qc->tf);
4647
4648                 if (qc->tf.flags & ATA_TFLAG_WRITE) {
4649                         /* PIO data out protocol */
4650                         ap->hsm_task_state = HSM_ST_FIRST;
4651                         ata_port_queue_task(ap, ata_pio_task, qc, 0);
4652
4653                         /* always send first data block using
4654                          * the ata_pio_task() codepath.
4655                          */
4656                 } else {
4657                         /* PIO data in protocol */
4658                         ap->hsm_task_state = HSM_ST;
4659
4660                         if (qc->tf.flags & ATA_TFLAG_POLLING)
4661                                 ata_port_queue_task(ap, ata_pio_task, qc, 0);
4662
4663                         /* if polling, ata_pio_task() handles the rest.
4664                          * otherwise, interrupt handler takes over from here.
4665                          */
4666                 }
4667
4668                 break;
4669
4670         case ATA_PROT_ATAPI:
4671         case ATA_PROT_ATAPI_NODATA:
4672                 if (qc->tf.flags & ATA_TFLAG_POLLING)
4673                         ata_qc_set_polling(qc);
4674
4675                 ata_tf_to_host(ap, &qc->tf);
4676
4677                 ap->hsm_task_state = HSM_ST_FIRST;
4678
4679                 /* send cdb by polling if no cdb interrupt */
4680                 if ((!(qc->dev->flags & ATA_DFLAG_CDB_INTR)) ||
4681                     (qc->tf.flags & ATA_TFLAG_POLLING))
4682                         ata_port_queue_task(ap, ata_pio_task, qc, 0);
4683                 break;
4684
4685         case ATA_PROT_ATAPI_DMA:
4686                 WARN_ON(qc->tf.flags & ATA_TFLAG_POLLING);
4687
4688                 ap->ops->tf_load(ap, &qc->tf);   /* load tf registers */
4689                 ap->ops->bmdma_setup(qc);           /* set up bmdma */
4690                 ap->hsm_task_state = HSM_ST_FIRST;
4691
4692                 /* send cdb by polling if no cdb interrupt */
4693                 if (!(qc->dev->flags & ATA_DFLAG_CDB_INTR))
4694                         ata_port_queue_task(ap, ata_pio_task, qc, 0);
4695                 break;
4696
4697         default:
4698                 WARN_ON(1);
4699                 return AC_ERR_SYSTEM;
4700         }
4701
4702         return 0;
4703 }
4704
4705 /**
4706  *      ata_host_intr - Handle host interrupt for given (port, task)
4707  *      @ap: Port on which interrupt arrived (possibly...)
4708  *      @qc: Taskfile currently active in engine
4709  *
4710  *      Handle host interrupt for given queued command.  Currently,
4711  *      only DMA interrupts are handled.  All other commands are
4712  *      handled via polling with interrupts disabled (nIEN bit).
4713  *
4714  *      LOCKING:
4715  *      spin_lock_irqsave(host_set lock)
4716  *
4717  *      RETURNS:
4718  *      One if interrupt was handled, zero if not (shared irq).
4719  */
4720
4721 inline unsigned int ata_host_intr (struct ata_port *ap,
4722                                    struct ata_queued_cmd *qc)
4723 {
4724         u8 status, host_stat = 0;
4725
4726         VPRINTK("ata%u: protocol %d task_state %d\n",
4727                 ap->id, qc->tf.protocol, ap->hsm_task_state);
4728
4729         /* Check whether we are expecting interrupt in this state */
4730         switch (ap->hsm_task_state) {
4731         case HSM_ST_FIRST:
4732                 /* Some pre-ATAPI-4 devices assert INTRQ
4733                  * at this state when ready to receive CDB.
4734                  */
4735
4736                 /* Check the ATA_DFLAG_CDB_INTR flag is enough here.
4737                  * The flag was turned on only for atapi devices.
4738                  * No need to check is_atapi_taskfile(&qc->tf) again.
4739                  */
4740                 if (!(qc->dev->flags & ATA_DFLAG_CDB_INTR))
4741                         goto idle_irq;
4742                 break;
4743         case HSM_ST_LAST:
4744                 if (qc->tf.protocol == ATA_PROT_DMA ||
4745                     qc->tf.protocol == ATA_PROT_ATAPI_DMA) {
4746                         /* check status of DMA engine */
4747                         host_stat = ap->ops->bmdma_status(ap);
4748                         VPRINTK("ata%u: host_stat 0x%X\n", ap->id, host_stat);
4749
4750                         /* if it's not our irq... */
4751                         if (!(host_stat & ATA_DMA_INTR))
4752                                 goto idle_irq;
4753
4754                         /* before we do anything else, clear DMA-Start bit */
4755                         ap->ops->bmdma_stop(qc);
4756
4757                         if (unlikely(host_stat & ATA_DMA_ERR)) {
4758                                 /* error when transfering data to/from memory */
4759                                 qc->err_mask |= AC_ERR_HOST_BUS;
4760                                 ap->hsm_task_state = HSM_ST_ERR;
4761                         }
4762                 }
4763                 break;
4764         case HSM_ST:
4765                 break;
4766         default:
4767                 goto idle_irq;
4768         }
4769
4770         /* check altstatus */
4771         status = ata_altstatus(ap);
4772         if (status & ATA_BUSY)
4773                 goto idle_irq;
4774
4775         /* check main status, clearing INTRQ */
4776         status = ata_chk_status(ap);
4777         if (unlikely(status & ATA_BUSY))
4778                 goto idle_irq;
4779
4780         /* ack bmdma irq events */
4781         ap->ops->irq_clear(ap);
4782
4783         ata_hsm_move(ap, qc, status, 0);
4784         return 1;       /* irq handled */
4785
4786 idle_irq:
4787         ap->stats.idle_irq++;
4788
4789 #ifdef ATA_IRQ_TRAP
4790         if ((ap->stats.idle_irq % 1000) == 0) {
4791                 ata_irq_ack(ap, 0); /* debug trap */
4792                 ata_port_printk(ap, KERN_WARNING, "irq trap\n");
4793                 return 1;
4794         }
4795 #endif
4796         return 0;       /* irq not handled */
4797 }
4798
4799 /**
4800  *      ata_interrupt - Default ATA host interrupt handler
4801  *      @irq: irq line (unused)
4802  *      @dev_instance: pointer to our ata_host_set information structure
4803  *      @regs: unused
4804  *
4805  *      Default interrupt handler for PCI IDE devices.  Calls
4806  *      ata_host_intr() for each port that is not disabled.
4807  *
4808  *      LOCKING:
4809  *      Obtains host_set lock during operation.
4810  *
4811  *      RETURNS:
4812  *      IRQ_NONE or IRQ_HANDLED.
4813  */
4814
4815 irqreturn_t ata_interrupt (int irq, void *dev_instance, struct pt_regs *regs)
4816 {
4817         struct ata_host_set *host_set = dev_instance;
4818         unsigned int i;
4819         unsigned int handled = 0;
4820         unsigned long flags;
4821
4822         /* TODO: make _irqsave conditional on x86 PCI IDE legacy mode */
4823         spin_lock_irqsave(&host_set->lock, flags);
4824
4825         for (i = 0; i < host_set->n_ports; i++) {
4826                 struct ata_port *ap;
4827
4828                 ap = host_set->ports[i];
4829                 if (ap &&
4830                     !(ap->flags & ATA_FLAG_DISABLED)) {
4831                         struct ata_queued_cmd *qc;
4832
4833                         qc = ata_qc_from_tag(ap, ap->active_tag);
4834                         if (qc && (!(qc->tf.flags & ATA_TFLAG_POLLING)) &&
4835                             (qc->flags & ATA_QCFLAG_ACTIVE))
4836                                 handled |= ata_host_intr(ap, qc);
4837                 }
4838         }
4839
4840         spin_unlock_irqrestore(&host_set->lock, flags);
4841
4842         return IRQ_RETVAL(handled);
4843 }
4844
4845 /**
4846  *      sata_scr_valid - test whether SCRs are accessible
4847  *      @ap: ATA port to test SCR accessibility for
4848  *
4849  *      Test whether SCRs are accessible for @ap.
4850  *
4851  *      LOCKING:
4852  *      None.
4853  *
4854  *      RETURNS:
4855  *      1 if SCRs are accessible, 0 otherwise.
4856  */
4857 int sata_scr_valid(struct ata_port *ap)
4858 {
4859         return ap->cbl == ATA_CBL_SATA && ap->ops->scr_read;
4860 }
4861
4862 /**
4863  *      sata_scr_read - read SCR register of the specified port
4864  *      @ap: ATA port to read SCR for
4865  *      @reg: SCR to read
4866  *      @val: Place to store read value
4867  *
4868  *      Read SCR register @reg of @ap into *@val.  This function is
4869  *      guaranteed to succeed if the cable type of the port is SATA
4870  *      and the port implements ->scr_read.
4871  *
4872  *      LOCKING:
4873  *      None.
4874  *
4875  *      RETURNS:
4876  *      0 on success, negative errno on failure.
4877  */
4878 int sata_scr_read(struct ata_port *ap, int reg, u32 *val)
4879 {
4880         if (sata_scr_valid(ap)) {
4881                 *val = ap->ops->scr_read(ap, reg);
4882                 return 0;
4883         }
4884         return -EOPNOTSUPP;
4885 }
4886
4887 /**
4888  *      sata_scr_write - write SCR register of the specified port
4889  *      @ap: ATA port to write SCR for
4890  *      @reg: SCR to write
4891  *      @val: value to write
4892  *
4893  *      Write @val to SCR register @reg of @ap.  This function is
4894  *      guaranteed to succeed if the cable type of the port is SATA
4895  *      and the port implements ->scr_read.
4896  *
4897  *      LOCKING:
4898  *      None.
4899  *
4900  *      RETURNS:
4901  *      0 on success, negative errno on failure.
4902  */
4903 int sata_scr_write(struct ata_port *ap, int reg, u32 val)
4904 {
4905         if (sata_scr_valid(ap)) {
4906                 ap->ops->scr_write(ap, reg, val);
4907                 return 0;
4908         }
4909         return -EOPNOTSUPP;
4910 }
4911
4912 /**
4913  *      sata_scr_write_flush - write SCR register of the specified port and flush
4914  *      @ap: ATA port to write SCR for
4915  *      @reg: SCR to write
4916  *      @val: value to write
4917  *
4918  *      This function is identical to sata_scr_write() except that this
4919  *      function performs flush after writing to the register.
4920  *
4921  *      LOCKING:
4922  *      None.
4923  *
4924  *      RETURNS:
4925  *      0 on success, negative errno on failure.
4926  */
4927 int sata_scr_write_flush(struct ata_port *ap, int reg, u32 val)
4928 {
4929         if (sata_scr_valid(ap)) {
4930                 ap->ops->scr_write(ap, reg, val);
4931                 ap->ops->scr_read(ap, reg);
4932                 return 0;
4933         }
4934         return -EOPNOTSUPP;
4935 }
4936
4937 /**
4938  *      ata_port_online - test whether the given port is online
4939  *      @ap: ATA port to test
4940  *
4941  *      Test whether @ap is online.  Note that this function returns 0
4942  *      if online status of @ap cannot be obtained, so
4943  *      ata_port_online(ap) != !ata_port_offline(ap).
4944  *
4945  *      LOCKING:
4946  *      None.
4947  *
4948  *      RETURNS:
4949  *      1 if the port online status is available and online.
4950  */
4951 int ata_port_online(struct ata_port *ap)
4952 {
4953         u32 sstatus;
4954
4955         if (!sata_scr_read(ap, SCR_STATUS, &sstatus) && (sstatus & 0xf) == 0x3)
4956                 return 1;
4957         return 0;
4958 }
4959
4960 /**
4961  *      ata_port_offline - test whether the given port is offline
4962  *      @ap: ATA port to test
4963  *
4964  *      Test whether @ap is offline.  Note that this function returns
4965  *      0 if offline status of @ap cannot be obtained, so
4966  *      ata_port_online(ap) != !ata_port_offline(ap).
4967  *
4968  *      LOCKING:
4969  *      None.
4970  *
4971  *      RETURNS:
4972  *      1 if the port offline status is available and offline.
4973  */
4974 int ata_port_offline(struct ata_port *ap)
4975 {
4976         u32 sstatus;
4977
4978         if (!sata_scr_read(ap, SCR_STATUS, &sstatus) && (sstatus & 0xf) != 0x3)
4979                 return 1;
4980         return 0;
4981 }
4982
4983 int ata_flush_cache(struct ata_device *dev)
4984 {
4985         unsigned int err_mask;
4986         u8 cmd;
4987
4988         if (!ata_try_flush_cache(dev))
4989                 return 0;
4990
4991         if (ata_id_has_flush_ext(dev->id))
4992                 cmd = ATA_CMD_FLUSH_EXT;
4993         else
4994                 cmd = ATA_CMD_FLUSH;
4995
4996         err_mask = ata_do_simple_cmd(dev, cmd);
4997         if (err_mask) {
4998                 ata_dev_printk(dev, KERN_ERR, "failed to flush cache\n");
4999                 return -EIO;
5000         }
5001
5002         return 0;
5003 }
5004
5005 static int ata_standby_drive(struct ata_device *dev)
5006 {
5007         unsigned int err_mask;
5008
5009         err_mask = ata_do_simple_cmd(dev, ATA_CMD_STANDBYNOW1);
5010         if (err_mask) {
5011                 ata_dev_printk(dev, KERN_ERR, "failed to standby drive "
5012                                "(err_mask=0x%x)\n", err_mask);
5013                 return -EIO;
5014         }
5015
5016         return 0;
5017 }
5018
5019 static int ata_start_drive(struct ata_device *dev)
5020 {
5021         unsigned int err_mask;
5022
5023         err_mask = ata_do_simple_cmd(dev, ATA_CMD_IDLEIMMEDIATE);
5024         if (err_mask) {
5025                 ata_dev_printk(dev, KERN_ERR, "failed to start drive "
5026                                "(err_mask=0x%x)\n", err_mask);
5027                 return -EIO;
5028         }
5029
5030         return 0;
5031 }
5032
5033 /**
5034  *      ata_device_resume - wakeup a previously suspended devices
5035  *      @dev: the device to resume
5036  *
5037  *      Kick the drive back into action, by sending it an idle immediate
5038  *      command and making sure its transfer mode matches between drive
5039  *      and host.
5040  *
5041  */
5042 int ata_device_resume(struct ata_device *dev)
5043 {
5044         struct ata_port *ap = dev->ap;
5045
5046         if (ap->flags & ATA_FLAG_SUSPENDED) {
5047                 struct ata_device *failed_dev;
5048
5049                 ata_busy_sleep(ap, ATA_TMOUT_BOOT_QUICK, ATA_TMOUT_BOOT);
5050                 ata_busy_wait(ap, ATA_BUSY | ATA_DRQ, 200000);
5051
5052                 ap->flags &= ~ATA_FLAG_SUSPENDED;
5053                 while (ata_set_mode(ap, &failed_dev))
5054                         ata_dev_disable(failed_dev);
5055         }
5056         if (!ata_dev_enabled(dev))
5057                 return 0;
5058         if (dev->class == ATA_DEV_ATA)
5059                 ata_start_drive(dev);
5060
5061         return 0;
5062 }
5063
5064 /**
5065  *      ata_device_suspend - prepare a device for suspend
5066  *      @dev: the device to suspend
5067  *      @state: target power management state
5068  *
5069  *      Flush the cache on the drive, if appropriate, then issue a
5070  *      standbynow command.
5071  */
5072 int ata_device_suspend(struct ata_device *dev, pm_message_t state)
5073 {
5074         struct ata_port *ap = dev->ap;
5075
5076         if (!ata_dev_enabled(dev))
5077                 return 0;
5078         if (dev->class == ATA_DEV_ATA)
5079                 ata_flush_cache(dev);
5080
5081         if (state.event != PM_EVENT_FREEZE)
5082                 ata_standby_drive(dev);
5083         ap->flags |= ATA_FLAG_SUSPENDED;
5084         return 0;
5085 }
5086
5087 /**
5088  *      ata_port_start - Set port up for dma.
5089  *      @ap: Port to initialize
5090  *
5091  *      Called just after data structures for each port are
5092  *      initialized.  Allocates space for PRD table.
5093  *
5094  *      May be used as the port_start() entry in ata_port_operations.
5095  *
5096  *      LOCKING:
5097  *      Inherited from caller.
5098  */
5099
5100 int ata_port_start (struct ata_port *ap)
5101 {
5102         struct device *dev = ap->dev;
5103         int rc;
5104
5105         ap->prd = dma_alloc_coherent(dev, ATA_PRD_TBL_SZ, &ap->prd_dma, GFP_KERNEL);
5106         if (!ap->prd)
5107                 return -ENOMEM;
5108
5109         rc = ata_pad_alloc(ap, dev);
5110         if (rc) {
5111                 dma_free_coherent(dev, ATA_PRD_TBL_SZ, ap->prd, ap->prd_dma);
5112                 return rc;
5113         }
5114
5115         DPRINTK("prd alloc, virt %p, dma %llx\n", ap->prd, (unsigned long long) ap->prd_dma);
5116
5117         return 0;
5118 }
5119
5120
5121 /**
5122  *      ata_port_stop - Undo ata_port_start()
5123  *      @ap: Port to shut down
5124  *
5125  *      Frees the PRD table.
5126  *
5127  *      May be used as the port_stop() entry in ata_port_operations.
5128  *
5129  *      LOCKING:
5130  *      Inherited from caller.
5131  */
5132
5133 void ata_port_stop (struct ata_port *ap)
5134 {
5135         struct device *dev = ap->dev;
5136
5137         dma_free_coherent(dev, ATA_PRD_TBL_SZ, ap->prd, ap->prd_dma);
5138         ata_pad_free(ap, dev);
5139 }
5140
5141 void ata_host_stop (struct ata_host_set *host_set)
5142 {
5143         if (host_set->mmio_base)
5144                 iounmap(host_set->mmio_base);
5145 }
5146
5147
5148 /**
5149  *      ata_host_remove - Unregister SCSI host structure with upper layers
5150  *      @ap: Port to unregister
5151  *      @do_unregister: 1 if we fully unregister, 0 to just stop the port
5152  *
5153  *      LOCKING:
5154  *      Inherited from caller.
5155  */
5156
5157 static void ata_host_remove(struct ata_port *ap, unsigned int do_unregister)
5158 {
5159         struct Scsi_Host *sh = ap->host;
5160
5161         DPRINTK("ENTER\n");
5162
5163         if (do_unregister)
5164                 scsi_remove_host(sh);
5165
5166         ap->ops->port_stop(ap);
5167 }
5168
5169 /**
5170  *      ata_dev_init - Initialize an ata_device structure
5171  *      @dev: Device structure to initialize
5172  *
5173  *      Initialize @dev in preparation for probing.
5174  *
5175  *      LOCKING:
5176  *      Inherited from caller.
5177  */
5178 void ata_dev_init(struct ata_device *dev)
5179 {
5180         struct ata_port *ap = dev->ap;
5181         unsigned long flags;
5182
5183         /* SATA spd limit is bound to the first device */
5184         ap->sata_spd_limit = ap->hw_sata_spd_limit;
5185
5186         /* High bits of dev->flags are used to record warm plug
5187          * requests which occur asynchronously.  Synchronize using
5188          * host_set lock.
5189          */
5190         spin_lock_irqsave(ap->lock, flags);
5191         dev->flags &= ~ATA_DFLAG_INIT_MASK;
5192         spin_unlock_irqrestore(ap->lock, flags);
5193
5194         memset((void *)dev + ATA_DEVICE_CLEAR_OFFSET, 0,
5195                sizeof(*dev) - ATA_DEVICE_CLEAR_OFFSET);
5196         dev->pio_mask = UINT_MAX;
5197         dev->mwdma_mask = UINT_MAX;
5198         dev->udma_mask = UINT_MAX;
5199 }
5200
5201 /**
5202  *      ata_host_init - Initialize an ata_port structure
5203  *      @ap: Structure to initialize
5204  *      @host: associated SCSI mid-layer structure
5205  *      @host_set: Collection of hosts to which @ap belongs
5206  *      @ent: Probe information provided by low-level driver
5207  *      @port_no: Port number associated with this ata_port
5208  *
5209  *      Initialize a new ata_port structure, and its associated
5210  *      scsi_host.
5211  *
5212  *      LOCKING:
5213  *      Inherited from caller.
5214  */
5215 static void ata_host_init(struct ata_port *ap, struct Scsi_Host *host,
5216                           struct ata_host_set *host_set,
5217                           const struct ata_probe_ent *ent, unsigned int port_no)
5218 {
5219         unsigned int i;
5220
5221         host->max_id = 16;
5222         host->max_lun = 1;
5223         host->max_channel = 1;
5224         host->unique_id = ata_unique_id++;
5225         host->max_cmd_len = 12;
5226
5227         ap->lock = &host_set->lock;
5228         ap->flags = ATA_FLAG_DISABLED;
5229         ap->id = host->unique_id;
5230         ap->host = host;
5231         ap->ctl = ATA_DEVCTL_OBS;
5232         ap->host_set = host_set;
5233         ap->dev = ent->dev;
5234         ap->port_no = port_no;
5235         ap->hard_port_no =
5236                 ent->legacy_mode ? ent->hard_port_no : port_no;
5237         ap->pio_mask = ent->pio_mask;
5238         ap->mwdma_mask = ent->mwdma_mask;
5239         ap->udma_mask = ent->udma_mask;
5240         ap->flags |= ent->host_flags;
5241         ap->ops = ent->port_ops;
5242         ap->hw_sata_spd_limit = UINT_MAX;
5243         ap->active_tag = ATA_TAG_POISON;
5244         ap->last_ctl = 0xFF;
5245
5246 #if defined(ATA_VERBOSE_DEBUG)
5247         /* turn on all debugging levels */
5248         ap->msg_enable = 0x00FF;
5249 #elif defined(ATA_DEBUG)
5250         ap->msg_enable = ATA_MSG_DRV | ATA_MSG_INFO | ATA_MSG_CTL | ATA_MSG_WARN | ATA_MSG_ERR;
5251 #else
5252         ap->msg_enable = ATA_MSG_DRV | ATA_MSG_ERR | ATA_MSG_WARN;
5253 #endif
5254
5255         INIT_WORK(&ap->port_task, NULL, NULL);
5256         INIT_WORK(&ap->hotplug_task, ata_scsi_hotplug, ap);
5257         INIT_WORK(&ap->scsi_rescan_task, ata_scsi_dev_rescan, ap);
5258         INIT_LIST_HEAD(&ap->eh_done_q);
5259         init_waitqueue_head(&ap->eh_wait_q);
5260
5261         /* set cable type */
5262         ap->cbl = ATA_CBL_NONE;
5263         if (ap->flags & ATA_FLAG_SATA)
5264                 ap->cbl = ATA_CBL_SATA;
5265
5266         for (i = 0; i < ATA_MAX_DEVICES; i++) {
5267                 struct ata_device *dev = &ap->device[i];
5268                 dev->ap = ap;
5269                 dev->devno = i;
5270                 ata_dev_init(dev);
5271         }
5272
5273 #ifdef ATA_IRQ_TRAP
5274         ap->stats.unhandled_irq = 1;
5275         ap->stats.idle_irq = 1;
5276 #endif
5277
5278         memcpy(&ap->ioaddr, &ent->port[port_no], sizeof(struct ata_ioports));
5279 }
5280
5281 /**
5282  *      ata_host_add - Attach low-level ATA driver to system
5283  *      @ent: Information provided by low-level driver
5284  *      @host_set: Collections of ports to which we add
5285  *      @port_no: Port number associated with this host
5286  *
5287  *      Attach low-level ATA driver to system.
5288  *
5289  *      LOCKING:
5290  *      PCI/etc. bus probe sem.
5291  *
5292  *      RETURNS:
5293  *      New ata_port on success, for NULL on error.
5294  */
5295
5296 static struct ata_port * ata_host_add(const struct ata_probe_ent *ent,
5297                                       struct ata_host_set *host_set,
5298                                       unsigned int port_no)
5299 {
5300         struct Scsi_Host *host;
5301         struct ata_port *ap;
5302         int rc;
5303
5304         DPRINTK("ENTER\n");
5305
5306         if (!ent->port_ops->error_handler &&
5307             !(ent->host_flags & (ATA_FLAG_SATA_RESET | ATA_FLAG_SRST))) {
5308                 printk(KERN_ERR "ata%u: no reset mechanism available\n",
5309                        port_no);
5310                 return NULL;
5311         }
5312
5313         host = scsi_host_alloc(ent->sht, sizeof(struct ata_port));
5314         if (!host)
5315                 return NULL;
5316
5317         host->transportt = &ata_scsi_transport_template;
5318
5319         ap = ata_shost_to_port(host);
5320
5321         ata_host_init(ap, host, host_set, ent, port_no);
5322
5323         rc = ap->ops->port_start(ap);
5324         if (rc)
5325                 goto err_out;
5326
5327         return ap;
5328
5329 err_out:
5330         scsi_host_put(host);
5331         return NULL;
5332 }
5333
5334 /**
5335  *      ata_device_add - Register hardware device with ATA and SCSI layers
5336  *      @ent: Probe information describing hardware device to be registered
5337  *
5338  *      This function processes the information provided in the probe
5339  *      information struct @ent, allocates the necessary ATA and SCSI
5340  *      host information structures, initializes them, and registers
5341  *      everything with requisite kernel subsystems.
5342  *
5343  *      This function requests irqs, probes the ATA bus, and probes
5344  *      the SCSI bus.
5345  *
5346  *      LOCKING:
5347  *      PCI/etc. bus probe sem.
5348  *
5349  *      RETURNS:
5350  *      Number of ports registered.  Zero on error (no ports registered).
5351  */
5352 int ata_device_add(const struct ata_probe_ent *ent)
5353 {
5354         unsigned int count = 0, i;
5355         struct device *dev = ent->dev;
5356         struct ata_host_set *host_set;
5357         int rc;
5358
5359         DPRINTK("ENTER\n");
5360         /* alloc a container for our list of ATA ports (buses) */
5361         host_set = kzalloc(sizeof(struct ata_host_set) +
5362                            (ent->n_ports * sizeof(void *)), GFP_KERNEL);
5363         if (!host_set)
5364                 return 0;
5365         spin_lock_init(&host_set->lock);
5366
5367         host_set->dev = dev;
5368         host_set->n_ports = ent->n_ports;
5369         host_set->irq = ent->irq;
5370         host_set->mmio_base = ent->mmio_base;
5371         host_set->private_data = ent->private_data;
5372         host_set->ops = ent->port_ops;
5373         host_set->flags = ent->host_set_flags;
5374
5375         /* register each port bound to this device */
5376         for (i = 0; i < ent->n_ports; i++) {
5377                 struct ata_port *ap;
5378                 unsigned long xfer_mode_mask;
5379
5380                 ap = ata_host_add(ent, host_set, i);
5381                 if (!ap)
5382                         goto err_out;
5383
5384                 host_set->ports[i] = ap;
5385                 xfer_mode_mask =(ap->udma_mask << ATA_SHIFT_UDMA) |
5386                                 (ap->mwdma_mask << ATA_SHIFT_MWDMA) |
5387                                 (ap->pio_mask << ATA_SHIFT_PIO);
5388
5389                 /* print per-port info to dmesg */
5390                 ata_port_printk(ap, KERN_INFO, "%cATA max %s cmd 0x%lX "
5391                                 "ctl 0x%lX bmdma 0x%lX irq %lu\n",
5392                                 ap->flags & ATA_FLAG_SATA ? 'S' : 'P',
5393                                 ata_mode_string(xfer_mode_mask),
5394                                 ap->ioaddr.cmd_addr,
5395                                 ap->ioaddr.ctl_addr,
5396                                 ap->ioaddr.bmdma_addr,
5397                                 ent->irq);
5398
5399                 ata_chk_status(ap);
5400                 host_set->ops->irq_clear(ap);
5401                 ata_eh_freeze_port(ap); /* freeze port before requesting IRQ */
5402                 count++;
5403         }
5404
5405         if (!count)
5406                 goto err_free_ret;
5407
5408         /* obtain irq, that is shared between channels */
5409         rc = request_irq(ent->irq, ent->port_ops->irq_handler, ent->irq_flags,
5410                          DRV_NAME, host_set);
5411         if (rc) {
5412                 dev_printk(KERN_ERR, dev, "irq %lu request failed: %d\n",
5413                            ent->irq, rc);
5414                 goto err_out;
5415         }
5416
5417         /* perform each probe synchronously */
5418         DPRINTK("probe begin\n");
5419         for (i = 0; i < count; i++) {
5420                 struct ata_port *ap;
5421                 u32 scontrol;
5422                 int rc;
5423
5424                 ap = host_set->ports[i];
5425
5426                 /* init sata_spd_limit to the current value */
5427                 if (sata_scr_read(ap, SCR_CONTROL, &scontrol) == 0) {
5428                         int spd = (scontrol >> 4) & 0xf;
5429                         ap->hw_sata_spd_limit &= (1 << spd) - 1;
5430                 }
5431                 ap->sata_spd_limit = ap->hw_sata_spd_limit;
5432
5433                 rc = scsi_add_host(ap->host, dev);
5434                 if (rc) {
5435                         ata_port_printk(ap, KERN_ERR, "scsi_add_host failed\n");
5436                         /* FIXME: do something useful here */
5437                         /* FIXME: handle unconditional calls to
5438                          * scsi_scan_host and ata_host_remove, below,
5439                          * at the very least
5440                          */
5441                 }
5442
5443                 if (ap->ops->error_handler) {
5444                         unsigned long flags;
5445
5446                         ata_port_probe(ap);
5447
5448                         /* kick EH for boot probing */
5449                         spin_lock_irqsave(ap->lock, flags);
5450
5451                         ap->eh_info.probe_mask = (1 << ATA_MAX_DEVICES) - 1;
5452                         ap->eh_info.action |= ATA_EH_SOFTRESET;
5453
5454                         ap->flags |= ATA_FLAG_LOADING;
5455                         ata_port_schedule_eh(ap);
5456
5457                         spin_unlock_irqrestore(ap->lock, flags);
5458
5459                         /* wait for EH to finish */
5460                         ata_port_wait_eh(ap);
5461                 } else {
5462                         DPRINTK("ata%u: bus probe begin\n", ap->id);
5463                         rc = ata_bus_probe(ap);
5464                         DPRINTK("ata%u: bus probe end\n", ap->id);
5465
5466                         if (rc) {
5467                                 /* FIXME: do something useful here?
5468                                  * Current libata behavior will
5469                                  * tear down everything when
5470                                  * the module is removed
5471                                  * or the h/w is unplugged.
5472                                  */
5473                         }
5474                 }
5475         }
5476
5477         /* probes are done, now scan each port's disk(s) */
5478         DPRINTK("host probe begin\n");
5479         for (i = 0; i < count; i++) {
5480                 struct ata_port *ap = host_set->ports[i];
5481
5482                 ata_scsi_scan_host(ap);
5483         }
5484
5485         dev_set_drvdata(dev, host_set);
5486
5487         VPRINTK("EXIT, returning %u\n", ent->n_ports);
5488         return ent->n_ports; /* success */
5489
5490 err_out:
5491         for (i = 0; i < count; i++) {
5492                 ata_host_remove(host_set->ports[i], 1);
5493                 scsi_host_put(host_set->ports[i]->host);
5494         }
5495 err_free_ret:
5496         kfree(host_set);
5497         VPRINTK("EXIT, returning 0\n");
5498         return 0;
5499 }
5500
5501 /**
5502  *      ata_port_detach - Detach ATA port in prepration of device removal
5503  *      @ap: ATA port to be detached
5504  *
5505  *      Detach all ATA devices and the associated SCSI devices of @ap;
5506  *      then, remove the associated SCSI host.  @ap is guaranteed to
5507  *      be quiescent on return from this function.
5508  *
5509  *      LOCKING:
5510  *      Kernel thread context (may sleep).
5511  */
5512 void ata_port_detach(struct ata_port *ap)
5513 {
5514         unsigned long flags;
5515         int i;
5516
5517         if (!ap->ops->error_handler)
5518                 return;
5519
5520         /* tell EH we're leaving & flush EH */
5521         spin_lock_irqsave(ap->lock, flags);
5522         ap->flags |= ATA_FLAG_UNLOADING;
5523         spin_unlock_irqrestore(ap->lock, flags);
5524
5525         ata_port_wait_eh(ap);
5526
5527         /* EH is now guaranteed to see UNLOADING, so no new device
5528          * will be attached.  Disable all existing devices.
5529          */
5530         spin_lock_irqsave(ap->lock, flags);
5531
5532         for (i = 0; i < ATA_MAX_DEVICES; i++)
5533                 ata_dev_disable(&ap->device[i]);
5534
5535         spin_unlock_irqrestore(ap->lock, flags);
5536
5537         /* Final freeze & EH.  All in-flight commands are aborted.  EH
5538          * will be skipped and retrials will be terminated with bad
5539          * target.
5540          */
5541         spin_lock_irqsave(ap->lock, flags);
5542         ata_port_freeze(ap);    /* won't be thawed */
5543         spin_unlock_irqrestore(ap->lock, flags);
5544
5545         ata_port_wait_eh(ap);
5546
5547         /* Flush hotplug task.  The sequence is similar to
5548          * ata_port_flush_task().
5549          */
5550         flush_workqueue(ata_aux_wq);
5551         cancel_delayed_work(&ap->hotplug_task);
5552         flush_workqueue(ata_aux_wq);
5553
5554         /* remove the associated SCSI host */
5555         scsi_remove_host(ap->host);
5556 }
5557
5558 /**
5559  *      ata_host_set_remove - PCI layer callback for device removal
5560  *      @host_set: ATA host set that was removed
5561  *
5562  *      Unregister all objects associated with this host set. Free those
5563  *      objects.
5564  *
5565  *      LOCKING:
5566  *      Inherited from calling layer (may sleep).
5567  */
5568
5569 void ata_host_set_remove(struct ata_host_set *host_set)
5570 {
5571         unsigned int i;
5572
5573         for (i = 0; i < host_set->n_ports; i++)
5574                 ata_port_detach(host_set->ports[i]);
5575
5576         free_irq(host_set->irq, host_set);
5577
5578         for (i = 0; i < host_set->n_ports; i++) {
5579                 struct ata_port *ap = host_set->ports[i];
5580
5581                 ata_scsi_release(ap->host);
5582
5583                 if ((ap->flags & ATA_FLAG_NO_LEGACY) == 0) {
5584                         struct ata_ioports *ioaddr = &ap->ioaddr;
5585
5586                         if (ioaddr->cmd_addr == 0x1f0)
5587                                 release_region(0x1f0, 8);
5588                         else if (ioaddr->cmd_addr == 0x170)
5589                                 release_region(0x170, 8);
5590                 }
5591
5592                 scsi_host_put(ap->host);
5593         }
5594
5595         if (host_set->ops->host_stop)
5596                 host_set->ops->host_stop(host_set);
5597
5598         kfree(host_set);
5599 }
5600
5601 /**
5602  *      ata_scsi_release - SCSI layer callback hook for host unload
5603  *      @host: libata host to be unloaded
5604  *
5605  *      Performs all duties necessary to shut down a libata port...
5606  *      Kill port kthread, disable port, and release resources.
5607  *
5608  *      LOCKING:
5609  *      Inherited from SCSI layer.
5610  *
5611  *      RETURNS:
5612  *      One.
5613  */
5614
5615 int ata_scsi_release(struct Scsi_Host *host)
5616 {
5617         struct ata_port *ap = ata_shost_to_port(host);
5618
5619         DPRINTK("ENTER\n");
5620
5621         ap->ops->port_disable(ap);
5622         ata_host_remove(ap, 0);
5623
5624         DPRINTK("EXIT\n");
5625         return 1;
5626 }
5627
5628 /**
5629  *      ata_std_ports - initialize ioaddr with standard port offsets.
5630  *      @ioaddr: IO address structure to be initialized
5631  *
5632  *      Utility function which initializes data_addr, error_addr,
5633  *      feature_addr, nsect_addr, lbal_addr, lbam_addr, lbah_addr,
5634  *      device_addr, status_addr, and command_addr to standard offsets
5635  *      relative to cmd_addr.
5636  *
5637  *      Does not set ctl_addr, altstatus_addr, bmdma_addr, or scr_addr.
5638  */
5639
5640 void ata_std_ports(struct ata_ioports *ioaddr)
5641 {
5642         ioaddr->data_addr = ioaddr->cmd_addr + ATA_REG_DATA;
5643         ioaddr->error_addr = ioaddr->cmd_addr + ATA_REG_ERR;
5644         ioaddr->feature_addr = ioaddr->cmd_addr + ATA_REG_FEATURE;
5645         ioaddr->nsect_addr = ioaddr->cmd_addr + ATA_REG_NSECT;
5646         ioaddr->lbal_addr = ioaddr->cmd_addr + ATA_REG_LBAL;
5647         ioaddr->lbam_addr = ioaddr->cmd_addr + ATA_REG_LBAM;
5648         ioaddr->lbah_addr = ioaddr->cmd_addr + ATA_REG_LBAH;
5649         ioaddr->device_addr = ioaddr->cmd_addr + ATA_REG_DEVICE;
5650         ioaddr->status_addr = ioaddr->cmd_addr + ATA_REG_STATUS;
5651         ioaddr->command_addr = ioaddr->cmd_addr + ATA_REG_CMD;
5652 }
5653
5654
5655 #ifdef CONFIG_PCI
5656
5657 void ata_pci_host_stop (struct ata_host_set *host_set)
5658 {
5659         struct pci_dev *pdev = to_pci_dev(host_set->dev);
5660
5661         pci_iounmap(pdev, host_set->mmio_base);
5662 }
5663
5664 /**
5665  *      ata_pci_remove_one - PCI layer callback for device removal
5666  *      @pdev: PCI device that was removed
5667  *
5668  *      PCI layer indicates to libata via this hook that
5669  *      hot-unplug or module unload event has occurred.
5670  *      Handle this by unregistering all objects associated
5671  *      with this PCI device.  Free those objects.  Then finally
5672  *      release PCI resources and disable device.
5673  *
5674  *      LOCKING:
5675  *      Inherited from PCI layer (may sleep).
5676  */
5677
5678 void ata_pci_remove_one (struct pci_dev *pdev)
5679 {
5680         struct device *dev = pci_dev_to_dev(pdev);
5681         struct ata_host_set *host_set = dev_get_drvdata(dev);
5682         struct ata_host_set *host_set2 = host_set->next;
5683
5684         ata_host_set_remove(host_set);
5685         if (host_set2)
5686                 ata_host_set_remove(host_set2);
5687
5688         pci_release_regions(pdev);
5689         pci_disable_device(pdev);
5690         dev_set_drvdata(dev, NULL);
5691 }
5692
5693 /* move to PCI subsystem */
5694 int pci_test_config_bits(struct pci_dev *pdev, const struct pci_bits *bits)
5695 {
5696         unsigned long tmp = 0;
5697
5698         switch (bits->width) {
5699         case 1: {
5700                 u8 tmp8 = 0;
5701                 pci_read_config_byte(pdev, bits->reg, &tmp8);
5702                 tmp = tmp8;
5703                 break;
5704         }
5705         case 2: {
5706                 u16 tmp16 = 0;
5707                 pci_read_config_word(pdev, bits->reg, &tmp16);
5708                 tmp = tmp16;
5709                 break;
5710         }
5711         case 4: {
5712                 u32 tmp32 = 0;
5713                 pci_read_config_dword(pdev, bits->reg, &tmp32);
5714                 tmp = tmp32;
5715                 break;
5716         }
5717
5718         default:
5719                 return -EINVAL;
5720         }
5721
5722         tmp &= bits->mask;
5723
5724         return (tmp == bits->val) ? 1 : 0;
5725 }
5726
5727 int ata_pci_device_suspend(struct pci_dev *pdev, pm_message_t state)
5728 {
5729         pci_save_state(pdev);
5730         pci_disable_device(pdev);
5731         pci_set_power_state(pdev, PCI_D3hot);
5732         return 0;
5733 }
5734
5735 int ata_pci_device_resume(struct pci_dev *pdev)
5736 {
5737         pci_set_power_state(pdev, PCI_D0);
5738         pci_restore_state(pdev);
5739         pci_enable_device(pdev);
5740         pci_set_master(pdev);
5741         return 0;
5742 }
5743 #endif /* CONFIG_PCI */
5744
5745
5746 static int __init ata_init(void)
5747 {
5748         ata_probe_timeout *= HZ;
5749         ata_wq = create_workqueue("ata");
5750         if (!ata_wq)
5751                 return -ENOMEM;
5752
5753         ata_aux_wq = create_singlethread_workqueue("ata_aux");
5754         if (!ata_aux_wq) {
5755                 destroy_workqueue(ata_wq);
5756                 return -ENOMEM;
5757         }
5758
5759         printk(KERN_DEBUG "libata version " DRV_VERSION " loaded.\n");
5760         return 0;
5761 }
5762
5763 static void __exit ata_exit(void)
5764 {
5765         destroy_workqueue(ata_wq);
5766         destroy_workqueue(ata_aux_wq);
5767 }
5768
5769 module_init(ata_init);
5770 module_exit(ata_exit);
5771
5772 static unsigned long ratelimit_time;
5773 static DEFINE_SPINLOCK(ata_ratelimit_lock);
5774
5775 int ata_ratelimit(void)
5776 {
5777         int rc;
5778         unsigned long flags;
5779
5780         spin_lock_irqsave(&ata_ratelimit_lock, flags);
5781
5782         if (time_after(jiffies, ratelimit_time)) {
5783                 rc = 1;
5784                 ratelimit_time = jiffies + (HZ/5);
5785         } else
5786                 rc = 0;
5787
5788         spin_unlock_irqrestore(&ata_ratelimit_lock, flags);
5789
5790         return rc;
5791 }
5792
5793 /**
5794  *      ata_wait_register - wait until register value changes
5795  *      @reg: IO-mapped register
5796  *      @mask: Mask to apply to read register value
5797  *      @val: Wait condition
5798  *      @interval_msec: polling interval in milliseconds
5799  *      @timeout_msec: timeout in milliseconds
5800  *
5801  *      Waiting for some bits of register to change is a common
5802  *      operation for ATA controllers.  This function reads 32bit LE
5803  *      IO-mapped register @reg and tests for the following condition.
5804  *
5805  *      (*@reg & mask) != val
5806  *
5807  *      If the condition is met, it returns; otherwise, the process is
5808  *      repeated after @interval_msec until timeout.
5809  *
5810  *      LOCKING:
5811  *      Kernel thread context (may sleep)
5812  *
5813  *      RETURNS:
5814  *      The final register value.
5815  */
5816 u32 ata_wait_register(void __iomem *reg, u32 mask, u32 val,
5817                       unsigned long interval_msec,
5818                       unsigned long timeout_msec)
5819 {
5820         unsigned long timeout;
5821         u32 tmp;
5822
5823         tmp = ioread32(reg);
5824
5825         /* Calculate timeout _after_ the first read to make sure
5826          * preceding writes reach the controller before starting to
5827          * eat away the timeout.
5828          */
5829         timeout = jiffies + (timeout_msec * HZ) / 1000;
5830
5831         while ((tmp & mask) == val && time_before(jiffies, timeout)) {
5832                 msleep(interval_msec);
5833                 tmp = ioread32(reg);
5834         }
5835
5836         return tmp;
5837 }
5838
5839 /*
5840  * libata is essentially a library of internal helper functions for
5841  * low-level ATA host controller drivers.  As such, the API/ABI is
5842  * likely to change as new drivers are added and updated.
5843  * Do not depend on ABI/API stability.
5844  */
5845
5846 EXPORT_SYMBOL_GPL(sata_deb_timing_boot);
5847 EXPORT_SYMBOL_GPL(sata_deb_timing_eh);
5848 EXPORT_SYMBOL_GPL(sata_deb_timing_before_fsrst);
5849 EXPORT_SYMBOL_GPL(ata_std_bios_param);
5850 EXPORT_SYMBOL_GPL(ata_std_ports);
5851 EXPORT_SYMBOL_GPL(ata_device_add);
5852 EXPORT_SYMBOL_GPL(ata_port_detach);
5853 EXPORT_SYMBOL_GPL(ata_host_set_remove);
5854 EXPORT_SYMBOL_GPL(ata_sg_init);
5855 EXPORT_SYMBOL_GPL(ata_sg_init_one);
5856 EXPORT_SYMBOL_GPL(ata_hsm_move);
5857 EXPORT_SYMBOL_GPL(ata_qc_complete);
5858 EXPORT_SYMBOL_GPL(ata_qc_complete_multiple);
5859 EXPORT_SYMBOL_GPL(ata_qc_issue_prot);
5860 EXPORT_SYMBOL_GPL(ata_tf_load);
5861 EXPORT_SYMBOL_GPL(ata_tf_read);
5862 EXPORT_SYMBOL_GPL(ata_noop_dev_select);
5863 EXPORT_SYMBOL_GPL(ata_std_dev_select);
5864 EXPORT_SYMBOL_GPL(ata_tf_to_fis);
5865 EXPORT_SYMBOL_GPL(ata_tf_from_fis);
5866 EXPORT_SYMBOL_GPL(ata_check_status);
5867 EXPORT_SYMBOL_GPL(ata_altstatus);
5868 EXPORT_SYMBOL_GPL(ata_exec_command);
5869 EXPORT_SYMBOL_GPL(ata_port_start);
5870 EXPORT_SYMBOL_GPL(ata_port_stop);
5871 EXPORT_SYMBOL_GPL(ata_host_stop);
5872 EXPORT_SYMBOL_GPL(ata_interrupt);
5873 EXPORT_SYMBOL_GPL(ata_mmio_data_xfer);
5874 EXPORT_SYMBOL_GPL(ata_pio_data_xfer);
5875 EXPORT_SYMBOL_GPL(ata_pio_data_xfer_noirq);
5876 EXPORT_SYMBOL_GPL(ata_qc_prep);
5877 EXPORT_SYMBOL_GPL(ata_noop_qc_prep);
5878 EXPORT_SYMBOL_GPL(ata_bmdma_setup);
5879 EXPORT_SYMBOL_GPL(ata_bmdma_start);
5880 EXPORT_SYMBOL_GPL(ata_bmdma_irq_clear);
5881 EXPORT_SYMBOL_GPL(ata_bmdma_status);
5882 EXPORT_SYMBOL_GPL(ata_bmdma_stop);
5883 EXPORT_SYMBOL_GPL(ata_bmdma_freeze);
5884 EXPORT_SYMBOL_GPL(ata_bmdma_thaw);
5885 EXPORT_SYMBOL_GPL(ata_bmdma_drive_eh);
5886 EXPORT_SYMBOL_GPL(ata_bmdma_error_handler);
5887 EXPORT_SYMBOL_GPL(ata_bmdma_post_internal_cmd);
5888 EXPORT_SYMBOL_GPL(ata_port_probe);
5889 EXPORT_SYMBOL_GPL(sata_set_spd);
5890 EXPORT_SYMBOL_GPL(sata_phy_debounce);
5891 EXPORT_SYMBOL_GPL(sata_phy_resume);
5892 EXPORT_SYMBOL_GPL(sata_phy_reset);
5893 EXPORT_SYMBOL_GPL(__sata_phy_reset);
5894 EXPORT_SYMBOL_GPL(ata_bus_reset);
5895 EXPORT_SYMBOL_GPL(ata_std_prereset);
5896 EXPORT_SYMBOL_GPL(ata_std_softreset);
5897 EXPORT_SYMBOL_GPL(sata_std_hardreset);
5898 EXPORT_SYMBOL_GPL(ata_std_postreset);
5899 EXPORT_SYMBOL_GPL(ata_dev_revalidate);
5900 EXPORT_SYMBOL_GPL(ata_dev_classify);
5901 EXPORT_SYMBOL_GPL(ata_dev_pair);
5902 EXPORT_SYMBOL_GPL(ata_port_disable);
5903 EXPORT_SYMBOL_GPL(ata_ratelimit);
5904 EXPORT_SYMBOL_GPL(ata_wait_register);
5905 EXPORT_SYMBOL_GPL(ata_busy_sleep);
5906 EXPORT_SYMBOL_GPL(ata_port_queue_task);
5907 EXPORT_SYMBOL_GPL(ata_scsi_ioctl);
5908 EXPORT_SYMBOL_GPL(ata_scsi_queuecmd);
5909 EXPORT_SYMBOL_GPL(ata_scsi_slave_config);
5910 EXPORT_SYMBOL_GPL(ata_scsi_slave_destroy);
5911 EXPORT_SYMBOL_GPL(ata_scsi_change_queue_depth);
5912 EXPORT_SYMBOL_GPL(ata_scsi_release);
5913 EXPORT_SYMBOL_GPL(ata_host_intr);
5914 EXPORT_SYMBOL_GPL(sata_scr_valid);
5915 EXPORT_SYMBOL_GPL(sata_scr_read);
5916 EXPORT_SYMBOL_GPL(sata_scr_write);
5917 EXPORT_SYMBOL_GPL(sata_scr_write_flush);
5918 EXPORT_SYMBOL_GPL(ata_port_online);
5919 EXPORT_SYMBOL_GPL(ata_port_offline);
5920 EXPORT_SYMBOL_GPL(ata_id_string);
5921 EXPORT_SYMBOL_GPL(ata_id_c_string);
5922 EXPORT_SYMBOL_GPL(ata_scsi_simulate);
5923
5924 EXPORT_SYMBOL_GPL(ata_pio_need_iordy);
5925 EXPORT_SYMBOL_GPL(ata_timing_compute);
5926 EXPORT_SYMBOL_GPL(ata_timing_merge);
5927
5928 #ifdef CONFIG_PCI
5929 EXPORT_SYMBOL_GPL(pci_test_config_bits);
5930 EXPORT_SYMBOL_GPL(ata_pci_host_stop);
5931 EXPORT_SYMBOL_GPL(ata_pci_init_native_mode);
5932 EXPORT_SYMBOL_GPL(ata_pci_init_one);
5933 EXPORT_SYMBOL_GPL(ata_pci_remove_one);
5934 EXPORT_SYMBOL_GPL(ata_pci_device_suspend);
5935 EXPORT_SYMBOL_GPL(ata_pci_device_resume);
5936 EXPORT_SYMBOL_GPL(ata_pci_default_filter);
5937 EXPORT_SYMBOL_GPL(ata_pci_clear_simplex);
5938 #endif /* CONFIG_PCI */
5939
5940 EXPORT_SYMBOL_GPL(ata_device_suspend);
5941 EXPORT_SYMBOL_GPL(ata_device_resume);
5942 EXPORT_SYMBOL_GPL(ata_scsi_device_suspend);
5943 EXPORT_SYMBOL_GPL(ata_scsi_device_resume);
5944
5945 EXPORT_SYMBOL_GPL(ata_eng_timeout);
5946 EXPORT_SYMBOL_GPL(ata_port_schedule_eh);
5947 EXPORT_SYMBOL_GPL(ata_port_abort);
5948 EXPORT_SYMBOL_GPL(ata_port_freeze);
5949 EXPORT_SYMBOL_GPL(ata_eh_freeze_port);
5950 EXPORT_SYMBOL_GPL(ata_eh_thaw_port);
5951 EXPORT_SYMBOL_GPL(ata_eh_qc_complete);
5952 EXPORT_SYMBOL_GPL(ata_eh_qc_retry);
5953 EXPORT_SYMBOL_GPL(ata_do_eh);