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