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