]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/dev.c
Update copyright
[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 may 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    Bacula® - The Network Backup Solution
33
34    Copyright (C) 2000-2006 Free Software Foundation Europe e.V.
35
36    The main author of Bacula is Kern Sibbald, with contributions from
37    many others, a complete list can be found in the file AUTHORS.
38    This program is Free Software; you can redistribute it and/or
39    modify it under the terms of version two of the GNU General Public
40    License as published by the Free Software Foundation plus additions
41    that are listed in the file LICENSE.
42
43    This program is distributed in the hope that it will be useful, but
44    WITHOUT ANY WARRANTY; without even the implied warranty of
45    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
46    General Public License for more details.
47
48    You should have received a copy of the GNU General Public License
49    along with this program; if not, write to the Free Software
50    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
51    02110-1301, USA.
52
53    Bacula® is a registered trademark of John Walker.
54    The licensor of Bacula is the Free Software Foundation Europe
55    (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich,
56    Switzerland, email:ftf@fsfeurope.org.
57 */
58
59 /*
60  * Handling I/O errors and end of tape conditions are a bit tricky.
61  * This is how it is currently done when writting.
62  * On either an I/O error or end of tape,
63  * we will stop writing on the physical device (no I/O recovery is
64  * attempted at least in this daemon). The state flag will be sent
65  * to include ST_EOT, which is ephemeral, and ST_WEOT, which is
66  * persistent. Lots of routines clear ST_EOT, but ST_WEOT is
67  * cleared only when the problem goes away.  Now when ST_WEOT
68  * is set all calls to write_block_to_device() call the fix_up
69  * routine. In addition, all threads are blocked
70  * from writing on the tape by calling lock_dev(), and thread other
71  * than the first thread to hit the EOT will block on a condition
72  * variable. The first thread to hit the EOT will continue to
73  * be able to read and write the tape (he sort of tunnels through
74  * the locking mechanism -- see lock_dev() for details).
75  *
76  * Now presumably somewhere higher in the chain of command
77  * (device.c), someone will notice the EOT condition and
78  * get a new tape up, get the tape label read, and mark
79  * the label for rewriting. Then this higher level routine
80  * will write the unwritten buffer to the new volume.
81  * Finally, he will release
82  * any blocked threads by doing a broadcast on the condition
83  * variable.  At that point, we should be totally back in
84  * business with no lost data.
85  */
86
87
88 #include "bacula.h"
89 #include "stored.h"
90
91 #ifndef O_NONBLOCK 
92 #define O_NONBLOCK 0
93 #endif
94
95 /* Forward referenced functions */
96 void set_os_device_parameters(DCR *dcr);   
97 static bool dev_get_os_pos(DEVICE *dev, struct mtget *mt_stat);
98 static char *mode_to_str(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, DEVRES *device)
113 {
114    struct stat statp;
115    int errstat;
116    DCR *dcr = NULL;
117    DEVICE *dev;
118
119
120    /* If no device type specified, try to guess */
121    if (!device->dev_type) {
122       /* Check that device is available */
123       if (stat(device->device_name, &statp) < 0) {
124          berrno be;
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       if (S_ISDIR(statp.st_mode)) {
130          device->dev_type = B_FILE_DEV;
131       } else if (S_ISCHR(statp.st_mode)) {
132          device->dev_type = B_TAPE_DEV;
133       } else if (S_ISFIFO(statp.st_mode)) {
134          device->dev_type = B_FIFO_DEV;
135       } else if (!(device->cap_bits & CAP_REQMOUNT)) {
136          Jmsg2(jcr, M_ERROR, 0, _("%s is an unknown device type. Must be tape or directory\n"
137                " or have RequiresMount=yes for DVD. st_mode=%x\n"),
138             device->device_name, statp.st_mode);
139          return NULL;
140       } else {
141          device->dev_type = B_DVD_DEV;
142       }
143    }
144
145    dev = (DEVICE *)malloc(sizeof(DEVICE));
146    memset(dev, 0, sizeof(DEVICE));
147    dev->Slot = -1;       /* unknown */
148
149    /* Copy user supplied device parameters from Resource */
150    dev->dev_name = get_memory(strlen(device->device_name)+1);
151    pm_strcpy(dev->dev_name, device->device_name);
152    dev->prt_name = get_memory(strlen(device->device_name) + strlen(device->hdr.name) + 20);
153    /* We edit "Resource-name" (physical-name) */
154    Mmsg(dev->prt_name, "\"%s\" (%s)", device->hdr.name, device->device_name);
155    Dmsg1(400, "Allocate dev=%s\n", dev->print_name());
156    dev->capabilities = device->cap_bits;
157    dev->min_block_size = device->min_block_size;
158    dev->max_block_size = device->max_block_size;
159    dev->max_volume_size = device->max_volume_size;
160    dev->max_file_size = device->max_file_size;
161    dev->volume_capacity = device->volume_capacity;
162    dev->max_rewind_wait = device->max_rewind_wait;
163    dev->max_open_wait = device->max_open_wait;
164    dev->max_open_vols = device->max_open_vols;
165    dev->vol_poll_interval = device->vol_poll_interval;
166    dev->max_spool_size = device->max_spool_size;
167    dev->drive_index = device->drive_index;
168    dev->autoselect = device->autoselect;
169    dev->dev_type = device->dev_type;
170    if (dev->is_tape()) { /* No parts on tapes */
171       dev->max_part_size = 0;
172    } else {
173       dev->max_part_size = device->max_part_size;
174    }
175    /* Sanity check */
176    if (dev->vol_poll_interval && dev->vol_poll_interval < 60) {
177       dev->vol_poll_interval = 60;
178    }
179    /* Link the dev and device structures together */
180    dev->device = device;
181    device->dev = dev;
182
183    if (dev->is_fifo()) {
184       dev->capabilities |= CAP_STREAM; /* set stream device */
185    }
186
187    /* If the device requires mount :
188     * - Check that the mount point is available 
189     * - Check that (un)mount commands are defined
190     */
191    if ((dev->is_file() || dev->is_dvd()) && dev->requires_mount()) {
192       if (!device->mount_point || stat(device->mount_point, &statp) < 0) {
193          berrno be;
194          dev->dev_errno = errno;
195          Jmsg2(jcr, M_ERROR, 0, _("Unable to stat mount point %s: ERR=%s\n"), 
196             device->mount_point, be.strerror());
197          return NULL;
198       }
199    }
200    if (dev->is_dvd()) {
201       if (!device->mount_command || !device->unmount_command) {
202          Jmsg0(jcr, M_ERROR_TERM, 0, _("Mount and unmount commands must defined for a device which requires mount.\n"));
203       }
204       if (!device->write_part_command) {
205          Jmsg0(jcr, M_ERROR_TERM, 0, _("Write part command must be defined for a device which requires mount.\n"));
206       }
207    }
208
209    if (dev->max_block_size > 1000000) {
210       Jmsg3(jcr, M_ERROR, 0, _("Block size %u on device %s is too large, using default %u\n"),
211          dev->max_block_size, dev->print_name(), DEFAULT_BLOCK_SIZE);
212       dev->max_block_size = 0;
213    }
214    if (dev->max_block_size % TAPE_BSIZE != 0) {
215       Jmsg2(jcr, M_WARNING, 0, _("Max block size %u not multiple of device %s block size.\n"),
216          dev->max_block_size, dev->print_name());
217    }
218
219    dev->errmsg = get_pool_memory(PM_EMSG);
220    *dev->errmsg = 0;
221
222    if ((errstat = pthread_mutex_init(&dev->mutex, NULL)) != 0) {
223       berrno be;
224       dev->dev_errno = errstat;
225       Mmsg1(dev->errmsg, _("Unable to init mutex: ERR=%s\n"), be.strerror(errstat));
226       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
227    }
228    if ((errstat = pthread_cond_init(&dev->wait, NULL)) != 0) {
229       berrno be;
230       dev->dev_errno = errstat;
231       Mmsg1(dev->errmsg, _("Unable to init cond variable: ERR=%s\n"), be.strerror(errstat));
232       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
233    }
234    if ((errstat = pthread_cond_init(&dev->wait_next_vol, NULL)) != 0) {
235       berrno be;
236       dev->dev_errno = errstat;
237       Mmsg1(dev->errmsg, _("Unable to init cond variable: ERR=%s\n"), be.strerror(errstat));
238       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
239    }
240    if ((errstat = pthread_mutex_init(&dev->spool_mutex, NULL)) != 0) {
241       berrno be;
242       dev->dev_errno = errstat;
243       Mmsg1(dev->errmsg, _("Unable to init mutex: ERR=%s\n"), be.strerror(errstat));
244       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
245    }
246    if ((errstat = rwl_init(&dev->lock)) != 0) {
247       berrno be;
248       dev->dev_errno = errstat;
249       Mmsg1(dev->errmsg, _("Unable to init mutex: ERR=%s\n"), be.strerror(errstat));
250       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
251    }
252
253    dev->clear_opened();
254    dev->attached_dcrs = New(dlist(dcr, &dcr->dev_link));
255    Dmsg2(29, "init_dev: tape=%d dev_name=%s\n", dev->is_tape(), dev->dev_name);
256    
257    return dev;
258 }
259
260 /*
261  * Open the device with the operating system and
262  * initialize buffer pointers.
263  *
264  * Returns:  -1  on error
265  *           fd  on success
266  *
267  * Note, for a tape, the VolName is the name we give to the
268  *    volume (not really used here), but for a file, the
269  *    VolName represents the name of the file to be created/opened.
270  *    In the case of a file, the full name is the device name
271  *    (archive_name) with the VolName concatenated.
272  */
273 int
274 DEVICE::open(DCR *dcr, int omode)
275 {
276    int preserve = 0;
277    if (is_open()) {
278       if (openmode == omode) {
279          return fd;
280       } else {
281          if (is_tape()) {
282             tape_close(fd);
283          } else {
284             ::close(fd);
285          }
286          clear_opened();
287          Dmsg0(100, "Close fd for mode change.\n");
288          preserve = state & (ST_LABEL|ST_APPEND|ST_READ);
289       }
290    }
291    if (dcr) {
292       bstrncpy(VolCatInfo.VolCatName, dcr->VolumeName, sizeof(VolCatInfo.VolCatName));
293    }
294
295    Dmsg4(29, "open dev: type=%d dev_name=%s vol=%s mode=%s\n", dev_type,
296          print_name(), VolCatInfo.VolCatName, mode_to_str(omode));
297    state &= ~(ST_LABEL|ST_APPEND|ST_READ|ST_EOT|ST_WEOT|ST_EOF);
298    Slot = -1;          /* unknown slot */
299    label_type = B_BACULA_LABEL;
300    if (is_tape() || is_fifo()) {
301       open_tape_device(dcr, omode);
302    } else if (is_dvd()) {
303       Dmsg1(100, "call open_dvd_device mode=%s\n", mode_to_str(omode));
304       open_dvd_device(dcr, omode);
305    } else {
306       Dmsg1(100, "call open_file_device mode=%s\n", mode_to_str(omode));
307       open_file_device(dcr, omode);
308    }
309    state |= preserve;                 /* reset any important state info */
310    Dmsg2(100, "preserve=0x%x fd=%d\n", preserve, fd);
311    return fd;
312 }
313
314 void DEVICE::set_mode(int new_mode) 
315 {
316    switch (new_mode) {
317    case CREATE_READ_WRITE:
318       mode = O_CREAT | O_RDWR | O_BINARY;
319       break;
320    case OPEN_READ_WRITE:
321       mode = O_RDWR | O_BINARY;
322       break;
323    case OPEN_READ_ONLY:
324       mode = O_RDONLY | O_BINARY;
325       break;
326    case OPEN_WRITE_ONLY:
327       mode = O_WRONLY | O_BINARY;
328       break;
329    default:
330       Emsg0(M_ABORT, 0, _("Illegal mode given to open dev.\n"));
331    }
332 }
333
334 /*
335  */
336 void DEVICE::open_tape_device(DCR *dcr, int omode) 
337 {
338    file_size = 0;
339    int timeout = max_open_wait;
340    struct mtop mt_com;
341    utime_t start_time = time(NULL);
342
343
344    Dmsg0(29, "Open dev: device is tape\n");
345
346    get_autochanger_loaded_slot(dcr);
347
348    openmode = omode;
349    set_mode(omode);
350
351    if (timeout < 1) {
352       timeout = 1;
353    }
354    errno = 0;
355    if (is_fifo() && timeout) {
356       /* Set open timer */
357       tid = start_thread_timer(pthread_self(), timeout);
358    }
359    Dmsg2(100, "Try open %s mode=%s\n", print_name(), mode_to_str(omode));
360 #if defined(HAVE_WIN32)
361
362    /*   Windows Code */
363    if ((fd = tape_open(dev_name, mode)) < 0) {
364       dev_errno = errno;
365    }
366
367 #else
368
369    /*  UNIX  Code */
370    /* If busy retry each second for max_open_wait seconds */
371    for ( ;; ) {
372       /* Try non-blocking open */
373       fd = ::open(dev_name, mode+O_NONBLOCK);
374       if (fd < 0) {
375          berrno be;
376          dev_errno = errno;
377          Dmsg5(050, "Open error on %s omode=%d mode=%x errno=%d: ERR=%s\n", 
378               print_name(), omode, mode, errno, be.strerror());
379       } else {
380          /* Tape open, now rewind it */
381          Dmsg0(050, "Rewind after open\n");
382          mt_com.mt_op = MTREW;
383          mt_com.mt_count = 1;
384          if (ioctl(fd, MTIOCTOP, (char *)&mt_com) < 0) {
385             berrno be;
386             dev_errno = errno;           /* set error status from rewind */
387             ::close(fd);
388             clear_opened();
389             Dmsg2(100, "Rewind error on %s close: ERR=%s\n", print_name(),
390                   be.strerror(dev_errno));
391             /* If we get busy, device is probably rewinding, try again */
392             if (dev_errno != EBUSY) {
393                break;                    /* error -- no medium */
394             }
395          } else {
396             /* Got fd and rewind worked, so we must have medium in drive */
397             ::close(fd);
398             fd = ::open(dev_name, mode);  /* open normally */
399             if (fd < 0) {
400                berrno be;
401                dev_errno = errno;
402                Dmsg5(050, "Open error on %s omode=%d mode=%x errno=%d: ERR=%s\n", 
403                      print_name(), omode, mode, errno, be.strerror());
404                break;
405             }
406             dev_errno = 0;
407             lock_door();
408             set_os_device_parameters(dcr);       /* do system dependent stuff */
409             break;                               /* Successfully opened and rewound */
410          }
411       }
412       bmicrosleep(5, 0);
413       /* Exceed wait time ? */
414       if (time(NULL) - start_time >= max_open_wait) {
415          break;                       /* yes, get out */
416       }
417    }
418 #endif
419
420    if (!is_open()) {
421       berrno be;
422       Mmsg2(errmsg, _("Unable to open device %s: ERR=%s\n"),
423             print_name(), be.strerror(dev_errno));
424       Dmsg1(100, "%s", errmsg);
425    }
426
427    /* Stop any open() timer we started */
428    if (tid) {
429       stop_thread_timer(tid);
430       tid = 0;
431    }
432    Dmsg1(29, "open dev: tape %d opened\n", fd);
433 }
434
435
436 /*
437  * Open a file device
438  */
439 void DEVICE::open_file_device(DCR *dcr, int omode) 
440 {
441    POOL_MEM archive_name(PM_FNAME);
442
443    get_autochanger_loaded_slot(dcr);
444
445    /*
446     * Handle opening of File Archive (not a tape)
447     */     
448
449    pm_strcpy(archive_name, dev_name);
450    /*  
451     * If this is a virtual autochanger (i.e. changer_res != NULL)
452     *  we simply use the device name, assuming it has been
453     *  appropriately setup by the "autochanger".
454     */
455    if (!device->changer_res) {
456       if (VolCatInfo.VolCatName[0] == 0) {
457          Mmsg(errmsg, _("Could not open file device %s. No Volume name given.\n"),
458             print_name());
459          clear_opened();
460          return;
461       }
462
463       if (!IsPathSeparator(archive_name.c_str()[strlen(archive_name.c_str())-1])) {
464          pm_strcat(archive_name, "/");
465       }
466       pm_strcat(archive_name, VolCatInfo.VolCatName);
467    }
468
469    mount(1);                          /* do mount if required */
470          
471    openmode = omode;
472    set_mode(omode);
473    /* If creating file, give 0640 permissions */
474    Dmsg3(29, "open disk: mode=%s open(%s, 0x%x, 0640)\n", mode_to_str(omode), 
475          archive_name.c_str(), mode);
476    /* Use system open() */
477    if ((fd = ::open(archive_name.c_str(), mode, 0640)) < 0) {
478       berrno be;
479       dev_errno = errno;
480       Mmsg2(errmsg, _("Could not open: %s, ERR=%s\n"), archive_name.c_str(), 
481             be.strerror());
482       Dmsg1(29, "open failed: %s", errmsg);
483       Emsg0(M_FATAL, 0, errmsg);
484    } else {
485       dev_errno = 0;
486       file = 0;
487       file_addr = 0;
488    }
489    Dmsg4(29, "open dev: disk fd=%d opened, part=%d/%d, part_size=%u\n", 
490       fd, part, num_dvd_parts, part_size);
491 }
492
493 /*
494  * Open a DVD device. N.B. at this point, dcr->VolCatInfo.VolCatName 
495  *  (NB:??? I think it's VolCatInfo.VolCatName that is right)
496  *  has the desired Volume name, but there is NO assurance that
497  *  any other field of VolCatInfo is correct.
498  */
499 void DEVICE::open_dvd_device(DCR *dcr, int omode) 
500 {
501    POOL_MEM archive_name(PM_FNAME);
502    struct stat filestat;
503
504    /*
505     * Handle opening of DVD Volume
506     */     
507    Dmsg2(29, "Enter: open_dvd_dev: DVD vol=%s mode=%s\n", 
508          &dcr->VolCatInfo, mode_to_str(omode));
509
510    /*
511     * For a DVD we must always pull the state info from dcr->VolCatInfo
512     *  This is a bit ugly, but is necessary because we need to open/close/re-open
513     *  the dvd file in order to properly mount/unmount and access the
514     *  DVD. So we store the state of the DVD as far as is known in the 
515     *  catalog in dcr->VolCatInfo, and thus we refresh the dev->VolCatInfo
516     *  copy here, when opening.
517     */
518    VolCatInfo = dcr->VolCatInfo;         /* structure assignment */
519    Dmsg1(100, "Volume=%s\n", VolCatInfo.VolCatName);
520
521    if (VolCatInfo.VolCatName[0] == 0) {
522       Dmsg1(10,  "Could not open file device %s. No Volume name given.\n",
523          print_name());
524       Mmsg(errmsg, _("Could not open file device %s. No Volume name given.\n"),
525          print_name());
526       clear_opened();
527       return;
528    }
529
530    if (part == 0) {
531       Dmsg0(100, "Set part=1\n");
532       part = 1;                       /* count from 1 */
533       file_size = 0;
534    }
535    part_size = 0;
536    if (num_dvd_parts != VolCatInfo.VolCatParts) {
537       num_dvd_parts = VolCatInfo.VolCatParts;
538    }
539
540    /*
541     * If we are not trying to access the last part, set mode to 
542     *   OPEN_READ_ONLY as writing would be an error.
543     */
544    Dmsg2(29, "open DVD part=%d num_dvd_parts=%d\n", part, num_dvd_parts);
545    /* Now find the name of the part that we want to access */
546    if (part <= num_dvd_parts) {
547       omode = OPEN_READ_ONLY;
548       make_mounted_dvd_filename(this, archive_name);
549       set_part_spooled(false);
550    } else {
551       omode = OPEN_READ_WRITE;
552       make_spooled_dvd_filename(this, archive_name);
553       set_part_spooled(true);
554    }
555    set_mode(omode);
556
557    // Clear any previous blank_dvd status - we will recalculate it here
558    blank_dvd = false;
559
560    Dmsg3(99, "open_dvd_device: part=%d num_dvd_parts=%d, VolCatInfo.VolCatParts=%d\n",
561       part, num_dvd_parts, dcr->VolCatInfo.VolCatParts);
562      
563    if (mount(1)) {
564       Dmsg0(99, "DVD device mounted.\n");
565       if (num_dvd_parts == 0 && !truncating) {
566          /*
567           * If we can mount the device, and we are not truncating the DVD, 
568           * we usually want to abort. There is one exception, if there is 
569           * only one 0-sized file on the DVD, with the right volume name,
570           * we continue (it's the method used by truncate_dvd to truncate a volume).   
571           */
572          if (!check_can_write_on_non_blank_dvd(dcr)) {
573             Mmsg(errmsg, _("The DVD in device %s contains data, please blank it before writing.\n"), print_name());
574             Emsg0(M_FATAL, 0, errmsg);
575             unmount(1); /* Unmount the device, so the operator can change it. */
576             clear_opened();
577             return;
578          }
579          blank_dvd = true;
580       } else {
581          /*
582           * Ensure that we have the correct DVD loaded by looking for part1.
583           * We only succeed the open if it exists. Failure to do this could
584           * leave us trying to add a part to a different DVD!
585           */
586          uint32_t oldpart = part;
587          struct stat statp;
588          POOL_MEM part1_name(PM_FNAME);
589          part = 1;
590          make_mounted_dvd_filename(this, part1_name);
591          part = oldpart;
592          if (stat(part1_name.c_str(), &statp) < 0) {
593             berrno be;
594             Mmsg(errmsg, _("Unable to stat DVD part 1 file %s: ERR=%s\n"),
595                part1_name.c_str(), be.strerror());
596             Emsg0(M_FATAL, 0, errmsg);
597             clear_opened();
598             return;
599          }
600          if (!S_ISREG(statp.st_mode)) {
601             /* It is not a regular file */
602             Mmsg(errmsg, _("DVD part 1 is not a regular file %s.\n"),
603                part1_name.c_str());
604             Emsg0(M_FATAL, 0, errmsg);
605             clear_opened();
606             return;
607          }
608       }
609    } else {
610       Dmsg0(99, "DVD device mount failed.\n");
611       /* We cannot mount the device */
612       if (num_dvd_parts == 0) {
613          /* Run free space, check there is a media. */
614          if (!update_freespace()) {
615             Emsg0(M_FATAL, 0, errmsg);
616             clear_opened();
617             return;
618          }
619          if (have_media()) {
620             Dmsg1(29, "Could not mount device %s, this is not a problem (num_dvd_parts == 0), and have media.\n", print_name());
621          } else {
622             Mmsg(errmsg, _("There is no valid DVD in device %s.\n"), print_name());
623             Emsg0(M_FATAL, 0, errmsg);
624             clear_opened();
625             return;
626          }
627       }  else {
628          Mmsg(errmsg, _("Could not mount DVD device %s.\n"), print_name());
629          Emsg0(M_FATAL, 0, errmsg);
630          clear_opened();
631          return;
632       }
633    }
634    
635    Dmsg5(29, "open dev: DVD dev=%s mode=%s part=%d npart=%d volcatnparts=%d\n", 
636       archive_name.c_str(), mode_to_str(omode),
637       part, num_dvd_parts, dcr->VolCatInfo.VolCatParts);
638    openmode = omode;
639    Dmsg2(100, "openmode=%d %s\n", openmode, mode_to_str(openmode));
640    
641
642    /* If creating file, give 0640 permissions */
643    Dmsg3(29, "mode=%s open(%s, 0x%x, 0640)\n", mode_to_str(omode), 
644          archive_name.c_str(), mode);
645    /* Use system open() */
646    if ((fd = ::open(archive_name.c_str(), mode, 0640)) < 0) {
647       berrno be;
648       Mmsg2(errmsg, _("Could not open: %s, ERR=%s\n"), archive_name.c_str(), 
649             be.strerror());
650       // Should this be set if we try the create/open below
651       dev_errno = EIO; /* Interpreted as no device present by acquire.c:acquire_device_for_read(). */
652       Dmsg1(29, "open failed: %s", errmsg);
653       
654       /* Previous open failed. See if we can recover */
655       if ((omode == OPEN_READ_ONLY || omode == OPEN_READ_WRITE) &&
656           (part > num_dvd_parts)) {
657          /* If the last part (on spool), doesn't exist when accessing,
658           * create it. In read/write mode a write will be allowed (higher
659           * level software thinks that we are extending a pre-existing
660           * media. Reads for READ_ONLY will report immediately an EOF 
661           * Sometimes it is better to finish with an EOF than with an error. */
662          Dmsg1(29, "Creating last part on spool: %s\n", archive_name.c_str());
663          omode = CREATE_READ_WRITE;
664          set_mode(CREATE_READ_WRITE);
665          fd = ::open(archive_name.c_str(), mode, 0640);
666          set_mode(omode);
667       }
668    }
669    Dmsg1(100, "after open fd=%d\n", fd);
670    if (is_open()) {
671       if (omode == OPEN_READ_WRITE || omode == CREATE_READ_WRITE) {
672          set_append();
673       }
674       /* Get size of file */
675       if (fstat(fd, &filestat) < 0) {
676          berrno be;
677          dev_errno = errno;
678          Mmsg2(errmsg, _("Could not fstat: %s, ERR=%s\n"), archive_name.c_str(), 
679                be.strerror());
680          Dmsg1(29, "open failed: %s", errmsg);
681          /* Use system close() */
682          ::close(fd);
683          clear_opened();
684       } else {
685          part_size = filestat.st_size;
686          dev_errno = 0;
687          update_pos(dcr);                    /* update position */
688       }
689    }
690 }
691
692
693 /*
694  * Rewind the device.
695  *  Returns: true  on success
696  *           false on failure
697  */
698 bool DEVICE::rewind(DCR *dcr)
699 {
700    struct mtop mt_com;
701    unsigned int i;
702    bool first = true;
703
704    Dmsg3(400, "rewind res=%d fd=%d %s\n", reserved_device, fd, print_name());
705    state &= ~(ST_EOT|ST_EOF|ST_WEOT);  /* remove EOF/EOT flags */
706    block_num = file = 0;
707    file_size = 0;
708    file_addr = 0;
709    if (fd < 0) {
710       if (!is_dvd()) { /* In case of major error, the fd is not open on DVD, so we don't want to abort. */
711          dev_errno = EBADF;
712          Mmsg1(errmsg, _("Bad call to rewind. Device %s not open\n"),
713             print_name());
714          Emsg0(M_ABORT, 0, errmsg);
715       }
716       return false;
717    }
718    if (is_tape()) {
719       mt_com.mt_op = MTREW;
720       mt_com.mt_count = 1;
721       /* If we get an I/O error on rewind, it is probably because
722        * the drive is actually busy. We loop for (about 5 minutes)
723        * retrying every 5 seconds.
724        */
725       for (i=max_rewind_wait; ; i -= 5) {
726          if (tape_ioctl(fd, MTIOCTOP, (char *)&mt_com) < 0) {
727             berrno be;
728             clrerror(MTREW);
729             if (i == max_rewind_wait) {
730                Dmsg1(200, "Rewind error, %s. retrying ...\n", be.strerror());
731             }
732             /*
733              * This is a gross hack, because if the user has the
734              *   device mounted (i.e. open), then uses mtx to load
735              *   a tape, the current open file descriptor is invalid.
736              *   So, we close the drive and re-open it.
737              */
738             if (first && dcr) {
739                int open_mode = openmode;
740                tape_close(fd);
741                clear_opened();
742                open(dcr, open_mode);
743                if (fd < 0) {
744                   return false;
745                }
746                first = false;
747                continue;
748             }
749 #ifdef HAVE_SUN_OS
750             if (dev_errno == EIO) {         
751                Mmsg1(errmsg, _("No tape loaded or drive offline on %s.\n"), print_name());
752                return false;
753             }
754 #else
755             if (dev_errno == EIO && i > 0) {
756                Dmsg0(200, "Sleeping 5 seconds.\n");
757                bmicrosleep(5, 0);
758                continue;
759             }
760 #endif
761             Mmsg2(errmsg, _("Rewind error on %s. ERR=%s.\n"),
762                print_name(), be.strerror());
763             return false;
764          }
765          break;
766       }
767    } else if (is_file() || is_dvd()) {
768       if (lseek(dcr, (boffset_t)0, SEEK_SET) < 0) {
769          berrno be;
770          dev_errno = errno;
771          Mmsg2(errmsg, _("lseek error on %s. ERR=%s.\n"),
772             print_name(), be.strerror());
773          return false;
774       }
775    }
776    return true;
777 }
778
779 void DEVICE::block(int why)
780 {
781    lock_device(this);
782    block_device(this, why);
783    V(mutex);
784 }
785
786 void DEVICE::unblock()
787 {  
788    P(mutex);
789    unblock_device(this);
790    V(mutex);
791 }
792
793 const char *DEVICE::print_blocked() const 
794 {
795    switch (dev_blocked) {
796    case BST_NOT_BLOCKED:
797       return "BST_NOT_BLOCKED";
798    case BST_UNMOUNTED:
799       return "BST_UNMOUNTED";
800    case BST_WAITING_FOR_SYSOP:
801       return "BST_WAITING_FOR_SYSOP";
802    case BST_DOING_ACQUIRE:
803       return "BST_DOING_ACQUIRE";
804    case BST_WRITING_LABEL:
805       return "BST_WRITING_LABEL";
806    case BST_UNMOUNTED_WAITING_FOR_SYSOP:
807       return "BST_UNMOUNTED_WAITING_FOR_SYSOP";
808    case BST_MOUNT:
809       return "BST_MOUNT";
810    default:
811       return _("unknown blocked code");
812    }
813 }
814
815 /*
816  * Called to indicate that we have just read an
817  *  EOF from the device.
818  */
819 void DEVICE::set_ateof() 
820
821    set_eof();
822    if (is_tape()) {
823       file++;
824    }
825    file_addr = 0;
826    file_size = 0;
827    block_num = 0;
828 }
829
830 /*
831  * Called to indicate we are now at the end of the tape, and
832  *   writing is not possible.
833  */
834 void DEVICE::set_ateot() 
835 {
836    /* Make tape effectively read-only */
837    state |= (ST_EOF|ST_EOT|ST_WEOT);
838    clear_append();
839 }
840
841 /*
842  * Position device to end of medium (end of data)
843  *  Returns: true  on succes
844  *           false on error
845  */
846 bool DEVICE::eod(DCR *dcr)
847 {
848    struct mtop mt_com;
849    struct mtget mt_stat;
850    bool ok = true;
851    boffset_t pos;
852
853    if (fd < 0) {
854       dev_errno = EBADF;
855       Mmsg1(errmsg, _("Bad call to eod. Device %s not open\n"), print_name());
856       return false;
857    }
858
859 #if defined (__digital__) && defined (__unix__)
860    return fsf(VolCatInfo.VolCatFiles);
861 #endif
862
863    Dmsg0(29, "eod\n");
864    if (at_eot()) {
865       return true;
866    }
867    clear_eof();         /* remove EOF flag */
868    block_num = file = 0;
869    file_size = 0;
870    file_addr = 0;
871    if (is_fifo() || is_prog()) {
872       return true;
873    }
874    if (!is_tape()) {
875       pos = lseek(dcr, (boffset_t)0, SEEK_END);
876 //    Dmsg1(100, "====== Seek to %lld\n", pos);
877       if (pos >= 0) {
878          update_pos(dcr);
879          set_eot();
880          return true;
881       }
882       dev_errno = errno;
883       berrno be;
884       Mmsg2(errmsg, _("lseek error on %s. ERR=%s.\n"),
885              print_name(), be.strerror());
886       return false;
887    }
888 #ifdef MTEOM
889    if (has_cap(CAP_FASTFSF) && !has_cap(CAP_EOM)) {
890       Dmsg0(100,"Using FAST FSF for EOM\n");
891       /* If unknown position, rewind */
892       if (!dev_get_os_pos(this, &mt_stat)) {
893         if (!rewind(NULL)) {
894           return false;
895         }
896       }
897       mt_com.mt_op = MTFSF;
898       /*
899        * ***FIXME*** fix code to handle case that INT16_MAX is
900        *   not large enough.
901        */
902       mt_com.mt_count = INT16_MAX;    /* use big positive number */
903       if (mt_com.mt_count < 0) {
904          mt_com.mt_count = INT16_MAX; /* brain damaged system */
905       }
906    }
907
908    if (has_cap(CAP_MTIOCGET) && (has_cap(CAP_FASTFSF) || has_cap(CAP_EOM))) {
909       if (has_cap(CAP_EOM)) {
910          Dmsg0(100,"Using EOM for EOM\n");
911          mt_com.mt_op = MTEOM;
912          mt_com.mt_count = 1;
913       }
914
915       if (tape_ioctl(fd, MTIOCTOP, (char *)&mt_com) < 0) {
916          berrno be;
917          clrerror(mt_com.mt_op);
918          Dmsg1(50, "ioctl error: %s\n", be.strerror());
919          update_pos(dcr);
920          Mmsg2(errmsg, _("ioctl MTEOM error on %s. ERR=%s.\n"),
921             print_name(), be.strerror());
922          return false;
923       }
924
925       if (!dev_get_os_pos(this, &mt_stat)) {
926          berrno be;
927          clrerror(-1);
928          Mmsg2(errmsg, _("ioctl MTIOCGET error on %s. ERR=%s.\n"),
929             print_name(), be.strerror());
930          return false;
931       }
932       Dmsg2(100, "EOD file=%d block=%d\n", mt_stat.mt_fileno, mt_stat.mt_blkno);
933       set_ateof();
934       file = mt_stat.mt_fileno;
935    } else {
936 #else
937    {
938 #endif
939       /*
940        * Rewind then use FSF until EOT reached
941        */
942       if (!rewind(NULL)) {
943          return false;
944       }
945       /*
946        * Move file by file to the end of the tape
947        */
948       int file_num;
949       for (file_num=file; !at_eot(); file_num++) {
950          Dmsg0(200, "eod: doing fsf 1\n");
951          if (!fsf(1)) {
952             Dmsg0(200, "fsf error.\n");
953             return false;
954          }
955          /*
956           * Avoid infinite loop by ensuring we advance.
957           */
958          if (!at_eot() && file_num == (int)file) {
959             struct mtget mt_stat;
960             Dmsg1(100, "fsf did not advance from file %d\n", file_num);
961             set_ateof();
962             if (dev_get_os_pos(this, &mt_stat)) {
963                Dmsg2(100, "Adjust file from %d to %d\n", file_num, mt_stat.mt_fileno);
964                file = mt_stat.mt_fileno;
965             }       
966             break;
967          }
968       }
969    }
970    /*
971     * Some drivers leave us after second EOF when doing
972     * MTEOM, so we must backup so that appending overwrites
973     * the second EOF.
974     */
975    if (has_cap(CAP_BSFATEOM)) {
976       struct mtget mt_stat;
977       /* Backup over EOF */
978       ok = bsf(1);
979       /* If BSF worked and fileno is known (not -1), set file */
980       if (dev_get_os_pos(this, &mt_stat)) {
981          Dmsg2(100, "BSFATEOF adjust file from %d to %d\n", file , mt_stat.mt_fileno);
982          file = mt_stat.mt_fileno;
983       } else {
984          file++;                       /* wing it -- not correct on all OSes */
985       }
986    } else {
987       update_pos(dcr);                 /* update position */
988    }
989    Dmsg1(200, "EOD dev->file=%d\n", file);
990    return ok;
991 }
992
993 /*
994  * Set the position of the device -- only for files and DVD
995  *   For other devices, there is no generic way to do it.
996  *  Returns: true  on succes
997  *           false on error
998  */
999 bool DEVICE::update_pos(DCR *dcr)
1000 {
1001    boffset_t pos;
1002    bool ok = true;
1003
1004    if (!is_open()) {
1005       dev_errno = EBADF;
1006       Mmsg0(errmsg, _("Bad device call. Device not open\n"));
1007       Emsg1(M_FATAL, 0, "%s", errmsg);
1008       return false;
1009    }
1010
1011    /* Find out where we are */
1012    if (is_file() || is_dvd()) {
1013       file = 0;
1014       file_addr = 0;
1015       pos = lseek(dcr, (boffset_t)0, SEEK_CUR);
1016       if (pos < 0) {
1017          berrno be;
1018          dev_errno = errno;
1019          Pmsg1(000, _("Seek error: ERR=%s\n"), be.strerror());
1020          Mmsg2(errmsg, _("lseek error on %s. ERR=%s.\n"),
1021             print_name(), be.strerror());
1022          ok = false;
1023       } else {
1024          file_addr = pos;
1025          block_num = (uint32_t)pos;
1026          file = (uint32_t)(pos >> 32);
1027       }
1028    }
1029    return ok;
1030 }
1031
1032 /*
1033  * Return the status of the device.  This was meant
1034  * to be a generic routine. Unfortunately, it doesn't
1035  * seem possible (at least I do not know how to do it
1036  * currently), which means that for the moment, this
1037  * routine has very little value.
1038  *
1039  *   Returns: status
1040  */
1041 uint32_t status_dev(DEVICE *dev)
1042 {
1043    struct mtget mt_stat;
1044    uint32_t stat = 0;
1045
1046    if (dev->state & (ST_EOT | ST_WEOT)) {
1047       stat |= BMT_EOD;
1048       Pmsg0(-20, " EOD");
1049    }
1050    if (dev->state & ST_EOF) {
1051       stat |= BMT_EOF;
1052       Pmsg0(-20, " EOF");
1053    }
1054    if (dev->is_tape()) {
1055       stat |= BMT_TAPE;
1056       Pmsg0(-20,_(" Bacula status:"));
1057       Pmsg2(-20,_(" file=%d block=%d\n"), dev->file, dev->block_num);
1058       if (tape_ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) < 0) {
1059          berrno be;
1060          dev->dev_errno = errno;
1061          Mmsg2(dev->errmsg, _("ioctl MTIOCGET error on %s. ERR=%s.\n"),
1062             dev->print_name(), be.strerror());
1063          return 0;
1064       }
1065       Pmsg0(-20, _(" Device status:"));
1066
1067 #if defined(HAVE_LINUX_OS)
1068       if (GMT_EOF(mt_stat.mt_gstat)) {
1069          stat |= BMT_EOF;
1070          Pmsg0(-20, " EOF");
1071       }
1072       if (GMT_BOT(mt_stat.mt_gstat)) {
1073          stat |= BMT_BOT;
1074          Pmsg0(-20, " BOT");
1075       }
1076       if (GMT_EOT(mt_stat.mt_gstat)) {
1077          stat |= BMT_EOT;
1078          Pmsg0(-20, " EOT");
1079       }
1080       if (GMT_SM(mt_stat.mt_gstat)) {
1081          stat |= BMT_SM;
1082          Pmsg0(-20, " SM");
1083       }
1084       if (GMT_EOD(mt_stat.mt_gstat)) {
1085          stat |= BMT_EOD;
1086          Pmsg0(-20, " EOD");
1087       }
1088       if (GMT_WR_PROT(mt_stat.mt_gstat)) {
1089          stat |= BMT_WR_PROT;
1090          Pmsg0(-20, " WR_PROT");
1091       }
1092       if (GMT_ONLINE(mt_stat.mt_gstat)) {
1093          stat |= BMT_ONLINE;
1094          Pmsg0(-20, " ONLINE");
1095       }
1096       if (GMT_DR_OPEN(mt_stat.mt_gstat)) {
1097          stat |= BMT_DR_OPEN;
1098          Pmsg0(-20, " DR_OPEN");
1099       }
1100       if (GMT_IM_REP_EN(mt_stat.mt_gstat)) {
1101          stat |= BMT_IM_REP_EN;
1102          Pmsg0(-20, " IM_REP_EN");
1103       }
1104 #elif defined(HAVE_WIN32)
1105       if (GMT_EOF(mt_stat.mt_gstat)) {
1106          stat |= BMT_EOF;
1107          Pmsg0(-20, " EOF");
1108       }
1109       if (GMT_BOT(mt_stat.mt_gstat)) {
1110          stat |= BMT_BOT;
1111          Pmsg0(-20, " BOT");
1112       }
1113       if (GMT_EOT(mt_stat.mt_gstat)) {
1114          stat |= BMT_EOT;
1115          Pmsg0(-20, " EOT");
1116       }
1117       if (GMT_EOD(mt_stat.mt_gstat)) {
1118          stat |= BMT_EOD;
1119          Pmsg0(-20, " EOD");
1120       }
1121       if (GMT_WR_PROT(mt_stat.mt_gstat)) {
1122          stat |= BMT_WR_PROT;
1123          Pmsg0(-20, " WR_PROT");
1124       }
1125       if (GMT_ONLINE(mt_stat.mt_gstat)) {
1126          stat |= BMT_ONLINE;
1127          Pmsg0(-20, " ONLINE");
1128       }
1129       if (GMT_DR_OPEN(mt_stat.mt_gstat)) {
1130          stat |= BMT_DR_OPEN;
1131          Pmsg0(-20, " DR_OPEN");
1132       }
1133       if (GMT_IM_REP_EN(mt_stat.mt_gstat)) {
1134          stat |= BMT_IM_REP_EN;
1135          Pmsg0(-20, " IM_REP_EN");
1136       }
1137
1138 #endif /* !SunOS && !OSF */
1139       if (dev->has_cap(CAP_MTIOCGET)) {
1140          Pmsg2(-20, _(" file=%d block=%d\n"), mt_stat.mt_fileno, mt_stat.mt_blkno);
1141       } else {
1142          Pmsg2(-20, _(" file=%d block=%d\n"), -1, -1);
1143       }
1144    } else {
1145       stat |= BMT_ONLINE | BMT_BOT;
1146    }
1147    return stat;
1148 }
1149
1150
1151 /*
1152  * Load medium in device
1153  *  Returns: true  on success
1154  *           false on failure
1155  */
1156 bool load_dev(DEVICE *dev)
1157 {
1158 #ifdef MTLOAD
1159    struct mtop mt_com;
1160 #endif
1161
1162    if (dev->fd < 0) {
1163       dev->dev_errno = EBADF;
1164       Mmsg0(dev->errmsg, _("Bad call to load_dev. Device not open\n"));
1165       Emsg0(M_FATAL, 0, dev->errmsg);
1166       return false;
1167    }
1168    if (!(dev->is_tape())) {
1169       return true;
1170    }
1171 #ifndef MTLOAD
1172    Dmsg0(200, "stored: MTLOAD command not available\n");
1173    berrno be;
1174    dev->dev_errno = ENOTTY;           /* function not available */
1175    Mmsg2(dev->errmsg, _("ioctl MTLOAD error on %s. ERR=%s.\n"),
1176          dev->print_name(), be.strerror());
1177    return false;
1178 #else
1179
1180    dev->block_num = dev->file = 0;
1181    dev->file_size = 0;
1182    dev->file_addr = 0;
1183    mt_com.mt_op = MTLOAD;
1184    mt_com.mt_count = 1;
1185    if (tape_ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1186       berrno be;
1187       dev->dev_errno = errno;
1188       Mmsg2(dev->errmsg, _("ioctl MTLOAD error on %s. ERR=%s.\n"),
1189          dev->print_name(), be.strerror());
1190       return false;
1191    }
1192    return true;
1193 #endif
1194 }
1195
1196 /*
1197  * Rewind device and put it offline
1198  *  Returns: true  on success
1199  *           false on failure
1200  */
1201 bool DEVICE::offline()
1202 {
1203    struct mtop mt_com;
1204
1205    if (!is_tape()) {
1206       return true;                    /* device not open */
1207    }
1208
1209    state &= ~(ST_APPEND|ST_READ|ST_EOT|ST_EOF|ST_WEOT);  /* remove EOF/EOT flags */
1210    block_num = file = 0;
1211    file_size = 0;
1212    file_addr = 0;
1213    unlock_door();
1214    mt_com.mt_op = MTOFFL;
1215    mt_com.mt_count = 1;
1216    if (tape_ioctl(fd, MTIOCTOP, (char *)&mt_com) < 0) {
1217       berrno be;
1218       dev_errno = errno;
1219       Mmsg2(errmsg, _("ioctl MTOFFL error on %s. ERR=%s.\n"),
1220          print_name(), be.strerror());
1221       return false;
1222    }
1223    Dmsg1(100, "Offlined device %s\n", print_name());
1224    return true;
1225 }
1226
1227 bool DEVICE::offline_or_rewind()
1228 {
1229    if (fd < 0) {
1230       return false;
1231    }
1232    if (has_cap(CAP_OFFLINEUNMOUNT)) {
1233       return offline();
1234    } else {
1235    /*
1236     * Note, this rewind probably should not be here (it wasn't
1237     *  in prior versions of Bacula), but on FreeBSD, this is
1238     *  needed in the case the tape was "frozen" due to an error
1239     *  such as backspacing after writing and EOF. If it is not
1240     *  done, all future references to the drive get and I/O error.
1241     */
1242       clrerror(MTREW);
1243       return rewind(NULL);
1244    }
1245 }
1246
1247 /*
1248  * Foward space a file
1249  *   Returns: true  on success
1250  *            false on failure
1251  */
1252 bool DEVICE::fsf(int num)
1253 {
1254    struct mtget mt_stat;
1255    struct mtop mt_com;
1256    int stat = 0;
1257
1258    if (!is_open()) {
1259       dev_errno = EBADF;
1260       Mmsg0(errmsg, _("Bad call to fsf. Device not open\n"));
1261       Emsg0(M_FATAL, 0, errmsg);
1262       return false;
1263    }
1264
1265    if (!is_tape()) {
1266       return true;
1267    }
1268
1269    if (at_eot()) {
1270       dev_errno = 0;
1271       Mmsg1(errmsg, _("Device %s at End of Tape.\n"), print_name());
1272       return false;
1273    }
1274    if (at_eof()) {
1275       Dmsg0(200, "ST_EOF set on entry to FSF\n");
1276    }
1277
1278    Dmsg0(100, "fsf\n");
1279    block_num = 0;
1280    /*
1281     * If Fast forward space file is set, then we
1282     *  use MTFSF to forward space and MTIOCGET
1283     *  to get the file position. We assume that
1284     *  the SCSI driver will ensure that we do not
1285     *  forward space past the end of the medium.
1286     */
1287    if (has_cap(CAP_FSF) && has_cap(CAP_MTIOCGET) && has_cap(CAP_FASTFSF)) {
1288       mt_com.mt_op = MTFSF;
1289       mt_com.mt_count = num;
1290       stat = tape_ioctl(fd, MTIOCTOP, (char *)&mt_com);
1291       if (stat < 0 || !dev_get_os_pos(this, &mt_stat)) {
1292          berrno be;
1293          set_eot();
1294          Dmsg0(200, "Set ST_EOT\n");
1295          clrerror(MTFSF);
1296          Mmsg2(errmsg, _("ioctl MTFSF error on %s. ERR=%s.\n"),
1297             print_name(), be.strerror());
1298          Dmsg1(200, "%s", errmsg);
1299          return false;
1300       }
1301       Dmsg2(200, "fsf file=%d block=%d\n", mt_stat.mt_fileno, mt_stat.mt_blkno);
1302       set_ateof();
1303       file = mt_stat.mt_fileno;
1304       return true;
1305
1306    /*
1307     * Here if CAP_FSF is set, and virtually all drives
1308     *  these days support it, we read a record, then forward
1309     *  space one file. Using this procedure, which is slow,
1310     *  is the only way we can be sure that we don't read
1311     *  two consecutive EOF marks, which means End of Data.
1312     */
1313    } else if (has_cap(CAP_FSF)) {
1314       POOLMEM *rbuf;
1315       int rbuf_len;
1316       Dmsg0(200, "FSF has cap_fsf\n");
1317       if (max_block_size == 0) {
1318          rbuf_len = DEFAULT_BLOCK_SIZE;
1319       } else {
1320          rbuf_len = max_block_size;
1321       }
1322       rbuf = get_memory(rbuf_len);
1323       mt_com.mt_op = MTFSF;
1324       mt_com.mt_count = 1;
1325       while (num-- && !at_eot()) {
1326          Dmsg0(100, "Doing read before fsf\n");
1327          if ((stat = tape_read(fd, (char *)rbuf, rbuf_len)) < 0) {
1328             if (errno == ENOMEM) {     /* tape record exceeds buf len */
1329                stat = rbuf_len;        /* This is OK */
1330             /*
1331              * On IBM drives, they return ENOSPC at EOM
1332              *  instead of EOF status
1333              */
1334             } else if (at_eof() && errno == ENOSPC) {
1335                stat = 0;
1336             } else {
1337                berrno be;
1338                set_eot();
1339                clrerror(-1);
1340                Dmsg2(100, "Set ST_EOT read errno=%d. ERR=%s\n", dev_errno,
1341                   be.strerror());
1342                Mmsg2(errmsg, _("read error on %s. ERR=%s.\n"),
1343                   print_name(), be.strerror());
1344                Dmsg1(100, "%s", errmsg);
1345                break;
1346             }
1347          }
1348          if (stat == 0) {                /* EOF */
1349             Dmsg1(100, "End of File mark from read. File=%d\n", file+1);
1350             /* Two reads of zero means end of tape */
1351             if (at_eof()) {
1352                set_eot();
1353                Dmsg0(100, "Set ST_EOT\n");
1354                break;
1355             } else {
1356                set_ateof();
1357                continue;
1358             }
1359          } else {                        /* Got data */
1360             clear_eot();
1361             clear_eof();
1362          }
1363
1364          Dmsg0(100, "Doing MTFSF\n");
1365          stat = tape_ioctl(fd, MTIOCTOP, (char *)&mt_com);
1366          if (stat < 0) {                 /* error => EOT */
1367             berrno be;
1368             set_eot();
1369             Dmsg0(100, "Set ST_EOT\n");
1370             clrerror(MTFSF);
1371             Mmsg2(errmsg, _("ioctl MTFSF error on %s. ERR=%s.\n"),
1372                print_name(), be.strerror());
1373             Dmsg0(100, "Got < 0 for MTFSF\n");
1374             Dmsg1(100, "%s", errmsg);
1375          } else {
1376             set_ateof();
1377          }
1378       }
1379       free_memory(rbuf);
1380
1381    /*
1382     * No FSF, so use FSR to simulate it
1383     */
1384    } else {
1385       Dmsg0(200, "Doing FSR for FSF\n");
1386       while (num-- && !at_eot()) {
1387          fsr(INT32_MAX);    /* returns -1 on EOF or EOT */
1388       }
1389       if (at_eot()) {
1390          dev_errno = 0;
1391          Mmsg1(errmsg, _("Device %s at End of Tape.\n"), print_name());
1392          stat = -1;
1393       } else {
1394          stat = 0;
1395       }
1396    }
1397    Dmsg1(200, "Return %d from FSF\n", stat);
1398    if (at_eof()) {
1399       Dmsg0(200, "ST_EOF set on exit FSF\n");
1400    }
1401    if (at_eot()) {
1402       Dmsg0(200, "ST_EOT set on exit FSF\n");
1403    }
1404    Dmsg1(200, "Return from FSF file=%d\n", file);
1405    return stat == 0;
1406 }
1407
1408 /*
1409  * Backward space a file
1410  *  Returns: false on failure
1411  *           true  on success
1412  */
1413 bool DEVICE::bsf(int num)
1414 {
1415    struct mtop mt_com;
1416    int stat;
1417
1418    if (!is_open()) {
1419       dev_errno = EBADF;
1420       Mmsg0(errmsg, _("Bad call to bsf. Device not open\n"));
1421       Emsg0(M_FATAL, 0, errmsg);
1422       return false;
1423    }
1424
1425    if (!is_tape()) {
1426       Mmsg1(errmsg, _("Device %s cannot BSF because it is not a tape.\n"),
1427          print_name());
1428       return false;
1429    }
1430
1431    Dmsg0(29, "bsf\n");
1432    clear_eot();
1433    clear_eof();
1434    file -= num;
1435    file_addr = 0;
1436    file_size = 0;
1437    mt_com.mt_op = MTBSF;
1438    mt_com.mt_count = num;
1439    stat = tape_ioctl(fd, MTIOCTOP, (char *)&mt_com);
1440    if (stat < 0) {
1441       berrno be;
1442       clrerror(MTBSF);
1443       Mmsg2(errmsg, _("ioctl MTBSF error on %s. ERR=%s.\n"),
1444          print_name(), be.strerror());
1445    }
1446    return stat == 0;
1447 }
1448
1449
1450 /*
1451  * Foward space num records
1452  *  Returns: false on failure
1453  *           true  on success
1454  */
1455 bool DEVICE::fsr(int num)
1456 {
1457    struct mtop mt_com;
1458    int stat;
1459
1460    if (!is_open()) {
1461       dev_errno = EBADF;
1462       Mmsg0(errmsg, _("Bad call to fsr. Device not open\n"));
1463       Emsg0(M_FATAL, 0, errmsg);
1464       return false;
1465    }
1466
1467    if (!is_tape()) {
1468       return false;
1469    }
1470
1471    if (!has_cap(CAP_FSR)) {
1472       Mmsg1(errmsg, _("ioctl MTFSR not permitted on %s.\n"), print_name());
1473       return false;
1474    }
1475
1476    Dmsg1(29, "fsr %d\n", num);
1477    mt_com.mt_op = MTFSR;
1478    mt_com.mt_count = num;
1479    stat = tape_ioctl(fd, MTIOCTOP, (char *)&mt_com);
1480    if (stat == 0) {
1481       clear_eof();
1482       block_num += num;
1483    } else {
1484       berrno be;
1485       struct mtget mt_stat;
1486       clrerror(MTFSR);
1487       Dmsg1(100, "FSF fail: ERR=%s\n", be.strerror());
1488       if (dev_get_os_pos(this, &mt_stat)) {
1489          Dmsg4(100, "Adjust from %d:%d to %d:%d\n", file,
1490             block_num, mt_stat.mt_fileno, mt_stat.mt_blkno);
1491          file = mt_stat.mt_fileno;
1492          block_num = mt_stat.mt_blkno;
1493       } else {
1494          if (at_eof()) {
1495             set_eot();
1496          } else {
1497             set_ateof();
1498          }
1499       }
1500       Mmsg3(errmsg, _("ioctl MTFSR %d error on %s. ERR=%s.\n"),
1501          num, print_name(), be.strerror());
1502    }
1503    return stat == 0;
1504 }
1505
1506 /*
1507  * Backward space a record
1508  *   Returns:  false on failure
1509  *             true  on success
1510  */
1511 bool DEVICE::bsr(int num)
1512 {
1513    struct mtop mt_com;
1514    int stat;
1515
1516    if (!is_open()) {
1517       dev_errno = EBADF;
1518       Mmsg0(errmsg, _("Bad call to bsr_dev. Device not open\n"));
1519       Emsg0(M_FATAL, 0, errmsg);
1520       return false;
1521    }
1522
1523    if (!is_tape()) {
1524       return false;
1525    }
1526
1527    if (!has_cap(CAP_BSR)) {
1528       Mmsg1(errmsg, _("ioctl MTBSR not permitted on %s.\n"), print_name());
1529       return false;
1530    }
1531
1532    Dmsg0(29, "bsr_dev\n");
1533    block_num -= num;
1534    clear_eof();
1535    clear_eot();
1536    mt_com.mt_op = MTBSR;
1537    mt_com.mt_count = num;
1538    stat = tape_ioctl(fd, MTIOCTOP, (char *)&mt_com);
1539    if (stat < 0) {
1540       berrno be;
1541       clrerror(MTBSR);
1542       Mmsg2(errmsg, _("ioctl MTBSR error on %s. ERR=%s.\n"),
1543          print_name(), be.strerror());
1544    }
1545    return stat == 0;
1546 }
1547
1548 void DEVICE::lock_door()
1549 {
1550 #ifdef MTLOCK
1551    struct mtop mt_com;
1552    mt_com.mt_op = MTLOCK;
1553    mt_com.mt_count = 1;
1554    tape_ioctl(fd, MTIOCTOP, (char *)&mt_com);
1555 #endif
1556 }
1557
1558 void DEVICE::unlock_door()
1559 {
1560 #ifdef MTUNLOCK
1561    struct mtop mt_com;
1562    mt_com.mt_op = MTUNLOCK;
1563    mt_com.mt_count = 1;
1564    tape_ioctl(fd, MTIOCTOP, (char *)&mt_com);
1565 #endif
1566 }
1567  
1568
1569 /*
1570  * Reposition the device to file, block
1571  * Returns: false on failure
1572  *          true  on success
1573  */
1574 bool DEVICE::reposition(DCR *dcr, uint32_t rfile, uint32_t rblock)
1575 {
1576    if (!is_open()) {
1577       dev_errno = EBADF;
1578       Mmsg0(errmsg, _("Bad call to reposition. Device not open\n"));
1579       Emsg0(M_FATAL, 0, errmsg);
1580       return false;
1581    }
1582
1583    if (!is_tape()) {
1584       boffset_t pos = (((boffset_t)rfile)<<32) | rblock;
1585       Dmsg1(100, "===== lseek to %d\n", (int)pos);
1586       if (lseek(dcr, pos, SEEK_SET) == (boffset_t)-1) {
1587          berrno be;
1588          dev_errno = errno;
1589          Mmsg2(errmsg, _("lseek error on %s. ERR=%s.\n"),
1590             print_name(), be.strerror());
1591          return false;
1592       }
1593       file = rfile;
1594       block_num = rblock;
1595       file_addr = pos;
1596       return true;
1597    }
1598
1599    /* After this point, we are tape only */
1600    Dmsg4(100, "reposition from %u:%u to %u:%u\n", file, block_num, rfile, rblock);
1601    if (rfile < file) {
1602       Dmsg0(100, "Rewind\n");
1603       if (!rewind(NULL)) {
1604          return false;
1605       }
1606    }
1607    if (rfile > file) {
1608       Dmsg1(100, "fsf %d\n", rfile-file);
1609       if (!fsf(rfile-file)) {
1610          Dmsg1(100, "fsf failed! ERR=%s\n", bstrerror());
1611          return false;
1612       }
1613       Dmsg2(100, "wanted_file=%d at_file=%d\n", rfile, file);
1614    }
1615    if (rblock < block_num) {
1616       Dmsg2(100, "wanted_blk=%d at_blk=%d\n", rblock, block_num);
1617       Dmsg0(100, "bsf 1\n");
1618       bsf(1);
1619       Dmsg0(100, "fsf 1\n");
1620       fsf(1);
1621       Dmsg2(100, "wanted_blk=%d at_blk=%d\n", rblock, block_num);
1622    }
1623    if (has_cap(CAP_POSITIONBLOCKS) && rblock > block_num) {
1624       /* Ignore errors as Bacula can read to the correct block */
1625       Dmsg1(100, "fsr %d\n", rblock-block_num);
1626       return fsr(rblock-block_num);
1627    } else {
1628       while (rblock > block_num) {
1629          if (!read_block_from_dev(dcr, NO_BLOCK_NUMBER_CHECK)) {
1630             berrno be;
1631             dev_errno = errno;
1632             Dmsg2(30, "Failed to find requested block on %s: ERR=%s",
1633                print_name(), be.strerror());
1634             return false;
1635          }
1636          Dmsg2(300, "moving forward wanted_blk=%d at_blk=%d\n", rblock, block_num);
1637       }
1638    }
1639    return true;
1640 }
1641
1642
1643
1644 /*
1645  * Write an end of file on the device
1646  *   Returns: true on success
1647  *            false on failure
1648  */
1649 bool DEVICE::weof(int num)
1650 {
1651    struct mtop mt_com;
1652    int stat;
1653    Dmsg0(129, "weof_dev\n");
1654    
1655    if (!is_open()) {
1656       dev_errno = EBADF;
1657       Mmsg0(errmsg, _("Bad call to weof_dev. Device not open\n"));
1658       Emsg0(M_FATAL, 0, errmsg);
1659       return false;
1660    }
1661    file_size = 0;
1662
1663    if (!is_tape()) {
1664       return true;
1665    }
1666    if (!can_append()) {
1667       Mmsg0(errmsg, _("Attempt to WEOF on non-appendable Volume\n"));
1668       Emsg0(M_FATAL, 0, errmsg);
1669       return false;
1670    }
1671       
1672    clear_eof();
1673    clear_eot();
1674    mt_com.mt_op = MTWEOF;
1675    mt_com.mt_count = num;
1676    stat = tape_ioctl(fd, MTIOCTOP, (char *)&mt_com);
1677    if (stat == 0) {
1678       block_num = 0;
1679       file += num;
1680       file_addr = 0;
1681    } else {
1682       berrno be;
1683       clrerror(MTWEOF);
1684       if (stat == -1) {
1685          Mmsg2(errmsg, _("ioctl MTWEOF error on %s. ERR=%s.\n"),
1686             print_name(), be.strerror());
1687        }
1688    }
1689    return stat == 0;
1690 }
1691
1692
1693 /*
1694  * If implemented in system, clear the tape
1695  * error status.
1696  */
1697 void DEVICE::clrerror(int func)
1698 {
1699    const char *msg = NULL;
1700    struct mtget mt_stat;
1701    char buf[100];
1702
1703    dev_errno = errno;         /* save errno */
1704    if (errno == EIO) {
1705       VolCatInfo.VolCatErrors++;
1706    }
1707
1708    if (!is_tape()) {
1709       return;
1710    }
1711
1712    if (errno == ENOTTY || errno == ENOSYS) { /* Function not implemented */
1713       switch (func) {
1714       case -1:
1715          break;              /* ignore message printed later */
1716       case MTWEOF:
1717          msg = "WTWEOF";
1718          capabilities &= ~CAP_EOF; /* turn off feature */
1719          break;
1720 #ifdef MTEOM
1721       case MTEOM:
1722          msg = "WTEOM";
1723          capabilities &= ~CAP_EOM; /* turn off feature */
1724          break;
1725 #endif
1726       case MTFSF:
1727          msg = "MTFSF";
1728          capabilities &= ~CAP_FSF; /* turn off feature */
1729          break;
1730       case MTBSF:
1731          msg = "MTBSF";
1732          capabilities &= ~CAP_BSF; /* turn off feature */
1733          break;
1734       case MTFSR:
1735          msg = "MTFSR";
1736          capabilities &= ~CAP_FSR; /* turn off feature */
1737          break;
1738       case MTBSR:
1739          msg = "MTBSR";
1740          capabilities &= ~CAP_BSR; /* turn off feature */
1741          break;
1742       case MTREW:
1743          msg = "MTREW";
1744          break;
1745 #ifdef MTSETBLK
1746       case MTSETBLK:
1747          msg = "MTSETBLK";
1748          break;
1749 #endif
1750 #ifdef MTSETDRVBUFFER
1751       case MTSETDRVBUFFER:
1752          msg = "MTSETDRVBUFFER";
1753          break;
1754 #endif
1755 #ifdef MTRESET
1756       case MTRESET:
1757          msg = "MTRESET";
1758          break;
1759 #endif
1760
1761 #ifdef MTSETBSIZ 
1762       case MTSETBSIZ:
1763          msg = "MTSETBSIZ";
1764          break;
1765 #endif
1766 #ifdef MTSRSZ
1767       case MTSRSZ:
1768          msg = "MTSRSZ";
1769          break;
1770 #endif
1771 #ifdef MTLOAD
1772       case MTLOAD:
1773          msg = "MTLOAD";
1774          break;
1775 #endif
1776 #ifdef MTUNLOCK
1777       case MTUNLOCK:
1778          msg = "MTUNLOCK";
1779          break;
1780 #endif
1781       case MTOFFL:
1782          msg = "MTOFFL";
1783          break;
1784       default:
1785          bsnprintf(buf, sizeof(buf), _("unknown func code %d"), func);
1786          msg = buf;
1787          break;
1788       }
1789       if (msg != NULL) {
1790          dev_errno = ENOSYS;
1791          Mmsg1(errmsg, _("I/O function \"%s\" not supported on this device.\n"), msg);
1792          Emsg0(M_ERROR, 0, errmsg);
1793       }
1794    }
1795
1796    /*
1797     * Now we try different methods of clearing the error
1798     *  status on the drive so that it is not locked for
1799     *  further operations.
1800     */
1801
1802    /* On some systems such as NetBSD, this clears all errors */
1803    tape_ioctl(fd, MTIOCGET, (char *)&mt_stat);
1804
1805 /* Found on Linux */
1806 #ifdef MTIOCLRERR
1807 {
1808    struct mtop mt_com;
1809    mt_com.mt_op = MTIOCLRERR;
1810    mt_com.mt_count = 1;
1811    /* Clear any error condition on the tape */
1812    tape_ioctl(fd, MTIOCTOP, (char *)&mt_com);
1813    Dmsg0(200, "Did MTIOCLRERR\n");
1814 }
1815 #endif
1816
1817 /* Typically on FreeBSD */
1818 #ifdef MTIOCERRSTAT
1819 {
1820   berrno be;
1821    /* Read and clear SCSI error status */
1822    union mterrstat mt_errstat;
1823    Dmsg2(200, "Doing MTIOCERRSTAT errno=%d ERR=%s\n", dev_errno,
1824       be.strerror(dev_errno));
1825    tape_ioctl(fd, MTIOCERRSTAT, (char *)&mt_errstat);
1826 }
1827 #endif
1828
1829 /* Clear Subsystem Exception OSF1 */
1830 #ifdef MTCSE
1831 {
1832    struct mtop mt_com;
1833    mt_com.mt_op = MTCSE;
1834    mt_com.mt_count = 1;
1835    /* Clear any error condition on the tape */
1836    tape_ioctl(fd, MTIOCTOP, (char *)&mt_com);
1837    Dmsg0(200, "Did MTCSE\n");
1838 }
1839 #endif
1840 }
1841
1842 /*
1843  * Close the device
1844  */
1845 void DEVICE::close()
1846 {
1847    Dmsg1(100, "close_dev %s\n", print_name());
1848    if (has_cap(CAP_OFFLINEUNMOUNT)) {
1849       offline();
1850    }
1851
1852    if (!is_open()) {
1853       Dmsg2(100, "device %s already closed vol=%s\n", print_name(),
1854          VolHdr.VolumeName);
1855       return;                         /* already closed */
1856    }
1857
1858    switch (dev_type) {
1859    case B_TAPE_DEV:
1860       unlock_door(); 
1861       tape_close(fd);
1862       break;
1863    default:
1864       ::close(fd);
1865    }
1866
1867    /* Clean up device packet so it can be reused */
1868    clear_opened();
1869    state &= ~(ST_LABEL|ST_READ|ST_APPEND|ST_EOT|ST_WEOT|ST_EOF);
1870    label_type = B_BACULA_LABEL;
1871    file = block_num = 0;
1872    file_size = 0;
1873    file_addr = 0;
1874    EndFile = EndBlock = 0;
1875    openmode = 0;
1876    Slot = -1;             /* unknown slot */
1877    free_volume(this);
1878    memset(&VolCatInfo, 0, sizeof(VolCatInfo));
1879    memset(&VolHdr, 0, sizeof(VolHdr));
1880    if (tid) {
1881       stop_thread_timer(tid);
1882       tid = 0;
1883    }
1884 }
1885
1886 /*
1887  * This call closes the device, but it is used in DVD handling
1888  *  where we close one part and then open the next part. The
1889  *  difference between close_part() and close() is that close_part()
1890  *  saves the state information of the device (e.g. the Volume lable,
1891  *  the Volume Catalog record, ...  This permits opening and closing
1892  *  the Volume parts multiple times without losing track of what the    
1893  *  main Volume parameters are.
1894  */
1895 void DEVICE::close_part(DCR *dcr)
1896 {
1897    VOLUME_LABEL saveVolHdr;
1898    VOLUME_CAT_INFO saveVolCatInfo;     /* Volume Catalog Information */
1899
1900
1901    saveVolHdr = VolHdr;               /* structure assignment */
1902    saveVolCatInfo = VolCatInfo;       /* structure assignment */
1903    close();                           /* close current part */
1904    VolHdr = saveVolHdr;               /* structure assignment */
1905    VolCatInfo = saveVolCatInfo;       /* structure assignment */
1906    dcr->VolCatInfo = saveVolCatInfo;  /* structure assignment */
1907 }
1908
1909 boffset_t DEVICE::lseek(DCR *dcr, boffset_t offset, int whence)
1910 {
1911    switch (dev_type) {
1912    case B_DVD_DEV:
1913       return lseek_dvd(dcr, offset, whence);
1914    case B_FILE_DEV:
1915 #if defined(HAVE_WIN32)
1916       return ::_lseeki64(fd, (__int64)offset, whence);
1917 #else
1918       return ::lseek(fd, (off_t)offset, whence);
1919 #endif
1920    }
1921    return -1;
1922 }
1923
1924
1925 bool DEVICE::truncate(DCR *dcr) /* We need the DCR for DVD-writing */
1926 {
1927    Dmsg1(100, "truncate %s\n", print_name());
1928    switch (dev_type) {
1929    case B_TAPE_DEV:
1930       /* maybe we should rewind and write and eof ???? */
1931       return true;                    /* we don't really truncate tapes */
1932    case B_DVD_DEV:
1933       return truncate_dvd(dcr);
1934    case B_FILE_DEV:
1935       /* ***FIXME*** we really need to unlink() the file so that
1936        *  its name can be changed for a relabel.
1937        */
1938       if (ftruncate(fd, 0) != 0) {
1939          berrno be;
1940          Mmsg2(errmsg, _("Unable to truncate device %s. ERR=%s\n"), 
1941                print_name(), be.strerror());
1942          return false;
1943       }
1944       return true;
1945    }
1946    return false;
1947 }
1948
1949 /* Mount the device.
1950  * If timeout, wait until the mount command returns 0.
1951  * If !timeout, try to mount the device only once.
1952  */
1953 bool DEVICE::mount(int timeout) 
1954 {
1955    Dmsg0(190, "Enter mount\n");
1956    if (is_mounted()) {
1957       return true;
1958    } else if (requires_mount()) {
1959       return do_mount(1, timeout);
1960    }       
1961    return true;
1962 }
1963
1964 /* Unmount the device
1965  * If timeout, wait until the unmount command returns 0.
1966  * If !timeout, try to unmount the device only once.
1967  */
1968 bool DEVICE::unmount(int timeout) 
1969 {
1970    Dmsg0(90, "Enter unmount\n");
1971    if (is_mounted()) {
1972       return do_mount(0, timeout);
1973    }
1974    return true;
1975 }
1976
1977 /* (Un)mount the device */
1978 bool DEVICE::do_mount(int mount, int dotimeout) 
1979 {
1980    POOL_MEM ocmd(PM_FNAME);
1981    POOLMEM *results;
1982    char *icmd;
1983    int status, timeout;
1984    
1985    sm_check(__FILE__, __LINE__, false);
1986    if (mount) {
1987       if (is_mounted()) {
1988          Dmsg0(200, "======= mount=1\n");
1989          return true;
1990       }
1991       icmd = device->mount_command;
1992    } else {
1993       if (!is_mounted()) {
1994          Dmsg0(200, "======= mount=0\n");
1995          return true;
1996       }
1997       icmd = device->unmount_command;
1998    }
1999    
2000    clear_freespace_ok();
2001    edit_mount_codes(ocmd, icmd);
2002    
2003    Dmsg2(100, "do_mount: cmd=%s mounted=%d\n", ocmd.c_str(), !!is_mounted());
2004
2005    if (dotimeout) {
2006       /* Try at most 1 time to (un)mount the device. This should perhaps be configurable. */
2007       timeout = 1;
2008    } else {
2009       timeout = 0;
2010    }
2011    results = get_memory(4000);
2012    results[0] = 0;
2013
2014    /* If busy retry each second */
2015    Dmsg1(20, "do_mount run_prog=%s\n", ocmd.c_str());
2016    while ((status = run_program_full_output(ocmd.c_str(), 
2017                        max_open_wait/2, results)) != 0) {
2018       /* Doesn't work with internationalization (This is not a problem) */
2019       if (mount && fnmatch("*is already mounted on*", results, 0) == 0) {
2020          break;
2021       }
2022       if (!mount && fnmatch("* not mounted*", results, 0) == 0) {
2023          break;
2024       }
2025       if (timeout-- > 0) {
2026          /* Sometimes the device cannot be mounted because it is already mounted.
2027           * Try to unmount it, then remount it */
2028          if (mount) {
2029             Dmsg1(400, "Trying to unmount the device %s...\n", print_name());
2030             do_mount(0, 0);
2031          }
2032          bmicrosleep(1, 0);
2033          continue;
2034       }
2035       if (status != 0) {
2036          berrno be;
2037          Dmsg5(40, "Device %s cannot be %smounted. stat=%d result=%s ERR=%s\n", print_name(),
2038               (mount ? "" : "un"), status, results, be.strerror(status));
2039          Mmsg(errmsg, _("Device %s cannot be %smounted. ERR=%s\n"), 
2040               print_name(), (mount ? "" : "un"), be.strerror(status));
2041       } else {
2042          Dmsg4(40, "Device %s cannot be %smounted. stat=%d ERR=%s\n", print_name(),
2043               (mount ? "" : "un"), status, results);
2044          Mmsg(errmsg, _("Device %s cannot be %smounted. ERR=%s\n"), 
2045               print_name(), (mount ? "" : "un"), results);
2046       }
2047       /*
2048        * Now, just to be sure it is not mounted, try to read the
2049        *  filesystem.
2050        */
2051       DIR* dp;
2052       struct dirent *entry, *result;
2053       int name_max;
2054       int count;
2055       
2056       name_max = pathconf(".", _PC_NAME_MAX);
2057       if (name_max < 1024) {
2058          name_max = 1024;
2059       }
2060          
2061       if (!(dp = opendir(device->mount_point))) {
2062          berrno be;
2063          dev_errno = errno;
2064          Dmsg3(29, "do_mount: failed to open dir %s (dev=%s), ERR=%s\n", 
2065                device->mount_point, print_name(), be.strerror());
2066          goto get_out;
2067       }
2068       
2069       entry = (struct dirent *)malloc(sizeof(struct dirent) + name_max + 1000);
2070       count = 0;
2071       while (1) {
2072          if ((readdir_r(dp, entry, &result) != 0) || (result == NULL)) {
2073             dev_errno = EIO;
2074             Dmsg2(129, "do_mount: failed to find suitable file in dir %s (dev=%s)\n", 
2075                   device->mount_point, print_name());
2076             break;
2077          }
2078          if ((strcmp(result->d_name, ".")) && (strcmp(result->d_name, "..")) && (strcmp(result->d_name, ".keep"))) {
2079             count++; /* result->d_name != ., .. or .keep (Gentoo-specific) */
2080             break;
2081          } else {
2082             Dmsg2(129, "do_mount: ignoring %s in %s\n", result->d_name, device->mount_point);
2083          }
2084       }
2085       free(entry);
2086       closedir(dp);
2087       
2088       Dmsg1(29, "do_mount: got %d files in the mount point (not counting ., .. and .keep)\n", count);
2089       
2090       if (count > 0) {
2091          /* If we got more than ., .. and .keep */
2092          /*   there must be something mounted */
2093          if (mount) {
2094             Dmsg1(100, "Did Mount by count=%d\n", count);
2095             break;
2096          } else {
2097             /* An unmount request. We failed to unmount - report an error */
2098             set_mounted(true);
2099             free_pool_memory(results);
2100             Dmsg0(200, "== error mount=1 wanted unmount\n");
2101             return false;
2102          }
2103       }
2104 get_out:
2105       set_mounted(false);
2106       sm_check(__FILE__, __LINE__, false);
2107       free_pool_memory(results);
2108       Dmsg0(200, "============ mount=0\n");
2109       return false;
2110    }
2111    
2112    set_mounted(mount);              /* set/clear mounted flag */
2113    free_pool_memory(results);
2114    /* Do not check free space when unmounting */
2115    if (mount && !update_freespace()) {
2116       return false;
2117    }
2118    Dmsg1(200, "============ mount=%d\n", mount);
2119    return true;
2120 }
2121
2122 /*
2123  * Edit codes into (Un)MountCommand, Write(First)PartCommand
2124  *  %% = %
2125  *  %a = archive device name
2126  *  %e = erase (set if cannot mount and first part)
2127  *  %n = part number
2128  *  %m = mount point
2129  *  %v = last part name
2130  *
2131  *  omsg = edited output message
2132  *  imsg = input string containing edit codes (%x)
2133  *
2134  */
2135 void DEVICE::edit_mount_codes(POOL_MEM &omsg, const char *imsg)
2136 {
2137    const char *p;
2138    const char *str;
2139    char add[20];
2140    
2141    POOL_MEM archive_name(PM_FNAME);
2142
2143    omsg.c_str()[0] = 0;
2144    Dmsg1(800, "edit_mount_codes: %s\n", imsg);
2145    for (p=imsg; *p; p++) {
2146       if (*p == '%') {
2147          switch (*++p) {
2148          case '%':
2149             str = "%";
2150             break;
2151          case 'a':
2152             str = dev_name;
2153             break;
2154          case 'e':
2155             if (num_dvd_parts == 0) {
2156                if (truncating || blank_dvd) {
2157                   str = "2";
2158                } else {
2159                   str = "1";
2160                }
2161             } else {
2162                str = "0";
2163             }
2164             break;
2165          case 'n':
2166             bsnprintf(add, sizeof(add), "%d", part);
2167             str = add;
2168             break;
2169          case 'm':
2170             str = device->mount_point;
2171             break;
2172          case 'v':
2173             make_spooled_dvd_filename(this, archive_name);
2174             str = archive_name.c_str();
2175             break;
2176          default:
2177             add[0] = '%';
2178             add[1] = *p;
2179             add[2] = 0;
2180             str = add;
2181             break;
2182          }
2183       } else {
2184          add[0] = *p;
2185          add[1] = 0;
2186          str = add;
2187       }
2188       Dmsg1(1900, "add_str %s\n", str);
2189       pm_strcat(omsg, (char *)str);
2190       Dmsg1(1800, "omsg=%s\n", omsg.c_str());
2191    }
2192 }
2193
2194
2195 /* Return the resource name for the device */
2196 const char *DEVICE::name() const
2197 {
2198    return device->hdr.name;
2199 }
2200
2201 char *
2202 dev_vol_name(DEVICE *dev)
2203 {
2204    return dev->VolCatInfo.VolCatName;
2205 }
2206
2207
2208 /*
2209  * Free memory allocated for the device
2210  */
2211 void DEVICE::term(void)
2212 {
2213    Dmsg1(900, "term dev: %s\n", print_name());
2214    close();
2215    if (dev_name) {
2216       free_memory(dev_name);
2217       dev_name = NULL;
2218    }
2219    if (prt_name) {
2220       free_memory(prt_name);
2221       prt_name = NULL;
2222    }
2223    if (errmsg) {
2224       free_pool_memory(errmsg);
2225       errmsg = NULL;
2226    }
2227    pthread_mutex_destroy(&mutex);
2228    pthread_cond_destroy(&wait);
2229    pthread_cond_destroy(&wait_next_vol);
2230    pthread_mutex_destroy(&spool_mutex);
2231    rwl_destroy(&lock);
2232    if (attached_dcrs) {
2233       delete attached_dcrs;
2234       attached_dcrs = NULL;
2235    }
2236    if (device) {
2237       device->dev = NULL;
2238    }
2239    free((char *)this);
2240 }
2241
2242 /*
2243  * This routine initializes the device wait timers
2244  */
2245 void init_device_wait_timers(DCR *dcr)
2246 {
2247    DEVICE *dev = dcr->dev;
2248    JCR *jcr = dcr->jcr;
2249
2250    /* ******FIXME******* put these on config variables */
2251    dev->min_wait = 60 * 60;
2252    dev->max_wait = 24 * 60 * 60;
2253    dev->max_num_wait = 9;              /* 5 waits =~ 1 day, then 1 day at a time */
2254    dev->wait_sec = dev->min_wait;
2255    dev->rem_wait_sec = dev->wait_sec;
2256    dev->num_wait = 0;
2257    dev->poll = false;
2258    dev->BadVolName[0] = 0;
2259
2260    jcr->min_wait = 60 * 60;
2261    jcr->max_wait = 24 * 60 * 60;
2262    jcr->max_num_wait = 9;              /* 5 waits =~ 1 day, then 1 day at a time */
2263    jcr->wait_sec = jcr->min_wait;
2264    jcr->rem_wait_sec = jcr->wait_sec;
2265    jcr->num_wait = 0;
2266
2267 }
2268
2269 void init_jcr_device_wait_timers(JCR *jcr)
2270 {
2271    /* ******FIXME******* put these on config variables */
2272    jcr->min_wait = 60 * 60;
2273    jcr->max_wait = 24 * 60 * 60;
2274    jcr->max_num_wait = 9;              /* 5 waits =~ 1 day, then 1 day at a time */
2275    jcr->wait_sec = jcr->min_wait;
2276    jcr->rem_wait_sec = jcr->wait_sec;
2277    jcr->num_wait = 0;
2278 }
2279
2280
2281 /*
2282  * The dev timers are used for waiting on a particular device 
2283  *
2284  * Returns: true if time doubled
2285  *          false if max time expired
2286  */
2287 bool double_dev_wait_time(DEVICE *dev)
2288 {
2289    dev->wait_sec *= 2;               /* double wait time */
2290    if (dev->wait_sec > dev->max_wait) {   /* but not longer than maxtime */
2291       dev->wait_sec = dev->max_wait;
2292    }
2293    dev->num_wait++;
2294    dev->rem_wait_sec = dev->wait_sec;
2295    if (dev->num_wait >= dev->max_num_wait) {
2296       return false;
2297    }
2298    return true;
2299 }
2300
2301
2302 void set_os_device_parameters(DCR *dcr)
2303 {
2304    DEVICE *dev = dcr->dev;
2305
2306 #if defined(HAVE_LINUX_OS) || defined(HAVE_WIN32)
2307    struct mtop mt_com;
2308
2309    Dmsg0(050, "In set_os_device_parameters\n");
2310 #if defined(MTSETBLK) 
2311    if (dev->min_block_size == dev->max_block_size &&
2312        dev->min_block_size == 0) {    /* variable block mode */
2313       mt_com.mt_op = MTSETBLK;
2314       mt_com.mt_count = 0;
2315       Dmsg0(050, "Set block size to zero\n");
2316       if (tape_ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
2317          dev->clrerror(MTSETBLK);
2318       }
2319    }
2320 #endif
2321 #if defined(MTSETDRVBUFFER)
2322    if (getpid() == 0) {          /* Only root can do this */
2323       mt_com.mt_op = MTSETDRVBUFFER;
2324       mt_com.mt_count = MT_ST_CLEARBOOLEANS;
2325       if (!dev->has_cap(CAP_TWOEOF)) {
2326          mt_com.mt_count |= MT_ST_TWO_FM;
2327       }
2328       if (dev->has_cap(CAP_EOM)) {
2329          mt_com.mt_count |= MT_ST_FAST_MTEOM;
2330       }
2331       Dmsg0(050, "MTSETDRVBUFFER\n");
2332       if (tape_ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
2333          dev->clrerror(MTSETDRVBUFFER);
2334       }
2335    }
2336 #endif
2337    return;
2338 #endif
2339
2340 #ifdef HAVE_NETBSD_OS
2341    struct mtop mt_com;
2342    if (dev->min_block_size == dev->max_block_size &&
2343        dev->min_block_size == 0) {    /* variable block mode */
2344       mt_com.mt_op = MTSETBSIZ;
2345       mt_com.mt_count = 0;
2346       if (tape_ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
2347          dev->clrerror(MTSETBSIZ);
2348       }
2349       /* Get notified at logical end of tape */
2350       mt_com.mt_op = MTEWARN;
2351       mt_com.mt_count = 1;
2352       if (tape_ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
2353          dev->clrerror(MTEWARN);
2354       }
2355    }
2356    return;
2357 #endif
2358
2359 #if HAVE_FREEBSD_OS || HAVE_OPENBSD_OS
2360    struct mtop mt_com;
2361    if (dev->min_block_size == dev->max_block_size &&
2362        dev->min_block_size == 0) {    /* variable block mode */
2363       mt_com.mt_op = MTSETBSIZ;
2364       mt_com.mt_count = 0;
2365       if (tape_ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
2366          dev->clrerror(MTSETBSIZ);
2367       }
2368    }
2369 /* Turn this on later when fully tested */
2370 #if defined(xxxMTIOCSETEOTMODEL) 
2371    uint32_t neof;
2372    if (dev_cap(dev, CAP_TWOEOF)) {
2373       neof = 2;
2374    } else {
2375       neof = 1;
2376    }
2377    if (ioctl(dev->fd, MTIOCSETEOTMODEL, (caddr_t)&neof) < 0) {
2378       berrno be;
2379       dev->dev_errno = errno;         /* save errno */
2380       Mmsg2(dev->errmsg, _("Unable to set eotmodel on device %s: ERR=%s\n"),
2381             dev->print_name(), be.strerror(dev->dev_errno));
2382       Jmsg(dcr->jcr, M_FATAL, 0, dev->errmsg);
2383    }
2384 #endif
2385    return;
2386 #endif
2387
2388 #ifdef HAVE_SUN_OS
2389    struct mtop mt_com;
2390    if (dev->min_block_size == dev->max_block_size &&
2391        dev->min_block_size == 0) {    /* variable block mode */
2392       mt_com.mt_op = MTSRSZ;
2393       mt_com.mt_count = 0;
2394       if (tape_ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
2395          dev->clrerror(MTSRSZ);
2396       }
2397    }
2398    return;
2399 #endif
2400 }
2401
2402 static bool dev_get_os_pos(DEVICE *dev, struct mtget *mt_stat)
2403 {
2404    Dmsg0(050, "dev_get_os_pos\n");
2405    return dev->has_cap(CAP_MTIOCGET) && 
2406           tape_ioctl(dev->fd, MTIOCGET, (char *)mt_stat) == 0 &&
2407           mt_stat->mt_fileno >= 0;
2408 }
2409
2410 static char *modes[] = {
2411    "CREATE_READ_WRITE",
2412    "OPEN_READ_WRITE",
2413    "OPEN_READ_ONLY",
2414    "OPEN_WRITE_ONLY"
2415 };
2416
2417
2418 static char *mode_to_str(int mode)  
2419 {
2420    static char buf[100];
2421    if (mode < 1 || mode > 4) {
2422       bsnprintf(buf, sizeof(buf), "BAD mode=%d", mode);
2423       return buf;
2424     }
2425    return modes[mode-1];
2426 }