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