File: /usr/src/linux/drivers/scsi/st.c

1     /*
2        SCSI Tape Driver for Linux version 1.1 and newer. See the accompanying
3        file README.st for more information.
4     
5        History:
6        Rewritten from Dwayne Forsyth's SCSI tape driver by Kai Makisara.
7        Contribution and ideas from several people including (in alphabetical
8        order) Klaus Ehrenfried, Eugene Exarevsky, Eric Lee Green, Wolfgang Denk,
9        Steve Hirsch, Andreas Koppenh"ofer, Michael Leodolter, Eyal Lebedinsky,
10        Michael Schaefer, J"org Weule, and Eric Youngdale.
11     
12        Copyright 1992 - 2001 Kai Makisara
13        email Kai.Makisara@metla.fi
14     
15        Last modified: Sun Aug 12 12:34:28 2001 by makisara@kai.makisara.local
16        Some small formal changes - aeb, 950809
17     
18        Last modified: 18-JAN-1998 Richard Gooch <rgooch@atnf.csiro.au> Devfs support
19     
20        Reminder: write_lock_irqsave() can be replaced by write_lock() when the old SCSI
21        error handling will be discarded.
22      */
23     
24     static char *verstr = "20010812";
25     
26     #include <linux/module.h>
27     
28     #include <linux/fs.h>
29     #include <linux/kernel.h>
30     #include <linux/sched.h>
31     #include <linux/mm.h>
32     #include <linux/init.h>
33     #include <linux/string.h>
34     #include <linux/errno.h>
35     #include <linux/mtio.h>
36     #include <linux/ioctl.h>
37     #include <linux/fcntl.h>
38     #include <linux/spinlock.h>
39     #include <linux/smp_lock.h>
40     #include <asm/uaccess.h>
41     #include <asm/dma.h>
42     #include <asm/system.h>
43     
44     /* The driver prints some debugging information on the console if DEBUG
45        is defined and non-zero. */
46     #define DEBUG 0
47     
48     #if DEBUG
49     /* The message level for the debug messages is currently set to KERN_NOTICE
50        so that people can easily see the messages. Later when the debugging messages
51        in the drivers are more widely classified, this may be changed to KERN_DEBUG. */
52     #define ST_DEB_MSG  KERN_NOTICE
53     #define DEB(a) a
54     #define DEBC(a) if (debugging) { a ; }
55     #else
56     #define DEB(a)
57     #define DEBC(a)
58     #endif
59     
60     #define MAJOR_NR SCSI_TAPE_MAJOR
61     #include <linux/blk.h>
62     
63     #include "scsi.h"
64     #include "hosts.h"
65     #include <scsi/scsi_ioctl.h>
66     
67     #define ST_KILOBYTE 1024
68     
69     #include "st_options.h"
70     #include "st.h"
71     
72     #include "constants.h"
73     
74     static int buffer_kbs;
75     static int write_threshold_kbs;
76     static int max_buffers = (-1);
77     static int max_sg_segs;
78     
79     MODULE_AUTHOR("Kai Makisara");
80     MODULE_DESCRIPTION("SCSI Tape Driver");
81     MODULE_PARM(buffer_kbs, "i");
82     MODULE_PARM_DESC(buffer_kbs, "Default driver buffer size (KB; 32)");
83     MODULE_PARM(write_threshold_kbs, "i");
84     MODULE_PARM_DESC(write_threshold_kbs, "Asynchronous write threshold (KB; 30)");
85     MODULE_PARM(max_buffers, "i");
86     MODULE_PARM_DESC(max_buffers, "Maximum number of buffer allocated at initialisation (4)");
87     MODULE_PARM(max_sg_segs, "i");
88     MODULE_PARM_DESC(max_sg_segs, "Maximum number of scatter/gather segments to use (32)");
89     
90     #ifndef MODULE
91     static struct st_dev_parm {
92     	char *name;
93     	int *val;
94     } parms[] __initdata = {
95     	{
96     		"buffer_kbs", &buffer_kbs
97     	},
98     	{
99     		"write_threshold_kbs", &write_threshold_kbs
100     	},
101     	{
102     		"max_buffers", &max_buffers
103     	},
104     	{
105     		"max_sg_segs", &max_sg_segs
106     	}
107     };
108     #endif
109     
110     
111     /* The default definitions have been moved to st_options.h */
112     
113     #define ST_BUFFER_SIZE (ST_BUFFER_BLOCKS * ST_KILOBYTE)
114     #define ST_WRITE_THRESHOLD (ST_WRITE_THRESHOLD_BLOCKS * ST_KILOBYTE)
115     
116     /* The buffer size should fit into the 24 bits for length in the
117        6-byte SCSI read and write commands. */
118     #if ST_BUFFER_SIZE >= (2 << 24 - 1)
119     #error "Buffer size should not exceed (2 << 24 - 1) bytes!"
120     #endif
121     
122     DEB( static int debugging = DEBUG; )
123     
124     #define MAX_RETRIES 0
125     #define MAX_WRITE_RETRIES 0
126     #define MAX_READY_RETRIES 5
127     #define NO_TAPE  NOT_READY
128     
129     #define ST_TIMEOUT (900 * HZ)
130     #define ST_LONG_TIMEOUT (14000 * HZ)
131     
132     #define TAPE_NR(x) (MINOR(x) & ~(128 | ST_MODE_MASK))
133     #define TAPE_MODE(x) ((MINOR(x) & ST_MODE_MASK) >> ST_MODE_SHIFT)
134     
135     /* Internal ioctl to set both density (uppermost 8 bits) and blocksize (lower
136        24 bits) */
137     #define SET_DENS_AND_BLK 0x10001
138     
139     #define ST_DEV_ARR_LUMP  6
140     static rwlock_t st_dev_arr_lock = RW_LOCK_UNLOCKED;
141     
142     static int st_nbr_buffers;
143     static ST_buffer **st_buffers = NULL;
144     static int st_buffer_size = ST_BUFFER_SIZE;
145     static int st_write_threshold = ST_WRITE_THRESHOLD;
146     static int st_max_buffers = ST_MAX_BUFFERS;
147     static int st_max_sg_segs = ST_MAX_SG;
148     
149     static Scsi_Tape **scsi_tapes = NULL;
150     
151     static int modes_defined;
152     
153     static ST_buffer *new_tape_buffer(int, int, int);
154     static int enlarge_buffer(ST_buffer *, int, int);
155     static void normalize_buffer(ST_buffer *);
156     static int append_to_buffer(const char *, ST_buffer *, int);
157     static int from_buffer(ST_buffer *, char *, int);
158     
159     static int st_init(void);
160     static int st_attach(Scsi_Device *);
161     static int st_detect(Scsi_Device *);
162     static void st_detach(Scsi_Device *);
163     
164     static struct Scsi_Device_Template st_template =
165     {
166     	name:"tape", 
167     	tag:"st", 
168     	scsi_type:TYPE_TAPE,
169     	major:SCSI_TAPE_MAJOR, 
170     	detect:st_detect, 
171     	init:st_init,
172     	attach:st_attach, 
173     	detach:st_detach
174     };
175     
176     static int st_compression(Scsi_Tape *, int);
177     
178     static int find_partition(Scsi_Tape *);
179     static int update_partition(Scsi_Tape *);
180     
181     static int st_int_ioctl(Scsi_Tape *, unsigned int, unsigned long);
182     
183     
184     #include "osst_detect.h"
185     #ifndef SIGS_FROM_OSST
186     #define SIGS_FROM_OSST \
187     	{"OnStream", "SC-", "", "osst"}, \
188     	{"OnStream", "DI-", "", "osst"}, \
189     	{"OnStream", "DP-", "", "osst"}, \
190     	{"OnStream", "USB", "", "osst"}, \
191     	{"OnStream", "FW-", "", "osst"}
192     #endif
193     
194     struct st_reject_data {
195     	char *vendor;
196     	char *model;
197     	char *rev;
198     	char *driver_hint; /* Name of the correct driver, NULL if unknown */
199     };
200     
201     static struct st_reject_data reject_list[] = {
202     	/* {"XXX", "Yy-", "", NULL},  example */
203     	SIGS_FROM_OSST,
204     	{NULL, }};
205     
206     /* If the device signature is on the list of incompatible drives, the
207        function returns a pointer to the name of the correct driver (if known) */
208     static char * st_incompatible(Scsi_Device* SDp)
209     {
210     	struct st_reject_data *rp;
211     
212     	for (rp=&(reject_list[0]); rp->vendor != NULL; rp++)
213     		if (!strncmp(rp->vendor, SDp->vendor, strlen(rp->vendor)) &&
214     		    !strncmp(rp->model, SDp->model, strlen(rp->model)) &&
215     		    !strncmp(rp->rev, SDp->rev, strlen(rp->rev))) {
216     			if (rp->driver_hint)
217     				return rp->driver_hint;
218     			else
219     				return "unknown";
220     		}
221     	return NULL;
222     }
223     
224     
225     /* Convert the result to success code */
226     static int st_chk_result(Scsi_Tape *STp, Scsi_Request * SRpnt)
227     {
228     	int dev;
229     	int result = SRpnt->sr_result;
230     	unsigned char *sense = SRpnt->sr_sense_buffer, scode;
231     	DEB(const char *stp;)
232     
233     	if (!result) {
234     		sense[0] = 0;	/* We don't have sense data if this byte is zero */
235     		return 0;
236     	}
237     
238     	if (driver_byte(result) & DRIVER_SENSE)
239     		scode = sense[2] & 0x0f;
240     	else {
241     		sense[0] = 0;
242     		scode = 0;
243     	}
244     
245     	dev = TAPE_NR(SRpnt->sr_request.rq_dev);
246             DEB(
247             if (debugging) {
248                     printk(ST_DEB_MSG "st%d: Error: %x, cmd: %x %x %x %x %x %x Len: %d\n",
249     		       dev, result,
250     		       SRpnt->sr_cmnd[0], SRpnt->sr_cmnd[1], SRpnt->sr_cmnd[2],
251     		       SRpnt->sr_cmnd[3], SRpnt->sr_cmnd[4], SRpnt->sr_cmnd[5],
252     		       SRpnt->sr_bufflen);
253     		if (driver_byte(result) & DRIVER_SENSE)
254     			print_req_sense("st", SRpnt);
255     	} else ) /* end DEB */
256     		if (!(driver_byte(result) & DRIVER_SENSE) ||
257     		    ((sense[0] & 0x70) == 0x70 &&
258     		     scode != NO_SENSE &&
259     		     scode != RECOVERED_ERROR &&
260                          /* scode != UNIT_ATTENTION && */
261     		     scode != BLANK_CHECK &&
262     		     scode != VOLUME_OVERFLOW &&
263     		     SRpnt->sr_cmnd[0] != MODE_SENSE &&
264     		     SRpnt->sr_cmnd[0] != TEST_UNIT_READY)) {	/* Abnormal conditions for tape */
265     		if (driver_byte(result) & DRIVER_SENSE) {
266     			printk(KERN_WARNING "st%d: Error with sense data: ", dev);
267     			print_req_sense("st", SRpnt);
268     		} else
269     			printk(KERN_WARNING
270     			       "st%d: Error %x (sugg. bt 0x%x, driver bt 0x%x, host bt 0x%x).\n",
271     			       dev, result, suggestion(result),
272                                    driver_byte(result) & DRIVER_MASK, host_byte(result));
273     	}
274     
275     	if ((sense[0] & 0x70) == 0x70 &&
276     	    scode == RECOVERED_ERROR
277     #if ST_RECOVERED_WRITE_FATAL
278     	    && SRpnt->sr_cmnd[0] != WRITE_6
279     	    && SRpnt->sr_cmnd[0] != WRITE_FILEMARKS
280     #endif
281     	    ) {
282     		STp->recover_count++;
283     		STp->recover_reg++;
284     
285                     DEB(
286     		if (debugging) {
287     			if (SRpnt->sr_cmnd[0] == READ_6)
288     				stp = "read";
289     			else if (SRpnt->sr_cmnd[0] == WRITE_6)
290     				stp = "write";
291     			else
292     				stp = "ioctl";
293     			printk(ST_DEB_MSG "st%d: Recovered %s error (%d).\n", dev, stp,
294     			       STp->recover_count);
295     		} ) /* end DEB */
296     
297     		if ((sense[2] & 0xe0) == 0)
298     			return 0;
299     	}
300     	return (-EIO);
301     }
302     
303     
304     /* Wakeup from interrupt */
305     static void st_sleep_done(Scsi_Cmnd * SCpnt)
306     {
307     	unsigned int st_nbr;
308     	int remainder;
309     	Scsi_Tape *STp;
310     
311     	st_nbr = TAPE_NR(SCpnt->request.rq_dev);
312     	read_lock(&st_dev_arr_lock);
313     	STp = scsi_tapes[st_nbr];
314     	read_unlock(&st_dev_arr_lock);
315     	if ((STp->buffer)->writing &&
316     	    (SCpnt->sense_buffer[0] & 0x70) == 0x70 &&
317     	    (SCpnt->sense_buffer[2] & 0x40)) {
318     		/* EOM at write-behind, has all been written? */
319     		if ((SCpnt->sense_buffer[0] & 0x80) != 0)
320     			remainder = (SCpnt->sense_buffer[3] << 24) |
321     				(SCpnt->sense_buffer[4] << 16) |
322     				(SCpnt->sense_buffer[5] << 8) |
323     				SCpnt->sense_buffer[6];
324     		else
325     			remainder = 0;
326     		if ((SCpnt->sense_buffer[2] & 0x0f) == VOLUME_OVERFLOW ||
327     		    remainder > 0)
328     			(STp->buffer)->midlevel_result = SCpnt->result; /* Error */
329     		else
330     			(STp->buffer)->midlevel_result = INT_MAX;	/* OK */
331     	} else
332     		(STp->buffer)->midlevel_result = SCpnt->result;
333     	SCpnt->request.rq_status = RQ_SCSI_DONE;
334     	(STp->buffer)->last_SRpnt = SCpnt->sc_request;
335     	DEB( STp->write_pending = 0; )
336     
337     	complete(SCpnt->request.waiting);
338     }
339     
340     
341     /* Do the scsi command. Waits until command performed if do_wait is true.
342        Otherwise write_behind_check() is used to check that the command
343        has finished. */
344     static Scsi_Request *
345      st_do_scsi(Scsi_Request * SRpnt, Scsi_Tape * STp, unsigned char *cmd, int bytes,
346     	    int direction, int timeout, int retries, int do_wait)
347     {
348     	unsigned char *bp;
349     
350     	if (SRpnt == NULL) {
351     		SRpnt = scsi_allocate_request(STp->device);
352     		if (SRpnt == NULL) {
353     			DEBC( printk(KERN_ERR "st%d: Can't get SCSI request.\n",
354     				     TAPE_NR(STp->devt)); );
355     			if (signal_pending(current))
356     				(STp->buffer)->syscall_result = (-EINTR);
357     			else
358     				(STp->buffer)->syscall_result = (-EBUSY);
359     			return NULL;
360     		}
361     	}
362     
363     	if (SRpnt->sr_device->scsi_level <= SCSI_2)
364     		cmd[1] |= (SRpnt->sr_device->lun << 5) & 0xe0;
365     	init_completion(&STp->wait);
366     	SRpnt->sr_use_sg = (bytes > (STp->buffer)->sg[0].length) ?
367     	    (STp->buffer)->use_sg : 0;
368     	if (SRpnt->sr_use_sg) {
369     		bp = (char *) &((STp->buffer)->sg[0]);
370     		if ((STp->buffer)->sg_segs < SRpnt->sr_use_sg)
371     			SRpnt->sr_use_sg = (STp->buffer)->sg_segs;
372     	} else
373     		bp = (STp->buffer)->b_data;
374     	SRpnt->sr_data_direction = direction;
375     	SRpnt->sr_cmd_len = 0;
376     	SRpnt->sr_request.waiting = &(STp->wait);
377     	SRpnt->sr_request.rq_status = RQ_SCSI_BUSY;
378     	SRpnt->sr_request.rq_dev = STp->devt;
379     
380     	scsi_do_req(SRpnt, (void *) cmd, bp, bytes,
381     		    st_sleep_done, timeout, retries);
382     
383     	if (do_wait) {
384     		wait_for_completion(SRpnt->sr_request.waiting);
385     		SRpnt->sr_request.waiting = NULL;
386     		(STp->buffer)->syscall_result = st_chk_result(STp, SRpnt);
387     	}
388     	return SRpnt;
389     }
390     
391     
392     /* Handle the write-behind checking (downs the semaphore) */
393     static void write_behind_check(Scsi_Tape * STp)
394     {
395     	ST_buffer *STbuffer;
396     	ST_partstat *STps;
397     
398     	STbuffer = STp->buffer;
399     
400             DEB(
401     	if (STp->write_pending)
402     		STp->nbr_waits++;
403     	else
404     		STp->nbr_finished++;
405             ) /* end DEB */
406     
407     	wait_for_completion(&(STp->wait));
408     	(STp->buffer)->last_SRpnt->sr_request.waiting = NULL;
409     
410     	(STp->buffer)->syscall_result = st_chk_result(STp, (STp->buffer)->last_SRpnt);
411     	scsi_release_request((STp->buffer)->last_SRpnt);
412     
413     	if (STbuffer->writing < STbuffer->buffer_bytes)
414     #if 0
415     		memcpy(STbuffer->b_data,
416     		       STbuffer->b_data + STbuffer->writing,
417     		       STbuffer->buffer_bytes - STbuffer->writing);
418     #else
419     		printk(KERN_WARNING
420                            "st: write_behind_check: something left in buffer!\n");
421     #endif
422     	STbuffer->buffer_bytes -= STbuffer->writing;
423     	STps = &(STp->ps[STp->partition]);
424     	if (STps->drv_block >= 0) {
425     		if (STp->block_size == 0)
426     			STps->drv_block++;
427     		else
428     			STps->drv_block += STbuffer->writing / STp->block_size;
429     	}
430     	STbuffer->writing = 0;
431     
432     	return;
433     }
434     
435     
436     /* Step over EOF if it has been inadvertently crossed (ioctl not used because
437        it messes up the block number). */
438     static int cross_eof(Scsi_Tape * STp, int forward)
439     {
440     	Scsi_Request *SRpnt;
441     	unsigned char cmd[MAX_COMMAND_SIZE];
442     
443     	cmd[0] = SPACE;
444     	cmd[1] = 0x01;		/* Space FileMarks */
445     	if (forward) {
446     		cmd[2] = cmd[3] = 0;
447     		cmd[4] = 1;
448     	} else
449     		cmd[2] = cmd[3] = cmd[4] = 0xff;	/* -1 filemarks */
450     	cmd[5] = 0;
451     
452             DEBC(printk(ST_DEB_MSG "st%d: Stepping over filemark %s.\n",
453     		   TAPE_NR(STp->devt), forward ? "forward" : "backward"));
454     
455     	SRpnt = st_do_scsi(NULL, STp, cmd, 0, SCSI_DATA_NONE,
456     			   STp->timeout, MAX_RETRIES, TRUE);
457     	if (!SRpnt)
458     		return (STp->buffer)->syscall_result;
459     
460     	scsi_release_request(SRpnt);
461     	SRpnt = NULL;
462     
463     	if ((STp->buffer)->midlevel_result != 0)
464     		printk(KERN_ERR "st%d: Stepping over filemark %s failed.\n",
465     		   TAPE_NR(STp->devt), forward ? "forward" : "backward");
466     
467     	return (STp->buffer)->syscall_result;
468     }
469     
470     
471     /* Flush the write buffer (never need to write if variable blocksize). */
472     static int flush_write_buffer(Scsi_Tape * STp)
473     {
474     	int offset, transfer, blks;
475     	int result;
476     	unsigned char cmd[MAX_COMMAND_SIZE];
477     	Scsi_Request *SRpnt;
478     	ST_partstat *STps;
479     
480     	if ((STp->buffer)->writing) {
481     		write_behind_check(STp);
482     		if ((STp->buffer)->syscall_result) {
483                             DEBC(printk(ST_DEB_MSG
484                                            "st%d: Async write error (flush) %x.\n",
485     				       TAPE_NR(STp->devt), (STp->buffer)->midlevel_result))
486     			if ((STp->buffer)->midlevel_result == INT_MAX)
487     				return (-ENOSPC);
488     			return (-EIO);
489     		}
490     	}
491     	if (STp->block_size == 0)
492     		return 0;
493     
494     	result = 0;
495     	if (STp->dirty == 1) {
496     
497     		offset = (STp->buffer)->buffer_bytes;
498     		transfer = ((offset + STp->block_size - 1) /
499     			    STp->block_size) * STp->block_size;
500                     DEBC(printk(ST_DEB_MSG "st%d: Flushing %d bytes.\n",
501                                    TAPE_NR(STp->devt), transfer));
502     
503     		memset((STp->buffer)->b_data + offset, 0, transfer - offset);
504     
505     		memset(cmd, 0, MAX_COMMAND_SIZE);
506     		cmd[0] = WRITE_6;
507     		cmd[1] = 1;
508     		blks = transfer / STp->block_size;
509     		cmd[2] = blks >> 16;
510     		cmd[3] = blks >> 8;
511     		cmd[4] = blks;
512     
513     		SRpnt = st_do_scsi(NULL, STp, cmd, transfer, SCSI_DATA_WRITE,
514     				   STp->timeout, MAX_WRITE_RETRIES, TRUE);
515     		if (!SRpnt)
516     			return (STp->buffer)->syscall_result;
517     
518     		STps = &(STp->ps[STp->partition]);
519     		if ((STp->buffer)->syscall_result != 0) {
520     			if ((SRpnt->sr_sense_buffer[0] & 0x70) == 0x70 &&
521     			    (SRpnt->sr_sense_buffer[2] & 0x40) &&
522     			    (SRpnt->sr_sense_buffer[2] & 0x0f) == NO_SENSE) {
523     				STp->dirty = 0;
524     				(STp->buffer)->buffer_bytes = 0;
525     				result = (-ENOSPC);
526     			} else {
527     				printk(KERN_ERR "st%d: Error on flush.\n",
528                                            TAPE_NR(STp->devt));
529     				result = (-EIO);
530     			}
531     			STps->drv_block = (-1);
532     		} else {
533     			if (STps->drv_block >= 0)
534     				STps->drv_block += blks;
535     			STp->dirty = 0;
536     			(STp->buffer)->buffer_bytes = 0;
537     		}
538     		scsi_release_request(SRpnt);
539     		SRpnt = NULL;
540     	}
541     	return result;
542     }
543     
544     
545     /* Flush the tape buffer. The tape will be positioned correctly unless
546        seek_next is true. */
547     static int flush_buffer(Scsi_Tape *STp, int seek_next)
548     {
549     	int backspace, result;
550     	ST_buffer *STbuffer;
551     	ST_partstat *STps;
552     
553     	STbuffer = STp->buffer;
554     
555     	/*
556     	 * If there was a bus reset, block further access
557     	 * to this device.
558     	 */
559     	if (STp->device->was_reset)
560     		return (-EIO);
561     
562     	if (STp->ready != ST_READY)
563     		return 0;
564     
565     	STps = &(STp->ps[STp->partition]);
566     	if (STps->rw == ST_WRITING)	/* Writing */
567     		return flush_write_buffer(STp);
568     
569     	if (STp->block_size == 0)
570     		return 0;
571     
572     	backspace = ((STp->buffer)->buffer_bytes +
573     		     (STp->buffer)->read_pointer) / STp->block_size -
574     	    ((STp->buffer)->read_pointer + STp->block_size - 1) /
575     	    STp->block_size;
576     	(STp->buffer)->buffer_bytes = 0;
577     	(STp->buffer)->read_pointer = 0;
578     	result = 0;
579     	if (!seek_next) {
580     		if (STps->eof == ST_FM_HIT) {
581     			result = cross_eof(STp, FALSE);	/* Back over the EOF hit */
582     			if (!result)
583     				STps->eof = ST_NOEOF;
584     			else {
585     				if (STps->drv_file >= 0)
586     					STps->drv_file++;
587     				STps->drv_block = 0;
588     			}
589     		}
590     		if (!result && backspace > 0)
591     			result = st_int_ioctl(STp, MTBSR, backspace);
592     	} else if (STps->eof == ST_FM_HIT) {
593     		if (STps->drv_file >= 0)
594     			STps->drv_file++;
595     		STps->drv_block = 0;
596     		STps->eof = ST_NOEOF;
597     	}
598     	return result;
599     
600     }
601     
602     /* Set the mode parameters */
603     static int set_mode_densblk(Scsi_Tape * STp, ST_mode * STm)
604     {
605     	int set_it = FALSE;
606     	unsigned long arg;
607     	int dev = TAPE_NR(STp->devt);
608     
609     	if (!STp->density_changed &&
610     	    STm->default_density >= 0 &&
611     	    STm->default_density != STp->density) {
612     		arg = STm->default_density;
613     		set_it = TRUE;
614     	} else
615     		arg = STp->density;
616     	arg <<= MT_ST_DENSITY_SHIFT;
617     	if (!STp->blksize_changed &&
618     	    STm->default_blksize >= 0 &&
619     	    STm->default_blksize != STp->block_size) {
620     		arg |= STm->default_blksize;
621     		set_it = TRUE;
622     	} else
623     		arg |= STp->block_size;
624     	if (set_it &&
625     	    st_int_ioctl(STp, SET_DENS_AND_BLK, arg)) {
626     		printk(KERN_WARNING
627     		       "st%d: Can't set default block size to %d bytes and density %x.\n",
628     		       dev, STm->default_blksize, STm->default_density);
629     		if (modes_defined)
630     			return (-EINVAL);
631     	}
632     	return 0;
633     }
634     
635     
636     /* Open the device. Needs to be called with BKL only because of incrementing the SCSI host
637        module count. */
638     static int st_open(struct inode *inode, struct file *filp)
639     {
640     	unsigned short st_flags;
641     	int i, need_dma_buffer, new_session = FALSE;
642     	int retval;
643     	unsigned char cmd[MAX_COMMAND_SIZE];
644     	Scsi_Request *SRpnt;
645     	Scsi_Tape *STp;
646     	ST_mode *STm;
647     	ST_partstat *STps;
648     	int dev = TAPE_NR(inode->i_rdev);
649     	int mode = TAPE_MODE(inode->i_rdev);
650     	unsigned long flags;
651     
652     	write_lock_irqsave(&st_dev_arr_lock, flags);
653     	STp = scsi_tapes[dev];
654     	if (dev >= st_template.dev_max || STp == NULL) {
655     		write_unlock_irqrestore(&st_dev_arr_lock, flags);
656     		return (-ENXIO);
657     	}
658     
659     	if (STp->in_use) {
660     		write_unlock_irqrestore(&st_dev_arr_lock, flags);
661     		DEB( printk(ST_DEB_MSG "st%d: Device already in use.\n", dev); )
662     		return (-EBUSY);
663     	}
664     	STp->in_use = 1;
665     	write_unlock_irqrestore(&st_dev_arr_lock, flags);
666     	STp->rew_at_close = STp->autorew_dev = (MINOR(inode->i_rdev) & 0x80) == 0;
667     
668     	if (STp->device->host->hostt->module)
669     		__MOD_INC_USE_COUNT(STp->device->host->hostt->module);
670     
671     	if (!scsi_block_when_processing_errors(STp->device)) {
672     		retval = (-ENXIO);
673     		goto err_out;
674     	}
675     
676     	if (mode != STp->current_mode) {
677                     DEBC(printk(ST_DEB_MSG "st%d: Mode change from %d to %d.\n",
678     			       dev, STp->current_mode, mode));
679     		new_session = TRUE;
680     		STp->current_mode = mode;
681     	}
682     	STm = &(STp->modes[STp->current_mode]);
683     
684     	/* Allocate a buffer for this user */
685     	need_dma_buffer = STp->restr_dma;
686     	write_lock_irqsave(&st_dev_arr_lock, flags);
687     	for (i = 0; i < st_nbr_buffers; i++)
688     		if (!st_buffers[i]->in_use &&
689     		    (!need_dma_buffer || st_buffers[i]->dma)) {
690     			STp->buffer = st_buffers[i];
691     			(STp->buffer)->in_use = 1;
692     			break;
693     		}
694     	write_unlock_irqrestore(&st_dev_arr_lock, flags);
695     	if (i >= st_nbr_buffers) {
696     		STp->buffer = new_tape_buffer(FALSE, need_dma_buffer, TRUE);
697     		if (STp->buffer == NULL) {
698     			printk(KERN_WARNING "st%d: Can't allocate tape buffer.\n", dev);
699     			retval = (-EBUSY);
700     			goto err_out;
701     		}
702     	}
703     
704     	(STp->buffer)->writing = 0;
705     	(STp->buffer)->syscall_result = 0;
706     	(STp->buffer)->use_sg = STp->device->host->sg_tablesize;
707     
708     	/* Compute the usable buffer size for this SCSI adapter */
709     	if (!(STp->buffer)->use_sg)
710     		(STp->buffer)->buffer_size = (STp->buffer)->sg[0].length;
711     	else {
712     		for (i = 0, (STp->buffer)->buffer_size = 0; i < (STp->buffer)->use_sg &&
713     		     i < (STp->buffer)->sg_segs; i++)
714     			(STp->buffer)->buffer_size += (STp->buffer)->sg[i].length;
715     	}
716     
717     	st_flags = filp->f_flags;
718     	STp->write_prot = ((st_flags & O_ACCMODE) == O_RDONLY);
719     
720     	STp->dirty = 0;
721     	for (i = 0; i < ST_NBR_PARTITIONS; i++) {
722     		STps = &(STp->ps[i]);
723     		STps->rw = ST_IDLE;
724     	}
725     	STp->ready = ST_READY;
726     	STp->recover_count = 0;
727     	DEB( STp->nbr_waits = STp->nbr_finished = 0; )
728     
729     	memset((void *) &cmd[0], 0, MAX_COMMAND_SIZE);
730     	cmd[0] = TEST_UNIT_READY;
731     
732     	SRpnt = st_do_scsi(NULL, STp, cmd, 0, SCSI_DATA_NONE, STp->long_timeout,
733     			   MAX_READY_RETRIES, TRUE);
734     	if (!SRpnt) {
735     		retval = (STp->buffer)->syscall_result;
736     		goto err_out;
737     	}
738     
739     	if ((SRpnt->sr_sense_buffer[0] & 0x70) == 0x70 &&
740     	    (SRpnt->sr_sense_buffer[2] & 0x0f) == UNIT_ATTENTION) {	/* New media? */
741     
742     		/* Flush the queued UNIT ATTENTION sense data */
743     		for (i=0; i < 10; i++) {
744                             memset((void *) &cmd[0], 0, MAX_COMMAND_SIZE);
745                             cmd[0] = TEST_UNIT_READY;
746                             SRpnt = st_do_scsi(SRpnt, STp, cmd, 0, SCSI_DATA_NONE,
747     					   STp->long_timeout, MAX_READY_RETRIES, TRUE);
748                             if ((SRpnt->sr_sense_buffer[0] & 0x70) != 0x70 ||
749                                 (SRpnt->sr_sense_buffer[2] & 0x0f) != UNIT_ATTENTION)
750                                     break;
751     		}
752     
753     		(STp->device)->was_reset = 0;
754     		STp->partition = STp->new_partition = 0;
755     		if (STp->can_partitions)
756     			STp->nbr_partitions = 1; /* This guess will be updated later
757                                                         if necessary */
758     		for (i = 0; i < ST_NBR_PARTITIONS; i++) {
759     			STps = &(STp->ps[i]);
760     			STps->rw = ST_IDLE;
761     			STps->eof = ST_NOEOF;
762     			STps->at_sm = 0;
763     			STps->last_block_valid = FALSE;
764     			STps->drv_block = 0;
765     			STps->drv_file = 0;
766     		}
767     		new_session = TRUE;
768     	}
769     
770     	if ((STp->buffer)->syscall_result != 0) {
771     		if ((STp->device)->scsi_level >= SCSI_2 &&
772     		    (SRpnt->sr_sense_buffer[0] & 0x70) == 0x70 &&
773     		    (SRpnt->sr_sense_buffer[2] & 0x0f) == NOT_READY &&
774     		    SRpnt->sr_sense_buffer[12] == 0x3a) {	/* Check ASC */
775     			STp->ready = ST_NO_TAPE;
776     		} else
777     			STp->ready = ST_NOT_READY;
778     		scsi_release_request(SRpnt);
779     		SRpnt = NULL;
780     		STp->density = 0;	/* Clear the erroneous "residue" */
781     		STp->write_prot = 0;
782     		STp->block_size = 0;
783     		STp->ps[0].drv_file = STp->ps[0].drv_block = (-1);
784     		STp->partition = STp->new_partition = 0;
785     		STp->door_locked = ST_UNLOCKED;
786     		return 0;
787     	}
788     
789     	if (STp->omit_blklims)
790     		STp->min_block = STp->max_block = (-1);
791     	else {
792     		memset((void *) &cmd[0], 0, MAX_COMMAND_SIZE);
793     		cmd[0] = READ_BLOCK_LIMITS;
794     
795     		SRpnt = st_do_scsi(SRpnt, STp, cmd, 6, SCSI_DATA_READ, STp->timeout,
796     				   MAX_READY_RETRIES, TRUE);
797     
798     		if (!SRpnt->sr_result && !SRpnt->sr_sense_buffer[0]) {
799     			STp->max_block = ((STp->buffer)->b_data[1] << 16) |
800     			    ((STp->buffer)->b_data[2] << 8) | (STp->buffer)->b_data[3];
801     			STp->min_block = ((STp->buffer)->b_data[4] << 8) |
802     			    (STp->buffer)->b_data[5];
803     			if ( DEB( debugging || ) !STp->inited)
804     				printk(KERN_WARNING
805                                            "st%d: Block limits %d - %d bytes.\n", dev,
806                                            STp->min_block, STp->max_block);
807     		} else {
808     			STp->min_block = STp->max_block = (-1);
809                             DEBC(printk(ST_DEB_MSG "st%d: Can't read block limits.\n",
810                                            dev));
811     		}
812     	}
813     
814     	memset((void *) &cmd[0], 0, MAX_COMMAND_SIZE);
815     	cmd[0] = MODE_SENSE;
816     	cmd[4] = 12;
817     
818     	SRpnt = st_do_scsi(SRpnt, STp, cmd, 12, SCSI_DATA_READ, STp->timeout,
819     			   MAX_READY_RETRIES, TRUE);
820     
821     	if ((STp->buffer)->syscall_result != 0) {
822                     DEBC(printk(ST_DEB_MSG "st%d: No Mode Sense.\n", dev));
823     		STp->block_size = ST_DEFAULT_BLOCK;	/* Educated guess (?) */
824     		(STp->buffer)->syscall_result = 0;	/* Prevent error propagation */
825     		STp->drv_write_prot = 0;
826     	} else {
827                     DEBC(printk(ST_DEB_MSG
828                                 "st%d: Mode sense. Length %d, medium %x, WBS %x, BLL %d\n",
829                                 dev,
830                                 (STp->buffer)->b_data[0], (STp->buffer)->b_data[1],
831                                 (STp->buffer)->b_data[2], (STp->buffer)->b_data[3]));
832     
833     		if ((STp->buffer)->b_data[3] >= 8) {
834     			STp->drv_buffer = ((STp->buffer)->b_data[2] >> 4) & 7;
835     			STp->density = (STp->buffer)->b_data[4];
836     			STp->block_size = (STp->buffer)->b_data[9] * 65536 +
837     			    (STp->buffer)->b_data[10] * 256 + (STp->buffer)->b_data[11];
838                             DEBC(printk(ST_DEB_MSG
839                                         "st%d: Density %x, tape length: %x, drv buffer: %d\n",
840                                         dev, STp->density, (STp->buffer)->b_data[5] * 65536 +
841                                         (STp->buffer)->b_data[6] * 256 + (STp->buffer)->b_data[7],
842                                         STp->drv_buffer));
843     		}
844     		STp->drv_write_prot = ((STp->buffer)->b_data[2] & 0x80) != 0;
845     	}
846     	scsi_release_request(SRpnt);
847     	SRpnt = NULL;
848             STp->inited = TRUE;
849     
850     	if (STp->block_size > 0)
851     		(STp->buffer)->buffer_blocks =
852                             (STp->buffer)->buffer_size / STp->block_size;
853     	else
854     		(STp->buffer)->buffer_blocks = 1;
855     	(STp->buffer)->buffer_bytes = (STp->buffer)->read_pointer = 0;
856     
857             DEBC(printk(ST_DEB_MSG
858                            "st%d: Block size: %d, buffer size: %d (%d blocks).\n", dev,
859     		       STp->block_size, (STp->buffer)->buffer_size,
860     		       (STp->buffer)->buffer_blocks));
861     
862     	if (STp->drv_write_prot) {
863     		STp->write_prot = 1;
864     
865                     DEBC(printk(ST_DEB_MSG "st%d: Write protected\n", dev));
866     
867     		if ((st_flags & O_ACCMODE) == O_WRONLY || (st_flags & O_ACCMODE) == O_RDWR) {
868     			retval = (-EROFS);
869     			goto err_out;
870     		}
871     	}
872     
873     	if (STp->can_partitions && STp->nbr_partitions < 1) {
874     		/* This code is reached when the device is opened for the first time
875     		   after the driver has been initialized with tape in the drive and the
876     		   partition support has been enabled. */
877                     DEBC(printk(ST_DEB_MSG
878                                 "st%d: Updating partition number in status.\n", dev));
879     		if ((STp->partition = find_partition(STp)) < 0) {
880     			retval = STp->partition;
881     			goto err_out;
882     		}
883     		STp->new_partition = STp->partition;
884     		STp->nbr_partitions = 1; /* This guess will be updated when necessary */
885     	}
886     
887     	if (new_session) {	/* Change the drive parameters for the new mode */
888     		STp->density_changed = STp->blksize_changed = FALSE;
889     		STp->compression_changed = FALSE;
890     		if (!(STm->defaults_for_writes) &&
891     		    (retval = set_mode_densblk(STp, STm)) < 0)
892     		    goto err_out;
893     
894     		if (STp->default_drvbuffer != 0xff) {
895     			if (st_int_ioctl(STp, MTSETDRVBUFFER, STp->default_drvbuffer))
896     				printk(KERN_WARNING
897                                            "st%d: Can't set default drive buffering to %d.\n",
898     				       dev, STp->default_drvbuffer);
899     		}
900     	}
901     
902     	return 0;
903     
904      err_out:
905     	if (STp->buffer != NULL) {
906     		(STp->buffer)->in_use = 0;
907     		STp->buffer = NULL;
908     	}
909     	STp->in_use = 0;
910     	if (STp->device->host->hostt->module)
911     	    __MOD_DEC_USE_COUNT(STp->device->host->hostt->module);
912     	return retval;
913     
914     }
915     
916     
917     /* Flush the tape buffer before close */
918     static int st_flush(struct file *filp)
919     {
920     	int result = 0, result2;
921     	unsigned char cmd[MAX_COMMAND_SIZE];
922     	Scsi_Request *SRpnt;
923     	Scsi_Tape *STp;
924     	ST_mode *STm;
925     	ST_partstat *STps;
926     
927     	struct inode *inode = filp->f_dentry->d_inode;
928     	kdev_t devt = inode->i_rdev;
929     	int dev;
930     
931     	if (file_count(filp) > 1)
932     		return 0;
933     
934     	dev = TAPE_NR(devt);
935     	read_lock(&st_dev_arr_lock);
936     	STp = scsi_tapes[dev];
937     	read_unlock(&st_dev_arr_lock);
938     	STm = &(STp->modes[STp->current_mode]);
939     	STps = &(STp->ps[STp->partition]);
940     
941     	if (STps->rw == ST_WRITING && !(STp->device)->was_reset) {
942     		result = flush_write_buffer(STp);
943     		if (result != 0 && result != (-ENOSPC))
944     			goto out;
945     	}
946     
947     	if (STp->can_partitions &&
948     	    (result2 = update_partition(STp)) < 0) {
949                     DEBC(printk(ST_DEB_MSG
950                                    "st%d: update_partition at close failed.\n", dev));
951     		if (result == 0)
952     			result = result2;
953     		goto out;
954     	}
955     
956     	if (STps->rw == ST_WRITING && !(STp->device)->was_reset) {
957     
958                     DEBC(printk(ST_DEB_MSG "st%d: File length %ld bytes.\n",
959                                 dev, (long) (filp->f_pos));
960                          printk(ST_DEB_MSG "st%d: Async write waits %d, finished %d.\n",
961                                 dev, STp->nbr_waits, STp->nbr_finished);
962     		)
963     
964     		memset(cmd, 0, MAX_COMMAND_SIZE);
965     		cmd[0] = WRITE_FILEMARKS;
966     		cmd[4] = 1 + STp->two_fm;
967     
968     		SRpnt = st_do_scsi(NULL, STp, cmd, 0, SCSI_DATA_NONE,
969     				   STp->timeout, MAX_WRITE_RETRIES, TRUE);
970     		if (!SRpnt) {
971     			result = (STp->buffer)->syscall_result;
972     			goto out;
973     		}
974     
975     		if ((STp->buffer)->syscall_result != 0 &&
976     		    ((SRpnt->sr_sense_buffer[0] & 0x70) != 0x70 ||
977     		     (SRpnt->sr_sense_buffer[2] & 0x4f) != 0x40 ||
978     		     ((SRpnt->sr_sense_buffer[0] & 0x80) != 0 &&
979     		      (SRpnt->sr_sense_buffer[3] | SRpnt->sr_sense_buffer[4] |
980     		       SRpnt->sr_sense_buffer[5] |
981     		       SRpnt->sr_sense_buffer[6]) != 0))) {
982     			/* Filter out successful write at EOM */
983     			scsi_release_request(SRpnt);
984     			SRpnt = NULL;
985     			printk(KERN_ERR "st%d: Error on write filemark.\n", dev);
986     			if (result == 0)
987     				result = (-EIO);
988     		} else {
989     			scsi_release_request(SRpnt);
990     			SRpnt = NULL;
991     			if (STps->drv_file >= 0)
992     				STps->drv_file++;
993     			STps->drv_block = 0;
994     			if (STp->two_fm)
995     				cross_eof(STp, FALSE);
996     			STps->eof = ST_FM;
997     		}
998     
999                     DEBC(printk(ST_DEB_MSG "st%d: Buffer flushed, %d EOF(s) written\n",
1000                                 dev, cmd[4]));
1001     	} else if (!STp->rew_at_close) {
1002     		STps = &(STp->ps[STp->partition]);
1003     		if (!STm->sysv || STps->rw != ST_READING) {
1004     			if (STp->can_bsr)
1005     				result = flush_buffer(STp, 0);
1006     			else if (STps->eof == ST_FM_HIT) {
1007     				result = cross_eof(STp, FALSE);
1008     				if (result) {
1009     					if (STps->drv_file >= 0)
1010     						STps->drv_file++;
1011     					STps->drv_block = 0;
1012     					STps->eof = ST_FM;
1013     				} else
1014     					STps->eof = ST_NOEOF;
1015     			}
1016     		} else if ((STps->eof == ST_NOEOF &&
1017     			    !(result = cross_eof(STp, TRUE))) ||
1018     			   STps->eof == ST_FM_HIT) {
1019     			if (STps->drv_file >= 0)
1020     				STps->drv_file++;
1021     			STps->drv_block = 0;
1022     			STps->eof = ST_FM;
1023     		}
1024     	}
1025     
1026           out:
1027     	if (STp->rew_at_close) {
1028     		result2 = st_int_ioctl(STp, MTREW, 1);
1029     		if (result == 0)
1030     			result = result2;
1031     	}
1032     	return result;
1033     }
1034     
1035     
1036     /* Close the device and release it. BKL is not needed: this is the only thread
1037        accessing this tape. */
1038     static int st_release(struct inode *inode, struct file *filp)
1039     {
1040     	int result = 0;
1041     	Scsi_Tape *STp;
1042     	unsigned long flags;
1043     
1044     	kdev_t devt = inode->i_rdev;
1045     	int dev;
1046     
1047     	dev = TAPE_NR(devt);
1048     	read_lock(&st_dev_arr_lock);
1049     	STp = scsi_tapes[dev];
1050     	read_unlock(&st_dev_arr_lock);
1051     
1052     	if (STp->door_locked == ST_LOCKED_AUTO)
1053     		st_int_ioctl(STp, MTUNLOCK, 0);
1054     
1055     	if (STp->buffer != NULL) {
1056     		normalize_buffer(STp->buffer);
1057     		write_lock_irqsave(&st_dev_arr_lock, flags);
1058     		(STp->buffer)->in_use = 0;
1059     		STp->buffer = NULL;
1060     	}
1061     	else {
1062     		write_lock_irqsave(&st_dev_arr_lock, flags);
1063     	}
1064     
1065     	STp->in_use = 0;
1066     	write_unlock_irqrestore(&st_dev_arr_lock, flags);
1067     	if (STp->device->host->hostt->module)
1068     		__MOD_DEC_USE_COUNT(STp->device->host->hostt->module);
1069     
1070     	return result;
1071     }
1072     
1073     
1074     /* Write command */
1075     static ssize_t
1076      st_write(struct file *filp, const char *buf, size_t count, loff_t * ppos)
1077     {
1078     	struct inode *inode = filp->f_dentry->d_inode;
1079     	ssize_t total;
1080     	ssize_t i, do_count, blks, transfer;
1081     	ssize_t retval = 0;
1082     	int write_threshold;
1083     	int doing_write = 0;
1084     	unsigned char cmd[MAX_COMMAND_SIZE];
1085     	const char *b_point;
1086     	Scsi_Request *SRpnt = NULL;
1087     	Scsi_Tape *STp;
1088     	ST_mode *STm;
1089     	ST_partstat *STps;
1090     	int dev = TAPE_NR(inode->i_rdev);
1091     
1092     	read_lock(&st_dev_arr_lock);
1093     	STp = scsi_tapes[dev];
1094     	read_unlock(&st_dev_arr_lock);
1095     
1096     	if (down_interruptible(&STp->lock))
1097     		return -ERESTARTSYS;
1098     
1099     	/*
1100     	 * If we are in the middle of error recovery, don't let anyone
1101     	 * else try and use this device.  Also, if error recovery fails, it
1102     	 * may try and take the device offline, in which case all further
1103     	 * access to the device is prohibited.
1104     	 */
1105     	if (!scsi_block_when_processing_errors(STp->device)) {
1106     		retval = (-ENXIO);
1107     		goto out;
1108     	}
1109     
1110     	if (ppos != &filp->f_pos) {
1111     		/* "A request was outside the capabilities of the device." */
1112     		retval = (-ENXIO);
1113     		goto out;
1114     	}
1115     
1116     	if (STp->ready != ST_READY) {
1117     		if (STp->ready == ST_NO_TAPE)
1118     			retval = (-ENOMEDIUM);
1119     		else
1120     			retval = (-EIO);
1121     		goto out;
1122     	}
1123     
1124     	STm = &(STp->modes[STp->current_mode]);
1125     	if (!STm->defined) {
1126     		retval = (-ENXIO);
1127     		goto out;
1128     	}
1129     	if (count == 0)
1130     		goto out;
1131     
1132     	/*
1133     	 * If there was a bus reset, block further access
1134     	 * to this device.
1135     	 */
1136     	if (STp->device->was_reset) {
1137     		retval = (-EIO);
1138     		goto out;
1139     	}
1140     
1141             DEB(
1142     	if (!STp->in_use) {
1143     		printk(ST_DEB_MSG "st%d: Incorrect device.\n", dev);
1144     		retval = (-EIO);
1145     		goto out;
1146     	} ) /* end DEB */
1147     
1148     	/* Write must be integral number of blocks */
1149     	if (STp->block_size != 0 && (count % STp->block_size) != 0) {
1150     		printk(KERN_WARNING "st%d: Write not multiple of tape block size.\n",
1151     		       dev);
1152     		retval = (-EINVAL);
1153     		goto out;
1154     	}
1155     
1156     	if (STp->can_partitions &&
1157     	    (retval = update_partition(STp)) < 0)
1158     		goto out;
1159     	STps = &(STp->ps[STp->partition]);
1160     
1161     	if (STp->write_prot) {
1162     		retval = (-EACCES);
1163     		goto out;
1164     	}
1165     
1166     	if (STp->block_size == 0) {
1167     		if (STp->max_block > 0 &&
1168     		    (count < STp->min_block || count > STp->max_block)) {
1169     			retval = (-EINVAL);
1170     			goto out;
1171     		}
1172     		if (count > (STp->buffer)->buffer_size &&
1173     		    !enlarge_buffer(STp->buffer, count, STp->restr_dma)) {
1174     			retval = (-EOVERFLOW);
1175     			goto out;
1176     		}
1177     	}
1178     	if ((STp->buffer)->buffer_blocks < 1) {
1179     		/* Fixed block mode with too small buffer */
1180     		if (!enlarge_buffer(STp->buffer, STp->block_size, STp->restr_dma)) {
1181     			retval = (-EOVERFLOW);
1182     			goto out;
1183     		}
1184     		(STp->buffer)->buffer_blocks = 1;
1185     	}
1186     
1187     	if (STp->do_auto_lock && STp->door_locked == ST_UNLOCKED &&
1188     	    !st_int_ioctl(STp, MTLOCK, 0))
1189     		STp->door_locked = ST_LOCKED_AUTO;
1190     
1191     	if (STps->rw == ST_READING) {
1192     		retval = flush_buffer(STp, 0);
1193     		if (retval)
1194     			goto out;
1195     		STps->rw = ST_WRITING;
1196     	} else if (STps->rw != ST_WRITING &&
1197     		   STps->drv_file == 0 && STps->drv_block == 0) {
1198     		if ((retval = set_mode_densblk(STp, STm)) < 0)
1199     			goto out;
1200     		if (STm->default_compression != ST_DONT_TOUCH &&
1201     		    !(STp->compression_changed)) {
1202     			if (st_compression(STp, (STm->default_compression == ST_YES))) {
1203     				printk(KERN_WARNING "st%d: Can't set default compression.\n",
1204     				       dev);
1205     				if (modes_defined) {
1206     					retval = (-EINVAL);
1207     					goto out;
1208     				}
1209     			}
1210     		}
1211     	}
1212     
1213     	if ((STp->buffer)->writing) {
1214     		write_behind_check(STp);
1215     		if ((STp->buffer)->syscall_result) {
1216                             DEBC(printk(ST_DEB_MSG "st%d: Async write error (write) %x.\n",
1217                                         dev, (STp->buffer)->midlevel_result));
1218     			if ((STp->buffer)->midlevel_result == INT_MAX)
1219     				STps->eof = ST_EOM_OK;
1220     			else
1221     				STps->eof = ST_EOM_ERROR;
1222     		}
1223     	}
1224     
1225     	if (STps->eof == ST_EOM_OK) {
1226     		retval = (-ENOSPC);
1227     		goto out;
1228     	}
1229     	else if (STps->eof == ST_EOM_ERROR) {
1230     		retval = (-EIO);
1231     		goto out;
1232     	}
1233     
1234     	/* Check the buffer readability in cases where copy_user might catch
1235     	   the problems after some tape movement. */
1236     	if (STp->block_size != 0 &&
1237     	    (copy_from_user(&i, buf, 1) != 0 ||
1238     	     copy_from_user(&i, buf + count - 1, 1) != 0)) {
1239     		retval = (-EFAULT);
1240     		goto out;
1241     	}
1242     
1243     	if (!STm->do_buffer_writes) {
1244     #if 0
1245     		if (STp->block_size != 0 && (count % STp->block_size) != 0) {
1246     			retval = (-EINVAL);	/* Write must be integral number of blocks */
1247     			goto out;
1248     		}
1249     #endif
1250     		write_threshold = 1;
1251     	} else
1252     		write_threshold = (STp->buffer)->buffer_blocks * STp->block_size;
1253     	if (!STm->do_async_writes)
1254     		write_threshold--;
1255     
1256     	total = count;
1257     
1258     	memset(cmd, 0, MAX_COMMAND_SIZE);
1259     	cmd[0] = WRITE_6;
1260     	cmd[1] = (STp->block_size != 0);
1261     
1262     	STps->rw = ST_WRITING;
1263     
1264     	b_point = buf;
1265     	while ((STp->block_size == 0 && !STm->do_async_writes && count > 0) ||
1266     	       (STp->block_size != 0 &&
1267     		(STp->buffer)->buffer_bytes + count > write_threshold)) {
1268     		doing_write = 1;
1269     		if (STp->block_size == 0)
1270     			do_count = count;
1271     		else {
1272     			do_count = (STp->buffer)->buffer_blocks * STp->block_size -
1273     			    (STp->buffer)->buffer_bytes;
1274     			if (do_count > count)
1275     				do_count = count;
1276     		}
1277     
1278     		i = append_to_buffer(b_point, STp->buffer, do_count);
1279     		if (i) {
1280     			retval = i;
1281     			goto out;
1282     		}
1283     
1284     		if (STp->block_size == 0)
1285     			blks = transfer = do_count;
1286     		else {
1287     			blks = (STp->buffer)->buffer_bytes /
1288     			    STp->block_size;
1289     			transfer = blks * STp->block_size;
1290     		}
1291     		cmd[2] = blks >> 16;
1292     		cmd[3] = blks >> 8;
1293     		cmd[4] = blks;
1294     
1295     		SRpnt = st_do_scsi(SRpnt, STp, cmd, transfer, SCSI_DATA_WRITE,
1296     				   STp->timeout, MAX_WRITE_RETRIES, TRUE);
1297     		if (!SRpnt) {
1298     			retval = (STp->buffer)->syscall_result;
1299     			goto out;
1300     		}
1301     
1302     		if ((STp->buffer)->syscall_result != 0) {
1303                             DEBC(printk(ST_DEB_MSG "st%d: Error on write:\n", dev));
1304     			if ((SRpnt->sr_sense_buffer[0] & 0x70) == 0x70 &&
1305     			    (SRpnt->sr_sense_buffer[2] & 0x40)) {
1306     				if ((SRpnt->sr_sense_buffer[0] & 0x80) != 0)
1307     					transfer = (SRpnt->sr_sense_buffer[3] << 24) |
1308     					    (SRpnt->sr_sense_buffer[4] << 16) |
1309     					    (SRpnt->sr_sense_buffer[5] << 8) |
1310                                                     SRpnt->sr_sense_buffer[6];
1311     				else if (STp->block_size == 0 &&
1312     					 (SRpnt->sr_sense_buffer[2] & 0x0f) ==
1313                                              VOLUME_OVERFLOW)
1314     					transfer = do_count;
1315     				else
1316     					transfer = 0;
1317     				if (STp->block_size != 0)
1318     					transfer *= STp->block_size;
1319     				if (transfer <= do_count) {
1320     					filp->f_pos += do_count - transfer;
1321     					count -= do_count - transfer;
1322     					if (STps->drv_block >= 0) {
1323     						if (STp->block_size == 0 &&
1324                                                         transfer < do_count)
1325     							STps->drv_block++;
1326     						else if (STp->block_size != 0)
1327     							STps->drv_block +=
1328                                                                     (do_count - transfer) /
1329                                                                     STp->block_size;
1330     					}
1331     					STps->eof = ST_EOM_OK;
1332     					retval = (-ENOSPC); /* EOM within current request */
1333                                             DEBC(printk(ST_DEB_MSG
1334                                                            "st%d: EOM with %d bytes unwritten.\n",
1335     						       dev, transfer));
1336     				} else {
1337     					STps->eof = ST_EOM_ERROR;
1338     					STps->drv_block = (-1); /* Too cautious? */
1339     					retval = (-EIO);	/* EOM for old data */
1340     					DEBC(printk(ST_DEB_MSG
1341                                                            "st%d: EOM with lost data.\n",
1342                                                            dev));
1343     				}
1344     			} else {
1345     				STps->drv_block = (-1);		/* Too cautious? */
1346     				retval = (-EIO);
1347     			}
1348     
1349     			scsi_release_request(SRpnt);
1350     			SRpnt = NULL;
1351     			(STp->buffer)->buffer_bytes = 0;
1352     			STp->dirty = 0;
1353     			if (count < total)
1354     				retval = total - count;
1355     			goto out;
1356     		}
1357     		filp->f_pos += do_count;
1358     		b_point += do_count;
1359     		count -= do_count;
1360     		if (STps->drv_block >= 0) {
1361     			if (STp->block_size == 0)
1362     				STps->drv_block++;
1363     			else
1364     				STps->drv_block += blks;
1365     		}
1366     		(STp->buffer)->buffer_bytes = 0;
1367     		STp->dirty = 0;
1368     	}
1369     	if (count != 0) {
1370     		STp->dirty = 1;
1371     		i = append_to_buffer(b_point, STp->buffer, count);
1372     		if (i) {
1373     			retval = i;
1374     			goto out;
1375     		}
1376     		filp->f_pos += count;
1377     		count = 0;
1378     	}
1379     
1380     	if (doing_write && (STp->buffer)->syscall_result != 0) {
1381     		retval = (STp->buffer)->syscall_result;
1382     		goto out;
1383     	}
1384     
1385     	if (STm->do_async_writes &&
1386     	    (((STp->buffer)->buffer_bytes >= STp->write_threshold &&
1387     	      (STp->buffer)->buffer_bytes >= STp->block_size) ||
1388     	     STp->block_size == 0)) {
1389     		/* Schedule an asynchronous write */
1390     		if (STp->block_size == 0)
1391     			(STp->buffer)->writing = (STp->buffer)->buffer_bytes;
1392     		else
1393     			(STp->buffer)->writing = ((STp->buffer)->buffer_bytes /
1394     				      STp->block_size) * STp->block_size;
1395     		STp->dirty = !((STp->buffer)->writing ==
1396     			       (STp->buffer)->buffer_bytes);
1397     
1398     		if (STp->block_size == 0)
1399     			blks = (STp->buffer)->writing;
1400     		else
1401     			blks = (STp->buffer)->writing / STp->block_size;
1402     		cmd[2] = blks >> 16;
1403     		cmd[3] = blks >> 8;
1404     		cmd[4] = blks;
1405     		DEB( STp->write_pending = 1; )
1406     
1407     		SRpnt = st_do_scsi(SRpnt, STp, cmd, (STp->buffer)->writing,
1408     				   SCSI_DATA_WRITE, STp->timeout,
1409     				   MAX_WRITE_RETRIES, FALSE);
1410     		if (SRpnt == NULL) {
1411     			retval = (STp->buffer)->syscall_result;
1412     			goto out;
1413     		}
1414     		SRpnt = NULL;  /* Prevent releasing this request! */
1415     
1416     	}
1417     	STps->at_sm &= (total == 0);
1418     	if (total > 0)
1419     		STps->eof = ST_NOEOF;
1420     	retval = total;
1421     
1422      out:
1423     	if (SRpnt != NULL)
1424     		scsi_release_request(SRpnt);
1425     	up(&STp->lock);
1426     
1427     	return retval;
1428     }
1429     
1430     /* Read data from the tape. Returns zero in the normal case, one if the
1431        eof status has changed, and the negative error code in case of a
1432        fatal error. Otherwise updates the buffer and the eof state. */
1433     static long read_tape(Scsi_Tape *STp, long count, Scsi_Request ** aSRpnt)
1434     {
1435     	int transfer, blks, bytes;
1436     	unsigned char cmd[MAX_COMMAND_SIZE];
1437     	Scsi_Request *SRpnt;
1438     	ST_mode *STm;
1439     	ST_partstat *STps;
1440     	int dev = TAPE_NR(STp->devt);
1441     	int retval = 0;
1442     
1443     	if (count == 0)
1444     		return 0;
1445     
1446     	STm = &(STp->modes[STp->current_mode]);
1447     	STps = &(STp->ps[STp->partition]);
1448     	if (STps->eof == ST_FM_HIT)
1449     		return 1;
1450     
1451     	memset(cmd, 0, MAX_COMMAND_SIZE);
1452     	cmd[0] = READ_6;
1453     	cmd[1] = (STp->block_size != 0);
1454     	if (STp->block_size == 0)
1455     		blks = bytes = count;
1456     	else {
1457     		if (STm->do_read_ahead) {
1458     			blks = (STp->buffer)->buffer_blocks;
1459     			bytes = blks * STp->block_size;
1460     		} else {
1461     			bytes = count;
1462     			if (bytes > (STp->buffer)->buffer_size)
1463     				bytes = (STp->buffer)->buffer_size;
1464     			blks = bytes / STp->block_size;
1465     			bytes = blks * STp->block_size;
1466     		}
1467     	}
1468     	cmd[2] = blks >> 16;
1469     	cmd[3] = blks >> 8;
1470     	cmd[4] = blks;
1471     
1472     	SRpnt = *aSRpnt;
1473     	SRpnt = st_do_scsi(SRpnt, STp, cmd, bytes, SCSI_DATA_READ,
1474     			   STp->timeout, MAX_RETRIES, TRUE);
1475     	*aSRpnt = SRpnt;
1476     	if (!SRpnt)
1477     		return (STp->buffer)->syscall_result;
1478     
1479     	(STp->buffer)->read_pointer = 0;
1480     	STps->at_sm = 0;
1481     
1482     	/* Something to check */
1483     	if ((STp->buffer)->syscall_result) {
1484     		retval = 1;
1485     		DEBC(printk(ST_DEB_MSG "st%d: Sense: %2x %2x %2x %2x %2x %2x %2x %2x\n",
1486                                 dev,
1487                                 SRpnt->sr_sense_buffer[0], SRpnt->sr_sense_buffer[1],
1488                                 SRpnt->sr_sense_buffer[2], SRpnt->sr_sense_buffer[3],
1489                                 SRpnt->sr_sense_buffer[4], SRpnt->sr_sense_buffer[5],
1490                                 SRpnt->sr_sense_buffer[6], SRpnt->sr_sense_buffer[7]));
1491     		if ((SRpnt->sr_sense_buffer[0] & 0x70) == 0x70) {	/* extended sense */
1492     
1493     			if ((SRpnt->sr_sense_buffer[2] & 0x0f) == BLANK_CHECK)
1494     				SRpnt->sr_sense_buffer[2] &= 0xcf;	/* No need for EOM in this case */
1495     
1496     			if ((SRpnt->sr_sense_buffer[2] & 0xe0) != 0) { /* EOF, EOM, or ILI */
1497     				/* Compute the residual count */
1498     				if ((SRpnt->sr_sense_buffer[0] & 0x80) != 0)
1499     					transfer = (SRpnt->sr_sense_buffer[3] << 24) |
1500     					    (SRpnt->sr_sense_buffer[4] << 16) |
1501     					    (SRpnt->sr_sense_buffer[5] << 8) |
1502     					    SRpnt->sr_sense_buffer[6];
1503     				else
1504     					transfer = 0;
1505     				if (STp->block_size == 0 &&
1506     				    (SRpnt->sr_sense_buffer[2] & 0x0f) == MEDIUM_ERROR)
1507     					transfer = bytes;
1508     
1509     				if (SRpnt->sr_sense_buffer[2] & 0x20) {	/* ILI */
1510     					if (STp->block_size == 0) {
1511     						if (transfer < 0) {
1512     							if (STps->drv_block >= 0)
1513     								STps->drv_block += 1;
1514     							return (-ENOMEM);
1515     						}
1516     						(STp->buffer)->buffer_bytes = bytes - transfer;
1517     					} else {
1518     						scsi_release_request(SRpnt);
1519     						SRpnt = *aSRpnt = NULL;
1520     						if (transfer == blks) {	/* We did not get anything, error */
1521     							printk(KERN_NOTICE "st%d: Incorrect block size.\n", dev);
1522     							if (STps->drv_block >= 0)
1523     								STps->drv_block += blks - transfer + 1;
1524     							st_int_ioctl(STp, MTBSR, 1);
1525     							return (-EIO);
1526     						}
1527     						/* We have some data, deliver it */
1528     						(STp->buffer)->buffer_bytes = (blks - transfer) *
1529     						    STp->block_size;
1530                                                     DEBC(printk(ST_DEB_MSG
1531                                                                 "st%d: ILI but enough data received %ld %d.\n",
1532                                                                 dev, count, (STp->buffer)->buffer_bytes));
1533     						if (STps->drv_block >= 0)
1534     							STps->drv_block += 1;
1535     						if (st_int_ioctl(STp, MTBSR, 1))
1536     							return (-EIO);
1537     					}
1538     				} else if (SRpnt->sr_sense_buffer[2] & 0x80) {	/* FM overrides EOM */
1539     					if (STps->eof != ST_FM_HIT)
1540     						STps->eof = ST_FM_HIT;
1541     					else
1542     						STps->eof = ST_EOD_2;
1543     					if (STp->block_size == 0)
1544     						(STp->buffer)->buffer_bytes = 0;
1545     					else
1546     						(STp->buffer)->buffer_bytes =
1547     						    bytes - transfer * STp->block_size;
1548                                             DEBC(printk(ST_DEB_MSG
1549                                                         "st%d: EOF detected (%d bytes read).\n",
1550                                                         dev, (STp->buffer)->buffer_bytes));
1551     				} else if (SRpnt->sr_sense_buffer[2] & 0x40) {
1552     					if (STps->eof == ST_FM)
1553     						STps->eof = ST_EOD_1;
1554     					else
1555     						STps->eof = ST_EOM_OK;
1556     					if (STp->block_size == 0)
1557     						(STp->buffer)->buffer_bytes = bytes - transfer;
1558     					else
1559     						(STp->buffer)->buffer_bytes =
1560     						    bytes - transfer * STp->block_size;
1561     
1562                                             DEBC(printk(ST_DEB_MSG "st%d: EOM detected (%d bytes read).\n",
1563                                                         dev, (STp->buffer)->buffer_bytes));
1564     				}
1565     			}
1566     			/* end of EOF, EOM, ILI test */ 
1567     			else {	/* nonzero sense key */
1568                                     DEBC(printk(ST_DEB_MSG
1569                                                 "st%d: Tape error while reading.\n", dev));
1570     				STps->drv_block = (-1);
1571     				if (STps->eof == ST_FM &&
1572     				    (SRpnt->sr_sense_buffer[2] & 0x0f) == BLANK_CHECK) {
1573                                             DEBC(printk(ST_DEB_MSG
1574                                                         "st%d: Zero returned for first BLANK CHECK after EOF.\n",
1575                                                         dev));
1576     					STps->eof = ST_EOD_2;	/* First BLANK_CHECK after FM */
1577     				} else	/* Some other extended sense code */
1578     					retval = (-EIO);
1579     			}
1580     		}
1581     		/* End of extended sense test */ 
1582     		else {		/* Non-extended sense */
1583     			retval = (STp->buffer)->syscall_result;
1584     		}
1585     
1586     	}
1587     	/* End of error handling */ 
1588     	else			/* Read successful */
1589     		(STp->buffer)->buffer_bytes = bytes;
1590     
1591     	if (STps->drv_block >= 0) {
1592     		if (STp->block_size == 0)
1593     			STps->drv_block++;
1594     		else
1595     			STps->drv_block += (STp->buffer)->buffer_bytes / STp->block_size;
1596     	}
1597     	return retval;
1598     }
1599     
1600     
1601     /* Read command */
1602     static ssize_t
1603      st_read(struct file *filp, char *buf, size_t count, loff_t * ppos)
1604     {
1605     	struct inode *inode = filp->f_dentry->d_inode;
1606     	ssize_t total;
1607     	ssize_t retval = 0;
1608     	ssize_t i, transfer;
1609     	int special;
1610     	Scsi_Request *SRpnt = NULL;
1611     	Scsi_Tape *STp;
1612     	ST_mode *STm;
1613     	ST_partstat *STps;
1614     	int dev = TAPE_NR(inode->i_rdev);
1615     
1616     	read_lock(&st_dev_arr_lock);
1617     	STp = scsi_tapes[dev];
1618     	read_unlock(&st_dev_arr_lock);
1619     
1620     	if (down_interruptible(&STp->lock))
1621     		return -ERESTARTSYS;
1622     
1623     	/*
1624     	 * If we are in the middle of error recovery, don't let anyone
1625     	 * else try and use this device.  Also, if error recovery fails, it
1626     	 * may try and take the device offline, in which case all further
1627     	 * access to the device is prohibited.
1628     	 */
1629     	if (!scsi_block_when_processing_errors(STp->device)) {
1630     		retval = (-ENXIO);
1631     		goto out;
1632     	}
1633     
1634     	if (ppos != &filp->f_pos) {
1635     		/* "A request was outside the capabilities of the device." */
1636     		retval = (-ENXIO);
1637     		goto out;
1638     	}
1639     
1640     	if (STp->ready != ST_READY) {
1641     		if (STp->ready == ST_NO_TAPE)
1642     			retval = (-ENOMEDIUM);
1643     		else
1644     			retval = (-EIO);
1645     		goto out;
1646     	}
1647     	STm = &(STp->modes[STp->current_mode]);
1648     	if (!STm->defined) {
1649     		retval = (-ENXIO);
1650     		goto out;
1651     	}
1652             DEB(
1653     	if (!STp->in_use) {
1654     		printk(ST_DEB_MSG "st%d: Incorrect device.\n", dev);
1655     		retval = (-EIO);
1656     		goto out;
1657     	} ) /* end DEB */
1658     
1659     	if (STp->can_partitions &&
1660     	    (retval = update_partition(STp)) < 0)
1661     		goto out;
1662     
1663     	if (STp->block_size == 0) {
1664     		if (STp->max_block > 0 &&
1665     		    (count < STp->min_block || count > STp->max_block)) {
1666     			retval = (-EINVAL);
1667     			goto out;
1668     		}
1669     		if (count > (STp->buffer)->buffer_size &&
1670     		    !enlarge_buffer(STp->buffer, count, STp->restr_dma)) {
1671     			retval = (-EOVERFLOW);
1672     			goto out;
1673     		}
1674     	}
1675     	if ((STp->buffer)->buffer_blocks < 1) {
1676     		/* Fixed block mode with too small buffer */
1677     		if (!enlarge_buffer(STp->buffer, STp->block_size, STp->restr_dma)) {
1678     			retval = (-EOVERFLOW);
1679     			goto out;
1680     		}
1681     		(STp->buffer)->buffer_blocks = 1;
1682     	}
1683     
1684     	if (!(STm->do_read_ahead) && STp->block_size != 0 &&
1685     	    (count % STp->block_size) != 0) {
1686     		retval = (-EINVAL);	/* Read must be integral number of blocks */
1687     		goto out;
1688     	}
1689     
1690     	if (STp->do_auto_lock && STp->door_locked == ST_UNLOCKED &&
1691     	    !st_int_ioctl(STp, MTLOCK, 0))
1692     		STp->door_locked = ST_LOCKED_AUTO;
1693     
1694     	STps = &(STp->ps[STp->partition]);
1695     	if (STps->rw == ST_WRITING) {
1696     		retval = flush_buffer(STp, 0);
1697     		if (retval)
1698     			goto out;
1699     		STps->rw = ST_READING;
1700     	}
1701             DEB(
1702     	if (debugging && STps->eof != ST_NOEOF)
1703     		printk(ST_DEB_MSG "st%d: EOF/EOM flag up (%d). Bytes %d\n", dev,
1704     		       STps->eof, (STp->buffer)->buffer_bytes);
1705             ) /* end DEB */
1706     
1707     	if ((STp->buffer)->buffer_bytes == 0 &&
1708     	    STps->eof >= ST_EOD_1) {
1709     		if (STps->eof < ST_EOD) {
1710     			STps->eof += 1;
1711     			retval = 0;
1712     			goto out;
1713     		}
1714     		retval = (-EIO);	/* EOM or Blank Check */
1715     		goto out;
1716     	}
1717     
1718     	/* Check the buffer writability before any tape movement. Don't alter
1719     	   buffer data. */
1720     	if (copy_from_user(&i, buf, 1) != 0 ||
1721     	    copy_to_user(buf, &i, 1) != 0 ||
1722     	    copy_from_user(&i, buf + count - 1, 1) != 0 ||
1723     	    copy_to_user(buf + count - 1, &i, 1) != 0) {
1724     		retval = (-EFAULT);
1725     		goto out;
1726     	}
1727     
1728     	STps->rw = ST_READING;
1729     
1730     
1731     	/* Loop until enough data in buffer or a special condition found */
1732     	for (total = 0, special = 0; total < count && !special;) {
1733     
1734     		/* Get new data if the buffer is empty */
1735     		if ((STp->buffer)->buffer_bytes == 0) {
1736     			special = read_tape(STp, count - total, &SRpnt);
1737     			if (special < 0) {	/* No need to continue read */
1738     				retval = special;
1739     				goto out;
1740     			}
1741     		}
1742     
1743     		/* Move the data from driver buffer to user buffer */
1744     		if ((STp->buffer)->buffer_bytes > 0) {
1745                             DEB(
1746     			if (debugging && STps->eof != ST_NOEOF)
1747     				printk(ST_DEB_MSG
1748                                            "st%d: EOF up (%d). Left %d, needed %d.\n", dev,
1749     				       STps->eof, (STp->buffer)->buffer_bytes,
1750                                            count - total);
1751                             ) /* end DEB */
1752     			transfer = (STp->buffer)->buffer_bytes < count - total ?
1753     			    (STp->buffer)->buffer_bytes : count - total;
1754     			i = from_buffer(STp->buffer, buf, transfer);
1755     			if (i) {
1756     				retval = i;
1757     				goto out;
1758     			}
1759     			filp->f_pos += transfer;
1760     			buf += transfer;
1761     			total += transfer;
1762     		}
1763     
1764     		if (STp->block_size == 0)
1765     			break;	/* Read only one variable length block */
1766     
1767     	}			/* for (total = 0, special = 0;
1768                                        total < count && !special; ) */
1769     
1770     	/* Change the eof state if no data from tape or buffer */
1771     	if (total == 0) {
1772     		if (STps->eof == ST_FM_HIT) {
1773     			STps->eof = ST_FM;
1774     			STps->drv_block = 0;
1775     			if (STps->drv_file >= 0)
1776     				STps->drv_file++;
1777     		} else if (STps->eof == ST_EOD_1) {
1778     			STps->eof = ST_EOD_2;
1779     			STps->drv_block = 0;
1780     			if (STps->drv_file >= 0)
1781     				STps->drv_file++;
1782     		} else if (STps->eof == ST_EOD_2)
1783     			STps->eof = ST_EOD;
1784     	} else if (STps->eof == ST_FM)
1785     		STps->eof = ST_NOEOF;
1786     	retval = total;
1787     
1788      out:
1789     	if (SRpnt != NULL) {
1790     		scsi_release_request(SRpnt);
1791     		SRpnt = NULL;
1792     	}
1793     	up(&STp->lock);
1794     
1795     	return retval;
1796     }
1797     
1798     
1799     
1800     /* Set the driver options */
1801     static void st_log_options(Scsi_Tape * STp, ST_mode * STm, int dev)
1802     {
1803     	printk(KERN_INFO
1804     	       "st%d: Mode %d options: buffer writes: %d, async writes: %d, read ahead: %d\n",
1805     	       dev, STp->current_mode, STm->do_buffer_writes, STm->do_async_writes,
1806     	       STm->do_read_ahead);
1807     	printk(KERN_INFO
1808     	       "st%d:    can bsr: %d, two FMs: %d, fast mteom: %d, auto lock: %d,\n",
1809     	       dev, STp->can_bsr, STp->two_fm, STp->fast_mteom, STp->do_auto_lock);
1810     	printk(KERN_INFO
1811     	       "st%d:    defs for wr: %d, no block limits: %d, partitions: %d, s2 log: %d\n",
1812     	       dev, STm->defaults_for_writes, STp->omit_blklims, STp->can_partitions,
1813     	       STp->scsi2_logical);
1814     	printk(KERN_INFO
1815     	       "st%d:    sysv: %d\n", dev, STm->sysv);
1816             DEB(printk(KERN_INFO
1817                        "st%d:    debugging: %d\n",
1818                        dev, debugging);)
1819     }
1820     
1821     
1822     static int st_set_options(Scsi_Tape *STp, long options)
1823     {
1824     	int value;
1825     	long code;
1826     	ST_mode *STm;
1827     	int dev = TAPE_NR(STp->devt);
1828     
1829     	STm = &(STp->modes[STp->current_mode]);
1830     	if (!STm->defined) {
1831     		memcpy(STm, &(STp->modes[0]), sizeof(ST_mode));
1832     		modes_defined = TRUE;
1833                     DEBC(printk(ST_DEB_MSG
1834                                 "st%d: Initialized mode %d definition from mode 0\n",
1835                                 dev, STp->current_mode));
1836     	}
1837     
1838     	code = options & MT_ST_OPTIONS;
1839     	if (code == MT_ST_BOOLEANS) {
1840     		STm->do_buffer_writes = (options & MT_ST_BUFFER_WRITES) != 0;
1841     		STm->do_async_writes = (options & MT_ST_ASYNC_WRITES) != 0;
1842     		STm->defaults_for_writes = (options & MT_ST_DEF_WRITES) != 0;
1843     		STm->do_read_ahead = (options & MT_ST_READ_AHEAD) != 0;
1844     		STp->two_fm = (options & MT_ST_TWO_FM) != 0;
1845     		STp->fast_mteom = (options & MT_ST_FAST_MTEOM) != 0;
1846     		STp->do_auto_lock = (options & MT_ST_AUTO_LOCK) != 0;
1847     		STp->can_bsr = (options & MT_ST_CAN_BSR) != 0;
1848     		STp->omit_blklims = (options & MT_ST_NO_BLKLIMS) != 0;
1849     		if ((STp->device)->scsi_level >= SCSI_2)
1850     			STp->can_partitions = (options & MT_ST_CAN_PARTITIONS) != 0;
1851     		STp->scsi2_logical = (options & MT_ST_SCSI2LOGICAL) != 0;
1852     		STm->sysv = (options & MT_ST_SYSV) != 0;
1853     		DEB( debugging = (options & MT_ST_DEBUGGING) != 0; )
1854     		st_log_options(STp, STm, dev);
1855     	} else if (code == MT_ST_SETBOOLEANS || code == MT_ST_CLEARBOOLEANS) {
1856     		value = (code == MT_ST_SETBOOLEANS);
1857     		if ((options & MT_ST_BUFFER_WRITES) != 0)
1858     			STm->do_buffer_writes = value;
1859     		if ((options & MT_ST_ASYNC_WRITES) != 0)
1860     			STm->do_async_writes = value;
1861     		if ((options & MT_ST_DEF_WRITES) != 0)
1862     			STm->defaults_for_writes = value;
1863     		if ((options & MT_ST_READ_AHEAD) != 0)
1864     			STm->do_read_ahead = value;
1865     		if ((options & MT_ST_TWO_FM) != 0)
1866     			STp->two_fm = value;
1867     		if ((options & MT_ST_FAST_MTEOM) != 0)
1868     			STp->fast_mteom = value;
1869     		if ((options & MT_ST_AUTO_LOCK) != 0)
1870     			STp->do_auto_lock = value;
1871     		if ((options & MT_ST_CAN_BSR) != 0)
1872     			STp->can_bsr = value;
1873     		if ((options & MT_ST_NO_BLKLIMS) != 0)
1874     			STp->omit_blklims = value;
1875     		if ((STp->device)->scsi_level >= SCSI_2 &&
1876     		    (options & MT_ST_CAN_PARTITIONS) != 0)
1877     			STp->can_partitions = value;
1878     		if ((options & MT_ST_SCSI2LOGICAL) != 0)
1879     			STp->scsi2_logical = value;
1880     		if ((options & MT_ST_SYSV) != 0)
1881     			STm->sysv = value;
1882                     DEB(
1883     		if ((options & MT_ST_DEBUGGING) != 0)
1884     			debugging = value; )
1885     		st_log_options(STp, STm, dev);
1886     	} else if (code == MT_ST_WRITE_THRESHOLD) {
1887     		value = (options & ~MT_ST_OPTIONS) * ST_KILOBYTE;
1888     		if (value < 1 || value > st_buffer_size) {
1889     			printk(KERN_WARNING
1890                                    "st%d: Write threshold %d too small or too large.\n",
1891     			       dev, value);
1892     			return (-EIO);
1893     		}
1894     		STp->write_threshold = value;
1895     		printk(KERN_INFO "st%d: Write threshold set to %d bytes.\n",
1896     		       dev, value);
1897     	} else if (code == MT_ST_DEF_BLKSIZE) {
1898     		value = (options & ~MT_ST_OPTIONS);
1899     		if (value == ~MT_ST_OPTIONS) {
1900     			STm->default_blksize = (-1);
1901     			printk(KERN_INFO "st%d: Default block size disabled.\n", dev);
1902     		} else {
1903     			STm->default_blksize = value;
1904     			printk(KERN_INFO "st%d: Default block size set to %d bytes.\n",
1905     			       dev, STm->default_blksize);
1906     		}
1907     	} else if (code == MT_ST_TIMEOUTS) {
1908     		value = (options & ~MT_ST_OPTIONS);
1909     		if ((value & MT_ST_SET_LONG_TIMEOUT) != 0) {
1910     			STp->long_timeout = (value & ~MT_ST_SET_LONG_TIMEOUT) * HZ;
1911     			printk(KERN_INFO "st%d: Long timeout set to %d seconds.\n", dev,
1912     			       (value & ~MT_ST_SET_LONG_TIMEOUT));
1913     		} else {
1914     			STp->timeout = value * HZ;
1915     			printk(KERN_INFO "st%d: Normal timeout set to %d seconds.\n",
1916                                    dev, value);
1917     		}
1918     	} else if (code == MT_ST_DEF_OPTIONS) {
1919     		code = (options & ~MT_ST_CLEAR_DEFAULT);
1920     		value = (options & MT_ST_CLEAR_DEFAULT);
1921     		if (code == MT_ST_DEF_DENSITY) {
1922     			if (value == MT_ST_CLEAR_DEFAULT) {
1923     				STm->default_density = (-1);
1924     				printk(KERN_INFO "st%d: Density default disabled.\n",
1925                                            dev);
1926     			} else {
1927     				STm->default_density = value & 0xff;
1928     				printk(KERN_INFO "st%d: Density default set to %x\n",
1929     				       dev, STm->default_density);
1930     			}
1931     		} else if (code == MT_ST_DEF_DRVBUFFER) {
1932     			if (value == MT_ST_CLEAR_DEFAULT) {
1933     				STp->default_drvbuffer = 0xff;
1934     				printk(KERN_INFO
1935                                            "st%d: Drive buffer default disabled.\n", dev);
1936     			} else {
1937     				STp->default_drvbuffer = value & 7;
1938     				printk(KERN_INFO
1939                                            "st%d: Drive buffer default set to %x\n",
1940     				       dev, STp->default_drvbuffer);
1941     			}
1942     		} else if (code == MT_ST_DEF_COMPRESSION) {
1943     			if (value == MT_ST_CLEAR_DEFAULT) {
1944     				STm->default_compression = ST_DONT_TOUCH;
1945     				printk(KERN_INFO
1946                                            "st%d: Compression default disabled.\n", dev);
1947     			} else {
1948     				STm->default_compression = (value & 1 ? ST_YES : ST_NO);
1949     				printk(KERN_INFO "st%d: Compression default set to %x\n",
1950     				       dev, (value & 1));
1951     			}
1952     		}
1953     	} else
1954     		return (-EIO);
1955     
1956     	return 0;
1957     }
1958     
1959     #define MODE_HEADER_LENGTH  4
1960     
1961     /* Mode header and page byte offsets */
1962     #define MH_OFF_DATA_LENGTH     0
1963     #define MH_OFF_MEDIUM_TYPE     1
1964     #define MH_OFF_DEV_SPECIFIC    2
1965     #define MH_OFF_BDESCS_LENGTH   3
1966     #define MP_OFF_PAGE_NBR        0
1967     #define MP_OFF_PAGE_LENGTH     1
1968     
1969     /* Mode header and page bit masks */
1970     #define MH_BIT_WP              0x80
1971     #define MP_MSK_PAGE_NBR        0x3f
1972     
1973     /* Don't return block descriptors */
1974     #define MODE_SENSE_OMIT_BDESCS 0x08
1975     
1976     #define MODE_SELECT_PAGE_FORMAT 0x10
1977     
1978     /* Read a mode page into the tape buffer. The block descriptors are included
1979        if incl_block_descs is true. */
1980     static int read_mode_page(Scsi_Tape *STp, int page, int omit_block_descs)
1981     {
1982     	unsigned char cmd[MAX_COMMAND_SIZE];
1983     	Scsi_Request *SRpnt = NULL;
1984     
1985     	memset(cmd, 0, MAX_COMMAND_SIZE);
1986     	cmd[0] = MODE_SENSE;
1987     	if (omit_block_descs)
1988     		cmd[1] = MODE_SENSE_OMIT_BDESCS;
1989     	cmd[2] = page;
1990     	cmd[4] = 255;
1991     
1992     	SRpnt = st_do_scsi(SRpnt, STp, cmd, cmd[4], SCSI_DATA_READ,
1993     			   STp->timeout, 0, TRUE);
1994     	if (SRpnt == NULL)
1995     		return (STp->buffer)->syscall_result;
1996     
1997     	scsi_release_request(SRpnt);
1998     
1999     	return (STp->buffer)->syscall_result;
2000     }
2001     
2002     
2003     /* Send the mode page in the tape buffer to the drive. Assumes that the mode data
2004        in the buffer is correctly formatted. */
2005     static int write_mode_page(Scsi_Tape *STp, int page)
2006     {
2007     	int pgo;
2008     	unsigned char cmd[MAX_COMMAND_SIZE];
2009     	Scsi_Request *SRpnt = NULL;
2010     
2011     	memset(cmd, 0, MAX_COMMAND_SIZE);
2012     	cmd[0] = MODE_SELECT;
2013     	cmd[1] = MODE_SELECT_PAGE_FORMAT;
2014     	pgo = MODE_HEADER_LENGTH + (STp->buffer)->b_data[MH_OFF_BDESCS_LENGTH];
2015     	cmd[4] = pgo + (STp->buffer)->b_data[pgo + MP_OFF_PAGE_LENGTH] + 2;
2016     
2017     	/* Clear reserved fields */
2018     	(STp->buffer)->b_data[MH_OFF_DATA_LENGTH] = 0;
2019     	(STp->buffer)->b_data[MH_OFF_MEDIUM_TYPE] = 0;
2020     	(STp->buffer)->b_data[MH_OFF_DEV_SPECIFIC] &= ~MH_BIT_WP;
2021     	(STp->buffer)->b_data[pgo + MP_OFF_PAGE_NBR] &= MP_MSK_PAGE_NBR;
2022     
2023     	SRpnt = st_do_scsi(SRpnt, STp, cmd, cmd[4], SCSI_DATA_WRITE,
2024     			   STp->timeout, 0, TRUE);
2025     	if (SRpnt == NULL)
2026     		return (STp->buffer)->syscall_result;
2027     
2028     	scsi_release_request(SRpnt);
2029     
2030     	return (STp->buffer)->syscall_result;
2031     }
2032     
2033     
2034     #define COMPRESSION_PAGE        0x0f
2035     #define COMPRESSION_PAGE_LENGTH 16
2036     
2037     #define CP_OFF_DCE_DCC          2
2038     
2039     #define DCE_MASK  0x80
2040     #define DCC_MASK  0x40
2041     #define RED_MASK  0x60
2042     
2043     
2044     /* Control the compression with mode page 15. Algorithm not changed if zero.
2045     
2046        The block descriptors are read and written because Sony SDT-7000 does not
2047        work without this (suggestion from Michael Schaefer <Michael.Schaefer@dlr.de>).
2048        Including block descriptors should not cause any harm to other drives. */
2049     
2050     static int st_compression(Scsi_Tape * STp, int state)
2051     {
2052     	int retval;
2053     	int mpoffs;  /* Offset to mode page start */
2054     	unsigned char *b_data = (STp->buffer)->b_data;
2055     	DEB( int dev = TAPE_NR(STp->devt); )
2056     
2057     	if (STp->ready != ST_READY)
2058     		return (-EIO);
2059     
2060     	/* Read the current page contents */
2061     	retval = read_mode_page(STp, COMPRESSION_PAGE, FALSE);
2062     	if (retval) {
2063                     DEBC(printk(ST_DEB_MSG "st%d: Compression mode page not supported.\n",
2064                                 dev));
2065     		return (-EIO);
2066     	}
2067     
2068     	mpoffs = MODE_HEADER_LENGTH + b_data[MH_OFF_BDESCS_LENGTH];
2069             DEBC(printk(ST_DEB_MSG "st%d: Compression state is %d.\n", dev,
2070                         (b_data[mpoffs + CP_OFF_DCE_DCC] & DCE_MASK ? 1 : 0)));
2071     
2072     	/* Check if compression can be changed */
2073     	if ((b_data[mpoffs + 2] & DCC_MASK) == 0) {
2074                     DEBC(printk(ST_DEB_MSG "st%d: Compression not supported.\n", dev));
2075     		return (-EIO);
2076     	}
2077     
2078     	/* Do the change */
2079     	if (state)
2080     		b_data[mpoffs + CP_OFF_DCE_DCC] |= DCE_MASK;
2081     	else
2082     		b_data[mpoffs + CP_OFF_DCE_DCC] &= ~DCE_MASK;
2083     
2084     	retval = write_mode_page(STp, COMPRESSION_PAGE);
2085     	if (retval) {
2086                     DEBC(printk(ST_DEB_MSG "st%d: Compression change failed.\n", dev));
2087     		return (-EIO);
2088     	}
2089             DEBC(printk(ST_DEB_MSG "st%d: Compression state changed to %d.\n",
2090     		       dev, state));
2091     
2092     	STp->compression_changed = TRUE;
2093     	return 0;
2094     }
2095     
2096     
2097     /* Internal ioctl function */
2098     static int st_int_ioctl(Scsi_Tape *STp, unsigned int cmd_in, unsigned long arg)
2099     {
2100     	int timeout;
2101     	long ltmp;
2102     	int i, ioctl_result;
2103     	int chg_eof = TRUE;
2104     	unsigned char cmd[MAX_COMMAND_SIZE];
2105     	Scsi_Request *SRpnt;
2106     	ST_partstat *STps;
2107     	int fileno, blkno, at_sm, undone;
2108     	int datalen = 0, direction = SCSI_DATA_NONE;
2109     	int dev = TAPE_NR(STp->devt);
2110     
2111     	if (STp->ready != ST_READY && cmd_in != MTLOAD) {
2112     		if (STp->ready == ST_NO_TAPE)
2113     			return (-ENOMEDIUM);
2114     		else
2115     			return (-EIO);
2116     	}
2117     	timeout = STp->long_timeout;
2118     	STps = &(STp->ps[STp->partition]);
2119     	fileno = STps->drv_file;
2120     	blkno = STps->drv_block;
2121     	at_sm = STps->at_sm;
2122     
2123     	memset(cmd, 0, MAX_COMMAND_SIZE);
2124     	switch (cmd_in) {
2125     	case MTFSFM:
2126     		chg_eof = FALSE;	/* Changed from the FSF after this */
2127     	case MTFSF:
2128     		cmd[0] = SPACE;
2129     		cmd[1] = 0x01;	/* Space FileMarks */
2130     		cmd[2] = (arg >> 16);
2131     		cmd[3] = (arg >> 8);
2132     		cmd[4] = arg;
2133                     DEBC(printk(ST_DEB_MSG "st%d: Spacing tape forward over %d filemarks.\n",
2134     			    dev, cmd[2] * 65536 + cmd[3] * 256 + cmd[4]));
2135     		if (fileno >= 0)
2136     			fileno += arg;
2137     		blkno = 0;
2138     		at_sm &= (arg == 0);
2139     		break;
2140     	case MTBSFM:
2141     		chg_eof = FALSE;	/* Changed from the FSF after this */
2142     	case MTBSF:
2143     		cmd[0] = SPACE;
2144     		cmd[1] = 0x01;	/* Space FileMarks */
2145     		ltmp = (-arg);
2146     		cmd[2] = (ltmp >> 16);
2147     		cmd[3] = (ltmp >> 8);
2148     		cmd[4] = ltmp;
2149                     DEBC(
2150                          if (cmd[2] & 0x80)
2151                          	ltmp = 0xff000000;
2152                          ltmp = ltmp | (cmd[2] << 16) | (cmd[3] << 8) | cmd[4];
2153                          printk(ST_DEB_MSG
2154                                 "st%d: Spacing tape backward over %ld filemarks.\n",
2155                                 dev, (-ltmp));
2156     		)
2157     		if (fileno >= 0)
2158     			fileno -= arg;
2159     		blkno = (-1);	/* We can't know the block number */
2160     		at_sm &= (arg == 0);
2161     		break;
2162     	case MTFSR:
2163     		cmd[0] = SPACE;
2164     		cmd[1] = 0x00;	/* Space Blocks */
2165     		cmd[2] = (arg >> 16);
2166     		cmd[3] = (arg >> 8);
2167     		cmd[4] = arg;
2168                     DEBC(printk(ST_DEB_MSG "st%d: Spacing tape forward %d blocks.\n", dev,
2169     			       cmd[2] * 65536 + cmd[3] * 256 + cmd[4]));
2170     		if (blkno >= 0)
2171     			blkno += arg;
2172     		at_sm &= (arg == 0);
2173     		break;
2174     	case MTBSR:
2175     		cmd[0] = SPACE;
2176     		cmd[1] = 0x00;	/* Space Blocks */
2177     		ltmp = (-arg);
2178     		cmd[2] = (ltmp >> 16);
2179     		cmd[3] = (ltmp >> 8);
2180     		cmd[4] = ltmp;
2181                     DEBC(
2182                          if (cmd[2] & 0x80)
2183                               ltmp = 0xff000000;
2184                          ltmp = ltmp | (cmd[2] << 16) | (cmd[3] << 8) | cmd[4];
2185                          printk(ST_DEB_MSG
2186                                 "st%d: Spacing tape backward %ld blocks.\n", dev, (-ltmp));
2187     		)
2188     		if (blkno >= 0)
2189     			blkno -= arg;
2190     		at_sm &= (arg == 0);
2191     		break;
2192     	case MTFSS:
2193     		cmd[0] = SPACE;
2194     		cmd[1] = 0x04;	/* Space Setmarks */
2195     		cmd[2] = (arg >> 16);
2196     		cmd[3] = (arg >> 8);
2197     		cmd[4] = arg;
2198                     DEBC(printk(ST_DEB_MSG "st%d: Spacing tape forward %d setmarks.\n", dev,
2199                                 cmd[2] * 65536 + cmd[3] * 256 + cmd[4]));
2200     		if (arg != 0) {
2201     			blkno = fileno = (-1);
2202     			at_sm = 1;
2203     		}
2204     		break;
2205     	case MTBSS:
2206     		cmd[0] = SPACE;
2207     		cmd[1] = 0x04;	/* Space Setmarks */
2208     		ltmp = (-arg);
2209     		cmd[2] = (ltmp >> 16);
2210     		cmd[3] = (ltmp >> 8);
2211     		cmd[4] = ltmp;
2212                     DEBC(
2213                          if (cmd[2] & 0x80)
2214     				ltmp = 0xff000000;
2215                          ltmp = ltmp | (cmd[2] << 16) | (cmd[3] << 8) | cmd[4];
2216                          printk(ST_DEB_MSG "st%d: Spacing tape backward %ld setmarks.\n",
2217                                 dev, (-ltmp));
2218     		)
2219     		if (arg != 0) {
2220     			blkno = fileno = (-1);
2221     			at_sm = 1;
2222     		}
2223     		break;
2224     	case MTWEOF:
2225     	case MTWSM:
2226     		if (STp->write_prot)
2227     			return (-EACCES);
2228     		cmd[0] = WRITE_FILEMARKS;
2229     		if (cmd_in == MTWSM)
2230     			cmd[1] = 2;
2231     		cmd[2] = (arg >> 16);
2232     		cmd[3] = (arg >> 8);
2233     		cmd[4] = arg;
2234     		timeout = STp->timeout;
2235                     DEBC(
2236                          if (cmd_in == MTWEOF)
2237                                    printk(ST_DEB_MSG "st%d: Writing %d filemarks.\n", dev,
2238     				 cmd[2] * 65536 + cmd[3] * 256 + cmd[4]);
2239                          else
2240     				printk(ST_DEB_MSG "st%d: Writing %d setmarks.\n", dev,
2241     				 cmd[2] * 65536 + cmd[3] * 256 + cmd[4]);
2242     		)
2243     		if (fileno >= 0)
2244     			fileno += arg;
2245     		blkno = 0;
2246     		at_sm = (cmd_in == MTWSM);
2247     		break;
2248     	case MTREW:
2249     		cmd[0] = REZERO_UNIT;
2250     #if ST_NOWAIT
2251     		cmd[1] = 1;	/* Don't wait for completion */
2252     		timeout = STp->timeout;
2253     #endif
2254                     DEBC(printk(ST_DEB_MSG "st%d: Rewinding tape.\n", dev));
2255     		fileno = blkno = at_sm = 0;
2256     		break;
2257     	case MTOFFL:
2258     	case MTLOAD:
2259     	case MTUNLOAD:
2260     		cmd[0] = START_STOP;
2261     		if (cmd_in == MTLOAD)
2262     			cmd[4] |= 1;
2263     		/*
2264     		 * If arg >= 1 && arg <= 6 Enhanced load/unload in HP C1553A
2265     		 */
2266     		if (cmd_in != MTOFFL &&
2267     		    arg >= 1 + MT_ST_HPLOADER_OFFSET
2268     		    && arg <= 6 + MT_ST_HPLOADER_OFFSET) {
2269                             DEBC(printk(ST_DEB_MSG "st%d: Enhanced %sload slot %2ld.\n",
2270                                         dev, (cmd[4]) ? "" : "un",
2271                                         arg - MT_ST_HPLOADER_OFFSET));
2272     			cmd[3] = arg - MT_ST_HPLOADER_OFFSET; /* MediaID field of C1553A */
2273     		}
2274     #if ST_NOWAIT
2275     		cmd[1] = 1;	/* Don't wait for completion */
2276     		timeout = STp->timeout;
2277     #else
2278     		timeout = STp->long_timeout;
2279     #endif
2280                     DEBC(
2281     			if (cmd_in != MTLOAD)
2282     				printk(ST_DEB_MSG "st%d: Unloading tape.\n", dev);
2283     			else
2284     				printk(ST_DEB_MSG "st%d: Loading tape.\n", dev);
2285     		)
2286     		fileno = blkno = at_sm = 0;
2287     		break;
2288     	case MTNOP:
2289                     DEBC(printk(ST_DEB_MSG "st%d: No op on tape.\n", dev));
2290     		return 0;	/* Should do something ? */
2291     		break;
2292     	case MTRETEN:
2293     		cmd[0] = START_STOP;
2294     #if ST_NOWAIT
2295     		cmd[1] = 1;	/* Don't wait for completion */
2296     		timeout = STp->timeout;
2297     #endif
2298     		cmd[4] = 3;
2299                     DEBC(printk(ST_DEB_MSG "st%d: Retensioning tape.\n", dev));
2300     		fileno = blkno = at_sm = 0;
2301     		break;
2302     	case MTEOM:
2303     		if (!STp->fast_mteom) {
2304     			/* space to the end of tape */
2305     			ioctl_result = st_int_ioctl(STp, MTFSF, 0x7fffff);
2306     			fileno = STps->drv_file;
2307     			if (STps->eof >= ST_EOD_1)
2308     				return 0;
2309     			/* The next lines would hide the number of spaced FileMarks
2310     			   That's why I inserted the previous lines. I had no luck
2311     			   with detecting EOM with FSF, so we go now to EOM.
2312     			   Joerg Weule */
2313     		} else
2314     			fileno = (-1);
2315     		cmd[0] = SPACE;
2316     		cmd[1] = 3;
2317                     DEBC(printk(ST_DEB_MSG "st%d: Spacing to end of recorded medium.\n",
2318                                 dev));
2319     		blkno = 0;
2320     		at_sm = 0;
2321     		break;
2322     	case MTERASE:
2323     		if (STp->write_prot)
2324     			return (-EACCES);
2325     		cmd[0] = ERASE;
2326     		cmd[1] = 1;	/* To the end of tape */
2327     #if ST_NOWAIT
2328     		cmd[1] |= 2;	/* Don't wait for completion */
2329     		timeout = STp->timeout;
2330     #else
2331     		timeout = STp->long_timeout * 8;
2332     #endif
2333                     DEBC(printk(ST_DEB_MSG "st%d: Erasing tape.\n", dev));
2334     		fileno = blkno = at_sm = 0;
2335     		break;
2336     	case MTLOCK:
2337     		chg_eof = FALSE;
2338     		cmd[0] = ALLOW_MEDIUM_REMOVAL;
2339     		cmd[4] = SCSI_REMOVAL_PREVENT;
2340                     DEBC(printk(ST_DEB_MSG "st%d: Locking drive door.\n", dev));
2341     		break;
2342     	case MTUNLOCK:
2343     		chg_eof = FALSE;
2344     		cmd[0] = ALLOW_MEDIUM_REMOVAL;
2345     		cmd[4] = SCSI_REMOVAL_ALLOW;
2346                     DEBC(printk(ST_DEB_MSG "st%d: Unlocking drive door.\n", dev));
2347     		break;
2348     	case MTSETBLK:		/* Set block length */
2349     	case MTSETDENSITY:	/* Set tape density */
2350     	case MTSETDRVBUFFER:	/* Set drive buffering */
2351     	case SET_DENS_AND_BLK:	/* Set density and block size */
2352     		chg_eof = FALSE;
2353     		if (STp->dirty || (STp->buffer)->buffer_bytes != 0)
2354     			return (-EIO);	/* Not allowed if data in buffer */
2355     		if ((cmd_in == MTSETBLK || cmd_in == SET_DENS_AND_BLK) &&
2356     		    (arg & MT_ST_BLKSIZE_MASK) != 0 &&
2357     		    STp->max_block > 0 &&
2358     		    ((arg & MT_ST_BLKSIZE_MASK) < STp->min_block ||
2359     		     (arg & MT_ST_BLKSIZE_MASK) > STp->max_block)) {
2360     			printk(KERN_WARNING "st%d: Illegal block size.\n", dev);
2361     			return (-EINVAL);
2362     		}
2363     		cmd[0] = MODE_SELECT;
2364     		if ((STp->use_pf & USE_PF))
2365     			cmd[1] = MODE_SELECT_PAGE_FORMAT;
2366     		cmd[4] = datalen = 12;
2367     		direction = SCSI_DATA_WRITE;
2368     
2369     		memset((STp->buffer)->b_data, 0, 12);
2370     		if (cmd_in == MTSETDRVBUFFER)
2371     			(STp->buffer)->b_data[2] = (arg & 7) << 4;
2372     		else
2373     			(STp->buffer)->b_data[2] =
2374     			    STp->drv_buffer << 4;
2375     		(STp->buffer)->b_data[3] = 8;	/* block descriptor length */
2376     		if (cmd_in == MTSETDENSITY) {
2377     			(STp->buffer)->b_data[4] = arg;
2378     			STp->density_changed = TRUE;	/* At least we tried ;-) */
2379     		} else if (cmd_in == SET_DENS_AND_BLK)
2380     			(STp->buffer)->b_data[4] = arg >> 24;
2381     		else
2382     			(STp->buffer)->b_data[4] = STp->density;
2383     		if (cmd_in == MTSETBLK || cmd_in == SET_DENS_AND_BLK) {
2384     			ltmp = arg & MT_ST_BLKSIZE_MASK;
2385     			if (cmd_in == MTSETBLK)
2386     				STp->blksize_changed = TRUE; /* At least we tried ;-) */
2387     		} else
2388     			ltmp = STp->block_size;
2389     		(STp->buffer)->b_data[9] = (ltmp >> 16);
2390     		(STp->buffer)->b_data[10] = (ltmp >> 8);
2391     		(STp->buffer)->b_data[11] = ltmp;
2392     		timeout = STp->timeout;
2393                     DEBC(
2394     			if (cmd_in == MTSETBLK || cmd_in == SET_DENS_AND_BLK)
2395     				printk(ST_DEB_MSG
2396                                            "st%d: Setting block size to %d bytes.\n", dev,
2397     				       (STp->buffer)->b_data[9] * 65536 +
2398     				       (STp->buffer)->b_data[10] * 256 +
2399     				       (STp->buffer)->b_data[11]);
2400     			if (cmd_in == MTSETDENSITY || cmd_in == SET_DENS_AND_BLK)
2401     				printk(ST_DEB_MSG
2402                                            "st%d: Setting density code to %x.\n", dev,
2403     				       (STp->buffer)->b_data[4]);
2404     			if (cmd_in == MTSETDRVBUFFER)
2405     				printk(ST_DEB_MSG
2406                                            "st%d: Setting drive buffer code to %d.\n", dev,
2407     				    ((STp->buffer)->b_data[2] >> 4) & 7);
2408     		)
2409     		break;
2410     	default:
2411     		return (-ENOSYS);
2412     	}
2413     
2414     	SRpnt = st_do_scsi(NULL, STp, cmd, datalen, direction,
2415     			   timeout, MAX_RETRIES, TRUE);
2416     	if (!SRpnt)
2417     		return (STp->buffer)->syscall_result;
2418     
2419     	ioctl_result = (STp->buffer)->syscall_result;
2420     
2421     	if (!ioctl_result) {	/* SCSI command successful */
2422     		scsi_release_request(SRpnt);
2423     		SRpnt = NULL;
2424     		STps->drv_block = blkno;
2425     		STps->drv_file = fileno;
2426     		STps->at_sm = at_sm;
2427     
2428     		if (cmd_in == MTLOCK)
2429     			STp->door_locked = ST_LOCKED_EXPLICIT;
2430     		else if (cmd_in == MTUNLOCK)
2431     			STp->door_locked = ST_UNLOCKED;
2432     
2433     		if (cmd_in == MTBSFM)
2434     			ioctl_result = st_int_ioctl(STp, MTFSF, 1);
2435     		else if (cmd_in == MTFSFM)
2436     			ioctl_result = st_int_ioctl(STp, MTBSF, 1);
2437     
2438     		if (cmd_in == MTSETBLK || cmd_in == SET_DENS_AND_BLK) {
2439     			STp->block_size = arg & MT_ST_BLKSIZE_MASK;
2440     			if (STp->block_size != 0)
2441     				(STp->buffer)->buffer_blocks =
2442     				    (STp->buffer)->buffer_size / STp->block_size;
2443     			(STp->buffer)->buffer_bytes = (STp->buffer)->read_pointer = 0;
2444     			if (cmd_in == SET_DENS_AND_BLK)
2445     				STp->density = arg >> MT_ST_DENSITY_SHIFT;
2446     		} else if (cmd_in == MTSETDRVBUFFER)
2447     			STp->drv_buffer = (arg & 7);
2448     		else if (cmd_in == MTSETDENSITY)
2449     			STp->density = arg;
2450     
2451     		if (cmd_in == MTEOM)
2452     			STps->eof = ST_EOD;
2453     		else if (cmd_in == MTFSF)
2454     			STps->eof = ST_FM;
2455     		else if (chg_eof)
2456     			STps->eof = ST_NOEOF;
2457     
2458     
2459     		if (cmd_in == MTOFFL || cmd_in == MTUNLOAD)
2460     			STp->rew_at_close = 0;
2461     		else if (cmd_in == MTLOAD) {
2462     			STp->rew_at_close = STp->autorew_dev;
2463     			for (i = 0; i < ST_NBR_PARTITIONS; i++) {
2464     				STp->ps[i].rw = ST_IDLE;
2465     				STp->ps[i].last_block_valid = FALSE;
2466     			}
2467     			STp->partition = 0;
2468     		}
2469     	} else { /* SCSI command was not completely successful. Don't return
2470                         from this block without releasing the SCSI command block! */
2471     
2472     		if (SRpnt->sr_sense_buffer[2] & 0x40) {
2473     			if (cmd_in != MTBSF && cmd_in != MTBSFM &&
2474     			    cmd_in != MTBSR && cmd_in != MTBSS)
2475     				STps->eof = ST_EOM_OK;
2476     			STps->drv_block = 0;
2477     		}
2478     
2479     		undone = ((SRpnt->sr_sense_buffer[3] << 24) +
2480     			  (SRpnt->sr_sense_buffer[4] << 16) +
2481     			  (SRpnt->sr_sense_buffer[5] << 8) +
2482     			  SRpnt->sr_sense_buffer[6]);
2483     
2484     		if (cmd_in == MTWEOF &&
2485     		    (SRpnt->sr_sense_buffer[0] & 0x70) == 0x70 &&
2486     		    (SRpnt->sr_sense_buffer[2] & 0x4f) == 0x40 &&
2487     		 ((SRpnt->sr_sense_buffer[0] & 0x80) == 0 || undone == 0)) {
2488     			ioctl_result = 0;	/* EOF written succesfully at EOM */
2489     			if (fileno >= 0)
2490     				fileno++;
2491     			STps->drv_file = fileno;
2492     			STps->eof = ST_NOEOF;
2493     		} else if ((cmd_in == MTFSF) || (cmd_in == MTFSFM)) {
2494     			if (fileno >= 0)
2495     				STps->drv_file = fileno - undone;
2496     			else
2497     				STps->drv_file = fileno;
2498     			STps->drv_block = 0;
2499     			STps->eof = ST_NOEOF;
2500     		} else if ((cmd_in == MTBSF) || (cmd_in == MTBSFM)) {
2501     			if (arg > 0 && undone < 0)  /* Some drives get this wrong */
2502     				undone = (-undone);
2503     			if (STps->drv_file >= 0)
2504     				STps->drv_file = fileno + undone;
2505     			STps->drv_block = 0;
2506     			STps->eof = ST_NOEOF;
2507     		} else if (cmd_in == MTFSR) {
2508     			if (SRpnt->sr_sense_buffer[2] & 0x80) {	/* Hit filemark */
2509     				if (STps->drv_file >= 0)
2510     					STps->drv_file++;
2511     				STps->drv_block = 0;
2512     				STps->eof = ST_FM;
2513     			} else {
2514     				if (blkno >= undone)
2515     					STps->drv_block = blkno - undone;
2516     				else
2517     					STps->drv_block = (-1);
2518     				STps->eof = ST_NOEOF;
2519     			}
2520     		} else if (cmd_in == MTBSR) {
2521     			if (SRpnt->sr_sense_buffer[2] & 0x80) {	/* Hit filemark */
2522     				STps->drv_file--;
2523     				STps->drv_block = (-1);
2524     			} else {
2525     				if (arg > 0 && undone < 0)  /* Some drives get this wrong */
2526     					undone = (-undone);
2527     				if (STps->drv_block >= 0)
2528     					STps->drv_block = blkno + undone;
2529     			}
2530     			STps->eof = ST_NOEOF;
2531     		} else if (cmd_in == MTEOM) {
2532     			STps->drv_file = (-1);
2533     			STps->drv_block = (-1);
2534     			STps->eof = ST_EOD;
2535     		} else if (cmd_in == MTSETBLK ||
2536     			   cmd_in == MTSETDENSITY ||
2537     			   cmd_in == MTSETDRVBUFFER ||
2538     			   cmd_in == SET_DENS_AND_BLK) {
2539     			if ((SRpnt->sr_sense_buffer[2] & 0x0f) == ILLEGAL_REQUEST &&
2540     			    !(STp->use_pf & PF_TESTED)) {
2541     				/* Try the other possible state of Page Format if not
2542     				   already tried */
2543     				STp->use_pf = !STp->use_pf | PF_TESTED;
2544     				scsi_release_request(SRpnt);
2545     				SRpnt = NULL;
2546     				return st_int_ioctl(STp, cmd_in, arg);
2547     			}
2548     		} else if (chg_eof)
2549     			STps->eof = ST_NOEOF;
2550     
2551     		if ((SRpnt->sr_sense_buffer[2] & 0x0f) == BLANK_CHECK)
2552     			STps->eof = ST_EOD;
2553     
2554     		if (cmd_in == MTLOCK)
2555     			STp->door_locked = ST_LOCK_FAILS;
2556     
2557     		scsi_release_request(SRpnt);
2558     		SRpnt = NULL;
2559     	}
2560     
2561     	return ioctl_result;
2562     }
2563     
2564     
2565     /* Get the tape position. If bt == 2, arg points into a kernel space mt_loc
2566        structure. */
2567     
2568     static int get_location(Scsi_Tape *STp, unsigned int *block, int *partition,
2569     			int logical)
2570     {
2571     	int result;
2572     	unsigned char scmd[MAX_COMMAND_SIZE];
2573     	Scsi_Request *SRpnt;
2574     	DEB( int dev = TAPE_NR(STp->devt); )
2575     
2576     	if (STp->ready != ST_READY)
2577     		return (-EIO);
2578     
2579     	memset(scmd, 0, MAX_COMMAND_SIZE);
2580     	if ((STp->device)->scsi_level < SCSI_2) {
2581     		scmd[0] = QFA_REQUEST_BLOCK;
2582     		scmd[4] = 3;
2583     	} else {
2584     		scmd[0] = READ_POSITION;
2585     		if (!logical && !STp->scsi2_logical)
2586     			scmd[1] = 1;
2587     	}
2588     	SRpnt = st_do_scsi(NULL, STp, scmd, 20, SCSI_DATA_READ, STp->timeout,
2589     			   MAX_READY_RETRIES, TRUE);
2590     	if (!SRpnt)
2591     		return (STp->buffer)->syscall_result;
2592     
2593     	if ((STp->buffer)->syscall_result != 0 ||
2594     	    (STp->device->scsi_level >= SCSI_2 &&
2595     	     ((STp->buffer)->b_data[0] & 4) != 0)) {
2596     		*block = *partition = 0;
2597                     DEBC(printk(ST_DEB_MSG "st%d: Can't read tape position.\n", dev));
2598     		result = (-EIO);
2599     	} else {
2600     		result = 0;
2601     		if ((STp->device)->scsi_level < SCSI_2) {
2602     			*block = ((STp->buffer)->b_data[0] << 16)
2603     			    + ((STp->buffer)->b_data[1] << 8)
2604     			    + (STp->buffer)->b_data[2];
2605     			*partition = 0;
2606     		} else {
2607     			*block = ((STp->buffer)->b_data[4] << 24)
2608     			    + ((STp->buffer)->b_data[5] << 16)
2609     			    + ((STp->buffer)->b_data[6] << 8)
2610     			    + (STp->buffer)->b_data[7];
2611     			*partition = (STp->buffer)->b_data[1];
2612     			if (((STp->buffer)->b_data[0] & 0x80) &&
2613     			    (STp->buffer)->b_data[1] == 0)	/* BOP of partition 0 */
2614     				STp->ps[0].drv_block = STp->ps[0].drv_file = 0;
2615     		}
2616                     DEBC(printk(ST_DEB_MSG "st%d: Got tape pos. blk %d part %d.\n", dev,
2617                                 *block, *partition));
2618     	}
2619     	scsi_release_request(SRpnt);
2620     	SRpnt = NULL;
2621     
2622     	return result;
2623     }
2624     
2625     
2626     /* Set the tape block and partition. Negative partition means that only the
2627        block should be set in vendor specific way. */
2628     static int set_location(Scsi_Tape *STp, unsigned int block, int partition,
2629     			int logical)
2630     {
2631     	ST_partstat *STps;
2632     	int result, p;
2633     	unsigned int blk;
2634     	int timeout;
2635     	unsigned char scmd[MAX_COMMAND_SIZE];
2636     	Scsi_Request *SRpnt;
2637     	DEB( int dev = TAPE_NR(STp->devt); )
2638     
2639     	if (STp->ready != ST_READY)
2640     		return (-EIO);
2641     	timeout = STp->long_timeout;
2642     	STps = &(STp->ps[STp->partition]);
2643     
2644             DEBC(printk(ST_DEB_MSG "st%d: Setting block to %d and partition to %d.\n",
2645                         dev, block, partition));
2646     	DEB(if (partition < 0)
2647     		return (-EIO); )
2648     
2649     	/* Update the location at the partition we are leaving */
2650     	if ((!STp->can_partitions && partition != 0) ||
2651     	    partition >= ST_NBR_PARTITIONS)
2652     		return (-EINVAL);
2653     	if (partition != STp->partition) {
2654     		if (get_location(STp, &blk, &p, 1))
2655     			STps->last_block_valid = FALSE;
2656     		else {
2657     			STps->last_block_valid = TRUE;
2658     			STps->last_block_visited = blk;
2659                             DEBC(printk(ST_DEB_MSG
2660                                         "st%d: Visited block %d for partition %d saved.\n",
2661                                         dev, blk, STp->partition));
2662     		}
2663     	}
2664     
2665     	memset(scmd, 0, MAX_COMMAND_SIZE);
2666     	if ((STp->device)->scsi_level < SCSI_2) {
2667     		scmd[0] = QFA_SEEK_BLOCK;
2668     		scmd[2] = (block >> 16);
2669     		scmd[3] = (block >> 8);
2670     		scmd[4] = block;
2671     		scmd[5] = 0;
2672     	} else {
2673     		scmd[0] = SEEK_10;
2674     		scmd[3] = (block >> 24);
2675     		scmd[4] = (block >> 16);
2676     		scmd[5] = (block >> 8);
2677     		scmd[6] = block;
2678     		if (!logical && !STp->scsi2_logical)
2679     			scmd[1] = 4;
2680     		if (STp->partition != partition) {
2681     			scmd[1] |= 2;
2682     			scmd[8] = partition;
2683                             DEBC(printk(ST_DEB_MSG
2684                                         "st%d: Trying to change partition from %d to %d\n",
2685                                         dev, STp->partition, partition));
2686     		}
2687     	}
2688     #if ST_NOWAIT
2689     	scmd[1] |= 1;		/* Don't wait for completion */
2690     	timeout = STp->timeout;
2691     #endif
2692     
2693     	SRpnt = st_do_scsi(NULL, STp, scmd, 0, SCSI_DATA_NONE,
2694     			   timeout, MAX_READY_RETRIES, TRUE);
2695     	if (!SRpnt)
2696     		return (STp->buffer)->syscall_result;
2697     
2698     	STps->drv_block = STps->drv_file = (-1);
2699     	STps->eof = ST_NOEOF;
2700     	if ((STp->buffer)->syscall_result != 0) {
2701     		result = (-EIO);
2702     		if (STp->can_partitions &&
2703     		    (STp->device)->scsi_level >= SCSI_2 &&
2704     		    (p = find_partition(STp)) >= 0)
2705     			STp->partition = p;
2706     	} else {
2707     		if (STp->can_partitions) {
2708     			STp->partition = partition;
2709     			STps = &(STp->ps[partition]);
2710     			if (!STps->last_block_valid ||
2711     			    STps->last_block_visited != block) {
2712     				STps->at_sm = 0;
2713     				STps->rw = ST_IDLE;
2714     			}
2715     		} else
2716     			STps->at_sm = 0;
2717     		if (block == 0)
2718     			STps->drv_block = STps->drv_file = 0;
2719     		result = 0;
2720     	}
2721     
2722     	scsi_release_request(SRpnt);
2723     	SRpnt = NULL;
2724     
2725     	return result;
2726     }
2727     
2728     
2729     /* Find the current partition number for the drive status. Called from open and
2730        returns either partition number of negative error code. */
2731     static int find_partition(Scsi_Tape *STp)
2732     {
2733     	int i, partition;
2734     	unsigned int block;
2735     
2736     	if ((i = get_location(STp, &block, &partition, 1)) < 0)
2737     		return i;
2738     	if (partition >= ST_NBR_PARTITIONS)
2739     		return (-EIO);
2740     	return partition;
2741     }
2742     
2743     
2744     /* Change the partition if necessary */
2745     static int update_partition(Scsi_Tape *STp)
2746     {
2747     	ST_partstat *STps;
2748     
2749     	if (STp->partition == STp->new_partition)
2750     		return 0;
2751     	STps = &(STp->ps[STp->new_partition]);
2752     	if (!STps->last_block_valid)
2753     		STps->last_block_visited = 0;
2754     	return set_location(STp, STps->last_block_visited, STp->new_partition, 1);
2755     }
2756     
2757     /* Functions for reading and writing the medium partition mode page. */
2758     
2759     #define PART_PAGE   0x11
2760     #define PART_PAGE_FIXED_LENGTH 8
2761     
2762     #define PP_OFF_MAX_ADD_PARTS   2
2763     #define PP_OFF_NBR_ADD_PARTS   3
2764     #define PP_OFF_FLAGS           4
2765     #define PP_OFF_PART_UNITS      6
2766     #define PP_OFF_RESERVED        7
2767     
2768     #define PP_BIT_IDP             0x20
2769     #define PP_MSK_PSUM_MB         0x10
2770     
2771     /* Get the number of partitions on the tape. As a side effect reads the
2772        mode page into the tape buffer. */
2773     static int nbr_partitions(Scsi_Tape *STp)
2774     {
2775     	int result;
2776     	DEB( int dev = TAPE_NR(STp->devt) );
2777     
2778     	if (STp->ready != ST_READY)
2779     		return (-EIO);
2780     
2781     	result = read_mode_page(STp, PART_PAGE, TRUE);
2782     
2783     	if (result) {
2784                     DEBC(printk(ST_DEB_MSG "st%d: Can't read medium partition page.\n",
2785                                 dev));
2786     		result = (-EIO);
2787     	} else {
2788     		result = (STp->buffer)->b_data[MODE_HEADER_LENGTH +
2789     					      PP_OFF_NBR_ADD_PARTS] + 1;
2790                     DEBC(printk(ST_DEB_MSG "st%d: Number of partitions %d.\n", dev, result));
2791     	}
2792     
2793     	return result;
2794     }
2795     
2796     
2797     /* Partition the tape into two partitions if size > 0 or one partition if
2798        size == 0.
2799     
2800        The block descriptors are read and written because Sony SDT-7000 does not
2801        work without this (suggestion from Michael Schaefer <Michael.Schaefer@dlr.de>).
2802     
2803        My HP C1533A drive returns only one partition size field. This is used to
2804        set the size of partition 1. There is no size field for the default partition.
2805        Michael Schaefer's Sony SDT-7000 returns two descriptors and the second is
2806        used to set the size of partition 1 (this is what the SCSI-3 standard specifies).
2807        The following algorithm is used to accomodate both drives: if the number of
2808        partition size fields is greater than the maximum number of additional partitions
2809        in the mode page, the second field is used. Otherwise the first field is used.
2810     
2811        For Seagate DDS drives the page length must be 8 when no partitions is defined
2812        and 10 when 1 partition is defined (information from Eric Lee Green). This is
2813        is acceptable also to some other old drives and enforced if the first partition
2814        size field is used for the first additional partition size.
2815      */
2816     static int partition_tape(Scsi_Tape *STp, int size)
2817     {
2818     	int dev = TAPE_NR(STp->devt), result;
2819     	int pgo, psd_cnt, psdo;
2820     	unsigned char *bp;
2821     
2822     	result = read_mode_page(STp, PART_PAGE, FALSE);
2823     	if (result) {
2824     		DEBC(printk(ST_DEB_MSG "st%d: Can't read partition mode page.\n", dev));
2825     		return result;
2826     	}
2827     	/* The mode page is in the buffer. Let's modify it and write it. */
2828     	bp = (STp->buffer)->b_data;
2829     	pgo = MODE_HEADER_LENGTH + bp[MH_OFF_BDESCS_LENGTH];
2830     	DEBC(printk(ST_DEB_MSG "st%d: Partition page length is %d bytes.\n",
2831     		    dev, bp[pgo + MP_OFF_PAGE_LENGTH] + 2));
2832     
2833     	psd_cnt = (bp[pgo + MP_OFF_PAGE_LENGTH] + 2 - PART_PAGE_FIXED_LENGTH) / 2;
2834     	psdo = pgo + PART_PAGE_FIXED_LENGTH;
2835     	if (psd_cnt > bp[pgo + PP_OFF_MAX_ADD_PARTS]) {
2836     		bp[psdo] = bp[psdo + 1] = 0xff;  /* Rest of the tape */
2837     		psdo += 2;
2838     	}
2839     	memset(bp + psdo, 0, bp[pgo + PP_OFF_NBR_ADD_PARTS] * 2);
2840     
2841     	DEBC(printk("st%d: psd_cnt %d, max.parts %d, nbr_parts %d\n", dev,
2842     		    psd_cnt, bp[pgo + PP_OFF_MAX_ADD_PARTS],
2843     		    bp[pgo + PP_OFF_NBR_ADD_PARTS]));
2844     
2845     	if (size <= 0) {
2846     		bp[pgo + PP_OFF_NBR_ADD_PARTS] = 0;
2847     		if (psd_cnt <= bp[pgo + PP_OFF_MAX_ADD_PARTS])
2848     		    bp[pgo + MP_OFF_PAGE_LENGTH] = 6;
2849                     DEBC(printk(ST_DEB_MSG "st%d: Formatting tape with one partition.\n",
2850                                 dev));
2851     	} else {
2852     		bp[psdo] = (size >> 8) & 0xff;
2853     		bp[psdo + 1] = size & 0xff;
2854     		bp[pgo + 3] = 1;
2855     		if (bp[pgo + MP_OFF_PAGE_LENGTH] < 8)
2856     		    bp[pgo + MP_OFF_PAGE_LENGTH] = 8;
2857                     DEBC(printk(ST_DEB_MSG
2858                                 "st%d: Formatting tape with two partitions (1 = %d MB).\n",
2859                                 dev, size));
2860     	}
2861     	bp[pgo + PP_OFF_PART_UNITS] = 0;
2862     	bp[pgo + PP_OFF_RESERVED] = 0;
2863     	bp[pgo + PP_OFF_FLAGS] = PP_BIT_IDP | PP_MSK_PSUM_MB;
2864     
2865     	result = write_mode_page(STp, PART_PAGE);
2866     	if (result) {
2867     		printk(KERN_INFO "st%d: Partitioning of tape failed.\n", dev);
2868     		result = (-EIO);
2869     	}
2870     
2871     	return result;
2872     }
2873     
2874     
2875     
2876     /* The ioctl command */
2877     static int st_ioctl(struct inode *inode, struct file *file,
2878     		    unsigned int cmd_in, unsigned long arg)
2879     {
2880     	int i, cmd_nr, cmd_type, bt;
2881     	int retval = 0;
2882     	unsigned int blk;
2883     	Scsi_Tape *STp;
2884     	ST_mode *STm;
2885     	ST_partstat *STps;
2886     	int dev = TAPE_NR(inode->i_rdev);
2887     
2888     	read_lock(&st_dev_arr_lock);
2889     	STp = scsi_tapes[dev];
2890     	read_unlock(&st_dev_arr_lock);
2891     
2892     	if (down_interruptible(&STp->lock))
2893     		return -ERESTARTSYS;
2894     
2895             DEB(
2896     	if (debugging && !STp->in_use) {
2897     		printk(ST_DEB_MSG "st%d: Incorrect device.\n", dev);
2898     		retval = (-EIO);
2899     		goto out;
2900     	} ) /* end DEB */
2901     
2902     	STm = &(STp->modes[STp->current_mode]);
2903     	STps = &(STp->ps[STp->partition]);
2904     
2905     	/*
2906     	 * If we are in the middle of error recovery, don't let anyone
2907     	 * else try and use this device.  Also, if error recovery fails, it
2908     	 * may try and take the device offline, in which case all further
2909     	 * access to the device is prohibited.
2910     	 */
2911     	if (!scsi_block_when_processing_errors(STp->device)) {
2912     		retval = (-ENXIO);
2913     		goto out;
2914     	}
2915     	cmd_type = _IOC_TYPE(cmd_in);
2916     	cmd_nr = _IOC_NR(cmd_in);
2917     
2918     	if (cmd_type == _IOC_TYPE(MTIOCTOP) && cmd_nr == _IOC_NR(MTIOCTOP)) {
2919     		struct mtop mtc;
2920     
2921     		if (_IOC_SIZE(cmd_in) != sizeof(mtc)) {
2922     			retval = (-EINVAL);
2923     			goto out;
2924     		}
2925     
2926     		i = copy_from_user((char *) &mtc, (char *) arg, sizeof(struct mtop));
2927     		if (i) {
2928     			retval = (-EFAULT);
2929     			goto out;
2930     		}
2931     
2932     		if (mtc.mt_op == MTSETDRVBUFFER && !capable(CAP_SYS_ADMIN)) {
2933     			printk(KERN_WARNING
2934                                    "st%d: MTSETDRVBUFFER only allowed for root.\n", dev);
2935     			retval = (-EPERM);
2936     			goto out;
2937     		}
2938     		if (!STm->defined &&
2939     		    (mtc.mt_op != MTSETDRVBUFFER &&
2940     		     (mtc.mt_count & MT_ST_OPTIONS) == 0)) {
2941     			retval = (-ENXIO);
2942     			goto out;
2943     		}
2944     
2945     		if (!(STp->device)->was_reset) {
2946     
2947     			if (STps->eof == ST_FM_HIT) {
2948     				if (mtc.mt_op == MTFSF || mtc.mt_op == MTFSFM ||
2949                                         mtc.mt_op == MTEOM) {
2950     					mtc.mt_count -= 1;
2951     					if (STps->drv_file >= 0)
2952     						STps->drv_file += 1;
2953     				} else if (mtc.mt_op == MTBSF || mtc.mt_op == MTBSFM) {
2954     					mtc.mt_count += 1;
2955     					if (STps->drv_file >= 0)
2956     						STps->drv_file += 1;
2957     				}
2958     			}
2959     
2960     			if (mtc.mt_op == MTSEEK) {
2961     				/* Old position must be restored if partition will be
2962                                        changed */
2963     				i = !STp->can_partitions ||
2964     				    (STp->new_partition != STp->partition);
2965     			} else {
2966     				i = mtc.mt_op == MTREW || mtc.mt_op == MTOFFL ||
2967     				    mtc.mt_op == MTRETEN || mtc.mt_op == MTEOM ||
2968     				    mtc.mt_op == MTLOCK || mtc.mt_op == MTLOAD ||
2969     				    mtc.mt_op == MTFSF || mtc.mt_op == MTFSFM ||
2970     				    mtc.mt_op == MTBSF || mtc.mt_op == MTBSFM ||
2971     				    mtc.mt_op == MTCOMPRESSION;
2972     			}
2973     			i = flush_buffer(STp, i);
2974     			if (i < 0) {
2975     				retval = i;
2976     				goto out;
2977     			}
2978     		} else {
2979     			/*
2980     			 * If there was a bus reset, block further access
2981     			 * to this device.  If the user wants to rewind the tape,
2982     			 * then reset the flag and allow access again.
2983     			 */
2984     			if (mtc.mt_op != MTREW &&
2985     			    mtc.mt_op != MTOFFL &&
2986     			    mtc.mt_op != MTRETEN &&
2987     			    mtc.mt_op != MTERASE &&
2988     			    mtc.mt_op != MTSEEK &&
2989     			    mtc.mt_op != MTEOM) {
2990     				retval = (-EIO);
2991     				goto out;
2992     			}
2993     			STp->device->was_reset = 0;
2994     			if (STp->door_locked != ST_UNLOCKED &&
2995     			    STp->door_locked != ST_LOCK_FAILS) {
2996     				if (st_int_ioctl(STp, MTLOCK, 0)) {
2997     					printk(KERN_NOTICE
2998                                                    "st%d: Could not relock door after bus reset.\n",
2999     					       dev);
3000     					STp->door_locked = ST_UNLOCKED;
3001     				}
3002     			}
3003     		}
3004     
3005     		if (mtc.mt_op != MTNOP && mtc.mt_op != MTSETBLK &&
3006     		    mtc.mt_op != MTSETDENSITY && mtc.mt_op != MTWSM &&
3007     		    mtc.mt_op != MTSETDRVBUFFER && mtc.mt_op != MTSETPART)
3008     			STps->rw = ST_IDLE;	/* Prevent automatic WEOF and fsf */
3009     
3010     		if (mtc.mt_op == MTOFFL && STp->door_locked != ST_UNLOCKED)
3011     			st_int_ioctl(STp, MTUNLOCK, 0);	/* Ignore result! */
3012     
3013     		if (mtc.mt_op == MTSETDRVBUFFER &&
3014     		    (mtc.mt_count & MT_ST_OPTIONS) != 0) {
3015     			retval = st_set_options(STp, mtc.mt_count);
3016     			goto out;
3017     		}
3018     
3019     		if (mtc.mt_op == MTSETPART) {
3020     			if (!STp->can_partitions ||
3021     			    mtc.mt_count < 0 || mtc.mt_count >= ST_NBR_PARTITIONS) {
3022     				retval = (-EINVAL);
3023     				goto out;
3024     			}
3025     			if (mtc.mt_count >= STp->nbr_partitions &&
3026     			    (STp->nbr_partitions = nbr_partitions(STp)) < 0) {
3027     				retval = (-EIO);
3028     				goto out;
3029     			}
3030     			if (mtc.mt_count >= STp->nbr_partitions) {
3031     				retval = (-EINVAL);
3032     				goto out;
3033     			}
3034     			STp->new_partition = mtc.mt_count;
3035     			retval = 0;
3036     			goto out;
3037     		}
3038     
3039     		if (mtc.mt_op == MTMKPART) {
3040     			if (!STp->can_partitions) {
3041     				retval = (-EINVAL);
3042     				goto out;
3043     			}
3044     			if ((i = st_int_ioctl(STp, MTREW, 0)) < 0 ||
3045     			    (i = partition_tape(STp, mtc.mt_count)) < 0) {
3046     				retval = i;
3047     				goto out;
3048     			}
3049     			for (i = 0; i < ST_NBR_PARTITIONS; i++) {
3050     				STp->ps[i].rw = ST_IDLE;
3051     				STp->ps[i].at_sm = 0;
3052     				STp->ps[i].last_block_valid = FALSE;
3053     			}
3054     			STp->partition = STp->new_partition = 0;
3055     			STp->nbr_partitions = 1;	/* Bad guess ?-) */
3056     			STps->drv_block = STps->drv_file = 0;
3057     			retval = 0;
3058     			goto out;
3059     		}
3060     
3061     		if (mtc.mt_op == MTSEEK) {
3062     			i = set_location(STp, mtc.mt_count, STp->new_partition, 0);
3063     			if (!STp->can_partitions)
3064     				STp->ps[0].rw = ST_IDLE;
3065     			retval = i;
3066     			goto out;
3067     		}
3068     
3069     		if (STp->can_partitions && STp->ready == ST_READY &&
3070     		    (i = update_partition(STp)) < 0) {
3071     			retval = i;
3072     			goto out;
3073     		}
3074     
3075     		if (mtc.mt_op == MTCOMPRESSION)
3076     			retval = st_compression(STp, (mtc.mt_count & 1));
3077     		else
3078     			retval = st_int_ioctl(STp, mtc.mt_op, mtc.mt_count);
3079     		goto out;
3080     	}
3081     	if (!STm->defined) {
3082     		retval = (-ENXIO);
3083     		goto out;
3084     	}
3085     
3086     	if ((i = flush_buffer(STp, FALSE)) < 0) {
3087     		retval = i;
3088     		goto out;
3089     	}
3090     	if (STp->can_partitions &&
3091     	    (i = update_partition(STp)) < 0) {
3092     		retval = i;
3093     		goto out;
3094     	}
3095     
3096     	if (cmd_type == _IOC_TYPE(MTIOCGET) && cmd_nr == _IOC_NR(MTIOCGET)) {
3097     		struct mtget mt_status;
3098     
3099     		if (_IOC_SIZE(cmd_in) != sizeof(struct mtget)) {
3100     			 retval = (-EINVAL);
3101     			 goto out;
3102     		}
3103     
3104     		mt_status.mt_type = STp->tape_type;
3105     		mt_status.mt_dsreg =
3106     		    ((STp->block_size << MT_ST_BLKSIZE_SHIFT) & MT_ST_BLKSIZE_MASK) |
3107     		    ((STp->density << MT_ST_DENSITY_SHIFT) & MT_ST_DENSITY_MASK);
3108     		mt_status.mt_blkno = STps->drv_block;
3109     		mt_status.mt_fileno = STps->drv_file;
3110     		if (STp->block_size != 0) {
3111     			if (STps->rw == ST_WRITING)
3112     				mt_status.mt_blkno +=
3113     				    (STp->buffer)->buffer_bytes / STp->block_size;
3114     			else if (STps->rw == ST_READING)
3115     				mt_status.mt_blkno -=
3116                                             ((STp->buffer)->buffer_bytes +
3117                                              STp->block_size - 1) / STp->block_size;
3118     		}
3119     
3120     		mt_status.mt_gstat = 0;
3121     		if (STp->drv_write_prot)
3122     			mt_status.mt_gstat |= GMT_WR_PROT(0xffffffff);
3123     		if (mt_status.mt_blkno == 0) {
3124     			if (mt_status.mt_fileno == 0)
3125     				mt_status.mt_gstat |= GMT_BOT(0xffffffff);
3126     			else
3127     				mt_status.mt_gstat |= GMT_EOF(0xffffffff);
3128     		}
3129     		mt_status.mt_erreg = (STp->recover_reg << MT_ST_SOFTERR_SHIFT);
3130     		mt_status.mt_resid = STp->partition;
3131     		if (STps->eof == ST_EOM_OK || STps->eof == ST_EOM_ERROR)
3132     			mt_status.mt_gstat |= GMT_EOT(0xffffffff);
3133     		else if (STps->eof >= ST_EOM_OK)
3134     			mt_status.mt_gstat |= GMT_EOD(0xffffffff);
3135     		if (STp->density == 1)
3136     			mt_status.mt_gstat |= GMT_D_800(0xffffffff);
3137     		else if (STp->density == 2)
3138     			mt_status.mt_gstat |= GMT_D_1600(0xffffffff);
3139     		else if (STp->density == 3)
3140     			mt_status.mt_gstat |= GMT_D_6250(0xffffffff);
3141     		if (STp->ready == ST_READY)
3142     			mt_status.mt_gstat |= GMT_ONLINE(0xffffffff);
3143     		if (STp->ready == ST_NO_TAPE)
3144     			mt_status.mt_gstat |= GMT_DR_OPEN(0xffffffff);
3145     		if (STps->at_sm)
3146     			mt_status.mt_gstat |= GMT_SM(0xffffffff);
3147     		if (STm->do_async_writes ||
3148                         (STm->do_buffer_writes && STp->block_size != 0) ||
3149     		    STp->drv_buffer != 0)
3150     			mt_status.mt_gstat |= GMT_IM_REP_EN(0xffffffff);
3151     
3152     		i = copy_to_user((char *) arg, (char *) &(mt_status),
3153     				 sizeof(struct mtget));
3154     		if (i) {
3155     			retval = (-EFAULT);
3156     			goto out;
3157     		}
3158     
3159     		STp->recover_reg = 0;		/* Clear after read */
3160     		retval = 0;
3161     		goto out;
3162     	}			/* End of MTIOCGET */
3163     	if (cmd_type == _IOC_TYPE(MTIOCPOS) && cmd_nr == _IOC_NR(MTIOCPOS)) {
3164     		struct mtpos mt_pos;
3165     		if (_IOC_SIZE(cmd_in) != sizeof(struct mtpos)) {
3166     			 retval = (-EINVAL);
3167     			 goto out;
3168     		}
3169     		if ((i = get_location(STp, &blk, &bt, 0)) < 0) {
3170     			retval = i;
3171     			goto out;
3172     		}
3173     		mt_pos.mt_blkno = blk;
3174     		i = copy_to_user((char *) arg, (char *) (&mt_pos), sizeof(struct mtpos));
3175     		if (i)
3176     			retval = (-EFAULT);
3177     		goto out;
3178     	}
3179     	up(&STp->lock);
3180     	return scsi_ioctl(STp->device, cmd_in, (void *) arg);
3181     
3182      out:
3183     	up(&STp->lock);
3184     	return retval;
3185     }
3186     
3187     
3188     /* Try to allocate a new tape buffer. Calling function must not hold
3189        dev_arr_lock. */
3190     static ST_buffer *
3191      new_tape_buffer(int from_initialization, int need_dma, int in_use)
3192     {
3193     	int i, priority, b_size, order, got = 0, segs = 0;
3194     	unsigned long flags;
3195     	ST_buffer *tb;
3196     
3197     	read_lock(&st_dev_arr_lock);
3198     	if (st_nbr_buffers >= st_template.dev_max) {
3199     		read_unlock(&st_dev_arr_lock);
3200     		return NULL;	/* Should never happen */
3201     	}
3202     	read_unlock(&st_dev_arr_lock);
3203     
3204     	if (from_initialization)
3205     		priority = GFP_ATOMIC;
3206     	else
3207     		priority = GFP_KERNEL;
3208     
3209     	i = sizeof(ST_buffer) + (st_max_sg_segs - 1) * sizeof(struct scatterlist);
3210     	tb = kmalloc(i, priority);
3211     	if (tb) {
3212     		if (need_dma)
3213     			priority |= GFP_DMA;
3214     
3215     		/* Try to allocate the first segment up to ST_FIRST_ORDER and the
3216     		   others big enough to reach the goal */
3217     		for (b_size = PAGE_SIZE, order=0;
3218     		     b_size < st_buffer_size && order < ST_FIRST_ORDER;
3219     		     order++, b_size *= 2)
3220     			;
3221     		for ( ; b_size >= PAGE_SIZE; order--, b_size /= 2) {
3222     			tb->sg[0].address =
3223     			    (unsigned char *) __get_free_pages(priority, order);
3224     			if (tb->sg[0].address != NULL) {
3225     				tb->sg[0].alt_address = NULL;
3226     				tb->sg[0].length = b_size;
3227     				break;
3228     			}
3229     		}
3230     		if (tb->sg[segs].address == NULL) {
3231     			kfree(tb);
3232     			tb = NULL;
3233     		} else {	/* Got something, continue */
3234     
3235     			for (b_size = PAGE_SIZE, order=0;
3236     			     st_buffer_size >
3237                                          tb->sg[0].length + (ST_FIRST_SG - 1) * b_size;
3238     			     order++, b_size *= 2)
3239     				;
3240     			for (segs = 1, got = tb->sg[0].length;
3241     			     got < st_buffer_size && segs < ST_FIRST_SG;) {
3242     				tb->sg[segs].address =
3243     					(unsigned char *) __get_free_pages(priority,
3244     									   order);
3245     				if (tb->sg[segs].address == NULL) {
3246     					if (st_buffer_size - got <=
3247     					    (ST_FIRST_SG - segs) * b_size / 2) {
3248     						b_size /= 2; /* Large enough for the
3249                                                                     rest of the buffers */
3250     						order--;
3251     						continue;
3252     					}
3253     					tb->sg_segs = segs;
3254     					tb->orig_sg_segs = 0;
3255     					DEB(tb->buffer_size = got);
3256     					normalize_buffer(tb);
3257     					kfree(tb);
3258     					tb = NULL;
3259     					break;
3260     				}
3261     				tb->sg[segs].alt_address = NULL;
3262     				tb->sg[segs].length = b_size;
3263     				got += b_size;
3264     				segs++;
3265     			}
3266     		}
3267     	}
3268     
3269     	if (!tb) {
3270     		printk(KERN_NOTICE "st: Can't allocate new tape buffer (nbr %d).\n",
3271     		       st_nbr_buffers);
3272     		return NULL;
3273     	}
3274     	tb->sg_segs = tb->orig_sg_segs = segs;
3275     	tb->b_data = tb->sg[0].address;
3276     
3277             DEBC(printk(ST_DEB_MSG
3278                         "st: Allocated tape buffer %d (%d bytes, %d segments, dma: %d, a: %p).\n",
3279                         st_nbr_buffers, got, tb->sg_segs, need_dma, tb->b_data);
3280                  printk(ST_DEB_MSG
3281                         "st: segment sizes: first %d, last %d bytes.\n",
3282                         tb->sg[0].length, tb->sg[segs - 1].length);
3283     	)
3284     	tb->in_use = in_use;
3285     	tb->dma = need_dma;
3286     	tb->buffer_size = got;
3287     	tb->writing = 0;
3288     
3289     	write_lock_irqsave(&st_dev_arr_lock, flags);
3290     	st_buffers[st_nbr_buffers++] = tb;
3291     	write_unlock_irqrestore(&st_dev_arr_lock, flags);
3292     
3293     	return tb;
3294     }
3295     
3296     
3297     /* Try to allocate a temporary enlarged tape buffer */
3298     static int enlarge_buffer(ST_buffer * STbuffer, int new_size, int need_dma)
3299     {
3300     	int segs, nbr, max_segs, b_size, priority, order, got;
3301     
3302     	normalize_buffer(STbuffer);
3303     
3304     	max_segs = STbuffer->use_sg;
3305     	if (max_segs > st_max_sg_segs)
3306     		max_segs = st_max_sg_segs;
3307     	nbr = max_segs - STbuffer->sg_segs;
3308     	if (nbr <= 0)
3309     		return FALSE;
3310     
3311     	priority = GFP_KERNEL;
3312     	if (need_dma)
3313     		priority |= GFP_DMA;
3314     	for (b_size = PAGE_SIZE, order=0;
3315     	     b_size * nbr < new_size - STbuffer->buffer_size;
3316     	     order++, b_size *= 2)
3317     		;  /* empty */
3318     
3319     	for (segs = STbuffer->sg_segs, got = STbuffer->buffer_size;
3320     	     segs < max_segs && got < new_size;) {
3321     		STbuffer->sg[segs].address =
3322     			(unsigned char *) __get_free_pages(priority, order);
3323     		if (STbuffer->sg[segs].address == NULL) {
3324     			if (new_size - got <= (max_segs - segs) * b_size / 2) {
3325     				b_size /= 2; /* Large enough for the rest of the buffers */
3326     				order--;
3327     				continue;
3328     			}
3329     			printk(KERN_NOTICE "st: failed to enlarge buffer to %d bytes.\n",
3330     			       new_size);
3331     			DEB(STbuffer->buffer_size = got);
3332     			normalize_buffer(STbuffer);
3333     			return FALSE;
3334     		}
3335     		STbuffer->sg[segs].alt_address = NULL;
3336     		STbuffer->sg[segs].length = b_size;
3337     		STbuffer->sg_segs += 1;
3338     		got += b_size;
3339     		STbuffer->buffer_size = got;
3340     		segs++;
3341     	}
3342             DEBC(printk(ST_DEB_MSG
3343                         "st: Succeeded to enlarge buffer to %d bytes (segs %d->%d, %d).\n",
3344                         got, STbuffer->orig_sg_segs, STbuffer->sg_segs, b_size));
3345     
3346     	return TRUE;
3347     }
3348     
3349     
3350     /* Release the extra buffer */
3351     static void normalize_buffer(ST_buffer * STbuffer)
3352     {
3353     	int i, order, b_size;
3354     
3355     	for (i = STbuffer->orig_sg_segs; i < STbuffer->sg_segs; i++) {
3356     		for (b_size=PAGE_SIZE, order=0; b_size < STbuffer->sg[i].length;
3357     		     order++, b_size *= 2)
3358     			; /* empty */
3359     		free_pages((unsigned long)(STbuffer->sg[i].address), order);
3360     		STbuffer->buffer_size -= STbuffer->sg[i].length;
3361     	}
3362             DEB(
3363     	if (debugging && STbuffer->orig_sg_segs < STbuffer->sg_segs)
3364     		printk(ST_DEB_MSG "st: Buffer at %p normalized to %d bytes (segs %d).\n",
3365     		       STbuffer->sg[0].address, STbuffer->buffer_size,
3366     		       STbuffer->sg_segs);
3367             ) /* end DEB */
3368     	STbuffer->sg_segs = STbuffer->orig_sg_segs;
3369     }
3370     
3371     
3372     /* Move data from the user buffer to the tape buffer. Returns zero (success) or
3373        negative error code. */
3374     static int append_to_buffer(const char *ubp, ST_buffer * st_bp, int do_count)
3375     {
3376     	int i, cnt, res, offset;
3377     
3378     	for (i = 0, offset = st_bp->buffer_bytes;
3379     	     i < st_bp->sg_segs && offset >= st_bp->sg[i].length; i++)
3380     		offset -= st_bp->sg[i].length;
3381     	if (i == st_bp->sg_segs) {	/* Should never happen */
3382     		printk(KERN_WARNING "st: append_to_buffer offset overflow.\n");
3383     		return (-EIO);
3384     	}
3385     	for (; i < st_bp->sg_segs && do_count > 0; i++) {
3386     		cnt = st_bp->sg[i].length - offset < do_count ?
3387     		    st_bp->sg[i].length - offset : do_count;
3388     		res = copy_from_user(st_bp->sg[i].address + offset, ubp, cnt);
3389     		if (res)
3390     			return (-EFAULT);
3391     		do_count -= cnt;
3392     		st_bp->buffer_bytes += cnt;
3393     		ubp += cnt;
3394     		offset = 0;
3395     	}
3396     	if (do_count) {		/* Should never happen */
3397     		printk(KERN_WARNING "st: append_to_buffer overflow (left %d).\n",
3398     		       do_count);
3399     		return (-EIO);
3400     	}
3401     	return 0;
3402     }
3403     
3404     
3405     /* Move data from the tape buffer to the user buffer. Returns zero (success) or
3406        negative error code. */
3407     static int from_buffer(ST_buffer * st_bp, char *ubp, int do_count)
3408     {
3409     	int i, cnt, res, offset;
3410     
3411     	for (i = 0, offset = st_bp->read_pointer;
3412     	     i < st_bp->sg_segs && offset >= st_bp->sg[i].length; i++)
3413     		offset -= st_bp->sg[i].length;
3414     	if (i == st_bp->sg_segs) {	/* Should never happen */
3415     		printk(KERN_WARNING "st: from_buffer offset overflow.\n");
3416     		return (-EIO);
3417     	}
3418     	for (; i < st_bp->sg_segs && do_count > 0; i++) {
3419     		cnt = st_bp->sg[i].length - offset < do_count ?
3420     		    st_bp->sg[i].length - offset : do_count;
3421     		res = copy_to_user(ubp, st_bp->sg[i].address + offset, cnt);
3422     		if (res)
3423     			return (-EFAULT);
3424     		do_count -= cnt;
3425     		st_bp->buffer_bytes -= cnt;
3426     		st_bp->read_pointer += cnt;
3427     		ubp += cnt;
3428     		offset = 0;
3429     	}
3430     	if (do_count) {		/* Should never happen */
3431     		printk(KERN_WARNING "st: from_buffer overflow (left %d).\n",
3432     		       do_count);
3433     		return (-EIO);
3434     	}
3435     	return 0;
3436     }
3437     
3438     
3439     /* Validate the options from command line or module parameters */
3440     static void validate_options(void)
3441     {
3442     	if (buffer_kbs > 0)
3443     		st_buffer_size = buffer_kbs * ST_KILOBYTE;
3444     	if (write_threshold_kbs > 0)
3445     		st_write_threshold = write_threshold_kbs * ST_KILOBYTE;
3446     	else if (buffer_kbs > 0)
3447     		st_write_threshold = st_buffer_size - 2048;
3448     	if (st_write_threshold > st_buffer_size) {
3449     		st_write_threshold = st_buffer_size;
3450     		printk(KERN_WARNING "st: write_threshold limited to %d bytes.\n",
3451     		       st_write_threshold);
3452     	}
3453     	if (max_buffers >= 0)
3454     		st_max_buffers = max_buffers;
3455     	if (max_sg_segs >= ST_FIRST_SG)
3456     		st_max_sg_segs = max_sg_segs;
3457     }
3458     
3459     #ifndef MODULE
3460     /* Set the boot options. Syntax is defined in README.st.
3461      */
3462     static int __init st_setup(char *str)
3463     {
3464     	int i, len, ints[5];
3465     	char *stp;
3466     
3467     	stp = get_options(str, ARRAY_SIZE(ints), ints);
3468     
3469     	if (ints[0] > 0) {
3470     		for (i = 0; i < ints[0] && i < ARRAY_SIZE(parms); i++)
3471     			*parms[i].val = ints[i + 1];
3472     	} else {
3473     		while (stp != NULL) {
3474     			for (i = 0; i < ARRAY_SIZE(parms); i++) {
3475     				len = strlen(parms[i].name);
3476     				if (!strncmp(stp, parms[i].name, len) &&
3477     				    (*(stp + len) == ':' || *(stp + len) == '=')) {
3478     					*parms[i].val =
3479                                                     simple_strtoul(stp + len + 1, NULL, 0);
3480     					break;
3481     				}
3482     			}
3483     			if (i >= sizeof(parms) / sizeof(struct st_dev_parm))
3484     				 printk(KERN_WARNING "st: illegal parameter in '%s'\n",
3485     					stp);
3486     			stp = strchr(stp, ',');
3487     			if (stp)
3488     				stp++;
3489     		}
3490     	}
3491     
3492     	validate_options();
3493     
3494     	return 1;
3495     }
3496     
3497     __setup("st=", st_setup);
3498     
3499     #endif
3500     
3501     
3502     static struct file_operations st_fops =
3503     {
3504     	owner:		THIS_MODULE,
3505     	read:		st_read,
3506     	write:		st_write,
3507     	ioctl:		st_ioctl,
3508     	open:		st_open,
3509     	flush:		st_flush,
3510     	release:	st_release,
3511     };
3512     
3513     static int st_attach(Scsi_Device * SDp)
3514     {
3515     	Scsi_Tape *tpnt;
3516     	ST_mode *STm;
3517     	ST_partstat *STps;
3518     	int i, mode, target_nbr, dev_num;
3519     	unsigned long flags = 0;
3520     	char *stp;
3521     
3522     	if (SDp->type != TYPE_TAPE)
3523     		return 1;
3524     	if ((stp = st_incompatible(SDp))) {
3525     		printk(KERN_INFO
3526     		       "st: Found incompatible tape at scsi%d, channel %d, id %d, lun %d\n",
3527     		       SDp->host->host_no, SDp->channel, SDp->id, SDp->lun);
3528     		printk(KERN_INFO "st: The suggested driver is %s.\n", stp);
3529     		return 1;
3530     	}
3531     
3532     	write_lock_irqsave(&st_dev_arr_lock, flags);
3533     	if (st_template.nr_dev >= st_template.dev_max) {
3534     		Scsi_Tape **tmp_da;
3535     		ST_buffer **tmp_ba;
3536     		int tmp_dev_max;
3537     
3538     		tmp_dev_max = st_template.nr_dev + ST_DEV_ARR_LUMP;
3539     		if (tmp_dev_max > ST_MAX_TAPES)
3540     			tmp_dev_max = ST_MAX_TAPES;
3541     		if (tmp_dev_max <= st_template.nr_dev) {
3542     			SDp->attached--;
3543     			write_unlock_irqrestore(&st_dev_arr_lock, flags);
3544     			printk(KERN_ERR "st: Too many tape devices (max. %d).\n",
3545     			       ST_MAX_TAPES);
3546     			return 1;
3547     		}
3548     
3549     		tmp_da = kmalloc(tmp_dev_max * sizeof(Scsi_Tape *), GFP_ATOMIC);
3550     		tmp_ba = kmalloc(tmp_dev_max * sizeof(ST_buffer *), GFP_ATOMIC);
3551     		if (tmp_da == NULL || tmp_ba == NULL) {
3552     			if (tmp_da != NULL)
3553     				kfree(tmp_da);
3554     			if (tmp_ba != NULL)
3555     				kfree(tmp_ba);
3556     			SDp->attached--;
3557     			write_unlock_irqrestore(&st_dev_arr_lock, flags);
3558     			printk(KERN_ERR "st: Can't extend device array.\n");
3559     			return 1;
3560     		}
3561     
3562     		memset(tmp_da, 0, tmp_dev_max * sizeof(Scsi_Tape *));
3563     		if (scsi_tapes != NULL) {
3564     			memcpy(tmp_da, scsi_tapes,
3565     			       st_template.dev_max * sizeof(Scsi_Tape *));
3566     			kfree(scsi_tapes);
3567     		}
3568     		scsi_tapes = tmp_da;
3569     
3570     		memset(tmp_ba, 0, tmp_dev_max * sizeof(ST_buffer *));
3571     		if (st_buffers != NULL) {
3572     			memcpy(tmp_ba, st_buffers,
3573     			       st_template.dev_max * sizeof(ST_buffer *));
3574     			kfree(st_buffers);
3575     		}
3576     		st_buffers = tmp_ba;
3577     
3578     		st_template.dev_max = tmp_dev_max;
3579     	}
3580     
3581     	for (i = 0; i < st_template.dev_max; i++)
3582     		if (scsi_tapes[i] == NULL)
3583     			break;
3584     	if (i >= st_template.dev_max)
3585     		panic("scsi_devices corrupt (st)");
3586     
3587     	tpnt = kmalloc(sizeof(Scsi_Tape), GFP_ATOMIC);
3588     	if (tpnt == NULL) {
3589     		SDp->attached--;
3590     		write_unlock_irqrestore(&st_dev_arr_lock, flags);
3591     		printk(KERN_ERR "st: Can't allocate device descriptor.\n");
3592     		return 1;
3593     	}
3594     	memset(tpnt, 0, sizeof(Scsi_Tape));
3595     	scsi_tapes[i] = tpnt;
3596     	dev_num = i;
3597     
3598     	for (mode = 0; mode < ST_NBR_MODES; ++mode) {
3599     	    char name[8];
3600     	    static char *formats[ST_NBR_MODES] ={"", "l", "m", "a"};
3601     
3602     	    /*  Rewind entry  */
3603     	    sprintf (name, "mt%s", formats[mode]);
3604     	    tpnt->de_r[mode] =
3605     		devfs_register (SDp->de, name, DEVFS_FL_DEFAULT,
3606     				MAJOR_NR, i + (mode << 5),
3607     				S_IFCHR | S_IRUGO | S_IWUGO,
3608     				&st_fops, NULL);
3609     	    /*  No-rewind entry  */
3610     	    sprintf (name, "mt%sn", formats[mode]);
3611     	    tpnt->de_n[mode] =
3612     		devfs_register (SDp->de, name, DEVFS_FL_DEFAULT,
3613     				MAJOR_NR, i + (mode << 5) + 128,
3614     				S_IFCHR | S_IRUGO | S_IWUGO,
3615     				&st_fops, NULL);
3616     	}
3617     	devfs_register_tape (tpnt->de_r[0]);
3618     	tpnt->device = SDp;
3619     	if (SDp->scsi_level <= 2)
3620     		tpnt->tape_type = MT_ISSCSI1;
3621     	else
3622     		tpnt->tape_type = MT_ISSCSI2;
3623     
3624             tpnt->inited = 0;
3625     	tpnt->devt = MKDEV(SCSI_TAPE_MAJOR, i);
3626     	tpnt->dirty = 0;
3627     	tpnt->in_use = 0;
3628     	tpnt->drv_buffer = 1;	/* Try buffering if no mode sense */
3629     	tpnt->restr_dma = (SDp->host)->unchecked_isa_dma;
3630     	tpnt->use_pf = (SDp->scsi_level >= SCSI_2);
3631     	tpnt->density = 0;
3632     	tpnt->do_auto_lock = ST_AUTO_LOCK;
3633     	tpnt->can_bsr = ST_IN_FILE_POS;
3634     	tpnt->can_partitions = 0;
3635     	tpnt->two_fm = ST_TWO_FM;
3636     	tpnt->fast_mteom = ST_FAST_MTEOM;
3637     	tpnt->scsi2_logical = ST_SCSI2LOGICAL;
3638     	tpnt->write_threshold = st_write_threshold;
3639     	tpnt->default_drvbuffer = 0xff;		/* No forced buffering */
3640     	tpnt->partition = 0;
3641     	tpnt->new_partition = 0;
3642     	tpnt->nbr_partitions = 0;
3643     	tpnt->timeout = ST_TIMEOUT;
3644     	tpnt->long_timeout = ST_LONG_TIMEOUT;
3645     
3646     	for (i = 0; i < ST_NBR_MODES; i++) {
3647     		STm = &(tpnt->modes[i]);
3648     		STm->defined = FALSE;
3649     		STm->sysv = ST_SYSV;
3650     		STm->defaults_for_writes = 0;
3651     		STm->do_async_writes = ST_ASYNC_WRITES;
3652     		STm->do_buffer_writes = ST_BUFFER_WRITES;
3653     		STm->do_read_ahead = ST_READ_AHEAD;
3654     		STm->default_compression = ST_DONT_TOUCH;
3655     		STm->default_blksize = (-1);	/* No forced size */
3656     		STm->default_density = (-1);	/* No forced density */
3657     	}
3658     
3659     	for (i = 0; i < ST_NBR_PARTITIONS; i++) {
3660     		STps = &(tpnt->ps[i]);
3661     		STps->rw = ST_IDLE;
3662     		STps->eof = ST_NOEOF;
3663     		STps->at_sm = 0;
3664     		STps->last_block_valid = FALSE;
3665     		STps->drv_block = (-1);
3666     		STps->drv_file = (-1);
3667     	}
3668     
3669     	tpnt->current_mode = 0;
3670     	tpnt->modes[0].defined = TRUE;
3671     
3672     	tpnt->density_changed = tpnt->compression_changed =
3673     	    tpnt->blksize_changed = FALSE;
3674     	init_MUTEX(&tpnt->lock);
3675     
3676     	st_template.nr_dev++;
3677     	write_unlock_irqrestore(&st_dev_arr_lock, flags);
3678     	printk(KERN_WARNING
3679     	"Attached scsi tape st%d at scsi%d, channel %d, id %d, lun %d\n",
3680     	       dev_num, SDp->host->host_no, SDp->channel, SDp->id, SDp->lun);
3681     
3682     	/* See if we need to allocate more static buffers */
3683     	target_nbr = st_template.nr_dev;
3684     	if (target_nbr > st_max_buffers)
3685     		target_nbr = st_max_buffers;
3686     	for (i=st_nbr_buffers; i < target_nbr; i++)
3687     		if (!new_tape_buffer(TRUE, TRUE, FALSE)) {
3688     			printk(KERN_INFO "st: Unable to allocate new static buffer.\n");
3689     			break;
3690     		}
3691     	/* If the previous allocation fails, we will try again when the buffer is
3692     	   really needed. */
3693     
3694     	return 0;
3695     };
3696     
3697     static int st_detect(Scsi_Device * SDp)
3698     {
3699     	if (SDp->type != TYPE_TAPE || st_incompatible(SDp))
3700     		return 0;
3701             st_template.dev_noticed++;
3702     	return 1;
3703     }
3704     
3705     static int st_registered = 0;
3706     
3707     /* Driver initialization (not __init because may be called later) */
3708     static int st_init()
3709     {
3710     	unsigned long flags;
3711     
3712     	if (st_template.dev_noticed == 0 || st_registered)
3713     		return 0;
3714     
3715     	printk(KERN_INFO
3716     	       "st: Version %s, bufsize %d, wrt %d, max init. bufs %d, s/g segs %d\n",
3717     	       verstr, st_buffer_size, st_write_threshold, st_max_buffers, st_max_sg_segs);
3718     
3719     	write_lock_irqsave(&st_dev_arr_lock, flags);
3720     	if (!st_registered) {
3721     		if (devfs_register_chrdev(SCSI_TAPE_MAJOR, "st", &st_fops)) {
3722     			write_unlock_irqrestore(&st_dev_arr_lock, flags);
3723     			printk(KERN_ERR "Unable to get major %d for SCSI tapes\n",
3724                                    MAJOR_NR);
3725     			return 1;
3726     		}
3727     		st_registered++;
3728     	}
3729     
3730     	st_template.dev_max = 0;
3731     	st_nbr_buffers = 0;
3732     	write_unlock_irqrestore(&st_dev_arr_lock, flags);
3733     
3734     	return 0;
3735     }
3736     
3737     static void st_detach(Scsi_Device * SDp)
3738     {
3739     	Scsi_Tape *tpnt;
3740     	int i, mode;
3741     	unsigned long flags;
3742     
3743     	write_lock_irqsave(&st_dev_arr_lock, flags);
3744     	for (i = 0; i < st_template.dev_max; i++) {
3745     		tpnt = scsi_tapes[i];
3746     		if (tpnt != NULL && tpnt->device == SDp) {
3747     			tpnt->device = NULL;
3748     			for (mode = 0; mode < ST_NBR_MODES; ++mode) {
3749     				devfs_unregister (tpnt->de_r[mode]);
3750     				tpnt->de_r[mode] = NULL;
3751     				devfs_unregister (tpnt->de_n[mode]);
3752     				tpnt->de_n[mode] = NULL;
3753     			}
3754     			kfree(tpnt);
3755     			scsi_tapes[i] = 0;
3756     			SDp->attached--;
3757     			st_template.nr_dev--;
3758     			st_template.dev_noticed--;
3759     			write_unlock_irqrestore(&st_dev_arr_lock, flags);
3760     			return;
3761     		}
3762     	}
3763     
3764     	write_unlock_irqrestore(&st_dev_arr_lock, flags);
3765     	return;
3766     }
3767     
3768     
3769     static int __init init_st(void)
3770     {
3771     	validate_options();
3772     
3773     	st_template.module = THIS_MODULE;
3774             return scsi_register_module(MODULE_SCSI_DEV, &st_template);
3775     }
3776     
3777     static void __exit exit_st(void)
3778     {
3779     	int i;
3780     
3781     	scsi_unregister_module(MODULE_SCSI_DEV, &st_template);
3782     	devfs_unregister_chrdev(SCSI_TAPE_MAJOR, "st");
3783     	st_registered--;
3784     	if (scsi_tapes != NULL) {
3785     		for (i=0; i < st_template.dev_max; ++i)
3786     			if (scsi_tapes[i])
3787     				kfree(scsi_tapes[i]);
3788     		kfree(scsi_tapes);
3789     		if (st_buffers != NULL) {
3790     			for (i = 0; i < st_nbr_buffers; i++) {
3791     				if (st_buffers[i] != NULL) {
3792     					st_buffers[i]->orig_sg_segs = 0;
3793     					normalize_buffer(st_buffers[i]);
3794     					kfree(st_buffers[i]);
3795     				}
3796     			}	
3797     			kfree(st_buffers);
3798     		}
3799     	}
3800     	st_template.dev_max = 0;
3801     	printk(KERN_INFO "st: Unloaded.\n");
3802     }
3803     
3804     module_init(init_st);
3805     module_exit(exit_st);
3806