ide-tape.c revision 67c56364df843fb9e3ed1af014b8fbe4b22ff25d
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 DRV_NAME "ide-tape"
19
20#define IDETAPE_VERSION "1.20"
21
22#include <linux/module.h>
23#include <linux/types.h>
24#include <linux/string.h>
25#include <linux/kernel.h>
26#include <linux/delay.h>
27#include <linux/timer.h>
28#include <linux/mm.h>
29#include <linux/interrupt.h>
30#include <linux/jiffies.h>
31#include <linux/major.h>
32#include <linux/errno.h>
33#include <linux/genhd.h>
34#include <linux/slab.h>
35#include <linux/pci.h>
36#include <linux/ide.h>
37#include <linux/smp_lock.h>
38#include <linux/completion.h>
39#include <linux/bitops.h>
40#include <linux/mutex.h>
41#include <scsi/scsi.h>
42
43#include <asm/byteorder.h>
44#include <linux/irq.h>
45#include <linux/uaccess.h>
46#include <linux/io.h>
47#include <asm/unaligned.h>
48#include <linux/mtio.h>
49
50enum {
51	/* output errors only */
52	DBG_ERR =		(1 << 0),
53	/* output all sense key/asc */
54	DBG_SENSE =		(1 << 1),
55	/* info regarding all chrdev-related procedures */
56	DBG_CHRDEV =		(1 << 2),
57	/* all remaining procedures */
58	DBG_PROCS =		(1 << 3),
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 * After each failed packet command we issue a request sense command and retry
77 * the packet command IDETAPE_MAX_PC_RETRIES times.
78 *
79 * Setting IDETAPE_MAX_PC_RETRIES to 0 will disable retries.
80 */
81#define IDETAPE_MAX_PC_RETRIES		3
82
83/*
84 * The following parameter is used to select the point in the internal tape fifo
85 * in which we will start to refill the buffer. Decreasing the following
86 * parameter will improve the system's latency and interactive response, while
87 * using a high value might improve system throughput.
88 */
89#define IDETAPE_FIFO_THRESHOLD		2
90
91/*
92 * DSC polling parameters.
93 *
94 * Polling for DSC (a single bit in the status register) is a very important
95 * function in ide-tape. There are two cases in which we poll for DSC:
96 *
97 * 1. Before a read/write packet command, to ensure that we can transfer data
98 * from/to the tape's data buffers, without causing an actual media access.
99 * In case the tape is not ready yet, we take out our request from the device
100 * request queue, so that ide.c could service requests from the other device
101 * on the same interface in the meantime.
102 *
103 * 2. After the successful initialization of a "media access packet command",
104 * which is a command that can take a long time to complete (the interval can
105 * range from several seconds to even an hour). Again, we postpone our request
106 * in the middle to free the bus for the other device. The polling frequency
107 * here should be lower than the read/write frequency since those media access
108 * commands are slow. We start from a "fast" frequency - IDETAPE_DSC_MA_FAST
109 * (1 second), and if we don't receive DSC after IDETAPE_DSC_MA_THRESHOLD
110 * (5 min), we switch it to a lower frequency - IDETAPE_DSC_MA_SLOW (1 min).
111 *
112 * We also set a timeout for the timer, in case something goes wrong. The
113 * timeout should be longer then the maximum execution time of a tape operation.
114 */
115
116/* DSC timings. */
117#define IDETAPE_DSC_RW_MIN		5*HZ/100	/* 50 msec */
118#define IDETAPE_DSC_RW_MAX		40*HZ/100	/* 400 msec */
119#define IDETAPE_DSC_RW_TIMEOUT		2*60*HZ		/* 2 minutes */
120#define IDETAPE_DSC_MA_FAST		2*HZ		/* 2 seconds */
121#define IDETAPE_DSC_MA_THRESHOLD	5*60*HZ		/* 5 minutes */
122#define IDETAPE_DSC_MA_SLOW		30*HZ		/* 30 seconds */
123#define IDETAPE_DSC_MA_TIMEOUT		2*60*60*HZ	/* 2 hours */
124
125/*************************** End of tunable parameters ***********************/
126
127/* tape directions */
128enum {
129	IDETAPE_DIR_NONE  = (1 << 0),
130	IDETAPE_DIR_READ  = (1 << 1),
131	IDETAPE_DIR_WRITE = (1 << 2),
132};
133
134struct idetape_bh {
135	u32 b_size;
136	atomic_t b_count;
137	struct idetape_bh *b_reqnext;
138	char *b_data;
139};
140
141/* Tape door status */
142#define DOOR_UNLOCKED			0
143#define DOOR_LOCKED			1
144#define DOOR_EXPLICITLY_LOCKED		2
145
146/* Some defines for the SPACE command */
147#define IDETAPE_SPACE_OVER_FILEMARK	1
148#define IDETAPE_SPACE_TO_EOD		3
149
150/* Some defines for the LOAD UNLOAD command */
151#define IDETAPE_LU_LOAD_MASK		1
152#define IDETAPE_LU_RETENSION_MASK	2
153#define IDETAPE_LU_EOT_MASK		4
154
155/* Error codes returned in rq->errors to the higher part of the driver. */
156#define IDETAPE_ERROR_GENERAL		101
157#define IDETAPE_ERROR_FILEMARK		102
158#define IDETAPE_ERROR_EOD		103
159
160/* Structures related to the SELECT SENSE / MODE SENSE packet commands. */
161#define IDETAPE_BLOCK_DESCRIPTOR	0
162#define IDETAPE_CAPABILITIES_PAGE	0x2a
163
164/*
165 * Most of our global data which we need to save even as we leave the driver due
166 * to an interrupt or a timer event is stored in the struct defined below.
167 */
168typedef struct ide_tape_obj {
169	ide_drive_t	*drive;
170	ide_driver_t	*driver;
171	struct gendisk	*disk;
172	struct kref	kref;
173
174	/*
175	 *	failed_pc points to the last failed packet command, or contains
176	 *	NULL if we do not need to retry any packet command. This is
177	 *	required since an additional packet command is needed before the
178	 *	retry, to get detailed information on what went wrong.
179	 */
180	/* Last failed packet command */
181	struct ide_atapi_pc *failed_pc;
182	/* used by REQ_IDETAPE_{READ,WRITE} requests */
183	struct ide_atapi_pc queued_pc;
184
185	/*
186	 * DSC polling variables.
187	 *
188	 * While polling for DSC we use postponed_rq to postpone the current
189	 * request so that ide.c will be able to service pending requests on the
190	 * other device. Note that at most we will have only one DSC (usually
191	 * data transfer) request in the device request queue.
192	 */
193	struct request *postponed_rq;
194	/* The time in which we started polling for DSC */
195	unsigned long dsc_polling_start;
196	/* Timer used to poll for dsc */
197	struct timer_list dsc_timer;
198	/* Read/Write dsc polling frequency */
199	unsigned long best_dsc_rw_freq;
200	unsigned long dsc_poll_freq;
201	unsigned long dsc_timeout;
202
203	/* Read position information */
204	u8 partition;
205	/* Current block */
206	unsigned int first_frame;
207
208	/* Last error information */
209	u8 sense_key, asc, ascq;
210
211	/* Character device operation */
212	unsigned int minor;
213	/* device name */
214	char name[4];
215	/* Current character device data transfer direction */
216	u8 chrdev_dir;
217
218	/* tape block size, usually 512 or 1024 bytes */
219	unsigned short blk_size;
220	int user_bs_factor;
221
222	/* Copy of the tape's Capabilities and Mechanical Page */
223	u8 caps[20];
224
225	/*
226	 * Active data transfer request parameters.
227	 *
228	 * At most, there is only one ide-tape originated data transfer request
229	 * in the device request queue. This allows ide.c to easily service
230	 * requests from the other device when we postpone our active request.
231	 */
232
233	/* Data buffer size chosen based on the tape's recommendation */
234	int buffer_size;
235	/* merge buffer */
236	struct idetape_bh *merge_bh;
237	/* size of the merge buffer */
238	int merge_bh_size;
239	/* pointer to current buffer head within the merge buffer */
240	struct idetape_bh *bh;
241	char *b_data;
242	int b_count;
243
244	int pages_per_buffer;
245	/* Wasted space in each stage */
246	int excess_bh_size;
247
248	/* protects the ide-tape queue */
249	spinlock_t lock;
250
251	/* Measures average tape speed */
252	unsigned long avg_time;
253	int avg_size;
254	int avg_speed;
255
256	/* the door is currently locked */
257	int door_locked;
258	/* the tape hardware is write protected */
259	char drv_write_prot;
260	/* the tape is write protected (hardware or opened as read-only) */
261	char write_prot;
262
263	u32 debug_mask;
264} idetape_tape_t;
265
266static DEFINE_MUTEX(idetape_ref_mutex);
267
268static struct class *idetape_sysfs_class;
269
270#define to_ide_tape(obj) container_of(obj, struct ide_tape_obj, kref)
271
272#define ide_tape_g(disk) \
273	container_of((disk)->private_data, struct ide_tape_obj, driver)
274
275static void ide_tape_release(struct kref *);
276
277static struct ide_tape_obj *ide_tape_get(struct gendisk *disk)
278{
279	struct ide_tape_obj *tape = NULL;
280
281	mutex_lock(&idetape_ref_mutex);
282	tape = ide_tape_g(disk);
283	if (tape) {
284		if (ide_device_get(tape->drive))
285			tape = NULL;
286		else
287			kref_get(&tape->kref);
288	}
289	mutex_unlock(&idetape_ref_mutex);
290	return tape;
291}
292
293static void ide_tape_put(struct ide_tape_obj *tape)
294{
295	ide_drive_t *drive = tape->drive;
296
297	mutex_lock(&idetape_ref_mutex);
298	kref_put(&tape->kref, ide_tape_release);
299	ide_device_put(drive);
300	mutex_unlock(&idetape_ref_mutex);
301}
302
303/*
304 * The variables below are used for the character device interface. Additional
305 * state variables are defined in our ide_drive_t structure.
306 */
307static struct ide_tape_obj *idetape_devs[MAX_HWIFS * MAX_DRIVES];
308
309#define ide_tape_f(file) ((file)->private_data)
310
311static struct ide_tape_obj *ide_tape_chrdev_get(unsigned int i)
312{
313	struct ide_tape_obj *tape = NULL;
314
315	mutex_lock(&idetape_ref_mutex);
316	tape = idetape_devs[i];
317	if (tape)
318		kref_get(&tape->kref);
319	mutex_unlock(&idetape_ref_mutex);
320	return tape;
321}
322
323static void idetape_input_buffers(ide_drive_t *drive, struct ide_atapi_pc *pc,
324				  unsigned int bcount)
325{
326	struct idetape_bh *bh = pc->bh;
327	int count;
328
329	while (bcount) {
330		if (bh == NULL) {
331			printk(KERN_ERR "ide-tape: bh == NULL in "
332				"idetape_input_buffers\n");
333			ide_pad_transfer(drive, 0, bcount);
334			return;
335		}
336		count = min(
337			(unsigned int)(bh->b_size - atomic_read(&bh->b_count)),
338			bcount);
339		drive->hwif->tp_ops->input_data(drive, NULL, bh->b_data +
340					atomic_read(&bh->b_count), count);
341		bcount -= count;
342		atomic_add(count, &bh->b_count);
343		if (atomic_read(&bh->b_count) == bh->b_size) {
344			bh = bh->b_reqnext;
345			if (bh)
346				atomic_set(&bh->b_count, 0);
347		}
348	}
349	pc->bh = bh;
350}
351
352static void idetape_output_buffers(ide_drive_t *drive, struct ide_atapi_pc *pc,
353				   unsigned int bcount)
354{
355	struct idetape_bh *bh = pc->bh;
356	int count;
357
358	while (bcount) {
359		if (bh == NULL) {
360			printk(KERN_ERR "ide-tape: bh == NULL in %s\n",
361					__func__);
362			return;
363		}
364		count = min((unsigned int)pc->b_count, (unsigned int)bcount);
365		drive->hwif->tp_ops->output_data(drive, NULL, pc->b_data, count);
366		bcount -= count;
367		pc->b_data += count;
368		pc->b_count -= count;
369		if (!pc->b_count) {
370			bh = bh->b_reqnext;
371			pc->bh = bh;
372			if (bh) {
373				pc->b_data = bh->b_data;
374				pc->b_count = atomic_read(&bh->b_count);
375			}
376		}
377	}
378}
379
380static void idetape_update_buffers(ide_drive_t *drive, struct ide_atapi_pc *pc)
381{
382	struct idetape_bh *bh = pc->bh;
383	int count;
384	unsigned int bcount = pc->xferred;
385
386	if (pc->flags & PC_FLAG_WRITING)
387		return;
388	while (bcount) {
389		if (bh == NULL) {
390			printk(KERN_ERR "ide-tape: bh == NULL in %s\n",
391					__func__);
392			return;
393		}
394		count = min((unsigned int)bh->b_size, (unsigned int)bcount);
395		atomic_set(&bh->b_count, count);
396		if (atomic_read(&bh->b_count) == bh->b_size)
397			bh = bh->b_reqnext;
398		bcount -= count;
399	}
400	pc->bh = bh;
401}
402
403/*
404 * called on each failed packet command retry to analyze the request sense. We
405 * currently do not utilize this information.
406 */
407static void idetape_analyze_error(ide_drive_t *drive, u8 *sense)
408{
409	idetape_tape_t *tape = drive->driver_data;
410	struct ide_atapi_pc *pc = tape->failed_pc;
411
412	tape->sense_key = sense[2] & 0xF;
413	tape->asc       = sense[12];
414	tape->ascq      = sense[13];
415
416	debug_log(DBG_ERR, "pc = %x, sense key = %x, asc = %x, ascq = %x\n",
417		 pc->c[0], tape->sense_key, tape->asc, tape->ascq);
418
419	/* Correct pc->xferred by asking the tape.	 */
420	if (pc->flags & PC_FLAG_DMA_ERROR) {
421		pc->xferred = pc->req_xfer -
422			tape->blk_size *
423			get_unaligned_be32(&sense[3]);
424		idetape_update_buffers(drive, pc);
425	}
426
427	/*
428	 * If error was the result of a zero-length read or write command,
429	 * with sense key=5, asc=0x22, ascq=0, let it slide.  Some drives
430	 * (i.e. Seagate STT3401A Travan) don't support 0-length read/writes.
431	 */
432	if ((pc->c[0] == READ_6 || pc->c[0] == WRITE_6)
433	    /* length == 0 */
434	    && pc->c[4] == 0 && pc->c[3] == 0 && pc->c[2] == 0) {
435		if (tape->sense_key == 5) {
436			/* don't report an error, everything's ok */
437			pc->error = 0;
438			/* don't retry read/write */
439			pc->flags |= PC_FLAG_ABORT;
440		}
441	}
442	if (pc->c[0] == READ_6 && (sense[2] & 0x80)) {
443		pc->error = IDETAPE_ERROR_FILEMARK;
444		pc->flags |= PC_FLAG_ABORT;
445	}
446	if (pc->c[0] == WRITE_6) {
447		if ((sense[2] & 0x40) || (tape->sense_key == 0xd
448		     && tape->asc == 0x0 && tape->ascq == 0x2)) {
449			pc->error = IDETAPE_ERROR_EOD;
450			pc->flags |= PC_FLAG_ABORT;
451		}
452	}
453	if (pc->c[0] == READ_6 || pc->c[0] == WRITE_6) {
454		if (tape->sense_key == 8) {
455			pc->error = IDETAPE_ERROR_EOD;
456			pc->flags |= PC_FLAG_ABORT;
457		}
458		if (!(pc->flags & PC_FLAG_ABORT) &&
459		    pc->xferred)
460			pc->retries = IDETAPE_MAX_PC_RETRIES + 1;
461	}
462}
463
464/* Free data buffers completely. */
465static void ide_tape_kfree_buffer(idetape_tape_t *tape)
466{
467	struct idetape_bh *prev_bh, *bh = tape->merge_bh;
468
469	while (bh) {
470		u32 size = bh->b_size;
471
472		while (size) {
473			unsigned int order = fls(size >> PAGE_SHIFT)-1;
474
475			if (bh->b_data)
476				free_pages((unsigned long)bh->b_data, order);
477
478			size &= (order-1);
479			bh->b_data += (1 << order) * PAGE_SIZE;
480		}
481		prev_bh = bh;
482		bh = bh->b_reqnext;
483		kfree(prev_bh);
484	}
485}
486
487static int idetape_end_request(ide_drive_t *drive, int uptodate, int nr_sects)
488{
489	struct request *rq = HWGROUP(drive)->rq;
490	idetape_tape_t *tape = drive->driver_data;
491	unsigned long flags;
492	int error;
493
494	debug_log(DBG_PROCS, "Enter %s\n", __func__);
495
496	switch (uptodate) {
497	case 0:	error = IDETAPE_ERROR_GENERAL; break;
498	case 1: error = 0; break;
499	default: error = uptodate;
500	}
501	rq->errors = error;
502	if (error)
503		tape->failed_pc = NULL;
504
505	if (!blk_special_request(rq)) {
506		ide_end_request(drive, uptodate, nr_sects);
507		return 0;
508	}
509
510	spin_lock_irqsave(&tape->lock, flags);
511
512	ide_end_drive_cmd(drive, 0, 0);
513
514	spin_unlock_irqrestore(&tape->lock, flags);
515	return 0;
516}
517
518static void ide_tape_handle_dsc(ide_drive_t *);
519
520static void ide_tape_callback(ide_drive_t *drive, int dsc)
521{
522	idetape_tape_t *tape = drive->driver_data;
523	struct ide_atapi_pc *pc = drive->pc;
524	int uptodate = pc->error ? 0 : 1;
525
526	debug_log(DBG_PROCS, "Enter %s\n", __func__);
527
528	if (dsc)
529		ide_tape_handle_dsc(drive);
530
531	if (tape->failed_pc == pc)
532		tape->failed_pc = NULL;
533
534	if (pc->c[0] == REQUEST_SENSE) {
535		if (uptodate)
536			idetape_analyze_error(drive, pc->buf);
537		else
538			printk(KERN_ERR "ide-tape: Error in REQUEST SENSE "
539					"itself - Aborting request!\n");
540	} else if (pc->c[0] == READ_6 || pc->c[0] == WRITE_6) {
541		struct request *rq = drive->hwif->hwgroup->rq;
542		int blocks = pc->xferred / tape->blk_size;
543
544		tape->avg_size += blocks * tape->blk_size;
545
546		if (time_after_eq(jiffies, tape->avg_time + HZ)) {
547			tape->avg_speed = tape->avg_size * HZ /
548				(jiffies - tape->avg_time) / 1024;
549			tape->avg_size = 0;
550			tape->avg_time = jiffies;
551		}
552
553		tape->first_frame += blocks;
554		rq->current_nr_sectors -= blocks;
555
556		if (pc->error)
557			uptodate = pc->error;
558	} else if (pc->c[0] == READ_POSITION && uptodate) {
559		u8 *readpos = pc->buf;
560
561		debug_log(DBG_SENSE, "BOP - %s\n",
562				(readpos[0] & 0x80) ? "Yes" : "No");
563		debug_log(DBG_SENSE, "EOP - %s\n",
564				(readpos[0] & 0x40) ? "Yes" : "No");
565
566		if (readpos[0] & 0x4) {
567			printk(KERN_INFO "ide-tape: Block location is unknown"
568					 "to the tape\n");
569			clear_bit(IDE_AFLAG_ADDRESS_VALID, &drive->atapi_flags);
570			uptodate = 0;
571		} else {
572			debug_log(DBG_SENSE, "Block Location - %u\n",
573					be32_to_cpup((__be32 *)&readpos[4]));
574
575			tape->partition = readpos[1];
576			tape->first_frame = be32_to_cpup((__be32 *)&readpos[4]);
577			set_bit(IDE_AFLAG_ADDRESS_VALID, &drive->atapi_flags);
578		}
579	}
580
581	idetape_end_request(drive, uptodate, 0);
582}
583
584static void idetape_create_request_sense_cmd(struct ide_atapi_pc *pc)
585{
586	ide_init_pc(pc);
587	pc->c[0] = REQUEST_SENSE;
588	pc->c[4] = 20;
589	pc->req_xfer = 20;
590}
591
592/*
593 *	idetape_retry_pc is called when an error was detected during the
594 *	last packet command. We queue a request sense packet command in
595 *	the head of the request list.
596 */
597static void idetape_retry_pc(ide_drive_t *drive)
598{
599	struct ide_tape_obj *tape = drive->driver_data;
600	struct request *rq = &drive->request_sense_rq;
601	struct ide_atapi_pc *pc = &drive->request_sense_pc;
602
603	(void)ide_read_error(drive);
604	idetape_create_request_sense_cmd(pc);
605	set_bit(IDE_AFLAG_IGNORE_DSC, &drive->atapi_flags);
606	ide_queue_pc_head(drive, tape->disk, pc, rq);
607}
608
609/*
610 * Postpone the current request so that ide.c will be able to service requests
611 * from another device on the same hwgroup while we are polling for DSC.
612 */
613static void idetape_postpone_request(ide_drive_t *drive)
614{
615	idetape_tape_t *tape = drive->driver_data;
616
617	debug_log(DBG_PROCS, "Enter %s\n", __func__);
618
619	tape->postponed_rq = HWGROUP(drive)->rq;
620	ide_stall_queue(drive, tape->dsc_poll_freq);
621}
622
623static void ide_tape_handle_dsc(ide_drive_t *drive)
624{
625	idetape_tape_t *tape = drive->driver_data;
626
627	/* Media access command */
628	tape->dsc_polling_start = jiffies;
629	tape->dsc_poll_freq = IDETAPE_DSC_MA_FAST;
630	tape->dsc_timeout = jiffies + IDETAPE_DSC_MA_TIMEOUT;
631	/* Allow ide.c to handle other requests */
632	idetape_postpone_request(drive);
633}
634
635static int ide_tape_io_buffers(ide_drive_t *drive, struct ide_atapi_pc *pc,
636				unsigned int bcount, int write)
637{
638	if (write)
639		idetape_output_buffers(drive, pc, bcount);
640	else
641		idetape_input_buffers(drive, pc, bcount);
642
643	return bcount;
644}
645
646/*
647 * This is the usual interrupt handler which will be called during a packet
648 * command. We will transfer some of the data (as requested by the drive) and
649 * will re-point interrupt handler to us. When data transfer is finished, we
650 * will act according to the algorithm described before
651 * idetape_issue_pc.
652 */
653static ide_startstop_t idetape_pc_intr(ide_drive_t *drive)
654{
655	return ide_pc_intr(drive, idetape_pc_intr, idetape_update_buffers,
656			   idetape_retry_pc, ide_tape_io_buffers);
657}
658
659/*
660 * Packet Command Interface
661 *
662 * The current Packet Command is available in drive->pc, and will not change
663 * until we finish handling it. Each packet command is associated with a
664 * callback function that will be called when the command is finished.
665 *
666 * The handling will be done in three stages:
667 *
668 * 1. idetape_issue_pc will send the packet command to the drive, and will set
669 * the interrupt handler to idetape_pc_intr.
670 *
671 * 2. On each interrupt, idetape_pc_intr will be called. This step will be
672 * repeated until the device signals us that no more interrupts will be issued.
673 *
674 * 3. ATAPI Tape media access commands have immediate status with a delayed
675 * process. In case of a successful initiation of a media access packet command,
676 * the DSC bit will be set when the actual execution of the command is finished.
677 * Since the tape drive will not issue an interrupt, we have to poll for this
678 * event. In this case, we define the request as "low priority request" by
679 * setting rq_status to IDETAPE_RQ_POSTPONED, set a timer to poll for DSC and
680 * exit the driver.
681 *
682 * ide.c will then give higher priority to requests which originate from the
683 * other device, until will change rq_status to RQ_ACTIVE.
684 *
685 * 4. When the packet command is finished, it will be checked for errors.
686 *
687 * 5. In case an error was found, we queue a request sense packet command in
688 * front of the request queue and retry the operation up to
689 * IDETAPE_MAX_PC_RETRIES times.
690 *
691 * 6. In case no error was found, or we decided to give up and not to retry
692 * again, the callback function will be called and then we will handle the next
693 * request.
694 */
695static ide_startstop_t idetape_transfer_pc(ide_drive_t *drive)
696{
697	return ide_transfer_pc(drive, idetape_pc_intr, WAIT_TAPE_CMD, NULL);
698}
699
700static ide_startstop_t idetape_issue_pc(ide_drive_t *drive,
701		struct ide_atapi_pc *pc)
702{
703	idetape_tape_t *tape = drive->driver_data;
704
705	if (drive->pc->c[0] == REQUEST_SENSE &&
706	    pc->c[0] == REQUEST_SENSE) {
707		printk(KERN_ERR "ide-tape: possible ide-tape.c bug - "
708			"Two request sense in serial were issued\n");
709	}
710
711	if (tape->failed_pc == NULL && pc->c[0] != REQUEST_SENSE)
712		tape->failed_pc = pc;
713
714	/* Set the current packet command */
715	drive->pc = pc;
716
717	if (pc->retries > IDETAPE_MAX_PC_RETRIES ||
718		(pc->flags & PC_FLAG_ABORT)) {
719		/*
720		 * We will "abort" retrying a packet command in case legitimate
721		 * error code was received (crossing a filemark, or end of the
722		 * media, for example).
723		 */
724		if (!(pc->flags & PC_FLAG_ABORT)) {
725			if (!(pc->c[0] == TEST_UNIT_READY &&
726			      tape->sense_key == 2 && tape->asc == 4 &&
727			     (tape->ascq == 1 || tape->ascq == 8))) {
728				printk(KERN_ERR "ide-tape: %s: I/O error, "
729						"pc = %2x, key = %2x, "
730						"asc = %2x, ascq = %2x\n",
731						tape->name, pc->c[0],
732						tape->sense_key, tape->asc,
733						tape->ascq);
734			}
735			/* Giving up */
736			pc->error = IDETAPE_ERROR_GENERAL;
737		}
738		tape->failed_pc = NULL;
739		drive->pc_callback(drive, 0);
740		return ide_stopped;
741	}
742	debug_log(DBG_SENSE, "Retry #%d, cmd = %02X\n", pc->retries, pc->c[0]);
743
744	pc->retries++;
745
746	return ide_issue_pc(drive, idetape_transfer_pc, WAIT_TAPE_CMD, NULL);
747}
748
749/* A mode sense command is used to "sense" tape parameters. */
750static void idetape_create_mode_sense_cmd(struct ide_atapi_pc *pc, u8 page_code)
751{
752	ide_init_pc(pc);
753	pc->c[0] = MODE_SENSE;
754	if (page_code != IDETAPE_BLOCK_DESCRIPTOR)
755		/* DBD = 1 - Don't return block descriptors */
756		pc->c[1] = 8;
757	pc->c[2] = page_code;
758	/*
759	 * Changed pc->c[3] to 0 (255 will at best return unused info).
760	 *
761	 * For SCSI this byte is defined as subpage instead of high byte
762	 * of length and some IDE drives seem to interpret it this way
763	 * and return an error when 255 is used.
764	 */
765	pc->c[3] = 0;
766	/* We will just discard data in that case */
767	pc->c[4] = 255;
768	if (page_code == IDETAPE_BLOCK_DESCRIPTOR)
769		pc->req_xfer = 12;
770	else if (page_code == IDETAPE_CAPABILITIES_PAGE)
771		pc->req_xfer = 24;
772	else
773		pc->req_xfer = 50;
774}
775
776static ide_startstop_t idetape_media_access_finished(ide_drive_t *drive)
777{
778	ide_hwif_t *hwif = drive->hwif;
779	idetape_tape_t *tape = drive->driver_data;
780	struct ide_atapi_pc *pc = drive->pc;
781	u8 stat;
782
783	stat = hwif->tp_ops->read_status(hwif);
784
785	if (stat & ATA_DSC) {
786		if (stat & ATA_ERR) {
787			/* Error detected */
788			if (pc->c[0] != TEST_UNIT_READY)
789				printk(KERN_ERR "ide-tape: %s: I/O error, ",
790						tape->name);
791			/* Retry operation */
792			idetape_retry_pc(drive);
793			return ide_stopped;
794		}
795		pc->error = 0;
796	} else {
797		pc->error = IDETAPE_ERROR_GENERAL;
798		tape->failed_pc = NULL;
799	}
800	drive->pc_callback(drive, 0);
801	return ide_stopped;
802}
803
804static void ide_tape_create_rw_cmd(idetape_tape_t *tape,
805				   struct ide_atapi_pc *pc, struct request *rq,
806				   u8 opcode)
807{
808	struct idetape_bh *bh = (struct idetape_bh *)rq->special;
809	unsigned int length = rq->current_nr_sectors;
810
811	ide_init_pc(pc);
812	put_unaligned(cpu_to_be32(length), (unsigned int *) &pc->c[1]);
813	pc->c[1] = 1;
814	pc->bh = bh;
815	pc->buf = NULL;
816	pc->buf_size = length * tape->blk_size;
817	pc->req_xfer = pc->buf_size;
818	if (pc->req_xfer == tape->buffer_size)
819		pc->flags |= PC_FLAG_DMA_OK;
820
821	if (opcode == READ_6) {
822		pc->c[0] = READ_6;
823		atomic_set(&bh->b_count, 0);
824	} else if (opcode == WRITE_6) {
825		pc->c[0] = WRITE_6;
826		pc->flags |= PC_FLAG_WRITING;
827		pc->b_data = bh->b_data;
828		pc->b_count = atomic_read(&bh->b_count);
829	}
830
831	memcpy(rq->cmd, pc->c, 12);
832}
833
834static ide_startstop_t idetape_do_request(ide_drive_t *drive,
835					  struct request *rq, sector_t block)
836{
837	ide_hwif_t *hwif = drive->hwif;
838	idetape_tape_t *tape = drive->driver_data;
839	struct ide_atapi_pc *pc = NULL;
840	struct request *postponed_rq = tape->postponed_rq;
841	u8 stat;
842
843	debug_log(DBG_SENSE, "sector: %llu, nr_sectors: %lu,"
844			" current_nr_sectors: %u\n",
845			(unsigned long long)rq->sector, rq->nr_sectors,
846			rq->current_nr_sectors);
847
848	if (!blk_special_request(rq)) {
849		/* We do not support buffer cache originated requests. */
850		printk(KERN_NOTICE "ide-tape: %s: Unsupported request in "
851			"request queue (%d)\n", drive->name, rq->cmd_type);
852		ide_end_request(drive, 0, 0);
853		return ide_stopped;
854	}
855
856	/* Retry a failed packet command */
857	if (tape->failed_pc && drive->pc->c[0] == REQUEST_SENSE) {
858		pc = tape->failed_pc;
859		goto out;
860	}
861
862	if (postponed_rq != NULL)
863		if (rq != postponed_rq) {
864			printk(KERN_ERR "ide-tape: ide-tape.c bug - "
865					"Two DSC requests were queued\n");
866			idetape_end_request(drive, 0, 0);
867			return ide_stopped;
868		}
869
870	tape->postponed_rq = NULL;
871
872	/*
873	 * If the tape is still busy, postpone our request and service
874	 * the other device meanwhile.
875	 */
876	stat = hwif->tp_ops->read_status(hwif);
877
878	if (!drive->dsc_overlap && !(rq->cmd[13] & REQ_IDETAPE_PC2))
879		set_bit(IDE_AFLAG_IGNORE_DSC, &drive->atapi_flags);
880
881	if (drive->post_reset == 1) {
882		set_bit(IDE_AFLAG_IGNORE_DSC, &drive->atapi_flags);
883		drive->post_reset = 0;
884	}
885
886	if (!test_and_clear_bit(IDE_AFLAG_IGNORE_DSC, &drive->atapi_flags) &&
887	    (stat & ATA_DSC) == 0) {
888		if (postponed_rq == NULL) {
889			tape->dsc_polling_start = jiffies;
890			tape->dsc_poll_freq = tape->best_dsc_rw_freq;
891			tape->dsc_timeout = jiffies + IDETAPE_DSC_RW_TIMEOUT;
892		} else if (time_after(jiffies, tape->dsc_timeout)) {
893			printk(KERN_ERR "ide-tape: %s: DSC timeout\n",
894				tape->name);
895			if (rq->cmd[13] & REQ_IDETAPE_PC2) {
896				idetape_media_access_finished(drive);
897				return ide_stopped;
898			} else {
899				return ide_do_reset(drive);
900			}
901		} else if (time_after(jiffies,
902					tape->dsc_polling_start +
903					IDETAPE_DSC_MA_THRESHOLD))
904			tape->dsc_poll_freq = IDETAPE_DSC_MA_SLOW;
905		idetape_postpone_request(drive);
906		return ide_stopped;
907	}
908	if (rq->cmd[13] & REQ_IDETAPE_READ) {
909		pc = &tape->queued_pc;
910		ide_tape_create_rw_cmd(tape, pc, rq, READ_6);
911		goto out;
912	}
913	if (rq->cmd[13] & REQ_IDETAPE_WRITE) {
914		pc = &tape->queued_pc;
915		ide_tape_create_rw_cmd(tape, pc, rq, WRITE_6);
916		goto out;
917	}
918	if (rq->cmd[13] & REQ_IDETAPE_PC1) {
919		pc = (struct ide_atapi_pc *) rq->buffer;
920		rq->cmd[13] &= ~(REQ_IDETAPE_PC1);
921		rq->cmd[13] |= REQ_IDETAPE_PC2;
922		goto out;
923	}
924	if (rq->cmd[13] & REQ_IDETAPE_PC2) {
925		idetape_media_access_finished(drive);
926		return ide_stopped;
927	}
928	BUG();
929
930out:
931	return idetape_issue_pc(drive, pc);
932}
933
934/*
935 * The function below uses __get_free_pages to allocate a data buffer of size
936 * tape->buffer_size (or a bit more). We attempt to combine sequential pages as
937 * much as possible.
938 *
939 * It returns a pointer to the newly allocated buffer, or NULL in case of
940 * failure.
941 */
942static struct idetape_bh *ide_tape_kmalloc_buffer(idetape_tape_t *tape,
943						  int full, int clear)
944{
945	struct idetape_bh *prev_bh, *bh, *merge_bh;
946	int pages = tape->pages_per_buffer;
947	unsigned int order, b_allocd;
948	char *b_data = NULL;
949
950	merge_bh = kmalloc(sizeof(struct idetape_bh), GFP_KERNEL);
951	bh = merge_bh;
952	if (bh == NULL)
953		goto abort;
954
955	order = fls(pages) - 1;
956	bh->b_data = (char *) __get_free_pages(GFP_KERNEL, order);
957	if (!bh->b_data)
958		goto abort;
959	b_allocd = (1 << order) * PAGE_SIZE;
960	pages &= (order-1);
961
962	if (clear)
963		memset(bh->b_data, 0, b_allocd);
964	bh->b_reqnext = NULL;
965	bh->b_size = b_allocd;
966	atomic_set(&bh->b_count, full ? bh->b_size : 0);
967
968	while (pages) {
969		order = fls(pages) - 1;
970		b_data = (char *) __get_free_pages(GFP_KERNEL, order);
971		if (!b_data)
972			goto abort;
973		b_allocd = (1 << order) * PAGE_SIZE;
974
975		if (clear)
976			memset(b_data, 0, b_allocd);
977
978		/* newly allocated page frames below buffer header or ...*/
979		if (bh->b_data == b_data + b_allocd) {
980			bh->b_size += b_allocd;
981			bh->b_data -= b_allocd;
982			if (full)
983				atomic_add(b_allocd, &bh->b_count);
984			continue;
985		}
986		/* they are above the header */
987		if (b_data == bh->b_data + bh->b_size) {
988			bh->b_size += b_allocd;
989			if (full)
990				atomic_add(b_allocd, &bh->b_count);
991			continue;
992		}
993		prev_bh = bh;
994		bh = kmalloc(sizeof(struct idetape_bh), GFP_KERNEL);
995		if (!bh) {
996			free_pages((unsigned long) b_data, order);
997			goto abort;
998		}
999		bh->b_reqnext = NULL;
1000		bh->b_data = b_data;
1001		bh->b_size = b_allocd;
1002		atomic_set(&bh->b_count, full ? bh->b_size : 0);
1003		prev_bh->b_reqnext = bh;
1004
1005		pages &= (order-1);
1006	}
1007
1008	bh->b_size -= tape->excess_bh_size;
1009	if (full)
1010		atomic_sub(tape->excess_bh_size, &bh->b_count);
1011	return merge_bh;
1012abort:
1013	ide_tape_kfree_buffer(tape);
1014	return NULL;
1015}
1016
1017static int idetape_copy_stage_from_user(idetape_tape_t *tape,
1018					const char __user *buf, int n)
1019{
1020	struct idetape_bh *bh = tape->bh;
1021	int count;
1022	int ret = 0;
1023
1024	while (n) {
1025		if (bh == NULL) {
1026			printk(KERN_ERR "ide-tape: bh == NULL in %s\n",
1027					__func__);
1028			return 1;
1029		}
1030		count = min((unsigned int)
1031				(bh->b_size - atomic_read(&bh->b_count)),
1032				(unsigned int)n);
1033		if (copy_from_user(bh->b_data + atomic_read(&bh->b_count), buf,
1034				count))
1035			ret = 1;
1036		n -= count;
1037		atomic_add(count, &bh->b_count);
1038		buf += count;
1039		if (atomic_read(&bh->b_count) == bh->b_size) {
1040			bh = bh->b_reqnext;
1041			if (bh)
1042				atomic_set(&bh->b_count, 0);
1043		}
1044	}
1045	tape->bh = bh;
1046	return ret;
1047}
1048
1049static int idetape_copy_stage_to_user(idetape_tape_t *tape, char __user *buf,
1050				      int n)
1051{
1052	struct idetape_bh *bh = tape->bh;
1053	int count;
1054	int ret = 0;
1055
1056	while (n) {
1057		if (bh == NULL) {
1058			printk(KERN_ERR "ide-tape: bh == NULL in %s\n",
1059					__func__);
1060			return 1;
1061		}
1062		count = min(tape->b_count, n);
1063		if  (copy_to_user(buf, tape->b_data, count))
1064			ret = 1;
1065		n -= count;
1066		tape->b_data += count;
1067		tape->b_count -= count;
1068		buf += count;
1069		if (!tape->b_count) {
1070			bh = bh->b_reqnext;
1071			tape->bh = bh;
1072			if (bh) {
1073				tape->b_data = bh->b_data;
1074				tape->b_count = atomic_read(&bh->b_count);
1075			}
1076		}
1077	}
1078	return ret;
1079}
1080
1081static void idetape_init_merge_buffer(idetape_tape_t *tape)
1082{
1083	struct idetape_bh *bh = tape->merge_bh;
1084	tape->bh = tape->merge_bh;
1085
1086	if (tape->chrdev_dir == IDETAPE_DIR_WRITE)
1087		atomic_set(&bh->b_count, 0);
1088	else {
1089		tape->b_data = bh->b_data;
1090		tape->b_count = atomic_read(&bh->b_count);
1091	}
1092}
1093
1094/*
1095 * Write a filemark if write_filemark=1. Flush the device buffers without
1096 * writing a filemark otherwise.
1097 */
1098static void idetape_create_write_filemark_cmd(ide_drive_t *drive,
1099		struct ide_atapi_pc *pc, int write_filemark)
1100{
1101	ide_init_pc(pc);
1102	pc->c[0] = WRITE_FILEMARKS;
1103	pc->c[4] = write_filemark;
1104	pc->flags |= PC_FLAG_WAIT_FOR_DSC;
1105}
1106
1107static int idetape_wait_ready(ide_drive_t *drive, unsigned long timeout)
1108{
1109	idetape_tape_t *tape = drive->driver_data;
1110	struct gendisk *disk = tape->disk;
1111	int load_attempted = 0;
1112
1113	/* Wait for the tape to become ready */
1114	set_bit(IDE_AFLAG_MEDIUM_PRESENT, &drive->atapi_flags);
1115	timeout += jiffies;
1116	while (time_before(jiffies, timeout)) {
1117		if (ide_do_test_unit_ready(drive, disk) == 0)
1118			return 0;
1119		if ((tape->sense_key == 2 && tape->asc == 4 && tape->ascq == 2)
1120		    || (tape->asc == 0x3A)) {
1121			/* no media */
1122			if (load_attempted)
1123				return -ENOMEDIUM;
1124			ide_do_start_stop(drive, disk, IDETAPE_LU_LOAD_MASK);
1125			load_attempted = 1;
1126		/* not about to be ready */
1127		} else if (!(tape->sense_key == 2 && tape->asc == 4 &&
1128			     (tape->ascq == 1 || tape->ascq == 8)))
1129			return -EIO;
1130		msleep(100);
1131	}
1132	return -EIO;
1133}
1134
1135static int idetape_flush_tape_buffers(ide_drive_t *drive)
1136{
1137	struct ide_tape_obj *tape = drive->driver_data;
1138	struct ide_atapi_pc pc;
1139	int rc;
1140
1141	idetape_create_write_filemark_cmd(drive, &pc, 0);
1142	rc = ide_queue_pc_tail(drive, tape->disk, &pc);
1143	if (rc)
1144		return rc;
1145	idetape_wait_ready(drive, 60 * 5 * HZ);
1146	return 0;
1147}
1148
1149static void idetape_create_read_position_cmd(struct ide_atapi_pc *pc)
1150{
1151	ide_init_pc(pc);
1152	pc->c[0] = READ_POSITION;
1153	pc->req_xfer = 20;
1154}
1155
1156static int idetape_read_position(ide_drive_t *drive)
1157{
1158	idetape_tape_t *tape = drive->driver_data;
1159	struct ide_atapi_pc pc;
1160	int position;
1161
1162	debug_log(DBG_PROCS, "Enter %s\n", __func__);
1163
1164	idetape_create_read_position_cmd(&pc);
1165	if (ide_queue_pc_tail(drive, tape->disk, &pc))
1166		return -1;
1167	position = tape->first_frame;
1168	return position;
1169}
1170
1171static void idetape_create_locate_cmd(ide_drive_t *drive,
1172		struct ide_atapi_pc *pc,
1173		unsigned int block, u8 partition, int skip)
1174{
1175	ide_init_pc(pc);
1176	pc->c[0] = POSITION_TO_ELEMENT;
1177	pc->c[1] = 2;
1178	put_unaligned(cpu_to_be32(block), (unsigned int *) &pc->c[3]);
1179	pc->c[8] = partition;
1180	pc->flags |= PC_FLAG_WAIT_FOR_DSC;
1181}
1182
1183static void __ide_tape_discard_merge_buffer(ide_drive_t *drive)
1184{
1185	idetape_tape_t *tape = drive->driver_data;
1186
1187	if (tape->chrdev_dir != IDETAPE_DIR_READ)
1188		return;
1189
1190	clear_bit(IDE_AFLAG_FILEMARK, &drive->atapi_flags);
1191	tape->merge_bh_size = 0;
1192	if (tape->merge_bh != NULL) {
1193		ide_tape_kfree_buffer(tape);
1194		tape->merge_bh = NULL;
1195	}
1196
1197	tape->chrdev_dir = IDETAPE_DIR_NONE;
1198}
1199
1200/*
1201 * Position the tape to the requested block using the LOCATE packet command.
1202 * A READ POSITION command is then issued to check where we are positioned. Like
1203 * all higher level operations, we queue the commands at the tail of the request
1204 * queue and wait for their completion.
1205 */
1206static int idetape_position_tape(ide_drive_t *drive, unsigned int block,
1207		u8 partition, int skip)
1208{
1209	idetape_tape_t *tape = drive->driver_data;
1210	struct gendisk *disk = tape->disk;
1211	int retval;
1212	struct ide_atapi_pc pc;
1213
1214	if (tape->chrdev_dir == IDETAPE_DIR_READ)
1215		__ide_tape_discard_merge_buffer(drive);
1216	idetape_wait_ready(drive, 60 * 5 * HZ);
1217	idetape_create_locate_cmd(drive, &pc, block, partition, skip);
1218	retval = ide_queue_pc_tail(drive, disk, &pc);
1219	if (retval)
1220		return (retval);
1221
1222	idetape_create_read_position_cmd(&pc);
1223	return ide_queue_pc_tail(drive, disk, &pc);
1224}
1225
1226static void ide_tape_discard_merge_buffer(ide_drive_t *drive,
1227					  int restore_position)
1228{
1229	idetape_tape_t *tape = drive->driver_data;
1230	int seek, position;
1231
1232	__ide_tape_discard_merge_buffer(drive);
1233	if (restore_position) {
1234		position = idetape_read_position(drive);
1235		seek = position > 0 ? position : 0;
1236		if (idetape_position_tape(drive, seek, 0, 0)) {
1237			printk(KERN_INFO "ide-tape: %s: position_tape failed in"
1238					 " %s\n", tape->name, __func__);
1239			return;
1240		}
1241	}
1242}
1243
1244/*
1245 * Generate a read/write request for the block device interface and wait for it
1246 * to be serviced.
1247 */
1248static int idetape_queue_rw_tail(ide_drive_t *drive, int cmd, int blocks,
1249				 struct idetape_bh *bh)
1250{
1251	idetape_tape_t *tape = drive->driver_data;
1252	struct request *rq;
1253	int ret, errors;
1254
1255	debug_log(DBG_SENSE, "%s: cmd=%d\n", __func__, cmd);
1256
1257	rq = blk_get_request(drive->queue, READ, __GFP_WAIT);
1258	rq->cmd_type = REQ_TYPE_SPECIAL;
1259	rq->cmd[13] = cmd;
1260	rq->rq_disk = tape->disk;
1261	rq->special = (void *)bh;
1262	rq->sector = tape->first_frame;
1263	rq->nr_sectors = blocks;
1264	rq->current_nr_sectors = blocks;
1265	blk_execute_rq(drive->queue, tape->disk, rq, 0);
1266
1267	errors = rq->errors;
1268	ret = tape->blk_size * (blocks - rq->current_nr_sectors);
1269	blk_put_request(rq);
1270
1271	if ((cmd & (REQ_IDETAPE_READ | REQ_IDETAPE_WRITE)) == 0)
1272		return 0;
1273
1274	if (tape->merge_bh)
1275		idetape_init_merge_buffer(tape);
1276	if (errors == IDETAPE_ERROR_GENERAL)
1277		return -EIO;
1278	return ret;
1279}
1280
1281static void idetape_create_inquiry_cmd(struct ide_atapi_pc *pc)
1282{
1283	ide_init_pc(pc);
1284	pc->c[0] = INQUIRY;
1285	pc->c[4] = 254;
1286	pc->req_xfer = 254;
1287}
1288
1289static void idetape_create_rewind_cmd(ide_drive_t *drive,
1290		struct ide_atapi_pc *pc)
1291{
1292	ide_init_pc(pc);
1293	pc->c[0] = REZERO_UNIT;
1294	pc->flags |= PC_FLAG_WAIT_FOR_DSC;
1295}
1296
1297static void idetape_create_erase_cmd(struct ide_atapi_pc *pc)
1298{
1299	ide_init_pc(pc);
1300	pc->c[0] = ERASE;
1301	pc->c[1] = 1;
1302	pc->flags |= PC_FLAG_WAIT_FOR_DSC;
1303}
1304
1305static void idetape_create_space_cmd(struct ide_atapi_pc *pc, int count, u8 cmd)
1306{
1307	ide_init_pc(pc);
1308	pc->c[0] = SPACE;
1309	put_unaligned(cpu_to_be32(count), (unsigned int *) &pc->c[1]);
1310	pc->c[1] = cmd;
1311	pc->flags |= PC_FLAG_WAIT_FOR_DSC;
1312}
1313
1314/* Queue up a character device originated write request. */
1315static int idetape_add_chrdev_write_request(ide_drive_t *drive, int blocks)
1316{
1317	idetape_tape_t *tape = drive->driver_data;
1318
1319	debug_log(DBG_CHRDEV, "Enter %s\n", __func__);
1320
1321	return idetape_queue_rw_tail(drive, REQ_IDETAPE_WRITE,
1322				     blocks, tape->merge_bh);
1323}
1324
1325static void ide_tape_flush_merge_buffer(ide_drive_t *drive)
1326{
1327	idetape_tape_t *tape = drive->driver_data;
1328	int blocks, min;
1329	struct idetape_bh *bh;
1330
1331	if (tape->chrdev_dir != IDETAPE_DIR_WRITE) {
1332		printk(KERN_ERR "ide-tape: bug: Trying to empty merge buffer"
1333				" but we are not writing.\n");
1334		return;
1335	}
1336	if (tape->merge_bh_size > tape->buffer_size) {
1337		printk(KERN_ERR "ide-tape: bug: merge_buffer too big\n");
1338		tape->merge_bh_size = tape->buffer_size;
1339	}
1340	if (tape->merge_bh_size) {
1341		blocks = tape->merge_bh_size / tape->blk_size;
1342		if (tape->merge_bh_size % tape->blk_size) {
1343			unsigned int i;
1344
1345			blocks++;
1346			i = tape->blk_size - tape->merge_bh_size %
1347				tape->blk_size;
1348			bh = tape->bh->b_reqnext;
1349			while (bh) {
1350				atomic_set(&bh->b_count, 0);
1351				bh = bh->b_reqnext;
1352			}
1353			bh = tape->bh;
1354			while (i) {
1355				if (bh == NULL) {
1356					printk(KERN_INFO "ide-tape: bug,"
1357							 " bh NULL\n");
1358					break;
1359				}
1360				min = min(i, (unsigned int)(bh->b_size -
1361						atomic_read(&bh->b_count)));
1362				memset(bh->b_data + atomic_read(&bh->b_count),
1363						0, min);
1364				atomic_add(min, &bh->b_count);
1365				i -= min;
1366				bh = bh->b_reqnext;
1367			}
1368		}
1369		(void) idetape_add_chrdev_write_request(drive, blocks);
1370		tape->merge_bh_size = 0;
1371	}
1372	if (tape->merge_bh != NULL) {
1373		ide_tape_kfree_buffer(tape);
1374		tape->merge_bh = NULL;
1375	}
1376	tape->chrdev_dir = IDETAPE_DIR_NONE;
1377}
1378
1379static int idetape_init_read(ide_drive_t *drive)
1380{
1381	idetape_tape_t *tape = drive->driver_data;
1382	int bytes_read;
1383
1384	/* Initialize read operation */
1385	if (tape->chrdev_dir != IDETAPE_DIR_READ) {
1386		if (tape->chrdev_dir == IDETAPE_DIR_WRITE) {
1387			ide_tape_flush_merge_buffer(drive);
1388			idetape_flush_tape_buffers(drive);
1389		}
1390		if (tape->merge_bh || tape->merge_bh_size) {
1391			printk(KERN_ERR "ide-tape: merge_bh_size should be"
1392					 " 0 now\n");
1393			tape->merge_bh_size = 0;
1394		}
1395		tape->merge_bh = ide_tape_kmalloc_buffer(tape, 0, 0);
1396		if (!tape->merge_bh)
1397			return -ENOMEM;
1398		tape->chrdev_dir = IDETAPE_DIR_READ;
1399
1400		/*
1401		 * Issue a read 0 command to ensure that DSC handshake is
1402		 * switched from completion mode to buffer available mode.
1403		 * No point in issuing this if DSC overlap isn't supported, some
1404		 * drives (Seagate STT3401A) will return an error.
1405		 */
1406		if (drive->dsc_overlap) {
1407			bytes_read = idetape_queue_rw_tail(drive,
1408							REQ_IDETAPE_READ, 0,
1409							tape->merge_bh);
1410			if (bytes_read < 0) {
1411				ide_tape_kfree_buffer(tape);
1412				tape->merge_bh = NULL;
1413				tape->chrdev_dir = IDETAPE_DIR_NONE;
1414				return bytes_read;
1415			}
1416		}
1417	}
1418
1419	return 0;
1420}
1421
1422/* called from idetape_chrdev_read() to service a chrdev read request. */
1423static int idetape_add_chrdev_read_request(ide_drive_t *drive, int blocks)
1424{
1425	idetape_tape_t *tape = drive->driver_data;
1426
1427	debug_log(DBG_PROCS, "Enter %s, %d blocks\n", __func__, blocks);
1428
1429	/* If we are at a filemark, return a read length of 0 */
1430	if (test_bit(IDE_AFLAG_FILEMARK, &drive->atapi_flags))
1431		return 0;
1432
1433	idetape_init_read(drive);
1434
1435	return idetape_queue_rw_tail(drive, REQ_IDETAPE_READ, blocks,
1436				     tape->merge_bh);
1437}
1438
1439static void idetape_pad_zeros(ide_drive_t *drive, int bcount)
1440{
1441	idetape_tape_t *tape = drive->driver_data;
1442	struct idetape_bh *bh;
1443	int blocks;
1444
1445	while (bcount) {
1446		unsigned int count;
1447
1448		bh = tape->merge_bh;
1449		count = min(tape->buffer_size, bcount);
1450		bcount -= count;
1451		blocks = count / tape->blk_size;
1452		while (count) {
1453			atomic_set(&bh->b_count,
1454				   min(count, (unsigned int)bh->b_size));
1455			memset(bh->b_data, 0, atomic_read(&bh->b_count));
1456			count -= atomic_read(&bh->b_count);
1457			bh = bh->b_reqnext;
1458		}
1459		idetape_queue_rw_tail(drive, REQ_IDETAPE_WRITE, blocks,
1460				      tape->merge_bh);
1461	}
1462}
1463
1464/*
1465 * Rewinds the tape to the Beginning Of the current Partition (BOP). We
1466 * currently support only one partition.
1467 */
1468static int idetape_rewind_tape(ide_drive_t *drive)
1469{
1470	struct ide_tape_obj *tape = drive->driver_data;
1471	struct gendisk *disk = tape->disk;
1472	int retval;
1473	struct ide_atapi_pc pc;
1474
1475	debug_log(DBG_SENSE, "Enter %s\n", __func__);
1476
1477	idetape_create_rewind_cmd(drive, &pc);
1478	retval = ide_queue_pc_tail(drive, disk, &pc);
1479	if (retval)
1480		return retval;
1481
1482	idetape_create_read_position_cmd(&pc);
1483	retval = ide_queue_pc_tail(drive, disk, &pc);
1484	if (retval)
1485		return retval;
1486	return 0;
1487}
1488
1489/* mtio.h compatible commands should be issued to the chrdev interface. */
1490static int idetape_blkdev_ioctl(ide_drive_t *drive, unsigned int cmd,
1491				unsigned long arg)
1492{
1493	idetape_tape_t *tape = drive->driver_data;
1494	void __user *argp = (void __user *)arg;
1495
1496	struct idetape_config {
1497		int dsc_rw_frequency;
1498		int dsc_media_access_frequency;
1499		int nr_stages;
1500	} config;
1501
1502	debug_log(DBG_PROCS, "Enter %s\n", __func__);
1503
1504	switch (cmd) {
1505	case 0x0340:
1506		if (copy_from_user(&config, argp, sizeof(config)))
1507			return -EFAULT;
1508		tape->best_dsc_rw_freq = config.dsc_rw_frequency;
1509		break;
1510	case 0x0350:
1511		config.dsc_rw_frequency = (int) tape->best_dsc_rw_freq;
1512		config.nr_stages = 1;
1513		if (copy_to_user(argp, &config, sizeof(config)))
1514			return -EFAULT;
1515		break;
1516	default:
1517		return -EIO;
1518	}
1519	return 0;
1520}
1521
1522static int idetape_space_over_filemarks(ide_drive_t *drive, short mt_op,
1523					int mt_count)
1524{
1525	idetape_tape_t *tape = drive->driver_data;
1526	struct gendisk *disk = tape->disk;
1527	struct ide_atapi_pc pc;
1528	int retval, count = 0;
1529	int sprev = !!(tape->caps[4] & 0x20);
1530
1531	if (mt_count == 0)
1532		return 0;
1533	if (MTBSF == mt_op || MTBSFM == mt_op) {
1534		if (!sprev)
1535			return -EIO;
1536		mt_count = -mt_count;
1537	}
1538
1539	if (tape->chrdev_dir == IDETAPE_DIR_READ) {
1540		tape->merge_bh_size = 0;
1541		if (test_and_clear_bit(IDE_AFLAG_FILEMARK, &drive->atapi_flags))
1542			++count;
1543		ide_tape_discard_merge_buffer(drive, 0);
1544	}
1545
1546	switch (mt_op) {
1547	case MTFSF:
1548	case MTBSF:
1549		idetape_create_space_cmd(&pc, mt_count - count,
1550					 IDETAPE_SPACE_OVER_FILEMARK);
1551		return ide_queue_pc_tail(drive, disk, &pc);
1552	case MTFSFM:
1553	case MTBSFM:
1554		if (!sprev)
1555			return -EIO;
1556		retval = idetape_space_over_filemarks(drive, MTFSF,
1557						      mt_count - count);
1558		if (retval)
1559			return retval;
1560		count = (MTBSFM == mt_op ? 1 : -1);
1561		return idetape_space_over_filemarks(drive, MTFSF, count);
1562	default:
1563		printk(KERN_ERR "ide-tape: MTIO operation %d not supported\n",
1564				mt_op);
1565		return -EIO;
1566	}
1567}
1568
1569/*
1570 * Our character device read / write functions.
1571 *
1572 * The tape is optimized to maximize throughput when it is transferring an
1573 * integral number of the "continuous transfer limit", which is a parameter of
1574 * the specific tape (26kB on my particular tape, 32kB for Onstream).
1575 *
1576 * As of version 1.3 of the driver, the character device provides an abstract
1577 * continuous view of the media - any mix of block sizes (even 1 byte) on the
1578 * same backup/restore procedure is supported. The driver will internally
1579 * convert the requests to the recommended transfer unit, so that an unmatch
1580 * between the user's block size to the recommended size will only result in a
1581 * (slightly) increased driver overhead, but will no longer hit performance.
1582 * This is not applicable to Onstream.
1583 */
1584static ssize_t idetape_chrdev_read(struct file *file, char __user *buf,
1585				   size_t count, loff_t *ppos)
1586{
1587	struct ide_tape_obj *tape = ide_tape_f(file);
1588	ide_drive_t *drive = tape->drive;
1589	ssize_t bytes_read, temp, actually_read = 0, rc;
1590	ssize_t ret = 0;
1591	u16 ctl = *(u16 *)&tape->caps[12];
1592
1593	debug_log(DBG_CHRDEV, "Enter %s, count %Zd\n", __func__, count);
1594
1595	if (tape->chrdev_dir != IDETAPE_DIR_READ) {
1596		if (test_bit(IDE_AFLAG_DETECT_BS, &drive->atapi_flags))
1597			if (count > tape->blk_size &&
1598			    (count % tape->blk_size) == 0)
1599				tape->user_bs_factor = count / tape->blk_size;
1600	}
1601	rc = idetape_init_read(drive);
1602	if (rc < 0)
1603		return rc;
1604	if (count == 0)
1605		return (0);
1606	if (tape->merge_bh_size) {
1607		actually_read = min((unsigned int)(tape->merge_bh_size),
1608				    (unsigned int)count);
1609		if (idetape_copy_stage_to_user(tape, buf, actually_read))
1610			ret = -EFAULT;
1611		buf += actually_read;
1612		tape->merge_bh_size -= actually_read;
1613		count -= actually_read;
1614	}
1615	while (count >= tape->buffer_size) {
1616		bytes_read = idetape_add_chrdev_read_request(drive, ctl);
1617		if (bytes_read <= 0)
1618			goto finish;
1619		if (idetape_copy_stage_to_user(tape, buf, bytes_read))
1620			ret = -EFAULT;
1621		buf += bytes_read;
1622		count -= bytes_read;
1623		actually_read += bytes_read;
1624	}
1625	if (count) {
1626		bytes_read = idetape_add_chrdev_read_request(drive, ctl);
1627		if (bytes_read <= 0)
1628			goto finish;
1629		temp = min((unsigned long)count, (unsigned long)bytes_read);
1630		if (idetape_copy_stage_to_user(tape, buf, temp))
1631			ret = -EFAULT;
1632		actually_read += temp;
1633		tape->merge_bh_size = bytes_read-temp;
1634	}
1635finish:
1636	if (!actually_read && test_bit(IDE_AFLAG_FILEMARK, &drive->atapi_flags)) {
1637		debug_log(DBG_SENSE, "%s: spacing over filemark\n", tape->name);
1638
1639		idetape_space_over_filemarks(drive, MTFSF, 1);
1640		return 0;
1641	}
1642
1643	return ret ? ret : actually_read;
1644}
1645
1646static ssize_t idetape_chrdev_write(struct file *file, const char __user *buf,
1647				     size_t count, loff_t *ppos)
1648{
1649	struct ide_tape_obj *tape = ide_tape_f(file);
1650	ide_drive_t *drive = tape->drive;
1651	ssize_t actually_written = 0;
1652	ssize_t ret = 0;
1653	u16 ctl = *(u16 *)&tape->caps[12];
1654
1655	/* The drive is write protected. */
1656	if (tape->write_prot)
1657		return -EACCES;
1658
1659	debug_log(DBG_CHRDEV, "Enter %s, count %Zd\n", __func__, count);
1660
1661	/* Initialize write operation */
1662	if (tape->chrdev_dir != IDETAPE_DIR_WRITE) {
1663		if (tape->chrdev_dir == IDETAPE_DIR_READ)
1664			ide_tape_discard_merge_buffer(drive, 1);
1665		if (tape->merge_bh || tape->merge_bh_size) {
1666			printk(KERN_ERR "ide-tape: merge_bh_size "
1667				"should be 0 now\n");
1668			tape->merge_bh_size = 0;
1669		}
1670		tape->merge_bh = ide_tape_kmalloc_buffer(tape, 0, 0);
1671		if (!tape->merge_bh)
1672			return -ENOMEM;
1673		tape->chrdev_dir = IDETAPE_DIR_WRITE;
1674		idetape_init_merge_buffer(tape);
1675
1676		/*
1677		 * Issue a write 0 command to ensure that DSC handshake is
1678		 * switched from completion mode to buffer available mode. No
1679		 * point in issuing this if DSC overlap isn't supported, some
1680		 * drives (Seagate STT3401A) will return an error.
1681		 */
1682		if (drive->dsc_overlap) {
1683			ssize_t retval = idetape_queue_rw_tail(drive,
1684							REQ_IDETAPE_WRITE, 0,
1685							tape->merge_bh);
1686			if (retval < 0) {
1687				ide_tape_kfree_buffer(tape);
1688				tape->merge_bh = NULL;
1689				tape->chrdev_dir = IDETAPE_DIR_NONE;
1690				return retval;
1691			}
1692		}
1693	}
1694	if (count == 0)
1695		return (0);
1696	if (tape->merge_bh_size) {
1697		if (tape->merge_bh_size >= tape->buffer_size) {
1698			printk(KERN_ERR "ide-tape: bug: merge buf too big\n");
1699			tape->merge_bh_size = 0;
1700		}
1701		actually_written = min((unsigned int)
1702				(tape->buffer_size - tape->merge_bh_size),
1703				(unsigned int)count);
1704		if (idetape_copy_stage_from_user(tape, buf, actually_written))
1705				ret = -EFAULT;
1706		buf += actually_written;
1707		tape->merge_bh_size += actually_written;
1708		count -= actually_written;
1709
1710		if (tape->merge_bh_size == tape->buffer_size) {
1711			ssize_t retval;
1712			tape->merge_bh_size = 0;
1713			retval = idetape_add_chrdev_write_request(drive, ctl);
1714			if (retval <= 0)
1715				return (retval);
1716		}
1717	}
1718	while (count >= tape->buffer_size) {
1719		ssize_t retval;
1720		if (idetape_copy_stage_from_user(tape, buf, tape->buffer_size))
1721			ret = -EFAULT;
1722		buf += tape->buffer_size;
1723		count -= tape->buffer_size;
1724		retval = idetape_add_chrdev_write_request(drive, ctl);
1725		actually_written += tape->buffer_size;
1726		if (retval <= 0)
1727			return (retval);
1728	}
1729	if (count) {
1730		actually_written += count;
1731		if (idetape_copy_stage_from_user(tape, buf, count))
1732			ret = -EFAULT;
1733		tape->merge_bh_size += count;
1734	}
1735	return ret ? ret : actually_written;
1736}
1737
1738static int idetape_write_filemark(ide_drive_t *drive)
1739{
1740	struct ide_tape_obj *tape = drive->driver_data;
1741	struct ide_atapi_pc pc;
1742
1743	/* Write a filemark */
1744	idetape_create_write_filemark_cmd(drive, &pc, 1);
1745	if (ide_queue_pc_tail(drive, tape->disk, &pc)) {
1746		printk(KERN_ERR "ide-tape: Couldn't write a filemark\n");
1747		return -EIO;
1748	}
1749	return 0;
1750}
1751
1752/*
1753 * Called from idetape_chrdev_ioctl when the general mtio MTIOCTOP ioctl is
1754 * requested.
1755 *
1756 * Note: MTBSF and MTBSFM are not supported when the tape doesn't support
1757 * spacing over filemarks in the reverse direction. In this case, MTFSFM is also
1758 * usually not supported.
1759 *
1760 * The following commands are currently not supported:
1761 *
1762 * MTFSS, MTBSS, MTWSM, MTSETDENSITY, MTSETDRVBUFFER, MT_ST_BOOLEANS,
1763 * MT_ST_WRITE_THRESHOLD.
1764 */
1765static int idetape_mtioctop(ide_drive_t *drive, short mt_op, int mt_count)
1766{
1767	idetape_tape_t *tape = drive->driver_data;
1768	struct gendisk *disk = tape->disk;
1769	struct ide_atapi_pc pc;
1770	int i, retval;
1771
1772	debug_log(DBG_ERR, "Handling MTIOCTOP ioctl: mt_op=%d, mt_count=%d\n",
1773			mt_op, mt_count);
1774
1775	switch (mt_op) {
1776	case MTFSF:
1777	case MTFSFM:
1778	case MTBSF:
1779	case MTBSFM:
1780		if (!mt_count)
1781			return 0;
1782		return idetape_space_over_filemarks(drive, mt_op, mt_count);
1783	default:
1784		break;
1785	}
1786
1787	switch (mt_op) {
1788	case MTWEOF:
1789		if (tape->write_prot)
1790			return -EACCES;
1791		ide_tape_discard_merge_buffer(drive, 1);
1792		for (i = 0; i < mt_count; i++) {
1793			retval = idetape_write_filemark(drive);
1794			if (retval)
1795				return retval;
1796		}
1797		return 0;
1798	case MTREW:
1799		ide_tape_discard_merge_buffer(drive, 0);
1800		if (idetape_rewind_tape(drive))
1801			return -EIO;
1802		return 0;
1803	case MTLOAD:
1804		ide_tape_discard_merge_buffer(drive, 0);
1805		return ide_do_start_stop(drive, disk, IDETAPE_LU_LOAD_MASK);
1806	case MTUNLOAD:
1807	case MTOFFL:
1808		/*
1809		 * If door is locked, attempt to unlock before
1810		 * attempting to eject.
1811		 */
1812		if (tape->door_locked) {
1813			if (!ide_set_media_lock(drive, disk, 0))
1814				tape->door_locked = DOOR_UNLOCKED;
1815		}
1816		ide_tape_discard_merge_buffer(drive, 0);
1817		retval = ide_do_start_stop(drive, disk, !IDETAPE_LU_LOAD_MASK);
1818		if (!retval)
1819			clear_bit(IDE_AFLAG_MEDIUM_PRESENT, &drive->atapi_flags);
1820		return retval;
1821	case MTNOP:
1822		ide_tape_discard_merge_buffer(drive, 0);
1823		return idetape_flush_tape_buffers(drive);
1824	case MTRETEN:
1825		ide_tape_discard_merge_buffer(drive, 0);
1826		return ide_do_start_stop(drive, disk,
1827			IDETAPE_LU_RETENSION_MASK | IDETAPE_LU_LOAD_MASK);
1828	case MTEOM:
1829		idetape_create_space_cmd(&pc, 0, IDETAPE_SPACE_TO_EOD);
1830		return ide_queue_pc_tail(drive, disk, &pc);
1831	case MTERASE:
1832		(void)idetape_rewind_tape(drive);
1833		idetape_create_erase_cmd(&pc);
1834		return ide_queue_pc_tail(drive, disk, &pc);
1835	case MTSETBLK:
1836		if (mt_count) {
1837			if (mt_count < tape->blk_size ||
1838			    mt_count % tape->blk_size)
1839				return -EIO;
1840			tape->user_bs_factor = mt_count / tape->blk_size;
1841			clear_bit(IDE_AFLAG_DETECT_BS, &drive->atapi_flags);
1842		} else
1843			set_bit(IDE_AFLAG_DETECT_BS, &drive->atapi_flags);
1844		return 0;
1845	case MTSEEK:
1846		ide_tape_discard_merge_buffer(drive, 0);
1847		return idetape_position_tape(drive,
1848			mt_count * tape->user_bs_factor, tape->partition, 0);
1849	case MTSETPART:
1850		ide_tape_discard_merge_buffer(drive, 0);
1851		return idetape_position_tape(drive, 0, mt_count, 0);
1852	case MTFSR:
1853	case MTBSR:
1854	case MTLOCK:
1855		retval = ide_set_media_lock(drive, disk, 1);
1856		if (retval)
1857			return retval;
1858		tape->door_locked = DOOR_EXPLICITLY_LOCKED;
1859		return 0;
1860	case MTUNLOCK:
1861		retval = ide_set_media_lock(drive, disk, 0);
1862		if (retval)
1863			return retval;
1864		tape->door_locked = DOOR_UNLOCKED;
1865		return 0;
1866	default:
1867		printk(KERN_ERR "ide-tape: MTIO operation %d not supported\n",
1868				mt_op);
1869		return -EIO;
1870	}
1871}
1872
1873/*
1874 * Our character device ioctls. General mtio.h magnetic io commands are
1875 * supported here, and not in the corresponding block interface. Our own
1876 * ide-tape ioctls are supported on both interfaces.
1877 */
1878static int idetape_chrdev_ioctl(struct inode *inode, struct file *file,
1879				unsigned int cmd, unsigned long arg)
1880{
1881	struct ide_tape_obj *tape = ide_tape_f(file);
1882	ide_drive_t *drive = tape->drive;
1883	struct mtop mtop;
1884	struct mtget mtget;
1885	struct mtpos mtpos;
1886	int block_offset = 0, position = tape->first_frame;
1887	void __user *argp = (void __user *)arg;
1888
1889	debug_log(DBG_CHRDEV, "Enter %s, cmd=%u\n", __func__, cmd);
1890
1891	if (tape->chrdev_dir == IDETAPE_DIR_WRITE) {
1892		ide_tape_flush_merge_buffer(drive);
1893		idetape_flush_tape_buffers(drive);
1894	}
1895	if (cmd == MTIOCGET || cmd == MTIOCPOS) {
1896		block_offset = tape->merge_bh_size /
1897			(tape->blk_size * tape->user_bs_factor);
1898		position = idetape_read_position(drive);
1899		if (position < 0)
1900			return -EIO;
1901	}
1902	switch (cmd) {
1903	case MTIOCTOP:
1904		if (copy_from_user(&mtop, argp, sizeof(struct mtop)))
1905			return -EFAULT;
1906		return idetape_mtioctop(drive, mtop.mt_op, mtop.mt_count);
1907	case MTIOCGET:
1908		memset(&mtget, 0, sizeof(struct mtget));
1909		mtget.mt_type = MT_ISSCSI2;
1910		mtget.mt_blkno = position / tape->user_bs_factor - block_offset;
1911		mtget.mt_dsreg =
1912			((tape->blk_size * tape->user_bs_factor)
1913			 << MT_ST_BLKSIZE_SHIFT) & MT_ST_BLKSIZE_MASK;
1914
1915		if (tape->drv_write_prot)
1916			mtget.mt_gstat |= GMT_WR_PROT(0xffffffff);
1917
1918		if (copy_to_user(argp, &mtget, sizeof(struct mtget)))
1919			return -EFAULT;
1920		return 0;
1921	case MTIOCPOS:
1922		mtpos.mt_blkno = position / tape->user_bs_factor - block_offset;
1923		if (copy_to_user(argp, &mtpos, sizeof(struct mtpos)))
1924			return -EFAULT;
1925		return 0;
1926	default:
1927		if (tape->chrdev_dir == IDETAPE_DIR_READ)
1928			ide_tape_discard_merge_buffer(drive, 1);
1929		return idetape_blkdev_ioctl(drive, cmd, arg);
1930	}
1931}
1932
1933/*
1934 * Do a mode sense page 0 with block descriptor and if it succeeds set the tape
1935 * block size with the reported value.
1936 */
1937static void ide_tape_get_bsize_from_bdesc(ide_drive_t *drive)
1938{
1939	idetape_tape_t *tape = drive->driver_data;
1940	struct ide_atapi_pc pc;
1941
1942	idetape_create_mode_sense_cmd(&pc, IDETAPE_BLOCK_DESCRIPTOR);
1943	if (ide_queue_pc_tail(drive, tape->disk, &pc)) {
1944		printk(KERN_ERR "ide-tape: Can't get block descriptor\n");
1945		if (tape->blk_size == 0) {
1946			printk(KERN_WARNING "ide-tape: Cannot deal with zero "
1947					    "block size, assuming 32k\n");
1948			tape->blk_size = 32768;
1949		}
1950		return;
1951	}
1952	tape->blk_size = (pc.buf[4 + 5] << 16) +
1953				(pc.buf[4 + 6] << 8)  +
1954				 pc.buf[4 + 7];
1955	tape->drv_write_prot = (pc.buf[2] & 0x80) >> 7;
1956}
1957
1958static int idetape_chrdev_open(struct inode *inode, struct file *filp)
1959{
1960	unsigned int minor = iminor(inode), i = minor & ~0xc0;
1961	ide_drive_t *drive;
1962	idetape_tape_t *tape;
1963	int retval;
1964
1965	if (i >= MAX_HWIFS * MAX_DRIVES)
1966		return -ENXIO;
1967
1968	lock_kernel();
1969	tape = ide_tape_chrdev_get(i);
1970	if (!tape) {
1971		unlock_kernel();
1972		return -ENXIO;
1973	}
1974
1975	debug_log(DBG_CHRDEV, "Enter %s\n", __func__);
1976
1977	/*
1978	 * We really want to do nonseekable_open(inode, filp); here, but some
1979	 * versions of tar incorrectly call lseek on tapes and bail out if that
1980	 * fails.  So we disallow pread() and pwrite(), but permit lseeks.
1981	 */
1982	filp->f_mode &= ~(FMODE_PREAD | FMODE_PWRITE);
1983
1984	drive = tape->drive;
1985
1986	filp->private_data = tape;
1987
1988	if (test_and_set_bit(IDE_AFLAG_BUSY, &drive->atapi_flags)) {
1989		retval = -EBUSY;
1990		goto out_put_tape;
1991	}
1992
1993	retval = idetape_wait_ready(drive, 60 * HZ);
1994	if (retval) {
1995		clear_bit(IDE_AFLAG_BUSY, &drive->atapi_flags);
1996		printk(KERN_ERR "ide-tape: %s: drive not ready\n", tape->name);
1997		goto out_put_tape;
1998	}
1999
2000	idetape_read_position(drive);
2001	if (!test_bit(IDE_AFLAG_ADDRESS_VALID, &drive->atapi_flags))
2002		(void)idetape_rewind_tape(drive);
2003
2004	/* Read block size and write protect status from drive. */
2005	ide_tape_get_bsize_from_bdesc(drive);
2006
2007	/* Set write protect flag if device is opened as read-only. */
2008	if ((filp->f_flags & O_ACCMODE) == O_RDONLY)
2009		tape->write_prot = 1;
2010	else
2011		tape->write_prot = tape->drv_write_prot;
2012
2013	/* Make sure drive isn't write protected if user wants to write. */
2014	if (tape->write_prot) {
2015		if ((filp->f_flags & O_ACCMODE) == O_WRONLY ||
2016		    (filp->f_flags & O_ACCMODE) == O_RDWR) {
2017			clear_bit(IDE_AFLAG_BUSY, &drive->atapi_flags);
2018			retval = -EROFS;
2019			goto out_put_tape;
2020		}
2021	}
2022
2023	/* Lock the tape drive door so user can't eject. */
2024	if (tape->chrdev_dir == IDETAPE_DIR_NONE) {
2025		if (!ide_set_media_lock(drive, tape->disk, 1)) {
2026			if (tape->door_locked != DOOR_EXPLICITLY_LOCKED)
2027				tape->door_locked = DOOR_LOCKED;
2028		}
2029	}
2030	unlock_kernel();
2031	return 0;
2032
2033out_put_tape:
2034	ide_tape_put(tape);
2035	unlock_kernel();
2036	return retval;
2037}
2038
2039static void idetape_write_release(ide_drive_t *drive, unsigned int minor)
2040{
2041	idetape_tape_t *tape = drive->driver_data;
2042
2043	ide_tape_flush_merge_buffer(drive);
2044	tape->merge_bh = ide_tape_kmalloc_buffer(tape, 1, 0);
2045	if (tape->merge_bh != NULL) {
2046		idetape_pad_zeros(drive, tape->blk_size *
2047				(tape->user_bs_factor - 1));
2048		ide_tape_kfree_buffer(tape);
2049		tape->merge_bh = NULL;
2050	}
2051	idetape_write_filemark(drive);
2052	idetape_flush_tape_buffers(drive);
2053	idetape_flush_tape_buffers(drive);
2054}
2055
2056static int idetape_chrdev_release(struct inode *inode, struct file *filp)
2057{
2058	struct ide_tape_obj *tape = ide_tape_f(filp);
2059	ide_drive_t *drive = tape->drive;
2060	unsigned int minor = iminor(inode);
2061
2062	lock_kernel();
2063	tape = drive->driver_data;
2064
2065	debug_log(DBG_CHRDEV, "Enter %s\n", __func__);
2066
2067	if (tape->chrdev_dir == IDETAPE_DIR_WRITE)
2068		idetape_write_release(drive, minor);
2069	if (tape->chrdev_dir == IDETAPE_DIR_READ) {
2070		if (minor < 128)
2071			ide_tape_discard_merge_buffer(drive, 1);
2072	}
2073
2074	if (minor < 128 && test_bit(IDE_AFLAG_MEDIUM_PRESENT, &drive->atapi_flags))
2075		(void) idetape_rewind_tape(drive);
2076	if (tape->chrdev_dir == IDETAPE_DIR_NONE) {
2077		if (tape->door_locked == DOOR_LOCKED) {
2078			if (!ide_set_media_lock(drive, tape->disk, 0))
2079				tape->door_locked = DOOR_UNLOCKED;
2080		}
2081	}
2082	clear_bit(IDE_AFLAG_BUSY, &drive->atapi_flags);
2083	ide_tape_put(tape);
2084	unlock_kernel();
2085	return 0;
2086}
2087
2088static void idetape_get_inquiry_results(ide_drive_t *drive)
2089{
2090	idetape_tape_t *tape = drive->driver_data;
2091	struct ide_atapi_pc pc;
2092	char fw_rev[4], vendor_id[8], product_id[16];
2093
2094	idetape_create_inquiry_cmd(&pc);
2095	if (ide_queue_pc_tail(drive, tape->disk, &pc)) {
2096		printk(KERN_ERR "ide-tape: %s: can't get INQUIRY results\n",
2097				tape->name);
2098		return;
2099	}
2100	memcpy(vendor_id, &pc.buf[8], 8);
2101	memcpy(product_id, &pc.buf[16], 16);
2102	memcpy(fw_rev, &pc.buf[32], 4);
2103
2104	ide_fixstring(vendor_id, 8, 0);
2105	ide_fixstring(product_id, 16, 0);
2106	ide_fixstring(fw_rev, 4, 0);
2107
2108	printk(KERN_INFO "ide-tape: %s <-> %s: %.8s %.16s rev %.4s\n",
2109			drive->name, tape->name, vendor_id, product_id, fw_rev);
2110}
2111
2112/*
2113 * Ask the tape about its various parameters. In particular, we will adjust our
2114 * data transfer buffer	size to the recommended value as returned by the tape.
2115 */
2116static void idetape_get_mode_sense_results(ide_drive_t *drive)
2117{
2118	idetape_tape_t *tape = drive->driver_data;
2119	struct ide_atapi_pc pc;
2120	u8 *caps;
2121	u8 speed, max_speed;
2122
2123	idetape_create_mode_sense_cmd(&pc, IDETAPE_CAPABILITIES_PAGE);
2124	if (ide_queue_pc_tail(drive, tape->disk, &pc)) {
2125		printk(KERN_ERR "ide-tape: Can't get tape parameters - assuming"
2126				" some default values\n");
2127		tape->blk_size = 512;
2128		put_unaligned(52,   (u16 *)&tape->caps[12]);
2129		put_unaligned(540,  (u16 *)&tape->caps[14]);
2130		put_unaligned(6*52, (u16 *)&tape->caps[16]);
2131		return;
2132	}
2133	caps = pc.buf + 4 + pc.buf[3];
2134
2135	/* convert to host order and save for later use */
2136	speed = be16_to_cpup((__be16 *)&caps[14]);
2137	max_speed = be16_to_cpup((__be16 *)&caps[8]);
2138
2139	*(u16 *)&caps[8] = max_speed;
2140	*(u16 *)&caps[12] = be16_to_cpup((__be16 *)&caps[12]);
2141	*(u16 *)&caps[14] = speed;
2142	*(u16 *)&caps[16] = be16_to_cpup((__be16 *)&caps[16]);
2143
2144	if (!speed) {
2145		printk(KERN_INFO "ide-tape: %s: invalid tape speed "
2146				"(assuming 650KB/sec)\n", drive->name);
2147		*(u16 *)&caps[14] = 650;
2148	}
2149	if (!max_speed) {
2150		printk(KERN_INFO "ide-tape: %s: invalid max_speed "
2151				"(assuming 650KB/sec)\n", drive->name);
2152		*(u16 *)&caps[8] = 650;
2153	}
2154
2155	memcpy(&tape->caps, caps, 20);
2156
2157	/* device lacks locking support according to capabilities page */
2158	if ((caps[6] & 1) == 0)
2159		drive->atapi_flags |= IDE_AFLAG_NO_DOORLOCK;
2160
2161	if (caps[7] & 0x02)
2162		tape->blk_size = 512;
2163	else if (caps[7] & 0x04)
2164		tape->blk_size = 1024;
2165}
2166
2167#ifdef CONFIG_IDE_PROC_FS
2168#define ide_tape_devset_get(name, field) \
2169static int get_##name(ide_drive_t *drive) \
2170{ \
2171	idetape_tape_t *tape = drive->driver_data; \
2172	return tape->field; \
2173}
2174
2175#define ide_tape_devset_set(name, field) \
2176static int set_##name(ide_drive_t *drive, int arg) \
2177{ \
2178	idetape_tape_t *tape = drive->driver_data; \
2179	tape->field = arg; \
2180	return 0; \
2181}
2182
2183#define ide_tape_devset_rw_field(_name, _field) \
2184ide_tape_devset_get(_name, _field) \
2185ide_tape_devset_set(_name, _field) \
2186IDE_DEVSET(_name, DS_SYNC, get_##_name, set_##_name)
2187
2188#define ide_tape_devset_r_field(_name, _field) \
2189ide_tape_devset_get(_name, _field) \
2190IDE_DEVSET(_name, 0, get_##_name, NULL)
2191
2192static int mulf_tdsc(ide_drive_t *drive)	{ return 1000; }
2193static int divf_tdsc(ide_drive_t *drive)	{ return   HZ; }
2194static int divf_buffer(ide_drive_t *drive)	{ return    2; }
2195static int divf_buffer_size(ide_drive_t *drive)	{ return 1024; }
2196
2197ide_devset_rw_field(dsc_overlap, dsc_overlap);
2198
2199ide_tape_devset_rw_field(debug_mask, debug_mask);
2200ide_tape_devset_rw_field(tdsc, best_dsc_rw_freq);
2201
2202ide_tape_devset_r_field(avg_speed, avg_speed);
2203ide_tape_devset_r_field(speed, caps[14]);
2204ide_tape_devset_r_field(buffer, caps[16]);
2205ide_tape_devset_r_field(buffer_size, buffer_size);
2206
2207static const struct ide_proc_devset idetape_settings[] = {
2208	__IDE_PROC_DEVSET(avg_speed,	0, 0xffff, NULL, NULL),
2209	__IDE_PROC_DEVSET(buffer,	0, 0xffff, NULL, divf_buffer),
2210	__IDE_PROC_DEVSET(buffer_size,	0, 0xffff, NULL, divf_buffer_size),
2211	__IDE_PROC_DEVSET(debug_mask,	0, 0xffff, NULL, NULL),
2212	__IDE_PROC_DEVSET(dsc_overlap,	0,      1, NULL, NULL),
2213	__IDE_PROC_DEVSET(speed,	0, 0xffff, NULL, NULL),
2214	__IDE_PROC_DEVSET(tdsc,		IDETAPE_DSC_RW_MIN, IDETAPE_DSC_RW_MAX,
2215					mulf_tdsc, divf_tdsc),
2216	{ 0 },
2217};
2218#endif
2219
2220/*
2221 * The function below is called to:
2222 *
2223 * 1. Initialize our various state variables.
2224 * 2. Ask the tape for its capabilities.
2225 * 3. Allocate a buffer which will be used for data transfer. The buffer size
2226 * is chosen based on the recommendation which we received in step 2.
2227 *
2228 * Note that at this point ide.c already assigned us an irq, so that we can
2229 * queue requests here and wait for their completion.
2230 */
2231static void idetape_setup(ide_drive_t *drive, idetape_tape_t *tape, int minor)
2232{
2233	unsigned long t;
2234	int speed;
2235	int buffer_size;
2236	u8 gcw[2];
2237	u16 *ctl = (u16 *)&tape->caps[12];
2238
2239	drive->pc_callback = ide_tape_callback;
2240
2241	spin_lock_init(&tape->lock);
2242	drive->dsc_overlap = 1;
2243	if (drive->hwif->host_flags & IDE_HFLAG_NO_DSC) {
2244		printk(KERN_INFO "ide-tape: %s: disabling DSC overlap\n",
2245				 tape->name);
2246		drive->dsc_overlap = 0;
2247	}
2248	/* Seagate Travan drives do not support DSC overlap. */
2249	if (strstr((char *)&drive->id[ATA_ID_PROD], "Seagate STT3401"))
2250		drive->dsc_overlap = 0;
2251	tape->minor = minor;
2252	tape->name[0] = 'h';
2253	tape->name[1] = 't';
2254	tape->name[2] = '0' + minor;
2255	tape->chrdev_dir = IDETAPE_DIR_NONE;
2256
2257	*((u16 *)&gcw) = drive->id[ATA_ID_CONFIG];
2258
2259	/* Command packet DRQ type */
2260	if (((gcw[0] & 0x60) >> 5) == 1)
2261		set_bit(IDE_AFLAG_DRQ_INTERRUPT, &drive->atapi_flags);
2262
2263	idetape_get_inquiry_results(drive);
2264	idetape_get_mode_sense_results(drive);
2265	ide_tape_get_bsize_from_bdesc(drive);
2266	tape->user_bs_factor = 1;
2267	tape->buffer_size = *ctl * tape->blk_size;
2268	while (tape->buffer_size > 0xffff) {
2269		printk(KERN_NOTICE "ide-tape: decreasing stage size\n");
2270		*ctl /= 2;
2271		tape->buffer_size = *ctl * tape->blk_size;
2272	}
2273	buffer_size = tape->buffer_size;
2274	tape->pages_per_buffer = buffer_size / PAGE_SIZE;
2275	if (buffer_size % PAGE_SIZE) {
2276		tape->pages_per_buffer++;
2277		tape->excess_bh_size = PAGE_SIZE - buffer_size % PAGE_SIZE;
2278	}
2279
2280	/* select the "best" DSC read/write polling freq */
2281	speed = max(*(u16 *)&tape->caps[14], *(u16 *)&tape->caps[8]);
2282
2283	t = (IDETAPE_FIFO_THRESHOLD * tape->buffer_size * HZ) / (speed * 1000);
2284
2285	/*
2286	 * Ensure that the number we got makes sense; limit it within
2287	 * IDETAPE_DSC_RW_MIN and IDETAPE_DSC_RW_MAX.
2288	 */
2289	tape->best_dsc_rw_freq = clamp_t(unsigned long, t, IDETAPE_DSC_RW_MIN,
2290					 IDETAPE_DSC_RW_MAX);
2291	printk(KERN_INFO "ide-tape: %s <-> %s: %dKBps, %d*%dkB buffer, "
2292		"%lums tDSC%s\n",
2293		drive->name, tape->name, *(u16 *)&tape->caps[14],
2294		(*(u16 *)&tape->caps[16] * 512) / tape->buffer_size,
2295		tape->buffer_size / 1024,
2296		tape->best_dsc_rw_freq * 1000 / HZ,
2297		drive->using_dma ? ", DMA":"");
2298
2299	ide_proc_register_driver(drive, tape->driver);
2300}
2301
2302static void ide_tape_remove(ide_drive_t *drive)
2303{
2304	idetape_tape_t *tape = drive->driver_data;
2305
2306	ide_proc_unregister_driver(drive, tape->driver);
2307
2308	ide_unregister_region(tape->disk);
2309
2310	ide_tape_put(tape);
2311}
2312
2313static void ide_tape_release(struct kref *kref)
2314{
2315	struct ide_tape_obj *tape = to_ide_tape(kref);
2316	ide_drive_t *drive = tape->drive;
2317	struct gendisk *g = tape->disk;
2318
2319	BUG_ON(tape->merge_bh_size);
2320
2321	drive->dsc_overlap = 0;
2322	drive->driver_data = NULL;
2323	device_destroy(idetape_sysfs_class, MKDEV(IDETAPE_MAJOR, tape->minor));
2324	device_destroy(idetape_sysfs_class,
2325			MKDEV(IDETAPE_MAJOR, tape->minor + 128));
2326	idetape_devs[tape->minor] = NULL;
2327	g->private_data = NULL;
2328	put_disk(g);
2329	kfree(tape);
2330}
2331
2332#ifdef CONFIG_IDE_PROC_FS
2333static int proc_idetape_read_name
2334	(char *page, char **start, off_t off, int count, int *eof, void *data)
2335{
2336	ide_drive_t	*drive = (ide_drive_t *) data;
2337	idetape_tape_t	*tape = drive->driver_data;
2338	char		*out = page;
2339	int		len;
2340
2341	len = sprintf(out, "%s\n", tape->name);
2342	PROC_IDE_READ_RETURN(page, start, off, count, eof, len);
2343}
2344
2345static ide_proc_entry_t idetape_proc[] = {
2346	{ "capacity",	S_IFREG|S_IRUGO,	proc_ide_read_capacity, NULL },
2347	{ "name",	S_IFREG|S_IRUGO,	proc_idetape_read_name,	NULL },
2348	{ NULL, 0, NULL, NULL }
2349};
2350#endif
2351
2352static int ide_tape_probe(ide_drive_t *);
2353
2354static ide_driver_t idetape_driver = {
2355	.gen_driver = {
2356		.owner		= THIS_MODULE,
2357		.name		= "ide-tape",
2358		.bus		= &ide_bus_type,
2359	},
2360	.probe			= ide_tape_probe,
2361	.remove			= ide_tape_remove,
2362	.version		= IDETAPE_VERSION,
2363	.media			= ide_tape,
2364	.do_request		= idetape_do_request,
2365	.end_request		= idetape_end_request,
2366	.error			= __ide_error,
2367#ifdef CONFIG_IDE_PROC_FS
2368	.proc			= idetape_proc,
2369	.settings		= idetape_settings,
2370#endif
2371};
2372
2373/* Our character device supporting functions, passed to register_chrdev. */
2374static const struct file_operations idetape_fops = {
2375	.owner		= THIS_MODULE,
2376	.read		= idetape_chrdev_read,
2377	.write		= idetape_chrdev_write,
2378	.ioctl		= idetape_chrdev_ioctl,
2379	.open		= idetape_chrdev_open,
2380	.release	= idetape_chrdev_release,
2381};
2382
2383static int idetape_open(struct inode *inode, struct file *filp)
2384{
2385	struct gendisk *disk = inode->i_bdev->bd_disk;
2386	struct ide_tape_obj *tape;
2387
2388	tape = ide_tape_get(disk);
2389	if (!tape)
2390		return -ENXIO;
2391
2392	return 0;
2393}
2394
2395static int idetape_release(struct inode *inode, struct file *filp)
2396{
2397	struct gendisk *disk = inode->i_bdev->bd_disk;
2398	struct ide_tape_obj *tape = ide_tape_g(disk);
2399
2400	ide_tape_put(tape);
2401
2402	return 0;
2403}
2404
2405static int idetape_ioctl(struct inode *inode, struct file *file,
2406			unsigned int cmd, unsigned long arg)
2407{
2408	struct block_device *bdev = inode->i_bdev;
2409	struct ide_tape_obj *tape = ide_tape_g(bdev->bd_disk);
2410	ide_drive_t *drive = tape->drive;
2411	int err = generic_ide_ioctl(drive, file, bdev, cmd, arg);
2412	if (err == -EINVAL)
2413		err = idetape_blkdev_ioctl(drive, cmd, arg);
2414	return err;
2415}
2416
2417static struct block_device_operations idetape_block_ops = {
2418	.owner		= THIS_MODULE,
2419	.open		= idetape_open,
2420	.release	= idetape_release,
2421	.ioctl		= idetape_ioctl,
2422};
2423
2424static int ide_tape_probe(ide_drive_t *drive)
2425{
2426	idetape_tape_t *tape;
2427	struct gendisk *g;
2428	int minor;
2429
2430	if (!strstr("ide-tape", drive->driver_req))
2431		goto failed;
2432
2433	if (drive->media != ide_tape)
2434		goto failed;
2435
2436	if (drive->id_read == 1 && !ide_check_atapi_device(drive, DRV_NAME)) {
2437		printk(KERN_ERR "ide-tape: %s: not supported by this version of"
2438				" the driver\n", drive->name);
2439		goto failed;
2440	}
2441	tape = kzalloc(sizeof(idetape_tape_t), GFP_KERNEL);
2442	if (tape == NULL) {
2443		printk(KERN_ERR "ide-tape: %s: Can't allocate a tape struct\n",
2444				drive->name);
2445		goto failed;
2446	}
2447
2448	g = alloc_disk(1 << PARTN_BITS);
2449	if (!g)
2450		goto out_free_tape;
2451
2452	ide_init_disk(g, drive);
2453
2454	kref_init(&tape->kref);
2455
2456	tape->drive = drive;
2457	tape->driver = &idetape_driver;
2458	tape->disk = g;
2459
2460	g->private_data = &tape->driver;
2461
2462	drive->driver_data = tape;
2463
2464	mutex_lock(&idetape_ref_mutex);
2465	for (minor = 0; idetape_devs[minor]; minor++)
2466		;
2467	idetape_devs[minor] = tape;
2468	mutex_unlock(&idetape_ref_mutex);
2469
2470	idetape_setup(drive, tape, minor);
2471
2472	device_create_drvdata(idetape_sysfs_class, &drive->gendev,
2473			      MKDEV(IDETAPE_MAJOR, minor), NULL,
2474			      "%s", tape->name);
2475	device_create_drvdata(idetape_sysfs_class, &drive->gendev,
2476			      MKDEV(IDETAPE_MAJOR, minor + 128), NULL,
2477			      "n%s", tape->name);
2478
2479	g->fops = &idetape_block_ops;
2480	ide_register_region(g);
2481
2482	return 0;
2483
2484out_free_tape:
2485	kfree(tape);
2486failed:
2487	return -ENODEV;
2488}
2489
2490static void __exit idetape_exit(void)
2491{
2492	driver_unregister(&idetape_driver.gen_driver);
2493	class_destroy(idetape_sysfs_class);
2494	unregister_chrdev(IDETAPE_MAJOR, "ht");
2495}
2496
2497static int __init idetape_init(void)
2498{
2499	int error = 1;
2500	idetape_sysfs_class = class_create(THIS_MODULE, "ide_tape");
2501	if (IS_ERR(idetape_sysfs_class)) {
2502		idetape_sysfs_class = NULL;
2503		printk(KERN_ERR "Unable to create sysfs class for ide tapes\n");
2504		error = -EBUSY;
2505		goto out;
2506	}
2507
2508	if (register_chrdev(IDETAPE_MAJOR, "ht", &idetape_fops)) {
2509		printk(KERN_ERR "ide-tape: Failed to register chrdev"
2510				" interface\n");
2511		error = -EBUSY;
2512		goto out_free_class;
2513	}
2514
2515	error = driver_register(&idetape_driver.gen_driver);
2516	if (error)
2517		goto out_free_driver;
2518
2519	return 0;
2520
2521out_free_driver:
2522	driver_unregister(&idetape_driver.gen_driver);
2523out_free_class:
2524	class_destroy(idetape_sysfs_class);
2525out:
2526	return error;
2527}
2528
2529MODULE_ALIAS("ide:*m-tape*");
2530module_init(idetape_init);
2531module_exit(idetape_exit);
2532MODULE_ALIAS_CHARDEV_MAJOR(IDETAPE_MAJOR);
2533MODULE_DESCRIPTION("ATAPI Streaming TAPE Driver");
2534MODULE_LICENSE("GPL");
2535