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