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 "volume_inline.h"
44 #include <afs/errors.h>
46 /*@+fcnmacros +macrofcndecl@*/
49 extern off64_t afs_lseek(int FD, off64_t O, int F);
50 #endif /*S_SPLINT_S */
51 #define afs_lseek(FD, O, F) lseek64(FD, (off64_t)(O), F)
52 #define afs_stat stat64
53 #define afs_fstat fstat64
54 #define afs_open open64
55 #define afs_fopen fopen64
56 #else /* !O_LARGEFILE */
58 extern off_t afs_lseek(int FD, off_t O, int F);
59 #endif /*S_SPLINT_S */
60 #define afs_lseek(FD, O, F) lseek(FD, (off_t)(O), F)
62 #define afs_fstat fstat
64 #define afs_fopen fopen
65 #endif /* !O_LARGEFILE */
66 /*@=fcnmacros =macrofcndecl@*/
68 /*@printflike@*/ extern void Log(const char *format, ...);
71 #define LOCK_SH 1 /* shared lock */
72 #define LOCK_EX 2 /* exclusive lock */
73 #define LOCK_NB 4 /* don't block when locking */
74 #define LOCK_UN 8 /* unlock */
81 * This function emulates a subset of flock()
84 emul_flock(int fd, int cmd)
87 memset(&f, 0, sizeof (f));
96 return fcntl(fd, (cmd & LOCK_NB) ? F_SETLK : F_SETLKW, &f);
99 #define flock(f,c) emul_flock(f,c)
106 namei_iread(IHandle_t * h, afs_foff_t offset, char *buf, afs_fsize_t size)
115 if (FDH_SEEK(fdP, offset, SEEK_SET) < 0) {
116 FDH_REALLYCLOSE(fdP);
120 nBytes = FDH_READ(fdP, buf, size);
126 namei_iwrite(IHandle_t * h, afs_foff_t offset, char *buf, afs_fsize_t size)
135 if (FDH_SEEK(fdP, offset, SEEK_SET) < 0) {
136 FDH_REALLYCLOSE(fdP);
139 nBytes = FDH_WRITE(fdP, buf, size);
146 /* Inode number format:
147 * low 26 bits - vnode number - all 1's if volume special file.
149 * next 3 bits spare (0's)
150 * high 32 bits - uniquifier (regular) or type if spare
152 #define NAMEI_VNODEMASK 0x003ffffff
153 #define NAMEI_TAGMASK 0x7
154 #define NAMEI_TAGSHIFT 26
155 #define NAMEI_UNIQMASK 0xffffffff
156 #define NAMEI_UNIQSHIFT 32
157 #define NAMEI_INODESPECIAL ((Inode)NAMEI_VNODEMASK)
158 #define NAMEI_VNODESPECIAL NAMEI_VNODEMASK
160 /* dir1 is the high 8 bits of the 26 bit vnode */
161 #define VNO_DIR1(vno) ((vno >> 14) & 0xff)
162 /* dir2 is the next 9 bits */
163 #define VNO_DIR2(vno) ((vno >> 9) & 0x1ff)
164 /* "name" is the low 9 bits of the vnode, the 3 bit tag and the uniq */
166 #define NAMEI_SPECDIR "special"
167 #define NAMEI_SPECDIRLEN (sizeof(NAMEI_SPECDIR)-1)
169 #define NAMEI_MAXVOLS 5 /* Maximum supported number of volumes per volume
170 * group, not counting temporary (move) volumes.
171 * This is the number of separate files, all having
172 * the same vnode number, which can occur in a volume
183 static int namei_GetLinkCount2(FdHandle_t * h, Inode ino, int lockit, int fixup, int nowrite);
185 static int GetFreeTag(IHandle_t * ih, int vno);
187 /* namei_HandleToInodeDir
189 * Construct the path name of the directory holding the inode data.
190 * Format: /<vicepx>/INODEDIR
193 #define PNAME_BLEN 64
195 namei_HandleToInodeDir(namei_t * name, IHandle_t * ih)
199 memset(name, '\0', sizeof(*name));
202 * Add the /vicepXX string to the start of name->n_base and then calculate
203 * offset as the number of bytes we know we added.
205 * FIXME: This embeds knowledge of the vice partition naming scheme and
206 * mapping from device numbers. There needs to be an API that tells us
209 volutil_PartitionName_r(ih->ih_dev, name->n_base, sizeof(name->n_base));
210 offset = VICE_PREFIX_SIZE + (ih->ih_dev > 25 ? 2 : 1);
211 name->n_base[offset] = '/';
213 strlcpy(name->n_base + offset, INODEDIR, sizeof(name->n_base) - offset);
214 strlcpy(name->n_path, name->n_base, sizeof(name->n_path));
217 #define addtoname(N, C) \
219 strlcat((N)->n_path, "/", sizeof((N)->n_path)); \
220 strlcat((N)->n_path, (C), sizeof((N)->n_path)); \
225 namei_HandleToVolDir(namei_t * name, IHandle_t * ih)
229 namei_HandleToInodeDir(name, ih);
230 (void)int32_to_flipbase64(tmp, (int64_t) (ih->ih_vid & 0xff));
231 strlcpy(name->n_voldir1, tmp, sizeof(name->n_voldir1));
232 addtoname(name, name->n_voldir1);
233 (void)int32_to_flipbase64(tmp, (int64_t) ih->ih_vid);
234 strlcpy(name->n_voldir2, tmp, sizeof(name->n_voldir2));
235 addtoname(name, name->n_voldir2);
238 /* namei_HandleToName
240 * Constructs a file name for the fully qualified handle.
241 * Note that special files end up in /vicepX/InodeDir/Vxx/V*.data/special
244 namei_HandleToName(namei_t * name, IHandle_t * ih)
247 int vno = (int)(ih->ih_ino & NAMEI_VNODEMASK);
249 namei_HandleToVolDir(name, ih);
251 if (vno == NAMEI_VNODESPECIAL) {
252 strlcpy(name->n_dir1, NAMEI_SPECDIR, sizeof(name->n_dir1));
253 addtoname(name, name->n_dir1);
254 name->n_dir2[0] = '\0';
256 (void)int32_to_flipbase64(str, VNO_DIR1(vno));
257 strlcpy(name->n_dir1, str, sizeof(name->n_dir1));
258 addtoname(name, name->n_dir1);
259 (void)int32_to_flipbase64(str, VNO_DIR2(vno));
260 strlcpy(name->n_dir2, str, sizeof(name->n_dir2));
261 addtoname(name, name->n_dir2);
263 (void)int64_to_flipbase64(str, (int64_t) ih->ih_ino);
264 strlcpy(name->n_inode, str, sizeof(name->n_inode));
265 addtoname(name, name->n_inode);
268 /* The following is a warning to tell sys-admins to not muck about in this
271 #define VICE_README "These files and directories are a part of the AFS \
272 namespace. Modifying them\nin any way will result in loss of AFS data,\n\
273 ownership and permissions included.\n"
275 namei_ViceREADME(char *partition)
280 /* Create the inode directory if we're starting for the first time */
281 (void)afs_snprintf(filename, sizeof filename, "%s/%s", partition,
283 mkdir(filename, 0700);
285 (void)afs_snprintf(filename, sizeof filename, "%s/%s/README", partition,
287 fd = afs_open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0444);
289 (void)write(fd, VICE_README, strlen(VICE_README));
296 #define create_dir() \
298 if (mkdir(tmp, 0700)<0) { \
299 if (errno != EEXIST) \
307 #define create_nextdir(A) \
309 strcat(tmp, "/"); strcat(tmp, A); create_dir(); \
312 /* namei_CreateDataDirectories
314 * If creating the file failed because of ENOENT or ENOTDIR, try
315 * creating all the directories first.
318 namei_CreateDataDirectories(namei_t * name, int *created)
324 strlcpy(tmp, name->n_base, sizeof(tmp));
327 create_nextdir(name->n_voldir1);
328 create_nextdir(name->n_voldir2);
329 create_nextdir(name->n_dir1);
330 if (name->n_dir2[0]) {
331 create_nextdir(name->n_dir2);
336 /* delTree(): Deletes an entire tree of directories (no files)
338 * root : Full path to the subtree. Should be big enough for PATH_MAX
339 * tree : the subtree to be deleted is rooted here. Specifies only the
340 * subtree beginning at tree (not the entire path). It should be
341 * a pointer into the "root" buffer.
343 * errp : errno of the first error encountered during the directory cleanup.
344 * *errp should have been initialized to 0.
347 * -1 : If errors were encountered during cleanup and error is set to
351 * If there are errors, we try to work around them and delete as many
352 * directories as possible. We don't attempt to remove directories that still
353 * have non-dir entries in them.
356 delTree(char *root, char *tree, int *errp)
364 /* delete the children first */
365 cp = strchr(tree, '/');
367 delTree(root, cp + 1, errp);
370 cp = tree + strlen(tree); /* move cp to the end of string tree */
372 /* now delete all entries in this dir */
373 if ((ds = opendir(root)) != (DIR *) NULL) {
375 while ((dirp = readdir(ds))) {
376 /* ignore . and .. */
377 if (!strcmp(dirp->d_name, ".") || !strcmp(dirp->d_name, ".."))
379 /* since root is big enough, we reuse the space to
380 * concatenate the dirname to the current tree
383 strcat(root, dirp->d_name);
384 if (afs_stat(root, &st) == 0 && S_ISDIR(st.st_mode)) {
385 /* delete this subtree */
386 delTree(root, cp + 1, errp);
388 *errp = *errp ? *errp : errno;
390 /* recover path to our cur tree by truncating it to
395 /* if (!errno) -- closedir not implicit if we got an error */
399 /* finally axe the current dir */
401 *errp = *errp ? *errp : errno;
403 #ifndef AFS_PTHREAD_ENV /* let rx get some work done */
405 #endif /* !AFS_PTHREAD_ENV */
410 /* if we encountered errors during cleanup, we return a -1 */
418 /* namei_RemoveDataDirectories
420 * Returns 0 on success.
421 * Returns -1 on error. Typically, callers ignore this error bcause we
422 * can continue running if the removes fail. The salvage process will
423 * finish tidying up for us. We only use the n_base and n_voldir1 entries
424 * and only do rmdir's.
428 namei_RemoveDataDirectories(namei_t * name)
430 char pbuf[MAXPATHLEN], *path = pbuf;
431 int prefixlen = strlen(name->n_base), err = 0;
433 strlcpy(path, name->n_path, sizeof(pbuf));
435 /* move past the prefix */
436 path = path + prefixlen + 1; /* skip over the trailing / */
438 /* now delete all dirs upto path */
439 return delTree(pbuf, path, &err);
443 /* Create the file in the name space.
445 * Parameters stored as follows:
447 * p1 - volid - implied in containing directory.
448 * p2 - vnode - name is <vno:31-23>/<vno:22-15>/<vno:15-0><uniq:31-5><tag:2-0>
449 * p3 - uniq -- bits 4-0 are in mode bits 4-0
450 * p4 - dv ---- dv:15-0 in uid, dv:29-16 in gid, dv:31-30 in mode:6-5
452 * p1 - volid - creation time - dwHighDateTime
453 * p2 - vnode - -1 means special, file goes in "S" subdirectory.
454 * p3 - type -- name is <type>.<tag> where tag is a file name unqiquifier.
455 * p4 - parid - parent volume id - implied in containing directory.
457 * Return value is the inode number or (Inode)-1 if error.
458 * We "know" there is only one link table, so return EEXIST if there already
459 * is a link table. It's up to the calling code to test errno and increment
465 * This function is called by VCreateVolume to hide the implementation
466 * details of the inode numbers. This only allows for 7 volume special
467 * types, but if we get that far, this could should be dead by then.
470 namei_MakeSpecIno(int volid, int type)
473 ino = NAMEI_INODESPECIAL;
474 type &= NAMEI_TAGMASK;
475 ino |= ((Inode) type) << NAMEI_TAGSHIFT;
476 ino |= ((Inode) volid) << NAMEI_UNIQSHIFT;
480 /* SetOGM - set owner group and mode bits from parm and tag
482 * owner - low 15 bits of parm.
483 * group - next 15 bits of parm.
484 * mode - 2 bits of parm, then lowest = 3 bits of tag.
487 SetOGM(int fd, int parm, int tag)
489 int owner, group, mode;
491 owner = parm & 0x7fff;
492 group = (parm >> 15) & 0x7fff;
493 if (fchown(fd, owner, group) < 0)
496 mode = (parm >> 27) & 0x18;
498 if (fchmod(fd, mode) < 0)
505 /* GetOGM - get parm and tag from owner, group and mode bits. */
507 GetOGMFromStat(struct afs_stat *status, int *parm, int *tag)
509 *parm = status->st_uid | (status->st_gid << 15);
510 *parm |= (status->st_mode & 0x18) << 27;
511 *tag = status->st_mode & 0x7;
515 GetOGM(int fd, int *parm, int *tag)
517 struct afs_stat status;
518 if (afs_fstat(fd, &status) < 0)
521 GetOGMFromStat(&status, parm, tag);
525 int big_vno = 0; /* Just in case we ever do 64 bit vnodes. */
527 /* Derive the name and create it O_EXCL. If that fails we have an error.
528 * Get the tag from a free column in the link table.
531 namei_icreate(IHandle_t * lh, char *part, int p1, int p2, int p3, int p4)
544 memset((void *)&tmp, 0, sizeof(IHandle_t));
547 tmp.ih_dev = volutil_GetPartitionID(part);
548 if (tmp.ih_dev == -1) {
554 /* Parameters for special file:
555 * p1 - volume id - goes into owner/group/mode
558 * p4 - parent volume id
563 tmp.ih_vid = p4; /* Use parent volume id, where this file will be. */
564 tmp.ih_ino = namei_MakeSpecIno(p1, p3);
566 int vno = p2 & NAMEI_VNODEMASK;
567 /* Parameters for regular file:
579 /* If GetFreeTag succeeds, it atomically sets link count to 1. */
580 tag = GetFreeTag(lh, p2);
584 /* name is <uniq(p3)><tag><vno(p2)> */
586 tmp.ih_ino = (Inode) p2;
587 tmp.ih_ino |= ((Inode) tag) << NAMEI_TAGSHIFT;
588 tmp.ih_ino |= ((Inode) p3) << NAMEI_UNIQSHIFT;
593 namei_HandleToName(&name, &tmp);
594 fd = afs_open(name.n_path, O_CREAT | O_EXCL | O_TRUNC | O_RDWR, 0);
596 if (errno == ENOTDIR || errno == ENOENT) {
597 if (namei_CreateDataDirectories(&name, &created_dir) < 0)
599 fd = afs_open(name.n_path, O_CREAT | O_EXCL | O_TRUNC | O_RDWR,
607 if (SetOGM(fd, ogm_parm, tag) < 0) {
613 if (p2 == -1 && p3 == VI_LINKTABLE) {
614 /* hack at tmp to setup for set link count call. */
615 memset((void *)&tfd, 0, sizeof(FdHandle_t)); /* minimalistic still, but a little cleaner */
618 code = namei_SetLinkCount(&tfd, (Inode) 0, 1, 0);
626 if (code || (fd < 0)) {
630 namei_SetLinkCount(fdP, tmp.ih_ino, 0, 0);
635 return (code || (fd < 0)) ? (Inode) - 1 : tmp.ih_ino;
641 namei_iopen(IHandle_t * h)
646 /* Convert handle to file name. */
647 namei_HandleToName(&name, h);
648 fd = afs_open(name.n_path, O_RDWR, 0666);
652 /* Need to detect vol special file and just unlink. In those cases, the
653 * handle passed in _is_ for the inode. We only check p1 for the special
657 namei_dec(IHandle_t * ih, Inode ino, int p1)
664 if ((ino & NAMEI_INODESPECIAL) == NAMEI_INODESPECIAL) {
667 int type = (int)((ino >> NAMEI_TAGSHIFT) & NAMEI_TAGMASK);
669 /* Verify this is the right file. */
670 IH_INIT(tmp, ih->ih_dev, ih->ih_vid, ino);
679 if ((GetOGM(fdP->fd_fd, &inode_p1, &tag) < 0) || (inode_p1 != p1)) {
680 FDH_REALLYCLOSE(fdP);
686 /* If it's the link table itself, decrement the link count. */
687 if (type == VI_LINKTABLE) {
688 if ((count = namei_GetLinkCount(fdP, (Inode) 0, 1)) < 0) {
689 FDH_REALLYCLOSE(fdP);
695 if (namei_SetLinkCount(fdP, (Inode) 0, count < 0 ? 0 : count, 1) <
697 FDH_REALLYCLOSE(fdP);
703 FDH_REALLYCLOSE(fdP);
709 namei_HandleToName(&name, tmp);
710 if ((code = unlink(name.n_path)) == 0) {
711 if (type == VI_LINKTABLE) {
712 /* Try to remove directory. If it fails, that's ok.
713 * Salvage will clean up.
715 (void)namei_RemoveDataDirectories(&name);
718 FDH_REALLYCLOSE(fdP);
721 /* Get a file descriptor handle for this Inode */
727 if ((count = namei_GetLinkCount(fdP, ino, 1)) < 0) {
728 FDH_REALLYCLOSE(fdP);
734 if (namei_SetLinkCount(fdP, ino, count, 1) < 0) {
735 FDH_REALLYCLOSE(fdP);
740 IH_INIT(th, ih->ih_dev, ih->ih_vid, ino);
741 Log("Warning: Lost ref on ihandle dev %d vid %d ino %" AFS_INT64_FMT "\n",
742 th->ih_dev, th->ih_vid, (int64_t) th->ih_ino);
745 /* If we're less than 0, someone presumably unlinked;
746 don't bother setting count to 0, but we need to drop a lock */
747 if (namei_SetLinkCount(fdP, ino, 0, 1) < 0) {
748 FDH_REALLYCLOSE(fdP);
754 IH_INIT(th, ih->ih_dev, ih->ih_vid, ino);
756 namei_HandleToName(&name, th);
758 code = unlink(name.n_path);
767 namei_inc(IHandle_t * h, Inode ino, int p1)
773 if ((ino & NAMEI_INODESPECIAL) == NAMEI_INODESPECIAL) {
774 int type = (int)((ino >> NAMEI_TAGSHIFT) & NAMEI_TAGMASK);
775 if (type != VI_LINKTABLE)
780 /* Get a file descriptor handle for this Inode */
786 if ((count = namei_GetLinkCount(fdP, ino, 1)) < 0)
795 if (namei_SetLinkCount(fdP, ino, count, 1) < 0)
799 FDH_REALLYCLOSE(fdP);
807 namei_replace_file_by_hardlink(IHandle_t *hLink, IHandle_t *hTarget)
813 /* Convert handle to file name. */
814 namei_HandleToName(&nameLink, hLink);
815 namei_HandleToName(&nameTarget, hTarget);
817 unlink(nameLink.n_path);
818 code = link(nameTarget.n_path, nameLink.n_path);
823 namei_copy_on_write(IHandle_t *h)
825 afs_int32 fd, code = 0;
828 struct afs_stat tstat;
830 namei_HandleToName(&name, h);
831 if (afs_stat(name.n_path, &tstat) < 0)
833 if (tstat.st_nlink > 1) { /* do a copy on write */
842 afs_snprintf(path, sizeof(path), "%s-tmp", name.n_path);
843 fd = afs_open(path, O_CREAT | O_EXCL | O_TRUNC | O_RDWR, 0);
855 size = tstat.st_size;
858 tlen = size > 8192 ? 8192 : size;
859 if (FDH_READ(fdP, buf, tlen) != tlen)
861 if (write(fd, buf, tlen) != tlen)
866 FDH_REALLYCLOSE(fdP);
872 code = rename(path, name.n_path);
878 /************************************************************************
879 * File Name Structure
880 ************************************************************************
882 * Each AFS file needs a unique name and it needs to be findable with
883 * minimal lookup time. Note that the constraint on the number of files and
884 * directories in a volume is the size of the vnode index files and the
885 * max file size AFS supports (for internal files) of 2^31. Since a record
886 * in the small vnode index file is 64 bytes long, we can have at most
887 * (2^31)/64 or 33554432 files. A record in the large index file is
888 * 256 bytes long, giving a maximum of (2^31)/256 = 8388608 directories.
889 * Another layout parameter is that there is roughly a 16 to 1 ratio between
890 * the number of files and the number of directories.
892 * Using this information we can see that a layout of 256 directories, each
893 * with 512 subdirectories and each of those having 512 files gives us
894 * 256*512*512 = 67108864 AFS files and directories.
896 * The volume, vnode, uniquifier and data version, as well as the tag
897 * are required, either for finding the file or for salvaging. It's best to
898 * restrict the name to something that can be mapped into 64 bits so the
899 * "Inode" is easily comparable (using "==") to other "Inodes". The tag
900 * is used to distinguish between different versions of the same file
901 * which are currently in the RW and clones of a volume. See "Link Table
902 * Organization" below for more information on the tag. The tag is
903 * required in the name of the file to ensure a unique name.
905 * We can store data in the uid, gid and mode bits of the files, provided
906 * the directories have root only access. This gives us 15 bits for each
907 * of uid and gid (GNU chown considers 65535 to mean "don't change").
908 * There are 9 available mode bits. Adn we need to store a total of
909 * 32 (volume id) + 26 (vnode) + 32 (uniquifier) + 32 (data-version) + 3 (tag)
910 * or 131 bits somewhere.
912 * The format of a file name for a regular file is:
913 * /vicepX/AFSIDat/V1/V2/AA/BB/<tag><uniq><vno>
914 * V1 - low 8 bits of RW volume id
915 * V2 - all bits of RW volume id
916 * AA - high 8 bits of vnode number.
917 * BB - next 9 bits of vnode number.
918 * <tag><uniq><vno> - file name
920 * Volume special files are stored in a separate directory:
921 * /vicepX/AFSIDat/V1/V2/special/<tag><uniq><vno>
924 * The vnode is hashed into the directory using the high bits of the
925 * vnode number. This is so that consecutively created vnodes are in
926 * roughly the same area on the disk. This will at least be optimal if
927 * the user is creating many files in the same AFS directory. The name
928 * should be formed so that the leading characters are different as quickly
929 * as possible, leading to faster discards of incorrect matches in the
935 /************************************************************************
936 * Link Table Organization
937 ************************************************************************
939 * The link table volume special file is used to hold the link counts that
940 * are held in the inodes in inode based AFS vice filesystems. For user
941 * space access, the link counts are being kept in a separate
942 * volume special file. The file begins with the usual version stamp
943 * information and is then followed by one row per vnode number. vnode 0
944 * is used to hold the link count of the link table itself. That is because
945 * the same link table is shared among all the volumes of the volume group
946 * and is deleted only when the last volume of a volume group is deleted.
948 * Within each row, the columns are 3 bits wide. They can each hold a 0 based
949 * link count from 0 through 7. Each colume represents a unique instance of
950 * that vnode. Say we have a file shared between the RW and a RO and a
951 * different version of the file (or a different uniquifer) for the BU volume.
952 * Then one column would be holding the link count of 2 for the RW and RO
953 * and a different column would hold the link count of 1 for the BU volume.
954 * Note that we allow only 5 volumes per file, giving 15 bits used in the
957 #define LINKTABLE_WIDTH 2
958 #define LINKTABLE_SHIFT 1 /* log 2 = 1 */
961 namei_GetLCOffsetAndIndexFromIno(Inode ino, afs_foff_t * offset, int *index)
963 int toff = (int)(ino & NAMEI_VNODEMASK);
964 int tindex = (int)((ino >> NAMEI_TAGSHIFT) & NAMEI_TAGMASK);
966 *offset = (afs_foff_t) ((toff << LINKTABLE_SHIFT) + 8); /* * 2 + sizeof stamp */
967 *index = (tindex << 1) + tindex;
971 /* namei_GetLinkCount
972 * If lockit is set, lock the file and leave it locked upon a successful
976 namei_GetLinkCount2(FdHandle_t * h, Inode ino, int lockit, int fixup, int nowrite)
978 unsigned short row = 0;
983 /* there's no linktable yet. the salvager will create one later */
984 if (h->fd_fd == -1 && fixup)
986 namei_GetLCOffsetAndIndexFromIno(ino, &offset, &index);
989 if (flock(h->fd_fd, LOCK_EX) < 0)
993 if (afs_lseek(h->fd_fd, offset, SEEK_SET) == -1)
994 goto bad_getLinkByte;
996 rc = read(h->fd_fd, (char *)&row, sizeof(row));
997 if ((rc == 0 || !((row >> index) & NAMEI_TAGMASK)) && fixup && nowrite)
999 if (rc == 0 && fixup) {
1001 if (fstat(h->fd_fd, &st) || st.st_size >= offset+sizeof(row))
1002 goto bad_getLinkByte;
1003 FDH_TRUNC(h, offset+sizeof(row));
1005 rc = write(h->fd_fd, (char *)&row, sizeof(row));
1007 if (rc != sizeof(row)) {
1008 goto bad_getLinkByte;
1011 if (fixup && !((row >> index) & NAMEI_TAGMASK)) {
1013 if (afs_lseek(h->fd_fd, offset, SEEK_SET) == -1)
1014 goto bad_getLinkByte;
1015 rc = write(h->fd_fd, (char *)&row, sizeof(row));
1016 if (rc != sizeof(row))
1017 goto bad_getLinkByte;
1020 return (int)((row >> index) & NAMEI_TAGMASK);
1024 flock(h->fd_fd, LOCK_UN);
1029 namei_GetLinkCount(FdHandle_t * h, Inode ino, int lockit)
1031 return namei_GetLinkCount2(h, ino, lockit, 0, 1);
1034 /* Return a free column index for this vnode. */
1036 GetFreeTag(IHandle_t * ih, int vno)
1050 /* Only one manipulates at a time. */
1051 if (flock(fdP->fd_fd, LOCK_EX) < 0) {
1052 FDH_REALLYCLOSE(fdP);
1056 offset = (vno << LINKTABLE_SHIFT) + 8; /* * 2 + sizeof stamp */
1057 if (afs_lseek(fdP->fd_fd, offset, SEEK_SET) == -1) {
1061 code = read(fdP->fd_fd, (char *)&row, sizeof(row));
1062 if (code != sizeof(row)) {
1068 /* Now find a free column in this row and claim it. */
1069 for (col = 0; col < NAMEI_MAXVOLS; col++) {
1070 coldata = 7 << (col * 3);
1071 if ((row & coldata) == 0)
1074 if (col >= NAMEI_MAXVOLS) {
1079 coldata = 1 << (col * 3);
1082 if (afs_lseek(fdP->fd_fd, offset, SEEK_SET) == -1) {
1085 if (write(fdP->fd_fd, (char *)&row, sizeof(row)) != sizeof(row)) {
1089 flock(fdP->fd_fd, LOCK_UN);
1090 FDH_REALLYCLOSE(fdP);
1094 flock(fdP->fd_fd, LOCK_UN);
1095 FDH_REALLYCLOSE(fdP);
1101 /* namei_SetLinkCount
1102 * If locked is set, assume file is locked. Otherwise, lock file before
1103 * proceeding to modify it.
1106 namei_SetLinkCount(FdHandle_t * fdP, Inode ino, int count, int locked)
1114 namei_GetLCOffsetAndIndexFromIno(ino, &offset, &index);
1117 if (flock(fdP->fd_fd, LOCK_EX) < 0) {
1121 if (afs_lseek(fdP->fd_fd, offset, SEEK_SET) == -1) {
1123 goto bad_SetLinkCount;
1127 code = read(fdP->fd_fd, (char *)&row, sizeof(row));
1128 if (code != sizeof(row)) {
1131 goto bad_SetLinkCount;
1138 row &= (unsigned short)~junk;
1139 row |= (unsigned short)count;
1141 if (afs_lseek(fdP->fd_fd, offset, SEEK_SET) == -1) {
1143 goto bad_SetLinkCount;
1146 if (write(fdP->fd_fd, (char *)&row, sizeof(short)) != sizeof(short)) {
1148 goto bad_SetLinkCount;
1156 flock(fdP->fd_fd, LOCK_UN);
1162 /* ListViceInodes - write inode data to a results file. */
1163 static int DecodeInode(char *dpath, char *name, struct ViceInodeInfo *info,
1164 unsigned int volid);
1165 static int DecodeVolumeName(char *name, unsigned int *vid);
1166 static int namei_ListAFSSubDirs(IHandle_t * dirIH,
1167 int (*write_fun) (FILE *,
1168 struct ViceInodeInfo *,
1169 char *, char *), FILE * fp,
1170 int (*judgeFun) (struct ViceInodeInfo *,
1171 afs_uint32 vid, void *),
1172 afs_uint32 singleVolumeNumber, void *rock);
1177 * Write the inode data to the results file.
1179 * Returns -2 on error, 0 on success.
1181 * This is written as a callback simply so that other listing routines
1182 * can use the same inode reading code.
1185 WriteInodeInfo(FILE * fp, struct ViceInodeInfo *info, char *dir, char *name)
1188 n = fwrite(info, sizeof(*info), 1, fp);
1189 return (n == 1) ? 0 : -2;
1193 int mode_errors; /* Number of errors found in mode bits on directories. */
1195 VerifyDirPerms(char *path)
1197 struct afs_stat status;
1199 if (afs_stat(path, &status) < 0) {
1200 Log("Unable to stat %s. Please manually verify mode bits for this"
1201 " directory\n", path);
1203 if (((status.st_mode & 0777) != 0700) || (status.st_uid != 0))
1209 * Fill the results file with the requested inode information.
1213 * -1 - complete failure, salvage should terminate.
1214 * -2 - not enough space on partition, salvager has error message for this.
1216 * This code optimizes single volume salvages by just looking at that one
1217 * volume's directory.
1219 * If the resultFile is NULL, then don't call the write routine.
1222 ListViceInodes(char *devname, char *mountedOn, FILE *inodeFile,
1223 int (*judgeInode) (struct ViceInodeInfo * info, afs_uint32 vid, void *rock),
1224 afs_uint32 singleVolumeNumber, int *forcep, int forceR, char *wpath,
1228 struct afs_stat status;
1230 *forcep = 0; /* no need to salvage until further notice */
1232 /* Verify protections on directories. */
1234 VerifyDirPerms(mountedOn);
1237 namei_ListAFSFiles(mountedOn, WriteInodeInfo, inodeFile, judgeInode,
1238 singleVolumeNumber, rock);
1247 if (fflush(inodeFile) == EOF) {
1248 Log("Unable to successfully flush inode file for %s\n", mountedOn);
1251 if (fsync(fileno(inodeFile)) == -1) {
1252 Log("Unable to successfully fsync inode file for %s\n", mountedOn);
1257 * Paranoia: check that the file is really the right size
1259 if (afs_fstat(fileno(inodeFile), &status) == -1) {
1260 Log("Unable to successfully stat inode file for %s\n", mountedOn);
1263 if (status.st_size != ninodes * sizeof(struct ViceInodeInfo)) {
1264 Log("Wrong size (%d instead of %d) in inode file for %s\n",
1265 status.st_size, ninodes * sizeof(struct ViceInodeInfo),
1273 /* namei_ListAFSFiles
1275 * Collect all the matching AFS files on the drive.
1276 * If singleVolumeNumber is non-zero, just return files for that volume.
1278 * Returns <0 on error, else number of files found to match.
1281 namei_ListAFSFiles(char *dev,
1282 int (*writeFun) (FILE *, struct ViceInodeInfo *, char *,
1284 int (*judgeFun) (struct ViceInodeInfo *, afs_uint32, void *),
1285 afs_uint32 singleVolumeNumber, void *rock)
1291 struct dirent *dp1, *dp2;
1294 static void FreeZLCList(void);
1297 memset((void *)&ih, 0, sizeof(IHandle_t));
1298 ih.ih_dev = volutil_GetPartitionID(dev);
1300 if (singleVolumeNumber) {
1301 ih.ih_vid = singleVolumeNumber;
1302 namei_HandleToVolDir(&name, &ih);
1304 namei_ListAFSSubDirs(&ih, writeFun, fp, judgeFun,
1305 singleVolumeNumber, rock);
1309 /* Find all volume data directories and descend through them. */
1310 namei_HandleToInodeDir(&name, &ih);
1312 dirp1 = opendir(name.n_path);
1315 while ((dp1 = readdir(dirp1))) {
1316 if (*dp1->d_name == '.')
1318 afs_snprintf(path2, sizeof(path2), "%s/%s", name.n_path,
1320 dirp2 = opendir(path2);
1322 while ((dp2 = readdir(dirp2))) {
1323 if (*dp2->d_name == '.')
1325 if (!DecodeVolumeName(dp2->d_name, &ih.ih_vid)) {
1327 namei_ListAFSSubDirs(&ih, writeFun, fp, judgeFun,
1344 /* namei_ListAFSSubDirs
1349 * > = 0 - number of AFS files found.
1352 namei_ListAFSSubDirs(IHandle_t * dirIH,
1353 int (*writeFun) (FILE *, struct ViceInodeInfo *, char *,
1355 int (*judgeFun) (struct ViceInodeInfo *, afs_uint32, void *),
1356 afs_uint32 singleVolumeNumber, void *rock)
1358 IHandle_t myIH = *dirIH;
1360 char path1[512], path2[512], path3[512];
1361 DIR *dirp1, *dirp2, *dirp3;
1362 struct dirent *dp1, *dp2, *dp3;
1363 struct ViceInodeInfo info;
1364 FdHandle_t linkHandle;
1368 static void AddToZLCDeleteList(char dir, char *name);
1369 static void DeleteZLCFiles(char *path);
1372 namei_HandleToVolDir(&name, &myIH);
1373 strlcpy(path1, name.n_path, sizeof(path1));
1375 /* Do the directory containing the special files first to pick up link
1378 (void)strcat(path1, "/");
1379 (void)strcat(path1, NAMEI_SPECDIR);
1381 linkHandle.fd_fd = -1;
1382 dirp1 = opendir(path1);
1384 while ((dp1 = readdir(dirp1))) {
1385 if (*dp1->d_name == '.')
1387 if (DecodeInode(path1, dp1->d_name, &info, myIH.ih_vid) < 0)
1389 if (info.u.param[2] != VI_LINKTABLE) {
1392 /* Open this handle */
1393 (void)afs_snprintf(path2, sizeof path2, "%s/%s", path1,
1395 linkHandle.fd_fd = afs_open(path2, Testing ? O_RDONLY : O_RDWR, 0666);
1397 namei_GetLinkCount2(&linkHandle, (Inode) 0, 1, 1, Testing);
1399 if (judgeFun && !(*judgeFun) (&info, singleVolumeNumber, rock))
1402 if ((*writeFun) (fp, &info, path1, dp1->d_name) < 0) {
1403 if (linkHandle.fd_fd >= 0)
1404 close(linkHandle.fd_fd);
1413 /* Now run through all the other subdirs */
1414 namei_HandleToVolDir(&name, &myIH);
1415 strlcpy(path1, name.n_path, sizeof(path1));
1417 dirp1 = opendir(path1);
1419 while ((dp1 = readdir(dirp1))) {
1420 if (*dp1->d_name == '.')
1422 if (!strcmp(dp1->d_name, NAMEI_SPECDIR))
1425 /* Now we've got a next level subdir. */
1426 afs_snprintf(path2, sizeof(path2), "%s/%s", path1, dp1->d_name);
1427 dirp2 = opendir(path2);
1429 while ((dp2 = readdir(dirp2))) {
1430 if (*dp2->d_name == '.')
1433 /* Now we've got to the actual data */
1434 afs_snprintf(path3, sizeof(path3), "%s/%s", path2,
1436 dirp3 = opendir(path3);
1438 while ((dp3 = readdir(dirp3))) {
1439 if (*dp3->d_name == '.')
1442 (path3, dp3->d_name, &info, myIH.ih_vid) < 0)
1445 namei_GetLinkCount2(&linkHandle,
1446 info.inodeNumber, 1, 1, Testing);
1447 if (info.linkCount == 0) {
1449 Log("Found 0 link count file %s/%s, deleting it.\n", path3, dp3->d_name);
1450 AddToZLCDeleteList((char)i, dp3->d_name);
1452 Log("Found 0 link count file %s/%s.\n", path3,
1458 && !(*judgeFun) (&info, singleVolumeNumber, rock))
1461 if ((*writeFun) (fp, &info, path3, dp3->d_name) <
1463 close(linkHandle.fd_fd);
1480 if (linkHandle.fd_fd >= 0)
1481 close(linkHandle.fd_fd);
1483 /* Then why does this directory exist? Blow it away. */
1484 namei_HandleToVolDir(&name, dirIH);
1485 namei_RemoveDataDirectories(&name);
1492 DecodeVolumeName(char *name, unsigned int *vid)
1494 if (strlen(name) <= 2)
1496 *vid = (unsigned int)flipbase64_to_int64(name);
1503 * Get the inode number from the name.
1507 DecodeInode(char *dpath, char *name, struct ViceInodeInfo *info,
1511 struct afs_stat status;
1513 lb64_string_t check;
1515 afs_snprintf(fpath, sizeof(fpath), "%s/%s", dpath, name);
1517 if (afs_stat(fpath, &status) < 0) {
1521 info->byteCount = status.st_size;
1522 info->inodeNumber = (Inode) flipbase64_to_int64(name);
1524 int64_to_flipbase64(check, info->inodeNumber);
1525 if (strcmp(name, check))
1528 GetOGMFromStat(&status, &parm, &tag);
1529 if ((info->inodeNumber & NAMEI_INODESPECIAL) == NAMEI_INODESPECIAL) {
1530 /* p1 - vid, p2 - -1, p3 - type, p4 - rwvid */
1531 info->u.param[0] = parm;
1532 info->u.param[1] = -1;
1533 info->u.param[2] = tag;
1534 info->u.param[3] = volid;
1536 /* p1 - vid, p2 - vno, p3 - uniq, p4 - dv */
1537 info->u.param[0] = volid;
1538 info->u.param[1] = (int)(info->inodeNumber & NAMEI_VNODEMASK);
1539 info->u.param[2] = (int)((info->inodeNumber >> NAMEI_UNIQSHIFT)
1540 & (Inode) NAMEI_UNIQMASK);
1541 info->u.param[3] = parm;
1547 * Convert the VolumeInfo file from RO to RW
1548 * this routine is called by namei_convertROtoRWvolume()
1551 #ifdef FSSYNC_BUILD_CLIENT
1553 convertVolumeInfo(int fdr, int fdw, afs_uint32 vid)
1555 struct VolumeDiskData vd;
1558 if (read(fdr, &vd, sizeof(struct VolumeDiskData)) !=
1559 sizeof(struct VolumeDiskData)) {
1560 Log("1 convertVolumeInfo: read failed for %lu with code %d\n", vid,
1564 vd.restoredFromId = vd.id; /* remember the RO volume here */
1566 vd.id = vd.parentId;
1570 vd.uniquifier += 5000; /* just in case there are still file copies from
1571 * the old RW volume around */
1572 p = strrchr(vd.name, '.');
1573 if (p && !strcmp(p, ".readonly")) {
1576 if (write(fdw, &vd, sizeof(struct VolumeDiskData)) !=
1577 sizeof(struct VolumeDiskData)) {
1578 Log("1 convertVolumeInfo: write failed for %lu with code %d\n", vid,
1587 * Convert a RO-volume into a RW-volume
1589 * This function allows to recover very fast from the loss of a partition
1590 * from RO-copies if all RO-Copies exist on another partition.
1591 * Then these RO-volumes can be made to the new RW-volumes.
1592 * Backup of RW-volumes then consists in "vos release".
1594 * We must make sure in this partition exists only the RO-volume which
1595 * is typical for remote replicas.
1597 * Then the linktable is already ok,
1598 * the vnode files need to be renamed
1599 * the volinfo file needs to be replaced by another one with
1600 * slightly different contents and new name.
1601 * The volume header file of the RO-volume in the /vicep<x> directory
1602 * is destroyed by this call. A new header file for the RW-volume must
1603 * be created after return from this routine.
1607 namei_ConvertROtoRWvolume(char *pname, afs_uint32 volumeId)
1610 #ifdef FSSYNC_BUILD_CLIENT
1612 char dir_name[512], oldpath[512], newpath[512];
1627 struct DiskPartition64 *partP;
1628 struct ViceInodeInfo info;
1629 struct VolumeDiskHeader h;
1630 # ifdef AFS_DEMAND_ATTACH_FS
1632 # endif /* AFS_DEMAND_ATTACH_FS */
1634 for (partP = DiskPartitionList; partP && strcmp(partP->name, pname);
1635 partP = partP->next);
1637 Log("1 namei_ConvertROtoRWvolume: Couldn't find DiskPartition for %s\n", pname);
1642 # ifdef AFS_DEMAND_ATTACH_FS
1643 locktype = VVolLockType(V_VOLUPD, 1);
1644 code = VLockVolumeByIdNB(volumeId, partP, locktype);
1650 # endif /* AFS_DEMAND_ATTACH_FS */
1652 if (VReadVolumeDiskHeader(volumeId, partP, &h)) {
1653 Log("1 namei_ConvertROtoRWvolume: Couldn't read header for RO-volume %lu.\n",
1654 afs_printable_uint32_lu(volumeId));
1659 FSYNC_VolOp(volumeId, pname, FSYNC_VOL_BREAKCBKS, 0, NULL);
1661 ino = namei_MakeSpecIno(h.parent, VI_LINKTABLE);
1662 IH_INIT(ih, partP->device, h.parent, ino);
1664 namei_HandleToName(&n, ih);
1665 strlcpy(dir_name, n.n_path, sizeof(dir_name));
1666 p = strrchr(dir_name, '/');
1668 dirp = opendir(dir_name);
1670 Log("1 namei_ConvertROtoRWvolume: Could not opendir(%s)\n", dir_name);
1675 while ((dp = readdir(dirp))) {
1676 /* struct ViceInodeInfo info; */
1678 if (*dp->d_name == '.')
1680 if (DecodeInode(dir_name, dp->d_name, &info, ih->ih_vid) < 0) {
1681 Log("1 namei_ConvertROtoRWvolume: DecodeInode failed for %s/%s\n",
1682 dir_name, dp->d_name);
1687 if (info.u.param[1] != -1) {
1688 Log("1 namei_ConvertROtoRWvolume: found other than volume special file %s/%s\n", dir_name, dp->d_name);
1693 if (info.u.param[0] != volumeId) {
1694 if (info.u.param[0] == ih->ih_vid) {
1695 if (info.u.param[2] == VI_LINKTABLE) { /* link table */
1700 Log("1 namei_ConvertROtoRWvolume: found special file %s/%s for volume %lu\n", dir_name, dp->d_name, info.u.param[0]);
1705 if (info.u.param[2] == VI_VOLINFO) { /* volume info file */
1706 strlcpy(infoName, dp->d_name, sizeof(infoName));
1708 } else if (info.u.param[2] == VI_SMALLINDEX) { /* small vnodes file */
1709 strlcpy(smallName, dp->d_name, sizeof(smallName));
1711 } else if (info.u.param[2] == VI_LARGEINDEX) { /* large vnodes file */
1712 strlcpy(largeName, dp->d_name, sizeof(largeName));
1716 Log("1 namei_ConvertROtoRWvolume: unknown type %d of special file found : %s/%s\n", info.u.param[2], dir_name, dp->d_name);
1723 if (!infoSeen || !smallSeen || !largeSeen || !linkSeen) {
1724 Log("1 namei_ConvertROtoRWvolume: not all special files found in %s\n", dir_name);
1730 * If we come here then there was only a RO-volume and we can safely
1734 memset(&t_ih, 0, sizeof(t_ih));
1735 t_ih.ih_dev = ih->ih_dev;
1736 t_ih.ih_vid = ih->ih_vid;
1738 (void)afs_snprintf(oldpath, sizeof oldpath, "%s/%s", dir_name, infoName);
1739 fd = afs_open(oldpath, O_RDWR, 0);
1741 Log("1 namei_ConvertROtoRWvolume: could not open RO info file: %s\n",
1746 t_ih.ih_ino = namei_MakeSpecIno(ih->ih_vid, VI_VOLINFO);
1747 namei_HandleToName(&n, &t_ih);
1748 fd2 = afs_open(n.n_path, O_CREAT | O_EXCL | O_TRUNC | O_RDWR, 0);
1750 Log("1 namei_ConvertROtoRWvolume: could not create RW info file: %s\n", n.n_path);
1755 code = convertVolumeInfo(fd, fd2, ih->ih_vid);
1763 SetOGM(fd2, ih->ih_vid, 1);
1766 t_ih.ih_ino = namei_MakeSpecIno(ih->ih_vid, VI_SMALLINDEX);
1767 namei_HandleToName(&n, &t_ih);
1768 (void)afs_snprintf(newpath, sizeof newpath, "%s/%s", dir_name, smallName);
1769 fd = afs_open(newpath, O_RDWR, 0);
1771 Log("1 namei_ConvertROtoRWvolume: could not open SmallIndex file: %s\n", newpath);
1775 SetOGM(fd, ih->ih_vid, 2);
1777 link(newpath, n.n_path);
1780 t_ih.ih_ino = namei_MakeSpecIno(ih->ih_vid, VI_LARGEINDEX);
1781 namei_HandleToName(&n, &t_ih);
1782 (void)afs_snprintf(newpath, sizeof newpath, "%s/%s", dir_name, largeName);
1783 fd = afs_open(newpath, O_RDWR, 0);
1785 Log("1 namei_ConvertROtoRWvolume: could not open LargeIndex file: %s\n", newpath);
1789 SetOGM(fd, ih->ih_vid, 3);
1791 link(newpath, n.n_path);
1797 h.volumeInfo_hi = h.id;
1798 h.smallVnodeIndex_hi = h.id;
1799 h.largeVnodeIndex_hi = h.id;
1800 h.linkTable_hi = h.id;
1802 if (VCreateVolumeDiskHeader(&h, partP)) {
1803 Log("1 namei_ConvertROtoRWvolume: Couldn't write header for RW-volume %lu\n",
1804 afs_printable_uint32_lu(h.id));
1809 if (VDestroyVolumeDiskHeader(partP, volumeId, h.parent)) {
1810 Log("1 namei_ConvertROtoRWvolume: Couldn't unlink header for RO-volume %lu\n",
1811 afs_printable_uint32_lu(volumeId));
1814 FSYNC_VolOp(volumeId, pname, FSYNC_VOL_DONE, 0, NULL);
1815 FSYNC_VolOp(h.id, pname, FSYNC_VOL_ON, 0, NULL);
1818 # ifdef AFS_DEMAND_ATTACH_FS
1820 VUnlockVolumeById(volumeId, partP);
1822 # endif /* AFS_DEMAND_ATTACH_FS */
1830 * returns a static string used to print either 32 or 64 bit inode numbers.
1833 PrintInode(char *s, Inode ino)
1835 static afs_ino_str_t result;
1839 (void)afs_snprintf(s, sizeof(afs_ino_str_t), "%llu", (afs_uintmax_t) ino);
1846 /* Routines to facilitate removing zero link count files. */
1847 #define MAX_ZLC_NAMES 32
1848 #define MAX_ZLC_NAMELEN 16
1849 typedef struct zlcList_s {
1850 struct zlcList_s *zlc_next;
1852 char zlc_names[MAX_ZLC_NAMES][MAX_ZLC_NAMELEN];
1855 static zlcList_t *zlcAnchor = NULL;
1856 static zlcList_t *zlcCur = NULL;
1859 AddToZLCDeleteList(char dir, char *name)
1861 assert(strlen(name) <= MAX_ZLC_NAMELEN - 3);
1863 if (!zlcCur || zlcCur->zlc_n >= MAX_ZLC_NAMES) {
1864 if (zlcCur && zlcCur->zlc_next)
1865 zlcCur = zlcCur->zlc_next;
1867 zlcList_t *tmp = (zlcList_t *) malloc(sizeof(zlcList_t));
1873 zlcCur->zlc_next = tmp;
1877 zlcCur->zlc_next = NULL;
1881 (void)sprintf(zlcCur->zlc_names[zlcCur->zlc_n], "%c\\%s", dir, name);
1886 DeleteZLCFiles(char *path)
1892 for (z = zlcAnchor; z; z = z->zlc_next) {
1893 for (i = 0; i < z->zlc_n; i++) {
1894 (void)sprintf(fname, "%s\\%s", path, z->zlc_names[i]);
1895 if (namei_unlink(fname) < 0) {
1896 Log("ZLC: Can't unlink %s, dos error = %d\n", fname,
1900 z->zlc_n = 0; /* Can reuse space. */
1913 tnext = i->zlc_next;
1917 zlcCur = zlcAnchor = NULL;
1921 #endif /* AFS_NAMEI_ENV */