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