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