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