ihandle positional read and write
[openafs.git] / src / vol / namei_ops.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 /* I/O operations for the Unix open by name (namei) interface. */
11
12 #include <afsconfig.h>
13 #include <afs/param.h>
14
15
16 #ifdef AFS_NAMEI_ENV
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <unistd.h>
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <sys/stat.h>
23 #include <dirent.h>
24 #include <afs/assert.h>
25 #include <string.h>
26 #include <sys/file.h>
27 #include <sys/param.h>
28 #include <lock.h>
29 #if defined(AFS_SUN5_ENV) || defined(AFS_HPUX_ENV)
30 #include <unistd.h>
31 #endif
32 #include <afs/afsutil.h>
33 #include <lwp.h>
34 #include "nfs.h"
35 #include <afs/afsint.h>
36 #include "ihandle.h"
37 #include "vnode.h"
38 #include "volume.h"
39 #include "viceinode.h"
40 #include "voldefs.h"
41 #include "partition.h"
42 #include "fssync.h"
43 #include "volume_inline.h"
44 #include "common.h"
45 #include <afs/errors.h>
46
47 /*@+fcnmacros +macrofcndecl@*/
48 #ifdef O_LARGEFILE
49 #ifdef S_SPLINT_S
50 #endif /*S_SPLINT_S */
51 #define afs_stat                stat64
52 #define afs_fstat               fstat64
53 #define afs_open                open64
54 #define afs_fopen               fopen64
55 #else /* !O_LARGEFILE */
56 #ifdef S_SPLINT_S
57 #endif /*S_SPLINT_S */
58 #define afs_stat                stat
59 #define afs_fstat               fstat
60 #define afs_open                open
61 #define afs_fopen               fopen
62 #endif /* !O_LARGEFILE */
63 /*@=fcnmacros =macrofcndecl@*/
64
65 #ifndef LOCK_SH
66 #define   LOCK_SH   1    /* shared lock */
67 #define   LOCK_EX   2    /* exclusive lock */
68 #define   LOCK_NB   4    /* don't block when locking */
69 #define   LOCK_UN   8    /* unlock */
70 #endif
71
72 #ifndef HAVE_FLOCK
73 #include <fcntl.h>
74
75 /*
76  * This function emulates a subset of flock()
77  */
78 int
79 emul_flock(int fd, int cmd)
80 {    struct flock f;
81
82     memset(&f, 0, sizeof (f));
83
84     if (cmd & LOCK_UN)
85         f.l_type = F_UNLCK;
86     if (cmd & LOCK_SH)
87         f.l_type = F_RDLCK;
88     if (cmd & LOCK_EX)
89         f.l_type = F_WRLCK;
90
91     return fcntl(fd, (cmd & LOCK_NB) ? F_SETLK : F_SETLKW, &f);
92 }
93
94 #define flock(f,c)      emul_flock(f,c)
95 #endif
96
97 int Testing=0;
98
99
100 afs_sfsize_t
101 namei_iread(IHandle_t * h, afs_foff_t offset, char *buf, afs_fsize_t size)
102 {
103     afs_sfsize_t nBytes;
104     FdHandle_t *fdP;
105
106     fdP = IH_OPEN(h);
107     if (fdP == NULL)
108         return -1;
109
110     nBytes = FDH_PREAD(fdP, buf, size, offset);
111     FDH_CLOSE(fdP);
112     return nBytes;
113 }
114
115 afs_sfsize_t
116 namei_iwrite(IHandle_t * h, afs_foff_t offset, char *buf, afs_fsize_t size)
117 {
118     afs_sfsize_t nBytes;
119     FdHandle_t *fdP;
120
121     fdP = IH_OPEN(h);
122     if (fdP == NULL)
123         return -1;
124
125     nBytes = FDH_PWRITE(fdP, buf, size, offset);
126     FDH_CLOSE(fdP);
127     return nBytes;
128 }
129
130
131
132 /* Inode number format:
133  * low 26 bits - vnode number - all 1's if volume special file.
134  * next 3 bits - tag
135  * next 3 bits spare (0's)
136  * high 32 bits - uniquifier (regular) or type if spare
137  */
138 #define NAMEI_VNODEMASK    0x003ffffff
139 #define NAMEI_TAGMASK      0x7
140 #define NAMEI_TAGSHIFT     26
141 #define NAMEI_UNIQMASK     0xffffffff
142 #define NAMEI_UNIQSHIFT    32
143 #define NAMEI_INODESPECIAL ((Inode)NAMEI_VNODEMASK)
144 #define NAMEI_VNODESPECIAL NAMEI_VNODEMASK
145
146 /* dir1 is the high 8 bits of the 26 bit vnode */
147 #define VNO_DIR1(vno) ((vno >> 14) & 0xff)
148 /* dir2 is the next 9 bits */
149 #define VNO_DIR2(vno) ((vno >> 9) & 0x1ff)
150 /* "name" is the low 9 bits of the vnode, the 3 bit tag and the uniq */
151
152 #define NAMEI_SPECDIR "special"
153 #define NAMEI_SPECDIRLEN (sizeof(NAMEI_SPECDIR)-1)
154
155 #define NAMEI_MAXVOLS 5         /* Maximum supported number of volumes per volume
156                                  * group, not counting temporary (move) volumes.
157                                  * This is the number of separate files, all having
158                                  * the same vnode number, which can occur in a volume
159                                  * group at once.
160                                  */
161
162
163 typedef struct {
164     int ogm_owner;
165     int ogm_group;
166     int ogm_mode;
167 } namei_ogm_t;
168
169 static int namei_GetLinkCount2(FdHandle_t * h, Inode ino, int lockit, int fixup, int nowrite);
170
171 static int GetFreeTag(IHandle_t * ih, int vno);
172
173 /* namei_HandleToInodeDir
174  *
175  * Construct the path name of the directory holding the inode data.
176  * Format: /<vicepx>/INODEDIR
177  *
178  */
179 #define PNAME_BLEN 64
180 static void
181 namei_HandleToInodeDir(namei_t * name, IHandle_t * ih)
182 {
183     size_t offset;
184
185     memset(name, '\0', sizeof(*name));
186
187     /*
188      * Add the /vicepXX string to the start of name->n_base and then calculate
189      * offset as the number of bytes we know we added.
190      *
191      * FIXME: This embeds knowledge of the vice partition naming scheme and
192      * mapping from device numbers.  There needs to be an API that tells us
193      * this offset.
194      */
195     volutil_PartitionName_r(ih->ih_dev, name->n_base, sizeof(name->n_base));
196     offset = VICE_PREFIX_SIZE + (ih->ih_dev > 25 ? 2 : 1);
197     name->n_base[offset] = '/';
198     offset++;
199     strlcpy(name->n_base + offset, INODEDIR, sizeof(name->n_base) - offset);
200     strlcpy(name->n_path, name->n_base, sizeof(name->n_path));
201 }
202
203 #define addtoname(N, C)                                 \
204 do {                                                    \
205     strlcat((N)->n_path, "/", sizeof((N)->n_path));     \
206     strlcat((N)->n_path, (C), sizeof((N)->n_path));     \
207 } while(0)
208
209
210 static void
211 namei_HandleToVolDir(namei_t * name, IHandle_t * ih)
212 {
213     lb64_string_t tmp;
214
215     namei_HandleToInodeDir(name, ih);
216     (void)int32_to_flipbase64(tmp, (int64_t) (ih->ih_vid & 0xff));
217     strlcpy(name->n_voldir1, tmp, sizeof(name->n_voldir1));
218     addtoname(name, name->n_voldir1);
219     (void)int32_to_flipbase64(tmp, (int64_t) ih->ih_vid);
220     strlcpy(name->n_voldir2, tmp, sizeof(name->n_voldir2));
221     addtoname(name, name->n_voldir2);
222 }
223
224 /* namei_HandleToName
225  *
226  * Constructs a file name for the fully qualified handle.
227  * Note that special files end up in /vicepX/InodeDir/Vxx/V*.data/special
228  */
229 void
230 namei_HandleToName(namei_t * name, IHandle_t * ih)
231 {
232     lb64_string_t str;
233     int vno = (int)(ih->ih_ino & NAMEI_VNODEMASK);
234
235     namei_HandleToVolDir(name, ih);
236
237     if (vno == NAMEI_VNODESPECIAL) {
238         strlcpy(name->n_dir1, NAMEI_SPECDIR, sizeof(name->n_dir1));
239         addtoname(name, name->n_dir1);
240         name->n_dir2[0] = '\0';
241     } else {
242         (void)int32_to_flipbase64(str, VNO_DIR1(vno));
243         strlcpy(name->n_dir1, str, sizeof(name->n_dir1));
244         addtoname(name, name->n_dir1);
245         (void)int32_to_flipbase64(str, VNO_DIR2(vno));
246         strlcpy(name->n_dir2, str, sizeof(name->n_dir2));
247         addtoname(name, name->n_dir2);
248     }
249     (void)int64_to_flipbase64(str, (int64_t) ih->ih_ino);
250     strlcpy(name->n_inode, str, sizeof(name->n_inode));
251     addtoname(name, name->n_inode);
252 }
253
254 /* The following is a warning to tell sys-admins to not muck about in this
255  * name space.
256  */
257 #define VICE_README "These files and directories are a part of the AFS \
258 namespace. Modifying them\nin any way will result in loss of AFS data,\n\
259 ownership and permissions included.\n"
260 int
261 namei_ViceREADME(char *partition)
262 {
263     char filename[32];
264     int fd;
265
266     /* Create the inode directory if we're starting for the first time */
267     (void)afs_snprintf(filename, sizeof filename, "%s/%s", partition,
268                        INODEDIR);
269     mkdir(filename, 0700);
270
271     (void)afs_snprintf(filename, sizeof filename, "%s/%s/README", partition,
272                        INODEDIR);
273     fd = afs_open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0444);
274     if (fd >= 0) {
275         (void)write(fd, VICE_README, strlen(VICE_README));
276         close(fd);
277     }
278     return (errno);
279 }
280
281
282 #define create_dir() \
283 do { \
284     if (mkdir(tmp, 0700)<0) { \
285         if (errno != EEXIST) \
286             return -1; \
287     } \
288     else { \
289         *created = 1; \
290     } \
291 } while (0)
292
293 #define create_nextdir(A) \
294 do { \
295          strcat(tmp, "/"); strcat(tmp, A); create_dir();  \
296 } while(0)
297
298 /* namei_CreateDataDirectories
299  *
300  * If creating the file failed because of ENOENT or ENOTDIR, try
301  * creating all the directories first.
302  */
303 static int
304 namei_CreateDataDirectories(namei_t * name, int *created)
305 {
306     char tmp[256];
307
308     *created = 0;
309
310     strlcpy(tmp, name->n_base, sizeof(tmp));
311     create_dir();
312
313     create_nextdir(name->n_voldir1);
314     create_nextdir(name->n_voldir2);
315     create_nextdir(name->n_dir1);
316     if (name->n_dir2[0]) {
317         create_nextdir(name->n_dir2);
318     }
319     return 0;
320 }
321
322 /* delTree(): Deletes an entire tree of directories (no files)
323  * Input:
324  *   root : Full path to the subtree. Should be big enough for PATH_MAX
325  *   tree : the subtree to be deleted is rooted here. Specifies only the
326  *          subtree beginning at tree (not the entire path). It should be
327  *          a pointer into the "root" buffer.
328  * Output:
329  *  errp : errno of the first error encountered during the directory cleanup.
330  *         *errp should have been initialized to 0.
331  *
332  * Return Values:
333  *  -1  : If errors were encountered during cleanup and error is set to
334  *        the first errno.
335  *   0  : Success.
336  *
337  * If there are errors, we try to work around them and delete as many
338  * directories as possible. We don't attempt to remove directories that still
339  * have non-dir entries in them.
340  */
341 static int
342 delTree(char *root, char *tree, int *errp)
343 {
344     char *cp;
345     DIR *ds;
346     struct dirent *dirp;
347     struct afs_stat st;
348
349     if (*tree) {
350         /* delete the children first */
351         cp = strchr(tree, '/');
352         if (cp) {
353             delTree(root, cp + 1, errp);
354             *cp = '\0';
355         } else
356             cp = tree + strlen(tree);   /* move cp to the end of string tree */
357
358         /* now delete all entries in this dir */
359         if ((ds = opendir(root)) != (DIR *) NULL) {
360             errno = 0;
361             while ((dirp = readdir(ds))) {
362                 /* ignore . and .. */
363                 if (!strcmp(dirp->d_name, ".") || !strcmp(dirp->d_name, ".."))
364                     continue;
365                 /* since root is big enough, we reuse the space to
366                  * concatenate the dirname to the current tree
367                  */
368                 strcat(root, "/");
369                 strcat(root, dirp->d_name);
370                 if (afs_stat(root, &st) == 0 && S_ISDIR(st.st_mode)) {
371                     /* delete this subtree */
372                     delTree(root, cp + 1, errp);
373                 } else
374                     *errp = *errp ? *errp : errno;
375
376                 /* recover path to our cur tree by truncating it to
377                  * its original len
378                  */
379                 *cp = 0;
380             }
381             /* if (!errno) -- closedir not implicit if we got an error */
382             closedir(ds);
383         }
384
385         /* finally axe the current dir */
386         if (rmdir(root))
387             *errp = *errp ? *errp : errno;
388
389 #ifndef AFS_PTHREAD_ENV         /* let rx get some work done */
390         IOMGR_Poll();
391 #endif /* !AFS_PTHREAD_ENV */
392
393     }
394
395     /* if valid tree */
396     /* if we encountered errors during cleanup, we return a -1 */
397     if (*errp)
398         return -1;
399
400     return 0;
401
402 }
403
404 /* namei_RemoveDataDirectories
405  * Return Values:
406  * Returns 0 on success.
407  * Returns -1 on error. Typically, callers ignore this error bcause we
408  * can continue running if the removes fail. The salvage process will
409  * finish tidying up for us. We only use the n_base and n_voldir1 entries
410  * and only do rmdir's.
411  */
412
413 static int
414 namei_RemoveDataDirectories(namei_t * name)
415 {
416     char pbuf[MAXPATHLEN], *path = pbuf;
417     int prefixlen = strlen(name->n_base), err = 0;
418
419     strlcpy(path, name->n_path, sizeof(pbuf));
420
421     /* move past the prefix */
422     path = path + prefixlen + 1;        /* skip over the trailing / */
423
424     /* now delete all dirs upto path */
425     return delTree(pbuf, path, &err);
426
427 }
428
429 /* Create the file in the name space.
430  *
431  * Parameters stored as follows:
432  * Regular files:
433  * p1 - volid - implied in containing directory.
434  * p2 - vnode - name is <vno:31-23>/<vno:22-15>/<vno:15-0><uniq:31-5><tag:2-0>
435  * p3 - uniq -- bits 4-0 are in mode bits 4-0
436  * p4 - dv ---- dv:15-0 in uid, dv:29-16 in gid, dv:31-30 in mode:6-5
437  * Special files:
438  * p1 - volid - creation time - dwHighDateTime
439  * p2 - vnode - -1 means special, file goes in "S" subdirectory.
440  * p3 - type -- name is <type>.<tag> where tag is a file name unqiquifier.
441  * p4 - parid - parent volume id - implied in containing directory.
442  *
443  * Return value is the inode number or (Inode)-1 if error.
444  * We "know" there is only one link table, so return EEXIST if there already
445  * is a link table. It's up to the calling code to test errno and increment
446  * the link count.
447  */
448
449 /* namei_MakeSpecIno
450  *
451  * This function is called by VCreateVolume to hide the implementation
452  * details of the inode numbers. This only allows for 7 volume special
453  * types, but if we get that far, this could should be dead by then.
454  */
455 Inode
456 namei_MakeSpecIno(int volid, int type)
457 {
458     Inode ino;
459     ino = NAMEI_INODESPECIAL;
460     type &= NAMEI_TAGMASK;
461     ino |= ((Inode) type) << NAMEI_TAGSHIFT;
462     ino |= ((Inode) volid) << NAMEI_UNIQSHIFT;
463     return ino;
464 }
465
466 /* SetOGM - set owner group and mode bits from parm and tag
467  *
468  * owner - low 15 bits of parm.
469  * group - next 15 bits of parm.
470  * mode - 2 bits of parm, then lowest = 3 bits of tag.
471  */
472 static int
473 SetOGM(int fd, int parm, int tag)
474 {
475     int owner, group, mode;
476
477     owner = parm & 0x7fff;
478     group = (parm >> 15) & 0x7fff;
479     if (fchown(fd, owner, group) < 0)
480         return -1;
481
482     mode = (parm >> 27) & 0x18;
483     mode |= tag & 0x7;
484     if (fchmod(fd, mode) < 0)
485         return -1;
486
487     return 0;
488
489 }
490
491 /* GetOGM - get parm and tag from owner, group and mode bits. */
492 static void
493 GetOGMFromStat(struct afs_stat *status, int *parm, int *tag)
494 {
495     *parm = status->st_uid | (status->st_gid << 15);
496     *parm |= (status->st_mode & 0x18) << 27;
497     *tag = status->st_mode & 0x7;
498 }
499
500 static int
501 GetOGM(int fd, int *parm, int *tag)
502 {
503     struct afs_stat status;
504     if (afs_fstat(fd, &status) < 0)
505         return -1;
506
507     GetOGMFromStat(&status, parm, tag);
508     return 0;
509 }
510
511 int big_vno = 0;                /* Just in case we ever do 64 bit vnodes. */
512
513 /* Derive the name and create it O_EXCL. If that fails we have an error.
514  * Get the tag from a free column in the link table.
515  */
516 Inode
517 namei_icreate(IHandle_t * lh, char *part, int p1, int p2, int p3, int p4)
518 {
519     namei_t name;
520     int fd = -1;
521     int code = 0;
522     int created_dir = 0;
523     IHandle_t tmp;
524     FdHandle_t *fdP;
525     FdHandle_t tfd;
526     int tag;
527     int ogm_parm;
528
529
530     memset((void *)&tmp, 0, sizeof(IHandle_t));
531
532
533     tmp.ih_dev = volutil_GetPartitionID(part);
534     if (tmp.ih_dev == -1) {
535         errno = EINVAL;
536         return -1;
537     }
538
539     if (p2 == -1) {
540         /* Parameters for special file:
541          * p1 - volume id - goes into owner/group/mode
542          * p2 - vnode == -1
543          * p3 - type
544          * p4 - parent volume id
545          */
546         ogm_parm = p1;
547         tag = p3;
548
549         tmp.ih_vid = p4;        /* Use parent volume id, where this file will be. */
550         tmp.ih_ino = namei_MakeSpecIno(p1, p3);
551     } else {
552         int vno = p2 & NAMEI_VNODEMASK;
553         /* Parameters for regular file:
554          * p1 - volume id
555          * p2 - vnode
556          * p3 - uniq
557          * p4 - dv
558          */
559
560         if (vno != p2) {
561             big_vno++;
562             errno = EINVAL;
563             return -1;
564         }
565         /* If GetFreeTag succeeds, it atomically sets link count to 1. */
566         tag = GetFreeTag(lh, p2);
567         if (tag < 0)
568             goto bad;
569
570         /* name is <uniq(p3)><tag><vno(p2)> */
571         tmp.ih_vid = p1;
572         tmp.ih_ino = (Inode) p2;
573         tmp.ih_ino |= ((Inode) tag) << NAMEI_TAGSHIFT;
574         tmp.ih_ino |= ((Inode) p3) << NAMEI_UNIQSHIFT;
575
576         ogm_parm = p4;
577     }
578
579     namei_HandleToName(&name, &tmp);
580     fd = afs_open(name.n_path, O_CREAT | O_EXCL | O_TRUNC | O_RDWR, 0);
581     if (fd < 0) {
582         if (errno == ENOTDIR || errno == ENOENT) {
583             if (namei_CreateDataDirectories(&name, &created_dir) < 0)
584                 goto bad;
585             fd = afs_open(name.n_path, O_CREAT | O_EXCL | O_TRUNC | O_RDWR,
586                           0);
587             if (fd < 0)
588                 goto bad;
589         } else {
590             goto bad;
591         }
592     }
593     if (SetOGM(fd, ogm_parm, tag) < 0) {
594         close(fd);
595         fd = -1;
596         goto bad;
597     }
598
599     if (p2 == -1 && p3 == VI_LINKTABLE) {
600         /* hack at tmp to setup for set link count call. */
601         memset((void *)&tfd, 0, sizeof(FdHandle_t));    /* minimalistic still, but a little cleaner */
602         tfd.fd_ih = &tmp;
603         tfd.fd_fd = fd;
604         code = namei_SetLinkCount(&tfd, (Inode) 0, 1, 0);
605     }
606
607   bad:
608     if (fd >= 0)
609         close(fd);
610
611
612     if (code || (fd < 0)) {
613         if (p2 != -1) {
614             fdP = IH_OPEN(lh);
615             if (fdP) {
616                 namei_SetLinkCount(fdP, tmp.ih_ino, 0, 0);
617                 FDH_CLOSE(fdP);
618             }
619         }
620     }
621     return (code || (fd < 0)) ? (Inode) - 1 : tmp.ih_ino;
622 }
623
624
625 /* namei_iopen */
626 int
627 namei_iopen(IHandle_t * h)
628 {
629     int fd;
630     namei_t name;
631
632     /* Convert handle to file name. */
633     namei_HandleToName(&name, h);
634     fd = afs_open(name.n_path, O_RDWR, 0666);
635     return fd;
636 }
637
638 /* Need to detect vol special file and just unlink. In those cases, the
639  * handle passed in _is_ for the inode. We only check p1 for the special
640  * files.
641  */
642 int
643 namei_dec(IHandle_t * ih, Inode ino, int p1)
644 {
645     int count = 0;
646     namei_t name;
647     int code = 0;
648     FdHandle_t *fdP;
649
650     if ((ino & NAMEI_INODESPECIAL) == NAMEI_INODESPECIAL) {
651         IHandle_t *tmp;
652         int inode_p1, tag;
653         int type = (int)((ino >> NAMEI_TAGSHIFT) & NAMEI_TAGMASK);
654
655         /* Verify this is the right file. */
656         IH_INIT(tmp, ih->ih_dev, ih->ih_vid, ino);
657
658         fdP = IH_OPEN(tmp);
659         if (fdP == NULL) {
660             IH_RELEASE(tmp);
661             errno = EINVAL;
662             return -1;
663         }
664
665         if ((GetOGM(fdP->fd_fd, &inode_p1, &tag) < 0) || (inode_p1 != p1)) {
666             FDH_REALLYCLOSE(fdP);
667             IH_RELEASE(tmp);
668             errno = EINVAL;
669             return -1;
670         }
671
672         /* If it's the link table itself, decrement the link count. */
673         if (type == VI_LINKTABLE) {
674             if ((count = namei_GetLinkCount(fdP, (Inode) 0, 1)) < 0) {
675                 FDH_REALLYCLOSE(fdP);
676                 IH_RELEASE(tmp);
677                 return -1;
678             }
679
680             count--;
681             if (namei_SetLinkCount(fdP, (Inode) 0, count < 0 ? 0 : count, 1) <
682                 0) {
683                 FDH_REALLYCLOSE(fdP);
684                 IH_RELEASE(tmp);
685                 return -1;
686             }
687
688             if (count > 0) {
689                 FDH_REALLYCLOSE(fdP);
690                 IH_RELEASE(tmp);
691                 return 0;
692             }
693         }
694
695         namei_HandleToName(&name, tmp);
696         if ((code = unlink(name.n_path)) == 0) {
697             if (type == VI_LINKTABLE) {
698                 /* Try to remove directory. If it fails, that's ok.
699                  * Salvage will clean up.
700                  */
701                 (void)namei_RemoveDataDirectories(&name);
702             }
703         }
704         FDH_REALLYCLOSE(fdP);
705         IH_RELEASE(tmp);
706     } else {
707         /* Get a file descriptor handle for this Inode */
708         fdP = IH_OPEN(ih);
709         if (fdP == NULL) {
710             return -1;
711         }
712
713         if ((count = namei_GetLinkCount(fdP, ino, 1)) < 0) {
714             FDH_REALLYCLOSE(fdP);
715             return -1;
716         }
717
718         count--;
719         if (count >= 0) {
720             if (namei_SetLinkCount(fdP, ino, count, 1) < 0) {
721                 FDH_REALLYCLOSE(fdP);
722                 return -1;
723             }
724         } else {
725             IHandle_t *th;
726             IH_INIT(th, ih->ih_dev, ih->ih_vid, ino);
727             Log("Warning: Lost ref on ihandle dev %d vid %d ino %" AFS_INT64_FMT "\n",
728                 th->ih_dev, th->ih_vid, (afs_int64)th->ih_ino);
729             IH_RELEASE(th);
730
731             /* If we're less than 0, someone presumably unlinked;
732                don't bother setting count to 0, but we need to drop a lock */
733             if (namei_SetLinkCount(fdP, ino, 0, 1) < 0) {
734                 FDH_REALLYCLOSE(fdP);
735                 return -1;
736             }
737         }
738         if (count == 0) {
739             IHandle_t *th;
740             IH_INIT(th, ih->ih_dev, ih->ih_vid, ino);
741
742             namei_HandleToName(&name, th);
743             IH_RELEASE(th);
744             code = unlink(name.n_path);
745         }
746         FDH_CLOSE(fdP);
747     }
748
749     return code;
750 }
751
752 int
753 namei_inc(IHandle_t * h, Inode ino, int p1)
754 {
755     int count;
756     int code = 0;
757     FdHandle_t *fdP;
758
759     if ((ino & NAMEI_INODESPECIAL) == NAMEI_INODESPECIAL) {
760         int type = (int)((ino >> NAMEI_TAGSHIFT) & NAMEI_TAGMASK);
761         if (type != VI_LINKTABLE)
762             return 0;
763         ino = (Inode) 0;
764     }
765
766     /* Get a file descriptor handle for this Inode */
767     fdP = IH_OPEN(h);
768     if (fdP == NULL) {
769         return -1;
770     }
771
772     if ((count = namei_GetLinkCount(fdP, ino, 1)) < 0)
773         code = -1;
774     else {
775         count++;
776         if (count > 7) {
777             errno = EINVAL;
778             code = -1;
779             count = 7;
780         }
781         if (namei_SetLinkCount(fdP, ino, count, 1) < 0)
782             code = -1;
783     }
784     if (code) {
785         FDH_REALLYCLOSE(fdP);
786     } else {
787         FDH_CLOSE(fdP);
788     }
789     return code;
790 }
791
792 int
793 namei_replace_file_by_hardlink(IHandle_t *hLink, IHandle_t *hTarget)
794 {
795     afs_int32 code;
796     namei_t nameLink;
797     namei_t nameTarget;
798
799     /* Convert handle to file name. */
800     namei_HandleToName(&nameLink, hLink);
801     namei_HandleToName(&nameTarget, hTarget);
802
803     unlink(nameLink.n_path);
804     code = link(nameTarget.n_path, nameLink.n_path);
805     return code;
806 }
807
808 int
809 namei_copy_on_write(IHandle_t *h)
810 {
811     afs_int32 fd, code = 0;
812     namei_t name;
813     FdHandle_t *fdP;
814     struct afs_stat tstat;
815     afs_foff_t offset;
816
817     namei_HandleToName(&name, h);
818     if (afs_stat(name.n_path, &tstat) < 0)
819         return EIO;
820     if (tstat.st_nlink > 1) {                   /* do a copy on write */
821         char path[259];
822         char *buf;
823         afs_size_t size;
824         ssize_t tlen;
825
826         fdP = IH_OPEN(h);
827         if (!fdP)
828             return EIO;
829         afs_snprintf(path, sizeof(path), "%s-tmp", name.n_path);
830         fd = afs_open(path, O_CREAT | O_EXCL | O_TRUNC | O_RDWR, 0);
831         if (fd < 0) {
832             FDH_CLOSE(fdP);
833             return EIO;
834         }
835         buf = malloc(8192);
836         if (!buf) {
837             close(fd);
838             unlink(path);
839             FDH_CLOSE(fdP);
840             return ENOMEM;
841         }
842         size = tstat.st_size;
843         offset = 0;
844         while (size) {
845             tlen = size > 8192 ? 8192 : size;
846             if (FDH_PREAD(fdP, buf, tlen, offset) != tlen)
847                 break;
848             if (write(fd, buf, tlen) != tlen)
849                 break;
850             size -= tlen;
851             offset += tlen;
852         }
853         close(fd);
854         FDH_REALLYCLOSE(fdP);
855         free(buf);
856         if (size)
857             code = EIO;
858         else {
859             unlink(name.n_path);
860             code = rename(path, name.n_path);
861         }
862     }
863     return code;
864 }
865
866 /************************************************************************
867  * File Name Structure
868  ************************************************************************
869  *
870  * Each AFS file needs a unique name and it needs to be findable with
871  * minimal lookup time. Note that the constraint on the number of files and
872  * directories in a volume is the size of the vnode index files and the
873  * max file size AFS supports (for internal files) of 2^31. Since a record
874  * in the small vnode index file is 64 bytes long, we can have at most
875  * (2^31)/64 or 33554432 files. A record in the large index file is
876  * 256 bytes long, giving a maximum of (2^31)/256 = 8388608 directories.
877  * Another layout parameter is that there is roughly a 16 to 1 ratio between
878  * the number of files and the number of directories.
879  *
880  * Using this information we can see that a layout of 256 directories, each
881  * with 512 subdirectories and each of those having 512 files gives us
882  * 256*512*512 = 67108864 AFS files and directories.
883  *
884  * The volume, vnode, uniquifier and data version, as well as the tag
885  * are required, either for finding the file or for salvaging. It's best to
886  * restrict the name to something that can be mapped into 64 bits so the
887  * "Inode" is easily comparable (using "==") to other "Inodes". The tag
888  * is used to distinguish between different versions of the same file
889  * which are currently in the RW and clones of a volume. See "Link Table
890  * Organization" below for more information on the tag. The tag is
891  * required in the name of the file to ensure a unique name.
892  *
893  * We can store data in the uid, gid and mode bits of the files, provided
894  * the directories have root only access. This gives us 15 bits for each
895  * of uid and gid (GNU chown considers 65535 to mean "don't change").
896  * There are 9 available mode bits. Adn we need to store a total of
897  * 32 (volume id) + 26 (vnode) + 32 (uniquifier) + 32 (data-version) + 3 (tag)
898  * or 131 bits somewhere.
899  *
900  * The format of a file name for a regular file is:
901  * /vicepX/AFSIDat/V1/V2/AA/BB/<tag><uniq><vno>
902  * V1 - low 8 bits of RW volume id
903  * V2 - all bits of RW volume id
904  * AA - high 8 bits of vnode number.
905  * BB - next 9 bits of vnode number.
906  * <tag><uniq><vno> - file name
907  *
908  * Volume special files are stored in a separate directory:
909  * /vicepX/AFSIDat/V1/V2/special/<tag><uniq><vno>
910  *
911  *
912  * The vnode is hashed into the directory using the high bits of the
913  * vnode number. This is so that consecutively created vnodes are in
914  * roughly the same area on the disk. This will at least be optimal if
915  * the user is creating many files in the same AFS directory. The name
916  * should be formed so that the leading characters are different as quickly
917  * as possible, leading to faster discards of incorrect matches in the
918  * lookup code.
919  *
920  */
921
922
923 /************************************************************************
924  *  Link Table Organization
925  ************************************************************************
926  *
927  * The link table volume special file is used to hold the link counts that
928  * are held in the inodes in inode based AFS vice filesystems. For user
929  * space access, the link counts are being kept in a separate
930  * volume special file. The file begins with the usual version stamp
931  * information and is then followed by one row per vnode number. vnode 0
932  * is used to hold the link count of the link table itself. That is because
933  * the same link table is shared among all the volumes of the volume group
934  * and is deleted only when the last volume of a volume group is deleted.
935  *
936  * Within each row, the columns are 3 bits wide. They can each hold a 0 based
937  * link count from 0 through 7. Each colume represents a unique instance of
938  * that vnode. Say we have a file shared between the RW and a RO and a
939  * different version of the file (or a different uniquifer) for the BU volume.
940  * Then one column would be holding the link count of 2 for the RW and RO
941  * and a different column would hold the link count of 1 for the BU volume.
942  * Note that we allow only 5 volumes per file, giving 15 bits used in the
943  * short.
944  */
945 #define LINKTABLE_WIDTH 2
946 #define LINKTABLE_SHIFT 1       /* log 2 = 1 */
947
948 static void
949 namei_GetLCOffsetAndIndexFromIno(Inode ino, afs_foff_t * offset, int *index)
950 {
951     int toff = (int)(ino & NAMEI_VNODEMASK);
952     int tindex = (int)((ino >> NAMEI_TAGSHIFT) & NAMEI_TAGMASK);
953
954     *offset = (afs_foff_t) ((toff << LINKTABLE_SHIFT) + 8);     /* * 2 + sizeof stamp */
955     *index = (tindex << 1) + tindex;
956 }
957
958
959 /* namei_GetLinkCount
960  * If lockit is set, lock the file and leave it locked upon a successful
961  * return.
962  */
963 static int
964 namei_GetLinkCount2(FdHandle_t * h, Inode ino, int lockit, int fixup, int nowrite)
965 {
966     unsigned short row = 0;
967     afs_foff_t offset;
968     ssize_t rc;
969     int index;
970
971     /* there's no linktable yet. the salvager will create one later */
972     if (h->fd_fd == -1 && fixup)
973        return 1;
974     namei_GetLCOffsetAndIndexFromIno(ino, &offset, &index);
975
976     if (lockit) {
977         if (flock(h->fd_fd, LOCK_EX) < 0)
978             return -1;
979     }
980
981     rc = FDH_PREAD(h, (char*)&row, sizeof(row), offset);
982     if ((rc == 0 || !((row >> index) & NAMEI_TAGMASK)) && fixup && nowrite)
983         return 1;
984     if (rc == 0 && fixup) {
985         struct stat st;
986         if (fstat(h->fd_fd, &st) || st.st_size >= offset+sizeof(row))
987            goto bad_getLinkByte;
988         FDH_TRUNC(h, offset+sizeof(row));
989         row = 1 << index;
990         rc = FDH_PWRITE(h, (char *)&row, sizeof(row), offset);
991     }
992     if (rc != sizeof(row)) {
993         goto bad_getLinkByte;
994     }
995
996     if (fixup && !((row >> index) & NAMEI_TAGMASK)) {
997         row |= 1<<index;
998         rc = FDH_PWRITE(h, (char *)&row, sizeof(row), offset);
999         if (rc != sizeof(row))
1000             goto bad_getLinkByte;
1001     }
1002
1003     return (int)((row >> index) & NAMEI_TAGMASK);
1004
1005   bad_getLinkByte:
1006     if (lockit)
1007         flock(h->fd_fd, LOCK_UN);
1008     return -1;
1009 }
1010
1011 int
1012 namei_GetLinkCount(FdHandle_t * h, Inode ino, int lockit)
1013 {
1014     return namei_GetLinkCount2(h, ino, lockit, 0, 1);
1015 }
1016
1017 /* Return a free column index for this vnode. */
1018 static int
1019 GetFreeTag(IHandle_t * ih, int vno)
1020 {
1021     FdHandle_t *fdP;
1022     afs_foff_t offset;
1023     int col;
1024     int coldata;
1025     short row;
1026     ssize_t nBytes;
1027
1028
1029     fdP = IH_OPEN(ih);
1030     if (fdP == NULL)
1031         return -1;
1032
1033     /* Only one manipulates at a time. */
1034     if (flock(fdP->fd_fd, LOCK_EX) < 0) {
1035         FDH_REALLYCLOSE(fdP);
1036         return -1;
1037     }
1038
1039     offset = (vno << LINKTABLE_SHIFT) + 8;      /* * 2 + sizeof stamp */
1040
1041     nBytes = FDH_PREAD(fdP, (char *)&row, sizeof(row), offset);
1042     if (nBytes != sizeof(row)) {
1043         if (nBytes != 0)
1044             goto badGetFreeTag;
1045         row = 0;
1046     }
1047
1048     /* Now find a free column in this row and claim it. */
1049     for (col = 0; col < NAMEI_MAXVOLS; col++) {
1050         coldata = 7 << (col * 3);
1051         if ((row & coldata) == 0)
1052             break;
1053     }
1054     if (col >= NAMEI_MAXVOLS) {
1055         errno = ENOSPC;
1056         goto badGetFreeTag;
1057     }
1058
1059     coldata = 1 << (col * 3);
1060     row |= coldata;
1061
1062     if (FDH_PWRITE(fdP, (char *)&row, sizeof(row), offset) != sizeof(row)) {
1063         goto badGetFreeTag;
1064     }
1065     FDH_SYNC(fdP);
1066     flock(fdP->fd_fd, LOCK_UN);
1067     FDH_REALLYCLOSE(fdP);
1068     return col;;
1069
1070   badGetFreeTag:
1071     flock(fdP->fd_fd, LOCK_UN);
1072     FDH_REALLYCLOSE(fdP);
1073     return -1;
1074 }
1075
1076
1077
1078 /* namei_SetLinkCount
1079  * If locked is set, assume file is locked. Otherwise, lock file before
1080  * proceeding to modify it.
1081  */
1082 int
1083 namei_SetLinkCount(FdHandle_t * fdP, Inode ino, int count, int locked)
1084 {
1085     afs_foff_t offset;
1086     int index;
1087     unsigned short row;
1088     int junk;
1089     ssize_t nBytes = -1;
1090
1091     namei_GetLCOffsetAndIndexFromIno(ino, &offset, &index);
1092
1093     if (!locked) {
1094         if (flock(fdP->fd_fd, LOCK_EX) < 0) {
1095             return -1;
1096         }
1097     }
1098
1099     nBytes = FDH_PREAD(fdP, (char *)&row, sizeof(row), offset);
1100     if (nBytes != sizeof(row)) {
1101         if (nBytes != 0) {
1102             errno = EBADF;
1103             goto bad_SetLinkCount;
1104         }
1105         row = 0;
1106     }
1107
1108     junk = 7 << index;
1109     count <<= index;
1110     row &= (unsigned short)~junk;
1111     row |= (unsigned short)count;
1112
1113     if (FDH_PWRITE(fdP, (char *)&row, sizeof(short), offset) != sizeof(short)) {
1114         errno = EBADF;
1115         goto bad_SetLinkCount;
1116     }
1117     FDH_SYNC(fdP);
1118
1119     nBytes = 0;
1120
1121
1122   bad_SetLinkCount:
1123     flock(fdP->fd_fd, LOCK_UN);
1124
1125     return nBytes;
1126 }
1127
1128
1129 /* ListViceInodes - write inode data to a results file. */
1130 static int DecodeInode(char *dpath, char *name, struct ViceInodeInfo *info,
1131                        unsigned int volid);
1132 static int DecodeVolumeName(char *name, unsigned int *vid);
1133 static int namei_ListAFSSubDirs(IHandle_t * dirIH,
1134                                 int (*write_fun) (FILE *,
1135                                                   struct ViceInodeInfo *,
1136                                                   char *, char *), FILE * fp,
1137                                 int (*judgeFun) (struct ViceInodeInfo *,
1138                                                  afs_uint32 vid, void *),
1139                                 afs_uint32 singleVolumeNumber, void *rock);
1140
1141
1142 /* WriteInodeInfo
1143  *
1144  * Write the inode data to the results file.
1145  *
1146  * Returns -2 on error, 0 on success.
1147  *
1148  * This is written as a callback simply so that other listing routines
1149  * can use the same inode reading code.
1150  */
1151 static int
1152 WriteInodeInfo(FILE * fp, struct ViceInodeInfo *info, char *dir, char *name)
1153 {
1154     int n;
1155     n = fwrite(info, sizeof(*info), 1, fp);
1156     return (n == 1) ? 0 : -2;
1157 }
1158
1159
1160 int mode_errors;                /* Number of errors found in mode bits on directories. */
1161 void
1162 VerifyDirPerms(char *path)
1163 {
1164     struct afs_stat status;
1165
1166     if (afs_stat(path, &status) < 0) {
1167         Log("Unable to stat %s. Please manually verify mode bits for this"
1168             " directory\n", path);
1169     } else {
1170         if (((status.st_mode & 0777) != 0700) || (status.st_uid != 0))
1171             mode_errors++;
1172     }
1173 }
1174
1175 /* ListViceInodes
1176  * Fill the results file with the requested inode information.
1177  *
1178  * Return values:
1179  *  0 - success
1180  * -1 - complete failure, salvage should terminate.
1181  * -2 - not enough space on partition, salvager has error message for this.
1182  *
1183  * This code optimizes single volume salvages by just looking at that one
1184  * volume's directory.
1185  *
1186  * If the resultFile is NULL, then don't call the write routine.
1187  */
1188 int
1189 ListViceInodes(char *devname, char *mountedOn, FILE *inodeFile,
1190                int (*judgeInode) (struct ViceInodeInfo * info, afs_uint32 vid, void *rock),
1191                afs_uint32 singleVolumeNumber, int *forcep, int forceR, char *wpath,
1192                void *rock)
1193 {
1194     int ninodes;
1195     struct afs_stat status;
1196
1197     *forcep = 0; /* no need to salvage until further notice */
1198
1199     /* Verify protections on directories. */
1200     mode_errors = 0;
1201     VerifyDirPerms(mountedOn);
1202
1203     ninodes =
1204         namei_ListAFSFiles(mountedOn, WriteInodeInfo, inodeFile, judgeInode,
1205                            singleVolumeNumber, rock);
1206
1207     if (!inodeFile)
1208         return ninodes;
1209
1210     if (ninodes < 0) {
1211         return ninodes;
1212     }
1213
1214     if (fflush(inodeFile) == EOF) {
1215         Log("Unable to successfully flush inode file for %s\n", mountedOn);
1216         return -2;
1217     }
1218     if (fsync(fileno(inodeFile)) == -1) {
1219         Log("Unable to successfully fsync inode file for %s\n", mountedOn);
1220         return -2;
1221     }
1222
1223     /*
1224      * Paranoia:  check that the file is really the right size
1225      */
1226     if (afs_fstat(fileno(inodeFile), &status) == -1) {
1227         Log("Unable to successfully stat inode file for %s\n", mountedOn);
1228         return -2;
1229     }
1230     if (status.st_size != ninodes * sizeof(struct ViceInodeInfo)) {
1231         Log("Wrong size (%d instead of %lu) in inode file for %s\n",
1232             (int) status.st_size,
1233             (long unsigned int) ninodes * sizeof(struct ViceInodeInfo),
1234             mountedOn);
1235         return -2;
1236     }
1237     return 0;
1238 }
1239
1240
1241 /* namei_ListAFSFiles
1242  *
1243  * Collect all the matching AFS files on the drive.
1244  * If singleVolumeNumber is non-zero, just return files for that volume.
1245  *
1246  * Returns <0 on error, else number of files found to match.
1247  */
1248 int
1249 namei_ListAFSFiles(char *dev,
1250                    int (*writeFun) (FILE *, struct ViceInodeInfo *, char *,
1251                                     char *), FILE * fp,
1252                    int (*judgeFun) (struct ViceInodeInfo *, afs_uint32, void *),
1253                    afs_uint32 singleVolumeNumber, void *rock)
1254 {
1255     IHandle_t ih;
1256     namei_t name;
1257     int ninodes = 0;
1258     DIR *dirp1, *dirp2;
1259     struct dirent *dp1, *dp2;
1260     char path2[512];
1261 #ifdef DELETE_ZLC
1262     static void FreeZLCList(void);
1263 #endif
1264
1265     memset((void *)&ih, 0, sizeof(IHandle_t));
1266     ih.ih_dev = volutil_GetPartitionID(dev);
1267
1268     if (singleVolumeNumber) {
1269         ih.ih_vid = singleVolumeNumber;
1270         namei_HandleToVolDir(&name, &ih);
1271         ninodes =
1272             namei_ListAFSSubDirs(&ih, writeFun, fp, judgeFun,
1273                                  singleVolumeNumber, rock);
1274         if (ninodes < 0)
1275             return ninodes;
1276     } else {
1277         /* Find all volume data directories and descend through them. */
1278         namei_HandleToInodeDir(&name, &ih);
1279         ninodes = 0;
1280         dirp1 = opendir(name.n_path);
1281         if (!dirp1)
1282             return 0;
1283         while ((dp1 = readdir(dirp1))) {
1284             if (*dp1->d_name == '.')
1285                 continue;
1286             afs_snprintf(path2, sizeof(path2), "%s/%s", name.n_path,
1287                          dp1->d_name);
1288             dirp2 = opendir(path2);
1289             if (dirp2) {
1290                 while ((dp2 = readdir(dirp2))) {
1291                     if (*dp2->d_name == '.')
1292                         continue;
1293                     if (!DecodeVolumeName(dp2->d_name, &ih.ih_vid)) {
1294                         ninodes +=
1295                             namei_ListAFSSubDirs(&ih, writeFun, fp, judgeFun,
1296                                                  0, rock);
1297                     }
1298                 }
1299                 closedir(dirp2);
1300             }
1301         }
1302         closedir(dirp1);
1303     }
1304 #ifdef DELETE_ZLC
1305     FreeZLCList();
1306 #endif
1307     return ninodes;
1308 }
1309
1310
1311
1312 /* namei_ListAFSSubDirs
1313  *
1314  *
1315  * Return values:
1316  * < 0 - an error
1317  * > = 0 - number of AFS files found.
1318  */
1319 static int
1320 namei_ListAFSSubDirs(IHandle_t * dirIH,
1321                      int (*writeFun) (FILE *, struct ViceInodeInfo *, char *,
1322                                       char *), FILE * fp,
1323                      int (*judgeFun) (struct ViceInodeInfo *, afs_uint32, void *),
1324                      afs_uint32 singleVolumeNumber, void *rock)
1325 {
1326     IHandle_t myIH = *dirIH;
1327     namei_t name;
1328     char path1[512], path2[512], path3[512];
1329     DIR *dirp1, *dirp2, *dirp3;
1330     struct dirent *dp1, *dp2, *dp3;
1331     struct ViceInodeInfo info;
1332     FdHandle_t linkHandle;
1333     int ninodes = 0;
1334 #ifdef DELETE_ZLC
1335     int i;
1336     static void AddToZLCDeleteList(char dir, char *name);
1337     static void DeleteZLCFiles(char *path);
1338 #endif
1339
1340     namei_HandleToVolDir(&name, &myIH);
1341     strlcpy(path1, name.n_path, sizeof(path1));
1342
1343     /* Do the directory containing the special files first to pick up link
1344      * counts.
1345      */
1346     (void)strcat(path1, "/");
1347     (void)strcat(path1, NAMEI_SPECDIR);
1348
1349     linkHandle.fd_fd = -1;
1350     dirp1 = opendir(path1);
1351     if (dirp1) {
1352         while ((dp1 = readdir(dirp1))) {
1353             if (*dp1->d_name == '.')
1354                 continue;
1355             if (DecodeInode(path1, dp1->d_name, &info, myIH.ih_vid) < 0)
1356                 continue;
1357             if (info.u.param[2] != VI_LINKTABLE) {
1358                 info.linkCount = 1;
1359             } else {
1360                 /* Open this handle */
1361                 (void)afs_snprintf(path2, sizeof path2, "%s/%s", path1,
1362                                    dp1->d_name);
1363                 linkHandle.fd_fd = afs_open(path2, Testing ? O_RDONLY : O_RDWR, 0666);
1364                 info.linkCount =
1365                     namei_GetLinkCount2(&linkHandle, (Inode) 0, 1, 1, Testing);
1366             }
1367             if (judgeFun && !(*judgeFun) (&info, singleVolumeNumber, rock))
1368                 continue;
1369
1370             if ((*writeFun) (fp, &info, path1, dp1->d_name) < 0) {
1371                 if (linkHandle.fd_fd >= 0)
1372                     close(linkHandle.fd_fd);
1373                 closedir(dirp1);
1374                 return -1;
1375             }
1376             ninodes++;
1377         }
1378         closedir(dirp1);
1379     }
1380
1381     /* Now run through all the other subdirs */
1382     namei_HandleToVolDir(&name, &myIH);
1383     strlcpy(path1, name.n_path, sizeof(path1));
1384
1385     dirp1 = opendir(path1);
1386     if (dirp1) {
1387         while ((dp1 = readdir(dirp1))) {
1388             if (*dp1->d_name == '.')
1389                 continue;
1390             if (!strcmp(dp1->d_name, NAMEI_SPECDIR))
1391                 continue;
1392
1393             /* Now we've got a next level subdir. */
1394             afs_snprintf(path2, sizeof(path2), "%s/%s", path1, dp1->d_name);
1395             dirp2 = opendir(path2);
1396             if (dirp2) {
1397                 while ((dp2 = readdir(dirp2))) {
1398                     if (*dp2->d_name == '.')
1399                         continue;
1400
1401                     /* Now we've got to the actual data */
1402                     afs_snprintf(path3, sizeof(path3), "%s/%s", path2,
1403                                  dp2->d_name);
1404                     dirp3 = opendir(path3);
1405                     if (dirp3) {
1406                         while ((dp3 = readdir(dirp3))) {
1407                             if (*dp3->d_name == '.')
1408                                 continue;
1409                             if (DecodeInode
1410                                 (path3, dp3->d_name, &info, myIH.ih_vid) < 0)
1411                                 continue;
1412                             info.linkCount =
1413                                 namei_GetLinkCount2(&linkHandle,
1414                                                    info.inodeNumber, 1, 1, Testing);
1415                             if (info.linkCount == 0) {
1416 #ifdef DELETE_ZLC
1417                                 Log("Found 0 link count file %s/%s, deleting it.\n", path3, dp3->d_name);
1418                                 AddToZLCDeleteList((char)i, dp3->d_name);
1419 #else
1420                                 Log("Found 0 link count file %s/%s.\n", path3,
1421                                     dp3->d_name);
1422 #endif
1423                                 continue;
1424                             }
1425                             if (judgeFun
1426                                 && !(*judgeFun) (&info, singleVolumeNumber, rock))
1427                                 continue;
1428
1429                             if ((*writeFun) (fp, &info, path3, dp3->d_name) <
1430                                 0) {
1431                                 close(linkHandle.fd_fd);
1432                                 closedir(dirp3);
1433                                 closedir(dirp2);
1434                                 closedir(dirp1);
1435                                 return -1;
1436                             }
1437                             ninodes++;
1438                         }
1439                         closedir(dirp3);
1440                     }
1441                 }
1442                 closedir(dirp2);
1443             }
1444         }
1445         closedir(dirp1);
1446     }
1447
1448     if (linkHandle.fd_fd >= 0)
1449         close(linkHandle.fd_fd);
1450     if (!ninodes) {
1451         /* Then why does this directory exist? Blow it away. */
1452         namei_HandleToVolDir(&name, dirIH);
1453         namei_RemoveDataDirectories(&name);
1454     }
1455
1456     return ninodes;
1457 }
1458
1459 static int
1460 DecodeVolumeName(char *name, unsigned int *vid)
1461 {
1462     if (strlen(name) < 1)
1463         return -1;
1464     *vid = (unsigned int)flipbase64_to_int64(name);
1465     return 0;
1466 }
1467
1468
1469 /* DecodeInode
1470  *
1471  * Get the inode number from the name.
1472  * Get
1473  */
1474 static int
1475 DecodeInode(char *dpath, char *name, struct ViceInodeInfo *info,
1476             unsigned int volid)
1477 {
1478     char fpath[512];
1479     struct afs_stat status;
1480     int parm, tag;
1481     lb64_string_t check;
1482
1483     afs_snprintf(fpath, sizeof(fpath), "%s/%s", dpath, name);
1484
1485     if (afs_stat(fpath, &status) < 0) {
1486         return -1;
1487     }
1488
1489     info->byteCount = status.st_size;
1490     info->inodeNumber = (Inode) flipbase64_to_int64(name);
1491
1492     int64_to_flipbase64(check, info->inodeNumber);
1493     if (strcmp(name, check))
1494         return -1;
1495
1496     GetOGMFromStat(&status, &parm, &tag);
1497     if ((info->inodeNumber & NAMEI_INODESPECIAL) == NAMEI_INODESPECIAL) {
1498         /* p1 - vid, p2 - -1, p3 - type, p4 - rwvid */
1499         info->u.param[0] = parm;
1500         info->u.param[1] = -1;
1501         info->u.param[2] = tag;
1502         info->u.param[3] = volid;
1503     } else {
1504         /* p1 - vid, p2 - vno, p3 - uniq, p4 - dv */
1505         info->u.param[0] = volid;
1506         info->u.param[1] = (int)(info->inodeNumber & NAMEI_VNODEMASK);
1507         info->u.param[2] = (int)((info->inodeNumber >> NAMEI_UNIQSHIFT)
1508                                  & (Inode) NAMEI_UNIQMASK);
1509         info->u.param[3] = parm;
1510     }
1511     return 0;
1512 }
1513
1514 /*
1515  * Convert the VolumeInfo file from RO to RW
1516  * this routine is called by namei_convertROtoRWvolume()
1517  */
1518
1519 #ifdef FSSYNC_BUILD_CLIENT
1520 static afs_int32
1521 convertVolumeInfo(int fdr, int fdw, afs_uint32 vid)
1522 {
1523     struct VolumeDiskData vd;
1524     char *p;
1525
1526     if (read(fdr, &vd, sizeof(struct VolumeDiskData)) !=
1527         sizeof(struct VolumeDiskData)) {
1528         Log("1 convertVolumeInfo: read failed for %lu with code %d\n",
1529             afs_printable_uint32_lu(vid),
1530             errno);
1531         return -1;
1532     }
1533     vd.restoredFromId = vd.id;  /* remember the RO volume here */
1534     vd.cloneId = vd.id;
1535     vd.id = vd.parentId;
1536     vd.type = RWVOL;
1537     vd.dontSalvage = 0;
1538     vd.inUse = 0;
1539     vd.uniquifier += 5000;      /* just in case there are still file copies from
1540                                  * the old RW volume around */
1541     p = strrchr(vd.name, '.');
1542     if (p && !strcmp(p, ".readonly")) {
1543         memset(p, 0, 9);
1544     }
1545     if (write(fdw, &vd, sizeof(struct VolumeDiskData)) !=
1546         sizeof(struct VolumeDiskData)) {
1547         Log("1 convertVolumeInfo: write failed for %lu with code %d\n",
1548             afs_printable_uint32_lu(vid),
1549             errno);
1550         return -1;
1551     }
1552     return 0;
1553 }
1554 #endif
1555
1556 /*
1557  * Convert a RO-volume into a RW-volume
1558  *
1559  * This function allows to recover very fast from the loss of a partition
1560  * from RO-copies if all RO-Copies exist on another partition.
1561  * Then these RO-volumes can be made to the new RW-volumes.
1562  * Backup of RW-volumes then consists in "vos release".
1563  *
1564  * We must make sure in this partition exists only the RO-volume which
1565  * is typical for remote replicas.
1566  *
1567  * Then the linktable is already ok,
1568  *      the vnode files need to be renamed
1569  *      the volinfo file needs to be replaced by another one with
1570  *                      slightly different contents and new name.
1571  * The volume header file of the RO-volume in the /vicep<x> directory
1572  * is destroyed by this call. A new header file for the RW-volume must
1573  * be created after return from this routine.
1574  */
1575
1576 int
1577 namei_ConvertROtoRWvolume(char *pname, afs_uint32 volumeId)
1578 {
1579     int code = 0;
1580 #ifdef FSSYNC_BUILD_CLIENT
1581     namei_t n;
1582     char dir_name[512], oldpath[512], newpath[512];
1583     char smallName[64];
1584     char largeName[64];
1585     char infoName[64];
1586     IHandle_t t_ih;
1587     IHandle_t *ih;
1588     char infoSeen = 0;
1589     char smallSeen = 0;
1590     char largeSeen = 0;
1591     char linkSeen = 0;
1592     int fd, fd2;
1593     char *p;
1594     DIR *dirp;
1595     Inode ino;
1596     struct dirent *dp;
1597     struct DiskPartition64 *partP;
1598     struct ViceInodeInfo info;
1599     struct VolumeDiskHeader h;
1600 # ifdef AFS_DEMAND_ATTACH_FS
1601     int locktype = 0;
1602 # endif /* AFS_DEMAND_ATTACH_FS */
1603
1604     for (partP = DiskPartitionList; partP && strcmp(partP->name, pname);
1605          partP = partP->next);
1606     if (!partP) {
1607         Log("1 namei_ConvertROtoRWvolume: Couldn't find DiskPartition for %s\n", pname);
1608         code = EIO;
1609         goto done;
1610     }
1611
1612 # ifdef AFS_DEMAND_ATTACH_FS
1613     locktype = VVolLockType(V_VOLUPD, 1);
1614     code = VLockVolumeByIdNB(volumeId, partP, locktype);
1615     if (code) {
1616         locktype = 0;
1617         code = EIO;
1618         goto done;
1619     }
1620 # endif /* AFS_DEMAND_ATTACH_FS */
1621
1622     if (VReadVolumeDiskHeader(volumeId, partP, &h)) {
1623         Log("1 namei_ConvertROtoRWvolume: Couldn't read header for RO-volume %lu.\n",
1624             afs_printable_uint32_lu(volumeId));
1625         code = EIO;
1626         goto done;
1627     }
1628
1629     FSYNC_VolOp(volumeId, pname, FSYNC_VOL_BREAKCBKS, 0, NULL);
1630
1631     ino = namei_MakeSpecIno(h.parent, VI_LINKTABLE);
1632     IH_INIT(ih, partP->device, h.parent, ino);
1633
1634     namei_HandleToName(&n, ih);
1635     strlcpy(dir_name, n.n_path, sizeof(dir_name));
1636     p = strrchr(dir_name, '/');
1637     *p = 0;
1638     dirp = opendir(dir_name);
1639     if (!dirp) {
1640         Log("1 namei_ConvertROtoRWvolume: Could not opendir(%s)\n", dir_name);
1641         code = EIO;
1642         goto done;
1643     }
1644
1645     while ((dp = readdir(dirp))) {
1646         /* struct ViceInodeInfo info; */
1647
1648         if (*dp->d_name == '.')
1649             continue;
1650         if (DecodeInode(dir_name, dp->d_name, &info, ih->ih_vid) < 0) {
1651             Log("1 namei_ConvertROtoRWvolume: DecodeInode failed for %s/%s\n",
1652                 dir_name, dp->d_name);
1653             closedir(dirp);
1654             code = -1;
1655             goto done;
1656         }
1657         if (info.u.param[1] != -1) {
1658             Log("1 namei_ConvertROtoRWvolume: found other than volume special file %s/%s\n", dir_name, dp->d_name);
1659             closedir(dirp);
1660             code = -1;
1661             goto done;
1662         }
1663         if (info.u.param[0] != volumeId) {
1664             if (info.u.param[0] == ih->ih_vid) {
1665                 if (info.u.param[2] == VI_LINKTABLE) {  /* link table */
1666                     linkSeen = 1;
1667                     continue;
1668                 }
1669             }
1670             Log("1 namei_ConvertROtoRWvolume: found special file %s/%s"
1671                 " for volume %lu\n", dir_name, dp->d_name,
1672                 afs_printable_uint32_lu(info.u.param[0]));
1673             closedir(dirp);
1674             code = VVOLEXISTS;
1675             goto done;
1676         }
1677         if (info.u.param[2] == VI_VOLINFO) {    /* volume info file */
1678             strlcpy(infoName, dp->d_name, sizeof(infoName));
1679             infoSeen = 1;
1680         } else if (info.u.param[2] == VI_SMALLINDEX) {  /* small vnodes file */
1681             strlcpy(smallName, dp->d_name, sizeof(smallName));
1682             smallSeen = 1;
1683         } else if (info.u.param[2] == VI_LARGEINDEX) {  /* large vnodes file */
1684             strlcpy(largeName, dp->d_name, sizeof(largeName));
1685             largeSeen = 1;
1686         } else {
1687             closedir(dirp);
1688             Log("1 namei_ConvertROtoRWvolume: unknown type %d of special file found : %s/%s\n", info.u.param[2], dir_name, dp->d_name);
1689             code = -1;
1690             goto done;
1691         }
1692     }
1693     closedir(dirp);
1694
1695     if (!infoSeen || !smallSeen || !largeSeen || !linkSeen) {
1696         Log("1 namei_ConvertROtoRWvolume: not all special files found in %s\n", dir_name);
1697         code = -1;
1698         goto done;
1699     }
1700
1701     /*
1702      * If we come here then there was only a RO-volume and we can safely
1703      * proceed.
1704      */
1705
1706     memset(&t_ih, 0, sizeof(t_ih));
1707     t_ih.ih_dev = ih->ih_dev;
1708     t_ih.ih_vid = ih->ih_vid;
1709
1710     (void)afs_snprintf(oldpath, sizeof oldpath, "%s/%s", dir_name, infoName);
1711     fd = afs_open(oldpath, O_RDWR, 0);
1712     if (fd < 0) {
1713         Log("1 namei_ConvertROtoRWvolume: could not open RO info file: %s\n",
1714             oldpath);
1715         code = -1;
1716         goto done;
1717     }
1718     t_ih.ih_ino = namei_MakeSpecIno(ih->ih_vid, VI_VOLINFO);
1719     namei_HandleToName(&n, &t_ih);
1720     fd2 = afs_open(n.n_path, O_CREAT | O_EXCL | O_TRUNC | O_RDWR, 0);
1721     if (fd2 < 0) {
1722         Log("1 namei_ConvertROtoRWvolume: could not create RW info file: %s\n", n.n_path);
1723         close(fd);
1724         code = -1;
1725         goto done;
1726     }
1727     code = convertVolumeInfo(fd, fd2, ih->ih_vid);
1728     close(fd);
1729     if (code) {
1730         close(fd2);
1731         unlink(n.n_path);
1732         code = -1;
1733         goto done;
1734     }
1735     SetOGM(fd2, ih->ih_vid, 1);
1736     close(fd2);
1737
1738     t_ih.ih_ino = namei_MakeSpecIno(ih->ih_vid, VI_SMALLINDEX);
1739     namei_HandleToName(&n, &t_ih);
1740     (void)afs_snprintf(newpath, sizeof newpath, "%s/%s", dir_name, smallName);
1741     fd = afs_open(newpath, O_RDWR, 0);
1742     if (fd < 0) {
1743         Log("1 namei_ConvertROtoRWvolume: could not open SmallIndex file: %s\n", newpath);
1744         code = -1;
1745         goto done;
1746     }
1747     SetOGM(fd, ih->ih_vid, 2);
1748     close(fd);
1749     link(newpath, n.n_path);
1750     unlink(newpath);
1751
1752     t_ih.ih_ino = namei_MakeSpecIno(ih->ih_vid, VI_LARGEINDEX);
1753     namei_HandleToName(&n, &t_ih);
1754     (void)afs_snprintf(newpath, sizeof newpath, "%s/%s", dir_name, largeName);
1755     fd = afs_open(newpath, O_RDWR, 0);
1756     if (fd < 0) {
1757         Log("1 namei_ConvertROtoRWvolume: could not open LargeIndex file: %s\n", newpath);
1758         code = -1;
1759         goto done;
1760     }
1761     SetOGM(fd, ih->ih_vid, 3);
1762     close(fd);
1763     link(newpath, n.n_path);
1764     unlink(newpath);
1765
1766     unlink(oldpath);
1767
1768     h.id = h.parent;
1769     h.volumeInfo_hi = h.id;
1770     h.smallVnodeIndex_hi = h.id;
1771     h.largeVnodeIndex_hi = h.id;
1772     h.linkTable_hi = h.id;
1773
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));
1777         code = EIO;
1778         goto done;
1779     }
1780
1781     if (VDestroyVolumeDiskHeader(partP, volumeId, h.parent)) {
1782         Log("1 namei_ConvertROtoRWvolume: Couldn't unlink header for RO-volume %lu\n",
1783             afs_printable_uint32_lu(volumeId));
1784     }
1785
1786     FSYNC_VolOp(volumeId, pname, FSYNC_VOL_DONE, 0, NULL);
1787     FSYNC_VolOp(h.id, pname, FSYNC_VOL_ON, 0, NULL);
1788
1789  done:
1790 # ifdef AFS_DEMAND_ATTACH_FS
1791     if (locktype) {
1792         VUnlockVolumeById(volumeId, partP);
1793     }
1794 # endif /* AFS_DEMAND_ATTACH_FS */
1795 #endif
1796
1797     return code;
1798 }
1799
1800 /* PrintInode
1801  *
1802  * returns a static string used to print either 32 or 64 bit inode numbers.
1803  */
1804 char *
1805 PrintInode(char *s, Inode ino)
1806 {
1807     static afs_ino_str_t result;
1808     if (!s)
1809         s = result;
1810
1811     (void)afs_snprintf(s, sizeof(afs_ino_str_t), "%llu", (afs_uintmax_t) ino);
1812
1813     return s;
1814 }
1815
1816
1817 #ifdef DELETE_ZLC
1818 /* Routines to facilitate removing zero link count files. */
1819 #define MAX_ZLC_NAMES 32
1820 #define MAX_ZLC_NAMELEN 16
1821 typedef struct zlcList_s {
1822     struct zlcList_s *zlc_next;
1823     int zlc_n;
1824     char zlc_names[MAX_ZLC_NAMES][MAX_ZLC_NAMELEN];
1825 } zlcList_t;
1826
1827 static zlcList_t *zlcAnchor = NULL;
1828 static zlcList_t *zlcCur = NULL;
1829
1830 static void
1831 AddToZLCDeleteList(char dir, char *name)
1832 {
1833     assert(strlen(name) <= MAX_ZLC_NAMELEN - 3);
1834
1835     if (!zlcCur || zlcCur->zlc_n >= MAX_ZLC_NAMES) {
1836         if (zlcCur && zlcCur->zlc_next)
1837             zlcCur = zlcCur->zlc_next;
1838         else {
1839             zlcList_t *tmp = (zlcList_t *) malloc(sizeof(zlcList_t));
1840             if (!tmp)
1841                 return;
1842             if (!zlcAnchor) {
1843                 zlcAnchor = tmp;
1844             } else {
1845                 zlcCur->zlc_next = tmp;
1846             }
1847             zlcCur = tmp;
1848             zlcCur->zlc_n = 0;
1849             zlcCur->zlc_next = NULL;
1850         }
1851     }
1852
1853     (void)sprintf(zlcCur->zlc_names[zlcCur->zlc_n], "%c\\%s", dir, name);
1854     zlcCur->zlc_n++;
1855 }
1856
1857 static void
1858 DeleteZLCFiles(char *path)
1859 {
1860     zlcList_t *z;
1861     int i;
1862     char fname[1024];
1863
1864     for (z = zlcAnchor; z; z = z->zlc_next) {
1865         for (i = 0; i < z->zlc_n; i++) {
1866             (void)sprintf(fname, "%s\\%s", path, z->zlc_names[i]);
1867             if (namei_unlink(fname) < 0) {
1868                 Log("ZLC: Can't unlink %s, dos error = %d\n", fname,
1869                     GetLastError());
1870             }
1871         }
1872         z->zlc_n = 0;           /* Can reuse space. */
1873     }
1874     zlcCur = zlcAnchor;
1875 }
1876
1877 static void
1878 FreeZLCList(void)
1879 {
1880     zlcList_t *tnext;
1881     zlcList_t *i;
1882
1883     i = zlcAnchor;
1884     while (i) {
1885         tnext = i->zlc_next;
1886         free(i);
1887         i = tnext;
1888     }
1889     zlcCur = zlcAnchor = NULL;
1890 }
1891 #endif
1892
1893 #endif /* AFS_NAMEI_ENV */