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