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