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