]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/dev.c
- Add Date, Job, level to updates to .bsr file in
[bacula/bacula] / bacula / src / stored / dev.c
1 /*
2  *
3  *   dev.c  -- low level operations on device (storage device)
4  *
5  *              Kern Sibbald, MM
6  *
7  *     NOTE!!!! None of these routines are reentrant. You must
8  *        use lock_device() and unlock_device() at a higher level,
9  *        or use the xxx_device() equivalents.  By moving the
10  *        thread synchronization to a higher level, we permit
11  *        the higher level routines to "seize" the device and
12  *        to carry out operations without worrying about who
13  *        set what lock (i.e. race conditions).
14  *
15  *     Note, this is the device dependent code, and my have
16  *           to be modified for each system, but is meant to
17  *           be as "generic" as possible.
18  *
19  *     The purpose of this code is to develop a SIMPLE Storage
20  *     daemon. More complicated coding (double buffering, writer
21  *     thread, ...) is left for a later version.
22  *
23  *     Unfortunately, I have had to add more and more complication
24  *     to this code. This was not foreseen as noted above, and as
25  *     a consequence has lead to something more contorted than is
26  *     really necessary -- KES.  Note, this contortion has been
27  *     corrected to a large extent by a rewrite (Apr MMI).
28  *
29  *   Version $Id$
30  */
31 /*
32    Copyright (C) 2000-2005 Kern Sibbald
33
34    This program is free software; you can redistribute it and/or
35    modify it under the terms of the GNU General Public License
36    version 2 as ammended with additional clauses defined in the
37    file LICENSE in the main source directory.
38
39    This program is distributed in the hope that it will be useful,
40    but WITHOUT ANY WARRANTY; without even the implied warranty of
41    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
42    the file LICENSE for additional details.
43
44  */
45
46 /*
47  * Handling I/O errors and end of tape conditions are a bit tricky.
48  * This is how it is currently done when writting.
49  * On either an I/O error or end of tape,
50  * we will stop writing on the physical device (no I/O recovery is
51  * attempted at least in this daemon). The state flag will be sent
52  * to include ST_EOT, which is ephimeral, and ST_WEOT, which is
53  * persistent. Lots of routines clear ST_EOT, but ST_WEOT is
54  * cleared only when the problem goes away.  Now when ST_WEOT
55  * is set all calls to write_block_to_device() call the fix_up
56  * routine. In addition, all threads are blocked
57  * from writing on the tape by calling lock_dev(), and thread other
58  * than the first thread to hit the EOT will block on a condition
59  * variable. The first thread to hit the EOT will continue to
60  * be able to read and write the tape (he sort of tunnels through
61  * the locking mechanism -- see lock_dev() for details).
62  *
63  * Now presumably somewhere higher in the chain of command
64  * (device.c), someone will notice the EOT condition and
65  * get a new tape up, get the tape label read, and mark
66  * the label for rewriting. Then this higher level routine
67  * will write the unwritten buffer to the new volume.
68  * Finally, he will release
69  * any blocked threads by doing a broadcast on the condition
70  * variable.  At that point, we should be totally back in
71  * business with no lost data.
72  */
73
74
75 #include "bacula.h"
76 #include "stored.h"
77
78 #ifndef O_NONBLOCK 
79 #define O_NONBLOCK 0
80 #endif
81
82 /* Functions in dvd.c */ 
83 void get_filename(DEVICE *dev, char *VolName, POOL_MEM& archive_name);
84 void update_free_space_dev(DEVICE* dev);
85
86
87 /* Forward referenced functions */
88 void set_os_device_parameters(DEVICE *dev);
89 static bool dev_get_os_pos(DEVICE *dev, struct mtget *mt_stat);
90 static void open_tape_device(DEVICE *dev, int mode);
91 static void open_file_device(DEVICE *dev, int mode);
92
93 /*
94  * Allocate and initialize the DEVICE structure
95  * Note, if dev is non-NULL, it is already allocated,
96  * thus we neither allocate it nor free it. This allows
97  * the caller to put the packet in shared memory.
98  *
99  *  Note, for a tape, the device->device_name is the device name
100  *     (e.g. /dev/nst0), and for a file, the device name
101  *     is the directory in which the file will be placed.
102  *
103  */
104 DEVICE *
105 init_dev(JCR *jcr, DEVRES *device)
106 {
107    struct stat statp;
108    bool tape, fifo;
109    int errstat;
110    DCR *dcr = NULL;
111    DEVICE *dev;
112
113    /* Check that device is available */
114    if (stat(device->device_name, &statp) < 0) {
115       berrno be;
116       Jmsg2(jcr, M_ERROR, 0, _("Unable to stat device %s: ERR=%s\n"), 
117          device->device_name, be.strerror());
118       return NULL;
119    }
120    
121    
122    tape = false;
123    fifo = false;
124    if (S_ISDIR(statp.st_mode)) {
125       tape = false;
126    } else if (S_ISCHR(statp.st_mode)) {
127       tape = true;
128    } else if (S_ISFIFO(statp.st_mode)) {
129       fifo = true;
130    } else if (!(device->cap_bits & CAP_REQMOUNT)) {
131       Jmsg2(jcr, M_ERROR, 0, _("%s is an unknown device type. Must be tape or directory. st_mode=%x\n"),
132          device->device_name, statp.st_mode);
133       return NULL;
134    }
135
136    dev = (DEVICE *)get_memory(sizeof(DEVICE));
137    memset(dev, 0, sizeof(DEVICE));
138    dev->state = ST_MALLOC;
139
140    /* Copy user supplied device parameters from Resource */
141    dev->dev_name = get_memory(strlen(device->device_name)+1);
142    pm_strcpy(dev->dev_name, device->device_name);
143    dev->prt_name = get_memory(strlen(device->device_name) + strlen(device->hdr.name) + 20);
144    /* We edit "Resource-name" (physical-name) */
145    Mmsg(dev->prt_name, "\"%s\" (%s)", device->hdr.name, device->device_name);
146    dev->capabilities = device->cap_bits;
147    dev->min_block_size = device->min_block_size;
148    dev->max_block_size = device->max_block_size;
149    dev->max_volume_size = device->max_volume_size;
150    dev->max_file_size = device->max_file_size;
151    dev->volume_capacity = device->volume_capacity;
152    dev->max_rewind_wait = device->max_rewind_wait;
153    dev->max_open_wait = device->max_open_wait;
154    dev->max_open_vols = device->max_open_vols;
155    dev->vol_poll_interval = device->vol_poll_interval;
156    dev->max_spool_size = device->max_spool_size;
157    dev->drive_index = device->drive_index;
158    dev->autoselect = device->autoselect;
159    if (tape) { /* No parts on tapes */
160       dev->max_part_size = 0;
161    }
162    else {
163       dev->max_part_size = device->max_part_size;
164    }
165    /* Sanity check */
166    if (dev->vol_poll_interval && dev->vol_poll_interval < 60) {
167       dev->vol_poll_interval = 60;
168    }
169    dev->device = device;
170
171    if (tape) {
172       dev->state |= ST_TAPE;
173    } else if (fifo) {
174       dev->state |= ST_FIFO;
175       dev->capabilities |= CAP_STREAM; /* set stream device */
176    } else {
177       dev->state |= ST_FILE;
178    }
179
180    /* If the device requires mount :
181     * - Check that the mount point is available 
182     * - Check that (un)mount commands are defined
183     */
184    if (dev->is_file() && device->cap_bits & CAP_REQMOUNT) {
185       if (stat(device->mount_point, &statp) < 0) {
186          berrno be;
187          dev->dev_errno = errno;
188          Jmsg2(jcr, M_ERROR, 0, _("Unable to stat mount point %s: ERR=%s\n"), 
189             device->mount_point, be.strerror());
190          return NULL;
191       }
192       if (!device->mount_command || !device->unmount_command) {
193          Jmsg0(jcr, M_ERROR_TERM, 0, _("Mount and unmount commands must defined for a device which requires mount.\n"));
194       }
195       if (!device->write_part_command) {
196          Jmsg0(jcr, M_ERROR_TERM, 0, _("Write part command must be defined for a device which requires mount.\n"));
197       }
198       dev->state |= ST_DVD;
199    }
200
201    if (dev->max_block_size > 1000000) {
202       Jmsg3(jcr, M_ERROR, 0, _("Block size %u on device %s is too large, using default %u\n"),
203          dev->max_block_size, dev->print_name(), DEFAULT_BLOCK_SIZE);
204       dev->max_block_size = 0;
205    }
206    if (dev->max_block_size % TAPE_BSIZE != 0) {
207       Jmsg2(jcr, M_WARNING, 0, _("Max block size %u not multiple of device %s block size.\n"),
208          dev->max_block_size, dev->print_name());
209    }
210
211    dev->errmsg = get_pool_memory(PM_EMSG);
212    *dev->errmsg = 0;
213
214    if ((errstat = pthread_mutex_init(&dev->mutex, NULL)) != 0) {
215       berrno be;
216       dev->dev_errno = errstat;
217       Mmsg1(dev->errmsg, _("Unable to init mutex: ERR=%s\n"), be.strerror(errstat));
218       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
219    }
220    if ((errstat = pthread_cond_init(&dev->wait, NULL)) != 0) {
221       berrno be;
222       dev->dev_errno = errstat;
223       Mmsg1(dev->errmsg, _("Unable to init cond variable: ERR=%s\n"), be.strerror(errstat));
224       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
225    }
226    if ((errstat = pthread_cond_init(&dev->wait_next_vol, NULL)) != 0) {
227       berrno be;
228       dev->dev_errno = errstat;
229       Mmsg1(dev->errmsg, _("Unable to init cond variable: ERR=%s\n"), be.strerror(errstat));
230       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
231    }
232    if ((errstat = pthread_mutex_init(&dev->spool_mutex, NULL)) != 0) {
233       berrno be;
234       dev->dev_errno = errstat;
235       Mmsg1(dev->errmsg, _("Unable to init mutex: ERR=%s\n"), be.strerror(errstat));
236       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
237    }
238    if ((errstat = rwl_init(&dev->lock)) != 0) {
239       berrno be;
240       dev->dev_errno = errstat;
241       Mmsg1(dev->errmsg, _("Unable to init mutex: ERR=%s\n"), be.strerror(errstat));
242       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
243    }
244
245    dev->fd = -1;
246    dev->attached_dcrs = New(dlist(dcr, &dcr->dev_link));
247    Dmsg2(29, "init_dev: tape=%d dev_name=%s\n", dev->is_tape(), dev->dev_name);
248    
249    return dev;
250 }
251
252 /*
253  * Open the device with the operating system and
254  * initialize buffer pointers.
255  *
256  * Returns:  -1  on error
257  *           fd  on success
258  *
259  * Note, for a tape, the VolName is the name we give to the
260  *    volume (not really used here), but for a file, the
261  *    VolName represents the name of the file to be created/opened.
262  *    In the case of a file, the full name is the device name
263  *    (archive_name) with the VolName concatenated.
264  */
265 int
266 DEVICE::open(char *VolName, int mode)
267 {
268    if (is_open()) {
269       if (openmode == mode) {
270          return fd;
271       } else {
272         ::close(fd); /* use system close so correct mode will be used on open */
273       }
274    }
275    if (VolName) {
276       bstrncpy(VolCatInfo.VolCatName, VolName, sizeof(VolCatInfo.VolCatName));
277    } else {
278       VolCatInfo.VolCatName[0] = 0;
279    }
280
281    Dmsg3(29, "open dev: tape=%d dev_name=%s vol=%s\n", is_tape(),
282          dev_name, VolCatInfo.VolCatName);
283    state &= ~(ST_LABEL|ST_APPEND|ST_READ|ST_EOT|ST_WEOT|ST_EOF);
284    label_type = B_BACULA_LABEL;
285    if (is_tape() || is_fifo()) {
286       open_tape_device(this, mode);
287    } else {
288       open_file_device(this, mode);
289    }
290    return fd;
291 }
292
293 static void open_tape_device(DEVICE *dev, int mode) 
294 {
295    int nonblocking = 0;;
296    dev->file_size = 0;
297    int timeout;
298    int ioerrcnt = 10;
299    Dmsg0(29, "open dev: device is tape\n");
300
301    if (mode == OPEN_READ_WRITE) {
302       dev->mode = O_RDWR | O_BINARY;
303    } else if (mode == OPEN_READ_ONLY) {
304       dev->mode = O_RDONLY | O_BINARY;
305    } else if (mode == OPEN_WRITE_ONLY) {
306       dev->mode = O_WRONLY | O_BINARY;
307    } else {
308       Emsg0(M_ABORT, 0, _("Illegal mode given to open dev.\n"));
309    }
310    timeout = dev->max_open_wait;
311    errno = 0;
312    if (dev->open_nowait) {
313        /* Set wait counters to zero for no wait */
314        timeout = ioerrcnt = 0;
315        /* Open drive in non-block mode */
316        nonblocking = O_NONBLOCK;
317    }
318    if (dev->is_fifo() && timeout) {
319       /* Set open timer */
320       dev->tid = start_thread_timer(pthread_self(), timeout);
321    }
322    /* If busy retry each second for max_open_wait seconds */
323 open_again:
324    Dmsg1(500, "Try open %s\n", dev->dev_name);
325    while ((dev->fd = open(dev->dev_name, dev->mode, MODE_RW+nonblocking)) < 0) {
326       berrno be;
327       Dmsg2(500, "Open error errno=%d ERR=%s\n", errno, be.strerror());
328       if (errno == EINTR || errno == EAGAIN) {
329          Dmsg0(500, "Continue open\n");
330          continue;
331       }
332       /* Busy wait for specified time (default = 5 mins) */
333       if (errno == EBUSY && timeout-- > 0) {
334          Dmsg2(100, "Device %s busy. ERR=%s\n", dev->print_name(), be.strerror());
335          bmicrosleep(1, 0);
336          continue;
337       }
338       /* IO error (no volume) try 10 times every 6 seconds */
339       if (errno == EIO && ioerrcnt-- > 0) {
340          bmicrosleep(5, 0);
341          Dmsg0(500, "Continue open\n");
342          continue;
343       }
344       dev->dev_errno = errno;
345       Mmsg2(dev->errmsg, _("Unable to open device %s: ERR=%s\n"),
346             dev->print_name(), be.strerror(dev->dev_errno));
347       /* Stop any open timer we set */
348       if (dev->tid) {
349          stop_thread_timer(dev->tid);
350          dev->tid = 0;
351       }
352       Emsg0(M_FATAL, 0, dev->errmsg);
353       break;
354    }
355    if (dev->fd >= 0) {
356       /* If opened in non-block mode, close it an open it normally */
357       if (nonblocking) {
358          nonblocking = 0;
359          close(dev->fd);
360          goto open_again;
361       }
362       dev->openmode = mode;               /* save open mode */
363       dev->dev_errno = 0;
364       dev->state |= ST_OPENED;
365       dev->use_count = 1;
366       update_pos_dev(dev);                /* update position */
367       set_os_device_parameters(dev);      /* do system dependent stuff */
368       Dmsg0(500, "Open OK\n");
369    }
370    /* Stop any open() timer we started */
371    if (dev->tid) {
372       stop_thread_timer(dev->tid);
373       dev->tid = 0;
374    }
375    Dmsg1(29, "open dev: tape %d opened\n", dev->fd);
376 }
377
378 /*
379  * Open a file or DVD device
380  */
381 static void open_file_device(DEVICE *dev, int mode) 
382 {
383    POOL_MEM archive_name(PM_FNAME);
384    struct stat filestat;
385    /*
386     * Handle opening of File Archive (not a tape)
387     */     
388    if (dev->part == 0) {
389       dev->file_size = 0;
390    }
391    dev->part_size = 0;
392    
393    /* if num_parts has not been set, but VolCatInfo is available, copy
394     * it from the VolCatInfo.VolCatParts */
395    if (dev->num_parts < dev->VolCatInfo.VolCatParts) {
396       dev->num_parts = dev->VolCatInfo.VolCatParts;
397    }
398    
399    if (dev->VolCatInfo.VolCatName[0] == 0) {
400       Mmsg(dev->errmsg, _("Could not open file device %s. No Volume name given.\n"),
401          dev->print_name());
402       dev->fd = -1;
403       return;
404    }
405    get_filename(dev, dev->VolCatInfo.VolCatName, archive_name);
406
407    if (mount_dev(dev, 1) < 0) {
408       Mmsg(dev->errmsg, _("Could not mount device %s.\n"),
409            dev->print_name());
410       Emsg0(M_FATAL, 0, dev->errmsg);
411       dev->fd = -1;
412       return;
413    }
414          
415    Dmsg3(29, "open dev: device is %s (mode:%d)\n", dev->is_dvd()?"DVD":"disk",
416          archive_name.c_str(), mode);
417    dev->openmode = mode;
418    
419    /*
420     * If we are not trying to access the last part, set mode to 
421     *   OPEN_READ_ONLY as writing would be an error.
422     */
423    if (dev->part < dev->num_parts) {
424       mode = OPEN_READ_ONLY;
425    }
426    
427    if (mode == OPEN_READ_WRITE) {
428       dev->mode = O_CREAT | O_RDWR | O_BINARY;
429    } else if (mode == OPEN_READ_ONLY) {
430       dev->mode = O_RDONLY | O_BINARY;
431    } else if (mode == OPEN_WRITE_ONLY) {
432       dev->mode = O_WRONLY | O_BINARY;
433    } else {
434       Emsg0(M_ABORT, 0, _("Illegal mode given to open dev.\n"));
435    }
436    /* If creating file, give 0640 permissions */
437    Dmsg2(29, "open(%s, 0x%x, 0640)\n", archive_name.c_str(), dev->mode);
438    if ((dev->fd = open(archive_name.c_str(), dev->mode, 0640)) < 0) {
439       berrno be;
440       dev->dev_errno = errno;
441       Mmsg2(dev->errmsg, _("Could not open: %s, ERR=%s\n"), archive_name.c_str(), 
442             be.strerror());
443       Emsg0(M_FATAL, 0, dev->errmsg);
444    } else {
445       dev->dev_errno = 0;
446       dev->state |= ST_OPENED;
447       dev->use_count = 1;
448       update_pos_dev(dev);                /* update position */
449       if (fstat(dev->fd, &filestat) < 0) {
450          berrno be;
451          dev->dev_errno = errno;
452          Mmsg2(dev->errmsg, _("Could not fstat: %s, ERR=%s\n"), archive_name.c_str(), 
453                be.strerror());
454          Emsg0(M_FATAL, 0, dev->errmsg);
455       } else {
456          dev->part_size = filestat.st_size;
457       }
458    }
459    Dmsg5(29, "open dev: %s fd=%d opened, part=%d/%d, part_size=%u\n", 
460       dev->is_dvd()?"DVD":"disk", dev->fd, dev->part, dev->num_parts, 
461       dev->part_size);
462    if (dev->is_dvd() && (dev->mode != OPEN_READ_ONLY) && 
463        (dev->free_space_errno == 0 || dev->num_parts == dev->part)) {
464       update_free_space_dev(dev);
465    }
466 }
467
468 #ifdef debug_tracing
469 #undef rewind_dev
470 bool _rewind_dev(char *file, int line, DEVICE *dev)
471 {
472    Dmsg2(100, "rewind_dev called from %s:%d\n", file, line);
473    return rewind_dev(dev);
474 }
475 #endif
476
477 /*
478  * Rewind the device.
479  *  Returns: true  on success
480  *           false on failure
481  */
482 bool rewind_dev(DEVICE *dev)
483 {
484    struct mtop mt_com;
485    unsigned int i;
486
487    Dmsg1(29, "rewind_dev %s\n", dev->print_name());
488    if (dev->fd < 0) {
489       dev->dev_errno = EBADF;
490       Mmsg1(dev->errmsg, _("Bad call to rewind_dev. Device %s not open\n"),
491             dev->print_name());
492       Emsg0(M_ABORT, 0, dev->errmsg);
493       return false;
494    }
495    dev->state &= ~(ST_EOT|ST_EOF|ST_WEOT);  /* remove EOF/EOT flags */
496    dev->block_num = dev->file = 0;
497    dev->file_size = 0;
498    dev->file_addr = 0;
499    if (dev->is_tape()) {
500       mt_com.mt_op = MTREW;
501       mt_com.mt_count = 1;
502       /* If we get an I/O error on rewind, it is probably because
503        * the drive is actually busy. We loop for (about 5 minutes)
504        * retrying every 5 seconds.
505        */
506       for (i=dev->max_rewind_wait; ; i -= 5) {
507          if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
508             berrno be;
509             clrerror_dev(dev, MTREW);
510             if (i == dev->max_rewind_wait) {
511                Dmsg1(200, "Rewind error, %s. retrying ...\n", be.strerror());
512             }
513             if (dev->dev_errno == EIO && i > 0) {
514                Dmsg0(200, "Sleeping 5 seconds.\n");
515                bmicrosleep(5, 0);
516                continue;
517             }
518             Mmsg2(dev->errmsg, _("Rewind error on %s. ERR=%s.\n"),
519                dev->print_name(), be.strerror());
520             return false;
521          }
522          break;
523       }
524    } else if (dev->is_file()) {      
525       if (lseek_dev(dev, (off_t)0, SEEK_SET) < 0) {
526          berrno be;
527          dev->dev_errno = errno;
528          Mmsg2(dev->errmsg, _("lseek_dev error on %s. ERR=%s.\n"),
529             dev->print_name(), be.strerror());
530          return false;
531       }
532    }
533    return true;
534 }
535
536 void DEVICE::block(int why)
537 {
538    lock_device(this);
539    block_device(this, why);
540    V(mutex);
541 }
542
543 void DEVICE::unblock()
544 {  
545    P(mutex);
546    unblock_device(this);
547    V(mutex);
548 }
549
550 /*
551  * Called to indicate that we have just read an
552  *  EOF from the device.
553  */
554 void DEVICE::set_ateof() 
555
556    set_eof();
557    file++;
558    file_addr = 0;
559    file_size = 0;
560    block_num = 0;
561 }
562
563 /*
564  * Called to indicate we are now at the end of the tape, and
565  *   writing is not possible.
566  */
567 void DEVICE::set_ateot() 
568 {
569    /* Make tape effectively read-only */
570    state |= (ST_EOF|ST_EOT|ST_WEOT);
571    clear_append();
572 }
573
574 /*
575  * Position device to end of medium (end of data)
576  *  Returns: true  on succes
577  *           false on error
578  */
579 bool
580 eod_dev(DEVICE *dev)
581 {
582    struct mtop mt_com;
583    struct mtget mt_stat;
584    bool ok = true;
585    off_t pos;
586
587    if (dev->fd < 0) {
588       dev->dev_errno = EBADF;
589       Mmsg1(dev->errmsg, _("Bad call to eod_dev. Device %s not open\n"),
590             dev->print_name());
591       return false;
592    }
593
594 #if defined (__digital__) && defined (__unix__)
595    return fsf_dev(dev, dev->VolCatInfo.VolCatFiles);
596 #endif
597
598    Dmsg0(29, "eod_dev\n");
599    if (dev->at_eot()) {
600       return true;
601    }
602    dev->state &= ~(ST_EOF);  /* remove EOF flags */
603    dev->block_num = dev->file = 0;
604    dev->file_size = 0;
605    dev->file_addr = 0;
606    if (dev->state & (ST_FIFO | ST_PROG)) {
607       return true;
608    }
609    if (!dev->is_tape()) {
610       pos = lseek_dev(dev, (off_t)0, SEEK_END);
611 //    Dmsg1(100, "====== Seek to %lld\n", pos);
612       if (pos >= 0) {
613          update_pos_dev(dev);
614          dev->state |= ST_EOT;
615          return true;
616       }
617       dev->dev_errno = errno;
618       berrno be;
619       Mmsg2(dev->errmsg, _("lseek_dev error on %s. ERR=%s.\n"),
620              dev->print_name(), be.strerror());
621       return false;
622    }
623 #ifdef MTEOM
624    if (dev_cap(dev, CAP_FASTFSF) && !dev_cap(dev, CAP_EOM)) {
625       Dmsg0(100,"Using FAST FSF for EOM\n");
626       /* If unknown position, rewind */
627       if (!dev_get_os_pos(dev, &mt_stat)) {
628         if (!rewind_dev(dev)) {
629           return false;
630         }
631       }
632       mt_com.mt_op = MTFSF;
633       /*
634        * ***FIXME*** fix code to handle case that INT16_MAX is
635        *   not large enough.
636        */
637       mt_com.mt_count = INT16_MAX;    /* use big positive number */
638       if (mt_com.mt_count < 0) {
639          mt_com.mt_count = INT16_MAX; /* brain damaged system */
640       }
641    }
642
643    if (dev_cap(dev, CAP_MTIOCGET) && (dev_cap(dev, CAP_FASTFSF) || dev_cap(dev, CAP_EOM))) {
644       if (dev_cap(dev, CAP_EOM)) {
645          Dmsg0(100,"Using EOM for EOM\n");
646          mt_com.mt_op = MTEOM;
647          mt_com.mt_count = 1;
648       }
649
650       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
651          berrno be;
652          clrerror_dev(dev, mt_com.mt_op);
653          Dmsg1(50, "ioctl error: %s\n", be.strerror());
654          update_pos_dev(dev);
655          Mmsg2(dev->errmsg, _("ioctl MTEOM error on %s. ERR=%s.\n"),
656             dev->print_name(), be.strerror());
657          return false;
658       }
659
660       if (!dev_get_os_pos(dev, &mt_stat)) {
661          berrno be;
662          clrerror_dev(dev, -1);
663          Mmsg2(dev->errmsg, _("ioctl MTIOCGET error on %s. ERR=%s.\n"),
664             dev->print_name(), be.strerror());
665          return false;
666       }
667       Dmsg2(100, "EOD file=%d block=%d\n", mt_stat.mt_fileno, mt_stat.mt_blkno);
668       dev->set_ateof();
669       dev->file = mt_stat.mt_fileno;
670    } else {
671 #else
672    {
673 #endif
674       /*
675        * Rewind then use FSF until EOT reached
676        */
677       if (!rewind_dev(dev)) {
678          return false;
679       }
680       /*
681        * Move file by file to the end of the tape
682        */
683       int file_num;
684       for (file_num=dev->file; !dev->at_eot(); file_num++) {
685          Dmsg0(200, "eod_dev: doing fsf 1\n");
686          if (!fsf_dev(dev, 1)) {
687             Dmsg0(200, "fsf_dev error.\n");
688             return false;
689          }
690          /*
691           * Avoid infinite loop. ***FIXME*** possibly add code
692           *   to set EOD or to turn off CAP_FASTFSF if on.
693           */
694          if (file_num == (int)dev->file) {
695             struct mtget mt_stat;
696             Dmsg1(100, "fsf_dev did not advance from file %d\n", file_num);
697             if (dev_get_os_pos(dev, &mt_stat)) {
698                Dmsg2(100, "Adjust file from %d to %d\n", dev->file , mt_stat.mt_fileno);
699                dev->set_ateof();
700                dev->file = mt_stat.mt_fileno;
701             }
702             return false;
703          }
704       }
705    }
706    /*
707     * Some drivers leave us after second EOF when doing
708     * MTEOM, so we must backup so that appending overwrites
709     * the second EOF.
710     */
711    if (dev_cap(dev, CAP_BSFATEOM)) {
712       struct mtget mt_stat;
713       /* Backup over EOF */
714       ok = bsf_dev(dev, 1);
715       /* If BSF worked and fileno is known (not -1), set file */
716       if (dev_get_os_pos(dev, &mt_stat)) {
717          Dmsg2(100, "BSFATEOF adjust file from %d to %d\n", dev->file , mt_stat.mt_fileno);
718          dev->file = mt_stat.mt_fileno;
719       } else {
720          dev->file++;                 /* wing it -- not correct on all OSes */
721       }
722    } else {
723       update_pos_dev(dev);                   /* update position */
724    }
725    Dmsg1(200, "EOD dev->file=%d\n", dev->file);
726    return ok;
727 }
728
729 /*
730  * Set the position of the device -- only for files
731  *   For other devices, there is no generic way to do it.
732  *  Returns: true  on succes
733  *           false on error
734  */
735 bool update_pos_dev(DEVICE *dev)
736 {
737    off_t pos;
738    bool ok = true;
739
740    if (dev->fd < 0) {
741       dev->dev_errno = EBADF;
742       Mmsg0(dev->errmsg, _("Bad device call. Device not open\n"));
743       Emsg0(M_FATAL, 0, dev->errmsg);
744       return false;
745    }
746
747    /* Find out where we are */
748    if (dev->is_file()) {
749       dev->file = 0;
750       dev->file_addr = 0;
751       pos = lseek_dev(dev, (off_t)0, SEEK_CUR);
752       if (pos < 0) {
753          berrno be;
754          dev->dev_errno = errno;
755          Pmsg1(000, "Seek error: ERR=%s\n", be.strerror());
756          Mmsg2(dev->errmsg, _("lseek_dev error on %s. ERR=%s.\n"),
757             dev->print_name(), be.strerror());
758          ok = false;
759       } else {
760          dev->file_addr = pos;
761       }
762    }
763    return ok;
764 }
765
766
767 /*
768  * Return the status of the device.  This was meant
769  * to be a generic routine. Unfortunately, it doesn't
770  * seem possible (at least I do not know how to do it
771  * currently), which means that for the moment, this
772  * routine has very little value.
773  *
774  *   Returns: status
775  */
776 uint32_t status_dev(DEVICE *dev)
777 {
778    struct mtget mt_stat;
779    uint32_t stat = 0;
780
781    if (dev->state & (ST_EOT | ST_WEOT)) {
782       stat |= BMT_EOD;
783       Pmsg0(-20, " EOD");
784    }
785    if (dev->state & ST_EOF) {
786       stat |= BMT_EOF;
787       Pmsg0(-20, " EOF");
788    }
789    if (dev->is_tape()) {
790       stat |= BMT_TAPE;
791       Pmsg0(-20," Bacula status:");
792       Pmsg2(-20," file=%d block=%d\n", dev->file, dev->block_num);
793       if (ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) < 0) {
794          berrno be;
795          dev->dev_errno = errno;
796          Mmsg2(dev->errmsg, _("ioctl MTIOCGET error on %s. ERR=%s.\n"),
797             dev->print_name(), be.strerror());
798          return 0;
799       }
800       Pmsg0(-20, " Device status:");
801
802 #if defined(HAVE_LINUX_OS)
803       if (GMT_EOF(mt_stat.mt_gstat)) {
804          stat |= BMT_EOF;
805          Pmsg0(-20, " EOF");
806       }
807       if (GMT_BOT(mt_stat.mt_gstat)) {
808          stat |= BMT_BOT;
809          Pmsg0(-20, " BOT");
810       }
811       if (GMT_EOT(mt_stat.mt_gstat)) {
812          stat |= BMT_EOT;
813          Pmsg0(-20, " EOT");
814       }
815       if (GMT_SM(mt_stat.mt_gstat)) {
816          stat |= BMT_SM;
817          Pmsg0(-20, " SM");
818       }
819       if (GMT_EOD(mt_stat.mt_gstat)) {
820          stat |= BMT_EOD;
821          Pmsg0(-20, " EOD");
822       }
823       if (GMT_WR_PROT(mt_stat.mt_gstat)) {
824          stat |= BMT_WR_PROT;
825          Pmsg0(-20, " WR_PROT");
826       }
827       if (GMT_ONLINE(mt_stat.mt_gstat)) {
828          stat |= BMT_ONLINE;
829          Pmsg0(-20, " ONLINE");
830       }
831       if (GMT_DR_OPEN(mt_stat.mt_gstat)) {
832          stat |= BMT_DR_OPEN;
833          Pmsg0(-20, " DR_OPEN");
834       }
835       if (GMT_IM_REP_EN(mt_stat.mt_gstat)) {
836          stat |= BMT_IM_REP_EN;
837          Pmsg0(-20, " IM_REP_EN");
838       }
839 #endif /* !SunOS && !OSF */
840       if (dev_cap(dev, CAP_MTIOCGET)) {
841          Pmsg2(-20, " file=%d block=%d\n", mt_stat.mt_fileno, mt_stat.mt_blkno);
842       } else {
843          Pmsg2(-20, " file=%d block=%d\n", -1, -1);
844       }
845    } else {
846       stat |= BMT_ONLINE | BMT_BOT;
847    }
848    return stat;
849 }
850
851
852 /*
853  * Load medium in device
854  *  Returns: true  on success
855  *           false on failure
856  */
857 bool load_dev(DEVICE *dev)
858 {
859 #ifdef MTLOAD
860    struct mtop mt_com;
861 #endif
862
863    if (dev->fd < 0) {
864       dev->dev_errno = EBADF;
865       Mmsg0(dev->errmsg, _("Bad call to load_dev. Device not open\n"));
866       Emsg0(M_FATAL, 0, dev->errmsg);
867       return false;
868    }
869    if (!(dev->is_tape())) {
870       return true;
871    }
872 #ifndef MTLOAD
873    Dmsg0(200, "stored: MTLOAD command not available\n");
874    berrno be;
875    dev->dev_errno = ENOTTY;           /* function not available */
876    Mmsg2(dev->errmsg, _("ioctl MTLOAD error on %s. ERR=%s.\n"),
877          dev->print_name(), be.strerror());
878    return false;
879 #else
880
881    dev->block_num = dev->file = 0;
882    dev->file_size = 0;
883    dev->file_addr = 0;
884    mt_com.mt_op = MTLOAD;
885    mt_com.mt_count = 1;
886    if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
887       berrno be;
888       dev->dev_errno = errno;
889       Mmsg2(dev->errmsg, _("ioctl MTLOAD error on %s. ERR=%s.\n"),
890          dev->print_name(), be.strerror());
891       return false;
892    }
893    return true;
894 #endif
895 }
896
897 /*
898  * Rewind device and put it offline
899  *  Returns: true  on success
900  *           false on failure
901  */
902 bool offline_dev(DEVICE *dev)
903 {
904    struct mtop mt_com;
905
906    if (dev->fd < 0) {
907       dev->dev_errno = EBADF;
908       Mmsg0(dev->errmsg, _("Bad call to offline_dev. Device not open\n"));
909       Emsg0(M_FATAL, 0, dev->errmsg);
910       return false;
911    }
912    if (!(dev->is_tape())) {
913       return true;
914    }
915
916    dev->state &= ~(ST_APPEND|ST_READ|ST_EOT|ST_EOF|ST_WEOT);  /* remove EOF/EOT flags */
917    dev->block_num = dev->file = 0;
918    dev->file_size = 0;
919    dev->file_addr = 0;
920    dev->part = 0;
921 #ifdef MTUNLOCK
922    mt_com.mt_op = MTUNLOCK;
923    mt_com.mt_count = 1;
924    ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
925 #endif
926    mt_com.mt_op = MTOFFL;
927    mt_com.mt_count = 1;
928    if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
929       berrno be;
930       dev->dev_errno = errno;
931       Mmsg2(dev->errmsg, _("ioctl MTOFFL error on %s. ERR=%s.\n"),
932          dev->print_name(), be.strerror());
933       return false;
934    }
935    Dmsg1(100, "Offlined device %s\n", dev->print_name());
936    return true;
937 }
938
939 bool offline_or_rewind_dev(DEVICE *dev)
940 {
941    if (dev->fd < 0) {
942       return false;
943    }
944    if (dev_cap(dev, CAP_OFFLINEUNMOUNT)) {
945       return offline_dev(dev);
946    } else {
947    /*
948     * Note, this rewind probably should not be here (it wasn't
949     *  in prior versions of Bacula), but on FreeBSD, this is
950     *  needed in the case the tape was "frozen" due to an error
951     *  such as backspacing after writing and EOF. If it is not
952     *  done, all future references to the drive get and I/O error.
953     */
954       clrerror_dev(dev, MTREW);
955       return rewind_dev(dev);
956    }
957 }
958
959 /*
960  * Foward space a file
961  *   Returns: true  on success
962  *            false on failure
963  */
964 bool
965 fsf_dev(DEVICE *dev, int num)
966 {
967    struct mtget mt_stat;
968    struct mtop mt_com;
969    int stat = 0;
970
971    if (dev->fd < 0) {
972       dev->dev_errno = EBADF;
973       Mmsg0(dev->errmsg, _("Bad call to fsf_dev. Device not open\n"));
974       Emsg0(M_FATAL, 0, dev->errmsg);
975       return false;
976    }
977
978    if (!dev->is_tape()) {
979       return true;
980    }
981    if (dev->state & ST_EOT) {
982       dev->dev_errno = 0;
983       Mmsg1(dev->errmsg, _("Device %s at End of Tape.\n"), dev->print_name());
984       return false;
985    }
986    if (dev->state & ST_EOF) {
987       Dmsg0(200, "ST_EOF set on entry to FSF\n");
988    }
989
990    Dmsg0(100, "fsf_dev\n");
991    dev->block_num = 0;
992    /*
993     * If Fast forward space file is set, then we
994     *  use MTFSF to forward space and MTIOCGET
995     *  to get the file position. We assume that
996     *  the SCSI driver will ensure that we do not
997     *  forward space past the end of the medium.
998     */
999    if (dev_cap(dev, CAP_FSF) && dev_cap(dev, CAP_MTIOCGET) && dev_cap(dev, CAP_FASTFSF)) {
1000       mt_com.mt_op = MTFSF;
1001       mt_com.mt_count = num;
1002       stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1003       if (stat < 0 || !dev_get_os_pos(dev, &mt_stat)) {
1004          berrno be;
1005          dev->state |= ST_EOT;
1006          Dmsg0(200, "Set ST_EOT\n");
1007          clrerror_dev(dev, MTFSF);
1008          Mmsg2(dev->errmsg, _("ioctl MTFSF error on %s. ERR=%s.\n"),
1009             dev->print_name(), be.strerror());
1010          Dmsg1(200, "%s", dev->errmsg);
1011          return false;
1012       }
1013       Dmsg2(200, "fsf file=%d block=%d\n", mt_stat.mt_fileno, mt_stat.mt_blkno);
1014       dev->set_ateof();
1015       dev->file = mt_stat.mt_fileno;
1016       return true;
1017
1018    /*
1019     * Here if CAP_FSF is set, and virtually all drives
1020     *  these days support it, we read a record, then forward
1021     *  space one file. Using this procedure, which is slow,
1022     *  is the only way we can be sure that we don't read
1023     *  two consecutive EOF marks, which means End of Data.
1024     */
1025    } else if (dev_cap(dev, CAP_FSF)) {
1026       POOLMEM *rbuf;
1027       int rbuf_len;
1028       Dmsg0(200, "FSF has cap_fsf\n");
1029       if (dev->max_block_size == 0) {
1030          rbuf_len = DEFAULT_BLOCK_SIZE;
1031       } else {
1032          rbuf_len = dev->max_block_size;
1033       }
1034       rbuf = get_memory(rbuf_len);
1035       mt_com.mt_op = MTFSF;
1036       mt_com.mt_count = 1;
1037       while (num-- && !(dev->state & ST_EOT)) {
1038          Dmsg0(100, "Doing read before fsf\n");
1039          if ((stat = read(dev->fd, (char *)rbuf, rbuf_len)) < 0) {
1040             if (errno == ENOMEM) {     /* tape record exceeds buf len */
1041                stat = rbuf_len;        /* This is OK */
1042             } else {
1043                berrno be;
1044                dev->state |= ST_EOT;
1045                clrerror_dev(dev, -1);
1046                Dmsg2(100, "Set ST_EOT read errno=%d. ERR=%s\n", dev->dev_errno,
1047                   be.strerror());
1048                Mmsg2(dev->errmsg, _("read error on %s. ERR=%s.\n"),
1049                   dev->print_name(), be.strerror());
1050                Dmsg1(100, "%s", dev->errmsg);
1051                break;
1052             }
1053          }
1054          if (stat == 0) {                /* EOF */
1055             update_pos_dev(dev);
1056             Dmsg1(100, "End of File mark from read. File=%d\n", dev->file+1);
1057             /* Two reads of zero means end of tape */
1058             if (dev->state & ST_EOF) {
1059                dev->state |= ST_EOT;
1060                Dmsg0(100, "Set ST_EOT\n");
1061                break;
1062             } else {
1063                dev->set_ateof();
1064                continue;
1065             }
1066          } else {                        /* Got data */
1067             dev->state &= ~(ST_EOF|ST_EOT);
1068          }
1069
1070          Dmsg0(100, "Doing MTFSF\n");
1071          stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1072          if (stat < 0) {                 /* error => EOT */
1073             berrno be;
1074             dev->state |= ST_EOT;
1075             Dmsg0(100, "Set ST_EOT\n");
1076             clrerror_dev(dev, MTFSF);
1077             Mmsg2(dev->errmsg, _("ioctl MTFSF error on %s. ERR=%s.\n"),
1078                dev->print_name(), be.strerror());
1079             Dmsg0(100, "Got < 0 for MTFSF\n");
1080             Dmsg1(100, "%s", dev->errmsg);
1081          } else {
1082             dev->set_ateof();
1083          }
1084       }
1085       free_memory(rbuf);
1086
1087    /*
1088     * No FSF, so use FSR to simulate it
1089     */
1090    } else {
1091       Dmsg0(200, "Doing FSR for FSF\n");
1092       while (num-- && !(dev->state & ST_EOT)) {
1093          dev->fsr(INT32_MAX);    /* returns -1 on EOF or EOT */
1094       }
1095       if (dev->state & ST_EOT) {
1096          dev->dev_errno = 0;
1097          Mmsg1(dev->errmsg, _("Device %s at End of Tape.\n"), dev->print_name());
1098          stat = -1;
1099       } else {
1100          stat = 0;
1101       }
1102    }
1103    update_pos_dev(dev);
1104    Dmsg1(200, "Return %d from FSF\n", stat);
1105    if (dev->state & ST_EOF)
1106       Dmsg0(200, "ST_EOF set on exit FSF\n");
1107    if (dev->state & ST_EOT)
1108       Dmsg0(200, "ST_EOT set on exit FSF\n");
1109    Dmsg1(200, "Return from FSF file=%d\n", dev->file);
1110    return stat == 0;
1111 }
1112
1113 /*
1114  * Backward space a file
1115  *  Returns: false on failure
1116  *           true  on success
1117  */
1118 bool
1119 bsf_dev(DEVICE *dev, int num)
1120 {
1121    struct mtop mt_com;
1122    int stat;
1123
1124    if (dev->fd < 0) {
1125       dev->dev_errno = EBADF;
1126       Mmsg0(dev->errmsg, _("Bad call to bsf_dev. Device not open\n"));
1127       Emsg0(M_FATAL, 0, dev->errmsg);
1128       return false;
1129    }
1130
1131    if (!dev->is_tape()) {
1132       Mmsg1(dev->errmsg, _("Device %s cannot BSF because it is not a tape.\n"),
1133          dev->print_name());
1134       return false;
1135    }
1136    Dmsg0(29, "bsf_dev\n");
1137    dev->state &= ~(ST_EOT|ST_EOF);
1138    dev->file -= num;
1139    dev->file_addr = 0;
1140    dev->file_size = 0;
1141    mt_com.mt_op = MTBSF;
1142    mt_com.mt_count = num;
1143    stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1144    if (stat < 0) {
1145       berrno be;
1146       clrerror_dev(dev, MTBSF);
1147       Mmsg2(dev->errmsg, _("ioctl MTBSF error on %s. ERR=%s.\n"),
1148          dev->print_name(), be.strerror());
1149    }
1150    update_pos_dev(dev);
1151    return stat == 0;
1152 }
1153
1154
1155 /*
1156  * Foward space num records
1157  *  Returns: false on failure
1158  *           true  on success
1159  */
1160 bool DEVICE::fsr(int num)
1161 {
1162    struct mtop mt_com;
1163    int stat;
1164
1165    if (fd < 0) {
1166       dev_errno = EBADF;
1167       Mmsg0(errmsg, _("Bad call to fsr. Device not open\n"));
1168       Emsg0(M_FATAL, 0, errmsg);
1169       return false;
1170    }
1171
1172    if (!is_tape()) {
1173       return false;
1174    }
1175    if (!dev_cap(this, CAP_FSR)) {
1176       Mmsg1(errmsg, _("ioctl MTFSR not permitted on %s.\n"), print_name());
1177       return false;
1178    }
1179
1180    Dmsg1(29, "fsr %d\n", num);
1181    mt_com.mt_op = MTFSR;
1182    mt_com.mt_count = num;
1183    stat = ioctl(fd, MTIOCTOP, (char *)&mt_com);
1184    if (stat == 0) {
1185       clear_eof();
1186       block_num += num;
1187    } else {
1188       berrno be;
1189       struct mtget mt_stat;
1190       clrerror_dev(this, MTFSR);
1191       Dmsg1(100, "FSF fail: ERR=%s\n", be.strerror());
1192       if (dev_get_os_pos(this, &mt_stat)) {
1193          Dmsg4(100, "Adjust from %d:%d to %d:%d\n", file,
1194             block_num, mt_stat.mt_fileno, mt_stat.mt_blkno);
1195          file = mt_stat.mt_fileno;
1196          block_num = mt_stat.mt_blkno;
1197       } else {
1198          if (at_eof()) {
1199             set_eot();
1200          } else {
1201             set_ateof();
1202          }
1203       }
1204       Mmsg3(errmsg, _("ioctl MTFSR %d error on %s. ERR=%s.\n"),
1205          num, print_name(), be.strerror());
1206    }
1207    update_pos_dev(this);
1208    return stat == 0;
1209 }
1210
1211 /*
1212  * Backward space a record
1213  *   Returns:  false on failure
1214  *             true  on success
1215  */
1216 bool
1217 bsr_dev(DEVICE *dev, int num)
1218 {
1219    struct mtop mt_com;
1220    int stat;
1221
1222    if (dev->fd < 0) {
1223       dev->dev_errno = EBADF;
1224       Mmsg0(dev->errmsg, _("Bad call to bsr_dev. Device not open\n"));
1225       Emsg0(M_FATAL, 0, dev->errmsg);
1226       return false;
1227    }
1228
1229    if (!dev->is_tape()) {
1230       return false;
1231    }
1232
1233    if (!dev_cap(dev, CAP_BSR)) {
1234       Mmsg1(dev->errmsg, _("ioctl MTBSR not permitted on %s.\n"), dev->print_name());
1235       return false;
1236    }
1237
1238    Dmsg0(29, "bsr_dev\n");
1239    dev->block_num -= num;
1240    dev->state &= ~(ST_EOF|ST_EOT|ST_EOF);
1241    mt_com.mt_op = MTBSR;
1242    mt_com.mt_count = num;
1243    stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1244    if (stat < 0) {
1245       berrno be;
1246       clrerror_dev(dev, MTBSR);
1247       Mmsg2(dev->errmsg, _("ioctl MTBSR error on %s. ERR=%s.\n"),
1248          dev->print_name(), be.strerror());
1249    }
1250    update_pos_dev(dev);
1251    return stat == 0;
1252 }
1253
1254 /*
1255  * Reposition the device to file, block
1256  * Returns: false on failure
1257  *          true  on success
1258  */
1259 bool
1260 reposition_dev(DEVICE *dev, uint32_t file, uint32_t block)
1261 {
1262    if (dev->fd < 0) {
1263       dev->dev_errno = EBADF;
1264       Mmsg0(dev->errmsg, _("Bad call to reposition_dev. Device not open\n"));
1265       Emsg0(M_FATAL, 0, dev->errmsg);
1266       return false;
1267    }
1268
1269    if (!dev->is_tape()) {
1270       off_t pos = (((off_t)file)<<32) + block;
1271       Dmsg1(100, "===== lseek_dev to %d\n", (int)pos);
1272       if (lseek_dev(dev, pos, SEEK_SET) == (off_t)-1) {
1273          berrno be;
1274          dev->dev_errno = errno;
1275          Mmsg2(dev->errmsg, _("lseek_dev error on %s. ERR=%s.\n"),
1276             dev->print_name(), be.strerror());
1277          return false;
1278       }
1279       dev->file = file;
1280       dev->block_num = block;
1281       dev->file_addr = pos;
1282       return true;
1283    }
1284    Dmsg4(100, "reposition_dev from %u:%u to %u:%u\n",
1285       dev->file, dev->block_num, file, block);
1286    if (file < dev->file) {
1287       Dmsg0(100, "Rewind_dev\n");
1288       if (!rewind_dev(dev)) {
1289          return false;
1290       }
1291    }
1292    if (file > dev->file) {
1293       Dmsg1(100, "fsf %d\n", file-dev->file);
1294       if (!fsf_dev(dev, file-dev->file)) {
1295          Dmsg1(100, "fsf failed! ERR=%s\n", strerror_dev(dev));
1296          return false;
1297       }
1298       Dmsg2(100, "wanted_file=%d at_file=%d\n", file, dev->file);
1299    }
1300    if (block < dev->block_num) {
1301       Dmsg2(100, "wanted_blk=%d at_blk=%d\n", block, dev->block_num);
1302       Dmsg0(100, "bsf_dev 1\n");
1303       bsf_dev(dev, 1);
1304       Dmsg0(100, "fsf_dev 1\n");
1305       fsf_dev(dev, 1);
1306       Dmsg2(100, "wanted_blk=%d at_blk=%d\n", block, dev->block_num);
1307    }
1308    if (dev_cap(dev, CAP_POSITIONBLOCKS) && block > dev->block_num) {
1309       /* Ignore errors as Bacula can read to the correct block */
1310       Dmsg1(100, "fsr %d\n", block-dev->block_num);
1311       return dev->fsr(block-dev->block_num);
1312    }
1313    return true;
1314 }
1315
1316
1317
1318 /*
1319  * Write an end of file on the device
1320  *   Returns: 0 on success
1321  *            non-zero on failure
1322  */
1323 int
1324 weof_dev(DEVICE *dev, int num)
1325 {
1326    struct mtop mt_com;
1327    int stat;
1328    Dmsg0(29, "weof_dev\n");
1329    
1330    if (dev->fd < 0) {
1331       dev->dev_errno = EBADF;
1332       Mmsg0(dev->errmsg, _("Bad call to weof_dev. Device not open\n"));
1333       Emsg0(M_FATAL, 0, dev->errmsg);
1334       return -1;
1335    }
1336    dev->file_size = 0;
1337
1338    if (!dev->is_tape()) {
1339       return 0;
1340    }
1341    if (!dev->can_append()) {
1342       Mmsg0(dev->errmsg, _("Attempt to WEOF on non-appendable Volume\n"));
1343       Emsg0(M_FATAL, 0, dev->errmsg);
1344       return -1;
1345    }
1346       
1347    dev->state &= ~(ST_EOT | ST_EOF);  /* remove EOF/EOT flags */
1348    mt_com.mt_op = MTWEOF;
1349    mt_com.mt_count = num;
1350    stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1351    if (stat == 0) {
1352       dev->block_num = 0;
1353       dev->file += num;
1354       dev->file_addr = 0;
1355    } else {
1356       berrno be;
1357       clrerror_dev(dev, MTWEOF);
1358       if (stat == -1) {
1359          Mmsg2(dev->errmsg, _("ioctl MTWEOF error on %s. ERR=%s.\n"),
1360             dev->print_name(), be.strerror());
1361        }
1362    }
1363    return stat;
1364 }
1365
1366 /*
1367  * Return string message with last error in English
1368  *  Be careful not to call this routine from within dev.c
1369  *  while editing an Mmsg() or you will end up in a recursive
1370  *  loop creating a Segmentation Violation.
1371  */
1372 char *
1373 strerror_dev(DEVICE *dev)
1374 {
1375    return dev->errmsg;
1376 }
1377
1378
1379 /*
1380  * If implemented in system, clear the tape
1381  * error status.
1382  */
1383 void
1384 clrerror_dev(DEVICE *dev, int func)
1385 {
1386    const char *msg = NULL;
1387    struct mtget mt_stat;
1388    char buf[100];
1389
1390    dev->dev_errno = errno;         /* save errno */
1391    if (errno == EIO) {
1392       dev->VolCatInfo.VolCatErrors++;
1393    }
1394
1395    if (!dev->is_tape()) {
1396       return;
1397    }
1398    if (errno == ENOTTY || errno == ENOSYS) { /* Function not implemented */
1399       switch (func) {
1400       case -1:
1401          Emsg0(M_ABORT, 0, "Got ENOTTY on read/write!\n");
1402          break;
1403       case MTWEOF:
1404          msg = "WTWEOF";
1405          dev->capabilities &= ~CAP_EOF; /* turn off feature */
1406          break;
1407 #ifdef MTEOM
1408       case MTEOM:
1409          msg = "WTEOM";
1410          dev->capabilities &= ~CAP_EOM; /* turn off feature */
1411          break;
1412 #endif
1413       case MTFSF:
1414          msg = "MTFSF";
1415          dev->capabilities &= ~CAP_FSF; /* turn off feature */
1416          break;
1417       case MTBSF:
1418          msg = "MTBSF";
1419          dev->capabilities &= ~CAP_BSF; /* turn off feature */
1420          break;
1421       case MTFSR:
1422          msg = "MTFSR";
1423          dev->capabilities &= ~CAP_FSR; /* turn off feature */
1424          break;
1425       case MTBSR:
1426          msg = "MTBSR";
1427          dev->capabilities &= ~CAP_BSR; /* turn off feature */
1428          break;
1429       case MTREW:
1430          msg = "MTREW";
1431          break;
1432 #ifdef MTSETBLK
1433       case MTSETBLK:
1434          msg = "MTSETBLK";
1435          break;
1436 #endif
1437 #ifdef MTSETBSIZ 
1438       case MTSETBSIZ:
1439          msg = "MTSETBSIZ";
1440          break;
1441 #endif
1442 #ifdef MTSRSZ
1443       case MTSRSZ:
1444          msg = "MTSRSZ";
1445          break;
1446 #endif
1447       default:
1448          bsnprintf(buf, sizeof(buf), "unknown func code %d", func);
1449          msg = buf;
1450          break;
1451       }
1452       if (msg != NULL) {
1453          dev->dev_errno = ENOSYS;
1454          Mmsg1(dev->errmsg, _("I/O function \"%s\" not supported on this device.\n"), msg);
1455          Emsg0(M_ERROR, 0, dev->errmsg);
1456       }
1457    }
1458    /* On some systems such as NetBSD, this clears all errors */
1459    ioctl(dev->fd, MTIOCGET, (char *)&mt_stat);
1460
1461 /* Found on Linux */
1462 #ifdef MTIOCLRERR
1463 {
1464    struct mtop mt_com;
1465    mt_com.mt_op = MTIOCLRERR;
1466    mt_com.mt_count = 1;
1467    /* Clear any error condition on the tape */
1468    ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1469    Dmsg0(200, "Did MTIOCLRERR\n");
1470 }
1471 #endif
1472
1473 /* Typically on FreeBSD */
1474 #ifdef MTIOCERRSTAT
1475 {
1476    /* Read and clear SCSI error status */
1477    union mterrstat mt_errstat;
1478    Dmsg2(200, "Doing MTIOCERRSTAT errno=%d ERR=%s\n", dev->dev_errno,
1479       strerror(dev->dev_errno));
1480    ioctl(dev->fd, MTIOCERRSTAT, (char *)&mt_errstat);
1481 }
1482 #endif
1483
1484 /* Clear Subsystem Exception OSF1 */
1485 #ifdef MTCSE
1486 {
1487    struct mtop mt_com;
1488    mt_com.mt_op = MTCSE;
1489    mt_com.mt_count = 1;
1490    /* Clear any error condition on the tape */
1491    ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1492    Dmsg0(200, "Did MTCSE\n");
1493 }
1494 #endif
1495 }
1496
1497 /*
1498  * Flush buffer contents
1499  *  No longer used.
1500  */
1501 int flush_dev(DEVICE *dev)
1502 {
1503    return 1;
1504 }
1505
1506 static void do_close(DEVICE *dev)
1507 {
1508
1509    Dmsg1(29, "really close_dev %s\n", dev->print_name());
1510    if (dev->fd >= 0) {
1511       close(dev->fd);
1512    }
1513
1514    if (unmount_dev(dev, 1) < 0) {
1515       Dmsg1(0, "Cannot unmount device %s.\n", dev->print_name());
1516    }
1517    
1518    /* Remove the last part file if it is empty */
1519    if (dev->can_append() && (dev->num_parts > 0)) {
1520       struct stat statp;
1521       POOL_MEM archive_name(PM_FNAME);
1522       dev->part = dev->num_parts;
1523       get_filename(dev, dev->VolCatInfo.VolCatName, archive_name);
1524       /* Check that the part file is empty */
1525       if ((stat(archive_name.c_str(), &statp) == 0) && (statp.st_size == 0)) {
1526          unlink(archive_name.c_str());
1527       }
1528    }
1529    
1530    /* Clean up device packet so it can be reused */
1531    dev->fd = -1;
1532    dev->state &= ~(ST_OPENED|ST_LABEL|ST_READ|ST_APPEND|ST_EOT|ST_WEOT|ST_EOF);
1533    dev->label_type = B_BACULA_LABEL;
1534    dev->file = dev->block_num = 0;
1535    dev->file_size = 0;
1536    dev->file_addr = 0;
1537    dev->part = 0;
1538    dev->part_size = 0;
1539    dev->part_start = 0;
1540    dev->EndFile = dev->EndBlock = 0;
1541    memset(&dev->VolCatInfo, 0, sizeof(dev->VolCatInfo));
1542    memset(&dev->VolHdr, 0, sizeof(dev->VolHdr));
1543    if (dev->tid) {
1544       stop_thread_timer(dev->tid);
1545       dev->tid = 0;
1546    }
1547    dev->use_count = 0;
1548    dev->openmode = 0;
1549 }
1550
1551 /*
1552  * Close the device
1553  */
1554 void DEVICE::close()
1555 {
1556    /*if (fd >= 0 && use_count == 1) {*/
1557    /* No need to check if fd >= 0: it is checked again
1558     * in do_close, and do_close MUST be called for volumes
1559     * splitted in parts, even if fd == -1. */
1560    if (use_count == 1) {
1561       do_close(this);
1562    } else if (use_count > 0) {
1563       use_count--;
1564    }
1565
1566 #ifdef FULL_DEBUG
1567    ASSERT(use_count >= 0);
1568 #endif
1569 }
1570
1571
1572 bool truncate_dev(DEVICE *dev)
1573 {
1574    Dmsg1(100, "truncate_dev %s\n", dev->print_name());
1575    if (dev->is_tape()) {
1576       return true;                    /* we don't really truncate tapes */
1577       /* maybe we should rewind and write and eof ???? */
1578    }
1579    
1580    /* If there is more than one part, open the first one, and then truncate it. */
1581    if (dev->num_parts > 0) {
1582       dev->num_parts = 0;
1583       dev->VolCatInfo.VolCatParts = 0;
1584       if (open_first_part(dev) < 0) {
1585          berrno be;
1586          Mmsg1(dev->errmsg, "Unable to truncate device, because I'm unable to open the first part. ERR=%s\n", be.strerror());
1587       }
1588    }
1589    
1590    if (ftruncate(dev->fd, 0) != 0) {
1591       berrno be;
1592       Mmsg1(dev->errmsg, _("Unable to truncate device. ERR=%s\n"), be.strerror());
1593       return false;
1594    }
1595    return true;
1596 }
1597
1598 /* Return the resource name for the device */
1599 const char *DEVICE::name() const
1600 {
1601    return device->hdr.name;
1602 }
1603
1604 char *
1605 dev_vol_name(DEVICE *dev)
1606 {
1607    return dev->VolCatInfo.VolCatName;
1608 }
1609
1610 uint32_t dev_block(DEVICE *dev)
1611 {
1612    update_pos_dev(dev);
1613    return dev->block_num;
1614 }
1615
1616 uint32_t dev_file(DEVICE *dev)
1617 {
1618    update_pos_dev(dev);
1619    return dev->file;
1620 }
1621
1622 /*
1623  * Free memory allocated for the device
1624  */
1625 void
1626 term_dev(DEVICE *dev)
1627 {
1628    if (!dev) {
1629       dev->dev_errno = EBADF;
1630       Mmsg0(dev->errmsg, _("Bad call to term_dev. Device not open\n"));
1631       Emsg0(M_FATAL, 0, dev->errmsg);
1632       return;
1633    }
1634    do_close(dev);
1635    Dmsg0(29, "term_dev\n");
1636    if (dev->dev_name) {
1637       free_memory(dev->dev_name);
1638       dev->dev_name = NULL;
1639    }
1640    if (dev->prt_name) {
1641       free_memory(dev->prt_name);
1642       dev->prt_name = NULL;
1643    }
1644    if (dev->errmsg) {
1645       free_pool_memory(dev->errmsg);
1646       dev->errmsg = NULL;
1647    }
1648    pthread_mutex_destroy(&dev->mutex);
1649    pthread_cond_destroy(&dev->wait);
1650    pthread_cond_destroy(&dev->wait_next_vol);
1651    pthread_mutex_destroy(&dev->spool_mutex);
1652    rwl_destroy(&dev->lock);
1653    if (dev->attached_dcrs) {
1654       delete dev->attached_dcrs;
1655       dev->attached_dcrs = NULL;
1656    }
1657    if (dev->state & ST_MALLOC) {
1658       free_pool_memory((POOLMEM *)dev);
1659    }
1660 }
1661
1662 /*
1663  * This routine initializes the device wait timers
1664  */
1665 void init_device_wait_timers(DCR *dcr)
1666 {
1667    DEVICE *dev = dcr->dev;
1668    JCR *jcr = dcr->jcr;
1669
1670    /* ******FIXME******* put these on config variables */
1671    dev->min_wait = 60 * 60;
1672    dev->max_wait = 24 * 60 * 60;
1673    dev->max_num_wait = 9;              /* 5 waits =~ 1 day, then 1 day at a time */
1674    dev->wait_sec = dev->min_wait;
1675    dev->rem_wait_sec = dev->wait_sec;
1676    dev->num_wait = 0;
1677    dev->poll = false;
1678    dev->BadVolName[0] = 0;
1679
1680    jcr->min_wait = 60 * 60;
1681    jcr->max_wait = 24 * 60 * 60;
1682    jcr->max_num_wait = 9;              /* 5 waits =~ 1 day, then 1 day at a time */
1683    jcr->wait_sec = jcr->min_wait;
1684    jcr->rem_wait_sec = jcr->wait_sec;
1685    jcr->num_wait = 0;
1686
1687 }
1688
1689 void init_jcr_device_wait_timers(JCR *jcr)
1690 {
1691    /* ******FIXME******* put these on config variables */
1692    jcr->min_wait = 60 * 60;
1693    jcr->max_wait = 24 * 60 * 60;
1694    jcr->max_num_wait = 9;              /* 5 waits =~ 1 day, then 1 day at a time */
1695    jcr->wait_sec = jcr->min_wait;
1696    jcr->rem_wait_sec = jcr->wait_sec;
1697    jcr->num_wait = 0;
1698 }
1699
1700
1701 /*
1702  * The dev timers are used for waiting on a particular device 
1703  *
1704  * Returns: true if time doubled
1705  *          false if max time expired
1706  */
1707 bool double_dev_wait_time(DEVICE *dev)
1708 {
1709    dev->wait_sec *= 2;               /* double wait time */
1710    if (dev->wait_sec > dev->max_wait) {   /* but not longer than maxtime */
1711       dev->wait_sec = dev->max_wait;
1712    }
1713    dev->num_wait++;
1714    dev->rem_wait_sec = dev->wait_sec;
1715    if (dev->num_wait >= dev->max_num_wait) {
1716       return false;
1717    }
1718    return true;
1719 }
1720
1721
1722 void set_os_device_parameters(DEVICE *dev)
1723 {
1724 #ifdef HAVE_LINUX_OS
1725    struct mtop mt_com;
1726    if (dev->min_block_size == dev->max_block_size &&
1727        dev->min_block_size == 0) {    /* variable block mode */
1728       mt_com.mt_op = MTSETBLK;
1729       mt_com.mt_count = 0;
1730       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1731          clrerror_dev(dev, MTSETBLK);
1732       }
1733       mt_com.mt_op = MTSETDRVBUFFER;
1734       mt_com.mt_count = MT_ST_CLEARBOOLEANS;
1735       if (!dev_cap(dev, CAP_TWOEOF)) {
1736          mt_com.mt_count |= MT_ST_TWO_FM;
1737       }
1738       if (dev_cap(dev, CAP_EOM)) {
1739          mt_com.mt_count |= MT_ST_FAST_MTEOM;
1740       }
1741       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1742          clrerror_dev(dev, MTSETBLK);
1743       }
1744    }
1745    return;
1746 #endif
1747
1748 #ifdef HAVE_NETBSD_OS
1749    struct mtop mt_com;
1750    if (dev->min_block_size == dev->max_block_size &&
1751        dev->min_block_size == 0) {    /* variable block mode */
1752       mt_com.mt_op = MTSETBSIZ;
1753       mt_com.mt_count = 0;
1754       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1755          clrerror_dev(dev, MTSETBSIZ);
1756       }
1757       /* Get notified at logical end of tape */
1758       mt_com.mt_op = MTEWARN;
1759       mt_com.mt_count = 1;
1760       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1761          clrerror_dev(dev, MTEWARN);
1762       }
1763    }
1764    return;
1765 #endif
1766
1767 #if HAVE_FREEBSD_OS || HAVE_OPENBSD_OS
1768    struct mtop mt_com;
1769    if (dev->min_block_size == dev->max_block_size &&
1770        dev->min_block_size == 0) {    /* variable block mode */
1771       mt_com.mt_op = MTSETBSIZ;
1772       mt_com.mt_count = 0;
1773       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1774          clrerror_dev(dev, MTSETBSIZ);
1775       }
1776    }
1777    return;
1778 #endif
1779
1780 #ifdef HAVE_SUN_OS
1781    struct mtop mt_com;
1782    if (dev->min_block_size == dev->max_block_size &&
1783        dev->min_block_size == 0) {    /* variable block mode */
1784       mt_com.mt_op = MTSRSZ;
1785       mt_com.mt_count = 0;
1786       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1787          clrerror_dev(dev, MTSRSZ);
1788       }
1789    }
1790    return;
1791 #endif
1792 }
1793
1794 static bool dev_get_os_pos(DEVICE *dev, struct mtget *mt_stat)
1795 {
1796    return dev_cap(dev, CAP_MTIOCGET) && 
1797           ioctl(dev->fd, MTIOCGET, (char *)mt_stat) == 0 &&
1798           mt_stat->mt_fileno >= 0;
1799 }