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