]> git.sur5r.net Git - bacula/bacula/blobdiff - bacula/src/stored/dev.c
Updates for debugging disk seek
[bacula/bacula] / bacula / src / stored / dev.c
index c053980bb33fd0731d734f5e6da3df342497c379..459a9caa94de46d1d2fe53ed145d6ed2fe11993b 100644 (file)
  *   Version $Id$
  */
 /*
-   Copyright (C) 2000-2006 Kern Sibbald
+   Bacula® - The Network Backup Solution
 
-   This program is free software; you can redistribute it and/or
-   modify it under the terms of the GNU General Public License
-   version 2 as amended with additional clauses defined in the
-   file LICENSE in the main source directory.
+   Copyright (C) 2000-2006 Free Software Foundation Europe e.V.
 
-   This program is distributed in the hope that it will be useful,
-   but WITHOUT ANY WARRANTY; without even the implied warranty of
-   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
-   the file LICENSE for additional details.
+   The main author of Bacula is Kern Sibbald, with contributions from
+   many others, a complete list can be found in the file AUTHORS.
+   This program is Free Software; you can redistribute it and/or
+   modify it under the terms of version two of the GNU General Public
+   License as published by the Free Software Foundation plus additions
+   that are listed in the file LICENSE.
 
- */
+   This program is distributed in the hope that it will be useful, but
+   WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+   General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program; if not, write to the Free Software
+   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+   02110-1301, USA.
+
+   Bacula® is a registered trademark of John Walker.
+   The licensor of Bacula is the Free Software Foundation Europe
+   (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich,
+   Switzerland, email:ftf@fsfeurope.org.
+*/
 
 /*
  * Handling I/O errors and end of tape conditions are a bit tricky.
@@ -49,7 +62,7 @@
  * On either an I/O error or end of tape,
  * we will stop writing on the physical device (no I/O recovery is
  * attempted at least in this daemon). The state flag will be sent
- * to include ST_EOT, which is ephimeral, and ST_WEOT, which is
+ * to include ST_EOT, which is ephemeral, and ST_WEOT, which is
  * persistent. Lots of routines clear ST_EOT, but ST_WEOT is
  * cleared only when the problem goes away.  Now when ST_WEOT
  * is set all calls to write_block_to_device() call the fix_up
@@ -80,7 +93,7 @@
 #endif
 
 /* Forward referenced functions */
-void set_os_device_parameters(DEVICE *dev);
+void set_os_device_parameters(DCR *dcr);   
 static bool dev_get_os_pos(DEVICE *dev, struct mtget *mt_stat);
 static char *mode_to_str(int mode);
 
@@ -118,7 +131,7 @@ init_dev(JCR *jcr, DEVRES *device)
       } else if (S_ISCHR(statp.st_mode)) {
          device->dev_type = B_TAPE_DEV;
       } else if (S_ISFIFO(statp.st_mode)) {
-         device->dev_type = B_FILE_DEV;
+         device->dev_type = B_FIFO_DEV;
       } else if (!(device->cap_bits & CAP_REQMOUNT)) {
          Jmsg2(jcr, M_ERROR, 0, _("%s is an unknown device type. Must be tape or directory\n"
                " or have RequiresMount=yes for DVD. st_mode=%x\n"),
@@ -323,70 +336,94 @@ void DEVICE::set_mode(int new_mode)
 void DEVICE::open_tape_device(DCR *dcr, int omode) 
 {
    file_size = 0;
-   int timeout;
-   int nonblocking = O_NONBLOCK;
-   Dmsg0(29, "open dev: device is tape\n");
+   int timeout = max_open_wait;
+#if !defined(HAVE_WIN32)
+   struct mtop mt_com;
+   utime_t start_time = time(NULL);
+#endif
+
+
+   Dmsg0(29, "Open dev: device is tape\n");
 
    get_autochanger_loaded_slot(dcr);
 
+   openmode = omode;
    set_mode(omode);
-   timeout = max_open_wait;
+
+   if (timeout < 1) {
+      timeout = 1;
+   }
    errno = 0;
    if (is_fifo() && timeout) {
       /* Set open timer */
       tid = start_thread_timer(pthread_self(), timeout);
    }
-   /* If busy retry each second for max_open_wait seconds */
-   Dmsg3(100, "Try open %s mode=%s nonblocking=%d\n", print_name(),
-      mode_to_str(omode), nonblocking);
-   /* Use system open() */
-
+   Dmsg2(100, "Try open %s mode=%s\n", print_name(), mode_to_str(omode));
 #if defined(HAVE_WIN32)
+
+   /*   Windows Code */
    if ((fd = tape_open(dev_name, mode)) < 0) {
-      berrno be;
       dev_errno = errno;
-
-      Mmsg2(errmsg, _("Unable to open device %s: ERR=%s\n"),
-            print_name(), be.strerror(dev_errno));
-      Jmsg0(dcr->jcr, M_FATAL, 0, errmsg);
    }
+
 #else
-   while ((fd = ::open(dev_name, mode+nonblocking)) < 0) {
-      berrno be;
-      dev_errno = errno;
-      Dmsg5(050, "Open omode=%d mode=%x nonblock=%d error errno=%d ERR=%s\n", 
-           omode, mode, nonblocking, errno, be.strerror());
-      if (dev_errno == EINTR || dev_errno == EAGAIN) {
-         Dmsg0(100, "Continue open\n");
-         continue;
-      }
-      /* Busy wait for specified time (default = 5 mins) */
-      if (dev_errno == EBUSY && timeout-- > 0) {
-         Dmsg2(100, "Device %s busy. ERR=%s\n", print_name(), be.strerror());
-         bmicrosleep(1, 0);
-         continue;
+
+   /*  UNIX  Code */
+   /* If busy retry each second for max_open_wait seconds */
+   for ( ;; ) {
+      /* Try non-blocking open */
+      fd = ::open(dev_name, mode+O_NONBLOCK);
+      if (fd < 0) {
+         berrno be;
+         dev_errno = errno;
+         Dmsg5(050, "Open error on %s omode=%d mode=%x errno=%d: ERR=%s\n", 
+              print_name(), omode, mode, errno, be.strerror());
+      } else {
+         /* Tape open, now rewind it */
+         Dmsg0(050, "Rewind after open\n");
+         mt_com.mt_op = MTREW;
+         mt_com.mt_count = 1;
+         if (ioctl(fd, MTIOCTOP, (char *)&mt_com) < 0) {
+            berrno be;
+            dev_errno = errno;           /* set error status from rewind */
+            ::close(fd);
+            clear_opened();
+            Dmsg2(100, "Rewind error on %s close: ERR=%s\n", print_name(),
+                  be.strerror(dev_errno));
+            /* If we get busy, device is probably rewinding, try again */
+            if (dev_errno != EBUSY) {
+               break;                    /* error -- no medium */
+            }
+         } else {
+            /* Got fd and rewind worked, so we must have medium in drive */
+            ::close(fd);
+            fd = ::open(dev_name, mode);  /* open normally */
+            if (fd < 0) {
+               berrno be;
+               dev_errno = errno;
+               Dmsg5(050, "Open error on %s omode=%d mode=%x errno=%d: ERR=%s\n", 
+                     print_name(), omode, mode, errno, be.strerror());
+               break;
+            }
+            dev_errno = 0;
+            lock_door();
+            set_os_device_parameters(dcr);       /* do system dependent stuff */
+            break;                               /* Successfully opened and rewound */
+         }
       }
-      Mmsg2(errmsg, _("Unable to open device %s: ERR=%s\n"),
-            print_name(), be.strerror(dev_errno));
-      /* Stop any open timer we set */
-      if (tid) {
-         stop_thread_timer(tid);
-         tid = 0;
+      bmicrosleep(5, 0);
+      /* Exceed wait time ? */
+      if (time(NULL) - start_time >= max_open_wait) {
+         break;                       /* yes, get out */
       }
-      Jmsg0(dcr->jcr, M_FATAL, 0, errmsg);
-      break;
    }
 #endif
 
-   if (fd >= 0) {
-      openmode = omode;              /* save open mode */
-      set_blocking();   
-      Dmsg2(100, "openmode=%d %s\n", openmode, mode_to_str(openmode));
-      dev_errno = 0;
-      update_pos_dev(this);                /* update position */
-      set_os_device_parameters(this);      /* do system dependent stuff */
-   } else {
-      clear_opened();
+   if (!is_open()) {
+      berrno be;
+      Mmsg2(errmsg, _("Unable to open device %s: ERR=%s\n"),
+            print_name(), be.strerror(dev_errno));
+      Dmsg1(100, "%s", errmsg);
    }
 
    /* Stop any open() timer we started */
@@ -397,24 +434,6 @@ void DEVICE::open_tape_device(DCR *dcr, int omode)
    Dmsg1(29, "open dev: tape %d opened\n", fd);
 }
 
-void DEVICE::set_blocking()
-{
-   int oflags;
-   /* Try to reset blocking */
-#ifdef xxx
-   if ((oflags = fcntl(fd, F_GETFL, 0)) < 0 ||
-       fcntl(fd, F_SETFL, oflags & ~O_NONBLOCK) < 0) {
-      berrno be;
-      ::close(fd);                   /* use system close() */
-      fd = ::open(dev_name, mode);       
-      Dmsg2(100, "fcntl error. ERR=%s. Close-reopen fd=%d\n", be.strerror(), fd);
-   }
-#endif
-   oflags = fcntl(fd, F_GETFL, 0);       
-   if (oflags > 0 && (oflags & O_NONBLOCK)) {
-      fcntl(fd, F_SETFL, oflags & ~O_NONBLOCK);
-   }
-}
 
 /*
  * Open a file device
@@ -432,7 +451,7 @@ void DEVICE::open_file_device(DCR *dcr, int omode)
    pm_strcpy(archive_name, dev_name);
    /*  
     * If this is a virtual autochanger (i.e. changer_res != NULL)
-    *  we simply use the deviced name, assuming it has been
+    *  we simply use the device name, assuming it has been
     *  appropriately setup by the "autochanger".
     */
    if (!device->changer_res) {
@@ -443,7 +462,7 @@ void DEVICE::open_file_device(DCR *dcr, int omode)
          return;
       }
 
-      if (archive_name.c_str()[strlen(archive_name.c_str())-1] != '/') {
+      if (!IsPathSeparator(archive_name.c_str()[strlen(archive_name.c_str())-1])) {
          pm_strcat(archive_name, "/");
       }
       pm_strcat(archive_name, VolCatInfo.VolCatName);
@@ -466,7 +485,8 @@ void DEVICE::open_file_device(DCR *dcr, int omode)
       Emsg0(M_FATAL, 0, errmsg);
    } else {
       dev_errno = 0;
-      update_pos_dev(this);                /* update position */
+      file = 0;
+      file_addr = 0;
    }
    Dmsg4(29, "open dev: disk fd=%d opened, part=%d/%d, part_size=%u\n", 
       fd, part, num_dvd_parts, part_size);
@@ -486,18 +506,18 @@ void DEVICE::open_dvd_device(DCR *dcr, int omode)
    /*
     * Handle opening of DVD Volume
     */     
-   Dmsg3(29, "Enter: open_dvd_dev: %s dev=%s mode=%s\n", is_dvd()?"DVD":"disk",
-         archive_name.c_str(), mode_to_str(omode));
+   Dmsg2(29, "Enter: open_dvd_dev: DVD vol=%s mode=%s\n", 
+         &dcr->VolCatInfo, mode_to_str(omode));
 
    /*
-    * For a DVD we must alway pull the state info from dcr->VolCatInfo
+    * For a DVD we must always pull the state info from dcr->VolCatInfo
     *  This is a bit ugly, but is necessary because we need to open/close/re-open
     *  the dvd file in order to properly mount/unmount and access the
     *  DVD. So we store the state of the DVD as far as is known in the 
     *  catalog in dcr->VolCatInfo, and thus we refresh the dev->VolCatInfo
     *  copy here, when opening.
     */
-   memcpy(&VolCatInfo, &dcr->VolCatInfo, sizeof(VolCatInfo));
+   VolCatInfo = dcr->VolCatInfo;         /* structure assignment */
    Dmsg1(100, "Volume=%s\n", VolCatInfo.VolCatName);
 
    if (VolCatInfo.VolCatName[0] == 0) {
@@ -518,16 +538,33 @@ void DEVICE::open_dvd_device(DCR *dcr, int omode)
    if (num_dvd_parts != VolCatInfo.VolCatParts) {
       num_dvd_parts = VolCatInfo.VolCatParts;
    }
-   // Clear any previous truncated_dvd status - we will recalculate it here
-   truncated_dvd = false;
+
+   /*
+    * If we are not trying to access the last part, set mode to 
+    *   OPEN_READ_ONLY as writing would be an error.
+    */
+   Dmsg2(29, "open DVD part=%d num_dvd_parts=%d\n", part, num_dvd_parts);
+   /* Now find the name of the part that we want to access */
+   if (part <= num_dvd_parts) {
+      omode = OPEN_READ_ONLY;
+      make_mounted_dvd_filename(this, archive_name);
+      set_part_spooled(false);
+   } else {
+      omode = OPEN_READ_WRITE;
+      make_spooled_dvd_filename(this, archive_name);
+      set_part_spooled(true);
+   }
+   set_mode(omode);
+
+   // Clear any previous blank_dvd status - we will recalculate it here
+   blank_dvd = false;
 
    Dmsg3(99, "open_dvd_device: part=%d num_dvd_parts=%d, VolCatInfo.VolCatParts=%d\n",
       part, num_dvd_parts, dcr->VolCatInfo.VolCatParts);
      
-   if (mount_dvd(this, 1)) {
+   if (mount(1)) {
       Dmsg0(99, "DVD device mounted.\n");
-      if ((num_dvd_parts == 0) && (!truncating)) {
-#ifdef needed
+      if (num_dvd_parts == 0 && !truncating) {
          /*
           * If we can mount the device, and we are not truncating the DVD, 
           * we usually want to abort. There is one exception, if there is 
@@ -535,21 +572,48 @@ void DEVICE::open_dvd_device(DCR *dcr, int omode)
           * we continue (it's the method used by truncate_dvd to truncate a volume).   
           */
          if (!check_can_write_on_non_blank_dvd(dcr)) {
-            Mmsg(errmsg, _("The media in the device %s is not empty, please blank it before writing anything to it.\n"), print_name());
+            Mmsg(errmsg, _("The DVD in device %s contains data, please blank it before writing.\n"), print_name());
+            Emsg0(M_FATAL, 0, errmsg);
+            unmount(1); /* Unmount the device, so the operator can change it. */
+            clear_opened();
+            return;
+         }
+         blank_dvd = true;
+      } else {
+         /*
+          * Ensure that we have the correct DVD loaded by looking for part1.
+          * We only succeed the open if it exists. Failure to do this could
+          * leave us trying to add a part to a different DVD!
+          */
+         uint32_t oldpart = part;
+         struct stat statp;
+         POOL_MEM part1_name(PM_FNAME);
+         part = 1;
+         make_mounted_dvd_filename(this, part1_name);
+         part = oldpart;
+         if (stat(part1_name.c_str(), &statp) < 0) {
+            berrno be;
+            Mmsg(errmsg, _("Unable to stat DVD part 1 file %s: ERR=%s\n"),
+               part1_name.c_str(), be.strerror());
+            Emsg0(M_FATAL, 0, errmsg);
+            clear_opened();
+            return;
+         }
+         if (!S_ISREG(statp.st_mode)) {
+            /* It is not a regular file */
+            Mmsg(errmsg, _("DVD part 1 is not a regular file %s.\n"),
+               part1_name.c_str());
             Emsg0(M_FATAL, 0, errmsg);
-            unmount_dvd(this, 1); /* Unmount the device, so the operator can change it. */
             clear_opened();
             return;
          }
-#endif
-         truncated_dvd = true;
       }
    } else {
       Dmsg0(99, "DVD device mount failed.\n");
       /* We cannot mount the device */
       if (num_dvd_parts == 0) {
          /* Run free space, check there is a media. */
-         if (!update_free_space_dev(this)) {
+         if (!update_freespace()) {
             Emsg0(M_FATAL, 0, errmsg);
             clear_opened();
             return;
@@ -557,13 +621,13 @@ void DEVICE::open_dvd_device(DCR *dcr, int omode)
          if (have_media()) {
             Dmsg1(29, "Could not mount device %s, this is not a problem (num_dvd_parts == 0), and have media.\n", print_name());
          } else {
-            Mmsg(errmsg, _("There is no valid media in the device %s.\n"), print_name());
+            Mmsg(errmsg, _("There is no valid DVD in device %s.\n"), print_name());
             Emsg0(M_FATAL, 0, errmsg);
             clear_opened();
             return;
          }
       }  else {
-         Mmsg(errmsg, _("Could not mount device %s.\n"), print_name());
+         Mmsg(errmsg, _("Could not mount DVD device %s.\n"), print_name());
          Emsg0(M_FATAL, 0, errmsg);
          clear_opened();
          return;
@@ -576,19 +640,6 @@ void DEVICE::open_dvd_device(DCR *dcr, int omode)
    openmode = omode;
    Dmsg2(100, "openmode=%d %s\n", openmode, mode_to_str(openmode));
    
-   /*
-    * If we are not trying to access the last part, set mode to 
-    *   OPEN_READ_ONLY as writing would be an error.
-    */
-   Dmsg2(29, "open DVD part=%d num_dvd_parts=%d\n", part, num_dvd_parts);
-   if (part <= num_dvd_parts) {
-      omode = OPEN_READ_ONLY;
-      make_mounted_dvd_filename(this, archive_name);
-   } else {
-      omode = OPEN_READ_WRITE;
-      make_spooled_dvd_filename(this, archive_name);
-   }
-   set_mode(omode);
 
    /* If creating file, give 0640 permissions */
    Dmsg3(29, "mode=%s open(%s, 0x%x, 0640)\n", mode_to_str(omode), 
@@ -618,7 +669,7 @@ void DEVICE::open_dvd_device(DCR *dcr, int omode)
       }
    }
    Dmsg1(100, "after open fd=%d\n", fd);
-   if (fd >= 0) {
+   if (is_open()) {
       if (omode == OPEN_READ_WRITE || omode == CREATE_READ_WRITE) {
          set_append();
       }
@@ -635,7 +686,7 @@ void DEVICE::open_dvd_device(DCR *dcr, int omode)
       } else {
          part_size = filestat.st_size;
          dev_errno = 0;
-         update_pos_dev(this);                /* update position */
+         update_pos(dcr);                    /* update position */
       }
    }
 }
@@ -716,10 +767,10 @@ bool DEVICE::rewind(DCR *dcr)
          break;
       }
    } else if (is_file() || is_dvd()) {
-      if (lseek_dev(this, (off_t)0, SEEK_SET) < 0) {
+      if (lseek(dcr, (boffset_t)0, SEEK_SET) < 0) {
          berrno be;
          dev_errno = errno;
-         Mmsg2(errmsg, _("lseek_dev error on %s. ERR=%s.\n"),
+         Mmsg2(errmsg, _("lseek error on %s. ERR=%s.\n"),
             print_name(), be.strerror());
          return false;
       }
@@ -794,16 +845,16 @@ void DEVICE::set_ateot()
  *  Returns: true  on succes
  *           false on error
  */
-bool DEVICE::eod()
+bool DEVICE::eod(DCR *dcr)
 {
    struct mtop mt_com;
    struct mtget mt_stat;
    bool ok = true;
-   off_t pos;
+   boffset_t pos;
 
    if (fd < 0) {
       dev_errno = EBADF;
-      Mmsg1(errmsg, _("Bad call to eod_dev. Device %s not open\n"), print_name());
+      Mmsg1(errmsg, _("Bad call to eod. Device %s not open\n"), print_name());
       return false;
    }
 
@@ -811,7 +862,7 @@ bool DEVICE::eod()
    return fsf(VolCatInfo.VolCatFiles);
 #endif
 
-   Dmsg0(29, "eod_dev\n");
+   Dmsg0(29, "eod\n");
    if (at_eot()) {
       return true;
    }
@@ -823,16 +874,16 @@ bool DEVICE::eod()
       return true;
    }
    if (!is_tape()) {
-      pos = lseek_dev(this, (off_t)0, SEEK_END);
+      pos = lseek(dcr, (boffset_t)0, SEEK_END);
 //    Dmsg1(100, "====== Seek to %lld\n", pos);
       if (pos >= 0) {
-         update_pos_dev(this);
+         update_pos(dcr);
          set_eot();
          return true;
       }
       dev_errno = errno;
       berrno be;
-      Mmsg2(errmsg, _("lseek_dev error on %s. ERR=%s.\n"),
+      Mmsg2(errmsg, _("lseek error on %s. ERR=%s.\n"),
              print_name(), be.strerror());
       return false;
    }
@@ -867,7 +918,7 @@ bool DEVICE::eod()
          berrno be;
          clrerror(mt_com.mt_op);
          Dmsg1(50, "ioctl error: %s\n", be.strerror());
-         update_pos_dev(this);
+         update_pos(dcr);
          Mmsg2(errmsg, _("ioctl MTEOM error on %s. ERR=%s.\n"),
             print_name(), be.strerror());
          return false;
@@ -898,7 +949,7 @@ bool DEVICE::eod()
        */
       int file_num;
       for (file_num=file; !at_eot(); file_num++) {
-         Dmsg0(200, "eod_dev: doing fsf 1\n");
+         Dmsg0(200, "eod: doing fsf 1\n");
          if (!fsf(1)) {
             Dmsg0(200, "fsf error.\n");
             return false;
@@ -906,12 +957,12 @@ bool DEVICE::eod()
          /*
           * Avoid infinite loop by ensuring we advance.
           */
-         if (file_num == (int)file) {
+         if (!at_eot() && file_num == (int)file) {
             struct mtget mt_stat;
             Dmsg1(100, "fsf did not advance from file %d\n", file_num);
             set_ateof();
             if (dev_get_os_pos(this, &mt_stat)) {
-               Dmsg2(100, "Adjust file from %d to %d\n", file , mt_stat.mt_fileno);
+               Dmsg2(100, "Adjust file from %d to %d\n", file_num, mt_stat.mt_fileno);
                file = mt_stat.mt_fileno;
             }       
             break;
@@ -932,10 +983,10 @@ bool DEVICE::eod()
          Dmsg2(100, "BSFATEOF adjust file from %d to %d\n", file , mt_stat.mt_fileno);
          file = mt_stat.mt_fileno;
       } else {
-         file++;                 /* wing it -- not correct on all OSes */
+         file++;                       /* wing it -- not correct on all OSes */
       }
    } else {
-      update_pos_dev(this);                   /* update position */
+      update_pos(dcr);                 /* update position */
    }
    Dmsg1(200, "EOD dev->file=%d\n", file);
    return ok;
@@ -947,40 +998,39 @@ bool DEVICE::eod()
  *  Returns: true  on succes
  *           false on error
  */
-bool update_pos_dev(DEVICE *dev)
+bool DEVICE::update_pos(DCR *dcr)
 {
-   off_t pos;
+   boffset_t pos;
    bool ok = true;
 
-   if (dev->fd < 0) {
-      dev->dev_errno = EBADF;
-      Mmsg0(dev->errmsg, _("Bad device call. Device not open\n"));
-      Emsg0(M_FATAL, 0, dev->errmsg);
+   if (!is_open()) {
+      dev_errno = EBADF;
+      Mmsg0(errmsg, _("Bad device call. Device not open\n"));
+      Emsg1(M_FATAL, 0, "%s", errmsg);
       return false;
    }
 
    /* Find out where we are */
-   if (dev->is_file()) {
-      dev->file = 0;
-      dev->file_addr = 0;
-      pos = lseek_dev(dev, (off_t)0, SEEK_CUR);
+   if (is_file() || is_dvd()) {
+      file = 0;
+      file_addr = 0;
+      pos = lseek(dcr, (boffset_t)0, SEEK_CUR);
       if (pos < 0) {
          berrno be;
-         dev->dev_errno = errno;
+         dev_errno = errno;
          Pmsg1(000, _("Seek error: ERR=%s\n"), be.strerror());
-         Mmsg2(dev->errmsg, _("lseek_dev error on %s. ERR=%s.\n"),
-            dev->print_name(), be.strerror());
+         Mmsg2(errmsg, _("lseek error on %s. ERR=%s.\n"),
+            print_name(), be.strerror());
          ok = false;
       } else {
-         dev->file_addr = pos;
-         dev->block_num = (uint32_t)pos;
-         dev->file = (uint32_t)(pos >> 32);
+         file_addr = pos;
+         block_num = (uint32_t)pos;
+         file = (uint32_t)(pos >> 32);
       }
    }
    return ok;
 }
 
-
 /*
  * Return the status of the device.  This was meant
  * to be a generic routine. Unfortunately, it doesn't
@@ -1162,11 +1212,7 @@ bool DEVICE::offline()
    block_num = file = 0;
    file_size = 0;
    file_addr = 0;
-#ifdef MTUNLOCK
-   mt_com.mt_op = MTUNLOCK;
-   mt_com.mt_count = 1;
-   tape_ioctl(fd, MTIOCTOP, (char *)&mt_com);
-#endif
+   unlock_door();
    mt_com.mt_op = MTOFFL;
    mt_com.mt_count = 1;
    if (tape_ioctl(fd, MTIOCTOP, (char *)&mt_com) < 0) {
@@ -1211,9 +1257,9 @@ bool DEVICE::fsf(int num)
    struct mtop mt_com;
    int stat = 0;
 
-   if (fd < 0) {
+   if (!is_open()) {
       dev_errno = EBADF;
-      Mmsg0(errmsg, _("Bad call to fsf_dev. Device not open\n"));
+      Mmsg0(errmsg, _("Bad call to fsf. Device not open\n"));
       Emsg0(M_FATAL, 0, errmsg);
       return false;
    }
@@ -1221,6 +1267,7 @@ bool DEVICE::fsf(int num)
    if (!is_tape()) {
       return true;
    }
+
    if (at_eot()) {
       dev_errno = 0;
       Mmsg1(errmsg, _("Device %s at End of Tape.\n"), print_name());
@@ -1301,7 +1348,6 @@ bool DEVICE::fsf(int num)
             }
          }
          if (stat == 0) {                /* EOF */
-            update_pos_dev(this);
             Dmsg1(100, "End of File mark from read. File=%d\n", file+1);
             /* Two reads of zero means end of tape */
             if (at_eof()) {
@@ -1350,7 +1396,6 @@ bool DEVICE::fsf(int num)
          stat = 0;
       }
    }
-   update_pos_dev(this);
    Dmsg1(200, "Return %d from FSF\n", stat);
    if (at_eof()) {
       Dmsg0(200, "ST_EOF set on exit FSF\n");
@@ -1372,7 +1417,7 @@ bool DEVICE::bsf(int num)
    struct mtop mt_com;
    int stat;
 
-   if (fd < 0) {
+   if (!is_open()) {
       dev_errno = EBADF;
       Mmsg0(errmsg, _("Bad call to bsf. Device not open\n"));
       Emsg0(M_FATAL, 0, errmsg);
@@ -1384,6 +1429,7 @@ bool DEVICE::bsf(int num)
          print_name());
       return false;
    }
+
    Dmsg0(29, "bsf\n");
    clear_eot();
    clear_eof();
@@ -1399,7 +1445,6 @@ bool DEVICE::bsf(int num)
       Mmsg2(errmsg, _("ioctl MTBSF error on %s. ERR=%s.\n"),
          print_name(), be.strerror());
    }
-   update_pos_dev(this);
    return stat == 0;
 }
 
@@ -1414,7 +1459,7 @@ bool DEVICE::fsr(int num)
    struct mtop mt_com;
    int stat;
 
-   if (fd < 0) {
+   if (!is_open()) {
       dev_errno = EBADF;
       Mmsg0(errmsg, _("Bad call to fsr. Device not open\n"));
       Emsg0(M_FATAL, 0, errmsg);
@@ -1424,6 +1469,7 @@ bool DEVICE::fsr(int num)
    if (!is_tape()) {
       return false;
    }
+
    if (!has_cap(CAP_FSR)) {
       Mmsg1(errmsg, _("ioctl MTFSR not permitted on %s.\n"), print_name());
       return false;
@@ -1456,7 +1502,6 @@ bool DEVICE::fsr(int num)
       Mmsg3(errmsg, _("ioctl MTFSR %d error on %s. ERR=%s.\n"),
          num, print_name(), be.strerror());
    }
-   update_pos_dev(this);
    return stat == 0;
 }
 
@@ -1470,7 +1515,7 @@ bool DEVICE::bsr(int num)
    struct mtop mt_com;
    int stat;
 
-   if (fd < 0) {
+   if (!is_open()) {
       dev_errno = EBADF;
       Mmsg0(errmsg, _("Bad call to bsr_dev. Device not open\n"));
       Emsg0(M_FATAL, 0, errmsg);
@@ -1499,18 +1544,38 @@ bool DEVICE::bsr(int num)
       Mmsg2(errmsg, _("ioctl MTBSR error on %s. ERR=%s.\n"),
          print_name(), be.strerror());
    }
-   update_pos_dev(this);
    return stat == 0;
 }
 
+void DEVICE::lock_door()
+{
+#ifdef MTLOCK
+   struct mtop mt_com;
+   mt_com.mt_op = MTLOCK;
+   mt_com.mt_count = 1;
+   tape_ioctl(fd, MTIOCTOP, (char *)&mt_com);
+#endif
+}
+
+void DEVICE::unlock_door()
+{
+#ifdef MTUNLOCK
+   struct mtop mt_com;
+   mt_com.mt_op = MTUNLOCK;
+   mt_com.mt_count = 1;
+   tape_ioctl(fd, MTIOCTOP, (char *)&mt_com);
+#endif
+}
+
 /*
  * Reposition the device to file, block
  * Returns: false on failure
  *          true  on success
  */
-bool DEVICE::reposition(uint32_t rfile, uint32_t rblock)
+bool DEVICE::reposition(DCR *dcr, uint32_t rfile, uint32_t rblock)
 {
-   if (fd < 0) {
+   if (!is_open()) {
       dev_errno = EBADF;
       Mmsg0(errmsg, _("Bad call to reposition. Device not open\n"));
       Emsg0(M_FATAL, 0, errmsg);
@@ -1518,12 +1583,12 @@ bool DEVICE::reposition(uint32_t rfile, uint32_t rblock)
    }
 
    if (!is_tape()) {
-      off_t pos = (((off_t)rfile)<<32) + (off_t)rblock;
-      Dmsg1(100, "===== lseek_dev to %d\n", (int)pos);
-      if (lseek_dev(this, pos, SEEK_SET) == (off_t)-1) {
+      boffset_t pos = (((boffset_t)rfile)<<32) | rblock;
+      Dmsg1(100, "===== lseek to %d\n", (int)pos);
+      if (lseek(dcr, pos, SEEK_SET) == (boffset_t)-1) {
          berrno be;
          dev_errno = errno;
-         Mmsg2(errmsg, _("lseek_dev error on %s. ERR=%s.\n"),
+         Mmsg2(errmsg, _("lseek error on %s. ERR=%s.\n"),
             print_name(), be.strerror());
          return false;
       }
@@ -1532,8 +1597,9 @@ bool DEVICE::reposition(uint32_t rfile, uint32_t rblock)
       file_addr = pos;
       return true;
    }
-   Dmsg4(100, "reposition from %u:%u to %u:%u\n",
-      file, block_num, rfile, rblock);
+
+   /* After this point, we are tape only */
+   Dmsg4(100, "reposition from %u:%u to %u:%u\n", file, block_num, rfile, rblock);
    if (rfile < file) {
       Dmsg0(100, "Rewind\n");
       if (!rewind(NULL)) {
@@ -1552,7 +1618,7 @@ bool DEVICE::reposition(uint32_t rfile, uint32_t rblock)
       Dmsg2(100, "wanted_blk=%d at_blk=%d\n", rblock, block_num);
       Dmsg0(100, "bsf 1\n");
       bsf(1);
-      Dmsg0(100, "fsf_dev 1\n");
+      Dmsg0(100, "fsf 1\n");
       fsf(1);
       Dmsg2(100, "wanted_blk=%d at_blk=%d\n", rblock, block_num);
    }
@@ -1560,6 +1626,17 @@ bool DEVICE::reposition(uint32_t rfile, uint32_t rblock)
       /* Ignore errors as Bacula can read to the correct block */
       Dmsg1(100, "fsr %d\n", rblock-block_num);
       return fsr(rblock-block_num);
+   } else {
+      while (rblock > block_num) {
+         if (!read_block_from_dev(dcr, NO_BLOCK_NUMBER_CHECK)) {
+            berrno be;
+            dev_errno = errno;
+            Dmsg2(30, "Failed to find requested block on %s: ERR=%s",
+               print_name(), be.strerror());
+            return false;
+         }
+         Dmsg2(300, "moving forward wanted_blk=%d at_blk=%d\n", rblock, block_num);
+      }
    }
    return true;
 }
@@ -1577,7 +1654,7 @@ bool DEVICE::weof(int num)
    int stat;
    Dmsg0(129, "weof_dev\n");
    
-   if (fd < 0) {
+   if (!is_open()) {
       dev_errno = EBADF;
       Mmsg0(errmsg, _("Bad call to weof_dev. Device not open\n"));
       Emsg0(M_FATAL, 0, errmsg);
@@ -1633,6 +1710,7 @@ void DEVICE::clrerror(int func)
    if (!is_tape()) {
       return;
    }
+
    if (errno == ENOTTY || errno == ENOSYS) { /* Function not implemented */
       switch (func) {
       case -1:
@@ -1671,6 +1749,17 @@ void DEVICE::clrerror(int func)
          msg = "MTSETBLK";
          break;
 #endif
+#ifdef MTSETDRVBUFFER
+      case MTSETDRVBUFFER:
+         msg = "MTSETDRVBUFFER";
+         break;
+#endif
+#ifdef MTRESET
+      case MTRESET:
+         msg = "MTRESET";
+         break;
+#endif
+
 #ifdef MTSETBSIZ 
       case MTSETBSIZ:
          msg = "MTSETBSIZ";
@@ -1761,40 +1850,22 @@ void DEVICE::close()
    if (has_cap(CAP_OFFLINEUNMOUNT)) {
       offline();
    }
-   if (fd >= 0) {
-      if (is_tape()) {
-         tape_close(fd);
-      } else {
-         ::close(fd);
-      }
-   } else {
+
+   if (!is_open()) {
       Dmsg2(100, "device %s already closed vol=%s\n", print_name(),
          VolHdr.VolumeName);
       return;                         /* already closed */
    }
 
-   if (is_dvd() && !unmount_dvd(this, 1)) {
-      Dmsg1(0, "Cannot unmount device %s.\n", print_name());
-   }
-   
-   /* Remove the last part file if it is empty */
-   if (num_dvd_parts > 0) {
-      struct stat statp;
-      int part_save = part;
-      POOL_MEM archive_name(PM_FNAME);
-
-      part = num_dvd_parts;
-      Dmsg3(100, "Remove empty part in close call make_dvd_filename. part=%d num=%d vol=%s\n", 
-         part, num_dvd_parts, VolCatInfo.VolCatName);
-      make_spooled_dvd_filename(this, archive_name);
-      /* Check that the part file is empty */
-      if ((stat(archive_name.c_str(), &statp) == 0) && (statp.st_size == 0)) {
-         Dmsg1(100, "unlink(%s)\n", archive_name.c_str());
-         unlink(archive_name.c_str());
-      }
-      part = part_save;               /* restore part number */
+   switch (dev_type) {
+   case B_TAPE_DEV:
+      unlock_door(); 
+      tape_close(fd);
+      break;
+   default:
+      ::close(fd);
    }
-   
+
    /* Clean up device packet so it can be reused */
    clear_opened();
    state &= ~(ST_LABEL|ST_READ|ST_APPEND|ST_EOT|ST_WEOT|ST_EOF);
@@ -1803,6 +1874,7 @@ void DEVICE::close()
    file_size = 0;
    file_addr = 0;
    EndFile = EndBlock = 0;
+   openmode = 0;
    Slot = -1;             /* unknown slot */
    free_volume(this);
    memset(&VolCatInfo, 0, sizeof(VolCatInfo));
@@ -1811,30 +1883,69 @@ void DEVICE::close()
       stop_thread_timer(tid);
       tid = 0;
    }
-   openmode = 0;
 }
 
+/*
+ * This call closes the device, but it is used in DVD handling
+ *  where we close one part and then open the next part. The
+ *  difference between close_part() and close() is that close_part()
+ *  saves the state information of the device (e.g. the Volume lable,
+ *  the Volume Catalog record, ...  This permits opening and closing
+ *  the Volume parts multiple times without losing track of what the    
+ *  main Volume parameters are.
+ */
+void DEVICE::close_part(DCR *dcr)
+{
+   VOLUME_LABEL saveVolHdr;
+   VOLUME_CAT_INFO saveVolCatInfo;     /* Volume Catalog Information */
+
+
+   saveVolHdr = VolHdr;               /* structure assignment */
+   saveVolCatInfo = VolCatInfo;       /* structure assignment */
+   close();                           /* close current part */
+   VolHdr = saveVolHdr;               /* structure assignment */
+   VolCatInfo = saveVolCatInfo;       /* structure assignment */
+   dcr->VolCatInfo = saveVolCatInfo;  /* structure assignment */
+}
+
+boffset_t DEVICE::lseek(DCR *dcr, boffset_t offset, int whence)
+{
+   switch (dev_type) {
+   case B_DVD_DEV:
+      return lseek_dvd(dcr, offset, whence);
+   case B_FILE_DEV:
+#if defined(HAVE_WIN32)
+      return ::_lseeki64(fd, (__int64)offset, whence);
+#else
+      return ::lseek(fd, (off_t)offset, whence);
+#endif
+   }
+   return -1;
+}
 
 
 bool DEVICE::truncate(DCR *dcr) /* We need the DCR for DVD-writing */
 {
-   Dmsg1(100, "truncate_dev %s\n", print_name());
-   if (is_tape()) {
-      return true;                    /* we don't really truncate tapes */
+   Dmsg1(100, "truncate %s\n", print_name());
+   switch (dev_type) {
+   case B_TAPE_DEV:
       /* maybe we should rewind and write and eof ???? */
-   }
-   
-   if (is_dvd()) {
+      return true;                    /* we don't really truncate tapes */
+   case B_DVD_DEV:
       return truncate_dvd(dcr);
+   case B_FILE_DEV:
+      /* ***FIXME*** we really need to unlink() the file so that
+       *  its name can be changed for a relabel.
+       */
+      if (ftruncate(fd, 0) != 0) {
+         berrno be;
+         Mmsg2(errmsg, _("Unable to truncate device %s. ERR=%s\n"), 
+               print_name(), be.strerror());
+         return false;
+      }
+      return true;
    }
-   
-   if (ftruncate(fd, 0) != 0) {
-      berrno be;
-      Mmsg2(errmsg, _("Unable to truncate device %s. ERR=%s\n"), 
-            print_name(), be.strerror());
-      return false;
-   }
-   return true;
+   return false;
 }
 
 /* Mount the device.
@@ -1858,7 +1969,7 @@ bool DEVICE::mount(int timeout)
  */
 bool DEVICE::unmount(int timeout) 
 {
-   Dmsg0(90, "Enter unmount_dvd\n");
+   Dmsg0(90, "Enter unmount\n");
    if (is_mounted()) {
       return do_mount(0, timeout);
    }
@@ -1888,9 +1999,10 @@ bool DEVICE::do_mount(int mount, int dotimeout)
       icmd = device->unmount_command;
    }
    
+   clear_freespace_ok();
    edit_mount_codes(ocmd, icmd);
    
-   Dmsg2(000, "do_mount_dvd: cmd=%s mounted=%d\n", ocmd.c_str(), !!is_mounted());
+   Dmsg2(100, "do_mount: cmd=%s mounted=%d\n", ocmd.c_str(), !!is_mounted());
 
    if (dotimeout) {
       /* Try at most 1 time to (un)mount the device. This should perhaps be configurable. */
@@ -1898,13 +2010,18 @@ bool DEVICE::do_mount(int mount, int dotimeout)
    } else {
       timeout = 0;
    }
-   results = get_memory(2000);
+   results = get_memory(4000);
    results[0] = 0;
+
    /* If busy retry each second */
+   Dmsg1(20, "do_mount run_prog=%s\n", ocmd.c_str());
    while ((status = run_program_full_output(ocmd.c_str(), 
                        max_open_wait/2, results)) != 0) {
-      /* Doesn't work with internationalisation (This is not a problem) */
-      if (fnmatch("*is already mounted on", results, 0) == 0) {
+      /* Doesn't work with internationalization (This is not a problem) */
+      if (mount && fnmatch("*is already mounted on*", results, 0) == 0) {
+         break;
+      }
+      if (!mount && fnmatch("* not mounted*", results, 0) == 0) {
          break;
       }
       if (timeout-- > 0) {
@@ -1917,9 +2034,18 @@ bool DEVICE::do_mount(int mount, int dotimeout)
          bmicrosleep(1, 0);
          continue;
       }
-      Dmsg2(40, "Device %s cannot be mounted. ERR=%s\n", print_name(), results);
-      Mmsg(errmsg, _("Device %s cannot be mounted. ERR=%s\n"), 
-           print_name(), results);
+      if (status != 0) {
+         berrno be;
+         Dmsg5(40, "Device %s cannot be %smounted. stat=%d result=%s ERR=%s\n", print_name(),
+              (mount ? "" : "un"), status, results, be.strerror(status));
+         Mmsg(errmsg, _("Device %s cannot be %smounted. ERR=%s\n"), 
+              print_name(), (mount ? "" : "un"), be.strerror(status));
+      } else {
+         Dmsg4(40, "Device %s cannot be %smounted. stat=%d ERR=%s\n", print_name(),
+              (mount ? "" : "un"), status, results);
+         Mmsg(errmsg, _("Device %s cannot be %smounted. ERR=%s\n"), 
+              print_name(), (mount ? "" : "un"), results);
+      }
       /*
        * Now, just to be sure it is not mounted, try to read the
        *  filesystem.
@@ -1964,8 +2090,18 @@ bool DEVICE::do_mount(int mount, int dotimeout)
       Dmsg1(29, "do_mount: got %d files in the mount point (not counting ., .. and .keep)\n", count);
       
       if (count > 0) {
-         mount = 1;                      /* If we got more than ., .. and .keep */
-         break;                          /*   there must be something mounted */
+         /* If we got more than ., .. and .keep */
+         /*   there must be something mounted */
+         if (mount) {
+            Dmsg1(100, "Did Mount by count=%d\n", count);
+            break;
+         } else {
+            /* An unmount request. We failed to unmount - report an error */
+            set_mounted(true);
+            free_pool_memory(results);
+            Dmsg0(200, "== error mount=1 wanted unmount\n");
+            return false;
+         }
       }
 get_out:
       set_mounted(false);
@@ -1977,6 +2113,10 @@ get_out:
    
    set_mounted(mount);              /* set/clear mounted flag */
    free_pool_memory(results);
+   /* Do not check free space when unmounting */
+   if (mount && !update_freespace()) {
+      return false;
+   }
    Dmsg1(200, "============ mount=%d\n", mount);
    return true;
 }
@@ -2015,7 +2155,7 @@ void DEVICE::edit_mount_codes(POOL_MEM &omsg, const char *imsg)
             break;
          case 'e':
             if (num_dvd_parts == 0) {
-               if (truncating || truncated_dvd) {
+               if (truncating || blank_dvd) {
                   str = "2";
                } else {
                   str = "1";
@@ -2066,17 +2206,6 @@ dev_vol_name(DEVICE *dev)
    return dev->VolCatInfo.VolCatName;
 }
 
-uint32_t dev_block(DEVICE *dev)
-{
-   update_pos_dev(dev);
-   return dev->block_num;
-}
-
-uint32_t dev_file(DEVICE *dev)
-{
-   update_pos_dev(dev);
-   return dev->file;
-}
 
 /*
  * Free memory allocated for the device
@@ -2172,17 +2301,27 @@ bool double_dev_wait_time(DEVICE *dev)
 }
 
 
-void set_os_device_parameters(DEVICE *dev)
+void set_os_device_parameters(DCR *dcr)
 {
+   DEVICE *dev = dcr->dev;
+
 #if defined(HAVE_LINUX_OS) || defined(HAVE_WIN32)
    struct mtop mt_com;
+
+   Dmsg0(050, "In set_os_device_parameters\n");
+#if defined(MTSETBLK) 
    if (dev->min_block_size == dev->max_block_size &&
        dev->min_block_size == 0) {    /* variable block mode */
       mt_com.mt_op = MTSETBLK;
       mt_com.mt_count = 0;
+      Dmsg0(050, "Set block size to zero\n");
       if (tape_ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
          dev->clrerror(MTSETBLK);
       }
+   }
+#endif
+#if defined(MTSETDRVBUFFER)
+   if (getpid() == 0) {          /* Only root can do this */
       mt_com.mt_op = MTSETDRVBUFFER;
       mt_com.mt_count = MT_ST_CLEARBOOLEANS;
       if (!dev->has_cap(CAP_TWOEOF)) {
@@ -2191,10 +2330,12 @@ void set_os_device_parameters(DEVICE *dev)
       if (dev->has_cap(CAP_EOM)) {
          mt_com.mt_count |= MT_ST_FAST_MTEOM;
       }
+      Dmsg0(050, "MTSETDRVBUFFER\n");
       if (tape_ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
-         dev->clrerror(MTSETBLK);
+         dev->clrerror(MTSETDRVBUFFER);
       }
    }
+#endif
    return;
 #endif
 
@@ -2227,6 +2368,22 @@ void set_os_device_parameters(DEVICE *dev)
          dev->clrerror(MTSETBSIZ);
       }
    }
+/* Turn this on later when fully tested */
+#if defined(xxxMTIOCSETEOTMODEL) 
+   uint32_t neof;
+   if (dev_cap(dev, CAP_TWOEOF)) {
+      neof = 2;
+   } else {
+      neof = 1;
+   }
+   if (ioctl(dev->fd, MTIOCSETEOTMODEL, (caddr_t)&neof) < 0) {
+      berrno be;
+      dev->dev_errno = errno;         /* save errno */
+      Mmsg2(dev->errmsg, _("Unable to set eotmodel on device %s: ERR=%s\n"),
+            dev->print_name(), be.strerror(dev->dev_errno));
+      Jmsg(dcr->jcr, M_FATAL, 0, dev->errmsg);
+   }
+#endif
    return;
 #endif
 
@@ -2246,6 +2403,7 @@ void set_os_device_parameters(DEVICE *dev)
 
 static bool dev_get_os_pos(DEVICE *dev, struct mtget *mt_stat)
 {
+   Dmsg0(050, "dev_get_os_pos\n");
    return dev->has_cap(CAP_MTIOCGET) && 
           tape_ioctl(dev->fd, MTIOCGET, (char *)mt_stat) == 0 &&
           mt_stat->mt_fileno >= 0;