2 * Copyright 2000, International Business Machines Corporation and others.
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
13 Institution: The Information Technology Center, Carnegie-Mellon University
17 #include <afsconfig.h>
18 #include <afs/param.h>
22 #include <sys/types.h>
34 #ifdef AFS_PTHREAD_ENV
36 #else /* AFS_PTHREAD_ENV */
37 #include <afs/afs_assert.h>
38 #endif /* AFS_PTHREAD_ENV */
41 #include <afs/afsint.h>
43 #include <afs/errors.h>
46 #include <afs/afssyscalls.h>
48 #include <afs/afsutil.h>
55 #include "volume_inline.h"
56 #include "partition.h"
57 #include "viceinode.h"
59 #include "volinodes.h"
60 #include "vol_prototypes.h"
64 #include <sys/lockf.h>
66 #if defined(AFS_SUN5_ENV) || defined(AFS_NT40_ENV) || defined(AFS_LINUX20_ENV)
73 #define afs_open open64
74 #else /* !O_LARGEFILE */
76 #endif /* !O_LARGEFILE */
79 /* Note: the volume creation functions herein leave the destroyMe flag in the
80 volume header ON: this means that the volumes will not be attached by the
81 file server and WILL BE DESTROYED the next time a system salvage is performed */
83 #ifdef FSSYNC_BUILD_CLIENT
85 RemoveInodes(struct afs_inode_info *stuff, Device dev, VolumeId vid)
90 /* This relies on the fact that IDEC only needs the device and NT only
91 * needs the dev and vid to decrement volume special files.
93 IH_INIT(handle, dev, vid, -1);
94 for (i = 0; i < MAXINODETYPE; i++) {
95 Inode inode = *stuff[i].inode;
97 IH_DEC(handle, inode, vid);
103 VCreateVolume(Error * ec, char *partname, VolId volumeId, VolId parentId)
104 { /* Should be the same as volumeId if there is
108 retVal = VCreateVolume_r(ec, partname, volumeId, parentId);
114 VCreateVolume_r(Error * ec, char *partname, VolId volumeId, VolId parentId)
115 { /* Should be the same as volumeId if there is
119 char headerName[VMAXPATHLEN], volumePath[VMAXPATHLEN];
121 struct DiskPartition64 *partition;
122 struct VolumeDiskHeader diskHeader;
128 struct VolumeHeader tempHeader;
129 struct afs_inode_info stuff[MAXINODETYPE];
131 # ifdef AFS_DEMAND_ATTACH_FS
133 # endif /* AFS_DEMAND_ATTACH_FS */
135 init_inode_info(&tempHeader, stuff);
138 memset(&vol, 0, sizeof(vol));
140 vol.parentId = parentId;
141 vol.copyDate = time(0); /* The only date which really means when this
142 * @i(instance) of this volume was created.
143 * Creation date does not mean this */
145 /* Initialize handle for error case below. */
148 /* Verify that the parition is valid before writing to it. */
149 if (!(partition = VGetPartition_r(partname, 0))) {
150 Log("VCreateVolume: partition %s is not in service.\n", partname);
154 #if defined(NEARINODE_HINT)
155 nearInodeHash(volumeId, nearInode);
156 nearInode %= partition->f_files;
158 VGetVolumePath(ec, vol.id, &part, &name);
159 if (*ec == VNOVOL || !strcmp(partition->name, part)) {
160 /* this case is ok */
162 /* return EXDEV if it's a clone to an alternate partition
163 * otherwise assume it's a move */
164 if (vol.parentId != vol.id) {
171 # ifdef AFS_DEMAND_ATTACH_FS
172 /* volume doesn't exist yet, but we must lock it to try to prevent something
173 * else from reading it when we're e.g. half way through creating it (or
174 * something tries to create the same volume at the same time) */
175 locktype = VVolLockType(V_VOLUPD, 1);
176 rc = VLockVolumeByIdNB(volumeId, partition, locktype);
178 Log("VCreateVolume: vol %lu already locked by someone else\n",
179 afs_printable_uint32_lu(volumeId));
183 # else /* AFS_DEMAND_ATTACH_FS */
184 VLockPartition_r(partname);
185 # endif /* !AFS_DEMAND_ATTACH_FS */
187 memset(&tempHeader, 0, sizeof(tempHeader));
188 tempHeader.stamp.magic = VOLUMEHEADERMAGIC;
189 tempHeader.stamp.version = VOLUMEHEADERVERSION;
190 tempHeader.id = vol.id;
191 tempHeader.parent = vol.parentId;
192 vol.stamp.magic = VOLUMEINFOMAGIC;
193 vol.stamp.version = VOLUMEINFOVERSION;
194 vol.destroyMe = DESTROY_ME;
195 (void)afs_snprintf(headerName, sizeof headerName, VFORMAT, afs_printable_uint32_lu(vol.id));
196 (void)afs_snprintf(volumePath, sizeof volumePath, "%s/%s",
197 VPartitionPath(partition), headerName);
198 rc = stat(volumePath, &st);
199 if (rc == 0 || errno != ENOENT) {
201 Log("VCreateVolume: Header file %s already exists!\n",
205 Log("VCreateVolume: Error %d trying to stat header file %s\n",
211 device = partition->device;
213 for (i = 0; i < MAXINODETYPE; i++) {
214 struct afs_inode_info *p = &stuff[i];
219 IH_CREATE(NULL, device, VPartitionPath(partition), nearInode,
220 (p->inodeType == VI_LINKTABLE) ? vol.parentId : vol.id,
221 INODESPECIAL, p->inodeType, vol.parentId);
222 if (!(VALID_INO(*(p->inode)))) {
223 if (errno == EEXIST && (p->inodeType == VI_LINKTABLE)) {
224 /* Increment the reference count instead. */
229 *(p->inode) = nt_MakeSpecIno(VI_LINKTABLE);
231 *(p->inode) = namei_MakeSpecIno(vol.parentId, VI_LINKTABLE);
233 IH_INIT(lh, device, parentId, *(p->inode));
239 code = IH_INC(lh, *(p->inode), parentId);
240 FDH_REALLYCLOSE(fdP);
249 IH_CREATE(NULL, device, VPartitionPath(partition), nearInode,
250 vol.id, INODESPECIAL, p->inodeType, vol.parentId);
253 if (!VALID_INO(*(p->inode))) {
254 Log("VCreateVolume: Problem creating %s file associated with volume header %s\n", p->description, volumePath);
258 RemoveInodes(stuff, device, vol.id);
262 VDestroyVolumeDiskHeader(partition, volumeId, parentId);
264 # ifdef AFS_DEMAND_ATTACH_FS
266 VUnlockVolumeById(volumeId, partition);
268 # endif /* AFS_DEMAND_ATTACH_FS */
271 IH_INIT(handle, device, vol.parentId, *(p->inode));
272 fdP = IH_OPEN(handle);
274 Log("VCreateVolume: Problem iopen inode %s (err=%d)\n",
275 PrintInode(stmp, *(p->inode)), errno);
278 if (FDH_PWRITE(fdP, (char *)&p->stamp, sizeof(p->stamp), 0) !=
280 Log("VCreateVolume: Problem writing to inode %s (err=%d)\n",
281 PrintInode(stmp, *(p->inode)), errno);
282 FDH_REALLYCLOSE(fdP);
285 FDH_REALLYCLOSE(fdP);
287 nearInode = *(p->inode);
290 IH_INIT(handle, device, vol.parentId, tempHeader.volumeInfo);
291 fdP = IH_OPEN(handle);
293 Log("VCreateVolume: Problem iopen inode %s (err=%d)\n",
294 PrintInode(stmp, tempHeader.volumeInfo), errno);
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);
306 VolumeHeaderToDisk(&diskHeader, &tempHeader);
307 rc = VCreateVolumeDiskHeader(&diskHeader, partition);
309 Log("VCreateVolume: Error %d trying to write volume header for "
310 "volume %u on partition %s; volume not created\n", rc,
311 vol.id, VPartitionPath(partition));
318 # ifdef AFS_DEMAND_ATTACH_FS
320 VUnlockVolumeById(volumeId, partition);
322 # endif /* AFS_DEMAND_ATTACH_FS */
323 return (VAttachVolumeByName_r(ec, partname, headerName, V_SECRETLY));
325 #endif /* FSSYNC_BUILD_CLIENT */
329 AssignVolumeName(VolumeDiskData * vol, char *name, char *ext)
332 AssignVolumeName_r(vol, name, ext);
337 AssignVolumeName_r(VolumeDiskData * vol, char *name, char *ext)
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))
346 strncat(vol->name, ext, VNAMESIZE - 1 - strlen(vol->name));
350 CopyVolumeHeader_r(VolumeDiskData * from, VolumeDiskData * to)
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). */
362 parent = to->parentId;
363 copydate = to->copyDate;
364 memcpy(to, from, sizeof(*from));
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;
375 CopyVolumeHeader(VolumeDiskData * from, VolumeDiskData * to)
380 code = CopyVolumeHeader_r(from, to);
386 ClearVolumeStats(VolumeDiskData * vol)
389 ClearVolumeStats_r(vol);
394 ClearVolumeStats_r(VolumeDiskData * vol)
396 memset(vol->weekUse, 0, sizeof(vol->weekUse));
402 * read an existing volume disk header.
404 * @param[in] volid volume id
405 * @param[in] dp disk partition object
406 * @param[out] hdr volume disk header or NULL
408 * @note if hdr is NULL, this is essentially an existence test for the vol
411 * @return operation status
413 * @retval -1 volume header doesn't exist
414 * @retval EIO failed to read volume header
419 VReadVolumeDiskHeader(VolumeId volid,
420 struct DiskPartition64 * dp,
421 VolumeDiskHeader_t * hdr)
425 char path[MAXPATHLEN];
427 (void)afs_snprintf(path, sizeof(path),
429 VPartitionPath(dp), afs_printable_uint32_lu(volid));
430 fd = open(path, O_RDONLY);
432 Log("VReadVolumeDiskHeader: Couldn't open header for volume %lu (errno %d).\n",
433 afs_printable_uint32_lu(volid), errno);
436 } else if (hdr && read(fd, hdr, sizeof(*hdr)) != sizeof(*hdr)) {
437 Log("VReadVolumeDiskHeader: Couldn't read header for volume %lu.\n",
438 afs_printable_uint32_lu(volid));
448 #ifdef FSSYNC_BUILD_CLIENT
450 * write an existing volume disk header.
452 * @param[in] hdr volume disk header
453 * @param[in] dp disk partition object
454 * @param[in] cr assert if O_CREAT | O_EXCL should be passed to open()
456 * @return operation status
458 * @retval -1 volume header doesn't exist
459 * @retval EIO failed to write volume header
464 _VWriteVolumeDiskHeader(VolumeDiskHeader_t * hdr,
465 struct DiskPartition64 * dp,
470 char path[MAXPATHLEN];
472 #ifdef AFS_DEMAND_ATTACH_FS
473 /* prevent racing with VGC scanners reading the vol header while we are
475 code = VPartHeaderLock(dp, READ_LOCK);
479 #endif /* AFS_DEMAND_ATTACH_FS */
483 (void)afs_snprintf(path, sizeof(path),
485 VPartitionPath(dp), afs_printable_uint32_lu(hdr->id));
486 fd = open(path, flags, 0644);
489 Log("_VWriteVolumeDiskHeader: Couldn't open header for volume %lu, "
490 "error = %d\n", afs_printable_uint32_lu(hdr->id), errno);
491 } else if (write(fd, hdr, sizeof(*hdr)) != sizeof(*hdr)) {
492 Log("_VWriteVolumeDiskHeader: Couldn't write header for volume %lu, "
493 "error = %d\n", afs_printable_uint32_lu(hdr->id), errno);
498 if (close(fd) != 0) {
499 Log("_VWriteVolumeDiskHeader: Error closing header for volume "
500 "%lu, errno %d\n", afs_printable_uint32_lu(hdr->id), errno);
504 #ifdef AFS_DEMAND_ATTACH_FS
505 VPartHeaderUnlock(dp, READ_LOCK);
506 #endif /* AFS_DEMAND_ATTACH_FS */
512 * write an existing volume disk header.
514 * @param[in] hdr volume disk header
515 * @param[in] dp disk partition object
517 * @return operation status
519 * @retval ENOENT volume header doesn't exist
520 * @retval EIO failed to write volume header
523 VWriteVolumeDiskHeader(VolumeDiskHeader_t * hdr,
524 struct DiskPartition64 * dp)
528 #ifdef AFS_DEMAND_ATTACH_FS
529 VolumeDiskHeader_t oldhdr;
530 int delvgc = 0, addvgc = 0;
533 /* first, see if anything with the volume IDs have changed; if so, we
534 * need to update the VGC */
536 code = VReadVolumeDiskHeader(hdr->id, dp, &oldhdr);
537 if (code == 0 && (oldhdr.id != hdr->id || oldhdr.parent != hdr->parent)) {
538 /* the vol id or parent vol id changed; need to delete the VGC entry
539 * for the old vol id/parent, and add the new one */
544 /* couldn't get the old header info; add the new header info to the
545 * VGC in case it hasn't been added yet */
549 #endif /* AFS_DEMAND_ATTACH_FS */
551 code = _VWriteVolumeDiskHeader(hdr, dp, 0);
556 #ifdef AFS_DEMAND_ATTACH_FS
558 memset(&res, 0, sizeof(res));
559 code = FSYNC_VGCDel(dp->name, oldhdr.parent, oldhdr.id, FSYNC_WHATEVER, &res);
561 /* unknown vol id is okay; it just further suggests the old header
562 * data was bogus, which is fine since we're trying to fix it */
563 if (code && res.hdr.reason != FSYNC_UNKNOWN_VOLID) {
564 Log("VWriteVolumeDiskHeader: FSYNC_VGCDel(%s, %lu, %lu) "
565 "failed with code %ld reason %ld\n", dp->name,
566 afs_printable_uint32_lu(oldhdr.parent),
567 afs_printable_uint32_lu(oldhdr.id),
568 afs_printable_int32_ld(code),
569 afs_printable_int32_ld(res.hdr.reason));
574 memset(&res, 0, sizeof(res));
575 code = FSYNC_VGCAdd(dp->name, hdr->parent, hdr->id, FSYNC_WHATEVER, &res);
577 Log("VWriteVolumeDiskHeader: FSYNC_VGCAdd(%s, %lu, %lu) "
578 "failed with code %ld reason %ld\n", dp->name,
579 afs_printable_uint32_lu(hdr->parent),
580 afs_printable_uint32_lu(hdr->id),
581 afs_printable_int32_ld(code),
582 afs_printable_int32_ld(res.hdr.reason));
586 #endif /* AFS_DEMAND_ATTACH_FS */
593 * create and write a volume disk header to disk.
595 * @param[in] hdr volume disk header
596 * @param[in] dp disk partition object
598 * @return operation status
600 * @retval EEXIST volume header already exists
601 * @retval EIO failed to write volume header
606 VCreateVolumeDiskHeader(VolumeDiskHeader_t * hdr,
607 struct DiskPartition64 * dp)
610 #ifdef AFS_DEMAND_ATTACH_FS
612 #endif /* AFS_DEMAND_ATTACH_FS */
614 code = _VWriteVolumeDiskHeader(hdr, dp, O_CREAT | O_EXCL);
619 #ifdef AFS_DEMAND_ATTACH_FS
620 memset(&res, 0, sizeof(res));
621 code = FSYNC_VGCAdd(dp->name, hdr->parent, hdr->id, FSYNC_WHATEVER, &res);
623 Log("VCreateVolumeDiskHeader: FSYNC_VGCAdd(%s, %lu, %lu) failed "
624 "with code %ld reason %ld\n", dp->name,
625 afs_printable_uint32_lu(hdr->parent),
626 afs_printable_uint32_lu(hdr->id),
627 afs_printable_int32_ld(code),
628 afs_printable_int32_ld(res.hdr.reason));
630 #endif /* AFS_DEMAND_ATTACH_FS */
638 * destroy a volume disk header.
640 * @param[in] dp disk partition object
641 * @param[in] volid volume id
642 * @param[in] parent parent's volume id, 0 if unknown
644 * @return operation status
647 * @note if parent is 0, the parent volume ID will be looked up from the
650 * @note for non-DAFS, parent is currently ignored
653 VDestroyVolumeDiskHeader(struct DiskPartition64 * dp,
658 char path[MAXPATHLEN];
659 #ifdef AFS_DEMAND_ATTACH_FS
661 #endif /* AFS_DEMAND_ATTACH_FS */
663 (void)afs_snprintf(path, sizeof(path),
665 VPartitionPath(dp), afs_printable_uint32_lu(volid));
668 Log("VDestroyVolumeDiskHeader: Couldn't unlink disk header, error = %d\n", errno);
672 #ifdef AFS_DEMAND_ATTACH_FS
673 memset(&res, 0, sizeof(res));
675 FSSYNC_VGQry_response_t q_res;
677 code = FSYNC_VGCQuery(dp->name, volid, &q_res, &res);
679 Log("VDestroyVolumeDiskHeader: FSYNC_VGCQuery(%s, %lu) failed "
680 "with code %ld, reason %ld\n", dp->name,
681 afs_printable_uint32_lu(volid), afs_printable_int32_ld(code),
682 afs_printable_int32_ld(res.hdr.reason));
689 code = FSYNC_VGCDel(dp->name, parent, volid, FSYNC_WHATEVER, &res);
691 Log("VDestroyVolumeDiskHeader: FSYNC_VGCDel(%s, %lu, %lu) failed "
692 "with code %ld reason %ld\n", dp->name,
693 afs_printable_uint32_lu(parent),
694 afs_printable_uint32_lu(volid),
695 afs_printable_int32_ld(code),
696 afs_printable_int32_ld(res.hdr.reason));
698 #endif /* AFS_DEMAND_ATTACH_FS */
703 #endif /* FSSYNC_BUILD_CLIENT */
706 * handle a single vol header as part of VWalkVolumeHeaders.
708 * @param[in] dp disk partition
709 * @param[in] volfunc function to call when a vol header is successfully read
710 * @param[in] name full path name to the .vol header
711 * @param[out] hdr header data read in from the .vol header
712 * @param[in] locked 1 if the partition headers are locked, 0 otherwise
713 * @param[in] rock the rock to pass to volfunc
715 * @return operation status
717 * @retval -1 fatal error, stop scanning
718 * @retval 1 failed to read header
719 * @retval 2 volfunc callback indicated error after header read
722 _VHandleVolumeHeader(struct DiskPartition64 *dp, VWalkVolFunc volfunc,
723 const char *name, struct VolumeDiskHeader *hdr,
724 int locked, void *rock)
729 if ((fd = afs_open(name, O_RDONLY)) == -1
730 || read(fd, hdr, sizeof(*hdr))
732 || hdr->stamp.magic != VOLUMEHEADERMAGIC) {
740 #ifdef AFSFS_DEMAND_ATTACH_FS
742 VPartHeaderUnlock(dp);
744 #endif /* AFS_DEMAND_ATTACH_FS */
746 if (!error && volfunc) {
747 /* the volume header seems fine; call the caller-supplied
748 * 'we-found-a-volume-header' function */
751 #ifdef AFS_DEMAND_ATTACH_FS
755 #endif /* AFS_DEMAND_ATTACH_FS */
757 error = (*volfunc) (dp, name, hdr, last, rock);
766 #ifdef AFS_DEMAND_ATTACH_FS
767 if (error && !locked) {
769 /* retry reading the volume header under the partition
770 * header lock, just to be safe and ensure we're not
771 * racing something rewriting the vol header */
772 code = VPartHeaderLock(dp, WRITE_LOCK);
774 Log("Error acquiring partition write lock when "
775 "looking at header %s\n", name);
779 return _VHandleVolumeHeader(dp, volfunc, name, hdr, 1, rock);
781 #endif /* AFS_DEMAND_ATTACH_FS */
787 * walk through the list of volume headers on a partition.
789 * This function looks through all of the .vol headers on a partition, reads in
790 * each header, and calls the supplied volfunc function on each one. If the
791 * header cannot be read (or volfunc returns a positive error code), DAFS will
792 * VPartHeaderExLock() and retry. If that fails, or if we are non-DAFS, errfunc
793 * will be called (which typically will unlink the problem volume header).
795 * If volfunc returns a negative error code, walking the partition will stop
796 * and we will return an error immediately.
798 * @param[in] dp partition to walk
799 * @param[in] partpath the path opendir()
800 * @param[in] volfunc the function to call when a header is encountered, or
801 * NULL to just skip over valid headers
802 * @param[in] errfunc the function to call when a problematic header is
803 * encountered, or NULL to just skip over bad headers
804 * @param[in] rock rock for volfunc and errfunc
809 * @return operation status
811 * @retval negative fatal error, walk did not finish
814 VWalkVolumeHeaders(struct DiskPartition64 *dp, const char *partpath,
815 VWalkVolFunc volfunc, VWalkErrFunc errfunc, void *rock)
818 struct dirent *dentry = NULL;
820 struct VolumeDiskHeader diskHeader;
822 dirp = opendir(partpath);
824 Log("VWalkVolumeHeaders: cannot open directory %s\n", partpath);
829 while ((dentry = readdir(dirp))) {
830 char *p = dentry->d_name;
831 p = strrchr(dentry->d_name, '.');
832 if (p != NULL && strcmp(p, VHDREXT) == 0) {
833 char name[VMAXPATHLEN];
835 sprintf(name, "%s/%s", partpath, dentry->d_name);
837 code = _VHandleVolumeHeader(dp, volfunc, name, &diskHeader, -1, rock);
839 /* fatal error, stop walking */
842 if (code && errfunc) {
843 /* error with header; call the caller-supplied vol error
846 struct VolumeDiskHeader *hdr = &diskHeader;
848 /* we failed to read the header at all, so don't pass in
852 (*errfunc) (dp, name, hdr, rock);
866 #ifdef AFS_PTHREAD_ENV
867 # define AFS_LF_LOCK(lf) assert(pthread_mutex_lock(&((lf)->mutex)) == 0)
868 # define AFS_LF_UNLOCK(lf) assert(pthread_mutex_unlock(&((lf)->mutex)) == 0)
870 # define AFS_LF_LOCK(lf)
871 # define AFS_LF_UNLOCK(lf)
872 #endif /* AFS_PTHREAD_ENV */
875 * initialize a struct VLockFile.
877 * @param[in] lf struct VLockFile to initialize
878 * @param[in] path Full path to the file to use for locks. The string contents
882 VLockFileInit(struct VLockFile *lf, const char *path)
884 memset(lf, 0, sizeof(*lf));
885 lf->path = strdup(path);
887 #ifdef AFS_PTHREAD_ENV
888 assert(pthread_mutex_init(&lf->mutex, NULL) == 0);
889 #endif /* AFS_PTHREAD_ENV */
894 _VOpenPath(const char *path)
898 handle = CreateFile(path,
899 GENERIC_READ | GENERIC_WRITE,
900 FILE_SHARE_READ | FILE_SHARE_WRITE,
903 FILE_ATTRIBUTE_HIDDEN,
905 if (handle == INVALID_HANDLE_VALUE) {
913 _VLockFd(FD_t handle, afs_uint32 offset, int locktype, int nonblock)
918 if (locktype == WRITE_LOCK) {
919 flags |= LOCKFILE_EXCLUSIVE_LOCK;
922 flags |= LOCKFILE_FAIL_IMMEDIATELY;
925 memset(&lap, 0, sizeof(lap));
928 if (!LockFileEx(handle, flags, 0, 1, 0, &lap)) {
929 if (GetLastError() == ERROR_LOCK_VIOLATION) {
939 _VUnlockFd(struct VLockFile *lf, afs_uint32 offset)
943 memset(&lap, 0, sizeof(lap));
946 UnlockFileEx(lf->fd, 0, 1, 0, &lap);
950 _VCloseFd(struct VLockFile *lf)
955 #else /* !AFS_NT40_ENV */
958 * open a file on the local filesystem suitable for locking
960 * @param[in] path abs path of the file to open
962 * @return file descriptor
963 * @retval INVALID_FD failure opening file
966 _VOpenPath(const char *path)
970 fd = open(path, O_RDWR | O_CREAT, 0660);
978 * lock an offset in a file descriptor.
980 * @param[in] fd file descriptor to lock
981 * @param[in] offset offset in file to lock
982 * @param[in] locktype READ_LOCK or WRITE_LOCK
983 * @param[in] nonblock 1 to fail immediately, 0 to wait to acquire lock
985 * @return operation status
987 * @retval EBUSY someone else is holding a conflicting lock and nonblock=1 was
989 * @retval EIO error acquiring file lock
992 _VLockFd(int fd, afs_uint32 offset, int locktype, int nonblock)
994 int l_type = F_WRLCK;
998 if (locktype == READ_LOCK) {
1005 sf.l_start = offset;
1008 sf.l_whence = SEEK_SET;
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 */
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));
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,
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));
1037 * close a file descriptor used for file locking.
1039 * @param[in] fd file descriptor to close
1045 Log("_VCloseFd: error %d closing fd %d\n",
1051 * unlock a file offset in a file descriptor.
1053 * @param[in] fd file descriptor to unlock
1054 * @param[in] offset offset to unlock
1057 _VUnlockFd(int fd, afs_uint32 offset)
1061 sf.l_start = offset;
1063 sf.l_type = F_UNLCK;
1064 sf.l_whence = SEEK_SET;
1066 if (fcntl(fd, F_SETLK, &sf)) {
1067 Log("_VUnlockFd: fcntl failed with error %d when trying to unlock "
1068 "fd %d\n", errno, fd);
1071 #endif /* !AFS_NT40_ENV */
1074 * reinitialize a struct VLockFile.
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
1082 * @param[in] lf struct VLockFile to reinit
1084 * @pre nobody is waiting for a lock on this lockfile or otherwise using
1085 * this lockfile at all
1088 VLockFileReinit(struct VLockFile *lf)
1090 #ifdef AFS_PTHREAD_ENV
1091 assert(pthread_mutex_lock(&lf->mutex) == 0);
1092 #endif /* AFS_PTHREAD_ENV */
1094 if (lf->fd != INVALID_FD) {
1096 lf->fd = INVALID_FD;
1101 #ifdef AFS_PTHREAD_ENV
1102 assert(pthread_mutex_unlock(&lf->mutex) == 0);
1103 #endif /* AFS_PTHREAD_ENV */
1107 * lock a file on disk for the process.
1109 * @param[in] lf the struct VLockFile representing the file to lock
1110 * @param[in] offset the offset in the file to lock
1111 * @param[in] locktype READ_LOCK or WRITE_LOCK
1112 * @param[in] nonblock 0 to wait for conflicting locks to clear before
1113 * obtaining the lock; 1 to fail immediately if a
1114 * conflicting lock is held by someone else
1116 * @return operation status
1118 * @retval EBUSY someone else is holding a conflicting lock and nonblock=1 was
1120 * @retval EIO error acquiring file lock
1124 * @note do not try to lock/unlock the same offset in the same file from
1125 * different threads; use VGetDiskLock to protect threads from each other in
1126 * addition to other processes
1129 VLockFileLock(struct VLockFile *lf, afs_uint32 offset, int locktype, int nonblock)
1133 assert(locktype == READ_LOCK || locktype == WRITE_LOCK);
1137 if (lf->fd == INVALID_FD) {
1138 lf->fd = _VOpenPath(lf->path);
1139 if (lf->fd == INVALID_FD) {
1149 code = _VLockFd(lf->fd, offset, locktype, nonblock);
1153 if (--lf->refcount < 1) {
1155 lf->fd = INVALID_FD;
1164 VLockFileUnlock(struct VLockFile *lf, afs_uint32 offset)
1168 assert(lf->fd != INVALID_FD);
1170 if (--lf->refcount < 1) {
1172 lf->fd = INVALID_FD;
1174 _VUnlockFd(lf->fd, offset);
1180 #ifdef AFS_DEMAND_ATTACH_FS
1183 * initialize a struct VDiskLock.
1185 * @param[in] dl struct VDiskLock to initialize
1186 * @param[in] lf the struct VLockFile to associate with this disk lock
1189 VDiskLockInit(struct VDiskLock *dl, struct VLockFile *lf, afs_uint32 offset)
1192 memset(dl, 0, sizeof(*dl));
1193 Lock_Init(&dl->rwlock);
1194 assert(pthread_mutex_init(&dl->mutex, NULL) == 0);
1195 assert(pthread_cond_init(&dl->cv, NULL) == 0);
1197 dl->offset = offset;
1201 * acquire a lock on a file on local disk.
1203 * @param[in] dl the VDiskLock structure corresponding to the file on disk
1204 * @param[in] locktype READ_LOCK if you want a read lock, or WRITE_LOCK if
1205 * you want a write lock
1206 * @param[in] nonblock 0 to wait for conflicting locks to clear before
1207 * obtaining the lock; 1 to fail immediately if a
1208 * conflicting lock is held by someone else
1210 * @return operation status
1212 * @retval EBUSY someone else is holding a conflicting lock and nonblock=1 was
1214 * @retval EIO error acquiring file lock
1218 * @note while normal fcntl-y locks on Unix systems generally only work per-
1219 * process, this interface also deals with locks between threads in the
1220 * process in addition to different processes acquiring the lock
1223 VGetDiskLock(struct VDiskLock *dl, int locktype, int nonblock)
1226 assert(locktype == READ_LOCK || locktype == WRITE_LOCK);
1229 if (locktype == READ_LOCK) {
1230 ObtainReadLockNoBlock(&dl->rwlock, code);
1232 ObtainWriteLockNoBlock(&dl->rwlock, code);
1239 } else if (locktype == READ_LOCK) {
1240 ObtainReadLock(&dl->rwlock);
1242 ObtainWriteLock(&dl->rwlock);
1245 assert(pthread_mutex_lock(&dl->mutex) == 0);
1247 if ((dl->flags & VDISKLOCK_ACQUIRING)) {
1248 /* Some other thread is waiting to acquire an fs lock. If nonblock=1,
1249 * we can return immediately, since we know we'll need to wait to
1250 * acquire. Otherwise, wait for the other thread to finish acquiring
1255 while ((dl->flags & VDISKLOCK_ACQUIRING)) {
1256 assert(pthread_cond_wait(&dl->cv, &dl->mutex) == 0);
1261 if (code == 0 && !(dl->flags & VDISKLOCK_ACQUIRED)) {
1262 /* no other thread holds the lock on the actual file; so grab one */
1264 /* first try, don't block on the lock to see if we can get it without
1266 code = VLockFileLock(dl->lockfile, dl->offset, locktype, 1);
1268 if (code == EBUSY && !nonblock) {
1270 /* mark that we are waiting on the fs lock */
1271 dl->flags |= VDISKLOCK_ACQUIRING;
1273 assert(pthread_mutex_unlock(&dl->mutex) == 0);
1274 code = VLockFileLock(dl->lockfile, dl->offset, locktype, nonblock);
1275 assert(pthread_mutex_lock(&dl->mutex) == 0);
1277 dl->flags &= ~VDISKLOCK_ACQUIRING;
1280 dl->flags |= VDISKLOCK_ACQUIRED;
1283 assert(pthread_cond_broadcast(&dl->cv) == 0);
1288 if (locktype == READ_LOCK) {
1289 ReleaseReadLock(&dl->rwlock);
1291 ReleaseWriteLock(&dl->rwlock);
1294 /* successfully got the lock, so inc the number of unlocks we need
1295 * to do before we can unlock the actual file */
1299 assert(pthread_mutex_unlock(&dl->mutex) == 0);
1305 * release a lock on a file on local disk.
1307 * @param[in] dl the struct VDiskLock to release
1308 * @param[in] locktype READ_LOCK if you are unlocking a read lock, or
1309 * WRITE_LOCK if you are unlocking a write lock
1311 * @return operation status
1315 VReleaseDiskLock(struct VDiskLock *dl, int locktype)
1317 assert(locktype == READ_LOCK || locktype == WRITE_LOCK);
1319 assert(pthread_mutex_lock(&dl->mutex) == 0);
1320 assert(dl->lockers > 0);
1322 if (--dl->lockers < 1) {
1323 /* no threads are holding this lock anymore, so we can release the
1324 * actual disk lock */
1325 VLockFileUnlock(dl->lockfile, dl->offset);
1326 dl->flags &= ~VDISKLOCK_ACQUIRED;
1329 assert(pthread_mutex_unlock(&dl->mutex) == 0);
1331 if (locktype == READ_LOCK) {
1332 ReleaseReadLock(&dl->rwlock);
1334 ReleaseWriteLock(&dl->rwlock);
1338 #endif /* AFS_DEMAND_ATTACH_FS */