Linux Audio

Check our new training course

Loading...
v3.1
   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/seq_file.h>
  35#include <linux/slab.h>
  36#include <linux/pci.h>
  37#include <linux/ide.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
  50/* define to see debug info */
  51#undef IDETAPE_DEBUG_LOG
  52
  53#ifdef IDETAPE_DEBUG_LOG
  54#define ide_debug_log(lvl, fmt, args...) __ide_debug_log(lvl, fmt, ## args)
  55#else
  56#define ide_debug_log(lvl, fmt, args...) do {} while (0)
  57#endif
  58
  59/**************************** Tunable parameters *****************************/
  60/*
  61 * After each failed packet command we issue a request sense command and retry
  62 * the packet command IDETAPE_MAX_PC_RETRIES times.
  63 *
  64 * Setting IDETAPE_MAX_PC_RETRIES to 0 will disable retries.
  65 */
  66#define IDETAPE_MAX_PC_RETRIES		3
  67
  68/*
  69 * The following parameter is used to select the point in the internal tape fifo
  70 * in which we will start to refill the buffer. Decreasing the following
  71 * parameter will improve the system's latency and interactive response, while
  72 * using a high value might improve system throughput.
  73 */
  74#define IDETAPE_FIFO_THRESHOLD		2
  75
  76/*
  77 * DSC polling parameters.
  78 *
  79 * Polling for DSC (a single bit in the status register) is a very important
  80 * function in ide-tape. There are two cases in which we poll for DSC:
  81 *
  82 * 1. Before a read/write packet command, to ensure that we can transfer data
  83 * from/to the tape's data buffers, without causing an actual media access.
  84 * In case the tape is not ready yet, we take out our request from the device
  85 * request queue, so that ide.c could service requests from the other device
  86 * on the same interface in the meantime.
  87 *
  88 * 2. After the successful initialization of a "media access packet command",
  89 * which is a command that can take a long time to complete (the interval can
  90 * range from several seconds to even an hour). Again, we postpone our request
  91 * in the middle to free the bus for the other device. The polling frequency
  92 * here should be lower than the read/write frequency since those media access
  93 * commands are slow. We start from a "fast" frequency - IDETAPE_DSC_MA_FAST
  94 * (1 second), and if we don't receive DSC after IDETAPE_DSC_MA_THRESHOLD
  95 * (5 min), we switch it to a lower frequency - IDETAPE_DSC_MA_SLOW (1 min).
  96 *
  97 * We also set a timeout for the timer, in case something goes wrong. The
  98 * timeout should be longer then the maximum execution time of a tape operation.
  99 */
 100
 101/* DSC timings. */
 102#define IDETAPE_DSC_RW_MIN		5*HZ/100	/* 50 msec */
 103#define IDETAPE_DSC_RW_MAX		40*HZ/100	/* 400 msec */
 104#define IDETAPE_DSC_RW_TIMEOUT		2*60*HZ		/* 2 minutes */
 105#define IDETAPE_DSC_MA_FAST		2*HZ		/* 2 seconds */
 106#define IDETAPE_DSC_MA_THRESHOLD	5*60*HZ		/* 5 minutes */
 107#define IDETAPE_DSC_MA_SLOW		30*HZ		/* 30 seconds */
 108#define IDETAPE_DSC_MA_TIMEOUT		2*60*60*HZ	/* 2 hours */
 109
 110/*************************** End of tunable parameters ***********************/
 111
 112/* tape directions */
 113enum {
 114	IDETAPE_DIR_NONE  = (1 << 0),
 115	IDETAPE_DIR_READ  = (1 << 1),
 116	IDETAPE_DIR_WRITE = (1 << 2),
 117};
 118
 119/* Tape door status */
 120#define DOOR_UNLOCKED			0
 121#define DOOR_LOCKED			1
 122#define DOOR_EXPLICITLY_LOCKED		2
 123
 124/* Some defines for the SPACE command */
 125#define IDETAPE_SPACE_OVER_FILEMARK	1
 126#define IDETAPE_SPACE_TO_EOD		3
 127
 128/* Some defines for the LOAD UNLOAD command */
 129#define IDETAPE_LU_LOAD_MASK		1
 130#define IDETAPE_LU_RETENSION_MASK	2
 131#define IDETAPE_LU_EOT_MASK		4
 132
 133/* Structures related to the SELECT SENSE / MODE SENSE packet commands. */
 134#define IDETAPE_BLOCK_DESCRIPTOR	0
 135#define IDETAPE_CAPABILITIES_PAGE	0x2a
 136
 137/*
 138 * Most of our global data which we need to save even as we leave the driver due
 139 * to an interrupt or a timer event is stored in the struct defined below.
 140 */
 141typedef struct ide_tape_obj {
 142	ide_drive_t		*drive;
 143	struct ide_driver	*driver;
 144	struct gendisk		*disk;
 145	struct device		dev;
 146
 147	/* used by REQ_IDETAPE_{READ,WRITE} requests */
 148	struct ide_atapi_pc queued_pc;
 149
 150	/*
 151	 * DSC polling variables.
 152	 *
 153	 * While polling for DSC we use postponed_rq to postpone the current
 154	 * request so that ide.c will be able to service pending requests on the
 155	 * other device. Note that at most we will have only one DSC (usually
 156	 * data transfer) request in the device request queue.
 157	 */
 158	bool postponed_rq;
 159
 160	/* The time in which we started polling for DSC */
 161	unsigned long dsc_polling_start;
 162	/* Timer used to poll for dsc */
 163	struct timer_list dsc_timer;
 164	/* Read/Write dsc polling frequency */
 165	unsigned long best_dsc_rw_freq;
 166	unsigned long dsc_poll_freq;
 167	unsigned long dsc_timeout;
 168
 169	/* Read position information */
 170	u8 partition;
 171	/* Current block */
 172	unsigned int first_frame;
 173
 174	/* Last error information */
 175	u8 sense_key, asc, ascq;
 176
 177	/* Character device operation */
 178	unsigned int minor;
 179	/* device name */
 180	char name[4];
 181	/* Current character device data transfer direction */
 182	u8 chrdev_dir;
 183
 184	/* tape block size, usually 512 or 1024 bytes */
 185	unsigned short blk_size;
 186	int user_bs_factor;
 187
 188	/* Copy of the tape's Capabilities and Mechanical Page */
 189	u8 caps[20];
 190
 191	/*
 192	 * Active data transfer request parameters.
 193	 *
 194	 * At most, there is only one ide-tape originated data transfer request
 195	 * in the device request queue. This allows ide.c to easily service
 196	 * requests from the other device when we postpone our active request.
 197	 */
 198
 199	/* Data buffer size chosen based on the tape's recommendation */
 200	int buffer_size;
 201	/* Staging buffer of buffer_size bytes */
 202	void *buf;
 203	/* The read/write cursor */
 204	void *cur;
 205	/* The number of valid bytes in buf */
 206	size_t valid;
 207
 208	/* Measures average tape speed */
 209	unsigned long avg_time;
 210	int avg_size;
 211	int avg_speed;
 212
 213	/* the door is currently locked */
 214	int door_locked;
 215	/* the tape hardware is write protected */
 216	char drv_write_prot;
 217	/* the tape is write protected (hardware or opened as read-only) */
 218	char write_prot;
 219} idetape_tape_t;
 220
 221static DEFINE_MUTEX(ide_tape_mutex);
 222static DEFINE_MUTEX(idetape_ref_mutex);
 223
 224static DEFINE_MUTEX(idetape_chrdev_mutex);
 225
 226static struct class *idetape_sysfs_class;
 227
 228static void ide_tape_release(struct device *);
 229
 230static struct ide_tape_obj *idetape_devs[MAX_HWIFS * MAX_DRIVES];
 231
 232static struct ide_tape_obj *ide_tape_get(struct gendisk *disk, bool cdev,
 233					 unsigned int i)
 234{
 235	struct ide_tape_obj *tape = NULL;
 236
 237	mutex_lock(&idetape_ref_mutex);
 238
 239	if (cdev)
 240		tape = idetape_devs[i];
 241	else
 242		tape = ide_drv_g(disk, ide_tape_obj);
 243
 244	if (tape) {
 245		if (ide_device_get(tape->drive))
 246			tape = NULL;
 247		else
 248			get_device(&tape->dev);
 249	}
 250
 251	mutex_unlock(&idetape_ref_mutex);
 252	return tape;
 253}
 254
 255static void ide_tape_put(struct ide_tape_obj *tape)
 256{
 257	ide_drive_t *drive = tape->drive;
 258
 259	mutex_lock(&idetape_ref_mutex);
 260	put_device(&tape->dev);
 261	ide_device_put(drive);
 262	mutex_unlock(&idetape_ref_mutex);
 263}
 264
 265/*
 266 * called on each failed packet command retry to analyze the request sense. We
 267 * currently do not utilize this information.
 268 */
 269static void idetape_analyze_error(ide_drive_t *drive)
 270{
 271	idetape_tape_t *tape = drive->driver_data;
 272	struct ide_atapi_pc *pc = drive->failed_pc;
 273	struct request *rq = drive->hwif->rq;
 274	u8 *sense = bio_data(rq->bio);
 275
 276	tape->sense_key = sense[2] & 0xF;
 277	tape->asc       = sense[12];
 278	tape->ascq      = sense[13];
 279
 280	ide_debug_log(IDE_DBG_FUNC,
 281		      "cmd: 0x%x, sense key = %x, asc = %x, ascq = %x",
 282		      rq->cmd[0], tape->sense_key, tape->asc, tape->ascq);
 283
 284	/* correct remaining bytes to transfer */
 285	if (pc->flags & PC_FLAG_DMA_ERROR)
 286		rq->resid_len = tape->blk_size * get_unaligned_be32(&sense[3]);
 287
 288	/*
 289	 * If error was the result of a zero-length read or write command,
 290	 * with sense key=5, asc=0x22, ascq=0, let it slide.  Some drives
 291	 * (i.e. Seagate STT3401A Travan) don't support 0-length read/writes.
 292	 */
 293	if ((pc->c[0] == READ_6 || pc->c[0] == WRITE_6)
 294	    /* length == 0 */
 295	    && pc->c[4] == 0 && pc->c[3] == 0 && pc->c[2] == 0) {
 296		if (tape->sense_key == 5) {
 297			/* don't report an error, everything's ok */
 298			pc->error = 0;
 299			/* don't retry read/write */
 300			pc->flags |= PC_FLAG_ABORT;
 301		}
 302	}
 303	if (pc->c[0] == READ_6 && (sense[2] & 0x80)) {
 304		pc->error = IDE_DRV_ERROR_FILEMARK;
 305		pc->flags |= PC_FLAG_ABORT;
 306	}
 307	if (pc->c[0] == WRITE_6) {
 308		if ((sense[2] & 0x40) || (tape->sense_key == 0xd
 309		     && tape->asc == 0x0 && tape->ascq == 0x2)) {
 310			pc->error = IDE_DRV_ERROR_EOD;
 311			pc->flags |= PC_FLAG_ABORT;
 312		}
 313	}
 314	if (pc->c[0] == READ_6 || pc->c[0] == WRITE_6) {
 315		if (tape->sense_key == 8) {
 316			pc->error = IDE_DRV_ERROR_EOD;
 317			pc->flags |= PC_FLAG_ABORT;
 318		}
 319		if (!(pc->flags & PC_FLAG_ABORT) &&
 320		    (blk_rq_bytes(rq) - rq->resid_len))
 321			pc->retries = IDETAPE_MAX_PC_RETRIES + 1;
 322	}
 323}
 324
 325static void ide_tape_handle_dsc(ide_drive_t *);
 326
 327static int ide_tape_callback(ide_drive_t *drive, int dsc)
 328{
 329	idetape_tape_t *tape = drive->driver_data;
 330	struct ide_atapi_pc *pc = drive->pc;
 331	struct request *rq = drive->hwif->rq;
 332	int uptodate = pc->error ? 0 : 1;
 333	int err = uptodate ? 0 : IDE_DRV_ERROR_GENERAL;
 334
 335	ide_debug_log(IDE_DBG_FUNC, "cmd: 0x%x, dsc: %d, err: %d", rq->cmd[0],
 336		      dsc, err);
 337
 338	if (dsc)
 339		ide_tape_handle_dsc(drive);
 340
 341	if (drive->failed_pc == pc)
 342		drive->failed_pc = NULL;
 343
 344	if (pc->c[0] == REQUEST_SENSE) {
 345		if (uptodate)
 346			idetape_analyze_error(drive);
 347		else
 348			printk(KERN_ERR "ide-tape: Error in REQUEST SENSE "
 349					"itself - Aborting request!\n");
 350	} else if (pc->c[0] == READ_6 || pc->c[0] == WRITE_6) {
 351		unsigned int blocks =
 352			(blk_rq_bytes(rq) - rq->resid_len) / tape->blk_size;
 353
 354		tape->avg_size += blocks * tape->blk_size;
 355
 356		if (time_after_eq(jiffies, tape->avg_time + HZ)) {
 357			tape->avg_speed = tape->avg_size * HZ /
 358				(jiffies - tape->avg_time) / 1024;
 359			tape->avg_size = 0;
 360			tape->avg_time = jiffies;
 361		}
 362
 363		tape->first_frame += blocks;
 364
 365		if (pc->error) {
 366			uptodate = 0;
 367			err = pc->error;
 368		}
 369	}
 370	rq->errors = err;
 371
 372	return uptodate;
 373}
 374
 375/*
 376 * Postpone the current request so that ide.c will be able to service requests
 377 * from another device on the same port while we are polling for DSC.
 378 */
 379static void ide_tape_stall_queue(ide_drive_t *drive)
 380{
 381	idetape_tape_t *tape = drive->driver_data;
 382
 383	ide_debug_log(IDE_DBG_FUNC, "cmd: 0x%x, dsc_poll_freq: %lu",
 384		      drive->hwif->rq->cmd[0], tape->dsc_poll_freq);
 385
 386	tape->postponed_rq = true;
 387
 388	ide_stall_queue(drive, tape->dsc_poll_freq);
 389}
 390
 391static void ide_tape_handle_dsc(ide_drive_t *drive)
 392{
 393	idetape_tape_t *tape = drive->driver_data;
 394
 395	/* Media access command */
 396	tape->dsc_polling_start = jiffies;
 397	tape->dsc_poll_freq = IDETAPE_DSC_MA_FAST;
 398	tape->dsc_timeout = jiffies + IDETAPE_DSC_MA_TIMEOUT;
 399	/* Allow ide.c to handle other requests */
 400	ide_tape_stall_queue(drive);
 401}
 402
 403/*
 404 * Packet Command Interface
 405 *
 406 * The current Packet Command is available in drive->pc, and will not change
 407 * until we finish handling it. Each packet command is associated with a
 408 * callback function that will be called when the command is finished.
 409 *
 410 * The handling will be done in three stages:
 411 *
 412 * 1. ide_tape_issue_pc will send the packet command to the drive, and will set
 413 * the interrupt handler to ide_pc_intr.
 414 *
 415 * 2. On each interrupt, ide_pc_intr will be called. This step will be
 416 * repeated until the device signals us that no more interrupts will be issued.
 417 *
 418 * 3. ATAPI Tape media access commands have immediate status with a delayed
 419 * process. In case of a successful initiation of a media access packet command,
 420 * the DSC bit will be set when the actual execution of the command is finished.
 421 * Since the tape drive will not issue an interrupt, we have to poll for this
 422 * event. In this case, we define the request as "low priority request" by
 423 * setting rq_status to IDETAPE_RQ_POSTPONED, set a timer to poll for DSC and
 424 * exit the driver.
 425 *
 426 * ide.c will then give higher priority to requests which originate from the
 427 * other device, until will change rq_status to RQ_ACTIVE.
 428 *
 429 * 4. When the packet command is finished, it will be checked for errors.
 430 *
 431 * 5. In case an error was found, we queue a request sense packet command in
 432 * front of the request queue and retry the operation up to
 433 * IDETAPE_MAX_PC_RETRIES times.
 434 *
 435 * 6. In case no error was found, or we decided to give up and not to retry
 436 * again, the callback function will be called and then we will handle the next
 437 * request.
 438 */
 439
 440static ide_startstop_t ide_tape_issue_pc(ide_drive_t *drive,
 441					 struct ide_cmd *cmd,
 442					 struct ide_atapi_pc *pc)
 443{
 444	idetape_tape_t *tape = drive->driver_data;
 445	struct request *rq = drive->hwif->rq;
 446
 447	if (drive->failed_pc == NULL && pc->c[0] != REQUEST_SENSE)
 448		drive->failed_pc = pc;
 449
 450	/* Set the current packet command */
 451	drive->pc = pc;
 452
 453	if (pc->retries > IDETAPE_MAX_PC_RETRIES ||
 454		(pc->flags & PC_FLAG_ABORT)) {
 455
 456		/*
 457		 * We will "abort" retrying a packet command in case legitimate
 458		 * error code was received (crossing a filemark, or end of the
 459		 * media, for example).
 460		 */
 461		if (!(pc->flags & PC_FLAG_ABORT)) {
 462			if (!(pc->c[0] == TEST_UNIT_READY &&
 463			      tape->sense_key == 2 && tape->asc == 4 &&
 464			     (tape->ascq == 1 || tape->ascq == 8))) {
 465				printk(KERN_ERR "ide-tape: %s: I/O error, "
 466						"pc = %2x, key = %2x, "
 467						"asc = %2x, ascq = %2x\n",
 468						tape->name, pc->c[0],
 469						tape->sense_key, tape->asc,
 470						tape->ascq);
 471			}
 472			/* Giving up */
 473			pc->error = IDE_DRV_ERROR_GENERAL;
 474		}
 475
 476		drive->failed_pc = NULL;
 477		drive->pc_callback(drive, 0);
 478		ide_complete_rq(drive, -EIO, blk_rq_bytes(rq));
 479		return ide_stopped;
 480	}
 481	ide_debug_log(IDE_DBG_SENSE, "retry #%d, cmd: 0x%02x", pc->retries,
 482		      pc->c[0]);
 483
 484	pc->retries++;
 485
 486	return ide_issue_pc(drive, cmd);
 487}
 488
 489/* A mode sense command is used to "sense" tape parameters. */
 490static void idetape_create_mode_sense_cmd(struct ide_atapi_pc *pc, u8 page_code)
 491{
 492	ide_init_pc(pc);
 493	pc->c[0] = MODE_SENSE;
 494	if (page_code != IDETAPE_BLOCK_DESCRIPTOR)
 495		/* DBD = 1 - Don't return block descriptors */
 496		pc->c[1] = 8;
 497	pc->c[2] = page_code;
 498	/*
 499	 * Changed pc->c[3] to 0 (255 will at best return unused info).
 500	 *
 501	 * For SCSI this byte is defined as subpage instead of high byte
 502	 * of length and some IDE drives seem to interpret it this way
 503	 * and return an error when 255 is used.
 504	 */
 505	pc->c[3] = 0;
 506	/* We will just discard data in that case */
 507	pc->c[4] = 255;
 508	if (page_code == IDETAPE_BLOCK_DESCRIPTOR)
 509		pc->req_xfer = 12;
 510	else if (page_code == IDETAPE_CAPABILITIES_PAGE)
 511		pc->req_xfer = 24;
 512	else
 513		pc->req_xfer = 50;
 514}
 515
 516static ide_startstop_t idetape_media_access_finished(ide_drive_t *drive)
 517{
 518	ide_hwif_t *hwif = drive->hwif;
 519	idetape_tape_t *tape = drive->driver_data;
 520	struct ide_atapi_pc *pc = drive->pc;
 521	u8 stat;
 522
 523	stat = hwif->tp_ops->read_status(hwif);
 524
 525	if (stat & ATA_DSC) {
 526		if (stat & ATA_ERR) {
 527			/* Error detected */
 528			if (pc->c[0] != TEST_UNIT_READY)
 529				printk(KERN_ERR "ide-tape: %s: I/O error, ",
 530						tape->name);
 531			/* Retry operation */
 532			ide_retry_pc(drive);
 533			return ide_stopped;
 534		}
 535		pc->error = 0;
 536	} else {
 537		pc->error = IDE_DRV_ERROR_GENERAL;
 538		drive->failed_pc = NULL;
 539	}
 540	drive->pc_callback(drive, 0);
 541	return ide_stopped;
 542}
 543
 544static void ide_tape_create_rw_cmd(idetape_tape_t *tape,
 545				   struct ide_atapi_pc *pc, struct request *rq,
 546				   u8 opcode)
 547{
 548	unsigned int length = blk_rq_sectors(rq) / (tape->blk_size >> 9);
 549
 550	ide_init_pc(pc);
 551	put_unaligned(cpu_to_be32(length), (unsigned int *) &pc->c[1]);
 552	pc->c[1] = 1;
 553
 554	if (blk_rq_bytes(rq) == tape->buffer_size)
 555		pc->flags |= PC_FLAG_DMA_OK;
 556
 557	if (opcode == READ_6)
 558		pc->c[0] = READ_6;
 559	else if (opcode == WRITE_6) {
 560		pc->c[0] = WRITE_6;
 561		pc->flags |= PC_FLAG_WRITING;
 562	}
 563
 564	memcpy(rq->cmd, pc->c, 12);
 565}
 566
 567static ide_startstop_t idetape_do_request(ide_drive_t *drive,
 568					  struct request *rq, sector_t block)
 569{
 570	ide_hwif_t *hwif = drive->hwif;
 571	idetape_tape_t *tape = drive->driver_data;
 572	struct ide_atapi_pc *pc = NULL;
 573	struct ide_cmd cmd;
 574	u8 stat;
 575
 576	ide_debug_log(IDE_DBG_RQ, "cmd: 0x%x, sector: %llu, nr_sectors: %u",
 577		      rq->cmd[0], (unsigned long long)blk_rq_pos(rq),
 578		      blk_rq_sectors(rq));
 579
 580	BUG_ON(!(rq->cmd_type == REQ_TYPE_SPECIAL ||
 581		 rq->cmd_type == REQ_TYPE_SENSE));
 582
 583	/* Retry a failed packet command */
 584	if (drive->failed_pc && drive->pc->c[0] == REQUEST_SENSE) {
 585		pc = drive->failed_pc;
 586		goto out;
 587	}
 588
 589	/*
 590	 * If the tape is still busy, postpone our request and service
 591	 * the other device meanwhile.
 592	 */
 593	stat = hwif->tp_ops->read_status(hwif);
 594
 595	if ((drive->dev_flags & IDE_DFLAG_DSC_OVERLAP) == 0 &&
 596	    (rq->cmd[13] & REQ_IDETAPE_PC2) == 0)
 597		drive->atapi_flags |= IDE_AFLAG_IGNORE_DSC;
 598
 599	if (drive->dev_flags & IDE_DFLAG_POST_RESET) {
 600		drive->atapi_flags |= IDE_AFLAG_IGNORE_DSC;
 601		drive->dev_flags &= ~IDE_DFLAG_POST_RESET;
 602	}
 603
 604	if (!(drive->atapi_flags & IDE_AFLAG_IGNORE_DSC) &&
 605	    !(stat & ATA_DSC)) {
 606		if (!tape->postponed_rq) {
 607			tape->dsc_polling_start = jiffies;
 608			tape->dsc_poll_freq = tape->best_dsc_rw_freq;
 609			tape->dsc_timeout = jiffies + IDETAPE_DSC_RW_TIMEOUT;
 610		} else if (time_after(jiffies, tape->dsc_timeout)) {
 611			printk(KERN_ERR "ide-tape: %s: DSC timeout\n",
 612				tape->name);
 613			if (rq->cmd[13] & REQ_IDETAPE_PC2) {
 614				idetape_media_access_finished(drive);
 615				return ide_stopped;
 616			} else {
 617				return ide_do_reset(drive);
 618			}
 619		} else if (time_after(jiffies,
 620					tape->dsc_polling_start +
 621					IDETAPE_DSC_MA_THRESHOLD))
 622			tape->dsc_poll_freq = IDETAPE_DSC_MA_SLOW;
 623		ide_tape_stall_queue(drive);
 624		return ide_stopped;
 625	} else {
 626		drive->atapi_flags &= ~IDE_AFLAG_IGNORE_DSC;
 627		tape->postponed_rq = false;
 628	}
 629
 630	if (rq->cmd[13] & REQ_IDETAPE_READ) {
 631		pc = &tape->queued_pc;
 632		ide_tape_create_rw_cmd(tape, pc, rq, READ_6);
 633		goto out;
 634	}
 635	if (rq->cmd[13] & REQ_IDETAPE_WRITE) {
 636		pc = &tape->queued_pc;
 637		ide_tape_create_rw_cmd(tape, pc, rq, WRITE_6);
 638		goto out;
 639	}
 640	if (rq->cmd[13] & REQ_IDETAPE_PC1) {
 641		pc = (struct ide_atapi_pc *)rq->special;
 642		rq->cmd[13] &= ~(REQ_IDETAPE_PC1);
 643		rq->cmd[13] |= REQ_IDETAPE_PC2;
 644		goto out;
 645	}
 646	if (rq->cmd[13] & REQ_IDETAPE_PC2) {
 647		idetape_media_access_finished(drive);
 648		return ide_stopped;
 649	}
 650	BUG();
 651
 652out:
 653	/* prepare sense request for this command */
 654	ide_prep_sense(drive, rq);
 655
 656	memset(&cmd, 0, sizeof(cmd));
 657
 658	if (rq_data_dir(rq))
 659		cmd.tf_flags |= IDE_TFLAG_WRITE;
 660
 661	cmd.rq = rq;
 662
 663	ide_init_sg_cmd(&cmd, blk_rq_bytes(rq));
 664	ide_map_sg(drive, &cmd);
 665
 666	return ide_tape_issue_pc(drive, &cmd, pc);
 667}
 668
 669/*
 670 * Write a filemark if write_filemark=1. Flush the device buffers without
 671 * writing a filemark otherwise.
 672 */
 673static void idetape_create_write_filemark_cmd(ide_drive_t *drive,
 674		struct ide_atapi_pc *pc, int write_filemark)
 675{
 676	ide_init_pc(pc);
 677	pc->c[0] = WRITE_FILEMARKS;
 678	pc->c[4] = write_filemark;
 679	pc->flags |= PC_FLAG_WAIT_FOR_DSC;
 680}
 681
 682static int idetape_wait_ready(ide_drive_t *drive, unsigned long timeout)
 683{
 684	idetape_tape_t *tape = drive->driver_data;
 685	struct gendisk *disk = tape->disk;
 686	int load_attempted = 0;
 687
 688	/* Wait for the tape to become ready */
 689	set_bit(ilog2(IDE_AFLAG_MEDIUM_PRESENT), &drive->atapi_flags);
 690	timeout += jiffies;
 691	while (time_before(jiffies, timeout)) {
 692		if (ide_do_test_unit_ready(drive, disk) == 0)
 693			return 0;
 694		if ((tape->sense_key == 2 && tape->asc == 4 && tape->ascq == 2)
 695		    || (tape->asc == 0x3A)) {
 696			/* no media */
 697			if (load_attempted)
 698				return -ENOMEDIUM;
 699			ide_do_start_stop(drive, disk, IDETAPE_LU_LOAD_MASK);
 700			load_attempted = 1;
 701		/* not about to be ready */
 702		} else if (!(tape->sense_key == 2 && tape->asc == 4 &&
 703			     (tape->ascq == 1 || tape->ascq == 8)))
 704			return -EIO;
 705		msleep(100);
 706	}
 707	return -EIO;
 708}
 709
 710static int idetape_flush_tape_buffers(ide_drive_t *drive)
 711{
 712	struct ide_tape_obj *tape = drive->driver_data;
 713	struct ide_atapi_pc pc;
 714	int rc;
 715
 716	idetape_create_write_filemark_cmd(drive, &pc, 0);
 717	rc = ide_queue_pc_tail(drive, tape->disk, &pc, NULL, 0);
 718	if (rc)
 719		return rc;
 720	idetape_wait_ready(drive, 60 * 5 * HZ);
 721	return 0;
 722}
 723
 724static int ide_tape_read_position(ide_drive_t *drive)
 725{
 726	idetape_tape_t *tape = drive->driver_data;
 727	struct ide_atapi_pc pc;
 728	u8 buf[20];
 729
 730	ide_debug_log(IDE_DBG_FUNC, "enter");
 731
 732	/* prep cmd */
 733	ide_init_pc(&pc);
 734	pc.c[0] = READ_POSITION;
 735	pc.req_xfer = 20;
 736
 737	if (ide_queue_pc_tail(drive, tape->disk, &pc, buf, pc.req_xfer))
 738		return -1;
 739
 740	if (!pc.error) {
 741		ide_debug_log(IDE_DBG_FUNC, "BOP - %s",
 742				(buf[0] & 0x80) ? "Yes" : "No");
 743		ide_debug_log(IDE_DBG_FUNC, "EOP - %s",
 744				(buf[0] & 0x40) ? "Yes" : "No");
 745
 746		if (buf[0] & 0x4) {
 747			printk(KERN_INFO "ide-tape: Block location is unknown"
 748					 "to the tape\n");
 749			clear_bit(ilog2(IDE_AFLAG_ADDRESS_VALID),
 750				  &drive->atapi_flags);
 751			return -1;
 752		} else {
 753			ide_debug_log(IDE_DBG_FUNC, "Block Location: %u",
 754				      be32_to_cpup((__be32 *)&buf[4]));
 755
 756			tape->partition = buf[1];
 757			tape->first_frame = be32_to_cpup((__be32 *)&buf[4]);
 758			set_bit(ilog2(IDE_AFLAG_ADDRESS_VALID),
 759				&drive->atapi_flags);
 760		}
 761	}
 762
 763	return tape->first_frame;
 764}
 765
 766static void idetape_create_locate_cmd(ide_drive_t *drive,
 767		struct ide_atapi_pc *pc,
 768		unsigned int block, u8 partition, int skip)
 769{
 770	ide_init_pc(pc);
 771	pc->c[0] = POSITION_TO_ELEMENT;
 772	pc->c[1] = 2;
 773	put_unaligned(cpu_to_be32(block), (unsigned int *) &pc->c[3]);
 774	pc->c[8] = partition;
 775	pc->flags |= PC_FLAG_WAIT_FOR_DSC;
 776}
 777
 778static void __ide_tape_discard_merge_buffer(ide_drive_t *drive)
 779{
 780	idetape_tape_t *tape = drive->driver_data;
 781
 782	if (tape->chrdev_dir != IDETAPE_DIR_READ)
 783		return;
 784
 785	clear_bit(ilog2(IDE_AFLAG_FILEMARK), &drive->atapi_flags);
 786	tape->valid = 0;
 787	if (tape->buf != NULL) {
 788		kfree(tape->buf);
 789		tape->buf = NULL;
 790	}
 791
 792	tape->chrdev_dir = IDETAPE_DIR_NONE;
 793}
 794
 795/*
 796 * Position the tape to the requested block using the LOCATE packet command.
 797 * A READ POSITION command is then issued to check where we are positioned. Like
 798 * all higher level operations, we queue the commands at the tail of the request
 799 * queue and wait for their completion.
 800 */
 801static int idetape_position_tape(ide_drive_t *drive, unsigned int block,
 802		u8 partition, int skip)
 803{
 804	idetape_tape_t *tape = drive->driver_data;
 805	struct gendisk *disk = tape->disk;
 806	int ret;
 807	struct ide_atapi_pc pc;
 808
 809	if (tape->chrdev_dir == IDETAPE_DIR_READ)
 810		__ide_tape_discard_merge_buffer(drive);
 811	idetape_wait_ready(drive, 60 * 5 * HZ);
 812	idetape_create_locate_cmd(drive, &pc, block, partition, skip);
 813	ret = ide_queue_pc_tail(drive, disk, &pc, NULL, 0);
 814	if (ret)
 815		return ret;
 816
 817	ret = ide_tape_read_position(drive);
 818	if (ret < 0)
 819		return ret;
 820	return 0;
 821}
 822
 823static void ide_tape_discard_merge_buffer(ide_drive_t *drive,
 824					  int restore_position)
 825{
 826	idetape_tape_t *tape = drive->driver_data;
 827	int seek, position;
 828
 829	__ide_tape_discard_merge_buffer(drive);
 830	if (restore_position) {
 831		position = ide_tape_read_position(drive);
 832		seek = position > 0 ? position : 0;
 833		if (idetape_position_tape(drive, seek, 0, 0)) {
 834			printk(KERN_INFO "ide-tape: %s: position_tape failed in"
 835					 " %s\n", tape->name, __func__);
 836			return;
 837		}
 838	}
 839}
 840
 841/*
 842 * Generate a read/write request for the block device interface and wait for it
 843 * to be serviced.
 844 */
 845static int idetape_queue_rw_tail(ide_drive_t *drive, int cmd, int size)
 846{
 847	idetape_tape_t *tape = drive->driver_data;
 848	struct request *rq;
 849	int ret;
 850
 851	ide_debug_log(IDE_DBG_FUNC, "cmd: 0x%x, size: %d", cmd, size);
 852
 853	BUG_ON(cmd != REQ_IDETAPE_READ && cmd != REQ_IDETAPE_WRITE);
 854	BUG_ON(size < 0 || size % tape->blk_size);
 855
 856	rq = blk_get_request(drive->queue, READ, __GFP_WAIT);
 857	rq->cmd_type = REQ_TYPE_SPECIAL;
 858	rq->cmd[13] = cmd;
 859	rq->rq_disk = tape->disk;
 860	rq->__sector = tape->first_frame;
 861
 862	if (size) {
 863		ret = blk_rq_map_kern(drive->queue, rq, tape->buf, size,
 864				      __GFP_WAIT);
 865		if (ret)
 866			goto out_put;
 867	}
 868
 869	blk_execute_rq(drive->queue, tape->disk, rq, 0);
 870
 871	/* calculate the number of transferred bytes and update buffer state */
 872	size -= rq->resid_len;
 873	tape->cur = tape->buf;
 874	if (cmd == REQ_IDETAPE_READ)
 875		tape->valid = size;
 876	else
 877		tape->valid = 0;
 878
 879	ret = size;
 880	if (rq->errors == IDE_DRV_ERROR_GENERAL)
 881		ret = -EIO;
 882out_put:
 883	blk_put_request(rq);
 884	return ret;
 885}
 886
 887static void idetape_create_inquiry_cmd(struct ide_atapi_pc *pc)
 888{
 889	ide_init_pc(pc);
 890	pc->c[0] = INQUIRY;
 891	pc->c[4] = 254;
 892	pc->req_xfer = 254;
 893}
 894
 895static void idetape_create_rewind_cmd(ide_drive_t *drive,
 896		struct ide_atapi_pc *pc)
 897{
 898	ide_init_pc(pc);
 899	pc->c[0] = REZERO_UNIT;
 900	pc->flags |= PC_FLAG_WAIT_FOR_DSC;
 901}
 902
 903static void idetape_create_erase_cmd(struct ide_atapi_pc *pc)
 904{
 905	ide_init_pc(pc);
 906	pc->c[0] = ERASE;
 907	pc->c[1] = 1;
 908	pc->flags |= PC_FLAG_WAIT_FOR_DSC;
 909}
 910
 911static void idetape_create_space_cmd(struct ide_atapi_pc *pc, int count, u8 cmd)
 912{
 913	ide_init_pc(pc);
 914	pc->c[0] = SPACE;
 915	put_unaligned(cpu_to_be32(count), (unsigned int *) &pc->c[1]);
 916	pc->c[1] = cmd;
 917	pc->flags |= PC_FLAG_WAIT_FOR_DSC;
 918}
 919
 920static void ide_tape_flush_merge_buffer(ide_drive_t *drive)
 921{
 922	idetape_tape_t *tape = drive->driver_data;
 923
 924	if (tape->chrdev_dir != IDETAPE_DIR_WRITE) {
 925		printk(KERN_ERR "ide-tape: bug: Trying to empty merge buffer"
 926				" but we are not writing.\n");
 927		return;
 928	}
 929	if (tape->buf) {
 930		size_t aligned = roundup(tape->valid, tape->blk_size);
 931
 932		memset(tape->cur, 0, aligned - tape->valid);
 933		idetape_queue_rw_tail(drive, REQ_IDETAPE_WRITE, aligned);
 934		kfree(tape->buf);
 935		tape->buf = NULL;
 936	}
 937	tape->chrdev_dir = IDETAPE_DIR_NONE;
 938}
 939
 940static int idetape_init_rw(ide_drive_t *drive, int dir)
 941{
 942	idetape_tape_t *tape = drive->driver_data;
 943	int rc;
 944
 945	BUG_ON(dir != IDETAPE_DIR_READ && dir != IDETAPE_DIR_WRITE);
 946
 947	if (tape->chrdev_dir == dir)
 948		return 0;
 949
 950	if (tape->chrdev_dir == IDETAPE_DIR_READ)
 951		ide_tape_discard_merge_buffer(drive, 1);
 952	else if (tape->chrdev_dir == IDETAPE_DIR_WRITE) {
 953		ide_tape_flush_merge_buffer(drive);
 954		idetape_flush_tape_buffers(drive);
 955	}
 956
 957	if (tape->buf || tape->valid) {
 958		printk(KERN_ERR "ide-tape: valid should be 0 now\n");
 959		tape->valid = 0;
 960	}
 961
 962	tape->buf = kmalloc(tape->buffer_size, GFP_KERNEL);
 963	if (!tape->buf)
 964		return -ENOMEM;
 965	tape->chrdev_dir = dir;
 966	tape->cur = tape->buf;
 967
 968	/*
 969	 * Issue a 0 rw command to ensure that DSC handshake is
 970	 * switched from completion mode to buffer available mode.  No
 971	 * point in issuing this if DSC overlap isn't supported, some
 972	 * drives (Seagate STT3401A) will return an error.
 973	 */
 974	if (drive->dev_flags & IDE_DFLAG_DSC_OVERLAP) {
 975		int cmd = dir == IDETAPE_DIR_READ ? REQ_IDETAPE_READ
 976						  : REQ_IDETAPE_WRITE;
 977
 978		rc = idetape_queue_rw_tail(drive, cmd, 0);
 979		if (rc < 0) {
 980			kfree(tape->buf);
 981			tape->buf = NULL;
 982			tape->chrdev_dir = IDETAPE_DIR_NONE;
 983			return rc;
 984		}
 985	}
 986
 987	return 0;
 988}
 989
 990static void idetape_pad_zeros(ide_drive_t *drive, int bcount)
 991{
 992	idetape_tape_t *tape = drive->driver_data;
 993
 994	memset(tape->buf, 0, tape->buffer_size);
 995
 996	while (bcount) {
 997		unsigned int count = min(tape->buffer_size, bcount);
 998
 999		idetape_queue_rw_tail(drive, REQ_IDETAPE_WRITE, count);
1000		bcount -= count;
1001	}
1002}
1003
1004/*
1005 * Rewinds the tape to the Beginning Of the current Partition (BOP). We
1006 * currently support only one partition.
1007 */
1008static int idetape_rewind_tape(ide_drive_t *drive)
1009{
1010	struct ide_tape_obj *tape = drive->driver_data;
1011	struct gendisk *disk = tape->disk;
1012	struct ide_atapi_pc pc;
1013	int ret;
1014
1015	ide_debug_log(IDE_DBG_FUNC, "enter");
1016
1017	idetape_create_rewind_cmd(drive, &pc);
1018	ret = ide_queue_pc_tail(drive, disk, &pc, NULL, 0);
1019	if (ret)
1020		return ret;
1021
1022	ret = ide_tape_read_position(drive);
1023	if (ret < 0)
1024		return ret;
1025	return 0;
1026}
1027
1028/* mtio.h compatible commands should be issued to the chrdev interface. */
1029static int idetape_blkdev_ioctl(ide_drive_t *drive, unsigned int cmd,
1030				unsigned long arg)
1031{
1032	idetape_tape_t *tape = drive->driver_data;
1033	void __user *argp = (void __user *)arg;
1034
1035	struct idetape_config {
1036		int dsc_rw_frequency;
1037		int dsc_media_access_frequency;
1038		int nr_stages;
1039	} config;
1040
1041	ide_debug_log(IDE_DBG_FUNC, "cmd: 0x%04x", cmd);
1042
1043	switch (cmd) {
1044	case 0x0340:
1045		if (copy_from_user(&config, argp, sizeof(config)))
1046			return -EFAULT;
1047		tape->best_dsc_rw_freq = config.dsc_rw_frequency;
1048		break;
1049	case 0x0350:
1050		memset(&config, 0, sizeof(config));
1051		config.dsc_rw_frequency = (int) tape->best_dsc_rw_freq;
1052		config.nr_stages = 1;
1053		if (copy_to_user(argp, &config, sizeof(config)))
1054			return -EFAULT;
1055		break;
1056	default:
1057		return -EIO;
1058	}
1059	return 0;
1060}
1061
1062static int idetape_space_over_filemarks(ide_drive_t *drive, short mt_op,
1063					int mt_count)
1064{
1065	idetape_tape_t *tape = drive->driver_data;
1066	struct gendisk *disk = tape->disk;
1067	struct ide_atapi_pc pc;
1068	int retval, count = 0;
1069	int sprev = !!(tape->caps[4] & 0x20);
1070
1071
1072	ide_debug_log(IDE_DBG_FUNC, "mt_op: %d, mt_count: %d", mt_op, mt_count);
1073
1074	if (mt_count == 0)
1075		return 0;
1076	if (MTBSF == mt_op || MTBSFM == mt_op) {
1077		if (!sprev)
1078			return -EIO;
1079		mt_count = -mt_count;
1080	}
1081
1082	if (tape->chrdev_dir == IDETAPE_DIR_READ) {
1083		tape->valid = 0;
1084		if (test_and_clear_bit(ilog2(IDE_AFLAG_FILEMARK),
1085				       &drive->atapi_flags))
1086			++count;
1087		ide_tape_discard_merge_buffer(drive, 0);
1088	}
1089
1090	switch (mt_op) {
1091	case MTFSF:
1092	case MTBSF:
1093		idetape_create_space_cmd(&pc, mt_count - count,
1094					 IDETAPE_SPACE_OVER_FILEMARK);
1095		return ide_queue_pc_tail(drive, disk, &pc, NULL, 0);
1096	case MTFSFM:
1097	case MTBSFM:
1098		if (!sprev)
1099			return -EIO;
1100		retval = idetape_space_over_filemarks(drive, MTFSF,
1101						      mt_count - count);
1102		if (retval)
1103			return retval;
1104		count = (MTBSFM == mt_op ? 1 : -1);
1105		return idetape_space_over_filemarks(drive, MTFSF, count);
1106	default:
1107		printk(KERN_ERR "ide-tape: MTIO operation %d not supported\n",
1108				mt_op);
1109		return -EIO;
1110	}
1111}
1112
1113/*
1114 * Our character device read / write functions.
1115 *
1116 * The tape is optimized to maximize throughput when it is transferring an
1117 * integral number of the "continuous transfer limit", which is a parameter of
1118 * the specific tape (26kB on my particular tape, 32kB for Onstream).
1119 *
1120 * As of version 1.3 of the driver, the character device provides an abstract
1121 * continuous view of the media - any mix of block sizes (even 1 byte) on the
1122 * same backup/restore procedure is supported. The driver will internally
1123 * convert the requests to the recommended transfer unit, so that an unmatch
1124 * between the user's block size to the recommended size will only result in a
1125 * (slightly) increased driver overhead, but will no longer hit performance.
1126 * This is not applicable to Onstream.
1127 */
1128static ssize_t idetape_chrdev_read(struct file *file, char __user *buf,
1129				   size_t count, loff_t *ppos)
1130{
1131	struct ide_tape_obj *tape = file->private_data;
1132	ide_drive_t *drive = tape->drive;
1133	size_t done = 0;
1134	ssize_t ret = 0;
1135	int rc;
1136
1137	ide_debug_log(IDE_DBG_FUNC, "count %Zd", count);
1138
1139	if (tape->chrdev_dir != IDETAPE_DIR_READ) {
1140		if (test_bit(ilog2(IDE_AFLAG_DETECT_BS), &drive->atapi_flags))
1141			if (count > tape->blk_size &&
1142			    (count % tape->blk_size) == 0)
1143				tape->user_bs_factor = count / tape->blk_size;
1144	}
1145
1146	rc = idetape_init_rw(drive, IDETAPE_DIR_READ);
1147	if (rc < 0)
1148		return rc;
1149
1150	while (done < count) {
1151		size_t todo;
1152
1153		/* refill if staging buffer is empty */
1154		if (!tape->valid) {
1155			/* If we are at a filemark, nothing more to read */
1156			if (test_bit(ilog2(IDE_AFLAG_FILEMARK),
1157				     &drive->atapi_flags))
1158				break;
1159			/* read */
1160			if (idetape_queue_rw_tail(drive, REQ_IDETAPE_READ,
1161						  tape->buffer_size) <= 0)
1162				break;
1163		}
1164
1165		/* copy out */
1166		todo = min_t(size_t, count - done, tape->valid);
1167		if (copy_to_user(buf + done, tape->cur, todo))
1168			ret = -EFAULT;
1169
1170		tape->cur += todo;
1171		tape->valid -= todo;
1172		done += todo;
1173	}
1174
1175	if (!done && test_bit(ilog2(IDE_AFLAG_FILEMARK), &drive->atapi_flags)) {
1176		idetape_space_over_filemarks(drive, MTFSF, 1);
1177		return 0;
1178	}
1179
1180	return ret ? ret : done;
1181}
1182
1183static ssize_t idetape_chrdev_write(struct file *file, const char __user *buf,
1184				     size_t count, loff_t *ppos)
1185{
1186	struct ide_tape_obj *tape = file->private_data;
1187	ide_drive_t *drive = tape->drive;
1188	size_t done = 0;
1189	ssize_t ret = 0;
1190	int rc;
1191
1192	/* The drive is write protected. */
1193	if (tape->write_prot)
1194		return -EACCES;
1195
1196	ide_debug_log(IDE_DBG_FUNC, "count %Zd", count);
1197
1198	/* Initialize write operation */
1199	rc = idetape_init_rw(drive, IDETAPE_DIR_WRITE);
1200	if (rc < 0)
1201		return rc;
1202
1203	while (done < count) {
1204		size_t todo;
1205
1206		/* flush if staging buffer is full */
1207		if (tape->valid == tape->buffer_size &&
1208		    idetape_queue_rw_tail(drive, REQ_IDETAPE_WRITE,
1209					  tape->buffer_size) <= 0)
1210			return rc;
1211
1212		/* copy in */
1213		todo = min_t(size_t, count - done,
1214			     tape->buffer_size - tape->valid);
1215		if (copy_from_user(tape->cur, buf + done, todo))
1216			ret = -EFAULT;
1217
1218		tape->cur += todo;
1219		tape->valid += todo;
1220		done += todo;
1221	}
1222
1223	return ret ? ret : done;
1224}
1225
1226static int idetape_write_filemark(ide_drive_t *drive)
1227{
1228	struct ide_tape_obj *tape = drive->driver_data;
1229	struct ide_atapi_pc pc;
1230
1231	/* Write a filemark */
1232	idetape_create_write_filemark_cmd(drive, &pc, 1);
1233	if (ide_queue_pc_tail(drive, tape->disk, &pc, NULL, 0)) {
1234		printk(KERN_ERR "ide-tape: Couldn't write a filemark\n");
1235		return -EIO;
1236	}
1237	return 0;
1238}
1239
1240/*
1241 * Called from idetape_chrdev_ioctl when the general mtio MTIOCTOP ioctl is
1242 * requested.
1243 *
1244 * Note: MTBSF and MTBSFM are not supported when the tape doesn't support
1245 * spacing over filemarks in the reverse direction. In this case, MTFSFM is also
1246 * usually not supported.
1247 *
1248 * The following commands are currently not supported:
1249 *
1250 * MTFSS, MTBSS, MTWSM, MTSETDENSITY, MTSETDRVBUFFER, MT_ST_BOOLEANS,
1251 * MT_ST_WRITE_THRESHOLD.
1252 */
1253static int idetape_mtioctop(ide_drive_t *drive, short mt_op, int mt_count)
1254{
1255	idetape_tape_t *tape = drive->driver_data;
1256	struct gendisk *disk = tape->disk;
1257	struct ide_atapi_pc pc;
1258	int i, retval;
1259
1260	ide_debug_log(IDE_DBG_FUNC, "MTIOCTOP ioctl: mt_op: %d, mt_count: %d",
1261		      mt_op, mt_count);
1262
1263	switch (mt_op) {
1264	case MTFSF:
1265	case MTFSFM:
1266	case MTBSF:
1267	case MTBSFM:
1268		if (!mt_count)
1269			return 0;
1270		return idetape_space_over_filemarks(drive, mt_op, mt_count);
1271	default:
1272		break;
1273	}
1274
1275	switch (mt_op) {
1276	case MTWEOF:
1277		if (tape->write_prot)
1278			return -EACCES;
1279		ide_tape_discard_merge_buffer(drive, 1);
1280		for (i = 0; i < mt_count; i++) {
1281			retval = idetape_write_filemark(drive);
1282			if (retval)
1283				return retval;
1284		}
1285		return 0;
1286	case MTREW:
1287		ide_tape_discard_merge_buffer(drive, 0);
1288		if (idetape_rewind_tape(drive))
1289			return -EIO;
1290		return 0;
1291	case MTLOAD:
1292		ide_tape_discard_merge_buffer(drive, 0);
1293		return ide_do_start_stop(drive, disk, IDETAPE_LU_LOAD_MASK);
1294	case MTUNLOAD:
1295	case MTOFFL:
1296		/*
1297		 * If door is locked, attempt to unlock before
1298		 * attempting to eject.
1299		 */
1300		if (tape->door_locked) {
1301			if (!ide_set_media_lock(drive, disk, 0))
1302				tape->door_locked = DOOR_UNLOCKED;
1303		}
1304		ide_tape_discard_merge_buffer(drive, 0);
1305		retval = ide_do_start_stop(drive, disk, !IDETAPE_LU_LOAD_MASK);
1306		if (!retval)
1307			clear_bit(ilog2(IDE_AFLAG_MEDIUM_PRESENT),
1308				  &drive->atapi_flags);
1309		return retval;
1310	case MTNOP:
1311		ide_tape_discard_merge_buffer(drive, 0);
1312		return idetape_flush_tape_buffers(drive);
1313	case MTRETEN:
1314		ide_tape_discard_merge_buffer(drive, 0);
1315		return ide_do_start_stop(drive, disk,
1316			IDETAPE_LU_RETENSION_MASK | IDETAPE_LU_LOAD_MASK);
1317	case MTEOM:
1318		idetape_create_space_cmd(&pc, 0, IDETAPE_SPACE_TO_EOD);
1319		return ide_queue_pc_tail(drive, disk, &pc, NULL, 0);
1320	case MTERASE:
1321		(void)idetape_rewind_tape(drive);
1322		idetape_create_erase_cmd(&pc);
1323		return ide_queue_pc_tail(drive, disk, &pc, NULL, 0);
1324	case MTSETBLK:
1325		if (mt_count) {
1326			if (mt_count < tape->blk_size ||
1327			    mt_count % tape->blk_size)
1328				return -EIO;
1329			tape->user_bs_factor = mt_count / tape->blk_size;
1330			clear_bit(ilog2(IDE_AFLAG_DETECT_BS),
1331				  &drive->atapi_flags);
1332		} else
1333			set_bit(ilog2(IDE_AFLAG_DETECT_BS),
1334				&drive->atapi_flags);
1335		return 0;
1336	case MTSEEK:
1337		ide_tape_discard_merge_buffer(drive, 0);
1338		return idetape_position_tape(drive,
1339			mt_count * tape->user_bs_factor, tape->partition, 0);
1340	case MTSETPART:
1341		ide_tape_discard_merge_buffer(drive, 0);
1342		return idetape_position_tape(drive, 0, mt_count, 0);
1343	case MTFSR:
1344	case MTBSR:
1345	case MTLOCK:
1346		retval = ide_set_media_lock(drive, disk, 1);
1347		if (retval)
1348			return retval;
1349		tape->door_locked = DOOR_EXPLICITLY_LOCKED;
1350		return 0;
1351	case MTUNLOCK:
1352		retval = ide_set_media_lock(drive, disk, 0);
1353		if (retval)
1354			return retval;
1355		tape->door_locked = DOOR_UNLOCKED;
1356		return 0;
1357	default:
1358		printk(KERN_ERR "ide-tape: MTIO operation %d not supported\n",
1359				mt_op);
1360		return -EIO;
1361	}
1362}
1363
1364/*
1365 * Our character device ioctls. General mtio.h magnetic io commands are
1366 * supported here, and not in the corresponding block interface. Our own
1367 * ide-tape ioctls are supported on both interfaces.
1368 */
1369static long do_idetape_chrdev_ioctl(struct file *file,
1370				unsigned int cmd, unsigned long arg)
1371{
1372	struct ide_tape_obj *tape = file->private_data;
1373	ide_drive_t *drive = tape->drive;
1374	struct mtop mtop;
1375	struct mtget mtget;
1376	struct mtpos mtpos;
1377	int block_offset = 0, position = tape->first_frame;
1378	void __user *argp = (void __user *)arg;
1379
1380	ide_debug_log(IDE_DBG_FUNC, "cmd: 0x%x", cmd);
1381
1382	if (tape->chrdev_dir == IDETAPE_DIR_WRITE) {
1383		ide_tape_flush_merge_buffer(drive);
1384		idetape_flush_tape_buffers(drive);
1385	}
1386	if (cmd == MTIOCGET || cmd == MTIOCPOS) {
1387		block_offset = tape->valid /
1388			(tape->blk_size * tape->user_bs_factor);
1389		position = ide_tape_read_position(drive);
1390		if (position < 0)
1391			return -EIO;
1392	}
1393	switch (cmd) {
1394	case MTIOCTOP:
1395		if (copy_from_user(&mtop, argp, sizeof(struct mtop)))
1396			return -EFAULT;
1397		return idetape_mtioctop(drive, mtop.mt_op, mtop.mt_count);
1398	case MTIOCGET:
1399		memset(&mtget, 0, sizeof(struct mtget));
1400		mtget.mt_type = MT_ISSCSI2;
1401		mtget.mt_blkno = position / tape->user_bs_factor - block_offset;
1402		mtget.mt_dsreg =
1403			((tape->blk_size * tape->user_bs_factor)
1404			 << MT_ST_BLKSIZE_SHIFT) & MT_ST_BLKSIZE_MASK;
1405
1406		if (tape->drv_write_prot)
1407			mtget.mt_gstat |= GMT_WR_PROT(0xffffffff);
1408
1409		if (copy_to_user(argp, &mtget, sizeof(struct mtget)))
1410			return -EFAULT;
1411		return 0;
1412	case MTIOCPOS:
1413		mtpos.mt_blkno = position / tape->user_bs_factor - block_offset;
1414		if (copy_to_user(argp, &mtpos, sizeof(struct mtpos)))
1415			return -EFAULT;
1416		return 0;
1417	default:
1418		if (tape->chrdev_dir == IDETAPE_DIR_READ)
1419			ide_tape_discard_merge_buffer(drive, 1);
1420		return idetape_blkdev_ioctl(drive, cmd, arg);
1421	}
1422}
1423
1424static long idetape_chrdev_ioctl(struct file *file,
1425				unsigned int cmd, unsigned long arg)
1426{
1427	long ret;
1428	mutex_lock(&ide_tape_mutex);
1429	ret = do_idetape_chrdev_ioctl(file, cmd, arg);
1430	mutex_unlock(&ide_tape_mutex);
1431	return ret;
1432}
1433
1434/*
1435 * Do a mode sense page 0 with block descriptor and if it succeeds set the tape
1436 * block size with the reported value.
1437 */
1438static void ide_tape_get_bsize_from_bdesc(ide_drive_t *drive)
1439{
1440	idetape_tape_t *tape = drive->driver_data;
1441	struct ide_atapi_pc pc;
1442	u8 buf[12];
1443
1444	idetape_create_mode_sense_cmd(&pc, IDETAPE_BLOCK_DESCRIPTOR);
1445	if (ide_queue_pc_tail(drive, tape->disk, &pc, buf, pc.req_xfer)) {
1446		printk(KERN_ERR "ide-tape: Can't get block descriptor\n");
1447		if (tape->blk_size == 0) {
1448			printk(KERN_WARNING "ide-tape: Cannot deal with zero "
1449					    "block size, assuming 32k\n");
1450			tape->blk_size = 32768;
1451		}
1452		return;
1453	}
1454	tape->blk_size = (buf[4 + 5] << 16) +
1455				(buf[4 + 6] << 8)  +
1456				 buf[4 + 7];
1457	tape->drv_write_prot = (buf[2] & 0x80) >> 7;
1458
1459	ide_debug_log(IDE_DBG_FUNC, "blk_size: %d, write_prot: %d",
1460		      tape->blk_size, tape->drv_write_prot);
1461}
1462
1463static int idetape_chrdev_open(struct inode *inode, struct file *filp)
1464{
1465	unsigned int minor = iminor(inode), i = minor & ~0xc0;
1466	ide_drive_t *drive;
1467	idetape_tape_t *tape;
1468	int retval;
1469
1470	if (i >= MAX_HWIFS * MAX_DRIVES)
1471		return -ENXIO;
1472
1473	mutex_lock(&idetape_chrdev_mutex);
1474
1475	tape = ide_tape_get(NULL, true, i);
1476	if (!tape) {
1477		mutex_unlock(&idetape_chrdev_mutex);
1478		return -ENXIO;
1479	}
1480
1481	drive = tape->drive;
1482	filp->private_data = tape;
1483
1484	ide_debug_log(IDE_DBG_FUNC, "enter");
1485
1486	/*
1487	 * We really want to do nonseekable_open(inode, filp); here, but some
1488	 * versions of tar incorrectly call lseek on tapes and bail out if that
1489	 * fails.  So we disallow pread() and pwrite(), but permit lseeks.
1490	 */
1491	filp->f_mode &= ~(FMODE_PREAD | FMODE_PWRITE);
1492
1493
1494	if (test_and_set_bit(ilog2(IDE_AFLAG_BUSY), &drive->atapi_flags)) {
1495		retval = -EBUSY;
1496		goto out_put_tape;
1497	}
1498
1499	retval = idetape_wait_ready(drive, 60 * HZ);
1500	if (retval) {
1501		clear_bit(ilog2(IDE_AFLAG_BUSY), &drive->atapi_flags);
1502		printk(KERN_ERR "ide-tape: %s: drive not ready\n", tape->name);
1503		goto out_put_tape;
1504	}
1505
1506	ide_tape_read_position(drive);
1507	if (!test_bit(ilog2(IDE_AFLAG_ADDRESS_VALID), &drive->atapi_flags))
1508		(void)idetape_rewind_tape(drive);
1509
1510	/* Read block size and write protect status from drive. */
1511	ide_tape_get_bsize_from_bdesc(drive);
1512
1513	/* Set write protect flag if device is opened as read-only. */
1514	if ((filp->f_flags & O_ACCMODE) == O_RDONLY)
1515		tape->write_prot = 1;
1516	else
1517		tape->write_prot = tape->drv_write_prot;
1518
1519	/* Make sure drive isn't write protected if user wants to write. */
1520	if (tape->write_prot) {
1521		if ((filp->f_flags & O_ACCMODE) == O_WRONLY ||
1522		    (filp->f_flags & O_ACCMODE) == O_RDWR) {
1523			clear_bit(ilog2(IDE_AFLAG_BUSY), &drive->atapi_flags);
1524			retval = -EROFS;
1525			goto out_put_tape;
1526		}
1527	}
1528
1529	/* Lock the tape drive door so user can't eject. */
1530	if (tape->chrdev_dir == IDETAPE_DIR_NONE) {
1531		if (!ide_set_media_lock(drive, tape->disk, 1)) {
1532			if (tape->door_locked != DOOR_EXPLICITLY_LOCKED)
1533				tape->door_locked = DOOR_LOCKED;
1534		}
1535	}
1536	mutex_unlock(&idetape_chrdev_mutex);
1537
1538	return 0;
1539
1540out_put_tape:
1541	ide_tape_put(tape);
1542
1543	mutex_unlock(&idetape_chrdev_mutex);
1544
1545	return retval;
1546}
1547
1548static void idetape_write_release(ide_drive_t *drive, unsigned int minor)
1549{
1550	idetape_tape_t *tape = drive->driver_data;
1551
1552	ide_tape_flush_merge_buffer(drive);
1553	tape->buf = kmalloc(tape->buffer_size, GFP_KERNEL);
1554	if (tape->buf != NULL) {
1555		idetape_pad_zeros(drive, tape->blk_size *
1556				(tape->user_bs_factor - 1));
1557		kfree(tape->buf);
1558		tape->buf = NULL;
1559	}
1560	idetape_write_filemark(drive);
1561	idetape_flush_tape_buffers(drive);
1562	idetape_flush_tape_buffers(drive);
1563}
1564
1565static int idetape_chrdev_release(struct inode *inode, struct file *filp)
1566{
1567	struct ide_tape_obj *tape = filp->private_data;
1568	ide_drive_t *drive = tape->drive;
1569	unsigned int minor = iminor(inode);
1570
1571	mutex_lock(&idetape_chrdev_mutex);
1572
1573	tape = drive->driver_data;
1574
1575	ide_debug_log(IDE_DBG_FUNC, "enter");
1576
1577	if (tape->chrdev_dir == IDETAPE_DIR_WRITE)
1578		idetape_write_release(drive, minor);
1579	if (tape->chrdev_dir == IDETAPE_DIR_READ) {
1580		if (minor < 128)
1581			ide_tape_discard_merge_buffer(drive, 1);
1582	}
1583
1584	if (minor < 128 && test_bit(ilog2(IDE_AFLAG_MEDIUM_PRESENT),
1585				    &drive->atapi_flags))
1586		(void) idetape_rewind_tape(drive);
1587
1588	if (tape->chrdev_dir == IDETAPE_DIR_NONE) {
1589		if (tape->door_locked == DOOR_LOCKED) {
1590			if (!ide_set_media_lock(drive, tape->disk, 0))
1591				tape->door_locked = DOOR_UNLOCKED;
1592		}
1593	}
1594	clear_bit(ilog2(IDE_AFLAG_BUSY), &drive->atapi_flags);
1595	ide_tape_put(tape);
1596
1597	mutex_unlock(&idetape_chrdev_mutex);
1598
1599	return 0;
1600}
1601
1602static void idetape_get_inquiry_results(ide_drive_t *drive)
1603{
1604	idetape_tape_t *tape = drive->driver_data;
1605	struct ide_atapi_pc pc;
1606	u8 pc_buf[256];
1607	char fw_rev[4], vendor_id[8], product_id[16];
1608
1609	idetape_create_inquiry_cmd(&pc);
1610	if (ide_queue_pc_tail(drive, tape->disk, &pc, pc_buf, pc.req_xfer)) {
1611		printk(KERN_ERR "ide-tape: %s: can't get INQUIRY results\n",
1612				tape->name);
1613		return;
1614	}
1615	memcpy(vendor_id, &pc_buf[8], 8);
1616	memcpy(product_id, &pc_buf[16], 16);
1617	memcpy(fw_rev, &pc_buf[32], 4);
1618
1619	ide_fixstring(vendor_id, 8, 0);
1620	ide_fixstring(product_id, 16, 0);
1621	ide_fixstring(fw_rev, 4, 0);
1622
1623	printk(KERN_INFO "ide-tape: %s <-> %s: %.8s %.16s rev %.4s\n",
1624			drive->name, tape->name, vendor_id, product_id, fw_rev);
1625}
1626
1627/*
1628 * Ask the tape about its various parameters. In particular, we will adjust our
1629 * data transfer buffer	size to the recommended value as returned by the tape.
1630 */
1631static void idetape_get_mode_sense_results(ide_drive_t *drive)
1632{
1633	idetape_tape_t *tape = drive->driver_data;
1634	struct ide_atapi_pc pc;
1635	u8 buf[24], *caps;
1636	u8 speed, max_speed;
1637
1638	idetape_create_mode_sense_cmd(&pc, IDETAPE_CAPABILITIES_PAGE);
1639	if (ide_queue_pc_tail(drive, tape->disk, &pc, buf, pc.req_xfer)) {
1640		printk(KERN_ERR "ide-tape: Can't get tape parameters - assuming"
1641				" some default values\n");
1642		tape->blk_size = 512;
1643		put_unaligned(52,   (u16 *)&tape->caps[12]);
1644		put_unaligned(540,  (u16 *)&tape->caps[14]);
1645		put_unaligned(6*52, (u16 *)&tape->caps[16]);
1646		return;
1647	}
1648	caps = buf + 4 + buf[3];
1649
1650	/* convert to host order and save for later use */
1651	speed = be16_to_cpup((__be16 *)&caps[14]);
1652	max_speed = be16_to_cpup((__be16 *)&caps[8]);
1653
1654	*(u16 *)&caps[8] = max_speed;
1655	*(u16 *)&caps[12] = be16_to_cpup((__be16 *)&caps[12]);
1656	*(u16 *)&caps[14] = speed;
1657	*(u16 *)&caps[16] = be16_to_cpup((__be16 *)&caps[16]);
1658
1659	if (!speed) {
1660		printk(KERN_INFO "ide-tape: %s: invalid tape speed "
1661				"(assuming 650KB/sec)\n", drive->name);
1662		*(u16 *)&caps[14] = 650;
1663	}
1664	if (!max_speed) {
1665		printk(KERN_INFO "ide-tape: %s: invalid max_speed "
1666				"(assuming 650KB/sec)\n", drive->name);
1667		*(u16 *)&caps[8] = 650;
1668	}
1669
1670	memcpy(&tape->caps, caps, 20);
1671
1672	/* device lacks locking support according to capabilities page */
1673	if ((caps[6] & 1) == 0)
1674		drive->dev_flags &= ~IDE_DFLAG_DOORLOCKING;
1675
1676	if (caps[7] & 0x02)
1677		tape->blk_size = 512;
1678	else if (caps[7] & 0x04)
1679		tape->blk_size = 1024;
1680}
1681
1682#ifdef CONFIG_IDE_PROC_FS
1683#define ide_tape_devset_get(name, field) \
1684static int get_##name(ide_drive_t *drive) \
1685{ \
1686	idetape_tape_t *tape = drive->driver_data; \
1687	return tape->field; \
1688}
1689
1690#define ide_tape_devset_set(name, field) \
1691static int set_##name(ide_drive_t *drive, int arg) \
1692{ \
1693	idetape_tape_t *tape = drive->driver_data; \
1694	tape->field = arg; \
1695	return 0; \
1696}
1697
1698#define ide_tape_devset_rw_field(_name, _field) \
1699ide_tape_devset_get(_name, _field) \
1700ide_tape_devset_set(_name, _field) \
1701IDE_DEVSET(_name, DS_SYNC, get_##_name, set_##_name)
1702
1703#define ide_tape_devset_r_field(_name, _field) \
1704ide_tape_devset_get(_name, _field) \
1705IDE_DEVSET(_name, 0, get_##_name, NULL)
1706
1707static int mulf_tdsc(ide_drive_t *drive)	{ return 1000; }
1708static int divf_tdsc(ide_drive_t *drive)	{ return   HZ; }
1709static int divf_buffer(ide_drive_t *drive)	{ return    2; }
1710static int divf_buffer_size(ide_drive_t *drive)	{ return 1024; }
1711
1712ide_devset_rw_flag(dsc_overlap, IDE_DFLAG_DSC_OVERLAP);
1713
1714ide_tape_devset_rw_field(tdsc, best_dsc_rw_freq);
1715
1716ide_tape_devset_r_field(avg_speed, avg_speed);
1717ide_tape_devset_r_field(speed, caps[14]);
1718ide_tape_devset_r_field(buffer, caps[16]);
1719ide_tape_devset_r_field(buffer_size, buffer_size);
1720
1721static const struct ide_proc_devset idetape_settings[] = {
1722	__IDE_PROC_DEVSET(avg_speed,	0, 0xffff, NULL, NULL),
1723	__IDE_PROC_DEVSET(buffer,	0, 0xffff, NULL, divf_buffer),
1724	__IDE_PROC_DEVSET(buffer_size,	0, 0xffff, NULL, divf_buffer_size),
1725	__IDE_PROC_DEVSET(dsc_overlap,	0,      1, NULL, NULL),
1726	__IDE_PROC_DEVSET(speed,	0, 0xffff, NULL, NULL),
1727	__IDE_PROC_DEVSET(tdsc,		IDETAPE_DSC_RW_MIN, IDETAPE_DSC_RW_MAX,
1728					mulf_tdsc, divf_tdsc),
1729	{ NULL },
1730};
1731#endif
1732
1733/*
1734 * The function below is called to:
1735 *
1736 * 1. Initialize our various state variables.
1737 * 2. Ask the tape for its capabilities.
1738 * 3. Allocate a buffer which will be used for data transfer. The buffer size
1739 * is chosen based on the recommendation which we received in step 2.
1740 *
1741 * Note that at this point ide.c already assigned us an irq, so that we can
1742 * queue requests here and wait for their completion.
1743 */
1744static void idetape_setup(ide_drive_t *drive, idetape_tape_t *tape, int minor)
1745{
1746	unsigned long t;
1747	int speed;
1748	int buffer_size;
1749	u16 *ctl = (u16 *)&tape->caps[12];
1750
1751	ide_debug_log(IDE_DBG_FUNC, "minor: %d", minor);
1752
1753	drive->pc_callback = ide_tape_callback;
1754
1755	drive->dev_flags |= IDE_DFLAG_DSC_OVERLAP;
1756
1757	if (drive->hwif->host_flags & IDE_HFLAG_NO_DSC) {
1758		printk(KERN_INFO "ide-tape: %s: disabling DSC overlap\n",
1759				 tape->name);
1760		drive->dev_flags &= ~IDE_DFLAG_DSC_OVERLAP;
1761	}
1762
1763	/* Seagate Travan drives do not support DSC overlap. */
1764	if (strstr((char *)&drive->id[ATA_ID_PROD], "Seagate STT3401"))
1765		drive->dev_flags &= ~IDE_DFLAG_DSC_OVERLAP;
1766
1767	tape->minor = minor;
1768	tape->name[0] = 'h';
1769	tape->name[1] = 't';
1770	tape->name[2] = '0' + minor;
1771	tape->chrdev_dir = IDETAPE_DIR_NONE;
1772
1773	idetape_get_inquiry_results(drive);
1774	idetape_get_mode_sense_results(drive);
1775	ide_tape_get_bsize_from_bdesc(drive);
1776	tape->user_bs_factor = 1;
1777	tape->buffer_size = *ctl * tape->blk_size;
1778	while (tape->buffer_size > 0xffff) {
1779		printk(KERN_NOTICE "ide-tape: decreasing stage size\n");
1780		*ctl /= 2;
1781		tape->buffer_size = *ctl * tape->blk_size;
1782	}
1783	buffer_size = tape->buffer_size;
1784
1785	/* select the "best" DSC read/write polling freq */
1786	speed = max(*(u16 *)&tape->caps[14], *(u16 *)&tape->caps[8]);
1787
1788	t = (IDETAPE_FIFO_THRESHOLD * tape->buffer_size * HZ) / (speed * 1000);
1789
1790	/*
1791	 * Ensure that the number we got makes sense; limit it within
1792	 * IDETAPE_DSC_RW_MIN and IDETAPE_DSC_RW_MAX.
1793	 */
1794	tape->best_dsc_rw_freq = clamp_t(unsigned long, t, IDETAPE_DSC_RW_MIN,
1795					 IDETAPE_DSC_RW_MAX);
1796	printk(KERN_INFO "ide-tape: %s <-> %s: %dKBps, %d*%dkB buffer, "
1797		"%lums tDSC%s\n",
1798		drive->name, tape->name, *(u16 *)&tape->caps[14],
1799		(*(u16 *)&tape->caps[16] * 512) / tape->buffer_size,
1800		tape->buffer_size / 1024,
1801		tape->best_dsc_rw_freq * 1000 / HZ,
1802		(drive->dev_flags & IDE_DFLAG_USING_DMA) ? ", DMA" : "");
1803
1804	ide_proc_register_driver(drive, tape->driver);
1805}
1806
1807static void ide_tape_remove(ide_drive_t *drive)
1808{
1809	idetape_tape_t *tape = drive->driver_data;
1810
1811	ide_proc_unregister_driver(drive, tape->driver);
1812	device_del(&tape->dev);
1813	ide_unregister_region(tape->disk);
1814
1815	mutex_lock(&idetape_ref_mutex);
1816	put_device(&tape->dev);
1817	mutex_unlock(&idetape_ref_mutex);
1818}
1819
1820static void ide_tape_release(struct device *dev)
1821{
1822	struct ide_tape_obj *tape = to_ide_drv(dev, ide_tape_obj);
1823	ide_drive_t *drive = tape->drive;
1824	struct gendisk *g = tape->disk;
1825
1826	BUG_ON(tape->valid);
1827
1828	drive->dev_flags &= ~IDE_DFLAG_DSC_OVERLAP;
1829	drive->driver_data = NULL;
1830	device_destroy(idetape_sysfs_class, MKDEV(IDETAPE_MAJOR, tape->minor));
1831	device_destroy(idetape_sysfs_class,
1832			MKDEV(IDETAPE_MAJOR, tape->minor + 128));
1833	idetape_devs[tape->minor] = NULL;
1834	g->private_data = NULL;
1835	put_disk(g);
1836	kfree(tape);
1837}
1838
1839#ifdef CONFIG_IDE_PROC_FS
1840static int idetape_name_proc_show(struct seq_file *m, void *v)
1841{
1842	ide_drive_t	*drive = (ide_drive_t *) m->private;
1843	idetape_tape_t	*tape = drive->driver_data;
1844
1845	seq_printf(m, "%s\n", tape->name);
1846	return 0;
1847}
1848
1849static int idetape_name_proc_open(struct inode *inode, struct file *file)
1850{
1851	return single_open(file, idetape_name_proc_show, PDE(inode)->data);
1852}
1853
1854static const struct file_operations idetape_name_proc_fops = {
1855	.owner		= THIS_MODULE,
1856	.open		= idetape_name_proc_open,
1857	.read		= seq_read,
1858	.llseek		= seq_lseek,
1859	.release	= single_release,
1860};
1861
1862static ide_proc_entry_t idetape_proc[] = {
1863	{ "capacity",	S_IFREG|S_IRUGO,	&ide_capacity_proc_fops	},
1864	{ "name",	S_IFREG|S_IRUGO,	&idetape_name_proc_fops	},
1865	{}
1866};
1867
1868static ide_proc_entry_t *ide_tape_proc_entries(ide_drive_t *drive)
1869{
1870	return idetape_proc;
1871}
1872
1873static const struct ide_proc_devset *ide_tape_proc_devsets(ide_drive_t *drive)
1874{
1875	return idetape_settings;
1876}
1877#endif
1878
1879static int ide_tape_probe(ide_drive_t *);
1880
1881static struct ide_driver idetape_driver = {
1882	.gen_driver = {
1883		.owner		= THIS_MODULE,
1884		.name		= "ide-tape",
1885		.bus		= &ide_bus_type,
1886	},
1887	.probe			= ide_tape_probe,
1888	.remove			= ide_tape_remove,
1889	.version		= IDETAPE_VERSION,
1890	.do_request		= idetape_do_request,
1891#ifdef CONFIG_IDE_PROC_FS
1892	.proc_entries		= ide_tape_proc_entries,
1893	.proc_devsets		= ide_tape_proc_devsets,
1894#endif
1895};
1896
1897/* Our character device supporting functions, passed to register_chrdev. */
1898static const struct file_operations idetape_fops = {
1899	.owner		= THIS_MODULE,
1900	.read		= idetape_chrdev_read,
1901	.write		= idetape_chrdev_write,
1902	.unlocked_ioctl	= idetape_chrdev_ioctl,
1903	.open		= idetape_chrdev_open,
1904	.release	= idetape_chrdev_release,
1905	.llseek		= noop_llseek,
1906};
1907
1908static int idetape_open(struct block_device *bdev, fmode_t mode)
1909{
1910	struct ide_tape_obj *tape;
1911
1912	mutex_lock(&ide_tape_mutex);
1913	tape = ide_tape_get(bdev->bd_disk, false, 0);
1914	mutex_unlock(&ide_tape_mutex);
1915
1916	if (!tape)
1917		return -ENXIO;
1918
1919	return 0;
1920}
1921
1922static int idetape_release(struct gendisk *disk, fmode_t mode)
1923{
1924	struct ide_tape_obj *tape = ide_drv_g(disk, ide_tape_obj);
1925
1926	mutex_lock(&ide_tape_mutex);
1927	ide_tape_put(tape);
1928	mutex_unlock(&ide_tape_mutex);
1929
1930	return 0;
1931}
1932
1933static int idetape_ioctl(struct block_device *bdev, fmode_t mode,
1934			unsigned int cmd, unsigned long arg)
1935{
1936	struct ide_tape_obj *tape = ide_drv_g(bdev->bd_disk, ide_tape_obj);
1937	ide_drive_t *drive = tape->drive;
1938	int err;
1939
1940	mutex_lock(&ide_tape_mutex);
1941	err = generic_ide_ioctl(drive, bdev, cmd, arg);
1942	if (err == -EINVAL)
1943		err = idetape_blkdev_ioctl(drive, cmd, arg);
1944	mutex_unlock(&ide_tape_mutex);
1945
1946	return err;
1947}
1948
1949static const struct block_device_operations idetape_block_ops = {
1950	.owner		= THIS_MODULE,
1951	.open		= idetape_open,
1952	.release	= idetape_release,
1953	.ioctl		= idetape_ioctl,
1954};
1955
1956static int ide_tape_probe(ide_drive_t *drive)
1957{
1958	idetape_tape_t *tape;
1959	struct gendisk *g;
1960	int minor;
1961
1962	ide_debug_log(IDE_DBG_FUNC, "enter");
1963
1964	if (!strstr(DRV_NAME, drive->driver_req))
1965		goto failed;
1966
1967	if (drive->media != ide_tape)
1968		goto failed;
1969
1970	if ((drive->dev_flags & IDE_DFLAG_ID_READ) &&
1971	    ide_check_atapi_device(drive, DRV_NAME) == 0) {
1972		printk(KERN_ERR "ide-tape: %s: not supported by this version of"
1973				" the driver\n", drive->name);
1974		goto failed;
1975	}
1976	tape = kzalloc(sizeof(idetape_tape_t), GFP_KERNEL);
1977	if (tape == NULL) {
1978		printk(KERN_ERR "ide-tape: %s: Can't allocate a tape struct\n",
1979				drive->name);
1980		goto failed;
1981	}
1982
1983	g = alloc_disk(1 << PARTN_BITS);
1984	if (!g)
1985		goto out_free_tape;
1986
1987	ide_init_disk(g, drive);
1988
1989	tape->dev.parent = &drive->gendev;
1990	tape->dev.release = ide_tape_release;
1991	dev_set_name(&tape->dev, dev_name(&drive->gendev));
1992
1993	if (device_register(&tape->dev))
1994		goto out_free_disk;
1995
1996	tape->drive = drive;
1997	tape->driver = &idetape_driver;
1998	tape->disk = g;
1999
2000	g->private_data = &tape->driver;
2001
2002	drive->driver_data = tape;
2003
2004	mutex_lock(&idetape_ref_mutex);
2005	for (minor = 0; idetape_devs[minor]; minor++)
2006		;
2007	idetape_devs[minor] = tape;
2008	mutex_unlock(&idetape_ref_mutex);
2009
2010	idetape_setup(drive, tape, minor);
2011
2012	device_create(idetape_sysfs_class, &drive->gendev,
2013		      MKDEV(IDETAPE_MAJOR, minor), NULL, "%s", tape->name);
2014	device_create(idetape_sysfs_class, &drive->gendev,
2015		      MKDEV(IDETAPE_MAJOR, minor + 128), NULL,
2016		      "n%s", tape->name);
2017
2018	g->fops = &idetape_block_ops;
2019	ide_register_region(g);
2020
2021	return 0;
2022
2023out_free_disk:
2024	put_disk(g);
2025out_free_tape:
2026	kfree(tape);
2027failed:
2028	return -ENODEV;
2029}
2030
2031static void __exit idetape_exit(void)
2032{
2033	driver_unregister(&idetape_driver.gen_driver);
2034	class_destroy(idetape_sysfs_class);
2035	unregister_chrdev(IDETAPE_MAJOR, "ht");
2036}
2037
2038static int __init idetape_init(void)
2039{
2040	int error = 1;
2041	idetape_sysfs_class = class_create(THIS_MODULE, "ide_tape");
2042	if (IS_ERR(idetape_sysfs_class)) {
2043		idetape_sysfs_class = NULL;
2044		printk(KERN_ERR "Unable to create sysfs class for ide tapes\n");
2045		error = -EBUSY;
2046		goto out;
2047	}
2048
2049	if (register_chrdev(IDETAPE_MAJOR, "ht", &idetape_fops)) {
2050		printk(KERN_ERR "ide-tape: Failed to register chrdev"
2051				" interface\n");
2052		error = -EBUSY;
2053		goto out_free_class;
2054	}
2055
2056	error = driver_register(&idetape_driver.gen_driver);
2057	if (error)
2058		goto out_free_driver;
2059
2060	return 0;
2061
2062out_free_driver:
2063	driver_unregister(&idetape_driver.gen_driver);
2064out_free_class:
2065	class_destroy(idetape_sysfs_class);
2066out:
2067	return error;
2068}
2069
2070MODULE_ALIAS("ide:*m-tape*");
2071module_init(idetape_init);
2072module_exit(idetape_exit);
2073MODULE_ALIAS_CHARDEV_MAJOR(IDETAPE_MAJOR);
2074MODULE_DESCRIPTION("ATAPI Streaming TAPE Driver");
2075MODULE_LICENSE("GPL");
v3.5.6
   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/seq_file.h>
  35#include <linux/slab.h>
  36#include <linux/pci.h>
  37#include <linux/ide.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/uaccess.h>
  45#include <linux/io.h>
  46#include <asm/unaligned.h>
  47#include <linux/mtio.h>
  48
  49/* define to see debug info */
  50#undef IDETAPE_DEBUG_LOG
  51
  52#ifdef IDETAPE_DEBUG_LOG
  53#define ide_debug_log(lvl, fmt, args...) __ide_debug_log(lvl, fmt, ## args)
  54#else
  55#define ide_debug_log(lvl, fmt, args...) do {} while (0)
  56#endif
  57
  58/**************************** Tunable parameters *****************************/
  59/*
  60 * After each failed packet command we issue a request sense command and retry
  61 * the packet command IDETAPE_MAX_PC_RETRIES times.
  62 *
  63 * Setting IDETAPE_MAX_PC_RETRIES to 0 will disable retries.
  64 */
  65#define IDETAPE_MAX_PC_RETRIES		3
  66
  67/*
  68 * The following parameter is used to select the point in the internal tape fifo
  69 * in which we will start to refill the buffer. Decreasing the following
  70 * parameter will improve the system's latency and interactive response, while
  71 * using a high value might improve system throughput.
  72 */
  73#define IDETAPE_FIFO_THRESHOLD		2
  74
  75/*
  76 * DSC polling parameters.
  77 *
  78 * Polling for DSC (a single bit in the status register) is a very important
  79 * function in ide-tape. There are two cases in which we poll for DSC:
  80 *
  81 * 1. Before a read/write packet command, to ensure that we can transfer data
  82 * from/to the tape's data buffers, without causing an actual media access.
  83 * In case the tape is not ready yet, we take out our request from the device
  84 * request queue, so that ide.c could service requests from the other device
  85 * on the same interface in the meantime.
  86 *
  87 * 2. After the successful initialization of a "media access packet command",
  88 * which is a command that can take a long time to complete (the interval can
  89 * range from several seconds to even an hour). Again, we postpone our request
  90 * in the middle to free the bus for the other device. The polling frequency
  91 * here should be lower than the read/write frequency since those media access
  92 * commands are slow. We start from a "fast" frequency - IDETAPE_DSC_MA_FAST
  93 * (1 second), and if we don't receive DSC after IDETAPE_DSC_MA_THRESHOLD
  94 * (5 min), we switch it to a lower frequency - IDETAPE_DSC_MA_SLOW (1 min).
  95 *
  96 * We also set a timeout for the timer, in case something goes wrong. The
  97 * timeout should be longer then the maximum execution time of a tape operation.
  98 */
  99
 100/* DSC timings. */
 101#define IDETAPE_DSC_RW_MIN		5*HZ/100	/* 50 msec */
 102#define IDETAPE_DSC_RW_MAX		40*HZ/100	/* 400 msec */
 103#define IDETAPE_DSC_RW_TIMEOUT		2*60*HZ		/* 2 minutes */
 104#define IDETAPE_DSC_MA_FAST		2*HZ		/* 2 seconds */
 105#define IDETAPE_DSC_MA_THRESHOLD	5*60*HZ		/* 5 minutes */
 106#define IDETAPE_DSC_MA_SLOW		30*HZ		/* 30 seconds */
 107#define IDETAPE_DSC_MA_TIMEOUT		2*60*60*HZ	/* 2 hours */
 108
 109/*************************** End of tunable parameters ***********************/
 110
 111/* tape directions */
 112enum {
 113	IDETAPE_DIR_NONE  = (1 << 0),
 114	IDETAPE_DIR_READ  = (1 << 1),
 115	IDETAPE_DIR_WRITE = (1 << 2),
 116};
 117
 118/* Tape door status */
 119#define DOOR_UNLOCKED			0
 120#define DOOR_LOCKED			1
 121#define DOOR_EXPLICITLY_LOCKED		2
 122
 123/* Some defines for the SPACE command */
 124#define IDETAPE_SPACE_OVER_FILEMARK	1
 125#define IDETAPE_SPACE_TO_EOD		3
 126
 127/* Some defines for the LOAD UNLOAD command */
 128#define IDETAPE_LU_LOAD_MASK		1
 129#define IDETAPE_LU_RETENSION_MASK	2
 130#define IDETAPE_LU_EOT_MASK		4
 131
 132/* Structures related to the SELECT SENSE / MODE SENSE packet commands. */
 133#define IDETAPE_BLOCK_DESCRIPTOR	0
 134#define IDETAPE_CAPABILITIES_PAGE	0x2a
 135
 136/*
 137 * Most of our global data which we need to save even as we leave the driver due
 138 * to an interrupt or a timer event is stored in the struct defined below.
 139 */
 140typedef struct ide_tape_obj {
 141	ide_drive_t		*drive;
 142	struct ide_driver	*driver;
 143	struct gendisk		*disk;
 144	struct device		dev;
 145
 146	/* used by REQ_IDETAPE_{READ,WRITE} requests */
 147	struct ide_atapi_pc queued_pc;
 148
 149	/*
 150	 * DSC polling variables.
 151	 *
 152	 * While polling for DSC we use postponed_rq to postpone the current
 153	 * request so that ide.c will be able to service pending requests on the
 154	 * other device. Note that at most we will have only one DSC (usually
 155	 * data transfer) request in the device request queue.
 156	 */
 157	bool postponed_rq;
 158
 159	/* The time in which we started polling for DSC */
 160	unsigned long dsc_polling_start;
 161	/* Timer used to poll for dsc */
 162	struct timer_list dsc_timer;
 163	/* Read/Write dsc polling frequency */
 164	unsigned long best_dsc_rw_freq;
 165	unsigned long dsc_poll_freq;
 166	unsigned long dsc_timeout;
 167
 168	/* Read position information */
 169	u8 partition;
 170	/* Current block */
 171	unsigned int first_frame;
 172
 173	/* Last error information */
 174	u8 sense_key, asc, ascq;
 175
 176	/* Character device operation */
 177	unsigned int minor;
 178	/* device name */
 179	char name[4];
 180	/* Current character device data transfer direction */
 181	u8 chrdev_dir;
 182
 183	/* tape block size, usually 512 or 1024 bytes */
 184	unsigned short blk_size;
 185	int user_bs_factor;
 186
 187	/* Copy of the tape's Capabilities and Mechanical Page */
 188	u8 caps[20];
 189
 190	/*
 191	 * Active data transfer request parameters.
 192	 *
 193	 * At most, there is only one ide-tape originated data transfer request
 194	 * in the device request queue. This allows ide.c to easily service
 195	 * requests from the other device when we postpone our active request.
 196	 */
 197
 198	/* Data buffer size chosen based on the tape's recommendation */
 199	int buffer_size;
 200	/* Staging buffer of buffer_size bytes */
 201	void *buf;
 202	/* The read/write cursor */
 203	void *cur;
 204	/* The number of valid bytes in buf */
 205	size_t valid;
 206
 207	/* Measures average tape speed */
 208	unsigned long avg_time;
 209	int avg_size;
 210	int avg_speed;
 211
 212	/* the door is currently locked */
 213	int door_locked;
 214	/* the tape hardware is write protected */
 215	char drv_write_prot;
 216	/* the tape is write protected (hardware or opened as read-only) */
 217	char write_prot;
 218} idetape_tape_t;
 219
 220static DEFINE_MUTEX(ide_tape_mutex);
 221static DEFINE_MUTEX(idetape_ref_mutex);
 222
 223static DEFINE_MUTEX(idetape_chrdev_mutex);
 224
 225static struct class *idetape_sysfs_class;
 226
 227static void ide_tape_release(struct device *);
 228
 229static struct ide_tape_obj *idetape_devs[MAX_HWIFS * MAX_DRIVES];
 230
 231static struct ide_tape_obj *ide_tape_get(struct gendisk *disk, bool cdev,
 232					 unsigned int i)
 233{
 234	struct ide_tape_obj *tape = NULL;
 235
 236	mutex_lock(&idetape_ref_mutex);
 237
 238	if (cdev)
 239		tape = idetape_devs[i];
 240	else
 241		tape = ide_drv_g(disk, ide_tape_obj);
 242
 243	if (tape) {
 244		if (ide_device_get(tape->drive))
 245			tape = NULL;
 246		else
 247			get_device(&tape->dev);
 248	}
 249
 250	mutex_unlock(&idetape_ref_mutex);
 251	return tape;
 252}
 253
 254static void ide_tape_put(struct ide_tape_obj *tape)
 255{
 256	ide_drive_t *drive = tape->drive;
 257
 258	mutex_lock(&idetape_ref_mutex);
 259	put_device(&tape->dev);
 260	ide_device_put(drive);
 261	mutex_unlock(&idetape_ref_mutex);
 262}
 263
 264/*
 265 * called on each failed packet command retry to analyze the request sense. We
 266 * currently do not utilize this information.
 267 */
 268static void idetape_analyze_error(ide_drive_t *drive)
 269{
 270	idetape_tape_t *tape = drive->driver_data;
 271	struct ide_atapi_pc *pc = drive->failed_pc;
 272	struct request *rq = drive->hwif->rq;
 273	u8 *sense = bio_data(rq->bio);
 274
 275	tape->sense_key = sense[2] & 0xF;
 276	tape->asc       = sense[12];
 277	tape->ascq      = sense[13];
 278
 279	ide_debug_log(IDE_DBG_FUNC,
 280		      "cmd: 0x%x, sense key = %x, asc = %x, ascq = %x",
 281		      rq->cmd[0], tape->sense_key, tape->asc, tape->ascq);
 282
 283	/* correct remaining bytes to transfer */
 284	if (pc->flags & PC_FLAG_DMA_ERROR)
 285		rq->resid_len = tape->blk_size * get_unaligned_be32(&sense[3]);
 286
 287	/*
 288	 * If error was the result of a zero-length read or write command,
 289	 * with sense key=5, asc=0x22, ascq=0, let it slide.  Some drives
 290	 * (i.e. Seagate STT3401A Travan) don't support 0-length read/writes.
 291	 */
 292	if ((pc->c[0] == READ_6 || pc->c[0] == WRITE_6)
 293	    /* length == 0 */
 294	    && pc->c[4] == 0 && pc->c[3] == 0 && pc->c[2] == 0) {
 295		if (tape->sense_key == 5) {
 296			/* don't report an error, everything's ok */
 297			pc->error = 0;
 298			/* don't retry read/write */
 299			pc->flags |= PC_FLAG_ABORT;
 300		}
 301	}
 302	if (pc->c[0] == READ_6 && (sense[2] & 0x80)) {
 303		pc->error = IDE_DRV_ERROR_FILEMARK;
 304		pc->flags |= PC_FLAG_ABORT;
 305	}
 306	if (pc->c[0] == WRITE_6) {
 307		if ((sense[2] & 0x40) || (tape->sense_key == 0xd
 308		     && tape->asc == 0x0 && tape->ascq == 0x2)) {
 309			pc->error = IDE_DRV_ERROR_EOD;
 310			pc->flags |= PC_FLAG_ABORT;
 311		}
 312	}
 313	if (pc->c[0] == READ_6 || pc->c[0] == WRITE_6) {
 314		if (tape->sense_key == 8) {
 315			pc->error = IDE_DRV_ERROR_EOD;
 316			pc->flags |= PC_FLAG_ABORT;
 317		}
 318		if (!(pc->flags & PC_FLAG_ABORT) &&
 319		    (blk_rq_bytes(rq) - rq->resid_len))
 320			pc->retries = IDETAPE_MAX_PC_RETRIES + 1;
 321	}
 322}
 323
 324static void ide_tape_handle_dsc(ide_drive_t *);
 325
 326static int ide_tape_callback(ide_drive_t *drive, int dsc)
 327{
 328	idetape_tape_t *tape = drive->driver_data;
 329	struct ide_atapi_pc *pc = drive->pc;
 330	struct request *rq = drive->hwif->rq;
 331	int uptodate = pc->error ? 0 : 1;
 332	int err = uptodate ? 0 : IDE_DRV_ERROR_GENERAL;
 333
 334	ide_debug_log(IDE_DBG_FUNC, "cmd: 0x%x, dsc: %d, err: %d", rq->cmd[0],
 335		      dsc, err);
 336
 337	if (dsc)
 338		ide_tape_handle_dsc(drive);
 339
 340	if (drive->failed_pc == pc)
 341		drive->failed_pc = NULL;
 342
 343	if (pc->c[0] == REQUEST_SENSE) {
 344		if (uptodate)
 345			idetape_analyze_error(drive);
 346		else
 347			printk(KERN_ERR "ide-tape: Error in REQUEST SENSE "
 348					"itself - Aborting request!\n");
 349	} else if (pc->c[0] == READ_6 || pc->c[0] == WRITE_6) {
 350		unsigned int blocks =
 351			(blk_rq_bytes(rq) - rq->resid_len) / tape->blk_size;
 352
 353		tape->avg_size += blocks * tape->blk_size;
 354
 355		if (time_after_eq(jiffies, tape->avg_time + HZ)) {
 356			tape->avg_speed = tape->avg_size * HZ /
 357				(jiffies - tape->avg_time) / 1024;
 358			tape->avg_size = 0;
 359			tape->avg_time = jiffies;
 360		}
 361
 362		tape->first_frame += blocks;
 363
 364		if (pc->error) {
 365			uptodate = 0;
 366			err = pc->error;
 367		}
 368	}
 369	rq->errors = err;
 370
 371	return uptodate;
 372}
 373
 374/*
 375 * Postpone the current request so that ide.c will be able to service requests
 376 * from another device on the same port while we are polling for DSC.
 377 */
 378static void ide_tape_stall_queue(ide_drive_t *drive)
 379{
 380	idetape_tape_t *tape = drive->driver_data;
 381
 382	ide_debug_log(IDE_DBG_FUNC, "cmd: 0x%x, dsc_poll_freq: %lu",
 383		      drive->hwif->rq->cmd[0], tape->dsc_poll_freq);
 384
 385	tape->postponed_rq = true;
 386
 387	ide_stall_queue(drive, tape->dsc_poll_freq);
 388}
 389
 390static void ide_tape_handle_dsc(ide_drive_t *drive)
 391{
 392	idetape_tape_t *tape = drive->driver_data;
 393
 394	/* Media access command */
 395	tape->dsc_polling_start = jiffies;
 396	tape->dsc_poll_freq = IDETAPE_DSC_MA_FAST;
 397	tape->dsc_timeout = jiffies + IDETAPE_DSC_MA_TIMEOUT;
 398	/* Allow ide.c to handle other requests */
 399	ide_tape_stall_queue(drive);
 400}
 401
 402/*
 403 * Packet Command Interface
 404 *
 405 * The current Packet Command is available in drive->pc, and will not change
 406 * until we finish handling it. Each packet command is associated with a
 407 * callback function that will be called when the command is finished.
 408 *
 409 * The handling will be done in three stages:
 410 *
 411 * 1. ide_tape_issue_pc will send the packet command to the drive, and will set
 412 * the interrupt handler to ide_pc_intr.
 413 *
 414 * 2. On each interrupt, ide_pc_intr will be called. This step will be
 415 * repeated until the device signals us that no more interrupts will be issued.
 416 *
 417 * 3. ATAPI Tape media access commands have immediate status with a delayed
 418 * process. In case of a successful initiation of a media access packet command,
 419 * the DSC bit will be set when the actual execution of the command is finished.
 420 * Since the tape drive will not issue an interrupt, we have to poll for this
 421 * event. In this case, we define the request as "low priority request" by
 422 * setting rq_status to IDETAPE_RQ_POSTPONED, set a timer to poll for DSC and
 423 * exit the driver.
 424 *
 425 * ide.c will then give higher priority to requests which originate from the
 426 * other device, until will change rq_status to RQ_ACTIVE.
 427 *
 428 * 4. When the packet command is finished, it will be checked for errors.
 429 *
 430 * 5. In case an error was found, we queue a request sense packet command in
 431 * front of the request queue and retry the operation up to
 432 * IDETAPE_MAX_PC_RETRIES times.
 433 *
 434 * 6. In case no error was found, or we decided to give up and not to retry
 435 * again, the callback function will be called and then we will handle the next
 436 * request.
 437 */
 438
 439static ide_startstop_t ide_tape_issue_pc(ide_drive_t *drive,
 440					 struct ide_cmd *cmd,
 441					 struct ide_atapi_pc *pc)
 442{
 443	idetape_tape_t *tape = drive->driver_data;
 444	struct request *rq = drive->hwif->rq;
 445
 446	if (drive->failed_pc == NULL && pc->c[0] != REQUEST_SENSE)
 447		drive->failed_pc = pc;
 448
 449	/* Set the current packet command */
 450	drive->pc = pc;
 451
 452	if (pc->retries > IDETAPE_MAX_PC_RETRIES ||
 453		(pc->flags & PC_FLAG_ABORT)) {
 454
 455		/*
 456		 * We will "abort" retrying a packet command in case legitimate
 457		 * error code was received (crossing a filemark, or end of the
 458		 * media, for example).
 459		 */
 460		if (!(pc->flags & PC_FLAG_ABORT)) {
 461			if (!(pc->c[0] == TEST_UNIT_READY &&
 462			      tape->sense_key == 2 && tape->asc == 4 &&
 463			     (tape->ascq == 1 || tape->ascq == 8))) {
 464				printk(KERN_ERR "ide-tape: %s: I/O error, "
 465						"pc = %2x, key = %2x, "
 466						"asc = %2x, ascq = %2x\n",
 467						tape->name, pc->c[0],
 468						tape->sense_key, tape->asc,
 469						tape->ascq);
 470			}
 471			/* Giving up */
 472			pc->error = IDE_DRV_ERROR_GENERAL;
 473		}
 474
 475		drive->failed_pc = NULL;
 476		drive->pc_callback(drive, 0);
 477		ide_complete_rq(drive, -EIO, blk_rq_bytes(rq));
 478		return ide_stopped;
 479	}
 480	ide_debug_log(IDE_DBG_SENSE, "retry #%d, cmd: 0x%02x", pc->retries,
 481		      pc->c[0]);
 482
 483	pc->retries++;
 484
 485	return ide_issue_pc(drive, cmd);
 486}
 487
 488/* A mode sense command is used to "sense" tape parameters. */
 489static void idetape_create_mode_sense_cmd(struct ide_atapi_pc *pc, u8 page_code)
 490{
 491	ide_init_pc(pc);
 492	pc->c[0] = MODE_SENSE;
 493	if (page_code != IDETAPE_BLOCK_DESCRIPTOR)
 494		/* DBD = 1 - Don't return block descriptors */
 495		pc->c[1] = 8;
 496	pc->c[2] = page_code;
 497	/*
 498	 * Changed pc->c[3] to 0 (255 will at best return unused info).
 499	 *
 500	 * For SCSI this byte is defined as subpage instead of high byte
 501	 * of length and some IDE drives seem to interpret it this way
 502	 * and return an error when 255 is used.
 503	 */
 504	pc->c[3] = 0;
 505	/* We will just discard data in that case */
 506	pc->c[4] = 255;
 507	if (page_code == IDETAPE_BLOCK_DESCRIPTOR)
 508		pc->req_xfer = 12;
 509	else if (page_code == IDETAPE_CAPABILITIES_PAGE)
 510		pc->req_xfer = 24;
 511	else
 512		pc->req_xfer = 50;
 513}
 514
 515static ide_startstop_t idetape_media_access_finished(ide_drive_t *drive)
 516{
 517	ide_hwif_t *hwif = drive->hwif;
 518	idetape_tape_t *tape = drive->driver_data;
 519	struct ide_atapi_pc *pc = drive->pc;
 520	u8 stat;
 521
 522	stat = hwif->tp_ops->read_status(hwif);
 523
 524	if (stat & ATA_DSC) {
 525		if (stat & ATA_ERR) {
 526			/* Error detected */
 527			if (pc->c[0] != TEST_UNIT_READY)
 528				printk(KERN_ERR "ide-tape: %s: I/O error, ",
 529						tape->name);
 530			/* Retry operation */
 531			ide_retry_pc(drive);
 532			return ide_stopped;
 533		}
 534		pc->error = 0;
 535	} else {
 536		pc->error = IDE_DRV_ERROR_GENERAL;
 537		drive->failed_pc = NULL;
 538	}
 539	drive->pc_callback(drive, 0);
 540	return ide_stopped;
 541}
 542
 543static void ide_tape_create_rw_cmd(idetape_tape_t *tape,
 544				   struct ide_atapi_pc *pc, struct request *rq,
 545				   u8 opcode)
 546{
 547	unsigned int length = blk_rq_sectors(rq) / (tape->blk_size >> 9);
 548
 549	ide_init_pc(pc);
 550	put_unaligned(cpu_to_be32(length), (unsigned int *) &pc->c[1]);
 551	pc->c[1] = 1;
 552
 553	if (blk_rq_bytes(rq) == tape->buffer_size)
 554		pc->flags |= PC_FLAG_DMA_OK;
 555
 556	if (opcode == READ_6)
 557		pc->c[0] = READ_6;
 558	else if (opcode == WRITE_6) {
 559		pc->c[0] = WRITE_6;
 560		pc->flags |= PC_FLAG_WRITING;
 561	}
 562
 563	memcpy(rq->cmd, pc->c, 12);
 564}
 565
 566static ide_startstop_t idetape_do_request(ide_drive_t *drive,
 567					  struct request *rq, sector_t block)
 568{
 569	ide_hwif_t *hwif = drive->hwif;
 570	idetape_tape_t *tape = drive->driver_data;
 571	struct ide_atapi_pc *pc = NULL;
 572	struct ide_cmd cmd;
 573	u8 stat;
 574
 575	ide_debug_log(IDE_DBG_RQ, "cmd: 0x%x, sector: %llu, nr_sectors: %u",
 576		      rq->cmd[0], (unsigned long long)blk_rq_pos(rq),
 577		      blk_rq_sectors(rq));
 578
 579	BUG_ON(!(rq->cmd_type == REQ_TYPE_SPECIAL ||
 580		 rq->cmd_type == REQ_TYPE_SENSE));
 581
 582	/* Retry a failed packet command */
 583	if (drive->failed_pc && drive->pc->c[0] == REQUEST_SENSE) {
 584		pc = drive->failed_pc;
 585		goto out;
 586	}
 587
 588	/*
 589	 * If the tape is still busy, postpone our request and service
 590	 * the other device meanwhile.
 591	 */
 592	stat = hwif->tp_ops->read_status(hwif);
 593
 594	if ((drive->dev_flags & IDE_DFLAG_DSC_OVERLAP) == 0 &&
 595	    (rq->cmd[13] & REQ_IDETAPE_PC2) == 0)
 596		drive->atapi_flags |= IDE_AFLAG_IGNORE_DSC;
 597
 598	if (drive->dev_flags & IDE_DFLAG_POST_RESET) {
 599		drive->atapi_flags |= IDE_AFLAG_IGNORE_DSC;
 600		drive->dev_flags &= ~IDE_DFLAG_POST_RESET;
 601	}
 602
 603	if (!(drive->atapi_flags & IDE_AFLAG_IGNORE_DSC) &&
 604	    !(stat & ATA_DSC)) {
 605		if (!tape->postponed_rq) {
 606			tape->dsc_polling_start = jiffies;
 607			tape->dsc_poll_freq = tape->best_dsc_rw_freq;
 608			tape->dsc_timeout = jiffies + IDETAPE_DSC_RW_TIMEOUT;
 609		} else if (time_after(jiffies, tape->dsc_timeout)) {
 610			printk(KERN_ERR "ide-tape: %s: DSC timeout\n",
 611				tape->name);
 612			if (rq->cmd[13] & REQ_IDETAPE_PC2) {
 613				idetape_media_access_finished(drive);
 614				return ide_stopped;
 615			} else {
 616				return ide_do_reset(drive);
 617			}
 618		} else if (time_after(jiffies,
 619					tape->dsc_polling_start +
 620					IDETAPE_DSC_MA_THRESHOLD))
 621			tape->dsc_poll_freq = IDETAPE_DSC_MA_SLOW;
 622		ide_tape_stall_queue(drive);
 623		return ide_stopped;
 624	} else {
 625		drive->atapi_flags &= ~IDE_AFLAG_IGNORE_DSC;
 626		tape->postponed_rq = false;
 627	}
 628
 629	if (rq->cmd[13] & REQ_IDETAPE_READ) {
 630		pc = &tape->queued_pc;
 631		ide_tape_create_rw_cmd(tape, pc, rq, READ_6);
 632		goto out;
 633	}
 634	if (rq->cmd[13] & REQ_IDETAPE_WRITE) {
 635		pc = &tape->queued_pc;
 636		ide_tape_create_rw_cmd(tape, pc, rq, WRITE_6);
 637		goto out;
 638	}
 639	if (rq->cmd[13] & REQ_IDETAPE_PC1) {
 640		pc = (struct ide_atapi_pc *)rq->special;
 641		rq->cmd[13] &= ~(REQ_IDETAPE_PC1);
 642		rq->cmd[13] |= REQ_IDETAPE_PC2;
 643		goto out;
 644	}
 645	if (rq->cmd[13] & REQ_IDETAPE_PC2) {
 646		idetape_media_access_finished(drive);
 647		return ide_stopped;
 648	}
 649	BUG();
 650
 651out:
 652	/* prepare sense request for this command */
 653	ide_prep_sense(drive, rq);
 654
 655	memset(&cmd, 0, sizeof(cmd));
 656
 657	if (rq_data_dir(rq))
 658		cmd.tf_flags |= IDE_TFLAG_WRITE;
 659
 660	cmd.rq = rq;
 661
 662	ide_init_sg_cmd(&cmd, blk_rq_bytes(rq));
 663	ide_map_sg(drive, &cmd);
 664
 665	return ide_tape_issue_pc(drive, &cmd, pc);
 666}
 667
 668/*
 669 * Write a filemark if write_filemark=1. Flush the device buffers without
 670 * writing a filemark otherwise.
 671 */
 672static void idetape_create_write_filemark_cmd(ide_drive_t *drive,
 673		struct ide_atapi_pc *pc, int write_filemark)
 674{
 675	ide_init_pc(pc);
 676	pc->c[0] = WRITE_FILEMARKS;
 677	pc->c[4] = write_filemark;
 678	pc->flags |= PC_FLAG_WAIT_FOR_DSC;
 679}
 680
 681static int idetape_wait_ready(ide_drive_t *drive, unsigned long timeout)
 682{
 683	idetape_tape_t *tape = drive->driver_data;
 684	struct gendisk *disk = tape->disk;
 685	int load_attempted = 0;
 686
 687	/* Wait for the tape to become ready */
 688	set_bit(ilog2(IDE_AFLAG_MEDIUM_PRESENT), &drive->atapi_flags);
 689	timeout += jiffies;
 690	while (time_before(jiffies, timeout)) {
 691		if (ide_do_test_unit_ready(drive, disk) == 0)
 692			return 0;
 693		if ((tape->sense_key == 2 && tape->asc == 4 && tape->ascq == 2)
 694		    || (tape->asc == 0x3A)) {
 695			/* no media */
 696			if (load_attempted)
 697				return -ENOMEDIUM;
 698			ide_do_start_stop(drive, disk, IDETAPE_LU_LOAD_MASK);
 699			load_attempted = 1;
 700		/* not about to be ready */
 701		} else if (!(tape->sense_key == 2 && tape->asc == 4 &&
 702			     (tape->ascq == 1 || tape->ascq == 8)))
 703			return -EIO;
 704		msleep(100);
 705	}
 706	return -EIO;
 707}
 708
 709static int idetape_flush_tape_buffers(ide_drive_t *drive)
 710{
 711	struct ide_tape_obj *tape = drive->driver_data;
 712	struct ide_atapi_pc pc;
 713	int rc;
 714
 715	idetape_create_write_filemark_cmd(drive, &pc, 0);
 716	rc = ide_queue_pc_tail(drive, tape->disk, &pc, NULL, 0);
 717	if (rc)
 718		return rc;
 719	idetape_wait_ready(drive, 60 * 5 * HZ);
 720	return 0;
 721}
 722
 723static int ide_tape_read_position(ide_drive_t *drive)
 724{
 725	idetape_tape_t *tape = drive->driver_data;
 726	struct ide_atapi_pc pc;
 727	u8 buf[20];
 728
 729	ide_debug_log(IDE_DBG_FUNC, "enter");
 730
 731	/* prep cmd */
 732	ide_init_pc(&pc);
 733	pc.c[0] = READ_POSITION;
 734	pc.req_xfer = 20;
 735
 736	if (ide_queue_pc_tail(drive, tape->disk, &pc, buf, pc.req_xfer))
 737		return -1;
 738
 739	if (!pc.error) {
 740		ide_debug_log(IDE_DBG_FUNC, "BOP - %s",
 741				(buf[0] & 0x80) ? "Yes" : "No");
 742		ide_debug_log(IDE_DBG_FUNC, "EOP - %s",
 743				(buf[0] & 0x40) ? "Yes" : "No");
 744
 745		if (buf[0] & 0x4) {
 746			printk(KERN_INFO "ide-tape: Block location is unknown"
 747					 "to the tape\n");
 748			clear_bit(ilog2(IDE_AFLAG_ADDRESS_VALID),
 749				  &drive->atapi_flags);
 750			return -1;
 751		} else {
 752			ide_debug_log(IDE_DBG_FUNC, "Block Location: %u",
 753				      be32_to_cpup((__be32 *)&buf[4]));
 754
 755			tape->partition = buf[1];
 756			tape->first_frame = be32_to_cpup((__be32 *)&buf[4]);
 757			set_bit(ilog2(IDE_AFLAG_ADDRESS_VALID),
 758				&drive->atapi_flags);
 759		}
 760	}
 761
 762	return tape->first_frame;
 763}
 764
 765static void idetape_create_locate_cmd(ide_drive_t *drive,
 766		struct ide_atapi_pc *pc,
 767		unsigned int block, u8 partition, int skip)
 768{
 769	ide_init_pc(pc);
 770	pc->c[0] = POSITION_TO_ELEMENT;
 771	pc->c[1] = 2;
 772	put_unaligned(cpu_to_be32(block), (unsigned int *) &pc->c[3]);
 773	pc->c[8] = partition;
 774	pc->flags |= PC_FLAG_WAIT_FOR_DSC;
 775}
 776
 777static void __ide_tape_discard_merge_buffer(ide_drive_t *drive)
 778{
 779	idetape_tape_t *tape = drive->driver_data;
 780
 781	if (tape->chrdev_dir != IDETAPE_DIR_READ)
 782		return;
 783
 784	clear_bit(ilog2(IDE_AFLAG_FILEMARK), &drive->atapi_flags);
 785	tape->valid = 0;
 786	if (tape->buf != NULL) {
 787		kfree(tape->buf);
 788		tape->buf = NULL;
 789	}
 790
 791	tape->chrdev_dir = IDETAPE_DIR_NONE;
 792}
 793
 794/*
 795 * Position the tape to the requested block using the LOCATE packet command.
 796 * A READ POSITION command is then issued to check where we are positioned. Like
 797 * all higher level operations, we queue the commands at the tail of the request
 798 * queue and wait for their completion.
 799 */
 800static int idetape_position_tape(ide_drive_t *drive, unsigned int block,
 801		u8 partition, int skip)
 802{
 803	idetape_tape_t *tape = drive->driver_data;
 804	struct gendisk *disk = tape->disk;
 805	int ret;
 806	struct ide_atapi_pc pc;
 807
 808	if (tape->chrdev_dir == IDETAPE_DIR_READ)
 809		__ide_tape_discard_merge_buffer(drive);
 810	idetape_wait_ready(drive, 60 * 5 * HZ);
 811	idetape_create_locate_cmd(drive, &pc, block, partition, skip);
 812	ret = ide_queue_pc_tail(drive, disk, &pc, NULL, 0);
 813	if (ret)
 814		return ret;
 815
 816	ret = ide_tape_read_position(drive);
 817	if (ret < 0)
 818		return ret;
 819	return 0;
 820}
 821
 822static void ide_tape_discard_merge_buffer(ide_drive_t *drive,
 823					  int restore_position)
 824{
 825	idetape_tape_t *tape = drive->driver_data;
 826	int seek, position;
 827
 828	__ide_tape_discard_merge_buffer(drive);
 829	if (restore_position) {
 830		position = ide_tape_read_position(drive);
 831		seek = position > 0 ? position : 0;
 832		if (idetape_position_tape(drive, seek, 0, 0)) {
 833			printk(KERN_INFO "ide-tape: %s: position_tape failed in"
 834					 " %s\n", tape->name, __func__);
 835			return;
 836		}
 837	}
 838}
 839
 840/*
 841 * Generate a read/write request for the block device interface and wait for it
 842 * to be serviced.
 843 */
 844static int idetape_queue_rw_tail(ide_drive_t *drive, int cmd, int size)
 845{
 846	idetape_tape_t *tape = drive->driver_data;
 847	struct request *rq;
 848	int ret;
 849
 850	ide_debug_log(IDE_DBG_FUNC, "cmd: 0x%x, size: %d", cmd, size);
 851
 852	BUG_ON(cmd != REQ_IDETAPE_READ && cmd != REQ_IDETAPE_WRITE);
 853	BUG_ON(size < 0 || size % tape->blk_size);
 854
 855	rq = blk_get_request(drive->queue, READ, __GFP_WAIT);
 856	rq->cmd_type = REQ_TYPE_SPECIAL;
 857	rq->cmd[13] = cmd;
 858	rq->rq_disk = tape->disk;
 859	rq->__sector = tape->first_frame;
 860
 861	if (size) {
 862		ret = blk_rq_map_kern(drive->queue, rq, tape->buf, size,
 863				      __GFP_WAIT);
 864		if (ret)
 865			goto out_put;
 866	}
 867
 868	blk_execute_rq(drive->queue, tape->disk, rq, 0);
 869
 870	/* calculate the number of transferred bytes and update buffer state */
 871	size -= rq->resid_len;
 872	tape->cur = tape->buf;
 873	if (cmd == REQ_IDETAPE_READ)
 874		tape->valid = size;
 875	else
 876		tape->valid = 0;
 877
 878	ret = size;
 879	if (rq->errors == IDE_DRV_ERROR_GENERAL)
 880		ret = -EIO;
 881out_put:
 882	blk_put_request(rq);
 883	return ret;
 884}
 885
 886static void idetape_create_inquiry_cmd(struct ide_atapi_pc *pc)
 887{
 888	ide_init_pc(pc);
 889	pc->c[0] = INQUIRY;
 890	pc->c[4] = 254;
 891	pc->req_xfer = 254;
 892}
 893
 894static void idetape_create_rewind_cmd(ide_drive_t *drive,
 895		struct ide_atapi_pc *pc)
 896{
 897	ide_init_pc(pc);
 898	pc->c[0] = REZERO_UNIT;
 899	pc->flags |= PC_FLAG_WAIT_FOR_DSC;
 900}
 901
 902static void idetape_create_erase_cmd(struct ide_atapi_pc *pc)
 903{
 904	ide_init_pc(pc);
 905	pc->c[0] = ERASE;
 906	pc->c[1] = 1;
 907	pc->flags |= PC_FLAG_WAIT_FOR_DSC;
 908}
 909
 910static void idetape_create_space_cmd(struct ide_atapi_pc *pc, int count, u8 cmd)
 911{
 912	ide_init_pc(pc);
 913	pc->c[0] = SPACE;
 914	put_unaligned(cpu_to_be32(count), (unsigned int *) &pc->c[1]);
 915	pc->c[1] = cmd;
 916	pc->flags |= PC_FLAG_WAIT_FOR_DSC;
 917}
 918
 919static void ide_tape_flush_merge_buffer(ide_drive_t *drive)
 920{
 921	idetape_tape_t *tape = drive->driver_data;
 922
 923	if (tape->chrdev_dir != IDETAPE_DIR_WRITE) {
 924		printk(KERN_ERR "ide-tape: bug: Trying to empty merge buffer"
 925				" but we are not writing.\n");
 926		return;
 927	}
 928	if (tape->buf) {
 929		size_t aligned = roundup(tape->valid, tape->blk_size);
 930
 931		memset(tape->cur, 0, aligned - tape->valid);
 932		idetape_queue_rw_tail(drive, REQ_IDETAPE_WRITE, aligned);
 933		kfree(tape->buf);
 934		tape->buf = NULL;
 935	}
 936	tape->chrdev_dir = IDETAPE_DIR_NONE;
 937}
 938
 939static int idetape_init_rw(ide_drive_t *drive, int dir)
 940{
 941	idetape_tape_t *tape = drive->driver_data;
 942	int rc;
 943
 944	BUG_ON(dir != IDETAPE_DIR_READ && dir != IDETAPE_DIR_WRITE);
 945
 946	if (tape->chrdev_dir == dir)
 947		return 0;
 948
 949	if (tape->chrdev_dir == IDETAPE_DIR_READ)
 950		ide_tape_discard_merge_buffer(drive, 1);
 951	else if (tape->chrdev_dir == IDETAPE_DIR_WRITE) {
 952		ide_tape_flush_merge_buffer(drive);
 953		idetape_flush_tape_buffers(drive);
 954	}
 955
 956	if (tape->buf || tape->valid) {
 957		printk(KERN_ERR "ide-tape: valid should be 0 now\n");
 958		tape->valid = 0;
 959	}
 960
 961	tape->buf = kmalloc(tape->buffer_size, GFP_KERNEL);
 962	if (!tape->buf)
 963		return -ENOMEM;
 964	tape->chrdev_dir = dir;
 965	tape->cur = tape->buf;
 966
 967	/*
 968	 * Issue a 0 rw command to ensure that DSC handshake is
 969	 * switched from completion mode to buffer available mode.  No
 970	 * point in issuing this if DSC overlap isn't supported, some
 971	 * drives (Seagate STT3401A) will return an error.
 972	 */
 973	if (drive->dev_flags & IDE_DFLAG_DSC_OVERLAP) {
 974		int cmd = dir == IDETAPE_DIR_READ ? REQ_IDETAPE_READ
 975						  : REQ_IDETAPE_WRITE;
 976
 977		rc = idetape_queue_rw_tail(drive, cmd, 0);
 978		if (rc < 0) {
 979			kfree(tape->buf);
 980			tape->buf = NULL;
 981			tape->chrdev_dir = IDETAPE_DIR_NONE;
 982			return rc;
 983		}
 984	}
 985
 986	return 0;
 987}
 988
 989static void idetape_pad_zeros(ide_drive_t *drive, int bcount)
 990{
 991	idetape_tape_t *tape = drive->driver_data;
 992
 993	memset(tape->buf, 0, tape->buffer_size);
 994
 995	while (bcount) {
 996		unsigned int count = min(tape->buffer_size, bcount);
 997
 998		idetape_queue_rw_tail(drive, REQ_IDETAPE_WRITE, count);
 999		bcount -= count;
1000	}
1001}
1002
1003/*
1004 * Rewinds the tape to the Beginning Of the current Partition (BOP). We
1005 * currently support only one partition.
1006 */
1007static int idetape_rewind_tape(ide_drive_t *drive)
1008{
1009	struct ide_tape_obj *tape = drive->driver_data;
1010	struct gendisk *disk = tape->disk;
1011	struct ide_atapi_pc pc;
1012	int ret;
1013
1014	ide_debug_log(IDE_DBG_FUNC, "enter");
1015
1016	idetape_create_rewind_cmd(drive, &pc);
1017	ret = ide_queue_pc_tail(drive, disk, &pc, NULL, 0);
1018	if (ret)
1019		return ret;
1020
1021	ret = ide_tape_read_position(drive);
1022	if (ret < 0)
1023		return ret;
1024	return 0;
1025}
1026
1027/* mtio.h compatible commands should be issued to the chrdev interface. */
1028static int idetape_blkdev_ioctl(ide_drive_t *drive, unsigned int cmd,
1029				unsigned long arg)
1030{
1031	idetape_tape_t *tape = drive->driver_data;
1032	void __user *argp = (void __user *)arg;
1033
1034	struct idetape_config {
1035		int dsc_rw_frequency;
1036		int dsc_media_access_frequency;
1037		int nr_stages;
1038	} config;
1039
1040	ide_debug_log(IDE_DBG_FUNC, "cmd: 0x%04x", cmd);
1041
1042	switch (cmd) {
1043	case 0x0340:
1044		if (copy_from_user(&config, argp, sizeof(config)))
1045			return -EFAULT;
1046		tape->best_dsc_rw_freq = config.dsc_rw_frequency;
1047		break;
1048	case 0x0350:
1049		memset(&config, 0, sizeof(config));
1050		config.dsc_rw_frequency = (int) tape->best_dsc_rw_freq;
1051		config.nr_stages = 1;
1052		if (copy_to_user(argp, &config, sizeof(config)))
1053			return -EFAULT;
1054		break;
1055	default:
1056		return -EIO;
1057	}
1058	return 0;
1059}
1060
1061static int idetape_space_over_filemarks(ide_drive_t *drive, short mt_op,
1062					int mt_count)
1063{
1064	idetape_tape_t *tape = drive->driver_data;
1065	struct gendisk *disk = tape->disk;
1066	struct ide_atapi_pc pc;
1067	int retval, count = 0;
1068	int sprev = !!(tape->caps[4] & 0x20);
1069
1070
1071	ide_debug_log(IDE_DBG_FUNC, "mt_op: %d, mt_count: %d", mt_op, mt_count);
1072
1073	if (mt_count == 0)
1074		return 0;
1075	if (MTBSF == mt_op || MTBSFM == mt_op) {
1076		if (!sprev)
1077			return -EIO;
1078		mt_count = -mt_count;
1079	}
1080
1081	if (tape->chrdev_dir == IDETAPE_DIR_READ) {
1082		tape->valid = 0;
1083		if (test_and_clear_bit(ilog2(IDE_AFLAG_FILEMARK),
1084				       &drive->atapi_flags))
1085			++count;
1086		ide_tape_discard_merge_buffer(drive, 0);
1087	}
1088
1089	switch (mt_op) {
1090	case MTFSF:
1091	case MTBSF:
1092		idetape_create_space_cmd(&pc, mt_count - count,
1093					 IDETAPE_SPACE_OVER_FILEMARK);
1094		return ide_queue_pc_tail(drive, disk, &pc, NULL, 0);
1095	case MTFSFM:
1096	case MTBSFM:
1097		if (!sprev)
1098			return -EIO;
1099		retval = idetape_space_over_filemarks(drive, MTFSF,
1100						      mt_count - count);
1101		if (retval)
1102			return retval;
1103		count = (MTBSFM == mt_op ? 1 : -1);
1104		return idetape_space_over_filemarks(drive, MTFSF, count);
1105	default:
1106		printk(KERN_ERR "ide-tape: MTIO operation %d not supported\n",
1107				mt_op);
1108		return -EIO;
1109	}
1110}
1111
1112/*
1113 * Our character device read / write functions.
1114 *
1115 * The tape is optimized to maximize throughput when it is transferring an
1116 * integral number of the "continuous transfer limit", which is a parameter of
1117 * the specific tape (26kB on my particular tape, 32kB for Onstream).
1118 *
1119 * As of version 1.3 of the driver, the character device provides an abstract
1120 * continuous view of the media - any mix of block sizes (even 1 byte) on the
1121 * same backup/restore procedure is supported. The driver will internally
1122 * convert the requests to the recommended transfer unit, so that an unmatch
1123 * between the user's block size to the recommended size will only result in a
1124 * (slightly) increased driver overhead, but will no longer hit performance.
1125 * This is not applicable to Onstream.
1126 */
1127static ssize_t idetape_chrdev_read(struct file *file, char __user *buf,
1128				   size_t count, loff_t *ppos)
1129{
1130	struct ide_tape_obj *tape = file->private_data;
1131	ide_drive_t *drive = tape->drive;
1132	size_t done = 0;
1133	ssize_t ret = 0;
1134	int rc;
1135
1136	ide_debug_log(IDE_DBG_FUNC, "count %Zd", count);
1137
1138	if (tape->chrdev_dir != IDETAPE_DIR_READ) {
1139		if (test_bit(ilog2(IDE_AFLAG_DETECT_BS), &drive->atapi_flags))
1140			if (count > tape->blk_size &&
1141			    (count % tape->blk_size) == 0)
1142				tape->user_bs_factor = count / tape->blk_size;
1143	}
1144
1145	rc = idetape_init_rw(drive, IDETAPE_DIR_READ);
1146	if (rc < 0)
1147		return rc;
1148
1149	while (done < count) {
1150		size_t todo;
1151
1152		/* refill if staging buffer is empty */
1153		if (!tape->valid) {
1154			/* If we are at a filemark, nothing more to read */
1155			if (test_bit(ilog2(IDE_AFLAG_FILEMARK),
1156				     &drive->atapi_flags))
1157				break;
1158			/* read */
1159			if (idetape_queue_rw_tail(drive, REQ_IDETAPE_READ,
1160						  tape->buffer_size) <= 0)
1161				break;
1162		}
1163
1164		/* copy out */
1165		todo = min_t(size_t, count - done, tape->valid);
1166		if (copy_to_user(buf + done, tape->cur, todo))
1167			ret = -EFAULT;
1168
1169		tape->cur += todo;
1170		tape->valid -= todo;
1171		done += todo;
1172	}
1173
1174	if (!done && test_bit(ilog2(IDE_AFLAG_FILEMARK), &drive->atapi_flags)) {
1175		idetape_space_over_filemarks(drive, MTFSF, 1);
1176		return 0;
1177	}
1178
1179	return ret ? ret : done;
1180}
1181
1182static ssize_t idetape_chrdev_write(struct file *file, const char __user *buf,
1183				     size_t count, loff_t *ppos)
1184{
1185	struct ide_tape_obj *tape = file->private_data;
1186	ide_drive_t *drive = tape->drive;
1187	size_t done = 0;
1188	ssize_t ret = 0;
1189	int rc;
1190
1191	/* The drive is write protected. */
1192	if (tape->write_prot)
1193		return -EACCES;
1194
1195	ide_debug_log(IDE_DBG_FUNC, "count %Zd", count);
1196
1197	/* Initialize write operation */
1198	rc = idetape_init_rw(drive, IDETAPE_DIR_WRITE);
1199	if (rc < 0)
1200		return rc;
1201
1202	while (done < count) {
1203		size_t todo;
1204
1205		/* flush if staging buffer is full */
1206		if (tape->valid == tape->buffer_size &&
1207		    idetape_queue_rw_tail(drive, REQ_IDETAPE_WRITE,
1208					  tape->buffer_size) <= 0)
1209			return rc;
1210
1211		/* copy in */
1212		todo = min_t(size_t, count - done,
1213			     tape->buffer_size - tape->valid);
1214		if (copy_from_user(tape->cur, buf + done, todo))
1215			ret = -EFAULT;
1216
1217		tape->cur += todo;
1218		tape->valid += todo;
1219		done += todo;
1220	}
1221
1222	return ret ? ret : done;
1223}
1224
1225static int idetape_write_filemark(ide_drive_t *drive)
1226{
1227	struct ide_tape_obj *tape = drive->driver_data;
1228	struct ide_atapi_pc pc;
1229
1230	/* Write a filemark */
1231	idetape_create_write_filemark_cmd(drive, &pc, 1);
1232	if (ide_queue_pc_tail(drive, tape->disk, &pc, NULL, 0)) {
1233		printk(KERN_ERR "ide-tape: Couldn't write a filemark\n");
1234		return -EIO;
1235	}
1236	return 0;
1237}
1238
1239/*
1240 * Called from idetape_chrdev_ioctl when the general mtio MTIOCTOP ioctl is
1241 * requested.
1242 *
1243 * Note: MTBSF and MTBSFM are not supported when the tape doesn't support
1244 * spacing over filemarks in the reverse direction. In this case, MTFSFM is also
1245 * usually not supported.
1246 *
1247 * The following commands are currently not supported:
1248 *
1249 * MTFSS, MTBSS, MTWSM, MTSETDENSITY, MTSETDRVBUFFER, MT_ST_BOOLEANS,
1250 * MT_ST_WRITE_THRESHOLD.
1251 */
1252static int idetape_mtioctop(ide_drive_t *drive, short mt_op, int mt_count)
1253{
1254	idetape_tape_t *tape = drive->driver_data;
1255	struct gendisk *disk = tape->disk;
1256	struct ide_atapi_pc pc;
1257	int i, retval;
1258
1259	ide_debug_log(IDE_DBG_FUNC, "MTIOCTOP ioctl: mt_op: %d, mt_count: %d",
1260		      mt_op, mt_count);
1261
1262	switch (mt_op) {
1263	case MTFSF:
1264	case MTFSFM:
1265	case MTBSF:
1266	case MTBSFM:
1267		if (!mt_count)
1268			return 0;
1269		return idetape_space_over_filemarks(drive, mt_op, mt_count);
1270	default:
1271		break;
1272	}
1273
1274	switch (mt_op) {
1275	case MTWEOF:
1276		if (tape->write_prot)
1277			return -EACCES;
1278		ide_tape_discard_merge_buffer(drive, 1);
1279		for (i = 0; i < mt_count; i++) {
1280			retval = idetape_write_filemark(drive);
1281			if (retval)
1282				return retval;
1283		}
1284		return 0;
1285	case MTREW:
1286		ide_tape_discard_merge_buffer(drive, 0);
1287		if (idetape_rewind_tape(drive))
1288			return -EIO;
1289		return 0;
1290	case MTLOAD:
1291		ide_tape_discard_merge_buffer(drive, 0);
1292		return ide_do_start_stop(drive, disk, IDETAPE_LU_LOAD_MASK);
1293	case MTUNLOAD:
1294	case MTOFFL:
1295		/*
1296		 * If door is locked, attempt to unlock before
1297		 * attempting to eject.
1298		 */
1299		if (tape->door_locked) {
1300			if (!ide_set_media_lock(drive, disk, 0))
1301				tape->door_locked = DOOR_UNLOCKED;
1302		}
1303		ide_tape_discard_merge_buffer(drive, 0);
1304		retval = ide_do_start_stop(drive, disk, !IDETAPE_LU_LOAD_MASK);
1305		if (!retval)
1306			clear_bit(ilog2(IDE_AFLAG_MEDIUM_PRESENT),
1307				  &drive->atapi_flags);
1308		return retval;
1309	case MTNOP:
1310		ide_tape_discard_merge_buffer(drive, 0);
1311		return idetape_flush_tape_buffers(drive);
1312	case MTRETEN:
1313		ide_tape_discard_merge_buffer(drive, 0);
1314		return ide_do_start_stop(drive, disk,
1315			IDETAPE_LU_RETENSION_MASK | IDETAPE_LU_LOAD_MASK);
1316	case MTEOM:
1317		idetape_create_space_cmd(&pc, 0, IDETAPE_SPACE_TO_EOD);
1318		return ide_queue_pc_tail(drive, disk, &pc, NULL, 0);
1319	case MTERASE:
1320		(void)idetape_rewind_tape(drive);
1321		idetape_create_erase_cmd(&pc);
1322		return ide_queue_pc_tail(drive, disk, &pc, NULL, 0);
1323	case MTSETBLK:
1324		if (mt_count) {
1325			if (mt_count < tape->blk_size ||
1326			    mt_count % tape->blk_size)
1327				return -EIO;
1328			tape->user_bs_factor = mt_count / tape->blk_size;
1329			clear_bit(ilog2(IDE_AFLAG_DETECT_BS),
1330				  &drive->atapi_flags);
1331		} else
1332			set_bit(ilog2(IDE_AFLAG_DETECT_BS),
1333				&drive->atapi_flags);
1334		return 0;
1335	case MTSEEK:
1336		ide_tape_discard_merge_buffer(drive, 0);
1337		return idetape_position_tape(drive,
1338			mt_count * tape->user_bs_factor, tape->partition, 0);
1339	case MTSETPART:
1340		ide_tape_discard_merge_buffer(drive, 0);
1341		return idetape_position_tape(drive, 0, mt_count, 0);
1342	case MTFSR:
1343	case MTBSR:
1344	case MTLOCK:
1345		retval = ide_set_media_lock(drive, disk, 1);
1346		if (retval)
1347			return retval;
1348		tape->door_locked = DOOR_EXPLICITLY_LOCKED;
1349		return 0;
1350	case MTUNLOCK:
1351		retval = ide_set_media_lock(drive, disk, 0);
1352		if (retval)
1353			return retval;
1354		tape->door_locked = DOOR_UNLOCKED;
1355		return 0;
1356	default:
1357		printk(KERN_ERR "ide-tape: MTIO operation %d not supported\n",
1358				mt_op);
1359		return -EIO;
1360	}
1361}
1362
1363/*
1364 * Our character device ioctls. General mtio.h magnetic io commands are
1365 * supported here, and not in the corresponding block interface. Our own
1366 * ide-tape ioctls are supported on both interfaces.
1367 */
1368static long do_idetape_chrdev_ioctl(struct file *file,
1369				unsigned int cmd, unsigned long arg)
1370{
1371	struct ide_tape_obj *tape = file->private_data;
1372	ide_drive_t *drive = tape->drive;
1373	struct mtop mtop;
1374	struct mtget mtget;
1375	struct mtpos mtpos;
1376	int block_offset = 0, position = tape->first_frame;
1377	void __user *argp = (void __user *)arg;
1378
1379	ide_debug_log(IDE_DBG_FUNC, "cmd: 0x%x", cmd);
1380
1381	if (tape->chrdev_dir == IDETAPE_DIR_WRITE) {
1382		ide_tape_flush_merge_buffer(drive);
1383		idetape_flush_tape_buffers(drive);
1384	}
1385	if (cmd == MTIOCGET || cmd == MTIOCPOS) {
1386		block_offset = tape->valid /
1387			(tape->blk_size * tape->user_bs_factor);
1388		position = ide_tape_read_position(drive);
1389		if (position < 0)
1390			return -EIO;
1391	}
1392	switch (cmd) {
1393	case MTIOCTOP:
1394		if (copy_from_user(&mtop, argp, sizeof(struct mtop)))
1395			return -EFAULT;
1396		return idetape_mtioctop(drive, mtop.mt_op, mtop.mt_count);
1397	case MTIOCGET:
1398		memset(&mtget, 0, sizeof(struct mtget));
1399		mtget.mt_type = MT_ISSCSI2;
1400		mtget.mt_blkno = position / tape->user_bs_factor - block_offset;
1401		mtget.mt_dsreg =
1402			((tape->blk_size * tape->user_bs_factor)
1403			 << MT_ST_BLKSIZE_SHIFT) & MT_ST_BLKSIZE_MASK;
1404
1405		if (tape->drv_write_prot)
1406			mtget.mt_gstat |= GMT_WR_PROT(0xffffffff);
1407
1408		if (copy_to_user(argp, &mtget, sizeof(struct mtget)))
1409			return -EFAULT;
1410		return 0;
1411	case MTIOCPOS:
1412		mtpos.mt_blkno = position / tape->user_bs_factor - block_offset;
1413		if (copy_to_user(argp, &mtpos, sizeof(struct mtpos)))
1414			return -EFAULT;
1415		return 0;
1416	default:
1417		if (tape->chrdev_dir == IDETAPE_DIR_READ)
1418			ide_tape_discard_merge_buffer(drive, 1);
1419		return idetape_blkdev_ioctl(drive, cmd, arg);
1420	}
1421}
1422
1423static long idetape_chrdev_ioctl(struct file *file,
1424				unsigned int cmd, unsigned long arg)
1425{
1426	long ret;
1427	mutex_lock(&ide_tape_mutex);
1428	ret = do_idetape_chrdev_ioctl(file, cmd, arg);
1429	mutex_unlock(&ide_tape_mutex);
1430	return ret;
1431}
1432
1433/*
1434 * Do a mode sense page 0 with block descriptor and if it succeeds set the tape
1435 * block size with the reported value.
1436 */
1437static void ide_tape_get_bsize_from_bdesc(ide_drive_t *drive)
1438{
1439	idetape_tape_t *tape = drive->driver_data;
1440	struct ide_atapi_pc pc;
1441	u8 buf[12];
1442
1443	idetape_create_mode_sense_cmd(&pc, IDETAPE_BLOCK_DESCRIPTOR);
1444	if (ide_queue_pc_tail(drive, tape->disk, &pc, buf, pc.req_xfer)) {
1445		printk(KERN_ERR "ide-tape: Can't get block descriptor\n");
1446		if (tape->blk_size == 0) {
1447			printk(KERN_WARNING "ide-tape: Cannot deal with zero "
1448					    "block size, assuming 32k\n");
1449			tape->blk_size = 32768;
1450		}
1451		return;
1452	}
1453	tape->blk_size = (buf[4 + 5] << 16) +
1454				(buf[4 + 6] << 8)  +
1455				 buf[4 + 7];
1456	tape->drv_write_prot = (buf[2] & 0x80) >> 7;
1457
1458	ide_debug_log(IDE_DBG_FUNC, "blk_size: %d, write_prot: %d",
1459		      tape->blk_size, tape->drv_write_prot);
1460}
1461
1462static int idetape_chrdev_open(struct inode *inode, struct file *filp)
1463{
1464	unsigned int minor = iminor(inode), i = minor & ~0xc0;
1465	ide_drive_t *drive;
1466	idetape_tape_t *tape;
1467	int retval;
1468
1469	if (i >= MAX_HWIFS * MAX_DRIVES)
1470		return -ENXIO;
1471
1472	mutex_lock(&idetape_chrdev_mutex);
1473
1474	tape = ide_tape_get(NULL, true, i);
1475	if (!tape) {
1476		mutex_unlock(&idetape_chrdev_mutex);
1477		return -ENXIO;
1478	}
1479
1480	drive = tape->drive;
1481	filp->private_data = tape;
1482
1483	ide_debug_log(IDE_DBG_FUNC, "enter");
1484
1485	/*
1486	 * We really want to do nonseekable_open(inode, filp); here, but some
1487	 * versions of tar incorrectly call lseek on tapes and bail out if that
1488	 * fails.  So we disallow pread() and pwrite(), but permit lseeks.
1489	 */
1490	filp->f_mode &= ~(FMODE_PREAD | FMODE_PWRITE);
1491
1492
1493	if (test_and_set_bit(ilog2(IDE_AFLAG_BUSY), &drive->atapi_flags)) {
1494		retval = -EBUSY;
1495		goto out_put_tape;
1496	}
1497
1498	retval = idetape_wait_ready(drive, 60 * HZ);
1499	if (retval) {
1500		clear_bit(ilog2(IDE_AFLAG_BUSY), &drive->atapi_flags);
1501		printk(KERN_ERR "ide-tape: %s: drive not ready\n", tape->name);
1502		goto out_put_tape;
1503	}
1504
1505	ide_tape_read_position(drive);
1506	if (!test_bit(ilog2(IDE_AFLAG_ADDRESS_VALID), &drive->atapi_flags))
1507		(void)idetape_rewind_tape(drive);
1508
1509	/* Read block size and write protect status from drive. */
1510	ide_tape_get_bsize_from_bdesc(drive);
1511
1512	/* Set write protect flag if device is opened as read-only. */
1513	if ((filp->f_flags & O_ACCMODE) == O_RDONLY)
1514		tape->write_prot = 1;
1515	else
1516		tape->write_prot = tape->drv_write_prot;
1517
1518	/* Make sure drive isn't write protected if user wants to write. */
1519	if (tape->write_prot) {
1520		if ((filp->f_flags & O_ACCMODE) == O_WRONLY ||
1521		    (filp->f_flags & O_ACCMODE) == O_RDWR) {
1522			clear_bit(ilog2(IDE_AFLAG_BUSY), &drive->atapi_flags);
1523			retval = -EROFS;
1524			goto out_put_tape;
1525		}
1526	}
1527
1528	/* Lock the tape drive door so user can't eject. */
1529	if (tape->chrdev_dir == IDETAPE_DIR_NONE) {
1530		if (!ide_set_media_lock(drive, tape->disk, 1)) {
1531			if (tape->door_locked != DOOR_EXPLICITLY_LOCKED)
1532				tape->door_locked = DOOR_LOCKED;
1533		}
1534	}
1535	mutex_unlock(&idetape_chrdev_mutex);
1536
1537	return 0;
1538
1539out_put_tape:
1540	ide_tape_put(tape);
1541
1542	mutex_unlock(&idetape_chrdev_mutex);
1543
1544	return retval;
1545}
1546
1547static void idetape_write_release(ide_drive_t *drive, unsigned int minor)
1548{
1549	idetape_tape_t *tape = drive->driver_data;
1550
1551	ide_tape_flush_merge_buffer(drive);
1552	tape->buf = kmalloc(tape->buffer_size, GFP_KERNEL);
1553	if (tape->buf != NULL) {
1554		idetape_pad_zeros(drive, tape->blk_size *
1555				(tape->user_bs_factor - 1));
1556		kfree(tape->buf);
1557		tape->buf = NULL;
1558	}
1559	idetape_write_filemark(drive);
1560	idetape_flush_tape_buffers(drive);
1561	idetape_flush_tape_buffers(drive);
1562}
1563
1564static int idetape_chrdev_release(struct inode *inode, struct file *filp)
1565{
1566	struct ide_tape_obj *tape = filp->private_data;
1567	ide_drive_t *drive = tape->drive;
1568	unsigned int minor = iminor(inode);
1569
1570	mutex_lock(&idetape_chrdev_mutex);
1571
1572	tape = drive->driver_data;
1573
1574	ide_debug_log(IDE_DBG_FUNC, "enter");
1575
1576	if (tape->chrdev_dir == IDETAPE_DIR_WRITE)
1577		idetape_write_release(drive, minor);
1578	if (tape->chrdev_dir == IDETAPE_DIR_READ) {
1579		if (minor < 128)
1580			ide_tape_discard_merge_buffer(drive, 1);
1581	}
1582
1583	if (minor < 128 && test_bit(ilog2(IDE_AFLAG_MEDIUM_PRESENT),
1584				    &drive->atapi_flags))
1585		(void) idetape_rewind_tape(drive);
1586
1587	if (tape->chrdev_dir == IDETAPE_DIR_NONE) {
1588		if (tape->door_locked == DOOR_LOCKED) {
1589			if (!ide_set_media_lock(drive, tape->disk, 0))
1590				tape->door_locked = DOOR_UNLOCKED;
1591		}
1592	}
1593	clear_bit(ilog2(IDE_AFLAG_BUSY), &drive->atapi_flags);
1594	ide_tape_put(tape);
1595
1596	mutex_unlock(&idetape_chrdev_mutex);
1597
1598	return 0;
1599}
1600
1601static void idetape_get_inquiry_results(ide_drive_t *drive)
1602{
1603	idetape_tape_t *tape = drive->driver_data;
1604	struct ide_atapi_pc pc;
1605	u8 pc_buf[256];
1606	char fw_rev[4], vendor_id[8], product_id[16];
1607
1608	idetape_create_inquiry_cmd(&pc);
1609	if (ide_queue_pc_tail(drive, tape->disk, &pc, pc_buf, pc.req_xfer)) {
1610		printk(KERN_ERR "ide-tape: %s: can't get INQUIRY results\n",
1611				tape->name);
1612		return;
1613	}
1614	memcpy(vendor_id, &pc_buf[8], 8);
1615	memcpy(product_id, &pc_buf[16], 16);
1616	memcpy(fw_rev, &pc_buf[32], 4);
1617
1618	ide_fixstring(vendor_id, 8, 0);
1619	ide_fixstring(product_id, 16, 0);
1620	ide_fixstring(fw_rev, 4, 0);
1621
1622	printk(KERN_INFO "ide-tape: %s <-> %s: %.8s %.16s rev %.4s\n",
1623			drive->name, tape->name, vendor_id, product_id, fw_rev);
1624}
1625
1626/*
1627 * Ask the tape about its various parameters. In particular, we will adjust our
1628 * data transfer buffer	size to the recommended value as returned by the tape.
1629 */
1630static void idetape_get_mode_sense_results(ide_drive_t *drive)
1631{
1632	idetape_tape_t *tape = drive->driver_data;
1633	struct ide_atapi_pc pc;
1634	u8 buf[24], *caps;
1635	u8 speed, max_speed;
1636
1637	idetape_create_mode_sense_cmd(&pc, IDETAPE_CAPABILITIES_PAGE);
1638	if (ide_queue_pc_tail(drive, tape->disk, &pc, buf, pc.req_xfer)) {
1639		printk(KERN_ERR "ide-tape: Can't get tape parameters - assuming"
1640				" some default values\n");
1641		tape->blk_size = 512;
1642		put_unaligned(52,   (u16 *)&tape->caps[12]);
1643		put_unaligned(540,  (u16 *)&tape->caps[14]);
1644		put_unaligned(6*52, (u16 *)&tape->caps[16]);
1645		return;
1646	}
1647	caps = buf + 4 + buf[3];
1648
1649	/* convert to host order and save for later use */
1650	speed = be16_to_cpup((__be16 *)&caps[14]);
1651	max_speed = be16_to_cpup((__be16 *)&caps[8]);
1652
1653	*(u16 *)&caps[8] = max_speed;
1654	*(u16 *)&caps[12] = be16_to_cpup((__be16 *)&caps[12]);
1655	*(u16 *)&caps[14] = speed;
1656	*(u16 *)&caps[16] = be16_to_cpup((__be16 *)&caps[16]);
1657
1658	if (!speed) {
1659		printk(KERN_INFO "ide-tape: %s: invalid tape speed "
1660				"(assuming 650KB/sec)\n", drive->name);
1661		*(u16 *)&caps[14] = 650;
1662	}
1663	if (!max_speed) {
1664		printk(KERN_INFO "ide-tape: %s: invalid max_speed "
1665				"(assuming 650KB/sec)\n", drive->name);
1666		*(u16 *)&caps[8] = 650;
1667	}
1668
1669	memcpy(&tape->caps, caps, 20);
1670
1671	/* device lacks locking support according to capabilities page */
1672	if ((caps[6] & 1) == 0)
1673		drive->dev_flags &= ~IDE_DFLAG_DOORLOCKING;
1674
1675	if (caps[7] & 0x02)
1676		tape->blk_size = 512;
1677	else if (caps[7] & 0x04)
1678		tape->blk_size = 1024;
1679}
1680
1681#ifdef CONFIG_IDE_PROC_FS
1682#define ide_tape_devset_get(name, field) \
1683static int get_##name(ide_drive_t *drive) \
1684{ \
1685	idetape_tape_t *tape = drive->driver_data; \
1686	return tape->field; \
1687}
1688
1689#define ide_tape_devset_set(name, field) \
1690static int set_##name(ide_drive_t *drive, int arg) \
1691{ \
1692	idetape_tape_t *tape = drive->driver_data; \
1693	tape->field = arg; \
1694	return 0; \
1695}
1696
1697#define ide_tape_devset_rw_field(_name, _field) \
1698ide_tape_devset_get(_name, _field) \
1699ide_tape_devset_set(_name, _field) \
1700IDE_DEVSET(_name, DS_SYNC, get_##_name, set_##_name)
1701
1702#define ide_tape_devset_r_field(_name, _field) \
1703ide_tape_devset_get(_name, _field) \
1704IDE_DEVSET(_name, 0, get_##_name, NULL)
1705
1706static int mulf_tdsc(ide_drive_t *drive)	{ return 1000; }
1707static int divf_tdsc(ide_drive_t *drive)	{ return   HZ; }
1708static int divf_buffer(ide_drive_t *drive)	{ return    2; }
1709static int divf_buffer_size(ide_drive_t *drive)	{ return 1024; }
1710
1711ide_devset_rw_flag(dsc_overlap, IDE_DFLAG_DSC_OVERLAP);
1712
1713ide_tape_devset_rw_field(tdsc, best_dsc_rw_freq);
1714
1715ide_tape_devset_r_field(avg_speed, avg_speed);
1716ide_tape_devset_r_field(speed, caps[14]);
1717ide_tape_devset_r_field(buffer, caps[16]);
1718ide_tape_devset_r_field(buffer_size, buffer_size);
1719
1720static const struct ide_proc_devset idetape_settings[] = {
1721	__IDE_PROC_DEVSET(avg_speed,	0, 0xffff, NULL, NULL),
1722	__IDE_PROC_DEVSET(buffer,	0, 0xffff, NULL, divf_buffer),
1723	__IDE_PROC_DEVSET(buffer_size,	0, 0xffff, NULL, divf_buffer_size),
1724	__IDE_PROC_DEVSET(dsc_overlap,	0,      1, NULL, NULL),
1725	__IDE_PROC_DEVSET(speed,	0, 0xffff, NULL, NULL),
1726	__IDE_PROC_DEVSET(tdsc,		IDETAPE_DSC_RW_MIN, IDETAPE_DSC_RW_MAX,
1727					mulf_tdsc, divf_tdsc),
1728	{ NULL },
1729};
1730#endif
1731
1732/*
1733 * The function below is called to:
1734 *
1735 * 1. Initialize our various state variables.
1736 * 2. Ask the tape for its capabilities.
1737 * 3. Allocate a buffer which will be used for data transfer. The buffer size
1738 * is chosen based on the recommendation which we received in step 2.
1739 *
1740 * Note that at this point ide.c already assigned us an irq, so that we can
1741 * queue requests here and wait for their completion.
1742 */
1743static void idetape_setup(ide_drive_t *drive, idetape_tape_t *tape, int minor)
1744{
1745	unsigned long t;
1746	int speed;
1747	int buffer_size;
1748	u16 *ctl = (u16 *)&tape->caps[12];
1749
1750	ide_debug_log(IDE_DBG_FUNC, "minor: %d", minor);
1751
1752	drive->pc_callback = ide_tape_callback;
1753
1754	drive->dev_flags |= IDE_DFLAG_DSC_OVERLAP;
1755
1756	if (drive->hwif->host_flags & IDE_HFLAG_NO_DSC) {
1757		printk(KERN_INFO "ide-tape: %s: disabling DSC overlap\n",
1758				 tape->name);
1759		drive->dev_flags &= ~IDE_DFLAG_DSC_OVERLAP;
1760	}
1761
1762	/* Seagate Travan drives do not support DSC overlap. */
1763	if (strstr((char *)&drive->id[ATA_ID_PROD], "Seagate STT3401"))
1764		drive->dev_flags &= ~IDE_DFLAG_DSC_OVERLAP;
1765
1766	tape->minor = minor;
1767	tape->name[0] = 'h';
1768	tape->name[1] = 't';
1769	tape->name[2] = '0' + minor;
1770	tape->chrdev_dir = IDETAPE_DIR_NONE;
1771
1772	idetape_get_inquiry_results(drive);
1773	idetape_get_mode_sense_results(drive);
1774	ide_tape_get_bsize_from_bdesc(drive);
1775	tape->user_bs_factor = 1;
1776	tape->buffer_size = *ctl * tape->blk_size;
1777	while (tape->buffer_size > 0xffff) {
1778		printk(KERN_NOTICE "ide-tape: decreasing stage size\n");
1779		*ctl /= 2;
1780		tape->buffer_size = *ctl * tape->blk_size;
1781	}
1782	buffer_size = tape->buffer_size;
1783
1784	/* select the "best" DSC read/write polling freq */
1785	speed = max(*(u16 *)&tape->caps[14], *(u16 *)&tape->caps[8]);
1786
1787	t = (IDETAPE_FIFO_THRESHOLD * tape->buffer_size * HZ) / (speed * 1000);
1788
1789	/*
1790	 * Ensure that the number we got makes sense; limit it within
1791	 * IDETAPE_DSC_RW_MIN and IDETAPE_DSC_RW_MAX.
1792	 */
1793	tape->best_dsc_rw_freq = clamp_t(unsigned long, t, IDETAPE_DSC_RW_MIN,
1794					 IDETAPE_DSC_RW_MAX);
1795	printk(KERN_INFO "ide-tape: %s <-> %s: %dKBps, %d*%dkB buffer, "
1796		"%lums tDSC%s\n",
1797		drive->name, tape->name, *(u16 *)&tape->caps[14],
1798		(*(u16 *)&tape->caps[16] * 512) / tape->buffer_size,
1799		tape->buffer_size / 1024,
1800		tape->best_dsc_rw_freq * 1000 / HZ,
1801		(drive->dev_flags & IDE_DFLAG_USING_DMA) ? ", DMA" : "");
1802
1803	ide_proc_register_driver(drive, tape->driver);
1804}
1805
1806static void ide_tape_remove(ide_drive_t *drive)
1807{
1808	idetape_tape_t *tape = drive->driver_data;
1809
1810	ide_proc_unregister_driver(drive, tape->driver);
1811	device_del(&tape->dev);
1812	ide_unregister_region(tape->disk);
1813
1814	mutex_lock(&idetape_ref_mutex);
1815	put_device(&tape->dev);
1816	mutex_unlock(&idetape_ref_mutex);
1817}
1818
1819static void ide_tape_release(struct device *dev)
1820{
1821	struct ide_tape_obj *tape = to_ide_drv(dev, ide_tape_obj);
1822	ide_drive_t *drive = tape->drive;
1823	struct gendisk *g = tape->disk;
1824
1825	BUG_ON(tape->valid);
1826
1827	drive->dev_flags &= ~IDE_DFLAG_DSC_OVERLAP;
1828	drive->driver_data = NULL;
1829	device_destroy(idetape_sysfs_class, MKDEV(IDETAPE_MAJOR, tape->minor));
1830	device_destroy(idetape_sysfs_class,
1831			MKDEV(IDETAPE_MAJOR, tape->minor + 128));
1832	idetape_devs[tape->minor] = NULL;
1833	g->private_data = NULL;
1834	put_disk(g);
1835	kfree(tape);
1836}
1837
1838#ifdef CONFIG_IDE_PROC_FS
1839static int idetape_name_proc_show(struct seq_file *m, void *v)
1840{
1841	ide_drive_t	*drive = (ide_drive_t *) m->private;
1842	idetape_tape_t	*tape = drive->driver_data;
1843
1844	seq_printf(m, "%s\n", tape->name);
1845	return 0;
1846}
1847
1848static int idetape_name_proc_open(struct inode *inode, struct file *file)
1849{
1850	return single_open(file, idetape_name_proc_show, PDE(inode)->data);
1851}
1852
1853static const struct file_operations idetape_name_proc_fops = {
1854	.owner		= THIS_MODULE,
1855	.open		= idetape_name_proc_open,
1856	.read		= seq_read,
1857	.llseek		= seq_lseek,
1858	.release	= single_release,
1859};
1860
1861static ide_proc_entry_t idetape_proc[] = {
1862	{ "capacity",	S_IFREG|S_IRUGO,	&ide_capacity_proc_fops	},
1863	{ "name",	S_IFREG|S_IRUGO,	&idetape_name_proc_fops	},
1864	{}
1865};
1866
1867static ide_proc_entry_t *ide_tape_proc_entries(ide_drive_t *drive)
1868{
1869	return idetape_proc;
1870}
1871
1872static const struct ide_proc_devset *ide_tape_proc_devsets(ide_drive_t *drive)
1873{
1874	return idetape_settings;
1875}
1876#endif
1877
1878static int ide_tape_probe(ide_drive_t *);
1879
1880static struct ide_driver idetape_driver = {
1881	.gen_driver = {
1882		.owner		= THIS_MODULE,
1883		.name		= "ide-tape",
1884		.bus		= &ide_bus_type,
1885	},
1886	.probe			= ide_tape_probe,
1887	.remove			= ide_tape_remove,
1888	.version		= IDETAPE_VERSION,
1889	.do_request		= idetape_do_request,
1890#ifdef CONFIG_IDE_PROC_FS
1891	.proc_entries		= ide_tape_proc_entries,
1892	.proc_devsets		= ide_tape_proc_devsets,
1893#endif
1894};
1895
1896/* Our character device supporting functions, passed to register_chrdev. */
1897static const struct file_operations idetape_fops = {
1898	.owner		= THIS_MODULE,
1899	.read		= idetape_chrdev_read,
1900	.write		= idetape_chrdev_write,
1901	.unlocked_ioctl	= idetape_chrdev_ioctl,
1902	.open		= idetape_chrdev_open,
1903	.release	= idetape_chrdev_release,
1904	.llseek		= noop_llseek,
1905};
1906
1907static int idetape_open(struct block_device *bdev, fmode_t mode)
1908{
1909	struct ide_tape_obj *tape;
1910
1911	mutex_lock(&ide_tape_mutex);
1912	tape = ide_tape_get(bdev->bd_disk, false, 0);
1913	mutex_unlock(&ide_tape_mutex);
1914
1915	if (!tape)
1916		return -ENXIO;
1917
1918	return 0;
1919}
1920
1921static int idetape_release(struct gendisk *disk, fmode_t mode)
1922{
1923	struct ide_tape_obj *tape = ide_drv_g(disk, ide_tape_obj);
1924
1925	mutex_lock(&ide_tape_mutex);
1926	ide_tape_put(tape);
1927	mutex_unlock(&ide_tape_mutex);
1928
1929	return 0;
1930}
1931
1932static int idetape_ioctl(struct block_device *bdev, fmode_t mode,
1933			unsigned int cmd, unsigned long arg)
1934{
1935	struct ide_tape_obj *tape = ide_drv_g(bdev->bd_disk, ide_tape_obj);
1936	ide_drive_t *drive = tape->drive;
1937	int err;
1938
1939	mutex_lock(&ide_tape_mutex);
1940	err = generic_ide_ioctl(drive, bdev, cmd, arg);
1941	if (err == -EINVAL)
1942		err = idetape_blkdev_ioctl(drive, cmd, arg);
1943	mutex_unlock(&ide_tape_mutex);
1944
1945	return err;
1946}
1947
1948static const struct block_device_operations idetape_block_ops = {
1949	.owner		= THIS_MODULE,
1950	.open		= idetape_open,
1951	.release	= idetape_release,
1952	.ioctl		= idetape_ioctl,
1953};
1954
1955static int ide_tape_probe(ide_drive_t *drive)
1956{
1957	idetape_tape_t *tape;
1958	struct gendisk *g;
1959	int minor;
1960
1961	ide_debug_log(IDE_DBG_FUNC, "enter");
1962
1963	if (!strstr(DRV_NAME, drive->driver_req))
1964		goto failed;
1965
1966	if (drive->media != ide_tape)
1967		goto failed;
1968
1969	if ((drive->dev_flags & IDE_DFLAG_ID_READ) &&
1970	    ide_check_atapi_device(drive, DRV_NAME) == 0) {
1971		printk(KERN_ERR "ide-tape: %s: not supported by this version of"
1972				" the driver\n", drive->name);
1973		goto failed;
1974	}
1975	tape = kzalloc(sizeof(idetape_tape_t), GFP_KERNEL);
1976	if (tape == NULL) {
1977		printk(KERN_ERR "ide-tape: %s: Can't allocate a tape struct\n",
1978				drive->name);
1979		goto failed;
1980	}
1981
1982	g = alloc_disk(1 << PARTN_BITS);
1983	if (!g)
1984		goto out_free_tape;
1985
1986	ide_init_disk(g, drive);
1987
1988	tape->dev.parent = &drive->gendev;
1989	tape->dev.release = ide_tape_release;
1990	dev_set_name(&tape->dev, dev_name(&drive->gendev));
1991
1992	if (device_register(&tape->dev))
1993		goto out_free_disk;
1994
1995	tape->drive = drive;
1996	tape->driver = &idetape_driver;
1997	tape->disk = g;
1998
1999	g->private_data = &tape->driver;
2000
2001	drive->driver_data = tape;
2002
2003	mutex_lock(&idetape_ref_mutex);
2004	for (minor = 0; idetape_devs[minor]; minor++)
2005		;
2006	idetape_devs[minor] = tape;
2007	mutex_unlock(&idetape_ref_mutex);
2008
2009	idetape_setup(drive, tape, minor);
2010
2011	device_create(idetape_sysfs_class, &drive->gendev,
2012		      MKDEV(IDETAPE_MAJOR, minor), NULL, "%s", tape->name);
2013	device_create(idetape_sysfs_class, &drive->gendev,
2014		      MKDEV(IDETAPE_MAJOR, minor + 128), NULL,
2015		      "n%s", tape->name);
2016
2017	g->fops = &idetape_block_ops;
2018	ide_register_region(g);
2019
2020	return 0;
2021
2022out_free_disk:
2023	put_disk(g);
2024out_free_tape:
2025	kfree(tape);
2026failed:
2027	return -ENODEV;
2028}
2029
2030static void __exit idetape_exit(void)
2031{
2032	driver_unregister(&idetape_driver.gen_driver);
2033	class_destroy(idetape_sysfs_class);
2034	unregister_chrdev(IDETAPE_MAJOR, "ht");
2035}
2036
2037static int __init idetape_init(void)
2038{
2039	int error = 1;
2040	idetape_sysfs_class = class_create(THIS_MODULE, "ide_tape");
2041	if (IS_ERR(idetape_sysfs_class)) {
2042		idetape_sysfs_class = NULL;
2043		printk(KERN_ERR "Unable to create sysfs class for ide tapes\n");
2044		error = -EBUSY;
2045		goto out;
2046	}
2047
2048	if (register_chrdev(IDETAPE_MAJOR, "ht", &idetape_fops)) {
2049		printk(KERN_ERR "ide-tape: Failed to register chrdev"
2050				" interface\n");
2051		error = -EBUSY;
2052		goto out_free_class;
2053	}
2054
2055	error = driver_register(&idetape_driver.gen_driver);
2056	if (error)
2057		goto out_free_driver;
2058
2059	return 0;
2060
2061out_free_driver:
2062	driver_unregister(&idetape_driver.gen_driver);
2063out_free_class:
2064	class_destroy(idetape_sysfs_class);
2065out:
2066	return error;
2067}
2068
2069MODULE_ALIAS("ide:*m-tape*");
2070module_init(idetape_init);
2071module_exit(idetape_exit);
2072MODULE_ALIAS_CHARDEV_MAJOR(IDETAPE_MAJOR);
2073MODULE_DESCRIPTION("ATAPI Streaming TAPE Driver");
2074MODULE_LICENSE("GPL");