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