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