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