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