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