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