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