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