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