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