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