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