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