6f52b598b8d2903fad221c7e687a44e5559ff612
[safe/jmp/linux-2.6] / drivers / ata / libata-sff.c
1 /*
2  *  libata-sff.c - helper library for PCI IDE BMDMA
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-2006 Red Hat, Inc.  All rights reserved.
9  *  Copyright 2003-2006 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/gfp.h>
37 #include <linux/pci.h>
38 #include <linux/libata.h>
39 #include <linux/highmem.h>
40
41 #include "libata.h"
42
43 static struct workqueue_struct *ata_sff_wq;
44
45 const struct ata_port_operations ata_sff_port_ops = {
46         .inherits               = &ata_base_port_ops,
47
48         .qc_prep                = ata_noop_qc_prep,
49         .qc_issue               = ata_sff_qc_issue,
50         .qc_fill_rtf            = ata_sff_qc_fill_rtf,
51
52         .freeze                 = ata_sff_freeze,
53         .thaw                   = ata_sff_thaw,
54         .prereset               = ata_sff_prereset,
55         .softreset              = ata_sff_softreset,
56         .hardreset              = sata_sff_hardreset,
57         .postreset              = ata_sff_postreset,
58         .error_handler          = ata_sff_error_handler,
59
60         .sff_dev_select         = ata_sff_dev_select,
61         .sff_check_status       = ata_sff_check_status,
62         .sff_tf_load            = ata_sff_tf_load,
63         .sff_tf_read            = ata_sff_tf_read,
64         .sff_exec_command       = ata_sff_exec_command,
65         .sff_data_xfer          = ata_sff_data_xfer,
66         .sff_irq_clear          = ata_sff_irq_clear,
67         .sff_drain_fifo         = ata_sff_drain_fifo,
68
69         .lost_interrupt         = ata_sff_lost_interrupt,
70 };
71 EXPORT_SYMBOL_GPL(ata_sff_port_ops);
72
73 /**
74  *      ata_sff_check_status - Read device status reg & clear interrupt
75  *      @ap: port where the device is
76  *
77  *      Reads ATA taskfile status register for currently-selected device
78  *      and return its value. This also clears pending interrupts
79  *      from this device
80  *
81  *      LOCKING:
82  *      Inherited from caller.
83  */
84 u8 ata_sff_check_status(struct ata_port *ap)
85 {
86         return ioread8(ap->ioaddr.status_addr);
87 }
88 EXPORT_SYMBOL_GPL(ata_sff_check_status);
89
90 /**
91  *      ata_sff_altstatus - Read device alternate status reg
92  *      @ap: port where the device is
93  *
94  *      Reads ATA taskfile alternate status register for
95  *      currently-selected device and return its value.
96  *
97  *      Note: may NOT be used as the check_altstatus() entry in
98  *      ata_port_operations.
99  *
100  *      LOCKING:
101  *      Inherited from caller.
102  */
103 static u8 ata_sff_altstatus(struct ata_port *ap)
104 {
105         if (ap->ops->sff_check_altstatus)
106                 return ap->ops->sff_check_altstatus(ap);
107
108         return ioread8(ap->ioaddr.altstatus_addr);
109 }
110
111 /**
112  *      ata_sff_irq_status - Check if the device is busy
113  *      @ap: port where the device is
114  *
115  *      Determine if the port is currently busy. Uses altstatus
116  *      if available in order to avoid clearing shared IRQ status
117  *      when finding an IRQ source. Non ctl capable devices don't
118  *      share interrupt lines fortunately for us.
119  *
120  *      LOCKING:
121  *      Inherited from caller.
122  */
123 static u8 ata_sff_irq_status(struct ata_port *ap)
124 {
125         u8 status;
126
127         if (ap->ops->sff_check_altstatus || ap->ioaddr.altstatus_addr) {
128                 status = ata_sff_altstatus(ap);
129                 /* Not us: We are busy */
130                 if (status & ATA_BUSY)
131                         return status;
132         }
133         /* Clear INTRQ latch */
134         status = ap->ops->sff_check_status(ap);
135         return status;
136 }
137
138 /**
139  *      ata_sff_sync - Flush writes
140  *      @ap: Port to wait for.
141  *
142  *      CAUTION:
143  *      If we have an mmio device with no ctl and no altstatus
144  *      method this will fail. No such devices are known to exist.
145  *
146  *      LOCKING:
147  *      Inherited from caller.
148  */
149
150 static void ata_sff_sync(struct ata_port *ap)
151 {
152         if (ap->ops->sff_check_altstatus)
153                 ap->ops->sff_check_altstatus(ap);
154         else if (ap->ioaddr.altstatus_addr)
155                 ioread8(ap->ioaddr.altstatus_addr);
156 }
157
158 /**
159  *      ata_sff_pause           -       Flush writes and wait 400nS
160  *      @ap: Port to pause for.
161  *
162  *      CAUTION:
163  *      If we have an mmio device with no ctl and no altstatus
164  *      method this will fail. No such devices are known to exist.
165  *
166  *      LOCKING:
167  *      Inherited from caller.
168  */
169
170 void ata_sff_pause(struct ata_port *ap)
171 {
172         ata_sff_sync(ap);
173         ndelay(400);
174 }
175 EXPORT_SYMBOL_GPL(ata_sff_pause);
176
177 /**
178  *      ata_sff_dma_pause       -       Pause before commencing DMA
179  *      @ap: Port to pause for.
180  *
181  *      Perform I/O fencing and ensure sufficient cycle delays occur
182  *      for the HDMA1:0 transition
183  */
184
185 void ata_sff_dma_pause(struct ata_port *ap)
186 {
187         if (ap->ops->sff_check_altstatus || ap->ioaddr.altstatus_addr) {
188                 /* An altstatus read will cause the needed delay without
189                    messing up the IRQ status */
190                 ata_sff_altstatus(ap);
191                 return;
192         }
193         /* There are no DMA controllers without ctl. BUG here to ensure
194            we never violate the HDMA1:0 transition timing and risk
195            corruption. */
196         BUG();
197 }
198 EXPORT_SYMBOL_GPL(ata_sff_dma_pause);
199
200 /**
201  *      ata_sff_busy_sleep - sleep until BSY clears, or timeout
202  *      @ap: port containing status register to be polled
203  *      @tmout_pat: impatience timeout in msecs
204  *      @tmout: overall timeout in msecs
205  *
206  *      Sleep until ATA Status register bit BSY clears,
207  *      or a timeout occurs.
208  *
209  *      LOCKING:
210  *      Kernel thread context (may sleep).
211  *
212  *      RETURNS:
213  *      0 on success, -errno otherwise.
214  */
215 int ata_sff_busy_sleep(struct ata_port *ap,
216                        unsigned long tmout_pat, unsigned long tmout)
217 {
218         unsigned long timer_start, timeout;
219         u8 status;
220
221         status = ata_sff_busy_wait(ap, ATA_BUSY, 300);
222         timer_start = jiffies;
223         timeout = ata_deadline(timer_start, tmout_pat);
224         while (status != 0xff && (status & ATA_BUSY) &&
225                time_before(jiffies, timeout)) {
226                 msleep(50);
227                 status = ata_sff_busy_wait(ap, ATA_BUSY, 3);
228         }
229
230         if (status != 0xff && (status & ATA_BUSY))
231                 ata_port_printk(ap, KERN_WARNING,
232                                 "port is slow to respond, please be patient "
233                                 "(Status 0x%x)\n", status);
234
235         timeout = ata_deadline(timer_start, tmout);
236         while (status != 0xff && (status & ATA_BUSY) &&
237                time_before(jiffies, timeout)) {
238                 msleep(50);
239                 status = ap->ops->sff_check_status(ap);
240         }
241
242         if (status == 0xff)
243                 return -ENODEV;
244
245         if (status & ATA_BUSY) {
246                 ata_port_printk(ap, KERN_ERR, "port failed to respond "
247                                 "(%lu secs, Status 0x%x)\n",
248                                 DIV_ROUND_UP(tmout, 1000), status);
249                 return -EBUSY;
250         }
251
252         return 0;
253 }
254 EXPORT_SYMBOL_GPL(ata_sff_busy_sleep);
255
256 static int ata_sff_check_ready(struct ata_link *link)
257 {
258         u8 status = link->ap->ops->sff_check_status(link->ap);
259
260         return ata_check_ready(status);
261 }
262
263 /**
264  *      ata_sff_wait_ready - sleep until BSY clears, or timeout
265  *      @link: SFF link to wait ready status for
266  *      @deadline: deadline jiffies for the operation
267  *
268  *      Sleep until ATA Status register bit BSY clears, or timeout
269  *      occurs.
270  *
271  *      LOCKING:
272  *      Kernel thread context (may sleep).
273  *
274  *      RETURNS:
275  *      0 on success, -errno otherwise.
276  */
277 int ata_sff_wait_ready(struct ata_link *link, unsigned long deadline)
278 {
279         return ata_wait_ready(link, deadline, ata_sff_check_ready);
280 }
281 EXPORT_SYMBOL_GPL(ata_sff_wait_ready);
282
283 /**
284  *      ata_sff_set_devctl - Write device control reg
285  *      @ap: port where the device is
286  *      @ctl: value to write
287  *
288  *      Writes ATA taskfile device control register.
289  *
290  *      Note: may NOT be used as the sff_set_devctl() entry in
291  *      ata_port_operations.
292  *
293  *      LOCKING:
294  *      Inherited from caller.
295  */
296 static void ata_sff_set_devctl(struct ata_port *ap, u8 ctl)
297 {
298         if (ap->ops->sff_set_devctl)
299                 ap->ops->sff_set_devctl(ap, ctl);
300         else
301                 iowrite8(ctl, ap->ioaddr.ctl_addr);
302 }
303
304 /**
305  *      ata_sff_dev_select - Select device 0/1 on ATA bus
306  *      @ap: ATA channel to manipulate
307  *      @device: ATA device (numbered from zero) to select
308  *
309  *      Use the method defined in the ATA specification to
310  *      make either device 0, or device 1, active on the
311  *      ATA channel.  Works with both PIO and MMIO.
312  *
313  *      May be used as the dev_select() entry in ata_port_operations.
314  *
315  *      LOCKING:
316  *      caller.
317  */
318 void ata_sff_dev_select(struct ata_port *ap, unsigned int device)
319 {
320         u8 tmp;
321
322         if (device == 0)
323                 tmp = ATA_DEVICE_OBS;
324         else
325                 tmp = ATA_DEVICE_OBS | ATA_DEV1;
326
327         iowrite8(tmp, ap->ioaddr.device_addr);
328         ata_sff_pause(ap);      /* needed; also flushes, for mmio */
329 }
330 EXPORT_SYMBOL_GPL(ata_sff_dev_select);
331
332 /**
333  *      ata_dev_select - Select device 0/1 on ATA bus
334  *      @ap: ATA channel to manipulate
335  *      @device: ATA device (numbered from zero) to select
336  *      @wait: non-zero to wait for Status register BSY bit to clear
337  *      @can_sleep: non-zero if context allows sleeping
338  *
339  *      Use the method defined in the ATA specification to
340  *      make either device 0, or device 1, active on the
341  *      ATA channel.
342  *
343  *      This is a high-level version of ata_sff_dev_select(), which
344  *      additionally provides the services of inserting the proper
345  *      pauses and status polling, where needed.
346  *
347  *      LOCKING:
348  *      caller.
349  */
350 static void ata_dev_select(struct ata_port *ap, unsigned int device,
351                            unsigned int wait, unsigned int can_sleep)
352 {
353         if (ata_msg_probe(ap))
354                 ata_port_printk(ap, KERN_INFO, "ata_dev_select: ENTER, "
355                                 "device %u, wait %u\n", device, wait);
356
357         if (wait)
358                 ata_wait_idle(ap);
359
360         ap->ops->sff_dev_select(ap, device);
361
362         if (wait) {
363                 if (can_sleep && ap->link.device[device].class == ATA_DEV_ATAPI)
364                         msleep(150);
365                 ata_wait_idle(ap);
366         }
367 }
368
369 /**
370  *      ata_sff_irq_on - Enable interrupts on a port.
371  *      @ap: Port on which interrupts are enabled.
372  *
373  *      Enable interrupts on a legacy IDE device using MMIO or PIO,
374  *      wait for idle, clear any pending interrupts.
375  *
376  *      Note: may NOT be used as the sff_irq_on() entry in
377  *      ata_port_operations.
378  *
379  *      LOCKING:
380  *      Inherited from caller.
381  */
382 void ata_sff_irq_on(struct ata_port *ap)
383 {
384         struct ata_ioports *ioaddr = &ap->ioaddr;
385
386         if (ap->ops->sff_irq_on) {
387                 ap->ops->sff_irq_on(ap);
388                 return;
389         }
390
391         ap->ctl &= ~ATA_NIEN;
392         ap->last_ctl = ap->ctl;
393
394         if (ap->ops->sff_set_devctl || ioaddr->ctl_addr)
395                 ata_sff_set_devctl(ap, ap->ctl);
396         ata_wait_idle(ap);
397
398         ap->ops->sff_irq_clear(ap);
399 }
400 EXPORT_SYMBOL_GPL(ata_sff_irq_on);
401
402 /**
403  *      ata_sff_irq_clear - Clear PCI IDE BMDMA interrupt.
404  *      @ap: Port associated with this ATA transaction.
405  *
406  *      Clear interrupt and error flags in DMA status register.
407  *
408  *      May be used as the irq_clear() entry in ata_port_operations.
409  *
410  *      LOCKING:
411  *      spin_lock_irqsave(host lock)
412  */
413 void ata_sff_irq_clear(struct ata_port *ap)
414 {
415         void __iomem *mmio = ap->ioaddr.bmdma_addr;
416
417         if (!mmio)
418                 return;
419
420         iowrite8(ioread8(mmio + ATA_DMA_STATUS), mmio + ATA_DMA_STATUS);
421 }
422 EXPORT_SYMBOL_GPL(ata_sff_irq_clear);
423
424 /**
425  *      ata_sff_tf_load - send taskfile registers to host controller
426  *      @ap: Port to which output is sent
427  *      @tf: ATA taskfile register set
428  *
429  *      Outputs ATA taskfile to standard ATA host controller.
430  *
431  *      LOCKING:
432  *      Inherited from caller.
433  */
434 void ata_sff_tf_load(struct ata_port *ap, const struct ata_taskfile *tf)
435 {
436         struct ata_ioports *ioaddr = &ap->ioaddr;
437         unsigned int is_addr = tf->flags & ATA_TFLAG_ISADDR;
438
439         if (tf->ctl != ap->last_ctl) {
440                 if (ioaddr->ctl_addr)
441                         iowrite8(tf->ctl, ioaddr->ctl_addr);
442                 ap->last_ctl = tf->ctl;
443         }
444
445         if (is_addr && (tf->flags & ATA_TFLAG_LBA48)) {
446                 WARN_ON_ONCE(!ioaddr->ctl_addr);
447                 iowrite8(tf->hob_feature, ioaddr->feature_addr);
448                 iowrite8(tf->hob_nsect, ioaddr->nsect_addr);
449                 iowrite8(tf->hob_lbal, ioaddr->lbal_addr);
450                 iowrite8(tf->hob_lbam, ioaddr->lbam_addr);
451                 iowrite8(tf->hob_lbah, ioaddr->lbah_addr);
452                 VPRINTK("hob: feat 0x%X nsect 0x%X, lba 0x%X 0x%X 0x%X\n",
453                         tf->hob_feature,
454                         tf->hob_nsect,
455                         tf->hob_lbal,
456                         tf->hob_lbam,
457                         tf->hob_lbah);
458         }
459
460         if (is_addr) {
461                 iowrite8(tf->feature, ioaddr->feature_addr);
462                 iowrite8(tf->nsect, ioaddr->nsect_addr);
463                 iowrite8(tf->lbal, ioaddr->lbal_addr);
464                 iowrite8(tf->lbam, ioaddr->lbam_addr);
465                 iowrite8(tf->lbah, ioaddr->lbah_addr);
466                 VPRINTK("feat 0x%X nsect 0x%X lba 0x%X 0x%X 0x%X\n",
467                         tf->feature,
468                         tf->nsect,
469                         tf->lbal,
470                         tf->lbam,
471                         tf->lbah);
472         }
473
474         if (tf->flags & ATA_TFLAG_DEVICE) {
475                 iowrite8(tf->device, ioaddr->device_addr);
476                 VPRINTK("device 0x%X\n", tf->device);
477         }
478 }
479 EXPORT_SYMBOL_GPL(ata_sff_tf_load);
480
481 /**
482  *      ata_sff_tf_read - input device's ATA taskfile shadow registers
483  *      @ap: Port from which input is read
484  *      @tf: ATA taskfile register set for storing input
485  *
486  *      Reads ATA taskfile registers for currently-selected device
487  *      into @tf. Assumes the device has a fully SFF compliant task file
488  *      layout and behaviour. If you device does not (eg has a different
489  *      status method) then you will need to provide a replacement tf_read
490  *
491  *      LOCKING:
492  *      Inherited from caller.
493  */
494 void ata_sff_tf_read(struct ata_port *ap, struct ata_taskfile *tf)
495 {
496         struct ata_ioports *ioaddr = &ap->ioaddr;
497
498         tf->command = ata_sff_check_status(ap);
499         tf->feature = ioread8(ioaddr->error_addr);
500         tf->nsect = ioread8(ioaddr->nsect_addr);
501         tf->lbal = ioread8(ioaddr->lbal_addr);
502         tf->lbam = ioread8(ioaddr->lbam_addr);
503         tf->lbah = ioread8(ioaddr->lbah_addr);
504         tf->device = ioread8(ioaddr->device_addr);
505
506         if (tf->flags & ATA_TFLAG_LBA48) {
507                 if (likely(ioaddr->ctl_addr)) {
508                         iowrite8(tf->ctl | ATA_HOB, ioaddr->ctl_addr);
509                         tf->hob_feature = ioread8(ioaddr->error_addr);
510                         tf->hob_nsect = ioread8(ioaddr->nsect_addr);
511                         tf->hob_lbal = ioread8(ioaddr->lbal_addr);
512                         tf->hob_lbam = ioread8(ioaddr->lbam_addr);
513                         tf->hob_lbah = ioread8(ioaddr->lbah_addr);
514                         iowrite8(tf->ctl, ioaddr->ctl_addr);
515                         ap->last_ctl = tf->ctl;
516                 } else
517                         WARN_ON_ONCE(1);
518         }
519 }
520 EXPORT_SYMBOL_GPL(ata_sff_tf_read);
521
522 /**
523  *      ata_sff_exec_command - issue ATA command to host controller
524  *      @ap: port to which command is being issued
525  *      @tf: ATA taskfile register set
526  *
527  *      Issues ATA command, with proper synchronization with interrupt
528  *      handler / other threads.
529  *
530  *      LOCKING:
531  *      spin_lock_irqsave(host lock)
532  */
533 void ata_sff_exec_command(struct ata_port *ap, const struct ata_taskfile *tf)
534 {
535         DPRINTK("ata%u: cmd 0x%X\n", ap->print_id, tf->command);
536
537         iowrite8(tf->command, ap->ioaddr.command_addr);
538         ata_sff_pause(ap);
539 }
540 EXPORT_SYMBOL_GPL(ata_sff_exec_command);
541
542 /**
543  *      ata_tf_to_host - issue ATA taskfile to host controller
544  *      @ap: port to which command is being issued
545  *      @tf: ATA taskfile register set
546  *
547  *      Issues ATA taskfile register set to ATA host controller,
548  *      with proper synchronization with interrupt handler and
549  *      other threads.
550  *
551  *      LOCKING:
552  *      spin_lock_irqsave(host lock)
553  */
554 static inline void ata_tf_to_host(struct ata_port *ap,
555                                   const struct ata_taskfile *tf)
556 {
557         ap->ops->sff_tf_load(ap, tf);
558         ap->ops->sff_exec_command(ap, tf);
559 }
560
561 /**
562  *      ata_sff_data_xfer - Transfer data by PIO
563  *      @dev: device to target
564  *      @buf: data buffer
565  *      @buflen: buffer length
566  *      @rw: read/write
567  *
568  *      Transfer data from/to the device data register by PIO.
569  *
570  *      LOCKING:
571  *      Inherited from caller.
572  *
573  *      RETURNS:
574  *      Bytes consumed.
575  */
576 unsigned int ata_sff_data_xfer(struct ata_device *dev, unsigned char *buf,
577                                unsigned int buflen, int rw)
578 {
579         struct ata_port *ap = dev->link->ap;
580         void __iomem *data_addr = ap->ioaddr.data_addr;
581         unsigned int words = buflen >> 1;
582
583         /* Transfer multiple of 2 bytes */
584         if (rw == READ)
585                 ioread16_rep(data_addr, buf, words);
586         else
587                 iowrite16_rep(data_addr, buf, words);
588
589         /* Transfer trailing byte, if any. */
590         if (unlikely(buflen & 0x01)) {
591                 unsigned char pad[2];
592
593                 /* Point buf to the tail of buffer */
594                 buf += buflen - 1;
595
596                 /*
597                  * Use io*16_rep() accessors here as well to avoid pointlessly
598                  * swapping bytes to and from on the big endian machines...
599                  */
600                 if (rw == READ) {
601                         ioread16_rep(data_addr, pad, 1);
602                         *buf = pad[0];
603                 } else {
604                         pad[0] = *buf;
605                         iowrite16_rep(data_addr, pad, 1);
606                 }
607                 words++;
608         }
609
610         return words << 1;
611 }
612 EXPORT_SYMBOL_GPL(ata_sff_data_xfer);
613
614 /**
615  *      ata_sff_data_xfer32 - Transfer data by PIO
616  *      @dev: device to target
617  *      @buf: data buffer
618  *      @buflen: buffer length
619  *      @rw: read/write
620  *
621  *      Transfer data from/to the device data register by PIO using 32bit
622  *      I/O operations.
623  *
624  *      LOCKING:
625  *      Inherited from caller.
626  *
627  *      RETURNS:
628  *      Bytes consumed.
629  */
630
631 unsigned int ata_sff_data_xfer32(struct ata_device *dev, unsigned char *buf,
632                                unsigned int buflen, int rw)
633 {
634         struct ata_port *ap = dev->link->ap;
635         void __iomem *data_addr = ap->ioaddr.data_addr;
636         unsigned int words = buflen >> 2;
637         int slop = buflen & 3;
638
639         if (!(ap->pflags & ATA_PFLAG_PIO32))
640                 return ata_sff_data_xfer(dev, buf, buflen, rw);
641
642         /* Transfer multiple of 4 bytes */
643         if (rw == READ)
644                 ioread32_rep(data_addr, buf, words);
645         else
646                 iowrite32_rep(data_addr, buf, words);
647
648         /* Transfer trailing bytes, if any */
649         if (unlikely(slop)) {
650                 unsigned char pad[4];
651
652                 /* Point buf to the tail of buffer */
653                 buf += buflen - slop;
654
655                 /*
656                  * Use io*_rep() accessors here as well to avoid pointlessly
657                  * swapping bytes to and from on the big endian machines...
658                  */
659                 if (rw == READ) {
660                         if (slop < 3)
661                                 ioread16_rep(data_addr, pad, 1);
662                         else
663                                 ioread32_rep(data_addr, pad, 1);
664                         memcpy(buf, pad, slop);
665                 } else {
666                         memcpy(pad, buf, slop);
667                         if (slop < 3)
668                                 iowrite16_rep(data_addr, pad, 1);
669                         else
670                                 iowrite32_rep(data_addr, pad, 1);
671                 }
672         }
673         return (buflen + 1) & ~1;
674 }
675 EXPORT_SYMBOL_GPL(ata_sff_data_xfer32);
676
677 /**
678  *      ata_sff_data_xfer_noirq - Transfer data by PIO
679  *      @dev: device to target
680  *      @buf: data buffer
681  *      @buflen: buffer length
682  *      @rw: read/write
683  *
684  *      Transfer data from/to the device data register by PIO. Do the
685  *      transfer with interrupts disabled.
686  *
687  *      LOCKING:
688  *      Inherited from caller.
689  *
690  *      RETURNS:
691  *      Bytes consumed.
692  */
693 unsigned int ata_sff_data_xfer_noirq(struct ata_device *dev, unsigned char *buf,
694                                      unsigned int buflen, int rw)
695 {
696         unsigned long flags;
697         unsigned int consumed;
698
699         local_irq_save(flags);
700         consumed = ata_sff_data_xfer(dev, buf, buflen, rw);
701         local_irq_restore(flags);
702
703         return consumed;
704 }
705 EXPORT_SYMBOL_GPL(ata_sff_data_xfer_noirq);
706
707 /**
708  *      ata_pio_sector - Transfer a sector of data.
709  *      @qc: Command on going
710  *
711  *      Transfer qc->sect_size bytes of data from/to the ATA device.
712  *
713  *      LOCKING:
714  *      Inherited from caller.
715  */
716 static void ata_pio_sector(struct ata_queued_cmd *qc)
717 {
718         int do_write = (qc->tf.flags & ATA_TFLAG_WRITE);
719         struct ata_port *ap = qc->ap;
720         struct page *page;
721         unsigned int offset;
722         unsigned char *buf;
723
724         if (qc->curbytes == qc->nbytes - qc->sect_size)
725                 ap->hsm_task_state = HSM_ST_LAST;
726
727         page = sg_page(qc->cursg);
728         offset = qc->cursg->offset + qc->cursg_ofs;
729
730         /* get the current page and offset */
731         page = nth_page(page, (offset >> PAGE_SHIFT));
732         offset %= PAGE_SIZE;
733
734         DPRINTK("data %s\n", qc->tf.flags & ATA_TFLAG_WRITE ? "write" : "read");
735
736         if (PageHighMem(page)) {
737                 unsigned long flags;
738
739                 /* FIXME: use a bounce buffer */
740                 local_irq_save(flags);
741                 buf = kmap_atomic(page, KM_IRQ0);
742
743                 /* do the actual data transfer */
744                 ap->ops->sff_data_xfer(qc->dev, buf + offset, qc->sect_size,
745                                        do_write);
746
747                 kunmap_atomic(buf, KM_IRQ0);
748                 local_irq_restore(flags);
749         } else {
750                 buf = page_address(page);
751                 ap->ops->sff_data_xfer(qc->dev, buf + offset, qc->sect_size,
752                                        do_write);
753         }
754
755         if (!do_write && !PageSlab(page))
756                 flush_dcache_page(page);
757
758         qc->curbytes += qc->sect_size;
759         qc->cursg_ofs += qc->sect_size;
760
761         if (qc->cursg_ofs == qc->cursg->length) {
762                 qc->cursg = sg_next(qc->cursg);
763                 qc->cursg_ofs = 0;
764         }
765 }
766
767 /**
768  *      ata_pio_sectors - Transfer one or many sectors.
769  *      @qc: Command on going
770  *
771  *      Transfer one or many sectors of data from/to the
772  *      ATA device for the DRQ request.
773  *
774  *      LOCKING:
775  *      Inherited from caller.
776  */
777 static void ata_pio_sectors(struct ata_queued_cmd *qc)
778 {
779         if (is_multi_taskfile(&qc->tf)) {
780                 /* READ/WRITE MULTIPLE */
781                 unsigned int nsect;
782
783                 WARN_ON_ONCE(qc->dev->multi_count == 0);
784
785                 nsect = min((qc->nbytes - qc->curbytes) / qc->sect_size,
786                             qc->dev->multi_count);
787                 while (nsect--)
788                         ata_pio_sector(qc);
789         } else
790                 ata_pio_sector(qc);
791
792         ata_sff_sync(qc->ap); /* flush */
793 }
794
795 /**
796  *      atapi_send_cdb - Write CDB bytes to hardware
797  *      @ap: Port to which ATAPI device is attached.
798  *      @qc: Taskfile currently active
799  *
800  *      When device has indicated its readiness to accept
801  *      a CDB, this function is called.  Send the CDB.
802  *
803  *      LOCKING:
804  *      caller.
805  */
806 static void atapi_send_cdb(struct ata_port *ap, struct ata_queued_cmd *qc)
807 {
808         /* send SCSI cdb */
809         DPRINTK("send cdb\n");
810         WARN_ON_ONCE(qc->dev->cdb_len < 12);
811
812         ap->ops->sff_data_xfer(qc->dev, qc->cdb, qc->dev->cdb_len, 1);
813         ata_sff_sync(ap);
814         /* FIXME: If the CDB is for DMA do we need to do the transition delay
815            or is bmdma_start guaranteed to do it ? */
816         switch (qc->tf.protocol) {
817         case ATAPI_PROT_PIO:
818                 ap->hsm_task_state = HSM_ST;
819                 break;
820         case ATAPI_PROT_NODATA:
821                 ap->hsm_task_state = HSM_ST_LAST;
822                 break;
823         case ATAPI_PROT_DMA:
824                 ap->hsm_task_state = HSM_ST_LAST;
825                 /* initiate bmdma */
826                 ap->ops->bmdma_start(qc);
827                 break;
828         }
829 }
830
831 /**
832  *      __atapi_pio_bytes - Transfer data from/to the ATAPI device.
833  *      @qc: Command on going
834  *      @bytes: number of bytes
835  *
836  *      Transfer Transfer data from/to the ATAPI device.
837  *
838  *      LOCKING:
839  *      Inherited from caller.
840  *
841  */
842 static int __atapi_pio_bytes(struct ata_queued_cmd *qc, unsigned int bytes)
843 {
844         int rw = (qc->tf.flags & ATA_TFLAG_WRITE) ? WRITE : READ;
845         struct ata_port *ap = qc->ap;
846         struct ata_device *dev = qc->dev;
847         struct ata_eh_info *ehi = &dev->link->eh_info;
848         struct scatterlist *sg;
849         struct page *page;
850         unsigned char *buf;
851         unsigned int offset, count, consumed;
852
853 next_sg:
854         sg = qc->cursg;
855         if (unlikely(!sg)) {
856                 ata_ehi_push_desc(ehi, "unexpected or too much trailing data "
857                                   "buf=%u cur=%u bytes=%u",
858                                   qc->nbytes, qc->curbytes, bytes);
859                 return -1;
860         }
861
862         page = sg_page(sg);
863         offset = sg->offset + qc->cursg_ofs;
864
865         /* get the current page and offset */
866         page = nth_page(page, (offset >> PAGE_SHIFT));
867         offset %= PAGE_SIZE;
868
869         /* don't overrun current sg */
870         count = min(sg->length - qc->cursg_ofs, bytes);
871
872         /* don't cross page boundaries */
873         count = min(count, (unsigned int)PAGE_SIZE - offset);
874
875         DPRINTK("data %s\n", qc->tf.flags & ATA_TFLAG_WRITE ? "write" : "read");
876
877         if (PageHighMem(page)) {
878                 unsigned long flags;
879
880                 /* FIXME: use bounce buffer */
881                 local_irq_save(flags);
882                 buf = kmap_atomic(page, KM_IRQ0);
883
884                 /* do the actual data transfer */
885                 consumed = ap->ops->sff_data_xfer(dev,  buf + offset,
886                                                                 count, rw);
887
888                 kunmap_atomic(buf, KM_IRQ0);
889                 local_irq_restore(flags);
890         } else {
891                 buf = page_address(page);
892                 consumed = ap->ops->sff_data_xfer(dev,  buf + offset,
893                                                                 count, rw);
894         }
895
896         bytes -= min(bytes, consumed);
897         qc->curbytes += count;
898         qc->cursg_ofs += count;
899
900         if (qc->cursg_ofs == sg->length) {
901                 qc->cursg = sg_next(qc->cursg);
902                 qc->cursg_ofs = 0;
903         }
904
905         /*
906          * There used to be a  WARN_ON_ONCE(qc->cursg && count != consumed);
907          * Unfortunately __atapi_pio_bytes doesn't know enough to do the WARN
908          * check correctly as it doesn't know if it is the last request being
909          * made. Somebody should implement a proper sanity check.
910          */
911         if (bytes)
912                 goto next_sg;
913         return 0;
914 }
915
916 /**
917  *      atapi_pio_bytes - Transfer data from/to the ATAPI device.
918  *      @qc: Command on going
919  *
920  *      Transfer Transfer data from/to the ATAPI device.
921  *
922  *      LOCKING:
923  *      Inherited from caller.
924  */
925 static void atapi_pio_bytes(struct ata_queued_cmd *qc)
926 {
927         struct ata_port *ap = qc->ap;
928         struct ata_device *dev = qc->dev;
929         struct ata_eh_info *ehi = &dev->link->eh_info;
930         unsigned int ireason, bc_lo, bc_hi, bytes;
931         int i_write, do_write = (qc->tf.flags & ATA_TFLAG_WRITE) ? 1 : 0;
932
933         /* Abuse qc->result_tf for temp storage of intermediate TF
934          * here to save some kernel stack usage.
935          * For normal completion, qc->result_tf is not relevant. For
936          * error, qc->result_tf is later overwritten by ata_qc_complete().
937          * So, the correctness of qc->result_tf is not affected.
938          */
939         ap->ops->sff_tf_read(ap, &qc->result_tf);
940         ireason = qc->result_tf.nsect;
941         bc_lo = qc->result_tf.lbam;
942         bc_hi = qc->result_tf.lbah;
943         bytes = (bc_hi << 8) | bc_lo;
944
945         /* shall be cleared to zero, indicating xfer of data */
946         if (unlikely(ireason & (1 << 0)))
947                 goto atapi_check;
948
949         /* make sure transfer direction matches expected */
950         i_write = ((ireason & (1 << 1)) == 0) ? 1 : 0;
951         if (unlikely(do_write != i_write))
952                 goto atapi_check;
953
954         if (unlikely(!bytes))
955                 goto atapi_check;
956
957         VPRINTK("ata%u: xfering %d bytes\n", ap->print_id, bytes);
958
959         if (unlikely(__atapi_pio_bytes(qc, bytes)))
960                 goto err_out;
961         ata_sff_sync(ap); /* flush */
962
963         return;
964
965  atapi_check:
966         ata_ehi_push_desc(ehi, "ATAPI check failed (ireason=0x%x bytes=%u)",
967                           ireason, bytes);
968  err_out:
969         qc->err_mask |= AC_ERR_HSM;
970         ap->hsm_task_state = HSM_ST_ERR;
971 }
972
973 /**
974  *      ata_hsm_ok_in_wq - Check if the qc can be handled in the workqueue.
975  *      @ap: the target ata_port
976  *      @qc: qc on going
977  *
978  *      RETURNS:
979  *      1 if ok in workqueue, 0 otherwise.
980  */
981 static inline int ata_hsm_ok_in_wq(struct ata_port *ap,
982                                                 struct ata_queued_cmd *qc)
983 {
984         if (qc->tf.flags & ATA_TFLAG_POLLING)
985                 return 1;
986
987         if (ap->hsm_task_state == HSM_ST_FIRST) {
988                 if (qc->tf.protocol == ATA_PROT_PIO &&
989                    (qc->tf.flags & ATA_TFLAG_WRITE))
990                     return 1;
991
992                 if (ata_is_atapi(qc->tf.protocol) &&
993                    !(qc->dev->flags & ATA_DFLAG_CDB_INTR))
994                         return 1;
995         }
996
997         return 0;
998 }
999
1000 /**
1001  *      ata_hsm_qc_complete - finish a qc running on standard HSM
1002  *      @qc: Command to complete
1003  *      @in_wq: 1 if called from workqueue, 0 otherwise
1004  *
1005  *      Finish @qc which is running on standard HSM.
1006  *
1007  *      LOCKING:
1008  *      If @in_wq is zero, spin_lock_irqsave(host lock).
1009  *      Otherwise, none on entry and grabs host lock.
1010  */
1011 static void ata_hsm_qc_complete(struct ata_queued_cmd *qc, int in_wq)
1012 {
1013         struct ata_port *ap = qc->ap;
1014         unsigned long flags;
1015
1016         if (ap->ops->error_handler) {
1017                 if (in_wq) {
1018                         spin_lock_irqsave(ap->lock, flags);
1019
1020                         /* EH might have kicked in while host lock is
1021                          * released.
1022                          */
1023                         qc = ata_qc_from_tag(ap, qc->tag);
1024                         if (qc) {
1025                                 if (likely(!(qc->err_mask & AC_ERR_HSM))) {
1026                                         ata_sff_irq_on(ap);
1027                                         ata_qc_complete(qc);
1028                                 } else
1029                                         ata_port_freeze(ap);
1030                         }
1031
1032                         spin_unlock_irqrestore(ap->lock, flags);
1033                 } else {
1034                         if (likely(!(qc->err_mask & AC_ERR_HSM)))
1035                                 ata_qc_complete(qc);
1036                         else
1037                                 ata_port_freeze(ap);
1038                 }
1039         } else {
1040                 if (in_wq) {
1041                         spin_lock_irqsave(ap->lock, flags);
1042                         ata_sff_irq_on(ap);
1043                         ata_qc_complete(qc);
1044                         spin_unlock_irqrestore(ap->lock, flags);
1045                 } else
1046                         ata_qc_complete(qc);
1047         }
1048 }
1049
1050 /**
1051  *      ata_sff_hsm_move - move the HSM to the next state.
1052  *      @ap: the target ata_port
1053  *      @qc: qc on going
1054  *      @status: current device status
1055  *      @in_wq: 1 if called from workqueue, 0 otherwise
1056  *
1057  *      RETURNS:
1058  *      1 when poll next status needed, 0 otherwise.
1059  */
1060 int ata_sff_hsm_move(struct ata_port *ap, struct ata_queued_cmd *qc,
1061                      u8 status, int in_wq)
1062 {
1063         struct ata_eh_info *ehi = &ap->link.eh_info;
1064         unsigned long flags = 0;
1065         int poll_next;
1066
1067         WARN_ON_ONCE((qc->flags & ATA_QCFLAG_ACTIVE) == 0);
1068
1069         /* Make sure ata_sff_qc_issue() does not throw things
1070          * like DMA polling into the workqueue. Notice that
1071          * in_wq is not equivalent to (qc->tf.flags & ATA_TFLAG_POLLING).
1072          */
1073         WARN_ON_ONCE(in_wq != ata_hsm_ok_in_wq(ap, qc));
1074
1075 fsm_start:
1076         DPRINTK("ata%u: protocol %d task_state %d (dev_stat 0x%X)\n",
1077                 ap->print_id, qc->tf.protocol, ap->hsm_task_state, status);
1078
1079         switch (ap->hsm_task_state) {
1080         case HSM_ST_FIRST:
1081                 /* Send first data block or PACKET CDB */
1082
1083                 /* If polling, we will stay in the work queue after
1084                  * sending the data. Otherwise, interrupt handler
1085                  * takes over after sending the data.
1086                  */
1087                 poll_next = (qc->tf.flags & ATA_TFLAG_POLLING);
1088
1089                 /* check device status */
1090                 if (unlikely((status & ATA_DRQ) == 0)) {
1091                         /* handle BSY=0, DRQ=0 as error */
1092                         if (likely(status & (ATA_ERR | ATA_DF)))
1093                                 /* device stops HSM for abort/error */
1094                                 qc->err_mask |= AC_ERR_DEV;
1095                         else {
1096                                 /* HSM violation. Let EH handle this */
1097                                 ata_ehi_push_desc(ehi,
1098                                         "ST_FIRST: !(DRQ|ERR|DF)");
1099                                 qc->err_mask |= AC_ERR_HSM;
1100                         }
1101
1102                         ap->hsm_task_state = HSM_ST_ERR;
1103                         goto fsm_start;
1104                 }
1105
1106                 /* Device should not ask for data transfer (DRQ=1)
1107                  * when it finds something wrong.
1108                  * We ignore DRQ here and stop the HSM by
1109                  * changing hsm_task_state to HSM_ST_ERR and
1110                  * let the EH abort the command or reset the device.
1111                  */
1112                 if (unlikely(status & (ATA_ERR | ATA_DF))) {
1113                         /* Some ATAPI tape drives forget to clear the ERR bit
1114                          * when doing the next command (mostly request sense).
1115                          * We ignore ERR here to workaround and proceed sending
1116                          * the CDB.
1117                          */
1118                         if (!(qc->dev->horkage & ATA_HORKAGE_STUCK_ERR)) {
1119                                 ata_ehi_push_desc(ehi, "ST_FIRST: "
1120                                         "DRQ=1 with device error, "
1121                                         "dev_stat 0x%X", status);
1122                                 qc->err_mask |= AC_ERR_HSM;
1123                                 ap->hsm_task_state = HSM_ST_ERR;
1124                                 goto fsm_start;
1125                         }
1126                 }
1127
1128                 /* Send the CDB (atapi) or the first data block (ata pio out).
1129                  * During the state transition, interrupt handler shouldn't
1130                  * be invoked before the data transfer is complete and
1131                  * hsm_task_state is changed. Hence, the following locking.
1132                  */
1133                 if (in_wq)
1134                         spin_lock_irqsave(ap->lock, flags);
1135
1136                 if (qc->tf.protocol == ATA_PROT_PIO) {
1137                         /* PIO data out protocol.
1138                          * send first data block.
1139                          */
1140
1141                         /* ata_pio_sectors() might change the state
1142                          * to HSM_ST_LAST. so, the state is changed here
1143                          * before ata_pio_sectors().
1144                          */
1145                         ap->hsm_task_state = HSM_ST;
1146                         ata_pio_sectors(qc);
1147                 } else
1148                         /* send CDB */
1149                         atapi_send_cdb(ap, qc);
1150
1151                 if (in_wq)
1152                         spin_unlock_irqrestore(ap->lock, flags);
1153
1154                 /* if polling, ata_sff_pio_task() handles the rest.
1155                  * otherwise, interrupt handler takes over from here.
1156                  */
1157                 break;
1158
1159         case HSM_ST:
1160                 /* complete command or read/write the data register */
1161                 if (qc->tf.protocol == ATAPI_PROT_PIO) {
1162                         /* ATAPI PIO protocol */
1163                         if ((status & ATA_DRQ) == 0) {
1164                                 /* No more data to transfer or device error.
1165                                  * Device error will be tagged in HSM_ST_LAST.
1166                                  */
1167                                 ap->hsm_task_state = HSM_ST_LAST;
1168                                 goto fsm_start;
1169                         }
1170
1171                         /* Device should not ask for data transfer (DRQ=1)
1172                          * when it finds something wrong.
1173                          * We ignore DRQ here and stop the HSM by
1174                          * changing hsm_task_state to HSM_ST_ERR and
1175                          * let the EH abort the command or reset the device.
1176                          */
1177                         if (unlikely(status & (ATA_ERR | ATA_DF))) {
1178                                 ata_ehi_push_desc(ehi, "ST-ATAPI: "
1179                                         "DRQ=1 with device error, "
1180                                         "dev_stat 0x%X", status);
1181                                 qc->err_mask |= AC_ERR_HSM;
1182                                 ap->hsm_task_state = HSM_ST_ERR;
1183                                 goto fsm_start;
1184                         }
1185
1186                         atapi_pio_bytes(qc);
1187
1188                         if (unlikely(ap->hsm_task_state == HSM_ST_ERR))
1189                                 /* bad ireason reported by device */
1190                                 goto fsm_start;
1191
1192                 } else {
1193                         /* ATA PIO protocol */
1194                         if (unlikely((status & ATA_DRQ) == 0)) {
1195                                 /* handle BSY=0, DRQ=0 as error */
1196                                 if (likely(status & (ATA_ERR | ATA_DF))) {
1197                                         /* device stops HSM for abort/error */
1198                                         qc->err_mask |= AC_ERR_DEV;
1199
1200                                         /* If diagnostic failed and this is
1201                                          * IDENTIFY, it's likely a phantom
1202                                          * device.  Mark hint.
1203                                          */
1204                                         if (qc->dev->horkage &
1205                                             ATA_HORKAGE_DIAGNOSTIC)
1206                                                 qc->err_mask |=
1207                                                         AC_ERR_NODEV_HINT;
1208                                 } else {
1209                                         /* HSM violation. Let EH handle this.
1210                                          * Phantom devices also trigger this
1211                                          * condition.  Mark hint.
1212                                          */
1213                                         ata_ehi_push_desc(ehi, "ST-ATA: "
1214                                                 "DRQ=0 without device error, "
1215                                                 "dev_stat 0x%X", status);
1216                                         qc->err_mask |= AC_ERR_HSM |
1217                                                         AC_ERR_NODEV_HINT;
1218                                 }
1219
1220                                 ap->hsm_task_state = HSM_ST_ERR;
1221                                 goto fsm_start;
1222                         }
1223
1224                         /* For PIO reads, some devices may ask for
1225                          * data transfer (DRQ=1) alone with ERR=1.
1226                          * We respect DRQ here and transfer one
1227                          * block of junk data before changing the
1228                          * hsm_task_state to HSM_ST_ERR.
1229                          *
1230                          * For PIO writes, ERR=1 DRQ=1 doesn't make
1231                          * sense since the data block has been
1232                          * transferred to the device.
1233                          */
1234                         if (unlikely(status & (ATA_ERR | ATA_DF))) {
1235                                 /* data might be corrputed */
1236                                 qc->err_mask |= AC_ERR_DEV;
1237
1238                                 if (!(qc->tf.flags & ATA_TFLAG_WRITE)) {
1239                                         ata_pio_sectors(qc);
1240                                         status = ata_wait_idle(ap);
1241                                 }
1242
1243                                 if (status & (ATA_BUSY | ATA_DRQ)) {
1244                                         ata_ehi_push_desc(ehi, "ST-ATA: "
1245                                                 "BUSY|DRQ persists on ERR|DF, "
1246                                                 "dev_stat 0x%X", status);
1247                                         qc->err_mask |= AC_ERR_HSM;
1248                                 }
1249
1250                                 /* There are oddball controllers with
1251                                  * status register stuck at 0x7f and
1252                                  * lbal/m/h at zero which makes it
1253                                  * pass all other presence detection
1254                                  * mechanisms we have.  Set NODEV_HINT
1255                                  * for it.  Kernel bz#7241.
1256                                  */
1257                                 if (status == 0x7f)
1258                                         qc->err_mask |= AC_ERR_NODEV_HINT;
1259
1260                                 /* ata_pio_sectors() might change the
1261                                  * state to HSM_ST_LAST. so, the state
1262                                  * is changed after ata_pio_sectors().
1263                                  */
1264                                 ap->hsm_task_state = HSM_ST_ERR;
1265                                 goto fsm_start;
1266                         }
1267
1268                         ata_pio_sectors(qc);
1269
1270                         if (ap->hsm_task_state == HSM_ST_LAST &&
1271                             (!(qc->tf.flags & ATA_TFLAG_WRITE))) {
1272                                 /* all data read */
1273                                 status = ata_wait_idle(ap);
1274                                 goto fsm_start;
1275                         }
1276                 }
1277
1278                 poll_next = 1;
1279                 break;
1280
1281         case HSM_ST_LAST:
1282                 if (unlikely(!ata_ok(status))) {
1283                         qc->err_mask |= __ac_err_mask(status);
1284                         ap->hsm_task_state = HSM_ST_ERR;
1285                         goto fsm_start;
1286                 }
1287
1288                 /* no more data to transfer */
1289                 DPRINTK("ata%u: dev %u command complete, drv_stat 0x%x\n",
1290                         ap->print_id, qc->dev->devno, status);
1291
1292                 WARN_ON_ONCE(qc->err_mask & (AC_ERR_DEV | AC_ERR_HSM));
1293
1294                 ap->hsm_task_state = HSM_ST_IDLE;
1295
1296                 /* complete taskfile transaction */
1297                 ata_hsm_qc_complete(qc, in_wq);
1298
1299                 poll_next = 0;
1300                 break;
1301
1302         case HSM_ST_ERR:
1303                 ap->hsm_task_state = HSM_ST_IDLE;
1304
1305                 /* complete taskfile transaction */
1306                 ata_hsm_qc_complete(qc, in_wq);
1307
1308                 poll_next = 0;
1309                 break;
1310         default:
1311                 poll_next = 0;
1312                 BUG();
1313         }
1314
1315         return poll_next;
1316 }
1317 EXPORT_SYMBOL_GPL(ata_sff_hsm_move);
1318
1319 void ata_sff_queue_pio_task(struct ata_port *ap, unsigned long delay)
1320 {
1321         /* may fail if ata_sff_flush_pio_task() in progress */
1322         queue_delayed_work(ata_sff_wq, &ap->sff_pio_task,
1323                            msecs_to_jiffies(delay));
1324 }
1325 EXPORT_SYMBOL_GPL(ata_sff_queue_pio_task);
1326
1327 void ata_sff_flush_pio_task(struct ata_port *ap)
1328 {
1329         DPRINTK("ENTER\n");
1330
1331         cancel_rearming_delayed_work(&ap->sff_pio_task);
1332         ap->hsm_task_state = HSM_ST_IDLE;
1333
1334         if (ata_msg_ctl(ap))
1335                 ata_port_printk(ap, KERN_DEBUG, "%s: EXIT\n", __func__);
1336 }
1337
1338 static void ata_sff_pio_task(struct work_struct *work)
1339 {
1340         struct ata_port *ap =
1341                 container_of(work, struct ata_port, sff_pio_task.work);
1342         struct ata_queued_cmd *qc;
1343         u8 status;
1344         int poll_next;
1345
1346         /* qc can be NULL if timeout occurred */
1347         qc = ata_qc_from_tag(ap, ap->link.active_tag);
1348         if (!qc)
1349                 return;
1350
1351 fsm_start:
1352         WARN_ON_ONCE(ap->hsm_task_state == HSM_ST_IDLE);
1353
1354         /*
1355          * This is purely heuristic.  This is a fast path.
1356          * Sometimes when we enter, BSY will be cleared in
1357          * a chk-status or two.  If not, the drive is probably seeking
1358          * or something.  Snooze for a couple msecs, then
1359          * chk-status again.  If still busy, queue delayed work.
1360          */
1361         status = ata_sff_busy_wait(ap, ATA_BUSY, 5);
1362         if (status & ATA_BUSY) {
1363                 msleep(2);
1364                 status = ata_sff_busy_wait(ap, ATA_BUSY, 10);
1365                 if (status & ATA_BUSY) {
1366                         ata_sff_queue_pio_task(ap, ATA_SHORT_PAUSE);
1367                         return;
1368                 }
1369         }
1370
1371         /* move the HSM */
1372         poll_next = ata_sff_hsm_move(ap, qc, status, 1);
1373
1374         /* another command or interrupt handler
1375          * may be running at this point.
1376          */
1377         if (poll_next)
1378                 goto fsm_start;
1379 }
1380
1381 /**
1382  *      ata_sff_qc_issue - issue taskfile to device in proto-dependent manner
1383  *      @qc: command to issue to device
1384  *
1385  *      Using various libata functions and hooks, this function
1386  *      starts an ATA command.  ATA commands are grouped into
1387  *      classes called "protocols", and issuing each type of protocol
1388  *      is slightly different.
1389  *
1390  *      May be used as the qc_issue() entry in ata_port_operations.
1391  *
1392  *      LOCKING:
1393  *      spin_lock_irqsave(host lock)
1394  *
1395  *      RETURNS:
1396  *      Zero on success, AC_ERR_* mask on failure
1397  */
1398 unsigned int ata_sff_qc_issue(struct ata_queued_cmd *qc)
1399 {
1400         struct ata_port *ap = qc->ap;
1401
1402         /* Use polling pio if the LLD doesn't handle
1403          * interrupt driven pio and atapi CDB interrupt.
1404          */
1405         if (ap->flags & ATA_FLAG_PIO_POLLING) {
1406                 switch (qc->tf.protocol) {
1407                 case ATA_PROT_PIO:
1408                 case ATA_PROT_NODATA:
1409                 case ATAPI_PROT_PIO:
1410                 case ATAPI_PROT_NODATA:
1411                         qc->tf.flags |= ATA_TFLAG_POLLING;
1412                         break;
1413                 case ATAPI_PROT_DMA:
1414                         if (qc->dev->flags & ATA_DFLAG_CDB_INTR)
1415                                 /* see ata_dma_blacklisted() */
1416                                 BUG();
1417                         break;
1418                 default:
1419                         break;
1420                 }
1421         }
1422
1423         /* select the device */
1424         ata_dev_select(ap, qc->dev->devno, 1, 0);
1425
1426         /* start the command */
1427         switch (qc->tf.protocol) {
1428         case ATA_PROT_NODATA:
1429                 if (qc->tf.flags & ATA_TFLAG_POLLING)
1430                         ata_qc_set_polling(qc);
1431
1432                 ata_tf_to_host(ap, &qc->tf);
1433                 ap->hsm_task_state = HSM_ST_LAST;
1434
1435                 if (qc->tf.flags & ATA_TFLAG_POLLING)
1436                         ata_sff_queue_pio_task(ap, 0);
1437
1438                 break;
1439
1440         case ATA_PROT_DMA:
1441                 WARN_ON_ONCE(qc->tf.flags & ATA_TFLAG_POLLING);
1442
1443                 ap->ops->sff_tf_load(ap, &qc->tf);  /* load tf registers */
1444                 ap->ops->bmdma_setup(qc);           /* set up bmdma */
1445                 ap->ops->bmdma_start(qc);           /* initiate bmdma */
1446                 ap->hsm_task_state = HSM_ST_LAST;
1447                 break;
1448
1449         case ATA_PROT_PIO:
1450                 if (qc->tf.flags & ATA_TFLAG_POLLING)
1451                         ata_qc_set_polling(qc);
1452
1453                 ata_tf_to_host(ap, &qc->tf);
1454
1455                 if (qc->tf.flags & ATA_TFLAG_WRITE) {
1456                         /* PIO data out protocol */
1457                         ap->hsm_task_state = HSM_ST_FIRST;
1458                         ata_sff_queue_pio_task(ap, 0);
1459
1460                         /* always send first data block using the
1461                          * ata_sff_pio_task() codepath.
1462                          */
1463                 } else {
1464                         /* PIO data in protocol */
1465                         ap->hsm_task_state = HSM_ST;
1466
1467                         if (qc->tf.flags & ATA_TFLAG_POLLING)
1468                                 ata_sff_queue_pio_task(ap, 0);
1469
1470                         /* if polling, ata_sff_pio_task() handles the
1471                          * rest.  otherwise, interrupt handler takes
1472                          * over from here.
1473                          */
1474                 }
1475
1476                 break;
1477
1478         case ATAPI_PROT_PIO:
1479         case ATAPI_PROT_NODATA:
1480                 if (qc->tf.flags & ATA_TFLAG_POLLING)
1481                         ata_qc_set_polling(qc);
1482
1483                 ata_tf_to_host(ap, &qc->tf);
1484
1485                 ap->hsm_task_state = HSM_ST_FIRST;
1486
1487                 /* send cdb by polling if no cdb interrupt */
1488                 if ((!(qc->dev->flags & ATA_DFLAG_CDB_INTR)) ||
1489                     (qc->tf.flags & ATA_TFLAG_POLLING))
1490                         ata_sff_queue_pio_task(ap, 0);
1491                 break;
1492
1493         case ATAPI_PROT_DMA:
1494                 WARN_ON_ONCE(qc->tf.flags & ATA_TFLAG_POLLING);
1495
1496                 ap->ops->sff_tf_load(ap, &qc->tf);  /* load tf registers */
1497                 ap->ops->bmdma_setup(qc);           /* set up bmdma */
1498                 ap->hsm_task_state = HSM_ST_FIRST;
1499
1500                 /* send cdb by polling if no cdb interrupt */
1501                 if (!(qc->dev->flags & ATA_DFLAG_CDB_INTR))
1502                         ata_sff_queue_pio_task(ap, 0);
1503                 break;
1504
1505         default:
1506                 WARN_ON_ONCE(1);
1507                 return AC_ERR_SYSTEM;
1508         }
1509
1510         return 0;
1511 }
1512 EXPORT_SYMBOL_GPL(ata_sff_qc_issue);
1513
1514 /**
1515  *      ata_sff_qc_fill_rtf - fill result TF using ->sff_tf_read
1516  *      @qc: qc to fill result TF for
1517  *
1518  *      @qc is finished and result TF needs to be filled.  Fill it
1519  *      using ->sff_tf_read.
1520  *
1521  *      LOCKING:
1522  *      spin_lock_irqsave(host lock)
1523  *
1524  *      RETURNS:
1525  *      true indicating that result TF is successfully filled.
1526  */
1527 bool ata_sff_qc_fill_rtf(struct ata_queued_cmd *qc)
1528 {
1529         qc->ap->ops->sff_tf_read(qc->ap, &qc->result_tf);
1530         return true;
1531 }
1532 EXPORT_SYMBOL_GPL(ata_sff_qc_fill_rtf);
1533
1534 /**
1535  *      ata_sff_host_intr - Handle host interrupt for given (port, task)
1536  *      @ap: Port on which interrupt arrived (possibly...)
1537  *      @qc: Taskfile currently active in engine
1538  *
1539  *      Handle host interrupt for given queued command.  Currently,
1540  *      only DMA interrupts are handled.  All other commands are
1541  *      handled via polling with interrupts disabled (nIEN bit).
1542  *
1543  *      LOCKING:
1544  *      spin_lock_irqsave(host lock)
1545  *
1546  *      RETURNS:
1547  *      One if interrupt was handled, zero if not (shared irq).
1548  */
1549 unsigned int ata_sff_host_intr(struct ata_port *ap,
1550                                       struct ata_queued_cmd *qc)
1551 {
1552         struct ata_eh_info *ehi = &ap->link.eh_info;
1553         u8 status, host_stat = 0;
1554         bool bmdma_stopped = false;
1555
1556         VPRINTK("ata%u: protocol %d task_state %d\n",
1557                 ap->print_id, qc->tf.protocol, ap->hsm_task_state);
1558
1559         /* Check whether we are expecting interrupt in this state */
1560         switch (ap->hsm_task_state) {
1561         case HSM_ST_FIRST:
1562                 /* Some pre-ATAPI-4 devices assert INTRQ
1563                  * at this state when ready to receive CDB.
1564                  */
1565
1566                 /* Check the ATA_DFLAG_CDB_INTR flag is enough here.
1567                  * The flag was turned on only for atapi devices.  No
1568                  * need to check ata_is_atapi(qc->tf.protocol) again.
1569                  */
1570                 if (!(qc->dev->flags & ATA_DFLAG_CDB_INTR))
1571                         goto idle_irq;
1572                 break;
1573         case HSM_ST_LAST:
1574                 if (qc->tf.protocol == ATA_PROT_DMA ||
1575                     qc->tf.protocol == ATAPI_PROT_DMA) {
1576                         /* check status of DMA engine */
1577                         host_stat = ap->ops->bmdma_status(ap);
1578                         VPRINTK("ata%u: host_stat 0x%X\n",
1579                                 ap->print_id, host_stat);
1580
1581                         /* if it's not our irq... */
1582                         if (!(host_stat & ATA_DMA_INTR))
1583                                 goto idle_irq;
1584
1585                         /* before we do anything else, clear DMA-Start bit */
1586                         ap->ops->bmdma_stop(qc);
1587                         bmdma_stopped = true;
1588
1589                         if (unlikely(host_stat & ATA_DMA_ERR)) {
1590                                 /* error when transfering data to/from memory */
1591                                 qc->err_mask |= AC_ERR_HOST_BUS;
1592                                 ap->hsm_task_state = HSM_ST_ERR;
1593                         }
1594                 }
1595                 break;
1596         case HSM_ST:
1597                 break;
1598         default:
1599                 goto idle_irq;
1600         }
1601
1602
1603         /* check main status, clearing INTRQ if needed */
1604         status = ata_sff_irq_status(ap);
1605         if (status & ATA_BUSY) {
1606                 if (bmdma_stopped) {
1607                         /* BMDMA engine is already stopped, we're screwed */
1608                         qc->err_mask |= AC_ERR_HSM;
1609                         ap->hsm_task_state = HSM_ST_ERR;
1610                 } else
1611                         goto idle_irq;
1612         }
1613
1614         /* clear irq events */
1615         ap->ops->sff_irq_clear(ap);
1616
1617         ata_sff_hsm_move(ap, qc, status, 0);
1618
1619         if (unlikely(qc->err_mask) && (qc->tf.protocol == ATA_PROT_DMA ||
1620                                        qc->tf.protocol == ATAPI_PROT_DMA))
1621                 ata_ehi_push_desc(ehi, "BMDMA stat 0x%x", host_stat);
1622
1623         return 1;       /* irq handled */
1624
1625 idle_irq:
1626         ap->stats.idle_irq++;
1627
1628 #ifdef ATA_IRQ_TRAP
1629         if ((ap->stats.idle_irq % 1000) == 0) {
1630                 ap->ops->sff_check_status(ap);
1631                 ap->ops->sff_irq_clear(ap);
1632                 ata_port_printk(ap, KERN_WARNING, "irq trap\n");
1633                 return 1;
1634         }
1635 #endif
1636         return 0;       /* irq not handled */
1637 }
1638 EXPORT_SYMBOL_GPL(ata_sff_host_intr);
1639
1640 /**
1641  *      ata_sff_interrupt - Default ATA host interrupt handler
1642  *      @irq: irq line (unused)
1643  *      @dev_instance: pointer to our ata_host information structure
1644  *
1645  *      Default interrupt handler for PCI IDE devices.  Calls
1646  *      ata_sff_host_intr() for each port that is not disabled.
1647  *
1648  *      LOCKING:
1649  *      Obtains host lock during operation.
1650  *
1651  *      RETURNS:
1652  *      IRQ_NONE or IRQ_HANDLED.
1653  */
1654 irqreturn_t ata_sff_interrupt(int irq, void *dev_instance)
1655 {
1656         struct ata_host *host = dev_instance;
1657         bool retried = false;
1658         unsigned int i;
1659         unsigned int handled, idle, polling;
1660         unsigned long flags;
1661
1662         /* TODO: make _irqsave conditional on x86 PCI IDE legacy mode */
1663         spin_lock_irqsave(&host->lock, flags);
1664
1665 retry:
1666         handled = idle = polling = 0;
1667         for (i = 0; i < host->n_ports; i++) {
1668                 struct ata_port *ap = host->ports[i];
1669                 struct ata_queued_cmd *qc;
1670
1671                 qc = ata_qc_from_tag(ap, ap->link.active_tag);
1672                 if (qc) {
1673                         if (!(qc->tf.flags & ATA_TFLAG_POLLING))
1674                                 handled |= ata_sff_host_intr(ap, qc);
1675                         else
1676                                 polling |= 1 << i;
1677                 } else
1678                         idle |= 1 << i;
1679         }
1680
1681         /*
1682          * If no port was expecting IRQ but the controller is actually
1683          * asserting IRQ line, nobody cared will ensue.  Check IRQ
1684          * pending status if available and clear spurious IRQ.
1685          */
1686         if (!handled && !retried) {
1687                 bool retry = false;
1688
1689                 for (i = 0; i < host->n_ports; i++) {
1690                         struct ata_port *ap = host->ports[i];
1691
1692                         if (polling & (1 << i))
1693                                 continue;
1694
1695                         if (!ap->ops->sff_irq_check ||
1696                             !ap->ops->sff_irq_check(ap))
1697                                 continue;
1698
1699                         if (idle & (1 << i)) {
1700                                 ap->ops->sff_check_status(ap);
1701                                 ap->ops->sff_irq_clear(ap);
1702                         } else {
1703                                 /* clear INTRQ and check if BUSY cleared */
1704                                 if (!(ap->ops->sff_check_status(ap) & ATA_BUSY))
1705                                         retry |= true;
1706                                 /*
1707                                  * With command in flight, we can't do
1708                                  * sff_irq_clear() w/o racing with completion.
1709                                  */
1710                         }
1711                 }
1712
1713                 if (retry) {
1714                         retried = true;
1715                         goto retry;
1716                 }
1717         }
1718
1719         spin_unlock_irqrestore(&host->lock, flags);
1720
1721         return IRQ_RETVAL(handled);
1722 }
1723 EXPORT_SYMBOL_GPL(ata_sff_interrupt);
1724
1725 /**
1726  *      ata_sff_lost_interrupt  -       Check for an apparent lost interrupt
1727  *      @ap: port that appears to have timed out
1728  *
1729  *      Called from the libata error handlers when the core code suspects
1730  *      an interrupt has been lost. If it has complete anything we can and
1731  *      then return. Interface must support altstatus for this faster
1732  *      recovery to occur.
1733  *
1734  *      Locking:
1735  *      Caller holds host lock
1736  */
1737
1738 void ata_sff_lost_interrupt(struct ata_port *ap)
1739 {
1740         u8 status;
1741         struct ata_queued_cmd *qc;
1742
1743         /* Only one outstanding command per SFF channel */
1744         qc = ata_qc_from_tag(ap, ap->link.active_tag);
1745         /* We cannot lose an interrupt on a non-existent or polled command */
1746         if (!qc || qc->tf.flags & ATA_TFLAG_POLLING)
1747                 return;
1748         /* See if the controller thinks it is still busy - if so the command
1749            isn't a lost IRQ but is still in progress */
1750         status = ata_sff_altstatus(ap);
1751         if (status & ATA_BUSY)
1752                 return;
1753
1754         /* There was a command running, we are no longer busy and we have
1755            no interrupt. */
1756         ata_port_printk(ap, KERN_WARNING, "lost interrupt (Status 0x%x)\n",
1757                                                                 status);
1758         /* Run the host interrupt logic as if the interrupt had not been
1759            lost */
1760         ata_sff_host_intr(ap, qc);
1761 }
1762 EXPORT_SYMBOL_GPL(ata_sff_lost_interrupt);
1763
1764 /**
1765  *      ata_sff_freeze - Freeze SFF controller port
1766  *      @ap: port to freeze
1767  *
1768  *      Freeze SFF controller port.
1769  *
1770  *      LOCKING:
1771  *      Inherited from caller.
1772  */
1773 void ata_sff_freeze(struct ata_port *ap)
1774 {
1775         ap->ctl |= ATA_NIEN;
1776         ap->last_ctl = ap->ctl;
1777
1778         if (ap->ops->sff_set_devctl || ap->ioaddr.ctl_addr)
1779                 ata_sff_set_devctl(ap, ap->ctl);
1780
1781         /* Under certain circumstances, some controllers raise IRQ on
1782          * ATA_NIEN manipulation.  Also, many controllers fail to mask
1783          * previously pending IRQ on ATA_NIEN assertion.  Clear it.
1784          */
1785         ap->ops->sff_check_status(ap);
1786
1787         ap->ops->sff_irq_clear(ap);
1788 }
1789 EXPORT_SYMBOL_GPL(ata_sff_freeze);
1790
1791 /**
1792  *      ata_sff_thaw - Thaw SFF controller port
1793  *      @ap: port to thaw
1794  *
1795  *      Thaw SFF controller port.
1796  *
1797  *      LOCKING:
1798  *      Inherited from caller.
1799  */
1800 void ata_sff_thaw(struct ata_port *ap)
1801 {
1802         /* clear & re-enable interrupts */
1803         ap->ops->sff_check_status(ap);
1804         ap->ops->sff_irq_clear(ap);
1805         ata_sff_irq_on(ap);
1806 }
1807 EXPORT_SYMBOL_GPL(ata_sff_thaw);
1808
1809 /**
1810  *      ata_sff_prereset - prepare SFF link for reset
1811  *      @link: SFF link to be reset
1812  *      @deadline: deadline jiffies for the operation
1813  *
1814  *      SFF link @link is about to be reset.  Initialize it.  It first
1815  *      calls ata_std_prereset() and wait for !BSY if the port is
1816  *      being softreset.
1817  *
1818  *      LOCKING:
1819  *      Kernel thread context (may sleep)
1820  *
1821  *      RETURNS:
1822  *      0 on success, -errno otherwise.
1823  */
1824 int ata_sff_prereset(struct ata_link *link, unsigned long deadline)
1825 {
1826         struct ata_eh_context *ehc = &link->eh_context;
1827         int rc;
1828
1829         rc = ata_std_prereset(link, deadline);
1830         if (rc)
1831                 return rc;
1832
1833         /* if we're about to do hardreset, nothing more to do */
1834         if (ehc->i.action & ATA_EH_HARDRESET)
1835                 return 0;
1836
1837         /* wait for !BSY if we don't know that no device is attached */
1838         if (!ata_link_offline(link)) {
1839                 rc = ata_sff_wait_ready(link, deadline);
1840                 if (rc && rc != -ENODEV) {
1841                         ata_link_printk(link, KERN_WARNING, "device not ready "
1842                                         "(errno=%d), forcing hardreset\n", rc);
1843                         ehc->i.action |= ATA_EH_HARDRESET;
1844                 }
1845         }
1846
1847         return 0;
1848 }
1849 EXPORT_SYMBOL_GPL(ata_sff_prereset);
1850
1851 /**
1852  *      ata_devchk - PATA device presence detection
1853  *      @ap: ATA channel to examine
1854  *      @device: Device to examine (starting at zero)
1855  *
1856  *      This technique was originally described in
1857  *      Hale Landis's ATADRVR (www.ata-atapi.com), and
1858  *      later found its way into the ATA/ATAPI spec.
1859  *
1860  *      Write a pattern to the ATA shadow registers,
1861  *      and if a device is present, it will respond by
1862  *      correctly storing and echoing back the
1863  *      ATA shadow register contents.
1864  *
1865  *      LOCKING:
1866  *      caller.
1867  */
1868 static unsigned int ata_devchk(struct ata_port *ap, unsigned int device)
1869 {
1870         struct ata_ioports *ioaddr = &ap->ioaddr;
1871         u8 nsect, lbal;
1872
1873         ap->ops->sff_dev_select(ap, device);
1874
1875         iowrite8(0x55, ioaddr->nsect_addr);
1876         iowrite8(0xaa, ioaddr->lbal_addr);
1877
1878         iowrite8(0xaa, ioaddr->nsect_addr);
1879         iowrite8(0x55, ioaddr->lbal_addr);
1880
1881         iowrite8(0x55, ioaddr->nsect_addr);
1882         iowrite8(0xaa, ioaddr->lbal_addr);
1883
1884         nsect = ioread8(ioaddr->nsect_addr);
1885         lbal = ioread8(ioaddr->lbal_addr);
1886
1887         if ((nsect == 0x55) && (lbal == 0xaa))
1888                 return 1;       /* we found a device */
1889
1890         return 0;               /* nothing found */
1891 }
1892
1893 /**
1894  *      ata_sff_dev_classify - Parse returned ATA device signature
1895  *      @dev: ATA device to classify (starting at zero)
1896  *      @present: device seems present
1897  *      @r_err: Value of error register on completion
1898  *
1899  *      After an event -- SRST, E.D.D., or SATA COMRESET -- occurs,
1900  *      an ATA/ATAPI-defined set of values is placed in the ATA
1901  *      shadow registers, indicating the results of device detection
1902  *      and diagnostics.
1903  *
1904  *      Select the ATA device, and read the values from the ATA shadow
1905  *      registers.  Then parse according to the Error register value,
1906  *      and the spec-defined values examined by ata_dev_classify().
1907  *
1908  *      LOCKING:
1909  *      caller.
1910  *
1911  *      RETURNS:
1912  *      Device type - %ATA_DEV_ATA, %ATA_DEV_ATAPI or %ATA_DEV_NONE.
1913  */
1914 unsigned int ata_sff_dev_classify(struct ata_device *dev, int present,
1915                                   u8 *r_err)
1916 {
1917         struct ata_port *ap = dev->link->ap;
1918         struct ata_taskfile tf;
1919         unsigned int class;
1920         u8 err;
1921
1922         ap->ops->sff_dev_select(ap, dev->devno);
1923
1924         memset(&tf, 0, sizeof(tf));
1925
1926         ap->ops->sff_tf_read(ap, &tf);
1927         err = tf.feature;
1928         if (r_err)
1929                 *r_err = err;
1930
1931         /* see if device passed diags: continue and warn later */
1932         if (err == 0)
1933                 /* diagnostic fail : do nothing _YET_ */
1934                 dev->horkage |= ATA_HORKAGE_DIAGNOSTIC;
1935         else if (err == 1)
1936                 /* do nothing */ ;
1937         else if ((dev->devno == 0) && (err == 0x81))
1938                 /* do nothing */ ;
1939         else
1940                 return ATA_DEV_NONE;
1941
1942         /* determine if device is ATA or ATAPI */
1943         class = ata_dev_classify(&tf);
1944
1945         if (class == ATA_DEV_UNKNOWN) {
1946                 /* If the device failed diagnostic, it's likely to
1947                  * have reported incorrect device signature too.
1948                  * Assume ATA device if the device seems present but
1949                  * device signature is invalid with diagnostic
1950                  * failure.
1951                  */
1952                 if (present && (dev->horkage & ATA_HORKAGE_DIAGNOSTIC))
1953                         class = ATA_DEV_ATA;
1954                 else
1955                         class = ATA_DEV_NONE;
1956         } else if ((class == ATA_DEV_ATA) &&
1957                    (ap->ops->sff_check_status(ap) == 0))
1958                 class = ATA_DEV_NONE;
1959
1960         return class;
1961 }
1962 EXPORT_SYMBOL_GPL(ata_sff_dev_classify);
1963
1964 /**
1965  *      ata_sff_wait_after_reset - wait for devices to become ready after reset
1966  *      @link: SFF link which is just reset
1967  *      @devmask: mask of present devices
1968  *      @deadline: deadline jiffies for the operation
1969  *
1970  *      Wait devices attached to SFF @link to become ready after
1971  *      reset.  It contains preceding 150ms wait to avoid accessing TF
1972  *      status register too early.
1973  *
1974  *      LOCKING:
1975  *      Kernel thread context (may sleep).
1976  *
1977  *      RETURNS:
1978  *      0 on success, -ENODEV if some or all of devices in @devmask
1979  *      don't seem to exist.  -errno on other errors.
1980  */
1981 int ata_sff_wait_after_reset(struct ata_link *link, unsigned int devmask,
1982                              unsigned long deadline)
1983 {
1984         struct ata_port *ap = link->ap;
1985         struct ata_ioports *ioaddr = &ap->ioaddr;
1986         unsigned int dev0 = devmask & (1 << 0);
1987         unsigned int dev1 = devmask & (1 << 1);
1988         int rc, ret = 0;
1989
1990         msleep(ATA_WAIT_AFTER_RESET);
1991
1992         /* always check readiness of the master device */
1993         rc = ata_sff_wait_ready(link, deadline);
1994         /* -ENODEV means the odd clown forgot the D7 pulldown resistor
1995          * and TF status is 0xff, bail out on it too.
1996          */
1997         if (rc)
1998                 return rc;
1999
2000         /* if device 1 was found in ata_devchk, wait for register
2001          * access briefly, then wait for BSY to clear.
2002          */
2003         if (dev1) {
2004                 int i;
2005
2006                 ap->ops->sff_dev_select(ap, 1);
2007
2008                 /* Wait for register access.  Some ATAPI devices fail
2009                  * to set nsect/lbal after reset, so don't waste too
2010                  * much time on it.  We're gonna wait for !BSY anyway.
2011                  */
2012                 for (i = 0; i < 2; i++) {
2013                         u8 nsect, lbal;
2014
2015                         nsect = ioread8(ioaddr->nsect_addr);
2016                         lbal = ioread8(ioaddr->lbal_addr);
2017                         if ((nsect == 1) && (lbal == 1))
2018                                 break;
2019                         msleep(50);     /* give drive a breather */
2020                 }
2021
2022                 rc = ata_sff_wait_ready(link, deadline);
2023                 if (rc) {
2024                         if (rc != -ENODEV)
2025                                 return rc;
2026                         ret = rc;
2027                 }
2028         }
2029
2030         /* is all this really necessary? */
2031         ap->ops->sff_dev_select(ap, 0);
2032         if (dev1)
2033                 ap->ops->sff_dev_select(ap, 1);
2034         if (dev0)
2035                 ap->ops->sff_dev_select(ap, 0);
2036
2037         return ret;
2038 }
2039 EXPORT_SYMBOL_GPL(ata_sff_wait_after_reset);
2040
2041 static int ata_bus_softreset(struct ata_port *ap, unsigned int devmask,
2042                              unsigned long deadline)
2043 {
2044         struct ata_ioports *ioaddr = &ap->ioaddr;
2045
2046         DPRINTK("ata%u: bus reset via SRST\n", ap->print_id);
2047
2048         /* software reset.  causes dev0 to be selected */
2049         iowrite8(ap->ctl, ioaddr->ctl_addr);
2050         udelay(20);     /* FIXME: flush */
2051         iowrite8(ap->ctl | ATA_SRST, ioaddr->ctl_addr);
2052         udelay(20);     /* FIXME: flush */
2053         iowrite8(ap->ctl, ioaddr->ctl_addr);
2054         ap->last_ctl = ap->ctl;
2055
2056         /* wait the port to become ready */
2057         return ata_sff_wait_after_reset(&ap->link, devmask, deadline);
2058 }
2059
2060 /**
2061  *      ata_sff_softreset - reset host port via ATA SRST
2062  *      @link: ATA link to reset
2063  *      @classes: resulting classes of attached devices
2064  *      @deadline: deadline jiffies for the operation
2065  *
2066  *      Reset host port using ATA SRST.
2067  *
2068  *      LOCKING:
2069  *      Kernel thread context (may sleep)
2070  *
2071  *      RETURNS:
2072  *      0 on success, -errno otherwise.
2073  */
2074 int ata_sff_softreset(struct ata_link *link, unsigned int *classes,
2075                       unsigned long deadline)
2076 {
2077         struct ata_port *ap = link->ap;
2078         unsigned int slave_possible = ap->flags & ATA_FLAG_SLAVE_POSS;
2079         unsigned int devmask = 0;
2080         int rc;
2081         u8 err;
2082
2083         DPRINTK("ENTER\n");
2084
2085         /* determine if device 0/1 are present */
2086         if (ata_devchk(ap, 0))
2087                 devmask |= (1 << 0);
2088         if (slave_possible && ata_devchk(ap, 1))
2089                 devmask |= (1 << 1);
2090
2091         /* select device 0 again */
2092         ap->ops->sff_dev_select(ap, 0);
2093
2094         /* issue bus reset */
2095         DPRINTK("about to softreset, devmask=%x\n", devmask);
2096         rc = ata_bus_softreset(ap, devmask, deadline);
2097         /* if link is occupied, -ENODEV too is an error */
2098         if (rc && (rc != -ENODEV || sata_scr_valid(link))) {
2099                 ata_link_printk(link, KERN_ERR, "SRST failed (errno=%d)\n", rc);
2100                 return rc;
2101         }
2102
2103         /* determine by signature whether we have ATA or ATAPI devices */
2104         classes[0] = ata_sff_dev_classify(&link->device[0],
2105                                           devmask & (1 << 0), &err);
2106         if (slave_possible && err != 0x81)
2107                 classes[1] = ata_sff_dev_classify(&link->device[1],
2108                                                   devmask & (1 << 1), &err);
2109
2110         DPRINTK("EXIT, classes[0]=%u [1]=%u\n", classes[0], classes[1]);
2111         return 0;
2112 }
2113 EXPORT_SYMBOL_GPL(ata_sff_softreset);
2114
2115 /**
2116  *      sata_sff_hardreset - reset host port via SATA phy reset
2117  *      @link: link to reset
2118  *      @class: resulting class of attached device
2119  *      @deadline: deadline jiffies for the operation
2120  *
2121  *      SATA phy-reset host port using DET bits of SControl register,
2122  *      wait for !BSY and classify the attached device.
2123  *
2124  *      LOCKING:
2125  *      Kernel thread context (may sleep)
2126  *
2127  *      RETURNS:
2128  *      0 on success, -errno otherwise.
2129  */
2130 int sata_sff_hardreset(struct ata_link *link, unsigned int *class,
2131                        unsigned long deadline)
2132 {
2133         struct ata_eh_context *ehc = &link->eh_context;
2134         const unsigned long *timing = sata_ehc_deb_timing(ehc);
2135         bool online;
2136         int rc;
2137
2138         rc = sata_link_hardreset(link, timing, deadline, &online,
2139                                  ata_sff_check_ready);
2140         if (online)
2141                 *class = ata_sff_dev_classify(link->device, 1, NULL);
2142
2143         DPRINTK("EXIT, class=%u\n", *class);
2144         return rc;
2145 }
2146 EXPORT_SYMBOL_GPL(sata_sff_hardreset);
2147
2148 /**
2149  *      ata_sff_postreset - SFF postreset callback
2150  *      @link: the target SFF ata_link
2151  *      @classes: classes of attached devices
2152  *
2153  *      This function is invoked after a successful reset.  It first
2154  *      calls ata_std_postreset() and performs SFF specific postreset
2155  *      processing.
2156  *
2157  *      LOCKING:
2158  *      Kernel thread context (may sleep)
2159  */
2160 void ata_sff_postreset(struct ata_link *link, unsigned int *classes)
2161 {
2162         struct ata_port *ap = link->ap;
2163
2164         ata_std_postreset(link, classes);
2165
2166         /* is double-select really necessary? */
2167         if (classes[0] != ATA_DEV_NONE)
2168                 ap->ops->sff_dev_select(ap, 1);
2169         if (classes[1] != ATA_DEV_NONE)
2170                 ap->ops->sff_dev_select(ap, 0);
2171
2172         /* bail out if no device is present */
2173         if (classes[0] == ATA_DEV_NONE && classes[1] == ATA_DEV_NONE) {
2174                 DPRINTK("EXIT, no device\n");
2175                 return;
2176         }
2177
2178         /* set up device control */
2179         if (ap->ops->sff_set_devctl || ap->ioaddr.ctl_addr) {
2180                 ata_sff_set_devctl(ap, ap->ctl);
2181                 ap->last_ctl = ap->ctl;
2182         }
2183 }
2184 EXPORT_SYMBOL_GPL(ata_sff_postreset);
2185
2186 /**
2187  *      ata_sff_drain_fifo - Stock FIFO drain logic for SFF controllers
2188  *      @qc: command
2189  *
2190  *      Drain the FIFO and device of any stuck data following a command
2191  *      failing to complete. In some cases this is necessary before a
2192  *      reset will recover the device.
2193  *
2194  */
2195
2196 void ata_sff_drain_fifo(struct ata_queued_cmd *qc)
2197 {
2198         int count;
2199         struct ata_port *ap;
2200
2201         /* We only need to flush incoming data when a command was running */
2202         if (qc == NULL || qc->dma_dir == DMA_TO_DEVICE)
2203                 return;
2204
2205         ap = qc->ap;
2206         /* Drain up to 64K of data before we give up this recovery method */
2207         for (count = 0; (ap->ops->sff_check_status(ap) & ATA_DRQ)
2208                                                 && count < 65536; count += 2)
2209                 ioread16(ap->ioaddr.data_addr);
2210
2211         /* Can become DEBUG later */
2212         if (count)
2213                 ata_port_printk(ap, KERN_DEBUG,
2214                         "drained %d bytes to clear DRQ.\n", count);
2215
2216 }
2217 EXPORT_SYMBOL_GPL(ata_sff_drain_fifo);
2218
2219 /**
2220  *      ata_sff_error_handler - Stock error handler for SFF controller
2221  *      @ap: port to handle error for
2222  *
2223  *      Stock error handler for SFF controller.  It can handle both
2224  *      PATA and SATA controllers.  Many controllers should be able to
2225  *      use this EH as-is or with some added handling before and
2226  *      after.
2227  *
2228  *      LOCKING:
2229  *      Kernel thread context (may sleep)
2230  */
2231 void ata_sff_error_handler(struct ata_port *ap)
2232 {
2233         ata_reset_fn_t softreset = ap->ops->softreset;
2234         ata_reset_fn_t hardreset = ap->ops->hardreset;
2235         struct ata_queued_cmd *qc;
2236         unsigned long flags;
2237
2238         qc = __ata_qc_from_tag(ap, ap->link.active_tag);
2239         if (qc && !(qc->flags & ATA_QCFLAG_FAILED))
2240                 qc = NULL;
2241
2242         spin_lock_irqsave(ap->lock, flags);
2243
2244         /*
2245          * We *MUST* do FIFO draining before we issue a reset as
2246          * several devices helpfully clear their internal state and
2247          * will lock solid if we touch the data port post reset. Pass
2248          * qc in case anyone wants to do different PIO/DMA recovery or
2249          * has per command fixups
2250          */
2251         if (ap->ops->sff_drain_fifo)
2252                 ap->ops->sff_drain_fifo(qc);
2253
2254         spin_unlock_irqrestore(ap->lock, flags);
2255
2256         /* ignore ata_sff_softreset if ctl isn't accessible */
2257         if (softreset == ata_sff_softreset && !ap->ioaddr.ctl_addr)
2258                 softreset = NULL;
2259
2260         /* ignore built-in hardresets if SCR access is not available */
2261         if ((hardreset == sata_std_hardreset ||
2262              hardreset == sata_sff_hardreset) && !sata_scr_valid(&ap->link))
2263                 hardreset = NULL;
2264
2265         ata_do_eh(ap, ap->ops->prereset, softreset, hardreset,
2266                   ap->ops->postreset);
2267 }
2268 EXPORT_SYMBOL_GPL(ata_sff_error_handler);
2269
2270 /**
2271  *      ata_sff_std_ports - initialize ioaddr with standard port offsets.
2272  *      @ioaddr: IO address structure to be initialized
2273  *
2274  *      Utility function which initializes data_addr, error_addr,
2275  *      feature_addr, nsect_addr, lbal_addr, lbam_addr, lbah_addr,
2276  *      device_addr, status_addr, and command_addr to standard offsets
2277  *      relative to cmd_addr.
2278  *
2279  *      Does not set ctl_addr, altstatus_addr, bmdma_addr, or scr_addr.
2280  */
2281 void ata_sff_std_ports(struct ata_ioports *ioaddr)
2282 {
2283         ioaddr->data_addr = ioaddr->cmd_addr + ATA_REG_DATA;
2284         ioaddr->error_addr = ioaddr->cmd_addr + ATA_REG_ERR;
2285         ioaddr->feature_addr = ioaddr->cmd_addr + ATA_REG_FEATURE;
2286         ioaddr->nsect_addr = ioaddr->cmd_addr + ATA_REG_NSECT;
2287         ioaddr->lbal_addr = ioaddr->cmd_addr + ATA_REG_LBAL;
2288         ioaddr->lbam_addr = ioaddr->cmd_addr + ATA_REG_LBAM;
2289         ioaddr->lbah_addr = ioaddr->cmd_addr + ATA_REG_LBAH;
2290         ioaddr->device_addr = ioaddr->cmd_addr + ATA_REG_DEVICE;
2291         ioaddr->status_addr = ioaddr->cmd_addr + ATA_REG_STATUS;
2292         ioaddr->command_addr = ioaddr->cmd_addr + ATA_REG_CMD;
2293 }
2294 EXPORT_SYMBOL_GPL(ata_sff_std_ports);
2295
2296 #ifdef CONFIG_PCI
2297
2298 static int ata_resources_present(struct pci_dev *pdev, int port)
2299 {
2300         int i;
2301
2302         /* Check the PCI resources for this channel are enabled */
2303         port = port * 2;
2304         for (i = 0; i < 2; i++) {
2305                 if (pci_resource_start(pdev, port + i) == 0 ||
2306                     pci_resource_len(pdev, port + i) == 0)
2307                         return 0;
2308         }
2309         return 1;
2310 }
2311
2312 /**
2313  *      ata_pci_sff_init_host - acquire native PCI ATA resources and init host
2314  *      @host: target ATA host
2315  *
2316  *      Acquire native PCI ATA resources for @host and initialize the
2317  *      first two ports of @host accordingly.  Ports marked dummy are
2318  *      skipped and allocation failure makes the port dummy.
2319  *
2320  *      Note that native PCI resources are valid even for legacy hosts
2321  *      as we fix up pdev resources array early in boot, so this
2322  *      function can be used for both native and legacy SFF hosts.
2323  *
2324  *      LOCKING:
2325  *      Inherited from calling layer (may sleep).
2326  *
2327  *      RETURNS:
2328  *      0 if at least one port is initialized, -ENODEV if no port is
2329  *      available.
2330  */
2331 int ata_pci_sff_init_host(struct ata_host *host)
2332 {
2333         struct device *gdev = host->dev;
2334         struct pci_dev *pdev = to_pci_dev(gdev);
2335         unsigned int mask = 0;
2336         int i, rc;
2337
2338         /* request, iomap BARs and init port addresses accordingly */
2339         for (i = 0; i < 2; i++) {
2340                 struct ata_port *ap = host->ports[i];
2341                 int base = i * 2;
2342                 void __iomem * const *iomap;
2343
2344                 if (ata_port_is_dummy(ap))
2345                         continue;
2346
2347                 /* Discard disabled ports.  Some controllers show
2348                  * their unused channels this way.  Disabled ports are
2349                  * made dummy.
2350                  */
2351                 if (!ata_resources_present(pdev, i)) {
2352                         ap->ops = &ata_dummy_port_ops;
2353                         continue;
2354                 }
2355
2356                 rc = pcim_iomap_regions(pdev, 0x3 << base,
2357                                         dev_driver_string(gdev));
2358                 if (rc) {
2359                         dev_printk(KERN_WARNING, gdev,
2360                                    "failed to request/iomap BARs for port %d "
2361                                    "(errno=%d)\n", i, rc);
2362                         if (rc == -EBUSY)
2363                                 pcim_pin_device(pdev);
2364                         ap->ops = &ata_dummy_port_ops;
2365                         continue;
2366                 }
2367                 host->iomap = iomap = pcim_iomap_table(pdev);
2368
2369                 ap->ioaddr.cmd_addr = iomap[base];
2370                 ap->ioaddr.altstatus_addr =
2371                 ap->ioaddr.ctl_addr = (void __iomem *)
2372                         ((unsigned long)iomap[base + 1] | ATA_PCI_CTL_OFS);
2373                 ata_sff_std_ports(&ap->ioaddr);
2374
2375                 ata_port_desc(ap, "cmd 0x%llx ctl 0x%llx",
2376                         (unsigned long long)pci_resource_start(pdev, base),
2377                         (unsigned long long)pci_resource_start(pdev, base + 1));
2378
2379                 mask |= 1 << i;
2380         }
2381
2382         if (!mask) {
2383                 dev_printk(KERN_ERR, gdev, "no available native port\n");
2384                 return -ENODEV;
2385         }
2386
2387         return 0;
2388 }
2389 EXPORT_SYMBOL_GPL(ata_pci_sff_init_host);
2390
2391 /**
2392  *      ata_pci_sff_prepare_host - helper to prepare native PCI ATA host
2393  *      @pdev: target PCI device
2394  *      @ppi: array of port_info, must be enough for two ports
2395  *      @r_host: out argument for the initialized ATA host
2396  *
2397  *      Helper to allocate ATA host for @pdev, acquire all native PCI
2398  *      resources and initialize it accordingly in one go.
2399  *
2400  *      LOCKING:
2401  *      Inherited from calling layer (may sleep).
2402  *
2403  *      RETURNS:
2404  *      0 on success, -errno otherwise.
2405  */
2406 int ata_pci_sff_prepare_host(struct pci_dev *pdev,
2407                              const struct ata_port_info * const *ppi,
2408                              struct ata_host **r_host)
2409 {
2410         struct ata_host *host;
2411         int rc;
2412
2413         if (!devres_open_group(&pdev->dev, NULL, GFP_KERNEL))
2414                 return -ENOMEM;
2415
2416         host = ata_host_alloc_pinfo(&pdev->dev, ppi, 2);
2417         if (!host) {
2418                 dev_printk(KERN_ERR, &pdev->dev,
2419                            "failed to allocate ATA host\n");
2420                 rc = -ENOMEM;
2421                 goto err_out;
2422         }
2423
2424         rc = ata_pci_sff_init_host(host);
2425         if (rc)
2426                 goto err_out;
2427
2428         /* init DMA related stuff */
2429         ata_pci_bmdma_init(host);
2430
2431         devres_remove_group(&pdev->dev, NULL);
2432         *r_host = host;
2433         return 0;
2434
2435 err_out:
2436         devres_release_group(&pdev->dev, NULL);
2437         return rc;
2438 }
2439 EXPORT_SYMBOL_GPL(ata_pci_sff_prepare_host);
2440
2441 /**
2442  *      ata_pci_sff_activate_host - start SFF host, request IRQ and register it
2443  *      @host: target SFF ATA host
2444  *      @irq_handler: irq_handler used when requesting IRQ(s)
2445  *      @sht: scsi_host_template to use when registering the host
2446  *
2447  *      This is the counterpart of ata_host_activate() for SFF ATA
2448  *      hosts.  This separate helper is necessary because SFF hosts
2449  *      use two separate interrupts in legacy mode.
2450  *
2451  *      LOCKING:
2452  *      Inherited from calling layer (may sleep).
2453  *
2454  *      RETURNS:
2455  *      0 on success, -errno otherwise.
2456  */
2457 int ata_pci_sff_activate_host(struct ata_host *host,
2458                               irq_handler_t irq_handler,
2459                               struct scsi_host_template *sht)
2460 {
2461         struct device *dev = host->dev;
2462         struct pci_dev *pdev = to_pci_dev(dev);
2463         const char *drv_name = dev_driver_string(host->dev);
2464         int legacy_mode = 0, rc;
2465
2466         rc = ata_host_start(host);
2467         if (rc)
2468                 return rc;
2469
2470         if ((pdev->class >> 8) == PCI_CLASS_STORAGE_IDE) {
2471                 u8 tmp8, mask;
2472
2473                 /* TODO: What if one channel is in native mode ... */
2474                 pci_read_config_byte(pdev, PCI_CLASS_PROG, &tmp8);
2475                 mask = (1 << 2) | (1 << 0);
2476                 if ((tmp8 & mask) != mask)
2477                         legacy_mode = 1;
2478 #if defined(CONFIG_NO_ATA_LEGACY)
2479                 /* Some platforms with PCI limits cannot address compat
2480                    port space. In that case we punt if their firmware has
2481                    left a device in compatibility mode */
2482                 if (legacy_mode) {
2483                         printk(KERN_ERR "ata: Compatibility mode ATA is not supported on this platform, skipping.\n");
2484                         return -EOPNOTSUPP;
2485                 }
2486 #endif
2487         }
2488
2489         if (!devres_open_group(dev, NULL, GFP_KERNEL))
2490                 return -ENOMEM;
2491
2492         if (!legacy_mode && pdev->irq) {
2493                 rc = devm_request_irq(dev, pdev->irq, irq_handler,
2494                                       IRQF_SHARED, drv_name, host);
2495                 if (rc)
2496                         goto out;
2497
2498                 ata_port_desc(host->ports[0], "irq %d", pdev->irq);
2499                 ata_port_desc(host->ports[1], "irq %d", pdev->irq);
2500         } else if (legacy_mode) {
2501                 if (!ata_port_is_dummy(host->ports[0])) {
2502                         rc = devm_request_irq(dev, ATA_PRIMARY_IRQ(pdev),
2503                                               irq_handler, IRQF_SHARED,
2504                                               drv_name, host);
2505                         if (rc)
2506                                 goto out;
2507
2508                         ata_port_desc(host->ports[0], "irq %d",
2509                                       ATA_PRIMARY_IRQ(pdev));
2510                 }
2511
2512                 if (!ata_port_is_dummy(host->ports[1])) {
2513                         rc = devm_request_irq(dev, ATA_SECONDARY_IRQ(pdev),
2514                                               irq_handler, IRQF_SHARED,
2515                                               drv_name, host);
2516                         if (rc)
2517                                 goto out;
2518
2519                         ata_port_desc(host->ports[1], "irq %d",
2520                                       ATA_SECONDARY_IRQ(pdev));
2521                 }
2522         }
2523
2524         rc = ata_host_register(host, sht);
2525 out:
2526         if (rc == 0)
2527                 devres_remove_group(dev, NULL);
2528         else
2529                 devres_release_group(dev, NULL);
2530
2531         return rc;
2532 }
2533 EXPORT_SYMBOL_GPL(ata_pci_sff_activate_host);
2534
2535 /**
2536  *      ata_pci_sff_init_one - Initialize/register PCI IDE host controller
2537  *      @pdev: Controller to be initialized
2538  *      @ppi: array of port_info, must be enough for two ports
2539  *      @sht: scsi_host_template to use when registering the host
2540  *      @host_priv: host private_data
2541  *      @hflag: host flags
2542  *
2543  *      This is a helper function which can be called from a driver's
2544  *      xxx_init_one() probe function if the hardware uses traditional
2545  *      IDE taskfile registers.
2546  *
2547  *      This function calls pci_enable_device(), reserves its register
2548  *      regions, sets the dma mask, enables bus master mode, and calls
2549  *      ata_device_add()
2550  *
2551  *      ASSUMPTION:
2552  *      Nobody makes a single channel controller that appears solely as
2553  *      the secondary legacy port on PCI.
2554  *
2555  *      LOCKING:
2556  *      Inherited from PCI layer (may sleep).
2557  *
2558  *      RETURNS:
2559  *      Zero on success, negative on errno-based value on error.
2560  */
2561 int ata_pci_sff_init_one(struct pci_dev *pdev,
2562                  const struct ata_port_info * const *ppi,
2563                  struct scsi_host_template *sht, void *host_priv, int hflag)
2564 {
2565         struct device *dev = &pdev->dev;
2566         const struct ata_port_info *pi = NULL;
2567         struct ata_host *host = NULL;
2568         int i, rc;
2569
2570         DPRINTK("ENTER\n");
2571
2572         /* look up the first valid port_info */
2573         for (i = 0; i < 2 && ppi[i]; i++) {
2574                 if (ppi[i]->port_ops != &ata_dummy_port_ops) {
2575                         pi = ppi[i];
2576                         break;
2577                 }
2578         }
2579
2580         if (!pi) {
2581                 dev_printk(KERN_ERR, &pdev->dev,
2582                            "no valid port_info specified\n");
2583                 return -EINVAL;
2584         }
2585
2586         if (!devres_open_group(dev, NULL, GFP_KERNEL))
2587                 return -ENOMEM;
2588
2589         rc = pcim_enable_device(pdev);
2590         if (rc)
2591                 goto out;
2592
2593         /* prepare and activate SFF host */
2594         rc = ata_pci_sff_prepare_host(pdev, ppi, &host);
2595         if (rc)
2596                 goto out;
2597         host->private_data = host_priv;
2598         host->flags |= hflag;
2599
2600         pci_set_master(pdev);
2601         rc = ata_pci_sff_activate_host(host, ata_sff_interrupt, sht);
2602 out:
2603         if (rc == 0)
2604                 devres_remove_group(&pdev->dev, NULL);
2605         else
2606                 devres_release_group(&pdev->dev, NULL);
2607
2608         return rc;
2609 }
2610 EXPORT_SYMBOL_GPL(ata_pci_sff_init_one);
2611
2612 #endif /* CONFIG_PCI */
2613
2614 const struct ata_port_operations ata_bmdma_port_ops = {
2615         .inherits               = &ata_sff_port_ops,
2616
2617         .error_handler          = ata_bmdma_error_handler,
2618         .post_internal_cmd      = ata_bmdma_post_internal_cmd,
2619
2620         .qc_prep                = ata_bmdma_qc_prep,
2621
2622         .bmdma_setup            = ata_bmdma_setup,
2623         .bmdma_start            = ata_bmdma_start,
2624         .bmdma_stop             = ata_bmdma_stop,
2625         .bmdma_status           = ata_bmdma_status,
2626
2627         .port_start             = ata_bmdma_port_start,
2628 };
2629 EXPORT_SYMBOL_GPL(ata_bmdma_port_ops);
2630
2631 const struct ata_port_operations ata_bmdma32_port_ops = {
2632         .inherits               = &ata_bmdma_port_ops,
2633
2634         .sff_data_xfer          = ata_sff_data_xfer32,
2635         .port_start             = ata_bmdma_port_start32,
2636 };
2637 EXPORT_SYMBOL_GPL(ata_bmdma32_port_ops);
2638
2639 /**
2640  *      ata_bmdma_fill_sg - Fill PCI IDE PRD table
2641  *      @qc: Metadata associated with taskfile to be transferred
2642  *
2643  *      Fill PCI IDE PRD (scatter-gather) table with segments
2644  *      associated with the current disk command.
2645  *
2646  *      LOCKING:
2647  *      spin_lock_irqsave(host lock)
2648  *
2649  */
2650 static void ata_bmdma_fill_sg(struct ata_queued_cmd *qc)
2651 {
2652         struct ata_port *ap = qc->ap;
2653         struct ata_bmdma_prd *prd = ap->bmdma_prd;
2654         struct scatterlist *sg;
2655         unsigned int si, pi;
2656
2657         pi = 0;
2658         for_each_sg(qc->sg, sg, qc->n_elem, si) {
2659                 u32 addr, offset;
2660                 u32 sg_len, len;
2661
2662                 /* determine if physical DMA addr spans 64K boundary.
2663                  * Note h/w doesn't support 64-bit, so we unconditionally
2664                  * truncate dma_addr_t to u32.
2665                  */
2666                 addr = (u32) sg_dma_address(sg);
2667                 sg_len = sg_dma_len(sg);
2668
2669                 while (sg_len) {
2670                         offset = addr & 0xffff;
2671                         len = sg_len;
2672                         if ((offset + sg_len) > 0x10000)
2673                                 len = 0x10000 - offset;
2674
2675                         prd[pi].addr = cpu_to_le32(addr);
2676                         prd[pi].flags_len = cpu_to_le32(len & 0xffff);
2677                         VPRINTK("PRD[%u] = (0x%X, 0x%X)\n", pi, addr, len);
2678
2679                         pi++;
2680                         sg_len -= len;
2681                         addr += len;
2682                 }
2683         }
2684
2685         prd[pi - 1].flags_len |= cpu_to_le32(ATA_PRD_EOT);
2686 }
2687
2688 /**
2689  *      ata_bmdma_fill_sg_dumb - Fill PCI IDE PRD table
2690  *      @qc: Metadata associated with taskfile to be transferred
2691  *
2692  *      Fill PCI IDE PRD (scatter-gather) table with segments
2693  *      associated with the current disk command. Perform the fill
2694  *      so that we avoid writing any length 64K records for
2695  *      controllers that don't follow the spec.
2696  *
2697  *      LOCKING:
2698  *      spin_lock_irqsave(host lock)
2699  *
2700  */
2701 static void ata_bmdma_fill_sg_dumb(struct ata_queued_cmd *qc)
2702 {
2703         struct ata_port *ap = qc->ap;
2704         struct ata_bmdma_prd *prd = ap->bmdma_prd;
2705         struct scatterlist *sg;
2706         unsigned int si, pi;
2707
2708         pi = 0;
2709         for_each_sg(qc->sg, sg, qc->n_elem, si) {
2710                 u32 addr, offset;
2711                 u32 sg_len, len, blen;
2712
2713                 /* determine if physical DMA addr spans 64K boundary.
2714                  * Note h/w doesn't support 64-bit, so we unconditionally
2715                  * truncate dma_addr_t to u32.
2716                  */
2717                 addr = (u32) sg_dma_address(sg);
2718                 sg_len = sg_dma_len(sg);
2719
2720                 while (sg_len) {
2721                         offset = addr & 0xffff;
2722                         len = sg_len;
2723                         if ((offset + sg_len) > 0x10000)
2724                                 len = 0x10000 - offset;
2725
2726                         blen = len & 0xffff;
2727                         prd[pi].addr = cpu_to_le32(addr);
2728                         if (blen == 0) {
2729                                 /* Some PATA chipsets like the CS5530 can't
2730                                    cope with 0x0000 meaning 64K as the spec
2731                                    says */
2732                                 prd[pi].flags_len = cpu_to_le32(0x8000);
2733                                 blen = 0x8000;
2734                                 prd[++pi].addr = cpu_to_le32(addr + 0x8000);
2735                         }
2736                         prd[pi].flags_len = cpu_to_le32(blen);
2737                         VPRINTK("PRD[%u] = (0x%X, 0x%X)\n", pi, addr, len);
2738
2739                         pi++;
2740                         sg_len -= len;
2741                         addr += len;
2742                 }
2743         }
2744
2745         prd[pi - 1].flags_len |= cpu_to_le32(ATA_PRD_EOT);
2746 }
2747
2748 /**
2749  *      ata_bmdma_qc_prep - Prepare taskfile for submission
2750  *      @qc: Metadata associated with taskfile to be prepared
2751  *
2752  *      Prepare ATA taskfile for submission.
2753  *
2754  *      LOCKING:
2755  *      spin_lock_irqsave(host lock)
2756  */
2757 void ata_bmdma_qc_prep(struct ata_queued_cmd *qc)
2758 {
2759         if (!(qc->flags & ATA_QCFLAG_DMAMAP))
2760                 return;
2761
2762         ata_bmdma_fill_sg(qc);
2763 }
2764 EXPORT_SYMBOL_GPL(ata_bmdma_qc_prep);
2765
2766 /**
2767  *      ata_bmdma_dumb_qc_prep - Prepare taskfile for submission
2768  *      @qc: Metadata associated with taskfile to be prepared
2769  *
2770  *      Prepare ATA taskfile for submission.
2771  *
2772  *      LOCKING:
2773  *      spin_lock_irqsave(host lock)
2774  */
2775 void ata_bmdma_dumb_qc_prep(struct ata_queued_cmd *qc)
2776 {
2777         if (!(qc->flags & ATA_QCFLAG_DMAMAP))
2778                 return;
2779
2780         ata_bmdma_fill_sg_dumb(qc);
2781 }
2782 EXPORT_SYMBOL_GPL(ata_bmdma_dumb_qc_prep);
2783
2784 /**
2785  *      ata_bmdma_error_handler - Stock error handler for BMDMA controller
2786  *      @ap: port to handle error for
2787  *
2788  *      Stock error handler for BMDMA controller.  It can handle both
2789  *      PATA and SATA controllers.  Most BMDMA controllers should be
2790  *      able to use this EH as-is or with some added handling before
2791  *      and after.
2792  *
2793  *      LOCKING:
2794  *      Kernel thread context (may sleep)
2795  */
2796 void ata_bmdma_error_handler(struct ata_port *ap)
2797 {
2798         struct ata_queued_cmd *qc;
2799         unsigned long flags;
2800         bool thaw = false;
2801
2802         qc = __ata_qc_from_tag(ap, ap->link.active_tag);
2803         if (qc && !(qc->flags & ATA_QCFLAG_FAILED))
2804                 qc = NULL;
2805
2806         /* reset PIO HSM and stop DMA engine */
2807         spin_lock_irqsave(ap->lock, flags);
2808
2809         if (qc && ata_is_dma(qc->tf.protocol)) {
2810                 u8 host_stat;
2811
2812                 host_stat = ap->ops->bmdma_status(ap);
2813
2814                 /* BMDMA controllers indicate host bus error by
2815                  * setting DMA_ERR bit and timing out.  As it wasn't
2816                  * really a timeout event, adjust error mask and
2817                  * cancel frozen state.
2818                  */
2819                 if (qc->err_mask == AC_ERR_TIMEOUT && (host_stat & ATA_DMA_ERR)) {
2820                         qc->err_mask = AC_ERR_HOST_BUS;
2821                         thaw = true;
2822                 }
2823
2824                 ap->ops->bmdma_stop(qc);
2825
2826                 /* if we're gonna thaw, make sure IRQ is clear */
2827                 if (thaw) {
2828                         ap->ops->sff_check_status(ap);
2829                         ap->ops->sff_irq_clear(ap);
2830                 }
2831         }
2832
2833         spin_unlock_irqrestore(ap->lock, flags);
2834
2835         if (thaw)
2836                 ata_eh_thaw_port(ap);
2837
2838         ata_sff_error_handler(ap);
2839 }
2840 EXPORT_SYMBOL_GPL(ata_bmdma_error_handler);
2841
2842 /**
2843  *      ata_bmdma_post_internal_cmd - Stock post_internal_cmd for BMDMA
2844  *      @qc: internal command to clean up
2845  *
2846  *      LOCKING:
2847  *      Kernel thread context (may sleep)
2848  */
2849 void ata_bmdma_post_internal_cmd(struct ata_queued_cmd *qc)
2850 {
2851         struct ata_port *ap = qc->ap;
2852         unsigned long flags;
2853
2854         if (ata_is_dma(qc->tf.protocol)) {
2855                 spin_lock_irqsave(ap->lock, flags);
2856                 ap->ops->bmdma_stop(qc);
2857                 spin_unlock_irqrestore(ap->lock, flags);
2858         }
2859 }
2860 EXPORT_SYMBOL_GPL(ata_bmdma_post_internal_cmd);
2861
2862 /**
2863  *      ata_bmdma_setup - Set up PCI IDE BMDMA transaction
2864  *      @qc: Info associated with this ATA transaction.
2865  *
2866  *      LOCKING:
2867  *      spin_lock_irqsave(host lock)
2868  */
2869 void ata_bmdma_setup(struct ata_queued_cmd *qc)
2870 {
2871         struct ata_port *ap = qc->ap;
2872         unsigned int rw = (qc->tf.flags & ATA_TFLAG_WRITE);
2873         u8 dmactl;
2874
2875         /* load PRD table addr. */
2876         mb();   /* make sure PRD table writes are visible to controller */
2877         iowrite32(ap->bmdma_prd_dma, ap->ioaddr.bmdma_addr + ATA_DMA_TABLE_OFS);
2878
2879         /* specify data direction, triple-check start bit is clear */
2880         dmactl = ioread8(ap->ioaddr.bmdma_addr + ATA_DMA_CMD);
2881         dmactl &= ~(ATA_DMA_WR | ATA_DMA_START);
2882         if (!rw)
2883                 dmactl |= ATA_DMA_WR;
2884         iowrite8(dmactl, ap->ioaddr.bmdma_addr + ATA_DMA_CMD);
2885
2886         /* issue r/w command */
2887         ap->ops->sff_exec_command(ap, &qc->tf);
2888 }
2889 EXPORT_SYMBOL_GPL(ata_bmdma_setup);
2890
2891 /**
2892  *      ata_bmdma_start - Start a PCI IDE BMDMA transaction
2893  *      @qc: Info associated with this ATA transaction.
2894  *
2895  *      LOCKING:
2896  *      spin_lock_irqsave(host lock)
2897  */
2898 void ata_bmdma_start(struct ata_queued_cmd *qc)
2899 {
2900         struct ata_port *ap = qc->ap;
2901         u8 dmactl;
2902
2903         /* start host DMA transaction */
2904         dmactl = ioread8(ap->ioaddr.bmdma_addr + ATA_DMA_CMD);
2905         iowrite8(dmactl | ATA_DMA_START, ap->ioaddr.bmdma_addr + ATA_DMA_CMD);
2906
2907         /* Strictly, one may wish to issue an ioread8() here, to
2908          * flush the mmio write.  However, control also passes
2909          * to the hardware at this point, and it will interrupt
2910          * us when we are to resume control.  So, in effect,
2911          * we don't care when the mmio write flushes.
2912          * Further, a read of the DMA status register _immediately_
2913          * following the write may not be what certain flaky hardware
2914          * is expected, so I think it is best to not add a readb()
2915          * without first all the MMIO ATA cards/mobos.
2916          * Or maybe I'm just being paranoid.
2917          *
2918          * FIXME: The posting of this write means I/O starts are
2919          * unneccessarily delayed for MMIO
2920          */
2921 }
2922 EXPORT_SYMBOL_GPL(ata_bmdma_start);
2923
2924 /**
2925  *      ata_bmdma_stop - Stop PCI IDE BMDMA transfer
2926  *      @qc: Command we are ending DMA for
2927  *
2928  *      Clears the ATA_DMA_START flag in the dma control register
2929  *
2930  *      May be used as the bmdma_stop() entry in ata_port_operations.
2931  *
2932  *      LOCKING:
2933  *      spin_lock_irqsave(host lock)
2934  */
2935 void ata_bmdma_stop(struct ata_queued_cmd *qc)
2936 {
2937         struct ata_port *ap = qc->ap;
2938         void __iomem *mmio = ap->ioaddr.bmdma_addr;
2939
2940         /* clear start/stop bit */
2941         iowrite8(ioread8(mmio + ATA_DMA_CMD) & ~ATA_DMA_START,
2942                  mmio + ATA_DMA_CMD);
2943
2944         /* one-PIO-cycle guaranteed wait, per spec, for HDMA1:0 transition */
2945         ata_sff_dma_pause(ap);
2946 }
2947 EXPORT_SYMBOL_GPL(ata_bmdma_stop);
2948
2949 /**
2950  *      ata_bmdma_status - Read PCI IDE BMDMA status
2951  *      @ap: Port associated with this ATA transaction.
2952  *
2953  *      Read and return BMDMA status register.
2954  *
2955  *      May be used as the bmdma_status() entry in ata_port_operations.
2956  *
2957  *      LOCKING:
2958  *      spin_lock_irqsave(host lock)
2959  */
2960 u8 ata_bmdma_status(struct ata_port *ap)
2961 {
2962         return ioread8(ap->ioaddr.bmdma_addr + ATA_DMA_STATUS);
2963 }
2964 EXPORT_SYMBOL_GPL(ata_bmdma_status);
2965
2966
2967 /**
2968  *      ata_bmdma_port_start - Set port up for bmdma.
2969  *      @ap: Port to initialize
2970  *
2971  *      Called just after data structures for each port are
2972  *      initialized.  Allocates space for PRD table.
2973  *
2974  *      May be used as the port_start() entry in ata_port_operations.
2975  *
2976  *      LOCKING:
2977  *      Inherited from caller.
2978  */
2979 int ata_bmdma_port_start(struct ata_port *ap)
2980 {
2981         if (ap->mwdma_mask || ap->udma_mask) {
2982                 ap->bmdma_prd =
2983                         dmam_alloc_coherent(ap->host->dev, ATA_PRD_TBL_SZ,
2984                                             &ap->bmdma_prd_dma, GFP_KERNEL);
2985                 if (!ap->bmdma_prd)
2986                         return -ENOMEM;
2987         }
2988
2989         return 0;
2990 }
2991 EXPORT_SYMBOL_GPL(ata_bmdma_port_start);
2992
2993 /**
2994  *      ata_bmdma_port_start32 - Set port up for dma.
2995  *      @ap: Port to initialize
2996  *
2997  *      Called just after data structures for each port are
2998  *      initialized.  Enables 32bit PIO and allocates space for PRD
2999  *      table.
3000  *
3001  *      May be used as the port_start() entry in ata_port_operations for
3002  *      devices that are capable of 32bit PIO.
3003  *
3004  *      LOCKING:
3005  *      Inherited from caller.
3006  */
3007 int ata_bmdma_port_start32(struct ata_port *ap)
3008 {
3009         ap->pflags |= ATA_PFLAG_PIO32 | ATA_PFLAG_PIO32CHANGE;
3010         return ata_bmdma_port_start(ap);
3011 }
3012 EXPORT_SYMBOL_GPL(ata_bmdma_port_start32);
3013
3014 #ifdef CONFIG_PCI
3015
3016 /**
3017  *      ata_pci_bmdma_clear_simplex -   attempt to kick device out of simplex
3018  *      @pdev: PCI device
3019  *
3020  *      Some PCI ATA devices report simplex mode but in fact can be told to
3021  *      enter non simplex mode. This implements the necessary logic to
3022  *      perform the task on such devices. Calling it on other devices will
3023  *      have -undefined- behaviour.
3024  */
3025 int ata_pci_bmdma_clear_simplex(struct pci_dev *pdev)
3026 {
3027         unsigned long bmdma = pci_resource_start(pdev, 4);
3028         u8 simplex;
3029
3030         if (bmdma == 0)
3031                 return -ENOENT;
3032
3033         simplex = inb(bmdma + 0x02);
3034         outb(simplex & 0x60, bmdma + 0x02);
3035         simplex = inb(bmdma + 0x02);
3036         if (simplex & 0x80)
3037                 return -EOPNOTSUPP;
3038         return 0;
3039 }
3040 EXPORT_SYMBOL_GPL(ata_pci_bmdma_clear_simplex);
3041
3042 static void ata_bmdma_nodma(struct ata_host *host, const char *reason)
3043 {
3044         int i;
3045
3046         dev_printk(KERN_ERR, host->dev, "BMDMA: %s, falling back to PIO\n",
3047                    reason);
3048
3049         for (i = 0; i < 2; i++) {
3050                 host->ports[i]->mwdma_mask = 0;
3051                 host->ports[i]->udma_mask = 0;
3052         }
3053 }
3054
3055 /**
3056  *      ata_pci_bmdma_init - acquire PCI BMDMA resources and init ATA host
3057  *      @host: target ATA host
3058  *
3059  *      Acquire PCI BMDMA resources and initialize @host accordingly.
3060  *
3061  *      LOCKING:
3062  *      Inherited from calling layer (may sleep).
3063  */
3064 void ata_pci_bmdma_init(struct ata_host *host)
3065 {
3066         struct device *gdev = host->dev;
3067         struct pci_dev *pdev = to_pci_dev(gdev);
3068         int i, rc;
3069
3070         /* No BAR4 allocation: No DMA */
3071         if (pci_resource_start(pdev, 4) == 0) {
3072                 ata_bmdma_nodma(host, "BAR4 is zero");
3073                 return;
3074         }
3075
3076         /*
3077          * Some controllers require BMDMA region to be initialized
3078          * even if DMA is not in use to clear IRQ status via
3079          * ->sff_irq_clear method.  Try to initialize bmdma_addr
3080          * regardless of dma masks.
3081          */
3082         rc = pci_set_dma_mask(pdev, ATA_DMA_MASK);
3083         if (rc)
3084                 ata_bmdma_nodma(host, "failed to set dma mask");
3085         if (!rc) {
3086                 rc = pci_set_consistent_dma_mask(pdev, ATA_DMA_MASK);
3087                 if (rc)
3088                         ata_bmdma_nodma(host,
3089                                         "failed to set consistent dma mask");
3090         }
3091
3092         /* request and iomap DMA region */
3093         rc = pcim_iomap_regions(pdev, 1 << 4, dev_driver_string(gdev));
3094         if (rc) {
3095                 ata_bmdma_nodma(host, "failed to request/iomap BAR4");
3096                 return;
3097         }
3098         host->iomap = pcim_iomap_table(pdev);
3099
3100         for (i = 0; i < 2; i++) {
3101                 struct ata_port *ap = host->ports[i];
3102                 void __iomem *bmdma = host->iomap[4] + 8 * i;
3103
3104                 if (ata_port_is_dummy(ap))
3105                         continue;
3106
3107                 ap->ioaddr.bmdma_addr = bmdma;
3108                 if ((!(ap->flags & ATA_FLAG_IGN_SIMPLEX)) &&
3109                     (ioread8(bmdma + 2) & 0x80))
3110                         host->flags |= ATA_HOST_SIMPLEX;
3111
3112                 ata_port_desc(ap, "bmdma 0x%llx",
3113                     (unsigned long long)pci_resource_start(pdev, 4) + 8 * i);
3114         }
3115 }
3116 EXPORT_SYMBOL_GPL(ata_pci_bmdma_init);
3117
3118 #endif /* CONFIG_PCI */
3119
3120 /**
3121  *      ata_sff_port_init - Initialize SFF/BMDMA ATA port
3122  *      @ap: Port to initialize
3123  *
3124  *      Called on port allocation to initialize SFF/BMDMA specific
3125  *      fields.
3126  *
3127  *      LOCKING:
3128  *      None.
3129  */
3130 void ata_sff_port_init(struct ata_port *ap)
3131 {
3132         INIT_DELAYED_WORK(&ap->sff_pio_task, ata_sff_pio_task);
3133         ap->ctl = ATA_DEVCTL_OBS;
3134         ap->last_ctl = 0xFF;
3135 }
3136
3137 int __init ata_sff_init(void)
3138 {
3139         /*
3140          * FIXME: In UP case, there is only one workqueue thread and if you
3141          * have more than one PIO device, latency is bloody awful, with
3142          * occasional multi-second "hiccups" as one PIO device waits for
3143          * another.  It's an ugly wart that users DO occasionally complain
3144          * about; luckily most users have at most one PIO polled device.
3145          */
3146         ata_sff_wq = create_workqueue("ata_sff");
3147         if (!ata_sff_wq)
3148                 return -ENOMEM;
3149
3150         return 0;
3151 }
3152
3153 void __exit ata_sff_exit(void)
3154 {
3155         destroy_workqueue(ata_sff_wq);
3156 }