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