ide-tape.c revision c7ea8a1b36487cb3002c2a626261c99a9f30790c
1/*
2 * IDE ATAPI streaming tape driver.
3 *
4 * Copyright (C) 1995-1999  Gadi Oxman <gadio@netvision.net.il>
5 * Copyright (C) 2003-2005  Bartlomiej Zolnierkiewicz
6 *
7 * This driver was constructed as a student project in the software laboratory
8 * of the faculty of electrical engineering in the Technion - Israel's
9 * Institute Of Technology, with the guide of Avner Lottem and Dr. Ilana David.
10 *
11 * It is hereby placed under the terms of the GNU general public license.
12 * (See linux/COPYING).
13 *
14 * For a historical changelog see
15 * Documentation/ide/ChangeLog.ide-tape.1995-2002
16 */
17
18#define IDETAPE_VERSION "1.19"
19
20#include <linux/module.h>
21#include <linux/types.h>
22#include <linux/string.h>
23#include <linux/kernel.h>
24#include <linux/delay.h>
25#include <linux/timer.h>
26#include <linux/mm.h>
27#include <linux/interrupt.h>
28#include <linux/jiffies.h>
29#include <linux/major.h>
30#include <linux/errno.h>
31#include <linux/genhd.h>
32#include <linux/slab.h>
33#include <linux/pci.h>
34#include <linux/ide.h>
35#include <linux/smp_lock.h>
36#include <linux/completion.h>
37#include <linux/bitops.h>
38#include <linux/mutex.h>
39
40#include <asm/byteorder.h>
41#include <asm/irq.h>
42#include <asm/uaccess.h>
43#include <asm/io.h>
44#include <asm/unaligned.h>
45
46/*
47 * partition
48 */
49typedef struct os_partition_s {
50	__u8	partition_num;
51	__u8	par_desc_ver;
52	__u16	wrt_pass_cntr;
53	__u32	first_frame_addr;
54	__u32	last_frame_addr;
55	__u32	eod_frame_addr;
56} os_partition_t;
57
58/*
59 * DAT entry
60 */
61typedef struct os_dat_entry_s {
62	__u32	blk_sz;
63	__u16	blk_cnt;
64	__u8	flags;
65	__u8	reserved;
66} os_dat_entry_t;
67
68/*
69 * DAT
70 */
71#define OS_DAT_FLAGS_DATA	(0xc)
72#define OS_DAT_FLAGS_MARK	(0x1)
73
74typedef struct os_dat_s {
75	__u8		dat_sz;
76	__u8		reserved1;
77	__u8		entry_cnt;
78	__u8		reserved3;
79	os_dat_entry_t	dat_list[16];
80} os_dat_t;
81
82#include <linux/mtio.h>
83
84/**************************** Tunable parameters *****************************/
85
86
87/*
88 *	Pipelined mode parameters.
89 *
90 *	We try to use the minimum number of stages which is enough to
91 *	keep the tape constantly streaming. To accomplish that, we implement
92 *	a feedback loop around the maximum number of stages:
93 *
94 *	We start from MIN maximum stages (we will not even use MIN stages
95 *      if we don't need them), increment it by RATE*(MAX-MIN)
96 *	whenever we sense that the pipeline is empty, until we reach
97 *	the optimum value or until we reach MAX.
98 *
99 *	Setting the following parameter to 0 is illegal: the pipelined mode
100 *	cannot be disabled (calculate_speeds() divides by tape->max_stages.)
101 */
102#define IDETAPE_MIN_PIPELINE_STAGES	  1
103#define IDETAPE_MAX_PIPELINE_STAGES	400
104#define IDETAPE_INCREASE_STAGES_RATE	 20
105
106/*
107 *	The following are used to debug the driver:
108 *
109 *	Setting IDETAPE_DEBUG_INFO to 1 will report device capabilities.
110 *	Setting IDETAPE_DEBUG_LOG to 1 will log driver flow control.
111 *	Setting IDETAPE_DEBUG_BUGS to 1 will enable self-sanity checks in
112 *	some places.
113 *
114 *	Setting them to 0 will restore normal operation mode:
115 *
116 *		1.	Disable logging normal successful operations.
117 *		2.	Disable self-sanity checks.
118 *		3.	Errors will still be logged, of course.
119 *
120 *	All the #if DEBUG code will be removed some day, when the driver
121 *	is verified to be stable enough. This will make it much more
122 *	esthetic.
123 */
124#define IDETAPE_DEBUG_INFO		0
125#define IDETAPE_DEBUG_LOG		0
126#define IDETAPE_DEBUG_BUGS		1
127
128/*
129 *	After each failed packet command we issue a request sense command
130 *	and retry the packet command IDETAPE_MAX_PC_RETRIES times.
131 *
132 *	Setting IDETAPE_MAX_PC_RETRIES to 0 will disable retries.
133 */
134#define IDETAPE_MAX_PC_RETRIES		3
135
136/*
137 *	With each packet command, we allocate a buffer of
138 *	IDETAPE_PC_BUFFER_SIZE bytes. This is used for several packet
139 *	commands (Not for READ/WRITE commands).
140 */
141#define IDETAPE_PC_BUFFER_SIZE		256
142
143/*
144 *	In various places in the driver, we need to allocate storage
145 *	for packet commands and requests, which will remain valid while
146 *	we leave the driver to wait for an interrupt or a timeout event.
147 */
148#define IDETAPE_PC_STACK		(10 + IDETAPE_MAX_PC_RETRIES)
149
150/*
151 * Some drives (for example, Seagate STT3401A Travan) require a very long
152 * timeout, because they don't return an interrupt or clear their busy bit
153 * until after the command completes (even retension commands).
154 */
155#define IDETAPE_WAIT_CMD		(900*HZ)
156
157/*
158 *	The following parameter is used to select the point in the internal
159 *	tape fifo in which we will start to refill the buffer. Decreasing
160 *	the following parameter will improve the system's latency and
161 *	interactive response, while using a high value might improve system
162 *	throughput.
163 */
164#define IDETAPE_FIFO_THRESHOLD 		2
165
166/*
167 *	DSC polling parameters.
168 *
169 *	Polling for DSC (a single bit in the status register) is a very
170 *	important function in ide-tape. There are two cases in which we
171 *	poll for DSC:
172 *
173 *	1.	Before a read/write packet command, to ensure that we
174 *		can transfer data from/to the tape's data buffers, without
175 *		causing an actual media access. In case the tape is not
176 *		ready yet, we take out our request from the device
177 *		request queue, so that ide.c will service requests from
178 *		the other device on the same interface meanwhile.
179 *
180 *	2.	After the successful initialization of a "media access
181 *		packet command", which is a command which can take a long
182 *		time to complete (it can be several seconds or even an hour).
183 *
184 *		Again, we postpone our request in the middle to free the bus
185 *		for the other device. The polling frequency here should be
186 *		lower than the read/write frequency since those media access
187 *		commands are slow. We start from a "fast" frequency -
188 *		IDETAPE_DSC_MA_FAST (one second), and if we don't receive DSC
189 *		after IDETAPE_DSC_MA_THRESHOLD (5 minutes), we switch it to a
190 *		lower frequency - IDETAPE_DSC_MA_SLOW (1 minute).
191 *
192 *	We also set a timeout for the timer, in case something goes wrong.
193 *	The timeout should be longer then the maximum execution time of a
194 *	tape operation.
195 */
196
197/*
198 *	DSC timings.
199 */
200#define IDETAPE_DSC_RW_MIN		5*HZ/100	/* 50 msec */
201#define IDETAPE_DSC_RW_MAX		40*HZ/100	/* 400 msec */
202#define IDETAPE_DSC_RW_TIMEOUT		2*60*HZ		/* 2 minutes */
203#define IDETAPE_DSC_MA_FAST		2*HZ		/* 2 seconds */
204#define IDETAPE_DSC_MA_THRESHOLD	5*60*HZ		/* 5 minutes */
205#define IDETAPE_DSC_MA_SLOW		30*HZ		/* 30 seconds */
206#define IDETAPE_DSC_MA_TIMEOUT		2*60*60*HZ	/* 2 hours */
207
208/*************************** End of tunable parameters ***********************/
209
210/*
211 *	Read/Write error simulation
212 */
213#define SIMULATE_ERRORS			0
214
215/*
216 *	For general magnetic tape device compatibility.
217 */
218typedef enum {
219	idetape_direction_none,
220	idetape_direction_read,
221	idetape_direction_write
222} idetape_chrdev_direction_t;
223
224struct idetape_bh {
225	u32 b_size;
226	atomic_t b_count;
227	struct idetape_bh *b_reqnext;
228	char *b_data;
229};
230
231/*
232 *	Our view of a packet command.
233 */
234typedef struct idetape_packet_command_s {
235	u8 c[12];				/* Actual packet bytes */
236	int retries;				/* On each retry, we increment retries */
237	int error;				/* Error code */
238	int request_transfer;			/* Bytes to transfer */
239	int actually_transferred;		/* Bytes actually transferred */
240	int buffer_size;			/* Size of our data buffer */
241	struct idetape_bh *bh;
242	char *b_data;
243	int b_count;
244	u8 *buffer;				/* Data buffer */
245	u8 *current_position;			/* Pointer into the above buffer */
246	ide_startstop_t (*callback) (ide_drive_t *);	/* Called when this packet command is completed */
247	u8 pc_buffer[IDETAPE_PC_BUFFER_SIZE];	/* Temporary buffer */
248	unsigned long flags;			/* Status/Action bit flags: long for set_bit */
249} idetape_pc_t;
250
251/*
252 *	Packet command flag bits.
253 */
254/* Set when an error is considered normal - We won't retry */
255#define	PC_ABORT			0
256/* 1 When polling for DSC on a media access command */
257#define PC_WAIT_FOR_DSC			1
258/* 1 when we prefer to use DMA if possible */
259#define PC_DMA_RECOMMENDED		2
260/* 1 while DMA in progress */
261#define	PC_DMA_IN_PROGRESS		3
262/* 1 when encountered problem during DMA */
263#define	PC_DMA_ERROR			4
264/* Data direction */
265#define	PC_WRITING			5
266
267/*
268 *	Capabilities and Mechanical Status Page
269 */
270typedef struct {
271	unsigned	page_code	:6;	/* Page code - Should be 0x2a */
272	__u8		reserved0_6	:1;
273	__u8		ps		:1;	/* parameters saveable */
274	__u8		page_length;		/* Page Length - Should be 0x12 */
275	__u8		reserved2, reserved3;
276	unsigned	ro		:1;	/* Read Only Mode */
277	unsigned	reserved4_1234	:4;
278	unsigned	sprev		:1;	/* Supports SPACE in the reverse direction */
279	unsigned	reserved4_67	:2;
280	unsigned	reserved5_012	:3;
281	unsigned	efmt		:1;	/* Supports ERASE command initiated formatting */
282	unsigned	reserved5_4	:1;
283	unsigned	qfa		:1;	/* Supports the QFA two partition formats */
284	unsigned	reserved5_67	:2;
285	unsigned	lock		:1;	/* Supports locking the volume */
286	unsigned	locked		:1;	/* The volume is locked */
287	unsigned	prevent		:1;	/* The device defaults in the prevent state after power up */
288	unsigned	eject		:1;	/* The device can eject the volume */
289	__u8		disconnect	:1;	/* The device can break request > ctl */
290	__u8		reserved6_5	:1;
291	unsigned	ecc		:1;	/* Supports error correction */
292	unsigned	cmprs		:1;	/* Supports data compression */
293	unsigned	reserved7_0	:1;
294	unsigned	blk512		:1;	/* Supports 512 bytes block size */
295	unsigned	blk1024		:1;	/* Supports 1024 bytes block size */
296	unsigned	reserved7_3_6	:4;
297	unsigned	blk32768	:1;	/* slowb - the device restricts the byte count for PIO */
298						/* transfers for slow buffer memory ??? */
299						/* Also 32768 block size in some cases */
300	__u16		max_speed;		/* Maximum speed supported in KBps */
301	__u8		reserved10, reserved11;
302	__u16		ctl;			/* Continuous Transfer Limit in blocks */
303	__u16		speed;			/* Current Speed, in KBps */
304	__u16		buffer_size;		/* Buffer Size, in 512 bytes */
305	__u8		reserved18, reserved19;
306} idetape_capabilities_page_t;
307
308/*
309 *	Block Size Page
310 */
311typedef struct {
312	unsigned	page_code	:6;	/* Page code - Should be 0x30 */
313	unsigned	reserved1_6	:1;
314	unsigned	ps		:1;
315	__u8		page_length;		/* Page Length - Should be 2 */
316	__u8		reserved2;
317	unsigned	play32		:1;
318	unsigned	play32_5	:1;
319	unsigned	reserved2_23	:2;
320	unsigned	record32	:1;
321	unsigned	record32_5	:1;
322	unsigned	reserved2_6	:1;
323	unsigned	one		:1;
324} idetape_block_size_page_t;
325
326/*
327 *	A pipeline stage.
328 */
329typedef struct idetape_stage_s {
330	struct request rq;			/* The corresponding request */
331	struct idetape_bh *bh;			/* The data buffers */
332	struct idetape_stage_s *next;		/* Pointer to the next stage */
333} idetape_stage_t;
334
335/*
336 *	REQUEST SENSE packet command result - Data Format.
337 */
338typedef struct {
339	unsigned	error_code	:7;	/* Current of deferred errors */
340	unsigned	valid		:1;	/* The information field conforms to QIC-157C */
341	__u8		reserved1	:8;	/* Segment Number - Reserved */
342	unsigned	sense_key	:4;	/* Sense Key */
343	unsigned	reserved2_4	:1;	/* Reserved */
344	unsigned	ili		:1;	/* Incorrect Length Indicator */
345	unsigned	eom		:1;	/* End Of Medium */
346	unsigned	filemark 	:1;	/* Filemark */
347	__u32		information __attribute__ ((packed));
348	__u8		asl;			/* Additional sense length (n-7) */
349	__u32		command_specific;	/* Additional command specific information */
350	__u8		asc;			/* Additional Sense Code */
351	__u8		ascq;			/* Additional Sense Code Qualifier */
352	__u8		replaceable_unit_code;	/* Field Replaceable Unit Code */
353	unsigned	sk_specific1 	:7;	/* Sense Key Specific */
354	unsigned	sksv		:1;	/* Sense Key Specific information is valid */
355	__u8		sk_specific2;		/* Sense Key Specific */
356	__u8		sk_specific3;		/* Sense Key Specific */
357	__u8		pad[2];			/* Padding to 20 bytes */
358} idetape_request_sense_result_t;
359
360
361/*
362 *	Most of our global data which we need to save even as we leave the
363 *	driver due to an interrupt or a timer event is stored in a variable
364 *	of type idetape_tape_t, defined below.
365 */
366typedef struct ide_tape_obj {
367	ide_drive_t	*drive;
368	ide_driver_t	*driver;
369	struct gendisk	*disk;
370	struct kref	kref;
371
372	/*
373	 *	Since a typical character device operation requires more
374	 *	than one packet command, we provide here enough memory
375	 *	for the maximum of interconnected packet commands.
376	 *	The packet commands are stored in the circular array pc_stack.
377	 *	pc_stack_index points to the last used entry, and warps around
378	 *	to the start when we get to the last array entry.
379	 *
380	 *	pc points to the current processed packet command.
381	 *
382	 *	failed_pc points to the last failed packet command, or contains
383	 *	NULL if we do not need to retry any packet command. This is
384	 *	required since an additional packet command is needed before the
385	 *	retry, to get detailed information on what went wrong.
386	 */
387	/* Current packet command */
388	idetape_pc_t *pc;
389	/* Last failed packet command */
390	idetape_pc_t *failed_pc;
391	/* Packet command stack */
392	idetape_pc_t pc_stack[IDETAPE_PC_STACK];
393	/* Next free packet command storage space */
394	int pc_stack_index;
395	struct request rq_stack[IDETAPE_PC_STACK];
396	/* We implement a circular array */
397	int rq_stack_index;
398
399	/*
400	 *	DSC polling variables.
401	 *
402	 *	While polling for DSC we use postponed_rq to postpone the
403	 *	current request so that ide.c will be able to service
404	 *	pending requests on the other device. Note that at most
405	 *	we will have only one DSC (usually data transfer) request
406	 *	in the device request queue. Additional requests can be
407	 *	queued in our internal pipeline, but they will be visible
408	 *	to ide.c only one at a time.
409	 */
410	struct request *postponed_rq;
411	/* The time in which we started polling for DSC */
412	unsigned long dsc_polling_start;
413	/* Timer used to poll for dsc */
414	struct timer_list dsc_timer;
415	/* Read/Write dsc polling frequency */
416	unsigned long best_dsc_rw_frequency;
417	/* The current polling frequency */
418	unsigned long dsc_polling_frequency;
419	/* Maximum waiting time */
420	unsigned long dsc_timeout;
421
422	/*
423	 *	Read position information
424	 */
425	u8 partition;
426	/* Current block */
427	unsigned int first_frame_position;
428	unsigned int last_frame_position;
429	unsigned int blocks_in_buffer;
430
431	/*
432	 *	Last error information
433	 */
434	u8 sense_key, asc, ascq;
435
436	/*
437	 *	Character device operation
438	 */
439	unsigned int minor;
440	/* device name */
441	char name[4];
442	/* Current character device data transfer direction */
443	idetape_chrdev_direction_t chrdev_direction;
444
445	/*
446	 *	Device information
447	 */
448	/* Usually 512 or 1024 bytes */
449	unsigned short tape_block_size;
450	int user_bs_factor;
451	/* Copy of the tape's Capabilities and Mechanical Page */
452	idetape_capabilities_page_t capabilities;
453
454	/*
455	 *	Active data transfer request parameters.
456	 *
457	 *	At most, there is only one ide-tape originated data transfer
458	 *	request in the device request queue. This allows ide.c to
459	 *	easily service requests from the other device when we
460	 *	postpone our active request. In the pipelined operation
461	 *	mode, we use our internal pipeline structure to hold
462	 *	more data requests.
463	 *
464	 *	The data buffer size is chosen based on the tape's
465	 *	recommendation.
466	 */
467	/* Pointer to the request which is waiting in the device request queue */
468	struct request *active_data_request;
469	/* Data buffer size (chosen based on the tape's recommendation */
470	int stage_size;
471	idetape_stage_t *merge_stage;
472	int merge_stage_size;
473	struct idetape_bh *bh;
474	char *b_data;
475	int b_count;
476
477	/*
478	 *	Pipeline parameters.
479	 *
480	 *	To accomplish non-pipelined mode, we simply set the following
481	 *	variables to zero (or NULL, where appropriate).
482	 */
483	/* Number of currently used stages */
484	int nr_stages;
485	/* Number of pending stages */
486	int nr_pending_stages;
487	/* We will not allocate more than this number of stages */
488	int max_stages, min_pipeline, max_pipeline;
489	/* The first stage which will be removed from the pipeline */
490	idetape_stage_t *first_stage;
491	/* The currently active stage */
492	idetape_stage_t *active_stage;
493	/* Will be serviced after the currently active request */
494	idetape_stage_t *next_stage;
495	/* New requests will be added to the pipeline here */
496	idetape_stage_t *last_stage;
497	/* Optional free stage which we can use */
498	idetape_stage_t *cache_stage;
499	int pages_per_stage;
500	/* Wasted space in each stage */
501	int excess_bh_size;
502
503	/* Status/Action flags: long for set_bit */
504	unsigned long flags;
505	/* protects the ide-tape queue */
506	spinlock_t spinlock;
507
508	/*
509	 * Measures average tape speed
510	 */
511	unsigned long avg_time;
512	int avg_size;
513	int avg_speed;
514
515	/* last sense information */
516	idetape_request_sense_result_t sense;
517
518	char vendor_id[10];
519	char product_id[18];
520	char firmware_revision[6];
521	int firmware_revision_num;
522
523	/* the door is currently locked */
524	int door_locked;
525	/* the tape hardware is write protected */
526	char drv_write_prot;
527	/* the tape is write protected (hardware or opened as read-only) */
528	char write_prot;
529
530	/*
531	 * Limit the number of times a request can
532	 * be postponed, to avoid an infinite postpone
533	 * deadlock.
534	 */
535	/* request postpone count limit */
536	int postpone_cnt;
537
538	/*
539	 * Measures number of frames:
540	 *
541	 * 1. written/read to/from the driver pipeline (pipeline_head).
542	 * 2. written/read to/from the tape buffers (idetape_bh).
543	 * 3. written/read by the tape to/from the media (tape_head).
544	 */
545	int pipeline_head;
546	int buffer_head;
547	int tape_head;
548	int last_tape_head;
549
550	/*
551	 * Speed control at the tape buffers input/output
552	 */
553	unsigned long insert_time;
554	int insert_size;
555	int insert_speed;
556	int max_insert_speed;
557	int measure_insert_time;
558
559	/*
560	 * Measure tape still time, in milliseconds
561	 */
562	unsigned long tape_still_time_begin;
563	int tape_still_time;
564
565	/*
566	 * Speed regulation negative feedback loop
567	 */
568	int speed_control;
569	int pipeline_head_speed;
570	int controlled_pipeline_head_speed;
571	int uncontrolled_pipeline_head_speed;
572	int controlled_last_pipeline_head;
573	int uncontrolled_last_pipeline_head;
574	unsigned long uncontrolled_pipeline_head_time;
575	unsigned long controlled_pipeline_head_time;
576	int controlled_previous_pipeline_head;
577	int uncontrolled_previous_pipeline_head;
578	unsigned long controlled_previous_head_time;
579	unsigned long uncontrolled_previous_head_time;
580	int restart_speed_control_req;
581
582        /*
583         * Debug_level determines amount of debugging output;
584         * can be changed using /proc/ide/hdx/settings
585         * 0 : almost no debugging output
586         * 1 : 0+output errors only
587         * 2 : 1+output all sensekey/asc
588         * 3 : 2+follow all chrdev related procedures
589         * 4 : 3+follow all procedures
590         * 5 : 4+include pc_stack rq_stack info
591         * 6 : 5+USE_COUNT updates
592         */
593         int debug_level;
594} idetape_tape_t;
595
596static DEFINE_MUTEX(idetape_ref_mutex);
597
598static struct class *idetape_sysfs_class;
599
600#define to_ide_tape(obj) container_of(obj, struct ide_tape_obj, kref)
601
602#define ide_tape_g(disk) \
603	container_of((disk)->private_data, struct ide_tape_obj, driver)
604
605static struct ide_tape_obj *ide_tape_get(struct gendisk *disk)
606{
607	struct ide_tape_obj *tape = NULL;
608
609	mutex_lock(&idetape_ref_mutex);
610	tape = ide_tape_g(disk);
611	if (tape)
612		kref_get(&tape->kref);
613	mutex_unlock(&idetape_ref_mutex);
614	return tape;
615}
616
617static void ide_tape_release(struct kref *);
618
619static void ide_tape_put(struct ide_tape_obj *tape)
620{
621	mutex_lock(&idetape_ref_mutex);
622	kref_put(&tape->kref, ide_tape_release);
623	mutex_unlock(&idetape_ref_mutex);
624}
625
626/*
627 *	Tape door status
628 */
629#define DOOR_UNLOCKED			0
630#define DOOR_LOCKED			1
631#define DOOR_EXPLICITLY_LOCKED		2
632
633/*
634 *	Tape flag bits values.
635 */
636#define IDETAPE_IGNORE_DSC		0
637#define IDETAPE_ADDRESS_VALID		1	/* 0 When the tape position is unknown */
638#define IDETAPE_BUSY			2	/* Device already opened */
639#define IDETAPE_PIPELINE_ERROR		3	/* Error detected in a pipeline stage */
640#define IDETAPE_DETECT_BS		4	/* Attempt to auto-detect the current user block size */
641#define IDETAPE_FILEMARK		5	/* Currently on a filemark */
642#define IDETAPE_DRQ_INTERRUPT		6	/* DRQ interrupt device */
643#define IDETAPE_READ_ERROR		7
644#define IDETAPE_PIPELINE_ACTIVE		8	/* pipeline active */
645/* 0 = no tape is loaded, so we don't rewind after ejecting */
646#define IDETAPE_MEDIUM_PRESENT		9
647
648/*
649 *	Supported ATAPI tape drives packet commands
650 */
651#define IDETAPE_TEST_UNIT_READY_CMD	0x00
652#define IDETAPE_REWIND_CMD		0x01
653#define IDETAPE_REQUEST_SENSE_CMD	0x03
654#define IDETAPE_READ_CMD		0x08
655#define IDETAPE_WRITE_CMD		0x0a
656#define IDETAPE_WRITE_FILEMARK_CMD	0x10
657#define IDETAPE_SPACE_CMD		0x11
658#define IDETAPE_INQUIRY_CMD		0x12
659#define IDETAPE_ERASE_CMD		0x19
660#define IDETAPE_MODE_SENSE_CMD		0x1a
661#define IDETAPE_MODE_SELECT_CMD		0x15
662#define IDETAPE_LOAD_UNLOAD_CMD		0x1b
663#define IDETAPE_PREVENT_CMD		0x1e
664#define IDETAPE_LOCATE_CMD		0x2b
665#define IDETAPE_READ_POSITION_CMD	0x34
666#define IDETAPE_READ_BUFFER_CMD		0x3c
667#define IDETAPE_SET_SPEED_CMD		0xbb
668
669/*
670 *	Some defines for the READ BUFFER command
671 */
672#define IDETAPE_RETRIEVE_FAULTY_BLOCK	6
673
674/*
675 *	Some defines for the SPACE command
676 */
677#define IDETAPE_SPACE_OVER_FILEMARK	1
678#define IDETAPE_SPACE_TO_EOD		3
679
680/*
681 *	Some defines for the LOAD UNLOAD command
682 */
683#define IDETAPE_LU_LOAD_MASK		1
684#define IDETAPE_LU_RETENSION_MASK	2
685#define IDETAPE_LU_EOT_MASK		4
686
687/*
688 *	Special requests for our block device strategy routine.
689 *
690 *	In order to service a character device command, we add special
691 *	requests to the tail of our block device request queue and wait
692 *	for their completion.
693 */
694
695enum {
696	REQ_IDETAPE_PC1		= (1 << 0), /* packet command (first stage) */
697	REQ_IDETAPE_PC2		= (1 << 1), /* packet command (second stage) */
698	REQ_IDETAPE_READ	= (1 << 2),
699	REQ_IDETAPE_WRITE	= (1 << 3),
700	REQ_IDETAPE_READ_BUFFER	= (1 << 4),
701};
702
703/*
704 *	Error codes which are returned in rq->errors to the higher part
705 *	of the driver.
706 */
707#define	IDETAPE_ERROR_GENERAL		101
708#define	IDETAPE_ERROR_FILEMARK		102
709#define	IDETAPE_ERROR_EOD		103
710
711/*
712 *	The following is used to format the general configuration word of
713 *	the ATAPI IDENTIFY DEVICE command.
714 */
715struct idetape_id_gcw {
716	unsigned packet_size		:2;	/* Packet Size */
717	unsigned reserved234		:3;	/* Reserved */
718	unsigned drq_type		:2;	/* Command packet DRQ type */
719	unsigned removable		:1;	/* Removable media */
720	unsigned device_type		:5;	/* Device type */
721	unsigned reserved13		:1;	/* Reserved */
722	unsigned protocol		:2;	/* Protocol type */
723};
724
725/*
726 *	INQUIRY packet command - Data Format (From Table 6-8 of QIC-157C)
727 */
728typedef struct {
729	unsigned	device_type	:5;	/* Peripheral Device Type */
730	unsigned	reserved0_765	:3;	/* Peripheral Qualifier - Reserved */
731	unsigned	reserved1_6t0	:7;	/* Reserved */
732	unsigned	rmb		:1;	/* Removable Medium Bit */
733	unsigned	ansi_version	:3;	/* ANSI Version */
734	unsigned	ecma_version	:3;	/* ECMA Version */
735	unsigned	iso_version	:2;	/* ISO Version */
736	unsigned	response_format :4;	/* Response Data Format */
737	unsigned	reserved3_45	:2;	/* Reserved */
738	unsigned	reserved3_6	:1;	/* TrmIOP - Reserved */
739	unsigned	reserved3_7	:1;	/* AENC - Reserved */
740	__u8		additional_length;	/* Additional Length (total_length-4) */
741	__u8		rsv5, rsv6, rsv7;	/* Reserved */
742	__u8		vendor_id[8];		/* Vendor Identification */
743	__u8		product_id[16];		/* Product Identification */
744	__u8		revision_level[4];	/* Revision Level */
745	__u8		vendor_specific[20];	/* Vendor Specific - Optional */
746	__u8		reserved56t95[40];	/* Reserved - Optional */
747						/* Additional information may be returned */
748} idetape_inquiry_result_t;
749
750/*
751 *	READ POSITION packet command - Data Format (From Table 6-57)
752 */
753typedef struct {
754	unsigned	reserved0_10	:2;	/* Reserved */
755	unsigned	bpu		:1;	/* Block Position Unknown */
756	unsigned	reserved0_543	:3;	/* Reserved */
757	unsigned	eop		:1;	/* End Of Partition */
758	unsigned	bop		:1;	/* Beginning Of Partition */
759	u8		partition;		/* Partition Number */
760	u8		reserved2, reserved3;	/* Reserved */
761	u32		first_block;		/* First Block Location */
762	u32		last_block;		/* Last Block Location (Optional) */
763	u8		reserved12;		/* Reserved */
764	u8		blocks_in_buffer[3];	/* Blocks In Buffer - (Optional) */
765	u32		bytes_in_buffer;	/* Bytes In Buffer (Optional) */
766} idetape_read_position_result_t;
767
768/*
769 *	Follows structures which are related to the SELECT SENSE / MODE SENSE
770 *	packet commands. Those packet commands are still not supported
771 *	by ide-tape.
772 */
773#define IDETAPE_BLOCK_DESCRIPTOR	0
774#define	IDETAPE_CAPABILITIES_PAGE	0x2a
775#define IDETAPE_PARAMTR_PAGE		0x2b   /* Onstream DI-x0 only */
776#define IDETAPE_BLOCK_SIZE_PAGE		0x30
777#define IDETAPE_BUFFER_FILLING_PAGE	0x33
778
779/*
780 *	Mode Parameter Header for the MODE SENSE packet command
781 */
782typedef struct {
783	__u8	mode_data_length;	/* Length of the following data transfer */
784	__u8	medium_type;		/* Medium Type */
785	__u8	dsp;			/* Device Specific Parameter */
786	__u8	bdl;			/* Block Descriptor Length */
787} idetape_mode_parameter_header_t;
788
789/*
790 *	Mode Parameter Block Descriptor the MODE SENSE packet command
791 *
792 *	Support for block descriptors is optional.
793 */
794typedef struct {
795	__u8		density_code;		/* Medium density code */
796	__u8		blocks[3];		/* Number of blocks */
797	__u8		reserved4;		/* Reserved */
798	__u8		length[3];		/* Block Length */
799} idetape_parameter_block_descriptor_t;
800
801/*
802 *	The Data Compression Page, as returned by the MODE SENSE packet command.
803 */
804typedef struct {
805	unsigned	page_code	:6;	/* Page Code - Should be 0xf */
806	unsigned	reserved0	:1;	/* Reserved */
807	unsigned	ps		:1;
808	__u8		page_length;		/* Page Length - Should be 14 */
809	unsigned	reserved2	:6;	/* Reserved */
810	unsigned	dcc		:1;	/* Data Compression Capable */
811	unsigned	dce		:1;	/* Data Compression Enable */
812	unsigned	reserved3	:5;	/* Reserved */
813	unsigned	red		:2;	/* Report Exception on Decompression */
814	unsigned	dde		:1;	/* Data Decompression Enable */
815	__u32		ca;			/* Compression Algorithm */
816	__u32		da;			/* Decompression Algorithm */
817	__u8		reserved[4];		/* Reserved */
818} idetape_data_compression_page_t;
819
820/*
821 *	The Medium Partition Page, as returned by the MODE SENSE packet command.
822 */
823typedef struct {
824	unsigned	page_code	:6;	/* Page Code - Should be 0x11 */
825	unsigned	reserved1_6	:1;	/* Reserved */
826	unsigned	ps		:1;
827	__u8		page_length;		/* Page Length - Should be 6 */
828	__u8		map;			/* Maximum Additional Partitions - Should be 0 */
829	__u8		apd;			/* Additional Partitions Defined - Should be 0 */
830	unsigned	reserved4_012	:3;	/* Reserved */
831	unsigned	psum		:2;	/* Should be 0 */
832	unsigned	idp		:1;	/* Should be 0 */
833	unsigned	sdp		:1;	/* Should be 0 */
834	unsigned	fdp		:1;	/* Fixed Data Partitions */
835	__u8		mfr;			/* Medium Format Recognition */
836	__u8		reserved[2];		/* Reserved */
837} idetape_medium_partition_page_t;
838
839/*
840 *	Run time configurable parameters.
841 */
842typedef struct {
843	int	dsc_rw_frequency;
844	int	dsc_media_access_frequency;
845	int	nr_stages;
846} idetape_config_t;
847
848/*
849 *	The variables below are used for the character device interface.
850 *	Additional state variables are defined in our ide_drive_t structure.
851 */
852static struct ide_tape_obj * idetape_devs[MAX_HWIFS * MAX_DRIVES];
853
854#define ide_tape_f(file) ((file)->private_data)
855
856static struct ide_tape_obj *ide_tape_chrdev_get(unsigned int i)
857{
858	struct ide_tape_obj *tape = NULL;
859
860	mutex_lock(&idetape_ref_mutex);
861	tape = idetape_devs[i];
862	if (tape)
863		kref_get(&tape->kref);
864	mutex_unlock(&idetape_ref_mutex);
865	return tape;
866}
867
868/*
869 *      Function declarations
870 *
871 */
872static int idetape_chrdev_release (struct inode *inode, struct file *filp);
873static void idetape_write_release (ide_drive_t *drive, unsigned int minor);
874
875/*
876 * Too bad. The drive wants to send us data which we are not ready to accept.
877 * Just throw it away.
878 */
879static void idetape_discard_data (ide_drive_t *drive, unsigned int bcount)
880{
881	while (bcount--)
882		(void) HWIF(drive)->INB(IDE_DATA_REG);
883}
884
885static void idetape_input_buffers (ide_drive_t *drive, idetape_pc_t *pc, unsigned int bcount)
886{
887	struct idetape_bh *bh = pc->bh;
888	int count;
889
890	while (bcount) {
891#if IDETAPE_DEBUG_BUGS
892		if (bh == NULL) {
893			printk(KERN_ERR "ide-tape: bh == NULL in "
894				"idetape_input_buffers\n");
895			idetape_discard_data(drive, bcount);
896			return;
897		}
898#endif /* IDETAPE_DEBUG_BUGS */
899		count = min((unsigned int)(bh->b_size - atomic_read(&bh->b_count)), bcount);
900		HWIF(drive)->atapi_input_bytes(drive, bh->b_data + atomic_read(&bh->b_count), count);
901		bcount -= count;
902		atomic_add(count, &bh->b_count);
903		if (atomic_read(&bh->b_count) == bh->b_size) {
904			bh = bh->b_reqnext;
905			if (bh)
906				atomic_set(&bh->b_count, 0);
907		}
908	}
909	pc->bh = bh;
910}
911
912static void idetape_output_buffers (ide_drive_t *drive, idetape_pc_t *pc, unsigned int bcount)
913{
914	struct idetape_bh *bh = pc->bh;
915	int count;
916
917	while (bcount) {
918#if IDETAPE_DEBUG_BUGS
919		if (bh == NULL) {
920			printk(KERN_ERR "ide-tape: bh == NULL in "
921				"idetape_output_buffers\n");
922			return;
923		}
924#endif /* IDETAPE_DEBUG_BUGS */
925		count = min((unsigned int)pc->b_count, (unsigned int)bcount);
926		HWIF(drive)->atapi_output_bytes(drive, pc->b_data, count);
927		bcount -= count;
928		pc->b_data += count;
929		pc->b_count -= count;
930		if (!pc->b_count) {
931			pc->bh = bh = bh->b_reqnext;
932			if (bh) {
933				pc->b_data = bh->b_data;
934				pc->b_count = atomic_read(&bh->b_count);
935			}
936		}
937	}
938}
939
940static void idetape_update_buffers (idetape_pc_t *pc)
941{
942	struct idetape_bh *bh = pc->bh;
943	int count;
944	unsigned int bcount = pc->actually_transferred;
945
946	if (test_bit(PC_WRITING, &pc->flags))
947		return;
948	while (bcount) {
949#if IDETAPE_DEBUG_BUGS
950		if (bh == NULL) {
951			printk(KERN_ERR "ide-tape: bh == NULL in "
952				"idetape_update_buffers\n");
953			return;
954		}
955#endif /* IDETAPE_DEBUG_BUGS */
956		count = min((unsigned int)bh->b_size, (unsigned int)bcount);
957		atomic_set(&bh->b_count, count);
958		if (atomic_read(&bh->b_count) == bh->b_size)
959			bh = bh->b_reqnext;
960		bcount -= count;
961	}
962	pc->bh = bh;
963}
964
965/*
966 *	idetape_next_pc_storage returns a pointer to a place in which we can
967 *	safely store a packet command, even though we intend to leave the
968 *	driver. A storage space for a maximum of IDETAPE_PC_STACK packet
969 *	commands is allocated at initialization time.
970 */
971static idetape_pc_t *idetape_next_pc_storage (ide_drive_t *drive)
972{
973	idetape_tape_t *tape = drive->driver_data;
974
975#if IDETAPE_DEBUG_LOG
976	if (tape->debug_level >= 5)
977		printk(KERN_INFO "ide-tape: pc_stack_index=%d\n",
978			tape->pc_stack_index);
979#endif /* IDETAPE_DEBUG_LOG */
980	if (tape->pc_stack_index == IDETAPE_PC_STACK)
981		tape->pc_stack_index=0;
982	return (&tape->pc_stack[tape->pc_stack_index++]);
983}
984
985/*
986 *	idetape_next_rq_storage is used along with idetape_next_pc_storage.
987 *	Since we queue packet commands in the request queue, we need to
988 *	allocate a request, along with the allocation of a packet command.
989 */
990
991/**************************************************************
992 *                                                            *
993 *  This should get fixed to use kmalloc(.., GFP_ATOMIC)      *
994 *  followed later on by kfree().   -ml                       *
995 *                                                            *
996 **************************************************************/
997
998static struct request *idetape_next_rq_storage (ide_drive_t *drive)
999{
1000	idetape_tape_t *tape = drive->driver_data;
1001
1002#if IDETAPE_DEBUG_LOG
1003	if (tape->debug_level >= 5)
1004		printk(KERN_INFO "ide-tape: rq_stack_index=%d\n",
1005			tape->rq_stack_index);
1006#endif /* IDETAPE_DEBUG_LOG */
1007	if (tape->rq_stack_index == IDETAPE_PC_STACK)
1008		tape->rq_stack_index=0;
1009	return (&tape->rq_stack[tape->rq_stack_index++]);
1010}
1011
1012/*
1013 *	idetape_init_pc initializes a packet command.
1014 */
1015static void idetape_init_pc (idetape_pc_t *pc)
1016{
1017	memset(pc->c, 0, 12);
1018	pc->retries = 0;
1019	pc->flags = 0;
1020	pc->request_transfer = 0;
1021	pc->buffer = pc->pc_buffer;
1022	pc->buffer_size = IDETAPE_PC_BUFFER_SIZE;
1023	pc->bh = NULL;
1024	pc->b_data = NULL;
1025}
1026
1027/*
1028 *	idetape_analyze_error is called on each failed packet command retry
1029 *	to analyze the request sense. We currently do not utilize this
1030 *	information.
1031 */
1032static void idetape_analyze_error (ide_drive_t *drive, idetape_request_sense_result_t *result)
1033{
1034	idetape_tape_t *tape = drive->driver_data;
1035	idetape_pc_t *pc = tape->failed_pc;
1036
1037	tape->sense     = *result;
1038	tape->sense_key = result->sense_key;
1039	tape->asc       = result->asc;
1040	tape->ascq      = result->ascq;
1041#if IDETAPE_DEBUG_LOG
1042	/*
1043	 *	Without debugging, we only log an error if we decided to
1044	 *	give up retrying.
1045	 */
1046	if (tape->debug_level >= 1)
1047		printk(KERN_INFO "ide-tape: pc = %x, sense key = %x, "
1048			"asc = %x, ascq = %x\n",
1049			pc->c[0], result->sense_key,
1050			result->asc, result->ascq);
1051#endif /* IDETAPE_DEBUG_LOG */
1052
1053	/*
1054	 *	Correct pc->actually_transferred by asking the tape.
1055	 */
1056	if (test_bit(PC_DMA_ERROR, &pc->flags)) {
1057		pc->actually_transferred = pc->request_transfer - tape->tape_block_size * ntohl(get_unaligned(&result->information));
1058		idetape_update_buffers(pc);
1059	}
1060
1061	/*
1062	 * If error was the result of a zero-length read or write command,
1063	 * with sense key=5, asc=0x22, ascq=0, let it slide.  Some drives
1064	 * (i.e. Seagate STT3401A Travan) don't support 0-length read/writes.
1065	 */
1066	if ((pc->c[0] == IDETAPE_READ_CMD || pc->c[0] == IDETAPE_WRITE_CMD)
1067	    && pc->c[4] == 0 && pc->c[3] == 0 && pc->c[2] == 0) { /* length==0 */
1068		if (result->sense_key == 5) {
1069			/* don't report an error, everything's ok */
1070			pc->error = 0;
1071			/* don't retry read/write */
1072			set_bit(PC_ABORT, &pc->flags);
1073		}
1074	}
1075	if (pc->c[0] == IDETAPE_READ_CMD && result->filemark) {
1076		pc->error = IDETAPE_ERROR_FILEMARK;
1077		set_bit(PC_ABORT, &pc->flags);
1078	}
1079	if (pc->c[0] == IDETAPE_WRITE_CMD) {
1080		if (result->eom ||
1081		    (result->sense_key == 0xd && result->asc == 0x0 &&
1082		     result->ascq == 0x2)) {
1083			pc->error = IDETAPE_ERROR_EOD;
1084			set_bit(PC_ABORT, &pc->flags);
1085		}
1086	}
1087	if (pc->c[0] == IDETAPE_READ_CMD || pc->c[0] == IDETAPE_WRITE_CMD) {
1088		if (result->sense_key == 8) {
1089			pc->error = IDETAPE_ERROR_EOD;
1090			set_bit(PC_ABORT, &pc->flags);
1091		}
1092		if (!test_bit(PC_ABORT, &pc->flags) &&
1093		    pc->actually_transferred)
1094			pc->retries = IDETAPE_MAX_PC_RETRIES + 1;
1095	}
1096}
1097
1098/*
1099 * idetape_active_next_stage will declare the next stage as "active".
1100 */
1101static void idetape_active_next_stage (ide_drive_t *drive)
1102{
1103	idetape_tape_t *tape = drive->driver_data;
1104	idetape_stage_t *stage = tape->next_stage;
1105	struct request *rq = &stage->rq;
1106
1107#if IDETAPE_DEBUG_LOG
1108	if (tape->debug_level >= 4)
1109		printk(KERN_INFO "ide-tape: Reached idetape_active_next_stage\n");
1110#endif /* IDETAPE_DEBUG_LOG */
1111#if IDETAPE_DEBUG_BUGS
1112	if (stage == NULL) {
1113		printk(KERN_ERR "ide-tape: bug: Trying to activate a non existing stage\n");
1114		return;
1115	}
1116#endif /* IDETAPE_DEBUG_BUGS */
1117
1118	rq->rq_disk = tape->disk;
1119	rq->buffer = NULL;
1120	rq->special = (void *)stage->bh;
1121	tape->active_data_request = rq;
1122	tape->active_stage = stage;
1123	tape->next_stage = stage->next;
1124}
1125
1126/*
1127 *	idetape_increase_max_pipeline_stages is a part of the feedback
1128 *	loop which tries to find the optimum number of stages. In the
1129 *	feedback loop, we are starting from a minimum maximum number of
1130 *	stages, and if we sense that the pipeline is empty, we try to
1131 *	increase it, until we reach the user compile time memory limit.
1132 */
1133static void idetape_increase_max_pipeline_stages (ide_drive_t *drive)
1134{
1135	idetape_tape_t *tape = drive->driver_data;
1136	int increase = (tape->max_pipeline - tape->min_pipeline) / 10;
1137
1138#if IDETAPE_DEBUG_LOG
1139	if (tape->debug_level >= 4)
1140		printk (KERN_INFO "ide-tape: Reached idetape_increase_max_pipeline_stages\n");
1141#endif /* IDETAPE_DEBUG_LOG */
1142
1143	tape->max_stages += max(increase, 1);
1144	tape->max_stages = max(tape->max_stages, tape->min_pipeline);
1145	tape->max_stages = min(tape->max_stages, tape->max_pipeline);
1146}
1147
1148/*
1149 *	idetape_kfree_stage calls kfree to completely free a stage, along with
1150 *	its related buffers.
1151 */
1152static void __idetape_kfree_stage (idetape_stage_t *stage)
1153{
1154	struct idetape_bh *prev_bh, *bh = stage->bh;
1155	int size;
1156
1157	while (bh != NULL) {
1158		if (bh->b_data != NULL) {
1159			size = (int) bh->b_size;
1160			while (size > 0) {
1161				free_page((unsigned long) bh->b_data);
1162				size -= PAGE_SIZE;
1163				bh->b_data += PAGE_SIZE;
1164			}
1165		}
1166		prev_bh = bh;
1167		bh = bh->b_reqnext;
1168		kfree(prev_bh);
1169	}
1170	kfree(stage);
1171}
1172
1173static void idetape_kfree_stage (idetape_tape_t *tape, idetape_stage_t *stage)
1174{
1175	__idetape_kfree_stage(stage);
1176}
1177
1178/*
1179 *	idetape_remove_stage_head removes tape->first_stage from the pipeline.
1180 *	The caller should avoid race conditions.
1181 */
1182static void idetape_remove_stage_head (ide_drive_t *drive)
1183{
1184	idetape_tape_t *tape = drive->driver_data;
1185	idetape_stage_t *stage;
1186
1187#if IDETAPE_DEBUG_LOG
1188	if (tape->debug_level >= 4)
1189		printk(KERN_INFO "ide-tape: Reached idetape_remove_stage_head\n");
1190#endif /* IDETAPE_DEBUG_LOG */
1191#if IDETAPE_DEBUG_BUGS
1192	if (tape->first_stage == NULL) {
1193		printk(KERN_ERR "ide-tape: bug: tape->first_stage is NULL\n");
1194		return;
1195	}
1196	if (tape->active_stage == tape->first_stage) {
1197		printk(KERN_ERR "ide-tape: bug: Trying to free our active pipeline stage\n");
1198		return;
1199	}
1200#endif /* IDETAPE_DEBUG_BUGS */
1201	stage = tape->first_stage;
1202	tape->first_stage = stage->next;
1203	idetape_kfree_stage(tape, stage);
1204	tape->nr_stages--;
1205	if (tape->first_stage == NULL) {
1206		tape->last_stage = NULL;
1207#if IDETAPE_DEBUG_BUGS
1208		if (tape->next_stage != NULL)
1209			printk(KERN_ERR "ide-tape: bug: tape->next_stage != NULL\n");
1210		if (tape->nr_stages)
1211			printk(KERN_ERR "ide-tape: bug: nr_stages should be 0 now\n");
1212#endif /* IDETAPE_DEBUG_BUGS */
1213	}
1214}
1215
1216/*
1217 * This will free all the pipeline stages starting from new_last_stage->next
1218 * to the end of the list, and point tape->last_stage to new_last_stage.
1219 */
1220static void idetape_abort_pipeline(ide_drive_t *drive,
1221				   idetape_stage_t *new_last_stage)
1222{
1223	idetape_tape_t *tape = drive->driver_data;
1224	idetape_stage_t *stage = new_last_stage->next;
1225	idetape_stage_t *nstage;
1226
1227#if IDETAPE_DEBUG_LOG
1228	if (tape->debug_level >= 4)
1229		printk(KERN_INFO "ide-tape: %s: idetape_abort_pipeline called\n", tape->name);
1230#endif
1231	while (stage) {
1232		nstage = stage->next;
1233		idetape_kfree_stage(tape, stage);
1234		--tape->nr_stages;
1235		--tape->nr_pending_stages;
1236		stage = nstage;
1237	}
1238	if (new_last_stage)
1239		new_last_stage->next = NULL;
1240	tape->last_stage = new_last_stage;
1241	tape->next_stage = NULL;
1242}
1243
1244/*
1245 *	idetape_end_request is used to finish servicing a request, and to
1246 *	insert a pending pipeline request into the main device queue.
1247 */
1248static int idetape_end_request(ide_drive_t *drive, int uptodate, int nr_sects)
1249{
1250	struct request *rq = HWGROUP(drive)->rq;
1251	idetape_tape_t *tape = drive->driver_data;
1252	unsigned long flags;
1253	int error;
1254	int remove_stage = 0;
1255	idetape_stage_t *active_stage;
1256
1257#if IDETAPE_DEBUG_LOG
1258        if (tape->debug_level >= 4)
1259	printk(KERN_INFO "ide-tape: Reached idetape_end_request\n");
1260#endif /* IDETAPE_DEBUG_LOG */
1261
1262	switch (uptodate) {
1263		case 0:	error = IDETAPE_ERROR_GENERAL; break;
1264		case 1: error = 0; break;
1265		default: error = uptodate;
1266	}
1267	rq->errors = error;
1268	if (error)
1269		tape->failed_pc = NULL;
1270
1271	if (!blk_special_request(rq)) {
1272		ide_end_request(drive, uptodate, nr_sects);
1273		return 0;
1274	}
1275
1276	spin_lock_irqsave(&tape->spinlock, flags);
1277
1278	/* The request was a pipelined data transfer request */
1279	if (tape->active_data_request == rq) {
1280		active_stage = tape->active_stage;
1281		tape->active_stage = NULL;
1282		tape->active_data_request = NULL;
1283		tape->nr_pending_stages--;
1284		if (rq->cmd[0] & REQ_IDETAPE_WRITE) {
1285			remove_stage = 1;
1286			if (error) {
1287				set_bit(IDETAPE_PIPELINE_ERROR, &tape->flags);
1288				if (error == IDETAPE_ERROR_EOD)
1289					idetape_abort_pipeline(drive, active_stage);
1290			}
1291		} else if (rq->cmd[0] & REQ_IDETAPE_READ) {
1292			if (error == IDETAPE_ERROR_EOD) {
1293				set_bit(IDETAPE_PIPELINE_ERROR, &tape->flags);
1294				idetape_abort_pipeline(drive, active_stage);
1295			}
1296		}
1297		if (tape->next_stage != NULL) {
1298			idetape_active_next_stage(drive);
1299
1300			/*
1301			 * Insert the next request into the request queue.
1302			 */
1303			(void) ide_do_drive_cmd(drive, tape->active_data_request, ide_end);
1304		} else if (!error) {
1305				idetape_increase_max_pipeline_stages(drive);
1306		}
1307	}
1308	ide_end_drive_cmd(drive, 0, 0);
1309//	blkdev_dequeue_request(rq);
1310//	drive->rq = NULL;
1311//	end_that_request_last(rq);
1312
1313	if (remove_stage)
1314		idetape_remove_stage_head(drive);
1315	if (tape->active_data_request == NULL)
1316		clear_bit(IDETAPE_PIPELINE_ACTIVE, &tape->flags);
1317	spin_unlock_irqrestore(&tape->spinlock, flags);
1318	return 0;
1319}
1320
1321static ide_startstop_t idetape_request_sense_callback (ide_drive_t *drive)
1322{
1323	idetape_tape_t *tape = drive->driver_data;
1324
1325#if IDETAPE_DEBUG_LOG
1326	if (tape->debug_level >= 4)
1327		printk(KERN_INFO "ide-tape: Reached idetape_request_sense_callback\n");
1328#endif /* IDETAPE_DEBUG_LOG */
1329	if (!tape->pc->error) {
1330		idetape_analyze_error(drive, (idetape_request_sense_result_t *) tape->pc->buffer);
1331		idetape_end_request(drive, 1, 0);
1332	} else {
1333		printk(KERN_ERR "ide-tape: Error in REQUEST SENSE itself - Aborting request!\n");
1334		idetape_end_request(drive, 0, 0);
1335	}
1336	return ide_stopped;
1337}
1338
1339static void idetape_create_request_sense_cmd (idetape_pc_t *pc)
1340{
1341	idetape_init_pc(pc);
1342	pc->c[0] = IDETAPE_REQUEST_SENSE_CMD;
1343	pc->c[4] = 20;
1344	pc->request_transfer = 20;
1345	pc->callback = &idetape_request_sense_callback;
1346}
1347
1348static void idetape_init_rq(struct request *rq, u8 cmd)
1349{
1350	memset(rq, 0, sizeof(*rq));
1351	rq->cmd_type = REQ_TYPE_SPECIAL;
1352	rq->cmd[0] = cmd;
1353}
1354
1355/*
1356 *	idetape_queue_pc_head generates a new packet command request in front
1357 *	of the request queue, before the current request, so that it will be
1358 *	processed immediately, on the next pass through the driver.
1359 *
1360 *	idetape_queue_pc_head is called from the request handling part of
1361 *	the driver (the "bottom" part). Safe storage for the request should
1362 *	be allocated with idetape_next_pc_storage and idetape_next_rq_storage
1363 *	before calling idetape_queue_pc_head.
1364 *
1365 *	Memory for those requests is pre-allocated at initialization time, and
1366 *	is limited to IDETAPE_PC_STACK requests. We assume that we have enough
1367 *	space for the maximum possible number of inter-dependent packet commands.
1368 *
1369 *	The higher level of the driver - The ioctl handler and the character
1370 *	device handling functions should queue request to the lower level part
1371 *	and wait for their completion using idetape_queue_pc_tail or
1372 *	idetape_queue_rw_tail.
1373 */
1374static void idetape_queue_pc_head (ide_drive_t *drive, idetape_pc_t *pc,struct request *rq)
1375{
1376	struct ide_tape_obj *tape = drive->driver_data;
1377
1378	idetape_init_rq(rq, REQ_IDETAPE_PC1);
1379	rq->buffer = (char *) pc;
1380	rq->rq_disk = tape->disk;
1381	(void) ide_do_drive_cmd(drive, rq, ide_preempt);
1382}
1383
1384/*
1385 *	idetape_retry_pc is called when an error was detected during the
1386 *	last packet command. We queue a request sense packet command in
1387 *	the head of the request list.
1388 */
1389static ide_startstop_t idetape_retry_pc (ide_drive_t *drive)
1390{
1391	idetape_tape_t *tape = drive->driver_data;
1392	idetape_pc_t *pc;
1393	struct request *rq;
1394
1395	(void)drive->hwif->INB(IDE_ERROR_REG);
1396	pc = idetape_next_pc_storage(drive);
1397	rq = idetape_next_rq_storage(drive);
1398	idetape_create_request_sense_cmd(pc);
1399	set_bit(IDETAPE_IGNORE_DSC, &tape->flags);
1400	idetape_queue_pc_head(drive, pc, rq);
1401	return ide_stopped;
1402}
1403
1404/*
1405 *	idetape_postpone_request postpones the current request so that
1406 *	ide.c will be able to service requests from another device on
1407 *	the same hwgroup while we are polling for DSC.
1408 */
1409static void idetape_postpone_request (ide_drive_t *drive)
1410{
1411	idetape_tape_t *tape = drive->driver_data;
1412
1413#if IDETAPE_DEBUG_LOG
1414	if (tape->debug_level >= 4)
1415		printk(KERN_INFO "ide-tape: idetape_postpone_request\n");
1416#endif
1417	tape->postponed_rq = HWGROUP(drive)->rq;
1418	ide_stall_queue(drive, tape->dsc_polling_frequency);
1419}
1420
1421/*
1422 *	idetape_pc_intr is the usual interrupt handler which will be called
1423 *	during a packet command. We will transfer some of the data (as
1424 *	requested by the drive) and will re-point interrupt handler to us.
1425 *	When data transfer is finished, we will act according to the
1426 *	algorithm described before idetape_issue_packet_command.
1427 *
1428 */
1429static ide_startstop_t idetape_pc_intr (ide_drive_t *drive)
1430{
1431	ide_hwif_t *hwif = drive->hwif;
1432	idetape_tape_t *tape = drive->driver_data;
1433	idetape_pc_t *pc = tape->pc;
1434	unsigned int temp;
1435#if SIMULATE_ERRORS
1436	static int error_sim_count = 0;
1437#endif
1438	u16 bcount;
1439	u8 stat, ireason;
1440
1441#if IDETAPE_DEBUG_LOG
1442	if (tape->debug_level >= 4)
1443		printk(KERN_INFO "ide-tape: Reached idetape_pc_intr "
1444				"interrupt handler\n");
1445#endif /* IDETAPE_DEBUG_LOG */
1446
1447	/* Clear the interrupt */
1448	stat = hwif->INB(IDE_STATUS_REG);
1449
1450	if (test_bit(PC_DMA_IN_PROGRESS, &pc->flags)) {
1451		if (hwif->ide_dma_end(drive) || (stat & ERR_STAT)) {
1452			/*
1453			 * A DMA error is sometimes expected. For example,
1454			 * if the tape is crossing a filemark during a
1455			 * READ command, it will issue an irq and position
1456			 * itself before the filemark, so that only a partial
1457			 * data transfer will occur (which causes the DMA
1458			 * error). In that case, we will later ask the tape
1459			 * how much bytes of the original request were
1460			 * actually transferred (we can't receive that
1461			 * information from the DMA engine on most chipsets).
1462			 */
1463
1464			/*
1465			 * On the contrary, a DMA error is never expected;
1466			 * it usually indicates a hardware error or abort.
1467			 * If the tape crosses a filemark during a READ
1468			 * command, it will issue an irq and position itself
1469			 * after the filemark (not before). Only a partial
1470			 * data transfer will occur, but no DMA error.
1471			 * (AS, 19 Apr 2001)
1472			 */
1473			set_bit(PC_DMA_ERROR, &pc->flags);
1474		} else {
1475			pc->actually_transferred = pc->request_transfer;
1476			idetape_update_buffers(pc);
1477		}
1478#if IDETAPE_DEBUG_LOG
1479		if (tape->debug_level >= 4)
1480			printk(KERN_INFO "ide-tape: DMA finished\n");
1481#endif /* IDETAPE_DEBUG_LOG */
1482	}
1483
1484	/* No more interrupts */
1485	if ((stat & DRQ_STAT) == 0) {
1486#if IDETAPE_DEBUG_LOG
1487		if (tape->debug_level >= 2)
1488			printk(KERN_INFO "ide-tape: Packet command completed, %d bytes transferred\n", pc->actually_transferred);
1489#endif /* IDETAPE_DEBUG_LOG */
1490		clear_bit(PC_DMA_IN_PROGRESS, &pc->flags);
1491
1492		local_irq_enable();
1493
1494#if SIMULATE_ERRORS
1495		if ((pc->c[0] == IDETAPE_WRITE_CMD ||
1496		     pc->c[0] == IDETAPE_READ_CMD) &&
1497		    (++error_sim_count % 100) == 0) {
1498			printk(KERN_INFO "ide-tape: %s: simulating error\n",
1499				tape->name);
1500			stat |= ERR_STAT;
1501		}
1502#endif
1503		if ((stat & ERR_STAT) && pc->c[0] == IDETAPE_REQUEST_SENSE_CMD)
1504			stat &= ~ERR_STAT;
1505		if ((stat & ERR_STAT) || test_bit(PC_DMA_ERROR, &pc->flags)) {
1506			/* Error detected */
1507#if IDETAPE_DEBUG_LOG
1508			if (tape->debug_level >= 1)
1509				printk(KERN_INFO "ide-tape: %s: I/O error\n",
1510					tape->name);
1511#endif /* IDETAPE_DEBUG_LOG */
1512			if (pc->c[0] == IDETAPE_REQUEST_SENSE_CMD) {
1513				printk(KERN_ERR "ide-tape: I/O error in request sense command\n");
1514				return ide_do_reset(drive);
1515			}
1516#if IDETAPE_DEBUG_LOG
1517			if (tape->debug_level >= 1)
1518				printk(KERN_INFO "ide-tape: [cmd %x]: check condition\n", pc->c[0]);
1519#endif
1520			/* Retry operation */
1521			return idetape_retry_pc(drive);
1522		}
1523		pc->error = 0;
1524		if (test_bit(PC_WAIT_FOR_DSC, &pc->flags) &&
1525		    (stat & SEEK_STAT) == 0) {
1526			/* Media access command */
1527			tape->dsc_polling_start = jiffies;
1528			tape->dsc_polling_frequency = IDETAPE_DSC_MA_FAST;
1529			tape->dsc_timeout = jiffies + IDETAPE_DSC_MA_TIMEOUT;
1530			/* Allow ide.c to handle other requests */
1531			idetape_postpone_request(drive);
1532			return ide_stopped;
1533		}
1534		if (tape->failed_pc == pc)
1535			tape->failed_pc = NULL;
1536		/* Command finished - Call the callback function */
1537		return pc->callback(drive);
1538	}
1539	if (test_and_clear_bit(PC_DMA_IN_PROGRESS, &pc->flags)) {
1540		printk(KERN_ERR "ide-tape: The tape wants to issue more "
1541				"interrupts in DMA mode\n");
1542		printk(KERN_ERR "ide-tape: DMA disabled, reverting to PIO\n");
1543		ide_dma_off(drive);
1544		return ide_do_reset(drive);
1545	}
1546	/* Get the number of bytes to transfer on this interrupt. */
1547	bcount = (hwif->INB(IDE_BCOUNTH_REG) << 8) |
1548		  hwif->INB(IDE_BCOUNTL_REG);
1549
1550	ireason = hwif->INB(IDE_IREASON_REG);
1551
1552	if (ireason & CD) {
1553		printk(KERN_ERR "ide-tape: CoD != 0 in idetape_pc_intr\n");
1554		return ide_do_reset(drive);
1555	}
1556	if (((ireason & IO) == IO) == test_bit(PC_WRITING, &pc->flags)) {
1557		/* Hopefully, we will never get here */
1558		printk(KERN_ERR "ide-tape: We wanted to %s, ",
1559				(ireason & IO) ? "Write" : "Read");
1560		printk(KERN_ERR "ide-tape: but the tape wants us to %s !\n",
1561				(ireason & IO) ? "Read" : "Write");
1562		return ide_do_reset(drive);
1563	}
1564	if (!test_bit(PC_WRITING, &pc->flags)) {
1565		/* Reading - Check that we have enough space */
1566		temp = pc->actually_transferred + bcount;
1567		if (temp > pc->request_transfer) {
1568			if (temp > pc->buffer_size) {
1569				printk(KERN_ERR "ide-tape: The tape wants to send us more data than expected - discarding data\n");
1570				idetape_discard_data(drive, bcount);
1571				ide_set_handler(drive, &idetape_pc_intr, IDETAPE_WAIT_CMD, NULL);
1572				return ide_started;
1573			}
1574#if IDETAPE_DEBUG_LOG
1575			if (tape->debug_level >= 2)
1576				printk(KERN_NOTICE "ide-tape: The tape wants to send us more data than expected - allowing transfer\n");
1577#endif /* IDETAPE_DEBUG_LOG */
1578		}
1579	}
1580	if (test_bit(PC_WRITING, &pc->flags)) {
1581		if (pc->bh != NULL)
1582			idetape_output_buffers(drive, pc, bcount);
1583		else
1584			/* Write the current buffer */
1585			hwif->atapi_output_bytes(drive, pc->current_position,
1586						 bcount);
1587	} else {
1588		if (pc->bh != NULL)
1589			idetape_input_buffers(drive, pc, bcount);
1590		else
1591			/* Read the current buffer */
1592			hwif->atapi_input_bytes(drive, pc->current_position,
1593						bcount);
1594	}
1595	/* Update the current position */
1596	pc->actually_transferred += bcount;
1597	pc->current_position += bcount;
1598#if IDETAPE_DEBUG_LOG
1599	if (tape->debug_level >= 2)
1600		printk(KERN_INFO "ide-tape: [cmd %x] transferred %d bytes "
1601				 "on that interrupt\n", pc->c[0], bcount);
1602#endif
1603	/* And set the interrupt handler again */
1604	ide_set_handler(drive, &idetape_pc_intr, IDETAPE_WAIT_CMD, NULL);
1605	return ide_started;
1606}
1607
1608/*
1609 *	Packet Command Interface
1610 *
1611 *	The current Packet Command is available in tape->pc, and will not
1612 *	change until we finish handling it. Each packet command is associated
1613 *	with a callback function that will be called when the command is
1614 *	finished.
1615 *
1616 *	The handling will be done in three stages:
1617 *
1618 *	1.	idetape_issue_packet_command will send the packet command to the
1619 *		drive, and will set the interrupt handler to idetape_pc_intr.
1620 *
1621 *	2.	On each interrupt, idetape_pc_intr will be called. This step
1622 *		will be repeated until the device signals us that no more
1623 *		interrupts will be issued.
1624 *
1625 *	3.	ATAPI Tape media access commands have immediate status with a
1626 *		delayed process. In case of a successful initiation of a
1627 *		media access packet command, the DSC bit will be set when the
1628 *		actual execution of the command is finished.
1629 *		Since the tape drive will not issue an interrupt, we have to
1630 *		poll for this event. In this case, we define the request as
1631 *		"low priority request" by setting rq_status to
1632 *		IDETAPE_RQ_POSTPONED, 	set a timer to poll for DSC and exit
1633 *		the driver.
1634 *
1635 *		ide.c will then give higher priority to requests which
1636 *		originate from the other device, until will change rq_status
1637 *		to RQ_ACTIVE.
1638 *
1639 *	4.	When the packet command is finished, it will be checked for errors.
1640 *
1641 *	5.	In case an error was found, we queue a request sense packet
1642 *		command in front of the request queue and retry the operation
1643 *		up to IDETAPE_MAX_PC_RETRIES times.
1644 *
1645 *	6.	In case no error was found, or we decided to give up and not
1646 *		to retry again, the callback function will be called and then
1647 *		we will handle the next request.
1648 *
1649 */
1650static ide_startstop_t idetape_transfer_pc(ide_drive_t *drive)
1651{
1652	ide_hwif_t *hwif = drive->hwif;
1653	idetape_tape_t *tape = drive->driver_data;
1654	idetape_pc_t *pc = tape->pc;
1655	int retries = 100;
1656	ide_startstop_t startstop;
1657	u8 ireason;
1658
1659	if (ide_wait_stat(&startstop,drive,DRQ_STAT,BUSY_STAT,WAIT_READY)) {
1660		printk(KERN_ERR "ide-tape: Strange, packet command initiated yet DRQ isn't asserted\n");
1661		return startstop;
1662	}
1663	ireason = hwif->INB(IDE_IREASON_REG);
1664	while (retries-- && ((ireason & CD) == 0 || (ireason & IO))) {
1665		printk(KERN_ERR "ide-tape: (IO,CoD != (0,1) while issuing "
1666				"a packet command, retrying\n");
1667		udelay(100);
1668		ireason = hwif->INB(IDE_IREASON_REG);
1669		if (retries == 0) {
1670			printk(KERN_ERR "ide-tape: (IO,CoD != (0,1) while "
1671					"issuing a packet command, ignoring\n");
1672			ireason |= CD;
1673			ireason &= ~IO;
1674		}
1675	}
1676	if ((ireason & CD) == 0 || (ireason & IO)) {
1677		printk(KERN_ERR "ide-tape: (IO,CoD) != (0,1) while issuing "
1678				"a packet command\n");
1679		return ide_do_reset(drive);
1680	}
1681	/* Set the interrupt routine */
1682	ide_set_handler(drive, &idetape_pc_intr, IDETAPE_WAIT_CMD, NULL);
1683#ifdef CONFIG_BLK_DEV_IDEDMA
1684	/* Begin DMA, if necessary */
1685	if (test_bit(PC_DMA_IN_PROGRESS, &pc->flags))
1686		hwif->dma_start(drive);
1687#endif
1688	/* Send the actual packet */
1689	HWIF(drive)->atapi_output_bytes(drive, pc->c, 12);
1690	return ide_started;
1691}
1692
1693static ide_startstop_t idetape_issue_packet_command (ide_drive_t *drive, idetape_pc_t *pc)
1694{
1695	ide_hwif_t *hwif = drive->hwif;
1696	idetape_tape_t *tape = drive->driver_data;
1697	int dma_ok = 0;
1698	u16 bcount;
1699
1700#if IDETAPE_DEBUG_BUGS
1701	if (tape->pc->c[0] == IDETAPE_REQUEST_SENSE_CMD &&
1702	    pc->c[0] == IDETAPE_REQUEST_SENSE_CMD) {
1703		printk(KERN_ERR "ide-tape: possible ide-tape.c bug - "
1704			"Two request sense in serial were issued\n");
1705	}
1706#endif /* IDETAPE_DEBUG_BUGS */
1707
1708	if (tape->failed_pc == NULL && pc->c[0] != IDETAPE_REQUEST_SENSE_CMD)
1709		tape->failed_pc = pc;
1710	/* Set the current packet command */
1711	tape->pc = pc;
1712
1713	if (pc->retries > IDETAPE_MAX_PC_RETRIES ||
1714	    test_bit(PC_ABORT, &pc->flags)) {
1715		/*
1716		 *	We will "abort" retrying a packet command in case
1717		 *	a legitimate error code was received (crossing a
1718		 *	filemark, or end of the media, for example).
1719		 */
1720		if (!test_bit(PC_ABORT, &pc->flags)) {
1721			if (!(pc->c[0] == IDETAPE_TEST_UNIT_READY_CMD &&
1722			      tape->sense_key == 2 && tape->asc == 4 &&
1723			     (tape->ascq == 1 || tape->ascq == 8))) {
1724				printk(KERN_ERR "ide-tape: %s: I/O error, "
1725						"pc = %2x, key = %2x, "
1726						"asc = %2x, ascq = %2x\n",
1727						tape->name, pc->c[0],
1728						tape->sense_key, tape->asc,
1729						tape->ascq);
1730			}
1731			/* Giving up */
1732			pc->error = IDETAPE_ERROR_GENERAL;
1733		}
1734		tape->failed_pc = NULL;
1735		return pc->callback(drive);
1736	}
1737#if IDETAPE_DEBUG_LOG
1738	if (tape->debug_level >= 2)
1739		printk(KERN_INFO "ide-tape: Retry number - %d, cmd = %02X\n", pc->retries, pc->c[0]);
1740#endif /* IDETAPE_DEBUG_LOG */
1741
1742	pc->retries++;
1743	/* We haven't transferred any data yet */
1744	pc->actually_transferred = 0;
1745	pc->current_position = pc->buffer;
1746	/* Request to transfer the entire buffer at once */
1747	bcount = pc->request_transfer;
1748
1749	if (test_and_clear_bit(PC_DMA_ERROR, &pc->flags)) {
1750		printk(KERN_WARNING "ide-tape: DMA disabled, "
1751				"reverting to PIO\n");
1752		ide_dma_off(drive);
1753	}
1754	if (test_bit(PC_DMA_RECOMMENDED, &pc->flags) && drive->using_dma)
1755		dma_ok = !hwif->dma_setup(drive);
1756
1757	ide_pktcmd_tf_load(drive, IDE_TFLAG_NO_SELECT_MASK |
1758			   IDE_TFLAG_OUT_DEVICE, bcount, dma_ok);
1759
1760	if (dma_ok)			/* Will begin DMA later */
1761		set_bit(PC_DMA_IN_PROGRESS, &pc->flags);
1762	if (test_bit(IDETAPE_DRQ_INTERRUPT, &tape->flags)) {
1763		ide_execute_command(drive, WIN_PACKETCMD, &idetape_transfer_pc,
1764				    IDETAPE_WAIT_CMD, NULL);
1765		return ide_started;
1766	} else {
1767		hwif->OUTB(WIN_PACKETCMD, IDE_COMMAND_REG);
1768		return idetape_transfer_pc(drive);
1769	}
1770}
1771
1772/*
1773 *	General packet command callback function.
1774 */
1775static ide_startstop_t idetape_pc_callback (ide_drive_t *drive)
1776{
1777	idetape_tape_t *tape = drive->driver_data;
1778
1779#if IDETAPE_DEBUG_LOG
1780	if (tape->debug_level >= 4)
1781		printk(KERN_INFO "ide-tape: Reached idetape_pc_callback\n");
1782#endif /* IDETAPE_DEBUG_LOG */
1783
1784	idetape_end_request(drive, tape->pc->error ? 0 : 1, 0);
1785	return ide_stopped;
1786}
1787
1788/*
1789 *	A mode sense command is used to "sense" tape parameters.
1790 */
1791static void idetape_create_mode_sense_cmd (idetape_pc_t *pc, u8 page_code)
1792{
1793	idetape_init_pc(pc);
1794	pc->c[0] = IDETAPE_MODE_SENSE_CMD;
1795	if (page_code != IDETAPE_BLOCK_DESCRIPTOR)
1796		pc->c[1] = 8;	/* DBD = 1 - Don't return block descriptors */
1797	pc->c[2] = page_code;
1798	/*
1799	 * Changed pc->c[3] to 0 (255 will at best return unused info).
1800	 *
1801	 * For SCSI this byte is defined as subpage instead of high byte
1802	 * of length and some IDE drives seem to interpret it this way
1803	 * and return an error when 255 is used.
1804	 */
1805	pc->c[3] = 0;
1806	pc->c[4] = 255;		/* (We will just discard data in that case) */
1807	if (page_code == IDETAPE_BLOCK_DESCRIPTOR)
1808		pc->request_transfer = 12;
1809	else if (page_code == IDETAPE_CAPABILITIES_PAGE)
1810		pc->request_transfer = 24;
1811	else
1812		pc->request_transfer = 50;
1813	pc->callback = &idetape_pc_callback;
1814}
1815
1816static void calculate_speeds(ide_drive_t *drive)
1817{
1818	idetape_tape_t *tape = drive->driver_data;
1819	int full = 125, empty = 75;
1820
1821	if (time_after(jiffies, tape->controlled_pipeline_head_time + 120 * HZ)) {
1822		tape->controlled_previous_pipeline_head = tape->controlled_last_pipeline_head;
1823		tape->controlled_previous_head_time = tape->controlled_pipeline_head_time;
1824		tape->controlled_last_pipeline_head = tape->pipeline_head;
1825		tape->controlled_pipeline_head_time = jiffies;
1826	}
1827	if (time_after(jiffies, tape->controlled_pipeline_head_time + 60 * HZ))
1828		tape->controlled_pipeline_head_speed = (tape->pipeline_head - tape->controlled_last_pipeline_head) * 32 * HZ / (jiffies - tape->controlled_pipeline_head_time);
1829	else if (time_after(jiffies, tape->controlled_previous_head_time))
1830		tape->controlled_pipeline_head_speed = (tape->pipeline_head - tape->controlled_previous_pipeline_head) * 32 * HZ / (jiffies - tape->controlled_previous_head_time);
1831
1832	if (tape->nr_pending_stages < tape->max_stages /*- 1 */) {
1833		/* -1 for read mode error recovery */
1834		if (time_after(jiffies, tape->uncontrolled_previous_head_time + 10 * HZ)) {
1835			tape->uncontrolled_pipeline_head_time = jiffies;
1836			tape->uncontrolled_pipeline_head_speed = (tape->pipeline_head - tape->uncontrolled_previous_pipeline_head) * 32 * HZ / (jiffies - tape->uncontrolled_previous_head_time);
1837		}
1838	} else {
1839		tape->uncontrolled_previous_head_time = jiffies;
1840		tape->uncontrolled_previous_pipeline_head = tape->pipeline_head;
1841		if (time_after(jiffies, tape->uncontrolled_pipeline_head_time + 30 * HZ)) {
1842			tape->uncontrolled_pipeline_head_time = jiffies;
1843		}
1844	}
1845	tape->pipeline_head_speed = max(tape->uncontrolled_pipeline_head_speed, tape->controlled_pipeline_head_speed);
1846	if (tape->speed_control == 0) {
1847		tape->max_insert_speed = 5000;
1848	} else if (tape->speed_control == 1) {
1849		if (tape->nr_pending_stages >= tape->max_stages / 2)
1850			tape->max_insert_speed = tape->pipeline_head_speed +
1851				(1100 - tape->pipeline_head_speed) * 2 * (tape->nr_pending_stages - tape->max_stages / 2) / tape->max_stages;
1852		else
1853			tape->max_insert_speed = 500 +
1854				(tape->pipeline_head_speed - 500) * 2 * tape->nr_pending_stages / tape->max_stages;
1855		if (tape->nr_pending_stages >= tape->max_stages * 99 / 100)
1856			tape->max_insert_speed = 5000;
1857	} else if (tape->speed_control == 2) {
1858		tape->max_insert_speed = tape->pipeline_head_speed * empty / 100 +
1859			(tape->pipeline_head_speed * full / 100 - tape->pipeline_head_speed * empty / 100) * tape->nr_pending_stages / tape->max_stages;
1860	} else
1861		tape->max_insert_speed = tape->speed_control;
1862	tape->max_insert_speed = max(tape->max_insert_speed, 500);
1863}
1864
1865static ide_startstop_t idetape_media_access_finished (ide_drive_t *drive)
1866{
1867	idetape_tape_t *tape = drive->driver_data;
1868	idetape_pc_t *pc = tape->pc;
1869	u8 stat;
1870
1871	stat = drive->hwif->INB(IDE_STATUS_REG);
1872	if (stat & SEEK_STAT) {
1873		if (stat & ERR_STAT) {
1874			/* Error detected */
1875			if (pc->c[0] != IDETAPE_TEST_UNIT_READY_CMD)
1876				printk(KERN_ERR "ide-tape: %s: I/O error, ",
1877						tape->name);
1878			/* Retry operation */
1879			return idetape_retry_pc(drive);
1880		}
1881		pc->error = 0;
1882		if (tape->failed_pc == pc)
1883			tape->failed_pc = NULL;
1884	} else {
1885		pc->error = IDETAPE_ERROR_GENERAL;
1886		tape->failed_pc = NULL;
1887	}
1888	return pc->callback(drive);
1889}
1890
1891static ide_startstop_t idetape_rw_callback (ide_drive_t *drive)
1892{
1893	idetape_tape_t *tape = drive->driver_data;
1894	struct request *rq = HWGROUP(drive)->rq;
1895	int blocks = tape->pc->actually_transferred / tape->tape_block_size;
1896
1897	tape->avg_size += blocks * tape->tape_block_size;
1898	tape->insert_size += blocks * tape->tape_block_size;
1899	if (tape->insert_size > 1024 * 1024)
1900		tape->measure_insert_time = 1;
1901	if (tape->measure_insert_time) {
1902		tape->measure_insert_time = 0;
1903		tape->insert_time = jiffies;
1904		tape->insert_size = 0;
1905	}
1906	if (time_after(jiffies, tape->insert_time))
1907		tape->insert_speed = tape->insert_size / 1024 * HZ / (jiffies - tape->insert_time);
1908	if (time_after_eq(jiffies, tape->avg_time + HZ)) {
1909		tape->avg_speed = tape->avg_size * HZ / (jiffies - tape->avg_time) / 1024;
1910		tape->avg_size = 0;
1911		tape->avg_time = jiffies;
1912	}
1913
1914#if IDETAPE_DEBUG_LOG
1915	if (tape->debug_level >= 4)
1916		printk(KERN_INFO "ide-tape: Reached idetape_rw_callback\n");
1917#endif /* IDETAPE_DEBUG_LOG */
1918
1919	tape->first_frame_position += blocks;
1920	rq->current_nr_sectors -= blocks;
1921
1922	if (!tape->pc->error)
1923		idetape_end_request(drive, 1, 0);
1924	else
1925		idetape_end_request(drive, tape->pc->error, 0);
1926	return ide_stopped;
1927}
1928
1929static void idetape_create_read_cmd(idetape_tape_t *tape, idetape_pc_t *pc, unsigned int length, struct idetape_bh *bh)
1930{
1931	idetape_init_pc(pc);
1932	pc->c[0] = IDETAPE_READ_CMD;
1933	put_unaligned(htonl(length), (unsigned int *) &pc->c[1]);
1934	pc->c[1] = 1;
1935	pc->callback = &idetape_rw_callback;
1936	pc->bh = bh;
1937	atomic_set(&bh->b_count, 0);
1938	pc->buffer = NULL;
1939	pc->request_transfer = pc->buffer_size = length * tape->tape_block_size;
1940	if (pc->request_transfer == tape->stage_size)
1941		set_bit(PC_DMA_RECOMMENDED, &pc->flags);
1942}
1943
1944static void idetape_create_read_buffer_cmd(idetape_tape_t *tape, idetape_pc_t *pc, unsigned int length, struct idetape_bh *bh)
1945{
1946	int size = 32768;
1947	struct idetape_bh *p = bh;
1948
1949	idetape_init_pc(pc);
1950	pc->c[0] = IDETAPE_READ_BUFFER_CMD;
1951	pc->c[1] = IDETAPE_RETRIEVE_FAULTY_BLOCK;
1952	pc->c[7] = size >> 8;
1953	pc->c[8] = size & 0xff;
1954	pc->callback = &idetape_pc_callback;
1955	pc->bh = bh;
1956	atomic_set(&bh->b_count, 0);
1957	pc->buffer = NULL;
1958	while (p) {
1959		atomic_set(&p->b_count, 0);
1960		p = p->b_reqnext;
1961	}
1962	pc->request_transfer = pc->buffer_size = size;
1963}
1964
1965static void idetape_create_write_cmd(idetape_tape_t *tape, idetape_pc_t *pc, unsigned int length, struct idetape_bh *bh)
1966{
1967	idetape_init_pc(pc);
1968	pc->c[0] = IDETAPE_WRITE_CMD;
1969	put_unaligned(htonl(length), (unsigned int *) &pc->c[1]);
1970	pc->c[1] = 1;
1971	pc->callback = &idetape_rw_callback;
1972	set_bit(PC_WRITING, &pc->flags);
1973	pc->bh = bh;
1974	pc->b_data = bh->b_data;
1975	pc->b_count = atomic_read(&bh->b_count);
1976	pc->buffer = NULL;
1977	pc->request_transfer = pc->buffer_size = length * tape->tape_block_size;
1978	if (pc->request_transfer == tape->stage_size)
1979		set_bit(PC_DMA_RECOMMENDED, &pc->flags);
1980}
1981
1982/*
1983 * idetape_do_request is our request handling function.
1984 */
1985static ide_startstop_t idetape_do_request(ide_drive_t *drive,
1986					  struct request *rq, sector_t block)
1987{
1988	idetape_tape_t *tape = drive->driver_data;
1989	idetape_pc_t *pc = NULL;
1990	struct request *postponed_rq = tape->postponed_rq;
1991	u8 stat;
1992
1993#if IDETAPE_DEBUG_LOG
1994	if (tape->debug_level >= 2)
1995		printk(KERN_INFO "ide-tape: sector: %ld, "
1996			"nr_sectors: %ld, current_nr_sectors: %d\n",
1997			rq->sector, rq->nr_sectors, rq->current_nr_sectors);
1998#endif /* IDETAPE_DEBUG_LOG */
1999
2000	if (!blk_special_request(rq)) {
2001		/*
2002		 * We do not support buffer cache originated requests.
2003		 */
2004		printk(KERN_NOTICE "ide-tape: %s: Unsupported request in "
2005			"request queue (%d)\n", drive->name, rq->cmd_type);
2006		ide_end_request(drive, 0, 0);
2007		return ide_stopped;
2008	}
2009
2010	/*
2011	 *	Retry a failed packet command
2012	 */
2013	if (tape->failed_pc != NULL &&
2014	    tape->pc->c[0] == IDETAPE_REQUEST_SENSE_CMD) {
2015		return idetape_issue_packet_command(drive, tape->failed_pc);
2016	}
2017#if IDETAPE_DEBUG_BUGS
2018	if (postponed_rq != NULL)
2019		if (rq != postponed_rq) {
2020			printk(KERN_ERR "ide-tape: ide-tape.c bug - "
2021					"Two DSC requests were queued\n");
2022			idetape_end_request(drive, 0, 0);
2023			return ide_stopped;
2024		}
2025#endif /* IDETAPE_DEBUG_BUGS */
2026
2027	tape->postponed_rq = NULL;
2028
2029	/*
2030	 * If the tape is still busy, postpone our request and service
2031	 * the other device meanwhile.
2032	 */
2033	stat = drive->hwif->INB(IDE_STATUS_REG);
2034
2035	if (!drive->dsc_overlap && !(rq->cmd[0] & REQ_IDETAPE_PC2))
2036		set_bit(IDETAPE_IGNORE_DSC, &tape->flags);
2037
2038	if (drive->post_reset == 1) {
2039		set_bit(IDETAPE_IGNORE_DSC, &tape->flags);
2040		drive->post_reset = 0;
2041	}
2042
2043	if (tape->tape_still_time > 100 && tape->tape_still_time < 200)
2044		tape->measure_insert_time = 1;
2045	if (time_after(jiffies, tape->insert_time))
2046		tape->insert_speed = tape->insert_size / 1024 * HZ / (jiffies - tape->insert_time);
2047	calculate_speeds(drive);
2048	if (!test_and_clear_bit(IDETAPE_IGNORE_DSC, &tape->flags) &&
2049	    (stat & SEEK_STAT) == 0) {
2050		if (postponed_rq == NULL) {
2051			tape->dsc_polling_start = jiffies;
2052			tape->dsc_polling_frequency = tape->best_dsc_rw_frequency;
2053			tape->dsc_timeout = jiffies + IDETAPE_DSC_RW_TIMEOUT;
2054		} else if (time_after(jiffies, tape->dsc_timeout)) {
2055			printk(KERN_ERR "ide-tape: %s: DSC timeout\n",
2056				tape->name);
2057			if (rq->cmd[0] & REQ_IDETAPE_PC2) {
2058				idetape_media_access_finished(drive);
2059				return ide_stopped;
2060			} else {
2061				return ide_do_reset(drive);
2062			}
2063		} else if (time_after(jiffies, tape->dsc_polling_start + IDETAPE_DSC_MA_THRESHOLD))
2064			tape->dsc_polling_frequency = IDETAPE_DSC_MA_SLOW;
2065		idetape_postpone_request(drive);
2066		return ide_stopped;
2067	}
2068	if (rq->cmd[0] & REQ_IDETAPE_READ) {
2069		tape->buffer_head++;
2070		tape->postpone_cnt = 0;
2071		pc = idetape_next_pc_storage(drive);
2072		idetape_create_read_cmd(tape, pc, rq->current_nr_sectors, (struct idetape_bh *)rq->special);
2073		goto out;
2074	}
2075	if (rq->cmd[0] & REQ_IDETAPE_WRITE) {
2076		tape->buffer_head++;
2077		tape->postpone_cnt = 0;
2078		pc = idetape_next_pc_storage(drive);
2079		idetape_create_write_cmd(tape, pc, rq->current_nr_sectors, (struct idetape_bh *)rq->special);
2080		goto out;
2081	}
2082	if (rq->cmd[0] & REQ_IDETAPE_READ_BUFFER) {
2083		tape->postpone_cnt = 0;
2084		pc = idetape_next_pc_storage(drive);
2085		idetape_create_read_buffer_cmd(tape, pc, rq->current_nr_sectors, (struct idetape_bh *)rq->special);
2086		goto out;
2087	}
2088	if (rq->cmd[0] & REQ_IDETAPE_PC1) {
2089		pc = (idetape_pc_t *) rq->buffer;
2090		rq->cmd[0] &= ~(REQ_IDETAPE_PC1);
2091		rq->cmd[0] |= REQ_IDETAPE_PC2;
2092		goto out;
2093	}
2094	if (rq->cmd[0] & REQ_IDETAPE_PC2) {
2095		idetape_media_access_finished(drive);
2096		return ide_stopped;
2097	}
2098	BUG();
2099out:
2100	return idetape_issue_packet_command(drive, pc);
2101}
2102
2103/*
2104 *	Pipeline related functions
2105 */
2106static inline int idetape_pipeline_active (idetape_tape_t *tape)
2107{
2108	int rc1, rc2;
2109
2110	rc1 = test_bit(IDETAPE_PIPELINE_ACTIVE, &tape->flags);
2111	rc2 = (tape->active_data_request != NULL);
2112	return rc1;
2113}
2114
2115/*
2116 *	idetape_kmalloc_stage uses __get_free_page to allocate a pipeline
2117 *	stage, along with all the necessary small buffers which together make
2118 *	a buffer of size tape->stage_size (or a bit more). We attempt to
2119 *	combine sequential pages as much as possible.
2120 *
2121 *	Returns a pointer to the new allocated stage, or NULL if we
2122 *	can't (or don't want to) allocate a stage.
2123 *
2124 *	Pipeline stages are optional and are used to increase performance.
2125 *	If we can't allocate them, we'll manage without them.
2126 */
2127static idetape_stage_t *__idetape_kmalloc_stage (idetape_tape_t *tape, int full, int clear)
2128{
2129	idetape_stage_t *stage;
2130	struct idetape_bh *prev_bh, *bh;
2131	int pages = tape->pages_per_stage;
2132	char *b_data = NULL;
2133
2134	if ((stage = kmalloc(sizeof (idetape_stage_t),GFP_KERNEL)) == NULL)
2135		return NULL;
2136	stage->next = NULL;
2137
2138	bh = stage->bh = kmalloc(sizeof(struct idetape_bh), GFP_KERNEL);
2139	if (bh == NULL)
2140		goto abort;
2141	bh->b_reqnext = NULL;
2142	if ((bh->b_data = (char *) __get_free_page (GFP_KERNEL)) == NULL)
2143		goto abort;
2144	if (clear)
2145		memset(bh->b_data, 0, PAGE_SIZE);
2146	bh->b_size = PAGE_SIZE;
2147	atomic_set(&bh->b_count, full ? bh->b_size : 0);
2148
2149	while (--pages) {
2150		if ((b_data = (char *) __get_free_page (GFP_KERNEL)) == NULL)
2151			goto abort;
2152		if (clear)
2153			memset(b_data, 0, PAGE_SIZE);
2154		if (bh->b_data == b_data + PAGE_SIZE) {
2155			bh->b_size += PAGE_SIZE;
2156			bh->b_data -= PAGE_SIZE;
2157			if (full)
2158				atomic_add(PAGE_SIZE, &bh->b_count);
2159			continue;
2160		}
2161		if (b_data == bh->b_data + bh->b_size) {
2162			bh->b_size += PAGE_SIZE;
2163			if (full)
2164				atomic_add(PAGE_SIZE, &bh->b_count);
2165			continue;
2166		}
2167		prev_bh = bh;
2168		if ((bh = kmalloc(sizeof(struct idetape_bh), GFP_KERNEL)) == NULL) {
2169			free_page((unsigned long) b_data);
2170			goto abort;
2171		}
2172		bh->b_reqnext = NULL;
2173		bh->b_data = b_data;
2174		bh->b_size = PAGE_SIZE;
2175		atomic_set(&bh->b_count, full ? bh->b_size : 0);
2176		prev_bh->b_reqnext = bh;
2177	}
2178	bh->b_size -= tape->excess_bh_size;
2179	if (full)
2180		atomic_sub(tape->excess_bh_size, &bh->b_count);
2181	return stage;
2182abort:
2183	__idetape_kfree_stage(stage);
2184	return NULL;
2185}
2186
2187static idetape_stage_t *idetape_kmalloc_stage (idetape_tape_t *tape)
2188{
2189	idetape_stage_t *cache_stage = tape->cache_stage;
2190
2191#if IDETAPE_DEBUG_LOG
2192	if (tape->debug_level >= 4)
2193		printk(KERN_INFO "ide-tape: Reached idetape_kmalloc_stage\n");
2194#endif /* IDETAPE_DEBUG_LOG */
2195
2196	if (tape->nr_stages >= tape->max_stages)
2197		return NULL;
2198	if (cache_stage != NULL) {
2199		tape->cache_stage = NULL;
2200		return cache_stage;
2201	}
2202	return __idetape_kmalloc_stage(tape, 0, 0);
2203}
2204
2205static int idetape_copy_stage_from_user (idetape_tape_t *tape, idetape_stage_t *stage, const char __user *buf, int n)
2206{
2207	struct idetape_bh *bh = tape->bh;
2208	int count;
2209	int ret = 0;
2210
2211	while (n) {
2212#if IDETAPE_DEBUG_BUGS
2213		if (bh == NULL) {
2214			printk(KERN_ERR "ide-tape: bh == NULL in "
2215				"idetape_copy_stage_from_user\n");
2216			return 1;
2217		}
2218#endif /* IDETAPE_DEBUG_BUGS */
2219		count = min((unsigned int)(bh->b_size - atomic_read(&bh->b_count)), (unsigned int)n);
2220		if (copy_from_user(bh->b_data + atomic_read(&bh->b_count), buf, count))
2221			ret = 1;
2222		n -= count;
2223		atomic_add(count, &bh->b_count);
2224		buf += count;
2225		if (atomic_read(&bh->b_count) == bh->b_size) {
2226			bh = bh->b_reqnext;
2227			if (bh)
2228				atomic_set(&bh->b_count, 0);
2229		}
2230	}
2231	tape->bh = bh;
2232	return ret;
2233}
2234
2235static int idetape_copy_stage_to_user (idetape_tape_t *tape, char __user *buf, idetape_stage_t *stage, int n)
2236{
2237	struct idetape_bh *bh = tape->bh;
2238	int count;
2239	int ret = 0;
2240
2241	while (n) {
2242#if IDETAPE_DEBUG_BUGS
2243		if (bh == NULL) {
2244			printk(KERN_ERR "ide-tape: bh == NULL in "
2245				"idetape_copy_stage_to_user\n");
2246			return 1;
2247		}
2248#endif /* IDETAPE_DEBUG_BUGS */
2249		count = min(tape->b_count, n);
2250		if  (copy_to_user(buf, tape->b_data, count))
2251			ret = 1;
2252		n -= count;
2253		tape->b_data += count;
2254		tape->b_count -= count;
2255		buf += count;
2256		if (!tape->b_count) {
2257			tape->bh = bh = bh->b_reqnext;
2258			if (bh) {
2259				tape->b_data = bh->b_data;
2260				tape->b_count = atomic_read(&bh->b_count);
2261			}
2262		}
2263	}
2264	return ret;
2265}
2266
2267static void idetape_init_merge_stage (idetape_tape_t *tape)
2268{
2269	struct idetape_bh *bh = tape->merge_stage->bh;
2270
2271	tape->bh = bh;
2272	if (tape->chrdev_direction == idetape_direction_write)
2273		atomic_set(&bh->b_count, 0);
2274	else {
2275		tape->b_data = bh->b_data;
2276		tape->b_count = atomic_read(&bh->b_count);
2277	}
2278}
2279
2280static void idetape_switch_buffers (idetape_tape_t *tape, idetape_stage_t *stage)
2281{
2282	struct idetape_bh *tmp;
2283
2284	tmp = stage->bh;
2285	stage->bh = tape->merge_stage->bh;
2286	tape->merge_stage->bh = tmp;
2287	idetape_init_merge_stage(tape);
2288}
2289
2290/*
2291 *	idetape_add_stage_tail adds a new stage at the end of the pipeline.
2292 */
2293static void idetape_add_stage_tail (ide_drive_t *drive,idetape_stage_t *stage)
2294{
2295	idetape_tape_t *tape = drive->driver_data;
2296	unsigned long flags;
2297
2298#if IDETAPE_DEBUG_LOG
2299	if (tape->debug_level >= 4)
2300		printk (KERN_INFO "ide-tape: Reached idetape_add_stage_tail\n");
2301#endif /* IDETAPE_DEBUG_LOG */
2302	spin_lock_irqsave(&tape->spinlock, flags);
2303	stage->next = NULL;
2304	if (tape->last_stage != NULL)
2305		tape->last_stage->next=stage;
2306	else
2307		tape->first_stage = tape->next_stage=stage;
2308	tape->last_stage = stage;
2309	if (tape->next_stage == NULL)
2310		tape->next_stage = tape->last_stage;
2311	tape->nr_stages++;
2312	tape->nr_pending_stages++;
2313	spin_unlock_irqrestore(&tape->spinlock, flags);
2314}
2315
2316/*
2317 *	idetape_wait_for_request installs a completion in a pending request
2318 *	and sleeps until it is serviced.
2319 *
2320 *	The caller should ensure that the request will not be serviced
2321 *	before we install the completion (usually by disabling interrupts).
2322 */
2323static void idetape_wait_for_request (ide_drive_t *drive, struct request *rq)
2324{
2325	DECLARE_COMPLETION_ONSTACK(wait);
2326	idetape_tape_t *tape = drive->driver_data;
2327
2328#if IDETAPE_DEBUG_BUGS
2329	if (rq == NULL || !blk_special_request(rq)) {
2330		printk (KERN_ERR "ide-tape: bug: Trying to sleep on non-valid request\n");
2331		return;
2332	}
2333#endif /* IDETAPE_DEBUG_BUGS */
2334	rq->end_io_data = &wait;
2335	rq->end_io = blk_end_sync_rq;
2336	spin_unlock_irq(&tape->spinlock);
2337	wait_for_completion(&wait);
2338	/* The stage and its struct request have been deallocated */
2339	spin_lock_irq(&tape->spinlock);
2340}
2341
2342static ide_startstop_t idetape_read_position_callback (ide_drive_t *drive)
2343{
2344	idetape_tape_t *tape = drive->driver_data;
2345	idetape_read_position_result_t *result;
2346
2347#if IDETAPE_DEBUG_LOG
2348	if (tape->debug_level >= 4)
2349		printk(KERN_INFO "ide-tape: Reached idetape_read_position_callback\n");
2350#endif /* IDETAPE_DEBUG_LOG */
2351
2352	if (!tape->pc->error) {
2353		result = (idetape_read_position_result_t *) tape->pc->buffer;
2354#if IDETAPE_DEBUG_LOG
2355		if (tape->debug_level >= 2)
2356			printk(KERN_INFO "ide-tape: BOP - %s\n",result->bop ? "Yes":"No");
2357		if (tape->debug_level >= 2)
2358			printk(KERN_INFO "ide-tape: EOP - %s\n",result->eop ? "Yes":"No");
2359#endif /* IDETAPE_DEBUG_LOG */
2360		if (result->bpu) {
2361			printk(KERN_INFO "ide-tape: Block location is unknown to the tape\n");
2362			clear_bit(IDETAPE_ADDRESS_VALID, &tape->flags);
2363			idetape_end_request(drive, 0, 0);
2364		} else {
2365#if IDETAPE_DEBUG_LOG
2366			if (tape->debug_level >= 2)
2367				printk(KERN_INFO "ide-tape: Block Location - %u\n", ntohl(result->first_block));
2368#endif /* IDETAPE_DEBUG_LOG */
2369			tape->partition = result->partition;
2370			tape->first_frame_position = ntohl(result->first_block);
2371			tape->last_frame_position = ntohl(result->last_block);
2372			tape->blocks_in_buffer = result->blocks_in_buffer[2];
2373			set_bit(IDETAPE_ADDRESS_VALID, &tape->flags);
2374			idetape_end_request(drive, 1, 0);
2375		}
2376	} else {
2377		idetape_end_request(drive, 0, 0);
2378	}
2379	return ide_stopped;
2380}
2381
2382/*
2383 *	idetape_create_write_filemark_cmd will:
2384 *
2385 *		1.	Write a filemark if write_filemark=1.
2386 *		2.	Flush the device buffers without writing a filemark
2387 *			if write_filemark=0.
2388 *
2389 */
2390static void idetape_create_write_filemark_cmd (ide_drive_t *drive, idetape_pc_t *pc,int write_filemark)
2391{
2392	idetape_init_pc(pc);
2393	pc->c[0] = IDETAPE_WRITE_FILEMARK_CMD;
2394	pc->c[4] = write_filemark;
2395	set_bit(PC_WAIT_FOR_DSC, &pc->flags);
2396	pc->callback = &idetape_pc_callback;
2397}
2398
2399static void idetape_create_test_unit_ready_cmd(idetape_pc_t *pc)
2400{
2401	idetape_init_pc(pc);
2402	pc->c[0] = IDETAPE_TEST_UNIT_READY_CMD;
2403	pc->callback = &idetape_pc_callback;
2404}
2405
2406/*
2407 *	idetape_queue_pc_tail is based on the following functions:
2408 *
2409 *	ide_do_drive_cmd from ide.c
2410 *	cdrom_queue_request and cdrom_queue_packet_command from ide-cd.c
2411 *
2412 *	We add a special packet command request to the tail of the request
2413 *	queue, and wait for it to be serviced.
2414 *
2415 *	This is not to be called from within the request handling part
2416 *	of the driver ! We allocate here data in the stack, and it is valid
2417 *	until the request is finished. This is not the case for the bottom
2418 *	part of the driver, where we are always leaving the functions to wait
2419 *	for an interrupt or a timer event.
2420 *
2421 *	From the bottom part of the driver, we should allocate safe memory
2422 *	using idetape_next_pc_storage and idetape_next_rq_storage, and add
2423 *	the request to the request list without waiting for it to be serviced !
2424 *	In that case, we usually use idetape_queue_pc_head.
2425 */
2426static int __idetape_queue_pc_tail (ide_drive_t *drive, idetape_pc_t *pc)
2427{
2428	struct ide_tape_obj *tape = drive->driver_data;
2429	struct request rq;
2430
2431	idetape_init_rq(&rq, REQ_IDETAPE_PC1);
2432	rq.buffer = (char *) pc;
2433	rq.rq_disk = tape->disk;
2434	return ide_do_drive_cmd(drive, &rq, ide_wait);
2435}
2436
2437static void idetape_create_load_unload_cmd (ide_drive_t *drive, idetape_pc_t *pc,int cmd)
2438{
2439	idetape_init_pc(pc);
2440	pc->c[0] = IDETAPE_LOAD_UNLOAD_CMD;
2441	pc->c[4] = cmd;
2442	set_bit(PC_WAIT_FOR_DSC, &pc->flags);
2443	pc->callback = &idetape_pc_callback;
2444}
2445
2446static int idetape_wait_ready(ide_drive_t *drive, unsigned long timeout)
2447{
2448	idetape_tape_t *tape = drive->driver_data;
2449	idetape_pc_t pc;
2450	int load_attempted = 0;
2451
2452	/*
2453	 * Wait for the tape to become ready
2454	 */
2455	set_bit(IDETAPE_MEDIUM_PRESENT, &tape->flags);
2456	timeout += jiffies;
2457	while (time_before(jiffies, timeout)) {
2458		idetape_create_test_unit_ready_cmd(&pc);
2459		if (!__idetape_queue_pc_tail(drive, &pc))
2460			return 0;
2461		if ((tape->sense_key == 2 && tape->asc == 4 && tape->ascq == 2)
2462		    || (tape->asc == 0x3A)) {	/* no media */
2463			if (load_attempted)
2464				return -ENOMEDIUM;
2465			idetape_create_load_unload_cmd(drive, &pc, IDETAPE_LU_LOAD_MASK);
2466			__idetape_queue_pc_tail(drive, &pc);
2467			load_attempted = 1;
2468		/* not about to be ready */
2469		} else if (!(tape->sense_key == 2 && tape->asc == 4 &&
2470			     (tape->ascq == 1 || tape->ascq == 8)))
2471			return -EIO;
2472		msleep(100);
2473	}
2474	return -EIO;
2475}
2476
2477static int idetape_queue_pc_tail (ide_drive_t *drive,idetape_pc_t *pc)
2478{
2479	return __idetape_queue_pc_tail(drive, pc);
2480}
2481
2482static int idetape_flush_tape_buffers (ide_drive_t *drive)
2483{
2484	idetape_pc_t pc;
2485	int rc;
2486
2487	idetape_create_write_filemark_cmd(drive, &pc, 0);
2488	if ((rc = idetape_queue_pc_tail(drive, &pc)))
2489		return rc;
2490	idetape_wait_ready(drive, 60 * 5 * HZ);
2491	return 0;
2492}
2493
2494static void idetape_create_read_position_cmd (idetape_pc_t *pc)
2495{
2496	idetape_init_pc(pc);
2497	pc->c[0] = IDETAPE_READ_POSITION_CMD;
2498	pc->request_transfer = 20;
2499	pc->callback = &idetape_read_position_callback;
2500}
2501
2502static int idetape_read_position (ide_drive_t *drive)
2503{
2504	idetape_tape_t *tape = drive->driver_data;
2505	idetape_pc_t pc;
2506	int position;
2507
2508#if IDETAPE_DEBUG_LOG
2509        if (tape->debug_level >= 4)
2510		printk(KERN_INFO "ide-tape: Reached idetape_read_position\n");
2511#endif /* IDETAPE_DEBUG_LOG */
2512
2513	idetape_create_read_position_cmd(&pc);
2514	if (idetape_queue_pc_tail(drive, &pc))
2515		return -1;
2516	position = tape->first_frame_position;
2517	return position;
2518}
2519
2520static void idetape_create_locate_cmd (ide_drive_t *drive, idetape_pc_t *pc, unsigned int block, u8 partition, int skip)
2521{
2522	idetape_init_pc(pc);
2523	pc->c[0] = IDETAPE_LOCATE_CMD;
2524	pc->c[1] = 2;
2525	put_unaligned(htonl(block), (unsigned int *) &pc->c[3]);
2526	pc->c[8] = partition;
2527	set_bit(PC_WAIT_FOR_DSC, &pc->flags);
2528	pc->callback = &idetape_pc_callback;
2529}
2530
2531static int idetape_create_prevent_cmd (ide_drive_t *drive, idetape_pc_t *pc, int prevent)
2532{
2533	idetape_tape_t *tape = drive->driver_data;
2534
2535	if (!tape->capabilities.lock)
2536		return 0;
2537
2538	idetape_init_pc(pc);
2539	pc->c[0] = IDETAPE_PREVENT_CMD;
2540	pc->c[4] = prevent;
2541	pc->callback = &idetape_pc_callback;
2542	return 1;
2543}
2544
2545static int __idetape_discard_read_pipeline (ide_drive_t *drive)
2546{
2547	idetape_tape_t *tape = drive->driver_data;
2548	unsigned long flags;
2549	int cnt;
2550
2551	if (tape->chrdev_direction != idetape_direction_read)
2552		return 0;
2553
2554	/* Remove merge stage. */
2555	cnt = tape->merge_stage_size / tape->tape_block_size;
2556	if (test_and_clear_bit(IDETAPE_FILEMARK, &tape->flags))
2557		++cnt;		/* Filemarks count as 1 sector */
2558	tape->merge_stage_size = 0;
2559	if (tape->merge_stage != NULL) {
2560		__idetape_kfree_stage(tape->merge_stage);
2561		tape->merge_stage = NULL;
2562	}
2563
2564	/* Clear pipeline flags. */
2565	clear_bit(IDETAPE_PIPELINE_ERROR, &tape->flags);
2566	tape->chrdev_direction = idetape_direction_none;
2567
2568	/* Remove pipeline stages. */
2569	if (tape->first_stage == NULL)
2570		return 0;
2571
2572	spin_lock_irqsave(&tape->spinlock, flags);
2573	tape->next_stage = NULL;
2574	if (idetape_pipeline_active(tape))
2575		idetape_wait_for_request(drive, tape->active_data_request);
2576	spin_unlock_irqrestore(&tape->spinlock, flags);
2577
2578	while (tape->first_stage != NULL) {
2579		struct request *rq_ptr = &tape->first_stage->rq;
2580
2581		cnt += rq_ptr->nr_sectors - rq_ptr->current_nr_sectors;
2582		if (rq_ptr->errors == IDETAPE_ERROR_FILEMARK)
2583			++cnt;
2584		idetape_remove_stage_head(drive);
2585	}
2586	tape->nr_pending_stages = 0;
2587	tape->max_stages = tape->min_pipeline;
2588	return cnt;
2589}
2590
2591/*
2592 *	idetape_position_tape positions the tape to the requested block
2593 *	using the LOCATE packet command. A READ POSITION command is then
2594 *	issued to check where we are positioned.
2595 *
2596 *	Like all higher level operations, we queue the commands at the tail
2597 *	of the request queue and wait for their completion.
2598 *
2599 */
2600static int idetape_position_tape (ide_drive_t *drive, unsigned int block, u8 partition, int skip)
2601{
2602	idetape_tape_t *tape = drive->driver_data;
2603	int retval;
2604	idetape_pc_t pc;
2605
2606	if (tape->chrdev_direction == idetape_direction_read)
2607		__idetape_discard_read_pipeline(drive);
2608	idetape_wait_ready(drive, 60 * 5 * HZ);
2609	idetape_create_locate_cmd(drive, &pc, block, partition, skip);
2610	retval = idetape_queue_pc_tail(drive, &pc);
2611	if (retval)
2612		return (retval);
2613
2614	idetape_create_read_position_cmd(&pc);
2615	return (idetape_queue_pc_tail(drive, &pc));
2616}
2617
2618static void idetape_discard_read_pipeline (ide_drive_t *drive, int restore_position)
2619{
2620	idetape_tape_t *tape = drive->driver_data;
2621	int cnt;
2622	int seek, position;
2623
2624	cnt = __idetape_discard_read_pipeline(drive);
2625	if (restore_position) {
2626		position = idetape_read_position(drive);
2627		seek = position > cnt ? position - cnt : 0;
2628		if (idetape_position_tape(drive, seek, 0, 0)) {
2629			printk(KERN_INFO "ide-tape: %s: position_tape failed in discard_pipeline()\n", tape->name);
2630			return;
2631		}
2632	}
2633}
2634
2635/*
2636 * idetape_queue_rw_tail generates a read/write request for the block
2637 * device interface and wait for it to be serviced.
2638 */
2639static int idetape_queue_rw_tail(ide_drive_t *drive, int cmd, int blocks, struct idetape_bh *bh)
2640{
2641	idetape_tape_t *tape = drive->driver_data;
2642	struct request rq;
2643
2644#if IDETAPE_DEBUG_LOG
2645	if (tape->debug_level >= 2)
2646		printk(KERN_INFO "ide-tape: idetape_queue_rw_tail: cmd=%d\n",cmd);
2647#endif /* IDETAPE_DEBUG_LOG */
2648#if IDETAPE_DEBUG_BUGS
2649	if (idetape_pipeline_active(tape)) {
2650		printk(KERN_ERR "ide-tape: bug: the pipeline is active in idetape_queue_rw_tail\n");
2651		return (0);
2652	}
2653#endif /* IDETAPE_DEBUG_BUGS */
2654
2655	idetape_init_rq(&rq, cmd);
2656	rq.rq_disk = tape->disk;
2657	rq.special = (void *)bh;
2658	rq.sector = tape->first_frame_position;
2659	rq.nr_sectors = rq.current_nr_sectors = blocks;
2660	(void) ide_do_drive_cmd(drive, &rq, ide_wait);
2661
2662	if ((cmd & (REQ_IDETAPE_READ | REQ_IDETAPE_WRITE)) == 0)
2663		return 0;
2664
2665	if (tape->merge_stage)
2666		idetape_init_merge_stage(tape);
2667	if (rq.errors == IDETAPE_ERROR_GENERAL)
2668		return -EIO;
2669	return (tape->tape_block_size * (blocks-rq.current_nr_sectors));
2670}
2671
2672/*
2673 *	idetape_insert_pipeline_into_queue is used to start servicing the
2674 *	pipeline stages, starting from tape->next_stage.
2675 */
2676static void idetape_insert_pipeline_into_queue (ide_drive_t *drive)
2677{
2678	idetape_tape_t *tape = drive->driver_data;
2679
2680	if (tape->next_stage == NULL)
2681		return;
2682	if (!idetape_pipeline_active(tape)) {
2683		set_bit(IDETAPE_PIPELINE_ACTIVE, &tape->flags);
2684		idetape_active_next_stage(drive);
2685		(void) ide_do_drive_cmd(drive, tape->active_data_request, ide_end);
2686	}
2687}
2688
2689static void idetape_create_inquiry_cmd (idetape_pc_t *pc)
2690{
2691	idetape_init_pc(pc);
2692	pc->c[0] = IDETAPE_INQUIRY_CMD;
2693	pc->c[4] = pc->request_transfer = 254;
2694	pc->callback = &idetape_pc_callback;
2695}
2696
2697static void idetape_create_rewind_cmd (ide_drive_t *drive, idetape_pc_t *pc)
2698{
2699	idetape_init_pc(pc);
2700	pc->c[0] = IDETAPE_REWIND_CMD;
2701	set_bit(PC_WAIT_FOR_DSC, &pc->flags);
2702	pc->callback = &idetape_pc_callback;
2703}
2704
2705static void idetape_create_erase_cmd (idetape_pc_t *pc)
2706{
2707	idetape_init_pc(pc);
2708	pc->c[0] = IDETAPE_ERASE_CMD;
2709	pc->c[1] = 1;
2710	set_bit(PC_WAIT_FOR_DSC, &pc->flags);
2711	pc->callback = &idetape_pc_callback;
2712}
2713
2714static void idetape_create_space_cmd (idetape_pc_t *pc,int count, u8 cmd)
2715{
2716	idetape_init_pc(pc);
2717	pc->c[0] = IDETAPE_SPACE_CMD;
2718	put_unaligned(htonl(count), (unsigned int *) &pc->c[1]);
2719	pc->c[1] = cmd;
2720	set_bit(PC_WAIT_FOR_DSC, &pc->flags);
2721	pc->callback = &idetape_pc_callback;
2722}
2723
2724static void idetape_wait_first_stage (ide_drive_t *drive)
2725{
2726	idetape_tape_t *tape = drive->driver_data;
2727	unsigned long flags;
2728
2729	if (tape->first_stage == NULL)
2730		return;
2731	spin_lock_irqsave(&tape->spinlock, flags);
2732	if (tape->active_stage == tape->first_stage)
2733		idetape_wait_for_request(drive, tape->active_data_request);
2734	spin_unlock_irqrestore(&tape->spinlock, flags);
2735}
2736
2737/*
2738 *	idetape_add_chrdev_write_request tries to add a character device
2739 *	originated write request to our pipeline. In case we don't succeed,
2740 *	we revert to non-pipelined operation mode for this request.
2741 *
2742 *	1.	Try to allocate a new pipeline stage.
2743 *	2.	If we can't, wait for more and more requests to be serviced
2744 *		and try again each time.
2745 *	3.	If we still can't allocate a stage, fallback to
2746 *		non-pipelined operation mode for this request.
2747 */
2748static int idetape_add_chrdev_write_request (ide_drive_t *drive, int blocks)
2749{
2750	idetape_tape_t *tape = drive->driver_data;
2751	idetape_stage_t *new_stage;
2752	unsigned long flags;
2753	struct request *rq;
2754
2755#if IDETAPE_DEBUG_LOG
2756	if (tape->debug_level >= 3)
2757		printk(KERN_INFO "ide-tape: Reached idetape_add_chrdev_write_request\n");
2758#endif /* IDETAPE_DEBUG_LOG */
2759
2760     	/*
2761     	 *	Attempt to allocate a new stage.
2762	 *	Pay special attention to possible race conditions.
2763	 */
2764	while ((new_stage = idetape_kmalloc_stage(tape)) == NULL) {
2765		spin_lock_irqsave(&tape->spinlock, flags);
2766		if (idetape_pipeline_active(tape)) {
2767			idetape_wait_for_request(drive, tape->active_data_request);
2768			spin_unlock_irqrestore(&tape->spinlock, flags);
2769		} else {
2770			spin_unlock_irqrestore(&tape->spinlock, flags);
2771			idetape_insert_pipeline_into_queue(drive);
2772			if (idetape_pipeline_active(tape))
2773				continue;
2774			/*
2775			 *	Linux is short on memory. Fallback to
2776			 *	non-pipelined operation mode for this request.
2777			 */
2778			return idetape_queue_rw_tail(drive, REQ_IDETAPE_WRITE, blocks, tape->merge_stage->bh);
2779		}
2780	}
2781	rq = &new_stage->rq;
2782	idetape_init_rq(rq, REQ_IDETAPE_WRITE);
2783	/* Doesn't actually matter - We always assume sequential access */
2784	rq->sector = tape->first_frame_position;
2785	rq->nr_sectors = rq->current_nr_sectors = blocks;
2786
2787	idetape_switch_buffers(tape, new_stage);
2788	idetape_add_stage_tail(drive, new_stage);
2789	tape->pipeline_head++;
2790	calculate_speeds(drive);
2791
2792	/*
2793	 *	Estimate whether the tape has stopped writing by checking
2794	 *	if our write pipeline is currently empty. If we are not
2795	 *	writing anymore, wait for the pipeline to be full enough
2796	 *	(90%) before starting to service requests, so that we will
2797	 *	be able to keep up with the higher speeds of the tape.
2798	 */
2799	if (!idetape_pipeline_active(tape)) {
2800		if (tape->nr_stages >= tape->max_stages * 9 / 10 ||
2801		    tape->nr_stages >= tape->max_stages - tape->uncontrolled_pipeline_head_speed * 3 * 1024 / tape->tape_block_size) {
2802			tape->measure_insert_time = 1;
2803			tape->insert_time = jiffies;
2804			tape->insert_size = 0;
2805			tape->insert_speed = 0;
2806			idetape_insert_pipeline_into_queue(drive);
2807		}
2808	}
2809	if (test_and_clear_bit(IDETAPE_PIPELINE_ERROR, &tape->flags))
2810		/* Return a deferred error */
2811		return -EIO;
2812	return blocks;
2813}
2814
2815/*
2816 *	idetape_wait_for_pipeline will wait until all pending pipeline
2817 *	requests are serviced. Typically called on device close.
2818 */
2819static void idetape_wait_for_pipeline (ide_drive_t *drive)
2820{
2821	idetape_tape_t *tape = drive->driver_data;
2822	unsigned long flags;
2823
2824	while (tape->next_stage || idetape_pipeline_active(tape)) {
2825		idetape_insert_pipeline_into_queue(drive);
2826		spin_lock_irqsave(&tape->spinlock, flags);
2827		if (idetape_pipeline_active(tape))
2828			idetape_wait_for_request(drive, tape->active_data_request);
2829		spin_unlock_irqrestore(&tape->spinlock, flags);
2830	}
2831}
2832
2833static void idetape_empty_write_pipeline (ide_drive_t *drive)
2834{
2835	idetape_tape_t *tape = drive->driver_data;
2836	int blocks, min;
2837	struct idetape_bh *bh;
2838
2839#if IDETAPE_DEBUG_BUGS
2840	if (tape->chrdev_direction != idetape_direction_write) {
2841		printk(KERN_ERR "ide-tape: bug: Trying to empty write pipeline, but we are not writing.\n");
2842		return;
2843	}
2844	if (tape->merge_stage_size > tape->stage_size) {
2845		printk(KERN_ERR "ide-tape: bug: merge_buffer too big\n");
2846		tape->merge_stage_size = tape->stage_size;
2847	}
2848#endif /* IDETAPE_DEBUG_BUGS */
2849	if (tape->merge_stage_size) {
2850		blocks = tape->merge_stage_size / tape->tape_block_size;
2851		if (tape->merge_stage_size % tape->tape_block_size) {
2852			unsigned int i;
2853
2854			blocks++;
2855			i = tape->tape_block_size - tape->merge_stage_size % tape->tape_block_size;
2856			bh = tape->bh->b_reqnext;
2857			while (bh) {
2858				atomic_set(&bh->b_count, 0);
2859				bh = bh->b_reqnext;
2860			}
2861			bh = tape->bh;
2862			while (i) {
2863				if (bh == NULL) {
2864
2865					printk(KERN_INFO "ide-tape: bug, bh NULL\n");
2866					break;
2867				}
2868				min = min(i, (unsigned int)(bh->b_size - atomic_read(&bh->b_count)));
2869				memset(bh->b_data + atomic_read(&bh->b_count), 0, min);
2870				atomic_add(min, &bh->b_count);
2871				i -= min;
2872				bh = bh->b_reqnext;
2873			}
2874		}
2875		(void) idetape_add_chrdev_write_request(drive, blocks);
2876		tape->merge_stage_size = 0;
2877	}
2878	idetape_wait_for_pipeline(drive);
2879	if (tape->merge_stage != NULL) {
2880		__idetape_kfree_stage(tape->merge_stage);
2881		tape->merge_stage = NULL;
2882	}
2883	clear_bit(IDETAPE_PIPELINE_ERROR, &tape->flags);
2884	tape->chrdev_direction = idetape_direction_none;
2885
2886	/*
2887	 *	On the next backup, perform the feedback loop again.
2888	 *	(I don't want to keep sense information between backups,
2889	 *	 as some systems are constantly on, and the system load
2890	 *	 can be totally different on the next backup).
2891	 */
2892	tape->max_stages = tape->min_pipeline;
2893#if IDETAPE_DEBUG_BUGS
2894	if (tape->first_stage != NULL ||
2895	    tape->next_stage != NULL ||
2896	    tape->last_stage != NULL ||
2897	    tape->nr_stages != 0) {
2898		printk(KERN_ERR "ide-tape: ide-tape pipeline bug, "
2899			"first_stage %p, next_stage %p, "
2900			"last_stage %p, nr_stages %d\n",
2901			tape->first_stage, tape->next_stage,
2902			tape->last_stage, tape->nr_stages);
2903	}
2904#endif /* IDETAPE_DEBUG_BUGS */
2905}
2906
2907static void idetape_restart_speed_control (ide_drive_t *drive)
2908{
2909	idetape_tape_t *tape = drive->driver_data;
2910
2911	tape->restart_speed_control_req = 0;
2912	tape->pipeline_head = 0;
2913	tape->controlled_last_pipeline_head = tape->uncontrolled_last_pipeline_head = 0;
2914	tape->controlled_previous_pipeline_head = tape->uncontrolled_previous_pipeline_head = 0;
2915	tape->pipeline_head_speed = tape->controlled_pipeline_head_speed = 5000;
2916	tape->uncontrolled_pipeline_head_speed = 0;
2917	tape->controlled_pipeline_head_time = tape->uncontrolled_pipeline_head_time = jiffies;
2918	tape->controlled_previous_head_time = tape->uncontrolled_previous_head_time = jiffies;
2919}
2920
2921static int idetape_initiate_read (ide_drive_t *drive, int max_stages)
2922{
2923	idetape_tape_t *tape = drive->driver_data;
2924	idetape_stage_t *new_stage;
2925	struct request rq;
2926	int bytes_read;
2927	int blocks = tape->capabilities.ctl;
2928
2929	/* Initialize read operation */
2930	if (tape->chrdev_direction != idetape_direction_read) {
2931		if (tape->chrdev_direction == idetape_direction_write) {
2932			idetape_empty_write_pipeline(drive);
2933			idetape_flush_tape_buffers(drive);
2934		}
2935#if IDETAPE_DEBUG_BUGS
2936		if (tape->merge_stage || tape->merge_stage_size) {
2937			printk (KERN_ERR "ide-tape: merge_stage_size should be 0 now\n");
2938			tape->merge_stage_size = 0;
2939		}
2940#endif /* IDETAPE_DEBUG_BUGS */
2941		if ((tape->merge_stage = __idetape_kmalloc_stage(tape, 0, 0)) == NULL)
2942			return -ENOMEM;
2943		tape->chrdev_direction = idetape_direction_read;
2944
2945		/*
2946		 *	Issue a read 0 command to ensure that DSC handshake
2947		 *	is switched from completion mode to buffer available
2948		 *	mode.
2949		 *	No point in issuing this if DSC overlap isn't supported,
2950		 *	some drives (Seagate STT3401A) will return an error.
2951		 */
2952		if (drive->dsc_overlap) {
2953			bytes_read = idetape_queue_rw_tail(drive, REQ_IDETAPE_READ, 0, tape->merge_stage->bh);
2954			if (bytes_read < 0) {
2955				__idetape_kfree_stage(tape->merge_stage);
2956				tape->merge_stage = NULL;
2957				tape->chrdev_direction = idetape_direction_none;
2958				return bytes_read;
2959			}
2960		}
2961	}
2962	if (tape->restart_speed_control_req)
2963		idetape_restart_speed_control(drive);
2964	idetape_init_rq(&rq, REQ_IDETAPE_READ);
2965	rq.sector = tape->first_frame_position;
2966	rq.nr_sectors = rq.current_nr_sectors = blocks;
2967	if (!test_bit(IDETAPE_PIPELINE_ERROR, &tape->flags) &&
2968	    tape->nr_stages < max_stages) {
2969		new_stage = idetape_kmalloc_stage(tape);
2970		while (new_stage != NULL) {
2971			new_stage->rq = rq;
2972			idetape_add_stage_tail(drive, new_stage);
2973			if (tape->nr_stages >= max_stages)
2974				break;
2975			new_stage = idetape_kmalloc_stage(tape);
2976		}
2977	}
2978	if (!idetape_pipeline_active(tape)) {
2979		if (tape->nr_pending_stages >= 3 * max_stages / 4) {
2980			tape->measure_insert_time = 1;
2981			tape->insert_time = jiffies;
2982			tape->insert_size = 0;
2983			tape->insert_speed = 0;
2984			idetape_insert_pipeline_into_queue(drive);
2985		}
2986	}
2987	return 0;
2988}
2989
2990/*
2991 *	idetape_add_chrdev_read_request is called from idetape_chrdev_read
2992 *	to service a character device read request and add read-ahead
2993 *	requests to our pipeline.
2994 */
2995static int idetape_add_chrdev_read_request (ide_drive_t *drive,int blocks)
2996{
2997	idetape_tape_t *tape = drive->driver_data;
2998	unsigned long flags;
2999	struct request *rq_ptr;
3000	int bytes_read;
3001
3002#if IDETAPE_DEBUG_LOG
3003	if (tape->debug_level >= 4)
3004		printk(KERN_INFO "ide-tape: Reached idetape_add_chrdev_read_request, %d blocks\n", blocks);
3005#endif /* IDETAPE_DEBUG_LOG */
3006
3007	/*
3008	 * If we are at a filemark, return a read length of 0
3009	 */
3010	if (test_bit(IDETAPE_FILEMARK, &tape->flags))
3011		return 0;
3012
3013	/*
3014	 * Wait for the next block to be available at the head
3015	 * of the pipeline
3016	 */
3017	idetape_initiate_read(drive, tape->max_stages);
3018	if (tape->first_stage == NULL) {
3019		if (test_bit(IDETAPE_PIPELINE_ERROR, &tape->flags))
3020			return 0;
3021		return idetape_queue_rw_tail(drive, REQ_IDETAPE_READ, blocks, tape->merge_stage->bh);
3022	}
3023	idetape_wait_first_stage(drive);
3024	rq_ptr = &tape->first_stage->rq;
3025	bytes_read = tape->tape_block_size * (rq_ptr->nr_sectors - rq_ptr->current_nr_sectors);
3026	rq_ptr->nr_sectors = rq_ptr->current_nr_sectors = 0;
3027
3028
3029	if (rq_ptr->errors == IDETAPE_ERROR_EOD)
3030		return 0;
3031	else {
3032		idetape_switch_buffers(tape, tape->first_stage);
3033		if (rq_ptr->errors == IDETAPE_ERROR_FILEMARK)
3034			set_bit(IDETAPE_FILEMARK, &tape->flags);
3035		spin_lock_irqsave(&tape->spinlock, flags);
3036		idetape_remove_stage_head(drive);
3037		spin_unlock_irqrestore(&tape->spinlock, flags);
3038		tape->pipeline_head++;
3039		calculate_speeds(drive);
3040	}
3041#if IDETAPE_DEBUG_BUGS
3042	if (bytes_read > blocks * tape->tape_block_size) {
3043		printk(KERN_ERR "ide-tape: bug: trying to return more bytes than requested\n");
3044		bytes_read = blocks * tape->tape_block_size;
3045	}
3046#endif /* IDETAPE_DEBUG_BUGS */
3047	return (bytes_read);
3048}
3049
3050static void idetape_pad_zeros (ide_drive_t *drive, int bcount)
3051{
3052	idetape_tape_t *tape = drive->driver_data;
3053	struct idetape_bh *bh;
3054	int blocks;
3055
3056	while (bcount) {
3057		unsigned int count;
3058
3059		bh = tape->merge_stage->bh;
3060		count = min(tape->stage_size, bcount);
3061		bcount -= count;
3062		blocks = count / tape->tape_block_size;
3063		while (count) {
3064			atomic_set(&bh->b_count, min(count, (unsigned int)bh->b_size));
3065			memset(bh->b_data, 0, atomic_read(&bh->b_count));
3066			count -= atomic_read(&bh->b_count);
3067			bh = bh->b_reqnext;
3068		}
3069		idetape_queue_rw_tail(drive, REQ_IDETAPE_WRITE, blocks, tape->merge_stage->bh);
3070	}
3071}
3072
3073static int idetape_pipeline_size (ide_drive_t *drive)
3074{
3075	idetape_tape_t *tape = drive->driver_data;
3076	idetape_stage_t *stage;
3077	struct request *rq;
3078	int size = 0;
3079
3080	idetape_wait_for_pipeline(drive);
3081	stage = tape->first_stage;
3082	while (stage != NULL) {
3083		rq = &stage->rq;
3084		size += tape->tape_block_size * (rq->nr_sectors-rq->current_nr_sectors);
3085		if (rq->errors == IDETAPE_ERROR_FILEMARK)
3086			size += tape->tape_block_size;
3087		stage = stage->next;
3088	}
3089	size += tape->merge_stage_size;
3090	return size;
3091}
3092
3093/*
3094 *	Rewinds the tape to the Beginning Of the current Partition (BOP).
3095 *
3096 *	We currently support only one partition.
3097 */
3098static int idetape_rewind_tape (ide_drive_t *drive)
3099{
3100	int retval;
3101	idetape_pc_t pc;
3102#if IDETAPE_DEBUG_LOG
3103	idetape_tape_t *tape = drive->driver_data;
3104	if (tape->debug_level >= 2)
3105		printk(KERN_INFO "ide-tape: Reached idetape_rewind_tape\n");
3106#endif /* IDETAPE_DEBUG_LOG */
3107
3108	idetape_create_rewind_cmd(drive, &pc);
3109	retval = idetape_queue_pc_tail(drive, &pc);
3110	if (retval)
3111		return retval;
3112
3113	idetape_create_read_position_cmd(&pc);
3114	retval = idetape_queue_pc_tail(drive, &pc);
3115	if (retval)
3116		return retval;
3117	return 0;
3118}
3119
3120/*
3121 *	Our special ide-tape ioctl's.
3122 *
3123 *	Currently there aren't any ioctl's.
3124 *	mtio.h compatible commands should be issued to the character device
3125 *	interface.
3126 */
3127static int idetape_blkdev_ioctl(ide_drive_t *drive, unsigned int cmd, unsigned long arg)
3128{
3129	idetape_tape_t *tape = drive->driver_data;
3130	idetape_config_t config;
3131	void __user *argp = (void __user *)arg;
3132
3133#if IDETAPE_DEBUG_LOG
3134	if (tape->debug_level >= 4)
3135		printk(KERN_INFO "ide-tape: Reached idetape_blkdev_ioctl\n");
3136#endif /* IDETAPE_DEBUG_LOG */
3137	switch (cmd) {
3138		case 0x0340:
3139			if (copy_from_user(&config, argp, sizeof (idetape_config_t)))
3140				return -EFAULT;
3141			tape->best_dsc_rw_frequency = config.dsc_rw_frequency;
3142			tape->max_stages = config.nr_stages;
3143			break;
3144		case 0x0350:
3145			config.dsc_rw_frequency = (int) tape->best_dsc_rw_frequency;
3146			config.nr_stages = tape->max_stages;
3147			if (copy_to_user(argp, &config, sizeof (idetape_config_t)))
3148				return -EFAULT;
3149			break;
3150		default:
3151			return -EIO;
3152	}
3153	return 0;
3154}
3155
3156/*
3157 *	idetape_space_over_filemarks is now a bit more complicated than just
3158 *	passing the command to the tape since we may have crossed some
3159 *	filemarks during our pipelined read-ahead mode.
3160 *
3161 *	As a minor side effect, the pipeline enables us to support MTFSFM when
3162 *	the filemark is in our internal pipeline even if the tape doesn't
3163 *	support spacing over filemarks in the reverse direction.
3164 */
3165static int idetape_space_over_filemarks (ide_drive_t *drive,short mt_op,int mt_count)
3166{
3167	idetape_tape_t *tape = drive->driver_data;
3168	idetape_pc_t pc;
3169	unsigned long flags;
3170	int retval,count=0;
3171
3172	if (mt_count == 0)
3173		return 0;
3174	if (MTBSF == mt_op || MTBSFM == mt_op) {
3175		if (!tape->capabilities.sprev)
3176			return -EIO;
3177		mt_count = - mt_count;
3178	}
3179
3180	if (tape->chrdev_direction == idetape_direction_read) {
3181		/*
3182		 *	We have a read-ahead buffer. Scan it for crossed
3183		 *	filemarks.
3184		 */
3185		tape->merge_stage_size = 0;
3186		if (test_and_clear_bit(IDETAPE_FILEMARK, &tape->flags))
3187			++count;
3188		while (tape->first_stage != NULL) {
3189			if (count == mt_count) {
3190				if (mt_op == MTFSFM)
3191					set_bit(IDETAPE_FILEMARK, &tape->flags);
3192				return 0;
3193			}
3194			spin_lock_irqsave(&tape->spinlock, flags);
3195			if (tape->first_stage == tape->active_stage) {
3196				/*
3197				 *	We have reached the active stage in the read pipeline.
3198				 *	There is no point in allowing the drive to continue
3199				 *	reading any farther, so we stop the pipeline.
3200				 *
3201				 *	This section should be moved to a separate subroutine,
3202				 *	because a similar function is performed in
3203				 *	__idetape_discard_read_pipeline(), for example.
3204				 */
3205				tape->next_stage = NULL;
3206				spin_unlock_irqrestore(&tape->spinlock, flags);
3207				idetape_wait_first_stage(drive);
3208				tape->next_stage = tape->first_stage->next;
3209			} else
3210				spin_unlock_irqrestore(&tape->spinlock, flags);
3211			if (tape->first_stage->rq.errors == IDETAPE_ERROR_FILEMARK)
3212				++count;
3213			idetape_remove_stage_head(drive);
3214		}
3215		idetape_discard_read_pipeline(drive, 0);
3216	}
3217
3218	/*
3219	 *	The filemark was not found in our internal pipeline.
3220	 *	Now we can issue the space command.
3221	 */
3222	switch (mt_op) {
3223		case MTFSF:
3224		case MTBSF:
3225			idetape_create_space_cmd(&pc,mt_count-count,IDETAPE_SPACE_OVER_FILEMARK);
3226			return (idetape_queue_pc_tail(drive, &pc));
3227		case MTFSFM:
3228		case MTBSFM:
3229			if (!tape->capabilities.sprev)
3230				return (-EIO);
3231			retval = idetape_space_over_filemarks(drive, MTFSF, mt_count-count);
3232			if (retval) return (retval);
3233			count = (MTBSFM == mt_op ? 1 : -1);
3234			return (idetape_space_over_filemarks(drive, MTFSF, count));
3235		default:
3236			printk(KERN_ERR "ide-tape: MTIO operation %d not supported\n",mt_op);
3237			return (-EIO);
3238	}
3239}
3240
3241
3242/*
3243 *	Our character device read / write functions.
3244 *
3245 *	The tape is optimized to maximize throughput when it is transferring
3246 *	an integral number of the "continuous transfer limit", which is
3247 *	a parameter of the specific tape (26 KB on my particular tape).
3248 *      (32 kB for Onstream)
3249 *
3250 *	As of version 1.3 of the driver, the character device provides an
3251 *	abstract continuous view of the media - any mix of block sizes (even 1
3252 *	byte) on the same backup/restore procedure is supported. The driver
3253 *	will internally convert the requests to the recommended transfer unit,
3254 *	so that an unmatch between the user's block size to the recommended
3255 *	size will only result in a (slightly) increased driver overhead, but
3256 *	will no longer hit performance.
3257 *      This is not applicable to Onstream.
3258 */
3259static ssize_t idetape_chrdev_read (struct file *file, char __user *buf,
3260				    size_t count, loff_t *ppos)
3261{
3262	struct ide_tape_obj *tape = ide_tape_f(file);
3263	ide_drive_t *drive = tape->drive;
3264	ssize_t bytes_read,temp, actually_read = 0, rc;
3265	ssize_t ret = 0;
3266
3267#if IDETAPE_DEBUG_LOG
3268	if (tape->debug_level >= 3)
3269		printk(KERN_INFO "ide-tape: Reached idetape_chrdev_read, count %Zd\n", count);
3270#endif /* IDETAPE_DEBUG_LOG */
3271
3272	if (tape->chrdev_direction != idetape_direction_read) {
3273		if (test_bit(IDETAPE_DETECT_BS, &tape->flags))
3274			if (count > tape->tape_block_size &&
3275			    (count % tape->tape_block_size) == 0)
3276				tape->user_bs_factor = count / tape->tape_block_size;
3277	}
3278	if ((rc = idetape_initiate_read(drive, tape->max_stages)) < 0)
3279		return rc;
3280	if (count == 0)
3281		return (0);
3282	if (tape->merge_stage_size) {
3283		actually_read = min((unsigned int)(tape->merge_stage_size), (unsigned int)count);
3284		if (idetape_copy_stage_to_user(tape, buf, tape->merge_stage, actually_read))
3285			ret = -EFAULT;
3286		buf += actually_read;
3287		tape->merge_stage_size -= actually_read;
3288		count -= actually_read;
3289	}
3290	while (count >= tape->stage_size) {
3291		bytes_read = idetape_add_chrdev_read_request(drive, tape->capabilities.ctl);
3292		if (bytes_read <= 0)
3293			goto finish;
3294		if (idetape_copy_stage_to_user(tape, buf, tape->merge_stage, bytes_read))
3295			ret = -EFAULT;
3296		buf += bytes_read;
3297		count -= bytes_read;
3298		actually_read += bytes_read;
3299	}
3300	if (count) {
3301		bytes_read = idetape_add_chrdev_read_request(drive, tape->capabilities.ctl);
3302		if (bytes_read <= 0)
3303			goto finish;
3304		temp = min((unsigned long)count, (unsigned long)bytes_read);
3305		if (idetape_copy_stage_to_user(tape, buf, tape->merge_stage, temp))
3306			ret = -EFAULT;
3307		actually_read += temp;
3308		tape->merge_stage_size = bytes_read-temp;
3309	}
3310finish:
3311	if (!actually_read && test_bit(IDETAPE_FILEMARK, &tape->flags)) {
3312#if IDETAPE_DEBUG_LOG
3313		if (tape->debug_level >= 2)
3314			printk(KERN_INFO "ide-tape: %s: spacing over filemark\n", tape->name);
3315#endif
3316		idetape_space_over_filemarks(drive, MTFSF, 1);
3317		return 0;
3318	}
3319
3320	return (ret) ? ret : actually_read;
3321}
3322
3323static ssize_t idetape_chrdev_write (struct file *file, const char __user *buf,
3324				     size_t count, loff_t *ppos)
3325{
3326	struct ide_tape_obj *tape = ide_tape_f(file);
3327	ide_drive_t *drive = tape->drive;
3328	ssize_t actually_written = 0;
3329	ssize_t ret = 0;
3330
3331	/* The drive is write protected. */
3332	if (tape->write_prot)
3333		return -EACCES;
3334
3335#if IDETAPE_DEBUG_LOG
3336	if (tape->debug_level >= 3)
3337		printk(KERN_INFO "ide-tape: Reached idetape_chrdev_write, "
3338			"count %Zd\n", count);
3339#endif /* IDETAPE_DEBUG_LOG */
3340
3341	/* Initialize write operation */
3342	if (tape->chrdev_direction != idetape_direction_write) {
3343		if (tape->chrdev_direction == idetape_direction_read)
3344			idetape_discard_read_pipeline(drive, 1);
3345#if IDETAPE_DEBUG_BUGS
3346		if (tape->merge_stage || tape->merge_stage_size) {
3347			printk(KERN_ERR "ide-tape: merge_stage_size "
3348				"should be 0 now\n");
3349			tape->merge_stage_size = 0;
3350		}
3351#endif /* IDETAPE_DEBUG_BUGS */
3352		if ((tape->merge_stage = __idetape_kmalloc_stage(tape, 0, 0)) == NULL)
3353			return -ENOMEM;
3354		tape->chrdev_direction = idetape_direction_write;
3355		idetape_init_merge_stage(tape);
3356
3357		/*
3358		 *	Issue a write 0 command to ensure that DSC handshake
3359		 *	is switched from completion mode to buffer available
3360		 *	mode.
3361		 *	No point in issuing this if DSC overlap isn't supported,
3362		 *	some drives (Seagate STT3401A) will return an error.
3363		 */
3364		if (drive->dsc_overlap) {
3365			ssize_t retval = idetape_queue_rw_tail(drive, REQ_IDETAPE_WRITE, 0, tape->merge_stage->bh);
3366			if (retval < 0) {
3367				__idetape_kfree_stage(tape->merge_stage);
3368				tape->merge_stage = NULL;
3369				tape->chrdev_direction = idetape_direction_none;
3370				return retval;
3371			}
3372		}
3373	}
3374	if (count == 0)
3375		return (0);
3376	if (tape->restart_speed_control_req)
3377		idetape_restart_speed_control(drive);
3378	if (tape->merge_stage_size) {
3379#if IDETAPE_DEBUG_BUGS
3380		if (tape->merge_stage_size >= tape->stage_size) {
3381			printk(KERN_ERR "ide-tape: bug: merge buffer too big\n");
3382			tape->merge_stage_size = 0;
3383		}
3384#endif /* IDETAPE_DEBUG_BUGS */
3385		actually_written = min((unsigned int)(tape->stage_size - tape->merge_stage_size), (unsigned int)count);
3386		if (idetape_copy_stage_from_user(tape, tape->merge_stage, buf, actually_written))
3387				ret = -EFAULT;
3388		buf += actually_written;
3389		tape->merge_stage_size += actually_written;
3390		count -= actually_written;
3391
3392		if (tape->merge_stage_size == tape->stage_size) {
3393			ssize_t retval;
3394			tape->merge_stage_size = 0;
3395			retval = idetape_add_chrdev_write_request(drive, tape->capabilities.ctl);
3396			if (retval <= 0)
3397				return (retval);
3398		}
3399	}
3400	while (count >= tape->stage_size) {
3401		ssize_t retval;
3402		if (idetape_copy_stage_from_user(tape, tape->merge_stage, buf, tape->stage_size))
3403			ret = -EFAULT;
3404		buf += tape->stage_size;
3405		count -= tape->stage_size;
3406		retval = idetape_add_chrdev_write_request(drive, tape->capabilities.ctl);
3407		actually_written += tape->stage_size;
3408		if (retval <= 0)
3409			return (retval);
3410	}
3411	if (count) {
3412		actually_written += count;
3413		if (idetape_copy_stage_from_user(tape, tape->merge_stage, buf, count))
3414			ret = -EFAULT;
3415		tape->merge_stage_size += count;
3416	}
3417	return (ret) ? ret : actually_written;
3418}
3419
3420static int idetape_write_filemark (ide_drive_t *drive)
3421{
3422	idetape_pc_t pc;
3423
3424	/* Write a filemark */
3425	idetape_create_write_filemark_cmd(drive, &pc, 1);
3426	if (idetape_queue_pc_tail(drive, &pc)) {
3427		printk(KERN_ERR "ide-tape: Couldn't write a filemark\n");
3428		return -EIO;
3429	}
3430	return 0;
3431}
3432
3433/*
3434 *	idetape_mtioctop is called from idetape_chrdev_ioctl when
3435 *	the general mtio MTIOCTOP ioctl is requested.
3436 *
3437 *	We currently support the following mtio.h operations:
3438 *
3439 *	MTFSF	-	Space over mt_count filemarks in the positive direction.
3440 *			The tape is positioned after the last spaced filemark.
3441 *
3442 *	MTFSFM	-	Same as MTFSF, but the tape is positioned before the
3443 *			last filemark.
3444 *
3445 *	MTBSF	-	Steps background over mt_count filemarks, tape is
3446 *			positioned before the last filemark.
3447 *
3448 *	MTBSFM	-	Like MTBSF, only tape is positioned after the last filemark.
3449 *
3450 *	Note:
3451 *
3452 *		MTBSF and MTBSFM are not supported when the tape doesn't
3453 *		support spacing over filemarks in the reverse direction.
3454 *		In this case, MTFSFM is also usually not supported (it is
3455 *		supported in the rare case in which we crossed the filemark
3456 *		during our read-ahead pipelined operation mode).
3457 *
3458 *	MTWEOF	-	Writes mt_count filemarks. Tape is positioned after
3459 *			the last written filemark.
3460 *
3461 *	MTREW	-	Rewinds tape.
3462 *
3463 *	MTLOAD	-	Loads the tape.
3464 *
3465 *	MTOFFL	-	Puts the tape drive "Offline": Rewinds the tape and
3466 *	MTUNLOAD	prevents further access until the media is replaced.
3467 *
3468 *	MTNOP	-	Flushes tape buffers.
3469 *
3470 *	MTRETEN	-	Retension media. This typically consists of one end
3471 *			to end pass on the media.
3472 *
3473 *	MTEOM	-	Moves to the end of recorded data.
3474 *
3475 *	MTERASE	-	Erases tape.
3476 *
3477 *	MTSETBLK - 	Sets the user block size to mt_count bytes. If
3478 *			mt_count is 0, we will attempt to autodetect
3479 *			the block size.
3480 *
3481 *	MTSEEK	-	Positions the tape in a specific block number, where
3482 *			each block is assumed to contain which user_block_size
3483 *			bytes.
3484 *
3485 *	MTSETPART - 	Switches to another tape partition.
3486 *
3487 *	MTLOCK - 	Locks the tape door.
3488 *
3489 *	MTUNLOCK - 	Unlocks the tape door.
3490 *
3491 *	The following commands are currently not supported:
3492 *
3493 *	MTFSS, MTBSS, MTWSM, MTSETDENSITY,
3494 *	MTSETDRVBUFFER, MT_ST_BOOLEANS, MT_ST_WRITE_THRESHOLD.
3495 */
3496static int idetape_mtioctop (ide_drive_t *drive,short mt_op,int mt_count)
3497{
3498	idetape_tape_t *tape = drive->driver_data;
3499	idetape_pc_t pc;
3500	int i,retval;
3501
3502#if IDETAPE_DEBUG_LOG
3503	if (tape->debug_level >= 1)
3504		printk(KERN_INFO "ide-tape: Handling MTIOCTOP ioctl: "
3505			"mt_op=%d, mt_count=%d\n", mt_op, mt_count);
3506#endif /* IDETAPE_DEBUG_LOG */
3507	/*
3508	 *	Commands which need our pipelined read-ahead stages.
3509	 */
3510	switch (mt_op) {
3511		case MTFSF:
3512		case MTFSFM:
3513		case MTBSF:
3514		case MTBSFM:
3515			if (!mt_count)
3516				return (0);
3517			return (idetape_space_over_filemarks(drive,mt_op,mt_count));
3518		default:
3519			break;
3520	}
3521	switch (mt_op) {
3522		case MTWEOF:
3523			if (tape->write_prot)
3524				return -EACCES;
3525			idetape_discard_read_pipeline(drive, 1);
3526			for (i = 0; i < mt_count; i++) {
3527				retval = idetape_write_filemark(drive);
3528				if (retval)
3529					return retval;
3530			}
3531			return (0);
3532		case MTREW:
3533			idetape_discard_read_pipeline(drive, 0);
3534			if (idetape_rewind_tape(drive))
3535				return -EIO;
3536			return 0;
3537		case MTLOAD:
3538			idetape_discard_read_pipeline(drive, 0);
3539			idetape_create_load_unload_cmd(drive, &pc, IDETAPE_LU_LOAD_MASK);
3540			return (idetape_queue_pc_tail(drive, &pc));
3541		case MTUNLOAD:
3542		case MTOFFL:
3543			/*
3544			 * If door is locked, attempt to unlock before
3545			 * attempting to eject.
3546			 */
3547			if (tape->door_locked) {
3548				if (idetape_create_prevent_cmd(drive, &pc, 0))
3549					if (!idetape_queue_pc_tail(drive, &pc))
3550						tape->door_locked = DOOR_UNLOCKED;
3551			}
3552			idetape_discard_read_pipeline(drive, 0);
3553			idetape_create_load_unload_cmd(drive, &pc,!IDETAPE_LU_LOAD_MASK);
3554			retval = idetape_queue_pc_tail(drive, &pc);
3555			if (!retval)
3556				clear_bit(IDETAPE_MEDIUM_PRESENT, &tape->flags);
3557			return retval;
3558		case MTNOP:
3559			idetape_discard_read_pipeline(drive, 0);
3560			return (idetape_flush_tape_buffers(drive));
3561		case MTRETEN:
3562			idetape_discard_read_pipeline(drive, 0);
3563			idetape_create_load_unload_cmd(drive, &pc,IDETAPE_LU_RETENSION_MASK | IDETAPE_LU_LOAD_MASK);
3564			return (idetape_queue_pc_tail(drive, &pc));
3565		case MTEOM:
3566			idetape_create_space_cmd(&pc, 0, IDETAPE_SPACE_TO_EOD);
3567			return (idetape_queue_pc_tail(drive, &pc));
3568		case MTERASE:
3569			(void) idetape_rewind_tape(drive);
3570			idetape_create_erase_cmd(&pc);
3571			return (idetape_queue_pc_tail(drive, &pc));
3572		case MTSETBLK:
3573			if (mt_count) {
3574				if (mt_count < tape->tape_block_size || mt_count % tape->tape_block_size)
3575					return -EIO;
3576				tape->user_bs_factor = mt_count / tape->tape_block_size;
3577				clear_bit(IDETAPE_DETECT_BS, &tape->flags);
3578			} else
3579				set_bit(IDETAPE_DETECT_BS, &tape->flags);
3580			return 0;
3581		case MTSEEK:
3582			idetape_discard_read_pipeline(drive, 0);
3583			return idetape_position_tape(drive, mt_count * tape->user_bs_factor, tape->partition, 0);
3584		case MTSETPART:
3585			idetape_discard_read_pipeline(drive, 0);
3586			return (idetape_position_tape(drive, 0, mt_count, 0));
3587		case MTFSR:
3588		case MTBSR:
3589		case MTLOCK:
3590			if (!idetape_create_prevent_cmd(drive, &pc, 1))
3591				return 0;
3592			retval = idetape_queue_pc_tail(drive, &pc);
3593			if (retval) return retval;
3594			tape->door_locked = DOOR_EXPLICITLY_LOCKED;
3595			return 0;
3596		case MTUNLOCK:
3597			if (!idetape_create_prevent_cmd(drive, &pc, 0))
3598				return 0;
3599			retval = idetape_queue_pc_tail(drive, &pc);
3600			if (retval) return retval;
3601			tape->door_locked = DOOR_UNLOCKED;
3602			return 0;
3603		default:
3604			printk(KERN_ERR "ide-tape: MTIO operation %d not "
3605				"supported\n", mt_op);
3606			return (-EIO);
3607	}
3608}
3609
3610/*
3611 *	Our character device ioctls.
3612 *
3613 *	General mtio.h magnetic io commands are supported here, and not in
3614 *	the corresponding block interface.
3615 *
3616 *	The following ioctls are supported:
3617 *
3618 *	MTIOCTOP -	Refer to idetape_mtioctop for detailed description.
3619 *
3620 *	MTIOCGET - 	The mt_dsreg field in the returned mtget structure
3621 *			will be set to (user block size in bytes <<
3622 *			MT_ST_BLKSIZE_SHIFT) & MT_ST_BLKSIZE_MASK.
3623 *
3624 *			The mt_blkno is set to the current user block number.
3625 *			The other mtget fields are not supported.
3626 *
3627 *	MTIOCPOS -	The current tape "block position" is returned. We
3628 *			assume that each block contains user_block_size
3629 *			bytes.
3630 *
3631 *	Our own ide-tape ioctls are supported on both interfaces.
3632 */
3633static int idetape_chrdev_ioctl (struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
3634{
3635	struct ide_tape_obj *tape = ide_tape_f(file);
3636	ide_drive_t *drive = tape->drive;
3637	struct mtop mtop;
3638	struct mtget mtget;
3639	struct mtpos mtpos;
3640	int block_offset = 0, position = tape->first_frame_position;
3641	void __user *argp = (void __user *)arg;
3642
3643#if IDETAPE_DEBUG_LOG
3644	if (tape->debug_level >= 3)
3645		printk(KERN_INFO "ide-tape: Reached idetape_chrdev_ioctl, "
3646			"cmd=%u\n", cmd);
3647#endif /* IDETAPE_DEBUG_LOG */
3648
3649	tape->restart_speed_control_req = 1;
3650	if (tape->chrdev_direction == idetape_direction_write) {
3651		idetape_empty_write_pipeline(drive);
3652		idetape_flush_tape_buffers(drive);
3653	}
3654	if (cmd == MTIOCGET || cmd == MTIOCPOS) {
3655		block_offset = idetape_pipeline_size(drive) / (tape->tape_block_size * tape->user_bs_factor);
3656		if ((position = idetape_read_position(drive)) < 0)
3657			return -EIO;
3658	}
3659	switch (cmd) {
3660		case MTIOCTOP:
3661			if (copy_from_user(&mtop, argp, sizeof (struct mtop)))
3662				return -EFAULT;
3663			return (idetape_mtioctop(drive,mtop.mt_op,mtop.mt_count));
3664		case MTIOCGET:
3665			memset(&mtget, 0, sizeof (struct mtget));
3666			mtget.mt_type = MT_ISSCSI2;
3667			mtget.mt_blkno = position / tape->user_bs_factor - block_offset;
3668			mtget.mt_dsreg = ((tape->tape_block_size * tape->user_bs_factor) << MT_ST_BLKSIZE_SHIFT) & MT_ST_BLKSIZE_MASK;
3669			if (tape->drv_write_prot) {
3670				mtget.mt_gstat |= GMT_WR_PROT(0xffffffff);
3671			}
3672			if (copy_to_user(argp, &mtget, sizeof(struct mtget)))
3673				return -EFAULT;
3674			return 0;
3675		case MTIOCPOS:
3676			mtpos.mt_blkno = position / tape->user_bs_factor - block_offset;
3677			if (copy_to_user(argp, &mtpos, sizeof(struct mtpos)))
3678				return -EFAULT;
3679			return 0;
3680		default:
3681			if (tape->chrdev_direction == idetape_direction_read)
3682				idetape_discard_read_pipeline(drive, 1);
3683			return idetape_blkdev_ioctl(drive, cmd, arg);
3684	}
3685}
3686
3687static void idetape_get_blocksize_from_block_descriptor(ide_drive_t *drive);
3688
3689/*
3690 *	Our character device open function.
3691 */
3692static int idetape_chrdev_open (struct inode *inode, struct file *filp)
3693{
3694	unsigned int minor = iminor(inode), i = minor & ~0xc0;
3695	ide_drive_t *drive;
3696	idetape_tape_t *tape;
3697	idetape_pc_t pc;
3698	int retval;
3699
3700	/*
3701	 * We really want to do nonseekable_open(inode, filp); here, but some
3702	 * versions of tar incorrectly call lseek on tapes and bail out if that
3703	 * fails.  So we disallow pread() and pwrite(), but permit lseeks.
3704	 */
3705	filp->f_mode &= ~(FMODE_PREAD | FMODE_PWRITE);
3706
3707#if IDETAPE_DEBUG_LOG
3708	printk(KERN_INFO "ide-tape: Reached idetape_chrdev_open\n");
3709#endif /* IDETAPE_DEBUG_LOG */
3710
3711	if (i >= MAX_HWIFS * MAX_DRIVES)
3712		return -ENXIO;
3713
3714	if (!(tape = ide_tape_chrdev_get(i)))
3715		return -ENXIO;
3716
3717	drive = tape->drive;
3718
3719	filp->private_data = tape;
3720
3721	if (test_and_set_bit(IDETAPE_BUSY, &tape->flags)) {
3722		retval = -EBUSY;
3723		goto out_put_tape;
3724	}
3725
3726	retval = idetape_wait_ready(drive, 60 * HZ);
3727	if (retval) {
3728		clear_bit(IDETAPE_BUSY, &tape->flags);
3729		printk(KERN_ERR "ide-tape: %s: drive not ready\n", tape->name);
3730		goto out_put_tape;
3731	}
3732
3733	idetape_read_position(drive);
3734	if (!test_bit(IDETAPE_ADDRESS_VALID, &tape->flags))
3735		(void)idetape_rewind_tape(drive);
3736
3737	if (tape->chrdev_direction != idetape_direction_read)
3738		clear_bit(IDETAPE_PIPELINE_ERROR, &tape->flags);
3739
3740	/* Read block size and write protect status from drive. */
3741	idetape_get_blocksize_from_block_descriptor(drive);
3742
3743	/* Set write protect flag if device is opened as read-only. */
3744	if ((filp->f_flags & O_ACCMODE) == O_RDONLY)
3745		tape->write_prot = 1;
3746	else
3747		tape->write_prot = tape->drv_write_prot;
3748
3749	/* Make sure drive isn't write protected if user wants to write. */
3750	if (tape->write_prot) {
3751		if ((filp->f_flags & O_ACCMODE) == O_WRONLY ||
3752		    (filp->f_flags & O_ACCMODE) == O_RDWR) {
3753			clear_bit(IDETAPE_BUSY, &tape->flags);
3754			retval = -EROFS;
3755			goto out_put_tape;
3756		}
3757	}
3758
3759	/*
3760	 * Lock the tape drive door so user can't eject.
3761	 */
3762	if (tape->chrdev_direction == idetape_direction_none) {
3763		if (idetape_create_prevent_cmd(drive, &pc, 1)) {
3764			if (!idetape_queue_pc_tail(drive, &pc)) {
3765				if (tape->door_locked != DOOR_EXPLICITLY_LOCKED)
3766					tape->door_locked = DOOR_LOCKED;
3767			}
3768		}
3769	}
3770	idetape_restart_speed_control(drive);
3771	tape->restart_speed_control_req = 0;
3772	return 0;
3773
3774out_put_tape:
3775	ide_tape_put(tape);
3776	return retval;
3777}
3778
3779static void idetape_write_release (ide_drive_t *drive, unsigned int minor)
3780{
3781	idetape_tape_t *tape = drive->driver_data;
3782
3783	idetape_empty_write_pipeline(drive);
3784	tape->merge_stage = __idetape_kmalloc_stage(tape, 1, 0);
3785	if (tape->merge_stage != NULL) {
3786		idetape_pad_zeros(drive, tape->tape_block_size * (tape->user_bs_factor - 1));
3787		__idetape_kfree_stage(tape->merge_stage);
3788		tape->merge_stage = NULL;
3789	}
3790	idetape_write_filemark(drive);
3791	idetape_flush_tape_buffers(drive);
3792	idetape_flush_tape_buffers(drive);
3793}
3794
3795/*
3796 *	Our character device release function.
3797 */
3798static int idetape_chrdev_release (struct inode *inode, struct file *filp)
3799{
3800	struct ide_tape_obj *tape = ide_tape_f(filp);
3801	ide_drive_t *drive = tape->drive;
3802	idetape_pc_t pc;
3803	unsigned int minor = iminor(inode);
3804
3805	lock_kernel();
3806	tape = drive->driver_data;
3807#if IDETAPE_DEBUG_LOG
3808	if (tape->debug_level >= 3)
3809		printk(KERN_INFO "ide-tape: Reached idetape_chrdev_release\n");
3810#endif /* IDETAPE_DEBUG_LOG */
3811
3812	if (tape->chrdev_direction == idetape_direction_write)
3813		idetape_write_release(drive, minor);
3814	if (tape->chrdev_direction == idetape_direction_read) {
3815		if (minor < 128)
3816			idetape_discard_read_pipeline(drive, 1);
3817		else
3818			idetape_wait_for_pipeline(drive);
3819	}
3820	if (tape->cache_stage != NULL) {
3821		__idetape_kfree_stage(tape->cache_stage);
3822		tape->cache_stage = NULL;
3823	}
3824	if (minor < 128 && test_bit(IDETAPE_MEDIUM_PRESENT, &tape->flags))
3825		(void) idetape_rewind_tape(drive);
3826	if (tape->chrdev_direction == idetape_direction_none) {
3827		if (tape->door_locked == DOOR_LOCKED) {
3828			if (idetape_create_prevent_cmd(drive, &pc, 0)) {
3829				if (!idetape_queue_pc_tail(drive, &pc))
3830					tape->door_locked = DOOR_UNLOCKED;
3831			}
3832		}
3833	}
3834	clear_bit(IDETAPE_BUSY, &tape->flags);
3835	ide_tape_put(tape);
3836	unlock_kernel();
3837	return 0;
3838}
3839
3840/*
3841 *	idetape_identify_device is called to check the contents of the
3842 *	ATAPI IDENTIFY command results. We return:
3843 *
3844 *	1	If the tape can be supported by us, based on the information
3845 *		we have so far.
3846 *
3847 *	0 	If this tape driver is not currently supported by us.
3848 */
3849static int idetape_identify_device (ide_drive_t *drive)
3850{
3851	struct idetape_id_gcw gcw;
3852	struct hd_driveid *id = drive->id;
3853
3854	if (drive->id_read == 0)
3855		return 1;
3856
3857	*((unsigned short *) &gcw) = id->config;
3858
3859#if IDETAPE_DEBUG_INFO
3860	printk(KERN_INFO "ide-tape: Dumping ATAPI Identify Device tape parameters\n");
3861	printk(KERN_INFO "ide-tape: Protocol Type: ");
3862	switch (gcw.protocol) {
3863		case 0: case 1: printk("ATA\n");break;
3864		case 2:	printk("ATAPI\n");break;
3865		case 3: printk("Reserved (Unknown to ide-tape)\n");break;
3866	}
3867	printk(KERN_INFO "ide-tape: Device Type: %x - ",gcw.device_type);
3868	switch (gcw.device_type) {
3869		case 0: printk("Direct-access Device\n");break;
3870		case 1: printk("Streaming Tape Device\n");break;
3871		case 2: case 3: case 4: printk("Reserved\n");break;
3872		case 5: printk("CD-ROM Device\n");break;
3873		case 6: printk("Reserved\n");
3874		case 7: printk("Optical memory Device\n");break;
3875		case 0x1f: printk("Unknown or no Device type\n");break;
3876		default: printk("Reserved\n");
3877	}
3878	printk(KERN_INFO "ide-tape: Removable: %s",gcw.removable ? "Yes\n":"No\n");
3879	printk(KERN_INFO "ide-tape: Command Packet DRQ Type: ");
3880	switch (gcw.drq_type) {
3881		case 0: printk("Microprocessor DRQ\n");break;
3882		case 1: printk("Interrupt DRQ\n");break;
3883		case 2: printk("Accelerated DRQ\n");break;
3884		case 3: printk("Reserved\n");break;
3885	}
3886	printk(KERN_INFO "ide-tape: Command Packet Size: ");
3887	switch (gcw.packet_size) {
3888		case 0: printk("12 bytes\n");break;
3889		case 1: printk("16 bytes\n");break;
3890		default: printk("Reserved\n");break;
3891	}
3892#endif /* IDETAPE_DEBUG_INFO */
3893
3894	/* Check that we can support this device */
3895
3896	if (gcw.protocol !=2 )
3897		printk(KERN_ERR "ide-tape: Protocol is not ATAPI\n");
3898	else if (gcw.device_type != 1)
3899		printk(KERN_ERR "ide-tape: Device type is not set to tape\n");
3900	else if (!gcw.removable)
3901		printk(KERN_ERR "ide-tape: The removable flag is not set\n");
3902	else if (gcw.packet_size != 0) {
3903		printk(KERN_ERR "ide-tape: Packet size is not 12 bytes long\n");
3904		if (gcw.packet_size == 1)
3905			printk(KERN_ERR "ide-tape: Sorry, padding to 16 bytes is still not supported\n");
3906	} else
3907		return 1;
3908	return 0;
3909}
3910
3911/*
3912 * Use INQUIRY to get the firmware revision
3913 */
3914static void idetape_get_inquiry_results (ide_drive_t *drive)
3915{
3916	char *r;
3917	idetape_tape_t *tape = drive->driver_data;
3918	idetape_pc_t pc;
3919	idetape_inquiry_result_t *inquiry;
3920
3921	idetape_create_inquiry_cmd(&pc);
3922	if (idetape_queue_pc_tail(drive, &pc)) {
3923		printk(KERN_ERR "ide-tape: %s: can't get INQUIRY results\n", tape->name);
3924		return;
3925	}
3926	inquiry = (idetape_inquiry_result_t *) pc.buffer;
3927	memcpy(tape->vendor_id, inquiry->vendor_id, 8);
3928	memcpy(tape->product_id, inquiry->product_id, 16);
3929	memcpy(tape->firmware_revision, inquiry->revision_level, 4);
3930	ide_fixstring(tape->vendor_id, 10, 0);
3931	ide_fixstring(tape->product_id, 18, 0);
3932	ide_fixstring(tape->firmware_revision, 6, 0);
3933	r = tape->firmware_revision;
3934	if (*(r + 1) == '.')
3935		tape->firmware_revision_num = (*r - '0') * 100 + (*(r + 2) - '0') * 10 + *(r + 3) - '0';
3936	printk(KERN_INFO "ide-tape: %s <-> %s: %s %s rev %s\n", drive->name, tape->name, tape->vendor_id, tape->product_id, tape->firmware_revision);
3937}
3938
3939/*
3940 *	idetape_get_mode_sense_results asks the tape about its various
3941 *	parameters. In particular, we will adjust our data transfer buffer
3942 *	size to the recommended value as returned by the tape.
3943 */
3944static void idetape_get_mode_sense_results (ide_drive_t *drive)
3945{
3946	idetape_tape_t *tape = drive->driver_data;
3947	idetape_pc_t pc;
3948	idetape_mode_parameter_header_t *header;
3949	idetape_capabilities_page_t *capabilities;
3950
3951	idetape_create_mode_sense_cmd(&pc, IDETAPE_CAPABILITIES_PAGE);
3952	if (idetape_queue_pc_tail(drive, &pc)) {
3953		printk(KERN_ERR "ide-tape: Can't get tape parameters - assuming some default values\n");
3954		tape->tape_block_size = 512;
3955		tape->capabilities.ctl = 52;
3956		tape->capabilities.speed = 450;
3957		tape->capabilities.buffer_size = 6 * 52;
3958		return;
3959	}
3960	header = (idetape_mode_parameter_header_t *) pc.buffer;
3961	capabilities = (idetape_capabilities_page_t *) (pc.buffer + sizeof(idetape_mode_parameter_header_t) + header->bdl);
3962
3963	capabilities->max_speed = ntohs(capabilities->max_speed);
3964	capabilities->ctl = ntohs(capabilities->ctl);
3965	capabilities->speed = ntohs(capabilities->speed);
3966	capabilities->buffer_size = ntohs(capabilities->buffer_size);
3967
3968	if (!capabilities->speed) {
3969		printk(KERN_INFO "ide-tape: %s: overriding capabilities->speed (assuming 650KB/sec)\n", drive->name);
3970		capabilities->speed = 650;
3971	}
3972	if (!capabilities->max_speed) {
3973		printk(KERN_INFO "ide-tape: %s: overriding capabilities->max_speed (assuming 650KB/sec)\n", drive->name);
3974		capabilities->max_speed = 650;
3975	}
3976
3977	tape->capabilities = *capabilities;		/* Save us a copy */
3978	if (capabilities->blk512)
3979		tape->tape_block_size = 512;
3980	else if (capabilities->blk1024)
3981		tape->tape_block_size = 1024;
3982
3983#if IDETAPE_DEBUG_INFO
3984	printk(KERN_INFO "ide-tape: Dumping the results of the MODE SENSE packet command\n");
3985	printk(KERN_INFO "ide-tape: Mode Parameter Header:\n");
3986	printk(KERN_INFO "ide-tape: Mode Data Length - %d\n",header->mode_data_length);
3987	printk(KERN_INFO "ide-tape: Medium Type - %d\n",header->medium_type);
3988	printk(KERN_INFO "ide-tape: Device Specific Parameter - %d\n",header->dsp);
3989	printk(KERN_INFO "ide-tape: Block Descriptor Length - %d\n",header->bdl);
3990
3991	printk(KERN_INFO "ide-tape: Capabilities and Mechanical Status Page:\n");
3992	printk(KERN_INFO "ide-tape: Page code - %d\n",capabilities->page_code);
3993	printk(KERN_INFO "ide-tape: Page length - %d\n",capabilities->page_length);
3994	printk(KERN_INFO "ide-tape: Read only - %s\n",capabilities->ro ? "Yes":"No");
3995	printk(KERN_INFO "ide-tape: Supports reverse space - %s\n",capabilities->sprev ? "Yes":"No");
3996	printk(KERN_INFO "ide-tape: Supports erase initiated formatting - %s\n",capabilities->efmt ? "Yes":"No");
3997	printk(KERN_INFO "ide-tape: Supports QFA two Partition format - %s\n",capabilities->qfa ? "Yes":"No");
3998	printk(KERN_INFO "ide-tape: Supports locking the medium - %s\n",capabilities->lock ? "Yes":"No");
3999	printk(KERN_INFO "ide-tape: The volume is currently locked - %s\n",capabilities->locked ? "Yes":"No");
4000	printk(KERN_INFO "ide-tape: The device defaults in the prevent state - %s\n",capabilities->prevent ? "Yes":"No");
4001	printk(KERN_INFO "ide-tape: Supports ejecting the medium - %s\n",capabilities->eject ? "Yes":"No");
4002	printk(KERN_INFO "ide-tape: Supports error correction - %s\n",capabilities->ecc ? "Yes":"No");
4003	printk(KERN_INFO "ide-tape: Supports data compression - %s\n",capabilities->cmprs ? "Yes":"No");
4004	printk(KERN_INFO "ide-tape: Supports 512 bytes block size - %s\n",capabilities->blk512 ? "Yes":"No");
4005	printk(KERN_INFO "ide-tape: Supports 1024 bytes block size - %s\n",capabilities->blk1024 ? "Yes":"No");
4006	printk(KERN_INFO "ide-tape: Supports 32768 bytes block size / Restricted byte count for PIO transfers - %s\n",capabilities->blk32768 ? "Yes":"No");
4007	printk(KERN_INFO "ide-tape: Maximum supported speed in KBps - %d\n",capabilities->max_speed);
4008	printk(KERN_INFO "ide-tape: Continuous transfer limits in blocks - %d\n",capabilities->ctl);
4009	printk(KERN_INFO "ide-tape: Current speed in KBps - %d\n",capabilities->speed);
4010	printk(KERN_INFO "ide-tape: Buffer size - %d\n",capabilities->buffer_size*512);
4011#endif /* IDETAPE_DEBUG_INFO */
4012}
4013
4014/*
4015 *	ide_get_blocksize_from_block_descriptor does a mode sense page 0 with block descriptor
4016 *	and if it succeeds sets the tape block size with the reported value
4017 */
4018static void idetape_get_blocksize_from_block_descriptor(ide_drive_t *drive)
4019{
4020
4021	idetape_tape_t *tape = drive->driver_data;
4022	idetape_pc_t pc;
4023	idetape_mode_parameter_header_t *header;
4024	idetape_parameter_block_descriptor_t *block_descrp;
4025
4026	idetape_create_mode_sense_cmd(&pc, IDETAPE_BLOCK_DESCRIPTOR);
4027	if (idetape_queue_pc_tail(drive, &pc)) {
4028		printk(KERN_ERR "ide-tape: Can't get block descriptor\n");
4029		if (tape->tape_block_size == 0) {
4030			printk(KERN_WARNING "ide-tape: Cannot deal with zero block size, assume 32k\n");
4031			tape->tape_block_size =  32768;
4032		}
4033		return;
4034	}
4035	header = (idetape_mode_parameter_header_t *) pc.buffer;
4036	block_descrp = (idetape_parameter_block_descriptor_t *) (pc.buffer + sizeof(idetape_mode_parameter_header_t));
4037	tape->tape_block_size =( block_descrp->length[0]<<16) + (block_descrp->length[1]<<8) + block_descrp->length[2];
4038	tape->drv_write_prot = (header->dsp & 0x80) >> 7;
4039
4040#if IDETAPE_DEBUG_INFO
4041	printk(KERN_INFO "ide-tape: Adjusted block size - %d\n", tape->tape_block_size);
4042#endif /* IDETAPE_DEBUG_INFO */
4043}
4044
4045#ifdef CONFIG_IDE_PROC_FS
4046static void idetape_add_settings (ide_drive_t *drive)
4047{
4048	idetape_tape_t *tape = drive->driver_data;
4049
4050/*
4051 *			drive	setting name		read/write	data type	min			max			mul_factor			div_factor	data pointer				set function
4052 */
4053	ide_add_setting(drive,	"buffer",		SETTING_READ,	TYPE_SHORT,	0,			0xffff,			1,				2,		&tape->capabilities.buffer_size,	NULL);
4054	ide_add_setting(drive,	"pipeline_min",		SETTING_RW,	TYPE_INT,	1,			0xffff,			tape->stage_size / 1024,	1,		&tape->min_pipeline,			NULL);
4055	ide_add_setting(drive,	"pipeline",		SETTING_RW,	TYPE_INT,	1,			0xffff,			tape->stage_size / 1024,	1,		&tape->max_stages,			NULL);
4056	ide_add_setting(drive,	"pipeline_max",		SETTING_RW,	TYPE_INT,	1,			0xffff,			tape->stage_size / 1024,	1,		&tape->max_pipeline,			NULL);
4057	ide_add_setting(drive,	"pipeline_used",	SETTING_READ,	TYPE_INT,	0,			0xffff,			tape->stage_size / 1024,	1,		&tape->nr_stages,			NULL);
4058	ide_add_setting(drive,	"pipeline_pending",	SETTING_READ,	TYPE_INT,	0,			0xffff,			tape->stage_size / 1024,	1,		&tape->nr_pending_stages,		NULL);
4059	ide_add_setting(drive,	"speed",		SETTING_READ,	TYPE_SHORT,	0,			0xffff,			1,				1,		&tape->capabilities.speed,		NULL);
4060	ide_add_setting(drive,	"stage",		SETTING_READ,	TYPE_INT,	0,			0xffff,			1,				1024,		&tape->stage_size,			NULL);
4061	ide_add_setting(drive,	"tdsc",			SETTING_RW,	TYPE_INT,	IDETAPE_DSC_RW_MIN,	IDETAPE_DSC_RW_MAX,	1000,				HZ,		&tape->best_dsc_rw_frequency,		NULL);
4062	ide_add_setting(drive,	"dsc_overlap",		SETTING_RW,	TYPE_BYTE,	0,			1,			1,				1,		&drive->dsc_overlap,			NULL);
4063	ide_add_setting(drive,	"pipeline_head_speed_c",SETTING_READ,	TYPE_INT,	0,			0xffff,			1,				1,		&tape->controlled_pipeline_head_speed,	NULL);
4064	ide_add_setting(drive,	"pipeline_head_speed_u",SETTING_READ,	TYPE_INT,	0,			0xffff,			1,				1,		&tape->uncontrolled_pipeline_head_speed,NULL);
4065	ide_add_setting(drive,	"avg_speed",		SETTING_READ,	TYPE_INT,	0,			0xffff,			1,				1,		&tape->avg_speed,			NULL);
4066	ide_add_setting(drive,	"debug_level",		SETTING_RW,	TYPE_INT,	0,			0xffff,			1,				1,		&tape->debug_level,			NULL);
4067}
4068#else
4069static inline void idetape_add_settings(ide_drive_t *drive) { ; }
4070#endif
4071
4072/*
4073 *	ide_setup is called to:
4074 *
4075 *		1.	Initialize our various state variables.
4076 *		2.	Ask the tape for its capabilities.
4077 *		3.	Allocate a buffer which will be used for data
4078 *			transfer. The buffer size is chosen based on
4079 *			the recommendation which we received in step (2).
4080 *
4081 *	Note that at this point ide.c already assigned us an irq, so that
4082 *	we can queue requests here and wait for their completion.
4083 */
4084static void idetape_setup (ide_drive_t *drive, idetape_tape_t *tape, int minor)
4085{
4086	unsigned long t1, tmid, tn, t;
4087	int speed;
4088	struct idetape_id_gcw gcw;
4089	int stage_size;
4090	struct sysinfo si;
4091
4092	spin_lock_init(&tape->spinlock);
4093	drive->dsc_overlap = 1;
4094	if (drive->hwif->host_flags & IDE_HFLAG_NO_DSC) {
4095		printk(KERN_INFO "ide-tape: %s: disabling DSC overlap\n",
4096				 tape->name);
4097		drive->dsc_overlap = 0;
4098	}
4099	/* Seagate Travan drives do not support DSC overlap. */
4100	if (strstr(drive->id->model, "Seagate STT3401"))
4101		drive->dsc_overlap = 0;
4102	tape->minor = minor;
4103	tape->name[0] = 'h';
4104	tape->name[1] = 't';
4105	tape->name[2] = '0' + minor;
4106	tape->chrdev_direction = idetape_direction_none;
4107	tape->pc = tape->pc_stack;
4108	tape->max_insert_speed = 10000;
4109	tape->speed_control = 1;
4110	*((unsigned short *) &gcw) = drive->id->config;
4111	if (gcw.drq_type == 1)
4112		set_bit(IDETAPE_DRQ_INTERRUPT, &tape->flags);
4113
4114	tape->min_pipeline = tape->max_pipeline = tape->max_stages = 10;
4115
4116	idetape_get_inquiry_results(drive);
4117	idetape_get_mode_sense_results(drive);
4118	idetape_get_blocksize_from_block_descriptor(drive);
4119	tape->user_bs_factor = 1;
4120	tape->stage_size = tape->capabilities.ctl * tape->tape_block_size;
4121	while (tape->stage_size > 0xffff) {
4122		printk(KERN_NOTICE "ide-tape: decreasing stage size\n");
4123		tape->capabilities.ctl /= 2;
4124		tape->stage_size = tape->capabilities.ctl * tape->tape_block_size;
4125	}
4126	stage_size = tape->stage_size;
4127	tape->pages_per_stage = stage_size / PAGE_SIZE;
4128	if (stage_size % PAGE_SIZE) {
4129		tape->pages_per_stage++;
4130		tape->excess_bh_size = PAGE_SIZE - stage_size % PAGE_SIZE;
4131	}
4132
4133	/*
4134	 *	Select the "best" DSC read/write polling frequency
4135	 *	and pipeline size.
4136	 */
4137	speed = max(tape->capabilities.speed, tape->capabilities.max_speed);
4138
4139	tape->max_stages = speed * 1000 * 10 / tape->stage_size;
4140
4141	/*
4142	 * 	Limit memory use for pipeline to 10% of physical memory
4143	 */
4144	si_meminfo(&si);
4145	if (tape->max_stages * tape->stage_size > si.totalram * si.mem_unit / 10)
4146		tape->max_stages = si.totalram * si.mem_unit / (10 * tape->stage_size);
4147	tape->max_stages   = min(tape->max_stages, IDETAPE_MAX_PIPELINE_STAGES);
4148	tape->min_pipeline = min(tape->max_stages, IDETAPE_MIN_PIPELINE_STAGES);
4149	tape->max_pipeline = min(tape->max_stages * 2, IDETAPE_MAX_PIPELINE_STAGES);
4150	if (tape->max_stages == 0)
4151		tape->max_stages = tape->min_pipeline = tape->max_pipeline = 1;
4152
4153	t1 = (tape->stage_size * HZ) / (speed * 1000);
4154	tmid = (tape->capabilities.buffer_size * 32 * HZ) / (speed * 125);
4155	tn = (IDETAPE_FIFO_THRESHOLD * tape->stage_size * HZ) / (speed * 1000);
4156
4157	if (tape->max_stages)
4158		t = tn;
4159	else
4160		t = t1;
4161
4162	/*
4163	 *	Ensure that the number we got makes sense; limit
4164	 *	it within IDETAPE_DSC_RW_MIN and IDETAPE_DSC_RW_MAX.
4165	 */
4166	tape->best_dsc_rw_frequency = max_t(unsigned long, min_t(unsigned long, t, IDETAPE_DSC_RW_MAX), IDETAPE_DSC_RW_MIN);
4167	printk(KERN_INFO "ide-tape: %s <-> %s: %dKBps, %d*%dkB buffer, "
4168		"%dkB pipeline, %lums tDSC%s\n",
4169		drive->name, tape->name, tape->capabilities.speed,
4170		(tape->capabilities.buffer_size * 512) / tape->stage_size,
4171		tape->stage_size / 1024,
4172		tape->max_stages * tape->stage_size / 1024,
4173		tape->best_dsc_rw_frequency * 1000 / HZ,
4174		drive->using_dma ? ", DMA":"");
4175
4176	idetape_add_settings(drive);
4177}
4178
4179static void ide_tape_remove(ide_drive_t *drive)
4180{
4181	idetape_tape_t *tape = drive->driver_data;
4182
4183	ide_proc_unregister_driver(drive, tape->driver);
4184
4185	ide_unregister_region(tape->disk);
4186
4187	ide_tape_put(tape);
4188}
4189
4190static void ide_tape_release(struct kref *kref)
4191{
4192	struct ide_tape_obj *tape = to_ide_tape(kref);
4193	ide_drive_t *drive = tape->drive;
4194	struct gendisk *g = tape->disk;
4195
4196	BUG_ON(tape->first_stage != NULL || tape->merge_stage_size);
4197
4198	drive->dsc_overlap = 0;
4199	drive->driver_data = NULL;
4200	device_destroy(idetape_sysfs_class, MKDEV(IDETAPE_MAJOR, tape->minor));
4201	device_destroy(idetape_sysfs_class, MKDEV(IDETAPE_MAJOR, tape->minor + 128));
4202	idetape_devs[tape->minor] = NULL;
4203	g->private_data = NULL;
4204	put_disk(g);
4205	kfree(tape);
4206}
4207
4208#ifdef CONFIG_IDE_PROC_FS
4209static int proc_idetape_read_name
4210	(char *page, char **start, off_t off, int count, int *eof, void *data)
4211{
4212	ide_drive_t	*drive = (ide_drive_t *) data;
4213	idetape_tape_t	*tape = drive->driver_data;
4214	char		*out = page;
4215	int		len;
4216
4217	len = sprintf(out, "%s\n", tape->name);
4218	PROC_IDE_READ_RETURN(page, start, off, count, eof, len);
4219}
4220
4221static ide_proc_entry_t idetape_proc[] = {
4222	{ "capacity",	S_IFREG|S_IRUGO,	proc_ide_read_capacity, NULL },
4223	{ "name",	S_IFREG|S_IRUGO,	proc_idetape_read_name,	NULL },
4224	{ NULL, 0, NULL, NULL }
4225};
4226#endif
4227
4228static int ide_tape_probe(ide_drive_t *);
4229
4230static ide_driver_t idetape_driver = {
4231	.gen_driver = {
4232		.owner		= THIS_MODULE,
4233		.name		= "ide-tape",
4234		.bus		= &ide_bus_type,
4235	},
4236	.probe			= ide_tape_probe,
4237	.remove			= ide_tape_remove,
4238	.version		= IDETAPE_VERSION,
4239	.media			= ide_tape,
4240	.supports_dsc_overlap 	= 1,
4241	.do_request		= idetape_do_request,
4242	.end_request		= idetape_end_request,
4243	.error			= __ide_error,
4244	.abort			= __ide_abort,
4245#ifdef CONFIG_IDE_PROC_FS
4246	.proc			= idetape_proc,
4247#endif
4248};
4249
4250/*
4251 *	Our character device supporting functions, passed to register_chrdev.
4252 */
4253static const struct file_operations idetape_fops = {
4254	.owner		= THIS_MODULE,
4255	.read		= idetape_chrdev_read,
4256	.write		= idetape_chrdev_write,
4257	.ioctl		= idetape_chrdev_ioctl,
4258	.open		= idetape_chrdev_open,
4259	.release	= idetape_chrdev_release,
4260};
4261
4262static int idetape_open(struct inode *inode, struct file *filp)
4263{
4264	struct gendisk *disk = inode->i_bdev->bd_disk;
4265	struct ide_tape_obj *tape;
4266
4267	if (!(tape = ide_tape_get(disk)))
4268		return -ENXIO;
4269
4270	return 0;
4271}
4272
4273static int idetape_release(struct inode *inode, struct file *filp)
4274{
4275	struct gendisk *disk = inode->i_bdev->bd_disk;
4276	struct ide_tape_obj *tape = ide_tape_g(disk);
4277
4278	ide_tape_put(tape);
4279
4280	return 0;
4281}
4282
4283static int idetape_ioctl(struct inode *inode, struct file *file,
4284			unsigned int cmd, unsigned long arg)
4285{
4286	struct block_device *bdev = inode->i_bdev;
4287	struct ide_tape_obj *tape = ide_tape_g(bdev->bd_disk);
4288	ide_drive_t *drive = tape->drive;
4289	int err = generic_ide_ioctl(drive, file, bdev, cmd, arg);
4290	if (err == -EINVAL)
4291		err = idetape_blkdev_ioctl(drive, cmd, arg);
4292	return err;
4293}
4294
4295static struct block_device_operations idetape_block_ops = {
4296	.owner		= THIS_MODULE,
4297	.open		= idetape_open,
4298	.release	= idetape_release,
4299	.ioctl		= idetape_ioctl,
4300};
4301
4302static int ide_tape_probe(ide_drive_t *drive)
4303{
4304	idetape_tape_t *tape;
4305	struct gendisk *g;
4306	int minor;
4307
4308	if (!strstr("ide-tape", drive->driver_req))
4309		goto failed;
4310	if (!drive->present)
4311		goto failed;
4312	if (drive->media != ide_tape)
4313		goto failed;
4314	if (!idetape_identify_device (drive)) {
4315		printk(KERN_ERR "ide-tape: %s: not supported by this version of ide-tape\n", drive->name);
4316		goto failed;
4317	}
4318	if (drive->scsi) {
4319		printk("ide-tape: passing drive %s to ide-scsi emulation.\n", drive->name);
4320		goto failed;
4321	}
4322	if (strstr(drive->id->model, "OnStream DI-")) {
4323		printk(KERN_WARNING "ide-tape: Use drive %s with ide-scsi emulation and osst.\n", drive->name);
4324		printk(KERN_WARNING "ide-tape: OnStream support will be removed soon from ide-tape!\n");
4325	}
4326	tape = kzalloc(sizeof (idetape_tape_t), GFP_KERNEL);
4327	if (tape == NULL) {
4328		printk(KERN_ERR "ide-tape: %s: Can't allocate a tape structure\n", drive->name);
4329		goto failed;
4330	}
4331
4332	g = alloc_disk(1 << PARTN_BITS);
4333	if (!g)
4334		goto out_free_tape;
4335
4336	ide_init_disk(g, drive);
4337
4338	ide_proc_register_driver(drive, &idetape_driver);
4339
4340	kref_init(&tape->kref);
4341
4342	tape->drive = drive;
4343	tape->driver = &idetape_driver;
4344	tape->disk = g;
4345
4346	g->private_data = &tape->driver;
4347
4348	drive->driver_data = tape;
4349
4350	mutex_lock(&idetape_ref_mutex);
4351	for (minor = 0; idetape_devs[minor]; minor++)
4352		;
4353	idetape_devs[minor] = tape;
4354	mutex_unlock(&idetape_ref_mutex);
4355
4356	idetape_setup(drive, tape, minor);
4357
4358	device_create(idetape_sysfs_class, &drive->gendev,
4359		      MKDEV(IDETAPE_MAJOR, minor), "%s", tape->name);
4360	device_create(idetape_sysfs_class, &drive->gendev,
4361			MKDEV(IDETAPE_MAJOR, minor + 128), "n%s", tape->name);
4362
4363	g->fops = &idetape_block_ops;
4364	ide_register_region(g);
4365
4366	return 0;
4367
4368out_free_tape:
4369	kfree(tape);
4370failed:
4371	return -ENODEV;
4372}
4373
4374MODULE_DESCRIPTION("ATAPI Streaming TAPE Driver");
4375MODULE_LICENSE("GPL");
4376
4377static void __exit idetape_exit (void)
4378{
4379	driver_unregister(&idetape_driver.gen_driver);
4380	class_destroy(idetape_sysfs_class);
4381	unregister_chrdev(IDETAPE_MAJOR, "ht");
4382}
4383
4384static int __init idetape_init(void)
4385{
4386	int error = 1;
4387	idetape_sysfs_class = class_create(THIS_MODULE, "ide_tape");
4388	if (IS_ERR(idetape_sysfs_class)) {
4389		idetape_sysfs_class = NULL;
4390		printk(KERN_ERR "Unable to create sysfs class for ide tapes\n");
4391		error = -EBUSY;
4392		goto out;
4393	}
4394
4395	if (register_chrdev(IDETAPE_MAJOR, "ht", &idetape_fops)) {
4396		printk(KERN_ERR "ide-tape: Failed to register character device interface\n");
4397		error = -EBUSY;
4398		goto out_free_class;
4399	}
4400
4401	error = driver_register(&idetape_driver.gen_driver);
4402	if (error)
4403		goto out_free_driver;
4404
4405	return 0;
4406
4407out_free_driver:
4408	driver_unregister(&idetape_driver.gen_driver);
4409out_free_class:
4410	class_destroy(idetape_sysfs_class);
4411out:
4412	return error;
4413}
4414
4415MODULE_ALIAS("ide:*m-tape*");
4416module_init(idetape_init);
4417module_exit(idetape_exit);
4418MODULE_ALIAS_CHARDEV_MAJOR(IDETAPE_MAJOR);
4419