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