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