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