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