vol: Handle large volume IDs in VLockFile
[openafs.git] / src / vol / vutil.c
index 9434403..55e60a6 100644 (file)
@@ -1,7 +1,7 @@
 /*
  * Copyright 2000, International Business Machines Corporation and others.
  * All Rights Reserved.
- * 
+ *
  * This software has been released under the terms of the IBM Public
  * License.  For details, see the LICENSE file in the top-level source
  * directory or online at http://www.openafs.org/dl/license10.html
@@ -17,6 +17,7 @@
 #include <afsconfig.h>
 #include <afs/param.h>
 
+#include <roken.h>
 
 #include <stdio.h>
 #include <sys/types.h>
 #include <sys/file.h>
 #include <unistd.h>
 #endif
+#include <dirent.h>
 #include <sys/stat.h>
-#ifdef AFS_PTHREAD_ENV
-#include <assert.h>
-#else /* AFS_PTHREAD_ENV */
-#include <afs/assert.h>
-#endif /* AFS_PTHREAD_ENV */
+#include <afs/afs_assert.h>
 
 #include <rx/xdr.h>
 #include <afs/afsint.h>
 #endif
 #include "vnode.h"
 #include "volume.h"
+#include "volume_inline.h"
 #include "partition.h"
 #include "viceinode.h"
 
 #include "volinodes.h"
 #include "vol_prototypes.h"
+#include "common.h"
 
 #ifdef AFS_AIX_ENV
 #include <sys/lockf.h>
 #include <strings.h>
 #endif
 
-#ifdef O_LARGEFILE
-#define afs_open       open64
-#else /* !O_LARGEFILE */
-#define afs_open       open
-#endif /* !O_LARGEFILE */
-
-/*@printflike@*/ extern void Log(const char *format, ...);
-
-#define nFILES (sizeof (stuff)/sizeof(struct stuff))
+#ifndef AFS_NT40_ENV
+# ifdef O_LARGEFILE
+#  define AFS_SETLKW   F_SETLKW64
+#  define AFS_SETLK    F_SETLK64
+#  define afs_st_flock flock64
+# else
+#  define AFS_SETLKW   F_SETLKW
+#  define AFS_SETLK    F_SETLK
+#  define afs_st_flock flock
+# endif
+#endif
 
 /* Note:  the volume creation functions herein leave the destroyMe flag in the
    volume header ON:  this means that the volumes will not be attached by the
    file server and WILL BE DESTROYED the next time a system salvage is performed */
 
+#ifdef FSSYNC_BUILD_CLIENT
 static void
-RemoveInodes(Device dev, VolumeId vid)
+RemoveInodes(struct afs_inode_info *stuff, Device dev, VolumeId vid)
 {
-    register int i;
+    int i;
     IHandle_t *handle;
 
     /* This relies on the fact that IDEC only needs the device and NT only
      * needs the dev and vid to decrement volume special files.
      */
     IH_INIT(handle, dev, vid, -1);
-    for (i = 0; i < nFILES; i++) {
+    for (i = 0; i < MAXINODETYPE; i++) {
        Inode inode = *stuff[i].inode;
        if (VALID_INO(inode))
            IH_DEC(handle, inode, vid);
@@ -124,6 +127,14 @@ VCreateVolume_r(Error * ec, char *partname, VolId volumeId, VolId parentId)
     Inode nearInode = 0;
     char *part, *name;
     struct stat st;
+    struct VolumeHeader tempHeader;
+    struct afs_inode_info stuff[MAXINODETYPE];
+    afs_ino_str_t stmp;
+# ifdef AFS_DEMAND_ATTACH_FS
+    int locktype = 0;
+# endif /* AFS_DEMAND_ATTACH_FS */
+
+    init_inode_info(&tempHeader, stuff);
 
     *ec = 0;
     memset(&vol, 0, sizeof(vol));
@@ -158,7 +169,23 @@ VCreateVolume_r(Error * ec, char *partname, VolId volumeId, VolId parentId)
        }
     }
     *ec = 0;
+
+# ifdef AFS_DEMAND_ATTACH_FS
+    /* volume doesn't exist yet, but we must lock it to try to prevent something
+     * else from reading it when we're e.g. half way through creating it (or
+     * something tries to create the same volume at the same time) */
+    locktype = VVolLockType(V_VOLUPD, 1);
+    rc = VLockVolumeByIdNB(volumeId, partition, locktype);
+    if (rc) {
+       Log("VCreateVolume: vol %lu already locked by someone else\n",
+           afs_printable_uint32_lu(volumeId));
+       *ec = VNOVOL;
+       return NULL;
+    }
+# else /* AFS_DEMAND_ATTACH_FS */
     VLockPartition_r(partname);
+# endif /* !AFS_DEMAND_ATTACH_FS */
+
     memset(&tempHeader, 0, sizeof(tempHeader));
     tempHeader.stamp.magic = VOLUMEHEADERMAGIC;
     tempHeader.stamp.version = VOLUMEHEADERVERSION;
@@ -168,7 +195,7 @@ VCreateVolume_r(Error * ec, char *partname, VolId volumeId, VolId parentId)
     vol.stamp.version = VOLUMEINFOVERSION;
     vol.destroyMe = DESTROY_ME;
     (void)afs_snprintf(headerName, sizeof headerName, VFORMAT, afs_printable_uint32_lu(vol.id));
-    (void)afs_snprintf(volumePath, sizeof volumePath, "%s/%s",
+    (void)afs_snprintf(volumePath, sizeof volumePath, "%s" OS_DIRSEP "%s",
                       VPartitionPath(partition), headerName);
     rc = stat(volumePath, &st);
     if (rc == 0 || errno != ENOENT) {
@@ -181,12 +208,12 @@ VCreateVolume_r(Error * ec, char *partname, VolId volumeId, VolId parentId)
                errno, volumePath);
            *ec = VNOVOL;
        }
-       return NULL;
+       goto bad_noheader;
     }
     device = partition->device;
 
-    for (i = 0; i < nFILES; i++) {
-       register struct stuff *p = &stuff[i];
+    for (i = 0; i < MAXINODETYPE; i++) {
+       struct afs_inode_info *p = &stuff[i];
        if (p->obsolete)
            continue;
 #ifdef AFS_NAMEI_ENV
@@ -195,16 +222,12 @@ VCreateVolume_r(Error * ec, char *partname, VolId volumeId, VolId parentId)
                      (p->inodeType == VI_LINKTABLE) ? vol.parentId : vol.id,
                      INODESPECIAL, p->inodeType, vol.parentId);
        if (!(VALID_INO(*(p->inode)))) {
-           if (errno == EEXIST) {
+           if (errno == EEXIST && (p->inodeType == VI_LINKTABLE)) {
                /* Increment the reference count instead. */
                IHandle_t *lh;
                int code;
 
-#ifdef AFS_NT40_ENV
-               *(p->inode) = nt_MakeSpecIno(VI_LINKTABLE);
-#else
                *(p->inode) = namei_MakeSpecIno(vol.parentId, VI_LINKTABLE);
-#endif
                IH_INIT(lh, device, parentId, *(p->inode));
                fdP = IH_OPEN(lh);
                if (fdP == NULL) {
@@ -230,30 +253,30 @@ VCreateVolume_r(Error * ec, char *partname, VolId volumeId, VolId parentId)
          bad:
            if (handle)
                IH_RELEASE(handle);
-           RemoveInodes(device, vol.id);
+           RemoveInodes(stuff, device, vol.id);
            if (!*ec) {
                *ec = VNOVOL;
            }
            VDestroyVolumeDiskHeader(partition, volumeId, parentId);
+         bad_noheader:
+# ifdef AFS_DEMAND_ATTACH_FS
+           if (locktype) {
+               VUnlockVolumeById(volumeId, partition);
+           }
+# endif /* AFS_DEMAND_ATTACH_FS */
            return NULL;
        }
        IH_INIT(handle, device, vol.parentId, *(p->inode));
        fdP = IH_OPEN(handle);
        if (fdP == NULL) {
            Log("VCreateVolume:  Problem iopen inode %s (err=%d)\n",
-               PrintInode(NULL, *(p->inode)), errno);
+               PrintInode(stmp, *(p->inode)), errno);
            goto bad;
        }
-       if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
-           Log("VCreateVolume:  Problem lseek inode %s (err=%d)\n",
-               PrintInode(NULL, *(p->inode)), errno);
-           FDH_REALLYCLOSE(fdP);
-           goto bad;
-       }
-       if (FDH_WRITE(fdP, (char *)&p->stamp, sizeof(p->stamp)) !=
+       if (FDH_PWRITE(fdP, (char *)&p->stamp, sizeof(p->stamp), 0) !=
            sizeof(p->stamp)) {
-           Log("VCreateVolume:  Problem writing to  inode %s (err=%d)\n",
-               PrintInode(NULL, *(p->inode)), errno);
+           Log("VCreateVolume:  Problem writing to inode %s (err=%d)\n",
+               PrintInode(stmp, *(p->inode)), errno);
            FDH_REALLYCLOSE(fdP);
            goto bad;
        }
@@ -266,18 +289,12 @@ VCreateVolume_r(Error * ec, char *partname, VolId volumeId, VolId parentId)
     fdP = IH_OPEN(handle);
     if (fdP == NULL) {
        Log("VCreateVolume:  Problem iopen inode %s (err=%d)\n",
-           PrintInode(NULL, tempHeader.volumeInfo), errno);
+           PrintInode(stmp, tempHeader.volumeInfo), errno);
        goto bad;
     }
-    if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
-       Log("VCreateVolume:  Problem lseek inode %s (err=%d)\n",
-           PrintInode(NULL, tempHeader.volumeInfo), errno);
-       FDH_REALLYCLOSE(fdP);
-       goto bad;
-    }
-    if (FDH_WRITE(fdP, (char *)&vol, sizeof(vol)) != sizeof(vol)) {
+    if (FDH_PWRITE(fdP, (char *)&vol, sizeof(vol), 0) != sizeof(vol)) {
        Log("VCreateVolume:  Problem writing to  inode %s (err=%d)\n",
-           PrintInode(NULL, tempHeader.volumeInfo), errno);
+           PrintInode(stmp, tempHeader.volumeInfo), errno);
        FDH_REALLYCLOSE(fdP);
        goto bad;
     }
@@ -296,12 +313,18 @@ VCreateVolume_r(Error * ec, char *partname, VolId volumeId, VolId parentId)
        goto bad;
     }
 
+# ifdef AFS_DEMAND_ATTACH_FS
+    if (locktype) {
+       VUnlockVolumeById(volumeId, partition);
+    }
+# endif /* AFS_DEMAND_ATTACH_FS */
     return (VAttachVolumeByName_r(ec, partname, headerName, V_SECRETLY));
 }
+#endif /* FSSYNC_BUILD_CLIENT */
 
 
 void
-AssignVolumeName(register VolumeDiskData * vol, char *name, char *ext)
+AssignVolumeName(VolumeDiskData * vol, char *name, char *ext)
 {
     VOL_LOCK;
     AssignVolumeName_r(vol, name, ext);
@@ -309,9 +332,9 @@ AssignVolumeName(register VolumeDiskData * vol, char *name, char *ext)
 }
 
 void
-AssignVolumeName_r(register VolumeDiskData * vol, char *name, char *ext)
+AssignVolumeName_r(VolumeDiskData * vol, char *name, char *ext)
 {
-    register char *dot;
+    char *dot;
     strncpy(vol->name, name, VNAMESIZE - 1);
     vol->name[VNAMESIZE - 1] = '\0';
     dot = strrchr(vol->name, '.');
@@ -358,7 +381,7 @@ CopyVolumeHeader(VolumeDiskData * from, VolumeDiskData * to)
 }
 
 void
-ClearVolumeStats(register VolumeDiskData * vol)
+ClearVolumeStats(VolumeDiskData * vol)
 {
     VOL_LOCK;
     ClearVolumeStats_r(vol);
@@ -366,7 +389,7 @@ ClearVolumeStats(register VolumeDiskData * vol)
 }
 
 void
-ClearVolumeStats_r(register VolumeDiskData * vol)
+ClearVolumeStats_r(VolumeDiskData * vol)
 {
     memset(vol->weekUse, 0, sizeof(vol->weekUse));
     vol->dayUse = 0;
@@ -378,7 +401,10 @@ ClearVolumeStats_r(register VolumeDiskData * vol)
  *
  * @param[in]  volid  volume id
  * @param[in]  dp     disk partition object
- * @param[out] hdr    volume disk header
+ * @param[out] hdr    volume disk header or NULL
+ *
+ * @note if hdr is NULL, this is essentially an existence test for the vol
+ *       header
  *
  * @return operation status
  *    @retval 0 success
@@ -397,14 +423,15 @@ VReadVolumeDiskHeader(VolumeId volid,
     char path[MAXPATHLEN];
 
     (void)afs_snprintf(path, sizeof(path),
-                      "%s/" VFORMAT,
+                      "%s" OS_DIRSEP VFORMAT,
                       VPartitionPath(dp), afs_printable_uint32_lu(volid));
     fd = open(path, O_RDONLY);
     if (fd < 0) {
-       Log("VReadVolumeDiskHeader: Couldn't open header for volume %lu.\n",
-           afs_printable_uint32_lu(volid));
+       Log("VReadVolumeDiskHeader: Couldn't open header for volume %lu (errno %d).\n",
+           afs_printable_uint32_lu(volid), errno);
        code = -1;
-    } else if (read(fd, hdr, sizeof(*hdr)) != sizeof(*hdr)) {
+
+    } else if (hdr && read(fd, hdr, sizeof(*hdr)) != sizeof(*hdr)) {
        Log("VReadVolumeDiskHeader: Couldn't read header for volume %lu.\n",
            afs_printable_uint32_lu(volid));
        code = EIO;
@@ -416,6 +443,7 @@ VReadVolumeDiskHeader(VolumeId volid,
     return code;
 }
 
+#ifdef FSSYNC_BUILD_CLIENT
 /**
  * write an existing volume disk header.
  *
@@ -439,10 +467,19 @@ _VWriteVolumeDiskHeader(VolumeDiskHeader_t * hdr,
     int fd;
     char path[MAXPATHLEN];
 
+#ifdef AFS_DEMAND_ATTACH_FS
+    /* prevent racing with VGC scanners reading the vol header while we are
+     * writing it */
+    code = VPartHeaderLock(dp, READ_LOCK);
+    if (code) {
+       return EIO;
+    }
+#endif /* AFS_DEMAND_ATTACH_FS */
+
     flags |= O_RDWR;
 
     (void)afs_snprintf(path, sizeof(path),
-                      "%s/" VFORMAT,
+                      "%s" OS_DIRSEP VFORMAT,
                       VPartitionPath(dp), afs_printable_uint32_lu(hdr->id));
     fd = open(path, flags, 0644);
     if (fd < 0) {
@@ -462,6 +499,10 @@ _VWriteVolumeDiskHeader(VolumeDiskHeader_t * hdr,
        }
     }
 
+#ifdef AFS_DEMAND_ATTACH_FS
+    VPartHeaderUnlock(dp, READ_LOCK);
+#endif /* AFS_DEMAND_ATTACH_FS */
+
     return code;
 }
 
@@ -482,11 +523,66 @@ VWriteVolumeDiskHeader(VolumeDiskHeader_t * hdr,
 {
     afs_int32 code;
 
+#ifdef AFS_DEMAND_ATTACH_FS
+    VolumeDiskHeader_t oldhdr;
+    int delvgc = 0, addvgc = 0;
+    SYNC_response res;
+
+    /* first, see if anything with the volume IDs have changed; if so, we
+     * need to update the VGC */
+
+    code = VReadVolumeDiskHeader(hdr->id, dp, &oldhdr);
+    if (code == 0 && (oldhdr.id != hdr->id || oldhdr.parent != hdr->parent)) {
+       /* the vol id or parent vol id changed; need to delete the VGC entry
+        * for the old vol id/parent, and add the new one */
+       delvgc = 1;
+       addvgc = 1;
+
+    } else if (code) {
+       /* couldn't get the old header info; add the new header info to the
+        * VGC in case it hasn't been added yet */
+       addvgc = 1;
+    }
+
+#endif /* AFS_DEMAND_ATTACH_FS */
+
     code = _VWriteVolumeDiskHeader(hdr, dp, 0);
     if (code) {
        goto done;
     }
 
+#ifdef AFS_DEMAND_ATTACH_FS
+    if (delvgc) {
+       memset(&res, 0, sizeof(res));
+       code = FSYNC_VGCDel(dp->name, oldhdr.parent, oldhdr.id, FSYNC_WHATEVER, &res);
+
+       /* unknown vol id is okay; it just further suggests the old header
+        * data was bogus, which is fine since we're trying to fix it */
+       if (code && res.hdr.reason != FSYNC_UNKNOWN_VOLID) {
+           Log("VWriteVolumeDiskHeader: FSYNC_VGCDel(%s, %lu, %lu) "
+               "failed with code %ld reason %ld\n", dp->name,
+               afs_printable_uint32_lu(oldhdr.parent),
+               afs_printable_uint32_lu(oldhdr.id),
+               afs_printable_int32_ld(code),
+               afs_printable_int32_ld(res.hdr.reason));
+       }
+
+    }
+    if (addvgc) {
+       memset(&res, 0, sizeof(res));
+       code = FSYNC_VGCAdd(dp->name, hdr->parent, hdr->id, FSYNC_WHATEVER, &res);
+       if (code) {
+           Log("VWriteVolumeDiskHeader: FSYNC_VGCAdd(%s, %lu, %lu) "
+               "failed with code %ld reason %ld\n", dp->name,
+               afs_printable_uint32_lu(hdr->parent),
+               afs_printable_uint32_lu(hdr->id),
+               afs_printable_int32_ld(code),
+               afs_printable_int32_ld(res.hdr.reason));
+       }
+    }
+
+#endif /* AFS_DEMAND_ATTACH_FS */
+
  done:
     return code;
 }
@@ -509,12 +605,28 @@ VCreateVolumeDiskHeader(VolumeDiskHeader_t * hdr,
                        struct DiskPartition64 * dp)
 {
     afs_int32 code = 0;
+#ifdef AFS_DEMAND_ATTACH_FS
+    SYNC_response res;
+#endif /* AFS_DEMAND_ATTACH_FS */
 
     code = _VWriteVolumeDiskHeader(hdr, dp, O_CREAT | O_EXCL);
     if (code) {
        goto done;
     }
 
+#ifdef AFS_DEMAND_ATTACH_FS
+    memset(&res, 0, sizeof(res));
+    code = FSYNC_VGCAdd(dp->name, hdr->parent, hdr->id, FSYNC_WHATEVER, &res);
+    if (code) {
+       Log("VCreateVolumeDiskHeader: FSYNC_VGCAdd(%s, %lu, %lu) failed "
+           "with code %ld reason %ld\n", dp->name,
+           afs_printable_uint32_lu(hdr->parent),
+           afs_printable_uint32_lu(hdr->id),
+           afs_printable_int32_ld(code),
+           afs_printable_int32_ld(res.hdr.reason));
+    }
+#endif /* AFS_DEMAND_ATTACH_FS */
+
  done:
     return code;
 }
@@ -542,9 +654,12 @@ VDestroyVolumeDiskHeader(struct DiskPartition64 * dp,
 {
     afs_int32 code = 0;
     char path[MAXPATHLEN];
+#ifdef AFS_DEMAND_ATTACH_FS
+    SYNC_response res;
+#endif /* AFS_DEMAND_ATTACH_FS */
 
     (void)afs_snprintf(path, sizeof(path),
-                       "%s/" VFORMAT,
+                       "%s" OS_DIRSEP VFORMAT,
                        VPartitionPath(dp), afs_printable_uint32_lu(volid));
     code = unlink(path);
     if (code) {
@@ -552,11 +667,199 @@ VDestroyVolumeDiskHeader(struct DiskPartition64 * dp,
        goto done;
     }
 
+#ifdef AFS_DEMAND_ATTACH_FS
+    memset(&res, 0, sizeof(res));
+    if (!parent) {
+       FSSYNC_VGQry_response_t q_res;
+
+       code = FSYNC_VGCQuery(dp->name, volid, &q_res, &res);
+       if (code) {
+           Log("VDestroyVolumeDiskHeader: FSYNC_VGCQuery(%s, %lu) failed "
+               "with code %ld, reason %ld\n", dp->name,
+               afs_printable_uint32_lu(volid), afs_printable_int32_ld(code),
+               afs_printable_int32_ld(res.hdr.reason));
+           goto done;
+       }
+
+       parent = q_res.rw;
+
+    }
+    code = FSYNC_VGCDel(dp->name, parent, volid, FSYNC_WHATEVER, &res);
+    if (code) {
+       Log("VDestroyVolumeDiskHeader: FSYNC_VGCDel(%s, %lu, %lu) failed "
+           "with code %ld reason %ld\n", dp->name,
+           afs_printable_uint32_lu(parent),
+           afs_printable_uint32_lu(volid),
+           afs_printable_int32_ld(code),
+           afs_printable_int32_ld(res.hdr.reason));
+    }
+#endif /* AFS_DEMAND_ATTACH_FS */
+
  done:
     return code;
 }
+#endif /* FSSYNC_BUILD_CLIENT */
+
+/**
+ * handle a single vol header as part of VWalkVolumeHeaders.
+ *
+ * @param[in] dp      disk partition
+ * @param[in] volfunc function to call when a vol header is successfully read
+ * @param[in] name    full path name to the .vol header
+ * @param[out] hdr    header data read in from the .vol header
+ * @param[in] locked  1 if the partition headers are locked, 0 otherwise
+ * @param[in] rock    the rock to pass to volfunc
+ *
+ * @return operation status
+ *  @retval 0  success
+ *  @retval -1 fatal error, stop scanning
+ *  @retval 1  failed to read header
+ *  @retval 2  volfunc callback indicated error after header read
+ */
+static int
+_VHandleVolumeHeader(struct DiskPartition64 *dp, VWalkVolFunc volfunc,
+                     const char *name, struct VolumeDiskHeader *hdr,
+                     int locked, void *rock)
+{
+    int error = 0;
+    FD_t fd;
+
+    if ((fd = OS_OPEN(name, O_RDONLY, 0)) == INVALID_FD
+        || OS_READ(fd, hdr, sizeof(*hdr))
+        != sizeof(*hdr)
+        || hdr->stamp.magic != VOLUMEHEADERMAGIC) {
+        error = 1;
+    }
+
+    if (fd != INVALID_FD) {
+       OS_CLOSE(fd);
+    }
+
+#ifdef AFSFS_DEMAND_ATTACH_FS
+    if (locked) {
+       VPartHeaderUnlock(dp);
+    }
+#endif /* AFS_DEMAND_ATTACH_FS */
+
+    if (!error && volfunc) {
+       /* the volume header seems fine; call the caller-supplied
+        * 'we-found-a-volume-header' function */
+       int last = 1;
+
+#ifdef AFS_DEMAND_ATTACH_FS
+       if (!locked) {
+           last = 0;
+       }
+#endif /* AFS_DEMAND_ATTACH_FS */
+
+       error = (*volfunc) (dp, name, hdr, last, rock);
+       if (error < 0) {
+           return -1;
+       }
+       if (error) {
+           error = 2;
+       }
+    }
 
 #ifdef AFS_DEMAND_ATTACH_FS
+    if (error && !locked) {
+       int code;
+       /* retry reading the volume header under the partition
+        * header lock, just to be safe and ensure we're not
+        * racing something rewriting the vol header */
+       code = VPartHeaderLock(dp, WRITE_LOCK);
+       if (code) {
+           Log("Error acquiring partition write lock when "
+               "looking at header %s\n", name);
+           return -1;
+       }
+
+       return _VHandleVolumeHeader(dp, volfunc, name, hdr, 1, rock);
+    }
+#endif /* AFS_DEMAND_ATTACH_FS */
+
+    return error;
+}
+
+/**
+ * walk through the list of volume headers on a partition.
+ *
+ * This function looks through all of the .vol headers on a partition, reads in
+ * each header, and calls the supplied volfunc function on each one. If the
+ * header cannot be read (or volfunc returns a positive error code), DAFS will
+ * VPartHeaderExLock() and retry. If that fails, or if we are non-DAFS, errfunc
+ * will be called (which typically will unlink the problem volume header).
+ *
+ * If volfunc returns a negative error code, walking the partition will stop
+ * and we will return an error immediately.
+ *
+ * @param[in] dp       partition to walk
+ * @param[in] partpath the path opendir()
+ * @param[in] volfunc  the function to call when a header is encountered, or
+ *                     NULL to just skip over valid headers
+ * @param[in] errfunc  the function to call when a problematic header is
+ *                     encountered, or NULL to just skip over bad headers
+ * @param[in] rock     rock for volfunc and errfunc
+ *
+ * @see VWalkVolFunc
+ * @see VWalkErrFunc
+ *
+ * @return operation status
+ *  @retval 0 success
+ *  @retval negative fatal error, walk did not finish
+ */
+int
+VWalkVolumeHeaders(struct DiskPartition64 *dp, const char *partpath,
+                   VWalkVolFunc volfunc, VWalkErrFunc errfunc, void *rock)
+{
+    DIR *dirp = NULL;
+    struct dirent *dentry = NULL;
+    int code = 0;
+    struct VolumeDiskHeader diskHeader;
+
+    dirp = opendir(partpath);
+    if (!dirp) {
+       Log("VWalkVolumeHeaders: cannot open directory %s\n", partpath);
+       code = -1;
+       goto done;
+    }
+
+    while ((dentry = readdir(dirp))) {
+       char *p = dentry->d_name;
+       p = strrchr(dentry->d_name, '.');
+       if (p != NULL && strcmp(p, VHDREXT) == 0) {
+           char name[VMAXPATHLEN];
+
+           sprintf(name, "%s" OS_DIRSEP "%s", partpath, dentry->d_name);
+
+           code = _VHandleVolumeHeader(dp, volfunc, name, &diskHeader, -1, rock);
+           if (code < 0) {
+               /* fatal error, stop walking */
+               goto done;
+           }
+           if (code && errfunc) {
+               /* error with header; call the caller-supplied vol error
+                * function */
+
+               struct VolumeDiskHeader *hdr = &diskHeader;
+               if (code == 1) {
+                   /* we failed to read the header at all, so don't pass in
+                    * the header ptr */
+                   hdr = NULL;
+               }
+               (*errfunc) (dp, name, hdr, rock);
+           }
+           code = 0;
+       }
+    }
+ done:
+    if (dirp) {
+       closedir(dirp);
+       dirp = NULL;
+    }
+
+    return code;
+}
 
 /**
  * initialize a struct VLockFile.
@@ -569,11 +872,12 @@ void
 VLockFileInit(struct VLockFile *lf, const char *path)
 {
     memset(lf, 0, sizeof(*lf));
-    assert(pthread_mutex_init(&lf->mutex, NULL) == 0);
     lf->path = strdup(path);
+    lf->fd = INVALID_FD;
+    MUTEX_INIT(&lf->mutex, "vlockfile", MUTEX_DEFAULT, 0);
 }
 
-# ifdef AFS_NT40_ENV
+#ifdef AFS_NT40_ENV
 static_inline FD_t
 _VOpenPath(const char *path)
 {
@@ -611,10 +915,8 @@ _VLockFd(FD_t handle, afs_uint32 offset, int locktype, int nonblock)
 
     if (!LockFileEx(handle, flags, 0, 1, 0, &lap)) {
        if (GetLastError() == ERROR_LOCK_VIOLATION) {
-           CloseHandle(handle);
            return EBUSY;
        }
-       CloseHandle(handle);
        return EIO;
     }
 
@@ -622,23 +924,23 @@ _VLockFd(FD_t handle, afs_uint32 offset, int locktype, int nonblock)
 }
 
 static_inline void
-_VUnlockFd(struct VLockFile *lf, afs_uint32 offset)
+_VUnlockFd(FD_t handle, afs_uint32 offset)
 {
     OVERLAPPED lap;
 
     memset(&lap, 0, sizeof(lap));
     lap.Offset = offset;
 
-    UnlockFileEx(lf->fd, 0, 1, 0, &lap);
+    UnlockFileEx(handle, 0, 1, 0, &lap);
 }
 
 static_inline void
-_VCloseFd(struct VLockFile *lf)
+_VCloseFd(FD_t handle)
 {
-    CloseHandle(lf->fd);
+    CloseHandle(handle);
 }
 
-# else /* !AFS_NT40_ENV */
+#else /* !AFS_NT40_ENV */
 
 /**
  * open a file on the local filesystem suitable for locking
@@ -648,7 +950,7 @@ _VCloseFd(struct VLockFile *lf)
  * @return file descriptor
  *  @retval INVALID_FD failure opening file
  */
-static_inline int
+static_inline FD_t
 _VOpenPath(const char *path)
 {
     int fd;
@@ -675,17 +977,17 @@ _VOpenPath(const char *path)
  *  @retval EIO   error acquiring file lock
  */
 static_inline int
-_VLockFd(int fd, afs_uint32 offset, int locktype, int nonblock)
+_VLockFd(FD_t fd, afs_uint32 offset, int locktype, int nonblock)
 {
     int l_type = F_WRLCK;
-    int cmd = F_SETLKW;
-    struct flock sf;
+    int cmd = AFS_SETLKW;
+    struct afs_st_flock sf;
 
     if (locktype == READ_LOCK) {
        l_type = F_RDLCK;
     }
     if (nonblock) {
-       cmd = F_SETLK;
+       cmd = AFS_SETLK;
     }
 
     sf.l_start = offset;
@@ -696,12 +998,23 @@ _VLockFd(int fd, afs_uint32 offset, int locktype, int nonblock)
     if (fcntl(fd, cmd, &sf)) {
        if (nonblock && (errno == EACCES || errno == EAGAIN)) {
            /* We asked for a nonblocking lock, and it was already locked */
-           close(fd);
+           sf.l_pid = 0;
+           if (fcntl(fd, F_GETLK, &sf) != 0 || sf.l_pid == 0) {
+               Log("_VLockFd: fcntl failed with error %d when trying to "
+                   "query the conflicting lock for fd %d (locktype=%d, "
+                   "offset=%lu)\n", errno, fd, locktype,
+                   afs_printable_uint32_lu(offset));
+           } else {
+               Log("_VLockFd: conflicting lock held on fd %d, offset %lu by "
+                   "pid %ld (locktype=%d)\n", fd,
+                   afs_printable_uint32_lu(offset), (long int)sf.l_pid,
+                   locktype);
+           }
            return EBUSY;
        }
        Log("_VLockFd: fcntl failed with error %d when trying to lock "
-           "fd %d (locktype=%d)\n", errno, fd, locktype);
-       close(fd);
+           "fd %d (locktype=%d, offset=%lu)\n", errno, fd, locktype,
+           afs_printable_uint32_lu(offset));
        return EIO;
     }
 
@@ -714,7 +1027,7 @@ _VLockFd(int fd, afs_uint32 offset, int locktype, int nonblock)
  * @param[in] fd file descriptor to close
  */
 static_inline void
-_VCloseFd(int fd)
+_VCloseFd(FD_t fd)
 {
     if (close(fd)) {
        Log("_VCloseFd: error %d closing fd %d\n",
@@ -729,21 +1042,50 @@ _VCloseFd(int fd)
  * @param[in] offset offset to unlock
  */
 static_inline void
-_VUnlockFd(int fd, afs_uint32 offset)
+_VUnlockFd(FD_t fd, afs_uint32 offset)
 {
-    struct flock sf;
+    struct afs_st_flock sf;
 
     sf.l_start = offset;
     sf.l_len = 1;
     sf.l_type = F_UNLCK;
     sf.l_whence = SEEK_SET;
 
-    if (fcntl(fd, F_SETLK, &sf)) {
+    if (fcntl(fd, AFS_SETLK, &sf)) {
        Log("_VUnlockFd: fcntl failed with error %d when trying to unlock "
            "fd %d\n", errno, fd);
     }
 }
-# endif /* !AFS_NT40_ENV */
+#endif /* !AFS_NT40_ENV */
+
+/**
+ * reinitialize a struct VLockFile.
+ *
+ * Use this to close the lock file (unlocking any locks in it), and effectively
+ * restore lf to the state it was in when it was initialized. This is the same
+ * as unlocking all of the locks on the file, without having to remember what
+ * all of the locks were. Do not unlock previously held locks after calling
+ * this.
+ *
+ * @param[in] lf  struct VLockFile to reinit
+ *
+ * @pre nobody is waiting for a lock on this lockfile or otherwise using
+ *      this lockfile at all
+ */
+void
+VLockFileReinit(struct VLockFile *lf)
+{
+    MUTEX_ENTER(&lf->mutex);
+
+    if (lf->fd != INVALID_FD) {
+       _VCloseFd(lf->fd);
+       lf->fd = INVALID_FD;
+    }
+
+    lf->refcount = 0;
+
+    MUTEX_EXIT(&lf->mutex);
+}
 
 /**
  * lock a file on disk for the process.
@@ -772,29 +1114,31 @@ VLockFileLock(struct VLockFile *lf, afs_uint32 offset, int locktype, int nonbloc
 {
     int code;
 
-    assert(pthread_mutex_lock(&lf->mutex) == 0);
+    osi_Assert(locktype == READ_LOCK || locktype == WRITE_LOCK);
+
+    MUTEX_ENTER(&lf->mutex);
 
     if (lf->fd == INVALID_FD) {
        lf->fd = _VOpenPath(lf->path);
        if (lf->fd == INVALID_FD) {
-           assert(pthread_mutex_unlock(&lf->mutex) == 0);
+           MUTEX_EXIT(&lf->mutex);
            return EIO;
        }
     }
 
     lf->refcount++;
 
-    assert(pthread_mutex_unlock(&lf->mutex) == 0);
+    MUTEX_EXIT(&lf->mutex);
 
     code = _VLockFd(lf->fd, offset, locktype, nonblock);
 
     if (code) {
-       assert(pthread_mutex_lock(&lf->mutex) == 0);
+       MUTEX_ENTER(&lf->mutex);
        if (--lf->refcount < 1) {
            _VCloseFd(lf->fd);
            lf->fd = INVALID_FD;
        }
-       assert(pthread_mutex_unlock(&lf->mutex) == 0);
+       MUTEX_EXIT(&lf->mutex);
     }
 
     return code;
@@ -803,7 +1147,9 @@ VLockFileLock(struct VLockFile *lf, afs_uint32 offset, int locktype, int nonbloc
 void
 VLockFileUnlock(struct VLockFile *lf, afs_uint32 offset)
 {
-    assert(pthread_mutex_lock(&lf->mutex) == 0);
+    MUTEX_ENTER(&lf->mutex);
+
+    osi_Assert(lf->fd != INVALID_FD);
 
     if (--lf->refcount < 1) {
        _VCloseFd(lf->fd);
@@ -812,9 +1158,11 @@ VLockFileUnlock(struct VLockFile *lf, afs_uint32 offset)
        _VUnlockFd(lf->fd, offset);
     }
 
-    assert(pthread_mutex_lock(&lf->mutex) == 0);
+    MUTEX_EXIT(&lf->mutex);
 }
 
+#ifdef AFS_DEMAND_ATTACH_FS
+
 /**
  * initialize a struct VDiskLock.
  *
@@ -824,11 +1172,11 @@ VLockFileUnlock(struct VLockFile *lf, afs_uint32 offset)
 void
 VDiskLockInit(struct VDiskLock *dl, struct VLockFile *lf, afs_uint32 offset)
 {
-    assert(lf);
+    osi_Assert(lf);
     memset(dl, 0, sizeof(*dl));
     Lock_Init(&dl->rwlock);
-    assert(pthread_mutex_init(&dl->mutex, NULL) == 0);
-    assert(pthread_cond_init(&dl->cv, NULL) == 0);
+    MUTEX_INIT(&dl->mutex, "disklock", MUTEX_DEFAULT, 0);
+    CV_INIT(&dl->cv, "disklock cv", CV_DEFAULT, 0);
     dl->lockfile = lf;
     dl->offset = offset;
 }
@@ -859,7 +1207,7 @@ int
 VGetDiskLock(struct VDiskLock *dl, int locktype, int nonblock)
 {
     int code = 0;
-    assert(locktype == READ_LOCK || locktype == WRITE_LOCK);
+    osi_Assert(locktype == READ_LOCK || locktype == WRITE_LOCK);
 
     if (nonblock) {
        if (locktype == READ_LOCK) {
@@ -878,7 +1226,7 @@ VGetDiskLock(struct VDiskLock *dl, int locktype, int nonblock)
        ObtainWriteLock(&dl->rwlock);
     }
 
-    assert(pthread_mutex_lock(&dl->mutex) == 0);
+    MUTEX_ENTER(&dl->mutex);
 
     if ((dl->flags & VDISKLOCK_ACQUIRING)) {
        /* Some other thread is waiting to acquire an fs lock. If nonblock=1,
@@ -889,7 +1237,7 @@ VGetDiskLock(struct VDiskLock *dl, int locktype, int nonblock)
            code = EBUSY;
        } else {
            while ((dl->flags & VDISKLOCK_ACQUIRING)) {
-               assert(pthread_cond_wait(&dl->cv, &dl->mutex) == 0);
+               CV_WAIT(&dl->cv, &dl->mutex);
            }
        }
     }
@@ -906,9 +1254,9 @@ VGetDiskLock(struct VDiskLock *dl, int locktype, int nonblock)
            /* mark that we are waiting on the fs lock */
            dl->flags |= VDISKLOCK_ACQUIRING;
 
-           assert(pthread_mutex_unlock(&dl->mutex) == 0);
+           MUTEX_EXIT(&dl->mutex);
            code = VLockFileLock(dl->lockfile, dl->offset, locktype, nonblock);
-           assert(pthread_mutex_lock(&dl->mutex) == 0);
+           MUTEX_ENTER(&dl->mutex);
 
            dl->flags &= ~VDISKLOCK_ACQUIRING;
 
@@ -916,7 +1264,7 @@ VGetDiskLock(struct VDiskLock *dl, int locktype, int nonblock)
                dl->flags |= VDISKLOCK_ACQUIRED;
            }
 
-           assert(pthread_cond_broadcast(&dl->cv) == 0);
+           CV_BROADCAST(&dl->cv);
        }
     }
 
@@ -932,7 +1280,7 @@ VGetDiskLock(struct VDiskLock *dl, int locktype, int nonblock)
        ++dl->lockers;
     }
 
-    assert(pthread_mutex_unlock(&dl->mutex) == 0);
+    MUTEX_EXIT(&dl->mutex);
 
     return code;
 }
@@ -950,10 +1298,10 @@ VGetDiskLock(struct VDiskLock *dl, int locktype, int nonblock)
 void
 VReleaseDiskLock(struct VDiskLock *dl, int locktype)
 {
-    assert(locktype == READ_LOCK || locktype == WRITE_LOCK);
+    osi_Assert(locktype == READ_LOCK || locktype == WRITE_LOCK);
 
-    assert(pthread_mutex_lock(&dl->mutex) == 0);
-    assert(dl->lockers > 0);
+    MUTEX_ENTER(&dl->mutex);
+    osi_Assert(dl->lockers > 0);
 
     if (--dl->lockers < 1) {
        /* no threads are holding this lock anymore, so we can release the
@@ -962,7 +1310,7 @@ VReleaseDiskLock(struct VDiskLock *dl, int locktype)
        dl->flags &= ~VDISKLOCK_ACQUIRED;
     }
 
-    assert(pthread_mutex_unlock(&dl->mutex) == 0);
+    MUTEX_EXIT(&dl->mutex);
 
     if (locktype == READ_LOCK) {
        ReleaseReadLock(&dl->rwlock);