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