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