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