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