File Index
Files and directories
Sign in
FILE

st.c

File preview with syntax highlighting.

linux-6.19.14/drivers/scsi/st.c C
   1// SPDX-License-Identifier: GPL-2.0-only
   2/*
   3   SCSI Tape Driver for Linux version 1.1 and newer. See the accompanying
   4   file Documentation/scsi/st.rst for more information.
   5
   6   History:
   7   Rewritten from Dwayne Forsyth's SCSI tape driver by Kai Makisara.
   8   Contribution and ideas from several people including (in alphabetical
   9   order) Klaus Ehrenfried, Eugene Exarevsky, Eric Lee Green, Wolfgang Denk,
  10   Steve Hirsch, Andreas Koppenh"ofer, Michael Leodolter, Eyal Lebedinsky,
  11   Michael Schaefer, J"org Weule, and Eric Youngdale.
  12
  13   Copyright 1992 - 2016 Kai Makisara
  14   email Kai.Makisara@kolumbus.fi
  15
  16   Some small formal changes - aeb, 950809
  17
  18   Last modified: 18-JAN-1998 Richard Gooch <rgooch@atnf.csiro.au> Devfs support
  19 */
  20
  21static const char *verstr = "20160209";
  22
  23#include <linux/module.h>
  24
  25#include <linux/compat.h>
  26#include <linux/fs.h>
  27#include <linux/kernel.h>
  28#include <linux/sched/signal.h>
  29#include <linux/mm.h>
  30#include <linux/init.h>
  31#include <linux/string.h>
  32#include <linux/slab.h>
  33#include <linux/errno.h>
  34#include <linux/mtio.h>
  35#include <linux/major.h>
  36#include <linux/cdrom.h>
  37#include <linux/ioctl.h>
  38#include <linux/fcntl.h>
  39#include <linux/spinlock.h>
  40#include <linux/blkdev.h>
  41#include <linux/moduleparam.h>
  42#include <linux/cdev.h>
  43#include <linux/idr.h>
  44#include <linux/delay.h>
  45#include <linux/mutex.h>
  46
  47#include <linux/uaccess.h>
  48#include <asm/dma.h>
  49#include <linux/unaligned.h>
  50
  51#include <scsi/scsi.h>
  52#include <scsi/scsi_dbg.h>
  53#include <scsi/scsi_device.h>
  54#include <scsi/scsi_driver.h>
  55#include <scsi/scsi_eh.h>
  56#include <scsi/scsi_host.h>
  57#include <scsi/scsi_ioctl.h>
  58#include <scsi/sg.h>
  59
  60
  61/* The driver prints some debugging information on the console if DEBUG
  62   is defined and non-zero. */
  63#define DEBUG 1
  64#define NO_DEBUG 0
  65
  66#define ST_DEB_MSG  KERN_NOTICE
  67#if DEBUG
  68/* The message level for the debug messages is currently set to KERN_NOTICE
  69   so that people can easily see the messages. Later when the debugging messages
  70   in the drivers are more widely classified, this may be changed to KERN_DEBUG. */
  71#define DEB(a) a
  72#define DEBC(a) if (debugging) { a ; }
  73#else
  74#define DEB(a)
  75#define DEBC(a)
  76#endif
  77
  78#define ST_KILOBYTE 1024
  79
  80#include "st_options.h"
  81#include "st.h"
  82
  83static int buffer_kbs;
  84static int max_sg_segs;
  85static int try_direct_io = TRY_DIRECT_IO;
  86static int try_rdio = 1;
  87static int try_wdio = 1;
  88static int debug_flag;
  89
  90static const struct class st_sysfs_class;
  91static const struct attribute_group *st_dev_groups[];
  92static const struct attribute_group *st_drv_groups[];
  93
  94MODULE_AUTHOR("Kai Makisara");
  95MODULE_DESCRIPTION("SCSI tape (st) driver");
  96MODULE_LICENSE("GPL");
  97MODULE_ALIAS_CHARDEV_MAJOR(SCSI_TAPE_MAJOR);
  98MODULE_ALIAS_SCSI_DEVICE(TYPE_TAPE);
  99
 100/* Set 'perm' (4th argument) to 0 to disable module_param's definition
 101 * of sysfs parameters (which module_param doesn't yet support).
 102 * Sysfs parameters defined explicitly later.
 103 */
 104module_param_named(buffer_kbs, buffer_kbs, int, 0);
 105MODULE_PARM_DESC(buffer_kbs, "Default driver buffer size for fixed block mode (KB; 32)");
 106module_param_named(max_sg_segs, max_sg_segs, int, 0);
 107MODULE_PARM_DESC(max_sg_segs, "Maximum number of scatter/gather segments to use (256)");
 108module_param_named(try_direct_io, try_direct_io, int, 0);
 109MODULE_PARM_DESC(try_direct_io, "Try direct I/O between user buffer and tape drive (1)");
 110module_param_named(debug_flag, debug_flag, int, 0);
 111MODULE_PARM_DESC(debug_flag, "Enable DEBUG, same as setting debugging=1");
 112
 113
 114/* Extra parameters for testing */
 115module_param_named(try_rdio, try_rdio, int, 0);
 116MODULE_PARM_DESC(try_rdio, "Try direct read i/o when possible");
 117module_param_named(try_wdio, try_wdio, int, 0);
 118MODULE_PARM_DESC(try_wdio, "Try direct write i/o when possible");
 119
 120#ifndef MODULE
 121static int write_threshold_kbs;  /* retained for compatibility */
 122static struct st_dev_parm {
 123	char *name;
 124	int *val;
 125} parms[] __initdata = {
 126	{
 127		"buffer_kbs", &buffer_kbs
 128	},
 129	{       /* Retained for compatibility with 2.4 */
 130		"write_threshold_kbs", &write_threshold_kbs
 131	},
 132	{
 133		"max_sg_segs", NULL
 134	},
 135	{
 136		"try_direct_io", &try_direct_io
 137	},
 138	{
 139		"debug_flag", &debug_flag
 140	}
 141};
 142#endif
 143
 144/* Restrict the number of modes so that names for all are assigned */
 145#if ST_NBR_MODES > 16
 146#error "Maximum number of modes is 16"
 147#endif
 148/* Bit reversed order to get same names for same minors with all
 149   mode counts */
 150static const char *st_formats[] = {
 151	"",  "r", "k", "s", "l", "t", "o", "u",
 152	"m", "v", "p", "x", "a", "y", "q", "z"}; 
 153
 154/* The default definitions have been moved to st_options.h */
 155
 156#define ST_FIXED_BUFFER_SIZE (ST_FIXED_BUFFER_BLOCKS * ST_KILOBYTE)
 157
 158/* The buffer size should fit into the 24 bits for length in the
 159   6-byte SCSI read and write commands. */
 160#if ST_FIXED_BUFFER_SIZE >= (2 << 24 - 1)
 161#error "Buffer size should not exceed (2 << 24 - 1) bytes!"
 162#endif
 163
 164static int debugging = DEBUG;
 165
 166/* Setting these non-zero may risk recognizing resets */
 167#define MAX_RETRIES 0
 168#define MAX_WRITE_RETRIES 0
 169#define MAX_READY_RETRIES 0
 170
 171#define NO_TAPE  NOT_READY
 172
 173#define ST_TIMEOUT (900 * HZ)
 174#define ST_LONG_TIMEOUT (14000 * HZ)
 175
 176/* Remove mode bits and auto-rewind bit (7) */
 177#define TAPE_NR(x) ( ((iminor(x) & ~255) >> (ST_NBR_MODE_BITS + 1)) | \
 178	(iminor(x) & ((1 << ST_MODE_SHIFT)-1)))
 179#define TAPE_MODE(x) ((iminor(x) & ST_MODE_MASK) >> ST_MODE_SHIFT)
 180
 181/* Construct the minor number from the device (d), mode (m), and non-rewind (n) data */
 182#define TAPE_MINOR(d, m, n) (((d & ~(255 >> (ST_NBR_MODE_BITS + 1))) << (ST_NBR_MODE_BITS + 1)) | \
 183  (d & (255 >> (ST_NBR_MODE_BITS + 1))) | (m << ST_MODE_SHIFT) | ((n != 0) << 7) )
 184
 185/* Internal ioctl to set both density (uppermost 8 bits) and blocksize (lower
 186   24 bits) */
 187#define SET_DENS_AND_BLK 0x10001
 188
 189static int st_fixed_buffer_size = ST_FIXED_BUFFER_SIZE;
 190static int st_max_sg_segs = ST_MAX_SG;
 191
 192static int modes_defined;
 193
 194static int enlarge_buffer(struct st_buffer *, int);
 195static void clear_buffer(struct st_buffer *);
 196static void normalize_buffer(struct st_buffer *);
 197static int append_to_buffer(const char __user *, struct st_buffer *, int);
 198static int from_buffer(struct st_buffer *, char __user *, int);
 199static void move_buffer_data(struct st_buffer *, int);
 200
 201static int sgl_map_user_pages(struct st_buffer *, const unsigned int,
 202			      unsigned long, size_t, int);
 203static int sgl_unmap_user_pages(struct st_buffer *, const unsigned int, int);
 204
 205static int st_probe(struct device *);
 206static int st_remove(struct device *);
 207
 208static struct scsi_driver st_template = {
 209	.gendrv = {
 210		.name		= "st",
 211		.probe		= st_probe,
 212		.remove		= st_remove,
 213		.groups		= st_drv_groups,
 214	},
 215};
 216
 217static int st_compression(struct scsi_tape *, int);
 218
 219static int find_partition(struct scsi_tape *);
 220static int switch_partition(struct scsi_tape *);
 221
 222static int st_int_ioctl(struct scsi_tape *, unsigned int, unsigned long);
 223
 224static void scsi_tape_release(struct kref *);
 225
 226#define to_scsi_tape(obj) container_of(obj, struct scsi_tape, kref)
 227
 228static DEFINE_MUTEX(st_ref_mutex);
 229static DEFINE_SPINLOCK(st_index_lock);
 230static DEFINE_SPINLOCK(st_use_lock);
 231static DEFINE_IDR(st_index_idr);
 232
 233
 234
 235#ifndef SIGS_FROM_OSST
 236#define SIGS_FROM_OSST \
 237	{"OnStream", "SC-", "", "osst"}, \
 238	{"OnStream", "DI-", "", "osst"}, \
 239	{"OnStream", "DP-", "", "osst"}, \
 240	{"OnStream", "USB", "", "osst"}, \
 241	{"OnStream", "FW-", "", "osst"}
 242#endif
 243
 244static struct scsi_tape *scsi_tape_get(int dev)
 245{
 246	struct scsi_tape *STp = NULL;
 247
 248	mutex_lock(&st_ref_mutex);
 249	spin_lock(&st_index_lock);
 250
 251	STp = idr_find(&st_index_idr, dev);
 252	if (!STp) goto out;
 253
 254	kref_get(&STp->kref);
 255
 256	if (!STp->device)
 257		goto out_put;
 258
 259	if (scsi_device_get(STp->device))
 260		goto out_put;
 261
 262	goto out;
 263
 264out_put:
 265	kref_put(&STp->kref, scsi_tape_release);
 266	STp = NULL;
 267out:
 268	spin_unlock(&st_index_lock);
 269	mutex_unlock(&st_ref_mutex);
 270	return STp;
 271}
 272
 273static void scsi_tape_put(struct scsi_tape *STp)
 274{
 275	struct scsi_device *sdev = STp->device;
 276
 277	mutex_lock(&st_ref_mutex);
 278	kref_put(&STp->kref, scsi_tape_release);
 279	scsi_device_put(sdev);
 280	mutex_unlock(&st_ref_mutex);
 281}
 282
 283struct st_reject_data {
 284	char *vendor;
 285	char *model;
 286	char *rev;
 287	char *driver_hint; /* Name of the correct driver, NULL if unknown */
 288};
 289
 290static struct st_reject_data reject_list[] = {
 291	/* {"XXX", "Yy-", "", NULL},  example */
 292	SIGS_FROM_OSST,
 293	{NULL, }};
 294
 295/* If the device signature is on the list of incompatible drives, the
 296   function returns a pointer to the name of the correct driver (if known) */
 297static char * st_incompatible(struct scsi_device* SDp)
 298{
 299	struct st_reject_data *rp;
 300
 301	for (rp=&(reject_list[0]); rp->vendor != NULL; rp++)
 302		if (!strncmp(rp->vendor, SDp->vendor, strlen(rp->vendor)) &&
 303		    !strncmp(rp->model, SDp->model, strlen(rp->model)) &&
 304		    !strncmp(rp->rev, SDp->rev, strlen(rp->rev))) {
 305			if (rp->driver_hint)
 306				return rp->driver_hint;
 307			else
 308				return "unknown";
 309		}
 310	return NULL;
 311}
 312
 313
 314#define st_printk(prefix, t, fmt, a...) \
 315	sdev_prefix_printk(prefix, (t)->device, (t)->name, fmt, ##a)
 316#ifdef DEBUG
 317#define DEBC_printk(t, fmt, a...) \
 318	if (debugging) { st_printk(ST_DEB_MSG, t, fmt, ##a ); }
 319#else
 320#define DEBC_printk(t, fmt, a...)
 321#endif
 322
 323static void st_analyze_sense(struct st_request *SRpnt, struct st_cmdstatus *s)
 324{
 325	const u8 *ucp;
 326	const u8 *sense = SRpnt->sense;
 327
 328	s->have_sense = scsi_normalize_sense(SRpnt->sense,
 329				SCSI_SENSE_BUFFERSIZE, &s->sense_hdr);
 330	s->flags = 0;
 331
 332	if (s->have_sense) {
 333		s->deferred = 0;
 334		s->remainder_valid =
 335			scsi_get_sense_info_fld(sense, SCSI_SENSE_BUFFERSIZE, &s->uremainder64);
 336		switch (sense[0] & 0x7f) {
 337		case 0x71:
 338			s->deferred = 1;
 339			fallthrough;
 340		case 0x70:
 341			s->fixed_format = 1;
 342			s->flags = sense[2] & 0xe0;
 343			break;
 344		case 0x73:
 345			s->deferred = 1;
 346			fallthrough;
 347		case 0x72:
 348			s->fixed_format = 0;
 349			ucp = scsi_sense_desc_find(sense, SCSI_SENSE_BUFFERSIZE, 4);
 350			s->flags = ucp ? (ucp[3] & 0xe0) : 0;
 351			break;
 352		}
 353	}
 354}
 355
 356
 357/* Convert the result to success code */
 358static int st_chk_result(struct scsi_tape *STp, struct st_request * SRpnt)
 359{
 360	int result = SRpnt->result;
 361	u8 scode;
 362	unsigned int ctr;
 363	DEB(const char *stp;)
 364	char *name = STp->name;
 365	struct st_cmdstatus *cmdstatp;
 366
 367	ctr = scsi_get_ua_por_ctr(STp->device);
 368	if (ctr != STp->por_ctr) {
 369		STp->por_ctr = ctr;
 370		STp->pos_unknown = 1; /* ASC => power on / reset */
 371		st_printk(KERN_WARNING, STp, "Power on/reset recognized.");
 372	}
 373
 374	if (!result)
 375		return 0;
 376
 377	cmdstatp = &STp->buffer->cmdstat;
 378	st_analyze_sense(SRpnt, cmdstatp);
 379
 380	if (cmdstatp->have_sense)
 381		scode = STp->buffer->cmdstat.sense_hdr.sense_key;
 382	else
 383		scode = 0;
 384
 385	DEB(
 386	if (debugging) {
 387		st_printk(ST_DEB_MSG, STp,
 388			    "Error: %x, cmd: %x %x %x %x %x %x\n", result,
 389			    SRpnt->cmd[0], SRpnt->cmd[1], SRpnt->cmd[2],
 390			    SRpnt->cmd[3], SRpnt->cmd[4], SRpnt->cmd[5]);
 391		if (cmdstatp->have_sense)
 392			__scsi_print_sense(STp->device, name,
 393					   SRpnt->sense, SCSI_SENSE_BUFFERSIZE);
 394	} ) /* end DEB */
 395	if (!debugging) { /* Abnormal conditions for tape */
 396		if (!cmdstatp->have_sense)
 397			st_printk(KERN_WARNING, STp,
 398			       "Error %x (driver bt 0, host bt 0x%x).\n",
 399			       result, host_byte(result));
 400		else if (cmdstatp->have_sense &&
 401			 scode != NO_SENSE &&
 402			 scode != RECOVERED_ERROR &&
 403			 /* scode != UNIT_ATTENTION && */
 404			 scode != BLANK_CHECK &&
 405			 scode != VOLUME_OVERFLOW &&
 406			 SRpnt->cmd[0] != MODE_SENSE &&
 407			 SRpnt->cmd[0] != TEST_UNIT_READY) {
 408
 409			__scsi_print_sense(STp->device, name,
 410					   SRpnt->sense, SCSI_SENSE_BUFFERSIZE);
 411		}
 412	}
 413
 414	if (cmdstatp->fixed_format &&
 415	    STp->cln_mode >= EXTENDED_SENSE_START) {  /* Only fixed format sense */
 416		if (STp->cln_sense_value)
 417			STp->cleaning_req |= ((SRpnt->sense[STp->cln_mode] &
 418					       STp->cln_sense_mask) == STp->cln_sense_value);
 419		else
 420			STp->cleaning_req |= ((SRpnt->sense[STp->cln_mode] &
 421					       STp->cln_sense_mask) != 0);
 422	}
 423	if (cmdstatp->have_sense &&
 424	    cmdstatp->sense_hdr.asc == 0 && cmdstatp->sense_hdr.ascq == 0x17)
 425		STp->cleaning_req = 1; /* ASC and ASCQ => cleaning requested */
 426	if (cmdstatp->have_sense && scode == UNIT_ATTENTION &&
 427		cmdstatp->sense_hdr.asc == 0x29 && !STp->pos_unknown) {
 428		STp->pos_unknown = 1; /* ASC => power on / reset */
 429		st_printk(KERN_WARNING, STp, "Power on/reset recognized.");
 430	}
 431
 432	if (cmdstatp->have_sense &&
 433	    scode == RECOVERED_ERROR
 434#if ST_RECOVERED_WRITE_FATAL
 435	    && SRpnt->cmd[0] != WRITE_6
 436	    && SRpnt->cmd[0] != WRITE_FILEMARKS
 437#endif
 438	    ) {
 439		STp->recover_count++;
 440		STp->recover_reg++;
 441
 442		DEB(
 443		if (debugging) {
 444			if (SRpnt->cmd[0] == READ_6)
 445				stp = "read";
 446			else if (SRpnt->cmd[0] == WRITE_6)
 447				stp = "write";
 448			else
 449				stp = "ioctl";
 450			st_printk(ST_DEB_MSG, STp,
 451				  "Recovered %s error (%d).\n",
 452				  stp, STp->recover_count);
 453		} ) /* end DEB */
 454
 455		if (cmdstatp->flags == 0)
 456			return 0;
 457	}
 458	return (-EIO);
 459}
 460
 461static struct st_request *st_allocate_request(struct scsi_tape *stp)
 462{
 463	struct st_request *streq;
 464
 465	streq = kzalloc(sizeof(*streq), GFP_KERNEL);
 466	if (streq)
 467		streq->stp = stp;
 468	else {
 469		st_printk(KERN_ERR, stp,
 470			  "Can't get SCSI request.\n");
 471		if (signal_pending(current))
 472			stp->buffer->syscall_result = -EINTR;
 473		else
 474			stp->buffer->syscall_result = -EBUSY;
 475	}
 476
 477	return streq;
 478}
 479
 480static void st_release_request(struct st_request *streq)
 481{
 482	kfree(streq);
 483}
 484
 485static void st_do_stats(struct scsi_tape *STp, struct request *req)
 486{
 487	struct scsi_cmnd *scmd = blk_mq_rq_to_pdu(req);
 488	ktime_t now;
 489
 490	now = ktime_get();
 491	if (scmd->cmnd[0] == WRITE_6) {
 492		now = ktime_sub(now, STp->stats->write_time);
 493		atomic64_add(ktime_to_ns(now), &STp->stats->tot_write_time);
 494		atomic64_add(ktime_to_ns(now), &STp->stats->tot_io_time);
 495		atomic64_inc(&STp->stats->write_cnt);
 496		if (scmd->result) {
 497			atomic64_add(atomic_read(&STp->stats->last_write_size)
 498				- STp->buffer->cmdstat.residual,
 499				&STp->stats->write_byte_cnt);
 500			if (STp->buffer->cmdstat.residual > 0)
 501				atomic64_inc(&STp->stats->resid_cnt);
 502		} else
 503			atomic64_add(atomic_read(&STp->stats->last_write_size),
 504				&STp->stats->write_byte_cnt);
 505	} else if (scmd->cmnd[0] == READ_6) {
 506		now = ktime_sub(now, STp->stats->read_time);
 507		atomic64_add(ktime_to_ns(now), &STp->stats->tot_read_time);
 508		atomic64_add(ktime_to_ns(now), &STp->stats->tot_io_time);
 509		atomic64_inc(&STp->stats->read_cnt);
 510		if (scmd->result) {
 511			atomic64_add(atomic_read(&STp->stats->last_read_size)
 512				- STp->buffer->cmdstat.residual,
 513				&STp->stats->read_byte_cnt);
 514			if (STp->buffer->cmdstat.residual > 0)
 515				atomic64_inc(&STp->stats->resid_cnt);
 516		} else
 517			atomic64_add(atomic_read(&STp->stats->last_read_size),
 518				&STp->stats->read_byte_cnt);
 519	} else {
 520		now = ktime_sub(now, STp->stats->other_time);
 521		atomic64_add(ktime_to_ns(now), &STp->stats->tot_io_time);
 522		atomic64_inc(&STp->stats->other_cnt);
 523	}
 524	atomic64_dec(&STp->stats->in_flight);
 525}
 526
 527static enum rq_end_io_ret st_scsi_execute_end(struct request *req,
 528					      blk_status_t status)
 529{
 530	struct scsi_cmnd *scmd = blk_mq_rq_to_pdu(req);
 531	struct st_request *SRpnt = req->end_io_data;
 532	struct scsi_tape *STp = SRpnt->stp;
 533	struct bio *tmp;
 534
 535	STp->buffer->cmdstat.midlevel_result = SRpnt->result = scmd->result;
 536	STp->buffer->cmdstat.residual = scmd->resid_len;
 537
 538	st_do_stats(STp, req);
 539
 540	tmp = SRpnt->bio;
 541	if (scmd->sense_len)
 542		memcpy(SRpnt->sense, scmd->sense_buffer, SCSI_SENSE_BUFFERSIZE);
 543	if (SRpnt->waiting)
 544		complete(SRpnt->waiting);
 545
 546	blk_rq_unmap_user(tmp);
 547	blk_mq_free_request(req);
 548	return RQ_END_IO_NONE;
 549}
 550
 551static int st_scsi_execute(struct st_request *SRpnt, const unsigned char *cmd,
 552			   int data_direction, void *buffer, unsigned bufflen,
 553			   int timeout, int retries)
 554{
 555	struct request *req;
 556	struct rq_map_data *mdata = &SRpnt->stp->buffer->map_data;
 557	int err = 0;
 558	struct scsi_tape *STp = SRpnt->stp;
 559	struct scsi_cmnd *scmd;
 560
 561	req = scsi_alloc_request(SRpnt->stp->device->request_queue,
 562			data_direction == DMA_TO_DEVICE ?
 563			REQ_OP_DRV_OUT : REQ_OP_DRV_IN, 0);
 564	if (IS_ERR(req))
 565		return PTR_ERR(req);
 566	scmd = blk_mq_rq_to_pdu(req);
 567	req->rq_flags |= RQF_QUIET;
 568
 569	mdata->null_mapped = 1;
 570
 571	if (bufflen) {
 572		err = blk_rq_map_user(req->q, req, mdata, NULL, bufflen,
 573				      GFP_KERNEL);
 574		if (err) {
 575			blk_mq_free_request(req);
 576			return err;
 577		}
 578	}
 579
 580	atomic64_inc(&STp->stats->in_flight);
 581	if (cmd[0] == WRITE_6) {
 582		atomic_set(&STp->stats->last_write_size, bufflen);
 583		STp->stats->write_time = ktime_get();
 584	} else if (cmd[0] == READ_6) {
 585		atomic_set(&STp->stats->last_read_size, bufflen);
 586		STp->stats->read_time = ktime_get();
 587	} else {
 588		STp->stats->other_time = ktime_get();
 589	}
 590
 591	SRpnt->bio = req->bio;
 592	scmd->cmd_len = COMMAND_SIZE(cmd[0]);
 593	memcpy(scmd->cmnd, cmd, scmd->cmd_len);
 594	req->timeout = timeout;
 595	scmd->allowed = retries;
 596	req->end_io = st_scsi_execute_end;
 597	req->end_io_data = SRpnt;
 598
 599	blk_execute_rq_nowait(req, true);
 600	return 0;
 601}
 602
 603/* Do the scsi command. Waits until command performed if do_wait is true.
 604   Otherwise write_behind_check() is used to check that the command
 605   has finished. */
 606static struct st_request *
 607st_do_scsi(struct st_request * SRpnt, struct scsi_tape * STp, unsigned char *cmd,
 608	   int bytes, int direction, int timeout, int retries, int do_wait)
 609{
 610	struct completion *waiting;
 611	struct rq_map_data *mdata = &STp->buffer->map_data;
 612	int ret;
 613
 614	/* if async, make sure there's no command outstanding */
 615	if (!do_wait && ((STp->buffer)->last_SRpnt)) {
 616		st_printk(KERN_ERR, STp,
 617			  "Async command already active.\n");
 618		if (signal_pending(current))
 619			(STp->buffer)->syscall_result = (-EINTR);
 620		else
 621			(STp->buffer)->syscall_result = (-EBUSY);
 622		return NULL;
 623	}
 624
 625	if (!SRpnt) {
 626		SRpnt = st_allocate_request(STp);
 627		if (!SRpnt)
 628			return NULL;
 629	}
 630
 631	/* If async IO, set last_SRpnt. This ptr tells write_behind_check
 632	   which IO is outstanding. It's nulled out when the IO completes. */
 633	if (!do_wait)
 634		(STp->buffer)->last_SRpnt = SRpnt;
 635
 636	waiting = &STp->wait;
 637	init_completion(waiting);
 638	SRpnt->waiting = waiting;
 639
 640	if (STp->buffer->do_dio) {
 641		mdata->page_order = 0;
 642		mdata->nr_entries = STp->buffer->sg_segs;
 643		mdata->pages = STp->buffer->mapped_pages;
 644	} else {
 645		mdata->page_order = STp->buffer->reserved_page_order;
 646		mdata->nr_entries =
 647			DIV_ROUND_UP(bytes, PAGE_SIZE << mdata->page_order);
 648		mdata->pages = STp->buffer->reserved_pages;
 649		mdata->offset = 0;
 650	}
 651
 652	memcpy(SRpnt->cmd, cmd, sizeof(SRpnt->cmd));
 653	STp->buffer->cmdstat.have_sense = 0;
 654	STp->buffer->syscall_result = 0;
 655
 656	ret = st_scsi_execute(SRpnt, cmd, direction, NULL, bytes, timeout,
 657			      retries);
 658	if (ret) {
 659		/* could not allocate the buffer or request was too large */
 660		(STp->buffer)->syscall_result = (-EBUSY);
 661		(STp->buffer)->last_SRpnt = NULL;
 662	} else if (do_wait) {
 663		wait_for_completion(waiting);
 664		SRpnt->waiting = NULL;
 665		(STp->buffer)->syscall_result = st_chk_result(STp, SRpnt);
 666	}
 667
 668	return SRpnt;
 669}
 670
 671
 672/* Handle the write-behind checking (waits for completion). Returns -ENOSPC if
 673   write has been correct but EOM early warning reached, -EIO if write ended in
 674   error or zero if write successful. Asynchronous writes are used only in
 675   variable block mode. */
 676static int write_behind_check(struct scsi_tape * STp)
 677{
 678	int retval = 0;
 679	struct st_buffer *STbuffer;
 680	struct st_partstat *STps;
 681	struct st_cmdstatus *cmdstatp;
 682	struct st_request *SRpnt;
 683
 684	STbuffer = STp->buffer;
 685	if (!STbuffer->writing)
 686		return 0;
 687
 688	DEB(
 689	if (STp->write_pending)
 690		STp->nbr_waits++;
 691	else
 692		STp->nbr_finished++;
 693	) /* end DEB */
 694
 695	wait_for_completion(&(STp->wait));
 696	SRpnt = STbuffer->last_SRpnt;
 697	STbuffer->last_SRpnt = NULL;
 698	SRpnt->waiting = NULL;
 699
 700	(STp->buffer)->syscall_result = st_chk_result(STp, SRpnt);
 701	st_release_request(SRpnt);
 702
 703	STbuffer->buffer_bytes -= STbuffer->writing;
 704	STps = &(STp->ps[STp->partition]);
 705	if (STps->drv_block >= 0) {
 706		if (STp->block_size == 0)
 707			STps->drv_block++;
 708		else
 709			STps->drv_block += STbuffer->writing / STp->block_size;
 710	}
 711
 712	cmdstatp = &STbuffer->cmdstat;
 713	if (STbuffer->syscall_result) {
 714		retval = -EIO;
 715		if (cmdstatp->have_sense && !cmdstatp->deferred &&
 716		    (cmdstatp->flags & SENSE_EOM) &&
 717		    (cmdstatp->sense_hdr.sense_key == NO_SENSE ||
 718		     cmdstatp->sense_hdr.sense_key == RECOVERED_ERROR)) {
 719			/* EOM at write-behind, has all data been written? */
 720			if (!cmdstatp->remainder_valid ||
 721			    cmdstatp->uremainder64 == 0)
 722				retval = -ENOSPC;
 723		}
 724		if (retval == -EIO)
 725			STps->drv_block = -1;
 726	}
 727	STbuffer->writing = 0;
 728
 729	DEB(if (debugging && retval)
 730		    st_printk(ST_DEB_MSG, STp,
 731				"Async write error %x, return value %d.\n",
 732				STbuffer->cmdstat.midlevel_result, retval);) /* end DEB */
 733
 734	return retval;
 735}
 736
 737
 738/* Step over EOF if it has been inadvertently crossed (ioctl not used because
 739   it messes up the block number). */
 740static int cross_eof(struct scsi_tape * STp, int forward)
 741{
 742	struct st_request *SRpnt;
 743	unsigned char cmd[MAX_COMMAND_SIZE];
 744
 745	cmd[0] = SPACE;
 746	cmd[1] = 0x01;		/* Space FileMarks */
 747	if (forward) {
 748		cmd[2] = cmd[3] = 0;
 749		cmd[4] = 1;
 750	} else
 751		cmd[2] = cmd[3] = cmd[4] = 0xff;	/* -1 filemarks */
 752	cmd[5] = 0;
 753
 754	DEBC_printk(STp, "Stepping over filemark %s.\n",
 755		    forward ? "forward" : "backward");
 756
 757	SRpnt = st_do_scsi(NULL, STp, cmd, 0, DMA_NONE,
 758			   STp->device->request_queue->rq_timeout,
 759			   MAX_RETRIES, 1);
 760	if (!SRpnt)
 761		return (STp->buffer)->syscall_result;
 762
 763	st_release_request(SRpnt);
 764	SRpnt = NULL;
 765
 766	if ((STp->buffer)->cmdstat.midlevel_result != 0)
 767		st_printk(KERN_ERR, STp,
 768			  "Stepping over filemark %s failed.\n",
 769			  forward ? "forward" : "backward");
 770
 771	return (STp->buffer)->syscall_result;
 772}
 773
 774
 775/* Flush the write buffer (never need to write if variable blocksize). */
 776static int st_flush_write_buffer(struct scsi_tape * STp)
 777{
 778	int transfer, blks;
 779	int result;
 780	unsigned char cmd[MAX_COMMAND_SIZE];
 781	struct st_request *SRpnt;
 782	struct st_partstat *STps;
 783
 784	result = write_behind_check(STp);
 785	if (result)
 786		return result;
 787
 788	result = 0;
 789	if (STp->dirty == 1) {
 790
 791		transfer = STp->buffer->buffer_bytes;
 792		DEBC_printk(STp, "Flushing %d bytes.\n", transfer);
 793
 794		memset(cmd, 0, MAX_COMMAND_SIZE);
 795		cmd[0] = WRITE_6;
 796		cmd[1] = 1;
 797		blks = transfer / STp->block_size;
 798		cmd[2] = blks >> 16;
 799		cmd[3] = blks >> 8;
 800		cmd[4] = blks;
 801
 802		SRpnt = st_do_scsi(NULL, STp, cmd, transfer, DMA_TO_DEVICE,
 803				   STp->device->request_queue->rq_timeout,
 804				   MAX_WRITE_RETRIES, 1);
 805		if (!SRpnt)
 806			return (STp->buffer)->syscall_result;
 807
 808		STps = &(STp->ps[STp->partition]);
 809		if ((STp->buffer)->syscall_result != 0) {
 810			struct st_cmdstatus *cmdstatp = &STp->buffer->cmdstat;
 811
 812			if (cmdstatp->have_sense && !cmdstatp->deferred &&
 813			    (cmdstatp->flags & SENSE_EOM) &&
 814			    (cmdstatp->sense_hdr.sense_key == NO_SENSE ||
 815			     cmdstatp->sense_hdr.sense_key == RECOVERED_ERROR) &&
 816			    (!cmdstatp->remainder_valid ||
 817			     cmdstatp->uremainder64 == 0)) { /* All written at EOM early warning */
 818				STp->dirty = 0;
 819				(STp->buffer)->buffer_bytes = 0;
 820				if (STps->drv_block >= 0)
 821					STps->drv_block += blks;
 822				result = (-ENOSPC);
 823			} else {
 824				st_printk(KERN_ERR, STp, "Error on flush.\n");
 825				STps->drv_block = (-1);
 826				result = (-EIO);
 827			}
 828		} else {
 829			if (STps->drv_block >= 0)
 830				STps->drv_block += blks;
 831			STp->dirty = 0;
 832			(STp->buffer)->buffer_bytes = 0;
 833		}
 834		st_release_request(SRpnt);
 835		SRpnt = NULL;
 836	}
 837	return result;
 838}
 839
 840
 841/* Flush the tape buffer. The tape will be positioned correctly unless
 842   seek_next is true. */
 843static int flush_buffer(struct scsi_tape *STp, int seek_next)
 844{
 845	int backspace, result;
 846	struct st_partstat *STps;
 847
 848	if (STp->ready != ST_READY)
 849		return 0;
 850
 851	/*
 852	 * If there was a bus reset, block further access
 853	 * to this device.
 854	 */
 855	if (STp->pos_unknown)
 856		return (-EIO);
 857
 858	STps = &(STp->ps[STp->partition]);
 859	if (STps->rw == ST_WRITING)	/* Writing */
 860		return st_flush_write_buffer(STp);
 861
 862	if (STp->block_size == 0)
 863		return 0;
 864
 865	backspace = ((STp->buffer)->buffer_bytes +
 866		     (STp->buffer)->read_pointer) / STp->block_size -
 867	    ((STp->buffer)->read_pointer + STp->block_size - 1) /
 868	    STp->block_size;
 869	(STp->buffer)->buffer_bytes = 0;
 870	(STp->buffer)->read_pointer = 0;
 871	result = 0;
 872	if (!seek_next) {
 873		if (STps->eof == ST_FM_HIT) {
 874			result = cross_eof(STp, 0);	/* Back over the EOF hit */
 875			if (!result)
 876				STps->eof = ST_NOEOF;
 877			else {
 878				if (STps->drv_file >= 0)
 879					STps->drv_file++;
 880				STps->drv_block = 0;
 881			}
 882		}
 883		if (!result && backspace > 0)
 884			result = st_int_ioctl(STp, MTBSR, backspace);
 885	} else if (STps->eof == ST_FM_HIT) {
 886		if (STps->drv_file >= 0)
 887			STps->drv_file++;
 888		STps->drv_block = 0;
 889		STps->eof = ST_NOEOF;
 890	}
 891	return result;
 892
 893}
 894
 895/* Set the mode parameters */
 896static int set_mode_densblk(struct scsi_tape * STp, struct st_modedef * STm)
 897{
 898	int set_it = 0;
 899	unsigned long arg;
 900
 901	if (!STp->density_changed &&
 902	    STm->default_density >= 0 &&
 903	    STm->default_density != STp->density) {
 904		arg = STm->default_density;
 905		set_it = 1;
 906	} else
 907		arg = STp->density;
 908	arg <<= MT_ST_DENSITY_SHIFT;
 909	if (!STp->blksize_changed &&
 910	    STm->default_blksize >= 0 &&
 911	    STm->default_blksize != STp->block_size) {
 912		arg |= STm->default_blksize;
 913		set_it = 1;
 914	} else
 915		arg |= STp->block_size;
 916	if (set_it &&
 917	    st_int_ioctl(STp, SET_DENS_AND_BLK, arg)) {
 918		st_printk(KERN_WARNING, STp,
 919			  "Can't set default block size to %d bytes "
 920			  "and density %x.\n",
 921			  STm->default_blksize, STm->default_density);
 922		if (modes_defined)
 923			return (-EINVAL);
 924	}
 925	return 0;
 926}
 927
 928
 929/* Lock or unlock the drive door. Don't use when st_request allocated. */
 930static int do_door_lock(struct scsi_tape * STp, int do_lock)
 931{
 932	int retval;
 933
 934	DEBC_printk(STp, "%socking drive door.\n", do_lock ? "L" : "Unl");
 935
 936	retval = scsi_set_medium_removal(STp->device,
 937			do_lock ? SCSI_REMOVAL_PREVENT : SCSI_REMOVAL_ALLOW);
 938	if (!retval)
 939		STp->door_locked = do_lock ? ST_LOCKED_EXPLICIT : ST_UNLOCKED;
 940	else
 941		STp->door_locked = ST_LOCK_FAILS;
 942	return retval;
 943}
 944
 945
 946/* Set the internal state after reset */
 947static void reset_state(struct scsi_tape *STp)
 948{
 949	int i;
 950	struct st_partstat *STps;
 951
 952	STp->pos_unknown = 0;
 953	for (i = 0; i < ST_NBR_PARTITIONS; i++) {
 954		STps = &(STp->ps[i]);
 955		STps->rw = ST_IDLE;
 956		STps->eof = ST_NOEOF;
 957		STps->at_sm = 0;
 958		STps->last_block_valid = 0;
 959		STps->drv_block = -1;
 960		STps->drv_file = -1;
 961	}
 962	if (STp->can_partitions) {
 963		STp->partition = find_partition(STp);
 964		if (STp->partition < 0)
 965			STp->partition = 0;
 966	}
 967}
 968
 969/* Test if the drive is ready. Returns either one of the codes below or a negative system
 970   error code. */
 971#define CHKRES_READY       0
 972#define CHKRES_NEW_SESSION 1
 973#define CHKRES_NOT_READY   2
 974#define CHKRES_NO_TAPE     3
 975
 976#define MAX_ATTENTIONS    10
 977
 978static int test_ready(struct scsi_tape *STp, int do_wait)
 979{
 980	int attentions, waits, max_wait, scode;
 981	int retval = CHKRES_READY, new_session = 0;
 982	unsigned int ctr;
 983	unsigned char cmd[MAX_COMMAND_SIZE];
 984	struct st_request *SRpnt = NULL;
 985	struct st_cmdstatus *cmdstatp = &STp->buffer->cmdstat;
 986
 987	max_wait = do_wait ? ST_BLOCK_SECONDS : 0;
 988
 989	for (attentions=waits=0; ; ) {
 990		memset((void *) &cmd[0], 0, MAX_COMMAND_SIZE);
 991		cmd[0] = TEST_UNIT_READY;
 992		SRpnt = st_do_scsi(SRpnt, STp, cmd, 0, DMA_NONE,
 993				   STp->long_timeout, MAX_READY_RETRIES, 1);
 994
 995		if (!SRpnt) {
 996			retval = (STp->buffer)->syscall_result;
 997			break;
 998		}
 999
1000		if (cmdstatp->have_sense) {
1001
1002			scode = cmdstatp->sense_hdr.sense_key;
1003
1004			if (scode == UNIT_ATTENTION) { /* New media? */
1005				if (cmdstatp->sense_hdr.asc == 0x28) { /* New media */
1006					new_session = 1;
1007					DEBC_printk(STp, "New tape session.");
1008				}
1009				if (attentions < MAX_ATTENTIONS) {
1010					attentions++;
1011					continue;
1012				}
1013				else {
1014					retval = (-EIO);
1015					break;
1016				}
1017			}
1018
1019			if (scode == NOT_READY) {
1020				if (waits < max_wait) {
1021					if (msleep_interruptible(1000)) {
1022						retval = (-EINTR);
1023						break;
1024					}
1025					waits++;
1026					continue;
1027				}
1028				else {
1029					if ((STp->device)->scsi_level >= SCSI_2 &&
1030					    cmdstatp->sense_hdr.asc == 0x3a)	/* Check ASC */
1031						retval = CHKRES_NO_TAPE;
1032					else
1033						retval = CHKRES_NOT_READY;
1034					break;
1035				}
1036			}
1037		}
1038
1039		ctr = scsi_get_ua_new_media_ctr(STp->device);
1040		if (ctr != STp->new_media_ctr) {
1041			STp->new_media_ctr = ctr;
1042			new_session = 1;
1043			DEBC_printk(STp, "New tape session.");
1044		}
1045
1046		retval = (STp->buffer)->syscall_result;
1047		if (!retval)
1048			retval = new_session ? CHKRES_NEW_SESSION : CHKRES_READY;
1049		break;
1050	}
1051	if (STp->first_tur) {
1052		/* Don't set pos_unknown right after device recognition */
1053		STp->pos_unknown = 0;
1054		STp->first_tur = 0;
1055	}
1056
1057	if (SRpnt != NULL)
1058		st_release_request(SRpnt);
1059	return retval;
1060}
1061
1062
1063/* See if the drive is ready and gather information about the tape. Return values:
1064   < 0   negative error code from errno.h
1065   0     drive ready
1066   1     drive not ready (possibly no tape)
1067*/
1068static int check_tape(struct scsi_tape *STp, struct file *filp)
1069{
1070	int i, retval, new_session = 0, do_wait;
1071	unsigned char cmd[MAX_COMMAND_SIZE], saved_cleaning;
1072	unsigned short st_flags = filp->f_flags;
1073	struct st_request *SRpnt = NULL;
1074	struct st_modedef *STm;
1075	struct st_partstat *STps;
1076	struct inode *inode = file_inode(filp);
1077	int mode = TAPE_MODE(inode);
1078
1079	STp->ready = ST_READY;
1080
1081	if (mode != STp->current_mode) {
1082		DEBC_printk(STp, "Mode change from %d to %d.\n",
1083			    STp->current_mode, mode);
1084		new_session = 1;
1085		STp->current_mode = mode;
1086	}
1087	STm = &(STp->modes[STp->current_mode]);
1088
1089	saved_cleaning = STp->cleaning_req;
1090	STp->cleaning_req = 0;
1091
1092	do_wait = ((filp->f_flags & O_NONBLOCK) == 0);
1093	retval = test_ready(STp, do_wait);
1094
1095	if (retval < 0)
1096	    goto err_out;
1097
1098	if (retval == CHKRES_NEW_SESSION) {
1099		STp->pos_unknown = 0;
1100		STp->partition = STp->new_partition = 0;
1101		if (STp->can_partitions)
1102			STp->nbr_partitions = 1; /* This guess will be updated later
1103                                                    if necessary */
1104		for (i = 0; i < ST_NBR_PARTITIONS; i++) {
1105			STps = &(STp->ps[i]);
1106			STps->rw = ST_IDLE;
1107			STps->eof = ST_NOEOF;
1108			STps->at_sm = 0;
1109			STps->last_block_valid = 0;
1110			STps->drv_block = 0;
1111			STps->drv_file = 0;
1112		}
1113		new_session = 1;
1114	}
1115	else {
1116		STp->cleaning_req |= saved_cleaning;
1117
1118		if (retval == CHKRES_NOT_READY || retval == CHKRES_NO_TAPE) {
1119			if (retval == CHKRES_NO_TAPE)
1120				STp->ready = ST_NO_TAPE;
1121			else
1122				STp->ready = ST_NOT_READY;
1123
1124			STp->density = 0;	/* Clear the erroneous "residue" */
1125			STp->write_prot = 0;
1126			STp->block_size = 0;
1127			STp->ps[0].drv_file = STp->ps[0].drv_block = (-1);
1128			STp->partition = STp->new_partition = 0;
1129			STp->door_locked = ST_UNLOCKED;
1130			return CHKRES_NOT_READY;
1131		}
1132	}
1133
1134	if (STp->omit_blklims)
1135		STp->min_block = STp->max_block = (-1);
1136	else {
1137		memset((void *) &cmd[0], 0, MAX_COMMAND_SIZE);
1138		cmd[0] = READ_BLOCK_LIMITS;
1139
1140		SRpnt = st_do_scsi(SRpnt, STp, cmd, 6, DMA_FROM_DEVICE,
1141				   STp->device->request_queue->rq_timeout,
1142				   MAX_READY_RETRIES, 1);
1143		if (!SRpnt) {
1144			retval = (STp->buffer)->syscall_result;
1145			goto err_out;
1146		}
1147
1148		if (!SRpnt->result && !STp->buffer->cmdstat.have_sense) {
1149			STp->max_block = ((STp->buffer)->b_data[1] << 16) |
1150			    ((STp->buffer)->b_data[2] << 8) | (STp->buffer)->b_data[3];
1151			STp->min_block = ((STp->buffer)->b_data[4] << 8) |
1152			    (STp->buffer)->b_data[5];
1153			if ( DEB( debugging || ) !STp->inited)
1154				st_printk(KERN_INFO, STp,
1155					  "Block limits %d - %d bytes.\n",
1156					  STp->min_block, STp->max_block);
1157		} else {
1158			STp->min_block = STp->max_block = (-1);
1159			DEBC_printk(STp, "Can't read block limits.\n");
1160		}
1161	}
1162
1163	memset((void *) &cmd[0], 0, MAX_COMMAND_SIZE);
1164	cmd[0] = MODE_SENSE;
1165	cmd[4] = 12;
1166
1167	SRpnt = st_do_scsi(SRpnt, STp, cmd, 12, DMA_FROM_DEVICE,
1168			   STp->device->request_queue->rq_timeout,
1169			   MAX_READY_RETRIES, 1);
1170	if (!SRpnt) {
1171		retval = (STp->buffer)->syscall_result;
1172		goto err_out;
1173	}
1174
1175	if ((STp->buffer)->syscall_result != 0) {
1176		DEBC_printk(STp, "No Mode Sense.\n");
1177		STp->block_size = ST_DEFAULT_BLOCK;	/* Educated guess (?) */
1178		(STp->buffer)->syscall_result = 0;	/* Prevent error propagation */
1179		STp->drv_write_prot = 0;
1180	} else {
1181		DEBC_printk(STp,"Mode sense. Length %d, "
1182			    "medium %x, WBS %x, BLL %d\n",
1183			    (STp->buffer)->b_data[0],
1184			    (STp->buffer)->b_data[1],
1185			    (STp->buffer)->b_data[2],
1186			    (STp->buffer)->b_data[3]);
1187
1188		if ((STp->buffer)->b_data[3] >= 8) {
1189			STp->drv_buffer = ((STp->buffer)->b_data[2] >> 4) & 7;
1190			STp->density = (STp->buffer)->b_data[4];
1191			STp->block_size = (STp->buffer)->b_data[9] * 65536 +
1192			    (STp->buffer)->b_data[10] * 256 + (STp->buffer)->b_data[11];
1193			DEBC_printk(STp, "Density %x, tape length: %x, "
1194				    "drv buffer: %d\n",
1195				    STp->density,
1196				    (STp->buffer)->b_data[5] * 65536 +
1197				    (STp->buffer)->b_data[6] * 256 +
1198				    (STp->buffer)->b_data[7],
1199				    STp->drv_buffer);
1200		}
1201		STp->drv_write_prot = ((STp->buffer)->b_data[2] & 0x80) != 0;
1202		if (!STp->drv_buffer && STp->immediate_filemark) {
1203			st_printk(KERN_WARNING, STp,
1204				  "non-buffered tape: disabling "
1205				  "writing immediate filemarks\n");
1206			STp->immediate_filemark = 0;
1207		}
1208	}
1209	st_release_request(SRpnt);
1210	SRpnt = NULL;
1211	STp->inited = 1;
1212
1213	if (STp->block_size > 0)
1214		(STp->buffer)->buffer_blocks =
1215			(STp->buffer)->buffer_size / STp->block_size;
1216	else
1217		(STp->buffer)->buffer_blocks = 1;
1218	(STp->buffer)->buffer_bytes = (STp->buffer)->read_pointer = 0;
1219
1220	DEBC_printk(STp, "Block size: %d, buffer size: %d (%d blocks).\n",
1221		    STp->block_size, (STp->buffer)->buffer_size,
1222		    (STp->buffer)->buffer_blocks);
1223
1224	if (STp->drv_write_prot) {
1225		STp->write_prot = 1;
1226
1227		DEBC_printk(STp, "Write protected\n");
1228
1229		if (do_wait &&
1230		    ((st_flags & O_ACCMODE) == O_WRONLY ||
1231		     (st_flags & O_ACCMODE) == O_RDWR)) {
1232			retval = (-EROFS);
1233			goto err_out;
1234		}
1235	}
1236
1237	if (STp->can_partitions && STp->nbr_partitions < 1) {
1238		/* This code is reached when the device is opened for the first time
1239		   after the driver has been initialized with tape in the drive and the
1240		   partition support has been enabled. */
1241		DEBC_printk(STp, "Updating partition number in status.\n");
1242		if ((STp->partition = find_partition(STp)) < 0) {
1243			retval = STp->partition;
1244			goto err_out;
1245		}
1246		STp->new_partition = STp->partition;
1247		STp->nbr_partitions = 1; /* This guess will be updated when necessary */
1248	}
1249
1250	if (new_session) {	/* Change the drive parameters for the new mode */
1251		STp->density_changed = STp->blksize_changed = 0;
1252		STp->compression_changed = 0;
1253		if (!(STm->defaults_for_writes) &&
1254		    (retval = set_mode_densblk(STp, STm)) < 0)
1255		    goto err_out;
1256
1257		if (STp->default_drvbuffer != 0xff) {
1258			if (st_int_ioctl(STp, MTSETDRVBUFFER, STp->default_drvbuffer))
1259				st_printk(KERN_WARNING, STp,
1260					  "Can't set default drive "
1261					  "buffering to %d.\n",
1262					  STp->default_drvbuffer);
1263		}
1264	}
1265
1266	return CHKRES_READY;
1267
1268 err_out:
1269	return retval;
1270}
1271
1272
1273/* Open the device. Needs to take the BKL only because of incrementing the SCSI host
1274   module count. */
1275static int st_open(struct inode *inode, struct file *filp)
1276{
1277	int i, retval = (-EIO);
1278	int resumed = 0;
1279	struct scsi_tape *STp;
1280	struct st_partstat *STps;
1281	int dev = TAPE_NR(inode);
1282
1283	/*
1284	 * We really want to do nonseekable_open(inode, filp); here, but some
1285	 * versions of tar incorrectly call lseek on tapes and bail out if that
1286	 * fails.  So we disallow pread() and pwrite(), but permit lseeks.
1287	 */
1288	filp->f_mode &= ~(FMODE_PREAD | FMODE_PWRITE);
1289
1290	if (!(STp = scsi_tape_get(dev))) {
1291		return -ENXIO;
1292	}
1293
1294	filp->private_data = STp;
1295
1296	spin_lock(&st_use_lock);
1297	if (STp->in_use) {
1298		spin_unlock(&st_use_lock);
1299		DEBC_printk(STp, "Device already in use.\n");
1300		scsi_tape_put(STp);
1301		return (-EBUSY);
1302	}
1303
1304	STp->in_use = 1;
1305	spin_unlock(&st_use_lock);
1306	STp->rew_at_close = STp->autorew_dev = (iminor(inode) & 0x80) == 0;
1307
1308	if (scsi_autopm_get_device(STp->device) < 0) {
1309		retval = -EIO;
1310		goto err_out;
1311	}
1312	resumed = 1;
1313	if (!scsi_block_when_processing_errors(STp->device)) {
1314		retval = (-ENXIO);
1315		goto err_out;
1316	}
1317
1318	/* See that we have at least a one page buffer available */
1319	if (!enlarge_buffer(STp->buffer, PAGE_SIZE)) {
1320		st_printk(KERN_WARNING, STp,
1321			  "Can't allocate one page tape buffer.\n");
1322		retval = (-EOVERFLOW);
1323		goto err_out;
1324	}
1325
1326	(STp->buffer)->cleared = 0;
1327	(STp->buffer)->writing = 0;
1328	(STp->buffer)->syscall_result = 0;
1329
1330	STp->write_prot = ((filp->f_flags & O_ACCMODE) == O_RDONLY);
1331
1332	STp->dirty = 0;
1333	for (i = 0; i < ST_NBR_PARTITIONS; i++) {
1334		STps = &(STp->ps[i]);
1335		STps->rw = ST_IDLE;
1336	}
1337	STp->try_dio_now = STp->try_dio;
1338	STp->recover_count = 0;
1339	DEB( STp->nbr_waits = STp->nbr_finished = 0;
1340	     STp->nbr_requests = STp->nbr_dio = STp->nbr_pages = 0; )
1341
1342	retval = check_tape(STp, filp);
1343	if (retval < 0)
1344		goto err_out;
1345	if ((filp->f_flags & O_NONBLOCK) == 0 &&
1346	    retval != CHKRES_READY) {
1347		if (STp->ready == NO_TAPE)
1348			retval = (-ENOMEDIUM);
1349		else
1350			retval = (-EIO);
1351		goto err_out;
1352	}
1353	return 0;
1354
1355 err_out:
1356	normalize_buffer(STp->buffer);
1357	spin_lock(&st_use_lock);
1358	STp->in_use = 0;
1359	spin_unlock(&st_use_lock);
1360	if (resumed)
1361		scsi_autopm_put_device(STp->device);
1362	scsi_tape_put(STp);
1363	return retval;
1364
1365}
1366
1367
1368/* Flush the tape buffer before close */
1369static int st_flush(struct file *filp, fl_owner_t id)
1370{
1371	int result = 0, result2;
1372	unsigned char cmd[MAX_COMMAND_SIZE];
1373	struct st_request *SRpnt;
1374	struct scsi_tape *STp = filp->private_data;
1375	struct st_modedef *STm = &(STp->modes[STp->current_mode]);
1376	struct st_partstat *STps = &(STp->ps[STp->partition]);
1377
1378	if (file_count(filp) > 1)
1379		return 0;
1380
1381	if (STps->rw == ST_WRITING && !STp->pos_unknown) {
1382		result = st_flush_write_buffer(STp);
1383		if (result != 0 && result != (-ENOSPC))
1384			goto out;
1385	}
1386
1387	if (STp->can_partitions &&
1388	    (result2 = switch_partition(STp)) < 0) {
1389		DEBC_printk(STp, "switch_partition at close failed.\n");
1390		if (result == 0)
1391			result = result2;
1392		goto out;
1393	}
1394
1395	DEBC( if (STp->nbr_requests)
1396		st_printk(KERN_DEBUG, STp,
1397			  "Number of r/w requests %d, dio used in %d, "
1398			  "pages %d.\n", STp->nbr_requests, STp->nbr_dio,
1399			  STp->nbr_pages));
1400
1401	if (STps->rw == ST_WRITING && !STp->pos_unknown) {
1402		struct st_cmdstatus *cmdstatp = &STp->buffer->cmdstat;
1403
1404#if DEBUG
1405		DEBC_printk(STp, "Async write waits %d, finished %d.\n",
1406			    STp->nbr_waits, STp->nbr_finished);
1407#endif
1408		memset(cmd, 0, MAX_COMMAND_SIZE);
1409		cmd[0] = WRITE_FILEMARKS;
1410		if (STp->immediate_filemark)
1411			cmd[1] = 1;
1412		cmd[4] = 1 + STp->two_fm;
1413
1414		SRpnt = st_do_scsi(NULL, STp, cmd, 0, DMA_NONE,
1415				   STp->device->request_queue->rq_timeout,
1416				   MAX_WRITE_RETRIES, 1);
1417		if (!SRpnt) {
1418			result = (STp->buffer)->syscall_result;
1419			goto out;
1420		}
1421
1422		if (STp->buffer->syscall_result == 0 ||
1423		    (cmdstatp->have_sense && !cmdstatp->deferred &&
1424		     (cmdstatp->flags & SENSE_EOM) &&
1425		     (cmdstatp->sense_hdr.sense_key == NO_SENSE ||
1426		      cmdstatp->sense_hdr.sense_key == RECOVERED_ERROR) &&
1427		     (!cmdstatp->remainder_valid || cmdstatp->uremainder64 == 0))) {
1428			/* Write successful at EOM */
1429			st_release_request(SRpnt);
1430			SRpnt = NULL;
1431			if (STps->drv_file >= 0)
1432				STps->drv_file++;
1433			STps->drv_block = 0;
1434			if (STp->two_fm)
1435				cross_eof(STp, 0);
1436			STps->eof = ST_FM;
1437		}
1438		else { /* Write error */
1439			st_release_request(SRpnt);
1440			SRpnt = NULL;
1441			st_printk(KERN_ERR, STp,
1442				  "Error on write filemark.\n");
1443			if (result == 0)
1444				result = (-EIO);
1445		}
1446
1447		DEBC_printk(STp, "Buffer flushed, %d EOF(s) written\n", cmd[4]);
1448	} else if (!STp->rew_at_close) {
1449		STps = &(STp->ps[STp->partition]);
1450		if (!STm->sysv || STps->rw != ST_READING) {
1451			if (STp->can_bsr)
1452				result = flush_buffer(STp, 0);
1453			else if (STps->eof == ST_FM_HIT) {
1454				result = cross_eof(STp, 0);
1455				if (result) {
1456					if (STps->drv_file >= 0)
1457						STps->drv_file++;
1458					STps->drv_block = 0;
1459					STps->eof = ST_FM;
1460				} else
1461					STps->eof = ST_NOEOF;
1462			}
1463		} else if ((STps->eof == ST_NOEOF &&
1464			    !(result = cross_eof(STp, 1))) ||
1465			   STps->eof == ST_FM_HIT) {
1466			if (STps->drv_file >= 0)
1467				STps->drv_file++;
1468			STps->drv_block = 0;
1469			STps->eof = ST_FM;
1470		}
1471	}
1472
1473      out:
1474	if (STp->rew_at_close) {
1475		result2 = st_int_ioctl(STp, MTREW, 1);
1476		if (result == 0)
1477			result = result2;
1478	}
1479	return result;
1480}
1481
1482
1483/* Close the device and release it. BKL is not needed: this is the only thread
1484   accessing this tape. */
1485static int st_release(struct inode *inode, struct file *filp)
1486{
1487	struct scsi_tape *STp = filp->private_data;
1488
1489	if (STp->door_locked == ST_LOCKED_AUTO)
1490		do_door_lock(STp, 0);
1491
1492	normalize_buffer(STp->buffer);
1493	spin_lock(&st_use_lock);
1494	STp->in_use = 0;
1495	spin_unlock(&st_use_lock);
1496	scsi_autopm_put_device(STp->device);
1497	scsi_tape_put(STp);
1498
1499	return 0;
1500}
1501
1502/* The checks common to both reading and writing */
1503static ssize_t rw_checks(struct scsi_tape *STp, struct file *filp, size_t count)
1504{
1505	ssize_t retval = 0;
1506
1507	/*
1508	 * If we are in the middle of error recovery, don't let anyone
1509	 * else try and use this device.  Also, if error recovery fails, it
1510	 * may try and take the device offline, in which case all further
1511	 * access to the device is prohibited.
1512	 */
1513	if (!scsi_block_when_processing_errors(STp->device)) {
1514		retval = (-ENXIO);
1515		goto out;
1516	}
1517
1518	if (STp->ready != ST_READY) {
1519		if (STp->ready == ST_NO_TAPE)
1520			retval = (-ENOMEDIUM);
1521		else
1522			retval = (-EIO);
1523		goto out;
1524	}
1525
1526	if (! STp->modes[STp->current_mode].defined) {
1527		retval = (-ENXIO);
1528		goto out;
1529	}
1530
1531
1532	/*
1533	 * If there was a bus reset, block further access
1534	 * to this device.
1535	 */
1536	if (STp->pos_unknown) {
1537		retval = (-EIO);
1538		goto out;
1539	}
1540
1541	if (count == 0)
1542		goto out;
1543
1544	DEB(
1545	if (!STp->in_use) {
1546		st_printk(ST_DEB_MSG, STp,
1547			  "Incorrect device.\n");
1548		retval = (-EIO);
1549		goto out;
1550	} ) /* end DEB */
1551
1552	if (STp->can_partitions &&
1553	    (retval = switch_partition(STp)) < 0)
1554		goto out;
1555
1556	if (STp->block_size == 0 && STp->max_block > 0 &&
1557	    (count < STp->min_block || count > STp->max_block)) {
1558		retval = (-EINVAL);
1559		goto out;
1560	}
1561
1562	if (STp->do_auto_lock && STp->door_locked == ST_UNLOCKED &&
1563	    !do_door_lock(STp, 1))
1564		STp->door_locked = ST_LOCKED_AUTO;
1565
1566 out:
1567	return retval;
1568}
1569
1570
1571static int setup_buffering(struct scsi_tape *STp, const char __user *buf,
1572			   size_t count, int is_read)
1573{
1574	int i, bufsize, retval = 0;
1575	struct st_buffer *STbp = STp->buffer;
1576
1577	if (is_read)
1578		i = STp->try_dio_now && try_rdio;
1579	else
1580		i = STp->try_dio_now && try_wdio;
1581
1582	if (i && ((unsigned long)buf & queue_dma_alignment(
1583					STp->device->request_queue)) == 0) {
1584		i = sgl_map_user_pages(STbp, STbp->use_sg, (unsigned long)buf,
1585				       count, (is_read ? READ : WRITE));
1586		if (i > 0) {
1587			STbp->do_dio = i;
1588			STbp->buffer_bytes = 0;   /* can be used as transfer counter */
1589		}
1590		else
1591			STbp->do_dio = 0;  /* fall back to buffering with any error */
1592		STbp->sg_segs = STbp->do_dio;
1593		DEB(
1594		     if (STbp->do_dio) {
1595			STp->nbr_dio++;
1596			STp->nbr_pages += STbp->do_dio;
1597		     }
1598		)
1599	} else
1600		STbp->do_dio = 0;
1601	DEB( STp->nbr_requests++; )
1602
1603	if (!STbp->do_dio) {
1604		if (STp->block_size)
1605			bufsize = STp->block_size > st_fixed_buffer_size ?
1606				STp->block_size : st_fixed_buffer_size;
1607		else {
1608			bufsize = count;
1609			/* Make sure that data from previous user is not leaked even if
1610			   HBA does not return correct residual */
1611			if (is_read && STp->sili && !STbp->cleared)
1612				clear_buffer(STbp);
1613		}
1614
1615		if (bufsize > STbp->buffer_size &&
1616		    !enlarge_buffer(STbp, bufsize)) {
1617			st_printk(KERN_WARNING, STp,
1618				  "Can't allocate %d byte tape buffer.\n",
1619				  bufsize);
1620			retval = (-EOVERFLOW);
1621			goto out;
1622		}
1623		if (STp->block_size)
1624			STbp->buffer_blocks = bufsize / STp->block_size;
1625	}
1626
1627 out:
1628	return retval;
1629}
1630
1631
1632/* Can be called more than once after each setup_buffer() */
1633static void release_buffering(struct scsi_tape *STp, int is_read)
1634{
1635	struct st_buffer *STbp;
1636
1637	STbp = STp->buffer;
1638	if (STbp->do_dio) {
1639		sgl_unmap_user_pages(STbp, STbp->do_dio, is_read);
1640		STbp->do_dio = 0;
1641		STbp->sg_segs = 0;
1642	}
1643}
1644
1645
1646/* Write command */
1647static ssize_t
1648st_write(struct file *filp, const char __user *buf, size_t count, loff_t * ppos)
1649{
1650	ssize_t total;
1651	ssize_t i, do_count, blks, transfer;
1652	ssize_t retval;
1653	int undone, retry_eot = 0, scode;
1654	int async_write;
1655	unsigned char cmd[MAX_COMMAND_SIZE];
1656	const char __user *b_point;
1657	struct st_request *SRpnt = NULL;
1658	struct scsi_tape *STp = filp->private_data;
1659	struct st_modedef *STm;
1660	struct st_partstat *STps;
1661	struct st_buffer *STbp;
1662
1663	if (mutex_lock_interruptible(&STp->lock))
1664		return -ERESTARTSYS;
1665
1666	retval = rw_checks(STp, filp, count);
1667	if (retval || count == 0)
1668		goto out;
1669
1670	/* Write must be integral number of blocks */
1671	if (STp->block_size != 0 && (count % STp->block_size) != 0) {
1672		st_printk(KERN_WARNING, STp,
1673			  "Write not multiple of tape block size.\n");
1674		retval = (-EINVAL);
1675		goto out;
1676	}
1677
1678	STm = &(STp->modes[STp->current_mode]);
1679	STps = &(STp->ps[STp->partition]);
1680
1681	if (STp->write_prot) {
1682		retval = (-EACCES);
1683		goto out;
1684	}
1685
1686
1687	if (STps->rw == ST_READING) {
1688		retval = flush_buffer(STp, 0);
1689		if (retval)
1690			goto out;
1691		STps->rw = ST_WRITING;
1692	} else if (STps->rw != ST_WRITING &&
1693		   STps->drv_file == 0 && STps->drv_block == 0) {
1694		if ((retval = set_mode_densblk(STp, STm)) < 0)
1695			goto out;
1696		if (STm->default_compression != ST_DONT_TOUCH &&
1697		    !(STp->compression_changed)) {
1698			if (st_compression(STp, (STm->default_compression == ST_YES))) {
1699				st_printk(KERN_WARNING, STp,
1700					  "Can't set default compression.\n");
1701				if (modes_defined) {
1702					retval = (-EINVAL);
1703					goto out;
1704				}
1705			}
1706		}
1707	}
1708
1709	STbp = STp->buffer;
1710	i = write_behind_check(STp);
1711	if (i) {
1712		if (i == -ENOSPC)
1713			STps->eof = ST_EOM_OK;
1714		else
1715			STps->eof = ST_EOM_ERROR;
1716	}
1717
1718	if (STps->eof == ST_EOM_OK) {
1719		STps->eof = ST_EOD_1;  /* allow next write */
1720		retval = (-ENOSPC);
1721		goto out;
1722	}
1723	else if (STps->eof == ST_EOM_ERROR) {
1724		retval = (-EIO);
1725		goto out;
1726	}
1727
1728	/* Check the buffer readability in cases where copy_user might catch
1729	   the problems after some tape movement. */
1730	if (STp->block_size != 0 &&
1731	    !STbp->do_dio &&
1732	    (copy_from_user(&i, buf, 1) != 0 ||
1733	     copy_from_user(&i, buf + count - 1, 1) != 0)) {
1734		retval = (-EFAULT);
1735		goto out;
1736	}
1737
1738	retval = setup_buffering(STp, buf, count, 0);
1739	if (retval)
1740		goto out;
1741
1742	total = count;
1743
1744	memset(cmd, 0, MAX_COMMAND_SIZE);
1745	cmd[0] = WRITE_6;
1746	cmd[1] = (STp->block_size != 0);
1747
1748	STps->rw = ST_WRITING;
1749
1750	b_point = buf;
1751	while (count > 0 && !retry_eot) {
1752
1753		if (STbp->do_dio) {
1754			do_count = count;
1755		}
1756		else {
1757			if (STp->block_size == 0)
1758				do_count = count;
1759			else {
1760				do_count = STbp->buffer_blocks * STp->block_size -
1761					STbp->buffer_bytes;
1762				if (do_count > count)
1763					do_count = count;
1764			}
1765
1766			i = append_to_buffer(b_point, STbp, do_count);
1767			if (i) {
1768				retval = i;
1769				goto out;
1770			}
1771		}
1772		count -= do_count;
1773		b_point += do_count;
1774
1775		async_write = STp->block_size == 0 && !STbp->do_dio &&
1776			STm->do_async_writes && STps->eof < ST_EOM_OK;
1777
1778		if (STp->block_size != 0 && STm->do_buffer_writes &&
1779		    !(STp->try_dio_now && try_wdio) && STps->eof < ST_EOM_OK &&
1780		    STbp->buffer_bytes < STbp->buffer_size) {
1781			STp->dirty = 1;
1782			/* Don't write a buffer that is not full enough. */
1783			if (!async_write && count == 0)
1784				break;
1785		}
1786
1787	retry_write:
1788		if (STp->block_size == 0)
1789			blks = transfer = do_count;
1790		else {
1791			if (!STbp->do_dio)
1792				blks = STbp->buffer_bytes;
1793			else
1794				blks = do_count;
1795			blks /= STp->block_size;
1796			transfer = blks * STp->block_size;
1797		}
1798		cmd[2] = blks >> 16;
1799		cmd[3] = blks >> 8;
1800		cmd[4] = blks;
1801
1802		SRpnt = st_do_scsi(SRpnt, STp, cmd, transfer, DMA_TO_DEVICE,
1803				   STp->device->request_queue->rq_timeout,
1804				   MAX_WRITE_RETRIES, !async_write);
1805		if (!SRpnt) {
1806			retval = STbp->syscall_result;
1807			goto out;
1808		}
1809		if (async_write && !STbp->syscall_result) {
1810			STbp->writing = transfer;
1811			STp->dirty = !(STbp->writing ==
1812				       STbp->buffer_bytes);
1813			SRpnt = NULL;  /* Prevent releasing this request! */
1814			DEB( STp->write_pending = 1; )
1815			break;
1816		}
1817
1818		if (STbp->syscall_result != 0) {
1819			struct st_cmdstatus *cmdstatp = &STp->buffer->cmdstat;
1820
1821			DEBC_printk(STp, "Error on write:\n");
1822			if (cmdstatp->have_sense && (cmdstatp->flags & SENSE_EOM)) {
1823				scode = cmdstatp->sense_hdr.sense_key;
1824				if (cmdstatp->remainder_valid)
1825					undone = (int)cmdstatp->uremainder64;
1826				else if (STp->block_size == 0 &&
1827					 scode == VOLUME_OVERFLOW)
1828					undone = transfer;
1829				else
1830					undone = 0;
1831				if (STp->block_size != 0)
1832					undone *= STp->block_size;
1833				if (undone <= do_count) {
1834					/* Only data from this write is not written */
1835					count += undone;
1836					b_point -= undone;
1837					do_count -= undone;
1838					if (STp->block_size)
1839						blks = (transfer - undone) / STp->block_size;
1840					STps->eof = ST_EOM_OK;
1841					/* Continue in fixed block mode if all written
1842					   in this request but still something left to write
1843					   (retval left to zero)
1844					*/
1845					if (STp->block_size == 0 ||
1846					    undone > 0 || count == 0)
1847						retval = (-ENOSPC); /* EOM within current request */
1848					DEBC_printk(STp, "EOM with %d "
1849						    "bytes unwritten.\n",
1850						    (int)count);
1851				} else {
1852					/* EOT within data buffered earlier (possible only
1853					   in fixed block mode without direct i/o) */
1854					if (!retry_eot && !cmdstatp->deferred &&
1855					    (scode == NO_SENSE || scode == RECOVERED_ERROR)) {
1856						move_buffer_data(STp->buffer, transfer - undone);
1857						retry_eot = 1;
1858						if (STps->drv_block >= 0) {
1859							STps->drv_block += (transfer - undone) /
1860								STp->block_size;
1861						}
1862						STps->eof = ST_EOM_OK;
1863						DEBC_printk(STp, "Retry "
1864							    "write of %d "
1865							    "bytes at EOM.\n",
1866							    STp->buffer->buffer_bytes);
1867						goto retry_write;
1868					}
1869					else {
1870						/* Either error within data buffered by driver or
1871						   failed retry */
1872						count -= do_count;
1873						blks = do_count = 0;
1874						STps->eof = ST_EOM_ERROR;
1875						STps->drv_block = (-1); /* Too cautious? */
1876						retval = (-EIO);	/* EOM for old data */
1877						DEBC_printk(STp, "EOM with "
1878							    "lost data.\n");
1879					}
1880				}
1881			} else {
1882				count += do_count;
1883				STps->drv_block = (-1);		/* Too cautious? */
1884				retval = STbp->syscall_result;
1885			}
1886
1887		}
1888
1889		if (STps->drv_block >= 0) {
1890			if (STp->block_size == 0)
1891				STps->drv_block += (do_count > 0);
1892			else
1893				STps->drv_block += blks;
1894		}
1895
1896		STbp->buffer_bytes = 0;
1897		STp->dirty = 0;
1898
1899		if (retval || retry_eot) {
1900			if (count < total)
1901				retval = total - count;
1902			goto out;
1903		}
1904	}
1905
1906	if (STps->eof == ST_EOD_1)
1907		STps->eof = ST_EOM_OK;
1908	else if (STps->eof != ST_EOM_OK)
1909		STps->eof = ST_NOEOF;
1910	retval = total - count;
1911
1912 out:
1913	if (SRpnt != NULL)
1914		st_release_request(SRpnt);
1915	release_buffering(STp, 0);
1916	mutex_unlock(&STp->lock);
1917
1918	return retval;
1919}
1920
1921/* Read data from the tape. Returns zero in the normal case, one if the
1922   eof status has changed, and the negative error code in case of a
1923   fatal error. Otherwise updates the buffer and the eof state.
1924
1925   Does release user buffer mapping if it is set.
1926*/
1927static long read_tape(struct scsi_tape *STp, long count,
1928		      struct st_request ** aSRpnt)
1929{
1930	int transfer, blks, bytes;
1931	unsigned char cmd[MAX_COMMAND_SIZE];
1932	struct st_request *SRpnt;
1933	struct st_modedef *STm;
1934	struct st_partstat *STps;
1935	struct st_buffer *STbp;
1936	int retval = 0;
1937
1938	if (count == 0)
1939		return 0;
1940
1941	STm = &(STp->modes[STp->current_mode]);
1942	STps = &(STp->ps[STp->partition]);
1943	if (STps->eof == ST_FM_HIT)
1944		return 1;
1945	STbp = STp->buffer;
1946
1947	if (STp->block_size == 0)
1948		blks = bytes = count;
1949	else {
1950		if (!(STp->try_dio_now && try_rdio) && STm->do_read_ahead) {
1951			blks = (STp->buffer)->buffer_blocks;
1952			bytes = blks * STp->block_size;
1953		} else {
1954			bytes = count;
1955			if (!STbp->do_dio && bytes > (STp->buffer)->buffer_size)
1956				bytes = (STp->buffer)->buffer_size;
1957			blks = bytes / STp->block_size;
1958			bytes = blks * STp->block_size;
1959		}
1960	}
1961
1962	memset(cmd, 0, MAX_COMMAND_SIZE);
1963	cmd[0] = READ_6;
1964	cmd[1] = (STp->block_size != 0);
1965	if (!cmd[1] && STp->sili)
1966		cmd[1] |= 2;
1967	cmd[2] = blks >> 16;
1968	cmd[3] = blks >> 8;
1969	cmd[4] = blks;
1970
1971	SRpnt = *aSRpnt;
1972	SRpnt = st_do_scsi(SRpnt, STp, cmd, bytes, DMA_FROM_DEVICE,
1973			   STp->device->request_queue->rq_timeout,
1974			   MAX_RETRIES, 1);
1975	release_buffering(STp, 1);
1976	*aSRpnt = SRpnt;
1977	if (!SRpnt)
1978		return STbp->syscall_result;
1979
1980	STbp->read_pointer = 0;
1981	STps->at_sm = 0;
1982
1983	/* Something to check */
1984	if (STbp->syscall_result) {
1985		struct st_cmdstatus *cmdstatp = &STp->buffer->cmdstat;
1986
1987		retval = 1;
1988		DEBC_printk(STp,
1989			    "Sense: %2x %2x %2x %2x %2x %2x %2x %2x\n",
1990			    SRpnt->sense[0], SRpnt->sense[1],
1991			    SRpnt->sense[2], SRpnt->sense[3],
1992			    SRpnt->sense[4], SRpnt->sense[5],
1993			    SRpnt->sense[6], SRpnt->sense[7]);
1994		if (cmdstatp->have_sense) {
1995
1996			if (cmdstatp->sense_hdr.sense_key == BLANK_CHECK)
1997				cmdstatp->flags &= 0xcf;	/* No need for EOM in this case */
1998
1999			if (cmdstatp->flags != 0) { /* EOF, EOM, or ILI */
2000				/* Compute the residual count */
2001				if (cmdstatp->remainder_valid)
2002					transfer = (int)cmdstatp->uremainder64;
2003				else
2004					transfer = 0;
2005				if (cmdstatp->sense_hdr.sense_key == MEDIUM_ERROR) {
2006					if (STp->block_size == 0)
2007						transfer = bytes;
2008					/* Some drives set ILI with MEDIUM ERROR */
2009					cmdstatp->flags &= ~SENSE_ILI;
2010				}
2011
2012				if (cmdstatp->flags & SENSE_ILI) {	/* ILI */
2013					if (STp->block_size == 0 &&
2014					    transfer < 0) {
2015						st_printk(KERN_NOTICE, STp,
2016							  "Failed to read %d "
2017							  "byte block with %d "
2018							  "byte transfer.\n",
2019							  bytes - transfer,
2020							  bytes);
2021						if (STps->drv_block >= 0)
2022							STps->drv_block += 1;
2023						STbp->buffer_bytes = 0;
2024						return (-ENOMEM);
2025					} else if (STp->block_size == 0) {
2026						STbp->buffer_bytes = bytes - transfer;
2027					} else {
2028						st_release_request(SRpnt);
2029						SRpnt = *aSRpnt = NULL;
2030						if (transfer == blks) {	/* We did not get anything, error */
2031							st_printk(KERN_NOTICE, STp,
2032								  "Incorrect "
2033								  "block size.\n");
2034							if (STps->drv_block >= 0)
2035								STps->drv_block += blks - transfer + 1;
2036							st_int_ioctl(STp, MTBSR, 1);
2037							return (-EIO);
2038						}
2039						/* We have some data, deliver it */
2040						STbp->buffer_bytes = (blks - transfer) *
2041						    STp->block_size;
2042						DEBC_printk(STp, "ILI but "
2043							    "enough data "
2044							    "received %ld "
2045							    "%d.\n", count,
2046							    STbp->buffer_bytes);
2047						if (STps->drv_block >= 0)
2048							STps->drv_block += 1;
2049						if (st_int_ioctl(STp, MTBSR, 1))
2050							return (-EIO);
2051					}
2052				} else if (cmdstatp->flags & SENSE_FMK) {	/* FM overrides EOM */
2053					if (STps->eof != ST_FM_HIT)
2054						STps->eof = ST_FM_HIT;
2055					else
2056						STps->eof = ST_EOD_2;
2057					if (STp->block_size == 0)
2058						STbp->buffer_bytes = 0;
2059					else
2060						STbp->buffer_bytes =
2061						    bytes - transfer * STp->block_size;
2062					DEBC_printk(STp, "EOF detected (%d "
2063						    "bytes read).\n",
2064						    STbp->buffer_bytes);
2065				} else if (cmdstatp->flags & SENSE_EOM) {
2066					if (STps->eof == ST_FM)
2067						STps->eof = ST_EOD_1;
2068					else
2069						STps->eof = ST_EOM_OK;
2070					if (STp->block_size == 0)
2071						STbp->buffer_bytes = bytes - transfer;
2072					else
2073						STbp->buffer_bytes =
2074						    bytes - transfer * STp->block_size;
2075
2076					DEBC_printk(STp, "EOM detected (%d "
2077						    "bytes read).\n",
2078						    STbp->buffer_bytes);
2079				}
2080			}
2081			/* end of EOF, EOM, ILI test */
2082			else {	/* nonzero sense key */
2083				DEBC_printk(STp, "Tape error while reading.\n");
2084				STps->drv_block = (-1);
2085				if (STps->eof == ST_FM &&
2086				    cmdstatp->sense_hdr.sense_key == BLANK_CHECK) {
2087					DEBC_printk(STp, "Zero returned for "
2088						    "first BLANK CHECK "
2089						    "after EOF.\n");
2090					STps->eof = ST_EOD_2;	/* First BLANK_CHECK after FM */
2091				} else	/* Some other extended sense code */
2092					retval = (-EIO);
2093			}
2094
2095			if (STbp->buffer_bytes < 0)  /* Caused by bogus sense data */
2096				STbp->buffer_bytes = 0;
2097		}
2098		/* End of extended sense test */
2099		else {		/* Non-extended sense */
2100			retval = STbp->syscall_result;
2101		}
2102
2103	}
2104	/* End of error handling */
2105	else {			/* Read successful */
2106		STbp->buffer_bytes = bytes;
2107		if (STp->sili) /* In fixed block mode residual is always zero here */
2108			STbp->buffer_bytes -= STp->buffer->cmdstat.residual;
2109	}
2110
2111	if (STps->drv_block >= 0) {
2112		if (STp->block_size == 0)
2113			STps->drv_block++;
2114		else
2115			STps->drv_block += STbp->buffer_bytes / STp->block_size;
2116	}
2117	return retval;
2118}
2119
2120
2121/* Read command */
2122static ssize_t
2123st_read(struct file *filp, char __user *buf, size_t count, loff_t * ppos)
2124{
2125	ssize_t total;
2126	ssize_t retval = 0;
2127	ssize_t i, transfer;
2128	int special, do_dio = 0;
2129	struct st_request *SRpnt = NULL;
2130	struct scsi_tape *STp = filp->private_data;
2131	struct st_modedef *STm;
2132	struct st_partstat *STps;
2133	struct st_buffer *STbp = STp->buffer;
2134
2135	if (mutex_lock_interruptible(&STp->lock))
2136		return -ERESTARTSYS;
2137
2138	retval = rw_checks(STp, filp, count);
2139	if (retval || count == 0)
2140		goto out;
2141
2142	STm = &(STp->modes[STp->current_mode]);
2143	if (STp->block_size != 0 && (count % STp->block_size) != 0) {
2144		if (!STm->do_read_ahead) {
2145			retval = (-EINVAL);	/* Read must be integral number of blocks */
2146			goto out;
2147		}
2148		STp->try_dio_now = 0;  /* Direct i/o can't handle split blocks */
2149	}
2150
2151	STps = &(STp->ps[STp->partition]);
2152	if (STps->rw == ST_WRITING) {
2153		retval = flush_buffer(STp, 0);
2154		if (retval)
2155			goto out;
2156		STps->rw = ST_READING;
2157	}
2158	DEB(
2159	if (debugging && STps->eof != ST_NOEOF)
2160		st_printk(ST_DEB_MSG, STp,
2161			  "EOF/EOM flag up (%d). Bytes %d\n",
2162			  STps->eof, STbp->buffer_bytes);
2163	) /* end DEB */
2164
2165	retval = setup_buffering(STp, buf, count, 1);
2166	if (retval)
2167		goto out;
2168	do_dio = STbp->do_dio;
2169
2170	if (STbp->buffer_bytes == 0 &&
2171	    STps->eof >= ST_EOD_1) {
2172		if (STps->eof < ST_EOD) {
2173			STps->eof += 1;
2174			retval = 0;
2175			goto out;
2176		}
2177		retval = (-EIO);	/* EOM or Blank Check */
2178		goto out;
2179	}
2180
2181	if (do_dio) {
2182		/* Check the buffer writability before any tape movement. Don't alter
2183		   buffer data. */
2184		if (copy_from_user(&i, buf, 1) != 0 ||
2185		    copy_to_user(buf, &i, 1) != 0 ||
2186		    copy_from_user(&i, buf + count - 1, 1) != 0 ||
2187		    copy_to_user(buf + count - 1, &i, 1) != 0) {
2188			retval = (-EFAULT);
2189			goto out;
2190		}
2191	}
2192
2193	STps->rw = ST_READING;
2194
2195
2196	/* Loop until enough data in buffer or a special condition found */
2197	for (total = 0, special = 0; total < count && !special;) {
2198
2199		/* Get new data if the buffer is empty */
2200		if (STbp->buffer_bytes == 0) {
2201			special = read_tape(STp, count - total, &SRpnt);
2202			if (special < 0) {	/* No need to continue read */
2203				retval = special;
2204				goto out;
2205			}
2206		}
2207
2208		/* Move the data from driver buffer to user buffer */
2209		if (STbp->buffer_bytes > 0) {
2210			DEB(
2211			if (debugging && STps->eof != ST_NOEOF)
2212				st_printk(ST_DEB_MSG, STp,
2213					  "EOF up (%d). Left %d, needed %d.\n",
2214					  STps->eof, STbp->buffer_bytes,
2215					  (int)(count - total));
2216			) /* end DEB */
2217			transfer = STbp->buffer_bytes < count - total ?
2218			    STbp->buffer_bytes : count - total;
2219			if (!do_dio) {
2220				i = from_buffer(STbp, buf, transfer);
2221				if (i) {
2222					retval = i;
2223					goto out;
2224				}
2225			}
2226			buf += transfer;
2227			total += transfer;
2228		}
2229
2230		if (STp->block_size == 0)
2231			break;	/* Read only one variable length block */
2232
2233	}			/* for (total = 0, special = 0;
2234                                   total < count && !special; ) */
2235
2236	/* Change the eof state if no data from tape or buffer */
2237	if (total == 0) {
2238		if (STps->eof == ST_FM_HIT) {
2239			STps->eof = ST_FM;
2240			STps->drv_block = 0;
2241			if (STps->drv_file >= 0)
2242				STps->drv_file++;
2243		} else if (STps->eof == ST_EOD_1) {
2244			STps->eof = ST_EOD_2;
2245			STps->drv_block = 0;
2246			if (STps->drv_file >= 0)
2247				STps->drv_file++;
2248		} else if (STps->eof == ST_EOD_2)
2249			STps->eof = ST_EOD;
2250	} else if (STps->eof == ST_FM)
2251		STps->eof = ST_NOEOF;
2252	retval = total;
2253
2254 out:
2255	if (SRpnt != NULL) {
2256		st_release_request(SRpnt);
2257		SRpnt = NULL;
2258	}
2259	if (do_dio) {
2260		release_buffering(STp, 1);
2261		STbp->buffer_bytes = 0;
2262	}
2263	mutex_unlock(&STp->lock);
2264
2265	return retval;
2266}
2267
2268
2269
2270DEB(
2271/* Set the driver options */
2272static void st_log_options(struct scsi_tape * STp, struct st_modedef * STm)
2273{
2274	if (debugging) {
2275		st_printk(KERN_INFO, STp,
2276			  "Mode %d options: buffer writes: %d, "
2277			  "async writes: %d, read ahead: %d\n",
2278			  STp->current_mode, STm->do_buffer_writes,
2279			  STm->do_async_writes, STm->do_read_ahead);
2280		st_printk(KERN_INFO, STp,
2281			  "    can bsr: %d, two FMs: %d, "
2282			  "fast mteom: %d, auto lock: %d,\n",
2283			  STp->can_bsr, STp->two_fm, STp->fast_mteom,
2284			  STp->do_auto_lock);
2285		st_printk(KERN_INFO, STp,
2286			  "    defs for wr: %d, no block limits: %d, "
2287			  "partitions: %d, s2 log: %d\n",
2288			  STm->defaults_for_writes, STp->omit_blklims,
2289			  STp->can_partitions, STp->scsi2_logical);
2290		st_printk(KERN_INFO, STp,
2291			  "    sysv: %d nowait: %d sili: %d "
2292			  "nowait_filemark: %d\n",
2293			  STm->sysv, STp->immediate, STp->sili,
2294			  STp->immediate_filemark);
2295		st_printk(KERN_INFO, STp, "    debugging: %d\n", debugging);
2296	}
2297}
2298	)
2299
2300
2301static int st_set_options(struct scsi_tape *STp, long options)
2302{
2303	int value;
2304	long code;
2305	struct st_modedef *STm;
2306	struct cdev *cd0, *cd1;
2307	struct device *d0, *d1;
2308
2309	STm = &(STp->modes[STp->current_mode]);
2310	if (!STm->defined) {
2311		cd0 = STm->cdevs[0];
2312		cd1 = STm->cdevs[1];
2313		d0  = STm->devs[0];
2314		d1  = STm->devs[1];
2315		memcpy(STm, &(STp->modes[0]), sizeof(struct st_modedef));
2316		STm->cdevs[0] = cd0;
2317		STm->cdevs[1] = cd1;
2318		STm->devs[0]  = d0;
2319		STm->devs[1]  = d1;
2320		modes_defined = 1;
2321		DEBC_printk(STp, "Initialized mode %d definition from mode 0\n",
2322			    STp->current_mode);
2323	}
2324
2325	code = options & MT_ST_OPTIONS;
2326	if (code == MT_ST_BOOLEANS) {
2327		STm->do_buffer_writes = (options & MT_ST_BUFFER_WRITES) != 0;
2328		STm->do_async_writes = (options & MT_ST_ASYNC_WRITES) != 0;
2329		STm->defaults_for_writes = (options & MT_ST_DEF_WRITES) != 0;
2330		STm->do_read_ahead = (options & MT_ST_READ_AHEAD) != 0;
2331		STp->two_fm = (options & MT_ST_TWO_FM) != 0;
2332		STp->fast_mteom = (options & MT_ST_FAST_MTEOM) != 0;
2333		STp->do_auto_lock = (options & MT_ST_AUTO_LOCK) != 0;
2334		STp->can_bsr = (options & MT_ST_CAN_BSR) != 0;
2335		STp->omit_blklims = (options & MT_ST_NO_BLKLIMS) != 0;
2336		if ((STp->device)->scsi_level >= SCSI_2)
2337			STp->can_partitions = (options & MT_ST_CAN_PARTITIONS) != 0;
2338		STp->scsi2_logical = (options & MT_ST_SCSI2LOGICAL) != 0;
2339		STp->immediate = (options & MT_ST_NOWAIT) != 0;
2340		STp->immediate_filemark = (options & MT_ST_NOWAIT_EOF) != 0;
2341		STm->sysv = (options & MT_ST_SYSV) != 0;
2342		STp->sili = (options & MT_ST_SILI) != 0;
2343		DEB( debugging = (options & MT_ST_DEBUGGING) != 0;
2344		     st_log_options(STp, STm); )
2345	} else if (code == MT_ST_SETBOOLEANS || code == MT_ST_CLEARBOOLEANS) {
2346		value = (code == MT_ST_SETBOOLEANS);
2347		if ((options & MT_ST_BUFFER_WRITES) != 0)
2348			STm->do_buffer_writes = value;
2349		if ((options & MT_ST_ASYNC_WRITES) != 0)
2350			STm->do_async_writes = value;
2351		if ((options & MT_ST_DEF_WRITES) != 0)
2352			STm->defaults_for_writes = value;
2353		if ((options & MT_ST_READ_AHEAD) != 0)
2354			STm->do_read_ahead = value;
2355		if ((options & MT_ST_TWO_FM) != 0)
2356			STp->two_fm = value;
2357		if ((options & MT_ST_FAST_MTEOM) != 0)
2358			STp->fast_mteom = value;
2359		if ((options & MT_ST_AUTO_LOCK) != 0)
2360			STp->do_auto_lock = value;
2361		if ((options & MT_ST_CAN_BSR) != 0)
2362			STp->can_bsr = value;
2363		if ((options & MT_ST_NO_BLKLIMS) != 0)
2364			STp->omit_blklims = value;
2365		if ((STp->device)->scsi_level >= SCSI_2 &&
2366		    (options & MT_ST_CAN_PARTITIONS) != 0)
2367			STp->can_partitions = value;
2368		if ((options & MT_ST_SCSI2LOGICAL) != 0)
2369			STp->scsi2_logical = value;
2370		if ((options & MT_ST_NOWAIT) != 0)
2371			STp->immediate = value;
2372		if ((options & MT_ST_NOWAIT_EOF) != 0)
2373			STp->immediate_filemark = value;
2374		if ((options & MT_ST_SYSV) != 0)
2375			STm->sysv = value;
2376		if ((options & MT_ST_SILI) != 0)
2377			STp->sili = value;
2378		DEB(
2379		if ((options & MT_ST_DEBUGGING) != 0)
2380			debugging = value;
2381			st_log_options(STp, STm); )
2382	} else if (code == MT_ST_WRITE_THRESHOLD) {
2383		/* Retained for compatibility */
2384	} else if (code == MT_ST_DEF_BLKSIZE) {
2385		value = (options & ~MT_ST_OPTIONS);
2386		if (value == ~MT_ST_OPTIONS) {
2387			STm->default_blksize = (-1);
2388			DEBC_printk(STp, "Default block size disabled.\n");
2389		} else {
2390			STm->default_blksize = value;
2391			DEBC_printk(STp,"Default block size set to "
2392				    "%d bytes.\n", STm->default_blksize);
2393			if (STp->ready == ST_READY) {
2394				STp->blksize_changed = 0;
2395				set_mode_densblk(STp, STm);
2396			}
2397		}
2398	} else if (code == MT_ST_TIMEOUTS) {
2399		value = (options & ~MT_ST_OPTIONS);
2400		if ((value & MT_ST_SET_LONG_TIMEOUT) != 0) {
2401			STp->long_timeout = (value & ~MT_ST_SET_LONG_TIMEOUT) * HZ;
2402			DEBC_printk(STp, "Long timeout set to %d seconds.\n",
2403				    (value & ~MT_ST_SET_LONG_TIMEOUT));
2404		} else {
2405			blk_queue_rq_timeout(STp->device->request_queue,
2406					     value * HZ);
2407			DEBC_printk(STp, "Normal timeout set to %d seconds.\n",
2408				    value);
2409		}
2410	} else if (code == MT_ST_SET_CLN) {
2411		value = (options & ~MT_ST_OPTIONS) & 0xff;
2412		if (value != 0 &&
2413			(value < EXTENDED_SENSE_START ||
2414				value >= SCSI_SENSE_BUFFERSIZE))
2415			return (-EINVAL);
2416		STp->cln_mode = value;
2417		STp->cln_sense_mask = (options >> 8) & 0xff;
2418		STp->cln_sense_value = (options >> 16) & 0xff;
2419		st_printk(KERN_INFO, STp,
2420			  "Cleaning request mode %d, mask %02x, value %02x\n",
2421			  value, STp->cln_sense_mask, STp->cln_sense_value);
2422	} else if (code == MT_ST_DEF_OPTIONS) {
2423		code = (options & ~MT_ST_CLEAR_DEFAULT);
2424		value = (options & MT_ST_CLEAR_DEFAULT);
2425		if (code == MT_ST_DEF_DENSITY) {
2426			if (value == MT_ST_CLEAR_DEFAULT) {
2427				STm->default_density = (-1);
2428				DEBC_printk(STp,
2429					    "Density default disabled.\n");
2430			} else {
2431				STm->default_density = value & 0xff;
2432				DEBC_printk(STp, "Density default set to %x\n",
2433					    STm->default_density);
2434				if (STp->ready == ST_READY) {
2435					STp->density_changed = 0;
2436					set_mode_densblk(STp, STm);
2437				}
2438			}
2439		} else if (code == MT_ST_DEF_DRVBUFFER) {
2440			if (value == MT_ST_CLEAR_DEFAULT) {
2441				STp->default_drvbuffer = 0xff;
2442				DEBC_printk(STp,
2443					    "Drive buffer default disabled.\n");
2444			} else {
2445				STp->default_drvbuffer = value & 7;
2446				DEBC_printk(STp,
2447					    "Drive buffer default set to %x\n",
2448					    STp->default_drvbuffer);
2449				if (STp->ready == ST_READY)
2450					st_int_ioctl(STp, MTSETDRVBUFFER, STp->default_drvbuffer);
2451			}
2452		} else if (code == MT_ST_DEF_COMPRESSION) {
2453			if (value == MT_ST_CLEAR_DEFAULT) {
2454				STm->default_compression = ST_DONT_TOUCH;
2455				DEBC_printk(STp,
2456					    "Compression default disabled.\n");
2457			} else {
2458				if ((value & 0xff00) != 0) {
2459					STp->c_algo = (value & 0xff00) >> 8;
2460					DEBC_printk(STp, "Compression "
2461						    "algorithm set to 0x%x.\n",
2462						    STp->c_algo);
2463				}
2464				if ((value & 0xff) != 0xff) {
2465					STm->default_compression = (value & 1 ? ST_YES : ST_NO);
2466					DEBC_printk(STp, "Compression default "
2467						    "set to %x\n",
2468						    (value & 1));
2469					if (STp->ready == ST_READY) {
2470						STp->compression_changed = 0;
2471						st_compression(STp, (STm->default_compression == ST_YES));
2472					}
2473				}
2474			}
2475		}
2476	} else
2477		return (-EIO);
2478
2479	return 0;
2480}
2481
2482#define MODE_HEADER_LENGTH  4
2483
2484/* Mode header and page byte offsets */
2485#define MH_OFF_DATA_LENGTH     0
2486#define MH_OFF_MEDIUM_TYPE     1
2487#define MH_OFF_DEV_SPECIFIC    2
2488#define MH_OFF_BDESCS_LENGTH   3
2489#define MP_OFF_PAGE_NBR        0
2490#define MP_OFF_PAGE_LENGTH     1
2491
2492/* Mode header and page bit masks */
2493#define MH_BIT_WP              0x80
2494#define MP_MSK_PAGE_NBR        0x3f
2495
2496/* Don't return block descriptors */
2497#define MODE_SENSE_OMIT_BDESCS 0x08
2498
2499#define MODE_SELECT_PAGE_FORMAT 0x10
2500
2501/* Read a mode page into the tape buffer. The block descriptors are included
2502   if incl_block_descs is true. The page control is ored to the page number
2503   parameter, if necessary. */
2504static int read_mode_page(struct scsi_tape *STp, int page, int omit_block_descs)
2505{
2506	unsigned char cmd[MAX_COMMAND_SIZE];
2507	struct st_request *SRpnt;
2508
2509	memset(cmd, 0, MAX_COMMAND_SIZE);
2510	cmd[0] = MODE_SENSE;
2511	if (omit_block_descs)
2512		cmd[1] = MODE_SENSE_OMIT_BDESCS;
2513	cmd[2] = page;
2514	cmd[4] = 255;
2515
2516	SRpnt = st_do_scsi(NULL, STp, cmd, cmd[4], DMA_FROM_DEVICE,
2517			   STp->device->request_queue->rq_timeout, 0, 1);
2518	if (SRpnt == NULL)
2519		return (STp->buffer)->syscall_result;
2520
2521	st_release_request(SRpnt);
2522
2523	return STp->buffer->syscall_result;
2524}
2525
2526
2527/* Send the mode page in the tape buffer to the drive. Assumes that the mode data
2528   in the buffer is correctly formatted. The long timeout is used if slow is non-zero. */
2529static int write_mode_page(struct scsi_tape *STp, int page, int slow)
2530{
2531	int pgo;
2532	unsigned char cmd[MAX_COMMAND_SIZE];
2533	struct st_request *SRpnt;
2534	int timeout;
2535
2536	memset(cmd, 0, MAX_COMMAND_SIZE);
2537	cmd[0] = MODE_SELECT;
2538	cmd[1] = MODE_SELECT_PAGE_FORMAT;
2539	pgo = MODE_HEADER_LENGTH + (STp->buffer)->b_data[MH_OFF_BDESCS_LENGTH];
2540	cmd[4] = pgo + (STp->buffer)->b_data[pgo + MP_OFF_PAGE_LENGTH] + 2;
2541
2542	/* Clear reserved fields */
2543	(STp->buffer)->b_data[MH_OFF_DATA_LENGTH] = 0;
2544	(STp->buffer)->b_data[MH_OFF_MEDIUM_TYPE] = 0;
2545	(STp->buffer)->b_data[MH_OFF_DEV_SPECIFIC] &= ~MH_BIT_WP;
2546	(STp->buffer)->b_data[pgo + MP_OFF_PAGE_NBR] &= MP_MSK_PAGE_NBR;
2547
2548	timeout = slow ?
2549		STp->long_timeout : STp->device->request_queue->rq_timeout;
2550	SRpnt = st_do_scsi(NULL, STp, cmd, cmd[4], DMA_TO_DEVICE,
2551			   timeout, 0, 1);
2552	if (SRpnt == NULL)
2553		return (STp->buffer)->syscall_result;
2554
2555	st_release_request(SRpnt);
2556
2557	return STp->buffer->syscall_result;
2558}
2559
2560
2561#define COMPRESSION_PAGE        0x0f
2562#define COMPRESSION_PAGE_LENGTH 16
2563
2564#define CP_OFF_DCE_DCC          2
2565#define CP_OFF_C_ALGO           7
2566
2567#define DCE_MASK  0x80
2568#define DCC_MASK  0x40
2569#define RED_MASK  0x60
2570
2571
2572/* Control the compression with mode page 15. Algorithm not changed if zero.
2573
2574   The block descriptors are read and written because Sony SDT-7000 does not
2575   work without this (suggestion from Michael Schaefer <Michael.Schaefer@dlr.de>).
2576   Including block descriptors should not cause any harm to other drives. */
2577
2578static int st_compression(struct scsi_tape * STp, int state)
2579{
2580	int retval;
2581	int mpoffs;  /* Offset to mode page start */
2582	unsigned char *b_data = (STp->buffer)->b_data;
2583
2584	if (STp->ready != ST_READY)
2585		return (-EIO);
2586
2587	/* Read the current page contents */
2588	retval = read_mode_page(STp, COMPRESSION_PAGE, 0);
2589	if (retval) {
2590		DEBC_printk(STp, "Compression mode page not supported.\n");
2591		return (-EIO);
2592	}
2593
2594	mpoffs = MODE_HEADER_LENGTH + b_data[MH_OFF_BDESCS_LENGTH];
2595	DEBC_printk(STp, "Compression state is %d.\n",
2596		    (b_data[mpoffs + CP_OFF_DCE_DCC] & DCE_MASK ? 1 : 0));
2597
2598	/* Check if compression can be changed */
2599	if ((b_data[mpoffs + CP_OFF_DCE_DCC] & DCC_MASK) == 0) {
2600		DEBC_printk(STp, "Compression not supported.\n");
2601		return (-EIO);
2602	}
2603
2604	/* Do the change */
2605	if (state) {
2606		b_data[mpoffs + CP_OFF_DCE_DCC] |= DCE_MASK;
2607		if (STp->c_algo != 0)
2608			b_data[mpoffs + CP_OFF_C_ALGO] = STp->c_algo;
2609	}
2610	else {
2611		b_data[mpoffs + CP_OFF_DCE_DCC] &= ~DCE_MASK;
2612		if (STp->c_algo != 0)
2613			b_data[mpoffs + CP_OFF_C_ALGO] = 0; /* no compression */
2614	}
2615
2616	retval = write_mode_page(STp, COMPRESSION_PAGE, 0);
2617	if (retval) {
2618		DEBC_printk(STp, "Compression change failed.\n");
2619		return (-EIO);
2620	}
2621	DEBC_printk(STp, "Compression state changed to %d.\n", state);
2622
2623	STp->compression_changed = 1;
2624	return 0;
2625}
2626
2627
2628/* Process the load and unload commands (does unload if the load code is zero) */
2629static int do_load_unload(struct scsi_tape *STp, struct file *filp, int load_code)
2630{
2631	int retval = (-EIO), timeout;
2632	unsigned char cmd[MAX_COMMAND_SIZE];
2633	struct st_partstat *STps;
2634	struct st_request *SRpnt;
2635
2636	if (STp->ready != ST_READY && !load_code) {
2637		if (STp->ready == ST_NO_TAPE)
2638			return (-ENOMEDIUM);
2639		else
2640			return (-EIO);
2641	}
2642
2643	memset(cmd, 0, MAX_COMMAND_SIZE);
2644	cmd[0] = START_STOP;
2645	if (load_code)
2646		cmd[4] |= 1;
2647	/*
2648	 * If arg >= 1 && arg <= 6 Enhanced load/unload in HP C1553A
2649	 */
2650	if (load_code >= 1 + MT_ST_HPLOADER_OFFSET
2651	    && load_code <= 6 + MT_ST_HPLOADER_OFFSET) {
2652		DEBC_printk(STp, " Enhanced %sload slot %2d.\n",
2653			    (cmd[4]) ? "" : "un",
2654			    load_code - MT_ST_HPLOADER_OFFSET);
2655		cmd[3] = load_code - MT_ST_HPLOADER_OFFSET; /* MediaID field of C1553A */
2656	}
2657	if (STp->immediate) {
2658		cmd[1] = 1;	/* Don't wait for completion */
2659		timeout = STp->device->request_queue->rq_timeout;
2660	}
2661	else
2662		timeout = STp->long_timeout;
2663
2664	DEBC(
2665		if (!load_code)
2666			st_printk(ST_DEB_MSG, STp, "Unloading tape.\n");
2667		else
2668			st_printk(ST_DEB_MSG, STp, "Loading tape.\n");
2669		);
2670
2671	SRpnt = st_do_scsi(NULL, STp, cmd, 0, DMA_NONE,
2672			   timeout, MAX_RETRIES, 1);
2673	if (!SRpnt)
2674		return (STp->buffer)->syscall_result;
2675
2676	retval = (STp->buffer)->syscall_result;
2677	st_release_request(SRpnt);
2678
2679	if (!retval) {	/* SCSI command successful */
2680
2681		if (!load_code) {
2682			STp->rew_at_close = 0;
2683			STp->ready = ST_NO_TAPE;
2684		}
2685		else {
2686			STp->rew_at_close = STp->autorew_dev;
2687			retval = check_tape(STp, filp);
2688			if (retval > 0)
2689				retval = 0;
2690		}
2691	}
2692	else {
2693		STps = &(STp->ps[STp->partition]);
2694		STps->drv_file = STps->drv_block = (-1);
2695	}
2696
2697	return retval;
2698}
2699
2700#if DEBUG
2701#define ST_DEB_FORWARD  0
2702#define ST_DEB_BACKWARD 1
2703static void deb_space_print(struct scsi_tape *STp, int direction, char *units, unsigned char *cmd)
2704{
2705	s32 sc;
2706
2707	if (!debugging)
2708		return;
2709
2710	sc = sign_extend32(get_unaligned_be24(&cmd[2]), 23);
2711	if (direction)
2712		sc = -sc;
2713	st_printk(ST_DEB_MSG, STp, "Spacing tape %s over %d %s.\n",
2714		  direction ? "backward" : "forward", sc, units);
2715}
2716#else
2717#define ST_DEB_FORWARD  0
2718#define ST_DEB_BACKWARD 1
2719static void deb_space_print(struct scsi_tape *STp, int direction, char *units, unsigned char *cmd) {}
2720#endif
2721
2722
2723/* Internal ioctl function */
2724static int st_int_ioctl(struct scsi_tape *STp, unsigned int cmd_in, unsigned long arg)
2725{
2726	int timeout;
2727	long ltmp;
2728	int ioctl_result;
2729	int chg_eof = 1;
2730	unsigned char cmd[MAX_COMMAND_SIZE];
2731	struct st_request *SRpnt;
2732	struct st_partstat *STps;
2733	int fileno, blkno, at_sm, undone;
2734	int datalen = 0, direction = DMA_NONE;
2735
2736	WARN_ON(STp->buffer->do_dio != 0);
2737	if (STp->ready != ST_READY) {
2738		if (STp->ready == ST_NO_TAPE)
2739			return (-ENOMEDIUM);
2740		else
2741			return (-EIO);
2742	}
2743	timeout = STp->long_timeout;
2744	STps = &(STp->ps[STp->partition]);
2745	fileno = STps->drv_file;
2746	blkno = STps->drv_block;
2747	at_sm = STps->at_sm;
2748
2749	memset(cmd, 0, MAX_COMMAND_SIZE);
2750	switch (cmd_in) {
2751	case MTFSFM:
2752		chg_eof = 0;	/* Changed from the FSF after this */
2753		fallthrough;
2754	case MTFSF:
2755		cmd[0] = SPACE;
2756		cmd[1] = 0x01;	/* Space FileMarks */
2757		cmd[2] = (arg >> 16);
2758		cmd[3] = (arg >> 8);
2759		cmd[4] = arg;
2760		deb_space_print(STp, ST_DEB_FORWARD, "filemarks", cmd);
2761		if (fileno >= 0)
2762			fileno += arg;
2763		blkno = 0;
2764		at_sm &= (arg == 0);
2765		break;
2766	case MTBSFM:
2767		chg_eof = 0;	/* Changed from the FSF after this */
2768		fallthrough;
2769	case MTBSF:
2770		cmd[0] = SPACE;
2771		cmd[1] = 0x01;	/* Space FileMarks */
2772		ltmp = (-arg);
2773		cmd[2] = (ltmp >> 16);
2774		cmd[3] = (ltmp >> 8);
2775		cmd[4] = ltmp;
2776		deb_space_print(STp, ST_DEB_BACKWARD, "filemarks", cmd);
2777		if (fileno >= 0)
2778			fileno -= arg;
2779		blkno = (-1);	/* We can't know the block number */
2780		at_sm &= (arg == 0);
2781		break;
2782	case MTFSR:
2783		cmd[0] = SPACE;
2784		cmd[1] = 0x00;	/* Space Blocks */
2785		cmd[2] = (arg >> 16);
2786		cmd[3] = (arg >> 8);
2787		cmd[4] = arg;
2788		deb_space_print(STp, ST_DEB_FORWARD, "blocks", cmd);
2789		if (blkno >= 0)
2790			blkno += arg;
2791		at_sm &= (arg == 0);
2792		break;
2793	case MTBSR:
2794		cmd[0] = SPACE;
2795		cmd[1] = 0x00;	/* Space Blocks */
2796		ltmp = (-arg);
2797		cmd[2] = (ltmp >> 16);
2798		cmd[3] = (ltmp >> 8);
2799		cmd[4] = ltmp;
2800		deb_space_print(STp, ST_DEB_BACKWARD, "blocks", cmd);
2801		if (blkno >= 0)
2802			blkno -= arg;
2803		at_sm &= (arg == 0);
2804		break;
2805	case MTFSS:
2806		cmd[0] = SPACE;
2807		cmd[1] = 0x04;	/* Space Setmarks */
2808		cmd[2] = (arg >> 16);
2809		cmd[3] = (arg >> 8);
2810		cmd[4] = arg;
2811		deb_space_print(STp, ST_DEB_FORWARD, "setmarks", cmd);
2812		if (arg != 0) {
2813			blkno = fileno = (-1);
2814			at_sm = 1;
2815		}
2816		break;
2817	case MTBSS:
2818		cmd[0] = SPACE;
2819		cmd[1] = 0x04;	/* Space Setmarks */
2820		ltmp = (-arg);
2821		cmd[2] = (ltmp >> 16);
2822		cmd[3] = (ltmp >> 8);
2823		cmd[4] = ltmp;
2824		deb_space_print(STp, ST_DEB_BACKWARD, "setmarks", cmd);
2825		if (arg != 0) {
2826			blkno = fileno = (-1);
2827			at_sm = 1;
2828		}
2829		break;
2830	case MTWEOF:
2831	case MTWEOFI:
2832	case MTWSM:
2833		if (STp->write_prot)
2834			return (-EACCES);
2835		cmd[0] = WRITE_FILEMARKS;
2836		if (cmd_in == MTWSM)
2837			cmd[1] = 2;
2838		if (cmd_in == MTWEOFI ||
2839		    (cmd_in == MTWEOF && STp->immediate_filemark))
2840			cmd[1] |= 1;
2841		cmd[2] = (arg >> 16);
2842		cmd[3] = (arg >> 8);
2843		cmd[4] = arg;
2844		timeout = STp->device->request_queue->rq_timeout;
2845		DEBC(
2846			if (cmd_in != MTWSM)
2847				st_printk(ST_DEB_MSG, STp,
2848					  "Writing %d filemarks.\n",
2849					  cmd[2] * 65536 +
2850					  cmd[3] * 256 +
2851					  cmd[4]);
2852			else
2853				st_printk(ST_DEB_MSG, STp,
2854					  "Writing %d setmarks.\n",
2855					  cmd[2] * 65536 +
2856					  cmd[3] * 256 +
2857					  cmd[4]);
2858		)
2859		if (fileno >= 0)
2860			fileno += arg;
2861		blkno = 0;
2862		at_sm = (cmd_in == MTWSM);
2863		break;
2864	case MTREW:
2865		cmd[0] = REZERO_UNIT;
2866		if (STp->immediate) {
2867			cmd[1] = 1;	/* Don't wait for completion */
2868			timeout = STp->device->request_queue->rq_timeout;
2869		}
2870		DEBC_printk(STp, "Rewinding tape.\n");
2871		fileno = blkno = at_sm = 0;
2872		break;
2873	case MTNOP:
2874		DEBC_printk(STp, "No op on tape.\n");
2875		return 0;	/* Should do something ? */
2876	case MTRETEN:
2877		cmd[0] = START_STOP;
2878		if (STp->immediate) {
2879			cmd[1] = 1;	/* Don't wait for completion */
2880			timeout = STp->device->request_queue->rq_timeout;
2881		}
2882		cmd[4] = 3;
2883		DEBC_printk(STp, "Retensioning tape.\n");
2884		fileno = blkno = at_sm = 0;
2885		break;
2886	case MTEOM:
2887		if (!STp->fast_mteom) {
2888			/* space to the end of tape */
2889			ioctl_result = st_int_ioctl(STp, MTFSF, 0x7fffff);
2890			fileno = STps->drv_file;
2891			if (STps->eof >= ST_EOD_1)
2892				return 0;
2893			/* The next lines would hide the number of spaced FileMarks
2894			   That's why I inserted the previous lines. I had no luck
2895			   with detecting EOM with FSF, so we go now to EOM.
2896			   Joerg Weule */
2897		} else
2898			fileno = (-1);
2899		cmd[0] = SPACE;
2900		cmd[1] = 3;
2901		DEBC_printk(STp, "Spacing to end of recorded medium.\n");
2902		blkno = -1;
2903		at_sm = 0;
2904		break;
2905	case MTERASE:
2906		if (STp->write_prot)
2907			return (-EACCES);
2908		cmd[0] = ERASE;
2909		cmd[1] = (arg ? 1 : 0);	/* Long erase with non-zero argument */
2910		if (STp->immediate) {
2911			cmd[1] |= 2;	/* Don't wait for completion */
2912			timeout = STp->device->request_queue->rq_timeout;
2913		}
2914		else
2915			timeout = STp->long_timeout * 8;
2916
2917		DEBC_printk(STp, "Erasing tape.\n");
2918		break;
2919	case MTSETBLK:		/* Set block length */
2920	case MTSETDENSITY:	/* Set tape density */
2921	case MTSETDRVBUFFER:	/* Set drive buffering */
2922	case SET_DENS_AND_BLK:	/* Set density and block size */
2923		chg_eof = 0;
2924		if (STp->dirty || (STp->buffer)->buffer_bytes != 0)
2925			return (-EIO);	/* Not allowed if data in buffer */
2926		if ((cmd_in == MTSETBLK || cmd_in == SET_DENS_AND_BLK) &&
2927		    (arg & MT_ST_BLKSIZE_MASK) != 0 &&
2928		    STp->max_block > 0 &&
2929		    ((arg & MT_ST_BLKSIZE_MASK) < STp->min_block ||
2930		     (arg & MT_ST_BLKSIZE_MASK) > STp->max_block)) {
2931			st_printk(KERN_WARNING, STp, "Illegal block size.\n");
2932			return (-EINVAL);
2933		}
2934		cmd[0] = MODE_SELECT;
2935		if ((STp->use_pf & USE_PF))
2936			cmd[1] = MODE_SELECT_PAGE_FORMAT;
2937		cmd[4] = datalen = 12;
2938		direction = DMA_TO_DEVICE;
2939
2940		memset((STp->buffer)->b_data, 0, 12);
2941		if (cmd_in == MTSETDRVBUFFER)
2942			(STp->buffer)->b_data[2] = (arg & 7) << 4;
2943		else
2944			(STp->buffer)->b_data[2] =
2945			    STp->drv_buffer << 4;
2946		(STp->buffer)->b_data[3] = 8;	/* block descriptor length */
2947		if (cmd_in == MTSETDENSITY) {
2948			(STp->buffer)->b_data[4] = arg;
2949			STp->density_changed = 1;	/* At least we tried ;-) */
2950			STp->changed_density = arg;
2951		} else if (cmd_in == SET_DENS_AND_BLK)
2952			(STp->buffer)->b_data[4] = arg >> 24;
2953		else
2954			(STp->buffer)->b_data[4] = STp->density;
2955		if (cmd_in == MTSETBLK || cmd_in == SET_DENS_AND_BLK) {
2956			ltmp = arg & MT_ST_BLKSIZE_MASK;
2957			if (cmd_in == MTSETBLK) {
2958				STp->blksize_changed = 1; /* At least we tried ;-) */
2959				STp->changed_blksize = arg;
2960			}
2961		} else
2962			ltmp = STp->block_size;
2963		(STp->buffer)->b_data[9] = (ltmp >> 16);
2964		(STp->buffer)->b_data[10] = (ltmp >> 8);
2965		(STp->buffer)->b_data[11] = ltmp;
2966		timeout = STp->device->request_queue->rq_timeout;
2967		DEBC(
2968			if (cmd_in == MTSETBLK || cmd_in == SET_DENS_AND_BLK)
2969				st_printk(ST_DEB_MSG, STp,
2970					  "Setting block size to %d bytes.\n",
2971					  (STp->buffer)->b_data[9] * 65536 +
2972					  (STp->buffer)->b_data[10] * 256 +
2973					  (STp->buffer)->b_data[11]);
2974			if (cmd_in == MTSETDENSITY || cmd_in == SET_DENS_AND_BLK)
2975				st_printk(ST_DEB_MSG, STp,
2976					  "Setting density code to %x.\n",
2977					  (STp->buffer)->b_data[4]);
2978			if (cmd_in == MTSETDRVBUFFER)
2979				st_printk(ST_DEB_MSG, STp,
2980					  "Setting drive buffer code to %d.\n",
2981					  ((STp->buffer)->b_data[2] >> 4) & 7);
2982		)
2983		break;
2984	default:
2985		return (-ENOSYS);
2986	}
2987
2988	SRpnt = st_do_scsi(NULL, STp, cmd, datalen, direction,
2989			   timeout, MAX_RETRIES, 1);
2990	if (!SRpnt)
2991		return (STp->buffer)->syscall_result;
2992
2993	ioctl_result = (STp->buffer)->syscall_result;
2994
2995	if (!ioctl_result) {	/* SCSI command successful */
2996		st_release_request(SRpnt);
2997		SRpnt = NULL;
2998		STps->drv_block = blkno;
2999		STps->drv_file = fileno;
3000		STps->at_sm = at_sm;
3001
3002		if (cmd_in == MTBSFM)
3003			ioctl_result = st_int_ioctl(STp, MTFSF, 1);
3004		else if (cmd_in == MTFSFM)
3005			ioctl_result = st_int_ioctl(STp, MTBSF, 1);
3006
3007		if (cmd_in == MTSETBLK || cmd_in == SET_DENS_AND_BLK) {
3008			STp->block_size = arg & MT_ST_BLKSIZE_MASK;
3009			if (STp->block_size != 0) {
3010				(STp->buffer)->buffer_blocks =
3011				    (STp->buffer)->buffer_size / STp->block_size;
3012			}
3013			(STp->buffer)->buffer_bytes = (STp->buffer)->read_pointer = 0;
3014			if (cmd_in == SET_DENS_AND_BLK)
3015				STp->density = arg >> MT_ST_DENSITY_SHIFT;
3016		} else if (cmd_in == MTSETDRVBUFFER)
3017			STp->drv_buffer = (arg & 7);
3018		else if (cmd_in == MTSETDENSITY)
3019			STp->density = arg;
3020
3021		if (cmd_in == MTEOM)
3022			STps->eof = ST_EOD;
3023		else if (cmd_in == MTFSF)
3024			STps->eof = ST_FM;
3025		else if (chg_eof)
3026			STps->eof = ST_NOEOF;
3027
3028		if (cmd_in == MTWEOF || cmd_in == MTWEOFI)
3029			STps->rw = ST_IDLE;  /* prevent automatic WEOF at close */
3030	} else { /* SCSI command was not completely successful. Don't return
3031                    from this block without releasing the SCSI command block! */
3032		struct st_cmdstatus *cmdstatp = &STp->buffer->cmdstat;
3033
3034		if (cmdstatp->flags & SENSE_EOM) {
3035			if (cmd_in != MTBSF && cmd_in != MTBSFM &&
3036			    cmd_in != MTBSR && cmd_in != MTBSS)
3037				STps->eof = ST_EOM_OK;
3038			STps->drv_block = 0;
3039		}
3040
3041		if (cmdstatp->remainder_valid)
3042			undone = (int)cmdstatp->uremainder64;
3043		else
3044			undone = 0;
3045
3046		if ((cmd_in == MTWEOF || cmd_in == MTWEOFI) &&
3047		    cmdstatp->have_sense &&
3048		    (cmdstatp->flags & SENSE_EOM)) {
3049			if (cmdstatp->sense_hdr.sense_key == NO_SENSE ||
3050			    cmdstatp->sense_hdr.sense_key == RECOVERED_ERROR) {
3051				ioctl_result = 0;	/* EOF(s) written successfully at EOM */
3052				STps->eof = ST_NOEOF;
3053			} else {  /* Writing EOF(s) failed */
3054				if (fileno >= 0)
3055					fileno -= undone;
3056				if (undone < arg)
3057					STps->eof = ST_NOEOF;
3058			}
3059			STps->drv_file = fileno;
3060		} else if ((cmd_in == MTFSF) || (cmd_in == MTFSFM)) {
3061			if (fileno >= 0)
3062				STps->drv_file = fileno - undone;
3063			else
3064				STps->drv_file = fileno;
3065			STps->drv_block = -1;
3066			STps->eof = ST_NOEOF;
3067		} else if ((cmd_in == MTBSF) || (cmd_in == MTBSFM)) {
3068			if (arg > 0 && undone < 0)  /* Some drives get this wrong */
3069				undone = (-undone);
3070			if (STps->drv_file >= 0)
3071				STps->drv_file = fileno + undone;
3072			STps->drv_block = 0;
3073			STps->eof = ST_NOEOF;
3074		} else if (cmd_in == MTFSR) {
3075			if (cmdstatp->flags & SENSE_FMK) {	/* Hit filemark */
3076				if (STps->drv_file >= 0)
3077					STps->drv_file++;
3078				STps->drv_block = 0;
3079				STps->eof = ST_FM;
3080			} else {
3081				if (blkno >= undone)
3082					STps->drv_block = blkno - undone;
3083				else
3084					STps->drv_block = (-1);
3085				STps->eof = ST_NOEOF;
3086			}
3087		} else if (cmd_in == MTBSR) {
3088			if (cmdstatp->flags & SENSE_FMK) {	/* Hit filemark */
3089				STps->drv_file--;
3090				STps->drv_block = (-1);
3091			} else {
3092				if (arg > 0 && undone < 0)  /* Some drives get this wrong */
3093					undone = (-undone);
3094				if (STps->drv_block >= 0)
3095					STps->drv_block = blkno + undone;
3096			}
3097			STps->eof = ST_NOEOF;
3098		} else if (cmd_in == MTEOM) {
3099			STps->drv_file = (-1);
3100			STps->drv_block = (-1);
3101			STps->eof = ST_EOD;
3102		} else if (cmd_in == MTSETBLK ||
3103			   cmd_in == MTSETDENSITY ||
3104			   cmd_in == MTSETDRVBUFFER ||
3105			   cmd_in == SET_DENS_AND_BLK) {
3106			if (cmdstatp->sense_hdr.sense_key == ILLEGAL_REQUEST &&
3107				cmdstatp->sense_hdr.asc == 0x24 &&
3108				(STp->device)->scsi_level <= SCSI_2 &&
3109				!(STp->use_pf & PF_TESTED)) {
3110				/* Try the other possible state of Page Format if not
3111				   already tried */
3112				STp->use_pf = (STp->use_pf ^ USE_PF) | PF_TESTED;
3113				st_release_request(SRpnt);
3114				SRpnt = NULL;
3115				return st_int_ioctl(STp, cmd_in, arg);
3116			}
3117		} else if (chg_eof)
3118			STps->eof = ST_NOEOF;
3119
3120		if (cmdstatp->sense_hdr.sense_key == BLANK_CHECK)
3121			STps->eof = ST_EOD;
3122
3123		st_release_request(SRpnt);
3124		SRpnt = NULL;
3125	}
3126
3127	return ioctl_result;
3128}
3129
3130
3131/* Get the tape position. If bt == 2, arg points into a kernel space mt_loc
3132   structure. */
3133
3134static int get_location(struct scsi_tape *STp, unsigned int *block, int *partition,
3135			int logical)
3136{
3137	int result;
3138	unsigned char scmd[MAX_COMMAND_SIZE];
3139	struct st_request *SRpnt;
3140
3141	if (STp->ready != ST_READY)
3142		return (-EIO);
3143
3144	memset(scmd, 0, MAX_COMMAND_SIZE);
3145	if ((STp->device)->scsi_level < SCSI_2) {
3146		scmd[0] = QFA_REQUEST_BLOCK;
3147		scmd[4] = 3;
3148	} else {
3149		scmd[0] = READ_POSITION;
3150		if (!logical && !STp->scsi2_logical)
3151			scmd[1] = 1;
3152	}
3153	SRpnt = st_do_scsi(NULL, STp, scmd, 20, DMA_FROM_DEVICE,
3154			   STp->device->request_queue->rq_timeout,
3155			   MAX_READY_RETRIES, 1);
3156	if (!SRpnt)
3157		return (STp->buffer)->syscall_result;
3158
3159	if ((STp->buffer)->syscall_result != 0 ||
3160	    (STp->device->scsi_level >= SCSI_2 &&
3161	     ((STp->buffer)->b_data[0] & 4) != 0)) {
3162		*block = *partition = 0;
3163		DEBC_printk(STp, " Can't read tape position.\n");
3164		result = (-EIO);
3165	} else {
3166		result = 0;
3167		if ((STp->device)->scsi_level < SCSI_2) {
3168			*block = ((STp->buffer)->b_data[0] << 16)
3169			    + ((STp->buffer)->b_data[1] << 8)
3170			    + (STp->buffer)->b_data[2];
3171			*partition = 0;
3172		} else {
3173			*block = ((STp->buffer)->b_data[4] << 24)
3174			    + ((STp->buffer)->b_data[5] << 16)
3175			    + ((STp->buffer)->b_data[6] << 8)
3176			    + (STp->buffer)->b_data[7];
3177			*partition = (STp->buffer)->b_data[1];
3178			if (((STp->buffer)->b_data[0] & 0x80) &&
3179			    (STp->buffer)->b_data[1] == 0)	/* BOP of partition 0 */
3180				STp->ps[0].drv_block = STp->ps[0].drv_file = 0;
3181		}
3182		DEBC_printk(STp, "Got tape pos. blk %d part %d.\n",
3183			    *block, *partition);
3184	}
3185	st_release_request(SRpnt);
3186	SRpnt = NULL;
3187
3188	return result;
3189}
3190
3191
3192/* Set the tape block and partition. Negative partition means that only the
3193   block should be set in vendor specific way. */
3194static int set_location(struct scsi_tape *STp, unsigned int block, int partition,
3195			int logical)
3196{
3197	struct st_partstat *STps;
3198	int result, p;
3199	unsigned int blk;
3200	int timeout;
3201	unsigned char scmd[MAX_COMMAND_SIZE];
3202	struct st_request *SRpnt;
3203
3204	if (STp->ready != ST_READY)
3205		return (-EIO);
3206	timeout = STp->long_timeout;
3207	STps = &(STp->ps[STp->partition]);
3208
3209	DEBC_printk(STp, "Setting block to %d and partition to %d.\n",
3210		    block, partition);
3211	DEB(if (partition < 0)
3212		return (-EIO); )
3213
3214	/* Update the location at the partition we are leaving */
3215	if ((!STp->can_partitions && partition != 0) ||
3216	    partition >= ST_NBR_PARTITIONS)
3217		return (-EINVAL);
3218	if (partition != STp->partition) {
3219		if (get_location(STp, &blk, &p, 1))
3220			STps->last_block_valid = 0;
3221		else {
3222			STps->last_block_valid = 1;
3223			STps->last_block_visited = blk;
3224			DEBC_printk(STp, "Visited block %d for "
3225				    "partition %d saved.\n",
3226				    blk, STp->partition);
3227		}
3228	}
3229
3230	memset(scmd, 0, MAX_COMMAND_SIZE);
3231	if ((STp->device)->scsi_level < SCSI_2) {
3232		scmd[0] = QFA_SEEK_BLOCK;
3233		scmd[2] = (block >> 16);
3234		scmd[3] = (block >> 8);
3235		scmd[4] = block;
3236		scmd[5] = 0;
3237	} else {
3238		scmd[0] = SEEK_10;
3239		scmd[3] = (block >> 24);
3240		scmd[4] = (block >> 16);
3241		scmd[5] = (block >> 8);
3242		scmd[6] = block;
3243		if (!logical && !STp->scsi2_logical)
3244			scmd[1] = 4;
3245		if (STp->partition != partition) {
3246			scmd[1] |= 2;
3247			scmd[8] = partition;
3248			DEBC_printk(STp, "Trying to change partition "
3249				    "from %d to %d\n", STp->partition,
3250				    partition);
3251		}
3252	}
3253	if (STp->immediate) {
3254		scmd[1] |= 1;		/* Don't wait for completion */
3255		timeout = STp->device->request_queue->rq_timeout;
3256	}
3257
3258	SRpnt = st_do_scsi(NULL, STp, scmd, 0, DMA_NONE,
3259			   timeout, MAX_READY_RETRIES, 1);
3260	if (!SRpnt)
3261		return (STp->buffer)->syscall_result;
3262
3263	STps->drv_block = STps->drv_file = (-1);
3264	STps->eof = ST_NOEOF;
3265	if ((STp->buffer)->syscall_result != 0) {
3266		result = (-EIO);
3267		if (STp->can_partitions &&
3268		    (STp->device)->scsi_level >= SCSI_2 &&
3269		    (p = find_partition(STp)) >= 0)
3270			STp->partition = p;
3271	} else {
3272		if (STp->can_partitions) {
3273			STp->partition = partition;
3274			STps = &(STp->ps[partition]);
3275			if (!STps->last_block_valid ||
3276			    STps->last_block_visited != block) {
3277				STps->at_sm = 0;
3278				STps->rw = ST_IDLE;
3279			}
3280		} else
3281			STps->at_sm = 0;
3282		if (block == 0)
3283			STps->drv_block = STps->drv_file = 0;
3284		result = 0;
3285	}
3286
3287	st_release_request(SRpnt);
3288	SRpnt = NULL;
3289
3290	return result;
3291}
3292
3293
3294/* Find the current partition number for the drive status. Called from open and
3295   returns either partition number of negative error code. */
3296static int find_partition(struct scsi_tape *STp)
3297{
3298	int i, partition;
3299	unsigned int block;
3300
3301	if ((i = get_location(STp, &block, &partition, 1)) < 0)
3302		return i;
3303	if (partition >= ST_NBR_PARTITIONS)
3304		return (-EIO);
3305	return partition;
3306}
3307
3308
3309/* Change the partition if necessary */
3310static int switch_partition(struct scsi_tape *STp)
3311{
3312	struct st_partstat *STps;
3313
3314	if (STp->partition == STp->new_partition)
3315		return 0;
3316	STps = &(STp->ps[STp->new_partition]);
3317	if (!STps->last_block_valid)
3318		STps->last_block_visited = 0;
3319	return set_location(STp, STps->last_block_visited, STp->new_partition, 1);
3320}
3321
3322/* Functions for reading and writing the medium partition mode page. */
3323
3324#define PART_PAGE   0x11
3325#define PART_PAGE_FIXED_LENGTH 8
3326
3327#define PP_OFF_MAX_ADD_PARTS   2
3328#define PP_OFF_NBR_ADD_PARTS   3
3329#define PP_OFF_FLAGS           4
3330#define PP_OFF_PART_UNITS      6
3331#define PP_OFF_RESERVED        7
3332
3333#define PP_BIT_IDP             0x20
3334#define PP_BIT_FDP             0x80
3335#define PP_MSK_PSUM_MB         0x10
3336#define PP_MSK_PSUM_UNITS      0x18
3337#define PP_MSK_POFM            0x04
3338
3339/* Get the number of partitions on the tape. As a side effect reads the
3340   mode page into the tape buffer. */
3341static int nbr_partitions(struct scsi_tape *STp)
3342{
3343	int result;
3344
3345	if (STp->ready != ST_READY)
3346		return (-EIO);
3347
3348	result = read_mode_page(STp, PART_PAGE, 1);
3349
3350	if (result) {
3351		DEBC_printk(STp, "Can't read medium partition page.\n");
3352		result = (-EIO);
3353	} else {
3354		result = (STp->buffer)->b_data[MODE_HEADER_LENGTH +
3355					      PP_OFF_NBR_ADD_PARTS] + 1;
3356		DEBC_printk(STp, "Number of partitions %d.\n", result);
3357	}
3358
3359	return result;
3360}
3361
3362
3363static int format_medium(struct scsi_tape *STp, int format)
3364{
3365	int result = 0;
3366	int timeout = STp->long_timeout;
3367	unsigned char scmd[MAX_COMMAND_SIZE];
3368	struct st_request *SRpnt;
3369
3370	memset(scmd, 0, MAX_COMMAND_SIZE);
3371	scmd[0] = FORMAT_UNIT;
3372	scmd[2] = format;
3373	if (STp->immediate) {
3374		scmd[1] |= 1;		/* Don't wait for completion */
3375		timeout = STp->device->request_queue->rq_timeout;
3376	}
3377	DEBC_printk(STp, "Sending FORMAT MEDIUM\n");
3378	SRpnt = st_do_scsi(NULL, STp, scmd, 0, DMA_NONE,
3379			   timeout, MAX_RETRIES, 1);
3380	if (!SRpnt)
3381		result = STp->buffer->syscall_result;
3382	return result;
3383}
3384
3385
3386/* Partition the tape into two partitions if size > 0 or one partition if
3387   size == 0.
3388
3389   The block descriptors are read and written because Sony SDT-7000 does not
3390   work without this (suggestion from Michael Schaefer <Michael.Schaefer@dlr.de>).
3391
3392   My HP C1533A drive returns only one partition size field. This is used to
3393   set the size of partition 1. There is no size field for the default partition.
3394   Michael Schaefer's Sony SDT-7000 returns two descriptors and the second is
3395   used to set the size of partition 1 (this is what the SCSI-3 standard specifies).
3396   The following algorithm is used to accommodate both drives: if the number of
3397   partition size fields is greater than the maximum number of additional partitions
3398   in the mode page, the second field is used. Otherwise the first field is used.
3399
3400   For Seagate DDS drives the page length must be 8 when no partitions is defined
3401   and 10 when 1 partition is defined (information from Eric Lee Green). This is
3402   is acceptable also to some other old drives and enforced if the first partition
3403   size field is used for the first additional partition size.
3404
3405   For drives that advertize SCSI-3 or newer, use the SSC-3 methods.
3406 */
3407static int partition_tape(struct scsi_tape *STp, int size)
3408{
3409	int result;
3410	int target_partition;
3411	bool scsi3 = STp->device->scsi_level >= SCSI_3, needs_format = false;
3412	int pgo, psd_cnt, psdo;
3413	int psum = PP_MSK_PSUM_MB, units = 0;
3414	unsigned char *bp;
3415
3416	result = read_mode_page(STp, PART_PAGE, 0);
3417	if (result) {
3418		DEBC_printk(STp, "Can't read partition mode page.\n");
3419		return result;
3420	}
3421	target_partition = 1;
3422	if (size < 0) {
3423		target_partition = 0;
3424		size = -size;
3425	}
3426
3427	/* The mode page is in the buffer. Let's modify it and write it. */
3428	bp = (STp->buffer)->b_data;
3429	pgo = MODE_HEADER_LENGTH + bp[MH_OFF_BDESCS_LENGTH];
3430	DEBC_printk(STp, "Partition page length is %d bytes.\n",
3431		    bp[pgo + MP_OFF_PAGE_LENGTH] + 2);
3432
3433	psd_cnt = (bp[pgo + MP_OFF_PAGE_LENGTH] + 2 - PART_PAGE_FIXED_LENGTH) / 2;
3434
3435	if (scsi3) {
3436		needs_format = (bp[pgo + PP_OFF_FLAGS] & PP_MSK_POFM) != 0;
3437		if (needs_format && size == 0) {
3438			/* No need to write the mode page when clearing
3439			 *  partitioning
3440			 */
3441			DEBC_printk(STp, "Formatting tape with one partition.\n");
3442			result = format_medium(STp, 0);
3443			goto out;
3444		}
3445		if (needs_format)  /* Leave the old value for HP DATs claiming SCSI_3 */
3446			psd_cnt = 2;
3447		if ((bp[pgo + PP_OFF_FLAGS] & PP_MSK_PSUM_UNITS) == PP_MSK_PSUM_UNITS) {
3448			/* Use units scaling for large partitions if the device
3449			 * suggests it and no precision lost. Required for IBM
3450			 * TS1140/50 drives that don't support MB units.
3451			 */
3452			if (size >= 1000 && (size % 1000) == 0) {
3453				size /= 1000;
3454				psum = PP_MSK_PSUM_UNITS;
3455				units = 9; /* GB */
3456			}
3457		}
3458		/* Try it anyway if too large to specify in MB */
3459		if (psum == PP_MSK_PSUM_MB && size >= 65534) {
3460			size /= 1000;
3461			psum = PP_MSK_PSUM_UNITS;
3462			units = 9;  /* GB */
3463		}
3464	}
3465
3466	if (size >= 65535 ||  /* Does not fit into two bytes */
3467	    (target_partition == 0 && psd_cnt < 2)) {
3468		result = -EINVAL;
3469		goto out;
3470	}
3471
3472	psdo = pgo + PART_PAGE_FIXED_LENGTH;
3473	/* The second condition is for HP DDS which use only one partition size
3474	 * descriptor
3475	 */
3476	if (target_partition > 0 &&
3477	    (psd_cnt > bp[pgo + PP_OFF_MAX_ADD_PARTS] ||
3478	     bp[pgo + PP_OFF_MAX_ADD_PARTS] != 1)) {
3479		bp[psdo] = bp[psdo + 1] = 0xff;  /* Rest to partition 0 */
3480		psdo += 2;
3481	}
3482	memset(bp + psdo, 0, bp[pgo + PP_OFF_NBR_ADD_PARTS] * 2);
3483
3484	DEBC_printk(STp, "psd_cnt %d, max.parts %d, nbr_parts %d\n",
3485		    psd_cnt, bp[pgo + PP_OFF_MAX_ADD_PARTS],
3486		    bp[pgo + PP_OFF_NBR_ADD_PARTS]);
3487
3488	if (size == 0) {
3489		bp[pgo + PP_OFF_NBR_ADD_PARTS] = 0;
3490		if (psd_cnt <= bp[pgo + PP_OFF_MAX_ADD_PARTS])
3491		    bp[pgo + MP_OFF_PAGE_LENGTH] = 6;
3492		DEBC_printk(STp, "Formatting tape with one partition.\n");
3493	} else {
3494		bp[psdo] = (size >> 8) & 0xff;
3495		bp[psdo + 1] = size & 0xff;
3496		if (target_partition == 0)
3497			bp[psdo + 2] = bp[psdo + 3] = 0xff;
3498		bp[pgo + 3] = 1;
3499		if (bp[pgo + MP_OFF_PAGE_LENGTH] < 8)
3500		    bp[pgo + MP_OFF_PAGE_LENGTH] = 8;
3501		DEBC_printk(STp,
3502			    "Formatting tape with two partitions (%i = %d MB).\n",
3503			    target_partition, units > 0 ? size * 1000 : size);
3504	}
3505	bp[pgo + PP_OFF_PART_UNITS] = 0;
3506	bp[pgo + PP_OFF_RESERVED] = 0;
3507	if (size != 1 || units != 0) {
3508		bp[pgo + PP_OFF_FLAGS] = PP_BIT_IDP | psum |
3509			(bp[pgo + PP_OFF_FLAGS] & 0x07);
3510		bp[pgo + PP_OFF_PART_UNITS] = units;
3511	} else
3512		bp[pgo + PP_OFF_FLAGS] = PP_BIT_FDP |
3513			(bp[pgo + PP_OFF_FLAGS] & 0x1f);
3514	bp[pgo + MP_OFF_PAGE_LENGTH] = 6 + psd_cnt * 2;
3515
3516	result = write_mode_page(STp, PART_PAGE, 1);
3517
3518	if (!result && needs_format)
3519		result = format_medium(STp, 1);
3520
3521	if (result) {
3522		st_printk(KERN_INFO, STp, "Partitioning of tape failed.\n");
3523		result = (-EIO);
3524	}
3525
3526out:
3527	return result;
3528}
3529
3530/*
3531 * Handles any extra state needed for ioctls which are not st-specific.
3532 * Called with the scsi_tape lock held, released before return
3533 */
3534static long st_common_ioctl(struct scsi_tape *STp, struct st_modedef *STm,
3535			    struct file *file, unsigned int cmd_in,
3536			    unsigned long arg)
3537{
3538	int i, retval = 0;
3539
3540	if (!STm->defined) {
3541		retval = -ENXIO;
3542		goto out;
3543	}
3544
3545	switch (cmd_in) {
3546	case SCSI_IOCTL_GET_IDLUN:
3547	case SCSI_IOCTL_GET_BUS_NUMBER:
3548	case SCSI_IOCTL_GET_PCI:
3549		break;
3550	case SG_IO:
3551	case SCSI_IOCTL_SEND_COMMAND:
3552	case CDROM_SEND_PACKET:
3553		if (!capable(CAP_SYS_RAWIO)) {
3554			retval = -EPERM;
3555			goto out;
3556		}
3557		fallthrough;
3558	default:
3559		if ((i = flush_buffer(STp, 0)) < 0) {
3560			retval = i;
3561			goto out;
3562		} else { /* flush_buffer succeeds */
3563			if (STp->can_partitions) {
3564				i = switch_partition(STp);
3565				if (i < 0) {
3566					retval = i;
3567					goto out;
3568				}
3569			}
3570		}
3571	}
3572	mutex_unlock(&STp->lock);
3573
3574	retval = scsi_ioctl(STp->device, file->f_mode & FMODE_WRITE,
3575			    cmd_in, (void __user *)arg);
3576	if (!retval && cmd_in == SCSI_IOCTL_STOP_UNIT) {
3577		/* unload */
3578		STp->rew_at_close = 0;
3579		STp->ready = ST_NO_TAPE;
3580	}
3581
3582	return retval;
3583out:
3584	mutex_unlock(&STp->lock);
3585	return retval;
3586}
3587
3588/* The ioctl command */
3589static long st_ioctl(struct file *file, unsigned int cmd_in, unsigned long arg)
3590{
3591	void __user *p = (void __user *)arg;
3592	int i, cmd_nr, cmd_type, bt;
3593	int retval = 0;
3594	unsigned int blk;
3595	bool cmd_mtiocget;
3596	struct scsi_tape *STp = file->private_data;
3597	struct st_modedef *STm;
3598	struct st_partstat *STps;
3599
3600	if (mutex_lock_interruptible(&STp->lock))
3601		return -ERESTARTSYS;
3602
3603	DEB(
3604	if (debugging && !STp->in_use) {
3605		st_printk(ST_DEB_MSG, STp, "Incorrect device.\n");
3606		retval = (-EIO);
3607		goto out;
3608	} ) /* end DEB */
3609
3610	STm = &(STp->modes[STp->current_mode]);
3611	STps = &(STp->ps[STp->partition]);
3612
3613	/*
3614	 * If we are in the middle of error recovery, don't let anyone
3615	 * else try and use this device.  Also, if error recovery fails, it
3616	 * may try and take the device offline, in which case all further
3617	 * access to the device is prohibited.
3618	 */
3619	retval = scsi_ioctl_block_when_processing_errors(STp->device, cmd_in,
3620			file->f_flags & O_NDELAY);
3621	if (retval)
3622		goto out;
3623
3624	switch (cmd_in) {
3625	case MTIOCPOS:
3626	case MTIOCGET:
3627	case MTIOCTOP:
3628		break;
3629	default:
3630		return st_common_ioctl(STp, STm, file, cmd_in, arg);
3631	}
3632
3633	cmd_type = _IOC_TYPE(cmd_in);
3634	cmd_nr = _IOC_NR(cmd_in);
3635
3636	if (cmd_type == _IOC_TYPE(MTIOCTOP) && cmd_nr == _IOC_NR(MTIOCTOP)) {
3637		struct mtop mtc;
3638
3639		if (_IOC_SIZE(cmd_in) != sizeof(mtc)) {
3640			retval = (-EINVAL);
3641			goto out;
3642		}
3643
3644		i = copy_from_user(&mtc, p, sizeof(struct mtop));
3645		if (i) {
3646			retval = (-EFAULT);
3647			goto out;
3648		}
3649
3650		if (mtc.mt_op == MTSETDRVBUFFER && !capable(CAP_SYS_ADMIN)) {
3651			st_printk(KERN_WARNING, STp,
3652				  "MTSETDRVBUFFER only allowed for root.\n");
3653			retval = (-EPERM);
3654			goto out;
3655		}
3656		if (!STm->defined &&
3657		    (mtc.mt_op != MTSETDRVBUFFER &&
3658		     (mtc.mt_count & MT_ST_OPTIONS) == 0)) {
3659			retval = (-ENXIO);
3660			goto out;
3661		}
3662
3663		if (!STp->pos_unknown) {
3664
3665			if (STps->eof == ST_FM_HIT) {
3666				if (mtc.mt_op == MTFSF || mtc.mt_op == MTFSFM ||
3667                                    mtc.mt_op == MTEOM) {
3668					mtc.mt_count -= 1;
3669					if (STps->drv_file >= 0)
3670						STps->drv_file += 1;
3671				} else if (mtc.mt_op == MTBSF || mtc.mt_op == MTBSFM) {
3672					mtc.mt_count += 1;
3673					if (STps->drv_file >= 0)
3674						STps->drv_file += 1;
3675				}
3676			}
3677
3678			if (mtc.mt_op == MTSEEK) {
3679				/* Old position must be restored if partition will be
3680                                   changed */
3681				i = !STp->can_partitions ||
3682				    (STp->new_partition != STp->partition);
3683			} else {
3684				i = mtc.mt_op == MTREW || mtc.mt_op == MTOFFL ||
3685				    mtc.mt_op == MTRETEN || mtc.mt_op == MTEOM ||
3686				    mtc.mt_op == MTLOCK || mtc.mt_op == MTLOAD ||
3687				    mtc.mt_op == MTFSF || mtc.mt_op == MTFSFM ||
3688				    mtc.mt_op == MTBSF || mtc.mt_op == MTBSFM ||
3689				    mtc.mt_op == MTCOMPRESSION;
3690			}
3691			i = flush_buffer(STp, i);
3692			if (i < 0) {
3693				retval = i;
3694				goto out;
3695			}
3696			if (STps->rw == ST_WRITING &&
3697			    (mtc.mt_op == MTREW || mtc.mt_op == MTOFFL ||
3698			     mtc.mt_op == MTSEEK ||
3699			     mtc.mt_op == MTBSF || mtc.mt_op == MTBSFM)) {
3700				i = st_int_ioctl(STp, MTWEOF, 1);
3701				if (i < 0) {
3702					retval = i;
3703					goto out;
3704				}
3705				if (mtc.mt_op == MTBSF || mtc.mt_op == MTBSFM)
3706					mtc.mt_count++;
3707				STps->rw = ST_IDLE;
3708			     }
3709
3710		} else {
3711			/*
3712			 * If there was a bus reset, block further access
3713			 * to this device.  If the user wants to rewind the tape,
3714			 * then reset the flag and allow access again.
3715			 */
3716			if (mtc.mt_op != MTREW &&
3717			    mtc.mt_op != MTOFFL &&
3718			    mtc.mt_op != MTLOAD &&
3719			    mtc.mt_op != MTRETEN &&
3720			    mtc.mt_op != MTERASE &&
3721			    mtc.mt_op != MTSEEK &&
3722			    mtc.mt_op != MTEOM) {
3723				retval = (-EIO);
3724				goto out;
3725			}
3726			reset_state(STp); /* Clears pos_unknown */
3727
3728			/* Fix the device settings after reset, ignore errors */
3729			if (mtc.mt_op == MTREW || mtc.mt_op == MTSEEK ||
3730				mtc.mt_op == MTEOM) {
3731				if (STp->can_partitions) {
3732					/* STp->new_partition contains the
3733					 *  latest partition set
3734					 */
3735					STp->partition = 0;
3736					switch_partition(STp);
3737				}
3738				if (STp->density_changed)
3739					st_int_ioctl(STp, MTSETDENSITY, STp->changed_density);
3740				if (STp->blksize_changed)
3741					st_int_ioctl(STp, MTSETBLK, STp->changed_blksize);
3742			}
3743		}
3744
3745		if (mtc.mt_op != MTNOP && mtc.mt_op != MTSETBLK &&
3746		    mtc.mt_op != MTSETDENSITY && mtc.mt_op != MTWSM &&
3747		    mtc.mt_op != MTSETDRVBUFFER && mtc.mt_op != MTSETPART)
3748			STps->rw = ST_IDLE;	/* Prevent automatic WEOF and fsf */
3749
3750		if (mtc.mt_op == MTOFFL && STp->door_locked != ST_UNLOCKED)
3751			do_door_lock(STp, 0);	/* Ignore result! */
3752
3753		if (mtc.mt_op == MTSETDRVBUFFER &&
3754		    (mtc.mt_count & MT_ST_OPTIONS) != 0) {
3755			retval = st_set_options(STp, mtc.mt_count);
3756			goto out;
3757		}
3758
3759		if (mtc.mt_op == MTSETPART) {
3760			if (!STp->can_partitions ||
3761			    mtc.mt_count < 0 || mtc.mt_count >= ST_NBR_PARTITIONS) {
3762				retval = (-EINVAL);
3763				goto out;
3764			}
3765			if (mtc.mt_count >= STp->nbr_partitions &&
3766			    (STp->nbr_partitions = nbr_partitions(STp)) < 0) {
3767				retval = (-EIO);
3768				goto out;
3769			}
3770			if (mtc.mt_count >= STp->nbr_partitions) {
3771				retval = (-EINVAL);
3772				goto out;
3773			}
3774			STp->new_partition = mtc.mt_count;
3775			retval = 0;
3776			goto out;
3777		}
3778
3779		if (mtc.mt_op == MTMKPART) {
3780			if (!STp->can_partitions) {
3781				retval = (-EINVAL);
3782				goto out;
3783			}
3784			i = do_load_unload(STp, file, 1);
3785			if (i < 0) {
3786				retval = i;
3787				goto out;
3788			}
3789			i = partition_tape(STp, mtc.mt_count);
3790			if (i < 0) {
3791				retval = i;
3792				goto out;
3793			}
3794			for (i = 0; i < ST_NBR_PARTITIONS; i++) {
3795				STp->ps[i].rw = ST_IDLE;
3796				STp->ps[i].at_sm = 0;
3797				STp->ps[i].last_block_valid = 0;
3798			}
3799			STp->partition = STp->new_partition = 0;
3800			STp->nbr_partitions = mtc.mt_count != 0 ? 2 : 1;
3801			STps->drv_block = STps->drv_file = 0;
3802			retval = 0;
3803			goto out;
3804		}
3805
3806		if (mtc.mt_op == MTSEEK) {
3807			i = set_location(STp, mtc.mt_count, STp->new_partition, 0);
3808			if (!STp->can_partitions)
3809				STp->ps[0].rw = ST_IDLE;
3810			retval = i;
3811			goto out;
3812		}
3813
3814		if (mtc.mt_op == MTUNLOAD || mtc.mt_op == MTOFFL) {
3815			retval = do_load_unload(STp, file, 0);
3816			goto out;
3817		}
3818
3819		if (mtc.mt_op == MTLOAD) {
3820			retval = do_load_unload(STp, file, max(1, mtc.mt_count));
3821			goto out;
3822		}
3823
3824		if (mtc.mt_op == MTLOCK || mtc.mt_op == MTUNLOCK) {
3825			retval = do_door_lock(STp, (mtc.mt_op == MTLOCK));
3826			goto out;
3827		}
3828
3829		if (STp->can_partitions && STp->ready == ST_READY &&
3830		    (i = switch_partition(STp)) < 0) {
3831			retval = i;
3832			goto out;
3833		}
3834
3835		if (mtc.mt_op == MTCOMPRESSION)
3836			retval = st_compression(STp, (mtc.mt_count & 1));
3837		else
3838			retval = st_int_ioctl(STp, mtc.mt_op, mtc.mt_count);
3839		goto out;
3840	}
3841	if (!STm->defined) {
3842		retval = (-ENXIO);
3843		goto out;
3844	}
3845
3846	cmd_mtiocget = cmd_type == _IOC_TYPE(MTIOCGET) && cmd_nr == _IOC_NR(MTIOCGET);
3847
3848	if ((i = flush_buffer(STp, 0)) < 0) {
3849		if (cmd_mtiocget && STp->pos_unknown) {
3850			/* flush fails -> modify status accordingly */
3851			reset_state(STp);
3852			STp->pos_unknown = 1;
3853		} else { /* return error */
3854			retval = i;
3855			goto out;
3856		}
3857	} else { /* flush_buffer succeeds */
3858		if (STp->can_partitions) {
3859			i = switch_partition(STp);
3860			if (i < 0) {
3861				retval = i;
3862				goto out;
3863			}
3864		}
3865	}
3866
3867	if (cmd_mtiocget) {
3868		struct mtget mt_status;
3869
3870		if (_IOC_SIZE(cmd_in) != sizeof(struct mtget)) {
3871			 retval = (-EINVAL);
3872			 goto out;
3873		}
3874
3875		mt_status.mt_type = STp->tape_type;
3876		mt_status.mt_dsreg =
3877		    ((STp->block_size << MT_ST_BLKSIZE_SHIFT) & MT_ST_BLKSIZE_MASK) |
3878		    ((STp->density << MT_ST_DENSITY_SHIFT) & MT_ST_DENSITY_MASK);
3879		mt_status.mt_blkno = STps->drv_block;
3880		mt_status.mt_fileno = STps->drv_file;
3881		if (STp->block_size != 0 && mt_status.mt_blkno >= 0) {
3882			if (STps->rw == ST_WRITING)
3883				mt_status.mt_blkno +=
3884				    (STp->buffer)->buffer_bytes / STp->block_size;
3885			else if (STps->rw == ST_READING)
3886				mt_status.mt_blkno -=
3887                                        ((STp->buffer)->buffer_bytes +
3888                                         STp->block_size - 1) / STp->block_size;
3889		}
3890
3891		mt_status.mt_gstat = 0;
3892		if (STp->drv_write_prot)
3893			mt_status.mt_gstat |= GMT_WR_PROT(0xffffffff);
3894		if (mt_status.mt_blkno == 0) {
3895			if (mt_status.mt_fileno == 0)
3896				mt_status.mt_gstat |= GMT_BOT(0xffffffff);
3897			else
3898				mt_status.mt_gstat |= GMT_EOF(0xffffffff);
3899		}
3900		mt_status.mt_erreg = (STp->recover_reg << MT_ST_SOFTERR_SHIFT);
3901		mt_status.mt_resid = STp->partition;
3902		if (STps->eof == ST_EOM_OK || STps->eof == ST_EOM_ERROR)
3903			mt_status.mt_gstat |= GMT_EOT(0xffffffff);
3904		else if (STps->eof >= ST_EOM_OK)
3905			mt_status.mt_gstat |= GMT_EOD(0xffffffff);
3906		if (STp->density == 1)
3907			mt_status.mt_gstat |= GMT_D_800(0xffffffff);
3908		else if (STp->density == 2)
3909			mt_status.mt_gstat |= GMT_D_1600(0xffffffff);
3910		else if (STp->density == 3)
3911			mt_status.mt_gstat |= GMT_D_6250(0xffffffff);
3912		if (STp->ready == ST_READY)
3913			mt_status.mt_gstat |= GMT_ONLINE(0xffffffff);
3914		if (STp->ready == ST_NO_TAPE)
3915			mt_status.mt_gstat |= GMT_DR_OPEN(0xffffffff);
3916		if (STps->at_sm)
3917			mt_status.mt_gstat |= GMT_SM(0xffffffff);
3918		if (STm->do_async_writes ||
3919                    (STm->do_buffer_writes && STp->block_size != 0) ||
3920		    STp->drv_buffer != 0)
3921			mt_status.mt_gstat |= GMT_IM_REP_EN(0xffffffff);
3922		if (STp->cleaning_req)
3923			mt_status.mt_gstat |= GMT_CLN(0xffffffff);
3924
3925		retval = put_user_mtget(p, &mt_status);
3926		if (retval)
3927			goto out;
3928
3929		STp->recover_reg = 0;		/* Clear after read */
3930		goto out;
3931	}			/* End of MTIOCGET */
3932	if (cmd_type == _IOC_TYPE(MTIOCPOS) && cmd_nr == _IOC_NR(MTIOCPOS)) {
3933		struct mtpos mt_pos;
3934		if (_IOC_SIZE(cmd_in) != sizeof(struct mtpos)) {
3935			 retval = (-EINVAL);
3936			 goto out;
3937		}
3938		if ((i = get_location(STp, &blk, &bt, 0)) < 0) {
3939			retval = i;
3940			goto out;
3941		}
3942		mt_pos.mt_blkno = blk;
3943		retval = put_user_mtpos(p, &mt_pos);
3944	}
3945 out:
3946	mutex_unlock(&STp->lock);
3947	return retval;
3948}
3949
3950#ifdef CONFIG_COMPAT
3951static long st_compat_ioctl(struct file *file, unsigned int cmd_in, unsigned long arg)
3952{
3953	/* argument conversion is handled using put_user_mtpos/put_user_mtget */
3954	switch (cmd_in) {
3955	case MTIOCPOS32:
3956		cmd_in = MTIOCPOS;
3957		break;
3958	case MTIOCGET32:
3959		cmd_in = MTIOCGET;
3960		break;
3961	}
3962
3963	return st_ioctl(file, cmd_in, arg);
3964}
3965#endif
3966
3967
3968
3969/* Try to allocate a new tape buffer. Calling function must not hold
3970   dev_arr_lock. */
3971static struct st_buffer *new_tape_buffer(int max_sg)
3972{
3973	struct st_buffer *tb;
3974
3975	tb = kzalloc(sizeof(struct st_buffer), GFP_KERNEL);
3976	if (!tb) {
3977		printk(KERN_NOTICE "st: Can't allocate new tape buffer.\n");
3978		return NULL;
3979	}
3980	tb->frp_segs = 0;
3981	tb->use_sg = max_sg;
3982	tb->buffer_size = 0;
3983
3984	tb->reserved_pages = kcalloc(max_sg, sizeof(struct page *),
3985				     GFP_KERNEL);
3986	if (!tb->reserved_pages) {
3987		kfree(tb);
3988		return NULL;
3989	}
3990
3991	return tb;
3992}
3993
3994
3995/* Try to allocate enough space in the tape buffer */
3996#define ST_MAX_ORDER 6
3997
3998static int enlarge_buffer(struct st_buffer * STbuffer, int new_size)
3999{
4000	int segs, max_segs, b_size, order, got;
4001	gfp_t priority;
4002
4003	if (new_size <= STbuffer->buffer_size)
4004		return 1;
4005
4006	if (STbuffer->buffer_size <= PAGE_SIZE)
4007		normalize_buffer(STbuffer);  /* Avoid extra segment */
4008
4009	max_segs = STbuffer->use_sg;
4010
4011	priority = GFP_KERNEL | __GFP_NOWARN;
4012
4013	if (STbuffer->cleared)
4014		priority |= __GFP_ZERO;
4015
4016	if (STbuffer->frp_segs) {
4017		order = STbuffer->reserved_page_order;
4018		b_size = PAGE_SIZE << order;
4019	} else {
4020		for (b_size = PAGE_SIZE, order = 0;
4021		     order < ST_MAX_ORDER &&
4022			     max_segs * (PAGE_SIZE << order) < new_size;
4023		     order++, b_size *= 2)
4024			;  /* empty */
4025		STbuffer->reserved_page_order = order;
4026	}
4027	if (max_segs * (PAGE_SIZE << order) < new_size) {
4028		if (order == ST_MAX_ORDER)
4029			return 0;
4030		normalize_buffer(STbuffer);
4031		return enlarge_buffer(STbuffer, new_size);
4032	}
4033
4034	for (segs = STbuffer->frp_segs, got = STbuffer->buffer_size;
4035	     segs < max_segs && got < new_size;) {
4036		struct page *page;
4037
4038		page = alloc_pages(priority, order);
4039		if (!page) {
4040			DEB(STbuffer->buffer_size = got);
4041			normalize_buffer(STbuffer);
4042			return 0;
4043		}
4044
4045		STbuffer->frp_segs += 1;
4046		got += b_size;
4047		STbuffer->buffer_size = got;
4048		STbuffer->reserved_pages[segs] = page;
4049		segs++;
4050	}
4051	STbuffer->b_data = page_address(STbuffer->reserved_pages[0]);
4052
4053	return 1;
4054}
4055
4056
4057/* Make sure that no data from previous user is in the internal buffer */
4058static void clear_buffer(struct st_buffer * st_bp)
4059{
4060	int i;
4061
4062	for (i=0; i < st_bp->frp_segs; i++)
4063		memset(page_address(st_bp->reserved_pages[i]), 0,
4064		       PAGE_SIZE << st_bp->reserved_page_order);
4065	st_bp->cleared = 1;
4066}
4067
4068
4069/* Release the extra buffer */
4070static void normalize_buffer(struct st_buffer * STbuffer)
4071{
4072	int i, order = STbuffer->reserved_page_order;
4073
4074	for (i = 0; i < STbuffer->frp_segs; i++) {
4075		__free_pages(STbuffer->reserved_pages[i], order);
4076		STbuffer->buffer_size -= (PAGE_SIZE << order);
4077	}
4078	STbuffer->frp_segs = 0;
4079	STbuffer->sg_segs = 0;
4080	STbuffer->reserved_page_order = 0;
4081	STbuffer->map_data.offset = 0;
4082}
4083
4084
4085/* Move data from the user buffer to the tape buffer. Returns zero (success) or
4086   negative error code. */
4087static int append_to_buffer(const char __user *ubp, struct st_buffer * st_bp, int do_count)
4088{
4089	int i, cnt, res, offset;
4090	int length = PAGE_SIZE << st_bp->reserved_page_order;
4091
4092	for (i = 0, offset = st_bp->buffer_bytes;
4093	     i < st_bp->frp_segs && offset >= length; i++)
4094		offset -= length;
4095	if (i == st_bp->frp_segs) {	/* Should never happen */
4096		printk(KERN_WARNING "st: append_to_buffer offset overflow.\n");
4097		return (-EIO);
4098	}
4099	for (; i < st_bp->frp_segs && do_count > 0; i++) {
4100		struct page *page = st_bp->reserved_pages[i];
4101		cnt = length - offset < do_count ? length - offset : do_count;
4102		res = copy_from_user(page_address(page) + offset, ubp, cnt);
4103		if (res)
4104			return (-EFAULT);
4105		do_count -= cnt;
4106		st_bp->buffer_bytes += cnt;
4107		ubp += cnt;
4108		offset = 0;
4109	}
4110	if (do_count) /* Should never happen */
4111		return (-EIO);
4112
4113	return 0;
4114}
4115
4116
4117/* Move data from the tape buffer to the user buffer. Returns zero (success) or
4118   negative error code. */
4119static int from_buffer(struct st_buffer * st_bp, char __user *ubp, int do_count)
4120{
4121	int i, cnt, res, offset;
4122	int length = PAGE_SIZE << st_bp->reserved_page_order;
4123
4124	for (i = 0, offset = st_bp->read_pointer;
4125	     i < st_bp->frp_segs && offset >= length; i++)
4126		offset -= length;
4127	if (i == st_bp->frp_segs) {	/* Should never happen */
4128		printk(KERN_WARNING "st: from_buffer offset overflow.\n");
4129		return (-EIO);
4130	}
4131	for (; i < st_bp->frp_segs && do_count > 0; i++) {
4132		struct page *page = st_bp->reserved_pages[i];
4133		cnt = length - offset < do_count ? length - offset : do_count;
4134		res = copy_to_user(ubp, page_address(page) + offset, cnt);
4135		if (res)
4136			return (-EFAULT);
4137		do_count -= cnt;
4138		st_bp->buffer_bytes -= cnt;
4139		st_bp->read_pointer += cnt;
4140		ubp += cnt;
4141		offset = 0;
4142	}
4143	if (do_count) /* Should never happen */
4144		return (-EIO);
4145
4146	return 0;
4147}
4148
4149
4150/* Move data towards start of buffer */
4151static void move_buffer_data(struct st_buffer * st_bp, int offset)
4152{
4153	int src_seg, dst_seg, src_offset = 0, dst_offset;
4154	int count, total;
4155	int length = PAGE_SIZE << st_bp->reserved_page_order;
4156
4157	if (offset == 0)
4158		return;
4159
4160	total=st_bp->buffer_bytes - offset;
4161	for (src_seg=0; src_seg < st_bp->frp_segs; src_seg++) {
4162		src_offset = offset;
4163		if (src_offset < length)
4164			break;
4165		offset -= length;
4166	}
4167
4168	st_bp->buffer_bytes = st_bp->read_pointer = total;
4169	for (dst_seg=dst_offset=0; total > 0; ) {
4170		struct page *dpage = st_bp->reserved_pages[dst_seg];
4171		struct page *spage = st_bp->reserved_pages[src_seg];
4172
4173		count = min(length - dst_offset, length - src_offset);
4174		memmove(page_address(dpage) + dst_offset,
4175			page_address(spage) + src_offset, count);
4176		src_offset += count;
4177		if (src_offset >= length) {
4178			src_seg++;
4179			src_offset = 0;
4180		}
4181		dst_offset += count;
4182		if (dst_offset >= length) {
4183			dst_seg++;
4184			dst_offset = 0;
4185		}
4186		total -= count;
4187	}
4188}
4189
4190/* Validate the options from command line or module parameters */
4191static void validate_options(void)
4192{
4193	if (buffer_kbs > 0)
4194		st_fixed_buffer_size = buffer_kbs * ST_KILOBYTE;
4195	if (max_sg_segs >= ST_FIRST_SG)
4196		st_max_sg_segs = max_sg_segs;
4197}
4198
4199#ifndef MODULE
4200/* Set the boot options. Syntax is defined in Documenation/scsi/st.txt.
4201 */
4202static int __init st_setup(char *str)
4203{
4204	int i, len, ints[ARRAY_SIZE(parms) + 1];
4205	char *stp;
4206
4207	stp = get_options(str, ARRAY_SIZE(ints), ints);
4208
4209	if (ints[0] > 0) {
4210		for (i = 0; i < ints[0] && i < ARRAY_SIZE(parms); i++)
4211			if (parms[i].val)
4212				*parms[i].val = ints[i + 1];
4213	} else {
4214		while (stp != NULL) {
4215			for (i = 0; i < ARRAY_SIZE(parms); i++) {
4216				len = strlen(parms[i].name);
4217				if (!strncmp(stp, parms[i].name, len) &&
4218				    (*(stp + len) == ':' || *(stp + len) == '=')) {
4219					if (parms[i].val)
4220						*parms[i].val =
4221							simple_strtoul(stp + len + 1, NULL, 0);
4222					else
4223						printk(KERN_WARNING "st: Obsolete parameter %s\n",
4224						       parms[i].name);
4225					break;
4226				}
4227			}
4228			if (i >= ARRAY_SIZE(parms))
4229				 printk(KERN_WARNING "st: invalid parameter in '%s'\n",
4230					stp);
4231			stp = strchr(stp, ',');
4232			if (stp)
4233				stp++;
4234		}
4235	}
4236
4237	validate_options();
4238
4239	return 1;
4240}
4241
4242__setup("st=", st_setup);
4243
4244#endif
4245
4246static const struct file_operations st_fops =
4247{
4248	.owner =	THIS_MODULE,
4249	.read =		st_read,
4250	.write =	st_write,
4251	.unlocked_ioctl = st_ioctl,
4252#ifdef CONFIG_COMPAT
4253	.compat_ioctl = st_compat_ioctl,
4254#endif
4255	.open =		st_open,
4256	.flush =	st_flush,
4257	.release =	st_release,
4258	.llseek =	noop_llseek,
4259};
4260
4261static int create_one_cdev(struct scsi_tape *tape, int mode, int rew)
4262{
4263	int i, error;
4264	dev_t cdev_devno;
4265	struct cdev *cdev;
4266	struct device *dev;
4267	struct st_modedef *STm = &(tape->modes[mode]);
4268	char name[10];
4269	int dev_num = tape->index;
4270
4271	cdev_devno = MKDEV(SCSI_TAPE_MAJOR, TAPE_MINOR(dev_num, mode, rew));
4272
4273	cdev = cdev_alloc();
4274	if (!cdev) {
4275		pr_err("st%d: out of memory. Device not attached.\n", dev_num);
4276		error = -ENOMEM;
4277		goto out;
4278	}
4279	cdev->owner = THIS_MODULE;
4280	cdev->ops = &st_fops;
4281	STm->cdevs[rew] = cdev;
4282
4283	error = cdev_add(cdev, cdev_devno, 1);
4284	if (error) {
4285		pr_err("st%d: Can't add %s-rewind mode %d\n", dev_num,
4286		       rew ? "non" : "auto", mode);
4287		pr_err("st%d: Device not attached.\n", dev_num);
4288		goto out_free;
4289	}
4290
4291	i = mode << (4 - ST_NBR_MODE_BITS);
4292	snprintf(name, 10, "%s%s%s", rew ? "n" : "",
4293		 tape->name, st_formats[i]);
4294
4295	dev = device_create(&st_sysfs_class, &tape->device->sdev_gendev,
4296			    cdev_devno, &tape->modes[mode], "%s", name);
4297	if (IS_ERR(dev)) {
4298		pr_err("st%d: device_create failed\n", dev_num);
4299		error = PTR_ERR(dev);
4300		goto out_free;
4301	}
4302
4303	STm->devs[rew] = dev;
4304
4305	return 0;
4306out_free:
4307	cdev_del(STm->cdevs[rew]);
4308out:
4309	STm->cdevs[rew] = NULL;
4310	STm->devs[rew] = NULL;
4311	return error;
4312}
4313
4314static int create_cdevs(struct scsi_tape *tape)
4315{
4316	int mode, error;
4317	for (mode = 0; mode < ST_NBR_MODES; ++mode) {
4318		error = create_one_cdev(tape, mode, 0);
4319		if (error)
4320			return error;
4321		error = create_one_cdev(tape, mode, 1);
4322		if (error)
4323			return error;
4324	}
4325
4326	return sysfs_create_link(&tape->device->sdev_gendev.kobj,
4327				 &tape->modes[0].devs[0]->kobj, "tape");
4328}
4329
4330static void remove_cdevs(struct scsi_tape *tape)
4331{
4332	int mode, rew;
4333	sysfs_remove_link(&tape->device->sdev_gendev.kobj, "tape");
4334	for (mode = 0; mode < ST_NBR_MODES; mode++) {
4335		struct st_modedef *STm = &(tape->modes[mode]);
4336		for (rew = 0; rew < 2; rew++) {
4337			if (STm->cdevs[rew])
4338				cdev_del(STm->cdevs[rew]);
4339			if (STm->devs[rew])
4340				device_unregister(STm->devs[rew]);
4341		}
4342	}
4343}
4344
4345static int st_probe(struct device *dev)
4346{
4347	struct scsi_device *SDp = to_scsi_device(dev);
4348	struct scsi_tape *tpnt = NULL;
4349	struct st_modedef *STm;
4350	struct st_partstat *STps;
4351	struct st_buffer *buffer;
4352	int i, error;
4353
4354	if (SDp->type != TYPE_TAPE)
4355		return -ENODEV;
4356	if (st_incompatible(SDp)) {
4357		sdev_printk(KERN_INFO, SDp,
4358			    "OnStream tapes are no longer supported;\n");
4359		sdev_printk(KERN_INFO, SDp,
4360			    "please mail to linux-scsi@vger.kernel.org.\n");
4361		return -ENODEV;
4362	}
4363
4364	scsi_autopm_get_device(SDp);
4365	i = queue_max_segments(SDp->request_queue);
4366	if (st_max_sg_segs < i)
4367		i = st_max_sg_segs;
4368	buffer = new_tape_buffer(i);
4369	if (buffer == NULL) {
4370		sdev_printk(KERN_ERR, SDp,
4371			    "st: Can't allocate new tape buffer. "
4372			    "Device not attached.\n");
4373		goto out;
4374	}
4375
4376	tpnt = kzalloc(sizeof(struct scsi_tape), GFP_KERNEL);
4377	if (tpnt == NULL) {
4378		sdev_printk(KERN_ERR, SDp,
4379			    "st: Can't allocate device descriptor.\n");
4380		goto out_buffer_free;
4381	}
4382	kref_init(&tpnt->kref);
4383
4384	tpnt->device = SDp;
4385	if (SDp->scsi_level <= 2)
4386		tpnt->tape_type = MT_ISSCSI1;
4387	else
4388		tpnt->tape_type = MT_ISSCSI2;
4389
4390	tpnt->buffer = buffer;
4391	tpnt->buffer->last_SRpnt = NULL;
4392
4393	tpnt->inited = 0;
4394	tpnt->dirty = 0;
4395	tpnt->in_use = 0;
4396	tpnt->drv_buffer = 1;	/* Try buffering if no mode sense */
4397	tpnt->use_pf = (SDp->scsi_level >= SCSI_2);
4398	tpnt->density = 0;
4399	tpnt->do_auto_lock = ST_AUTO_LOCK;
4400	tpnt->can_bsr = (SDp->scsi_level > 2 ? 1 : ST_IN_FILE_POS); /* BSR mandatory in SCSI3 */
4401	tpnt->can_partitions = 0;
4402	tpnt->two_fm = ST_TWO_FM;
4403	tpnt->fast_mteom = ST_FAST_MTEOM;
4404	tpnt->scsi2_logical = ST_SCSI2LOGICAL;
4405	tpnt->sili = ST_SILI;
4406	tpnt->immediate = ST_NOWAIT;
4407	tpnt->immediate_filemark = 0;
4408	tpnt->default_drvbuffer = 0xff;		/* No forced buffering */
4409	tpnt->partition = 0;
4410	tpnt->new_partition = 0;
4411	tpnt->nbr_partitions = 0;
4412	blk_queue_rq_timeout(tpnt->device->request_queue, ST_TIMEOUT);
4413	tpnt->long_timeout = ST_LONG_TIMEOUT;
4414	tpnt->try_dio = try_direct_io;
4415	tpnt->first_tur = 1;
4416
4417	for (i = 0; i < ST_NBR_MODES; i++) {
4418		STm = &(tpnt->modes[i]);
4419		STm->defined = 0;
4420		STm->sysv = ST_SYSV;
4421		STm->defaults_for_writes = 0;
4422		STm->do_async_writes = ST_ASYNC_WRITES;
4423		STm->do_buffer_writes = ST_BUFFER_WRITES;
4424		STm->do_read_ahead = ST_READ_AHEAD;
4425		STm->default_compression = ST_DONT_TOUCH;
4426		STm->default_blksize = (-1);	/* No forced size */
4427		STm->default_density = (-1);	/* No forced density */
4428		STm->tape = tpnt;
4429	}
4430
4431	for (i = 0; i < ST_NBR_PARTITIONS; i++) {
4432		STps = &(tpnt->ps[i]);
4433		STps->rw = ST_IDLE;
4434		STps->eof = ST_NOEOF;
4435		STps->at_sm = 0;
4436		STps->last_block_valid = 0;
4437		STps->drv_block = (-1);
4438		STps->drv_file = (-1);
4439	}
4440
4441	tpnt->current_mode = 0;
4442	tpnt->modes[0].defined = 1;
4443
4444	tpnt->density_changed = tpnt->compression_changed =
4445	    tpnt->blksize_changed = 0;
4446	mutex_init(&tpnt->lock);
4447
4448	idr_preload(GFP_KERNEL);
4449	spin_lock(&st_index_lock);
4450	error = idr_alloc(&st_index_idr, tpnt, 0, ST_MAX_TAPES + 1, GFP_NOWAIT);
4451	spin_unlock(&st_index_lock);
4452	idr_preload_end();
4453	if (error < 0) {
4454		pr_warn("st: idr allocation failed: %d\n", error);
4455		goto out_free_tape;
4456	}
4457	tpnt->index = error;
4458	sprintf(tpnt->name, "st%d", tpnt->index);
4459	tpnt->stats = kzalloc(sizeof(struct scsi_tape_stats), GFP_KERNEL);
4460	if (tpnt->stats == NULL) {
4461		sdev_printk(KERN_ERR, SDp,
4462			    "st: Can't allocate statistics.\n");
4463		goto out_idr_remove;
4464	}
4465
4466	tpnt->new_media_ctr = scsi_get_ua_new_media_ctr(SDp);
4467	tpnt->por_ctr = scsi_get_ua_por_ctr(SDp);
4468
4469	dev_set_drvdata(dev, tpnt);
4470
4471
4472	error = create_cdevs(tpnt);
4473	if (error)
4474		goto out_remove_devs;
4475	scsi_autopm_put_device(SDp);
4476
4477	sdev_printk(KERN_NOTICE, SDp,
4478		    "Attached scsi tape %s\n", tpnt->name);
4479	sdev_printk(KERN_INFO, SDp, "%s: try direct i/o: %s (alignment %d B)\n",
4480		    tpnt->name, tpnt->try_dio ? "yes" : "no",
4481		    queue_dma_alignment(SDp->request_queue) + 1);
4482
4483	return 0;
4484
4485out_remove_devs:
4486	remove_cdevs(tpnt);
4487	kfree(tpnt->stats);
4488out_idr_remove:
4489	spin_lock(&st_index_lock);
4490	idr_remove(&st_index_idr, tpnt->index);
4491	spin_unlock(&st_index_lock);
4492out_free_tape:
4493	kfree(tpnt);
4494out_buffer_free:
4495	kfree(buffer);
4496out:
4497	scsi_autopm_put_device(SDp);
4498	return -ENODEV;
4499};
4500
4501
4502static int st_remove(struct device *dev)
4503{
4504	struct scsi_tape *tpnt = dev_get_drvdata(dev);
4505	int index = tpnt->index;
4506
4507	scsi_autopm_get_device(to_scsi_device(dev));
4508	remove_cdevs(tpnt);
4509
4510	mutex_lock(&st_ref_mutex);
4511	kref_put(&tpnt->kref, scsi_tape_release);
4512	mutex_unlock(&st_ref_mutex);
4513	spin_lock(&st_index_lock);
4514	idr_remove(&st_index_idr, index);
4515	spin_unlock(&st_index_lock);
4516	return 0;
4517}
4518
4519/**
4520 *      scsi_tape_release - Called to free the Scsi_Tape structure
4521 *      @kref: pointer to embedded kref
4522 *
4523 *      st_ref_mutex must be held entering this routine.  Because it is
4524 *      called on last put, you should always use the scsi_tape_get()
4525 *      scsi_tape_put() helpers which manipulate the semaphore directly
4526 *      and never do a direct kref_put().
4527 **/
4528static void scsi_tape_release(struct kref *kref)
4529{
4530	struct scsi_tape *tpnt = to_scsi_tape(kref);
4531
4532	tpnt->device = NULL;
4533
4534	if (tpnt->buffer) {
4535		normalize_buffer(tpnt->buffer);
4536		kfree(tpnt->buffer->reserved_pages);
4537		kfree(tpnt->buffer);
4538	}
4539
4540	kfree(tpnt->stats);
4541	kfree(tpnt);
4542	return;
4543}
4544
4545static const struct class st_sysfs_class = {
4546	.name = "scsi_tape",
4547	.dev_groups = st_dev_groups,
4548};
4549
4550static int __init init_st(void)
4551{
4552	int err;
4553
4554	validate_options();
4555
4556	printk(KERN_INFO "st: Version %s, fixed bufsize %d, s/g segs %d\n",
4557		verstr, st_fixed_buffer_size, st_max_sg_segs);
4558
4559	debugging = (debug_flag > 0) ? debug_flag : NO_DEBUG;
4560	if (debugging) {
4561		printk(KERN_INFO "st: Debugging enabled debug_flag = %d\n",
4562			debugging);
4563	}
4564
4565	err = class_register(&st_sysfs_class);
4566	if (err) {
4567		pr_err("Unable register sysfs class for SCSI tapes\n");
4568		return err;
4569	}
4570
4571	err = register_chrdev_region(MKDEV(SCSI_TAPE_MAJOR, 0),
4572				     ST_MAX_TAPE_ENTRIES, "st");
4573	if (err) {
4574		printk(KERN_ERR "Unable to get major %d for SCSI tapes\n",
4575		       SCSI_TAPE_MAJOR);
4576		goto err_class;
4577	}
4578
4579	err = scsi_register_driver(&st_template.gendrv);
4580	if (err)
4581		goto err_chrdev;
4582
4583	return 0;
4584
4585err_chrdev:
4586	unregister_chrdev_region(MKDEV(SCSI_TAPE_MAJOR, 0),
4587				 ST_MAX_TAPE_ENTRIES);
4588err_class:
4589	class_unregister(&st_sysfs_class);
4590	return err;
4591}
4592
4593static void __exit exit_st(void)
4594{
4595	scsi_unregister_driver(&st_template.gendrv);
4596	unregister_chrdev_region(MKDEV(SCSI_TAPE_MAJOR, 0),
4597				 ST_MAX_TAPE_ENTRIES);
4598	class_unregister(&st_sysfs_class);
4599	idr_destroy(&st_index_idr);
4600	printk(KERN_INFO "st: Unloaded.\n");
4601}
4602
4603module_init(init_st);
4604module_exit(exit_st);
4605
4606
4607/* The sysfs driver interface. Read-only at the moment */
4608static ssize_t try_direct_io_show(struct device_driver *ddp, char *buf)
4609{
4610	return scnprintf(buf, PAGE_SIZE, "%d\n", try_direct_io);
4611}
4612static DRIVER_ATTR_RO(try_direct_io);
4613
4614static ssize_t fixed_buffer_size_show(struct device_driver *ddp, char *buf)
4615{
4616	return scnprintf(buf, PAGE_SIZE, "%d\n", st_fixed_buffer_size);
4617}
4618static DRIVER_ATTR_RO(fixed_buffer_size);
4619
4620static ssize_t max_sg_segs_show(struct device_driver *ddp, char *buf)
4621{
4622	return scnprintf(buf, PAGE_SIZE, "%d\n", st_max_sg_segs);
4623}
4624static DRIVER_ATTR_RO(max_sg_segs);
4625
4626static ssize_t version_show(struct device_driver *ddd, char *buf)
4627{
4628	return scnprintf(buf, PAGE_SIZE, "[%s]\n", verstr);
4629}
4630static DRIVER_ATTR_RO(version);
4631
4632#if DEBUG
4633static ssize_t debug_flag_store(struct device_driver *ddp,
4634	const char *buf, size_t count)
4635{
4636/* We only care what the first byte of the data is the rest is unused.
4637 * if it's a '1' we turn on debug and if it's a '0' we disable it. All
4638 * other values have -EINVAL returned if they are passed in.
4639 */
4640	if (count > 0) {
4641		if (buf[0] == '0') {
4642			debugging = NO_DEBUG;
4643			return count;
4644		} else if (buf[0] == '1') {
4645			debugging = 1;
4646			return count;
4647		}
4648	}
4649	return -EINVAL;
4650}
4651
4652static ssize_t debug_flag_show(struct device_driver *ddp, char *buf)
4653{
4654	return scnprintf(buf, PAGE_SIZE, "%d\n", debugging);
4655}
4656static DRIVER_ATTR_RW(debug_flag);
4657#endif
4658
4659static struct attribute *st_drv_attrs[] = {
4660	&driver_attr_try_direct_io.attr,
4661	&driver_attr_fixed_buffer_size.attr,
4662	&driver_attr_max_sg_segs.attr,
4663	&driver_attr_version.attr,
4664#if DEBUG
4665	&driver_attr_debug_flag.attr,
4666#endif
4667	NULL,
4668};
4669ATTRIBUTE_GROUPS(st_drv);
4670
4671/* The sysfs simple class interface */
4672static ssize_t
4673defined_show(struct device *dev, struct device_attribute *attr, char *buf)
4674{
4675	struct st_modedef *STm = dev_get_drvdata(dev);
4676	ssize_t l = 0;
4677
4678	l = snprintf(buf, PAGE_SIZE, "%d\n", STm->defined);
4679	return l;
4680}
4681static DEVICE_ATTR_RO(defined);
4682
4683static ssize_t
4684default_blksize_show(struct device *dev, struct device_attribute *attr,
4685		     char *buf)
4686{
4687	struct st_modedef *STm = dev_get_drvdata(dev);
4688	ssize_t l = 0;
4689
4690	l = snprintf(buf, PAGE_SIZE, "%d\n", STm->default_blksize);
4691	return l;
4692}
4693static DEVICE_ATTR_RO(default_blksize);
4694
4695static ssize_t
4696default_density_show(struct device *dev, struct device_attribute *attr,
4697		     char *buf)
4698{
4699	struct st_modedef *STm = dev_get_drvdata(dev);
4700	ssize_t l = 0;
4701	char *fmt;
4702
4703	fmt = STm->default_density >= 0 ? "0x%02x\n" : "%d\n";
4704	l = snprintf(buf, PAGE_SIZE, fmt, STm->default_density);
4705	return l;
4706}
4707static DEVICE_ATTR_RO(default_density);
4708
4709static ssize_t
4710default_compression_show(struct device *dev, struct device_attribute *attr,
4711			 char *buf)
4712{
4713	struct st_modedef *STm = dev_get_drvdata(dev);
4714	ssize_t l = 0;
4715
4716	l = snprintf(buf, PAGE_SIZE, "%d\n", STm->default_compression - 1);
4717	return l;
4718}
4719static DEVICE_ATTR_RO(default_compression);
4720
4721static ssize_t
4722options_show(struct device *dev, struct device_attribute *attr, char *buf)
4723{
4724	struct st_modedef *STm = dev_get_drvdata(dev);
4725	struct scsi_tape *STp = STm->tape;
4726	int options;
4727	ssize_t l = 0;
4728
4729	options = STm->do_buffer_writes ? MT_ST_BUFFER_WRITES : 0;
4730	options |= STm->do_async_writes ? MT_ST_ASYNC_WRITES : 0;
4731	options |= STm->do_read_ahead ? MT_ST_READ_AHEAD : 0;
4732	DEB( options |= debugging ? MT_ST_DEBUGGING : 0 );
4733	options |= STp->two_fm ? MT_ST_TWO_FM : 0;
4734	options |= STp->fast_mteom ? MT_ST_FAST_MTEOM : 0;
4735	options |= STm->defaults_for_writes ? MT_ST_DEF_WRITES : 0;
4736	options |= STp->can_bsr ? MT_ST_CAN_BSR : 0;
4737	options |= STp->omit_blklims ? MT_ST_NO_BLKLIMS : 0;
4738	options |= STp->can_partitions ? MT_ST_CAN_PARTITIONS : 0;
4739	options |= STp->scsi2_logical ? MT_ST_SCSI2LOGICAL : 0;
4740	options |= STm->sysv ? MT_ST_SYSV : 0;
4741	options |= STp->immediate ? MT_ST_NOWAIT : 0;
4742	options |= STp->immediate_filemark ? MT_ST_NOWAIT_EOF : 0;
4743	options |= STp->sili ? MT_ST_SILI : 0;
4744
4745	l = snprintf(buf, PAGE_SIZE, "0x%08x\n", options);
4746	return l;
4747}
4748static DEVICE_ATTR_RO(options);
4749
4750/**
4751 * position_lost_in_reset_show - Value 1 indicates that reads, writes, etc.
4752 * are blocked because a device reset has occurred and no operation positioning
4753 * the tape has been issued.
4754 * @dev: struct device
4755 * @attr: attribute structure
4756 * @buf: buffer to return formatted data in
4757 */
4758static ssize_t position_lost_in_reset_show(struct device *dev,
4759	struct device_attribute *attr, char *buf)
4760{
4761	struct st_modedef *STm = dev_get_drvdata(dev);
4762	struct scsi_tape *STp = STm->tape;
4763
4764	return sprintf(buf, "%d", STp->pos_unknown);
4765}
4766static DEVICE_ATTR_RO(position_lost_in_reset);
4767
4768/* Support for tape stats */
4769
4770/**
4771 * read_cnt_show - return read count - count of reads made from tape drive
4772 * @dev: struct device
4773 * @attr: attribute structure
4774 * @buf: buffer to return formatted data in
4775 */
4776static ssize_t read_cnt_show(struct device *dev,
4777	struct device_attribute *attr, char *buf)
4778{
4779	struct st_modedef *STm = dev_get_drvdata(dev);
4780
4781	return sprintf(buf, "%lld",
4782		       (long long)atomic64_read(&STm->tape->stats->read_cnt));
4783}
4784static DEVICE_ATTR_RO(read_cnt);
4785
4786/**
4787 * read_byte_cnt_show - return read byte count - tape drives
4788 * may use blocks less than 512 bytes this gives the raw byte count of
4789 * of data read from the tape drive.
4790 * @dev: struct device
4791 * @attr: attribute structure
4792 * @buf: buffer to return formatted data in
4793 */
4794static ssize_t read_byte_cnt_show(struct device *dev,
4795	struct device_attribute *attr, char *buf)
4796{
4797	struct st_modedef *STm = dev_get_drvdata(dev);
4798
4799	return sprintf(buf, "%lld",
4800		       (long long)atomic64_read(&STm->tape->stats->read_byte_cnt));
4801}
4802static DEVICE_ATTR_RO(read_byte_cnt);
4803
4804/**
4805 * read_ns_show - return read ns - overall time spent waiting on reads in ns.
4806 * @dev: struct device
4807 * @attr: attribute structure
4808 * @buf: buffer to return formatted data in
4809 */
4810static ssize_t read_ns_show(struct device *dev,
4811	struct device_attribute *attr, char *buf)
4812{
4813	struct st_modedef *STm = dev_get_drvdata(dev);
4814
4815	return sprintf(buf, "%lld",
4816		       (long long)atomic64_read(&STm->tape->stats->tot_read_time));
4817}
4818static DEVICE_ATTR_RO(read_ns);
4819
4820/**
4821 * write_cnt_show - write count - number of user calls
4822 * to write(2) that have written data to tape.
4823 * @dev: struct device
4824 * @attr: attribute structure
4825 * @buf: buffer to return formatted data in
4826 */
4827static ssize_t write_cnt_show(struct device *dev,
4828	struct device_attribute *attr, char *buf)
4829{
4830	struct st_modedef *STm = dev_get_drvdata(dev);
4831
4832	return sprintf(buf, "%lld",
4833		       (long long)atomic64_read(&STm->tape->stats->write_cnt));
4834}
4835static DEVICE_ATTR_RO(write_cnt);
4836
4837/**
4838 * write_byte_cnt_show - write byte count - raw count of
4839 * bytes written to tape.
4840 * @dev: struct device
4841 * @attr: attribute structure
4842 * @buf: buffer to return formatted data in
4843 */
4844static ssize_t write_byte_cnt_show(struct device *dev,
4845	struct device_attribute *attr, char *buf)
4846{
4847	struct st_modedef *STm = dev_get_drvdata(dev);
4848
4849	return sprintf(buf, "%lld",
4850		       (long long)atomic64_read(&STm->tape->stats->write_byte_cnt));
4851}
4852static DEVICE_ATTR_RO(write_byte_cnt);
4853
4854/**
4855 * write_ns_show - write ns - number of nanoseconds waiting on write
4856 * requests to complete.
4857 * @dev: struct device
4858 * @attr: attribute structure
4859 * @buf: buffer to return formatted data in
4860 */
4861static ssize_t write_ns_show(struct device *dev,
4862	struct device_attribute *attr, char *buf)
4863{
4864	struct st_modedef *STm = dev_get_drvdata(dev);
4865
4866	return sprintf(buf, "%lld",
4867		       (long long)atomic64_read(&STm->tape->stats->tot_write_time));
4868}
4869static DEVICE_ATTR_RO(write_ns);
4870
4871/**
4872 * in_flight_show - number of I/Os currently in flight -
4873 * in most cases this will be either 0 or 1. It may be higher if someone
4874 * has also issued other SCSI commands such as via an ioctl.
4875 * @dev: struct device
4876 * @attr: attribute structure
4877 * @buf: buffer to return formatted data in
4878 */
4879static ssize_t in_flight_show(struct device *dev,
4880	struct device_attribute *attr, char *buf)
4881{
4882	struct st_modedef *STm = dev_get_drvdata(dev);
4883
4884	return sprintf(buf, "%lld",
4885		       (long long)atomic64_read(&STm->tape->stats->in_flight));
4886}
4887static DEVICE_ATTR_RO(in_flight);
4888
4889/**
4890 * io_ns_show - io wait ns - this is the number of ns spent
4891 * waiting on all I/O to complete. This includes tape movement commands
4892 * such as rewinding, seeking to end of file or tape, it also includes
4893 * read and write. To determine the time spent on tape movement
4894 * subtract the read and write ns from this value.
4895 * @dev: struct device
4896 * @attr: attribute structure
4897 * @buf: buffer to return formatted data in
4898 */
4899static ssize_t io_ns_show(struct device *dev,
4900	struct device_attribute *attr, char *buf)
4901{
4902	struct st_modedef *STm = dev_get_drvdata(dev);
4903
4904	return sprintf(buf, "%lld",
4905		       (long long)atomic64_read(&STm->tape->stats->tot_io_time));
4906}
4907static DEVICE_ATTR_RO(io_ns);
4908
4909/**
4910 * other_cnt_show - other io count - this is the number of
4911 * I/O requests other than read and write requests.
4912 * Typically these are tape movement requests but will include driver
4913 * tape movement. This includes only requests issued by the st driver.
4914 * @dev: struct device
4915 * @attr: attribute structure
4916 * @buf: buffer to return formatted data in
4917 */
4918static ssize_t other_cnt_show(struct device *dev,
4919	struct device_attribute *attr, char *buf)
4920{
4921	struct st_modedef *STm = dev_get_drvdata(dev);
4922
4923	return sprintf(buf, "%lld",
4924		       (long long)atomic64_read(&STm->tape->stats->other_cnt));
4925}
4926static DEVICE_ATTR_RO(other_cnt);
4927
4928/**
4929 * resid_cnt_show - A count of the number of times we get a residual
4930 * count - this should indicate someone issuing reads larger than the
4931 * block size on tape.
4932 * @dev: struct device
4933 * @attr: attribute structure
4934 * @buf: buffer to return formatted data in
4935 */
4936static ssize_t resid_cnt_show(struct device *dev,
4937	struct device_attribute *attr, char *buf)
4938{
4939	struct st_modedef *STm = dev_get_drvdata(dev);
4940
4941	return sprintf(buf, "%lld",
4942		       (long long)atomic64_read(&STm->tape->stats->resid_cnt));
4943}
4944static DEVICE_ATTR_RO(resid_cnt);
4945
4946static struct attribute *st_dev_attrs[] = {
4947	&dev_attr_defined.attr,
4948	&dev_attr_default_blksize.attr,
4949	&dev_attr_default_density.attr,
4950	&dev_attr_default_compression.attr,
4951	&dev_attr_options.attr,
4952	&dev_attr_position_lost_in_reset.attr,
4953	NULL,
4954};
4955
4956static struct attribute *st_stats_attrs[] = {
4957	&dev_attr_read_cnt.attr,
4958	&dev_attr_read_byte_cnt.attr,
4959	&dev_attr_read_ns.attr,
4960	&dev_attr_write_cnt.attr,
4961	&dev_attr_write_byte_cnt.attr,
4962	&dev_attr_write_ns.attr,
4963	&dev_attr_in_flight.attr,
4964	&dev_attr_io_ns.attr,
4965	&dev_attr_other_cnt.attr,
4966	&dev_attr_resid_cnt.attr,
4967	NULL,
4968};
4969
4970static struct attribute_group stats_group = {
4971	.name = "stats",
4972	.attrs = st_stats_attrs,
4973};
4974
4975static struct attribute_group st_group = {
4976	.attrs = st_dev_attrs,
4977};
4978
4979static const struct attribute_group *st_dev_groups[] = {
4980	&st_group,
4981	&stats_group,
4982	NULL,
4983};
4984
4985/* The following functions may be useful for a larger audience. */
4986static int sgl_map_user_pages(struct st_buffer *STbp,
4987			      const unsigned int max_pages, unsigned long uaddr,
4988			      size_t count, int rw)
4989{
4990	unsigned long end = (uaddr + count + PAGE_SIZE - 1) >> PAGE_SHIFT;
4991	unsigned long start = uaddr >> PAGE_SHIFT;
4992	const int nr_pages = end - start;
4993	int res, i;
4994	struct page **pages;
4995	struct rq_map_data *mdata = &STbp->map_data;
4996
4997	/* User attempted Overflow! */
4998	if ((uaddr + count) < uaddr)
4999		return -EINVAL;
5000
5001	/* Too big */
5002        if (nr_pages > max_pages)
5003		return -ENOMEM;
5004
5005	/* Hmm? */
5006	if (count == 0)
5007		return 0;
5008
5009	pages = kmalloc_array(max_pages, sizeof(*pages), GFP_KERNEL);
5010	if (pages == NULL)
5011		return -ENOMEM;
5012
5013        /* Try to fault in all of the necessary pages */
5014        /* rw==READ means read from drive, write into memory area */
5015	res = pin_user_pages_fast(uaddr, nr_pages, rw == READ ? FOLL_WRITE : 0,
5016				  pages);
5017
5018	/* Errors and no page mapped should return here */
5019	if (res < nr_pages)
5020		goto out_unmap;
5021
5022        for (i=0; i < nr_pages; i++) {
5023                /* FIXME: flush superflous for rw==READ,
5024                 * probably wrong function for rw==WRITE
5025                 */
5026		flush_dcache_page(pages[i]);
5027        }
5028
5029	mdata->offset = uaddr & ~PAGE_MASK;
5030	STbp->mapped_pages = pages;
5031
5032	return nr_pages;
5033 out_unmap:
5034	if (res > 0) {
5035		unpin_user_pages(pages, res);
5036		res = 0;
5037	}
5038	kfree(pages);
5039	return res;
5040}
5041
5042
5043/* And unmap them... */
5044static int sgl_unmap_user_pages(struct st_buffer *STbp,
5045				const unsigned int nr_pages, int dirtied)
5046{
5047	/* FIXME: cache flush missing for rw==READ */
5048	unpin_user_pages_dirty_lock(STbp->mapped_pages, nr_pages, dirtied);
5049
5050	kfree(STbp->mapped_pages);
5051	STbp->mapped_pages = NULL;
5052
5053	return 0;
5054}
~/ Read-only file preview.