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