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