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