]> err.no Git - linux-2.6/blob - drivers/ata/libata-core.c
libata: assume ATA_DEV_ATA on diagnostic failure
[linux-2.6] / drivers / ata / 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/kernel.h>
36 #include <linux/module.h>
37 #include <linux/pci.h>
38 #include <linux/init.h>
39 #include <linux/list.h>
40 #include <linux/mm.h>
41 #include <linux/highmem.h>
42 #include <linux/spinlock.h>
43 #include <linux/blkdev.h>
44 #include <linux/delay.h>
45 #include <linux/timer.h>
46 #include <linux/interrupt.h>
47 #include <linux/completion.h>
48 #include <linux/suspend.h>
49 #include <linux/workqueue.h>
50 #include <linux/jiffies.h>
51 #include <linux/scatterlist.h>
52 #include <scsi/scsi.h>
53 #include <scsi/scsi_cmnd.h>
54 #include <scsi/scsi_host.h>
55 #include <linux/libata.h>
56 #include <asm/io.h>
57 #include <asm/semaphore.h>
58 #include <asm/byteorder.h>
59
60 #include "libata.h"
61
62 #define DRV_VERSION     "2.21"  /* must be exactly four chars */
63
64
65 /* debounce timing parameters in msecs { interval, duration, timeout } */
66 const unsigned long sata_deb_timing_normal[]            = {   5,  100, 2000 };
67 const unsigned long sata_deb_timing_hotplug[]           = {  25,  500, 2000 };
68 const unsigned long sata_deb_timing_long[]              = { 100, 2000, 5000 };
69
70 static unsigned int ata_dev_init_params(struct ata_device *dev,
71                                         u16 heads, u16 sectors);
72 static unsigned int ata_dev_set_xfermode(struct ata_device *dev);
73 static unsigned int ata_dev_set_AN(struct ata_device *dev, u8 enable);
74 static void ata_dev_xfermask(struct ata_device *dev);
75 static unsigned long ata_dev_blacklisted(const struct ata_device *dev);
76
77 unsigned int ata_print_id = 1;
78 static struct workqueue_struct *ata_wq;
79
80 struct workqueue_struct *ata_aux_wq;
81
82 int atapi_enabled = 1;
83 module_param(atapi_enabled, int, 0444);
84 MODULE_PARM_DESC(atapi_enabled, "Enable discovery of ATAPI devices (0=off, 1=on)");
85
86 int atapi_dmadir = 0;
87 module_param(atapi_dmadir, int, 0444);
88 MODULE_PARM_DESC(atapi_dmadir, "Enable ATAPI DMADIR bridge support (0=off, 1=on)");
89
90 int atapi_passthru16 = 1;
91 module_param(atapi_passthru16, int, 0444);
92 MODULE_PARM_DESC(atapi_passthru16, "Enable ATA_16 passthru for ATAPI devices; on by default (0=off, 1=on)");
93
94 int libata_fua = 0;
95 module_param_named(fua, libata_fua, int, 0444);
96 MODULE_PARM_DESC(fua, "FUA support (0=off, 1=on)");
97
98 static int ata_ignore_hpa = 0;
99 module_param_named(ignore_hpa, ata_ignore_hpa, int, 0644);
100 MODULE_PARM_DESC(ignore_hpa, "Ignore HPA limit (0=keep BIOS limits, 1=ignore limits, using full disk)");
101
102 static int ata_probe_timeout = ATA_TMOUT_INTERNAL / HZ;
103 module_param(ata_probe_timeout, int, 0444);
104 MODULE_PARM_DESC(ata_probe_timeout, "Set ATA probing timeout (seconds)");
105
106 int libata_noacpi = 1;
107 module_param_named(noacpi, libata_noacpi, int, 0444);
108 MODULE_PARM_DESC(noacpi, "Disables the use of ACPI in suspend/resume when set");
109
110 MODULE_AUTHOR("Jeff Garzik");
111 MODULE_DESCRIPTION("Library module for ATA devices");
112 MODULE_LICENSE("GPL");
113 MODULE_VERSION(DRV_VERSION);
114
115
116 /**
117  *      ata_tf_to_fis - Convert ATA taskfile to SATA FIS structure
118  *      @tf: Taskfile to convert
119  *      @pmp: Port multiplier port
120  *      @is_cmd: This FIS is for command
121  *      @fis: Buffer into which data will output
122  *
123  *      Converts a standard ATA taskfile to a Serial ATA
124  *      FIS structure (Register - Host to Device).
125  *
126  *      LOCKING:
127  *      Inherited from caller.
128  */
129 void ata_tf_to_fis(const struct ata_taskfile *tf, u8 pmp, int is_cmd, u8 *fis)
130 {
131         fis[0] = 0x27;                  /* Register - Host to Device FIS */
132         fis[1] = pmp & 0xf;             /* Port multiplier number*/
133         if (is_cmd)
134                 fis[1] |= (1 << 7);     /* bit 7 indicates Command FIS */
135
136         fis[2] = tf->command;
137         fis[3] = tf->feature;
138
139         fis[4] = tf->lbal;
140         fis[5] = tf->lbam;
141         fis[6] = tf->lbah;
142         fis[7] = tf->device;
143
144         fis[8] = tf->hob_lbal;
145         fis[9] = tf->hob_lbam;
146         fis[10] = tf->hob_lbah;
147         fis[11] = tf->hob_feature;
148
149         fis[12] = tf->nsect;
150         fis[13] = tf->hob_nsect;
151         fis[14] = 0;
152         fis[15] = tf->ctl;
153
154         fis[16] = 0;
155         fis[17] = 0;
156         fis[18] = 0;
157         fis[19] = 0;
158 }
159
160 /**
161  *      ata_tf_from_fis - Convert SATA FIS to ATA taskfile
162  *      @fis: Buffer from which data will be input
163  *      @tf: Taskfile to output
164  *
165  *      Converts a serial ATA FIS structure to a standard ATA taskfile.
166  *
167  *      LOCKING:
168  *      Inherited from caller.
169  */
170
171 void ata_tf_from_fis(const u8 *fis, struct ata_taskfile *tf)
172 {
173         tf->command     = fis[2];       /* status */
174         tf->feature     = fis[3];       /* error */
175
176         tf->lbal        = fis[4];
177         tf->lbam        = fis[5];
178         tf->lbah        = fis[6];
179         tf->device      = fis[7];
180
181         tf->hob_lbal    = fis[8];
182         tf->hob_lbam    = fis[9];
183         tf->hob_lbah    = fis[10];
184
185         tf->nsect       = fis[12];
186         tf->hob_nsect   = fis[13];
187 }
188
189 static const u8 ata_rw_cmds[] = {
190         /* pio multi */
191         ATA_CMD_READ_MULTI,
192         ATA_CMD_WRITE_MULTI,
193         ATA_CMD_READ_MULTI_EXT,
194         ATA_CMD_WRITE_MULTI_EXT,
195         0,
196         0,
197         0,
198         ATA_CMD_WRITE_MULTI_FUA_EXT,
199         /* pio */
200         ATA_CMD_PIO_READ,
201         ATA_CMD_PIO_WRITE,
202         ATA_CMD_PIO_READ_EXT,
203         ATA_CMD_PIO_WRITE_EXT,
204         0,
205         0,
206         0,
207         0,
208         /* dma */
209         ATA_CMD_READ,
210         ATA_CMD_WRITE,
211         ATA_CMD_READ_EXT,
212         ATA_CMD_WRITE_EXT,
213         0,
214         0,
215         0,
216         ATA_CMD_WRITE_FUA_EXT
217 };
218
219 /**
220  *      ata_rwcmd_protocol - set taskfile r/w commands and protocol
221  *      @tf: command to examine and configure
222  *      @dev: device tf belongs to
223  *
224  *      Examine the device configuration and tf->flags to calculate
225  *      the proper read/write commands and protocol to use.
226  *
227  *      LOCKING:
228  *      caller.
229  */
230 static int ata_rwcmd_protocol(struct ata_taskfile *tf, struct ata_device *dev)
231 {
232         u8 cmd;
233
234         int index, fua, lba48, write;
235
236         fua = (tf->flags & ATA_TFLAG_FUA) ? 4 : 0;
237         lba48 = (tf->flags & ATA_TFLAG_LBA48) ? 2 : 0;
238         write = (tf->flags & ATA_TFLAG_WRITE) ? 1 : 0;
239
240         if (dev->flags & ATA_DFLAG_PIO) {
241                 tf->protocol = ATA_PROT_PIO;
242                 index = dev->multi_count ? 0 : 8;
243         } else if (lba48 && (dev->link->ap->flags & ATA_FLAG_PIO_LBA48)) {
244                 /* Unable to use DMA due to host limitation */
245                 tf->protocol = ATA_PROT_PIO;
246                 index = dev->multi_count ? 0 : 8;
247         } else {
248                 tf->protocol = ATA_PROT_DMA;
249                 index = 16;
250         }
251
252         cmd = ata_rw_cmds[index + fua + lba48 + write];
253         if (cmd) {
254                 tf->command = cmd;
255                 return 0;
256         }
257         return -1;
258 }
259
260 /**
261  *      ata_tf_read_block - Read block address from ATA taskfile
262  *      @tf: ATA taskfile of interest
263  *      @dev: ATA device @tf belongs to
264  *
265  *      LOCKING:
266  *      None.
267  *
268  *      Read block address from @tf.  This function can handle all
269  *      three address formats - LBA, LBA48 and CHS.  tf->protocol and
270  *      flags select the address format to use.
271  *
272  *      RETURNS:
273  *      Block address read from @tf.
274  */
275 u64 ata_tf_read_block(struct ata_taskfile *tf, struct ata_device *dev)
276 {
277         u64 block = 0;
278
279         if (tf->flags & ATA_TFLAG_LBA) {
280                 if (tf->flags & ATA_TFLAG_LBA48) {
281                         block |= (u64)tf->hob_lbah << 40;
282                         block |= (u64)tf->hob_lbam << 32;
283                         block |= tf->hob_lbal << 24;
284                 } else
285                         block |= (tf->device & 0xf) << 24;
286
287                 block |= tf->lbah << 16;
288                 block |= tf->lbam << 8;
289                 block |= tf->lbal;
290         } else {
291                 u32 cyl, head, sect;
292
293                 cyl = tf->lbam | (tf->lbah << 8);
294                 head = tf->device & 0xf;
295                 sect = tf->lbal;
296
297                 block = (cyl * dev->heads + head) * dev->sectors + sect;
298         }
299
300         return block;
301 }
302
303 /**
304  *      ata_build_rw_tf - Build ATA taskfile for given read/write request
305  *      @tf: Target ATA taskfile
306  *      @dev: ATA device @tf belongs to
307  *      @block: Block address
308  *      @n_block: Number of blocks
309  *      @tf_flags: RW/FUA etc...
310  *      @tag: tag
311  *
312  *      LOCKING:
313  *      None.
314  *
315  *      Build ATA taskfile @tf for read/write request described by
316  *      @block, @n_block, @tf_flags and @tag on @dev.
317  *
318  *      RETURNS:
319  *
320  *      0 on success, -ERANGE if the request is too large for @dev,
321  *      -EINVAL if the request is invalid.
322  */
323 int ata_build_rw_tf(struct ata_taskfile *tf, struct ata_device *dev,
324                     u64 block, u32 n_block, unsigned int tf_flags,
325                     unsigned int tag)
326 {
327         tf->flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
328         tf->flags |= tf_flags;
329
330         if (ata_ncq_enabled(dev) && likely(tag != ATA_TAG_INTERNAL)) {
331                 /* yay, NCQ */
332                 if (!lba_48_ok(block, n_block))
333                         return -ERANGE;
334
335                 tf->protocol = ATA_PROT_NCQ;
336                 tf->flags |= ATA_TFLAG_LBA | ATA_TFLAG_LBA48;
337
338                 if (tf->flags & ATA_TFLAG_WRITE)
339                         tf->command = ATA_CMD_FPDMA_WRITE;
340                 else
341                         tf->command = ATA_CMD_FPDMA_READ;
342
343                 tf->nsect = tag << 3;
344                 tf->hob_feature = (n_block >> 8) & 0xff;
345                 tf->feature = n_block & 0xff;
346
347                 tf->hob_lbah = (block >> 40) & 0xff;
348                 tf->hob_lbam = (block >> 32) & 0xff;
349                 tf->hob_lbal = (block >> 24) & 0xff;
350                 tf->lbah = (block >> 16) & 0xff;
351                 tf->lbam = (block >> 8) & 0xff;
352                 tf->lbal = block & 0xff;
353
354                 tf->device = 1 << 6;
355                 if (tf->flags & ATA_TFLAG_FUA)
356                         tf->device |= 1 << 7;
357         } else if (dev->flags & ATA_DFLAG_LBA) {
358                 tf->flags |= ATA_TFLAG_LBA;
359
360                 if (lba_28_ok(block, n_block)) {
361                         /* use LBA28 */
362                         tf->device |= (block >> 24) & 0xf;
363                 } else if (lba_48_ok(block, n_block)) {
364                         if (!(dev->flags & ATA_DFLAG_LBA48))
365                                 return -ERANGE;
366
367                         /* use LBA48 */
368                         tf->flags |= ATA_TFLAG_LBA48;
369
370                         tf->hob_nsect = (n_block >> 8) & 0xff;
371
372                         tf->hob_lbah = (block >> 40) & 0xff;
373                         tf->hob_lbam = (block >> 32) & 0xff;
374                         tf->hob_lbal = (block >> 24) & 0xff;
375                 } else
376                         /* request too large even for LBA48 */
377                         return -ERANGE;
378
379                 if (unlikely(ata_rwcmd_protocol(tf, dev) < 0))
380                         return -EINVAL;
381
382                 tf->nsect = n_block & 0xff;
383
384                 tf->lbah = (block >> 16) & 0xff;
385                 tf->lbam = (block >> 8) & 0xff;
386                 tf->lbal = block & 0xff;
387
388                 tf->device |= ATA_LBA;
389         } else {
390                 /* CHS */
391                 u32 sect, head, cyl, track;
392
393                 /* The request -may- be too large for CHS addressing. */
394                 if (!lba_28_ok(block, n_block))
395                         return -ERANGE;
396
397                 if (unlikely(ata_rwcmd_protocol(tf, dev) < 0))
398                         return -EINVAL;
399
400                 /* Convert LBA to CHS */
401                 track = (u32)block / dev->sectors;
402                 cyl   = track / dev->heads;
403                 head  = track % dev->heads;
404                 sect  = (u32)block % dev->sectors + 1;
405
406                 DPRINTK("block %u track %u cyl %u head %u sect %u\n",
407                         (u32)block, track, cyl, head, sect);
408
409                 /* Check whether the converted CHS can fit.
410                    Cylinder: 0-65535
411                    Head: 0-15
412                    Sector: 1-255*/
413                 if ((cyl >> 16) || (head >> 4) || (sect >> 8) || (!sect))
414                         return -ERANGE;
415
416                 tf->nsect = n_block & 0xff; /* Sector count 0 means 256 sectors */
417                 tf->lbal = sect;
418                 tf->lbam = cyl;
419                 tf->lbah = cyl >> 8;
420                 tf->device |= head;
421         }
422
423         return 0;
424 }
425
426 /**
427  *      ata_pack_xfermask - Pack pio, mwdma and udma masks into xfer_mask
428  *      @pio_mask: pio_mask
429  *      @mwdma_mask: mwdma_mask
430  *      @udma_mask: udma_mask
431  *
432  *      Pack @pio_mask, @mwdma_mask and @udma_mask into a single
433  *      unsigned int xfer_mask.
434  *
435  *      LOCKING:
436  *      None.
437  *
438  *      RETURNS:
439  *      Packed xfer_mask.
440  */
441 static unsigned int ata_pack_xfermask(unsigned int pio_mask,
442                                       unsigned int mwdma_mask,
443                                       unsigned int udma_mask)
444 {
445         return ((pio_mask << ATA_SHIFT_PIO) & ATA_MASK_PIO) |
446                 ((mwdma_mask << ATA_SHIFT_MWDMA) & ATA_MASK_MWDMA) |
447                 ((udma_mask << ATA_SHIFT_UDMA) & ATA_MASK_UDMA);
448 }
449
450 /**
451  *      ata_unpack_xfermask - Unpack xfer_mask into pio, mwdma and udma masks
452  *      @xfer_mask: xfer_mask to unpack
453  *      @pio_mask: resulting pio_mask
454  *      @mwdma_mask: resulting mwdma_mask
455  *      @udma_mask: resulting udma_mask
456  *
457  *      Unpack @xfer_mask into @pio_mask, @mwdma_mask and @udma_mask.
458  *      Any NULL distination masks will be ignored.
459  */
460 static void ata_unpack_xfermask(unsigned int xfer_mask,
461                                 unsigned int *pio_mask,
462                                 unsigned int *mwdma_mask,
463                                 unsigned int *udma_mask)
464 {
465         if (pio_mask)
466                 *pio_mask = (xfer_mask & ATA_MASK_PIO) >> ATA_SHIFT_PIO;
467         if (mwdma_mask)
468                 *mwdma_mask = (xfer_mask & ATA_MASK_MWDMA) >> ATA_SHIFT_MWDMA;
469         if (udma_mask)
470                 *udma_mask = (xfer_mask & ATA_MASK_UDMA) >> ATA_SHIFT_UDMA;
471 }
472
473 static const struct ata_xfer_ent {
474         int shift, bits;
475         u8 base;
476 } ata_xfer_tbl[] = {
477         { ATA_SHIFT_PIO, ATA_BITS_PIO, XFER_PIO_0 },
478         { ATA_SHIFT_MWDMA, ATA_BITS_MWDMA, XFER_MW_DMA_0 },
479         { ATA_SHIFT_UDMA, ATA_BITS_UDMA, XFER_UDMA_0 },
480         { -1, },
481 };
482
483 /**
484  *      ata_xfer_mask2mode - Find matching XFER_* for the given xfer_mask
485  *      @xfer_mask: xfer_mask of interest
486  *
487  *      Return matching XFER_* value for @xfer_mask.  Only the highest
488  *      bit of @xfer_mask is considered.
489  *
490  *      LOCKING:
491  *      None.
492  *
493  *      RETURNS:
494  *      Matching XFER_* value, 0 if no match found.
495  */
496 static u8 ata_xfer_mask2mode(unsigned int xfer_mask)
497 {
498         int highbit = fls(xfer_mask) - 1;
499         const struct ata_xfer_ent *ent;
500
501         for (ent = ata_xfer_tbl; ent->shift >= 0; ent++)
502                 if (highbit >= ent->shift && highbit < ent->shift + ent->bits)
503                         return ent->base + highbit - ent->shift;
504         return 0;
505 }
506
507 /**
508  *      ata_xfer_mode2mask - Find matching xfer_mask for XFER_*
509  *      @xfer_mode: XFER_* of interest
510  *
511  *      Return matching xfer_mask for @xfer_mode.
512  *
513  *      LOCKING:
514  *      None.
515  *
516  *      RETURNS:
517  *      Matching xfer_mask, 0 if no match found.
518  */
519 static unsigned int ata_xfer_mode2mask(u8 xfer_mode)
520 {
521         const struct ata_xfer_ent *ent;
522
523         for (ent = ata_xfer_tbl; ent->shift >= 0; ent++)
524                 if (xfer_mode >= ent->base && xfer_mode < ent->base + ent->bits)
525                         return 1 << (ent->shift + xfer_mode - ent->base);
526         return 0;
527 }
528
529 /**
530  *      ata_xfer_mode2shift - Find matching xfer_shift for XFER_*
531  *      @xfer_mode: XFER_* of interest
532  *
533  *      Return matching xfer_shift for @xfer_mode.
534  *
535  *      LOCKING:
536  *      None.
537  *
538  *      RETURNS:
539  *      Matching xfer_shift, -1 if no match found.
540  */
541 static int ata_xfer_mode2shift(unsigned int xfer_mode)
542 {
543         const struct ata_xfer_ent *ent;
544
545         for (ent = ata_xfer_tbl; ent->shift >= 0; ent++)
546                 if (xfer_mode >= ent->base && xfer_mode < ent->base + ent->bits)
547                         return ent->shift;
548         return -1;
549 }
550
551 /**
552  *      ata_mode_string - convert xfer_mask to string
553  *      @xfer_mask: mask of bits supported; only highest bit counts.
554  *
555  *      Determine string which represents the highest speed
556  *      (highest bit in @modemask).
557  *
558  *      LOCKING:
559  *      None.
560  *
561  *      RETURNS:
562  *      Constant C string representing highest speed listed in
563  *      @mode_mask, or the constant C string "<n/a>".
564  */
565 static const char *ata_mode_string(unsigned int xfer_mask)
566 {
567         static const char * const xfer_mode_str[] = {
568                 "PIO0",
569                 "PIO1",
570                 "PIO2",
571                 "PIO3",
572                 "PIO4",
573                 "PIO5",
574                 "PIO6",
575                 "MWDMA0",
576                 "MWDMA1",
577                 "MWDMA2",
578                 "MWDMA3",
579                 "MWDMA4",
580                 "UDMA/16",
581                 "UDMA/25",
582                 "UDMA/33",
583                 "UDMA/44",
584                 "UDMA/66",
585                 "UDMA/100",
586                 "UDMA/133",
587                 "UDMA7",
588         };
589         int highbit;
590
591         highbit = fls(xfer_mask) - 1;
592         if (highbit >= 0 && highbit < ARRAY_SIZE(xfer_mode_str))
593                 return xfer_mode_str[highbit];
594         return "<n/a>";
595 }
596
597 static const char *sata_spd_string(unsigned int spd)
598 {
599         static const char * const spd_str[] = {
600                 "1.5 Gbps",
601                 "3.0 Gbps",
602         };
603
604         if (spd == 0 || (spd - 1) >= ARRAY_SIZE(spd_str))
605                 return "<unknown>";
606         return spd_str[spd - 1];
607 }
608
609 void ata_dev_disable(struct ata_device *dev)
610 {
611         if (ata_dev_enabled(dev)) {
612                 if (ata_msg_drv(dev->link->ap))
613                         ata_dev_printk(dev, KERN_WARNING, "disabled\n");
614                 ata_down_xfermask_limit(dev, ATA_DNXFER_FORCE_PIO0 |
615                                              ATA_DNXFER_QUIET);
616                 dev->class++;
617         }
618 }
619
620 /**
621  *      ata_devchk - PATA device presence detection
622  *      @ap: ATA channel to examine
623  *      @device: Device to examine (starting at zero)
624  *
625  *      This technique was originally described in
626  *      Hale Landis's ATADRVR (www.ata-atapi.com), and
627  *      later found its way into the ATA/ATAPI spec.
628  *
629  *      Write a pattern to the ATA shadow registers,
630  *      and if a device is present, it will respond by
631  *      correctly storing and echoing back the
632  *      ATA shadow register contents.
633  *
634  *      LOCKING:
635  *      caller.
636  */
637
638 static unsigned int ata_devchk(struct ata_port *ap, unsigned int device)
639 {
640         struct ata_ioports *ioaddr = &ap->ioaddr;
641         u8 nsect, lbal;
642
643         ap->ops->dev_select(ap, device);
644
645         iowrite8(0x55, ioaddr->nsect_addr);
646         iowrite8(0xaa, ioaddr->lbal_addr);
647
648         iowrite8(0xaa, ioaddr->nsect_addr);
649         iowrite8(0x55, ioaddr->lbal_addr);
650
651         iowrite8(0x55, ioaddr->nsect_addr);
652         iowrite8(0xaa, ioaddr->lbal_addr);
653
654         nsect = ioread8(ioaddr->nsect_addr);
655         lbal = ioread8(ioaddr->lbal_addr);
656
657         if ((nsect == 0x55) && (lbal == 0xaa))
658                 return 1;       /* we found a device */
659
660         return 0;               /* nothing found */
661 }
662
663 /**
664  *      ata_dev_classify - determine device type based on ATA-spec signature
665  *      @tf: ATA taskfile register set for device to be identified
666  *
667  *      Determine from taskfile register contents whether a device is
668  *      ATA or ATAPI, as per "Signature and persistence" section
669  *      of ATA/PI spec (volume 1, sect 5.14).
670  *
671  *      LOCKING:
672  *      None.
673  *
674  *      RETURNS:
675  *      Device type, %ATA_DEV_ATA, %ATA_DEV_ATAPI, or %ATA_DEV_UNKNOWN
676  *      the event of failure.
677  */
678
679 unsigned int ata_dev_classify(const struct ata_taskfile *tf)
680 {
681         /* Apple's open source Darwin code hints that some devices only
682          * put a proper signature into the LBA mid/high registers,
683          * So, we only check those.  It's sufficient for uniqueness.
684          */
685
686         if (((tf->lbam == 0) && (tf->lbah == 0)) ||
687             ((tf->lbam == 0x3c) && (tf->lbah == 0xc3))) {
688                 DPRINTK("found ATA device by sig\n");
689                 return ATA_DEV_ATA;
690         }
691
692         if (((tf->lbam == 0x14) && (tf->lbah == 0xeb)) ||
693             ((tf->lbam == 0x69) && (tf->lbah == 0x96))) {
694                 DPRINTK("found ATAPI device by sig\n");
695                 return ATA_DEV_ATAPI;
696         }
697
698         DPRINTK("unknown device\n");
699         return ATA_DEV_UNKNOWN;
700 }
701
702 /**
703  *      ata_dev_try_classify - Parse returned ATA device signature
704  *      @dev: ATA device to classify (starting at zero)
705  *      @present: device seems present
706  *      @r_err: Value of error register on completion
707  *
708  *      After an event -- SRST, E.D.D., or SATA COMRESET -- occurs,
709  *      an ATA/ATAPI-defined set of values is placed in the ATA
710  *      shadow registers, indicating the results of device detection
711  *      and diagnostics.
712  *
713  *      Select the ATA device, and read the values from the ATA shadow
714  *      registers.  Then parse according to the Error register value,
715  *      and the spec-defined values examined by ata_dev_classify().
716  *
717  *      LOCKING:
718  *      caller.
719  *
720  *      RETURNS:
721  *      Device type - %ATA_DEV_ATA, %ATA_DEV_ATAPI or %ATA_DEV_NONE.
722  */
723 unsigned int ata_dev_try_classify(struct ata_device *dev, int present,
724                                   u8 *r_err)
725 {
726         struct ata_port *ap = dev->link->ap;
727         struct ata_taskfile tf;
728         unsigned int class;
729         u8 err;
730
731         ap->ops->dev_select(ap, dev->devno);
732
733         memset(&tf, 0, sizeof(tf));
734
735         ap->ops->tf_read(ap, &tf);
736         err = tf.feature;
737         if (r_err)
738                 *r_err = err;
739
740         /* see if device passed diags: if master then continue and warn later */
741         if (err == 0 && dev->devno == 0)
742                 /* diagnostic fail : do nothing _YET_ */
743                 dev->horkage |= ATA_HORKAGE_DIAGNOSTIC;
744         else if (err == 1)
745                 /* do nothing */ ;
746         else if ((dev->devno == 0) && (err == 0x81))
747                 /* do nothing */ ;
748         else
749                 return ATA_DEV_NONE;
750
751         /* determine if device is ATA or ATAPI */
752         class = ata_dev_classify(&tf);
753
754         if (class == ATA_DEV_UNKNOWN) {
755                 /* If the device failed diagnostic, it's likely to
756                  * have reported incorrect device signature too.
757                  * Assume ATA device if the device seems present but
758                  * device signature is invalid with diagnostic
759                  * failure.
760                  */
761                 if (present && (dev->horkage & ATA_HORKAGE_DIAGNOSTIC))
762                         class = ATA_DEV_ATA;
763                 else
764                         class = ATA_DEV_NONE;
765         } else if ((class == ATA_DEV_ATA) && (ata_chk_status(ap) == 0))
766                 class = ATA_DEV_NONE;
767
768         return class;
769 }
770
771 /**
772  *      ata_id_string - Convert IDENTIFY DEVICE page into string
773  *      @id: IDENTIFY DEVICE results we will examine
774  *      @s: string into which data is output
775  *      @ofs: offset into identify device page
776  *      @len: length of string to return. must be an even number.
777  *
778  *      The strings in the IDENTIFY DEVICE page are broken up into
779  *      16-bit chunks.  Run through the string, and output each
780  *      8-bit chunk linearly, regardless of platform.
781  *
782  *      LOCKING:
783  *      caller.
784  */
785
786 void ata_id_string(const u16 *id, unsigned char *s,
787                    unsigned int ofs, unsigned int len)
788 {
789         unsigned int c;
790
791         while (len > 0) {
792                 c = id[ofs] >> 8;
793                 *s = c;
794                 s++;
795
796                 c = id[ofs] & 0xff;
797                 *s = c;
798                 s++;
799
800                 ofs++;
801                 len -= 2;
802         }
803 }
804
805 /**
806  *      ata_id_c_string - Convert IDENTIFY DEVICE page into C string
807  *      @id: IDENTIFY DEVICE results we will examine
808  *      @s: string into which data is output
809  *      @ofs: offset into identify device page
810  *      @len: length of string to return. must be an odd number.
811  *
812  *      This function is identical to ata_id_string except that it
813  *      trims trailing spaces and terminates the resulting string with
814  *      null.  @len must be actual maximum length (even number) + 1.
815  *
816  *      LOCKING:
817  *      caller.
818  */
819 void ata_id_c_string(const u16 *id, unsigned char *s,
820                      unsigned int ofs, unsigned int len)
821 {
822         unsigned char *p;
823
824         WARN_ON(!(len & 1));
825
826         ata_id_string(id, s, ofs, len - 1);
827
828         p = s + strnlen(s, len - 1);
829         while (p > s && p[-1] == ' ')
830                 p--;
831         *p = '\0';
832 }
833
834 static u64 ata_id_n_sectors(const u16 *id)
835 {
836         if (ata_id_has_lba(id)) {
837                 if (ata_id_has_lba48(id))
838                         return ata_id_u64(id, 100);
839                 else
840                         return ata_id_u32(id, 60);
841         } else {
842                 if (ata_id_current_chs_valid(id))
843                         return ata_id_u32(id, 57);
844                 else
845                         return id[1] * id[3] * id[6];
846         }
847 }
848
849 static u64 ata_tf_to_lba48(struct ata_taskfile *tf)
850 {
851         u64 sectors = 0;
852
853         sectors |= ((u64)(tf->hob_lbah & 0xff)) << 40;
854         sectors |= ((u64)(tf->hob_lbam & 0xff)) << 32;
855         sectors |= (tf->hob_lbal & 0xff) << 24;
856         sectors |= (tf->lbah & 0xff) << 16;
857         sectors |= (tf->lbam & 0xff) << 8;
858         sectors |= (tf->lbal & 0xff);
859
860         return ++sectors;
861 }
862
863 static u64 ata_tf_to_lba(struct ata_taskfile *tf)
864 {
865         u64 sectors = 0;
866
867         sectors |= (tf->device & 0x0f) << 24;
868         sectors |= (tf->lbah & 0xff) << 16;
869         sectors |= (tf->lbam & 0xff) << 8;
870         sectors |= (tf->lbal & 0xff);
871
872         return ++sectors;
873 }
874
875 /**
876  *      ata_read_native_max_address - Read native max address
877  *      @dev: target device
878  *      @max_sectors: out parameter for the result native max address
879  *
880  *      Perform an LBA48 or LBA28 native size query upon the device in
881  *      question.
882  *
883  *      RETURNS:
884  *      0 on success, -EACCES if command is aborted by the drive.
885  *      -EIO on other errors.
886  */
887 static int ata_read_native_max_address(struct ata_device *dev, u64 *max_sectors)
888 {
889         unsigned int err_mask;
890         struct ata_taskfile tf;
891         int lba48 = ata_id_has_lba48(dev->id);
892
893         ata_tf_init(dev, &tf);
894
895         /* always clear all address registers */
896         tf.flags |= ATA_TFLAG_DEVICE | ATA_TFLAG_ISADDR;
897
898         if (lba48) {
899                 tf.command = ATA_CMD_READ_NATIVE_MAX_EXT;
900                 tf.flags |= ATA_TFLAG_LBA48;
901         } else
902                 tf.command = ATA_CMD_READ_NATIVE_MAX;
903
904         tf.protocol |= ATA_PROT_NODATA;
905         tf.device |= ATA_LBA;
906
907         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0);
908         if (err_mask) {
909                 ata_dev_printk(dev, KERN_WARNING, "failed to read native "
910                                "max address (err_mask=0x%x)\n", err_mask);
911                 if (err_mask == AC_ERR_DEV && (tf.feature & ATA_ABORTED))
912                         return -EACCES;
913                 return -EIO;
914         }
915
916         if (lba48)
917                 *max_sectors = ata_tf_to_lba48(&tf);
918         else
919                 *max_sectors = ata_tf_to_lba(&tf);
920
921         return 0;
922 }
923
924 /**
925  *      ata_set_max_sectors - Set max sectors
926  *      @dev: target device
927  *      @new_sectors: new max sectors value to set for the device
928  *
929  *      Set max sectors of @dev to @new_sectors.
930  *
931  *      RETURNS:
932  *      0 on success, -EACCES if command is aborted or denied (due to
933  *      previous non-volatile SET_MAX) by the drive.  -EIO on other
934  *      errors.
935  */
936 static int ata_set_max_sectors(struct ata_device *dev, u64 new_sectors)
937 {
938         unsigned int err_mask;
939         struct ata_taskfile tf;
940         int lba48 = ata_id_has_lba48(dev->id);
941
942         new_sectors--;
943
944         ata_tf_init(dev, &tf);
945
946         tf.flags |= ATA_TFLAG_DEVICE | ATA_TFLAG_ISADDR;
947
948         if (lba48) {
949                 tf.command = ATA_CMD_SET_MAX_EXT;
950                 tf.flags |= ATA_TFLAG_LBA48;
951
952                 tf.hob_lbal = (new_sectors >> 24) & 0xff;
953                 tf.hob_lbam = (new_sectors >> 32) & 0xff;
954                 tf.hob_lbah = (new_sectors >> 40) & 0xff;
955         } else
956                 tf.command = ATA_CMD_SET_MAX;
957
958         tf.protocol |= ATA_PROT_NODATA;
959         tf.device |= ATA_LBA;
960
961         tf.lbal = (new_sectors >> 0) & 0xff;
962         tf.lbam = (new_sectors >> 8) & 0xff;
963         tf.lbah = (new_sectors >> 16) & 0xff;
964
965         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0);
966         if (err_mask) {
967                 ata_dev_printk(dev, KERN_WARNING, "failed to set "
968                                "max address (err_mask=0x%x)\n", err_mask);
969                 if (err_mask == AC_ERR_DEV &&
970                     (tf.feature & (ATA_ABORTED | ATA_IDNF)))
971                         return -EACCES;
972                 return -EIO;
973         }
974
975         return 0;
976 }
977
978 /**
979  *      ata_hpa_resize          -       Resize a device with an HPA set
980  *      @dev: Device to resize
981  *
982  *      Read the size of an LBA28 or LBA48 disk with HPA features and resize
983  *      it if required to the full size of the media. The caller must check
984  *      the drive has the HPA feature set enabled.
985  *
986  *      RETURNS:
987  *      0 on success, -errno on failure.
988  */
989 static int ata_hpa_resize(struct ata_device *dev)
990 {
991         struct ata_eh_context *ehc = &dev->link->eh_context;
992         int print_info = ehc->i.flags & ATA_EHI_PRINTINFO;
993         u64 sectors = ata_id_n_sectors(dev->id);
994         u64 native_sectors;
995         int rc;
996
997         /* do we need to do it? */
998         if (dev->class != ATA_DEV_ATA ||
999             !ata_id_has_lba(dev->id) || !ata_id_hpa_enabled(dev->id) ||
1000             (dev->horkage & ATA_HORKAGE_BROKEN_HPA))
1001                 return 0;
1002
1003         /* read native max address */
1004         rc = ata_read_native_max_address(dev, &native_sectors);
1005         if (rc) {
1006                 /* If HPA isn't going to be unlocked, skip HPA
1007                  * resizing from the next try.
1008                  */
1009                 if (!ata_ignore_hpa) {
1010                         ata_dev_printk(dev, KERN_WARNING, "HPA support seems "
1011                                        "broken, will skip HPA handling\n");
1012                         dev->horkage |= ATA_HORKAGE_BROKEN_HPA;
1013
1014                         /* we can continue if device aborted the command */
1015                         if (rc == -EACCES)
1016                                 rc = 0;
1017                 }
1018
1019                 return rc;
1020         }
1021
1022         /* nothing to do? */
1023         if (native_sectors <= sectors || !ata_ignore_hpa) {
1024                 if (!print_info || native_sectors == sectors)
1025                         return 0;
1026
1027                 if (native_sectors > sectors)
1028                         ata_dev_printk(dev, KERN_INFO,
1029                                 "HPA detected: current %llu, native %llu\n",
1030                                 (unsigned long long)sectors,
1031                                 (unsigned long long)native_sectors);
1032                 else if (native_sectors < sectors)
1033                         ata_dev_printk(dev, KERN_WARNING,
1034                                 "native sectors (%llu) is smaller than "
1035                                 "sectors (%llu)\n",
1036                                 (unsigned long long)native_sectors,
1037                                 (unsigned long long)sectors);
1038                 return 0;
1039         }
1040
1041         /* let's unlock HPA */
1042         rc = ata_set_max_sectors(dev, native_sectors);
1043         if (rc == -EACCES) {
1044                 /* if device aborted the command, skip HPA resizing */
1045                 ata_dev_printk(dev, KERN_WARNING, "device aborted resize "
1046                                "(%llu -> %llu), skipping HPA handling\n",
1047                                (unsigned long long)sectors,
1048                                (unsigned long long)native_sectors);
1049                 dev->horkage |= ATA_HORKAGE_BROKEN_HPA;
1050                 return 0;
1051         } else if (rc)
1052                 return rc;
1053
1054         /* re-read IDENTIFY data */
1055         rc = ata_dev_reread_id(dev, 0);
1056         if (rc) {
1057                 ata_dev_printk(dev, KERN_ERR, "failed to re-read IDENTIFY "
1058                                "data after HPA resizing\n");
1059                 return rc;
1060         }
1061
1062         if (print_info) {
1063                 u64 new_sectors = ata_id_n_sectors(dev->id);
1064                 ata_dev_printk(dev, KERN_INFO,
1065                         "HPA unlocked: %llu -> %llu, native %llu\n",
1066                         (unsigned long long)sectors,
1067                         (unsigned long long)new_sectors,
1068                         (unsigned long long)native_sectors);
1069         }
1070
1071         return 0;
1072 }
1073
1074 /**
1075  *      ata_id_to_dma_mode      -       Identify DMA mode from id block
1076  *      @dev: device to identify
1077  *      @unknown: mode to assume if we cannot tell
1078  *
1079  *      Set up the timing values for the device based upon the identify
1080  *      reported values for the DMA mode. This function is used by drivers
1081  *      which rely upon firmware configured modes, but wish to report the
1082  *      mode correctly when possible.
1083  *
1084  *      In addition we emit similarly formatted messages to the default
1085  *      ata_dev_set_mode handler, in order to provide consistency of
1086  *      presentation.
1087  */
1088
1089 void ata_id_to_dma_mode(struct ata_device *dev, u8 unknown)
1090 {
1091         unsigned int mask;
1092         u8 mode;
1093
1094         /* Pack the DMA modes */
1095         mask = ((dev->id[63] >> 8) << ATA_SHIFT_MWDMA) & ATA_MASK_MWDMA;
1096         if (dev->id[53] & 0x04)
1097                 mask |= ((dev->id[88] >> 8) << ATA_SHIFT_UDMA) & ATA_MASK_UDMA;
1098
1099         /* Select the mode in use */
1100         mode = ata_xfer_mask2mode(mask);
1101
1102         if (mode != 0) {
1103                 ata_dev_printk(dev, KERN_INFO, "configured for %s\n",
1104                        ata_mode_string(mask));
1105         } else {
1106                 /* SWDMA perhaps ? */
1107                 mode = unknown;
1108                 ata_dev_printk(dev, KERN_INFO, "configured for DMA\n");
1109         }
1110
1111         /* Configure the device reporting */
1112         dev->xfer_mode = mode;
1113         dev->xfer_shift = ata_xfer_mode2shift(mode);
1114 }
1115
1116 /**
1117  *      ata_noop_dev_select - Select device 0/1 on ATA bus
1118  *      @ap: ATA channel to manipulate
1119  *      @device: ATA device (numbered from zero) to select
1120  *
1121  *      This function performs no actual function.
1122  *
1123  *      May be used as the dev_select() entry in ata_port_operations.
1124  *
1125  *      LOCKING:
1126  *      caller.
1127  */
1128 void ata_noop_dev_select (struct ata_port *ap, unsigned int device)
1129 {
1130 }
1131
1132
1133 /**
1134  *      ata_std_dev_select - Select device 0/1 on ATA bus
1135  *      @ap: ATA channel to manipulate
1136  *      @device: ATA device (numbered from zero) to select
1137  *
1138  *      Use the method defined in the ATA specification to
1139  *      make either device 0, or device 1, active on the
1140  *      ATA channel.  Works with both PIO and MMIO.
1141  *
1142  *      May be used as the dev_select() entry in ata_port_operations.
1143  *
1144  *      LOCKING:
1145  *      caller.
1146  */
1147
1148 void ata_std_dev_select (struct ata_port *ap, unsigned int device)
1149 {
1150         u8 tmp;
1151
1152         if (device == 0)
1153                 tmp = ATA_DEVICE_OBS;
1154         else
1155                 tmp = ATA_DEVICE_OBS | ATA_DEV1;
1156
1157         iowrite8(tmp, ap->ioaddr.device_addr);
1158         ata_pause(ap);          /* needed; also flushes, for mmio */
1159 }
1160
1161 /**
1162  *      ata_dev_select - Select device 0/1 on ATA bus
1163  *      @ap: ATA channel to manipulate
1164  *      @device: ATA device (numbered from zero) to select
1165  *      @wait: non-zero to wait for Status register BSY bit to clear
1166  *      @can_sleep: non-zero if context allows sleeping
1167  *
1168  *      Use the method defined in the ATA specification to
1169  *      make either device 0, or device 1, active on the
1170  *      ATA channel.
1171  *
1172  *      This is a high-level version of ata_std_dev_select(),
1173  *      which additionally provides the services of inserting
1174  *      the proper pauses and status polling, where needed.
1175  *
1176  *      LOCKING:
1177  *      caller.
1178  */
1179
1180 void ata_dev_select(struct ata_port *ap, unsigned int device,
1181                            unsigned int wait, unsigned int can_sleep)
1182 {
1183         if (ata_msg_probe(ap))
1184                 ata_port_printk(ap, KERN_INFO, "ata_dev_select: ENTER, "
1185                                 "device %u, wait %u\n", device, wait);
1186
1187         if (wait)
1188                 ata_wait_idle(ap);
1189
1190         ap->ops->dev_select(ap, device);
1191
1192         if (wait) {
1193                 if (can_sleep && ap->link.device[device].class == ATA_DEV_ATAPI)
1194                         msleep(150);
1195                 ata_wait_idle(ap);
1196         }
1197 }
1198
1199 /**
1200  *      ata_dump_id - IDENTIFY DEVICE info debugging output
1201  *      @id: IDENTIFY DEVICE page to dump
1202  *
1203  *      Dump selected 16-bit words from the given IDENTIFY DEVICE
1204  *      page.
1205  *
1206  *      LOCKING:
1207  *      caller.
1208  */
1209
1210 static inline void ata_dump_id(const u16 *id)
1211 {
1212         DPRINTK("49==0x%04x  "
1213                 "53==0x%04x  "
1214                 "63==0x%04x  "
1215                 "64==0x%04x  "
1216                 "75==0x%04x  \n",
1217                 id[49],
1218                 id[53],
1219                 id[63],
1220                 id[64],
1221                 id[75]);
1222         DPRINTK("80==0x%04x  "
1223                 "81==0x%04x  "
1224                 "82==0x%04x  "
1225                 "83==0x%04x  "
1226                 "84==0x%04x  \n",
1227                 id[80],
1228                 id[81],
1229                 id[82],
1230                 id[83],
1231                 id[84]);
1232         DPRINTK("88==0x%04x  "
1233                 "93==0x%04x\n",
1234                 id[88],
1235                 id[93]);
1236 }
1237
1238 /**
1239  *      ata_id_xfermask - Compute xfermask from the given IDENTIFY data
1240  *      @id: IDENTIFY data to compute xfer mask from
1241  *
1242  *      Compute the xfermask for this device. This is not as trivial
1243  *      as it seems if we must consider early devices correctly.
1244  *
1245  *      FIXME: pre IDE drive timing (do we care ?).
1246  *
1247  *      LOCKING:
1248  *      None.
1249  *
1250  *      RETURNS:
1251  *      Computed xfermask
1252  */
1253 static unsigned int ata_id_xfermask(const u16 *id)
1254 {
1255         unsigned int pio_mask, mwdma_mask, udma_mask;
1256
1257         /* Usual case. Word 53 indicates word 64 is valid */
1258         if (id[ATA_ID_FIELD_VALID] & (1 << 1)) {
1259                 pio_mask = id[ATA_ID_PIO_MODES] & 0x03;
1260                 pio_mask <<= 3;
1261                 pio_mask |= 0x7;
1262         } else {
1263                 /* If word 64 isn't valid then Word 51 high byte holds
1264                  * the PIO timing number for the maximum. Turn it into
1265                  * a mask.
1266                  */
1267                 u8 mode = (id[ATA_ID_OLD_PIO_MODES] >> 8) & 0xFF;
1268                 if (mode < 5)   /* Valid PIO range */
1269                         pio_mask = (2 << mode) - 1;
1270                 else
1271                         pio_mask = 1;
1272
1273                 /* But wait.. there's more. Design your standards by
1274                  * committee and you too can get a free iordy field to
1275                  * process. However its the speeds not the modes that
1276                  * are supported... Note drivers using the timing API
1277                  * will get this right anyway
1278                  */
1279         }
1280
1281         mwdma_mask = id[ATA_ID_MWDMA_MODES] & 0x07;
1282
1283         if (ata_id_is_cfa(id)) {
1284                 /*
1285                  *      Process compact flash extended modes
1286                  */
1287                 int pio = id[163] & 0x7;
1288                 int dma = (id[163] >> 3) & 7;
1289
1290                 if (pio)
1291                         pio_mask |= (1 << 5);
1292                 if (pio > 1)
1293                         pio_mask |= (1 << 6);
1294                 if (dma)
1295                         mwdma_mask |= (1 << 3);
1296                 if (dma > 1)
1297                         mwdma_mask |= (1 << 4);
1298         }
1299
1300         udma_mask = 0;
1301         if (id[ATA_ID_FIELD_VALID] & (1 << 2))
1302                 udma_mask = id[ATA_ID_UDMA_MODES] & 0xff;
1303
1304         return ata_pack_xfermask(pio_mask, mwdma_mask, udma_mask);
1305 }
1306
1307 /**
1308  *      ata_port_queue_task - Queue port_task
1309  *      @ap: The ata_port to queue port_task for
1310  *      @fn: workqueue function to be scheduled
1311  *      @data: data for @fn to use
1312  *      @delay: delay time for workqueue function
1313  *
1314  *      Schedule @fn(@data) for execution after @delay jiffies using
1315  *      port_task.  There is one port_task per port and it's the
1316  *      user(low level driver)'s responsibility to make sure that only
1317  *      one task is active at any given time.
1318  *
1319  *      libata core layer takes care of synchronization between
1320  *      port_task and EH.  ata_port_queue_task() may be ignored for EH
1321  *      synchronization.
1322  *
1323  *      LOCKING:
1324  *      Inherited from caller.
1325  */
1326 void ata_port_queue_task(struct ata_port *ap, work_func_t fn, void *data,
1327                          unsigned long delay)
1328 {
1329         PREPARE_DELAYED_WORK(&ap->port_task, fn);
1330         ap->port_task_data = data;
1331
1332         /* may fail if ata_port_flush_task() in progress */
1333         queue_delayed_work(ata_wq, &ap->port_task, delay);
1334 }
1335
1336 /**
1337  *      ata_port_flush_task - Flush port_task
1338  *      @ap: The ata_port to flush port_task for
1339  *
1340  *      After this function completes, port_task is guranteed not to
1341  *      be running or scheduled.
1342  *
1343  *      LOCKING:
1344  *      Kernel thread context (may sleep)
1345  */
1346 void ata_port_flush_task(struct ata_port *ap)
1347 {
1348         DPRINTK("ENTER\n");
1349
1350         cancel_rearming_delayed_work(&ap->port_task);
1351
1352         if (ata_msg_ctl(ap))
1353                 ata_port_printk(ap, KERN_DEBUG, "%s: EXIT\n", __FUNCTION__);
1354 }
1355
1356 static void ata_qc_complete_internal(struct ata_queued_cmd *qc)
1357 {
1358         struct completion *waiting = qc->private_data;
1359
1360         complete(waiting);
1361 }
1362
1363 /**
1364  *      ata_exec_internal_sg - execute libata internal command
1365  *      @dev: Device to which the command is sent
1366  *      @tf: Taskfile registers for the command and the result
1367  *      @cdb: CDB for packet command
1368  *      @dma_dir: Data tranfer direction of the command
1369  *      @sg: sg list for the data buffer of the command
1370  *      @n_elem: Number of sg entries
1371  *
1372  *      Executes libata internal command with timeout.  @tf contains
1373  *      command on entry and result on return.  Timeout and error
1374  *      conditions are reported via return value.  No recovery action
1375  *      is taken after a command times out.  It's caller's duty to
1376  *      clean up after timeout.
1377  *
1378  *      LOCKING:
1379  *      None.  Should be called with kernel context, might sleep.
1380  *
1381  *      RETURNS:
1382  *      Zero on success, AC_ERR_* mask on failure
1383  */
1384 unsigned ata_exec_internal_sg(struct ata_device *dev,
1385                               struct ata_taskfile *tf, const u8 *cdb,
1386                               int dma_dir, struct scatterlist *sg,
1387                               unsigned int n_elem)
1388 {
1389         struct ata_link *link = dev->link;
1390         struct ata_port *ap = link->ap;
1391         u8 command = tf->command;
1392         struct ata_queued_cmd *qc;
1393         unsigned int tag, preempted_tag;
1394         u32 preempted_sactive, preempted_qc_active;
1395         DECLARE_COMPLETION_ONSTACK(wait);
1396         unsigned long flags;
1397         unsigned int err_mask;
1398         int rc;
1399
1400         spin_lock_irqsave(ap->lock, flags);
1401
1402         /* no internal command while frozen */
1403         if (ap->pflags & ATA_PFLAG_FROZEN) {
1404                 spin_unlock_irqrestore(ap->lock, flags);
1405                 return AC_ERR_SYSTEM;
1406         }
1407
1408         /* initialize internal qc */
1409
1410         /* XXX: Tag 0 is used for drivers with legacy EH as some
1411          * drivers choke if any other tag is given.  This breaks
1412          * ata_tag_internal() test for those drivers.  Don't use new
1413          * EH stuff without converting to it.
1414          */
1415         if (ap->ops->error_handler)
1416                 tag = ATA_TAG_INTERNAL;
1417         else
1418                 tag = 0;
1419
1420         if (test_and_set_bit(tag, &ap->qc_allocated))
1421                 BUG();
1422         qc = __ata_qc_from_tag(ap, tag);
1423
1424         qc->tag = tag;
1425         qc->scsicmd = NULL;
1426         qc->ap = ap;
1427         qc->dev = dev;
1428         ata_qc_reinit(qc);
1429
1430         preempted_tag = link->active_tag;
1431         preempted_sactive = link->sactive;
1432         preempted_qc_active = ap->qc_active;
1433         link->active_tag = ATA_TAG_POISON;
1434         link->sactive = 0;
1435         ap->qc_active = 0;
1436
1437         /* prepare & issue qc */
1438         qc->tf = *tf;
1439         if (cdb)
1440                 memcpy(qc->cdb, cdb, ATAPI_CDB_LEN);
1441         qc->flags |= ATA_QCFLAG_RESULT_TF;
1442         qc->dma_dir = dma_dir;
1443         if (dma_dir != DMA_NONE) {
1444                 unsigned int i, buflen = 0;
1445
1446                 for (i = 0; i < n_elem; i++)
1447                         buflen += sg[i].length;
1448
1449                 ata_sg_init(qc, sg, n_elem);
1450                 qc->nbytes = buflen;
1451         }
1452
1453         qc->private_data = &wait;
1454         qc->complete_fn = ata_qc_complete_internal;
1455
1456         ata_qc_issue(qc);
1457
1458         spin_unlock_irqrestore(ap->lock, flags);
1459
1460         rc = wait_for_completion_timeout(&wait, ata_probe_timeout);
1461
1462         ata_port_flush_task(ap);
1463
1464         if (!rc) {
1465                 spin_lock_irqsave(ap->lock, flags);
1466
1467                 /* We're racing with irq here.  If we lose, the
1468                  * following test prevents us from completing the qc
1469                  * twice.  If we win, the port is frozen and will be
1470                  * cleaned up by ->post_internal_cmd().
1471                  */
1472                 if (qc->flags & ATA_QCFLAG_ACTIVE) {
1473                         qc->err_mask |= AC_ERR_TIMEOUT;
1474
1475                         if (ap->ops->error_handler)
1476                                 ata_port_freeze(ap);
1477                         else
1478                                 ata_qc_complete(qc);
1479
1480                         if (ata_msg_warn(ap))
1481                                 ata_dev_printk(dev, KERN_WARNING,
1482                                         "qc timeout (cmd 0x%x)\n", command);
1483                 }
1484
1485                 spin_unlock_irqrestore(ap->lock, flags);
1486         }
1487
1488         /* do post_internal_cmd */
1489         if (ap->ops->post_internal_cmd)
1490                 ap->ops->post_internal_cmd(qc);
1491
1492         /* perform minimal error analysis */
1493         if (qc->flags & ATA_QCFLAG_FAILED) {
1494                 if (qc->result_tf.command & (ATA_ERR | ATA_DF))
1495                         qc->err_mask |= AC_ERR_DEV;
1496
1497                 if (!qc->err_mask)
1498                         qc->err_mask |= AC_ERR_OTHER;
1499
1500                 if (qc->err_mask & ~AC_ERR_OTHER)
1501                         qc->err_mask &= ~AC_ERR_OTHER;
1502         }
1503
1504         /* finish up */
1505         spin_lock_irqsave(ap->lock, flags);
1506
1507         *tf = qc->result_tf;
1508         err_mask = qc->err_mask;
1509
1510         ata_qc_free(qc);
1511         link->active_tag = preempted_tag;
1512         link->sactive = preempted_sactive;
1513         ap->qc_active = preempted_qc_active;
1514
1515         /* XXX - Some LLDDs (sata_mv) disable port on command failure.
1516          * Until those drivers are fixed, we detect the condition
1517          * here, fail the command with AC_ERR_SYSTEM and reenable the
1518          * port.
1519          *
1520          * Note that this doesn't change any behavior as internal
1521          * command failure results in disabling the device in the
1522          * higher layer for LLDDs without new reset/EH callbacks.
1523          *
1524          * Kill the following code as soon as those drivers are fixed.
1525          */
1526         if (ap->flags & ATA_FLAG_DISABLED) {
1527                 err_mask |= AC_ERR_SYSTEM;
1528                 ata_port_probe(ap);
1529         }
1530
1531         spin_unlock_irqrestore(ap->lock, flags);
1532
1533         return err_mask;
1534 }
1535
1536 /**
1537  *      ata_exec_internal - execute libata internal command
1538  *      @dev: Device to which the command is sent
1539  *      @tf: Taskfile registers for the command and the result
1540  *      @cdb: CDB for packet command
1541  *      @dma_dir: Data tranfer direction of the command
1542  *      @buf: Data buffer of the command
1543  *      @buflen: Length of data buffer
1544  *
1545  *      Wrapper around ata_exec_internal_sg() which takes simple
1546  *      buffer instead of sg list.
1547  *
1548  *      LOCKING:
1549  *      None.  Should be called with kernel context, might sleep.
1550  *
1551  *      RETURNS:
1552  *      Zero on success, AC_ERR_* mask on failure
1553  */
1554 unsigned ata_exec_internal(struct ata_device *dev,
1555                            struct ata_taskfile *tf, const u8 *cdb,
1556                            int dma_dir, void *buf, unsigned int buflen)
1557 {
1558         struct scatterlist *psg = NULL, sg;
1559         unsigned int n_elem = 0;
1560
1561         if (dma_dir != DMA_NONE) {
1562                 WARN_ON(!buf);
1563                 sg_init_one(&sg, buf, buflen);
1564                 psg = &sg;
1565                 n_elem++;
1566         }
1567
1568         return ata_exec_internal_sg(dev, tf, cdb, dma_dir, psg, n_elem);
1569 }
1570
1571 /**
1572  *      ata_do_simple_cmd - execute simple internal command
1573  *      @dev: Device to which the command is sent
1574  *      @cmd: Opcode to execute
1575  *
1576  *      Execute a 'simple' command, that only consists of the opcode
1577  *      'cmd' itself, without filling any other registers
1578  *
1579  *      LOCKING:
1580  *      Kernel thread context (may sleep).
1581  *
1582  *      RETURNS:
1583  *      Zero on success, AC_ERR_* mask on failure
1584  */
1585 unsigned int ata_do_simple_cmd(struct ata_device *dev, u8 cmd)
1586 {
1587         struct ata_taskfile tf;
1588
1589         ata_tf_init(dev, &tf);
1590
1591         tf.command = cmd;
1592         tf.flags |= ATA_TFLAG_DEVICE;
1593         tf.protocol = ATA_PROT_NODATA;
1594
1595         return ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0);
1596 }
1597
1598 /**
1599  *      ata_pio_need_iordy      -       check if iordy needed
1600  *      @adev: ATA device
1601  *
1602  *      Check if the current speed of the device requires IORDY. Used
1603  *      by various controllers for chip configuration.
1604  */
1605
1606 unsigned int ata_pio_need_iordy(const struct ata_device *adev)
1607 {
1608         /* Controller doesn't support  IORDY. Probably a pointless check
1609            as the caller should know this */
1610         if (adev->link->ap->flags & ATA_FLAG_NO_IORDY)
1611                 return 0;
1612         /* PIO3 and higher it is mandatory */
1613         if (adev->pio_mode > XFER_PIO_2)
1614                 return 1;
1615         /* We turn it on when possible */
1616         if (ata_id_has_iordy(adev->id))
1617                 return 1;
1618         return 0;
1619 }
1620
1621 /**
1622  *      ata_pio_mask_no_iordy   -       Return the non IORDY mask
1623  *      @adev: ATA device
1624  *
1625  *      Compute the highest mode possible if we are not using iordy. Return
1626  *      -1 if no iordy mode is available.
1627  */
1628
1629 static u32 ata_pio_mask_no_iordy(const struct ata_device *adev)
1630 {
1631         /* If we have no drive specific rule, then PIO 2 is non IORDY */
1632         if (adev->id[ATA_ID_FIELD_VALID] & 2) { /* EIDE */
1633                 u16 pio = adev->id[ATA_ID_EIDE_PIO];
1634                 /* Is the speed faster than the drive allows non IORDY ? */
1635                 if (pio) {
1636                         /* This is cycle times not frequency - watch the logic! */
1637                         if (pio > 240)  /* PIO2 is 240nS per cycle */
1638                                 return 3 << ATA_SHIFT_PIO;
1639                         return 7 << ATA_SHIFT_PIO;
1640                 }
1641         }
1642         return 3 << ATA_SHIFT_PIO;
1643 }
1644
1645 /**
1646  *      ata_dev_read_id - Read ID data from the specified device
1647  *      @dev: target device
1648  *      @p_class: pointer to class of the target device (may be changed)
1649  *      @flags: ATA_READID_* flags
1650  *      @id: buffer to read IDENTIFY data into
1651  *
1652  *      Read ID data from the specified device.  ATA_CMD_ID_ATA is
1653  *      performed on ATA devices and ATA_CMD_ID_ATAPI on ATAPI
1654  *      devices.  This function also issues ATA_CMD_INIT_DEV_PARAMS
1655  *      for pre-ATA4 drives.
1656  *
1657  *      FIXME: ATA_CMD_ID_ATA is optional for early drives and right
1658  *      now we abort if we hit that case. 
1659  *
1660  *      LOCKING:
1661  *      Kernel thread context (may sleep)
1662  *
1663  *      RETURNS:
1664  *      0 on success, -errno otherwise.
1665  */
1666 int ata_dev_read_id(struct ata_device *dev, unsigned int *p_class,
1667                     unsigned int flags, u16 *id)
1668 {
1669         struct ata_port *ap = dev->link->ap;
1670         unsigned int class = *p_class;
1671         struct ata_taskfile tf;
1672         unsigned int err_mask = 0;
1673         const char *reason;
1674         int may_fallback = 1, tried_spinup = 0;
1675         int rc;
1676
1677         if (ata_msg_ctl(ap))
1678                 ata_dev_printk(dev, KERN_DEBUG, "%s: ENTER\n", __FUNCTION__);
1679
1680         ata_dev_select(ap, dev->devno, 1, 1); /* select device 0/1 */
1681  retry:
1682         ata_tf_init(dev, &tf);
1683
1684         switch (class) {
1685         case ATA_DEV_ATA:
1686                 tf.command = ATA_CMD_ID_ATA;
1687                 break;
1688         case ATA_DEV_ATAPI:
1689                 tf.command = ATA_CMD_ID_ATAPI;
1690                 break;
1691         default:
1692                 rc = -ENODEV;
1693                 reason = "unsupported class";
1694                 goto err_out;
1695         }
1696
1697         tf.protocol = ATA_PROT_PIO;
1698
1699         /* Some devices choke if TF registers contain garbage.  Make
1700          * sure those are properly initialized.
1701          */
1702         tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
1703
1704         /* Device presence detection is unreliable on some
1705          * controllers.  Always poll IDENTIFY if available.
1706          */
1707         tf.flags |= ATA_TFLAG_POLLING;
1708
1709         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_FROM_DEVICE,
1710                                      id, sizeof(id[0]) * ATA_ID_WORDS);
1711         if (err_mask) {
1712                 if (err_mask & AC_ERR_NODEV_HINT) {
1713                         DPRINTK("ata%u.%d: NODEV after polling detection\n",
1714                                 ap->print_id, dev->devno);
1715                         return -ENOENT;
1716                 }
1717
1718                 /* Device or controller might have reported the wrong
1719                  * device class.  Give a shot at the other IDENTIFY if
1720                  * the current one is aborted by the device.
1721                  */
1722                 if (may_fallback &&
1723                     (err_mask == AC_ERR_DEV) && (tf.feature & ATA_ABORTED)) {
1724                         may_fallback = 0;
1725
1726                         if (class == ATA_DEV_ATA)
1727                                 class = ATA_DEV_ATAPI;
1728                         else
1729                                 class = ATA_DEV_ATA;
1730                         goto retry;
1731                 }
1732
1733                 rc = -EIO;
1734                 reason = "I/O error";
1735                 goto err_out;
1736         }
1737
1738         /* Falling back doesn't make sense if ID data was read
1739          * successfully at least once.
1740          */
1741         may_fallback = 0;
1742
1743         swap_buf_le16(id, ATA_ID_WORDS);
1744
1745         /* sanity check */
1746         rc = -EINVAL;
1747         reason = "device reports invalid type";
1748
1749         if (class == ATA_DEV_ATA) {
1750                 if (!ata_id_is_ata(id) && !ata_id_is_cfa(id))
1751                         goto err_out;
1752         } else {
1753                 if (ata_id_is_ata(id))
1754                         goto err_out;
1755         }
1756
1757         if (!tried_spinup && (id[2] == 0x37c8 || id[2] == 0x738c)) {
1758                 tried_spinup = 1;
1759                 /*
1760                  * Drive powered-up in standby mode, and requires a specific
1761                  * SET_FEATURES spin-up subcommand before it will accept
1762                  * anything other than the original IDENTIFY command.
1763                  */
1764                 ata_tf_init(dev, &tf);
1765                 tf.command = ATA_CMD_SET_FEATURES;
1766                 tf.feature = SETFEATURES_SPINUP;
1767                 tf.protocol = ATA_PROT_NODATA;
1768                 tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
1769                 err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0);
1770                 if (err_mask && id[2] != 0x738c) {
1771                         rc = -EIO;
1772                         reason = "SPINUP failed";
1773                         goto err_out;
1774                 }
1775                 /*
1776                  * If the drive initially returned incomplete IDENTIFY info,
1777                  * we now must reissue the IDENTIFY command.
1778                  */
1779                 if (id[2] == 0x37c8)
1780                         goto retry;
1781         }
1782
1783         if ((flags & ATA_READID_POSTRESET) && class == ATA_DEV_ATA) {
1784                 /*
1785                  * The exact sequence expected by certain pre-ATA4 drives is:
1786                  * SRST RESET
1787                  * IDENTIFY (optional in early ATA)
1788                  * INITIALIZE DEVICE PARAMETERS (later IDE and ATA)
1789                  * anything else..
1790                  * Some drives were very specific about that exact sequence.
1791                  *
1792                  * Note that ATA4 says lba is mandatory so the second check
1793                  * shoud never trigger.
1794                  */
1795                 if (ata_id_major_version(id) < 4 || !ata_id_has_lba(id)) {
1796                         err_mask = ata_dev_init_params(dev, id[3], id[6]);
1797                         if (err_mask) {
1798                                 rc = -EIO;
1799                                 reason = "INIT_DEV_PARAMS failed";
1800                                 goto err_out;
1801                         }
1802
1803                         /* current CHS translation info (id[53-58]) might be
1804                          * changed. reread the identify device info.
1805                          */
1806                         flags &= ~ATA_READID_POSTRESET;
1807                         goto retry;
1808                 }
1809         }
1810
1811         *p_class = class;
1812
1813         return 0;
1814
1815  err_out:
1816         if (ata_msg_warn(ap))
1817                 ata_dev_printk(dev, KERN_WARNING, "failed to IDENTIFY "
1818                                "(%s, err_mask=0x%x)\n", reason, err_mask);
1819         return rc;
1820 }
1821
1822 static inline u8 ata_dev_knobble(struct ata_device *dev)
1823 {
1824         struct ata_port *ap = dev->link->ap;
1825         return ((ap->cbl == ATA_CBL_SATA) && (!ata_id_is_sata(dev->id)));
1826 }
1827
1828 static void ata_dev_config_ncq(struct ata_device *dev,
1829                                char *desc, size_t desc_sz)
1830 {
1831         struct ata_port *ap = dev->link->ap;
1832         int hdepth = 0, ddepth = ata_id_queue_depth(dev->id);
1833
1834         if (!ata_id_has_ncq(dev->id)) {
1835                 desc[0] = '\0';
1836                 return;
1837         }
1838         if (dev->horkage & ATA_HORKAGE_NONCQ) {
1839                 snprintf(desc, desc_sz, "NCQ (not used)");
1840                 return;
1841         }
1842         if (ap->flags & ATA_FLAG_NCQ) {
1843                 hdepth = min(ap->scsi_host->can_queue, ATA_MAX_QUEUE - 1);
1844                 dev->flags |= ATA_DFLAG_NCQ;
1845         }
1846
1847         if (hdepth >= ddepth)
1848                 snprintf(desc, desc_sz, "NCQ (depth %d)", ddepth);
1849         else
1850                 snprintf(desc, desc_sz, "NCQ (depth %d/%d)", hdepth, ddepth);
1851 }
1852
1853 /**
1854  *      ata_dev_configure - Configure the specified ATA/ATAPI device
1855  *      @dev: Target device to configure
1856  *
1857  *      Configure @dev according to @dev->id.  Generic and low-level
1858  *      driver specific fixups are also applied.
1859  *
1860  *      LOCKING:
1861  *      Kernel thread context (may sleep)
1862  *
1863  *      RETURNS:
1864  *      0 on success, -errno otherwise
1865  */
1866 int ata_dev_configure(struct ata_device *dev)
1867 {
1868         struct ata_port *ap = dev->link->ap;
1869         struct ata_eh_context *ehc = &dev->link->eh_context;
1870         int print_info = ehc->i.flags & ATA_EHI_PRINTINFO;
1871         const u16 *id = dev->id;
1872         unsigned int xfer_mask;
1873         char revbuf[7];         /* XYZ-99\0 */
1874         char fwrevbuf[ATA_ID_FW_REV_LEN+1];
1875         char modelbuf[ATA_ID_PROD_LEN+1];
1876         int rc;
1877
1878         if (!ata_dev_enabled(dev) && ata_msg_info(ap)) {
1879                 ata_dev_printk(dev, KERN_INFO, "%s: ENTER/EXIT -- nodev\n",
1880                                __FUNCTION__);
1881                 return 0;
1882         }
1883
1884         if (ata_msg_probe(ap))
1885                 ata_dev_printk(dev, KERN_DEBUG, "%s: ENTER\n", __FUNCTION__);
1886
1887         /* set horkage */
1888         dev->horkage |= ata_dev_blacklisted(dev);
1889
1890         /* let ACPI work its magic */
1891         rc = ata_acpi_on_devcfg(dev);
1892         if (rc)
1893                 return rc;
1894
1895         /* massage HPA, do it early as it might change IDENTIFY data */
1896         rc = ata_hpa_resize(dev);
1897         if (rc)
1898                 return rc;
1899
1900         /* print device capabilities */
1901         if (ata_msg_probe(ap))
1902                 ata_dev_printk(dev, KERN_DEBUG,
1903                                "%s: cfg 49:%04x 82:%04x 83:%04x 84:%04x "
1904                                "85:%04x 86:%04x 87:%04x 88:%04x\n",
1905                                __FUNCTION__,
1906                                id[49], id[82], id[83], id[84],
1907                                id[85], id[86], id[87], id[88]);
1908
1909         /* initialize to-be-configured parameters */
1910         dev->flags &= ~ATA_DFLAG_CFG_MASK;
1911         dev->max_sectors = 0;
1912         dev->cdb_len = 0;
1913         dev->n_sectors = 0;
1914         dev->cylinders = 0;
1915         dev->heads = 0;
1916         dev->sectors = 0;
1917
1918         /*
1919          * common ATA, ATAPI feature tests
1920          */
1921
1922         /* find max transfer mode; for printk only */
1923         xfer_mask = ata_id_xfermask(id);
1924
1925         if (ata_msg_probe(ap))
1926                 ata_dump_id(id);
1927
1928         /* SCSI only uses 4-char revisions, dump full 8 chars from ATA */
1929         ata_id_c_string(dev->id, fwrevbuf, ATA_ID_FW_REV,
1930                         sizeof(fwrevbuf));
1931
1932         ata_id_c_string(dev->id, modelbuf, ATA_ID_PROD,
1933                         sizeof(modelbuf));
1934
1935         /* ATA-specific feature tests */
1936         if (dev->class == ATA_DEV_ATA) {
1937                 if (ata_id_is_cfa(id)) {
1938                         if (id[162] & 1) /* CPRM may make this media unusable */
1939                                 ata_dev_printk(dev, KERN_WARNING,
1940                                                "supports DRM functions and may "
1941                                                "not be fully accessable.\n");
1942                         snprintf(revbuf, 7, "CFA");
1943                 }
1944                 else
1945                         snprintf(revbuf, 7, "ATA-%d",  ata_id_major_version(id));
1946
1947                 dev->n_sectors = ata_id_n_sectors(id);
1948
1949                 if (dev->id[59] & 0x100)
1950                         dev->multi_count = dev->id[59] & 0xff;
1951
1952                 if (ata_id_has_lba(id)) {
1953                         const char *lba_desc;
1954                         char ncq_desc[20];
1955
1956                         lba_desc = "LBA";
1957                         dev->flags |= ATA_DFLAG_LBA;
1958                         if (ata_id_has_lba48(id)) {
1959                                 dev->flags |= ATA_DFLAG_LBA48;
1960                                 lba_desc = "LBA48";
1961
1962                                 if (dev->n_sectors >= (1UL << 28) &&
1963                                     ata_id_has_flush_ext(id))
1964                                         dev->flags |= ATA_DFLAG_FLUSH_EXT;
1965                         }
1966
1967                         /* config NCQ */
1968                         ata_dev_config_ncq(dev, ncq_desc, sizeof(ncq_desc));
1969
1970                         /* print device info to dmesg */
1971                         if (ata_msg_drv(ap) && print_info) {
1972                                 ata_dev_printk(dev, KERN_INFO,
1973                                         "%s: %s, %s, max %s\n",
1974                                         revbuf, modelbuf, fwrevbuf,
1975                                         ata_mode_string(xfer_mask));
1976                                 ata_dev_printk(dev, KERN_INFO,
1977                                         "%Lu sectors, multi %u: %s %s\n",
1978                                         (unsigned long long)dev->n_sectors,
1979                                         dev->multi_count, lba_desc, ncq_desc);
1980                         }
1981                 } else {
1982                         /* CHS */
1983
1984                         /* Default translation */
1985                         dev->cylinders  = id[1];
1986                         dev->heads      = id[3];
1987                         dev->sectors    = id[6];
1988
1989                         if (ata_id_current_chs_valid(id)) {
1990                                 /* Current CHS translation is valid. */
1991                                 dev->cylinders = id[54];
1992                                 dev->heads     = id[55];
1993                                 dev->sectors   = id[56];
1994                         }
1995
1996                         /* print device info to dmesg */
1997                         if (ata_msg_drv(ap) && print_info) {
1998                                 ata_dev_printk(dev, KERN_INFO,
1999                                         "%s: %s, %s, max %s\n",
2000                                         revbuf, modelbuf, fwrevbuf,
2001                                         ata_mode_string(xfer_mask));
2002                                 ata_dev_printk(dev, KERN_INFO,
2003                                         "%Lu sectors, multi %u, CHS %u/%u/%u\n",
2004                                         (unsigned long long)dev->n_sectors,
2005                                         dev->multi_count, dev->cylinders,
2006                                         dev->heads, dev->sectors);
2007                         }
2008                 }
2009
2010                 dev->cdb_len = 16;
2011         }
2012
2013         /* ATAPI-specific feature tests */
2014         else if (dev->class == ATA_DEV_ATAPI) {
2015                 char *cdb_intr_string = "";
2016
2017                 rc = atapi_cdb_len(id);
2018                 if ((rc < 12) || (rc > ATAPI_CDB_LEN)) {
2019                         if (ata_msg_warn(ap))
2020                                 ata_dev_printk(dev, KERN_WARNING,
2021                                                "unsupported CDB len\n");
2022                         rc = -EINVAL;
2023                         goto err_out_nosup;
2024                 }
2025                 dev->cdb_len = (unsigned int) rc;
2026
2027                 /*
2028                  * check to see if this ATAPI device supports
2029                  * Asynchronous Notification
2030                  */
2031                 if ((ap->flags & ATA_FLAG_AN) && ata_id_has_AN(id)) {
2032                         int err;
2033                         /* issue SET feature command to turn this on */
2034                         err = ata_dev_set_AN(dev, SETFEATURES_SATA_ENABLE);
2035                         if (err)
2036                                 ata_dev_printk(dev, KERN_ERR,
2037                                                 "unable to set AN, err %x\n",
2038                                                 err);
2039                         else
2040                                 dev->flags |= ATA_DFLAG_AN;
2041                 }
2042
2043                 if (ata_id_cdb_intr(dev->id)) {
2044                         dev->flags |= ATA_DFLAG_CDB_INTR;
2045                         cdb_intr_string = ", CDB intr";
2046                 }
2047
2048                 /* print device info to dmesg */
2049                 if (ata_msg_drv(ap) && print_info)
2050                         ata_dev_printk(dev, KERN_INFO,
2051                                        "ATAPI: %s, %s, max %s%s\n",
2052                                        modelbuf, fwrevbuf,
2053                                        ata_mode_string(xfer_mask),
2054                                        cdb_intr_string);
2055         }
2056
2057         /* determine max_sectors */
2058         dev->max_sectors = ATA_MAX_SECTORS;
2059         if (dev->flags & ATA_DFLAG_LBA48)
2060                 dev->max_sectors = ATA_MAX_SECTORS_LBA48;
2061
2062         if (dev->horkage & ATA_HORKAGE_DIAGNOSTIC) {
2063                 /* Let the user know. We don't want to disallow opens for
2064                    rescue purposes, or in case the vendor is just a blithering
2065                    idiot */
2066                 if (print_info) {
2067                         ata_dev_printk(dev, KERN_WARNING,
2068 "Drive reports diagnostics failure. This may indicate a drive\n");
2069                         ata_dev_printk(dev, KERN_WARNING,
2070 "fault or invalid emulation. Contact drive vendor for information.\n");
2071                 }
2072         }
2073
2074         /* limit bridge transfers to udma5, 200 sectors */
2075         if (ata_dev_knobble(dev)) {
2076                 if (ata_msg_drv(ap) && print_info)
2077                         ata_dev_printk(dev, KERN_INFO,
2078                                        "applying bridge limits\n");
2079                 dev->udma_mask &= ATA_UDMA5;
2080                 dev->max_sectors = ATA_MAX_SECTORS;
2081         }
2082
2083         if (dev->horkage & ATA_HORKAGE_MAX_SEC_128)
2084                 dev->max_sectors = min_t(unsigned int, ATA_MAX_SECTORS_128,
2085                                          dev->max_sectors);
2086
2087         if (ap->ops->dev_config)
2088                 ap->ops->dev_config(dev);
2089
2090         if (ata_msg_probe(ap))
2091                 ata_dev_printk(dev, KERN_DEBUG, "%s: EXIT, drv_stat = 0x%x\n",
2092                         __FUNCTION__, ata_chk_status(ap));
2093         return 0;
2094
2095 err_out_nosup:
2096         if (ata_msg_probe(ap))
2097                 ata_dev_printk(dev, KERN_DEBUG,
2098                                "%s: EXIT, err\n", __FUNCTION__);
2099         return rc;
2100 }
2101
2102 /**
2103  *      ata_cable_40wire        -       return 40 wire cable type
2104  *      @ap: port
2105  *
2106  *      Helper method for drivers which want to hardwire 40 wire cable
2107  *      detection.
2108  */
2109
2110 int ata_cable_40wire(struct ata_port *ap)
2111 {
2112         return ATA_CBL_PATA40;
2113 }
2114
2115 /**
2116  *      ata_cable_80wire        -       return 80 wire cable type
2117  *      @ap: port
2118  *
2119  *      Helper method for drivers which want to hardwire 80 wire cable
2120  *      detection.
2121  */
2122
2123 int ata_cable_80wire(struct ata_port *ap)
2124 {
2125         return ATA_CBL_PATA80;
2126 }
2127
2128 /**
2129  *      ata_cable_unknown       -       return unknown PATA cable.
2130  *      @ap: port
2131  *
2132  *      Helper method for drivers which have no PATA cable detection.
2133  */
2134
2135 int ata_cable_unknown(struct ata_port *ap)
2136 {
2137         return ATA_CBL_PATA_UNK;
2138 }
2139
2140 /**
2141  *      ata_cable_sata  -       return SATA cable type
2142  *      @ap: port
2143  *
2144  *      Helper method for drivers which have SATA cables
2145  */
2146
2147 int ata_cable_sata(struct ata_port *ap)
2148 {
2149         return ATA_CBL_SATA;
2150 }
2151
2152 /**
2153  *      ata_bus_probe - Reset and probe ATA bus
2154  *      @ap: Bus to probe
2155  *
2156  *      Master ATA bus probing function.  Initiates a hardware-dependent
2157  *      bus reset, then attempts to identify any devices found on
2158  *      the bus.
2159  *
2160  *      LOCKING:
2161  *      PCI/etc. bus probe sem.
2162  *
2163  *      RETURNS:
2164  *      Zero on success, negative errno otherwise.
2165  */
2166
2167 int ata_bus_probe(struct ata_port *ap)
2168 {
2169         unsigned int classes[ATA_MAX_DEVICES];
2170         int tries[ATA_MAX_DEVICES];
2171         int rc;
2172         struct ata_device *dev;
2173
2174         ata_port_probe(ap);
2175
2176         ata_link_for_each_dev(dev, &ap->link)
2177                 tries[dev->devno] = ATA_PROBE_MAX_TRIES;
2178
2179  retry:
2180         /* reset and determine device classes */
2181         ap->ops->phy_reset(ap);
2182
2183         ata_link_for_each_dev(dev, &ap->link) {
2184                 if (!(ap->flags & ATA_FLAG_DISABLED) &&
2185                     dev->class != ATA_DEV_UNKNOWN)
2186                         classes[dev->devno] = dev->class;
2187                 else
2188                         classes[dev->devno] = ATA_DEV_NONE;
2189
2190                 dev->class = ATA_DEV_UNKNOWN;
2191         }
2192
2193         ata_port_probe(ap);
2194
2195         /* after the reset the device state is PIO 0 and the controller
2196            state is undefined. Record the mode */
2197
2198         ata_link_for_each_dev(dev, &ap->link)
2199                 dev->pio_mode = XFER_PIO_0;
2200
2201         /* read IDENTIFY page and configure devices. We have to do the identify
2202            specific sequence bass-ackwards so that PDIAG- is released by
2203            the slave device */
2204
2205         ata_link_for_each_dev(dev, &ap->link) {
2206                 if (tries[dev->devno])
2207                         dev->class = classes[dev->devno];
2208
2209                 if (!ata_dev_enabled(dev))
2210                         continue;
2211
2212                 rc = ata_dev_read_id(dev, &dev->class, ATA_READID_POSTRESET,
2213                                      dev->id);
2214                 if (rc)
2215                         goto fail;
2216         }
2217
2218         /* Now ask for the cable type as PDIAG- should have been released */
2219         if (ap->ops->cable_detect)
2220                 ap->cbl = ap->ops->cable_detect(ap);
2221
2222         /* We may have SATA bridge glue hiding here irrespective of the
2223            reported cable types and sensed types */
2224         ata_link_for_each_dev(dev, &ap->link) {
2225                 if (!ata_dev_enabled(dev))
2226                         continue;
2227                 /* SATA drives indicate we have a bridge. We don't know which
2228                    end of the link the bridge is which is a problem */
2229                 if (ata_id_is_sata(dev->id))
2230                         ap->cbl = ATA_CBL_SATA;
2231         }
2232
2233         /* After the identify sequence we can now set up the devices. We do
2234            this in the normal order so that the user doesn't get confused */
2235
2236         ata_link_for_each_dev(dev, &ap->link) {
2237                 if (!ata_dev_enabled(dev))
2238                         continue;
2239
2240                 ap->link.eh_context.i.flags |= ATA_EHI_PRINTINFO;
2241                 rc = ata_dev_configure(dev);
2242                 ap->link.eh_context.i.flags &= ~ATA_EHI_PRINTINFO;
2243                 if (rc)
2244                         goto fail;
2245         }
2246
2247         /* configure transfer mode */
2248         rc = ata_set_mode(&ap->link, &dev);
2249         if (rc)
2250                 goto fail;
2251
2252         ata_link_for_each_dev(dev, &ap->link)
2253                 if (ata_dev_enabled(dev))
2254                         return 0;
2255
2256         /* no device present, disable port */
2257         ata_port_disable(ap);
2258         return -ENODEV;
2259
2260  fail:
2261         tries[dev->devno]--;
2262
2263         switch (rc) {
2264         case -EINVAL:
2265                 /* eeek, something went very wrong, give up */
2266                 tries[dev->devno] = 0;
2267                 break;
2268
2269         case -ENODEV:
2270                 /* give it just one more chance */
2271                 tries[dev->devno] = min(tries[dev->devno], 1);
2272         case -EIO:
2273                 if (tries[dev->devno] == 1) {
2274                         /* This is the last chance, better to slow
2275                          * down than lose it.
2276                          */
2277                         sata_down_spd_limit(&ap->link);
2278                         ata_down_xfermask_limit(dev, ATA_DNXFER_PIO);
2279                 }
2280         }
2281
2282         if (!tries[dev->devno])
2283                 ata_dev_disable(dev);
2284
2285         goto retry;
2286 }
2287
2288 /**
2289  *      ata_port_probe - Mark port as enabled
2290  *      @ap: Port for which we indicate enablement
2291  *
2292  *      Modify @ap data structure such that the system
2293  *      thinks that the entire port is enabled.
2294  *
2295  *      LOCKING: host lock, or some other form of
2296  *      serialization.
2297  */
2298
2299 void ata_port_probe(struct ata_port *ap)
2300 {
2301         ap->flags &= ~ATA_FLAG_DISABLED;
2302 }
2303
2304 /**
2305  *      sata_print_link_status - Print SATA link status
2306  *      @link: SATA link to printk link status about
2307  *
2308  *      This function prints link speed and status of a SATA link.
2309  *
2310  *      LOCKING:
2311  *      None.
2312  */
2313 void sata_print_link_status(struct ata_link *link)
2314 {
2315         u32 sstatus, scontrol, tmp;
2316
2317         if (sata_scr_read(link, SCR_STATUS, &sstatus))
2318                 return;
2319         sata_scr_read(link, SCR_CONTROL, &scontrol);
2320
2321         if (ata_link_online(link)) {
2322                 tmp = (sstatus >> 4) & 0xf;
2323                 ata_link_printk(link, KERN_INFO,
2324                                 "SATA link up %s (SStatus %X SControl %X)\n",
2325                                 sata_spd_string(tmp), sstatus, scontrol);
2326         } else {
2327                 ata_link_printk(link, KERN_INFO,
2328                                 "SATA link down (SStatus %X SControl %X)\n",
2329                                 sstatus, scontrol);
2330         }
2331 }
2332
2333 /**
2334  *      __sata_phy_reset - Wake/reset a low-level SATA PHY
2335  *      @ap: SATA port associated with target SATA PHY.
2336  *
2337  *      This function issues commands to standard SATA Sxxx
2338  *      PHY registers, to wake up the phy (and device), and
2339  *      clear any reset condition.
2340  *
2341  *      LOCKING:
2342  *      PCI/etc. bus probe sem.
2343  *
2344  */
2345 void __sata_phy_reset(struct ata_port *ap)
2346 {
2347         struct ata_link *link = &ap->link;
2348         unsigned long timeout = jiffies + (HZ * 5);
2349         u32 sstatus;
2350
2351         if (ap->flags & ATA_FLAG_SATA_RESET) {
2352                 /* issue phy wake/reset */
2353                 sata_scr_write_flush(link, SCR_CONTROL, 0x301);
2354                 /* Couldn't find anything in SATA I/II specs, but
2355                  * AHCI-1.1 10.4.2 says at least 1 ms. */
2356                 mdelay(1);
2357         }
2358         /* phy wake/clear reset */
2359         sata_scr_write_flush(link, SCR_CONTROL, 0x300);
2360
2361         /* wait for phy to become ready, if necessary */
2362         do {
2363                 msleep(200);
2364                 sata_scr_read(link, SCR_STATUS, &sstatus);
2365                 if ((sstatus & 0xf) != 1)
2366                         break;
2367         } while (time_before(jiffies, timeout));
2368
2369         /* print link status */
2370         sata_print_link_status(link);
2371
2372         /* TODO: phy layer with polling, timeouts, etc. */
2373         if (!ata_link_offline(link))
2374                 ata_port_probe(ap);
2375         else
2376                 ata_port_disable(ap);
2377
2378         if (ap->flags & ATA_FLAG_DISABLED)
2379                 return;
2380
2381         if (ata_busy_sleep(ap, ATA_TMOUT_BOOT_QUICK, ATA_TMOUT_BOOT)) {
2382                 ata_port_disable(ap);
2383                 return;
2384         }
2385
2386         ap->cbl = ATA_CBL_SATA;
2387 }
2388
2389 /**
2390  *      sata_phy_reset - Reset SATA bus.
2391  *      @ap: SATA port associated with target SATA PHY.
2392  *
2393  *      This function resets the SATA bus, and then probes
2394  *      the bus for devices.
2395  *
2396  *      LOCKING:
2397  *      PCI/etc. bus probe sem.
2398  *
2399  */
2400 void sata_phy_reset(struct ata_port *ap)
2401 {
2402         __sata_phy_reset(ap);
2403         if (ap->flags & ATA_FLAG_DISABLED)
2404                 return;
2405         ata_bus_reset(ap);
2406 }
2407
2408 /**
2409  *      ata_dev_pair            -       return other device on cable
2410  *      @adev: device
2411  *
2412  *      Obtain the other device on the same cable, or if none is
2413  *      present NULL is returned
2414  */
2415
2416 struct ata_device *ata_dev_pair(struct ata_device *adev)
2417 {
2418         struct ata_link *link = adev->link;
2419         struct ata_device *pair = &link->device[1 - adev->devno];
2420         if (!ata_dev_enabled(pair))
2421                 return NULL;
2422         return pair;
2423 }
2424
2425 /**
2426  *      ata_port_disable - Disable port.
2427  *      @ap: Port to be disabled.
2428  *
2429  *      Modify @ap data structure such that the system
2430  *      thinks that the entire port is disabled, and should
2431  *      never attempt to probe or communicate with devices
2432  *      on this port.
2433  *
2434  *      LOCKING: host lock, or some other form of
2435  *      serialization.
2436  */
2437
2438 void ata_port_disable(struct ata_port *ap)
2439 {
2440         ap->link.device[0].class = ATA_DEV_NONE;
2441         ap->link.device[1].class = ATA_DEV_NONE;
2442         ap->flags |= ATA_FLAG_DISABLED;
2443 }
2444
2445 /**
2446  *      sata_down_spd_limit - adjust SATA spd limit downward
2447  *      @link: Link to adjust SATA spd limit for
2448  *
2449  *      Adjust SATA spd limit of @link downward.  Note that this
2450  *      function only adjusts the limit.  The change must be applied
2451  *      using sata_set_spd().
2452  *
2453  *      LOCKING:
2454  *      Inherited from caller.
2455  *
2456  *      RETURNS:
2457  *      0 on success, negative errno on failure
2458  */
2459 int sata_down_spd_limit(struct ata_link *link)
2460 {
2461         u32 sstatus, spd, mask;
2462         int rc, highbit;
2463
2464         if (!sata_scr_valid(link))
2465                 return -EOPNOTSUPP;
2466
2467         /* If SCR can be read, use it to determine the current SPD.
2468          * If not, use cached value in link->sata_spd.
2469          */
2470         rc = sata_scr_read(link, SCR_STATUS, &sstatus);
2471         if (rc == 0)
2472                 spd = (sstatus >> 4) & 0xf;
2473         else
2474                 spd = link->sata_spd;
2475
2476         mask = link->sata_spd_limit;
2477         if (mask <= 1)
2478                 return -EINVAL;
2479
2480         /* unconditionally mask off the highest bit */
2481         highbit = fls(mask) - 1;
2482         mask &= ~(1 << highbit);
2483
2484         /* Mask off all speeds higher than or equal to the current
2485          * one.  Force 1.5Gbps if current SPD is not available.
2486          */
2487         if (spd > 1)
2488                 mask &= (1 << (spd - 1)) - 1;
2489         else
2490                 mask &= 1;
2491
2492         /* were we already at the bottom? */
2493         if (!mask)
2494                 return -EINVAL;
2495
2496         link->sata_spd_limit = mask;
2497
2498         ata_link_printk(link, KERN_WARNING, "limiting SATA link speed to %s\n",
2499                         sata_spd_string(fls(mask)));
2500
2501         return 0;
2502 }
2503
2504 static int __sata_set_spd_needed(struct ata_link *link, u32 *scontrol)
2505 {
2506         u32 spd, limit;
2507
2508         if (link->sata_spd_limit == UINT_MAX)
2509                 limit = 0;
2510         else
2511                 limit = fls(link->sata_spd_limit);
2512
2513         spd = (*scontrol >> 4) & 0xf;
2514         *scontrol = (*scontrol & ~0xf0) | ((limit & 0xf) << 4);
2515
2516         return spd != limit;
2517 }
2518
2519 /**
2520  *      sata_set_spd_needed - is SATA spd configuration needed
2521  *      @link: Link in question
2522  *
2523  *      Test whether the spd limit in SControl matches
2524  *      @link->sata_spd_limit.  This function is used to determine
2525  *      whether hardreset is necessary to apply SATA spd
2526  *      configuration.
2527  *
2528  *      LOCKING:
2529  *      Inherited from caller.
2530  *
2531  *      RETURNS:
2532  *      1 if SATA spd configuration is needed, 0 otherwise.
2533  */
2534 int sata_set_spd_needed(struct ata_link *link)
2535 {
2536         u32 scontrol;
2537
2538         if (sata_scr_read(link, SCR_CONTROL, &scontrol))
2539                 return 0;
2540
2541         return __sata_set_spd_needed(link, &scontrol);
2542 }
2543
2544 /**
2545  *      sata_set_spd - set SATA spd according to spd limit
2546  *      @link: Link to set SATA spd for
2547  *
2548  *      Set SATA spd of @link according to sata_spd_limit.
2549  *
2550  *      LOCKING:
2551  *      Inherited from caller.
2552  *
2553  *      RETURNS:
2554  *      0 if spd doesn't need to be changed, 1 if spd has been
2555  *      changed.  Negative errno if SCR registers are inaccessible.
2556  */
2557 int sata_set_spd(struct ata_link *link)
2558 {
2559         u32 scontrol;
2560         int rc;
2561
2562         if ((rc = sata_scr_read(link, SCR_CONTROL, &scontrol)))
2563                 return rc;
2564
2565         if (!__sata_set_spd_needed(link, &scontrol))
2566                 return 0;
2567
2568         if ((rc = sata_scr_write(link, SCR_CONTROL, scontrol)))
2569                 return rc;
2570
2571         return 1;
2572 }
2573
2574 /*
2575  * This mode timing computation functionality is ported over from
2576  * drivers/ide/ide-timing.h and was originally written by Vojtech Pavlik
2577  */
2578 /*
2579  * PIO 0-4, MWDMA 0-2 and UDMA 0-6 timings (in nanoseconds).
2580  * These were taken from ATA/ATAPI-6 standard, rev 0a, except
2581  * for UDMA6, which is currently supported only by Maxtor drives.
2582  *
2583  * For PIO 5/6 MWDMA 3/4 see the CFA specification 3.0.
2584  */
2585
2586 static const struct ata_timing ata_timing[] = {
2587
2588         { XFER_UDMA_6,     0,   0,   0,   0,   0,   0,   0,  15 },
2589         { XFER_UDMA_5,     0,   0,   0,   0,   0,   0,   0,  20 },
2590         { XFER_UDMA_4,     0,   0,   0,   0,   0,   0,   0,  30 },
2591         { XFER_UDMA_3,     0,   0,   0,   0,   0,   0,   0,  45 },
2592
2593         { XFER_MW_DMA_4,  25,   0,   0,   0,  55,  20,  80,   0 },
2594         { XFER_MW_DMA_3,  25,   0,   0,   0,  65,  25, 100,   0 },
2595         { XFER_UDMA_2,     0,   0,   0,   0,   0,   0,   0,  60 },
2596         { XFER_UDMA_1,     0,   0,   0,   0,   0,   0,   0,  80 },
2597         { XFER_UDMA_0,     0,   0,   0,   0,   0,   0,   0, 120 },
2598
2599 /*      { XFER_UDMA_SLOW,  0,   0,   0,   0,   0,   0,   0, 150 }, */
2600
2601         { XFER_MW_DMA_2,  25,   0,   0,   0,  70,  25, 120,   0 },
2602         { XFER_MW_DMA_1,  45,   0,   0,   0,  80,  50, 150,   0 },
2603         { XFER_MW_DMA_0,  60,   0,   0,   0, 215, 215, 480,   0 },
2604
2605         { XFER_SW_DMA_2,  60,   0,   0,   0, 120, 120, 240,   0 },
2606         { XFER_SW_DMA_1,  90,   0,   0,   0, 240, 240, 480,   0 },
2607         { XFER_SW_DMA_0, 120,   0,   0,   0, 480, 480, 960,   0 },
2608
2609         { XFER_PIO_6,     10,  55,  20,  80,  55,  20,  80,   0 },
2610         { XFER_PIO_5,     15,  65,  25, 100,  65,  25, 100,   0 },
2611         { XFER_PIO_4,     25,  70,  25, 120,  70,  25, 120,   0 },
2612         { XFER_PIO_3,     30,  80,  70, 180,  80,  70, 180,   0 },
2613
2614         { XFER_PIO_2,     30, 290,  40, 330, 100,  90, 240,   0 },
2615         { XFER_PIO_1,     50, 290,  93, 383, 125, 100, 383,   0 },
2616         { XFER_PIO_0,     70, 290, 240, 600, 165, 150, 600,   0 },
2617
2618 /*      { XFER_PIO_SLOW, 120, 290, 240, 960, 290, 240, 960,   0 }, */
2619
2620         { 0xFF }
2621 };
2622
2623 #define ENOUGH(v,unit)          (((v)-1)/(unit)+1)
2624 #define EZ(v,unit)              ((v)?ENOUGH(v,unit):0)
2625
2626 static void ata_timing_quantize(const struct ata_timing *t, struct ata_timing *q, int T, int UT)
2627 {
2628         q->setup   = EZ(t->setup   * 1000,  T);
2629         q->act8b   = EZ(t->act8b   * 1000,  T);
2630         q->rec8b   = EZ(t->rec8b   * 1000,  T);
2631         q->cyc8b   = EZ(t->cyc8b   * 1000,  T);
2632         q->active  = EZ(t->active  * 1000,  T);
2633         q->recover = EZ(t->recover * 1000,  T);
2634         q->cycle   = EZ(t->cycle   * 1000,  T);
2635         q->udma    = EZ(t->udma    * 1000, UT);
2636 }
2637
2638 void ata_timing_merge(const struct ata_timing *a, const struct ata_timing *b,
2639                       struct ata_timing *m, unsigned int what)
2640 {
2641         if (what & ATA_TIMING_SETUP  ) m->setup   = max(a->setup,   b->setup);
2642         if (what & ATA_TIMING_ACT8B  ) m->act8b   = max(a->act8b,   b->act8b);
2643         if (what & ATA_TIMING_REC8B  ) m->rec8b   = max(a->rec8b,   b->rec8b);
2644         if (what & ATA_TIMING_CYC8B  ) m->cyc8b   = max(a->cyc8b,   b->cyc8b);
2645         if (what & ATA_TIMING_ACTIVE ) m->active  = max(a->active,  b->active);
2646         if (what & ATA_TIMING_RECOVER) m->recover = max(a->recover, b->recover);
2647         if (what & ATA_TIMING_CYCLE  ) m->cycle   = max(a->cycle,   b->cycle);
2648         if (what & ATA_TIMING_UDMA   ) m->udma    = max(a->udma,    b->udma);
2649 }
2650
2651 static const struct ata_timing* ata_timing_find_mode(unsigned short speed)
2652 {
2653         const struct ata_timing *t;
2654
2655         for (t = ata_timing; t->mode != speed; t++)
2656                 if (t->mode == 0xFF)
2657                         return NULL;
2658         return t;
2659 }
2660
2661 int ata_timing_compute(struct ata_device *adev, unsigned short speed,
2662                        struct ata_timing *t, int T, int UT)
2663 {
2664         const struct ata_timing *s;
2665         struct ata_timing p;
2666
2667         /*
2668          * Find the mode.
2669          */
2670
2671         if (!(s = ata_timing_find_mode(speed)))
2672                 return -EINVAL;
2673
2674         memcpy(t, s, sizeof(*s));
2675
2676         /*
2677          * If the drive is an EIDE drive, it can tell us it needs extended
2678          * PIO/MW_DMA cycle timing.
2679          */
2680
2681         if (adev->id[ATA_ID_FIELD_VALID] & 2) { /* EIDE drive */
2682                 memset(&p, 0, sizeof(p));
2683                 if(speed >= XFER_PIO_0 && speed <= XFER_SW_DMA_0) {
2684                         if (speed <= XFER_PIO_2) p.cycle = p.cyc8b = adev->id[ATA_ID_EIDE_PIO];
2685                                             else p.cycle = p.cyc8b = adev->id[ATA_ID_EIDE_PIO_IORDY];
2686                 } else if(speed >= XFER_MW_DMA_0 && speed <= XFER_MW_DMA_2) {
2687                         p.cycle = adev->id[ATA_ID_EIDE_DMA_MIN];
2688                 }
2689                 ata_timing_merge(&p, t, t, ATA_TIMING_CYCLE | ATA_TIMING_CYC8B);
2690         }
2691
2692         /*
2693          * Convert the timing to bus clock counts.
2694          */
2695
2696         ata_timing_quantize(t, t, T, UT);
2697
2698         /*
2699          * Even in DMA/UDMA modes we still use PIO access for IDENTIFY,
2700          * S.M.A.R.T * and some other commands. We have to ensure that the
2701          * DMA cycle timing is slower/equal than the fastest PIO timing.
2702          */
2703
2704         if (speed > XFER_PIO_6) {
2705                 ata_timing_compute(adev, adev->pio_mode, &p, T, UT);
2706                 ata_timing_merge(&p, t, t, ATA_TIMING_ALL);
2707         }
2708
2709         /*
2710          * Lengthen active & recovery time so that cycle time is correct.
2711          */
2712
2713         if (t->act8b + t->rec8b < t->cyc8b) {
2714                 t->act8b += (t->cyc8b - (t->act8b + t->rec8b)) / 2;
2715                 t->rec8b = t->cyc8b - t->act8b;
2716         }
2717
2718         if (t->active + t->recover < t->cycle) {
2719                 t->active += (t->cycle - (t->active + t->recover)) / 2;
2720                 t->recover = t->cycle - t->active;
2721         }
2722
2723         /* In a few cases quantisation may produce enough errors to
2724            leave t->cycle too low for the sum of active and recovery
2725            if so we must correct this */
2726         if (t->active + t->recover > t->cycle)
2727                 t->cycle = t->active + t->recover;
2728
2729         return 0;
2730 }
2731
2732 /**
2733  *      ata_down_xfermask_limit - adjust dev xfer masks downward
2734  *      @dev: Device to adjust xfer masks
2735  *      @sel: ATA_DNXFER_* selector
2736  *
2737  *      Adjust xfer masks of @dev downward.  Note that this function
2738  *      does not apply the change.  Invoking ata_set_mode() afterwards
2739  *      will apply the limit.
2740  *
2741  *      LOCKING:
2742  *      Inherited from caller.
2743  *
2744  *      RETURNS:
2745  *      0 on success, negative errno on failure
2746  */
2747 int ata_down_xfermask_limit(struct ata_device *dev, unsigned int sel)
2748 {
2749         char buf[32];
2750         unsigned int orig_mask, xfer_mask;
2751         unsigned int pio_mask, mwdma_mask, udma_mask;
2752         int quiet, highbit;
2753
2754         quiet = !!(sel & ATA_DNXFER_QUIET);
2755         sel &= ~ATA_DNXFER_QUIET;
2756
2757         xfer_mask = orig_mask = ata_pack_xfermask(dev->pio_mask,
2758                                                   dev->mwdma_mask,
2759                                                   dev->udma_mask);
2760         ata_unpack_xfermask(xfer_mask, &pio_mask, &mwdma_mask, &udma_mask);
2761
2762         switch (sel) {
2763         case ATA_DNXFER_PIO:
2764                 highbit = fls(pio_mask) - 1;
2765                 pio_mask &= ~(1 << highbit);
2766                 break;
2767
2768         case ATA_DNXFER_DMA:
2769                 if (udma_mask) {
2770                         highbit = fls(udma_mask) - 1;
2771                         udma_mask &= ~(1 << highbit);
2772                         if (!udma_mask)
2773                                 return -ENOENT;
2774                 } else if (mwdma_mask) {
2775                         highbit = fls(mwdma_mask) - 1;
2776                         mwdma_mask &= ~(1 << highbit);
2777                         if (!mwdma_mask)
2778                                 return -ENOENT;
2779                 }
2780                 break;
2781
2782         case ATA_DNXFER_40C:
2783                 udma_mask &= ATA_UDMA_MASK_40C;
2784                 break;
2785
2786         case ATA_DNXFER_FORCE_PIO0:
2787                 pio_mask &= 1;
2788         case ATA_DNXFER_FORCE_PIO:
2789                 mwdma_mask = 0;
2790                 udma_mask = 0;
2791                 break;
2792
2793         default:
2794                 BUG();
2795         }
2796
2797         xfer_mask &= ata_pack_xfermask(pio_mask, mwdma_mask, udma_mask);
2798
2799         if (!(xfer_mask & ATA_MASK_PIO) || xfer_mask == orig_mask)
2800                 return -ENOENT;
2801
2802         if (!quiet) {
2803                 if (xfer_mask & (ATA_MASK_MWDMA | ATA_MASK_UDMA))
2804                         snprintf(buf, sizeof(buf), "%s:%s",
2805                                  ata_mode_string(xfer_mask),
2806                                  ata_mode_string(xfer_mask & ATA_MASK_PIO));
2807                 else
2808                         snprintf(buf, sizeof(buf), "%s",
2809                                  ata_mode_string(xfer_mask));
2810
2811                 ata_dev_printk(dev, KERN_WARNING,
2812                                "limiting speed to %s\n", buf);
2813         }
2814
2815         ata_unpack_xfermask(xfer_mask, &dev->pio_mask, &dev->mwdma_mask,
2816                             &dev->udma_mask);
2817
2818         return 0;
2819 }
2820
2821 static int ata_dev_set_mode(struct ata_device *dev)
2822 {
2823         struct ata_eh_context *ehc = &dev->link->eh_context;
2824         unsigned int err_mask;
2825         int rc;
2826
2827         dev->flags &= ~ATA_DFLAG_PIO;
2828         if (dev->xfer_shift == ATA_SHIFT_PIO)
2829                 dev->flags |= ATA_DFLAG_PIO;
2830
2831         err_mask = ata_dev_set_xfermode(dev);
2832         /* Old CFA may refuse this command, which is just fine */
2833         if (dev->xfer_shift == ATA_SHIFT_PIO && ata_id_is_cfa(dev->id))
2834                 err_mask &= ~AC_ERR_DEV;
2835         /* Some very old devices and some bad newer ones fail any kind of
2836            SET_XFERMODE request but support PIO0-2 timings and no IORDY */
2837         if (dev->xfer_shift == ATA_SHIFT_PIO && !ata_id_has_iordy(dev->id) &&
2838                         dev->pio_mode <= XFER_PIO_2)
2839                 err_mask &= ~AC_ERR_DEV;
2840         if (err_mask) {
2841                 ata_dev_printk(dev, KERN_ERR, "failed to set xfermode "
2842                                "(err_mask=0x%x)\n", err_mask);
2843                 return -EIO;
2844         }
2845
2846         ehc->i.flags |= ATA_EHI_POST_SETMODE;
2847         rc = ata_dev_revalidate(dev, 0);
2848         ehc->i.flags &= ~ATA_EHI_POST_SETMODE;
2849         if (rc)
2850                 return rc;
2851
2852         DPRINTK("xfer_shift=%u, xfer_mode=0x%x\n",
2853                 dev->xfer_shift, (int)dev->xfer_mode);
2854
2855         ata_dev_printk(dev, KERN_INFO, "configured for %s\n",
2856                        ata_mode_string(ata_xfer_mode2mask(dev->xfer_mode)));
2857         return 0;
2858 }
2859
2860 /**
2861  *      ata_do_set_mode - Program timings and issue SET FEATURES - XFER
2862  *      @link: link on which timings will be programmed
2863  *      @r_failed_dev: out paramter for failed device
2864  *
2865  *      Standard implementation of the function used to tune and set
2866  *      ATA device disk transfer mode (PIO3, UDMA6, etc.).  If
2867  *      ata_dev_set_mode() fails, pointer to the failing device is
2868  *      returned in @r_failed_dev.
2869  *
2870  *      LOCKING:
2871  *      PCI/etc. bus probe sem.
2872  *
2873  *      RETURNS:
2874  *      0 on success, negative errno otherwise
2875  */
2876
2877 int ata_do_set_mode(struct ata_link *link, struct ata_device **r_failed_dev)
2878 {
2879         struct ata_port *ap = link->ap;
2880         struct ata_device *dev;
2881         int rc = 0, used_dma = 0, found = 0;
2882
2883         /* step 1: calculate xfer_mask */
2884         ata_link_for_each_dev(dev, link) {
2885                 unsigned int pio_mask, dma_mask;
2886
2887                 if (!ata_dev_enabled(dev))
2888                         continue;
2889
2890                 ata_dev_xfermask(dev);
2891
2892                 pio_mask = ata_pack_xfermask(dev->pio_mask, 0, 0);
2893                 dma_mask = ata_pack_xfermask(0, dev->mwdma_mask, dev->udma_mask);
2894                 dev->pio_mode = ata_xfer_mask2mode(pio_mask);
2895                 dev->dma_mode = ata_xfer_mask2mode(dma_mask);
2896
2897                 found = 1;
2898                 if (dev->dma_mode)
2899                         used_dma = 1;
2900         }
2901         if (!found)
2902                 goto out;
2903
2904         /* step 2: always set host PIO timings */
2905         ata_link_for_each_dev(dev, link) {
2906                 if (!ata_dev_enabled(dev))
2907                         continue;
2908
2909                 if (!dev->pio_mode) {
2910                         ata_dev_printk(dev, KERN_WARNING, "no PIO support\n");
2911                         rc = -EINVAL;
2912                         goto out;
2913                 }
2914
2915                 dev->xfer_mode = dev->pio_mode;
2916                 dev->xfer_shift = ATA_SHIFT_PIO;
2917                 if (ap->ops->set_piomode)
2918                         ap->ops->set_piomode(ap, dev);
2919         }
2920
2921         /* step 3: set host DMA timings */
2922         ata_link_for_each_dev(dev, link) {
2923                 if (!ata_dev_enabled(dev) || !dev->dma_mode)
2924                         continue;
2925
2926                 dev->xfer_mode = dev->dma_mode;
2927                 dev->xfer_shift = ata_xfer_mode2shift(dev->dma_mode);
2928                 if (ap->ops->set_dmamode)
2929                         ap->ops->set_dmamode(ap, dev);
2930         }
2931
2932         /* step 4: update devices' xfer mode */
2933         ata_link_for_each_dev(dev, link) {
2934                 /* don't update suspended devices' xfer mode */
2935                 if (!ata_dev_enabled(dev))
2936                         continue;
2937
2938                 rc = ata_dev_set_mode(dev);
2939                 if (rc)
2940                         goto out;
2941         }
2942
2943         /* Record simplex status. If we selected DMA then the other
2944          * host channels are not permitted to do so.
2945          */
2946         if (used_dma && (ap->host->flags & ATA_HOST_SIMPLEX))
2947                 ap->host->simplex_claimed = ap;
2948
2949  out:
2950         if (rc)
2951                 *r_failed_dev = dev;
2952         return rc;
2953 }
2954
2955 /**
2956  *      ata_set_mode - Program timings and issue SET FEATURES - XFER
2957  *      @link: link on which timings will be programmed
2958  *      @r_failed_dev: out paramter for failed device
2959  *
2960  *      Set ATA device disk transfer mode (PIO3, UDMA6, etc.).  If
2961  *      ata_set_mode() fails, pointer to the failing device is
2962  *      returned in @r_failed_dev.
2963  *
2964  *      LOCKING:
2965  *      PCI/etc. bus probe sem.
2966  *
2967  *      RETURNS:
2968  *      0 on success, negative errno otherwise
2969  */
2970 int ata_set_mode(struct ata_link *link, struct ata_device **r_failed_dev)
2971 {
2972         struct ata_port *ap = link->ap;
2973
2974         /* has private set_mode? */
2975         if (ap->ops->set_mode)
2976                 return ap->ops->set_mode(link, r_failed_dev);
2977         return ata_do_set_mode(link, r_failed_dev);
2978 }
2979
2980 /**
2981  *      ata_tf_to_host - issue ATA taskfile to host controller
2982  *      @ap: port to which command is being issued
2983  *      @tf: ATA taskfile register set
2984  *
2985  *      Issues ATA taskfile register set to ATA host controller,
2986  *      with proper synchronization with interrupt handler and
2987  *      other threads.
2988  *
2989  *      LOCKING:
2990  *      spin_lock_irqsave(host lock)
2991  */
2992
2993 static inline void ata_tf_to_host(struct ata_port *ap,
2994                                   const struct ata_taskfile *tf)
2995 {
2996         ap->ops->tf_load(ap, tf);
2997         ap->ops->exec_command(ap, tf);
2998 }
2999
3000 /**
3001  *      ata_busy_sleep - sleep until BSY clears, or timeout
3002  *      @ap: port containing status register to be polled
3003  *      @tmout_pat: impatience timeout
3004  *      @tmout: overall timeout
3005  *
3006  *      Sleep until ATA Status register bit BSY clears,
3007  *      or a timeout occurs.
3008  *
3009  *      LOCKING:
3010  *      Kernel thread context (may sleep).
3011  *
3012  *      RETURNS:
3013  *      0 on success, -errno otherwise.
3014  */
3015 int ata_busy_sleep(struct ata_port *ap,
3016                    unsigned long tmout_pat, unsigned long tmout)
3017 {
3018         unsigned long timer_start, timeout;
3019         u8 status;
3020
3021         status = ata_busy_wait(ap, ATA_BUSY, 300);
3022         timer_start = jiffies;
3023         timeout = timer_start + tmout_pat;
3024         while (status != 0xff && (status & ATA_BUSY) &&
3025                time_before(jiffies, timeout)) {
3026                 msleep(50);
3027                 status = ata_busy_wait(ap, ATA_BUSY, 3);
3028         }
3029
3030         if (status != 0xff && (status & ATA_BUSY))
3031                 ata_port_printk(ap, KERN_WARNING,
3032                                 "port is slow to respond, please be patient "
3033                                 "(Status 0x%x)\n", status);
3034
3035         timeout = timer_start + tmout;
3036         while (status != 0xff && (status & ATA_BUSY) &&
3037                time_before(jiffies, timeout)) {
3038                 msleep(50);
3039                 status = ata_chk_status(ap);
3040         }
3041
3042         if (status == 0xff)
3043                 return -ENODEV;
3044
3045         if (status & ATA_BUSY) {
3046                 ata_port_printk(ap, KERN_ERR, "port failed to respond "
3047                                 "(%lu secs, Status 0x%x)\n",
3048                                 tmout / HZ, status);
3049                 return -EBUSY;
3050         }
3051
3052         return 0;
3053 }
3054
3055 /**
3056  *      ata_wait_ready - sleep until BSY clears, or timeout
3057  *      @ap: port containing status register to be polled
3058  *      @deadline: deadline jiffies for the operation
3059  *
3060  *      Sleep until ATA Status register bit BSY clears, or timeout
3061  *      occurs.
3062  *
3063  *      LOCKING:
3064  *      Kernel thread context (may sleep).
3065  *
3066  *      RETURNS:
3067  *      0 on success, -errno otherwise.
3068  */
3069 int ata_wait_ready(struct ata_port *ap, unsigned long deadline)
3070 {
3071         unsigned long start = jiffies;
3072         int warned = 0;
3073
3074         while (1) {
3075                 u8 status = ata_chk_status(ap);
3076                 unsigned long now = jiffies;
3077
3078                 if (!(status & ATA_BUSY))
3079                         return 0;
3080                 if (!ata_link_online(&ap->link) && status == 0xff)
3081                         return -ENODEV;
3082                 if (time_after(now, deadline))
3083                         return -EBUSY;
3084
3085                 if (!warned && time_after(now, start + 5 * HZ) &&
3086                     (deadline - now > 3 * HZ)) {
3087                         ata_port_printk(ap, KERN_WARNING,
3088                                 "port is slow to respond, please be patient "
3089                                 "(Status 0x%x)\n", status);
3090                         warned = 1;
3091                 }
3092
3093                 msleep(50);
3094         }
3095 }
3096
3097 static int ata_bus_post_reset(struct ata_port *ap, unsigned int devmask,
3098                               unsigned long deadline)
3099 {
3100         struct ata_ioports *ioaddr = &ap->ioaddr;
3101         unsigned int dev0 = devmask & (1 << 0);
3102         unsigned int dev1 = devmask & (1 << 1);
3103         int rc, ret = 0;
3104
3105         /* if device 0 was found in ata_devchk, wait for its
3106          * BSY bit to clear
3107          */
3108         if (dev0) {
3109                 rc = ata_wait_ready(ap, deadline);
3110                 if (rc) {
3111                         if (rc != -ENODEV)
3112                                 return rc;
3113                         ret = rc;
3114                 }
3115         }
3116
3117         /* if device 1 was found in ata_devchk, wait for register
3118          * access briefly, then wait for BSY to clear.
3119          */
3120         if (dev1) {
3121                 int i;
3122
3123                 ap->ops->dev_select(ap, 1);
3124
3125                 /* Wait for register access.  Some ATAPI devices fail
3126                  * to set nsect/lbal after reset, so don't waste too
3127                  * much time on it.  We're gonna wait for !BSY anyway.
3128                  */
3129                 for (i = 0; i < 2; i++) {
3130                         u8 nsect, lbal;
3131
3132                         nsect = ioread8(ioaddr->nsect_addr);
3133                         lbal = ioread8(ioaddr->lbal_addr);
3134                         if ((nsect == 1) && (lbal == 1))
3135                                 break;
3136                         msleep(50);     /* give drive a breather */
3137                 }
3138
3139                 rc = ata_wait_ready(ap, deadline);
3140                 if (rc) {
3141                         if (rc != -ENODEV)
3142                                 return rc;
3143                         ret = rc;
3144                 }
3145         }
3146
3147         /* is all this really necessary? */
3148         ap->ops->dev_select(ap, 0);
3149         if (dev1)
3150                 ap->ops->dev_select(ap, 1);
3151         if (dev0)
3152                 ap->ops->dev_select(ap, 0);
3153
3154         return ret;
3155 }
3156
3157 static int ata_bus_softreset(struct ata_port *ap, unsigned int devmask,
3158                              unsigned long deadline)
3159 {
3160         struct ata_ioports *ioaddr = &ap->ioaddr;
3161
3162         DPRINTK("ata%u: bus reset via SRST\n", ap->print_id);
3163
3164         /* software reset.  causes dev0 to be selected */
3165         iowrite8(ap->ctl, ioaddr->ctl_addr);
3166         udelay(20);     /* FIXME: flush */
3167         iowrite8(ap->ctl | ATA_SRST, ioaddr->ctl_addr);
3168         udelay(20);     /* FIXME: flush */
3169         iowrite8(ap->ctl, ioaddr->ctl_addr);
3170
3171         /* spec mandates ">= 2ms" before checking status.
3172          * We wait 150ms, because that was the magic delay used for
3173          * ATAPI devices in Hale Landis's ATADRVR, for the period of time
3174          * between when the ATA command register is written, and then
3175          * status is checked.  Because waiting for "a while" before
3176          * checking status is fine, post SRST, we perform this magic
3177          * delay here as well.
3178          *
3179          * Old drivers/ide uses the 2mS rule and then waits for ready
3180          */
3181         msleep(150);
3182
3183         /* Before we perform post reset processing we want to see if
3184          * the bus shows 0xFF because the odd clown forgets the D7
3185          * pulldown resistor.
3186          */
3187         if (ata_check_status(ap) == 0xFF)
3188                 return -ENODEV;
3189
3190         return ata_bus_post_reset(ap, devmask, deadline);
3191 }
3192
3193 /**
3194  *      ata_bus_reset - reset host port and associated ATA channel
3195  *      @ap: port to reset
3196  *
3197  *      This is typically the first time we actually start issuing
3198  *      commands to the ATA channel.  We wait for BSY to clear, then
3199  *      issue EXECUTE DEVICE DIAGNOSTIC command, polling for its
3200  *      result.  Determine what devices, if any, are on the channel
3201  *      by looking at the device 0/1 error register.  Look at the signature
3202  *      stored in each device's taskfile registers, to determine if
3203  *      the device is ATA or ATAPI.
3204  *
3205  *      LOCKING:
3206  *      PCI/etc. bus probe sem.
3207  *      Obtains host lock.
3208  *
3209  *      SIDE EFFECTS:
3210  *      Sets ATA_FLAG_DISABLED if bus reset fails.
3211  */
3212
3213 void ata_bus_reset(struct ata_port *ap)
3214 {
3215         struct ata_device *device = ap->link.device;
3216         struct ata_ioports *ioaddr = &ap->ioaddr;
3217         unsigned int slave_possible = ap->flags & ATA_FLAG_SLAVE_POSS;
3218         u8 err;
3219         unsigned int dev0, dev1 = 0, devmask = 0;
3220         int rc;
3221
3222         DPRINTK("ENTER, host %u, port %u\n", ap->print_id, ap->port_no);
3223
3224         /* determine if device 0/1 are present */
3225         if (ap->flags & ATA_FLAG_SATA_RESET)
3226                 dev0 = 1;
3227         else {
3228                 dev0 = ata_devchk(ap, 0);
3229                 if (slave_possible)
3230                         dev1 = ata_devchk(ap, 1);
3231         }
3232
3233         if (dev0)
3234                 devmask |= (1 << 0);
3235         if (dev1)
3236                 devmask |= (1 << 1);
3237
3238         /* select device 0 again */
3239         ap->ops->dev_select(ap, 0);
3240
3241         /* issue bus reset */
3242         if (ap->flags & ATA_FLAG_SRST) {
3243                 rc = ata_bus_softreset(ap, devmask, jiffies + 40 * HZ);
3244                 if (rc && rc != -ENODEV)
3245                         goto err_out;
3246         }
3247
3248         /*
3249          * determine by signature whether we have ATA or ATAPI devices
3250          */
3251         device[0].class = ata_dev_try_classify(&device[0], dev0, &err);
3252         if ((slave_possible) && (err != 0x81))
3253                 device[1].class = ata_dev_try_classify(&device[1], dev1, &err);
3254
3255         /* is double-select really necessary? */
3256         if (device[1].class != ATA_DEV_NONE)
3257                 ap->ops->dev_select(ap, 1);
3258         if (device[0].class != ATA_DEV_NONE)
3259                 ap->ops->dev_select(ap, 0);
3260
3261         /* if no devices were detected, disable this port */
3262         if ((device[0].class == ATA_DEV_NONE) &&
3263             (device[1].class == ATA_DEV_NONE))
3264                 goto err_out;
3265
3266         if (ap->flags & (ATA_FLAG_SATA_RESET | ATA_FLAG_SRST)) {
3267                 /* set up device control for ATA_FLAG_SATA_RESET */
3268                 iowrite8(ap->ctl, ioaddr->ctl_addr);
3269         }
3270
3271         DPRINTK("EXIT\n");
3272         return;
3273
3274 err_out:
3275         ata_port_printk(ap, KERN_ERR, "disabling port\n");
3276         ata_port_disable(ap);
3277
3278         DPRINTK("EXIT\n");
3279 }
3280
3281 /**
3282  *      sata_link_debounce - debounce SATA phy status
3283  *      @link: ATA link to debounce SATA phy status for
3284  *      @params: timing parameters { interval, duratinon, timeout } in msec
3285  *      @deadline: deadline jiffies for the operation
3286  *
3287 *       Make sure SStatus of @link reaches stable state, determined by
3288  *      holding the same value where DET is not 1 for @duration polled
3289  *      every @interval, before @timeout.  Timeout constraints the
3290  *      beginning of the stable state.  Because DET gets stuck at 1 on
3291  *      some controllers after hot unplugging, this functions waits
3292  *      until timeout then returns 0 if DET is stable at 1.
3293  *
3294  *      @timeout is further limited by @deadline.  The sooner of the
3295  *      two is used.
3296  *
3297  *      LOCKING:
3298  *      Kernel thread context (may sleep)
3299  *
3300  *      RETURNS:
3301  *      0 on success, -errno on failure.
3302  */
3303 int sata_link_debounce(struct ata_link *link, const unsigned long *params,
3304                        unsigned long deadline)
3305 {
3306         unsigned long interval_msec = params[0];
3307         unsigned long duration = msecs_to_jiffies(params[1]);
3308         unsigned long last_jiffies, t;
3309         u32 last, cur;
3310         int rc;
3311
3312         t = jiffies + msecs_to_jiffies(params[2]);
3313         if (time_before(t, deadline))
3314                 deadline = t;
3315
3316         if ((rc = sata_scr_read(link, SCR_STATUS, &cur)))
3317                 return rc;
3318         cur &= 0xf;
3319
3320         last = cur;
3321         last_jiffies = jiffies;
3322
3323         while (1) {
3324                 msleep(interval_msec);
3325                 if ((rc = sata_scr_read(link, SCR_STATUS, &cur)))
3326                         return rc;
3327                 cur &= 0xf;
3328
3329                 /* DET stable? */
3330                 if (cur == last) {
3331                         if (cur == 1 && time_before(jiffies, deadline))
3332                                 continue;
3333                         if (time_after(jiffies, last_jiffies + duration))
3334                                 return 0;
3335                         continue;
3336                 }
3337
3338                 /* unstable, start over */
3339                 last = cur;
3340                 last_jiffies = jiffies;
3341
3342                 /* Check deadline.  If debouncing failed, return
3343                  * -EPIPE to tell upper layer to lower link speed.
3344                  */
3345                 if (time_after(jiffies, deadline))
3346                         return -EPIPE;
3347         }
3348 }
3349
3350 /**
3351  *      sata_link_resume - resume SATA link
3352  *      @link: ATA link to resume SATA
3353  *      @params: timing parameters { interval, duratinon, timeout } in msec
3354  *      @deadline: deadline jiffies for the operation
3355  *
3356  *      Resume SATA phy @link and debounce it.
3357  *
3358  *      LOCKING:
3359  *      Kernel thread context (may sleep)
3360  *
3361  *      RETURNS:
3362  *      0 on success, -errno on failure.
3363  */
3364 int sata_link_resume(struct ata_link *link, const unsigned long *params,
3365                      unsigned long deadline)
3366 {
3367         u32 scontrol;
3368         int rc;
3369
3370         if ((rc = sata_scr_read(link, SCR_CONTROL, &scontrol)))
3371                 return rc;
3372
3373         scontrol = (scontrol & 0x0f0) | 0x300;
3374
3375         if ((rc = sata_scr_write(link, SCR_CONTROL, scontrol)))
3376                 return rc;
3377
3378         /* Some PHYs react badly if SStatus is pounded immediately
3379          * after resuming.  Delay 200ms before debouncing.
3380          */
3381         msleep(200);
3382
3383         return sata_link_debounce(link, params, deadline);
3384 }
3385
3386 /**
3387  *      ata_std_prereset - prepare for reset
3388  *      @link: ATA link to be reset
3389  *      @deadline: deadline jiffies for the operation
3390  *
3391  *      @link is about to be reset.  Initialize it.  Failure from
3392  *      prereset makes libata abort whole reset sequence and give up
3393  *      that port, so prereset should be best-effort.  It does its
3394  *      best to prepare for reset sequence but if things go wrong, it
3395  *      should just whine, not fail.
3396  *
3397  *      LOCKING:
3398  *      Kernel thread context (may sleep)
3399  *
3400  *      RETURNS:
3401  *      0 on success, -errno otherwise.
3402  */
3403 int ata_std_prereset(struct ata_link *link, unsigned long deadline)
3404 {
3405         struct ata_port *ap = link->ap;
3406         struct ata_eh_context *ehc = &link->eh_context;
3407         const unsigned long *timing = sata_ehc_deb_timing(ehc);
3408         int rc;
3409
3410         /* handle link resume */
3411         if ((ehc->i.flags & ATA_EHI_RESUME_LINK) &&
3412             (link->flags & ATA_LFLAG_HRST_TO_RESUME))
3413                 ehc->i.action |= ATA_EH_HARDRESET;
3414
3415         /* if we're about to do hardreset, nothing more to do */
3416         if (ehc->i.action & ATA_EH_HARDRESET)
3417                 return 0;
3418
3419         /* if SATA, resume link */
3420         if (ap->flags & ATA_FLAG_SATA) {
3421                 rc = sata_link_resume(link, timing, deadline);
3422                 /* whine about phy resume failure but proceed */
3423                 if (rc && rc != -EOPNOTSUPP)
3424                         ata_link_printk(link, KERN_WARNING, "failed to resume "
3425                                         "link for reset (errno=%d)\n", rc);
3426         }
3427
3428         /* Wait for !BSY if the controller can wait for the first D2H
3429          * Reg FIS and we don't know that no device is attached.
3430          */
3431         if (!(link->flags & ATA_LFLAG_SKIP_D2H_BSY) && !ata_link_offline(link)) {
3432                 rc = ata_wait_ready(ap, deadline);
3433                 if (rc && rc != -ENODEV) {
3434                         ata_link_printk(link, KERN_WARNING, "device not ready "
3435                                         "(errno=%d), forcing hardreset\n", rc);
3436                         ehc->i.action |= ATA_EH_HARDRESET;
3437                 }
3438         }
3439
3440         return 0;
3441 }
3442
3443 /**
3444  *      ata_std_softreset - reset host port via ATA SRST
3445  *      @link: ATA link to reset
3446  *      @classes: resulting classes of attached devices
3447  *      @deadline: deadline jiffies for the operation
3448  *
3449  *      Reset host port using ATA SRST.
3450  *
3451  *      LOCKING:
3452  *      Kernel thread context (may sleep)
3453  *
3454  *      RETURNS:
3455  *      0 on success, -errno otherwise.
3456  */
3457 int ata_std_softreset(struct ata_link *link, unsigned int *classes,
3458                       unsigned long deadline)
3459 {
3460         struct ata_port *ap = link->ap;
3461         unsigned int slave_possible = ap->flags & ATA_FLAG_SLAVE_POSS;
3462         unsigned int devmask = 0;
3463         int rc;
3464         u8 err;
3465
3466         DPRINTK("ENTER\n");
3467
3468         if (ata_link_offline(link)) {
3469                 classes[0] = ATA_DEV_NONE;
3470                 goto out;
3471         }
3472
3473         /* determine if device 0/1 are present */
3474         if (ata_devchk(ap, 0))
3475                 devmask |= (1 << 0);
3476         if (slave_possible && ata_devchk(ap, 1))
3477                 devmask |= (1 << 1);
3478
3479         /* select device 0 again */
3480         ap->ops->dev_select(ap, 0);
3481
3482         /* issue bus reset */
3483         DPRINTK("about to softreset, devmask=%x\n", devmask);
3484         rc = ata_bus_softreset(ap, devmask, deadline);
3485         /* if link is occupied, -ENODEV too is an error */
3486         if (rc && (rc != -ENODEV || sata_scr_valid(link))) {
3487                 ata_link_printk(link, KERN_ERR, "SRST failed (errno=%d)\n", rc);
3488                 return rc;
3489         }
3490
3491         /* determine by signature whether we have ATA or ATAPI devices */
3492         classes[0] = ata_dev_try_classify(&link->device[0],
3493                                           devmask & (1 << 0), &err);
3494         if (slave_possible && err != 0x81)
3495                 classes[1] = ata_dev_try_classify(&link->device[1],
3496                                                   devmask & (1 << 1), &err);
3497
3498  out:
3499         DPRINTK("EXIT, classes[0]=%u [1]=%u\n", classes[0], classes[1]);
3500         return 0;
3501 }
3502
3503 /**
3504  *      sata_link_hardreset - reset link via SATA phy reset
3505  *      @link: link to reset
3506  *      @timing: timing parameters { interval, duratinon, timeout } in msec
3507  *      @deadline: deadline jiffies for the operation
3508  *
3509  *      SATA phy-reset @link using DET bits of SControl register.
3510  *
3511  *      LOCKING:
3512  *      Kernel thread context (may sleep)
3513  *
3514  *      RETURNS:
3515  *      0 on success, -errno otherwise.
3516  */
3517 int sata_link_hardreset(struct ata_link *link, const unsigned long *timing,
3518                         unsigned long deadline)
3519 {
3520         u32 scontrol;
3521         int rc;
3522
3523         DPRINTK("ENTER\n");
3524
3525         if (sata_set_spd_needed(link)) {
3526                 /* SATA spec says nothing about how to reconfigure
3527                  * spd.  To be on the safe side, turn off phy during
3528                  * reconfiguration.  This works for at least ICH7 AHCI
3529                  * and Sil3124.
3530                  */
3531                 if ((rc = sata_scr_read(link, SCR_CONTROL, &scontrol)))
3532                         goto out;
3533
3534                 scontrol = (scontrol & 0x0f0) | 0x304;
3535
3536                 if ((rc = sata_scr_write(link, SCR_CONTROL, scontrol)))
3537                         goto out;
3538
3539                 sata_set_spd(link);
3540         }
3541
3542         /* issue phy wake/reset */
3543         if ((rc = sata_scr_read(link, SCR_CONTROL, &scontrol)))
3544                 goto out;
3545
3546         scontrol = (scontrol & 0x0f0) | 0x301;
3547
3548         if ((rc = sata_scr_write_flush(link, SCR_CONTROL, scontrol)))
3549                 goto out;
3550
3551         /* Couldn't find anything in SATA I/II specs, but AHCI-1.1
3552          * 10.4.2 says at least 1 ms.
3553          */
3554         msleep(1);
3555
3556         /* bring link back */
3557         rc = sata_link_resume(link, timing, deadline);
3558  out:
3559         DPRINTK("EXIT, rc=%d\n", rc);
3560         return rc;
3561 }
3562
3563 /**
3564  *      sata_std_hardreset - reset host port via SATA phy reset
3565  *      @link: link to reset
3566  *      @class: resulting class of attached device
3567  *      @deadline: deadline jiffies for the operation
3568  *
3569  *      SATA phy-reset host port using DET bits of SControl register,
3570  *      wait for !BSY and classify the attached device.
3571  *
3572  *      LOCKING:
3573  *      Kernel thread context (may sleep)
3574  *
3575  *      RETURNS:
3576  *      0 on success, -errno otherwise.
3577  */
3578 int sata_std_hardreset(struct ata_link *link, unsigned int *class,
3579                        unsigned long deadline)
3580 {
3581         struct ata_port *ap = link->ap;
3582         const unsigned long *timing = sata_ehc_deb_timing(&link->eh_context);
3583         int rc;
3584
3585         DPRINTK("ENTER\n");
3586
3587         /* do hardreset */
3588         rc = sata_link_hardreset(link, timing, deadline);
3589         if (rc) {
3590                 ata_link_printk(link, KERN_ERR,
3591                                 "COMRESET failed (errno=%d)\n", rc);
3592                 return rc;
3593         }
3594
3595         /* TODO: phy layer with polling, timeouts, etc. */
3596         if (ata_link_offline(link)) {
3597                 *class = ATA_DEV_NONE;
3598                 DPRINTK("EXIT, link offline\n");
3599                 return 0;
3600         }
3601
3602         /* wait a while before checking status, see SRST for more info */
3603         msleep(150);
3604
3605         rc = ata_wait_ready(ap, deadline);
3606         /* link occupied, -ENODEV too is an error */
3607         if (rc) {
3608                 ata_link_printk(link, KERN_ERR,
3609                                 "COMRESET failed (errno=%d)\n", rc);
3610                 return rc;
3611         }
3612
3613         ap->ops->dev_select(ap, 0);     /* probably unnecessary */
3614
3615         *class = ata_dev_try_classify(link->device, 1, NULL);
3616
3617         DPRINTK("EXIT, class=%u\n", *class);
3618         return 0;
3619 }
3620
3621 /**
3622  *      ata_std_postreset - standard postreset callback
3623  *      @link: the target ata_link
3624  *      @classes: classes of attached devices
3625  *
3626  *      This function is invoked after a successful reset.  Note that
3627  *      the device might have been reset more than once using
3628  *      different reset methods before postreset is invoked.
3629  *
3630  *      LOCKING:
3631  *      Kernel thread context (may sleep)
3632  */
3633 void ata_std_postreset(struct ata_link *link, unsigned int *classes)
3634 {
3635         struct ata_port *ap = link->ap;
3636         u32 serror;
3637
3638         DPRINTK("ENTER\n");
3639
3640         /* print link status */
3641         sata_print_link_status(link);
3642
3643         /* clear SError */
3644         if (sata_scr_read(link, SCR_ERROR, &serror) == 0)
3645                 sata_scr_write(link, SCR_ERROR, serror);
3646
3647         /* is double-select really necessary? */
3648         if (classes[0] != ATA_DEV_NONE)
3649                 ap->ops->dev_select(ap, 1);
3650         if (classes[1] != ATA_DEV_NONE)
3651                 ap->ops->dev_select(ap, 0);
3652
3653         /* bail out if no device is present */
3654         if (classes[0] == ATA_DEV_NONE && classes[1] == ATA_DEV_NONE) {
3655                 DPRINTK("EXIT, no device\n");
3656                 return;
3657         }
3658
3659         /* set up device control */
3660         if (ap->ioaddr.ctl_addr)
3661                 iowrite8(ap->ctl, ap->ioaddr.ctl_addr);
3662
3663         DPRINTK("EXIT\n");
3664 }
3665
3666 /**
3667  *      ata_dev_same_device - Determine whether new ID matches configured device
3668  *      @dev: device to compare against
3669  *      @new_class: class of the new device
3670  *      @new_id: IDENTIFY page of the new device
3671  *
3672  *      Compare @new_class and @new_id against @dev and determine
3673  *      whether @dev is the device indicated by @new_class and
3674  *      @new_id.
3675  *
3676  *      LOCKING:
3677  *      None.
3678  *
3679  *      RETURNS:
3680  *      1 if @dev matches @new_class and @new_id, 0 otherwise.
3681  */
3682 static int ata_dev_same_device(struct ata_device *dev, unsigned int new_class,
3683                                const u16 *new_id)
3684 {
3685         const u16 *old_id = dev->id;
3686         unsigned char model[2][ATA_ID_PROD_LEN + 1];
3687         unsigned char serial[2][ATA_ID_SERNO_LEN + 1];
3688
3689         if (dev->class != new_class) {
3690                 ata_dev_printk(dev, KERN_INFO, "class mismatch %d != %d\n",
3691                                dev->class, new_class);
3692                 return 0;
3693         }
3694
3695         ata_id_c_string(old_id, model[0], ATA_ID_PROD, sizeof(model[0]));
3696         ata_id_c_string(new_id, model[1], ATA_ID_PROD, sizeof(model[1]));
3697         ata_id_c_string(old_id, serial[0], ATA_ID_SERNO, sizeof(serial[0]));
3698         ata_id_c_string(new_id, serial[1], ATA_ID_SERNO, sizeof(serial[1]));
3699
3700         if (strcmp(model[0], model[1])) {
3701                 ata_dev_printk(dev, KERN_INFO, "model number mismatch "
3702                                "'%s' != '%s'\n", model[0], model[1]);
3703                 return 0;
3704         }
3705
3706         if (strcmp(serial[0], serial[1])) {
3707                 ata_dev_printk(dev, KERN_INFO, "serial number mismatch "
3708                                "'%s' != '%s'\n", serial[0], serial[1]);
3709                 return 0;
3710         }
3711
3712         return 1;
3713 }
3714
3715 /**
3716  *      ata_dev_reread_id - Re-read IDENTIFY data
3717  *      @dev: target ATA device
3718  *      @readid_flags: read ID flags
3719  *
3720  *      Re-read IDENTIFY page and make sure @dev is still attached to
3721  *      the port.
3722  *
3723  *      LOCKING:
3724  *      Kernel thread context (may sleep)
3725  *
3726  *      RETURNS:
3727  *      0 on success, negative errno otherwise
3728  */
3729 int ata_dev_reread_id(struct ata_device *dev, unsigned int readid_flags)
3730 {
3731         unsigned int class = dev->class;
3732         u16 *id = (void *)dev->link->ap->sector_buf;
3733         int rc;
3734
3735         /* read ID data */
3736         rc = ata_dev_read_id(dev, &class, readid_flags, id);
3737         if (rc)
3738                 return rc;
3739
3740         /* is the device still there? */
3741         if (!ata_dev_same_device(dev, class, id))
3742                 return -ENODEV;
3743
3744         memcpy(dev->id, id, sizeof(id[0]) * ATA_ID_WORDS);
3745         return 0;
3746 }
3747
3748 /**
3749  *      ata_dev_revalidate - Revalidate ATA device
3750  *      @dev: device to revalidate
3751  *      @readid_flags: read ID flags
3752  *
3753  *      Re-read IDENTIFY page, make sure @dev is still attached to the
3754  *      port and reconfigure it according to the new IDENTIFY page.
3755  *
3756  *      LOCKING:
3757  *      Kernel thread context (may sleep)
3758  *
3759  *      RETURNS:
3760  *      0 on success, negative errno otherwise
3761  */
3762 int ata_dev_revalidate(struct ata_device *dev, unsigned int readid_flags)
3763 {
3764         u64 n_sectors = dev->n_sectors;
3765         int rc;
3766
3767         if (!ata_dev_enabled(dev))
3768                 return -ENODEV;
3769
3770         /* re-read ID */
3771         rc = ata_dev_reread_id(dev, readid_flags);
3772         if (rc)
3773                 goto fail;
3774
3775         /* configure device according to the new ID */
3776         rc = ata_dev_configure(dev);
3777         if (rc)
3778                 goto fail;
3779
3780         /* verify n_sectors hasn't changed */
3781         if (dev->class == ATA_DEV_ATA && n_sectors &&
3782             dev->n_sectors != n_sectors) {
3783                 ata_dev_printk(dev, KERN_INFO, "n_sectors mismatch "
3784                                "%llu != %llu\n",
3785                                (unsigned long long)n_sectors,
3786                                (unsigned long long)dev->n_sectors);
3787
3788                 /* restore original n_sectors */
3789                 dev->n_sectors = n_sectors;
3790
3791                 rc = -ENODEV;
3792                 goto fail;
3793         }
3794
3795         return 0;
3796
3797  fail:
3798         ata_dev_printk(dev, KERN_ERR, "revalidation failed (errno=%d)\n", rc);
3799         return rc;
3800 }
3801
3802 struct ata_blacklist_entry {
3803         const char *model_num;
3804         const char *model_rev;
3805         unsigned long horkage;
3806 };
3807
3808 static const struct ata_blacklist_entry ata_device_blacklist [] = {
3809         /* Devices with DMA related problems under Linux */
3810         { "WDC AC11000H",       NULL,           ATA_HORKAGE_NODMA },
3811         { "WDC AC22100H",       NULL,           ATA_HORKAGE_NODMA },
3812         { "WDC AC32500H",       NULL,           ATA_HORKAGE_NODMA },
3813         { "WDC AC33100H",       NULL,           ATA_HORKAGE_NODMA },
3814         { "WDC AC31600H",       NULL,           ATA_HORKAGE_NODMA },
3815         { "WDC AC32100H",       "24.09P07",     ATA_HORKAGE_NODMA },
3816         { "WDC AC23200L",       "21.10N21",     ATA_HORKAGE_NODMA },
3817         { "Compaq CRD-8241B",   NULL,           ATA_HORKAGE_NODMA },
3818         { "CRD-8400B",          NULL,           ATA_HORKAGE_NODMA },
3819         { "CRD-8480B",          NULL,           ATA_HORKAGE_NODMA },
3820         { "CRD-8482B",          NULL,           ATA_HORKAGE_NODMA },
3821         { "CRD-84",             NULL,           ATA_HORKAGE_NODMA },
3822         { "SanDisk SDP3B",      NULL,           ATA_HORKAGE_NODMA },
3823         { "SanDisk SDP3B-64",   NULL,           ATA_HORKAGE_NODMA },
3824         { "SANYO CD-ROM CRD",   NULL,           ATA_HORKAGE_NODMA },
3825         { "HITACHI CDR-8",      NULL,           ATA_HORKAGE_NODMA },
3826         { "HITACHI CDR-8335",   NULL,           ATA_HORKAGE_NODMA },
3827         { "HITACHI CDR-8435",   NULL,           ATA_HORKAGE_NODMA },
3828         { "Toshiba CD-ROM XM-6202B", NULL,      ATA_HORKAGE_NODMA },
3829         { "TOSHIBA CD-ROM XM-1702BC", NULL,     ATA_HORKAGE_NODMA },
3830         { "CD-532E-A",          NULL,           ATA_HORKAGE_NODMA },
3831         { "E-IDE CD-ROM CR-840",NULL,           ATA_HORKAGE_NODMA },
3832         { "CD-ROM Drive/F5A",   NULL,           ATA_HORKAGE_NODMA },
3833         { "WPI CDD-820",        NULL,           ATA_HORKAGE_NODMA },
3834         { "SAMSUNG CD-ROM SC-148C", NULL,       ATA_HORKAGE_NODMA },
3835         { "SAMSUNG CD-ROM SC",  NULL,           ATA_HORKAGE_NODMA },
3836         { "ATAPI CD-ROM DRIVE 40X MAXIMUM",NULL,ATA_HORKAGE_NODMA },
3837         { "_NEC DV5800A",       NULL,           ATA_HORKAGE_NODMA },
3838         { "SAMSUNG CD-ROM SN-124","N001",       ATA_HORKAGE_NODMA },
3839         { "Seagate STT20000A", NULL,            ATA_HORKAGE_NODMA },
3840         { "IOMEGA  ZIP 250       ATAPI", NULL,  ATA_HORKAGE_NODMA }, /* temporary fix */
3841         { "IOMEGA  ZIP 250       ATAPI       Floppy",
3842                                 NULL,           ATA_HORKAGE_NODMA },
3843
3844         /* Weird ATAPI devices */
3845         { "TORiSAN DVD-ROM DRD-N216", NULL,     ATA_HORKAGE_MAX_SEC_128 },
3846
3847         /* Devices we expect to fail diagnostics */
3848
3849         /* Devices where NCQ should be avoided */
3850         /* NCQ is slow */
3851         { "WDC WD740ADFD-00",   NULL,           ATA_HORKAGE_NONCQ },
3852         /* http://thread.gmane.org/gmane.linux.ide/14907 */
3853         { "FUJITSU MHT2060BH",  NULL,           ATA_HORKAGE_NONCQ },
3854         /* NCQ is broken */
3855         { "Maxtor *",           "BANC*",        ATA_HORKAGE_NONCQ },
3856         { "Maxtor 7V300F0",     "VA111630",     ATA_HORKAGE_NONCQ },
3857         { "HITACHI HDS7250SASUN500G 0621KTAWSD", "K2AOAJ0AHITACHI",
3858           ATA_HORKAGE_NONCQ },
3859
3860         /* Blacklist entries taken from Silicon Image 3124/3132
3861            Windows driver .inf file - also several Linux problem reports */
3862         { "HTS541060G9SA00",    "MB3OC60D",     ATA_HORKAGE_NONCQ, },
3863         { "HTS541080G9SA00",    "MB4OC60D",     ATA_HORKAGE_NONCQ, },
3864         { "HTS541010G9SA00",    "MBZOC60D",     ATA_HORKAGE_NONCQ, },
3865         /* Drives which do spurious command completion */
3866         { "HTS541680J9SA00",    "SB2IC7EP",     ATA_HORKAGE_NONCQ, },
3867         { "HTS541612J9SA00",    "SBDIC7JP",     ATA_HORKAGE_NONCQ, },
3868         { "Hitachi HTS541616J9SA00", "SB4OC70P", ATA_HORKAGE_NONCQ, },
3869         { "WDC WD740ADFD-00NLR1", NULL,         ATA_HORKAGE_NONCQ, },
3870         { "FUJITSU MHV2080BH",  "00840028",     ATA_HORKAGE_NONCQ, },
3871         { "ST9160821AS",        "3.CLF",        ATA_HORKAGE_NONCQ, },
3872         { "ST3160812AS",        "3.AD",         ATA_HORKAGE_NONCQ, },
3873         { "SAMSUNG HD401LJ",    "ZZ100-15",     ATA_HORKAGE_NONCQ, },
3874
3875         /* devices which puke on READ_NATIVE_MAX */
3876         { "HDS724040KLSA80",    "KFAOA20N",     ATA_HORKAGE_BROKEN_HPA, },
3877         { "WDC WD3200JD-00KLB0", "WD-WCAMR1130137", ATA_HORKAGE_BROKEN_HPA },
3878         { "WDC WD2500JD-00HBB0", "WD-WMAL71490727", ATA_HORKAGE_BROKEN_HPA },
3879         { "MAXTOR 6L080L4",     "A93.0500",     ATA_HORKAGE_BROKEN_HPA },
3880
3881         /* End Marker */
3882         { }
3883 };
3884
3885 int strn_pattern_cmp(const char *patt, const char *name, int wildchar)
3886 {
3887         const char *p;
3888         int len;
3889
3890         /*
3891          * check for trailing wildcard: *\0
3892          */
3893         p = strchr(patt, wildchar);
3894         if (p && ((*(p + 1)) == 0))
3895                 len = p - patt;
3896         else
3897                 len = strlen(name);
3898
3899         return strncmp(patt, name, len);
3900 }
3901
3902 static unsigned long ata_dev_blacklisted(const struct ata_device *dev)
3903 {
3904         unsigned char model_num[ATA_ID_PROD_LEN + 1];
3905         unsigned char model_rev[ATA_ID_FW_REV_LEN + 1];
3906         const struct ata_blacklist_entry *ad = ata_device_blacklist;
3907
3908         ata_id_c_string(dev->id, model_num, ATA_ID_PROD, sizeof(model_num));
3909         ata_id_c_string(dev->id, model_rev, ATA_ID_FW_REV, sizeof(model_rev));
3910
3911         while (ad->model_num) {
3912                 if (!strn_pattern_cmp(ad->model_num, model_num, '*')) {
3913                         if (ad->model_rev == NULL)
3914                                 return ad->horkage;
3915                         if (!strn_pattern_cmp(ad->model_rev, model_rev, '*'))
3916                                 return ad->horkage;
3917                 }
3918                 ad++;
3919         }
3920         return 0;
3921 }
3922
3923 static int ata_dma_blacklisted(const struct ata_device *dev)
3924 {
3925         /* We don't support polling DMA.
3926          * DMA blacklist those ATAPI devices with CDB-intr (and use PIO)
3927          * if the LLDD handles only interrupts in the HSM_ST_LAST state.
3928          */
3929         if ((dev->link->ap->flags & ATA_FLAG_PIO_POLLING) &&
3930             (dev->flags & ATA_DFLAG_CDB_INTR))
3931                 return 1;
3932         return (dev->horkage & ATA_HORKAGE_NODMA) ? 1 : 0;
3933 }
3934
3935 /**
3936  *      ata_dev_xfermask - Compute supported xfermask of the given device
3937  *      @dev: Device to compute xfermask for
3938  *
3939  *      Compute supported xfermask of @dev and store it in
3940  *      dev->*_mask.  This function is responsible for applying all
3941  *      known limits including host controller limits, device
3942  *      blacklist, etc...
3943  *
3944  *      LOCKING:
3945  *      None.
3946  */
3947 static void ata_dev_xfermask(struct ata_device *dev)
3948 {
3949         struct ata_link *link = dev->link;
3950         struct ata_port *ap = link->ap;
3951         struct ata_host *host = ap->host;
3952         unsigned long xfer_mask;
3953
3954         /* controller modes available */
3955         xfer_mask = ata_pack_xfermask(ap->pio_mask,
3956                                       ap->mwdma_mask, ap->udma_mask);
3957
3958         /* drive modes available */
3959         xfer_mask &= ata_pack_xfermask(dev->pio_mask,
3960                                        dev->mwdma_mask, dev->udma_mask);
3961         xfer_mask &= ata_id_xfermask(dev->id);
3962
3963         /*
3964          *      CFA Advanced TrueIDE timings are not allowed on a shared
3965          *      cable
3966          */
3967         if (ata_dev_pair(dev)) {
3968                 /* No PIO5 or PIO6 */
3969                 xfer_mask &= ~(0x03 << (ATA_SHIFT_PIO + 5));
3970                 /* No MWDMA3 or MWDMA 4 */
3971                 xfer_mask &= ~(0x03 << (ATA_SHIFT_MWDMA + 3));
3972         }
3973
3974         if (ata_dma_blacklisted(dev)) {
3975                 xfer_mask &= ~(ATA_MASK_MWDMA | ATA_MASK_UDMA);
3976                 ata_dev_printk(dev, KERN_WARNING,
3977                                "device is on DMA blacklist, disabling DMA\n");
3978         }
3979
3980         if ((host->flags & ATA_HOST_SIMPLEX) &&
3981             host->simplex_claimed && host->simplex_claimed != ap) {
3982                 xfer_mask &= ~(ATA_MASK_MWDMA | ATA_MASK_UDMA);
3983                 ata_dev_printk(dev, KERN_WARNING, "simplex DMA is claimed by "
3984                                "other device, disabling DMA\n");
3985         }
3986
3987         if (ap->flags & ATA_FLAG_NO_IORDY)
3988                 xfer_mask &= ata_pio_mask_no_iordy(dev);
3989
3990         if (ap->ops->mode_filter)
3991                 xfer_mask = ap->ops->mode_filter(dev, xfer_mask);
3992
3993         /* Apply cable rule here.  Don't apply it early because when
3994          * we handle hot plug the cable type can itself change.
3995          * Check this last so that we know if the transfer rate was
3996          * solely limited by the cable.
3997          * Unknown or 80 wire cables reported host side are checked
3998          * drive side as well. Cases where we know a 40wire cable
3999          * is used safely for 80 are not checked here.
4000          */
4001         if (xfer_mask & (0xF8 << ATA_SHIFT_UDMA))
4002                 /* UDMA/44 or higher would be available */
4003                 if((ap->cbl == ATA_CBL_PATA40) ||
4004                     (ata_drive_40wire(dev->id) &&
4005                      (ap->cbl == ATA_CBL_PATA_UNK ||
4006                      ap->cbl == ATA_CBL_PATA80))) {
4007                         ata_dev_printk(dev, KERN_WARNING,
4008                                  "limited to UDMA/33 due to 40-wire cable\n");
4009                         xfer_mask &= ~(0xF8 << ATA_SHIFT_UDMA);
4010                 }
4011
4012         ata_unpack_xfermask(xfer_mask, &dev->pio_mask,
4013                             &dev->mwdma_mask, &dev->udma_mask);
4014 }
4015
4016 /**
4017  *      ata_dev_set_xfermode - Issue SET FEATURES - XFER MODE command
4018  *      @dev: Device to which command will be sent
4019  *
4020  *      Issue SET FEATURES - XFER MODE command to device @dev
4021  *      on port @ap.
4022  *
4023  *      LOCKING:
4024  *      PCI/etc. bus probe sem.
4025  *
4026  *      RETURNS:
4027  *      0 on success, AC_ERR_* mask otherwise.
4028  */
4029
4030 static unsigned int ata_dev_set_xfermode(struct ata_device *dev)
4031 {
4032         struct ata_taskfile tf;
4033         unsigned int err_mask;
4034
4035         /* set up set-features taskfile */
4036         DPRINTK("set features - xfer mode\n");
4037
4038         /* Some controllers and ATAPI devices show flaky interrupt
4039          * behavior after setting xfer mode.  Use polling instead.
4040          */
4041         ata_tf_init(dev, &tf);
4042         tf.command = ATA_CMD_SET_FEATURES;
4043         tf.feature = SETFEATURES_XFER;
4044         tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE | ATA_TFLAG_POLLING;
4045         tf.protocol = ATA_PROT_NODATA;
4046         tf.nsect = dev->xfer_mode;
4047
4048         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0);
4049
4050         DPRINTK("EXIT, err_mask=%x\n", err_mask);
4051         return err_mask;
4052 }
4053
4054 /**
4055  *      ata_dev_set_AN - Issue SET FEATURES - SATA FEATURES
4056  *      @dev: Device to which command will be sent
4057  *      @enable: Whether to enable or disable the feature
4058  *
4059  *      Issue SET FEATURES - SATA FEATURES command to device @dev
4060  *      on port @ap with sector count set to indicate Asynchronous
4061  *      Notification feature
4062  *
4063  *      LOCKING:
4064  *      PCI/etc. bus probe sem.
4065  *
4066  *      RETURNS:
4067  *      0 on success, AC_ERR_* mask otherwise.
4068  */
4069 static unsigned int ata_dev_set_AN(struct ata_device *dev, u8 enable)
4070 {
4071         struct ata_taskfile tf;
4072         unsigned int err_mask;
4073
4074         /* set up set-features taskfile */
4075         DPRINTK("set features - SATA features\n");
4076
4077         ata_tf_init(dev, &tf);
4078         tf.command = ATA_CMD_SET_FEATURES;
4079         tf.feature = enable;
4080         tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
4081         tf.protocol = ATA_PROT_NODATA;
4082         tf.nsect = SATA_AN;
4083
4084         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0);
4085
4086         DPRINTK("EXIT, err_mask=%x\n", err_mask);
4087         return err_mask;
4088 }
4089
4090 /**
4091  *      ata_dev_init_params - Issue INIT DEV PARAMS command
4092  *      @dev: Device to which command will be sent
4093  *      @heads: Number of heads (taskfile parameter)
4094  *      @sectors: Number of sectors (taskfile parameter)
4095  *
4096  *      LOCKING:
4097  *      Kernel thread context (may sleep)
4098  *
4099  *      RETURNS:
4100  *      0 on success, AC_ERR_* mask otherwise.
4101  */
4102 static unsigned int ata_dev_init_params(struct ata_device *dev,
4103                                         u16 heads, u16 sectors)
4104 {
4105         struct ata_taskfile tf;
4106         unsigned int err_mask;
4107
4108         /* Number of sectors per track 1-255. Number of heads 1-16 */
4109         if (sectors < 1 || sectors > 255 || heads < 1 || heads > 16)
4110                 return AC_ERR_INVALID;
4111
4112         /* set up init dev params taskfile */
4113         DPRINTK("init dev params \n");
4114
4115         ata_tf_init(dev, &tf);
4116         tf.command = ATA_CMD_INIT_DEV_PARAMS;
4117         tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
4118         tf.protocol = ATA_PROT_NODATA;
4119         tf.nsect = sectors;
4120         tf.device |= (heads - 1) & 0x0f; /* max head = num. of heads - 1 */
4121
4122         err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0);
4123         /* A clean abort indicates an original or just out of spec drive
4124            and we should continue as we issue the setup based on the
4125            drive reported working geometry */
4126         if (err_mask == AC_ERR_DEV && (tf.feature & ATA_ABORTED))
4127                 err_mask = 0;
4128
4129         DPRINTK("EXIT, err_mask=%x\n", err_mask);
4130         return err_mask;
4131 }
4132
4133 /**
4134  *      ata_sg_clean - Unmap DMA memory associated with command
4135  *      @qc: Command containing DMA memory to be released
4136  *
4137  *      Unmap all mapped DMA memory associated with this command.
4138  *
4139  *      LOCKING:
4140  *      spin_lock_irqsave(host lock)
4141  */
4142 void ata_sg_clean(struct ata_queued_cmd *qc)
4143 {
4144         struct ata_port *ap = qc->ap;
4145         struct scatterlist *sg = qc->__sg;
4146         int dir = qc->dma_dir;
4147         void *pad_buf = NULL;
4148
4149         WARN_ON(!(qc->flags & ATA_QCFLAG_DMAMAP));
4150         WARN_ON(sg == NULL);
4151
4152         if (qc->flags & ATA_QCFLAG_SINGLE)
4153                 WARN_ON(qc->n_elem > 1);
4154
4155         VPRINTK("unmapping %u sg elements\n", qc->n_elem);
4156
4157         /* if we padded the buffer out to 32-bit bound, and data
4158          * xfer direction is from-device, we must copy from the
4159          * pad buffer back into the supplied buffer
4160          */
4161         if (qc->pad_len && !(qc->tf.flags & ATA_TFLAG_WRITE))
4162                 pad_buf = ap->pad + (qc->tag * ATA_DMA_PAD_SZ);
4163
4164         if (qc->flags & ATA_QCFLAG_SG) {
4165                 if (qc->n_elem)
4166                         dma_unmap_sg(ap->dev, sg, qc->n_elem, dir);
4167                 /* restore last sg */
4168                 sg[qc->orig_n_elem - 1].length += qc->pad_len;
4169                 if (pad_buf) {
4170                         struct scatterlist *psg = &qc->pad_sgent;
4171                         void *addr = kmap_atomic(psg->page, KM_IRQ0);
4172                         memcpy(addr + psg->offset, pad_buf, qc->pad_len);
4173                         kunmap_atomic(addr, KM_IRQ0);
4174                 }
4175         } else {
4176                 if (qc->n_elem)
4177                         dma_unmap_single(ap->dev,
4178                                 sg_dma_address(&sg[0]), sg_dma_len(&sg[0]),
4179                                 dir);
4180                 /* restore sg */
4181                 sg->length += qc->pad_len;
4182                 if (pad_buf)
4183                         memcpy(qc->buf_virt + sg->length - qc->pad_len,
4184                                pad_buf, qc->pad_len);
4185         }
4186
4187         qc->flags &= ~ATA_QCFLAG_DMAMAP;
4188         qc->__sg = NULL;
4189 }
4190
4191 /**
4192  *      ata_fill_sg - Fill PCI IDE PRD table
4193  *      @qc: Metadata associated with taskfile to be transferred
4194  *
4195  *      Fill PCI IDE PRD (scatter-gather) table with segments
4196  *      associated with the current disk command.
4197  *
4198  *      LOCKING:
4199  *      spin_lock_irqsave(host lock)
4200  *
4201  */
4202 static void ata_fill_sg(struct ata_queued_cmd *qc)
4203 {
4204         struct ata_port *ap = qc->ap;
4205         struct scatterlist *sg;
4206         unsigned int idx;
4207
4208         WARN_ON(qc->__sg == NULL);
4209         WARN_ON(qc->n_elem == 0 && qc->pad_len == 0);
4210
4211         idx = 0;
4212         ata_for_each_sg(sg, qc) {
4213                 u32 addr, offset;
4214                 u32 sg_len, len;
4215
4216                 /* determine if physical DMA addr spans 64K boundary.
4217                  * Note h/w doesn't support 64-bit, so we unconditionally
4218                  * truncate dma_addr_t to u32.
4219                  */
4220                 addr = (u32) sg_dma_address(sg);
4221                 sg_len = sg_dma_len(sg);
4222
4223                 while (sg_len) {
4224                         offset = addr & 0xffff;
4225                         len = sg_len;
4226                         if ((offset + sg_len) > 0x10000)
4227                                 len = 0x10000 - offset;
4228
4229                         ap->prd[idx].addr = cpu_to_le32(addr);
4230                         ap->prd[idx].flags_len = cpu_to_le32(len & 0xffff);
4231                         VPRINTK("PRD[%u] = (0x%X, 0x%X)\n", idx, addr, len);
4232
4233                         idx++;
4234                         sg_len -= len;
4235                         addr += len;
4236                 }
4237         }
4238
4239         if (idx)
4240                 ap->prd[idx - 1].flags_len |= cpu_to_le32(ATA_PRD_EOT);
4241 }
4242
4243 /**
4244  *      ata_fill_sg_dumb - Fill PCI IDE PRD table
4245  *      @qc: Metadata associated with taskfile to be transferred
4246  *
4247  *      Fill PCI IDE PRD (scatter-gather) table with segments
4248  *      associated with the current disk command. Perform the fill
4249  *      so that we avoid writing any length 64K records for
4250  *      controllers that don't follow the spec.
4251  *
4252  *      LOCKING:
4253  *      spin_lock_irqsave(host lock)
4254  *
4255  */
4256 static void ata_fill_sg_dumb(struct ata_queued_cmd *qc)
4257 {
4258         struct ata_port *ap = qc->ap;
4259         struct scatterlist *sg;
4260         unsigned int idx;
4261
4262         WARN_ON(qc->__sg == NULL);
4263         WARN_ON(qc->n_elem == 0 && qc->pad_len == 0);
4264
4265         idx = 0;
4266         ata_for_each_sg(sg, qc) {
4267                 u32 addr, offset;
4268                 u32 sg_len, len, blen;
4269
4270                 /* determine if physical DMA addr spans 64K boundary.
4271                  * Note h/w doesn't support 64-bit, so we unconditionally
4272                  * truncate dma_addr_t to u32.
4273                  */
4274                 addr = (u32) sg_dma_address(sg);
4275                 sg_len = sg_dma_len(sg);
4276
4277                 while (sg_len) {
4278                         offset = addr & 0xffff;
4279                         len = sg_len;
4280                         if ((offset + sg_len) > 0x10000)
4281                                 len = 0x10000 - offset;
4282
4283                         blen = len & 0xffff;
4284                         ap->prd[idx].addr = cpu_to_le32(addr);
4285                         if (blen == 0) {
4286                            /* Some PATA chipsets like the CS5530 can't
4287                               cope with 0x0000 meaning 64K as the spec says */
4288                                 ap->prd[idx].flags_len = cpu_to_le32(0x8000);
4289                                 blen = 0x8000;
4290                                 ap->prd[++idx].addr = cpu_to_le32(addr + 0x8000);
4291                         }
4292                         ap->prd[idx].flags_len = cpu_to_le32(blen);
4293                         VPRINTK("PRD[%u] = (0x%X, 0x%X)\n", idx, addr, len);
4294
4295                         idx++;
4296                         sg_len -= len;
4297                         addr += len;
4298                 }
4299         }
4300
4301         if (idx)
4302                 ap->prd[idx - 1].flags_len |= cpu_to_le32(ATA_PRD_EOT);
4303 }
4304
4305 /**
4306  *      ata_check_atapi_dma - Check whether ATAPI DMA can be supported
4307  *      @qc: Metadata associated with taskfile to check
4308  *
4309  *      Allow low-level driver to filter ATA PACKET commands, returning
4310  *      a status indicating whether or not it is OK to use DMA for the
4311  *      supplied PACKET command.
4312  *
4313  *      LOCKING:
4314  *      spin_lock_irqsave(host lock)
4315  *
4316  *      RETURNS: 0 when ATAPI DMA can be used
4317  *               nonzero otherwise
4318  */
4319 int ata_check_atapi_dma(struct ata_queued_cmd *qc)
4320 {
4321         struct ata_port *ap = qc->ap;
4322
4323         /* Don't allow DMA if it isn't multiple of 16 bytes.  Quite a
4324          * few ATAPI devices choke on such DMA requests.
4325          */
4326         if (unlikely(qc->nbytes & 15))
4327                 return 1;
4328
4329         if (ap->ops->check_atapi_dma)
4330                 return ap->ops->check_atapi_dma(qc);
4331
4332         return 0;
4333 }
4334
4335 /**
4336  *      ata_qc_prep - Prepare taskfile for submission
4337  *      @qc: Metadata associated with taskfile to be prepared
4338  *
4339  *      Prepare ATA taskfile for submission.
4340  *
4341  *      LOCKING:
4342  *      spin_lock_irqsave(host lock)
4343  */
4344 void ata_qc_prep(struct ata_queued_cmd *qc)
4345 {
4346         if (!(qc->flags & ATA_QCFLAG_DMAMAP))
4347                 return;
4348
4349         ata_fill_sg(qc);
4350 }
4351
4352 /**
4353  *      ata_dumb_qc_prep - Prepare taskfile for submission
4354  *      @qc: Metadata associated with taskfile to be prepared
4355  *
4356  *      Prepare ATA taskfile for submission.
4357  *
4358  *      LOCKING:
4359  *      spin_lock_irqsave(host lock)
4360  */
4361 void ata_dumb_qc_prep(struct ata_queued_cmd *qc)
4362 {
4363         if (!(qc->flags & ATA_QCFLAG_DMAMAP))
4364                 return;
4365
4366         ata_fill_sg_dumb(qc);
4367 }
4368
4369 void ata_noop_qc_prep(struct ata_queued_cmd *qc) { }
4370
4371 /**
4372  *      ata_sg_init_one - Associate command with memory buffer
4373  *      @qc: Command to be associated
4374  *      @buf: Memory buffer
4375  *      @buflen: Length of memory buffer, in bytes.
4376  *
4377  *      Initialize the data-related elements of queued_cmd @qc
4378  *      to point to a single memory buffer, @buf of byte length @buflen.
4379  *
4380  *      LOCKING:
4381  *      spin_lock_irqsave(host lock)
4382  */
4383
4384 void ata_sg_init_one(struct ata_queued_cmd *qc, void *buf, unsigned int buflen)
4385 {
4386         qc->flags |= ATA_QCFLAG_SINGLE;
4387
4388         qc->__sg = &qc->sgent;
4389         qc->n_elem = 1;
4390         qc->orig_n_elem = 1;
4391         qc->buf_virt = buf;
4392         qc->nbytes = buflen;
4393
4394         sg_init_one(&qc->sgent, buf, buflen);
4395 }
4396
4397 /**
4398  *      ata_sg_init - Associate command with scatter-gather table.
4399  *      @qc: Command to be associated
4400  *      @sg: Scatter-gather table.
4401  *      @n_elem: Number of elements in s/g table.
4402  *
4403  *      Initialize the data-related elements of queued_cmd @qc
4404  *      to point to a scatter-gather table @sg, containing @n_elem
4405  *      elements.
4406  *
4407  *      LOCKING:
4408  *      spin_lock_irqsave(host lock)
4409  */
4410
4411 void ata_sg_init(struct ata_queued_cmd *qc, struct scatterlist *sg,
4412                  unsigned int n_elem)
4413 {
4414         qc->flags |= ATA_QCFLAG_SG;
4415         qc->__sg = sg;
4416         qc->n_elem = n_elem;
4417         qc->orig_n_elem = n_elem;
4418 }
4419
4420 /**
4421  *      ata_sg_setup_one - DMA-map the memory buffer associated with a command.
4422  *      @qc: Command with memory buffer to be mapped.
4423  *
4424  *      DMA-map the memory buffer associated with queued_cmd @qc.
4425  *
4426  *      LOCKING:
4427  *      spin_lock_irqsave(host lock)
4428  *
4429  *      RETURNS:
4430  *      Zero on success, negative on error.
4431  */
4432
4433 static int ata_sg_setup_one(struct ata_queued_cmd *qc)
4434 {
4435         struct ata_port *ap = qc->ap;
4436         int dir = qc->dma_dir;
4437         struct scatterlist *sg = qc->__sg;
4438         dma_addr_t dma_address;
4439         int trim_sg = 0;
4440
4441         /* we must lengthen transfers to end on a 32-bit boundary */
4442         qc->pad_len = sg->length & 3;
4443         if (qc->pad_len) {
4444                 void *pad_buf = ap->pad + (qc->tag * ATA_DMA_PAD_SZ);
4445                 struct scatterlist *psg = &qc->pad_sgent;
4446
4447                 WARN_ON(qc->dev->class != ATA_DEV_ATAPI);
4448
4449                 memset(pad_buf, 0, ATA_DMA_PAD_SZ);
4450
4451                 if (qc->tf.flags & ATA_TFLAG_WRITE)
4452                         memcpy(pad_buf, qc->buf_virt + sg->length - qc->pad_len,
4453                                qc->pad_len);
4454
4455                 sg_dma_address(psg) = ap->pad_dma + (qc->tag * ATA_DMA_PAD_SZ);
4456                 sg_dma_len(psg) = ATA_DMA_PAD_SZ;
4457                 /* trim sg */
4458                 sg->length -= qc->pad_len;
4459                 if (sg->length == 0)
4460                         trim_sg = 1;
4461
4462                 DPRINTK("padding done, sg->length=%u pad_len=%u\n",
4463                         sg->length, qc->pad_len);
4464         }
4465
4466         if (trim_sg) {
4467                 qc->n_elem--;
4468                 goto skip_map;
4469         }
4470
4471         dma_address = dma_map_single(ap->dev, qc->buf_virt,
4472                                      sg->length, dir);
4473         if (dma_mapping_error(dma_address)) {
4474                 /* restore sg */
4475                 sg->length += qc->pad_len;
4476                 return -1;
4477         }
4478
4479         sg_dma_address(sg) = dma_address;
4480         sg_dma_len(sg) = sg->length;
4481
4482 skip_map:
4483         DPRINTK("mapped buffer of %d bytes for %s\n", sg_dma_len(sg),
4484                 qc->tf.flags & ATA_TFLAG_WRITE ? "write" : "read");
4485
4486         return 0;
4487 }
4488
4489 /**
4490  *      ata_sg_setup - DMA-map the scatter-gather table associated with a command.
4491  *      @qc: Command with scatter-gather table to be mapped.
4492  *
4493  *      DMA-map the scatter-gather table associated with queued_cmd @qc.
4494  *
4495  *      LOCKING:
4496  *      spin_lock_irqsave(host lock)
4497  *
4498  *      RETURNS:
4499  *      Zero on success, negative on error.
4500  *
4501  */
4502
4503 static int ata_sg_setup(struct ata_queued_cmd *qc)
4504 {
4505         struct ata_port *ap = qc->ap;
4506         struct scatterlist *sg = qc->__sg;
4507         struct scatterlist *lsg = &sg[qc->n_elem - 1];
4508         int n_elem, pre_n_elem, dir, trim_sg = 0;
4509
4510         VPRINTK("ENTER, ata%u\n", ap->print_id);
4511         WARN_ON(!(qc->flags & ATA_QCFLAG_SG));
4512
4513         /* we must lengthen transfers to end on a 32-bit boundary */
4514         qc->pad_len = lsg->length & 3;
4515         if (qc->pad_len) {
4516                 void *pad_buf = ap->pad + (qc->tag * ATA_DMA_PAD_SZ);
4517                 struct scatterlist *psg = &qc->pad_sgent;
4518                 unsigned int offset;
4519
4520                 WARN_ON(qc->dev->class != ATA_DEV_ATAPI);
4521
4522                 memset(pad_buf, 0, ATA_DMA_PAD_SZ);
4523
4524                 /*
4525                  * psg->page/offset are used to copy to-be-written
4526                  * data in this function or read data in ata_sg_clean.
4527                  */
4528                 offset = lsg->offset + lsg->length - qc->pad_len;
4529                 psg->page = nth_page(lsg->page, offset >> PAGE_SHIFT);
4530                 psg->offset = offset_in_page(offset);
4531
4532                 if (qc->tf.flags & ATA_TFLAG_WRITE) {
4533                         void *addr = kmap_atomic(psg->page, KM_IRQ0);
4534                         memcpy(pad_buf, addr + psg->offset, qc->pad_len);
4535                         kunmap_atomic(addr, KM_IRQ0);
4536                 }
4537
4538                 sg_dma_address(psg) = ap->pad_dma + (qc->tag * ATA_DMA_PAD_SZ);
4539                 sg_dma_len(psg) = ATA_DMA_PAD_SZ;
4540                 /* trim last sg */
4541                 lsg->length -= qc->pad_len;
4542                 if (lsg->length == 0)
4543                         trim_sg = 1;
4544
4545                 DPRINTK("padding done, sg[%d].length=%u pad_len=%u\n",
4546                         qc->n_elem - 1, lsg->length, qc->pad_len);
4547         }
4548
4549         pre_n_elem = qc->n_elem;
4550         if (trim_sg && pre_n_elem)
4551                 pre_n_elem--;
4552
4553         if (!pre_n_elem) {
4554                 n_elem = 0;
4555                 goto skip_map;
4556         }
4557
4558         dir = qc->dma_dir;
4559         n_elem = dma_map_sg(ap->dev, sg, pre_n_elem, dir);
4560         if (n_elem < 1) {
4561                 /* restore last sg */
4562                 lsg->length += qc->pad_len;
4563                 return -1;
4564         }
4565
4566         DPRINTK("%d sg elements mapped\n", n_elem);
4567
4568 skip_map:
4569         qc->n_elem = n_elem;
4570
4571         return 0;
4572 }
4573
4574 /**
4575  *      swap_buf_le16 - swap halves of 16-bit words in place
4576  *      @buf:  Buffer to swap
4577  *      @buf_words:  Number of 16-bit words in buffer.
4578  *
4579  *      Swap halves of 16-bit words if needed to convert from
4580  *      little-endian byte order to native cpu byte order, or
4581  *      vice-versa.
4582  *
4583  *      LOCKING:
4584  *      Inherited from caller.
4585  */
4586 void swap_buf_le16(u16 *buf, unsigned int buf_words)
4587 {
4588 #ifdef __BIG_ENDIAN
4589         unsigned int i;
4590
4591         for (i = 0; i < buf_words; i++)
4592                 buf[i] = le16_to_cpu(buf[i]);
4593 #endif /* __BIG_ENDIAN */
4594 }
4595
4596 /**
4597  *      ata_data_xfer - Transfer data by PIO
4598  *      @adev: device to target
4599  *      @buf: data buffer
4600  *      @buflen: buffer length
4601  *      @write_data: read/write
4602  *
4603  *      Transfer data from/to the device data register by PIO.
4604  *
4605  *      LOCKING:
4606  *      Inherited from caller.
4607  */
4608 void ata_data_xfer(struct ata_device *adev, unsigned char *buf,
4609                    unsigned int buflen, int write_data)
4610 {
4611         struct ata_port *ap = adev->link->ap;
4612         unsigned int words = buflen >> 1;
4613
4614         /* Transfer multiple of 2 bytes */
4615         if (write_data)
4616                 iowrite16_rep(ap->ioaddr.data_addr, buf, words);
4617         else
4618                 ioread16_rep(ap->ioaddr.data_addr, buf, words);
4619
4620         /* Transfer trailing 1 byte, if any. */
4621         if (unlikely(buflen & 0x01)) {
4622                 u16 align_buf[1] = { 0 };
4623                 unsigned char *trailing_buf = buf + buflen - 1;
4624
4625                 if (write_data) {
4626                         memcpy(align_buf, trailing_buf, 1);
4627                         iowrite16(le16_to_cpu(align_buf[0]), ap->ioaddr.data_addr);
4628                 } else {
4629                         align_buf[0] = cpu_to_le16(ioread16(ap->ioaddr.data_addr));
4630                         memcpy(trailing_buf, align_buf, 1);
4631                 }
4632         }
4633 }
4634
4635 /**
4636  *      ata_data_xfer_noirq - Transfer data by PIO
4637  *      @adev: device to target
4638  *      @buf: data buffer
4639  *      @buflen: buffer length
4640  *      @write_data: read/write
4641  *
4642  *      Transfer data from/to the device data register by PIO. Do the
4643  *      transfer with interrupts disabled.
4644  *
4645  *      LOCKING:
4646  *      Inherited from caller.
4647  */
4648 void ata_data_xfer_noirq(struct ata_device *adev, unsigned char *buf,
4649                          unsigned int buflen, int write_data)
4650 {
4651         unsigned long flags;
4652         local_irq_save(flags);
4653         ata_data_xfer(adev, buf, buflen, write_data);
4654         local_irq_restore(flags);
4655 }
4656
4657
4658 /**
4659  *      ata_pio_sector - Transfer a sector of data.
4660  *      @qc: Command on going
4661  *
4662  *      Transfer qc->sect_size bytes of data from/to the ATA device.
4663  *
4664  *      LOCKING:
4665  *      Inherited from caller.
4666  */
4667
4668 static void ata_pio_sector(struct ata_queued_cmd *qc)
4669 {
4670         int do_write = (qc->tf.flags & ATA_TFLAG_WRITE);
4671         struct scatterlist *sg = qc->__sg;
4672         struct ata_port *ap = qc->ap;
4673         struct page *page;
4674         unsigned int offset;
4675         unsigned char *buf;
4676
4677         if (qc->curbytes == qc->nbytes - qc->sect_size)
4678                 ap->hsm_task_state = HSM_ST_LAST;
4679
4680         page = sg[qc->cursg].page;
4681         offset = sg[qc->cursg].offset + qc->cursg_ofs;
4682
4683         /* get the current page and offset */
4684         page = nth_page(page, (offset >> PAGE_SHIFT));
4685         offset %= PAGE_SIZE;
4686
4687         DPRINTK("data %s\n", qc->tf.flags & ATA_TFLAG_WRITE ? "write" : "read");
4688
4689         if (PageHighMem(page)) {
4690                 unsigned long flags;
4691
4692                 /* FIXME: use a bounce buffer */
4693                 local_irq_save(flags);
4694                 buf = kmap_atomic(page, KM_IRQ0);
4695
4696                 /* do the actual data transfer */
4697                 ap->ops->data_xfer(qc->dev, buf + offset, qc->sect_size, do_write);
4698
4699                 kunmap_atomic(buf, KM_IRQ0);
4700                 local_irq_restore(flags);
4701         } else {
4702                 buf = page_address(page);
4703                 ap->ops->data_xfer(qc->dev, buf + offset, qc->sect_size, do_write);
4704         }
4705
4706         qc->curbytes += qc->sect_size;
4707         qc->cursg_ofs += qc->sect_size;
4708
4709         if (qc->cursg_ofs == (&sg[qc->cursg])->length) {
4710                 qc->cursg++;
4711                 qc->cursg_ofs = 0;
4712         }
4713 }
4714
4715 /**
4716  *      ata_pio_sectors - Transfer one or many sectors.
4717  *      @qc: Command on going
4718  *
4719  *      Transfer one or many sectors of data from/to the
4720  *      ATA device for the DRQ request.
4721  *
4722  *      LOCKING:
4723  *      Inherited from caller.
4724  */
4725
4726 static void ata_pio_sectors(struct ata_queued_cmd *qc)
4727 {
4728         if (is_multi_taskfile(&qc->tf)) {
4729                 /* READ/WRITE MULTIPLE */
4730                 unsigned int nsect;
4731
4732                 WARN_ON(qc->dev->multi_count == 0);
4733
4734                 nsect = min((qc->nbytes - qc->curbytes) / qc->sect_size,
4735                             qc->dev->multi_count);
4736                 while (nsect--)
4737                         ata_pio_sector(qc);
4738         } else
4739                 ata_pio_sector(qc);
4740
4741         ata_altstatus(qc->ap); /* flush */
4742 }
4743
4744 /**
4745  *      atapi_send_cdb - Write CDB bytes to hardware
4746  *      @ap: Port to which ATAPI device is attached.
4747  *      @qc: Taskfile currently active
4748  *
4749  *      When device has indicated its readiness to accept
4750  *      a CDB, this function is called.  Send the CDB.
4751  *
4752  *      LOCKING:
4753  *      caller.
4754  */
4755
4756 static void atapi_send_cdb(struct ata_port *ap, struct ata_queued_cmd *qc)
4757 {
4758         /* send SCSI cdb */
4759         DPRINTK("send cdb\n");
4760         WARN_ON(qc->dev->cdb_len < 12);
4761
4762         ap->ops->data_xfer(qc->dev, qc->cdb, qc->dev->cdb_len, 1);
4763         ata_altstatus(ap); /* flush */
4764
4765         switch (qc->tf.protocol) {
4766         case ATA_PROT_ATAPI:
4767                 ap->hsm_task_state = HSM_ST;
4768                 break;
4769         case ATA_PROT_ATAPI_NODATA:
4770                 ap->hsm_task_state = HSM_ST_LAST;
4771                 break;
4772         case ATA_PROT_ATAPI_DMA:
4773                 ap->hsm_task_state = HSM_ST_LAST;
4774                 /* initiate bmdma */
4775                 ap->ops->bmdma_start(qc);
4776                 break;
4777         }
4778 }
4779
4780 /**
4781  *      __atapi_pio_bytes - Transfer data from/to the ATAPI device.
4782  *      @qc: Command on going
4783  *      @bytes: number of bytes
4784  *
4785  *      Transfer Transfer data from/to the ATAPI device.
4786  *
4787  *      LOCKING:
4788  *      Inherited from caller.
4789  *
4790  */
4791
4792 static void __atapi_pio_bytes(struct ata_queued_cmd *qc, unsigned int bytes)
4793 {
4794         int do_write = (qc->tf.flags & ATA_TFLAG_WRITE);
4795         struct scatterlist *sg = qc->__sg;
4796         struct ata_port *ap = qc->ap;
4797         struct page *page;
4798         unsigned char *buf;
4799         unsigned int offset, count;
4800
4801         if (qc->curbytes + bytes >= qc->nbytes)
4802                 ap->hsm_task_state = HSM_ST_LAST;
4803
4804 next_sg:
4805         if (unlikely(qc->cursg >= qc->n_elem)) {
4806                 /*
4807                  * The end of qc->sg is reached and the device expects
4808                  * more data to transfer. In order not to overrun qc->sg
4809                  * and fulfill length specified in the byte count register,
4810                  *    - for read case, discard trailing data from the device
4811                  *    - for write case, padding zero data to the device
4812                  */
4813                 u16 pad_buf[1] = { 0 };
4814                 unsigned int words = bytes >> 1;
4815                 unsigned int i;
4816
4817                 if (words) /* warning if bytes > 1 */
4818                         ata_dev_printk(qc->dev, KERN_WARNING,
4819                                        "%u bytes trailing data\n", bytes);
4820
4821                 for (i = 0; i < words; i++)
4822                         ap->ops->data_xfer(qc->dev, (unsigned char*)pad_buf, 2, do_write);
4823
4824                 ap->hsm_task_state = HSM_ST_LAST;
4825                 return;
4826         }
4827
4828         sg = &qc->__sg[qc->cursg];
4829
4830         page = sg->page;
4831         offset = sg->offset + qc->cursg_ofs;
4832
4833         /* get the current page and offset */
4834         page = nth_page(page, (offset >> PAGE_SHIFT));
4835         offset %= PAGE_SIZE;
4836
4837         /* don't overrun current sg */
4838         count = min(sg->length - qc->cursg_ofs, bytes);
4839
4840         /* don't cross page boundaries */
4841         count = min(count, (unsigned int)PAGE_SIZE - offset);
4842
4843         DPRINTK("data %s\n", qc->tf.flags & ATA_TFLAG_WRITE ? "write" : "read");
4844
4845         if (PageHighMem(page)) {
4846                 unsigned long flags;
4847
4848                 /* FIXME: use bounce buffer */
4849                 local_irq_save(flags);
4850                 buf = kmap_atomic(page, KM_IRQ0);
4851
4852                 /* do the actual data transfer */
4853                 ap->ops->data_xfer(qc->dev,  buf + offset, count, do_write);
4854
4855                 kunmap_atomic(buf, KM_IRQ0);
4856                 local_irq_restore(flags);
4857         } else {
4858                 buf = page_address(page);
4859                 ap->ops->data_xfer(qc->dev,  buf + offset, count, do_write);
4860         }
4861
4862         bytes -= count;
4863         qc->curbytes += count;
4864         qc->cursg_ofs += count;
4865
4866         if (qc->cursg_ofs == sg->length) {
4867                 qc->cursg++;
4868                 qc->cursg_ofs = 0;
4869         }
4870
4871         if (bytes)
4872                 goto next_sg;
4873 }
4874
4875 /**
4876  *      atapi_pio_bytes - Transfer data from/to the ATAPI device.
4877  *      @qc: Command on going
4878  *
4879  *      Transfer Transfer data from/to the ATAPI device.
4880  *
4881  *      LOCKING:
4882  *      Inherited from caller.
4883  */
4884
4885 static void atapi_pio_bytes(struct ata_queued_cmd *qc)
4886 {
4887         struct ata_port *ap = qc->ap;
4888         struct ata_device *dev = qc->dev;
4889         unsigned int ireason, bc_lo, bc_hi, bytes;
4890         int i_write, do_write = (qc->tf.flags & ATA_TFLAG_WRITE) ? 1 : 0;
4891
4892         /* Abuse qc->result_tf for temp storage of intermediate TF
4893          * here to save some kernel stack usage.
4894          * For normal completion, qc->result_tf is not relevant. For
4895          * error, qc->result_tf is later overwritten by ata_qc_complete().
4896          * So, the correctness of qc->result_tf is not affected.
4897          */
4898         ap->ops->tf_read(ap, &qc->result_tf);
4899         ireason = qc->result_tf.nsect;
4900         bc_lo = qc->result_tf.lbam;
4901         bc_hi = qc->result_tf.lbah;
4902         bytes = (bc_hi << 8) | bc_lo;
4903
4904         /* shall be cleared to zero, indicating xfer of data */
4905         if (ireason & (1 << 0))
4906                 goto err_out;
4907
4908         /* make sure transfer direction matches expected */
4909         i_write = ((ireason & (1 << 1)) == 0) ? 1 : 0;
4910         if (do_write != i_write)
4911                 goto err_out;
4912
4913         VPRINTK("ata%u: xfering %d bytes\n", ap->print_id, bytes);
4914
4915         __atapi_pio_bytes(qc, bytes);
4916         ata_altstatus(ap); /* flush */
4917
4918         return;
4919
4920 err_out:
4921         ata_dev_printk(dev, KERN_INFO, "ATAPI check failed\n");
4922         qc->err_mask |= AC_ERR_HSM;
4923         ap->hsm_task_state = HSM_ST_ERR;
4924 }
4925
4926 /**
4927  *      ata_hsm_ok_in_wq - Check if the qc can be handled in the workqueue.
4928  *      @ap: the target ata_port
4929  *      @qc: qc on going
4930  *
4931  *      RETURNS:
4932  *      1 if ok in workqueue, 0 otherwise.
4933  */
4934
4935 static inline int ata_hsm_ok_in_wq(struct ata_port *ap, struct ata_queued_cmd *qc)
4936 {
4937         if (qc->tf.flags & ATA_TFLAG_POLLING)
4938                 return 1;
4939
4940         if (ap->hsm_task_state == HSM_ST_FIRST) {
4941                 if (qc->tf.protocol == ATA_PROT_PIO &&
4942                     (qc->tf.flags & ATA_TFLAG_WRITE))
4943                     return 1;
4944
4945                 if (is_atapi_taskfile(&qc->tf) &&
4946                     !(qc->dev->flags & ATA_DFLAG_CDB_INTR))
4947                         return 1;
4948         }
4949
4950         return 0;
4951 }
4952
4953 /**
4954  *      ata_hsm_qc_complete - finish a qc running on standard HSM
4955  *      @qc: Command to complete
4956  *      @in_wq: 1 if called from workqueue, 0 otherwise
4957  *
4958  *      Finish @qc which is running on standard HSM.
4959  *
4960  *      LOCKING:
4961  *      If @in_wq is zero, spin_lock_irqsave(host lock).
4962  *      Otherwise, none on entry and grabs host lock.
4963  */
4964 static void ata_hsm_qc_complete(struct ata_queued_cmd *qc, int in_wq)
4965 {
4966         struct ata_port *ap = qc->ap;
4967         unsigned long flags;
4968
4969         if (ap->ops->error_handler) {
4970                 if (in_wq) {
4971                         spin_lock_irqsave(ap->lock, flags);
4972
4973                         /* EH might have kicked in while host lock is
4974                          * released.
4975                          */
4976                         qc = ata_qc_from_tag(ap, qc->tag);
4977                         if (qc) {
4978                                 if (likely(!(qc->err_mask & AC_ERR_HSM))) {
4979                                         ap->ops->irq_on(ap);
4980                                         ata_qc_complete(qc);
4981                                 } else
4982                                         ata_port_freeze(ap);
4983                         }
4984
4985                         spin_unlock_irqrestore(ap->lock, flags);
4986                 } else {
4987                         if (likely(!(qc->err_mask & AC_ERR_HSM)))
4988                                 ata_qc_complete(qc);
4989                         else
4990                                 ata_port_freeze(ap);
4991                 }
4992         } else {
4993                 if (in_wq) {
4994                         spin_lock_irqsave(ap->lock, flags);
4995                         ap->ops->irq_on(ap);
4996                         ata_qc_complete(qc);
4997                         spin_unlock_irqrestore(ap->lock, flags);
4998                 } else
4999                         ata_qc_complete(qc);
5000         }
5001 }
5002
5003 /**
5004  *      ata_hsm_move - move the HSM to the next state.
5005  *      @ap: the target ata_port
5006  *      @qc: qc on going
5007  *      @status: current device status
5008  *      @in_wq: 1 if called from workqueue, 0 otherwise
5009  *
5010  *      RETURNS:
5011  *      1 when poll next status needed, 0 otherwise.
5012  */
5013 int ata_hsm_move(struct ata_port *ap, struct ata_queued_cmd *qc,
5014                  u8 status, int in_wq)
5015 {
5016         unsigned long flags = 0;
5017         int poll_next;
5018
5019         WARN_ON((qc->flags & ATA_QCFLAG_ACTIVE) == 0);
5020
5021         /* Make sure ata_qc_issue_prot() does not throw things
5022          * like DMA polling into the workqueue. Notice that
5023          * in_wq is not equivalent to (qc->tf.flags & ATA_TFLAG_POLLING).
5024          */
5025         WARN_ON(in_wq != ata_hsm_ok_in_wq(ap, qc));
5026
5027 fsm_start:
5028         DPRINTK("ata%u: protocol %d task_state %d (dev_stat 0x%X)\n",
5029                 ap->print_id, qc->tf.protocol, ap->hsm_task_state, status);
5030
5031         switch (ap->hsm_task_state) {
5032         case HSM_ST_FIRST:
5033                 /* Send first data block or PACKET CDB */
5034
5035                 /* If polling, we will stay in the work queue after
5036                  * sending the data. Otherwise, interrupt handler
5037                  * takes over after sending the data.
5038                  */
5039                 poll_next = (qc->tf.flags & ATA_TFLAG_POLLING);
5040
5041                 /* check device status */
5042                 if (unlikely((status & ATA_DRQ) == 0)) {
5043                         /* handle BSY=0, DRQ=0 as error */
5044                         if (likely(status & (ATA_ERR | ATA_DF)))
5045                                 /* device stops HSM for abort/error */
5046                                 qc->err_mask |= AC_ERR_DEV;
5047                         else
5048                                 /* HSM violation. Let EH handle this */
5049                                 qc->err_mask |= AC_ERR_HSM;
5050
5051                         ap->hsm_task_state = HSM_ST_ERR;
5052                         goto fsm_start;
5053                 }
5054
5055                 /* Device should not ask for data transfer (DRQ=1)
5056                  * when it finds something wrong.
5057                  * We ignore DRQ here and stop the HSM by
5058                  * changing hsm_task_state to HSM_ST_ERR and
5059                  * let the EH abort the command or reset the device.
5060                  */
5061                 if (unlikely(status & (ATA_ERR | ATA_DF))) {
5062                         ata_port_printk(ap, KERN_WARNING, "DRQ=1 with device "
5063                                         "error, dev_stat 0x%X\n", status);
5064                         qc->err_mask |= AC_ERR_HSM;
5065                         ap->hsm_task_state = HSM_ST_ERR;
5066                         goto fsm_start;
5067                 }
5068
5069                 /* Send the CDB (atapi) or the first data block (ata pio out).
5070                  * During the state transition, interrupt handler shouldn't
5071                  * be invoked before the data transfer is complete and
5072                  * hsm_task_state is changed. Hence, the following locking.
5073                  */
5074                 if (in_wq)
5075                         spin_lock_irqsave(ap->lock, flags);
5076
5077                 if (qc->tf.protocol == ATA_PROT_PIO) {
5078                         /* PIO data out protocol.
5079                          * send first data block.
5080                          */
5081
5082                         /* ata_pio_sectors() might change the state
5083                          * to HSM_ST_LAST. so, the state is changed here
5084                          * before ata_pio_sectors().
5085                          */
5086                         ap->hsm_task_state = HSM_ST;
5087                         ata_pio_sectors(qc);
5088                 } else
5089                         /* send CDB */
5090                         atapi_send_cdb(ap, qc);
5091
5092                 if (in_wq)
5093                         spin_unlock_irqrestore(ap->lock, flags);
5094
5095                 /* if polling, ata_pio_task() handles the rest.
5096                  * otherwise, interrupt handler takes over from here.
5097                  */
5098                 break;
5099
5100         case HSM_ST:
5101                 /* complete command or read/write the data register */
5102                 if (qc->tf.protocol == ATA_PROT_ATAPI) {
5103                         /* ATAPI PIO protocol */
5104                         if ((status & ATA_DRQ) == 0) {
5105                                 /* No more data to transfer or device error.
5106                                  * Device error will be tagged in HSM_ST_LAST.
5107                                  */
5108                                 ap->hsm_task_state = HSM_ST_LAST;
5109                                 goto fsm_start;
5110                         }
5111
5112                         /* Device should not ask for data transfer (DRQ=1)
5113                          * when it finds something wrong.
5114                          * We ignore DRQ here and stop the HSM by
5115                          * changing hsm_task_state to HSM_ST_ERR and
5116                          * let the EH abort the command or reset the device.
5117                          */
5118                         if (unlikely(status & (ATA_ERR | ATA_DF))) {
5119                                 ata_port_printk(ap, KERN_WARNING, "DRQ=1 with "
5120                                                 "device error, dev_stat 0x%X\n",
5121                                                 status);
5122                                 qc->err_mask |= AC_ERR_HSM;
5123                                 ap->hsm_task_state = HSM_ST_ERR;
5124                                 goto fsm_start;
5125                         }
5126
5127                         atapi_pio_bytes(qc);
5128
5129                         if (unlikely(ap->hsm_task_state == HSM_ST_ERR))
5130                                 /* bad ireason reported by device */
5131                                 goto fsm_start;
5132
5133                 } else {
5134                         /* ATA PIO protocol */
5135                         if (unlikely((status & ATA_DRQ) == 0)) {
5136                                 /* handle BSY=0, DRQ=0 as error */
5137                                 if (likely(status & (ATA_ERR | ATA_DF)))
5138                                         /* device stops HSM for abort/error */
5139                                         qc->err_mask |= AC_ERR_DEV;
5140                                 else
5141                                         /* HSM violation. Let EH handle this.
5142                                          * Phantom devices also trigger this
5143                                          * condition.  Mark hint.
5144                                          */
5145                                         qc->err_mask |= AC_ERR_HSM |
5146                                                         AC_ERR_NODEV_HINT;
5147
5148                                 ap->hsm_task_state = HSM_ST_ERR;
5149                                 goto fsm_start;
5150                         }
5151
5152                         /* For PIO reads, some devices may ask for
5153                          * data transfer (DRQ=1) alone with ERR=1.
5154                          * We respect DRQ here and transfer one
5155                          * block of junk data before changing the
5156                          * hsm_task_state to HSM_ST_ERR.
5157                          *
5158                          * For PIO writes, ERR=1 DRQ=1 doesn't make
5159                          * sense since the data block has been
5160                          * transferred to the device.
5161                          */
5162                         if (unlikely(status & (ATA_ERR | ATA_DF))) {
5163                                 /* data might be corrputed */
5164                                 qc->err_mask |= AC_ERR_DEV;
5165
5166                                 if (!(qc->tf.flags & ATA_TFLAG_WRITE)) {
5167                                         ata_pio_sectors(qc);
5168                                         status = ata_wait_idle(ap);
5169                                 }
5170
5171                                 if (status & (ATA_BUSY | ATA_DRQ))
5172                                         qc->err_mask |= AC_ERR_HSM;
5173
5174                                 /* ata_pio_sectors() might change the
5175                                  * state to HSM_ST_LAST. so, the state
5176                                  * is changed after ata_pio_sectors().
5177                                  */
5178                                 ap->hsm_task_state = HSM_ST_ERR;
5179                                 goto fsm_start;
5180                         }
5181
5182                         ata_pio_sectors(qc);
5183
5184                         if (ap->hsm_task_state == HSM_ST_LAST &&
5185                             (!(qc->tf.flags & ATA_TFLAG_WRITE))) {
5186                                 /* all data read */
5187                                 status = ata_wait_idle(ap);
5188                                 goto fsm_start;
5189                         }
5190                 }
5191
5192                 poll_next = 1;
5193                 break;
5194
5195         case HSM_ST_LAST:
5196                 if (unlikely(!ata_ok(status))) {
5197                         qc->err_mask |= __ac_err_mask(status);
5198                         ap->hsm_task_state = HSM_ST_ERR;
5199                         goto fsm_start;
5200                 }
5201
5202                 /* no more data to transfer */
5203                 DPRINTK("ata%u: dev %u command complete, drv_stat 0x%x\n",
5204                         ap->print_id, qc->dev->devno, status);
5205
5206                 WARN_ON(qc->err_mask);
5207
5208                 ap->hsm_task_state = HSM_ST_IDLE;
5209
5210                 /* complete taskfile transaction */
5211                 ata_hsm_qc_complete(qc, in_wq);
5212
5213                 poll_next = 0;
5214                 break;
5215
5216         case HSM_ST_ERR:
5217                 /* make sure qc->err_mask is available to
5218                  * know what's wrong and recover
5219                  */
5220                 WARN_ON(qc->err_mask == 0);
5221
5222                 ap->hsm_task_state = HSM_ST_IDLE;
5223
5224                 /* complete taskfile transaction */
5225                 ata_hsm_qc_complete(qc, in_wq);
5226
5227                 poll_next = 0;
5228                 break;
5229         default:
5230                 poll_next = 0;
5231                 BUG();
5232         }
5233
5234         return poll_next;
5235 }
5236
5237 static void ata_pio_task(struct work_struct *work)
5238 {
5239         struct ata_port *ap =
5240                 container_of(work, struct ata_port, port_task.work);
5241         struct ata_queued_cmd *qc = ap->port_task_data;
5242         u8 status;
5243         int poll_next;
5244
5245 fsm_start:
5246         WARN_ON(ap->hsm_task_state == HSM_ST_IDLE);
5247
5248         /*
5249          * This is purely heuristic.  This is a fast path.
5250          * Sometimes when we enter, BSY will be cleared in
5251          * a chk-status or two.  If not, the drive is probably seeking
5252          * or something.  Snooze for a couple msecs, then
5253          * chk-status again.  If still busy, queue delayed work.
5254          */
5255         status = ata_busy_wait(ap, ATA_BUSY, 5);
5256         if (status & ATA_BUSY) {
5257                 msleep(2);
5258                 status = ata_busy_wait(ap, ATA_BUSY, 10);
5259                 if (status & ATA_BUSY) {
5260                         ata_port_queue_task(ap, ata_pio_task, qc, ATA_SHORT_PAUSE);
5261                         return;
5262                 }
5263         }
5264
5265         /* move the HSM */
5266         poll_next = ata_hsm_move(ap, qc, status, 1);
5267
5268         /* another command or interrupt handler
5269          * may be running at this point.
5270          */
5271         if (poll_next)
5272                 goto fsm_start;
5273 }
5274
5275 /**
5276  *      ata_qc_new - Request an available ATA command, for queueing
5277  *      @ap: Port associated with device @dev
5278  *      @dev: Device from whom we request an available command structure
5279  *
5280  *      LOCKING:
5281  *      None.
5282  */
5283
5284 static struct ata_queued_cmd *ata_qc_new(struct ata_port *ap)
5285 {
5286         struct ata_queued_cmd *qc = NULL;
5287         unsigned int i;
5288
5289         /* no command while frozen */
5290         if (unlikely(ap->pflags & ATA_PFLAG_FROZEN))
5291                 return NULL;
5292
5293         /* the last tag is reserved for internal command. */
5294         for (i = 0; i < ATA_MAX_QUEUE - 1; i++)
5295                 if (!test_and_set_bit(i, &ap->qc_allocated)) {
5296                         qc = __ata_qc_from_tag(ap, i);
5297                         break;
5298                 }
5299
5300         if (qc)
5301                 qc->tag = i;
5302
5303         return qc;
5304 }
5305
5306 /**
5307  *      ata_qc_new_init - Request an available ATA command, and initialize it
5308  *      @dev: Device from whom we request an available command structure
5309  *
5310  *      LOCKING:
5311  *      None.
5312  */
5313
5314 struct ata_queued_cmd *ata_qc_new_init(struct ata_device *dev)
5315 {
5316         struct ata_port *ap = dev->link->ap;
5317         struct ata_queued_cmd *qc;
5318
5319         qc = ata_qc_new(ap);
5320         if (qc) {
5321                 qc->scsicmd = NULL;
5322                 qc->ap = ap;
5323                 qc->dev = dev;
5324
5325                 ata_qc_reinit(qc);
5326         }
5327
5328         return qc;
5329 }
5330
5331 /**
5332  *      ata_qc_free - free unused ata_queued_cmd
5333  *      @qc: Command to complete
5334  *
5335  *      Designed to free unused ata_queued_cmd object
5336  *      in case something prevents using it.
5337  *
5338  *      LOCKING:
5339  *      spin_lock_irqsave(host lock)
5340  */
5341 void ata_qc_free(struct ata_queued_cmd *qc)
5342 {
5343         struct ata_port *ap = qc->ap;
5344         unsigned int tag;
5345
5346         WARN_ON(qc == NULL);    /* ata_qc_from_tag _might_ return NULL */
5347
5348         qc->flags = 0;
5349         tag = qc->tag;
5350         if (likely(ata_tag_valid(tag))) {
5351                 qc->tag = ATA_TAG_POISON;
5352                 clear_bit(tag, &ap->qc_allocated);
5353         }
5354 }
5355
5356 void __ata_qc_complete(struct ata_queued_cmd *qc)
5357 {
5358         struct ata_port *ap = qc->ap;
5359         struct ata_link *link = qc->dev->link;
5360
5361         WARN_ON(qc == NULL);    /* ata_qc_from_tag _might_ return NULL */
5362         WARN_ON(!(qc->flags & ATA_QCFLAG_ACTIVE));
5363
5364         if (likely(qc->flags & ATA_QCFLAG_DMAMAP))
5365                 ata_sg_clean(qc);
5366
5367         /* command should be marked inactive atomically with qc completion */
5368         if (qc->tf.protocol == ATA_PROT_NCQ)
5369                 link->sactive &= ~(1 << qc->tag);
5370         else
5371                 link->active_tag = ATA_TAG_POISON;
5372
5373         /* atapi: mark qc as inactive to prevent the interrupt handler
5374          * from completing the command twice later, before the error handler
5375          * is called. (when rc != 0 and atapi request sense is needed)
5376          */
5377         qc->flags &= ~ATA_QCFLAG_ACTIVE;
5378         ap->qc_active &= ~(1 << qc->tag);
5379
5380         /* call completion callback */
5381         qc->complete_fn(qc);
5382 }
5383
5384 static void fill_result_tf(struct ata_queued_cmd *qc)
5385 {
5386         struct ata_port *ap = qc->ap;
5387
5388         qc->result_tf.flags = qc->tf.flags;
5389         ap->ops->tf_read(ap, &qc->result_tf);
5390 }
5391
5392 /**
5393  *      ata_qc_complete - Complete an active ATA command
5394  *      @qc: Command to complete
5395  *      @err_mask: ATA Status register contents
5396  *
5397  *      Indicate to the mid and upper layers that an ATA
5398  *      command has completed, with either an ok or not-ok status.
5399  *
5400  *      LOCKING:
5401  *      spin_lock_irqsave(host lock)
5402  */
5403 void ata_qc_complete(struct ata_queued_cmd *qc)
5404 {
5405         struct ata_port *ap = qc->ap;
5406
5407         /* XXX: New EH and old EH use different mechanisms to
5408          * synchronize EH with regular execution path.
5409          *
5410          * In new EH, a failed qc is marked with ATA_QCFLAG_FAILED.
5411          * Normal execution path is responsible for not accessing a
5412          * failed qc.  libata core enforces the rule by returning NULL
5413          * from ata_qc_from_tag() for failed qcs.
5414          *
5415          * Old EH depends on ata_qc_complete() nullifying completion
5416          * requests if ATA_QCFLAG_EH_SCHEDULED is set.  Old EH does
5417          * not synchronize with interrupt handler.  Only PIO task is
5418          * taken care of.
5419          */
5420         if (ap->ops->error_handler) {
5421                 WARN_ON(ap->pflags & ATA_PFLAG_FROZEN);
5422
5423                 if (unlikely(qc->err_mask))
5424                         qc->flags |= ATA_QCFLAG_FAILED;
5425
5426                 if (unlikely(qc->flags & ATA_QCFLAG_FAILED)) {
5427                         if (!ata_tag_internal(qc->tag)) {
5428                                 /* always fill result TF for failed qc */
5429                                 fill_result_tf(qc);
5430                                 ata_qc_schedule_eh(qc);
5431                                 return;
5432                         }
5433                 }
5434
5435                 /* read result TF if requested */
5436                 if (qc->flags & ATA_QCFLAG_RESULT_TF)
5437                         fill_result_tf(qc);
5438
5439                 __ata_qc_complete(qc);
5440         } else {
5441                 if (qc->flags & ATA_QCFLAG_EH_SCHEDULED)
5442                         return;
5443
5444                 /* read result TF if failed or requested */
5445                 if (qc->err_mask || qc->flags & ATA_QCFLAG_RESULT_TF)
5446                         fill_result_tf(qc);
5447
5448                 __ata_qc_complete(qc);
5449         }
5450 }
5451
5452 /**
5453  *      ata_qc_complete_multiple - Complete multiple qcs successfully
5454  *      @ap: port in question
5455  *      @qc_active: new qc_active mask
5456  *      @finish_qc: LLDD callback invoked before completing a qc
5457  *
5458  *      Complete in-flight commands.  This functions is meant to be
5459  *      called from low-level driver's interrupt routine to complete
5460  *      requests normally.  ap->qc_active and @qc_active is compared
5461  *      and commands are completed accordingly.
5462  *
5463  *      LOCKING:
5464  *      spin_lock_irqsave(host lock)
5465  *
5466  *      RETURNS:
5467  *      Number of completed commands on success, -errno otherwise.
5468  */
5469 int ata_qc_complete_multiple(struct ata_port *ap, u32 qc_active,
5470                              void (*finish_qc)(struct ata_queued_cmd *))
5471 {
5472         int nr_done = 0;
5473         u32 done_mask;
5474         int i;
5475
5476         done_mask = ap->qc_active ^ qc_active;
5477
5478         if (unlikely(done_mask & qc_active)) {
5479                 ata_port_printk(ap, KERN_ERR, "illegal qc_active transition "
5480                                 "(%08x->%08x)\n", ap->qc_active, qc_active);
5481                 return -EINVAL;
5482         }
5483
5484         for (i = 0; i < ATA_MAX_QUEUE; i++) {
5485                 struct ata_queued_cmd *qc;
5486
5487                 if (!(done_mask & (1 << i)))
5488                         continue;
5489
5490                 if ((qc = ata_qc_from_tag(ap, i))) {
5491                         if (finish_qc)
5492                                 finish_qc(qc);
5493                         ata_qc_complete(qc);
5494                         nr_done++;
5495                 }
5496         }
5497
5498         return nr_done;
5499 }
5500
5501 static inline int ata_should_dma_map(struct ata_queued_cmd *qc)
5502 {
5503         struct ata_port *ap = qc->ap;
5504
5505         switch (qc->tf.protocol) {
5506         case ATA_PROT_NCQ:
5507         case ATA_PROT_DMA:
5508         case ATA_PROT_ATAPI_DMA:
5509                 return 1;
5510
5511         case ATA_PROT_ATAPI:
5512         case ATA_PROT_PIO:
5513                 if (ap->flags & ATA_FLAG_PIO_DMA)
5514                         return 1;
5515
5516                 /* fall through */
5517
5518         default:
5519                 return 0;
5520         }
5521
5522         /* never reached */
5523 }
5524
5525 /**
5526  *      ata_qc_issue - issue taskfile to device
5527  *      @qc: command to issue to device
5528  *
5529  *      Prepare an ATA command to submission to device.
5530  *      This includes mapping the data into a DMA-able
5531  *      area, filling in the S/G table, and finally
5532  *      writing the taskfile to hardware, starting the command.
5533  *
5534  *      LOCKING:
5535  *      spin_lock_irqsave(host lock)
5536  */
5537 void ata_qc_issue(struct ata_queued_cmd *qc)
5538 {
5539         struct ata_port *ap = qc->ap;
5540         struct ata_link *link = qc->dev->link;
5541
5542         /* Make sure only one non-NCQ command is outstanding.  The
5543          * check is skipped for old EH because it reuses active qc to
5544          * request ATAPI sense.
5545          */
5546         WARN_ON(ap->ops->error_handler && ata_tag_valid(link->active_tag));
5547
5548         if (qc->tf.protocol == ATA_PROT_NCQ) {
5549                 WARN_ON(link->sactive & (1 << qc->tag));
5550                 link->sactive |= 1 << qc->tag;
5551         } else {
5552                 WARN_ON(link->sactive);
5553                 link->active_tag = qc->tag;
5554         }
5555
5556         qc->flags |= ATA_QCFLAG_ACTIVE;
5557         ap->qc_active |= 1 << qc->tag;
5558
5559         if (ata_should_dma_map(qc)) {
5560                 if (qc->flags & ATA_QCFLAG_SG) {
5561                         if (ata_sg_setup(qc))
5562                                 goto sg_err;
5563                 } else if (qc->flags & ATA_QCFLAG_SINGLE) {
5564                         if (ata_sg_setup_one(qc))
5565                                 goto sg_err;
5566                 }
5567         } else {
5568                 qc->flags &= ~ATA_QCFLAG_DMAMAP;
5569         }
5570
5571         ap->ops->qc_prep(qc);
5572
5573         qc->err_mask |= ap->ops->qc_issue(qc);
5574         if (unlikely(qc->err_mask))
5575                 goto err;
5576         return;
5577
5578 sg_err:
5579         qc->flags &= ~ATA_QCFLAG_DMAMAP;
5580         qc->err_mask |= AC_ERR_SYSTEM;
5581 err:
5582         ata_qc_complete(qc);
5583 }
5584
5585 /**
5586  *      ata_qc_issue_prot - issue taskfile to device in proto-dependent manner
5587  *      @qc: command to issue to device
5588  *
5589  *      Using various libata functions and hooks, this function
5590  *      starts an ATA command.  ATA commands are grouped into
5591  *      classes called "protocols", and issuing each type of protocol
5592  *      is slightly different.
5593  *
5594  *      May be used as the qc_issue() entry in ata_port_operations.
5595  *
5596  *      LOCKING:
5597  *      spin_lock_irqsave(host lock)
5598  *
5599  *      RETURNS:
5600  *      Zero on success, AC_ERR_* mask on failure
5601  */
5602
5603 unsigned int ata_qc_issue_prot(struct ata_queued_cmd *qc)
5604 {
5605         struct ata_port *ap = qc->ap;
5606
5607         /* Use polling pio if the LLD doesn't handle
5608          * interrupt driven pio and atapi CDB interrupt.
5609          */
5610         if (ap->flags & ATA_FLAG_PIO_POLLING) {
5611                 switch (qc->tf.protocol) {
5612                 case ATA_PROT_PIO:
5613                 case ATA_PROT_NODATA:
5614                 case ATA_PROT_ATAPI:
5615                 case ATA_PROT_ATAPI_NODATA:
5616                         qc->tf.flags |= ATA_TFLAG_POLLING;
5617                         break;
5618                 case ATA_PROT_ATAPI_DMA:
5619                         if (qc->dev->flags & ATA_DFLAG_CDB_INTR)
5620                                 /* see ata_dma_blacklisted() */
5621                                 BUG();
5622                         break;
5623                 default:
5624                         break;
5625                 }
5626         }
5627
5628         /* select the device */
5629         ata_dev_select(ap, qc->dev->devno, 1, 0);
5630
5631         /* start the command */
5632         switch (qc->tf.protocol) {
5633         case ATA_PROT_NODATA:
5634                 if (qc->tf.flags & ATA_TFLAG_POLLING)
5635                         ata_qc_set_polling(qc);
5636
5637                 ata_tf_to_host(ap, &qc->tf);
5638                 ap->hsm_task_state = HSM_ST_LAST;
5639
5640                 if (qc->tf.flags & ATA_TFLAG_POLLING)
5641                         ata_port_queue_task(ap, ata_pio_task, qc, 0);
5642
5643                 break;
5644
5645         case ATA_PROT_DMA:
5646                 WARN_ON(qc->tf.flags & ATA_TFLAG_POLLING);
5647
5648                 ap->ops->tf_load(ap, &qc->tf);   /* load tf registers */
5649                 ap->ops->bmdma_setup(qc);           /* set up bmdma */
5650                 ap->ops->bmdma_start(qc);           /* initiate bmdma */
5651                 ap->hsm_task_state = HSM_ST_LAST;
5652                 break;
5653
5654         case ATA_PROT_PIO:
5655                 if (qc->tf.flags & ATA_TFLAG_POLLING)
5656                         ata_qc_set_polling(qc);
5657
5658                 ata_tf_to_host(ap, &qc->tf);
5659
5660                 if (qc->tf.flags & ATA_TFLAG_WRITE) {
5661                         /* PIO data out protocol */
5662                         ap->hsm_task_state = HSM_ST_FIRST;
5663                         ata_port_queue_task(ap, ata_pio_task, qc, 0);
5664
5665                         /* always send first data block using
5666                          * the ata_pio_task() codepath.
5667                          */
5668                 } else {
5669                         /* PIO data in protocol */
5670                         ap->hsm_task_state = HSM_ST;
5671
5672                         if (qc->tf.flags & ATA_TFLAG_POLLING)
5673                                 ata_port_queue_task(ap, ata_pio_task, qc, 0);
5674
5675                         /* if polling, ata_pio_task() handles the rest.
5676                          * otherwise, interrupt handler takes over from here.
5677                          */
5678                 }
5679
5680                 break;
5681
5682         case ATA_PROT_ATAPI:
5683         case ATA_PROT_ATAPI_NODATA:
5684                 if (qc->tf.flags & ATA_TFLAG_POLLING)
5685                         ata_qc_set_polling(qc);
5686
5687                 ata_tf_to_host(ap, &qc->tf);
5688
5689                 ap->hsm_task_state = HSM_ST_FIRST;
5690
5691                 /* send cdb by polling if no cdb interrupt */
5692                 if ((!(qc->dev->flags & ATA_DFLAG_CDB_INTR)) ||
5693                     (qc->tf.flags & ATA_TFLAG_POLLING))
5694                         ata_port_queue_task(ap, ata_pio_task, qc, 0);
5695                 break;
5696
5697         case ATA_PROT_ATAPI_DMA:
5698                 WARN_ON(qc->tf.flags & ATA_TFLAG_POLLING);
5699
5700                 ap->ops->tf_load(ap, &qc->tf);   /* load tf registers */
5701                 ap->ops->bmdma_setup(qc);           /* set up bmdma */
5702                 ap->hsm_task_state = HSM_ST_FIRST;
5703
5704                 /* send cdb by polling if no cdb interrupt */
5705                 if (!(qc->dev->flags & ATA_DFLAG_CDB_INTR))
5706                         ata_port_queue_task(ap, ata_pio_task, qc, 0);
5707                 break;
5708
5709         default:
5710                 WARN_ON(1);
5711                 return AC_ERR_SYSTEM;
5712         }
5713
5714         return 0;
5715 }
5716
5717 /**
5718  *      ata_host_intr - Handle host interrupt for given (port, task)
5719  *      @ap: Port on which interrupt arrived (possibly...)
5720  *      @qc: Taskfile currently active in engine
5721  *
5722  *      Handle host interrupt for given queued command.  Currently,
5723  *      only DMA interrupts are handled.  All other commands are
5724  *      handled via polling with interrupts disabled (nIEN bit).
5725  *
5726  *      LOCKING:
5727  *      spin_lock_irqsave(host lock)
5728  *
5729  *      RETURNS:
5730  *      One if interrupt was handled, zero if not (shared irq).
5731  */
5732
5733 inline unsigned int ata_host_intr (struct ata_port *ap,
5734                                    struct ata_queued_cmd *qc)
5735 {
5736         struct ata_eh_info *ehi = &ap->link.eh_info;
5737         u8 status, host_stat = 0;
5738
5739         VPRINTK("ata%u: protocol %d task_state %d\n",
5740                 ap->print_id, qc->tf.protocol, ap->hsm_task_state);
5741
5742         /* Check whether we are expecting interrupt in this state */
5743         switch (ap->hsm_task_state) {
5744         case HSM_ST_FIRST:
5745                 /* Some pre-ATAPI-4 devices assert INTRQ
5746                  * at this state when ready to receive CDB.
5747                  */
5748
5749                 /* Check the ATA_DFLAG_CDB_INTR flag is enough here.
5750                  * The flag was turned on only for atapi devices.
5751                  * No need to check is_atapi_taskfile(&qc->tf) again.
5752                  */
5753                 if (!(qc->dev->flags & ATA_DFLAG_CDB_INTR))
5754                         goto idle_irq;
5755                 break;
5756         case HSM_ST_LAST:
5757                 if (qc->tf.protocol == ATA_PROT_DMA ||
5758                     qc->tf.protocol == ATA_PROT_ATAPI_DMA) {
5759                         /* check status of DMA engine */
5760                         host_stat = ap->ops->bmdma_status(ap);
5761                         VPRINTK("ata%u: host_stat 0x%X\n",
5762                                 ap->print_id, host_stat);
5763
5764                         /* if it's not our irq... */
5765                         if (!(host_stat & ATA_DMA_INTR))
5766                                 goto idle_irq;
5767
5768                         /* before we do anything else, clear DMA-Start bit */
5769                         ap->ops->bmdma_stop(qc);
5770
5771                         if (unlikely(host_stat & ATA_DMA_ERR)) {
5772                                 /* error when transfering data to/from memory */
5773                                 qc->err_mask |= AC_ERR_HOST_BUS;
5774                                 ap->hsm_task_state = HSM_ST_ERR;
5775                         }
5776                 }
5777                 break;
5778         case HSM_ST:
5779                 break;
5780         default:
5781                 goto idle_irq;
5782         }
5783
5784         /* check altstatus */
5785         status = ata_altstatus(ap);
5786         if (status & ATA_BUSY)
5787                 goto idle_irq;
5788
5789         /* check main status, clearing INTRQ */
5790         status = ata_chk_status(ap);
5791         if (unlikely(status & ATA_BUSY))
5792                 goto idle_irq;
5793
5794         /* ack bmdma irq events */
5795         ap->ops->irq_clear(ap);
5796
5797         ata_hsm_move(ap, qc, status, 0);
5798
5799         if (unlikely(qc->err_mask) && (qc->tf.protocol == ATA_PROT_DMA ||
5800                                        qc->tf.protocol == ATA_PROT_ATAPI_DMA))
5801                 ata_ehi_push_desc(ehi, "BMDMA stat 0x%x", host_stat);
5802
5803         return 1;       /* irq handled */
5804
5805 idle_irq:
5806         ap->stats.idle_irq++;
5807
5808 #ifdef ATA_IRQ_TRAP
5809         if ((ap->stats.idle_irq % 1000) == 0) {
5810                 ata_chk_status(ap);
5811                 ap->ops->irq_clear(ap);
5812                 ata_port_printk(ap, KERN_WARNING, "irq trap\n");
5813                 return 1;
5814         }
5815 #endif
5816         return 0;       /* irq not handled */
5817 }
5818
5819 /**
5820  *      ata_interrupt - Default ATA host interrupt handler
5821  *      @irq: irq line (unused)
5822  *      @dev_instance: pointer to our ata_host information structure
5823  *
5824  *      Default interrupt handler for PCI IDE devices.  Calls
5825  *      ata_host_intr() for each port that is not disabled.
5826  *
5827  *      LOCKING:
5828  *      Obtains host lock during operation.
5829  *
5830  *      RETURNS:
5831  *      IRQ_NONE or IRQ_HANDLED.
5832  */
5833
5834 irqreturn_t ata_interrupt (int irq, void *dev_instance)
5835 {
5836         struct ata_host *host = dev_instance;
5837         unsigned int i;
5838         unsigned int handled = 0;
5839         unsigned long flags;
5840
5841         /* TODO: make _irqsave conditional on x86 PCI IDE legacy mode */
5842         spin_lock_irqsave(&host->lock, flags);
5843
5844         for (i = 0; i < host->n_ports; i++) {
5845                 struct ata_port *ap;
5846
5847                 ap = host->ports[i];
5848                 if (ap &&
5849                     !(ap->flags & ATA_FLAG_DISABLED)) {
5850                         struct ata_queued_cmd *qc;
5851
5852                         qc = ata_qc_from_tag(ap, ap->link.active_tag);
5853                         if (qc && (!(qc->tf.flags & ATA_TFLAG_POLLING)) &&
5854                             (qc->flags & ATA_QCFLAG_ACTIVE))
5855                                 handled |= ata_host_intr(ap, qc);
5856                 }
5857         }
5858
5859         spin_unlock_irqrestore(&host->lock, flags);
5860
5861         return IRQ_RETVAL(handled);
5862 }
5863
5864 /**
5865  *      sata_scr_valid - test whether SCRs are accessible
5866  *      @link: ATA link to test SCR accessibility for
5867  *
5868  *      Test whether SCRs are accessible for @link.
5869  *
5870  *      LOCKING:
5871  *      None.
5872  *
5873  *      RETURNS:
5874  *      1 if SCRs are accessible, 0 otherwise.
5875  */
5876 int sata_scr_valid(struct ata_link *link)
5877 {
5878         struct ata_port *ap = link->ap;
5879
5880         return (ap->flags & ATA_FLAG_SATA) && ap->ops->scr_read;
5881 }
5882
5883 /**
5884  *      sata_scr_read - read SCR register of the specified port
5885  *      @link: ATA link to read SCR for
5886  *      @reg: SCR to read
5887  *      @val: Place to store read value
5888  *
5889  *      Read SCR register @reg of @link into *@val.  This function is
5890  *      guaranteed to succeed if the cable type of the port is SATA
5891  *      and the port implements ->scr_read.
5892  *
5893  *      LOCKING:
5894  *      None.
5895  *
5896  *      RETURNS:
5897  *      0 on success, negative errno on failure.
5898  */
5899 int sata_scr_read(struct ata_link *link, int reg, u32 *val)
5900 {
5901         struct ata_port *ap = link->ap;
5902
5903         if (sata_scr_valid(link))
5904                 return ap->ops->scr_read(ap, reg, val);
5905         return -EOPNOTSUPP;
5906 }
5907
5908 /**
5909  *      sata_scr_write - write SCR register of the specified port
5910  *      @link: ATA link to write SCR for
5911  *      @reg: SCR to write
5912  *      @val: value to write
5913  *
5914  *      Write @val to SCR register @reg of @link.  This function is
5915  *      guaranteed to succeed if the cable type of the port is SATA
5916  *      and the port implements ->scr_read.
5917  *
5918  *      LOCKING:
5919  *      None.
5920  *
5921  *      RETURNS:
5922  *      0 on success, negative errno on failure.
5923  */
5924 int sata_scr_write(struct ata_link *link, int reg, u32 val)
5925 {
5926         struct ata_port *ap = link->ap;
5927
5928         if (sata_scr_valid(link))
5929                 return ap->ops->scr_write(ap, reg, val);
5930         return -EOPNOTSUPP;
5931 }
5932
5933 /**
5934  *      sata_scr_write_flush - write SCR register of the specified port and flush
5935  *      @link: ATA link to write SCR for
5936  *      @reg: SCR to write
5937  *      @val: value to write
5938  *
5939  *      This function is identical to sata_scr_write() except that this
5940  *      function performs flush after writing to the register.
5941  *
5942  *      LOCKING:
5943  *      None.
5944  *
5945  *      RETURNS:
5946  *      0 on success, negative errno on failure.
5947  */
5948 int sata_scr_write_flush(struct ata_link *link, int reg, u32 val)
5949 {
5950         struct ata_port *ap = link->ap;
5951         int rc;
5952
5953         if (sata_scr_valid(link)) {
5954                 rc = ap->ops->scr_write(ap, reg, val);
5955                 if (rc == 0)
5956                         rc = ap->ops->scr_read(ap, reg, &val);
5957                 return rc;
5958         }
5959         return -EOPNOTSUPP;
5960 }
5961
5962 /**
5963  *      ata_link_online - test whether the given link is online
5964  *      @link: ATA link to test
5965  *
5966  *      Test whether @link is online.  Note that this function returns
5967  *      0 if online status of @link cannot be obtained, so
5968  *      ata_link_online(link) != !ata_link_offline(link).
5969  *
5970  *      LOCKING:
5971  *      None.
5972  *
5973  *      RETURNS:
5974  *      1 if the port online status is available and online.
5975  */
5976 int ata_link_online(struct ata_link *link)
5977 {
5978         u32 sstatus;
5979
5980         if (sata_scr_read(link, SCR_STATUS, &sstatus) == 0 &&
5981             (sstatus & 0xf) == 0x3)
5982                 return 1;
5983         return 0;
5984 }
5985
5986 /**
5987  *      ata_link_offline - test whether the given link is offline
5988  *      @link: ATA link to test
5989  *
5990  *      Test whether @link is offline.  Note that this function
5991  *      returns 0 if offline status of @link cannot be obtained, so
5992  *      ata_link_online(link) != !ata_link_offline(link).
5993  *
5994  *      LOCKING:
5995  *      None.
5996  *
5997  *      RETURNS:
5998  *      1 if the port offline status is available and offline.
5999  */
6000 int ata_link_offline(struct ata_link *link)
6001 {
6002         u32 sstatus;
6003
6004         if (sata_scr_read(link, SCR_STATUS, &sstatus) == 0 &&
6005             (sstatus & 0xf) != 0x3)
6006                 return 1;
6007         return 0;
6008 }
6009
6010 int ata_flush_cache(struct ata_device *dev)
6011 {
6012         unsigned int err_mask;
6013         u8 cmd;
6014
6015         if (!ata_try_flush_cache(dev))
6016                 return 0;
6017
6018         if (dev->flags & ATA_DFLAG_FLUSH_EXT)
6019                 cmd = ATA_CMD_FLUSH_EXT;
6020         else
6021                 cmd = ATA_CMD_FLUSH;
6022
6023         /* This is wrong. On a failed flush we get back the LBA of the lost
6024            sector and we should (assuming it wasn't aborted as unknown) issue
6025            a further flush command to continue the writeback until it 
6026            does not error */
6027         err_mask = ata_do_simple_cmd(dev, cmd);
6028         if (err_mask) {
6029                 ata_dev_printk(dev, KERN_ERR, "failed to flush cache\n");
6030                 return -EIO;
6031         }
6032
6033         return 0;
6034 }
6035
6036 #ifdef CONFIG_PM
6037 static int ata_host_request_pm(struct ata_host *host, pm_message_t mesg,
6038                                unsigned int action, unsigned int ehi_flags,
6039                                int wait)
6040 {
6041         unsigned long flags;
6042         int i, rc;
6043
6044         for (i = 0; i < host->n_ports; i++) {
6045                 struct ata_port *ap = host->ports[i];
6046                 struct ata_link *link;
6047
6048                 /* Previous resume operation might still be in
6049                  * progress.  Wait for PM_PENDING to clear.
6050                  */
6051                 if (ap->pflags & ATA_PFLAG_PM_PENDING) {
6052                         ata_port_wait_eh(ap);
6053                         WARN_ON(ap->pflags & ATA_PFLAG_PM_PENDING);
6054                 }
6055
6056                 /* request PM ops to EH */
6057                 spin_lock_irqsave(ap->lock, flags);
6058
6059                 ap->pm_mesg = mesg;
6060                 if (wait) {
6061                         rc = 0;
6062                         ap->pm_result = &rc;
6063                 }
6064
6065                 ap->pflags |= ATA_PFLAG_PM_PENDING;
6066                 __ata_port_for_each_link(link, ap) {
6067                         link->eh_info.action |= action;
6068                         link->eh_info.flags |= ehi_flags;
6069                 }
6070
6071                 ata_port_schedule_eh(ap);
6072
6073                 spin_unlock_irqrestore(ap->lock, flags);
6074
6075                 /* wait and check result */
6076                 if (wait) {
6077                         ata_port_wait_eh(ap);
6078                         WARN_ON(ap->pflags & ATA_PFLAG_PM_PENDING);
6079                         if (rc)
6080                                 return rc;
6081                 }
6082         }
6083
6084         return 0;
6085 }
6086
6087 /**
6088  *      ata_host_suspend - suspend host
6089  *      @host: host to suspend
6090  *      @mesg: PM message
6091  *
6092  *      Suspend @host.  Actual operation is performed by EH.  This
6093  *      function requests EH to perform PM operations and waits for EH
6094  *      to finish.
6095  *
6096  *      LOCKING:
6097  *      Kernel thread context (may sleep).
6098  *
6099  *      RETURNS:
6100  *      0 on success, -errno on failure.
6101  */
6102 int ata_host_suspend(struct ata_host *host, pm_message_t mesg)
6103 {
6104         int rc;
6105
6106         rc = ata_host_request_pm(host, mesg, 0, ATA_EHI_QUIET, 1);
6107         if (rc == 0)
6108                 host->dev->power.power_state = mesg;
6109         return rc;
6110 }
6111
6112 /**
6113  *      ata_host_resume - resume host
6114  *      @host: host to resume
6115  *
6116  *      Resume @host.  Actual operation is performed by EH.  This
6117  *      function requests EH to perform PM operations and returns.
6118  *      Note that all resume operations are performed parallely.
6119  *
6120  *      LOCKING:
6121  *      Kernel thread context (may sleep).
6122  */
6123 void ata_host_resume(struct ata_host *host)
6124 {
6125         ata_host_request_pm(host, PMSG_ON, ATA_EH_SOFTRESET,
6126                             ATA_EHI_NO_AUTOPSY | ATA_EHI_QUIET, 0);
6127         host->dev->power.power_state = PMSG_ON;
6128 }
6129 #endif
6130
6131 /**
6132  *      ata_port_start - Set port up for dma.
6133  *      @ap: Port to initialize
6134  *
6135  *      Called just after data structures for each port are
6136  *      initialized.  Allocates space for PRD table.
6137  *
6138  *      May be used as the port_start() entry in ata_port_operations.
6139  *
6140  *      LOCKING:
6141  *      Inherited from caller.
6142  */
6143 int ata_port_start(struct ata_port *ap)
6144 {
6145         struct device *dev = ap->dev;
6146         int rc;
6147
6148         ap->prd = dmam_alloc_coherent(dev, ATA_PRD_TBL_SZ, &ap->prd_dma,
6149                                       GFP_KERNEL);
6150         if (!ap->prd)
6151                 return -ENOMEM;
6152
6153         rc = ata_pad_alloc(ap, dev);
6154         if (rc)
6155                 return rc;
6156
6157         DPRINTK("prd alloc, virt %p, dma %llx\n", ap->prd,
6158                 (unsigned long long)ap->prd_dma);
6159         return 0;
6160 }
6161
6162 /**
6163  *      ata_dev_init - Initialize an ata_device structure
6164  *      @dev: Device structure to initialize
6165  *
6166  *      Initialize @dev in preparation for probing.
6167  *
6168  *      LOCKING:
6169  *      Inherited from caller.
6170  */
6171 void ata_dev_init(struct ata_device *dev)
6172 {
6173         struct ata_link *link = dev->link;
6174         struct ata_port *ap = link->ap;
6175         unsigned long flags;
6176
6177         /* SATA spd limit is bound to the first device */
6178         link->sata_spd_limit = link->hw_sata_spd_limit;
6179         link->sata_spd = 0;
6180
6181         /* High bits of dev->flags are used to record warm plug
6182          * requests which occur asynchronously.  Synchronize using
6183          * host lock.
6184          */
6185         spin_lock_irqsave(ap->lock, flags);
6186         dev->flags &= ~ATA_DFLAG_INIT_MASK;
6187         dev->horkage = 0;
6188         spin_unlock_irqrestore(ap->lock, flags);
6189
6190         memset((void *)dev + ATA_DEVICE_CLEAR_OFFSET, 0,
6191                sizeof(*dev) - ATA_DEVICE_CLEAR_OFFSET);
6192         dev->pio_mask = UINT_MAX;
6193         dev->mwdma_mask = UINT_MAX;
6194         dev->udma_mask = UINT_MAX;
6195 }
6196
6197 /**
6198  *      ata_link_init - Initialize an ata_link structure
6199  *      @ap: ATA port link is attached to
6200  *      @link: Link structure to initialize
6201  *      @pmp: Port multiplier port number
6202  *
6203  *      Initialize @link.
6204  *
6205  *      LOCKING:
6206  *      Kernel thread context (may sleep)
6207  */
6208 static void ata_link_init(struct ata_port *ap, struct ata_link *link, int pmp)
6209 {
6210         int i;
6211
6212         /* clear everything except for devices */
6213         memset(link, 0, offsetof(struct ata_link, device[0]));
6214
6215         link->ap = ap;
6216         link->pmp = pmp;
6217         link->active_tag = ATA_TAG_POISON;
6218         link->hw_sata_spd_limit = UINT_MAX;
6219
6220         /* can't use iterator, ap isn't initialized yet */
6221         for (i = 0; i < ATA_MAX_DEVICES; i++) {
6222                 struct ata_device *dev = &link->device[i];
6223
6224                 dev->link = link;
6225                 dev->devno = dev - link->device;
6226                 ata_dev_init(dev);
6227         }
6228 }
6229
6230 /**
6231  *      sata_link_init_spd - Initialize link->sata_spd_limit
6232  *      @link: Link to configure sata_spd_limit for
6233  *
6234  *      Initialize @link->[hw_]sata_spd_limit to the currently
6235  *      configured value.
6236  *
6237  *      LOCKING:
6238  *      Kernel thread context (may sleep).
6239  *
6240  *      RETURNS:
6241  *      0 on success, -errno on failure.
6242  */
6243 static int sata_link_init_spd(struct ata_link *link)
6244 {
6245         u32 scontrol, spd;
6246         int rc;
6247
6248         rc = sata_scr_read(link, SCR_CONTROL, &scontrol);
6249         if (rc)
6250                 return rc;
6251
6252         spd = (scontrol >> 4) & 0xf;
6253         if (spd)
6254                 link->hw_sata_spd_limit &= (1 << spd) - 1;
6255
6256         link->sata_spd_limit = link->hw_sata_spd_limit;
6257
6258         return 0;
6259 }
6260
6261 /**
6262  *      ata_port_alloc - allocate and initialize basic ATA port resources
6263  *      @host: ATA host this allocated port belongs to
6264  *
6265  *      Allocate and initialize basic ATA port resources.
6266  *
6267  *      RETURNS:
6268  *      Allocate ATA port on success, NULL on failure.
6269  *
6270  *      LOCKING:
6271  *      Inherited from calling layer (may sleep).
6272  */
6273 struct ata_port *ata_port_alloc(struct ata_host *host)
6274 {
6275         struct ata_port *ap;
6276
6277         DPRINTK("ENTER\n");
6278
6279         ap = kzalloc(sizeof(*ap), GFP_KERNEL);
6280         if (!ap)
6281                 return NULL;
6282
6283         ap->pflags |= ATA_PFLAG_INITIALIZING;
6284         ap->lock = &host->lock;
6285         ap->flags = ATA_FLAG_DISABLED;
6286         ap->print_id = -1;
6287         ap->ctl = ATA_DEVCTL_OBS;
6288         ap->host = host;
6289         ap->dev = host->dev;
6290         ap->last_ctl = 0xFF;
6291
6292 #if defined(ATA_VERBOSE_DEBUG)
6293         /* turn on all debugging levels */
6294         ap->msg_enable = 0x00FF;
6295 #elif defined(ATA_DEBUG)
6296         ap->msg_enable = ATA_MSG_DRV | ATA_MSG_INFO | ATA_MSG_CTL | ATA_MSG_WARN | ATA_MSG_ERR;
6297 #else
6298         ap->msg_enable = ATA_MSG_DRV | ATA_MSG_ERR | ATA_MSG_WARN;
6299 #endif
6300
6301         INIT_DELAYED_WORK(&ap->port_task, NULL);
6302         INIT_DELAYED_WORK(&ap->hotplug_task, ata_scsi_hotplug);
6303         INIT_WORK(&ap->scsi_rescan_task, ata_scsi_dev_rescan);
6304         INIT_LIST_HEAD(&ap->eh_done_q);
6305         init_waitqueue_head(&ap->eh_wait_q);
6306         init_timer_deferrable(&ap->fastdrain_timer);
6307         ap->fastdrain_timer.function = ata_eh_fastdrain_timerfn;
6308         ap->fastdrain_timer.data = (unsigned long)ap;
6309
6310         ap->cbl = ATA_CBL_NONE;
6311
6312         ata_link_init(ap, &ap->link, 0);
6313
6314 #ifdef ATA_IRQ_TRAP
6315         ap->stats.unhandled_irq = 1;
6316         ap->stats.idle_irq = 1;
6317 #endif
6318         return ap;
6319 }
6320
6321 static void ata_host_release(struct device *gendev, void *res)
6322 {
6323         struct ata_host *host = dev_get_drvdata(gendev);
6324         int i;
6325
6326         for (i = 0; i < host->n_ports; i++) {
6327                 struct ata_port *ap = host->ports[i];
6328
6329                 if (!ap)
6330                         continue;
6331
6332                 if ((host->flags & ATA_HOST_STARTED) && ap->ops->port_stop)
6333                         ap->ops->port_stop(ap);
6334         }
6335
6336         if ((host->flags & ATA_HOST_STARTED) && host->ops->host_stop)
6337                 host->ops->host_stop(host);
6338
6339         for (i = 0; i < host->n_ports; i++) {
6340                 struct ata_port *ap = host->ports[i];
6341
6342                 if (!ap)
6343                         continue;
6344
6345                 if (ap->scsi_host)
6346                         scsi_host_put(ap->scsi_host);
6347
6348                 kfree(ap);
6349                 host->ports[i] = NULL;
6350         }
6351
6352         dev_set_drvdata(gendev, NULL);
6353 }
6354
6355 /**
6356  *      ata_host_alloc - allocate and init basic ATA host resources
6357  *      @dev: generic device this host is associated with
6358  *      @max_ports: maximum number of ATA ports associated with this host
6359  *
6360  *      Allocate and initialize basic ATA host resources.  LLD calls
6361  *      this function to allocate a host, initializes it fully and
6362  *      attaches it using ata_host_register().
6363  *
6364  *      @max_ports ports are allocated and host->n_ports is
6365  *      initialized to @max_ports.  The caller is allowed to decrease
6366  *      host->n_ports before calling ata_host_register().  The unused
6367  *      ports will be automatically freed on registration.
6368  *
6369  *      RETURNS:
6370  *      Allocate ATA host on success, NULL on failure.
6371  *
6372  *      LOCKING:
6373  *      Inherited from calling layer (may sleep).
6374  */
6375 struct ata_host *ata_host_alloc(struct device *dev, int max_ports)
6376 {
6377         struct ata_host *host;
6378         size_t sz;
6379         int i;
6380
6381         DPRINTK("ENTER\n");
6382
6383         if (!devres_open_group(dev, NULL, GFP_KERNEL))
6384                 return NULL;
6385
6386         /* alloc a container for our list of ATA ports (buses) */
6387         sz = sizeof(struct ata_host) + (max_ports + 1) * sizeof(void *);
6388         /* alloc a container for our list of ATA ports (buses) */
6389         host = devres_alloc(ata_host_release, sz, GFP_KERNEL);
6390         if (!host)
6391                 goto err_out;
6392
6393         devres_add(dev, host);
6394         dev_set_drvdata(dev, host);
6395
6396         spin_lock_init(&host->lock);
6397         host->dev = dev;
6398         host->n_ports = max_ports;
6399
6400         /* allocate ports bound to this host */
6401         for (i = 0; i < max_ports; i++) {
6402                 struct ata_port *ap;
6403
6404                 ap = ata_port_alloc(host);
6405                 if (!ap)
6406                         goto err_out;
6407
6408                 ap->port_no = i;
6409                 host->ports[i] = ap;
6410         }
6411
6412         devres_remove_group(dev, NULL);
6413         return host;
6414
6415  err_out:
6416         devres_release_group(dev, NULL);
6417         return NULL;
6418 }
6419
6420 /**
6421  *      ata_host_alloc_pinfo - alloc host and init with port_info array
6422  *      @dev: generic device this host is associated with
6423  *      @ppi: array of ATA port_info to initialize host with
6424  *      @n_ports: number of ATA ports attached to this host
6425  *
6426  *      Allocate ATA host and initialize with info from @ppi.  If NULL
6427  *      terminated, @ppi may contain fewer entries than @n_ports.  The
6428  *      last entry will be used for the remaining ports.
6429  *
6430  *      RETURNS:
6431  *      Allocate ATA host on success, NULL on failure.
6432  *
6433  *      LOCKING:
6434  *      Inherited from calling layer (may sleep).
6435  */
6436 struct ata_host *ata_host_alloc_pinfo(struct device *dev,
6437                                       const struct ata_port_info * const * ppi,
6438                                       int n_ports)
6439 {
6440         const struct ata_port_info *pi;
6441         struct ata_host *host;
6442         int i, j;
6443
6444         host = ata_host_alloc(dev, n_ports);
6445         if (!host)
6446                 return NULL;
6447
6448         for (i = 0, j = 0, pi = NULL; i < host->n_ports; i++) {
6449                 struct ata_port *ap = host->ports[i];
6450
6451                 if (ppi[j])
6452                         pi = ppi[j++];
6453
6454                 ap->pio_mask = pi->pio_mask;
6455                 ap->mwdma_mask = pi->mwdma_mask;
6456                 ap->udma_mask = pi->udma_mask;
6457                 ap->flags |= pi->flags;
6458                 ap->link.flags |= pi->link_flags;
6459                 ap->ops = pi->port_ops;
6460
6461                 if (!host->ops && (pi->port_ops != &ata_dummy_port_ops))
6462                         host->ops = pi->port_ops;
6463                 if (!host->private_data && pi->private_data)
6464                         host->private_data = pi->private_data;
6465         }
6466
6467         return host;
6468 }
6469
6470 /**
6471  *      ata_host_start - start and freeze ports of an ATA host
6472  *      @host: ATA host to start ports for
6473  *
6474  *      Start and then freeze ports of @host.  Started status is
6475  *      recorded in host->flags, so this function can be called
6476  *      multiple times.  Ports are guaranteed to get started only
6477  *      once.  If host->ops isn't initialized yet, its set to the
6478  *      first non-dummy port ops.
6479  *
6480  *      LOCKING:
6481  *      Inherited from calling layer (may sleep).
6482  *
6483  *      RETURNS:
6484  *      0 if all ports are started successfully, -errno otherwise.
6485  */
6486 int ata_host_start(struct ata_host *host)
6487 {
6488         int i, rc;
6489
6490         if (host->flags & ATA_HOST_STARTED)
6491                 return 0;
6492
6493         for (i = 0; i < host->n_ports; i++) {
6494                 struct ata_port *ap = host->ports[i];
6495
6496                 if (!host->ops && !ata_port_is_dummy(ap))
6497                         host->ops = ap->ops;
6498
6499                 if (ap->ops->port_start) {
6500                         rc = ap->ops->port_start(ap);
6501                         if (rc) {
6502                                 ata_port_printk(ap, KERN_ERR, "failed to "
6503                                                 "start port (errno=%d)\n", rc);
6504                                 goto err_out;
6505                         }
6506                 }
6507
6508                 ata_eh_freeze_port(ap);
6509         }
6510
6511         host->flags |= ATA_HOST_STARTED;
6512         return 0;
6513
6514  err_out:
6515         while (--i >= 0) {
6516                 struct ata_port *ap = host->ports[i];
6517
6518                 if (ap->ops->port_stop)
6519                         ap->ops->port_stop(ap);
6520         }
6521         return rc;
6522 }
6523
6524 /**
6525  *      ata_sas_host_init - Initialize a host struct
6526  *      @host:  host to initialize
6527  *      @dev:   device host is attached to
6528  *      @flags: host flags
6529  *      @ops:   port_ops
6530  *
6531  *      LOCKING:
6532  *      PCI/etc. bus probe sem.
6533  *
6534  */
6535 /* KILLME - the only user left is ipr */
6536 void ata_host_init(struct ata_host *host, struct device *dev,
6537                    unsigned long flags, const struct ata_port_operations *ops)
6538 {
6539         spin_lock_init(&host->lock);
6540         host->dev = dev;
6541         host->flags = flags;
6542         host->ops = ops;
6543 }
6544
6545 /**
6546  *      ata_host_register - register initialized ATA host
6547  *      @host: ATA host to register
6548  *      @sht: template for SCSI host
6549  *
6550  *      Register initialized ATA host.  @host is allocated using
6551  *      ata_host_alloc() and fully initialized by LLD.  This function
6552  *      starts ports, registers @host with ATA and SCSI layers and
6553  *      probe registered devices.
6554  *
6555  *      LOCKING:
6556  *      Inherited from calling layer (may sleep).
6557  *
6558  *      RETURNS:
6559  *      0 on success, -errno otherwise.
6560  */
6561 int ata_host_register(struct ata_host *host, struct scsi_host_template *sht)
6562 {
6563         int i, rc;
6564
6565         /* host must have been started */
6566         if (!(host->flags & ATA_HOST_STARTED)) {
6567                 dev_printk(KERN_ERR, host->dev,
6568                            "BUG: trying to register unstarted host\n");
6569                 WARN_ON(1);
6570                 return -EINVAL;
6571         }
6572
6573         /* Blow away unused ports.  This happens when LLD can't
6574          * determine the exact number of ports to allocate at
6575          * allocation time.
6576          */
6577         for (i = host->n_ports; host->ports[i]; i++)
6578                 kfree(host->ports[i]);
6579
6580         /* give ports names and add SCSI hosts */
6581         for (i = 0; i < host->n_ports; i++)
6582                 host->ports[i]->print_id = ata_print_id++;
6583
6584         rc = ata_scsi_add_hosts(host, sht);
6585         if (rc)
6586                 return rc;
6587
6588         /* associate with ACPI nodes */
6589         ata_acpi_associate(host);
6590
6591         /* set cable, sata_spd_limit and report */
6592         for (i = 0; i < host->n_ports; i++) {
6593                 struct ata_port *ap = host->ports[i];
6594                 unsigned long xfer_mask;
6595
6596                 /* set SATA cable type if still unset */
6597                 if (ap->cbl == ATA_CBL_NONE && (ap->flags & ATA_FLAG_SATA))
6598                         ap->cbl = ATA_CBL_SATA;
6599
6600                 /* init sata_spd_limit to the current value */
6601                 sata_link_init_spd(&ap->link);
6602
6603                 /* print per-port info to dmesg */
6604                 xfer_mask = ata_pack_xfermask(ap->pio_mask, ap->mwdma_mask,
6605                                               ap->udma_mask);
6606
6607                 if (!ata_port_is_dummy(ap))
6608                         ata_port_printk(ap, KERN_INFO,
6609                                         "%cATA max %s %s\n",
6610                                         (ap->flags & ATA_FLAG_SATA) ? 'S' : 'P',
6611                                         ata_mode_string(xfer_mask),
6612                                         ap->link.eh_info.desc);
6613                 else
6614                         ata_port_printk(ap, KERN_INFO, "DUMMY\n");
6615         }
6616
6617         /* perform each probe synchronously */
6618         DPRINTK("probe begin\n");
6619         for (i = 0; i < host->n_ports; i++) {
6620                 struct ata_port *ap = host->ports[i];
6621                 int rc;
6622
6623                 /* probe */
6624                 if (ap->ops->error_handler) {
6625                         struct ata_eh_info *ehi = &ap->link.eh_info;
6626                         unsigned long flags;
6627
6628                         ata_port_probe(ap);
6629
6630                         /* kick EH for boot probing */
6631                         spin_lock_irqsave(ap->lock, flags);
6632
6633                         ehi->probe_mask =
6634                                 (1 << ata_link_max_devices(&ap->link)) - 1;
6635                         ehi->action |= ATA_EH_SOFTRESET;
6636                         ehi->flags |= ATA_EHI_NO_AUTOPSY | ATA_EHI_QUIET;
6637
6638                         ap->pflags &= ~ATA_PFLAG_INITIALIZING;
6639                         ap->pflags |= ATA_PFLAG_LOADING;
6640                         ata_port_schedule_eh(ap);
6641
6642                         spin_unlock_irqrestore(ap->lock, flags);
6643
6644                         /* wait for EH to finish */
6645                         ata_port_wait_eh(ap);
6646                 } else {
6647                         DPRINTK("ata%u: bus probe begin\n", ap->print_id);
6648                         rc = ata_bus_probe(ap);
6649                         DPRINTK("ata%u: bus probe end\n", ap->print_id);
6650
6651                         if (rc) {
6652                                 /* FIXME: do something useful here?
6653                                  * Current libata behavior will
6654                                  * tear down everything when
6655                                  * the module is removed
6656                                  * or the h/w is unplugged.
6657                                  */
6658                         }
6659                 }
6660         }
6661
6662         /* probes are done, now scan each port's disk(s) */
6663         DPRINTK("host probe begin\n");
6664         for (i = 0; i < host->n_ports; i++) {
6665                 struct ata_port *ap = host->ports[i];
6666
6667                 ata_scsi_scan_host(ap, 1);
6668         }
6669
6670         return 0;
6671 }
6672
6673 /**
6674  *      ata_host_activate - start host, request IRQ and register it
6675  *      @host: target ATA host
6676  *      @irq: IRQ to request
6677  *      @irq_handler: irq_handler used when requesting IRQ
6678  *      @irq_flags: irq_flags used when requesting IRQ
6679  *      @sht: scsi_host_template to use when registering the host
6680  *
6681  *      After allocating an ATA host and initializing it, most libata
6682  *      LLDs perform three steps to activate the host - start host,
6683  *      request IRQ and register it.  This helper takes necessasry
6684  *      arguments and performs the three steps in one go.
6685  *
6686  *      LOCKING:
6687  *      Inherited from calling layer (may sleep).
6688  *
6689  *      RETURNS:
6690  *      0 on success, -errno otherwise.
6691  */
6692 int ata_host_activate(struct ata_host *host, int irq,
6693                       irq_handler_t irq_handler, unsigned long irq_flags,
6694                       struct scsi_host_template *sht)
6695 {
6696         int i, rc;
6697
6698         rc = ata_host_start(host);
6699         if (rc)
6700                 return rc;
6701
6702         rc = devm_request_irq(host->dev, irq, irq_handler, irq_flags,
6703                               dev_driver_string(host->dev), host);
6704         if (rc)
6705                 return rc;
6706
6707         for (i = 0; i < host->n_ports; i++)
6708                 ata_port_desc(host->ports[i], "irq %d", irq);
6709
6710         rc = ata_host_register(host, sht);
6711         /* if failed, just free the IRQ and leave ports alone */
6712         if (rc)
6713                 devm_free_irq(host->dev, irq, host);
6714
6715         return rc;
6716 }
6717
6718 /**
6719  *      ata_port_detach - Detach ATA port in prepration of device removal
6720  *      @ap: ATA port to be detached
6721  *
6722  *      Detach all ATA devices and the associated SCSI devices of @ap;
6723  *      then, remove the associated SCSI host.  @ap is guaranteed to
6724  *      be quiescent on return from this function.
6725  *
6726  *      LOCKING:
6727  *      Kernel thread context (may sleep).
6728  */
6729 void ata_port_detach(struct ata_port *ap)
6730 {
6731         unsigned long flags;
6732         struct ata_link *link;
6733         struct ata_device *dev;
6734
6735         if (!ap->ops->error_handler)
6736                 goto skip_eh;
6737
6738         /* tell EH we're leaving & flush EH */
6739         spin_lock_irqsave(ap->lock, flags);
6740         ap->pflags |= ATA_PFLAG_UNLOADING;
6741         spin_unlock_irqrestore(ap->lock, flags);
6742
6743         ata_port_wait_eh(ap);
6744
6745         /* EH is now guaranteed to see UNLOADING, so no new device
6746          * will be attached.  Disable all existing devices.
6747          */
6748         spin_lock_irqsave(ap->lock, flags);
6749
6750         ata_port_for_each_link(link, ap) {
6751                 ata_link_for_each_dev(dev, link)
6752                         ata_dev_disable(dev);
6753         }
6754
6755         spin_unlock_irqrestore(ap->lock, flags);
6756
6757         /* Final freeze & EH.  All in-flight commands are aborted.  EH
6758          * will be skipped and retrials will be terminated with bad
6759          * target.
6760          */
6761         spin_lock_irqsave(ap->lock, flags);
6762         ata_port_freeze(ap);    /* won't be thawed */
6763         spin_unlock_irqrestore(ap->lock, flags);
6764
6765         ata_port_wait_eh(ap);
6766         cancel_rearming_delayed_work(&ap->hotplug_task);
6767
6768  skip_eh:
6769         /* remove the associated SCSI host */
6770         scsi_remove_host(ap->scsi_host);
6771 }
6772
6773 /**
6774  *      ata_host_detach - Detach all ports of an ATA host
6775  *      @host: Host to detach
6776  *
6777  *      Detach all ports of @host.
6778  *
6779  *      LOCKING:
6780  *      Kernel thread context (may sleep).
6781  */
6782 void ata_host_detach(struct ata_host *host)
6783 {
6784         int i;
6785
6786         for (i = 0; i < host->n_ports; i++)
6787                 ata_port_detach(host->ports[i]);
6788 }
6789
6790 /**
6791  *      ata_std_ports - initialize ioaddr with standard port offsets.
6792  *      @ioaddr: IO address structure to be initialized
6793  *
6794  *      Utility function which initializes data_addr, error_addr,
6795  *      feature_addr, nsect_addr, lbal_addr, lbam_addr, lbah_addr,
6796  *      device_addr, status_addr, and command_addr to standard offsets
6797  *      relative to cmd_addr.
6798  *
6799  *      Does not set ctl_addr, altstatus_addr, bmdma_addr, or scr_addr.
6800  */
6801
6802 void ata_std_ports(struct ata_ioports *ioaddr)
6803 {
6804         ioaddr->data_addr = ioaddr->cmd_addr + ATA_REG_DATA;
6805         ioaddr->error_addr = ioaddr->cmd_addr + ATA_REG_ERR;
6806         ioaddr->feature_addr = ioaddr->cmd_addr + ATA_REG_FEATURE;
6807         ioaddr->nsect_addr = ioaddr->cmd_addr + ATA_REG_NSECT;
6808         ioaddr->lbal_addr = ioaddr->cmd_addr + ATA_REG_LBAL;
6809         ioaddr->lbam_addr = ioaddr->cmd_addr + ATA_REG_LBAM;
6810         ioaddr->lbah_addr = ioaddr->cmd_addr + ATA_REG_LBAH;
6811         ioaddr->device_addr = ioaddr->cmd_addr + ATA_REG_DEVICE;
6812         ioaddr->status_addr = ioaddr->cmd_addr + ATA_REG_STATUS;
6813         ioaddr->command_addr = ioaddr->cmd_addr + ATA_REG_CMD;
6814 }
6815
6816
6817 #ifdef CONFIG_PCI
6818
6819 /**
6820  *      ata_pci_remove_one - PCI layer callback for device removal
6821  *      @pdev: PCI device that was removed
6822  *
6823  *      PCI layer indicates to libata via this hook that hot-unplug or
6824  *      module unload event has occurred.  Detach all ports.  Resource
6825  *      release is handled via devres.
6826  *
6827  *      LOCKING:
6828  *      Inherited from PCI layer (may sleep).
6829  */
6830 void ata_pci_remove_one(struct pci_dev *pdev)
6831 {
6832         struct device *dev = pci_dev_to_dev(pdev);
6833         struct ata_host *host = dev_get_drvdata(dev);
6834
6835         ata_host_detach(host);
6836 }
6837
6838 /* move to PCI subsystem */
6839 int pci_test_config_bits(struct pci_dev *pdev, const struct pci_bits *bits)
6840 {
6841         unsigned long tmp = 0;
6842
6843         switch (bits->width) {
6844         case 1: {
6845                 u8 tmp8 = 0;
6846                 pci_read_config_byte(pdev, bits->reg, &tmp8);
6847                 tmp = tmp8;
6848                 break;
6849         }
6850         case 2: {
6851                 u16 tmp16 = 0;
6852                 pci_read_config_word(pdev, bits->reg, &tmp16);
6853                 tmp = tmp16;
6854                 break;
6855         }
6856         case 4: {
6857                 u32 tmp32 = 0;
6858                 pci_read_config_dword(pdev, bits->reg, &tmp32);
6859                 tmp = tmp32;
6860                 break;
6861         }
6862
6863         default:
6864                 return -EINVAL;
6865         }
6866
6867         tmp &= bits->mask;
6868
6869         return (tmp == bits->val) ? 1 : 0;
6870 }
6871
6872 #ifdef CONFIG_PM
6873 void ata_pci_device_do_suspend(struct pci_dev *pdev, pm_message_t mesg)
6874 {
6875         pci_save_state(pdev);
6876         pci_disable_device(pdev);
6877
6878         if (mesg.event == PM_EVENT_SUSPEND)
6879                 pci_set_power_state(pdev, PCI_D3hot);
6880 }
6881
6882 int ata_pci_device_do_resume(struct pci_dev *pdev)
6883 {
6884         int rc;
6885
6886         pci_set_power_state(pdev, PCI_D0);
6887         pci_restore_state(pdev);
6888
6889         rc = pcim_enable_device(pdev);
6890         if (rc) {
6891                 dev_printk(KERN_ERR, &pdev->dev,
6892                            "failed to enable device after resume (%d)\n", rc);
6893                 return rc;
6894         }
6895
6896         pci_set_master(pdev);
6897         return 0;
6898 }
6899
6900 int ata_pci_device_suspend(struct pci_dev *pdev, pm_message_t mesg)
6901 {
6902         struct ata_host *host = dev_get_drvdata(&pdev->dev);
6903         int rc = 0;
6904
6905         rc = ata_host_suspend(host, mesg);
6906         if (rc)
6907                 return rc;
6908
6909         ata_pci_device_do_suspend(pdev, mesg);
6910
6911         return 0;
6912 }
6913
6914 int ata_pci_device_resume(struct pci_dev *pdev)
6915 {
6916         struct ata_host *host = dev_get_drvdata(&pdev->dev);
6917         int rc;
6918
6919         rc = ata_pci_device_do_resume(pdev);
6920         if (rc == 0)
6921                 ata_host_resume(host);
6922         return rc;
6923 }
6924 #endif /* CONFIG_PM */
6925
6926 #endif /* CONFIG_PCI */
6927
6928
6929 static int __init ata_init(void)
6930 {
6931         ata_probe_timeout *= HZ;
6932         ata_wq = create_workqueue("ata");
6933         if (!ata_wq)
6934                 return -ENOMEM;
6935
6936         ata_aux_wq = create_singlethread_workqueue("ata_aux");
6937         if (!ata_aux_wq) {
6938                 destroy_workqueue(ata_wq);
6939                 return -ENOMEM;
6940         }
6941
6942         printk(KERN_DEBUG "libata version " DRV_VERSION " loaded.\n");
6943         return 0;
6944 }
6945
6946 static void __exit ata_exit(void)
6947 {
6948         destroy_workqueue(ata_wq);
6949         destroy_workqueue(ata_aux_wq);
6950 }
6951
6952 subsys_initcall(ata_init);
6953 module_exit(ata_exit);
6954
6955 static unsigned long ratelimit_time;
6956 static DEFINE_SPINLOCK(ata_ratelimit_lock);
6957
6958 int ata_ratelimit(void)
6959 {
6960         int rc;
6961         unsigned long flags;
6962
6963         spin_lock_irqsave(&ata_ratelimit_lock, flags);
6964
6965         if (time_after(jiffies, ratelimit_time)) {
6966                 rc = 1;
6967                 ratelimit_time = jiffies + (HZ/5);
6968         } else
6969                 rc = 0;
6970
6971         spin_unlock_irqrestore(&ata_ratelimit_lock, flags);
6972
6973         return rc;
6974 }
6975
6976 /**
6977  *      ata_wait_register - wait until register value changes
6978  *      @reg: IO-mapped register
6979  *      @mask: Mask to apply to read register value
6980  *      @val: Wait condition
6981  *      @interval_msec: polling interval in milliseconds
6982  *      @timeout_msec: timeout in milliseconds
6983  *
6984  *      Waiting for some bits of register to change is a common
6985  *      operation for ATA controllers.  This function reads 32bit LE
6986  *      IO-mapped register @reg and tests for the following condition.
6987  *
6988  *      (*@reg & mask) != val
6989  *
6990  *      If the condition is met, it returns; otherwise, the process is
6991  *      repeated after @interval_msec until timeout.
6992  *
6993  *      LOCKING:
6994  *      Kernel thread context (may sleep)
6995  *
6996  *      RETURNS:
6997  *      The final register value.
6998  */
6999 u32 ata_wait_register(void __iomem *reg, u32 mask, u32 val,
7000                       unsigned long interval_msec,
7001                       unsigned long timeout_msec)
7002 {
7003         unsigned long timeout;
7004         u32 tmp;
7005
7006         tmp = ioread32(reg);
7007
7008         /* Calculate timeout _after_ the first read to make sure
7009          * preceding writes reach the controller before starting to
7010          * eat away the timeout.
7011          */
7012         timeout = jiffies + (timeout_msec * HZ) / 1000;
7013
7014         while ((tmp & mask) == val && time_before(jiffies, timeout)) {
7015                 msleep(interval_msec);
7016                 tmp = ioread32(reg);
7017         }
7018
7019         return tmp;
7020 }
7021
7022 /*
7023  * Dummy port_ops
7024  */
7025 static void ata_dummy_noret(struct ata_port *ap)        { }
7026 static int ata_dummy_ret0(struct ata_port *ap)          { return 0; }
7027 static void ata_dummy_qc_noret(struct ata_queued_cmd *qc) { }
7028
7029 static u8 ata_dummy_check_status(struct ata_port *ap)
7030 {
7031         return ATA_DRDY;
7032 }
7033
7034 static unsigned int ata_dummy_qc_issue(struct ata_queued_cmd *qc)
7035 {
7036         return AC_ERR_SYSTEM;
7037 }
7038
7039 const struct ata_port_operations ata_dummy_port_ops = {
7040         .check_status           = ata_dummy_check_status,
7041         .check_altstatus        = ata_dummy_check_status,
7042         .dev_select             = ata_noop_dev_select,
7043         .qc_prep                = ata_noop_qc_prep,
7044         .qc_issue               = ata_dummy_qc_issue,
7045         .freeze                 = ata_dummy_noret,
7046         .thaw                   = ata_dummy_noret,
7047         .error_handler          = ata_dummy_noret,
7048         .post_internal_cmd      = ata_dummy_qc_noret,
7049         .irq_clear              = ata_dummy_noret,
7050         .port_start             = ata_dummy_ret0,
7051         .port_stop              = ata_dummy_noret,
7052 };
7053
7054 const struct ata_port_info ata_dummy_port_info = {
7055         .port_ops               = &ata_dummy_port_ops,
7056 };
7057
7058 /*
7059  * libata is essentially a library of internal helper functions for
7060  * low-level ATA host controller drivers.  As such, the API/ABI is
7061  * likely to change as new drivers are added and updated.
7062  * Do not depend on ABI/API stability.
7063  */
7064
7065 EXPORT_SYMBOL_GPL(sata_deb_timing_normal);
7066 EXPORT_SYMBOL_GPL(sata_deb_timing_hotplug);
7067 EXPORT_SYMBOL_GPL(sata_deb_timing_long);
7068 EXPORT_SYMBOL_GPL(ata_dummy_port_ops);
7069 EXPORT_SYMBOL_GPL(ata_dummy_port_info);
7070 EXPORT_SYMBOL_GPL(ata_std_bios_param);
7071 EXPORT_SYMBOL_GPL(ata_std_ports);
7072 EXPORT_SYMBOL_GPL(ata_host_init);
7073 EXPORT_SYMBOL_GPL(ata_host_alloc);
7074 EXPORT_SYMBOL_GPL(ata_host_alloc_pinfo);
7075 EXPORT_SYMBOL_GPL(ata_host_start);
7076 EXPORT_SYMBOL_GPL(ata_host_register);
7077 EXPORT_SYMBOL_GPL(ata_host_activate);
7078 EXPORT_SYMBOL_GPL(ata_host_detach);
7079 EXPORT_SYMBOL_GPL(ata_sg_init);
7080 EXPORT_SYMBOL_GPL(ata_sg_init_one);
7081 EXPORT_SYMBOL_GPL(ata_hsm_move);
7082 EXPORT_SYMBOL_GPL(ata_qc_complete);
7083 EXPORT_SYMBOL_GPL(ata_qc_complete_multiple);
7084 EXPORT_SYMBOL_GPL(ata_qc_issue_prot);
7085 EXPORT_SYMBOL_GPL(ata_tf_load);
7086 EXPORT_SYMBOL_GPL(ata_tf_read);
7087 EXPORT_SYMBOL_GPL(ata_noop_dev_select);
7088 EXPORT_SYMBOL_GPL(ata_std_dev_select);
7089 EXPORT_SYMBOL_GPL(sata_print_link_status);
7090 EXPORT_SYMBOL_GPL(ata_tf_to_fis);
7091 EXPORT_SYMBOL_GPL(ata_tf_from_fis);
7092 EXPORT_SYMBOL_GPL(ata_check_status);
7093 EXPORT_SYMBOL_GPL(ata_altstatus);
7094 EXPORT_SYMBOL_GPL(ata_exec_command);
7095 EXPORT_SYMBOL_GPL(ata_port_start);
7096 EXPORT_SYMBOL_GPL(ata_sff_port_start);
7097 EXPORT_SYMBOL_GPL(ata_interrupt);
7098 EXPORT_SYMBOL_GPL(ata_do_set_mode);
7099 EXPORT_SYMBOL_GPL(ata_data_xfer);
7100 EXPORT_SYMBOL_GPL(ata_data_xfer_noirq);
7101 EXPORT_SYMBOL_GPL(ata_qc_prep);
7102 EXPORT_SYMBOL_GPL(ata_dumb_qc_prep);
7103 EXPORT_SYMBOL_GPL(ata_noop_qc_prep);
7104 EXPORT_SYMBOL_GPL(ata_bmdma_setup);
7105 EXPORT_SYMBOL_GPL(ata_bmdma_start);
7106 EXPORT_SYMBOL_GPL(ata_bmdma_irq_clear);
7107 EXPORT_SYMBOL_GPL(ata_bmdma_status);
7108 EXPORT_SYMBOL_GPL(ata_bmdma_stop);
7109 EXPORT_SYMBOL_GPL(ata_bmdma_freeze);
7110 EXPORT_SYMBOL_GPL(ata_bmdma_thaw);
7111 EXPORT_SYMBOL_GPL(ata_bmdma_drive_eh);
7112 EXPORT_SYMBOL_GPL(ata_bmdma_error_handler);
7113 EXPORT_SYMBOL_GPL(ata_bmdma_post_internal_cmd);
7114 EXPORT_SYMBOL_GPL(ata_port_probe);
7115 EXPORT_SYMBOL_GPL(ata_dev_disable);
7116 EXPORT_SYMBOL_GPL(sata_set_spd);
7117 EXPORT_SYMBOL_GPL(sata_link_debounce);
7118 EXPORT_SYMBOL_GPL(sata_link_resume);
7119 EXPORT_SYMBOL_GPL(sata_phy_reset);
7120 EXPORT_SYMBOL_GPL(__sata_phy_reset);
7121 EXPORT_SYMBOL_GPL(ata_bus_reset);
7122 EXPORT_SYMBOL_GPL(ata_std_prereset);
7123 EXPORT_SYMBOL_GPL(ata_std_softreset);
7124 EXPORT_SYMBOL_GPL(sata_link_hardreset);
7125 EXPORT_SYMBOL_GPL(sata_std_hardreset);
7126 EXPORT_SYMBOL_GPL(ata_std_postreset);
7127 EXPORT_SYMBOL_GPL(ata_dev_classify);
7128 EXPORT_SYMBOL_GPL(ata_dev_pair);
7129 EXPORT_SYMBOL_GPL(ata_port_disable);
7130 EXPORT_SYMBOL_GPL(ata_ratelimit);
7131 EXPORT_SYMBOL_GPL(ata_wait_register);
7132 EXPORT_SYMBOL_GPL(ata_busy_sleep);
7133 EXPORT_SYMBOL_GPL(ata_wait_ready);
7134 EXPORT_SYMBOL_GPL(ata_port_queue_task);
7135 EXPORT_SYMBOL_GPL(ata_scsi_ioctl);
7136 EXPORT_SYMBOL_GPL(ata_scsi_queuecmd);
7137 EXPORT_SYMBOL_GPL(ata_scsi_slave_config);
7138 EXPORT_SYMBOL_GPL(ata_scsi_slave_destroy);
7139 EXPORT_SYMBOL_GPL(ata_scsi_change_queue_depth);
7140 EXPORT_SYMBOL_GPL(ata_host_intr);
7141 EXPORT_SYMBOL_GPL(sata_scr_valid);
7142 EXPORT_SYMBOL_GPL(sata_scr_read);
7143 EXPORT_SYMBOL_GPL(sata_scr_write);
7144 EXPORT_SYMBOL_GPL(sata_scr_write_flush);
7145 EXPORT_SYMBOL_GPL(ata_link_online);
7146 EXPORT_SYMBOL_GPL(ata_link_offline);
7147 #ifdef CONFIG_PM
7148 EXPORT_SYMBOL_GPL(ata_host_suspend);
7149 EXPORT_SYMBOL_GPL(ata_host_resume);
7150 #endif /* CONFIG_PM */
7151 EXPORT_SYMBOL_GPL(ata_id_string);
7152 EXPORT_SYMBOL_GPL(ata_id_c_string);
7153 EXPORT_SYMBOL_GPL(ata_id_to_dma_mode);
7154 EXPORT_SYMBOL_GPL(ata_scsi_simulate);
7155
7156 EXPORT_SYMBOL_GPL(ata_pio_need_iordy);
7157 EXPORT_SYMBOL_GPL(ata_timing_compute);
7158 EXPORT_SYMBOL_GPL(ata_timing_merge);
7159
7160 #ifdef CONFIG_PCI
7161 EXPORT_SYMBOL_GPL(pci_test_config_bits);
7162 EXPORT_SYMBOL_GPL(ata_pci_init_sff_host);
7163 EXPORT_SYMBOL_GPL(ata_pci_init_bmdma);
7164 EXPORT_SYMBOL_GPL(ata_pci_prepare_sff_host);
7165 EXPORT_SYMBOL_GPL(ata_pci_init_one);
7166 EXPORT_SYMBOL_GPL(ata_pci_remove_one);
7167 #ifdef CONFIG_PM
7168 EXPORT_SYMBOL_GPL(ata_pci_device_do_suspend);
7169 EXPORT_SYMBOL_GPL(ata_pci_device_do_resume);
7170 EXPORT_SYMBOL_GPL(ata_pci_device_suspend);
7171 EXPORT_SYMBOL_GPL(ata_pci_device_resume);
7172 #endif /* CONFIG_PM */
7173 EXPORT_SYMBOL_GPL(ata_pci_default_filter);
7174 EXPORT_SYMBOL_GPL(ata_pci_clear_simplex);
7175 #endif /* CONFIG_PCI */
7176
7177 EXPORT_SYMBOL_GPL(__ata_ehi_push_desc);
7178 EXPORT_SYMBOL_GPL(ata_ehi_push_desc);
7179 EXPORT_SYMBOL_GPL(ata_ehi_clear_desc);
7180 EXPORT_SYMBOL_GPL(ata_port_desc);
7181 #ifdef CONFIG_PCI
7182 EXPORT_SYMBOL_GPL(ata_port_pbar_desc);
7183 #endif /* CONFIG_PCI */
7184 EXPORT_SYMBOL_GPL(ata_eng_timeout);
7185 EXPORT_SYMBOL_GPL(ata_port_schedule_eh);
7186 EXPORT_SYMBOL_GPL(ata_link_abort);
7187 EXPORT_SYMBOL_GPL(ata_port_abort);
7188 EXPORT_SYMBOL_GPL(ata_port_freeze);
7189 EXPORT_SYMBOL_GPL(ata_eh_freeze_port);
7190 EXPORT_SYMBOL_GPL(ata_eh_thaw_port);
7191 EXPORT_SYMBOL_GPL(ata_eh_qc_complete);
7192 EXPORT_SYMBOL_GPL(ata_eh_qc_retry);
7193 EXPORT_SYMBOL_GPL(ata_do_eh);
7194 EXPORT_SYMBOL_GPL(ata_irq_on);
7195 EXPORT_SYMBOL_GPL(ata_dev_try_classify);
7196
7197 EXPORT_SYMBOL_GPL(ata_cable_40wire);
7198 EXPORT_SYMBOL_GPL(ata_cable_80wire);
7199 EXPORT_SYMBOL_GPL(ata_cable_unknown);
7200 EXPORT_SYMBOL_GPL(ata_cable_sata);