vol: avoid query for parent id when deleting disk header
[openafs.git] / src / vol / vutil.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  *
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 /*
11         System:         VICE-TWO
12         Module:         vutil.c
13         Institution:    The Information Technology Center, Carnegie-Mellon University
14
15  */
16
17 #include <afsconfig.h>
18 #include <afs/param.h>
19
20 #include <roken.h>
21 #include <afs/opr.h>
22
23 #ifdef HAVE_SYS_FILE_H
24 #include <sys/file.h>
25 #endif
26
27 #ifdef HAVE_SYS_LOCKF_H
28 #include <sys/lockf.h>
29 #endif
30
31 #ifdef AFS_PTHREAD_ENV
32 # include <opr/lock.h>
33 #else
34 # include <opr/lockstub.h>
35 #endif
36
37 #include <rx/rx_queue.h>
38 #include <rx/xdr.h>
39 #include <afs/afsint.h>
40 #include "nfs.h"
41 #include <afs/errors.h>
42 #include "lock.h"
43 #include "lwp.h"
44 #include <afs/afssyscalls.h>
45 #include "ihandle.h"
46 #include <afs/afsutil.h>
47 #ifdef AFS_NT40_ENV
48 #include "ntops.h"
49 #endif
50 #include "vnode.h"
51 #include "volume.h"
52 #include "volume_inline.h"
53 #include "partition.h"
54 #include "viceinode.h"
55
56 #include "volinodes.h"
57 #include "vol_prototypes.h"
58 #include "common.h"
59
60 #ifndef AFS_NT40_ENV
61 # ifdef O_LARGEFILE
62 #  define AFS_SETLKW   F_SETLKW64
63 #  define AFS_SETLK    F_SETLK64
64 #  define afs_st_flock flock64
65 # else
66 #  define AFS_SETLKW   F_SETLKW
67 #  define AFS_SETLK    F_SETLK
68 #  define afs_st_flock flock
69 # endif
70 #endif
71
72 /* Note:  the volume creation functions herein leave the destroyMe flag in the
73    volume header ON:  this means that the volumes will not be attached by the
74    file server and WILL BE DESTROYED the next time a system salvage is performed */
75
76 #ifdef FSSYNC_BUILD_CLIENT
77 static void
78 RemoveInodes(struct afs_inode_info *stuff, Device dev, VolumeId parent,
79              VolumeId vid)
80 {
81     int i;
82     IHandle_t *handle;
83
84     /* This relies on the fact that IDEC only needs the device and NT only
85      * needs the dev and vid to decrement volume special files.
86      */
87     IH_INIT(handle, dev, parent, -1);
88     for (i = 0; i < MAXINODETYPE; i++) {
89         Inode inode = *stuff[i].inode;
90         if (VALID_INO(inode)) {
91             if (stuff[i].inodeType == VI_LINKTABLE) {
92                 IH_DEC(handle, inode, parent);
93             } else {
94                 IH_DEC(handle, inode, vid);
95             }
96         }
97     }
98     IH_RELEASE(handle);
99 }
100
101 Volume *
102 VCreateVolume(Error * ec, char *partname, VolumeId volumeId, VolumeId parentId)
103 {                               /* Should be the same as volumeId if there is
104                                  * no parent */
105     Volume *retVal;
106     VOL_LOCK;
107     retVal = VCreateVolume_r(ec, partname, volumeId, parentId);
108     VOL_UNLOCK;
109     return retVal;
110 }
111
112 Volume *
113 VCreateVolume_r(Error * ec, char *partname, VolumeId volumeId, VolumeId parentId)
114 {                               /* Should be the same as volumeId if there is
115                                  * no parent */
116     VolumeDiskData vol;
117     int i, rc;
118     char headerName[VMAXPATHLEN], volumePath[VMAXPATHLEN];
119     Device device;
120     struct DiskPartition64 *partition;
121     struct VolumeDiskHeader diskHeader;
122     IHandle_t *handle;
123     FdHandle_t *fdP;
124     Inode nearInode AFS_UNUSED = 0;
125     char *part, *name;
126     struct stat st;
127     struct VolumeHeader tempHeader;
128     struct afs_inode_info stuff[MAXINODETYPE];
129     afs_ino_str_t stmp;
130 # ifdef AFS_DEMAND_ATTACH_FS
131     int locktype = 0;
132 # endif /* AFS_DEMAND_ATTACH_FS */
133
134     init_inode_info(&tempHeader, stuff);
135
136     *ec = 0;
137     memset(&vol, 0, sizeof(vol));
138     vol.id = volumeId;
139     vol.parentId = parentId;
140     vol.copyDate = time(0);     /* The only date which really means when this
141                                  * @i(instance) of this volume was created.
142                                  * Creation date does not mean this */
143
144     /* Initialize handle for error case below. */
145     handle = NULL;
146
147     /* Verify that the parition is valid before writing to it. */
148     if (!(partition = VGetPartition_r(partname, 0))) {
149         Log("VCreateVolume: partition %s is not in service.\n", partname);
150         *ec = VNOVOL;
151         return NULL;
152     }
153 #if     defined(NEARINODE_HINT)
154     nearInodeHash(volumeId, nearInode);
155     nearInode %= partition->f_files;
156 #endif
157     VGetVolumePath(ec, vol.id, &part, &name);
158     if (*ec == VNOVOL || !strcmp(partition->name, part)) {
159         /* this case is ok */
160     } else {
161         /* return EXDEV if it's a clone or read-only to an alternate partition
162          * otherwise assume it's a move */
163         if (vol.parentId != vol.id) {
164             Log("VCreateVolume: volume %" AFS_VOLID_FMT " for parent %" AFS_VOLID_FMT
165                 " found on %s; unable to create volume on %s.\n",
166                 afs_printable_VolumeId_lu(vol.id),
167                 afs_printable_VolumeId_lu(vol.parentId), part, partition->name);
168             *ec = EXDEV;
169             return NULL;
170         }
171     }
172     *ec = 0;
173
174 # ifdef AFS_DEMAND_ATTACH_FS
175     /* volume doesn't exist yet, but we must lock it to try to prevent something
176      * else from reading it when we're e.g. half way through creating it (or
177      * something tries to create the same volume at the same time) */
178     locktype = VVolLockType(V_VOLUPD, 1);
179     rc = VLockVolumeByIdNB(volumeId, partition, locktype);
180     if (rc) {
181         Log("VCreateVolume: vol %lu already locked by someone else\n",
182             afs_printable_uint32_lu(volumeId));
183         *ec = VNOVOL;
184         return NULL;
185     }
186 # else /* AFS_DEMAND_ATTACH_FS */
187     VLockPartition_r(partname);
188 # endif /* !AFS_DEMAND_ATTACH_FS */
189
190     memset(&tempHeader, 0, sizeof(tempHeader));
191     tempHeader.stamp.magic = VOLUMEHEADERMAGIC;
192     tempHeader.stamp.version = VOLUMEHEADERVERSION;
193     tempHeader.id = vol.id;
194     tempHeader.parent = vol.parentId;
195     vol.stamp.magic = VOLUMEINFOMAGIC;
196     vol.stamp.version = VOLUMEINFOVERSION;
197     vol.destroyMe = DESTROY_ME;
198     snprintf(headerName, sizeof headerName, VFORMAT,
199              afs_printable_VolumeId_lu(vol.id));
200     snprintf(volumePath, sizeof volumePath, "%s" OS_DIRSEP "%s",
201              VPartitionPath(partition), headerName);
202     rc = stat(volumePath, &st);
203     if (rc == 0 || errno != ENOENT) {
204         if (rc == 0) {
205             Log("VCreateVolume: Header file %s already exists!\n",
206                 volumePath);
207             *ec = VVOLEXISTS;
208         } else {
209             Log("VCreateVolume: Error %d trying to stat header file %s\n",
210                 errno, volumePath);
211             *ec = VNOVOL;
212         }
213         goto bad_noheader;
214     }
215     device = partition->device;
216
217     for (i = 0; i < MAXINODETYPE; i++) {
218         struct afs_inode_info *p = &stuff[i];
219         if (p->obsolete)
220             continue;
221 #ifdef AFS_NAMEI_ENV
222         *(p->inode) =
223             IH_CREATE(NULL, device, VPartitionPath(partition), nearInode,
224                       (p->inodeType == VI_LINKTABLE) ? vol.parentId : vol.id,
225                       INODESPECIAL, p->inodeType, vol.parentId);
226         if (!(VALID_INO(*(p->inode)))) {
227             if (errno == EEXIST && (p->inodeType == VI_LINKTABLE)) {
228                 /* Increment the reference count instead. */
229                 IHandle_t *lh;
230                 int code;
231
232                 *(p->inode) = namei_MakeSpecIno(vol.parentId, VI_LINKTABLE);
233                 IH_INIT(lh, device, parentId, *(p->inode));
234                 fdP = IH_OPEN(lh);
235                 if (fdP == NULL) {
236                     IH_RELEASE(lh);
237                     goto bad;
238                 }
239                 code = IH_INC(lh, *(p->inode), parentId);
240                 FDH_REALLYCLOSE(fdP);
241                 IH_RELEASE(lh);
242                 if (code < 0)
243                     goto bad;
244                 continue;
245             }
246         }
247 #else
248         *(p->inode) =
249             IH_CREATE(NULL, device, VPartitionPath(partition), nearInode,
250                       vol.id, INODESPECIAL, p->inodeType, vol.parentId);
251 #endif
252
253         if (!VALID_INO(*(p->inode))) {
254             Log("VCreateVolume:  Problem creating %s file associated with volume header %s\n", p->description, volumePath);
255           bad:
256             if (handle)
257                 IH_RELEASE(handle);
258             RemoveInodes(stuff, device, vol.parentId, vol.id);
259             if (!*ec) {
260                 *ec = VNOVOL;
261             }
262             VDestroyVolumeDiskHeader(partition, volumeId, parentId);
263           bad_noheader:
264 # ifdef AFS_DEMAND_ATTACH_FS
265             if (locktype) {
266                 VUnlockVolumeById(volumeId, partition);
267             }
268 # endif /* AFS_DEMAND_ATTACH_FS */
269             return NULL;
270         }
271         IH_INIT(handle, device, vol.parentId, *(p->inode));
272         fdP = IH_OPEN(handle);
273         if (fdP == NULL) {
274             Log("VCreateVolume:  Problem iopen inode %s (err=%d)\n",
275                 PrintInode(stmp, *(p->inode)), errno);
276             goto bad;
277         }
278         if (FDH_PWRITE(fdP, (char *)&p->stamp, sizeof(p->stamp), 0) !=
279             sizeof(p->stamp)) {
280             Log("VCreateVolume:  Problem writing to inode %s (err=%d)\n",
281                 PrintInode(stmp, *(p->inode)), errno);
282             FDH_REALLYCLOSE(fdP);
283             goto bad;
284         }
285         FDH_REALLYCLOSE(fdP);
286         IH_RELEASE(handle);
287         nearInode = *(p->inode);
288     }
289
290     IH_INIT(handle, device, vol.parentId, tempHeader.volumeInfo);
291     fdP = IH_OPEN(handle);
292     if (fdP == NULL) {
293         Log("VCreateVolume:  Problem iopen inode %s (err=%d)\n",
294             PrintInode(stmp, tempHeader.volumeInfo), errno);
295         goto bad;
296     }
297     if (FDH_PWRITE(fdP, (char *)&vol, sizeof(vol), 0) != sizeof(vol)) {
298         Log("VCreateVolume:  Problem writing to  inode %s (err=%d)\n",
299             PrintInode(stmp, tempHeader.volumeInfo), errno);
300         FDH_REALLYCLOSE(fdP);
301         goto bad;
302     }
303     FDH_CLOSE(fdP);
304     IH_RELEASE(handle);
305
306     VolumeHeaderToDisk(&diskHeader, &tempHeader);
307     rc = VCreateVolumeDiskHeader(&diskHeader, partition);
308     if (rc) {
309         Log("VCreateVolume: Error %d trying to write volume header for "
310             "volume %" AFS_VOLID_FMT " on partition %s; volume not created\n", rc,
311             afs_printable_VolumeId_lu(vol.id), VPartitionPath(partition));
312         if (rc == EEXIST) {
313             *ec = VVOLEXISTS;
314         }
315         goto bad;
316     }
317
318 # ifdef AFS_DEMAND_ATTACH_FS
319     if (locktype) {
320         VUnlockVolumeById(volumeId, partition);
321     }
322 # endif /* AFS_DEMAND_ATTACH_FS */
323     return (VAttachVolumeByName_r(ec, partname, headerName, V_SECRETLY));
324 }
325 #endif /* FSSYNC_BUILD_CLIENT */
326
327
328 void
329 AssignVolumeName(VolumeDiskData * vol, char *name, char *ext)
330 {
331     VOL_LOCK;
332     AssignVolumeName_r(vol, name, ext);
333     VOL_UNLOCK;
334 }
335
336 void
337 AssignVolumeName_r(VolumeDiskData * vol, char *name, char *ext)
338 {
339     char *dot;
340     strncpy(vol->name, name, VNAMESIZE - 1);
341     vol->name[VNAMESIZE - 1] = '\0';
342     dot = strrchr(vol->name, '.');
343     if (dot && (strcmp(dot, ".backup") == 0 || strcmp(dot, ".readonly") == 0))
344         *dot = 0;
345     if (ext)
346         strncat(vol->name, ext, VNAMESIZE - 1 - strlen(vol->name));
347 }
348
349 afs_int32
350 CopyVolumeHeader_r(VolumeDiskData * from, VolumeDiskData * to)
351 {
352     /* The id and parentId fields are not copied; these are inviolate--the to volume
353      * is assumed to have already been created.  The id's cannot be changed once
354      * creation has taken place, since they are embedded in the various inodes associated
355      * with the volume.  The copydate is also inviolate--it always reflects the time
356      * this volume was created (compare with the creation date--the creation date of
357      * a backup volume is the creation date of the original parent, because the backup
358      * is used to backup the parent volume). */
359     Date copydate;
360     VolumeId id, parent;
361     id = to->id;
362     parent = to->parentId;
363     copydate = to->copyDate;
364     memcpy(to, from, sizeof(*from));
365     to->id = id;
366     to->parentId = parent;
367     to->copyDate = copydate;
368     to->destroyMe = DESTROY_ME; /* Caller must always clear this!!! */
369     to->stamp.magic = VOLUMEINFOMAGIC;
370     to->stamp.version = VOLUMEINFOVERSION;
371     return 0;
372 }
373
374 afs_int32
375 CopyVolumeHeader(VolumeDiskData * from, VolumeDiskData * to)
376 {
377     afs_int32 code;
378
379     VOL_LOCK;
380     code = CopyVolumeHeader_r(from, to);
381     VOL_UNLOCK;
382     return (code);
383 }
384
385 void
386 ClearVolumeStats(VolumeDiskData * vol)
387 {
388     VOL_LOCK;
389     ClearVolumeStats_r(vol);
390     VOL_UNLOCK;
391 }
392
393 void
394 ClearVolumeStats_r(VolumeDiskData * vol)
395 {
396     memset(vol->weekUse, 0, sizeof(vol->weekUse));
397     vol->dayUse = 0;
398     vol->dayUseDate = 0;
399 }
400
401 void
402 CopyVolumeStats_r(VolumeDiskData * from, VolumeDiskData * to)
403 {
404     memcpy(to->weekUse, from->weekUse, sizeof(to->weekUse));
405     to->dayUse = from->dayUse;
406     to->dayUseDate = from->dayUseDate;
407     if (from->stat_initialized) {
408         memcpy(to->stat_reads, from->stat_reads, sizeof(to->stat_reads));
409         memcpy(to->stat_writes, from->stat_writes, sizeof(to->stat_writes));
410         memcpy(to->stat_fileSameAuthor, from->stat_fileSameAuthor,
411                sizeof(to->stat_fileSameAuthor));
412         memcpy(to->stat_fileDiffAuthor, from->stat_fileDiffAuthor,
413                sizeof(to->stat_fileDiffAuthor));
414         memcpy(to->stat_dirSameAuthor, from->stat_dirSameAuthor,
415                sizeof(to->stat_dirSameAuthor));
416         memcpy(to->stat_dirDiffAuthor, from->stat_dirDiffAuthor,
417                sizeof(to->stat_dirDiffAuthor));
418     }
419 }
420
421 void
422 CopyVolumeStats(VolumeDiskData * from, VolumeDiskData * to)
423 {
424     VOL_LOCK;
425     CopyVolumeStats_r(from, to);
426     VOL_UNLOCK;
427 }
428
429 /**
430  * read an existing volume disk header.
431  *
432  * @param[in]  volid  volume id
433  * @param[in]  dp     disk partition object
434  * @param[out] hdr    volume disk header or NULL
435  *
436  * @note if hdr is NULL, this is essentially an existence test for the vol
437  *       header
438  *
439  * @return operation status
440  *    @retval 0 success
441  *    @retval -1 volume header doesn't exist
442  *    @retval EIO failed to read volume header
443  *
444  * @internal
445  */
446 afs_int32
447 VReadVolumeDiskHeader(VolumeId volid,
448                       struct DiskPartition64 * dp,
449                       VolumeDiskHeader_t * hdr)
450 {
451     afs_int32 code = 0;
452     int fd;
453     char path[MAXPATHLEN];
454
455     snprintf(path, sizeof(path), "%s" OS_DIRSEP VFORMAT,
456              VPartitionPath(dp), afs_printable_VolumeId_lu(volid));
457     fd = open(path, O_RDONLY);
458     if (fd < 0) {
459         Log("VReadVolumeDiskHeader: Couldn't open header for volume %" AFS_VOLID_FMT " (errno %d).\n",
460             afs_printable_VolumeId_lu(volid), errno);
461         code = -1;
462
463     } else if (hdr && read(fd, hdr, sizeof(*hdr)) != sizeof(*hdr)) {
464         Log("VReadVolumeDiskHeader: Couldn't read header for volume %" AFS_VOLID_FMT ".\n",
465             afs_printable_VolumeId_lu(volid));
466         code = EIO;
467     }
468
469     if (fd >= 0) {
470         close(fd);
471     }
472     return code;
473 }
474
475 #ifdef FSSYNC_BUILD_CLIENT
476 /**
477  * write an existing volume disk header.
478  *
479  * @param[in] hdr   volume disk header
480  * @param[in] dp    disk partition object
481  * @param[in] cr    assert if O_CREAT | O_EXCL should be passed to open()
482  *
483  * @return operation status
484  *    @retval 0 success
485  *    @retval -1 volume header doesn't exist
486  *    @retval EIO failed to write volume header
487  *
488  * @internal
489  */
490 static afs_int32
491 _VWriteVolumeDiskHeader(VolumeDiskHeader_t * hdr,
492                         struct DiskPartition64 * dp,
493                         int flags)
494 {
495     afs_int32 code = 0;
496     int fd;
497     char path[MAXPATHLEN];
498
499 #ifdef AFS_DEMAND_ATTACH_FS
500     /* prevent racing with VGC scanners reading the vol header while we are
501      * writing it */
502     code = VPartHeaderLock(dp, READ_LOCK);
503     if (code) {
504         return EIO;
505     }
506 #endif /* AFS_DEMAND_ATTACH_FS */
507
508     flags |= O_RDWR;
509
510     snprintf(path, sizeof(path), "%s" OS_DIRSEP VFORMAT,
511              VPartitionPath(dp), afs_printable_VolumeId_lu(hdr->id));
512     fd = open(path, flags, 0644);
513     if (fd < 0) {
514         code = errno;
515         Log("_VWriteVolumeDiskHeader: Couldn't open header for volume %lu, "
516             "error = %d\n", afs_printable_uint32_lu(hdr->id), errno);
517     } else if (write(fd, hdr, sizeof(*hdr)) != sizeof(*hdr)) {
518         Log("_VWriteVolumeDiskHeader: Couldn't write header for volume %lu, "
519             "error = %d\n", afs_printable_uint32_lu(hdr->id), errno);
520         code = EIO;
521     }
522
523     if (fd >= 0) {
524         if (close(fd) != 0) {
525             Log("_VWriteVolumeDiskHeader: Error closing header for volume "
526                 "%lu, errno %d\n", afs_printable_uint32_lu(hdr->id), errno);
527         }
528     }
529
530 #ifdef AFS_DEMAND_ATTACH_FS
531     VPartHeaderUnlock(dp, READ_LOCK);
532 #endif /* AFS_DEMAND_ATTACH_FS */
533
534     return code;
535 }
536
537 /**
538  * write an existing volume disk header.
539  *
540  * @param[in] hdr   volume disk header
541  * @param[in] dp    disk partition object
542  *
543  * @return operation status
544  *    @retval 0 success
545  *    @retval ENOENT volume header doesn't exist
546  *    @retval EIO failed to write volume header
547  */
548 afs_int32
549 VWriteVolumeDiskHeader(VolumeDiskHeader_t * hdr,
550                        struct DiskPartition64 * dp)
551 {
552     afs_int32 code;
553
554 #ifdef AFS_DEMAND_ATTACH_FS
555     VolumeDiskHeader_t oldhdr;
556     int delvgc = 0, addvgc = 0;
557     SYNC_response res;
558
559     /* first, see if anything with the volume IDs have changed; if so, we
560      * need to update the VGC */
561
562     code = VReadVolumeDiskHeader(hdr->id, dp, &oldhdr);
563     if (code == 0 && (oldhdr.id != hdr->id || oldhdr.parent != hdr->parent)) {
564         /* the vol id or parent vol id changed; need to delete the VGC entry
565          * for the old vol id/parent, and add the new one */
566         delvgc = 1;
567         addvgc = 1;
568
569     } else if (code) {
570         /* couldn't get the old header info; add the new header info to the
571          * VGC in case it hasn't been added yet */
572         addvgc = 1;
573     }
574
575 #endif /* AFS_DEMAND_ATTACH_FS */
576
577     code = _VWriteVolumeDiskHeader(hdr, dp, 0);
578     if (code) {
579         goto done;
580     }
581
582 #ifdef AFS_DEMAND_ATTACH_FS
583     if (delvgc) {
584         memset(&res, 0, sizeof(res));
585         code = FSYNC_VGCDel(dp->name, oldhdr.parent, oldhdr.id, FSYNC_WHATEVER, &res);
586
587         /* unknown vol id is okay; it just further suggests the old header
588          * data was bogus, which is fine since we're trying to fix it */
589         if (code && res.hdr.reason != FSYNC_UNKNOWN_VOLID) {
590             Log("VWriteVolumeDiskHeader: FSYNC_VGCDel(%s, %lu, %lu) "
591                 "failed with code %ld reason %ld\n", dp->name,
592                 afs_printable_uint32_lu(oldhdr.parent),
593                 afs_printable_uint32_lu(oldhdr.id),
594                 afs_printable_int32_ld(code),
595                 afs_printable_int32_ld(res.hdr.reason));
596         }
597
598     }
599     if (addvgc) {
600         memset(&res, 0, sizeof(res));
601         code = FSYNC_VGCAdd(dp->name, hdr->parent, hdr->id, FSYNC_WHATEVER, &res);
602         if (code) {
603             Log("VWriteVolumeDiskHeader: FSYNC_VGCAdd(%s, %lu, %lu) "
604                 "failed with code %ld reason %ld\n", dp->name,
605                 afs_printable_uint32_lu(hdr->parent),
606                 afs_printable_uint32_lu(hdr->id),
607                 afs_printable_int32_ld(code),
608                 afs_printable_int32_ld(res.hdr.reason));
609         }
610     }
611
612 #endif /* AFS_DEMAND_ATTACH_FS */
613
614  done:
615     return code;
616 }
617
618 /**
619  * create and write a volume disk header to disk.
620  *
621  * @param[in] hdr   volume disk header
622  * @param[in] dp    disk partition object
623  *
624  * @return operation status
625  *    @retval 0 success
626  *    @retval EEXIST volume header already exists
627  *    @retval EIO failed to write volume header
628  *
629  * @internal
630  */
631 afs_int32
632 VCreateVolumeDiskHeader(VolumeDiskHeader_t * hdr,
633                         struct DiskPartition64 * dp)
634 {
635     afs_int32 code = 0;
636 #ifdef AFS_DEMAND_ATTACH_FS
637     SYNC_response res;
638 #endif /* AFS_DEMAND_ATTACH_FS */
639
640     code = _VWriteVolumeDiskHeader(hdr, dp, O_CREAT | O_EXCL);
641     if (code) {
642         goto done;
643     }
644
645 #ifdef AFS_DEMAND_ATTACH_FS
646     memset(&res, 0, sizeof(res));
647     code = FSYNC_VGCAdd(dp->name, hdr->parent, hdr->id, FSYNC_WHATEVER, &res);
648     if (code) {
649         Log("VCreateVolumeDiskHeader: FSYNC_VGCAdd(%s, %lu, %lu) failed "
650             "with code %ld reason %ld\n", dp->name,
651             afs_printable_uint32_lu(hdr->parent),
652             afs_printable_uint32_lu(hdr->id),
653             afs_printable_int32_ld(code),
654             afs_printable_int32_ld(res.hdr.reason));
655     }
656 #endif /* AFS_DEMAND_ATTACH_FS */
657
658  done:
659     return code;
660 }
661
662
663 /**
664  * destroy a volume disk header.
665  *
666  * @param[in] dp      disk partition object
667  * @param[in] volid   volume id
668  * @param[in] parent  parent's volume id, 0 if unknown
669  *
670  * @return operation status
671  *    @retval 0 success
672  *
673  * @note for non-DAFS, parent is currently ignored
674  */
675 afs_int32
676 VDestroyVolumeDiskHeader(struct DiskPartition64 * dp,
677                          VolumeId volid,
678                          VolumeId parent)
679 {
680     afs_int32 code = 0;
681     char path[MAXPATHLEN];
682 #ifdef AFS_DEMAND_ATTACH_FS
683     SYNC_response res;
684 #endif /* AFS_DEMAND_ATTACH_FS */
685
686     snprintf(path, sizeof(path), "%s" OS_DIRSEP VFORMAT,
687              VPartitionPath(dp), afs_printable_VolumeId_lu(volid));
688     code = unlink(path);
689     if (code) {
690         Log("VDestroyVolumeDiskHeader: Couldn't unlink disk header, error = %d\n", errno);
691         goto done;
692     }
693
694 #ifdef AFS_DEMAND_ATTACH_FS
695     /* Remove the volume entry from the fileserver's volume group cache, if found. */
696     memset(&res, 0, sizeof(res));
697     code = FSYNC_VGCDel(dp->name, parent, volid, FSYNC_WHATEVER, &res);
698     if (code) {
699         Log("VDestroyVolumeDiskHeader: FSYNC_VGCDel(%s, %" AFS_VOLID_FMT ", %" AFS_VOLID_FMT ") failed "
700             "with code %ld reason %ld\n", dp->name,
701             afs_printable_VolumeId_lu(parent),
702             afs_printable_VolumeId_lu(volid),
703             afs_printable_int32_ld(code),
704             afs_printable_int32_ld(res.hdr.reason));
705     }
706 #endif /* AFS_DEMAND_ATTACH_FS */
707
708  done:
709     return code;
710 }
711 #endif /* FSSYNC_BUILD_CLIENT */
712
713 /**
714  * handle a single vol header as part of VWalkVolumeHeaders.
715  *
716  * @param[in] dp      disk partition
717  * @param[in] volfunc function to call when a vol header is successfully read
718  * @param[in] name    full path name to the .vol header
719  * @param[out] hdr    header data read in from the .vol header
720  * @param[in] locked  1 if the partition headers are locked, 0 otherwise
721  * @param[in] rock    the rock to pass to volfunc
722  *
723  * @return operation status
724  *  @retval 0  success
725  *  @retval -1 fatal error, stop scanning
726  *  @retval 1  failed to read header
727  *  @retval 2  volfunc callback indicated error after header read
728  */
729 static int
730 _VHandleVolumeHeader(struct DiskPartition64 *dp, VWalkVolFunc volfunc,
731                      const char *name, struct VolumeDiskHeader *hdr,
732                      int locked, void *rock)
733 {
734     int error = 0;
735     FD_t fd;
736
737     if ((fd = OS_OPEN(name, O_RDONLY, 0)) == INVALID_FD
738         || OS_READ(fd, hdr, sizeof(*hdr))
739         != sizeof(*hdr)
740         || hdr->stamp.magic != VOLUMEHEADERMAGIC) {
741         error = 1;
742     }
743
744     if (fd != INVALID_FD) {
745         OS_CLOSE(fd);
746     }
747
748 #ifdef AFSFS_DEMAND_ATTACH_FS
749     if (locked) {
750         VPartHeaderUnlock(dp);
751     }
752 #endif /* AFS_DEMAND_ATTACH_FS */
753
754     if (!error && volfunc) {
755         /* the volume header seems fine; call the caller-supplied
756          * 'we-found-a-volume-header' function */
757         int last = 1;
758
759 #ifdef AFS_DEMAND_ATTACH_FS
760         if (!locked) {
761             last = 0;
762         }
763 #endif /* AFS_DEMAND_ATTACH_FS */
764
765         error = (*volfunc) (dp, name, hdr, last, rock);
766         if (error < 0) {
767             return -1;
768         }
769         if (error) {
770             error = 2;
771         }
772     }
773
774 #ifdef AFS_DEMAND_ATTACH_FS
775     if (error && !locked) {
776         int code;
777         /* retry reading the volume header under the partition
778          * header lock, just to be safe and ensure we're not
779          * racing something rewriting the vol header */
780         code = VPartHeaderLock(dp, WRITE_LOCK);
781         if (code) {
782             Log("Error acquiring partition write lock when "
783                 "looking at header %s\n", name);
784             return -1;
785         }
786
787         return _VHandleVolumeHeader(dp, volfunc, name, hdr, 1, rock);
788     }
789 #endif /* AFS_DEMAND_ATTACH_FS */
790
791     return error;
792 }
793
794 /**
795  * walk through the list of volume headers on a partition.
796  *
797  * This function looks through all of the .vol headers on a partition, reads in
798  * each header, and calls the supplied volfunc function on each one. If the
799  * header cannot be read (or volfunc returns a positive error code), DAFS will
800  * VPartHeaderExLock() and retry. If that fails, or if we are non-DAFS, errfunc
801  * will be called (which typically will unlink the problem volume header).
802  *
803  * If volfunc returns a negative error code, walking the partition will stop
804  * and we will return an error immediately.
805  *
806  * @param[in] dp       partition to walk
807  * @param[in] partpath the path opendir()
808  * @param[in] volfunc  the function to call when a header is encountered, or
809  *                     NULL to just skip over valid headers
810  * @param[in] errfunc  the function to call when a problematic header is
811  *                     encountered, or NULL to just skip over bad headers
812  * @param[in] rock     rock for volfunc and errfunc
813  *
814  * @see VWalkVolFunc
815  * @see VWalkErrFunc
816  *
817  * @return operation status
818  *  @retval 0 success
819  *  @retval negative fatal error, walk did not finish
820  */
821 int
822 VWalkVolumeHeaders(struct DiskPartition64 *dp, const char *partpath,
823                    VWalkVolFunc volfunc, VWalkErrFunc errfunc, void *rock)
824 {
825     DIR *dirp;
826     struct dirent *dentry;
827     int code = 0;
828     struct VolumeDiskHeader diskHeader;
829
830     dirp = opendir(partpath);
831     if (!dirp) {
832         Log("VWalkVolumeHeaders: cannot open directory %s\n", partpath);
833         code = -1;
834         goto done;
835     }
836
837     while ((dentry = readdir(dirp)) != NULL) {
838         char *p;
839         p = strrchr(dentry->d_name, '.');
840         if (p != NULL && strcmp(p, VHDREXT) == 0) {
841             char name[VMAXPATHLEN];
842
843             snprintf(name, VMAXPATHLEN, "%s" OS_DIRSEP "%s", partpath, dentry->d_name);
844
845             code = _VHandleVolumeHeader(dp, volfunc, name, &diskHeader, -1, rock);
846             if (code < 0) {
847                 /* fatal error, stop walking */
848                 goto done;
849             }
850             if (code && errfunc) {
851                 /* error with header; call the caller-supplied vol error
852                  * function */
853
854                 struct VolumeDiskHeader *hdr = &diskHeader;
855                 if (code == 1) {
856                     /* we failed to read the header at all, so don't pass in
857                      * the header ptr */
858                     hdr = NULL;
859                 }
860                 (*errfunc) (dp, name, hdr, rock);
861             }
862             code = 0;
863         }
864     }
865  done:
866     if (dirp) {
867         closedir(dirp);
868         dirp = NULL;
869     }
870
871     return code;
872 }
873
874 /**
875  * initialize a struct VLockFile.
876  *
877  * @param[in] lf   struct VLockFile to initialize
878  * @param[in] path Full path to the file to use for locks. The string contents
879  *                 are copied.
880  */
881 void
882 VLockFileInit(struct VLockFile *lf, const char *path)
883 {
884     memset(lf, 0, sizeof(*lf));
885     lf->path = strdup(path);
886     lf->fd = INVALID_FD;
887     opr_mutex_init(&lf->mutex);
888 }
889
890 #ifdef AFS_NT40_ENV
891 static_inline FD_t
892 _VOpenPath(const char *path)
893 {
894     HANDLE handle;
895
896     handle = CreateFile(path,
897                         GENERIC_READ | GENERIC_WRITE,
898                         FILE_SHARE_READ | FILE_SHARE_WRITE,
899                         NULL,
900                         OPEN_ALWAYS,
901                         FILE_ATTRIBUTE_HIDDEN,
902                         NULL);
903     if (handle == INVALID_HANDLE_VALUE) {
904         return INVALID_FD;
905     }
906
907     return handle;
908 }
909
910 static_inline int
911 _VLockFd(FD_t handle, afs_uint32 offset, int locktype, int nonblock)
912 {
913     DWORD flags = 0;
914     OVERLAPPED lap;
915
916     if (locktype == WRITE_LOCK) {
917         flags |= LOCKFILE_EXCLUSIVE_LOCK;
918     }
919     if (nonblock) {
920         flags |= LOCKFILE_FAIL_IMMEDIATELY;
921     }
922
923     memset(&lap, 0, sizeof(lap));
924     lap.Offset = offset;
925
926     if (!LockFileEx(handle, flags, 0, 1, 0, &lap)) {
927         if (GetLastError() == ERROR_LOCK_VIOLATION) {
928             return EBUSY;
929         }
930         return EIO;
931     }
932
933     return 0;
934 }
935
936 static_inline void
937 _VUnlockFd(FD_t handle, afs_uint32 offset)
938 {
939     OVERLAPPED lap;
940
941     memset(&lap, 0, sizeof(lap));
942     lap.Offset = offset;
943
944     UnlockFileEx(handle, 0, 1, 0, &lap);
945 }
946
947 static_inline void
948 _VCloseFd(FD_t handle)
949 {
950     CloseHandle(handle);
951 }
952
953 #else /* !AFS_NT40_ENV */
954
955 /**
956  * open a file on the local filesystem suitable for locking
957  *
958  * @param[in] path  abs path of the file to open
959  *
960  * @return file descriptor
961  *  @retval INVALID_FD failure opening file
962  */
963 static_inline FD_t
964 _VOpenPath(const char *path)
965 {
966     int fd;
967
968     fd = open(path, O_RDWR | O_CREAT, 0660);
969     if (fd < 0) {
970         return INVALID_FD;
971     }
972     return fd;
973 }
974
975 /**
976  * lock an offset in a file descriptor.
977  *
978  * @param[in] fd       file descriptor to lock
979  * @param[in] offset   offset in file to lock
980  * @param[in] locktype READ_LOCK or WRITE_LOCK
981  * @param[in] nonblock 1 to fail immediately, 0 to wait to acquire lock
982  *
983  * @return operation status
984  *  @retval 0 success
985  *  @retval EBUSY someone else is holding a conflicting lock and nonblock=1 was
986  *                specified
987  *  @retval EIO   error acquiring file lock
988  */
989 static_inline int
990 _VLockFd(FD_t fd, afs_uint32 offset, int locktype, int nonblock)
991 {
992     int l_type = F_WRLCK;
993     int cmd = AFS_SETLKW;
994     struct afs_st_flock sf;
995
996     opr_Assert(fd >= 0);
997
998     if (locktype == READ_LOCK) {
999         l_type = F_RDLCK;
1000     }
1001     if (nonblock) {
1002         cmd = AFS_SETLK;
1003     }
1004
1005     sf.l_start = offset;
1006     sf.l_len = 1;
1007     sf.l_type = l_type;
1008     sf.l_whence = SEEK_SET;
1009
1010     if (fcntl(fd, cmd, &sf)) {
1011         if (nonblock && (errno == EACCES || errno == EAGAIN)) {
1012             /* We asked for a nonblocking lock, and it was already locked */
1013             sf.l_pid = 0;
1014             if (fcntl(fd, F_GETLK, &sf) != 0 || sf.l_pid == 0) {
1015                 Log("_VLockFd: fcntl failed with error %d when trying to "
1016                     "query the conflicting lock for fd %d (locktype=%d, "
1017                     "offset=%lu)\n", errno, fd, locktype,
1018                     afs_printable_uint32_lu(offset));
1019             } else {
1020                 Log("_VLockFd: conflicting lock held on fd %d, offset %lu by "
1021                     "pid %ld (locktype=%d)\n", fd,
1022                     afs_printable_uint32_lu(offset), (long int)sf.l_pid,
1023                     locktype);
1024             }
1025             return EBUSY;
1026         }
1027         Log("_VLockFd: fcntl failed with error %d when trying to lock "
1028             "fd %d (locktype=%d, offset=%lu)\n", errno, fd, locktype,
1029             afs_printable_uint32_lu(offset));
1030         return EIO;
1031     }
1032
1033     return 0;
1034 }
1035
1036 /**
1037  * close a file descriptor used for file locking.
1038  *
1039  * @param[in] fd file descriptor to close
1040  */
1041 static_inline void
1042 _VCloseFd(FD_t fd)
1043 {
1044     if (close(fd)) {
1045         Log("_VCloseFd: error %d closing fd %d\n",
1046             errno, fd);
1047     }
1048 }
1049
1050 /**
1051  * unlock a file offset in a file descriptor.
1052  *
1053  * @param[in] fd file descriptor to unlock
1054  * @param[in] offset offset to unlock
1055  */
1056 static_inline void
1057 _VUnlockFd(FD_t fd, afs_uint32 offset)
1058 {
1059     struct afs_st_flock sf;
1060
1061     sf.l_start = offset;
1062     sf.l_len = 1;
1063     sf.l_type = F_UNLCK;
1064     sf.l_whence = SEEK_SET;
1065
1066     if (fcntl(fd, AFS_SETLK, &sf)) {
1067         Log("_VUnlockFd: fcntl failed with error %d when trying to unlock "
1068             "fd %d\n", errno, fd);
1069     }
1070 }
1071 #endif /* !AFS_NT40_ENV */
1072
1073 /**
1074  * reinitialize a struct VLockFile.
1075  *
1076  * Use this to close the lock file (unlocking any locks in it), and effectively
1077  * restore lf to the state it was in when it was initialized. This is the same
1078  * as unlocking all of the locks on the file, without having to remember what
1079  * all of the locks were. Do not unlock previously held locks after calling
1080  * this.
1081  *
1082  * @param[in] lf  struct VLockFile to reinit
1083  *
1084  * @pre nobody is waiting for a lock on this lockfile or otherwise using
1085  *      this lockfile at all
1086  */
1087 void
1088 VLockFileReinit(struct VLockFile *lf)
1089 {
1090     opr_mutex_enter(&lf->mutex);
1091
1092     if (lf->fd != INVALID_FD) {
1093         _VCloseFd(lf->fd);
1094         lf->fd = INVALID_FD;
1095     }
1096
1097     lf->refcount = 0;
1098
1099     opr_mutex_exit(&lf->mutex);
1100 }
1101
1102 /**
1103  * lock a file on disk for the process.
1104  *
1105  * @param[in] lf       the struct VLockFile representing the file to lock
1106  * @param[in] offset   the offset in the file to lock
1107  * @param[in] locktype READ_LOCK or WRITE_LOCK
1108  * @param[in] nonblock 0 to wait for conflicting locks to clear before
1109  *                     obtaining the lock; 1 to fail immediately if a
1110  *                     conflicting lock is held by someone else
1111  *
1112  * @return operation status
1113  *  @retval 0 success
1114  *  @retval EBUSY someone else is holding a conflicting lock and nonblock=1 was
1115  *                specified
1116  *  @retval EIO   error acquiring file lock
1117  *
1118  * @note DAFS only
1119  *
1120  * @note do not try to lock/unlock the same offset in the same file from
1121  * different threads; use VGetDiskLock to protect threads from each other in
1122  * addition to other processes
1123  */
1124 int
1125 VLockFileLock(struct VLockFile *lf, afs_uint32 offset, int locktype, int nonblock)
1126 {
1127     int code;
1128
1129     opr_Assert(locktype == READ_LOCK || locktype == WRITE_LOCK);
1130
1131     opr_mutex_enter(&lf->mutex);
1132
1133     if (lf->fd == INVALID_FD) {
1134         opr_Assert(lf->refcount == 0);
1135         lf->fd = _VOpenPath(lf->path);
1136         if (lf->fd == INVALID_FD) {
1137             opr_mutex_exit(&lf->mutex);
1138             return EIO;
1139         }
1140     }
1141
1142     lf->refcount++;
1143
1144     opr_Assert(lf->refcount > 0);
1145
1146     opr_mutex_exit(&lf->mutex);
1147
1148     code = _VLockFd(lf->fd, offset, locktype, nonblock);
1149
1150     if (code) {
1151         opr_mutex_enter(&lf->mutex);
1152         opr_Assert(lf->refcount > 0);
1153         if (--lf->refcount < 1) {
1154             _VCloseFd(lf->fd);
1155             lf->fd = INVALID_FD;
1156         }
1157         opr_mutex_exit(&lf->mutex);
1158     }
1159
1160     return code;
1161 }
1162
1163 void
1164 VLockFileUnlock(struct VLockFile *lf, afs_uint32 offset)
1165 {
1166     opr_mutex_enter(&lf->mutex);
1167
1168     opr_Assert(lf->fd != INVALID_FD);
1169     opr_Assert(lf->refcount > 0);
1170
1171     if (--lf->refcount < 1) {
1172         _VCloseFd(lf->fd);
1173         lf->fd = INVALID_FD;
1174     } else {
1175         _VUnlockFd(lf->fd, offset);
1176     }
1177
1178     opr_mutex_exit(&lf->mutex);
1179 }
1180
1181 #ifdef AFS_DEMAND_ATTACH_FS
1182
1183 /**
1184  * initialize a struct VDiskLock.
1185  *
1186  * @param[in] dl struct VDiskLock to initialize
1187  * @param[in] lf the struct VLockFile to associate with this disk lock
1188  */
1189 void
1190 VDiskLockInit(struct VDiskLock *dl, struct VLockFile *lf, afs_uint32 offset)
1191 {
1192     opr_Assert(lf);
1193     memset(dl, 0, sizeof(*dl));
1194     Lock_Init(&dl->rwlock);
1195     opr_mutex_init(&dl->mutex);
1196     opr_cv_init(&dl->cv);
1197     dl->lockfile = lf;
1198     dl->offset = offset;
1199 }
1200
1201 /**
1202  * acquire a lock on a file on local disk.
1203  *
1204  * @param[in] dl       the VDiskLock structure corresponding to the file on disk
1205  * @param[in] locktype READ_LOCK if you want a read lock, or WRITE_LOCK if
1206  *                     you want a write lock
1207  * @param[in] nonblock 0 to wait for conflicting locks to clear before
1208  *                     obtaining the lock; 1 to fail immediately if a
1209  *                     conflicting lock is held by someone else
1210  *
1211  * @return operation status
1212  *  @retval 0 success
1213  *  @retval EBUSY someone else is holding a conflicting lock and nonblock=1 was
1214  *                specified
1215  *  @retval EIO   error acquiring file lock
1216  *
1217  * @note DAFS only
1218  *
1219  * @note while normal fcntl-y locks on Unix systems generally only work per-
1220  * process, this interface also deals with locks between threads in the
1221  * process in addition to different processes acquiring the lock
1222  */
1223 int
1224 VGetDiskLock(struct VDiskLock *dl, int locktype, int nonblock)
1225 {
1226     int code = 0;
1227     opr_Assert(locktype == READ_LOCK || locktype == WRITE_LOCK);
1228
1229     if (nonblock) {
1230         if (locktype == READ_LOCK) {
1231             ObtainReadLockNoBlock(&dl->rwlock, code);
1232         } else {
1233             ObtainWriteLockNoBlock(&dl->rwlock, code);
1234         }
1235
1236         if (code) {
1237             return EBUSY;
1238         }
1239
1240     } else if (locktype == READ_LOCK) {
1241         ObtainReadLock(&dl->rwlock);
1242     } else {
1243         ObtainWriteLock(&dl->rwlock);
1244     }
1245
1246     opr_mutex_enter(&dl->mutex);
1247
1248     if ((dl->flags & VDISKLOCK_ACQUIRING)) {
1249         /* Some other thread is waiting to acquire an fs lock. If nonblock=1,
1250          * we can return immediately, since we know we'll need to wait to
1251          * acquire. Otherwise, wait for the other thread to finish acquiring
1252          * the fs lock */
1253         if (nonblock) {
1254             code = EBUSY;
1255         } else {
1256             while ((dl->flags & VDISKLOCK_ACQUIRING)) {
1257                 opr_cv_wait(&dl->cv, &dl->mutex);
1258             }
1259         }
1260     }
1261
1262     if (code == 0 && !(dl->flags & VDISKLOCK_ACQUIRED)) {
1263         /* no other thread holds the lock on the actual file; so grab one */
1264
1265         /* first try, don't block on the lock to see if we can get it without
1266          * waiting */
1267         code = VLockFileLock(dl->lockfile, dl->offset, locktype, 1);
1268
1269         if (code == EBUSY && !nonblock) {
1270
1271             /* mark that we are waiting on the fs lock */
1272             dl->flags |= VDISKLOCK_ACQUIRING;
1273
1274             opr_mutex_exit(&dl->mutex);
1275             code = VLockFileLock(dl->lockfile, dl->offset, locktype, nonblock);
1276             opr_mutex_enter(&dl->mutex);
1277
1278             dl->flags &= ~VDISKLOCK_ACQUIRING;
1279
1280             if (code == 0) {
1281                 dl->flags |= VDISKLOCK_ACQUIRED;
1282             }
1283
1284             opr_cv_broadcast(&dl->cv);
1285         }
1286     }
1287
1288     if (code) {
1289         if (locktype == READ_LOCK) {
1290             ReleaseReadLock(&dl->rwlock);
1291         } else {
1292             ReleaseWriteLock(&dl->rwlock);
1293         }
1294     } else {
1295         /* successfully got the lock, so inc the number of unlocks we need
1296          * to do before we can unlock the actual file */
1297         ++dl->lockers;
1298     }
1299
1300     opr_mutex_exit(&dl->mutex);
1301
1302     return code;
1303 }
1304
1305 /**
1306  * release a lock on a file on local disk.
1307  *
1308  * @param[in] dl the struct VDiskLock to release
1309  * @param[in] locktype READ_LOCK if you are unlocking a read lock, or
1310  *                     WRITE_LOCK if you are unlocking a write lock
1311  *
1312  * @return operation status
1313  *  @retval 0 success
1314  */
1315 void
1316 VReleaseDiskLock(struct VDiskLock *dl, int locktype)
1317 {
1318     opr_Assert(locktype == READ_LOCK || locktype == WRITE_LOCK);
1319
1320     opr_mutex_enter(&dl->mutex);
1321     opr_Assert(dl->lockers > 0);
1322
1323     if (--dl->lockers < 1) {
1324         /* no threads are holding this lock anymore, so we can release the
1325          * actual disk lock */
1326         VLockFileUnlock(dl->lockfile, dl->offset);
1327         dl->flags &= ~VDISKLOCK_ACQUIRED;
1328     }
1329
1330     opr_mutex_exit(&dl->mutex);
1331
1332     if (locktype == READ_LOCK) {
1333         ReleaseReadLock(&dl->rwlock);
1334     } else {
1335         ReleaseWriteLock(&dl->rwlock);
1336     }
1337 }
1338
1339 #endif /* AFS_DEMAND_ATTACH_FS */