]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/dev.c
- Start removing #ifdef HAVE_TLS by sneaky tricks.
[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
604 #if defined (__digital__) && defined (__unix__)
605    return fsf_dev(dev, dev->VolCatInfo.VolCatFiles);
606 #endif
607
608    Dmsg0(29, "eod_dev\n");
609    if (dev->at_eot()) {
610       return true;
611    }
612    dev->state &= ~(ST_EOF);  /* remove EOF flags */
613    dev->block_num = dev->file = 0;
614    dev->file_size = 0;
615    dev->file_addr = 0;
616    if (dev->state & (ST_FIFO | ST_PROG)) {
617       return true;
618    }
619    if (!dev->is_tape()) {
620       pos = lseek_dev(dev, (off_t)0, SEEK_END);
621 //    Dmsg1(100, "====== Seek to %lld\n", pos);
622       if (pos >= 0) {
623          update_pos_dev(dev);
624          dev->state |= ST_EOT;
625          return true;
626       }
627       dev->dev_errno = errno;
628       berrno be;
629       Mmsg2(dev->errmsg, _("lseek_dev error on %s. ERR=%s.\n"),
630              dev->print_name(), be.strerror());
631       return false;
632    }
633 #ifdef MTEOM
634    if (dev_cap(dev, CAP_FASTFSF) && !dev_cap(dev, CAP_EOM)) {
635       Dmsg0(100,"Using FAST FSF for EOM\n");
636       /* If unknown position, rewind */
637       if (!dev_get_os_pos(dev, &mt_stat)) {
638         if (!rewind_dev(dev)) {
639           return false;
640         }
641       }
642       mt_com.mt_op = MTFSF;
643       /*
644        * ***FIXME*** fix code to handle case that INT16_MAX is
645        *   not large enough.
646        */
647       mt_com.mt_count = INT16_MAX;    /* use big positive number */
648       if (mt_com.mt_count < 0) {
649          mt_com.mt_count = INT16_MAX; /* brain damaged system */
650       }
651    }
652
653    if (dev_cap(dev, CAP_MTIOCGET) && (dev_cap(dev, CAP_FASTFSF) || dev_cap(dev, CAP_EOM))) {
654       if (dev_cap(dev, CAP_EOM)) {
655          Dmsg0(100,"Using EOM for EOM\n");
656          mt_com.mt_op = MTEOM;
657          mt_com.mt_count = 1;
658       }
659
660       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
661          berrno be;
662          clrerror_dev(dev, mt_com.mt_op);
663          Dmsg1(50, "ioctl error: %s\n", be.strerror());
664          update_pos_dev(dev);
665          Mmsg2(dev->errmsg, _("ioctl MTEOM error on %s. ERR=%s.\n"),
666             dev->print_name(), be.strerror());
667          return false;
668       }
669
670       if (!dev_get_os_pos(dev, &mt_stat)) {
671          berrno be;
672          clrerror_dev(dev, -1);
673          Mmsg2(dev->errmsg, _("ioctl MTIOCGET error on %s. ERR=%s.\n"),
674             dev->print_name(), be.strerror());
675          return false;
676       }
677       Dmsg2(100, "EOD file=%d block=%d\n", mt_stat.mt_fileno, mt_stat.mt_blkno);
678       dev->set_eof();
679       dev->file = mt_stat.mt_fileno;
680    } else {
681 #else
682    {
683 #endif
684       /*
685        * Rewind then use FSF until EOT reached
686        */
687       if (!rewind_dev(dev)) {
688          return false;
689       }
690       /*
691        * Move file by file to the end of the tape
692        */
693       int file_num;
694       for (file_num=dev->file; !dev->at_eot(); file_num++) {
695          Dmsg0(200, "eod_dev: doing fsf 1\n");
696          if (!fsf_dev(dev, 1)) {
697             Dmsg0(200, "fsf_dev error.\n");
698             return false;
699          }
700          /*
701           * Avoid infinite loop. ***FIXME*** possibly add code
702           *   to set EOD or to turn off CAP_FASTFSF if on.
703           */
704          if (file_num == (int)dev->file) {
705             struct mtget mt_stat;
706             Dmsg1(100, "fsf_dev did not advance from file %d\n", file_num);
707             if (dev_get_os_pos(dev, &mt_stat)) {
708                Dmsg2(100, "Adjust file from %d to %d\n", dev->file , mt_stat.mt_fileno);
709                dev->set_eof();
710                dev->file = mt_stat.mt_fileno;
711             }
712             return false;
713          }
714       }
715    }
716    /*
717     * Some drivers leave us after second EOF when doing
718     * MTEOM, so we must backup so that appending overwrites
719     * the second EOF.
720     */
721    if (dev_cap(dev, CAP_BSFATEOM)) {
722       struct mtget mt_stat;
723       /* Backup over EOF */
724       ok = bsf_dev(dev, 1);
725       /* If BSF worked and fileno is known (not -1), set file */
726       if (dev_get_os_pos(dev, &mt_stat)) {
727          Dmsg2(100, "BSFATEOF adjust file from %d to %d\n", dev->file , mt_stat.mt_fileno);
728          dev->file = mt_stat.mt_fileno;
729       } else {
730          dev->file++;                 /* wing it -- not correct on all OSes */
731       }
732    } else {
733       update_pos_dev(dev);                   /* update position */
734    }
735    Dmsg1(200, "EOD dev->file=%d\n", dev->file);
736    return ok;
737 }
738
739 /*
740  * Set the position of the device -- only for files
741  *   For other devices, there is no generic way to do it.
742  *  Returns: true  on succes
743  *           false on error
744  */
745 bool update_pos_dev(DEVICE *dev)
746 {
747    off_t pos;
748    bool ok = true;
749
750    if (dev->fd < 0) {
751       dev->dev_errno = EBADF;
752       Mmsg0(dev->errmsg, _("Bad device call. Device not open\n"));
753       Emsg0(M_FATAL, 0, dev->errmsg);
754       return false;
755    }
756
757    /* Find out where we are */
758    if (dev->is_file()) {
759       dev->file = 0;
760       dev->file_addr = 0;
761       pos = lseek_dev(dev, (off_t)0, SEEK_CUR);
762       if (pos < 0) {
763          berrno be;
764          dev->dev_errno = errno;
765          Pmsg1(000, "Seek error: ERR=%s\n", be.strerror());
766          Mmsg2(dev->errmsg, _("lseek_dev error on %s. ERR=%s.\n"),
767             dev->print_name(), be.strerror());
768          ok = false;
769       } else {
770          dev->file_addr = pos;
771       }
772    }
773    return ok;
774 }
775
776
777 /*
778  * Return the status of the device.  This was meant
779  * to be a generic routine. Unfortunately, it doesn't
780  * seem possible (at least I do not know how to do it
781  * currently), which means that for the moment, this
782  * routine has very little value.
783  *
784  *   Returns: status
785  */
786 uint32_t status_dev(DEVICE *dev)
787 {
788    struct mtget mt_stat;
789    uint32_t stat = 0;
790
791    if (dev->state & (ST_EOT | ST_WEOT)) {
792       stat |= BMT_EOD;
793       Pmsg0(-20, " EOD");
794    }
795    if (dev->state & ST_EOF) {
796       stat |= BMT_EOF;
797       Pmsg0(-20, " EOF");
798    }
799    if (dev->is_tape()) {
800       stat |= BMT_TAPE;
801       Pmsg0(-20," Bacula status:");
802       Pmsg2(-20," file=%d block=%d\n", dev->file, dev->block_num);
803       if (ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) < 0) {
804          berrno be;
805          dev->dev_errno = errno;
806          Mmsg2(dev->errmsg, _("ioctl MTIOCGET error on %s. ERR=%s.\n"),
807             dev->print_name(), be.strerror());
808          return 0;
809       }
810       Pmsg0(-20, " Device status:");
811
812 #if defined(HAVE_LINUX_OS)
813       if (GMT_EOF(mt_stat.mt_gstat)) {
814          stat |= BMT_EOF;
815          Pmsg0(-20, " EOF");
816       }
817       if (GMT_BOT(mt_stat.mt_gstat)) {
818          stat |= BMT_BOT;
819          Pmsg0(-20, " BOT");
820       }
821       if (GMT_EOT(mt_stat.mt_gstat)) {
822          stat |= BMT_EOT;
823          Pmsg0(-20, " EOT");
824       }
825       if (GMT_SM(mt_stat.mt_gstat)) {
826          stat |= BMT_SM;
827          Pmsg0(-20, " SM");
828       }
829       if (GMT_EOD(mt_stat.mt_gstat)) {
830          stat |= BMT_EOD;
831          Pmsg0(-20, " EOD");
832       }
833       if (GMT_WR_PROT(mt_stat.mt_gstat)) {
834          stat |= BMT_WR_PROT;
835          Pmsg0(-20, " WR_PROT");
836       }
837       if (GMT_ONLINE(mt_stat.mt_gstat)) {
838          stat |= BMT_ONLINE;
839          Pmsg0(-20, " ONLINE");
840       }
841       if (GMT_DR_OPEN(mt_stat.mt_gstat)) {
842          stat |= BMT_DR_OPEN;
843          Pmsg0(-20, " DR_OPEN");
844       }
845       if (GMT_IM_REP_EN(mt_stat.mt_gstat)) {
846          stat |= BMT_IM_REP_EN;
847          Pmsg0(-20, " IM_REP_EN");
848       }
849 #endif /* !SunOS && !OSF */
850       if (dev_cap(dev, CAP_MTIOCGET)) {
851          Pmsg2(-20, " file=%d block=%d\n", mt_stat.mt_fileno, mt_stat.mt_blkno);
852       } else {
853          Pmsg2(-20, " file=%d block=%d\n", -1, -1);
854       }
855    } else {
856       stat |= BMT_ONLINE | BMT_BOT;
857    }
858    return stat;
859 }
860
861
862 /*
863  * Load medium in device
864  *  Returns: true  on success
865  *           false on failure
866  */
867 bool load_dev(DEVICE *dev)
868 {
869 #ifdef MTLOAD
870    struct mtop mt_com;
871 #endif
872
873    if (dev->fd < 0) {
874       dev->dev_errno = EBADF;
875       Mmsg0(dev->errmsg, _("Bad call to load_dev. Device not open\n"));
876       Emsg0(M_FATAL, 0, dev->errmsg);
877       return false;
878    }
879    if (!(dev->is_tape())) {
880       return true;
881    }
882 #ifndef MTLOAD
883    Dmsg0(200, "stored: MTLOAD command not available\n");
884    berrno be;
885    dev->dev_errno = ENOTTY;           /* function not available */
886    Mmsg2(dev->errmsg, _("ioctl MTLOAD error on %s. ERR=%s.\n"),
887          dev->print_name(), be.strerror());
888    return false;
889 #else
890
891    dev->block_num = dev->file = 0;
892    dev->file_size = 0;
893    dev->file_addr = 0;
894    mt_com.mt_op = MTLOAD;
895    mt_com.mt_count = 1;
896    if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
897       berrno be;
898       dev->dev_errno = errno;
899       Mmsg2(dev->errmsg, _("ioctl MTLOAD error on %s. ERR=%s.\n"),
900          dev->print_name(), be.strerror());
901       return false;
902    }
903    return true;
904 #endif
905 }
906
907 /*
908  * Rewind device and put it offline
909  *  Returns: true  on success
910  *           false on failure
911  */
912 bool offline_dev(DEVICE *dev)
913 {
914    struct mtop mt_com;
915
916    if (dev->fd < 0) {
917       dev->dev_errno = EBADF;
918       Mmsg0(dev->errmsg, _("Bad call to offline_dev. Device not open\n"));
919       Emsg0(M_FATAL, 0, dev->errmsg);
920       return false;
921    }
922    if (!(dev->is_tape())) {
923       return true;
924    }
925
926    dev->state &= ~(ST_APPEND|ST_READ|ST_EOT|ST_EOF|ST_WEOT);  /* remove EOF/EOT flags */
927    dev->block_num = dev->file = 0;
928    dev->file_size = 0;
929    dev->file_addr = 0;
930    dev->part = 0;
931 #ifdef MTUNLOCK
932    mt_com.mt_op = MTUNLOCK;
933    mt_com.mt_count = 1;
934    ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
935 #endif
936    mt_com.mt_op = MTOFFL;
937    mt_com.mt_count = 1;
938    if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
939       berrno be;
940       dev->dev_errno = errno;
941       Mmsg2(dev->errmsg, _("ioctl MTOFFL error on %s. ERR=%s.\n"),
942          dev->print_name(), be.strerror());
943       return false;
944    }
945    Dmsg1(100, "Offlined device %s\n", dev->print_name());
946    return true;
947 }
948
949 bool offline_or_rewind_dev(DEVICE *dev)
950 {
951    if (dev->fd < 0) {
952       return false;
953    }
954    if (dev_cap(dev, CAP_OFFLINEUNMOUNT)) {
955       return offline_dev(dev);
956    } else {
957    /*
958     * Note, this rewind probably should not be here (it wasn't
959     *  in prior versions of Bacula), but on FreeBSD, this is
960     *  needed in the case the tape was "frozen" due to an error
961     *  such as backspacing after writing and EOF. If it is not
962     *  done, all future references to the drive get and I/O error.
963     */
964       clrerror_dev(dev, MTREW);
965       return rewind_dev(dev);
966    }
967 }
968
969 /*
970  * Foward space a file
971  *   Returns: true  on success
972  *            false on failure
973  */
974 bool
975 fsf_dev(DEVICE *dev, int num)
976 {
977    struct mtget mt_stat;
978    struct mtop mt_com;
979    int stat = 0;
980
981    if (dev->fd < 0) {
982       dev->dev_errno = EBADF;
983       Mmsg0(dev->errmsg, _("Bad call to fsf_dev. Device not open\n"));
984       Emsg0(M_FATAL, 0, dev->errmsg);
985       return false;
986    }
987
988    if (!dev->is_tape()) {
989       return true;
990    }
991    if (dev->state & ST_EOT) {
992       dev->dev_errno = 0;
993       Mmsg1(dev->errmsg, _("Device %s at End of Tape.\n"), dev->print_name());
994       return false;
995    }
996    if (dev->state & ST_EOF) {
997       Dmsg0(200, "ST_EOF set on entry to FSF\n");
998    }
999
1000    Dmsg0(100, "fsf_dev\n");
1001    dev->block_num = 0;
1002    /*
1003     * If Fast forward space file is set, then we
1004     *  use MTFSF to forward space and MTIOCGET
1005     *  to get the file position. We assume that
1006     *  the SCSI driver will ensure that we do not
1007     *  forward space past the end of the medium.
1008     */
1009    if (dev_cap(dev, CAP_FSF) && dev_cap(dev, CAP_MTIOCGET) && dev_cap(dev, CAP_FASTFSF)) {
1010       mt_com.mt_op = MTFSF;
1011       mt_com.mt_count = num;
1012       stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1013       if (stat < 0 || !dev_get_os_pos(dev, &mt_stat)) {
1014          berrno be;
1015          dev->state |= ST_EOT;
1016          Dmsg0(200, "Set ST_EOT\n");
1017          clrerror_dev(dev, MTFSF);
1018          Mmsg2(dev->errmsg, _("ioctl MTFSF error on %s. ERR=%s.\n"),
1019             dev->print_name(), be.strerror());
1020          Dmsg1(200, "%s", dev->errmsg);
1021          return false;
1022       }
1023       Dmsg2(200, "fsf file=%d block=%d\n", mt_stat.mt_fileno, mt_stat.mt_blkno);
1024       dev->set_eof();
1025       dev->file = mt_stat.mt_fileno;
1026       return true;
1027
1028    /*
1029     * Here if CAP_FSF is set, and virtually all drives
1030     *  these days support it, we read a record, then forward
1031     *  space one file. Using this procedure, which is slow,
1032     *  is the only way we can be sure that we don't read
1033     *  two consecutive EOF marks, which means End of Data.
1034     */
1035    } else if (dev_cap(dev, CAP_FSF)) {
1036       POOLMEM *rbuf;
1037       int rbuf_len;
1038       Dmsg0(200, "FSF has cap_fsf\n");
1039       if (dev->max_block_size == 0) {
1040          rbuf_len = DEFAULT_BLOCK_SIZE;
1041       } else {
1042          rbuf_len = dev->max_block_size;
1043       }
1044       rbuf = get_memory(rbuf_len);
1045       mt_com.mt_op = MTFSF;
1046       mt_com.mt_count = 1;
1047       while (num-- && !(dev->state & ST_EOT)) {
1048          Dmsg0(100, "Doing read before fsf\n");
1049          if ((stat = read(dev->fd, (char *)rbuf, rbuf_len)) < 0) {
1050             if (errno == ENOMEM) {     /* tape record exceeds buf len */
1051                stat = rbuf_len;        /* This is OK */
1052             } else {
1053                berrno be;
1054                dev->state |= ST_EOT;
1055                clrerror_dev(dev, -1);
1056                Dmsg2(100, "Set ST_EOT read errno=%d. ERR=%s\n", dev->dev_errno,
1057                   be.strerror());
1058                Mmsg2(dev->errmsg, _("read error on %s. ERR=%s.\n"),
1059                   dev->print_name(), be.strerror());
1060                Dmsg1(100, "%s", dev->errmsg);
1061                break;
1062             }
1063          }
1064          if (stat == 0) {                /* EOF */
1065             update_pos_dev(dev);
1066             Dmsg1(100, "End of File mark from read. File=%d\n", dev->file+1);
1067             /* Two reads of zero means end of tape */
1068             if (dev->state & ST_EOF) {
1069                dev->state |= ST_EOT;
1070                Dmsg0(100, "Set ST_EOT\n");
1071                break;
1072             } else {
1073                dev->set_eof();
1074                continue;
1075             }
1076          } else {                        /* Got data */
1077             dev->state &= ~(ST_EOF|ST_EOT);
1078          }
1079
1080          Dmsg0(100, "Doing MTFSF\n");
1081          stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1082          if (stat < 0) {                 /* error => EOT */
1083             berrno be;
1084             dev->state |= ST_EOT;
1085             Dmsg0(100, "Set ST_EOT\n");
1086             clrerror_dev(dev, MTFSF);
1087             Mmsg2(dev->errmsg, _("ioctl MTFSF error on %s. ERR=%s.\n"),
1088                dev->print_name(), be.strerror());
1089             Dmsg0(100, "Got < 0 for MTFSF\n");
1090             Dmsg1(100, "%s", dev->errmsg);
1091          } else {
1092             dev->set_eof();
1093          }
1094       }
1095       free_memory(rbuf);
1096
1097    /*
1098     * No FSF, so use FSR to simulate it
1099     */
1100    } else {
1101       Dmsg0(200, "Doing FSR for FSF\n");
1102       while (num-- && !(dev->state & ST_EOT)) {
1103          dev->fsr(INT32_MAX);    /* returns -1 on EOF or EOT */
1104       }
1105       if (dev->state & ST_EOT) {
1106          dev->dev_errno = 0;
1107          Mmsg1(dev->errmsg, _("Device %s at End of Tape.\n"), dev->print_name());
1108          stat = -1;
1109       } else {
1110          stat = 0;
1111       }
1112    }
1113    update_pos_dev(dev);
1114    Dmsg1(200, "Return %d from FSF\n", stat);
1115    if (dev->state & ST_EOF)
1116       Dmsg0(200, "ST_EOF set on exit FSF\n");
1117    if (dev->state & ST_EOT)
1118       Dmsg0(200, "ST_EOT set on exit FSF\n");
1119    Dmsg1(200, "Return from FSF file=%d\n", dev->file);
1120    return stat == 0;
1121 }
1122
1123 /*
1124  * Backward space a file
1125  *  Returns: false on failure
1126  *           true  on success
1127  */
1128 bool
1129 bsf_dev(DEVICE *dev, int num)
1130 {
1131    struct mtop mt_com;
1132    int stat;
1133
1134    if (dev->fd < 0) {
1135       dev->dev_errno = EBADF;
1136       Mmsg0(dev->errmsg, _("Bad call to bsf_dev. Device not open\n"));
1137       Emsg0(M_FATAL, 0, dev->errmsg);
1138       return false;
1139    }
1140
1141    if (!dev->is_tape()) {
1142       Mmsg1(dev->errmsg, _("Device %s cannot BSF because it is not a tape.\n"),
1143          dev->print_name());
1144       return false;
1145    }
1146    Dmsg0(29, "bsf_dev\n");
1147    dev->state &= ~(ST_EOT|ST_EOF);
1148    dev->file -= num;
1149    dev->file_addr = 0;
1150    dev->file_size = 0;
1151    mt_com.mt_op = MTBSF;
1152    mt_com.mt_count = num;
1153    stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1154    if (stat < 0) {
1155       berrno be;
1156       clrerror_dev(dev, MTBSF);
1157       Mmsg2(dev->errmsg, _("ioctl MTBSF error on %s. ERR=%s.\n"),
1158          dev->print_name(), be.strerror());
1159    }
1160    update_pos_dev(dev);
1161    return stat == 0;
1162 }
1163
1164
1165 /*
1166  * Foward space num records
1167  *  Returns: false on failure
1168  *           true  on success
1169  */
1170 bool DEVICE::fsr(int num)
1171 {
1172    struct mtop mt_com;
1173    int stat;
1174
1175    if (fd < 0) {
1176       dev_errno = EBADF;
1177       Mmsg0(errmsg, _("Bad call to fsr. Device not open\n"));
1178       Emsg0(M_FATAL, 0, errmsg);
1179       return false;
1180    }
1181
1182    if (!is_tape()) {
1183       return false;
1184    }
1185    if (!dev_cap(this, CAP_FSR)) {
1186       Mmsg1(errmsg, _("ioctl MTFSR not permitted on %s.\n"), print_name());
1187       return false;
1188    }
1189
1190    Dmsg1(29, "fsr %d\n", num);
1191    mt_com.mt_op = MTFSR;
1192    mt_com.mt_count = num;
1193    stat = ioctl(fd, MTIOCTOP, (char *)&mt_com);
1194    if (stat == 0) {
1195       clear_eof();
1196       block_num += num;
1197    } else {
1198       berrno be;
1199       struct mtget mt_stat;
1200       clrerror_dev(this, MTFSR);
1201       Dmsg1(100, "FSF fail: ERR=%s\n", be.strerror());
1202       if (dev_get_os_pos(this, &mt_stat)) {
1203          Dmsg4(100, "Adjust from %d:%d to %d:%d\n", file,
1204             block_num, mt_stat.mt_fileno, mt_stat.mt_blkno);
1205          file = mt_stat.mt_fileno;
1206          block_num = mt_stat.mt_blkno;
1207       } else {
1208          if (at_eof()) {
1209             state |= ST_EOT;
1210          } else {
1211             set_eof();
1212          }
1213       }
1214       Mmsg3(errmsg, _("ioctl MTFSR %d error on %s. ERR=%s.\n"),
1215          num, print_name(), be.strerror());
1216    }
1217    update_pos_dev(this);
1218    return stat == 0;
1219 }
1220
1221 /*
1222  * Backward space a record
1223  *   Returns:  false on failure
1224  *             true  on success
1225  */
1226 bool
1227 bsr_dev(DEVICE *dev, int num)
1228 {
1229    struct mtop mt_com;
1230    int stat;
1231
1232    if (dev->fd < 0) {
1233       dev->dev_errno = EBADF;
1234       Mmsg0(dev->errmsg, _("Bad call to bsr_dev. Device not open\n"));
1235       Emsg0(M_FATAL, 0, dev->errmsg);
1236       return false;
1237    }
1238
1239    if (!dev->is_tape()) {
1240       return false;
1241    }
1242
1243    if (!dev_cap(dev, CAP_BSR)) {
1244       Mmsg1(dev->errmsg, _("ioctl MTBSR not permitted on %s.\n"), dev->print_name());
1245       return false;
1246    }
1247
1248    Dmsg0(29, "bsr_dev\n");
1249    dev->block_num -= num;
1250    dev->state &= ~(ST_EOF|ST_EOT|ST_EOF);
1251    mt_com.mt_op = MTBSR;
1252    mt_com.mt_count = num;
1253    stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1254    if (stat < 0) {
1255       berrno be;
1256       clrerror_dev(dev, MTBSR);
1257       Mmsg2(dev->errmsg, _("ioctl MTBSR error on %s. ERR=%s.\n"),
1258          dev->print_name(), be.strerror());
1259    }
1260    update_pos_dev(dev);
1261    return stat == 0;
1262 }
1263
1264 /*
1265  * Reposition the device to file, block
1266  * Returns: false on failure
1267  *          true  on success
1268  */
1269 bool
1270 reposition_dev(DEVICE *dev, uint32_t file, uint32_t block)
1271 {
1272    if (dev->fd < 0) {
1273       dev->dev_errno = EBADF;
1274       Mmsg0(dev->errmsg, _("Bad call to reposition_dev. Device not open\n"));
1275       Emsg0(M_FATAL, 0, dev->errmsg);
1276       return false;
1277    }
1278
1279    if (!dev->is_tape()) {
1280       off_t pos = (((off_t)file)<<32) + block;
1281       Dmsg1(100, "===== lseek_dev to %d\n", (int)pos);
1282       if (lseek_dev(dev, pos, SEEK_SET) == (off_t)-1) {
1283          berrno be;
1284          dev->dev_errno = errno;
1285          Mmsg2(dev->errmsg, _("lseek_dev error on %s. ERR=%s.\n"),
1286             dev->print_name(), be.strerror());
1287          return false;
1288       }
1289       dev->file = file;
1290       dev->block_num = block;
1291       dev->file_addr = pos;
1292       return true;
1293    }
1294    Dmsg4(100, "reposition_dev from %u:%u to %u:%u\n",
1295       dev->file, dev->block_num, file, block);
1296    if (file < dev->file) {
1297       Dmsg0(100, "Rewind_dev\n");
1298       if (!rewind_dev(dev)) {
1299          return false;
1300       }
1301    }
1302    if (file > dev->file) {
1303       Dmsg1(100, "fsf %d\n", file-dev->file);
1304       if (!fsf_dev(dev, file-dev->file)) {
1305          Dmsg1(100, "fsf failed! ERR=%s\n", strerror_dev(dev));
1306          return false;
1307       }
1308       Dmsg2(100, "wanted_file=%d at_file=%d\n", file, dev->file);
1309    }
1310    if (block < dev->block_num) {
1311       Dmsg2(100, "wanted_blk=%d at_blk=%d\n", block, dev->block_num);
1312       Dmsg0(100, "bsf_dev 1\n");
1313       bsf_dev(dev, 1);
1314       Dmsg0(100, "fsf_dev 1\n");
1315       fsf_dev(dev, 1);
1316       Dmsg2(100, "wanted_blk=%d at_blk=%d\n", block, dev->block_num);
1317    }
1318    if (dev_cap(dev, CAP_POSITIONBLOCKS) && block > dev->block_num) {
1319       /* Ignore errors as Bacula can read to the correct block */
1320       Dmsg1(100, "fsr %d\n", block-dev->block_num);
1321       return dev->fsr(block-dev->block_num);
1322    }
1323    return true;
1324 }
1325
1326
1327
1328 /*
1329  * Write an end of file on the device
1330  *   Returns: 0 on success
1331  *            non-zero on failure
1332  */
1333 int
1334 weof_dev(DEVICE *dev, int num)
1335 {
1336    struct mtop mt_com;
1337    int stat;
1338    Dmsg0(29, "weof_dev\n");
1339    
1340    if (dev->fd < 0) {
1341       dev->dev_errno = EBADF;
1342       Mmsg0(dev->errmsg, _("Bad call to weof_dev. Device not open\n"));
1343       Emsg0(M_FATAL, 0, dev->errmsg);
1344       return -1;
1345    }
1346    dev->file_size = 0;
1347
1348    if (!dev->is_tape()) {
1349       return 0;
1350    }
1351    if (!dev->can_append()) {
1352       Mmsg0(dev->errmsg, _("Attempt to WEOF on non-appendable Volume\n"));
1353       Emsg0(M_FATAL, 0, dev->errmsg);
1354       return -1;
1355    }
1356       
1357    dev->state &= ~(ST_EOT | ST_EOF);  /* remove EOF/EOT flags */
1358    mt_com.mt_op = MTWEOF;
1359    mt_com.mt_count = num;
1360    stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1361    if (stat == 0) {
1362       dev->block_num = 0;
1363       dev->file += num;
1364       dev->file_addr = 0;
1365    } else {
1366       berrno be;
1367       clrerror_dev(dev, MTWEOF);
1368       if (stat == -1) {
1369          Mmsg2(dev->errmsg, _("ioctl MTWEOF error on %s. ERR=%s.\n"),
1370             dev->print_name(), be.strerror());
1371        }
1372    }
1373    return stat;
1374 }
1375
1376 /*
1377  * Return string message with last error in English
1378  *  Be careful not to call this routine from within dev.c
1379  *  while editing an Mmsg() or you will end up in a recursive
1380  *  loop creating a Segmentation Violation.
1381  */
1382 char *
1383 strerror_dev(DEVICE *dev)
1384 {
1385    return dev->errmsg;
1386 }
1387
1388
1389 /*
1390  * If implemented in system, clear the tape
1391  * error status.
1392  */
1393 void
1394 clrerror_dev(DEVICE *dev, int func)
1395 {
1396    const char *msg = NULL;
1397    struct mtget mt_stat;
1398    char buf[100];
1399
1400    dev->dev_errno = errno;         /* save errno */
1401    if (errno == EIO) {
1402       dev->VolCatInfo.VolCatErrors++;
1403    }
1404
1405    if (!dev->is_tape()) {
1406       return;
1407    }
1408    if (errno == ENOTTY || errno == ENOSYS) { /* Function not implemented */
1409       switch (func) {
1410       case -1:
1411          Emsg0(M_ABORT, 0, "Got ENOTTY on read/write!\n");
1412          break;
1413       case MTWEOF:
1414          msg = "WTWEOF";
1415          dev->capabilities &= ~CAP_EOF; /* turn off feature */
1416          break;
1417 #ifdef MTEOM
1418       case MTEOM:
1419          msg = "WTEOM";
1420          dev->capabilities &= ~CAP_EOM; /* turn off feature */
1421          break;
1422 #endif
1423       case MTFSF:
1424          msg = "MTFSF";
1425          dev->capabilities &= ~CAP_FSF; /* turn off feature */
1426          break;
1427       case MTBSF:
1428          msg = "MTBSF";
1429          dev->capabilities &= ~CAP_BSF; /* turn off feature */
1430          break;
1431       case MTFSR:
1432          msg = "MTFSR";
1433          dev->capabilities &= ~CAP_FSR; /* turn off feature */
1434          break;
1435       case MTBSR:
1436          msg = "MTBSR";
1437          dev->capabilities &= ~CAP_BSR; /* turn off feature */
1438          break;
1439       case MTREW:
1440          msg = "MTREW";
1441          break;
1442 #ifdef MTSETBLK
1443       case MTSETBLK:
1444          msg = "MTSETBLK";
1445          break;
1446 #endif
1447 #ifdef MTSETBSIZ 
1448       case MTSETBSIZ:
1449          msg = "MTSETBSIZ";
1450          break;
1451 #endif
1452 #ifdef MTSRSZ
1453       case MTSRSZ:
1454          msg = "MTSRSZ";
1455          break;
1456 #endif
1457       default:
1458          bsnprintf(buf, sizeof(buf), "unknown func code %d", func);
1459          msg = buf;
1460          break;
1461       }
1462       if (msg != NULL) {
1463          dev->dev_errno = ENOSYS;
1464          Mmsg1(dev->errmsg, _("I/O function \"%s\" not supported on this device.\n"), msg);
1465          Emsg0(M_ERROR, 0, dev->errmsg);
1466       }
1467    }
1468    /* On some systems such as NetBSD, this clears all errors */
1469    ioctl(dev->fd, MTIOCGET, (char *)&mt_stat);
1470
1471 /* Found on Linux */
1472 #ifdef MTIOCLRERR
1473 {
1474    struct mtop mt_com;
1475    mt_com.mt_op = MTIOCLRERR;
1476    mt_com.mt_count = 1;
1477    /* Clear any error condition on the tape */
1478    ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1479    Dmsg0(200, "Did MTIOCLRERR\n");
1480 }
1481 #endif
1482
1483 /* Typically on FreeBSD */
1484 #ifdef MTIOCERRSTAT
1485 {
1486    /* Read and clear SCSI error status */
1487    union mterrstat mt_errstat;
1488    Dmsg2(200, "Doing MTIOCERRSTAT errno=%d ERR=%s\n", dev->dev_errno,
1489       strerror(dev->dev_errno));
1490    ioctl(dev->fd, MTIOCERRSTAT, (char *)&mt_errstat);
1491 }
1492 #endif
1493
1494 /* Clear Subsystem Exception OSF1 */
1495 #ifdef MTCSE
1496 {
1497    struct mtop mt_com;
1498    mt_com.mt_op = MTCSE;
1499    mt_com.mt_count = 1;
1500    /* Clear any error condition on the tape */
1501    ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1502    Dmsg0(200, "Did MTCSE\n");
1503 }
1504 #endif
1505 }
1506
1507 /*
1508  * Flush buffer contents
1509  *  No longer used.
1510  */
1511 int flush_dev(DEVICE *dev)
1512 {
1513    return 1;
1514 }
1515
1516 static void do_close(DEVICE *dev)
1517 {
1518
1519    Dmsg1(29, "really close_dev %s\n", dev->print_name());
1520    if (dev->fd >= 0) {
1521       close(dev->fd);
1522    }
1523
1524    if (unmount_dev(dev, 1) < 0) {
1525       Dmsg1(0, "Cannot unmount device %s.\n", dev->print_name());
1526    }
1527    
1528    /* Remove the last part file if it is empty */
1529    if (dev->can_append() && (dev->num_parts > 0)) {
1530       struct stat statp;
1531       POOL_MEM archive_name(PM_FNAME);
1532       dev->part = dev->num_parts;
1533       get_filename(dev, dev->VolCatInfo.VolCatName, archive_name);
1534       /* Check that the part file is empty */
1535       if ((stat(archive_name.c_str(), &statp) == 0) && (statp.st_size == 0)) {
1536          unlink(archive_name.c_str());
1537       }
1538    }
1539    
1540    /* Clean up device packet so it can be reused */
1541    dev->fd = -1;
1542    dev->state &= ~(ST_OPENED|ST_LABEL|ST_READ|ST_APPEND|ST_EOT|ST_WEOT|ST_EOF);
1543    dev->label_type = B_BACULA_LABEL;
1544    dev->file = dev->block_num = 0;
1545    dev->file_size = 0;
1546    dev->file_addr = 0;
1547    dev->part = 0;
1548    dev->part_size = 0;
1549    dev->part_start = 0;
1550    dev->EndFile = dev->EndBlock = 0;
1551    memset(&dev->VolCatInfo, 0, sizeof(dev->VolCatInfo));
1552    memset(&dev->VolHdr, 0, sizeof(dev->VolHdr));
1553    if (dev->tid) {
1554       stop_thread_timer(dev->tid);
1555       dev->tid = 0;
1556    }
1557    dev->use_count = 0;
1558    dev->openmode = 0;
1559 }
1560
1561 /*
1562  * Close the device
1563  */
1564 void DEVICE::close()
1565 {
1566    /*if (fd >= 0 && use_count == 1) {*/
1567    /* No need to check if fd >= 0: it is checked again
1568     * in do_close, and do_close MUST be called for volumes
1569     * splitted in parts, even if fd == -1. */
1570    if (use_count == 1) {
1571       do_close(this);
1572    } else if (use_count > 0) {
1573       use_count--;
1574    }
1575
1576 #ifdef FULL_DEBUG
1577    ASSERT(use_count >= 0);
1578 #endif
1579 }
1580
1581
1582 bool truncate_dev(DEVICE *dev)
1583 {
1584    Dmsg1(100, "truncate_dev %s\n", dev->print_name());
1585    if (dev->is_tape()) {
1586       return true;                    /* we don't really truncate tapes */
1587       /* maybe we should rewind and write and eof ???? */
1588    }
1589    
1590    /* If there is more than one part, open the first one, and then truncate it. */
1591    if (dev->num_parts > 0) {
1592       dev->num_parts = 0;
1593       dev->VolCatInfo.VolCatParts = 0;
1594       if (open_first_part(dev) < 0) {
1595          berrno be;
1596          Mmsg1(dev->errmsg, "Unable to truncate device, because I'm unable to open the first part. ERR=%s\n", be.strerror());
1597       }
1598    }
1599    
1600    if (ftruncate(dev->fd, 0) != 0) {
1601       berrno be;
1602       Mmsg1(dev->errmsg, _("Unable to truncate device. ERR=%s\n"), be.strerror());
1603       return false;
1604    }
1605    return true;
1606 }
1607
1608 /* Return the resource name for the device */
1609 const char *DEVICE::name() const
1610 {
1611    return device->hdr.name;
1612 }
1613
1614 char *
1615 dev_vol_name(DEVICE *dev)
1616 {
1617    return dev->VolCatInfo.VolCatName;
1618 }
1619
1620 uint32_t dev_block(DEVICE *dev)
1621 {
1622    update_pos_dev(dev);
1623    return dev->block_num;
1624 }
1625
1626 uint32_t dev_file(DEVICE *dev)
1627 {
1628    update_pos_dev(dev);
1629    return dev->file;
1630 }
1631
1632 /*
1633  * Free memory allocated for the device
1634  */
1635 void
1636 term_dev(DEVICE *dev)
1637 {
1638    if (!dev) {
1639       dev->dev_errno = EBADF;
1640       Mmsg0(dev->errmsg, _("Bad call to term_dev. Device not open\n"));
1641       Emsg0(M_FATAL, 0, dev->errmsg);
1642       return;
1643    }
1644    do_close(dev);
1645    Dmsg0(29, "term_dev\n");
1646    if (dev->dev_name) {
1647       free_memory(dev->dev_name);
1648       dev->dev_name = NULL;
1649    }
1650    if (dev->prt_name) {
1651       free_memory(dev->prt_name);
1652       dev->prt_name = NULL;
1653    }
1654    if (dev->errmsg) {
1655       free_pool_memory(dev->errmsg);
1656       dev->errmsg = NULL;
1657    }
1658    pthread_mutex_destroy(&dev->mutex);
1659    pthread_cond_destroy(&dev->wait);
1660    pthread_cond_destroy(&dev->wait_next_vol);
1661    pthread_mutex_destroy(&dev->spool_mutex);
1662    rwl_destroy(&dev->lock);
1663    if (dev->attached_dcrs) {
1664       delete dev->attached_dcrs;
1665       dev->attached_dcrs = NULL;
1666    }
1667    if (dev->state & ST_MALLOC) {
1668       free_pool_memory((POOLMEM *)dev);
1669    }
1670 }
1671
1672 /*
1673  * This routine initializes the device wait timers
1674  */
1675 void init_device_wait_timers(DCR *dcr)
1676 {
1677    DEVICE *dev = dcr->dev;
1678    JCR *jcr = dcr->jcr;
1679
1680    /* ******FIXME******* put these on config variables */
1681    dev->min_wait = 60 * 60;
1682    dev->max_wait = 24 * 60 * 60;
1683    dev->max_num_wait = 9;              /* 5 waits =~ 1 day, then 1 day at a time */
1684    dev->wait_sec = dev->min_wait;
1685    dev->rem_wait_sec = dev->wait_sec;
1686    dev->num_wait = 0;
1687    dev->poll = false;
1688    dev->BadVolName[0] = 0;
1689
1690    jcr->min_wait = 60 * 60;
1691    jcr->max_wait = 24 * 60 * 60;
1692    jcr->max_num_wait = 9;              /* 5 waits =~ 1 day, then 1 day at a time */
1693    jcr->wait_sec = jcr->min_wait;
1694    jcr->rem_wait_sec = jcr->wait_sec;
1695    jcr->num_wait = 0;
1696
1697 }
1698
1699 void init_jcr_device_wait_timers(JCR *jcr)
1700 {
1701    /* ******FIXME******* put these on config variables */
1702    jcr->min_wait = 60 * 60;
1703    jcr->max_wait = 24 * 60 * 60;
1704    jcr->max_num_wait = 9;              /* 5 waits =~ 1 day, then 1 day at a time */
1705    jcr->wait_sec = jcr->min_wait;
1706    jcr->rem_wait_sec = jcr->wait_sec;
1707    jcr->num_wait = 0;
1708 }
1709
1710
1711 /*
1712  * The dev timers are used for waiting on a particular device 
1713  *
1714  * Returns: true if time doubled
1715  *          false if max time expired
1716  */
1717 bool double_dev_wait_time(DEVICE *dev)
1718 {
1719    dev->wait_sec *= 2;               /* double wait time */
1720    if (dev->wait_sec > dev->max_wait) {   /* but not longer than maxtime */
1721       dev->wait_sec = dev->max_wait;
1722    }
1723    dev->num_wait++;
1724    dev->rem_wait_sec = dev->wait_sec;
1725    if (dev->num_wait >= dev->max_num_wait) {
1726       return false;
1727    }
1728    return true;
1729 }
1730
1731
1732 void set_os_device_parameters(DEVICE *dev)
1733 {
1734 #ifdef HAVE_LINUX_OS
1735    struct mtop mt_com;
1736    if (dev->min_block_size == dev->max_block_size &&
1737        dev->min_block_size == 0) {    /* variable block mode */
1738       mt_com.mt_op = MTSETBLK;
1739       mt_com.mt_count = 0;
1740       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1741          clrerror_dev(dev, MTSETBLK);
1742       }
1743       mt_com.mt_op = MTSETDRVBUFFER;
1744       mt_com.mt_count = MT_ST_CLEARBOOLEANS;
1745       if (!dev_cap(dev, CAP_TWOEOF)) {
1746          mt_com.mt_count |= MT_ST_TWO_FM;
1747       }
1748       if (dev_cap(dev, CAP_EOM)) {
1749          mt_com.mt_count |= MT_ST_FAST_MTEOM;
1750       }
1751       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1752          clrerror_dev(dev, MTSETBLK);
1753       }
1754    }
1755    return;
1756 #endif
1757
1758 #ifdef HAVE_NETBSD_OS
1759    struct mtop mt_com;
1760    if (dev->min_block_size == dev->max_block_size &&
1761        dev->min_block_size == 0) {    /* variable block mode */
1762       mt_com.mt_op = MTSETBSIZ;
1763       mt_com.mt_count = 0;
1764       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1765          clrerror_dev(dev, MTSETBSIZ);
1766       }
1767       /* Get notified at logical end of tape */
1768       mt_com.mt_op = MTEWARN;
1769       mt_com.mt_count = 1;
1770       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1771          clrerror_dev(dev, MTEWARN);
1772       }
1773    }
1774    return;
1775 #endif
1776
1777 #if HAVE_FREEBSD_OS || HAVE_OPENBSD_OS
1778    struct mtop mt_com;
1779    if (dev->min_block_size == dev->max_block_size &&
1780        dev->min_block_size == 0) {    /* variable block mode */
1781       mt_com.mt_op = MTSETBSIZ;
1782       mt_com.mt_count = 0;
1783       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1784          clrerror_dev(dev, MTSETBSIZ);
1785       }
1786    }
1787    return;
1788 #endif
1789
1790 #ifdef HAVE_SUN_OS
1791    struct mtop mt_com;
1792    if (dev->min_block_size == dev->max_block_size &&
1793        dev->min_block_size == 0) {    /* variable block mode */
1794       mt_com.mt_op = MTSRSZ;
1795       mt_com.mt_count = 0;
1796       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1797          clrerror_dev(dev, MTSRSZ);
1798       }
1799    }
1800    return;
1801 #endif
1802 }
1803
1804 static bool dev_get_os_pos(DEVICE *dev, struct mtget *mt_stat)
1805 {
1806    return dev_cap(dev, CAP_MTIOCGET) && 
1807           ioctl(dev->fd, MTIOCGET, (char *)mt_stat) == 0 &&
1808           mt_stat->mt_fileno >= 0;
1809 }