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