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