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