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/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"
63 #include <sys/lockf.h>
65 #if defined(AFS_SUN5_ENV) || defined(AFS_NT40_ENV) || defined(AFS_LINUX20_ENV)
72 #define afs_open open64
73 #else /* !O_LARGEFILE */
75 #endif /* !O_LARGEFILE */
77 /*@printflike@*/ extern void Log(const char *format, ...);
79 #define nFILES (sizeof (stuff)/sizeof(struct stuff))
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 */
85 #ifdef FSSYNC_BUILD_CLIENT
87 RemoveInodes(Device dev, VolumeId vid)
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.
95 IH_INIT(handle, dev, vid, -1);
96 for (i = 0; i < nFILES; i++) {
97 Inode inode = *stuff[i].inode;
99 IH_DEC(handle, inode, vid);
105 VCreateVolume(Error * ec, char *partname, VolId volumeId, VolId parentId)
106 { /* Should be the same as volumeId if there is
110 retVal = VCreateVolume_r(ec, partname, volumeId, parentId);
116 VCreateVolume_r(Error * ec, char *partname, VolId volumeId, VolId parentId)
117 { /* Should be the same as volumeId if there is
121 char headerName[VMAXPATHLEN], volumePath[VMAXPATHLEN];
123 struct DiskPartition64 *partition;
124 struct VolumeDiskHeader diskHeader;
130 # ifdef AFS_DEMAND_ATTACH_FS
132 # endif /* AFS_DEMAND_ATTACH_FS */
135 memset(&vol, 0, sizeof(vol));
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 */
142 /* Initialize handle for error case below. */
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);
151 #if defined(NEARINODE_HINT)
152 nearInodeHash(volumeId, nearInode);
153 nearInode %= partition->f_files;
155 VGetVolumePath(ec, vol.id, &part, &name);
156 if (*ec == VNOVOL || !strcmp(partition->name, part)) {
157 /* this case is ok */
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) {
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);
175 Log("VCreateVolume: vol %lu already locked by someone else\n",
176 afs_printable_uint32_lu(volumeId));
180 # else /* AFS_DEMAND_ATTACH_FS */
181 VLockPartition_r(partname);
182 # endif /* !AFS_DEMAND_ATTACH_FS */
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/%s",
194 VPartitionPath(partition), headerName);
195 rc = stat(volumePath, &st);
196 if (rc == 0 || errno != ENOENT) {
198 Log("VCreateVolume: Header file %s already exists!\n",
202 Log("VCreateVolume: Error %d trying to stat header file %s\n",
208 device = partition->device;
210 for (i = 0; i < nFILES; i++) {
211 register struct stuff *p = &stuff[i];
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) {
221 /* Increment the reference count instead. */
226 *(p->inode) = nt_MakeSpecIno(VI_LINKTABLE);
228 *(p->inode) = namei_MakeSpecIno(vol.parentId, VI_LINKTABLE);
230 IH_INIT(lh, device, parentId, *(p->inode));
236 code = IH_INC(lh, *(p->inode), parentId);
237 FDH_REALLYCLOSE(fdP);
246 IH_CREATE(NULL, device, VPartitionPath(partition), nearInode,
247 vol.id, INODESPECIAL, p->inodeType, vol.parentId);
250 if (!VALID_INO(*(p->inode))) {
251 Log("VCreateVolume: Problem creating %s file associated with volume header %s\n", p->description, volumePath);
255 RemoveInodes(device, vol.id);
259 VDestroyVolumeDiskHeader(partition, volumeId, parentId);
261 # ifdef AFS_DEMAND_ATTACH_FS
263 VUnlockVolumeById(volumeId, partition);
265 # endif /* AFS_DEMAND_ATTACH_FS */
268 IH_INIT(handle, device, vol.parentId, *(p->inode));
269 fdP = IH_OPEN(handle);
271 Log("VCreateVolume: Problem iopen inode %s (err=%d)\n",
272 PrintInode(NULL, *(p->inode)), errno);
275 if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
276 Log("VCreateVolume: Problem lseek inode %s (err=%d)\n",
277 PrintInode(NULL, *(p->inode)), errno);
278 FDH_REALLYCLOSE(fdP);
281 if (FDH_WRITE(fdP, (char *)&p->stamp, sizeof(p->stamp)) !=
283 Log("VCreateVolume: Problem writing to inode %s (err=%d)\n",
284 PrintInode(NULL, *(p->inode)), errno);
285 FDH_REALLYCLOSE(fdP);
288 FDH_REALLYCLOSE(fdP);
290 nearInode = *(p->inode);
293 IH_INIT(handle, device, vol.parentId, tempHeader.volumeInfo);
294 fdP = IH_OPEN(handle);
296 Log("VCreateVolume: Problem iopen inode %s (err=%d)\n",
297 PrintInode(NULL, tempHeader.volumeInfo), errno);
300 if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
301 Log("VCreateVolume: Problem lseek inode %s (err=%d)\n",
302 PrintInode(NULL, tempHeader.volumeInfo), errno);
303 FDH_REALLYCLOSE(fdP);
306 if (FDH_WRITE(fdP, (char *)&vol, sizeof(vol)) != sizeof(vol)) {
307 Log("VCreateVolume: Problem writing to inode %s (err=%d)\n",
308 PrintInode(NULL, tempHeader.volumeInfo), errno);
309 FDH_REALLYCLOSE(fdP);
315 VolumeHeaderToDisk(&diskHeader, &tempHeader);
316 rc = VCreateVolumeDiskHeader(&diskHeader, partition);
318 Log("VCreateVolume: Error %d trying to write volume header for "
319 "volume %u on partition %s; volume not created\n", rc,
320 vol.id, VPartitionPath(partition));
327 # ifdef AFS_DEMAND_ATTACH_FS
329 VUnlockVolumeById(volumeId, partition);
331 # endif /* AFS_DEMAND_ATTACH_FS */
332 return (VAttachVolumeByName_r(ec, partname, headerName, V_SECRETLY));
334 #endif /* FSSYNC_BUILD_CLIENT */
338 AssignVolumeName(register VolumeDiskData * vol, char *name, char *ext)
341 AssignVolumeName_r(vol, name, ext);
346 AssignVolumeName_r(register VolumeDiskData * vol, char *name, char *ext)
349 strncpy(vol->name, name, VNAMESIZE - 1);
350 vol->name[VNAMESIZE - 1] = '\0';
351 dot = strrchr(vol->name, '.');
352 if (dot && (strcmp(dot, ".backup") == 0 || strcmp(dot, ".readonly") == 0))
355 strncat(vol->name, ext, VNAMESIZE - 1 - strlen(vol->name));
359 CopyVolumeHeader_r(VolumeDiskData * from, VolumeDiskData * to)
361 /* The id and parentId fields are not copied; these are inviolate--the to volume
362 * is assumed to have already been created. The id's cannot be changed once
363 * creation has taken place, since they are embedded in the various inodes associated
364 * with the volume. The copydate is also inviolate--it always reflects the time
365 * this volume was created (compare with the creation date--the creation date of
366 * a backup volume is the creation date of the original parent, because the backup
367 * is used to backup the parent volume). */
371 parent = to->parentId;
372 copydate = to->copyDate;
373 memcpy(to, from, sizeof(*from));
375 to->parentId = parent;
376 to->copyDate = copydate;
377 to->destroyMe = DESTROY_ME; /* Caller must always clear this!!! */
378 to->stamp.magic = VOLUMEINFOMAGIC;
379 to->stamp.version = VOLUMEINFOVERSION;
384 CopyVolumeHeader(VolumeDiskData * from, VolumeDiskData * to)
389 code = CopyVolumeHeader_r(from, to);
395 ClearVolumeStats(register VolumeDiskData * vol)
398 ClearVolumeStats_r(vol);
403 ClearVolumeStats_r(register VolumeDiskData * vol)
405 memset(vol->weekUse, 0, sizeof(vol->weekUse));
411 * read an existing volume disk header.
413 * @param[in] volid volume id
414 * @param[in] dp disk partition object
415 * @param[out] hdr volume disk header or NULL
417 * @note if hdr is NULL, this is essentially an existence test for the vol
420 * @return operation status
422 * @retval -1 volume header doesn't exist
423 * @retval EIO failed to read volume header
428 VReadVolumeDiskHeader(VolumeId volid,
429 struct DiskPartition64 * dp,
430 VolumeDiskHeader_t * hdr)
434 char path[MAXPATHLEN];
436 (void)afs_snprintf(path, sizeof(path),
438 VPartitionPath(dp), afs_printable_uint32_lu(volid));
439 fd = open(path, O_RDONLY);
441 Log("VReadVolumeDiskHeader: Couldn't open header for volume %lu (errno %d).\n",
442 afs_printable_uint32_lu(volid), errno);
445 } else if (hdr && read(fd, hdr, sizeof(*hdr)) != sizeof(*hdr)) {
446 Log("VReadVolumeDiskHeader: Couldn't read header for volume %lu.\n",
447 afs_printable_uint32_lu(volid));
457 #ifdef FSSYNC_BUILD_CLIENT
459 * write an existing volume disk header.
461 * @param[in] hdr volume disk header
462 * @param[in] dp disk partition object
463 * @param[in] cr assert if O_CREAT | O_EXCL should be passed to open()
465 * @return operation status
467 * @retval -1 volume header doesn't exist
468 * @retval EIO failed to write volume header
473 _VWriteVolumeDiskHeader(VolumeDiskHeader_t * hdr,
474 struct DiskPartition64 * dp,
479 char path[MAXPATHLEN];
481 #ifdef AFS_DEMAND_ATTACH_FS
482 /* prevent racing with VGC scanners reading the vol header while we are
484 code = VPartHeaderLock(dp, READ_LOCK);
488 #endif /* AFS_DEMAND_ATTACH_FS */
492 (void)afs_snprintf(path, sizeof(path),
494 VPartitionPath(dp), afs_printable_uint32_lu(hdr->id));
495 fd = open(path, flags, 0644);
498 Log("_VWriteVolumeDiskHeader: Couldn't open header for volume %lu, "
499 "error = %d\n", afs_printable_uint32_lu(hdr->id), errno);
500 } else if (write(fd, hdr, sizeof(*hdr)) != sizeof(*hdr)) {
501 Log("_VWriteVolumeDiskHeader: Couldn't write header for volume %lu, "
502 "error = %d\n", afs_printable_uint32_lu(hdr->id), errno);
507 if (close(fd) != 0) {
508 Log("_VWriteVolumeDiskHeader: Error closing header for volume "
509 "%lu, errno %d\n", afs_printable_uint32_lu(hdr->id), errno);
513 #ifdef AFS_DEMAND_ATTACH_FS
514 VPartHeaderUnlock(dp, READ_LOCK);
515 #endif /* AFS_DEMAND_ATTACH_FS */
521 * write an existing volume disk header.
523 * @param[in] hdr volume disk header
524 * @param[in] dp disk partition object
526 * @return operation status
528 * @retval ENOENT volume header doesn't exist
529 * @retval EIO failed to write volume header
532 VWriteVolumeDiskHeader(VolumeDiskHeader_t * hdr,
533 struct DiskPartition64 * dp)
537 #ifdef AFS_DEMAND_ATTACH_FS
538 VolumeDiskHeader_t oldhdr;
539 int delvgc = 0, addvgc = 0;
542 /* first, see if anything with the volume IDs have changed; if so, we
543 * need to update the VGC */
545 code = VReadVolumeDiskHeader(hdr->id, dp, &oldhdr);
546 if (code == 0 && (oldhdr.id != hdr->id || oldhdr.parent != hdr->parent)) {
547 /* the vol id or parent vol id changed; need to delete the VGC entry
548 * for the old vol id/parent, and add the new one */
553 /* couldn't get the old header info; add the new header info to the
554 * VGC in case it hasn't been added yet */
558 #endif /* AFS_DEMAND_ATTACH_FS */
560 code = _VWriteVolumeDiskHeader(hdr, dp, 0);
565 #ifdef AFS_DEMAND_ATTACH_FS
567 memset(&res, 0, sizeof(res));
568 code = FSYNC_VGCDel(dp->name, oldhdr.parent, oldhdr.id, FSYNC_WHATEVER, &res);
570 /* unknown vol id is okay; it just further suggests the old header
571 * data was bogus, which is fine since we're trying to fix it */
572 if (code && res.hdr.reason != FSYNC_UNKNOWN_VOLID) {
573 Log("VWriteVolumeDiskHeader: FSYNC_VGCDel(%s, %lu, %lu) "
574 "failed with code %ld reason %ld\n", dp->name,
575 afs_printable_uint32_lu(oldhdr.parent),
576 afs_printable_uint32_lu(oldhdr.id),
577 afs_printable_int32_ld(code),
578 afs_printable_int32_ld(res.hdr.reason));
583 memset(&res, 0, sizeof(res));
584 code = FSYNC_VGCAdd(dp->name, hdr->parent, hdr->id, FSYNC_WHATEVER, &res);
586 Log("VWriteVolumeDiskHeader: FSYNC_VGCAdd(%s, %lu, %lu) "
587 "failed with code %ld reason %ld\n", dp->name,
588 afs_printable_uint32_lu(hdr->parent),
589 afs_printable_uint32_lu(hdr->id),
590 afs_printable_int32_ld(code),
591 afs_printable_int32_ld(res.hdr.reason));
595 #endif /* AFS_DEMAND_ATTACH_FS */
602 * create and write a volume disk header to disk.
604 * @param[in] hdr volume disk header
605 * @param[in] dp disk partition object
607 * @return operation status
609 * @retval EEXIST volume header already exists
610 * @retval EIO failed to write volume header
615 VCreateVolumeDiskHeader(VolumeDiskHeader_t * hdr,
616 struct DiskPartition64 * dp)
619 #ifdef AFS_DEMAND_ATTACH_FS
621 #endif /* AFS_DEMAND_ATTACH_FS */
623 code = _VWriteVolumeDiskHeader(hdr, dp, O_CREAT | O_EXCL);
628 #ifdef AFS_DEMAND_ATTACH_FS
629 memset(&res, 0, sizeof(res));
630 code = FSYNC_VGCAdd(dp->name, hdr->parent, hdr->id, FSYNC_WHATEVER, &res);
632 Log("VCreateVolumeDiskHeader: FSYNC_VGCAdd(%s, %lu, %lu) failed "
633 "with code %ld reason %ld\n", dp->name,
634 afs_printable_uint32_lu(hdr->parent),
635 afs_printable_uint32_lu(hdr->id),
636 afs_printable_int32_ld(code),
637 afs_printable_int32_ld(res.hdr.reason));
639 #endif /* AFS_DEMAND_ATTACH_FS */
647 * destroy a volume disk header.
649 * @param[in] dp disk partition object
650 * @param[in] volid volume id
651 * @param[in] parent parent's volume id, 0 if unknown
653 * @return operation status
656 * @note if parent is 0, the parent volume ID will be looked up from the
659 * @note for non-DAFS, parent is currently ignored
662 VDestroyVolumeDiskHeader(struct DiskPartition64 * dp,
667 char path[MAXPATHLEN];
668 #ifdef AFS_DEMAND_ATTACH_FS
670 #endif /* AFS_DEMAND_ATTACH_FS */
672 (void)afs_snprintf(path, sizeof(path),
674 VPartitionPath(dp), afs_printable_uint32_lu(volid));
677 Log("VDestroyVolumeDiskHeader: Couldn't unlink disk header, error = %d\n", errno);
681 #ifdef AFS_DEMAND_ATTACH_FS
682 memset(&res, 0, sizeof(res));
684 FSSYNC_VGQry_response_t q_res;
686 code = FSYNC_VGCQuery(dp->name, volid, &q_res, &res);
688 Log("VDestroyVolumeDiskHeader: FSYNC_VGCQuery(%s, %lu) failed "
689 "with code %ld, reason %ld\n", dp->name,
690 afs_printable_uint32_lu(volid), afs_printable_int32_ld(code),
691 afs_printable_int32_ld(res.hdr.reason));
698 code = FSYNC_VGCDel(dp->name, parent, volid, FSYNC_WHATEVER, &res);
700 Log("VDestroyVolumeDiskHeader: FSYNC_VGCDel(%s, %lu, %lu) failed "
701 "with code %ld reason %ld\n", dp->name,
702 afs_printable_uint32_lu(parent),
703 afs_printable_uint32_lu(volid),
704 afs_printable_int32_ld(code),
705 afs_printable_int32_ld(res.hdr.reason));
707 #endif /* AFS_DEMAND_ATTACH_FS */
712 #endif /* FSSYNC_BUILD_CLIENT */
715 * handle a single vol header as part of VWalkVolumeHeaders.
717 * @param[in] dp disk partition
718 * @param[in] volfunc function to call when a vol header is successfully read
719 * @param[in] name full path name to the .vol header
720 * @param[out] hdr header data read in from the .vol header
721 * @param[in] locked 1 if the partition headers are locked, 0 otherwise
722 * @param[in] rock the rock to pass to volfunc
724 * @return operation status
726 * @retval -1 fatal error, stop scanning
727 * @retval 1 failed to read header
728 * @retval 2 volfunc callback indicated error after header read
731 _VHandleVolumeHeader(struct DiskPartition64 *dp, VWalkVolFunc volfunc,
732 const char *name, struct VolumeDiskHeader *hdr,
733 int locked, void *rock)
738 if ((fd = afs_open(name, O_RDONLY)) == -1
739 || read(fd, hdr, sizeof(*hdr))
741 || hdr->stamp.magic != VOLUMEHEADERMAGIC) {
749 #ifdef AFSFS_DEMAND_ATTACH_FS
751 VPartHeaderUnlock(dp);
753 #endif /* AFS_DEMAND_ATTACH_FS */
755 if (!error && volfunc) {
756 /* the volume header seems fine; call the caller-supplied
757 * 'we-found-a-volume-header' function */
760 #ifdef AFS_DEMAND_ATTACH_FS
764 #endif /* AFS_DEMAND_ATTACH_FS */
766 error = (*volfunc) (dp, name, hdr, last, rock);
775 #ifdef AFS_DEMAND_ATTACH_FS
776 if (error && !locked) {
778 /* retry reading the volume header under the partition
779 * header lock, just to be safe and ensure we're not
780 * racing something rewriting the vol header */
781 code = VPartHeaderLock(dp, WRITE_LOCK);
783 Log("Error acquiring partition write lock when "
784 "looking at header %s\n", name);
788 return _VHandleVolumeHeader(dp, volfunc, name, hdr, 1, rock);
790 #endif /* AFS_DEMAND_ATTACH_FS */
796 * walk through the list of volume headers on a partition.
798 * This function looks through all of the .vol headers on a partition, reads in
799 * each header, and calls the supplied volfunc function on each one. If the
800 * header cannot be read (or volfunc returns a positive error code), DAFS will
801 * VPartHeaderExLock() and retry. If that fails, or if we are non-DAFS, errfunc
802 * will be called (which typically will unlink the problem volume header).
804 * If volfunc returns a negative error code, walking the partition will stop
805 * and we will return an error immediately.
807 * @param[in] dp partition to walk
808 * @param[in] partpath the path opendir()
809 * @param[in] volfunc the function to call when a header is encountered, or
810 * NULL to just skip over valid headers
811 * @param[in] errfunc the function to call when a problematic header is
812 * encountered, or NULL to just skip over bad headers
813 * @param[in] rock rock for volfunc and errfunc
818 * @return operation status
820 * @retval negative fatal error, walk did not finish
823 VWalkVolumeHeaders(struct DiskPartition64 *dp, const char *partpath,
824 VWalkVolFunc volfunc, VWalkErrFunc errfunc, void *rock)
827 struct dirent *dentry = NULL;
829 struct VolumeDiskHeader diskHeader;
831 dirp = opendir(partpath);
833 Log("VWalkVolumeHeaders: cannot open directory %s\n", partpath);
838 while ((dentry = readdir(dirp))) {
839 char *p = dentry->d_name;
840 p = strrchr(dentry->d_name, '.');
841 if (p != NULL && strcmp(p, VHDREXT) == 0) {
842 char name[VMAXPATHLEN];
844 sprintf(name, "%s/%s", partpath, dentry->d_name);
846 code = _VHandleVolumeHeader(dp, volfunc, name, &diskHeader, -1, rock);
848 /* fatal error, stop walking */
851 if (code && errfunc) {
852 /* error with header; call the caller-supplied vol error
855 struct VolumeDiskHeader *hdr = &diskHeader;
857 /* we failed to read the header at all, so don't pass in
861 (*errfunc) (dp, name, hdr, rock);
875 #ifdef AFS_PTHREAD_ENV
876 # define AFS_LF_LOCK(lf) assert(pthread_mutex_lock(&((lf)->mutex)) == 0)
877 # define AFS_LF_UNLOCK(lf) assert(pthread_mutex_unlock(&((lf)->mutex)) == 0)
879 # define AFS_LF_LOCK(lf)
880 # define AFS_LF_UNLOCK(lf)
881 #endif /* AFS_PTHREAD_ENV */
884 * initialize a struct VLockFile.
886 * @param[in] lf struct VLockFile to initialize
887 * @param[in] path Full path to the file to use for locks. The string contents
891 VLockFileInit(struct VLockFile *lf, const char *path)
893 memset(lf, 0, sizeof(*lf));
894 lf->path = strdup(path);
896 #ifdef AFS_PTHREAD_ENV
897 assert(pthread_mutex_init(&lf->mutex, NULL) == 0);
898 #endif /* AFS_PTHREAD_ENV */
903 _VOpenPath(const char *path)
907 handle = CreateFile(path,
908 GENERIC_READ | GENERIC_WRITE,
909 FILE_SHARE_READ | FILE_SHARE_WRITE,
912 FILE_ATTRIBUTE_HIDDEN,
914 if (handle == INVALID_HANDLE_VALUE) {
922 _VLockFd(FD_t handle, afs_uint32 offset, int locktype, int nonblock)
927 if (locktype == WRITE_LOCK) {
928 flags |= LOCKFILE_EXCLUSIVE_LOCK;
931 flags |= LOCKFILE_FAIL_IMMEDIATELY;
934 memset(&lap, 0, sizeof(lap));
937 if (!LockFileEx(handle, flags, 0, 1, 0, &lap)) {
938 if (GetLastError() == ERROR_LOCK_VIOLATION) {
948 _VUnlockFd(struct VLockFile *lf, afs_uint32 offset)
952 memset(&lap, 0, sizeof(lap));
955 UnlockFileEx(lf->fd, 0, 1, 0, &lap);
959 _VCloseFd(struct VLockFile *lf)
964 #else /* !AFS_NT40_ENV */
967 * open a file on the local filesystem suitable for locking
969 * @param[in] path abs path of the file to open
971 * @return file descriptor
972 * @retval INVALID_FD failure opening file
975 _VOpenPath(const char *path)
979 fd = open(path, O_RDWR | O_CREAT, 0660);
987 * lock an offset in a file descriptor.
989 * @param[in] fd file descriptor to lock
990 * @param[in] offset offset in file to lock
991 * @param[in] locktype READ_LOCK or WRITE_LOCK
992 * @param[in] nonblock 1 to fail immediately, 0 to wait to acquire lock
994 * @return operation status
996 * @retval EBUSY someone else is holding a conflicting lock and nonblock=1 was
998 * @retval EIO error acquiring file lock
1001 _VLockFd(int fd, afs_uint32 offset, int locktype, int nonblock)
1003 int l_type = F_WRLCK;
1007 if (locktype == READ_LOCK) {
1014 sf.l_start = offset;
1017 sf.l_whence = SEEK_SET;
1019 if (fcntl(fd, cmd, &sf)) {
1020 if (nonblock && (errno == EACCES || errno == EAGAIN)) {
1021 /* We asked for a nonblocking lock, and it was already locked */
1023 if (fcntl(fd, F_GETLK, &sf) != 0 || sf.l_pid == 0) {
1024 Log("_VLockFd: fcntl failed with error %d when trying to "
1025 "query the conflicting lock for fd %d (locktype=%d, "
1026 "offset=%lu)\n", errno, fd, locktype,
1027 afs_printable_uint32_lu(offset));
1029 Log("_VLockFd: conflicting lock held on fd %d, offset %lu by "
1030 "pid %ld (locktype=%d)\n", fd,
1031 afs_printable_uint32_lu(offset), (long int)sf.l_pid,
1036 Log("_VLockFd: fcntl failed with error %d when trying to lock "
1037 "fd %d (locktype=%d, offset=%lu)\n", errno, fd, locktype,
1038 afs_printable_uint32_lu(offset));
1046 * close a file descriptor used for file locking.
1048 * @param[in] fd file descriptor to close
1054 Log("_VCloseFd: error %d closing fd %d\n",
1060 * unlock a file offset in a file descriptor.
1062 * @param[in] fd file descriptor to unlock
1063 * @param[in] offset offset to unlock
1066 _VUnlockFd(int fd, afs_uint32 offset)
1070 sf.l_start = offset;
1072 sf.l_type = F_UNLCK;
1073 sf.l_whence = SEEK_SET;
1075 if (fcntl(fd, F_SETLK, &sf)) {
1076 Log("_VUnlockFd: fcntl failed with error %d when trying to unlock "
1077 "fd %d\n", errno, fd);
1080 #endif /* !AFS_NT40_ENV */
1083 * reinitialize a struct VLockFile.
1085 * Use this to close the lock file (unlocking any locks in it), and effectively
1086 * restore lf to the state it was in when it was initialized. This is the same
1087 * as unlocking all of the locks on the file, without having to remember what
1088 * all of the locks were. Do not unlock previously held locks after calling
1091 * @param[in] lf struct VLockFile to reinit
1093 * @pre nobody is waiting for a lock on this lockfile or otherwise using
1094 * this lockfile at all
1097 VLockFileReinit(struct VLockFile *lf)
1099 #ifdef AFS_PTHREAD_ENV
1100 assert(pthread_mutex_lock(&lf->mutex) == 0);
1101 #endif /* AFS_PTHREAD_ENV */
1103 if (lf->fd != INVALID_FD) {
1105 lf->fd = INVALID_FD;
1110 #ifdef AFS_PTHREAD_ENV
1111 assert(pthread_mutex_unlock(&lf->mutex) == 0);
1112 #endif /* AFS_PTHREAD_ENV */
1116 * lock a file on disk for the process.
1118 * @param[in] lf the struct VLockFile representing the file to lock
1119 * @param[in] offset the offset in the file to lock
1120 * @param[in] locktype READ_LOCK or WRITE_LOCK
1121 * @param[in] nonblock 0 to wait for conflicting locks to clear before
1122 * obtaining the lock; 1 to fail immediately if a
1123 * conflicting lock is held by someone else
1125 * @return operation status
1127 * @retval EBUSY someone else is holding a conflicting lock and nonblock=1 was
1129 * @retval EIO error acquiring file lock
1133 * @note do not try to lock/unlock the same offset in the same file from
1134 * different threads; use VGetDiskLock to protect threads from each other in
1135 * addition to other processes
1138 VLockFileLock(struct VLockFile *lf, afs_uint32 offset, int locktype, int nonblock)
1142 assert(locktype == READ_LOCK || locktype == WRITE_LOCK);
1146 if (lf->fd == INVALID_FD) {
1147 lf->fd = _VOpenPath(lf->path);
1148 if (lf->fd == INVALID_FD) {
1158 code = _VLockFd(lf->fd, offset, locktype, nonblock);
1162 if (--lf->refcount < 1) {
1164 lf->fd = INVALID_FD;
1173 VLockFileUnlock(struct VLockFile *lf, afs_uint32 offset)
1177 assert(lf->fd != INVALID_FD);
1179 if (--lf->refcount < 1) {
1181 lf->fd = INVALID_FD;
1183 _VUnlockFd(lf->fd, offset);
1189 #ifdef AFS_DEMAND_ATTACH_FS
1192 * initialize a struct VDiskLock.
1194 * @param[in] dl struct VDiskLock to initialize
1195 * @param[in] lf the struct VLockFile to associate with this disk lock
1198 VDiskLockInit(struct VDiskLock *dl, struct VLockFile *lf, afs_uint32 offset)
1201 memset(dl, 0, sizeof(*dl));
1202 Lock_Init(&dl->rwlock);
1203 assert(pthread_mutex_init(&dl->mutex, NULL) == 0);
1204 assert(pthread_cond_init(&dl->cv, NULL) == 0);
1206 dl->offset = offset;
1210 * acquire a lock on a file on local disk.
1212 * @param[in] dl the VDiskLock structure corresponding to the file on disk
1213 * @param[in] locktype READ_LOCK if you want a read lock, or WRITE_LOCK if
1214 * you want a write lock
1215 * @param[in] nonblock 0 to wait for conflicting locks to clear before
1216 * obtaining the lock; 1 to fail immediately if a
1217 * conflicting lock is held by someone else
1219 * @return operation status
1221 * @retval EBUSY someone else is holding a conflicting lock and nonblock=1 was
1223 * @retval EIO error acquiring file lock
1227 * @note while normal fcntl-y locks on Unix systems generally only work per-
1228 * process, this interface also deals with locks between threads in the
1229 * process in addition to different processes acquiring the lock
1232 VGetDiskLock(struct VDiskLock *dl, int locktype, int nonblock)
1235 assert(locktype == READ_LOCK || locktype == WRITE_LOCK);
1238 if (locktype == READ_LOCK) {
1239 ObtainReadLockNoBlock(&dl->rwlock, code);
1241 ObtainWriteLockNoBlock(&dl->rwlock, code);
1248 } else if (locktype == READ_LOCK) {
1249 ObtainReadLock(&dl->rwlock);
1251 ObtainWriteLock(&dl->rwlock);
1254 assert(pthread_mutex_lock(&dl->mutex) == 0);
1256 if ((dl->flags & VDISKLOCK_ACQUIRING)) {
1257 /* Some other thread is waiting to acquire an fs lock. If nonblock=1,
1258 * we can return immediately, since we know we'll need to wait to
1259 * acquire. Otherwise, wait for the other thread to finish acquiring
1264 while ((dl->flags & VDISKLOCK_ACQUIRING)) {
1265 assert(pthread_cond_wait(&dl->cv, &dl->mutex) == 0);
1270 if (code == 0 && !(dl->flags & VDISKLOCK_ACQUIRED)) {
1271 /* no other thread holds the lock on the actual file; so grab one */
1273 /* first try, don't block on the lock to see if we can get it without
1275 code = VLockFileLock(dl->lockfile, dl->offset, locktype, 1);
1277 if (code == EBUSY && !nonblock) {
1279 /* mark that we are waiting on the fs lock */
1280 dl->flags |= VDISKLOCK_ACQUIRING;
1282 assert(pthread_mutex_unlock(&dl->mutex) == 0);
1283 code = VLockFileLock(dl->lockfile, dl->offset, locktype, nonblock);
1284 assert(pthread_mutex_lock(&dl->mutex) == 0);
1286 dl->flags &= ~VDISKLOCK_ACQUIRING;
1289 dl->flags |= VDISKLOCK_ACQUIRED;
1292 assert(pthread_cond_broadcast(&dl->cv) == 0);
1297 if (locktype == READ_LOCK) {
1298 ReleaseReadLock(&dl->rwlock);
1300 ReleaseWriteLock(&dl->rwlock);
1303 /* successfully got the lock, so inc the number of unlocks we need
1304 * to do before we can unlock the actual file */
1308 assert(pthread_mutex_unlock(&dl->mutex) == 0);
1314 * release a lock on a file on local disk.
1316 * @param[in] dl the struct VDiskLock to release
1317 * @param[in] locktype READ_LOCK if you are unlocking a read lock, or
1318 * WRITE_LOCK if you are unlocking a write lock
1320 * @return operation status
1324 VReleaseDiskLock(struct VDiskLock *dl, int locktype)
1326 assert(locktype == READ_LOCK || locktype == WRITE_LOCK);
1328 assert(pthread_mutex_lock(&dl->mutex) == 0);
1329 assert(dl->lockers > 0);
1331 if (--dl->lockers < 1) {
1332 /* no threads are holding this lock anymore, so we can release the
1333 * actual disk lock */
1334 VLockFileUnlock(dl->lockfile, dl->offset);
1335 dl->flags &= ~VDISKLOCK_ACQUIRED;
1338 assert(pthread_mutex_unlock(&dl->mutex) == 0);
1340 if (locktype == READ_LOCK) {
1341 ReleaseReadLock(&dl->rwlock);
1343 ReleaseWriteLock(&dl->rwlock);
1347 #endif /* AFS_DEMAND_ATTACH_FS */