upgrade to linux 2.6.10-1.12_FC2
[linux-2.6.git] / drivers / ide / ide-io.c
1 /*
2  *      IDE I/O functions
3  *
4  *      Basic PIO and command management functionality.
5  *
6  * This code was split off from ide.c. See ide.c for history and original
7  * copyrights.
8  *
9  * This program is free software; you can redistribute it and/or modify it
10  * under the terms of the GNU General Public License as published by the
11  * Free Software Foundation; either version 2, or (at your option) any
12  * later version.
13  *
14  * This program is distributed in the hope that it will be useful, but
15  * WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * General Public License for more details.
18  *
19  * For the avoidance of doubt the "preferred form" of this code is one which
20  * is in an open non patent encumbered format. Where cryptographic key signing
21  * forms part of the process of creating an executable the information
22  * including keys needed to generate an equivalently functional executable
23  * are deemed to be part of the source code.
24  */
25  
26  
27 #include <linux/config.h>
28 #include <linux/module.h>
29 #include <linux/types.h>
30 #include <linux/string.h>
31 #include <linux/kernel.h>
32 #include <linux/timer.h>
33 #include <linux/mm.h>
34 #include <linux/interrupt.h>
35 #include <linux/major.h>
36 #include <linux/errno.h>
37 #include <linux/genhd.h>
38 #include <linux/blkpg.h>
39 #include <linux/slab.h>
40 #include <linux/init.h>
41 #include <linux/pci.h>
42 #include <linux/delay.h>
43 #include <linux/ide.h>
44 #include <linux/completion.h>
45 #include <linux/reboot.h>
46 #include <linux/cdrom.h>
47 #include <linux/seq_file.h>
48 #include <linux/device.h>
49 #include <linux/kmod.h>
50 #include <linux/scatterlist.h>
51
52 #include <asm/byteorder.h>
53 #include <asm/irq.h>
54 #include <asm/uaccess.h>
55 #include <asm/io.h>
56 #include <asm/bitops.h>
57
58 static void ide_fill_flush_cmd(ide_drive_t *drive, struct request *rq)
59 {
60         char *buf = rq->cmd;
61
62         /*
63          * reuse cdb space for ata command
64          */
65         memset(buf, 0, sizeof(rq->cmd));
66
67         rq->flags |= REQ_DRIVE_TASK | REQ_STARTED;
68         rq->buffer = buf;
69         rq->buffer[0] = WIN_FLUSH_CACHE;
70
71         if (ide_id_has_flush_cache_ext(drive->id) &&
72             (drive->capacity64 >= (1UL << 28)))
73                 rq->buffer[0] = WIN_FLUSH_CACHE_EXT;
74 }
75
76 /*
77  * preempt pending requests, and store this cache flush for immediate
78  * execution
79  */
80 static struct request *ide_queue_flush_cmd(ide_drive_t *drive,
81                                            struct request *rq, int post)
82 {
83         struct request *flush_rq = &HWGROUP(drive)->wrq;
84
85         /*
86          * write cache disabled, clear the barrier bit and treat it like
87          * an ordinary write
88          */
89         if (!drive->wcache) {
90                 rq->flags |= REQ_BAR_PREFLUSH;
91                 return rq;
92         }
93
94         ide_init_drive_cmd(flush_rq);
95         ide_fill_flush_cmd(drive, flush_rq);
96
97         flush_rq->special = rq;
98         flush_rq->nr_sectors = rq->nr_sectors;
99
100         if (!post) {
101                 drive->doing_barrier = 1;
102                 flush_rq->flags |= REQ_BAR_PREFLUSH;
103                 blkdev_dequeue_request(rq);
104         } else
105                 flush_rq->flags |= REQ_BAR_POSTFLUSH;
106
107         __elv_add_request(drive->queue, flush_rq, ELEVATOR_INSERT_FRONT, 0);
108         HWGROUP(drive)->rq = NULL;
109         return flush_rq;
110 }
111
112 static int __ide_end_request(ide_drive_t *drive, struct request *rq,
113                              int uptodate, int nr_sectors)
114 {
115         int ret = 1;
116
117         BUG_ON(!(rq->flags & REQ_STARTED));
118
119         /*
120          * if failfast is set on a request, override number of sectors and
121          * complete the whole request right now
122          */
123         if (blk_noretry_request(rq) && end_io_error(uptodate))
124                 nr_sectors = rq->hard_nr_sectors;
125
126         if (!blk_fs_request(rq) && end_io_error(uptodate) && !rq->errors)
127                 rq->errors = -EIO;
128
129         /*
130          * decide whether to reenable DMA -- 3 is a random magic for now,
131          * if we DMA timeout more than 3 times, just stay in PIO
132          */
133         if (drive->state == DMA_PIO_RETRY && drive->retry_pio <= 3) {
134                 drive->state = 0;
135                 HWGROUP(drive)->hwif->ide_dma_on(drive);
136         }
137
138         if (!end_that_request_first(rq, uptodate, nr_sectors)) {
139                 add_disk_randomness(rq->rq_disk);
140
141                 if (blk_rq_tagged(rq))
142                         blk_queue_end_tag(drive->queue, rq);
143
144                 blkdev_dequeue_request(rq);
145                 HWGROUP(drive)->rq = NULL;
146                 end_that_request_last(rq);
147                 ret = 0;
148         }
149         return ret;
150 }
151
152 /**
153  *      ide_end_request         -       complete an IDE I/O
154  *      @drive: IDE device for the I/O
155  *      @uptodate:
156  *      @nr_sectors: number of sectors completed
157  *
158  *      This is our end_request wrapper function. We complete the I/O
159  *      update random number input and dequeue the request, which if
160  *      it was tagged may be out of order.
161  */
162
163 int ide_end_request (ide_drive_t *drive, int uptodate, int nr_sectors)
164 {
165         struct request *rq;
166         unsigned long flags;
167         int ret = 1;
168
169         spin_lock_irqsave(&ide_lock, flags);
170         rq = HWGROUP(drive)->rq;
171
172         if (!nr_sectors)
173                 nr_sectors = rq->hard_cur_sectors;
174
175         if (!blk_barrier_rq(rq) || !drive->wcache)
176                 ret = __ide_end_request(drive, rq, uptodate, nr_sectors);
177         else {
178                 struct request *flush_rq = &HWGROUP(drive)->wrq;
179
180                 flush_rq->nr_sectors -= nr_sectors;
181                 if (!flush_rq->nr_sectors) {
182                         ide_queue_flush_cmd(drive, rq, 1);
183                         ret = 0;
184                 }
185         }
186
187         spin_unlock_irqrestore(&ide_lock, flags);
188         return ret;
189 }
190 EXPORT_SYMBOL(ide_end_request);
191
192 /**
193  *      ide_end_dequeued_request        -       complete an IDE I/O
194  *      @drive: IDE device for the I/O
195  *      @uptodate:
196  *      @nr_sectors: number of sectors completed
197  *
198  *      Complete an I/O that is no longer on the request queue. This 
199  *      typically occurs when we pull the request and issue a REQUEST_SENSE.
200  *      We must still finish the old request but we must not tamper with the
201  *      queue in the meantime.
202  *
203  *      NOTE: This path does not handle barrier, but barrier is not supported
204  *      on ide-cd anyway.
205  */
206
207 int ide_end_dequeued_request(ide_drive_t *drive, struct request *rq,
208                              int uptodate, int nr_sectors)
209 {
210         unsigned long flags;
211         int ret = 1;
212
213         spin_lock_irqsave(&ide_lock, flags);
214
215         BUG_ON(!(rq->flags & REQ_STARTED));
216
217         /*
218          * if failfast is set on a request, override number of sectors and
219          * complete the whole request right now
220          */
221         if (blk_noretry_request(rq) && end_io_error(uptodate))
222                 nr_sectors = rq->hard_nr_sectors;
223
224         if (!blk_fs_request(rq) && end_io_error(uptodate) && !rq->errors)
225                 rq->errors = -EIO;
226
227         /*
228          * decide whether to reenable DMA -- 3 is a random magic for now,
229          * if we DMA timeout more than 3 times, just stay in PIO
230          */
231         if (drive->state == DMA_PIO_RETRY && drive->retry_pio <= 3) {
232                 drive->state = 0;
233                 HWGROUP(drive)->hwif->ide_dma_on(drive);
234         }
235
236         if (!end_that_request_first(rq, uptodate, nr_sectors)) {
237                 add_disk_randomness(rq->rq_disk);
238                 if (blk_rq_tagged(rq))
239                         blk_queue_end_tag(drive->queue, rq);
240                 end_that_request_last(rq);
241                 ret = 0;
242         }
243         spin_unlock_irqrestore(&ide_lock, flags);
244         return ret;
245 }
246 EXPORT_SYMBOL_GPL(ide_end_dequeued_request);
247
248 /**
249  *      ide_complete_pm_request - end the current Power Management request
250  *      @drive: target drive
251  *      @rq: request
252  *
253  *      This function cleans up the current PM request and stops the queue
254  *      if necessary.
255  */
256 static void ide_complete_pm_request (ide_drive_t *drive, struct request *rq)
257 {
258         unsigned long flags;
259
260 #ifdef DEBUG_PM
261         printk("%s: completing PM request, %s\n", drive->name,
262                blk_pm_suspend_request(rq) ? "suspend" : "resume");
263 #endif
264         spin_lock_irqsave(&ide_lock, flags);
265         if (blk_pm_suspend_request(rq)) {
266                 blk_stop_queue(drive->queue);
267         } else {
268                 drive->blocked = 0;
269                 blk_start_queue(drive->queue);
270         }
271         blkdev_dequeue_request(rq);
272         HWGROUP(drive)->rq = NULL;
273         end_that_request_last(rq);
274         spin_unlock_irqrestore(&ide_lock, flags);
275 }
276
277 /*
278  * FIXME: probably move this somewhere else, name is bad too :)
279  */
280 u64 ide_get_error_location(ide_drive_t *drive, char *args)
281 {
282         u32 high, low;
283         u8 hcyl, lcyl, sect;
284         u64 sector;
285
286         high = 0;
287         hcyl = args[5];
288         lcyl = args[4];
289         sect = args[3];
290
291         if (ide_id_has_flush_cache_ext(drive->id)) {
292                 low = (hcyl << 16) | (lcyl << 8) | sect;
293                 HWIF(drive)->OUTB(drive->ctl|0x80, IDE_CONTROL_REG);
294                 high = ide_read_24(drive);
295         } else {
296                 u8 cur = HWIF(drive)->INB(IDE_SELECT_REG);
297                 if (cur & 0x40)
298                         low = (hcyl << 16) | (lcyl << 8) | sect;
299                 else {
300                         low = hcyl * drive->head * drive->sect;
301                         low += lcyl * drive->sect;
302                         low += sect - 1;
303                 }
304         }
305
306         sector = ((u64) high << 24) | low;
307         return sector;
308 }
309 EXPORT_SYMBOL(ide_get_error_location);
310
311 static void ide_complete_barrier(ide_drive_t *drive, struct request *rq,
312                                  int error)
313 {
314         struct request *real_rq = rq->special;
315         int good_sectors, bad_sectors;
316         sector_t sector;
317
318         if (!error) {
319                 if (blk_barrier_postflush(rq)) {
320                         /*
321                          * this completes the barrier write
322                          */
323                         __ide_end_request(drive, real_rq, 1, real_rq->hard_nr_sectors);
324                         drive->doing_barrier = 0;
325                 } else {
326                         /*
327                          * just indicate that we did the pre flush
328                          */
329                         real_rq->flags |= REQ_BAR_PREFLUSH;
330                         elv_requeue_request(drive->queue, real_rq);
331                 }
332                 /*
333                  * all is fine, return
334                  */
335                 return;
336         }
337
338         /*
339          * we need to end real_rq, but it's not on the queue currently.
340          * put it back on the queue, so we don't have to special case
341          * anything else for completing it
342          */
343         if (!blk_barrier_postflush(rq))
344                 elv_requeue_request(drive->queue, real_rq);
345
346         /*
347          * drive aborted flush command, assume FLUSH_CACHE_* doesn't
348          * work and disable barrier support
349          */
350         if (error & ABRT_ERR) {
351                 printk(KERN_ERR "%s: barrier support doesn't work\n", drive->name);
352                 __ide_end_request(drive, real_rq, -EOPNOTSUPP, real_rq->hard_nr_sectors);
353                 blk_queue_ordered(drive->queue, 0);
354                 blk_queue_issue_flush_fn(drive->queue, NULL);
355         } else {
356                 /*
357                  * find out what part of the request failed
358                  */
359                 good_sectors = 0;
360                 if (blk_barrier_postflush(rq)) {
361                         sector = ide_get_error_location(drive, rq->buffer);
362
363                         if ((sector >= real_rq->hard_sector) &&
364                             (sector < real_rq->hard_sector + real_rq->hard_nr_sectors))
365                                 good_sectors = sector - real_rq->hard_sector;
366                 } else
367                         sector = real_rq->hard_sector;
368
369                 bad_sectors = real_rq->hard_nr_sectors - good_sectors;
370                 if (good_sectors)
371                         __ide_end_request(drive, real_rq, 1, good_sectors);
372                 if (bad_sectors)
373                         __ide_end_request(drive, real_rq, 0, bad_sectors);
374
375                 printk(KERN_ERR "%s: failed barrier write: "
376                                 "sector=%Lx(good=%d/bad=%d)\n",
377                                 drive->name, (unsigned long long)sector,
378                                 good_sectors, bad_sectors);
379         }
380
381         drive->doing_barrier = 0;
382 }
383
384 /**
385  *      ide_end_drive_cmd       -       end an explicit drive command
386  *      @drive: command 
387  *      @stat: status bits
388  *      @err: error bits
389  *
390  *      Clean up after success/failure of an explicit drive command.
391  *      These get thrown onto the queue so they are synchronized with
392  *      real I/O operations on the drive.
393  *
394  *      In LBA48 mode we have to read the register set twice to get
395  *      all the extra information out.
396  */
397  
398 void ide_end_drive_cmd (ide_drive_t *drive, u8 stat, u8 err)
399 {
400         ide_hwif_t *hwif = HWIF(drive);
401         unsigned long flags;
402         struct request *rq;
403
404         spin_lock_irqsave(&ide_lock, flags);
405         rq = HWGROUP(drive)->rq;
406         spin_unlock_irqrestore(&ide_lock, flags);
407
408         if (rq->flags & REQ_DRIVE_CMD) {
409                 u8 *args = (u8 *) rq->buffer;
410                 if (rq->errors == 0)
411                         rq->errors = !OK_STAT(stat,READY_STAT,BAD_STAT);
412
413                 if (args) {
414                         args[0] = stat;
415                         args[1] = err;
416                         args[2] = hwif->INB(IDE_NSECTOR_REG);
417                 }
418         } else if (rq->flags & REQ_DRIVE_TASK) {
419                 u8 *args = (u8 *) rq->buffer;
420                 if (rq->errors == 0)
421                         rq->errors = !OK_STAT(stat,READY_STAT,BAD_STAT);
422
423                 if (args) {
424                         args[0] = stat;
425                         args[1] = err;
426                         args[2] = hwif->INB(IDE_NSECTOR_REG);
427                         args[3] = hwif->INB(IDE_SECTOR_REG);
428                         args[4] = hwif->INB(IDE_LCYL_REG);
429                         args[5] = hwif->INB(IDE_HCYL_REG);
430                         args[6] = hwif->INB(IDE_SELECT_REG);
431                 }
432         } else if (rq->flags & REQ_DRIVE_TASKFILE) {
433                 ide_task_t *args = (ide_task_t *) rq->special;
434                 if (rq->errors == 0)
435                         rq->errors = !OK_STAT(stat,READY_STAT,BAD_STAT);
436                         
437                 if (args) {
438                         if (args->tf_in_flags.b.data) {
439                                 u16 data                                = hwif->INW(IDE_DATA_REG);
440                                 args->tfRegister[IDE_DATA_OFFSET]       = (data) & 0xFF;
441                                 args->hobRegister[IDE_DATA_OFFSET]      = (data >> 8) & 0xFF;
442                         }
443                         args->tfRegister[IDE_ERROR_OFFSET]   = err;
444                         /* be sure we're looking at the low order bits */
445                         hwif->OUTB(drive->ctl & ~0x80, IDE_CONTROL_REG);
446                         args->tfRegister[IDE_NSECTOR_OFFSET] = hwif->INB(IDE_NSECTOR_REG);
447                         args->tfRegister[IDE_SECTOR_OFFSET]  = hwif->INB(IDE_SECTOR_REG);
448                         args->tfRegister[IDE_LCYL_OFFSET]    = hwif->INB(IDE_LCYL_REG);
449                         args->tfRegister[IDE_HCYL_OFFSET]    = hwif->INB(IDE_HCYL_REG);
450                         args->tfRegister[IDE_SELECT_OFFSET]  = hwif->INB(IDE_SELECT_REG);
451                         args->tfRegister[IDE_STATUS_OFFSET]  = stat;
452
453                         if (drive->addressing == 1) {
454                                 hwif->OUTB(drive->ctl|0x80, IDE_CONTROL_REG);
455                                 args->hobRegister[IDE_FEATURE_OFFSET]   = hwif->INB(IDE_FEATURE_REG);
456                                 args->hobRegister[IDE_NSECTOR_OFFSET]   = hwif->INB(IDE_NSECTOR_REG);
457                                 args->hobRegister[IDE_SECTOR_OFFSET]    = hwif->INB(IDE_SECTOR_REG);
458                                 args->hobRegister[IDE_LCYL_OFFSET]      = hwif->INB(IDE_LCYL_REG);
459                                 args->hobRegister[IDE_HCYL_OFFSET]      = hwif->INB(IDE_HCYL_REG);
460                         }
461                 }
462         } else if (blk_pm_request(rq)) {
463 #ifdef DEBUG_PM
464                 printk("%s: complete_power_step(step: %d, stat: %x, err: %x)\n",
465                         drive->name, rq->pm->pm_step, stat, err);
466 #endif
467                 DRIVER(drive)->complete_power_step(drive, rq, stat, err);
468                 if (rq->pm->pm_step == ide_pm_state_completed)
469                         ide_complete_pm_request(drive, rq);
470                 return;
471         }
472
473         spin_lock_irqsave(&ide_lock, flags);
474         blkdev_dequeue_request(rq);
475
476         if (blk_barrier_preflush(rq) || blk_barrier_postflush(rq))
477                 ide_complete_barrier(drive, rq, err);
478
479         HWGROUP(drive)->rq = NULL;
480         end_that_request_last(rq);
481         spin_unlock_irqrestore(&ide_lock, flags);
482 }
483
484 EXPORT_SYMBOL(ide_end_drive_cmd);
485
486 /**
487  *      try_to_flush_leftover_data      -       flush junk
488  *      @drive: drive to flush
489  *
490  *      try_to_flush_leftover_data() is invoked in response to a drive
491  *      unexpectedly having its DRQ_STAT bit set.  As an alternative to
492  *      resetting the drive, this routine tries to clear the condition
493  *      by read a sector's worth of data from the drive.  Of course,
494  *      this may not help if the drive is *waiting* for data from *us*.
495  */
496 void try_to_flush_leftover_data (ide_drive_t *drive)
497 {
498         int i = (drive->mult_count ? drive->mult_count : 1) * SECTOR_WORDS;
499
500         if (drive->media != ide_disk)
501                 return;
502         while (i > 0) {
503                 u32 buffer[16];
504                 u32 wcount = (i > 16) ? 16 : i;
505
506                 i -= wcount;
507                 HWIF(drive)->ata_input_data(drive, buffer, wcount);
508         }
509 }
510
511 EXPORT_SYMBOL(try_to_flush_leftover_data);
512
513 /*
514  * FIXME Add an ATAPI error
515  */
516
517 /**
518  *      ide_error       -       handle an error on the IDE
519  *      @drive: drive the error occurred on
520  *      @msg: message to report
521  *      @stat: status bits
522  *
523  *      ide_error() takes action based on the error returned by the drive.
524  *      For normal I/O that may well include retries. We deal with
525  *      both new-style (taskfile) and old style command handling here.
526  *      In the case of taskfile command handling there is work left to
527  *      do
528  */
529  
530 ide_startstop_t ide_error (ide_drive_t *drive, const char *msg, u8 stat)
531 {
532         ide_hwif_t *hwif;
533         struct request *rq;
534         u8 err;
535
536         err = ide_dump_status(drive, msg, stat);
537         if (drive == NULL || (rq = HWGROUP(drive)->rq) == NULL)
538                 return ide_stopped;
539
540         hwif = HWIF(drive);
541         /* retry only "normal" I/O: */
542         if (rq->flags & (REQ_DRIVE_CMD | REQ_DRIVE_TASK)) {
543                 rq->errors = 1;
544                 ide_end_drive_cmd(drive, stat, err);
545                 return ide_stopped;
546         }
547         if (rq->flags & REQ_DRIVE_TASKFILE) {
548                 rq->errors = 1;
549                 ide_end_drive_cmd(drive, stat, err);
550                 return ide_stopped;
551         }
552
553         if (stat & BUSY_STAT || ((stat & WRERR_STAT) && !drive->nowerr)) {
554                  /* other bits are useless when BUSY */
555                 rq->errors |= ERROR_RESET;
556         } else {
557                 if (drive->media != ide_disk)
558                         goto media_out;
559
560                 if (stat & ERR_STAT) {
561                         /* err has different meaning on cdrom and tape */
562                         if (err == ABRT_ERR) {
563                                 if (drive->select.b.lba &&
564                                     (hwif->INB(IDE_COMMAND_REG) == WIN_SPECIFY))
565                                         /* some newer drives don't
566                                          * support WIN_SPECIFY
567                                          */
568                                         return ide_stopped;
569                         } else if ((err & BAD_CRC) == BAD_CRC) {
570                                 drive->crc_count++;
571                                 /* UDMA crc error -- just retry the operation */
572                         } else if (err & (BBD_ERR | ECC_ERR)) {
573                                 /* retries won't help these */
574                                 rq->errors = ERROR_MAX;
575                         } else if (err & TRK0_ERR) {
576                                 /* help it find track zero */
577                                 rq->errors |= ERROR_RECAL;
578                         }
579                 }
580 media_out:
581                 if ((stat & DRQ_STAT) && rq_data_dir(rq) != WRITE)
582                         try_to_flush_leftover_data(drive);
583         }
584         if (hwif->INB(IDE_STATUS_REG) & (BUSY_STAT|DRQ_STAT)) {
585                 /* force an abort */
586                 hwif->OUTB(WIN_IDLEIMMEDIATE,IDE_COMMAND_REG);
587         }
588         if (rq->errors >= ERROR_MAX) {
589                 DRIVER(drive)->end_request(drive, 0, 0);
590         } else {
591                 if ((rq->errors & ERROR_RESET) == ERROR_RESET) {
592                         ++rq->errors;
593                         return ide_do_reset(drive);
594                 }
595                 if ((rq->errors & ERROR_RECAL) == ERROR_RECAL)
596                         drive->special.b.recalibrate = 1;
597                 ++rq->errors;
598         }
599         return ide_stopped;
600 }
601
602 /**
603  *      ide_abort       -       abort pending IDE operatins
604  *      @drive: drive the error occurred on
605  *      @msg: message to report
606  *
607  *      ide_abort kills and cleans up when we are about to do a 
608  *      host initiated reset on active commands. Longer term we
609  *      want handlers to have sensible abort handling themselves
610  *
611  *      This differs fundamentally from ide_error because in 
612  *      this case the command is doing just fine when we
613  *      blow it away.
614  *
615  *      FIXME: need to fix locking corner cases
616  */
617  
618 ide_startstop_t ide_abort(ide_drive_t *drive, const char *msg)
619 {
620         ide_hwif_t *hwif;
621         struct request *rq;
622         unsigned long flags;
623
624         spin_lock_irqsave(&ide_lock, flags);
625         if (drive == NULL || (rq = HWGROUP(drive)->rq) == NULL) {
626                 spin_unlock_irqrestore(&ide_lock, flags);
627                 return ide_stopped;
628         }
629         hwif = HWIF(drive);
630         /* retry only "normal" I/O: */
631         if (rq->flags & (REQ_DRIVE_CMD | REQ_DRIVE_TASK)) {
632                 rq->errors = 1;
633                 spin_unlock_irqrestore(&ide_lock, flags);
634                 ide_end_drive_cmd(drive, BUSY_STAT, 0);
635                 return ide_stopped;
636         }
637         if (rq->flags & REQ_DRIVE_TASKFILE) {
638                 rq->errors = 1;
639                 spin_unlock_irqrestore(&ide_lock, flags);
640                 ide_end_drive_cmd(drive, BUSY_STAT, 0);
641                 return ide_stopped;
642         }
643
644         rq->errors |= ERROR_RESET;
645         spin_unlock_irqrestore(&ide_lock, flags);
646         DRIVER(drive)->end_request(drive, 0, 0);
647         return ide_stopped;
648 }
649
650 /**
651  *      ide_cmd         -       issue a simple drive command
652  *      @drive: drive the command is for
653  *      @cmd: command byte
654  *      @nsect: sector byte
655  *      @handler: handler for the command completion
656  *
657  *      Issue a simple drive command with interrupts.
658  *      The drive must be selected beforehand.
659  */
660
661 static void ide_cmd (ide_drive_t *drive, u8 cmd, u8 nsect,
662                 ide_handler_t *handler)
663 {
664         ide_hwif_t *hwif = HWIF(drive);
665         if (IDE_CONTROL_REG)
666                 hwif->OUTB(drive->ctl,IDE_CONTROL_REG); /* clear nIEN */
667         SELECT_MASK(drive,0);
668         hwif->OUTB(nsect,IDE_NSECTOR_REG);
669         ide_execute_command(drive, cmd, handler, WAIT_CMD, NULL);
670 }
671
672 /**
673  *      drive_cmd_intr          -       drive command completion interrupt
674  *      @drive: drive the completion interrupt occurred on
675  *
676  *      drive_cmd_intr() is invoked on completion of a special DRIVE_CMD.
677  *      We do any necessary daya reading and then wait for the drive to
678  *      go non busy. At that point we may read the error data and complete
679  *      the request
680  */
681  
682 static ide_startstop_t drive_cmd_intr (ide_drive_t *drive)
683 {
684         struct request *rq = HWGROUP(drive)->rq;
685         ide_hwif_t *hwif = HWIF(drive);
686         u8 *args = (u8 *) rq->buffer;
687         u8 stat = hwif->INB(IDE_STATUS_REG);
688         int retries = 10;
689
690         local_irq_enable();
691         if ((stat & DRQ_STAT) && args && args[3]) {
692                 u8 io_32bit = drive->io_32bit;
693                 drive->io_32bit = 0;
694                 hwif->ata_input_data(drive, &args[4], args[3] * SECTOR_WORDS);
695                 drive->io_32bit = io_32bit;
696                 while (((stat = hwif->INB(IDE_STATUS_REG)) & BUSY_STAT) && retries--)
697                         udelay(100);
698         }
699
700         if (!OK_STAT(stat, READY_STAT, BAD_STAT) && DRIVER(drive) != NULL)
701                 return DRIVER(drive)->error(drive, "drive_cmd", stat);
702                 /* calls ide_end_drive_cmd */
703         ide_end_drive_cmd(drive, stat, hwif->INB(IDE_ERROR_REG));
704         return ide_stopped;
705 }
706
707 /**
708  *      do_special              -       issue some special commands
709  *      @drive: drive the command is for
710  *
711  *      do_special() is used to issue WIN_SPECIFY, WIN_RESTORE, and WIN_SETMULT
712  *      commands to a drive.  It used to do much more, but has been scaled
713  *      back.
714  */
715
716 static ide_startstop_t do_special (ide_drive_t *drive)
717 {
718         special_t *s = &drive->special;
719
720 #ifdef DEBUG
721         printk("%s: do_special: 0x%02x\n", drive->name, s->all);
722 #endif
723         if (s->b.set_tune) {
724                 s->b.set_tune = 0;
725                 if (HWIF(drive)->tuneproc != NULL)
726                         HWIF(drive)->tuneproc(drive, drive->tune_req);
727                 return ide_stopped;
728         }
729         else
730                 return DRIVER(drive)->special(drive);
731 }
732
733 void ide_map_sg(ide_drive_t *drive, struct request *rq)
734 {
735         ide_hwif_t *hwif = drive->hwif;
736         struct scatterlist *sg = hwif->sg_table;
737
738         if (hwif->sg_mapped)    /* needed by ide-scsi */
739                 return;
740
741         if ((rq->flags & REQ_DRIVE_TASKFILE) == 0) {
742                 hwif->sg_nents = blk_rq_map_sg(drive->queue, rq, sg);
743         } else {
744                 sg_init_one(sg, rq->buffer, rq->nr_sectors * SECTOR_SIZE);
745                 hwif->sg_nents = 1;
746         }
747 }
748
749 EXPORT_SYMBOL_GPL(ide_map_sg);
750
751 void ide_init_sg_cmd(ide_drive_t *drive, struct request *rq)
752 {
753         ide_hwif_t *hwif = drive->hwif;
754
755         hwif->nsect = hwif->nleft = rq->nr_sectors;
756         hwif->cursg = hwif->cursg_ofs = 0;
757 }
758
759 EXPORT_SYMBOL_GPL(ide_init_sg_cmd);
760
761 /**
762  *      execute_drive_command   -       issue special drive command
763  *      @drive: the drive to issue th command on
764  *      @rq: the request structure holding the command
765  *
766  *      execute_drive_cmd() issues a special drive command,  usually 
767  *      initiated by ioctl() from the external hdparm program. The
768  *      command can be a drive command, drive task or taskfile 
769  *      operation. Weirdly you can call it with NULL to wait for
770  *      all commands to finish. Don't do this as that is due to change
771  */
772
773 static ide_startstop_t execute_drive_cmd (ide_drive_t *drive,
774                 struct request *rq)
775 {
776         ide_hwif_t *hwif = HWIF(drive);
777         if (rq->flags & REQ_DRIVE_TASKFILE) {
778                 ide_task_t *args = rq->special;
779  
780                 if (!args)
781                         goto done;
782
783                 hwif->data_phase = args->data_phase;
784
785                 switch (hwif->data_phase) {
786                 case TASKFILE_MULTI_OUT:
787                 case TASKFILE_OUT:
788                 case TASKFILE_MULTI_IN:
789                 case TASKFILE_IN:
790                         ide_init_sg_cmd(drive, rq);
791                         ide_map_sg(drive, rq);
792                 default:
793                         break;
794                 }
795
796                 if (args->tf_out_flags.all != 0) 
797                         return flagged_taskfile(drive, args);
798                 return do_rw_taskfile(drive, args);
799         } else if (rq->flags & REQ_DRIVE_TASK) {
800                 u8 *args = rq->buffer;
801                 u8 sel;
802  
803                 if (!args)
804                         goto done;
805 #ifdef DEBUG
806                 printk("%s: DRIVE_TASK_CMD ", drive->name);
807                 printk("cmd=0x%02x ", args[0]);
808                 printk("fr=0x%02x ", args[1]);
809                 printk("ns=0x%02x ", args[2]);
810                 printk("sc=0x%02x ", args[3]);
811                 printk("lcyl=0x%02x ", args[4]);
812                 printk("hcyl=0x%02x ", args[5]);
813                 printk("sel=0x%02x\n", args[6]);
814 #endif
815                 hwif->OUTB(args[1], IDE_FEATURE_REG);
816                 hwif->OUTB(args[3], IDE_SECTOR_REG);
817                 hwif->OUTB(args[4], IDE_LCYL_REG);
818                 hwif->OUTB(args[5], IDE_HCYL_REG);
819                 sel = (args[6] & ~0x10);
820                 if (drive->select.b.unit)
821                         sel |= 0x10;
822                 hwif->OUTB(sel, IDE_SELECT_REG);
823                 ide_cmd(drive, args[0], args[2], &drive_cmd_intr);
824                 return ide_started;
825         } else if (rq->flags & REQ_DRIVE_CMD) {
826                 u8 *args = rq->buffer;
827
828                 if (!args)
829                         goto done;
830 #ifdef DEBUG
831                 printk("%s: DRIVE_CMD ", drive->name);
832                 printk("cmd=0x%02x ", args[0]);
833                 printk("sc=0x%02x ", args[1]);
834                 printk("fr=0x%02x ", args[2]);
835                 printk("xx=0x%02x\n", args[3]);
836 #endif
837                 if (args[0] == WIN_SMART) {
838                         hwif->OUTB(0x4f, IDE_LCYL_REG);
839                         hwif->OUTB(0xc2, IDE_HCYL_REG);
840                         hwif->OUTB(args[2],IDE_FEATURE_REG);
841                         hwif->OUTB(args[1],IDE_SECTOR_REG);
842                         ide_cmd(drive, args[0], args[3], &drive_cmd_intr);
843                         return ide_started;
844                 }
845                 hwif->OUTB(args[2],IDE_FEATURE_REG);
846                 ide_cmd(drive, args[0], args[1], &drive_cmd_intr);
847                 return ide_started;
848         }
849
850 done:
851         /*
852          * NULL is actually a valid way of waiting for
853          * all current requests to be flushed from the queue.
854          */
855 #ifdef DEBUG
856         printk("%s: DRIVE_CMD (null)\n", drive->name);
857 #endif
858         ide_end_drive_cmd(drive,
859                         hwif->INB(IDE_STATUS_REG),
860                         hwif->INB(IDE_ERROR_REG));
861         return ide_stopped;
862 }
863
864 /**
865  *      start_request   -       start of I/O and command issuing for IDE
866  *
867  *      start_request() initiates handling of a new I/O request. It
868  *      accepts commands and I/O (read/write) requests. It also does
869  *      the final remapping for weird stuff like EZDrive. Once 
870  *      device mapper can work sector level the EZDrive stuff can go away
871  *
872  *      FIXME: this function needs a rename
873  */
874  
875 static ide_startstop_t start_request (ide_drive_t *drive, struct request *rq)
876 {
877         ide_startstop_t startstop;
878         sector_t block;
879
880         BUG_ON(!(rq->flags & REQ_STARTED));
881
882 #ifdef DEBUG
883         printk("%s: start_request: current=0x%08lx\n",
884                 HWIF(drive)->name, (unsigned long) rq);
885 #endif
886
887         /* bail early if we've exceeded max_failures */
888         if (drive->max_failures && (drive->failures > drive->max_failures)) {
889                 goto kill_rq;
890         }
891
892         /*
893          * bail early if we've sent a device to sleep, however how to wake
894          * this needs to be a masked flag.  FIXME for proper operations.
895          */
896         if (drive->suspend_reset)
897                 goto kill_rq;
898
899         block    = rq->sector;
900         if (blk_fs_request(rq) &&
901             (drive->media == ide_disk || drive->media == ide_floppy)) {
902                 block += drive->sect0;
903         }
904         /* Yecch - this will shift the entire interval,
905            possibly killing some innocent following sector */
906         if (block == 0 && drive->remap_0_to_1 == 1)
907                 block = 1;  /* redirect MBR access to EZ-Drive partn table */
908
909         if (blk_pm_suspend_request(rq) &&
910             rq->pm->pm_step == ide_pm_state_start_suspend)
911                 /* Mark drive blocked when starting the suspend sequence. */
912                 drive->blocked = 1;
913         else if (blk_pm_resume_request(rq) &&
914                  rq->pm->pm_step == ide_pm_state_start_resume) {
915                 /* 
916                  * The first thing we do on wakeup is to wait for BSY bit to
917                  * go away (with a looong timeout) as a drive on this hwif may
918                  * just be POSTing itself.
919                  * We do that before even selecting as the "other" device on
920                  * the bus may be broken enough to walk on our toes at this
921                  * point.
922                  */
923                 int rc;
924 #ifdef DEBUG_PM
925                 printk("%s: Wakeup request inited, waiting for !BSY...\n", drive->name);
926 #endif
927                 rc = ide_wait_not_busy(HWIF(drive), 35000);
928                 if (rc)
929                         printk(KERN_WARNING "%s: bus not ready on wakeup\n", drive->name);
930                 SELECT_DRIVE(drive);
931                 HWIF(drive)->OUTB(8, HWIF(drive)->io_ports[IDE_CONTROL_OFFSET]);
932                 rc = ide_wait_not_busy(HWIF(drive), 10000);
933                 if (rc)
934                         printk(KERN_WARNING "%s: drive not ready on wakeup\n", drive->name);
935         }
936
937         SELECT_DRIVE(drive);
938         if (ide_wait_stat(&startstop, drive, drive->ready_stat, BUSY_STAT|DRQ_STAT, WAIT_READY)) {
939                 printk(KERN_ERR "%s: drive not ready for command\n", drive->name);
940                 return startstop;
941         }
942         if (!drive->special.all) {
943                 if (rq->flags & (REQ_DRIVE_CMD | REQ_DRIVE_TASK))
944                         return execute_drive_cmd(drive, rq);
945                 else if (rq->flags & REQ_DRIVE_TASKFILE)
946                         return execute_drive_cmd(drive, rq);
947                 else if (blk_pm_request(rq)) {
948 #ifdef DEBUG_PM
949                         printk("%s: start_power_step(step: %d)\n",
950                                 drive->name, rq->pm->pm_step);
951 #endif
952                         startstop = DRIVER(drive)->start_power_step(drive, rq);
953                         if (startstop == ide_stopped &&
954                             rq->pm->pm_step == ide_pm_state_completed)
955                                 ide_complete_pm_request(drive, rq);
956                         return startstop;
957                 }
958                 return (DRIVER(drive)->do_request(drive, rq, block));
959         }
960         return do_special(drive);
961 kill_rq:
962         DRIVER(drive)->end_request(drive, 0, 0);
963         return ide_stopped;
964 }
965
966 /**
967  *      ide_stall_queue         -       pause an IDE device
968  *      @drive: drive to stall
969  *      @timeout: time to stall for (jiffies)
970  *
971  *      ide_stall_queue() can be used by a drive to give excess bandwidth back
972  *      to the hwgroup by sleeping for timeout jiffies.
973  */
974  
975 void ide_stall_queue (ide_drive_t *drive, unsigned long timeout)
976 {
977         if (timeout > WAIT_WORSTCASE)
978                 timeout = WAIT_WORSTCASE;
979         drive->sleep = timeout + jiffies;
980 }
981
982 EXPORT_SYMBOL(ide_stall_queue);
983
984 #define WAKEUP(drive)   ((drive)->service_start + 2 * (drive)->service_time)
985
986 /**
987  *      choose_drive            -       select a drive to service
988  *      @hwgroup: hardware group to select on
989  *
990  *      choose_drive() selects the next drive which will be serviced.
991  *      This is necessary because the IDE layer can't issue commands
992  *      to both drives on the same cable, unlike SCSI.
993  */
994  
995 static inline ide_drive_t *choose_drive (ide_hwgroup_t *hwgroup)
996 {
997         ide_drive_t *drive, *best;
998
999 repeat: 
1000         best = NULL;
1001         drive = hwgroup->drive;
1002
1003         /*
1004          * drive is doing pre-flush, ordered write, post-flush sequence. even
1005          * though that is 3 requests, it must be seen as a single transaction.
1006          * we must not preempt this drive until that is complete
1007          */
1008         if (drive->doing_barrier) {
1009                 /*
1010                  * small race where queue could get replugged during
1011                  * the 3-request flush cycle, just yank the plug since
1012                  * we want it to finish asap
1013                  */
1014                 blk_remove_plug(drive->queue);
1015                 return drive;
1016         }
1017
1018         do {
1019                 if ((!drive->sleep || time_after_eq(jiffies, drive->sleep))
1020                     && !elv_queue_empty(drive->queue)) {
1021                         if (!best
1022                          || (drive->sleep && (!best->sleep || 0 < (signed long)(best->sleep - drive->sleep)))
1023                          || (!best->sleep && 0 < (signed long)(WAKEUP(best) - WAKEUP(drive))))
1024                         {
1025                                 if (!blk_queue_plugged(drive->queue))
1026                                         best = drive;
1027                         }
1028                 }
1029         } while ((drive = drive->next) != hwgroup->drive);
1030         if (best && best->nice1 && !best->sleep && best != hwgroup->drive && best->service_time > WAIT_MIN_SLEEP) {
1031                 long t = (signed long)(WAKEUP(best) - jiffies);
1032                 if (t >= WAIT_MIN_SLEEP) {
1033                 /*
1034                  * We *may* have some time to spare, but first let's see if
1035                  * someone can potentially benefit from our nice mood today..
1036                  */
1037                         drive = best->next;
1038                         do {
1039                                 if (!drive->sleep
1040                                 /* FIXME: use time_before */
1041                                  && 0 < (signed long)(WAKEUP(drive) - (jiffies - best->service_time))
1042                                  && 0 < (signed long)((jiffies + t) - WAKEUP(drive)))
1043                                 {
1044                                         ide_stall_queue(best, min_t(long, t, 10 * WAIT_MIN_SLEEP));
1045                                         goto repeat;
1046                                 }
1047                         } while ((drive = drive->next) != best);
1048                 }
1049         }
1050         return best;
1051 }
1052
1053 /*
1054  * Issue a new request to a drive from hwgroup
1055  * Caller must have already done spin_lock_irqsave(&ide_lock, ..);
1056  *
1057  * A hwgroup is a serialized group of IDE interfaces.  Usually there is
1058  * exactly one hwif (interface) per hwgroup, but buggy controllers (eg. CMD640)
1059  * may have both interfaces in a single hwgroup to "serialize" access.
1060  * Or possibly multiple ISA interfaces can share a common IRQ by being grouped
1061  * together into one hwgroup for serialized access.
1062  *
1063  * Note also that several hwgroups can end up sharing a single IRQ,
1064  * possibly along with many other devices.  This is especially common in
1065  * PCI-based systems with off-board IDE controller cards.
1066  *
1067  * The IDE driver uses the single global ide_lock spinlock to protect
1068  * access to the request queues, and to protect the hwgroup->busy flag.
1069  *
1070  * The first thread into the driver for a particular hwgroup sets the
1071  * hwgroup->busy flag to indicate that this hwgroup is now active,
1072  * and then initiates processing of the top request from the request queue.
1073  *
1074  * Other threads attempting entry notice the busy setting, and will simply
1075  * queue their new requests and exit immediately.  Note that hwgroup->busy
1076  * remains set even when the driver is merely awaiting the next interrupt.
1077  * Thus, the meaning is "this hwgroup is busy processing a request".
1078  *
1079  * When processing of a request completes, the completing thread or IRQ-handler
1080  * will start the next request from the queue.  If no more work remains,
1081  * the driver will clear the hwgroup->busy flag and exit.
1082  *
1083  * The ide_lock (spinlock) is used to protect all access to the
1084  * hwgroup->busy flag, but is otherwise not needed for most processing in
1085  * the driver.  This makes the driver much more friendlier to shared IRQs
1086  * than previous designs, while remaining 100% (?) SMP safe and capable.
1087  */
1088 static void ide_do_request (ide_hwgroup_t *hwgroup, int masked_irq)
1089 {
1090         ide_drive_t     *drive;
1091         ide_hwif_t      *hwif;
1092         struct request  *rq;
1093         ide_startstop_t startstop;
1094
1095         /* for atari only: POSSIBLY BROKEN HERE(?) */
1096         ide_get_lock(ide_intr, hwgroup);
1097
1098         /* caller must own ide_lock */
1099         BUG_ON(!irqs_disabled());
1100
1101         while (!hwgroup->busy) {
1102                 hwgroup->busy = 1;
1103                 drive = choose_drive(hwgroup);
1104                 if (drive == NULL) {
1105                         unsigned long sleep = 0;
1106                         hwgroup->rq = NULL;
1107                         drive = hwgroup->drive;
1108                         do {
1109                                 if (drive->sleep && (!sleep || 0 < (signed long)(sleep - drive->sleep)))
1110                                         sleep = drive->sleep;
1111                         } while ((drive = drive->next) != hwgroup->drive);
1112                         if (sleep) {
1113                 /*
1114                  * Take a short snooze, and then wake up this hwgroup again.
1115                  * This gives other hwgroups on the same a chance to
1116                  * play fairly with us, just in case there are big differences
1117                  * in relative throughputs.. don't want to hog the cpu too much.
1118                  */
1119                                 if (time_before(sleep, jiffies + WAIT_MIN_SLEEP))
1120                                         sleep = jiffies + WAIT_MIN_SLEEP;
1121 #if 1
1122                                 if (timer_pending(&hwgroup->timer))
1123                                         printk(KERN_CRIT "ide_set_handler: timer already active\n");
1124 #endif
1125                                 /* so that ide_timer_expiry knows what to do */
1126                                 hwgroup->sleeping = 1;
1127                                 mod_timer(&hwgroup->timer, sleep);
1128                                 /* we purposely leave hwgroup->busy==1
1129                                  * while sleeping */
1130                         } else {
1131                                 /* Ugly, but how can we sleep for the lock
1132                                  * otherwise? perhaps from tq_disk?
1133                                  */
1134
1135                                 /* for atari only */
1136                                 ide_release_lock();
1137                                 hwgroup->busy = 0;
1138                         }
1139
1140                         /* no more work for this hwgroup (for now) */
1141                         return;
1142                 }
1143                 hwif = HWIF(drive);
1144                 if (hwgroup->hwif->sharing_irq &&
1145                     hwif != hwgroup->hwif &&
1146                     hwif->io_ports[IDE_CONTROL_OFFSET]) {
1147                         /* set nIEN for previous hwif */
1148                         SELECT_INTERRUPT(drive);
1149                 }
1150                 hwgroup->hwif = hwif;
1151                 hwgroup->drive = drive;
1152                 drive->sleep = 0;
1153                 drive->service_start = jiffies;
1154
1155                 if (blk_queue_plugged(drive->queue)) {
1156                         printk(KERN_ERR "ide: huh? queue was plugged!\n");
1157                         break;
1158                 }
1159
1160                 /*
1161                  * we know that the queue isn't empty, but this can happen
1162                  * if the q->prep_rq_fn() decides to kill a request
1163                  */
1164                 rq = elv_next_request(drive->queue);
1165                 if (!rq) {
1166                         hwgroup->busy = 0;
1167                         break;
1168                 }
1169
1170                 /*
1171                  * if rq is a barrier write, issue pre cache flush if not
1172                  * already done
1173                  */
1174                 if (blk_barrier_rq(rq) && !blk_barrier_preflush(rq))
1175                         rq = ide_queue_flush_cmd(drive, rq, 0);
1176
1177                 /*
1178                  * Sanity: don't accept a request that isn't a PM request
1179                  * if we are currently power managed. This is very important as
1180                  * blk_stop_queue() doesn't prevent the elv_next_request()
1181                  * above to return us whatever is in the queue. Since we call
1182                  * ide_do_request() ourselves, we end up taking requests while
1183                  * the queue is blocked...
1184                  * 
1185                  * We let requests forced at head of queue with ide-preempt
1186                  * though. I hope that doesn't happen too much, hopefully not
1187                  * unless the subdriver triggers such a thing in its own PM
1188                  * state machine.
1189                  */
1190                 if (drive->blocked && !blk_pm_request(rq) && !(rq->flags & REQ_PREEMPT)) {
1191                         /* We clear busy, there should be no pending ATA command at this point. */
1192                         hwgroup->busy = 0;
1193                         break;
1194                 }
1195
1196                 hwgroup->rq = rq;
1197
1198                 /*
1199                  * Some systems have trouble with IDE IRQs arriving while
1200                  * the driver is still setting things up.  So, here we disable
1201                  * the IRQ used by this interface while the request is being started.
1202                  * This may look bad at first, but pretty much the same thing
1203                  * happens anyway when any interrupt comes in, IDE or otherwise
1204                  *  -- the kernel masks the IRQ while it is being handled.
1205                  */
1206                 if (hwif->irq != masked_irq)
1207                         disable_irq_nosync(hwif->irq);
1208                 spin_unlock(&ide_lock);
1209                 local_irq_enable();
1210                         /* allow other IRQs while we start this request */
1211                 startstop = start_request(drive, rq);
1212                 spin_lock_irq(&ide_lock);
1213                 if (hwif->irq != masked_irq)
1214                         enable_irq(hwif->irq);
1215                 if (startstop == ide_stopped)
1216                         hwgroup->busy = 0;
1217         }
1218 }
1219
1220 /*
1221  * Passes the stuff to ide_do_request
1222  */
1223 void do_ide_request(request_queue_t *q)
1224 {
1225         ide_drive_t *drive = q->queuedata;
1226
1227         ide_do_request(HWGROUP(drive), IDE_NO_IRQ);
1228 }
1229
1230 /*
1231  * un-busy the hwgroup etc, and clear any pending DMA status. we want to
1232  * retry the current request in pio mode instead of risking tossing it
1233  * all away
1234  */
1235 static ide_startstop_t ide_dma_timeout_retry(ide_drive_t *drive, int error)
1236 {
1237         ide_hwif_t *hwif = HWIF(drive);
1238         struct request *rq;
1239         ide_startstop_t ret = ide_stopped;
1240
1241         /*
1242          * end current dma transaction
1243          */
1244
1245         if (error < 0) {
1246                 printk(KERN_WARNING "%s: DMA timeout error\n", drive->name);
1247                 (void)HWIF(drive)->ide_dma_end(drive);
1248                 ret = DRIVER(drive)->error(drive, "dma timeout error",
1249                                                 hwif->INB(IDE_STATUS_REG));
1250         } else {
1251                 printk(KERN_WARNING "%s: DMA timeout retry\n", drive->name);
1252                 (void) hwif->ide_dma_timeout(drive);
1253         }
1254
1255         /*
1256          * disable dma for now, but remember that we did so because of
1257          * a timeout -- we'll reenable after we finish this next request
1258          * (or rather the first chunk of it) in pio.
1259          */
1260         drive->retry_pio++;
1261         drive->state = DMA_PIO_RETRY;
1262         (void) hwif->ide_dma_off_quietly(drive);
1263
1264         /*
1265          * un-busy drive etc (hwgroup->busy is cleared on return) and
1266          * make sure request is sane
1267          */
1268         rq = HWGROUP(drive)->rq;
1269         HWGROUP(drive)->rq = NULL;
1270
1271         rq->errors = 0;
1272
1273         if (!rq->bio)
1274                 goto out;
1275
1276         rq->sector = rq->bio->bi_sector;
1277         rq->current_nr_sectors = bio_iovec(rq->bio)->bv_len >> 9;
1278         rq->hard_cur_sectors = rq->current_nr_sectors;
1279         rq->buffer = bio_data(rq->bio);
1280 out:
1281         return ret;
1282 }
1283
1284 /**
1285  *      ide_timer_expiry        -       handle lack of an IDE interrupt
1286  *      @data: timer callback magic (hwgroup)
1287  *
1288  *      An IDE command has timed out before the expected drive return
1289  *      occurred. At this point we attempt to clean up the current
1290  *      mess. If the current handler includes an expiry handler then
1291  *      we invoke the expiry handler, and providing it is happy the
1292  *      work is done. If that fails we apply generic recovery rules
1293  *      invoking the handler and checking the drive DMA status. We
1294  *      have an excessively incestuous relationship with the DMA
1295  *      logic that wants cleaning up.
1296  */
1297  
1298 void ide_timer_expiry (unsigned long data)
1299 {
1300         ide_hwgroup_t   *hwgroup = (ide_hwgroup_t *) data;
1301         ide_handler_t   *handler;
1302         ide_expiry_t    *expiry;
1303         unsigned long   flags;
1304         unsigned long   wait = -1;
1305
1306         spin_lock_irqsave(&ide_lock, flags);
1307
1308         if ((handler = hwgroup->handler) == NULL) {
1309                 /*
1310                  * Either a marginal timeout occurred
1311                  * (got the interrupt just as timer expired),
1312                  * or we were "sleeping" to give other devices a chance.
1313                  * Either way, we don't really want to complain about anything.
1314                  */
1315                 if (hwgroup->sleeping) {
1316                         hwgroup->sleeping = 0;
1317                         hwgroup->busy = 0;
1318                 }
1319         } else {
1320                 ide_drive_t *drive = hwgroup->drive;
1321                 if (!drive) {
1322                         printk(KERN_ERR "ide_timer_expiry: hwgroup->drive was NULL\n");
1323                         hwgroup->handler = NULL;
1324                 } else {
1325                         ide_hwif_t *hwif;
1326                         ide_startstop_t startstop = ide_stopped;
1327                         if (!hwgroup->busy) {
1328                                 hwgroup->busy = 1;      /* paranoia */
1329                                 printk(KERN_ERR "%s: ide_timer_expiry: hwgroup->busy was 0 ??\n", drive->name);
1330                         }
1331                         if ((expiry = hwgroup->expiry) != NULL) {
1332                                 /* continue */
1333                                 if ((wait = expiry(drive)) > 0) {
1334                                         /* reset timer */
1335                                         hwgroup->timer.expires  = jiffies + wait;
1336                                         add_timer(&hwgroup->timer);
1337                                         spin_unlock_irqrestore(&ide_lock, flags);
1338                                         return;
1339                                 }
1340                         }
1341                         hwgroup->handler = NULL;
1342                         /*
1343                          * We need to simulate a real interrupt when invoking
1344                          * the handler() function, which means we need to
1345                          * globally mask the specific IRQ:
1346                          */
1347                         spin_unlock(&ide_lock);
1348                         hwif  = HWIF(drive);
1349 #if DISABLE_IRQ_NOSYNC
1350                         disable_irq_nosync(hwif->irq);
1351 #else
1352                         /* disable_irq_nosync ?? */
1353                         disable_irq(hwif->irq);
1354 #endif /* DISABLE_IRQ_NOSYNC */
1355                         /* local CPU only,
1356                          * as if we were handling an interrupt */
1357                         local_irq_disable();
1358                         if (hwgroup->poll_timeout != 0) {
1359                                 startstop = handler(drive);
1360                         } else if (drive_is_ready(drive)) {
1361                                 if (drive->waiting_for_dma)
1362                                         (void) hwgroup->hwif->ide_dma_lostirq(drive);
1363                                 (void)ide_ack_intr(hwif);
1364                                 printk(KERN_WARNING "%s: lost interrupt\n", drive->name);
1365                                 startstop = handler(drive);
1366                         } else {
1367                                 if (drive->waiting_for_dma) {
1368                                         startstop = ide_dma_timeout_retry(drive, wait);
1369                                 } else
1370                                         startstop =
1371                                         DRIVER(drive)->error(drive, "irq timeout", hwif->INB(IDE_STATUS_REG));
1372                         }
1373                         drive->service_time = jiffies - drive->service_start;
1374                         spin_lock_irq(&ide_lock);
1375                         enable_irq(hwif->irq);
1376                         if (startstop == ide_stopped)
1377                                 hwgroup->busy = 0;
1378                 }
1379         }
1380         ide_do_request(hwgroup, IDE_NO_IRQ);
1381         spin_unlock_irqrestore(&ide_lock, flags);
1382 }
1383
1384 /**
1385  *      unexpected_intr         -       handle an unexpected IDE interrupt
1386  *      @irq: interrupt line
1387  *      @hwgroup: hwgroup being processed
1388  *
1389  *      There's nothing really useful we can do with an unexpected interrupt,
1390  *      other than reading the status register (to clear it), and logging it.
1391  *      There should be no way that an irq can happen before we're ready for it,
1392  *      so we needn't worry much about losing an "important" interrupt here.
1393  *
1394  *      On laptops (and "green" PCs), an unexpected interrupt occurs whenever
1395  *      the drive enters "idle", "standby", or "sleep" mode, so if the status
1396  *      looks "good", we just ignore the interrupt completely.
1397  *
1398  *      This routine assumes __cli() is in effect when called.
1399  *
1400  *      If an unexpected interrupt happens on irq15 while we are handling irq14
1401  *      and if the two interfaces are "serialized" (CMD640), then it looks like
1402  *      we could screw up by interfering with a new request being set up for 
1403  *      irq15.
1404  *
1405  *      In reality, this is a non-issue.  The new command is not sent unless 
1406  *      the drive is ready to accept one, in which case we know the drive is
1407  *      not trying to interrupt us.  And ide_set_handler() is always invoked
1408  *      before completing the issuance of any new drive command, so we will not
1409  *      be accidentally invoked as a result of any valid command completion
1410  *      interrupt.
1411  *
1412  *      Note that we must walk the entire hwgroup here. We know which hwif
1413  *      is doing the current command, but we don't know which hwif burped
1414  *      mysteriously.
1415  */
1416  
1417 static void unexpected_intr (int irq, ide_hwgroup_t *hwgroup)
1418 {
1419         u8 stat;
1420         ide_hwif_t *hwif = hwgroup->hwif;
1421
1422         /*
1423          * handle the unexpected interrupt
1424          */
1425         do {
1426                 if (hwif->irq == irq) {
1427                         stat = hwif->INB(hwif->io_ports[IDE_STATUS_OFFSET]);
1428                         if (!OK_STAT(stat, READY_STAT, BAD_STAT)) {
1429                                 /* Try to not flood the console with msgs */
1430                                 static unsigned long last_msgtime, count;
1431                                 ++count;
1432                                 if (time_after(jiffies, last_msgtime + HZ)) {
1433                                         last_msgtime = jiffies;
1434                                         printk(KERN_ERR "%s%s: unexpected interrupt, "
1435                                                 "status=0x%02x, count=%ld\n",
1436                                                 hwif->name,
1437                                                 (hwif->next==hwgroup->hwif) ? "" : "(?)", stat, count);
1438                                 }
1439                         }
1440                 }
1441         } while ((hwif = hwif->next) != hwgroup->hwif);
1442 }
1443
1444 /**
1445  *      ide_intr        -       default IDE interrupt handler
1446  *      @irq: interrupt number
1447  *      @dev_id: hwif group
1448  *      @regs: unused weirdness from the kernel irq layer
1449  *
1450  *      This is the default IRQ handler for the IDE layer. You should
1451  *      not need to override it. If you do be aware it is subtle in
1452  *      places
1453  *
1454  *      hwgroup->hwif is the interface in the group currently performing
1455  *      a command. hwgroup->drive is the drive and hwgroup->handler is
1456  *      the IRQ handler to call. As we issue a command the handlers
1457  *      step through multiple states, reassigning the handler to the
1458  *      next step in the process. Unlike a smart SCSI controller IDE
1459  *      expects the main processor to sequence the various transfer
1460  *      stages. We also manage a poll timer to catch up with most
1461  *      timeout situations. There are still a few where the handlers
1462  *      don't ever decide to give up.
1463  *
1464  *      The handler eventually returns ide_stopped to indicate the
1465  *      request completed. At this point we issue the next request
1466  *      on the hwgroup and the process begins again.
1467  */
1468  
1469 irqreturn_t ide_intr (int irq, void *dev_id, struct pt_regs *regs)
1470 {
1471         unsigned long flags;
1472         ide_hwgroup_t *hwgroup = (ide_hwgroup_t *)dev_id;
1473         ide_hwif_t *hwif;
1474         ide_drive_t *drive;
1475         ide_handler_t *handler;
1476         ide_startstop_t startstop;
1477
1478         spin_lock_irqsave(&ide_lock, flags);
1479         hwif = hwgroup->hwif;
1480
1481         if (!ide_ack_intr(hwif)) {
1482                 spin_unlock_irqrestore(&ide_lock, flags);
1483                 return IRQ_NONE;
1484         }
1485
1486         if (hwif->polling) {
1487                 /* We took an interrupt during a polled drive retune. 
1488                    This should go away eventually when that code uses
1489                    the polling logic like do_reset1 */
1490                 spin_unlock_irqrestore(&ide_lock, flags);
1491                 return IRQ_HANDLED;
1492         }
1493         if ((handler = hwgroup->handler) == NULL ||
1494             hwgroup->poll_timeout != 0) {
1495                 /*
1496                  * Not expecting an interrupt from this drive.
1497                  * That means this could be:
1498                  *      (1) an interrupt from another PCI device
1499                  *      sharing the same PCI INT# as us.
1500                  * or   (2) a drive just entered sleep or standby mode,
1501                  *      and is interrupting to let us know.
1502                  * or   (3) a spurious interrupt of unknown origin.
1503                  *
1504                  * For PCI, we cannot tell the difference,
1505                  * so in that case we just ignore it and hope it goes away.
1506                  *
1507                  * FIXME: unexpected_intr should be hwif-> then we can
1508                  * remove all the ifdef PCI crap
1509                  */
1510 #ifdef CONFIG_BLK_DEV_IDEPCI
1511                 if (hwif->pci_dev && !hwif->pci_dev->vendor)
1512 #endif  /* CONFIG_BLK_DEV_IDEPCI */
1513                 {
1514                         /*
1515                          * Probably not a shared PCI interrupt,
1516                          * so we can safely try to do something about it:
1517                          */
1518                         unexpected_intr(irq, hwgroup);
1519 #ifdef CONFIG_BLK_DEV_IDEPCI
1520                 } else {
1521                         /*
1522                          * Whack the status register, just in case
1523                          * we have a leftover pending IRQ.
1524                          */
1525                         (void) hwif->INB(hwif->io_ports[IDE_STATUS_OFFSET]);
1526 #endif /* CONFIG_BLK_DEV_IDEPCI */
1527                 }
1528                 spin_unlock_irqrestore(&ide_lock, flags);
1529                 return IRQ_NONE;
1530         }
1531         drive = hwgroup->drive;
1532         if (!drive) {
1533                 /*
1534                  * This should NEVER happen, and there isn't much
1535                  * we could do about it here.
1536                  *
1537                  * [Note - this can occur if the drive is hot unplugged]
1538                  */
1539                 spin_unlock_irqrestore(&ide_lock, flags);
1540                 return IRQ_HANDLED;
1541         }
1542         if (!drive_is_ready(drive)) {
1543                 /*
1544                  * This happens regularly when we share a PCI IRQ with
1545                  * another device.  Unfortunately, it can also happen
1546                  * with some buggy drives that trigger the IRQ before
1547                  * their status register is up to date.  Hopefully we have
1548                  * enough advance overhead that the latter isn't a problem.
1549                  */
1550                 spin_unlock_irqrestore(&ide_lock, flags);
1551                 return IRQ_NONE;
1552         }
1553         if (!hwgroup->busy) {
1554                 hwgroup->busy = 1;      /* paranoia */
1555                 printk(KERN_ERR "%s: ide_intr: hwgroup->busy was 0 ??\n", drive->name);
1556         }
1557         hwgroup->handler = NULL;
1558         del_timer(&hwgroup->timer);
1559         spin_unlock(&ide_lock);
1560
1561         if (drive->unmask)
1562                 local_irq_enable();
1563         /* service this interrupt, may set handler for next interrupt */
1564         startstop = handler(drive);
1565         spin_lock_irq(&ide_lock);
1566
1567         /*
1568          * Note that handler() may have set things up for another
1569          * interrupt to occur soon, but it cannot happen until
1570          * we exit from this routine, because it will be the
1571          * same irq as is currently being serviced here, and Linux
1572          * won't allow another of the same (on any CPU) until we return.
1573          */
1574         drive->service_time = jiffies - drive->service_start;
1575         if (startstop == ide_stopped) {
1576                 if (hwgroup->handler == NULL) { /* paranoia */
1577                         hwgroup->busy = 0;
1578                         ide_do_request(hwgroup, hwif->irq);
1579                 } else {
1580                         printk(KERN_ERR "%s: ide_intr: huh? expected NULL handler "
1581                                 "on exit\n", drive->name);
1582                 }
1583         }
1584         spin_unlock_irqrestore(&ide_lock, flags);
1585         return IRQ_HANDLED;
1586 }
1587
1588 /**
1589  *      ide_init_drive_cmd      -       initialize a drive command request
1590  *      @rq: request object
1591  *
1592  *      Initialize a request before we fill it in and send it down to
1593  *      ide_do_drive_cmd. Commands must be set up by this function. Right
1594  *      now it doesn't do a lot, but if that changes abusers will have a
1595  *      nasty suprise.
1596  */
1597
1598 void ide_init_drive_cmd (struct request *rq)
1599 {
1600         memset(rq, 0, sizeof(*rq));
1601         rq->flags = REQ_DRIVE_CMD;
1602         rq->ref_count = 1;
1603 }
1604
1605 EXPORT_SYMBOL(ide_init_drive_cmd);
1606
1607 /**
1608  *      ide_do_drive_cmd        -       issue IDE special command
1609  *      @drive: device to issue command
1610  *      @rq: request to issue
1611  *      @action: action for processing
1612  *
1613  *      This function issues a special IDE device request
1614  *      onto the request queue.
1615  *
1616  *      If action is ide_wait, then the rq is queued at the end of the
1617  *      request queue, and the function sleeps until it has been processed.
1618  *      This is for use when invoked from an ioctl handler.
1619  *
1620  *      If action is ide_preempt, then the rq is queued at the head of
1621  *      the request queue, displacing the currently-being-processed
1622  *      request and this function returns immediately without waiting
1623  *      for the new rq to be completed.  This is VERY DANGEROUS, and is
1624  *      intended for careful use by the ATAPI tape/cdrom driver code.
1625  *
1626  *      If action is ide_next, then the rq is queued immediately after
1627  *      the currently-being-processed-request (if any), and the function
1628  *      returns without waiting for the new rq to be completed.  As above,
1629  *      This is VERY DANGEROUS, and is intended for careful use by the
1630  *      ATAPI tape/cdrom driver code.
1631  *
1632  *      If action is ide_end, then the rq is queued at the end of the
1633  *      request queue, and the function returns immediately without waiting
1634  *      for the new rq to be completed. This is again intended for careful
1635  *      use by the ATAPI tape/cdrom driver code.
1636  */
1637  
1638 int ide_do_drive_cmd (ide_drive_t *drive, struct request *rq, ide_action_t action)
1639 {
1640         unsigned long flags;
1641         ide_hwgroup_t *hwgroup = HWGROUP(drive);
1642         DECLARE_COMPLETION(wait);
1643         int where = ELEVATOR_INSERT_BACK, err;
1644         int must_wait = (action == ide_wait || action == ide_head_wait);
1645
1646         rq->errors = 0;
1647         rq->rq_status = RQ_ACTIVE;
1648
1649         rq->rq_disk = drive->disk;
1650
1651         /*
1652          * we need to hold an extra reference to request for safe inspection
1653          * after completion
1654          */
1655         if (must_wait) {
1656                 rq->ref_count++;
1657                 rq->waiting = &wait;
1658         }
1659
1660         spin_lock_irqsave(&ide_lock, flags);
1661         if (action == ide_preempt)
1662                 hwgroup->rq = NULL;
1663         if (action == ide_preempt || action == ide_head_wait) {
1664                 where = ELEVATOR_INSERT_FRONT;
1665                 rq->flags |= REQ_PREEMPT;
1666         }
1667         __elv_add_request(drive->queue, rq, where, 0);
1668         ide_do_request(hwgroup, IDE_NO_IRQ);
1669         spin_unlock_irqrestore(&ide_lock, flags);
1670
1671         err = 0;
1672         if (must_wait) {
1673                 wait_for_completion(&wait);
1674                 rq->waiting = NULL;
1675                 if (rq->errors)
1676                         err = -EIO;
1677
1678                 blk_put_request(rq);
1679         }
1680
1681         return err;
1682 }
1683
1684 EXPORT_SYMBOL(ide_do_drive_cmd);