41c07c7ad0736398382179a25e5c82bc742a7c1d
[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 #include <roken.h>
16
17 #ifdef AFS_NAMEI_ENV
18 #include <stdio.h>
19 #include <stdlib.h>
20 #ifndef AFS_NT40_ENV
21 #include <unistd.h>
22 #else
23 #define DELETE_ZLC
24 #include <io.h>
25 #include <windows.h>
26 #include <winnt.h>
27 #include <winbase.h>
28 #include <winsock2.h>
29 #endif
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <sys/stat.h>
33 #ifdef AFS_NT40_ENV
34 #include <direct.h>
35 #else
36 #include <sys/file.h>
37 #include <sys/param.h>
38 #endif
39 #include <dirent.h>
40 #include <afs/afs_assert.h>
41 #include <string.h>
42 #include <lock.h>
43 #include <afs/afsutil.h>
44 #include <lwp.h>
45 #include "nfs.h"
46 #include <afs/afsint.h>
47 #include "ihandle.h"
48 #include "vnode.h"
49 #include "volume.h"
50 #include "viceinode.h"
51 #include "voldefs.h"
52 #include "partition.h"
53 #include "fssync.h"
54 #include "volume_inline.h"
55 #include "common.h"
56 #include <afs/errors.h>
57 #ifdef AFS_NT40_ENV
58 #include <afs/errmap_nt.h>
59 #endif
60
61 /*@+fcnmacros +macrofcndecl@*/
62 #ifdef O_LARGEFILE
63 #ifdef S_SPLINT_S
64 #endif /*S_SPLINT_S */
65 #define afs_stat                stat64
66 #define afs_fstat               fstat64
67 #ifdef AFS_NT40_ENV
68 #define afs_open                nt_open
69 #else
70 #define afs_open                open64
71 #endif
72 #define afs_fopen               fopen64
73 #else /* !O_LARGEFILE */
74 #ifdef S_SPLINT_S
75 #endif /*S_SPLINT_S */
76 #define afs_stat                stat
77 #define afs_fstat               fstat
78 #ifdef AFS_NT40_ENV
79 #define afs_open                nt_open
80 #else
81 #define afs_open                open
82 #endif
83 #define afs_fopen               fopen
84 #endif /* !O_LARGEFILE */
85 /*@=fcnmacros =macrofcndecl@*/
86
87 #ifndef LOCK_SH
88 #define   LOCK_SH   1    /* shared lock */
89 #define   LOCK_EX   2    /* exclusive lock */
90 #define   LOCK_NB   4    /* don't block when locking */
91 #define   LOCK_UN   8    /* unlock */
92 #endif
93
94 #ifdef AFS_SALSRV_ENV
95 #include <pthread.h>
96 #include <afs/work_queue.h>
97 #include <afs/thread_pool.h>
98 #include <vol/vol-salvage.h>
99 #endif
100
101 #if !defined(HAVE_FLOCK) && !defined(AFS_NT40_ENV)
102 #include <fcntl.h>
103
104 /*
105  * This function emulates a subset of flock()
106  */
107 int
108 emul_flock(int fd, int cmd)
109 {    struct flock f;
110
111     memset(&f, 0, sizeof (f));
112
113     if (cmd & LOCK_UN)
114         f.l_type = F_UNLCK;
115     if (cmd & LOCK_SH)
116         f.l_type = F_RDLCK;
117     if (cmd & LOCK_EX)
118         f.l_type = F_WRLCK;
119
120     return fcntl(fd, (cmd & LOCK_NB) ? F_SETLK : F_SETLKW, &f);
121 }
122
123 #define flock(f,c)      emul_flock(f,c)
124 #endif
125
126 int Testing=0;
127
128
129 afs_sfsize_t
130 namei_iread(IHandle_t * h, afs_foff_t offset, char *buf, afs_fsize_t size)
131 {
132     afs_sfsize_t nBytes;
133     FdHandle_t *fdP;
134
135     fdP = IH_OPEN(h);
136     if (fdP == NULL)
137         return -1;
138
139     nBytes = FDH_PREAD(fdP, buf, size, offset);
140     FDH_CLOSE(fdP);
141     return nBytes;
142 }
143
144 afs_sfsize_t
145 namei_iwrite(IHandle_t * h, afs_foff_t offset, char *buf, afs_fsize_t size)
146 {
147     afs_sfsize_t nBytes;
148     FdHandle_t *fdP;
149
150     fdP = IH_OPEN(h);
151     if (fdP == NULL)
152         return -1;
153
154     nBytes = FDH_PWRITE(fdP, buf, size, offset);
155     FDH_CLOSE(fdP);
156     return nBytes;
157 }
158
159 #ifdef AFS_NT40_ENV
160 /* Inode number format:
161  * low 32 bits - if a regular file or directory, the vnode; else the type.
162  * 32-36 - uniquifier tag and index into counts array for this vnode. Only
163  *         two of the available bits are currently used. The rest are
164  *         present in case we ever increase the number of types of volumes
165  *         in the volume group.
166  * bit 37 : 1  == special, 0 == regular
167  */
168 # define NAMEI_VNODEMASK    0x00ffffffff
169 # define NAMEI_TAGSHIFT     32
170 # define NAMEI_INODESPECIAL 0x2000000000
171 # define NAMEI_SPECDIR "R"
172 # define NAMEI_SPECDIRC 'R'
173 #else /* !AFS_NT40_ENV */
174 /* Inode number format:
175  * low 26 bits - vnode number - all 1's if volume special file.
176  * next 3 bits - tag
177  * next 3 bits spare (0's)
178  * high 32 bits - uniquifier (regular) or type if spare
179  */
180 # define NAMEI_VNODEMASK    0x003ffffff
181 # define NAMEI_TAGSHIFT     26
182 # define NAMEI_UNIQMASK     0xffffffff
183 # define NAMEI_UNIQSHIFT    32
184 # define NAMEI_INODESPECIAL ((Inode)NAMEI_VNODEMASK)
185 /* dir1 is the high 8 bits of the 26 bit vnode */
186 # define VNO_DIR1(vno) ((vno >> 14) & 0xff)
187 /* dir2 is the next 9 bits */
188 # define VNO_DIR2(vno) ((vno >> 9) & 0x1ff)
189 /* "name" is the low 9 bits of the vnode, the 3 bit tag and the uniq */
190 # define NAMEI_SPECDIR "special"
191 #endif /* !AFS_NT40_ENV */
192 #define NAMEI_TAGMASK      0x7
193 #define NAMEI_VNODESPECIAL NAMEI_VNODEMASK
194
195 #define NAMEI_SPECDIRLEN (sizeof(NAMEI_SPECDIR)-1)
196
197 #define NAMEI_MAXVOLS 5         /* Maximum supported number of volumes per volume
198                                  * group, not counting temporary (move) volumes.
199                                  * This is the number of separate files, all having
200                                  * the same vnode number, which can occur in a volume
201                                  * group at once.
202                                  */
203
204 #ifndef AFS_NT40_ENV
205 typedef struct {
206     int ogm_owner;
207     int ogm_group;
208     int ogm_mode;
209 } namei_ogm_t;
210 #endif
211
212 static int GetFreeTag(IHandle_t * ih, int vno);
213
214 /* namei_HandleToInodeDir
215  *
216  * Construct the path name of the directory holding the inode data.
217  * Format: /<vicepx>/INODEDIR
218  *
219  */
220 #ifdef AFS_NT40_ENV
221 static void
222 namei_HandleToInodeDir(namei_t * name, IHandle_t * ih)
223 {
224     memset(name, '\0', sizeof(*name));
225     nt_DevToDrive(name->n_drive, ih->ih_dev);
226     strlcpy(name->n_path, name->n_drive, sizeof(name->n_path));
227 }
228
229 #else
230 /* Format: /<vicepx>/INODEDIR */
231 #define PNAME_BLEN 64
232 static void
233 namei_HandleToInodeDir(namei_t * name, IHandle_t * ih)
234 {
235     size_t offset;
236
237     memset(name, '\0', sizeof(*name));
238
239     /*
240      * Add the /vicepXX string to the start of name->n_base and then calculate
241      * offset as the number of bytes we know we added.
242      *
243      * FIXME: This embeds knowledge of the vice partition naming scheme and
244      * mapping from device numbers.  There needs to be an API that tells us
245      * this offset.
246      */
247     volutil_PartitionName_r(ih->ih_dev, name->n_base, sizeof(name->n_base));
248     offset = VICE_PREFIX_SIZE + (ih->ih_dev > 25 ? 2 : 1);
249     name->n_base[offset] = OS_DIRSEPC;
250     offset++;
251     strlcpy(name->n_base + offset, INODEDIR, sizeof(name->n_base) - offset);
252     strlcpy(name->n_path, name->n_base, sizeof(name->n_path));
253 }
254 #endif
255
256 #define addtoname(N, C)                                         \
257 do {                                                            \
258     if ((N)->n_path[strlen((N)->n_path)-1] != OS_DIRSEPC)       \
259         strlcat((N)->n_path, OS_DIRSEP, sizeof((N)->n_path));   \
260     strlcat((N)->n_path, (C), sizeof((N)->n_path));             \
261 } while(0)
262
263
264 #ifdef AFS_NT40_ENV
265 static void
266 namei_HandleToVolDir(namei_t * name, IHandle_t * ih)
267 {
268     /* X:\Vol_XXXXXXX.data */
269     b32_string_t str1;
270     char *namep;
271
272     namei_HandleToInodeDir(name, ih);
273     /* nt_drive added to name by namei_HandleToInodeDir() */
274     namep = name->n_voldir;
275     (void)memcpy(namep, "\\Vol_", 5);
276     namep += 5;
277     (void)strcpy(namep, int_to_base32(str1, ih->ih_vid));
278     namep += strlen(namep);
279     memcpy(namep, ".data", 5);
280     namep += 5;
281     *namep = '\0';
282     addtoname(name, name->n_voldir);
283 }
284 #else
285 static void
286 namei_HandleToVolDir(namei_t * name, IHandle_t * ih)
287 {
288     lb64_string_t tmp;
289
290     namei_HandleToInodeDir(name, ih);
291     (void)int32_to_flipbase64(tmp, (int64_t) (ih->ih_vid & 0xff));
292     strlcpy(name->n_voldir1, tmp, sizeof(name->n_voldir1));
293     addtoname(name, name->n_voldir1);
294     (void)int32_to_flipbase64(tmp, (int64_t) ih->ih_vid);
295     strlcpy(name->n_voldir2, tmp, sizeof(name->n_voldir2));
296     addtoname(name, name->n_voldir2);
297 }
298 #endif
299
300 /* namei_HandleToName
301  *
302  * Constructs a file name for the fully qualified handle.
303  */
304 #ifdef AFS_NT40_ENV
305 /* Note that special files end up in X:\Vol_XXXXXXX.data\R */
306 void
307 namei_HandleToName(namei_t * name, IHandle_t * ih)
308 {
309     int vno = (int)(ih->ih_ino & NAMEI_VNODEMASK);
310     int special = (ih->ih_ino & NAMEI_INODESPECIAL)?1:0;
311     int tag = (int)((ih->ih_ino >> NAMEI_TAGSHIFT) & NAMEI_TAGMASK);
312     b32_string_t str1;
313     char *namep;
314     namei_HandleToVolDir(name, ih);
315
316     if (special) {
317         name->n_dir[0] = NAMEI_SPECDIRC;
318     } else {
319         if (vno & 0x1)
320             name->n_dir[0] = 'Q';
321         else
322             name->n_dir[0] = ((vno & 0x1f) >> 1) + 'A';
323
324     }
325     name->n_dir[1] = '\0';
326     addtoname(name, name->n_dir);
327     /* X:\Vol_XXXXXXX.data\X\V_XXXXXXX.XXX */
328     namep = name->n_inode;
329     (void)memcpy(namep, "\\V_", 3);
330     namep += 3;
331     (void)strcpy(namep, int_to_base32(str1, vno));
332     namep += strlen(namep);
333     *(namep++) = '.';
334     (void)strcpy(namep, int_to_base32(str1, tag));
335     namep += strlen(namep);
336     addtoname(name, name->n_inode);
337 }
338 #else
339 /* Note that special files end up in /vicepX/InodeDir/Vxx/V*.data/special */
340 void
341 namei_HandleToName(namei_t * name, IHandle_t * ih)
342 {
343     int vno = (int)(ih->ih_ino & NAMEI_VNODEMASK);
344     lb64_string_t str;
345
346     namei_HandleToVolDir(name, ih);
347
348     if (vno == NAMEI_VNODESPECIAL) {
349         strlcpy(name->n_dir1, NAMEI_SPECDIR, sizeof(name->n_dir1));
350         addtoname(name, name->n_dir1);
351         name->n_dir2[0] = '\0';
352     } else {
353         (void)int32_to_flipbase64(str, VNO_DIR1(vno));
354         strlcpy(name->n_dir1, str, sizeof(name->n_dir1));
355         addtoname(name, name->n_dir1);
356         (void)int32_to_flipbase64(str, VNO_DIR2(vno));
357         strlcpy(name->n_dir2, str, sizeof(name->n_dir2));
358         addtoname(name, name->n_dir2);
359     }
360     (void)int64_to_flipbase64(str, (int64_t) ih->ih_ino);
361     strlcpy(name->n_inode, str, sizeof(name->n_inode));
362     addtoname(name, name->n_inode);
363 }
364 #endif
365
366 #ifndef AFS_NT40_ENV
367 /* The following is a warning to tell sys-admins to not muck about in this
368  * name space.
369  */
370 #define VICE_README "These files and directories are a part of the AFS \
371 namespace. Modifying them\nin any way will result in loss of AFS data,\n\
372 ownership and permissions included.\n"
373 int
374 namei_ViceREADME(char *partition)
375 {
376     char filename[32];
377     int fd;
378
379     /* Create the inode directory if we're starting for the first time */
380     (void)afs_snprintf(filename, sizeof filename, "%s" OS_DIRSEP "%s", partition,
381                        INODEDIR);
382     mkdir(filename, 0700);
383
384     (void)afs_snprintf(filename, sizeof filename, "%s" OS_DIRSEP "%s" OS_DIRSEP "README",
385                        partition, INODEDIR);
386     fd = afs_open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0444);
387     if (fd >= 0) {
388         (void)write(fd, VICE_README, strlen(VICE_README));
389         close(fd);
390     }
391     return (errno);
392 }
393 #endif
394
395 /* namei_CreateDataDirectories
396  *
397  * If creating the file failed because of ENOENT or ENOTDIR, try
398  * creating all the directories first.
399  */
400 #ifdef AFS_NT40_ENV
401 static int
402 namei_CreateDataDirectories(namei_t * name, int *created)
403 {
404     char tmp[256];
405     char *s;
406     int i;
407
408     *created = 0;
409     afs_snprintf(tmp, 256, "%s" OS_DIRSEP "%s", name->n_drive, name->n_voldir);
410
411     if (mkdir(tmp) < 0) {
412         if (errno != EEXIST)
413             return -1;
414     } else
415         *created = 1;
416
417     s = tmp;
418     s += strlen(tmp);
419
420     *s++ = OS_DIRSEPC;
421     *(s + 1) = '\0';
422     for (i = 'A'; i <= NAMEI_SPECDIRC; i++) {
423         *s = (char)i;
424         if (mkdir(tmp) < 0 && errno != EEXIST)
425             return -1;
426     }
427     return 0;
428 }
429 #else
430 #define create_dir() \
431 do { \
432     if (mkdir(tmp, 0700)<0) { \
433         if (errno != EEXIST) \
434             return -1; \
435     } \
436     else { \
437         *created = 1; \
438     } \
439 } while (0)
440
441 #define create_nextdir(A) \
442 do { \
443          strcat(tmp, OS_DIRSEP); strcat(tmp, A); create_dir();  \
444 } while(0)
445
446 static int
447 namei_CreateDataDirectories(namei_t * name, int *created)
448 {
449     char tmp[256];
450
451     *created = 0;
452
453     strlcpy(tmp, name->n_base, sizeof(tmp));
454     create_dir();
455
456     create_nextdir(name->n_voldir1);
457     create_nextdir(name->n_voldir2);
458     create_nextdir(name->n_dir1);
459     if (name->n_dir2[0]) {
460         create_nextdir(name->n_dir2);
461     }
462     return 0;
463 }
464 #endif
465
466 #ifndef AFS_NT40_ENV
467 /* delTree(): Deletes an entire tree of directories (no files)
468  * Input:
469  *   root : Full path to the subtree. Should be big enough for PATH_MAX
470  *   tree : the subtree to be deleted is rooted here. Specifies only the
471  *          subtree beginning at tree (not the entire path). It should be
472  *          a pointer into the "root" buffer.
473  * Output:
474  *  errp : errno of the first error encountered during the directory cleanup.
475  *         *errp should have been initialized to 0.
476  *
477  * Return Values:
478  *  -1  : If errors were encountered during cleanup and error is set to
479  *        the first errno.
480  *   0  : Success.
481  *
482  * If there are errors, we try to work around them and delete as many
483  * directories as possible. We don't attempt to remove directories that still
484  * have non-dir entries in them.
485  */
486 static int
487 delTree(char *root, char *tree, int *errp)
488 {
489     char *cp;
490     DIR *ds;
491     struct dirent *dirp;
492     struct afs_stat st;
493
494     if (*tree) {
495         /* delete the children first */
496         cp = strchr(tree, OS_DIRSEPC);
497         if (cp) {
498             delTree(root, cp + 1, errp);
499             *cp = '\0';
500         } else
501             cp = tree + strlen(tree);   /* move cp to the end of string tree */
502
503         /* now delete all entries in this dir */
504         if ((ds = opendir(root)) != (DIR *) NULL) {
505             errno = 0;
506             while ((dirp = readdir(ds))) {
507                 /* ignore . and .. */
508                 if (!strcmp(dirp->d_name, ".") || !strcmp(dirp->d_name, ".."))
509                     continue;
510                 /* since root is big enough, we reuse the space to
511                  * concatenate the dirname to the current tree
512                  */
513                 strcat(root, OS_DIRSEP);
514                 strcat(root, dirp->d_name);
515                 if (afs_stat(root, &st) == 0 && S_ISDIR(st.st_mode)) {
516                     /* delete this subtree */
517                     delTree(root, cp + 1, errp);
518                 } else
519                     *errp = *errp ? *errp : errno;
520
521                 /* recover path to our cur tree by truncating it to
522                  * its original len
523                  */
524                 *cp = 0;
525             }
526             /* if (!errno) -- closedir not implicit if we got an error */
527             closedir(ds);
528         }
529
530         /* finally axe the current dir */
531         if (rmdir(root))
532             *errp = *errp ? *errp : errno;
533
534 #ifndef AFS_PTHREAD_ENV         /* let rx get some work done */
535         IOMGR_Poll();
536 #endif /* !AFS_PTHREAD_ENV */
537
538     }
539
540     /* if valid tree */
541     /* if we encountered errors during cleanup, we return a -1 */
542     if (*errp)
543         return -1;
544
545     return 0;
546
547 }
548 #endif
549
550 /* namei_RemoveDataDirectories
551  * Return Values:
552  * Returns 0 on success.
553  * Returns -1 on error. Typically, callers ignore this error because we
554  * can continue running if the removes fail. The salvage process will
555  * finish tidying up for us.
556  */
557
558 #ifdef AFS_NT40_ENV
559 static int
560 namei_RemoveDataDirectories(namei_t * name)
561 {
562     int code = 0;
563     char *path;
564     char tmp[256];
565     int i;
566
567     afs_snprintf(tmp, 256, "%s" OS_DIRSEP "%s", name->n_drive, name->n_voldir);
568
569     path = tmp;
570     path += strlen(path);
571     *path++ = OS_DIRSEPC;
572     *(path + 1) = '\0';
573     for (i = 'A'; i <= NAMEI_SPECDIRC; i++) {
574         *path = (char)i;
575         if (rmdir(name->n_path) < 0 && errno != ENOENT)
576             code = -1;
577     }
578
579     if (!code) {
580         /* Delete the Vol_NNNNNN.data directory. */
581         path--;
582         *path = '\0';
583         if (rmdir(name->n_path) < 0 && errno != ENOENT) {
584             code = -1;
585         }
586     }
587     return code;
588 }
589 #else
590 /*
591  * We only use the n_base and n_voldir1 entries
592  * and only do rmdir's.
593  */
594 static int
595 namei_RemoveDataDirectories(namei_t * name)
596 {
597     int code = 0;
598     char *path;
599     int prefixlen = strlen(name->n_base), err = 0;
600     int vollen = strlen(name->n_voldir1);
601     char pbuf[MAXPATHLEN];
602
603     path = pbuf;
604
605     strlcpy(path, name->n_path, sizeof(pbuf));
606
607     /* move past the prefix and n_voldir1 */
608     path = path + prefixlen + 1 + vollen + 1;   /* skip over the trailing / */
609
610     /* now delete all dirs upto path */
611     code = delTree(pbuf, path, &err);
612
613     /* We've now deleted everything under /n_base/n_voldir1/n_voldir2 that
614      * we could. Do not delete /n_base/n_voldir1, since doing such might
615      * interrupt another thread trying to create a volume. We could introduce
616      * some locking to make this safe (or only remove it for whole-partition
617      * salvages), but by not deleting it we only leave behind a maximum of
618      * 256 empty directories. So at least for now, don't bother. */
619     return code;
620 }
621 #endif
622
623 /* Create the file in the name space.
624  *
625  * Parameters stored as follows:
626  * Regular files:
627  * p1 - volid - implied in containing directory.
628  * p2 - vnode - name is <vno:31-23>/<vno:22-15>/<vno:15-0><uniq:31-5><tag:2-0>
629  * p3 - uniq -- bits 4-0 are in mode bits 4-0
630  * p4 - dv ---- dv:15-0 in uid, dv:29-16 in gid, dv:31-30 in mode:6-5
631  * Special files:
632  * p1 - volid - creation time - dwHighDateTime
633  * p2 - vnode - -1 means special, file goes in "S" subdirectory.
634  * p3 - type -- name is <type>.<tag> where tag is a file name unqiquifier.
635  * p4 - parid - parent volume id - implied in containing directory.
636  *
637  * Return value is the inode number or (Inode)-1 if error.
638  * We "know" there is only one link table, so return EEXIST if there already
639  * is a link table. It's up to the calling code to test errno and increment
640  * the link count.
641  */
642
643 /* namei_MakeSpecIno
644  *
645  * This function is called by VCreateVolume to hide the implementation
646  * details of the inode numbers. This only allows for 7 volume special
647  * types, but if we get that far, this could should be dead by then.
648  */
649 Inode
650 namei_MakeSpecIno(int volid, int type)
651 {
652     Inode ino;
653     ino = NAMEI_INODESPECIAL;
654 #ifdef AFS_NT40_ENV
655     ino |= type;
656     /* tag is always 0 for special */
657 #else
658     type &= NAMEI_TAGMASK;
659     ino |= ((Inode) type) << NAMEI_TAGSHIFT;
660     ino |= ((Inode) volid) << NAMEI_UNIQSHIFT;
661 #endif
662     return ino;
663 }
664
665 #ifdef AFS_NT40_ENV
666 /* SetOGM */
667 static int
668 SetOGM(FD_t fd, int parm, int tag)
669 {
670     return -1;
671 }
672
673 static int
674 CheckOGM(namei_t *name, FdHandle_t *fdP, int p1)
675 {
676     WIN32_FIND_DATA info;
677     HANDLE dirH;
678
679     dirH =
680         FindFirstFileEx(name->n_path, FindExInfoStandard, &info,
681                         FindExSearchNameMatch, NULL,
682                         FIND_FIRST_EX_CASE_SENSITIVE);
683
684     if (!dirH)
685         return -1;          /* Can't get info, leave alone */
686
687     FindClose(dirH);
688
689     if (info.ftCreationTime.dwHighDateTime != (unsigned int)p1)
690         return -1;
691
692     return 0;
693 }
694 #else /* AFS_NT40_ENV */
695 /* SetOGM - set owner group and mode bits from parm and tag */
696 static int
697 SetOGM(FD_t fd, int parm, int tag)
698 {
699 /*
700  * owner - low 15 bits of parm.
701  * group - next 15 bits of parm.
702  * mode - 2 bits of parm, then lowest = 3 bits of tag.
703  */
704     int owner, group, mode;
705
706     owner = parm & 0x7fff;
707     group = (parm >> 15) & 0x7fff;
708     if (fchown(fd, owner, group) < 0)
709         return -1;
710
711     mode = (parm >> 27) & 0x18;
712     mode |= tag & 0x7;
713     if (fchmod(fd, mode) < 0)
714         return -1;
715     return 0;
716 }
717
718 /* GetOGM - get parm and tag from owner, group and mode bits. */
719 static void
720 GetOGMFromStat(struct afs_stat *status, int *parm, int *tag)
721 {
722     *parm = status->st_uid | (status->st_gid << 15);
723     *parm |= (status->st_mode & 0x18) << 27;
724     *tag = status->st_mode & 0x7;
725 }
726
727 static int
728 CheckOGM(namei_t *name, FdHandle_t *fdP, int p1)
729 {
730     struct afs_stat status;
731     int parm, tag;
732     if (afs_fstat(fdP->fd_fd, &status) < 0)
733         return -1;
734
735     GetOGMFromStat(&status, &parm, &tag);
736     if (parm != p1)
737         return -1;
738
739     return 0;
740 }
741 #endif /* !AFS_NT40_ENV */
742
743 int big_vno = 0;                /* Just in case we ever do 64 bit vnodes. */
744
745 /* Derive the name and create it O_EXCL. If that fails we have an error.
746  * Get the tag from a free column in the link table.
747  */
748 #ifdef AFS_NT40_ENV
749 Inode
750 namei_icreate(IHandle_t * lh, char *part, afs_uint32 p1, afs_uint32 p2, afs_uint32 p3, afs_uint32 p4)
751 {
752     namei_t name;
753     FD_t fd = INVALID_FD;
754     int code = 0;
755     int created_dir = 0;
756     IHandle_t tmp;
757     FdHandle_t *fdP;
758     FdHandle_t tfd;
759     int type, tag;
760     FILETIME ftime;
761     char *p;
762     b32_string_t str1;
763
764     memset((void *)&tmp, 0, sizeof(IHandle_t));
765     memset(&tfd, 0, sizeof(FdHandle_t));
766
767     tmp.ih_dev = nt_DriveToDev(part);
768     if (tmp.ih_dev == -1) {
769         errno = EINVAL;
770         return -1;
771     }
772
773     if (p2 == INODESPECIAL) {
774         /* Parameters for special file:
775          * p1 - volume id - goes into owner/group/mode
776          * p2 - vnode == INODESPECIAL
777          * p3 - type
778          * p4 - parent volume id
779          */
780         ftime.dwHighDateTime = p1;
781         ftime.dwLowDateTime = p2;
782         type = p3;
783         tmp.ih_vid = p4;        /* Use parent volume id, where this file will be. */
784         tmp.ih_ino = namei_MakeSpecIno(p1, p3);
785     } else {
786         int vno = p2 & NAMEI_VNODEMASK;
787         /* Parameters for regular file:
788          * p1 - volume id
789          * p2 - vnode
790          * p3 - uniq
791          * p4 - dv
792          */
793
794         if (vno != p2) {
795             big_vno++;
796             errno = EINVAL;
797             return -1;
798         }
799
800         tmp.ih_vid = p1;
801         tmp.ih_ino = (Inode) p2;
802         ftime.dwHighDateTime = p3;
803         ftime.dwLowDateTime = p4;
804     }
805
806     namei_HandleToName(&name, &tmp);
807     p = strrchr((char *)&name.n_path, '.');
808     p++;
809     for (tag = 0; tag < NAMEI_MAXVOLS; tag++) {
810         *p = *int_to_base32(str1, tag);
811         fd = afs_open((char *)&name.n_path, O_CREAT | O_RDWR | O_TRUNC | O_EXCL, 0666);
812         if (fd == INVALID_FD) {
813             if (errno == ENOTDIR || errno == ENOENT) {
814                 if (namei_CreateDataDirectories(&name, &created_dir) == 0)
815                     fd = afs_open((char *)&name.n_path, O_CREAT | O_RDWR | O_TRUNC | O_EXCL, 0666);
816             }
817         }
818
819         if (fd != INVALID_FD)
820             break;
821         if (p2 == INODESPECIAL && p3 == VI_LINKTABLE)
822             break;
823     }
824     if (fd == INVALID_FD) {
825         code = -1;
826         goto bad;
827     }
828     tmp.ih_ino &= ~(((Inode) NAMEI_TAGMASK) << NAMEI_TAGSHIFT);
829     tmp.ih_ino |= (((Inode) tag) << NAMEI_TAGSHIFT);
830
831     if (!code) {
832         if (!SetFileTime((HANDLE) fd, &ftime, NULL, NULL)) {
833             errno = OS_ERROR(EBADF);
834             code = -1;
835         }
836     }
837
838     if (!code) {
839         if (p2 != INODESPECIAL) {
840             if (fd == INVALID_FD) {
841                 errno = ENOENT;
842                 code = nt_unlink((char *)&name.n_path);
843                 code = -1;
844                 goto bad;
845             }
846             fdP = IH_OPEN(lh);
847             if (fdP == NULL) {
848                 code = -1;
849                 goto bad;
850             }
851             code = namei_SetLinkCount(fdP, tmp.ih_ino, 1, 0);
852             FDH_CLOSE(fdP);
853         } else if (p2 == INODESPECIAL && p3 == VI_LINKTABLE) {
854             if (fd == INVALID_FD)
855                 goto bad;
856             /* hack at tmp to setup for set link count call. */
857             tfd.fd_fd = fd;
858             code = namei_SetLinkCount(&tfd, (Inode) 0, 1, 0);
859         }
860     }
861
862 bad:
863     if (fd != INVALID_FD)
864         nt_close(fd);
865
866     if (code || (fd == INVALID_FD)) {
867         if (p2 != INODESPECIAL) {
868             fdP = IH_OPEN(lh);
869             if (fdP) {
870                 namei_SetLinkCount(fdP, tmp.ih_ino, 0, 0);
871                 FDH_CLOSE(fdP);
872             }
873         }
874
875         if (created_dir) {
876             int save_errno = errno;
877             namei_RemoveDataDirectories(&name);
878             errno = save_errno;
879         }
880     }
881     return (code || (fd == INVALID_FD)) ? (Inode) -1 : tmp.ih_ino;
882 }
883 #else /* !AFS_NT40_ENV */
884 Inode
885 namei_icreate(IHandle_t * lh, char *part, afs_uint32 p1, afs_uint32 p2, afs_uint32 p3, afs_uint32 p4)
886 {
887     namei_t name;
888     int fd = INVALID_FD;
889     int code = 0;
890     int created_dir = 0;
891     IHandle_t tmp;
892     FdHandle_t *fdP;
893     FdHandle_t tfd;
894     int tag;
895     int ogm_parm;
896
897     memset((void *)&tmp, 0, sizeof(IHandle_t));
898     memset(&tfd, 0, sizeof(FdHandle_t));
899
900     tmp.ih_dev = volutil_GetPartitionID(part);
901     if (tmp.ih_dev == -1) {
902         errno = EINVAL;
903         return -1;
904     }
905
906     if (p2 == -1) {
907         /* Parameters for special file:
908          * p1 - volume id - goes into owner/group/mode
909          * p2 - vnode == -1
910          * p3 - type
911          * p4 - parent volume id
912          */
913         ogm_parm = p1;
914
915         tag = p3;
916         tmp.ih_vid = p4;        /* Use parent volume id, where this file will be. */
917         tmp.ih_ino = namei_MakeSpecIno(p1, p3);
918     } else {
919         int vno = p2 & NAMEI_VNODEMASK;
920         /* Parameters for regular file:
921          * p1 - volume id
922          * p2 - vnode
923          * p3 - uniq
924          * p4 - dv
925          */
926
927         if (vno != p2) {
928             big_vno++;
929             errno = EINVAL;
930             return -1;
931         }
932         /* If GetFreeTag succeeds, it atomically sets link count to 1. */
933         tag = GetFreeTag(lh, p2);
934         if (tag < 0)
935             goto bad;
936
937         tmp.ih_vid = p1;
938         tmp.ih_ino = (Inode) p2;
939         /* name is <uniq(p3)><tag><vno(p2)> */
940         tmp.ih_ino |= ((Inode) tag) << NAMEI_TAGSHIFT;
941         tmp.ih_ino |= ((Inode) p3) << NAMEI_UNIQSHIFT;
942
943         ogm_parm = p4;
944     }
945
946     namei_HandleToName(&name, &tmp);
947     fd = afs_open(name.n_path, O_CREAT | O_EXCL | O_TRUNC | O_RDWR, 0);
948     if (fd < 0) {
949         if (errno == ENOTDIR || errno == ENOENT) {
950             if (namei_CreateDataDirectories(&name, &created_dir) < 0)
951                 goto bad;
952             fd = afs_open(name.n_path, O_CREAT | O_EXCL | O_TRUNC | O_RDWR,
953                           0);
954             if (fd < 0)
955                 goto bad;
956         } else {
957             goto bad;
958         }
959     }
960     if (SetOGM(fd, ogm_parm, tag) < 0) {
961         close(fd);
962         fd = INVALID_FD;
963         goto bad;
964     }
965
966     if (p2 == (afs_uint32)-1 && p3 == VI_LINKTABLE) {
967         /* hack at tmp to setup for set link count call. */
968         memset((void *)&tfd, 0, sizeof(FdHandle_t));    /* minimalistic still, but a little cleaner */
969         tfd.fd_ih = &tmp;
970         tfd.fd_fd = fd;
971         code = namei_SetLinkCount(&tfd, (Inode) 0, 1, 0);
972     }
973
974   bad:
975     if (fd >= 0)
976         close(fd);
977
978
979     if (code || (fd < 0)) {
980         if (p2 != -1) {
981             fdP = IH_OPEN(lh);
982             if (fdP) {
983                 namei_SetLinkCount(fdP, tmp.ih_ino, 0, 0);
984                 FDH_CLOSE(fdP);
985             }
986         }
987     }
988     return (code || (fd < 0)) ? (Inode) - 1 : tmp.ih_ino;
989 }
990 #endif
991
992 /* namei_iopen */
993 FD_t
994 namei_iopen(IHandle_t * h)
995 {
996     FD_t fd;
997     namei_t name;
998
999     /* Convert handle to file name. */
1000     namei_HandleToName(&name, h);
1001     fd = afs_open((char *)&name.n_path, O_RDWR, 0666);
1002     return fd;
1003 }
1004
1005 /* Need to detect vol special file and just unlink. In those cases, the
1006  * handle passed in _is_ for the inode. We only check p1 for the special
1007  * files.
1008  */
1009 int
1010 namei_dec(IHandle_t * ih, Inode ino, int p1)
1011 {
1012     int count = 0;
1013     namei_t name;
1014     int code = 0;
1015     FdHandle_t *fdP;
1016
1017     if ((ino & NAMEI_INODESPECIAL) == NAMEI_INODESPECIAL) {
1018         IHandle_t *tmp;
1019         int type = (int)((ino >> NAMEI_TAGSHIFT) & NAMEI_TAGMASK);
1020
1021         /* Verify this is the right file. */
1022         IH_INIT(tmp, ih->ih_dev, ih->ih_vid, ino);
1023
1024         namei_HandleToName(&name, tmp);
1025
1026         fdP = IH_OPEN(tmp);
1027         if (fdP == NULL) {
1028             IH_RELEASE(tmp);
1029             errno = OS_ERROR(ENOENT);
1030             return -1;
1031         }
1032
1033         if (CheckOGM(&name, fdP, p1) < 0) {
1034             FDH_REALLYCLOSE(fdP);
1035             IH_RELEASE(tmp);
1036             errno = OS_ERROR(EINVAL);
1037             return -1;
1038         }
1039
1040         /* If it's the link table itself, decrement the link count. */
1041         if (type == VI_LINKTABLE) {
1042           if ((count = namei_GetLinkCount(fdP, (Inode) 0, 1, 0, 1)) < 0) {
1043                 FDH_REALLYCLOSE(fdP);
1044                 IH_RELEASE(tmp);
1045                 return -1;
1046             }
1047
1048             count--;
1049             if (namei_SetLinkCount(fdP, (Inode) 0, count < 0 ? 0 : count, 1) <
1050                 0) {
1051                 FDH_REALLYCLOSE(fdP);
1052                 IH_RELEASE(tmp);
1053                 return -1;
1054             }
1055
1056             if (count > 0) {
1057                 FDH_REALLYCLOSE(fdP);
1058                 IH_RELEASE(tmp);
1059                 return 0;
1060             }
1061         }
1062
1063         if ((code = OS_UNLINK(name.n_path)) == 0) {
1064             if (type == VI_LINKTABLE) {
1065                 /* Try to remove directory. If it fails, that's ok.
1066                  * Salvage will clean up.
1067                  */
1068                 (void)namei_RemoveDataDirectories(&name);
1069             }
1070         }
1071         FDH_REALLYCLOSE(fdP);
1072         IH_RELEASE(tmp);
1073     } else {
1074         /* Get a file descriptor handle for this Inode */
1075         fdP = IH_OPEN(ih);
1076         if (fdP == NULL) {
1077             return -1;
1078         }
1079
1080         if ((count = namei_GetLinkCount(fdP, ino, 1, 0, 1)) < 0) {
1081             FDH_REALLYCLOSE(fdP);
1082             return -1;
1083         }
1084
1085         count--;
1086         if (count >= 0) {
1087             if (namei_SetLinkCount(fdP, ino, count, 1) < 0) {
1088                 FDH_REALLYCLOSE(fdP);
1089                 return -1;
1090             }
1091         } else {
1092             IHandle_t *th;
1093             IH_INIT(th, ih->ih_dev, ih->ih_vid, ino);
1094             Log("Warning: Lost ref on ihandle dev %d vid %d ino %" AFS_INT64_FMT "\n",
1095                 th->ih_dev, th->ih_vid, (afs_int64)th->ih_ino);
1096             IH_RELEASE(th);
1097
1098             /* If we're less than 0, someone presumably unlinked;
1099                don't bother setting count to 0, but we need to drop a lock */
1100             if (namei_SetLinkCount(fdP, ino, 0, 1) < 0) {
1101                 FDH_REALLYCLOSE(fdP);
1102                 return -1;
1103             }
1104         }
1105         if (count == 0) {
1106             IHandle_t *th;
1107             IH_INIT(th, ih->ih_dev, ih->ih_vid, ino);
1108
1109             namei_HandleToName(&name, th);
1110             IH_RELEASE(th);
1111             code = OS_UNLINK(name.n_path);
1112         }
1113         FDH_CLOSE(fdP);
1114     }
1115
1116     return code;
1117 }
1118
1119 int
1120 namei_inc(IHandle_t * h, Inode ino, int p1)
1121 {
1122     int count;
1123     int code = 0;
1124     FdHandle_t *fdP;
1125
1126     if ((ino & NAMEI_INODESPECIAL) == NAMEI_INODESPECIAL) {
1127         int type = (int)((ino >> NAMEI_TAGSHIFT) & NAMEI_TAGMASK);
1128         if (type != VI_LINKTABLE)
1129             return 0;
1130         ino = (Inode) 0;
1131     }
1132
1133     /* Get a file descriptor handle for this Inode */
1134     fdP = IH_OPEN(h);
1135     if (fdP == NULL) {
1136         return -1;
1137     }
1138
1139     if ((count = namei_GetLinkCount(fdP, ino, 1, 0, 1)) < 0)
1140         code = -1;
1141     else {
1142         count++;
1143         if (count > 7) {
1144             errno = OS_ERROR(EINVAL);
1145             code = -1;
1146             count = 7;
1147         }
1148         if (namei_SetLinkCount(fdP, ino, count, 1) < 0)
1149             code = -1;
1150     }
1151     if (code) {
1152         FDH_REALLYCLOSE(fdP);
1153     } else {
1154         FDH_CLOSE(fdP);
1155     }
1156     return code;
1157 }
1158
1159 #ifndef AFS_NT40_ENV
1160 int
1161 namei_replace_file_by_hardlink(IHandle_t *hLink, IHandle_t *hTarget)
1162 {
1163     afs_int32 code;
1164     namei_t nameLink;
1165     namei_t nameTarget;
1166
1167     /* Convert handle to file name. */
1168     namei_HandleToName(&nameLink, hLink);
1169     namei_HandleToName(&nameTarget, hTarget);
1170
1171     OS_UNLINK(nameLink.n_path);
1172     code = link(nameTarget.n_path, nameLink.n_path);
1173     return code;
1174 }
1175
1176 int
1177 namei_copy_on_write(IHandle_t *h)
1178 {
1179     afs_int32 fd, code = 0;
1180     namei_t name;
1181     FdHandle_t *fdP;
1182     struct afs_stat tstat;
1183     afs_foff_t offset;
1184
1185     namei_HandleToName(&name, h);
1186     if (afs_stat(name.n_path, &tstat) < 0)
1187         return EIO;
1188     if (tstat.st_nlink > 1) {                   /* do a copy on write */
1189         char path[259];
1190         char *buf;
1191         afs_size_t size;
1192         ssize_t tlen;
1193
1194         fdP = IH_OPEN(h);
1195         if (!fdP)
1196             return EIO;
1197         afs_snprintf(path, sizeof(path), "%s-tmp", name.n_path);
1198         fd = afs_open(path, O_CREAT | O_EXCL | O_TRUNC | O_RDWR, 0);
1199         if (fd < 0) {
1200             FDH_CLOSE(fdP);
1201             return EIO;
1202         }
1203         buf = malloc(8192);
1204         if (!buf) {
1205             close(fd);
1206             OS_UNLINK(path);
1207             FDH_CLOSE(fdP);
1208             return ENOMEM;
1209         }
1210         size = tstat.st_size;
1211         offset = 0;
1212         while (size) {
1213             tlen = size > 8192 ? 8192 : size;
1214             if (FDH_PREAD(fdP, buf, tlen, offset) != tlen)
1215                 break;
1216             if (write(fd, buf, tlen) != tlen)
1217                 break;
1218             size -= tlen;
1219             offset += tlen;
1220         }
1221         close(fd);
1222         FDH_REALLYCLOSE(fdP);
1223         free(buf);
1224         if (size)
1225             code = EIO;
1226         else {
1227             OS_UNLINK(name.n_path);
1228             code = rename(path, name.n_path);
1229         }
1230     }
1231     return code;
1232 }
1233 #endif
1234
1235 /************************************************************************
1236  * File Name Structure
1237  ************************************************************************
1238  *
1239  * Each AFS file needs a unique name and it needs to be findable with
1240  * minimal lookup time. Note that the constraint on the number of files and
1241  * directories in a volume is the size of the vnode index files and the
1242  * max file size AFS supports (for internal files) of 2^31. Since a record
1243  * in the small vnode index file is 64 bytes long, we can have at most
1244  * (2^31)/64 or 33554432 files. A record in the large index file is
1245  * 256 bytes long, giving a maximum of (2^31)/256 = 8388608 directories.
1246  * Another layout parameter is that there is roughly a 16 to 1 ratio between
1247  * the number of files and the number of directories.
1248  *
1249  * Using this information we can see that a layout of 256 directories, each
1250  * with 512 subdirectories and each of those having 512 files gives us
1251  * 256*512*512 = 67108864 AFS files and directories.
1252  *
1253  * The volume, vnode, uniquifier and data version, as well as the tag
1254  * are required, either for finding the file or for salvaging. It's best to
1255  * restrict the name to something that can be mapped into 64 bits so the
1256  * "Inode" is easily comparable (using "==") to other "Inodes". The tag
1257  * is used to distinguish between different versions of the same file
1258  * which are currently in the RW and clones of a volume. See "Link Table
1259  * Organization" below for more information on the tag. The tag is
1260  * required in the name of the file to ensure a unique name.
1261  *
1262  * ifdef AFS_NT40_ENV
1263  * The data for each volume group is in a separate directory. The name of the
1264  * volume is of the form: Vol_NNNNNN.data, where NNNNNN is a base 32
1265  * representation of the RW volume ID (even where the RO is the only volume
1266  * on the partition). Below that are separate subdirectories for the
1267  * AFS directories and special files. There are also 16 directories for files,
1268  * hashed on the low 5 bits (recall bit0 is always 0) of the vnode number.
1269  * These directories are named:
1270  * A - P - 16 file directories.
1271  * Q ----- data directory
1272  * R ----- special files directory
1273  *
1274  * The vnode is hashed into the directory using the low bits of the
1275  * vnode number.
1276  *
1277  * The format of a file name for a regular file is:
1278  * Y:\Vol_NNNNNN.data\X\V_IIIIII.J
1279  * Y - partition encoded as drive letter, starting with D
1280  * NNNNNN - base 32 encoded volume number of RW volume
1281  * X - hash directory, as above
1282  * IIIIII - base 32 encoded vnode number
1283  * J - base 32 encoded tag
1284  *
1285  * uniq is stored in the dwHighDateTime creation time field
1286  * dv is stored in the dwLowDateTime creation time field
1287  *
1288  * Special inodes are always in the R directory, as above, and are
1289  * encoded:
1290  * True child volid is stored in the dwHighDateTime creation time field
1291  * vnode number is always -1 (Special)
1292  * type is the IIIIII part of the filename
1293  * uniq is the J part of the filename
1294  * parent volume id is implied in the containing directory
1295  *
1296  * else
1297  * We can store data in the uid, gid and mode bits of the files, provided
1298  * the directories have root only access. This gives us 15 bits for each
1299  * of uid and gid (GNU chown considers 65535 to mean "don't change").
1300  * There are 9 available mode bits. Adn we need to store a total of
1301  * 32 (volume id) + 26 (vnode) + 32 (uniquifier) + 32 (data-version) + 3 (tag)
1302  * or 131 bits somewhere.
1303  *
1304  * The format of a file name for a regular file is:
1305  * /vicepX/AFSIDat/V1/V2/AA/BB/<tag><uniq><vno>
1306  * V1 - low 8 bits of RW volume id
1307  * V2 - all bits of RW volume id
1308  * AA - high 8 bits of vnode number.
1309  * BB - next 9 bits of vnode number.
1310  * <tag><uniq><vno> - file name
1311  *
1312  * Volume special files are stored in a separate directory:
1313  * /vicepX/AFSIDat/V1/V2/special/<tag><uniq><vno>
1314  *
1315  *
1316  * The vnode is hashed into the directory using the high bits of the
1317  * vnode number. This is so that consecutively created vnodes are in
1318  * roughly the same area on the disk. This will at least be optimal if
1319  * the user is creating many files in the same AFS directory. The name
1320  * should be formed so that the leading characters are different as quickly
1321  * as possible, leading to faster discards of incorrect matches in the
1322  * lookup code.
1323  *
1324  * endif
1325  *
1326  */
1327
1328
1329 /************************************************************************
1330  *  Link Table Organization
1331  ************************************************************************
1332  *
1333  * The link table volume special file is used to hold the link counts that
1334  * are held in the inodes in inode based AFS vice filesystems. For user
1335  * space access, the link counts are being kept in a separate
1336  * volume special file. The file begins with the usual version stamp
1337  * information and is then followed by one row per vnode number. vnode 0
1338  * is used to hold the link count of the link table itself. That is because
1339  * the same link table is shared among all the volumes of the volume group
1340  * and is deleted only when the last volume of a volume group is deleted.
1341  *
1342  * Within each row, the columns are 3 bits wide. They can each hold a 0 based
1343  * link count from 0 through 7. Each colume represents a unique instance of
1344  * that vnode. Say we have a file shared between the RW and a RO and a
1345  * different version of the file (or a different uniquifer) for the BU volume.
1346  * Then one column would be holding the link count of 2 for the RW and RO
1347  * and a different column would hold the link count of 1 for the BU volume.
1348  * # ifdef AFS_NT40_ENV
1349  * The column used is determined for NT by the uniquifier tag applied to
1350  * generate a unique file name in the NTFS namespace. The file name is
1351  * of the form "V_<vno>.<tag>" . And the <tag> is also the column number
1352  * in the link table.
1353  * # else
1354  * Note that we allow only 5 volumes per file, giving 15 bits used in the
1355  * short.
1356  * # endif
1357  */
1358 #define LINKTABLE_WIDTH 2
1359 #define LINKTABLE_SHIFT 1       /* log 2 = 1 */
1360
1361 /**
1362  * compute namei link table file and bit offset from inode number.
1363  *
1364  * @param[in]   ino     inode number
1365  * @param[out]  offset  link table file offset
1366  * @param[out]  index   bit offset within 2-byte record
1367  *
1368  * @internal
1369  */
1370 static void
1371 namei_GetLCOffsetAndIndexFromIno(Inode ino, afs_foff_t * offset, int *index)
1372 {
1373     int toff = (int)(ino & NAMEI_VNODEMASK);
1374     int tindex = (int)((ino >> NAMEI_TAGSHIFT) & NAMEI_TAGMASK);
1375
1376     *offset = (afs_foff_t) ((toff << LINKTABLE_SHIFT) + 8);     /* * 2 + sizeof stamp */
1377     *index = (tindex << 1) + tindex;
1378 }
1379
1380 #ifdef AFS_PTHREAD_ENV
1381 /* XXX do static initializers work for WINNT/pthread? */
1382 pthread_mutex_t _namei_glc_lock = PTHREAD_MUTEX_INITIALIZER;
1383 #define NAMEI_GLC_LOCK MUTEX_ENTER(&_namei_glc_lock)
1384 #define NAMEI_GLC_UNLOCK MUTEX_EXIT(&_namei_glc_lock)
1385 #else /* !AFS_PTHREAD_ENV */
1386 #define NAMEI_GLC_LOCK
1387 #define NAMEI_GLC_UNLOCK
1388 #endif /* !AFS_PTHREAD_ENV */
1389
1390 /**
1391  * get the link count of an inode.
1392  *
1393  * @param[in]  h        namei link count table file handle
1394  * @param[in]  ino      inode number for which we are requesting a link count
1395  * @param[in]  lockit   if asserted, return with lock held on link table file
1396  * @param[in]  fixup    if asserted, write 1 to link count when read() returns
1397  *                      zero (at EOF)
1398  * @param[in]  nowrite  return success on zero byte read or ZLC
1399  *
1400  * @post if lockit asserted and lookup was successful, will return with write
1401  *       lock on link table file descriptor
1402  *
1403  * @return link count
1404  *    @retval -1 namei link table i/o error
1405  *
1406  * @internal
1407  */
1408 int
1409 namei_GetLinkCount(FdHandle_t * h, Inode ino, int lockit, int fixup, int nowrite)
1410 {
1411     unsigned short row = 0;
1412     afs_foff_t offset;
1413     ssize_t rc;
1414     int index;
1415
1416     /* there's no linktable yet. the salvager will create one later */
1417     if (h->fd_fd == INVALID_FD && fixup)
1418        return 1;
1419     namei_GetLCOffsetAndIndexFromIno(ino, &offset, &index);
1420
1421     if (lockit) {
1422         if (FDH_LOCKFILE(h, offset) != 0)
1423             return -1;
1424     }
1425
1426     rc = FDH_PREAD(h, (char*)&row, sizeof(row), offset);
1427     if ((rc == 0 || !((row >> index) & NAMEI_TAGMASK)) && fixup && nowrite)
1428         return 1;
1429     if (rc == 0 && fixup) {
1430         /*
1431          * extend link table and write a link count of 1 for ino
1432          *
1433          * in order to make MT-safe, truncation (extension really)
1434          * must happen under a mutex
1435          */
1436         NAMEI_GLC_LOCK;
1437         if (FDH_SIZE(h) >= offset+sizeof(row)) {
1438             NAMEI_GLC_UNLOCK;
1439             goto bad_getLinkByte;
1440         }
1441         FDH_TRUNC(h, offset+sizeof(row));
1442         row = 1 << index;
1443         rc = FDH_PWRITE(h, (char *)&row, sizeof(row), offset);
1444         NAMEI_GLC_UNLOCK;
1445     }
1446     if (rc != sizeof(row)) {
1447         goto bad_getLinkByte;
1448     }
1449
1450     if (fixup && !((row >> index) & NAMEI_TAGMASK)) {
1451         /*
1452          * fix up zlc
1453          *
1454          * in order to make this mt-safe, we need to do the read-modify-write
1455          * under a mutex.  thus, we repeat the read inside the lock.
1456          */
1457         NAMEI_GLC_LOCK;
1458         rc = FDH_PREAD(h, (char *)&row, sizeof(row), offset);
1459         if (rc == sizeof(row)) {
1460             row |= 1<<index;
1461             rc = FDH_PWRITE(h, (char *)&row, sizeof(row), offset);
1462         }
1463         NAMEI_GLC_UNLOCK;
1464         if (rc != sizeof(row))
1465             goto bad_getLinkByte;
1466     }
1467
1468     return (int)((row >> index) & NAMEI_TAGMASK);
1469
1470   bad_getLinkByte:
1471     if (lockit)
1472         FDH_UNLOCKFILE(h, offset);
1473     return -1;
1474 }
1475
1476 int
1477 namei_SetNonZLC(FdHandle_t * h, Inode ino)
1478 {
1479     return namei_GetLinkCount(h, ino, 0, 1, 0);
1480 }
1481
1482 /* Return a free column index for this vnode. */
1483 static int
1484 GetFreeTag(IHandle_t * ih, int vno)
1485 {
1486     FdHandle_t *fdP;
1487     afs_foff_t offset;
1488     int col;
1489     int coldata;
1490     short row;
1491     ssize_t nBytes;
1492
1493
1494     fdP = IH_OPEN(ih);
1495     if (fdP == NULL)
1496         return -1;
1497
1498     /* Only one manipulates at a time. */
1499     if (FDH_LOCKFILE(fdP, offset) != 0) {
1500         FDH_REALLYCLOSE(fdP);
1501         return -1;
1502     }
1503
1504     offset = (vno << LINKTABLE_SHIFT) + 8;      /* * 2 + sizeof stamp */
1505
1506     nBytes = FDH_PREAD(fdP, (char *)&row, sizeof(row), offset);
1507     if (nBytes != sizeof(row)) {
1508         if (nBytes != 0)
1509             goto badGetFreeTag;
1510         row = 0;
1511     }
1512
1513     /* Now find a free column in this row and claim it. */
1514     for (col = 0; col < NAMEI_MAXVOLS; col++) {
1515         coldata = 7 << (col * 3);
1516         if ((row & coldata) == 0)
1517             break;
1518     }
1519     if (col >= NAMEI_MAXVOLS) {
1520         errno = ENOSPC;
1521         goto badGetFreeTag;
1522     }
1523
1524     coldata = 1 << (col * 3);
1525     row |= coldata;
1526
1527     if (FDH_PWRITE(fdP, (char *)&row, sizeof(row), offset) != sizeof(row)) {
1528         goto badGetFreeTag;
1529     }
1530     FDH_SYNC(fdP);
1531     FDH_UNLOCKFILE(fdP, offset);
1532     FDH_REALLYCLOSE(fdP);
1533     return col;
1534
1535   badGetFreeTag:
1536     FDH_UNLOCKFILE(fdP, offset);
1537     FDH_REALLYCLOSE(fdP);
1538     return -1;
1539 }
1540
1541
1542
1543 /* namei_SetLinkCount
1544  * If locked is set, assume file is locked. Otherwise, lock file before
1545  * proceeding to modify it.
1546  */
1547 int
1548 namei_SetLinkCount(FdHandle_t * fdP, Inode ino, int count, int locked)
1549 {
1550     afs_foff_t offset;
1551     int index;
1552     unsigned short row;
1553     int bytesRead;
1554     ssize_t nBytes = -1;
1555
1556     namei_GetLCOffsetAndIndexFromIno(ino, &offset, &index);
1557
1558     if (!locked) {
1559         if (FDH_LOCKFILE(fdP, offset) != 0) {
1560             return -1;
1561         }
1562     }
1563
1564     nBytes = FDH_PREAD(fdP, (char *)&row, sizeof(row), offset);
1565     if (nBytes != sizeof(row)) {
1566         if (nBytes != 0) {
1567             errno = OS_ERROR(EBADF);
1568             goto bad_SetLinkCount;
1569         }
1570         row = 0;
1571     }
1572
1573     bytesRead = 7 << index;
1574     count <<= index;
1575     row &= (unsigned short)~bytesRead;
1576     row |= (unsigned short)count;
1577
1578     if (FDH_PWRITE(fdP, (char *)&row, sizeof(short), offset) != sizeof(short)) {
1579         errno = OS_ERROR(EBADF);
1580         goto bad_SetLinkCount;
1581     }
1582     FDH_SYNC(fdP);
1583
1584     nBytes = 0;
1585
1586
1587   bad_SetLinkCount:
1588     FDH_UNLOCKFILE(fdP, offset);
1589
1590     /* disallowed above 7, so... */
1591     return (int)nBytes;
1592 }
1593
1594
1595 /* ListViceInodes - write inode data to a results file. */
1596 static int DecodeInode(char *dpath, char *name, struct ViceInodeInfo *info,
1597                        unsigned int volid);
1598 static int DecodeVolumeName(char *name, unsigned int *vid);
1599 static int namei_ListAFSSubDirs(IHandle_t * dirIH,
1600                                 int (*write_fun) (FILE *,
1601                                                   struct ViceInodeInfo *,
1602                                                   char *, char *), FILE * fp,
1603                                 int (*judgeFun) (struct ViceInodeInfo *,
1604                                                  afs_uint32 vid, void *),
1605                                 afs_uint32 singleVolumeNumber, void *rock);
1606
1607
1608 /* WriteInodeInfo
1609  *
1610  * Write the inode data to the results file.
1611  *
1612  * Returns -2 on error, 0 on success.
1613  *
1614  * This is written as a callback simply so that other listing routines
1615  * can use the same inode reading code.
1616  */
1617 static int
1618 WriteInodeInfo(FILE * fp, struct ViceInodeInfo *info, char *dir, char *name)
1619 {
1620     size_t n;
1621     n = fwrite(info, sizeof(*info), 1, fp);
1622     return (n == 1) ? 0 : -2;
1623 }
1624
1625
1626 int mode_errors;                /* Number of errors found in mode bits on directories. */
1627 void
1628 VerifyDirPerms(char *path)
1629 {
1630     struct afs_stat status;
1631
1632     if (afs_stat(path, &status) < 0) {
1633         Log("Unable to stat %s. Please manually verify mode bits for this"
1634             " directory\n", path);
1635     } else {
1636         if (((status.st_mode & 0777) != 0700) || (status.st_uid != 0))
1637             mode_errors++;
1638     }
1639 }
1640
1641 /**
1642  * Fill the results file with the requested inode information.
1643  *
1644  * This code optimizes single volume salvages by just looking at that one
1645  * volume's directory.
1646  *
1647  * @param[in]   devname             device name string
1648  * @param[in]   moutnedOn           vice partition mount point
1649  * @param[in]   resultFile          result file in which to write inode
1650  *                                  metadata.  If NULL, write routine is not
1651  *                                  called.
1652  * @param[in]   judgeInode          filter function pointer.  if not NULL, only
1653  *                                  inodes for which this routine returns non-
1654  *                                  zero will be written to the results file.
1655  * @param[in]   singleVolumeNumber  volume id filter
1656  * @param[out]  forcep              always set to 0 for namei impl
1657  * @param[in]   forceR              not used by namei impl
1658  * @param[in]   wpath               not used by namei impl
1659  * @param[in]   rock                opaque pointer passed to judgeInode
1660  *
1661  * @return operation status
1662  *    @retval 0   success
1663  *    @retval -1  complete failure, salvage should terminate.
1664  *    @retval -2  not enough space on partition, salvager has error message
1665  *                for this.
1666  */
1667 int
1668 ListViceInodes(char *devname, char *mountedOn, FILE *inodeFile,
1669                int (*judgeInode) (struct ViceInodeInfo * info, afs_uint32 vid, void *rock),
1670                afs_uint32 singleVolumeNumber, int *forcep, int forceR, char *wpath,
1671                void *rock)
1672 {
1673     int ninodes;
1674     struct afs_stat status;
1675
1676     *forcep = 0; /* no need to salvage until further notice */
1677
1678     /* Verify protections on directories. */
1679     mode_errors = 0;
1680     VerifyDirPerms(mountedOn);
1681
1682     ninodes =
1683         namei_ListAFSFiles(mountedOn, WriteInodeInfo, inodeFile, judgeInode,
1684                            singleVolumeNumber, rock);
1685
1686     if (!inodeFile)
1687         return ninodes;
1688
1689     if (ninodes < 0) {
1690         return ninodes;
1691     }
1692
1693     if (fflush(inodeFile) == EOF) {
1694         Log("Unable to successfully flush inode file for %s\n", mountedOn);
1695         return -2;
1696     }
1697     if (fsync(fileno(inodeFile)) == -1) {
1698         Log("Unable to successfully fsync inode file for %s\n", mountedOn);
1699         return -2;
1700     }
1701
1702     /*
1703      * Paranoia:  check that the file is really the right size
1704      */
1705     if (afs_fstat(fileno(inodeFile), &status) == -1) {
1706         Log("Unable to successfully stat inode file for %s\n", mountedOn);
1707         return -2;
1708     }
1709     if (status.st_size != ninodes * sizeof(struct ViceInodeInfo)) {
1710         Log("Wrong size (%d instead of %lu) in inode file for %s\n",
1711             (int) status.st_size,
1712             (long unsigned int) ninodes * sizeof(struct ViceInodeInfo),
1713             mountedOn);
1714         return -2;
1715     }
1716     return 0;
1717 }
1718
1719
1720 /**
1721  * Collect all the matching AFS files on the drive.
1722  * If singleVolumeNumber is non-zero, just return files for that volume.
1723  *
1724  * @param[in] dev                 vice partition path
1725  * @param[in] writeFun            function pointer to a function which
1726  *                                writes inode information to FILE fp
1727  * @param[in] fp                  file stream where inode metadata is sent
1728  * @param[in] judgeFun            filter function pointer.  if not NULL,
1729  *                                only entries for which a non-zero value
1730  *                                is returned are written to fp
1731  * @param[in] singleVolumeNumber  volume id filter.  if nonzero, only
1732  *                                process files for that specific volume id
1733  * @param[in] rock                opaque pointer passed into writeFun and
1734  *                                judgeFun
1735  *
1736  * @return operation status
1737  *    @retval <0 error
1738  *    @retval >=0 number of matching files found
1739  */
1740 int
1741 namei_ListAFSFiles(char *dev,
1742                    int (*writeFun) (FILE *, struct ViceInodeInfo *, char *,
1743                                     char *),
1744                    FILE * fp,
1745                    int (*judgeFun) (struct ViceInodeInfo *, afs_uint32, void *),
1746                    afs_uint32 singleVolumeNumber, void *rock)
1747 {
1748     IHandle_t ih;
1749     namei_t name;
1750     int ninodes = 0;
1751     DIR *dirp1;
1752     struct dirent *dp1;
1753 #ifndef AFS_NT40_ENV
1754     DIR *dirp2;
1755     struct dirent *dp2;
1756     char path2[512];
1757 #endif
1758 #ifdef DELETE_ZLC
1759     static void FreeZLCList(void);
1760 #endif
1761
1762     memset((void *)&ih, 0, sizeof(IHandle_t));
1763 #ifdef AFS_NT40_ENV
1764     ih.ih_dev = nt_DriveToDev(dev);
1765 #else
1766     ih.ih_dev = volutil_GetPartitionID(dev);
1767 #endif
1768
1769     if (singleVolumeNumber) {
1770         ih.ih_vid = singleVolumeNumber;
1771         namei_HandleToVolDir(&name, &ih);
1772         ninodes =
1773             namei_ListAFSSubDirs(&ih, writeFun, fp, judgeFun,
1774                                  singleVolumeNumber, rock);
1775         if (ninodes < 0)
1776             return ninodes;
1777     } else {
1778         /* Find all volume data directories and descend through them. */
1779         namei_HandleToInodeDir(&name, &ih);
1780         ninodes = 0;
1781         dirp1 = opendir(name.n_path);
1782         if (!dirp1)
1783             return 0;
1784         while ((dp1 = readdir(dirp1))) {
1785 #ifdef AFS_NT40_ENV
1786             /* Heirarchy is one level on Windows */
1787             if (!DecodeVolumeName(dp1->d_name, &ih.ih_vid)) {
1788                 ninodes +=
1789                     namei_ListAFSSubDirs(&ih, writeFun, fp, judgeFun,
1790                                          0, rock);
1791             }
1792 #else
1793             if (*dp1->d_name == '.')
1794                 continue;
1795             afs_snprintf(path2, sizeof(path2), "%s" OS_DIRSEP "%s", name.n_path,
1796                          dp1->d_name);
1797             dirp2 = opendir(path2);
1798             if (dirp2) {
1799                 while ((dp2 = readdir(dirp2))) {
1800                     if (*dp2->d_name == '.')
1801                         continue;
1802                     if (!DecodeVolumeName(dp2->d_name, &ih.ih_vid)) {
1803                         ninodes +=
1804                             namei_ListAFSSubDirs(&ih, writeFun, fp, judgeFun,
1805                                                  0, rock);
1806                     }
1807                 }
1808                 closedir(dirp2);
1809             }
1810 #endif
1811         }
1812         closedir(dirp1);
1813     }
1814 #ifdef DELETE_ZLC
1815     FreeZLCList();
1816 #endif
1817     return ninodes;
1818 }
1819
1820 #ifdef DELETE_ZLC
1821 static void AddToZLCDeleteList(char dir, char *name);
1822 static void DeleteZLCFiles(char *path);
1823 #endif
1824
1825 /**
1826  * examine a namei volume special file.
1827  *
1828  * @param[in] path1               volume special directory path
1829  * @param[in] dname               directory entry name
1830  * @param[in] myIH                inode handle to volume directory
1831  * @param[out] linkHandle         namei link count fd handle.  if
1832  *                                the inode in question is the link
1833  *                                table, then the FdHandle is populated
1834  * @param[in] writeFun            metadata write function pointer
1835  * @param[in] fp                  file pointer where inode metadata
1836  *                                is written by (*writeFun)()
1837  * @param[in] judgeFun            inode filter function pointer.  if
1838  *                                not NULL, only inodes for which this
1839  *                                function returns non-zero are recorded
1840  *                                into fp by writeFun
1841  * @param[in] singleVolumeNumer   volume id filter.  if non-zero, only
1842  *                                inodes associated with this volume id
1843  *                                are recorded by writeFun
1844  * @param[in] rock                opaque pointer passed to writeFun and
1845  *                                judgeFun
1846  *
1847  * @return operation status
1848  *    @retval 1 count this inode
1849  *    @retval 0 don't count this inode
1850  *    @retval -1 failure
1851  *
1852  * @internal
1853  */
1854 static int
1855 _namei_examine_special(char * path1,
1856                        char * dname,
1857                        IHandle_t * myIH,
1858                        FdHandle_t * linkHandle,
1859                        int (*writeFun) (FILE *, struct ViceInodeInfo *, char *,
1860                                         char *),
1861                        FILE * fp,
1862                        int (*judgeFun) (struct ViceInodeInfo *, afs_uint32, void *),
1863                        int singleVolumeNumber,
1864                        void *rock)
1865 {
1866     int ret = 0;
1867     struct ViceInodeInfo info;
1868     afs_uint32 inode_vgid;
1869
1870     if (DecodeInode(path1, dname, &info, myIH->ih_vid) < 0) {
1871         ret = 0;
1872         goto error;
1873     }
1874
1875 #ifdef AFS_NT40_ENV
1876     inode_vgid = myIH->ih_vid;
1877 #else
1878     inode_vgid = (info.inodeNumber >> NAMEI_UNIQSHIFT) & NAMEI_UNIQMASK;
1879 #endif
1880
1881     if (info.u.param[2] != VI_LINKTABLE) {
1882         info.linkCount = 1;
1883     } else if ((info.u.param[0] != myIH->ih_vid) ||
1884                (inode_vgid != myIH->ih_vid)) {
1885         /* VGID encoded in linktable filename and/or OGM data isn't
1886          * consistent with VGID encoded in namei path */
1887         Log("namei_ListAFSSubDirs: warning: inconsistent linktable "
1888             "filename \"%s" OS_DIRSEP "%s\"; salvager will delete it "
1889             "(dir_vgid=%u, inode_vgid=%u, ogm_vgid=%u)\n",
1890             path1, dname, myIH->ih_vid,
1891             (unsigned int)inode_vgid,
1892             info.u.param[0]);
1893     } else {
1894         char path2[512];
1895         /* Open this handle */
1896         (void)afs_snprintf(path2, sizeof(path2),
1897                            "%s" OS_DIRSEP "%s", path1, dname);
1898         linkHandle->fd_fd = afs_open(path2, Testing ? O_RDONLY : O_RDWR, 0666);
1899         info.linkCount =
1900             namei_GetLinkCount(linkHandle, (Inode) 0, 1, 1, Testing);
1901     }
1902
1903     if (!judgeFun ||
1904         (*judgeFun) (&info, singleVolumeNumber, rock)) {
1905         ret = 1;
1906         if ((*writeFun) (fp, &info, path1, dname) < 0) {
1907             ret = -1;
1908         }
1909     }
1910
1911  error:
1912     return ret;
1913 }
1914
1915 /**
1916  * examine a namei file.
1917  *
1918  * @param[in] path3               volume special directory path
1919  * @param[in] dname               directory entry name
1920  * @param[in] myIH                inode handle to volume directory
1921  * @param[in] linkHandle          namei link count fd handle.
1922  * @param[in] writeFun            metadata write function pointer
1923  * @param[in] fp                  file pointer where inode metadata
1924  *                                is written by (*writeFun)()
1925  * @param[in] judgeFun            inode filter function pointer.  if
1926  *                                not NULL, only inodes for which this
1927  *                                function returns non-zero are recorded
1928  *                                into fp by writeFun
1929  * @param[in] singleVolumeNumer   volume id filter.  if non-zero, only
1930  *                                inodes associated with this volume id
1931  *                                are recorded by writeFun
1932  * @param[in] rock                opaque pointer passed to writeFun and
1933  *                                judgeFun
1934  *
1935  * @return operation status
1936  *    @retval 1 count this inode
1937  *    @retval 0 don't count this inode
1938  *    @retval -1 failure
1939  *    @retval -2 request ZLC delete
1940  *
1941  * @internal
1942  */
1943 static int
1944 _namei_examine_reg(char * path3,
1945                    char * dname,
1946                    IHandle_t * myIH,
1947                    FdHandle_t * linkHandle,
1948                    int (*writeFun) (FILE *, struct ViceInodeInfo *, char *,
1949                                     char *),
1950                    FILE * fp,
1951                    int (*judgeFun) (struct ViceInodeInfo *, afs_uint32, void *),
1952                    int singleVolumeNumber,
1953                    void *rock)
1954 {
1955     int ret = 0;
1956     struct ViceInodeInfo info;
1957 #ifdef DELETE_ZLC
1958     int dirl; /* Windows-only (one level hash dir) */
1959 #endif
1960
1961     if (DecodeInode(path3, dname, &info, myIH->ih_vid) < 0) {
1962         goto error;
1963     }
1964
1965     info.linkCount =
1966         namei_GetLinkCount(linkHandle,
1967                             info.inodeNumber, 1, 1, Testing);
1968     if (info.linkCount == 0) {
1969 #ifdef DELETE_ZLC
1970         Log("Found 0 link count file %s" OS_DIRSEP "%s, deleting it.\n", path3, dname);
1971 #ifdef AFS_SALSRV_ENV
1972         /* defer -- the AddToZLCDeleteList() interface is not MT-safe */
1973         ret = -2;
1974 #else /* !AFS_SALSRV_ENV */
1975         dirl = path3[strlen(path3)-1];
1976         AddToZLCDeleteList((char)dirl, dname);
1977 #endif /* !AFS_SALSRV_ENV */
1978 #else /* !DELETE_ZLC */
1979         Log("Found 0 link count file %s" OS_DIRSEP "%s.\n", path3,
1980             dname);
1981 #endif
1982         goto error;
1983     }
1984
1985     if (!judgeFun ||
1986         (*judgeFun) (&info, singleVolumeNumber, rock)) {
1987         ret = 1;
1988         if ((*writeFun) (fp, &info, path3, dname) < 0) {
1989             ret = -1;
1990         }
1991     }
1992
1993  error:
1994     return ret;
1995 }
1996
1997 /**
1998  * listsubdirs work queue node.
1999  */
2000 struct listsubdirs_work_node {
2001 #ifdef AFS_SALSRV_ENV
2002     int *error;                         /**< *error set if an error was
2003                                          *   encountered in any listsubdirs
2004                                          *   thread. */
2005 #endif
2006
2007     IHandle_t * IH;                     /**< volume directory handle */
2008     FdHandle_t *linkHandle;             /**< namei link count fd handle. when
2009                                          *   examinining the link table special
2010                                          *   inode, this will be pointed at the
2011                                          *   link table
2012                                          */
2013     FILE * fp;                          /**< file pointer for writeFun */
2014
2015     /** function which will write inode metadata to fp */
2016     int (*writeFun) (FILE *, struct ViceInodeInfo *, char *, char *);
2017
2018     /** inode filter function */
2019     int (*judgeFun) (struct ViceInodeInfo *, afs_uint32, void *);
2020     int singleVolumeNumber;             /**< volume id filter */
2021     void * rock;                        /**< pointer passed to writeFun and judgeFun */
2022     int code;                           /**< return code from examine function */
2023     int special;                        /**< asserted when this is a volume
2024                                          *   special file */
2025 };
2026
2027 /**
2028  * simple wrapper around _namei_examine_special and _namei_examine_reg.
2029  *
2030  * @param[in] work  the struct listsubdirs_work_node for the associated
2031  *                  "list subdirs" job
2032  * @param[in] dir   the directory to examine
2033  * @param[in] filename  the filename in 'dir' to examine
2034  *
2035  * @return operation status
2036  *   @retval 1  count this inode
2037  *   @retval 0  don't count this inode
2038  *   @retval -1 failure
2039  */
2040 static_inline int
2041 _namei_examine_file(const struct listsubdirs_work_node *work, char *dir,
2042                     char *filename)
2043 {
2044     if (work->special) {
2045         return _namei_examine_special(dir, filename, work->IH,
2046                                       work->linkHandle, work->writeFun, work->fp,
2047                                       work->judgeFun, work->singleVolumeNumber,
2048                                       work->rock);
2049     } else {
2050         return _namei_examine_reg(dir, filename, work->IH,
2051                                   work->linkHandle, work->writeFun, work->fp,
2052                                   work->judgeFun, work->singleVolumeNumber,
2053                                   work->rock);
2054     }
2055 }
2056
2057
2058 #ifdef AFS_SALSRV_ENV
2059 /** @addtogroup afs_vol_salsrv_pario */
2060 /*@{*/
2061
2062 /**
2063  * arguments for the _namei_examine_file_cbk callback function.
2064  */
2065 struct listsubdirs_args {
2066     const struct listsubdirs_work_node *work; /**< arguments that are the same
2067                                                *   for all invocations of
2068                                                *   _namei_examine_file_cbk, in
2069                                                *   threads */
2070     int *result;        /**< where we can store the return code of _namei_examine_file */
2071
2072     char dir[512];      /**< directory to examine */
2073     char filename[256]; /**< filename in 'dir' to examine */
2074 };
2075
2076 /**
2077  * a node in the list of results of listsubdir jobs.
2078  */
2079 struct listsubdirs_result {
2080     struct rx_queue q;
2081     int inodes;        /**< return value from _namei_examine_file */
2082 };
2083
2084 /**
2085  * clean up a list of 'struct listsubdirs_result's and interpret the results.
2086  *
2087  * @param[in] resultlist  a list of 'struct listsubdirs_result's
2088  *
2089  * @return number of inodes found
2090  *   @retval -1  error
2091  */
2092 static int
2093 _namei_listsubdirs_cleanup_results(struct rx_queue *resultlist)
2094 {
2095     struct listsubdirs_result *res, *nres;
2096     int ret = 0;
2097
2098     for(queue_Scan(resultlist, res, nres, listsubdirs_result)) {
2099         if (ret < 0) {
2100             /* noop, retain erroneous error code */
2101         } else if (res->inodes < 0) {
2102             ret = -1;
2103         } else {
2104             ret += res->inodes;
2105         }
2106
2107         queue_Remove(res);
2108         free(res);
2109         res = NULL;
2110     }
2111
2112     return ret;
2113 }
2114
2115 /**
2116  * wait for the spawned listsubdirs jobs to finish, and return how many inodes
2117  * they found.
2118  *
2119  * @param[in] queue    queue to wait to finish
2120  * @param[in] resultlist list of 'struct listsubdirs_result's that the queued
2121  *                       jobs are storing their results in
2122  *
2123  * @return number of inodes found
2124  *   @retval -1  error
2125  */
2126 static int
2127 _namei_listsubdirs_wait(struct afs_work_queue *queue, struct rx_queue *resultlist)
2128 {
2129     int code;
2130
2131     code = afs_wq_wait_all(queue);
2132     if (code) {
2133         return -1;
2134     }
2135
2136     return _namei_listsubdirs_cleanup_results(resultlist);
2137 }
2138
2139 /**
2140  * work queue entry point for examining namei files.
2141  *
2142  * @param[in] queue        pointer to struct Vwork_queue
2143  * @param[in] node         pointer to struct Vwork_queue_node
2144  * @param[in] queue_rock   opaque pointer to struct salsrv_pool_state
2145  * @param[in] node_rock    opaque pointer to struct listsubdirs_work_node
2146  * @param[in] caller_rock  opaque pointer to struct salsrv_worker_thread_state
2147  *
2148  * @return operation status
2149  *
2150  * @see Vwork_queue_callback_func_t
2151  *
2152  * @internal
2153  */
2154 static int
2155 _namei_examine_file_cbk(struct afs_work_queue *queue,
2156                         struct afs_work_queue_node *node,
2157                         void *queue_rock,
2158                         void *node_rock,
2159                         void *caller_rock)
2160 {
2161     int code;
2162     struct listsubdirs_args *args = node_rock;
2163     const struct listsubdirs_work_node * work = args->work;
2164     char *dir = args->dir;
2165     char *filename = args->filename;
2166
2167     code = _namei_examine_file(work, dir, filename);
2168
2169     *(args->result) = code;
2170
2171     if (code < 0) {
2172         *(work->error) = 1;
2173         /* we've errored, so no point in letting more jobs continue */
2174         afs_wq_shutdown(queue);
2175     }
2176
2177     return 0;
2178 }
2179
2180 static pthread_once_t wq_once = PTHREAD_ONCE_INIT;
2181 static pthread_key_t wq_key;
2182
2183 /**
2184  * create the wq_key key for storing a work queue.
2185  */
2186 static void
2187 _namei_wq_keycreate(void)
2188 {
2189     osi_Assert(pthread_key_create(&wq_key, NULL) == 0);
2190 }
2191
2192 /**
2193  * set the work queue for this thread to use for backgrounding namei ops.
2194  *
2195  * The work queue will be used in ListAFSSubdirs (called indirectly by
2196  * ListViceInodes) to examine files in parallel.
2197  *
2198  * @param[in] wq  the work queue to use
2199  */
2200 void
2201 namei_SetWorkQueue(struct afs_work_queue *wq)
2202 {
2203     osi_Assert(pthread_once(&wq_once, _namei_wq_keycreate) == 0);
2204
2205     osi_Assert(pthread_setspecific(wq_key, wq) == 0);
2206 }
2207
2208 /**
2209  * enqueue an examine file work unit.
2210  *
2211  * @param[in] work     the _namei_examine_file arguments that are common to
2212  *                     all callers within the same ListAFSFiles operation
2213  * @param[in] dir      the specific directory to look at (string will be
2214  *                     copied; can be stack/temporary memory)
2215  * @param[in] filename the filename to look at (string will be copied; can be
2216  *                     stack/temporary memory)
2217  * @param[in] wq       work queue to enqueue this work unit to
2218  * @param[in] resultlist the list to append the 'struct listsubdirs_result' to
2219  *                       for the enqueued work unit
2220  *
2221  * @return operation status
2222  *    @retval 0 success
2223  *    @retval -1 fatal error
2224  *
2225  * @note errors MUST be indicated by a -1 error code and nothing else, to be
2226  *       compatible with _namei_examine_reg and _namei_examine_special
2227  *
2228  * @internal
2229  */
2230 static int
2231 _namei_examine_file_spawn(const struct listsubdirs_work_node *work,
2232                           const char *dir, const char *filename,
2233                           struct afs_work_queue *wq,
2234                           struct rx_queue *resultlist)
2235 {
2236     int code, ret = 0;
2237     struct listsubdirs_args *args = NULL;
2238     struct listsubdirs_result *result = NULL;
2239     struct afs_work_queue_node *node = NULL;
2240     struct afs_work_queue_add_opts opts;
2241
2242     args = malloc(sizeof(*args));
2243     if (args == NULL) {
2244         ret = -1;
2245         goto error;
2246     }
2247
2248     result = malloc(sizeof(*result));
2249     if (result == NULL) {
2250         ret = -1;
2251         goto error;
2252     }
2253
2254     code = afs_wq_node_alloc(&node);
2255     if (code) {
2256         ret = -1;
2257         goto error;
2258     }
2259     code = afs_wq_node_set_detached(node);
2260     if (code) {
2261         ret = -1;
2262         goto error;
2263     }
2264
2265     args->work = work;
2266     args->result = &result->inodes;
2267     strlcpy(args->dir, dir, sizeof(args->dir));
2268     strlcpy(args->filename, filename, sizeof(args->filename));
2269
2270     code = afs_wq_node_set_callback(node,
2271                                          &_namei_examine_file_cbk,
2272                                          args, &free);
2273     if (code) {
2274         ret = -1;
2275         goto error;
2276     }
2277     args = NULL;
2278
2279     afs_wq_add_opts_init(&opts);
2280     opts.donate = 1;
2281
2282     code = afs_wq_add(wq, node, &opts);
2283     if (code) {
2284         ret = -1;
2285         goto error;
2286     }
2287     node = NULL;
2288
2289     queue_Append(resultlist, result);
2290     result = NULL;
2291
2292  error:
2293     if (node) {
2294         afs_wq_node_put(node);
2295         node = NULL;
2296     }
2297     if (args) {
2298         free(args);
2299         args = NULL;
2300     }
2301     if (result) {
2302         free(result);
2303         result = NULL;
2304     }
2305
2306     return ret;
2307 }
2308
2309 /*@}*/
2310 #else /* !AFS_SALSRV_ENV */
2311 # define _namei_examine_file_spawn(work, dir, file, wq, resultlist) \
2312          _namei_examine_file(work, dir, file)
2313 #endif /* !AFS_SALSRV_ENV */
2314
2315 /**
2316  * traverse and check inodes.
2317  *
2318  * @param[in] dirIH               volume group directory handle
2319  * @param[in] writeFun            function pointer which will write inode
2320  *                                metadata to FILE stream fp
2321  * @param[in] fp                  file stream where inode metadata gets
2322  *                                written
2323  * @param[in] judgeFun            inode filter function.  if not NULL, only
2324  *                                inodes for which the filter returns non-zero
2325  *                                will be written out by writeFun
2326  * @param[in] singleVolumeNumber  volume id filter.  only inodes matching this
2327  *                                filter are written out by writeFun
2328  * @param[in] rock                opaque pointer passed to judgeFun and writeFun
2329  *
2330  * @return operation status
2331  *    @retval <0 error
2332  *    @retval >=0 number of matching inodes found
2333  *
2334  * @todo the salsrv implementation may consume a lot of
2335  *       memory for a large volume.  at some point we should
2336  *       probably write a background thread to asynchronously
2337  *       clean up the resultlist nodes to reduce memory footprint
2338  *
2339  * @internal
2340  */
2341 static int
2342 namei_ListAFSSubDirs(IHandle_t * dirIH,
2343                      int (*writeFun) (FILE *, struct ViceInodeInfo *, char *,
2344                                       char *),
2345                      FILE * fp,
2346                      int (*judgeFun) (struct ViceInodeInfo *, afs_uint32, void *),
2347                      afs_uint32 singleVolumeNumber, void *rock)
2348 {
2349     int code = 0, ret = 0;
2350     IHandle_t myIH = *dirIH;
2351     namei_t name;
2352     char path1[512], path3[512];
2353     DIR *dirp1, *dirp3;
2354 #ifndef AFS_NT40_ENV
2355     DIR *dirp2;
2356     struct dirent *dp2;
2357     char path2[512];
2358 #endif
2359     struct dirent *dp1, *dp3;
2360     FdHandle_t linkHandle;
2361     int ninodes = 0;
2362     struct listsubdirs_work_node work;
2363 #ifdef AFS_SALSRV_ENV
2364     int error = 0;
2365     struct afs_work_queue *wq;
2366     int wq_up = 0;
2367     struct rx_queue resultlist;
2368 #endif
2369
2370     namei_HandleToVolDir(&name, &myIH);
2371     strlcpy(path1, name.n_path, sizeof(path1));
2372
2373     /* Do the directory containing the special files first to pick up link
2374      * counts.
2375      */
2376     (void)strcat(path1, OS_DIRSEP);
2377     (void)strcat(path1, NAMEI_SPECDIR);
2378
2379     linkHandle.fd_fd = INVALID_FD;
2380 #ifdef AFS_SALSRV_ENV
2381     osi_Assert(pthread_once(&wq_once, _namei_wq_keycreate) == 0);
2382
2383     wq = pthread_getspecific(wq_key);
2384     if (!wq) {
2385         ret = -1;
2386         goto error;
2387     }
2388     wq_up = 1;
2389     queue_Init(&resultlist);
2390 #endif
2391
2392     memset(&work, 0, sizeof(work));
2393     work.linkHandle = &linkHandle;
2394     work.IH = &myIH;
2395     work.fp = fp;
2396     work.writeFun = writeFun;
2397     work.judgeFun = judgeFun;
2398     work.singleVolumeNumber = singleVolumeNumber;
2399     work.rock = rock;
2400     work.special = 1;
2401 #ifdef AFS_SALSRV_ENV
2402     work.error = &error;
2403 #endif
2404
2405     dirp1 = opendir(path1);
2406     if (dirp1) {
2407         while ((dp1 = readdir(dirp1))) {
2408             if (*dp1->d_name == '.')
2409                 continue;
2410
2411 #ifdef AFS_SALSRV_ENV
2412             if (error) {
2413                 closedir(dirp1);
2414                 ret = -1;
2415                 goto error;
2416             }
2417 #endif /* AFS_SALSRV_ENV */
2418
2419             code = _namei_examine_file_spawn(&work, path1, dp1->d_name, wq, &resultlist);
2420
2421             switch (code) {
2422             case -1:
2423                 /* fatal error */
2424                 closedir(dirp1);
2425                 ret = -1;
2426                 goto error;
2427
2428             case 1:
2429                 /* count this inode */
2430 #ifndef AFS_SALSRV_ENV
2431                 ninodes++;
2432 #endif
2433                 break;
2434             }
2435         }
2436         closedir(dirp1);
2437     }
2438
2439 #ifdef AFS_SALSRV_ENV
2440     /* effectively a barrier */
2441     code = _namei_listsubdirs_wait(wq, &resultlist);
2442     if (code < 0 || error) {
2443         ret = -1;
2444         goto error;
2445     }
2446     error = 0;
2447     ninodes += code;
2448 #endif
2449
2450     if (linkHandle.fd_fd == INVALID_FD) {
2451         Log("namei_ListAFSSubDirs: warning: VG %u does not have a link table; "
2452             "salvager will recreate it.\n", dirIH->ih_vid);
2453     }
2454
2455     /* Now run through all the other subdirs */
2456     namei_HandleToVolDir(&name, &myIH);
2457     strlcpy(path1, name.n_path, sizeof(path1));
2458
2459     work.special = 0;
2460
2461     dirp1 = opendir(path1);
2462     if (dirp1) {
2463         while ((dp1 = readdir(dirp1))) {
2464 #ifndef AFS_NT40_ENV
2465             if (*dp1->d_name == '.')
2466                 continue;
2467 #endif
2468             if (!strcmp(dp1->d_name, NAMEI_SPECDIR))
2469                 continue;
2470
2471 #ifndef AFS_NT40_ENV /* This level missing on Windows */
2472             /* Now we've got a next level subdir. */
2473             afs_snprintf(path2, sizeof(path2), "%s" OS_DIRSEP "%s", path1, dp1->d_name);
2474             dirp2 = opendir(path2);
2475             if (dirp2) {
2476                 while ((dp2 = readdir(dirp2))) {
2477                     if (*dp2->d_name == '.')
2478                         continue;
2479
2480                     /* Now we've got to the actual data */
2481                     afs_snprintf(path3, sizeof(path3), "%s" OS_DIRSEP "%s", path2,
2482                                  dp2->d_name);
2483 #else
2484                     /* Now we've got to the actual data */
2485                     afs_snprintf(path3, sizeof(path3), "%s" OS_DIRSEP "%s", path1,
2486                                  dp1->d_name);
2487 #endif
2488                     dirp3 = opendir(path3);
2489                     if (dirp3) {
2490                         while ((dp3 = readdir(dirp3))) {
2491 #ifndef AFS_NT40_ENV
2492                             if (*dp3->d_name == '.')
2493                                 continue;
2494 #endif
2495
2496 #ifdef AFS_SALSRV_ENV
2497                             if (error) {
2498                                 closedir(dirp3);
2499 #ifndef AFS_NT40_ENV
2500                                 closedir(dirp2);
2501 #endif
2502                                 closedir(dirp1);
2503                                 ret = -1;
2504                                 goto error;
2505                             }
2506 #endif /* AFS_SALSRV_ENV */
2507
2508                             code = _namei_examine_file_spawn(&work, path3,
2509                                                              dp3->d_name, wq,
2510                                                              &resultlist);
2511
2512                             switch (code) {
2513                             case -1:
2514                                 closedir(dirp3);
2515 #ifndef AFS_NT40_ENV
2516                                 closedir(dirp2);
2517 #endif
2518                                 closedir(dirp1);
2519                                 ret = -1;
2520                                 goto error;
2521
2522                             case 1:
2523 #ifndef AFS_SALSRV_ENV
2524                                 ninodes++;
2525 #endif
2526                                 break;
2527                             }
2528                         }
2529                         closedir(dirp3);
2530                     }
2531 #ifndef AFS_NT40_ENV /* This level missing on Windows */
2532                 }
2533                 closedir(dirp2);
2534             }
2535 #endif
2536         }
2537         closedir(dirp1);
2538     }
2539
2540 #ifdef AFS_SALSRV_ENV
2541     /* effectively a barrier */
2542     code = _namei_listsubdirs_wait(wq, &resultlist);
2543     if (code < 0 || error) {
2544         ret = -1;
2545         goto error;
2546     }
2547     error = 0;
2548     ninodes += code;
2549     wq_up = 0;
2550 #endif
2551
2552     if (!ninodes) {
2553         /* Then why does this directory exist? Blow it away. */
2554         namei_HandleToVolDir(&name, dirIH);
2555         namei_RemoveDataDirectories(&name);
2556     }
2557
2558  error:
2559 #ifdef AFS_SALSRV_ENV
2560     if (wq_up) {
2561         afs_wq_wait_all(wq);
2562     }
2563     _namei_listsubdirs_cleanup_results(&resultlist);
2564 #endif
2565     if (linkHandle.fd_fd != INVALID_FD)
2566         OS_CLOSE(linkHandle.fd_fd);
2567
2568     if (!ret) {
2569         ret = ninodes;
2570     }
2571     return ret;
2572 }
2573
2574 /*@}*/
2575
2576 #ifdef AFS_NT40_ENV
2577 static int
2578 DecodeVolumeName(char *name, unsigned int *vid)
2579 {
2580     /* Name begins with "Vol_" and ends with .data.  See nt_HandleToVolDir() */
2581     char stmp[32];
2582     size_t len;
2583
2584     len = strlen(name);
2585     if (len <= 9)
2586         return -1;
2587     if (strncmp(name, "Vol_", 4))
2588         return -1;
2589     if (strcmp(name + len - 5, ".data"))
2590         return -1;
2591     strcpy(stmp, name);
2592     stmp[len - 5] = '\0';
2593     *vid = base32_to_int(stmp + 4);
2594     return 0;
2595 }
2596 #else
2597 static int
2598 DecodeVolumeName(char *name, unsigned int *vid)
2599 {
2600     if (strlen(name) < 1)
2601         return -1;
2602     *vid = (unsigned int)flipbase64_to_int64(name);
2603     return 0;
2604 }
2605 #endif
2606
2607
2608 /* DecodeInode
2609  *
2610  * Get the inode number from the name.
2611  *
2612  */
2613 #ifdef AFS_NT40_ENV
2614 static int
2615 DecodeInode(char *dpath, char *name, struct ViceInodeInfo *info,
2616             unsigned int volid)
2617 {
2618     char fpath[512];
2619     int tag, vno;
2620     WIN32_FIND_DATA data;
2621     HANDLE dirH;
2622     char *s, *t;
2623     char stmp[16];
2624     FdHandle_t linkHandle;
2625     char dirl;
2626
2627     afs_snprintf(fpath, sizeof(fpath), "%s" OS_DIRSEP "%s", dpath, name);
2628
2629     dirH = FindFirstFileEx(fpath, FindExInfoStandard, &data,
2630                            FindExSearchNameMatch, NULL,
2631                            FIND_FIRST_EX_CASE_SENSITIVE);
2632     if (dirH == INVALID_HANDLE_VALUE)
2633         return -1;
2634
2635     (void)strcpy(stmp, name);
2636     s = strrchr(stmp, '_');
2637     if (!s)
2638         return -1;
2639     s++;
2640     t = strrchr(s, '.');
2641     if (!t)
2642         return -1;
2643
2644     *t = '\0';
2645     vno = base32_to_int(s);     /* type for special files */
2646     tag = base32_to_int(t+1);
2647     info->inodeNumber = ((Inode) tag) << NAMEI_TAGSHIFT;
2648     info->inodeNumber |= vno;
2649     info->byteCount = data.nFileSizeLow;
2650
2651     dirl = dpath[strlen(dpath)-1];
2652     if (dirl == NAMEI_SPECDIRC) { /* Special inode. */
2653         info->inodeNumber |= NAMEI_INODESPECIAL;
2654         info->u.param[0] = data.ftCreationTime.dwHighDateTime;
2655         info->u.param[1] = data.ftCreationTime.dwLowDateTime;
2656         info->u.param[2] = vno; /* type */
2657         info->u.param[3] = volid;
2658         if (vno != VI_LINKTABLE)
2659             info->linkCount = 1;
2660         else {
2661             /* Open this handle */
2662             char lpath[1024];
2663             (void)sprintf(lpath, "%s" OS_DIRSEP "%s", fpath, data.cFileName);
2664             linkHandle.fd_fd = afs_open(lpath, O_RDONLY, 0666);
2665             info->linkCount =
2666                 namei_GetLinkCount(&linkHandle, (Inode) 0, 0, 0, 0);
2667         }
2668     } else {
2669         info->linkCount =
2670             namei_GetLinkCount(&linkHandle, info->inodeNumber, 0, 0, 0);
2671         if (info->linkCount == 0) {
2672 #ifdef DELETE_ZLC
2673             Log("Found 0 link count file %s" OS_DIRSEP "%s, deleting it.\n",
2674                 fpath, data.cFileName);
2675             AddToZLCDeleteList(dirl, data.cFileName);
2676 #else
2677             Log("Found 0 link count file %s" OS_DIRSEP "%s.\n", path,
2678                 data.cFileName);
2679 #endif
2680         } else {
2681             info->u.param[2] = data.ftCreationTime.dwHighDateTime;
2682             info->u.param[3] = data.ftCreationTime.dwLowDateTime;
2683             info->u.param[1] = vno;
2684             info->u.param[0] = volid;
2685         }
2686     }
2687     return 0;
2688 }
2689 #else
2690 static int
2691 DecodeInode(char *dpath, char *name, struct ViceInodeInfo *info,
2692             unsigned int volid)
2693 {
2694     char fpath[512];
2695     struct afs_stat status;
2696     int parm, tag;
2697     lb64_string_t check;
2698
2699     afs_snprintf(fpath, sizeof(fpath), "%s" OS_DIRSEP "%s", dpath, name);
2700
2701     if (afs_stat(fpath, &status) < 0) {
2702         return -1;
2703     }
2704
2705     info->byteCount = status.st_size;
2706     info->inodeNumber = (Inode) flipbase64_to_int64(name);
2707
2708     int64_to_flipbase64(check, info->inodeNumber);
2709     if (strcmp(name, check))
2710         return -1;
2711
2712     GetOGMFromStat(&status, &parm, &tag);
2713     if ((info->inodeNumber & NAMEI_INODESPECIAL) == NAMEI_INODESPECIAL) {
2714         /* p1 - vid, p2 - -1, p3 - type, p4 - rwvid */
2715         info->u.param[0] = parm;
2716         info->u.param[1] = -1;
2717         info->u.param[2] = tag;
2718         info->u.param[3] = volid;
2719     } else {
2720         /* p1 - vid, p2 - vno, p3 - uniq, p4 - dv */
2721         info->u.param[0] = volid;
2722         info->u.param[1] = (int)(info->inodeNumber & NAMEI_VNODEMASK);
2723         info->u.param[2] = (int)((info->inodeNumber >> NAMEI_UNIQSHIFT)
2724                                  & (Inode) NAMEI_UNIQMASK);
2725         info->u.param[3] = parm;
2726     }
2727     return 0;
2728 }
2729 #endif
2730
2731 /*
2732  * Convert the VolumeInfo file from RO to RW
2733  * this routine is called by namei_convertROtoRWvolume()
2734  */
2735
2736 #ifdef FSSYNC_BUILD_CLIENT
2737 static afs_int32
2738 convertVolumeInfo(FD_t fdr, FD_t fdw, afs_uint32 vid)
2739 {
2740     struct VolumeDiskData vd;
2741     char *p;
2742
2743     if (OS_READ(fdr, &vd, sizeof(struct VolumeDiskData)) !=
2744         sizeof(struct VolumeDiskData)) {
2745         Log("1 convertVolumeInfo: read failed for %lu with code %d\n",
2746             afs_printable_uint32_lu(vid),
2747             errno);
2748         return -1;
2749     }
2750     vd.restoredFromId = vd.id;  /* remember the RO volume here */
2751     vd.cloneId = vd.id;
2752     vd.id = vd.parentId;
2753     vd.type = RWVOL;
2754     vd.dontSalvage = 0;
2755     vd.inUse = 0;
2756     vd.uniquifier += 5000;      /* just in case there are still file copies from
2757                                  * the old RW volume around */
2758
2759     /* For ROs, the copyDate contains the time that the RO volume was actually
2760      * created, and the creationDate just contains the last time the RO was
2761      * copied from the RW data. So, make the new RW creationDate more accurate
2762      * by setting it to copyDate, if copyDate is older. Since, we know the
2763      * volume is at least as old as copyDate. */
2764     if (vd.copyDate < vd.creationDate) {
2765         vd.creationDate = vd.copyDate;
2766     } else {
2767         /* If copyDate is newer, just make copyDate and creationDate the same,
2768          * for consistency with other RWs */
2769         vd.copyDate = vd.creationDate;
2770     }
2771
2772     p = strrchr(vd.name, '.');
2773     if (p && !strcmp(p, ".readonly")) {
2774         memset(p, 0, 9);
2775     }
2776     if (OS_WRITE(fdw, &vd, sizeof(struct VolumeDiskData)) !=
2777         sizeof(struct VolumeDiskData)) {
2778         Log("1 convertVolumeInfo: write failed for %lu with code %d\n",
2779             afs_printable_uint32_lu(vid),
2780             errno);
2781         return -1;
2782     }
2783     return 0;
2784 }
2785 #endif
2786
2787 /*
2788  * Convert a RO-volume into a RW-volume
2789  *
2790  * This function allows to recover very fast from the loss of a partition
2791  * from RO-copies if all RO-Copies exist on another partition.
2792  * Then these RO-volumes can be made to the new RW-volumes.
2793  * Backup of RW-volumes then consists in "vos release".
2794  *
2795  * We must make sure in this partition exists only the RO-volume which
2796  * is typical for remote replicas.
2797  *
2798  * Then the linktable is already ok,
2799  *      the vnode files need to be renamed
2800  *      the volinfo file needs to be replaced by another one with
2801  *                      slightly different contents and new name.
2802  * The volume header file of the RO-volume in the /vicep<x> directory
2803  * is destroyed by this call. A new header file for the RW-volume must
2804  * be created after return from this routine.
2805  */
2806
2807 int
2808 namei_ConvertROtoRWvolume(char *pname, afs_uint32 volumeId)
2809 {
2810     int code = 0;
2811 #ifdef FSSYNC_BUILD_CLIENT
2812     namei_t n;
2813     char dir_name[512], oldpath[512], newpath[512];
2814     char smallName[64];
2815     char largeName[64];
2816     char infoName[64];
2817     IHandle_t t_ih;
2818     IHandle_t *ih;
2819     char infoSeen = 0;
2820     char smallSeen = 0;
2821     char largeSeen = 0;
2822     char linkSeen = 0;
2823     FD_t fd, fd2;
2824     char *p;
2825     DIR *dirp;
2826     Inode ino;
2827     struct dirent *dp;
2828     struct DiskPartition64 *partP;
2829     struct ViceInodeInfo info;
2830     struct VolumeDiskHeader h;
2831 # ifdef AFS_DEMAND_ATTACH_FS
2832     int locktype = 0;
2833 # endif /* AFS_DEMAND_ATTACH_FS */
2834
2835     for (partP = DiskPartitionList; partP && strcmp(partP->name, pname);
2836          partP = partP->next);
2837     if (!partP) {
2838         Log("1 namei_ConvertROtoRWvolume: Couldn't find DiskPartition for %s\n", pname);
2839         code = EIO;
2840         goto done;
2841     }
2842
2843 # ifdef AFS_DEMAND_ATTACH_FS
2844     locktype = VVolLockType(V_VOLUPD, 1);
2845     code = VLockVolumeByIdNB(volumeId, partP, locktype);
2846     if (code) {
2847         locktype = 0;
2848         code = EIO;
2849         goto done;
2850     }
2851 # endif /* AFS_DEMAND_ATTACH_FS */
2852
2853     if (VReadVolumeDiskHeader(volumeId, partP, &h)) {
2854         Log("1 namei_ConvertROtoRWvolume: Couldn't read header for RO-volume %lu.\n",
2855             afs_printable_uint32_lu(volumeId));
2856         code = EIO;
2857         goto done;
2858     }
2859
2860     FSYNC_VolOp(volumeId, pname, FSYNC_VOL_BREAKCBKS, 0, NULL);
2861
2862     ino = namei_MakeSpecIno(h.parent, VI_LINKTABLE);
2863     IH_INIT(ih, partP->device, h.parent, ino);
2864
2865     namei_HandleToName(&n, ih);
2866     strlcpy(dir_name, n.n_path, sizeof(dir_name));
2867     p = strrchr(dir_name, OS_DIRSEPC);
2868     *p = 0;
2869     dirp = opendir(dir_name);
2870     if (!dirp) {
2871         Log("1 namei_ConvertROtoRWvolume: Could not opendir(%s)\n", dir_name);
2872         code = EIO;
2873         goto done;
2874     }
2875
2876     while ((dp = readdir(dirp))) {
2877         /* struct ViceInodeInfo info; */
2878 #ifndef AFS_NT40_ENV
2879         if (*dp->d_name == '.')
2880             continue;
2881 #endif
2882         if (DecodeInode(dir_name, dp->d_name, &info, ih->ih_vid) < 0) {
2883             Log("1 namei_ConvertROtoRWvolume: DecodeInode failed for %s" OS_DIRSEP "%s\n",
2884                 dir_name, dp->d_name);
2885             closedir(dirp);
2886             code = -1;
2887             goto done;
2888         }
2889         if (info.u.param[1] != -1) {
2890             Log("1 namei_ConvertROtoRWvolume: found other than volume special file %s" OS_DIRSEP "%s\n", dir_name, dp->d_name);
2891             closedir(dirp);
2892             code = -1;
2893             goto done;
2894         }
2895         if (info.u.param[0] != volumeId) {
2896             if (info.u.param[0] == ih->ih_vid) {
2897                 if (info.u.param[2] == VI_LINKTABLE) {  /* link table */
2898                     linkSeen = 1;
2899                     continue;
2900                 }
2901             }
2902             Log("1 namei_ConvertROtoRWvolume: found special file %s" OS_DIRSEP "%s"
2903                 " for volume %lu\n", dir_name, dp->d_name,
2904                 afs_printable_uint32_lu(info.u.param[0]));
2905             closedir(dirp);
2906             code = VVOLEXISTS;
2907             goto done;
2908         }
2909         if (info.u.param[2] == VI_VOLINFO) {    /* volume info file */
2910             strlcpy(infoName, dp->d_name, sizeof(infoName));
2911             infoSeen = 1;
2912         } else if (info.u.param[2] == VI_SMALLINDEX) {  /* small vnodes file */
2913             strlcpy(smallName, dp->d_name, sizeof(smallName));
2914             smallSeen = 1;
2915         } else if (info.u.param[2] == VI_LARGEINDEX) {  /* large vnodes file */
2916             strlcpy(largeName, dp->d_name, sizeof(largeName));
2917             largeSeen = 1;
2918         } else {
2919             closedir(dirp);
2920             Log("1 namei_ConvertROtoRWvolume: unknown type %d of special file found : %s" OS_DIRSEP "%s\n", info.u.param[2], dir_name, dp->d_name);
2921             code = -1;
2922             goto done;
2923         }
2924     }
2925     closedir(dirp);
2926
2927     if (!infoSeen || !smallSeen || !largeSeen || !linkSeen) {
2928         Log("1 namei_ConvertROtoRWvolume: not all special files found in %s\n", dir_name);
2929         code = -1;
2930         goto done;
2931     }
2932
2933     /*
2934      * If we come here then there was only a RO-volume and we can safely
2935      * proceed.
2936      */
2937
2938     memset(&t_ih, 0, sizeof(t_ih));
2939     t_ih.ih_dev = ih->ih_dev;
2940     t_ih.ih_vid = ih->ih_vid;
2941
2942     (void)afs_snprintf(oldpath, sizeof oldpath, "%s" OS_DIRSEP "%s", dir_name,
2943                        infoName);
2944     fd = afs_open(oldpath, O_RDWR, 0);
2945     if (fd == INVALID_FD) {
2946         Log("1 namei_ConvertROtoRWvolume: could not open RO info file: %s\n",
2947             oldpath);
2948         code = -1;
2949         goto done;
2950     }
2951     t_ih.ih_ino = namei_MakeSpecIno(ih->ih_vid, VI_VOLINFO);
2952     namei_HandleToName(&n, &t_ih);
2953     fd2 = afs_open(n.n_path, O_CREAT | O_EXCL | O_TRUNC | O_RDWR, 0);
2954     if (fd2 == INVALID_FD) {
2955         Log("1 namei_ConvertROtoRWvolume: could not create RW info file: %s\n", n.n_path);
2956         OS_CLOSE(fd);
2957         code = -1;
2958         goto done;
2959     }
2960     code = convertVolumeInfo(fd, fd2, ih->ih_vid);
2961     OS_CLOSE(fd);
2962     if (code) {
2963         OS_CLOSE(fd2);
2964         OS_UNLINK(n.n_path);
2965         code = -1;
2966         goto done;
2967     }
2968     SetOGM(fd2, ih->ih_vid, 1);
2969     OS_CLOSE(fd2);
2970
2971     t_ih.ih_ino = namei_MakeSpecIno(ih->ih_vid, VI_SMALLINDEX);
2972     namei_HandleToName(&n, &t_ih);
2973     (void)afs_snprintf(newpath, sizeof newpath, "%s" OS_DIRSEP "%s", dir_name,
2974                        smallName);
2975     fd = afs_open(newpath, O_RDWR, 0);
2976     if (fd == INVALID_FD) {
2977         Log("1 namei_ConvertROtoRWvolume: could not open SmallIndex file: %s\n", newpath);
2978         code = -1;
2979         goto done;
2980     }
2981     SetOGM(fd, ih->ih_vid, 2);
2982     OS_CLOSE(fd);
2983 #ifdef AFS_NT40_ENV
2984     MoveFileEx(n.n_path, newpath, MOVEFILE_WRITE_THROUGH);
2985 #else
2986     link(newpath, n.n_path);
2987     OS_UNLINK(newpath);
2988 #endif
2989
2990     t_ih.ih_ino = namei_MakeSpecIno(ih->ih_vid, VI_LARGEINDEX);
2991     namei_HandleToName(&n, &t_ih);
2992     (void)afs_snprintf(newpath, sizeof newpath, "%s" OS_DIRSEP "%s", dir_name,
2993                        largeName);
2994     fd = afs_open(newpath, O_RDWR, 0);
2995     if (fd == INVALID_FD) {
2996         Log("1 namei_ConvertROtoRWvolume: could not open LargeIndex file: %s\n", newpath);
2997         code = -1;
2998         goto done;
2999     }
3000     SetOGM(fd, ih->ih_vid, 3);
3001     OS_CLOSE(fd);
3002 #ifdef AFS_NT40_ENV
3003     MoveFileEx(n.n_path, newpath, MOVEFILE_WRITE_THROUGH);
3004 #else
3005     link(newpath, n.n_path);
3006     OS_UNLINK(newpath);
3007 #endif
3008
3009     OS_UNLINK(oldpath);
3010
3011     h.id = h.parent;
3012     h.volumeInfo_hi = h.id;
3013     h.smallVnodeIndex_hi = h.id;
3014     h.largeVnodeIndex_hi = h.id;
3015     h.linkTable_hi = h.id;
3016
3017     if (VCreateVolumeDiskHeader(&h, partP)) {
3018         Log("1 namei_ConvertROtoRWvolume: Couldn't write header for RW-volume %lu\n",
3019             afs_printable_uint32_lu(h.id));
3020         code = EIO;
3021         goto done;
3022     }
3023
3024     if (VDestroyVolumeDiskHeader(partP, volumeId, h.parent)) {
3025         Log("1 namei_ConvertROtoRWvolume: Couldn't unlink header for RO-volume %lu\n",
3026             afs_printable_uint32_lu(volumeId));
3027     }
3028
3029     FSYNC_VolOp(volumeId, pname, FSYNC_VOL_DONE, 0, NULL);
3030     FSYNC_VolOp(h.id, pname, FSYNC_VOL_ON, 0, NULL);
3031
3032  done:
3033 # ifdef AFS_DEMAND_ATTACH_FS
3034     if (locktype) {
3035         VUnlockVolumeById(volumeId, partP);
3036     }
3037 # endif /* AFS_DEMAND_ATTACH_FS */
3038 #endif
3039
3040     return code;
3041 }
3042
3043 /* PrintInode
3044  *
3045  * returns a static string used to print either 32 or 64 bit inode numbers.
3046  */
3047 char *
3048 PrintInode(char *s, Inode ino)
3049 {
3050     static afs_ino_str_t result;
3051     if (!s)
3052         s = result;
3053
3054     (void)afs_snprintf(s, sizeof(afs_ino_str_t), "%" AFS_UINT64_FMT, (afs_uintmax_t) ino);
3055
3056     return s;
3057 }
3058
3059
3060 #ifdef DELETE_ZLC
3061 /* Routines to facilitate removing zero link count files. */
3062 #define MAX_ZLC_NAMES 32
3063 #define MAX_ZLC_NAMELEN 16
3064 typedef struct zlcList_s {
3065     struct zlcList_s *zlc_next;
3066     int zlc_n;
3067     char zlc_names[MAX_ZLC_NAMES][MAX_ZLC_NAMELEN];
3068 } zlcList_t;
3069
3070 static zlcList_t *zlcAnchor = NULL;
3071 static zlcList_t *zlcCur = NULL;
3072
3073 static void
3074 AddToZLCDeleteList(char dir, char *name)
3075 {
3076     osi_Assert(strlen(name) <= MAX_ZLC_NAMELEN - 3);
3077
3078     if (!zlcCur || zlcCur->zlc_n >= MAX_ZLC_NAMES) {
3079         if (zlcCur && zlcCur->zlc_next)
3080             zlcCur = zlcCur->zlc_next;
3081         else {
3082             zlcList_t *tmp = (zlcList_t *) malloc(sizeof(zlcList_t));
3083             if (!tmp)
3084                 return;
3085             if (!zlcAnchor) {
3086                 zlcAnchor = tmp;
3087             } else {
3088                 zlcCur->zlc_next = tmp;
3089             }
3090             zlcCur = tmp;
3091             zlcCur->zlc_n = 0;
3092             zlcCur->zlc_next = NULL;
3093         }
3094     }
3095
3096     if (dir)
3097         (void)sprintf(zlcCur->zlc_names[zlcCur->zlc_n], "%c" OS_DIRSEP "%s", dir, name);
3098     else
3099         (void)sprintf(zlcCur->zlc_names[zlcCur->zlc_n], "%s", name);
3100
3101     zlcCur->zlc_n++;
3102 }
3103
3104 static void
3105 DeleteZLCFiles(char *path)
3106 {
3107     zlcList_t *z;
3108     int i;
3109     char fname[1024];
3110
3111     for (z = zlcAnchor; z; z = z->zlc_next) {
3112         for (i = 0; i < z->zlc_n; i++) {
3113             if (path)
3114                 (void)sprintf(fname, "%s" OS_DIRSEP "%s", path, z->zlc_names[i]);
3115             else
3116                 (void)sprintf(fname, "%s", z->zlc_names[i]);
3117             if (namei_unlink(fname) < 0) {
3118                 Log("ZLC: Can't unlink %s, dos error = %d\n", fname,
3119                     GetLastError());
3120             }
3121         }
3122         z->zlc_n = 0;           /* Can reuse space. */
3123     }
3124     zlcCur = zlcAnchor;
3125 }
3126
3127 static void
3128 FreeZLCList(void)
3129 {
3130     zlcList_t *tnext;
3131     zlcList_t *i;
3132
3133     i = zlcAnchor;
3134     while (i) {
3135         tnext = i->zlc_next;
3136         free(i);
3137         i = tnext;
3138     }
3139     zlcCur = zlcAnchor = NULL;
3140 }
3141 #endif
3142
3143 #endif /* AFS_NAMEI_ENV */