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