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