2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
10 /* I/O operations for the Unix open by name (namei) interface. */
12 #include <afsconfig.h>
13 #include <afs/param.h>
24 #include <afs/assert.h>
27 #include <sys/param.h>
29 #if defined(AFS_SUN5_ENV) || defined(AFS_HPUX_ENV)
32 #include <afs/afsutil.h>
35 #include <afs/afsint.h>
39 #include "viceinode.h"
41 #include "partition.h"
43 #include <afs/errors.h>
45 /*@+fcnmacros +macrofcndecl@*/
48 extern off64_t afs_lseek(int FD, off64_t O, int F);
49 #endif /*S_SPLINT_S */
50 #define afs_lseek(FD, O, F) lseek64(FD, (off64_t)(O), F)
51 #define afs_stat stat64
52 #define afs_fstat fstat64
53 #define afs_open open64
54 #define afs_fopen fopen64
55 #else /* !O_LARGEFILE */
57 extern off_t afs_lseek(int FD, off_t O, int F);
58 #endif /*S_SPLINT_S */
59 #define afs_lseek(FD, O, F) lseek(FD, (off_t)(O), F)
61 #define afs_fstat fstat
63 #define afs_fopen fopen
64 #endif /* !O_LARGEFILE */
65 /*@=fcnmacros =macrofcndecl@*/
67 /*@printflike@*/ extern void Log(const char *format, ...);
70 #define LOCK_SH 1 /* shared lock */
71 #define LOCK_EX 2 /* exclusive lock */
72 #define LOCK_NB 4 /* don't block when locking */
73 #define LOCK_UN 8 /* unlock */
80 * This function emulates a subset of flock()
83 emul_flock(int fd, int cmd)
86 memset(&f, 0, sizeof (f));
95 return fcntl(fd, (cmd & LOCK_NB) ? F_SETLK : F_SETLKW, &f);
98 #define flock(f,c) emul_flock(f,c)
105 namei_iread(IHandle_t * h, afs_foff_t offset, char *buf, afs_fsize_t size)
114 if (FDH_SEEK(fdP, offset, SEEK_SET) < 0) {
115 FDH_REALLYCLOSE(fdP);
119 nBytes = FDH_READ(fdP, buf, size);
125 namei_iwrite(IHandle_t * h, afs_foff_t offset, char *buf, afs_fsize_t size)
134 if (FDH_SEEK(fdP, offset, SEEK_SET) < 0) {
135 FDH_REALLYCLOSE(fdP);
138 nBytes = FDH_WRITE(fdP, buf, size);
145 /* Inode number format:
146 * low 26 bits - vnode number - all 1's if volume special file.
148 * next 3 bits spare (0's)
149 * high 32 bits - uniquifier (regular) or type if spare
151 #define NAMEI_VNODEMASK 0x003ffffff
152 #define NAMEI_TAGMASK 0x7
153 #define NAMEI_TAGSHIFT 26
154 #define NAMEI_UNIQMASK 0xffffffff
155 #define NAMEI_UNIQSHIFT 32
156 #define NAMEI_INODESPECIAL ((Inode)NAMEI_VNODEMASK)
157 #define NAMEI_VNODESPECIAL NAMEI_VNODEMASK
159 /* dir1 is the high 8 bits of the 26 bit vnode */
160 #define VNO_DIR1(vno) ((vno >> 14) & 0xff)
161 /* dir2 is the next 9 bits */
162 #define VNO_DIR2(vno) ((vno >> 9) & 0x1ff)
163 /* "name" is the low 9 bits of the vnode, the 3 bit tag and the uniq */
165 #define NAMEI_SPECDIR "special"
166 #define NAMEI_SPECDIRLEN (sizeof(NAMEI_SPECDIR)-1)
168 #define NAMEI_MAXVOLS 5 /* Maximum supported number of volumes per volume
169 * group, not counting temporary (move) volumes.
170 * This is the number of separate files, all having
171 * the same vnode number, which can occur in a volume
182 static int namei_GetLinkCount2(FdHandle_t * h, Inode ino, int lockit, int fixup, int nowrite);
184 static int GetFreeTag(IHandle_t * ih, int vno);
186 /* namei_HandleToInodeDir
188 * Construct the path name of the directory holding the inode data.
189 * Format: /<vicepx>/INODEDIR
192 #define PNAME_BLEN 64
194 namei_HandleToInodeDir(namei_t * name, IHandle_t * ih)
198 memset(name, '\0', sizeof(*name));
201 * Add the /vicepXX string to the start of name->n_base and then calculate
202 * offset as the number of bytes we know we added.
204 * FIXME: This embeds knowledge of the vice partition naming scheme and
205 * mapping from device numbers. There needs to be an API that tells us
208 volutil_PartitionName_r(ih->ih_dev, name->n_base, sizeof(name->n_base));
209 offset = VICE_PREFIX_SIZE + (ih->ih_dev > 25 ? 2 : 1);
210 name->n_base[offset] = '/';
212 strlcpy(name->n_base + offset, INODEDIR, sizeof(name->n_base) - offset);
213 strlcpy(name->n_path, name->n_base, sizeof(name->n_path));
216 #define addtoname(N, C) \
218 strlcat((N)->n_path, "/", sizeof((N)->n_path)); \
219 strlcat((N)->n_path, (C), sizeof((N)->n_path)); \
224 namei_HandleToVolDir(namei_t * name, IHandle_t * ih)
228 namei_HandleToInodeDir(name, ih);
229 (void)int32_to_flipbase64(tmp, (int64_t) (ih->ih_vid & 0xff));
230 strlcpy(name->n_voldir1, tmp, sizeof(name->n_voldir1));
231 addtoname(name, name->n_voldir1);
232 (void)int32_to_flipbase64(tmp, (int64_t) ih->ih_vid);
233 strlcpy(name->n_voldir2, tmp, sizeof(name->n_voldir2));
234 addtoname(name, name->n_voldir2);
237 /* namei_HandleToName
239 * Constructs a file name for the fully qualified handle.
240 * Note that special files end up in /vicepX/InodeDir/Vxx/V*.data/special
243 namei_HandleToName(namei_t * name, IHandle_t * ih)
246 int vno = (int)(ih->ih_ino & NAMEI_VNODEMASK);
248 namei_HandleToVolDir(name, ih);
250 if (vno == NAMEI_VNODESPECIAL) {
251 strlcpy(name->n_dir1, NAMEI_SPECDIR, sizeof(name->n_dir1));
252 addtoname(name, name->n_dir1);
253 name->n_dir2[0] = '\0';
255 (void)int32_to_flipbase64(str, VNO_DIR1(vno));
256 strlcpy(name->n_dir1, str, sizeof(name->n_dir1));
257 addtoname(name, name->n_dir1);
258 (void)int32_to_flipbase64(str, VNO_DIR2(vno));
259 strlcpy(name->n_dir2, str, sizeof(name->n_dir2));
260 addtoname(name, name->n_dir2);
262 (void)int64_to_flipbase64(str, (int64_t) ih->ih_ino);
263 strlcpy(name->n_inode, str, sizeof(name->n_inode));
264 addtoname(name, name->n_inode);
267 /* The following is a warning to tell sys-admins to not muck about in this
270 #define VICE_README "These files and directories are a part of the AFS \
271 namespace. Modifying them\nin any way will result in loss of AFS data,\n\
272 ownership and permissions included.\n"
274 namei_ViceREADME(char *partition)
279 /* Create the inode directory if we're starting for the first time */
280 (void)afs_snprintf(filename, sizeof filename, "%s/%s", partition,
282 mkdir(filename, 0700);
284 (void)afs_snprintf(filename, sizeof filename, "%s/%s/README", partition,
286 fd = afs_open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0444);
288 (void)write(fd, VICE_README, strlen(VICE_README));
295 #define create_dir() \
297 if (mkdir(tmp, 0700)<0) { \
298 if (errno != EEXIST) \
306 #define create_nextdir(A) \
308 strcat(tmp, "/"); strcat(tmp, A); create_dir(); \
311 /* namei_CreateDataDirectories
313 * If creating the file failed because of ENOENT or ENOTDIR, try
314 * creating all the directories first.
317 namei_CreateDataDirectories(namei_t * name, int *created)
323 strlcpy(tmp, name->n_base, sizeof(tmp));
326 create_nextdir(name->n_voldir1);
327 create_nextdir(name->n_voldir2);
328 create_nextdir(name->n_dir1);
329 if (name->n_dir2[0]) {
330 create_nextdir(name->n_dir2);
335 /* delTree(): Deletes an entire tree of directories (no files)
337 * root : Full path to the subtree. Should be big enough for PATH_MAX
338 * tree : the subtree to be deleted is rooted here. Specifies only the
339 * subtree beginning at tree (not the entire path). It should be
340 * a pointer into the "root" buffer.
342 * errp : errno of the first error encountered during the directory cleanup.
343 * *errp should have been initialized to 0.
346 * -1 : If errors were encountered during cleanup and error is set to
350 * If there are errors, we try to work around them and delete as many
351 * directories as possible. We don't attempt to remove directories that still
352 * have non-dir entries in them.
355 delTree(char *root, char *tree, int *errp)
363 /* delete the children first */
364 cp = strchr(tree, '/');
366 delTree(root, cp + 1, errp);
369 cp = tree + strlen(tree); /* move cp to the end of string tree */
371 /* now delete all entries in this dir */
372 if ((ds = opendir(root)) != (DIR *) NULL) {
374 while ((dirp = readdir(ds))) {
375 /* ignore . and .. */
376 if (!strcmp(dirp->d_name, ".") || !strcmp(dirp->d_name, ".."))
378 /* since root is big enough, we reuse the space to
379 * concatenate the dirname to the current tree
382 strcat(root, dirp->d_name);
383 if (afs_stat(root, &st) == 0 && S_ISDIR(st.st_mode)) {
384 /* delete this subtree */
385 delTree(root, cp + 1, errp);
387 *errp = *errp ? *errp : errno;
389 /* recover path to our cur tree by truncating it to
394 /* if (!errno) -- closedir not implicit if we got an error */
398 /* finally axe the current dir */
400 *errp = *errp ? *errp : errno;
402 #ifndef AFS_PTHREAD_ENV /* let rx get some work done */
404 #endif /* !AFS_PTHREAD_ENV */
409 /* if we encountered errors during cleanup, we return a -1 */
417 /* namei_RemoveDataDirectories
419 * Returns 0 on success.
420 * Returns -1 on error. Typically, callers ignore this error bcause we
421 * can continue running if the removes fail. The salvage process will
422 * finish tidying up for us. We only use the n_base and n_voldir1 entries
423 * and only do rmdir's.
427 namei_RemoveDataDirectories(namei_t * name)
429 char pbuf[MAXPATHLEN], *path = pbuf;
430 int prefixlen = strlen(name->n_base), err = 0;
432 strlcpy(path, name->n_path, sizeof(pbuf));
434 /* move past the prefix */
435 path = path + prefixlen + 1; /* skip over the trailing / */
437 /* now delete all dirs upto path */
438 return delTree(pbuf, path, &err);
442 /* Create the file in the name space.
444 * Parameters stored as follows:
446 * p1 - volid - implied in containing directory.
447 * p2 - vnode - name is <vno:31-23>/<vno:22-15>/<vno:15-0><uniq:31-5><tag:2-0>
448 * p3 - uniq -- bits 4-0 are in mode bits 4-0
449 * p4 - dv ---- dv:15-0 in uid, dv:29-16 in gid, dv:31-30 in mode:6-5
451 * p1 - volid - creation time - dwHighDateTime
452 * p2 - vnode - -1 means special, file goes in "S" subdirectory.
453 * p3 - type -- name is <type>.<tag> where tag is a file name unqiquifier.
454 * p4 - parid - parent volume id - implied in containing directory.
456 * Return value is the inode number or (Inode)-1 if error.
457 * We "know" there is only one link table, so return EEXIST if there already
458 * is a link table. It's up to the calling code to test errno and increment
464 * This function is called by VCreateVolume to hide the implementation
465 * details of the inode numbers. This only allows for 7 volume special
466 * types, but if we get that far, this could should be dead by then.
469 namei_MakeSpecIno(int volid, int type)
472 ino = NAMEI_INODESPECIAL;
473 type &= NAMEI_TAGMASK;
474 ino |= ((Inode) type) << NAMEI_TAGSHIFT;
475 ino |= ((Inode) volid) << NAMEI_UNIQSHIFT;
479 /* SetOGM - set owner group and mode bits from parm and tag
481 * owner - low 15 bits of parm.
482 * group - next 15 bits of parm.
483 * mode - 2 bits of parm, then lowest = 3 bits of tag.
486 SetOGM(int fd, int parm, int tag)
488 int owner, group, mode;
490 owner = parm & 0x7fff;
491 group = (parm >> 15) & 0x7fff;
492 if (fchown(fd, owner, group) < 0)
495 mode = (parm >> 27) & 0x18;
497 if (fchmod(fd, mode) < 0)
504 /* GetOGM - get parm and tag from owner, group and mode bits. */
506 GetOGMFromStat(struct afs_stat *status, int *parm, int *tag)
508 *parm = status->st_uid | (status->st_gid << 15);
509 *parm |= (status->st_mode & 0x18) << 27;
510 *tag = status->st_mode & 0x7;
514 GetOGM(int fd, int *parm, int *tag)
516 struct afs_stat status;
517 if (afs_fstat(fd, &status) < 0)
520 GetOGMFromStat(&status, parm, tag);
524 int big_vno = 0; /* Just in case we ever do 64 bit vnodes. */
526 /* Derive the name and create it O_EXCL. If that fails we have an error.
527 * Get the tag from a free column in the link table.
530 namei_icreate(IHandle_t * lh, char *part, int p1, int p2, int p3, int p4)
543 memset((void *)&tmp, 0, sizeof(IHandle_t));
546 tmp.ih_dev = volutil_GetPartitionID(part);
547 if (tmp.ih_dev == -1) {
553 /* Parameters for special file:
554 * p1 - volume id - goes into owner/group/mode
557 * p4 - parent volume id
562 tmp.ih_vid = p4; /* Use parent volume id, where this file will be. */
563 tmp.ih_ino = namei_MakeSpecIno(p1, p3);
565 int vno = p2 & NAMEI_VNODEMASK;
566 /* Parameters for regular file:
578 /* If GetFreeTag succeeds, it atomically sets link count to 1. */
579 tag = GetFreeTag(lh, p2);
583 /* name is <uniq(p3)><tag><vno(p2)> */
585 tmp.ih_ino = (Inode) p2;
586 tmp.ih_ino |= ((Inode) tag) << NAMEI_TAGSHIFT;
587 tmp.ih_ino |= ((Inode) p3) << NAMEI_UNIQSHIFT;
592 namei_HandleToName(&name, &tmp);
593 fd = afs_open(name.n_path, O_CREAT | O_EXCL | O_TRUNC | O_RDWR, 0);
595 if (errno == ENOTDIR || errno == ENOENT) {
596 if (namei_CreateDataDirectories(&name, &created_dir) < 0)
598 fd = afs_open(name.n_path, O_CREAT | O_EXCL | O_TRUNC | O_RDWR,
606 if (SetOGM(fd, ogm_parm, tag) < 0) {
612 if (p2 == -1 && p3 == VI_LINKTABLE) {
613 /* hack at tmp to setup for set link count call. */
614 memset((void *)&tfd, 0, sizeof(FdHandle_t)); /* minimalistic still, but a little cleaner */
617 code = namei_SetLinkCount(&tfd, (Inode) 0, 1, 0);
625 if (code || (fd < 0)) {
629 namei_SetLinkCount(fdP, tmp.ih_ino, 0, 0);
634 return (code || (fd < 0)) ? (Inode) - 1 : tmp.ih_ino;
640 namei_iopen(IHandle_t * h)
645 /* Convert handle to file name. */
646 namei_HandleToName(&name, h);
647 fd = afs_open(name.n_path, O_RDWR, 0666);
651 /* Need to detect vol special file and just unlink. In those cases, the
652 * handle passed in _is_ for the inode. We only check p1 for the special
656 namei_dec(IHandle_t * ih, Inode ino, int p1)
663 if ((ino & NAMEI_INODESPECIAL) == NAMEI_INODESPECIAL) {
666 int type = (int)((ino >> NAMEI_TAGSHIFT) & NAMEI_TAGMASK);
668 /* Verify this is the right file. */
669 IH_INIT(tmp, ih->ih_dev, ih->ih_vid, ino);
678 if ((GetOGM(fdP->fd_fd, &inode_p1, &tag) < 0) || (inode_p1 != p1)) {
679 FDH_REALLYCLOSE(fdP);
685 /* If it's the link table itself, decrement the link count. */
686 if (type == VI_LINKTABLE) {
687 if ((count = namei_GetLinkCount(fdP, (Inode) 0, 1)) < 0) {
688 FDH_REALLYCLOSE(fdP);
694 if (namei_SetLinkCount(fdP, (Inode) 0, count < 0 ? 0 : count, 1) <
696 FDH_REALLYCLOSE(fdP);
702 FDH_REALLYCLOSE(fdP);
708 namei_HandleToName(&name, tmp);
709 if ((code = unlink(name.n_path)) == 0) {
710 if (type == VI_LINKTABLE) {
711 /* Try to remove directory. If it fails, that's ok.
712 * Salvage will clean up.
714 (void)namei_RemoveDataDirectories(&name);
717 FDH_REALLYCLOSE(fdP);
720 /* Get a file descriptor handle for this Inode */
726 if ((count = namei_GetLinkCount(fdP, ino, 1)) < 0) {
727 FDH_REALLYCLOSE(fdP);
733 if (namei_SetLinkCount(fdP, ino, count, 1) < 0) {
734 FDH_REALLYCLOSE(fdP);
739 IH_INIT(th, ih->ih_dev, ih->ih_vid, ino);
740 Log("Warning: Lost ref on ihandle dev %d vid %d ino %" AFS_INT64_FMT "\n",
741 th->ih_dev, th->ih_vid, (int64_t) th->ih_ino);
744 /* If we're less than 0, someone presumably unlinked;
745 don't bother setting count to 0, but we need to drop a lock */
746 if (namei_SetLinkCount(fdP, ino, 0, 1) < 0) {
747 FDH_REALLYCLOSE(fdP);
753 IH_INIT(th, ih->ih_dev, ih->ih_vid, ino);
755 namei_HandleToName(&name, th);
757 code = unlink(name.n_path);
766 namei_inc(IHandle_t * h, Inode ino, int p1)
772 if ((ino & NAMEI_INODESPECIAL) == NAMEI_INODESPECIAL) {
773 int type = (int)((ino >> NAMEI_TAGSHIFT) & NAMEI_TAGMASK);
774 if (type != VI_LINKTABLE)
779 /* Get a file descriptor handle for this Inode */
785 if ((count = namei_GetLinkCount(fdP, ino, 1)) < 0)
794 if (namei_SetLinkCount(fdP, ino, count, 1) < 0)
798 FDH_REALLYCLOSE(fdP);
806 namei_replace_file_by_hardlink(IHandle_t *hLink, IHandle_t *hTarget)
812 /* Convert handle to file name. */
813 namei_HandleToName(&nameLink, hLink);
814 namei_HandleToName(&nameTarget, hTarget);
816 unlink(nameLink.n_path);
817 code = link(nameTarget.n_path, nameLink.n_path);
822 namei_copy_on_write(IHandle_t *h)
824 afs_int32 fd, code = 0;
827 struct afs_stat tstat;
829 namei_HandleToName(&name, h);
830 if (afs_stat(name.n_path, &tstat) < 0)
832 if (tstat.st_nlink > 1) { /* do a copy on write */
841 afs_snprintf(path, sizeof(path), "%s-tmp", name.n_path);
842 fd = afs_open(path, O_CREAT | O_EXCL | O_TRUNC | O_RDWR, 0);
854 size = tstat.st_size;
857 tlen = size > 8192 ? 8192 : size;
858 if (FDH_READ(fdP, buf, tlen) != tlen)
860 if (write(fd, buf, tlen) != tlen)
865 FDH_REALLYCLOSE(fdP);
871 code = rename(path, name.n_path);
877 /************************************************************************
878 * File Name Structure
879 ************************************************************************
881 * Each AFS file needs a unique name and it needs to be findable with
882 * minimal lookup time. Note that the constraint on the number of files and
883 * directories in a volume is the size of the vnode index files and the
884 * max file size AFS supports (for internal files) of 2^31. Since a record
885 * in the small vnode index file is 64 bytes long, we can have at most
886 * (2^31)/64 or 33554432 files. A record in the large index file is
887 * 256 bytes long, giving a maximum of (2^31)/256 = 8388608 directories.
888 * Another layout parameter is that there is roughly a 16 to 1 ratio between
889 * the number of files and the number of directories.
891 * Using this information we can see that a layout of 256 directories, each
892 * with 512 subdirectories and each of those having 512 files gives us
893 * 256*512*512 = 67108864 AFS files and directories.
895 * The volume, vnode, uniquifier and data version, as well as the tag
896 * are required, either for finding the file or for salvaging. It's best to
897 * restrict the name to something that can be mapped into 64 bits so the
898 * "Inode" is easily comparable (using "==") to other "Inodes". The tag
899 * is used to distinguish between different versions of the same file
900 * which are currently in the RW and clones of a volume. See "Link Table
901 * Organization" below for more information on the tag. The tag is
902 * required in the name of the file to ensure a unique name.
904 * We can store data in the uid, gid and mode bits of the files, provided
905 * the directories have root only access. This gives us 15 bits for each
906 * of uid and gid (GNU chown considers 65535 to mean "don't change").
907 * There are 9 available mode bits. Adn we need to store a total of
908 * 32 (volume id) + 26 (vnode) + 32 (uniquifier) + 32 (data-version) + 3 (tag)
909 * or 131 bits somewhere.
911 * The format of a file name for a regular file is:
912 * /vicepX/AFSIDat/V1/V2/AA/BB/<tag><uniq><vno>
913 * V1 - low 8 bits of RW volume id
914 * V2 - all bits of RW volume id
915 * AA - high 8 bits of vnode number.
916 * BB - next 9 bits of vnode number.
917 * <tag><uniq><vno> - file name
919 * Volume special files are stored in a separate directory:
920 * /vicepX/AFSIDat/V1/V2/special/<tag><uniq><vno>
923 * The vnode is hashed into the directory using the high bits of the
924 * vnode number. This is so that consecutively created vnodes are in
925 * roughly the same area on the disk. This will at least be optimal if
926 * the user is creating many files in the same AFS directory. The name
927 * should be formed so that the leading characters are different as quickly
928 * as possible, leading to faster discards of incorrect matches in the
934 /************************************************************************
935 * Link Table Organization
936 ************************************************************************
938 * The link table volume special file is used to hold the link counts that
939 * are held in the inodes in inode based AFS vice filesystems. For user
940 * space access, the link counts are being kept in a separate
941 * volume special file. The file begins with the usual version stamp
942 * information and is then followed by one row per vnode number. vnode 0
943 * is used to hold the link count of the link table itself. That is because
944 * the same link table is shared among all the volumes of the volume group
945 * and is deleted only when the last volume of a volume group is deleted.
947 * Within each row, the columns are 3 bits wide. They can each hold a 0 based
948 * link count from 0 through 7. Each colume represents a unique instance of
949 * that vnode. Say we have a file shared between the RW and a RO and a
950 * different version of the file (or a different uniquifer) for the BU volume.
951 * Then one column would be holding the link count of 2 for the RW and RO
952 * and a different column would hold the link count of 1 for the BU volume.
953 * Note that we allow only 5 volumes per file, giving 15 bits used in the
956 #define LINKTABLE_WIDTH 2
957 #define LINKTABLE_SHIFT 1 /* log 2 = 1 */
960 namei_GetLCOffsetAndIndexFromIno(Inode ino, afs_foff_t * offset, int *index)
962 int toff = (int)(ino & NAMEI_VNODEMASK);
963 int tindex = (int)((ino >> NAMEI_TAGSHIFT) & NAMEI_TAGMASK);
965 *offset = (afs_foff_t) ((toff << LINKTABLE_SHIFT) + 8); /* * 2 + sizeof stamp */
966 *index = (tindex << 1) + tindex;
970 /* namei_GetLinkCount
971 * If lockit is set, lock the file and leave it locked upon a successful
975 namei_GetLinkCount2(FdHandle_t * h, Inode ino, int lockit, int fixup, int nowrite)
977 unsigned short row = 0;
982 /* there's no linktable yet. the salvager will create one later */
983 if (h->fd_fd == -1 && fixup)
985 namei_GetLCOffsetAndIndexFromIno(ino, &offset, &index);
988 if (flock(h->fd_fd, LOCK_EX) < 0)
992 if (afs_lseek(h->fd_fd, offset, SEEK_SET) == -1)
993 goto bad_getLinkByte;
995 rc = read(h->fd_fd, (char *)&row, sizeof(row));
996 if ((rc == 0 || !((row >> index) & NAMEI_TAGMASK)) && fixup && nowrite)
998 if (rc == 0 && fixup) {
1000 if (fstat(h->fd_fd, &st) || st.st_size >= offset+sizeof(row))
1001 goto bad_getLinkByte;
1002 FDH_TRUNC(h, offset+sizeof(row));
1004 rc = write(h->fd_fd, (char *)&row, sizeof(row));
1006 if (rc != sizeof(row)) {
1007 goto bad_getLinkByte;
1010 if (fixup && !((row >> index) & NAMEI_TAGMASK)) {
1012 if (afs_lseek(h->fd_fd, offset, SEEK_SET) == -1)
1013 goto bad_getLinkByte;
1014 rc = write(h->fd_fd, (char *)&row, sizeof(row));
1015 if (rc != sizeof(row))
1016 goto bad_getLinkByte;
1019 return (int)((row >> index) & NAMEI_TAGMASK);
1023 flock(h->fd_fd, LOCK_UN);
1028 namei_GetLinkCount(FdHandle_t * h, Inode ino, int lockit)
1030 return namei_GetLinkCount2(h, ino, lockit, 0, 1);
1033 /* Return a free column index for this vnode. */
1035 GetFreeTag(IHandle_t * ih, int vno)
1049 /* Only one manipulates at a time. */
1050 if (flock(fdP->fd_fd, LOCK_EX) < 0) {
1051 FDH_REALLYCLOSE(fdP);
1055 offset = (vno << LINKTABLE_SHIFT) + 8; /* * 2 + sizeof stamp */
1056 if (afs_lseek(fdP->fd_fd, offset, SEEK_SET) == -1) {
1060 code = read(fdP->fd_fd, (char *)&row, sizeof(row));
1061 if (code != sizeof(row)) {
1067 /* Now find a free column in this row and claim it. */
1068 for (col = 0; col < NAMEI_MAXVOLS; col++) {
1069 coldata = 7 << (col * 3);
1070 if ((row & coldata) == 0)
1073 if (col >= NAMEI_MAXVOLS) {
1078 coldata = 1 << (col * 3);
1081 if (afs_lseek(fdP->fd_fd, offset, SEEK_SET) == -1) {
1084 if (write(fdP->fd_fd, (char *)&row, sizeof(row)) != sizeof(row)) {
1088 flock(fdP->fd_fd, LOCK_UN);
1089 FDH_REALLYCLOSE(fdP);
1093 flock(fdP->fd_fd, LOCK_UN);
1094 FDH_REALLYCLOSE(fdP);
1100 /* namei_SetLinkCount
1101 * If locked is set, assume file is locked. Otherwise, lock file before
1102 * proceeding to modify it.
1105 namei_SetLinkCount(FdHandle_t * fdP, Inode ino, int count, int locked)
1113 namei_GetLCOffsetAndIndexFromIno(ino, &offset, &index);
1116 if (flock(fdP->fd_fd, LOCK_EX) < 0) {
1120 if (afs_lseek(fdP->fd_fd, offset, SEEK_SET) == -1) {
1122 goto bad_SetLinkCount;
1126 code = read(fdP->fd_fd, (char *)&row, sizeof(row));
1127 if (code != sizeof(row)) {
1130 goto bad_SetLinkCount;
1137 row &= (unsigned short)~junk;
1138 row |= (unsigned short)count;
1140 if (afs_lseek(fdP->fd_fd, offset, SEEK_SET) == -1) {
1142 goto bad_SetLinkCount;
1145 if (write(fdP->fd_fd, (char *)&row, sizeof(short)) != sizeof(short)) {
1147 goto bad_SetLinkCount;
1155 flock(fdP->fd_fd, LOCK_UN);
1161 /* ListViceInodes - write inode data to a results file. */
1162 static int DecodeInode(char *dpath, char *name, struct ViceInodeInfo *info,
1163 unsigned int volid);
1164 static int DecodeVolumeName(char *name, unsigned int *vid);
1165 static int namei_ListAFSSubDirs(IHandle_t * dirIH,
1166 int (*write_fun) (FILE *,
1167 struct ViceInodeInfo *,
1168 char *, char *), FILE * fp,
1169 int (*judgeFun) (struct ViceInodeInfo *,
1170 afs_uint32 vid, void *),
1171 afs_uint32 singleVolumeNumber, void *rock);
1176 * Write the inode data to the results file.
1178 * Returns -2 on error, 0 on success.
1180 * This is written as a callback simply so that other listing routines
1181 * can use the same inode reading code.
1184 WriteInodeInfo(FILE * fp, struct ViceInodeInfo *info, char *dir, char *name)
1187 n = fwrite(info, sizeof(*info), 1, fp);
1188 return (n == 1) ? 0 : -2;
1192 int mode_errors; /* Number of errors found in mode bits on directories. */
1194 VerifyDirPerms(char *path)
1196 struct afs_stat status;
1198 if (afs_stat(path, &status) < 0) {
1199 Log("Unable to stat %s. Please manually verify mode bits for this"
1200 " directory\n", path);
1202 if (((status.st_mode & 0777) != 0700) || (status.st_uid != 0))
1208 * Fill the results file with the requested inode information.
1212 * -1 - complete failure, salvage should terminate.
1213 * -2 - not enough space on partition, salvager has error message for this.
1215 * This code optimizes single volume salvages by just looking at that one
1216 * volume's directory.
1218 * If the resultFile is NULL, then don't call the write routine.
1221 ListViceInodes(char *devname, char *mountedOn, FILE *inodeFile,
1222 int (*judgeInode) (struct ViceInodeInfo * info, afs_uint32 vid, void *rock),
1223 afs_uint32 singleVolumeNumber, int *forcep, int forceR, char *wpath,
1227 struct afs_stat status;
1229 *forcep = 0; /* no need to salvage until further notice */
1231 /* Verify protections on directories. */
1233 VerifyDirPerms(mountedOn);
1236 namei_ListAFSFiles(mountedOn, WriteInodeInfo, inodeFile, judgeInode,
1237 singleVolumeNumber, rock);
1246 if (fflush(inodeFile) == EOF) {
1247 Log("Unable to successfully flush inode file for %s\n", mountedOn);
1250 if (fsync(fileno(inodeFile)) == -1) {
1251 Log("Unable to successfully fsync inode file for %s\n", mountedOn);
1256 * Paranoia: check that the file is really the right size
1258 if (afs_fstat(fileno(inodeFile), &status) == -1) {
1259 Log("Unable to successfully stat inode file for %s\n", mountedOn);
1262 if (status.st_size != ninodes * sizeof(struct ViceInodeInfo)) {
1263 Log("Wrong size (%d instead of %d) in inode file for %s\n",
1264 status.st_size, ninodes * sizeof(struct ViceInodeInfo),
1272 /* namei_ListAFSFiles
1274 * Collect all the matching AFS files on the drive.
1275 * If singleVolumeNumber is non-zero, just return files for that volume.
1277 * Returns <0 on error, else number of files found to match.
1280 namei_ListAFSFiles(char *dev,
1281 int (*writeFun) (FILE *, struct ViceInodeInfo *, char *,
1283 int (*judgeFun) (struct ViceInodeInfo *, afs_uint32, void *),
1284 afs_uint32 singleVolumeNumber, void *rock)
1290 struct dirent *dp1, *dp2;
1293 static void FreeZLCList(void);
1296 memset((void *)&ih, 0, sizeof(IHandle_t));
1297 ih.ih_dev = volutil_GetPartitionID(dev);
1299 if (singleVolumeNumber) {
1300 ih.ih_vid = singleVolumeNumber;
1301 namei_HandleToVolDir(&name, &ih);
1303 namei_ListAFSSubDirs(&ih, writeFun, fp, judgeFun,
1304 singleVolumeNumber, rock);
1308 /* Find all volume data directories and descend through them. */
1309 namei_HandleToInodeDir(&name, &ih);
1311 dirp1 = opendir(name.n_path);
1314 while ((dp1 = readdir(dirp1))) {
1315 if (*dp1->d_name == '.')
1317 afs_snprintf(path2, sizeof(path2), "%s/%s", name.n_path,
1319 dirp2 = opendir(path2);
1321 while ((dp2 = readdir(dirp2))) {
1322 if (*dp2->d_name == '.')
1324 if (!DecodeVolumeName(dp2->d_name, &ih.ih_vid)) {
1326 namei_ListAFSSubDirs(&ih, writeFun, fp, judgeFun,
1343 /* namei_ListAFSSubDirs
1348 * > = 0 - number of AFS files found.
1351 namei_ListAFSSubDirs(IHandle_t * dirIH,
1352 int (*writeFun) (FILE *, struct ViceInodeInfo *, char *,
1354 int (*judgeFun) (struct ViceInodeInfo *, afs_uint32, void *),
1355 afs_uint32 singleVolumeNumber, void *rock)
1357 IHandle_t myIH = *dirIH;
1359 char path1[512], path2[512], path3[512];
1360 DIR *dirp1, *dirp2, *dirp3;
1361 struct dirent *dp1, *dp2, *dp3;
1362 struct ViceInodeInfo info;
1363 FdHandle_t linkHandle;
1367 static void AddToZLCDeleteList(char dir, char *name);
1368 static void DeleteZLCFiles(char *path);
1371 namei_HandleToVolDir(&name, &myIH);
1372 strlcpy(path1, name.n_path, sizeof(path1));
1374 /* Do the directory containing the special files first to pick up link
1377 (void)strcat(path1, "/");
1378 (void)strcat(path1, NAMEI_SPECDIR);
1380 linkHandle.fd_fd = -1;
1381 dirp1 = opendir(path1);
1383 while ((dp1 = readdir(dirp1))) {
1384 if (*dp1->d_name == '.')
1386 if (DecodeInode(path1, dp1->d_name, &info, myIH.ih_vid) < 0)
1388 if (info.u.param[2] != VI_LINKTABLE) {
1391 /* Open this handle */
1392 (void)afs_snprintf(path2, sizeof path2, "%s/%s", path1,
1394 linkHandle.fd_fd = afs_open(path2, Testing ? O_RDONLY : O_RDWR, 0666);
1396 namei_GetLinkCount2(&linkHandle, (Inode) 0, 1, 1, Testing);
1398 if (judgeFun && !(*judgeFun) (&info, singleVolumeNumber, rock))
1401 if ((*writeFun) (fp, &info, path1, dp1->d_name) < 0) {
1402 if (linkHandle.fd_fd >= 0)
1403 close(linkHandle.fd_fd);
1412 /* Now run through all the other subdirs */
1413 namei_HandleToVolDir(&name, &myIH);
1414 strlcpy(path1, name.n_path, sizeof(path1));
1416 dirp1 = opendir(path1);
1418 while ((dp1 = readdir(dirp1))) {
1419 if (*dp1->d_name == '.')
1421 if (!strcmp(dp1->d_name, NAMEI_SPECDIR))
1424 /* Now we've got a next level subdir. */
1425 afs_snprintf(path2, sizeof(path2), "%s/%s", path1, dp1->d_name);
1426 dirp2 = opendir(path2);
1428 while ((dp2 = readdir(dirp2))) {
1429 if (*dp2->d_name == '.')
1432 /* Now we've got to the actual data */
1433 afs_snprintf(path3, sizeof(path3), "%s/%s", path2,
1435 dirp3 = opendir(path3);
1437 while ((dp3 = readdir(dirp3))) {
1438 if (*dp3->d_name == '.')
1441 (path3, dp3->d_name, &info, myIH.ih_vid) < 0)
1444 namei_GetLinkCount2(&linkHandle,
1445 info.inodeNumber, 1, 1, Testing);
1446 if (info.linkCount == 0) {
1448 Log("Found 0 link count file %s/%s, deleting it.\n", path3, dp3->d_name);
1449 AddToZLCDeleteList((char)i, dp3->d_name);
1451 Log("Found 0 link count file %s/%s.\n", path3,
1457 && !(*judgeFun) (&info, singleVolumeNumber, rock))
1460 if ((*writeFun) (fp, &info, path3, dp3->d_name) <
1462 close(linkHandle.fd_fd);
1479 if (linkHandle.fd_fd >= 0)
1480 close(linkHandle.fd_fd);
1482 /* Then why does this directory exist? Blow it away. */
1483 namei_HandleToVolDir(&name, dirIH);
1484 namei_RemoveDataDirectories(&name);
1491 DecodeVolumeName(char *name, unsigned int *vid)
1493 if (strlen(name) <= 2)
1495 *vid = (unsigned int)flipbase64_to_int64(name);
1502 * Get the inode number from the name.
1506 DecodeInode(char *dpath, char *name, struct ViceInodeInfo *info,
1510 struct afs_stat status;
1512 lb64_string_t check;
1514 afs_snprintf(fpath, sizeof(fpath), "%s/%s", dpath, name);
1516 if (afs_stat(fpath, &status) < 0) {
1520 info->byteCount = status.st_size;
1521 info->inodeNumber = (Inode) flipbase64_to_int64(name);
1523 int64_to_flipbase64(check, info->inodeNumber);
1524 if (strcmp(name, check))
1527 GetOGMFromStat(&status, &parm, &tag);
1528 if ((info->inodeNumber & NAMEI_INODESPECIAL) == NAMEI_INODESPECIAL) {
1529 /* p1 - vid, p2 - -1, p3 - type, p4 - rwvid */
1530 info->u.param[0] = parm;
1531 info->u.param[1] = -1;
1532 info->u.param[2] = tag;
1533 info->u.param[3] = volid;
1535 /* p1 - vid, p2 - vno, p3 - uniq, p4 - dv */
1536 info->u.param[0] = volid;
1537 info->u.param[1] = (int)(info->inodeNumber & NAMEI_VNODEMASK);
1538 info->u.param[2] = (int)((info->inodeNumber >> NAMEI_UNIQSHIFT)
1539 & (Inode) NAMEI_UNIQMASK);
1540 info->u.param[3] = parm;
1546 * Convert the VolumeInfo file from RO to RW
1547 * this routine is called by namei_convertROtoRWvolume()
1550 #ifdef FSSYNC_BUILD_CLIENT
1552 convertVolumeInfo(int fdr, int fdw, afs_uint32 vid)
1554 struct VolumeDiskData vd;
1557 if (read(fdr, &vd, sizeof(struct VolumeDiskData)) !=
1558 sizeof(struct VolumeDiskData)) {
1559 Log("1 convertVolumeInfo: read failed for %lu with code %d\n", vid,
1563 vd.restoredFromId = vd.id; /* remember the RO volume here */
1565 vd.id = vd.parentId;
1569 vd.uniquifier += 5000; /* just in case there are still file copies from
1570 * the old RW volume around */
1571 p = strrchr(vd.name, '.');
1572 if (p && !strcmp(p, ".readonly")) {
1575 if (write(fdw, &vd, sizeof(struct VolumeDiskData)) !=
1576 sizeof(struct VolumeDiskData)) {
1577 Log("1 convertVolumeInfo: write failed for %lu with code %d\n", vid,
1586 * Convert a RO-volume into a RW-volume
1588 * This function allows to recover very fast from the loss of a partition
1589 * from RO-copies if all RO-Copies exist on another partition.
1590 * Then these RO-volumes can be made to the new RW-volumes.
1591 * Backup of RW-volumes then consists in "vos release".
1593 * We must make sure in this partition exists only the RO-volume which
1594 * is typical for remote replicas.
1596 * Then the linktable is already ok,
1597 * the vnode files need to be renamed
1598 * the volinfo file needs to be replaced by another one with
1599 * slightly different contents and new name.
1600 * The volume header file of the RO-volume in the /vicep<x> directory
1601 * is destroyed by this call. A new header file for the RW-volume must
1602 * be created after return from this routine.
1606 namei_ConvertROtoRWvolume(char *pname, afs_uint32 volumeId)
1608 #ifdef FSSYNC_BUILD_CLIENT
1610 char dir_name[512], oldpath[512], newpath[512];
1625 struct DiskPartition64 *partP;
1626 struct ViceInodeInfo info;
1627 struct VolumeDiskHeader h;
1629 for (partP = DiskPartitionList; partP && strcmp(partP->name, pname);
1630 partP = partP->next);
1632 Log("1 namei_ConvertROtoRWvolume: Couldn't find DiskPartition for %s\n", pname);
1636 if (VReadVolumeDiskHeader(volumeId, partP, &h)) {
1637 Log("1 namei_ConvertROtoRWvolume: Couldn't read header for RO-volume %lu.\n",
1638 afs_printable_uint32_lu(volumeId));
1642 FSYNC_VolOp(volumeId, pname, FSYNC_VOL_BREAKCBKS, 0, NULL);
1644 ino = namei_MakeSpecIno(h.parent, VI_LINKTABLE);
1645 IH_INIT(ih, partP->device, h.parent, ino);
1647 namei_HandleToName(&n, ih);
1648 strlcpy(dir_name, n.n_path, sizeof(dir_name));
1649 p = strrchr(dir_name, '/');
1651 dirp = opendir(dir_name);
1653 Log("1 namei_ConvertROtoRWvolume: Could not opendir(%s)\n", dir_name);
1657 while ((dp = readdir(dirp))) {
1658 /* struct ViceInodeInfo info; */
1660 if (*dp->d_name == '.')
1662 if (DecodeInode(dir_name, dp->d_name, &info, ih->ih_vid) < 0) {
1663 Log("1 namei_ConvertROtoRWvolume: DecodeInode failed for %s/%s\n",
1664 dir_name, dp->d_name);
1668 if (info.u.param[1] != -1) {
1669 Log("1 namei_ConvertROtoRWvolume: found other than volume special file %s/%s\n", dir_name, dp->d_name);
1673 if (info.u.param[0] != volumeId) {
1674 if (info.u.param[0] == ih->ih_vid) {
1675 if (info.u.param[2] == VI_LINKTABLE) { /* link table */
1680 Log("1 namei_ConvertROtoRWvolume: found special file %s/%s for volume %lu\n", dir_name, dp->d_name, info.u.param[0]);
1684 if (info.u.param[2] == VI_VOLINFO) { /* volume info file */
1685 strlcpy(infoName, dp->d_name, sizeof(infoName));
1687 } else if (info.u.param[2] == VI_SMALLINDEX) { /* small vnodes file */
1688 strlcpy(smallName, dp->d_name, sizeof(smallName));
1690 } else if (info.u.param[2] == VI_LARGEINDEX) { /* large vnodes file */
1691 strlcpy(largeName, dp->d_name, sizeof(largeName));
1695 Log("1 namei_ConvertROtoRWvolume: unknown type %d of special file found : %s/%s\n", info.u.param[2], dir_name, dp->d_name);
1701 if (!infoSeen || !smallSeen || !largeSeen || !linkSeen) {
1702 Log("1 namei_ConvertROtoRWvolume: not all special files found in %s\n", dir_name);
1707 * If we come here then there was only a RO-volume and we can safely
1711 memset(&t_ih, 0, sizeof(t_ih));
1712 t_ih.ih_dev = ih->ih_dev;
1713 t_ih.ih_vid = ih->ih_vid;
1715 (void)afs_snprintf(oldpath, sizeof oldpath, "%s/%s", dir_name, infoName);
1716 fd = afs_open(oldpath, O_RDWR, 0);
1718 Log("1 namei_ConvertROtoRWvolume: could not open RO info file: %s\n",
1722 t_ih.ih_ino = namei_MakeSpecIno(ih->ih_vid, VI_VOLINFO);
1723 namei_HandleToName(&n, &t_ih);
1724 fd2 = afs_open(n.n_path, O_CREAT | O_EXCL | O_TRUNC | O_RDWR, 0);
1726 Log("1 namei_ConvertROtoRWvolume: could not create RW info file: %s\n", n.n_path);
1730 code = convertVolumeInfo(fd, fd2, ih->ih_vid);
1737 SetOGM(fd2, ih->ih_vid, 1);
1740 t_ih.ih_ino = namei_MakeSpecIno(ih->ih_vid, VI_SMALLINDEX);
1741 namei_HandleToName(&n, &t_ih);
1742 (void)afs_snprintf(newpath, sizeof newpath, "%s/%s", dir_name, smallName);
1743 fd = afs_open(newpath, O_RDWR, 0);
1745 Log("1 namei_ConvertROtoRWvolume: could not open SmallIndex file: %s\n", newpath);
1748 SetOGM(fd, ih->ih_vid, 2);
1750 link(newpath, n.n_path);
1753 t_ih.ih_ino = namei_MakeSpecIno(ih->ih_vid, VI_LARGEINDEX);
1754 namei_HandleToName(&n, &t_ih);
1755 (void)afs_snprintf(newpath, sizeof newpath, "%s/%s", dir_name, largeName);
1756 fd = afs_open(newpath, O_RDWR, 0);
1758 Log("1 namei_ConvertROtoRWvolume: could not open LargeIndex file: %s\n", newpath);
1761 SetOGM(fd, ih->ih_vid, 3);
1763 link(newpath, n.n_path);
1769 h.volumeInfo_hi = h.id;
1770 h.smallVnodeIndex_hi = h.id;
1771 h.largeVnodeIndex_hi = h.id;
1772 h.linkTable_hi = h.id;
1774 if (VCreateVolumeDiskHeader(&h, partP)) {
1775 Log("1 namei_ConvertROtoRWvolume: Couldn't write header for RW-volume %lu\n",
1776 afs_printable_uint32_lu(h.id));
1780 if (VDestroyVolumeDiskHeader(partP, volumeId, h.parent)) {
1781 Log("1 namei_ConvertROtoRWvolume: Couldn't unlink header for RO-volume %lu\n",
1782 afs_printable_uint32_lu(volumeId));
1785 FSYNC_VolOp(volumeId, pname, FSYNC_VOL_DONE, 0, NULL);
1786 FSYNC_VolOp(h.id, pname, FSYNC_VOL_ON, 0, NULL);
1793 * returns a static string used to print either 32 or 64 bit inode numbers.
1796 PrintInode(char *s, Inode ino)
1798 static afs_ino_str_t result;
1802 (void)afs_snprintf(s, sizeof(afs_ino_str_t), "%llu", (afs_uintmax_t) ino);
1809 /* Routines to facilitate removing zero link count files. */
1810 #define MAX_ZLC_NAMES 32
1811 #define MAX_ZLC_NAMELEN 16
1812 typedef struct zlcList_s {
1813 struct zlcList_s *zlc_next;
1815 char zlc_names[MAX_ZLC_NAMES][MAX_ZLC_NAMELEN];
1818 static zlcList_t *zlcAnchor = NULL;
1819 static zlcList_t *zlcCur = NULL;
1822 AddToZLCDeleteList(char dir, char *name)
1824 assert(strlen(name) <= MAX_ZLC_NAMELEN - 3);
1826 if (!zlcCur || zlcCur->zlc_n >= MAX_ZLC_NAMES) {
1827 if (zlcCur && zlcCur->zlc_next)
1828 zlcCur = zlcCur->zlc_next;
1830 zlcList_t *tmp = (zlcList_t *) malloc(sizeof(zlcList_t));
1836 zlcCur->zlc_next = tmp;
1840 zlcCur->zlc_next = NULL;
1844 (void)sprintf(zlcCur->zlc_names[zlcCur->zlc_n], "%c\\%s", dir, name);
1849 DeleteZLCFiles(char *path)
1855 for (z = zlcAnchor; z; z = z->zlc_next) {
1856 for (i = 0; i < z->zlc_n; i++) {
1857 (void)sprintf(fname, "%s\\%s", path, z->zlc_names[i]);
1858 if (namei_unlink(fname) < 0) {
1859 Log("ZLC: Can't unlink %s, dos error = %d\n", fname,
1863 z->zlc_n = 0; /* Can reuse space. */
1876 tnext = i->zlc_next;
1880 zlcCur = zlcAnchor = NULL;
1884 #endif /* AFS_NAMEI_ENV */