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