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