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