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