vol-salvage: calloc volume summary structs
[openafs.git] / src / vol / vol-salvage.c
index ee9b8f1..d78a6ba 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
@@ -71,7 +71,7 @@ Vnodes with 0 inode pointers in RW volumes are now deleted.
        Logs missing inode numbers.
 
     2.3 features:
-           Increments directory version number by 200 (rather than by 1) when it is salvaged, in order to prevent problems due to the fact that a version number can be promised to a workstation before it is written to disk.  If the server crashes, it may have an older version.  Salvaging it could bring the version number up to the same version the workstation believed it already had a call back on. 
+           Increments directory version number by 200 (rather than by 1) when it is salvaged, in order to prevent problems due to the fact that a version number can be promised to a workstation before it is written to disk.  If the server crashes, it may have an older version.  Salvaging it could bring the version number up to the same version the workstation believed it already had a call back on.
 
     2.4 features:
            Locks the file /vice/vol/salvage.lock before starting.  Aborts if it can't acquire the lock.
@@ -86,8 +86,8 @@ Vnodes with 0 inode pointers in RW volumes are now deleted.
 #include <afsconfig.h>
 #include <afs/param.h>
 
-RCSID
-    ("$Header$");
+#include <afs/procmgmt.h>
+#include <roken.h>
 
 #ifndef AFS_NT40_ENV
 #include <sys/param.h>
@@ -107,12 +107,12 @@ RCSID
 #include <io.h>
 #include <WINNT/afsevent.h>
 #endif
-#if    defined(AFS_AIX_ENV) || defined(AFS_SUN4_ENV)
-#define WCOREDUMP(x)   (x & 0200)
+#ifndef WCOREDUMP
+#define WCOREDUMP(x)   ((x) & 0200)
 #endif
 #include <rx/xdr.h>
 #include <afs/afsint.h>
-#include <afs/assert.h>
+#include <afs/afs_assert.h>
 #if !defined(AFS_SGI_ENV) && !defined(AFS_NT40_ENV)
 #if defined(AFS_VFSINCL_ENV)
 #include <sys/vnode.h>
@@ -130,7 +130,7 @@ RCSID
 #ifdef AFS_OSF_ENV
 #include <ufs/inode.h>
 #else /* AFS_OSF_ENV */
-#if !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV)
+#if !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV) && !defined(AFS_ARM_DARWIN_ENV)
 #include <sys/inode.h>
 #endif
 #endif
@@ -167,6 +167,7 @@ RCSID
 #include <afs/osi_inode.h>
 #endif
 #include <afs/cmd.h>
+#include <afs/dir.h>
 #include <afs/afsutil.h>
 #include <afs/fileutil.h>
 #include <afs/procmgmt.h>      /* signal(), kill(), wait(), etc. */
@@ -184,11 +185,21 @@ RCSID
 #include "partition.h"
 #include "daemon_com.h"
 #include "fssync.h"
+#include "volume_inline.h"
 #include "salvsync.h"
 #include "viceinode.h"
 #include "salvage.h"
 #include "volinodes.h"         /* header magic number, etc. stuff */
 #include "vol-salvage.h"
+#include "common.h"
+#include "vol_internal.h"
+#include <afs/acl.h>
+#include <afs/prs_fs.h>
+
+#ifdef FSSYNC_BUILD_CLIENT
+#include "vg_cache.h"
+#endif
+
 #ifdef AFS_NT40_ENV
 #include <pthread.h>
 #endif
@@ -257,49 +268,62 @@ FILE *logFile = 0;        /* one of {/usr/afs/logs,/vice/file}/SalvageLog */
 
 #define ROOTINODE      2       /* Root inode of a 4.2 Unix file system
                                 * partition */
-Device fileSysDevice;          /* The device number of the current
-                                * partition being salvaged */
-#ifdef AFS_NT40_ENV
-char fileSysPath[8];
-#else
-char *fileSysPath;             /* The path of the mounted partition currently
-                                * being salvaged, i.e. the directory
-                                * containing the volume headers */
-#endif
-char *fileSysPathName;         /* NT needs this to make name pretty in log. */
-IHandle_t *VGLinkH;            /* Link handle for current volume group. */
-int VGLinkH_cnt;               /* # of references to lnk handle. */
-struct DiskPartition64 *fileSysPartition;      /* Partition  being salvaged */
+/**
+ * information that is 'global' to a particular salvage job.
+ */
+struct SalvInfo {
+    Device fileSysDevice;    /**< The device number of the current partition
+                             *   being salvaged */
+    char fileSysPath[8];     /**< The path of the mounted partition currently
+                              *   being salvaged, i.e. the directory containing
+                              *   the volume headers */
+    char *fileSysPathName;   /**< NT needs this to make name pretty log. */
+    IHandle_t *VGLinkH;      /**< Link handle for current volume group. */
+    int VGLinkH_cnt;         /**< # of references to lnk handle. */
+    struct DiskPartition64 *fileSysPartition; /**< Partition being salvaged */
+
 #ifndef AFS_NT40_ENV
-char *fileSysDeviceName;       /* The block device where the file system
-                                * being salvaged was mounted */
-char *filesysfulldev;
+    char *fileSysDeviceName; /**< The block device where the file system being
+                              *   salvaged was mounted */
+    char *filesysfulldev;
 #endif
-int VolumeChanged;             /* Set by any routine which would change the volume in
-                                * a way which would require callback is to be broken if the
-                                * volume was put back on line by an active file server */
-
-VolumeDiskData VolInfo;                /* A copy of the last good or salvaged volume header dealt with */
-
-int nVolumesInInodeFile;       /* Number of read-write volumes summarized */
-int inodeFd;                   /* File descriptor for inode file */
-
-
-struct VnodeInfo vnodeInfo[nVNODECLASSES];
-
-
-struct VolumeSummary *volumeSummaryp;  /* Holds all the volumes in a part */
-int nVolumes;                  /* Number of volumes (read-write and read-only)
-                                * in volume summary */
+    int VolumeChanged;       /**< Set by any routine which would change the
+                              *   volume in a way which would require callbacks
+                              *   to be broken if the volume was put back on
+                              *   on line by an active file server */
+
+    VolumeDiskData VolInfo;  /**< A copy of the last good or salvaged volume
+                              *   header dealt with */
+
+    int nVolumesInInodeFile; /**< Number of read-write volumes summarized */
+    int inodeFd;             /**< File descriptor for inode file */
+
+    struct VolumeSummary *volumeSummaryp; /**< Holds all the volumes in a part */
+    int nVolumes;            /**< Number of volumes (read-write and read-only)
+                              *   in volume summary */
+    struct InodeSummary *inodeSummary; /**< contains info on all the relevant
+                                        *   inodes */
+
+    struct VnodeInfo vnodeInfo[nVNODECLASSES]; /**< contains info on all of the
+                                                *   vnodes in the volume that
+                                                *   we are currently looking
+                                                *   at */
+    int useFSYNC; /**< 0 if the fileserver is unavailable; 1 if we should try
+                   *   to contact the fileserver over FSYNC */
+};
 
 char *tmpdir = NULL;
 
 
 
 /* Forward declarations */
-/*@printflike@*/ void Log(const char *format, ...);
-/*@printflike@*/ void Abort(const char *format, ...);
-static int IsVnodeOrphaned(VnodeId vnode);
+static int IsVnodeOrphaned(struct SalvInfo *salvinfo, VnodeId vnode);
+static int AskVolumeSummary(struct SalvInfo *salvinfo,
+                            VolumeId singleVolumeNumber);
+
+#ifdef AFS_DEMAND_ATTACH_FS
+static int LockVolume(struct SalvInfo *salvinfo, VolumeId volumeId);
+#endif /* AFS_DEMAND_ATTACH_FS */
 
 /* Uniquifier stored in the Inode */
 static Unique
@@ -317,7 +341,7 @@ IUnique(Unique u)
 }
 
 static int
-BadError(register int aerror)
+BadError(int aerror)
 {
     if (aerror == EPERM || aerror == ENXIO || aerror == ENOENT)
        return 1;
@@ -332,40 +356,43 @@ extern pthread_t main_thread;
 childJob_t myjob = { SALVAGER_MAGIC, NOT_CHILD, "" };
 #endif
 
-/* Get the salvage lock if not already held. Hold until process exits. */
-void
-ObtainSalvageLock(void)
+/**
+ * Get the salvage lock if not already held. Hold until process exits.
+ *
+ * @param[in] locktype READ_LOCK or WRITE_LOCK
+ */
+static void
+_ObtainSalvageLock(int locktype)
 {
-    int salvageLock;
+    struct VLockFile salvageLock;
+    int offset = 0;
+    int nonblock = 1;
+    int code;
 
-#ifdef AFS_NT40_ENV
-    salvageLock =
-       (int)CreateFile(AFSDIR_SERVER_SLVGLOCK_FILEPATH, 0, 0, NULL,
-                       OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
-    if (salvageLock == (int)INVALID_HANDLE_VALUE) {
-       fprintf(stderr,
-               "salvager:  There appears to be another salvager running!  Aborted.\n");
-       Exit(1);
-    }
-#else
-    salvageLock =
-       afs_open(AFSDIR_SERVER_SLVGLOCK_FILEPATH, O_CREAT | O_RDWR, 0666);
-    if (salvageLock < 0) {
+    VLockFileInit(&salvageLock, AFSDIR_SERVER_SLVGLOCK_FILEPATH);
+
+    code = VLockFileLock(&salvageLock, offset, locktype, nonblock);
+    if (code == EBUSY) {
        fprintf(stderr,
-               "salvager:  can't open salvage lock file %s, aborting\n",
-               AFSDIR_SERVER_SLVGLOCK_FILEPATH);
+               "salvager:  There appears to be another salvager running!  "
+               "Aborted.\n");
        Exit(1);
-    }
-#ifdef AFS_DARWIN_ENV
-    if (flock(salvageLock, LOCK_EX) == -1) {
-#else
-    if (lockf(salvageLock, F_LOCK, 0) == -1) {
-#endif
+    } else if (code) {
        fprintf(stderr,
-               "salvager:  There appears to be another salvager running!  Aborted.\n");
+               "salvager:  Error %d trying to acquire salvage lock!  "
+               "Aborted.\n", code);
        Exit(1);
     }
-#endif
+}
+void
+ObtainSalvageLock(void)
+{
+    _ObtainSalvageLock(WRITE_LOCK);
+}
+void
+ObtainSharedSalvageLock(void)
+{
+    _ObtainSalvageLock(READ_LOCK);
 }
 
 
@@ -379,7 +406,7 @@ IsPartitionMounted(char *part)
     FILE *mntfp;
     struct mntent *mntent;
 
-    assert(mntfp = setmntent(MOUNTED, "r"));
+    osi_Assert(mntfp = setmntent(MOUNTED, "r"));
     while (mntent = getmntent(mntfp)) {
        if (!strcmp(part, mntent->mnt_dir))
            break;
@@ -396,7 +423,7 @@ IsRootInode(struct afs_stat *status)
 {
     /*
      * The root inode is not a fixed value in XFS partitions. So we need to
-     * see if the partition is in the list of mounted partitions. This only 
+     * see if the partition is in the list of mounted partitions. This only
      * affects the SalvageFileSys path, so we check there.
      */
     return (status->st_ino == ROOTINODE);
@@ -442,35 +469,31 @@ int
 SameDisk(struct DiskPartition64 *p1, struct DiskPartition64 *p2)
 {
 #define RES_LEN 256
-    char res[RES_LEN];
-    int d1, d2;
+    char res1[RES_LEN];
+    char res2[RES_LEN];
+
     static int dowarn = 1;
 
-    if (!QueryDosDevice(p1->devName, res, RES_LEN - 1))
+    if (!QueryDosDevice(p1->devName, res1, RES_LEN - 1))
        return 1;
-    if (strncmp(res, HDSTR, HDLEN)) {
+    if (strncmp(res1, HDSTR, HDLEN)) {
        if (dowarn) {
            dowarn = 0;
            Log("WARNING: QueryDosDevice is returning %s, not %s for %s\n",
-               res, HDSTR, p1->devName);
+               res1, HDSTR, p1->devName);
        }
-       return 1;
     }
-    d1 = atoi(&res[HDLEN]);
-
-    if (!QueryDosDevice(p2->devName, res, RES_LEN - 1))
+    if (!QueryDosDevice(p2->devName, res2, RES_LEN - 1))
        return 1;
-    if (strncmp(res, HDSTR, HDLEN)) {
+    if (strncmp(res2, HDSTR, HDLEN)) {
        if (dowarn) {
            dowarn = 0;
            Log("WARNING: QueryDosDevice is returning %s, not %s for %s\n",
-               res, HDSTR, p2->devName);
+               res2, HDSTR, p2->devName);
        }
-       return 1;
     }
-    d2 = atoi(&res[HDLEN]);
 
-    return d1 == d2;
+    return (0 == _strnicmp(res1, res2, RES_LEN - 1));
 }
 #else
 #define SameDisk(P1, P2) ((P1)->device/PartsPerDisk == (P2)->device/PartsPerDisk)
@@ -529,12 +552,12 @@ SalvageFileSysParallel(struct DiskPartition64 *partP)
     }
 
     if (thisjob) {
-       /* Check to see if thisjob is for a disk that we are already 
+       /* Check to see if thisjob is for a disk that we are already
         * salvaging. If it is, link it in as the next job to do. The
-        * jobs array has 1 entry per disk being salvages. numjobs is 
-        * the total number of disks currently being salvaged. In 
+        * jobs array has 1 entry per disk being salvages. numjobs is
+        * the total number of disks currently being salvaged. In
         * order to keep thejobs array compact, when a disk is
-        * completed, the hightest element in the jobs array is moved 
+        * completed, the hightest element in the jobs array is moved
         * down to now open slot.
         */
        for (j = 0; j < numjobs; j++) {
@@ -558,12 +581,12 @@ SalvageFileSysParallel(struct DiskPartition64 *partP)
             * job to finish. When it's done, clean up after it.
             */
            pid = wait(&wstatus);
-           assert(pid != -1);
+           osi_Assert(pid != -1);
            for (j = 0; j < numjobs; j++) {     /* Find which job it is */
                if (pid == jobs[j]->pid)
                    break;
            }
-           assert(j < numjobs);
+           osi_Assert(j < numjobs);
            if (WCOREDUMP(wstatus)) {   /* Say if the job core dumped */
                Log("Salvage of %s core dumped!\n", jobs[j]->partP->name);
            }
@@ -573,7 +596,7 @@ SalvageFileSysParallel(struct DiskPartition64 *partP)
            jobs[j] = jobs[j]->nextjob; /* Step to next part on same disk */
            free(oldjob);       /* free the old job */
 
-           /* If there is another partition on the disk to salvage, then 
+           /* If there is another partition on the disk to salvage, then
             * say we will start it (startjob). If not, then put thisjob there
             * and say we will start it.
             */
@@ -623,7 +646,7 @@ SalvageFileSysParallel(struct DiskPartition64 *partP)
                ShowLog = 0;
                for (fd = 0; fd < 16; fd++)
                    close(fd);
-               open("/", 0);
+               open(OS_DIRSEP, 0);
                dup2(0, 1);
                dup2(0, 2);
 #ifndef AFS_NT40_ENV
@@ -688,13 +711,13 @@ get_DevName(char *pbuffer, char *wpath)
 {
     char pbuf[128], *ptr;
     strcpy(pbuf, pbuffer);
-    ptr = (char *)strrchr(pbuf, '/');
+    ptr = (char *)strrchr(pbuf, OS_DIRSEPC);
     if (ptr) {
        *ptr = '\0';
        strcpy(wpath, pbuf);
     } else
        return NULL;
-    ptr = (char *)strrchr(pbuffer, '/');
+    ptr = (char *)strrchr(pbuffer, OS_DIRSEPC);
     if (ptr) {
        strcpy(pbuffer, ptr + 1);
        return pbuffer;
@@ -707,40 +730,82 @@ SalvageFileSys1(struct DiskPartition64 *partP, VolumeId singleVolumeNumber)
 {
     char *name, *tdir;
     char inodeListPath[256];
+    FILE *inodeFile = NULL;
     static char tmpDevName[100];
     static char wpath[100];
     struct VolumeSummary *vsp, *esp;
     int i, j;
+    int code;
+    int tries = 0;
+    struct SalvInfo l_salvinfo;
+    struct SalvInfo *salvinfo = &l_salvinfo;
 
-    fileSysPartition = partP;
-    fileSysDevice = fileSysPartition->device;
-    fileSysPathName = VPartitionPath(fileSysPartition);
+ retry:
+    memset(salvinfo, 0, sizeof(*salvinfo));
+
+    tries++;
+    if (inodeFile) {
+       fclose(inodeFile);
+       inodeFile = NULL;
+    }
+    if (tries > VOL_MAX_CHECKOUT_RETRIES) {
+       Abort("Raced too many times with fileserver restarts while trying to "
+             "checkout/lock volumes; Aborted\n");
+    }
+#ifdef AFS_DEMAND_ATTACH_FS
+    if (tries > 1) {
+       /* unlock all previous volume locks, since we're about to lock them
+        * again */
+       VLockFileReinit(&partP->volLockFile);
+    }
+#endif /* AFS_DEMAND_ATTACH_FS */
+
+    salvinfo->fileSysPartition = partP;
+    salvinfo->fileSysDevice = salvinfo->fileSysPartition->device;
+    salvinfo->fileSysPathName = VPartitionPath(salvinfo->fileSysPartition);
 
 #ifdef AFS_NT40_ENV
     /* Opendir can fail on "C:" but not on "C:\" if C is empty! */
-    (void)sprintf(fileSysPath, "%s\\", fileSysPathName);
+    (void)sprintf(salvinfo->fileSysPath, "%s" OS_DIRSEP, salvinfo->fileSysPathName);
     name = partP->devName;
 #else
-    fileSysPath = fileSysPathName;
+    strlcpy(salvinfo->fileSysPath, salvinfo->fileSysPathName, sizeof(salvinfo->fileSysPath));
     strcpy(tmpDevName, partP->devName);
     name = get_DevName(tmpDevName, wpath);
-    fileSysDeviceName = name;
-    filesysfulldev = wpath;
+    salvinfo->fileSysDeviceName = name;
+    salvinfo->filesysfulldev = wpath;
 #endif
 
-    VLockPartition(partP->name);
-    if (singleVolumeNumber || ForceSalvage)
+    if (singleVolumeNumber) {
+#ifndef AFS_DEMAND_ATTACH_FS
+       /* only non-DAFS locks the partition when salvaging a single volume;
+        * DAFS will lock the individual volumes in the VG */
+       VLockPartition(partP->name);
+#endif /* !AFS_DEMAND_ATTACH_FS */
+
        ForceSalvage = 1;
-    else
-       ForceSalvage = UseTheForceLuke(fileSysPath);
 
-    if (singleVolumeNumber) {
        /* salvageserver already setup fssync conn for us */
        if ((programType != salvageServer) && !VConnectFS()) {
            Abort("Couldn't connect to file server\n");
        }
-       AskOffline(singleVolumeNumber, partP->name);
+
+       salvinfo->useFSYNC = 1;
+       AskOffline(salvinfo, singleVolumeNumber);
+#ifdef AFS_DEMAND_ATTACH_FS
+       if (LockVolume(salvinfo, singleVolumeNumber)) {
+           goto retry;
+       }
+#endif /* AFS_DEMAND_ATTACH_FS */
+
     } else {
+       salvinfo->useFSYNC = 0;
+       VLockPartition(partP->name);
+       if (ForceSalvage) {
+           ForceSalvage = 1;
+       } else {
+           ForceSalvage = UseTheForceLuke(salvinfo->fileSysPath);
+       }
        if (!Showmode)
            Log("SALVAGING FILE SYSTEM PARTITION %s (device=%s%s)\n",
                partP->name, name, (Testing ? "(READONLY mode)" : ""));
@@ -750,56 +815,70 @@ SalvageFileSys1(struct DiskPartition64 *partP, VolumeId singleVolumeNumber)
 
 
     /*
-     * Remove any leftover /vicepa/salvage.inodes.* or /vicepa/salvage.temp.* 
-     * files 
+     * Remove any leftover /vicepa/salvage.inodes.* or /vicepa/salvage.temp.*
+     * files
      */
     {
        DIR *dirp;
        struct dirent *dp;
 
-       assert((dirp = opendir(fileSysPath)) != NULL);
+       osi_Assert((dirp = opendir(salvinfo->fileSysPath)) != NULL);
        while ((dp = readdir(dirp))) {
            if (!strncmp(dp->d_name, "salvage.inodes.", 15)
                || !strncmp(dp->d_name, "salvage.temp.", 13)) {
                char npath[1024];
                Log("Removing old salvager temp files %s\n", dp->d_name);
-               strcpy(npath, fileSysPath);
-               strcat(npath, "/");
+               strcpy(npath, salvinfo->fileSysPath);
+               strcat(npath, OS_DIRSEP);
                strcat(npath, dp->d_name);
-               unlink(npath);
+               OS_UNLINK(npath);
            }
        }
        closedir(dirp);
     }
-    tdir = (tmpdir ? tmpdir : fileSysPath);
+    tdir = (tmpdir ? tmpdir : salvinfo->fileSysPath);
 #ifdef AFS_NT40_ENV
     (void)_putenv("TMP=");     /* If "TMP" is set, then that overrides tdir. */
     (void)strncpy(inodeListPath, _tempnam(tdir, "salvage.inodes."), 255);
 #else
-    snprintf(inodeListPath, 255, "%s/salvage.inodes.%s.%d", tdir, name,
+    snprintf(inodeListPath, 255, "%s" OS_DIRSEP "salvage.inodes.%s.%d", tdir, name,
             getpid());
 #endif
-    if (GetInodeSummary(inodeListPath, singleVolumeNumber) < 0) {
-       unlink(inodeListPath);
-       return;
+
+    inodeFile = fopen(inodeListPath, "w+b");
+    if (!inodeFile) {
+       Abort("Error %d when creating inode description file %s; not salvaged\n", errno, inodeListPath);
     }
 #ifdef AFS_NT40_ENV
     /* Using nt_unlink here since we're really using the delete on close
      * semantics of unlink. In most places in the salvager, we really do
      * mean to unlink the file at that point. Those places have been
      * modified to actually do that so that the NT crt can be used there.
+     *
+     * jaltman - On NT delete on close cannot be applied to a file while the
+     * process has an open file handle that does not have DELETE file
+     * access and FILE_SHARE_DELETE.  fopen() calls CreateFile() without
+     * delete privileges.  As a result the nt_unlink() call will always
+     * fail.
      */
-    inodeFd =
-       _open_osfhandle((long)nt_open(inodeListPath, O_RDWR, 0), O_RDWR);
-    nt_unlink(inodeListPath);  /* NT's crt unlink won't if file is open. */
+    code = nt_unlink(inodeListPath);
 #else
-    inodeFd = afs_open(inodeListPath, O_RDONLY);
-    unlink(inodeListPath);
+    code = unlink(inodeListPath);
 #endif
-    if (inodeFd == -1)
+    if (code < 0) {
+       Log("Error %d when trying to unlink %s\n", errno, inodeListPath);
+    }
+
+    if (GetInodeSummary(salvinfo, inodeFile, singleVolumeNumber) < 0) {
+       fclose(inodeFile);
+       return;
+    }
+    salvinfo->inodeFd = fileno(inodeFile);
+    if (salvinfo->inodeFd == -1)
        Abort("Temporary file %s is missing...\n", inodeListPath);
+    afs_lseek(salvinfo->inodeFd, 0L, SEEK_SET);
     if (ListInodeOption) {
-       PrintInodeList();
+       PrintInodeList(salvinfo);
        return;
     }
     /* enumerate volumes in the partition.
@@ -808,15 +887,17 @@ SalvageFileSys1(struct DiskPartition64 *partP, VolumeId singleVolumeNumber)
      * Fix up inodes on last volume in set (whether it is read-write
      * or read-only).
      */
-    GetVolumeSummary(singleVolumeNumber);
+    if (GetVolumeSummary(salvinfo, singleVolumeNumber)) {
+       goto retry;
+    }
 
-    for (i = j = 0, vsp = volumeSummaryp, esp = vsp + nVolumes;
-        i < nVolumesInInodeFile; i = j) {
-       VolumeId rwvid = inodeSummary[i].RWvolumeId;
+    for (i = j = 0, vsp = salvinfo->volumeSummaryp, esp = vsp + salvinfo->nVolumes;
+        i < salvinfo->nVolumesInInodeFile; i = j) {
+       VolumeId rwvid = salvinfo->inodeSummary[i].RWvolumeId;
        for (j = i;
-            j < nVolumesInInodeFile && inodeSummary[j].RWvolumeId == rwvid;
+            j < salvinfo->nVolumesInInodeFile && salvinfo->inodeSummary[j].RWvolumeId == rwvid;
             j++) {
-           VolumeId vid = inodeSummary[j].volumeId;
+           VolumeId vid = salvinfo->inodeSummary[j].volumeId;
            struct VolumeSummary *tsp;
            /* Scan volume list (from partition root directory) looking for the
             * current rw volume number in the volume list from the inode scan.
@@ -824,14 +905,14 @@ SalvageFileSys1(struct DiskPartition64 *partP, VolumeId singleVolumeNumber)
             * delete it now. */
            for (; vsp < esp && (vsp->header.parent < rwvid); vsp++) {
                if (vsp->fileName)
-                   DeleteExtraVolumeHeaderFile(vsp);
+                   DeleteExtraVolumeHeaderFile(salvinfo, vsp);
            }
            /* Now match up the volume summary info from the root directory with the
             * entry in the volume list obtained from scanning inodes */
-           inodeSummary[j].volSummary = NULL;
+           salvinfo->inodeSummary[j].volSummary = NULL;
            for (tsp = vsp; tsp < esp && (tsp->header.parent == rwvid); tsp++) {
                if (tsp->header.id == vid) {
-                   inodeSummary[j].volSummary = tsp;
+                   salvinfo->inodeSummary[j].volSummary = tsp;
                    tsp->fileName = 0;
                    break;
                }
@@ -840,50 +921,73 @@ SalvageFileSys1(struct DiskPartition64 *partP, VolumeId singleVolumeNumber)
        /* Salvage the group of volumes (several read-only + 1 read/write)
         * starting with the current read-only volume we're looking at.
         */
-       SalvageVolumeGroup(&inodeSummary[i], j - i);
+       SalvageVolumeGroup(salvinfo, &salvinfo->inodeSummary[i], j - i);
     }
 
     /* Delete any additional volumes that were listed in the partition but which didn't have any corresponding inodes */
     for (; vsp < esp; vsp++) {
        if (vsp->fileName)
-           DeleteExtraVolumeHeaderFile(vsp);
+           DeleteExtraVolumeHeaderFile(salvinfo, vsp);
     }
 
     if (!singleVolumeNumber)   /* Remove the FORCESALVAGE file */
-       RemoveTheForce(fileSysPath);
+       RemoveTheForce(salvinfo->fileSysPath);
 
     if (!Testing && singleVolumeNumber) {
-       AskOnline(singleVolumeNumber, fileSysPartition->name);
+#ifdef AFS_DEMAND_ATTACH_FS
+       /* unlock vol headers so the fs can attach them when we AskOnline */
+       VLockFileReinit(&salvinfo->fileSysPartition->volLockFile);
+#endif /* AFS_DEMAND_ATTACH_FS */
+
+       AskOnline(salvinfo, singleVolumeNumber);
 
        /* Step through the volumeSummary list and set all volumes on-line.
         * The volumes were taken off-line in GetVolumeSummary.
         */
-       for (j = 0; j < nVolumes; j++) {
-           AskOnline(volumeSummaryp[j].header.id, fileSysPartition->name);
+       for (j = 0; j < salvinfo->nVolumes; j++) {
+           AskOnline(salvinfo, salvinfo->volumeSummaryp[j].header.id);
        }
     } else {
        if (!Showmode)
            Log("SALVAGING OF PARTITION %s%s COMPLETED\n",
-               fileSysPartition->name, (Testing ? " (READONLY mode)" : ""));
+               salvinfo->fileSysPartition->name, (Testing ? " (READONLY mode)" : ""));
     }
 
-    close(inodeFd);            /* SalvageVolumeGroup was the last which needed it. */
+    fclose(inodeFile);         /* SalvageVolumeGroup was the last which needed it. */
 }
 
 void
-DeleteExtraVolumeHeaderFile(register struct VolumeSummary *vsp)
+DeleteExtraVolumeHeaderFile(struct SalvInfo *salvinfo, struct VolumeSummary *vsp)
 {
+    char path[64];
+    sprintf(path, "%s" OS_DIRSEP "%s", salvinfo->fileSysPath, vsp->fileName);
+
     if (!Showmode)
-       Log("The volume header file %s is not associated with any actual data (%sdeleted)\n", vsp->fileName, (Testing ? "would have been " : ""));
-    if (!Testing)
-       unlink(vsp->fileName);
+       Log("The volume header file %s is not associated with any actual data (%sdeleted)\n", path, (Testing ? "would have been " : ""));
+    if (!Testing) {
+       afs_int32 code;
+       code = VDestroyVolumeDiskHeader(salvinfo->fileSysPartition, vsp->header.id, vsp->header.parent);
+       if (code) {
+           Log("Error %ld destroying volume disk header for volume %lu\n",
+               afs_printable_int32_ld(code),
+               afs_printable_uint32_lu(vsp->header.id));
+       }
+
+       /* make sure we actually delete the fileName file; ENOENT
+        * is fine, since VDestroyVolumeDiskHeader probably already
+        * unlinked it */
+       if (unlink(path) && errno != ENOENT) {
+           Log("Unable to unlink %s (errno = %d)\n", path, errno);
+       }
+    }
     vsp->fileName = 0;
 }
 
+int
 CompareInodes(const void *_p1, const void *_p2)
 {
-    register const struct ViceInodeInfo *p1 = _p1;
-    register const struct ViceInodeInfo *p2 = _p2;
+    const struct ViceInodeInfo *p1 = _p1;
+    const struct ViceInodeInfo *p2 = _p2;
     if (p1->u.vnode.vnodeNumber == INODESPECIAL
        || p2->u.vnode.vnodeNumber == INODESPECIAL) {
        VolumeId p1rwid, p2rwid;
@@ -977,13 +1081,13 @@ CompareInodes(const void *_p1, const void *_p2)
 }
 
 void
-CountVolumeInodes(register struct ViceInodeInfo *ip, int maxInodes,
-                 register struct InodeSummary *summary)
+CountVolumeInodes(struct ViceInodeInfo *ip, int maxInodes,
+                 struct InodeSummary *summary)
 {
-    int volume = ip->u.vnode.volumeId;
-    int rwvolume = volume;
-    register n, nSpecial;
-    register Unique maxunique;
+    VolumeId volume = ip->u.vnode.volumeId;
+    VolumeId rwvolume = volume;
+    int n, nSpecial;
+    Unique maxunique;
     n = nSpecial = 0;
     maxunique = 0;
     while (maxInodes-- && volume == ip->u.vnode.volumeId) {
@@ -1007,7 +1111,7 @@ CountVolumeInodes(register struct ViceInodeInfo *ip, int maxInodes,
 }
 
 int
-OnlyOneVolume(struct ViceInodeInfo *inodeinfo, int singleVolumeNumber, void *rock)
+OnlyOneVolume(struct ViceInodeInfo *inodeinfo, afs_uint32 singleVolumeNumber, void *rock)
 {
     if (inodeinfo->u.vnode.vnodeNumber == INODESPECIAL)
        return (inodeinfo->u.special.parentId == singleVolumeNumber);
@@ -1021,78 +1125,93 @@ OnlyOneVolume(struct ViceInodeInfo *inodeinfo, int singleVolumeNumber, void *roc
  * be unlinked by the caller.
  */
 int
-GetInodeSummary(char *path, VolumeId singleVolumeNumber)
+GetInodeSummary(struct SalvInfo *salvinfo, FILE *inodeFile, VolumeId singleVolumeNumber)
 {
     struct afs_stat status;
     int forceSal, err;
-    struct ViceInodeInfo *ip;
+    int code;
+    struct ViceInodeInfo *ip, *ip_save;
     struct InodeSummary summary;
     char summaryFileName[50];
     FILE *summaryFile;
 #ifdef AFS_NT40_ENV
-    char *dev = fileSysPath;
-    char *wpath = fileSysPath;
+    char *dev = salvinfo->fileSysPath;
+    char *wpath = salvinfo->fileSysPath;
 #else
-    char *dev = fileSysDeviceName;
-    char *wpath = filesysfulldev;
+    char *dev = salvinfo->fileSysDeviceName;
+    char *wpath = salvinfo->filesysfulldev;
 #endif
-    char *part = fileSysPath;
+    char *part = salvinfo->fileSysPath;
     char *tdir;
+    int i;
 
     /* This file used to come from vfsck; cobble it up ourselves now... */
     if ((err =
-        ListViceInodes(dev, fileSysPath, path,
+        ListViceInodes(dev, salvinfo->fileSysPath, inodeFile,
                        singleVolumeNumber ? OnlyOneVolume : 0,
                        singleVolumeNumber, &forceSal, forceR, wpath, NULL)) < 0) {
        if (err == -2) {
-           Log("*** I/O error %d when writing a tmp inode file %s; Not salvaged %s ***\nIncrease space on partition or use '-tmpdir'\n", errno, path, dev);
+           Log("*** I/O error %d when writing a tmp inode file; Not salvaged %s ***\nIncrease space on partition or use '-tmpdir'\n", errno, dev);
            return -1;
        }
-       unlink(path);
        Abort("Unable to get inodes for \"%s\"; not salvaged\n", dev);
     }
     if (forceSal && !ForceSalvage) {
        Log("***Forced salvage of all volumes on this partition***\n");
        ForceSalvage = 1;
     }
-    inodeFd = afs_open(path, O_RDWR);
-    if (inodeFd == -1 || afs_fstat(inodeFd, &status) == -1) {
-       unlink(path);
+    fseek(inodeFile, 0L, SEEK_SET);
+    salvinfo->inodeFd = fileno(inodeFile);
+    if (salvinfo->inodeFd == -1 || afs_fstat(salvinfo->inodeFd, &status) == -1) {
        Abort("No inode description file for \"%s\"; not salvaged\n", dev);
     }
     tdir = (tmpdir ? tmpdir : part);
 #ifdef AFS_NT40_ENV
     (void)_putenv("TMP=");     /* If "TMP" is set, then that overrides tdir. */
-    (void)strcpy(summaryFileName, _tempnam(tdir, "salvage.temp"));
+    (void)strcpy(summaryFileName, _tempnam(tdir, "salvage.temp."));
 #else
     (void)afs_snprintf(summaryFileName, sizeof summaryFileName,
-                      "%s/salvage.temp.%d", tdir, getpid());
+                      "%s" OS_DIRSEP "salvage.temp.%d", tdir, getpid());
 #endif
     summaryFile = afs_fopen(summaryFileName, "a+");
     if (summaryFile == NULL) {
-       close(inodeFd);
-       unlink(path);
        Abort("Unable to create inode summary file\n");
     }
+
+#ifdef AFS_NT40_ENV
+    /* Using nt_unlink here since we're really using the delete on close
+     * semantics of unlink. In most places in the salvager, we really do
+     * mean to unlink the file at that point. Those places have been
+     * modified to actually do that so that the NT crt can be used there.
+     *
+     * jaltman - As commented elsewhere, this cannot work because fopen()
+     * does not open files with DELETE and FILE_SHARE_DELETE.
+     */
+    code = nt_unlink(summaryFileName);
+#else
+    code = unlink(summaryFileName);
+#endif
+    if (code < 0) {
+       Log("Error %d when trying to unlink %s\n", errno, summaryFileName);
+    }
+
     if (!canfork || debug || Fork() == 0) {
        int nInodes;
        unsigned long st_size=(unsigned long) status.st_size;
        nInodes = st_size / sizeof(struct ViceInodeInfo);
        if (nInodes == 0) {
            fclose(summaryFile);
-           close(inodeFd);
-           unlink(summaryFileName);
            if (!singleVolumeNumber)    /* Remove the FORCESALVAGE file */
-               RemoveTheForce(fileSysPath);
+               RemoveTheForce(salvinfo->fileSysPath);
            else {
                struct VolumeSummary *vsp;
                int i;
 
-               GetVolumeSummary(singleVolumeNumber);
+               GetVolumeSummary(salvinfo, singleVolumeNumber);
 
-               for (i = 0, vsp = volumeSummaryp; i < nVolumes; i++) {
+               for (i = 0, vsp = salvinfo->volumeSummaryp; i < salvinfo->nVolumes; i++) {
                    if (vsp->fileName)
-                       DeleteExtraVolumeHeaderFile(vsp);
+                       DeleteExtraVolumeHeaderFile(salvinfo, vsp);
                }
            }
            Log("%s vice inodes on %s; not salvaged\n",
@@ -1102,47 +1221,39 @@ GetInodeSummary(char *path, VolumeId singleVolumeNumber)
        ip = (struct ViceInodeInfo *)malloc(nInodes*sizeof(struct ViceInodeInfo));
        if (ip == NULL) {
            fclose(summaryFile);
-           close(inodeFd);
-           unlink(path);
-           unlink(summaryFileName);
            Abort
                ("Unable to allocate enough space to read inode table; %s not salvaged\n",
                 dev);
        }
-       if (read(inodeFd, ip, st_size) != st_size) {
+       if (read(salvinfo->inodeFd, ip, st_size) != st_size) {
            fclose(summaryFile);
-           close(inodeFd);
-           unlink(path);
-           unlink(summaryFileName);
            Abort("Unable to read inode table; %s not salvaged\n", dev);
        }
        qsort(ip, nInodes, sizeof(struct ViceInodeInfo), CompareInodes);
-       if (afs_lseek(inodeFd, 0, SEEK_SET) == -1
-           || write(inodeFd, ip, st_size) != st_size) {
+       if (afs_lseek(salvinfo->inodeFd, 0, SEEK_SET) == -1
+           || write(salvinfo->inodeFd, ip, st_size) != st_size) {
            fclose(summaryFile);
-           close(inodeFd);
-           unlink(path);
-           unlink(summaryFileName);
            Abort("Unable to rewrite inode table; %s not salvaged\n", dev);
        }
        summary.index = 0;
+       ip_save = ip;
        while (nInodes) {
            CountVolumeInodes(ip, nInodes, &summary);
            if (fwrite(&summary, sizeof(summary), 1, summaryFile) != 1) {
                Log("Difficulty writing summary file (errno = %d); %s not salvaged\n", errno, dev);
                fclose(summaryFile);
-               close(inodeFd);
                return -1;
            }
            summary.index += (summary.nInodes);
            nInodes -= summary.nInodes;
            ip += summary.nInodes;
        }
+       free(ip_save);
+       ip = ip_save = NULL;
        /* Following fflush is not fclose, because if it was debug mode would not work */
        if (fflush(summaryFile) == EOF || fsync(fileno(summaryFile)) == -1) {
            Log("Unable to write summary file (errno = %d); %s not salvaged\n", errno, dev);
            fclose(summaryFile);
-           close(inodeFd);
            return -1;
        }
        if (canfork && !debug) {
@@ -1152,28 +1263,26 @@ GetInodeSummary(char *path, VolumeId singleVolumeNumber)
     } else {
        if (Wait("Inode summary") == -1) {
            fclose(summaryFile);
-           close(inodeFd);
-           unlink(path);
-           unlink(summaryFileName);
            Exit(1);            /* salvage of this partition aborted */
        }
     }
-    assert(afs_fstat(fileno(summaryFile), &status) != -1);
+    osi_Assert(afs_fstat(fileno(summaryFile), &status) != -1);
     if (status.st_size != 0) {
        int ret;
        unsigned long st_status=(unsigned long)status.st_size;
-       inodeSummary = (struct InodeSummary *)malloc(st_status);
-       assert(inodeSummary != NULL);
+       salvinfo->inodeSummary = (struct InodeSummary *)malloc(st_status);
+       osi_Assert(salvinfo->inodeSummary != NULL);
        /* For GNU we need to do lseek to get the file pointer moved. */
-       assert(afs_lseek(fileno(summaryFile), 0, SEEK_SET) == 0);
-       ret = read(fileno(summaryFile), inodeSummary, st_status);
-       assert(ret == st_status);
+       osi_Assert(afs_lseek(fileno(summaryFile), 0, SEEK_SET) == 0);
+       ret = read(fileno(summaryFile), salvinfo->inodeSummary, st_status);
+       osi_Assert(ret == st_status);
+    }
+    salvinfo->nVolumesInInodeFile =(unsigned long)(status.st_size) / sizeof(struct InodeSummary);
+    for (i = 0; i < salvinfo->nVolumesInInodeFile; i++) {
+       salvinfo->inodeSummary[i].volSummary = NULL;
     }
-    nVolumesInInodeFile =(unsigned long)(status.st_size) / sizeof(struct InodeSummary);
-    Log("%d nVolumesInInodeFile %d \n",nVolumesInInodeFile,(unsigned long)(status.st_size));
+    Log("%d nVolumesInInodeFile %lu \n",salvinfo->nVolumesInInodeFile,(unsigned long)(status.st_size));
     fclose(summaryFile);
-    close(inodeFd);
-    unlink(summaryFileName);
     return 0;
 }
 
@@ -1183,8 +1292,8 @@ GetInodeSummary(char *path, VolumeId singleVolumeNumber)
 int
 CompareVolumes(const void *_p1, const void *_p2)
 {
-    register const struct VolumeSummary *p1 = _p1;
-    register const struct VolumeSummary *p2 = _p2;
+    const struct VolumeSummary *p1 = _p1;
+    const struct VolumeSummary *p2 = _p2;
     if (p1->header.parent != p2->header.parent)
        return p1->header.parent < p2->header.parent ? -1 : 1;
     if (p1->header.id == p1->header.parent)    /* p1 is rw volume */
@@ -1194,129 +1303,452 @@ CompareVolumes(const void *_p1, const void *_p2)
     return p1->header.id < p2->header.id ? -1 : 1;     /* Both read-only */
 }
 
-void
-GetVolumeSummary(VolumeId singleVolumeNumber)
+/**
+ * Gleans volumeSummary information by asking the fileserver
+ *
+ * @param[in] singleVolumeNumber  the volume we're salvaging. 0 if we're
+ *                                salvaging a whole partition
+ *
+ * @return whether we obtained the volume summary information or not
+ *  @retval 0  success; we obtained the volume summary information
+ *  @retval -1 we raced with a fileserver restart; volume locks and checkout
+ *             must be retried
+ *  @retval 1  we did not get the volume summary information; either the
+ *             fileserver responded with an error, or we are not supposed to
+ *             ask the fileserver for the information (e.g. we are salvaging
+ *             the entire partition or we are not the salvageserver)
+ *
+ * @note for non-DAFS, always returns 1
+ */
+static int
+AskVolumeSummary(struct SalvInfo *salvinfo, VolumeId singleVolumeNumber)
 {
-    DIR *dirp = NULL;
-    afs_int32 nvols = 0;
-    struct VolumeSummary *vsp, vs;
-    struct VolumeDiskHeader diskHeader;
-    struct dirent *dp;
-
-    /* Get headers from volume directory */
-    dirp = opendir(fileSysPath);
-    if (dirp  == NULL)
-       Abort("Can't read directory %s; not salvaged\n", fileSysPath);
-    if (!singleVolumeNumber) {
-       while ((dp = readdir(dirp))) {
-           char *p = dp->d_name;
-           p = strrchr(dp->d_name, '.');
-           if (p != NULL && strcmp(p, VHDREXT) == 0) {
-               int fd;
-               if ((fd = afs_open(dp->d_name, O_RDONLY)) != -1
-                   && read(fd, (char *)&diskHeader, sizeof(diskHeader))
-                   == sizeof(diskHeader)
-                   && diskHeader.stamp.magic == VOLUMEHEADERMAGIC) {
-                   DiskToVolumeHeader(&vs.header, &diskHeader);
-                   nvols++;
+    afs_int32 code = 1;
+#if defined(FSSYNC_BUILD_CLIENT) && defined(AFS_DEMAND_ATTACH_FS)
+    if (programType == salvageServer) {
+       if (singleVolumeNumber) {
+           FSSYNC_VGQry_response_t q_res;
+           SYNC_response res;
+           struct VolumeSummary *vsp;
+           int i;
+           struct VolumeDiskHeader diskHdr;
+
+           memset(&res, 0, sizeof(res));
+
+           code = FSYNC_VGCQuery(salvinfo->fileSysPartition->name, singleVolumeNumber, &q_res, &res);
+
+           /*
+            * We must wait for the partition to finish scanning before
+            * can continue, since we will not know if we got the entire
+            * VG membership unless the partition is fully scanned.
+            * We could, in theory, just scan the partition ourselves if
+            * the VG cache is not ready, but we would be doing the exact
+            * same scan the fileserver is doing; it will almost always
+            * be faster to wait for the fileserver. The only exceptions
+            * are if the partition does not take very long to scan, and
+            * in that case it's fast either way, so who cares?
+            */
+           if (code == SYNC_FAILED && res.hdr.reason == FSYNC_PART_SCANNING) {
+               Log("waiting for fileserver to finish scanning partition %s...\n",
+                   salvinfo->fileSysPartition->name);
+
+               for (i = 1; code == SYNC_FAILED && res.hdr.reason == FSYNC_PART_SCANNING; i++) {
+                   /* linearly ramp up from 1 to 10 seconds; nothing fancy,
+                    * just so small partitions don't need to wait over 10
+                    * seconds every time, and large partitions are generally
+                    * polled only once every ten seconds. */
+                   sleep((i > 10) ? (i = 10) : i);
+
+                   code = FSYNC_VGCQuery(salvinfo->fileSysPartition->name, singleVolumeNumber, &q_res, &res);
                }
-               close(fd);
            }
-       }
-#ifdef AFS_NT40_ENV
-       closedir(dirp);
-       dirp = opendir(".");    /* No rewinddir for NT */
-#else
-       rewinddir(dirp);
-#endif
-       if (!nvols)
-           nvols = 1;
-       volumeSummaryp =
-           (struct VolumeSummary *)malloc(nvols *
-                                          sizeof(struct VolumeSummary));
-    } else
-       volumeSummaryp =
-           (struct VolumeSummary *)malloc(20 * sizeof(struct VolumeSummary));
-    assert(volumeSummaryp != NULL);
-
-    nVolumes = 0;
-    vsp = volumeSummaryp;
-    while ((dp = readdir(dirp))) {
-       char *p = dp->d_name;
-       p = strrchr(dp->d_name, '.');
-       if (p != NULL && strcmp(p, VHDREXT) == 0) {
-           int error = 0;
-           int fd;
-           if ((fd = afs_open(dp->d_name, O_RDONLY)) == -1
-               || read(fd, &diskHeader, sizeof(diskHeader))
-               != sizeof(diskHeader)
-               || diskHeader.stamp.magic != VOLUMEHEADERMAGIC) {
-               error = 1;
+
+           if (code == SYNC_FAILED && res.hdr.reason == FSYNC_UNKNOWN_VOLID) {
+               /* This can happen if there's no header for the volume
+                * we're salvaging, or no headers exist for the VG (if
+                * we're salvaging an RW). Act as if we got a response
+                * with no VG members. The headers may be created during
+                * salvaging, if there are inodes in this VG. */
+               code = 0;
+               memset(&q_res, 0, sizeof(q_res));
+               q_res.rw = singleVolumeNumber;
            }
-           close(fd);
-           if (error) {
-               if (!singleVolumeNumber) {
-                   if (!Showmode)
-                       Log("%s/%s is not a legitimate volume header file; %sdeleted\n", fileSysPathName, dp->d_name, (Testing ? "it would have been " : ""));
-                   if (!Testing)
-                       unlink(dp->d_name);
-               }
-           } else {
-               char nameShouldBe[64];
-               DiskToVolumeHeader(&vsp->header, &diskHeader);
-               if (singleVolumeNumber && vsp->header.id == singleVolumeNumber
-                   && vsp->header.parent != singleVolumeNumber) {
-                   if (programType == salvageServer) {
+
+           if (code) {
+               Log("fileserver refused VGCQuery request for volume %lu on "
+                   "partition %s, code %ld reason %ld\n",
+                   afs_printable_uint32_lu(singleVolumeNumber),
+                   salvinfo->fileSysPartition->name,
+                   afs_printable_int32_ld(code),
+                   afs_printable_int32_ld(res.hdr.reason));
+               goto done;
+           }
+
+           if (q_res.rw != singleVolumeNumber) {
+               Log("fileserver requested salvage of clone %lu; scheduling salvage of volume group %lu...\n",
+                   afs_printable_uint32_lu(singleVolumeNumber),
+                   afs_printable_uint32_lu(q_res.rw));
 #ifdef SALVSYNC_BUILD_CLIENT
-                       Log("fileserver requested salvage of clone %u; scheduling salvage of volume group %u...\n",
-                           vsp->header.id, vsp->header.parent);
-                       if (SALVSYNC_LinkVolume(vsp->header.parent,
-                                               vsp->header.id,
-                                               fileSysPartition->name,
-                                               NULL) != SYNC_OK) {
-                           Log("schedule request failed\n");
-                       }
-#endif
-                       Exit(SALSRV_EXIT_VOLGROUP_LINK);
-                   } else {
-                       Log("%u is a read-only volume; not salvaged\n",
-                           singleVolumeNumber);
-                       Exit(1);
+               if (SALVSYNC_LinkVolume(q_res.rw,
+                                      singleVolumeNumber,
+                                      salvinfo->fileSysPartition->name,
+                                      NULL) != SYNC_OK) {
+                   Log("schedule request failed\n");
+               }
+#endif /* SALVSYNC_BUILD_CLIENT */
+               Exit(SALSRV_EXIT_VOLGROUP_LINK);
+           }
+
+           salvinfo->volumeSummaryp = calloc(VOL_VG_MAX_VOLS, sizeof(struct VolumeSummary));
+           osi_Assert(salvinfo->volumeSummaryp != NULL);
+
+           salvinfo->nVolumes = 0;
+           vsp = salvinfo->volumeSummaryp;
+
+           for (i = 0; i < VOL_VG_MAX_VOLS; i++) {
+               char name[VMAXPATHLEN];
+
+               if (!q_res.children[i]) {
+                   continue;
+               }
+
+               /* AskOffline for singleVolumeNumber was called much earlier */
+               if (q_res.children[i] != singleVolumeNumber) {
+                   AskOffline(salvinfo, q_res.children[i]);
+                   if (LockVolume(salvinfo, q_res.children[i])) {
+                       /* need to retry */
+                       return -1;
                    }
                }
-               if (!singleVolumeNumber
-                   || (vsp->header.id == singleVolumeNumber
-                       || vsp->header.parent == singleVolumeNumber)) {
-                   (void)afs_snprintf(nameShouldBe, sizeof nameShouldBe,
-                                      VFORMAT, vsp->header.id);
-                   if (singleVolumeNumber 
-                       && vsp->header.id != singleVolumeNumber)
-                       AskOffline(vsp->header.id, fileSysPartition->name);
-                   if (strcmp(nameShouldBe, dp->d_name)) {
-                       if (!Showmode)
-                           Log("Volume header file %s is incorrectly named; %sdeleted (it will be recreated later, if necessary)\n", dp->d_name, (Testing ? "it would have been " : ""));
-                       if (!Testing)
-                           unlink(dp->d_name);
-                   } else {
-                       vsp->fileName = ToString(dp->d_name);
-                       nVolumes++;
-                       vsp++;
+
+               code = VReadVolumeDiskHeader(q_res.children[i], salvinfo->fileSysPartition, &diskHdr);
+               if (code) {
+                   Log("Cannot read header for %lu; trying to salvage group anyway\n",
+                       afs_printable_uint32_lu(q_res.children[i]));
+                   code = 0;
+                   continue;
+               }
+
+               DiskToVolumeHeader(&vsp->header, &diskHdr);
+               VolumeExternalName_r(q_res.children[i], name, sizeof(name));
+               vsp->fileName = ToString(name);
+               salvinfo->nVolumes++;
+               vsp++;
+           }
+
+           qsort(salvinfo->volumeSummaryp, salvinfo->nVolumes, sizeof(struct VolumeSummary),
+                 CompareVolumes);
+       }
+      done:
+       if (code) {
+           Log("Cannot get volume summary from fileserver; falling back to scanning "
+               "entire partition\n");
+       }
+    }
+#endif /* FSSYNC_BUILD_CLIENT && AFS_DEMAND_ATTACH_FS */
+    return code;
+}
+
+/**
+ * count how many volume headers are found by VWalkVolumeHeaders.
+ *
+ * @param[in] dp   the disk partition (unused)
+ * @param[in] name full path to the .vol header (unused)
+ * @param[in] hdr  the header data (unused)
+ * @param[in] last whether this is the last try or not (unused)
+ * @param[in] rock actually an afs_int32*; the running count of how many
+ *                 volumes we have found
+ *
+ * @retval 0 always
+ */
+static int
+CountHeader(struct DiskPartition64 *dp, const char *name,
+            struct VolumeDiskHeader *hdr, int last, void *rock)
+{
+    afs_int32 *nvols = (afs_int32 *)rock;
+    (*nvols)++;
+    return 0;
+}
+
+/**
+ * parameters to pass to the VWalkVolumeHeaders callbacks when recording volume
+ * data.
+ */
+struct SalvageScanParams {
+    VolumeId singleVolumeNumber; /**< 0 for a partition-salvage, otherwise the
+                                  * vol id of the VG we're salvaging */
+    struct VolumeSummary *vsp;   /**< ptr to the current volume summary object
+                                  * we're filling in */
+    afs_int32 nVolumes;          /**< # of vols we've encountered */
+    afs_int32 totalVolumes;      /**< max # of vols we should encounter (the
+                                  * # of vols we've alloc'd memory for) */
+    int retry;  /**< do we need to retry vol lock/checkout? */
+    struct SalvInfo *salvinfo; /**< salvage job info */
+};
+
+/**
+ * records volume summary info found from VWalkVolumeHeaders.
+ *
+ * Found volumes are also taken offline if they are in the specific volume
+ * group we are looking for.
+ *
+ * @param[in] dp   the disk partition
+ * @param[in] name full path to the .vol header
+ * @param[in] hdr  the header data
+ * @param[in] last 1 if this is the last try to read the header, 0 otherwise
+ * @param[in] rock actually a struct SalvageScanParams*, containing the
+ *                 information needed to record the volume summary data
+ *
+ * @return operation status
+ *  @retval 0  success
+ *  @retval -1 volume locking raced with fileserver restart; checking out
+ *             and locking volumes needs to be retried
+ *  @retval 1  volume header is mis-named and should be deleted
+ */
+static int
+RecordHeader(struct DiskPartition64 *dp, const char *name,
+             struct VolumeDiskHeader *hdr, int last, void *rock)
+{
+    char nameShouldBe[64];
+    struct SalvageScanParams *params;
+    struct VolumeSummary summary;
+    VolumeId singleVolumeNumber;
+    struct SalvInfo *salvinfo;
+
+    params = (struct SalvageScanParams *)rock;
+
+    singleVolumeNumber = params->singleVolumeNumber;
+    salvinfo = params->salvinfo;
+
+    DiskToVolumeHeader(&summary.header, hdr);
+
+    if (singleVolumeNumber && summary.header.id == singleVolumeNumber
+        && summary.header.parent != singleVolumeNumber) {
+
+       if (programType == salvageServer) {
+#ifdef SALVSYNC_BUILD_CLIENT
+           Log("fileserver requested salvage of clone %u; scheduling salvage of volume group %u...\n",
+               summary.header.id, summary.header.parent);
+           if (SALVSYNC_LinkVolume(summary.header.parent,
+                                   summary.header.id,
+                                   dp->name,
+                                   NULL) != SYNC_OK) {
+               Log("schedule request failed\n");
+           }
+#endif
+           Exit(SALSRV_EXIT_VOLGROUP_LINK);
+
+       } else {
+           Log("%u is a read-only volume; not salvaged\n",
+               singleVolumeNumber);
+           Exit(1);
+       }
+    }
+
+    if (!singleVolumeNumber || summary.header.id == singleVolumeNumber
+       || summary.header.parent == singleVolumeNumber) {
+
+       /* check if the header file is incorrectly named */
+       int badname = 0;
+       const char *base = strrchr(name, OS_DIRSEPC);
+       if (base) {
+           base++;
+       } else {
+           base = name;
+       }
+
+       (void)afs_snprintf(nameShouldBe, sizeof nameShouldBe,
+                          VFORMAT, afs_printable_uint32_lu(summary.header.id));
+
+
+       if (strcmp(nameShouldBe, base)) {
+           /* .vol file has wrong name; retry/delete */
+           badname = 1;
+       }
+
+       if (!badname || last) {
+           /* only offline the volume if the header is good, or if this is
+            * the last try looking at it; avoid AskOffline'ing the same vol
+            * multiple times */
+
+           if (singleVolumeNumber
+               && summary.header.id != singleVolumeNumber) {
+               /* don't offline singleVolumeNumber; we already did that
+                * earlier */
+
+               AskOffline(salvinfo, summary.header.id);
+
+#ifdef AFS_DEMAND_ATTACH_FS
+               if (!badname) {
+                   /* don't lock the volume if the header is bad, since we're
+                    * about to delete it anyway. */
+                   if (LockVolume(salvinfo, summary.header.id)) {
+                       params->retry = 1;
+                       return -1;
                    }
                }
+#endif /* AFS_DEMAND_ATTACH_FS */
+           }
+       }
+       if (badname) {
+           if (last && !Showmode) {
+               Log("Volume header file %s is incorrectly named (should be %s "
+                   "not %s); %sdeleted (it will be recreated later, if "
+                   "necessary)\n", name, nameShouldBe, base,
+                   (Testing ? "it would have been " : ""));
            }
-           close(fd);
+           return 1;
+       }
+
+       summary.fileName = ToString(base);
+       params->nVolumes++;
+
+       if (params->nVolumes > params->totalVolumes) {
+           /* We found more volumes than we found on the first partition walk;
+            * apparently something created a volume while we were
+            * partition-salvaging, or we found more than 20 vols when salvaging a
+            * particular volume. Abort if we detect this, since other programs
+            * supposed to not touch the partition while it is partition-salvaging,
+            * and we shouldn't find more than 20 vols in a VG.
+            */
+           Abort("Found %ld vol headers, but should have found at most %ld! "
+                 "Make sure the volserver/fileserver are not running at the "
+                 "same time as a partition salvage\n",
+                 afs_printable_int32_ld(params->nVolumes),
+                 afs_printable_int32_ld(params->totalVolumes));
+       }
+
+       memcpy(params->vsp, &summary, sizeof(summary));
+       params->vsp++;
+    }
+
+    return 0;
+}
+
+/**
+ * possibly unlinks bad volume headers found from VWalkVolumeHeaders.
+ *
+ * If the header could not be read in at all, the header is always unlinked.
+ * If instead RecordHeader said the header was bad (that is, the header file
+ * is mis-named), we only unlink if we are doing a partition salvage, as
+ * opposed to salvaging a specific volume group.
+ *
+ * @param[in] dp   the disk partition
+ * @param[in] name full path to the .vol header
+ * @param[in] hdr  header data, or NULL if the header could not be read
+ * @param[in] rock actually a struct SalvageScanParams*, with some information
+ *                 about the scan
+ */
+static void
+UnlinkHeader(struct DiskPartition64 *dp, const char *name,
+             struct VolumeDiskHeader *hdr, void *rock)
+{
+    struct SalvageScanParams *params;
+    int dounlink = 0;
+
+    params = (struct SalvageScanParams *)rock;
+
+    if (!hdr) {
+       /* no header; header is too bogus to read in at all */
+       if (!Showmode) {
+           Log("%s is not a legitimate volume header file; %sdeleted\n", name, (Testing ? "it would have been " : ""));
+       }
+       if (!Testing) {
+           dounlink = 1;
+       }
+
+    } else if (!params->singleVolumeNumber) {
+       /* We were able to read in a header, but RecordHeader said something
+        * was wrong with it. We only unlink those if we are doing a partition
+        * salvage. */
+       if (!Testing) {
+           dounlink = 1;
+       }
+    }
+
+    if (dounlink && unlink(name)) {
+       Log("Error %d while trying to unlink %s\n", errno, name);
+    }
+}
+
+/**
+ * Populates salvinfo->volumeSummaryp with volume summary information, either by asking
+ * the fileserver for VG information, or by scanning the /vicepX partition.
+ *
+ * @param[in] singleVolumeNumber  the volume ID of the single volume group we
+ *                                are salvaging, or 0 if this is a partition
+ *                                salvage
+ *
+ * @return operation status
+ *  @retval 0  success
+ *  @retval -1 we raced with a fileserver restart; checking out and locking
+ *             volumes must be retried
+ */
+int
+GetVolumeSummary(struct SalvInfo *salvinfo, VolumeId singleVolumeNumber)
+{
+    afs_int32 nvols = 0;
+    struct SalvageScanParams params;
+    int code;
+
+    code = AskVolumeSummary(salvinfo, singleVolumeNumber);
+    if (code == 0) {
+       /* we successfully got the vol information from the fileserver; no
+        * need to scan the partition */
+       return 0;
+    }
+    if (code < 0) {
+       /* we need to retry volume checkout */
+       return code;
+    }
+
+    if (!singleVolumeNumber) {
+       /* Count how many volumes we have in /vicepX */
+       code = VWalkVolumeHeaders(salvinfo->fileSysPartition, salvinfo->fileSysPath, CountHeader,
+                                 NULL, &nvols);
+       if (code < 0) {
+           Abort("Can't read directory %s; not salvaged\n", salvinfo->fileSysPath);
        }
+       if (!nvols)
+           nvols = 1;
+    } else {
+       nvols = VOL_VG_MAX_VOLS;
+    }
+
+    salvinfo->volumeSummaryp = calloc(nvols, sizeof(struct VolumeSummary));
+    osi_Assert(salvinfo->volumeSummaryp != NULL);
+
+    params.singleVolumeNumber = singleVolumeNumber;
+    params.vsp = salvinfo->volumeSummaryp;
+    params.nVolumes = 0;
+    params.totalVolumes = nvols;
+    params.retry = 0;
+    params.salvinfo = salvinfo;
+
+    /* walk the partition directory of volume headers and record the info
+     * about them; unlinking invalid headers */
+    code = VWalkVolumeHeaders(salvinfo->fileSysPartition, salvinfo->fileSysPath, RecordHeader,
+                              UnlinkHeader, &params);
+    if (params.retry) {
+       /* we apparently need to retry checking-out/locking volumes */
+       return -1;
+    }
+    if (code < 0) {
+       Abort("Failed to get volume header summary\n");
     }
-    closedir(dirp);
-    qsort(volumeSummaryp, nVolumes, sizeof(struct VolumeSummary),
+    salvinfo->nVolumes = params.nVolumes;
+
+    qsort(salvinfo->volumeSummaryp, salvinfo->nVolumes, sizeof(struct VolumeSummary),
          CompareVolumes);
+
+    return 0;
 }
 
 /* Find the link table. This should be associated with the RW volume or, if
  * a RO only site, then the RO volume. For now, be cautious and hunt carefully.
  */
 Inode
-FindLinkHandle(register struct InodeSummary *isp, int nVols,
+FindLinkHandle(struct InodeSummary *isp, int nVols,
               struct ViceInodeInfo *allInodes)
 {
     int i, j;
@@ -1333,21 +1765,21 @@ FindLinkHandle(register struct InodeSummary *isp, int nVols,
 }
 
 int
-CreateLinkTable(register struct InodeSummary *isp, Inode ino)
+CreateLinkTable(struct SalvInfo *salvinfo, struct InodeSummary *isp, Inode ino)
 {
     struct versionStamp version;
     FdHandle_t *fdP;
 
     if (!VALID_INO(ino))
        ino =
-           IH_CREATE(NULL, fileSysDevice, fileSysPath, 0, isp->volumeId,
+           IH_CREATE(NULL, salvinfo->fileSysDevice, salvinfo->fileSysPath, 0, isp->volumeId,
                      INODESPECIAL, VI_LINKTABLE, isp->RWvolumeId);
     if (!VALID_INO(ino))
        Abort
            ("Unable to allocate link table inode for volume %u (error = %d)\n",
             isp->RWvolumeId, errno);
-    IH_INIT(VGLinkH, fileSysDevice, isp->RWvolumeId, ino);
-    fdP = IH_OPEN(VGLinkH);
+    IH_INIT(salvinfo->VGLinkH, salvinfo->fileSysDevice, isp->RWvolumeId, ino);
+    fdP = IH_OPEN(salvinfo->VGLinkH);
     if (fdP == NULL)
        Abort("Can't open link table for volume %u (error = %d)\n",
              isp->RWvolumeId, errno);
@@ -1359,7 +1791,7 @@ CreateLinkTable(register struct InodeSummary *isp, Inode ino)
     version.magic = LINKTABLEMAGIC;
     version.version = LINKTABLEVERSION;
 
-    if (FDH_WRITE(fdP, (char *)&version, sizeof(version))
+    if (FDH_PWRITE(fdP, (char *)&version, sizeof(version), 0)
        != sizeof(version))
        Abort("Can't truncate link table for volume %u (error = %d)\n",
              isp->RWvolumeId, errno);
@@ -1380,12 +1812,12 @@ void *
 nt_SVG(void *arg)
 {
     SVGParms_t *parms = (SVGParms_t *) arg;
-    DoSalvageVolumeGroup(parms->svgp_inodeSummaryp, parms->svgp_count);
+    DoSalvageVolumeGroup(parms->svgp_salvinfo, parms->svgp_inodeSummaryp, parms->svgp_count);
     return NULL;
 }
 
 void
-SalvageVolumeGroup(register struct InodeSummary *isp, int nVols)
+SalvageVolumeGroup(struct SalvInfo *salvinfo, struct InodeSummary *isp, int nVols)
 {
     pthread_t tid;
     pthread_attr_t tattr;
@@ -1393,13 +1825,14 @@ SalvageVolumeGroup(register struct InodeSummary *isp, int nVols)
     SVGParms_t parms;
 
     /* Initialize per volume global variables, even if later code does so */
-    VolumeChanged = 0;
-    VGLinkH = NULL;
-    VGLinkH_cnt = 0;
-    memset(&VolInfo, 0, sizeof(VolInfo));
+    salvinfo->VolumeChanged = 0;
+    salvinfo->VGLinkH = NULL;
+    salvinfo->VGLinkH_cnt = 0;
+    memset(&salvinfo->VolInfo, 0, sizeof(salvinfo->VolInfo));
 
     parms.svgp_inodeSummaryp = isp;
     parms.svgp_count = nVols;
+    parms.svgp_salvinfo = salvinfo;
     code = pthread_attr_init(&tattr);
     if (code) {
        Log("Failed to salvage volume group %u: pthread_attr_init()\n",
@@ -1422,7 +1855,7 @@ SalvageVolumeGroup(register struct InodeSummary *isp, int nVols)
 #endif /* AFS_NT40_ENV */
 
 void
-DoSalvageVolumeGroup(register struct InodeSummary *isp, int nVols)
+DoSalvageVolumeGroup(struct SalvInfo *salvinfo, struct InodeSummary *isp, int nVols)
 {
     struct ViceInodeInfo *inodes, *allInodes, *ip;
     int i, totalInodes, size, salvageTo;
@@ -1433,11 +1866,11 @@ DoSalvageVolumeGroup(register struct InodeSummary *isp, int nVols)
     int VGLinkH_p1 =0;
     FdHandle_t *fdP = NULL;
 
-    VGLinkH_cnt = 0;
+    salvinfo->VGLinkH_cnt = 0;
     haveRWvolume = (isp->volumeId == isp->RWvolumeId
                    && isp->nSpecialInodes > 0);
     if ((!ShowMounts) || (ShowMounts && !haveRWvolume)) {
-       if (!ForceSalvage && QuickCheck(isp, nVols))
+       if (!ForceSalvage && QuickCheck(salvinfo, isp, nVols))
            return;
     }
     if (ShowMounts && !haveRWvolume)
@@ -1453,10 +1886,10 @@ DoSalvageVolumeGroup(register struct InodeSummary *isp, int nVols)
     allInodes = inodes - isp->index;   /* this would the base of all the inodes
                                         * for the partition, if all the inodes
                                         * had been read into memory */
-    assert(afs_lseek
-          (inodeFd, isp->index * sizeof(struct ViceInodeInfo),
+    osi_Assert(afs_lseek
+          (salvinfo->inodeFd, isp->index * sizeof(struct ViceInodeInfo),
            SEEK_SET) != -1);
-    assert(read(inodeFd, inodes, size) == size);
+    osi_Assert(read(salvinfo->inodeFd, inodes, size) == size);
 
     /* Don't try to salvage a read write volume if there isn't one on this
      * partition */
@@ -1465,29 +1898,25 @@ DoSalvageVolumeGroup(register struct InodeSummary *isp, int nVols)
 #ifdef AFS_NAMEI_ENV
     ino = FindLinkHandle(isp, nVols, allInodes);
     if (VALID_INO(ino)) {
-       IH_INIT(VGLinkH, fileSysDevice, isp->RWvolumeId, ino);
-       fdP = IH_OPEN(VGLinkH);
+       IH_INIT(salvinfo->VGLinkH, salvinfo->fileSysDevice, isp->RWvolumeId, ino);
+       fdP = IH_OPEN(salvinfo->VGLinkH);
     }
     if (!VALID_INO(ino) || fdP == NULL) {
        Log("%s link table for volume %u.\n",
            Testing ? "Would have recreated" : "Recreating", isp->RWvolumeId);
        if (Testing) {
-           IH_INIT(VGLinkH, fileSysDevice, -1, -1);
+           IH_INIT(salvinfo->VGLinkH, salvinfo->fileSysDevice, -1, -1);
        } else {
             int i, j;
             struct ViceInodeInfo *ip;
-           CreateLinkTable(isp, ino);
-           fdP = IH_OPEN(VGLinkH);
+           CreateLinkTable(salvinfo, isp, ino);
+           fdP = IH_OPEN(salvinfo->VGLinkH);
             /* Sync fake 1 link counts to the link table, now that it exists */
             if (fdP) {
                for (i = 0; i < nVols; i++) {
                        ip = allInodes + isp[i].index;
                         for (j = isp[i].nSpecialInodes; j < isp[i].nInodes; j++) {
-#ifdef AFS_NT40_ENV
-                                nt_SetLinkCount(fdP, ip[j].inodeNumber, 1, 1);
-#else
                                 namei_SetLinkCount(fdP, ip[j].inodeNumber, 1, 1);
-#endif
                    }
                }
            }
@@ -1496,7 +1925,7 @@ DoSalvageVolumeGroup(register struct InodeSummary *isp, int nVols)
     if (fdP)
        FDH_REALLYCLOSE(fdP);
 #else
-    IH_INIT(VGLinkH, fileSysDevice, -1, -1);
+    IH_INIT(salvinfo->VGLinkH, salvinfo->fileSysDevice, -1, -1);
 #endif
 
     /* Salvage in reverse order--read/write volume last; this way any
@@ -1526,9 +1955,9 @@ DoSalvageVolumeGroup(register struct InodeSummary *isp, int nVols)
         * way the whole RO volume can be deleted, below, if anything goes wrong */
        for (check = 1; check >= 0; check--) {
            int deleteMe;
-           if (SalvageVolumeHeaderFile(lisp, allInodes, rw, check, &deleteMe)
+           if (SalvageVolumeHeaderFile(salvinfo, lisp, allInodes, rw, check, &deleteMe)
                == -1) {
-               MaybeZapVolume(lisp, "Volume header", deleteMe, check);
+               MaybeZapVolume(salvinfo, lisp, "Volume header", deleteMe, check);
                if (rw && deleteMe) {
                    haveRWvolume = 0;   /* This will cause its inodes to be deleted--since salvage
                                         * volume won't be called */
@@ -1539,8 +1968,8 @@ DoSalvageVolumeGroup(register struct InodeSummary *isp, int nVols)
            }
            if (rw && check == 1)
                continue;
-           if (SalvageVnodes(isp, lisp, allInodes, check) == -1) {
-               MaybeZapVolume(lisp, "Vnode index", 0, check);
+           if (SalvageVnodes(salvinfo, isp, lisp, allInodes, check) == -1) {
+               MaybeZapVolume(salvinfo, lisp, "Vnode index", 0, check);
                break;
            }
        }
@@ -1548,26 +1977,27 @@ DoSalvageVolumeGroup(register struct InodeSummary *isp, int nVols)
 
     /* Fix actual inode counts */
     if (!Showmode) {
+       afs_ino_str_t stmp;
        Log("totalInodes %d\n",totalInodes);
        for (ip = inodes; totalInodes; ip++, totalInodes--) {
            static int TraceBadLinkCounts = 0;
 #ifdef AFS_NAMEI_ENV
-           if (VGLinkH->ih_ino == ip->inodeNumber) {
-               dec_VGLinkH = ip->linkCount - VGLinkH_cnt;
+           if (salvinfo->VGLinkH->ih_ino == ip->inodeNumber) {
+               dec_VGLinkH = ip->linkCount - salvinfo->VGLinkH_cnt;
                VGLinkH_p1 = ip->u.param[0];
                continue;       /* Deal with this last. */
            }
 #endif
            if (ip->linkCount != 0 && TraceBadLinkCounts) {
                TraceBadLinkCounts--;   /* Limit reports, per volume */
-               Log("#### DEBUG #### Link count incorrect by %d; inode %s, size %llu, p=(%u,%u,%u,%u)\n", ip->linkCount, PrintInode(NULL, ip->inodeNumber), (afs_uintmax_t) ip->byteCount, ip->u.param[0], ip->u.param[1], ip->u.param[2], ip->u.param[3]);
+               Log("#### DEBUG #### Link count incorrect by %d; inode %s, size %llu, p=(%u,%u,%u,%u)\n", ip->linkCount, PrintInode(stmp, ip->inodeNumber), (afs_uintmax_t) ip->byteCount, ip->u.param[0], ip->u.param[1], ip->u.param[2], ip->u.param[3]);
            }
            while (ip->linkCount > 0) {
                /* below used to assert, not break */
                if (!Testing) {
-                   if (IH_DEC(VGLinkH, ip->inodeNumber, ip->u.param[0])) {
+                   if (IH_DEC(salvinfo->VGLinkH, ip->inodeNumber, ip->u.param[0])) {
                        Log("idec failed. inode %s errno %d\n",
-                           PrintInode(NULL, ip->inodeNumber), errno);
+                           PrintInode(stmp, ip->inodeNumber), errno);
                        break;
                    }
                }
@@ -1576,9 +2006,9 @@ DoSalvageVolumeGroup(register struct InodeSummary *isp, int nVols)
            while (ip->linkCount < 0) {
                /* these used to be asserts */
                if (!Testing) {
-                   if (IH_INC(VGLinkH, ip->inodeNumber, ip->u.param[0])) {
+                   if (IH_INC(salvinfo->VGLinkH, ip->inodeNumber, ip->u.param[0])) {
                        Log("iinc failed. inode %s errno %d\n",
-                           PrintInode(NULL, ip->inodeNumber), errno);
+                           PrintInode(stmp, ip->inodeNumber), errno);
                        break;
                    }
                }
@@ -1587,13 +2017,13 @@ DoSalvageVolumeGroup(register struct InodeSummary *isp, int nVols)
        }
 #ifdef AFS_NAMEI_ENV
        while (dec_VGLinkH > 0) {
-           if (IH_DEC(VGLinkH, VGLinkH->ih_ino, VGLinkH_p1) < 0) {
+           if (IH_DEC(salvinfo->VGLinkH, salvinfo->VGLinkH->ih_ino, VGLinkH_p1) < 0) {
                Log("idec failed on link table, errno = %d\n", errno);
            }
            dec_VGLinkH--;
        }
        while (dec_VGLinkH < 0) {
-           if (IH_INC(VGLinkH, VGLinkH->ih_ino, VGLinkH_p1) < 0) {
+           if (IH_INC(salvinfo->VGLinkH, salvinfo->VGLinkH->ih_ino, VGLinkH_p1) < 0) {
                Log("iinc failed on link table, errno = %d\n", errno);
            }
            dec_VGLinkH++;
@@ -1603,8 +2033,8 @@ DoSalvageVolumeGroup(register struct InodeSummary *isp, int nVols)
     free(inodes);
     /* Directory consistency checks on the rw volume */
     if (haveRWvolume)
-       SalvageVolume(isp, VGLinkH);
-    IH_RELEASE(VGLinkH);
+       SalvageVolume(salvinfo, isp, salvinfo->VGLinkH);
+    IH_RELEASE(salvinfo->VGLinkH);
 
     if (canfork && !debug) {
        ShowLog = 0;
@@ -1613,10 +2043,10 @@ DoSalvageVolumeGroup(register struct InodeSummary *isp, int nVols)
 }
 
 int
-QuickCheck(register struct InodeSummary *isp, int nVols)
+QuickCheck(struct SalvInfo *salvinfo, struct InodeSummary *isp, int nVols)
 {
     /* Check headers BEFORE forking */
-    register int i;
+    int i;
     IHandle_t *h;
 
     for (i = 0; i < nVols; i++) {
@@ -1629,7 +2059,7 @@ QuickCheck(register struct InodeSummary *isp, int nVols)
                continue;
            return 0;
        }
-       IH_INIT(h, fileSysDevice, vs->header.parent, vs->header.volumeInfo);
+       IH_INIT(h, salvinfo->fileSysDevice, vs->header.parent, vs->header.volumeInfo);
        if (IH_IREAD(h, 0, (char *)&volHeader, sizeof(volHeader))
            == sizeof(volHeader)
            && volHeader.stamp.magic == VOLUMEINFOMAGIC
@@ -1665,47 +2095,157 @@ QuickCheck(register struct InodeSummary *isp, int nVols)
  */
 
 int
-SalvageVolumeHeaderFile(register struct InodeSummary *isp,
-                       register struct ViceInodeInfo *inodes, int RW,
+SalvageVolumeHeaderFile(struct SalvInfo *salvinfo, struct InodeSummary *isp,
+                       struct ViceInodeInfo *inodes, int RW,
                        int check, int *deleteMe)
 {
-    int headerFd = 0;
     int i;
-    register struct ViceInodeInfo *ip;
+    struct ViceInodeInfo *ip;
     int allinodesobsolete = 1;
     struct VolumeDiskHeader diskHeader;
+    afs_int32 (*writefunc)(VolumeDiskHeader_t *, struct DiskPartition64 *) = NULL;
+    int *skip;
+    struct VolumeHeader tempHeader;
+    struct afs_inode_info stuff[MAXINODETYPE];
+
+    /* keeps track of special inodes that are probably 'good'; they are
+     * referenced in the vol header, and are included in the given inodes
+     * array */
+    struct {
+       int valid;
+       Inode inode;
+    } goodspecial[MAXINODETYPE];
 
     if (deleteMe)
        *deleteMe = 0;
+
+    memset(goodspecial, 0, sizeof(goodspecial));
+
+    skip = malloc(isp->nSpecialInodes * sizeof(*skip));
+    if (skip) {
+       memset(skip, 0, isp->nSpecialInodes * sizeof(*skip));
+    } else {
+       Log("cannot allocate memory for inode skip array when salvaging "
+           "volume %lu; not performing duplicate special inode recovery\n",
+           afs_printable_uint32_lu(isp->volumeId));
+       /* still try to perform the salvage; the skip array only does anything
+        * if we detect duplicate special inodes */
+    }
+
+    init_inode_info(&tempHeader, stuff);
+
+    /*
+     * First, look at the special inodes and see if any are referenced by
+     * the existing volume header. If we find duplicate special inodes, we
+     * can use this information to use the referenced inode (it's more
+     * likely to be the 'good' one), and throw away the duplicates.
+     */
+    if (isp->volSummary && skip) {
+       /* use tempHeader, so we can use the stuff[] array to easily index
+        * into the isp->volSummary special inodes */
+       memcpy(&tempHeader, &isp->volSummary->header, sizeof(struct VolumeHeader));
+
+       for (i = 0; i < isp->nSpecialInodes; i++) {
+           ip = &inodes[isp->index + i];
+           if (ip->u.special.type <= 0 || ip->u.special.type > MAXINODETYPE) {
+               /* will get taken care of in a later loop */
+               continue;
+           }
+           if (ip->inodeNumber == *(stuff[ip->u.special.type - 1].inode)) {
+               goodspecial[ip->u.special.type-1].valid = 1;
+               goodspecial[ip->u.special.type-1].inode = ip->inodeNumber;
+           }
+       }
+    }
+
     memset(&tempHeader, 0, sizeof(tempHeader));
     tempHeader.stamp.magic = VOLUMEHEADERMAGIC;
     tempHeader.stamp.version = VOLUMEHEADERVERSION;
     tempHeader.id = isp->volumeId;
     tempHeader.parent = isp->RWvolumeId;
+
     /* Check for duplicates (inodes are sorted by type field) */
     for (i = 0; i < isp->nSpecialInodes - 1; i++) {
        ip = &inodes[isp->index + i];
        if (ip->u.special.type == (ip + 1)->u.special.type) {
-           if (!Showmode)
-               Log("Duplicate special inodes in volume header; salvage of volume %u aborted\n", isp->volumeId);
-           return -1;
+           afs_ino_str_t stmp1, stmp2;
+
+           if (ip->u.special.type <= 0 || ip->u.special.type > MAXINODETYPE) {
+               /* Will be caught in the loop below */
+               continue;
+           }
+           if (!Showmode) {
+               Log("Duplicate special %d inodes for volume %u found (%s, %s);\n",
+                   ip->u.special.type, isp->volumeId,
+                   PrintInode(stmp1, ip->inodeNumber),
+                   PrintInode(stmp2, (ip+1)->inodeNumber));
+           }
+           if (skip && goodspecial[ip->u.special.type-1].valid) {
+               Inode gi = goodspecial[ip->u.special.type-1].inode;
+
+               if (!Showmode) {
+                   Log("using special inode referenced by vol header (%s)\n",
+                       PrintInode(stmp1, gi));
+               }
+
+               /* the volume header references some special inode of
+                * this type in the inodes array; are we it? */
+               if (ip->inodeNumber != gi) {
+                   skip[i] = 1;
+               } else if ((ip+1)->inodeNumber != gi) {
+                   /* in case this is the last iteration; we need to
+                    * make sure we check ip+1, too */
+                   skip[i+1] = 1;
+               }
+           } else {
+               if (!Showmode)
+                   Log("cannot determine which is correct; salvage of volume %u aborted\n", isp->volumeId);
+               if (skip) {
+                   free(skip);
+               }
+               return -1;
+           }
        }
     }
     for (i = 0; i < isp->nSpecialInodes; i++) {
+       afs_ino_str_t stmp;
        ip = &inodes[isp->index + i];
        if (ip->u.special.type <= 0 || ip->u.special.type > MAXINODETYPE) {
            if (check) {
-               Log("Rubbish header inode\n");
+               Log("Rubbish header inode %s of type %d\n",
+                   PrintInode(stmp, ip->inodeNumber),
+                   ip->u.special.type);
+               if (skip) {
+                   free(skip);
+               }
                return -1;
            }
-           Log("Rubbish header inode; deleted\n");
+           Log("Rubbish header inode %s of type %d; deleted\n",
+               PrintInode(stmp, ip->inodeNumber),
+               ip->u.special.type);
        } else if (!stuff[ip->u.special.type - 1].obsolete) {
-           *(stuff[ip->u.special.type - 1].inode) = ip->inodeNumber;
+           if (skip && skip[i]) {
+               if (orphans == ORPH_REMOVE) {
+                   Log("Removing orphan special inode %s of type %d\n",
+                       PrintInode(stmp, ip->inodeNumber), ip->u.special.type);
+                   continue;
+               } else {
+                   Log("Ignoring orphan special inode %s of type %d\n",
+                       PrintInode(stmp, ip->inodeNumber), ip->u.special.type);
+                   /* fall through to the ip->linkCount--; line below */
+               }
+           } else {
+               *(stuff[ip->u.special.type - 1].inode) = ip->inodeNumber;
+               allinodesobsolete = 0;
+           }
            if (!check && ip->u.special.type != VI_LINKTABLE)
                ip->linkCount--;        /* Keep the inode around */
-           allinodesobsolete = 0;
        }
     }
+    if (skip) {
+       free(skip);
+    }
+    skip = NULL;
 
     if (allinodesobsolete) {
        if (deleteMe)
@@ -1714,7 +2254,7 @@ SalvageVolumeHeaderFile(register struct InodeSummary *isp,
     }
 
     if (!check)
-       VGLinkH_cnt++;          /* one for every header. */
+       salvinfo->VGLinkH_cnt++;                /* one for every header. */
 
     if (!RW && !check && isp->volSummary) {
        ClearROInUseBit(isp->volSummary);
@@ -1727,33 +2267,35 @@ SalvageVolumeHeaderFile(register struct InodeSummary *isp,
             * And we may have recreated the link table earlier, so set the
             * RW header as well.
             */
-           if (VALID_INO(VGLinkH->ih_ino)) {
-               *stuff[i].inode = VGLinkH->ih_ino;
+           if (VALID_INO(salvinfo->VGLinkH->ih_ino)) {
+               *stuff[i].inode = salvinfo->VGLinkH->ih_ino;
            }
            continue;
        }
-       if (SalvageHeader(&stuff[i], isp, check, deleteMe) == -1 && check)
+       if (SalvageHeader(salvinfo, &stuff[i], isp, check, deleteMe) == -1 && check)
            return -1;
     }
 
     if (isp->volSummary == NULL) {
-       char name[64];
-       (void)afs_snprintf(name, sizeof name, VFORMAT, isp->volumeId);
+       char path[64];
+       char headerName[64];
+       (void)afs_snprintf(headerName, sizeof headerName, VFORMAT, afs_printable_uint32_lu(isp->volumeId));
+       (void)afs_snprintf(path, sizeof path, "%s" OS_DIRSEP "%s", salvinfo->fileSysPath, headerName);
        if (check) {
            Log("No header file for volume %u\n", isp->volumeId);
            return -1;
        }
        if (!Showmode)
-           Log("No header file for volume %u; %screating %s/%s\n",
+           Log("No header file for volume %u; %screating %s\n",
                isp->volumeId, (Testing ? "it would have been " : ""),
-               fileSysPathName, name);
-       headerFd = afs_open(name, O_RDWR | O_CREAT | O_TRUNC, 0644);
-       assert(headerFd != -1);
-       isp->volSummary = (struct VolumeSummary *)
-           malloc(sizeof(struct VolumeSummary));
-       isp->volSummary->fileName = ToString(name);
+               path);
+       isp->volSummary = calloc(1, sizeof(struct VolumeSummary));
+       isp->volSummary->fileName = ToString(headerName);
+
+       writefunc = VCreateVolumeDiskHeader;
     } else {
-       char name[64];
+       char path[64];
+       char headerName[64];
        /* hack: these two fields are obsolete... */
        isp->volSummary->header.volumeAcl = 0;
        isp->volSummary->header.volumeMountTable = 0;
@@ -1763,22 +2305,22 @@ SalvageVolumeHeaderFile(register struct InodeSummary *isp,
             sizeof(struct VolumeHeader))) {
            /* We often remove the name before calling us, so we make a fake one up */
            if (isp->volSummary->fileName) {
-               strcpy(name, isp->volSummary->fileName);
+               strcpy(headerName, isp->volSummary->fileName);
            } else {
-               (void)afs_snprintf(name, sizeof name, VFORMAT, isp->volumeId);
-               isp->volSummary->fileName = ToString(name);
+               (void)afs_snprintf(headerName, sizeof headerName, VFORMAT, afs_printable_uint32_lu(isp->volumeId));
+               isp->volSummary->fileName = ToString(headerName);
            }
+           (void)afs_snprintf(path, sizeof path, "%s" OS_DIRSEP "%s", salvinfo->fileSysPath, headerName);
 
-           Log("Header file %s is damaged or no longer valid%s\n", name,
+           Log("Header file %s is damaged or no longer valid%s\n", path,
                (check ? "" : "; repairing"));
            if (check)
                return -1;
 
-           headerFd = afs_open(name, O_RDWR | O_TRUNC, 0644);
-           assert(headerFd != -1);
+           writefunc = VWriteVolumeDiskHeader;
        }
     }
-    if (headerFd) {
+    if (writefunc) {
        memcpy(&isp->volSummary->header, &tempHeader,
               sizeof(struct VolumeHeader));
        if (Testing) {
@@ -1786,24 +2328,25 @@ SalvageVolumeHeaderFile(register struct InodeSummary *isp,
                Log("It would have written a new header file for volume %u\n",
                    isp->volumeId);
        } else {
+           afs_int32 code;
            VolumeHeaderToDisk(&diskHeader, &tempHeader);
-           if (write(headerFd, &diskHeader, sizeof(struct VolumeDiskHeader))
-               != sizeof(struct VolumeDiskHeader)) {
-               Log("Couldn't rewrite volume header file!\n");
-               close(headerFd);
+           code = (*writefunc)(&diskHeader, salvinfo->fileSysPartition);
+           if (code) {
+               Log("Error %ld writing volume header file for volume %lu\n",
+                   afs_printable_int32_ld(code),
+                   afs_printable_uint32_lu(diskHeader.id));
                return -1;
            }
        }
-       close(headerFd);
     }
-    IH_INIT(isp->volSummary->volumeInfoHandle, fileSysDevice, isp->RWvolumeId,
+    IH_INIT(isp->volSummary->volumeInfoHandle, salvinfo->fileSysDevice, isp->RWvolumeId,
            isp->volSummary->header.volumeInfo);
     return 0;
 }
 
 int
-SalvageHeader(register struct stuff *sp, struct InodeSummary *isp, int check,
-             int *deleteMe)
+SalvageHeader(struct SalvInfo *salvinfo, struct afs_inode_info *sp,
+              struct InodeSummary *isp, int check, int *deleteMe)
 {
     union {
        VolumeDiskData volumeInfo;
@@ -1811,7 +2354,7 @@ SalvageHeader(register struct stuff *sp, struct InodeSummary *isp, int check,
     } header;
     IHandle_t *specH;
     int recreate = 0;
-    afs_int32 code;
+    ssize_t nBytes;
     FdHandle_t *fdP;
 
     if (sp->obsolete)
@@ -1830,7 +2373,7 @@ SalvageHeader(register struct stuff *sp, struct InodeSummary *isp, int check,
                (Testing ? "it would have recreated it" : "recreating"));
        if (!Testing) {
            *(sp->inode) =
-               IH_CREATE(NULL, fileSysDevice, fileSysPath, 0, isp->volumeId,
+               IH_CREATE(NULL, salvinfo->fileSysDevice, salvinfo->fileSysPath, 0, isp->volumeId,
                          INODESPECIAL, sp->inodeType, isp->RWvolumeId);
            if (!VALID_INO(*(sp->inode)))
                Abort
@@ -1840,7 +2383,7 @@ SalvageHeader(register struct stuff *sp, struct InodeSummary *isp, int check,
        recreate = 1;
     }
 
-    IH_INIT(specH, fileSysDevice, isp->RWvolumeId, *(sp->inode));
+    IH_INIT(specH, salvinfo->fileSysDevice, isp->RWvolumeId, *(sp->inode));
     fdP = IH_OPEN(specH);
     if (OKToZap && (fdP == NULL) && BadError(errno)) {
        /* bail out early and destroy the volume */
@@ -1856,7 +2399,7 @@ SalvageHeader(register struct stuff *sp, struct InodeSummary *isp, int check,
              sp->description, errno);
 
     if (!recreate
-       && (FDH_READ(fdP, (char *)&header, sp->size) != sp->size
+       && (FDH_PREAD(fdP, (char *)&header, sp->size, 0) != sp->size
            || header.fileHeader.magic != sp->stamp.magic)) {
        if (check) {
            Log("Part of the header (%s) is corrupted\n", sp->description);
@@ -1867,6 +2410,9 @@ SalvageHeader(register struct stuff *sp, struct InodeSummary *isp, int check,
        Log("Part of the header (%s) is corrupted; recreating\n",
            sp->description);
        recreate = 1;
+       /* header can be garbage; make sure we don't read garbage data from
+        * it below */
+       memset(&header, 0, sizeof(header));
     }
     if (sp->inodeType == VI_VOLINFO
        && header.volumeInfo.destroyMe == DESTROY_ME) {
@@ -1881,8 +2427,8 @@ SalvageHeader(register struct stuff *sp, struct InodeSummary *isp, int check,
            Abort
                ("Internal error: recreating volume header (%s) in check mode\n",
                 sp->description);
-       code = FDH_TRUNC(fdP, 0);
-       if (code == -1)
+       nBytes = FDH_TRUNC(fdP, 0);
+       if (nBytes == -1)
            Abort("Unable to truncate volume header file (%s) (error = %d)\n",
                  sp->description, errno);
 
@@ -1904,16 +2450,11 @@ SalvageHeader(register struct stuff *sp, struct InodeSummary *isp, int check,
            header.volumeInfo.needsCallback = 0;
            gettimeofday(&tp, 0);
            header.volumeInfo.creationDate = tp.tv_sec;
-           if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
-               Abort
-                   ("Unable to seek to beginning of volume header file (%s) (errno = %d)\n",
-                    sp->description, errno);
-           }
-           code =
-               FDH_WRITE(fdP, (char *)&header.volumeInfo,
-                         sizeof(header.volumeInfo));
-           if (code != sizeof(header.volumeInfo)) {
-               if (code < 0)
+           nBytes =
+               FDH_PWRITE(fdP, (char *)&header.volumeInfo,
+                          sizeof(header.volumeInfo), 0);
+           if (nBytes != sizeof(header.volumeInfo)) {
+               if (nBytes < 0)
                    Abort
                        ("Unable to write volume header file (%s) (errno = %d)\n",
                         sp->description, errno);
@@ -1921,14 +2462,9 @@ SalvageHeader(register struct stuff *sp, struct InodeSummary *isp, int check,
                      sp->description);
            }
        } else {
-           if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
-               Abort
-                   ("Unable to seek to beginning of volume header file (%s) (errno = %d)\n",
-                    sp->description, errno);
-           }
-           code = FDH_WRITE(fdP, (char *)&sp->stamp, sizeof(sp->stamp));
-           if (code != sizeof(sp->stamp)) {
-               if (code < 0)
+           nBytes = FDH_PWRITE(fdP, (char *)&sp->stamp, sizeof(sp->stamp), 0);
+           if (nBytes != sizeof(sp->stamp)) {
+               if (nBytes < 0)
                    Abort
                        ("Unable to write version stamp in volume header file (%s) (errno = %d)\n",
                         sp->description, errno);
@@ -1941,19 +2477,21 @@ SalvageHeader(register struct stuff *sp, struct InodeSummary *isp, int check,
     FDH_REALLYCLOSE(fdP);
     IH_RELEASE(specH);
     if (sp->inodeType == VI_VOLINFO) {
-       VolInfo = header.volumeInfo;
+       salvinfo->VolInfo = header.volumeInfo;
        if (check) {
            char update[25];
-           if (VolInfo.updateDate) {
-               strcpy(update, TimeStamp(VolInfo.updateDate, 0));
+
+           if (salvinfo->VolInfo.updateDate) {
+               strcpy(update, TimeStamp(salvinfo->VolInfo.updateDate, 0));
                if (!Showmode)
-                   Log("%s (%u) %supdated %s\n", VolInfo.name, VolInfo.id,
+                   Log("%s (%u) %supdated %s\n", salvinfo->VolInfo.name,
+                       salvinfo->VolInfo.id,
                        (Testing ? "it would have been " : ""), update);
            } else {
-               strcpy(update, TimeStamp(VolInfo.creationDate, 0));
+               strcpy(update, TimeStamp(salvinfo->VolInfo.creationDate, 0));
                if (!Showmode)
-                   Log("%s (%u) not updated (created %s)\n", VolInfo.name,
-                       VolInfo.id, update);
+                   Log("%s (%u) not updated (created %s)\n",
+                       salvinfo->VolInfo.name, salvinfo->VolInfo.id, update);
            }
 
        }
@@ -1963,9 +2501,10 @@ SalvageHeader(register struct stuff *sp, struct InodeSummary *isp, int check,
 }
 
 int
-SalvageVnodes(register struct InodeSummary *rwIsp,
-             register struct InodeSummary *thisIsp,
-             register struct ViceInodeInfo *inodes, int check)
+SalvageVnodes(struct SalvInfo *salvinfo,
+              struct InodeSummary *rwIsp,
+             struct InodeSummary *thisIsp,
+             struct ViceInodeInfo *inodes, int check)
 {
     int ilarge, ismall, ioffset, RW, nInodes;
     ioffset = rwIsp->index + rwIsp->nSpecialInodes;    /* first inode */
@@ -1974,47 +2513,46 @@ SalvageVnodes(register struct InodeSummary *rwIsp,
     RW = (rwIsp == thisIsp);
     nInodes = (rwIsp->nInodes - rwIsp->nSpecialInodes);
     ismall =
-       SalvageIndex(thisIsp->volSummary->header.smallVnodeIndex, vSmall, RW,
+       SalvageIndex(salvinfo, thisIsp->volSummary->header.smallVnodeIndex, vSmall, RW,
                     &inodes[ioffset], nInodes, thisIsp->volSummary, check);
     if (check && ismall == -1)
        return -1;
     ilarge =
-       SalvageIndex(thisIsp->volSummary->header.largeVnodeIndex, vLarge, RW,
+       SalvageIndex(salvinfo, thisIsp->volSummary->header.largeVnodeIndex, vLarge, RW,
                     &inodes[ioffset], nInodes, thisIsp->volSummary, check);
     return (ilarge == 0 && ismall == 0 ? 0 : -1);
 }
 
 int
-SalvageIndex(Inode ino, VnodeClass class, int RW,
-            register struct ViceInodeInfo *ip, int nInodes,
-            struct VolumeSummary *volSummary, int check)
+SalvageIndex(struct SalvInfo *salvinfo, Inode ino, VnodeClass class, int RW,
+            struct ViceInodeInfo *ip, int nInodes,
+             struct VolumeSummary *volSummary, int check)
 {
-    VolumeId volumeNumber;
     char buf[SIZEOF_LARGEDISKVNODE];
     struct VnodeDiskObject *vnode = (struct VnodeDiskObject *)buf;
     int err = 0;
     StreamHandle_t *file;
     struct VnodeClassInfo *vcp;
     afs_sfsize_t size;
+    afs_sfsize_t nVnodes;
     afs_fsize_t vnodeLength;
-    int vnodeIndex, nVnodes;
+    int vnodeIndex;
     afs_ino_str_t stmp1, stmp2;
     IHandle_t *handle;
     FdHandle_t *fdP;
 
-    volumeNumber = volSummary->header.id;
-    IH_INIT(handle, fileSysDevice, volSummary->header.parent, ino);
+    IH_INIT(handle, salvinfo->fileSysDevice, volSummary->header.parent, ino);
     fdP = IH_OPEN(handle);
-    assert(fdP != NULL);
+    osi_Assert(fdP != NULL);
     file = FDH_FDOPEN(fdP, "r+");
-    assert(file != NULL);
+    osi_Assert(file != NULL);
     vcp = &VnodeClassInfo[class];
     size = OS_SIZE(fdP->fd_fd);
-    assert(size != -1);
+    osi_Assert(size != -1);
     nVnodes = (size / vcp->diskSize) - 1;
     if (nVnodes > 0) {
-       assert((nVnodes + 1) * vcp->diskSize == size);
-       assert(STREAM_SEEK(file, vcp->diskSize, 0) == 0);
+       osi_Assert((nVnodes + 1) * vcp->diskSize == size);
+       osi_Assert(STREAM_ASEEK(file, vcp->diskSize) == 0);
     } else {
        nVnodes = 0;
     }
@@ -2024,12 +2562,6 @@ SalvageIndex(Inode ino, VnodeClass class, int RW,
        if (vnode->type != vNull) {
            int vnodeChanged = 0;
            int vnodeNumber = bitNumberToVnodeNumber(vnodeIndex, class);
-           /* Log programs that belong to root (potentially suid root);
-            * don't bother for read-only or backup volumes */
-#ifdef notdef                  /* This is done elsewhere */
-           if (ShowRootFiles && RW && vnode->owner == 0 && vnodeNumber != 1)
-               Log("OWNER IS ROOT %s %u dir %u vnode %u author %u owner %u mode %o\n", VolInfo.name, volumeNumber, vnode->parent, vnodeNumber, vnode->author, vnode->owner, vnode->modeBits);
-#endif
            if (VNDISK_GET_INO(vnode) == 0) {
                if (RW) {
                    /* Log("### DEBUG ### Deleted Vnode with 0 inode (vnode %d)\n", vnodeNumber); */
@@ -2039,6 +2571,14 @@ SalvageIndex(Inode ino, VnodeClass class, int RW,
            } else {
                if (vcp->magic != vnode->vnodeMagic) {
                    /* bad magic #, probably partially created vnode */
+                   if (check) {
+                      Log("Partially allocated vnode %d: bad magic (is %lx should be %lx)\n",
+                          vnodeNumber, afs_printable_uint32_lu(vnode->vnodeMagic),
+                          afs_printable_uint32_lu(vcp->magic));
+                      memset(vnode, 0, vcp->diskSize);
+                      err = -1;
+                      goto zooks;
+                   }
                    Log("Partially allocated vnode %d deleted.\n",
                        vnodeNumber);
                    memset(vnode, 0, vcp->diskSize);
@@ -2072,8 +2612,8 @@ SalvageIndex(Inode ino, VnodeClass class, int RW,
                    /* For RW volume, look for vnode with matching inode number;
                     * if no such match, take the first determined by our sort
                     * order */
-                   register struct ViceInodeInfo *lip = ip;
-                   register int lnInodes = nInodes;
+                   struct ViceInodeInfo *lip = ip;
+                   int lnInodes = nInodes;
                    while (lnInodes
                           && lip->u.vnode.vnodeNumber == vnodeNumber) {
                        if (VNDISK_GET_INO(vnode) == lip->inodeNumber) {
@@ -2097,7 +2637,7 @@ SalvageIndex(Inode ino, VnodeClass class, int RW,
                        /*
                         * Because of the possibility of the uniquifier overflows (> 4M)
                         * we compare them modulo the low 22-bits; we shouldn't worry
-                        * about mismatching since they shouldn't to many old 
+                        * about mismatching since they shouldn't to many old
                         * uniquifiers of the same vnode...
                         */
                        if (IUnique(vu) != IUnique(iu)) {
@@ -2186,13 +2726,14 @@ SalvageIndex(Inode ino, VnodeClass class, int RW,
                    ip++;
                    nInodes--;
                } else {        /* no matching inode */
+                   afs_ino_str_t stmp;
                    if (VNDISK_GET_INO(vnode) != 0
                        || vnode->type == vDirectory) {
                        /* No matching inode--get rid of the vnode */
                        if (check) {
                            if (VNDISK_GET_INO(vnode)) {
                                if (!Showmode) {
-                                   Log("Vnode %d (unique %u): corresponding inode %s is missing\n", vnodeNumber, vnode->uniquifier, PrintInode(NULL, VNDISK_GET_INO(vnode)));
+                                   Log("Vnode %d (unique %u): corresponding inode %s is missing\n", vnodeNumber, vnode->uniquifier, PrintInode(stmp, VNDISK_GET_INO(vnode)));
                                }
                            } else {
                                if (!Showmode)
@@ -2204,7 +2745,7 @@ SalvageIndex(Inode ino, VnodeClass class, int RW,
                        if (VNDISK_GET_INO(vnode)) {
                            if (!Showmode) {
                                time_t serverModifyTime = vnode->serverModifyTime;
-                               Log("Vnode %d (unique %u): corresponding inode %s is missing; vnode deleted, vnode mod time=%s", vnodeNumber, vnode->uniquifier, PrintInode(NULL, VNDISK_GET_INO(vnode)), ctime(&serverModifyTime));
+                               Log("Vnode %d (unique %u): corresponding inode %s is missing; vnode deleted, vnode mod time=%s", vnodeNumber, vnode->uniquifier, PrintInode(stmp, VNDISK_GET_INO(vnode)), ctime(&serverModifyTime));
                            }
                        } else {
                            if (!Showmode) {
@@ -2215,7 +2756,7 @@ SalvageIndex(Inode ino, VnodeClass class, int RW,
                        memset(vnode, 0, vcp->diskSize);
                        vnodeChanged = 1;
                    } else {
-                       /* Should not reach here becuase we checked for 
+                       /* Should not reach here becuase we checked for
                         * (inodeNumber == 0) above. And where we zero the vnode,
                         * we also goto vnodeDone.
                         */
@@ -2227,13 +2768,13 @@ SalvageIndex(Inode ino, VnodeClass class, int RW,
                }
            }                   /* VNDISK_GET_INO(vnode) != 0 */
          vnodeDone:
-           assert(!(vnodeChanged && check));
+           osi_Assert(!(vnodeChanged && check));
            if (vnodeChanged && !Testing) {
-               assert(IH_IWRITE
+               osi_Assert(IH_IWRITE
                       (handle, vnodeIndexOffset(vcp, vnodeNumber),
                        (char *)vnode, vcp->diskSize)
                       == vcp->diskSize);
-               VolumeChanged = 1;      /* For break call back */
+               salvinfo->VolumeChanged = 1;    /* For break call back */
            }
        }
     }
@@ -2245,20 +2786,20 @@ SalvageIndex(Inode ino, VnodeClass class, int RW,
 }
 
 struct VnodeEssence *
-CheckVnodeNumber(VnodeId vnodeNumber)
+CheckVnodeNumber(struct SalvInfo *salvinfo, VnodeId vnodeNumber)
 {
     VnodeClass class;
     struct VnodeInfo *vip;
     int offset;
 
     class = vnodeIdToClass(vnodeNumber);
-    vip = &vnodeInfo[class];
+    vip = &salvinfo->vnodeInfo[class];
     offset = vnodeIdToBitNumber(vnodeNumber);
     return (offset >= vip->nVnodes ? NULL : &vip->vnodes[offset]);
 }
 
 void
-CopyOnWrite(register struct DirSummary *dir)
+CopyOnWrite(struct SalvInfo *salvinfo, struct DirSummary *dir)
 {
     /* Copy the directory unconditionally if we are going to change it:
      * not just if was cloned.
@@ -2273,31 +2814,32 @@ CopyOnWrite(register struct DirSummary *dir)
     DFlush();                  /* Well justified paranoia... */
 
     code =
-       IH_IREAD(vnodeInfo[vLarge].handle,
+       IH_IREAD(salvinfo->vnodeInfo[vLarge].handle,
                 vnodeIndexOffset(vcp, dir->vnodeNumber), (char *)&vnode,
                 sizeof(vnode));
-    assert(code == sizeof(vnode));
+    osi_Assert(code == sizeof(vnode));
     oldinode = VNDISK_GET_INO(&vnode);
     /* Increment the version number by a whole lot to avoid problems with
      * clients that were promised new version numbers--but the file server
      * crashed before the versions were written to disk.
      */
     newinode =
-       IH_CREATE(dir->ds_linkH, fileSysDevice, fileSysPath, 0, dir->rwVid,
+       IH_CREATE(dir->ds_linkH, salvinfo->fileSysDevice, salvinfo->fileSysPath, 0, dir->rwVid,
                  dir->vnodeNumber, vnode.uniquifier, vnode.dataVersion +=
                  200);
-    assert(VALID_INO(newinode));
-    assert(CopyInode(fileSysDevice, oldinode, newinode, dir->rwVid) == 0);
+    osi_Assert(VALID_INO(newinode));
+    osi_Assert(CopyInode(salvinfo->fileSysDevice, oldinode, newinode, dir->rwVid) == 0);
     vnode.cloned = 0;
     VNDISK_SET_INO(&vnode, newinode);
     code =
-       IH_IWRITE(vnodeInfo[vLarge].handle,
+       IH_IWRITE(salvinfo->vnodeInfo[vLarge].handle,
                  vnodeIndexOffset(vcp, dir->vnodeNumber), (char *)&vnode,
                  sizeof(vnode));
-    assert(code == sizeof(vnode));
+    osi_Assert(code == sizeof(vnode));
 
     SetSalvageDirHandle(&dir->dirHandle, dir->dirHandle.dirh_handle->ih_vid,
-                       fileSysDevice, newinode);
+                       salvinfo->fileSysDevice, newinode,
+                        &salvinfo->VolumeChanged);
     /* Don't delete the original inode right away, because the directory is
      * still being scanned.
      */
@@ -2305,13 +2847,13 @@ CopyOnWrite(register struct DirSummary *dir)
 }
 
 /*
- * This function should either successfully create a new dir, or give up 
- * and leave things the way they were.  In particular, if it fails to write 
- * the new dir properly, it should return w/o changing the reference to the 
+ * This function should either successfully create a new dir, or give up
+ * and leave things the way they were.  In particular, if it fails to write
+ * the new dir properly, it should return w/o changing the reference to the
  * old dir.
  */
 void
-CopyAndSalvage(register struct DirSummary *dir)
+CopyAndSalvage(struct SalvInfo *salvinfo, struct DirSummary *dir)
 {
     struct VnodeDiskObject vnode;
     struct VnodeClassInfo *vcp = &VnodeClassInfo[vLarge];
@@ -2328,28 +2870,29 @@ CopyAndSalvage(register struct DirSummary *dir)
        return;
     Log("Salvaging directory %u...\n", dir->vnodeNumber);
     lcode =
-       IH_IREAD(vnodeInfo[vLarge].handle,
+       IH_IREAD(salvinfo->vnodeInfo[vLarge].handle,
                 vnodeIndexOffset(vcp, dir->vnodeNumber), (char *)&vnode,
                 sizeof(vnode));
-    assert(lcode == sizeof(vnode));
+    osi_Assert(lcode == sizeof(vnode));
     oldinode = VNDISK_GET_INO(&vnode);
     /* Increment the version number by a whole lot to avoid problems with
      * clients that were promised new version numbers--but the file server
      * crashed before the versions were written to disk.
      */
     newinode =
-       IH_CREATE(dir->ds_linkH, fileSysDevice, fileSysPath, 0, dir->rwVid,
+       IH_CREATE(dir->ds_linkH, salvinfo->fileSysDevice, salvinfo->fileSysPath, 0, dir->rwVid,
                  dir->vnodeNumber, vnode.uniquifier, vnode.dataVersion +=
                  200);
-    assert(VALID_INO(newinode));
-    SetSalvageDirHandle(&newdir, dir->rwVid, fileSysDevice, newinode);
+    osi_Assert(VALID_INO(newinode));
+    SetSalvageDirHandle(&newdir, dir->rwVid, salvinfo->fileSysDevice, newinode,
+                        &salvinfo->VolumeChanged);
 
-    /* Assign . and .. vnode numbers from dir and vnode.parent. 
+    /* Assign . and .. vnode numbers from dir and vnode.parent.
      * The uniquifier for . is in the vnode.
-     * The uniquifier for .. might be set to a bogus value of 1 and 
+     * The uniquifier for .. might be set to a bogus value of 1 and
      * the salvager will later clean it up.
      */
-    if (vnode.parent && (vnodeEssence = CheckVnodeNumber(vnode.parent))) {
+    if (vnode.parent && (vnodeEssence = CheckVnodeNumber(salvinfo, vnode.parent))) {
        parentUnique = (vnodeEssence->unique ? vnodeEssence->unique : 1);
     }
     code =
@@ -2366,75 +2909,86 @@ CopyAndSalvage(register struct DirSummary *dir)
        if (code) {
            Log("also failed to decrement link count on new inode");
        }
-       assert(1 == 2);
+       osi_Assert(1 == 2);
     }
     Log("Checking the results of the directory salvage...\n");
     if (!DirOK(&newdir)) {
        Log("Directory salvage failed!!!; restoring old version of the directory.\n");
        code = IH_DEC(dir->ds_linkH, newinode, dir->rwVid);
-       assert(code == 0);
-       assert(1 == 2);
+       osi_Assert(code == 0);
+       osi_Assert(1 == 2);
     }
     vnode.cloned = 0;
     VNDISK_SET_INO(&vnode, newinode);
     length = Length(&newdir);
     VNDISK_SET_LEN(&vnode, length);
     lcode =
-       IH_IWRITE(vnodeInfo[vLarge].handle,
+       IH_IWRITE(salvinfo->vnodeInfo[vLarge].handle,
                  vnodeIndexOffset(vcp, dir->vnodeNumber), (char *)&vnode,
                  sizeof(vnode));
-    assert(lcode == sizeof(vnode));
+    osi_Assert(lcode == sizeof(vnode));
 #if 0
 #ifdef AFS_NT40_ENV
-    nt_sync(fileSysDevice);
+    nt_sync(salvinfo->fileSysDevice);
 #else
     sync();                    /* this is slow, but hopefully rarely called.  We don't have
                                 * an open FD on the file itself to fsync.
                                 */
 #endif
 #else
-    vnodeInfo[vLarge].handle->ih_synced = 1;
+    salvinfo->vnodeInfo[vLarge].handle->ih_synced = 1;
 #endif
     /* make sure old directory file is really closed */
     fdP = IH_OPEN(dir->dirHandle.dirh_handle);
     FDH_REALLYCLOSE(fdP);
-    
+
     code = IH_DEC(dir->ds_linkH, oldinode, dir->rwVid);
-    assert(code == 0);
+    osi_Assert(code == 0);
     dir->dirHandle = newdir;
 }
 
+/**
+ * arguments for JudgeEntry.
+ */
+struct judgeEntry_params {
+    struct DirSummary *dir;    /**< directory we're examining entries in */
+    struct SalvInfo *salvinfo; /**< SalvInfo for the current salvage job */
+};
+
 int
-JudgeEntry(struct DirSummary *dir, char *name, VnodeId vnodeNumber,
-          Unique unique)
+JudgeEntry(void *arock, char *name, afs_int32 vnodeNumber,
+          afs_int32 unique)
 {
+    struct judgeEntry_params *params = arock;
+    struct DirSummary *dir = params->dir;
+    struct SalvInfo *salvinfo = params->salvinfo;
     struct VnodeEssence *vnodeEssence;
     afs_int32 dirOrphaned, todelete;
 
-    dirOrphaned = IsVnodeOrphaned(dir->vnodeNumber);
+    dirOrphaned = IsVnodeOrphaned(salvinfo, dir->vnodeNumber);
 
-    vnodeEssence = CheckVnodeNumber(vnodeNumber);
+    vnodeEssence = CheckVnodeNumber(salvinfo, vnodeNumber);
     if (vnodeEssence == NULL) {
        if (!Showmode) {
-           Log("dir vnode %u: invalid entry deleted: %s/%s (vnode %u, unique %u)\n", dir->vnodeNumber, dir->name ? dir->name : "??", name, vnodeNumber, unique);
+           Log("dir vnode %u: invalid entry deleted: %s" OS_DIRSEP "%s (vnode %u, unique %u)\n", dir->vnodeNumber, dir->name ? dir->name : "??", name, vnodeNumber, unique);
        }
        if (!Testing) {
-           CopyOnWrite(dir);
-           assert(Delete(&dir->dirHandle, name) == 0);
+           CopyOnWrite(salvinfo, dir);
+           osi_Assert(Delete(&dir->dirHandle, name) == 0);
        }
        return 0;
     }
 #ifdef AFS_AIX_ENV
 #ifndef AFS_NAMEI_ENV
-    /* On AIX machines, don't allow entries to point to inode 0. That is a special 
+    /* On AIX machines, don't allow entries to point to inode 0. That is a special
      * mount inode for the partition. If this inode were deleted, it would crash
      * the machine.
      */
     if (vnodeEssence->InodeNumber == 0) {
-       Log("dir vnode %d: invalid entry: %s/%s has no inode (vnode %d, unique %d)%s\n", dir->vnodeNumber, (dir->name ? dir->name : "??"), name, vnodeNumber, unique, (Testing ? "-- would have deleted" : " -- deleted"));
+       Log("dir vnode %d: invalid entry: %s" OS_DIRSEP "%s has no inode (vnode %d, unique %d)%s\n", dir->vnodeNumber, (dir->name ? dir->name : "??"), name, vnodeNumber, unique, (Testing ? "-- would have deleted" : " -- deleted"));
        if (!Testing) {
-           CopyOnWrite(dir);
-           assert(Delete(&dir->dirHandle, name) == 0);
+           CopyOnWrite(salvinfo, dir);
+           osi_Assert(Delete(&dir->dirHandle, name) == 0);
        }
        return 0;
     }
@@ -2444,15 +2998,15 @@ JudgeEntry(struct DirSummary *dir, char *name, VnodeId vnodeNumber,
     if (!(vnodeNumber & 1) && !Showmode
        && !(vnodeEssence->count || vnodeEssence->unique
             || vnodeEssence->modeBits)) {
-       Log("dir vnode %u: invalid entry: %s/%s (vnode %u, unique %u)%s\n",
+       Log("dir vnode %u: invalid entry: %s" OS_DIRSEP "%s (vnode %u, unique %u)%s\n",
            dir->vnodeNumber, (dir->name ? dir->name : "??"), name,
            vnodeNumber, unique,
            ((!unique) ? (Testing ? "-- would have deleted" : " -- deleted") :
             ""));
        if (!unique) {
            if (!Testing) {
-               CopyOnWrite(dir);
-               assert(Delete(&dir->dirHandle, name) == 0);
+               CopyOnWrite(salvinfo, dir);
+               osi_Assert(Delete(&dir->dirHandle, name) == 0);
            }
            return 0;
        }
@@ -2466,7 +3020,7 @@ JudgeEntry(struct DirSummary *dir, char *name, VnodeId vnodeNumber,
        if (!vnodeEssence->unique
            && ((strcmp(name, "..") == 0) || (strcmp(name, ".") == 0))) {
            /* This is an orphaned directory. Don't delete the . or ..
-            * entry. Otherwise, it will get created in the next 
+            * entry. Otherwise, it will get created in the next
             * salvage and deleted again here. So Just skip it.
             */
            return 0;
@@ -2475,16 +3029,16 @@ JudgeEntry(struct DirSummary *dir, char *name, VnodeId vnodeNumber,
        todelete = ((!vnodeEssence->unique || dirOrphaned) ? 1 : 0);
 
        if (!Showmode) {
-           Log("dir vnode %u: %s/%s (vnode %u): unique changed from %u to %u %s\n", dir->vnodeNumber, (dir->name ? dir->name : "??"), name, vnodeNumber, unique, vnodeEssence->unique, (!todelete ? "" : (Testing ? "-- would have deleted" : "-- deleted")));
+           Log("dir vnode %u: %s" OS_DIRSEP "%s (vnode %u): unique changed from %u to %u %s\n", dir->vnodeNumber, (dir->name ? dir->name : "??"), name, vnodeNumber, unique, vnodeEssence->unique, (!todelete ? "" : (Testing ? "-- would have deleted" : "-- deleted")));
        }
        if (!Testing) {
-           ViceFid fid;
+           AFSFid fid;
            fid.Vnode = vnodeNumber;
            fid.Unique = vnodeEssence->unique;
-           CopyOnWrite(dir);
-           assert(Delete(&dir->dirHandle, name) == 0);
+           CopyOnWrite(salvinfo, dir);
+           osi_Assert(Delete(&dir->dirHandle, name) == 0);
            if (!todelete)
-               assert(Create(&dir->dirHandle, name, &fid) == 0);
+               osi_Assert(Create(&dir->dirHandle, name, &fid) == 0);
        }
        if (todelete)
            return 0;           /* no need to continue */
@@ -2492,29 +3046,29 @@ JudgeEntry(struct DirSummary *dir, char *name, VnodeId vnodeNumber,
 
     if (strcmp(name, ".") == 0) {
        if (dir->vnodeNumber != vnodeNumber || (dir->unique != unique)) {
-           ViceFid fid;
+           AFSFid fid;
            if (!Showmode)
                Log("directory vnode %u.%u: bad '.' entry (was %u.%u); fixed\n", dir->vnodeNumber, dir->unique, vnodeNumber, unique);
            if (!Testing) {
-               CopyOnWrite(dir);
-               assert(Delete(&dir->dirHandle, ".") == 0);
+               CopyOnWrite(salvinfo, dir);
+               osi_Assert(Delete(&dir->dirHandle, ".") == 0);
                fid.Vnode = dir->vnodeNumber;
                fid.Unique = dir->unique;
-               assert(Create(&dir->dirHandle, ".", &fid) == 0);
+               osi_Assert(Create(&dir->dirHandle, ".", &fid) == 0);
            }
 
            vnodeNumber = fid.Vnode;    /* Get the new Essence */
            unique = fid.Unique;
-           vnodeEssence = CheckVnodeNumber(vnodeNumber);
+           vnodeEssence = CheckVnodeNumber(salvinfo, vnodeNumber);
        }
        dir->haveDot = 1;
     } else if (strcmp(name, "..") == 0) {
-       ViceFid pa;
+       AFSFid pa;
        if (dir->parent) {
            struct VnodeEssence *dotdot;
            pa.Vnode = dir->parent;
-           dotdot = CheckVnodeNumber(pa.Vnode);
-           assert(dotdot != NULL);     /* XXX Should not be assert */
+           dotdot = CheckVnodeNumber(salvinfo, pa.Vnode);
+           osi_Assert(dotdot != NULL); /* XXX Should not be assert */
            pa.Unique = dotdot->unique;
        } else {
            pa.Vnode = dir->vnodeNumber;
@@ -2524,14 +3078,14 @@ JudgeEntry(struct DirSummary *dir, char *name, VnodeId vnodeNumber,
            if (!Showmode)
                Log("directory vnode %u.%u: bad '..' entry (was %u.%u); fixed\n", dir->vnodeNumber, dir->unique, vnodeNumber, unique);
            if (!Testing) {
-               CopyOnWrite(dir);
-               assert(Delete(&dir->dirHandle, "..") == 0);
-               assert(Create(&dir->dirHandle, "..", &pa) == 0);
+               CopyOnWrite(salvinfo, dir);
+               osi_Assert(Delete(&dir->dirHandle, "..") == 0);
+               osi_Assert(Create(&dir->dirHandle, "..", &pa) == 0);
            }
 
            vnodeNumber = pa.Vnode;     /* Get the new Essence */
            unique = pa.Unique;
-           vnodeEssence = CheckVnodeNumber(vnodeNumber);
+           vnodeEssence = CheckVnodeNumber(salvinfo, vnodeNumber);
        }
        dir->haveDotDot = 1;
     } else if (strncmp(name, ".__afs", 6) == 0) {
@@ -2539,23 +3093,24 @@ JudgeEntry(struct DirSummary *dir, char *name, VnodeId vnodeNumber,
            Log("dir vnode %u: special old unlink-while-referenced file %s %s deleted (vnode %u)\n", dir->vnodeNumber, name, (Testing ? "would have been" : "is"), vnodeNumber);
        }
        if (!Testing) {
-           CopyOnWrite(dir);
-           assert(Delete(&dir->dirHandle, name) == 0);
+           CopyOnWrite(salvinfo, dir);
+           osi_Assert(Delete(&dir->dirHandle, name) == 0);
        }
        vnodeEssence->claimed = 0;      /* Not claimed: Orphaned */
        vnodeEssence->todelete = 1;     /* Will later delete vnode and decr inode */
        return 0;
     } else {
        if (ShowSuid && (vnodeEssence->modeBits & 06000))
-           Log("FOUND suid/sgid file: %s/%s (%u.%u %05o) author %u (vnode %u dir %u)\n", dir->name ? dir->name : "??", name, vnodeEssence->owner, vnodeEssence->group, vnodeEssence->modeBits, vnodeEssence->author, vnodeNumber, dir->vnodeNumber);
+           Log("FOUND suid/sgid file: %s" OS_DIRSEP "%s (%u.%u %05o) author %u (vnode %u dir %u)\n", dir->name ? dir->name : "??", name, vnodeEssence->owner, vnodeEssence->group, vnodeEssence->modeBits, vnodeEssence->author, vnodeNumber, dir->vnodeNumber);
        if (/* ShowMounts && */ (vnodeEssence->type == vSymlink)
            && !(vnodeEssence->modeBits & 0111)) {
-           int code, size;
+           afs_sfsize_t nBytes;
+           afs_sfsize_t size;
            char buf[1025];
            IHandle_t *ihP;
            FdHandle_t *fdP;
 
-           IH_INIT(ihP, fileSysDevice, dir->dirHandle.dirh_handle->ih_vid,
+           IH_INIT(ihP, salvinfo->fileSysDevice, dir->dirHandle.dirh_handle->ih_vid,
                    vnodeEssence->InodeNumber);
            fdP = IH_OPEN(ihP);
            if (fdP == NULL) {
@@ -2565,35 +3120,35 @@ JudgeEntry(struct DirSummary *dir, char *name, VnodeId vnodeNumber,
            }
            size = FDH_SIZE(fdP);
            if (size < 0) {
-               Log("ERROR %s mount point has invalid size %d, vnode %u\n", dir->vname, size, vnodeNumber);
+               Log("ERROR %s mount point has invalid size %d, vnode %u\n", dir->vname, (int)size, vnodeNumber);
                FDH_REALLYCLOSE(fdP);
                IH_RELEASE(ihP);
                return 0;
            }
-       
+
            if (size > 1024)
                size = 1024;
-           code = FDH_READ(fdP, buf, size);
-           if (code == size) {
+           nBytes = FDH_PREAD(fdP, buf, size, 0);
+           if (nBytes == size) {
                buf[size] = '\0';
                if ( (*buf != '#' && *buf != '%') || buf[strlen(buf)-1] != '.' ) {
-                   Log("Volume %u (%s) mount point %s/%s to '%s' invalid, %s to symbolic link\n",
+                   Log("Volume %u (%s) mount point %s" OS_DIRSEP "%s to '%s' invalid, %s to symbolic link\n",
                        dir->dirHandle.dirh_handle->ih_vid, dir->vname, dir->name ? dir->name : "??", name, buf,
                        Testing ? "would convert" : "converted");
                    vnodeEssence->modeBits |= 0111;
                    vnodeEssence->changed = 1;
-               } else if (ShowMounts) Log("In volume %u (%s) found mountpoint %s/%s to '%s'\n",
+               } else if (ShowMounts) Log("In volume %u (%s) found mountpoint %s" OS_DIRSEP "%s to '%s'\n",
                    dir->dirHandle.dirh_handle->ih_vid, dir->vname,
                    dir->name ? dir->name : "??", name, buf);
            } else {
                Log("Volume %s cound not read mount point vnode %u size %d code %d\n",
-                   dir->vname, vnodeNumber, size, code);
+                   dir->vname, vnodeNumber, (int)size, (int)nBytes);
            }
            FDH_REALLYCLOSE(fdP);
            IH_RELEASE(ihP);
        }
        if (ShowRootFiles && vnodeEssence->owner == 0 && vnodeNumber != 1)
-           Log("FOUND root file: %s/%s (%u.%u %05o) author %u (vnode %u dir %u)\n", dir->name ? dir->name : "??", name, vnodeEssence->owner, vnodeEssence->group, vnodeEssence->modeBits, vnodeEssence->author, vnodeNumber, dir->vnodeNumber);
+           Log("FOUND root file: %s" OS_DIRSEP "%s (%u.%u %05o) author %u (vnode %u dir %u)\n", dir->name ? dir->name : "??", name, vnodeEssence->owner, vnodeEssence->group, vnodeEssence->modeBits, vnodeEssence->author, vnodeNumber, dir->vnodeNumber);
        if (vnodeIdToClass(vnodeNumber) == vLarge
            && vnodeEssence->name == NULL) {
            char *n;
@@ -2603,8 +3158,8 @@ JudgeEntry(struct DirSummary *dir, char *name, VnodeId vnodeNumber,
        }
 
        /* The directory entry points to the vnode. Check to see if the
-        * vnode points back to the directory. If not, then let the 
-        * directory claim it (else it might end up orphaned). Vnodes 
+        * vnode points back to the directory. If not, then let the
+        * directory claim it (else it might end up orphaned). Vnodes
         * already claimed by another directory are deleted from this
         * directory: hardlinks to the same vnode are not allowed
         * from different directories.
@@ -2616,7 +3171,7 @@ JudgeEntry(struct DirSummary *dir, char *name, VnodeId vnodeNumber,
                 * another non-orphaned dir).
                 */
                if (!Showmode) {
-                   Log("dir vnode %u: %s/%s (vnode %u, unique %u) -- parent vnode %schanged from %u to %u\n", dir->vnodeNumber, (dir->name ? dir->name : "??"), name, vnodeNumber, unique, (Testing ? "would have been " : ""), vnodeEssence->parent, dir->vnodeNumber);
+                   Log("dir vnode %u: %s" OS_DIRSEP "%s (vnode %u, unique %u) -- parent vnode %schanged from %u to %u\n", dir->vnodeNumber, (dir->name ? dir->name : "??"), name, vnodeNumber, unique, (Testing ? "would have been " : ""), vnodeEssence->parent, dir->vnodeNumber);
                }
                vnodeEssence->parent = dir->vnodeNumber;
                vnodeEssence->changed = 1;
@@ -2624,16 +3179,16 @@ JudgeEntry(struct DirSummary *dir, char *name, VnodeId vnodeNumber,
                /* Vnode was claimed by another directory */
                if (!Showmode) {
                    if (dirOrphaned) {
-                       Log("dir vnode %u: %s/%s parent vnode is %u (vnode %u, unique %u) -- %sdeleted\n", dir->vnodeNumber, (dir->name ? dir->name : "??"), name, vnodeEssence->parent, vnodeNumber, unique, (Testing ? "would have been " : ""));
+                       Log("dir vnode %u: %s" OS_DIRSEP "%s parent vnode is %u (vnode %u, unique %u) -- %sdeleted\n", dir->vnodeNumber, (dir->name ? dir->name : "??"), name, vnodeEssence->parent, vnodeNumber, unique, (Testing ? "would have been " : ""));
                    } else if (vnodeNumber == 1) {
-                       Log("dir vnode %d: %s/%s is invalid (vnode %d, unique %d) -- %sdeleted\n", dir->vnodeNumber, (dir->name ? dir->name : "??"), name, vnodeNumber, unique, (Testing ? "would have been " : ""));
+                       Log("dir vnode %d: %s" OS_DIRSEP "%s is invalid (vnode %d, unique %d) -- %sdeleted\n", dir->vnodeNumber, (dir->name ? dir->name : "??"), name, vnodeNumber, unique, (Testing ? "would have been " : ""));
                    } else {
-                       Log("dir vnode %u: %s/%s already claimed by directory vnode %u (vnode %u, unique %u) -- %sdeleted\n", dir->vnodeNumber, (dir->name ? dir->name : "??"), name, vnodeEssence->parent, vnodeNumber, unique, (Testing ? "would have been " : ""));
+                       Log("dir vnode %u: %s" OS_DIRSEP "%s already claimed by directory vnode %u (vnode %u, unique %u) -- %sdeleted\n", dir->vnodeNumber, (dir->name ? dir->name : "??"), name, vnodeEssence->parent, vnodeNumber, unique, (Testing ? "would have been " : ""));
                    }
                }
                if (!Testing) {
-                   CopyOnWrite(dir);
-                   assert(Delete(&dir->dirHandle, name) == 0);
+                   CopyOnWrite(salvinfo, dir);
+                   osi_Assert(Delete(&dir->dirHandle, name) == 0);
                }
                return 0;
            }
@@ -2646,9 +3201,10 @@ JudgeEntry(struct DirSummary *dir, char *name, VnodeId vnodeNumber,
 }
 
 void
-DistilVnodeEssence(VolumeId rwVId, VnodeClass class, Inode ino, Unique * maxu)
+DistilVnodeEssence(struct SalvInfo *salvinfo, VolumeId rwVId,
+                   VnodeClass class, Inode ino, Unique * maxu)
 {
-    register struct VnodeInfo *vip = &vnodeInfo[class];
+    struct VnodeInfo *vip = &salvinfo->vnodeInfo[class];
     struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
     char buf[SIZEOF_LARGEDISKVNODE];
     struct VnodeDiskObject *vnode = (struct VnodeDiskObject *)buf;
@@ -2658,21 +3214,21 @@ DistilVnodeEssence(VolumeId rwVId, VnodeClass class, Inode ino, Unique * maxu)
     int nVnodes;
     FdHandle_t *fdP;
 
-    IH_INIT(vip->handle, fileSysDevice, rwVId, ino);
+    IH_INIT(vip->handle, salvinfo->fileSysDevice, rwVId, ino);
     fdP = IH_OPEN(vip->handle);
-    assert(fdP != NULL);
+    osi_Assert(fdP != NULL);
     file = FDH_FDOPEN(fdP, "r+");
-    assert(file != NULL);
+    osi_Assert(file != NULL);
     size = OS_SIZE(fdP->fd_fd);
-    assert(size != -1);
+    osi_Assert(size != -1);
     vip->nVnodes = (size / vcp->diskSize) - 1;
     if (vip->nVnodes > 0) {
-       assert((vip->nVnodes + 1) * vcp->diskSize == size);
-       assert(STREAM_SEEK(file, vcp->diskSize, 0) == 0);
-       assert((vip->vnodes = (struct VnodeEssence *)
+       osi_Assert((vip->nVnodes + 1) * vcp->diskSize == size);
+       osi_Assert(STREAM_ASEEK(file, vcp->diskSize) == 0);
+       osi_Assert((vip->vnodes = (struct VnodeEssence *)
                calloc(vip->nVnodes, sizeof(struct VnodeEssence))) != NULL);
        if (class == vLarge) {
-           assert((vip->inodes = (Inode *)
+           osi_Assert((vip->inodes = (Inode *)
                    calloc(vip->nVnodes, sizeof(Inode))) != NULL);
        } else {
            vip->inodes = NULL;
@@ -2687,7 +3243,7 @@ DistilVnodeEssence(VolumeId rwVId, VnodeClass class, Inode ino, Unique * maxu)
         nVnodes && STREAM_READ(vnode, vcp->diskSize, 1, file) == 1;
         nVnodes--, vnodeIndex++) {
        if (vnode->type != vNull) {
-           register struct VnodeEssence *vep = &vip->vnodes[vnodeIndex];
+           struct VnodeEssence *vep = &vip->vnodes[vnodeIndex];
            afs_fsize_t vnodeLength;
            vip->nAllocatedVnodes++;
            vep->count = vnode->linkCount;
@@ -2705,8 +3261,16 @@ DistilVnodeEssence(VolumeId rwVId, VnodeClass class, Inode ino, Unique * maxu)
            vep->owner = vnode->owner;
            vep->group = vnode->group;
            if (vnode->type == vDirectory) {
-               assert(class == vLarge);
-               vip->inodes[vnodeIndex] = VNDISK_GET_INO(vnode);
+               if (class != vLarge) {
+                   VnodeId vnodeNumber = bitNumberToVnodeNumber(vnodeIndex, class);
+                   vip->nAllocatedVnodes--;
+                   memset(vnode, 0, sizeof(vnode));
+                   IH_IWRITE(salvinfo->vnodeInfo[vSmall].handle,
+                             vnodeIndexOffset(vcp, vnodeNumber),
+                             (char *)&vnode, sizeof(vnode));
+                   salvinfo->VolumeChanged = 1;
+               } else
+                   vip->inodes[vnodeIndex] = VNDISK_GET_INO(vnode);
            }
        }
     }
@@ -2715,7 +3279,8 @@ DistilVnodeEssence(VolumeId rwVId, VnodeClass class, Inode ino, Unique * maxu)
 }
 
 static char *
-GetDirName(VnodeId vnode, struct VnodeEssence *vp, char *path)
+GetDirName(struct SalvInfo *salvinfo, VnodeId vnode, struct VnodeEssence *vp,
+           char *path)
 {
     struct VnodeEssence *parentvp;
 
@@ -2723,9 +3288,9 @@ GetDirName(VnodeId vnode, struct VnodeEssence *vp, char *path)
        strcpy(path, ".");
        return path;
     }
-    if (vp->parent && vp->name && (parentvp = CheckVnodeNumber(vp->parent))
-       && GetDirName(vp->parent, parentvp, path)) {
-       strcat(path, "/");
+    if (vp->parent && vp->name && (parentvp = CheckVnodeNumber(salvinfo, vp->parent))
+       && GetDirName(salvinfo, vp->parent, parentvp, path)) {
+       strcat(path, OS_DIRSEP);
        strcat(path, vp->name);
        return path;
     }
@@ -2736,7 +3301,7 @@ GetDirName(VnodeId vnode, struct VnodeEssence *vp, char *path)
  * vnodes must be "claimed". The vep->claimed flag is set in JudgeEntry().
  */
 static int
-IsVnodeOrphaned(VnodeId vnode)
+IsVnodeOrphaned(struct SalvInfo *salvinfo, VnodeId vnode)
 {
     struct VnodeEssence *vep;
 
@@ -2744,17 +3309,17 @@ IsVnodeOrphaned(VnodeId vnode)
        return (1);             /* Vnode zero does not exist */
     if (vnode == 1)
        return (0);             /* The root dir vnode is always claimed */
-    vep = CheckVnodeNumber(vnode);     /* Get the vnode essence */
+    vep = CheckVnodeNumber(salvinfo, vnode);   /* Get the vnode essence */
     if (!vep || !vep->claimed)
        return (1);             /* Vnode is not claimed - it is orphaned */
 
-    return (IsVnodeOrphaned(vep->parent));
+    return (IsVnodeOrphaned(salvinfo, vep->parent));
 }
 
 void
-SalvageDir(char *name, VolumeId rwVid, struct VnodeInfo *dirVnodeInfo,
-          IHandle_t * alinkH, int i, struct DirSummary *rootdir,
-          int *rootdirfound)
+SalvageDir(struct SalvInfo *salvinfo, char *name, VolumeId rwVid,
+          struct VnodeInfo *dirVnodeInfo, IHandle_t * alinkH, int i,
+          struct DirSummary *rootdir, int *rootdirfound)
 {
     static struct DirSummary dir;
     static struct DirHandle dirHandle;
@@ -2779,9 +3344,9 @@ SalvageDir(char *name, VolumeId rwVid, struct VnodeInfo *dirVnodeInfo,
            dirVnodeInfo->vnodes[i].changed = 1;
        }
     } else {
-       parent = CheckVnodeNumber(dirVnodeInfo->vnodes[i].parent);
+       parent = CheckVnodeNumber(salvinfo, dirVnodeInfo->vnodes[i].parent);
        if (parent && parent->salvaged == 0)
-           SalvageDir(name, rwVid, dirVnodeInfo, alinkH,
+           SalvageDir(salvinfo, name, rwVid, dirVnodeInfo, alinkH,
                       vnodeIdToBitNumber(dirVnodeInfo->vnodes[i].parent),
                       rootdir, rootdirfound);
     }
@@ -2793,8 +3358,8 @@ SalvageDir(char *name, VolumeId rwVid, struct VnodeInfo *dirVnodeInfo,
     dir.parent = dirVnodeInfo->vnodes[i].parent;
     dir.haveDot = dir.haveDotDot = 0;
     dir.ds_linkH = alinkH;
-    SetSalvageDirHandle(&dir.dirHandle, dir.rwVid, fileSysDevice,
-                       dirVnodeInfo->inodes[i]);
+    SetSalvageDirHandle(&dir.dirHandle, dir.rwVid, salvinfo->fileSysDevice,
+                       dirVnodeInfo->inodes[i], &salvinfo->VolumeChanged);
 
     dirok = ((RebuildDirs && !Testing) ? 0 : DirOK(&dir.dirHandle));
     if (!dirok) {
@@ -2803,21 +3368,26 @@ SalvageDir(char *name, VolumeId rwVid, struct VnodeInfo *dirVnodeInfo,
                (Testing ? "skipping" : "salvaging"));
        }
        if (!Testing) {
-           CopyAndSalvage(&dir);
+           CopyAndSalvage(salvinfo, &dir);
            dirok = 1;
+           dirVnodeInfo->inodes[i] = dir.dirHandle.dirh_inode;
        }
     }
     dirHandle = dir.dirHandle;
 
     dir.name =
-       GetDirName(bitNumberToVnodeNumber(i, vLarge),
+       GetDirName(salvinfo, bitNumberToVnodeNumber(i, vLarge),
                   &dirVnodeInfo->vnodes[i], path);
 
     if (dirok) {
        /* If enumeration failed for random reasons, we will probably delete
         * too much stuff, so we guard against this instead.
         */
-       assert(EnumerateDir(&dirHandle, JudgeEntry, &dir) == 0);
+       struct judgeEntry_params judge_params;
+       judge_params.salvinfo = salvinfo;
+       judge_params.dir = &dir;
+
+       osi_Assert(EnumerateDir(&dirHandle, JudgeEntry, &judge_params) == 0);
     }
 
     /* Delete the old directory if it was copied in order to salvage.
@@ -2828,7 +3398,7 @@ SalvageDir(char *name, VolumeId rwVid, struct VnodeInfo *dirVnodeInfo,
     DFlush();
     if (dir.copied && !Testing) {
        code = IH_DEC(dir.ds_linkH, dirHandle.dirh_handle->ih_ino, rwVid);
-       assert(code == 0);
+       osi_Assert(code == 0);
        dirVnodeInfo->inodes[i] = dir.dirHandle.dirh_inode;
     }
 
@@ -2841,13 +3411,397 @@ SalvageDir(char *name, VolumeId rwVid, struct VnodeInfo *dirVnodeInfo,
     return;
 }
 
+/**
+ * Get a new FID that can be used to create a new file.
+ *
+ * @param[in] volHeader vol header for the volume
+ * @param[in] class     what type of vnode we'll be creating (vLarge or vSmall)
+ * @param[out] afid     the FID that we can use (only Vnode and Unique are set)
+ * @param[inout] maxunique  max uniquifier for all vnodes in the volume;
+ *                          updated to the new max unique if we create a new
+ *                          vnode
+ */
+static void
+GetNewFID(struct SalvInfo *salvinfo, VolumeDiskData *volHeader,
+          VnodeClass class, AFSFid *afid, Unique *maxunique)
+{
+    int i;
+    for (i = 0; i < salvinfo->vnodeInfo[class].nVnodes; i++) {
+       if (salvinfo->vnodeInfo[class].vnodes[i].type == vNull) {
+           break;
+       }
+    }
+    if (i == salvinfo->vnodeInfo[class].nVnodes) {
+       /* no free vnodes; make a new one */
+       salvinfo->vnodeInfo[class].nVnodes++;
+       salvinfo->vnodeInfo[class].vnodes =
+           realloc(salvinfo->vnodeInfo[class].vnodes,
+                   sizeof(struct VnodeEssence) * (i+1));
+
+       salvinfo->vnodeInfo[class].vnodes[i].type = vNull;
+    }
+
+    afid->Vnode = bitNumberToVnodeNumber(i, class);
+
+    if (volHeader->uniquifier < (*maxunique + 1)) {
+       /* header uniq is bad; it will get bumped by 2000 later */
+       afid->Unique = *maxunique + 1 + 2000;
+       (*maxunique)++;
+    } else {
+       /* header uniq seems okay; just use that */
+       afid->Unique = *maxunique = volHeader->uniquifier++;
+    }
+}
+
+/**
+ * Create a vnode for a README file explaining not to use a recreated-root vol.
+ *
+ * @param[in] volHeader vol header for the volume
+ * @param[in] alinkH    ihandle for i/o for the volume
+ * @param[in] vid       volume id
+ * @param[inout] maxunique  max uniquifier for all vnodes in the volume;
+ *                          updated to the new max unique if we create a new
+ *                          vnode
+ * @param[out] afid     FID for the new readme vnode
+ * @param[out] ainode   the inode for the new readme file
+ *
+ * @return operation status
+ *  @retval 0 success
+ *  @retval -1 error
+ */
+static int
+CreateReadme(struct SalvInfo *salvinfo, VolumeDiskData *volHeader,
+             IHandle_t *alinkH, VolumeId vid, Unique *maxunique, AFSFid *afid,
+             Inode *ainode)
+{
+    Inode readmeinode;
+    struct VnodeDiskObject *rvnode = NULL;
+    afs_sfsize_t bytes;
+    IHandle_t *readmeH = NULL;
+    struct VnodeEssence *vep;
+    afs_fsize_t length;
+    time_t now = time(NULL);
+
+    /* Try to make the note brief, but informative. Only administrators should
+     * be able to read this file at first, so we can hopefully assume they
+     * know what AFS is, what a volume is, etc. */
+    char readme[] =
+"This volume has been salvaged, but has lost its original root directory.\n"
+"The root directory that exists now has been recreated from orphan files\n"
+"from the rest of the volume. This recreated root directory may interfere\n"
+"with old cached data on clients, and there is no way the salvager can\n"
+"reasonably prevent that. So, it is recommended that you do not continue to\n"
+"use this volume, but only copy the salvaged data to a new volume.\n"
+"Continuing to use this volume as it exists now may cause some clients to\n"
+"behave oddly when accessing this volume.\n"
+"\n\t -- Your friendly neighborhood OpenAFS salvager\n";
+    /* ^ the person reading this probably just lost some data, so they could
+     * use some cheering up. */
+
+    /* -1 for the trailing NUL */
+    length = sizeof(readme) - 1;
+
+    GetNewFID(salvinfo, volHeader, vSmall, afid, maxunique);
+
+    vep = &salvinfo->vnodeInfo[vSmall].vnodes[vnodeIdToBitNumber(afid->Vnode)];
+
+    /* create the inode and write the contents */
+    readmeinode = IH_CREATE(alinkH, salvinfo->fileSysDevice,
+                            salvinfo->fileSysPath, 0, vid,
+                            afid->Vnode, afid->Unique, 1);
+    if (!VALID_INO(readmeinode)) {
+       Log("CreateReadme: readme IH_CREATE failed\n");
+       goto error;
+    }
+
+    IH_INIT(readmeH, salvinfo->fileSysDevice, vid, readmeinode);
+    bytes = IH_IWRITE(readmeH, 0, readme, length);
+    IH_RELEASE(readmeH);
+
+    if (bytes != length) {
+       Log("CreateReadme: IWRITE failed (%d/%d)\n", (int)bytes,
+           (int)sizeof(readme));
+       goto error;
+    }
+
+    /* create the vnode and write it out */
+    rvnode = calloc(1, SIZEOF_SMALLDISKVNODE);
+    if (!rvnode) {
+       Log("CreateRootDir: error alloc'ing memory\n");
+       goto error;
+    }
+
+    rvnode->type = vFile;
+    rvnode->cloned = 0;
+    rvnode->modeBits = 0777;
+    rvnode->linkCount = 1;
+    VNDISK_SET_LEN(rvnode, length);
+    rvnode->uniquifier = afid->Unique;
+    rvnode->dataVersion = 1;
+    VNDISK_SET_INO(rvnode, readmeinode);
+    rvnode->unixModifyTime = rvnode->serverModifyTime = now;
+    rvnode->author = 0;
+    rvnode->owner = 0;
+    rvnode->parent = 1;
+    rvnode->group = 0;
+    rvnode->vnodeMagic = VnodeClassInfo[vSmall].magic;
+
+    bytes = IH_IWRITE(salvinfo->vnodeInfo[vSmall].handle,
+                      vnodeIndexOffset(&VnodeClassInfo[vSmall], afid->Vnode),
+                      (char*)rvnode, SIZEOF_SMALLDISKVNODE);
+
+    if (bytes != SIZEOF_SMALLDISKVNODE) {
+       Log("CreateReadme: IH_IWRITE failed (%d/%d)\n", (int)bytes,
+           (int)SIZEOF_SMALLDISKVNODE);
+       goto error;
+    }
+
+    /* update VnodeEssence for new readme vnode */
+    salvinfo->vnodeInfo[vSmall].nAllocatedVnodes++;
+    vep->count = 0;
+    vep->blockCount = nBlocks(length);
+    salvinfo->vnodeInfo[vSmall].volumeBlockCount += vep->blockCount;
+    vep->parent = rvnode->parent;
+    vep->unique = rvnode->uniquifier;
+    vep->modeBits = rvnode->modeBits;
+    vep->InodeNumber = VNDISK_GET_INO(rvnode);
+    vep->type = rvnode->type;
+    vep->author = rvnode->author;
+    vep->owner = rvnode->owner;
+    vep->group = rvnode->group;
+
+    free(rvnode);
+    rvnode = NULL;
+
+    vep->claimed = 1;
+    vep->changed = 0;
+    vep->salvaged = 1;
+    vep->todelete = 0;
+
+    *ainode = readmeinode;
+
+    return 0;
+
+ error:
+    if (IH_DEC(alinkH, readmeinode, vid)) {
+       Log("CreateReadme (recovery): IH_DEC failed\n");
+    }
+
+    if (rvnode) {
+       free(rvnode);
+       rvnode = NULL;
+    }
+
+    return -1;
+}
+
+/**
+ * create a root dir for a volume that lacks one.
+ *
+ * @param[in] volHeader vol header for the volume
+ * @param[in] alinkH    ihandle for disk access for this volume group
+ * @param[in] vid       volume id we're dealing with
+ * @param[out] rootdir  populated with info about the new root dir
+ * @param[inout] maxunique  max uniquifier for all vnodes in the volume;
+ *                          updated to the new max unique if we create a new
+ *                          vnode
+ *
+ * @return operation status
+ *  @retval 0  success
+ *  @retval -1 error
+ */
+static int
+CreateRootDir(struct SalvInfo *salvinfo, VolumeDiskData *volHeader,
+              IHandle_t *alinkH, VolumeId vid, struct DirSummary *rootdir,
+              Unique *maxunique)
+{
+    FileVersion dv;
+    int decroot = 0, decreadme = 0;
+    AFSFid did, readmeid;
+    afs_fsize_t length;
+    Inode rootinode;
+    struct VnodeDiskObject *rootvnode = NULL;
+    struct acl_accessList *ACL;
+    Inode *ip;
+    afs_sfsize_t bytes;
+    struct VnodeEssence *vep;
+    Inode readmeinode;
+    time_t now = time(NULL);
+
+    if (!salvinfo->vnodeInfo[vLarge].vnodes && !salvinfo->vnodeInfo[vSmall].vnodes) {
+       Log("Not creating new root dir; volume appears to lack any vnodes\n");
+       goto error;
+    }
+
+    if (!salvinfo->vnodeInfo[vLarge].vnodes) {
+       /* We don't have any large vnodes in the volume; allocate room
+        * for one so we can recreate the root dir */
+       salvinfo->vnodeInfo[vLarge].nVnodes = 1;
+       salvinfo->vnodeInfo[vLarge].vnodes = calloc(1, sizeof(struct VnodeEssence));
+       salvinfo->vnodeInfo[vLarge].inodes = calloc(1, sizeof(Inode));
+
+       osi_Assert(salvinfo->vnodeInfo[vLarge].vnodes);
+       osi_Assert(salvinfo->vnodeInfo[vLarge].inodes);
+    }
+
+    vep = &salvinfo->vnodeInfo[vLarge].vnodes[vnodeIdToBitNumber(1)];
+    ip = &salvinfo->vnodeInfo[vLarge].inodes[vnodeIdToBitNumber(1)];
+    if (vep->type != vNull) {
+       Log("Not creating new root dir; existing vnode 1 is non-null\n");
+       goto error;
+    }
+
+    if (CreateReadme(salvinfo, volHeader, alinkH, vid, maxunique, &readmeid,
+                     &readmeinode) != 0) {
+       goto error;
+    }
+    decreadme = 1;
+
+    /* set the DV to a very high number, so it is unlikely that we collide
+     * with a cached DV */
+    dv = 1 << 30;
+
+    rootinode = IH_CREATE(alinkH, salvinfo->fileSysDevice, salvinfo->fileSysPath,
+                          0, vid, 1, 1, dv);
+    if (!VALID_INO(rootinode)) {
+       Log("CreateRootDir: IH_CREATE failed\n");
+       goto error;
+    }
+    decroot = 1;
+
+    SetSalvageDirHandle(&rootdir->dirHandle, vid, salvinfo->fileSysDevice,
+                        rootinode, &salvinfo->VolumeChanged);
+    did.Volume = vid;
+    did.Vnode = 1;
+    did.Unique = 1;
+    if (MakeDir(&rootdir->dirHandle, (afs_int32*)&did, (afs_int32*)&did)) {
+       Log("CreateRootDir: MakeDir failed\n");
+       goto error;
+    }
+    if (Create(&rootdir->dirHandle, "README.ROOTDIR", &readmeid)) {
+       Log("CreateRootDir: Create failed\n");
+       goto error;
+    }
+    DFlush();
+    length = Length(&rootdir->dirHandle);
+    DZap((void *)&rootdir->dirHandle);
+
+    /* create the new root dir vnode */
+    rootvnode = calloc(1, SIZEOF_LARGEDISKVNODE);
+    if (!rootvnode) {
+       Log("CreateRootDir: malloc failed\n");
+       goto error;
+    }
+
+    /* only give 'rl' permissions to 'system:administrators'. We do this to
+     * try to catch the attention of an administrator, that they should not
+     * be writing to this directory or continue to use it. */
+    ACL = VVnodeDiskACL(rootvnode);
+    ACL->size = sizeof(struct acl_accessList);
+    ACL->version = ACL_ACLVERSION;
+    ACL->total = 1;
+    ACL->positive = 1;
+    ACL->negative = 0;
+    ACL->entries[0].id = -204; /* system:administrators */
+    ACL->entries[0].rights = PRSFS_READ | PRSFS_LOOKUP;
+
+    rootvnode->type = vDirectory;
+    rootvnode->cloned = 0;
+    rootvnode->modeBits = 0777;
+    rootvnode->linkCount = 2;
+    VNDISK_SET_LEN(rootvnode, length);
+    rootvnode->uniquifier = 1;
+    rootvnode->dataVersion = dv;
+    VNDISK_SET_INO(rootvnode, rootinode);
+    rootvnode->unixModifyTime = rootvnode->serverModifyTime = now;
+    rootvnode->author = 0;
+    rootvnode->owner = 0;
+    rootvnode->parent = 0;
+    rootvnode->group = 0;
+    rootvnode->vnodeMagic = VnodeClassInfo[vLarge].magic;
+
+    /* write it out to disk */
+    bytes = IH_IWRITE(salvinfo->vnodeInfo[vLarge].handle,
+             vnodeIndexOffset(&VnodeClassInfo[vLarge], 1),
+             (char*)rootvnode, SIZEOF_LARGEDISKVNODE);
+
+    if (bytes != SIZEOF_LARGEDISKVNODE) {
+       /* just cast to int and don't worry about printing real 64-bit ints;
+        * a large disk vnode isn't anywhere near the 32-bit limit */
+       Log("CreateRootDir: IH_IWRITE failed (%d/%d)\n", (int)bytes,
+           (int)SIZEOF_LARGEDISKVNODE);
+       goto error;
+    }
+
+    /* update VnodeEssence for the new root vnode */
+    salvinfo->vnodeInfo[vLarge].nAllocatedVnodes++;
+    vep->count = 0;
+    vep->blockCount = nBlocks(length);
+    salvinfo->vnodeInfo[vLarge].volumeBlockCount += vep->blockCount;
+    vep->parent = rootvnode->parent;
+    vep->unique = rootvnode->uniquifier;
+    vep->modeBits = rootvnode->modeBits;
+    vep->InodeNumber = VNDISK_GET_INO(rootvnode);
+    vep->type = rootvnode->type;
+    vep->author = rootvnode->author;
+    vep->owner = rootvnode->owner;
+    vep->group = rootvnode->group;
+
+    free(rootvnode);
+    rootvnode = NULL;
+
+    vep->claimed = 0;
+    vep->changed = 0;
+    vep->salvaged = 1;
+    vep->todelete = 0;
+
+    /* update DirSummary for the new root vnode */
+    rootdir->vnodeNumber = 1;
+    rootdir->unique = 1;
+    rootdir->haveDot = 1;
+    rootdir->haveDotDot = 1;
+    rootdir->rwVid = vid;
+    rootdir->copied = 0;
+    rootdir->parent = 0;
+    rootdir->name = strdup(".");
+    rootdir->vname = volHeader->name;
+    rootdir->ds_linkH = alinkH;
+
+    *ip = rootinode;
+
+    return 0;
+
+ error:
+    if (decroot && IH_DEC(alinkH, rootinode, vid)) {
+       Log("CreateRootDir (recovery): IH_DEC (root) failed\n");
+    }
+    if (decreadme && IH_DEC(alinkH, readmeinode, vid)) {
+       Log("CreateRootDir (recovery): IH_DEC (readme) failed\n");
+    }
+    if (rootvnode) {
+       free(rootvnode);
+       rootvnode = NULL;
+    }
+    return -1;
+}
+
+/**
+ * salvage a volume group.
+ *
+ * @param[in] salvinfo information for the curent salvage job
+ * @param[in] rwIsp    inode summary for rw volume
+ * @param[in] alinkH   link table inode handle
+ *
+ * @return operation status
+ *   @retval 0 success
+ */
 int
-SalvageVolume(register struct InodeSummary *rwIsp, IHandle_t * alinkH)
+SalvageVolume(struct SalvInfo *salvinfo, struct InodeSummary *rwIsp, IHandle_t * alinkH)
 {
     /* This routine, for now, will only be called for read-write volumes */
     int i, j, code;
     int BlocksInVolume = 0, FilesInVolume = 0;
-    register VnodeClass class;
+    VnodeClass class;
     struct DirSummary rootdir, oldrootdir;
     struct VnodeInfo *dirVnodeInfo;
     struct VnodeDiskObject vnode;
@@ -2860,31 +3814,32 @@ SalvageVolume(register struct InodeSummary *rwIsp, IHandle_t * alinkH)
     afs_int32 v, pv;
     IHandle_t *h;
     afs_sfsize_t nBytes;
-    ViceFid pa;
+    AFSFid pa;
     VnodeId LFVnode, ThisVnode;
     Unique LFUnique, ThisUnique;
     char npath[128];
+    int newrootdir = 0;
 
     vid = rwIsp->volSummary->header.id;
-    IH_INIT(h, fileSysDevice, vid, rwIsp->volSummary->header.volumeInfo);
+    IH_INIT(h, salvinfo->fileSysDevice, vid, rwIsp->volSummary->header.volumeInfo);
     nBytes = IH_IREAD(h, 0, (char *)&volHeader, sizeof(volHeader));
-    assert(nBytes == sizeof(volHeader));
-    assert(volHeader.stamp.magic == VOLUMEINFOMAGIC);
-    assert(volHeader.destroyMe != DESTROY_ME);
+    osi_Assert(nBytes == sizeof(volHeader));
+    osi_Assert(volHeader.stamp.magic == VOLUMEINFOMAGIC);
+    osi_Assert(volHeader.destroyMe != DESTROY_ME);
     /* (should not have gotten this far with DESTROY_ME flag still set!) */
 
-    DistilVnodeEssence(vid, vLarge, rwIsp->volSummary->header.largeVnodeIndex,
-                      &maxunique);
-    DistilVnodeEssence(vid, vSmall, rwIsp->volSummary->header.smallVnodeIndex,
-                      &maxunique);
+    DistilVnodeEssence(salvinfo, vid, vLarge,
+                       rwIsp->volSummary->header.largeVnodeIndex, &maxunique);
+    DistilVnodeEssence(salvinfo, vid, vSmall,
+                       rwIsp->volSummary->header.smallVnodeIndex, &maxunique);
 
-    dirVnodeInfo = &vnodeInfo[vLarge];
+    dirVnodeInfo = &salvinfo->vnodeInfo[vLarge];
     for (i = 0; i < dirVnodeInfo->nVnodes; i++) {
-       SalvageDir(volHeader.name, vid, dirVnodeInfo, alinkH, i, &rootdir,
-                  &rootdirfound);
+       SalvageDir(salvinfo, volHeader.name, vid, dirVnodeInfo, alinkH, i,
+                  &rootdir, &rootdirfound);
     }
 #ifdef AFS_NT40_ENV
-    nt_sync(fileSysDevice);
+    nt_sync(salvinfo->fileSysDevice);
 #else
     sync();                            /* This used to be done lower level, for every dir */
 #endif
@@ -2893,13 +3848,27 @@ SalvageVolume(register struct InodeSummary *rwIsp, IHandle_t * alinkH)
        return 0;
     }
 
+    if (!rootdirfound && (orphans == ORPH_ATTACH) && !Testing) {
+
+       Log("Cannot find root directory for volume %lu; attempting to create "
+           "a new one\n", afs_printable_uint32_lu(vid));
+
+       code = CreateRootDir(salvinfo, &volHeader, alinkH, vid, &rootdir,
+                            &maxunique);
+       if (code == 0) {
+           rootdirfound = 1;
+           newrootdir = 1;
+           salvinfo->VolumeChanged = 1;
+       }
+    }
+
     /* Parse each vnode looking for orphaned vnodes and
      * connect them to the tree as orphaned (if requested).
      */
     oldrootdir = rootdir;
     for (class = 0; class < nVNODECLASSES; class++) {
-       for (v = 0; v < vnodeInfo[class].nVnodes; v++) {
-           vep = &(vnodeInfo[class].vnodes[v]);
+       for (v = 0; v < salvinfo->vnodeInfo[class].nVnodes; v++) {
+           vep = &(salvinfo->vnodeInfo[class].vnodes[v]);
            ThisVnode = bitNumberToVnodeNumber(v, class);
            ThisUnique = vep->unique;
 
@@ -2914,8 +3883,20 @@ SalvageVolume(register struct InodeSummary *rwIsp, IHandle_t * alinkH)
             */
            if (class == vLarge) {      /* directory vnode */
                pv = vnodeIdToBitNumber(vep->parent);
-               if (vnodeInfo[vLarge].vnodes[pv].unique != 0)
-                   vnodeInfo[vLarge].vnodes[pv].count++;
+               if (salvinfo->vnodeInfo[vLarge].vnodes[pv].unique != 0) {
+                   if (vep->parent == 1 && newrootdir) {
+                       /* this vnode's parent was the volume root, and
+                        * we just created the volume root. So, the parent
+                        * dir didn't exist during JudgeEntry, so the link
+                        * count was not inc'd there, so don't dec it here.
+                        */
+
+                        /* noop */
+
+                   } else {
+                       salvinfo->vnodeInfo[vLarge].vnodes[pv].count++;
+                   }
+               }
            }
 
            if (!rootdirfound)
@@ -2928,7 +3909,7 @@ SalvageVolume(register struct InodeSummary *rwIsp, IHandle_t * alinkH)
                LFVnode = rootdir.vnodeNumber;  /* Lost+Found vnode number */
                LFUnique = rootdir.unique;      /* Lost+Found uniquifier */
 
-               /* Update this orphaned vnode's info. Its parent info and 
+               /* Update this orphaned vnode's info. Its parent info and
                 * link count (do for orphaned directories and files).
                 */
                vep->parent = LFVnode;  /* Parent is the root dir */
@@ -2937,29 +3918,30 @@ SalvageVolume(register struct InodeSummary *rwIsp, IHandle_t * alinkH)
                vep->claimed = 1;
                vep->count--;   /* Inc link count (root dir will pt to it) */
 
-               /* If this orphaned vnode is a directory, change '..'. 
+               /* If this orphaned vnode is a directory, change '..'.
                 * The name of the orphaned dir/file is unknown, so we
                 * build a unique name. No need to CopyOnWrite the directory
                 * since it is not connected to tree in BK or RO volume and
                 * won't be visible there.
                 */
                if (class == vLarge) {
-                   ViceFid pa;
+                   AFSFid pa;
                    DirHandle dh;
 
                    /* Remove and recreate the ".." entry in this orphaned directory */
-                   SetSalvageDirHandle(&dh, vid, fileSysDevice,
-                                       vnodeInfo[class].inodes[v]);
+                   SetSalvageDirHandle(&dh, vid, salvinfo->fileSysDevice,
+                                       salvinfo->vnodeInfo[class].inodes[v],
+                                       &salvinfo->VolumeChanged);
                    pa.Vnode = LFVnode;
                    pa.Unique = LFUnique;
-                   assert(Delete(&dh, "..") == 0);
-                   assert(Create(&dh, "..", &pa) == 0);
+                   osi_Assert(Delete(&dh, "..") == 0);
+                   osi_Assert(Create(&dh, "..", &pa) == 0);
 
                    /* The original parent's link count was decremented above.
                     * Here we increment the new parent's link count.
                     */
                    pv = vnodeIdToBitNumber(LFVnode);
-                   vnodeInfo[vLarge].vnodes[pv].count--;
+                   salvinfo->vnodeInfo[vLarge].vnodes[pv].count--;
 
                }
 
@@ -2976,14 +3958,14 @@ SalvageVolume(register struct InodeSummary *rwIsp, IHandle_t * alinkH)
                                        "__ORPHANFILE__"), ThisVnode,
                                       ThisUnique);
 
-                   CopyOnWrite(&rootdir);
+                   CopyOnWrite(salvinfo, &rootdir);
                    code = Create(&rootdir.dirHandle, npath, &pa);
                    if (!code)
                        break;
 
                    ThisUnique += 50;   /* Try creating a different file */
                }
-               assert(code == 0);
+               osi_Assert(code == 0);
                Log("Attaching orphaned %s to volume's root dir as %s\n",
                    ((class == vLarge) ? "directory" : "file"), npath);
            }
@@ -2992,11 +3974,11 @@ SalvageVolume(register struct InodeSummary *rwIsp, IHandle_t * alinkH)
 
     /* Delete the old rootinode directory if the rootdir was CopyOnWrite */
     DFlush();
-    if (!oldrootdir.copied && rootdir.copied) {
+    if (rootdirfound && !oldrootdir.copied && rootdir.copied) {
        code =
            IH_DEC(oldrootdir.ds_linkH, oldrootdir.dirHandle.dirh_inode,
                   oldrootdir.rwVid);
-       assert(code == 0);
+       osi_Assert(code == 0);
        /* dirVnodeInfo->inodes[?] is not updated with new inode number */
     }
 
@@ -3010,43 +3992,42 @@ SalvageVolume(register struct InodeSummary *rwIsp, IHandle_t * alinkH)
      * will get removed here also (if requested).
      */
     for (class = 0; class < nVNODECLASSES; class++) {
-       int nVnodes = vnodeInfo[class].nVnodes;
+       afs_sfsize_t nVnodes = salvinfo->vnodeInfo[class].nVnodes;
        struct VnodeClassInfo *vcp = &VnodeClassInfo[class];
-       struct VnodeEssence *vnodes = vnodeInfo[class].vnodes;
-       FilesInVolume += vnodeInfo[class].nAllocatedVnodes;
-       BlocksInVolume += vnodeInfo[class].volumeBlockCount;
+       struct VnodeEssence *vnodes = salvinfo->vnodeInfo[class].vnodes;
+       FilesInVolume += salvinfo->vnodeInfo[class].nAllocatedVnodes;
+       BlocksInVolume += salvinfo->vnodeInfo[class].volumeBlockCount;
        for (i = 0; i < nVnodes; i++) {
-           register struct VnodeEssence *vnp = &vnodes[i];
+           struct VnodeEssence *vnp = &vnodes[i];
            VnodeId vnodeNumber = bitNumberToVnodeNumber(i, class);
 
            /* If the vnode is good but is unclaimed (not listed in
             * any directory entries), then it is orphaned.
             */
            orphaned = -1;
-           if ((vnp->type != 0) && (orphaned = IsVnodeOrphaned(vnodeNumber))) {
+           if ((vnp->type != 0) && (orphaned = IsVnodeOrphaned(salvinfo, vnodeNumber))) {
                vnp->claimed = 0;       /* Makes IsVnodeOrphaned calls faster */
                vnp->changed = 1;
            }
 
            if (vnp->changed || vnp->count) {
                int oldCount;
-               int code;
                nBytes =
-                   IH_IREAD(vnodeInfo[class].handle,
+                   IH_IREAD(salvinfo->vnodeInfo[class].handle,
                             vnodeIndexOffset(vcp, vnodeNumber),
                             (char *)&vnode, sizeof(vnode));
-               assert(nBytes == sizeof(vnode));
+               osi_Assert(nBytes == sizeof(vnode));
 
                vnode.parent = vnp->parent;
                oldCount = vnode.linkCount;
                vnode.linkCount = vnode.linkCount - vnp->count;
 
                if (orphaned == -1)
-                   orphaned = IsVnodeOrphaned(vnodeNumber);
+                   orphaned = IsVnodeOrphaned(salvinfo, vnodeNumber);
                if (orphaned) {
                    if (!vnp->todelete) {
                        /* Orphans should have already been attached (if requested) */
-                       assert(orphans != ORPH_ATTACH);
+                       osi_Assert(orphans != ORPH_ATTACH);
                        oblocks += vnp->blockCount;
                        ofiles++;
                    }
@@ -3057,7 +4038,7 @@ SalvageVolume(register struct InodeSummary *rwIsp, IHandle_t * alinkH)
                        if (VNDISK_GET_INO(&vnode)) {
                            code =
                                IH_DEC(alinkH, VNDISK_GET_INO(&vnode), vid);
-                           assert(code == 0);
+                           osi_Assert(code == 0);
                        }
                        memset(&vnode, 0, sizeof(vnode));
                    }
@@ -3072,12 +4053,12 @@ SalvageVolume(register struct InodeSummary *rwIsp, IHandle_t * alinkH)
                vnode.dataVersion++;
                if (!Testing) {
                    nBytes =
-                       IH_IWRITE(vnodeInfo[class].handle,
+                       IH_IWRITE(salvinfo->vnodeInfo[class].handle,
                                  vnodeIndexOffset(vcp, vnodeNumber),
                                  (char *)&vnode, sizeof(vnode));
-                   assert(nBytes == sizeof(vnode));
+                   osi_Assert(nBytes == sizeof(vnode));
                }
-               VolumeChanged = 1;
+               salvinfo->VolumeChanged = 1;
            }
        }
     }
@@ -3089,7 +4070,7 @@ SalvageVolume(register struct InodeSummary *rwIsp, IHandle_t * alinkH)
     }
 
     for (class = 0; class < nVNODECLASSES; class++) {
-       register struct VnodeInfo *vip = &vnodeInfo[class];
+       struct VnodeInfo *vip = &salvinfo->vnodeInfo[class];
        for (i = 0; i < vip->nVnodes; i++)
            if (vip->vnodes[i].name)
                free(vip->vnodes[i].name);
@@ -3113,24 +4094,48 @@ SalvageVolume(register struct InodeSummary *rwIsp, IHandle_t * alinkH)
        volHeader.uniquifier = (maxunique + 1 + 2000);
     }
 
+    if (newrootdir) {
+       Log("*** WARNING: Root directory recreated, but volume is fragile! "
+           "Only use this salvaged volume to copy data to another volume; "
+           "do not continue to use this volume (%lu) as-is.\n",
+           afs_printable_uint32_lu(vid));
+    }
+
+#ifdef FSSYNC_BUILD_CLIENT
+    if (!Testing && salvinfo->VolumeChanged && salvinfo->useFSYNC) {
+       afs_int32 fsync_code;
+
+       fsync_code = FSYNC_VolOp(vid, NULL, FSYNC_VOL_BREAKCBKS, FSYNC_SALVAGE, NULL);
+       if (fsync_code) {
+           Log("Error trying to tell the fileserver to break callbacks for "
+               "changed volume %lu; error code %ld\n",
+               afs_printable_uint32_lu(vid),
+               afs_printable_int32_ld(fsync_code));
+       } else {
+           salvinfo->VolumeChanged = 0;
+       }
+    }
+#endif /* FSSYNC_BUILD_CLIENT */
+
     /* Turn off the inUse bit; the volume's been salvaged! */
     volHeader.inUse = 0;       /* clear flag indicating inUse@last crash */
     volHeader.needsSalvaged = 0;       /* clear 'damaged' flag */
     volHeader.inService = 1;   /* allow service again */
-    volHeader.needsCallback = (VolumeChanged != 0);
+    volHeader.needsCallback = (salvinfo->VolumeChanged != 0);
     volHeader.dontSalvage = DONT_SALVAGE;
-    VolumeChanged = 0;
+    salvinfo->VolumeChanged = 0;
     if (!Testing) {
        nBytes = IH_IWRITE(h, 0, (char *)&volHeader, sizeof(volHeader));
-       assert(nBytes == sizeof(volHeader));
+       osi_Assert(nBytes == sizeof(volHeader));
     }
     if (!Showmode) {
        Log("%sSalvaged %s (%u): %d files, %d blocks\n",
            (Testing ? "It would have " : ""), volHeader.name, volHeader.id,
            FilesInVolume, BlocksInVolume);
     }
-    IH_RELEASE(vnodeInfo[vSmall].handle);
-    IH_RELEASE(vnodeInfo[vLarge].handle);
+
+    IH_RELEASE(salvinfo->vnodeInfo[vSmall].handle);
+    IH_RELEASE(salvinfo->vnodeInfo[vLarge].handle);
     IH_RELEASE(h);
     return 0;
 }
@@ -3144,15 +4149,15 @@ ClearROInUseBit(struct VolumeSummary *summary)
     VolumeDiskData volHeader;
 
     nBytes = IH_IREAD(h, 0, (char *)&volHeader, sizeof(volHeader));
-    assert(nBytes == sizeof(volHeader));
-    assert(volHeader.stamp.magic == VOLUMEINFOMAGIC);
+    osi_Assert(nBytes == sizeof(volHeader));
+    osi_Assert(volHeader.stamp.magic == VOLUMEINFOMAGIC);
     volHeader.inUse = 0;
     volHeader.needsSalvaged = 0;
     volHeader.inService = 1;
     volHeader.dontSalvage = DONT_SALVAGE;
     if (!Testing) {
        nBytes = IH_IWRITE(h, 0, (char *)&volHeader, sizeof(volHeader));
-       assert(nBytes == sizeof(volHeader));
+       osi_Assert(nBytes == sizeof(volHeader));
     }
 }
 
@@ -3162,8 +4167,8 @@ ClearROInUseBit(struct VolumeSummary *summary)
  * deleteMe - Always do so, only a partial volume.
  */
 void
-MaybeZapVolume(register struct InodeSummary *isp, char *message, int deleteMe,
-              int check)
+MaybeZapVolume(struct SalvInfo *salvinfo, struct InodeSummary *isp,
+               char *message, int deleteMe, int check)
 {
     if (readOnly(isp) || deleteMe) {
        if (isp->volSummary && isp->volSummary->fileName) {
@@ -3178,8 +4183,25 @@ MaybeZapVolume(register struct InodeSummary *isp, char *message, int deleteMe,
                if (!Showmode)
                    Log("it will be deleted instead.  It should be recloned.\n");
            }
-           if (!Testing)
-               unlink(isp->volSummary->fileName);
+           if (!Testing) {
+               afs_int32 code;
+               char path[64];
+               sprintf(path, "%s" OS_DIRSEP "%s", salvinfo->fileSysPath, isp->volSummary->fileName);
+
+               code = VDestroyVolumeDiskHeader(salvinfo->fileSysPartition, isp->volumeId, isp->RWvolumeId);
+               if (code) {
+                   Log("Error %ld destroying volume disk header for volume %lu\n",
+                       afs_printable_int32_ld(code),
+                       afs_printable_uint32_lu(isp->volumeId));
+               }
+
+               /* make sure we actually delete the fileName file; ENOENT
+                * is fine, since VDestroyVolumeDiskHeader probably already
+                * unlinked it */
+               if (unlink(path) && errno != ENOENT) {
+                   Log("Unable to unlink %s (errno = %d)\n", path, errno);
+               }
+           }
        }
     } else if (!check) {
        Log("%s salvage was unsuccessful: read-write volume %u\n", message,
@@ -3188,14 +4210,105 @@ MaybeZapVolume(register struct InodeSummary *isp, char *message, int deleteMe,
     }
 }
 
+#ifdef AFS_DEMAND_ATTACH_FS
+/**
+ * Locks a volume on disk for salvaging.
+ *
+ * @param[in] volumeId   volume ID to lock
+ *
+ * @return operation status
+ *  @retval 0  success
+ *  @retval -1 volume lock raced with a fileserver restart; all volumes must
+ *             checked out and locked again
+ *
+ * @note DAFS only
+ */
+static int
+LockVolume(struct SalvInfo *salvinfo, VolumeId volumeId)
+{
+    afs_int32 code;
+    int locktype;
+
+    /* should always be WRITE_LOCK, but keep the lock-type logic all
+     * in one place, in VVolLockType. Params will be ignored, but
+     * try to provide what we're logically doing. */
+    locktype = VVolLockType(V_VOLUPD, 1);
+
+    code = VLockVolumeByIdNB(volumeId, salvinfo->fileSysPartition, locktype);
+    if (code) {
+       if (code == EBUSY) {
+           Abort("Someone else appears to be using volume %lu; Aborted\n",
+                 afs_printable_uint32_lu(volumeId));
+       }
+       Abort("Error %ld trying to lock volume %lu; Aborted\n",
+             afs_printable_int32_ld(code),
+             afs_printable_uint32_lu(volumeId));
+    }
+
+    code = FSYNC_VerifyCheckout(volumeId, salvinfo->fileSysPathName, FSYNC_VOL_OFF, FSYNC_SALVAGE);
+    if (code == SYNC_DENIED) {
+       /* need to retry checking out volumes */
+       return -1;
+    }
+    if (code != SYNC_OK) {
+       Abort("FSYNC_VerifyCheckout failed for volume %lu with code %ld\n",
+             afs_printable_uint32_lu(volumeId), afs_printable_int32_ld(code));
+    }
+
+    /* set inUse = programType in the volume header to ensure that nobody
+     * tries to use this volume again without salvaging, if we somehow crash
+     * or otherwise exit before finishing the salvage.
+     */
+    if (!Testing) {
+       IHandle_t *h;
+       struct VolumeHeader header;
+       struct VolumeDiskHeader diskHeader;
+       struct VolumeDiskData volHeader;
+
+       code = VReadVolumeDiskHeader(volumeId, salvinfo->fileSysPartition, &diskHeader);
+       if (code) {
+           return 0;
+       }
+
+       DiskToVolumeHeader(&header, &diskHeader);
+
+       IH_INIT(h, salvinfo->fileSysDevice, header.parent, header.volumeInfo);
+       if (IH_IREAD(h, 0, (char*)&volHeader, sizeof(volHeader)) != sizeof(volHeader) ||
+           volHeader.stamp.magic != VOLUMEINFOMAGIC) {
+
+           IH_RELEASE(h);
+           return 0;
+       }
+
+       volHeader.inUse = programType;
+
+       /* If we can't re-write the header, bail out and error. We don't
+        * assert when reading the header, since it's possible the
+        * header isn't really there (when there's no data associated
+        * with the volume; we just delete the vol header file in that
+        * case). But if it's there enough that we can read it, but
+        * somehow we cannot write to it to signify we're salvaging it,
+        * we've got a big problem and we cannot continue. */
+       osi_Assert(IH_IWRITE(h, 0, (char*)&volHeader, sizeof(volHeader)) == sizeof(volHeader));
+
+       IH_RELEASE(h);
+    }
+
+    return 0;
+}
+#endif /* AFS_DEMAND_ATTACH_FS */
 
 void
-AskOffline(VolumeId volumeId, char * partition)
+AskOffline(struct SalvInfo *salvinfo, VolumeId volumeId)
 {
     afs_int32 code, i;
+    SYNC_response res;
+
+    memset(&res, 0, sizeof(res));
 
     for (i = 0; i < 3; i++) {
-       code = FSYNC_VolOp(volumeId, partition, FSYNC_VOL_OFF, FSYNC_SALVAGE, NULL);
+       code = FSYNC_VolOp(volumeId, salvinfo->fileSysPartition->name,
+                          FSYNC_VOL_OFF, FSYNC_SALVAGE, &res);
 
        if (code == SYNC_OK) {
            break;
@@ -3229,17 +4342,18 @@ AskOffline(VolumeId volumeId, char * partition)
 }
 
 void
-AskOnline(VolumeId volumeId, char *partition)
+AskOnline(struct SalvInfo *salvinfo, VolumeId volumeId)
 {
     afs_int32 code, i;
 
     for (i = 0; i < 3; i++) {
-       code = FSYNC_VolOp(volumeId, partition, FSYNC_VOL_ON, FSYNC_WHATEVER, NULL);
+       code = FSYNC_VolOp(volumeId, salvinfo->fileSysPartition->name,
+                          FSYNC_VOL_ON, FSYNC_WHATEVER, NULL);
 
        if (code == SYNC_OK) {
            break;
        } else if (code == SYNC_DENIED) {
-           Log("AskOnline:  file server denied online request to volume %u partition %s; trying again...\n", volumeId, partition);
+           Log("AskOnline:  file server denied online request to volume %u partition %s; trying again...\n", volumeId, salvinfo->fileSysPartition->name);
        } else if (code == SYNC_BAD_COMMAND) {
            Log("AskOnline:  fssync protocol mismatch (bad command word '%d')\n",
                FSYNC_VOL_ON);
@@ -3251,7 +4365,7 @@ AskOnline(VolumeId volumeId, char *partition)
            break;
        } else if (i < 2) {
            /* try it again */
-           Log("AskOnline:  request for fileserver to take volume offline failed; trying again...\n");
+           Log("AskOnline:  request for fileserver to put volume online failed; trying again...\n");
            FSYNC_clientFinis();
            FSYNC_clientInit();
        }
@@ -3267,17 +4381,19 @@ CopyInode(Device device, Inode inode1, Inode inode2, int rwvolume)
     char buf[4096];
     IHandle_t *srcH, *destH;
     FdHandle_t *srcFdP, *destFdP;
-    register int n = 0;
+    ssize_t nBytes = 0;
+    afs_foff_t size = 0;
 
     IH_INIT(srcH, device, rwvolume, inode1);
     srcFdP = IH_OPEN(srcH);
-    assert(srcFdP != NULL);
+    osi_Assert(srcFdP != NULL);
     IH_INIT(destH, device, rwvolume, inode2);
     destFdP = IH_OPEN(destH);
-    assert(n != -1);
-    while ((n = FDH_READ(srcFdP, buf, sizeof(buf))) > 0)
-       assert(FDH_WRITE(destFdP, buf, n) == n);
-    assert(n == 0);
+    while ((nBytes = FDH_PREAD(srcFdP, buf, sizeof(buf), size)) > 0) {
+       osi_Assert(FDH_PWRITE(destFdP, buf, nBytes, size) == nBytes);
+       size += nBytes;
+    }
+    osi_Assert(nBytes == 0);
     FDH_REALLYCLOSE(srcFdP);
     FDH_REALLYCLOSE(destFdP);
     IH_RELEASE(srcH);
@@ -3286,21 +4402,22 @@ CopyInode(Device device, Inode inode1, Inode inode2, int rwvolume)
 }
 
 void
-PrintInodeList(void)
+PrintInodeList(struct SalvInfo *salvinfo)
 {
-    register struct ViceInodeInfo *ip;
+    struct ViceInodeInfo *ip;
     struct ViceInodeInfo *buf;
     struct afs_stat status;
-    register nInodes;
+    int nInodes;
+    afs_ino_str_t stmp;
 
-    assert(afs_fstat(inodeFd, &status) == 0);
+    osi_Assert(afs_fstat(salvinfo->inodeFd, &status) == 0);
     buf = (struct ViceInodeInfo *)malloc(status.st_size);
-    assert(buf != NULL);
+    osi_Assert(buf != NULL);
     nInodes = status.st_size / sizeof(struct ViceInodeInfo);
-    assert(read(inodeFd, buf, status.st_size) == status.st_size);
+    osi_Assert(read(salvinfo->inodeFd, buf, status.st_size) == status.st_size);
     for (ip = buf; nInodes--; ip++) {
        Log("Inode:%s, linkCount=%d, size=%#llx, p=(%u,%u,%u,%u)\n",
-           PrintInode(NULL, ip->inodeNumber), ip->linkCount,
+           PrintInode(stmp, ip->inodeNumber), ip->linkCount,
            (afs_uintmax_t) ip->byteCount, ip->u.param[0], ip->u.param[1],
            ip->u.param[2], ip->u.param[3]);
     }
@@ -3308,24 +4425,24 @@ PrintInodeList(void)
 }
 
 void
-PrintInodeSummary(void)
+PrintInodeSummary(struct SalvInfo *salvinfo)
 {
     int i;
     struct InodeSummary *isp;
 
-    for (i = 0; i < nVolumesInInodeFile; i++) {
-       isp = &inodeSummary[i];
+    for (i = 0; i < salvinfo->nVolumesInInodeFile; i++) {
+       isp = &salvinfo->inodeSummary[i];
        Log("VID:%u, RW:%u, index:%d, nInodes:%d, nSpecialInodes:%d, maxUniquifier:%u, volSummary\n", isp->volumeId, isp->RWvolumeId, isp->index, isp->nInodes, isp->nSpecialInodes, isp->maxUniquifier);
     }
 }
 
 void
-PrintVolumeSummary(void)
+PrintVolumeSummary(struct SalvInfo *salvinfo)
 {
     int i;
     struct VolumeSummary *vsp;
 
-    for (i = 0, vsp = volumeSummaryp; i < nVolumes; vsp++, i++) {
+    for (i = 0, vsp = salvinfo->volumeSummaryp; i < salvinfo->nVolumes; vsp++, i++) {
        Log("fileName:%s, header, wouldNeedCallback\n", vsp->fileName);
     }
 }
@@ -3336,10 +4453,10 @@ Fork(void)
     int f;
 #ifdef AFS_NT40_ENV
     f = 0;
-    assert(0);                 /* Fork is never executed in the NT code path */
+    osi_Assert(0);                     /* Fork is never executed in the NT code path */
 #else
     f = fork();
-    assert(f >= 0);
+    osi_Assert(f >= 0);
 #ifdef AFS_DEMAND_ATTACH_FS
     if ((f == 0) && (programType == salvageServer)) {
        /* we are a salvageserver child */
@@ -3356,8 +4473,7 @@ Fork(void)
 }
 
 void
-Exit(code)
-     int code;
+Exit(int code)
 {
     if (ShowLog)
        showlog();
@@ -3389,7 +4505,7 @@ Wait(char *prog)
     int status;
     int pid;
     pid = wait(&status);
-    assert(pid != -1);
+    osi_Assert(pid != -1);
     if (WCOREDUMP(status))
        Log("\"%s\" core dumped!\n", prog);
     if (WIFSIGNALED(status) != 0 || WEXITSTATUS(status) != 0)
@@ -3473,8 +4589,10 @@ showlog(void)
     }
 #endif
 
-    rewind(logFile);
-    fclose(logFile);
+    if (logFile) {
+       rewind(logFile);
+       fclose(logFile);
+    }
 
     logFile = afs_fopen(AFSDIR_SERVER_SLVGLOG_FILEPATH, "r");
 
@@ -3537,11 +4655,11 @@ Abort(const char *format, ...)
 }
 
 char *
-ToString(char *s)
+ToString(const char *s)
 {
-    register char *p;
+    char *p;
     p = (char *)malloc(strlen(s) + 1);
-    assert(p != NULL);
+    osi_Assert(p != NULL);
     strcpy(p, s);
     return p;
 }
@@ -3551,7 +4669,7 @@ void
 RemoveTheForce(char *path)
 {
     char target[1024];
-    struct afs_stat force; // so we can use afs_stat to find it
+    struct afs_stat force; /* so we can use afs_stat to find it */
     strcpy(target,path);
     strcat(target,"/FORCESALVAGE");
     if (!Testing && ForceSalvage) {