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 #include <afs/afs_assert.h>
37 #include <afs/afsint.h>
39 #include <afs/errors.h>
42 #include <afs/afssyscalls.h>
44 #include <afs/afsutil.h>
51 #include "volume_inline.h"
52 #include "partition.h"
53 #include "viceinode.h"
55 #include "volinodes.h"
56 #include "vol_prototypes.h"
60 #include <sys/lockf.h>
62 #if defined(AFS_SUN5_ENV) || defined(AFS_NT40_ENV) || defined(AFS_LINUX20_ENV)
69 #define afs_open open64
70 #else /* !O_LARGEFILE */
72 #endif /* !O_LARGEFILE */
75 /* Note: the volume creation functions herein leave the destroyMe flag in the
76 volume header ON: this means that the volumes will not be attached by the
77 file server and WILL BE DESTROYED the next time a system salvage is performed */
79 #ifdef FSSYNC_BUILD_CLIENT
81 RemoveInodes(struct afs_inode_info *stuff, Device dev, VolumeId vid)
86 /* This relies on the fact that IDEC only needs the device and NT only
87 * needs the dev and vid to decrement volume special files.
89 IH_INIT(handle, dev, vid, -1);
90 for (i = 0; i < MAXINODETYPE; i++) {
91 Inode inode = *stuff[i].inode;
93 IH_DEC(handle, inode, vid);
99 VCreateVolume(Error * ec, char *partname, VolId volumeId, VolId parentId)
100 { /* Should be the same as volumeId if there is
104 retVal = VCreateVolume_r(ec, partname, volumeId, parentId);
110 VCreateVolume_r(Error * ec, char *partname, VolId volumeId, VolId parentId)
111 { /* Should be the same as volumeId if there is
115 char headerName[VMAXPATHLEN], volumePath[VMAXPATHLEN];
117 struct DiskPartition64 *partition;
118 struct VolumeDiskHeader diskHeader;
124 struct VolumeHeader tempHeader;
125 struct afs_inode_info stuff[MAXINODETYPE];
127 # ifdef AFS_DEMAND_ATTACH_FS
129 # endif /* AFS_DEMAND_ATTACH_FS */
131 init_inode_info(&tempHeader, stuff);
134 memset(&vol, 0, sizeof(vol));
136 vol.parentId = parentId;
137 vol.copyDate = time(0); /* The only date which really means when this
138 * @i(instance) of this volume was created.
139 * Creation date does not mean this */
141 /* Initialize handle for error case below. */
144 /* Verify that the parition is valid before writing to it. */
145 if (!(partition = VGetPartition_r(partname, 0))) {
146 Log("VCreateVolume: partition %s is not in service.\n", partname);
150 #if defined(NEARINODE_HINT)
151 nearInodeHash(volumeId, nearInode);
152 nearInode %= partition->f_files;
154 VGetVolumePath(ec, vol.id, &part, &name);
155 if (*ec == VNOVOL || !strcmp(partition->name, part)) {
156 /* this case is ok */
158 /* return EXDEV if it's a clone to an alternate partition
159 * otherwise assume it's a move */
160 if (vol.parentId != vol.id) {
167 # ifdef AFS_DEMAND_ATTACH_FS
168 /* volume doesn't exist yet, but we must lock it to try to prevent something
169 * else from reading it when we're e.g. half way through creating it (or
170 * something tries to create the same volume at the same time) */
171 locktype = VVolLockType(V_VOLUPD, 1);
172 rc = VLockVolumeByIdNB(volumeId, partition, locktype);
174 Log("VCreateVolume: vol %lu already locked by someone else\n",
175 afs_printable_uint32_lu(volumeId));
179 # else /* AFS_DEMAND_ATTACH_FS */
180 VLockPartition_r(partname);
181 # endif /* !AFS_DEMAND_ATTACH_FS */
183 memset(&tempHeader, 0, sizeof(tempHeader));
184 tempHeader.stamp.magic = VOLUMEHEADERMAGIC;
185 tempHeader.stamp.version = VOLUMEHEADERVERSION;
186 tempHeader.id = vol.id;
187 tempHeader.parent = vol.parentId;
188 vol.stamp.magic = VOLUMEINFOMAGIC;
189 vol.stamp.version = VOLUMEINFOVERSION;
190 vol.destroyMe = DESTROY_ME;
191 (void)afs_snprintf(headerName, sizeof headerName, VFORMAT, afs_printable_uint32_lu(vol.id));
192 (void)afs_snprintf(volumePath, sizeof volumePath, "%s/%s",
193 VPartitionPath(partition), headerName);
194 rc = stat(volumePath, &st);
195 if (rc == 0 || errno != ENOENT) {
197 Log("VCreateVolume: Header file %s already exists!\n",
201 Log("VCreateVolume: Error %d trying to stat header file %s\n",
207 device = partition->device;
209 for (i = 0; i < MAXINODETYPE; i++) {
210 struct afs_inode_info *p = &stuff[i];
215 IH_CREATE(NULL, device, VPartitionPath(partition), nearInode,
216 (p->inodeType == VI_LINKTABLE) ? vol.parentId : vol.id,
217 INODESPECIAL, p->inodeType, vol.parentId);
218 if (!(VALID_INO(*(p->inode)))) {
219 if (errno == EEXIST && (p->inodeType == VI_LINKTABLE)) {
220 /* Increment the reference count instead. */
225 *(p->inode) = nt_MakeSpecIno(VI_LINKTABLE);
227 *(p->inode) = namei_MakeSpecIno(vol.parentId, VI_LINKTABLE);
229 IH_INIT(lh, device, parentId, *(p->inode));
235 code = IH_INC(lh, *(p->inode), parentId);
236 FDH_REALLYCLOSE(fdP);
245 IH_CREATE(NULL, device, VPartitionPath(partition), nearInode,
246 vol.id, INODESPECIAL, p->inodeType, vol.parentId);
249 if (!VALID_INO(*(p->inode))) {
250 Log("VCreateVolume: Problem creating %s file associated with volume header %s\n", p->description, volumePath);
254 RemoveInodes(stuff, device, vol.id);
258 VDestroyVolumeDiskHeader(partition, volumeId, parentId);
260 # ifdef AFS_DEMAND_ATTACH_FS
262 VUnlockVolumeById(volumeId, partition);
264 # endif /* AFS_DEMAND_ATTACH_FS */
267 IH_INIT(handle, device, vol.parentId, *(p->inode));
268 fdP = IH_OPEN(handle);
270 Log("VCreateVolume: Problem iopen inode %s (err=%d)\n",
271 PrintInode(stmp, *(p->inode)), errno);
274 if (FDH_PWRITE(fdP, (char *)&p->stamp, sizeof(p->stamp), 0) !=
276 Log("VCreateVolume: Problem writing to inode %s (err=%d)\n",
277 PrintInode(stmp, *(p->inode)), errno);
278 FDH_REALLYCLOSE(fdP);
281 FDH_REALLYCLOSE(fdP);
283 nearInode = *(p->inode);
286 IH_INIT(handle, device, vol.parentId, tempHeader.volumeInfo);
287 fdP = IH_OPEN(handle);
289 Log("VCreateVolume: Problem iopen inode %s (err=%d)\n",
290 PrintInode(stmp, tempHeader.volumeInfo), errno);
293 if (FDH_PWRITE(fdP, (char *)&vol, sizeof(vol), 0) != sizeof(vol)) {
294 Log("VCreateVolume: Problem writing to inode %s (err=%d)\n",
295 PrintInode(stmp, tempHeader.volumeInfo), errno);
296 FDH_REALLYCLOSE(fdP);
302 VolumeHeaderToDisk(&diskHeader, &tempHeader);
303 rc = VCreateVolumeDiskHeader(&diskHeader, partition);
305 Log("VCreateVolume: Error %d trying to write volume header for "
306 "volume %u on partition %s; volume not created\n", rc,
307 vol.id, VPartitionPath(partition));
314 # ifdef AFS_DEMAND_ATTACH_FS
316 VUnlockVolumeById(volumeId, partition);
318 # endif /* AFS_DEMAND_ATTACH_FS */
319 return (VAttachVolumeByName_r(ec, partname, headerName, V_SECRETLY));
321 #endif /* FSSYNC_BUILD_CLIENT */
325 AssignVolumeName(VolumeDiskData * vol, char *name, char *ext)
328 AssignVolumeName_r(vol, name, ext);
333 AssignVolumeName_r(VolumeDiskData * vol, char *name, char *ext)
336 strncpy(vol->name, name, VNAMESIZE - 1);
337 vol->name[VNAMESIZE - 1] = '\0';
338 dot = strrchr(vol->name, '.');
339 if (dot && (strcmp(dot, ".backup") == 0 || strcmp(dot, ".readonly") == 0))
342 strncat(vol->name, ext, VNAMESIZE - 1 - strlen(vol->name));
346 CopyVolumeHeader_r(VolumeDiskData * from, VolumeDiskData * to)
348 /* The id and parentId fields are not copied; these are inviolate--the to volume
349 * is assumed to have already been created. The id's cannot be changed once
350 * creation has taken place, since they are embedded in the various inodes associated
351 * with the volume. The copydate is also inviolate--it always reflects the time
352 * this volume was created (compare with the creation date--the creation date of
353 * a backup volume is the creation date of the original parent, because the backup
354 * is used to backup the parent volume). */
358 parent = to->parentId;
359 copydate = to->copyDate;
360 memcpy(to, from, sizeof(*from));
362 to->parentId = parent;
363 to->copyDate = copydate;
364 to->destroyMe = DESTROY_ME; /* Caller must always clear this!!! */
365 to->stamp.magic = VOLUMEINFOMAGIC;
366 to->stamp.version = VOLUMEINFOVERSION;
371 CopyVolumeHeader(VolumeDiskData * from, VolumeDiskData * to)
376 code = CopyVolumeHeader_r(from, to);
382 ClearVolumeStats(VolumeDiskData * vol)
385 ClearVolumeStats_r(vol);
390 ClearVolumeStats_r(VolumeDiskData * vol)
392 memset(vol->weekUse, 0, sizeof(vol->weekUse));
398 * read an existing volume disk header.
400 * @param[in] volid volume id
401 * @param[in] dp disk partition object
402 * @param[out] hdr volume disk header or NULL
404 * @note if hdr is NULL, this is essentially an existence test for the vol
407 * @return operation status
409 * @retval -1 volume header doesn't exist
410 * @retval EIO failed to read volume header
415 VReadVolumeDiskHeader(VolumeId volid,
416 struct DiskPartition64 * dp,
417 VolumeDiskHeader_t * hdr)
421 char path[MAXPATHLEN];
423 (void)afs_snprintf(path, sizeof(path),
425 VPartitionPath(dp), afs_printable_uint32_lu(volid));
426 fd = open(path, O_RDONLY);
428 Log("VReadVolumeDiskHeader: Couldn't open header for volume %lu (errno %d).\n",
429 afs_printable_uint32_lu(volid), errno);
432 } else if (hdr && read(fd, hdr, sizeof(*hdr)) != sizeof(*hdr)) {
433 Log("VReadVolumeDiskHeader: Couldn't read header for volume %lu.\n",
434 afs_printable_uint32_lu(volid));
444 #ifdef FSSYNC_BUILD_CLIENT
446 * write an existing volume disk header.
448 * @param[in] hdr volume disk header
449 * @param[in] dp disk partition object
450 * @param[in] cr assert if O_CREAT | O_EXCL should be passed to open()
452 * @return operation status
454 * @retval -1 volume header doesn't exist
455 * @retval EIO failed to write volume header
460 _VWriteVolumeDiskHeader(VolumeDiskHeader_t * hdr,
461 struct DiskPartition64 * dp,
466 char path[MAXPATHLEN];
468 #ifdef AFS_DEMAND_ATTACH_FS
469 /* prevent racing with VGC scanners reading the vol header while we are
471 code = VPartHeaderLock(dp, READ_LOCK);
475 #endif /* AFS_DEMAND_ATTACH_FS */
479 (void)afs_snprintf(path, sizeof(path),
481 VPartitionPath(dp), afs_printable_uint32_lu(hdr->id));
482 fd = open(path, flags, 0644);
485 Log("_VWriteVolumeDiskHeader: Couldn't open header for volume %lu, "
486 "error = %d\n", afs_printable_uint32_lu(hdr->id), errno);
487 } else if (write(fd, hdr, sizeof(*hdr)) != sizeof(*hdr)) {
488 Log("_VWriteVolumeDiskHeader: Couldn't write header for volume %lu, "
489 "error = %d\n", afs_printable_uint32_lu(hdr->id), errno);
494 if (close(fd) != 0) {
495 Log("_VWriteVolumeDiskHeader: Error closing header for volume "
496 "%lu, errno %d\n", afs_printable_uint32_lu(hdr->id), errno);
500 #ifdef AFS_DEMAND_ATTACH_FS
501 VPartHeaderUnlock(dp, READ_LOCK);
502 #endif /* AFS_DEMAND_ATTACH_FS */
508 * write an existing volume disk header.
510 * @param[in] hdr volume disk header
511 * @param[in] dp disk partition object
513 * @return operation status
515 * @retval ENOENT volume header doesn't exist
516 * @retval EIO failed to write volume header
519 VWriteVolumeDiskHeader(VolumeDiskHeader_t * hdr,
520 struct DiskPartition64 * dp)
524 #ifdef AFS_DEMAND_ATTACH_FS
525 VolumeDiskHeader_t oldhdr;
526 int delvgc = 0, addvgc = 0;
529 /* first, see if anything with the volume IDs have changed; if so, we
530 * need to update the VGC */
532 code = VReadVolumeDiskHeader(hdr->id, dp, &oldhdr);
533 if (code == 0 && (oldhdr.id != hdr->id || oldhdr.parent != hdr->parent)) {
534 /* the vol id or parent vol id changed; need to delete the VGC entry
535 * for the old vol id/parent, and add the new one */
540 /* couldn't get the old header info; add the new header info to the
541 * VGC in case it hasn't been added yet */
545 #endif /* AFS_DEMAND_ATTACH_FS */
547 code = _VWriteVolumeDiskHeader(hdr, dp, 0);
552 #ifdef AFS_DEMAND_ATTACH_FS
554 memset(&res, 0, sizeof(res));
555 code = FSYNC_VGCDel(dp->name, oldhdr.parent, oldhdr.id, FSYNC_WHATEVER, &res);
557 /* unknown vol id is okay; it just further suggests the old header
558 * data was bogus, which is fine since we're trying to fix it */
559 if (code && res.hdr.reason != FSYNC_UNKNOWN_VOLID) {
560 Log("VWriteVolumeDiskHeader: FSYNC_VGCDel(%s, %lu, %lu) "
561 "failed with code %ld reason %ld\n", dp->name,
562 afs_printable_uint32_lu(oldhdr.parent),
563 afs_printable_uint32_lu(oldhdr.id),
564 afs_printable_int32_ld(code),
565 afs_printable_int32_ld(res.hdr.reason));
570 memset(&res, 0, sizeof(res));
571 code = FSYNC_VGCAdd(dp->name, hdr->parent, hdr->id, FSYNC_WHATEVER, &res);
573 Log("VWriteVolumeDiskHeader: FSYNC_VGCAdd(%s, %lu, %lu) "
574 "failed with code %ld reason %ld\n", dp->name,
575 afs_printable_uint32_lu(hdr->parent),
576 afs_printable_uint32_lu(hdr->id),
577 afs_printable_int32_ld(code),
578 afs_printable_int32_ld(res.hdr.reason));
582 #endif /* AFS_DEMAND_ATTACH_FS */
589 * create and write a volume disk header to disk.
591 * @param[in] hdr volume disk header
592 * @param[in] dp disk partition object
594 * @return operation status
596 * @retval EEXIST volume header already exists
597 * @retval EIO failed to write volume header
602 VCreateVolumeDiskHeader(VolumeDiskHeader_t * hdr,
603 struct DiskPartition64 * dp)
606 #ifdef AFS_DEMAND_ATTACH_FS
608 #endif /* AFS_DEMAND_ATTACH_FS */
610 code = _VWriteVolumeDiskHeader(hdr, dp, O_CREAT | O_EXCL);
615 #ifdef AFS_DEMAND_ATTACH_FS
616 memset(&res, 0, sizeof(res));
617 code = FSYNC_VGCAdd(dp->name, hdr->parent, hdr->id, FSYNC_WHATEVER, &res);
619 Log("VCreateVolumeDiskHeader: FSYNC_VGCAdd(%s, %lu, %lu) failed "
620 "with code %ld reason %ld\n", dp->name,
621 afs_printable_uint32_lu(hdr->parent),
622 afs_printable_uint32_lu(hdr->id),
623 afs_printable_int32_ld(code),
624 afs_printable_int32_ld(res.hdr.reason));
626 #endif /* AFS_DEMAND_ATTACH_FS */
634 * destroy a volume disk header.
636 * @param[in] dp disk partition object
637 * @param[in] volid volume id
638 * @param[in] parent parent's volume id, 0 if unknown
640 * @return operation status
643 * @note if parent is 0, the parent volume ID will be looked up from the
646 * @note for non-DAFS, parent is currently ignored
649 VDestroyVolumeDiskHeader(struct DiskPartition64 * dp,
654 char path[MAXPATHLEN];
655 #ifdef AFS_DEMAND_ATTACH_FS
657 #endif /* AFS_DEMAND_ATTACH_FS */
659 (void)afs_snprintf(path, sizeof(path),
661 VPartitionPath(dp), afs_printable_uint32_lu(volid));
664 Log("VDestroyVolumeDiskHeader: Couldn't unlink disk header, error = %d\n", errno);
668 #ifdef AFS_DEMAND_ATTACH_FS
669 memset(&res, 0, sizeof(res));
671 FSSYNC_VGQry_response_t q_res;
673 code = FSYNC_VGCQuery(dp->name, volid, &q_res, &res);
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));
685 code = FSYNC_VGCDel(dp->name, parent, volid, FSYNC_WHATEVER, &res);
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));
694 #endif /* AFS_DEMAND_ATTACH_FS */
699 #endif /* FSSYNC_BUILD_CLIENT */
702 * handle a single vol header as part of VWalkVolumeHeaders.
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
711 * @return operation status
713 * @retval -1 fatal error, stop scanning
714 * @retval 1 failed to read header
715 * @retval 2 volfunc callback indicated error after header read
718 _VHandleVolumeHeader(struct DiskPartition64 *dp, VWalkVolFunc volfunc,
719 const char *name, struct VolumeDiskHeader *hdr,
720 int locked, void *rock)
725 if ((fd = afs_open(name, O_RDONLY)) == -1
726 || read(fd, hdr, sizeof(*hdr))
728 || hdr->stamp.magic != VOLUMEHEADERMAGIC) {
736 #ifdef AFSFS_DEMAND_ATTACH_FS
738 VPartHeaderUnlock(dp);
740 #endif /* AFS_DEMAND_ATTACH_FS */
742 if (!error && volfunc) {
743 /* the volume header seems fine; call the caller-supplied
744 * 'we-found-a-volume-header' function */
747 #ifdef AFS_DEMAND_ATTACH_FS
751 #endif /* AFS_DEMAND_ATTACH_FS */
753 error = (*volfunc) (dp, name, hdr, last, rock);
762 #ifdef AFS_DEMAND_ATTACH_FS
763 if (error && !locked) {
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);
770 Log("Error acquiring partition write lock when "
771 "looking at header %s\n", name);
775 return _VHandleVolumeHeader(dp, volfunc, name, hdr, 1, rock);
777 #endif /* AFS_DEMAND_ATTACH_FS */
783 * walk through the list of volume headers on a partition.
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).
791 * If volfunc returns a negative error code, walking the partition will stop
792 * and we will return an error immediately.
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
805 * @return operation status
807 * @retval negative fatal error, walk did not finish
810 VWalkVolumeHeaders(struct DiskPartition64 *dp, const char *partpath,
811 VWalkVolFunc volfunc, VWalkErrFunc errfunc, void *rock)
814 struct dirent *dentry = NULL;
816 struct VolumeDiskHeader diskHeader;
818 dirp = opendir(partpath);
820 Log("VWalkVolumeHeaders: cannot open directory %s\n", partpath);
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];
831 sprintf(name, "%s/%s", partpath, dentry->d_name);
833 code = _VHandleVolumeHeader(dp, volfunc, name, &diskHeader, -1, rock);
835 /* fatal error, stop walking */
838 if (code && errfunc) {
839 /* error with header; call the caller-supplied vol error
842 struct VolumeDiskHeader *hdr = &diskHeader;
844 /* we failed to read the header at all, so don't pass in
848 (*errfunc) (dp, name, hdr, rock);
863 * initialize a struct VLockFile.
865 * @param[in] lf struct VLockFile to initialize
866 * @param[in] path Full path to the file to use for locks. The string contents
870 VLockFileInit(struct VLockFile *lf, const char *path)
872 memset(lf, 0, sizeof(*lf));
873 lf->path = strdup(path);
875 MUTEX_INIT(&lf->mutex, "vlockfile", MUTEX_DEFAULT, 0);
880 _VOpenPath(const char *path)
884 handle = CreateFile(path,
885 GENERIC_READ | GENERIC_WRITE,
886 FILE_SHARE_READ | FILE_SHARE_WRITE,
889 FILE_ATTRIBUTE_HIDDEN,
891 if (handle == INVALID_HANDLE_VALUE) {
899 _VLockFd(FD_t handle, afs_uint32 offset, int locktype, int nonblock)
904 if (locktype == WRITE_LOCK) {
905 flags |= LOCKFILE_EXCLUSIVE_LOCK;
908 flags |= LOCKFILE_FAIL_IMMEDIATELY;
911 memset(&lap, 0, sizeof(lap));
914 if (!LockFileEx(handle, flags, 0, 1, 0, &lap)) {
915 if (GetLastError() == ERROR_LOCK_VIOLATION) {
925 _VUnlockFd(struct VLockFile *lf, afs_uint32 offset)
929 memset(&lap, 0, sizeof(lap));
932 UnlockFileEx(lf->fd, 0, 1, 0, &lap);
936 _VCloseFd(struct VLockFile *lf)
941 #else /* !AFS_NT40_ENV */
944 * open a file on the local filesystem suitable for locking
946 * @param[in] path abs path of the file to open
948 * @return file descriptor
949 * @retval INVALID_FD failure opening file
952 _VOpenPath(const char *path)
956 fd = open(path, O_RDWR | O_CREAT, 0660);
964 * lock an offset in a file descriptor.
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
971 * @return operation status
973 * @retval EBUSY someone else is holding a conflicting lock and nonblock=1 was
975 * @retval EIO error acquiring file lock
978 _VLockFd(int fd, afs_uint32 offset, int locktype, int nonblock)
980 int l_type = F_WRLCK;
984 if (locktype == READ_LOCK) {
994 sf.l_whence = SEEK_SET;
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 */
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));
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,
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));
1023 * close a file descriptor used for file locking.
1025 * @param[in] fd file descriptor to close
1031 Log("_VCloseFd: error %d closing fd %d\n",
1037 * unlock a file offset in a file descriptor.
1039 * @param[in] fd file descriptor to unlock
1040 * @param[in] offset offset to unlock
1043 _VUnlockFd(int fd, afs_uint32 offset)
1047 sf.l_start = offset;
1049 sf.l_type = F_UNLCK;
1050 sf.l_whence = SEEK_SET;
1052 if (fcntl(fd, F_SETLK, &sf)) {
1053 Log("_VUnlockFd: fcntl failed with error %d when trying to unlock "
1054 "fd %d\n", errno, fd);
1057 #endif /* !AFS_NT40_ENV */
1060 * reinitialize a struct VLockFile.
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
1068 * @param[in] lf struct VLockFile to reinit
1070 * @pre nobody is waiting for a lock on this lockfile or otherwise using
1071 * this lockfile at all
1074 VLockFileReinit(struct VLockFile *lf)
1076 MUTEX_ENTER(&lf->mutex);
1078 if (lf->fd != INVALID_FD) {
1080 lf->fd = INVALID_FD;
1085 MUTEX_EXIT(&lf->mutex);
1089 * lock a file on disk for the process.
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
1098 * @return operation status
1100 * @retval EBUSY someone else is holding a conflicting lock and nonblock=1 was
1102 * @retval EIO error acquiring file lock
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
1111 VLockFileLock(struct VLockFile *lf, afs_uint32 offset, int locktype, int nonblock)
1115 osi_Assert(locktype == READ_LOCK || locktype == WRITE_LOCK);
1117 MUTEX_ENTER(&lf->mutex);
1119 if (lf->fd == INVALID_FD) {
1120 lf->fd = _VOpenPath(lf->path);
1121 if (lf->fd == INVALID_FD) {
1122 MUTEX_EXIT(&lf->mutex);
1129 MUTEX_EXIT(&lf->mutex);
1131 code = _VLockFd(lf->fd, offset, locktype, nonblock);
1134 MUTEX_ENTER(&lf->mutex);
1135 if (--lf->refcount < 1) {
1137 lf->fd = INVALID_FD;
1139 MUTEX_EXIT(&lf->mutex);
1146 VLockFileUnlock(struct VLockFile *lf, afs_uint32 offset)
1148 MUTEX_ENTER(&lf->mutex);
1150 osi_Assert(lf->fd != INVALID_FD);
1152 if (--lf->refcount < 1) {
1154 lf->fd = INVALID_FD;
1156 _VUnlockFd(lf->fd, offset);
1159 MUTEX_EXIT(&lf->mutex);
1162 #ifdef AFS_DEMAND_ATTACH_FS
1165 * initialize a struct VDiskLock.
1167 * @param[in] dl struct VDiskLock to initialize
1168 * @param[in] lf the struct VLockFile to associate with this disk lock
1171 VDiskLockInit(struct VDiskLock *dl, struct VLockFile *lf, afs_uint32 offset)
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);
1179 dl->offset = offset;
1183 * acquire a lock on a file on local disk.
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
1192 * @return operation status
1194 * @retval EBUSY someone else is holding a conflicting lock and nonblock=1 was
1196 * @retval EIO error acquiring file lock
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
1205 VGetDiskLock(struct VDiskLock *dl, int locktype, int nonblock)
1208 osi_Assert(locktype == READ_LOCK || locktype == WRITE_LOCK);
1211 if (locktype == READ_LOCK) {
1212 ObtainReadLockNoBlock(&dl->rwlock, code);
1214 ObtainWriteLockNoBlock(&dl->rwlock, code);
1221 } else if (locktype == READ_LOCK) {
1222 ObtainReadLock(&dl->rwlock);
1224 ObtainWriteLock(&dl->rwlock);
1227 MUTEX_ENTER(&dl->mutex);
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
1237 while ((dl->flags & VDISKLOCK_ACQUIRING)) {
1238 CV_WAIT(&dl->cv, &dl->mutex);
1243 if (code == 0 && !(dl->flags & VDISKLOCK_ACQUIRED)) {
1244 /* no other thread holds the lock on the actual file; so grab one */
1246 /* first try, don't block on the lock to see if we can get it without
1248 code = VLockFileLock(dl->lockfile, dl->offset, locktype, 1);
1250 if (code == EBUSY && !nonblock) {
1252 /* mark that we are waiting on the fs lock */
1253 dl->flags |= VDISKLOCK_ACQUIRING;
1255 MUTEX_EXIT(&dl->mutex);
1256 code = VLockFileLock(dl->lockfile, dl->offset, locktype, nonblock);
1257 MUTEX_ENTER(&dl->mutex);
1259 dl->flags &= ~VDISKLOCK_ACQUIRING;
1262 dl->flags |= VDISKLOCK_ACQUIRED;
1265 CV_BROADCAST(&dl->cv);
1270 if (locktype == READ_LOCK) {
1271 ReleaseReadLock(&dl->rwlock);
1273 ReleaseWriteLock(&dl->rwlock);
1276 /* successfully got the lock, so inc the number of unlocks we need
1277 * to do before we can unlock the actual file */
1281 MUTEX_EXIT(&dl->mutex);
1287 * release a lock on a file on local disk.
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
1293 * @return operation status
1297 VReleaseDiskLock(struct VDiskLock *dl, int locktype)
1299 osi_Assert(locktype == READ_LOCK || locktype == WRITE_LOCK);
1301 MUTEX_ENTER(&dl->mutex);
1302 osi_Assert(dl->lockers > 0);
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;
1311 MUTEX_EXIT(&dl->mutex);
1313 if (locktype == READ_LOCK) {
1314 ReleaseReadLock(&dl->rwlock);
1316 ReleaseWriteLock(&dl->rwlock);
1320 #endif /* AFS_DEMAND_ATTACH_FS */