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