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