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