]> nv-tegra.nvidia Code Review - linux-2.6.git/blob - drivers/scsi/libata-core.c
d8f248dd0d010b467b607a77b9064b981920a3d6
[linux-2.6.git] / drivers / scsi / libata-core.c
1 /*
2  *  libata-core.c - helper library for ATA
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-2004 Red Hat, Inc.  All rights reserved.
9  *  Copyright 2003-2004 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/config.h>
36 #include <linux/kernel.h>
37 #include <linux/module.h>
38 #include <linux/pci.h>
39 #include <linux/init.h>
40 #include <linux/list.h>
41 #include <linux/mm.h>
42 #include <linux/highmem.h>
43 #include <linux/spinlock.h>
44 #include <linux/blkdev.h>
45 #include <linux/delay.h>
46 #include <linux/timer.h>
47 #include <linux/interrupt.h>
48 #include <linux/completion.h>
49 #include <linux/suspend.h>
50 #include <linux/workqueue.h>
51 #include <linux/jiffies.h>
52 #include <linux/scatterlist.h>
53 #include <scsi/scsi.h>
54 #include "scsi.h"
55 #include "scsi_priv.h"
56 #include <scsi/scsi_host.h>
57 #include <linux/libata.h>
58 #include <asm/io.h>
59 #include <asm/semaphore.h>
60 #include <asm/byteorder.h>
61
62 #include "libata.h"
63
64 static unsigned int ata_busy_sleep (struct ata_port *ap,
65                                     unsigned long tmout_pat,
66                                     unsigned long tmout);
67 static void ata_dev_reread_id(struct ata_port *ap, struct ata_device *dev);
68 static void ata_dev_init_params(struct ata_port *ap, struct ata_device *dev);
69 static void ata_set_mode(struct ata_port *ap);
70 static void ata_dev_set_xfermode(struct ata_port *ap, struct ata_device *dev);
71 static unsigned int ata_get_mode_mask(const struct ata_port *ap, int shift);
72 static int fgb(u32 bitmap);
73 static int ata_choose_xfer_mode(const struct ata_port *ap,
74                                 u8 *xfer_mode_out,
75                                 unsigned int *xfer_shift_out);
76 static void __ata_qc_complete(struct ata_queued_cmd *qc);
77 static void ata_pio_error(struct ata_port *ap);
78
79 static unsigned int ata_unique_id = 1;
80 static struct workqueue_struct *ata_wq;
81
82 int atapi_enabled = 0;
83 module_param(atapi_enabled, int, 0444);
84 MODULE_PARM_DESC(atapi_enabled, "Enable discovery of ATAPI devices (0=off, 1=on)");
85
86 MODULE_AUTHOR("Jeff Garzik");
87 MODULE_DESCRIPTION("Library module for ATA devices");
88 MODULE_LICENSE("GPL");
89 MODULE_VERSION(DRV_VERSION);
90
91 /**
92  *      ata_tf_load_pio - send taskfile registers to host controller
93  *      @ap: Port to which output is sent
94  *      @tf: ATA taskfile register set
95  *
96  *      Outputs ATA taskfile to standard ATA host controller.
97  *
98  *      LOCKING:
99  *      Inherited from caller.
100  */
101
102 static void ata_tf_load_pio(struct ata_port *ap, const struct ata_taskfile *tf)
103 {
104         struct ata_ioports *ioaddr = &ap->ioaddr;
105         unsigned int is_addr = tf->flags & ATA_TFLAG_ISADDR;
106
107         if (tf->ctl != ap->last_ctl) {
108                 outb(tf->ctl, ioaddr->ctl_addr);
109                 ap->last_ctl = tf->ctl;
110                 ata_wait_idle(ap);
111         }
112
113         if (is_addr && (tf->flags & ATA_TFLAG_LBA48)) {
114                 outb(tf->hob_feature, ioaddr->feature_addr);
115                 outb(tf->hob_nsect, ioaddr->nsect_addr);
116                 outb(tf->hob_lbal, ioaddr->lbal_addr);
117                 outb(tf->hob_lbam, ioaddr->lbam_addr);
118                 outb(tf->hob_lbah, ioaddr->lbah_addr);
119                 VPRINTK("hob: feat 0x%X nsect 0x%X, lba 0x%X 0x%X 0x%X\n",
120                         tf->hob_feature,
121                         tf->hob_nsect,
122                         tf->hob_lbal,
123                         tf->hob_lbam,
124                         tf->hob_lbah);
125         }
126
127         if (is_addr) {
128                 outb(tf->feature, ioaddr->feature_addr);
129                 outb(tf->nsect, ioaddr->nsect_addr);
130                 outb(tf->lbal, ioaddr->lbal_addr);
131                 outb(tf->lbam, ioaddr->lbam_addr);
132                 outb(tf->lbah, ioaddr->lbah_addr);
133                 VPRINTK("feat 0x%X nsect 0x%X lba 0x%X 0x%X 0x%X\n",
134                         tf->feature,
135                         tf->nsect,
136                         tf->lbal,
137                         tf->lbam,
138                         tf->lbah);
139         }
140
141         if (tf->flags & ATA_TFLAG_DEVICE) {
142                 outb(tf->device, ioaddr->device_addr);
143                 VPRINTK("device 0x%X\n", tf->device);
144         }
145
146         ata_wait_idle(ap);
147 }
148
149 /**
150  *      ata_tf_load_mmio - send taskfile registers to host controller
151  *      @ap: Port to which output is sent
152  *      @tf: ATA taskfile register set
153  *
154  *      Outputs ATA taskfile to standard ATA host controller using MMIO.
155  *
156  *      LOCKING:
157  *      Inherited from caller.
158  */
159
160 static void ata_tf_load_mmio(struct ata_port *ap, const struct ata_taskfile *tf)
161 {
162         struct ata_ioports *ioaddr = &ap->ioaddr;
163         unsigned int is_addr = tf->flags & ATA_TFLAG_ISADDR;
164
165         if (tf->ctl != ap->last_ctl) {
166                 writeb(tf->ctl, (void __iomem *) ap->ioaddr.ctl_addr);
167                 ap->last_ctl = tf->ctl;
168                 ata_wait_idle(ap);
169         }
170
171         if (is_addr && (tf->flags & ATA_TFLAG_LBA48)) {
172                 writeb(tf->hob_feature, (void __iomem *) ioaddr->feature_addr);
173                 writeb(tf->hob_nsect, (void __iomem *) ioaddr->nsect_addr);
174                 writeb(tf->hob_lbal, (void __iomem *) ioaddr->lbal_addr);
175                 writeb(tf->hob_lbam, (void __iomem *) ioaddr->lbam_addr);
176                 writeb(tf->hob_lbah, (void __iomem *) ioaddr->lbah_addr);
177                 VPRINTK("hob: feat 0x%X nsect 0x%X, lba 0x%X 0x%X 0x%X\n",
178                         tf->hob_feature,
179                         tf->hob_nsect,
180                         tf->hob_lbal,
181                         tf->hob_lbam,
182                         tf->hob_lbah);
183         }
184
185         if (is_addr) {
186                 writeb(tf->feature, (void __iomem *) ioaddr->feature_addr);
187                 writeb(tf->nsect, (void __iomem *) ioaddr->nsect_addr);
188                 writeb(tf->lbal, (void __iomem *) ioaddr->lbal_addr);
189                 writeb(tf->lbam, (void __iomem *) ioaddr->lbam_addr);
190                 writeb(tf->lbah, (void __iomem *) ioaddr->lbah_addr);
191                 VPRINTK("feat 0x%X nsect 0x%X lba 0x%X 0x%X 0x%X\n",
192                         tf->feature,
193                         tf->nsect,
194                         tf->lbal,
195                         tf->lbam,
196                         tf->lbah);
197         }
198
199         if (tf->flags & ATA_TFLAG_DEVICE) {
200                 writeb(tf->device, (void __iomem *) ioaddr->device_addr);
201                 VPRINTK("device 0x%X\n", tf->device);
202         }
203
204         ata_wait_idle(ap);
205 }
206
207
208 /**
209  *      ata_tf_load - send taskfile registers to host controller
210  *      @ap: Port to which output is sent
211  *      @tf: ATA taskfile register set
212  *
213  *      Outputs ATA taskfile to standard ATA host controller using MMIO
214  *      or PIO as indicated by the ATA_FLAG_MMIO flag.
215  *      Writes the control, feature, nsect, lbal, lbam, and lbah registers.
216  *      Optionally (ATA_TFLAG_LBA48) writes hob_feature, hob_nsect,
217  *      hob_lbal, hob_lbam, and hob_lbah.
218  *
219  *      This function waits for idle (!BUSY and !DRQ) after writing
220  *      registers.  If the control register has a new value, this
221  *      function also waits for idle after writing control and before
222  *      writing the remaining registers.
223  *
224  *      May be used as the tf_load() entry in ata_port_operations.
225  *
226  *      LOCKING:
227  *      Inherited from caller.
228  */
229 void ata_tf_load(struct ata_port *ap, const struct ata_taskfile *tf)
230 {
231         if (ap->flags & ATA_FLAG_MMIO)
232                 ata_tf_load_mmio(ap, tf);
233         else
234                 ata_tf_load_pio(ap, tf);
235 }
236
237 /**
238  *      ata_exec_command_pio - issue ATA command to host controller
239  *      @ap: port to which command is being issued
240  *      @tf: ATA taskfile register set
241  *
242  *      Issues PIO write to ATA command register, with proper
243  *      synchronization with interrupt handler / other threads.
244  *
245  *      LOCKING:
246  *      spin_lock_irqsave(host_set lock)
247  */
248
249 static void ata_exec_command_pio(struct ata_port *ap, const struct ata_taskfile *tf)
250 {
251         DPRINTK("ata%u: cmd 0x%X\n", ap->id, tf->command);
252
253         outb(tf->command, ap->ioaddr.command_addr);
254         ata_pause(ap);
255 }
256
257
258 /**
259  *      ata_exec_command_mmio - issue ATA command to host controller
260  *      @ap: port to which command is being issued
261  *      @tf: ATA taskfile register set
262  *
263  *      Issues MMIO write to ATA command register, with proper
264  *      synchronization with interrupt handler / other threads.
265  *
266  *      LOCKING:
267  *      spin_lock_irqsave(host_set lock)
268  */
269
270 static void ata_exec_command_mmio(struct ata_port *ap, const struct ata_taskfile *tf)
271 {
272         DPRINTK("ata%u: cmd 0x%X\n", ap->id, tf->command);
273
274         writeb(tf->command, (void __iomem *) ap->ioaddr.command_addr);
275         ata_pause(ap);
276 }
277
278
279 /**
280  *      ata_exec_command - issue ATA command to host controller
281  *      @ap: port to which command is being issued
282  *      @tf: ATA taskfile register set
283  *
284  *      Issues PIO/MMIO write to ATA command register, with proper
285  *      synchronization with interrupt handler / other threads.
286  *
287  *      LOCKING:
288  *      spin_lock_irqsave(host_set lock)
289  */
290 void ata_exec_command(struct ata_port *ap, const struct ata_taskfile *tf)
291 {
292         if (ap->flags & ATA_FLAG_MMIO)
293                 ata_exec_command_mmio(ap, tf);
294         else
295                 ata_exec_command_pio(ap, tf);
296 }
297
298 /**
299  *      ata_exec - issue ATA command to host controller
300  *      @ap: port to which command is being issued
301  *      @tf: ATA taskfile register set
302  *
303  *      Issues PIO/MMIO write to ATA command register, with proper
304  *      synchronization with interrupt handler / other threads.
305  *
306  *      LOCKING:
307  *      Obtains host_set lock.
308  */
309
310 static inline void ata_exec(struct ata_port *ap, const struct ata_taskfile *tf)
311 {
312         unsigned long flags;
313
314         DPRINTK("ata%u: cmd 0x%X\n", ap->id, tf->command);
315         spin_lock_irqsave(&ap->host_set->lock, flags);
316         ap->ops->exec_command(ap, tf);
317         spin_unlock_irqrestore(&ap->host_set->lock, flags);
318 }
319
320 /**
321  *      ata_tf_to_host - issue ATA taskfile to host controller
322  *      @ap: port to which command is being issued
323  *      @tf: ATA taskfile register set
324  *
325  *      Issues ATA taskfile register set to ATA host controller,
326  *      with proper synchronization with interrupt handler and
327  *      other threads.
328  *
329  *      LOCKING:
330  *      Obtains host_set lock.
331  */
332
333 static void ata_tf_to_host(struct ata_port *ap, const struct ata_taskfile *tf)
334 {
335         ap->ops->tf_load(ap, tf);
336
337         ata_exec(ap, tf);
338 }
339
340 /**
341  *      ata_tf_to_host_nolock - issue ATA taskfile to host controller
342  *      @ap: port to which command is being issued
343  *      @tf: ATA taskfile register set
344  *
345  *      Issues ATA taskfile register set to ATA host controller,
346  *      with proper synchronization with interrupt handler and
347  *      other threads.
348  *
349  *      LOCKING:
350  *      spin_lock_irqsave(host_set lock)
351  */
352
353 void ata_tf_to_host_nolock(struct ata_port *ap, const struct ata_taskfile *tf)
354 {
355         ap->ops->tf_load(ap, tf);
356         ap->ops->exec_command(ap, tf);
357 }
358
359 /**
360  *      ata_tf_read_pio - input device's ATA taskfile shadow registers
361  *      @ap: Port from which input is read
362  *      @tf: ATA taskfile register set for storing input
363  *
364  *      Reads ATA taskfile registers for currently-selected device
365  *      into @tf.
366  *
367  *      LOCKING:
368  *      Inherited from caller.
369  */
370
371 static void ata_tf_read_pio(struct ata_port *ap, struct ata_taskfile *tf)
372 {
373         struct ata_ioports *ioaddr = &ap->ioaddr;
374
375         tf->command = ata_check_status(ap);
376         tf->feature = inb(ioaddr->error_addr);
377         tf->nsect = inb(ioaddr->nsect_addr);
378         tf->lbal = inb(ioaddr->lbal_addr);
379         tf->lbam = inb(ioaddr->lbam_addr);
380         tf->lbah = inb(ioaddr->lbah_addr);
381         tf->device = inb(ioaddr->device_addr);
382
383         if (tf->flags & ATA_TFLAG_LBA48) {
384                 outb(tf->ctl | ATA_HOB, ioaddr->ctl_addr);
385                 tf->hob_feature = inb(ioaddr->error_addr);
386                 tf->hob_nsect = inb(ioaddr->nsect_addr);
387                 tf->hob_lbal = inb(ioaddr->lbal_addr);
388                 tf->hob_lbam = inb(ioaddr->lbam_addr);
389                 tf->hob_lbah = inb(ioaddr->lbah_addr);
390         }
391 }
392
393 /**
394  *      ata_tf_read_mmio - input device's ATA taskfile shadow registers
395  *      @ap: Port from which input is read
396  *      @tf: ATA taskfile register set for storing input
397  *
398  *      Reads ATA taskfile registers for currently-selected device
399  *      into @tf via MMIO.
400  *
401  *      LOCKING:
402  *      Inherited from caller.
403  */
404
405 static void ata_tf_read_mmio(struct ata_port *ap, struct ata_taskfile *tf)
406 {
407         struct ata_ioports *ioaddr = &ap->ioaddr;
408
409         tf->command = ata_check_status(ap);
410         tf->feature = readb((void __iomem *)ioaddr->error_addr);
411         tf->nsect = readb((void __iomem *)ioaddr->nsect_addr);
412         tf->lbal = readb((void __iomem *)ioaddr->lbal_addr);
413         tf->lbam = readb((void __iomem *)ioaddr->lbam_addr);
414         tf->lbah = readb((void __iomem *)ioaddr->lbah_addr);
415         tf->device = readb((void __iomem *)ioaddr->device_addr);
416
417         if (tf->flags & ATA_TFLAG_LBA48) {
418                 writeb(tf->ctl | ATA_HOB, (void __iomem *) ap->ioaddr.ctl_addr);
419                 tf->hob_feature = readb((void __iomem *)ioaddr->error_addr);
420                 tf->hob_nsect = readb((void __iomem *)ioaddr->nsect_addr);
421                 tf->hob_lbal = readb((void __iomem *)ioaddr->lbal_addr);
422                 tf->hob_lbam = readb((void __iomem *)ioaddr->lbam_addr);
423                 tf->hob_lbah = readb((void __iomem *)ioaddr->lbah_addr);
424         }
425 }
426
427
428 /**
429  *      ata_tf_read - input device's ATA taskfile shadow registers
430  *      @ap: Port from which input is read
431  *      @tf: ATA taskfile register set for storing input
432  *
433  *      Reads ATA taskfile registers for currently-selected device
434  *      into @tf.
435  *
436  *      Reads nsect, lbal, lbam, lbah, and device.  If ATA_TFLAG_LBA48
437  *      is set, also reads the hob registers.
438  *
439  *      May be used as the tf_read() entry in ata_port_operations.
440  *
441  *      LOCKING:
442  *      Inherited from caller.
443  */
444 void ata_tf_read(struct ata_port *ap, struct ata_taskfile *tf)
445 {
446         if (ap->flags & ATA_FLAG_MMIO)
447                 ata_tf_read_mmio(ap, tf);
448         else
449                 ata_tf_read_pio(ap, tf);
450 }
451
452 /**
453  *      ata_check_status_pio - Read device status reg & clear interrupt
454  *      @ap: port where the device is
455  *
456  *      Reads ATA taskfile status register for currently-selected device
457  *      and return its value. This also clears pending interrupts
458  *      from this device
459  *
460  *      LOCKING:
461  *      Inherited from caller.
462  */
463 static u8 ata_check_status_pio(struct ata_port *ap)
464 {
465         return inb(ap->ioaddr.status_addr);
466 }
467
468 /**
469  *      ata_check_status_mmio - Read device status reg & clear interrupt
470  *      @ap: port where the device is
471  *
472  *      Reads ATA taskfile status register for currently-selected device
473  *      via MMIO and return its value. This also clears pending interrupts
474  *      from this device
475  *
476  *      LOCKING:
477  *      Inherited from caller.
478  */
479 static u8 ata_check_status_mmio(struct ata_port *ap)
480 {
481         return readb((void __iomem *) ap->ioaddr.status_addr);
482 }
483
484
485 /**
486  *      ata_check_status - Read device status reg & clear interrupt
487  *      @ap: port where the device is
488  *
489  *      Reads ATA taskfile status register for currently-selected device
490  *      and return its value. This also clears pending interrupts
491  *      from this device
492  *
493  *      May be used as the check_status() entry in ata_port_operations.
494  *
495  *      LOCKING:
496  *      Inherited from caller.
497  */
498 u8 ata_check_status(struct ata_port *ap)
499 {
500         if (ap->flags & ATA_FLAG_MMIO)
501                 return ata_check_status_mmio(ap);
502         return ata_check_status_pio(ap);
503 }
504
505
506 /**
507  *      ata_altstatus - Read device alternate status reg
508  *      @ap: port where the device is
509  *
510  *      Reads ATA taskfile alternate status register for
511  *      currently-selected device and return its value.
512  *
513  *      Note: may NOT be used as the check_altstatus() entry in
514  *      ata_port_operations.
515  *
516  *      LOCKING:
517  *      Inherited from caller.
518  */
519 u8 ata_altstatus(struct ata_port *ap)
520 {
521         if (ap->ops->check_altstatus)
522                 return ap->ops->check_altstatus(ap);
523
524         if (ap->flags & ATA_FLAG_MMIO)
525                 return readb((void __iomem *)ap->ioaddr.altstatus_addr);
526         return inb(ap->ioaddr.altstatus_addr);
527 }
528
529
530 /**
531  *      ata_tf_to_fis - Convert ATA taskfile to SATA FIS structure
532  *      @tf: Taskfile to convert
533  *      @fis: Buffer into which data will output
534  *      @pmp: Port multiplier port
535  *
536  *      Converts a standard ATA taskfile to a Serial ATA
537  *      FIS structure (Register - Host to Device).
538  *
539  *      LOCKING:
540  *      Inherited from caller.
541  */
542
543 void ata_tf_to_fis(const struct ata_taskfile *tf, u8 *fis, u8 pmp)
544 {
545         fis[0] = 0x27;  /* Register - Host to Device FIS */
546         fis[1] = (pmp & 0xf) | (1 << 7); /* Port multiplier number,
547                                             bit 7 indicates Command FIS */
548         fis[2] = tf->command;
549         fis[3] = tf->feature;
550
551         fis[4] = tf->lbal;
552         fis[5] = tf->lbam;
553         fis[6] = tf->lbah;
554         fis[7] = tf->device;
555
556         fis[8] = tf->hob_lbal;
557         fis[9] = tf->hob_lbam;
558         fis[10] = tf->hob_lbah;
559         fis[11] = tf->hob_feature;
560
561         fis[12] = tf->nsect;
562         fis[13] = tf->hob_nsect;
563         fis[14] = 0;
564         fis[15] = tf->ctl;
565
566         fis[16] = 0;
567         fis[17] = 0;
568         fis[18] = 0;
569         fis[19] = 0;
570 }
571
572 /**
573  *      ata_tf_from_fis - Convert SATA FIS to ATA taskfile
574  *      @fis: Buffer from which data will be input
575  *      @tf: Taskfile to output
576  *
577  *      Converts a standard ATA taskfile to a Serial ATA
578  *      FIS structure (Register - Host to Device).
579  *
580  *      LOCKING:
581  *      Inherited from caller.
582  */
583
584 void ata_tf_from_fis(const u8 *fis, struct ata_taskfile *tf)
585 {
586         tf->command     = fis[2];       /* status */
587         tf->feature     = fis[3];       /* error */
588
589         tf->lbal        = fis[4];
590         tf->lbam        = fis[5];
591         tf->lbah        = fis[6];
592         tf->device      = fis[7];
593
594         tf->hob_lbal    = fis[8];
595         tf->hob_lbam    = fis[9];
596         tf->hob_lbah    = fis[10];
597
598         tf->nsect       = fis[12];
599         tf->hob_nsect   = fis[13];
600 }
601
602 static const u8 ata_rw_cmds[] = {
603         /* pio multi */
604         ATA_CMD_READ_MULTI,
605         ATA_CMD_WRITE_MULTI,
606         ATA_CMD_READ_MULTI_EXT,
607         ATA_CMD_WRITE_MULTI_EXT,
608         /* pio */
609         ATA_CMD_PIO_READ,
610         ATA_CMD_PIO_WRITE,
611         ATA_CMD_PIO_READ_EXT,
612         ATA_CMD_PIO_WRITE_EXT,
613         /* dma */
614         ATA_CMD_READ,
615         ATA_CMD_WRITE,
616         ATA_CMD_READ_EXT,
617         ATA_CMD_WRITE_EXT
618 };
619
620 /**
621  *      ata_rwcmd_protocol - set taskfile r/w commands and protocol
622  *      @qc: command to examine and configure
623  *
624  *      Examine the device configuration and tf->flags to calculate 
625  *      the proper read/write commands and protocol to use.
626  *
627  *      LOCKING:
628  *      caller.
629  */
630 void ata_rwcmd_protocol(struct ata_queued_cmd *qc)
631 {
632         struct ata_taskfile *tf = &qc->tf;
633         struct ata_device *dev = qc->dev;
634
635         int index, lba48, write;
636  
637         lba48 = (tf->flags & ATA_TFLAG_LBA48) ? 2 : 0;
638         write = (tf->flags & ATA_TFLAG_WRITE) ? 1 : 0;
639
640         if (dev->flags & ATA_DFLAG_PIO) {
641                 tf->protocol = ATA_PROT_PIO;
642                 index = dev->multi_count ? 0 : 4;
643         } else {
644                 tf->protocol = ATA_PROT_DMA;
645                 index = 8;
646         }
647
648         tf->command = ata_rw_cmds[index + lba48 + write];
649 }
650
651 static const char * xfer_mode_str[] = {
652         "UDMA/16",
653         "UDMA/25",
654         "UDMA/33",
655         "UDMA/44",
656         "UDMA/66",
657         "UDMA/100",
658         "UDMA/133",
659         "UDMA7",
660         "MWDMA0",
661         "MWDMA1",
662         "MWDMA2",
663         "PIO0",
664         "PIO1",
665         "PIO2",
666         "PIO3",
667         "PIO4",
668 };
669
670 /**
671  *      ata_udma_string - convert UDMA bit offset to string
672  *      @mask: mask of bits supported; only highest bit counts.
673  *
674  *      Determine string which represents the highest speed
675  *      (highest bit in @udma_mask).
676  *
677  *      LOCKING:
678  *      None.
679  *
680  *      RETURNS:
681  *      Constant C string representing highest speed listed in
682  *      @udma_mask, or the constant C string "<n/a>".
683  */
684
685 static const char *ata_mode_string(unsigned int mask)
686 {
687         int i;
688
689         for (i = 7; i >= 0; i--)
690                 if (mask & (1 << i))
691                         goto out;
692         for (i = ATA_SHIFT_MWDMA + 2; i >= ATA_SHIFT_MWDMA; i--)
693                 if (mask & (1 << i))
694                         goto out;
695         for (i = ATA_SHIFT_PIO + 4; i >= ATA_SHIFT_PIO; i--)
696                 if (mask & (1 << i))
697                         goto out;
698
699         return "<n/a>";
700
701 out:
702         return xfer_mode_str[i];
703 }
704
705 /**
706  *      ata_pio_devchk - PATA device presence detection
707  *      @ap: ATA channel to examine
708  *      @device: Device to examine (starting at zero)
709  *
710  *      This technique was originally described in
711  *      Hale Landis's ATADRVR (www.ata-atapi.com), and
712  *      later found its way into the ATA/ATAPI spec.
713  *
714  *      Write a pattern to the ATA shadow registers,
715  *      and if a device is present, it will respond by
716  *      correctly storing and echoing back the
717  *      ATA shadow register contents.
718  *
719  *      LOCKING:
720  *      caller.
721  */
722
723 static unsigned int ata_pio_devchk(struct ata_port *ap,
724                                    unsigned int device)
725 {
726         struct ata_ioports *ioaddr = &ap->ioaddr;
727         u8 nsect, lbal;
728
729         ap->ops->dev_select(ap, device);
730
731         outb(0x55, ioaddr->nsect_addr);
732         outb(0xaa, ioaddr->lbal_addr);
733
734         outb(0xaa, ioaddr->nsect_addr);
735         outb(0x55, ioaddr->lbal_addr);
736
737         outb(0x55, ioaddr->nsect_addr);
738         outb(0xaa, ioaddr->lbal_addr);
739
740         nsect = inb(ioaddr->nsect_addr);
741         lbal = inb(ioaddr->lbal_addr);
742
743         if ((nsect == 0x55) && (lbal == 0xaa))
744                 return 1;       /* we found a device */
745
746         return 0;               /* nothing found */
747 }
748
749 /**
750  *      ata_mmio_devchk - PATA device presence detection
751  *      @ap: ATA channel to examine
752  *      @device: Device to examine (starting at zero)
753  *
754  *      This technique was originally described in
755  *      Hale Landis's ATADRVR (www.ata-atapi.com), and
756  *      later found its way into the ATA/ATAPI spec.
757  *
758  *      Write a pattern to the ATA shadow registers,
759  *      and if a device is present, it will respond by
760  *      correctly storing and echoing back the
761  *      ATA shadow register contents.
762  *
763  *      LOCKING:
764  *      caller.
765  */
766
767 static unsigned int ata_mmio_devchk(struct ata_port *ap,
768                                     unsigned int device)
769 {
770         struct ata_ioports *ioaddr = &ap->ioaddr;
771         u8 nsect, lbal;
772
773         ap->ops->dev_select(ap, device);
774
775         writeb(0x55, (void __iomem *) ioaddr->nsect_addr);
776         writeb(0xaa, (void __iomem *) ioaddr->lbal_addr);
777
778         writeb(0xaa, (void __iomem *) ioaddr->nsect_addr);
779         writeb(0x55, (void __iomem *) ioaddr->lbal_addr);
780
781         writeb(0x55, (void __iomem *) ioaddr->nsect_addr);
782         writeb(0xaa, (void __iomem *) ioaddr->lbal_addr);
783
784         nsect = readb((void __iomem *) ioaddr->nsect_addr);
785         lbal = readb((void __iomem *) ioaddr->lbal_addr);
786
787         if ((nsect == 0x55) && (lbal == 0xaa))
788                 return 1;       /* we found a device */
789
790         return 0;               /* nothing found */
791 }
792
793 /**
794  *      ata_devchk - PATA device presence detection
795  *      @ap: ATA channel to examine
796  *      @device: Device to examine (starting at zero)
797  *
798  *      Dispatch ATA device presence detection, depending
799  *      on whether we are using PIO or MMIO to talk to the
800  *      ATA shadow registers.
801  *
802  *      LOCKING:
803  *      caller.
804  */
805
806 static unsigned int ata_devchk(struct ata_port *ap,
807                                     unsigned int device)
808 {
809         if (ap->flags & ATA_FLAG_MMIO)
810                 return ata_mmio_devchk(ap, device);
811         return ata_pio_devchk(ap, device);
812 }
813
814 /**
815  *      ata_dev_classify - determine device type based on ATA-spec signature
816  *      @tf: ATA taskfile register set for device to be identified
817  *
818  *      Determine from taskfile register contents whether a device is
819  *      ATA or ATAPI, as per "Signature and persistence" section
820  *      of ATA/PI spec (volume 1, sect 5.14).
821  *
822  *      LOCKING:
823  *      None.
824  *
825  *      RETURNS:
826  *      Device type, %ATA_DEV_ATA, %ATA_DEV_ATAPI, or %ATA_DEV_UNKNOWN
827  *      the event of failure.
828  */
829
830 unsigned int ata_dev_classify(const struct ata_taskfile *tf)
831 {
832         /* Apple's open source Darwin code hints that some devices only
833          * put a proper signature into the LBA mid/high registers,
834          * So, we only check those.  It's sufficient for uniqueness.
835          */
836
837         if (((tf->lbam == 0) && (tf->lbah == 0)) ||
838             ((tf->lbam == 0x3c) && (tf->lbah == 0xc3))) {
839                 DPRINTK("found ATA device by sig\n");
840                 return ATA_DEV_ATA;
841         }
842
843         if (((tf->lbam == 0x14) && (tf->lbah == 0xeb)) ||
844             ((tf->lbam == 0x69) && (tf->lbah == 0x96))) {
845                 DPRINTK("found ATAPI device by sig\n");
846                 return ATA_DEV_ATAPI;
847         }
848
849         DPRINTK("unknown device\n");
850         return ATA_DEV_UNKNOWN;
851 }
852
853 /**
854  *      ata_dev_try_classify - Parse returned ATA device signature
855  *      @ap: ATA channel to examine
856  *      @device: Device to examine (starting at zero)
857  *
858  *      After an event -- SRST, E.D.D., or SATA COMRESET -- occurs,
859  *      an ATA/ATAPI-defined set of values is placed in the ATA
860  *      shadow registers, indicating the results of device detection
861  *      and diagnostics.
862  *
863  *      Select the ATA device, and read the values from the ATA shadow
864  *      registers.  Then parse according to the Error register value,
865  *      and the spec-defined values examined by ata_dev_classify().
866  *
867  *      LOCKING:
868  *      caller.
869  */
870
871 static u8 ata_dev_try_classify(struct ata_port *ap, unsigned int device)
872 {
873         struct ata_device *dev = &ap->device[device];
874         struct ata_taskfile tf;
875         unsigned int class;
876         u8 err;
877
878         ap->ops->dev_select(ap, device);
879
880         memset(&tf, 0, sizeof(tf));
881
882         ap->ops->tf_read(ap, &tf);
883         err = tf.feature;
884
885         dev->class = ATA_DEV_NONE;
886
887         /* see if device passed diags */
888         if (err == 1)
889                 /* do nothing */ ;
890         else if ((device == 0) && (err == 0x81))
891                 /* do nothing */ ;
892         else
893                 return err;
894
895         /* determine if device if ATA or ATAPI */
896         class = ata_dev_classify(&tf);
897         if (class == ATA_DEV_UNKNOWN)
898                 return err;
899         if ((class == ATA_DEV_ATA) && (ata_chk_status(ap) == 0))
900                 return err;
901
902         dev->class = class;
903
904         return err;
905 }
906
907 /**
908  *      ata_dev_id_string - Convert IDENTIFY DEVICE page into string
909  *      @id: IDENTIFY DEVICE results we will examine
910  *      @s: string into which data is output
911  *      @ofs: offset into identify device page
912  *      @len: length of string to return. must be an even number.
913  *
914  *      The strings in the IDENTIFY DEVICE page are broken up into
915  *      16-bit chunks.  Run through the string, and output each
916  *      8-bit chunk linearly, regardless of platform.
917  *
918  *      LOCKING:
919  *      caller.
920  */
921
922 void ata_dev_id_string(const u16 *id, unsigned char *s,
923                        unsigned int ofs, unsigned int len)
924 {
925         unsigned int c;
926
927         while (len > 0) {
928                 c = id[ofs] >> 8;
929                 *s = c;
930                 s++;
931
932                 c = id[ofs] & 0xff;
933                 *s = c;
934                 s++;
935
936                 ofs++;
937                 len -= 2;
938         }
939 }
940
941
942 /**
943  *      ata_noop_dev_select - Select device 0/1 on ATA bus
944  *      @ap: ATA channel to manipulate
945  *      @device: ATA device (numbered from zero) to select
946  *
947  *      This function performs no actual function.
948  *
949  *      May be used as the dev_select() entry in ata_port_operations.
950  *
951  *      LOCKING:
952  *      caller.
953  */
954 void ata_noop_dev_select (struct ata_port *ap, unsigned int device)
955 {
956 }
957
958
959 /**
960  *      ata_std_dev_select - Select device 0/1 on ATA bus
961  *      @ap: ATA channel to manipulate
962  *      @device: ATA device (numbered from zero) to select
963  *
964  *      Use the method defined in the ATA specification to
965  *      make either device 0, or device 1, active on the
966  *      ATA channel.  Works with both PIO and MMIO.
967  *
968  *      May be used as the dev_select() entry in ata_port_operations.
969  *
970  *      LOCKING:
971  *      caller.
972  */
973
974 void ata_std_dev_select (struct ata_port *ap, unsigned int device)
975 {
976         u8 tmp;
977
978         if (device == 0)
979                 tmp = ATA_DEVICE_OBS;
980         else
981                 tmp = ATA_DEVICE_OBS | ATA_DEV1;
982
983         if (ap->flags & ATA_FLAG_MMIO) {
984                 writeb(tmp, (void __iomem *) ap->ioaddr.device_addr);
985         } else {
986                 outb(tmp, ap->ioaddr.device_addr);
987         }
988         ata_pause(ap);          /* needed; also flushes, for mmio */
989 }
990
991 /**
992  *      ata_dev_select - Select device 0/1 on ATA bus
993  *      @ap: ATA channel to manipulate
994  *      @device: ATA device (numbered from zero) to select
995  *      @wait: non-zero to wait for Status register BSY bit to clear
996  *      @can_sleep: non-zero if context allows sleeping
997  *
998  *      Use the method defined in the ATA specification to
999  *      make either device 0, or device 1, active on the
1000  *      ATA channel.
1001  *
1002  *      This is a high-level version of ata_std_dev_select(),
1003  *      which additionally provides the services of inserting
1004  *      the proper pauses and status polling, where needed.
1005  *
1006  *      LOCKING:
1007  *      caller.
1008  */
1009
1010 void ata_dev_select(struct ata_port *ap, unsigned int device,
1011                            unsigned int wait, unsigned int can_sleep)
1012 {
1013         VPRINTK("ENTER, ata%u: device %u, wait %u\n",
1014                 ap->id, device, wait);
1015
1016         if (wait)
1017                 ata_wait_idle(ap);
1018
1019         ap->ops->dev_select(ap, device);
1020
1021         if (wait) {
1022                 if (can_sleep && ap->device[device].class == ATA_DEV_ATAPI)
1023                         msleep(150);
1024                 ata_wait_idle(ap);
1025         }
1026 }
1027
1028 /**
1029  *      ata_dump_id - IDENTIFY DEVICE info debugging output
1030  *      @dev: Device whose IDENTIFY DEVICE page we will dump
1031  *
1032  *      Dump selected 16-bit words from a detected device's
1033  *      IDENTIFY PAGE page.
1034  *
1035  *      LOCKING:
1036  *      caller.
1037  */
1038
1039 static inline void ata_dump_id(const struct ata_device *dev)
1040 {
1041         DPRINTK("49==0x%04x  "
1042                 "53==0x%04x  "
1043                 "63==0x%04x  "
1044                 "64==0x%04x  "
1045                 "75==0x%04x  \n",
1046                 dev->id[49],
1047                 dev->id[53],
1048                 dev->id[63],
1049                 dev->id[64],
1050                 dev->id[75]);
1051         DPRINTK("80==0x%04x  "
1052                 "81==0x%04x  "
1053                 "82==0x%04x  "
1054                 "83==0x%04x  "
1055                 "84==0x%04x  \n",
1056                 dev->id[80],
1057                 dev->id[81],
1058                 dev->id[82],
1059                 dev->id[83],
1060                 dev->id[84]);
1061         DPRINTK("88==0x%04x  "
1062                 "93==0x%04x\n",
1063                 dev->id[88],
1064                 dev->id[93]);
1065 }
1066
1067 /*
1068  *      Compute the PIO modes available for this device. This is not as
1069  *      trivial as it seems if we must consider early devices correctly.
1070  *
1071  *      FIXME: pre IDE drive timing (do we care ?). 
1072  */
1073
1074 static unsigned int ata_pio_modes(const struct ata_device *adev)
1075 {
1076         u16 modes;
1077
1078         /* Usual case. Word 53 indicates word 88 is valid */
1079         if (adev->id[ATA_ID_FIELD_VALID] & (1 << 2)) {
1080                 modes = adev->id[ATA_ID_PIO_MODES] & 0x03;
1081                 modes <<= 3;
1082                 modes |= 0x7;
1083                 return modes;
1084         }
1085
1086         /* If word 88 isn't valid then Word 51 holds the PIO timing number
1087            for the maximum. Turn it into a mask and return it */
1088         modes = (2 << (adev->id[ATA_ID_OLD_PIO_MODES] & 0xFF)) - 1 ;
1089         return modes;
1090 }
1091
1092 /**
1093  *      ata_dev_identify - obtain IDENTIFY x DEVICE page
1094  *      @ap: port on which device we wish to probe resides
1095  *      @device: device bus address, starting at zero
1096  *
1097  *      Following bus reset, we issue the IDENTIFY [PACKET] DEVICE
1098  *      command, and read back the 512-byte device information page.
1099  *      The device information page is fed to us via the standard
1100  *      PIO-IN protocol, but we hand-code it here. (TODO: investigate
1101  *      using standard PIO-IN paths)
1102  *
1103  *      After reading the device information page, we use several
1104  *      bits of information from it to initialize data structures
1105  *      that will be used during the lifetime of the ata_device.
1106  *      Other data from the info page is used to disqualify certain
1107  *      older ATA devices we do not wish to support.
1108  *
1109  *      LOCKING:
1110  *      Inherited from caller.  Some functions called by this function
1111  *      obtain the host_set lock.
1112  */
1113
1114 static void ata_dev_identify(struct ata_port *ap, unsigned int device)
1115 {
1116         struct ata_device *dev = &ap->device[device];
1117         unsigned int major_version;
1118         u16 tmp;
1119         unsigned long xfer_modes;
1120         unsigned int using_edd;
1121         DECLARE_COMPLETION(wait);
1122         struct ata_queued_cmd *qc;
1123         unsigned long flags;
1124         int rc;
1125
1126         if (!ata_dev_present(dev)) {
1127                 DPRINTK("ENTER/EXIT (host %u, dev %u) -- nodev\n",
1128                         ap->id, device);
1129                 return;
1130         }
1131
1132         if (ap->flags & (ATA_FLAG_SRST | ATA_FLAG_SATA_RESET))
1133                 using_edd = 0;
1134         else
1135                 using_edd = 1;
1136
1137         DPRINTK("ENTER, host %u, dev %u\n", ap->id, device);
1138
1139         assert (dev->class == ATA_DEV_ATA || dev->class == ATA_DEV_ATAPI ||
1140                 dev->class == ATA_DEV_NONE);
1141
1142         ata_dev_select(ap, device, 1, 1); /* select device 0/1 */
1143
1144         qc = ata_qc_new_init(ap, dev);
1145         BUG_ON(qc == NULL);
1146
1147         ata_sg_init_one(qc, dev->id, sizeof(dev->id));
1148         qc->dma_dir = DMA_FROM_DEVICE;
1149         qc->tf.protocol = ATA_PROT_PIO;
1150         qc->nsect = 1;
1151
1152 retry:
1153         if (dev->class == ATA_DEV_ATA) {
1154                 qc->tf.command = ATA_CMD_ID_ATA;
1155                 DPRINTK("do ATA identify\n");
1156         } else {
1157                 qc->tf.command = ATA_CMD_ID_ATAPI;
1158                 DPRINTK("do ATAPI identify\n");
1159         }
1160
1161         qc->waiting = &wait;
1162         qc->complete_fn = ata_qc_complete_noop;
1163
1164         spin_lock_irqsave(&ap->host_set->lock, flags);
1165         rc = ata_qc_issue(qc);
1166         spin_unlock_irqrestore(&ap->host_set->lock, flags);
1167
1168         if (rc)
1169                 goto err_out;
1170         else
1171                 wait_for_completion(&wait);
1172
1173         spin_lock_irqsave(&ap->host_set->lock, flags);
1174         ap->ops->tf_read(ap, &qc->tf);
1175         spin_unlock_irqrestore(&ap->host_set->lock, flags);
1176
1177         if (qc->tf.command & ATA_ERR) {
1178                 /*
1179                  * arg!  EDD works for all test cases, but seems to return
1180                  * the ATA signature for some ATAPI devices.  Until the
1181                  * reason for this is found and fixed, we fix up the mess
1182                  * here.  If IDENTIFY DEVICE returns command aborted
1183                  * (as ATAPI devices do), then we issue an
1184                  * IDENTIFY PACKET DEVICE.
1185                  *
1186                  * ATA software reset (SRST, the default) does not appear
1187                  * to have this problem.
1188                  */
1189                 if ((using_edd) && (qc->tf.command == ATA_CMD_ID_ATA)) {
1190                         u8 err = qc->tf.feature;
1191                         if (err & ATA_ABORTED) {
1192                                 dev->class = ATA_DEV_ATAPI;
1193                                 qc->cursg = 0;
1194                                 qc->cursg_ofs = 0;
1195                                 qc->cursect = 0;
1196                                 qc->nsect = 1;
1197                                 goto retry;
1198                         }
1199                 }
1200                 goto err_out;
1201         }
1202
1203         swap_buf_le16(dev->id, ATA_ID_WORDS);
1204
1205         /* print device capabilities */
1206         printk(KERN_DEBUG "ata%u: dev %u cfg "
1207                "49:%04x 82:%04x 83:%04x 84:%04x 85:%04x 86:%04x 87:%04x 88:%04x\n",
1208                ap->id, device, dev->id[49],
1209                dev->id[82], dev->id[83], dev->id[84],
1210                dev->id[85], dev->id[86], dev->id[87],
1211                dev->id[88]);
1212
1213         /*
1214          * common ATA, ATAPI feature tests
1215          */
1216
1217         /* we require DMA support (bits 8 of word 49) */
1218         if (!ata_id_has_dma(dev->id)) {
1219                 printk(KERN_DEBUG "ata%u: no dma\n", ap->id);
1220                 goto err_out_nosup;
1221         }
1222
1223         /* quick-n-dirty find max transfer mode; for printk only */
1224         xfer_modes = dev->id[ATA_ID_UDMA_MODES];
1225         if (!xfer_modes)
1226                 xfer_modes = (dev->id[ATA_ID_MWDMA_MODES]) << ATA_SHIFT_MWDMA;
1227         if (!xfer_modes)
1228                 xfer_modes = ata_pio_modes(dev);
1229
1230         ata_dump_id(dev);
1231
1232         /* ATA-specific feature tests */
1233         if (dev->class == ATA_DEV_ATA) {
1234                 if (!ata_id_is_ata(dev->id))    /* sanity check */
1235                         goto err_out_nosup;
1236
1237                 /* get major version */
1238                 tmp = dev->id[ATA_ID_MAJOR_VER];
1239                 for (major_version = 14; major_version >= 1; major_version--)
1240                         if (tmp & (1 << major_version))
1241                                 break;
1242
1243                 /*
1244                  * The exact sequence expected by certain pre-ATA4 drives is:
1245                  * SRST RESET
1246                  * IDENTIFY
1247                  * INITIALIZE DEVICE PARAMETERS
1248                  * anything else..
1249                  * Some drives were very specific about that exact sequence.
1250                  */
1251                 if (major_version < 4 || (!ata_id_has_lba(dev->id))) {
1252                         ata_dev_init_params(ap, dev);
1253
1254                         /* current CHS translation info (id[53-58]) might be
1255                          * changed. reread the identify device info.
1256                          */
1257                         ata_dev_reread_id(ap, dev);
1258                 }
1259
1260                 if (ata_id_has_lba(dev->id)) {
1261                         dev->flags |= ATA_DFLAG_LBA;
1262
1263                         if (ata_id_has_lba48(dev->id)) {
1264                                 dev->flags |= ATA_DFLAG_LBA48;
1265                                 dev->n_sectors = ata_id_u64(dev->id, 100);
1266                         } else {
1267                                 dev->n_sectors = ata_id_u32(dev->id, 60);
1268                         }
1269
1270                         /* print device info to dmesg */
1271                         printk(KERN_INFO "ata%u: dev %u ATA-%d, max %s, %Lu sectors:%s\n",
1272                                ap->id, device,
1273                                major_version,
1274                                ata_mode_string(xfer_modes),
1275                                (unsigned long long)dev->n_sectors,
1276                                dev->flags & ATA_DFLAG_LBA48 ? " LBA48" : " LBA");
1277                 } else { 
1278                         /* CHS */
1279
1280                         /* Default translation */
1281                         dev->cylinders  = dev->id[1];
1282                         dev->heads      = dev->id[3];
1283                         dev->sectors    = dev->id[6];
1284                         dev->n_sectors  = dev->cylinders * dev->heads * dev->sectors;
1285
1286                         if (ata_id_current_chs_valid(dev->id)) {
1287                                 /* Current CHS translation is valid. */
1288                                 dev->cylinders = dev->id[54];
1289                                 dev->heads     = dev->id[55];
1290                                 dev->sectors   = dev->id[56];
1291                                 
1292                                 dev->n_sectors = ata_id_u32(dev->id, 57);
1293                         }
1294
1295                         /* print device info to dmesg */
1296                         printk(KERN_INFO "ata%u: dev %u ATA-%d, max %s, %Lu sectors: CHS %d/%d/%d\n",
1297                                ap->id, device,
1298                                major_version,
1299                                ata_mode_string(xfer_modes),
1300                                (unsigned long long)dev->n_sectors,
1301                                (int)dev->cylinders, (int)dev->heads, (int)dev->sectors);
1302
1303                 }
1304
1305                 ap->host->max_cmd_len = 16;
1306         }
1307
1308         /* ATAPI-specific feature tests */
1309         else {
1310                 if (ata_id_is_ata(dev->id))             /* sanity check */
1311                         goto err_out_nosup;
1312
1313                 rc = atapi_cdb_len(dev->id);
1314                 if ((rc < 12) || (rc > ATAPI_CDB_LEN)) {
1315                         printk(KERN_WARNING "ata%u: unsupported CDB len\n", ap->id);
1316                         goto err_out_nosup;
1317                 }
1318                 ap->cdb_len = (unsigned int) rc;
1319                 ap->host->max_cmd_len = (unsigned char) ap->cdb_len;
1320
1321                 if (ata_id_cdb_intr(dev->id))
1322                         dev->flags |= ATA_DFLAG_CDB_INTR;
1323
1324                 /* print device info to dmesg */
1325                 printk(KERN_INFO "ata%u: dev %u ATAPI, max %s\n",
1326                        ap->id, device,
1327                        ata_mode_string(xfer_modes));
1328         }
1329
1330         DPRINTK("EXIT, drv_stat = 0x%x\n", ata_chk_status(ap));
1331         return;
1332
1333 err_out_nosup:
1334         printk(KERN_WARNING "ata%u: dev %u not supported, ignoring\n",
1335                ap->id, device);
1336 err_out:
1337         dev->class++;   /* converts ATA_DEV_xxx into ATA_DEV_xxx_UNSUP */
1338         DPRINTK("EXIT, err\n");
1339 }
1340
1341
1342 static inline u8 ata_dev_knobble(const struct ata_port *ap)
1343 {
1344         return ((ap->cbl == ATA_CBL_SATA) && (!ata_id_is_sata(ap->device->id)));
1345 }
1346
1347 /**
1348  *      ata_dev_config - Run device specific handlers and check for
1349  *                       SATA->PATA bridges
1350  *      @ap: Bus
1351  *      @i:  Device
1352  *
1353  *      LOCKING:
1354  */
1355
1356 void ata_dev_config(struct ata_port *ap, unsigned int i)
1357 {
1358         /* limit bridge transfers to udma5, 200 sectors */
1359         if (ata_dev_knobble(ap)) {
1360                 printk(KERN_INFO "ata%u(%u): applying bridge limits\n",
1361                         ap->id, ap->device->devno);
1362                 ap->udma_mask &= ATA_UDMA5;
1363                 ap->host->max_sectors = ATA_MAX_SECTORS;
1364                 ap->host->hostt->max_sectors = ATA_MAX_SECTORS;
1365                 ap->device->flags |= ATA_DFLAG_LOCK_SECTORS;
1366         }
1367
1368         if (ap->ops->dev_config)
1369                 ap->ops->dev_config(ap, &ap->device[i]);
1370 }
1371
1372 /**
1373  *      ata_bus_probe - Reset and probe ATA bus
1374  *      @ap: Bus to probe
1375  *
1376  *      Master ATA bus probing function.  Initiates a hardware-dependent
1377  *      bus reset, then attempts to identify any devices found on
1378  *      the bus.
1379  *
1380  *      LOCKING:
1381  *      PCI/etc. bus probe sem.
1382  *
1383  *      RETURNS:
1384  *      Zero on success, non-zero on error.
1385  */
1386
1387 static int ata_bus_probe(struct ata_port *ap)
1388 {
1389         unsigned int i, found = 0;
1390
1391         ap->ops->phy_reset(ap);
1392         if (ap->flags & ATA_FLAG_PORT_DISABLED)
1393                 goto err_out;
1394
1395         for (i = 0; i < ATA_MAX_DEVICES; i++) {
1396                 ata_dev_identify(ap, i);
1397                 if (ata_dev_present(&ap->device[i])) {
1398                         found = 1;
1399                         ata_dev_config(ap,i);
1400                 }
1401         }
1402
1403         if ((!found) || (ap->flags & ATA_FLAG_PORT_DISABLED))
1404                 goto err_out_disable;
1405
1406         ata_set_mode(ap);
1407         if (ap->flags & ATA_FLAG_PORT_DISABLED)
1408                 goto err_out_disable;
1409
1410         return 0;
1411
1412 err_out_disable:
1413         ap->ops->port_disable(ap);
1414 err_out:
1415         return -1;
1416 }
1417
1418 /**
1419  *      ata_port_probe - Mark port as enabled
1420  *      @ap: Port for which we indicate enablement
1421  *
1422  *      Modify @ap data structure such that the system
1423  *      thinks that the entire port is enabled.
1424  *
1425  *      LOCKING: host_set lock, or some other form of
1426  *      serialization.
1427  */
1428
1429 void ata_port_probe(struct ata_port *ap)
1430 {
1431         ap->flags &= ~ATA_FLAG_PORT_DISABLED;
1432 }
1433
1434 /**
1435  *      __sata_phy_reset - Wake/reset a low-level SATA PHY
1436  *      @ap: SATA port associated with target SATA PHY.
1437  *
1438  *      This function issues commands to standard SATA Sxxx
1439  *      PHY registers, to wake up the phy (and device), and
1440  *      clear any reset condition.
1441  *
1442  *      LOCKING:
1443  *      PCI/etc. bus probe sem.
1444  *
1445  */
1446 void __sata_phy_reset(struct ata_port *ap)
1447 {
1448         u32 sstatus;
1449         unsigned long timeout = jiffies + (HZ * 5);
1450
1451         if (ap->flags & ATA_FLAG_SATA_RESET) {
1452                 /* issue phy wake/reset */
1453                 scr_write_flush(ap, SCR_CONTROL, 0x301);
1454                 /* Couldn't find anything in SATA I/II specs, but
1455                  * AHCI-1.1 10.4.2 says at least 1 ms. */
1456                 mdelay(1);
1457         }
1458         scr_write_flush(ap, SCR_CONTROL, 0x300); /* phy wake/clear reset */
1459
1460         /* wait for phy to become ready, if necessary */
1461         do {
1462                 msleep(200);
1463                 sstatus = scr_read(ap, SCR_STATUS);
1464                 if ((sstatus & 0xf) != 1)
1465                         break;
1466         } while (time_before(jiffies, timeout));
1467
1468         /* TODO: phy layer with polling, timeouts, etc. */
1469         if (sata_dev_present(ap))
1470                 ata_port_probe(ap);
1471         else {
1472                 sstatus = scr_read(ap, SCR_STATUS);
1473                 printk(KERN_INFO "ata%u: no device found (phy stat %08x)\n",
1474                        ap->id, sstatus);
1475                 ata_port_disable(ap);
1476         }
1477
1478         if (ap->flags & ATA_FLAG_PORT_DISABLED)
1479                 return;
1480
1481         if (ata_busy_sleep(ap, ATA_TMOUT_BOOT_QUICK, ATA_TMOUT_BOOT)) {
1482                 ata_port_disable(ap);
1483                 return;
1484         }
1485
1486         ap->cbl = ATA_CBL_SATA;
1487 }
1488
1489 /**
1490  *      sata_phy_reset - Reset SATA bus.
1491  *      @ap: SATA port associated with target SATA PHY.
1492  *
1493  *      This function resets the SATA bus, and then probes
1494  *      the bus for devices.
1495  *
1496  *      LOCKING:
1497  *      PCI/etc. bus probe sem.
1498  *
1499  */
1500 void sata_phy_reset(struct ata_port *ap)
1501 {
1502         __sata_phy_reset(ap);
1503         if (ap->flags & ATA_FLAG_PORT_DISABLED)
1504                 return;
1505         ata_bus_reset(ap);
1506 }
1507
1508 /**
1509  *      ata_port_disable - Disable port.
1510  *      @ap: Port to be disabled.
1511  *
1512  *      Modify @ap data structure such that the system
1513  *      thinks that the entire port is disabled, and should
1514  *      never attempt to probe or communicate with devices
1515  *      on this port.
1516  *
1517  *      LOCKING: host_set lock, or some other form of
1518  *      serialization.
1519  */
1520
1521 void ata_port_disable(struct ata_port *ap)
1522 {
1523         ap->device[0].class = ATA_DEV_NONE;
1524         ap->device[1].class = ATA_DEV_NONE;
1525         ap->flags |= ATA_FLAG_PORT_DISABLED;
1526 }
1527
1528 /*
1529  * This mode timing computation functionality is ported over from
1530  * drivers/ide/ide-timing.h and was originally written by Vojtech Pavlik
1531  */
1532 /*
1533  * PIO 0-5, MWDMA 0-2 and UDMA 0-6 timings (in nanoseconds).
1534  * These were taken from ATA/ATAPI-6 standard, rev 0a, except
1535  * for PIO 5, which is a nonstandard extension and UDMA6, which
1536  * is currently supported only by Maxtor drives. 
1537  */
1538
1539 static const struct ata_timing ata_timing[] = {
1540
1541         { XFER_UDMA_6,     0,   0,   0,   0,   0,   0,   0,  15 },
1542         { XFER_UDMA_5,     0,   0,   0,   0,   0,   0,   0,  20 },
1543         { XFER_UDMA_4,     0,   0,   0,   0,   0,   0,   0,  30 },
1544         { XFER_UDMA_3,     0,   0,   0,   0,   0,   0,   0,  45 },
1545
1546         { XFER_UDMA_2,     0,   0,   0,   0,   0,   0,   0,  60 },
1547         { XFER_UDMA_1,     0,   0,   0,   0,   0,   0,   0,  80 },
1548         { XFER_UDMA_0,     0,   0,   0,   0,   0,   0,   0, 120 },
1549
1550 /*      { XFER_UDMA_SLOW,  0,   0,   0,   0,   0,   0,   0, 150 }, */
1551                                           
1552         { XFER_MW_DMA_2,  25,   0,   0,   0,  70,  25, 120,   0 },
1553         { XFER_MW_DMA_1,  45,   0,   0,   0,  80,  50, 150,   0 },
1554         { XFER_MW_DMA_0,  60,   0,   0,   0, 215, 215, 480,   0 },
1555                                           
1556         { XFER_SW_DMA_2,  60,   0,   0,   0, 120, 120, 240,   0 },
1557         { XFER_SW_DMA_1,  90,   0,   0,   0, 240, 240, 480,   0 },
1558         { XFER_SW_DMA_0, 120,   0,   0,   0, 480, 480, 960,   0 },
1559
1560 /*      { XFER_PIO_5,     20,  50,  30, 100,  50,  30, 100,   0 }, */
1561         { XFER_PIO_4,     25,  70,  25, 120,  70,  25, 120,   0 },
1562         { XFER_PIO_3,     30,  80,  70, 180,  80,  70, 180,   0 },
1563
1564         { XFER_PIO_2,     30, 290,  40, 330, 100,  90, 240,   0 },
1565         { XFER_PIO_1,     50, 290,  93, 383, 125, 100, 383,   0 },
1566         { XFER_PIO_0,     70, 290, 240, 600, 165, 150, 600,   0 },
1567
1568 /*      { XFER_PIO_SLOW, 120, 290, 240, 960, 290, 240, 960,   0 }, */
1569
1570         { 0xFF }
1571 };
1572
1573 #define ENOUGH(v,unit)          (((v)-1)/(unit)+1)
1574 #define EZ(v,unit)              ((v)?ENOUGH(v,unit):0)
1575
1576 static void ata_timing_quantize(const struct ata_timing *t, struct ata_timing *q, int T, int UT)
1577 {
1578         q->setup   = EZ(t->setup   * 1000,  T);
1579         q->act8b   = EZ(t->act8b   * 1000,  T);
1580         q->rec8b   = EZ(t->rec8b   * 1000,  T);
1581         q->cyc8b   = EZ(t->cyc8b   * 1000,  T);
1582         q->active  = EZ(t->active  * 1000,  T);
1583         q->recover = EZ(t->recover * 1000,  T);
1584         q->cycle   = EZ(t->cycle   * 1000,  T);
1585         q->udma    = EZ(t->udma    * 1000, UT);
1586 }
1587
1588 void ata_timing_merge(const struct ata_timing *a, const struct ata_timing *b,
1589                       struct ata_timing *m, unsigned int what)
1590 {
1591         if (what & ATA_TIMING_SETUP  ) m->setup   = max(a->setup,   b->setup);
1592         if (what & ATA_TIMING_ACT8B  ) m->act8b   = max(a->act8b,   b->act8b);
1593         if (what & ATA_TIMING_REC8B  ) m->rec8b   = max(a->rec8b,   b->rec8b);
1594         if (what & ATA_TIMING_CYC8B  ) m->cyc8b   = max(a->cyc8b,   b->cyc8b);
1595         if (what & ATA_TIMING_ACTIVE ) m->active  = max(a->active,  b->active);
1596         if (what & ATA_TIMING_RECOVER) m->recover = max(a->recover, b->recover);
1597         if (what & ATA_TIMING_CYCLE  ) m->cycle   = max(a->cycle,   b->cycle);
1598         if (what & ATA_TIMING_UDMA   ) m->udma    = max(a->udma,    b->udma);
1599 }
1600
1601 static const struct ata_timing* ata_timing_find_mode(unsigned short speed)
1602 {
1603         const struct ata_timing *t;
1604
1605         for (t = ata_timing; t->mode != speed; t++)
1606                 if (t->mode == 0xFF)
1607                         return NULL;
1608         return t; 
1609 }
1610
1611 int ata_timing_compute(struct ata_device *adev, unsigned short speed,
1612                        struct ata_timing *t, int T, int UT)
1613 {
1614         const struct ata_timing *s;
1615         struct ata_timing p;
1616
1617         /*
1618          * Find the mode. 
1619         */
1620
1621         if (!(s = ata_timing_find_mode(speed)))
1622                 return -EINVAL;
1623
1624         /*
1625          * If the drive is an EIDE drive, it can tell us it needs extended
1626          * PIO/MW_DMA cycle timing.
1627          */
1628
1629         if (adev->id[ATA_ID_FIELD_VALID] & 2) { /* EIDE drive */
1630                 memset(&p, 0, sizeof(p));
1631                 if(speed >= XFER_PIO_0 && speed <= XFER_SW_DMA_0) {
1632                         if (speed <= XFER_PIO_2) p.cycle = p.cyc8b = adev->id[ATA_ID_EIDE_PIO];
1633                                             else p.cycle = p.cyc8b = adev->id[ATA_ID_EIDE_PIO_IORDY];
1634                 } else if(speed >= XFER_MW_DMA_0 && speed <= XFER_MW_DMA_2) {
1635                         p.cycle = adev->id[ATA_ID_EIDE_DMA_MIN];
1636                 }
1637                 ata_timing_merge(&p, t, t, ATA_TIMING_CYCLE | ATA_TIMING_CYC8B);
1638         }
1639
1640         /*
1641          * Convert the timing to bus clock counts.
1642          */
1643
1644         ata_timing_quantize(s, t, T, UT);
1645
1646         /*
1647          * Even in DMA/UDMA modes we still use PIO access for IDENTIFY, S.M.A.R.T
1648          * and some other commands. We have to ensure that the DMA cycle timing is
1649          * slower/equal than the fastest PIO timing.
1650          */
1651
1652         if (speed > XFER_PIO_4) {
1653                 ata_timing_compute(adev, adev->pio_mode, &p, T, UT);
1654                 ata_timing_merge(&p, t, t, ATA_TIMING_ALL);
1655         }
1656
1657         /*
1658          * Lenghten active & recovery time so that cycle time is correct.
1659          */
1660
1661         if (t->act8b + t->rec8b < t->cyc8b) {
1662                 t->act8b += (t->cyc8b - (t->act8b + t->rec8b)) / 2;
1663                 t->rec8b = t->cyc8b - t->act8b;
1664         }
1665
1666         if (t->active + t->recover < t->cycle) {
1667                 t->active += (t->cycle - (t->active + t->recover)) / 2;
1668                 t->recover = t->cycle - t->active;
1669         }
1670
1671         return 0;
1672 }
1673
1674 static const struct {
1675         unsigned int shift;
1676         u8 base;
1677 } xfer_mode_classes[] = {
1678         { ATA_SHIFT_UDMA,       XFER_UDMA_0 },
1679         { ATA_SHIFT_MWDMA,      XFER_MW_DMA_0 },
1680         { ATA_SHIFT_PIO,        XFER_PIO_0 },
1681 };
1682
1683 static inline u8 base_from_shift(unsigned int shift)
1684 {
1685         int i;
1686
1687         for (i = 0; i < ARRAY_SIZE(xfer_mode_classes); i++)
1688                 if (xfer_mode_classes[i].shift == shift)
1689                         return xfer_mode_classes[i].base;
1690
1691         return 0xff;
1692 }
1693
1694 static void ata_dev_set_mode(struct ata_port *ap, struct ata_device *dev)
1695 {
1696         int ofs, idx;
1697         u8 base;
1698
1699         if (!ata_dev_present(dev) || (ap->flags & ATA_FLAG_PORT_DISABLED))
1700                 return;
1701
1702         if (dev->xfer_shift == ATA_SHIFT_PIO)
1703                 dev->flags |= ATA_DFLAG_PIO;
1704
1705         ata_dev_set_xfermode(ap, dev);
1706
1707         base = base_from_shift(dev->xfer_shift);
1708         ofs = dev->xfer_mode - base;
1709         idx = ofs + dev->xfer_shift;
1710         WARN_ON(idx >= ARRAY_SIZE(xfer_mode_str));
1711
1712         DPRINTK("idx=%d xfer_shift=%u, xfer_mode=0x%x, base=0x%x, offset=%d\n",
1713                 idx, dev->xfer_shift, (int)dev->xfer_mode, (int)base, ofs);
1714
1715         printk(KERN_INFO "ata%u: dev %u configured for %s\n",
1716                 ap->id, dev->devno, xfer_mode_str[idx]);
1717 }
1718
1719 static int ata_host_set_pio(struct ata_port *ap)
1720 {
1721         unsigned int mask;
1722         int x, i;
1723         u8 base, xfer_mode;
1724
1725         mask = ata_get_mode_mask(ap, ATA_SHIFT_PIO);
1726         x = fgb(mask);
1727         if (x < 0) {
1728                 printk(KERN_WARNING "ata%u: no PIO support\n", ap->id);
1729                 return -1;
1730         }
1731
1732         base = base_from_shift(ATA_SHIFT_PIO);
1733         xfer_mode = base + x;
1734
1735         DPRINTK("base 0x%x xfer_mode 0x%x mask 0x%x x %d\n",
1736                 (int)base, (int)xfer_mode, mask, x);
1737
1738         for (i = 0; i < ATA_MAX_DEVICES; i++) {
1739                 struct ata_device *dev = &ap->device[i];
1740                 if (ata_dev_present(dev)) {
1741                         dev->pio_mode = xfer_mode;
1742                         dev->xfer_mode = xfer_mode;
1743                         dev->xfer_shift = ATA_SHIFT_PIO;
1744                         if (ap->ops->set_piomode)
1745                                 ap->ops->set_piomode(ap, dev);
1746                 }
1747         }
1748
1749         return 0;
1750 }
1751
1752 static void ata_host_set_dma(struct ata_port *ap, u8 xfer_mode,
1753                             unsigned int xfer_shift)
1754 {
1755         int i;
1756
1757         for (i = 0; i < ATA_MAX_DEVICES; i++) {
1758                 struct ata_device *dev = &ap->device[i];
1759                 if (ata_dev_present(dev)) {
1760                         dev->dma_mode = xfer_mode;
1761                         dev->xfer_mode = xfer_mode;
1762                         dev->xfer_shift = xfer_shift;
1763                         if (ap->ops->set_dmamode)
1764                                 ap->ops->set_dmamode(ap, dev);
1765                 }
1766         }
1767 }
1768
1769 /**
1770  *      ata_set_mode - Program timings and issue SET FEATURES - XFER
1771  *      @ap: port on which timings will be programmed
1772  *
1773  *      Set ATA device disk transfer mode (PIO3, UDMA6, etc.).
1774  *
1775  *      LOCKING:
1776  *      PCI/etc. bus probe sem.
1777  *
1778  */
1779 static void ata_set_mode(struct ata_port *ap)
1780 {
1781         unsigned int xfer_shift;
1782         u8 xfer_mode;
1783         int rc;
1784
1785         /* step 1: always set host PIO timings */
1786         rc = ata_host_set_pio(ap);
1787         if (rc)
1788                 goto err_out;
1789
1790         /* step 2: choose the best data xfer mode */
1791         xfer_mode = xfer_shift = 0;
1792         rc = ata_choose_xfer_mode(ap, &xfer_mode, &xfer_shift);
1793         if (rc)
1794                 goto err_out;
1795
1796         /* step 3: if that xfer mode isn't PIO, set host DMA timings */
1797         if (xfer_shift != ATA_SHIFT_PIO)
1798                 ata_host_set_dma(ap, xfer_mode, xfer_shift);
1799
1800         /* step 4: update devices' xfer mode */
1801         ata_dev_set_mode(ap, &ap->device[0]);
1802         ata_dev_set_mode(ap, &ap->device[1]);
1803
1804         if (ap->flags & ATA_FLAG_PORT_DISABLED)
1805                 return;
1806
1807         if (ap->ops->post_set_mode)
1808                 ap->ops->post_set_mode(ap);
1809
1810         return;
1811
1812 err_out:
1813         ata_port_disable(ap);
1814 }
1815
1816 /**
1817  *      ata_busy_sleep - sleep until BSY clears, or timeout
1818  *      @ap: port containing status register to be polled
1819  *      @tmout_pat: impatience timeout
1820  *      @tmout: overall timeout
1821  *
1822  *      Sleep until ATA Status register bit BSY clears,
1823  *      or a timeout occurs.
1824  *
1825  *      LOCKING: None.
1826  *
1827  */
1828
1829 static unsigned int ata_busy_sleep (struct ata_port *ap,
1830                                     unsigned long tmout_pat,
1831                                     unsigned long tmout)
1832 {
1833         unsigned long timer_start, timeout;
1834         u8 status;
1835
1836         status = ata_busy_wait(ap, ATA_BUSY, 300);
1837         timer_start = jiffies;
1838         timeout = timer_start + tmout_pat;
1839         while ((status & ATA_BUSY) && (time_before(jiffies, timeout))) {
1840                 msleep(50);
1841                 status = ata_busy_wait(ap, ATA_BUSY, 3);
1842         }
1843
1844         if (status & ATA_BUSY)
1845                 printk(KERN_WARNING "ata%u is slow to respond, "
1846                        "please be patient\n", ap->id);
1847
1848         timeout = timer_start + tmout;
1849         while ((status & ATA_BUSY) && (time_before(jiffies, timeout))) {
1850                 msleep(50);
1851                 status = ata_chk_status(ap);
1852         }
1853
1854         if (status & ATA_BUSY) {
1855                 printk(KERN_ERR "ata%u failed to respond (%lu secs)\n",
1856                        ap->id, tmout / HZ);
1857                 return 1;
1858         }
1859
1860         return 0;
1861 }
1862
1863 static void ata_bus_post_reset(struct ata_port *ap, unsigned int devmask)
1864 {
1865         struct ata_ioports *ioaddr = &ap->ioaddr;
1866         unsigned int dev0 = devmask & (1 << 0);
1867         unsigned int dev1 = devmask & (1 << 1);
1868         unsigned long timeout;
1869
1870         /* if device 0 was found in ata_devchk, wait for its
1871          * BSY bit to clear
1872          */
1873         if (dev0)
1874                 ata_busy_sleep(ap, ATA_TMOUT_BOOT_QUICK, ATA_TMOUT_BOOT);
1875
1876         /* if device 1 was found in ata_devchk, wait for
1877          * register access, then wait for BSY to clear
1878          */
1879         timeout = jiffies + ATA_TMOUT_BOOT;
1880         while (dev1) {
1881                 u8 nsect, lbal;
1882
1883                 ap->ops->dev_select(ap, 1);
1884                 if (ap->flags & ATA_FLAG_MMIO) {
1885                         nsect = readb((void __iomem *) ioaddr->nsect_addr);
1886                         lbal = readb((void __iomem *) ioaddr->lbal_addr);
1887                 } else {
1888                         nsect = inb(ioaddr->nsect_addr);
1889                         lbal = inb(ioaddr->lbal_addr);
1890                 }
1891                 if ((nsect == 1) && (lbal == 1))
1892                         break;
1893                 if (time_after(jiffies, timeout)) {
1894                         dev1 = 0;
1895                         break;
1896                 }
1897                 msleep(50);     /* give drive a breather */
1898         }
1899         if (dev1)
1900                 ata_busy_sleep(ap, ATA_TMOUT_BOOT_QUICK, ATA_TMOUT_BOOT);
1901
1902         /* is all this really necessary? */
1903         ap->ops->dev_select(ap, 0);
1904         if (dev1)
1905                 ap->ops->dev_select(ap, 1);
1906         if (dev0)
1907                 ap->ops->dev_select(ap, 0);
1908 }
1909
1910 /**
1911  *      ata_bus_edd - Issue EXECUTE DEVICE DIAGNOSTIC command.
1912  *      @ap: Port to reset and probe
1913  *
1914  *      Use the EXECUTE DEVICE DIAGNOSTIC command to reset and
1915  *      probe the bus.  Not often used these days.
1916  *
1917  *      LOCKING:
1918  *      PCI/etc. bus probe sem.
1919  *
1920  */
1921
1922 static unsigned int ata_bus_edd(struct ata_port *ap)
1923 {
1924         struct ata_taskfile tf;
1925
1926         /* set up execute-device-diag (bus reset) taskfile */
1927         /* also, take interrupts to a known state (disabled) */
1928         DPRINTK("execute-device-diag\n");
1929         ata_tf_init(ap, &tf, 0);
1930         tf.ctl |= ATA_NIEN;
1931         tf.command = ATA_CMD_EDD;
1932         tf.protocol = ATA_PROT_NODATA;
1933
1934         /* do bus reset */
1935         ata_tf_to_host(ap, &tf);
1936
1937         /* spec says at least 2ms.  but who knows with those
1938          * crazy ATAPI devices...
1939          */
1940         msleep(150);
1941
1942         return ata_busy_sleep(ap, ATA_TMOUT_BOOT_QUICK, ATA_TMOUT_BOOT);
1943 }
1944
1945 static unsigned int ata_bus_softreset(struct ata_port *ap,
1946                                       unsigned int devmask)
1947 {
1948         struct ata_ioports *ioaddr = &ap->ioaddr;
1949
1950         DPRINTK("ata%u: bus reset via SRST\n", ap->id);
1951
1952         /* software reset.  causes dev0 to be selected */
1953         if (ap->flags & ATA_FLAG_MMIO) {
1954                 writeb(ap->ctl, (void __iomem *) ioaddr->ctl_addr);
1955                 udelay(20);     /* FIXME: flush */
1956                 writeb(ap->ctl | ATA_SRST, (void __iomem *) ioaddr->ctl_addr);
1957                 udelay(20);     /* FIXME: flush */
1958                 writeb(ap->ctl, (void __iomem *) ioaddr->ctl_addr);
1959         } else {
1960                 outb(ap->ctl, ioaddr->ctl_addr);
1961                 udelay(10);
1962                 outb(ap->ctl | ATA_SRST, ioaddr->ctl_addr);
1963                 udelay(10);
1964                 outb(ap->ctl, ioaddr->ctl_addr);
1965         }
1966
1967         /* spec mandates ">= 2ms" before checking status.
1968          * We wait 150ms, because that was the magic delay used for
1969          * ATAPI devices in Hale Landis's ATADRVR, for the period of time
1970          * between when the ATA command register is written, and then
1971          * status is checked.  Because waiting for "a while" before
1972          * checking status is fine, post SRST, we perform this magic
1973          * delay here as well.
1974          */
1975         msleep(150);
1976
1977         ata_bus_post_reset(ap, devmask);
1978
1979         return 0;
1980 }
1981
1982 /**
1983  *      ata_bus_reset - reset host port and associated ATA channel
1984  *      @ap: port to reset
1985  *
1986  *      This is typically the first time we actually start issuing
1987  *      commands to the ATA channel.  We wait for BSY to clear, then
1988  *      issue EXECUTE DEVICE DIAGNOSTIC command, polling for its
1989  *      result.  Determine what devices, if any, are on the channel
1990  *      by looking at the device 0/1 error register.  Look at the signature
1991  *      stored in each device's taskfile registers, to determine if
1992  *      the device is ATA or ATAPI.
1993  *
1994  *      LOCKING:
1995  *      PCI/etc. bus probe sem.
1996  *      Obtains host_set lock.
1997  *
1998  *      SIDE EFFECTS:
1999  *      Sets ATA_FLAG_PORT_DISABLED if bus reset fails.
2000  */
2001
2002 void ata_bus_reset(struct ata_port *ap)
2003 {
2004         struct ata_ioports *ioaddr = &ap->ioaddr;
2005         unsigned int slave_possible = ap->flags & ATA_FLAG_SLAVE_POSS;
2006         u8 err;
2007         unsigned int dev0, dev1 = 0, rc = 0, devmask = 0;
2008
2009         DPRINTK("ENTER, host %u, port %u\n", ap->id, ap->port_no);
2010
2011         /* determine if device 0/1 are present */
2012         if (ap->flags & ATA_FLAG_SATA_RESET)
2013                 dev0 = 1;
2014         else {
2015                 dev0 = ata_devchk(ap, 0);
2016                 if (slave_possible)
2017                         dev1 = ata_devchk(ap, 1);
2018         }
2019
2020         if (dev0)
2021                 devmask |= (1 << 0);
2022         if (dev1)
2023                 devmask |= (1 << 1);
2024
2025         /* select device 0 again */
2026         ap->ops->dev_select(ap, 0);
2027
2028         /* issue bus reset */
2029         if (ap->flags & ATA_FLAG_SRST)
2030                 rc = ata_bus_softreset(ap, devmask);
2031         else if ((ap->flags & ATA_FLAG_SATA_RESET) == 0) {
2032                 /* set up device control */
2033                 if (ap->flags & ATA_FLAG_MMIO)
2034                         writeb(ap->ctl, (void __iomem *) ioaddr->ctl_addr);
2035                 else
2036                         outb(ap->ctl, ioaddr->ctl_addr);
2037                 rc = ata_bus_edd(ap);
2038         }
2039
2040         if (rc)
2041                 goto err_out;
2042
2043         /*
2044          * determine by signature whether we have ATA or ATAPI devices
2045          */
2046         err = ata_dev_try_classify(ap, 0);
2047         if ((slave_possible) && (err != 0x81))
2048                 ata_dev_try_classify(ap, 1);
2049
2050         /* re-enable interrupts */
2051         if (ap->ioaddr.ctl_addr)        /* FIXME: hack. create a hook instead */
2052                 ata_irq_on(ap);
2053
2054         /* is double-select really necessary? */
2055         if (ap->device[1].class != ATA_DEV_NONE)
2056                 ap->ops->dev_select(ap, 1);
2057         if (ap->device[0].class != ATA_DEV_NONE)
2058                 ap->ops->dev_select(ap, 0);
2059
2060         /* if no devices were detected, disable this port */
2061         if ((ap->device[0].class == ATA_DEV_NONE) &&
2062             (ap->device[1].class == ATA_DEV_NONE))
2063                 goto err_out;
2064
2065         if (ap->flags & (ATA_FLAG_SATA_RESET | ATA_FLAG_SRST)) {
2066                 /* set up device control for ATA_FLAG_SATA_RESET */
2067                 if (ap->flags & ATA_FLAG_MMIO)
2068                         writeb(ap->ctl, (void __iomem *) ioaddr->ctl_addr);
2069                 else
2070                         outb(ap->ctl, ioaddr->ctl_addr);
2071         }
2072
2073         DPRINTK("EXIT\n");
2074         return;
2075
2076 err_out:
2077         printk(KERN_ERR "ata%u: disabling port\n", ap->id);
2078         ap->ops->port_disable(ap);
2079
2080         DPRINTK("EXIT\n");
2081 }
2082
2083 static void ata_pr_blacklisted(const struct ata_port *ap,
2084                                const struct ata_device *dev)
2085 {
2086         printk(KERN_WARNING "ata%u: dev %u is on DMA blacklist, disabling DMA\n",
2087                 ap->id, dev->devno);
2088 }
2089
2090 static const char * ata_dma_blacklist [] = {
2091         "WDC AC11000H",
2092         "WDC AC22100H",
2093         "WDC AC32500H",
2094         "WDC AC33100H",
2095         "WDC AC31600H",
2096         "WDC AC32100H",
2097         "WDC AC23200L",
2098         "Compaq CRD-8241B",
2099         "CRD-8400B",
2100         "CRD-8480B",
2101         "CRD-8482B",
2102         "CRD-84",
2103         "SanDisk SDP3B",
2104         "SanDisk SDP3B-64",
2105         "SANYO CD-ROM CRD",
2106         "HITACHI CDR-8",
2107         "HITACHI CDR-8335",
2108         "HITACHI CDR-8435",
2109         "Toshiba CD-ROM XM-6202B",
2110         "TOSHIBA CD-ROM XM-1702BC",
2111         "CD-532E-A",
2112         "E-IDE CD-ROM CR-840",
2113         "CD-ROM Drive/F5A",
2114         "WPI CDD-820",
2115         "SAMSUNG CD-ROM SC-148C",
2116         "SAMSUNG CD-ROM SC",
2117         "SanDisk SDP3B-64",
2118         "ATAPI CD-ROM DRIVE 40X MAXIMUM",
2119         "_NEC DV5800A",
2120 };
2121
2122 static int ata_dma_blacklisted(const struct ata_device *dev)
2123 {
2124         unsigned char model_num[40];
2125         char *s;
2126         unsigned int len;
2127         int i;
2128
2129         ata_dev_id_string(dev->id, model_num, ATA_ID_PROD_OFS,
2130                           sizeof(model_num));
2131         s = &model_num[0];
2132         len = strnlen(s, sizeof(model_num));
2133
2134         /* ATAPI specifies that empty space is blank-filled; remove blanks */
2135         while ((len > 0) && (s[len - 1] == ' ')) {
2136                 len--;
2137                 s[len] = 0;
2138         }
2139
2140         for (i = 0; i < ARRAY_SIZE(ata_dma_blacklist); i++)
2141                 if (!strncmp(ata_dma_blacklist[i], s, len))
2142                         return 1;
2143
2144         return 0;
2145 }
2146
2147 static unsigned int ata_get_mode_mask(const struct ata_port *ap, int shift)
2148 {
2149         const struct ata_device *master, *slave;
2150         unsigned int mask;
2151
2152         master = &ap->device[0];
2153         slave = &ap->device[1];
2154
2155         assert (ata_dev_present(master) || ata_dev_present(slave));
2156
2157         if (shift == ATA_SHIFT_UDMA) {
2158                 mask = ap->udma_mask;
2159                 if (ata_dev_present(master)) {
2160                         mask &= (master->id[ATA_ID_UDMA_MODES] & 0xff);
2161                         if (ata_dma_blacklisted(master)) {
2162                                 mask = 0;
2163                                 ata_pr_blacklisted(ap, master);
2164                         }
2165                 }
2166                 if (ata_dev_present(slave)) {
2167                         mask &= (slave->id[ATA_ID_UDMA_MODES] & 0xff);
2168                         if (ata_dma_blacklisted(slave)) {
2169                                 mask = 0;
2170                                 ata_pr_blacklisted(ap, slave);
2171                         }
2172                 }
2173         }
2174         else if (shift == ATA_SHIFT_MWDMA) {
2175                 mask = ap->mwdma_mask;
2176                 if (ata_dev_present(master)) {
2177                         mask &= (master->id[ATA_ID_MWDMA_MODES] & 0x07);
2178                         if (ata_dma_blacklisted(master)) {
2179                                 mask = 0;
2180                                 ata_pr_blacklisted(ap, master);
2181                         }
2182                 }
2183                 if (ata_dev_present(slave)) {
2184                         mask &= (slave->id[ATA_ID_MWDMA_MODES] & 0x07);
2185                         if (ata_dma_blacklisted(slave)) {
2186                                 mask = 0;
2187                                 ata_pr_blacklisted(ap, slave);
2188                         }
2189                 }
2190         }
2191         else if (shift == ATA_SHIFT_PIO) {
2192                 mask = ap->pio_mask;
2193                 if (ata_dev_present(master)) {
2194                         /* spec doesn't return explicit support for
2195                          * PIO0-2, so we fake it
2196                          */
2197                         u16 tmp_mode = master->id[ATA_ID_PIO_MODES] & 0x03;
2198                         tmp_mode <<= 3;
2199                         tmp_mode |= 0x7;
2200                         mask &= tmp_mode;
2201                 }
2202                 if (ata_dev_present(slave)) {
2203                         /* spec doesn't return explicit support for
2204                          * PIO0-2, so we fake it
2205                          */
2206                         u16 tmp_mode = slave->id[ATA_ID_PIO_MODES] & 0x03;
2207                         tmp_mode <<= 3;
2208                         tmp_mode |= 0x7;
2209                         mask &= tmp_mode;
2210                 }
2211         }
2212         else {
2213                 mask = 0xffffffff; /* shut up compiler warning */
2214                 BUG();
2215         }
2216
2217         return mask;
2218 }
2219
2220 /* find greatest bit */
2221 static int fgb(u32 bitmap)
2222 {
2223         unsigned int i;
2224         int x = -1;
2225
2226         for (i = 0; i < 32; i++)
2227                 if (bitmap & (1 << i))
2228                         x = i;
2229
2230         return x;
2231 }
2232
2233 /**
2234  *      ata_choose_xfer_mode - attempt to find best transfer mode
2235  *      @ap: Port for which an xfer mode will be selected
2236  *      @xfer_mode_out: (output) SET FEATURES - XFER MODE code
2237  *      @xfer_shift_out: (output) bit shift that selects this mode
2238  *
2239  *      Based on host and device capabilities, determine the
2240  *      maximum transfer mode that is amenable to all.
2241  *
2242  *      LOCKING:
2243  *      PCI/etc. bus probe sem.
2244  *
2245  *      RETURNS:
2246  *      Zero on success, negative on error.
2247  */
2248
2249 static int ata_choose_xfer_mode(const struct ata_port *ap,
2250                                 u8 *xfer_mode_out,
2251                                 unsigned int *xfer_shift_out)
2252 {
2253         unsigned int mask, shift;
2254         int x, i;
2255
2256         for (i = 0; i < ARRAY_SIZE(xfer_mode_classes); i++) {
2257                 shift = xfer_mode_classes[i].shift;
2258                 mask = ata_get_mode_mask(ap, shift);
2259
2260                 x = fgb(mask);
2261                 if (x >= 0) {
2262                         *xfer_mode_out = xfer_mode_classes[i].base + x;
2263                         *xfer_shift_out = shift;
2264                         return 0;
2265                 }
2266         }
2267
2268         return -1;
2269 }
2270
2271 /**
2272  *      ata_dev_set_xfermode - Issue SET FEATURES - XFER MODE command
2273  *      @ap: Port associated with device @dev
2274  *      @dev: Device to which command will be sent
2275  *
2276  *      Issue SET FEATURES - XFER MODE command to device @dev
2277  *      on port @ap.
2278  *
2279  *      LOCKING:
2280  *      PCI/etc. bus probe sem.
2281  */
2282
2283 static void ata_dev_set_xfermode(struct ata_port *ap, struct ata_device *dev)
2284 {
2285         DECLARE_COMPLETION(wait);
2286         struct ata_queued_cmd *qc;
2287         int rc;
2288         unsigned long flags;
2289
2290         /* set up set-features taskfile */
2291         DPRINTK("set features - xfer mode\n");
2292
2293         qc = ata_qc_new_init(ap, dev);
2294         BUG_ON(qc == NULL);
2295
2296         qc->tf.command = ATA_CMD_SET_FEATURES;
2297         qc->tf.feature = SETFEATURES_XFER;
2298         qc->tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
2299         qc->tf.protocol = ATA_PROT_NODATA;
2300         qc->tf.nsect = dev->xfer_mode;
2301
2302         qc->waiting = &wait;
2303         qc->complete_fn = ata_qc_complete_noop;
2304
2305         spin_lock_irqsave(&ap->host_set->lock, flags);
2306         rc = ata_qc_issue(qc);
2307         spin_unlock_irqrestore(&ap->host_set->lock, flags);
2308
2309         if (rc)
2310                 ata_port_disable(ap);
2311         else
2312                 wait_for_completion(&wait);
2313
2314         DPRINTK("EXIT\n");
2315 }
2316
2317 /**
2318  *      ata_dev_reread_id - Reread the device identify device info
2319  *      @ap: port where the device is
2320  *      @dev: device to reread the identify device info
2321  *
2322  *      LOCKING:
2323  */
2324
2325 static void ata_dev_reread_id(struct ata_port *ap, struct ata_device *dev)
2326 {
2327         DECLARE_COMPLETION(wait);
2328         struct ata_queued_cmd *qc;
2329         unsigned long flags;
2330         int rc;
2331
2332         qc = ata_qc_new_init(ap, dev);
2333         BUG_ON(qc == NULL);
2334
2335         ata_sg_init_one(qc, dev->id, sizeof(dev->id));
2336         qc->dma_dir = DMA_FROM_DEVICE;
2337
2338         if (dev->class == ATA_DEV_ATA) {
2339                 qc->tf.command = ATA_CMD_ID_ATA;
2340                 DPRINTK("do ATA identify\n");
2341         } else {
2342                 qc->tf.command = ATA_CMD_ID_ATAPI;
2343                 DPRINTK("do ATAPI identify\n");
2344         }
2345
2346         qc->tf.flags |= ATA_TFLAG_DEVICE;
2347         qc->tf.protocol = ATA_PROT_PIO;
2348         qc->nsect = 1;
2349
2350         qc->waiting = &wait;
2351         qc->complete_fn = ata_qc_complete_noop;
2352
2353         spin_lock_irqsave(&ap->host_set->lock, flags);
2354         rc = ata_qc_issue(qc);
2355         spin_unlock_irqrestore(&ap->host_set->lock, flags);
2356
2357         if (rc)
2358                 goto err_out;
2359
2360         wait_for_completion(&wait);
2361
2362         swap_buf_le16(dev->id, ATA_ID_WORDS);
2363
2364         ata_dump_id(dev);
2365
2366         DPRINTK("EXIT\n");
2367
2368         return;
2369 err_out:
2370         ata_port_disable(ap);
2371 }
2372
2373 /**
2374  *      ata_dev_init_params - Issue INIT DEV PARAMS command
2375  *      @ap: Port associated with device @dev
2376  *      @dev: Device to which command will be sent
2377  *
2378  *      LOCKING:
2379  */
2380
2381 static void ata_dev_init_params(struct ata_port *ap, struct ata_device *dev)
2382 {
2383         DECLARE_COMPLETION(wait);
2384         struct ata_queued_cmd *qc;
2385         int rc;
2386         unsigned long flags;
2387         u16 sectors = dev->id[6];
2388         u16 heads   = dev->id[3];
2389
2390         /* Number of sectors per track 1-255. Number of heads 1-16 */
2391         if (sectors < 1 || sectors > 255 || heads < 1 || heads > 16)
2392                 return;
2393
2394         /* set up init dev params taskfile */
2395         DPRINTK("init dev params \n");
2396
2397         qc = ata_qc_new_init(ap, dev);
2398         BUG_ON(qc == NULL);
2399
2400         qc->tf.command = ATA_CMD_INIT_DEV_PARAMS;
2401         qc->tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
2402         qc->tf.protocol = ATA_PROT_NODATA;
2403         qc->tf.nsect = sectors;
2404         qc->tf.device |= (heads - 1) & 0x0f; /* max head = num. of heads - 1 */
2405
2406         qc->waiting = &wait;
2407         qc->complete_fn = ata_qc_complete_noop;
2408
2409         spin_lock_irqsave(&ap->host_set->lock, flags);
2410         rc = ata_qc_issue(qc);
2411         spin_unlock_irqrestore(&ap->host_set->lock, flags);
2412
2413         if (rc)
2414                 ata_port_disable(ap);
2415         else
2416                 wait_for_completion(&wait);
2417
2418         DPRINTK("EXIT\n");
2419 }
2420
2421 /**
2422  *      ata_sg_clean - Unmap DMA memory associated with command
2423  *      @qc: Command containing DMA memory to be released
2424  *
2425  *      Unmap all mapped DMA memory associated with this command.
2426  *
2427  *      LOCKING:
2428  *      spin_lock_irqsave(host_set lock)
2429  */
2430
2431 static void ata_sg_clean(struct ata_queued_cmd *qc)
2432 {
2433         struct ata_port *ap = qc->ap;
2434         struct scatterlist *sg = qc->sg;
2435         int dir = qc->dma_dir;
2436
2437         assert(qc->flags & ATA_QCFLAG_DMAMAP);
2438         assert(sg != NULL);
2439
2440         if (qc->flags & ATA_QCFLAG_SINGLE)
2441                 assert(qc->n_elem == 1);
2442
2443         DPRINTK("unmapping %u sg elements\n", qc->n_elem);
2444
2445         if (qc->flags & ATA_QCFLAG_SG)
2446                 dma_unmap_sg(ap->host_set->dev, sg, qc->n_elem, dir);
2447         else
2448                 dma_unmap_single(ap->host_set->dev, sg_dma_address(&sg[0]),
2449                                  sg_dma_len(&sg[0]), dir);
2450
2451         qc->flags &= ~ATA_QCFLAG_DMAMAP;
2452         qc->sg = NULL;
2453 }
2454
2455 /**
2456  *      ata_fill_sg - Fill PCI IDE PRD table
2457  *      @qc: Metadata associated with taskfile to be transferred
2458  *
2459  *      Fill PCI IDE PRD (scatter-gather) table with segments
2460  *      associated with the current disk command.
2461  *
2462  *      LOCKING:
2463  *      spin_lock_irqsave(host_set lock)
2464  *
2465  */
2466 static void ata_fill_sg(struct ata_queued_cmd *qc)
2467 {
2468         struct scatterlist *sg = qc->sg;
2469         struct ata_port *ap = qc->ap;
2470         unsigned int idx, nelem;
2471
2472         assert(sg != NULL);
2473         assert(qc->n_elem > 0);
2474
2475         idx = 0;
2476         for (nelem = qc->n_elem; nelem; nelem--,sg++) {
2477                 u32 addr, offset;
2478                 u32 sg_len, len;
2479
2480                 /* determine if physical DMA addr spans 64K boundary.
2481                  * Note h/w doesn't support 64-bit, so we unconditionally
2482                  * truncate dma_addr_t to u32.
2483                  */
2484                 addr = (u32) sg_dma_address(sg);
2485                 sg_len = sg_dma_len(sg);
2486
2487                 while (sg_len) {
2488                         offset = addr & 0xffff;
2489                         len = sg_len;
2490                         if ((offset + sg_len) > 0x10000)
2491                                 len = 0x10000 - offset;
2492
2493                         ap->prd[idx].addr = cpu_to_le32(addr);
2494                         ap->prd[idx].flags_len = cpu_to_le32(len & 0xffff);
2495                         VPRINTK("PRD[%u] = (0x%X, 0x%X)\n", idx, addr, len);
2496
2497                         idx++;
2498                         sg_len -= len;
2499                         addr += len;
2500                 }
2501         }
2502
2503         if (idx)
2504                 ap->prd[idx - 1].flags_len |= cpu_to_le32(ATA_PRD_EOT);
2505 }
2506 /**
2507  *      ata_check_atapi_dma - Check whether ATAPI DMA can be supported
2508  *      @qc: Metadata associated with taskfile to check
2509  *
2510  *      Allow low-level driver to filter ATA PACKET commands, returning
2511  *      a status indicating whether or not it is OK to use DMA for the
2512  *      supplied PACKET command.
2513  *
2514  *      LOCKING:
2515  *      spin_lock_irqsave(host_set lock)
2516  *
2517  *      RETURNS: 0 when ATAPI DMA can be used
2518  *               nonzero otherwise
2519  */
2520 int ata_check_atapi_dma(struct ata_queued_cmd *qc)
2521 {
2522         struct ata_port *ap = qc->ap;
2523         int rc = 0; /* Assume ATAPI DMA is OK by default */
2524
2525         if (ap->ops->check_atapi_dma)
2526                 rc = ap->ops->check_atapi_dma(qc);
2527
2528         return rc;
2529 }
2530 /**
2531  *      ata_qc_prep - Prepare taskfile for submission
2532  *      @qc: Metadata associated with taskfile to be prepared
2533  *
2534  *      Prepare ATA taskfile for submission.
2535  *
2536  *      LOCKING:
2537  *      spin_lock_irqsave(host_set lock)
2538  */
2539 void ata_qc_prep(struct ata_queued_cmd *qc)
2540 {
2541         if (!(qc->flags & ATA_QCFLAG_DMAMAP))
2542                 return;
2543
2544         ata_fill_sg(qc);
2545 }
2546
2547 /**
2548  *      ata_sg_init_one - Associate command with memory buffer
2549  *      @qc: Command to be associated
2550  *      @buf: Memory buffer
2551  *      @buflen: Length of memory buffer, in bytes.
2552  *
2553  *      Initialize the data-related elements of queued_cmd @qc
2554  *      to point to a single memory buffer, @buf of byte length @buflen.
2555  *
2556  *      LOCKING:
2557  *      spin_lock_irqsave(host_set lock)
2558  */
2559
2560 void ata_sg_init_one(struct ata_queued_cmd *qc, void *buf, unsigned int buflen)
2561 {
2562         qc->flags |= ATA_QCFLAG_SINGLE;
2563
2564         qc->sg = &qc->sgent;
2565         qc->n_elem = 1;
2566         qc->buf_virt = buf;
2567         sg_init_one(qc->sg, buf, buflen);
2568 }
2569
2570 /**
2571  *      ata_sg_init - Associate command with scatter-gather table.
2572  *      @qc: Command to be associated
2573  *      @sg: Scatter-gather table.
2574  *      @n_elem: Number of elements in s/g table.
2575  *
2576  *      Initialize the data-related elements of queued_cmd @qc
2577  *      to point to a scatter-gather table @sg, containing @n_elem
2578  *      elements.
2579  *
2580  *      LOCKING:
2581  *      spin_lock_irqsave(host_set lock)
2582  */
2583
2584 void ata_sg_init(struct ata_queued_cmd *qc, struct scatterlist *sg,
2585                  unsigned int n_elem)
2586 {
2587         qc->flags |= ATA_QCFLAG_SG;
2588         qc->sg = sg;
2589         qc->n_elem = n_elem;
2590 }
2591
2592 /**
2593  *      ata_sg_setup_one - DMA-map the memory buffer associated with a command.
2594  *      @qc: Command with memory buffer to be mapped.
2595  *
2596  *      DMA-map the memory buffer associated with queued_cmd @qc.
2597  *
2598  *      LOCKING:
2599  *      spin_lock_irqsave(host_set lock)
2600  *
2601  *      RETURNS:
2602  *      Zero on success, negative on error.
2603  */
2604
2605 static int ata_sg_setup_one(struct ata_queued_cmd *qc)
2606 {
2607         struct ata_port *ap = qc->ap;
2608         int dir = qc->dma_dir;
2609         struct scatterlist *sg = qc->sg;
2610         dma_addr_t dma_address;
2611
2612         dma_address = dma_map_single(ap->host_set->dev, qc->buf_virt,
2613                                      sg->length, dir);
2614         if (dma_mapping_error(dma_address))
2615                 return -1;
2616
2617         sg_dma_address(sg) = dma_address;
2618         sg_dma_len(sg) = sg->length;
2619
2620         DPRINTK("mapped buffer of %d bytes for %s\n", sg_dma_len(sg),
2621                 qc->tf.flags & ATA_TFLAG_WRITE ? "write" : "read");
2622
2623         return 0;
2624 }
2625
2626 /**
2627  *      ata_sg_setup - DMA-map the scatter-gather table associated with a command.
2628  *      @qc: Command with scatter-gather table to be mapped.
2629  *
2630  *      DMA-map the scatter-gather table associated with queued_cmd @qc.
2631  *
2632  *      LOCKING:
2633  *      spin_lock_irqsave(host_set lock)
2634  *
2635  *      RETURNS:
2636  *      Zero on success, negative on error.
2637  *
2638  */
2639
2640 static int ata_sg_setup(struct ata_queued_cmd *qc)
2641 {
2642         struct ata_port *ap = qc->ap;
2643         struct scatterlist *sg = qc->sg;
2644         int n_elem, dir;
2645
2646         VPRINTK("ENTER, ata%u\n", ap->id);
2647         assert(qc->flags & ATA_QCFLAG_SG);
2648
2649         dir = qc->dma_dir;
2650         n_elem = dma_map_sg(ap->host_set->dev, sg, qc->n_elem, dir);
2651         if (n_elem < 1)
2652                 return -1;
2653
2654         DPRINTK("%d sg elements mapped\n", n_elem);
2655
2656         qc->n_elem = n_elem;
2657
2658         return 0;
2659 }
2660
2661 /**
2662  *      ata_poll_qc_complete - turn irq back on and finish qc
2663  *      @qc: Command to complete
2664  *      @drv_stat: ATA status register content
2665  *
2666  *      LOCKING:
2667  *      None.  (grabs host lock)
2668  */
2669
2670 void ata_poll_qc_complete(struct ata_queued_cmd *qc, u8 drv_stat)
2671 {
2672         struct ata_port *ap = qc->ap;
2673         unsigned long flags;
2674
2675         spin_lock_irqsave(&ap->host_set->lock, flags);
2676         ata_irq_on(ap);
2677         ata_qc_complete(qc, drv_stat);
2678         spin_unlock_irqrestore(&ap->host_set->lock, flags);
2679 }
2680
2681 /**
2682  *      ata_pio_poll -
2683  *      @ap: the target ata_port
2684  *
2685  *      LOCKING:
2686  *      None.  (executing in kernel thread context)
2687  *
2688  *      RETURNS:
2689  *      timeout value to use
2690  */
2691
2692 static unsigned long ata_pio_poll(struct ata_port *ap)
2693 {
2694         u8 status;
2695         unsigned int poll_state = HSM_ST_UNKNOWN;
2696         unsigned int reg_state = HSM_ST_UNKNOWN;
2697         const unsigned int tmout_state = HSM_ST_TMOUT;
2698
2699         switch (ap->hsm_task_state) {
2700         case HSM_ST:
2701         case HSM_ST_POLL:
2702                 poll_state = HSM_ST_POLL;
2703                 reg_state = HSM_ST;
2704                 break;
2705         case HSM_ST_LAST:
2706         case HSM_ST_LAST_POLL:
2707                 poll_state = HSM_ST_LAST_POLL;
2708                 reg_state = HSM_ST_LAST;
2709                 break;
2710         default:
2711                 BUG();
2712                 break;
2713         }
2714
2715         status = ata_chk_status(ap);
2716         if (status & ATA_BUSY) {
2717                 if (time_after(jiffies, ap->pio_task_timeout)) {
2718                         ap->hsm_task_state = tmout_state;
2719                         return 0;
2720                 }
2721                 ap->hsm_task_state = poll_state;
2722                 return ATA_SHORT_PAUSE;
2723         }
2724
2725         ap->hsm_task_state = reg_state;
2726         return 0;
2727 }
2728
2729 /**
2730  *      ata_pio_complete - check if drive is busy or idle
2731  *      @ap: the target ata_port
2732  *
2733  *      LOCKING:
2734  *      None.  (executing in kernel thread context)
2735  *
2736  *      RETURNS:
2737  *      Non-zero if qc completed, zero otherwise.
2738  */
2739
2740 static int ata_pio_complete (struct ata_port *ap)
2741 {
2742         struct ata_queued_cmd *qc;
2743         u8 drv_stat;
2744
2745         /*
2746          * This is purely heuristic.  This is a fast path.  Sometimes when
2747          * we enter, BSY will be cleared in a chk-status or two.  If not,
2748          * the drive is probably seeking or something.  Snooze for a couple
2749          * msecs, then chk-status again.  If still busy, fall back to
2750          * HSM_ST_POLL state.
2751          */
2752         drv_stat = ata_busy_wait(ap, ATA_BUSY | ATA_DRQ, 10);
2753         if (drv_stat & (ATA_BUSY | ATA_DRQ)) {
2754                 msleep(2);
2755                 drv_stat = ata_busy_wait(ap, ATA_BUSY | ATA_DRQ, 10);
2756                 if (drv_stat & (ATA_BUSY | ATA_DRQ)) {
2757                         ap->hsm_task_state = HSM_ST_LAST_POLL;
2758                         ap->pio_task_timeout = jiffies + ATA_TMOUT_PIO;
2759                         return 0;
2760                 }
2761         }
2762
2763         drv_stat = ata_wait_idle(ap);
2764         if (!ata_ok(drv_stat)) {
2765                 ap->hsm_task_state = HSM_ST_ERR;
2766                 return 0;
2767         }
2768
2769         qc = ata_qc_from_tag(ap, ap->active_tag);
2770         assert(qc != NULL);
2771
2772         ap->hsm_task_state = HSM_ST_IDLE;
2773
2774         ata_poll_qc_complete(qc, drv_stat);
2775
2776         /* another command may start at this point */
2777
2778         return 1;
2779 }
2780
2781
2782 /**
2783  *      swap_buf_le16 - swap halves of 16-words in place
2784  *      @buf:  Buffer to swap
2785  *      @buf_words:  Number of 16-bit words in buffer.
2786  *
2787  *      Swap halves of 16-bit words if needed to convert from
2788  *      little-endian byte order to native cpu byte order, or
2789  *      vice-versa.
2790  *
2791  *      LOCKING:
2792  *      Inherited from caller.
2793  */
2794 void swap_buf_le16(u16 *buf, unsigned int buf_words)
2795 {
2796 #ifdef __BIG_ENDIAN
2797         unsigned int i;
2798
2799         for (i = 0; i < buf_words; i++)
2800                 buf[i] = le16_to_cpu(buf[i]);
2801 #endif /* __BIG_ENDIAN */
2802 }
2803
2804 /**
2805  *      ata_mmio_data_xfer - Transfer data by MMIO
2806  *      @ap: port to read/write
2807  *      @buf: data buffer
2808  *      @buflen: buffer length
2809  *      @write_data: read/write
2810  *
2811  *      Transfer data from/to the device data register by MMIO.
2812  *
2813  *      LOCKING:
2814  *      Inherited from caller.
2815  */
2816
2817 static void ata_mmio_data_xfer(struct ata_port *ap, unsigned char *buf,
2818                                unsigned int buflen, int write_data)
2819 {
2820         unsigned int i;
2821         unsigned int words = buflen >> 1;
2822         u16 *buf16 = (u16 *) buf;
2823         void __iomem *mmio = (void __iomem *)ap->ioaddr.data_addr;
2824
2825         /* Transfer multiple of 2 bytes */
2826         if (write_data) {
2827                 for (i = 0; i < words; i++)
2828                         writew(le16_to_cpu(buf16[i]), mmio);
2829         } else {
2830                 for (i = 0; i < words; i++)
2831                         buf16[i] = cpu_to_le16(readw(mmio));
2832         }
2833
2834         /* Transfer trailing 1 byte, if any. */
2835         if (unlikely(buflen & 0x01)) {
2836                 u16 align_buf[1] = { 0 };
2837                 unsigned char *trailing_buf = buf + buflen - 1;
2838
2839                 if (write_data) {
2840                         memcpy(align_buf, trailing_buf, 1);
2841                         writew(le16_to_cpu(align_buf[0]), mmio);
2842                 } else {
2843                         align_buf[0] = cpu_to_le16(readw(mmio));
2844                         memcpy(trailing_buf, align_buf, 1);
2845                 }
2846         }
2847 }
2848
2849 /**
2850  *      ata_pio_data_xfer - Transfer data by PIO
2851  *      @ap: port to read/write
2852  *      @buf: data buffer
2853  *      @buflen: buffer length
2854  *      @write_data: read/write
2855  *
2856  *      Transfer data from/to the device data register by PIO.
2857  *
2858  *      LOCKING:
2859  *      Inherited from caller.
2860  */
2861
2862 static void ata_pio_data_xfer(struct ata_port *ap, unsigned char *buf,
2863                               unsigned int buflen, int write_data)
2864 {
2865         unsigned int words = buflen >> 1;
2866
2867         /* Transfer multiple of 2 bytes */
2868         if (write_data)
2869                 outsw(ap->ioaddr.data_addr, buf, words);
2870         else
2871                 insw(ap->ioaddr.data_addr, buf, words);
2872
2873         /* Transfer trailing 1 byte, if any. */
2874         if (unlikely(buflen & 0x01)) {
2875                 u16 align_buf[1] = { 0 };
2876                 unsigned char *trailing_buf = buf + buflen - 1;
2877
2878                 if (write_data) {
2879                         memcpy(align_buf, trailing_buf, 1);
2880                         outw(le16_to_cpu(align_buf[0]), ap->ioaddr.data_addr);
2881                 } else {
2882                         align_buf[0] = cpu_to_le16(inw(ap->ioaddr.data_addr));
2883                         memcpy(trailing_buf, align_buf, 1);
2884                 }
2885         }
2886 }
2887
2888 /**
2889  *      ata_data_xfer - Transfer data from/to the data register.
2890  *      @ap: port to read/write
2891  *      @buf: data buffer
2892  *      @buflen: buffer length
2893  *      @do_write: read/write
2894  *
2895  *      Transfer data from/to the device data register.
2896  *
2897  *      LOCKING:
2898  *      Inherited from caller.
2899  */
2900
2901 static void ata_data_xfer(struct ata_port *ap, unsigned char *buf,
2902                           unsigned int buflen, int do_write)
2903 {
2904         if (ap->flags & ATA_FLAG_MMIO)
2905                 ata_mmio_data_xfer(ap, buf, buflen, do_write);
2906         else
2907                 ata_pio_data_xfer(ap, buf, buflen, do_write);
2908 }
2909
2910 /**
2911  *      ata_pio_sector - Transfer ATA_SECT_SIZE (512 bytes) of data.
2912  *      @qc: Command on going
2913  *
2914  *      Transfer ATA_SECT_SIZE of data from/to the ATA device.
2915  *
2916  *      LOCKING:
2917  *      Inherited from caller.
2918  */
2919
2920 static void ata_pio_sector(struct ata_queued_cmd *qc)
2921 {
2922         int do_write = (qc->tf.flags & ATA_TFLAG_WRITE);
2923         struct scatterlist *sg = qc->sg;
2924         struct ata_port *ap = qc->ap;
2925         struct page *page;
2926         unsigned int offset;
2927         unsigned char *buf;
2928
2929         if (qc->cursect == (qc->nsect - 1))
2930                 ap->hsm_task_state = HSM_ST_LAST;
2931
2932         page = sg[qc->cursg].page;
2933         offset = sg[qc->cursg].offset + qc->cursg_ofs * ATA_SECT_SIZE;
2934
2935         /* get the current page and offset */
2936         page = nth_page(page, (offset >> PAGE_SHIFT));
2937         offset %= PAGE_SIZE;
2938
2939         DPRINTK("data %s\n", qc->tf.flags & ATA_TFLAG_WRITE ? "write" : "read");
2940
2941         if (PageHighMem(page)) {
2942                 unsigned long flags;
2943
2944                 local_irq_save(flags);
2945                 buf = kmap_atomic(page, KM_IRQ0);
2946
2947                 /* do the actual data transfer */
2948                 ata_data_xfer(ap, buf + offset, ATA_SECT_SIZE, do_write);
2949
2950                 kunmap_atomic(buf, KM_IRQ0);
2951                 local_irq_restore(flags);
2952         } else {
2953                 buf = page_address(page);
2954                 ata_data_xfer(ap, buf + offset, ATA_SECT_SIZE, do_write);
2955         }
2956
2957         qc->cursect++;
2958         qc->cursg_ofs++;
2959
2960         if ((qc->cursg_ofs * ATA_SECT_SIZE) == (&sg[qc->cursg])->length) {
2961                 qc->cursg++;
2962                 qc->cursg_ofs = 0;
2963         }
2964 }
2965
2966 /**
2967  *      atapi_send_cdb - Write CDB bytes to hardware
2968  *      @ap: Port to which ATAPI device is attached.
2969  *      @qc: Taskfile currently active
2970  *
2971  *      When device has indicated its readiness to accept
2972  *      a CDB, this function is called.  Send the CDB.
2973  *
2974  *      LOCKING:
2975  *      caller.
2976  */
2977
2978 static void atapi_send_cdb(struct ata_port *ap, struct ata_queued_cmd *qc)
2979 {
2980         /* send SCSI cdb */
2981         DPRINTK("send cdb\n");
2982         assert(ap->cdb_len >= 12);
2983
2984         ata_data_xfer(ap, qc->cdb, ap->cdb_len, 1);
2985         ata_altstatus(ap); /* flush */
2986
2987         switch (qc->tf.protocol) {
2988         case ATA_PROT_ATAPI:
2989                 ap->hsm_task_state = HSM_ST;
2990                 break;
2991         case ATA_PROT_ATAPI_NODATA:
2992                 ap->hsm_task_state = HSM_ST_LAST;
2993                 break;
2994         case ATA_PROT_ATAPI_DMA:
2995                 ap->hsm_task_state = HSM_ST_LAST;
2996                 /* initiate bmdma */
2997                 ap->ops->bmdma_start(qc);
2998                 break;
2999         }
3000 }
3001
3002 /**
3003  *      ata_dataout_task - Write first data block to hardware
3004  *      @_data: Port to which ATA/ATAPI device is attached.
3005  *
3006  *      When device has indicated its readiness to accept
3007  *      the data, this function sends out the CDB or 
3008  *      the first data block by PIO.
3009  *      After this, 
3010  *        - If polling, ata_pio_task() handles the rest.
3011  *        - Otherwise, interrupt handler takes over.
3012  *
3013  *      LOCKING:
3014  *      Kernel thread context (may sleep)
3015  */
3016
3017 static void ata_dataout_task(void *_data)
3018 {
3019         struct ata_port *ap = _data;
3020         struct ata_queued_cmd *qc;
3021         u8 status;
3022         unsigned long flags;
3023
3024         qc = ata_qc_from_tag(ap, ap->active_tag);
3025         assert(qc != NULL);
3026         assert(qc->flags & ATA_QCFLAG_ACTIVE);
3027
3028         /* sleep-wait for BSY to clear */
3029         DPRINTK("busy wait\n");
3030         if (ata_busy_sleep(ap, ATA_TMOUT_DATAOUT_QUICK, ATA_TMOUT_DATAOUT))
3031                 goto err_out;
3032
3033         /* make sure DRQ is set */
3034         status = ata_chk_status(ap);
3035         if ((status & (ATA_BUSY | ATA_DRQ)) != ATA_DRQ)
3036                 goto err_out;
3037
3038         /* Send the CDB (atapi) or the first data block (ata pio out).
3039          * During the state transition, interrupt handler shouldn't
3040          * be invoked before the data transfer is complete and
3041          * hsm_task_state is changed. Hence, the following locking.
3042          */
3043         spin_lock_irqsave(&ap->host_set->lock, flags);
3044
3045         if (qc->tf.protocol == ATA_PROT_PIO) {
3046                 /* PIO data out protocol.
3047                  * send first data block.
3048                  */
3049
3050                 /* ata_pio_sector() might change the state to HSM_ST_LAST.
3051                  * so, the state is changed here before ata_pio_sector().
3052                  */
3053                 ap->hsm_task_state = HSM_ST;
3054                 ata_pio_sector(qc);
3055                 ata_altstatus(ap); /* flush */
3056         } else
3057                 /* send CDB */
3058                 atapi_send_cdb(ap, qc);
3059
3060         /* if polling, ata_pio_task() handles the rest.
3061          * otherwise, interrupt handler takes over from here.
3062          */
3063         if (qc->tf.flags & ATA_TFLAG_POLLING)
3064                 queue_work(ata_wq, &ap->pio_task);
3065
3066         spin_unlock_irqrestore(&ap->host_set->lock, flags);
3067
3068         return;
3069
3070 err_out:
3071         ata_pio_error(ap);
3072 }
3073
3074 /**
3075  *      __atapi_pio_bytes - Transfer data from/to the ATAPI device.
3076  *      @qc: Command on going
3077  *      @bytes: number of bytes
3078  *
3079  *      Transfer Transfer data from/to the ATAPI device.
3080  *
3081  *      LOCKING:
3082  *      Inherited from caller.
3083  *
3084  */
3085
3086 static void __atapi_pio_bytes(struct ata_queued_cmd *qc, unsigned int bytes)
3087 {
3088         int do_write = (qc->tf.flags & ATA_TFLAG_WRITE);
3089         struct scatterlist *sg = qc->sg;
3090         struct ata_port *ap = qc->ap;
3091         struct page *page;
3092         unsigned char *buf;
3093         unsigned int offset, count;
3094
3095         if (qc->curbytes + bytes >= qc->nbytes)
3096                 ap->hsm_task_state = HSM_ST_LAST;
3097
3098 next_sg:
3099         if (unlikely(qc->cursg >= qc->n_elem)) {
3100                 /*
3101                  * The end of qc->sg is reached and the device expects
3102                  * more data to transfer. In order not to overrun qc->sg
3103                  * and fulfill length specified in the byte count register,
3104                  *    - for read case, discard trailing data from the device
3105                  *    - for write case, padding zero data to the device
3106                  */
3107                 u16 pad_buf[1] = { 0 };
3108                 unsigned int words = bytes >> 1;
3109                 unsigned int i;
3110
3111                 if (words) /* warning if bytes > 1 */
3112                         printk(KERN_WARNING "ata%u: %u bytes trailing data\n",
3113                                ap->id, bytes);
3114
3115                 for (i = 0; i < words; i++)
3116                         ata_data_xfer(ap, (unsigned char*)pad_buf, 2, do_write);
3117
3118                 ap->hsm_task_state = HSM_ST_LAST;
3119                 return;
3120         }
3121
3122         sg = &qc->sg[qc->cursg];
3123
3124         page = sg->page;
3125         offset = sg->offset + qc->cursg_ofs;
3126
3127         /* get the current page and offset */
3128         page = nth_page(page, (offset >> PAGE_SHIFT));
3129         offset %= PAGE_SIZE;
3130
3131         /* don't overrun current sg */
3132         count = min(sg->length - qc->cursg_ofs, bytes);
3133
3134         /* don't cross page boundaries */
3135         count = min(count, (unsigned int)PAGE_SIZE - offset);
3136
3137         DPRINTK("data %s\n", qc->tf.flags & ATA_TFLAG_WRITE ? "write" : "read");
3138
3139         if (PageHighMem(page)) {
3140                 unsigned long flags;
3141
3142                 local_irq_save(flags);
3143                 buf = kmap_atomic(page, KM_IRQ0);
3144
3145                 /* do the actual data transfer */
3146                 ata_data_xfer(ap, buf + offset, count, do_write);
3147
3148                 kunmap_atomic(buf, KM_IRQ0);
3149                 local_irq_restore(flags);
3150         } else {
3151                 buf = page_address(page);
3152                 ata_data_xfer(ap, buf + offset, count, do_write);
3153         }
3154
3155         bytes -= count;
3156         qc->curbytes += count;
3157         qc->cursg_ofs += count;
3158
3159         if (qc->cursg_ofs == sg->length) {
3160                 qc->cursg++;
3161                 qc->cursg_ofs = 0;
3162         }
3163
3164         if (bytes)
3165                 goto next_sg;
3166 }
3167
3168 /**
3169  *      atapi_pio_bytes - Transfer data from/to the ATAPI device.
3170  *      @qc: Command on going
3171  *
3172  *      Transfer Transfer data from/to the ATAPI device.
3173  *
3174  *      LOCKING:
3175  *      Inherited from caller.
3176  */
3177
3178 static void atapi_pio_bytes(struct ata_queued_cmd *qc)
3179 {
3180         struct ata_port *ap = qc->ap;
3181         struct ata_device *dev = qc->dev;
3182         unsigned int ireason, bc_lo, bc_hi, bytes;
3183         int i_write, do_write = (qc->tf.flags & ATA_TFLAG_WRITE) ? 1 : 0;
3184
3185         ap->ops->tf_read(ap, &qc->tf);
3186         ireason = qc->tf.nsect;
3187         bc_lo = qc->tf.lbam;
3188         bc_hi = qc->tf.lbah;
3189         bytes = (bc_hi << 8) | bc_lo;
3190
3191         /* shall be cleared to zero, indicating xfer of data */
3192         if (ireason & (1 << 0))
3193                 goto err_out;
3194
3195         /* make sure transfer direction matches expected */
3196         i_write = ((ireason & (1 << 1)) == 0) ? 1 : 0;
3197         if (do_write != i_write)
3198                 goto err_out;
3199
3200         VPRINTK("ata%u: xfering %d bytes\n", ap->id, bytes);
3201
3202         __atapi_pio_bytes(qc, bytes);
3203
3204         return;
3205
3206 err_out:
3207         printk(KERN_INFO "ata%u: dev %u: ATAPI check failed\n",
3208               ap->id, dev->devno);
3209         ap->hsm_task_state = HSM_ST_ERR;
3210 }
3211
3212 /**
3213  *      ata_pio_block - start PIO on a block
3214  *      @ap: the target ata_port
3215  *
3216  *      LOCKING:
3217  *      None.  (executing in kernel thread context)
3218  */
3219
3220 static void ata_pio_block(struct ata_port *ap)
3221 {
3222         struct ata_queued_cmd *qc;
3223         u8 status;
3224
3225         /*
3226          * This is purely heuristic.  This is a fast path.
3227          * Sometimes when we enter, BSY will be cleared in
3228          * a chk-status or two.  If not, the drive is probably seeking
3229          * or something.  Snooze for a couple msecs, then
3230          * chk-status again.  If still busy, fall back to
3231          * HSM_ST_POLL state.
3232          */
3233         status = ata_busy_wait(ap, ATA_BUSY, 5);
3234         if (status & ATA_BUSY) {
3235                 msleep(2);
3236                 status = ata_busy_wait(ap, ATA_BUSY, 10);
3237                 if (status & ATA_BUSY) {
3238                         ap->hsm_task_state = HSM_ST_POLL;
3239                         ap->pio_task_timeout = jiffies + ATA_TMOUT_PIO;
3240                         return;
3241                 }
3242         }
3243
3244         qc = ata_qc_from_tag(ap, ap->active_tag);
3245         assert(qc != NULL);
3246
3247         if (is_atapi_taskfile(&qc->tf)) {
3248                 /* no more data to transfer or unsupported ATAPI command */
3249                 if ((status & ATA_DRQ) == 0) {
3250                         ap->hsm_task_state = HSM_ST_LAST;
3251                         return;
3252                 }
3253
3254                 atapi_pio_bytes(qc);
3255         } else {
3256                 /* handle BSY=0, DRQ=0 as error */
3257                 if ((status & ATA_DRQ) == 0) {
3258                         ap->hsm_task_state = HSM_ST_ERR;
3259                         return;
3260                 }
3261
3262                 ata_pio_sector(qc);
3263         }
3264 }
3265
3266 static void ata_pio_error(struct ata_port *ap)
3267 {
3268         struct ata_queued_cmd *qc;
3269         u8 drv_stat;
3270
3271         qc = ata_qc_from_tag(ap, ap->active_tag);
3272         assert(qc != NULL);
3273
3274         drv_stat = ata_chk_status(ap);
3275         printk(KERN_WARNING "ata%u: PIO error, drv_stat 0x%x\n",
3276                ap->id, drv_stat);
3277
3278         ap->hsm_task_state = HSM_ST_IDLE;
3279
3280         ata_poll_qc_complete(qc, drv_stat | ATA_ERR);
3281 }
3282
3283 static void ata_pio_task(void *_data)
3284 {
3285         struct ata_port *ap = _data;
3286         unsigned long timeout;
3287         int qc_completed;
3288
3289 fsm_start:
3290         timeout = 0;
3291         qc_completed = 0;
3292
3293         switch (ap->hsm_task_state) {
3294         case HSM_ST_IDLE:
3295                 return;
3296
3297         case HSM_ST:
3298                 ata_pio_block(ap);
3299                 break;
3300
3301         case HSM_ST_LAST:
3302                 qc_completed = ata_pio_complete(ap);
3303                 break;
3304
3305         case HSM_ST_POLL:
3306         case HSM_ST_LAST_POLL:
3307                 timeout = ata_pio_poll(ap);
3308                 break;
3309
3310         case HSM_ST_TMOUT:
3311         case HSM_ST_ERR:
3312                 ata_pio_error(ap);
3313                 return;
3314         }
3315
3316         if (timeout)
3317                 queue_delayed_work(ata_wq, &ap->pio_task, timeout);
3318         else if (!qc_completed)
3319                 goto fsm_start;
3320 }
3321
3322 /**
3323  *      ata_qc_timeout - Handle timeout of queued command
3324  *      @qc: Command that timed out
3325  *
3326  *      Some part of the kernel (currently, only the SCSI layer)
3327  *      has noticed that the active command on port @ap has not
3328  *      completed after a specified length of time.  Handle this
3329  *      condition by disabling DMA (if necessary) and completing
3330  *      transactions, with error if necessary.
3331  *
3332  *      This also handles the case of the "lost interrupt", where
3333  *      for some reason (possibly hardware bug, possibly driver bug)
3334  *      an interrupt was not delivered to the driver, even though the
3335  *      transaction completed successfully.
3336  *
3337  *      LOCKING:
3338  *      Inherited from SCSI layer (none, can sleep)
3339  */
3340
3341 static void ata_qc_timeout(struct ata_queued_cmd *qc)
3342 {
3343         struct ata_port *ap = qc->ap;
3344         struct ata_host_set *host_set = ap->host_set;
3345         struct ata_device *dev = qc->dev;
3346         u8 host_stat = 0, drv_stat;
3347         unsigned long flags;
3348
3349         DPRINTK("ENTER\n");
3350
3351         /* FIXME: doesn't this conflict with timeout handling? */
3352         if (qc->dev->class == ATA_DEV_ATAPI && qc->scsicmd) {
3353                 struct scsi_cmnd *cmd = qc->scsicmd;
3354
3355                 if (!(cmd->eh_eflags & SCSI_EH_CANCEL_CMD)) {
3356
3357                         /* finish completing original command */
3358                         spin_lock_irqsave(&host_set->lock, flags);
3359                         __ata_qc_complete(qc);
3360                         spin_unlock_irqrestore(&host_set->lock, flags);
3361
3362                         atapi_request_sense(ap, dev, cmd);
3363
3364                         cmd->result = (CHECK_CONDITION << 1) | (DID_OK << 16);
3365                         scsi_finish_command(cmd);
3366
3367                         goto out;
3368                 }
3369         }
3370
3371         spin_lock_irqsave(&host_set->lock, flags);
3372
3373         /* hack alert!  We cannot use the supplied completion
3374          * function from inside the ->eh_strategy_handler() thread.
3375          * libata is the only user of ->eh_strategy_handler() in
3376          * any kernel, so the default scsi_done() assumes it is
3377          * not being called from the SCSI EH.
3378          */
3379         qc->scsidone = scsi_finish_command;
3380
3381         switch (qc->tf.protocol) {
3382
3383         case ATA_PROT_DMA:
3384         case ATA_PROT_ATAPI_DMA:
3385                 host_stat = ap->ops->bmdma_status(ap);
3386
3387                 /* before we do anything else, clear DMA-Start bit */
3388                 ap->ops->bmdma_stop(qc);
3389
3390                 /* fall through */
3391
3392         default:
3393                 ata_altstatus(ap);
3394                 drv_stat = ata_chk_status(ap);
3395
3396                 /* ack bmdma irq events */
3397                 ap->ops->irq_clear(ap);
3398
3399                 printk(KERN_ERR "ata%u: command 0x%x timeout, stat 0x%x host_stat 0x%x\n",
3400                        ap->id, qc->tf.command, drv_stat, host_stat);
3401
3402                 ap->hsm_task_state = HSM_ST_IDLE;
3403
3404                 /* complete taskfile transaction */
3405                 ata_qc_complete(qc, drv_stat);
3406                 break;
3407         }
3408
3409         spin_unlock_irqrestore(&host_set->lock, flags);
3410
3411 out:
3412         DPRINTK("EXIT\n");
3413 }
3414
3415 /**
3416  *      ata_eng_timeout - Handle timeout of queued command
3417  *      @ap: Port on which timed-out command is active
3418  *
3419  *      Some part of the kernel (currently, only the SCSI layer)
3420  *      has noticed that the active command on port @ap has not
3421  *      completed after a specified length of time.  Handle this
3422  *      condition by disabling DMA (if necessary) and completing
3423  *      transactions, with error if necessary.
3424  *
3425  *      This also handles the case of the "lost interrupt", where