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