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