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