]> err.no Git - linux-2.6/blob - drivers/scsi/libata-core.c
[PATCH] libata-dev: filter out noisy ATAPI error messages
[linux-2.6] / 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                 qc->err_mask |= AC_ERR_ATA_BUS;
3269                 ap->hsm_task_state = HSM_ST_TMOUT;
3270                 goto err_out;
3271         }
3272
3273         /* make sure DRQ is set */
3274         status = ata_chk_status(ap);
3275         if ((status & (ATA_BUSY | ATA_DRQ)) != ATA_DRQ) {
3276                 /* device status error */
3277                 qc->err_mask |= AC_ERR_ATA_BUS;
3278                 ap->hsm_task_state = HSM_ST_ERR;
3279                 goto err_out;
3280         }
3281
3282         /* Send the CDB (atapi) or the first data block (ata pio out).
3283          * During the state transition, interrupt handler shouldn't
3284          * be invoked before the data transfer is complete and
3285          * hsm_task_state is changed. Hence, the following locking.
3286          */
3287         spin_lock_irqsave(&ap->host_set->lock, flags);
3288
3289         if (qc->tf.protocol == ATA_PROT_PIO) {
3290                 /* PIO data out protocol.
3291                  * send first data block.
3292                  */
3293
3294                 /* ata_pio_sectors() might change the state to HSM_ST_LAST.
3295                  * so, the state is changed here before ata_pio_sectors().
3296                  */
3297                 ap->hsm_task_state = HSM_ST;
3298                 ata_pio_sectors(qc);
3299                 ata_altstatus(ap); /* flush */
3300         } else
3301                 /* send CDB */
3302                 atapi_send_cdb(ap, qc);
3303
3304         spin_unlock_irqrestore(&ap->host_set->lock, flags);
3305
3306         /* if polling, ata_pio_task() handles the rest.
3307          * otherwise, interrupt handler takes over from here.
3308          */
3309         return has_next;
3310
3311 err_out:
3312         return 1; /* has next */
3313 }
3314
3315 /**
3316  *      __atapi_pio_bytes - Transfer data from/to the ATAPI device.
3317  *      @qc: Command on going
3318  *      @bytes: number of bytes
3319  *
3320  *      Transfer Transfer data from/to the ATAPI device.
3321  *
3322  *      LOCKING:
3323  *      Inherited from caller.
3324  *
3325  */
3326
3327 static void __atapi_pio_bytes(struct ata_queued_cmd *qc, unsigned int bytes)
3328 {
3329         int do_write = (qc->tf.flags & ATA_TFLAG_WRITE);
3330         struct scatterlist *sg = qc->__sg;
3331         struct ata_port *ap = qc->ap;
3332         struct page *page;
3333         unsigned char *buf;
3334         unsigned int offset, count;
3335
3336         if (qc->curbytes + bytes >= qc->nbytes)
3337                 ap->hsm_task_state = HSM_ST_LAST;
3338
3339 next_sg:
3340         if (unlikely(qc->cursg >= qc->n_elem)) {
3341                 /*
3342                  * The end of qc->sg is reached and the device expects
3343                  * more data to transfer. In order not to overrun qc->sg
3344                  * and fulfill length specified in the byte count register,
3345                  *    - for read case, discard trailing data from the device
3346                  *    - for write case, padding zero data to the device
3347                  */
3348                 u16 pad_buf[1] = { 0 };
3349                 unsigned int words = bytes >> 1;
3350                 unsigned int i;
3351
3352                 if (words) /* warning if bytes > 1 */
3353                         printk(KERN_WARNING "ata%u: %u bytes trailing data\n",
3354                                ap->id, bytes);
3355
3356                 for (i = 0; i < words; i++)
3357                         ata_data_xfer(ap, (unsigned char*)pad_buf, 2, do_write);
3358
3359                 ap->hsm_task_state = HSM_ST_LAST;
3360                 return;
3361         }
3362
3363         sg = &qc->__sg[qc->cursg];
3364
3365         page = sg->page;
3366         offset = sg->offset + qc->cursg_ofs;
3367
3368         /* get the current page and offset */
3369         page = nth_page(page, (offset >> PAGE_SHIFT));
3370         offset %= PAGE_SIZE;
3371
3372         /* don't overrun current sg */
3373         count = min(sg->length - qc->cursg_ofs, bytes);
3374
3375         /* don't cross page boundaries */
3376         count = min(count, (unsigned int)PAGE_SIZE - offset);
3377
3378         DPRINTK("data %s\n", qc->tf.flags & ATA_TFLAG_WRITE ? "write" : "read");
3379
3380         if (PageHighMem(page)) {
3381                 unsigned long flags;
3382
3383                 local_irq_save(flags);
3384                 buf = kmap_atomic(page, KM_IRQ0);
3385
3386                 /* do the actual data transfer */
3387                 ata_data_xfer(ap, buf + offset, count, do_write);
3388
3389                 kunmap_atomic(buf, KM_IRQ0);
3390                 local_irq_restore(flags);
3391         } else {
3392                 buf = page_address(page);
3393                 ata_data_xfer(ap, buf + offset, count, do_write);
3394         }
3395
3396         bytes -= count;
3397         qc->curbytes += count;
3398         qc->cursg_ofs += count;
3399
3400         if (qc->cursg_ofs == sg->length) {
3401                 qc->cursg++;
3402                 qc->cursg_ofs = 0;
3403         }
3404
3405         if (bytes)
3406                 goto next_sg;
3407 }
3408
3409 /**
3410  *      atapi_pio_bytes - Transfer data from/to the ATAPI device.
3411  *      @qc: Command on going
3412  *
3413  *      Transfer Transfer data from/to the ATAPI device.
3414  *
3415  *      LOCKING:
3416  *      Inherited from caller.
3417  */
3418
3419 static void atapi_pio_bytes(struct ata_queued_cmd *qc)
3420 {
3421         struct ata_port *ap = qc->ap;
3422         struct ata_device *dev = qc->dev;
3423         unsigned int ireason, bc_lo, bc_hi, bytes;
3424         int i_write, do_write = (qc->tf.flags & ATA_TFLAG_WRITE) ? 1 : 0;
3425
3426         ap->ops->tf_read(ap, &qc->tf);
3427         ireason = qc->tf.nsect;
3428         bc_lo = qc->tf.lbam;
3429         bc_hi = qc->tf.lbah;
3430         bytes = (bc_hi << 8) | bc_lo;
3431
3432         /* shall be cleared to zero, indicating xfer of data */
3433         if (ireason & (1 << 0))
3434                 goto err_out;
3435
3436         /* make sure transfer direction matches expected */
3437         i_write = ((ireason & (1 << 1)) == 0) ? 1 : 0;
3438         if (do_write != i_write)
3439                 goto err_out;
3440
3441         VPRINTK("ata%u: xfering %d bytes\n", ap->id, bytes);
3442
3443         __atapi_pio_bytes(qc, bytes);
3444
3445         return;
3446
3447 err_out:
3448         printk(KERN_INFO "ata%u: dev %u: ATAPI check failed\n",
3449               ap->id, dev->devno);
3450         qc->err_mask |= AC_ERR_ATA_BUS;
3451         ap->hsm_task_state = HSM_ST_ERR;
3452 }
3453
3454 /**
3455  *      ata_pio_block - start PIO on a block
3456  *      @ap: the target ata_port
3457  *
3458  *      LOCKING:
3459  *      None.  (executing in kernel thread context)
3460  */
3461
3462 static void ata_pio_block(struct ata_port *ap)
3463 {
3464         struct ata_queued_cmd *qc;
3465         u8 status;
3466
3467         /*
3468          * This is purely heuristic.  This is a fast path.
3469          * Sometimes when we enter, BSY will be cleared in
3470          * a chk-status or two.  If not, the drive is probably seeking
3471          * or something.  Snooze for a couple msecs, then
3472          * chk-status again.  If still busy, fall back to
3473          * HSM_ST_POLL state.
3474          */
3475         status = ata_busy_wait(ap, ATA_BUSY, 5);
3476         if (status & ATA_BUSY) {
3477                 msleep(2);
3478                 status = ata_busy_wait(ap, ATA_BUSY, 10);
3479                 if (status & ATA_BUSY) {
3480                         ap->hsm_task_state = HSM_ST_POLL;
3481                         ap->pio_task_timeout = jiffies + ATA_TMOUT_PIO;
3482                         return;
3483                 }
3484         }
3485
3486         qc = ata_qc_from_tag(ap, ap->active_tag);
3487         assert(qc != NULL);
3488
3489         /* check error */
3490         if (status & (ATA_ERR | ATA_DF)) {
3491                 qc->err_mask |= AC_ERR_DEV;
3492                 ap->hsm_task_state = HSM_ST_ERR;
3493                 return;
3494         }
3495
3496         /* transfer data if any */
3497         if (is_atapi_taskfile(&qc->tf)) {
3498                 /* DRQ=0 means no more data to transfer */
3499                 if ((status & ATA_DRQ) == 0) {
3500                         ap->hsm_task_state = HSM_ST_LAST;
3501                         return;
3502                 }
3503
3504                 atapi_pio_bytes(qc);
3505         } else {
3506                 /* handle BSY=0, DRQ=0 as error */
3507                 if ((status & ATA_DRQ) == 0) {
3508                         qc->err_mask |= AC_ERR_ATA_BUS;
3509                         ap->hsm_task_state = HSM_ST_ERR;
3510                         return;
3511                 }
3512
3513                 ata_pio_sectors(qc);
3514         }
3515
3516         ata_altstatus(ap); /* flush */
3517 }
3518
3519 static void ata_pio_error(struct ata_port *ap)
3520 {
3521         struct ata_queued_cmd *qc;
3522
3523         qc = ata_qc_from_tag(ap, ap->active_tag);
3524         assert(qc != NULL);
3525
3526         if (qc->tf.command != ATA_CMD_PACKET)
3527                 printk(KERN_WARNING "ata%u: PIO error\n", ap->id);
3528
3529         /* make sure qc->err_mask is available to 
3530          * know what's wrong and recover
3531          */
3532         assert(qc->err_mask);
3533
3534         ap->hsm_task_state = HSM_ST_IDLE;
3535
3536         ata_poll_qc_complete(qc);
3537 }
3538
3539 static void ata_pio_task(void *_data)
3540 {
3541         struct ata_port *ap = _data;
3542         unsigned long timeout;
3543         int has_next;
3544
3545 fsm_start:
3546         timeout = 0;
3547         has_next = 1;
3548
3549         switch (ap->hsm_task_state) {
3550         case HSM_ST_FIRST:
3551                 has_next = ata_pio_first_block(ap);
3552                 break;
3553
3554         case HSM_ST:
3555                 ata_pio_block(ap);
3556                 break;
3557
3558         case HSM_ST_LAST:
3559                 has_next = ata_pio_complete(ap);
3560                 break;
3561
3562         case HSM_ST_POLL:
3563         case HSM_ST_LAST_POLL:
3564                 timeout = ata_pio_poll(ap);
3565                 break;
3566
3567         case HSM_ST_TMOUT:
3568         case HSM_ST_ERR:
3569                 ata_pio_error(ap);
3570                 return;
3571
3572         default:
3573                 BUG();
3574                 return;
3575         }
3576
3577         if (timeout)
3578                 queue_delayed_work(ata_wq, &ap->pio_task, timeout);
3579         else if (has_next)
3580                 goto fsm_start;
3581 }
3582
3583 /**
3584  *      ata_qc_timeout - Handle timeout of queued command
3585  *      @qc: Command that timed out
3586  *
3587  *      Some part of the kernel (currently, only the SCSI layer)
3588  *      has noticed that the active command on port @ap has not
3589  *      completed after a specified length of time.  Handle this
3590  *      condition by disabling DMA (if necessary) and completing
3591  *      transactions, with error if necessary.
3592  *
3593  *      This also handles the case of the "lost interrupt", where
3594  *      for some reason (possibly hardware bug, possibly driver bug)
3595  *      an interrupt was not delivered to the driver, even though the
3596  *      transaction completed successfully.
3597  *
3598  *      LOCKING:
3599  *      Inherited from SCSI layer (none, can sleep)
3600  */
3601
3602 static void ata_qc_timeout(struct ata_queued_cmd *qc)
3603 {
3604         struct ata_port *ap = qc->ap;
3605         struct ata_host_set *host_set = ap->host_set;
3606         u8 host_stat = 0, drv_stat;
3607         unsigned long flags;
3608
3609         DPRINTK("ENTER\n");
3610
3611         spin_lock_irqsave(&host_set->lock, flags);
3612
3613         /* hack alert!  We cannot use the supplied completion
3614          * function from inside the ->eh_strategy_handler() thread.
3615          * libata is the only user of ->eh_strategy_handler() in
3616          * any kernel, so the default scsi_done() assumes it is
3617          * not being called from the SCSI EH.
3618          */
3619         qc->scsidone = scsi_finish_command;
3620
3621         switch (qc->tf.protocol) {
3622
3623         case ATA_PROT_DMA:
3624         case ATA_PROT_ATAPI_DMA:
3625                 host_stat = ap->ops->bmdma_status(ap);
3626
3627                 /* before we do anything else, clear DMA-Start bit */
3628                 ap->ops->bmdma_stop(qc);
3629
3630                 /* fall through */
3631
3632         default:
3633                 ata_altstatus(ap);
3634                 drv_stat = ata_chk_status(ap);
3635
3636                 /* ack bmdma irq events */
3637                 ap->ops->irq_clear(ap);
3638
3639                 printk(KERN_ERR "ata%u: command 0x%x timeout, stat 0x%x host_stat 0x%x\n",
3640                        ap->id, qc->tf.command, drv_stat, host_stat);
3641
3642                 ap->hsm_task_state = HSM_ST_IDLE;
3643
3644                 /* complete taskfile transaction */
3645                 qc->err_mask |= ac_err_mask(drv_stat);
3646                 ata_qc_complete(qc);
3647                 break;
3648         }
3649
3650         spin_unlock_irqrestore(&host_set->lock, flags);
3651
3652         DPRINTK("EXIT\n");
3653 }
3654
3655 /**
3656  *      ata_eng_timeout - Handle timeout of queued command
3657  *      @ap: Port on which timed-out command is active
3658  *
3659  *      Some part of the kernel (currently, only the SCSI layer)
3660  *      has noticed that the active command on port @ap has not
3661  *      completed after a specified length of time.  Handle this
3662  *      condition by disabling DMA (if necessary) and completing
3663  *      transactions, with error if necessary.
3664  *
3665  *      This also handles the case of the "lost interrupt", where
3666  *      for some reason (possibly hardware bug, possibly driver bug)
3667  *      an interrupt was not delivered to the driver, even though the
3668  *      transaction completed successfully.
3669  *
3670  *      LOCKING:
3671  *      Inherited from SCSI layer (none, can sleep)
3672  */
3673
3674 void ata_eng_timeout(struct ata_port *ap)
3675 {
3676         struct ata_queued_cmd *qc;
3677
3678         DPRINTK("ENTER\n");
3679
3680         qc = ata_qc_from_tag(ap, ap->active_tag);
3681         if (qc)
3682                 ata_qc_timeout(qc);
3683         else {
3684                 printk(KERN_ERR "ata%u: BUG: timeout without command\n",
3685                        ap->id);
3686                 goto out;
3687         }
3688
3689 out:
3690         DPRINTK("EXIT\n");
3691 }
3692
3693 /**
3694  *      ata_qc_new - Request an available ATA command, for queueing
3695  *      @ap: Port associated with device @dev
3696  *      @dev: Device from whom we request an available command structure
3697  *
3698  *      LOCKING:
3699  *      None.
3700  */
3701
3702 static struct ata_queued_cmd *ata_qc_new(struct ata_port *ap)
3703 {
3704         struct ata_queued_cmd *qc = NULL;
3705         unsigned int i;
3706
3707         for (i = 0; i < ATA_MAX_QUEUE; i++)
3708                 if (!test_and_set_bit(i, &ap->qactive)) {
3709                         qc = ata_qc_from_tag(ap, i);
3710                         break;
3711                 }
3712
3713         if (qc)
3714                 qc->tag = i;
3715
3716         return qc;
3717 }
3718
3719 /**
3720  *      ata_qc_new_init - Request an available ATA command, and initialize it
3721  *      @ap: Port associated with device @dev
3722  *      @dev: Device from whom we request an available command structure
3723  *
3724  *      LOCKING:
3725  *      None.
3726  */
3727
3728 struct ata_queued_cmd *ata_qc_new_init(struct ata_port *ap,
3729                                       struct ata_device *dev)
3730 {
3731         struct ata_queued_cmd *qc;
3732
3733         qc = ata_qc_new(ap);
3734         if (qc) {
3735                 qc->scsicmd = NULL;
3736                 qc->ap = ap;
3737                 qc->dev = dev;
3738
3739                 ata_qc_reinit(qc);
3740         }
3741
3742         return qc;
3743 }
3744
3745 static void __ata_qc_complete(struct ata_queued_cmd *qc)
3746 {
3747         struct ata_port *ap = qc->ap;
3748         unsigned int tag;
3749
3750         qc->flags = 0;
3751         tag = qc->tag;
3752         if (likely(ata_tag_valid(tag))) {
3753                 if (tag == ap->active_tag)
3754                         ap->active_tag = ATA_TAG_POISON;
3755                 qc->tag = ATA_TAG_POISON;
3756                 clear_bit(tag, &ap->qactive);
3757         }
3758 }
3759
3760 /**
3761  *      ata_qc_free - free unused ata_queued_cmd
3762  *      @qc: Command to complete
3763  *
3764  *      Designed to free unused ata_queued_cmd object
3765  *      in case something prevents using it.
3766  *
3767  *      LOCKING:
3768  *      spin_lock_irqsave(host_set lock)
3769  */
3770 void ata_qc_free(struct ata_queued_cmd *qc)
3771 {
3772         assert(qc != NULL);     /* ata_qc_from_tag _might_ return NULL */
3773
3774         __ata_qc_complete(qc);
3775 }
3776
3777 /**
3778  *      ata_qc_complete - Complete an active ATA command
3779  *      @qc: Command to complete
3780  *      @err_mask: ATA Status register contents
3781  *
3782  *      Indicate to the mid and upper layers that an ATA
3783  *      command has completed, with either an ok or not-ok status.
3784  *
3785  *      LOCKING:
3786  *      spin_lock_irqsave(host_set lock)
3787  */
3788
3789 void ata_qc_complete(struct ata_queued_cmd *qc)
3790 {
3791         int rc;
3792
3793         assert(qc != NULL);     /* ata_qc_from_tag _might_ return NULL */
3794         assert(qc->flags & ATA_QCFLAG_ACTIVE);
3795
3796         if (likely(qc->flags & ATA_QCFLAG_DMAMAP))
3797                 ata_sg_clean(qc);
3798
3799         /* atapi: mark qc as inactive to prevent the interrupt handler
3800          * from completing the command twice later, before the error handler
3801          * is called. (when rc != 0 and atapi request sense is needed)
3802          */
3803         qc->flags &= ~ATA_QCFLAG_ACTIVE;
3804
3805         /* call completion callback */
3806         rc = qc->complete_fn(qc);
3807
3808         /* if callback indicates not to complete command (non-zero),
3809          * return immediately
3810          */
3811         if (rc != 0)
3812                 return;
3813
3814         __ata_qc_complete(qc);
3815
3816         VPRINTK("EXIT\n");
3817 }
3818
3819 static inline int ata_should_dma_map(struct ata_queued_cmd *qc)
3820 {
3821         struct ata_port *ap = qc->ap;
3822
3823         switch (qc->tf.protocol) {
3824         case ATA_PROT_DMA:
3825         case ATA_PROT_ATAPI_DMA:
3826                 return 1;
3827
3828         case ATA_PROT_ATAPI:
3829         case ATA_PROT_PIO:
3830         case ATA_PROT_PIO_MULT:
3831                 if (ap->flags & ATA_FLAG_PIO_DMA)
3832                         return 1;
3833
3834                 /* fall through */
3835
3836         default:
3837                 return 0;
3838         }
3839
3840         /* never reached */
3841 }
3842
3843 /**
3844  *      ata_qc_issue - issue taskfile to device
3845  *      @qc: command to issue to device
3846  *
3847  *      Prepare an ATA command to submission to device.
3848  *      This includes mapping the data into a DMA-able
3849  *      area, filling in the S/G table, and finally
3850  *      writing the taskfile to hardware, starting the command.
3851  *
3852  *      LOCKING:
3853  *      spin_lock_irqsave(host_set lock)
3854  *
3855  *      RETURNS:
3856  *      Zero on success, negative on error.
3857  */
3858
3859 int ata_qc_issue(struct ata_queued_cmd *qc)
3860 {
3861         struct ata_port *ap = qc->ap;
3862
3863         if (ata_should_dma_map(qc)) {
3864                 if (qc->flags & ATA_QCFLAG_SG) {
3865                         if (ata_sg_setup(qc))
3866                                 goto err_out;
3867                 } else if (qc->flags & ATA_QCFLAG_SINGLE) {
3868                         if (ata_sg_setup_one(qc))
3869                                 goto err_out;
3870                 }
3871         } else {
3872                 qc->flags &= ~ATA_QCFLAG_DMAMAP;
3873         }
3874
3875         ap->ops->qc_prep(qc);
3876
3877         qc->ap->active_tag = qc->tag;
3878         qc->flags |= ATA_QCFLAG_ACTIVE;
3879
3880         return ap->ops->qc_issue(qc);
3881
3882 err_out:
3883         return -1;
3884 }
3885
3886
3887 /**
3888  *      ata_qc_issue_prot - issue taskfile to device in proto-dependent manner
3889  *      @qc: command to issue to device
3890  *
3891  *      Using various libata functions and hooks, this function
3892  *      starts an ATA command.  ATA commands are grouped into
3893  *      classes called "protocols", and issuing each type of protocol
3894  *      is slightly different.
3895  *
3896  *      May be used as the qc_issue() entry in ata_port_operations.
3897  *
3898  *      LOCKING:
3899  *      spin_lock_irqsave(host_set lock)
3900  *
3901  *      RETURNS:
3902  *      Zero on success, negative on error.
3903  */
3904
3905 int ata_qc_issue_prot(struct ata_queued_cmd *qc)
3906 {
3907         struct ata_port *ap = qc->ap;
3908
3909         /* Use polling pio if the LLD doesn't handle
3910          * interrupt driven pio and atapi CDB interrupt.
3911          */
3912         if (ap->flags & ATA_FLAG_PIO_POLLING) {
3913                 switch (qc->tf.protocol) {
3914                 case ATA_PROT_PIO:
3915                 case ATA_PROT_ATAPI:
3916                 case ATA_PROT_ATAPI_NODATA:
3917                         qc->tf.flags |= ATA_TFLAG_POLLING;
3918                         break;
3919                 case ATA_PROT_ATAPI_DMA:
3920                         if (qc->dev->flags & ATA_DFLAG_CDB_INTR)
3921                                 BUG();
3922                         break;
3923                 default:
3924                         break;
3925                 }
3926         }
3927
3928         /* select the device */
3929         ata_dev_select(ap, qc->dev->devno, 1, 0);
3930
3931         /* start the command */
3932         switch (qc->tf.protocol) {
3933         case ATA_PROT_NODATA:
3934                 if (qc->tf.flags & ATA_TFLAG_POLLING)
3935                         ata_qc_set_polling(qc);
3936
3937                 ata_tf_to_host(ap, &qc->tf);
3938                 ap->hsm_task_state = HSM_ST_LAST;
3939
3940                 if (qc->tf.flags & ATA_TFLAG_POLLING)
3941                         queue_work(ata_wq, &ap->pio_task);
3942
3943                 break;
3944
3945         case ATA_PROT_DMA:
3946                 assert(!(qc->tf.flags & ATA_TFLAG_POLLING));
3947
3948                 ap->ops->tf_load(ap, &qc->tf);   /* load tf registers */
3949                 ap->ops->bmdma_setup(qc);           /* set up bmdma */
3950                 ap->ops->bmdma_start(qc);           /* initiate bmdma */
3951                 ap->hsm_task_state = HSM_ST_LAST;
3952                 break;
3953
3954         case ATA_PROT_PIO:
3955                 if (qc->tf.flags & ATA_TFLAG_POLLING)
3956                         ata_qc_set_polling(qc);
3957
3958                 ata_tf_to_host(ap, &qc->tf);
3959
3960                 if (qc->tf.flags & ATA_TFLAG_WRITE) {
3961                         /* PIO data out protocol */
3962                         ap->hsm_task_state = HSM_ST_FIRST;
3963                         queue_work(ata_wq, &ap->pio_task);
3964
3965                         /* always send first data block using
3966                          * the ata_pio_task() codepath.
3967                          */
3968                 } else {
3969                         /* PIO data in protocol */
3970                         ap->hsm_task_state = HSM_ST;
3971
3972                         if (qc->tf.flags & ATA_TFLAG_POLLING)
3973                                 queue_work(ata_wq, &ap->pio_task);
3974
3975                         /* if polling, ata_pio_task() handles the rest.
3976                          * otherwise, interrupt handler takes over from here.
3977                          */
3978                 }
3979
3980                 break;
3981
3982         case ATA_PROT_ATAPI:
3983         case ATA_PROT_ATAPI_NODATA:
3984                 if (qc->tf.flags & ATA_TFLAG_POLLING)
3985                         ata_qc_set_polling(qc);
3986
3987                 ata_tf_to_host(ap, &qc->tf);
3988                 ap->hsm_task_state = HSM_ST_FIRST;
3989
3990                 /* send cdb by polling if no cdb interrupt */
3991                 if ((!(qc->dev->flags & ATA_DFLAG_CDB_INTR)) ||
3992                     (qc->tf.flags & ATA_TFLAG_POLLING))
3993                         queue_work(ata_wq, &ap->pio_task);
3994                 break;
3995
3996         case ATA_PROT_ATAPI_DMA:
3997                 assert(!(qc->tf.flags & ATA_TFLAG_POLLING));
3998
3999                 ap->ops->tf_load(ap, &qc->tf);   /* load tf registers */
4000                 ap->ops->bmdma_setup(qc);           /* set up bmdma */
4001                 ap->hsm_task_state = HSM_ST_FIRST;
4002
4003                 /* send cdb by polling if no cdb interrupt */
4004                 if (!(qc->dev->flags & ATA_DFLAG_CDB_INTR))
4005                         queue_work(ata_wq, &ap->pio_task);
4006                 break;
4007
4008         default:
4009                 WARN_ON(1);
4010                 return -1;
4011         }
4012
4013         return 0;
4014 }
4015
4016 /**
4017  *      ata_bmdma_setup_mmio - Set up PCI IDE BMDMA transaction
4018  *      @qc: Info associated with this ATA transaction.
4019  *
4020  *      LOCKING:
4021  *      spin_lock_irqsave(host_set lock)
4022  */
4023
4024 static void ata_bmdma_setup_mmio (struct ata_queued_cmd *qc)
4025 {
4026         struct ata_port *ap = qc->ap;
4027         unsigned int rw = (qc->tf.flags & ATA_TFLAG_WRITE);
4028         u8 dmactl;
4029         void __iomem *mmio = (void __iomem *) ap->ioaddr.bmdma_addr;
4030
4031         /* load PRD table addr. */
4032         mb();   /* make sure PRD table writes are visible to controller */
4033         writel(ap->prd_dma, mmio + ATA_DMA_TABLE_OFS);
4034
4035         /* specify data direction, triple-check start bit is clear */
4036         dmactl = readb(mmio + ATA_DMA_CMD);
4037         dmactl &= ~(ATA_DMA_WR | ATA_DMA_START);
4038         if (!rw)
4039                 dmactl |= ATA_DMA_WR;
4040         writeb(dmactl, mmio + ATA_DMA_CMD);
4041
4042         /* issue r/w command */
4043         ap->ops->exec_command(ap, &qc->tf);
4044 }
4045
4046 /**
4047  *      ata_bmdma_start_mmio - Start a PCI IDE BMDMA transaction
4048  *      @qc: Info associated with this ATA transaction.
4049  *
4050  *      LOCKING:
4051  *      spin_lock_irqsave(host_set lock)
4052  */
4053
4054 static void ata_bmdma_start_mmio (struct ata_queued_cmd *qc)
4055 {
4056         struct ata_port *ap = qc->ap;
4057         void __iomem *mmio = (void __iomem *) ap->ioaddr.bmdma_addr;
4058         u8 dmactl;
4059
4060         /* start host DMA transaction */
4061         dmactl = readb(mmio + ATA_DMA_CMD);
4062         writeb(dmactl | ATA_DMA_START, mmio + ATA_DMA_CMD);
4063
4064         /* Strictly, one may wish to issue a readb() here, to
4065          * flush the mmio write.  However, control also passes
4066          * to the hardware at this point, and it will interrupt
4067          * us when we are to resume control.  So, in effect,
4068          * we don't care when the mmio write flushes.
4069          * Further, a read of the DMA status register _immediately_
4070          * following the write may not be what certain flaky hardware
4071          * is expected, so I think it is best to not add a readb()
4072          * without first all the MMIO ATA cards/mobos.
4073          * Or maybe I'm just being paranoid.
4074          */
4075 }
4076
4077 /**
4078  *      ata_bmdma_setup_pio - Set up PCI IDE BMDMA transaction (PIO)
4079  *      @qc: Info associated with this ATA transaction.
4080  *
4081  *      LOCKING:
4082  *      spin_lock_irqsave(host_set lock)
4083  */
4084
4085 static void ata_bmdma_setup_pio (struct ata_queued_cmd *qc)
4086 {
4087         struct ata_port *ap = qc->ap;
4088         unsigned int rw = (qc->tf.flags & ATA_TFLAG_WRITE);
4089         u8 dmactl;
4090
4091         /* load PRD table addr. */
4092         outl(ap->prd_dma, ap->ioaddr.bmdma_addr + ATA_DMA_TABLE_OFS);
4093
4094         /* specify data direction, triple-check start bit is clear */
4095         dmactl = inb(ap->ioaddr.bmdma_addr + ATA_DMA_CMD);
4096         dmactl &= ~(ATA_DMA_WR | ATA_DMA_START);
4097         if (!rw)
4098                 dmactl |= ATA_DMA_WR;
4099         outb(dmactl, ap->ioaddr.bmdma_addr + ATA_DMA_CMD);
4100
4101         /* issue r/w command */
4102         ap->ops->exec_command(ap, &qc->tf);
4103 }
4104
4105 /**
4106  *      ata_bmdma_start_pio - Start a PCI IDE BMDMA transaction (PIO)
4107  *      @qc: Info associated with this ATA transaction.
4108  *
4109  *      LOCKING:
4110  *      spin_lock_irqsave(host_set lock)
4111  */
4112
4113 static void ata_bmdma_start_pio (struct ata_queued_cmd *qc)
4114 {
4115         struct ata_port *ap = qc->ap;
4116         u8 dmactl;
4117
4118         /* start host DMA transaction */
4119         dmactl = inb(ap->ioaddr.bmdma_addr + ATA_DMA_CMD);
4120         outb(dmactl | ATA_DMA_START,
4121              ap->ioaddr.bmdma_addr + ATA_DMA_CMD);
4122 }
4123
4124
4125 /**
4126  *      ata_bmdma_start - Start a PCI IDE BMDMA transaction
4127  *      @qc: Info associated with this ATA transaction.
4128  *
4129  *      Writes the ATA_DMA_START flag to the DMA command register.
4130  *
4131  *      May be used as the bmdma_start() entry in ata_port_operations.
4132  *
4133  *      LOCKING:
4134  *      spin_lock_irqsave(host_set lock)
4135  */
4136 void ata_bmdma_start(struct ata_queued_cmd *qc)
4137 {
4138         if (qc->ap->flags & ATA_FLAG_MMIO)
4139                 ata_bmdma_start_mmio(qc);
4140         else
4141                 ata_bmdma_start_pio(qc);
4142 }
4143
4144
4145 /**
4146  *      ata_bmdma_setup - Set up PCI IDE BMDMA transaction
4147  *      @qc: Info associated with this ATA transaction.
4148  *
4149  *      Writes address of PRD table to device's PRD Table Address
4150  *      register, sets the DMA control register, and calls
4151  *      ops->exec_command() to start the transfer.
4152  *
4153  *      May be used as the bmdma_setup() entry in ata_port_operations.
4154  *
4155  *      LOCKING:
4156  *      spin_lock_irqsave(host_set lock)
4157  */
4158 void ata_bmdma_setup(struct ata_queued_cmd *qc)
4159 {
4160         if (qc->ap->flags & ATA_FLAG_MMIO)
4161                 ata_bmdma_setup_mmio(qc);
4162         else
4163                 ata_bmdma_setup_pio(qc);
4164 }
4165
4166
4167 /**
4168  *      ata_bmdma_irq_clear - Clear PCI IDE BMDMA interrupt.
4169  *      @ap: Port associated with this ATA transaction.
4170  *
4171  *      Clear interrupt and error flags in DMA status register.
4172  *
4173  *      May be used as the irq_clear() entry in ata_port_operations.
4174  *
4175  *      LOCKING:
4176  *      spin_lock_irqsave(host_set lock)
4177  */
4178
4179 void ata_bmdma_irq_clear(struct ata_port *ap)
4180 {
4181     if (ap->flags & ATA_FLAG_MMIO) {
4182         void __iomem *mmio = ((void __iomem *) ap->ioaddr.bmdma_addr) + ATA_DMA_STATUS;
4183         writeb(readb(mmio), mmio);
4184     } else {
4185         unsigned long addr = ap->ioaddr.bmdma_addr + ATA_DMA_STATUS;
4186         outb(inb(addr), addr);
4187     }
4188
4189 }
4190
4191
4192 /**
4193  *      ata_bmdma_status - Read PCI IDE BMDMA status
4194  *      @ap: Port associated with this ATA transaction.
4195  *
4196  *      Read and return BMDMA status register.
4197  *
4198  *      May be used as the bmdma_status() entry in ata_port_operations.
4199  *
4200  *      LOCKING:
4201  *      spin_lock_irqsave(host_set lock)
4202  */
4203
4204 u8 ata_bmdma_status(struct ata_port *ap)
4205 {
4206         u8 host_stat;
4207         if (ap->flags & ATA_FLAG_MMIO) {
4208                 void __iomem *mmio = (void __iomem *) ap->ioaddr.bmdma_addr;
4209                 host_stat = readb(mmio + ATA_DMA_STATUS);
4210         } else
4211                 host_stat = inb(ap->ioaddr.bmdma_addr + ATA_DMA_STATUS);
4212         return host_stat;
4213 }
4214
4215
4216 /**
4217  *      ata_bmdma_stop - Stop PCI IDE BMDMA transfer
4218  *      @qc: Command we are ending DMA for
4219  *
4220  *      Clears the ATA_DMA_START flag in the dma control register
4221  *
4222  *      May be used as the bmdma_stop() entry in ata_port_operations.
4223  *
4224  *      LOCKING:
4225  *      spin_lock_irqsave(host_set lock)
4226  */
4227
4228 void ata_bmdma_stop(struct ata_queued_cmd *qc)
4229 {
4230         struct ata_port *ap = qc->ap;
4231         if (ap->flags & ATA_FLAG_MMIO) {
4232                 void __iomem *mmio = (void __iomem *) ap->ioaddr.bmdma_addr;
4233
4234                 /* clear start/stop bit */
4235                 writeb(readb(mmio + ATA_DMA_CMD) & ~ATA_DMA_START,
4236                         mmio + ATA_DMA_CMD);
4237         } else {
4238                 /* clear start/stop bit */
4239                 outb(inb(ap->ioaddr.bmdma_addr + ATA_DMA_CMD) & ~ATA_DMA_START,
4240                         ap->ioaddr.bmdma_addr + ATA_DMA_CMD);
4241         }
4242
4243         /* one-PIO-cycle guaranteed wait, per spec, for HDMA1:0 transition */
4244         ata_altstatus(ap);        /* dummy read */
4245 }
4246
4247 /**
4248  *      ata_host_intr - Handle host interrupt for given (port, task)
4249  *      @ap: Port on which interrupt arrived (possibly...)
4250  *      @qc: Taskfile currently active in engine
4251  *
4252  *      Handle host interrupt for given queued command.  Currently,
4253  *      only DMA interrupts are handled.  All other commands are
4254  *      handled via polling with interrupts disabled (nIEN bit).
4255  *
4256  *      LOCKING:
4257  *      spin_lock_irqsave(host_set lock)
4258  *
4259  *      RETURNS:
4260  *      One if interrupt was handled, zero if not (shared irq).
4261  */
4262
4263 inline unsigned int ata_host_intr (struct ata_port *ap,
4264                                    struct ata_queued_cmd *qc)
4265 {
4266         u8 status, host_stat = 0;
4267
4268         VPRINTK("ata%u: protocol %d task_state %d\n",
4269                 ap->id, qc->tf.protocol, ap->hsm_task_state);
4270
4271         /* Check whether we are expecting interrupt in this state */
4272         switch (ap->hsm_task_state) {
4273         case HSM_ST_FIRST:
4274                 /* Check the ATA_DFLAG_CDB_INTR flag is enough here.
4275                  * The flag was turned on only for atapi devices.
4276                  * No need to check is_atapi_taskfile(&qc->tf) again.
4277                  */
4278                 if (!(qc->dev->flags & ATA_DFLAG_CDB_INTR))
4279                         goto idle_irq;
4280                 break;
4281         case HSM_ST_LAST:
4282                 if (qc->tf.protocol == ATA_PROT_DMA ||
4283                     qc->tf.protocol == ATA_PROT_ATAPI_DMA) {
4284                         /* check status of DMA engine */
4285                         host_stat = ap->ops->bmdma_status(ap);
4286                         VPRINTK("ata%u: host_stat 0x%X\n", ap->id, host_stat);
4287
4288                         /* if it's not our irq... */
4289                         if (!(host_stat & ATA_DMA_INTR))
4290                                 goto idle_irq;
4291
4292                         /* before we do anything else, clear DMA-Start bit */
4293                         ap->ops->bmdma_stop(qc);
4294
4295                         if (unlikely(host_stat & ATA_DMA_ERR)) {
4296                                 /* error when transfering data to/from memory */
4297                                 qc->err_mask |= AC_ERR_HOST_BUS;
4298                                 ap->hsm_task_state = HSM_ST_ERR;
4299                         }
4300                 }
4301                 break;
4302         case HSM_ST:
4303                 break;
4304         default:
4305                 goto idle_irq;
4306         }
4307
4308         /* check altstatus */
4309         status = ata_altstatus(ap);
4310         if (status & ATA_BUSY)
4311                 goto idle_irq;
4312
4313         /* check main status, clearing INTRQ */
4314         status = ata_chk_status(ap);
4315         if (unlikely(status & ATA_BUSY))
4316                 goto idle_irq;
4317
4318         DPRINTK("ata%u: protocol %d task_state %d (dev_stat 0x%X)\n",
4319                 ap->id, qc->tf.protocol, ap->hsm_task_state, status);
4320
4321         /* ack bmdma irq events */
4322         ap->ops->irq_clear(ap);
4323
4324         /* check error */
4325         if (unlikely(status & (ATA_ERR | ATA_DF))) {
4326                 qc->err_mask |= AC_ERR_DEV;
4327                 ap->hsm_task_state = HSM_ST_ERR;
4328         }
4329
4330 fsm_start:
4331         switch (ap->hsm_task_state) {
4332         case HSM_ST_FIRST:
4333                 /* Some pre-ATAPI-4 devices assert INTRQ 
4334                  * at this state when ready to receive CDB.
4335                  */
4336
4337                 /* check device status */
4338                 if (unlikely((status & (ATA_BUSY | ATA_DRQ)) != ATA_DRQ)) {
4339                         /* Wrong status. Let EH handle this */
4340                         qc->err_mask |= AC_ERR_ATA_BUS;
4341                         ap->hsm_task_state = HSM_ST_ERR;
4342                         goto fsm_start;
4343                 }
4344
4345                 atapi_send_cdb(ap, qc);
4346
4347                 break;
4348
4349         case HSM_ST:
4350                 /* complete command or read/write the data register */
4351                 if (qc->tf.protocol == ATA_PROT_ATAPI) {
4352                         /* ATAPI PIO protocol */
4353                         if ((status & ATA_DRQ) == 0) {
4354                                 /* no more data to transfer */
4355                                 ap->hsm_task_state = HSM_ST_LAST;
4356                                 goto fsm_start;
4357                         }
4358                         
4359                         atapi_pio_bytes(qc);
4360
4361                         if (unlikely(ap->hsm_task_state == HSM_ST_ERR))
4362                                 /* bad ireason reported by device */
4363                                 goto fsm_start;
4364
4365                 } else {
4366                         /* ATA PIO protocol */
4367                         if (unlikely((status & ATA_DRQ) == 0)) {
4368                                 /* handle BSY=0, DRQ=0 as error */
4369                                 qc->err_mask |= AC_ERR_ATA_BUS;
4370                                 ap->hsm_task_state = HSM_ST_ERR;
4371                                 goto fsm_start;
4372                         }
4373
4374                         ata_pio_sectors(qc);
4375
4376                         if (ap->hsm_task_state == HSM_ST_LAST &&
4377                             (!(qc->tf.flags & ATA_TFLAG_WRITE))) {
4378                                 /* all data read */
4379                                 ata_altstatus(ap);
4380                                 status = ata_chk_status(ap);
4381                                 goto fsm_start;
4382                         }
4383                 }
4384
4385                 ata_altstatus(ap); /* flush */
4386                 break;
4387
4388         case HSM_ST_LAST:
4389                 if (unlikely(status & ATA_DRQ)) {
4390                         /* handle DRQ=1 as error */
4391                         qc->err_mask |= AC_ERR_ATA_BUS;
4392                         ap->hsm_task_state = HSM_ST_ERR;
4393                         goto fsm_start;
4394                 }
4395
4396                 /* no more data to transfer */
4397                 DPRINTK("ata%u: command complete, drv_stat 0x%x\n",
4398                         ap->id, status);
4399
4400                 ap->hsm_task_state = HSM_ST_IDLE;
4401
4402                 /* complete taskfile transaction */
4403                 qc->err_mask |= ac_err_mask(status);
4404                 ata_qc_complete(qc);
4405                 break;
4406
4407         case HSM_ST_ERR:
4408                 if (qc->tf.command != ATA_CMD_PACKET)
4409                         printk(KERN_ERR "ata%u: command error, drv_stat 0x%x host_stat 0x%x\n",
4410                                ap->id, status, host_stat);
4411
4412                 /* make sure qc->err_mask is available to 
4413                  * know what's wrong and recover
4414                  */
4415                 assert(qc->err_mask);
4416
4417                 ap->hsm_task_state = HSM_ST_IDLE;
4418                 ata_qc_complete(qc);
4419                 break;
4420         default:
4421                 goto idle_irq;
4422         }
4423
4424         return 1;       /* irq handled */
4425
4426 idle_irq:
4427         ap->stats.idle_irq++;
4428
4429 #ifdef ATA_IRQ_TRAP
4430         if ((ap->stats.idle_irq % 1000) == 0) {
4431                 handled = 1;
4432                 ata_irq_ack(ap, 0); /* debug trap */
4433                 printk(KERN_WARNING "ata%d: irq trap\n", ap->id);
4434         }
4435 #endif
4436         return 0;       /* irq not handled */
4437 }
4438
4439 /**
4440  *      ata_interrupt - Default ATA host interrupt handler
4441  *      @irq: irq line (unused)
4442  *      @dev_instance: pointer to our ata_host_set information structure
4443  *      @regs: unused
4444  *
4445  *      Default interrupt handler for PCI IDE devices.  Calls
4446  *      ata_host_intr() for each port that is not disabled.
4447  *
4448  *      LOCKING:
4449  *      Obtains host_set lock during operation.
4450  *
4451  *      RETURNS:
4452  *      IRQ_NONE or IRQ_HANDLED.
4453  */
4454
4455 irqreturn_t ata_interrupt (int irq, void *dev_instance, struct pt_regs *regs)
4456 {
4457         struct ata_host_set *host_set = dev_instance;
4458         unsigned int i;
4459         unsigned int handled = 0;
4460         unsigned long flags;
4461
4462         /* TODO: make _irqsave conditional on x86 PCI IDE legacy mode */
4463         spin_lock_irqsave(&host_set->lock, flags);
4464
4465         for (i = 0; i < host_set->n_ports; i++) {
4466                 struct ata_port *ap;
4467
4468                 ap = host_set->ports[i];
4469                 if (ap &&
4470                     !(ap->flags & ATA_FLAG_PORT_DISABLED)) {
4471                         struct ata_queued_cmd *qc;
4472
4473                         qc = ata_qc_from_tag(ap, ap->active_tag);
4474                         if (qc && (!(qc->tf.flags & ATA_TFLAG_POLLING)) &&
4475                             (qc->flags & ATA_QCFLAG_ACTIVE))
4476                                 handled |= ata_host_intr(ap, qc);
4477                 }
4478         }
4479
4480         spin_unlock_irqrestore(&host_set->lock, flags);
4481
4482         return IRQ_RETVAL(handled);
4483 }
4484
4485 /**
4486  *      ata_port_start - Set port up for dma.
4487  *      @ap: Port to initialize
4488  *
4489  *      Called just after data structures for each port are
4490  *      initialized.  Allocates space for PRD table.
4491  *
4492  *      May be used as the port_start() entry in ata_port_operations.
4493  *
4494  *      LOCKING:
4495  *      Inherited from caller.
4496  */
4497
4498 /*
4499  * Execute a 'simple' command, that only consists of the opcode 'cmd' itself,
4500  * without filling any other registers
4501  */
4502 static int ata_do_simple_cmd(struct ata_port *ap, struct ata_device *dev,
4503                              u8 cmd)
4504 {
4505         struct ata_taskfile tf;
4506         int err;
4507
4508         ata_tf_init(ap, &tf, dev->devno);
4509
4510         tf.command = cmd;
4511         tf.flags |= ATA_TFLAG_DEVICE;
4512         tf.protocol = ATA_PROT_NODATA;
4513
4514         err = ata_exec_internal(ap, dev, &tf, DMA_NONE, NULL, 0);
4515         if (err)
4516                 printk(KERN_ERR "%s: ata command failed: %d\n",
4517                                 __FUNCTION__, err);
4518
4519         return err;
4520 }
4521
4522 static int ata_flush_cache(struct ata_port *ap, struct ata_device *dev)
4523 {
4524         u8 cmd;
4525
4526         if (!ata_try_flush_cache(dev))
4527                 return 0;
4528
4529         if (ata_id_has_flush_ext(dev->id))
4530                 cmd = ATA_CMD_FLUSH_EXT;
4531         else
4532                 cmd = ATA_CMD_FLUSH;
4533
4534         return ata_do_simple_cmd(ap, dev, cmd);
4535 }
4536
4537 static int ata_standby_drive(struct ata_port *ap, struct ata_device *dev)
4538 {
4539         return ata_do_simple_cmd(ap, dev, ATA_CMD_STANDBYNOW1);
4540 }
4541
4542 static int ata_start_drive(struct ata_port *ap, struct ata_device *dev)
4543 {
4544         return ata_do_simple_cmd(ap, dev, ATA_CMD_IDLEIMMEDIATE);
4545 }
4546
4547 /**
4548  *      ata_device_resume - wakeup a previously suspended devices
4549  *
4550  *      Kick the drive back into action, by sending it an idle immediate
4551  *      command and making sure its transfer mode matches between drive
4552  *      and host.
4553  *
4554  */
4555 int ata_device_resume(struct ata_port *ap, struct ata_device *dev)
4556 {
4557         if (ap->flags & ATA_FLAG_SUSPENDED) {
4558                 ap->flags &= ~ATA_FLAG_SUSPENDED;
4559                 ata_set_mode(ap);
4560         }
4561         if (!ata_dev_present(dev))
4562                 return 0;
4563         if (dev->class == ATA_DEV_ATA)
4564                 ata_start_drive(ap, dev);
4565
4566         return 0;
4567 }
4568
4569 /**
4570  *      ata_device_suspend - prepare a device for suspend
4571  *
4572  *      Flush the cache on the drive, if appropriate, then issue a
4573  *      standbynow command.
4574  *
4575  */
4576 int ata_device_suspend(struct ata_port *ap, struct ata_device *dev)
4577 {
4578         if (!ata_dev_present(dev))
4579                 return 0;
4580         if (dev->class == ATA_DEV_ATA)
4581                 ata_flush_cache(ap, dev);
4582
4583         ata_standby_drive(ap, dev);
4584         ap->flags |= ATA_FLAG_SUSPENDED;
4585         return 0;
4586 }
4587
4588 int ata_port_start (struct ata_port *ap)
4589 {
4590         struct device *dev = ap->host_set->dev;
4591         int rc;
4592
4593         ap->prd = dma_alloc_coherent(dev, ATA_PRD_TBL_SZ, &ap->prd_dma, GFP_KERNEL);
4594         if (!ap->prd)
4595                 return -ENOMEM;
4596
4597         rc = ata_pad_alloc(ap, dev);
4598         if (rc) {
4599                 dma_free_coherent(dev, ATA_PRD_TBL_SZ, ap->prd, ap->prd_dma);
4600                 return rc;
4601         }
4602
4603         DPRINTK("prd alloc, virt %p, dma %llx\n", ap->prd, (unsigned long long) ap->prd_dma);
4604
4605         return 0;
4606 }
4607
4608
4609 /**
4610  *      ata_port_stop - Undo ata_port_start()
4611  *      @ap: Port to shut down
4612  *
4613  *      Frees the PRD table.
4614  *
4615  *      May be used as the port_stop() entry in ata_port_operations.
4616  *
4617  *      LOCKING:
4618  *      Inherited from caller.
4619  */
4620
4621 void ata_port_stop (struct ata_port *ap)
4622 {
4623         struct device *dev = ap->host_set->dev;
4624
4625         dma_free_coherent(dev, ATA_PRD_TBL_SZ, ap->prd, ap->prd_dma);
4626         ata_pad_free(ap, dev);
4627 }
4628
4629 void ata_host_stop (struct ata_host_set *host_set)
4630 {
4631         if (host_set->mmio_base)
4632                 iounmap(host_set->mmio_base);
4633 }
4634
4635
4636 /**
4637  *      ata_host_remove - Unregister SCSI host structure with upper layers
4638  *      @ap: Port to unregister
4639  *      @do_unregister: 1 if we fully unregister, 0 to just stop the port
4640  *
4641  *      LOCKING:
4642  *      Inherited from caller.
4643  */
4644
4645 static void ata_host_remove(struct ata_port *ap, unsigned int do_unregister)
4646 {
4647         struct Scsi_Host *sh = ap->host;
4648
4649         DPRINTK("ENTER\n");
4650
4651         if (do_unregister)
4652                 scsi_remove_host(sh);
4653
4654         ap->ops->port_stop(ap);
4655 }
4656
4657 /**
4658  *      ata_host_init - Initialize an ata_port structure
4659  *      @ap: Structure to initialize
4660  *      @host: associated SCSI mid-layer structure
4661  *      @host_set: Collection of hosts to which @ap belongs
4662  *      @ent: Probe information provided by low-level driver
4663  *      @port_no: Port number associated with this ata_port
4664  *
4665  *      Initialize a new ata_port structure, and its associated
4666  *      scsi_host.
4667  *
4668  *      LOCKING:
4669  *      Inherited from caller.
4670  */
4671
4672 static void ata_host_init(struct ata_port *ap, struct Scsi_Host *host,
4673                           struct ata_host_set *host_set,
4674                           const struct ata_probe_ent *ent, unsigned int port_no)
4675 {
4676         unsigned int i;
4677
4678         host->max_id = 16;
4679         host->max_lun = 1;
4680         host->max_channel = 1;
4681         host->unique_id = ata_unique_id++;
4682         host->max_cmd_len = 12;
4683
4684         ap->flags = ATA_FLAG_PORT_DISABLED;
4685         ap->id = host->unique_id;
4686         ap->host = host;
4687         ap->ctl = ATA_DEVCTL_OBS;
4688         ap->host_set = host_set;
4689         ap->port_no = port_no;
4690         ap->hard_port_no =
4691                 ent->legacy_mode ? ent->hard_port_no : port_no;
4692         ap->pio_mask = ent->pio_mask;
4693         ap->mwdma_mask = ent->mwdma_mask;
4694         ap->udma_mask = ent->udma_mask;
4695         ap->flags |= ent->host_flags;
4696         ap->ops = ent->port_ops;
4697         ap->cbl = ATA_CBL_NONE;
4698         ap->active_tag = ATA_TAG_POISON;
4699         ap->last_ctl = 0xFF;
4700
4701         INIT_WORK(&ap->pio_task, ata_pio_task, ap);
4702
4703         for (i = 0; i < ATA_MAX_DEVICES; i++)
4704                 ap->device[i].devno = i;
4705
4706 #ifdef ATA_IRQ_TRAP
4707         ap->stats.unhandled_irq = 1;
4708         ap->stats.idle_irq = 1;
4709 #endif
4710
4711         memcpy(&ap->ioaddr, &ent->port[port_no], sizeof(struct ata_ioports));
4712 }
4713
4714 /**
4715  *      ata_host_add - Attach low-level ATA driver to system
4716  *      @ent: Information provided by low-level driver
4717  *      @host_set: Collections of ports to which we add
4718  *      @port_no: Port number associated with this host
4719  *
4720  *      Attach low-level ATA driver to system.
4721  *
4722  *      LOCKING:
4723  *      PCI/etc. bus probe sem.
4724  *
4725  *      RETURNS:
4726  *      New ata_port on success, for NULL on error.
4727  */
4728
4729 static struct ata_port * ata_host_add(const struct ata_probe_ent *ent,
4730                                       struct ata_host_set *host_set,
4731                                       unsigned int port_no)
4732 {
4733         struct Scsi_Host *host;
4734         struct ata_port *ap;
4735         int rc;
4736
4737         DPRINTK("ENTER\n");
4738         host = scsi_host_alloc(ent->sht, sizeof(struct ata_port));
4739         if (!host)
4740                 return NULL;
4741
4742         ap = (struct ata_port *) &host->hostdata[0];
4743
4744         ata_host_init(ap, host, host_set, ent, port_no);
4745
4746         rc = ap->ops->port_start(ap);
4747         if (rc)
4748                 goto err_out;
4749
4750         return ap;
4751
4752 err_out:
4753         scsi_host_put(host);
4754         return NULL;
4755 }
4756
4757 /**
4758  *      ata_device_add - Register hardware device with ATA and SCSI layers
4759  *      @ent: Probe information describing hardware device to be registered
4760  *
4761  *      This function processes the information provided in the probe
4762  *      information struct @ent, allocates the necessary ATA and SCSI
4763  *      host information structures, initializes them, and registers
4764  *      everything with requisite kernel subsystems.
4765  *
4766  *      This function requests irqs, probes the ATA bus, and probes
4767  *      the SCSI bus.
4768  *
4769  *      LOCKING:
4770  *      PCI/etc. bus probe sem.
4771  *
4772  *      RETURNS:
4773  *      Number of ports registered.  Zero on error (no ports registered).
4774  */
4775
4776 int ata_device_add(const struct ata_probe_ent *ent)
4777 {
4778         unsigned int count = 0, i;
4779         struct device *dev = ent->dev;
4780         struct ata_host_set *host_set;
4781
4782         DPRINTK("ENTER\n");
4783         /* alloc a container for our list of ATA ports (buses) */
4784         host_set = kzalloc(sizeof(struct ata_host_set) +
4785                            (ent->n_ports * sizeof(void *)), GFP_KERNEL);
4786         if (!host_set)
4787                 return 0;
4788         spin_lock_init(&host_set->lock);
4789
4790         host_set->dev = dev;
4791         host_set->n_ports = ent->n_ports;
4792         host_set->irq = ent->irq;
4793         host_set->mmio_base = ent->mmio_base;
4794         host_set->private_data = ent->private_data;
4795         host_set->ops = ent->port_ops;
4796
4797         /* register each port bound to this device */
4798         for (i = 0; i < ent->n_ports; i++) {
4799                 struct ata_port *ap;
4800                 unsigned long xfer_mode_mask;
4801
4802                 ap = ata_host_add(ent, host_set, i);
4803                 if (!ap)
4804                         goto err_out;
4805
4806                 host_set->ports[i] = ap;
4807                 xfer_mode_mask =(ap->udma_mask << ATA_SHIFT_UDMA) |
4808                                 (ap->mwdma_mask << ATA_SHIFT_MWDMA) |
4809                                 (ap->pio_mask << ATA_SHIFT_PIO);
4810
4811                 /* print per-port info to dmesg */
4812                 printk(KERN_INFO "ata%u: %cATA max %s cmd 0x%lX ctl 0x%lX "
4813                                  "bmdma 0x%lX irq %lu\n",
4814                         ap->id,
4815                         ap->flags & ATA_FLAG_SATA ? 'S' : 'P',
4816                         ata_mode_string(xfer_mode_mask),
4817                         ap->ioaddr.cmd_addr,
4818                         ap->ioaddr.ctl_addr,
4819                         ap->ioaddr.bmdma_addr,
4820                         ent->irq);
4821
4822                 ata_chk_status(ap);
4823                 host_set->ops->irq_clear(ap);
4824                 count++;
4825         }
4826
4827         if (!count)
4828                 goto err_free_ret;
4829
4830         /* obtain irq, that is shared between channels */
4831         if (request_irq(ent->irq, ent->port_ops->irq_handler, ent->irq_flags,
4832                         DRV_NAME, host_set))
4833                 goto err_out;
4834
4835         /* perform each probe synchronously */
4836         DPRINTK("probe begin\n");
4837         for (i = 0; i < count; i++) {
4838                 struct ata_port *ap;
4839                 int rc;
4840
4841                 ap = host_set->ports[i];
4842
4843                 DPRINTK("ata%u: probe begin\n", ap->id);
4844                 rc = ata_bus_probe(ap);
4845                 DPRINTK("ata%u: probe end\n", ap->id);
4846
4847                 if (rc) {
4848                         /* FIXME: do something useful here?
4849                          * Current libata behavior will
4850                          * tear down everything when
4851                          * the module is removed
4852                          * or the h/w is unplugged.
4853                          */
4854                 }
4855
4856                 rc = scsi_add_host(ap->host, dev);
4857                 if (rc) {
4858                         printk(KERN_ERR "ata%u: scsi_add_host failed\n",
4859                                ap->id);
4860                         /* FIXME: do something useful here */
4861                         /* FIXME: handle unconditional calls to
4862                          * scsi_scan_host and ata_host_remove, below,
4863                          * at the very least
4864                          */
4865                 }
4866         }
4867
4868         /* probes are done, now scan each port's disk(s) */
4869         DPRINTK("probe begin\n");
4870         for (i = 0; i < count; i++) {
4871                 struct ata_port *ap = host_set->ports[i];
4872
4873                 ata_scsi_scan_host(ap);
4874         }
4875
4876         dev_set_drvdata(dev, host_set);
4877
4878         VPRINTK("EXIT, returning %u\n", ent->n_ports);
4879         return ent->n_ports; /* success */
4880
4881 err_out:
4882         for (i = 0; i < count; i++) {
4883                 ata_host_remove(host_set->ports[i], 1);
4884                 scsi_host_put(host_set->ports[i]->host);
4885         }
4886 err_free_ret:
4887         kfree(host_set);
4888         VPRINTK("EXIT, returning 0\n");
4889         return 0;
4890 }
4891
4892 /**
4893  *      ata_host_set_remove - PCI layer callback for device removal
4894  *      @host_set: ATA host set that was removed
4895  *
4896  *      Unregister all objects associated with this host set. Free those 
4897  *      objects.
4898  *
4899  *      LOCKING:
4900  *      Inherited from calling layer (may sleep).
4901  */
4902
4903 void ata_host_set_remove(struct ata_host_set *host_set)
4904 {
4905         struct ata_port *ap;
4906         unsigned int i;
4907
4908         for (i = 0; i < host_set->n_ports; i++) {
4909                 ap = host_set->ports[i];
4910                 scsi_remove_host(ap->host);
4911         }
4912
4913         free_irq(host_set->irq, host_set);
4914
4915         for (i = 0; i < host_set->n_ports; i++) {
4916                 ap = host_set->ports[i];
4917
4918                 ata_scsi_release(ap->host);
4919
4920                 if ((ap->flags & ATA_FLAG_NO_LEGACY) == 0) {
4921                         struct ata_ioports *ioaddr = &ap->ioaddr;
4922
4923                         if (ioaddr->cmd_addr == 0x1f0)
4924                                 release_region(0x1f0, 8);
4925                         else if (ioaddr->cmd_addr == 0x170)
4926                                 release_region(0x170, 8);
4927                 }
4928
4929                 scsi_host_put(ap->host);
4930         }
4931
4932         if (host_set->ops->host_stop)
4933                 host_set->ops->host_stop(host_set);
4934
4935         kfree(host_set);
4936 }
4937
4938 /**
4939  *      ata_scsi_release - SCSI layer callback hook for host unload
4940  *      @host: libata host to be unloaded
4941  *
4942  *      Performs all duties necessary to shut down a libata port...
4943  *      Kill port kthread, disable port, and release resources.
4944  *
4945  *      LOCKING:
4946  *      Inherited from SCSI layer.
4947  *
4948  *      RETURNS:
4949  *      One.
4950  */
4951
4952 int ata_scsi_release(struct Scsi_Host *host)
4953 {
4954         struct ata_port *ap = (struct ata_port *) &host->hostdata[0];
4955
4956         DPRINTK("ENTER\n");
4957
4958         ap->ops->port_disable(ap);
4959         ata_host_remove(ap, 0);
4960
4961         DPRINTK("EXIT\n");
4962         return 1;
4963 }
4964
4965 /**
4966  *      ata_std_ports - initialize ioaddr with standard port offsets.
4967  *      @ioaddr: IO address structure to be initialized
4968  *
4969  *      Utility function which initializes data_addr, error_addr,
4970  *      feature_addr, nsect_addr, lbal_addr, lbam_addr, lbah_addr,
4971  *      device_addr, status_addr, and command_addr to standard offsets
4972  *      relative to cmd_addr.
4973  *
4974  *      Does not set ctl_addr, altstatus_addr, bmdma_addr, or scr_addr.
4975  */
4976
4977 void ata_std_ports(struct ata_ioports *ioaddr)
4978 {
4979         ioaddr->data_addr = ioaddr->cmd_addr + ATA_REG_DATA;
4980         ioaddr->error_addr = ioaddr->cmd_addr + ATA_REG_ERR;
4981         ioaddr->feature_addr = ioaddr->cmd_addr + ATA_REG_FEATURE;
4982         ioaddr->nsect_addr = ioaddr->cmd_addr + ATA_REG_NSECT;
4983         ioaddr->lbal_addr = ioaddr->cmd_addr + ATA_REG_LBAL;
4984         ioaddr->lbam_addr = ioaddr->cmd_addr + ATA_REG_LBAM;
4985         ioaddr->lbah_addr = ioaddr->cmd_addr + ATA_REG_LBAH;
4986         ioaddr->device_addr = ioaddr->cmd_addr + ATA_REG_DEVICE;
4987         ioaddr->status_addr = ioaddr->cmd_addr + ATA_REG_STATUS;
4988         ioaddr->command_addr = ioaddr->cmd_addr + ATA_REG_CMD;
4989 }
4990
4991 static struct ata_probe_ent *
4992 ata_probe_ent_alloc(struct device *dev, const struct ata_port_info *port)
4993 {
4994         struct ata_probe_ent *probe_ent;
4995
4996         probe_ent = kzalloc(sizeof(*probe_ent), GFP_KERNEL);
4997         if (!probe_ent) {
4998                 printk(KERN_ERR DRV_NAME "(%s): out of memory\n",
4999                        kobject_name(&(dev->kobj)));
5000                 return NULL;
5001         }
5002
5003         INIT_LIST_HEAD(&probe_ent->node);
5004         probe_ent->dev = dev;
5005
5006         probe_ent->sht = port->sht;
5007         probe_ent->host_flags = port->host_flags;
5008         probe_ent->pio_mask = port->pio_mask;
5009         probe_ent->mwdma_mask = port->mwdma_mask;
5010         probe_ent->udma_mask = port->udma_mask;
5011         probe_ent->port_ops = port->port_ops;
5012
5013         return probe_ent;
5014 }
5015
5016
5017
5018 #ifdef CONFIG_PCI
5019
5020 void ata_pci_host_stop (struct ata_host_set *host_set)
5021 {
5022         struct pci_dev *pdev = to_pci_dev(host_set->dev);
5023
5024         pci_iounmap(pdev, host_set->mmio_base);
5025 }
5026
5027 /**
5028  *      ata_pci_init_native_mode - Initialize native-mode driver
5029  *      @pdev:  pci device to be initialized
5030  *      @port:  array[2] of pointers to port info structures.
5031  *      @ports: bitmap of ports present
5032  *
5033  *      Utility function which allocates and initializes an
5034  *      ata_probe_ent structure for a standard dual-port
5035  *      PIO-based IDE controller.  The returned ata_probe_ent
5036  *      structure can be passed to ata_device_add().  The returned
5037  *      ata_probe_ent structure should then be freed with kfree().
5038  *
5039  *      The caller need only pass the address of the primary port, the
5040  *      secondary will be deduced automatically. If the device has non
5041  *      standard secondary port mappings this function can be called twice,
5042  *      once for each interface.
5043  */
5044
5045 struct ata_probe_ent *
5046 ata_pci_init_native_mode(struct pci_dev *pdev, struct ata_port_info **port, int ports)
5047 {
5048         struct ata_probe_ent *probe_ent =
5049                 ata_probe_ent_alloc(pci_dev_to_dev(pdev), port[0]);
5050         int p = 0;
5051
5052         if (!probe_ent)
5053                 return NULL;
5054
5055         probe_ent->irq = pdev->irq;
5056         probe_ent->irq_flags = SA_SHIRQ;
5057         probe_ent->private_data = port[0]->private_data;
5058
5059         if (ports & ATA_PORT_PRIMARY) {
5060                 probe_ent->port[p].cmd_addr = pci_resource_start(pdev, 0);
5061                 probe_ent->port[p].altstatus_addr =
5062                 probe_ent->port[p].ctl_addr =
5063                         pci_resource_start(pdev, 1) | ATA_PCI_CTL_OFS;
5064                 probe_ent->port[p].bmdma_addr = pci_resource_start(pdev, 4);
5065                 ata_std_ports(&probe_ent->port[p]);
5066                 p++;
5067         }
5068
5069         if (ports & ATA_PORT_SECONDARY) {
5070                 probe_ent->port[p].cmd_addr = pci_resource_start(pdev, 2);
5071                 probe_ent->port[p].altstatus_addr =
5072                 probe_ent->port[p].ctl_addr =
5073                         pci_resource_start(pdev, 3) | ATA_PCI_CTL_OFS;
5074                 probe_ent->port[p].bmdma_addr = pci_resource_start(pdev, 4) + 8;
5075                 ata_std_ports(&probe_ent->port[p]);
5076                 p++;
5077         }
5078
5079         probe_ent->n_ports = p;
5080         return probe_ent;
5081 }
5082
5083 static struct ata_probe_ent *ata_pci_init_legacy_port(struct pci_dev *pdev, struct ata_port_info *port, int port_num)
5084 {
5085         struct ata_probe_ent *probe_ent;
5086
5087         probe_ent = ata_probe_ent_alloc(pci_dev_to_dev(pdev), port);
5088         if (!probe_ent)
5089                 return NULL;
5090
5091         probe_ent->legacy_mode = 1;
5092         probe_ent->n_ports = 1;
5093         probe_ent->hard_port_no = port_num;
5094         probe_ent->private_data = port->private_data;
5095
5096         switch(port_num)
5097         {
5098                 case 0:
5099                         probe_ent->irq = 14;
5100                         probe_ent->port[0].cmd_addr = 0x1f0;
5101                         probe_ent->port[0].altstatus_addr =
5102                         probe_ent->port[0].ctl_addr = 0x3f6;
5103                         break;
5104                 case 1:
5105                         probe_ent->irq = 15;
5106                         probe_ent->port[0].cmd_addr = 0x170;
5107                         probe_ent->port[0].altstatus_addr =
5108                         probe_ent->port[0].ctl_addr = 0x376;
5109                         break;
5110         }
5111         probe_ent->port[0].bmdma_addr = pci_resource_start(pdev, 4) + 8 * port_num;
5112         ata_std_ports(&probe_ent->port[0]);
5113         return probe_ent;
5114 }
5115
5116 /**
5117  *      ata_pci_init_one - Initialize/register PCI IDE host controller
5118  *      @pdev: Controller to be initialized
5119  *      @port_info: Information from low-level host driver
5120  *      @n_ports: Number of ports attached to host controller
5121  *
5122  *      This is a helper function which can be called from a driver's
5123  *      xxx_init_one() probe function if the hardware uses traditional
5124  *      IDE taskfile registers.
5125  *
5126  *      This function calls pci_enable_device(), reserves its register
5127  *      regions, sets the dma mask, enables bus master mode, and calls
5128  *      ata_device_add()
5129  *
5130  *      LOCKING:
5131  *      Inherited from PCI layer (may sleep).
5132  *
5133  *      RETURNS:
5134  *      Zero on success, negative on errno-based value on error.
5135  */
5136
5137 int ata_pci_init_one (struct pci_dev *pdev, struct ata_port_info **port_info,
5138                       unsigned int n_ports)
5139 {
5140         struct ata_probe_ent *probe_ent = NULL, *probe_ent2 = NULL;
5141         struct ata_port_info *port[2];
5142         u8 tmp8, mask;
5143         unsigned int legacy_mode = 0;
5144         int disable_dev_on_err = 1;
5145         int rc;
5146
5147         DPRINTK("ENTER\n");
5148
5149         port[0] = port_info[0];
5150         if (n_ports > 1)
5151                 port[1] = port_info[1];
5152         else
5153                 port[1] = port[0];
5154
5155         if ((port[0]->host_flags & ATA_FLAG_NO_LEGACY) == 0
5156             && (pdev->class >> 8) == PCI_CLASS_STORAGE_IDE) {
5157                 /* TODO: What if one channel is in native mode ... */
5158                 pci_read_config_byte(pdev, PCI_CLASS_PROG, &tmp8);
5159                 mask = (1 << 2) | (1 << 0);
5160                 if ((tmp8 & mask) != mask)
5161                         legacy_mode = (1 << 3);
5162         }
5163
5164         /* FIXME... */
5165         if ((!legacy_mode) && (n_ports > 2)) {
5166                 printk(KERN_ERR "ata: BUG: native mode, n_ports > 2\n");
5167                 n_ports = 2;
5168                 /* For now */
5169         }
5170
5171         /* FIXME: Really for ATA it isn't safe because the device may be
5172            multi-purpose and we want to leave it alone if it was already
5173            enabled. Secondly for shared use as Arjan says we want refcounting
5174            
5175            Checking dev->is_enabled is insufficient as this is not set at
5176            boot for the primary video which is BIOS enabled
5177          */
5178          
5179         rc = pci_enable_device(pdev);
5180         if (rc)
5181                 return rc;
5182
5183         rc = pci_request_regions(pdev, DRV_NAME);
5184         if (rc) {
5185                 disable_dev_on_err = 0;
5186                 goto err_out;
5187         }
5188
5189         /* FIXME: Should use platform specific mappers for legacy port ranges */
5190         if (legacy_mode) {
5191                 if (!request_region(0x1f0, 8, "libata")) {
5192                         struct resource *conflict, res;
5193                         res.start = 0x1f0;
5194                         res.end = 0x1f0 + 8 - 1;
5195                         conflict = ____request_resource(&ioport_resource, &res);
5196                         if (!strcmp(conflict->name, "libata"))
5197                                 legacy_mode |= (1 << 0);
5198                         else {
5199                                 disable_dev_on_err = 0;
5200                                 printk(KERN_WARNING "ata: 0x1f0 IDE port busy\n");
5201                         }
5202                 } else
5203                         legacy_mode |= (1 << 0);
5204
5205                 if (!request_region(0x170, 8, "libata")) {
5206                         struct resource *conflict, res;
5207                         res.start = 0x170;
5208                         res.end = 0x170 + 8 - 1;
5209                         conflict = ____request_resource(&ioport_resource, &res);
5210                         if (!strcmp(conflict->name, "libata"))
5211                                 legacy_mode |= (1 << 1);
5212                         else {
5213                                 disable_dev_on_err = 0;
5214                                 printk(KERN_WARNING "ata: 0x170 IDE port busy\n");
5215                         }
5216                 } else
5217                         legacy_mode |= (1 << 1);
5218         }
5219
5220         /* we have legacy mode, but all ports are unavailable */
5221         if (legacy_mode == (1 << 3)) {
5222                 rc = -EBUSY;
5223                 goto err_out_regions;
5224         }
5225
5226         rc = pci_set_dma_mask(pdev, ATA_DMA_MASK);
5227         if (rc)
5228                 goto err_out_regions;
5229         rc = pci_set_consistent_dma_mask(pdev, ATA_DMA_MASK);
5230         if (rc)
5231                 goto err_out_regions;
5232
5233         if (legacy_mode) {
5234                 if (legacy_mode & (1 << 0))
5235                         probe_ent = ata_pci_init_legacy_port(pdev, port[0], 0);
5236                 if (legacy_mode & (1 << 1))
5237                         probe_ent2 = ata_pci_init_legacy_port(pdev, port[1], 1);
5238         } else {
5239                 if (n_ports == 2)
5240                         probe_ent = ata_pci_init_native_mode(pdev, port, ATA_PORT_PRIMARY | ATA_PORT_SECONDARY);
5241                 else
5242                         probe_ent = ata_pci_init_native_mode(pdev, port, ATA_PORT_PRIMARY);
5243         }
5244         if (!probe_ent && !probe_ent2) {
5245                 rc = -ENOMEM;
5246                 goto err_out_regions;
5247         }
5248
5249         pci_set_master(pdev);
5250
5251         /* FIXME: check ata_device_add return */
5252         if (legacy_mode) {
5253                 if (legacy_mode & (1 << 0))
5254                         ata_device_add(probe_ent);
5255                 if (legacy_mode & (1 << 1))
5256                         ata_device_add(probe_ent2);
5257         } else
5258                 ata_device_add(probe_ent);
5259
5260         kfree(probe_ent);
5261         kfree(probe_ent2);
5262
5263         return 0;
5264
5265 err_out_regions:
5266         if (legacy_mode & (1 << 0))
5267                 release_region(0x1f0, 8);
5268         if (legacy_mode & (1 << 1))
5269                 release_region(0x170, 8);
5270         pci_release_regions(pdev);
5271 err_out:
5272         if (disable_dev_on_err)
5273                 pci_disable_device(pdev);
5274         return rc;
5275 }
5276
5277 /**
5278  *      ata_pci_remove_one - PCI layer callback for device removal
5279  *      @pdev: PCI device that was removed
5280  *
5281  *      PCI layer indicates to libata via this hook that
5282  *      hot-unplug or module unload event has occurred.
5283  *      Handle this by unregistering all objects associated
5284  *      with this PCI device.  Free those objects.  Then finally
5285  *      release PCI resources and disable device.
5286  *
5287  *      LOCKING:
5288  *      Inherited from PCI layer (may sleep).
5289  */
5290
5291 void ata_pci_remove_one (struct pci_dev *pdev)
5292 {
5293         struct device *dev = pci_dev_to_dev(pdev);
5294         struct ata_host_set *host_set = dev_get_drvdata(dev);
5295
5296         ata_host_set_remove(host_set);
5297         pci_release_regions(pdev);
5298         pci_disable_device(pdev);
5299         dev_set_drvdata(dev, NULL);
5300 }
5301
5302 /* move to PCI subsystem */
5303 int pci_test_config_bits(struct pci_dev *pdev, const struct pci_bits *bits)
5304 {
5305         unsigned long tmp = 0;
5306
5307         switch (bits->width) {
5308         case 1: {
5309                 u8 tmp8 = 0;
5310                 pci_read_config_byte(pdev, bits->reg, &tmp8);
5311                 tmp = tmp8;
5312                 break;
5313         }
5314         case 2: {
5315                 u16 tmp16 = 0;
5316                 pci_read_config_word(pdev, bits->reg, &tmp16);
5317                 tmp = tmp16;
5318                 break;
5319         }
5320         case 4: {
5321                 u32 tmp32 = 0;
5322                 pci_read_config_dword(pdev, bits->reg, &tmp32);
5323                 tmp = tmp32;
5324                 break;
5325         }
5326
5327         default:
5328                 return -EINVAL;
5329         }
5330
5331         tmp &= bits->mask;
5332
5333         return (tmp == bits->val) ? 1 : 0;
5334 }
5335
5336 int ata_pci_device_suspend(struct pci_dev *pdev, pm_message_t state)
5337 {
5338         pci_save_state(pdev);
5339         pci_disable_device(pdev);
5340         pci_set_power_state(pdev, PCI_D3hot);
5341         return 0;
5342 }
5343
5344 int ata_pci_device_resume(struct pci_dev *pdev)
5345 {
5346         pci_set_power_state(pdev, PCI_D0);
5347         pci_restore_state(pdev);
5348         pci_enable_device(pdev);
5349         pci_set_master(pdev);
5350         return 0;
5351 }
5352 #endif /* CONFIG_PCI */
5353
5354
5355 static int __init ata_init(void)
5356 {
5357         ata_wq = create_workqueue("ata");
5358         if (!ata_wq)
5359                 return -ENOMEM;
5360
5361         printk(KERN_DEBUG "libata version " DRV_VERSION " loaded.\n");
5362         return 0;
5363 }
5364
5365 static void __exit ata_exit(void)
5366 {
5367         destroy_workqueue(ata_wq);
5368 }
5369
5370 module_init(ata_init);
5371 module_exit(ata_exit);
5372
5373 static unsigned long ratelimit_time;
5374 static spinlock_t ata_ratelimit_lock = SPIN_LOCK_UNLOCKED;
5375
5376 int ata_ratelimit(void)
5377 {
5378         int rc;
5379         unsigned long flags;
5380
5381         spin_lock_irqsave(&ata_ratelimit_lock, flags);
5382
5383         if (time_after(jiffies, ratelimit_time)) {
5384                 rc = 1;
5385                 ratelimit_time = jiffies + (HZ/5);
5386         } else
5387                 rc = 0;
5388
5389         spin_unlock_irqrestore(&ata_ratelimit_lock, flags);
5390
5391         return rc;
5392 }
5393
5394 /*
5395  * libata is essentially a library of internal helper functions for
5396  * low-level ATA host controller drivers.  As such, the API/ABI is
5397  * likely to change as new drivers are added and updated.
5398  * Do not depend on ABI/API stability.
5399  */
5400
5401 EXPORT_SYMBOL_GPL(ata_std_bios_param);
5402 EXPORT_SYMBOL_GPL(ata_std_ports);
5403 EXPORT_SYMBOL_GPL(ata_device_add);
5404 EXPORT_SYMBOL_GPL(ata_host_set_remove);
5405 EXPORT_SYMBOL_GPL(ata_sg_init);
5406 EXPORT_SYMBOL_GPL(ata_sg_init_one);
5407 EXPORT_SYMBOL_GPL(ata_qc_complete);
5408 EXPORT_SYMBOL_GPL(ata_qc_issue_prot);
5409 EXPORT_SYMBOL_GPL(ata_eng_timeout);
5410 EXPORT_SYMBOL_GPL(ata_tf_load);
5411 EXPORT_SYMBOL_GPL(ata_tf_read);
5412 EXPORT_SYMBOL_GPL(ata_noop_dev_select);
5413 EXPORT_SYMBOL_GPL(ata_std_dev_select);
5414 EXPORT_SYMBOL_GPL(ata_tf_to_fis);
5415 EXPORT_SYMBOL_GPL(ata_tf_from_fis);
5416 EXPORT_SYMBOL_GPL(ata_check_status);
5417 EXPORT_SYMBOL_GPL(ata_altstatus);
5418 EXPORT_SYMBOL_GPL(ata_exec_command);
5419 EXPORT_SYMBOL_GPL(ata_port_start);
5420 EXPORT_SYMBOL_GPL(ata_port_stop);
5421 EXPORT_SYMBOL_GPL(ata_host_stop);
5422 EXPORT_SYMBOL_GPL(ata_interrupt);
5423 EXPORT_SYMBOL_GPL(ata_qc_prep);
5424 EXPORT_SYMBOL_GPL(ata_bmdma_setup);
5425 EXPORT_SYMBOL_GPL(ata_bmdma_start);
5426 EXPORT_SYMBOL_GPL(ata_bmdma_irq_clear);
5427 EXPORT_SYMBOL_GPL(ata_bmdma_status);
5428 EXPORT_SYMBOL_GPL(ata_bmdma_stop);
5429 EXPORT_SYMBOL_GPL(ata_port_probe);
5430 EXPORT_SYMBOL_GPL(sata_phy_reset);
5431 EXPORT_SYMBOL_GPL(__sata_phy_reset);
5432 EXPORT_SYMBOL_GPL(ata_bus_reset);
5433 EXPORT_SYMBOL_GPL(ata_port_disable);
5434 EXPORT_SYMBOL_GPL(ata_ratelimit);
5435 EXPORT_SYMBOL_GPL(ata_scsi_ioctl);
5436 EXPORT_SYMBOL_GPL(ata_scsi_queuecmd);
5437 EXPORT_SYMBOL_GPL(ata_scsi_error);
5438 EXPORT_SYMBOL_GPL(ata_scsi_slave_config);
5439 EXPORT_SYMBOL_GPL(ata_scsi_release);
5440 EXPORT_SYMBOL_GPL(ata_host_intr);
5441 EXPORT_SYMBOL_GPL(ata_dev_classify);
5442 EXPORT_SYMBOL_GPL(ata_dev_id_string);
5443 EXPORT_SYMBOL_GPL(ata_dev_config);
5444 EXPORT_SYMBOL_GPL(ata_scsi_simulate);
5445
5446 EXPORT_SYMBOL_GPL(ata_pio_need_iordy);
5447 EXPORT_SYMBOL_GPL(ata_timing_compute);
5448 EXPORT_SYMBOL_GPL(ata_timing_merge);
5449
5450 #ifdef CONFIG_PCI
5451 EXPORT_SYMBOL_GPL(pci_test_config_bits);
5452 EXPORT_SYMBOL_GPL(ata_pci_host_stop);
5453 EXPORT_SYMBOL_GPL(ata_pci_init_native_mode);
5454 EXPORT_SYMBOL_GPL(ata_pci_init_one);
5455 EXPORT_SYMBOL_GPL(ata_pci_remove_one);
5456 EXPORT_SYMBOL_GPL(ata_pci_device_suspend);
5457 EXPORT_SYMBOL_GPL(ata_pci_device_resume);
5458 #endif /* CONFIG_PCI */
5459
5460 EXPORT_SYMBOL_GPL(ata_device_suspend);
5461 EXPORT_SYMBOL_GPL(ata_device_resume);
5462 EXPORT_SYMBOL_GPL(ata_scsi_device_suspend);
5463 EXPORT_SYMBOL_GPL(ata_scsi_device_resume);