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