dce65651d8586ffb67c4bf4dcc3efc38940cc8b0
[sfrench/cifs-2.6.git] / drivers / ata / libata-core.c
1 /*
2  *  libata-core.c - helper library for ATA
3  *
4  *  Maintained by:  Jeff Garzik <jgarzik@pobox.com>
5  *                  Please ALWAYS copy linux-ide@vger.kernel.org
6  *                  on emails.
7  *
8  *  Copyright 2003-2004 Red Hat, Inc.  All rights reserved.
9  *  Copyright 2003-2004 Jeff Garzik
10  *
11  *
12  *  This program is free software; you can redistribute it and/or modify
13  *  it under the terms of the GNU General Public License as published by
14  *  the Free Software Foundation; either version 2, or (at your option)
15  *  any later version.
16  *
17  *  This program is distributed in the hope that it will be useful,
18  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
19  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  *  GNU General Public License for more details.
21  *
22  *  You should have received a copy of the GNU General Public License
23  *  along with this program; see the file COPYING.  If not, write to
24  *  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
25  *
26  *
27  *  libata documentation is available via 'make {ps|pdf}docs',
28  *  as Documentation/DocBook/libata.*
29  *
30  *  Hardware documentation available from http://www.t13.org/ and
31  *  http://www.sata-io.org/
32  *
33  */
34
35 #include <linux/kernel.h>
36 #include <linux/module.h>
37 #include <linux/pci.h>
38 #include <linux/init.h>
39 #include <linux/list.h>
40 #include <linux/mm.h>
41 #include <linux/highmem.h>
42 #include <linux/spinlock.h>
43 #include <linux/blkdev.h>
44 #include <linux/delay.h>
45 #include <linux/timer.h>
46 #include <linux/interrupt.h>
47 #include <linux/completion.h>
48 #include <linux/suspend.h>
49 #include <linux/workqueue.h>
50 #include <linux/jiffies.h>
51 #include <linux/scatterlist.h>
52 #include <scsi/scsi.h>
53 #include <scsi/scsi_cmnd.h>
54 #include <scsi/scsi_host.h>
55 #include <linux/libata.h>
56 #include <asm/io.h>
57 #include <asm/semaphore.h>
58 #include <asm/byteorder.h>
59
60 #include "libata.h"
61
62 /* debounce timing parameters in msecs { interval, duration, timeout } */
63 const unsigned long sata_deb_timing_normal[]            = {   5,  100, 2000 };
64 const unsigned long sata_deb_timing_hotplug[]           = {  25,  500, 2000 };
65 const unsigned long sata_deb_timing_long[]              = { 100, 2000, 5000 };
66
67 static unsigned int ata_dev_init_params(struct ata_device *dev,
68                                         u16 heads, u16 sectors);
69 static unsigned int ata_dev_set_xfermode(struct ata_device *dev);
70 static void ata_dev_xfermask(struct ata_device *dev);
71
72 static unsigned int ata_unique_id = 1;
73 static struct workqueue_struct *ata_wq;
74
75 struct workqueue_struct *ata_aux_wq;
76
77 int atapi_enabled = 1;
78 module_param(atapi_enabled, int, 0444);
79 MODULE_PARM_DESC(atapi_enabled, "Enable discovery of ATAPI devices (0=off, 1=on)");
80
81 int atapi_dmadir = 0;
82 module_param(atapi_dmadir, int, 0444);
83 MODULE_PARM_DESC(atapi_dmadir, "Enable ATAPI DMADIR bridge support (0=off, 1=on)");
84
85 int libata_fua = 0;
86 module_param_named(fua, libata_fua, int, 0444);
87 MODULE_PARM_DESC(fua, "FUA support (0=off, 1=on)");
88
89 static int ata_probe_timeout = ATA_TMOUT_INTERNAL / HZ;
90 module_param(ata_probe_timeout, int, 0444);
91 MODULE_PARM_DESC(ata_probe_timeout, "Set ATA probing timeout (seconds)");
92
93 MODULE_AUTHOR("Jeff Garzik");
94 MODULE_DESCRIPTION("Library module for ATA devices");
95 MODULE_LICENSE("GPL");
96 MODULE_VERSION(DRV_VERSION);
97
98
99 /**
100  *      ata_tf_to_fis - Convert ATA taskfile to SATA FIS structure
101  *      @tf: Taskfile to convert
102  *      @fis: Buffer into which data will output
103  *      @pmp: Port multiplier port
104  *
105  *      Converts a standard ATA taskfile to a Serial ATA
106  *      FIS structure (Register - Host to Device).
107  *
108  *      LOCKING:
109  *      Inherited from caller.
110  */
111
112 void ata_tf_to_fis(const struct ata_taskfile *tf, u8 *fis, u8 pmp)
113 {
114         fis[0] = 0x27;  /* Register - Host to Device FIS */
115         fis[1] = (pmp & 0xf) | (1 << 7); /* Port multiplier number,
116                                             bit 7 indicates Command FIS */
117         fis[2] = tf->command;
118         fis[3] = tf->feature;
119
120         fis[4] = tf->lbal;
121         fis[5] = tf->lbam;
122         fis[6] = tf->lbah;
123         fis[7] = tf->device;
124
125         fis[8] = tf->hob_lbal;
126         fis[9] = tf->hob_lbam;
127         fis[10] = tf->hob_lbah;
128         fis[11] = tf->hob_feature;
129
130         fis[12] = tf->nsect;
131         fis[13] = tf->hob_nsect;
132         fis[14] = 0;
133         fis[15] = tf->ctl;
134
135         fis[16] = 0;
136         fis[17] = 0;
137         fis[18] = 0;
138         fis[19] = 0;
139 }
140
141 /**
142  *      ata_tf_from_fis - Convert SATA FIS to ATA taskfile
143  *      @fis: Buffer from which data will be input
144  *      @tf: Taskfile to output
145  *
146  *      Converts a serial ATA FIS structure to a standard ATA taskfile.
147  *
148  *      LOCKING:
149  *      Inherited from caller.
150  */
151
152 void ata_tf_from_fis(const u8 *fis, struct ata_taskfile *tf)
153 {
154         tf->command     = fis[2];       /* status */
155         tf->feature     = fis[3];       /* error */
156
157         tf->lbal        = fis[4];
158         tf->lbam        = fis[5];
159         tf->lbah        = fis[6];
160         tf->device      = fis[7];
161
162         tf->hob_lbal    = fis[8];
163         tf->hob_lbam    = fis[9];
164         tf->hob_lbah    = fis[10];
165
166         tf->nsect       = fis[12];
167         tf->hob_nsect   = fis[13];
168 }
169
170 static const u8 ata_rw_cmds[] = {
171         /* pio multi */
172         ATA_CMD_READ_MULTI,
173         ATA_CMD_WRITE_MULTI,
174         ATA_CMD_READ_MULTI_EXT,
175         ATA_CMD_WRITE_MULTI_EXT,
176         0,
177         0,
178         0,
179         ATA_CMD_WRITE_MULTI_FUA_EXT,
180         /* pio */
181         ATA_CMD_PIO_READ,
182         ATA_CMD_PIO_WRITE,
183         ATA_CMD_PIO_READ_EXT,
184         ATA_CMD_PIO_WRITE_EXT,
185         0,
186         0,
187         0,
188         0,
189         /* dma */
190         ATA_CMD_READ,
191         ATA_CMD_WRITE,
192         ATA_CMD_READ_EXT,
193         ATA_CMD_WRITE_EXT,
194         0,
195         0,
196         0,
197         ATA_CMD_WRITE_FUA_EXT
198 };
199
200 /**
201  *      ata_rwcmd_protocol - set taskfile r/w commands and protocol
202  *      @qc: command to examine and configure
203  *
204  *      Examine the device configuration and tf->flags to calculate
205  *      the proper read/write commands and protocol to use.
206  *
207  *      LOCKING:
208  *      caller.
209  */
210 int ata_rwcmd_protocol(struct ata_queued_cmd *qc)
211 {
212         struct ata_taskfile *tf = &qc->tf;
213         struct ata_device *dev = qc->dev;
214         u8 cmd;
215
216         int index, fua, lba48, write;
217
218         fua = (tf->flags & ATA_TFLAG_FUA) ? 4 : 0;
219         lba48 = (tf->flags & ATA_TFLAG_LBA48) ? 2 : 0;
220         write = (tf->flags & ATA_TFLAG_WRITE) ? 1 : 0;
221
222         if (dev->flags & ATA_DFLAG_PIO) {
223                 tf->protocol = ATA_PROT_PIO;
224                 index = dev->multi_count ? 0 : 8;
225         } else if (lba48 && (qc->ap->flags & ATA_FLAG_PIO_LBA48)) {
226                 /* Unable to use DMA due to host limitation */
227                 tf->protocol = ATA_PROT_PIO;
228                 index = dev->multi_count ? 0 : 8;
229         } else {
230                 tf->protocol = ATA_PROT_DMA;
231                 index = 16;
232         }
233
234         cmd = ata_rw_cmds[index + fua + lba48 + write];
235         if (cmd) {
236                 tf->command = cmd;
237                 return 0;
238         }
239         return -1;
240 }
241
242 /**
243  *      ata_pack_xfermask - Pack pio, mwdma and udma masks into xfer_mask
244  *      @pio_mask: pio_mask
245  *      @mwdma_mask: mwdma_mask
246  *      @udma_mask: udma_mask
247  *
248  *      Pack @pio_mask, @mwdma_mask and @udma_mask into a single
249  *      unsigned int xfer_mask.
250  *
251  *      LOCKING:
252  *      None.
253  *
254  *      RETURNS:
255  *      Packed xfer_mask.
256  */
257 static unsigned int ata_pack_xfermask(unsigned int pio_mask,
258                                       unsigned int mwdma_mask,
259                                       unsigned int udma_mask)
260 {
261         return ((pio_mask << ATA_SHIFT_PIO) & ATA_MASK_PIO) |
262                 ((mwdma_mask << ATA_SHIFT_MWDMA) & ATA_MASK_MWDMA) |
263                 ((udma_mask << ATA_SHIFT_UDMA) & ATA_MASK_UDMA);
264 }
265
266 /**
267  *      ata_unpack_xfermask - Unpack xfer_mask into pio, mwdma and udma masks
268  *      @xfer_mask: xfer_mask to unpack
269  *      @pio_mask: resulting pio_mask
270  *      @mwdma_mask: resulting mwdma_mask
271  *      @udma_mask: resulting udma_mask
272  *
273  *      Unpack @xfer_mask into @pio_mask, @mwdma_mask and @udma_mask.
274  *      Any NULL distination masks will be ignored.
275  */
276 static void ata_unpack_xfermask(unsigned int xfer_mask,
277                                 unsigned int *pio_mask,
278                                 unsigned int *mwdma_mask,
279                                 unsigned int *udma_mask)
280 {
281         if (pio_mask)
282                 *pio_mask = (xfer_mask & ATA_MASK_PIO) >> ATA_SHIFT_PIO;
283         if (mwdma_mask)
284                 *mwdma_mask = (xfer_mask & ATA_MASK_MWDMA) >> ATA_SHIFT_MWDMA;
285         if (udma_mask)
286                 *udma_mask = (xfer_mask & ATA_MASK_UDMA) >> ATA_SHIFT_UDMA;
287 }
288
289 static const struct ata_xfer_ent {
290         int shift, bits;
291         u8 base;
292 } ata_xfer_tbl[] = {
293         { ATA_SHIFT_PIO, ATA_BITS_PIO, XFER_PIO_0 },
294         { ATA_SHIFT_MWDMA, ATA_BITS_MWDMA, XFER_MW_DMA_0 },
295         { ATA_SHIFT_UDMA, ATA_BITS_UDMA, XFER_UDMA_0 },
296         { -1, },
297 };
298
299 /**
300  *      ata_xfer_mask2mode - Find matching XFER_* for the given xfer_mask
301  *      @xfer_mask: xfer_mask of interest
302  *
303  *      Return matching XFER_* value for @xfer_mask.  Only the highest
304  *      bit of @xfer_mask is considered.
305  *
306  *      LOCKING:
307  *      None.
308  *
309  *      RETURNS:
310  *      Matching XFER_* value, 0 if no match found.
311  */
312 static u8 ata_xfer_mask2mode(unsigned int xfer_mask)
313 {
314         int highbit = fls(xfer_mask) - 1;
315         const struct ata_xfer_ent *ent;
316
317         for (ent = ata_xfer_tbl; ent->shift >= 0; ent++)
318                 if (highbit >= ent->shift && highbit < ent->shift + ent->bits)
319                         return ent->base + highbit - ent->shift;
320         return 0;
321 }
322
323 /**
324  *      ata_xfer_mode2mask - Find matching xfer_mask for XFER_*
325  *      @xfer_mode: XFER_* of interest
326  *
327  *      Return matching xfer_mask for @xfer_mode.
328  *
329  *      LOCKING:
330  *      None.
331  *
332  *      RETURNS:
333  *      Matching xfer_mask, 0 if no match found.
334  */
335 static unsigned int ata_xfer_mode2mask(u8 xfer_mode)
336 {
337         const struct ata_xfer_ent *ent;
338
339         for (ent = ata_xfer_tbl; ent->shift >= 0; ent++)
340                 if (xfer_mode >= ent->base && xfer_mode < ent->base + ent->bits)
341                         return 1 << (ent->shift + xfer_mode - ent->base);
342         return 0;
343 }
344
345 /**
346  *      ata_xfer_mode2shift - Find matching xfer_shift for XFER_*
347  *      @xfer_mode: XFER_* of interest
348  *
349  *      Return matching xfer_shift for @xfer_mode.
350  *
351  *      LOCKING:
352  *      None.
353  *
354  *      RETURNS:
355  *      Matching xfer_shift, -1 if no match found.
356  */
357 static int ata_xfer_mode2shift(unsigned int xfer_mode)
358 {
359         const struct ata_xfer_ent *ent;
360
361         for (ent = ata_xfer_tbl; ent->shift >= 0; ent++)
362                 if (xfer_mode >= ent->base && xfer_mode < ent->base + ent->bits)
363                         return ent->shift;
364         return -1;
365 }
366
367 /**
368  *      ata_mode_string - convert xfer_mask to string
369  *      @xfer_mask: mask of bits supported; only highest bit counts.
370  *
371  *      Determine string which represents the highest speed
372  *      (highest bit in @modemask).
373  *
374  *      LOCKING:
375  *      None.
376  *
377  *      RETURNS:
378  *      Constant C string representing highest speed listed in
379  *      @mode_mask, or the constant C string "<n/a>".
380  */
381 static const char *ata_mode_string(unsigned int xfer_mask)
382 {
383         static const char * const xfer_mode_str[] = {
384                 "PIO0",
385                 "PIO1",
386                 "PIO2",
387                 "PIO3",
388                 "PIO4",
389                 "PIO5",
390                 "PIO6",
391                 "MWDMA0",
392                 "MWDMA1",
393                 "MWDMA2",
394                 "MWDMA3",
395                 "MWDMA4",
396                 "UDMA/16",
397                 "UDMA/25",
398                 "UDMA/33",
399                 "UDMA/44",
400                 "UDMA/66",
401                 "UDMA/100",
402                 "UDMA/133",
403                 "UDMA7",
404         };
405         int highbit;
406
407         highbit = fls(xfer_mask) - 1;
408         if (highbit >= 0 && highbit < ARRAY_SIZE(xfer_mode_str))
409                 return xfer_mode_str[highbit];
410         return "<n/a>";
411 }
412
413 static const char *sata_spd_string(unsigned int spd)
414 {
415         static const char * const spd_str[] = {
416                 "1.5 Gbps",
417                 "3.0 Gbps",
418         };
419
420         if (spd == 0 || (spd - 1) >= ARRAY_SIZE(spd_str))
421                 return "<unknown>";
422         return spd_str[spd - 1];
423 }
424
425 void ata_dev_disable(struct ata_device *dev)
426 {
427         if (ata_dev_enabled(dev) && ata_msg_drv(dev->ap)) {
428                 ata_dev_printk(dev, KERN_WARNING, "disabled\n");
429                 dev->class++;
430         }
431 }
432
433 /**
434  *      ata_pio_devchk - PATA device presence detection
435  *      @ap: ATA channel to examine
436  *      @device: Device to examine (starting at zero)
437  *
438  *      This technique was originally described in
439  *      Hale Landis's ATADRVR (www.ata-atapi.com), and
440  *      later found its way into the ATA/ATAPI spec.
441  *
442  *      Write a pattern to the ATA shadow registers,
443  *      and if a device is present, it will respond by
444  *      correctly storing and echoing back the
445  *      ATA shadow register contents.
446  *
447  *      LOCKING:
448  *      caller.
449  */
450
451 static unsigned int ata_pio_devchk(struct ata_port *ap,
452                                    unsigned int device)
453 {
454         struct ata_ioports *ioaddr = &ap->ioaddr;
455         u8 nsect, lbal;
456
457         ap->ops->dev_select(ap, device);
458
459         outb(0x55, ioaddr->nsect_addr);
460         outb(0xaa, ioaddr->lbal_addr);
461
462         outb(0xaa, ioaddr->nsect_addr);
463         outb(0x55, ioaddr->lbal_addr);
464
465         outb(0x55, ioaddr->nsect_addr);
466         outb(0xaa, ioaddr->lbal_addr);
467
468         nsect = inb(ioaddr->nsect_addr);
469         lbal = inb(ioaddr->lbal_addr);
470
471         if ((nsect == 0x55) && (lbal == 0xaa))
472                 return 1;       /* we found a device */
473
474         return 0;               /* nothing found */
475 }
476
477 /**
478  *      ata_mmio_devchk - PATA device presence detection
479  *      @ap: ATA channel to examine
480  *      @device: Device to examine (starting at zero)
481  *
482  *      This technique was originally described in
483  *      Hale Landis's ATADRVR (www.ata-atapi.com), and
484  *      later found its way into the ATA/ATAPI spec.
485  *
486  *      Write a pattern to the ATA shadow registers,
487  *      and if a device is present, it will respond by
488  *      correctly storing and echoing back the
489  *      ATA shadow register contents.
490  *
491  *      LOCKING:
492  *      caller.
493  */
494
495 static unsigned int ata_mmio_devchk(struct ata_port *ap,
496                                     unsigned int device)
497 {
498         struct ata_ioports *ioaddr = &ap->ioaddr;
499         u8 nsect, lbal;
500
501         ap->ops->dev_select(ap, device);
502
503         writeb(0x55, (void __iomem *) ioaddr->nsect_addr);
504         writeb(0xaa, (void __iomem *) ioaddr->lbal_addr);
505
506         writeb(0xaa, (void __iomem *) ioaddr->nsect_addr);
507         writeb(0x55, (void __iomem *) ioaddr->lbal_addr);
508
509         writeb(0x55, (void __iomem *) ioaddr->nsect_addr);
510         writeb(0xaa, (void __iomem *) ioaddr->lbal_addr);
511
512         nsect = readb((void __iomem *) ioaddr->nsect_addr);
513         lbal = readb((void __iomem *) ioaddr->lbal_addr);
514
515         if ((nsect == 0x55) && (lbal == 0xaa))
516                 return 1;       /* we found a device */
517
518         return 0;               /* nothing found */
519 }
520
521 /**
522  *      ata_devchk - PATA device presence detection
523  *      @ap: ATA channel to examine
524  *      @device: Device to examine (starting at zero)
525  *
526  *      Dispatch ATA device presence detection, depending
527  *      on whether we are using PIO or MMIO to talk to the
528  *      ATA shadow registers.
529  *
530  *      LOCKING:
531  *      caller.
532  */
533
534 static unsigned int ata_devchk(struct ata_port *ap,
535                                     unsigned int device)
536 {
537         if (ap->flags & ATA_FLAG_MMIO)
538                 return ata_mmio_devchk(ap, device);
539         return ata_pio_devchk(ap, device);
540 }
541
542 /**
543  *      ata_dev_classify - determine device type based on ATA-spec signature
544  *      @tf: ATA taskfile register set for device to be identified
545  *
546  *      Determine from taskfile register contents whether a device is
547  *      ATA or ATAPI, as per "Signature and persistence" section
548  *      of ATA/PI spec (volume 1, sect 5.14).
549  *
550  *      LOCKING:
551  *      None.
552  *
553  *      RETURNS:
554  *      Device type, %ATA_DEV_ATA, %ATA_DEV_ATAPI, or %ATA_DEV_UNKNOWN
555  *      the event of failure.
556  */
557
558 unsigned int ata_dev_classify(const struct ata_taskfile *tf)
559 {
560         /* Apple's open source Darwin code hints that some devices only
561          * put a proper signature into the LBA mid/high registers,
562          * So, we only check those.  It's sufficient for uniqueness.
563          */
564
565         if (((tf->lbam == 0) && (tf->lbah == 0)) ||
566             ((tf->lbam == 0x3c) && (tf->lbah == 0xc3))) {
567                 DPRINTK("found ATA device by sig\n");
568                 return ATA_DEV_ATA;
569         }
570
571         if (((tf->lbam == 0x14) && (tf->lbah == 0xeb)) ||
572             ((tf->lbam == 0x69) && (tf->lbah == 0x96))) {
573                 DPRINTK("found ATAPI device by sig\n");
574                 return ATA_DEV_ATAPI;
575         }
576
577         DPRINTK("unknown device\n");
578         return ATA_DEV_UNKNOWN;
579 }
580
581 /**
582  *      ata_dev_try_classify - Parse returned ATA device signature
583  *      @ap: ATA channel to examine
584  *      @device: Device to examine (starting at zero)
585  *      @r_err: Value of error register on completion
586  *
587  *      After an event -- SRST, E.D.D., or SATA COMRESET -- occurs,
588  *      an ATA/ATAPI-defined set of values is placed in the ATA
589  *      shadow registers, indicating the results of device detection
590  *      and diagnostics.
591  *
592  *      Select the ATA device, and read the values from the ATA shadow
593  *      registers.  Then parse according to the Error register value,
594  *      and the spec-defined values examined by ata_dev_classify().
595  *
596  *      LOCKING:
597  *      caller.
598  *
599  *      RETURNS:
600  *      Device type - %ATA_DEV_ATA, %ATA_DEV_ATAPI or %ATA_DEV_NONE.
601  */
602
603 static unsigned int
604 ata_dev_try_classify(struct ata_port *ap, unsigned int device, u8 *r_err)
605 {
606         struct ata_taskfile tf;
607         unsigned int class;
608         u8 err;
609
610         ap->ops->dev_select(ap, device);
611
612         memset(&tf, 0, sizeof(tf));
613
614         ap->ops->tf_read(ap, &tf);
615         err = tf.feature;
616         if (r_err)
617                 *r_err = err;
618
619         /* see if device passed diags: if master then continue and warn later */
620         if (err == 0 && device == 0)
621                 /* diagnostic fail : do nothing _YET_ */
622                 ap->device[device].horkage |= ATA_HORKAGE_DIAGNOSTIC;
623         else if (err == 1)
624                 /* do nothing */ ;
625         else if ((device == 0) && (err == 0x81))
626                 /* do nothing */ ;
627         else
628                 return ATA_DEV_NONE;
629
630         /* determine if device is ATA or ATAPI */
631         class = ata_dev_classify(&tf);
632
633         if (class == ATA_DEV_UNKNOWN)
634                 return ATA_DEV_NONE;
635         if ((class == ATA_DEV_ATA) && (ata_chk_status(ap) == 0))
636                 return ATA_DEV_NONE;
637         return class;
638 }
639
640 /**
641  *      ata_id_string - Convert IDENTIFY DEVICE page into string
642  *      @id: IDENTIFY DEVICE results we will examine
643  *      @s: string into which data is output
644  *      @ofs: offset into identify device page
645  *      @len: length of string to return. must be an even number.
646  *
647  *      The strings in the IDENTIFY DEVICE page are broken up into
648  *      16-bit chunks.  Run through the string, and output each
649  *      8-bit chunk linearly, regardless of platform.
650  *
651  *      LOCKING:
652  *      caller.
653  */
654
655 void ata_id_string(const u16 *id, unsigned char *s,
656                    unsigned int ofs, unsigned int len)
657 {
658         unsigned int c;
659
660         while (len > 0) {
661                 c = id[ofs] >> 8;
662                 *s = c;
663                 s++;
664
665                 c = id[ofs] & 0xff;
666                 *s = c;
667                 s++;
668
669                 ofs++;
670                 len -= 2;
671         }
672 }
673
674 /**
675  *      ata_id_c_string - Convert IDENTIFY DEVICE page into C string
676  *      @id: IDENTIFY DEVICE results we will examine
677  *      @s: string into which data is output
678  *      @ofs: offset into identify device page
679  *      @len: length of string to return. must be an odd number.
680  *
681  *      This function is identical to ata_id_string except that it
682  *      trims trailing spaces and terminates the resulting string with
683  *      null.  @len must be actual maximum length (even number) + 1.
684  *
685  *      LOCKING:
686  *      caller.
687  */
688 void ata_id_c_string(const u16 *id, unsigned char *s,
689                      unsigned int ofs, unsigned int len)
690 {
691         unsigned char *p;
692
693         WARN_ON(!(len & 1));
694
695         ata_id_string(id, s, ofs, len - 1);
696
697         p = s + strnlen(s, len - 1);
698         while (p > s && p[-1] == ' ')
699                 p--;
700         *p = '\0';
701 }
702
703 static u64 ata_id_n_sectors(const u16 *id)
704 {
705         if (ata_id_has_lba(id)) {
706                 if (ata_id_has_lba48(id))
707                         return ata_id_u64(id, 100);
708                 else
709                         return ata_id_u32(id, 60);
710         } else {
711                 if (ata_id_current_chs_valid(id))
712                         return ata_id_u32(id, 57);
713                 else
714                         return id[1] * id[3] * id[6];
715         }
716 }
717
718 /**
719  *      ata_noop_dev_select - Select device 0/1 on ATA bus
720  *      @ap: ATA channel to manipulate
721  *      @device: ATA device (numbered from zero) to select
722  *
723  *      This function performs no actual function.
724  *
725  *      May be used as the dev_select() entry in ata_port_operations.
726  *
727  *      LOCKING:
728  *      caller.
729  */
730 void ata_noop_dev_select (struct ata_port *ap, unsigned int device)
731 {
732 }
733
734
735 /**
736  *      ata_std_dev_select - Select device 0/1 on ATA bus
737  *      @ap: ATA channel to manipulate
738  *      @device: ATA device (numbered from zero) to select
739  *
740  *      Use the method defined in the ATA specification to
741  *      make either device 0, or device 1, active on the
742  *      ATA channel.  Works with both PIO and MMIO.
743  *
744  *      May be used as the dev_select() entry in ata_port_operations.
745  *
746  *      LOCKING:
747  *      caller.
748  */
749
750 void ata_std_dev_select (struct ata_port *ap, unsigned int device)
751 {
752         u8 tmp;
753
754         if (device == 0)
755                 tmp = ATA_DEVICE_OBS;
756         else
757                 tmp = ATA_DEVICE_OBS | ATA_DEV1;
758
759         if (ap->flags & ATA_FLAG_MMIO) {
760                 writeb(tmp, (void __iomem *) ap->ioaddr.device_addr);
761         } else {
762                 outb(tmp, ap->ioaddr.device_addr);
763         }
764         ata_pause(ap);          /* needed; also flushes, for mmio */
765 }
766
767 /**
768  *      ata_dev_select - Select device 0/1 on ATA bus
769  *      @ap: ATA channel to manipulate
770  *      @device: ATA device (numbered from zero) to select
771  *      @wait: non-zero to wait for Status register BSY bit to clear
772  *      @can_sleep: non-zero if context allows sleeping
773  *
774  *      Use the method defined in the ATA specification to
775  *      make either device 0, or device 1, active on the
776  *      ATA channel.
777  *
778  *      This is a high-level version of ata_std_dev_select(),
779  *      which additionally provides the services of inserting
780  *      the proper pauses and status polling, where needed.
781  *
782  *      LOCKING:
783  *      caller.
784  */
785
786 void ata_dev_select(struct ata_port *ap, unsigned int device,
787                            unsigned int wait, unsigned int can_sleep)
788 {
789         if (ata_msg_probe(ap))
790                 ata_port_printk(ap, KERN_INFO, "ata_dev_select: ENTER, ata%u: "
791                                 "device %u, wait %u\n", ap->id, device, wait);
792
793         if (wait)
794                 ata_wait_idle(ap);
795
796         ap->ops->dev_select(ap, device);
797
798         if (wait) {
799                 if (can_sleep && ap->device[device].class == ATA_DEV_ATAPI)
800                         msleep(150);
801                 ata_wait_idle(ap);
802         }
803 }
804
805 /**
806  *      ata_dump_id - IDENTIFY DEVICE info debugging output
807  *      @id: IDENTIFY DEVICE page to dump
808  *
809  *      Dump selected 16-bit words from the given IDENTIFY DEVICE
810  *      page.
811  *
812  *      LOCKING:
813  *      caller.
814  */
815
816 static inline void ata_dump_id(const u16 *id)
817 {
818         DPRINTK("49==0x%04x  "
819                 "53==0x%04x  "
820                 "63==0x%04x  "
821                 "64==0x%04x  "
822                 "75==0x%04x  \n",
823                 id[49],
824                 id[53],
825                 id[63],
826                 id[64],
827                 id[75]);
828         DPRINTK("80==0x%04x  "
829                 "81==0x%04x  "
830                 "82==0x%04x  "
831                 "83==0x%04x  "
832                 "84==0x%04x  \n",
833                 id[80],
834                 id[81],
835                 id[82],
836                 id[83],
837                 id[84]);
838         DPRINTK("88==0x%04x  "
839                 "93==0x%04x\n",
840                 id[88],
841                 id[93]);
842 }
843
844 /**
845  *      ata_id_xfermask - Compute xfermask from the given IDENTIFY data
846  *      @id: IDENTIFY data to compute xfer mask from
847  *
848  *      Compute the xfermask for this device. This is not as trivial
849  *      as it seems if we must consider early devices correctly.
850  *
851  *      FIXME: pre IDE drive timing (do we care ?).
852  *
853  *      LOCKING:
854  *      None.
855  *
856  *      RETURNS:
857  *      Computed xfermask
858  */
859 static unsigned int ata_id_xfermask(const u16 *id)
860 {
861         unsigned int pio_mask, mwdma_mask, udma_mask;
862
863         /* Usual case. Word 53 indicates word 64 is valid */
864         if (id[ATA_ID_FIELD_VALID] & (1 << 1)) {
865                 pio_mask = id[ATA_ID_PIO_MODES] & 0x03;
866                 pio_mask <<= 3;
867                 pio_mask |= 0x7;
868         } else {
869                 /* If word 64 isn't valid then Word 51 high byte holds
870                  * the PIO timing number for the maximum. Turn it into
871                  * a mask.
872                  */
873                 pio_mask = (2 << (id[ATA_ID_OLD_PIO_MODES] & 0xFF)) - 1 ;
874
875                 /* But wait.. there's more. Design your standards by
876                  * committee and you too can get a free iordy field to
877                  * process. However its the speeds not the modes that
878                  * are supported... Note drivers using the timing API
879                  * will get this right anyway
880                  */
881         }
882
883         mwdma_mask = id[ATA_ID_MWDMA_MODES] & 0x07;
884
885         if (ata_id_is_cfa(id)) {
886                 /*
887                  *      Process compact flash extended modes
888                  */
889                 int pio = id[163] & 0x7;
890                 int dma = (id[163] >> 3) & 7;
891
892                 if (pio)
893                         pio_mask |= (1 << 5);
894                 if (pio > 1)
895                         pio_mask |= (1 << 6);
896                 if (dma)
897                         mwdma_mask |= (1 << 3);
898                 if (dma > 1)
899                         mwdma_mask |= (1 << 4);
900         }
901
902         udma_mask = 0;
903         if (id[ATA_ID_FIELD_VALID] & (1 << 2))
904                 udma_mask = id[ATA_ID_UDMA_MODES] & 0xff;
905
906         return ata_pack_xfermask(pio_mask, mwdma_mask, udma_mask);
907 }
908
909 /**
910  *      ata_port_queue_task - Queue port_task
911  *      @ap: The ata_port to queue port_task for
912  *      @fn: workqueue function to be scheduled
913  *      @data: data value to pass to workqueue function
914  *      @delay: delay time for workqueue function
915  *
916  *      Schedule @fn(@data) for execution after @delay jiffies using
917  *      port_task.  There is one port_task per port and it's the
918  *      user(low level driver)'s responsibility to make sure that only
919  *      one task is active at any given time.
920  *
921  *      libata core layer takes care of synchronization between
922  *      port_task and EH.  ata_port_queue_task() may be ignored for EH
923  *      synchronization.
924  *
925  *      LOCKING:
926  *      Inherited from caller.
927  */
928 void ata_port_queue_task(struct ata_port *ap, void (*fn)(void *), void *data,
929                          unsigned long delay)
930 {
931         int rc;
932
933         if (ap->pflags & ATA_PFLAG_FLUSH_PORT_TASK)
934                 return;
935
936         PREPARE_WORK(&ap->port_task, fn, data);
937
938         if (!delay)
939                 rc = queue_work(ata_wq, &ap->port_task);
940         else
941                 rc = queue_delayed_work(ata_wq, &ap->port_task, delay);
942
943         /* rc == 0 means that another user is using port task */
944         WARN_ON(rc == 0);
945 }
946
947 /**
948  *      ata_port_flush_task - Flush port_task
949  *      @ap: The ata_port to flush port_task for
950  *
951  *      After this function completes, port_task is guranteed not to
952  *      be running or scheduled.
953  *
954  *      LOCKING:
955  *      Kernel thread context (may sleep)
956  */
957 void ata_port_flush_task(struct ata_port *ap)
958 {
959         unsigned long flags;
960
961         DPRINTK("ENTER\n");
962
963         spin_lock_irqsave(ap->lock, flags);
964         ap->pflags |= ATA_PFLAG_FLUSH_PORT_TASK;
965         spin_unlock_irqrestore(ap->lock, flags);
966
967         DPRINTK("flush #1\n");
968         flush_workqueue(ata_wq);
969
970         /*
971          * At this point, if a task is running, it's guaranteed to see
972          * the FLUSH flag; thus, it will never queue pio tasks again.
973          * Cancel and flush.
974          */
975         if (!cancel_delayed_work(&ap->port_task)) {
976                 if (ata_msg_ctl(ap))
977                         ata_port_printk(ap, KERN_DEBUG, "%s: flush #2\n",
978                                         __FUNCTION__);
979                 flush_workqueue(ata_wq);
980         }
981
982         spin_lock_irqsave(ap->lock, flags);
983         ap->pflags &= ~ATA_PFLAG_FLUSH_PORT_TASK;
984         spin_unlock_irqrestore(ap->lock, flags);
985
986         if (ata_msg_ctl(ap))
987                 ata_port_printk(ap, KERN_DEBUG, "%s: EXIT\n", __FUNCTION__);
988 }
989
990 void ata_qc_complete_internal(struct ata_queued_cmd *qc)
991 {
992         struct completion *waiting = qc->private_data;
993
994         complete(waiting);
995 }
996
997 /**
998  *      ata_exec_internal - execute libata internal command
999  *      @dev: Device to which the command is sent
1000  *      @tf: Taskfile registers for the command and the result
1001  *      @cdb: CDB for packet command
1002  *      @dma_dir: Data tranfer direction of the command
1003  *      @buf: Data buffer of the command
1004  *      @buflen: Length of data buffer
1005  *
1006  *      Executes libata internal command with timeout.  @tf contains
1007  *      command on entry and result on return.  Timeout and error
1008  *      conditions are reported via return value.  No recovery action
1009  *      is taken after a command times out.  It's caller's duty to
1010  *      clean up after timeout.
1011  *
1012  *      LOCKING:
1013  *      None.  Should be called with kernel context, might sleep.
1014  *
1015  *      RETURNS:
1016  *      Zero on success, AC_ERR_* mask on failure
1017  */
1018 unsigned ata_exec_internal(struct ata_device *dev,
1019                            struct ata_taskfile *tf, const u8 *cdb,
1020                            int dma_dir, void *buf, unsigned int buflen)
1021 {
1022         struct ata_port *ap = dev->ap;
1023         u8 command = tf->command;
1024         struct ata_queued_cmd *qc;
1025         unsigned int tag, preempted_tag;
1026         u32 preempted_sactive, preempted_qc_active;
1027         DECLARE_COMPLETION_ONSTACK(wait);
1028         unsigned long flags;
1029         unsigned int err_mask;
1030         int rc;
1031
1032         spin_lock_irqsave(ap->lock, flags);
1033
1034         /* no internal command while frozen */
1035         if (ap->pflags & ATA_PFLAG_FROZEN) {
1036                 spin_unlock_irqrestore(ap->lock, flags);
1037                 return AC_ERR_SYSTEM;
1038         }
1039
1040         /* initialize internal qc */
1041
1042         /* XXX: Tag 0 is used for drivers with legacy EH as some
1043          * drivers choke if any other tag is given.  This breaks
1044          * ata_tag_internal() test for those drivers.  Don't use new
1045          * EH stuff without converting to it.
1046          */
1047         if (ap->ops->error_handler)
1048                 tag = ATA_TAG_INTERNAL;
1049         else
1050                 tag = 0;
1051
1052         if (test_and_set_bit(tag, &ap->qc_allocated))
1053                 BUG();
1054         qc = __ata_qc_from_tag(ap, tag);
1055
1056         qc->tag = tag;
1057         qc->scsicmd = NULL;
1058         qc->ap = ap;
1059         qc->dev = dev;
1060         ata_qc_reinit(qc);
1061
1062         preempted_tag = ap->active_tag;
1063         preempted_sactive = ap->sactive;
1064         preempted_qc_active = ap->qc_active;
1065         ap->active_tag = ATA_TAG_POISON;
1066         ap->sactive = 0;
1067         ap->qc_active = 0;
1068
1069         /* prepare & issue qc */
1070         qc->tf = *tf;
1071         if (cdb)
1072                 memcpy(qc->cdb, cdb, ATAPI_CDB_LEN);
1073         qc->flags |= ATA_QCFLAG_RESULT_TF;
1074         qc->dma_dir = dma_dir;
1075         if (dma_dir != DMA_NONE) {
1076                 ata_sg_init_one(qc, buf, buflen);
1077                 qc->nsect = buflen / ATA_SECT_SIZE;
1078         }
1079
1080         qc->private_data = &wait;
1081         qc->complete_fn = ata_qc_complete_internal;
1082
1083         ata_qc_issue(qc);
1084
1085         spin_unlock_irqrestore(ap->lock, flags);
1086
1087         rc = wait_for_completion_timeout(&wait, ata_probe_timeout);
1088
1089         ata_port_flush_task(ap);
1090
1091         if (!rc) {
1092                 spin_lock_irqsave(ap->lock, flags);
1093
1094                 /* We're racing with irq here.  If we lose, the
1095                  * following test prevents us from completing the qc
1096                  * twice.  If we win, the port is frozen and will be
1097                  * cleaned up by ->post_internal_cmd().
1098                  */
1099                 if (qc->flags & ATA_QCFLAG_ACTIVE) {
1100                         qc->err_mask |= AC_ERR_TIMEOUT;
1101
1102                         if (ap->ops->error_handler)
1103                                 ata_port_freeze(ap);
1104                         else
1105                                 ata_qc_complete(qc);
1106
1107                         if (ata_msg_warn(ap))
1108                                 ata_dev_printk(dev, KERN_WARNING,
1109                                         "qc timeout (cmd 0x%x)\n", command);
1110                 }
1111
1112                 spin_unlock_irqrestore(ap->lock, flags);
1113         }
1114
1115         /* do post_internal_cmd */
1116         if (ap->ops->post_internal_cmd)
1117                 ap->ops->post_internal_cmd(qc);
1118
1119         if (qc->flags & ATA_QCFLAG_FAILED && !qc->err_mask) {
1120                 if (ata_msg_warn(ap))
1121                         ata_dev_printk(dev, KERN_WARNING,
1122                                 "zero err_mask for failed "
1123                                 "internal command, assuming AC_ERR_OTHER\n");
1124                 qc->err_mask |= AC_ERR_OTHER;
1125         }
1126
1127         /* finish up */
1128         spin_lock_irqsave(ap->lock, flags);
1129
1130         *tf = qc->result_tf;
1131         err_mask = qc->err_mask;
1132
1133         ata_qc_free(qc);
1134         ap->active_tag = preempted_tag;
1135         ap->sactive = preempted_sactive;
1136         ap->qc_active = preempted_qc_active;
1137
1138         /* XXX - Some LLDDs (sata_mv) disable port on command failure.
1139          * Until those drivers are fixed, we detect the condition
1140          * here, fail the command with AC_ERR_SYSTEM and reenable the
1141          * port.
1142          *
1143          * Note that this doesn't change any behavior as internal
1144          * command failure results in disabling the device in the
1145          * higher layer for LLDDs without new reset/EH callbacks.
1146          *
1147          * Kill the following code as soon as those drivers are fixed.
1148          */
1149         if (ap->flags & ATA_FLAG_DISABLED) {
1150                 err_mask |= AC_ERR_SYSTEM;
1151                 ata_port_probe(ap);
1152         }
1153
1154         spin_unlock_irqrestore(ap->lock, flags);
1155
1156         return err_mask;
1157 }
1158
1159 /**
1160  *      ata_do_simple_cmd - execute simple internal command
1161  *      @dev: Device to which the command is sent
1162  *      @cmd: Opcode to execute
1163  *
1164  *      Execute a 'simple' command, that only consists of the opcode
1165  *      'cmd' itself, without filling any other registers
1166  *
1167  *      LOCKING:
1168  *      Kernel thread context (may sleep).
1169  *
1170  *      RETURNS:
1171  *      Zero on success, AC_ERR_* mask on failure
1172  */
1173 unsigned int ata_do_simple_cmd(struct ata_device *dev, u8 cmd)
1174 {
1175         struct ata_taskfile tf;
1176
1177         ata_tf_init(dev, &tf);
1178
1179         tf.command = cmd;
1180         tf.flags |= ATA_TFLAG_DEVICE;
1181         tf.protocol = ATA_PROT_NODATA;
1182
1183         return ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0);
1184 }
1185
1186 /**
1187  *      ata_pio_need_iordy      -       check if iordy needed
1188  *      @adev: ATA device
1189  *
1190  *      Check if the current speed of the device requires IORDY. Used
1191  *      by various controllers for chip configuration.
1192  */
1193
1194 unsigned int ata_pio_need_iordy(const struct ata_device *adev)
1195 {
1196         int pio;
1197         int speed = adev->pio_mode - XFER_PIO_0;
1198
1199         if (speed < 2)
1200                 return 0;
1201         if (speed > 2)
1202                 return 1;
1203
1204         /* If we have no drive specific rule, then PIO 2 is non IORDY */
1205
1206         if (adev->id[ATA_ID_FIELD_VALID] & 2) { /* EIDE */
1207                 pio = adev->id[ATA_ID_EIDE_PIO];
1208                 /* Is the speed faster than the drive allows non IORDY ? */
1209                 if (pio) {
1210                         /* This is cycle times not frequency - watch the logic! */
1211                         if (pio > 240)  /* PIO2 is 240nS per cycle */
1212                                 return 1;
1213                         return 0;
1214                 }
1215         }
1216         return 0;
1217 }
1218
1219 /**
1220  *      ata_dev_read_id - Read ID data from the specified device
1221  *      @dev: target device
1222  *      @p_class: pointer to class of the target device (may be changed)
1223  *      @post_reset: is this read ID post-reset?
1224  *      @id: buffer to read IDENTIFY data into
1225  *
1226  *      Read ID data from the specified device.  ATA_CMD_ID_ATA is
1227  *      performed on ATA devices and ATA_CMD_ID_ATAPI on ATAPI
1228  *      devices.  This function also issues ATA_CMD_INIT_DEV_PARAMS
1229  *      for pre-ATA4 drives.
1230  *
1231  *      LOCKING:
1232  *      Kernel thread context (may sleep)
1233  *
1234  *      RETURNS:
1235  *      0 on success, -errno otherwise.
1236  */
1237 int ata_dev_read_id(struct ata_device *dev, unsigned int *p_class,
1238                     int post_reset, u16 *id)
1239 {
1240         struct ata_port *ap = dev->ap;
1241         unsigned int class = *p_class;
1242         struct ata_taskfile tf;
1243         unsigned int err_mask = 0;
1244         const char *reason;
1245         int rc;
1246
1247         if (ata_msg_ctl(ap))
1248                 ata_dev_printk(dev, KERN_DEBUG, "%s: ENTER, host %u, dev %u\n",
1249                                __FUNCTION__, ap->id, dev->devno);
1250
1251         ata_dev_select(ap, dev->devno, 1, 1); /* select device 0/1 */
1252
1253  retry:
1254         ata_tf_init(dev, &tf);
1255
1256         switch (class) {
1257         case ATA_DEV_ATA:
1258                 tf.command = ATA_CMD_ID_ATA;
1259                 break;
1260         case ATA_DEV_ATAPI:
1261                 tf.command = ATA_CMD_ID_ATAPI;
1262                 break;
1263         default:
1264                 rc = -ENODEV;
1265                 reason = "unsupported class";
1266                 goto err_out;
1267         }
1268
1269         tf.protocol = ATA_PROT_PIO;
1270
1271         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_FROM_DEVICE,
1272                                      id, sizeof(id[0]) * ATA_ID_WORDS);
1273         if (err_mask) {
1274                 rc = -EIO;
1275                 reason = "I/O error";
1276                 goto err_out;
1277         }
1278
1279         swap_buf_le16(id, ATA_ID_WORDS);
1280
1281         /* sanity check */
1282         rc = -EINVAL;
1283         reason = "device reports illegal type";
1284
1285         if (class == ATA_DEV_ATA) {
1286                 if (!ata_id_is_ata(id) && !ata_id_is_cfa(id))
1287                         goto err_out;
1288         } else {
1289                 if (ata_id_is_ata(id))
1290                         goto err_out;
1291         }
1292
1293         if (post_reset && class == ATA_DEV_ATA) {
1294                 /*
1295                  * The exact sequence expected by certain pre-ATA4 drives is:
1296                  * SRST RESET
1297                  * IDENTIFY
1298                  * INITIALIZE DEVICE PARAMETERS
1299                  * anything else..
1300                  * Some drives were very specific about that exact sequence.
1301                  */
1302                 if (ata_id_major_version(id) < 4 || !ata_id_has_lba(id)) {
1303                         err_mask = ata_dev_init_params(dev, id[3], id[6]);
1304                         if (err_mask) {
1305                                 rc = -EIO;
1306                                 reason = "INIT_DEV_PARAMS failed";
1307                                 goto err_out;
1308                         }
1309
1310                         /* current CHS translation info (id[53-58]) might be
1311                          * changed. reread the identify device info.
1312                          */
1313                         post_reset = 0;
1314                         goto retry;
1315                 }
1316         }
1317
1318         *p_class = class;
1319
1320         return 0;
1321
1322  err_out:
1323         if (ata_msg_warn(ap))
1324                 ata_dev_printk(dev, KERN_WARNING, "failed to IDENTIFY "
1325                                "(%s, err_mask=0x%x)\n", reason, err_mask);
1326         return rc;
1327 }
1328
1329 static inline u8 ata_dev_knobble(struct ata_device *dev)
1330 {
1331         return ((dev->ap->cbl == ATA_CBL_SATA) && (!ata_id_is_sata(dev->id)));
1332 }
1333
1334 static void ata_dev_config_ncq(struct ata_device *dev,
1335                                char *desc, size_t desc_sz)
1336 {
1337         struct ata_port *ap = dev->ap;
1338         int hdepth = 0, ddepth = ata_id_queue_depth(dev->id);
1339
1340         if (!ata_id_has_ncq(dev->id)) {
1341                 desc[0] = '\0';
1342                 return;
1343         }
1344
1345         if (ap->flags & ATA_FLAG_NCQ) {
1346                 hdepth = min(ap->scsi_host->can_queue, ATA_MAX_QUEUE - 1);
1347                 dev->flags |= ATA_DFLAG_NCQ;
1348         }
1349
1350         if (hdepth >= ddepth)
1351                 snprintf(desc, desc_sz, "NCQ (depth %d)", ddepth);
1352         else
1353                 snprintf(desc, desc_sz, "NCQ (depth %d/%d)", hdepth, ddepth);
1354 }
1355
1356 static void ata_set_port_max_cmd_len(struct ata_port *ap)
1357 {
1358         int i;
1359
1360         if (ap->scsi_host) {
1361                 unsigned int len = 0;
1362
1363                 for (i = 0; i < ATA_MAX_DEVICES; i++)
1364                         len = max(len, ap->device[i].cdb_len);
1365
1366                 ap->scsi_host->max_cmd_len = len;
1367         }
1368 }
1369
1370 /**
1371  *      ata_dev_configure - Configure the specified ATA/ATAPI device
1372  *      @dev: Target device to configure
1373  *      @print_info: Enable device info printout
1374  *
1375  *      Configure @dev according to @dev->id.  Generic and low-level
1376  *      driver specific fixups are also applied.
1377  *
1378  *      LOCKING:
1379  *      Kernel thread context (may sleep)
1380  *
1381  *      RETURNS:
1382  *      0 on success, -errno otherwise
1383  */
1384 int ata_dev_configure(struct ata_device *dev, int print_info)
1385 {
1386         struct ata_port *ap = dev->ap;
1387         const u16 *id = dev->id;
1388         unsigned int xfer_mask;
1389         char revbuf[7];         /* XYZ-99\0 */
1390         int rc;
1391
1392         if (!ata_dev_enabled(dev) && ata_msg_info(ap)) {
1393                 ata_dev_printk(dev, KERN_INFO,
1394                                "%s: ENTER/EXIT (host %u, dev %u) -- nodev\n",
1395                                __FUNCTION__, ap->id, dev->devno);
1396                 return 0;
1397         }
1398
1399         if (ata_msg_probe(ap))
1400                 ata_dev_printk(dev, KERN_DEBUG, "%s: ENTER, host %u, dev %u\n",
1401                                __FUNCTION__, ap->id, dev->devno);
1402
1403         /* print device capabilities */
1404         if (ata_msg_probe(ap))
1405                 ata_dev_printk(dev, KERN_DEBUG,
1406                                "%s: cfg 49:%04x 82:%04x 83:%04x 84:%04x "
1407                                "85:%04x 86:%04x 87:%04x 88:%04x\n",
1408                                __FUNCTION__,
1409                                id[49], id[82], id[83], id[84],
1410                                id[85], id[86], id[87], id[88]);
1411
1412         /* initialize to-be-configured parameters */
1413         dev->flags &= ~ATA_DFLAG_CFG_MASK;
1414         dev->max_sectors = 0;
1415         dev->cdb_len = 0;
1416         dev->n_sectors = 0;
1417         dev->cylinders = 0;
1418         dev->heads = 0;
1419         dev->sectors = 0;
1420
1421         /*
1422          * common ATA, ATAPI feature tests
1423          */
1424
1425         /* find max transfer mode; for printk only */
1426         xfer_mask = ata_id_xfermask(id);
1427
1428         if (ata_msg_probe(ap))
1429                 ata_dump_id(id);
1430
1431         /* ATA-specific feature tests */
1432         if (dev->class == ATA_DEV_ATA) {
1433                 if (ata_id_is_cfa(id)) {
1434                         if (id[162] & 1) /* CPRM may make this media unusable */
1435                                 ata_dev_printk(dev, KERN_WARNING, "ata%u: device %u  supports DRM functions and may not be fully accessable.\n",
1436                                         ap->id, dev->devno);
1437                         snprintf(revbuf, 7, "CFA");
1438                 }
1439                 else
1440                         snprintf(revbuf, 7, "ATA-%d",  ata_id_major_version(id));
1441
1442                 dev->n_sectors = ata_id_n_sectors(id);
1443
1444                 if (ata_id_has_lba(id)) {
1445                         const char *lba_desc;
1446                         char ncq_desc[20];
1447
1448                         lba_desc = "LBA";
1449                         dev->flags |= ATA_DFLAG_LBA;
1450                         if (ata_id_has_lba48(id)) {
1451                                 dev->flags |= ATA_DFLAG_LBA48;
1452                                 lba_desc = "LBA48";
1453                         }
1454
1455                         /* config NCQ */
1456                         ata_dev_config_ncq(dev, ncq_desc, sizeof(ncq_desc));
1457
1458                         /* print device info to dmesg */
1459                         if (ata_msg_drv(ap) && print_info)
1460                                 ata_dev_printk(dev, KERN_INFO, "%s, "
1461                                         "max %s, %Lu sectors: %s %s\n",
1462                                         revbuf,
1463                                         ata_mode_string(xfer_mask),
1464                                         (unsigned long long)dev->n_sectors,
1465                                         lba_desc, ncq_desc);
1466                 } else {
1467                         /* CHS */
1468
1469                         /* Default translation */
1470                         dev->cylinders  = id[1];
1471                         dev->heads      = id[3];
1472                         dev->sectors    = id[6];
1473
1474                         if (ata_id_current_chs_valid(id)) {
1475                                 /* Current CHS translation is valid. */
1476                                 dev->cylinders = id[54];
1477                                 dev->heads     = id[55];
1478                                 dev->sectors   = id[56];
1479                         }
1480
1481                         /* print device info to dmesg */
1482                         if (ata_msg_drv(ap) && print_info)
1483                                 ata_dev_printk(dev, KERN_INFO, "%s, "
1484                                         "max %s, %Lu sectors: CHS %u/%u/%u\n",
1485                                         revbuf,
1486                                         ata_mode_string(xfer_mask),
1487                                         (unsigned long long)dev->n_sectors,
1488                                         dev->cylinders, dev->heads,
1489                                         dev->sectors);
1490                 }
1491
1492                 if (dev->id[59] & 0x100) {
1493                         dev->multi_count = dev->id[59] & 0xff;
1494                         if (ata_msg_drv(ap) && print_info)
1495                                 ata_dev_printk(dev, KERN_INFO,
1496                                         "ata%u: dev %u multi count %u\n",
1497                                         ap->id, dev->devno, dev->multi_count);
1498                 }
1499
1500                 dev->cdb_len = 16;
1501         }
1502
1503         /* ATAPI-specific feature tests */
1504         else if (dev->class == ATA_DEV_ATAPI) {
1505                 char *cdb_intr_string = "";
1506
1507                 rc = atapi_cdb_len(id);
1508                 if ((rc < 12) || (rc > ATAPI_CDB_LEN)) {
1509                         if (ata_msg_warn(ap))
1510                                 ata_dev_printk(dev, KERN_WARNING,
1511                                                "unsupported CDB len\n");
1512                         rc = -EINVAL;
1513                         goto err_out_nosup;
1514                 }
1515                 dev->cdb_len = (unsigned int) rc;
1516
1517                 if (ata_id_cdb_intr(dev->id)) {
1518                         dev->flags |= ATA_DFLAG_CDB_INTR;
1519                         cdb_intr_string = ", CDB intr";
1520                 }
1521
1522                 /* print device info to dmesg */
1523                 if (ata_msg_drv(ap) && print_info)
1524                         ata_dev_printk(dev, KERN_INFO, "ATAPI, max %s%s\n",
1525                                        ata_mode_string(xfer_mask),
1526                                        cdb_intr_string);
1527         }
1528
1529         if (dev->horkage & ATA_HORKAGE_DIAGNOSTIC) {
1530                 /* Let the user know. We don't want to disallow opens for
1531                    rescue purposes, or in case the vendor is just a blithering
1532                    idiot */
1533                 if (print_info) {
1534                         ata_dev_printk(dev, KERN_WARNING,
1535 "Drive reports diagnostics failure. This may indicate a drive\n");
1536                         ata_dev_printk(dev, KERN_WARNING,
1537 "fault or invalid emulation. Contact drive vendor for information.\n");
1538                 }
1539         }
1540
1541         ata_set_port_max_cmd_len(ap);
1542
1543         /* limit bridge transfers to udma5, 200 sectors */
1544         if (ata_dev_knobble(dev)) {
1545                 if (ata_msg_drv(ap) && print_info)
1546                         ata_dev_printk(dev, KERN_INFO,
1547                                        "applying bridge limits\n");
1548                 dev->udma_mask &= ATA_UDMA5;
1549                 dev->max_sectors = ATA_MAX_SECTORS;
1550         }
1551
1552         if (ap->ops->dev_config)
1553                 ap->ops->dev_config(ap, dev);
1554
1555         if (ata_msg_probe(ap))
1556                 ata_dev_printk(dev, KERN_DEBUG, "%s: EXIT, drv_stat = 0x%x\n",
1557                         __FUNCTION__, ata_chk_status(ap));
1558         return 0;
1559
1560 err_out_nosup:
1561         if (ata_msg_probe(ap))
1562                 ata_dev_printk(dev, KERN_DEBUG,
1563                                "%s: EXIT, err\n", __FUNCTION__);
1564         return rc;
1565 }
1566
1567 /**
1568  *      ata_bus_probe - Reset and probe ATA bus
1569  *      @ap: Bus to probe
1570  *
1571  *      Master ATA bus probing function.  Initiates a hardware-dependent
1572  *      bus reset, then attempts to identify any devices found on
1573  *      the bus.
1574  *
1575  *      LOCKING:
1576  *      PCI/etc. bus probe sem.
1577  *
1578  *      RETURNS:
1579  *      Zero on success, negative errno otherwise.
1580  */
1581
1582 int ata_bus_probe(struct ata_port *ap)
1583 {
1584         unsigned int classes[ATA_MAX_DEVICES];
1585         int tries[ATA_MAX_DEVICES];
1586         int i, rc, down_xfermask;
1587         struct ata_device *dev;
1588
1589         ata_port_probe(ap);
1590
1591         for (i = 0; i < ATA_MAX_DEVICES; i++)
1592                 tries[i] = ATA_PROBE_MAX_TRIES;
1593
1594  retry:
1595         down_xfermask = 0;
1596
1597         /* reset and determine device classes */
1598         ap->ops->phy_reset(ap);
1599
1600         for (i = 0; i < ATA_MAX_DEVICES; i++) {
1601                 dev = &ap->device[i];
1602
1603                 if (!(ap->flags & ATA_FLAG_DISABLED) &&
1604                     dev->class != ATA_DEV_UNKNOWN)
1605                         classes[dev->devno] = dev->class;
1606                 else
1607                         classes[dev->devno] = ATA_DEV_NONE;
1608
1609                 dev->class = ATA_DEV_UNKNOWN;
1610         }
1611
1612         ata_port_probe(ap);
1613
1614         /* after the reset the device state is PIO 0 and the controller
1615            state is undefined. Record the mode */
1616
1617         for (i = 0; i < ATA_MAX_DEVICES; i++)
1618                 ap->device[i].pio_mode = XFER_PIO_0;
1619
1620         /* read IDENTIFY page and configure devices */
1621         for (i = 0; i < ATA_MAX_DEVICES; i++) {
1622                 dev = &ap->device[i];
1623
1624                 if (tries[i])
1625                         dev->class = classes[i];
1626
1627                 if (!ata_dev_enabled(dev))
1628                         continue;
1629
1630                 rc = ata_dev_read_id(dev, &dev->class, 1, dev->id);
1631                 if (rc)
1632                         goto fail;
1633
1634                 rc = ata_dev_configure(dev, 1);
1635                 if (rc)
1636                         goto fail;
1637         }
1638
1639         /* configure transfer mode */
1640         rc = ata_set_mode(ap, &dev);
1641         if (rc) {
1642                 down_xfermask = 1;
1643                 goto fail;
1644         }
1645
1646         for (i = 0; i < ATA_MAX_DEVICES; i++)
1647                 if (ata_dev_enabled(&ap->device[i]))
1648                         return 0;
1649
1650         /* no device present, disable port */
1651         ata_port_disable(ap);
1652         ap->ops->port_disable(ap);
1653         return -ENODEV;
1654
1655  fail:
1656         switch (rc) {
1657         case -EINVAL:
1658         case -ENODEV:
1659                 tries[dev->devno] = 0;
1660                 break;
1661         case -EIO:
1662                 sata_down_spd_limit(ap);
1663                 /* fall through */
1664         default:
1665                 tries[dev->devno]--;
1666                 if (down_xfermask &&
1667                     ata_down_xfermask_limit(dev, tries[dev->devno] == 1))
1668                         tries[dev->devno] = 0;
1669         }
1670
1671         if (!tries[dev->devno]) {
1672                 ata_down_xfermask_limit(dev, 1);
1673                 ata_dev_disable(dev);
1674         }
1675
1676         goto retry;
1677 }
1678
1679 /**
1680  *      ata_port_probe - Mark port as enabled
1681  *      @ap: Port for which we indicate enablement
1682  *
1683  *      Modify @ap data structure such that the system
1684  *      thinks that the entire port is enabled.
1685  *
1686  *      LOCKING: host lock, or some other form of
1687  *      serialization.
1688  */
1689
1690 void ata_port_probe(struct ata_port *ap)
1691 {
1692         ap->flags &= ~ATA_FLAG_DISABLED;
1693 }
1694
1695 /**
1696  *      sata_print_link_status - Print SATA link status
1697  *      @ap: SATA port to printk link status about
1698  *
1699  *      This function prints link speed and status of a SATA link.
1700  *
1701  *      LOCKING:
1702  *      None.
1703  */
1704 static void sata_print_link_status(struct ata_port *ap)
1705 {
1706         u32 sstatus, scontrol, tmp;
1707
1708         if (sata_scr_read(ap, SCR_STATUS, &sstatus))
1709                 return;
1710         sata_scr_read(ap, SCR_CONTROL, &scontrol);
1711
1712         if (ata_port_online(ap)) {
1713                 tmp = (sstatus >> 4) & 0xf;
1714                 ata_port_printk(ap, KERN_INFO,
1715                                 "SATA link up %s (SStatus %X SControl %X)\n",
1716                                 sata_spd_string(tmp), sstatus, scontrol);
1717         } else {
1718                 ata_port_printk(ap, KERN_INFO,
1719                                 "SATA link down (SStatus %X SControl %X)\n",
1720                                 sstatus, scontrol);
1721         }
1722 }
1723
1724 /**
1725  *      __sata_phy_reset - Wake/reset a low-level SATA PHY
1726  *      @ap: SATA port associated with target SATA PHY.
1727  *
1728  *      This function issues commands to standard SATA Sxxx
1729  *      PHY registers, to wake up the phy (and device), and
1730  *      clear any reset condition.
1731  *
1732  *      LOCKING:
1733  *      PCI/etc. bus probe sem.
1734  *
1735  */
1736 void __sata_phy_reset(struct ata_port *ap)
1737 {
1738         u32 sstatus;
1739         unsigned long timeout = jiffies + (HZ * 5);
1740
1741         if (ap->flags & ATA_FLAG_SATA_RESET) {
1742                 /* issue phy wake/reset */
1743                 sata_scr_write_flush(ap, SCR_CONTROL, 0x301);
1744                 /* Couldn't find anything in SATA I/II specs, but
1745                  * AHCI-1.1 10.4.2 says at least 1 ms. */
1746                 mdelay(1);
1747         }
1748         /* phy wake/clear reset */
1749         sata_scr_write_flush(ap, SCR_CONTROL, 0x300);
1750
1751         /* wait for phy to become ready, if necessary */
1752         do {
1753                 msleep(200);
1754                 sata_scr_read(ap, SCR_STATUS, &sstatus);
1755                 if ((sstatus & 0xf) != 1)
1756                         break;
1757         } while (time_before(jiffies, timeout));
1758
1759         /* print link status */
1760         sata_print_link_status(ap);
1761
1762         /* TODO: phy layer with polling, timeouts, etc. */
1763         if (!ata_port_offline(ap))
1764                 ata_port_probe(ap);
1765         else
1766                 ata_port_disable(ap);
1767
1768         if (ap->flags & ATA_FLAG_DISABLED)
1769                 return;
1770
1771         if (ata_busy_sleep(ap, ATA_TMOUT_BOOT_QUICK, ATA_TMOUT_BOOT)) {
1772                 ata_port_disable(ap);
1773                 return;
1774         }
1775
1776         ap->cbl = ATA_CBL_SATA;
1777 }
1778
1779 /**
1780  *      sata_phy_reset - Reset SATA bus.
1781  *      @ap: SATA port associated with target SATA PHY.
1782  *
1783  *      This function resets the SATA bus, and then probes
1784  *      the bus for devices.
1785  *
1786  *      LOCKING:
1787  *      PCI/etc. bus probe sem.
1788  *
1789  */
1790 void sata_phy_reset(struct ata_port *ap)
1791 {
1792         __sata_phy_reset(ap);
1793         if (ap->flags & ATA_FLAG_DISABLED)
1794                 return;
1795         ata_bus_reset(ap);
1796 }
1797
1798 /**
1799  *      ata_dev_pair            -       return other device on cable
1800  *      @adev: device
1801  *
1802  *      Obtain the other device on the same cable, or if none is
1803  *      present NULL is returned
1804  */
1805
1806 struct ata_device *ata_dev_pair(struct ata_device *adev)
1807 {
1808         struct ata_port *ap = adev->ap;
1809         struct ata_device *pair = &ap->device[1 - adev->devno];
1810         if (!ata_dev_enabled(pair))
1811                 return NULL;
1812         return pair;
1813 }
1814
1815 /**
1816  *      ata_port_disable - Disable port.
1817  *      @ap: Port to be disabled.
1818  *
1819  *      Modify @ap data structure such that the system
1820  *      thinks that the entire port is disabled, and should
1821  *      never attempt to probe or communicate with devices
1822  *      on this port.
1823  *
1824  *      LOCKING: host lock, or some other form of
1825  *      serialization.
1826  */
1827
1828 void ata_port_disable(struct ata_port *ap)
1829 {
1830         ap->device[0].class = ATA_DEV_NONE;
1831         ap->device[1].class = ATA_DEV_NONE;
1832         ap->flags |= ATA_FLAG_DISABLED;
1833 }
1834
1835 /**
1836  *      sata_down_spd_limit - adjust SATA spd limit downward
1837  *      @ap: Port to adjust SATA spd limit for
1838  *
1839  *      Adjust SATA spd limit of @ap downward.  Note that this
1840  *      function only adjusts the limit.  The change must be applied
1841  *      using sata_set_spd().
1842  *
1843  *      LOCKING:
1844  *      Inherited from caller.
1845  *
1846  *      RETURNS:
1847  *      0 on success, negative errno on failure
1848  */
1849 int sata_down_spd_limit(struct ata_port *ap)
1850 {
1851         u32 sstatus, spd, mask;
1852         int rc, highbit;
1853
1854         rc = sata_scr_read(ap, SCR_STATUS, &sstatus);
1855         if (rc)
1856                 return rc;
1857
1858         mask = ap->sata_spd_limit;
1859         if (mask <= 1)
1860                 return -EINVAL;
1861         highbit = fls(mask) - 1;
1862         mask &= ~(1 << highbit);
1863
1864         spd = (sstatus >> 4) & 0xf;
1865         if (spd <= 1)
1866                 return -EINVAL;
1867         spd--;
1868         mask &= (1 << spd) - 1;
1869         if (!mask)
1870                 return -EINVAL;
1871
1872         ap->sata_spd_limit = mask;
1873
1874         ata_port_printk(ap, KERN_WARNING, "limiting SATA link speed to %s\n",
1875                         sata_spd_string(fls(mask)));
1876
1877         return 0;
1878 }
1879
1880 static int __sata_set_spd_needed(struct ata_port *ap, u32 *scontrol)
1881 {
1882         u32 spd, limit;
1883
1884         if (ap->sata_spd_limit == UINT_MAX)
1885                 limit = 0;
1886         else
1887                 limit = fls(ap->sata_spd_limit);
1888
1889         spd = (*scontrol >> 4) & 0xf;
1890         *scontrol = (*scontrol & ~0xf0) | ((limit & 0xf) << 4);
1891
1892         return spd != limit;
1893 }
1894
1895 /**
1896  *      sata_set_spd_needed - is SATA spd configuration needed
1897  *      @ap: Port in question
1898  *
1899  *      Test whether the spd limit in SControl matches
1900  *      @ap->sata_spd_limit.  This function is used to determine
1901  *      whether hardreset is necessary to apply SATA spd
1902  *      configuration.
1903  *
1904  *      LOCKING:
1905  *      Inherited from caller.
1906  *
1907  *      RETURNS:
1908  *      1 if SATA spd configuration is needed, 0 otherwise.
1909  */
1910 int sata_set_spd_needed(struct ata_port *ap)
1911 {
1912         u32 scontrol;
1913
1914         if (sata_scr_read(ap, SCR_CONTROL, &scontrol))
1915                 return 0;
1916
1917         return __sata_set_spd_needed(ap, &scontrol);
1918 }
1919
1920 /**
1921  *      sata_set_spd - set SATA spd according to spd limit
1922  *      @ap: Port to set SATA spd for
1923  *
1924  *      Set SATA spd of @ap according to sata_spd_limit.
1925  *
1926  *      LOCKING:
1927  *      Inherited from caller.
1928  *
1929  *      RETURNS:
1930  *      0 if spd doesn't need to be changed, 1 if spd has been
1931  *      changed.  Negative errno if SCR registers are inaccessible.
1932  */
1933 int sata_set_spd(struct ata_port *ap)
1934 {
1935         u32 scontrol;
1936         int rc;
1937
1938         if ((rc = sata_scr_read(ap, SCR_CONTROL, &scontrol)))
1939                 return rc;
1940
1941         if (!__sata_set_spd_needed(ap, &scontrol))
1942                 return 0;
1943
1944         if ((rc = sata_scr_write(ap, SCR_CONTROL, scontrol)))
1945                 return rc;
1946
1947         return 1;
1948 }
1949
1950 /*
1951  * This mode timing computation functionality is ported over from
1952  * drivers/ide/ide-timing.h and was originally written by Vojtech Pavlik
1953  */
1954 /*
1955  * PIO 0-4, MWDMA 0-2 and UDMA 0-6 timings (in nanoseconds).
1956  * These were taken from ATA/ATAPI-6 standard, rev 0a, except
1957  * for UDMA6, which is currently supported only by Maxtor drives.
1958  *
1959  * For PIO 5/6 MWDMA 3/4 see the CFA specification 3.0.
1960  */
1961
1962 static const struct ata_timing ata_timing[] = {
1963
1964         { XFER_UDMA_6,     0,   0,   0,   0,   0,   0,   0,  15 },
1965         { XFER_UDMA_5,     0,   0,   0,   0,   0,   0,   0,  20 },
1966         { XFER_UDMA_4,     0,   0,   0,   0,   0,   0,   0,  30 },
1967         { XFER_UDMA_3,     0,   0,   0,   0,   0,   0,   0,  45 },
1968
1969         { XFER_MW_DMA_4,  25,   0,   0,   0,  55,  20,  80,   0 },
1970         { XFER_MW_DMA_3,  25,   0,   0,   0,  65,  25, 100,   0 },
1971         { XFER_UDMA_2,     0,   0,   0,   0,   0,   0,   0,  60 },
1972         { XFER_UDMA_1,     0,   0,   0,   0,   0,   0,   0,  80 },
1973         { XFER_UDMA_0,     0,   0,   0,   0,   0,   0,   0, 120 },
1974
1975 /*      { XFER_UDMA_SLOW,  0,   0,   0,   0,   0,   0,   0, 150 }, */
1976
1977         { XFER_MW_DMA_2,  25,   0,   0,   0,  70,  25, 120,   0 },
1978         { XFER_MW_DMA_1,  45,   0,   0,   0,  80,  50, 150,   0 },
1979         { XFER_MW_DMA_0,  60,   0,   0,   0, 215, 215, 480,   0 },
1980
1981         { XFER_SW_DMA_2,  60,   0,   0,   0, 120, 120, 240,   0 },
1982         { XFER_SW_DMA_1,  90,   0,   0,   0, 240, 240, 480,   0 },
1983         { XFER_SW_DMA_0, 120,   0,   0,   0, 480, 480, 960,   0 },
1984
1985         { XFER_PIO_6,     10,  55,  20,  80,  55,  20,  80,   0 },
1986         { XFER_PIO_5,     15,  65,  25, 100,  65,  25, 100,   0 },
1987         { XFER_PIO_4,     25,  70,  25, 120,  70,  25, 120,   0 },
1988         { XFER_PIO_3,     30,  80,  70, 180,  80,  70, 180,   0 },
1989
1990         { XFER_PIO_2,     30, 290,  40, 330, 100,  90, 240,   0 },
1991         { XFER_PIO_1,     50, 290,  93, 383, 125, 100, 383,   0 },
1992         { XFER_PIO_0,     70, 290, 240, 600, 165, 150, 600,   0 },
1993
1994 /*      { XFER_PIO_SLOW, 120, 290, 240, 960, 290, 240, 960,   0 }, */
1995
1996         { 0xFF }
1997 };
1998
1999 #define ENOUGH(v,unit)          (((v)-1)/(unit)+1)
2000 #define EZ(v,unit)              ((v)?ENOUGH(v,unit):0)
2001
2002 static void ata_timing_quantize(const struct ata_timing *t, struct ata_timing *q, int T, int UT)
2003 {
2004         q->setup   = EZ(t->setup   * 1000,  T);
2005         q->act8b   = EZ(t->act8b   * 1000,  T);
2006         q->rec8b   = EZ(t->rec8b   * 1000,  T);
2007         q->cyc8b   = EZ(t->cyc8b   * 1000,  T);
2008         q->active  = EZ(t->active  * 1000,  T);
2009         q->recover = EZ(t->recover * 1000,  T);
2010         q->cycle   = EZ(t->cycle   * 1000,  T);
2011         q->udma    = EZ(t->udma    * 1000, UT);
2012 }
2013
2014 void ata_timing_merge(const struct ata_timing *a, const struct ata_timing *b,
2015                       struct ata_timing *m, unsigned int what)
2016 {
2017         if (what & ATA_TIMING_SETUP  ) m->setup   = max(a->setup,   b->setup);
2018         if (what & ATA_TIMING_ACT8B  ) m->act8b   = max(a->act8b,   b->act8b);
2019         if (what & ATA_TIMING_REC8B  ) m->rec8b   = max(a->rec8b,   b->rec8b);
2020         if (what & ATA_TIMING_CYC8B  ) m->cyc8b   = max(a->cyc8b,   b->cyc8b);
2021         if (what & ATA_TIMING_ACTIVE ) m->active  = max(a->active,  b->active);
2022         if (what & ATA_TIMING_RECOVER) m->recover = max(a->recover, b->recover);
2023         if (what & ATA_TIMING_CYCLE  ) m->cycle   = max(a->cycle,   b->cycle);
2024         if (what & ATA_TIMING_UDMA   ) m->udma    = max(a->udma,    b->udma);
2025 }
2026
2027 static const struct ata_timing* ata_timing_find_mode(unsigned short speed)
2028 {
2029         const struct ata_timing *t;
2030
2031         for (t = ata_timing; t->mode != speed; t++)
2032                 if (t->mode == 0xFF)
2033                         return NULL;
2034         return t;
2035 }
2036
2037 int ata_timing_compute(struct ata_device *adev, unsigned short speed,
2038                        struct ata_timing *t, int T, int UT)
2039 {
2040         const struct ata_timing *s;
2041         struct ata_timing p;
2042
2043         /*
2044          * Find the mode.
2045          */
2046
2047         if (!(s = ata_timing_find_mode(speed)))
2048                 return -EINVAL;
2049
2050         memcpy(t, s, sizeof(*s));
2051
2052         /*
2053          * If the drive is an EIDE drive, it can tell us it needs extended
2054          * PIO/MW_DMA cycle timing.
2055          */
2056
2057         if (adev->id[ATA_ID_FIELD_VALID] & 2) { /* EIDE drive */
2058                 memset(&p, 0, sizeof(p));
2059                 if(speed >= XFER_PIO_0 && speed <= XFER_SW_DMA_0) {
2060                         if (speed <= XFER_PIO_2) p.cycle = p.cyc8b = adev->id[ATA_ID_EIDE_PIO];
2061                                             else p.cycle = p.cyc8b = adev->id[ATA_ID_EIDE_PIO_IORDY];
2062                 } else if(speed >= XFER_MW_DMA_0 && speed <= XFER_MW_DMA_2) {
2063                         p.cycle = adev->id[ATA_ID_EIDE_DMA_MIN];
2064                 }
2065                 ata_timing_merge(&p, t, t, ATA_TIMING_CYCLE | ATA_TIMING_CYC8B);
2066         }
2067
2068         /*
2069          * Convert the timing to bus clock counts.
2070          */
2071
2072         ata_timing_quantize(t, t, T, UT);
2073
2074         /*
2075          * Even in DMA/UDMA modes we still use PIO access for IDENTIFY,
2076          * S.M.A.R.T * and some other commands. We have to ensure that the
2077          * DMA cycle timing is slower/equal than the fastest PIO timing.
2078          */
2079
2080         if (speed > XFER_PIO_4) {
2081                 ata_timing_compute(adev, adev->pio_mode, &p, T, UT);
2082                 ata_timing_merge(&p, t, t, ATA_TIMING_ALL);
2083         }
2084
2085         /*
2086          * Lengthen active & recovery time so that cycle time is correct.
2087          */
2088
2089         if (t->act8b + t->rec8b < t->cyc8b) {
2090                 t->act8b += (t->cyc8b - (t->act8b + t->rec8b)) / 2;
2091                 t->rec8b = t->cyc8b - t->act8b;
2092         }
2093
2094         if (t->active + t->recover < t->cycle) {
2095                 t->active += (t->cycle - (t->active + t->recover)) / 2;
2096                 t->recover = t->cycle - t->active;
2097         }
2098
2099         return 0;
2100 }
2101
2102 /**
2103  *      ata_down_xfermask_limit - adjust dev xfer masks downward
2104  *      @dev: Device to adjust xfer masks
2105  *      @force_pio0: Force PIO0
2106  *
2107  *      Adjust xfer masks of @dev downward.  Note that this function
2108  *      does not apply the change.  Invoking ata_set_mode() afterwards
2109  *      will apply the limit.
2110  *
2111  *      LOCKING:
2112  *      Inherited from caller.
2113  *
2114  *      RETURNS:
2115  *      0 on success, negative errno on failure
2116  */
2117 int ata_down_xfermask_limit(struct ata_device *dev, int force_pio0)
2118 {
2119         unsigned long xfer_mask;
2120         int highbit;
2121
2122         xfer_mask = ata_pack_xfermask(dev->pio_mask, dev->mwdma_mask,
2123                                       dev->udma_mask);
2124
2125         if (!xfer_mask)
2126                 goto fail;
2127         /* don't gear down to MWDMA from UDMA, go directly to PIO */
2128         if (xfer_mask & ATA_MASK_UDMA)
2129                 xfer_mask &= ~ATA_MASK_MWDMA;
2130
2131         highbit = fls(xfer_mask) - 1;
2132         xfer_mask &= ~(1 << highbit);
2133         if (force_pio0)
2134                 xfer_mask &= 1 << ATA_SHIFT_PIO;
2135         if (!xfer_mask)
2136                 goto fail;
2137
2138         ata_unpack_xfermask(xfer_mask, &dev->pio_mask, &dev->mwdma_mask,
2139                             &dev->udma_mask);
2140
2141         ata_dev_printk(dev, KERN_WARNING, "limiting speed to %s\n",
2142                        ata_mode_string(xfer_mask));
2143
2144         return 0;
2145
2146  fail:
2147         return -EINVAL;
2148 }
2149
2150 static int ata_dev_set_mode(struct ata_device *dev)
2151 {
2152         unsigned int err_mask;
2153         int rc;
2154
2155         dev->flags &= ~ATA_DFLAG_PIO;
2156         if (dev->xfer_shift == ATA_SHIFT_PIO)
2157                 dev->flags |= ATA_DFLAG_PIO;
2158
2159         err_mask = ata_dev_set_xfermode(dev);
2160         if (err_mask) {
2161                 ata_dev_printk(dev, KERN_ERR, "failed to set xfermode "
2162                                "(err_mask=0x%x)\n", err_mask);
2163                 return -EIO;
2164         }
2165
2166         rc = ata_dev_revalidate(dev, 0);
2167         if (rc)
2168                 return rc;
2169
2170         DPRINTK("xfer_shift=%u, xfer_mode=0x%x\n",
2171                 dev->xfer_shift, (int)dev->xfer_mode);
2172
2173         ata_dev_printk(dev, KERN_INFO, "configured for %s\n",
2174                        ata_mode_string(ata_xfer_mode2mask(dev->xfer_mode)));
2175         return 0;
2176 }
2177
2178 /**
2179  *      ata_set_mode - Program timings and issue SET FEATURES - XFER
2180  *      @ap: port on which timings will be programmed
2181  *      @r_failed_dev: out paramter for failed device
2182  *
2183  *      Set ATA device disk transfer mode (PIO3, UDMA6, etc.).  If
2184  *      ata_set_mode() fails, pointer to the failing device is
2185  *      returned in @r_failed_dev.
2186  *
2187  *      LOCKING:
2188  *      PCI/etc. bus probe sem.
2189  *
2190  *      RETURNS:
2191  *      0 on success, negative errno otherwise
2192  */
2193 int ata_set_mode(struct ata_port *ap, struct ata_device **r_failed_dev)
2194 {
2195         struct ata_device *dev;
2196         int i, rc = 0, used_dma = 0, found = 0;
2197
2198         /* has private set_mode? */
2199         if (ap->ops->set_mode) {
2200                 /* FIXME: make ->set_mode handle no device case and
2201                  * return error code and failing device on failure.
2202                  */
2203                 for (i = 0; i < ATA_MAX_DEVICES; i++) {
2204                         if (ata_dev_ready(&ap->device[i])) {
2205                                 ap->ops->set_mode(ap);
2206                                 break;
2207                         }
2208                 }
2209                 return 0;
2210         }
2211
2212         /* step 1: calculate xfer_mask */
2213         for (i = 0; i < ATA_MAX_DEVICES; i++) {
2214                 unsigned int pio_mask, dma_mask;
2215
2216                 dev = &ap->device[i];
2217
2218                 if (!ata_dev_enabled(dev))
2219                         continue;
2220
2221                 ata_dev_xfermask(dev);
2222
2223                 pio_mask = ata_pack_xfermask(dev->pio_mask, 0, 0);
2224                 dma_mask = ata_pack_xfermask(0, dev->mwdma_mask, dev->udma_mask);
2225                 dev->pio_mode = ata_xfer_mask2mode(pio_mask);
2226                 dev->dma_mode = ata_xfer_mask2mode(dma_mask);
2227
2228                 found = 1;
2229                 if (dev->dma_mode)
2230                         used_dma = 1;
2231         }
2232         if (!found)
2233                 goto out;
2234
2235         /* step 2: always set host PIO timings */
2236         for (i = 0; i < ATA_MAX_DEVICES; i++) {
2237                 dev = &ap->device[i];
2238                 if (!ata_dev_enabled(dev))
2239                         continue;
2240
2241                 if (!dev->pio_mode) {
2242                         ata_dev_printk(dev, KERN_WARNING, "no PIO support\n");
2243                         rc = -EINVAL;
2244                         goto out;
2245                 }
2246
2247                 dev->xfer_mode = dev->pio_mode;
2248                 dev->xfer_shift = ATA_SHIFT_PIO;
2249                 if (ap->ops->set_piomode)
2250                         ap->ops->set_piomode(ap, dev);
2251         }
2252
2253         /* step 3: set host DMA timings */
2254         for (i = 0; i < ATA_MAX_DEVICES; i++) {
2255                 dev = &ap->device[i];
2256
2257                 if (!ata_dev_enabled(dev) || !dev->dma_mode)
2258                         continue;
2259
2260                 dev->xfer_mode = dev->dma_mode;
2261                 dev->xfer_shift = ata_xfer_mode2shift(dev->dma_mode);
2262                 if (ap->ops->set_dmamode)
2263                         ap->ops->set_dmamode(ap, dev);
2264         }
2265
2266         /* step 4: update devices' xfer mode */
2267         for (i = 0; i < ATA_MAX_DEVICES; i++) {
2268                 dev = &ap->device[i];
2269
2270                 /* don't udpate suspended devices' xfer mode */
2271                 if (!ata_dev_ready(dev))
2272                         continue;
2273
2274                 rc = ata_dev_set_mode(dev);
2275                 if (rc)
2276                         goto out;
2277         }
2278
2279         /* Record simplex status. If we selected DMA then the other
2280          * host channels are not permitted to do so.
2281          */
2282         if (used_dma && (ap->host->flags & ATA_HOST_SIMPLEX))
2283                 ap->host->simplex_claimed = 1;
2284
2285         /* step5: chip specific finalisation */
2286         if (ap->ops->post_set_mode)
2287                 ap->ops->post_set_mode(ap);
2288
2289  out:
2290         if (rc)
2291                 *r_failed_dev = dev;
2292         return rc;
2293 }
2294
2295 /**
2296  *      ata_tf_to_host - issue ATA taskfile to host controller
2297  *      @ap: port to which command is being issued
2298  *      @tf: ATA taskfile register set
2299  *
2300  *      Issues ATA taskfile register set to ATA host controller,
2301  *      with proper synchronization with interrupt handler and
2302  *      other threads.
2303  *
2304  *      LOCKING:
2305  *      spin_lock_irqsave(host lock)
2306  */
2307
2308 static inline void ata_tf_to_host(struct ata_port *ap,
2309                                   const struct ata_taskfile *tf)
2310 {
2311         ap->ops->tf_load(ap, tf);
2312         ap->ops->exec_command(ap, tf);
2313 }
2314
2315 /**
2316  *      ata_busy_sleep - sleep until BSY clears, or timeout
2317  *      @ap: port containing status register to be polled
2318  *      @tmout_pat: impatience timeout
2319  *      @tmout: overall timeout
2320  *
2321  *      Sleep until ATA Status register bit BSY clears,
2322  *      or a timeout occurs.
2323  *
2324  *      LOCKING: None.
2325  */
2326
2327 unsigned int ata_busy_sleep (struct ata_port *ap,
2328                              unsigned long tmout_pat, unsigned long tmout)
2329 {
2330         unsigned long timer_start, timeout;
2331         u8 status;
2332
2333         status = ata_busy_wait(ap, ATA_BUSY, 300);
2334         timer_start = jiffies;
2335         timeout = timer_start + tmout_pat;
2336         while ((status & ATA_BUSY) && (time_before(jiffies, timeout))) {
2337                 msleep(50);
2338                 status = ata_busy_wait(ap, ATA_BUSY, 3);
2339         }
2340
2341         if (status & ATA_BUSY)
2342                 ata_port_printk(ap, KERN_WARNING,
2343                                 "port is slow to respond, please be patient "
2344                                 "(Status 0x%x)\n", status);
2345
2346         timeout = timer_start + tmout;
2347         while ((status & ATA_BUSY) && (time_before(jiffies, timeout))) {
2348                 msleep(50);
2349                 status = ata_chk_status(ap);
2350         }
2351
2352         if (status & ATA_BUSY) {
2353                 ata_port_printk(ap, KERN_ERR, "port failed to respond "
2354                                 "(%lu secs, Status 0x%x)\n",
2355                                 tmout / HZ, status);
2356                 return 1;
2357         }
2358
2359         return 0;
2360 }
2361
2362 static void ata_bus_post_reset(struct ata_port *ap, unsigned int devmask)
2363 {
2364         struct ata_ioports *ioaddr = &ap->ioaddr;
2365         unsigned int dev0 = devmask & (1 << 0);
2366         unsigned int dev1 = devmask & (1 << 1);
2367         unsigned long timeout;
2368
2369         /* if device 0 was found in ata_devchk, wait for its
2370          * BSY bit to clear
2371          */
2372         if (dev0)
2373                 ata_busy_sleep(ap, ATA_TMOUT_BOOT_QUICK, ATA_TMOUT_BOOT);
2374
2375         /* if device 1 was found in ata_devchk, wait for
2376          * register access, then wait for BSY to clear
2377          */
2378         timeout = jiffies + ATA_TMOUT_BOOT;
2379         while (dev1) {
2380                 u8 nsect, lbal;
2381
2382                 ap->ops->dev_select(ap, 1);
2383                 if (ap->flags & ATA_FLAG_MMIO) {
2384                         nsect = readb((void __iomem *) ioaddr->nsect_addr);
2385                         lbal = readb((void __iomem *) ioaddr->lbal_addr);
2386                 } else {
2387                         nsect = inb(ioaddr->nsect_addr);
2388                         lbal = inb(ioaddr->lbal_addr);
2389                 }
2390                 if ((nsect == 1) && (lbal == 1))
2391                         break;
2392                 if (time_after(jiffies, timeout)) {
2393                         dev1 = 0;
2394                         break;
2395                 }
2396                 msleep(50);     /* give drive a breather */
2397         }
2398         if (dev1)
2399                 ata_busy_sleep(ap, ATA_TMOUT_BOOT_QUICK, ATA_TMOUT_BOOT);
2400
2401         /* is all this really necessary? */
2402         ap->ops->dev_select(ap, 0);
2403         if (dev1)
2404                 ap->ops->dev_select(ap, 1);
2405         if (dev0)
2406                 ap->ops->dev_select(ap, 0);
2407 }
2408
2409 static unsigned int ata_bus_softreset(struct ata_port *ap,
2410                                       unsigned int devmask)
2411 {
2412         struct ata_ioports *ioaddr = &ap->ioaddr;
2413
2414         DPRINTK("ata%u: bus reset via SRST\n", ap->id);
2415
2416         /* software reset.  causes dev0 to be selected */
2417         if (ap->flags & ATA_FLAG_MMIO) {
2418                 writeb(ap->ctl, (void __iomem *) ioaddr->ctl_addr);
2419                 udelay(20);     /* FIXME: flush */
2420                 writeb(ap->ctl | ATA_SRST, (void __iomem *) ioaddr->ctl_addr);
2421                 udelay(20);     /* FIXME: flush */
2422                 writeb(ap->ctl, (void __iomem *) ioaddr->ctl_addr);
2423         } else {
2424                 outb(ap->ctl, ioaddr->ctl_addr);
2425                 udelay(10);
2426                 outb(ap->ctl | ATA_SRST, ioaddr->ctl_addr);
2427                 udelay(10);
2428                 outb(ap->ctl, ioaddr->ctl_addr);
2429         }
2430
2431         /* spec mandates ">= 2ms" before checking status.
2432          * We wait 150ms, because that was the magic delay used for
2433          * ATAPI devices in Hale Landis's ATADRVR, for the period of time
2434          * between when the ATA command register is written, and then
2435          * status is checked.  Because waiting for "a while" before
2436          * checking status is fine, post SRST, we perform this magic
2437          * delay here as well.
2438          *
2439          * Old drivers/ide uses the 2mS rule and then waits for ready
2440          */
2441         msleep(150);
2442
2443         /* Before we perform post reset processing we want to see if
2444          * the bus shows 0xFF because the odd clown forgets the D7
2445          * pulldown resistor.
2446          */
2447         if (ata_check_status(ap) == 0xFF) {
2448                 ata_port_printk(ap, KERN_ERR, "SRST failed (status 0xFF)\n");
2449                 return AC_ERR_OTHER;
2450         }
2451
2452         ata_bus_post_reset(ap, devmask);
2453
2454         return 0;
2455 }
2456
2457 /**
2458  *      ata_bus_reset - reset host port and associated ATA channel
2459  *      @ap: port to reset
2460  *
2461  *      This is typically the first time we actually start issuing
2462  *      commands to the ATA channel.  We wait for BSY to clear, then
2463  *      issue EXECUTE DEVICE DIAGNOSTIC command, polling for its
2464  *      result.  Determine what devices, if any, are on the channel
2465  *      by looking at the device 0/1 error register.  Look at the signature
2466  *      stored in each device's taskfile registers, to determine if
2467  *      the device is ATA or ATAPI.
2468  *
2469  *      LOCKING:
2470  *      PCI/etc. bus probe sem.
2471  *      Obtains host lock.
2472  *
2473  *      SIDE EFFECTS:
2474  *      Sets ATA_FLAG_DISABLED if bus reset fails.
2475  */
2476
2477 void ata_bus_reset(struct ata_port *ap)
2478 {
2479         struct ata_ioports *ioaddr = &ap->ioaddr;
2480         unsigned int slave_possible = ap->flags & ATA_FLAG_SLAVE_POSS;
2481         u8 err;
2482         unsigned int dev0, dev1 = 0, devmask = 0;
2483
2484         DPRINTK("ENTER, host %u, port %u\n", ap->id, ap->port_no);
2485
2486         /* determine if device 0/1 are present */
2487         if (ap->flags & ATA_FLAG_SATA_RESET)
2488                 dev0 = 1;
2489         else {
2490                 dev0 = ata_devchk(ap, 0);
2491                 if (slave_possible)
2492                         dev1 = ata_devchk(ap, 1);
2493         }
2494
2495         if (dev0)
2496                 devmask |= (1 << 0);
2497         if (dev1)
2498                 devmask |= (1 << 1);
2499
2500         /* select device 0 again */
2501         ap->ops->dev_select(ap, 0);
2502
2503         /* issue bus reset */
2504         if (ap->flags & ATA_FLAG_SRST)
2505                 if (ata_bus_softreset(ap, devmask))
2506                         goto err_out;
2507
2508         /*
2509          * determine by signature whether we have ATA or ATAPI devices
2510          */
2511         ap->device[0].class = ata_dev_try_classify(ap, 0, &err);
2512         if ((slave_possible) && (err != 0x81))
2513                 ap->device[1].class = ata_dev_try_classify(ap, 1, &err);
2514
2515         /* re-enable interrupts */
2516         if (ap->ioaddr.ctl_addr)        /* FIXME: hack. create a hook instead */
2517                 ata_irq_on(ap);
2518
2519         /* is double-select really necessary? */
2520         if (ap->device[1].class != ATA_DEV_NONE)
2521                 ap->ops->dev_select(ap, 1);
2522         if (ap->device[0].class != ATA_DEV_NONE)
2523                 ap->ops->dev_select(ap, 0);
2524
2525         /* if no devices were detected, disable this port */
2526         if ((ap->device[0].class == ATA_DEV_NONE) &&
2527             (ap->device[1].class == ATA_DEV_NONE))
2528                 goto err_out;
2529
2530         if (ap->flags & (ATA_FLAG_SATA_RESET | ATA_FLAG_SRST)) {
2531                 /* set up device control for ATA_FLAG_SATA_RESET */
2532                 if (ap->flags & ATA_FLAG_MMIO)
2533                         writeb(ap->ctl, (void __iomem *) ioaddr->ctl_addr);
2534                 else
2535                         outb(ap->ctl, ioaddr->ctl_addr);
2536         }
2537
2538         DPRINTK("EXIT\n");
2539         return;
2540
2541 err_out:
2542         ata_port_printk(ap, KERN_ERR, "disabling port\n");
2543         ap->ops->port_disable(ap);
2544
2545         DPRINTK("EXIT\n");
2546 }
2547
2548 /**
2549  *      sata_phy_debounce - debounce SATA phy status
2550  *      @ap: ATA port to debounce SATA phy status for
2551  *      @params: timing parameters { interval, duratinon, timeout } in msec
2552  *
2553  *      Make sure SStatus of @ap reaches stable state, determined by
2554  *      holding the same value where DET is not 1 for @duration polled
2555  *      every @interval, before @timeout.  Timeout constraints the
2556  *      beginning of the stable state.  Because, after hot unplugging,
2557  *      DET gets stuck at 1 on some controllers, this functions waits
2558  *      until timeout then returns 0 if DET is stable at 1.
2559  *
2560  *      LOCKING:
2561  *      Kernel thread context (may sleep)
2562  *
2563  *      RETURNS:
2564  *      0 on success, -errno on failure.
2565  */
2566 int sata_phy_debounce(struct ata_port *ap, const unsigned long *params)
2567 {
2568         unsigned long interval_msec = params[0];
2569         unsigned long duration = params[1] * HZ / 1000;
2570         unsigned long timeout = jiffies + params[2] * HZ / 1000;
2571         unsigned long last_jiffies;
2572         u32 last, cur;
2573         int rc;
2574
2575         if ((rc = sata_scr_read(ap, SCR_STATUS, &cur)))
2576                 return rc;
2577         cur &= 0xf;
2578
2579         last = cur;
2580         last_jiffies = jiffies;
2581
2582         while (1) {
2583                 msleep(interval_msec);
2584                 if ((rc = sata_scr_read(ap, SCR_STATUS, &cur)))
2585                         return rc;
2586                 cur &= 0xf;
2587
2588                 /* DET stable? */
2589                 if (cur == last) {
2590                         if (cur == 1 && time_before(jiffies, timeout))
2591                                 continue;
2592                         if (time_after(jiffies, last_jiffies + duration))
2593                                 return 0;
2594                         continue;
2595                 }
2596
2597                 /* unstable, start over */
2598                 last = cur;
2599                 last_jiffies = jiffies;
2600
2601                 /* check timeout */
2602                 if (time_after(jiffies, timeout))
2603                         return -EBUSY;
2604         }
2605 }
2606
2607 /**
2608  *      sata_phy_resume - resume SATA phy
2609  *      @ap: ATA port to resume SATA phy for
2610  *      @params: timing parameters { interval, duratinon, timeout } in msec
2611  *
2612  *      Resume SATA phy of @ap and debounce it.
2613  *
2614  *      LOCKING:
2615  *      Kernel thread context (may sleep)
2616  *
2617  *      RETURNS:
2618  *      0 on success, -errno on failure.
2619  */
2620 int sata_phy_resume(struct ata_port *ap, const unsigned long *params)
2621 {
2622         u32 scontrol;
2623         int rc;
2624
2625         if ((rc = sata_scr_read(ap, SCR_CONTROL, &scontrol)))
2626                 return rc;
2627
2628         scontrol = (scontrol & 0x0f0) | 0x300;
2629
2630         if ((rc = sata_scr_write(ap, SCR_CONTROL, scontrol)))
2631                 return rc;
2632
2633         /* Some PHYs react badly if SStatus is pounded immediately
2634          * after resuming.  Delay 200ms before debouncing.
2635          */
2636         msleep(200);
2637
2638         return sata_phy_debounce(ap, params);
2639 }
2640
2641 static void ata_wait_spinup(struct ata_port *ap)
2642 {
2643         struct ata_eh_context *ehc = &ap->eh_context;
2644         unsigned long end, secs;
2645         int rc;
2646
2647         /* first, debounce phy if SATA */
2648         if (ap->cbl == ATA_CBL_SATA) {
2649                 rc = sata_phy_debounce(ap, sata_deb_timing_hotplug);
2650
2651                 /* if debounced successfully and offline, no need to wait */
2652                 if ((rc == 0 || rc == -EOPNOTSUPP) && ata_port_offline(ap))
2653                         return;
2654         }
2655
2656         /* okay, let's give the drive time to spin up */
2657         end = ehc->i.hotplug_timestamp + ATA_SPINUP_WAIT * HZ / 1000;
2658         secs = ((end - jiffies) + HZ - 1) / HZ;
2659
2660         if (time_after(jiffies, end))
2661                 return;
2662
2663         if (secs > 5)
2664                 ata_port_printk(ap, KERN_INFO, "waiting for device to spin up "
2665                                 "(%lu secs)\n", secs);
2666
2667         schedule_timeout_uninterruptible(end - jiffies);
2668 }
2669
2670 /**
2671  *      ata_std_prereset - prepare for reset
2672  *      @ap: ATA port to be reset
2673  *
2674  *      @ap is about to be reset.  Initialize it.
2675  *
2676  *      LOCKING:
2677  *      Kernel thread context (may sleep)
2678  *
2679  *      RETURNS:
2680  *      0 on success, -errno otherwise.
2681  */
2682 int ata_std_prereset(struct ata_port *ap)
2683 {
2684         struct ata_eh_context *ehc = &ap->eh_context;
2685         const unsigned long *timing = sata_ehc_deb_timing(ehc);
2686         int rc;
2687
2688         /* handle link resume & hotplug spinup */
2689         if ((ehc->i.flags & ATA_EHI_RESUME_LINK) &&
2690             (ap->flags & ATA_FLAG_HRST_TO_RESUME))
2691                 ehc->i.action |= ATA_EH_HARDRESET;
2692
2693         if ((ehc->i.flags & ATA_EHI_HOTPLUGGED) &&
2694             (ap->flags & ATA_FLAG_SKIP_D2H_BSY))
2695                 ata_wait_spinup(ap);
2696
2697         /* if we're about to do hardreset, nothing more to do */
2698         if (ehc->i.action & ATA_EH_HARDRESET)
2699                 return 0;
2700
2701         /* if SATA, resume phy */
2702         if (ap->cbl == ATA_CBL_SATA) {
2703                 rc = sata_phy_resume(ap, timing);
2704                 if (rc && rc != -EOPNOTSUPP) {
2705                         /* phy resume failed */
2706                         ata_port_printk(ap, KERN_WARNING, "failed to resume "
2707                                         "link for reset (errno=%d)\n", rc);
2708                         return rc;
2709                 }
2710         }
2711
2712         /* Wait for !BSY if the controller can wait for the first D2H
2713          * Reg FIS and we don't know that no device is attached.
2714          */
2715         if (!(ap->flags & ATA_FLAG_SKIP_D2H_BSY) && !ata_port_offline(ap))
2716                 ata_busy_sleep(ap, ATA_TMOUT_BOOT_QUICK, ATA_TMOUT_BOOT);
2717
2718         return 0;
2719 }
2720
2721 /**
2722  *      ata_std_softreset - reset host port via ATA SRST
2723  *      @ap: port to reset
2724  *      @classes: resulting classes of attached devices
2725  *
2726  *      Reset host port using ATA SRST.
2727  *
2728  *      LOCKING:
2729  *      Kernel thread context (may sleep)
2730  *
2731  *      RETURNS:
2732  *      0 on success, -errno otherwise.
2733  */
2734 int ata_std_softreset(struct ata_port *ap, unsigned int *classes)
2735 {
2736         unsigned int slave_possible = ap->flags & ATA_FLAG_SLAVE_POSS;
2737         unsigned int devmask = 0, err_mask;
2738         u8 err;
2739
2740         DPRINTK("ENTER\n");
2741
2742         if (ata_port_offline(ap)) {
2743                 classes[0] = ATA_DEV_NONE;
2744                 goto out;
2745         }
2746
2747         /* determine if device 0/1 are present */
2748         if (ata_devchk(ap, 0))
2749                 devmask |= (1 << 0);
2750         if (slave_possible && ata_devchk(ap, 1))
2751                 devmask |= (1 << 1);
2752
2753         /* select device 0 again */
2754         ap->ops->dev_select(ap, 0);
2755
2756         /* issue bus reset */
2757         DPRINTK("about to softreset, devmask=%x\n", devmask);
2758         err_mask = ata_bus_softreset(ap, devmask);
2759         if (err_mask) {
2760                 ata_port_printk(ap, KERN_ERR, "SRST failed (err_mask=0x%x)\n",
2761                                 err_mask);
2762                 return -EIO;
2763         }
2764
2765         /* determine by signature whether we have ATA or ATAPI devices */
2766         classes[0] = ata_dev_try_classify(ap, 0, &err);
2767         if (slave_possible && err != 0x81)
2768                 classes[1] = ata_dev_try_classify(ap, 1, &err);
2769
2770  out:
2771         DPRINTK("EXIT, classes[0]=%u [1]=%u\n", classes[0], classes[1]);
2772         return 0;
2773 }
2774
2775 /**
2776  *      sata_std_hardreset - reset host port via SATA phy reset
2777  *      @ap: port to reset
2778  *      @class: resulting class of attached device
2779  *
2780  *      SATA phy-reset host port using DET bits of SControl register.
2781  *
2782  *      LOCKING:
2783  *      Kernel thread context (may sleep)
2784  *
2785  *      RETURNS:
2786  *      0 on success, -errno otherwise.
2787  */
2788 int sata_std_hardreset(struct ata_port *ap, unsigned int *class)
2789 {
2790         struct ata_eh_context *ehc = &ap->eh_context;
2791         const unsigned long *timing = sata_ehc_deb_timing(ehc);
2792         u32 scontrol;
2793         int rc;
2794
2795         DPRINTK("ENTER\n");
2796
2797         if (sata_set_spd_needed(ap)) {
2798                 /* SATA spec says nothing about how to reconfigure
2799                  * spd.  To be on the safe side, turn off phy during
2800                  * reconfiguration.  This works for at least ICH7 AHCI
2801                  * and Sil3124.
2802                  */
2803                 if ((rc = sata_scr_read(ap, SCR_CONTROL, &scontrol)))
2804                         return rc;
2805
2806                 scontrol = (scontrol & 0x0f0) | 0x304;
2807
2808                 if ((rc = sata_scr_write(ap, SCR_CONTROL, scontrol)))
2809                         return rc;
2810
2811                 sata_set_spd(ap);
2812         }
2813
2814         /* issue phy wake/reset */
2815         if ((rc = sata_scr_read(ap, SCR_CONTROL, &scontrol)))
2816                 return rc;
2817
2818         scontrol = (scontrol & 0x0f0) | 0x301;
2819
2820         if ((rc = sata_scr_write_flush(ap, SCR_CONTROL, scontrol)))
2821                 return rc;
2822
2823         /* Couldn't find anything in SATA I/II specs, but AHCI-1.1
2824          * 10.4.2 says at least 1 ms.
2825          */
2826         msleep(1);
2827
2828         /* bring phy back */
2829         sata_phy_resume(ap, timing);
2830
2831         /* TODO: phy layer with polling, timeouts, etc. */
2832         if (ata_port_offline(ap)) {
2833                 *class = ATA_DEV_NONE;
2834                 DPRINTK("EXIT, link offline\n");
2835                 return 0;
2836         }
2837
2838         if (ata_busy_sleep(ap, ATA_TMOUT_BOOT_QUICK, ATA_TMOUT_BOOT)) {
2839                 ata_port_printk(ap, KERN_ERR,
2840                                 "COMRESET failed (device not ready)\n");
2841                 return -EIO;
2842         }
2843
2844         ap->ops->dev_select(ap, 0);     /* probably unnecessary */
2845
2846         *class = ata_dev_try_classify(ap, 0, NULL);
2847
2848         DPRINTK("EXIT, class=%u\n", *class);
2849         return 0;
2850 }
2851
2852 /**
2853  *      ata_std_postreset - standard postreset callback
2854  *      @ap: the target ata_port
2855  *      @classes: classes of attached devices
2856  *
2857  *      This function is invoked after a successful reset.  Note that
2858  *      the device might have been reset more than once using
2859  *      different reset methods before postreset is invoked.
2860  *
2861  *      LOCKING:
2862  *      Kernel thread context (may sleep)
2863  */
2864 void ata_std_postreset(struct ata_port *ap, unsigned int *classes)
2865 {
2866         u32 serror;
2867
2868         DPRINTK("ENTER\n");
2869
2870         /* print link status */
2871         sata_print_link_status(ap);
2872
2873         /* clear SError */
2874         if (sata_scr_read(ap, SCR_ERROR, &serror) == 0)
2875                 sata_scr_write(ap, SCR_ERROR, serror);
2876
2877         /* re-enable interrupts */
2878         if (!ap->ops->error_handler) {
2879                 /* FIXME: hack. create a hook instead */
2880                 if (ap->ioaddr.ctl_addr)
2881                         ata_irq_on(ap);
2882         }
2883
2884         /* is double-select really necessary? */
2885         if (classes[0] != ATA_DEV_NONE)
2886                 ap->ops->dev_select(ap, 1);
2887         if (classes[1] != ATA_DEV_NONE)
2888                 ap->ops->dev_select(ap, 0);
2889
2890         /* bail out if no device is present */
2891         if (classes[0] == ATA_DEV_NONE && classes[1] == ATA_DEV_NONE) {
2892                 DPRINTK("EXIT, no device\n");
2893                 return;
2894         }
2895
2896         /* set up device control */
2897         if (ap->ioaddr.ctl_addr) {
2898                 if (ap->flags & ATA_FLAG_MMIO)
2899                         writeb(ap->ctl, (void __iomem *) ap->ioaddr.ctl_addr);
2900                 else
2901                         outb(ap->ctl, ap->ioaddr.ctl_addr);
2902         }
2903
2904         DPRINTK("EXIT\n");
2905 }
2906
2907 /**
2908  *      ata_dev_same_device - Determine whether new ID matches configured device
2909  *      @dev: device to compare against
2910  *      @new_class: class of the new device
2911  *      @new_id: IDENTIFY page of the new device
2912  *
2913  *      Compare @new_class and @new_id against @dev and determine
2914  *      whether @dev is the device indicated by @new_class and
2915  *      @new_id.
2916  *
2917  *      LOCKING:
2918  *      None.
2919  *
2920  *      RETURNS:
2921  *      1 if @dev matches @new_class and @new_id, 0 otherwise.
2922  */
2923 static int ata_dev_same_device(struct ata_device *dev, unsigned int new_class,
2924                                const u16 *new_id)
2925 {
2926         const u16 *old_id = dev->id;
2927         unsigned char model[2][41], serial[2][21];
2928         u64 new_n_sectors;
2929
2930         if (dev->class != new_class) {
2931                 ata_dev_printk(dev, KERN_INFO, "class mismatch %d != %d\n",
2932                                dev->class, new_class);
2933                 return 0;
2934         }
2935
2936         ata_id_c_string(old_id, model[0], ATA_ID_PROD_OFS, sizeof(model[0]));
2937         ata_id_c_string(new_id, model[1], ATA_ID_PROD_OFS, sizeof(model[1]));
2938         ata_id_c_string(old_id, serial[0], ATA_ID_SERNO_OFS, sizeof(serial[0]));
2939         ata_id_c_string(new_id, serial[1], ATA_ID_SERNO_OFS, sizeof(serial[1]));
2940         new_n_sectors = ata_id_n_sectors(new_id);
2941
2942         if (strcmp(model[0], model[1])) {
2943                 ata_dev_printk(dev, KERN_INFO, "model number mismatch "
2944                                "'%s' != '%s'\n", model[0], model[1]);
2945                 return 0;
2946         }
2947
2948         if (strcmp(serial[0], serial[1])) {
2949                 ata_dev_printk(dev, KERN_INFO, "serial number mismatch "
2950                                "'%s' != '%s'\n", serial[0], serial[1]);
2951                 return 0;
2952         }
2953
2954         if (dev->class == ATA_DEV_ATA && dev->n_sectors != new_n_sectors) {
2955                 ata_dev_printk(dev, KERN_INFO, "n_sectors mismatch "
2956                                "%llu != %llu\n",
2957                                (unsigned long long)dev->n_sectors,
2958                                (unsigned long long)new_n_sectors);
2959                 return 0;
2960         }
2961
2962         return 1;
2963 }
2964
2965 /**
2966  *      ata_dev_revalidate - Revalidate ATA device
2967  *      @dev: device to revalidate
2968  *      @post_reset: is this revalidation after reset?
2969  *
2970  *      Re-read IDENTIFY page and make sure @dev is still attached to
2971  *      the port.
2972  *
2973  *      LOCKING:
2974  *      Kernel thread context (may sleep)
2975  *
2976  *      RETURNS:
2977  *      0 on success, negative errno otherwise
2978  */
2979 int ata_dev_revalidate(struct ata_device *dev, int post_reset)
2980 {
2981         unsigned int class = dev->class;
2982         u16 *id = (void *)dev->ap->sector_buf;
2983         int rc;
2984
2985         if (!ata_dev_enabled(dev)) {
2986                 rc = -ENODEV;
2987                 goto fail;
2988         }
2989
2990         /* read ID data */
2991         rc = ata_dev_read_id(dev, &class, post_reset, id);
2992         if (rc)
2993                 goto fail;
2994
2995         /* is the device still there? */
2996         if (!ata_dev_same_device(dev, class, id)) {
2997                 rc = -ENODEV;
2998                 goto fail;
2999         }
3000
3001         memcpy(dev->id, id, sizeof(id[0]) * ATA_ID_WORDS);
3002
3003         /* configure device according to the new ID */
3004         rc = ata_dev_configure(dev, 0);
3005         if (rc == 0)
3006                 return 0;
3007
3008  fail:
3009         ata_dev_printk(dev, KERN_ERR, "revalidation failed (errno=%d)\n", rc);
3010         return rc;
3011 }
3012
3013 static const char * const ata_dma_blacklist [] = {
3014         "WDC AC11000H", NULL,
3015         "WDC AC22100H", NULL,
3016         "WDC AC32500H", NULL,
3017         "WDC AC33100H", NULL,
3018         "WDC AC31600H", NULL,
3019         "WDC AC32100H", "24.09P07",
3020         "WDC AC23200L", "21.10N21",
3021         "Compaq CRD-8241B",  NULL,
3022         "CRD-8400B", NULL,
3023         "CRD-8480B", NULL,
3024         "CRD-8482B", NULL,
3025         "CRD-84", NULL,
3026         "SanDisk SDP3B", NULL,
3027         "SanDisk SDP3B-64", NULL,
3028         "SANYO CD-ROM CRD", NULL,
3029         "HITACHI CDR-8", NULL,
3030         "HITACHI CDR-8335", NULL,
3031         "HITACHI CDR-8435", NULL,
3032         "Toshiba CD-ROM XM-6202B", NULL,
3033         "TOSHIBA CD-ROM XM-1702BC", NULL,
3034         "CD-532E-A", NULL,
3035         "E-IDE CD-ROM CR-840", NULL,
3036         "CD-ROM Drive/F5A", NULL,
3037         "WPI CDD-820", NULL,
3038         "SAMSUNG CD-ROM SC-148C", NULL,
3039         "SAMSUNG CD-ROM SC", NULL,
3040         "SanDisk SDP3B-64", NULL,
3041         "ATAPI CD-ROM DRIVE 40X MAXIMUM",NULL,
3042         "_NEC DV5800A", NULL,
3043         "SAMSUNG CD-ROM SN-124", "N001"
3044 };
3045
3046 static int ata_strim(char *s, size_t len)
3047 {
3048         len = strnlen(s, len);
3049
3050         /* ATAPI specifies that empty space is blank-filled; remove blanks */
3051         while ((len > 0) && (s[len - 1] == ' ')) {
3052                 len--;
3053                 s[len] = 0;
3054         }
3055         return len;
3056 }
3057
3058 static int ata_dma_blacklisted(const struct ata_device *dev)
3059 {
3060         unsigned char model_num[40];
3061         unsigned char model_rev[16];
3062         unsigned int nlen, rlen;
3063         int i;
3064
3065         /* We don't support polling DMA.
3066          * DMA blacklist those ATAPI devices with CDB-intr (and use PIO)
3067          * if the LLDD handles only interrupts in the HSM_ST_LAST state.
3068          */
3069         if ((dev->ap->flags & ATA_FLAG_PIO_POLLING) &&
3070             (dev->flags & ATA_DFLAG_CDB_INTR))
3071                 return 1;
3072
3073         ata_id_string(dev->id, model_num, ATA_ID_PROD_OFS,
3074                           sizeof(model_num));
3075         ata_id_string(dev->id, model_rev, ATA_ID_FW_REV_OFS,
3076                           sizeof(model_rev));
3077         nlen = ata_strim(model_num, sizeof(model_num));
3078         rlen = ata_strim(model_rev, sizeof(model_rev));
3079
3080         for (i = 0; i < ARRAY_SIZE(ata_dma_blacklist); i += 2) {
3081                 if (!strncmp(ata_dma_blacklist[i], model_num, nlen)) {
3082                         if (ata_dma_blacklist[i+1] == NULL)
3083                                 return 1;
3084                         if (!strncmp(ata_dma_blacklist[i], model_rev, rlen))
3085                                 return 1;
3086                 }
3087         }
3088         return 0;
3089 }
3090
3091 /**
3092  *      ata_dev_xfermask - Compute supported xfermask of the given device
3093  *      @dev: Device to compute xfermask for
3094  *
3095  *      Compute supported xfermask of @dev and store it in
3096  *      dev->*_mask.  This function is responsible for applying all
3097  *      known limits including host controller limits, device
3098  *      blacklist, etc...
3099  *
3100  *      LOCKING:
3101  *      None.
3102  */
3103 static void ata_dev_xfermask(struct ata_device *dev)
3104 {
3105         struct ata_port *ap = dev->ap;
3106         struct ata_host *host = ap->host;
3107         unsigned long xfer_mask;
3108
3109         /* controller modes available */
3110         xfer_mask = ata_pack_xfermask(ap->pio_mask,
3111                                       ap->mwdma_mask, ap->udma_mask);
3112
3113         /* Apply cable rule here.  Don't apply it early because when
3114          * we handle hot plug the cable type can itself change.
3115          */
3116         if (ap->cbl == ATA_CBL_PATA40)
3117                 xfer_mask &= ~(0xF8 << ATA_SHIFT_UDMA);
3118
3119         xfer_mask &= ata_pack_xfermask(dev->pio_mask,
3120                                        dev->mwdma_mask, dev->udma_mask);
3121         xfer_mask &= ata_id_xfermask(dev->id);
3122
3123         /*
3124          *      CFA Advanced TrueIDE timings are not allowed on a shared
3125          *      cable
3126          */
3127         if (ata_dev_pair(dev)) {
3128                 /* No PIO5 or PIO6 */
3129                 xfer_mask &= ~(0x03 << (ATA_SHIFT_PIO + 5));
3130                 /* No MWDMA3 or MWDMA 4 */
3131                 xfer_mask &= ~(0x03 << (ATA_SHIFT_MWDMA + 3));
3132         }
3133
3134         if (ata_dma_blacklisted(dev)) {
3135                 xfer_mask &= ~(ATA_MASK_MWDMA | ATA_MASK_UDMA);
3136                 ata_dev_printk(dev, KERN_WARNING,
3137                                "device is on DMA blacklist, disabling DMA\n");
3138         }
3139
3140         if ((host->flags & ATA_HOST_SIMPLEX) && host->simplex_claimed) {
3141                 xfer_mask &= ~(ATA_MASK_MWDMA | ATA_MASK_UDMA);
3142                 ata_dev_printk(dev, KERN_WARNING, "simplex DMA is claimed by "
3143                                "other device, disabling DMA\n");
3144         }
3145
3146         if (ap->ops->mode_filter)
3147                 xfer_mask = ap->ops->mode_filter(ap, dev, xfer_mask);
3148
3149         ata_unpack_xfermask(xfer_mask, &dev->pio_mask,
3150                             &dev->mwdma_mask, &dev->udma_mask);
3151 }
3152
3153 /**
3154  *      ata_dev_set_xfermode - Issue SET FEATURES - XFER MODE command
3155  *      @dev: Device to which command will be sent
3156  *
3157  *      Issue SET FEATURES - XFER MODE command to device @dev
3158  *      on port @ap.
3159  *
3160  *      LOCKING:
3161  *      PCI/etc. bus probe sem.
3162  *
3163  *      RETURNS:
3164  *      0 on success, AC_ERR_* mask otherwise.
3165  */
3166
3167 static unsigned int ata_dev_set_xfermode(struct ata_device *dev)
3168 {
3169         struct ata_taskfile tf;
3170         unsigned int err_mask;
3171
3172         /* set up set-features taskfile */
3173         DPRINTK("set features - xfer mode\n");
3174
3175         ata_tf_init(dev, &tf);
3176         tf.command = ATA_CMD_SET_FEATURES;
3177         tf.feature = SETFEATURES_XFER;
3178         tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
3179         tf.protocol = ATA_PROT_NODATA;
3180         tf.nsect = dev->xfer_mode;
3181
3182         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0);
3183
3184         DPRINTK("EXIT, err_mask=%x\n", err_mask);
3185         return err_mask;
3186 }
3187
3188 /**
3189  *      ata_dev_init_params - Issue INIT DEV PARAMS command
3190  *      @dev: Device to which command will be sent
3191  *      @heads: Number of heads (taskfile parameter)
3192  *      @sectors: Number of sectors (taskfile parameter)
3193  *
3194  *      LOCKING:
3195  *      Kernel thread context (may sleep)
3196  *
3197  *      RETURNS:
3198  *      0 on success, AC_ERR_* mask otherwise.
3199  */
3200 static unsigned int ata_dev_init_params(struct ata_device *dev,
3201                                         u16 heads, u16 sectors)
3202 {
3203         struct ata_taskfile tf;
3204         unsigned int err_mask;
3205
3206         /* Number of sectors per track 1-255. Number of heads 1-16 */
3207         if (sectors < 1 || sectors > 255 || heads < 1 || heads > 16)
3208                 return AC_ERR_INVALID;
3209
3210         /* set up init dev params taskfile */
3211         DPRINTK("init dev params \n");
3212
3213         ata_tf_init(dev, &tf);
3214         tf.command = ATA_CMD_INIT_DEV_PARAMS;
3215         tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
3216         tf.protocol = ATA_PROT_NODATA;
3217         tf.nsect = sectors;
3218         tf.device |= (heads - 1) & 0x0f; /* max head = num. of heads - 1 */
3219
3220         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0);
3221
3222         DPRINTK("EXIT, err_mask=%x\n", err_mask);
3223         return err_mask;
3224 }
3225
3226 /**
3227  *      ata_sg_clean - Unmap DMA memory associated with command
3228  *      @qc: Command containing DMA memory to be released
3229  *
3230  *      Unmap all mapped DMA memory associated with this command.
3231  *
3232  *      LOCKING:
3233  *      spin_lock_irqsave(host lock)
3234  */
3235
3236 static void ata_sg_clean(struct ata_queued_cmd *qc)
3237 {
3238         struct ata_port *ap = qc->ap;
3239         struct scatterlist *sg = qc->__sg;
3240         int dir = qc->dma_dir;
3241         void *pad_buf = NULL;
3242
3243         WARN_ON(!(qc->flags & ATA_QCFLAG_DMAMAP));
3244         WARN_ON(sg == NULL);
3245
3246         if (qc->flags & ATA_QCFLAG_SINGLE)
3247                 WARN_ON(qc->n_elem > 1);
3248
3249         VPRINTK("unmapping %u sg elements\n", qc->n_elem);
3250
3251         /* if we padded the buffer out to 32-bit bound, and data
3252          * xfer direction is from-device, we must copy from the
3253          * pad buffer back into the supplied buffer
3254          */
3255         if (qc->pad_len && !(qc->tf.flags & ATA_TFLAG_WRITE))
3256                 pad_buf = ap->pad + (qc->tag * ATA_DMA_PAD_SZ);
3257
3258         if (qc->flags & ATA_QCFLAG_SG) {
3259                 if (qc->n_elem)
3260                         dma_unmap_sg(ap->dev, sg, qc->n_elem, dir);
3261                 /* restore last sg */
3262                 sg[qc->orig_n_elem - 1].length += qc->pad_len;
3263                 if (pad_buf) {
3264                         struct scatterlist *psg = &qc->pad_sgent;
3265                         void *addr = kmap_atomic(psg->page, KM_IRQ0);
3266                         memcpy(addr + psg->offset, pad_buf, qc->pad_len);
3267                         kunmap_atomic(addr, KM_IRQ0);
3268                 }
3269         } else {
3270                 if (qc->n_elem)
3271                         dma_unmap_single(ap->dev,
3272                                 sg_dma_address(&sg[0]), sg_dma_len(&sg[0]),
3273                                 dir);
3274                 /* restore sg */
3275                 sg->length += qc->pad_len;
3276                 if (pad_buf)
3277                         memcpy(qc->buf_virt + sg->length - qc->pad_len,
3278                                pad_buf, qc->pad_len);
3279         }
3280
3281         qc->flags &= ~ATA_QCFLAG_DMAMAP;
3282         qc->__sg = NULL;
3283 }
3284
3285 /**
3286  *      ata_fill_sg - Fill PCI IDE PRD table
3287  *      @qc: Metadata associated with taskfile to be transferred
3288  *
3289  *      Fill PCI IDE PRD (scatter-gather) table with segments
3290  *      associated with the current disk command.
3291  *
3292  *      LOCKING:
3293  *      spin_lock_irqsave(host lock)
3294  *
3295  */
3296 static void ata_fill_sg(struct ata_queued_cmd *qc)
3297 {
3298         struct ata_port *ap = qc->ap;
3299         struct scatterlist *sg;
3300         unsigned int idx;
3301
3302         WARN_ON(qc->__sg == NULL);
3303         WARN_ON(qc->n_elem == 0 && qc->pad_len == 0);
3304
3305         idx = 0;
3306         ata_for_each_sg(sg, qc) {
3307                 u32 addr, offset;
3308                 u32 sg_len, len;
3309
3310                 /* determine if physical DMA addr spans 64K boundary.
3311                  * Note h/w doesn't support 64-bit, so we unconditionally
3312                  * truncate dma_addr_t to u32.
3313                  */
3314                 addr = (u32) sg_dma_address(sg);
3315                 sg_len = sg_dma_len(sg);
3316
3317                 while (sg_len) {
3318                         offset = addr & 0xffff;
3319                         len = sg_len;
3320                         if ((offset + sg_len) > 0x10000)
3321                                 len = 0x10000 - offset;
3322
3323                         ap->prd[idx].addr = cpu_to_le32(addr);
3324                         ap->prd[idx].flags_len = cpu_to_le32(len & 0xffff);
3325                         VPRINTK("PRD[%u] = (0x%X, 0x%X)\n", idx, addr, len);
3326
3327                         idx++;
3328                         sg_len -= len;
3329                         addr += len;
3330                 }
3331         }
3332
3333         if (idx)
3334                 ap->prd[idx - 1].flags_len |= cpu_to_le32(ATA_PRD_EOT);
3335 }
3336 /**
3337  *      ata_check_atapi_dma - Check whether ATAPI DMA can be supported
3338  *      @qc: Metadata associated with taskfile to check
3339  *
3340  *      Allow low-level driver to filter ATA PACKET commands, returning
3341  *      a status indicating whether or not it is OK to use DMA for the
3342  *      supplied PACKET command.
3343  *
3344  *      LOCKING:
3345  *      spin_lock_irqsave(host lock)
3346  *
3347  *      RETURNS: 0 when ATAPI DMA can be used
3348  *               nonzero otherwise
3349  */
3350 int ata_check_atapi_dma(struct ata_queued_cmd *qc)
3351 {
3352         struct ata_port *ap = qc->ap;
3353         int rc = 0; /* Assume ATAPI DMA is OK by default */
3354
3355         if (ap->ops->check_atapi_dma)
3356                 rc = ap->ops->check_atapi_dma(qc);
3357
3358         return rc;
3359 }
3360 /**
3361  *      ata_qc_prep - Prepare taskfile for submission
3362  *      @qc: Metadata associated with taskfile to be prepared
3363  *
3364  *      Prepare ATA taskfile for submission.
3365  *
3366  *      LOCKING:
3367  *      spin_lock_irqsave(host lock)
3368  */
3369 void ata_qc_prep(struct ata_queued_cmd *qc)
3370 {
3371         if (!(qc->flags & ATA_QCFLAG_DMAMAP))
3372                 return;
3373
3374         ata_fill_sg(qc);
3375 }
3376
3377 void ata_noop_qc_prep(struct ata_queued_cmd *qc) { }
3378
3379 /**
3380  *      ata_sg_init_one - Associate command with memory buffer
3381  *      @qc: Command to be associated
3382  *      @buf: Memory buffer
3383  *      @buflen: Length of memory buffer, in bytes.
3384  *
3385  *      Initialize the data-related elements of queued_cmd @qc
3386  *      to point to a single memory buffer, @buf of byte length @buflen.
3387  *
3388  *      LOCKING:
3389  *      spin_lock_irqsave(host lock)
3390  */
3391
3392 void ata_sg_init_one(struct ata_queued_cmd *qc, void *buf, unsigned int buflen)
3393 {
3394         struct scatterlist *sg;
3395
3396         qc->flags |= ATA_QCFLAG_SINGLE;
3397
3398         memset(&qc->sgent, 0, sizeof(qc->sgent));
3399         qc->__sg = &qc->sgent;
3400         qc->n_elem = 1;
3401         qc->orig_n_elem = 1;
3402         qc->buf_virt = buf;
3403         qc->nbytes = buflen;
3404
3405         sg = qc->__sg;
3406         sg_init_one(sg, buf, buflen);
3407 }
3408
3409 /**
3410  *      ata_sg_init - Associate command with scatter-gather table.
3411  *      @qc: Command to be associated
3412  *      @sg: Scatter-gather table.
3413  *      @n_elem: Number of elements in s/g table.
3414  *
3415  *      Initialize the data-related elements of queued_cmd @qc
3416  *      to point to a scatter-gather table @sg, containing @n_elem
3417  *      elements.
3418  *
3419  *      LOCKING:
3420  *      spin_lock_irqsave(host lock)
3421  */
3422
3423 void ata_sg_init(struct ata_queued_cmd *qc, struct scatterlist *sg,
3424                  unsigned int n_elem)
3425 {
3426         qc->flags |= ATA_QCFLAG_SG;
3427         qc->__sg = sg;
3428         qc->n_elem = n_elem;
3429         qc->orig_n_elem = n_elem;
3430 }
3431
3432 /**
3433  *      ata_sg_setup_one - DMA-map the memory buffer associated with a command.
3434  *      @qc: Command with memory buffer to be mapped.
3435  *
3436  *      DMA-map the memory buffer associated with queued_cmd @qc.
3437  *
3438  *      LOCKING:
3439  *      spin_lock_irqsave(host lock)
3440  *
3441  *      RETURNS:
3442  *      Zero on success, negative on error.
3443  */
3444
3445 static int ata_sg_setup_one(struct ata_queued_cmd *qc)
3446 {
3447         struct ata_port *ap = qc->ap;
3448         int dir = qc->dma_dir;
3449         struct scatterlist *sg = qc->__sg;
3450         dma_addr_t dma_address;
3451         int trim_sg = 0;
3452
3453         /* we must lengthen transfers to end on a 32-bit boundary */
3454         qc->pad_len = sg->length & 3;
3455         if (qc->pad_len) {
3456                 void *pad_buf = ap->pad + (qc->tag * ATA_DMA_PAD_SZ);
3457                 struct scatterlist *psg = &qc->pad_sgent;
3458
3459                 WARN_ON(qc->dev->class != ATA_DEV_ATAPI);
3460
3461                 memset(pad_buf, 0, ATA_DMA_PAD_SZ);
3462
3463                 if (qc->tf.flags & ATA_TFLAG_WRITE)
3464                         memcpy(pad_buf, qc->buf_virt + sg->length - qc->pad_len,
3465                                qc->pad_len);
3466
3467                 sg_dma_address(psg) = ap->pad_dma + (qc->tag * ATA_DMA_PAD_SZ);
3468                 sg_dma_len(psg) = ATA_DMA_PAD_SZ;
3469                 /* trim sg */
3470                 sg->length -= qc->pad_len;
3471                 if (sg->length == 0)
3472                         trim_sg = 1;
3473
3474                 DPRINTK("padding done, sg->length=%u pad_len=%u\n",
3475                         sg->length, qc->pad_len);
3476         }
3477
3478         if (trim_sg) {
3479                 qc->n_elem--;
3480                 goto skip_map;
3481         }
3482
3483         dma_address = dma_map_single(ap->dev, qc->buf_virt,
3484                                      sg->length, dir);
3485         if (dma_mapping_error(dma_address)) {
3486                 /* restore sg */
3487                 sg->length += qc->pad_len;
3488                 return -1;
3489         }
3490
3491         sg_dma_address(sg) = dma_address;
3492         sg_dma_len(sg) = sg->length;
3493
3494 skip_map:
3495         DPRINTK("mapped buffer of %d bytes for %s\n", sg_dma_len(sg),
3496                 qc->tf.flags & ATA_TFLAG_WRITE ? "write" : "read");
3497
3498         return 0;
3499 }
3500
3501 /**
3502  *      ata_sg_setup - DMA-map the scatter-gather table associated with a command.
3503  *      @qc: Command with scatter-gather table to be mapped.
3504  *
3505  *      DMA-map the scatter-gather table associated with queued_cmd @qc.
3506  *
3507  *      LOCKING:
3508  *      spin_lock_irqsave(host lock)
3509  *
3510  *      RETURNS:
3511  *      Zero on success, negative on error.
3512  *
3513  */
3514
3515 static int ata_sg_setup(struct ata_queued_cmd *qc)
3516 {
3517         struct ata_port *ap = qc->ap;
3518         struct scatterlist *sg = qc->__sg;
3519         struct scatterlist *lsg = &sg[qc->n_elem - 1];
3520         int n_elem, pre_n_elem, dir, trim_sg = 0;
3521
3522         VPRINTK("ENTER, ata%u\n", ap->id);
3523         WARN_ON(!(qc->flags & ATA_QCFLAG_SG));
3524
3525         /* we must lengthen transfers to end on a 32-bit boundary */
3526         qc->pad_len = lsg->length & 3;
3527         if (qc->pad_len) {
3528                 void *pad_buf = ap->pad + (qc->tag * ATA_DMA_PAD_SZ);
3529                 struct scatterlist *psg = &qc->pad_sgent;
3530                 unsigned int offset;
3531
3532                 WARN_ON(qc->dev->class != ATA_DEV_ATAPI);
3533
3534                 memset(pad_buf, 0, ATA_DMA_PAD_SZ);
3535
3536                 /*
3537                  * psg->page/offset are used to copy to-be-written
3538                  * data in this function or read data in ata_sg_clean.
3539                  */
3540                 offset = lsg->offset + lsg->length - qc->pad_len;
3541                 psg->page = nth_page(lsg->page, offset >> PAGE_SHIFT);
3542                 psg->offset = offset_in_page(offset);
3543
3544                 if (qc->tf.flags & ATA_TFLAG_WRITE) {
3545                         void *addr = kmap_atomic(psg->page, KM_IRQ0);
3546                         memcpy(pad_buf, addr + psg->offset, qc->pad_len);
3547                         kunmap_atomic(addr, KM_IRQ0);
3548                 }
3549
3550                 sg_dma_address(psg) = ap->pad_dma + (qc->tag * ATA_DMA_PAD_SZ);
3551                 sg_dma_len(psg) = ATA_DMA_PAD_SZ;
3552                 /* trim last sg */
3553                 lsg->length -= qc->pad_len;
3554                 if (lsg->length == 0)
3555                         trim_sg = 1;
3556
3557                 DPRINTK("padding done, sg[%d].length=%u pad_len=%u\n",
3558                         qc->n_elem - 1, lsg->length, qc->pad_len);
3559         }
3560
3561         pre_n_elem = qc->n_elem;
3562         if (trim_sg && pre_n_elem)
3563                 pre_n_elem--;
3564
3565         if (!pre_n_elem) {
3566                 n_elem = 0;
3567                 goto skip_map;
3568         }
3569
3570         dir = qc->dma_dir;
3571         n_elem = dma_map_sg(ap->dev, sg, pre_n_elem, dir);
3572         if (n_elem < 1) {
3573                 /* restore last sg */
3574                 lsg->length += qc->pad_len;
3575                 return -1;
3576         }
3577
3578         DPRINTK("%d sg elements mapped\n", n_elem);
3579
3580 skip_map:
3581         qc->n_elem = n_elem;
3582
3583         return 0;
3584 }
3585
3586 /**
3587  *      swap_buf_le16 - swap halves of 16-bit words in place
3588  *      @buf:  Buffer to swap
3589  *      @buf_words:  Number of 16-bit words in buffer.
3590  *
3591  *      Swap halves of 16-bit words if needed to convert from
3592  *      little-endian byte order to native cpu byte order, or
3593  *      vice-versa.
3594  *
3595  *      LOCKING:
3596  *      Inherited from caller.
3597  */
3598 void swap_buf_le16(u16 *buf, unsigned int buf_words)
3599 {
3600 #ifdef __BIG_ENDIAN
3601         unsigned int i;
3602
3603         for (i = 0; i < buf_words; i++)
3604                 buf[i] = le16_to_cpu(buf[i]);
3605 #endif /* __BIG_ENDIAN */
3606 }
3607
3608 /**
3609  *      ata_mmio_data_xfer - Transfer data by MMIO
3610  *      @adev: device for this I/O
3611  *      @buf: data buffer
3612  *      @buflen: buffer length
3613  *      @write_data: read/write
3614  *
3615  *      Transfer data from/to the device data register by MMIO.
3616  *
3617  *      LOCKING:
3618  *      Inherited from caller.
3619  */
3620
3621 void ata_mmio_data_xfer(struct ata_device *adev, unsigned char *buf,
3622                         unsigned int buflen, int write_data)
3623 {
3624         struct ata_port *ap = adev->ap;
3625         unsigned int i;
3626         unsigned int words = buflen >> 1;
3627         u16 *buf16 = (u16 *) buf;
3628         void __iomem *mmio = (void __iomem *)ap->ioaddr.data_addr;
3629
3630         /* Transfer multiple of 2 bytes */
3631         if (write_data) {
3632                 for (i = 0; i < words; i++)
3633                         writew(le16_to_cpu(buf16[i]), mmio);
3634         } else {
3635                 for (i = 0; i < words; i++)
3636                         buf16[i] = cpu_to_le16(readw(mmio));
3637         }
3638
3639         /* Transfer trailing 1 byte, if any. */
3640         if (unlikely(buflen & 0x01)) {
3641                 u16 align_buf[1] = { 0 };
3642                 unsigned char *trailing_buf = buf + buflen - 1;
3643
3644                 if (write_data) {
3645                         memcpy(align_buf, trailing_buf, 1);
3646                         writew(le16_to_cpu(align_buf[0]), mmio);
3647                 } else {
3648                         align_buf[0] = cpu_to_le16(readw(mmio));
3649                         memcpy(trailing_buf, align_buf, 1);
3650                 }
3651         }
3652 }
3653
3654 /**
3655  *      ata_pio_data_xfer - Transfer data by PIO
3656  *      @adev: device to target
3657  *      @buf: data buffer
3658  *      @buflen: buffer length
3659  *      @write_data: read/write
3660  *
3661  *      Transfer data from/to the device data register by PIO.
3662  *
3663  *      LOCKING:
3664  *      Inherited from caller.
3665  */
3666
3667 void ata_pio_data_xfer(struct ata_device *adev, unsigned char *buf,
3668                        unsigned int buflen, int write_data)
3669 {
3670         struct ata_port *ap = adev->ap;
3671         unsigned int words = buflen >> 1;
3672
3673         /* Transfer multiple of 2 bytes */
3674         if (write_data)
3675                 outsw(ap->ioaddr.data_addr, buf, words);
3676         else
3677                 insw(ap->ioaddr.data_addr, buf, words);
3678
3679         /* Transfer trailing 1 byte, if any. */
3680         if (unlikely(buflen & 0x01)) {
3681                 u16 align_buf[1] = { 0 };
3682                 unsigned char *trailing_buf = buf + buflen - 1;
3683
3684                 if (write_data) {
3685                         memcpy(align_buf, trailing_buf, 1);
3686                         outw(le16_to_cpu(align_buf[0]), ap->ioaddr.data_addr);
3687                 } else {
3688                         align_buf[0] = cpu_to_le16(inw(ap->ioaddr.data_addr));
3689                         memcpy(trailing_buf, align_buf, 1);
3690                 }
3691         }
3692 }
3693
3694 /**
3695  *      ata_pio_data_xfer_noirq - Transfer data by PIO
3696  *      @adev: device to target
3697  *      @buf: data buffer
3698  *      @buflen: buffer length
3699  *      @write_data: read/write
3700  *
3701  *      Transfer data from/to the device data register by PIO. Do the
3702  *      transfer with interrupts disabled.
3703  *
3704  *      LOCKING:
3705  *      Inherited from caller.
3706  */
3707
3708 void ata_pio_data_xfer_noirq(struct ata_device *adev, unsigned char *buf,
3709                                     unsigned int buflen, int write_data)
3710 {
3711         unsigned long flags;
3712         local_irq_save(flags);
3713         ata_pio_data_xfer(adev, buf, buflen, write_data);
3714         local_irq_restore(flags);
3715 }
3716
3717
3718 /**
3719  *      ata_pio_sector - Transfer ATA_SECT_SIZE (512 bytes) of data.
3720  *      @qc: Command on going
3721  *
3722  *      Transfer ATA_SECT_SIZE of data from/to the ATA device.
3723  *
3724  *      LOCKING:
3725  *      Inherited from caller.
3726  */
3727
3728 static void ata_pio_sector(struct ata_queued_cmd *qc)
3729 {
3730         int do_write = (qc->tf.flags & ATA_TFLAG_WRITE);
3731         struct scatterlist *sg = qc->__sg;
3732         struct ata_port *ap = qc->ap;
3733         struct page *page;
3734         unsigned int offset;
3735         unsigned char *buf;
3736
3737         if (qc->cursect == (qc->nsect - 1))
3738                 ap->hsm_task_state = HSM_ST_LAST;
3739
3740         page = sg[qc->cursg].page;
3741         offset = sg[qc->cursg].offset + qc->cursg_ofs * ATA_SECT_SIZE;
3742
3743         /* get the current page and offset */
3744         page = nth_page(page, (offset >> PAGE_SHIFT));
3745         offset %= PAGE_SIZE;
3746
3747         DPRINTK("data %s\n", qc->tf.flags & ATA_TFLAG_WRITE ? "write" : "read");
3748
3749         if (PageHighMem(page)) {
3750                 unsigned long flags;
3751
3752                 /* FIXME: use a bounce buffer */
3753                 local_irq_save(flags);
3754                 buf = kmap_atomic(page, KM_IRQ0);
3755
3756                 /* do the actual data transfer */
3757                 ap->ops->data_xfer(qc->dev, buf + offset, ATA_SECT_SIZE, do_write);
3758
3759                 kunmap_atomic(buf, KM_IRQ0);
3760                 local_irq_restore(flags);
3761         } else {
3762                 buf = page_address(page);
3763                 ap->ops->data_xfer(qc->dev, buf + offset, ATA_SECT_SIZE, do_write);
3764         }
3765
3766         qc->cursect++;
3767         qc->cursg_ofs++;
3768
3769         if ((qc->cursg_ofs * ATA_SECT_SIZE) == (&sg[qc->cursg])->length) {
3770                 qc->cursg++;
3771                 qc->cursg_ofs = 0;
3772         }
3773 }
3774
3775 /**
3776  *      ata_pio_sectors - Transfer one or many 512-byte sectors.
3777  *      @qc: Command on going
3778  *
3779  *      Transfer one or many ATA_SECT_SIZE of data from/to the
3780  *      ATA device for the DRQ request.
3781  *
3782  *      LOCKING:
3783  *      Inherited from caller.
3784  */
3785
3786 static void ata_pio_sectors(struct ata_queued_cmd *qc)
3787 {
3788         if (is_multi_taskfile(&qc->tf)) {
3789                 /* READ/WRITE MULTIPLE */
3790                 unsigned int nsect;
3791
3792                 WARN_ON(qc->dev->multi_count == 0);
3793
3794                 nsect = min(qc->nsect - qc->cursect, qc->dev->multi_count);
3795                 while (nsect--)
3796                         ata_pio_sector(qc);
3797         } else
3798                 ata_pio_sector(qc);
3799 }
3800
3801 /**
3802  *      atapi_send_cdb - Write CDB bytes to hardware
3803  *      @ap: Port to which ATAPI device is attached.
3804  *      @qc: Taskfile currently active
3805  *
3806  *      When device has indicated its readiness to accept
3807  *      a CDB, this function is called.  Send the CDB.
3808  *
3809  *      LOCKING:
3810  *      caller.
3811  */
3812
3813 static void atapi_send_cdb(struct ata_port *ap, struct ata_queued_cmd *qc)
3814 {
3815         /* send SCSI cdb */
3816         DPRINTK("send cdb\n");
3817         WARN_ON(qc->dev->cdb_len < 12);
3818
3819         ap->ops->data_xfer(qc->dev, qc->cdb, qc->dev->cdb_len, 1);
3820         ata_altstatus(ap); /* flush */
3821
3822         switch (qc->tf.protocol) {
3823         case ATA_PROT_ATAPI:
3824                 ap->hsm_task_state = HSM_ST;
3825                 break;
3826         case ATA_PROT_ATAPI_NODATA:
3827                 ap->hsm_task_state = HSM_ST_LAST;
3828                 break;
3829         case ATA_PROT_ATAPI_DMA:
3830                 ap->hsm_task_state = HSM_ST_LAST;
3831                 /* initiate bmdma */
3832                 ap->ops->bmdma_start(qc);
3833                 break;
3834         }
3835 }
3836
3837 /**
3838  *      __atapi_pio_bytes - Transfer data from/to the ATAPI device.