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