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