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