1/*
2 * linux/drivers/ide/ide-tape.c		Version 1.17a	Jan, 2001
3 *
4 * Copyright (C) 1995 - 1999 Gadi Oxman <gadio@netvision.net.il>
5 *
6 * $Header: /home/user/PROJECT/WL-520gu-NewUI/src/linux/linux/drivers/ide/ide-tape.c,v 1.1.1.1 2008/10/15 03:26:33 james26_jang Exp $
7 *
8 * This driver was constructed as a student project in the software laboratory
9 * of the faculty of electrical engineering in the Technion - Israel's
10 * Institute Of Technology, with the guide of Avner Lottem and Dr. Ilana David.
11 *
12 * It is hereby placed under the terms of the GNU general public license.
13 * (See linux/COPYING).
14 */
15
16
17/*
18 * An overview of the pipelined operation mode.
19 *
20 * In the pipelined write mode, we will usually just add requests to our
21 * pipeline and return immediately, before we even start to service them. The
22 * user program will then have enough time to prepare the next request while
23 * we are still busy servicing previous requests. In the pipelined read mode,
24 * the situation is similar - we add read-ahead requests into the pipeline,
25 * before the user even requested them.
26 *
27 * The pipeline can be viewed as a "safety net" which will be activated when
28 * the system load is high and prevents the user backup program from keeping up
29 * with the current tape speed. At this point, the pipeline will get
30 * shorter and shorter but the tape will still be streaming at the same speed.
31 * Assuming we have enough pipeline stages, the system load will hopefully
32 * decrease before the pipeline is completely empty, and the backup program
33 * will be able to "catch up" and refill the pipeline again.
34 *
35 * When using the pipelined mode, it would be best to disable any type of
36 * buffering done by the user program, as ide-tape already provides all the
37 * benefits in the kernel, where it can be done in a more efficient way.
38 * As we will usually not block the user program on a request, the most
39 * efficient user code will then be a simple read-write-read-... cycle.
40 * Any additional logic will usually just slow down the backup process.
41 *
42 * Using the pipelined mode, I get a constant over 400 KBps throughput,
43 * which seems to be the maximum throughput supported by my tape.
44 *
45 * However, there are some downfalls:
46 *
47 *	1.	We use memory (for data buffers) in proportional to the number
48 *		of pipeline stages (each stage is about 26 KB with my tape).
49 *	2.	In the pipelined write mode, we cheat and postpone error codes
50 *		to the user task. In read mode, the actual tape position
51 *		will be a bit further than the last requested block.
52 *
53 * Concerning (1):
54 *
55 *	1.	We allocate stages dynamically only when we need them. When
56 *		we don't need them, we don't consume additional memory. In
57 *		case we can't allocate stages, we just manage without them
58 *		(at the expense of decreased throughput) so when Linux is
59 *		tight in memory, we will not pose additional difficulties.
60 *
61 *	2.	The maximum number of stages (which is, in fact, the maximum
62 *		amount of memory) which we allocate is limited by the compile
63 *		time parameter IDETAPE_MAX_PIPELINE_STAGES.
64 *
65 *	3.	The maximum number of stages is a controlled parameter - We
66 *		don't start from the user defined maximum number of stages
67 *		but from the lower IDETAPE_MIN_PIPELINE_STAGES (again, we
68 *		will not even allocate this amount of stages if the user
69 *		program can't handle the speed). We then implement a feedback
70 *		loop which checks if the pipeline is empty, and if it is, we
71 *		increase the maximum number of stages as necessary until we
72 *		reach the optimum value which just manages to keep the tape
73 *		busy with minimum allocated memory or until we reach
74 *		IDETAPE_MAX_PIPELINE_STAGES.
75 *
76 * Concerning (2):
77 *
78 *	In pipelined write mode, ide-tape can not return accurate error codes
79 *	to the user program since we usually just add the request to the
80 *      pipeline without waiting for it to be serviced. In case an error
81 *      occurs, I will report it on the next user request.
82 *
83 *	In the pipelined read mode, subsequent read requests or forward
84 *	filemark spacing will perform correctly, as we preserve all blocks
85 *	and filemarks which we encountered during our excess read-ahead.
86 *
87 *	For accurate tape positioning and error reporting, disabling
88 *	pipelined mode might be the best option.
89 *
90 * You can enable/disable/tune the pipelined operation mode by adjusting
91 * the compile time parameters below.
92 */
93
94/*
95 *	Possible improvements.
96 *
97 *	1.	Support for the ATAPI overlap protocol.
98 *
99 *		In order to maximize bus throughput, we currently use the DSC
100 *		overlap method which enables ide.c to service requests from the
101 *		other device while the tape is busy executing a command. The
102 *		DSC overlap method involves polling the tape's status register
103 *		for the DSC bit, and servicing the other device while the tape
104 *		isn't ready.
105 *
106 *		In the current QIC development standard (December 1995),
107 *		it is recommended that new tape drives will *in addition*
108 *		implement the ATAPI overlap protocol, which is used for the
109 *		same purpose - efficient use of the IDE bus, but is interrupt
110 *		driven and thus has much less CPU overhead.
111 *
112 *		ATAPI overlap is likely to be supported in most new ATAPI
113 *		devices, including new ATAPI cdroms, and thus provides us
114 *		a method by which we can achieve higher throughput when
115 *		sharing a (fast) ATA-2 disk with any (slow) new ATAPI device.
116 */
117
118#define IDETAPE_VERSION "1.17a"
119
120#include <linux/config.h>
121#include <linux/module.h>
122#include <linux/types.h>
123#include <linux/string.h>
124#include <linux/kernel.h>
125#include <linux/delay.h>
126#include <linux/timer.h>
127#include <linux/mm.h>
128#include <linux/interrupt.h>
129#include <linux/major.h>
130#include <linux/devfs_fs_kernel.h>
131#include <linux/errno.h>
132#include <linux/genhd.h>
133#include <linux/slab.h>
134#include <linux/pci.h>
135#include <linux/ide.h>
136#include <linux/smp_lock.h>
137#include <linux/completion.h>
138
139#include <asm/byteorder.h>
140#include <asm/irq.h>
141#include <asm/uaccess.h>
142#include <asm/io.h>
143#include <asm/unaligned.h>
144#include <asm/bitops.h>
145
146
147#define NO_LONGER_REQUIRED	(1)
148
149/*
150 *	OnStream support
151 */
152#define ONSTREAM_DEBUG		(0)
153#define OS_CONFIG_PARTITION	(0xff)
154#define OS_DATA_PARTITION	(0)
155#define OS_PARTITION_VERSION	(1)
156#define OS_EW			300
157#define OS_ADR_MINREV		2
158
159#define OS_DATA_STARTFRAME1	20
160#define OS_DATA_ENDFRAME1	2980
161/*
162 * partition
163 */
164typedef struct os_partition_s {
165	__u8	partition_num;
166	__u8	par_desc_ver;
167	__u16	wrt_pass_cntr;
168	__u32	first_frame_addr;
169	__u32	last_frame_addr;
170	__u32	eod_frame_addr;
171} os_partition_t;
172
173/*
174 * DAT entry
175 */
176typedef struct os_dat_entry_s {
177	__u32	blk_sz;
178	__u16	blk_cnt;
179	__u8	flags;
180	__u8	reserved;
181} os_dat_entry_t;
182
183/*
184 * DAT
185 */
186#define OS_DAT_FLAGS_DATA	(0xc)
187#define OS_DAT_FLAGS_MARK	(0x1)
188
189typedef struct os_dat_s {
190	__u8		dat_sz;
191	__u8		reserved1;
192	__u8		entry_cnt;
193	__u8		reserved3;
194	os_dat_entry_t	dat_list[16];
195} os_dat_t;
196
197/*
198 * Frame types
199 */
200#define OS_FRAME_TYPE_FILL	(0)
201#define OS_FRAME_TYPE_EOD	(1 << 0)
202#define OS_FRAME_TYPE_MARKER	(1 << 1)
203#define OS_FRAME_TYPE_HEADER	(1 << 3)
204#define OS_FRAME_TYPE_DATA	(1 << 7)
205
206/*
207 * AUX
208 */
209typedef struct os_aux_s {
210	__u32		format_id;		/* hardware compability AUX is based on */
211	char		application_sig[4];	/* driver used to write this media */
212	__u32		hdwr;			/* reserved */
213	__u32		update_frame_cntr;	/* for configuration frame */
214	__u8		frame_type;
215	__u8		frame_type_reserved;
216	__u8		reserved_18_19[2];
217	os_partition_t	partition;
218	__u8		reserved_36_43[8];
219	__u32		frame_seq_num;
220	__u32		logical_blk_num_high;
221	__u32		logical_blk_num;
222	os_dat_t	dat;
223	__u8		reserved188_191[4];
224	__u32		filemark_cnt;
225	__u32		phys_fm;
226	__u32		last_mark_addr;
227	__u8		reserved204_223[20];
228
229	/*
230	 * __u8		app_specific[32];
231	 *
232	 * Linux specific fields:
233	 */
234	 __u32		next_mark_addr;		/* when known, points to next marker */
235	 __u8		linux_specific[28];
236
237	__u8		reserved_256_511[256];
238} os_aux_t;
239
240typedef struct os_header_s {
241	char		ident_str[8];
242	__u8		major_rev;
243	__u8		minor_rev;
244	__u8		reserved10_15[6];
245	__u8		par_num;
246	__u8		reserved1_3[3];
247	os_partition_t	partition;
248} os_header_t;
249
250/*
251 *	OnStream Tape Parameters Page
252 */
253typedef struct {
254	unsigned	page_code	:6;	/* Page code - Should be 0x2b */
255	unsigned	reserved1_6	:1;
256	unsigned	ps		:1;
257	__u8		reserved2;
258	__u8		density;		/* kbpi */
259	__u8		reserved3,reserved4;
260	__u16		segtrk;                 /* segment of per track */
261	__u16		trks;                   /* tracks per tape */
262	__u8		reserved5,reserved6,reserved7,reserved8,reserved9,reserved10;
263} onstream_tape_paramtr_page_t;
264
265/*
266 * OnStream ADRL frame
267 */
268#define OS_FRAME_SIZE	(32 * 1024 + 512)
269#define OS_DATA_SIZE	(32 * 1024)
270#define OS_AUX_SIZE	(512)
271
272/*
273 * internal error codes for onstream
274 */
275#define OS_PART_ERROR    2
276#define OS_WRITE_ERROR   1
277
278#include <linux/mtio.h>
279
280/**************************** Tunable parameters *****************************/
281
282
283/*
284 *	Pipelined mode parameters.
285 *
286 *	We try to use the minimum number of stages which is enough to
287 *	keep the tape constantly streaming. To accomplish that, we implement
288 *	a feedback loop around the maximum number of stages:
289 *
290 *	We start from MIN maximum stages (we will not even use MIN stages
291 *      if we don't need them), increment it by RATE*(MAX-MIN)
292 *	whenever we sense that the pipeline is empty, until we reach
293 *	the optimum value or until we reach MAX.
294 *
295 *	Setting the following parameter to 0 will disable the pipelined mode.
296 */
297#define IDETAPE_MIN_PIPELINE_STAGES	200
298#define IDETAPE_MAX_PIPELINE_STAGES	400
299#define IDETAPE_INCREASE_STAGES_RATE	 20
300
301/*
302 *	The following are used to debug the driver:
303 *
304 *	Setting IDETAPE_DEBUG_INFO to 1 will report device capabilities.
305 *	Setting IDETAPE_DEBUG_LOG to 1 will log driver flow control.
306 *	Setting IDETAPE_DEBUG_BUGS to 1 will enable self-sanity checks in
307 *	some places.
308 *
309 *	Setting them to 0 will restore normal operation mode:
310 *
311 *		1.	Disable logging normal successful operations.
312 *		2.	Disable self-sanity checks.
313 *		3.	Errors will still be logged, of course.
314 *
315 *	All the #if DEBUG code will be removed some day, when the driver
316 *	is verified to be stable enough. This will make it much more
317 *	esthetic.
318 */
319#define IDETAPE_DEBUG_INFO		1
320#define IDETAPE_DEBUG_LOG		1
321#define IDETAPE_DEBUG_LOG_VERBOSE	0
322#define IDETAPE_DEBUG_BUGS		1
323
324/*
325 *	After each failed packet command we issue a request sense command
326 *	and retry the packet command IDETAPE_MAX_PC_RETRIES times.
327 *
328 *	Setting IDETAPE_MAX_PC_RETRIES to 0 will disable retries.
329 */
330#define IDETAPE_MAX_PC_RETRIES		3
331
332/*
333 *	With each packet command, we allocate a buffer of
334 *	IDETAPE_PC_BUFFER_SIZE bytes. This is used for several packet
335 *	commands (Not for READ/WRITE commands).
336 */
337#define IDETAPE_PC_BUFFER_SIZE		256
338
339/*
340 *	In various places in the driver, we need to allocate storage
341 *	for packet commands and requests, which will remain valid while
342 *	we leave the driver to wait for an interrupt or a timeout event.
343 */
344#define IDETAPE_PC_STACK		(10 + IDETAPE_MAX_PC_RETRIES)
345
346/*
347 *	Some tape drives require a long irq timeout
348 */
349#define IDETAPE_WAIT_CMD		(60*HZ)
350
351/*
352 *	The following parameter is used to select the point in the internal
353 *	tape fifo in which we will start to refill the buffer. Decreasing
354 *	the following parameter will improve the system's latency and
355 *	interactive response, while using a high value might improve sytem
356 *	throughput.
357 */
358#define IDETAPE_FIFO_THRESHOLD 		2
359
360/*
361 *	DSC polling parameters.
362 *
363 *	Polling for DSC (a single bit in the status register) is a very
364 *	important function in ide-tape. There are two cases in which we
365 *	poll for DSC:
366 *
367 *	1.	Before a read/write packet command, to ensure that we
368 *		can transfer data from/to the tape's data buffers, without
369 *		causing an actual media access. In case the tape is not
370 *		ready yet, we take out our request from the device
371 *		request queue, so that ide.c will service requests from
372 *		the other device on the same interface meanwhile.
373 *
374 *	2.	After the successful initialization of a "media access
375 *		packet command", which is a command which can take a long
376 *		time to complete (it can be several seconds or even an hour).
377 *
378 *		Again, we postpone our request in the middle to free the bus
379 *		for the other device. The polling frequency here should be
380 *		lower than the read/write frequency since those media access
381 *		commands are slow. We start from a "fast" frequency -
382 *		IDETAPE_DSC_MA_FAST (one second), and if we don't receive DSC
383 *		after IDETAPE_DSC_MA_THRESHOLD (5 minutes), we switch it to a
384 *		lower frequency - IDETAPE_DSC_MA_SLOW (1 minute).
385 *
386 *	We also set a timeout for the timer, in case something goes wrong.
387 *	The timeout should be longer then the maximum execution time of a
388 *	tape operation.
389 */
390
391/*
392 *	DSC timings.
393 */
394#define IDETAPE_DSC_RW_MIN		5*HZ/100	/* 50 msec */
395#define IDETAPE_DSC_RW_MAX		40*HZ/100	/* 400 msec */
396#define IDETAPE_DSC_RW_TIMEOUT		2*60*HZ		/* 2 minutes */
397#define IDETAPE_DSC_MA_FAST		2*HZ		/* 2 seconds */
398#define IDETAPE_DSC_MA_THRESHOLD	5*60*HZ		/* 5 minutes */
399#define IDETAPE_DSC_MA_SLOW		30*HZ		/* 30 seconds */
400#define IDETAPE_DSC_MA_TIMEOUT		2*60*60*HZ	/* 2 hours */
401
402/*************************** End of tunable parameters ***********************/
403
404/*
405 *	Debugging/Performance analysis
406 *
407 *	I/O trace support
408 */
409#define USE_IOTRACE	0
410#if USE_IOTRACE
411#include <linux/io_trace.h>
412#define IO_IDETAPE_FIFO	500
413#endif
414
415/*
416 *	Read/Write error simulation
417 */
418#define SIMULATE_ERRORS			0
419
420/*
421 *	For general magnetic tape device compatibility.
422 */
423typedef enum {
424	idetape_direction_none,
425	idetape_direction_read,
426	idetape_direction_write
427} idetape_chrdev_direction_t;
428
429/*
430 *	Our view of a packet command.
431 */
432typedef struct idetape_packet_command_s {
433	u8 c[12];				/* Actual packet bytes */
434	int retries;				/* On each retry, we increment retries */
435	int error;				/* Error code */
436	int request_transfer;			/* Bytes to transfer */
437	int actually_transferred;		/* Bytes actually transferred */
438	int buffer_size;			/* Size of our data buffer */
439	struct buffer_head *bh;
440	char *b_data;
441	int b_count;
442	byte *buffer;				/* Data buffer */
443	byte *current_position;			/* Pointer into the above buffer */
444	ide_startstop_t (*callback) (ide_drive_t *);	/* Called when this packet command is completed */
445	byte pc_buffer[IDETAPE_PC_BUFFER_SIZE];	/* Temporary buffer */
446	unsigned long flags;			/* Status/Action bit flags: long for set_bit */
447} idetape_pc_t;
448
449/*
450 *	Packet command flag bits.
451 */
452#define	PC_ABORT			0	/* Set when an error is considered normal - We won't retry */
453#define PC_WAIT_FOR_DSC			1	/* 1 When polling for DSC on a media access command */
454#define PC_DMA_RECOMMENDED		2	/* 1 when we prefer to use DMA if possible */
455#define	PC_DMA_IN_PROGRESS		3	/* 1 while DMA in progress */
456#define	PC_DMA_ERROR			4	/* 1 when encountered problem during DMA */
457#define	PC_WRITING			5	/* Data direction */
458
459/*
460 *	Capabilities and Mechanical Status Page
461 */
462typedef struct {
463	unsigned	page_code	:6;	/* Page code - Should be 0x2a */
464	__u8		reserved0_6	:1;
465	__u8		ps		:1;	/* parameters saveable */
466	__u8		page_length;		/* Page Length - Should be 0x12 */
467	__u8		reserved2, reserved3;
468	unsigned	ro		:1;	/* Read Only Mode */
469	unsigned	reserved4_1234	:4;
470	unsigned	sprev		:1;	/* Supports SPACE in the reverse direction */
471	unsigned	reserved4_67	:2;
472	unsigned	reserved5_012	:3;
473	unsigned	efmt		:1;	/* Supports ERASE command initiated formatting */
474	unsigned	reserved5_4	:1;
475	unsigned	qfa		:1;	/* Supports the QFA two partition formats */
476	unsigned	reserved5_67	:2;
477	unsigned	lock		:1;	/* Supports locking the volume */
478	unsigned	locked		:1;	/* The volume is locked */
479	unsigned	prevent		:1;	/* The device defaults in the prevent state after power up */
480	unsigned	eject		:1;	/* The device can eject the volume */
481	__u8		disconnect	:1;	/* The device can break request > ctl */
482	__u8		reserved6_5	:1;
483	unsigned	ecc		:1;	/* Supports error correction */
484	unsigned	cmprs		:1;	/* Supports data compression */
485	unsigned	reserved7_0	:1;
486	unsigned	blk512		:1;	/* Supports 512 bytes block size */
487	unsigned	blk1024		:1;	/* Supports 1024 bytes block size */
488	unsigned	reserved7_3_6	:4;
489	unsigned	blk32768	:1;	/* slowb - the device restricts the byte count for PIO */
490						/* transfers for slow buffer memory ??? */
491						/* Also 32768 block size in some cases */
492	__u16		max_speed;		/* Maximum speed supported in KBps */
493	__u8		reserved10, reserved11;
494	__u16		ctl;			/* Continuous Transfer Limit in blocks */
495	__u16		speed;			/* Current Speed, in KBps */
496	__u16		buffer_size;		/* Buffer Size, in 512 bytes */
497	__u8		reserved18, reserved19;
498} idetape_capabilities_page_t;
499
500/*
501 *	Block Size Page
502 */
503typedef struct {
504	unsigned	page_code	:6;	/* Page code - Should be 0x30 */
505	unsigned	reserved1_6	:1;
506	unsigned	ps		:1;
507	__u8		page_length;		/* Page Length - Should be 2 */
508	__u8		reserved2;
509	unsigned	play32		:1;
510	unsigned	play32_5	:1;
511	unsigned	reserved2_23	:2;
512	unsigned	record32	:1;
513	unsigned	record32_5	:1;
514	unsigned	reserved2_6	:1;
515	unsigned	one		:1;
516} idetape_block_size_page_t;
517
518/*
519 *	A pipeline stage.
520 */
521typedef struct idetape_stage_s {
522	struct request rq;			/* The corresponding request */
523	struct buffer_head *bh;			/* The data buffers */
524	struct idetape_stage_s *next;		/* Pointer to the next stage */
525	os_aux_t *aux;				/* OnStream aux ptr */
526} idetape_stage_t;
527
528/*
529 *	REQUEST SENSE packet command result - Data Format.
530 */
531typedef struct {
532	unsigned	error_code	:7;	/* Current of deferred errors */
533	unsigned	valid		:1;	/* The information field conforms to QIC-157C */
534	__u8		reserved1	:8;	/* Segment Number - Reserved */
535	unsigned	sense_key	:4;	/* Sense Key */
536	unsigned	reserved2_4	:1;	/* Reserved */
537	unsigned	ili		:1;	/* Incorrect Length Indicator */
538	unsigned	eom		:1;	/* End Of Medium */
539	unsigned	filemark 	:1;	/* Filemark */
540	__u32		information __attribute__ ((packed));
541	__u8		asl;			/* Additional sense length (n-7) */
542	__u32		command_specific;	/* Additional command specific information */
543	__u8		asc;			/* Additional Sense Code */
544	__u8		ascq;			/* Additional Sense Code Qualifier */
545	__u8		replaceable_unit_code;	/* Field Replaceable Unit Code */
546	unsigned	sk_specific1 	:7;	/* Sense Key Specific */
547	unsigned	sksv		:1;	/* Sense Key Specific information is valid */
548	__u8		sk_specific2;		/* Sense Key Specific */
549	__u8		sk_specific3;		/* Sense Key Specific */
550	__u8		pad[2];			/* Padding to 20 bytes */
551} idetape_request_sense_result_t;
552
553
554/*
555 *	Most of our global data which we need to save even as we leave the
556 *	driver due to an interrupt or a timer event is stored in a variable
557 *	of type idetape_tape_t, defined below.
558 */
559typedef struct {
560	ide_drive_t *drive;
561	devfs_handle_t de_r, de_n;
562
563	/*
564	 *	Since a typical character device operation requires more
565	 *	than one packet command, we provide here enough memory
566	 *	for the maximum of interconnected packet commands.
567	 *	The packet commands are stored in the circular array pc_stack.
568	 *	pc_stack_index points to the last used entry, and warps around
569	 *	to the start when we get to the last array entry.
570	 *
571	 *	pc points to the current processed packet command.
572	 *
573	 *	failed_pc points to the last failed packet command, or contains
574	 *	NULL if we do not need to retry any packet command. This is
575	 *	required since an additional packet command is needed before the
576	 *	retry, to get detailed information on what went wrong.
577	 */
578	idetape_pc_t *pc;			/* Current packet command */
579	idetape_pc_t *failed_pc; 		/* Last failed packet command */
580	idetape_pc_t pc_stack[IDETAPE_PC_STACK];/* Packet command stack */
581	int pc_stack_index;			/* Next free packet command storage space */
582	struct request rq_stack[IDETAPE_PC_STACK];
583	int rq_stack_index;			/* We implement a circular array */
584
585	/*
586	 *	DSC polling variables.
587	 *
588	 *	While polling for DSC we use postponed_rq to postpone the
589	 *	current request so that ide.c will be able to service
590	 *	pending requests on the other device. Note that at most
591	 *	we will have only one DSC (usually data transfer) request
592	 *	in the device request queue. Additional requests can be
593	 *	queued in our internal pipeline, but they will be visible
594	 *	to ide.c only one at a time.
595	 */
596	struct request *postponed_rq;
597	unsigned long dsc_polling_start;	/* The time in which we started polling for DSC */
598	struct timer_list dsc_timer;		/* Timer used to poll for dsc */
599	unsigned long best_dsc_rw_frequency;	/* Read/Write dsc polling frequency */
600	unsigned long dsc_polling_frequency;	/* The current polling frequency */
601	unsigned long dsc_timeout;		/* Maximum waiting time */
602
603	/*
604	 *	Read position information
605	 */
606	byte partition;
607	unsigned int first_frame_position;		/* Current block */
608	unsigned int last_frame_position;
609	unsigned int blocks_in_buffer;
610
611	/*
612	 *	Last error information
613	 */
614	byte sense_key, asc, ascq;
615
616	/*
617	 *	Character device operation
618	 */
619	unsigned int minor;
620	char name[4];					/* device name */
621	idetape_chrdev_direction_t chrdev_direction;	/* Current character device data transfer direction */
622
623	/*
624	 *	Device information
625	 */
626	unsigned short tape_block_size;			/* Usually 512 or 1024 bytes */
627	int user_bs_factor;
628	idetape_capabilities_page_t capabilities;	/* Copy of the tape's Capabilities and Mechanical Page */
629
630	/*
631	 *	Active data transfer request parameters.
632	 *
633	 *	At most, there is only one ide-tape originated data transfer
634	 *	request in the device request queue. This allows ide.c to
635	 *	easily service requests from the other device when we
636	 *	postpone our active request. In the pipelined operation
637	 *	mode, we use our internal pipeline structure to hold
638	 *	more data requests.
639	 *
640	 *	The data buffer size is chosen based on the tape's
641	 *	recommendation.
642	 */
643	struct request *active_data_request;	/* Pointer to the request which is waiting in the device request queue */
644	int stage_size;				/* Data buffer size (chosen based on the tape's recommendation */
645	idetape_stage_t *merge_stage;
646	int merge_stage_size;
647	struct buffer_head *bh;
648	char *b_data;
649	int b_count;
650
651	/*
652	 *	Pipeline parameters.
653	 *
654	 *	To accomplish non-pipelined mode, we simply set the following
655	 *	variables to zero (or NULL, where appropriate).
656	 */
657	int nr_stages;				/* Number of currently used stages */
658	int nr_pending_stages;			/* Number of pending stages */
659	int max_stages, min_pipeline, max_pipeline; /* We will not allocate more than this number of stages */
660	idetape_stage_t *first_stage;		/* The first stage which will be removed from the pipeline */
661	idetape_stage_t *active_stage;		/* The currently active stage */
662	idetape_stage_t *next_stage;		/* Will be serviced after the currently active request */
663	idetape_stage_t *last_stage;		/* New requests will be added to the pipeline here */
664	idetape_stage_t *cache_stage;		/* Optional free stage which we can use */
665	int pages_per_stage;
666	int excess_bh_size;			/* Wasted space in each stage */
667
668	unsigned long flags;			/* Status/Action flags: long for set_bit */
669	spinlock_t spinlock;			/* protects the ide-tape queue */
670
671	/*
672	 * Measures average tape speed
673	 */
674	unsigned long avg_time;
675	int avg_size;
676	int avg_speed;
677
678	idetape_request_sense_result_t sense;	/* last sense information */
679
680	char vendor_id[10];
681	char product_id[18];
682	char firmware_revision[6];
683	int firmware_revision_num;
684
685	int door_locked;			/* the door is currently locked */
686
687	/*
688	 * OnStream flags
689	 */
690	int onstream;				/* the tape is an OnStream tape */
691	int raw;				/* OnStream raw access (32.5KB block size) */
692	int cur_frames;				/* current number of frames in internal buffer */
693	int max_frames;				/* max number of frames in internal buffer */
694	int logical_blk_num;			/* logical block number */
695	__u16 wrt_pass_cntr;			/* write pass counter */
696	__u32 update_frame_cntr;		/* update frame counter */
697	struct completion *waiting;
698	int onstream_write_error;		/* write error recovery active */
699	int header_ok;				/* header frame verified ok */
700	int linux_media;			/* reading linux-specifc media */
701	int linux_media_version;
702	char application_sig[5];		/* application signature */
703	int filemark_cnt;
704	int first_mark_addr;
705	int last_mark_addr;
706	int eod_frame_addr;
707	unsigned long cmd_start_time;
708	unsigned long max_cmd_time;
709	unsigned capacity;
710
711	/*
712	 * Optimize the number of "buffer filling"
713	 * mode sense commands.
714	 */
715	unsigned long last_buffer_fill;		/* last time in which we issued fill cmd */
716	int req_buffer_fill;			/* buffer fill command requested */
717	int writes_since_buffer_fill;
718	int reads_since_buffer_fill;
719
720	/*
721	 * Limit the number of times a request can
722	 * be postponed, to avoid an infinite postpone
723	 * deadlock.
724	 */
725	int postpone_cnt;			/* request postpone count limit */
726
727	/*
728	 * Measures number of frames:
729	 *
730	 * 1. written/read to/from the driver pipeline (pipeline_head).
731	 * 2. written/read to/from the tape buffers (buffer_head).
732	 * 3. written/read by the tape to/from the media (tape_head).
733	 */
734	int pipeline_head;
735	int buffer_head;
736	int tape_head;
737	int last_tape_head;
738
739	/*
740	 * Speed control at the tape buffers input/output
741	 */
742	unsigned long insert_time;
743	int insert_size;
744	int insert_speed;
745	int max_insert_speed;
746	int measure_insert_time;
747
748	/*
749	 * Measure tape still time, in milliseconds
750	 */
751	unsigned long tape_still_time_begin;
752	int tape_still_time;
753
754	/*
755	 * Speed regulation negative feedback loop
756	 */
757	int speed_control;
758	int pipeline_head_speed, controlled_pipeline_head_speed, uncontrolled_pipeline_head_speed;
759	int controlled_last_pipeline_head, uncontrolled_last_pipeline_head;
760	unsigned long uncontrolled_pipeline_head_time, controlled_pipeline_head_time;
761	int controlled_previous_pipeline_head, uncontrolled_previous_pipeline_head;
762	unsigned long controlled_previous_head_time, uncontrolled_previous_head_time;
763	int restart_speed_control_req;
764
765        /*
766         * Debug_level determines amount of debugging output;
767         * can be changed using /proc/ide/hdx/settings
768         * 0 : almost no debugging output
769         * 1 : 0+output errors only
770         * 2 : 1+output all sensekey/asc
771         * 3 : 2+follow all chrdev related procedures
772         * 4 : 3+follow all procedures
773         * 5 : 4+include pc_stack rq_stack info
774         * 6 : 5+USE_COUNT updates
775         */
776         int debug_level;
777} idetape_tape_t;
778
779/*
780 *	Tape door status
781 */
782#define DOOR_UNLOCKED			0
783#define DOOR_LOCKED			1
784#define DOOR_EXPLICITLY_LOCKED		2
785
786/*
787 *	Tape flag bits values.
788 */
789#define IDETAPE_IGNORE_DSC		0
790#define IDETAPE_ADDRESS_VALID		1	/* 0 When the tape position is unknown */
791#define IDETAPE_BUSY			2	/* Device already opened */
792#define IDETAPE_PIPELINE_ERROR		3	/* Error detected in a pipeline stage */
793#define IDETAPE_DETECT_BS		4	/* Attempt to auto-detect the current user block size */
794#define IDETAPE_FILEMARK		5	/* Currently on a filemark */
795#define IDETAPE_DRQ_INTERRUPT		6	/* DRQ interrupt device */
796#define IDETAPE_READ_ERROR		7
797#define IDETAPE_PIPELINE_ACTIVE		8	/* pipeline active */
798
799/*
800 *	Supported ATAPI tape drives packet commands
801 */
802#define IDETAPE_TEST_UNIT_READY_CMD	0x00
803#define IDETAPE_REWIND_CMD		0x01
804#define IDETAPE_REQUEST_SENSE_CMD	0x03
805#define IDETAPE_READ_CMD		0x08
806#define IDETAPE_WRITE_CMD		0x0a
807#define IDETAPE_WRITE_FILEMARK_CMD	0x10
808#define IDETAPE_SPACE_CMD		0x11
809#define IDETAPE_INQUIRY_CMD		0x12
810#define IDETAPE_ERASE_CMD		0x19
811#define IDETAPE_MODE_SENSE_CMD		0x1a
812#define IDETAPE_MODE_SELECT_CMD		0x15
813#define IDETAPE_LOAD_UNLOAD_CMD		0x1b
814#define IDETAPE_PREVENT_CMD		0x1e
815#define IDETAPE_LOCATE_CMD		0x2b
816#define IDETAPE_READ_POSITION_CMD	0x34
817#define IDETAPE_READ_BUFFER_CMD		0x3c
818#define IDETAPE_SET_SPEED_CMD		0xbb
819
820/*
821 *	Some defines for the READ BUFFER command
822 */
823#define IDETAPE_RETRIEVE_FAULTY_BLOCK	6
824
825/*
826 *	Some defines for the SPACE command
827 */
828#define IDETAPE_SPACE_OVER_FILEMARK	1
829#define IDETAPE_SPACE_TO_EOD		3
830
831/*
832 *	Some defines for the LOAD UNLOAD command
833 */
834#define IDETAPE_LU_LOAD_MASK		1
835#define IDETAPE_LU_RETENSION_MASK	2
836#define IDETAPE_LU_EOT_MASK		4
837
838/*
839 *	Special requests for our block device strategy routine.
840 *
841 *	In order to service a character device command, we add special
842 *	requests to the tail of our block device request queue and wait
843 *	for their completion.
844 *
845 */
846#define IDETAPE_FIRST_RQ		90
847
848/*
849 * 	IDETAPE_PC_RQ is used to queue a packet command in the request queue.
850 */
851#define IDETAPE_PC_RQ1			90
852#define IDETAPE_PC_RQ2			91
853
854/*
855 *	IDETAPE_READ_RQ and IDETAPE_WRITE_RQ are used by our
856 *	character device interface to request read/write operations from
857 *	our block device interface.
858 */
859#define IDETAPE_READ_RQ			92
860#define IDETAPE_WRITE_RQ		93
861#define IDETAPE_ABORTED_WRITE_RQ	94
862#define IDETAPE_ABORTED_READ_RQ		95
863#define IDETAPE_READ_BUFFER_RQ		96
864
865#define IDETAPE_LAST_RQ			96
866
867/*
868 *	A macro which can be used to check if a we support a given
869 *	request command.
870 */
871#define IDETAPE_RQ_CMD(cmd) 		((cmd >= IDETAPE_FIRST_RQ) && (cmd <= IDETAPE_LAST_RQ))
872
873/*
874 *	Error codes which are returned in rq->errors to the higher part
875 *	of the driver.
876 */
877#define	IDETAPE_ERROR_GENERAL		101
878#define	IDETAPE_ERROR_FILEMARK		102
879#define	IDETAPE_ERROR_EOD		103
880
881/*
882 *	The ATAPI Status Register.
883 */
884typedef union {
885	unsigned all			:8;
886	struct {
887		unsigned check		:1;	/* Error occurred */
888		unsigned idx		:1;	/* Reserved */
889		unsigned corr		:1;	/* Correctable error occurred */
890		unsigned drq		:1;	/* Data is request by the device */
891		unsigned dsc		:1;	/* Buffer availability / Media access command finished */
892		unsigned reserved5	:1;	/* Reserved */
893		unsigned drdy		:1;	/* Ignored for ATAPI commands (ready to accept ATA command) */
894		unsigned bsy		:1;	/* The device has access to the command block */
895	} b;
896} idetape_status_reg_t;
897
898/*
899 *	The ATAPI error register.
900 */
901typedef union {
902	unsigned all			:8;
903	struct {
904		unsigned ili		:1;	/* Illegal Length Indication */
905		unsigned eom		:1;	/* End Of Media Detected */
906		unsigned abrt		:1;	/* Aborted command - As defined by ATA */
907		unsigned mcr		:1;	/* Media Change Requested - As defined by ATA */
908		unsigned sense_key	:4;	/* Sense key of the last failed packet command */
909	} b;
910} idetape_error_reg_t;
911
912/*
913 *	ATAPI Feature Register
914 */
915typedef union {
916	unsigned all			:8;
917	struct {
918		unsigned dma		:1;	/* Using DMA or PIO */
919		unsigned reserved321	:3;	/* Reserved */
920		unsigned reserved654	:3;	/* Reserved (Tag Type) */
921		unsigned reserved7	:1;	/* Reserved */
922	} b;
923} idetape_feature_reg_t;
924
925/*
926 *	ATAPI Byte Count Register.
927 */
928typedef union {
929	unsigned all			:16;
930	struct {
931		unsigned low		:8;	/* LSB */
932		unsigned high		:8;	/* MSB */
933	} b;
934} idetape_bcount_reg_t;
935
936/*
937 *	ATAPI Interrupt Reason Register.
938 */
939typedef union {
940	unsigned all			:8;
941	struct {
942		unsigned cod		:1;	/* Information transferred is command (1) or data (0) */
943		unsigned io		:1;	/* The device requests us to read (1) or write (0) */
944		unsigned reserved	:6;	/* Reserved */
945	} b;
946} idetape_ireason_reg_t;
947
948/*
949 *	ATAPI Drive Select Register
950 */
951typedef union {
952	unsigned all			:8;
953	struct {
954		unsigned sam_lun	:4;	/* Should be zero with ATAPI (not used) */
955		unsigned drv		:1;	/* The responding drive will be drive 0 (0) or drive 1 (1) */
956		unsigned one5		:1;	/* Should be set to 1 */
957		unsigned reserved6	:1;	/* Reserved */
958		unsigned one7		:1;	/* Should be set to 1 */
959	} b;
960} idetape_drivesel_reg_t;
961
962/*
963 *	ATAPI Device Control Register
964 */
965typedef union {
966	unsigned all			:8;
967	struct {
968		unsigned zero0		:1;	/* Should be set to zero */
969		unsigned nien		:1;	/* Device interrupt is disabled (1) or enabled (0) */
970		unsigned srst		:1;	/* ATA software reset. ATAPI devices should use the new ATAPI srst. */
971		unsigned one3		:1;	/* Should be set to 1 */
972		unsigned reserved4567	:4;	/* Reserved */
973	} b;
974} idetape_control_reg_t;
975
976/*
977 *	idetape_chrdev_t provides the link between out character device
978 *	interface and our block device interface and the corresponding
979 *	ide_drive_t structure.
980 */
981typedef struct {
982	ide_drive_t *drive;
983} idetape_chrdev_t;
984
985/*
986 *	The following is used to format the general configuration word of
987 *	the ATAPI IDENTIFY DEVICE command.
988 */
989struct idetape_id_gcw {
990	unsigned packet_size		:2;	/* Packet Size */
991	unsigned reserved234		:3;	/* Reserved */
992	unsigned drq_type		:2;	/* Command packet DRQ type */
993	unsigned removable		:1;	/* Removable media */
994	unsigned device_type		:5;	/* Device type */
995	unsigned reserved13		:1;	/* Reserved */
996	unsigned protocol		:2;	/* Protocol type */
997};
998
999/*
1000 *	INQUIRY packet command - Data Format (From Table 6-8 of QIC-157C)
1001 */
1002typedef struct {
1003	unsigned	device_type	:5;	/* Peripheral Device Type */
1004	unsigned	reserved0_765	:3;	/* Peripheral Qualifier - Reserved */
1005	unsigned	reserved1_6t0	:7;	/* Reserved */
1006	unsigned	rmb		:1;	/* Removable Medium Bit */
1007	unsigned	ansi_version	:3;	/* ANSI Version */
1008	unsigned	ecma_version	:3;	/* ECMA Version */
1009	unsigned	iso_version	:2;	/* ISO Version */
1010	unsigned	response_format :4;	/* Response Data Format */
1011	unsigned	reserved3_45	:2;	/* Reserved */
1012	unsigned	reserved3_6	:1;	/* TrmIOP - Reserved */
1013	unsigned	reserved3_7	:1;	/* AENC - Reserved */
1014	__u8		additional_length;	/* Additional Length (total_length-4) */
1015	__u8		rsv5, rsv6, rsv7;	/* Reserved */
1016	__u8		vendor_id[8];		/* Vendor Identification */
1017	__u8		product_id[16];		/* Product Identification */
1018	__u8		revision_level[4];	/* Revision Level */
1019	__u8		vendor_specific[20];	/* Vendor Specific - Optional */
1020	__u8		reserved56t95[40];	/* Reserved - Optional */
1021						/* Additional information may be returned */
1022} idetape_inquiry_result_t;
1023
1024/*
1025 *	READ POSITION packet command - Data Format (From Table 6-57)
1026 */
1027typedef struct {
1028	unsigned	reserved0_10	:2;	/* Reserved */
1029	unsigned	bpu		:1;	/* Block Position Unknown */
1030	unsigned	reserved0_543	:3;	/* Reserved */
1031	unsigned	eop		:1;	/* End Of Partition */
1032	unsigned	bop		:1;	/* Beginning Of Partition */
1033	u8		partition;		/* Partition Number */
1034	u8		reserved2, reserved3;	/* Reserved */
1035	u32		first_block;		/* First Block Location */
1036	u32		last_block;		/* Last Block Location (Optional) */
1037	u8		reserved12;		/* Reserved */
1038	u8		blocks_in_buffer[3];	/* Blocks In Buffer - (Optional) */
1039	u32		bytes_in_buffer;	/* Bytes In Buffer (Optional) */
1040} idetape_read_position_result_t;
1041
1042/*
1043 *	Follows structures which are related to the SELECT SENSE / MODE SENSE
1044 *	packet commands. Those packet commands are still not supported
1045 *	by ide-tape.
1046 */
1047#define IDETAPE_BLOCK_DESCRIPTOR	0
1048#define	IDETAPE_CAPABILITIES_PAGE	0x2a
1049#define IDETAPE_PARAMTR_PAGE		0x2b   /* Onstream DI-x0 only */
1050#define IDETAPE_BLOCK_SIZE_PAGE		0x30
1051#define IDETAPE_BUFFER_FILLING_PAGE	0x33
1052
1053/*
1054 *	Mode Parameter Header for the MODE SENSE packet command
1055 */
1056typedef struct {
1057	__u8	mode_data_length;	/* Length of the following data transfer */
1058	__u8	medium_type;		/* Medium Type */
1059	__u8	dsp;			/* Device Specific Parameter */
1060	__u8	bdl;			/* Block Descriptor Length */
1061} idetape_mode_parameter_header_t;
1062
1063/*
1064 *	Mode Parameter Block Descriptor the MODE SENSE packet command
1065 *
1066 *	Support for block descriptors is optional.
1067 */
1068typedef struct {
1069	__u8		density_code;		/* Medium density code */
1070	__u8		blocks[3];		/* Number of blocks */
1071	__u8		reserved4;		/* Reserved */
1072	__u8		length[3];		/* Block Length */
1073} idetape_parameter_block_descriptor_t;
1074
1075/*
1076 *	The Data Compression Page, as returned by the MODE SENSE packet command.
1077 */
1078typedef struct {
1079	unsigned	page_code	:6;	/* Page Code - Should be 0xf */
1080	unsigned	reserved0	:1;	/* Reserved */
1081	unsigned	ps		:1;
1082	__u8		page_length;		/* Page Length - Should be 14 */
1083	unsigned	reserved2	:6;	/* Reserved */
1084	unsigned	dcc		:1;	/* Data Compression Capable */
1085	unsigned	dce		:1;	/* Data Compression Enable */
1086	unsigned	reserved3	:5;	/* Reserved */
1087	unsigned	red		:2;	/* Report Exception on Decompression */
1088	unsigned	dde		:1;	/* Data Decompression Enable */
1089	__u32		ca;			/* Compression Algorithm */
1090	__u32		da;			/* Decompression Algorithm */
1091	__u8		reserved[4];		/* Reserved */
1092} idetape_data_compression_page_t;
1093
1094/*
1095 *	The Medium Partition Page, as returned by the MODE SENSE packet command.
1096 */
1097typedef struct {
1098	unsigned	page_code	:6;	/* Page Code - Should be 0x11 */
1099	unsigned	reserved1_6	:1;	/* Reserved */
1100	unsigned	ps		:1;
1101	__u8		page_length;		/* Page Length - Should be 6 */
1102	__u8		map;			/* Maximum Additional Partitions - Should be 0 */
1103	__u8		apd;			/* Additional Partitions Defined - Should be 0 */
1104	unsigned	reserved4_012	:3;	/* Reserved */
1105	unsigned	psum		:2;	/* Should be 0 */
1106	unsigned	idp		:1;	/* Should be 0 */
1107	unsigned	sdp		:1;	/* Should be 0 */
1108	unsigned	fdp		:1;	/* Fixed Data Partitions */
1109	__u8		mfr;			/* Medium Format Recognition */
1110	__u8		reserved[2];		/* Reserved */
1111} idetape_medium_partition_page_t;
1112
1113/*
1114 *	Run time configurable parameters.
1115 */
1116typedef struct {
1117	int	dsc_rw_frequency;
1118	int	dsc_media_access_frequency;
1119	int	nr_stages;
1120} idetape_config_t;
1121
1122/*
1123 *	The variables below are used for the character device interface.
1124 *	Additional state variables are defined in our ide_drive_t structure.
1125 */
1126static idetape_chrdev_t idetape_chrdevs[MAX_HWIFS * MAX_DRIVES];
1127static int idetape_chrdev_present = 0;
1128
1129#if IDETAPE_DEBUG_LOG_VERBOSE
1130
1131/*
1132 * DO NOT REMOVE, BUILDING A VERBOSE DEBUG SCHEME FOR ATAPI
1133 */
1134
1135char *idetape_sense_key_verbose (byte idetape_sense_key)
1136{
1137	switch (idetape_sense_key) {
1138		default: {
1139			char buf[22];
1140			sprintf(buf, "IDETAPE_SENSE (0x%02x)", idetape_sense_key);
1141			return(buf);
1142		}
1143
1144	}
1145}
1146
1147char *idetape_command_key_verbose (byte idetape_command_key)
1148{
1149	switch (idetape_command_key) {
1150		case IDETAPE_TEST_UNIT_READY_CMD:	return("TEST_UNIT_READY_CMD");
1151		case IDETAPE_REWIND_CMD:		return("REWIND_CMD");
1152		case IDETAPE_REQUEST_SENSE_CMD:		return("REQUEST_SENSE_CMD");
1153		case IDETAPE_READ_CMD:			return("READ_CMD");
1154		case IDETAPE_WRITE_CMD:			return("WRITE_CMD");
1155		case IDETAPE_WRITE_FILEMARK_CMD:	return("WRITE_FILEMARK_CMD");
1156		case IDETAPE_SPACE_CMD:			return("SPACE_CMD");
1157		case IDETAPE_INQUIRY_CMD:		return("INQUIRY_CMD");
1158		case IDETAPE_ERASE_CMD:			return("ERASE_CMD");
1159		case IDETAPE_MODE_SENSE_CMD:		return("MODE_SENSE_CMD");
1160		case IDETAPE_MODE_SELECT_CMD:		return("MODE_SELECT_CMD");
1161		case IDETAPE_LOAD_UNLOAD_CMD:		return("LOAD_UNLOAD_CMD");
1162		case IDETAPE_PREVENT_CMD:		return("PREVENT_CMD");
1163		case IDETAPE_LOCATE_CMD:		return("LOCATE_CMD");
1164		case IDETAPE_READ_POSITION_CMD:		return("READ_POSITION_CMD");
1165		case IDETAPE_READ_BUFFER_CMD:		return("READ_BUFFER_CMD");
1166		case IDETAPE_SET_SPEED_CMD:		return("SET_SPEED_CMD");
1167		default: {
1168				char buf[20];
1169				sprintf(buf, "CMD (0x%02x)", idetape_command_key);
1170				return(buf);
1171			}
1172	}
1173}
1174#endif /* IDETAPE_DEBUG_LOG_VERBOSE */
1175
1176/*
1177 *      Function declarations
1178 *
1179 */
1180static void idetape_onstream_mode_sense_tape_parameter_page(ide_drive_t *drive, int debug);
1181static int idetape_chrdev_release (struct inode *inode, struct file *filp);
1182static void idetape_write_release (struct inode *inode);
1183
1184/*
1185 *	Too bad. The drive wants to send us data which we are not ready to accept.
1186 *	Just throw it away.
1187 */
1188static void idetape_discard_data (ide_drive_t *drive, unsigned int bcount)
1189{
1190	while (bcount--)
1191		IN_BYTE (IDE_DATA_REG);
1192}
1193
1194static void idetape_input_buffers (ide_drive_t *drive, idetape_pc_t *pc, unsigned int bcount)
1195{
1196	struct buffer_head *bh = pc->bh;
1197	int count;
1198
1199	while (bcount) {
1200#if IDETAPE_DEBUG_BUGS
1201		if (bh == NULL) {
1202			printk (KERN_ERR "ide-tape: bh == NULL in idetape_input_buffers\n");
1203			idetape_discard_data (drive, bcount);
1204			return;
1205		}
1206#endif /* IDETAPE_DEBUG_BUGS */
1207		count = IDE_MIN (bh->b_size - atomic_read(&bh->b_count), bcount);
1208		atapi_input_bytes (drive, bh->b_data + atomic_read(&bh->b_count), count);
1209		bcount -= count;
1210		atomic_add(count, &bh->b_count);
1211		if (atomic_read(&bh->b_count) == bh->b_size) {
1212			bh = bh->b_reqnext;
1213			if (bh)
1214				atomic_set(&bh->b_count, 0);
1215		}
1216	}
1217	pc->bh = bh;
1218}
1219
1220static void idetape_output_buffers (ide_drive_t *drive, idetape_pc_t *pc, unsigned int bcount)
1221{
1222	struct buffer_head *bh = pc->bh;
1223	int count;
1224
1225	while (bcount) {
1226#if IDETAPE_DEBUG_BUGS
1227		if (bh == NULL) {
1228			printk (KERN_ERR "ide-tape: bh == NULL in idetape_output_buffers\n");
1229			return;
1230		}
1231#endif /* IDETAPE_DEBUG_BUGS */
1232		count = IDE_MIN (pc->b_count, bcount);
1233		atapi_output_bytes (drive, pc->b_data, count);
1234		bcount -= count;
1235		pc->b_data += count;
1236		pc->b_count -= count;
1237		if (!pc->b_count) {
1238			pc->bh = bh = bh->b_reqnext;
1239			if (bh) {
1240				pc->b_data = bh->b_data;
1241				pc->b_count = atomic_read(&bh->b_count);
1242			}
1243		}
1244	}
1245}
1246
1247#ifdef CONFIG_BLK_DEV_IDEDMA
1248static void idetape_update_buffers (idetape_pc_t *pc)
1249{
1250	struct buffer_head *bh = pc->bh;
1251	int count, bcount = pc->actually_transferred;
1252
1253	if (test_bit (PC_WRITING, &pc->flags))
1254		return;
1255	while (bcount) {
1256#if IDETAPE_DEBUG_BUGS
1257		if (bh == NULL) {
1258			printk (KERN_ERR "ide-tape: bh == NULL in idetape_update_buffers\n");
1259			return;
1260		}
1261#endif /* IDETAPE_DEBUG_BUGS */
1262		count = IDE_MIN (bh->b_size, bcount);
1263		atomic_set(&bh->b_count, count);
1264		if (atomic_read(&bh->b_count) == bh->b_size)
1265			bh = bh->b_reqnext;
1266		bcount -= count;
1267	}
1268	pc->bh = bh;
1269}
1270#endif /* CONFIG_BLK_DEV_IDEDMA */
1271
1272/*
1273 *	idetape_next_pc_storage returns a pointer to a place in which we can
1274 *	safely store a packet command, even though we intend to leave the
1275 *	driver. A storage space for a maximum of IDETAPE_PC_STACK packet
1276 *	commands is allocated at initialization time.
1277 */
1278static idetape_pc_t *idetape_next_pc_storage (ide_drive_t *drive)
1279{
1280	idetape_tape_t *tape = drive->driver_data;
1281
1282#if IDETAPE_DEBUG_LOG
1283	if (tape->debug_level >= 5)
1284		printk (KERN_INFO "ide-tape: pc_stack_index=%d\n",tape->pc_stack_index);
1285#endif /* IDETAPE_DEBUG_LOG */
1286	if (tape->pc_stack_index==IDETAPE_PC_STACK)
1287		tape->pc_stack_index=0;
1288	return (&tape->pc_stack[tape->pc_stack_index++]);
1289}
1290
1291/*
1292 *	idetape_next_rq_storage is used along with idetape_next_pc_storage.
1293 *	Since we queue packet commands in the request queue, we need to
1294 *	allocate a request, along with the allocation of a packet command.
1295 */
1296
1297/**************************************************************
1298 *                                                            *
1299 *  This should get fixed to use kmalloc(.., GFP_ATOMIC)      *
1300 *  followed later on by kfree().   -ml                       *
1301 *                                                            *
1302 **************************************************************/
1303
1304static struct request *idetape_next_rq_storage (ide_drive_t *drive)
1305{
1306	idetape_tape_t *tape = drive->driver_data;
1307
1308#if IDETAPE_DEBUG_LOG
1309	if (tape->debug_level >= 5)
1310		printk (KERN_INFO "ide-tape: rq_stack_index=%d\n",tape->rq_stack_index);
1311#endif /* IDETAPE_DEBUG_LOG */
1312	if (tape->rq_stack_index==IDETAPE_PC_STACK)
1313		tape->rq_stack_index=0;
1314	return (&tape->rq_stack[tape->rq_stack_index++]);
1315}
1316
1317/*
1318 *	idetape_init_pc initializes a packet command.
1319 */
1320static void idetape_init_pc (idetape_pc_t *pc)
1321{
1322	memset (pc->c, 0, 12);
1323	pc->retries = 0;
1324	pc->flags = 0;
1325	pc->request_transfer = 0;
1326	pc->buffer = pc->pc_buffer;
1327	pc->buffer_size = IDETAPE_PC_BUFFER_SIZE;
1328	pc->bh = NULL;
1329	pc->b_data = NULL;
1330}
1331
1332/*
1333 *	idetape_analyze_error is called on each failed packet command retry
1334 *	to analyze the request sense. We currently do not utilize this
1335 *	information.
1336 */
1337static void idetape_analyze_error (ide_drive_t *drive, idetape_request_sense_result_t *result)
1338{
1339	idetape_tape_t *tape = drive->driver_data;
1340	idetape_pc_t *pc = tape->failed_pc;
1341
1342	tape->sense     = *result;
1343	tape->sense_key = result->sense_key;
1344	tape->asc       = result->asc;
1345	tape->ascq      = result->ascq;
1346#if IDETAPE_DEBUG_LOG
1347	/*
1348	 *	Without debugging, we only log an error if we decided to
1349	 *	give up retrying.
1350	 */
1351	if (tape->debug_level >= 1)
1352		printk (KERN_INFO "ide-tape: pc = %x, sense key = %x, asc = %x, ascq = %x\n",
1353				pc->c[0], result->sense_key, result->asc, result->ascq);
1354#if IDETAPE_DEBUG_LOG_VERBOSE
1355	if (tape->debug_level >= 1)
1356		printk (KERN_INFO "ide-tape: pc = %s, sense key = %x, asc = %x, ascq = %x\n",
1357			idetape_command_key_verbose((byte) pc->c[0]),
1358			result->sense_key,
1359			result->asc,
1360			result->ascq);
1361#endif /* IDETAPE_DEBUG_LOG_VERBOSE */
1362#endif /* IDETAPE_DEBUG_LOG */
1363
1364	if (tape->onstream && result->sense_key == 2 && result->asc == 0x53 && result->ascq == 2) {
1365		clear_bit(PC_DMA_ERROR, &pc->flags);
1366		ide_stall_queue(drive, HZ / 2);
1367		return;
1368	}
1369#ifdef CONFIG_BLK_DEV_IDEDMA
1370
1371	/*
1372	 *	Correct pc->actually_transferred by asking the tape.
1373	 */
1374	if (test_bit (PC_DMA_ERROR, &pc->flags)) {
1375		pc->actually_transferred = pc->request_transfer - tape->tape_block_size * ntohl (get_unaligned (&result->information));
1376		idetape_update_buffers (pc);
1377	}
1378#endif /* CONFIG_BLK_DEV_IDEDMA */
1379	if (pc->c[0] == IDETAPE_READ_CMD && result->filemark) {
1380		pc->error = IDETAPE_ERROR_FILEMARK;
1381		set_bit (PC_ABORT, &pc->flags);
1382	}
1383	if (pc->c[0] == IDETAPE_WRITE_CMD) {
1384		if (result->eom || (result->sense_key == 0xd && result->asc == 0x0 && result->ascq == 0x2)) {
1385			pc->error = IDETAPE_ERROR_EOD;
1386			set_bit (PC_ABORT, &pc->flags);
1387		}
1388	}
1389	if (pc->c[0] == IDETAPE_READ_CMD || pc->c[0] == IDETAPE_WRITE_CMD) {
1390		if (result->sense_key == 8) {
1391			pc->error = IDETAPE_ERROR_EOD;
1392			set_bit (PC_ABORT, &pc->flags);
1393		}
1394		if (!test_bit (PC_ABORT, &pc->flags) && (tape->onstream || pc->actually_transferred))
1395			pc->retries = IDETAPE_MAX_PC_RETRIES + 1;
1396	}
1397}
1398
1399static void idetape_abort_pipeline (ide_drive_t *drive)
1400{
1401	idetape_tape_t *tape = drive->driver_data;
1402	idetape_stage_t *stage = tape->next_stage;
1403
1404#if IDETAPE_DEBUG_LOG
1405	if (tape->debug_level >= 4)
1406		printk(KERN_INFO "ide-tape: %s: idetape_abort_pipeline called\n", tape->name);
1407#endif
1408	while (stage) {
1409		if (stage->rq.cmd == IDETAPE_WRITE_RQ)
1410			stage->rq.cmd = IDETAPE_ABORTED_WRITE_RQ;
1411		else if (stage->rq.cmd == IDETAPE_READ_RQ)
1412			stage->rq.cmd = IDETAPE_ABORTED_READ_RQ;
1413		stage = stage->next;
1414	}
1415}
1416
1417/*
1418 *	idetape_active_next_stage will declare the next stage as "active".
1419 */
1420static void idetape_active_next_stage (ide_drive_t *drive)
1421{
1422	idetape_tape_t *tape = drive->driver_data;
1423	idetape_stage_t *stage = tape->next_stage;
1424	struct request *rq = &stage->rq;
1425
1426#if IDETAPE_DEBUG_LOG
1427	if (tape->debug_level >= 4)
1428		printk (KERN_INFO "ide-tape: Reached idetape_active_next_stage\n");
1429#endif /* IDETAPE_DEBUG_LOG */
1430#if IDETAPE_DEBUG_BUGS
1431	if (stage == NULL) {
1432		printk (KERN_ERR "ide-tape: bug: Trying to activate a non existing stage\n");
1433		return;
1434	}
1435#endif /* IDETAPE_DEBUG_BUGS */
1436
1437	rq->buffer = NULL;
1438	rq->bh = stage->bh;
1439	tape->active_data_request = rq;
1440	tape->active_stage = stage;
1441	tape->next_stage = stage->next;
1442}
1443
1444/*
1445 *	idetape_increase_max_pipeline_stages is a part of the feedback
1446 *	loop which tries to find the optimum number of stages. In the
1447 *	feedback loop, we are starting from a minimum maximum number of
1448 *	stages, and if we sense that the pipeline is empty, we try to
1449 *	increase it, until we reach the user compile time memory limit.
1450 */
1451static void idetape_increase_max_pipeline_stages (ide_drive_t *drive)
1452{
1453	idetape_tape_t *tape = drive->driver_data;
1454	int increase = (tape->max_pipeline - tape->min_pipeline) / 10;
1455
1456#if IDETAPE_DEBUG_LOG
1457	if (tape->debug_level >= 4)
1458		printk (KERN_INFO "ide-tape: Reached idetape_increase_max_pipeline_stages\n");
1459#endif /* IDETAPE_DEBUG_LOG */
1460
1461	tape->max_stages += increase;
1462	tape->max_stages = IDE_MAX(tape->max_stages, tape->min_pipeline);
1463	tape->max_stages = IDE_MIN(tape->max_stages, tape->max_pipeline);
1464}
1465
1466/*
1467 *	idetape_kfree_stage calls kfree to completely free a stage, along with
1468 *	its related buffers.
1469 */
1470static void __idetape_kfree_stage (idetape_stage_t *stage)
1471{
1472	struct buffer_head *prev_bh, *bh = stage->bh;
1473	int size;
1474
1475	while (bh != NULL) {
1476		if (bh->b_data != NULL) {
1477			size = (int) bh->b_size;
1478			while (size > 0) {
1479				free_page ((unsigned long) bh->b_data);
1480				size -= PAGE_SIZE;
1481				bh->b_data += PAGE_SIZE;
1482			}
1483		}
1484		prev_bh = bh;
1485		bh = bh->b_reqnext;
1486		kfree (prev_bh);
1487	}
1488	kfree (stage);
1489}
1490
1491static void idetape_kfree_stage (idetape_tape_t *tape, idetape_stage_t *stage)
1492{
1493	__idetape_kfree_stage (stage);
1494}
1495
1496/*
1497 *	idetape_remove_stage_head removes tape->first_stage from the pipeline.
1498 *	The caller should avoid race conditions.
1499 */
1500static void idetape_remove_stage_head (ide_drive_t *drive)
1501{
1502	idetape_tape_t *tape = drive->driver_data;
1503	idetape_stage_t *stage;
1504
1505#if IDETAPE_DEBUG_LOG
1506	if (tape->debug_level >= 4)
1507		printk (KERN_INFO "ide-tape: Reached idetape_remove_stage_head\n");
1508#endif /* IDETAPE_DEBUG_LOG */
1509#if IDETAPE_DEBUG_BUGS
1510	if (tape->first_stage == NULL) {
1511		printk (KERN_ERR "ide-tape: bug: tape->first_stage is NULL\n");
1512		return;
1513	}
1514	if (tape->active_stage == tape->first_stage) {
1515		printk (KERN_ERR "ide-tape: bug: Trying to free our active pipeline stage\n");
1516		return;
1517	}
1518#endif /* IDETAPE_DEBUG_BUGS */
1519	stage = tape->first_stage;
1520	tape->first_stage = stage->next;
1521	idetape_kfree_stage (tape, stage);
1522	tape->nr_stages--;
1523	if (tape->first_stage == NULL) {
1524		tape->last_stage = NULL;
1525#if IDETAPE_DEBUG_BUGS
1526		if (tape->next_stage != NULL)
1527			printk (KERN_ERR "ide-tape: bug: tape->next_stage != NULL\n");
1528		if (tape->nr_stages)
1529			printk (KERN_ERR "ide-tape: bug: nr_stages should be 0 now\n");
1530#endif /* IDETAPE_DEBUG_BUGS */
1531	}
1532}
1533
1534/*
1535 *	idetape_end_request is used to finish servicing a request, and to
1536 *	insert a pending pipeline request into the main device queue.
1537 */
1538static void idetape_end_request (byte uptodate, ide_hwgroup_t *hwgroup)
1539{
1540	ide_drive_t *drive = hwgroup->drive;
1541	struct request *rq = hwgroup->rq;
1542	idetape_tape_t *tape = drive->driver_data;
1543	unsigned long flags;
1544	int error;
1545	int remove_stage = 0;
1546#if ONSTREAM_DEBUG
1547	idetape_stage_t *stage;
1548	os_aux_t *aux;
1549	unsigned char *p;
1550#endif
1551
1552#if IDETAPE_DEBUG_LOG
1553        if (tape->debug_level >= 4)
1554	printk (KERN_INFO "ide-tape: Reached idetape_end_request\n");
1555#endif /* IDETAPE_DEBUG_LOG */
1556
1557	switch (uptodate) {
1558		case 0:	error = IDETAPE_ERROR_GENERAL; break;
1559		case 1: error = 0; break;
1560		default: error = uptodate;
1561	}
1562	rq->errors = error;
1563	if (error)
1564		tape->failed_pc = NULL;
1565
1566	spin_lock_irqsave(&tape->spinlock, flags);
1567	if (tape->active_data_request == rq) {		/* The request was a pipelined data transfer request */
1568		tape->active_stage = NULL;
1569		tape->active_data_request = NULL;
1570		tape->nr_pending_stages--;
1571		if (rq->cmd == IDETAPE_WRITE_RQ) {
1572#if ONSTREAM_DEBUG
1573			if (tape->debug_level >= 2) {
1574				if (tape->onstream) {
1575					stage = tape->first_stage;
1576					aux = stage->aux;
1577					p = stage->bh->b_data;
1578					if (ntohl(aux->logical_blk_num) < 11300 && ntohl(aux->logical_blk_num) > 11100)
1579						printk(KERN_INFO "ide-tape: finished writing logical blk %u (data %x %x %x %x)\n", ntohl(aux->logical_blk_num), *p++, *p++, *p++, *p++);
1580				}
1581			}
1582#endif
1583			if (tape->onstream && !tape->raw) {
1584				if (tape->first_frame_position == OS_DATA_ENDFRAME1) {
1585#if ONSTREAM_DEBUG
1586					if (tape->debug_level >= 2)
1587						printk("ide-tape: %s: skipping over config parition..\n", tape->name);
1588#endif
1589					tape->onstream_write_error = OS_PART_ERROR;
1590					if (tape->waiting)
1591						complete(tape->waiting);
1592				}
1593			}
1594			remove_stage = 1;
1595			if (error) {
1596				set_bit (IDETAPE_PIPELINE_ERROR, &tape->flags);
1597				if (error == IDETAPE_ERROR_EOD)
1598					idetape_abort_pipeline (drive);
1599				if (tape->onstream && !tape->raw && error == IDETAPE_ERROR_GENERAL && tape->sense.sense_key == 3) {
1600					clear_bit (IDETAPE_PIPELINE_ERROR, &tape->flags);
1601					printk(KERN_ERR "ide-tape: %s: write error, enabling error recovery\n", tape->name);
1602					tape->onstream_write_error = OS_WRITE_ERROR;
1603					remove_stage = 0;
1604					tape->nr_pending_stages++;
1605					tape->next_stage = tape->first_stage;
1606					rq->current_nr_sectors = rq->nr_sectors;
1607					if (tape->waiting)
1608						complete(tape->waiting);
1609				}
1610			}
1611		} else if (rq->cmd == IDETAPE_READ_RQ) {
1612			if (error == IDETAPE_ERROR_EOD) {
1613				set_bit (IDETAPE_PIPELINE_ERROR, &tape->flags);
1614				idetape_abort_pipeline(drive);
1615			}
1616		}
1617		if (tape->next_stage != NULL && !tape->onstream_write_error) {
1618			idetape_active_next_stage (drive);
1619
1620			/*
1621			 *	Insert the next request into the request queue.
1622			 */
1623			(void) ide_do_drive_cmd (drive, tape->active_data_request, ide_end);
1624		} else if (!error) {
1625			if (!tape->onstream)
1626				idetape_increase_max_pipeline_stages (drive);
1627		}
1628	}
1629	ide_end_drive_cmd (drive, 0, 0);
1630	if (remove_stage)
1631		idetape_remove_stage_head (drive);
1632	if (tape->active_data_request == NULL)
1633		clear_bit(IDETAPE_PIPELINE_ACTIVE, &tape->flags);
1634	spin_unlock_irqrestore(&tape->spinlock, flags);
1635}
1636
1637static ide_startstop_t idetape_request_sense_callback (ide_drive_t *drive)
1638{
1639	idetape_tape_t *tape = drive->driver_data;
1640
1641#if IDETAPE_DEBUG_LOG
1642	if (tape->debug_level >= 4)
1643		printk (KERN_INFO "ide-tape: Reached idetape_request_sense_callback\n");
1644#endif /* IDETAPE_DEBUG_LOG */
1645	if (!tape->pc->error) {
1646		idetape_analyze_error (drive, (idetape_request_sense_result_t *) tape->pc->buffer);
1647		idetape_end_request (1, HWGROUP (drive));
1648	} else {
1649		printk (KERN_ERR "ide-tape: Error in REQUEST SENSE itself - Aborting request!\n");
1650		idetape_end_request (0, HWGROUP (drive));
1651	}
1652	return ide_stopped;
1653}
1654
1655static void idetape_create_request_sense_cmd (idetape_pc_t *pc)
1656{
1657	idetape_init_pc (pc);
1658	pc->c[0] = IDETAPE_REQUEST_SENSE_CMD;
1659	pc->c[4] = 20;
1660	pc->request_transfer = 18;
1661	pc->callback = &idetape_request_sense_callback;
1662}
1663
1664/*
1665 *	idetape_queue_pc_head generates a new packet command request in front
1666 *	of the request queue, before the current request, so that it will be
1667 *	processed immediately, on the next pass through the driver.
1668 *
1669 *	idetape_queue_pc_head is called from the request handling part of
1670 *	the driver (the "bottom" part). Safe storage for the request should
1671 *	be allocated with idetape_next_pc_storage and idetape_next_rq_storage
1672 *	before calling idetape_queue_pc_head.
1673 *
1674 *	Memory for those requests is pre-allocated at initialization time, and
1675 *	is limited to IDETAPE_PC_STACK requests. We assume that we have enough
1676 *	space for the maximum possible number of inter-dependent packet commands.
1677 *
1678 *	The higher level of the driver - The ioctl handler and the character
1679 *	device handling functions should queue request to the lower level part
1680 *	and wait for their completion using idetape_queue_pc_tail or
1681 *	idetape_queue_rw_tail.
1682 */
1683static void idetape_queue_pc_head (ide_drive_t *drive,idetape_pc_t *pc,struct request *rq)
1684{
1685	ide_init_drive_cmd (rq);
1686	rq->buffer = (char *) pc;
1687	rq->cmd = IDETAPE_PC_RQ1;
1688	(void) ide_do_drive_cmd (drive, rq, ide_preempt);
1689}
1690
1691/*
1692 *	idetape_retry_pc is called when an error was detected during the
1693 *	last packet command. We queue a request sense packet command in
1694 *	the head of the request list.
1695 */
1696static ide_startstop_t idetape_retry_pc (ide_drive_t *drive)
1697{
1698	idetape_tape_t *tape = drive->driver_data;
1699	idetape_pc_t *pc;
1700	struct request *rq;
1701	idetape_error_reg_t error;
1702
1703	error.all = IN_BYTE (IDE_ERROR_REG);
1704	pc = idetape_next_pc_storage (drive);
1705	rq = idetape_next_rq_storage (drive);
1706	idetape_create_request_sense_cmd (pc);
1707	set_bit (IDETAPE_IGNORE_DSC, &tape->flags);
1708	idetape_queue_pc_head (drive, pc, rq);
1709	return ide_stopped;
1710}
1711
1712/*
1713 *	idetape_postpone_request postpones the current request so that
1714 *	ide.c will be able to service requests from another device on
1715 *	the same hwgroup while we are polling for DSC.
1716 */
1717static void idetape_postpone_request (ide_drive_t *drive)
1718{
1719	idetape_tape_t *tape = drive->driver_data;
1720
1721#if IDETAPE_DEBUG_LOG
1722	if (tape->debug_level >= 4)
1723		printk(KERN_INFO "ide-tape: idetape_postpone_request\n");
1724#endif
1725	tape->postponed_rq = HWGROUP(drive)->rq;
1726	ide_stall_queue(drive, tape->dsc_polling_frequency);
1727}
1728
1729/*
1730 *	idetape_pc_intr is the usual interrupt handler which will be called
1731 *	during a packet command. We will transfer some of the data (as
1732 *	requested by the drive) and will re-point interrupt handler to us.
1733 *	When data transfer is finished, we will act according to the
1734 *	algorithm described before idetape_issue_packet_command.
1735 *
1736 */
1737static ide_startstop_t idetape_pc_intr (ide_drive_t *drive)
1738{
1739	idetape_tape_t *tape = drive->driver_data;
1740	idetape_status_reg_t status;
1741	idetape_bcount_reg_t bcount;
1742	idetape_ireason_reg_t ireason;
1743	idetape_pc_t *pc = tape->pc;
1744
1745	unsigned int temp;
1746	unsigned long cmd_time;
1747#if SIMULATE_ERRORS
1748	static int error_sim_count = 0;
1749#endif
1750
1751#if IDETAPE_DEBUG_LOG
1752	if (tape->debug_level >= 4)
1753		printk (KERN_INFO "ide-tape: Reached idetape_pc_intr interrupt handler\n");
1754#endif /* IDETAPE_DEBUG_LOG */
1755
1756	status.all = GET_STAT();					/* Clear the interrupt */
1757
1758#ifdef CONFIG_BLK_DEV_IDEDMA
1759	if (test_bit (PC_DMA_IN_PROGRESS, &pc->flags)) {
1760		if (HWIF(drive)->dmaproc(ide_dma_end, drive)) {
1761			/*
1762			 * A DMA error is sometimes expected. For example,
1763			 * if the tape is crossing a filemark during a
1764			 * READ command, it will issue an irq and position
1765			 * itself before the filemark, so that only a partial
1766			 * data transfer will occur (which causes the DMA
1767			 * error). In that case, we will later ask the tape
1768			 * how much bytes of the original request were
1769			 * actually transferred (we can't receive that
1770			 * information from the DMA engine on most chipsets).
1771			 */
1772			set_bit (PC_DMA_ERROR, &pc->flags);
1773		} else if (!status.b.check) {
1774			pc->actually_transferred = pc->request_transfer;
1775			idetape_update_buffers (pc);
1776		}
1777#if IDETAPE_DEBUG_LOG
1778		if (tape->debug_level >= 4)
1779			printk (KERN_INFO "ide-tape: DMA finished\n");
1780#endif /* IDETAPE_DEBUG_LOG */
1781	}
1782#endif /* CONFIG_BLK_DEV_IDEDMA */
1783
1784	if (!status.b.drq) {						/* No more interrupts */
1785		cmd_time = (jiffies - tape->cmd_start_time) * 1000 / HZ;
1786		tape->max_cmd_time = IDE_MAX(cmd_time, tape->max_cmd_time);
1787#if IDETAPE_DEBUG_LOG
1788		if (tape->debug_level >= 2)
1789			printk (KERN_INFO "ide-tape: Packet command completed, %d bytes transferred\n", pc->actually_transferred);
1790#endif /* IDETAPE_DEBUG_LOG */
1791		clear_bit (PC_DMA_IN_PROGRESS, &pc->flags);
1792
1793		ide__sti();	/* local CPU only */
1794
1795#if SIMULATE_ERRORS
1796		if ((pc->c[0] == IDETAPE_WRITE_CMD || pc->c[0] == IDETAPE_READ_CMD) && (++error_sim_count % 100) == 0) {
1797			printk(KERN_INFO "ide-tape: %s: simulating error\n", tape->name);
1798			status.b.check = 1;
1799		}
1800#endif
1801		if (status.b.check && pc->c[0] == IDETAPE_REQUEST_SENSE_CMD)
1802			status.b.check = 0;
1803		if (status.b.check || test_bit (PC_DMA_ERROR, &pc->flags)) {	/* Error detected */
1804#if IDETAPE_DEBUG_LOG
1805			if (tape->debug_level >= 1)
1806				printk (KERN_INFO "ide-tape: %s: I/O error, ",tape->name);
1807#endif /* IDETAPE_DEBUG_LOG */
1808			if (pc->c[0] == IDETAPE_REQUEST_SENSE_CMD) {
1809				printk (KERN_ERR "ide-tape: I/O error in request sense command\n");
1810				return ide_do_reset (drive);
1811			}
1812#if IDETAPE_DEBUG_LOG
1813			if (tape->debug_level >= 1)
1814				printk(KERN_INFO "ide-tape: [cmd %x]: check condition\n", pc->c[0]);
1815#endif
1816			return idetape_retry_pc (drive);				/* Retry operation */
1817		}
1818		pc->error = 0;
1819		if (!tape->onstream && test_bit (PC_WAIT_FOR_DSC, &pc->flags) && !status.b.dsc) {	/* Media access command */
1820			tape->dsc_polling_start = jiffies;
1821			tape->dsc_polling_frequency = IDETAPE_DSC_MA_FAST;
1822			tape->dsc_timeout = jiffies + IDETAPE_DSC_MA_TIMEOUT;
1823			idetape_postpone_request (drive);		/* Allow ide.c to handle other requests */
1824			return ide_stopped;
1825		}
1826		if (tape->failed_pc == pc)
1827			tape->failed_pc = NULL;
1828		return pc->callback(drive);			/* Command finished - Call the callback function */
1829	}
1830#ifdef CONFIG_BLK_DEV_IDEDMA
1831	if (test_and_clear_bit (PC_DMA_IN_PROGRESS, &pc->flags)) {
1832		printk (KERN_ERR "ide-tape: The tape wants to issue more interrupts in DMA mode\n");
1833		printk (KERN_ERR "ide-tape: DMA disabled, reverting to PIO\n");
1834		(void) HWIF(drive)->dmaproc(ide_dma_off, drive);
1835		return ide_do_reset (drive);
1836	}
1837#endif /* CONFIG_BLK_DEV_IDEDMA */
1838	bcount.b.high = IN_BYTE (IDE_BCOUNTH_REG);			/* Get the number of bytes to transfer */
1839	bcount.b.low  = IN_BYTE (IDE_BCOUNTL_REG);			/* on this interrupt */
1840	ireason.all   = IN_BYTE (IDE_IREASON_REG);
1841
1842	if (ireason.b.cod) {
1843		printk (KERN_ERR "ide-tape: CoD != 0 in idetape_pc_intr\n");
1844		return ide_do_reset (drive);
1845	}
1846	if (ireason.b.io == test_bit (PC_WRITING, &pc->flags)) {	/* Hopefully, we will never get here */
1847		printk (KERN_ERR "ide-tape: We wanted to %s, ", ireason.b.io ? "Write":"Read");
1848		printk (KERN_ERR "ide-tape: but the tape wants us to %s !\n",ireason.b.io ? "Read":"Write");
1849		return ide_do_reset (drive);
1850	}
1851	if (!test_bit (PC_WRITING, &pc->flags)) {			/* Reading - Check that we have enough space */
1852		temp = pc->actually_transferred + bcount.all;
1853		if ( temp > pc->request_transfer) {
1854			if (temp > pc->buffer_size) {
1855				printk (KERN_ERR "ide-tape: The tape wants to send us more data than expected - discarding data\n");
1856				idetape_discard_data (drive, bcount.all);
1857				ide_set_handler (drive, &idetape_pc_intr, IDETAPE_WAIT_CMD, NULL);
1858				return ide_started;
1859			}
1860#if IDETAPE_DEBUG_LOG
1861			if (tape->debug_level >= 2)
1862				printk (KERN_NOTICE "ide-tape: The tape wants to send us more data than expected - allowing transfer\n");
1863#endif /* IDETAPE_DEBUG_LOG */
1864		}
1865	}
1866	if (test_bit (PC_WRITING, &pc->flags)) {
1867		if (pc->bh != NULL)
1868			idetape_output_buffers (drive, pc, bcount.all);
1869		else
1870			atapi_output_bytes (drive,pc->current_position,bcount.all);	/* Write the current buffer */
1871	} else {
1872		if (pc->bh != NULL)
1873			idetape_input_buffers (drive, pc, bcount.all);
1874		else
1875			atapi_input_bytes (drive,pc->current_position,bcount.all);	/* Read the current buffer */
1876	}
1877	pc->actually_transferred += bcount.all;					/* Update the current position */
1878	pc->current_position+=bcount.all;
1879#if IDETAPE_DEBUG_LOG
1880	if (tape->debug_level >= 2)
1881		printk(KERN_INFO "ide-tape: [cmd %x] transferred %d bytes on that interrupt\n", pc->c[0], bcount.all);
1882#endif
1883	ide_set_handler (drive, &idetape_pc_intr, IDETAPE_WAIT_CMD, NULL);	/* And set the interrupt handler again */
1884	return ide_started;
1885}
1886
1887/*
1888 *	Packet Command Interface
1889 *
1890 *	The current Packet Command is available in tape->pc, and will not
1891 *	change until we finish handling it. Each packet command is associated
1892 *	with a callback function that will be called when the command is
1893 *	finished.
1894 *
1895 *	The handling will be done in three stages:
1896 *
1897 *	1.	idetape_issue_packet_command will send the packet command to the
1898 *		drive, and will set the interrupt handler to idetape_pc_intr.
1899 *
1900 *	2.	On each interrupt, idetape_pc_intr will be called. This step
1901 *		will be repeated until the device signals us that no more
1902 *		interrupts will be issued.
1903 *
1904 *	3.	ATAPI Tape media access commands have immediate status with a
1905 *		delayed process. In case of a successful initiation of a
1906 *		media access packet command, the DSC bit will be set when the
1907 *		actual execution of the command is finished.
1908 *		Since the tape drive will not issue an interrupt, we have to
1909 *		poll for this event. In this case, we define the request as
1910 *		"low priority request" by setting rq_status to
1911 *		IDETAPE_RQ_POSTPONED, 	set a timer to poll for DSC and exit
1912 *		the driver.
1913 *
1914 *		ide.c will then give higher priority to requests which
1915 *		originate from the other device, until will change rq_status
1916 *		to RQ_ACTIVE.
1917 *
1918 *	4.	When the packet command is finished, it will be checked for errors.
1919 *
1920 *	5.	In case an error was found, we queue a request sense packet command
1921 *		in front of the request queue and retry the operation up to
1922 *		IDETAPE_MAX_PC_RETRIES times.
1923 *
1924 *	6.	In case no error was found, or we decided to give up and not
1925 *		to retry again, the callback function will be called and then
1926 *		we will handle the next request.
1927 *
1928 */
1929static ide_startstop_t idetape_transfer_pc(ide_drive_t *drive)
1930{
1931	idetape_tape_t *tape = drive->driver_data;
1932	idetape_pc_t *pc = tape->pc;
1933	idetape_ireason_reg_t ireason;
1934	int retries = 100;
1935	ide_startstop_t startstop;
1936
1937	if (ide_wait_stat (&startstop,drive,DRQ_STAT,BUSY_STAT,WAIT_READY)) {
1938		printk (KERN_ERR "ide-tape: Strange, packet command initiated yet DRQ isn't asserted\n");
1939		return startstop;
1940	}
1941	ireason.all = IN_BYTE (IDE_IREASON_REG);
1942	while (retries-- && (!ireason.b.cod || ireason.b.io)) {
1943		printk(KERN_ERR "ide-tape: (IO,CoD != (0,1) while issuing a packet command, retrying\n");
1944		udelay(100);
1945		ireason.all = IN_BYTE(IDE_IREASON_REG);
1946		if (retries == 0) {
1947			printk(KERN_ERR "ide-tape: (IO,CoD != (0,1) while issuing a packet command, ignoring\n");
1948			ireason.b.cod = 1;
1949			ireason.b.io = 0;
1950		}
1951	}
1952	if (!ireason.b.cod || ireason.b.io) {
1953		printk (KERN_ERR "ide-tape: (IO,CoD) != (0,1) while issuing a packet command\n");
1954		return ide_do_reset (drive);
1955	}
1956	tape->cmd_start_time = jiffies;
1957	ide_set_handler(drive, &idetape_pc_intr, IDETAPE_WAIT_CMD, NULL);	/* Set the interrupt routine */
1958	atapi_output_bytes (drive,pc->c,12);			/* Send the actual packet */
1959	return ide_started;
1960}
1961
1962static ide_startstop_t idetape_issue_packet_command (ide_drive_t *drive, idetape_pc_t *pc)
1963{
1964	idetape_tape_t *tape = drive->driver_data;
1965	idetape_bcount_reg_t bcount;
1966	int dma_ok = 0;
1967
1968#if IDETAPE_DEBUG_BUGS
1969	if (tape->pc->c[0] == IDETAPE_REQUEST_SENSE_CMD && pc->c[0] == IDETAPE_REQUEST_SENSE_CMD) {
1970		printk (KERN_ERR "ide-tape: possible ide-tape.c bug - Two request sense in serial were issued\n");
1971	}
1972#endif /* IDETAPE_DEBUG_BUGS */
1973
1974	if (tape->failed_pc == NULL && pc->c[0] != IDETAPE_REQUEST_SENSE_CMD)
1975		tape->failed_pc = pc;
1976	tape->pc = pc;							/* Set the current packet command */
1977
1978	if (pc->retries > IDETAPE_MAX_PC_RETRIES || test_bit (PC_ABORT, &pc->flags)) {
1979		/*
1980		 *	We will "abort" retrying a packet command in case
1981		 *	a legitimate error code was received (crossing a
1982		 *	filemark, or DMA error in the end of media, for
1983		 *	example).
1984		 */
1985		if (!test_bit (PC_ABORT, &pc->flags)) {
1986			if (!(pc->c[0] == IDETAPE_TEST_UNIT_READY_CMD && tape->sense_key == 2 &&
1987			      tape->asc == 4 && (tape->ascq == 1 || tape->ascq == 8))) {
1988				printk (KERN_ERR "ide-tape: %s: I/O error, pc = %2x, key = %2x, asc = %2x, ascq = %2x\n",
1989					tape->name, pc->c[0], tape->sense_key, tape->asc, tape->ascq);
1990				if (tape->onstream && pc->c[0] == IDETAPE_READ_CMD && tape->sense_key == 3 && tape->asc == 0x11)  /* AJN-1: 11 should be 0x11 */
1991					printk(KERN_ERR "ide-tape: %s: enabling read error recovery\n", tape->name);
1992			}
1993			pc->error = IDETAPE_ERROR_GENERAL;		/* Giving up */
1994		}
1995		tape->failed_pc = NULL;
1996		return pc->callback(drive);
1997	}
1998#if IDETAPE_DEBUG_LOG
1999	if (tape->debug_level >= 2)
2000		printk (KERN_INFO "ide-tape: Retry number - %d\n", pc->retries);
2001#endif /* IDETAPE_DEBUG_LOG */
2002
2003	pc->retries++;
2004	pc->actually_transferred = 0;					/* We haven't transferred any data yet */
2005	pc->current_position=pc->buffer;
2006	bcount.all=pc->request_transfer;				/* Request to transfer the entire buffer at once */
2007
2008#ifdef CONFIG_BLK_DEV_IDEDMA
2009	if (test_and_clear_bit (PC_DMA_ERROR, &pc->flags)) {
2010		printk (KERN_WARNING "ide-tape: DMA disabled, reverting to PIO\n");
2011		(void) HWIF(drive)->dmaproc(ide_dma_off, drive);
2012	}
2013	if (test_bit (PC_DMA_RECOMMENDED, &pc->flags) && drive->using_dma)
2014		dma_ok = !HWIF(drive)->dmaproc(test_bit (PC_WRITING, &pc->flags) ? ide_dma_write : ide_dma_read, drive);
2015#endif /* CONFIG_BLK_DEV_IDEDMA */
2016
2017	if (IDE_CONTROL_REG)
2018		OUT_BYTE (drive->ctl, IDE_CONTROL_REG);
2019	OUT_BYTE (dma_ok ? 1 : 0,    IDE_FEATURE_REG);			/* Use PIO/DMA */
2020	OUT_BYTE (bcount.b.high,     IDE_BCOUNTH_REG);
2021	OUT_BYTE (bcount.b.low,      IDE_BCOUNTL_REG);
2022	OUT_BYTE (drive->select.all, IDE_SELECT_REG);
2023#ifdef CONFIG_BLK_DEV_IDEDMA
2024	if (dma_ok) {						/* Begin DMA, if necessary */
2025		set_bit (PC_DMA_IN_PROGRESS, &pc->flags);
2026		(void) (HWIF(drive)->dmaproc(ide_dma_begin, drive));
2027	}
2028#endif /* CONFIG_BLK_DEV_IDEDMA */
2029	if (test_bit(IDETAPE_DRQ_INTERRUPT, &tape->flags)) {
2030		ide_set_handler(drive, &idetape_transfer_pc, IDETAPE_WAIT_CMD, NULL);
2031		OUT_BYTE(WIN_PACKETCMD, IDE_COMMAND_REG);
2032		return ide_started;
2033	} else {
2034		OUT_BYTE(WIN_PACKETCMD, IDE_COMMAND_REG);
2035		return idetape_transfer_pc(drive);
2036	}
2037}
2038
2039/*
2040 *	General packet command callback function.
2041 */
2042static ide_startstop_t idetape_pc_callback (ide_drive_t *drive)
2043{
2044	idetape_tape_t *tape = drive->driver_data;
2045
2046#if IDETAPE_DEBUG_LOG
2047	if (tape->debug_level >= 4)
2048		printk (KERN_INFO "ide-tape: Reached idetape_pc_callback\n");
2049#endif /* IDETAPE_DEBUG_LOG */
2050
2051	idetape_end_request (tape->pc->error ? 0 : 1, HWGROUP(drive));
2052	return ide_stopped;
2053}
2054
2055/*
2056 *	A mode sense command is used to "sense" tape parameters.
2057 */
2058static void idetape_create_mode_sense_cmd (idetape_pc_t *pc, byte page_code)
2059{
2060	idetape_init_pc (pc);
2061	pc->c[0] = IDETAPE_MODE_SENSE_CMD;
2062	if (page_code != IDETAPE_BLOCK_DESCRIPTOR)
2063		pc->c[1] = 8;			/* DBD = 1 - Don't return block descriptors */
2064	pc->c[2] = page_code;
2065	pc->c[3] = 255;				/* Don't limit the returned information */
2066	pc->c[4] = 255;				/* (We will just discard data in that case) */
2067	if (page_code == IDETAPE_BLOCK_DESCRIPTOR)
2068		pc->request_transfer = 12;
2069	else if (page_code == IDETAPE_CAPABILITIES_PAGE)
2070		pc->request_transfer = 24;
2071	else
2072		pc->request_transfer = 50;
2073	pc->callback = &idetape_pc_callback;
2074}
2075
2076static ide_startstop_t idetape_onstream_buffer_fill_callback (ide_drive_t *drive)
2077{
2078	idetape_tape_t *tape = drive->driver_data;
2079
2080	tape->max_frames = tape->pc->buffer[4 + 2];
2081	tape->cur_frames = tape->pc->buffer[4 + 3];
2082	if (tape->chrdev_direction == idetape_direction_write)
2083		tape->tape_head = tape->buffer_head - tape->cur_frames;
2084	else
2085		tape->tape_head = tape->buffer_head + tape->cur_frames;
2086	if (tape->tape_head != tape->last_tape_head) {
2087		tape->last_tape_head = tape->tape_head;
2088		tape->tape_still_time_begin = jiffies;
2089		if (tape->tape_still_time > 200)
2090			tape->measure_insert_time = 1;
2091	}
2092	tape->tape_still_time = (jiffies - tape->tape_still_time_begin) * 1000 / HZ;
2093#if USE_IOTRACE
2094	IO_trace(IO_IDETAPE_FIFO, tape->pipeline_head, tape->buffer_head, tape->tape_head, tape->minor);
2095#endif
2096#if IDETAPE_DEBUG_LOG
2097	if (tape->debug_level >= 1)
2098		printk(KERN_INFO "ide-tape: buffer fill callback, %d/%d\n", tape->cur_frames, tape->max_frames);
2099#endif
2100	idetape_end_request (tape->pc->error ? 0 : 1, HWGROUP(drive));
2101	return ide_stopped;
2102}
2103
2104static void idetape_queue_onstream_buffer_fill (ide_drive_t *drive)
2105{
2106	idetape_pc_t *pc;
2107	struct request *rq;
2108
2109	pc = idetape_next_pc_storage (drive);
2110	rq = idetape_next_rq_storage (drive);
2111	idetape_create_mode_sense_cmd (pc, IDETAPE_BUFFER_FILLING_PAGE);
2112	pc->callback = idetape_onstream_buffer_fill_callback;
2113	idetape_queue_pc_head (drive, pc, rq);
2114}
2115
2116static void calculate_speeds(ide_drive_t *drive)
2117{
2118	idetape_tape_t *tape = drive->driver_data;
2119	int full = 125, empty = 75;
2120
2121	if (time_after(jiffies, tape->controlled_pipeline_head_time + 120 * HZ)) {
2122		tape->controlled_previous_pipeline_head = tape->controlled_last_pipeline_head;
2123		tape->controlled_previous_head_time = tape->controlled_pipeline_head_time;
2124		tape->controlled_last_pipeline_head = tape->pipeline_head;
2125		tape->controlled_pipeline_head_time = jiffies;
2126	}
2127	if (time_after(jiffies, tape->controlled_pipeline_head_time + 60 * HZ))
2128		tape->controlled_pipeline_head_speed = (tape->pipeline_head - tape->controlled_last_pipeline_head) * 32 * HZ / (jiffies - tape->controlled_pipeline_head_time);
2129	else if (time_after(jiffies, tape->controlled_previous_head_time))
2130		tape->controlled_pipeline_head_speed = (tape->pipeline_head - tape->controlled_previous_pipeline_head) * 32 * HZ / (jiffies - tape->controlled_previous_head_time);
2131
2132	if (tape->nr_pending_stages < tape->max_stages /*- 1 */) { /* -1 for read mode error recovery */
2133		if (time_after(jiffies, tape->uncontrolled_previous_head_time + 10 * HZ)) {
2134			tape->uncontrolled_pipeline_head_time = jiffies;
2135			tape->uncontrolled_pipeline_head_speed = (tape->pipeline_head - tape->uncontrolled_previous_pipeline_head) * 32 * HZ / (jiffies - tape->uncontrolled_previous_head_time);
2136		}
2137	} else {
2138		tape->uncontrolled_previous_head_time = jiffies;
2139		tape->uncontrolled_previous_pipeline_head = tape->pipeline_head;
2140		if (time_after(jiffies, tape->uncontrolled_pipeline_head_time + 30 * HZ)) {
2141			tape->uncontrolled_pipeline_head_time = jiffies;
2142		}
2143	}
2144	tape->pipeline_head_speed = IDE_MAX(tape->uncontrolled_pipeline_head_speed, tape->controlled_pipeline_head_speed);
2145	if (tape->speed_control == 0) {
2146		tape->max_insert_speed = 5000;
2147	} else if (tape->speed_control == 1) {
2148		if (tape->nr_pending_stages >= tape->max_stages / 2)
2149			tape->max_insert_speed = tape->pipeline_head_speed +
2150				(1100 - tape->pipeline_head_speed) * 2 * (tape->nr_pending_stages - tape->max_stages / 2) / tape->max_stages;
2151		else
2152			tape->max_insert_speed = 500 +
2153				(tape->pipeline_head_speed - 500) * 2 * tape->nr_pending_stages / tape->max_stages;
2154		if (tape->nr_pending_stages >= tape->max_stages * 99 / 100)
2155			tape->max_insert_speed = 5000;
2156	} else if (tape->speed_control == 2) {
2157		tape->max_insert_speed = tape->pipeline_head_speed * empty / 100 +
2158			(tape->pipeline_head_speed * full / 100 - tape->pipeline_head_speed * empty / 100) * tape->nr_pending_stages / tape->max_stages;
2159	} else
2160		tape->max_insert_speed = tape->speed_control;
2161	tape->max_insert_speed = IDE_MAX(tape->max_insert_speed, 500);
2162}
2163
2164static ide_startstop_t idetape_media_access_finished (ide_drive_t *drive)
2165{
2166	idetape_tape_t *tape = drive->driver_data;
2167	idetape_pc_t *pc = tape->pc;
2168	idetape_status_reg_t status;
2169
2170	if (tape->onstream)
2171		printk(KERN_INFO "ide-tape: bug: onstream, media_access_finished\n");
2172	status.all = GET_STAT();
2173	if (status.b.dsc) {
2174		if (status.b.check) {					/* Error detected */
2175			printk (KERN_ERR "ide-tape: %s: I/O error, ",tape->name);
2176			return idetape_retry_pc (drive);			/* Retry operation */
2177		}
2178		pc->error = 0;
2179		if (tape->failed_pc == pc)
2180			tape->failed_pc = NULL;
2181	} else {
2182		pc->error = IDETAPE_ERROR_GENERAL;
2183		tape->failed_pc = NULL;
2184	}
2185	return pc->callback (drive);
2186}
2187
2188static ide_startstop_t idetape_rw_callback (ide_drive_t *drive)
2189{
2190	idetape_tape_t *tape = drive->driver_data;
2191	struct request *rq = HWGROUP(drive)->rq;
2192	int blocks = tape->pc->actually_transferred / tape->tape_block_size;
2193
2194	tape->avg_size += blocks * tape->tape_block_size;
2195	tape->insert_size += blocks * tape->tape_block_size;
2196	if (tape->insert_size > 1024 * 1024)
2197		tape->measure_insert_time = 1;
2198	if (tape->measure_insert_time) {
2199		tape->measure_insert_time = 0;
2200		tape->insert_time = jiffies;
2201		tape->insert_size = 0;
2202	}
2203	if (time_after(jiffies, tape->insert_time))
2204		tape->insert_speed = tape->insert_size / 1024 * HZ / (jiffies - tape->insert_time);
2205	if (jiffies - tape->avg_time >= HZ) {
2206		tape->avg_speed = tape->avg_size * HZ / (jiffies - tape->avg_time) / 1024;
2207		tape->avg_size = 0;
2208		tape->avg_time = jiffies;
2209	}
2210
2211#if IDETAPE_DEBUG_LOG
2212	if (tape->debug_level >= 4)
2213		printk (KERN_INFO "ide-tape: Reached idetape_rw_callback\n");
2214#endif /* IDETAPE_DEBUG_LOG */
2215
2216	tape->first_frame_position += blocks;
2217	rq->current_nr_sectors -= blocks;
2218
2219	if (!tape->pc->error)
2220		idetape_end_request (1, HWGROUP (drive));
2221	else
2222		idetape_end_request (tape->pc->error, HWGROUP (drive));
2223	return ide_stopped;
2224}
2225
2226static void idetape_create_read_cmd (idetape_tape_t *tape, idetape_pc_t *pc, unsigned int length, struct buffer_head *bh)
2227{
2228	struct buffer_head *p = bh;
2229	idetape_init_pc (pc);
2230	pc->c[0] = IDETAPE_READ_CMD;
2231	put_unaligned (htonl (length), (unsigned int *) &pc->c[1]);
2232	pc->c[1] = 1;
2233	pc->callback = &idetape_rw_callback;
2234	pc->bh = bh;
2235	atomic_set(&bh->b_count, 0);
2236	pc->buffer = NULL;
2237	if (tape->onstream) {
2238		while (p) {
2239			atomic_set(&p->b_count, 0);
2240			p = p->b_reqnext;
2241		}
2242	}
2243	if (!tape->onstream) {
2244		pc->request_transfer = pc->buffer_size = length * tape->tape_block_size;
2245		if (pc->request_transfer == tape->stage_size)
2246			set_bit (PC_DMA_RECOMMENDED, &pc->flags);
2247	} else  {
2248		if (length) {
2249			pc->request_transfer = pc->buffer_size = 32768 + 512;
2250			set_bit (PC_DMA_RECOMMENDED, &pc->flags);
2251		} else
2252			pc->request_transfer = 0;
2253	}
2254}
2255
2256static void idetape_create_read_buffer_cmd(idetape_tape_t *tape, idetape_pc_t *pc, unsigned int length, struct buffer_head *bh)
2257{
2258	int size = 32768;
2259
2260	struct buffer_head *p = bh;
2261	idetape_init_pc (pc);
2262	pc->c[0] = IDETAPE_READ_BUFFER_CMD;
2263	pc->c[1] = IDETAPE_RETRIEVE_FAULTY_BLOCK;
2264	pc->c[7] = size >> 8;
2265	pc->c[8] = size & 0xff;
2266	pc->callback = &idetape_pc_callback;
2267	pc->bh = bh;
2268	atomic_set(&bh->b_count, 0);
2269	pc->buffer = NULL;
2270	while (p) {
2271		atomic_set(&p->b_count, 0);
2272		p = p->b_reqnext;
2273	}
2274	pc->request_transfer = pc->buffer_size = size;
2275}
2276
2277static void idetape_create_write_cmd (idetape_tape_t *tape, idetape_pc_t *pc, unsigned int length, struct buffer_head *bh)
2278{
2279	struct buffer_head *p = bh;
2280	idetape_init_pc (pc);
2281	pc->c[0] = IDETAPE_WRITE_CMD;
2282	put_unaligned (htonl (length), (unsigned int *) &pc->c[1]);
2283	pc->c[1] = 1;
2284	pc->callback = &idetape_rw_callback;
2285	set_bit (PC_WRITING, &pc->flags);
2286	if (tape->onstream) {
2287		while (p) {
2288			atomic_set(&p->b_count, p->b_size);
2289			p = p->b_reqnext;
2290		}
2291	}
2292	pc->bh = bh;
2293	pc->b_data = bh->b_data;
2294	pc->b_count = atomic_read(&bh->b_count);
2295	pc->buffer = NULL;
2296	if (!tape->onstream) {
2297		pc->request_transfer = pc->buffer_size = length * tape->tape_block_size;
2298		if (pc->request_transfer == tape->stage_size)
2299			set_bit (PC_DMA_RECOMMENDED, &pc->flags);
2300	} else  {
2301		if (length) {
2302			pc->request_transfer = pc->buffer_size = 32768 + 512;
2303			set_bit (PC_DMA_RECOMMENDED, &pc->flags);
2304		} else
2305			pc->request_transfer = 0;
2306	}
2307}
2308
2309/*
2310 *	idetape_do_request is our request handling function.
2311 */
2312static ide_startstop_t idetape_do_request (ide_drive_t *drive, struct request *rq, unsigned long block)
2313{
2314	idetape_tape_t *tape = drive->driver_data;
2315	idetape_pc_t *pc;
2316	struct request *postponed_rq = tape->postponed_rq;
2317	idetape_status_reg_t status;
2318
2319#if IDETAPE_DEBUG_LOG
2320	if (tape->debug_level >= 5)
2321		printk (KERN_INFO "ide-tape: rq_status: %d, rq_dev: %u, cmd: %d, errors: %d\n",rq->rq_status,(unsigned int) rq->rq_dev,rq->cmd,rq->errors);
2322	if (tape->debug_level >= 2)
2323		printk (KERN_INFO "ide-tape: sector: %ld, nr_sectors: %ld, current_nr_sectors: %ld\n",rq->sector,rq->nr_sectors,rq->current_nr_sectors);
2324#endif /* IDETAPE_DEBUG_LOG */
2325
2326	if (!IDETAPE_RQ_CMD (rq->cmd)) {
2327		/*
2328		 *	We do not support buffer cache originated requests.
2329		 */
2330		printk (KERN_NOTICE "ide-tape: %s: Unsupported command in request queue (%d)\n", drive->name, rq->cmd);
2331		ide_end_request (0, HWGROUP (drive));			/* Let the common code handle it */
2332		return ide_stopped;
2333	}
2334
2335	/*
2336	 *	Retry a failed packet command
2337	 */
2338	if (tape->failed_pc != NULL && tape->pc->c[0] == IDETAPE_REQUEST_SENSE_CMD) {
2339		return idetape_issue_packet_command (drive, tape->failed_pc);
2340	}
2341#if IDETAPE_DEBUG_BUGS
2342	if (postponed_rq != NULL)
2343		if (rq != postponed_rq) {
2344			printk (KERN_ERR "ide-tape: ide-tape.c bug - Two DSC requests were queued\n");
2345			idetape_end_request (0, HWGROUP (drive));
2346			return ide_stopped;
2347		}
2348#endif /* IDETAPE_DEBUG_BUGS */
2349
2350	tape->postponed_rq = NULL;
2351
2352	/*
2353	 *	If the tape is still busy, postpone our request and service
2354	 *	the other device meanwhile.
2355	 */
2356	status.all = GET_STAT();
2357
2358	/*
2359	 * The OnStream tape drive doesn't support DSC. Assume
2360	 * that DSC is always set.
2361	 */
2362	if (tape->onstream)
2363		status.b.dsc = 1;
2364	if (!drive->dsc_overlap && rq->cmd != IDETAPE_PC_RQ2)
2365		set_bit (IDETAPE_IGNORE_DSC, &tape->flags);
2366
2367	/*
2368	 * For the OnStream tape, check the current status of the tape
2369	 * internal buffer using data gathered from the buffer fill
2370	 * mode page, and postpone our request, effectively "disconnecting"
2371	 * from the IDE bus, in case the buffer is full (writing) or
2372	 * empty (reading), and there is a danger that our request will
2373	 * hold the IDE bus during actual media access.
2374	 */
2375	if (tape->tape_still_time > 100 && tape->tape_still_time < 200)
2376		tape->measure_insert_time = 1;
2377	if (tape->req_buffer_fill && (rq->cmd == IDETAPE_WRITE_RQ || rq->cmd == IDETAPE_READ_RQ)) {
2378		tape->req_buffer_fill = 0;
2379		tape->writes_since_buffer_fill = 0;
2380		tape->reads_since_buffer_fill = 0;
2381		tape->last_buffer_fill = jiffies;
2382		idetape_queue_onstream_buffer_fill(drive);
2383		if (time_after(jiffies, tape->insert_time))
2384			tape->insert_speed = tape->insert_size / 1024 * HZ / (jiffies - tape->insert_time);
2385		return ide_stopped;
2386	}
2387	if (time_after(jiffies, tape->insert_time))
2388		tape->insert_speed = tape->insert_size / 1024 * HZ / (jiffies - tape->insert_time);
2389	calculate_speeds(drive);
2390	if (tape->onstream && tape->max_frames &&
2391	    ((rq->cmd == IDETAPE_WRITE_RQ &&
2392              ( tape->cur_frames == tape->max_frames ||
2393                ( tape->speed_control && tape->cur_frames > 5 &&
2394                       (tape->insert_speed > tape->max_insert_speed ||
2395                        (0 /* tape->cur_frames > 30 && tape->tape_still_time > 200 */) ) ) ) ) ||
2396	     (rq->cmd == IDETAPE_READ_RQ &&
2397	      ( tape->cur_frames == 0 ||
2398		( tape->speed_control && (tape->cur_frames < tape->max_frames - 5) &&
2399			tape->insert_speed > tape->max_insert_speed ) ) && rq->nr_sectors) ) ) {
2400#if IDETAPE_DEBUG_LOG
2401		if (tape->debug_level >= 4)
2402			printk(KERN_INFO "ide-tape: postponing request, cmd %d, cur %d, max %d\n",
2403				rq->cmd, tape->cur_frames, tape->max_frames);
2404#endif
2405		if (tape->postpone_cnt++ < 500) {
2406			status.b.dsc = 0;
2407			tape->req_buffer_fill = 1;
2408		}
2409#if ONSTREAM_DEBUG
2410		else if (tape->debug_level >= 4)
2411			printk(KERN_INFO "ide-tape: %s: postpone_cnt %d\n", tape->name, tape->postpone_cnt);
2412#endif
2413	}
2414	if (!test_and_clear_bit (IDETAPE_IGNORE_DSC, &tape->flags) && !status.b.dsc) {
2415		if (postponed_rq == NULL) {
2416			tape->dsc_polling_start = jiffies;
2417			tape->dsc_polling_frequency = tape->best_dsc_rw_frequency;
2418			tape->dsc_timeout = jiffies + IDETAPE_DSC_RW_TIMEOUT;
2419		} else if ((signed long) (jiffies - tape->dsc_timeout) > 0) {
2420			printk (KERN_ERR "ide-tape: %s: DSC timeout\n", tape->name);
2421			if (rq->cmd == IDETAPE_PC_RQ2) {
2422				idetape_media_access_finished (drive);
2423				return ide_stopped;
2424			} else {
2425				return ide_do_reset (drive);
2426			}
2427		} else if (jiffies - tape->dsc_polling_start > IDETAPE_DSC_MA_THRESHOLD)
2428			tape->dsc_polling_frequency = IDETAPE_DSC_MA_SLOW;
2429		idetape_postpone_request (drive);
2430		return ide_stopped;
2431	}
2432	switch (rq->cmd) {
2433		case IDETAPE_READ_RQ:
2434			tape->buffer_head++;
2435#if USE_IOTRACE
2436			IO_trace(IO_IDETAPE_FIFO, tape->pipeline_head, tape->buffer_head, tape->tape_head, tape->minor);
2437#endif
2438			tape->postpone_cnt = 0;
2439			tape->reads_since_buffer_fill++;
2440			if (tape->onstream) {
2441				if (tape->cur_frames - tape->reads_since_buffer_fill <= 0)
2442					tape->req_buffer_fill = 1;
2443				if (time_after(jiffies, tape->last_buffer_fill + 5 * HZ / 100))
2444					tape->req_buffer_fill = 1;
2445			}
2446			pc = idetape_next_pc_storage (drive);
2447			idetape_create_read_cmd (tape, pc, rq->current_nr_sectors, rq->bh);
2448			break;
2449		case IDETAPE_WRITE_RQ:
2450			tape->buffer_head++;
2451#if USE_IOTRACE
2452			IO_trace(IO_IDETAPE_FIFO, tape->pipeline_head, tape->buffer_head, tape->tape_head, tape->minor);
2453#endif
2454			tape->postpone_cnt = 0;
2455			tape->writes_since_buffer_fill++;
2456			if (tape->onstream) {
2457				if (tape->cur_frames + tape->writes_since_buffer_fill >= tape->max_frames)
2458					tape->req_buffer_fill = 1;
2459				if (time_after(jiffies, tape->last_buffer_fill + 5 * HZ / 100))
2460					tape->req_buffer_fill = 1;
2461				calculate_speeds(drive);
2462			}
2463			pc = idetape_next_pc_storage (drive);
2464			idetape_create_write_cmd (tape, pc, rq->current_nr_sectors, rq->bh);
2465			break;
2466		case IDETAPE_READ_BUFFER_RQ:
2467			tape->postpone_cnt = 0;
2468			pc = idetape_next_pc_storage (drive);
2469			idetape_create_read_buffer_cmd (tape, pc, rq->current_nr_sectors, rq->bh);
2470			break;
2471		case IDETAPE_ABORTED_WRITE_RQ:
2472			rq->cmd = IDETAPE_WRITE_RQ;
2473			idetape_end_request (IDETAPE_ERROR_EOD, HWGROUP(drive));
2474			return ide_stopped;
2475		case IDETAPE_ABORTED_READ_RQ:
2476#if IDETAPE_DEBUG_LOG
2477			if (tape->debug_level >= 2)
2478				printk(KERN_INFO "ide-tape: %s: detected aborted read rq\n", tape->name);
2479#endif
2480			rq->cmd = IDETAPE_READ_RQ;
2481			idetape_end_request (IDETAPE_ERROR_EOD, HWGROUP(drive));
2482			return ide_stopped;
2483		case IDETAPE_PC_RQ1:
2484			pc = (idetape_pc_t *) rq->buffer;
2485			rq->cmd = IDETAPE_PC_RQ2;
2486			break;
2487		case IDETAPE_PC_RQ2:
2488			idetape_media_access_finished (drive);
2489			return ide_stopped;
2490		default:
2491			printk (KERN_ERR "ide-tape: bug in IDETAPE_RQ_CMD macro\n");
2492			idetape_end_request (0, HWGROUP (drive));
2493			return ide_stopped;
2494	}
2495	return idetape_issue_packet_command (drive, pc);
2496}
2497
2498/*
2499 *	Pipeline related functions
2500 */
2501static inline int idetape_pipeline_active (idetape_tape_t *tape)
2502{
2503	int rc1, rc2;
2504
2505	rc1 = test_bit(IDETAPE_PIPELINE_ACTIVE, &tape->flags);
2506	rc2 = (tape->active_data_request != NULL);
2507	return rc1;
2508}
2509
2510/*
2511 *	idetape_kmalloc_stage uses __get_free_page to allocate a pipeline
2512 *	stage, along with all the necessary small buffers which together make
2513 *	a buffer of size tape->stage_size (or a bit more). We attempt to
2514 *	combine sequential pages as much as possible.
2515 *
2516 *	Returns a pointer to the new allocated stage, or NULL if we
2517 *	can't (or don't want to) allocate a stage.
2518 *
2519 *	Pipeline stages are optional and are used to increase performance.
2520 *	If we can't allocate them, we'll manage without them.
2521 */
2522static idetape_stage_t *__idetape_kmalloc_stage (idetape_tape_t *tape, int full, int clear)
2523{
2524	idetape_stage_t *stage;
2525	struct buffer_head *prev_bh, *bh;
2526	int pages = tape->pages_per_stage;
2527	char *b_data;
2528
2529	if ((stage = (idetape_stage_t *) kmalloc (sizeof (idetape_stage_t),GFP_KERNEL)) == NULL)
2530		return NULL;
2531	stage->next = NULL;
2532
2533	bh = stage->bh = (struct buffer_head *) kmalloc (sizeof (struct buffer_head), GFP_KERNEL);
2534	if (bh == NULL)
2535		goto abort;
2536	bh->b_reqnext = NULL;
2537	if ((bh->b_data = (char *) __get_free_page (GFP_KERNEL)) == NULL)
2538		goto abort;
2539	if (clear)
2540		memset(bh->b_data, 0, PAGE_SIZE);
2541	bh->b_size = PAGE_SIZE;
2542	atomic_set(&bh->b_count, full ? bh->b_size : 0);
2543	set_bit (BH_Lock, &bh->b_state);
2544
2545	while (--pages) {
2546		if ((b_data = (char *) __get_free_page (GFP_KERNEL)) == NULL)
2547			goto abort;
2548		if (clear)
2549			memset(b_data, 0, PAGE_SIZE);
2550		if (bh->b_data == b_data + PAGE_SIZE) {
2551			bh->b_size += PAGE_SIZE;
2552			bh->b_data -= PAGE_SIZE;
2553			if (full)
2554				atomic_add(PAGE_SIZE, &bh->b_count);
2555			continue;
2556		}
2557		if (b_data == bh->b_data + bh->b_size) {
2558			bh->b_size += PAGE_SIZE;
2559			if (full)
2560				atomic_add(PAGE_SIZE, &bh->b_count);
2561			continue;
2562		}
2563		prev_bh = bh;
2564		if ((bh = (struct buffer_head *) kmalloc (sizeof (struct buffer_head), GFP_KERNEL)) == NULL) {
2565			free_page ((unsigned long) b_data);
2566			goto abort;
2567		}
2568		bh->b_reqnext = NULL;
2569		bh->b_data = b_data;
2570		bh->b_size = PAGE_SIZE;
2571		atomic_set(&bh->b_count, full ? bh->b_size : 0);
2572		set_bit (BH_Lock, &bh->b_state);
2573		prev_bh->b_reqnext = bh;
2574	}
2575	bh->b_size -= tape->excess_bh_size;
2576	if (full)
2577		atomic_sub(tape->excess_bh_size, &bh->b_count);
2578	if (tape->onstream)
2579		stage->aux = (os_aux_t *) (bh->b_data + bh->b_size - OS_AUX_SIZE);
2580	return stage;
2581abort:
2582	__idetape_kfree_stage (stage);
2583	return NULL;
2584}
2585
2586static idetape_stage_t *idetape_kmalloc_stage (idetape_tape_t *tape)
2587{
2588	idetape_stage_t *cache_stage = tape->cache_stage;
2589
2590#if IDETAPE_DEBUG_LOG
2591	if (tape->debug_level >= 4)
2592		printk (KERN_INFO "ide-tape: Reached idetape_kmalloc_stage\n");
2593#endif /* IDETAPE_DEBUG_LOG */
2594
2595	if (tape->nr_stages >= tape->max_stages)
2596		return NULL;
2597	if (cache_stage != NULL) {
2598		tape->cache_stage = NULL;
2599		return cache_stage;
2600	}
2601	return __idetape_kmalloc_stage (tape, 0, 0);
2602}
2603
2604static void idetape_copy_stage_from_user (idetape_tape_t *tape, idetape_stage_t *stage, const char *buf, int n)
2605{
2606	struct buffer_head *bh = tape->bh;
2607	int count;
2608
2609	while (n) {
2610#if IDETAPE_DEBUG_BUGS
2611		if (bh == NULL) {
2612			printk (KERN_ERR "ide-tape: bh == NULL in idetape_copy_stage_from_user\n");
2613			return;
2614		}
2615#endif /* IDETAPE_DEBUG_BUGS */
2616		count = IDE_MIN (bh->b_size - atomic_read(&bh->b_count), n);
2617		copy_from_user (bh->b_data + atomic_read(&bh->b_count), buf, count);
2618		n -= count;
2619		atomic_add(count, &bh->b_count);
2620		buf += count;
2621		if (atomic_read(&bh->b_count) == bh->b_size) {
2622			bh = bh->b_reqnext;
2623			if (bh)
2624				atomic_set(&bh->b_count, 0);
2625		}
2626	}
2627	tape->bh = bh;
2628}
2629
2630static void idetape_copy_stage_to_user (idetape_tape_t *tape, char *buf, idetape_stage_t *stage, int n)
2631{
2632	struct buffer_head *bh = tape->bh;
2633	int count;
2634
2635	while (n) {
2636#if IDETAPE_DEBUG_BUGS
2637		if (bh == NULL) {
2638			printk (KERN_ERR "ide-tape: bh == NULL in idetape_copy_stage_to_user\n");
2639			return;
2640		}
2641#endif /* IDETAPE_DEBUG_BUGS */
2642		count = IDE_MIN (tape->b_count, n);
2643		copy_to_user (buf, tape->b_data, count);
2644		n -= count;
2645		tape->b_data += count;
2646		tape->b_count -= count;
2647		buf += count;
2648		if (!tape->b_count) {
2649			tape->bh = bh = bh->b_reqnext;
2650			if (bh) {
2651				tape->b_data = bh->b_data;
2652				tape->b_count = atomic_read(&bh->b_count);
2653			}
2654		}
2655	}
2656}
2657
2658static void idetape_init_merge_stage (idetape_tape_t *tape)
2659{
2660	struct buffer_head *bh = tape->merge_stage->bh;
2661
2662	tape->bh = bh;
2663	if (tape->chrdev_direction == idetape_direction_write)
2664		atomic_set(&bh->b_count, 0);
2665	else {
2666		tape->b_data = bh->b_data;
2667		tape->b_count = atomic_read(&bh->b_count);
2668	}
2669}
2670
2671static void idetape_switch_buffers (idetape_tape_t *tape, idetape_stage_t *stage)
2672{
2673	struct buffer_head *tmp;
2674	os_aux_t *tmp_aux;
2675
2676	tmp = stage->bh; tmp_aux = stage->aux;
2677	stage->bh = tape->merge_stage->bh; stage->aux = tape->merge_stage->aux;
2678	tape->merge_stage->bh = tmp; tape->merge_stage->aux = tmp_aux;
2679	idetape_init_merge_stage (tape);
2680}
2681
2682/*
2683 *	idetape_add_stage_tail adds a new stage at the end of the pipeline.
2684 */
2685static void idetape_add_stage_tail (ide_drive_t *drive,idetape_stage_t *stage)
2686{
2687	idetape_tape_t *tape = drive->driver_data;
2688	unsigned long flags;
2689
2690#if IDETAPE_DEBUG_LOG
2691	if (tape->debug_level >= 4)
2692		printk (KERN_INFO "ide-tape: Reached idetape_add_stage_tail\n");
2693#endif /* IDETAPE_DEBUG_LOG */
2694	spin_lock_irqsave(&tape->spinlock, flags);
2695	stage->next=NULL;
2696	if (tape->last_stage != NULL)
2697		tape->last_stage->next=stage;
2698	else
2699		tape->first_stage = tape->next_stage=stage;
2700	tape->last_stage = stage;
2701	if (tape->next_stage == NULL)
2702		tape->next_stage = tape->last_stage;
2703	tape->nr_stages++;
2704	tape->nr_pending_stages++;
2705	spin_unlock_irqrestore(&tape->spinlock, flags);
2706}
2707
2708/*
2709 * Initialize the OnStream AUX
2710 */
2711static void idetape_init_stage (ide_drive_t *drive, idetape_stage_t *stage, int frame_type, int logical_blk_num)
2712{
2713	idetape_tape_t *tape = drive->driver_data;
2714	os_aux_t *aux = stage->aux;
2715	os_partition_t *par = &aux->partition;
2716	os_dat_t *dat = &aux->dat;
2717
2718	if (!tape->onstream || tape->raw)
2719		return;
2720	memset(aux, 0, sizeof(*aux));
2721	aux->format_id = htonl(0);
2722	memcpy(aux->application_sig, "LIN3", 4);
2723	aux->hdwr = htonl(0);
2724	aux->frame_type = frame_type;
2725
2726	if (frame_type == OS_FRAME_TYPE_HEADER) {
2727		aux->update_frame_cntr = htonl(tape->update_frame_cntr);
2728		par->partition_num = OS_CONFIG_PARTITION;
2729		par->par_desc_ver = OS_PARTITION_VERSION;
2730		par->wrt_pass_cntr = htons(0xffff);
2731		par->first_frame_addr = htonl(0);
2732		par->last_frame_addr = htonl(0xbb7); /* 2999 */
2733		aux->frame_seq_num = htonl(0);
2734		aux->logical_blk_num_high = htonl(0);
2735		aux->logical_blk_num = htonl(0);
2736		aux->next_mark_addr = htonl(tape->first_mark_addr);
2737	} else {
2738		aux->update_frame_cntr = htonl(0);
2739		par->partition_num = OS_DATA_PARTITION;
2740		par->par_desc_ver = OS_PARTITION_VERSION;
2741		par->wrt_pass_cntr = htons(tape->wrt_pass_cntr);
2742		par->first_frame_addr = htonl(OS_DATA_STARTFRAME1);
2743		par->last_frame_addr = htonl(tape->capacity);
2744		aux->frame_seq_num = htonl(logical_blk_num);
2745		aux->logical_blk_num_high = htonl(0);
2746		aux->logical_blk_num = htonl(logical_blk_num);
2747		dat->dat_sz = 8;
2748		dat->reserved1 = 0;
2749		dat->entry_cnt = 1;
2750		dat->reserved3 = 0;
2751		if (frame_type == OS_FRAME_TYPE_DATA)
2752			dat->dat_list[0].blk_sz = htonl(32 * 1024);
2753		else
2754			dat->dat_list[0].blk_sz = 0;
2755		dat->dat_list[0].blk_cnt = htons(1);
2756		if (frame_type == OS_FRAME_TYPE_MARKER)
2757			dat->dat_list[0].flags = OS_DAT_FLAGS_MARK;
2758		else
2759			dat->dat_list[0].flags = OS_DAT_FLAGS_DATA;
2760		dat->dat_list[0].reserved = 0;
2761	}
2762	aux->filemark_cnt = ntohl(tape->filemark_cnt);		/* shouldn't this be htonl ?? */
2763	aux->phys_fm = ntohl(0xffffffff);			/* shouldn't this be htonl ?? */
2764	aux->last_mark_addr = ntohl(tape->last_mark_addr);	/* shouldn't this be htonl ?? */
2765}
2766
2767/*
2768 *	idetape_wait_for_request installs a completion in a pending request
2769 *	and sleeps until it is serviced.
2770 *
2771 *	The caller should ensure that the request will not be serviced
2772 *	before we install the completion (usually by disabling interrupts).
2773 */
2774static void idetape_wait_for_request (ide_drive_t *drive, struct request *rq)
2775{
2776	DECLARE_COMPLETION(wait);
2777	idetape_tape_t *tape = drive->driver_data;
2778
2779#if IDETAPE_DEBUG_BUGS
2780	if (rq == NULL || !IDETAPE_RQ_CMD (rq->cmd)) {
2781		printk (KERN_ERR "ide-tape: bug: Trying to sleep on non-valid request\n");
2782		return;
2783	}
2784#endif /* IDETAPE_DEBUG_BUGS */
2785	rq->waiting = &wait;
2786	tape->waiting = &wait;
2787	spin_unlock(&tape->spinlock);
2788	wait_for_completion(&wait);
2789	rq->waiting = NULL;
2790	tape->waiting = NULL;
2791	spin_lock_irq(&tape->spinlock);
2792}
2793
2794static ide_startstop_t idetape_read_position_callback (ide_drive_t *drive)
2795{
2796	idetape_tape_t *tape = drive->driver_data;
2797	idetape_read_position_result_t *result;
2798
2799#if IDETAPE_DEBUG_LOG
2800	if (tape->debug_level >= 4)
2801		printk (KERN_INFO "ide-tape: Reached idetape_read_position_callback\n");
2802#endif /* IDETAPE_DEBUG_LOG */
2803
2804	if (!tape->pc->error) {
2805		result = (idetape_read_position_result_t *) tape->pc->buffer;
2806#if IDETAPE_DEBUG_LOG
2807		if (tape->debug_level >= 2)
2808			printk (KERN_INFO "ide-tape: BOP - %s\n",result->bop ? "Yes":"No");
2809		if (tape->debug_level >= 2)
2810			printk (KERN_INFO "ide-tape: EOP - %s\n",result->eop ? "Yes":"No");
2811#endif /* IDETAPE_DEBUG_LOG */
2812		if (result->bpu) {
2813			printk (KERN_INFO "ide-tape: Block location is unknown to the tape\n");
2814			clear_bit (IDETAPE_ADDRESS_VALID, &tape->flags);
2815			idetape_end_request (0, HWGROUP (drive));
2816		} else {
2817#if IDETAPE_DEBUG_LOG
2818			if (tape->debug_level >= 2)
2819				printk (KERN_INFO "ide-tape: Block Location - %u\n", ntohl (result->first_block));
2820#endif /* IDETAPE_DEBUG_LOG */
2821			tape->partition = result->partition;
2822			tape->first_frame_position = ntohl (result->first_block);
2823			tape->last_frame_position = ntohl (result->last_block);
2824			tape->blocks_in_buffer = result->blocks_in_buffer[2];
2825			set_bit (IDETAPE_ADDRESS_VALID, &tape->flags);
2826			idetape_end_request (1, HWGROUP (drive));
2827		}
2828	} else {
2829		idetape_end_request (0, HWGROUP (drive));
2830	}
2831	return ide_stopped;
2832}
2833
2834/*
2835 *	idetape_create_write_filemark_cmd will:
2836 *
2837 *		1.	Write a filemark if write_filemark=1.
2838 *		2.	Flush the device buffers without writing a filemark
2839 *			if write_filemark=0.
2840 *
2841 */
2842static void idetape_create_write_filemark_cmd (ide_drive_t *drive, idetape_pc_t *pc,int write_filemark)
2843{
2844	idetape_tape_t *tape = drive->driver_data;
2845
2846	idetape_init_pc (pc);
2847	pc->c[0] = IDETAPE_WRITE_FILEMARK_CMD;
2848	if (tape->onstream)
2849		pc->c[1] = 1; /* Immed bit */
2850	pc->c[4] = write_filemark;  /* not used for OnStream ?? */
2851	set_bit (PC_WAIT_FOR_DSC, &pc->flags);
2852	pc->callback = &idetape_pc_callback;
2853}
2854
2855static void idetape_create_test_unit_ready_cmd(idetape_pc_t *pc)
2856{
2857	idetape_init_pc(pc);
2858	pc->c[0] = IDETAPE_TEST_UNIT_READY_CMD;
2859	pc->callback = &idetape_pc_callback;
2860}
2861
2862/*
2863 *	idetape_queue_pc_tail is based on the following functions:
2864 *
2865 *	ide_do_drive_cmd from ide.c
2866 *	cdrom_queue_request and cdrom_queue_packet_command from ide-cd.c
2867 *
2868 *	We add a special packet command request to the tail of the request queue,
2869 *	and wait for it to be serviced.
2870 *
2871 *	This is not to be called from within the request handling part
2872 *	of the driver ! We allocate here data in the stack, and it is valid
2873 *	until the request is finished. This is not the case for the bottom
2874 *	part of the driver, where we are always leaving the functions to wait
2875 *	for an interrupt or a timer event.
2876 *
2877 *	From the bottom part of the driver, we should allocate safe memory
2878 *	using idetape_next_pc_storage and idetape_next_rq_storage, and add
2879 *	the request to the request list without waiting for it to be serviced !
2880 *	In that case, we usually use idetape_queue_pc_head.
2881 */
2882static int __idetape_queue_pc_tail (ide_drive_t *drive, idetape_pc_t *pc)
2883{
2884	struct request rq;
2885
2886	ide_init_drive_cmd (&rq);
2887	rq.buffer = (char *) pc;
2888	rq.cmd = IDETAPE_PC_RQ1;
2889	return ide_do_drive_cmd (drive, &rq, ide_wait);
2890}
2891
2892static void idetape_create_load_unload_cmd (ide_drive_t *drive, idetape_pc_t *pc,int cmd)
2893{
2894	idetape_tape_t *tape = drive->driver_data;
2895
2896	idetape_init_pc (pc);
2897	pc->c[0] = IDETAPE_LOAD_UNLOAD_CMD;
2898	pc->c[4] = cmd;
2899	if (tape->onstream) {
2900		pc->c[1] = 1;
2901		if (cmd == !IDETAPE_LU_LOAD_MASK)
2902			pc->c[4] = 4;
2903	}
2904	set_bit (PC_WAIT_FOR_DSC, &pc->flags);
2905	pc->callback = &idetape_pc_callback;
2906}
2907
2908static int idetape_wait_ready (ide_drive_t *drive, unsigned long long timeout)
2909{
2910	idetape_tape_t *tape = drive->driver_data;
2911	idetape_pc_t pc;
2912
2913	/*
2914	 * Wait for the tape to become ready
2915	 */
2916	timeout += jiffies;
2917	while (time_before(jiffies, timeout)) {
2918		idetape_create_test_unit_ready_cmd(&pc);
2919		if (!__idetape_queue_pc_tail(drive, &pc))
2920			return 0;
2921		if (tape->sense_key == 2 && tape->asc == 4 && tape->ascq == 2) {
2922			idetape_create_load_unload_cmd (drive, &pc, IDETAPE_LU_LOAD_MASK);
2923			__idetape_queue_pc_tail(drive, &pc);
2924			idetape_create_test_unit_ready_cmd(&pc);
2925			if (!__idetape_queue_pc_tail(drive, &pc))
2926				return 0;
2927		}
2928		if (!(tape->sense_key == 2 && tape->asc == 4 && (tape->ascq == 1 || tape->ascq == 8)))
2929			break;
2930		current->state = TASK_INTERRUPTIBLE;
2931  		schedule_timeout(HZ / 10);
2932	}
2933	return -EIO;
2934}
2935
2936static int idetape_queue_pc_tail (ide_drive_t *drive,idetape_pc_t *pc)
2937{
2938	idetape_tape_t *tape = drive->driver_data;
2939	int rc;
2940
2941	rc = __idetape_queue_pc_tail(drive, pc);
2942	if (rc)
2943		return rc;
2944	if (tape->onstream && test_bit(PC_WAIT_FOR_DSC, &pc->flags))
2945		rc = idetape_wait_ready(drive, 60 * 10 * HZ);   /* AJN-4: Changed from 5 to 10 minutes;
2946                          because retension takes approx. 8:20 with Onstream 30GB tape */
2947	return rc;
2948}
2949
2950static int idetape_flush_tape_buffers (ide_drive_t *drive)
2951{
2952	idetape_pc_t pc;
2953	int rc;
2954
2955	idetape_create_write_filemark_cmd(drive, &pc, 0);
2956	if ((rc = idetape_queue_pc_tail (drive, &pc)))
2957		return rc;
2958	idetape_wait_ready(drive, 60 * 5 * HZ);
2959	return 0;
2960}
2961
2962static void idetape_create_read_position_cmd (idetape_pc_t *pc)
2963{
2964	idetape_init_pc (pc);
2965	pc->c[0] = IDETAPE_READ_POSITION_CMD;
2966	pc->request_transfer = 20;
2967	pc->callback = &idetape_read_position_callback;
2968}
2969
2970static int idetape_read_position (ide_drive_t *drive)
2971{
2972	idetape_tape_t *tape = drive->driver_data;
2973	idetape_pc_t pc;
2974	int position;
2975
2976#if IDETAPE_DEBUG_LOG
2977        if (tape->debug_level >= 4)
2978	printk (KERN_INFO "ide-tape: Reached idetape_read_position\n");
2979#endif /* IDETAPE_DEBUG_LOG */
2980
2981#ifdef NO_LONGER_REQUIRED
2982	idetape_flush_tape_buffers(drive);
2983#endif
2984	idetape_create_read_position_cmd(&pc);
2985	if (idetape_queue_pc_tail (drive, &pc))
2986		return -1;
2987	position = tape->first_frame_position;
2988#ifdef NO_LONGER_REQUIRED
2989	if (tape->onstream) {
2990		if ((position != tape->last_frame_position - tape->blocks_in_buffer) &&
2991		    (position != tape->last_frame_position + tape->blocks_in_buffer)) {
2992			if (tape->blocks_in_buffer == 0) {
2993				printk("ide-tape: %s: correcting read position %d, %d, %d\n", tape->name, position, tape->last_frame_position, tape->blocks_in_buffer);
2994				position = tape->last_frame_position;
2995				tape->first_frame_position = position;
2996			}
2997		}
2998	}
2999#endif
3000	return position;
3001}
3002
3003static void idetape_create_locate_cmd (ide_drive_t *drive, idetape_pc_t *pc, unsigned int block, byte partition, int skip)
3004{
3005	idetape_tape_t *tape = drive->driver_data;
3006
3007	idetape_init_pc (pc);
3008	pc->c[0] = IDETAPE_LOCATE_CMD;
3009	if (tape->onstream)
3010		pc->c[1] = 1; /* Immediate bit */
3011	else
3012		pc->c[1] = 2;
3013	put_unaligned (htonl (block), (unsigned int *) &pc->c[3]);
3014	pc->c[8] = partition;
3015	if (tape->onstream)
3016                /*
3017                 * Set SKIP bit.
3018                 * In case of write error this will write buffered
3019                 * data in the drive to this new position!
3020                 */
3021		pc->c[9] = skip << 7;
3022	set_bit (PC_WAIT_FOR_DSC, &pc->flags);
3023	pc->callback = &idetape_pc_callback;
3024}
3025
3026static int idetape_create_prevent_cmd (ide_drive_t *drive, idetape_pc_t *pc, int prevent)
3027{
3028	idetape_tape_t *tape = drive->driver_data;
3029
3030	if (!tape->capabilities.lock)
3031		return 0;
3032
3033	idetape_init_pc(pc);
3034	pc->c[0] = IDETAPE_PREVENT_CMD;
3035	pc->c[4] = prevent;
3036	pc->callback = &idetape_pc_callback;
3037	return 1;
3038}
3039
3040static int __idetape_discard_read_pipeline (ide_drive_t *drive)
3041{
3042	idetape_tape_t *tape = drive->driver_data;
3043	unsigned long flags;
3044	int cnt;
3045
3046	if (tape->chrdev_direction != idetape_direction_read)
3047		return 0;
3048	tape->merge_stage_size = 0;
3049	if (tape->merge_stage != NULL) {
3050		__idetape_kfree_stage (tape->merge_stage);
3051		tape->merge_stage = NULL;
3052	}
3053	tape->chrdev_direction = idetape_direction_none;
3054
3055	if (tape->first_stage == NULL)
3056		return 0;
3057
3058	spin_lock_irqsave(&tape->spinlock, flags);
3059	tape->next_stage = NULL;
3060	if (idetape_pipeline_active (tape))
3061		idetape_wait_for_request(drive, tape->active_data_request);
3062	spin_unlock_irqrestore(&tape->spinlock, flags);
3063
3064	cnt = tape->nr_stages - tape->nr_pending_stages;
3065	while (tape->first_stage != NULL)
3066		idetape_remove_stage_head (drive);
3067	tape->nr_pending_stages = 0;
3068	tape->max_stages = tape->min_pipeline;
3069	return cnt;
3070}
3071
3072/*
3073 *	idetape_position_tape positions the tape to the requested block
3074 *	using the LOCATE packet command. A READ POSITION command is then
3075 *	issued to check where we are positioned.
3076 *
3077 *	Like all higher level operations, we queue the commands at the tail
3078 *	of the request queue and wait for their completion.
3079 *
3080 */
3081static int idetape_position_tape (ide_drive_t *drive, unsigned int block, byte partition, int skip)
3082{
3083	idetape_tape_t *tape = drive->driver_data;
3084	int retval;
3085	idetape_pc_t pc;
3086
3087	if (tape->chrdev_direction == idetape_direction_read)
3088		__idetape_discard_read_pipeline(drive);
3089	idetape_wait_ready(drive, 60 * 5 * HZ);
3090	idetape_create_locate_cmd (drive, &pc, block, partition, skip);
3091	retval = idetape_queue_pc_tail (drive, &pc);
3092	if (retval)
3093		return (retval);
3094
3095	idetape_create_read_position_cmd (&pc);
3096	return (idetape_queue_pc_tail (drive, &pc));
3097}
3098
3099static void idetape_discard_read_pipeline (ide_drive_t *drive, int restore_position)
3100{
3101	idetape_tape_t *tape = drive->driver_data;
3102	int cnt;
3103	int seek, position;
3104
3105	cnt = __idetape_discard_read_pipeline(drive);
3106	if (restore_position) {
3107		position = idetape_read_position(drive);
3108#if ONSTREAM_DEBUG
3109		if (tape->debug_level >= 2)
3110			printk(KERN_INFO "ide-tape: address %u, nr_stages %d\n", position, cnt);
3111#endif
3112		seek = position > cnt ? position - cnt : 0;
3113		if (idetape_position_tape(drive, seek, 0, 0)) {
3114			printk(KERN_INFO "ide-tape: %s: position_tape failed in discard_pipeline()\n", tape->name);
3115			return;
3116		}
3117	}
3118}
3119
3120static void idetape_update_stats (ide_drive_t *drive)
3121{
3122	idetape_pc_t pc;
3123
3124	idetape_create_mode_sense_cmd (&pc, IDETAPE_BUFFER_FILLING_PAGE);
3125	pc.callback = idetape_onstream_buffer_fill_callback;
3126	(void) idetape_queue_pc_tail(drive, &pc);
3127}
3128
3129/*
3130 *	idetape_queue_rw_tail generates a read/write request for the block
3131 *	device interface and wait for it to be serviced.
3132 */
3133static int idetape_queue_rw_tail (ide_drive_t *drive, int cmd, int blocks, struct buffer_head *bh)
3134{
3135	idetape_tape_t *tape = drive->driver_data;
3136	struct request rq;
3137
3138#if IDETAPE_DEBUG_LOG
3139	if (tape->debug_level >= 2)
3140		printk (KERN_INFO "ide-tape: idetape_queue_rw_tail: cmd=%d\n",cmd);
3141#endif /* IDETAPE_DEBUG_LOG */
3142#if IDETAPE_DEBUG_BUGS
3143	if (idetape_pipeline_active (tape)) {
3144		printk (KERN_ERR "ide-tape: bug: the pipeline is active in idetape_queue_rw_tail\n");
3145		return (0);
3146	}
3147#endif /* IDETAPE_DEBUG_BUGS */
3148
3149	ide_init_drive_cmd (&rq);
3150	rq.bh = bh;
3151	rq.cmd = cmd;
3152	rq.sector = tape->first_frame_position;
3153	rq.nr_sectors = rq.current_nr_sectors = blocks;
3154	if (tape->onstream)
3155		tape->postpone_cnt = 600;
3156	(void) ide_do_drive_cmd (drive, &rq, ide_wait);
3157
3158	if (cmd != IDETAPE_READ_RQ && cmd != IDETAPE_WRITE_RQ)
3159		return 0;
3160
3161	if (tape->merge_stage)
3162		idetape_init_merge_stage (tape);
3163	if (rq.errors == IDETAPE_ERROR_GENERAL)
3164		return -EIO;
3165	return (tape->tape_block_size * (blocks-rq.current_nr_sectors));
3166}
3167
3168/*
3169 * Read back the drive's internal buffer contents, as a part
3170 * of the write error recovery mechanism for old OnStream
3171 * firmware revisions.
3172 */
3173static void idetape_onstream_read_back_buffer (ide_drive_t *drive)
3174{
3175	idetape_tape_t *tape = drive->driver_data;
3176	int frames, i, logical_blk_num;
3177	idetape_stage_t *stage, *first = NULL, *last = NULL;
3178	os_aux_t *aux;
3179	struct request *rq;
3180	unsigned char *p;
3181	unsigned long flags;
3182
3183	idetape_update_stats(drive);
3184	frames = tape->cur_frames;
3185	logical_blk_num = ntohl(tape->first_stage->aux->logical_blk_num) - frames;
3186	printk(KERN_INFO "ide-tape: %s: reading back %d frames from the drive's internal buffer\n", tape->name, frames);
3187	for (i = 0; i < frames; i++) {
3188		stage = __idetape_kmalloc_stage(tape, 0, 0);
3189		if (!first)
3190			first = stage;
3191		aux = stage->aux;
3192		p = stage->bh->b_data;
3193		idetape_queue_rw_tail(drive, IDETAPE_READ_BUFFER_RQ, tape->capabilities.ctl, stage->bh);
3194#if ONSTREAM_DEBUG
3195		if (tape->debug_level >= 2)
3196			printk(KERN_INFO "ide-tape: %s: read back logical block %d, data %x %x %x %x\n", tape->name, logical_blk_num, *p++, *p++, *p++, *p++);
3197#endif
3198		rq = &stage->rq;
3199		ide_init_drive_cmd (rq);
3200		rq->cmd = IDETAPE_WRITE_RQ;
3201		rq->sector = tape->first_frame_position;
3202		rq->nr_sectors = rq->current_nr_sectors = tape->capabilities.ctl;
3203		idetape_init_stage(drive, stage, OS_FRAME_TYPE_DATA, logical_blk_num++);
3204		stage->next = NULL;
3205		if (last)
3206			last->next = stage;
3207		last = stage;
3208	}
3209	if (frames) {
3210		spin_lock_irqsave(&tape->spinlock, flags);
3211		last->next = tape->first_stage;
3212		tape->next_stage = tape->first_stage = first;
3213		tape->nr_stages += frames;
3214		tape->nr_pending_stages += frames;
3215		spin_unlock_irqrestore(&tape->spinlock, flags);
3216	}
3217	idetape_update_stats(drive);
3218#if ONSTREAM_DEBUG
3219	if (tape->debug_level >= 2)
3220		printk(KERN_INFO "ide-tape: %s: frames left in buffer: %d\n", tape->name, tape->cur_frames);
3221#endif
3222}
3223
3224/*
3225 * Error recovery algorithm for the OnStream tape.
3226 */
3227static void idetape_onstream_write_error_recovery (ide_drive_t *drive)
3228{
3229	idetape_tape_t *tape = drive->driver_data;
3230	unsigned int block;
3231
3232	if (tape->onstream_write_error == OS_WRITE_ERROR) {
3233		printk(KERN_ERR "ide-tape: %s: onstream_write_error_recovery: detected physical bad block at %u, logical %u first frame %u last_frame %u bufblocks %u stages %u skipping %u frames\n",
3234			tape->name, ntohl(tape->sense.information), tape->logical_blk_num,
3235			tape->first_frame_position, tape->last_frame_position,
3236			tape->blocks_in_buffer, tape->nr_stages,
3237 			(ntohl(tape->sense.command_specific) >> 16) & 0xff );
3238		block = ntohl(tape->sense.information) + ((ntohl(tape->sense.command_specific) >> 16) & 0xff);
3239		idetape_update_stats(drive);
3240		printk(KERN_ERR "ide-tape: %s: relocating %d buffered logical blocks to physical block %u\n", tape->name, tape->cur_frames, block);
3241		if (tape->firmware_revision_num >= 106)
3242			idetape_position_tape(drive, block, 0, 1);
3243		else {
3244			idetape_onstream_read_back_buffer(drive);
3245			idetape_position_tape(drive, block, 0, 0);
3246		}
3247#if ONSTREAM_DEBUG
3248		if (tape->debug_level >= 1)
3249			printk(KERN_ERR "ide-tape: %s: positioning complete, cur_frames %d, pos %d, tape pos %d\n", tape->name, tape->cur_frames, tape->first_frame_position, tape->last_frame_position);
3250#endif
3251	} else if (tape->onstream_write_error == OS_PART_ERROR) {
3252#if ONSTREAM_DEBUG
3253		if (tape->debug_level >= 1)
3254			printk(KERN_INFO "ide-tape: %s: skipping over config partition\n", tape->name);
3255#endif
3256		idetape_flush_tape_buffers(drive);
3257		block = idetape_read_position(drive);
3258		if (block != OS_DATA_ENDFRAME1)
3259			printk(KERN_ERR "ide-tape: warning, current position %d, expected %d\n", block, OS_DATA_ENDFRAME1);
3260		idetape_position_tape(drive, 0xbb8, 0, 0); /* 3000 */
3261	}
3262	tape->onstream_write_error = 0;
3263}
3264
3265/*
3266 *	idetape_insert_pipeline_into_queue is used to start servicing the
3267 *	pipeline stages, starting from tape->next_stage.
3268 */
3269static void idetape_insert_pipeline_into_queue (ide_drive_t *drive)
3270{
3271	idetape_tape_t *tape = drive->driver_data;
3272
3273	if (tape->next_stage == NULL)
3274		return;
3275	if (!idetape_pipeline_active (tape)) {
3276		if (tape->onstream_write_error)
3277			idetape_onstream_write_error_recovery(drive);
3278		set_bit(IDETAPE_PIPELINE_ACTIVE, &tape->flags);
3279		idetape_active_next_stage (drive);
3280		(void) ide_do_drive_cmd (drive, tape->active_data_request, ide_end);
3281	}
3282}
3283
3284static void idetape_create_inquiry_cmd (idetape_pc_t *pc)
3285{
3286	idetape_init_pc(pc);
3287	pc->c[0] = IDETAPE_INQUIRY_CMD;
3288	pc->c[4] = pc->request_transfer = 254;
3289	pc->callback = &idetape_pc_callback;
3290}
3291
3292static void idetape_create_rewind_cmd (ide_drive_t *drive, idetape_pc_t *pc)
3293{
3294	idetape_tape_t *tape = drive->driver_data;
3295
3296	idetape_init_pc (pc);
3297	pc->c[0] = IDETAPE_REWIND_CMD;
3298	if (tape->onstream)
3299		pc->c[1] = 1;
3300	set_bit (PC_WAIT_FOR_DSC, &pc->flags);
3301	pc->callback = &idetape_pc_callback;
3302}
3303
3304static void idetape_create_mode_select_cmd (idetape_pc_t *pc, int length)
3305{
3306	idetape_init_pc (pc);
3307	set_bit (PC_WRITING, &pc->flags);
3308	pc->c[0] = IDETAPE_MODE_SELECT_CMD;
3309	pc->c[1] = 0x10;
3310	put_unaligned (htons(length), (unsigned short *) &pc->c[3]);
3311	pc->request_transfer = 255;
3312	pc->callback = &idetape_pc_callback;
3313}
3314
3315static void idetape_create_erase_cmd (idetape_pc_t *pc)
3316{
3317	idetape_init_pc (pc);
3318	pc->c[0] = IDETAPE_ERASE_CMD;
3319	pc->c[1] = 1;
3320	set_bit (PC_WAIT_FOR_DSC, &pc->flags);
3321	pc->callback = &idetape_pc_callback;
3322}
3323
3324static void idetape_create_space_cmd (idetape_pc_t *pc,int count,byte cmd)
3325{
3326	idetape_init_pc (pc);
3327	pc->c[0] = IDETAPE_SPACE_CMD;
3328	put_unaligned (htonl (count), (unsigned int *) &pc->c[1]);
3329	pc->c[1] = cmd;
3330	set_bit (PC_WAIT_FOR_DSC, &pc->flags);
3331	pc->callback = &idetape_pc_callback;
3332}
3333
3334/*
3335 * Verify that we have the correct tape frame
3336 */
3337static int idetape_verify_stage (ide_drive_t *drive, idetape_stage_t *stage, int logical_blk_num, int quiet)
3338{
3339	idetape_tape_t *tape = drive->driver_data;
3340	os_aux_t *aux = stage->aux;
3341	os_partition_t *par = &aux->partition;
3342	struct request *rq = &stage->rq;
3343	struct buffer_head *bh;
3344
3345	if (!tape->onstream)
3346		return 1;
3347	if (tape->raw) {
3348		if (rq->errors) {
3349			bh = stage->bh;
3350			while (bh) {
3351				memset(bh->b_data, 0, bh->b_size);
3352				bh = bh->b_reqnext;
3353			}
3354			strcpy(stage->bh->b_data, "READ ERROR ON FRAME");
3355		}
3356		return 1;
3357	}
3358	if (rq->errors == IDETAPE_ERROR_GENERAL) {
3359		printk(KERN_INFO "ide-tape: %s: skipping frame %d, read error\n", tape->name, tape->first_frame_position);
3360		return 0;
3361	}
3362	if (rq->errors == IDETAPE_ERROR_EOD) {
3363		printk(KERN_INFO "ide-tape: %s: skipping frame %d, eod\n", tape->name, tape->first_frame_position);
3364		return 0;
3365	}
3366	if (ntohl(aux->format_id) != 0) {
3367		printk(KERN_INFO "ide-tape: %s: skipping frame %d, format_id %u\n", tape->name, tape->first_frame_position, ntohl(aux->format_id));
3368		return 0;
3369	}
3370	if (memcmp(aux->application_sig, tape->application_sig, 4) != 0) {
3371		printk(KERN_INFO "ide-tape: %s: skipping frame %d, incorrect application signature\n", tape->name, tape->first_frame_position);
3372		return 0;
3373	}
3374	if (aux->frame_type != OS_FRAME_TYPE_DATA &&
3375	    aux->frame_type != OS_FRAME_TYPE_EOD &&
3376	    aux->frame_type != OS_FRAME_TYPE_MARKER) {
3377		printk(KERN_INFO "ide-tape: %s: skipping frame %d, frame type %x\n", tape->name, tape->first_frame_position, aux->frame_type);
3378		return 0;
3379	}
3380	if (par->partition_num != OS_DATA_PARTITION) {
3381		if (!tape->linux_media || tape->linux_media_version != 2) {
3382			printk(KERN_INFO "ide-tape: %s: skipping frame %d, partition num %d\n", tape->name, tape->first_frame_position, par->partition_num);
3383			return 0;
3384		}
3385	}
3386	if (par->par_desc_ver != OS_PARTITION_VERSION) {
3387		printk(KERN_INFO "ide-tape: %s: skipping frame %d, partition version %d\n", tape->name, tape->first_frame_position, par->par_desc_ver);
3388		return 0;
3389	}
3390	if (ntohs(par->wrt_pass_cntr) != tape->wrt_pass_cntr) {
3391		printk(KERN_INFO "ide-tape: %s: skipping frame %d, wrt_pass_cntr %d (expected %d)(logical_blk_num %u)\n", tape->name, tape->first_frame_position, ntohs(par->wrt_pass_cntr), tape->wrt_pass_cntr, ntohl(aux->logical_blk_num));
3392		return 0;
3393	}
3394	if (aux->frame_seq_num != aux->logical_blk_num) {
3395		printk(KERN_INFO "ide-tape: %s: skipping frame %d, seq != logical\n", tape->name, tape->first_frame_position);
3396		return 0;
3397	}
3398	if (logical_blk_num != -1 && ntohl(aux->logical_blk_num) != logical_blk_num) {
3399		if (!quiet)
3400			printk(KERN_INFO "ide-tape: %s: skipping frame %d, logical_blk_num %u (expected %d)\n", tape->name, tape->first_frame_position, ntohl(aux->logical_blk_num), logical_blk_num);
3401		return 0;
3402	}
3403	if (aux->frame_type == OS_FRAME_TYPE_MARKER) {
3404		rq->errors = IDETAPE_ERROR_FILEMARK;
3405		rq->current_nr_sectors = rq->nr_sectors;
3406	}
3407	return 1;
3408}
3409
3410static void idetape_wait_first_stage (ide_drive_t *drive)
3411{
3412	idetape_tape_t *tape = drive->driver_data;
3413	unsigned long flags;
3414
3415	if (tape->first_stage == NULL)
3416		return;
3417	spin_lock_irqsave(&tape->spinlock, flags);
3418	if (tape->active_stage == tape->first_stage)
3419		idetape_wait_for_request(drive, tape->active_data_request);
3420	spin_unlock_irqrestore(&tape->spinlock, flags);
3421}
3422
3423/*
3424 *	idetape_add_chrdev_write_request tries to add a character device
3425 *	originated write request to our pipeline. In case we don't succeed,
3426 *	we revert to non-pipelined operation mode for this request.
3427 *
3428 *	1.	Try to allocate a new pipeline stage.
3429 *	2.	If we can't, wait for more and more requests to be serviced
3430 *		and try again each time.
3431 *	3.	If we still can't allocate a stage, fallback to
3432 *		non-pipelined operation mode for this request.
3433 */
3434static int idetape_add_chrdev_write_request (ide_drive_t *drive, int blocks)
3435{
3436	idetape_tape_t *tape = drive->driver_data;
3437	idetape_stage_t *new_stage;
3438	unsigned long flags;
3439	struct request *rq;
3440
3441#if IDETAPE_DEBUG_LOG
3442	if (tape->debug_level >= 3)
3443		printk (KERN_INFO "ide-tape: Reached idetape_add_chrdev_write_request\n");
3444#endif /* IDETAPE_DEBUG_LOG */
3445
3446     	/*
3447     	 *	Attempt to allocate a new stage.
3448	 *	Pay special attention to possible race conditions.
3449	 */
3450	while ((new_stage = idetape_kmalloc_stage (tape)) == NULL) {
3451		spin_lock_irqsave(&tape->spinlock, flags);
3452		if (idetape_pipeline_active (tape)) {
3453			idetape_wait_for_request(drive, tape->active_data_request);
3454			spin_unlock_irqrestore(&tape->spinlock, flags);
3455		} else {
3456			spin_unlock_irqrestore(&tape->spinlock, flags);
3457			idetape_insert_pipeline_into_queue (drive);
3458			if (idetape_pipeline_active (tape))
3459				continue;
3460			/*
3461			 *	Linux is short on memory. Fallback to
3462			 *	non-pipelined operation mode for this request.
3463			 */
3464			return idetape_queue_rw_tail (drive, IDETAPE_WRITE_RQ, blocks, tape->merge_stage->bh);
3465		}
3466	}
3467	rq = &new_stage->rq;
3468	ide_init_drive_cmd (rq);
3469	rq->cmd = IDETAPE_WRITE_RQ;
3470	rq->sector = tape->first_frame_position;	/* Doesn't actually matter - We always assume sequential access */
3471	rq->nr_sectors = rq->current_nr_sectors = blocks;
3472
3473	idetape_switch_buffers (tape, new_stage);
3474	idetape_init_stage(drive, new_stage, OS_FRAME_TYPE_DATA, tape->logical_blk_num);
3475	tape->logical_blk_num++;
3476	idetape_add_stage_tail (drive, new_stage);
3477	tape->pipeline_head++;
3478#if USE_IOTRACE
3479	IO_trace(IO_IDETAPE_FIFO, tape->pipeline_head, tape->buffer_head, tape->tape_head, tape->minor);
3480#endif
3481	calculate_speeds(drive);
3482
3483	/*
3484	 *	Estimate whether the tape has stopped writing by checking
3485	 *	if our write pipeline is currently empty. If we are not
3486	 *	writing anymore, wait for the pipeline to be full enough
3487	 *	(90%) before starting to service requests, so that we will
3488	 *	be able to keep up with the higher speeds of the tape.
3489	 *
3490	 *	For the OnStream drive, we can query the number of pending
3491	 *	frames in the drive's internal buffer. As long as the tape
3492	 *	is still writing, it is better to write frames immediately
3493	 *	rather than gather them in the pipeline. This will give the
3494	 *	tape's firmware the ability to sense the current incoming
3495	 *	data rate more accurately, and since the OnStream tape
3496	 *	supports variable speeds, it can try to adjust itself to the
3497	 *	incoming data rate.
3498	 */
3499	if (!idetape_pipeline_active(tape)) {
3500		if (tape->nr_stages >= tape->max_stages * 9 / 10 ||
3501		    tape->nr_stages >= tape->max_stages - tape->uncontrolled_pipeline_head_speed * 3 * 1024 / tape->tape_block_size) {
3502			tape->measure_insert_time = 1;
3503			tape->insert_time = jiffies;
3504			tape->insert_size = 0;
3505			tape->insert_speed = 0;
3506			idetape_insert_pipeline_into_queue (drive);
3507		} else if (tape->onstream) {
3508			idetape_update_stats(drive);
3509			if (tape->cur_frames > 5)
3510				idetape_insert_pipeline_into_queue (drive);
3511		}
3512	}
3513	if (test_and_clear_bit (IDETAPE_PIPELINE_ERROR, &tape->flags))		/* Return a deferred error */
3514		return -EIO;
3515	return blocks;
3516}
3517
3518/*
3519 *	idetape_wait_for_pipeline will wait until all pending pipeline
3520 *	requests are serviced. Typically called on device close.
3521 */
3522static void idetape_wait_for_pipeline (ide_drive_t *drive)
3523{
3524	idetape_tape_t *tape = drive->driver_data;
3525	unsigned long flags;
3526
3527	while (tape->next_stage || idetape_pipeline_active(tape)) {
3528		idetape_insert_pipeline_into_queue (drive);
3529		spin_lock_irqsave(&tape->spinlock, flags);
3530		if (idetape_pipeline_active(tape))
3531			idetape_wait_for_request(drive, tape->active_data_request);
3532		spin_unlock_irqrestore(&tape->spinlock, flags);
3533	}
3534}
3535
3536static void idetape_empty_write_pipeline (ide_drive_t *drive)
3537{
3538	idetape_tape_t *tape = drive->driver_data;
3539	int blocks, i, min;
3540	struct buffer_head *bh;
3541
3542#if IDETAPE_DEBUG_BUGS
3543	if (tape->chrdev_direction != idetape_direction_write) {
3544		printk (KERN_ERR "ide-tape: bug: Trying to empty write pipeline, but we are not writing.\n");
3545		return;
3546	}
3547	if (tape->merge_stage_size > tape->stage_size) {
3548		printk (KERN_ERR "ide-tape: bug: merge_buffer too big\n");
3549		tape->merge_stage_size = tape->stage_size;
3550	}
3551#endif /* IDETAPE_DEBUG_BUGS */
3552	if (tape->merge_stage_size) {
3553		blocks = tape->merge_stage_size / tape->tape_block_size;
3554		if (tape->merge_stage_size % tape->tape_block_size) {
3555			blocks++;
3556			i = tape->tape_block_size - tape->merge_stage_size % tape->tape_block_size;
3557			bh = tape->bh->b_reqnext;
3558			while (bh) {
3559				atomic_set(&bh->b_count, 0);
3560				bh = bh->b_reqnext;
3561			}
3562			bh = tape->bh;
3563			while (i) {
3564				if (bh == NULL) {
3565					printk(KERN_INFO "ide-tape: bug, bh NULL\n");
3566					break;
3567				}
3568				min = IDE_MIN(i, bh->b_size - atomic_read(&bh->b_count));
3569				memset(bh->b_data + atomic_read(&bh->b_count), 0, min);
3570				atomic_add(min, &bh->b_count);
3571				i -= min;
3572				bh = bh->b_reqnext;
3573			}
3574		}
3575		(void) idetape_add_chrdev_write_request (drive, blocks);
3576		tape->merge_stage_size = 0;
3577	}
3578	idetape_wait_for_pipeline (drive);
3579	if (tape->merge_stage != NULL) {
3580		__idetape_kfree_stage (tape->merge_stage);
3581		tape->merge_stage = NULL;
3582	}
3583	clear_bit (IDETAPE_PIPELINE_ERROR, &tape->flags);
3584	tape->chrdev_direction = idetape_direction_none;
3585
3586	/*
3587	 *	On the next backup, perform the feedback loop again.
3588	 *	(I don't want to keep sense information between backups,
3589	 *	 as some systems are constantly on, and the system load
3590	 *	 can be totally different on the next backup).
3591	 */
3592	tape->max_stages = tape->min_pipeline;
3593#if IDETAPE_DEBUG_BUGS
3594	if (tape->first_stage != NULL || tape->next_stage != NULL || tape->last_stage != NULL || tape->nr_stages != 0) {
3595		printk (KERN_ERR "ide-tape: ide-tape pipeline bug, "
3596		"first_stage %p, next_stage %p, last_stage %p, nr_stages %d\n",
3597		tape->first_stage, tape->next_stage, tape->last_stage, tape->nr_stages);
3598	}
3599#endif /* IDETAPE_DEBUG_BUGS */
3600}
3601
3602static void idetape_restart_speed_control (ide_drive_t *drive)
3603{
3604	idetape_tape_t *tape = drive->driver_data;
3605
3606	tape->restart_speed_control_req = 0;
3607	tape->pipeline_head = 0;
3608	tape->buffer_head = tape->tape_head = tape->cur_frames;
3609	tape->controlled_last_pipeline_head = tape->uncontrolled_last_pipeline_head = 0;
3610	tape->controlled_previous_pipeline_head = tape->uncontrolled_previous_pipeline_head = 0;
3611	tape->pipeline_head_speed = tape->controlled_pipeline_head_speed = 5000;
3612	tape->uncontrolled_pipeline_head_speed = 0;
3613	tape->controlled_pipeline_head_time = tape->uncontrolled_pipeline_head_time = jiffies;
3614	tape->controlled_previous_head_time = tape->uncontrolled_previous_head_time = jiffies;
3615}
3616
3617static int idetape_initiate_read (ide_drive_t *drive, int max_stages)
3618{
3619	idetape_tape_t *tape = drive->driver_data;
3620	idetape_stage_t *new_stage;
3621	struct request rq;
3622	int bytes_read;
3623	int blocks = tape->capabilities.ctl;
3624
3625	if (tape->chrdev_direction != idetape_direction_read) {		/* Initialize read operation */
3626		if (tape->chrdev_direction == idetape_direction_write) {
3627			idetape_empty_write_pipeline (drive);
3628			idetape_flush_tape_buffers (drive);
3629		}
3630#if IDETAPE_DEBUG_BUGS
3631		if (tape->merge_stage || tape->merge_stage_size) {
3632			printk (KERN_ERR "ide-tape: merge_stage_size should be 0 now\n");
3633			tape->merge_stage_size = 0;
3634		}
3635#endif /* IDETAPE_DEBUG_BUGS */
3636		if ((tape->merge_stage = __idetape_kmalloc_stage (tape, 0, 0)) == NULL)
3637			return -ENOMEM;
3638		tape->chrdev_direction = idetape_direction_read;
3639		tape->logical_blk_num = 0;
3640
3641		/*
3642		 *	Issue a read 0 command to ensure that DSC handshake
3643		 *	is switched from completion mode to buffer available
3644		 *	mode.
3645		 */
3646		bytes_read = idetape_queue_rw_tail (drive, IDETAPE_READ_RQ, 0, tape->merge_stage->bh);
3647		if (bytes_read < 0) {
3648			kfree (tape->merge_stage);
3649			tape->merge_stage = NULL;
3650			tape->chrdev_direction = idetape_direction_none;
3651			return bytes_read;
3652		}
3653	}
3654	if (tape->restart_speed_control_req)
3655		idetape_restart_speed_control(drive);
3656	ide_init_drive_cmd (&rq);
3657	rq.cmd = IDETAPE_READ_RQ;
3658	rq.sector = tape->first_frame_position;
3659	rq.nr_sectors = rq.current_nr_sectors = blocks;
3660	if (!test_bit(IDETAPE_PIPELINE_ERROR, &tape->flags) && tape->nr_stages <= max_stages) {
3661		new_stage = idetape_kmalloc_stage (tape);
3662		while (new_stage != NULL) {
3663			new_stage->rq = rq;
3664			idetape_add_stage_tail (drive, new_stage);
3665			if (tape->nr_stages >= max_stages)
3666				break;
3667			new_stage = idetape_kmalloc_stage (tape);
3668		}
3669	}
3670	if (!idetape_pipeline_active(tape)) {
3671		if (tape->nr_pending_stages >= 3 * max_stages / 4) {
3672			tape->measure_insert_time = 1;
3673			tape->insert_time = jiffies;
3674			tape->insert_size = 0;
3675			tape->insert_speed = 0;
3676			idetape_insert_pipeline_into_queue (drive);
3677		} else if (tape->onstream) {
3678			idetape_update_stats(drive);
3679			if (tape->cur_frames < tape->max_frames - 5)
3680				idetape_insert_pipeline_into_queue (drive);
3681		}
3682	}
3683	return 0;
3684}
3685
3686static int idetape_get_logical_blk (ide_drive_t *drive, int logical_blk_num, int max_stages, int quiet)
3687{
3688	idetape_tape_t *tape = drive->driver_data;
3689	unsigned long flags;
3690	int cnt = 0, x, position;
3691
3692	/*
3693	 * Search and wait for the next logical tape block
3694	 */
3695	while (1) {
3696		if (cnt++ > 1000) {   /* AJN: was 100 */
3697			printk(KERN_INFO "ide-tape: %s: couldn't find logical block %d, aborting\n", tape->name, logical_blk_num);
3698			return 0;
3699		}
3700		idetape_initiate_read(drive, max_stages);
3701		if (tape->first_stage == NULL) {
3702			if (tape->onstream) {
3703#if ONSTREAM_DEBUG
3704				if (tape->debug_level >= 1)
3705					printk(KERN_INFO "ide-tape: %s: first_stage == NULL, pipeline error %ld\n", tape->name, (long)test_bit(IDETAPE_PIPELINE_ERROR, &tape->flags));
3706#endif
3707				clear_bit(IDETAPE_PIPELINE_ERROR, &tape->flags);
3708				position = idetape_read_position(drive);
3709				printk(KERN_INFO "ide-tape: %s: blank block detected at %d\n", tape->name, position);
3710				if (position >= 3000 && position < 3080)
3711					position += 32;  /* Why is this check and number ??? MM */
3712				if (position >= OS_DATA_ENDFRAME1 && position < 3000)
3713					position = 3000;
3714				else
3715					/*
3716					 * compensate for write errors that generally skip 80 frames,
3717					 * expect around 20 read errors in a row...
3718					 */
3719					position += 60;
3720				if (position >= OS_DATA_ENDFRAME1 && position < 3000)
3721					position = 3000;
3722				printk(KERN_INFO "ide-tape: %s: positioning tape to block %d\n", tape->name, position);
3723				if (position == 3000)  /* seems to be needed to correctly position at block 3000 MM */
3724					idetape_position_tape(drive, 0, 0, 0);
3725				idetape_position_tape(drive, position, 0, 0);
3726				cnt += 40;
3727				continue;
3728			} else
3729				return 0;
3730		}
3731		idetape_wait_first_stage(drive);
3732		if (idetape_verify_stage(drive, tape->first_stage, logical_blk_num, quiet))
3733			break;
3734		if (tape->first_stage->rq.errors == IDETAPE_ERROR_EOD)
3735			cnt--;
3736		if (idetape_verify_stage(drive, tape->first_stage, -1, quiet)) {
3737			x = ntohl(tape->first_stage->aux->logical_blk_num);
3738			if (x > logical_blk_num) {
3739				printk(KERN_ERR "ide-tape: %s: couldn't find logical block %d, aborting (block %d found)\n", tape->name, logical_blk_num, x);
3740				return 0;
3741			}
3742		}
3743		spin_lock_irqsave(&tape->spinlock, flags);
3744		idetape_remove_stage_head(drive);
3745		spin_unlock_irqrestore(&tape->spinlock, flags);
3746	}
3747	if (tape->onstream)
3748		tape->logical_blk_num = ntohl(tape->first_stage->aux->logical_blk_num);
3749	return 1;
3750}
3751
3752/*
3753 *	idetape_add_chrdev_read_request is called from idetape_chrdev_read
3754 *	to service a character device read request and add read-ahead
3755 *	requests to our pipeline.
3756 */
3757static int idetape_add_chrdev_read_request (ide_drive_t *drive,int blocks)
3758{
3759	idetape_tape_t *tape = drive->driver_data;
3760	unsigned long flags;
3761	struct request *rq_ptr;
3762	int bytes_read;
3763
3764#if IDETAPE_DEBUG_LOG
3765	if (tape->debug_level >= 4)
3766		printk (KERN_INFO "ide-tape: Reached idetape_add_chrdev_read_request, %d blocks\n", blocks);
3767#endif /* IDETAPE_DEBUG_LOG */
3768
3769	/*
3770	 * Wait for the next logical block to be available at the head
3771	 * of the pipeline
3772	 */
3773	if (!idetape_get_logical_blk(drive, tape->logical_blk_num, tape->max_stages, 0)) {
3774		if (tape->onstream) {
3775			set_bit(IDETAPE_READ_ERROR, &tape->flags);
3776			return 0;
3777		}
3778		if (test_bit(IDETAPE_PIPELINE_ERROR, &tape->flags))
3779		 	return 0;
3780		return idetape_queue_rw_tail (drive, IDETAPE_READ_RQ, blocks, tape->merge_stage->bh);
3781	}
3782	rq_ptr = &tape->first_stage->rq;
3783	bytes_read = tape->tape_block_size * (rq_ptr->nr_sectors - rq_ptr->current_nr_sectors);
3784	rq_ptr->nr_sectors = rq_ptr->current_nr_sectors = 0;
3785
3786
3787	if (tape->onstream && !tape->raw && tape->first_stage->aux->frame_type == OS_FRAME_TYPE_EOD) {
3788#if ONSTREAM_DEBUG
3789		if (tape->debug_level >= 2)
3790			printk(KERN_INFO "ide-tape: %s: EOD reached\n", tape->name);
3791#endif
3792		return 0;
3793	}
3794	if (rq_ptr->errors == IDETAPE_ERROR_EOD)
3795		return 0;
3796	if (rq_ptr->errors == IDETAPE_ERROR_FILEMARK) {
3797		idetape_switch_buffers (tape, tape->first_stage);
3798		set_bit (IDETAPE_FILEMARK, &tape->flags);
3799#if USE_IOTRACE
3800		IO_trace(IO_IDETAPE_FIFO, tape->pipeline_head, tape->buffer_head, tape->tape_head, tape->minor);
3801#endif
3802		calculate_speeds(drive);
3803	} else {
3804		idetape_switch_buffers (tape, tape->first_stage);
3805		if (rq_ptr->errors == IDETAPE_ERROR_GENERAL) {
3806#if ONSTREAM_DEBUG
3807			if (tape->debug_level >= 1)
3808				printk(KERN_INFO "ide-tape: error detected, bytes_read %d\n", bytes_read);
3809#endif
3810		}
3811		clear_bit (IDETAPE_FILEMARK, &tape->flags);
3812		spin_lock_irqsave(&tape->spinlock, flags);
3813		idetape_remove_stage_head (drive);
3814		spin_unlock_irqrestore(&tape->spinlock, flags);
3815		tape->logical_blk_num++;
3816		tape->pipeline_head++;
3817#if USE_IOTRACE
3818		IO_trace(IO_IDETAPE_FIFO, tape->pipeline_head, tape->buffer_head, tape->tape_head, tape->minor);
3819#endif
3820		calculate_speeds(drive);
3821	}
3822#if IDETAPE_DEBUG_BUGS
3823	if (bytes_read > blocks*tape->tape_block_size) {
3824		printk (KERN_ERR "ide-tape: bug: trying to return more bytes than requested\n");
3825		bytes_read=blocks*tape->tape_block_size;
3826	}
3827#endif /* IDETAPE_DEBUG_BUGS */
3828	return (bytes_read);
3829}
3830
3831static void idetape_pad_zeros (ide_drive_t *drive, int bcount)
3832{
3833	idetape_tape_t *tape = drive->driver_data;
3834	struct buffer_head *bh;
3835	int count, blocks;
3836
3837	while (bcount) {
3838		bh = tape->merge_stage->bh;
3839		count = IDE_MIN (tape->stage_size, bcount);
3840		bcount -= count;
3841		blocks = count / tape->tape_block_size;
3842		while (count) {
3843			atomic_set(&bh->b_count, IDE_MIN (count, bh->b_size));
3844			memset (bh->b_data, 0, atomic_read(&bh->b_count));
3845			count -= atomic_read(&bh->b_count);
3846			bh = bh->b_reqnext;
3847		}
3848		idetape_queue_rw_tail (drive, IDETAPE_WRITE_RQ, blocks, tape->merge_stage->bh);
3849	}
3850}
3851
3852static int idetape_pipeline_size (ide_drive_t *drive)
3853{
3854	idetape_tape_t *tape = drive->driver_data;
3855	idetape_stage_t *stage;
3856	struct request *rq;
3857	int size = 0;
3858
3859	idetape_wait_for_pipeline (drive);
3860	stage = tape->first_stage;
3861	while (stage != NULL) {
3862		rq = &stage->rq;
3863		size += tape->tape_block_size * (rq->nr_sectors-rq->current_nr_sectors);
3864		if (rq->errors == IDETAPE_ERROR_FILEMARK)
3865			size += tape->tape_block_size;
3866		stage = stage->next;
3867	}
3868	size += tape->merge_stage_size;
3869	return size;
3870}
3871
3872/*
3873 *	Rewinds the tape to the Beginning Of the current Partition (BOP).
3874 *
3875 *	We currently support only one partition.
3876 */
3877static int idetape_rewind_tape (ide_drive_t *drive)
3878{
3879	int retval;
3880	idetape_pc_t pc;
3881	idetape_tape_t *tape = drive->driver_data;
3882#if IDETAPE_DEBUG_LOG
3883	if (tape->debug_level >= 2)
3884		printk (KERN_INFO "ide-tape: Reached idetape_rewind_tape\n");
3885#endif /* IDETAPE_DEBUG_LOG */
3886
3887	idetape_create_rewind_cmd (drive, &pc);
3888	retval = idetape_queue_pc_tail (drive, &pc);
3889	if (retval)
3890		return retval;
3891
3892	idetape_create_read_position_cmd (&pc);
3893	retval = idetape_queue_pc_tail (drive, &pc);
3894	if (retval)
3895		return retval;
3896	tape->logical_blk_num = 0;
3897	return 0;
3898}
3899
3900/*
3901 *	Our special ide-tape ioctl's.
3902 *
3903 *	Currently there aren't any ioctl's.
3904 *	mtio.h compatible commands should be issued to the character device
3905 *	interface.
3906 */
3907static int idetape_blkdev_ioctl (ide_drive_t *drive, struct inode *inode, struct file *file,
3908				 unsigned int cmd, unsigned long arg)
3909{
3910	idetape_tape_t *tape = drive->driver_data;
3911	idetape_config_t config;
3912
3913#if IDETAPE_DEBUG_LOG
3914	if (tape->debug_level >= 4)
3915		printk (KERN_INFO "ide-tape: Reached idetape_blkdev_ioctl\n");
3916#endif /* IDETAPE_DEBUG_LOG */
3917	switch (cmd) {
3918		case 0x0340:
3919			if (copy_from_user ((char *) &config, (char *) arg, sizeof (idetape_config_t)))
3920				return -EFAULT;
3921			tape->best_dsc_rw_frequency = config.dsc_rw_frequency;
3922			tape->max_stages = config.nr_stages;
3923			break;
3924		case 0x0350:
3925			config.dsc_rw_frequency = (int) tape->best_dsc_rw_frequency;
3926			config.nr_stages = tape->max_stages;
3927			if (copy_to_user ((char *) arg, (char *) &config, sizeof (idetape_config_t)))
3928				return -EFAULT;
3929			break;
3930		default:
3931			return -EIO;
3932	}
3933	return 0;
3934}
3935
3936/*
3937 *	The block device interface should not be used for data transfers.
3938 *	However, we still allow opening it so that we can issue general
3939 *	ide driver configuration ioctl's, such as the interrupt unmask feature.
3940 */
3941static int idetape_blkdev_open (struct inode *inode, struct file *filp, ide_drive_t *drive)
3942{
3943	MOD_INC_USE_COUNT;
3944#if ONSTREAM_DEBUG
3945        printk(KERN_INFO "ide-tape: MOD_INC_USE_COUNT in idetape_blkdev_open\n");
3946#endif
3947	return 0;
3948}
3949
3950static void idetape_blkdev_release (struct inode *inode, struct file *filp, ide_drive_t *drive)
3951{
3952	MOD_DEC_USE_COUNT;
3953#if ONSTREAM_DEBUG
3954        printk(KERN_INFO "ide-tape: MOD_DEC_USE_COUNT in idetape_blkdev_release\n");
3955#endif
3956}
3957
3958/*
3959 *	idetape_pre_reset is called before an ATAPI/ATA software reset.
3960 */
3961static void idetape_pre_reset (ide_drive_t *drive)
3962{
3963	idetape_tape_t *tape = drive->driver_data;
3964	if (tape != NULL)
3965		set_bit (IDETAPE_IGNORE_DSC, &tape->flags);
3966}
3967
3968/*
3969 *	Character device interface functions
3970 */
3971static ide_drive_t *get_drive_ptr (kdev_t i_rdev)
3972{
3973	unsigned int i = MINOR(i_rdev) & ~0xc0;
3974
3975	if (i >= MAX_HWIFS * MAX_DRIVES)
3976		return NULL;
3977	return (idetape_chrdevs[i].drive);
3978}
3979
3980static int idetape_onstream_space_over_filemarks_backward (ide_drive_t *drive,short mt_op,int mt_count)
3981{
3982	idetape_tape_t *tape = drive->driver_data;
3983	int cnt = 0;
3984	int last_mark_addr;
3985	unsigned long flags;
3986
3987	if (!idetape_get_logical_blk(drive, -1, 10, 0)) {
3988		printk(KERN_INFO "ide-tape: %s: couldn't get logical blk num in space_filemarks_bwd\n", tape->name);
3989		return -EIO;
3990	}
3991	while (cnt != mt_count) {
3992		last_mark_addr = ntohl(tape->first_stage->aux->last_mark_addr);
3993		if (last_mark_addr == -1)
3994			return -EIO;
3995#if ONSTREAM_DEBUG
3996		if (tape->debug_level >= 2)
3997			printk(KERN_INFO "ide-tape: positioning to last mark at %d\n", last_mark_addr);
3998#endif
3999		idetape_position_tape(drive, last_mark_addr, 0, 0);
4000		cnt++;
4001		if (!idetape_get_logical_blk(drive, -1, 10, 0)) {
4002			printk(KERN_INFO "ide-tape: %s: couldn't get logical blk num in space_filemarks\n", tape->name);
4003			return -EIO;
4004		}
4005		if (tape->first_stage->aux->frame_type != OS_FRAME_TYPE_MARKER) {
4006			printk(KERN_INFO "ide-tape: %s: expected to find marker at block %d, not found\n", tape->name, last_mark_addr);
4007			return -EIO;
4008		}
4009	}
4010	if (mt_op == MTBSFM) {
4011		spin_lock_irqsave(&tape->spinlock, flags);
4012		idetape_remove_stage_head (drive);
4013		tape->logical_blk_num++;
4014		spin_unlock_irqrestore(&tape->spinlock, flags);
4015	}
4016	return 0;
4017}
4018
4019/*
4020 * ADRL 1.1 compatible "slow" space filemarks fwd version
4021 *
4022 * Just scans for the filemark sequentially.
4023 */
4024static int idetape_onstream_space_over_filemarks_forward_slow (ide_drive_t *drive,short mt_op,int mt_count)
4025{
4026	idetape_tape_t *tape = drive->driver_data;
4027	int cnt = 0;
4028	unsigned long flags;
4029
4030	if (!idetape_get_logical_blk(drive, -1, 10, 0)) {
4031		printk(KERN_INFO "ide-tape: %s: couldn't get logical blk num in space_filemarks_fwd\n", tape->name);
4032		return -EIO;
4033	}
4034	while (1) {
4035		if (!idetape_get_logical_blk(drive, -1, 10, 0)) {
4036			printk(KERN_INFO "ide-tape: %s: couldn't get logical blk num in space_filemarks\n", tape->name);
4037			return -EIO;
4038		}
4039		if (tape->first_stage->aux->frame_type == OS_FRAME_TYPE_MARKER)
4040			cnt++;
4041		if (tape->first_stage->aux->frame_type == OS_FRAME_TYPE_EOD) {
4042#if ONSTREAM_DEBUG
4043			if (tape->debug_level >= 2)
4044				printk(KERN_INFO "ide-tape: %s: space_fwd: EOD reached\n", tape->name);
4045#endif
4046			return -EIO;
4047		}
4048		if (cnt == mt_count)
4049			break;
4050		spin_lock_irqsave(&tape->spinlock, flags);
4051		idetape_remove_stage_head (drive);
4052		spin_unlock_irqrestore(&tape->spinlock, flags);
4053	}
4054	if (mt_op == MTFSF) {
4055		spin_lock_irqsave(&tape->spinlock, flags);
4056		idetape_remove_stage_head (drive);
4057		tape->logical_blk_num++;
4058		spin_unlock_irqrestore(&tape->spinlock, flags);
4059	}
4060	return 0;
4061}
4062
4063
4064/*
4065 * Fast linux specific version of OnStream FSF
4066 */
4067static int idetape_onstream_space_over_filemarks_forward_fast (ide_drive_t *drive,short mt_op,int mt_count)
4068{
4069	idetape_tape_t *tape = drive->driver_data;
4070	int cnt = 0, next_mark_addr;
4071	unsigned long flags;
4072
4073	if (!idetape_get_logical_blk(drive, -1, 10, 0)) {
4074		printk(KERN_INFO "ide-tape: %s: couldn't get logical blk num in space_filemarks_fwd\n", tape->name);
4075		return -EIO;
4076	}
4077
4078	/*
4079	 * Find nearest (usually previous) marker
4080	 */
4081	while (1) {
4082		if (tape->first_stage->aux->frame_type == OS_FRAME_TYPE_MARKER)
4083			break;
4084		if (tape->first_stage->aux->frame_type == OS_FRAME_TYPE_EOD) {
4085#if ONSTREAM_DEBUG
4086			if (tape->debug_level >= 2)
4087				printk(KERN_INFO "ide-tape: %s: space_fwd: EOD reached\n", tape->name);
4088#endif
4089			return -EIO;
4090		}
4091		if (ntohl(tape->first_stage->aux->filemark_cnt) == 0) {
4092			if (tape->first_mark_addr == -1) {
4093				printk(KERN_INFO "ide-tape: %s: reverting to slow filemark space\n", tape->name);
4094				return idetape_onstream_space_over_filemarks_forward_slow(drive, mt_op, mt_count);
4095			}
4096			idetape_position_tape(drive, tape->first_mark_addr, 0, 0);
4097			if (!idetape_get_logical_blk(drive, -1, 10, 0)) {
4098				printk(KERN_INFO "ide-tape: %s: couldn't get logical blk num in space_filemarks_fwd_fast\n", tape->name);
4099				return -EIO;
4100			}
4101			if (tape->first_stage->aux->frame_type != OS_FRAME_TYPE_MARKER) {
4102				printk(KERN_INFO "ide-tape: %s: expected to find filemark at %d\n", tape->name, tape->first_mark_addr);
4103				return -EIO;
4104			}
4105		} else {
4106			if (idetape_onstream_space_over_filemarks_backward(drive, MTBSF, 1) < 0)
4107				return -EIO;
4108			mt_count++;
4109		}
4110	}
4111	cnt++;
4112	while (cnt != mt_count) {
4113		next_mark_addr = ntohl(tape->first_stage->aux->next_mark_addr);
4114		if (!next_mark_addr || next_mark_addr > tape->eod_frame_addr) {
4115			printk(KERN_INFO "ide-tape: %s: reverting to slow filemark space\n", tape->name);
4116			return idetape_onstream_space_over_filemarks_forward_slow(drive, mt_op, mt_count - cnt);
4117#if ONSTREAM_DEBUG
4118		} else if (tape->debug_level >= 2) {
4119		     printk(KERN_INFO "ide-tape: positioning to next mark at %d\n", next_mark_addr);
4120#endif
4121		}
4122		idetape_position_tape(drive, next_mark_addr, 0, 0);
4123		cnt++;
4124		if (!idetape_get_logical_blk(drive, -1, 10, 0)) {
4125			printk(KERN_INFO "ide-tape: %s: couldn't get logical blk num in space_filemarks\n", tape->name);
4126			return -EIO;
4127		}
4128		if (tape->first_stage->aux->frame_type != OS_FRAME_TYPE_MARKER) {
4129			printk(KERN_INFO "ide-tape: %s: expected to find marker at block %d, not found\n", tape->name, next_mark_addr);
4130			return -EIO;
4131		}
4132	}
4133	if (mt_op == MTFSF) {
4134		spin_lock_irqsave(&tape->spinlock, flags);
4135		idetape_remove_stage_head (drive);
4136		tape->logical_blk_num++;
4137		spin_unlock_irqrestore(&tape->spinlock, flags);
4138	}
4139	return 0;
4140}
4141
4142/*
4143 *	idetape_space_over_filemarks is now a bit more complicated than just
4144 *	passing the command to the tape since we may have crossed some
4145 *	filemarks during our pipelined read-ahead mode.
4146 *
4147 *	As a minor side effect, the pipeline enables us to support MTFSFM when
4148 *	the filemark is in our internal pipeline even if the tape doesn't
4149 *	support spacing over filemarks in the reverse direction.
4150 */
4151static int idetape_space_over_filemarks (ide_drive_t *drive,short mt_op,int mt_count)
4152{
4153	idetape_tape_t *tape = drive->driver_data;
4154	idetape_pc_t pc;
4155	unsigned long flags;
4156	int retval,count=0;
4157	int speed_control;
4158
4159	if (tape->onstream) {
4160		if (tape->raw)
4161			return -EIO;
4162		speed_control = tape->speed_control;
4163		tape->speed_control = 0;
4164		if (mt_op == MTFSF || mt_op == MTFSFM) {
4165			if (tape->linux_media)
4166				retval = idetape_onstream_space_over_filemarks_forward_fast(drive, mt_op, mt_count);
4167			else
4168				retval = idetape_onstream_space_over_filemarks_forward_slow(drive, mt_op, mt_count);
4169		} else
4170			retval = idetape_onstream_space_over_filemarks_backward(drive, mt_op, mt_count);
4171		tape->speed_control = speed_control;
4172		tape->restart_speed_control_req = 1;
4173		return retval;
4174	}
4175
4176	if (tape->chrdev_direction == idetape_direction_read) {
4177		/*
4178		 *	We have a read-ahead buffer. Scan it for crossed
4179		 *	filemarks.
4180		 */
4181		tape->merge_stage_size = 0;
4182		clear_bit (IDETAPE_FILEMARK, &tape->flags);
4183		while (tape->first_stage != NULL) {
4184			idetape_wait_first_stage(drive);
4185			if (tape->first_stage->rq.errors == IDETAPE_ERROR_FILEMARK)
4186				count++;
4187			if (count == mt_count) {
4188				switch (mt_op) {
4189					case MTFSF:
4190						spin_lock_irqsave(&tape->spinlock, flags);
4191						idetape_remove_stage_head (drive);
4192						spin_unlock_irqrestore(&tape->spinlock, flags);
4193					case MTFSFM:
4194						return (0);
4195					default:
4196						break;
4197				}
4198			}
4199			spin_lock_irqsave(&tape->spinlock, flags);
4200			idetape_remove_stage_head (drive);
4201			spin_unlock_irqrestore(&tape->spinlock, flags);
4202		}
4203		idetape_discard_read_pipeline (drive, 1);
4204	}
4205
4206	/*
4207	 *	The filemark was not found in our internal pipeline.
4208	 *	Now we can issue the space command.
4209	 */
4210	switch (mt_op) {
4211		case MTFSF:
4212			idetape_create_space_cmd (&pc,mt_count-count,IDETAPE_SPACE_OVER_FILEMARK);
4213			return (idetape_queue_pc_tail (drive, &pc));
4214		case MTFSFM:
4215			if (!tape->capabilities.sprev)
4216				return (-EIO);
4217			retval = idetape_space_over_filemarks (drive, MTFSF, mt_count-count);
4218			if (retval) return (retval);
4219			return (idetape_space_over_filemarks (drive, MTBSF, 1));
4220		case MTBSF:
4221			if (!tape->capabilities.sprev)
4222				return (-EIO);
4223			idetape_create_space_cmd (&pc,-(mt_count+count),IDETAPE_SPACE_OVER_FILEMARK);
4224			return (idetape_queue_pc_tail (drive, &pc));
4225		case MTBSFM:
4226			if (!tape->capabilities.sprev)
4227				return (-EIO);
4228			retval = idetape_space_over_filemarks (drive, MTBSF, mt_count+count);
4229			if (retval) return (retval);
4230			return (idetape_space_over_filemarks (drive, MTFSF, 1));
4231		default:
4232			printk (KERN_ERR "ide-tape: MTIO operation %d not supported\n",mt_op);
4233			return (-EIO);
4234	}
4235}
4236
4237
4238/*
4239 *	Our character device read / write functions.
4240 *
4241 *	The tape is optimized to maximize throughput when it is transferring
4242 *	an integral number of the "continuous transfer limit", which is
4243 *	a parameter of the specific tape (26 KB on my particular tape).
4244 *      (32 kB for Onstream)
4245 *
4246 *	As of version 1.3 of the driver, the character device provides an
4247 *	abstract continuous view of the media - any mix of block sizes (even 1
4248 *	byte) on the same backup/restore procedure is supported. The driver
4249 *	will internally convert the requests to the recommended transfer unit,
4250 *	so that an unmatch between the user's block size to the recommended
4251 *	size will only result in a (slightly) increased driver overhead, but
4252 *	will no longer hit performance.
4253 *      This is not applicable to Onstream.
4254 */
4255static ssize_t idetape_chrdev_read (struct file *file, char *buf,
4256				    size_t count, loff_t *ppos)
4257{
4258	struct inode *inode = file->f_dentry->d_inode;
4259	ide_drive_t *drive = get_drive_ptr (inode->i_rdev);
4260	idetape_tape_t *tape = drive->driver_data;
4261	ssize_t bytes_read,temp, actually_read = 0, rc;
4262
4263	if (ppos != &file->f_pos) {
4264		/* "A request was outside the capabilities of the device." */
4265		return -ENXIO;
4266	}
4267	if (tape->onstream && (count != tape->tape_block_size)) {
4268		printk(KERN_ERR "ide-tape: %s: use %d bytes as block size (%Zd used)\n", tape->name, tape->tape_block_size, count);
4269		return -EINVAL;
4270	}
4271#if IDETAPE_DEBUG_LOG
4272	if (tape->debug_level >= 3)
4273		printk (KERN_INFO "ide-tape: Reached idetape_chrdev_read, count %Zd\n", count);
4274#endif /* IDETAPE_DEBUG_LOG */
4275
4276	if (tape->chrdev_direction != idetape_direction_read) {
4277		if (test_bit (IDETAPE_DETECT_BS, &tape->flags))
4278			if (count > tape->tape_block_size && (count % tape->tape_block_size) == 0)
4279				tape->user_bs_factor = count / tape->tape_block_size;
4280	}
4281	if ((rc = idetape_initiate_read(drive, tape->max_stages)) < 0)
4282		return rc;
4283	if (count == 0)
4284		return (0);
4285	if (tape->merge_stage_size) {
4286		actually_read = IDE_MIN (tape->merge_stage_size, count);
4287		idetape_copy_stage_to_user (tape, buf, tape->merge_stage, actually_read);
4288		buf += actually_read;
4289		tape->merge_stage_size -= actually_read;
4290		count -= actually_read;
4291	}
4292	while (count >= tape->stage_size) {
4293		bytes_read = idetape_add_chrdev_read_request (drive, tape->capabilities.ctl);
4294		if (bytes_read <= 0)
4295			goto finish;
4296		idetape_copy_stage_to_user (tape, buf, tape->merge_stage, bytes_read);
4297		buf += bytes_read;
4298		count -= bytes_read;
4299		actually_read += bytes_read;
4300	}
4301	if (count) {
4302		bytes_read=idetape_add_chrdev_read_request (drive, tape->capabilities.ctl);
4303		if (bytes_read <= 0)
4304			goto finish;
4305		temp = IDE_MIN (count, bytes_read);
4306		idetape_copy_stage_to_user (tape, buf, tape->merge_stage, temp);
4307		actually_read += temp;
4308		tape->merge_stage_size = bytes_read-temp;
4309	}
4310finish:
4311	if (!actually_read && test_bit (IDETAPE_FILEMARK, &tape->flags)) {
4312#if IDETAPE_DEBUG_LOG
4313		if (tape->debug_level >= 2)
4314			printk(KERN_INFO "ide-tape: %s: spacing over filemark\n", tape->name);
4315#endif
4316		idetape_space_over_filemarks (drive, MTFSF, 1);
4317		return 0;
4318	}
4319	if (tape->onstream && !actually_read && test_and_clear_bit(IDETAPE_READ_ERROR, &tape->flags)) {
4320		printk(KERN_ERR "ide-tape: %s: unrecovered read error on logical block number %d, skipping\n",
4321					tape->name, tape->logical_blk_num);
4322		tape->logical_blk_num++;
4323		return -EIO;
4324	}
4325	return actually_read;
4326}
4327
4328static void idetape_update_last_marker (ide_drive_t *drive, int last_mark_addr, int next_mark_addr)
4329{
4330	idetape_tape_t *tape = drive->driver_data;
4331	idetape_stage_t *stage;
4332	os_aux_t *aux;
4333	int position;
4334
4335	if (!tape->onstream || tape->raw)
4336		return;
4337	if (last_mark_addr == -1)
4338		return;
4339	stage = __idetape_kmalloc_stage(tape, 0, 0);
4340	if (stage == NULL)
4341		return;
4342	idetape_flush_tape_buffers(drive);
4343	position = idetape_read_position(drive);
4344#if ONSTREAM_DEBUG
4345	if (tape->debug_level >= 2)
4346		printk(KERN_INFO "ide-tape: current position (2) %d, lblk %d\n", position, tape->logical_blk_num);
4347	if (tape->debug_level >= 2)
4348		printk(KERN_INFO "ide-tape: current position (2) tape block %d\n", tape->last_frame_position);
4349#endif
4350	idetape_position_tape(drive, last_mark_addr, 0, 0);
4351	if (!idetape_queue_rw_tail (drive, IDETAPE_READ_RQ, 1, stage->bh)) {
4352		printk(KERN_INFO "ide-tape: %s: couldn't read last marker\n", tape->name);
4353		__idetape_kfree_stage (stage);
4354		idetape_position_tape(drive, position, 0, 0);
4355		return;
4356	}
4357	aux = stage->aux;
4358	if (aux->frame_type != OS_FRAME_TYPE_MARKER) {
4359		printk(KERN_INFO "ide-tape: %s: expected to find marker at addr %d\n", tape->name, last_mark_addr);
4360		__idetape_kfree_stage (stage);
4361		idetape_position_tape(drive, position, 0, 0);
4362		return;
4363	}
4364#if ONSTREAM_DEBUG
4365	if (tape->debug_level >= 2)
4366		printk(KERN_INFO "ide-tape: writing back marker\n");
4367#endif
4368	aux->next_mark_addr = htonl(next_mark_addr);
4369	idetape_position_tape(drive, last_mark_addr, 0, 0);
4370	if (!idetape_queue_rw_tail (drive, IDETAPE_WRITE_RQ, 1, stage->bh)) {
4371		printk(KERN_INFO "ide-tape: %s: couldn't write back marker frame at %d\n", tape->name, last_mark_addr);
4372		__idetape_kfree_stage (stage);
4373		idetape_position_tape(drive, position, 0, 0);
4374		return;
4375	}
4376	__idetape_kfree_stage (stage);
4377	idetape_flush_tape_buffers (drive);
4378	idetape_position_tape(drive, position, 0, 0);
4379	return;
4380}
4381
4382static void idetape_write_filler (ide_drive_t *drive, int block, int cnt)
4383{
4384	idetape_tape_t *tape = drive->driver_data;
4385	idetape_stage_t *stage;
4386	int rc;
4387
4388	if (!tape->onstream || tape->raw)
4389		return;
4390	stage = __idetape_kmalloc_stage(tape, 1, 1);
4391	if (stage == NULL)
4392		return;
4393	idetape_init_stage(drive, stage, OS_FRAME_TYPE_FILL, 0);
4394	idetape_wait_ready(drive, 60 * 5 * HZ);
4395	rc = idetape_position_tape(drive, block, 0, 0);
4396#if ONSTREAM_DEBUG
4397	printk(KERN_INFO "write_filler: positioning failed it returned %d\n", rc);
4398#endif
4399	if (rc != 0)
4400		return;	/* don't write fillers if we cannot position the tape. */
4401
4402	strcpy(stage->bh->b_data, "Filler");
4403	while (cnt--) {
4404		if (!idetape_queue_rw_tail (drive, IDETAPE_WRITE_RQ, 1, stage->bh)) {
4405			printk(KERN_INFO "ide-tape: %s: write_filler: couldn't write header frame\n", tape->name);
4406			__idetape_kfree_stage (stage);
4407			return;
4408		}
4409	}
4410	__idetape_kfree_stage (stage);
4411}
4412
4413static void __idetape_write_header (ide_drive_t *drive, int block, int cnt)
4414{
4415	idetape_tape_t *tape = drive->driver_data;
4416	idetape_stage_t *stage;
4417	os_header_t header;
4418
4419	stage = __idetape_kmalloc_stage(tape, 1, 1);
4420	if (stage == NULL)
4421		return;
4422	idetape_init_stage(drive, stage, OS_FRAME_TYPE_HEADER, tape->logical_blk_num);
4423	idetape_wait_ready(drive, 60 * 5 * HZ);
4424	idetape_position_tape(drive, block, 0, 0);
4425	memset(&header, 0, sizeof(header));
4426	strcpy(header.ident_str, "ADR_SEQ");
4427	header.major_rev = 1;
4428	header.minor_rev = OS_ADR_MINREV;
4429	header.par_num = 1;
4430	header.partition.partition_num = OS_DATA_PARTITION;
4431	header.partition.par_desc_ver = OS_PARTITION_VERSION;
4432	header.partition.first_frame_addr = htonl(OS_DATA_STARTFRAME1);
4433	header.partition.last_frame_addr = htonl(tape->capacity);
4434	header.partition.wrt_pass_cntr = htons(tape->wrt_pass_cntr);
4435	header.partition.eod_frame_addr = htonl(tape->eod_frame_addr);
4436	memcpy(stage->bh->b_data, &header, sizeof(header));
4437	while (cnt--) {
4438		if (!idetape_queue_rw_tail (drive, IDETAPE_WRITE_RQ, 1, stage->bh)) {
4439			printk(KERN_INFO "ide-tape: %s: couldn't write header frame\n", tape->name);
4440			__idetape_kfree_stage (stage);
4441			return;
4442		}
4443	}
4444	__idetape_kfree_stage (stage);
4445	idetape_flush_tape_buffers (drive);
4446}
4447
4448static void idetape_write_header (ide_drive_t *drive, int locate_eod)
4449{
4450	idetape_tape_t *tape = drive->driver_data;
4451
4452#if ONSTREAM_DEBUG
4453	if (tape->debug_level >= 2)
4454		printk(KERN_INFO "ide-tape: %s: writing tape header\n", tape->name);
4455#endif
4456	if (!tape->onstream || tape->raw)
4457		return;
4458	tape->update_frame_cntr++;
4459	__idetape_write_header(drive, 5, 5);
4460	__idetape_write_header(drive, 0xbae, 5); /* 2990 */
4461	if (locate_eod) {
4462#if ONSTREAM_DEBUG
4463		if (tape->debug_level >= 2)
4464			printk(KERN_INFO "ide-tape: %s: locating back to eod frame addr %d\n", tape->name, tape->eod_frame_addr);
4465#endif
4466		idetape_position_tape(drive, tape->eod_frame_addr, 0, 0);
4467	}
4468}
4469
4470static ssize_t idetape_chrdev_write (struct file *file, const char *buf,
4471				     size_t count, loff_t *ppos)
4472{
4473	struct inode *inode = file->f_dentry->d_inode;
4474	ide_drive_t *drive = get_drive_ptr (inode->i_rdev);
4475	idetape_tape_t *tape = drive->driver_data;
4476	ssize_t retval, actually_written = 0;
4477	int position;
4478
4479	if (ppos != &file->f_pos) {
4480		/* "A request was outside the capabilities of the device." */
4481		return -ENXIO;
4482	}
4483
4484#if IDETAPE_DEBUG_LOG
4485	if (tape->debug_level >= 3)
4486		printk (KERN_INFO "ide-tape: Reached idetape_chrdev_write, count %Zd\n", count);
4487#endif /* IDETAPE_DEBUG_LOG */
4488
4489	if (tape->onstream) {
4490		if (count != tape->tape_block_size) {
4491			printk(KERN_ERR "ide-tape: %s: chrdev_write: use %d bytes as block size (%Zd used)\n",
4492					tape->name, tape->tape_block_size, count);
4493			return -EINVAL;
4494		}
4495		/*
4496		 * Check if we reach the end of the tape. Just assume the whole pipeline
4497		 * is filled with write requests!
4498		 */
4499		if (tape->first_frame_position + tape->nr_stages >= tape->capacity - OS_EW)  {
4500#if ONSTREAM_DEBUG
4501			printk(KERN_INFO, "chrdev_write: Write truncated at EOM early warning");
4502#endif
4503			if (tape->chrdev_direction == idetape_direction_write)
4504				idetape_write_release(inode);
4505			return -ENOSPC;
4506		}
4507	}
4508
4509	if (tape->chrdev_direction != idetape_direction_write) {	/* Initialize write operation */
4510		if (tape->chrdev_direction == idetape_direction_read)
4511			idetape_discard_read_pipeline (drive, 1);
4512#if IDETAPE_DEBUG_BUGS
4513		if (tape->merge_stage || tape->merge_stage_size) {
4514			printk (KERN_ERR "ide-tape: merge_stage_size should be 0 now\n");
4515			tape->merge_stage_size = 0;
4516		}
4517#endif /* IDETAPE_DEBUG_BUGS */
4518		if ((tape->merge_stage = __idetape_kmalloc_stage (tape, 0, 0)) == NULL)
4519			return -ENOMEM;
4520		tape->chrdev_direction = idetape_direction_write;
4521		idetape_init_merge_stage (tape);
4522
4523		if (tape->onstream) {
4524			position = idetape_read_position(drive);
4525			if (position <= OS_DATA_STARTFRAME1) {
4526				tape->logical_blk_num = 0;
4527				tape->wrt_pass_cntr++;
4528#if ONSTREAM_DEBUG
4529				if (tape->debug_level >= 2)
4530					printk(KERN_INFO "ide-tape: %s: logical block num 0, setting eod to %d\n", tape->name, OS_DATA_STARTFRAME1);
4531				if (tape->debug_level >= 2)
4532					printk(KERN_INFO "ide-tape: %s: allocating new write pass counter %d\n", tape->name, tape->wrt_pass_cntr);
4533#endif
4534				tape->filemark_cnt = 0;
4535				tape->eod_frame_addr = OS_DATA_STARTFRAME1;
4536				tape->first_mark_addr = tape->last_mark_addr = -1;
4537				idetape_write_header(drive, 1);
4538			}
4539#if ONSTREAM_DEBUG
4540			if (tape->debug_level >= 2)
4541				printk(KERN_INFO "ide-tape: %s: positioning tape to eod at %d\n", tape->name, tape->eod_frame_addr);
4542#endif
4543			position = idetape_read_position(drive);
4544			if (position != tape->eod_frame_addr)
4545				idetape_position_tape(drive, tape->eod_frame_addr, 0, 0);
4546#if ONSTREAM_DEBUG
4547			if (tape->debug_level >= 2)
4548				printk(KERN_INFO "ide-tape: %s: first_frame_position %d\n", tape->name, tape->first_frame_position);
4549#endif
4550		}
4551
4552		/*
4553		 *	Issue a write 0 command to ensure that DSC handshake
4554		 *	is switched from completion mode to buffer available
4555		 *	mode.
4556		 */
4557		retval = idetape_queue_rw_tail (drive, IDETAPE_WRITE_RQ, 0, tape->merge_stage->bh);
4558		if (retval < 0) {
4559			kfree (tape->merge_stage);
4560			tape->merge_stage = NULL;
4561			tape->chrdev_direction = idetape_direction_none;
4562			return retval;
4563		}
4564#if ONSTREAM_DEBUG
4565		if (tape->debug_level >= 2)
4566			printk("ide-tape: first_frame_position %d\n", tape->first_frame_position);
4567#endif
4568	}
4569	if (count == 0)
4570		return (0);
4571	if (tape->restart_speed_control_req)
4572		idetape_restart_speed_control(drive);
4573	if (tape->merge_stage_size) {
4574#if IDETAPE_DEBUG_BUGS
4575		if (tape->merge_stage_size >= tape->stage_size) {
4576			printk (KERN_ERR "ide-tape: bug: merge buffer too big\n");
4577			tape->merge_stage_size = 0;
4578		}
4579#endif /* IDETAPE_DEBUG_BUGS */
4580		actually_written = IDE_MIN (tape->stage_size - tape->merge_stage_size, count);
4581		idetape_copy_stage_from_user (tape, tape->merge_stage, buf, actually_written);
4582		buf += actually_written;
4583		tape->merge_stage_size += actually_written;
4584		count -= actually_written;
4585
4586		if (tape->merge_stage_size == tape->stage_size) {
4587			tape->merge_stage_size = 0;
4588			retval = idetape_add_chrdev_write_request (drive, tape->capabilities.ctl);
4589			if (retval <= 0)
4590				return (retval);
4591		}
4592	}
4593	while (count >= tape->stage_size) {
4594		idetape_copy_stage_from_user (tape, tape->merge_stage, buf, tape->stage_size);
4595		buf += tape->stage_size;
4596		count -= tape->stage_size;
4597		retval = idetape_add_chrdev_write_request (drive, tape->capabilities.ctl);
4598		actually_written += tape->stage_size;
4599		if (retval <= 0)
4600			return (retval);
4601	}
4602	if (count) {
4603		actually_written+=count;
4604		idetape_copy_stage_from_user (tape, tape->merge_stage, buf, count);
4605		tape->merge_stage_size += count;
4606	}
4607	return (actually_written);
4608}
4609
4610static int idetape_write_filemark (ide_drive_t *drive)
4611{
4612	idetape_tape_t *tape = drive->driver_data;
4613	int last_mark_addr;
4614	idetape_pc_t pc;
4615
4616	if (!tape->onstream) {
4617		idetape_create_write_filemark_cmd(drive, &pc, 1);	/* Write a filemark */
4618		if (idetape_queue_pc_tail (drive, &pc)) {
4619			printk (KERN_ERR "ide-tape: Couldn't write a filemark\n");
4620			return -EIO;
4621		}
4622	} else if (!tape->raw) {
4623		last_mark_addr = idetape_read_position(drive);
4624		tape->merge_stage = __idetape_kmalloc_stage (tape, 1, 0);
4625		if (tape->merge_stage != NULL) {
4626			idetape_init_stage(drive, tape->merge_stage, OS_FRAME_TYPE_MARKER, tape->logical_blk_num);
4627			idetape_pad_zeros (drive, tape->stage_size);
4628			tape->logical_blk_num++;
4629			__idetape_kfree_stage (tape->merge_stage);
4630			tape->merge_stage = NULL;
4631		}
4632		if (tape->filemark_cnt)
4633			idetape_update_last_marker(drive, tape->last_mark_addr, last_mark_addr);
4634		tape->last_mark_addr = last_mark_addr;
4635		if (tape->filemark_cnt++ == 0)
4636			tape->first_mark_addr = last_mark_addr;
4637	}
4638	return 0;
4639}
4640
4641static void idetape_write_eod (ide_drive_t *drive)
4642{
4643	idetape_tape_t *tape = drive->driver_data;
4644
4645	if (!tape->onstream || tape->raw)
4646		return;
4647	tape->merge_stage = __idetape_kmalloc_stage (tape, 1, 0);
4648	if (tape->merge_stage != NULL) {
4649		tape->eod_frame_addr = idetape_read_position(drive);
4650		idetape_init_stage(drive, tape->merge_stage, OS_FRAME_TYPE_EOD, tape->logical_blk_num);
4651		idetape_pad_zeros (drive, tape->stage_size);
4652		__idetape_kfree_stage (tape->merge_stage);
4653		tape->merge_stage = NULL;
4654	}
4655	return;
4656}
4657
4658int idetape_seek_logical_blk (ide_drive_t *drive, int logical_blk_num)
4659{
4660	idetape_tape_t *tape = drive->driver_data;
4661	int estimated_address = logical_blk_num + 20;
4662	int retries = 0;
4663	int speed_control;
4664
4665	speed_control = tape->speed_control;
4666	tape->speed_control = 0;
4667	if (logical_blk_num < 0)
4668		logical_blk_num = 0;
4669	if (idetape_get_logical_blk(drive, logical_blk_num, 10, 1))
4670		goto ok;
4671	while (++retries < 10) {
4672		idetape_discard_read_pipeline(drive, 0);
4673		idetape_position_tape(drive, estimated_address, 0, 0);
4674		if (idetape_get_logical_blk(drive, logical_blk_num, 10, 1))
4675			goto ok;
4676		if (!idetape_get_logical_blk(drive, -1, 10, 1))
4677			goto error;
4678		if (tape->logical_blk_num < logical_blk_num)
4679			estimated_address += logical_blk_num - tape->logical_blk_num;
4680		else
4681			break;
4682	}
4683error:
4684	tape->speed_control = speed_control;
4685	tape->restart_speed_control_req = 1;
4686	printk(KERN_INFO "ide-tape: %s: couldn't seek to logical block %d (at %d), %d retries\n", tape->name, logical_blk_num, tape->logical_blk_num, retries);
4687	return -EIO;
4688ok:
4689	tape->speed_control = speed_control;
4690	tape->restart_speed_control_req = 1;
4691	return 0;
4692}
4693
4694/*
4695 *	idetape_mtioctop is called from idetape_chrdev_ioctl when
4696 *	the general mtio MTIOCTOP ioctl is requested.
4697 *
4698 *	We currently support the following mtio.h operations:
4699 *
4700 *	MTFSF	-	Space over mt_count filemarks in the positive direction.
4701 *			The tape is positioned after the last spaced filemark.
4702 *
4703 *	MTFSFM	-	Same as MTFSF, but the tape is positioned before the
4704 *			last filemark.
4705 *
4706 *	MTBSF	-	Steps background over mt_count filemarks, tape is
4707 *			positioned before the last filemark.
4708 *
4709 *	MTBSFM	-	Like MTBSF, only tape is positioned after the last filemark.
4710 *
4711 *	Note:
4712 *
4713 *		MTBSF and MTBSFM are not supported when the tape doesn't
4714 *		supports spacing over filemarks in the reverse direction.
4715 *		In this case, MTFSFM is also usually not supported (it is
4716 *		supported in the rare case in which we crossed the filemark
4717 *		during our read-ahead pipelined operation mode).
4718 *
4719 *	MTWEOF	-	Writes mt_count filemarks. Tape is positioned after
4720 *			the last written filemark.
4721 *
4722 *	MTREW	-	Rewinds tape.
4723 *
4724 *	MTLOAD	-	Loads the tape.
4725 *
4726 *	MTOFFL	-	Puts the tape drive "Offline": Rewinds the tape and
4727 *	MTUNLOAD	prevents further access until the media is replaced.
4728 *
4729 *	MTNOP	-	Flushes tape buffers.
4730 *
4731 *	MTRETEN	-	Retension media. This typically consists of one end
4732 *			to end pass on the media.
4733 *
4734 *	MTEOM	-	Moves to the end of recorded data.
4735 *
4736 *	MTERASE	-	Erases tape.
4737 *
4738 *	MTSETBLK - 	Sets the user block size to mt_count bytes. If
4739 *			mt_count is 0, we will attempt to autodetect
4740 *			the block size.
4741 *
4742 *	MTSEEK	-	Positions the tape in a specific block number, where
4743 *			each block is assumed to contain which user_block_size
4744 *			bytes.
4745 *
4746 *	MTSETPART - 	Switches to another tape partition.
4747 *
4748 *	MTLOCK - 	Locks the tape door.
4749 *
4750 *	MTUNLOCK - 	Unlocks the tape door.
4751 *
4752 *	The following commands are currently not supported:
4753 *
4754 *	MTFSS, MTBSS, MTWSM, MTSETDENSITY,
4755 *	MTSETDRVBUFFER, MT_ST_BOOLEANS, MT_ST_WRITE_THRESHOLD.
4756 */
4757static int idetape_mtioctop (ide_drive_t *drive,short mt_op,int mt_count)
4758{
4759	idetape_tape_t *tape = drive->driver_data;
4760	idetape_pc_t pc;
4761	int i,retval;
4762
4763#if IDETAPE_DEBUG_LOG
4764	if (tape->debug_level >= 1)
4765		printk (KERN_INFO "ide-tape: Handling MTIOCTOP ioctl: mt_op=%d, mt_count=%d\n",mt_op,mt_count);
4766#endif /* IDETAPE_DEBUG_LOG */
4767	/*
4768	 *	Commands which need our pipelined read-ahead stages.
4769	 */
4770	switch (mt_op) {
4771		case MTFSF:
4772		case MTFSFM:
4773		case MTBSF:
4774		case MTBSFM:
4775			if (!mt_count)
4776				return (0);
4777			return (idetape_space_over_filemarks (drive,mt_op,mt_count));
4778		default:
4779			break;
4780	}
4781	switch (mt_op) {
4782		case MTWEOF:
4783			idetape_discard_read_pipeline (drive, 1);
4784			for (i = 0; i < mt_count; i++) {
4785				retval = idetape_write_filemark(drive);
4786				if (retval) return retval;
4787			}
4788			return (0);
4789		case MTREW:
4790			idetape_discard_read_pipeline (drive, 0);
4791			if (idetape_rewind_tape(drive))
4792				return -EIO;
4793			if (tape->onstream && !tape->raw)
4794				return idetape_position_tape(drive, OS_DATA_STARTFRAME1, 0, 0);
4795			return 0;
4796		case MTLOAD:
4797			idetape_discard_read_pipeline (drive, 0);
4798			idetape_create_load_unload_cmd (drive, &pc, IDETAPE_LU_LOAD_MASK);
4799			return (idetape_queue_pc_tail (drive, &pc));
4800		case MTUNLOAD:
4801		case MTOFFL:
4802			idetape_discard_read_pipeline (drive, 0);
4803			idetape_create_load_unload_cmd (drive, &pc,!IDETAPE_LU_LOAD_MASK);
4804			return (idetape_queue_pc_tail (drive, &pc));
4805		case MTNOP:
4806			idetape_discard_read_pipeline (drive, 0);
4807			return (idetape_flush_tape_buffers (drive));
4808		case MTRETEN:
4809			idetape_discard_read_pipeline (drive, 0);
4810			idetape_create_load_unload_cmd (drive, &pc,IDETAPE_LU_RETENSION_MASK | IDETAPE_LU_LOAD_MASK);
4811			return (idetape_queue_pc_tail (drive, &pc));
4812		case MTEOM:
4813			if (tape->onstream) {
4814#if ONSTREAM_DEBUG
4815				if (tape->debug_level >= 2)
4816					printk(KERN_INFO "ide-tape: %s: positioning tape to eod at %d\n", tape->name, tape->eod_frame_addr);
4817#endif
4818				idetape_position_tape(drive, tape->eod_frame_addr, 0, 0);
4819				if (!idetape_get_logical_blk(drive, -1, 10, 0))
4820					return -EIO;
4821				if (tape->first_stage->aux->frame_type != OS_FRAME_TYPE_EOD)
4822					return -EIO;
4823				return 0;
4824			}
4825			idetape_create_space_cmd (&pc, 0, IDETAPE_SPACE_TO_EOD);
4826			return (idetape_queue_pc_tail (drive, &pc));
4827		case MTERASE:
4828			if (tape->onstream) {
4829				tape->eod_frame_addr = OS_DATA_STARTFRAME1;
4830				tape->logical_blk_num = 0;
4831				tape->first_mark_addr = tape->last_mark_addr = -1;
4832				idetape_position_tape(drive, tape->eod_frame_addr, 0, 0);
4833				idetape_write_eod(drive);
4834				idetape_flush_tape_buffers (drive);
4835				idetape_write_header(drive, 0);
4836				/*
4837				 * write filler frames to the unused frames...
4838				 * REMOVE WHEN going to LIN4 application type...
4839				 */
4840				idetape_write_filler(drive, OS_DATA_STARTFRAME1 - 10, 10);
4841				idetape_write_filler(drive, OS_DATA_ENDFRAME1, 10);
4842				idetape_flush_tape_buffers (drive);
4843				(void) idetape_rewind_tape (drive);
4844				return 0;
4845			}
4846			(void) idetape_rewind_tape (drive);
4847			idetape_create_erase_cmd (&pc);
4848			return (idetape_queue_pc_tail (drive, &pc));
4849		case MTSETBLK:
4850			if (tape->onstream) {
4851				if (mt_count != tape->tape_block_size) {
4852					printk(KERN_INFO "ide-tape: %s: MTSETBLK %d -- only %d bytes block size supported\n", tape->name, mt_count, tape->tape_block_size);
4853					return -EINVAL;
4854				}
4855				return 0;
4856			}
4857			if (mt_count) {
4858				if (mt_count < tape->tape_block_size || mt_count % tape->tape_block_size)
4859					return -EIO;
4860				tape->user_bs_factor = mt_count / tape->tape_block_size;
4861				clear_bit (IDETAPE_DETECT_BS, &tape->flags);
4862			} else
4863				set_bit (IDETAPE_DETECT_BS, &tape->flags);
4864			return 0;
4865		case MTSEEK:
4866			if (!tape->onstream || tape->raw) {
4867				idetape_discard_read_pipeline (drive, 0);
4868				return idetape_position_tape (drive, mt_count * tape->user_bs_factor, tape->partition, 0);
4869			}
4870			return idetape_seek_logical_blk(drive, mt_count);
4871		case MTSETPART:
4872			idetape_discard_read_pipeline (drive, 0);
4873			if (tape->onstream)
4874				return -EIO;
4875			return (idetape_position_tape (drive, 0, mt_count, 0));
4876		case MTFSR:
4877		case MTBSR:
4878			if (tape->onstream) {
4879				if (!idetape_get_logical_blk(drive, -1, 10, 0))
4880					return -EIO;
4881				if (mt_op == MTFSR)
4882					return idetape_seek_logical_blk(drive, tape->logical_blk_num + mt_count);
4883				else {
4884					idetape_discard_read_pipeline (drive, 0);
4885					return idetape_seek_logical_blk(drive, tape->logical_blk_num - mt_count);
4886				}
4887			}
4888		case MTLOCK:
4889			if (!idetape_create_prevent_cmd(drive, &pc, 1))
4890				return 0;
4891			retval = idetape_queue_pc_tail (drive, &pc);
4892			if (retval) return retval;
4893			tape->door_locked = DOOR_EXPLICITLY_LOCKED;
4894			return 0;
4895		case MTUNLOCK:
4896			if (!idetape_create_prevent_cmd(drive, &pc, 0))
4897				return 0;
4898			retval = idetape_queue_pc_tail (drive, &pc);
4899			if (retval) return retval;
4900			tape->door_locked = DOOR_UNLOCKED;
4901			return 0;
4902		default:
4903			printk (KERN_ERR "ide-tape: MTIO operation %d not supported\n",mt_op);
4904			return (-EIO);
4905	}
4906}
4907
4908/*
4909 *	Our character device ioctls.
4910 *
4911 *	General mtio.h magnetic io commands are supported here, and not in
4912 *	the corresponding block interface.
4913 *
4914 *	The following ioctls are supported:
4915 *
4916 *	MTIOCTOP -	Refer to idetape_mtioctop for detailed description.
4917 *
4918 *	MTIOCGET - 	The mt_dsreg field in the returned mtget structure
4919 *			will be set to (user block size in bytes <<
4920 *			MT_ST_BLKSIZE_SHIFT) & MT_ST_BLKSIZE_MASK.
4921 *
4922 *			The mt_blkno is set to the current user block number.
4923 *			The other mtget fields are not supported.
4924 *
4925 *	MTIOCPOS -	The current tape "block position" is returned. We
4926 *			assume that each block contains user_block_size
4927 *			bytes.
4928 *
4929 *	Our own ide-tape ioctls are supported on both interfaces.
4930 */
4931static int idetape_chrdev_ioctl (struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
4932{
4933	ide_drive_t *drive = get_drive_ptr (inode->i_rdev);
4934	idetape_tape_t *tape = drive->driver_data;
4935	struct mtop mtop;
4936	struct mtget mtget;
4937	struct mtpos mtpos;
4938	int block_offset = 0, position = tape->first_frame_position;
4939
4940#if IDETAPE_DEBUG_LOG
4941	if (tape->debug_level >= 3)
4942		printk (KERN_INFO "ide-tape: Reached idetape_chrdev_ioctl, cmd=%u\n",cmd);
4943#endif /* IDETAPE_DEBUG_LOG */
4944
4945	tape->restart_speed_control_req = 1;
4946	if (tape->chrdev_direction == idetape_direction_write) {
4947		idetape_empty_write_pipeline (drive);
4948		idetape_flush_tape_buffers (drive);
4949	}
4950	if (cmd == MTIOCGET || cmd == MTIOCPOS) {
4951		block_offset = idetape_pipeline_size (drive) / (tape->tape_block_size * tape->user_bs_factor);
4952		if ((position = idetape_read_position(drive)) < 0)
4953			return -EIO;
4954	}
4955	switch (cmd) {
4956		case MTIOCTOP:
4957			if (copy_from_user ((char *) &mtop, (char *) arg, sizeof (struct mtop)))
4958				return -EFAULT;
4959			return (idetape_mtioctop (drive,mtop.mt_op,mtop.mt_count));
4960		case MTIOCGET:
4961			memset (&mtget, 0, sizeof (struct mtget));
4962			mtget.mt_type = MT_ISSCSI2;
4963			if (!tape->onstream || tape->raw)
4964				mtget.mt_blkno = position / tape->user_bs_factor - block_offset;
4965			else {
4966				if (!idetape_get_logical_blk(drive, -1, 10, 0))
4967					mtget.mt_blkno = -1;
4968				else
4969					mtget.mt_blkno = tape->logical_blk_num;
4970			}
4971			mtget.mt_dsreg = ((tape->tape_block_size * tape->user_bs_factor) << MT_ST_BLKSIZE_SHIFT) & MT_ST_BLKSIZE_MASK;
4972			if (tape->onstream) {
4973				mtget.mt_gstat |= GMT_ONLINE(0xffffffff);
4974				if (tape->first_stage && tape->first_stage->aux->frame_type == OS_FRAME_TYPE_EOD)
4975					mtget.mt_gstat |= GMT_EOD(0xffffffff);
4976				if (position <= OS_DATA_STARTFRAME1)
4977					mtget.mt_gstat |= GMT_BOT(0xffffffff);
4978			}
4979			if (copy_to_user ((char *) arg,(char *) &mtget, sizeof (struct mtget)))
4980				return -EFAULT;
4981			return 0;
4982		case MTIOCPOS:
4983			if (tape->onstream && !tape->raw) {
4984				if (!idetape_get_logical_blk(drive, -1, 10, 0))
4985					return -EIO;
4986				mtpos.mt_blkno = tape->logical_blk_num;
4987			} else
4988				mtpos.mt_blkno = position / tape->user_bs_factor - block_offset;
4989			if (copy_to_user ((char *) arg,(char *) &mtpos, sizeof (struct mtpos)))
4990				return -EFAULT;
4991			return 0;
4992		default:
4993			if (tape->chrdev_direction == idetape_direction_read)
4994				idetape_discard_read_pipeline (drive, 1);
4995			return (idetape_blkdev_ioctl (drive,inode,file,cmd,arg));
4996	}
4997}
4998
4999static int __idetape_analyze_headers (ide_drive_t *drive, int block)
5000{
5001	idetape_tape_t *tape = drive->driver_data;
5002	idetape_stage_t *stage;
5003	os_header_t *header;
5004	os_aux_t *aux;
5005
5006	if (!tape->onstream || tape->raw) {
5007		tape->header_ok = tape->linux_media = 1;
5008		return 1;
5009	}
5010	tape->header_ok = tape->linux_media = 0;
5011	tape->update_frame_cntr = 0;
5012	tape->wrt_pass_cntr = 0;
5013	tape->eod_frame_addr = OS_DATA_STARTFRAME1;
5014	tape->first_mark_addr = tape->last_mark_addr = -1;
5015	stage = __idetape_kmalloc_stage (tape, 0, 0);
5016	if (stage == NULL)
5017		return 0;
5018#if ONSTREAM_DEBUG
5019	if (tape->debug_level >= 2)
5020		printk(KERN_INFO "ide-tape: %s: reading header\n", tape->name);
5021#endif
5022	idetape_position_tape(drive, block, 0, 0);
5023	if (!idetape_queue_rw_tail (drive, IDETAPE_READ_RQ, 1, stage->bh)) {
5024		printk(KERN_INFO "ide-tape: %s: couldn't read header frame\n", tape->name);
5025		__idetape_kfree_stage (stage);
5026		return 0;
5027	}
5028	header = (os_header_t *) stage->bh->b_data;
5029	aux = stage->aux;
5030	if (strncmp(header->ident_str, "ADR_SEQ", 7) != 0) {
5031		printk(KERN_INFO "ide-tape: %s: invalid header identification string\n", tape->name);
5032		__idetape_kfree_stage (stage);
5033		return 0;
5034	}
5035	if (header->major_rev != 1 || (header->minor_rev > OS_ADR_MINREV))
5036		printk(KERN_INFO "ide-tape: warning: revision %d.%d detected (up to 1.%d supported)\n", header->major_rev, header->minor_rev, OS_ADR_MINREV);
5037	if (header->par_num != 1)
5038		printk(KERN_INFO "ide-tape: warning: %d partitions defined, only one supported\n", header->par_num);
5039	tape->wrt_pass_cntr = ntohs(header->partition.wrt_pass_cntr);
5040	tape->eod_frame_addr = ntohl(header->partition.eod_frame_addr);
5041	tape->filemark_cnt = ntohl(aux->filemark_cnt);
5042	tape->first_mark_addr = ntohl(aux->next_mark_addr);
5043	tape->last_mark_addr = ntohl(aux->last_mark_addr);
5044	tape->update_frame_cntr = ntohl(aux->update_frame_cntr);
5045	memcpy(tape->application_sig, aux->application_sig, 4);
5046	tape->application_sig[4] = 0;
5047	if (memcmp(tape->application_sig, "LIN", 3) == 0) {
5048		tape->linux_media = 1;
5049		tape->linux_media_version = tape->application_sig[3] - '0';
5050		if (tape->linux_media_version != 3)
5051			printk(KERN_INFO "ide-tape: %s: Linux media version %d detected (current 3)\n",
5052					 tape->name, tape->linux_media_version);
5053	} else {
5054		printk(KERN_INFO "ide-tape: %s: non Linux media detected (%s)\n", tape->name, tape->application_sig);
5055		tape->linux_media = 0;
5056	}
5057#if ONSTREAM_DEBUG
5058	if (tape->debug_level >= 2)
5059		printk(KERN_INFO "ide-tape: %s: detected write pass counter %d, eod frame addr %d\n", tape->name, tape->wrt_pass_cntr, tape->eod_frame_addr);
5060#endif
5061	__idetape_kfree_stage (stage);
5062	return 1;
5063}
5064
5065static int idetape_analyze_headers (ide_drive_t *drive)
5066{
5067	idetape_tape_t *tape = drive->driver_data;
5068	int position, block;
5069
5070	if (!tape->onstream || tape->raw) {
5071		tape->header_ok = tape->linux_media = 1;
5072		return 1;
5073	}
5074	tape->header_ok = tape->linux_media = 0;
5075	position = idetape_read_position(drive);
5076	for (block = 5; block < 10; block++)
5077		if (__idetape_analyze_headers(drive, block))
5078			goto ok;
5079	for (block = 0xbae; block < 0xbb3; block++) /* 2990 - 2994 */
5080		if (__idetape_analyze_headers(drive, block))
5081			goto ok;
5082	printk(KERN_ERR "ide-tape: %s: failed to find valid ADRL header\n", tape->name);
5083	return 0;
5084ok:
5085	if (position < OS_DATA_STARTFRAME1)
5086		position = OS_DATA_STARTFRAME1;
5087	idetape_position_tape(drive, position, 0, 0);
5088	tape->header_ok = 1;
5089	return 1;
5090}
5091
5092/*
5093 *	Our character device open function.
5094 */
5095static int idetape_chrdev_open (struct inode *inode, struct file *filp)
5096{
5097	ide_drive_t *drive;
5098	idetape_tape_t *tape;
5099	idetape_pc_t pc;
5100	unsigned int minor=MINOR (inode->i_rdev);
5101
5102#if IDETAPE_DEBUG_LOG
5103	printk (KERN_INFO "ide-tape: Reached idetape_chrdev_open\n");
5104#endif /* IDETAPE_DEBUG_LOG */
5105
5106	if ((drive = get_drive_ptr (inode->i_rdev)) == NULL)
5107		return -ENXIO;
5108	tape = drive->driver_data;
5109
5110	if (test_and_set_bit (IDETAPE_BUSY, &tape->flags))
5111		return -EBUSY;
5112	MOD_INC_USE_COUNT;
5113	if (!tape->onstream) {
5114		idetape_read_position(drive);
5115		if (!test_bit (IDETAPE_ADDRESS_VALID, &tape->flags))
5116			(void) idetape_rewind_tape (drive);
5117	} else {
5118		if (minor & 64) {
5119			tape->tape_block_size = tape->stage_size = 32768 + 512;
5120			tape->raw = 1;
5121		} else {
5122			tape->tape_block_size = tape->stage_size = 32768;
5123			tape->raw = 0;
5124		}
5125                idetape_onstream_mode_sense_tape_parameter_page(drive, tape->debug_level);
5126	}
5127	if (idetape_wait_ready(drive, 60 * HZ)) {
5128		clear_bit(IDETAPE_BUSY, &tape->flags);
5129		printk(KERN_ERR "ide-tape: %s: drive not ready\n", tape->name);
5130		MOD_DEC_USE_COUNT;
5131		return -EBUSY;
5132	}
5133	idetape_read_position(drive);
5134	MOD_DEC_USE_COUNT;
5135	clear_bit (IDETAPE_PIPELINE_ERROR, &tape->flags);
5136
5137	if (tape->chrdev_direction == idetape_direction_none) {
5138		MOD_INC_USE_COUNT;
5139		if (idetape_create_prevent_cmd(drive, &pc, 1)) {
5140			if (!idetape_queue_pc_tail (drive, &pc)) {
5141				if (tape->door_locked != DOOR_EXPLICITLY_LOCKED)
5142					tape->door_locked = DOOR_LOCKED;
5143			}
5144		}
5145		idetape_analyze_headers(drive);
5146	}
5147	tape->max_frames = tape->cur_frames = tape->req_buffer_fill = 0;
5148	idetape_restart_speed_control(drive);
5149	tape->restart_speed_control_req = 0;
5150	return 0;
5151}
5152
5153static void idetape_write_release (struct inode *inode)
5154{
5155	ide_drive_t *drive = get_drive_ptr (inode->i_rdev);
5156	idetape_tape_t *tape = drive->driver_data;
5157	unsigned int minor=MINOR (inode->i_rdev);
5158
5159	idetape_empty_write_pipeline (drive);
5160	tape->merge_stage = __idetape_kmalloc_stage (tape, 1, 0);
5161	if (tape->merge_stage != NULL) {
5162		idetape_pad_zeros (drive, tape->tape_block_size * (tape->user_bs_factor - 1));
5163		__idetape_kfree_stage (tape->merge_stage);
5164		tape->merge_stage = NULL;
5165	}
5166	idetape_write_filemark(drive);
5167	idetape_write_eod(drive);
5168	idetape_flush_tape_buffers (drive);
5169	idetape_write_header(drive, minor >= 128);
5170	idetape_flush_tape_buffers (drive);
5171
5172	return;
5173}
5174
5175/*
5176 *	Our character device release function.
5177 */
5178static int idetape_chrdev_release (struct inode *inode, struct file *filp)
5179{
5180	ide_drive_t *drive = get_drive_ptr (inode->i_rdev);
5181	idetape_tape_t *tape;
5182	idetape_pc_t pc;
5183	unsigned int minor=MINOR (inode->i_rdev);
5184
5185	lock_kernel();
5186	tape = drive->driver_data;
5187#if IDETAPE_DEBUG_LOG
5188	if (tape->debug_level >= 3)
5189		printk (KERN_INFO "ide-tape: Reached idetape_chrdev_release\n");
5190#endif /* IDETAPE_DEBUG_LOG */
5191
5192	if (tape->chrdev_direction == idetape_direction_write) {
5193		idetape_write_release(inode);
5194	}
5195	if (tape->chrdev_direction == idetape_direction_read) {
5196		if (minor < 128)
5197			idetape_discard_read_pipeline (drive, 1);
5198		else
5199			idetape_wait_for_pipeline (drive);
5200	}
5201	if (tape->cache_stage != NULL) {
5202		__idetape_kfree_stage (tape->cache_stage);
5203		tape->cache_stage = NULL;
5204	}
5205	if (minor < 128)
5206		(void) idetape_rewind_tape (drive);
5207	if (tape->chrdev_direction == idetape_direction_none) {
5208		if (tape->door_locked != DOOR_EXPLICITLY_LOCKED) {
5209			if (idetape_create_prevent_cmd(drive, &pc, 0))
5210				if (!idetape_queue_pc_tail (drive, &pc))
5211					tape->door_locked = DOOR_UNLOCKED;
5212		}
5213		MOD_DEC_USE_COUNT;
5214	}
5215	clear_bit (IDETAPE_BUSY, &tape->flags);
5216	unlock_kernel();
5217	return 0;
5218}
5219
5220/*
5221 *	idetape_identify_device is called to check the contents of the
5222 *	ATAPI IDENTIFY command results. We return:
5223 *
5224 *	1	If the tape can be supported by us, based on the information
5225 *		we have so far.
5226 *
5227 *	0 	If this tape driver is not currently supported by us.
5228 */
5229static int idetape_identify_device (ide_drive_t *drive,struct hd_driveid *id)
5230{
5231	struct idetape_id_gcw gcw;
5232#if IDETAPE_DEBUG_INFO
5233	unsigned short mask,i;
5234#endif /* IDETAPE_DEBUG_INFO */
5235
5236	if (!id)
5237		return 0;
5238
5239	*((unsigned short *) &gcw) = id->config;
5240
5241#if IDETAPE_DEBUG_INFO
5242	printk (KERN_INFO "ide-tape: Dumping ATAPI Identify Device tape parameters\n");
5243	printk (KERN_INFO "ide-tape: Protocol Type: ");
5244	switch (gcw.protocol) {
5245		case 0: case 1: printk (KERN_INFO "ATA\n");break;
5246		case 2:	printk (KERN_INFO "ATAPI\n");break;
5247		case 3: printk (KERN_INFO "Reserved (Unknown to ide-tape)\n");break;
5248	}
5249	printk (KERN_INFO "ide-tape: Device Type: %x - ",gcw.device_type);
5250	switch (gcw.device_type) {
5251		case 0: printk (KERN_INFO "Direct-access Device\n");break;
5252		case 1: printk (KERN_INFO "Streaming Tape Device\n");break;
5253		case 2: case 3: case 4: printk (KERN_INFO "Reserved\n");break;
5254		case 5: printk (KERN_INFO "CD-ROM Device\n");break;
5255		case 6: printk (KERN_INFO "Reserved\n");
5256		case 7: printk (KERN_INFO "Optical memory Device\n");break;
5257		case 0x1f: printk (KERN_INFO "Unknown or no Device type\n");break;
5258		default: printk (KERN_INFO "Reserved\n");
5259	}
5260	printk (KERN_INFO "ide-tape: Removable: %s",gcw.removable ? "Yes\n":"No\n");
5261	printk (KERN_INFO "ide-tape: Command Packet DRQ Type: ");
5262	switch (gcw.drq_type) {
5263		case 0: printk (KERN_INFO "Microprocessor DRQ\n");break;
5264		case 1: printk (KERN_INFO "Interrupt DRQ\n");break;
5265		case 2: printk (KERN_INFO "Accelerated DRQ\n");break;
5266		case 3: printk (KERN_INFO "Reserved\n");break;
5267	}
5268	printk (KERN_INFO "ide-tape: Command Packet Size: ");
5269	switch (gcw.packet_size) {
5270		case 0: printk (KERN_INFO "12 bytes\n");break;
5271		case 1: printk (KERN_INFO "16 bytes\n");break;
5272		default: printk (KERN_INFO "Reserved\n");break;
5273	}
5274	printk (KERN_INFO "ide-tape: Model: %.40s\n",id->model);
5275	printk (KERN_INFO "ide-tape: Firmware Revision: %.8s\n",id->fw_rev);
5276	printk (KERN_INFO "ide-tape: Serial Number: %.20s\n",id->serial_no);
5277	printk (KERN_INFO "ide-tape: Write buffer size: %d bytes\n",id->buf_size*512);
5278	printk (KERN_INFO "ide-tape: DMA: %s",id->capability & 0x01 ? "Yes\n":"No\n");
5279	printk (KERN_INFO "ide-tape: LBA: %s",id->capability & 0x02 ? "Yes\n":"No\n");
5280	printk (KERN_INFO "ide-tape: IORDY can be disabled: %s",id->capability & 0x04 ? "Yes\n":"No\n");
5281	printk (KERN_INFO "ide-tape: IORDY supported: %s",id->capability & 0x08 ? "Yes\n":"Unknown\n");
5282	printk (KERN_INFO "ide-tape: ATAPI overlap supported: %s",id->capability & 0x20 ? "Yes\n":"No\n");
5283	printk (KERN_INFO "ide-tape: PIO Cycle Timing Category: %d\n",id->tPIO);
5284	printk (KERN_INFO "ide-tape: DMA Cycle Timing Category: %d\n",id->tDMA);
5285	printk (KERN_INFO "ide-tape: Single Word DMA supported modes: ");
5286	for (i=0,mask=1;i<8;i++,mask=mask << 1) {
5287		if (id->dma_1word & mask)
5288			printk (KERN_INFO "%d ",i);
5289		if (id->dma_1word & (mask << 8))
5290			printk (KERN_INFO "(active) ");
5291	}
5292	printk (KERN_INFO "\n");
5293	printk (KERN_INFO "ide-tape: Multi Word DMA supported modes: ");
5294	for (i=0,mask=1;i<8;i++,mask=mask << 1) {
5295		if (id->dma_mword & mask)
5296			printk (KERN_INFO "%d ",i);
5297		if (id->dma_mword & (mask << 8))
5298			printk (KERN_INFO "(active) ");
5299	}
5300	printk (KERN_INFO "\n");
5301	if (id->field_valid & 0x0002) {
5302		printk (KERN_INFO "ide-tape: Enhanced PIO Modes: %s\n",id->eide_pio_modes & 1 ? "Mode 3":"None");
5303		printk (KERN_INFO "ide-tape: Minimum Multi-word DMA cycle per word: ");
5304		if (id->eide_dma_min == 0)
5305			printk (KERN_INFO "Not supported\n");
5306		else
5307			printk (KERN_INFO "%d ns\n",id->eide_dma_min);
5308
5309		printk (KERN_INFO "ide-tape: Manufacturer\'s Recommended Multi-word cycle: ");
5310		if (id->eide_dma_time == 0)
5311			printk (KERN_INFO "Not supported\n");
5312		else
5313			printk (KERN_INFO "%d ns\n",id->eide_dma_time);
5314
5315		printk (KERN_INFO "ide-tape: Minimum PIO cycle without IORDY: ");
5316		if (id->eide_pio == 0)
5317			printk (KERN_INFO "Not supported\n");
5318		else
5319			printk (KERN_INFO "%d ns\n",id->eide_pio);
5320
5321		printk (KERN_INFO "ide-tape: Minimum PIO cycle with IORDY: ");
5322		if (id->eide_pio_iordy == 0)
5323			printk (KERN_INFO "Not supported\n");
5324		else
5325			printk (KERN_INFO "%d ns\n",id->eide_pio_iordy);
5326
5327	} else
5328		printk (KERN_INFO "ide-tape: According to the device, fields 64-70 are not valid.\n");
5329#endif /* IDETAPE_DEBUG_INFO */
5330
5331	/* Check that we can support this device */
5332
5333	if (gcw.protocol !=2 )
5334		printk (KERN_ERR "ide-tape: Protocol is not ATAPI\n");
5335	else if (gcw.device_type != 1)
5336		printk (KERN_ERR "ide-tape: Device type is not set to tape\n");
5337	else if (!gcw.removable)
5338		printk (KERN_ERR "ide-tape: The removable flag is not set\n");
5339	else if (gcw.packet_size != 0) {
5340		printk (KERN_ERR "ide-tape: Packet size is not 12 bytes long\n");
5341		if (gcw.packet_size == 1)
5342			printk (KERN_ERR "ide-tape: Sorry, padding to 16 bytes is still not supported\n");
5343	} else
5344		return 1;
5345	return 0;
5346}
5347
5348/*
5349 * Notify vendor ID to the OnStream tape drive
5350 */
5351static void idetape_onstream_set_vendor (ide_drive_t *drive, char *vendor)
5352{
5353	idetape_pc_t pc;
5354	idetape_mode_parameter_header_t *header;
5355
5356	idetape_create_mode_select_cmd(&pc, sizeof(*header) + 8);
5357	pc.buffer[0] = 3 + 8;	/* Mode Data Length */
5358	pc.buffer[1] = 0;	/* Medium Type - ignoring */
5359	pc.buffer[2] = 0;	/* Reserved */
5360	pc.buffer[3] = 0;	/* Block Descriptor Length */
5361	pc.buffer[4 + 0] = 0x36 | (1 << 7);
5362	pc.buffer[4 + 1] = 6;
5363	pc.buffer[4 + 2] = vendor[0];
5364	pc.buffer[4 + 3] = vendor[1];
5365	pc.buffer[4 + 4] = vendor[2];
5366	pc.buffer[4 + 5] = vendor[3];
5367	pc.buffer[4 + 6] = 0;
5368	pc.buffer[4 + 7] = 0;
5369	if (idetape_queue_pc_tail (drive, &pc))
5370		printk (KERN_ERR "ide-tape: Couldn't set vendor name to %s\n", vendor);
5371
5372}
5373
5374/*
5375 * Various unused OnStream commands
5376 */
5377#if ONSTREAM_DEBUG
5378static void idetape_onstream_set_retries (ide_drive_t *drive, int retries)
5379{
5380	idetape_pc_t pc;
5381
5382	idetape_create_mode_select_cmd(&pc, sizeof(idetape_mode_parameter_header_t) + 4);
5383	pc.buffer[0] = 3 + 4;
5384	pc.buffer[1] = 0;	/* Medium Type - ignoring */
5385	pc.buffer[2] = 0;	/* Reserved */
5386	pc.buffer[3] = 0;	/* Block Descriptor Length */
5387	pc.buffer[4 + 0] = 0x2f | (1 << 7);
5388	pc.buffer[4 + 1] = 2;
5389	pc.buffer[4 + 2] = 4;
5390	pc.buffer[4 + 3] = retries;
5391	if (idetape_queue_pc_tail (drive, &pc))
5392		printk (KERN_ERR "ide-tape: Couldn't set retries to %d\n", retries);
5393}
5394#endif
5395
5396/*
5397 * Configure 32.5KB block size.
5398 */
5399static void idetape_onstream_configure_block_size (ide_drive_t *drive)
5400{
5401	idetape_pc_t pc;
5402	idetape_mode_parameter_header_t *header;
5403	idetape_block_size_page_t *bs;
5404
5405	/*
5406	 * Get the current block size from the block size mode page
5407	 */
5408	idetape_create_mode_sense_cmd (&pc, IDETAPE_BLOCK_SIZE_PAGE);
5409	if (idetape_queue_pc_tail (drive, &pc))
5410		printk (KERN_ERR "ide-tape: can't get tape block size mode page\n");
5411	header = (idetape_mode_parameter_header_t *) pc.buffer;
5412	bs = (idetape_block_size_page_t *) (pc.buffer + sizeof(idetape_mode_parameter_header_t) + header->bdl);
5413
5414#if IDETAPE_DEBUG_INFO
5415	printk(KERN_INFO "ide-tape: 32KB play back: %s\n", bs->play32 ? "Yes" : "No");
5416	printk(KERN_INFO "ide-tape: 32.5KB play back: %s\n", bs->play32_5 ? "Yes" : "No");
5417	printk(KERN_INFO "ide-tape: 32KB record: %s\n", bs->record32 ? "Yes" : "No");
5418	printk(KERN_INFO "ide-tape: 32.5KB record: %s\n", bs->record32_5 ? "Yes" : "No");
5419#endif /* IDETAPE_DEBUG_INFO */
5420
5421	/*
5422	 * Configure default auto columns mode, 32.5KB block size
5423	 */
5424	bs->one = 1;
5425	bs->play32 = 0;
5426	bs->play32_5 = 1;
5427	bs->record32 = 0;
5428	bs->record32_5 = 1;
5429	idetape_create_mode_select_cmd(&pc, sizeof(*header) + sizeof(*bs));
5430	if (idetape_queue_pc_tail (drive, &pc))
5431		printk (KERN_ERR "ide-tape: Couldn't set tape block size mode page\n");
5432
5433#if ONSTREAM_DEBUG
5434	/*
5435	 * In debug mode, we want to see as many errors as possible
5436	 * to test the error recovery mechanism.
5437	 */
5438	idetape_onstream_set_retries(drive, 0);
5439#endif
5440}
5441
5442/*
5443 * Use INQUIRY to get the firmware revision
5444 */
5445static void idetape_get_inquiry_results (ide_drive_t *drive)
5446{
5447	char *r;
5448	idetape_tape_t *tape = drive->driver_data;
5449	idetape_pc_t pc;
5450	idetape_inquiry_result_t *inquiry;
5451
5452	idetape_create_inquiry_cmd(&pc);
5453	if (idetape_queue_pc_tail (drive, &pc)) {
5454		printk (KERN_ERR "ide-tape: %s: can't get INQUIRY results\n", tape->name);
5455		return;
5456	}
5457	inquiry = (idetape_inquiry_result_t *) pc.buffer;
5458	memcpy(tape->vendor_id, inquiry->vendor_id, 8);
5459	memcpy(tape->product_id, inquiry->product_id, 16);
5460	memcpy(tape->firmware_revision, inquiry->revision_level, 4);
5461	ide_fixstring(tape->vendor_id, 10, 0);
5462	ide_fixstring(tape->product_id, 18, 0);
5463	ide_fixstring(tape->firmware_revision, 6, 0);
5464	r = tape->firmware_revision;
5465	if (*(r + 1) == '.')
5466		tape->firmware_revision_num = (*r - '0') * 100 + (*(r + 2) - '0') * 10 + *(r + 3) - '0';
5467	else if (tape->onstream)
5468		tape->firmware_revision_num = (*r - '0') * 100 + (*(r + 1) - '0') * 10 + *(r + 2) - '0';
5469	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);
5470}
5471
5472/*
5473 * Configure the OnStream ATAPI tape drive for default operation
5474 */
5475static void idetape_configure_onstream (ide_drive_t *drive)
5476{
5477	idetape_tape_t *tape = drive->driver_data;
5478
5479	if (tape->firmware_revision_num < 105) {
5480		printk(KERN_INFO "ide-tape: %s: Old OnStream firmware revision detected (%s)\n", tape->name, tape->firmware_revision);
5481		printk(KERN_INFO "ide-tape: %s: An upgrade to version 1.05 or above is recommended\n", tape->name);
5482	}
5483
5484	/*
5485	 * Configure 32.5KB (data+aux) block size.
5486	 */
5487	idetape_onstream_configure_block_size(drive);
5488
5489	/*
5490	 * Set vendor name to 'LIN3' for "Linux support version 3".
5491	 */
5492	idetape_onstream_set_vendor(drive, "LIN3");
5493}
5494
5495/*
5496 *	idetape_get_mode_sense_parameters asks the tape about its various
5497 *	parameters. This may work for other drives to???
5498 */
5499static void idetape_onstream_mode_sense_tape_parameter_page(ide_drive_t *drive, int debug)
5500{
5501	idetape_tape_t *tape = drive->driver_data;
5502	idetape_pc_t pc;
5503	idetape_mode_parameter_header_t *header;
5504	onstream_tape_paramtr_page_t *prm;
5505
5506	idetape_create_mode_sense_cmd (&pc, IDETAPE_PARAMTR_PAGE);
5507	if (idetape_queue_pc_tail (drive, &pc)) {
5508		printk (KERN_ERR "ide-tape: Can't get tape parameters page - probably no tape inserted in onstream drive\n");
5509		return;
5510	}
5511	header = (idetape_mode_parameter_header_t *) pc.buffer;
5512	prm = (onstream_tape_paramtr_page_t *) (pc.buffer + sizeof(idetape_mode_parameter_header_t) + header->bdl);
5513
5514        tape->capacity = ntohs(prm->segtrk) * ntohs(prm->trks);
5515        if (debug) {
5516	    printk (KERN_INFO "ide-tape: %s <-> %s: Tape length %dMB (%d frames/track, %d tracks = %d blocks, density: %dKbpi)\n",
5517               drive->name, tape->name, tape->capacity/32, ntohs(prm->segtrk), ntohs(prm->trks), tape->capacity, prm->density);
5518        }
5519
5520        return;
5521}
5522
5523/*
5524 *	idetape_get_mode_sense_results asks the tape about its various
5525 *	parameters. In particular, we will adjust our data transfer buffer
5526 *	size to the recommended value as returned by the tape.
5527 */
5528static void idetape_get_mode_sense_results (ide_drive_t *drive)
5529{
5530	idetape_tape_t *tape = drive->driver_data;
5531	idetape_pc_t pc;
5532	idetape_mode_parameter_header_t *header;
5533	idetape_capabilities_page_t *capabilities;
5534
5535	idetape_create_mode_sense_cmd (&pc, IDETAPE_CAPABILITIES_PAGE);
5536	if (idetape_queue_pc_tail (drive, &pc)) {
5537		printk (KERN_ERR "ide-tape: Can't get tape parameters - assuming some default values\n");
5538		tape->tape_block_size = 512; tape->capabilities.ctl = 52;
5539		tape->capabilities.speed = 450; tape->capabilities.buffer_size = 6 * 52;
5540		return;
5541	}
5542	header = (idetape_mode_parameter_header_t *) pc.buffer;
5543	capabilities = (idetape_capabilities_page_t *) (pc.buffer + sizeof(idetape_mode_parameter_header_t) + header->bdl);
5544
5545	capabilities->max_speed = ntohs (capabilities->max_speed);
5546	capabilities->ctl = ntohs (capabilities->ctl);
5547	capabilities->speed = ntohs (capabilities->speed);
5548	capabilities->buffer_size = ntohs (capabilities->buffer_size);
5549
5550	if (!capabilities->speed) {
5551		printk(KERN_INFO "ide-tape: %s: overriding capabilities->speed (assuming 650KB/sec)\n", drive->name);
5552		capabilities->speed = 650;
5553	}
5554	if (!capabilities->max_speed) {
5555		printk(KERN_INFO "ide-tape: %s: overriding capabilities->max_speed (assuming 650KB/sec)\n", drive->name);
5556		capabilities->max_speed = 650;
5557	}
5558
5559	tape->capabilities = *capabilities;		/* Save us a copy */
5560	if (capabilities->blk512)
5561		tape->tape_block_size = 512;
5562	else if (capabilities->blk1024)
5563		tape->tape_block_size = 1024;
5564	else if (tape->onstream && capabilities->blk32768)
5565		tape->tape_block_size = 32768;
5566
5567#if IDETAPE_DEBUG_INFO
5568	printk (KERN_INFO "ide-tape: Dumping the results of the MODE SENSE packet command\n");
5569	printk (KERN_INFO "ide-tape: Mode Parameter Header:\n");
5570	printk (KERN_INFO "ide-tape: Mode Data Length - %d\n",header->mode_data_length);
5571	printk (KERN_INFO "ide-tape: Medium Type - %d\n",header->medium_type);
5572	printk (KERN_INFO "ide-tape: Device Specific Parameter - %d\n",header->dsp);
5573	printk (KERN_INFO "ide-tape: Block Descriptor Length - %d\n",header->bdl);
5574
5575	printk (KERN_INFO "ide-tape: Capabilities and Mechanical Status Page:\n");
5576	printk (KERN_INFO "ide-tape: Page code - %d\n",capabilities->page_code);
5577	printk (KERN_INFO "ide-tape: Page length - %d\n",capabilities->page_length);
5578	printk (KERN_INFO "ide-tape: Read only - %s\n",capabilities->ro ? "Yes":"No");
5579	printk (KERN_INFO "ide-tape: Supports reverse space - %s\n",capabilities->sprev ? "Yes":"No");
5580	printk (KERN_INFO "ide-tape: Supports erase initiated formatting - %s\n",capabilities->efmt ? "Yes":"No");
5581	printk (KERN_INFO "ide-tape: Supports QFA two Partition format - %s\n",capabilities->qfa ? "Yes":"No");
5582	printk (KERN_INFO "ide-tape: Supports locking the medium - %s\n",capabilities->lock ? "Yes":"No");
5583	printk (KERN_INFO "ide-tape: The volume is currently locked - %s\n",capabilities->locked ? "Yes":"No");
5584	printk (KERN_INFO "ide-tape: The device defaults in the prevent state - %s\n",capabilities->prevent ? "Yes":"No");
5585	printk (KERN_INFO "ide-tape: Supports ejecting the medium - %s\n",capabilities->eject ? "Yes":"No");
5586	printk (KERN_INFO "ide-tape: Supports error correction - %s\n",capabilities->ecc ? "Yes":"No");
5587	printk (KERN_INFO "ide-tape: Supports data compression - %s\n",capabilities->cmprs ? "Yes":"No");
5588	printk (KERN_INFO "ide-tape: Supports 512 bytes block size - %s\n",capabilities->blk512 ? "Yes":"No");
5589	printk (KERN_INFO "ide-tape: Supports 1024 bytes block size - %s\n",capabilities->blk1024 ? "Yes":"No");
5590	printk (KERN_INFO "ide-tape: Supports 32768 bytes block size / Restricted byte count for PIO transfers - %s\n",capabilities->blk32768 ? "Yes":"No");
5591	printk (KERN_INFO "ide-tape: Maximum supported speed in KBps - %d\n",capabilities->max_speed);
5592	printk (KERN_INFO "ide-tape: Continuous transfer limits in blocks - %d\n",capabilities->ctl);
5593	printk (KERN_INFO "ide-tape: Current speed in KBps - %d\n",capabilities->speed);
5594	printk (KERN_INFO "ide-tape: Buffer size - %d\n",capabilities->buffer_size*512);
5595#endif /* IDETAPE_DEBUG_INFO */
5596}
5597
5598/*
5599 *	ide_get_blocksize_from_block_descriptor does a mode sense page 0 with block descriptor
5600 *	and if it succeeds sets the tape block size with the reported value
5601 */
5602static void idetape_get_blocksize_from_block_descriptor(ide_drive_t *drive)
5603{
5604
5605	idetape_tape_t *tape = drive->driver_data;
5606	idetape_pc_t pc;
5607	idetape_mode_parameter_header_t *header;
5608	idetape_parameter_block_descriptor_t *block_descrp;
5609
5610	idetape_create_mode_sense_cmd (&pc, IDETAPE_BLOCK_DESCRIPTOR);
5611	if (idetape_queue_pc_tail (drive, &pc)) {
5612		printk (KERN_ERR "ide-tape: Can't get block descriptor\n");
5613		if (tape->tape_block_size == 0) {
5614			printk(KERN_WARNING "ide-tape: Cannot deal with zero block size, assume 32k\n");
5615			tape->tape_block_size =  32768;
5616		}
5617		return;
5618	}
5619	header = (idetape_mode_parameter_header_t *) pc.buffer;
5620	block_descrp = (idetape_parameter_block_descriptor_t *) (pc.buffer + sizeof(idetape_mode_parameter_header_t));
5621	tape->tape_block_size =( block_descrp->length[0]<<16) + (block_descrp->length[1]<<8) + block_descrp->length[2];
5622#if IDETAPE_DEBUG_INFO
5623	printk (KERN_INFO "ide-tape: Adjusted block size - %d\n", tape->tape_block_size);
5624#endif /* IDETAPE_DEBUG_INFO */
5625}
5626static void idetape_add_settings (ide_drive_t *drive)
5627{
5628	idetape_tape_t *tape = drive->driver_data;
5629
5630/*
5631 *			drive	setting name	read/write	ioctl	ioctl		data type	min			max			mul_factor			div_factor			data pointer				set function
5632 */
5633	ide_add_setting(drive,	"buffer",	SETTING_READ,	-1,	-1,		TYPE_SHORT,	0,			0xffff,			1,				2,				&tape->capabilities.buffer_size,	NULL);
5634	ide_add_setting(drive,	"pipeline_min",	SETTING_RW,	-1,	-1,		TYPE_INT,	2,			0xffff,			tape->stage_size / 1024,	1,				&tape->min_pipeline,			NULL);
5635	ide_add_setting(drive,	"pipeline",	SETTING_RW,	-1,	-1,		TYPE_INT,	2,			0xffff,			tape->stage_size / 1024,	1,				&tape->max_stages,			NULL);
5636	ide_add_setting(drive,	"pipeline_max",	SETTING_RW,	-1,	-1,		TYPE_INT,	2,			0xffff,			tape->stage_size / 1024,	1,				&tape->max_pipeline,			NULL);
5637	ide_add_setting(drive,	"pipeline_used",SETTING_READ,	-1,	-1,		TYPE_INT,	0,			0xffff,			tape->stage_size / 1024,	1,				&tape->nr_stages,			NULL);
5638	ide_add_setting(drive,	"pipeline_pending",SETTING_READ,-1,	-1,		TYPE_INT,	0,			0xffff,			tape->stage_size / 1024,	1,				&tape->nr_pending_stages,		NULL);
5639	ide_add_setting(drive,	"speed",	SETTING_READ,	-1,	-1,		TYPE_SHORT,	0,			0xffff,			1,				1,				&tape->capabilities.speed,		NULL);
5640	ide_add_setting(drive,	"stage",	SETTING_READ,	-1,	-1,		TYPE_INT,	0,			0xffff,			1,				1024,				&tape->stage_size,			NULL);
5641	ide_add_setting(drive,	"tdsc",		SETTING_RW,	-1,	-1,		TYPE_INT,	IDETAPE_DSC_RW_MIN,	IDETAPE_DSC_RW_MAX,	1000,				HZ,				&tape->best_dsc_rw_frequency,		NULL);
5642	ide_add_setting(drive,	"dsc_overlap",	SETTING_RW,	-1,	-1,		TYPE_BYTE,	0,			1,			1,				1,				&drive->dsc_overlap,			NULL);
5643	ide_add_setting(drive,	"pipeline_head_speed_c",SETTING_READ,	-1,	-1,	TYPE_INT,	0,			0xffff,			1,				1,				&tape->controlled_pipeline_head_speed,	NULL);
5644	ide_add_setting(drive,	"pipeline_head_speed_u",SETTING_READ,	-1,	-1,	TYPE_INT,	0,			0xffff,			1,				1,				&tape->uncontrolled_pipeline_head_speed,	NULL);
5645	ide_add_setting(drive,	"avg_speed",	SETTING_READ,	-1,	-1,		TYPE_INT,	0,			0xffff,			1,				1,				&tape->avg_speed,		NULL);
5646	ide_add_setting(drive,	"debug_level",SETTING_RW,	-1,	-1,		TYPE_INT,	0,			0xffff,			1,				1,				&tape->debug_level,		NULL);
5647	if (tape->onstream) {
5648		ide_add_setting(drive,	"cur_frames",	SETTING_READ,	-1,	-1,		TYPE_SHORT,	0,			0xffff,			1,				1,				&tape->cur_frames,		NULL);
5649		ide_add_setting(drive,	"max_frames",	SETTING_READ,	-1,	-1,		TYPE_SHORT,	0,			0xffff,			1,				1,				&tape->max_frames,		NULL);
5650		ide_add_setting(drive,	"insert_speed",	SETTING_READ,	-1,	-1,		TYPE_INT,	0,			0xffff,			1,				1,				&tape->insert_speed,		NULL);
5651		ide_add_setting(drive,	"speed_control",SETTING_RW,	-1,	-1,		TYPE_INT,	0,			0xffff,			1,				1,				&tape->speed_control,		NULL);
5652		ide_add_setting(drive,	"tape_still_time",SETTING_READ,	-1,	-1,		TYPE_INT,	0,			0xffff,			1,				1,				&tape->tape_still_time,		NULL);
5653		ide_add_setting(drive,	"max_insert_speed",SETTING_RW,	-1,	-1,		TYPE_INT,	0,			0xffff,			1,				1,				&tape->max_insert_speed,	NULL);
5654		ide_add_setting(drive,	"insert_size",	SETTING_READ,	-1,	-1,		TYPE_INT,	0,			0xffff,			1,				1,				&tape->insert_size,		NULL);
5655		ide_add_setting(drive,	"capacity",	SETTING_READ,	-1,	-1,		TYPE_INT,	0,			0xffff,			1,				1,				&tape->capacity,		NULL);
5656		ide_add_setting(drive,	"first_frame",	SETTING_READ,	-1,	-1,		TYPE_INT,	0,			0xffff,			1,				1,				&tape->first_frame_position,		NULL);
5657		ide_add_setting(drive,	"logical_blk",	SETTING_READ,	-1,	-1,		TYPE_INT,	0,			0xffff,			1,				1,				&tape->logical_blk_num,		NULL);
5658	}
5659}
5660
5661/*
5662 *	ide_setup is called to:
5663 *
5664 *		1.	Initialize our various state variables.
5665 *		2.	Ask the tape for its capabilities.
5666 *		3.	Allocate a buffer which will be used for data
5667 *			transfer. The buffer size is chosen based on
5668 *			the recommendation which we received in step (2).
5669 *
5670 *	Note that at this point ide.c already assigned us an irq, so that
5671 *	we can queue requests here and wait for their completion.
5672 */
5673static void idetape_setup (ide_drive_t *drive, idetape_tape_t *tape, int minor)
5674{
5675	unsigned long t1, tmid, tn, t;
5676	int speed;
5677	struct idetape_id_gcw gcw;
5678	int stage_size;
5679	struct sysinfo si;
5680
5681	memset (tape, 0, sizeof (idetape_tape_t));
5682	spin_lock_init(&tape->spinlock);
5683	drive->driver_data = tape;
5684	drive->ready_stat = 0;			/* An ATAPI device ignores DRDY */
5685	if (strstr(drive->id->model, "OnStream DI-"))
5686		tape->onstream = 1;
5687	drive->dsc_overlap = 1;
5688#ifdef CONFIG_BLK_DEV_IDEPCI
5689	if (!tape->onstream && HWIF(drive)->pci_dev != NULL) {
5690		/*
5691		 * These two ide-pci host adapters appear to need DSC overlap disabled.
5692		 * This probably needs further analysis.
5693		 */
5694		if ((HWIF(drive)->pci_dev->device == PCI_DEVICE_ID_ARTOP_ATP850UF) ||
5695		    (HWIF(drive)->pci_dev->device == PCI_DEVICE_ID_TTI_HPT343)) {
5696			printk(KERN_INFO "ide-tape: %s: disabling DSC overlap\n", tape->name);
5697		    	drive->dsc_overlap = 0;
5698		}
5699	}
5700#endif /* CONFIG_BLK_DEV_IDEPCI */
5701	tape->drive = drive;
5702	tape->minor = minor;
5703	tape->name[0] = 'h'; tape->name[1] = 't'; tape->name[2] = '0' + minor;
5704	tape->chrdev_direction = idetape_direction_none;
5705	tape->pc = tape->pc_stack;
5706	tape->max_insert_speed = 10000;
5707	tape->speed_control = 1;
5708	*((unsigned short *) &gcw) = drive->id->config;
5709	if (gcw.drq_type == 1)
5710		set_bit(IDETAPE_DRQ_INTERRUPT, &tape->flags);
5711
5712	tape->min_pipeline = tape->max_pipeline = tape->max_stages = 10;
5713
5714	idetape_get_inquiry_results(drive);
5715	idetape_get_mode_sense_results(drive);
5716	idetape_get_blocksize_from_block_descriptor(drive);
5717	if (tape->onstream) {
5718		idetape_onstream_mode_sense_tape_parameter_page(drive, 1);
5719		idetape_configure_onstream(drive);
5720	}
5721	tape->user_bs_factor = 1;
5722	tape->stage_size = tape->capabilities.ctl * tape->tape_block_size;
5723	while (tape->stage_size > 0xffff) {
5724		printk (KERN_NOTICE "ide-tape: decreasing stage size\n");
5725		tape->capabilities.ctl /= 2;
5726		tape->stage_size = tape->capabilities.ctl * tape->tape_block_size;
5727	}
5728	stage_size = tape->stage_size;
5729	if (tape->onstream)
5730		stage_size = 32768 + 512;
5731	tape->pages_per_stage = stage_size / PAGE_SIZE;
5732	if (stage_size % PAGE_SIZE) {
5733		tape->pages_per_stage++;
5734		tape->excess_bh_size = PAGE_SIZE - stage_size % PAGE_SIZE;
5735	}
5736
5737	/*
5738	 *	Select the "best" DSC read/write polling frequency
5739	 *	and pipeline size.
5740	 */
5741	speed = IDE_MAX (tape->capabilities.speed, tape->capabilities.max_speed);
5742
5743	tape->max_stages = speed * 1000 * 10 / tape->stage_size;
5744
5745	/*
5746	 * 	Limit memory use for pipeline to 10% of physical memory
5747	 */
5748	si_meminfo(&si);
5749	if ( tape->max_stages * tape->stage_size > si.totalram * si.mem_unit / 10)
5750		tape->max_stages = si.totalram * si.mem_unit / (10 * tape->stage_size);
5751	tape->min_pipeline = tape->max_stages;
5752	tape->max_pipeline = tape->max_stages * 2;
5753
5754	t1 = (tape->stage_size * HZ) / (speed * 1000);
5755	tmid = (tape->capabilities.buffer_size * 32 * HZ) / (speed * 125);
5756	tn = (IDETAPE_FIFO_THRESHOLD * tape->stage_size * HZ) / (speed * 1000);
5757
5758	if (tape->max_stages)
5759		t = tn;
5760	else
5761		t = t1;
5762
5763	/*
5764	 *	Ensure that the number we got makes sense; limit
5765	 *	it within IDETAPE_DSC_RW_MIN and IDETAPE_DSC_RW_MAX.
5766	 */
5767	tape->best_dsc_rw_frequency = IDE_MAX (IDE_MIN (t, IDETAPE_DSC_RW_MAX), IDETAPE_DSC_RW_MIN);
5768	printk (KERN_INFO "ide-tape: %s <-> %s: %dKBps, %d*%dkB buffer, %dkB pipeline, %lums tDSC%s\n",
5769		drive->name, tape->name, tape->capabilities.speed, (tape->capabilities.buffer_size * 512) / tape->stage_size,
5770		tape->stage_size / 1024, tape->max_stages * tape->stage_size / 1024,
5771		tape->best_dsc_rw_frequency * 1000 / HZ, drive->using_dma ? ", DMA":"");
5772
5773	idetape_add_settings(drive);
5774}
5775
5776static int idetape_cleanup (ide_drive_t *drive)
5777{
5778	idetape_tape_t *tape = drive->driver_data;
5779	int minor = tape->minor;
5780	unsigned long flags;
5781
5782	save_flags (flags);	/* all CPUs (overkill?) */
5783	cli();			/* all CPUs (overkill?) */
5784	if (test_bit (IDETAPE_BUSY, &tape->flags) || tape->first_stage != NULL || tape->merge_stage_size || drive->usage) {
5785		restore_flags(flags);	/* all CPUs (overkill?) */
5786		return 1;
5787	}
5788	idetape_chrdevs[minor].drive = NULL;
5789	restore_flags (flags);	/* all CPUs (overkill?) */
5790	DRIVER(drive)->busy = 0;
5791	(void) ide_unregister_subdriver (drive);
5792	drive->driver_data = NULL;
5793	devfs_unregister (tape->de_r);
5794	devfs_unregister (tape->de_n);
5795	kfree (tape);
5796	for (minor = 0; minor < MAX_HWIFS * MAX_DRIVES; minor++)
5797		if (idetape_chrdevs[minor].drive != NULL)
5798			return 0;
5799	devfs_unregister_chrdev (IDETAPE_MAJOR, "ht");
5800	idetape_chrdev_present = 0;
5801	return 0;
5802}
5803
5804#ifdef CONFIG_PROC_FS
5805
5806static int proc_idetape_read_name
5807	(char *page, char **start, off_t off, int count, int *eof, void *data)
5808{
5809	ide_drive_t	*drive = (ide_drive_t *) data;
5810	idetape_tape_t	*tape = drive->driver_data;
5811	char		*out = page;
5812	int		len;
5813
5814	len = sprintf(out, "%s\n", tape->name);
5815	PROC_IDE_READ_RETURN(page, start, off, count, eof, len);
5816}
5817
5818static ide_proc_entry_t idetape_proc[] = {
5819	{ "name",	S_IFREG|S_IRUGO,	proc_idetape_read_name,	NULL },
5820	{ NULL, 0, NULL, NULL }
5821};
5822
5823#else
5824
5825#define	idetape_proc	NULL
5826
5827#endif
5828
5829int idetape_reinit(ide_drive_t *drive);
5830
5831/*
5832 *	IDE subdriver functions, registered with ide.c
5833 */
5834static ide_driver_t idetape_driver = {
5835	name:			"ide-tape",
5836	version:		IDETAPE_VERSION,
5837	media:			ide_tape,
5838	busy:			1,
5839	supports_dma:		1,
5840	supports_dsc_overlap: 	1,
5841	cleanup:		idetape_cleanup,
5842	standby:		NULL,
5843	flushcache:		NULL,
5844	do_request:		idetape_do_request,
5845	end_request:		idetape_end_request,
5846	ioctl:			idetape_blkdev_ioctl,
5847	open:			idetape_blkdev_open,
5848	release:		idetape_blkdev_release,
5849	media_change:		NULL,
5850	revalidate:		NULL,
5851	pre_reset:		idetape_pre_reset,
5852	capacity:		NULL,
5853	proc:			idetape_proc,
5854	reinit:			idetape_reinit,
5855	ata_prebuilder:		NULL,
5856	atapi_prebuilder:	NULL,
5857};
5858
5859int idetape_init (void);
5860static ide_module_t idetape_module = {
5861	IDE_DRIVER_MODULE,
5862	idetape_init,
5863	&idetape_driver,
5864	NULL
5865};
5866
5867/*
5868 *	Our character device supporting functions, passed to register_chrdev.
5869 */
5870static struct file_operations idetape_fops = {
5871	owner:		THIS_MODULE,
5872	read:		idetape_chrdev_read,
5873	write:		idetape_chrdev_write,
5874	ioctl:		idetape_chrdev_ioctl,
5875	open:		idetape_chrdev_open,
5876	release:	idetape_chrdev_release,
5877};
5878
5879int idetape_reinit (ide_drive_t *drive)
5880{
5881	return 1;
5882}
5883
5884MODULE_DESCRIPTION("ATAPI Streaming TAPE Driver");
5885MODULE_LICENSE("GPL");
5886
5887static void __exit idetape_exit (void)
5888{
5889	ide_drive_t *drive;
5890	int minor;
5891
5892	for (minor = 0; minor < MAX_HWIFS * MAX_DRIVES; minor++) {
5893		drive = idetape_chrdevs[minor].drive;
5894		if (drive != NULL && idetape_cleanup (drive))
5895		printk (KERN_ERR "ide-tape: %s: cleanup_module() called while still busy\n", drive->name);
5896	}
5897	ide_unregister_module(&idetape_module);
5898}
5899
5900/*
5901 *	idetape_init will register the driver for each tape.
5902 */
5903int idetape_init (void)
5904{
5905	ide_drive_t *drive;
5906	idetape_tape_t *tape;
5907	int minor, failed = 0, supported = 0;
5908/* DRIVER(drive)->busy++; */
5909	MOD_INC_USE_COUNT;
5910#if ONSTREAM_DEBUG
5911        printk(KERN_INFO "ide-tape: MOD_INC_USE_COUNT in idetape_init\n");
5912#endif
5913	if (!idetape_chrdev_present)
5914		for (minor = 0; minor < MAX_HWIFS * MAX_DRIVES; minor++ )
5915			idetape_chrdevs[minor].drive = NULL;
5916
5917	if ((drive = ide_scan_devices (ide_tape, idetape_driver.name, NULL, failed++)) == NULL) {
5918		ide_register_module (&idetape_module);
5919		MOD_DEC_USE_COUNT;
5920#if ONSTREAM_DEBUG
5921		printk(KERN_INFO "ide-tape: MOD_DEC_USE_COUNT in idetape_init\n");
5922#endif
5923		return 0;
5924	}
5925	if (!idetape_chrdev_present &&
5926	    devfs_register_chrdev (IDETAPE_MAJOR, "ht", &idetape_fops)) {
5927		printk (KERN_ERR "ide-tape: Failed to register character device interface\n");
5928		MOD_DEC_USE_COUNT;
5929#if ONSTREAM_DEBUG
5930		printk(KERN_INFO "ide-tape: MOD_DEC_USE_COUNT in idetape_init\n");
5931#endif
5932		return -EBUSY;
5933	}
5934	do {
5935		if (!idetape_identify_device (drive, drive->id)) {
5936			printk (KERN_ERR "ide-tape: %s: not supported by this version of ide-tape\n", drive->name);
5937			continue;
5938		}
5939		if (drive->scsi) {
5940			if (strstr(drive->id->model, "OnStream DI-")) {
5941				printk("ide-tape: ide-scsi emulation is not supported for %s.\n", drive->id->model);
5942			} else {
5943				printk("ide-tape: passing drive %s to ide-scsi emulation.\n", drive->name);
5944				continue;
5945			}
5946		}
5947		tape = (idetape_tape_t *) kmalloc (sizeof (idetape_tape_t), GFP_KERNEL);
5948		if (tape == NULL) {
5949			printk (KERN_ERR "ide-tape: %s: Can't allocate a tape structure\n", drive->name);
5950			continue;
5951		}
5952		if (ide_register_subdriver (drive, &idetape_driver, IDE_SUBDRIVER_VERSION)) {
5953			printk (KERN_ERR "ide-tape: %s: Failed to register the driver with ide.c\n", drive->name);
5954			kfree (tape);
5955			continue;
5956		}
5957		for (minor = 0; idetape_chrdevs[minor].drive != NULL; minor++);
5958		idetape_setup (drive, tape, minor);
5959		idetape_chrdevs[minor].drive = drive;
5960		tape->de_r =
5961		    devfs_register (drive->de, "mt", DEVFS_FL_DEFAULT,
5962				    HWIF(drive)->major, minor,
5963				    S_IFCHR | S_IRUGO | S_IWUGO,
5964				    &idetape_fops, NULL);
5965		tape->de_n =
5966		    devfs_register (drive->de, "mtn", DEVFS_FL_DEFAULT,
5967				    HWIF(drive)->major, minor + 128,
5968				    S_IFCHR | S_IRUGO | S_IWUGO,
5969				    &idetape_fops, NULL);
5970		devfs_register_tape (tape->de_r);
5971		supported++; failed--;
5972	} while ((drive = ide_scan_devices (ide_tape, idetape_driver.name, NULL, failed++)) != NULL);
5973	if (!idetape_chrdev_present && !supported) {
5974		devfs_unregister_chrdev (IDETAPE_MAJOR, "ht");
5975	} else
5976		idetape_chrdev_present = 1;
5977	ide_register_module (&idetape_module);
5978	MOD_DEC_USE_COUNT;
5979#if ONSTREAM_DEBUG
5980	printk(KERN_INFO "ide-tape: MOD_DEC_USE_COUNT in idetape_init\n");
5981#endif
5982	return 0;
5983}
5984
5985module_init(idetape_init);
5986module_exit(idetape_exit);
5987