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