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