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