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