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