[PATCH] libata: export ata_busy_sleep
[firefly-linux-kernel-4.4.55.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_priv.h"
55 #include <scsi/scsi_cmnd.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 void ata_dev_reread_id(struct ata_port *ap, struct ata_device *dev);
65 static void ata_dev_init_params(struct ata_port *ap, struct ata_device *dev);
66 static void ata_set_mode(struct ata_port *ap);
67 static void ata_dev_set_xfermode(struct ata_port *ap, struct ata_device *dev);
68 static unsigned int ata_get_mode_mask(const struct ata_port *ap, int shift);
69 static int fgb(u32 bitmap);
70 static int ata_choose_xfer_mode(const struct ata_port *ap,
71                                 u8 *xfer_mode_out,
72                                 unsigned int *xfer_shift_out);
73
74 static unsigned int ata_unique_id = 1;
75 static struct workqueue_struct *ata_wq;
76
77 int atapi_enabled = 0;
78 module_param(atapi_enabled, int, 0444);
79 MODULE_PARM_DESC(atapi_enabled, "Enable discovery of ATAPI devices (0=off, 1=on)");
80
81 MODULE_AUTHOR("Jeff Garzik");
82 MODULE_DESCRIPTION("Library module for ATA devices");
83 MODULE_LICENSE("GPL");
84 MODULE_VERSION(DRV_VERSION);
85
86 /**
87  *      ata_tf_load_pio - send taskfile registers to host controller
88  *      @ap: Port to which output is sent
89  *      @tf: ATA taskfile register set
90  *
91  *      Outputs ATA taskfile to standard ATA host controller.
92  *
93  *      LOCKING:
94  *      Inherited from caller.
95  */
96
97 static void ata_tf_load_pio(struct ata_port *ap, const struct ata_taskfile *tf)
98 {
99         struct ata_ioports *ioaddr = &ap->ioaddr;
100         unsigned int is_addr = tf->flags & ATA_TFLAG_ISADDR;
101
102         if (tf->ctl != ap->last_ctl) {
103                 outb(tf->ctl, ioaddr->ctl_addr);
104                 ap->last_ctl = tf->ctl;
105                 ata_wait_idle(ap);
106         }
107
108         if (is_addr && (tf->flags & ATA_TFLAG_LBA48)) {
109                 outb(tf->hob_feature, ioaddr->feature_addr);
110                 outb(tf->hob_nsect, ioaddr->nsect_addr);
111                 outb(tf->hob_lbal, ioaddr->lbal_addr);
112                 outb(tf->hob_lbam, ioaddr->lbam_addr);
113                 outb(tf->hob_lbah, ioaddr->lbah_addr);
114                 VPRINTK("hob: feat 0x%X nsect 0x%X, lba 0x%X 0x%X 0x%X\n",
115                         tf->hob_feature,
116                         tf->hob_nsect,
117                         tf->hob_lbal,
118                         tf->hob_lbam,
119                         tf->hob_lbah);
120         }
121
122         if (is_addr) {
123                 outb(tf->feature, ioaddr->feature_addr);
124                 outb(tf->nsect, ioaddr->nsect_addr);
125                 outb(tf->lbal, ioaddr->lbal_addr);
126                 outb(tf->lbam, ioaddr->lbam_addr);
127                 outb(tf->lbah, ioaddr->lbah_addr);
128                 VPRINTK("feat 0x%X nsect 0x%X lba 0x%X 0x%X 0x%X\n",
129                         tf->feature,
130                         tf->nsect,
131                         tf->lbal,
132                         tf->lbam,
133                         tf->lbah);
134         }
135
136         if (tf->flags & ATA_TFLAG_DEVICE) {
137                 outb(tf->device, ioaddr->device_addr);
138                 VPRINTK("device 0x%X\n", tf->device);
139         }
140
141         ata_wait_idle(ap);
142 }
143
144 /**
145  *      ata_tf_load_mmio - send taskfile registers to host controller
146  *      @ap: Port to which output is sent
147  *      @tf: ATA taskfile register set
148  *
149  *      Outputs ATA taskfile to standard ATA host controller using MMIO.
150  *
151  *      LOCKING:
152  *      Inherited from caller.
153  */
154
155 static void ata_tf_load_mmio(struct ata_port *ap, const struct ata_taskfile *tf)
156 {
157         struct ata_ioports *ioaddr = &ap->ioaddr;
158         unsigned int is_addr = tf->flags & ATA_TFLAG_ISADDR;
159
160         if (tf->ctl != ap->last_ctl) {
161                 writeb(tf->ctl, (void __iomem *) ap->ioaddr.ctl_addr);
162                 ap->last_ctl = tf->ctl;
163                 ata_wait_idle(ap);
164         }
165
166         if (is_addr && (tf->flags & ATA_TFLAG_LBA48)) {
167                 writeb(tf->hob_feature, (void __iomem *) ioaddr->feature_addr);
168                 writeb(tf->hob_nsect, (void __iomem *) ioaddr->nsect_addr);
169                 writeb(tf->hob_lbal, (void __iomem *) ioaddr->lbal_addr);
170                 writeb(tf->hob_lbam, (void __iomem *) ioaddr->lbam_addr);
171                 writeb(tf->hob_lbah, (void __iomem *) ioaddr->lbah_addr);
172                 VPRINTK("hob: feat 0x%X nsect 0x%X, lba 0x%X 0x%X 0x%X\n",
173                         tf->hob_feature,
174                         tf->hob_nsect,
175                         tf->hob_lbal,
176                         tf->hob_lbam,
177                         tf->hob_lbah);
178         }
179
180         if (is_addr) {
181                 writeb(tf->feature, (void __iomem *) ioaddr->feature_addr);
182                 writeb(tf->nsect, (void __iomem *) ioaddr->nsect_addr);
183                 writeb(tf->lbal, (void __iomem *) ioaddr->lbal_addr);
184                 writeb(tf->lbam, (void __iomem *) ioaddr->lbam_addr);
185                 writeb(tf->lbah, (void __iomem *) ioaddr->lbah_addr);
186                 VPRINTK("feat 0x%X nsect 0x%X lba 0x%X 0x%X 0x%X\n",
187                         tf->feature,
188                         tf->nsect,
189                         tf->lbal,
190                         tf->lbam,
191                         tf->lbah);
192         }
193
194         if (tf->flags & ATA_TFLAG_DEVICE) {
195                 writeb(tf->device, (void __iomem *) ioaddr->device_addr);
196                 VPRINTK("device 0x%X\n", tf->device);
197         }
198
199         ata_wait_idle(ap);
200 }
201
202
203 /**
204  *      ata_tf_load - send taskfile registers to host controller
205  *      @ap: Port to which output is sent
206  *      @tf: ATA taskfile register set
207  *
208  *      Outputs ATA taskfile to standard ATA host controller using MMIO
209  *      or PIO as indicated by the ATA_FLAG_MMIO flag.
210  *      Writes the control, feature, nsect, lbal, lbam, and lbah registers.
211  *      Optionally (ATA_TFLAG_LBA48) writes hob_feature, hob_nsect,
212  *      hob_lbal, hob_lbam, and hob_lbah.
213  *
214  *      This function waits for idle (!BUSY and !DRQ) after writing
215  *      registers.  If the control register has a new value, this
216  *      function also waits for idle after writing control and before
217  *      writing the remaining registers.
218  *
219  *      May be used as the tf_load() entry in ata_port_operations.
220  *
221  *      LOCKING:
222  *      Inherited from caller.
223  */
224 void ata_tf_load(struct ata_port *ap, const struct ata_taskfile *tf)
225 {
226         if (ap->flags & ATA_FLAG_MMIO)
227                 ata_tf_load_mmio(ap, tf);
228         else
229                 ata_tf_load_pio(ap, tf);
230 }
231
232 /**
233  *      ata_exec_command_pio - issue ATA command to host controller
234  *      @ap: port to which command is being issued
235  *      @tf: ATA taskfile register set
236  *
237  *      Issues PIO write to ATA command register, with proper
238  *      synchronization with interrupt handler / other threads.
239  *
240  *      LOCKING:
241  *      spin_lock_irqsave(host_set lock)
242  */
243
244 static void ata_exec_command_pio(struct ata_port *ap, const struct ata_taskfile *tf)
245 {
246         DPRINTK("ata%u: cmd 0x%X\n", ap->id, tf->command);
247
248         outb(tf->command, ap->ioaddr.command_addr);
249         ata_pause(ap);
250 }
251
252
253 /**
254  *      ata_exec_command_mmio - issue ATA command to host controller
255  *      @ap: port to which command is being issued
256  *      @tf: ATA taskfile register set
257  *
258  *      Issues MMIO write to ATA command register, with proper
259  *      synchronization with interrupt handler / other threads.
260  *
261  *      LOCKING:
262  *      spin_lock_irqsave(host_set lock)
263  */
264
265 static void ata_exec_command_mmio(struct ata_port *ap, const struct ata_taskfile *tf)
266 {
267         DPRINTK("ata%u: cmd 0x%X\n", ap->id, tf->command);
268
269         writeb(tf->command, (void __iomem *) ap->ioaddr.command_addr);
270         ata_pause(ap);
271 }
272
273
274 /**
275  *      ata_exec_command - issue ATA command to host controller
276  *      @ap: port to which command is being issued
277  *      @tf: ATA taskfile register set
278  *
279  *      Issues PIO/MMIO write to ATA command register, with proper
280  *      synchronization with interrupt handler / other threads.
281  *
282  *      LOCKING:
283  *      spin_lock_irqsave(host_set lock)
284  */
285 void ata_exec_command(struct ata_port *ap, const struct ata_taskfile *tf)
286 {
287         if (ap->flags & ATA_FLAG_MMIO)
288                 ata_exec_command_mmio(ap, tf);
289         else
290                 ata_exec_command_pio(ap, tf);
291 }
292
293 /**
294  *      ata_tf_to_host - issue ATA taskfile to host controller
295  *      @ap: port to which command is being issued
296  *      @tf: ATA taskfile register set
297  *
298  *      Issues ATA taskfile register set to ATA host controller,
299  *      with proper synchronization with interrupt handler and
300  *      other threads.
301  *
302  *      LOCKING:
303  *      spin_lock_irqsave(host_set lock)
304  */
305
306 static inline void ata_tf_to_host(struct ata_port *ap,
307                                   const struct ata_taskfile *tf)
308 {
309         ap->ops->tf_load(ap, tf);
310         ap->ops->exec_command(ap, tf);
311 }
312
313 /**
314  *      ata_tf_read_pio - input device's ATA taskfile shadow registers
315  *      @ap: Port from which input is read
316  *      @tf: ATA taskfile register set for storing input
317  *
318  *      Reads ATA taskfile registers for currently-selected device
319  *      into @tf.
320  *
321  *      LOCKING:
322  *      Inherited from caller.
323  */
324
325 static void ata_tf_read_pio(struct ata_port *ap, struct ata_taskfile *tf)
326 {
327         struct ata_ioports *ioaddr = &ap->ioaddr;
328
329         tf->command = ata_check_status(ap);
330         tf->feature = inb(ioaddr->error_addr);
331         tf->nsect = inb(ioaddr->nsect_addr);
332         tf->lbal = inb(ioaddr->lbal_addr);
333         tf->lbam = inb(ioaddr->lbam_addr);
334         tf->lbah = inb(ioaddr->lbah_addr);
335         tf->device = inb(ioaddr->device_addr);
336
337         if (tf->flags & ATA_TFLAG_LBA48) {
338                 outb(tf->ctl | ATA_HOB, ioaddr->ctl_addr);
339                 tf->hob_feature = inb(ioaddr->error_addr);
340                 tf->hob_nsect = inb(ioaddr->nsect_addr);
341                 tf->hob_lbal = inb(ioaddr->lbal_addr);
342                 tf->hob_lbam = inb(ioaddr->lbam_addr);
343                 tf->hob_lbah = inb(ioaddr->lbah_addr);
344         }
345 }
346
347 /**
348  *      ata_tf_read_mmio - input device's ATA taskfile shadow registers
349  *      @ap: Port from which input is read
350  *      @tf: ATA taskfile register set for storing input
351  *
352  *      Reads ATA taskfile registers for currently-selected device
353  *      into @tf via MMIO.
354  *
355  *      LOCKING:
356  *      Inherited from caller.
357  */
358
359 static void ata_tf_read_mmio(struct ata_port *ap, struct ata_taskfile *tf)
360 {
361         struct ata_ioports *ioaddr = &ap->ioaddr;
362
363         tf->command = ata_check_status(ap);
364         tf->feature = readb((void __iomem *)ioaddr->error_addr);
365         tf->nsect = readb((void __iomem *)ioaddr->nsect_addr);
366         tf->lbal = readb((void __iomem *)ioaddr->lbal_addr);
367         tf->lbam = readb((void __iomem *)ioaddr->lbam_addr);
368         tf->lbah = readb((void __iomem *)ioaddr->lbah_addr);
369         tf->device = readb((void __iomem *)ioaddr->device_addr);
370
371         if (tf->flags & ATA_TFLAG_LBA48) {
372                 writeb(tf->ctl | ATA_HOB, (void __iomem *) ap->ioaddr.ctl_addr);
373                 tf->hob_feature = readb((void __iomem *)ioaddr->error_addr);
374                 tf->hob_nsect = readb((void __iomem *)ioaddr->nsect_addr);
375                 tf->hob_lbal = readb((void __iomem *)ioaddr->lbal_addr);
376                 tf->hob_lbam = readb((void __iomem *)ioaddr->lbam_addr);
377                 tf->hob_lbah = readb((void __iomem *)ioaddr->lbah_addr);
378         }
379 }
380
381
382 /**
383  *      ata_tf_read - input device's ATA taskfile shadow registers
384  *      @ap: Port from which input is read
385  *      @tf: ATA taskfile register set for storing input
386  *
387  *      Reads ATA taskfile registers for currently-selected device
388  *      into @tf.
389  *
390  *      Reads nsect, lbal, lbam, lbah, and device.  If ATA_TFLAG_LBA48
391  *      is set, also reads the hob registers.
392  *
393  *      May be used as the tf_read() entry in ata_port_operations.
394  *
395  *      LOCKING:
396  *      Inherited from caller.
397  */
398 void ata_tf_read(struct ata_port *ap, struct ata_taskfile *tf)
399 {
400         if (ap->flags & ATA_FLAG_MMIO)
401                 ata_tf_read_mmio(ap, tf);
402         else
403                 ata_tf_read_pio(ap, tf);
404 }
405
406 /**
407  *      ata_check_status_pio - Read device status reg & clear interrupt
408  *      @ap: port where the device is
409  *
410  *      Reads ATA taskfile status register for currently-selected device
411  *      and return its value. This also clears pending interrupts
412  *      from this device
413  *
414  *      LOCKING:
415  *      Inherited from caller.
416  */
417 static u8 ata_check_status_pio(struct ata_port *ap)
418 {
419         return inb(ap->ioaddr.status_addr);
420 }
421
422 /**
423  *      ata_check_status_mmio - Read device status reg & clear interrupt
424  *      @ap: port where the device is
425  *
426  *      Reads ATA taskfile status register for currently-selected device
427  *      via MMIO and return its value. This also clears pending interrupts
428  *      from this device
429  *
430  *      LOCKING:
431  *      Inherited from caller.
432  */
433 static u8 ata_check_status_mmio(struct ata_port *ap)
434 {
435         return readb((void __iomem *) ap->ioaddr.status_addr);
436 }
437
438
439 /**
440  *      ata_check_status - Read device status reg & clear interrupt
441  *      @ap: port where the device is
442  *
443  *      Reads ATA taskfile status register for currently-selected device
444  *      and return its value. This also clears pending interrupts
445  *      from this device
446  *
447  *      May be used as the check_status() entry in ata_port_operations.
448  *
449  *      LOCKING:
450  *      Inherited from caller.
451  */
452 u8 ata_check_status(struct ata_port *ap)
453 {
454         if (ap->flags & ATA_FLAG_MMIO)
455                 return ata_check_status_mmio(ap);
456         return ata_check_status_pio(ap);
457 }
458
459
460 /**
461  *      ata_altstatus - Read device alternate status reg
462  *      @ap: port where the device is
463  *
464  *      Reads ATA taskfile alternate status register for
465  *      currently-selected device and return its value.
466  *
467  *      Note: may NOT be used as the check_altstatus() entry in
468  *      ata_port_operations.
469  *
470  *      LOCKING:
471  *      Inherited from caller.
472  */
473 u8 ata_altstatus(struct ata_port *ap)
474 {
475         if (ap->ops->check_altstatus)
476                 return ap->ops->check_altstatus(ap);
477
478         if (ap->flags & ATA_FLAG_MMIO)
479                 return readb((void __iomem *)ap->ioaddr.altstatus_addr);
480         return inb(ap->ioaddr.altstatus_addr);
481 }
482
483
484 /**
485  *      ata_tf_to_fis - Convert ATA taskfile to SATA FIS structure
486  *      @tf: Taskfile to convert
487  *      @fis: Buffer into which data will output
488  *      @pmp: Port multiplier port
489  *
490  *      Converts a standard ATA taskfile to a Serial ATA
491  *      FIS structure (Register - Host to Device).
492  *
493  *      LOCKING:
494  *      Inherited from caller.
495  */
496
497 void ata_tf_to_fis(const struct ata_taskfile *tf, u8 *fis, u8 pmp)
498 {
499         fis[0] = 0x27;  /* Register - Host to Device FIS */
500         fis[1] = (pmp & 0xf) | (1 << 7); /* Port multiplier number,
501                                             bit 7 indicates Command FIS */
502         fis[2] = tf->command;
503         fis[3] = tf->feature;
504
505         fis[4] = tf->lbal;
506         fis[5] = tf->lbam;
507         fis[6] = tf->lbah;
508         fis[7] = tf->device;
509
510         fis[8] = tf->hob_lbal;
511         fis[9] = tf->hob_lbam;
512         fis[10] = tf->hob_lbah;
513         fis[11] = tf->hob_feature;
514
515         fis[12] = tf->nsect;
516         fis[13] = tf->hob_nsect;
517         fis[14] = 0;
518         fis[15] = tf->ctl;
519
520         fis[16] = 0;
521         fis[17] = 0;
522         fis[18] = 0;
523         fis[19] = 0;
524 }
525
526 /**
527  *      ata_tf_from_fis - Convert SATA FIS to ATA taskfile
528  *      @fis: Buffer from which data will be input
529  *      @tf: Taskfile to output
530  *
531  *      Converts a serial ATA FIS structure to a standard ATA taskfile.
532  *
533  *      LOCKING:
534  *      Inherited from caller.
535  */
536
537 void ata_tf_from_fis(const u8 *fis, struct ata_taskfile *tf)
538 {
539         tf->command     = fis[2];       /* status */
540         tf->feature     = fis[3];       /* error */
541
542         tf->lbal        = fis[4];
543         tf->lbam        = fis[5];
544         tf->lbah        = fis[6];
545         tf->device      = fis[7];
546
547         tf->hob_lbal    = fis[8];
548         tf->hob_lbam    = fis[9];
549         tf->hob_lbah    = fis[10];
550
551         tf->nsect       = fis[12];
552         tf->hob_nsect   = fis[13];
553 }
554
555 static const u8 ata_rw_cmds[] = {
556         /* pio multi */
557         ATA_CMD_READ_MULTI,
558         ATA_CMD_WRITE_MULTI,
559         ATA_CMD_READ_MULTI_EXT,
560         ATA_CMD_WRITE_MULTI_EXT,
561         0,
562         0,
563         0,
564         ATA_CMD_WRITE_MULTI_FUA_EXT,
565         /* pio */
566         ATA_CMD_PIO_READ,
567         ATA_CMD_PIO_WRITE,
568         ATA_CMD_PIO_READ_EXT,
569         ATA_CMD_PIO_WRITE_EXT,
570         0,
571         0,
572         0,
573         0,
574         /* dma */
575         ATA_CMD_READ,
576         ATA_CMD_WRITE,
577         ATA_CMD_READ_EXT,
578         ATA_CMD_WRITE_EXT,
579         0,
580         0,
581         0,
582         ATA_CMD_WRITE_FUA_EXT
583 };
584
585 /**
586  *      ata_rwcmd_protocol - set taskfile r/w commands and protocol
587  *      @qc: command to examine and configure
588  *
589  *      Examine the device configuration and tf->flags to calculate 
590  *      the proper read/write commands and protocol to use.
591  *
592  *      LOCKING:
593  *      caller.
594  */
595 int ata_rwcmd_protocol(struct ata_queued_cmd *qc)
596 {
597         struct ata_taskfile *tf = &qc->tf;
598         struct ata_device *dev = qc->dev;
599         u8 cmd;
600
601         int index, fua, lba48, write;
602  
603         fua = (tf->flags & ATA_TFLAG_FUA) ? 4 : 0;
604         lba48 = (tf->flags & ATA_TFLAG_LBA48) ? 2 : 0;
605         write = (tf->flags & ATA_TFLAG_WRITE) ? 1 : 0;
606
607         if (dev->flags & ATA_DFLAG_PIO) {
608                 tf->protocol = ATA_PROT_PIO;
609                 index = dev->multi_count ? 0 : 8;
610         } else if (lba48 && (qc->ap->flags & ATA_FLAG_PIO_LBA48)) {
611                 /* Unable to use DMA due to host limitation */
612                 tf->protocol = ATA_PROT_PIO;
613                 index = dev->multi_count ? 0 : 4;
614         } else {
615                 tf->protocol = ATA_PROT_DMA;
616                 index = 16;
617         }
618
619         cmd = ata_rw_cmds[index + fua + lba48 + write];
620         if (cmd) {
621                 tf->command = cmd;
622                 return 0;
623         }
624         return -1;
625 }
626
627 static const char * const xfer_mode_str[] = {
628         "UDMA/16",
629         "UDMA/25",
630         "UDMA/33",
631         "UDMA/44",
632         "UDMA/66",
633         "UDMA/100",
634         "UDMA/133",
635         "UDMA7",
636         "MWDMA0",
637         "MWDMA1",
638         "MWDMA2",
639         "PIO0",
640         "PIO1",
641         "PIO2",
642         "PIO3",
643         "PIO4",
644 };
645
646 /**
647  *      ata_udma_string - convert UDMA bit offset to string
648  *      @mask: mask of bits supported; only highest bit counts.
649  *
650  *      Determine string which represents the highest speed
651  *      (highest bit in @udma_mask).
652  *
653  *      LOCKING:
654  *      None.
655  *
656  *      RETURNS:
657  *      Constant C string representing highest speed listed in
658  *      @udma_mask, or the constant C string "<n/a>".
659  */
660
661 static const char *ata_mode_string(unsigned int mask)
662 {
663         int i;
664
665         for (i = 7; i >= 0; i--)
666                 if (mask & (1 << i))
667                         goto out;
668         for (i = ATA_SHIFT_MWDMA + 2; i >= ATA_SHIFT_MWDMA; i--)
669                 if (mask & (1 << i))
670                         goto out;
671         for (i = ATA_SHIFT_PIO + 4; i >= ATA_SHIFT_PIO; i--)
672                 if (mask & (1 << i))
673                         goto out;
674
675         return "<n/a>";
676
677 out:
678         return xfer_mode_str[i];
679 }
680
681 /**
682  *      ata_pio_devchk - PATA device presence detection
683  *      @ap: ATA channel to examine
684  *      @device: Device to examine (starting at zero)
685  *
686  *      This technique was originally described in
687  *      Hale Landis's ATADRVR (www.ata-atapi.com), and
688  *      later found its way into the ATA/ATAPI spec.
689  *
690  *      Write a pattern to the ATA shadow registers,
691  *      and if a device is present, it will respond by
692  *      correctly storing and echoing back the
693  *      ATA shadow register contents.
694  *
695  *      LOCKING:
696  *      caller.
697  */
698
699 static unsigned int ata_pio_devchk(struct ata_port *ap,
700                                    unsigned int device)
701 {
702         struct ata_ioports *ioaddr = &ap->ioaddr;
703         u8 nsect, lbal;
704
705         ap->ops->dev_select(ap, device);
706
707         outb(0x55, ioaddr->nsect_addr);
708         outb(0xaa, ioaddr->lbal_addr);
709
710         outb(0xaa, ioaddr->nsect_addr);
711         outb(0x55, ioaddr->lbal_addr);
712
713         outb(0x55, ioaddr->nsect_addr);
714         outb(0xaa, ioaddr->lbal_addr);
715
716         nsect = inb(ioaddr->nsect_addr);
717         lbal = inb(ioaddr->lbal_addr);
718
719         if ((nsect == 0x55) && (lbal == 0xaa))
720                 return 1;       /* we found a device */
721
722         return 0;               /* nothing found */
723 }
724
725 /**
726  *      ata_mmio_devchk - PATA device presence detection
727  *      @ap: ATA channel to examine
728  *      @device: Device to examine (starting at zero)
729  *
730  *      This technique was originally described in
731  *      Hale Landis's ATADRVR (www.ata-atapi.com), and
732  *      later found its way into the ATA/ATAPI spec.
733  *
734  *      Write a pattern to the ATA shadow registers,
735  *      and if a device is present, it will respond by
736  *      correctly storing and echoing back the
737  *      ATA shadow register contents.
738  *
739  *      LOCKING:
740  *      caller.
741  */
742
743 static unsigned int ata_mmio_devchk(struct ata_port *ap,
744                                     unsigned int device)
745 {
746         struct ata_ioports *ioaddr = &ap->ioaddr;
747         u8 nsect, lbal;
748
749         ap->ops->dev_select(ap, device);
750
751         writeb(0x55, (void __iomem *) ioaddr->nsect_addr);
752         writeb(0xaa, (void __iomem *) ioaddr->lbal_addr);
753
754         writeb(0xaa, (void __iomem *) ioaddr->nsect_addr);
755         writeb(0x55, (void __iomem *) ioaddr->lbal_addr);
756
757         writeb(0x55, (void __iomem *) ioaddr->nsect_addr);
758         writeb(0xaa, (void __iomem *) ioaddr->lbal_addr);
759
760         nsect = readb((void __iomem *) ioaddr->nsect_addr);
761         lbal = readb((void __iomem *) ioaddr->lbal_addr);
762
763         if ((nsect == 0x55) && (lbal == 0xaa))
764                 return 1;       /* we found a device */
765
766         return 0;               /* nothing found */
767 }
768
769 /**
770  *      ata_devchk - PATA device presence detection
771  *      @ap: ATA channel to examine
772  *      @device: Device to examine (starting at zero)
773  *
774  *      Dispatch ATA device presence detection, depending
775  *      on whether we are using PIO or MMIO to talk to the
776  *      ATA shadow registers.
777  *
778  *      LOCKING:
779  *      caller.
780  */
781
782 static unsigned int ata_devchk(struct ata_port *ap,
783                                     unsigned int device)
784 {
785         if (ap->flags & ATA_FLAG_MMIO)
786                 return ata_mmio_devchk(ap, device);
787         return ata_pio_devchk(ap, device);
788 }
789
790 /**
791  *      ata_dev_classify - determine device type based on ATA-spec signature
792  *      @tf: ATA taskfile register set for device to be identified
793  *
794  *      Determine from taskfile register contents whether a device is
795  *      ATA or ATAPI, as per "Signature and persistence" section
796  *      of ATA/PI spec (volume 1, sect 5.14).
797  *
798  *      LOCKING:
799  *      None.
800  *
801  *      RETURNS:
802  *      Device type, %ATA_DEV_ATA, %ATA_DEV_ATAPI, or %ATA_DEV_UNKNOWN
803  *      the event of failure.
804  */
805
806 unsigned int ata_dev_classify(const struct ata_taskfile *tf)
807 {
808         /* Apple's open source Darwin code hints that some devices only
809          * put a proper signature into the LBA mid/high registers,
810          * So, we only check those.  It's sufficient for uniqueness.
811          */
812
813         if (((tf->lbam == 0) && (tf->lbah == 0)) ||
814             ((tf->lbam == 0x3c) && (tf->lbah == 0xc3))) {
815                 DPRINTK("found ATA device by sig\n");
816                 return ATA_DEV_ATA;
817         }
818
819         if (((tf->lbam == 0x14) && (tf->lbah == 0xeb)) ||
820             ((tf->lbam == 0x69) && (tf->lbah == 0x96))) {
821                 DPRINTK("found ATAPI device by sig\n");
822                 return ATA_DEV_ATAPI;
823         }
824
825         DPRINTK("unknown device\n");
826         return ATA_DEV_UNKNOWN;
827 }
828
829 /**
830  *      ata_dev_try_classify - Parse returned ATA device signature
831  *      @ap: ATA channel to examine
832  *      @device: Device to examine (starting at zero)
833  *
834  *      After an event -- SRST, E.D.D., or SATA COMRESET -- occurs,
835  *      an ATA/ATAPI-defined set of values is placed in the ATA
836  *      shadow registers, indicating the results of device detection
837  *      and diagnostics.
838  *
839  *      Select the ATA device, and read the values from the ATA shadow
840  *      registers.  Then parse according to the Error register value,
841  *      and the spec-defined values examined by ata_dev_classify().
842  *
843  *      LOCKING:
844  *      caller.
845  */
846
847 static u8 ata_dev_try_classify(struct ata_port *ap, unsigned int device)
848 {
849         struct ata_device *dev = &ap->device[device];
850         struct ata_taskfile tf;
851         unsigned int class;
852         u8 err;
853
854         ap->ops->dev_select(ap, device);
855
856         memset(&tf, 0, sizeof(tf));
857
858         ap->ops->tf_read(ap, &tf);
859         err = tf.feature;
860
861         dev->class = ATA_DEV_NONE;
862
863         /* see if device passed diags */
864         if (err == 1)
865                 /* do nothing */ ;
866         else if ((device == 0) && (err == 0x81))
867                 /* do nothing */ ;
868         else
869                 return err;
870
871         /* determine if device if ATA or ATAPI */
872         class = ata_dev_classify(&tf);
873         if (class == ATA_DEV_UNKNOWN)
874                 return err;
875         if ((class == ATA_DEV_ATA) && (ata_chk_status(ap) == 0))
876                 return err;
877
878         dev->class = class;
879
880         return err;
881 }
882
883 /**
884  *      ata_dev_id_string - Convert IDENTIFY DEVICE page into string
885  *      @id: IDENTIFY DEVICE results we will examine
886  *      @s: string into which data is output
887  *      @ofs: offset into identify device page
888  *      @len: length of string to return. must be an even number.
889  *
890  *      The strings in the IDENTIFY DEVICE page are broken up into
891  *      16-bit chunks.  Run through the string, and output each
892  *      8-bit chunk linearly, regardless of platform.
893  *
894  *      LOCKING:
895  *      caller.
896  */
897
898 void ata_dev_id_string(const u16 *id, unsigned char *s,
899                        unsigned int ofs, unsigned int len)
900 {
901         unsigned int c;
902
903         while (len > 0) {
904                 c = id[ofs] >> 8;
905                 *s = c;
906                 s++;
907
908                 c = id[ofs] & 0xff;
909                 *s = c;
910                 s++;
911
912                 ofs++;
913                 len -= 2;
914         }
915 }
916
917
918 /**
919  *      ata_noop_dev_select - Select device 0/1 on ATA bus
920  *      @ap: ATA channel to manipulate
921  *      @device: ATA device (numbered from zero) to select
922  *
923  *      This function performs no actual function.
924  *
925  *      May be used as the dev_select() entry in ata_port_operations.
926  *
927  *      LOCKING:
928  *      caller.
929  */
930 void ata_noop_dev_select (struct ata_port *ap, unsigned int device)
931 {
932 }
933
934
935 /**
936  *      ata_std_dev_select - Select device 0/1 on ATA bus
937  *      @ap: ATA channel to manipulate
938  *      @device: ATA device (numbered from zero) to select
939  *
940  *      Use the method defined in the ATA specification to
941  *      make either device 0, or device 1, active on the
942  *      ATA channel.  Works with both PIO and MMIO.
943  *
944  *      May be used as the dev_select() entry in ata_port_operations.
945  *
946  *      LOCKING:
947  *      caller.
948  */
949
950 void ata_std_dev_select (struct ata_port *ap, unsigned int device)
951 {
952         u8 tmp;
953
954         if (device == 0)
955                 tmp = ATA_DEVICE_OBS;
956         else
957                 tmp = ATA_DEVICE_OBS | ATA_DEV1;
958
959         if (ap->flags & ATA_FLAG_MMIO) {
960                 writeb(tmp, (void __iomem *) ap->ioaddr.device_addr);
961         } else {
962                 outb(tmp, ap->ioaddr.device_addr);
963         }
964         ata_pause(ap);          /* needed; also flushes, for mmio */
965 }
966
967 /**
968  *      ata_dev_select - Select device 0/1 on ATA bus
969  *      @ap: ATA channel to manipulate
970  *      @device: ATA device (numbered from zero) to select
971  *      @wait: non-zero to wait for Status register BSY bit to clear
972  *      @can_sleep: non-zero if context allows sleeping
973  *
974  *      Use the method defined in the ATA specification to
975  *      make either device 0, or device 1, active on the
976  *      ATA channel.
977  *
978  *      This is a high-level version of ata_std_dev_select(),
979  *      which additionally provides the services of inserting
980  *      the proper pauses and status polling, where needed.
981  *
982  *      LOCKING:
983  *      caller.
984  */
985
986 void ata_dev_select(struct ata_port *ap, unsigned int device,
987                            unsigned int wait, unsigned int can_sleep)
988 {
989         VPRINTK("ENTER, ata%u: device %u, wait %u\n",
990                 ap->id, device, wait);
991
992         if (wait)
993                 ata_wait_idle(ap);
994
995         ap->ops->dev_select(ap, device);
996
997         if (wait) {
998                 if (can_sleep && ap->device[device].class == ATA_DEV_ATAPI)
999                         msleep(150);
1000                 ata_wait_idle(ap);
1001         }
1002 }
1003
1004 /**
1005  *      ata_dump_id - IDENTIFY DEVICE info debugging output
1006  *      @dev: Device whose IDENTIFY DEVICE page we will dump
1007  *
1008  *      Dump selected 16-bit words from a detected device's
1009  *      IDENTIFY PAGE page.
1010  *
1011  *      LOCKING:
1012  *      caller.
1013  */
1014
1015 static inline void ata_dump_id(const struct ata_device *dev)
1016 {
1017         DPRINTK("49==0x%04x  "
1018                 "53==0x%04x  "
1019                 "63==0x%04x  "
1020                 "64==0x%04x  "
1021                 "75==0x%04x  \n",
1022                 dev->id[49],
1023                 dev->id[53],
1024                 dev->id[63],
1025                 dev->id[64],
1026                 dev->id[75]);
1027         DPRINTK("80==0x%04x  "
1028                 "81==0x%04x  "
1029                 "82==0x%04x  "
1030                 "83==0x%04x  "
1031                 "84==0x%04x  \n",
1032                 dev->id[80],
1033                 dev->id[81],
1034                 dev->id[82],
1035                 dev->id[83],
1036                 dev->id[84]);
1037         DPRINTK("88==0x%04x  "
1038                 "93==0x%04x\n",
1039                 dev->id[88],
1040                 dev->id[93]);
1041 }
1042
1043 /*
1044  *      Compute the PIO modes available for this device. This is not as
1045  *      trivial as it seems if we must consider early devices correctly.
1046  *
1047  *      FIXME: pre IDE drive timing (do we care ?). 
1048  */
1049
1050 static unsigned int ata_pio_modes(const struct ata_device *adev)
1051 {
1052         u16 modes;
1053
1054         /* Usual case. Word 53 indicates word 64 is valid */
1055         if (adev->id[ATA_ID_FIELD_VALID] & (1 << 1)) {
1056                 modes = adev->id[ATA_ID_PIO_MODES] & 0x03;
1057                 modes <<= 3;
1058                 modes |= 0x7;
1059                 return modes;
1060         }
1061
1062         /* If word 64 isn't valid then Word 51 high byte holds the PIO timing
1063            number for the maximum. Turn it into a mask and return it */
1064         modes = (2 << ((adev->id[ATA_ID_OLD_PIO_MODES] >> 8) & 0xFF)) - 1 ;
1065         return modes;
1066         /* But wait.. there's more. Design your standards by committee and
1067            you too can get a free iordy field to process. However its the 
1068            speeds not the modes that are supported... Note drivers using the
1069            timing API will get this right anyway */
1070 }
1071
1072 static inline void
1073 ata_queue_packet_task(struct ata_port *ap)
1074 {
1075         queue_work(ata_wq, &ap->packet_task);
1076 }
1077
1078 static inline void
1079 ata_queue_pio_task(struct ata_port *ap)
1080 {
1081         queue_work(ata_wq, &ap->pio_task);
1082 }
1083
1084 static inline void
1085 ata_queue_delayed_pio_task(struct ata_port *ap, unsigned long delay)
1086 {
1087         queue_delayed_work(ata_wq, &ap->pio_task, delay);
1088 }
1089
1090 void ata_qc_complete_internal(struct ata_queued_cmd *qc)
1091 {
1092         struct completion *waiting = qc->private_data;
1093
1094         qc->ap->ops->tf_read(qc->ap, &qc->tf);
1095         complete(waiting);
1096 }
1097
1098 /**
1099  *      ata_exec_internal - execute libata internal command
1100  *      @ap: Port to which the command is sent
1101  *      @dev: Device to which the command is sent
1102  *      @tf: Taskfile registers for the command and the result
1103  *      @dma_dir: Data tranfer direction of the command
1104  *      @buf: Data buffer of the command
1105  *      @buflen: Length of data buffer
1106  *
1107  *      Executes libata internal command with timeout.  @tf contains
1108  *      command on entry and result on return.  Timeout and error
1109  *      conditions are reported via return value.  No recovery action
1110  *      is taken after a command times out.  It's caller's duty to
1111  *      clean up after timeout.
1112  *
1113  *      LOCKING:
1114  *      None.  Should be called with kernel context, might sleep.
1115  */
1116
1117 static unsigned
1118 ata_exec_internal(struct ata_port *ap, struct ata_device *dev,
1119                   struct ata_taskfile *tf,
1120                   int dma_dir, void *buf, unsigned int buflen)
1121 {
1122         u8 command = tf->command;
1123         struct ata_queued_cmd *qc;
1124         DECLARE_COMPLETION(wait);
1125         unsigned long flags;
1126         unsigned int err_mask;
1127
1128         spin_lock_irqsave(&ap->host_set->lock, flags);
1129
1130         qc = ata_qc_new_init(ap, dev);
1131         BUG_ON(qc == NULL);
1132
1133         qc->tf = *tf;
1134         qc->dma_dir = dma_dir;
1135         if (dma_dir != DMA_NONE) {
1136                 ata_sg_init_one(qc, buf, buflen);
1137                 qc->nsect = buflen / ATA_SECT_SIZE;
1138         }
1139
1140         qc->private_data = &wait;
1141         qc->complete_fn = ata_qc_complete_internal;
1142
1143         qc->err_mask = ata_qc_issue(qc);
1144         if (qc->err_mask)
1145                 ata_qc_complete(qc);
1146
1147         spin_unlock_irqrestore(&ap->host_set->lock, flags);
1148
1149         if (!wait_for_completion_timeout(&wait, ATA_TMOUT_INTERNAL)) {
1150                 spin_lock_irqsave(&ap->host_set->lock, flags);
1151
1152                 /* We're racing with irq here.  If we lose, the
1153                  * following test prevents us from completing the qc
1154                  * again.  If completion irq occurs after here but
1155                  * before the caller cleans up, it will result in a
1156                  * spurious interrupt.  We can live with that.
1157                  */
1158                 if (qc->flags & ATA_QCFLAG_ACTIVE) {
1159                         qc->err_mask = AC_ERR_TIMEOUT;
1160                         ata_qc_complete(qc);
1161                         printk(KERN_WARNING "ata%u: qc timeout (cmd 0x%x)\n",
1162                                ap->id, command);
1163                 }
1164
1165                 spin_unlock_irqrestore(&ap->host_set->lock, flags);
1166         }
1167
1168         *tf = qc->tf;
1169         err_mask = qc->err_mask;
1170
1171         ata_qc_free(qc);
1172
1173         return err_mask;
1174 }
1175
1176 /**
1177  *      ata_pio_need_iordy      -       check if iordy needed
1178  *      @adev: ATA device
1179  *
1180  *      Check if the current speed of the device requires IORDY. Used
1181  *      by various controllers for chip configuration.
1182  */
1183
1184 unsigned int ata_pio_need_iordy(const struct ata_device *adev)
1185 {
1186         int pio;
1187         int speed = adev->pio_mode - XFER_PIO_0;
1188
1189         if (speed < 2)
1190                 return 0;
1191         if (speed > 2)
1192                 return 1;
1193                 
1194         /* If we have no drive specific rule, then PIO 2 is non IORDY */
1195
1196         if (adev->id[ATA_ID_FIELD_VALID] & 2) { /* EIDE */
1197                 pio = adev->id[ATA_ID_EIDE_PIO];
1198                 /* Is the speed faster than the drive allows non IORDY ? */
1199                 if (pio) {
1200                         /* This is cycle times not frequency - watch the logic! */
1201                         if (pio > 240)  /* PIO2 is 240nS per cycle */
1202                                 return 1;
1203                         return 0;
1204                 }
1205         }
1206         return 0;
1207 }
1208
1209 /**
1210  *      ata_dev_identify - obtain IDENTIFY x DEVICE page
1211  *      @ap: port on which device we wish to probe resides
1212  *      @device: device bus address, starting at zero
1213  *
1214  *      Following bus reset, we issue the IDENTIFY [PACKET] DEVICE
1215  *      command, and read back the 512-byte device information page.
1216  *      The device information page is fed to us via the standard
1217  *      PIO-IN protocol, but we hand-code it here. (TODO: investigate
1218  *      using standard PIO-IN paths)
1219  *
1220  *      After reading the device information page, we use several
1221  *      bits of information from it to initialize data structures
1222  *      that will be used during the lifetime of the ata_device.
1223  *      Other data from the info page is used to disqualify certain
1224  *      older ATA devices we do not wish to support.
1225  *
1226  *      LOCKING:
1227  *      Inherited from caller.  Some functions called by this function
1228  *      obtain the host_set lock.
1229  */
1230
1231 static void ata_dev_identify(struct ata_port *ap, unsigned int device)
1232 {
1233         struct ata_device *dev = &ap->device[device];
1234         unsigned int major_version;
1235         u16 tmp;
1236         unsigned long xfer_modes;
1237         unsigned int using_edd;
1238         struct ata_taskfile tf;
1239         unsigned int err_mask;
1240         int rc;
1241
1242         if (!ata_dev_present(dev)) {
1243                 DPRINTK("ENTER/EXIT (host %u, dev %u) -- nodev\n",
1244                         ap->id, device);
1245                 return;
1246         }
1247
1248         if (ap->flags & (ATA_FLAG_SRST | ATA_FLAG_SATA_RESET))
1249                 using_edd = 0;
1250         else
1251                 using_edd = 1;
1252
1253         DPRINTK("ENTER, host %u, dev %u\n", ap->id, device);
1254
1255         assert (dev->class == ATA_DEV_ATA || dev->class == ATA_DEV_ATAPI ||
1256                 dev->class == ATA_DEV_NONE);
1257
1258         ata_dev_select(ap, device, 1, 1); /* select device 0/1 */
1259
1260 retry:
1261         ata_tf_init(ap, &tf, device);
1262
1263         if (dev->class == ATA_DEV_ATA) {
1264                 tf.command = ATA_CMD_ID_ATA;
1265                 DPRINTK("do ATA identify\n");
1266         } else {
1267                 tf.command = ATA_CMD_ID_ATAPI;
1268                 DPRINTK("do ATAPI identify\n");
1269         }
1270
1271         tf.protocol = ATA_PROT_PIO;
1272
1273         err_mask = ata_exec_internal(ap, dev, &tf, DMA_FROM_DEVICE,
1274                                      dev->id, sizeof(dev->id));
1275
1276         if (err_mask) {
1277                 if (err_mask & ~AC_ERR_DEV)
1278                         goto err_out;
1279
1280                 /*
1281                  * arg!  EDD works for all test cases, but seems to return
1282                  * the ATA signature for some ATAPI devices.  Until the
1283                  * reason for this is found and fixed, we fix up the mess
1284                  * here.  If IDENTIFY DEVICE returns command aborted
1285                  * (as ATAPI devices do), then we issue an
1286                  * IDENTIFY PACKET DEVICE.
1287                  *
1288                  * ATA software reset (SRST, the default) does not appear
1289                  * to have this problem.
1290                  */
1291                 if ((using_edd) && (dev->class == ATA_DEV_ATA)) {
1292                         u8 err = tf.feature;
1293                         if (err & ATA_ABORTED) {
1294                                 dev->class = ATA_DEV_ATAPI;
1295                                 goto retry;
1296                         }
1297                 }
1298                 goto err_out;
1299         }
1300
1301         swap_buf_le16(dev->id, ATA_ID_WORDS);
1302
1303         /* print device capabilities */
1304         printk(KERN_DEBUG "ata%u: dev %u cfg "
1305                "49:%04x 82:%04x 83:%04x 84:%04x 85:%04x 86:%04x 87:%04x 88:%04x\n",
1306                ap->id, device, dev->id[49],
1307                dev->id[82], dev->id[83], dev->id[84],
1308                dev->id[85], dev->id[86], dev->id[87],
1309                dev->id[88]);
1310
1311         /*
1312          * common ATA, ATAPI feature tests
1313          */
1314
1315         /* we require DMA support (bits 8 of word 49) */
1316         if (!ata_id_has_dma(dev->id)) {
1317                 printk(KERN_DEBUG "ata%u: no dma\n", ap->id);
1318                 goto err_out_nosup;
1319         }
1320
1321         /* quick-n-dirty find max transfer mode; for printk only */
1322         xfer_modes = dev->id[ATA_ID_UDMA_MODES];
1323         if (!xfer_modes)
1324                 xfer_modes = (dev->id[ATA_ID_MWDMA_MODES]) << ATA_SHIFT_MWDMA;
1325         if (!xfer_modes)
1326                 xfer_modes = ata_pio_modes(dev);
1327
1328         ata_dump_id(dev);
1329
1330         /* ATA-specific feature tests */
1331         if (dev->class == ATA_DEV_ATA) {
1332                 if (!ata_id_is_ata(dev->id))    /* sanity check */
1333                         goto err_out_nosup;
1334
1335                 /* get major version */
1336                 tmp = dev->id[ATA_ID_MAJOR_VER];
1337                 for (major_version = 14; major_version >= 1; major_version--)
1338                         if (tmp & (1 << major_version))
1339                                 break;
1340
1341                 /*
1342                  * The exact sequence expected by certain pre-ATA4 drives is:
1343                  * SRST RESET
1344                  * IDENTIFY
1345                  * INITIALIZE DEVICE PARAMETERS
1346                  * anything else..
1347                  * Some drives were very specific about that exact sequence.
1348                  */
1349                 if (major_version < 4 || (!ata_id_has_lba(dev->id))) {
1350                         ata_dev_init_params(ap, dev);
1351
1352                         /* current CHS translation info (id[53-58]) might be
1353                          * changed. reread the identify device info.
1354                          */
1355                         ata_dev_reread_id(ap, dev);
1356                 }
1357
1358                 if (ata_id_has_lba(dev->id)) {
1359                         dev->flags |= ATA_DFLAG_LBA;
1360
1361                         if (ata_id_has_lba48(dev->id)) {
1362                                 dev->flags |= ATA_DFLAG_LBA48;
1363                                 dev->n_sectors = ata_id_u64(dev->id, 100);
1364                         } else {
1365                                 dev->n_sectors = ata_id_u32(dev->id, 60);
1366                         }
1367
1368                         /* print device info to dmesg */
1369                         printk(KERN_INFO "ata%u: dev %u ATA-%d, max %s, %Lu sectors:%s\n",
1370                                ap->id, device,
1371                                major_version,
1372                                ata_mode_string(xfer_modes),
1373                                (unsigned long long)dev->n_sectors,
1374                                dev->flags & ATA_DFLAG_LBA48 ? " LBA48" : " LBA");
1375                 } else { 
1376                         /* CHS */
1377
1378                         /* Default translation */
1379                         dev->cylinders  = dev->id[1];
1380                         dev->heads      = dev->id[3];
1381                         dev->sectors    = dev->id[6];
1382                         dev->n_sectors  = dev->cylinders * dev->heads * dev->sectors;
1383
1384                         if (ata_id_current_chs_valid(dev->id)) {
1385                                 /* Current CHS translation is valid. */
1386                                 dev->cylinders = dev->id[54];
1387                                 dev->heads     = dev->id[55];
1388                                 dev->sectors   = dev->id[56];
1389                                 
1390                                 dev->n_sectors = ata_id_u32(dev->id, 57);
1391                         }
1392
1393                         /* print device info to dmesg */
1394                         printk(KERN_INFO "ata%u: dev %u ATA-%d, max %s, %Lu sectors: CHS %d/%d/%d\n",
1395                                ap->id, device,
1396                                major_version,
1397                                ata_mode_string(xfer_modes),
1398                                (unsigned long long)dev->n_sectors,
1399                                (int)dev->cylinders, (int)dev->heads, (int)dev->sectors);
1400
1401                 }
1402
1403                 ap->host->max_cmd_len = 16;
1404         }
1405
1406         /* ATAPI-specific feature tests */
1407         else if (dev->class == ATA_DEV_ATAPI) {
1408                 if (ata_id_is_ata(dev->id))             /* sanity check */
1409                         goto err_out_nosup;
1410
1411                 rc = atapi_cdb_len(dev->id);
1412                 if ((rc < 12) || (rc > ATAPI_CDB_LEN)) {
1413                         printk(KERN_WARNING "ata%u: unsupported CDB len\n", ap->id);
1414                         goto err_out_nosup;
1415                 }
1416                 ap->cdb_len = (unsigned int) rc;
1417                 ap->host->max_cmd_len = (unsigned char) ap->cdb_len;
1418
1419                 /* print device info to dmesg */
1420                 printk(KERN_INFO "ata%u: dev %u ATAPI, max %s\n",
1421                        ap->id, device,
1422                        ata_mode_string(xfer_modes));
1423         }
1424
1425         DPRINTK("EXIT, drv_stat = 0x%x\n", ata_chk_status(ap));
1426         return;
1427
1428 err_out_nosup:
1429         printk(KERN_WARNING "ata%u: dev %u not supported, ignoring\n",
1430                ap->id, device);
1431 err_out:
1432         dev->class++;   /* converts ATA_DEV_xxx into ATA_DEV_xxx_UNSUP */
1433         DPRINTK("EXIT, err\n");
1434 }
1435
1436
1437 static inline u8 ata_dev_knobble(const struct ata_port *ap)
1438 {
1439         return ((ap->cbl == ATA_CBL_SATA) && (!ata_id_is_sata(ap->device->id)));
1440 }
1441
1442 /**
1443  *      ata_dev_config - Run device specific handlers and check for
1444  *                       SATA->PATA bridges
1445  *      @ap: Bus
1446  *      @i:  Device
1447  *
1448  *      LOCKING:
1449  */
1450
1451 void ata_dev_config(struct ata_port *ap, unsigned int i)
1452 {
1453         /* limit bridge transfers to udma5, 200 sectors */
1454         if (ata_dev_knobble(ap)) {
1455                 printk(KERN_INFO "ata%u(%u): applying bridge limits\n",
1456                         ap->id, ap->device->devno);
1457                 ap->udma_mask &= ATA_UDMA5;
1458                 ap->host->max_sectors = ATA_MAX_SECTORS;
1459                 ap->host->hostt->max_sectors = ATA_MAX_SECTORS;
1460                 ap->device[i].flags |= ATA_DFLAG_LOCK_SECTORS;
1461         }
1462
1463         if (ap->ops->dev_config)
1464                 ap->ops->dev_config(ap, &ap->device[i]);
1465 }
1466
1467 /**
1468  *      ata_bus_probe - Reset and probe ATA bus
1469  *      @ap: Bus to probe
1470  *
1471  *      Master ATA bus probing function.  Initiates a hardware-dependent
1472  *      bus reset, then attempts to identify any devices found on
1473  *      the bus.
1474  *
1475  *      LOCKING:
1476  *      PCI/etc. bus probe sem.
1477  *
1478  *      RETURNS:
1479  *      Zero on success, non-zero on error.
1480  */
1481
1482 static int ata_bus_probe(struct ata_port *ap)
1483 {
1484         unsigned int i, found = 0;
1485
1486         ap->ops->phy_reset(ap);
1487         if (ap->flags & ATA_FLAG_PORT_DISABLED)
1488                 goto err_out;
1489
1490         for (i = 0; i < ATA_MAX_DEVICES; i++) {
1491                 ata_dev_identify(ap, i);
1492                 if (ata_dev_present(&ap->device[i])) {
1493                         found = 1;
1494                         ata_dev_config(ap,i);
1495                 }
1496         }
1497
1498         if ((!found) || (ap->flags & ATA_FLAG_PORT_DISABLED))
1499                 goto err_out_disable;
1500
1501         ata_set_mode(ap);
1502         if (ap->flags & ATA_FLAG_PORT_DISABLED)
1503                 goto err_out_disable;
1504
1505         return 0;
1506
1507 err_out_disable:
1508         ap->ops->port_disable(ap);
1509 err_out:
1510         return -1;
1511 }
1512
1513 /**
1514  *      ata_port_probe - Mark port as enabled
1515  *      @ap: Port for which we indicate enablement
1516  *
1517  *      Modify @ap data structure such that the system
1518  *      thinks that the entire port is enabled.
1519  *
1520  *      LOCKING: host_set lock, or some other form of
1521  *      serialization.
1522  */
1523
1524 void ata_port_probe(struct ata_port *ap)
1525 {
1526         ap->flags &= ~ATA_FLAG_PORT_DISABLED;
1527 }
1528
1529 /**
1530  *      sata_print_link_status - Print SATA link status
1531  *      @ap: SATA port to printk link status about
1532  *
1533  *      This function prints link speed and status of a SATA link.
1534  *
1535  *      LOCKING:
1536  *      None.
1537  */
1538 static void sata_print_link_status(struct ata_port *ap)
1539 {
1540         u32 sstatus, tmp;
1541         const char *speed;
1542
1543         if (!ap->ops->scr_read)
1544                 return;
1545
1546         sstatus = scr_read(ap, SCR_STATUS);
1547
1548         if (sata_dev_present(ap)) {
1549                 tmp = (sstatus >> 4) & 0xf;
1550                 if (tmp & (1 << 0))
1551                         speed = "1.5";
1552                 else if (tmp & (1 << 1))
1553                         speed = "3.0";
1554                 else
1555                         speed = "<unknown>";
1556                 printk(KERN_INFO "ata%u: SATA link up %s Gbps (SStatus %X)\n",
1557                        ap->id, speed, sstatus);
1558         } else {
1559                 printk(KERN_INFO "ata%u: SATA link down (SStatus %X)\n",
1560                        ap->id, sstatus);
1561         }
1562 }
1563
1564 /**
1565  *      __sata_phy_reset - Wake/reset a low-level SATA PHY
1566  *      @ap: SATA port associated with target SATA PHY.
1567  *
1568  *      This function issues commands to standard SATA Sxxx
1569  *      PHY registers, to wake up the phy (and device), and
1570  *      clear any reset condition.
1571  *
1572  *      LOCKING:
1573  *      PCI/etc. bus probe sem.
1574  *
1575  */
1576 void __sata_phy_reset(struct ata_port *ap)
1577 {
1578         u32 sstatus;
1579         unsigned long timeout = jiffies + (HZ * 5);
1580
1581         if (ap->flags & ATA_FLAG_SATA_RESET) {
1582                 /* issue phy wake/reset */
1583                 scr_write_flush(ap, SCR_CONTROL, 0x301);
1584                 /* Couldn't find anything in SATA I/II specs, but
1585                  * AHCI-1.1 10.4.2 says at least 1 ms. */
1586                 mdelay(1);
1587         }
1588         scr_write_flush(ap, SCR_CONTROL, 0x300); /* phy wake/clear reset */
1589
1590         /* wait for phy to become ready, if necessary */
1591         do {
1592                 msleep(200);
1593                 sstatus = scr_read(ap, SCR_STATUS);
1594                 if ((sstatus & 0xf) != 1)
1595                         break;
1596         } while (time_before(jiffies, timeout));
1597
1598         /* print link status */
1599         sata_print_link_status(ap);
1600
1601         /* TODO: phy layer with polling, timeouts, etc. */
1602         if (sata_dev_present(ap))
1603                 ata_port_probe(ap);
1604         else
1605                 ata_port_disable(ap);
1606
1607         if (ap->flags & ATA_FLAG_PORT_DISABLED)
1608                 return;
1609
1610         if (ata_busy_sleep(ap, ATA_TMOUT_BOOT_QUICK, ATA_TMOUT_BOOT)) {
1611                 ata_port_disable(ap);
1612                 return;
1613         }
1614
1615         ap->cbl = ATA_CBL_SATA;
1616 }
1617
1618 /**
1619  *      sata_phy_reset - Reset SATA bus.
1620  *      @ap: SATA port associated with target SATA PHY.
1621  *
1622  *      This function resets the SATA bus, and then probes
1623  *      the bus for devices.
1624  *
1625  *      LOCKING:
1626  *      PCI/etc. bus probe sem.
1627  *
1628  */
1629 void sata_phy_reset(struct ata_port *ap)
1630 {
1631         __sata_phy_reset(ap);
1632         if (ap->flags & ATA_FLAG_PORT_DISABLED)
1633                 return;
1634         ata_bus_reset(ap);
1635 }
1636
1637 /**
1638  *      ata_port_disable - Disable port.
1639  *      @ap: Port to be disabled.
1640  *
1641  *      Modify @ap data structure such that the system
1642  *      thinks that the entire port is disabled, and should
1643  *      never attempt to probe or communicate with devices
1644  *      on this port.
1645  *
1646  *      LOCKING: host_set lock, or some other form of
1647  *      serialization.
1648  */
1649
1650 void ata_port_disable(struct ata_port *ap)
1651 {
1652         ap->device[0].class = ATA_DEV_NONE;
1653         ap->device[1].class = ATA_DEV_NONE;
1654         ap->flags |= ATA_FLAG_PORT_DISABLED;
1655 }
1656
1657 /*
1658  * This mode timing computation functionality is ported over from
1659  * drivers/ide/ide-timing.h and was originally written by Vojtech Pavlik
1660  */
1661 /*
1662  * PIO 0-5, MWDMA 0-2 and UDMA 0-6 timings (in nanoseconds).
1663  * These were taken from ATA/ATAPI-6 standard, rev 0a, except
1664  * for PIO 5, which is a nonstandard extension and UDMA6, which
1665  * is currently supported only by Maxtor drives. 
1666  */
1667
1668 static const struct ata_timing ata_timing[] = {
1669
1670         { XFER_UDMA_6,     0,   0,   0,   0,   0,   0,   0,  15 },
1671         { XFER_UDMA_5,     0,   0,   0,   0,   0,   0,   0,  20 },
1672         { XFER_UDMA_4,     0,   0,   0,   0,   0,   0,   0,  30 },
1673         { XFER_UDMA_3,     0,   0,   0,   0,   0,   0,   0,  45 },
1674
1675         { XFER_UDMA_2,     0,   0,   0,   0,   0,   0,   0,  60 },
1676         { XFER_UDMA_1,     0,   0,   0,   0,   0,   0,   0,  80 },
1677         { XFER_UDMA_0,     0,   0,   0,   0,   0,   0,   0, 120 },
1678
1679 /*      { XFER_UDMA_SLOW,  0,   0,   0,   0,   0,   0,   0, 150 }, */
1680                                           
1681         { XFER_MW_DMA_2,  25,   0,   0,   0,  70,  25, 120,   0 },
1682         { XFER_MW_DMA_1,  45,   0,   0,   0,  80,  50, 150,   0 },
1683         { XFER_MW_DMA_0,  60,   0,   0,   0, 215, 215, 480,   0 },
1684                                           
1685         { XFER_SW_DMA_2,  60,   0,   0,   0, 120, 120, 240,   0 },
1686         { XFER_SW_DMA_1,  90,   0,   0,   0, 240, 240, 480,   0 },
1687         { XFER_SW_DMA_0, 120,   0,   0,   0, 480, 480, 960,   0 },
1688
1689 /*      { XFER_PIO_5,     20,  50,  30, 100,  50,  30, 100,   0 }, */
1690         { XFER_PIO_4,     25,  70,  25, 120,  70,  25, 120,   0 },
1691         { XFER_PIO_3,     30,  80,  70, 180,  80,  70, 180,   0 },
1692
1693         { XFER_PIO_2,     30, 290,  40, 330, 100,  90, 240,   0 },
1694         { XFER_PIO_1,     50, 290,  93, 383, 125, 100, 383,   0 },
1695         { XFER_PIO_0,     70, 290, 240, 600, 165, 150, 600,   0 },
1696
1697 /*      { XFER_PIO_SLOW, 120, 290, 240, 960, 290, 240, 960,   0 }, */
1698
1699         { 0xFF }
1700 };
1701
1702 #define ENOUGH(v,unit)          (((v)-1)/(unit)+1)
1703 #define EZ(v,unit)              ((v)?ENOUGH(v,unit):0)
1704
1705 static void ata_timing_quantize(const struct ata_timing *t, struct ata_timing *q, int T, int UT)
1706 {
1707         q->setup   = EZ(t->setup   * 1000,  T);
1708         q->act8b   = EZ(t->act8b   * 1000,  T);
1709         q->rec8b   = EZ(t->rec8b   * 1000,  T);
1710         q->cyc8b   = EZ(t->cyc8b   * 1000,  T);
1711         q->active  = EZ(t->active  * 1000,  T);
1712         q->recover = EZ(t->recover * 1000,  T);
1713         q->cycle   = EZ(t->cycle   * 1000,  T);
1714         q->udma    = EZ(t->udma    * 1000, UT);
1715 }
1716
1717 void ata_timing_merge(const struct ata_timing *a, const struct ata_timing *b,
1718                       struct ata_timing *m, unsigned int what)
1719 {
1720         if (what & ATA_TIMING_SETUP  ) m->setup   = max(a->setup,   b->setup);
1721         if (what & ATA_TIMING_ACT8B  ) m->act8b   = max(a->act8b,   b->act8b);
1722         if (what & ATA_TIMING_REC8B  ) m->rec8b   = max(a->rec8b,   b->rec8b);
1723         if (what & ATA_TIMING_CYC8B  ) m->cyc8b   = max(a->cyc8b,   b->cyc8b);
1724         if (what & ATA_TIMING_ACTIVE ) m->active  = max(a->active,  b->active);
1725         if (what & ATA_TIMING_RECOVER) m->recover = max(a->recover, b->recover);
1726         if (what & ATA_TIMING_CYCLE  ) m->cycle   = max(a->cycle,   b->cycle);
1727         if (what & ATA_TIMING_UDMA   ) m->udma    = max(a->udma,    b->udma);
1728 }
1729
1730 static const struct ata_timing* ata_timing_find_mode(unsigned short speed)
1731 {
1732         const struct ata_timing *t;
1733
1734         for (t = ata_timing; t->mode != speed; t++)
1735                 if (t->mode == 0xFF)
1736                         return NULL;
1737         return t; 
1738 }
1739
1740 int ata_timing_compute(struct ata_device *adev, unsigned short speed,
1741                        struct ata_timing *t, int T, int UT)
1742 {
1743         const struct ata_timing *s;
1744         struct ata_timing p;
1745
1746         /*
1747          * Find the mode. 
1748          */
1749
1750         if (!(s = ata_timing_find_mode(speed)))
1751                 return -EINVAL;
1752
1753         memcpy(t, s, sizeof(*s));
1754
1755         /*
1756          * If the drive is an EIDE drive, it can tell us it needs extended
1757          * PIO/MW_DMA cycle timing.
1758          */
1759
1760         if (adev->id[ATA_ID_FIELD_VALID] & 2) { /* EIDE drive */
1761                 memset(&p, 0, sizeof(p));
1762                 if(speed >= XFER_PIO_0 && speed <= XFER_SW_DMA_0) {
1763                         if (speed <= XFER_PIO_2) p.cycle = p.cyc8b = adev->id[ATA_ID_EIDE_PIO];
1764                                             else p.cycle = p.cyc8b = adev->id[ATA_ID_EIDE_PIO_IORDY];
1765                 } else if(speed >= XFER_MW_DMA_0 && speed <= XFER_MW_DMA_2) {
1766                         p.cycle = adev->id[ATA_ID_EIDE_DMA_MIN];
1767                 }
1768                 ata_timing_merge(&p, t, t, ATA_TIMING_CYCLE | ATA_TIMING_CYC8B);
1769         }
1770
1771         /*
1772          * Convert the timing to bus clock counts.
1773          */
1774
1775         ata_timing_quantize(t, t, T, UT);
1776
1777         /*
1778          * Even in DMA/UDMA modes we still use PIO access for IDENTIFY, S.M.A.R.T
1779          * and some other commands. We have to ensure that the DMA cycle timing is
1780          * slower/equal than the fastest PIO timing.
1781          */
1782
1783         if (speed > XFER_PIO_4) {
1784                 ata_timing_compute(adev, adev->pio_mode, &p, T, UT);
1785                 ata_timing_merge(&p, t, t, ATA_TIMING_ALL);
1786         }
1787
1788         /*
1789          * Lenghten active & recovery time so that cycle time is correct.
1790          */
1791
1792         if (t->act8b + t->rec8b < t->cyc8b) {
1793                 t->act8b += (t->cyc8b - (t->act8b + t->rec8b)) / 2;
1794                 t->rec8b = t->cyc8b - t->act8b;
1795         }
1796
1797         if (t->active + t->recover < t->cycle) {
1798                 t->active += (t->cycle - (t->active + t->recover)) / 2;
1799                 t->recover = t->cycle - t->active;
1800         }
1801
1802         return 0;
1803 }
1804
1805 static const struct {
1806         unsigned int shift;
1807         u8 base;
1808 } xfer_mode_classes[] = {
1809         { ATA_SHIFT_UDMA,       XFER_UDMA_0 },
1810         { ATA_SHIFT_MWDMA,      XFER_MW_DMA_0 },
1811         { ATA_SHIFT_PIO,        XFER_PIO_0 },
1812 };
1813
1814 static u8 base_from_shift(unsigned int shift)
1815 {
1816         int i;
1817
1818         for (i = 0; i < ARRAY_SIZE(xfer_mode_classes); i++)
1819                 if (xfer_mode_classes[i].shift == shift)
1820                         return xfer_mode_classes[i].base;
1821
1822         return 0xff;
1823 }
1824
1825 static void ata_dev_set_mode(struct ata_port *ap, struct ata_device *dev)
1826 {
1827         int ofs, idx;
1828         u8 base;
1829
1830         if (!ata_dev_present(dev) || (ap->flags & ATA_FLAG_PORT_DISABLED))
1831                 return;
1832
1833         if (dev->xfer_shift == ATA_SHIFT_PIO)
1834                 dev->flags |= ATA_DFLAG_PIO;
1835
1836         ata_dev_set_xfermode(ap, dev);
1837
1838         base = base_from_shift(dev->xfer_shift);
1839         ofs = dev->xfer_mode - base;
1840         idx = ofs + dev->xfer_shift;
1841         WARN_ON(idx >= ARRAY_SIZE(xfer_mode_str));
1842
1843         DPRINTK("idx=%d xfer_shift=%u, xfer_mode=0x%x, base=0x%x, offset=%d\n",
1844                 idx, dev->xfer_shift, (int)dev->xfer_mode, (int)base, ofs);
1845
1846         printk(KERN_INFO "ata%u: dev %u configured for %s\n",
1847                 ap->id, dev->devno, xfer_mode_str[idx]);
1848 }
1849
1850 static int ata_host_set_pio(struct ata_port *ap)
1851 {
1852         unsigned int mask;
1853         int x, i;
1854         u8 base, xfer_mode;
1855
1856         mask = ata_get_mode_mask(ap, ATA_SHIFT_PIO);
1857         x = fgb(mask);
1858         if (x < 0) {
1859                 printk(KERN_WARNING "ata%u: no PIO support\n", ap->id);
1860                 return -1;
1861         }
1862
1863         base = base_from_shift(ATA_SHIFT_PIO);
1864         xfer_mode = base + x;
1865
1866         DPRINTK("base 0x%x xfer_mode 0x%x mask 0x%x x %d\n",
1867                 (int)base, (int)xfer_mode, mask, x);
1868
1869         for (i = 0; i < ATA_MAX_DEVICES; i++) {
1870                 struct ata_device *dev = &ap->device[i];
1871                 if (ata_dev_present(dev)) {
1872                         dev->pio_mode = xfer_mode;
1873                         dev->xfer_mode = xfer_mode;
1874                         dev->xfer_shift = ATA_SHIFT_PIO;
1875                         if (ap->ops->set_piomode)
1876                                 ap->ops->set_piomode(ap, dev);
1877                 }
1878         }
1879
1880         return 0;
1881 }
1882
1883 static void ata_host_set_dma(struct ata_port *ap, u8 xfer_mode,
1884                             unsigned int xfer_shift)
1885 {
1886         int i;
1887
1888         for (i = 0; i < ATA_MAX_DEVICES; i++) {
1889                 struct ata_device *dev = &ap->device[i];
1890                 if (ata_dev_present(dev)) {
1891                         dev->dma_mode = xfer_mode;
1892                         dev->xfer_mode = xfer_mode;
1893                         dev->xfer_shift = xfer_shift;
1894                         if (ap->ops->set_dmamode)
1895                                 ap->ops->set_dmamode(ap, dev);
1896                 }
1897         }
1898 }
1899
1900 /**
1901  *      ata_set_mode - Program timings and issue SET FEATURES - XFER
1902  *      @ap: port on which timings will be programmed
1903  *
1904  *      Set ATA device disk transfer mode (PIO3, UDMA6, etc.).
1905  *
1906  *      LOCKING:
1907  *      PCI/etc. bus probe sem.
1908  *
1909  */
1910 static void ata_set_mode(struct ata_port *ap)
1911 {
1912         unsigned int xfer_shift;
1913         u8 xfer_mode;
1914         int rc;
1915
1916         /* step 1: always set host PIO timings */
1917         rc = ata_host_set_pio(ap);
1918         if (rc)
1919                 goto err_out;
1920
1921         /* step 2: choose the best data xfer mode */
1922         xfer_mode = xfer_shift = 0;
1923         rc = ata_choose_xfer_mode(ap, &xfer_mode, &xfer_shift);
1924         if (rc)
1925                 goto err_out;
1926
1927         /* step 3: if that xfer mode isn't PIO, set host DMA timings */
1928         if (xfer_shift != ATA_SHIFT_PIO)
1929                 ata_host_set_dma(ap, xfer_mode, xfer_shift);
1930
1931         /* step 4: update devices' xfer mode */
1932         ata_dev_set_mode(ap, &ap->device[0]);
1933         ata_dev_set_mode(ap, &ap->device[1]);
1934
1935         if (ap->flags & ATA_FLAG_PORT_DISABLED)
1936                 return;
1937
1938         if (ap->ops->post_set_mode)
1939                 ap->ops->post_set_mode(ap);
1940
1941         return;
1942
1943 err_out:
1944         ata_port_disable(ap);
1945 }
1946
1947 /**
1948  *      ata_busy_sleep - sleep until BSY clears, or timeout
1949  *      @ap: port containing status register to be polled
1950  *      @tmout_pat: impatience timeout
1951  *      @tmout: overall timeout
1952  *
1953  *      Sleep until ATA Status register bit BSY clears,
1954  *      or a timeout occurs.
1955  *
1956  *      LOCKING: None.
1957  *
1958  */
1959
1960 unsigned int ata_busy_sleep (struct ata_port *ap,
1961                              unsigned long tmout_pat, unsigned long tmout)
1962 {
1963         unsigned long timer_start, timeout;
1964         u8 status;
1965
1966         status = ata_busy_wait(ap, ATA_BUSY, 300);
1967         timer_start = jiffies;
1968         timeout = timer_start + tmout_pat;
1969         while ((status & ATA_BUSY) && (time_before(jiffies, timeout))) {
1970                 msleep(50);
1971                 status = ata_busy_wait(ap, ATA_BUSY, 3);
1972         }
1973
1974         if (status & ATA_BUSY)
1975                 printk(KERN_WARNING "ata%u is slow to respond, "
1976                        "please be patient\n", ap->id);
1977
1978         timeout = timer_start + tmout;
1979         while ((status & ATA_BUSY) && (time_before(jiffies, timeout))) {
1980                 msleep(50);
1981                 status = ata_chk_status(ap);
1982         }
1983
1984         if (status & ATA_BUSY) {
1985                 printk(KERN_ERR "ata%u failed to respond (%lu secs)\n",
1986                        ap->id, tmout / HZ);
1987                 return 1;
1988         }
1989
1990         return 0;
1991 }
1992
1993 static void ata_bus_post_reset(struct ata_port *ap, unsigned int devmask)
1994 {
1995         struct ata_ioports *ioaddr = &ap->ioaddr;
1996         unsigned int dev0 = devmask & (1 << 0);
1997         unsigned int dev1 = devmask & (1 << 1);
1998         unsigned long timeout;
1999
2000         /* if device 0 was found in ata_devchk, wait for its
2001          * BSY bit to clear
2002          */
2003         if (dev0)
2004                 ata_busy_sleep(ap, ATA_TMOUT_BOOT_QUICK, ATA_TMOUT_BOOT);
2005
2006         /* if device 1 was found in ata_devchk, wait for
2007          * register access, then wait for BSY to clear
2008          */
2009         timeout = jiffies + ATA_TMOUT_BOOT;
2010         while (dev1) {
2011                 u8 nsect, lbal;
2012
2013                 ap->ops->dev_select(ap, 1);
2014                 if (ap->flags & ATA_FLAG_MMIO) {
2015                         nsect = readb((void __iomem *) ioaddr->nsect_addr);
2016                         lbal = readb((void __iomem *) ioaddr->lbal_addr);
2017                 } else {
2018                         nsect = inb(ioaddr->nsect_addr);
2019                         lbal = inb(ioaddr->lbal_addr);
2020                 }
2021                 if ((nsect == 1) && (lbal == 1))
2022                         break;
2023                 if (time_after(jiffies, timeout)) {
2024                         dev1 = 0;
2025                         break;
2026                 }
2027                 msleep(50);     /* give drive a breather */
2028         }
2029         if (dev1)
2030                 ata_busy_sleep(ap, ATA_TMOUT_BOOT_QUICK, ATA_TMOUT_BOOT);
2031
2032         /* is all this really necessary? */
2033         ap->ops->dev_select(ap, 0);
2034         if (dev1)
2035                 ap->ops->dev_select(ap, 1);
2036         if (dev0)
2037                 ap->ops->dev_select(ap, 0);
2038 }
2039
2040 /**
2041  *      ata_bus_edd - Issue EXECUTE DEVICE DIAGNOSTIC command.
2042  *      @ap: Port to reset and probe
2043  *
2044  *      Use the EXECUTE DEVICE DIAGNOSTIC command to reset and
2045  *      probe the bus.  Not often used these days.
2046  *
2047  *      LOCKING:
2048  *      PCI/etc. bus probe sem.
2049  *      Obtains host_set lock.
2050  *
2051  */
2052
2053 static unsigned int ata_bus_edd(struct ata_port *ap)
2054 {
2055         struct ata_taskfile tf;
2056         unsigned long flags;
2057
2058         /* set up execute-device-diag (bus reset) taskfile */
2059         /* also, take interrupts to a known state (disabled) */
2060         DPRINTK("execute-device-diag\n");
2061         ata_tf_init(ap, &tf, 0);
2062         tf.ctl |= ATA_NIEN;
2063         tf.command = ATA_CMD_EDD;
2064         tf.protocol = ATA_PROT_NODATA;
2065
2066         /* do bus reset */
2067         spin_lock_irqsave(&ap->host_set->lock, flags);
2068         ata_tf_to_host(ap, &tf);
2069         spin_unlock_irqrestore(&ap->host_set->lock, flags);
2070
2071         /* spec says at least 2ms.  but who knows with those
2072          * crazy ATAPI devices...
2073          */
2074         msleep(150);
2075
2076         return ata_busy_sleep(ap, ATA_TMOUT_BOOT_QUICK, ATA_TMOUT_BOOT);
2077 }
2078
2079 static unsigned int ata_bus_softreset(struct ata_port *ap,
2080                                       unsigned int devmask)
2081 {
2082         struct ata_ioports *ioaddr = &ap->ioaddr;
2083
2084         DPRINTK("ata%u: bus reset via SRST\n", ap->id);
2085
2086         /* software reset.  causes dev0 to be selected */
2087         if (ap->flags & ATA_FLAG_MMIO) {
2088                 writeb(ap->ctl, (void __iomem *) ioaddr->ctl_addr);
2089                 udelay(20);     /* FIXME: flush */
2090                 writeb(ap->ctl | ATA_SRST, (void __iomem *) ioaddr->ctl_addr);
2091                 udelay(20);     /* FIXME: flush */
2092                 writeb(ap->ctl, (void __iomem *) ioaddr->ctl_addr);
2093         } else {
2094                 outb(ap->ctl, ioaddr->ctl_addr);
2095                 udelay(10);
2096                 outb(ap->ctl | ATA_SRST, ioaddr->ctl_addr);
2097                 udelay(10);
2098                 outb(ap->ctl, ioaddr->ctl_addr);
2099         }
2100
2101         /* spec mandates ">= 2ms" before checking status.
2102          * We wait 150ms, because that was the magic delay used for
2103          * ATAPI devices in Hale Landis's ATADRVR, for the period of time
2104          * between when the ATA command register is written, and then
2105          * status is checked.  Because waiting for "a while" before
2106          * checking status is fine, post SRST, we perform this magic
2107          * delay here as well.
2108          */
2109         msleep(150);
2110
2111         ata_bus_post_reset(ap, devmask);
2112
2113         return 0;
2114 }
2115
2116 /**
2117  *      ata_bus_reset - reset host port and associated ATA channel
2118  *      @ap: port to reset
2119  *
2120  *      This is typically the first time we actually start issuing
2121  *      commands to the ATA channel.  We wait for BSY to clear, then
2122  *      issue EXECUTE DEVICE DIAGNOSTIC command, polling for its
2123  *      result.  Determine what devices, if any, are on the channel
2124  *      by looking at the device 0/1 error register.  Look at the signature
2125  *      stored in each device's taskfile registers, to determine if
2126  *      the device is ATA or ATAPI.
2127  *
2128  *      LOCKING:
2129  *      PCI/etc. bus probe sem.
2130  *      Obtains host_set lock.
2131  *
2132  *      SIDE EFFECTS:
2133  *      Sets ATA_FLAG_PORT_DISABLED if bus reset fails.
2134  */
2135
2136 void ata_bus_reset(struct ata_port *ap)
2137 {
2138         struct ata_ioports *ioaddr = &ap->ioaddr;
2139         unsigned int slave_possible = ap->flags & ATA_FLAG_SLAVE_POSS;
2140         u8 err;
2141         unsigned int dev0, dev1 = 0, rc = 0, devmask = 0;
2142
2143         DPRINTK("ENTER, host %u, port %u\n", ap->id, ap->port_no);
2144
2145         /* determine if device 0/1 are present */
2146         if (ap->flags & ATA_FLAG_SATA_RESET)
2147                 dev0 = 1;
2148         else {
2149                 dev0 = ata_devchk(ap, 0);
2150                 if (slave_possible)
2151                         dev1 = ata_devchk(ap, 1);
2152         }
2153
2154         if (dev0)
2155                 devmask |= (1 << 0);
2156         if (dev1)
2157                 devmask |= (1 << 1);
2158
2159         /* select device 0 again */
2160         ap->ops->dev_select(ap, 0);
2161
2162         /* issue bus reset */
2163         if (ap->flags & ATA_FLAG_SRST)
2164                 rc = ata_bus_softreset(ap, devmask);
2165         else if ((ap->flags & ATA_FLAG_SATA_RESET) == 0) {
2166                 /* set up device control */
2167                 if (ap->flags & ATA_FLAG_MMIO)
2168                         writeb(ap->ctl, (void __iomem *) ioaddr->ctl_addr);
2169                 else
2170                         outb(ap->ctl, ioaddr->ctl_addr);
2171                 rc = ata_bus_edd(ap);
2172         }
2173
2174         if (rc)
2175                 goto err_out;
2176
2177         /*
2178          * determine by signature whether we have ATA or ATAPI devices
2179          */
2180         err = ata_dev_try_classify(ap, 0);
2181         if ((slave_possible) && (err != 0x81))
2182                 ata_dev_try_classify(ap, 1);
2183
2184         /* re-enable interrupts */
2185         if (ap->ioaddr.ctl_addr)        /* FIXME: hack. create a hook instead */
2186                 ata_irq_on(ap);
2187
2188         /* is double-select really necessary? */
2189         if (ap->device[1].class != ATA_DEV_NONE)
2190                 ap->ops->dev_select(ap, 1);
2191         if (ap->device[0].class != ATA_DEV_NONE)
2192                 ap->ops->dev_select(ap, 0);
2193
2194         /* if no devices were detected, disable this port */
2195         if ((ap->device[0].class == ATA_DEV_NONE) &&
2196             (ap->device[1].class == ATA_DEV_NONE))
2197                 goto err_out;
2198
2199         if (ap->flags & (ATA_FLAG_SATA_RESET | ATA_FLAG_SRST)) {
2200                 /* set up device control for ATA_FLAG_SATA_RESET */
2201                 if (ap->flags & ATA_FLAG_MMIO)
2202                         writeb(ap->ctl, (void __iomem *) ioaddr->ctl_addr);
2203                 else
2204                         outb(ap->ctl, ioaddr->ctl_addr);
2205         }
2206
2207         DPRINTK("EXIT\n");
2208         return;
2209
2210 err_out:
2211         printk(KERN_ERR "ata%u: disabling port\n", ap->id);
2212         ap->ops->port_disable(ap);
2213
2214         DPRINTK("EXIT\n");
2215 }
2216
2217 static void ata_pr_blacklisted(const struct ata_port *ap,
2218                                const struct ata_device *dev)
2219 {
2220         printk(KERN_WARNING "ata%u: dev %u is on DMA blacklist, disabling DMA\n",
2221                 ap->id, dev->devno);
2222 }
2223
2224 static const char * const ata_dma_blacklist [] = {
2225         "WDC AC11000H",
2226         "WDC AC22100H",
2227         "WDC AC32500H",
2228         "WDC AC33100H",
2229         "WDC AC31600H",
2230         "WDC AC32100H",
2231         "WDC AC23200L",
2232         "Compaq CRD-8241B",
2233         "CRD-8400B",
2234         "CRD-8480B",
2235         "CRD-8482B",
2236         "CRD-84",
2237         "SanDisk SDP3B",
2238         "SanDisk SDP3B-64",
2239         "SANYO CD-ROM CRD",
2240         "HITACHI CDR-8",
2241         "HITACHI CDR-8335",
2242         "HITACHI CDR-8435",
2243         "Toshiba CD-ROM XM-6202B",
2244         "TOSHIBA CD-ROM XM-1702BC",
2245         "CD-532E-A",
2246         "E-IDE CD-ROM CR-840",
2247         "CD-ROM Drive/F5A",
2248         "WPI CDD-820",
2249         "SAMSUNG CD-ROM SC-148C",
2250         "SAMSUNG CD-ROM SC",
2251         "SanDisk SDP3B-64",
2252         "ATAPI CD-ROM DRIVE 40X MAXIMUM",
2253         "_NEC DV5800A",
2254 };
2255
2256 static int ata_dma_blacklisted(const struct ata_device *dev)
2257 {
2258         unsigned char model_num[40];
2259         char *s;
2260         unsigned int len;
2261         int i;
2262
2263         ata_dev_id_string(dev->id, model_num, ATA_ID_PROD_OFS,
2264                           sizeof(model_num));
2265         s = &model_num[0];
2266         len = strnlen(s, sizeof(model_num));
2267
2268         /* ATAPI specifies that empty space is blank-filled; remove blanks */
2269         while ((len > 0) && (s[len - 1] == ' ')) {
2270                 len--;
2271                 s[len] = 0;
2272         }
2273
2274         for (i = 0; i < ARRAY_SIZE(ata_dma_blacklist); i++)
2275                 if (!strncmp(ata_dma_blacklist[i], s, len))
2276                         return 1;
2277
2278         return 0;
2279 }
2280
2281 static unsigned int ata_get_mode_mask(const struct ata_port *ap, int shift)
2282 {
2283         const struct ata_device *master, *slave;
2284         unsigned int mask;
2285
2286         master = &ap->device[0];
2287         slave = &ap->device[1];
2288
2289         assert (ata_dev_present(master) || ata_dev_present(slave));
2290
2291         if (shift == ATA_SHIFT_UDMA) {
2292                 mask = ap->udma_mask;
2293                 if (ata_dev_present(master)) {
2294                         mask &= (master->id[ATA_ID_UDMA_MODES] & 0xff);
2295                         if (ata_dma_blacklisted(master)) {
2296                                 mask = 0;
2297                                 ata_pr_blacklisted(ap, master);
2298                         }
2299                 }
2300                 if (ata_dev_present(slave)) {
2301                         mask &= (slave->id[ATA_ID_UDMA_MODES] & 0xff);
2302                         if (ata_dma_blacklisted(slave)) {
2303                                 mask = 0;
2304                                 ata_pr_blacklisted(ap, slave);
2305                         }
2306                 }
2307         }
2308         else if (shift == ATA_SHIFT_MWDMA) {
2309                 mask = ap->mwdma_mask;
2310                 if (ata_dev_present(master)) {
2311                         mask &= (master->id[ATA_ID_MWDMA_MODES] & 0x07);
2312                         if (ata_dma_blacklisted(master)) {
2313                                 mask = 0;
2314                                 ata_pr_blacklisted(ap, master);
2315                         }
2316                 }
2317                 if (ata_dev_present(slave)) {
2318                         mask &= (slave->id[ATA_ID_MWDMA_MODES] & 0x07);
2319                         if (ata_dma_blacklisted(slave)) {
2320                                 mask = 0;
2321                                 ata_pr_blacklisted(ap, slave);
2322                         }
2323                 }
2324         }
2325         else if (shift == ATA_SHIFT_PIO) {
2326                 mask = ap->pio_mask;
2327                 if (ata_dev_present(master)) {
2328                         /* spec doesn't return explicit support for
2329                          * PIO0-2, so we fake it
2330                          */
2331                         u16 tmp_mode = master->id[ATA_ID_PIO_MODES] & 0x03;
2332                         tmp_mode <<= 3;
2333                         tmp_mode |= 0x7;
2334                         mask &= tmp_mode;
2335                 }
2336                 if (ata_dev_present(slave)) {
2337                         /* spec doesn't return explicit support for
2338                          * PIO0-2, so we fake it
2339                          */
2340                         u16 tmp_mode = slave->id[ATA_ID_PIO_MODES] & 0x03;
2341                         tmp_mode <<= 3;
2342                         tmp_mode |= 0x7;
2343                         mask &= tmp_mode;
2344                 }
2345         }
2346         else {
2347                 mask = 0xffffffff; /* shut up compiler warning */
2348                 BUG();
2349         }
2350
2351         return mask;
2352 }
2353
2354 /* find greatest bit */
2355 static int fgb(u32 bitmap)
2356 {
2357         unsigned int i;
2358         int x = -1;
2359
2360         for (i = 0; i < 32; i++)
2361                 if (bitmap & (1 << i))
2362                         x = i;
2363
2364         return x;
2365 }
2366
2367 /**
2368  *      ata_choose_xfer_mode - attempt to find best transfer mode
2369  *      @ap: Port for which an xfer mode will be selected
2370  *      @xfer_mode_out: (output) SET FEATURES - XFER MODE code
2371  *      @xfer_shift_out: (output) bit shift that selects this mode
2372  *
2373  *      Based on host and device capabilities, determine the
2374  *      maximum transfer mode that is amenable to all.
2375  *
2376  *      LOCKING:
2377  *      PCI/etc. bus probe sem.
2378  *
2379  *      RETURNS:
2380  *      Zero on success, negative on error.
2381  */
2382
2383 static int ata_choose_xfer_mode(const struct ata_port *ap,
2384                                 u8 *xfer_mode_out,
2385                                 unsigned int *xfer_shift_out)
2386 {
2387         unsigned int mask, shift;
2388         int x, i;
2389
2390         for (i = 0; i < ARRAY_SIZE(xfer_mode_classes); i++) {
2391                 shift = xfer_mode_classes[i].shift;
2392                 mask = ata_get_mode_mask(ap, shift);
2393
2394                 x = fgb(mask);
2395                 if (x >= 0) {
2396                         *xfer_mode_out = xfer_mode_classes[i].base + x;
2397                         *xfer_shift_out = shift;
2398                         return 0;
2399                 }
2400         }
2401
2402         return -1;
2403 }
2404
2405 /**
2406  *      ata_dev_set_xfermode - Issue SET FEATURES - XFER MODE command
2407  *      @ap: Port associated with device @dev
2408  *      @dev: Device to which command will be sent
2409  *
2410  *      Issue SET FEATURES - XFER MODE command to device @dev
2411  *      on port @ap.
2412  *
2413  *      LOCKING:
2414  *      PCI/etc. bus probe sem.
2415  */
2416
2417 static void ata_dev_set_xfermode(struct ata_port *ap, struct ata_device *dev)
2418 {
2419         struct ata_taskfile tf;
2420
2421         /* set up set-features taskfile */
2422         DPRINTK("set features - xfer mode\n");
2423
2424         ata_tf_init(ap, &tf, dev->devno);
2425         tf.command = ATA_CMD_SET_FEATURES;
2426         tf.feature = SETFEATURES_XFER;
2427         tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
2428         tf.protocol = ATA_PROT_NODATA;
2429         tf.nsect = dev->xfer_mode;
2430
2431         if (ata_exec_internal(ap, dev, &tf, DMA_NONE, NULL, 0)) {
2432                 printk(KERN_ERR "ata%u: failed to set xfermode, disabled\n",
2433                        ap->id);
2434                 ata_port_disable(ap);
2435         }
2436
2437         DPRINTK("EXIT\n");
2438 }
2439
2440 /**
2441  *      ata_dev_reread_id - Reread the device identify device info
2442  *      @ap: port where the device is
2443  *      @dev: device to reread the identify device info
2444  *
2445  *      LOCKING:
2446  */
2447
2448 static void ata_dev_reread_id(struct ata_port *ap, struct ata_device *dev)
2449 {
2450         struct ata_taskfile tf;
2451
2452         ata_tf_init(ap, &tf, dev->devno);
2453
2454         if (dev->class == ATA_DEV_ATA) {
2455                 tf.command = ATA_CMD_ID_ATA;
2456                 DPRINTK("do ATA identify\n");
2457         } else {
2458                 tf.command = ATA_CMD_ID_ATAPI;
2459                 DPRINTK("do ATAPI identify\n");
2460         }
2461
2462         tf.flags |= ATA_TFLAG_DEVICE;
2463         tf.protocol = ATA_PROT_PIO;
2464
2465         if (ata_exec_internal(ap, dev, &tf, DMA_FROM_DEVICE,
2466                               dev->id, sizeof(dev->id)))
2467                 goto err_out;
2468
2469         swap_buf_le16(dev->id, ATA_ID_WORDS);
2470
2471         ata_dump_id(dev);
2472
2473         DPRINTK("EXIT\n");
2474
2475         return;
2476 err_out:
2477         printk(KERN_ERR "ata%u: failed to reread ID, disabled\n", ap->id);
2478         ata_port_disable(ap);
2479 }
2480
2481 /**
2482  *      ata_dev_init_params - Issue INIT DEV PARAMS command
2483  *      @ap: Port associated with device @dev
2484  *      @dev: Device to which command will be sent
2485  *
2486  *      LOCKING:
2487  */
2488
2489 static void ata_dev_init_params(struct ata_port *ap, struct ata_device *dev)
2490 {
2491         struct ata_taskfile tf;
2492         u16 sectors = dev->id[6];
2493         u16 heads   = dev->id[3];
2494
2495         /* Number of sectors per track 1-255. Number of heads 1-16 */
2496         if (sectors < 1 || sectors > 255 || heads < 1 || heads > 16)
2497                 return;
2498
2499         /* set up init dev params taskfile */
2500         DPRINTK("init dev params \n");
2501
2502         ata_tf_init(ap, &tf, dev->devno);
2503         tf.command = ATA_CMD_INIT_DEV_PARAMS;
2504         tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
2505         tf.protocol = ATA_PROT_NODATA;
2506         tf.nsect = sectors;
2507         tf.device |= (heads - 1) & 0x0f; /* max head = num. of heads - 1 */
2508
2509         if (ata_exec_internal(ap, dev, &tf, DMA_NONE, NULL, 0)) {
2510                 printk(KERN_ERR "ata%u: failed to init parameters, disabled\n",
2511                        ap->id);
2512                 ata_port_disable(ap);
2513         }
2514
2515         DPRINTK("EXIT\n");
2516 }
2517
2518 /**
2519  *      ata_sg_clean - Unmap DMA memory associated with command
2520  *      @qc: Command containing DMA memory to be released
2521  *
2522  *      Unmap all mapped DMA memory associated with this command.
2523  *
2524  *      LOCKING:
2525  *      spin_lock_irqsave(host_set lock)
2526  */
2527
2528 static void ata_sg_clean(struct ata_queued_cmd *qc)
2529 {
2530         struct ata_port *ap = qc->ap;
2531         struct scatterlist *sg = qc->__sg;
2532         int dir = qc->dma_dir;
2533         void *pad_buf = NULL;
2534
2535         assert(qc->flags & ATA_QCFLAG_DMAMAP);
2536         assert(sg != NULL);
2537
2538         if (qc->flags & ATA_QCFLAG_SINGLE)
2539                 assert(qc->n_elem == 1);
2540
2541         VPRINTK("unmapping %u sg elements\n", qc->n_elem);
2542
2543         /* if we padded the buffer out to 32-bit bound, and data
2544          * xfer direction is from-device, we must copy from the
2545          * pad buffer back into the supplied buffer
2546          */
2547         if (qc->pad_len && !(qc->tf.flags & ATA_TFLAG_WRITE))
2548                 pad_buf = ap->pad + (qc->tag * ATA_DMA_PAD_SZ);
2549
2550         if (qc->flags & ATA_QCFLAG_SG) {
2551                 if (qc->n_elem)
2552                         dma_unmap_sg(ap->host_set->dev, sg, qc->n_elem, dir);
2553                 /* restore last sg */
2554                 sg[qc->orig_n_elem - 1].length += qc->pad_len;
2555                 if (pad_buf) {
2556                         struct scatterlist *psg = &qc->pad_sgent;
2557                         void *addr = kmap_atomic(psg->page, KM_IRQ0);
2558                         memcpy(addr + psg->offset, pad_buf, qc->pad_len);
2559                         kunmap_atomic(addr, KM_IRQ0);
2560                 }
2561         } else {
2562                 if (sg_dma_len(&sg[0]) > 0)
2563                         dma_unmap_single(ap->host_set->dev,
2564                                 sg_dma_address(&sg[0]), sg_dma_len(&sg[0]),
2565                                 dir);
2566                 /* restore sg */
2567                 sg->length += qc->pad_len;
2568                 if (pad_buf)
2569                         memcpy(qc->buf_virt + sg->length - qc->pad_len,
2570                                pad_buf, qc->pad_len);
2571         }
2572
2573         qc->flags &= ~ATA_QCFLAG_DMAMAP;
2574         qc->__sg = NULL;
2575 }
2576
2577 /**
2578  *      ata_fill_sg - Fill PCI IDE PRD table
2579  *      @qc: Metadata associated with taskfile to be transferred
2580  *
2581  *      Fill PCI IDE PRD (scatter-gather) table with segments
2582  *      associated with the current disk command.
2583  *
2584  *      LOCKING:
2585  *      spin_lock_irqsave(host_set lock)
2586  *
2587  */
2588 static void ata_fill_sg(struct ata_queued_cmd *qc)
2589 {
2590         struct ata_port *ap = qc->ap;
2591         struct scatterlist *sg;
2592         unsigned int idx;
2593
2594         assert(qc->__sg != NULL);
2595         assert(qc->n_elem > 0);
2596
2597         idx = 0;
2598         ata_for_each_sg(sg, qc) {
2599                 u32 addr, offset;
2600                 u32 sg_len, len;
2601
2602                 /* determine if physical DMA addr spans 64K boundary.
2603                  * Note h/w doesn't support 64-bit, so we unconditionally
2604                  * truncate dma_addr_t to u32.
2605                  */
2606                 addr = (u32) sg_dma_address(sg);
2607                 sg_len = sg_dma_len(sg);
2608
2609                 while (sg_len) {
2610                         offset = addr & 0xffff;
2611                         len = sg_len;
2612                         if ((offset + sg_len) > 0x10000)
2613                                 len = 0x10000 - offset;
2614
2615                         ap->prd[idx].addr = cpu_to_le32(addr);
2616                         ap->prd[idx].flags_len = cpu_to_le32(len & 0xffff);
2617                         VPRINTK("PRD[%u] = (0x%X, 0x%X)\n", idx, addr, len);
2618
2619                         idx++;
2620                         sg_len -= len;
2621                         addr += len;
2622                 }
2623         }
2624
2625         if (idx)
2626                 ap->prd[idx - 1].flags_len |= cpu_to_le32(ATA_PRD_EOT);
2627 }
2628 /**
2629  *      ata_check_atapi_dma - Check whether ATAPI DMA can be supported
2630  *      @qc: Metadata associated with taskfile to check
2631  *
2632  *      Allow low-level driver to filter ATA PACKET commands, returning
2633  *      a status indicating whether or not it is OK to use DMA for the
2634  *      supplied PACKET command.
2635  *
2636  *      LOCKING:
2637  *      spin_lock_irqsave(host_set lock)
2638  *
2639  *      RETURNS: 0 when ATAPI DMA can be used
2640  *               nonzero otherwise
2641  */
2642 int ata_check_atapi_dma(struct ata_queued_cmd *qc)
2643 {
2644         struct ata_port *ap = qc->ap;
2645         int rc = 0; /* Assume ATAPI DMA is OK by default */
2646
2647         if (ap->ops->check_atapi_dma)
2648                 rc = ap->ops->check_atapi_dma(qc);
2649
2650         return rc;
2651 }
2652 /**
2653  *      ata_qc_prep - Prepare taskfile for submission
2654  *      @qc: Metadata associated with taskfile to be prepared
2655  *
2656  *      Prepare ATA taskfile for submission.
2657  *
2658  *      LOCKING:
2659  *      spin_lock_irqsave(host_set lock)
2660  */
2661 void ata_qc_prep(struct ata_queued_cmd *qc)
2662 {
2663         if (!(qc->flags & ATA_QCFLAG_DMAMAP))
2664                 return;
2665
2666         ata_fill_sg(qc);
2667 }
2668
2669 /**
2670  *      ata_sg_init_one - Associate command with memory buffer
2671  *      @qc: Command to be associated
2672  *      @buf: Memory buffer
2673  *      @buflen: Length of memory buffer, in bytes.
2674  *
2675  *      Initialize the data-related elements of queued_cmd @qc
2676  *      to point to a single memory buffer, @buf of byte length @buflen.
2677  *
2678  *      LOCKING:
2679  *      spin_lock_irqsave(host_set lock)
2680  */
2681
2682 void ata_sg_init_one(struct ata_queued_cmd *qc, void *buf, unsigned int buflen)
2683 {
2684         struct scatterlist *sg;
2685
2686         qc->flags |= ATA_QCFLAG_SINGLE;
2687
2688         memset(&qc->sgent, 0, sizeof(qc->sgent));
2689         qc->__sg = &qc->sgent;
2690         qc->n_elem = 1;
2691         qc->orig_n_elem = 1;
2692         qc->buf_virt = buf;
2693
2694         sg = qc->__sg;
2695         sg_init_one(sg, buf, buflen);
2696 }
2697
2698 /**
2699  *      ata_sg_init - Associate command with scatter-gather table.
2700  *      @qc: Command to be associated
2701  *      @sg: Scatter-gather table.
2702  *      @n_elem: Number of elements in s/g table.
2703  *
2704  *      Initialize the data-related elements of queued_cmd @qc
2705  *      to point to a scatter-gather table @sg, containing @n_elem
2706  *      elements.
2707  *
2708  *      LOCKING:
2709  *      spin_lock_irqsave(host_set lock)
2710  */
2711
2712 void ata_sg_init(struct ata_queued_cmd *qc, struct scatterlist *sg,
2713                  unsigned int n_elem)
2714 {
2715         qc->flags |= ATA_QCFLAG_SG;
2716         qc->__sg = sg;
2717         qc->n_elem = n_elem;
2718         qc->orig_n_elem = n_elem;
2719 }
2720
2721 /**
2722  *      ata_sg_setup_one - DMA-map the memory buffer associated with a command.
2723  *      @qc: Command with memory buffer to be mapped.
2724  *
2725  *      DMA-map the memory buffer associated with queued_cmd @qc.
2726  *
2727  *      LOCKING:
2728  *      spin_lock_irqsave(host_set lock)
2729  *
2730  *      RETURNS:
2731  *      Zero on success, negative on error.
2732  */
2733
2734 static int ata_sg_setup_one(struct ata_queued_cmd *qc)
2735 {
2736         struct ata_port *ap = qc->ap;
2737         int dir = qc->dma_dir;
2738         struct scatterlist *sg = qc->__sg;
2739         dma_addr_t dma_address;
2740
2741         /* we must lengthen transfers to end on a 32-bit boundary */
2742         qc->pad_len = sg->length & 3;
2743         if (qc->pad_len) {
2744                 void *pad_buf = ap->pad + (qc->tag * ATA_DMA_PAD_SZ);
2745                 struct scatterlist *psg = &qc->pad_sgent;
2746
2747                 assert(qc->dev->class == ATA_DEV_ATAPI);
2748
2749                 memset(pad_buf, 0, ATA_DMA_PAD_SZ);
2750
2751                 if (qc->tf.flags & ATA_TFLAG_WRITE)
2752                         memcpy(pad_buf, qc->buf_virt + sg->length - qc->pad_len,
2753                                qc->pad_len);
2754
2755                 sg_dma_address(psg) = ap->pad_dma + (qc->tag * ATA_DMA_PAD_SZ);
2756                 sg_dma_len(psg) = ATA_DMA_PAD_SZ;
2757                 /* trim sg */
2758                 sg->length -= qc->pad_len;
2759
2760                 DPRINTK("padding done, sg->length=%u pad_len=%u\n",
2761                         sg->length, qc->pad_len);
2762         }
2763
2764         if (!sg->length) {
2765                 sg_dma_address(sg) = 0;
2766                 goto skip_map;
2767         }
2768
2769         dma_address = dma_map_single(ap->host_set->dev, qc->buf_virt,
2770                                      sg->length, dir);
2771         if (dma_mapping_error(dma_address)) {
2772                 /* restore sg */
2773                 sg->length += qc->pad_len;
2774                 return -1;
2775         }
2776
2777         sg_dma_address(sg) = dma_address;
2778 skip_map:
2779         sg_dma_len(sg) = sg->length;
2780
2781         DPRINTK("mapped buffer of %d bytes for %s\n", sg_dma_len(sg),
2782                 qc->tf.flags & ATA_TFLAG_WRITE ? "write" : "read");
2783
2784         return 0;
2785 }
2786
2787 /**
2788  *      ata_sg_setup - DMA-map the scatter-gather table associated with a command.
2789  *      @qc: Command with scatter-gather table to be mapped.
2790  *
2791  *      DMA-map the scatter-gather table associated with queued_cmd @qc.
2792  *
2793  *      LOCKING:
2794  *      spin_lock_irqsave(host_set lock)
2795  *
2796  *      RETURNS:
2797  *      Zero on success, negative on error.
2798  *
2799  */
2800
2801 static int ata_sg_setup(struct ata_queued_cmd *qc)
2802 {
2803         struct ata_port *ap = qc->ap;
2804         struct scatterlist *sg = qc->__sg;
2805         struct scatterlist *lsg = &sg[qc->n_elem - 1];
2806         int n_elem, pre_n_elem, dir, trim_sg = 0;
2807
2808         VPRINTK("ENTER, ata%u\n", ap->id);
2809         assert(qc->flags & ATA_QCFLAG_SG);
2810
2811         /* we must lengthen transfers to end on a 32-bit boundary */
2812         qc->pad_len = lsg->length & 3;
2813         if (qc->pad_len) {
2814                 void *pad_buf = ap->pad + (qc->tag * ATA_DMA_PAD_SZ);
2815                 struct scatterlist *psg = &qc->pad_sgent;
2816                 unsigned int offset;
2817
2818                 assert(qc->dev->class == ATA_DEV_ATAPI);
2819
2820                 memset(pad_buf, 0, ATA_DMA_PAD_SZ);
2821
2822                 /*
2823                  * psg->page/offset are used to copy to-be-written
2824                  * data in this function or read data in ata_sg_clean.
2825                  */
2826                 offset = lsg->offset + lsg->length - qc->pad_len;
2827                 psg->page = nth_page(lsg->page, offset >> PAGE_SHIFT);
2828                 psg->offset = offset_in_page(offset);
2829
2830                 if (qc->tf.flags & ATA_TFLAG_WRITE) {
2831                         void *addr = kmap_atomic(psg->page, KM_IRQ0);
2832                         memcpy(pad_buf, addr + psg->offset, qc->pad_len);
2833                         kunmap_atomic(addr, KM_IRQ0);
2834                 }
2835
2836                 sg_dma_address(psg) = ap->pad_dma + (qc->tag * ATA_DMA_PAD_SZ);
2837                 sg_dma_len(psg) = ATA_DMA_PAD_SZ;
2838                 /* trim last sg */
2839                 lsg->length -= qc->pad_len;
2840                 if (lsg->length == 0)
2841                         trim_sg = 1;
2842
2843                 DPRINTK("padding done, sg[%d].length=%u pad_len=%u\n",
2844                         qc->n_elem - 1, lsg->length, qc->pad_len);
2845         }
2846
2847         pre_n_elem = qc->n_elem;
2848         if (trim_sg && pre_n_elem)
2849                 pre_n_elem--;
2850
2851         if (!pre_n_elem) {
2852                 n_elem = 0;
2853                 goto skip_map;
2854         }
2855
2856         dir = qc->dma_dir;
2857         n_elem = dma_map_sg(ap->host_set->dev, sg, pre_n_elem, dir);
2858         if (n_elem < 1) {
2859                 /* restore last sg */
2860                 lsg->length += qc->pad_len;
2861                 return -1;
2862         }
2863
2864         DPRINTK("%d sg elements mapped\n", n_elem);
2865
2866 skip_map:
2867         qc->n_elem = n_elem;
2868
2869         return 0;
2870 }
2871
2872 /**
2873  *      ata_poll_qc_complete - turn irq back on and finish qc
2874  *      @qc: Command to complete
2875  *      @err_mask: ATA status register content
2876  *
2877  *      LOCKING:
2878  *      None.  (grabs host lock)
2879  */
2880
2881 void ata_poll_qc_complete(struct ata_queued_cmd *qc)
2882 {
2883         struct ata_port *ap = qc->ap;
2884         unsigned long flags;
2885
2886         spin_lock_irqsave(&ap->host_set->lock, flags);
2887         ap->flags &= ~ATA_FLAG_NOINTR;
2888         ata_irq_on(ap);
2889         ata_qc_complete(qc);
2890         spin_unlock_irqrestore(&ap->host_set->lock, flags);
2891 }
2892
2893 /**
2894  *      ata_pio_poll -
2895  *      @ap: the target ata_port
2896  *
2897  *      LOCKING:
2898  *      None.  (executing in kernel thread context)
2899  *
2900  *      RETURNS:
2901  *      timeout value to use
2902  */
2903
2904 static unsigned long ata_pio_poll(struct ata_port *ap)
2905 {
2906         struct ata_queued_cmd *qc;
2907         u8 status;
2908         unsigned int poll_state = HSM_ST_UNKNOWN;
2909         unsigned int reg_state = HSM_ST_UNKNOWN;
2910
2911         qc = ata_qc_from_tag(ap, ap->active_tag);
2912         assert(qc != NULL);
2913
2914         switch (ap->hsm_task_state) {
2915         case HSM_ST:
2916         case HSM_ST_POLL:
2917                 poll_state = HSM_ST_POLL;
2918                 reg_state = HSM_ST;
2919                 break;
2920         case HSM_ST_LAST:
2921         case HSM_ST_LAST_POLL:
2922                 poll_state = HSM_ST_LAST_POLL;
2923                 reg_state = HSM_ST_LAST;
2924                 break;
2925         default:
2926                 BUG();
2927                 break;
2928         }
2929
2930         status = ata_chk_status(ap);
2931         if (status & ATA_BUSY) {
2932                 if (time_after(jiffies, ap->pio_task_timeout)) {
2933                         qc->err_mask |= AC_ERR_TIMEOUT;
2934                         ap->hsm_task_state = HSM_ST_TMOUT;
2935                         return 0;
2936                 }
2937                 ap->hsm_task_state = poll_state;
2938                 return ATA_SHORT_PAUSE;
2939         }
2940
2941         ap->hsm_task_state = reg_state;
2942         return 0;
2943 }
2944
2945 /**
2946  *      ata_pio_complete - check if drive is busy or idle
2947  *      @ap: the target ata_port
2948  *
2949  *      LOCKING:
2950  *      None.  (executing in kernel thread context)
2951  *
2952  *      RETURNS:
2953  *      Non-zero if qc completed, zero otherwise.
2954  */
2955
2956 static int ata_pio_complete (struct ata_port *ap)
2957 {
2958         struct ata_queued_cmd *qc;
2959         u8 drv_stat;
2960
2961         /*
2962          * This is purely heuristic.  This is a fast path.  Sometimes when
2963          * we enter, BSY will be cleared in a chk-status or two.  If not,
2964          * the drive is probably seeking or something.  Snooze for a couple
2965          * msecs, then chk-status again.  If still busy, fall back to
2966          * HSM_ST_POLL state.
2967          */
2968         drv_stat = ata_busy_wait(ap, ATA_BUSY, 10);
2969         if (drv_stat & ATA_BUSY) {
2970                 msleep(2);
2971                 drv_stat = ata_busy_wait(ap, ATA_BUSY, 10);
2972                 if (drv_stat & ATA_BUSY) {
2973                         ap->hsm_task_state = HSM_ST_LAST_POLL;
2974                         ap->pio_task_timeout = jiffies + ATA_TMOUT_PIO;
2975                         return 0;
2976                 }
2977         }
2978
2979         qc = ata_qc_from_tag(ap, ap->active_tag);
2980         assert(qc != NULL);
2981
2982         drv_stat = ata_wait_idle(ap);
2983         if (!ata_ok(drv_stat)) {
2984                 qc->err_mask |= __ac_err_mask(drv_stat);
2985                 ap->hsm_task_state = HSM_ST_ERR;
2986                 return 0;
2987         }
2988
2989         ap->hsm_task_state = HSM_ST_IDLE;
2990
2991         assert(qc->err_mask == 0);
2992         ata_poll_qc_complete(qc);
2993
2994         /* another command may start at this point */
2995
2996         return 1;
2997 }
2998
2999
3000 /**
3001  *      swap_buf_le16 - swap halves of 16-words in place
3002  *      @buf:  Buffer to swap
3003  *      @buf_words:  Number of 16-bit words in buffer.
3004  *
3005  *      Swap halves of 16-bit words if needed to convert from
3006  *      little-endian byte order to native cpu byte order, or
3007  *      vice-versa.
3008  *
3009  *      LOCKING:
3010  *      Inherited from caller.
3011  */
3012 void swap_buf_le16(u16 *buf, unsigned int buf_words)
3013 {
3014 #ifdef __BIG_ENDIAN
3015         unsigned int i;
3016
3017         for (i = 0; i < buf_words; i++)
3018                 buf[i] = le16_to_cpu(buf[i]);
3019 #endif /* __BIG_ENDIAN */
3020 }
3021
3022 /**
3023  *      ata_mmio_data_xfer - Transfer data by MMIO
3024  *      @ap: port to read/write
3025  *      @buf: data buffer
3026  *      @buflen: buffer length
3027  *      @write_data: read/write
3028  *
3029  *      Transfer data from/to the device data register by MMIO.
3030  *
3031  *      LOCKING:
3032  *      Inherited from caller.
3033  */
3034
3035 static void ata_mmio_data_xfer(struct ata_port *ap, unsigned char *buf,
3036                                unsigned int buflen, int write_data)
3037 {
3038         unsigned int i;
3039         unsigned int words = buflen >> 1;
3040         u16 *buf16 = (u16 *) buf;
3041         void __iomem *mmio = (void __iomem *)ap->ioaddr.data_addr;
3042
3043         /* Transfer multiple of 2 bytes */
3044         if (write_data) {
3045                 for (i = 0; i < words; i++)
3046                         writew(le16_to_cpu(buf16[i]), mmio);
3047         } else {
3048                 for (i = 0; i < words; i++)
3049                         buf16[i] = cpu_to_le16(readw(mmio));
3050         }
3051
3052         /* Transfer trailing 1 byte, if any. */
3053         if (unlikely(buflen & 0x01)) {
3054                 u16 align_buf[1] = { 0 };
3055                 unsigned char *trailing_buf = buf + buflen - 1;
3056
3057                 if (write_data) {
3058                         memcpy(align_buf, trailing_buf, 1);
3059                         writew(le16_to_cpu(align_buf[0]), mmio);
3060                 } else {
3061                         align_buf[0] = cpu_to_le16(readw(mmio));
3062                         memcpy(trailing_buf, align_buf, 1);
3063                 }
3064         }
3065 }
3066
3067 /**
3068  *      ata_pio_data_xfer - Transfer data by PIO
3069  *      @ap: port to read/write
3070  *      @buf: data buffer
3071  *      @buflen: buffer length
3072  *      @write_data: read/write
3073  *
3074  *      Transfer data from/to the device data register by PIO.
3075  *
3076  *      LOCKING:
3077  *      Inherited from caller.
3078  */
3079
3080 static void ata_pio_data_xfer(struct ata_port *ap, unsigned char *buf,
3081                               unsigned int buflen, int write_data)
3082 {
3083         unsigned int words = buflen >> 1;
3084
3085         /* Transfer multiple of 2 bytes */
3086         if (write_data)
3087                 outsw(ap->ioaddr.data_addr, buf, words);
3088         else
3089                 insw(ap->ioaddr.data_addr, buf, words);
3090
3091         /* Transfer trailing 1 byte, if any. */
3092         if (unlikely(buflen & 0x01)) {
3093                 u16 align_buf[1] = { 0 };
3094                 unsigned char *trailing_buf = buf + buflen - 1;
3095
3096                 if (write_data) {
3097                         memcpy(align_buf, trailing_buf, 1);
3098                         outw(le16_to_cpu(align_buf[0]), ap->ioaddr.data_addr);
3099                 } else {
3100                         align_buf[0] = cpu_to_le16(inw(ap->ioaddr.data_addr));
3101                         memcpy(trailing_buf, align_buf, 1);
3102                 }
3103         }
3104 }
3105
3106 /**
3107  *      ata_data_xfer - Transfer data from/to the data register.
3108  *      @ap: port to read/write
3109  *      @buf: data buffer
3110  *      @buflen: buffer length
3111  *      @do_write: read/write
3112  *
3113  *      Transfer data from/to the device data register.
3114  *
3115  *      LOCKING:
3116  *      Inherited from caller.
3117  */
3118
3119 static void ata_data_xfer(struct ata_port *ap, unsigned char *buf,
3120                           unsigned int buflen, int do_write)
3121 {
3122         /* Make the crap hardware pay the costs not the good stuff */
3123         if (unlikely(ap->flags & ATA_FLAG_IRQ_MASK)) {
3124                 unsigned long flags;
3125                 local_irq_save(flags);
3126                 if (ap->flags & ATA_FLAG_MMIO)
3127                         ata_mmio_data_xfer(ap, buf, buflen, do_write);
3128                 else
3129                         ata_pio_data_xfer(ap, buf, buflen, do_write);
3130                 local_irq_restore(flags);
3131         } else {
3132                 if (ap->flags & ATA_FLAG_MMIO)
3133                         ata_mmio_data_xfer(ap, buf, buflen, do_write);
3134                 else
3135                         ata_pio_data_xfer(ap, buf, buflen, do_write);
3136         }
3137 }
3138
3139 /**
3140  *      ata_pio_sector - Transfer ATA_SECT_SIZE (512 bytes) of data.
3141  *      @qc: Command on going
3142  *
3143  *      Transfer ATA_SECT_SIZE of data from/to the ATA device.
3144  *
3145  *      LOCKING:
3146  *      Inherited from caller.
3147  */
3148
3149 static void ata_pio_sector(struct ata_queued_cmd *qc)
3150 {
3151         int do_write = (qc->tf.flags & ATA_TFLAG_WRITE);
3152         struct scatterlist *sg = qc->__sg;
3153         struct ata_port *ap = qc->ap;
3154         struct page *page;
3155         unsigned int offset;
3156         unsigned char *buf;
3157
3158         if (qc->cursect == (qc->nsect - 1))
3159                 ap->hsm_task_state = HSM_ST_LAST;
3160
3161         page = sg[qc->cursg].page;
3162         offset = sg[qc->cursg].offset + qc->cursg_ofs * ATA_SECT_SIZE;
3163
3164         /* get the current page and offset */
3165         page = nth_page(page, (offset >> PAGE_SHIFT));
3166         offset %= PAGE_SIZE;
3167
3168         buf = kmap(page) + offset;
3169
3170         qc->cursect++;
3171         qc->cursg_ofs++;
3172
3173         if ((qc->cursg_ofs * ATA_SECT_SIZE) == (&sg[qc->cursg])->length) {
3174                 qc->cursg++;
3175                 qc->cursg_ofs = 0;
3176         }
3177
3178         DPRINTK("data %s\n", qc->tf.flags & ATA_TFLAG_WRITE ? "write" : "read");
3179
3180         /* do the actual data transfer */
3181         do_write = (qc->tf.flags & ATA_TFLAG_WRITE);
3182         ata_data_xfer(ap, buf, ATA_SECT_SIZE, do_write);
3183
3184         kunmap(page);
3185 }
3186
3187 /**
3188  *      __atapi_pio_bytes - Transfer data from/to the ATAPI device.
3189  *      @qc: Command on going
3190  *      @bytes: number of bytes
3191  *
3192  *      Transfer Transfer data from/to the ATAPI device.
3193  *
3194  *      LOCKING:
3195  *      Inherited from caller.
3196  *
3197  */
3198
3199 static void __atapi_pio_bytes(struct ata_queued_cmd *qc, unsigned int bytes)
3200 {
3201         int do_write = (qc->tf.flags & ATA_TFLAG_WRITE);
3202         struct scatterlist *sg = qc->__sg;
3203         struct ata_port *ap = qc->ap;
3204         struct page *page;
3205         unsigned char *buf;
3206         unsigned int offset, count;
3207
3208         if (qc->curbytes + bytes >= qc->nbytes)
3209                 ap->hsm_task_state = HSM_ST_LAST;
3210
3211 next_sg:
3212         if (unlikely(qc->cursg >= qc->n_elem)) {
3213                 /*
3214                  * The end of qc->sg is reached and the device expects
3215                  * more data to transfer. In order not to overrun qc->sg
3216                  * and fulfill length specified in the byte count register,
3217                  *    - for read case, discard trailing data from the device
3218                  *    - for write case, padding zero data to the device
3219                  */
3220                 u16 pad_buf[1] = { 0 };
3221                 unsigned int words = bytes >> 1;
3222                 unsigned int i;
3223
3224                 if (words) /* warning if bytes > 1 */
3225                         printk(KERN_WARNING "ata%u: %u bytes trailing data\n",
3226                                ap->id, bytes);
3227
3228                 for (i = 0; i < words; i++)
3229                         ata_data_xfer(ap, (unsigned char*)pad_buf, 2, do_write);
3230
3231                 ap->hsm_task_state = HSM_ST_LAST;
3232                 return;
3233         }
3234
3235         sg = &qc->__sg[qc->cursg];
3236
3237         page = sg->page;
3238         offset = sg->offset + qc->cursg_ofs;
3239
3240         /* get the current page and offset */
3241         page = nth_page(page, (offset >> PAGE_SHIFT));
3242         offset %= PAGE_SIZE;
3243
3244         /* don't overrun current sg */
3245         count = min(sg->length - qc->cursg_ofs, bytes);
3246
3247         /* don't cross page boundaries */
3248         count = min(count, (unsigned int)PAGE_SIZE - offset);
3249
3250         buf = kmap(page) + offset;
3251
3252         bytes -= count;
3253         qc->curbytes += count;
3254         qc->cursg_ofs += count;
3255
3256         if (qc->cursg_ofs == sg->length) {
3257                 qc->cursg++;
3258                 qc->cursg_ofs = 0;
3259         }
3260
3261         DPRINTK("data %s\n", qc->tf.flags & ATA_TFLAG_WRITE ? "write" : "read");
3262
3263         /* do the actual data transfer */
3264         ata_data_xfer(ap, buf, count, do_write);
3265
3266         kunmap(page);
3267
3268         if (bytes)
3269                 goto next_sg;
3270 }
3271
3272 /**
3273  *      atapi_pio_bytes - Transfer data from/to the ATAPI device.
3274  *      @qc: Command on going
3275  *
3276  *      Transfer Transfer data from/to the ATAPI device.
3277  *
3278  *      LOCKING:
3279  *      Inherited from caller.
3280  */
3281
3282 static void atapi_pio_bytes(struct ata_queued_cmd *qc)
3283 {
3284         struct ata_port *ap = qc->ap;
3285         struct ata_device *dev = qc->dev;
3286         unsigned int ireason, bc_lo, bc_hi, bytes;
3287         int i_write, do_write = (qc->tf.flags & ATA_TFLAG_WRITE) ? 1 : 0;
3288
3289         ap->ops->tf_read(ap, &qc->tf);
3290         ireason = qc->tf.nsect;
3291         bc_lo = qc->tf.lbam;
3292         bc_hi = qc->tf.lbah;
3293         bytes = (bc_hi << 8) | bc_lo;
3294
3295         /* shall be cleared to zero, indicating xfer of data */
3296         if (ireason & (1 << 0))
3297                 goto err_out;
3298
3299         /* make sure transfer direction matches expected */
3300         i_write = ((ireason & (1 << 1)) == 0) ? 1 : 0;
3301         if (do_write != i_write)
3302                 goto err_out;
3303
3304         __atapi_pio_bytes(qc, bytes);
3305
3306         return;
3307
3308 err_out:
3309         printk(KERN_INFO "ata%u: dev %u: ATAPI check failed\n",
3310               ap->id, dev->devno);
3311         qc->err_mask |= AC_ERR_HSM;
3312         ap->hsm_task_state = HSM_ST_ERR;
3313 }
3314
3315 /**
3316  *      ata_pio_block - start PIO on a block
3317  *      @ap: the target ata_port
3318  *
3319  *      LOCKING:
3320  *      None.  (executing in kernel thread context)
3321  */
3322
3323 static void ata_pio_block(struct ata_port *ap)
3324 {
3325         struct ata_queued_cmd *qc;
3326         u8 status;
3327
3328         /*
3329          * This is purely heuristic.  This is a fast path.
3330          * Sometimes when we enter, BSY will be cleared in
3331          * a chk-status or two.  If not, the drive is probably seeking
3332          * or something.  Snooze for a couple msecs, then
3333          * chk-status again.  If still busy, fall back to
3334          * HSM_ST_POLL state.
3335          */
3336         status = ata_busy_wait(ap, ATA_BUSY, 5);
3337         if (status & ATA_BUSY) {
3338                 msleep(2);
3339                 status = ata_busy_wait(ap, ATA_BUSY, 10);
3340                 if (status & ATA_BUSY) {
3341                         ap->hsm_task_state = HSM_ST_POLL;
3342                         ap->pio_task_timeout = jiffies + ATA_TMOUT_PIO;
3343                         return;
3344                 }
3345         }
3346
3347         qc = ata_qc_from_tag(ap, ap->active_tag);
3348         assert(qc != NULL);
3349
3350         /* check error */
3351         if (status & (ATA_ERR | ATA_DF)) {
3352                 qc->err_mask |= AC_ERR_DEV;
3353                 ap->hsm_task_state = HSM_ST_ERR;
3354                 return;
3355         }
3356
3357         /* transfer data if any */
3358         if (is_atapi_taskfile(&qc->tf)) {
3359                 /* DRQ=0 means no more data to transfer */
3360                 if ((status & ATA_DRQ) == 0) {
3361                         ap->hsm_task_state = HSM_ST_LAST;
3362                         return;
3363                 }
3364
3365                 atapi_pio_bytes(qc);
3366         } else {
3367                 /* handle BSY=0, DRQ=0 as error */
3368                 if ((status & ATA_DRQ) == 0) {
3369                         qc->err_mask |= AC_ERR_HSM;
3370                         ap->hsm_task_state = HSM_ST_ERR;
3371                         return;
3372                 }
3373
3374                 ata_pio_sector(qc);
3375         }
3376 }
3377
3378 static void ata_pio_error(struct ata_port *ap)
3379 {
3380         struct ata_queued_cmd *qc;
3381
3382         printk(KERN_WARNING "ata%u: PIO error\n", ap->id);
3383
3384         qc = ata_qc_from_tag(ap, ap->active_tag);
3385         assert(qc != NULL);
3386
3387         /* make sure qc->err_mask is available to 
3388          * know what's wrong and recover
3389          */
3390         assert(qc->err_mask);
3391
3392         ap->hsm_task_state = HSM_ST_IDLE;
3393
3394         ata_poll_qc_complete(qc);
3395 }
3396
3397 static void ata_pio_task(void *_data)
3398 {
3399         struct ata_port *ap = _data;
3400         unsigned long timeout;
3401         int qc_completed;
3402
3403 fsm_start:
3404         timeout = 0;
3405         qc_completed = 0;
3406
3407         switch (ap->hsm_task_state) {
3408         case HSM_ST_IDLE:
3409                 return;
3410
3411         case HSM_ST:
3412                 ata_pio_block(ap);
3413                 break;
3414
3415         case HSM_ST_LAST:
3416                 qc_completed = ata_pio_complete(ap);
3417                 break;
3418
3419         case HSM_ST_POLL:
3420         case HSM_ST_LAST_POLL:
3421                 timeout = ata_pio_poll(ap);
3422                 break;
3423
3424         case HSM_ST_TMOUT:
3425         case HSM_ST_ERR:
3426                 ata_pio_error(ap);
3427                 return;
3428         }
3429
3430         if (timeout)
3431                 ata_queue_delayed_pio_task(ap, timeout);
3432         else if (!qc_completed)
3433                 goto fsm_start;
3434 }
3435
3436 /**
3437  *      ata_qc_timeout - Handle timeout of queued command
3438  *      @qc: Command that timed out
3439  *
3440  *      Some part of the kernel (currently, only the SCSI layer)
3441  *      has noticed that the active command on port @ap has not
3442  *      completed after a specified length of time.  Handle this
3443  *      condition by disabling DMA (if necessary) and completing
3444  *      transactions, with error if necessary.
3445  *
3446  *      This also handles the case of the "lost interrupt", where
3447  *      for some reason (possibly hardware bug, possibly driver bug)
3448  *      an interrupt was not delivered to the driver, even though the
3449  *      transaction completed successfully.
3450  *
3451  *      LOCKING:
3452  *      Inherited from SCSI layer (none, can sleep)
3453  */
3454
3455 static void ata_qc_timeout(struct ata_queued_cmd *qc)
3456 {
3457         struct ata_port *ap = qc->ap;
3458         struct ata_host_set *host_set = ap->host_set;
3459         u8 host_stat = 0, drv_stat;
3460         unsigned long flags;
3461
3462         DPRINTK("ENTER\n");
3463
3464         spin_lock_irqsave(&host_set->lock, flags);
3465
3466         switch (qc->tf.protocol) {
3467
3468         case ATA_PROT_DMA:
3469         case ATA_PROT_ATAPI_DMA:
3470                 host_stat = ap->ops->bmdma_status(ap);
3471
3472                 /* before we do anything else, clear DMA-Start bit */
3473                 ap->ops->bmdma_stop(qc);
3474
3475                 /* fall through */
3476
3477         default:
3478                 ata_altstatus(ap);
3479                 drv_stat = ata_chk_status(ap);
3480
3481                 /* ack bmdma irq events */
3482                 ap->ops->irq_clear(ap);
3483
3484                 printk(KERN_ERR "ata%u: command 0x%x timeout, stat 0x%x host_stat 0x%x\n",
3485                        ap->id, qc->tf.command, drv_stat, host_stat);
3486
3487                 /* complete taskfile transaction */
3488                 qc->err_mask |= ac_err_mask(drv_stat);
3489                 break;
3490         }
3491
3492         spin_unlock_irqrestore(&host_set->lock, flags);
3493
3494         ata_eh_qc_complete(qc);
3495
3496         DPRINTK("EXIT\n");
3497 }
3498
3499 /**
3500  *      ata_eng_timeout - Handle timeout of queued command
3501  *      @ap: Port on which timed-out command is active
3502  *
3503  *      Some part of the kernel (currently, only the SCSI layer)
3504  *      has noticed that the active command on port @ap has not
3505  *      completed after a specified length of time.  Handle this
3506  *      condition by disabling DMA (if necessary) and completing
3507  *      transactions, with error if necessary.
3508  *
3509  *      This also handles the case of the "lost interrupt", where
3510  *      for some reason (possibly hardware bug, possibly driver bug)
3511  *      an interrupt was not delivered to the driver, even though the
3512  *      transaction completed successfully.
3513  *
3514  *      LOCKING:
3515  *      Inherited from SCSI layer (none, can sleep)
3516  */
3517
3518 void ata_eng_timeout(struct ata_port *ap)
3519 {
3520         struct ata_queued_cmd *qc;
3521
3522         DPRINTK("ENTER\n");
3523
3524         qc = ata_qc_from_tag(ap, ap->active_tag);
3525         if (qc)
3526                 ata_qc_timeout(qc);
3527         else {
3528                 printk(KERN_ERR "ata%u: BUG: timeout without command\n",
3529                        ap->id);
3530                 goto out;
3531         }
3532
3533 out:
3534         DPRINTK("EXIT\n");
3535 }
3536
3537 /**
3538  *      ata_qc_new - Request an available ATA command, for queueing
3539  *      @ap: Port associated with device @dev
3540  *      @dev: Device from whom we request an available command structure
3541  *
3542  *      LOCKING:
3543  *      None.
3544  */
3545
3546 static struct ata_queued_cmd *ata_qc_new(struct ata_port *ap)
3547 {
3548         struct ata_queued_cmd *qc = NULL;
3549         unsigned int i;
3550
3551         for (i = 0; i < ATA_MAX_QUEUE; i++)
3552                 if (!test_and_set_bit(i, &ap->qactive)) {
3553                         qc = ata_qc_from_tag(ap, i);
3554                         break;
3555                 }
3556
3557         if (qc)
3558                 qc->tag = i;
3559
3560         return qc;
3561 }
3562
3563 /**
3564  *      ata_qc_new_init - Request an available ATA command, and initialize it
3565  *      @ap: Port associated with device @dev
3566  *      @dev: Device from whom we request an available command structure
3567  *
3568  *      LOCKING:
3569  *      None.
3570  */
3571
3572 struct ata_queued_cmd *ata_qc_new_init(struct ata_port *ap,
3573                                       struct ata_device *dev)
3574 {
3575         struct ata_queued_cmd *qc;
3576
3577         qc = ata_qc_new(ap);
3578         if (qc) {
3579                 qc->scsicmd = NULL;
3580                 qc->ap = ap;
3581                 qc->dev = dev;
3582
3583                 ata_qc_reinit(qc);
3584         }
3585
3586         return qc;
3587 }
3588
3589 /**
3590  *      ata_qc_free - free unused ata_queued_cmd
3591  *      @qc: Command to complete
3592  *
3593  *      Designed to free unused ata_queued_cmd object
3594  *      in case something prevents using it.
3595  *
3596  *      LOCKING:
3597  *      spin_lock_irqsave(host_set lock)
3598  */
3599 void ata_qc_free(struct ata_queued_cmd *qc)
3600 {
3601         struct ata_port *ap = qc->ap;
3602         unsigned int tag;
3603
3604         assert(qc != NULL);     /* ata_qc_from_tag _might_ return NULL */
3605
3606         qc->flags = 0;
3607         tag = qc->tag;
3608         if (likely(ata_tag_valid(tag))) {
3609                 if (tag == ap->active_tag)
3610                         ap->active_tag = ATA_TAG_POISON;
3611                 qc->tag = ATA_TAG_POISON;
3612                 clear_bit(tag, &ap->qactive);
3613         }
3614 }
3615
3616 /**
3617  *      ata_qc_complete - Complete an active ATA command
3618  *      @qc: Command to complete
3619  *      @err_mask: ATA Status register contents
3620  *
3621  *      Indicate to the mid and upper layers that an ATA
3622  *      command has completed, with either an ok or not-ok status.
3623  *
3624  *      LOCKING:
3625  *      spin_lock_irqsave(host_set lock)
3626  */
3627
3628 void ata_qc_complete(struct ata_queued_cmd *qc)
3629 {
3630         assert(qc != NULL);     /* ata_qc_from_tag _might_ return NULL */
3631         assert(qc->flags & ATA_QCFLAG_ACTIVE);
3632
3633         if (likely(qc->flags & ATA_QCFLAG_DMAMAP))
3634                 ata_sg_clean(qc);
3635
3636         /* atapi: mark qc as inactive to prevent the interrupt handler
3637          * from completing the command twice later, before the error handler
3638          * is called. (when rc != 0 and atapi request sense is needed)
3639          */
3640         qc->flags &= ~ATA_QCFLAG_ACTIVE;
3641
3642         /* call completion callback */
3643         qc->complete_fn(qc);
3644 }
3645
3646 static inline int ata_should_dma_map(struct ata_queued_cmd *qc)
3647 {
3648         struct ata_port *ap = qc->ap;
3649
3650         switch (qc->tf.protocol) {
3651         case ATA_PROT_DMA:
3652         case ATA_PROT_ATAPI_DMA:
3653                 return 1;
3654
3655         case ATA_PROT_ATAPI:
3656         case ATA_PROT_PIO:
3657         case ATA_PROT_PIO_MULT:
3658                 if (ap->flags & ATA_FLAG_PIO_DMA)
3659                         return 1;
3660
3661                 /* fall through */
3662
3663         default:
3664                 return 0;
3665         }
3666
3667         /* never reached */
3668 }
3669
3670 /**
3671  *      ata_qc_issue - issue taskfile to device
3672  *      @qc: command to issue to device
3673  *
3674  *      Prepare an ATA command to submission to device.
3675  *      This includes mapping the data into a DMA-able
3676  *      area, filling in the S/G table, and finally
3677  *      writing the taskfile to hardware, starting the command.
3678  *
3679  *      LOCKING:
3680  *      spin_lock_irqsave(host_set lock)
3681  *
3682  *      RETURNS:
3683  *      Zero on success, AC_ERR_* mask on failure
3684  */
3685
3686 unsigned int ata_qc_issue(struct ata_queued_cmd *qc)
3687 {
3688         struct ata_port *ap = qc->ap;
3689
3690         if (ata_should_dma_map(qc)) {
3691                 if (qc->flags & ATA_QCFLAG_SG) {
3692                         if (ata_sg_setup(qc))
3693                                 goto sg_err;
3694                 } else if (qc->flags & ATA_QCFLAG_SINGLE) {
3695                         if (ata_sg_setup_one(qc))
3696                                 goto sg_err;
3697                 }
3698         } else {
3699                 qc->flags &= ~ATA_QCFLAG_DMAMAP;
3700         }
3701
3702         ap->ops->qc_prep(qc);
3703
3704         qc->ap->active_tag = qc->tag;
3705         qc->flags |= ATA_QCFLAG_ACTIVE;
3706
3707         return ap->ops->qc_issue(qc);
3708
3709 sg_err:
3710         qc->flags &= ~ATA_QCFLAG_DMAMAP;
3711         return AC_ERR_SYSTEM;
3712 }
3713
3714
3715 /**
3716  *      ata_qc_issue_prot - issue taskfile to device in proto-dependent manner
3717  *      @qc: command to issue to device
3718  *
3719  *      Using various libata functions and hooks, this function
3720  *      starts an ATA command.  ATA commands are grouped into
3721  *      classes called "protocols", and issuing each type of protocol
3722  *      is slightly different.
3723  *
3724  *      May be used as the qc_issue() entry in ata_port_operations.
3725  *
3726  *      LOCKING:
3727  *      spin_lock_irqsave(host_set lock)
3728  *
3729  *      RETURNS:
3730  *      Zero on success, AC_ERR_* mask on failure
3731  */
3732
3733 unsigned int ata_qc_issue_prot(struct ata_queued_cmd *qc)
3734 {
3735         struct ata_port *ap = qc->ap;
3736
3737         ata_dev_select(ap, qc->dev->devno, 1, 0);
3738
3739         switch (qc->tf.protocol) {
3740         case ATA_PROT_NODATA:
3741                 ata_tf_to_host(ap, &qc->tf);
3742                 break;
3743
3744         case ATA_PROT_DMA:
3745                 ap->ops->tf_load(ap, &qc->tf);   /* load tf registers */
3746                 ap->ops->bmdma_setup(qc);           /* set up bmdma */
3747                 ap->ops->bmdma_start(qc);           /* initiate bmdma */
3748                 break;
3749
3750         case ATA_PROT_PIO: /* load tf registers, initiate polling pio */
3751                 ata_qc_set_polling(qc);
3752                 ata_tf_to_host(ap, &qc->tf);
3753                 ap->hsm_task_state = HSM_ST;
3754                 ata_queue_pio_task(ap);
3755                 break;
3756
3757         case ATA_PROT_ATAPI:
3758                 ata_qc_set_polling(qc);
3759                 ata_tf_to_host(ap, &qc->tf);
3760                 ata_queue_packet_task(ap);
3761                 break;
3762
3763         case ATA_PROT_ATAPI_NODATA:
3764                 ap->flags |= ATA_FLAG_NOINTR;
3765                 ata_tf_to_host(ap, &qc->tf);
3766                 ata_queue_packet_task(ap);
3767                 break;
3768
3769         case ATA_PROT_ATAPI_DMA:
3770                 ap->flags |= ATA_FLAG_NOINTR;
3771                 ap->ops->tf_load(ap, &qc->tf);   /* load tf registers */
3772                 ap->ops->bmdma_setup(qc);           /* set up bmdma */
3773                 ata_queue_packet_task(ap);
3774                 break;
3775
3776         default:
3777                 WARN_ON(1);
3778                 return AC_ERR_SYSTEM;
3779         }
3780
3781         return 0;
3782 }
3783
3784 /**
3785  *      ata_bmdma_setup_mmio - Set up PCI IDE BMDMA transaction
3786  *      @qc: Info associated with this ATA transaction.
3787  *
3788  *      LOCKING:
3789  *      spin_lock_irqsave(host_set lock)
3790  */
3791
3792 static void ata_bmdma_setup_mmio (struct ata_queued_cmd *qc)
3793 {
3794         struct ata_port *ap = qc->ap;
3795         unsigned int rw = (qc->tf.flags & ATA_TFLAG_WRITE);
3796         u8 dmactl;
3797         void __iomem *mmio = (void __iomem *) ap->ioaddr.bmdma_addr;
3798
3799         /* load PRD table addr. */
3800         mb();   /* make sure PRD table writes are visible to controller */
3801         writel(ap->prd_dma, mmio + ATA_DMA_TABLE_OFS);
3802
3803         /* specify data direction, triple-check start bit is clear */
3804         dmactl = readb(mmio + ATA_DMA_CMD);
3805         dmactl &= ~(ATA_DMA_WR | ATA_DMA_START);
3806         if (!rw)
3807                 dmactl |= ATA_DMA_WR;
3808         writeb(dmactl, mmio + ATA_DMA_CMD);
3809
3810         /* issue r/w command */
3811         ap->ops->exec_command(ap, &qc->tf);
3812 }
3813
3814 /**
3815  *      ata_bmdma_start_mmio - Start a PCI IDE BMDMA transaction
3816  *      @qc: Info associated with this ATA transaction.
3817  *
3818  *      LOCKING:
3819  *      spin_lock_irqsave(host_set lock)
3820  */
3821
3822 static void ata_bmdma_start_mmio (struct ata_queued_cmd *qc)
3823 {
3824         struct ata_port *ap = qc->ap;
3825         void __iomem *mmio = (void __iomem *) ap->ioaddr.bmdma_addr;
3826         u8 dmactl;
3827
3828         /* start host DMA transaction */
3829         dmactl = readb(mmio + ATA_DMA_CMD);
3830         writeb(dmactl | ATA_DMA_START, mmio + ATA_DMA_CMD);
3831
3832         /* Strictly, one may wish to issue a readb() here, to
3833          * flush the mmio write.  However, control also passes
3834          * to the hardware at this point, and it will interrupt
3835          * us when we are to resume control.  So, in effect,
3836          * we don't care when the mmio write flushes.
3837          * Further, a read of the DMA status register _immediately_
3838          * following the write may not be what certain flaky hardware
3839          * is expected, so I think it is best to not add a readb()
3840          * without first all the MMIO ATA cards/mobos.
3841          * Or maybe I'm just being paranoid.
3842          */
3843 }
3844
3845 /**
3846  *      ata_bmdma_setup_pio - Set up PCI IDE BMDMA transaction (PIO)
3847  *      @qc: Info associated with this ATA transaction.
3848  *
3849  *      LOCKING:
3850  *      spin_lock_irqsave(host_set lock)
3851  */
3852
3853 static void ata_bmdma_setup_pio (struct ata_queued_cmd *qc)
3854 {
3855         struct ata_port *ap = qc->ap;
3856         unsigned int rw = (qc->tf.flags & ATA_TFLAG_WRITE);
3857         u8 dmactl;
3858
3859         /* load PRD table addr. */
3860         outl(ap->prd_dma, ap->ioaddr.bmdma_addr + ATA_DMA_TABLE_OFS);
3861
3862         /* specify data direction, triple-check start bit is clear */
3863         dmactl = inb(ap->ioaddr.bmdma_addr + ATA_DMA_CMD);
3864         dmactl &= ~(ATA_DMA_WR | ATA_DMA_START);
3865         if (!rw)
3866                 dmactl |= ATA_DMA_WR;
3867         outb(dmactl, ap->ioaddr.bmdma_addr + ATA_DMA_CMD);
3868
3869         /* issue r/w command */
3870         ap->ops->exec_command(ap, &qc->tf);
3871 }
3872
3873 /**
3874  *      ata_bmdma_start_pio - Start a PCI IDE BMDMA transaction (PIO)
3875  *      @qc: Info associated with this ATA transaction.
3876  *
3877  *      LOCKING:
3878  *      spin_lock_irqsave(host_set lock)
3879  */
3880
3881 static void ata_bmdma_start_pio (struct ata_queued_cmd *qc)
3882 {
3883         struct ata_port *ap = qc->ap;
3884         u8 dmactl;
3885
3886         /* start host DMA transaction */
3887         dmactl = inb(ap->ioaddr.bmdma_addr + ATA_DMA_CMD);
3888         outb(dmactl | ATA_DMA_START,
3889              ap->ioaddr.bmdma_addr + ATA_DMA_CMD);
3890 }
3891
3892
3893 /**
3894  *      ata_bmdma_start - Start a PCI IDE BMDMA transaction
3895  *      @qc: Info associated with this ATA transaction.
3896  *
3897  *      Writes the ATA_DMA_START flag to the DMA command register.
3898  *
3899  *      May be used as the bmdma_start() entry in ata_port_operations.
3900  *
3901  *      LOCKING:
3902  *      spin_lock_irqsave(host_set lock)
3903  */
3904 void ata_bmdma_start(struct ata_queued_cmd *qc)
3905 {
3906         if (qc->ap->flags & ATA_FLAG_MMIO)
3907                 ata_bmdma_start_mmio(qc);
3908         else
3909                 ata_bmdma_start_pio(qc);
3910 }
3911
3912
3913 /**
3914  *      ata_bmdma_setup - Set up PCI IDE BMDMA transaction
3915  *      @qc: Info associated with this ATA transaction.
3916  *
3917  *      Writes address of PRD table to device's PRD Table Address
3918  *      register, sets the DMA control register, and calls
3919  *      ops->exec_command() to start the transfer.
3920  *
3921  *      May be used as the bmdma_setup() entry in ata_port_operations.
3922  *
3923  *      LOCKING:
3924  *      spin_lock_irqsave(host_set lock)
3925  */
3926 void ata_bmdma_setup(struct ata_queued_cmd *qc)
3927 {
3928         if (qc->ap->flags & ATA_FLAG_MMIO)
3929                 ata_bmdma_setup_mmio(qc);
3930         else
3931                 ata_bmdma_setup_pio(qc);
3932 }
3933
3934
3935 /**
3936  *      ata_bmdma_irq_clear - Clear PCI IDE BMDMA interrupt.
3937  *      @ap: Port associated with this ATA transaction.
3938  *
3939  *      Clear interrupt and error flags in DMA status register.
3940  *
3941  *      May be used as the irq_clear() entry in ata_port_operations.
3942  *
3943  *      LOCKING:
3944  *      spin_lock_irqsave(host_set lock)
3945  */
3946
3947 void ata_bmdma_irq_clear(struct ata_port *ap)
3948 {
3949     if (ap->flags & ATA_FLAG_MMIO) {
3950         void __iomem *mmio = ((void __iomem *) ap->ioaddr.bmdma_addr) + ATA_DMA_STATUS;
3951         writeb(readb(mmio), mmio);
3952     } else {
3953         unsigned long addr = ap->ioaddr.bmdma_addr + ATA_DMA_STATUS;
3954         outb(inb(addr), addr);
3955     }
3956
3957 }
3958
3959
3960 /**
3961  *      ata_bmdma_status - Read PCI IDE BMDMA status
3962  *      @ap: Port associated with this ATA transaction.
3963  *
3964  *      Read and return BMDMA status register.
3965  *
3966  *      May be used as the bmdma_status() entry in ata_port_operations.
3967  *
3968  *      LOCKING:
3969  *      spin_lock_irqsave(host_set lock)
3970  */
3971
3972 u8 ata_bmdma_status(struct ata_port *ap)
3973 {
3974         u8 host_stat;
3975         if (ap->flags & ATA_FLAG_MMIO) {
3976                 void __iomem *mmio = (void __iomem *) ap->ioaddr.bmdma_addr;
3977                 host_stat = readb(mmio + ATA_DMA_STATUS);
3978         } else
3979                 host_stat = inb(ap->ioaddr.bmdma_addr + ATA_DMA_STATUS);
3980         return host_stat;
3981 }
3982
3983
3984 /**
3985  *      ata_bmdma_stop - Stop PCI IDE BMDMA transfer
3986  *      @qc: Command we are ending DMA for
3987  *
3988  *      Clears the ATA_DMA_START flag in the dma control register
3989  *
3990  *      May be used as the bmdma_stop() entry in ata_port_operations.
3991  *
3992  *      LOCKING:
3993  *      spin_lock_irqsave(host_set lock)
3994  */
3995
3996 void ata_bmdma_stop(struct ata_queued_cmd *qc)
3997 {
3998         struct ata_port *ap = qc->ap;
3999         if (ap->flags & ATA_FLAG_MMIO) {
4000                 void __iomem *mmio = (void __iomem *) ap->ioaddr.bmdma_addr;
4001
4002                 /* clear start/stop bit */
4003                 writeb(readb(mmio + ATA_DMA_CMD) & ~ATA_DMA_START,
4004                         mmio + ATA_DMA_CMD);
4005         } else {
4006                 /* clear start/stop bit */
4007                 outb(inb(ap->ioaddr.bmdma_addr + ATA_DMA_CMD) & ~ATA_DMA_START,
4008                         ap->ioaddr.bmdma_addr + ATA_DMA_CMD);
4009         }
4010
4011         /* one-PIO-cycle guaranteed wait, per spec, for HDMA1:0 transition */
4012         ata_altstatus(ap);        /* dummy read */
4013 }
4014
4015 /**
4016  *      ata_host_intr - Handle host interrupt for given (port, task)
4017  *      @ap: Port on which interrupt arrived (possibly...)
4018  *      @qc: Taskfile currently active in engine
4019  *
4020  *      Handle host interrupt for given queued command.  Currently,
4021  *      only DMA interrupts are handled.  All other commands are
4022  *      handled via polling with interrupts disabled (nIEN bit).
4023  *
4024  *      LOCKING:
4025  *      spin_lock_irqsave(host_set lock)
4026  *
4027  *      RETURNS:
4028  *      One if interrupt was handled, zero if not (shared irq).
4029  */
4030
4031 inline unsigned int ata_host_intr (struct ata_port *ap,
4032                                    struct ata_queued_cmd *qc)
4033 {
4034         u8 status, host_stat;
4035
4036         switch (qc->tf.protocol) {
4037
4038         case ATA_PROT_DMA:
4039         case ATA_PROT_ATAPI_DMA:
4040         case ATA_PROT_ATAPI:
4041                 /* check status of DMA engine */
4042                 host_stat = ap->ops->bmdma_status(ap);
4043                 VPRINTK("ata%u: host_stat 0x%X\n", ap->id, host_stat);
4044
4045                 /* if it's not our irq... */
4046                 if (!(host_stat & ATA_DMA_INTR))
4047                         goto idle_irq;
4048
4049                 /* before we do anything else, clear DMA-Start bit */
4050                 ap->ops->bmdma_stop(qc);
4051
4052                 /* fall through */
4053
4054         case ATA_PROT_ATAPI_NODATA:
4055         case ATA_PROT_NODATA:
4056                 /* check altstatus */
4057                 status = ata_altstatus(ap);
4058                 if (status & ATA_BUSY)
4059                         goto idle_irq;
4060
4061                 /* check main status, clearing INTRQ */
4062                 status = ata_chk_status(ap);
4063                 if (unlikely(status & ATA_BUSY))
4064                         goto idle_irq;
4065                 DPRINTK("ata%u: protocol %d (dev_stat 0x%X)\n",
4066                         ap->id, qc->tf.protocol, status);
4067
4068                 /* ack bmdma irq events */
4069                 ap->ops->irq_clear(ap);
4070
4071                 /* complete taskfile transaction */
4072                 qc->err_mask |= ac_err_mask(status);
4073                 ata_qc_complete(qc);
4074                 break;
4075
4076         default:
4077                 goto idle_irq;
4078         }
4079
4080         return 1;       /* irq handled */
4081
4082 idle_irq:
4083         ap->stats.idle_irq++;
4084
4085 #ifdef ATA_IRQ_TRAP
4086         if ((ap->stats.idle_irq % 1000) == 0) {
4087                 handled = 1;
4088                 ata_irq_ack(ap, 0); /* debug trap */
4089                 printk(KERN_WARNING "ata%d: irq trap\n", ap->id);
4090         }
4091 #endif
4092         return 0;       /* irq not handled */
4093 }
4094
4095 /**
4096  *      ata_interrupt - Default ATA host interrupt handler
4097  *      @irq: irq line (unused)
4098  *      @dev_instance: pointer to our ata_host_set information structure
4099  *      @regs: unused
4100  *
4101  *      Default interrupt handler for PCI IDE devices.  Calls
4102  *      ata_host_intr() for each port that is not disabled.
4103  *
4104  *      LOCKING:
4105  *      Obtains host_set lock during operation.
4106  *
4107  *      RETURNS:
4108  *      IRQ_NONE or IRQ_HANDLED.
4109  */
4110
4111 irqreturn_t ata_interrupt (int irq, void *dev_instance, struct pt_regs *regs)
4112 {
4113         struct ata_host_set *host_set = dev_instance;
4114         unsigned int i;
4115         unsigned int handled = 0;
4116         unsigned long flags;
4117
4118         /* TODO: make _irqsave conditional on x86 PCI IDE legacy mode */
4119         spin_lock_irqsave(&host_set->lock, flags);
4120
4121         for (i = 0; i < host_set->n_ports; i++) {
4122                 struct ata_port *ap;
4123
4124                 ap = host_set->ports[i];
4125                 if (ap &&
4126                     !(ap->flags & (ATA_FLAG_PORT_DISABLED | ATA_FLAG_NOINTR))) {
4127                         struct ata_queued_cmd *qc;
4128
4129                         qc = ata_qc_from_tag(ap, ap->active_tag);
4130                         if (qc && (!(qc->tf.ctl & ATA_NIEN)) &&
4131                             (qc->flags & ATA_QCFLAG_ACTIVE))
4132                                 handled |= ata_host_intr(ap, qc);
4133                 }
4134         }
4135
4136         spin_unlock_irqrestore(&host_set->lock, flags);
4137
4138         return IRQ_RETVAL(handled);
4139 }
4140
4141 /**
4142  *      atapi_packet_task - Write CDB bytes to hardware
4143  *      @_data: Port to which ATAPI device is attached.
4144  *
4145  *      When device has indicated its readiness to accept
4146  *      a CDB, this function is called.  Send the CDB.
4147  *      If DMA is to be performed, exit immediately.
4148  *      Otherwise, we are in polling mode, so poll
4149  *      status under operation succeeds or fails.
4150  *
4151  *      LOCKING:
4152  *      Kernel thread context (may sleep)
4153  */
4154
4155 static void atapi_packet_task(void *_data)
4156 {
4157         struct ata_port *ap = _data;
4158         struct ata_queued_cmd *qc;
4159         u8 status;
4160
4161         qc = ata_qc_from_tag(ap, ap->active_tag);
4162         assert(qc != NULL);
4163         assert(qc->flags & ATA_QCFLAG_ACTIVE);
4164
4165         /* sleep-wait for BSY to clear */
4166         DPRINTK("busy wait\n");
4167         if (ata_busy_sleep(ap, ATA_TMOUT_CDB_QUICK, ATA_TMOUT_CDB)) {
4168                 qc->err_mask |= AC_ERR_TIMEOUT;
4169                 goto err_out;
4170         }
4171
4172         /* make sure DRQ is set */
4173         status = ata_chk_status(ap);
4174         if ((status & (ATA_BUSY | ATA_DRQ)) != ATA_DRQ) {
4175                 qc->err_mask |= AC_ERR_HSM;
4176                 goto err_out;
4177         }
4178
4179         /* send SCSI cdb */
4180         DPRINTK("send cdb\n");
4181         assert(ap->cdb_len >= 12);
4182
4183         if (qc->tf.protocol == ATA_PROT_ATAPI_DMA ||
4184             qc->tf.protocol == ATA_PROT_ATAPI_NODATA) {
4185                 unsigned long flags;
4186
4187                 /* Once we're done issuing command and kicking bmdma,
4188                  * irq handler takes over.  To not lose irq, we need
4189                  * to clear NOINTR flag before sending cdb, but
4190                  * interrupt handler shouldn't be invoked before we're
4191                  * finished.  Hence, the following locking.
4192                  */
4193                 spin_lock_irqsave(&ap->host_set->lock, flags);
4194                 ap->flags &= ~ATA_FLAG_NOINTR;
4195                 ata_data_xfer(ap, qc->cdb, ap->cdb_len, 1);
4196                 if (qc->tf.protocol == ATA_PROT_ATAPI_DMA)
4197                         ap->ops->bmdma_start(qc);       /* initiate bmdma */
4198                 spin_unlock_irqrestore(&ap->host_set->lock, flags);
4199         } else {
4200                 ata_data_xfer(ap, qc->cdb, ap->cdb_len, 1);
4201
4202                 /* PIO commands are handled by polling */
4203                 ap->hsm_task_state = HSM_ST;
4204                 ata_queue_pio_task(ap);
4205         }
4206
4207         return;
4208
4209 err_out:
4210         ata_poll_qc_complete(qc);
4211 }
4212
4213
4214 /**
4215  *      ata_port_start - Set port up for dma.
4216  *      @ap: Port to initialize
4217  *
4218  *      Called just after data structures for each port are
4219  *      initialized.  Allocates space for PRD table.
4220  *
4221  *      May be used as the port_start() entry in ata_port_operations.
4222  *
4223  *      LOCKING:
4224  *      Inherited from caller.
4225  */
4226
4227 /*
4228  * Execute a 'simple' command, that only consists of the opcode 'cmd' itself,
4229  * without filling any other registers
4230  */
4231 static int ata_do_simple_cmd(struct ata_port *ap, struct ata_device *dev,
4232                              u8 cmd)
4233 {
4234         struct ata_taskfile tf;
4235         int err;
4236
4237         ata_tf_init(ap, &tf, dev->devno);
4238
4239         tf.command = cmd;
4240         tf.flags |= ATA_TFLAG_DEVICE;
4241         tf.protocol = ATA_PROT_NODATA;
4242
4243         err = ata_exec_internal(ap, dev, &tf, DMA_NONE, NULL, 0);
4244         if (err)
4245                 printk(KERN_ERR "%s: ata command failed: %d\n",
4246                                 __FUNCTION__, err);
4247
4248         return err;
4249 }
4250
4251 static int ata_flush_cache(struct ata_port *ap, struct ata_device *dev)
4252 {
4253         u8 cmd;
4254
4255         if (!ata_try_flush_cache(dev))
4256                 return 0;
4257
4258         if (ata_id_has_flush_ext(dev->id))
4259                 cmd = ATA_CMD_FLUSH_EXT;
4260         else
4261                 cmd = ATA_CMD_FLUSH;
4262
4263         return ata_do_simple_cmd(ap, dev, cmd);
4264 }
4265
4266 static int ata_standby_drive(struct ata_port *ap, struct ata_device *dev)
4267 {
4268         return ata_do_simple_cmd(ap, dev, ATA_CMD_STANDBYNOW1);
4269 }
4270
4271 static int ata_start_drive(struct ata_port *ap, struct ata_device *dev)
4272 {
4273         return ata_do_simple_cmd(ap, dev, ATA_CMD_IDLEIMMEDIATE);
4274 }
4275
4276 /**
4277  *      ata_device_resume - wakeup a previously suspended devices
4278  *
4279  *      Kick the drive back into action, by sending it an idle immediate
4280  *      command and making sure its transfer mode matches between drive
4281  *      and host.
4282  *
4283  */
4284 int ata_device_resume(struct ata_port *ap, struct ata_device *dev)
4285 {
4286         if (ap->flags & ATA_FLAG_SUSPENDED) {
4287                 ap->flags &= ~ATA_FLAG_SUSPENDED;
4288                 ata_set_mode(ap);
4289         }
4290         if (!ata_dev_present(dev))
4291                 return 0;
4292         if (dev->class == ATA_DEV_ATA)
4293                 ata_start_drive(ap, dev);
4294
4295         return 0;
4296 }
4297
4298 /**
4299  *      ata_device_suspend - prepare a device for suspend
4300  *
4301  *      Flush the cache on the drive, if appropriate, then issue a
4302  *      standbynow command.
4303  *
4304  */
4305 int ata_device_suspend(struct ata_port *ap, struct ata_device *dev)
4306 {
4307         if (!ata_dev_present(dev))
4308                 return 0;
4309         if (dev->class == ATA_DEV_ATA)
4310                 ata_flush_cache(ap, dev);
4311
4312         ata_standby_drive(ap, dev);
4313         ap->flags |= ATA_FLAG_SUSPENDED;
4314         return 0;
4315 }
4316
4317 int ata_port_start (struct ata_port *ap)
4318 {
4319         struct device *dev = ap->host_set->dev;
4320         int rc;
4321
4322         ap->prd = dma_alloc_coherent(dev, ATA_PRD_TBL_SZ, &ap->prd_dma, GFP_KERNEL);
4323         if (!ap->prd)
4324                 return -ENOMEM;
4325
4326         rc = ata_pad_alloc(ap, dev);
4327         if (rc) {
4328                 dma_free_coherent(dev, ATA_PRD_TBL_SZ, ap->prd, ap->prd_dma);
4329                 return rc;
4330         }
4331
4332         DPRINTK("prd alloc, virt %p, dma %llx\n", ap->prd, (unsigned long long) ap->prd_dma);
4333
4334         return 0;
4335 }
4336
4337
4338 /**
4339  *      ata_port_stop - Undo ata_port_start()
4340  *      @ap: Port to shut down
4341  *
4342  *      Frees the PRD table.
4343  *
4344  *      May be used as the port_stop() entry in ata_port_operations.
4345  *
4346  *      LOCKING:
4347  *      Inherited from caller.
4348  */
4349
4350 void ata_port_stop (struct ata_port *ap)
4351 {
4352         struct device *dev = ap->host_set->dev;
4353
4354         dma_free_coherent(dev, ATA_PRD_TBL_SZ, ap->prd, ap->prd_dma);
4355         ata_pad_free(ap, dev);
4356 }
4357
4358 void ata_host_stop (struct ata_host_set *host_set)
4359 {
4360         if (host_set->mmio_base)
4361                 iounmap(host_set->mmio_base);
4362 }
4363
4364
4365 /**
4366  *      ata_host_remove - Unregister SCSI host structure with upper layers
4367  *      @ap: Port to unregister
4368  *      @do_unregister: 1 if we fully unregister, 0 to just stop the port
4369  *
4370  *      LOCKING:
4371  *      Inherited from caller.
4372  */
4373
4374 static void ata_host_remove(struct ata_port *ap, unsigned int do_unregister)
4375 {
4376         struct Scsi_Host *sh = ap->host;
4377
4378         DPRINTK("ENTER\n");
4379
4380         if (do_unregister)
4381                 scsi_remove_host(sh);
4382
4383         ap->ops->port_stop(ap);
4384 }
4385
4386 /**
4387  *      ata_host_init - Initialize an ata_port structure
4388  *      @ap: Structure to initialize
4389  *      @host: associated SCSI mid-layer structure
4390  *      @host_set: Collection of hosts to which @ap belongs
4391  *      @ent: Probe information provided by low-level driver
4392  *      @port_no: Port number associated with this ata_port
4393  *
4394  *      Initialize a new ata_port structure, and its associated
4395  *      scsi_host.
4396  *
4397  *      LOCKING:
4398  *      Inherited from caller.
4399  */
4400
4401 static void ata_host_init(struct ata_port *ap, struct Scsi_Host *host,
4402                           struct ata_host_set *host_set,
4403                           const struct ata_probe_ent *ent, unsigned int port_no)
4404 {
4405         unsigned int i;
4406
4407         host->max_id = 16;
4408         host->max_lun = 1;
4409         host->max_channel = 1;
4410         host->unique_id = ata_unique_id++;
4411         host->max_cmd_len = 12;
4412
4413         ap->flags = ATA_FLAG_PORT_DISABLED;
4414         ap->id = host->unique_id;
4415         ap->host = host;
4416         ap->ctl = ATA_DEVCTL_OBS;
4417         ap->host_set = host_set;
4418         ap->port_no = port_no;
4419         ap->hard_port_no =
4420                 ent->legacy_mode ? ent->hard_port_no : port_no;
4421         ap->pio_mask = ent->pio_mask;
4422         ap->mwdma_mask = ent->mwdma_mask;
4423         ap->udma_mask = ent->udma_mask;
4424         ap->flags |= ent->host_flags;
4425         ap->ops = ent->port_ops;
4426         ap->cbl = ATA_CBL_NONE;
4427         ap->active_tag = ATA_TAG_POISON;
4428         ap->last_ctl = 0xFF;
4429
4430         INIT_WORK(&ap->packet_task, atapi_packet_task, ap);
4431         INIT_WORK(&ap->pio_task, ata_pio_task, ap);
4432         INIT_LIST_HEAD(&ap->eh_done_q);
4433
4434         for (i = 0; i < ATA_MAX_DEVICES; i++)
4435                 ap->device[i].devno = i;
4436
4437 #ifdef ATA_IRQ_TRAP
4438         ap->stats.unhandled_irq = 1;
4439         ap->stats.idle_irq = 1;
4440 #endif
4441
4442         memcpy(&ap->ioaddr, &ent->port[port_no], sizeof(struct ata_ioports));
4443 }
4444
4445 /**
4446  *      ata_host_add - Attach low-level ATA driver to system
4447  *      @ent: Information provided by low-level driver
4448  *      @host_set: Collections of ports to which we add
4449  *      @port_no: Port number associated with this host
4450  *
4451  *      Attach low-level ATA driver to system.
4452  *
4453  *      LOCKING:
4454  *      PCI/etc. bus probe sem.
4455  *
4456  *      RETURNS:
4457  *      New ata_port on success, for NULL on error.
4458  */
4459
4460 static struct ata_port * ata_host_add(const struct ata_probe_ent *ent,
4461                                       struct ata_host_set *host_set,
4462                                       unsigned int port_no)
4463 {
4464         struct Scsi_Host *host;
4465         struct ata_port *ap;
4466         int rc;
4467
4468         DPRINTK("ENTER\n");
4469         host = scsi_host_alloc(ent->sht, sizeof(struct ata_port));
4470         if (!host)
4471                 return NULL;
4472
4473         ap = (struct ata_port *) &host->hostdata[0];
4474
4475         ata_host_init(ap, host, host_set, ent, port_no);
4476
4477         rc = ap->ops->port_start(ap);
4478         if (rc)
4479                 goto err_out;
4480
4481         return ap;
4482
4483 err_out:
4484         scsi_host_put(host);
4485         return NULL;
4486 }
4487
4488 /**
4489  *      ata_device_add - Register hardware device with ATA and SCSI layers
4490  *      @ent: Probe information describing hardware device to be registered
4491  *
4492  *      This function processes the information provided in the probe
4493  *      information struct @ent, allocates the necessary ATA and SCSI
4494  *      host information structures, initializes them, and registers
4495  *      everything with requisite kernel subsystems.
4496  *
4497  *      This function requests irqs, probes the ATA bus, and probes
4498  *      the SCSI bus.
4499  *
4500  *      LOCKING:
4501  *      PCI/etc. bus probe sem.
4502  *
4503  *      RETURNS:
4504  *      Number of ports registered.  Zero on error (no ports registered).
4505  */
4506
4507 int ata_device_add(const struct ata_probe_ent *ent)
4508 {
4509         unsigned int count = 0, i;
4510         struct device *dev = ent->dev;
4511         struct ata_host_set *host_set;
4512
4513         DPRINTK("ENTER\n");
4514         /* alloc a container for our list of ATA ports (buses) */
4515         host_set = kzalloc(sizeof(struct ata_host_set) +
4516                            (ent->n_ports * sizeof(void *)), GFP_KERNEL);
4517         if (!host_set)
4518                 return 0;
4519         spin_lock_init(&host_set->lock);
4520
4521         host_set->dev = dev;
4522         host_set->n_ports = ent->n_ports;
4523         host_set->irq = ent->irq;
4524         host_set->mmio_base = ent->mmio_base;
4525         host_set->private_data = ent->private_data;
4526         host_set->ops = ent->port_ops;
4527
4528         /* register each port bound to this device */
4529         for (i = 0; i < ent->n_ports; i++) {
4530                 struct ata_port *ap;
4531                 unsigned long xfer_mode_mask;
4532
4533                 ap = ata_host_add(ent, host_set, i);
4534                 if (!ap)
4535                         goto err_out;
4536
4537                 host_set->ports[i] = ap;
4538                 xfer_mode_mask =(ap->udma_mask << ATA_SHIFT_UDMA) |
4539                                 (ap->mwdma_mask << ATA_SHIFT_MWDMA) |
4540                                 (ap->pio_mask << ATA_SHIFT_PIO);
4541
4542                 /* print per-port info to dmesg */
4543                 printk(KERN_INFO "ata%u: %cATA max %s cmd 0x%lX ctl 0x%lX "
4544                                  "bmdma 0x%lX irq %lu\n",
4545                         ap->id,
4546                         ap->flags & ATA_FLAG_SATA ? 'S' : 'P',
4547                         ata_mode_string(xfer_mode_mask),
4548                         ap->ioaddr.cmd_addr,
4549                         ap->ioaddr.ctl_addr,
4550                         ap->ioaddr.bmdma_addr,
4551                         ent->irq);
4552
4553                 ata_chk_status(ap);
4554                 host_set->ops->irq_clear(ap);
4555                 count++;
4556         }
4557
4558         if (!count)
4559                 goto err_free_ret;
4560
4561         /* obtain irq, that is shared between channels */
4562         if (request_irq(ent->irq, ent->port_ops->irq_handler, ent->irq_flags,
4563                         DRV_NAME, host_set))
4564                 goto err_out;
4565
4566         /* perform each probe synchronously */
4567         DPRINTK("probe begin\n");
4568         for (i = 0; i < count; i++) {
4569                 struct ata_port *ap;
4570                 int rc;
4571
4572                 ap = host_set->ports[i];
4573
4574                 DPRINTK("ata%u: probe begin\n", ap->id);
4575                 rc = ata_bus_probe(ap);
4576                 DPRINTK("ata%u: probe end\n", ap->id);
4577
4578                 if (rc) {
4579                         /* FIXME: do something useful here?
4580                          * Current libata behavior will
4581                          * tear down everything when
4582                          * the module is removed
4583                          * or the h/w is unplugged.
4584                          */
4585                 }
4586
4587                 rc = scsi_add_host(ap->host, dev);
4588                 if (rc) {
4589                         printk(KERN_ERR "ata%u: scsi_add_host failed\n",
4590                                ap->id);
4591                         /* FIXME: do something useful here */
4592                         /* FIXME: handle unconditional calls to
4593                          * scsi_scan_host and ata_host_remove, below,
4594                          * at the very least
4595                          */
4596                 }
4597         }
4598
4599         /* probes are done, now scan each port's disk(s) */
4600         DPRINTK("probe begin\n");
4601         for (i = 0; i < count; i++) {
4602                 struct ata_port *ap = host_set->ports[i];
4603
4604                 ata_scsi_scan_host(ap);
4605         }
4606
4607         dev_set_drvdata(dev, host_set);
4608
4609         VPRINTK("EXIT, returning %u\n", ent->n_ports);
4610         return ent->n_ports; /* success */
4611
4612 err_out:
4613         for (i = 0; i < count; i++) {
4614                 ata_host_remove(host_set->ports[i], 1);
4615                 scsi_host_put(host_set->ports[i]->host);
4616         }
4617 err_free_ret:
4618         kfree(host_set);
4619         VPRINTK("EXIT, returning 0\n");
4620         return 0;
4621 }
4622
4623 /**
4624  *      ata_host_set_remove - PCI layer callback for device removal
4625  *      @host_set: ATA host set that was removed
4626  *
4627  *      Unregister all objects associated with this host set. Free those 
4628  *      objects.
4629  *
4630  *      LOCKING:
4631  *      Inherited from calling layer (may sleep).
4632  */
4633
4634 void ata_host_set_remove(struct ata_host_set *host_set)
4635 {
4636         struct ata_port *ap;
4637         unsigned int i;
4638
4639         for (i = 0; i < host_set->n_ports; i++) {
4640                 ap = host_set->ports[i];
4641                 scsi_remove_host(ap->host);
4642         }
4643
4644         free_irq(host_set->irq, host_set);
4645
4646         for (i = 0; i < host_set->n_ports; i++) {
4647                 ap = host_set->ports[i];
4648
4649                 ata_scsi_release(ap->host);
4650
4651                 if ((ap->flags & ATA_FLAG_NO_LEGACY) == 0) {
4652                         struct ata_ioports *ioaddr = &ap->ioaddr;
4653
4654                         if (ioaddr->cmd_addr == 0x1f0)
4655                                 release_region(0x1f0, 8);
4656                         else if (ioaddr->cmd_addr == 0x170)
4657                                 release_region(0x170, 8);
4658                 }
4659
4660                 scsi_host_put(ap->host);
4661         }
4662
4663         if (host_set->ops->host_stop)
4664                 host_set->ops->host_stop(host_set);
4665
4666         kfree(host_set);
4667 }
4668
4669 /**
4670  *      ata_scsi_release - SCSI layer callback hook for host unload
4671  *      @host: libata host to be unloaded
4672  *
4673  *      Performs all duties necessary to shut down a libata port...
4674  *      Kill port kthread, disable port, and release resources.
4675  *
4676  *      LOCKING:
4677  *      Inherited from SCSI layer.
4678  *
4679  *      RETURNS:
4680  *      One.
4681  */
4682
4683 int ata_scsi_release(struct Scsi_Host *host)
4684 {
4685         struct ata_port *ap = (struct ata_port *) &host->hostdata[0];
4686
4687         DPRINTK("ENTER\n");
4688
4689         ap->ops->port_disable(ap);
4690         ata_host_remove(ap, 0);
4691
4692         DPRINTK("EXIT\n");
4693         return 1;
4694 }
4695
4696 /**
4697  *      ata_std_ports - initialize ioaddr with standard port offsets.
4698  *      @ioaddr: IO address structure to be initialized
4699  *
4700  *      Utility function which initializes data_addr, error_addr,
4701  *      feature_addr, nsect_addr, lbal_addr, lbam_addr, lbah_addr,
4702  *      device_addr, status_addr, and command_addr to standard offsets
4703  *      relative to cmd_addr.
4704  *
4705  *      Does not set ctl_addr, altstatus_addr, bmdma_addr, or scr_addr.
4706  */
4707
4708 void ata_std_ports(struct ata_ioports *ioaddr)
4709 {
4710         ioaddr->data_addr = ioaddr->cmd_addr + ATA_REG_DATA;
4711         ioaddr->error_addr = ioaddr->cmd_addr + ATA_REG_ERR;
4712         ioaddr->feature_addr = ioaddr->cmd_addr + ATA_REG_FEATURE;
4713         ioaddr->nsect_addr = ioaddr->cmd_addr + ATA_REG_NSECT;
4714         ioaddr->lbal_addr = ioaddr->cmd_addr + ATA_REG_LBAL;
4715         ioaddr->lbam_addr = ioaddr->cmd_addr + ATA_REG_LBAM;
4716         ioaddr->lbah_addr = ioaddr->cmd_addr + ATA_REG_LBAH;
4717         ioaddr->device_addr = ioaddr->cmd_addr + ATA_REG_DEVICE;
4718         ioaddr->status_addr = ioaddr->cmd_addr + ATA_REG_STATUS;
4719         ioaddr->command_addr = ioaddr->cmd_addr + ATA_REG_CMD;
4720 }
4721
4722 static struct ata_probe_ent *
4723 ata_probe_ent_alloc(struct device *dev, const struct ata_port_info *port)
4724 {
4725         struct ata_probe_ent *probe_ent;
4726
4727         probe_ent = kzalloc(sizeof(*probe_ent), GFP_KERNEL);
4728         if (!probe_ent) {
4729                 printk(KERN_ERR DRV_NAME "(%s): out of memory\n",
4730                        kobject_name(&(dev->kobj)));
4731                 return NULL;
4732         }
4733
4734         INIT_LIST_HEAD(&probe_ent->node);
4735         probe_ent->dev = dev;
4736
4737         probe_ent->sht = port->sht;
4738         probe_ent->host_flags = port->host_flags;
4739         probe_ent->pio_mask = port->pio_mask;
4740         probe_ent->mwdma_mask = port->mwdma_mask;
4741         probe_ent->udma_mask = port->udma_mask;
4742         probe_ent->port_ops = port->port_ops;
4743
4744         return probe_ent;
4745 }
4746
4747
4748
4749 #ifdef CONFIG_PCI
4750
4751 void ata_pci_host_stop (struct ata_host_set *host_set)
4752 {
4753         struct pci_dev *pdev = to_pci_dev(host_set->dev);
4754
4755         pci_iounmap(pdev, host_set->mmio_base);
4756 }
4757
4758 /**
4759  *      ata_pci_init_native_mode - Initialize native-mode driver
4760  *      @pdev:  pci device to be initialized
4761  *      @port:  array[2] of pointers to port info structures.
4762  *      @ports: bitmap of ports present
4763  *
4764  *      Utility function which allocates and initializes an
4765  *      ata_probe_ent structure for a standard dual-port
4766  *      PIO-based IDE controller.  The returned ata_probe_ent
4767  *      structure can be passed to ata_device_add().  The returned
4768  *      ata_probe_ent structure should then be freed with kfree().
4769  *
4770  *      The caller need only pass the address of the primary port, the
4771  *      secondary will be deduced automatically. If the device has non
4772  *      standard secondary port mappings this function can be called twice,
4773  *      once for each interface.
4774  */
4775
4776 struct ata_probe_ent *
4777 ata_pci_init_native_mode(struct pci_dev *pdev, struct ata_port_info **port, int ports)
4778 {
4779         struct ata_probe_ent *probe_ent =
4780                 ata_probe_ent_alloc(pci_dev_to_dev(pdev), port[0]);
4781         int p = 0;
4782
4783         if (!probe_ent)
4784                 return NULL;
4785
4786         probe_ent->irq = pdev->irq;
4787         probe_ent->irq_flags = SA_SHIRQ;
4788         probe_ent->private_data = port[0]->private_data;
4789
4790         if (ports & ATA_PORT_PRIMARY) {
4791                 probe_ent->port[p].cmd_addr = pci_resource_start(pdev, 0);
4792                 probe_ent->port[p].altstatus_addr =
4793                 probe_ent->port[p].ctl_addr =
4794                         pci_resource_start(pdev, 1) | ATA_PCI_CTL_OFS;
4795                 probe_ent->port[p].bmdma_addr = pci_resource_start(pdev, 4);
4796                 ata_std_ports(&probe_ent->port[p]);
4797                 p++;
4798         }
4799
4800         if (ports & ATA_PORT_SECONDARY) {
4801                 probe_ent->port[p].cmd_addr = pci_resource_start(pdev, 2);
4802                 probe_ent->port[p].altstatus_addr =
4803                 probe_ent->port[p].ctl_addr =
4804                         pci_resource_start(pdev, 3) | ATA_PCI_CTL_OFS;
4805                 probe_ent->port[p].bmdma_addr = pci_resource_start(pdev, 4) + 8;
4806                 ata_std_ports(&probe_ent->port[p]);
4807                 p++;
4808         }
4809
4810         probe_ent->n_ports = p;
4811         return probe_ent;
4812 }
4813
4814 static struct ata_probe_ent *ata_pci_init_legacy_port(struct pci_dev *pdev, struct ata_port_info *port, int port_num)
4815 {
4816         struct ata_probe_ent *probe_ent;
4817
4818         probe_ent = ata_probe_ent_alloc(pci_dev_to_dev(pdev), port);
4819         if (!probe_ent)
4820                 return NULL;
4821
4822         probe_ent->legacy_mode = 1;
4823         probe_ent->n_ports = 1;
4824         probe_ent->hard_port_no = port_num;
4825         probe_ent->private_data = port->private_data;
4826
4827         switch(port_num)
4828         {
4829                 case 0:
4830                         probe_ent->irq = 14;
4831                         probe_ent->port[0].cmd_addr = 0x1f0;
4832                         probe_ent->port[0].altstatus_addr =
4833                         probe_ent->port[0].ctl_addr = 0x3f6;
4834                         break;
4835                 case 1:
4836                         probe_ent->irq = 15;
4837                         probe_ent->port[0].cmd_addr = 0x170;
4838                         probe_ent->port[0].altstatus_addr =
4839                         probe_ent->port[0].ctl_addr = 0x376;
4840                         break;
4841         }
4842         probe_ent->port[0].bmdma_addr = pci_resource_start(pdev, 4) + 8 * port_num;
4843         ata_std_ports(&probe_ent->port[0]);
4844         return probe_ent;
4845 }
4846
4847 /**
4848  *      ata_pci_init_one - Initialize/register PCI IDE host controller
4849  *      @pdev: Controller to be initialized
4850  *      @port_info: Information from low-level host driver
4851  *      @n_ports: Number of ports attached to host controller
4852  *
4853  *      This is a helper function which can be called from a driver's
4854  *      xxx_init_one() probe function if the hardware uses traditional
4855  *      IDE taskfile registers.
4856  *
4857  *      This function calls pci_enable_device(), reserves its register
4858  *      regions, sets the dma mask, enables bus master mode, and calls
4859  *      ata_device_add()
4860  *
4861  *      LOCKING:
4862  *      Inherited from PCI layer (may sleep).
4863  *
4864  *      RETURNS:
4865  *      Zero on success, negative on errno-based value on error.
4866  */
4867
4868 int ata_pci_init_one (struct pci_dev *pdev, struct ata_port_info **port_info,
4869                       unsigned int n_ports)
4870 {
4871         struct ata_probe_ent *probe_ent = NULL, *probe_ent2 = NULL;
4872         struct ata_port_info *port[2];
4873         u8 tmp8, mask;
4874         unsigned int legacy_mode = 0;
4875         int disable_dev_on_err = 1;
4876         int rc;
4877
4878         DPRINTK("ENTER\n");
4879
4880         port[0] = port_info[0];
4881         if (n_ports > 1)
4882                 port[1] = port_info[1];
4883         else
4884                 port[1] = port[0];
4885
4886         if ((port[0]->host_flags & ATA_FLAG_NO_LEGACY) == 0
4887             && (pdev->class >> 8) == PCI_CLASS_STORAGE_IDE) {
4888                 /* TODO: What if one channel is in native mode ... */
4889                 pci_read_config_byte(pdev, PCI_CLASS_PROG, &tmp8);
4890                 mask = (1 << 2) | (1 << 0);
4891                 if ((tmp8 & mask) != mask)
4892                         legacy_mode = (1 << 3);
4893         }
4894
4895         /* FIXME... */
4896         if ((!legacy_mode) && (n_ports > 2)) {
4897                 printk(KERN_ERR "ata: BUG: native mode, n_ports > 2\n");
4898                 n_ports = 2;
4899                 /* For now */
4900         }
4901
4902         /* FIXME: Really for ATA it isn't safe because the device may be
4903            multi-purpose and we want to leave it alone if it was already
4904            enabled. Secondly for shared use as Arjan says we want refcounting
4905            
4906            Checking dev->is_enabled is insufficient as this is not set at
4907            boot for the primary video which is BIOS enabled
4908          */
4909          
4910         rc = pci_enable_device(pdev);
4911         if (rc)
4912                 return rc;
4913
4914         rc = pci_request_regions(pdev, DRV_NAME);
4915         if (rc) {
4916                 disable_dev_on_err = 0;
4917                 goto err_out;
4918         }
4919
4920         /* FIXME: Should use platform specific mappers for legacy port ranges */
4921         if (legacy_mode) {
4922                 if (!request_region(0x1f0, 8, "libata")) {
4923                         struct resource *conflict, res;
4924                         res.start = 0x1f0;
4925                         res.end = 0x1f0 + 8 - 1;
4926                         conflict = ____request_resource(&ioport_resource, &res);
4927                         if (!strcmp(conflict->name, "libata"))
4928                                 legacy_mode |= (1 << 0);
4929                         else {
4930                                 disable_dev_on_err = 0;
4931                                 printk(KERN_WARNING "ata: 0x1f0 IDE port busy\n");
4932                         }
4933                 } else
4934                         legacy_mode |= (1 << 0);
4935
4936                 if (!request_region(0x170, 8, "libata")) {
4937                         struct resource *conflict, res;
4938                         res.start = 0x170;
4939                         res.end = 0x170 + 8 - 1;
4940                         conflict = ____request_resource(&ioport_resource, &res);
4941                         if (!strcmp(conflict->name, "libata"))
4942                                 legacy_mode |= (1 << 1);
4943                         else {
4944                                 disable_dev_on_err = 0;
4945                                 printk(KERN_WARNING "ata: 0x170 IDE port busy\n");
4946                         }
4947                 } else
4948                         legacy_mode |= (1 << 1);
4949         }
4950
4951         /* we have legacy mode, but all ports are unavailable */
4952         if (legacy_mode == (1 << 3)) {
4953                 rc = -EBUSY;
4954                 goto err_out_regions;
4955         }
4956
4957         rc = pci_set_dma_mask(pdev, ATA_DMA_MASK);
4958         if (rc)
4959                 goto err_out_regions;
4960         rc = pci_set_consistent_dma_mask(pdev, ATA_DMA_MASK);
4961         if (rc)
4962                 goto err_out_regions;
4963
4964         if (legacy_mode) {
4965                 if (legacy_mode & (1 << 0))
4966                         probe_ent = ata_pci_init_legacy_port(pdev, port[0], 0);
4967                 if (legacy_mode & (1 << 1))
4968                         probe_ent2 = ata_pci_init_legacy_port(pdev, port[1], 1);
4969         } else {
4970                 if (n_ports == 2)
4971                         probe_ent = ata_pci_init_native_mode(pdev, port, ATA_PORT_PRIMARY | ATA_PORT_SECONDARY);
4972                 else
4973                         probe_ent = ata_pci_init_native_mode(pdev, port, ATA_PORT_PRIMARY);
4974         }
4975         if (!probe_ent && !probe_ent2) {
4976                 rc = -ENOMEM;
4977                 goto err_out_regions;
4978         }
4979
4980         pci_set_master(pdev);
4981
4982         /* FIXME: check ata_device_add return */
4983         if (legacy_mode) {
4984                 if (legacy_mode & (1 << 0))
4985                         ata_device_add(probe_ent);
4986                 if (legacy_mode & (1 << 1))
4987                         ata_device_add(probe_ent2);
4988         } else
4989                 ata_device_add(probe_ent);
4990
4991         kfree(probe_ent);
4992         kfree(probe_ent2);
4993
4994         return 0;
4995
4996 err_out_regions:
4997         if (legacy_mode & (1 << 0))
4998                 release_region(0x1f0, 8);
4999         if (legacy_mode & (1 << 1))
5000                 release_region(0x170, 8);
5001         pci_release_regions(pdev);
5002 err_out:
5003         if (disable_dev_on_err)
5004                 pci_disable_device(pdev);
5005         return rc;
5006 }
5007
5008 /**
5009  *      ata_pci_remove_one - PCI layer callback for device removal
5010  *      @pdev: PCI device that was removed
5011  *
5012  *      PCI layer indicates to libata via this hook that
5013  *      hot-unplug or module unload event has occurred.
5014  *      Handle this by unregistering all objects associated
5015  *      with this PCI device.  Free those objects.  Then finally
5016  *      release PCI resources and disable device.
5017  *
5018  *      LOCKING:
5019  *      Inherited from PCI layer (may sleep).
5020  */
5021
5022 void ata_pci_remove_one (struct pci_dev *pdev)
5023 {
5024         struct device *dev = pci_dev_to_dev(pdev);
5025         struct ata_host_set *host_set = dev_get_drvdata(dev);
5026
5027         ata_host_set_remove(host_set);
5028         pci_release_regions(pdev);
5029         pci_disable_device(pdev);
5030         dev_set_drvdata(dev, NULL);
5031 }
5032
5033 /* move to PCI subsystem */
5034 int pci_test_config_bits(struct pci_dev *pdev, const struct pci_bits *bits)
5035 {
5036         unsigned long tmp = 0;
5037
5038         switch (bits->width) {
5039         case 1: {
5040                 u8 tmp8 = 0;
5041                 pci_read_config_byte(pdev, bits->reg, &tmp8);
5042                 tmp = tmp8;
5043                 break;
5044         }
5045         case 2: {
5046                 u16 tmp16 = 0;
5047                 pci_read_config_word(pdev, bits->reg, &tmp16);
5048                 tmp = tmp16;
5049                 break;
5050         }
5051         case 4: {
5052                 u32 tmp32 = 0;
5053                 pci_read_config_dword(pdev, bits->reg, &tmp32);
5054                 tmp = tmp32;
5055                 break;
5056         }
5057
5058         default:
5059                 return -EINVAL;
5060         }
5061
5062         tmp &= bits->mask;
5063
5064         return (tmp == bits->val) ? 1 : 0;
5065 }
5066
5067 int ata_pci_device_suspend(struct pci_dev *pdev, pm_message_t state)
5068 {
5069         pci_save_state(pdev);
5070         pci_disable_device(pdev);
5071         pci_set_power_state(pdev, PCI_D3hot);
5072         return 0;
5073 }
5074
5075 int ata_pci_device_resume(struct pci_dev *pdev)
5076 {
5077         pci_set_power_state(pdev, PCI_D0);
5078         pci_restore_state(pdev);
5079         pci_enable_device(pdev);
5080         pci_set_master(pdev);
5081         return 0;
5082 }
5083 #endif /* CONFIG_PCI */
5084
5085
5086 static int __init ata_init(void)
5087 {
5088         ata_wq = create_workqueue("ata");
5089         if (!ata_wq)
5090                 return -ENOMEM;
5091
5092         printk(KERN_DEBUG "libata version " DRV_VERSION " loaded.\n");
5093         return 0;
5094 }
5095
5096 static void __exit ata_exit(void)
5097 {
5098         destroy_workqueue(ata_wq);
5099 }
5100
5101 module_init(ata_init);
5102 module_exit(ata_exit);
5103
5104 static unsigned long ratelimit_time;
5105 static spinlock_t ata_ratelimit_lock = SPIN_LOCK_UNLOCKED;
5106
5107 int ata_ratelimit(void)
5108 {
5109         int rc;
5110         unsigned long flags;
5111
5112         spin_lock_irqsave(&ata_ratelimit_lock, flags);
5113
5114         if (time_after(jiffies, ratelimit_time)) {
5115                 rc = 1;
5116                 ratelimit_time = jiffies + (HZ/5);
5117         } else
5118                 rc = 0;
5119
5120         spin_unlock_irqrestore(&ata_ratelimit_lock, flags);
5121
5122         return rc;
5123 }
5124
5125 /*
5126  * libata is essentially a library of internal helper functions for
5127  * low-level ATA host controller drivers.  As such, the API/ABI is
5128  * likely to change as new drivers are added and updated.
5129  * Do not depend on ABI/API stability.
5130  */
5131
5132 EXPORT_SYMBOL_GPL(ata_std_bios_param);
5133 EXPORT_SYMBOL_GPL(ata_std_ports);
5134 EXPORT_SYMBOL_GPL(ata_device_add);
5135 EXPORT_SYMBOL_GPL(ata_host_set_remove);
5136 EXPORT_SYMBOL_GPL(ata_sg_init);
5137 EXPORT_SYMBOL_GPL(ata_sg_init_one);
5138 EXPORT_SYMBOL_GPL(ata_qc_complete);
5139 EXPORT_SYMBOL_GPL(ata_qc_issue_prot);
5140 EXPORT_SYMBOL_GPL(ata_eng_timeout);
5141 EXPORT_SYMBOL_GPL(ata_tf_load);
5142 EXPORT_SYMBOL_GPL(ata_tf_read);
5143 EXPORT_SYMBOL_GPL(ata_noop_dev_select);
5144 EXPORT_SYMBOL_GPL(ata_std_dev_select);
5145 EXPORT_SYMBOL_GPL(ata_tf_to_fis);
5146 EXPORT_SYMBOL_GPL(ata_tf_from_fis);
5147 EXPORT_SYMBOL_GPL(ata_check_status);
5148 EXPORT_SYMBOL_GPL(ata_altstatus);
5149 EXPORT_SYMBOL_GPL(ata_exec_command);
5150 EXPORT_SYMBOL_GPL(ata_port_start);
5151 EXPORT_SYMBOL_GPL(ata_port_stop);
5152 EXPORT_SYMBOL_GPL(ata_host_stop);
5153 EXPORT_SYMBOL_GPL(ata_interrupt);
5154 EXPORT_SYMBOL_GPL(ata_qc_prep);
5155 EXPORT_SYMBOL_GPL(ata_bmdma_setup);
5156 EXPORT_SYMBOL_GPL(ata_bmdma_start);
5157 EXPORT_SYMBOL_GPL(ata_bmdma_irq_clear);
5158 EXPORT_SYMBOL_GPL(ata_bmdma_status);
5159 EXPORT_SYMBOL_GPL(ata_bmdma_stop);
5160 EXPORT_SYMBOL_GPL(ata_port_probe);
5161 EXPORT_SYMBOL_GPL(sata_phy_reset);
5162 EXPORT_SYMBOL_GPL(__sata_phy_reset);
5163 EXPORT_SYMBOL_GPL(ata_bus_reset);
5164 EXPORT_SYMBOL_GPL(ata_port_disable);
5165 EXPORT_SYMBOL_GPL(ata_ratelimit);
5166 EXPORT_SYMBOL_GPL(ata_busy_sleep);
5167 EXPORT_SYMBOL_GPL(ata_scsi_ioctl);
5168 EXPORT_SYMBOL_GPL(ata_scsi_queuecmd);
5169 EXPORT_SYMBOL_GPL(ata_scsi_error);
5170 EXPORT_SYMBOL_GPL(ata_scsi_slave_config);
5171 EXPORT_SYMBOL_GPL(ata_scsi_release);
5172 EXPORT_SYMBOL_GPL(ata_host_intr);
5173 EXPORT_SYMBOL_GPL(ata_dev_classify);
5174 EXPORT_SYMBOL_GPL(ata_dev_id_string);
5175 EXPORT_SYMBOL_GPL(ata_dev_config);
5176 EXPORT_SYMBOL_GPL(ata_scsi_simulate);
5177 EXPORT_SYMBOL_GPL(ata_eh_qc_complete);
5178 EXPORT_SYMBOL_GPL(ata_eh_qc_retry);
5179
5180 EXPORT_SYMBOL_GPL(ata_pio_need_iordy);
5181 EXPORT_SYMBOL_GPL(ata_timing_compute);
5182 EXPORT_SYMBOL_GPL(ata_timing_merge);
5183
5184 #ifdef CONFIG_PCI
5185 EXPORT_SYMBOL_GPL(pci_test_config_bits);
5186 EXPORT_SYMBOL_GPL(ata_pci_host_stop);
5187 EXPORT_SYMBOL_GPL(ata_pci_init_native_mode);
5188 EXPORT_SYMBOL_GPL(ata_pci_init_one);
5189 EXPORT_SYMBOL_GPL(ata_pci_remove_one);
5190 EXPORT_SYMBOL_GPL(ata_pci_device_suspend);
5191 EXPORT_SYMBOL_GPL(ata_pci_device_resume);
5192 #endif /* CONFIG_PCI */
5193
5194 EXPORT_SYMBOL_GPL(ata_device_suspend);
5195 EXPORT_SYMBOL_GPL(ata_device_resume);
5196 EXPORT_SYMBOL_GPL(ata_scsi_device_suspend);
5197 EXPORT_SYMBOL_GPL(ata_scsi_device_resume);