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