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