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