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