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