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