VServer 1.9.2 (patch-2.6.8.1-vs1.9.2.diff)
[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 = "20040403";
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 <scsi/scsi_host.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 __user *, ST_buffer *, int);
180 static int from_buffer(ST_buffer *, char __user *, 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->device->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->device->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->device->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->device->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         nonseekable_open(inode, filp);
1005         write_lock(&st_dev_arr_lock);
1006         if (dev >= st_dev_max || scsi_tapes == NULL ||
1007             ((STp = scsi_tapes[dev]) == NULL)) {
1008                 write_unlock(&st_dev_arr_lock);
1009                 return (-ENXIO);
1010         }
1011         filp->private_data = STp;
1012         name = tape_name(STp);
1013
1014         if (STp->in_use) {
1015                 write_unlock(&st_dev_arr_lock);
1016                 DEB( printk(ST_DEB_MSG "%s: Device already in use.\n", name); )
1017                 return (-EBUSY);
1018         }
1019
1020         if(scsi_device_get(STp->device)) {
1021                 write_unlock(&st_dev_arr_lock);
1022                 return (-ENXIO);
1023         }
1024         STp->in_use = 1;
1025         write_unlock(&st_dev_arr_lock);
1026         STp->rew_at_close = STp->autorew_dev = (iminor(inode) & 0x80) == 0;
1027
1028         if (!scsi_block_when_processing_errors(STp->device)) {
1029                 retval = (-ENXIO);
1030                 goto err_out;
1031         }
1032
1033         /* See that we have at least a one page buffer available */
1034         if (!enlarge_buffer(STp->buffer, PAGE_SIZE, STp->restr_dma)) {
1035                 printk(KERN_WARNING "%s: Can't allocate one page tape buffer.\n",
1036                        name);
1037                 retval = (-EOVERFLOW);
1038                 goto err_out;
1039         }
1040
1041         (STp->buffer)->writing = 0;
1042         (STp->buffer)->syscall_result = 0;
1043
1044         STp->write_prot = ((filp->f_flags & O_ACCMODE) == O_RDONLY);
1045
1046         STp->dirty = 0;
1047         for (i = 0; i < ST_NBR_PARTITIONS; i++) {
1048                 STps = &(STp->ps[i]);
1049                 STps->rw = ST_IDLE;
1050         }
1051         STp->recover_count = 0;
1052         DEB( STp->nbr_waits = STp->nbr_finished = 0;
1053              STp->nbr_requests = STp->nbr_dio = STp->nbr_pages = STp->nbr_combinable = 0; )
1054
1055         retval = check_tape(STp, filp);
1056         if (retval < 0)
1057                 goto err_out;
1058         if ((filp->f_flags & O_NONBLOCK) == 0 &&
1059             retval != CHKRES_READY) {
1060                 retval = (-EIO);
1061                 goto err_out;
1062         }
1063         return 0;
1064
1065  err_out:
1066         normalize_buffer(STp->buffer);
1067         STp->in_use = 0;
1068         scsi_device_put(STp->device);
1069         return retval;
1070
1071 }
1072 \f
1073
1074 /* Flush the tape buffer before close */
1075 static int st_flush(struct file *filp)
1076 {
1077         int result = 0, result2;
1078         unsigned char cmd[MAX_COMMAND_SIZE];
1079         Scsi_Request *SRpnt;
1080         Scsi_Tape *STp = filp->private_data;
1081         ST_mode *STm = &(STp->modes[STp->current_mode]);
1082         ST_partstat *STps = &(STp->ps[STp->partition]);
1083         char *name = tape_name(STp);
1084
1085         if (file_count(filp) > 1)
1086                 return 0;
1087
1088         if (STps->rw == ST_WRITING && !STp->pos_unknown) {
1089                 result = flush_write_buffer(STp);
1090                 if (result != 0 && result != (-ENOSPC))
1091                         goto out;
1092         }
1093
1094         if (STp->can_partitions &&
1095             (result2 = switch_partition(STp)) < 0) {
1096                 DEBC(printk(ST_DEB_MSG
1097                                "%s: switch_partition at close failed.\n", name));
1098                 if (result == 0)
1099                         result = result2;
1100                 goto out;
1101         }
1102
1103         DEBC( if (STp->nbr_requests)
1104                 printk(KERN_WARNING "%s: Number of r/w requests %d, dio used in %d, pages %d (%d).\n",
1105                        name, STp->nbr_requests, STp->nbr_dio, STp->nbr_pages, STp->nbr_combinable));
1106
1107         if (STps->rw == ST_WRITING && !STp->pos_unknown) {
1108
1109                 DEBC(printk(ST_DEB_MSG "%s: File length %ld bytes.\n",
1110                             name, (long) (filp->f_pos));
1111                      printk(ST_DEB_MSG "%s: Async write waits %d, finished %d.\n",
1112                             name, STp->nbr_waits, STp->nbr_finished);
1113                 )
1114
1115                 memset(cmd, 0, MAX_COMMAND_SIZE);
1116                 cmd[0] = WRITE_FILEMARKS;
1117                 cmd[4] = 1 + STp->two_fm;
1118
1119                 SRpnt = st_do_scsi(NULL, STp, cmd, 0, SCSI_DATA_NONE,
1120                                    STp->device->timeout, MAX_WRITE_RETRIES, TRUE);
1121                 if (!SRpnt) {
1122                         result = (STp->buffer)->syscall_result;
1123                         goto out;
1124                 }
1125
1126                 if ((STp->buffer)->syscall_result != 0 &&
1127                     ((SRpnt->sr_sense_buffer[0] & 0x70) != 0x70 ||
1128                      (SRpnt->sr_sense_buffer[2] & 0x4f) != 0x40 ||
1129                      ((SRpnt->sr_sense_buffer[0] & 0x80) != 0 &&
1130                       (SRpnt->sr_sense_buffer[3] | SRpnt->sr_sense_buffer[4] |
1131                        SRpnt->sr_sense_buffer[5] |
1132                        SRpnt->sr_sense_buffer[6]) != 0))) {
1133                         /* Filter out successful write at EOM */
1134                         scsi_release_request(SRpnt);
1135                         SRpnt = NULL;
1136                         printk(KERN_ERR "%s: Error on write filemark.\n", name);
1137                         if (result == 0)
1138                                 result = (-EIO);
1139                 } else {
1140                         scsi_release_request(SRpnt);
1141                         SRpnt = NULL;
1142                         if (STps->drv_file >= 0)
1143                                 STps->drv_file++;
1144                         STps->drv_block = 0;
1145                         if (STp->two_fm)
1146                                 cross_eof(STp, FALSE);
1147                         STps->eof = ST_FM;
1148                 }
1149
1150                 DEBC(printk(ST_DEB_MSG "%s: Buffer flushed, %d EOF(s) written\n",
1151                             name, cmd[4]));
1152         } else if (!STp->rew_at_close) {
1153                 STps = &(STp->ps[STp->partition]);
1154                 if (!STm->sysv || STps->rw != ST_READING) {
1155                         if (STp->can_bsr)
1156                                 result = flush_buffer(STp, 0);
1157                         else if (STps->eof == ST_FM_HIT) {
1158                                 result = cross_eof(STp, FALSE);
1159                                 if (result) {
1160                                         if (STps->drv_file >= 0)
1161                                                 STps->drv_file++;
1162                                         STps->drv_block = 0;
1163                                         STps->eof = ST_FM;
1164                                 } else
1165                                         STps->eof = ST_NOEOF;
1166                         }
1167                 } else if ((STps->eof == ST_NOEOF &&
1168                             !(result = cross_eof(STp, TRUE))) ||
1169                            STps->eof == ST_FM_HIT) {
1170                         if (STps->drv_file >= 0)
1171                                 STps->drv_file++;
1172                         STps->drv_block = 0;
1173                         STps->eof = ST_FM;
1174                 }
1175         }
1176
1177       out:
1178         if (STp->rew_at_close) {
1179                 result2 = st_int_ioctl(STp, MTREW, 1);
1180                 if (result == 0)
1181                         result = result2;
1182         }
1183         return result;
1184 }
1185
1186
1187 /* Close the device and release it. BKL is not needed: this is the only thread
1188    accessing this tape. */
1189 static int st_release(struct inode *inode, struct file *filp)
1190 {
1191         int result = 0;
1192         Scsi_Tape *STp = filp->private_data;
1193
1194         if (STp->door_locked == ST_LOCKED_AUTO)
1195                 do_door_lock(STp, 0);
1196
1197         normalize_buffer(STp->buffer);
1198         write_lock(&st_dev_arr_lock);
1199         STp->in_use = 0;
1200         write_unlock(&st_dev_arr_lock);
1201         scsi_device_put(STp->device);
1202
1203         return result;
1204 }
1205 \f
1206 /* The checks common to both reading and writing */
1207 static ssize_t rw_checks(Scsi_Tape *STp, struct file *filp, size_t count)
1208 {
1209         ssize_t retval = 0;
1210
1211         /*
1212          * If we are in the middle of error recovery, don't let anyone
1213          * else try and use this device.  Also, if error recovery fails, it
1214          * may try and take the device offline, in which case all further
1215          * access to the device is prohibited.
1216          */
1217         if (!scsi_block_when_processing_errors(STp->device)) {
1218                 retval = (-ENXIO);
1219                 goto out;
1220         }
1221
1222         if (STp->ready != ST_READY) {
1223                 if (STp->ready == ST_NO_TAPE)
1224                         retval = (-ENOMEDIUM);
1225                 else
1226                         retval = (-EIO);
1227                 goto out;
1228         }
1229
1230         if (! STp->modes[STp->current_mode].defined) {
1231                 retval = (-ENXIO);
1232                 goto out;
1233         }
1234
1235
1236         /*
1237          * If there was a bus reset, block further access
1238          * to this device.
1239          */
1240         if (STp->pos_unknown) {
1241                 retval = (-EIO);
1242                 goto out;
1243         }
1244
1245         if (count == 0)
1246                 goto out;
1247
1248         DEB(
1249         if (!STp->in_use) {
1250                 printk(ST_DEB_MSG "%s: Incorrect device.\n", tape_name(STp));
1251                 retval = (-EIO);
1252                 goto out;
1253         } ) /* end DEB */
1254
1255         if (STp->can_partitions &&
1256             (retval = switch_partition(STp)) < 0)
1257                 goto out;
1258
1259         if (STp->block_size == 0 && STp->max_block > 0 &&
1260             (count < STp->min_block || count > STp->max_block)) {
1261                 retval = (-EINVAL);
1262                 goto out;
1263         }
1264
1265         if (STp->do_auto_lock && STp->door_locked == ST_UNLOCKED &&
1266             !do_door_lock(STp, 1))
1267                 STp->door_locked = ST_LOCKED_AUTO;
1268
1269  out:
1270         return retval;
1271 }
1272
1273
1274 static int setup_buffering(Scsi_Tape *STp, const char __user *buf, size_t count, int is_read)
1275 {
1276         int i, bufsize, retval = 0;
1277         ST_buffer *STbp = STp->buffer;
1278
1279         if (is_read)
1280                 i = STp->try_dio && try_rdio;
1281         else
1282                 i = STp->try_dio && try_wdio;
1283         if (i && ((unsigned long)buf & queue_dma_alignment(
1284                                         STp->device->request_queue)) == 0) {
1285                 i = st_map_user_pages(&(STbp->sg[0]), STbp->use_sg,
1286                                       (unsigned long)buf, count, (is_read ? READ : WRITE),
1287                                       STp->max_pfn);
1288                 if (i > 0) {
1289                         STbp->do_dio = i;
1290                         STbp->buffer_bytes = 0;   /* can be used as transfer counter */
1291                 }
1292                 else
1293                         STbp->do_dio = FALSE;  /* fall back to buffering with any error */
1294                 STbp->sg_segs = STbp->do_dio;
1295                 STbp->frp_sg_current = 0;
1296                 DEB(
1297                      if (STbp->do_dio) {
1298                         STp->nbr_dio++;
1299                         STp->nbr_pages += STbp->do_dio;
1300                         for (i=1; i < STbp->do_dio; i++)
1301                                 if (page_to_pfn(STbp->sg[i].page) == page_to_pfn(STbp->sg[i-1].page) + 1)
1302                                         STp->nbr_combinable++;
1303                      }
1304                 )
1305         } else
1306                 STbp->do_dio = FALSE;
1307         DEB( STp->nbr_requests++; )
1308
1309         if (!STbp->do_dio) {
1310                 if (STp->block_size)
1311                         bufsize = STp->block_size > st_fixed_buffer_size ?
1312                                 STp->block_size : st_fixed_buffer_size;
1313                 else
1314                         bufsize = count;
1315                 if (bufsize > STbp->buffer_size &&
1316                     !enlarge_buffer(STbp, bufsize, STp->restr_dma)) {
1317                         printk(KERN_WARNING "%s: Can't allocate %d byte tape buffer.\n",
1318                                tape_name(STp), bufsize);
1319                         retval = (-EOVERFLOW);
1320                         goto out;
1321                 }
1322                 if (STp->block_size)
1323                         STbp->buffer_blocks = bufsize / STp->block_size;
1324         }
1325
1326  out:
1327         return retval;
1328 }
1329
1330
1331 /* Can be called more than once after each setup_buffer() */
1332 static void release_buffering(Scsi_Tape *STp)
1333 {
1334         ST_buffer *STbp;
1335
1336         STbp = STp->buffer;
1337         if (STbp->do_dio) {
1338                 sgl_unmap_user_pages(&(STbp->sg[0]), STbp->do_dio, FALSE);
1339                 STbp->do_dio = 0;
1340         }
1341 }
1342
1343
1344 /* Write command */
1345 static ssize_t
1346 st_write(struct file *filp, const char __user *buf, size_t count, loff_t * ppos)
1347 {
1348         ssize_t total;
1349         ssize_t i, do_count, blks, transfer;
1350         ssize_t retval;
1351         int undone, retry_eot = 0, scode;
1352         int async_write;
1353         unsigned char cmd[MAX_COMMAND_SIZE];
1354         const char __user *b_point;
1355         Scsi_Request *SRpnt = NULL;
1356         Scsi_Tape *STp = filp->private_data;
1357         ST_mode *STm;
1358         ST_partstat *STps;
1359         ST_buffer *STbp;
1360         char *name = tape_name(STp);
1361
1362         if (down_interruptible(&STp->lock))
1363                 return -ERESTARTSYS;
1364
1365         retval = rw_checks(STp, filp, count);
1366         if (retval || count == 0)
1367                 goto out;
1368
1369         /* Write must be integral number of blocks */
1370         if (STp->block_size != 0 && (count % STp->block_size) != 0) {
1371                 printk(KERN_WARNING "%s: Write not multiple of tape block size.\n",
1372                        name);
1373                 retval = (-EINVAL);
1374                 goto out;
1375         }
1376
1377         STm = &(STp->modes[STp->current_mode]);
1378         STps = &(STp->ps[STp->partition]);
1379
1380         if (STp->write_prot) {
1381                 retval = (-EACCES);
1382                 goto out;
1383         }
1384
1385
1386         if (STps->rw == ST_READING) {
1387                 retval = flush_buffer(STp, 0);
1388                 if (retval)
1389                         goto out;
1390                 STps->rw = ST_WRITING;
1391         } else if (STps->rw != ST_WRITING &&
1392                    STps->drv_file == 0 && STps->drv_block == 0) {
1393                 if ((retval = set_mode_densblk(STp, STm)) < 0)
1394                         goto out;
1395                 if (STm->default_compression != ST_DONT_TOUCH &&
1396                     !(STp->compression_changed)) {
1397                         if (st_compression(STp, (STm->default_compression == ST_YES))) {
1398                                 printk(KERN_WARNING "%s: Can't set default compression.\n",
1399                                        name);
1400                                 if (modes_defined) {
1401                                         retval = (-EINVAL);
1402                                         goto out;
1403                                 }
1404                         }
1405                 }
1406         }
1407
1408         STbp = STp->buffer;
1409         if (STbp->writing) {
1410                 write_behind_check(STp);
1411                 if (STbp->syscall_result) {
1412                         DEBC(printk(ST_DEB_MSG "%s: Async write error (write) %x.\n",
1413                                     name, STbp->midlevel_result));
1414                         if (STbp->midlevel_result == INT_MAX)
1415                                 STps->eof = ST_EOM_OK;
1416                         else
1417                                 STps->eof = ST_EOM_ERROR;
1418                 }
1419         }
1420
1421         if (STps->eof == ST_EOM_OK) {
1422                 STps->eof = ST_EOD_1;  /* allow next write */
1423                 retval = (-ENOSPC);
1424                 goto out;
1425         }
1426         else if (STps->eof == ST_EOM_ERROR) {
1427                 retval = (-EIO);
1428                 goto out;
1429         }
1430
1431         /* Check the buffer readability in cases where copy_user might catch
1432            the problems after some tape movement. */
1433         if (STp->block_size != 0 &&
1434             !STbp->do_dio &&
1435             (copy_from_user(&i, buf, 1) != 0 ||
1436              copy_from_user(&i, buf + count - 1, 1) != 0)) {
1437                 retval = (-EFAULT);
1438                 goto out;
1439         }
1440
1441         retval = setup_buffering(STp, buf, count, FALSE);
1442         if (retval)
1443                 goto out;
1444
1445         total = count;
1446
1447         memset(cmd, 0, MAX_COMMAND_SIZE);
1448         cmd[0] = WRITE_6;
1449         cmd[1] = (STp->block_size != 0);
1450
1451         STps->rw = ST_WRITING;
1452
1453         b_point = buf;
1454         while (count > 0 && !retry_eot) {
1455
1456                 if (STbp->do_dio) {
1457                         do_count = count;
1458                 }
1459                 else {
1460                         if (STp->block_size == 0)
1461                                 do_count = count;
1462                         else {
1463                                 do_count = STbp->buffer_blocks * STp->block_size -
1464                                         STbp->buffer_bytes;
1465                                 if (do_count > count)
1466                                         do_count = count;
1467                         }
1468
1469                         i = append_to_buffer(b_point, STbp, do_count);
1470                         if (i) {
1471                                 retval = i;
1472                                 goto out;
1473                         }
1474                 }
1475                 count -= do_count;
1476                 filp->f_pos += do_count;
1477                 b_point += do_count;
1478
1479                 async_write = STp->block_size == 0 && !STbp->do_dio &&
1480                         STm->do_async_writes && STps->eof < ST_EOM_OK;
1481
1482                 if (STp->block_size != 0 && STm->do_buffer_writes &&
1483                     !(STp->try_dio && try_wdio) && STps->eof < ST_EOM_OK &&
1484                     STbp->buffer_bytes < STbp->buffer_size) {
1485                         STp->dirty = TRUE;
1486                         /* Don't write a buffer that is not full enough. */
1487                         if (!async_write && count == 0)
1488                                 break;
1489                 }
1490
1491         retry_write:
1492                 if (STp->block_size == 0)
1493                         blks = transfer = do_count;
1494                 else {
1495                         if (!STbp->do_dio)
1496                                 blks = STbp->buffer_bytes;
1497                         else
1498                                 blks = do_count;
1499                         blks /= STp->block_size;
1500                         transfer = blks * STp->block_size;
1501                 }
1502                 cmd[2] = blks >> 16;
1503                 cmd[3] = blks >> 8;
1504                 cmd[4] = blks;
1505
1506                 SRpnt = st_do_scsi(SRpnt, STp, cmd, transfer, SCSI_DATA_WRITE,
1507                                    STp->device->timeout, MAX_WRITE_RETRIES, !async_write);
1508                 if (!SRpnt) {
1509                         retval = STbp->syscall_result;
1510                         goto out;
1511                 }
1512                 if (async_write) {
1513                         STbp->writing = transfer;
1514                         STp->dirty = !(STbp->writing ==
1515                                        STbp->buffer_bytes);
1516                         SRpnt = NULL;  /* Prevent releasing this request! */
1517                         DEB( STp->write_pending = 1; )
1518                         break;
1519                 }
1520
1521                 if (STbp->syscall_result != 0) {
1522                         DEBC(printk(ST_DEB_MSG "%s: Error on write:\n", name));
1523                         if ((SRpnt->sr_sense_buffer[0] & 0x70) == 0x70 &&
1524                             (SRpnt->sr_sense_buffer[2] & 0x40)) {
1525                                 scode = SRpnt->sr_sense_buffer[2] & 0x0f;
1526                                 if ((SRpnt->sr_sense_buffer[0] & 0x80) != 0)
1527                                         undone = (SRpnt->sr_sense_buffer[3] << 24) |
1528                                             (SRpnt->sr_sense_buffer[4] << 16) |
1529                                             (SRpnt->sr_sense_buffer[5] << 8) |
1530                                                 SRpnt->sr_sense_buffer[6];
1531                                 else if (STp->block_size == 0 &&
1532                                          scode == VOLUME_OVERFLOW)
1533                                         undone = transfer;
1534                                 else
1535                                         undone = 0;
1536                                 if (STp->block_size != 0)
1537                                         undone *= STp->block_size;
1538                                 filp->f_pos -= undone;
1539                                 if (undone <= do_count) {
1540                                         /* Only data from this write is not written */
1541                                         count += undone;
1542                                         do_count -= undone;
1543                                         if (STp->block_size)
1544                                                 blks = (transfer - undone) / STp->block_size;
1545                                         STps->eof = ST_EOM_OK;
1546                                         /* Continue in fixed block mode if all written
1547                                            in this request but still something left to write
1548                                            (retval left to zero)
1549                                         */
1550                                         if (STp->block_size == 0 ||
1551                                             undone > 0 || count == 0)
1552                                                 retval = (-ENOSPC); /* EOM within current request */
1553                                         DEBC(printk(ST_DEB_MSG
1554                                                        "%s: EOM with %d bytes unwritten.\n",
1555                                                        name, count));
1556                                 } else {
1557                                         /* EOT within data buffered earlier (possible only
1558                                            in fixed block mode without direct i/o) */
1559                                         if (!retry_eot && (SRpnt->sr_sense_buffer[0] & 1) == 0 &&
1560                                             (scode == NO_SENSE || scode == RECOVERED_ERROR)) {
1561                                                 move_buffer_data(STp->buffer, transfer - undone);
1562                                                 retry_eot = TRUE;
1563                                                 if (STps->drv_block >= 0) {
1564                                                         STps->drv_block += (transfer - undone) /
1565                                                                 STp->block_size;
1566                                                 }
1567                                                 STps->eof = ST_EOM_OK;
1568                                                 DEBC(printk(ST_DEB_MSG
1569                                                             "%s: Retry write of %d bytes at EOM.\n",
1570                                                             name, STp->buffer->buffer_bytes));
1571                                                 goto retry_write;
1572                                         }
1573                                         else {
1574                                                 /* Either error within data buffered by driver or
1575                                                    failed retry */
1576                                                 count -= do_count;
1577                                                 blks = do_count = 0;
1578                                                 STps->eof = ST_EOM_ERROR;
1579                                                 STps->drv_block = (-1); /* Too cautious? */
1580                                                 retval = (-EIO);        /* EOM for old data */
1581                                                 DEBC(printk(ST_DEB_MSG
1582                                                             "%s: EOM with lost data.\n",
1583                                                             name));
1584                                         }
1585                                 }
1586                         } else {
1587                                 filp->f_pos -= do_count;
1588                                 count += do_count;
1589                                 STps->drv_block = (-1);         /* Too cautious? */
1590                                 retval = (-EIO);
1591                         }
1592
1593                 }
1594
1595                 if (STps->drv_block >= 0) {
1596                         if (STp->block_size == 0)
1597                                 STps->drv_block += (do_count > 0);
1598                         else
1599                                 STps->drv_block += blks;
1600                 }
1601
1602                 STbp->buffer_bytes = 0;
1603                 STp->dirty = 0;
1604
1605                 if (retval || retry_eot) {
1606                         if (count < total)
1607                                 retval = total - count;
1608                         goto out;
1609                 }
1610         }
1611
1612         if (STps->eof == ST_EOD_1)
1613                 STps->eof = ST_EOM_OK;
1614         else if (STps->eof != ST_EOM_OK)
1615                 STps->eof = ST_NOEOF;
1616         retval = total - count;
1617
1618  out:
1619         if (SRpnt != NULL)
1620                 scsi_release_request(SRpnt);
1621         release_buffering(STp);
1622         up(&STp->lock);
1623
1624         return retval;
1625 }
1626 \f
1627 /* Read data from the tape. Returns zero in the normal case, one if the
1628    eof status has changed, and the negative error code in case of a
1629    fatal error. Otherwise updates the buffer and the eof state.
1630
1631    Does release user buffer mapping if it is set.
1632 */
1633 static long read_tape(Scsi_Tape *STp, long count, Scsi_Request ** aSRpnt)
1634 {
1635         int transfer, blks, bytes;
1636         unsigned char cmd[MAX_COMMAND_SIZE];
1637         Scsi_Request *SRpnt;
1638         ST_mode *STm;
1639         ST_partstat *STps;
1640         ST_buffer *STbp;
1641         int retval = 0;
1642         char *name = tape_name(STp);
1643
1644         if (count == 0)
1645                 return 0;
1646
1647         STm = &(STp->modes[STp->current_mode]);
1648         STps = &(STp->ps[STp->partition]);
1649         if (STps->eof == ST_FM_HIT)
1650                 return 1;
1651         STbp = STp->buffer;
1652
1653         if (STp->block_size == 0)
1654                 blks = bytes = count;
1655         else {
1656                 if (!(STp->try_dio && try_rdio) && STm->do_read_ahead) {
1657                         blks = (STp->buffer)->buffer_blocks;
1658                         bytes = blks * STp->block_size;
1659                 } else {
1660                         bytes = count;
1661                         if (!STbp->do_dio && bytes > (STp->buffer)->buffer_size)
1662                                 bytes = (STp->buffer)->buffer_size;
1663                         blks = bytes / STp->block_size;
1664                         bytes = blks * STp->block_size;
1665                 }
1666         }
1667
1668         memset(cmd, 0, MAX_COMMAND_SIZE);
1669         cmd[0] = READ_6;
1670         cmd[1] = (STp->block_size != 0);
1671         cmd[2] = blks >> 16;
1672         cmd[3] = blks >> 8;
1673         cmd[4] = blks;
1674
1675         SRpnt = *aSRpnt;
1676         SRpnt = st_do_scsi(SRpnt, STp, cmd, bytes, SCSI_DATA_READ,
1677                            STp->device->timeout, MAX_RETRIES, TRUE);
1678         release_buffering(STp);
1679         *aSRpnt = SRpnt;
1680         if (!SRpnt)
1681                 return STbp->syscall_result;
1682
1683         STbp->read_pointer = 0;
1684         STps->at_sm = 0;
1685
1686         /* Something to check */
1687         if (STbp->syscall_result) {
1688                 retval = 1;
1689                 DEBC(printk(ST_DEB_MSG "%s: Sense: %2x %2x %2x %2x %2x %2x %2x %2x\n",
1690                             name,
1691                             SRpnt->sr_sense_buffer[0], SRpnt->sr_sense_buffer[1],
1692                             SRpnt->sr_sense_buffer[2], SRpnt->sr_sense_buffer[3],
1693                             SRpnt->sr_sense_buffer[4], SRpnt->sr_sense_buffer[5],
1694                             SRpnt->sr_sense_buffer[6], SRpnt->sr_sense_buffer[7]));
1695                 if ((SRpnt->sr_sense_buffer[0] & 0x70) == 0x70) {       /* extended sense */
1696
1697                         if ((SRpnt->sr_sense_buffer[2] & 0x0f) == BLANK_CHECK)
1698                                 SRpnt->sr_sense_buffer[2] &= 0xcf;      /* No need for EOM in this case */
1699
1700                         if ((SRpnt->sr_sense_buffer[2] & 0xe0) != 0) { /* EOF, EOM, or ILI */
1701                                 /* Compute the residual count */
1702                                 if ((SRpnt->sr_sense_buffer[0] & 0x80) != 0)
1703                                         transfer = (SRpnt->sr_sense_buffer[3] << 24) |
1704                                             (SRpnt->sr_sense_buffer[4] << 16) |
1705                                             (SRpnt->sr_sense_buffer[5] << 8) |
1706                                             SRpnt->sr_sense_buffer[6];
1707                                 else
1708                                         transfer = 0;
1709                                 if (STp->block_size == 0 &&
1710                                     (SRpnt->sr_sense_buffer[2] & 0x0f) == MEDIUM_ERROR)
1711                                         transfer = bytes;
1712
1713                                 if (SRpnt->sr_sense_buffer[2] & 0x20) { /* ILI */
1714                                         if (STp->block_size == 0) {
1715                                                 if (transfer <= 0) {
1716                                                         if (transfer < 0)
1717                                                                 printk(KERN_NOTICE
1718                                                                        "%s: Failed to read %d byte block with %d byte transfer.\n",
1719                                                                        name, bytes - transfer, bytes);
1720                                                         if (STps->drv_block >= 0)
1721                                                                 STps->drv_block += 1;
1722                                                         STbp->buffer_bytes = 0;
1723                                                         return (-ENOMEM);
1724                                                 }
1725                                                 STbp->buffer_bytes = bytes - transfer;
1726                                         } else {
1727                                                 scsi_release_request(SRpnt);
1728                                                 SRpnt = *aSRpnt = NULL;
1729                                                 if (transfer == blks) { /* We did not get anything, error */
1730                                                         printk(KERN_NOTICE "%s: Incorrect block size.\n", name);
1731                                                         if (STps->drv_block >= 0)
1732                                                                 STps->drv_block += blks - transfer + 1;
1733                                                         st_int_ioctl(STp, MTBSR, 1);
1734                                                         return (-EIO);
1735                                                 }
1736                                                 /* We have some data, deliver it */
1737                                                 STbp->buffer_bytes = (blks - transfer) *
1738                                                     STp->block_size;
1739                                                 DEBC(printk(ST_DEB_MSG
1740                                                             "%s: ILI but enough data received %ld %d.\n",
1741                                                             name, count, STbp->buffer_bytes));
1742                                                 if (STps->drv_block >= 0)
1743                                                         STps->drv_block += 1;
1744                                                 if (st_int_ioctl(STp, MTBSR, 1))
1745                                                         return (-EIO);
1746                                         }
1747                                 } else if (SRpnt->sr_sense_buffer[2] & 0x80) {  /* FM overrides EOM */
1748                                         if (STps->eof != ST_FM_HIT)
1749                                                 STps->eof = ST_FM_HIT;
1750                                         else
1751                                                 STps->eof = ST_EOD_2;
1752                                         if (STp->block_size == 0)
1753                                                 STbp->buffer_bytes = 0;
1754                                         else
1755                                                 STbp->buffer_bytes =
1756                                                     bytes - transfer * STp->block_size;
1757                                         DEBC(printk(ST_DEB_MSG
1758                                                     "%s: EOF detected (%d bytes read).\n",
1759                                                     name, STbp->buffer_bytes));
1760                                 } else if (SRpnt->sr_sense_buffer[2] & 0x40) {
1761                                         if (STps->eof == ST_FM)
1762                                                 STps->eof = ST_EOD_1;
1763                                         else
1764                                                 STps->eof = ST_EOM_OK;
1765                                         if (STp->block_size == 0)
1766                                                 STbp->buffer_bytes = bytes - transfer;
1767                                         else
1768                                                 STbp->buffer_bytes =
1769                                                     bytes - transfer * STp->block_size;
1770
1771                                         DEBC(printk(ST_DEB_MSG "%s: EOM detected (%d bytes read).\n",
1772                                                     name, STbp->buffer_bytes));
1773                                 }
1774                         }
1775                         /* end of EOF, EOM, ILI test */ 
1776                         else {  /* nonzero sense key */
1777                                 DEBC(printk(ST_DEB_MSG
1778                                             "%s: Tape error while reading.\n", name));
1779                                 STps->drv_block = (-1);
1780                                 if (STps->eof == ST_FM &&
1781                                     (SRpnt->sr_sense_buffer[2] & 0x0f) == BLANK_CHECK) {
1782                                         DEBC(printk(ST_DEB_MSG
1783                                                     "%s: Zero returned for first BLANK CHECK after EOF.\n",
1784                                                     name));
1785                                         STps->eof = ST_EOD_2;   /* First BLANK_CHECK after FM */
1786                                 } else  /* Some other extended sense code */
1787                                         retval = (-EIO);
1788                         }
1789
1790                         if (STbp->buffer_bytes < 0)  /* Caused by bogus sense data */
1791                                 STbp->buffer_bytes = 0;
1792                 }
1793                 /* End of extended sense test */ 
1794                 else {          /* Non-extended sense */
1795                         retval = STbp->syscall_result;
1796                 }
1797
1798         }
1799         /* End of error handling */ 
1800         else                    /* Read successful */
1801                 STbp->buffer_bytes = bytes;
1802
1803         if (STps->drv_block >= 0) {
1804                 if (STp->block_size == 0)
1805                         STps->drv_block++;
1806                 else
1807                         STps->drv_block += STbp->buffer_bytes / STp->block_size;
1808         }
1809         return retval;
1810 }
1811 \f
1812
1813 /* Read command */
1814 static ssize_t
1815 st_read(struct file *filp, char __user *buf, size_t count, loff_t * ppos)
1816 {
1817         ssize_t total;
1818         ssize_t retval = 0;
1819         ssize_t i, transfer;
1820         int special, do_dio = 0;
1821         Scsi_Request *SRpnt = NULL;
1822         Scsi_Tape *STp = filp->private_data;
1823         ST_mode *STm;
1824         ST_partstat *STps;
1825         ST_buffer *STbp = STp->buffer;
1826         DEB( char *name = tape_name(STp); )
1827
1828         if (down_interruptible(&STp->lock))
1829                 return -ERESTARTSYS;
1830
1831         retval = rw_checks(STp, filp, count);
1832         if (retval || count == 0)
1833                 goto out;
1834
1835         STm = &(STp->modes[STp->current_mode]);
1836         if (!(STm->do_read_ahead) && STp->block_size != 0 &&
1837             (count % STp->block_size) != 0) {
1838                 retval = (-EINVAL);     /* Read must be integral number of blocks */
1839                 goto out;
1840         }
1841
1842         STps = &(STp->ps[STp->partition]);
1843         if (STps->rw == ST_WRITING) {
1844                 retval = flush_buffer(STp, 0);
1845                 if (retval)
1846                         goto out;
1847                 STps->rw = ST_READING;
1848         }
1849         DEB(
1850         if (debugging && STps->eof != ST_NOEOF)
1851                 printk(ST_DEB_MSG "%s: EOF/EOM flag up (%d). Bytes %d\n", name,
1852                        STps->eof, STbp->buffer_bytes);
1853         ) /* end DEB */
1854
1855         retval = setup_buffering(STp, buf, count, TRUE);
1856         if (retval)
1857                 goto out;
1858         do_dio = STbp->do_dio;
1859
1860         if (STbp->buffer_bytes == 0 &&
1861             STps->eof >= ST_EOD_1) {
1862                 if (STps->eof < ST_EOD) {
1863                         STps->eof += 1;
1864                         retval = 0;
1865                         goto out;
1866                 }
1867                 retval = (-EIO);        /* EOM or Blank Check */
1868                 goto out;
1869         }
1870
1871         if (do_dio) {
1872                 /* Check the buffer writability before any tape movement. Don't alter
1873                    buffer data. */
1874                 if (copy_from_user(&i, buf, 1) != 0 ||
1875                     copy_to_user(buf, &i, 1) != 0 ||
1876                     copy_from_user(&i, buf + count - 1, 1) != 0 ||
1877                     copy_to_user(buf + count - 1, &i, 1) != 0) {
1878                         retval = (-EFAULT);
1879                         goto out;
1880                 }
1881         }
1882
1883         STps->rw = ST_READING;
1884
1885
1886         /* Loop until enough data in buffer or a special condition found */
1887         for (total = 0, special = 0; total < count && !special;) {
1888
1889                 /* Get new data if the buffer is empty */
1890                 if (STbp->buffer_bytes == 0) {
1891                         special = read_tape(STp, count - total, &SRpnt);
1892                         if (special < 0) {      /* No need to continue read */
1893                                 retval = special;
1894                                 goto out;
1895                         }
1896                 }
1897
1898                 /* Move the data from driver buffer to user buffer */
1899                 if (STbp->buffer_bytes > 0) {
1900                         DEB(
1901                         if (debugging && STps->eof != ST_NOEOF)
1902                                 printk(ST_DEB_MSG
1903                                        "%s: EOF up (%d). Left %d, needed %d.\n", name,
1904                                        STps->eof, STbp->buffer_bytes,
1905                                        count - total);
1906                         ) /* end DEB */
1907                         transfer = STbp->buffer_bytes < count - total ?
1908                             STbp->buffer_bytes : count - total;
1909                         if (!do_dio) {
1910                                 i = from_buffer(STbp, buf, transfer);
1911                                 if (i) {
1912                                         retval = i;
1913                                         goto out;
1914                                 }
1915                         }
1916                         filp->f_pos += transfer;
1917                         buf += transfer;
1918                         total += transfer;
1919                 }
1920
1921                 if (STp->block_size == 0)
1922                         break;  /* Read only one variable length block */
1923
1924         }                       /* for (total = 0, special = 0;
1925                                    total < count && !special; ) */
1926
1927         /* Change the eof state if no data from tape or buffer */
1928         if (total == 0) {
1929                 if (STps->eof == ST_FM_HIT) {
1930                         STps->eof = ST_FM;
1931                         STps->drv_block = 0;
1932                         if (STps->drv_file >= 0)
1933                                 STps->drv_file++;
1934                 } else if (STps->eof == ST_EOD_1) {
1935                         STps->eof = ST_EOD_2;
1936                         STps->drv_block = 0;
1937                         if (STps->drv_file >= 0)
1938                                 STps->drv_file++;
1939                 } else if (STps->eof == ST_EOD_2)
1940                         STps->eof = ST_EOD;
1941         } else if (STps->eof == ST_FM)
1942                 STps->eof = ST_NOEOF;
1943         retval = total;
1944
1945  out:
1946         if (SRpnt != NULL) {
1947                 scsi_release_request(SRpnt);
1948                 SRpnt = NULL;
1949         }
1950         if (do_dio) {
1951                 release_buffering(STp);
1952                 STbp->buffer_bytes = 0;
1953         }
1954         up(&STp->lock);
1955
1956         return retval;
1957 }
1958 \f
1959
1960
1961 DEB(
1962 /* Set the driver options */
1963 static void st_log_options(Scsi_Tape * STp, ST_mode * STm, char *name)
1964 {
1965         if (debugging) {
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                 printk(KERN_INFO "%s:    debugging: %d\n",
1980                        name, debugging);
1981         }
1982 }
1983         )
1984
1985
1986 static int st_set_options(Scsi_Tape *STp, long options)
1987 {
1988         int value;
1989         long code;
1990         ST_mode *STm;
1991         char *name = tape_name(STp);
1992         struct cdev *cd0, *cd1;
1993
1994         STm = &(STp->modes[STp->current_mode]);
1995         if (!STm->defined) {
1996                 cd0 = STm->cdevs[0]; cd1 = STm->cdevs[1];
1997                 memcpy(STm, &(STp->modes[0]), sizeof(ST_mode));
1998                 STm->cdevs[0] = cd0; STm->cdevs[1] = cd1;
1999                 modes_defined = TRUE;
2000                 DEBC(printk(ST_DEB_MSG
2001                             "%s: Initialized mode %d definition from mode 0\n",
2002                             name, STp->current_mode));
2003         }
2004
2005         code = options & MT_ST_OPTIONS;
2006         if (code == MT_ST_BOOLEANS) {
2007                 STm->do_buffer_writes = (options & MT_ST_BUFFER_WRITES) != 0;
2008                 STm->do_async_writes = (options & MT_ST_ASYNC_WRITES) != 0;
2009                 STm->defaults_for_writes = (options & MT_ST_DEF_WRITES) != 0;
2010                 STm->do_read_ahead = (options & MT_ST_READ_AHEAD) != 0;
2011                 STp->two_fm = (options & MT_ST_TWO_FM) != 0;
2012                 STp->fast_mteom = (options & MT_ST_FAST_MTEOM) != 0;
2013                 STp->do_auto_lock = (options & MT_ST_AUTO_LOCK) != 0;
2014                 STp->can_bsr = (options & MT_ST_CAN_BSR) != 0;
2015                 STp->omit_blklims = (options & MT_ST_NO_BLKLIMS) != 0;
2016                 if ((STp->device)->scsi_level >= SCSI_2)
2017                         STp->can_partitions = (options & MT_ST_CAN_PARTITIONS) != 0;
2018                 STp->scsi2_logical = (options & MT_ST_SCSI2LOGICAL) != 0;
2019                 STp->immediate = (options & MT_ST_NOWAIT) != 0;
2020                 STm->sysv = (options & MT_ST_SYSV) != 0;
2021                 DEB( debugging = (options & MT_ST_DEBUGGING) != 0;
2022                      st_log_options(STp, STm, name); )
2023         } else if (code == MT_ST_SETBOOLEANS || code == MT_ST_CLEARBOOLEANS) {
2024                 value = (code == MT_ST_SETBOOLEANS);
2025                 if ((options & MT_ST_BUFFER_WRITES) != 0)
2026                         STm->do_buffer_writes = value;
2027                 if ((options & MT_ST_ASYNC_WRITES) != 0)
2028                         STm->do_async_writes = value;
2029                 if ((options & MT_ST_DEF_WRITES) != 0)
2030                         STm->defaults_for_writes = value;
2031                 if ((options & MT_ST_READ_AHEAD) != 0)
2032                         STm->do_read_ahead = value;
2033                 if ((options & MT_ST_TWO_FM) != 0)
2034                         STp->two_fm = value;
2035                 if ((options & MT_ST_FAST_MTEOM) != 0)
2036                         STp->fast_mteom = value;
2037                 if ((options & MT_ST_AUTO_LOCK) != 0)
2038                         STp->do_auto_lock = value;
2039                 if ((options & MT_ST_CAN_BSR) != 0)
2040                         STp->can_bsr = value;
2041                 if ((options & MT_ST_NO_BLKLIMS) != 0)
2042                         STp->omit_blklims = value;
2043                 if ((STp->device)->scsi_level >= SCSI_2 &&
2044                     (options & MT_ST_CAN_PARTITIONS) != 0)
2045                         STp->can_partitions = value;
2046                 if ((options & MT_ST_SCSI2LOGICAL) != 0)
2047                         STp->scsi2_logical = value;
2048                 if ((options & MT_ST_NOWAIT) != 0)
2049                         STp->immediate = value;
2050                 if ((options & MT_ST_SYSV) != 0)
2051                         STm->sysv = value;
2052                 DEB(
2053                 if ((options & MT_ST_DEBUGGING) != 0)
2054                         debugging = value;
2055                         st_log_options(STp, STm, name); )
2056         } else if (code == MT_ST_WRITE_THRESHOLD) {
2057                 /* Retained for compatibility */
2058         } else if (code == MT_ST_DEF_BLKSIZE) {
2059                 value = (options & ~MT_ST_OPTIONS);
2060                 if (value == ~MT_ST_OPTIONS) {
2061                         STm->default_blksize = (-1);
2062                         DEBC( printk(KERN_INFO "%s: Default block size disabled.\n", name));
2063                 } else {
2064                         STm->default_blksize = value;
2065                         DEBC( printk(KERN_INFO "%s: Default block size set to %d bytes.\n",
2066                                name, STm->default_blksize));
2067                         if (STp->ready == ST_READY) {
2068                                 STp->blksize_changed = FALSE;
2069                                 set_mode_densblk(STp, STm);
2070                         }
2071                 }
2072         } else if (code == MT_ST_TIMEOUTS) {
2073                 value = (options & ~MT_ST_OPTIONS);
2074                 if ((value & MT_ST_SET_LONG_TIMEOUT) != 0) {
2075                         STp->long_timeout = (value & ~MT_ST_SET_LONG_TIMEOUT) * HZ;
2076                         DEBC( printk(KERN_INFO "%s: Long timeout set to %d seconds.\n", name,
2077                                (value & ~MT_ST_SET_LONG_TIMEOUT)));
2078                 } else {
2079                         STp->device->timeout = value * HZ;
2080                         DEBC( printk(KERN_INFO "%s: Normal timeout set to %d seconds.\n",
2081                                 name, value) );
2082                 }
2083         } else if (code == MT_ST_SET_CLN) {
2084                 value = (options & ~MT_ST_OPTIONS) & 0xff;
2085                 if (value != 0 &&
2086                     value < EXTENDED_SENSE_START && value >= SCSI_SENSE_BUFFERSIZE)
2087                         return (-EINVAL);
2088                 STp->cln_mode = value;
2089                 STp->cln_sense_mask = (options >> 8) & 0xff;
2090                 STp->cln_sense_value = (options >> 16) & 0xff;
2091                 printk(KERN_INFO
2092                        "%s: Cleaning request mode %d, mask %02x, value %02x\n",
2093                        name, value, STp->cln_sense_mask, STp->cln_sense_value);
2094         } else if (code == MT_ST_DEF_OPTIONS) {
2095                 code = (options & ~MT_ST_CLEAR_DEFAULT);
2096                 value = (options & MT_ST_CLEAR_DEFAULT);
2097                 if (code == MT_ST_DEF_DENSITY) {
2098                         if (value == MT_ST_CLEAR_DEFAULT) {
2099                                 STm->default_density = (-1);
2100                                 DEBC( printk(KERN_INFO "%s: Density default disabled.\n",
2101                                        name));
2102                         } else {
2103                                 STm->default_density = value & 0xff;
2104                                 DEBC( printk(KERN_INFO "%s: Density default set to %x\n",
2105                                        name, STm->default_density));
2106                                 if (STp->ready == ST_READY) {
2107                                         STp->density_changed = FALSE;
2108                                         set_mode_densblk(STp, STm);
2109                                 }
2110                         }
2111                 } else if (code == MT_ST_DEF_DRVBUFFER) {
2112                         if (value == MT_ST_CLEAR_DEFAULT) {
2113                                 STp->default_drvbuffer = 0xff;
2114                                 DEBC( printk(KERN_INFO
2115                                        "%s: Drive buffer default disabled.\n", name));
2116                         } else {
2117                                 STp->default_drvbuffer = value & 7;
2118                                 DEBC( printk(KERN_INFO
2119                                        "%s: Drive buffer default set to %x\n",
2120                                        name, STp->default_drvbuffer));
2121                                 if (STp->ready == ST_READY)
2122                                         st_int_ioctl(STp, MTSETDRVBUFFER, STp->default_drvbuffer);
2123                         }
2124                 } else if (code == MT_ST_DEF_COMPRESSION) {
2125                         if (value == MT_ST_CLEAR_DEFAULT) {
2126                                 STm->default_compression = ST_DONT_TOUCH;
2127                                 DEBC( printk(KERN_INFO
2128                                        "%s: Compression default disabled.\n", name));
2129                         } else {
2130                                 if ((value & 0xff00) != 0) {
2131                                         STp->c_algo = (value & 0xff00) >> 8;
2132                                         DEBC( printk(KERN_INFO "%s: Compression algorithm set to 0x%x.\n",
2133                                                name, STp->c_algo));
2134                                 }
2135                                 if ((value & 0xff) != 0xff) {
2136                                         STm->default_compression = (value & 1 ? ST_YES : ST_NO);
2137                                         DEBC( printk(KERN_INFO "%s: Compression default set to %x\n",
2138                                                name, (value & 1)));
2139                                         if (STp->ready == ST_READY) {
2140                                                 STp->compression_changed = FALSE;
2141                                                 st_compression(STp, (STm->default_compression == ST_YES));
2142                                         }
2143                                 }
2144                         }
2145                 }
2146         } else
2147                 return (-EIO);
2148
2149         return 0;
2150 }
2151 \f
2152 #define MODE_HEADER_LENGTH  4
2153
2154 /* Mode header and page byte offsets */
2155 #define MH_OFF_DATA_LENGTH     0
2156 #define MH_OFF_MEDIUM_TYPE     1
2157 #define MH_OFF_DEV_SPECIFIC    2
2158 #define MH_OFF_BDESCS_LENGTH   3
2159 #define MP_OFF_PAGE_NBR        0
2160 #define MP_OFF_PAGE_LENGTH     1
2161
2162 /* Mode header and page bit masks */
2163 #define MH_BIT_WP              0x80
2164 #define MP_MSK_PAGE_NBR        0x3f
2165
2166 /* Don't return block descriptors */
2167 #define MODE_SENSE_OMIT_BDESCS 0x08
2168
2169 #define MODE_SELECT_PAGE_FORMAT 0x10
2170
2171 /* Read a mode page into the tape buffer. The block descriptors are included
2172    if incl_block_descs is true. The page control is ored to the page number
2173    parameter, if necessary. */
2174 static int read_mode_page(Scsi_Tape *STp, int page, int omit_block_descs)
2175 {
2176         unsigned char cmd[MAX_COMMAND_SIZE];
2177         Scsi_Request *SRpnt = NULL;
2178
2179         memset(cmd, 0, MAX_COMMAND_SIZE);
2180         cmd[0] = MODE_SENSE;
2181         if (omit_block_descs)
2182                 cmd[1] = MODE_SENSE_OMIT_BDESCS;
2183         cmd[2] = page;
2184         cmd[4] = 255;
2185
2186         SRpnt = st_do_scsi(SRpnt, STp, cmd, cmd[4], SCSI_DATA_READ,
2187                            STp->device->timeout, 0, TRUE);
2188         if (SRpnt == NULL)
2189                 return (STp->buffer)->syscall_result;
2190
2191         scsi_release_request(SRpnt);
2192
2193         return (STp->buffer)->syscall_result;
2194 }
2195
2196
2197 /* Send the mode page in the tape buffer to the drive. Assumes that the mode data
2198    in the buffer is correctly formatted. The long timeout is used if slow is non-zero. */
2199 static int write_mode_page(Scsi_Tape *STp, int page, int slow)
2200 {
2201         int pgo;
2202         unsigned char cmd[MAX_COMMAND_SIZE];
2203         Scsi_Request *SRpnt = NULL;
2204
2205         memset(cmd, 0, MAX_COMMAND_SIZE);
2206         cmd[0] = MODE_SELECT;
2207         cmd[1] = MODE_SELECT_PAGE_FORMAT;
2208         pgo = MODE_HEADER_LENGTH + (STp->buffer)->b_data[MH_OFF_BDESCS_LENGTH];
2209         cmd[4] = pgo + (STp->buffer)->b_data[pgo + MP_OFF_PAGE_LENGTH] + 2;
2210
2211         /* Clear reserved fields */
2212         (STp->buffer)->b_data[MH_OFF_DATA_LENGTH] = 0;
2213         (STp->buffer)->b_data[MH_OFF_MEDIUM_TYPE] = 0;
2214         (STp->buffer)->b_data[MH_OFF_DEV_SPECIFIC] &= ~MH_BIT_WP;
2215         (STp->buffer)->b_data[pgo + MP_OFF_PAGE_NBR] &= MP_MSK_PAGE_NBR;
2216
2217         SRpnt = st_do_scsi(SRpnt, STp, cmd, cmd[4], SCSI_DATA_WRITE,
2218                            (slow ? STp->long_timeout : STp->device->timeout), 0, TRUE);
2219         if (SRpnt == NULL)
2220                 return (STp->buffer)->syscall_result;
2221
2222         scsi_release_request(SRpnt);
2223
2224         return (STp->buffer)->syscall_result;
2225 }
2226
2227
2228 #define COMPRESSION_PAGE        0x0f
2229 #define COMPRESSION_PAGE_LENGTH 16
2230
2231 #define CP_OFF_DCE_DCC          2
2232 #define CP_OFF_C_ALGO           7
2233
2234 #define DCE_MASK  0x80
2235 #define DCC_MASK  0x40
2236 #define RED_MASK  0x60
2237
2238
2239 /* Control the compression with mode page 15. Algorithm not changed if zero.
2240
2241    The block descriptors are read and written because Sony SDT-7000 does not
2242    work without this (suggestion from Michael Schaefer <Michael.Schaefer@dlr.de>).
2243    Including block descriptors should not cause any harm to other drives. */
2244
2245 static int st_compression(Scsi_Tape * STp, int state)
2246 {
2247         int retval;
2248         int mpoffs;  /* Offset to mode page start */
2249         unsigned char *b_data = (STp->buffer)->b_data;
2250         DEB( char *name = tape_name(STp); )
2251
2252         if (STp->ready != ST_READY)
2253                 return (-EIO);
2254
2255         /* Read the current page contents */
2256         retval = read_mode_page(STp, COMPRESSION_PAGE, FALSE);
2257         if (retval) {
2258                 DEBC(printk(ST_DEB_MSG "%s: Compression mode page not supported.\n",
2259                             name));
2260                 return (-EIO);
2261         }
2262
2263         mpoffs = MODE_HEADER_LENGTH + b_data[MH_OFF_BDESCS_LENGTH];
2264         DEBC(printk(ST_DEB_MSG "%s: Compression state is %d.\n", name,
2265                     (b_data[mpoffs + CP_OFF_DCE_DCC] & DCE_MASK ? 1 : 0)));
2266
2267         /* Check if compression can be changed */
2268         if ((b_data[mpoffs + CP_OFF_DCE_DCC] & DCC_MASK) == 0) {
2269                 DEBC(printk(ST_DEB_MSG "%s: Compression not supported.\n", name));
2270                 return (-EIO);
2271         }
2272
2273         /* Do the change */
2274         if (state) {
2275                 b_data[mpoffs + CP_OFF_DCE_DCC] |= DCE_MASK;
2276                 if (STp->c_algo != 0)
2277                         b_data[mpoffs + CP_OFF_C_ALGO] = STp->c_algo;
2278         }
2279         else {
2280                 b_data[mpoffs + CP_OFF_DCE_DCC] &= ~DCE_MASK;
2281                 if (STp->c_algo != 0)
2282                         b_data[mpoffs + CP_OFF_C_ALGO] = 0; /* no compression */
2283         }
2284
2285         retval = write_mode_page(STp, COMPRESSION_PAGE, FALSE);
2286         if (retval) {
2287                 DEBC(printk(ST_DEB_MSG "%s: Compression change failed.\n", name));
2288                 return (-EIO);
2289         }
2290         DEBC(printk(ST_DEB_MSG "%s: Compression state changed to %d.\n",
2291                        name, state));
2292
2293         STp->compression_changed = TRUE;
2294         return 0;
2295 }
2296
2297
2298 /* Process the load and unload commands (does unload if the load code is zero) */
2299 static int do_load_unload(Scsi_Tape *STp, struct file *filp, int load_code)
2300 {
2301         int retval = (-EIO), timeout;
2302         DEB( char *name = tape_name(STp); )
2303         unsigned char cmd[MAX_COMMAND_SIZE];
2304         ST_partstat *STps;
2305         Scsi_Request *SRpnt;
2306
2307         if (STp->ready != ST_READY && !load_code) {
2308                 if (STp->ready == ST_NO_TAPE)
2309                         return (-ENOMEDIUM);
2310                 else
2311                         return (-EIO);
2312         }
2313
2314         memset(cmd, 0, MAX_COMMAND_SIZE);
2315         cmd[0] = START_STOP;
2316         if (load_code)
2317                 cmd[4] |= 1;
2318         /*
2319          * If arg >= 1 && arg <= 6 Enhanced load/unload in HP C1553A
2320          */
2321         if (load_code >= 1 + MT_ST_HPLOADER_OFFSET
2322             && load_code <= 6 + MT_ST_HPLOADER_OFFSET) {
2323                 DEBC(printk(ST_DEB_MSG "%s: Enhanced %sload slot %2d.\n",
2324                             name, (cmd[4]) ? "" : "un",
2325                             load_code - MT_ST_HPLOADER_OFFSET));
2326                 cmd[3] = load_code - MT_ST_HPLOADER_OFFSET; /* MediaID field of C1553A */
2327         }
2328         if (STp->immediate) {
2329                 cmd[1] = 1;     /* Don't wait for completion */
2330                 timeout = STp->device->timeout;
2331         }
2332         else
2333                 timeout = STp->long_timeout;
2334
2335         DEBC(
2336                 if (!load_code)
2337                 printk(ST_DEB_MSG "%s: Unloading tape.\n", name);
2338                 else
2339                 printk(ST_DEB_MSG "%s: Loading tape.\n", name);
2340                 );
2341
2342         SRpnt = st_do_scsi(NULL, STp, cmd, 0, SCSI_DATA_NONE,
2343                            timeout, MAX_RETRIES, TRUE);
2344         if (!SRpnt)
2345                 return (STp->buffer)->syscall_result;
2346
2347         retval = (STp->buffer)->syscall_result;
2348         scsi_release_request(SRpnt);
2349
2350         if (!retval) {  /* SCSI command successful */
2351
2352                 if (!load_code) {
2353                         STp->rew_at_close = 0;
2354                         STp->ready = ST_NO_TAPE;
2355                 }
2356                 else {
2357                         STp->rew_at_close = STp->autorew_dev;
2358                         retval = check_tape(STp, filp);
2359                         if (retval > 0)
2360                                 retval = 0;
2361                 }
2362         }
2363         else {
2364                 STps = &(STp->ps[STp->partition]);
2365                 STps->drv_file = STps->drv_block = (-1);
2366         }
2367
2368         return retval;
2369 }
2370 \f
2371
2372 /* Internal ioctl function */
2373 static int st_int_ioctl(Scsi_Tape *STp, unsigned int cmd_in, unsigned long arg)
2374 {
2375         int timeout;
2376         long ltmp;
2377         int ioctl_result;
2378         int chg_eof = TRUE;
2379         unsigned char cmd[MAX_COMMAND_SIZE];
2380         Scsi_Request *SRpnt;
2381         ST_partstat *STps;
2382         int fileno, blkno, at_sm, undone;
2383         int datalen = 0, direction = SCSI_DATA_NONE;
2384         char *name = tape_name(STp);
2385
2386         WARN_ON(STp->buffer->do_dio != 0);
2387         if (STp->ready != ST_READY) {
2388                 if (STp->ready == ST_NO_TAPE)
2389                         return (-ENOMEDIUM);
2390                 else
2391                         return (-EIO);
2392         }
2393         timeout = STp->long_timeout;
2394         STps = &(STp->ps[STp->partition]);
2395         fileno = STps->drv_file;
2396         blkno = STps->drv_block;
2397         at_sm = STps->at_sm;
2398
2399         memset(cmd, 0, MAX_COMMAND_SIZE);
2400         switch (cmd_in) {
2401         case MTFSFM:
2402                 chg_eof = FALSE;        /* Changed from the FSF after this */
2403         case MTFSF:
2404                 cmd[0] = SPACE;
2405                 cmd[1] = 0x01;  /* Space FileMarks */
2406                 cmd[2] = (arg >> 16);
2407                 cmd[3] = (arg >> 8);
2408                 cmd[4] = arg;
2409                 DEBC(printk(ST_DEB_MSG "%s: Spacing tape forward over %d filemarks.\n",
2410                             name, cmd[2] * 65536 + cmd[3] * 256 + cmd[4]));
2411                 if (fileno >= 0)
2412                         fileno += arg;
2413                 blkno = 0;
2414                 at_sm &= (arg == 0);
2415                 break;
2416         case MTBSFM:
2417                 chg_eof = FALSE;        /* Changed from the FSF after this */
2418         case MTBSF:
2419                 cmd[0] = SPACE;
2420                 cmd[1] = 0x01;  /* Space FileMarks */
2421                 ltmp = (-arg);
2422                 cmd[2] = (ltmp >> 16);
2423                 cmd[3] = (ltmp >> 8);
2424                 cmd[4] = ltmp;
2425                 DEBC(
2426                      if (cmd[2] & 0x80)
2427                         ltmp = 0xff000000;
2428                      ltmp = ltmp | (cmd[2] << 16) | (cmd[3] << 8) | cmd[4];
2429                      printk(ST_DEB_MSG
2430                             "%s: Spacing tape backward over %ld filemarks.\n",
2431                             name, (-ltmp));
2432                 )
2433                 if (fileno >= 0)
2434                         fileno -= arg;
2435                 blkno = (-1);   /* We can't know the block number */
2436                 at_sm &= (arg == 0);
2437                 break;
2438         case MTFSR:
2439                 cmd[0] = SPACE;
2440                 cmd[1] = 0x00;  /* Space Blocks */
2441                 cmd[2] = (arg >> 16);
2442                 cmd[3] = (arg >> 8);
2443                 cmd[4] = arg;
2444                 DEBC(printk(ST_DEB_MSG "%s: Spacing tape forward %d blocks.\n", name,
2445                                cmd[2] * 65536 + cmd[3] * 256 + cmd[4]));
2446                 if (blkno >= 0)
2447                         blkno += arg;
2448                 at_sm &= (arg == 0);
2449                 break;
2450         case MTBSR:
2451                 cmd[0] = SPACE;
2452                 cmd[1] = 0x00;  /* Space Blocks */
2453                 ltmp = (-arg);
2454                 cmd[2] = (ltmp >> 16);
2455                 cmd[3] = (ltmp >> 8);
2456                 cmd[4] = ltmp;
2457                 DEBC(
2458                      if (cmd[2] & 0x80)
2459                           ltmp = 0xff000000;
2460                      ltmp = ltmp | (cmd[2] << 16) | (cmd[3] << 8) | cmd[4];
2461                      printk(ST_DEB_MSG
2462                             "%s: Spacing tape backward %ld blocks.\n", name, (-ltmp));
2463                 )
2464                 if (blkno >= 0)
2465                         blkno -= arg;
2466                 at_sm &= (arg == 0);
2467                 break;
2468         case MTFSS:
2469                 cmd[0] = SPACE;
2470                 cmd[1] = 0x04;  /* Space Setmarks */
2471                 cmd[2] = (arg >> 16);
2472                 cmd[3] = (arg >> 8);
2473                 cmd[4] = arg;
2474                 DEBC(printk(ST_DEB_MSG "%s: Spacing tape forward %d setmarks.\n", name,
2475                             cmd[2] * 65536 + cmd[3] * 256 + cmd[4]));
2476                 if (arg != 0) {
2477                         blkno = fileno = (-1);
2478                         at_sm = 1;
2479                 }
2480                 break;
2481         case MTBSS:
2482                 cmd[0] = SPACE;
2483                 cmd[1] = 0x04;  /* Space Setmarks */
2484                 ltmp = (-arg);
2485                 cmd[2] = (ltmp >> 16);
2486                 cmd[3] = (ltmp >> 8);
2487                 cmd[4] = ltmp;
2488                 DEBC(
2489                      if (cmd[2] & 0x80)
2490                                 ltmp = 0xff000000;
2491                      ltmp = ltmp | (cmd[2] << 16) | (cmd[3] << 8) | cmd[4];
2492                      printk(ST_DEB_MSG "%s: Spacing tape backward %ld setmarks.\n",
2493                             name, (-ltmp));
2494                 )
2495                 if (arg != 0) {
2496                         blkno = fileno = (-1);
2497                         at_sm = 1;
2498                 }
2499                 break;
2500         case MTWEOF:
2501         case MTWSM:
2502                 if (STp->write_prot)
2503                         return (-EACCES);
2504                 cmd[0] = WRITE_FILEMARKS;
2505                 if (cmd_in == MTWSM)
2506                         cmd[1] = 2;
2507                 cmd[2] = (arg >> 16);
2508                 cmd[3] = (arg >> 8);
2509                 cmd[4] = arg;
2510                 timeout = STp->device->timeout;
2511                 DEBC(
2512                      if (cmd_in == MTWEOF)
2513                                printk(ST_DEB_MSG "%s: Writing %d filemarks.\n", name,
2514                                  cmd[2] * 65536 + cmd[3] * 256 + cmd[4]);
2515                      else
2516                                 printk(ST_DEB_MSG "%s: Writing %d setmarks.\n", name,
2517                                  cmd[2] * 65536 + cmd[3] * 256 + cmd[4]);
2518                 )
2519                 if (fileno >= 0)
2520                         fileno += arg;
2521                 blkno = 0;
2522                 at_sm = (cmd_in == MTWSM);
2523                 break;
2524         case MTREW:
2525                 cmd[0] = REZERO_UNIT;
2526                 if (STp->immediate) {
2527                         cmd[1] = 1;     /* Don't wait for completion */
2528                         timeout = STp->device->timeout;
2529                 }
2530                 DEBC(printk(ST_DEB_MSG "%s: Rewinding tape.\n", name));
2531                 fileno = blkno = at_sm = 0;
2532                 break;
2533         case MTNOP:
2534                 DEBC(printk(ST_DEB_MSG "%s: No op on tape.\n", name));
2535                 return 0;       /* Should do something ? */
2536                 break;
2537         case MTRETEN:
2538                 cmd[0] = START_STOP;
2539                 if (STp->immediate) {
2540                         cmd[1] = 1;     /* Don't wait for completion */
2541                         timeout = STp->device->timeout;
2542                 }
2543                 cmd[4] = 3;
2544                 DEBC(printk(ST_DEB_MSG "%s: Retensioning tape.\n", name));
2545                 fileno = blkno = at_sm = 0;
2546                 break;
2547         case MTEOM:
2548                 if (!STp->fast_mteom) {
2549                         /* space to the end of tape */
2550                         ioctl_result = st_int_ioctl(STp, MTFSF, 0x7fffff);
2551                         fileno = STps->drv_file;
2552                         if (STps->eof >= ST_EOD_1)
2553                                 return 0;
2554                         /* The next lines would hide the number of spaced FileMarks
2555                            That's why I inserted the previous lines. I had no luck
2556                            with detecting EOM with FSF, so we go now to EOM.
2557                            Joerg Weule */
2558                 } else
2559                         fileno = (-1);
2560                 cmd[0] = SPACE;
2561                 cmd[1] = 3;
2562                 DEBC(printk(ST_DEB_MSG "%s: Spacing to end of recorded medium.\n",
2563                             name));
2564                 blkno = 0;
2565                 at_sm = 0;
2566                 break;
2567         case MTERASE:
2568                 if (STp->write_prot)
2569                         return (-EACCES);
2570                 cmd[0] = ERASE;
2571                 cmd[1] = (arg ? 1 : 0); /* Long erase with non-zero argument */
2572                 if (STp->immediate) {
2573                         cmd[1] |= 2;    /* Don't wait for completion */
2574                         timeout = STp->device->timeout;
2575                 }
2576                 else
2577                         timeout = STp->long_timeout * 8;
2578
2579                 DEBC(printk(ST_DEB_MSG "%s: Erasing tape.\n", name));
2580                 fileno = blkno = at_sm = 0;
2581                 break;
2582         case MTSETBLK:          /* Set block length */
2583         case MTSETDENSITY:      /* Set tape density */
2584         case MTSETDRVBUFFER:    /* Set drive buffering */
2585         case SET_DENS_AND_BLK:  /* Set density and block size */
2586                 chg_eof = FALSE;
2587                 if (STp->dirty || (STp->buffer)->buffer_bytes != 0)
2588                         return (-EIO);  /* Not allowed if data in buffer */
2589                 if ((cmd_in == MTSETBLK || cmd_in == SET_DENS_AND_BLK) &&
2590                     (arg & MT_ST_BLKSIZE_MASK) != 0 &&
2591                     STp->max_block > 0 &&
2592                     ((arg & MT_ST_BLKSIZE_MASK) < STp->min_block ||
2593                      (arg & MT_ST_BLKSIZE_MASK) > STp->max_block)) {
2594                         printk(KERN_WARNING "%s: Illegal block size.\n", name);
2595                         return (-EINVAL);
2596                 }
2597                 cmd[0] = MODE_SELECT;
2598                 if ((STp->use_pf & USE_PF))
2599                         cmd[1] = MODE_SELECT_PAGE_FORMAT;
2600                 cmd[4] = datalen = 12;
2601                 direction = SCSI_DATA_WRITE;
2602
2603                 memset((STp->buffer)->b_data, 0, 12);
2604                 if (cmd_in == MTSETDRVBUFFER)
2605                         (STp->buffer)->b_data[2] = (arg & 7) << 4;
2606                 else
2607                         (STp->buffer)->b_data[2] =
2608                             STp->drv_buffer << 4;
2609                 (STp->buffer)->b_data[3] = 8;   /* block descriptor length */
2610                 if (cmd_in == MTSETDENSITY) {
2611                         (STp->buffer)->b_data[4] = arg;
2612                         STp->density_changed = TRUE;    /* At least we tried ;-) */
2613                 } else if (cmd_in == SET_DENS_AND_BLK)
2614                         (STp->buffer)->b_data[4] = arg >> 24;
2615                 else
2616                         (STp->buffer)->b_data[4] = STp->density;
2617                 if (cmd_in == MTSETBLK || cmd_in == SET_DENS_AND_BLK) {
2618                         ltmp = arg & MT_ST_BLKSIZE_MASK;
2619                         if (cmd_in == MTSETBLK)
2620                                 STp->blksize_changed = TRUE; /* At least we tried ;-) */
2621                 } else
2622                         ltmp = STp->block_size;
2623                 (STp->buffer)->b_data[9] = (ltmp >> 16);
2624                 (STp->buffer)->b_data[10] = (ltmp >> 8);
2625                 (STp->buffer)->b_data[11] = ltmp;
2626                 timeout = STp->device->timeout;
2627                 DEBC(
2628                         if (cmd_in == MTSETBLK || cmd_in == SET_DENS_AND_BLK)
2629                                 printk(ST_DEB_MSG
2630                                        "%s: Setting block size to %d bytes.\n", name,
2631                                        (STp->buffer)->b_data[9] * 65536 +
2632                                        (STp->buffer)->b_data[10] * 256 +
2633                                        (STp->buffer)->b_data[11]);
2634                         if (cmd_in == MTSETDENSITY || cmd_in == SET_DENS_AND_BLK)
2635                                 printk(ST_DEB_MSG
2636                                        "%s: Setting density code to %x.\n", name,
2637                                        (STp->buffer)->b_data[4]);
2638                         if (cmd_in == MTSETDRVBUFFER)
2639                                 printk(ST_DEB_MSG
2640                                        "%s: Setting drive buffer code to %d.\n", name,
2641                                     ((STp->buffer)->b_data[2] >> 4) & 7);
2642                 )
2643                 break;
2644         default:
2645                 return (-ENOSYS);
2646         }
2647
2648         SRpnt = st_do_scsi(NULL, STp, cmd, datalen, direction,
2649                            timeout, MAX_RETRIES, TRUE);
2650         if (!SRpnt)
2651                 return (STp->buffer)->syscall_result;
2652
2653         ioctl_result = (STp->buffer)->syscall_result;
2654
2655         if (!ioctl_result) {    /* SCSI command successful */
2656                 scsi_release_request(SRpnt);
2657                 SRpnt = NULL;
2658                 STps->drv_block = blkno;
2659                 STps->drv_file = fileno;
2660                 STps->at_sm = at_sm;
2661
2662                 if (cmd_in == MTBSFM)
2663                         ioctl_result = st_int_ioctl(STp, MTFSF, 1);
2664                 else if (cmd_in == MTFSFM)
2665                         ioctl_result = st_int_ioctl(STp, MTBSF, 1);
2666
2667                 if (cmd_in == MTSETBLK || cmd_in == SET_DENS_AND_BLK) {
2668                         int old_block_size = STp->block_size;
2669                         STp->block_size = arg & MT_ST_BLKSIZE_MASK;
2670                         if (STp->block_size != 0) {
2671                                 if (old_block_size == 0)
2672                                         normalize_buffer(STp->buffer);
2673                                 (STp->buffer)->buffer_blocks =
2674                                     (STp->buffer)->buffer_size / STp->block_size;
2675                         }
2676                         (STp->buffer)->buffer_bytes = (STp->buffer)->read_pointer = 0;
2677                         if (cmd_in == SET_DENS_AND_BLK)
2678                                 STp->density = arg >> MT_ST_DENSITY_SHIFT;
2679                 } else if (cmd_in == MTSETDRVBUFFER)
2680                         STp->drv_buffer = (arg & 7);
2681                 else if (cmd_in == MTSETDENSITY)
2682                         STp->density = arg;
2683
2684                 if (cmd_in == MTEOM)
2685                         STps->eof = ST_EOD;
2686                 else if (cmd_in == MTFSF)
2687                         STps->eof = ST_FM;
2688                 else if (chg_eof)
2689                         STps->eof = ST_NOEOF;
2690
2691         } else { /* SCSI command was not completely successful. Don't return
2692                     from this block without releasing the SCSI command block! */
2693
2694                 if (SRpnt->sr_sense_buffer[2] & 0x40) {
2695                         if (cmd_in != MTBSF && cmd_in != MTBSFM &&
2696                             cmd_in != MTBSR && cmd_in != MTBSS)
2697                                 STps->eof = ST_EOM_OK;
2698                         STps->drv_block = 0;
2699                 }
2700
2701                 undone = ((SRpnt->sr_sense_buffer[3] << 24) +
2702                           (SRpnt->sr_sense_buffer[4] << 16) +
2703                           (SRpnt->sr_sense_buffer[5] << 8) +
2704                           SRpnt->sr_sense_buffer[6]);
2705
2706                 if (cmd_in == MTWEOF &&
2707                     (SRpnt->sr_sense_buffer[0] & 0x70) == 0x70 &&
2708                     (SRpnt->sr_sense_buffer[2] & 0x4f) == 0x40 &&
2709                  ((SRpnt->sr_sense_buffer[0] & 0x80) == 0 || undone == 0)) {
2710                         ioctl_result = 0;       /* EOF written succesfully at EOM */
2711                         if (fileno >= 0)
2712                                 fileno++;
2713                         STps->drv_file = fileno;
2714                         STps->eof = ST_NOEOF;
2715                 } else if ((cmd_in == MTFSF) || (cmd_in == MTFSFM)) {
2716                         if (fileno >= 0)
2717                                 STps->drv_file = fileno - undone;
2718                         else
2719                                 STps->drv_file = fileno;
2720                         STps->drv_block = 0;
2721                         STps->eof = ST_NOEOF;
2722                 } else if ((cmd_in == MTBSF) || (cmd_in == MTBSFM)) {
2723                         if (arg > 0 && undone < 0)  /* Some drives get this wrong */
2724                                 undone = (-undone);
2725                         if (STps->drv_file >= 0)
2726                                 STps->drv_file = fileno + undone;
2727                         STps->drv_block = 0;
2728                         STps->eof = ST_NOEOF;
2729                 } else if (cmd_in == MTFSR) {
2730                         if (SRpnt->sr_sense_buffer[2] & 0x80) { /* Hit filemark */
2731                                 if (STps->drv_file >= 0)
2732                                         STps->drv_file++;
2733                                 STps->drv_block = 0;
2734                                 STps->eof = ST_FM;
2735                         } else {
2736                                 if (blkno >= undone)
2737                                         STps->drv_block = blkno - undone;
2738                                 else
2739                                         STps->drv_block = (-1);
2740                                 STps->eof = ST_NOEOF;
2741                         }
2742                 } else if (cmd_in == MTBSR) {
2743                         if (SRpnt->sr_sense_buffer[2] & 0x80) { /* Hit filemark */
2744                                 STps->drv_file--;
2745                                 STps->drv_block = (-1);
2746                         } else {
2747                                 if (arg > 0 && undone < 0)  /* Some drives get this wrong */
2748                                         undone = (-undone);
2749                                 if (STps->drv_block >= 0)
2750                                         STps->drv_block = blkno + undone;
2751                         }
2752                         STps->eof = ST_NOEOF;
2753                 } else if (cmd_in == MTEOM) {
2754                         STps->drv_file = (-1);
2755                         STps->drv_block = (-1);
2756                         STps->eof = ST_EOD;
2757                 } else if (cmd_in == MTSETBLK ||
2758                            cmd_in == MTSETDENSITY ||
2759                            cmd_in == MTSETDRVBUFFER ||
2760                            cmd_in == SET_DENS_AND_BLK) {
2761                         if ((SRpnt->sr_sense_buffer[2] & 0x0f) == ILLEGAL_REQUEST &&
2762                             !(STp->use_pf & PF_TESTED)) {
2763                                 /* Try the other possible state of Page Format if not
2764                                    already tried */
2765                                 STp->use_pf = !STp->use_pf | PF_TESTED;
2766                                 scsi_release_request(SRpnt);
2767                                 SRpnt = NULL;
2768                                 return st_int_ioctl(STp, cmd_in, arg);
2769                         }
2770                 } else if (chg_eof)
2771                         STps->eof = ST_NOEOF;
2772
2773                 if ((SRpnt->sr_sense_buffer[2] & 0x0f) == BLANK_CHECK)
2774                         STps->eof = ST_EOD;
2775
2776                 scsi_release_request(SRpnt);
2777                 SRpnt = NULL;
2778         }
2779
2780         return ioctl_result;
2781 }
2782 \f
2783
2784 /* Get the tape position. If bt == 2, arg points into a kernel space mt_loc
2785    structure. */
2786
2787 static int get_location(Scsi_Tape *STp, unsigned int *block, int *partition,
2788                         int logical)
2789 {
2790         int result;
2791         unsigned char scmd[MAX_COMMAND_SIZE];
2792         Scsi_Request *SRpnt;
2793         DEB( char *name = tape_name(STp); )
2794
2795         if (STp->ready != ST_READY)
2796                 return (-EIO);
2797
2798         memset(scmd, 0, MAX_COMMAND_SIZE);
2799         if ((STp->device)->scsi_level < SCSI_2) {
2800                 scmd[0] = QFA_REQUEST_BLOCK;
2801                 scmd[4] = 3;
2802         } else {
2803                 scmd[0] = READ_POSITION;
2804                 if (!logical && !STp->scsi2_logical)
2805                         scmd[1] = 1;
2806         }
2807         SRpnt = st_do_scsi(NULL, STp, scmd, 20, SCSI_DATA_READ, STp->device->timeout,
2808                            MAX_READY_RETRIES, TRUE);
2809         if (!SRpnt)
2810                 return (STp->buffer)->syscall_result;
2811
2812         if ((STp->buffer)->syscall_result != 0 ||
2813             (STp->device->scsi_level >= SCSI_2 &&
2814              ((STp->buffer)->b_data[0] & 4) != 0)) {
2815                 *block = *partition = 0;
2816                 DEBC(printk(ST_DEB_MSG "%s: Can't read tape position.\n", name));
2817                 result = (-EIO);
2818         } else {
2819                 result = 0;
2820                 if ((STp->device)->scsi_level < SCSI_2) {
2821                         *block = ((STp->buffer)->b_data[0] << 16)
2822                             + ((STp->buffer)->b_data[1] << 8)
2823                             + (STp->buffer)->b_data[2];
2824                         *partition = 0;
2825                 } else {
2826                         *block = ((STp->buffer)->b_data[4] << 24)
2827                             + ((STp->buffer)->b_data[5] << 16)
2828                             + ((STp->buffer)->b_data[6] << 8)
2829                             + (STp->buffer)->b_data[7];
2830                         *partition = (STp->buffer)->b_data[1];
2831                         if (((STp->buffer)->b_data[0] & 0x80) &&
2832                             (STp->buffer)->b_data[1] == 0)      /* BOP of partition 0 */
2833                                 STp->ps[0].drv_block = STp->ps[0].drv_file = 0;
2834                 }
2835                 DEBC(printk(ST_DEB_MSG "%s: Got tape pos. blk %d part %d.\n", name,
2836                             *block, *partition));
2837         }
2838         scsi_release_request(SRpnt);
2839         SRpnt = NULL;
2840
2841         return result;
2842 }
2843
2844
2845 /* Set the tape block and partition. Negative partition means that only the
2846    block should be set in vendor specific way. */
2847 static int set_location(Scsi_Tape *STp, unsigned int block, int partition,
2848                         int logical)
2849 {
2850         ST_partstat *STps;
2851         int result, p;
2852         unsigned int blk;
2853         int timeout;
2854         unsigned char scmd[MAX_COMMAND_SIZE];
2855         Scsi_Request *SRpnt;
2856         DEB( char *name = tape_name(STp); )
2857
2858         if (STp->ready != ST_READY)
2859                 return (-EIO);
2860         timeout = STp->long_timeout;
2861         STps = &(STp->ps[STp->partition]);
2862
2863         DEBC(printk(ST_DEB_MSG "%s: Setting block to %d and partition to %d.\n",
2864                     name, block, partition));
2865         DEB(if (partition < 0)
2866                 return (-EIO); )
2867
2868         /* Update the location at the partition we are leaving */
2869         if ((!STp->can_partitions && partition != 0) ||
2870             partition >= ST_NBR_PARTITIONS)
2871                 return (-EINVAL);
2872         if (partition != STp->partition) {
2873                 if (get_location(STp, &blk, &p, 1))
2874                         STps->last_block_valid = FALSE;
2875                 else {
2876                         STps->last_block_valid = TRUE;
2877                         STps->last_block_visited = blk;
2878                         DEBC(printk(ST_DEB_MSG
2879                                     "%s: Visited block %d for partition %d saved.\n",
2880                                     name, blk, STp->partition));
2881                 }
2882         }
2883
2884         memset(scmd, 0, MAX_COMMAND_SIZE);
2885         if ((STp->device)->scsi_level < SCSI_2) {
2886                 scmd[0] = QFA_SEEK_BLOCK;
2887                 scmd[2] = (block >> 16);
2888                 scmd[3] = (block >> 8);
2889                 scmd[4] = block;
2890                 scmd[5] = 0;
2891         } else {
2892                 scmd[0] = SEEK_10;
2893                 scmd[3] = (block >> 24);
2894                 scmd[4] = (block >> 16);
2895                 scmd[5] = (block >> 8);
2896                 scmd[6] = block;
2897                 if (!logical && !STp->scsi2_logical)
2898                         scmd[1] = 4;
2899                 if (STp->partition != partition) {
2900                         scmd[1] |= 2;
2901                         scmd[8] = partition;
2902                         DEBC(printk(ST_DEB_MSG
2903                                     "%s: Trying to change partition from %d to %d\n",
2904                                     name, STp->partition, partition));
2905                 }
2906         }
2907         if (STp->immediate) {
2908                 scmd[1] |= 1;           /* Don't wait for completion */
2909                 timeout = STp->device->timeout;
2910         }
2911
2912         SRpnt = st_do_scsi(NULL, STp, scmd, 0, SCSI_DATA_NONE,
2913                            timeout, MAX_READY_RETRIES, TRUE);
2914         if (!SRpnt)
2915                 return (STp->buffer)->syscall_result;
2916
2917         STps->drv_block = STps->drv_file = (-1);
2918         STps->eof = ST_NOEOF;
2919         if ((STp->buffer)->syscall_result != 0) {
2920                 result = (-EIO);
2921                 if (STp->can_partitions &&
2922                     (STp->device)->scsi_level >= SCSI_2 &&
2923                     (p = find_partition(STp)) >= 0)
2924                         STp->partition = p;
2925         } else {
2926                 if (STp->can_partitions) {
2927                         STp->partition = partition;
2928                         STps = &(STp->ps[partition]);
2929                         if (!STps->last_block_valid ||
2930                             STps->last_block_visited != block) {
2931                                 STps->at_sm = 0;
2932                                 STps->rw = ST_IDLE;
2933                         }
2934                 } else
2935                         STps->at_sm = 0;
2936                 if (block == 0)
2937                         STps->drv_block = STps->drv_file = 0;
2938                 result = 0;
2939         }
2940
2941         scsi_release_request(SRpnt);
2942         SRpnt = NULL;
2943
2944         return result;
2945 }
2946
2947
2948 /* Find the current partition number for the drive status. Called from open and
2949    returns either partition number of negative error code. */
2950 static int find_partition(Scsi_Tape *STp)
2951 {
2952         int i, partition;
2953         unsigned int block;
2954
2955         if ((i = get_location(STp, &block, &partition, 1)) < 0)
2956                 return i;
2957         if (partition >= ST_NBR_PARTITIONS)
2958                 return (-EIO);
2959         return partition;
2960 }
2961
2962
2963 /* Change the partition if necessary */
2964 static int switch_partition(Scsi_Tape *STp)
2965 {
2966         ST_partstat *STps;
2967
2968         if (STp->partition == STp->new_partition)
2969                 return 0;
2970         STps = &(STp->ps[STp->new_partition]);
2971         if (!STps->last_block_valid)
2972                 STps->last_block_visited = 0;
2973         return set_location(STp, STps->last_block_visited, STp->new_partition, 1);
2974 }
2975 \f
2976 /* Functions for reading and writing the medium partition mode page. */
2977
2978 #define PART_PAGE   0x11
2979 #define PART_PAGE_FIXED_LENGTH 8
2980
2981 #define PP_OFF_MAX_ADD_PARTS   2
2982 #define PP_OFF_NBR_ADD_PARTS   3
2983 #define PP_OFF_FLAGS           4
2984 #define PP_OFF_PART_UNITS      6
2985 #define PP_OFF_RESERVED        7
2986
2987 #define PP_BIT_IDP             0x20
2988 #define PP_MSK_PSUM_MB         0x10
2989
2990 /* Get the number of partitions on the tape. As a side effect reads the
2991    mode page into the tape buffer. */
2992 static int nbr_partitions(Scsi_Tape *STp)
2993 {
2994         int result;
2995         DEB( char *name = tape_name(STp); )
2996
2997         if (STp->ready != ST_READY)
2998                 return (-EIO);
2999
3000         result = read_mode_page(STp, PART_PAGE, TRUE);
3001
3002         if (result) {
3003                 DEBC(printk(ST_DEB_MSG "%s: Can't read medium partition page.\n",
3004                             name));
3005                 result = (-EIO);
3006         } else {
3007                 result = (STp->buffer)->b_data[MODE_HEADER_LENGTH +
3008                                               PP_OFF_NBR_ADD_PARTS] + 1;
3009                 DEBC(printk(ST_DEB_MSG "%s: Number of partitions %d.\n", name, result));
3010         }
3011
3012         return result;
3013 }
3014
3015
3016 /* Partition the tape into two partitions if size > 0 or one partition if
3017    size == 0.
3018
3019    The block descriptors are read and written because Sony SDT-7000 does not
3020    work without this (suggestion from Michael Schaefer <Michael.Schaefer@dlr.de>).
3021
3022    My HP C1533A drive returns only one partition size field. This is used to
3023    set the size of partition 1. There is no size field for the default partition.
3024    Michael Schaefer's Sony SDT-7000 returns two descriptors and the second is
3025    used to set the size of partition 1 (this is what the SCSI-3 standard specifies).
3026    The following algorithm is used to accommodate both drives: if the number of
3027    partition size fields is greater than the maximum number of additional partitions
3028    in the mode page, the second field is used. Otherwise the first field is used.
3029
3030    For Seagate DDS drives the page length must be 8 when no partitions is defined
3031    and 10 when 1 partition is defined (information from Eric Lee Green). This is
3032    is acceptable also to some other old drives and enforced if the first partition
3033    size field is used for the first additional partition size.
3034  */
3035 static int partition_tape(Scsi_Tape *STp, int size)
3036 {
3037         char *name = tape_name(STp);
3038         int result;
3039         int pgo, psd_cnt, psdo;
3040         unsigned char *bp;
3041
3042         result = read_mode_page(STp, PART_PAGE, FALSE);
3043         if (result) {
3044                 DEBC(printk(ST_DEB_MSG "%s: Can't read partition mode page.\n", name));
3045                 return result;
3046         }
3047         /* The mode page is in the buffer. Let's modify it and write it. */
3048         bp = (STp->buffer)->b_data;
3049         pgo = MODE_HEADER_LENGTH + bp[MH_OFF_BDESCS_LENGTH];
3050         DEBC(printk(ST_DEB_MSG "%s: Partition page length is %d bytes.\n",
3051                     name, bp[pgo + MP_OFF_PAGE_LENGTH] + 2));
3052
3053         psd_cnt = (bp[pgo + MP_OFF_PAGE_LENGTH] + 2 - PART_PAGE_FIXED_LENGTH) / 2;
3054         psdo = pgo + PART_PAGE_FIXED_LENGTH;
3055         if (psd_cnt > bp[pgo + PP_OFF_MAX_ADD_PARTS]) {
3056                 bp[psdo] = bp[psdo + 1] = 0xff;  /* Rest of the tape */
3057                 psdo += 2;
3058         }
3059         memset(bp + psdo, 0, bp[pgo + PP_OFF_NBR_ADD_PARTS] * 2);
3060
3061         DEBC(printk("%s: psd_cnt %d, max.parts %d, nbr_parts %d\n", name,
3062                     psd_cnt, bp[pgo + PP_OFF_MAX_ADD_PARTS],
3063                     bp[pgo + PP_OFF_NBR_ADD_PARTS]));
3064
3065         if (size <= 0) {
3066                 bp[pgo + PP_OFF_NBR_ADD_PARTS] = 0;
3067                 if (psd_cnt <= bp[pgo + PP_OFF_MAX_ADD_PARTS])
3068                     bp[pgo + MP_OFF_PAGE_LENGTH] = 6;
3069                 DEBC(printk(ST_DEB_MSG "%s: Formatting tape with one partition.\n",
3070                             name));
3071         } else {
3072                 bp[psdo] = (size >> 8) & 0xff;
3073                 bp[psdo + 1] = size & 0xff;
3074                 bp[pgo + 3] = 1;
3075                 if (bp[pgo + MP_OFF_PAGE_LENGTH] < 8)
3076                     bp[pgo + MP_OFF_PAGE_LENGTH] = 8;
3077                 DEBC(printk(ST_DEB_MSG
3078                             "%s: Formatting tape with two partitions (1 = %d MB).\n",
3079                             name, size));
3080         }
3081         bp[pgo + PP_OFF_PART_UNITS] = 0;
3082         bp[pgo + PP_OFF_RESERVED] = 0;
3083         bp[pgo + PP_OFF_FLAGS] = PP_BIT_IDP | PP_MSK_PSUM_MB;
3084
3085         result = write_mode_page(STp, PART_PAGE, TRUE);
3086         if (result) {
3087                 printk(KERN_INFO "%s: Partitioning of tape failed.\n", name);
3088                 result = (-EIO);
3089         }
3090
3091         return result;
3092 }
3093 \f
3094
3095
3096 /* The ioctl command */
3097 static int st_ioctl(struct inode *inode, struct file *file,
3098                     unsigned int cmd_in, unsigned long arg)
3099 {
3100         int i, cmd_nr, cmd_type, bt;
3101         int retval = 0;
3102         unsigned int blk;
3103         Scsi_Tape *STp = file->private_data;
3104         ST_mode *STm;
3105         ST_partstat *STps;
3106         char *name = tape_name(STp);
3107         void __user *p = (void __user *)arg;
3108
3109         if (down_interruptible(&STp->lock))
3110                 return -ERESTARTSYS;
3111
3112         DEB(
3113         if (debugging && !STp->in_use) {
3114                 printk(ST_DEB_MSG "%s: Incorrect device.\n", name);
3115                 retval = (-EIO);
3116                 goto out;
3117         } ) /* end DEB */
3118
3119         STm = &(STp->modes[STp->current_mode]);
3120         STps = &(STp->ps[STp->partition]);
3121
3122         /*
3123          * If we are in the middle of error recovery, don't let anyone
3124          * else try and use this device.  Also, if error recovery fails, it
3125          * may try and take the device offline, in which case all further
3126          * access to the device is prohibited.
3127          */
3128         if (!scsi_block_when_processing_errors(STp->device)) {
3129                 retval = (-ENXIO);
3130                 goto out;
3131         }
3132         cmd_type = _IOC_TYPE(cmd_in);
3133         cmd_nr = _IOC_NR(cmd_in);
3134
3135         if (cmd_type == _IOC_TYPE(MTIOCTOP) && cmd_nr == _IOC_NR(MTIOCTOP)) {
3136                 struct mtop mtc;
3137
3138                 if (_IOC_SIZE(cmd_in) != sizeof(mtc)) {
3139                         retval = (-EINVAL);
3140                         goto out;
3141                 }
3142
3143                 i = copy_from_user(&mtc, p, sizeof(struct mtop));
3144                 if (i) {
3145                         retval = (-EFAULT);
3146                         goto out;
3147                 }
3148
3149                 if (mtc.mt_op == MTSETDRVBUFFER && !capable(CAP_SYS_ADMIN)) {
3150                         printk(KERN_WARNING
3151                                "%s: MTSETDRVBUFFER only allowed for root.\n", name);
3152                         retval = (-EPERM);
3153                         goto out;
3154                 }
3155                 if (!STm->defined &&
3156                     (mtc.mt_op != MTSETDRVBUFFER &&
3157                      (mtc.mt_count & MT_ST_OPTIONS) == 0)) {
3158                         retval = (-ENXIO);
3159                         goto out;
3160                 }
3161
3162                 if (!STp->pos_unknown) {
3163
3164                         if (STps->eof == ST_FM_HIT) {
3165                                 if (mtc.mt_op == MTFSF || mtc.mt_op == MTFSFM ||
3166                                     mtc.mt_op == MTEOM) {
3167                                         mtc.mt_count -= 1;
3168                                         if (STps->drv_file >= 0)
3169                                                 STps->drv_file += 1;
3170                                 } else if (mtc.mt_op == MTBSF || mtc.mt_op == MTBSFM) {
3171                                         mtc.mt_count += 1;
3172                                         if (STps->drv_file >= 0)
3173                                                 STps->drv_file += 1;
3174                                 }
3175                         }
3176
3177                         if (mtc.mt_op == MTSEEK) {
3178                                 /* Old position must be restored if partition will be
3179                                    changed */
3180                                 i = !STp->can_partitions ||
3181                                     (STp->new_partition != STp->partition);
3182                         } else {
3183                                 i = mtc.mt_op == MTREW || mtc.mt_op == MTOFFL ||
3184                                     mtc.mt_op == MTRETEN || mtc.mt_op == MTEOM ||
3185                                     mtc.mt_op == MTLOCK || mtc.mt_op == MTLOAD ||
3186                                     mtc.mt_op == MTFSF || mtc.mt_op == MTFSFM ||
3187                                     mtc.mt_op == MTBSF || mtc.mt_op == MTBSFM ||
3188                                     mtc.mt_op == MTCOMPRESSION;
3189                         }
3190                         i = flush_buffer(STp, i);
3191                         if (i < 0) {
3192                                 retval = i;
3193                                 goto out;
3194                         }
3195                 } else {
3196                         /*
3197                          * If there was a bus reset, block further access
3198                          * to this device.  If the user wants to rewind the tape,
3199                          * then reset the flag and allow access again.
3200                          */
3201                         if (mtc.mt_op != MTREW &&
3202                             mtc.mt_op != MTOFFL &&
3203                             mtc.mt_op != MTRETEN &&
3204                             mtc.mt_op != MTERASE &&
3205                             mtc.mt_op != MTSEEK &&
3206                             mtc.mt_op != MTEOM) {
3207                                 retval = (-EIO);
3208                                 goto out;
3209                         }
3210                         reset_state(STp);
3211                         /* remove this when the midlevel properly clears was_reset */
3212                         STp->device->was_reset = 0;
3213                 }
3214
3215                 if (mtc.mt_op != MTNOP && mtc.mt_op != MTSETBLK &&
3216                     mtc.mt_op != MTSETDENSITY && mtc.mt_op != MTWSM &&
3217                     mtc.mt_op != MTSETDRVBUFFER && mtc.mt_op != MTSETPART)
3218                         STps->rw = ST_IDLE;     /* Prevent automatic WEOF and fsf */
3219
3220                 if (mtc.mt_op == MTOFFL && STp->door_locked != ST_UNLOCKED)
3221                         do_door_lock(STp, 0);   /* Ignore result! */
3222
3223                 if (mtc.mt_op == MTSETDRVBUFFER &&
3224                     (mtc.mt_count & MT_ST_OPTIONS) != 0) {
3225                         retval = st_set_options(STp, mtc.mt_count);
3226                         goto out;
3227                 }
3228
3229                 if (mtc.mt_op == MTSETPART) {
3230                         if (!STp->can_partitions ||
3231                             mtc.mt_count < 0 || mtc.mt_count >= ST_NBR_PARTITIONS) {
3232                                 retval = (-EINVAL);
3233                                 goto out;
3234                         }
3235                         if (mtc.mt_count >= STp->nbr_partitions &&
3236                             (STp->nbr_partitions = nbr_partitions(STp)) < 0) {
3237                                 retval = (-EIO);
3238                                 goto out;
3239                         }
3240                         if (mtc.mt_count >= STp->nbr_partitions) {
3241                                 retval = (-EINVAL);
3242                                 goto out;
3243                         }
3244                         STp->new_partition = mtc.mt_count;
3245                         retval = 0;
3246                         goto out;
3247                 }
3248
3249                 if (mtc.mt_op == MTMKPART) {
3250                         if (!STp->can_partitions) {
3251                                 retval = (-EINVAL);
3252                                 goto out;
3253                         }
3254                         if ((i = st_int_ioctl(STp, MTREW, 0)) < 0 ||
3255                             (i = partition_tape(STp, mtc.mt_count)) < 0) {
3256                                 retval = i;
3257                                 goto out;
3258                         }
3259                         for (i = 0; i < ST_NBR_PARTITIONS; i++) {
3260                                 STp->ps[i].rw = ST_IDLE;
3261                                 STp->ps[i].at_sm = 0;
3262                                 STp->ps[i].last_block_valid = FALSE;
3263                         }
3264                         STp->partition = STp->new_partition = 0;
3265                         STp->nbr_partitions = 1;        /* Bad guess ?-) */
3266                         STps->drv_block = STps->drv_file = 0;
3267                         retval = 0;
3268                         goto out;
3269                 }
3270
3271                 if (mtc.mt_op == MTSEEK) {
3272                         i = set_location(STp, mtc.mt_count, STp->new_partition, 0);
3273                         if (!STp->can_partitions)
3274                                 STp->ps[0].rw = ST_IDLE;
3275                         retval = i;
3276                         goto out;
3277                 }
3278
3279                 if (mtc.mt_op == MTUNLOAD || mtc.mt_op == MTOFFL) {
3280                         retval = do_load_unload(STp, file, 0);
3281                         goto out;
3282                 }
3283
3284                 if (mtc.mt_op == MTLOAD) {
3285                         retval = do_load_unload(STp, file, max(1, mtc.mt_count));
3286                         goto out;
3287                 }
3288
3289                 if (mtc.mt_op == MTLOCK || mtc.mt_op == MTUNLOCK) {
3290                         retval = do_door_lock(STp, (mtc.mt_op == MTLOCK));
3291                         goto out;
3292                 }
3293
3294                 if (STp->can_partitions && STp->ready == ST_READY &&
3295                     (i = switch_partition(STp)) < 0) {
3296                         retval = i;
3297                         goto out;
3298                 }
3299
3300                 if (mtc.mt_op == MTCOMPRESSION)
3301                         retval = st_compression(STp, (mtc.mt_count & 1));
3302                 else
3303                         retval = st_int_ioctl(STp, mtc.mt_op, mtc.mt_count);
3304                 goto out;
3305         }
3306         if (!STm->defined) {
3307                 retval = (-ENXIO);
3308                 goto out;
3309         }
3310
3311         if ((i = flush_buffer(STp, FALSE)) < 0) {
3312                 retval = i;
3313                 goto out;
3314         }
3315         if (STp->can_partitions &&
3316             (i = switch_partition(STp)) < 0) {
3317                 retval = i;
3318                 goto out;
3319         }
3320
3321         if (cmd_type == _IOC_TYPE(MTIOCGET) && cmd_nr == _IOC_NR(MTIOCGET)) {
3322                 struct mtget mt_status;
3323
3324                 if (_IOC_SIZE(cmd_in) != sizeof(struct mtget)) {
3325                          retval = (-EINVAL);
3326                          goto out;
3327                 }
3328
3329                 mt_status.mt_type = STp->tape_type;
3330                 mt_status.mt_dsreg =
3331                     ((STp->block_size << MT_ST_BLKSIZE_SHIFT) & MT_ST_BLKSIZE_MASK) |
3332                     ((STp->density << MT_ST_DENSITY_SHIFT) & MT_ST_DENSITY_MASK);
3333                 mt_status.mt_blkno = STps->drv_block;
3334                 mt_status.mt_fileno = STps->drv_file;
3335                 if (STp->block_size != 0) {
3336                         if (STps->rw == ST_WRITING)
3337                                 mt_status.mt_blkno +=
3338                                     (STp->buffer)->buffer_bytes / STp->block_size;
3339                         else if (STps->rw == ST_READING)
3340                                 mt_status.mt_blkno -=
3341                                         ((STp->buffer)->buffer_bytes +
3342                                          STp->block_size - 1) / STp->block_size;
3343                 }
3344
3345                 mt_status.mt_gstat = 0;
3346                 if (STp->drv_write_prot)
3347                         mt_status.mt_gstat |= GMT_WR_PROT(0xffffffff);
3348                 if (mt_status.mt_blkno == 0) {
3349                         if (mt_status.mt_fileno == 0)
3350                                 mt_status.mt_gstat |= GMT_BOT(0xffffffff);
3351                         else
3352                                 mt_status.mt_gstat |= GMT_EOF(0xffffffff);
3353                 }
3354                 mt_status.mt_erreg = (STp->recover_reg << MT_ST_SOFTERR_SHIFT);
3355                 mt_status.mt_resid = STp->partition;
3356                 if (STps->eof == ST_EOM_OK || STps->eof == ST_EOM_ERROR)
3357                         mt_status.mt_gstat |= GMT_EOT(0xffffffff);
3358                 else if (STps->eof >= ST_EOM_OK)
3359                         mt_status.mt_gstat |= GMT_EOD(0xffffffff);
3360                 if (STp->density == 1)
3361                         mt_status.mt_gstat |= GMT_D_800(0xffffffff);
3362                 else if (STp->density == 2)
3363                         mt_status.mt_gstat |= GMT_D_1600(0xffffffff);
3364                 else if (STp->density == 3)
3365                         mt_status.mt_gstat |= GMT_D_6250(0xffffffff);
3366                 if (STp->ready == ST_READY)
3367                         mt_status.mt_gstat |= GMT_ONLINE(0xffffffff);
3368                 if (STp->ready == ST_NO_TAPE)
3369                         mt_status.mt_gstat |= GMT_DR_OPEN(0xffffffff);
3370                 if (STps->at_sm)
3371                         mt_status.mt_gstat |= GMT_SM(0xffffffff);
3372                 if (STm->do_async_writes ||
3373                     (STm->do_buffer_writes && STp->block_size != 0) ||
3374                     STp->drv_buffer != 0)
3375                         mt_status.mt_gstat |= GMT_IM_REP_EN(0xffffffff);
3376                 if (STp->cleaning_req)
3377                         mt_status.mt_gstat |= GMT_CLN(0xffffffff);
3378
3379                 i = copy_to_user(p, &mt_status, sizeof(struct mtget));
3380                 if (i) {
3381                         retval = (-EFAULT);
3382                         goto out;
3383                 }
3384
3385                 STp->recover_reg = 0;           /* Clear after read */
3386                 retval = 0;
3387                 goto out;
3388         }                       /* End of MTIOCGET */
3389         if (cmd_type == _IOC_TYPE(MTIOCPOS) && cmd_nr == _IOC_NR(MTIOCPOS)) {
3390                 struct mtpos mt_pos;
3391                 if (_IOC_SIZE(cmd_in) != sizeof(struct mtpos)) {
3392                          retval = (-EINVAL);
3393                          goto out;
3394                 }
3395                 if ((i = get_location(STp, &blk, &bt, 0)) < 0) {
3396                         retval = i;
3397                         goto out;
3398                 }
3399                 mt_pos.mt_blkno = blk;
3400                 i = copy_to_user(p, &mt_pos, sizeof(struct mtpos));
3401                 if (i)
3402                         retval = (-EFAULT);
3403                 goto out;
3404         }
3405         up(&STp->lock);
3406         switch (cmd_in) {
3407                 case SCSI_IOCTL_GET_IDLUN:
3408                 case SCSI_IOCTL_GET_BUS_NUMBER:
3409                         break;
3410                 default:
3411                         i = scsi_cmd_ioctl(file, STp->disk, cmd_in, p);
3412                         if (i != -ENOTTY)
3413                                 return i;
3414                         break;
3415         }
3416         return scsi_ioctl(STp->device, cmd_in, p);
3417
3418  out:
3419         up(&STp->lock);
3420         return retval;
3421 }
3422 \f
3423
3424 /* Try to allocate a new tape buffer. Calling function must not hold
3425    dev_arr_lock. */
3426 static ST_buffer *
3427  new_tape_buffer(int from_initialization, int need_dma, int max_sg)
3428 {
3429         int i, priority, got = 0, segs = 0;
3430         ST_buffer *tb;
3431
3432         if (from_initialization)
3433                 priority = GFP_ATOMIC;
3434         else
3435                 priority = GFP_KERNEL;
3436
3437         i = sizeof(ST_buffer) + (max_sg - 1) * sizeof(struct scatterlist) +
3438                 max_sg * sizeof(struct st_buf_fragment);
3439         tb = kmalloc(i, priority);
3440         if (!tb) {
3441                 printk(KERN_NOTICE "st: Can't allocate new tape buffer.\n");
3442                 return NULL;
3443         }
3444         memset(tb, 0, i);
3445         tb->frp_segs = tb->orig_frp_segs = segs;
3446         tb->use_sg = max_sg;
3447         if (segs > 0)
3448                 tb->b_data = page_address(tb->sg[0].page);
3449         tb->frp = (struct st_buf_fragment *)(&(tb->sg[0]) + max_sg);
3450
3451         tb->in_use = TRUE;
3452         tb->dma = need_dma;
3453         tb->buffer_size = got;
3454
3455         return tb;
3456 }
3457
3458
3459 /* Try to allocate enough space in the tape buffer */
3460 static int enlarge_buffer(ST_buffer * STbuffer, int new_size, int need_dma)
3461 {
3462         int segs, nbr, max_segs, b_size, priority, order, got;
3463
3464         if (new_size <= STbuffer->buffer_size)
3465                 return TRUE;
3466
3467         if (STbuffer->buffer_size <= PAGE_SIZE)
3468                 normalize_buffer(STbuffer);  /* Avoid extra segment */
3469
3470         max_segs = STbuffer->use_sg;
3471         nbr = max_segs - STbuffer->frp_segs;
3472         if (nbr <= 0)
3473                 return FALSE;
3474
3475         priority = GFP_KERNEL | __GFP_NOWARN;
3476         if (need_dma)
3477                 priority |= GFP_DMA;
3478         for (b_size = PAGE_SIZE, order=0;
3479              b_size < new_size - STbuffer->buffer_size;
3480              order++, b_size *= 2)
3481                 ;  /* empty */
3482
3483         for (segs = STbuffer->frp_segs, got = STbuffer->buffer_size;
3484              segs < max_segs && got < new_size;) {
3485                 STbuffer->frp[segs].page = alloc_pages(priority, order);
3486                 if (STbuffer->frp[segs].page == NULL) {
3487                         if (new_size - got <= (max_segs - segs) * b_size / 2) {
3488                                 b_size /= 2; /* Large enough for the rest of the buffers */
3489                                 order--;
3490                                 continue;
3491                         }
3492                         DEB(STbuffer->buffer_size = got);
3493                         normalize_buffer(STbuffer);
3494                         return FALSE;
3495                 }
3496                 STbuffer->frp[segs].length = b_size;
3497                 STbuffer->frp_segs += 1;
3498                 got += b_size;
3499                 STbuffer->buffer_size = got;
3500                 segs++;
3501         }
3502         STbuffer->b_data = page_address(STbuffer->frp[0].page);
3503
3504         return TRUE;
3505 }
3506
3507
3508 /* Release the extra buffer */
3509 static void normalize_buffer(ST_buffer * STbuffer)
3510 {
3511         int i, order;
3512
3513         for (i = STbuffer->orig_frp_segs; i < STbuffer->frp_segs; i++) {
3514                 order = get_order(STbuffer->frp[i].length);
3515                 __free_pages(STbuffer->frp[i].page, order);
3516                 STbuffer->buffer_size -= STbuffer->frp[i].length;
3517         }
3518         STbuffer->frp_segs = STbuffer->orig_frp_segs;
3519         STbuffer->frp_sg_current = 0;
3520 }
3521
3522
3523 /* Move data from the user buffer to the tape buffer. Returns zero (success) or
3524    negative error code. */
3525 static int append_to_buffer(const char __user *ubp, ST_buffer * st_bp, int do_count)
3526 {
3527         int i, cnt, res, offset;
3528
3529         for (i = 0, offset = st_bp->buffer_bytes;
3530              i < st_bp->frp_segs && offset >= st_bp->frp[i].length; i++)
3531                 offset -= st_bp->frp[i].length;
3532         if (i == st_bp->frp_segs) {     /* Should never happen */
3533                 printk(KERN_WARNING "st: append_to_buffer offset overflow.\n");
3534                 return (-EIO);
3535         }
3536         for (; i < st_bp->frp_segs && do_count > 0; i++) {
3537                 cnt = st_bp->frp[i].length - offset < do_count ?
3538                     st_bp->frp[i].length - offset : do_count;
3539                 res = copy_from_user(page_address(st_bp->frp[i].page) + offset, ubp, cnt);
3540                 if (res)
3541                         return (-EFAULT);
3542                 do_count -= cnt;
3543                 st_bp->buffer_bytes += cnt;
3544                 ubp += cnt;
3545                 offset = 0;
3546         }
3547         if (do_count) /* Should never happen */
3548                 return (-EIO);
3549
3550         return 0;
3551 }
3552
3553
3554 /* Move data from the tape buffer to the user buffer. Returns zero (success) or
3555    negative error code. */
3556 static int from_buffer(ST_buffer * st_bp, char __user *ubp, int do_count)
3557 {
3558         int i, cnt, res, offset;
3559
3560         for (i = 0, offset = st_bp->read_pointer;
3561              i < st_bp->frp_segs && offset >= st_bp->frp[i].length; i++)
3562                 offset -= st_bp->frp[i].length;
3563         if (i == st_bp->frp_segs) {     /* Should never happen */
3564                 printk(KERN_WARNING "st: from_buffer offset overflow.\n");
3565                 return (-EIO);
3566         }
3567         for (; i < st_bp->frp_segs && do_count > 0; i++) {
3568                 cnt = st_bp->frp[i].length - offset < do_count ?
3569                     st_bp->frp[i].length - offset : do_count;
3570                 res = copy_to_user(ubp, page_address(st_bp->frp[i].page) + offset, cnt);
3571                 if (res)
3572                         return (-EFAULT);
3573                 do_count -= cnt;
3574                 st_bp->buffer_bytes -= cnt;
3575                 st_bp->read_pointer += cnt;
3576                 ubp += cnt;
3577                 offset = 0;
3578         }
3579         if (do_count) /* Should never happen */
3580                 return (-EIO);
3581
3582         return 0;
3583 }
3584
3585
3586 /* Move data towards start of buffer */
3587 static void move_buffer_data(ST_buffer * st_bp, int offset)
3588 {
3589         int src_seg, dst_seg, src_offset = 0, dst_offset;
3590         int count, total;
3591
3592         if (offset == 0)
3593                 return;
3594
3595         total=st_bp->buffer_bytes - offset;
3596         for (src_seg=0; src_seg < st_bp->frp_segs; src_seg++) {
3597                 src_offset = offset;
3598                 if (src_offset < st_bp->frp[src_seg].length)
3599                         break;
3600                 offset -= st_bp->frp[src_seg].length;
3601         }
3602
3603         st_bp->buffer_bytes = st_bp->read_pointer = total;
3604         for (dst_seg=dst_offset=0; total > 0; ) {
3605                 count = min(st_bp->frp[dst_seg].length - dst_offset,
3606                             st_bp->frp[src_seg].length - src_offset);
3607                 memmove(page_address(st_bp->frp[dst_seg].page) + dst_offset,
3608                         page_address(st_bp->frp[src_seg].page) + src_offset, count);
3609                 src_offset += count;
3610                 if (src_offset >= st_bp->frp[src_seg].length) {
3611                         src_seg++;
3612                         src_offset = 0;
3613                 }
3614                 dst_offset += count;
3615                 if (dst_offset >= st_bp->frp[dst_seg].length) {
3616                         dst_seg++;
3617                         dst_offset = 0;
3618                 }
3619                 total -= count;
3620         }
3621 }
3622
3623
3624 /* Fill the s/g list up to the length required for this transfer */
3625 static void buf_to_sg(ST_buffer *STbp, unsigned int length)
3626 {
3627         int i;
3628         unsigned int count;
3629         struct scatterlist *sg;
3630         struct st_buf_fragment *frp;
3631
3632         if (length == STbp->frp_sg_current)
3633                 return;   /* work already done */
3634
3635         sg = &(STbp->sg[0]);
3636         frp = STbp->frp;
3637         for (i=count=0; count < length; i++) {
3638                 sg[i].page = frp[i].page;
3639                 if (length - count > frp[i].length)
3640                         sg[i].length = frp[i].length;
3641                 else
3642                         sg[i].length = length - count;
3643                 count += sg[i].length;
3644                 sg[i].offset = 0;
3645         }
3646         STbp->sg_segs = i;
3647         STbp->frp_sg_current = length;
3648 }
3649
3650
3651 /* Validate the options from command line or module parameters */
3652 static void validate_options(void)
3653 {
3654         if (buffer_kbs > 0)
3655                 st_fixed_buffer_size = buffer_kbs * ST_KILOBYTE;
3656         if (max_sg_segs >= ST_FIRST_SG)
3657                 st_max_sg_segs = max_sg_segs;
3658 }
3659
3660 #ifndef MODULE
3661 /* Set the boot options. Syntax is defined in Documenation/scsi/st.txt.
3662  */
3663 static int __init st_setup(char *str)
3664 {
3665         int i, len, ints[5];
3666         char *stp;
3667
3668         stp = get_options(str, ARRAY_SIZE(ints), ints);
3669
3670         if (ints[0] > 0) {
3671                 for (i = 0; i < ints[0] && i < ARRAY_SIZE(parms); i++)
3672                         if (parms[i].val)
3673                                 *parms[i].val = ints[i + 1];
3674         } else {
3675                 while (stp != NULL) {
3676                         for (i = 0; i < ARRAY_SIZE(parms); i++) {
3677                                 len = strlen(parms[i].name);
3678                                 if (!strncmp(stp, parms[i].name, len) &&
3679                                     (*(stp + len) == ':' || *(stp + len) == '=')) {
3680                                         if (parms[i].val)
3681                                                 *parms[i].val =
3682                                                         simple_strtoul(stp + len + 1, NULL, 0);
3683                                         else
3684                                                 printk(KERN_WARNING "st: Obsolete parameter %s\n",
3685                                                        parms[i].name);
3686                                         break;
3687                                 }
3688                         }
3689                         if (i >= sizeof(parms) / sizeof(struct st_dev_parm))
3690                                  printk(KERN_WARNING "st: invalid parameter in '%s'\n",
3691                                         stp);
3692                         stp = strchr(stp, ',');
3693                         if (stp)
3694                                 stp++;
3695                 }
3696         }
3697
3698         validate_options();
3699
3700         return 1;
3701 }
3702
3703 __setup("st=", st_setup);
3704
3705 #endif
3706
3707 static struct file_operations st_fops =
3708 {
3709         .owner =        THIS_MODULE,
3710         .read =         st_read,
3711         .write =        st_write,
3712         .ioctl =        st_ioctl,
3713         .open =         st_open,
3714         .flush =        st_flush,
3715         .release =      st_release,
3716 };
3717
3718 static int st_probe(struct device *dev)
3719 {
3720         struct scsi_device *SDp = to_scsi_device(dev);
3721         struct gendisk *disk = NULL;
3722         struct cdev *cdev = NULL;
3723         Scsi_Tape *tpnt = NULL;
3724         ST_mode *STm;
3725         ST_partstat *STps;
3726         ST_buffer *buffer;
3727         int i, j, mode, dev_num, error;
3728         char *stp;
3729         u64 bounce_limit;
3730
3731         if (SDp->type != TYPE_TAPE)
3732                 return -ENODEV;
3733         if ((stp = st_incompatible(SDp))) {
3734                 printk(KERN_INFO
3735                        "st: Found incompatible tape at scsi%d, channel %d, id %d, lun %d\n",
3736                        SDp->host->host_no, SDp->channel, SDp->id, SDp->lun);
3737                 printk(KERN_INFO "st: The suggested driver is %s.\n", stp);
3738                 return -ENODEV;
3739         }
3740
3741         i = SDp->host->sg_tablesize;
3742         if (st_max_sg_segs < i)
3743                 i = st_max_sg_segs;
3744         buffer = new_tape_buffer(TRUE, (SDp->host)->unchecked_isa_dma, i);
3745         if (buffer == NULL) {
3746                 printk(KERN_ERR "st: Can't allocate new tape buffer. Device not attached.\n");
3747                 goto out;
3748         }
3749
3750         disk = alloc_disk(1);
3751         if (!disk) {
3752                 printk(KERN_ERR "st: out of memory. Device not attached.\n");
3753                 goto out_buffer_free;
3754         }
3755
3756         write_lock(&st_dev_arr_lock);
3757         if (st_nr_dev >= st_dev_max) {
3758                 Scsi_Tape **tmp_da;
3759                 int tmp_dev_max;
3760
3761                 tmp_dev_max = max(st_nr_dev * 2, 8);
3762                 if (tmp_dev_max > ST_MAX_TAPES)
3763                         tmp_dev_max = ST_MAX_TAPES;
3764                 if (tmp_dev_max <= st_nr_dev) {
3765                         write_unlock(&st_dev_arr_lock);
3766                         printk(KERN_ERR "st: Too many tape devices (max. %d).\n",
3767                                ST_MAX_TAPES);
3768                         goto out_put_disk;
3769                 }
3770
3771                 tmp_da = kmalloc(tmp_dev_max * sizeof(Scsi_Tape *), GFP_ATOMIC);
3772                 if (tmp_da == NULL) {
3773                         write_unlock(&st_dev_arr_lock);
3774                         printk(KERN_ERR "st: Can't extend device array.\n");
3775                         goto out_put_disk;
3776                 }
3777
3778                 memset(tmp_da, 0, tmp_dev_max * sizeof(Scsi_Tape *));
3779                 if (scsi_tapes != NULL) {
3780                         memcpy(tmp_da, scsi_tapes,
3781                                st_dev_max * sizeof(Scsi_Tape *));
3782                         kfree(scsi_tapes);
3783                 }
3784                 scsi_tapes = tmp_da;
3785
3786                 st_dev_max = tmp_dev_max;
3787         }
3788
3789         for (i = 0; i < st_dev_max; i++)
3790                 if (scsi_tapes[i] == NULL)
3791                         break;
3792         if (i >= st_dev_max)
3793                 panic("scsi_devices corrupt (st)");
3794
3795         tpnt = kmalloc(sizeof(Scsi_Tape), GFP_ATOMIC);
3796         if (tpnt == NULL) {
3797                 write_unlock(&st_dev_arr_lock);
3798                 printk(KERN_ERR "st: Can't allocate device descriptor.\n");
3799                 goto out_put_disk;
3800         }
3801         memset(tpnt, 0, sizeof(Scsi_Tape));
3802         tpnt->disk = disk;
3803         sprintf(disk->disk_name, "st%d", i);
3804         disk->private_data = &tpnt->driver;
3805         disk->queue = SDp->request_queue;
3806         tpnt->driver = &st_template;
3807         scsi_tapes[i] = tpnt;
3808         dev_num = i;
3809
3810         tpnt->device = SDp;
3811         if (SDp->scsi_level <= 2)
3812                 tpnt->tape_type = MT_ISSCSI1;
3813         else
3814                 tpnt->tape_type = MT_ISSCSI2;
3815
3816         tpnt->buffer = buffer;
3817
3818         tpnt->inited = 0;
3819         tpnt->dirty = 0;
3820         tpnt->in_use = 0;
3821         tpnt->drv_buffer = 1;   /* Try buffering if no mode sense */
3822         tpnt->restr_dma = (SDp->host)->unchecked_isa_dma;
3823         tpnt->use_pf = (SDp->scsi_level >= SCSI_2);
3824         tpnt->density = 0;
3825         tpnt->do_auto_lock = ST_AUTO_LOCK;
3826         tpnt->can_bsr = (SDp->scsi_level > 2 ? 1 : ST_IN_FILE_POS); /* BSR mandatory in SCSI3 */
3827         tpnt->can_partitions = 0;
3828         tpnt->two_fm = ST_TWO_FM;
3829         tpnt->fast_mteom = ST_FAST_MTEOM;
3830         tpnt->scsi2_logical = ST_SCSI2LOGICAL;
3831         tpnt->immediate = ST_NOWAIT;
3832         tpnt->default_drvbuffer = 0xff;         /* No forced buffering */
3833         tpnt->partition = 0;
3834         tpnt->new_partition = 0;
3835         tpnt->nbr_partitions = 0;
3836         tpnt->device->timeout = ST_TIMEOUT;
3837         tpnt->long_timeout = ST_LONG_TIMEOUT;
3838         tpnt->try_dio = try_direct_io && !SDp->host->unchecked_isa_dma;
3839
3840         bounce_limit = scsi_calculate_bounce_limit(SDp->host) >> PAGE_SHIFT;
3841         if (bounce_limit > ULONG_MAX)
3842                 bounce_limit = ULONG_MAX;
3843         tpnt->max_pfn = bounce_limit;
3844
3845         for (i = 0; i < ST_NBR_MODES; i++) {
3846                 STm = &(tpnt->modes[i]);
3847                 STm->defined = FALSE;
3848                 STm->sysv = ST_SYSV;
3849                 STm->defaults_for_writes = 0;
3850                 STm->do_async_writes = ST_ASYNC_WRITES;
3851                 STm->do_buffer_writes = ST_BUFFER_WRITES;
3852                 STm->do_read_ahead = ST_READ_AHEAD;
3853                 STm->default_compression = ST_DONT_TOUCH;
3854                 STm->default_blksize = (-1);    /* No forced size */
3855                 STm->default_density = (-1);    /* No forced density */
3856         }
3857
3858         for (i = 0; i < ST_NBR_PARTITIONS; i++) {
3859                 STps = &(tpnt->ps[i]);
3860                 STps->rw = ST_IDLE;
3861                 STps->eof = ST_NOEOF;
3862                 STps->at_sm = 0;
3863                 STps->last_block_valid = FALSE;
3864                 STps->drv_block = (-1);
3865                 STps->drv_file = (-1);
3866         }
3867
3868         tpnt->current_mode = 0;
3869         tpnt->modes[0].defined = TRUE;
3870
3871         tpnt->density_changed = tpnt->compression_changed =
3872             tpnt->blksize_changed = FALSE;
3873         init_MUTEX(&tpnt->lock);
3874
3875         st_nr_dev++;
3876         write_unlock(&st_dev_arr_lock);
3877
3878         for (mode = 0; mode < ST_NBR_MODES; ++mode) {
3879                 STm = &(tpnt->modes[mode]);
3880                 for (j=0; j < 2; j++) {
3881                         cdev = cdev_alloc();
3882                         if (!cdev) {
3883                                 printk(KERN_ERR
3884                                        "st%d: out of memory. Device not attached.\n",
3885                                        dev_num);
3886                                 goto out_free_tape;
3887                         }
3888                         cdev->owner = THIS_MODULE;
3889                         cdev->ops = &st_fops;
3890
3891                         error = cdev_add(cdev,
3892                                          MKDEV(SCSI_TAPE_MAJOR, TAPE_MINOR(dev_num, mode, j)),
3893                                          1);
3894                         if (error) {
3895                                 printk(KERN_ERR "st%d: Can't add %s-rewind mode %d\n",
3896                                        dev_num, j ? "non" : "auto", mode);
3897                                 printk(KERN_ERR "st%d: Device not attached.\n", dev_num);
3898                                 goto out_free_tape;
3899                         }
3900                         STm->cdevs[j] = cdev;
3901
3902                 }
3903                 do_create_class_files(tpnt, dev_num, mode);
3904         }
3905
3906         for (mode = 0; mode < ST_NBR_MODES; ++mode) {
3907                 /* Make sure that the minor numbers corresponding to the four
3908                    first modes always get the same names */
3909                 i = mode << (4 - ST_NBR_MODE_BITS);
3910                 /*  Rewind entry  */
3911                 devfs_mk_cdev(MKDEV(SCSI_TAPE_MAJOR, TAPE_MINOR(dev_num, mode, 0)),
3912                               S_IFCHR | S_IRUGO | S_IWUGO,
3913                               "%s/mt%s", SDp->devfs_name, st_formats[i]);
3914                 /*  No-rewind entry  */
3915                 devfs_mk_cdev(MKDEV(SCSI_TAPE_MAJOR, TAPE_MINOR(dev_num, mode, 1)),
3916                               S_IFCHR | S_IRUGO | S_IWUGO,
3917                               "%s/mt%sn", SDp->devfs_name, st_formats[i]);
3918         }
3919         disk->number = devfs_register_tape(SDp->devfs_name);
3920
3921         printk(KERN_WARNING
3922         "Attached scsi tape %s at scsi%d, channel %d, id %d, lun %d\n",
3923                tape_name(tpnt), SDp->host->host_no, SDp->channel, SDp->id, SDp->lun);
3924         printk(KERN_WARNING "%s: try direct i/o: %s (alignment %d B), max page reachable by HBA %lu\n",
3925                tape_name(tpnt), tpnt->try_dio ? "yes" : "no",
3926                queue_dma_alignment(SDp->request_queue) + 1, tpnt->max_pfn);
3927
3928         return 0;
3929
3930 out_free_tape:
3931         for (mode=0; mode < ST_NBR_MODES; mode++) {
3932                 STm = &(tpnt->modes[mode]);
3933                 sysfs_remove_link(&tpnt->device->sdev_gendev.kobj,
3934                                   "tape");
3935                 for (j=0; j < 2; j++) {
3936                         if (STm->cdevs[j]) {
3937                                 if (cdev == STm->cdevs[j])
3938                                         cdev = NULL;
3939                                 class_simple_device_remove(MKDEV(SCSI_TAPE_MAJOR,
3940                                                                  TAPE_MINOR(i, mode, j)));
3941                                 cdev_del(STm->cdevs[j]);
3942                         }
3943                 }
3944         }
3945         if (cdev)
3946                 cdev_del(cdev);
3947         write_lock(&st_dev_arr_lock);
3948         scsi_tapes[dev_num] = NULL;
3949         st_nr_dev--;
3950         write_unlock(&st_dev_arr_lock);
3951 out_put_disk:
3952         put_disk(disk);
3953         if (tpnt)
3954                 kfree(tpnt);
3955 out_buffer_free:
3956         kfree(buffer);
3957 out:
3958         return -ENODEV;
3959 };
3960
3961
3962 static int st_remove(struct device *dev)
3963 {
3964         Scsi_Device *SDp = to_scsi_device(dev);
3965         Scsi_Tape *tpnt;
3966         int i, j, mode;
3967
3968         write_lock(&st_dev_arr_lock);
3969         for (i = 0; i < st_dev_max; i++) {
3970                 tpnt = scsi_tapes[i];
3971                 if (tpnt != NULL && tpnt->device == SDp) {
3972                         scsi_tapes[i] = NULL;
3973                         st_nr_dev--;
3974                         write_unlock(&st_dev_arr_lock);
3975                         devfs_unregister_tape(tpnt->disk->number);
3976                         sysfs_remove_link(&tpnt->device->sdev_gendev.kobj,
3977                                           "tape");
3978                         for (mode = 0; mode < ST_NBR_MODES; ++mode) {
3979                                 j = mode << (4 - ST_NBR_MODE_BITS);
3980                                 devfs_remove("%s/mt%s", SDp->devfs_name, st_formats[j]);
3981                                 devfs_remove("%s/mt%sn", SDp->devfs_name, st_formats[j]);
3982                                 for (j=0; j < 2; j++) {
3983                                         class_simple_device_remove(MKDEV(SCSI_TAPE_MAJOR,
3984                                                                          TAPE_MINOR(i, mode, j)));
3985                                         cdev_del(tpnt->modes[mode].cdevs[j]);
3986                                         tpnt->modes[mode].cdevs[j] = NULL;
3987                                 }
3988                         }
3989                         tpnt->device = NULL;
3990
3991                         if (tpnt->buffer) {
3992                                 tpnt->buffer->orig_frp_segs = 0;
3993                                 normalize_buffer(tpnt->buffer);
3994                                 kfree(tpnt->buffer);
3995                         }
3996                         put_disk(tpnt->disk);
3997                         kfree(tpnt);
3998                         return 0;
3999                 }
4000         }
4001
4002         write_unlock(&st_dev_arr_lock);
4003         return 0;
4004 }
4005
4006 static void st_intr(struct scsi_cmnd *SCpnt)
4007 {
4008         scsi_io_completion(SCpnt, (SCpnt->result ? 0: SCpnt->bufflen), 1);
4009 }
4010
4011 /*
4012  * st_init_command: only called via the scsi_cmd_ioctl (block SG_IO)
4013  * interface for REQ_BLOCK_PC commands.
4014  */
4015 static int st_init_command(struct scsi_cmnd *SCpnt)
4016 {
4017         struct request *rq;
4018
4019         if (!(SCpnt->request->flags & REQ_BLOCK_PC))
4020                 return 0;
4021
4022         rq = SCpnt->request;
4023         if (sizeof(rq->cmd) > sizeof(SCpnt->cmnd))
4024                 return 0;
4025
4026         memcpy(SCpnt->cmnd, rq->cmd, sizeof(SCpnt->cmnd));
4027
4028         if (rq_data_dir(rq) == WRITE)
4029                 SCpnt->sc_data_direction = DMA_TO_DEVICE;
4030         else if (rq->data_len)
4031                 SCpnt->sc_data_direction = DMA_FROM_DEVICE;
4032         else
4033                 SCpnt->sc_data_direction = DMA_NONE;
4034
4035         SCpnt->timeout_per_command = rq->timeout;
4036         SCpnt->transfersize = rq->data_len;
4037         SCpnt->done = st_intr;
4038         return 1;
4039 }
4040
4041 static int __init init_st(void)
4042 {
4043         validate_options();
4044
4045         printk(KERN_INFO
4046                 "st: Version %s, fixed bufsize %d, s/g segs %d\n",
4047                 verstr, st_fixed_buffer_size, st_max_sg_segs);
4048
4049         st_sysfs_class = class_simple_create(THIS_MODULE, "scsi_tape");
4050         if (IS_ERR(st_sysfs_class)) {
4051                 st_sysfs_class = NULL;
4052                 printk(KERN_ERR "Unable create sysfs class for SCSI tapes\n");
4053                 return 1;
4054         }
4055
4056         if (!register_chrdev_region(MKDEV(SCSI_TAPE_MAJOR, 0),
4057                                     ST_MAX_TAPE_ENTRIES, "st")) {
4058                 if (scsi_register_driver(&st_template.gendrv) == 0) {
4059                         do_create_driverfs_files();
4060                         return 0;
4061                 }
4062                 if (st_sysfs_class)
4063                         class_simple_destroy(st_sysfs_class);           
4064                 unregister_chrdev_region(MKDEV(SCSI_TAPE_MAJOR, 0),
4065
4066                                          ST_MAX_TAPE_ENTRIES);
4067         }
4068
4069         printk(KERN_ERR "Unable to get major %d for SCSI tapes\n", SCSI_TAPE_MAJOR);
4070         return 1;
4071 }
4072
4073 static void __exit exit_st(void)
4074 {
4075         if (st_sysfs_class)
4076                 class_simple_destroy(st_sysfs_class);
4077         st_sysfs_class = NULL;
4078         do_remove_driverfs_files();
4079         scsi_unregister_driver(&st_template.gendrv);
4080         unregister_chrdev_region(MKDEV(SCSI_TAPE_MAJOR, 0),
4081                                  ST_MAX_TAPE_ENTRIES);
4082         kfree(scsi_tapes);
4083         printk(KERN_INFO "st: Unloaded.\n");
4084 }
4085
4086 module_init(init_st);
4087 module_exit(exit_st);
4088
4089
4090 /* The sysfs driver interface. Read-only at the moment */
4091 static ssize_t st_try_direct_io_show(struct device_driver *ddp, char *buf)
4092 {
4093         return snprintf(buf, PAGE_SIZE, "%d\n", try_direct_io);
4094 }
4095 static DRIVER_ATTR(try_direct_io, S_IRUGO, st_try_direct_io_show, NULL);
4096
4097 static ssize_t st_fixed_buffer_size_show(struct device_driver *ddp, char *buf)
4098 {
4099         return snprintf(buf, PAGE_SIZE, "%d\n", st_fixed_buffer_size);
4100 }
4101 static DRIVER_ATTR(fixed_buffer_size, S_IRUGO, st_fixed_buffer_size_show, NULL);
4102
4103 static ssize_t st_max_sg_segs_show(struct device_driver *ddp, char *buf)
4104 {
4105         return snprintf(buf, PAGE_SIZE, "%d\n", st_max_sg_segs);
4106 }
4107 static DRIVER_ATTR(max_sg_segs, S_IRUGO, st_max_sg_segs_show, NULL);
4108
4109 static ssize_t st_version_show(struct device_driver *ddd, char *buf)
4110 {
4111         return snprintf(buf, PAGE_SIZE, "[%s]\n", verstr);
4112 }
4113 static DRIVER_ATTR(version, S_IRUGO, st_version_show, NULL);
4114
4115 static void do_create_driverfs_files(void)
4116 {
4117         struct device_driver *driverfs = &st_template.gendrv;
4118
4119         driver_create_file(driverfs, &driver_attr_try_direct_io);
4120         driver_create_file(driverfs, &driver_attr_fixed_buffer_size);
4121         driver_create_file(driverfs, &driver_attr_max_sg_segs);
4122         driver_create_file(driverfs, &driver_attr_version);
4123 }
4124
4125 static void do_remove_driverfs_files(void)
4126 {
4127         struct device_driver *driverfs = &st_template.gendrv;
4128
4129         driver_remove_file(driverfs, &driver_attr_version);
4130         driver_remove_file(driverfs, &driver_attr_max_sg_segs);
4131         driver_remove_file(driverfs, &driver_attr_fixed_buffer_size);
4132         driver_remove_file(driverfs, &driver_attr_try_direct_io);
4133 }
4134
4135
4136 /* The sysfs simple class interface */
4137 static ssize_t st_defined_show(struct class_device *class_dev, char *buf)
4138 {
4139         ST_mode *STm = (ST_mode *)class_get_devdata(class_dev);
4140         ssize_t l = 0;
4141
4142         l = snprintf(buf, PAGE_SIZE, "%d\n", STm->defined);
4143         return l;
4144 }
4145
4146 CLASS_DEVICE_ATTR(defined, S_IRUGO, st_defined_show, NULL);
4147
4148 static ssize_t st_defblk_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->default_blksize);
4154         return l;
4155 }
4156
4157 CLASS_DEVICE_ATTR(default_blksize, S_IRUGO, st_defblk_show, NULL);
4158
4159 static ssize_t st_defdensity_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         char *fmt;
4164
4165         fmt = STm->default_density >= 0 ? "0x%02x\n" : "%d\n";
4166         l = snprintf(buf, PAGE_SIZE, fmt, STm->default_density);
4167         return l;
4168 }
4169
4170 CLASS_DEVICE_ATTR(default_density, S_IRUGO, st_defdensity_show, NULL);
4171
4172 static ssize_t st_defcompression_show(struct class_device *class_dev, char *buf)
4173 {
4174         ST_mode *STm = (ST_mode *)class_get_devdata(class_dev);
4175         ssize_t l = 0;
4176
4177         l = snprintf(buf, PAGE_SIZE, "%d\n", STm->default_compression - 1);
4178         return l;
4179 }
4180
4181 CLASS_DEVICE_ATTR(default_compression, S_IRUGO, st_defcompression_show, NULL);
4182
4183 static void do_create_class_files(Scsi_Tape *STp, int dev_num, int mode)
4184 {
4185         int i, rew, error;
4186         char name[10];
4187         struct class_device *st_class_member;
4188
4189         if (!st_sysfs_class)
4190                 return;
4191
4192         for (rew=0; rew < 2; rew++) {
4193                 /* Make sure that the minor numbers corresponding to the four
4194                    first modes always get the same names */
4195                 i = mode << (4 - ST_NBR_MODE_BITS);
4196                 snprintf(name, 10, "%s%s%s", rew ? "n" : "",
4197                          STp->disk->disk_name, st_formats[i]);
4198                 st_class_member =
4199                         class_simple_device_add(st_sysfs_class,
4200                                                 MKDEV(SCSI_TAPE_MAJOR,
4201                                                       TAPE_MINOR(dev_num, mode, rew)),
4202                                                 &STp->device->sdev_gendev, "%s", name);
4203                 if (IS_ERR(st_class_member)) {
4204                         printk(KERN_WARNING "st%d: class_simple_device_add failed\n",
4205                                dev_num);
4206                         goto out;
4207                 }
4208                 class_set_devdata(st_class_member, &STp->modes[mode]);
4209
4210                 class_device_create_file(st_class_member,
4211                                          &class_device_attr_defined);
4212                 class_device_create_file(st_class_member,
4213                                          &class_device_attr_default_blksize);
4214                 class_device_create_file(st_class_member,
4215                                          &class_device_attr_default_density);
4216                 class_device_create_file(st_class_member,
4217                                          &class_device_attr_default_compression);
4218                 if (mode == 0 && rew == 0) {
4219                         error = sysfs_create_link(&STp->device->sdev_gendev.kobj,
4220                                                   &st_class_member->kobj,
4221                                                   "tape");
4222                         if (error) {
4223                                 printk(KERN_ERR
4224                                        "st%d: Can't create sysfs link from SCSI device.\n",
4225                                        dev_num);
4226                         }
4227                 }
4228         }
4229  out:
4230         return;
4231 }
4232
4233
4234 /* Pin down user pages and put them into a scatter gather list. Returns <= 0 if
4235    - mapping of all pages not successful
4236    - any page is above max_pfn
4237    (i.e., either completely successful or fails)
4238 */
4239 static int st_map_user_pages(struct scatterlist *sgl, const unsigned int max_pages, 
4240                              unsigned long uaddr, size_t count, int rw,
4241                              unsigned long max_pfn)
4242 {
4243         int i, nr_pages;
4244
4245         nr_pages = sgl_map_user_pages(sgl, max_pages, uaddr, count, rw);
4246         if (nr_pages <= 0)
4247                 return nr_pages;
4248
4249         for (i=0; i < nr_pages; i++) {
4250                 if (page_to_pfn(sgl[i].page) > max_pfn)
4251                         goto out_unmap;
4252         }
4253         return nr_pages;
4254
4255  out_unmap:
4256         sgl_unmap_user_pages(sgl, nr_pages, FALSE);
4257         return 0;
4258 }
4259
4260
4261 /* The following functions may be useful for a larger audience. */
4262 static int sgl_map_user_pages(struct scatterlist *sgl, const unsigned int max_pages, 
4263                               unsigned long uaddr, size_t count, int rw)
4264 {
4265         int res, i, j;
4266         unsigned int nr_pages;
4267         struct page **pages;
4268
4269         nr_pages = ((uaddr & ~PAGE_MASK) + count + ~PAGE_MASK) >> PAGE_SHIFT;
4270
4271         /* User attempted Overflow! */
4272         if ((uaddr + count) < uaddr)
4273                 return -EINVAL;
4274
4275         /* Too big */
4276         if (nr_pages > max_pages)
4277                 return -ENOMEM;
4278
4279         /* Hmm? */
4280         if (count == 0)
4281                 return 0;
4282
4283         if ((pages = kmalloc(max_pages * sizeof(*pages), GFP_KERNEL)) == NULL)
4284                 return -ENOMEM;
4285
4286         /* Try to fault in all of the necessary pages */
4287         down_read(&current->mm->mmap_sem);
4288         /* rw==READ means read from drive, write into memory area */
4289         res = get_user_pages(
4290                 current,
4291                 current->mm,
4292                 uaddr,
4293                 nr_pages,
4294                 rw == READ,
4295                 0, /* don't force */
4296                 pages,
4297                 NULL);
4298         up_read(&current->mm->mmap_sem);
4299
4300         /* Errors and no page mapped should return here */
4301         if (res < nr_pages)
4302                 goto out_unmap;
4303
4304         for (i=0; i < nr_pages; i++) {
4305                 /* FIXME: flush superflous for rw==READ,
4306                  * probably wrong function for rw==WRITE
4307                  */
4308                 flush_dcache_page(pages[i]);
4309         }
4310
4311         /* Populate the scatter/gather list */
4312         sgl[0].page = pages[0]; 
4313         sgl[0].offset = uaddr & ~PAGE_MASK;
4314         if (nr_pages > 1) {
4315                 sgl[0].length = PAGE_SIZE - sgl[0].offset;
4316                 count -= sgl[0].length;
4317                 for (i=1; i < nr_pages ; i++) {
4318                         sgl[i].offset = 0;
4319                         sgl[i].page = pages[i]; 
4320                         sgl[i].length = count < PAGE_SIZE ? count : PAGE_SIZE;
4321                         count -= PAGE_SIZE;
4322                 }
4323         }
4324         else {
4325                 sgl[0].length = count;
4326         }
4327
4328         kfree(pages);
4329         return nr_pages;
4330
4331  out_unmap:
4332         if (res > 0) {
4333                 for (j=0; j < res; j++)
4334                         page_cache_release(pages[j]);
4335         }
4336         kfree(pages);
4337         return res;
4338 }
4339
4340
4341 /* And unmap them... */
4342 static int sgl_unmap_user_pages(struct scatterlist *sgl, const unsigned int nr_pages,
4343                                 int dirtied)
4344 {
4345         int i;
4346
4347         for (i=0; i < nr_pages; i++) {
4348                 if (dirtied && !PageReserved(sgl[i].page))
4349                         SetPageDirty(sgl[i].page);
4350                 /* FIXME: cache flush missing for rw==READ
4351                  * FIXME: call the correct reference counting function
4352                  */
4353                 page_cache_release(sgl[i].page);
4354         }
4355
4356         return 0;
4357 }