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