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