namei: Calculate offset before use in GetFreeTag
[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[512];
2027         /* Open this handle */
2028         snprintf(path2, sizeof(path2),
2029                  "%s" OS_DIRSEP "%s", path1, dname);
2030         linkHandle->fd_fd = OS_OPEN(path2, Testing ? O_RDONLY : O_RDWR, 0666);
2031         info.linkCount =
2032             namei_GetLinkCount(linkHandle, (Inode) 0, 1, 1, Testing);
2033     }
2034
2035     if (!judgeFun ||
2036         (*judgeFun) (&info, singleVolumeNumber, rock)) {
2037         ret = (*writeFun) (fp, &info, path1, dname);
2038         if (ret < 0) {
2039             Log("_namei_examine_special: writeFun returned %d\n", ret);
2040             ret = -1;
2041         } else {
2042             ret = 1;
2043         }
2044     }
2045
2046  error:
2047     return ret;
2048 }
2049
2050 /**
2051  * examine a namei file.
2052  *
2053  * @param[in] path3               volume special directory path
2054  * @param[in] dname               directory entry name
2055  * @param[in] myIH                inode handle to volume directory
2056  * @param[in] linkHandle          namei link count fd handle.
2057  * @param[in] writeFun            metadata write function pointer
2058  * @param[in] fp                  file pointer where inode metadata
2059  *                                is written by (*writeFun)()
2060  * @param[in] judgeFun            inode filter function pointer.  if
2061  *                                not NULL, only inodes for which this
2062  *                                function returns non-zero are recorded
2063  *                                into fp by writeFun
2064  * @param[in] singleVolumeNumer   volume id filter.  if non-zero, only
2065  *                                inodes associated with this volume id
2066  *                                are recorded by writeFun
2067  * @param[in] rock                opaque pointer passed to writeFun and
2068  *                                judgeFun
2069  *
2070  * @return operation status
2071  *    @retval 1 count this inode
2072  *    @retval 0 don't count this inode
2073  *    @retval -1 failure
2074  *    @retval -2 request ZLC delete
2075  *
2076  * @internal
2077  */
2078 static int
2079 _namei_examine_reg(char * path3,
2080                    char * dname,
2081                    IHandle_t * myIH,
2082                    FdHandle_t * linkHandle,
2083                    int (*writeFun) (FD_t, struct ViceInodeInfo *, char *,
2084                                     char *),
2085                    FD_t fp,
2086                    int (*judgeFun) (struct ViceInodeInfo *, VolumeId, void *),
2087                    VolumeId singleVolumeNumber,
2088                    void *rock)
2089 {
2090     int ret = 0;
2091     struct ViceInodeInfo info;
2092 #ifdef DELETE_ZLC
2093     int dirl; /* Windows-only (one level hash dir) */
2094 #endif
2095
2096     if (DecodeInode(path3, dname, &info, myIH) < 0) {
2097         goto error;
2098     }
2099
2100     info.linkCount =
2101         namei_GetLinkCount(linkHandle,
2102                             info.inodeNumber, 1, 1, Testing);
2103     if (info.linkCount == 0) {
2104 #ifdef DELETE_ZLC
2105         Log("Found 0 link count file %s" OS_DIRSEP "%s, deleting it.\n", path3, dname);
2106 #ifdef AFS_SALSRV_ENV
2107         /* defer -- the AddToZLCDeleteList() interface is not MT-safe */
2108         ret = -2;
2109 #else /* !AFS_SALSRV_ENV */
2110         dirl = path3[strlen(path3)-1];
2111         AddToZLCDeleteList((char)dirl, dname);
2112 #endif /* !AFS_SALSRV_ENV */
2113 #else /* !DELETE_ZLC */
2114         Log("Found 0 link count file %s" OS_DIRSEP "%s.\n", path3,
2115             dname);
2116 #endif
2117         goto error;
2118     }
2119
2120     if (!judgeFun ||
2121         (*judgeFun) (&info, singleVolumeNumber, rock)) {
2122         ret = (*writeFun) (fp, &info, path3, dname);
2123         if (ret < 0) {
2124             Log("_namei_examine_reg: writeFun returned %d\n", ret);
2125             ret = -1;
2126         } else {
2127             ret = 1;
2128         }
2129     }
2130
2131  error:
2132     return ret;
2133 }
2134
2135 /**
2136  * listsubdirs work queue node.
2137  */
2138 struct listsubdirs_work_node {
2139 #ifdef AFS_SALSRV_ENV
2140     int *error;                         /**< *error set if an error was
2141                                          *   encountered in any listsubdirs
2142                                          *   thread. */
2143 #endif
2144
2145     IHandle_t * IH;                     /**< volume directory handle */
2146     FdHandle_t *linkHandle;             /**< namei link count fd handle. when
2147                                          *   examinining the link table special
2148                                          *   inode, this will be pointed at the
2149                                          *   link table
2150                                          */
2151     FD_t fp;                            /**< file pointer for writeFun */
2152
2153     /** function which will write inode metadata to fp */
2154     int (*writeFun) (FD_t, struct ViceInodeInfo *, char *, char *);
2155
2156     /** inode filter function */
2157     int (*judgeFun) (struct ViceInodeInfo *, VolumeId, void *);
2158     VolumeId singleVolumeNumber;             /**< volume id filter */
2159     void * rock;                        /**< pointer passed to writeFun and judgeFun */
2160     int code;                           /**< return code from examine function */
2161     int special;                        /**< asserted when this is a volume
2162                                          *   special file */
2163 };
2164
2165 /**
2166  * simple wrapper around _namei_examine_special and _namei_examine_reg.
2167  *
2168  * @param[in] work  the struct listsubdirs_work_node for the associated
2169  *                  "list subdirs" job
2170  * @param[in] dir   the directory to examine
2171  * @param[in] filename  the filename in 'dir' to examine
2172  *
2173  * @return operation status
2174  *   @retval 1  count this inode
2175  *   @retval 0  don't count this inode
2176  *   @retval -1 failure
2177  */
2178 static_inline int
2179 _namei_examine_file(const struct listsubdirs_work_node *work, char *dir,
2180                     char *filename)
2181 {
2182     if (work->special) {
2183         return _namei_examine_special(dir, filename, work->IH,
2184                                       work->linkHandle, work->writeFun, work->fp,
2185                                       work->judgeFun, work->singleVolumeNumber,
2186                                       work->rock);
2187     } else {
2188         return _namei_examine_reg(dir, filename, work->IH,
2189                                   work->linkHandle, work->writeFun, work->fp,
2190                                   work->judgeFun, work->singleVolumeNumber,
2191                                   work->rock);
2192     }
2193 }
2194
2195
2196 #ifdef AFS_SALSRV_ENV
2197 /** @addtogroup afs_vol_salsrv_pario */
2198 /*@{*/
2199
2200 /**
2201  * arguments for the _namei_examine_file_cbk callback function.
2202  */
2203 struct listsubdirs_args {
2204     const struct listsubdirs_work_node *work; /**< arguments that are the same
2205                                                *   for all invocations of
2206                                                *   _namei_examine_file_cbk, in
2207                                                *   threads */
2208     int *result;        /**< where we can store the return code of _namei_examine_file */
2209
2210     char dir[512];      /**< directory to examine */
2211     char filename[256]; /**< filename in 'dir' to examine */
2212 };
2213
2214 /**
2215  * a node in the list of results of listsubdir jobs.
2216  */
2217 struct listsubdirs_result {
2218     struct rx_queue q;
2219     int inodes;        /**< return value from _namei_examine_file */
2220 };
2221
2222 /**
2223  * clean up a list of 'struct listsubdirs_result's and interpret the results.
2224  *
2225  * @param[in] resultlist  a list of 'struct listsubdirs_result's
2226  *
2227  * @return number of inodes found
2228  *   @retval -1  error
2229  */
2230 static int
2231 _namei_listsubdirs_cleanup_results(struct rx_queue *resultlist)
2232 {
2233     struct listsubdirs_result *res, *nres;
2234     int ret = 0;
2235
2236     for(queue_Scan(resultlist, res, nres, listsubdirs_result)) {
2237         if (ret < 0) {
2238             /* noop, retain erroneous error code */
2239         } else if (res->inodes < 0) {
2240             ret = -1;
2241         } else {
2242             ret += res->inodes;
2243         }
2244
2245         queue_Remove(res);
2246         free(res);
2247         res = NULL;
2248     }
2249
2250     return ret;
2251 }
2252
2253 /**
2254  * wait for the spawned listsubdirs jobs to finish, and return how many inodes
2255  * they found.
2256  *
2257  * @param[in] queue    queue to wait to finish
2258  * @param[in] resultlist list of 'struct listsubdirs_result's that the queued
2259  *                       jobs are storing their results in
2260  *
2261  * @return number of inodes found
2262  *   @retval -1  error
2263  */
2264 static int
2265 _namei_listsubdirs_wait(struct afs_work_queue *queue, struct rx_queue *resultlist)
2266 {
2267     int code;
2268
2269     code = afs_wq_wait_all(queue);
2270     if (code) {
2271         return -1;
2272     }
2273
2274     return _namei_listsubdirs_cleanup_results(resultlist);
2275 }
2276
2277 /**
2278  * work queue entry point for examining namei files.
2279  *
2280  * @param[in] queue        pointer to struct Vwork_queue
2281  * @param[in] node         pointer to struct Vwork_queue_node
2282  * @param[in] queue_rock   opaque pointer to struct salsrv_pool_state
2283  * @param[in] node_rock    opaque pointer to struct listsubdirs_work_node
2284  * @param[in] caller_rock  opaque pointer to struct salsrv_worker_thread_state
2285  *
2286  * @return operation status
2287  *
2288  * @see Vwork_queue_callback_func_t
2289  *
2290  * @internal
2291  */
2292 static int
2293 _namei_examine_file_cbk(struct afs_work_queue *queue,
2294                         struct afs_work_queue_node *node,
2295                         void *queue_rock,
2296                         void *node_rock,
2297                         void *caller_rock)
2298 {
2299     int code;
2300     struct listsubdirs_args *args = node_rock;
2301     const struct listsubdirs_work_node * work = args->work;
2302     char *dir = args->dir;
2303     char *filename = args->filename;
2304
2305     code = _namei_examine_file(work, dir, filename);
2306
2307     *(args->result) = code;
2308
2309     if (code < 0) {
2310         *(work->error) = 1;
2311         /* we've errored, so no point in letting more jobs continue */
2312         afs_wq_shutdown(queue);
2313     }
2314
2315     return 0;
2316 }
2317
2318 static pthread_once_t wq_once = PTHREAD_ONCE_INIT;
2319 static pthread_key_t wq_key;
2320
2321 /**
2322  * create the wq_key key for storing a work queue.
2323  */
2324 static void
2325 _namei_wq_keycreate(void)
2326 {
2327     opr_Verify(pthread_key_create(&wq_key, NULL) == 0);
2328 }
2329
2330 /**
2331  * set the work queue for this thread to use for backgrounding namei ops.
2332  *
2333  * The work queue will be used in ListAFSSubdirs (called indirectly by
2334  * ListViceInodes) to examine files in parallel.
2335  *
2336  * @param[in] wq  the work queue to use
2337  */
2338 void
2339 namei_SetWorkQueue(struct afs_work_queue *wq)
2340 {
2341     opr_Verify(pthread_once(&wq_once, _namei_wq_keycreate) == 0);
2342
2343     opr_Verify(pthread_setspecific(wq_key, wq) == 0);
2344 }
2345
2346 /**
2347  * enqueue an examine file work unit.
2348  *
2349  * @param[in] work     the _namei_examine_file arguments that are common to
2350  *                     all callers within the same ListAFSFiles operation
2351  * @param[in] dir      the specific directory to look at (string will be
2352  *                     copied; can be stack/temporary memory)
2353  * @param[in] filename the filename to look at (string will be copied; can be
2354  *                     stack/temporary memory)
2355  * @param[in] wq       work queue to enqueue this work unit to
2356  * @param[in] resultlist the list to append the 'struct listsubdirs_result' to
2357  *                       for the enqueued work unit
2358  *
2359  * @return operation status
2360  *    @retval 0 success
2361  *    @retval -1 fatal error
2362  *
2363  * @note errors MUST be indicated by a -1 error code and nothing else, to be
2364  *       compatible with _namei_examine_reg and _namei_examine_special
2365  *
2366  * @internal
2367  */
2368 static int
2369 _namei_examine_file_spawn(const struct listsubdirs_work_node *work,
2370                           const char *dir, const char *filename,
2371                           struct afs_work_queue *wq,
2372                           struct rx_queue *resultlist)
2373 {
2374     int code, ret = 0;
2375     struct listsubdirs_args *args = NULL;
2376     struct listsubdirs_result *result = NULL;
2377     struct afs_work_queue_node *node = NULL;
2378     struct afs_work_queue_add_opts opts;
2379
2380     args = malloc(sizeof(*args));
2381     if (args == NULL) {
2382         ret = -1;
2383         goto error;
2384     }
2385
2386     result = malloc(sizeof(*result));
2387     if (result == NULL) {
2388         ret = -1;
2389         goto error;
2390     }
2391
2392     code = afs_wq_node_alloc(&node);
2393     if (code) {
2394         ret = -1;
2395         goto error;
2396     }
2397     code = afs_wq_node_set_detached(node);
2398     if (code) {
2399         ret = -1;
2400         goto error;
2401     }
2402
2403     args->work = work;
2404     args->result = &result->inodes;
2405     strlcpy(args->dir, dir, sizeof(args->dir));
2406     strlcpy(args->filename, filename, sizeof(args->filename));
2407
2408     code = afs_wq_node_set_callback(node,
2409                                          &_namei_examine_file_cbk,
2410                                          args, &free);
2411     if (code) {
2412         ret = -1;
2413         goto error;
2414     }
2415     args = NULL;
2416
2417     afs_wq_add_opts_init(&opts);
2418     opts.donate = 1;
2419
2420     code = afs_wq_add(wq, node, &opts);
2421     if (code) {
2422         ret = -1;
2423         goto error;
2424     }
2425     node = NULL;
2426
2427     queue_Append(resultlist, result);
2428     result = NULL;
2429
2430  error:
2431     if (node) {
2432         afs_wq_node_put(node);
2433         node = NULL;
2434     }
2435     if (args) {
2436         free(args);
2437         args = NULL;
2438     }
2439     if (result) {
2440         free(result);
2441         result = NULL;
2442     }
2443
2444     return ret;
2445 }
2446
2447 /*@}*/
2448 #else /* !AFS_SALSRV_ENV */
2449 # define _namei_examine_file_spawn(work, dir, file, wq, resultlist) \
2450          _namei_examine_file(work, dir, file)
2451 #endif /* !AFS_SALSRV_ENV */
2452
2453 /**
2454  * traverse and check inodes.
2455  *
2456  * @param[in] dirIH               volume group directory handle
2457  * @param[in] writeFun            function pointer which will write inode
2458  *                                metadata to FILE stream fp
2459  * @param[in] fp                  file stream where inode metadata gets
2460  *                                written
2461  * @param[in] judgeFun            inode filter function.  if not NULL, only
2462  *                                inodes for which the filter returns non-zero
2463  *                                will be written out by writeFun
2464  * @param[in] singleVolumeNumber  volume id filter.  only inodes matching this
2465  *                                filter are written out by writeFun
2466  * @param[in] rock                opaque pointer passed to judgeFun and writeFun
2467  *
2468  * @return operation status
2469  *    @retval <0 error
2470  *    @retval >=0 number of matching inodes found
2471  *
2472  * @todo the salsrv implementation may consume a lot of
2473  *       memory for a large volume.  at some point we should
2474  *       probably write a background thread to asynchronously
2475  *       clean up the resultlist nodes to reduce memory footprint
2476  *
2477  * @internal
2478  */
2479 static int
2480 namei_ListAFSSubDirs(IHandle_t * dirIH,
2481                      int (*writeFun) (FD_t, struct ViceInodeInfo *, char *,
2482                                       char *),
2483                      FD_t fp,
2484                      int (*judgeFun) (struct ViceInodeInfo *, VolumeId, void *),
2485                      VolumeId singleVolumeNumber, void *rock)
2486 {
2487     int code = 0, ret = 0;
2488     IHandle_t myIH = *dirIH;
2489     namei_t name;
2490     char path1[512], path3[512];
2491     DIR *dirp1, *dirp3;
2492 #ifndef AFS_NT40_ENV
2493     DIR *dirp2;
2494     struct dirent *dp2;
2495     char path2[512];
2496 #endif
2497     struct dirent *dp1, *dp3;
2498     FdHandle_t linkHandle;
2499     int ninodes = 0;
2500     struct listsubdirs_work_node work;
2501 #ifdef AFS_SALSRV_ENV
2502     int error = 0;
2503     struct afs_work_queue *wq;
2504     int wq_up = 0;
2505     struct rx_queue resultlist;
2506 #endif
2507
2508     namei_HandleToVolDir(&name, &myIH);
2509     strlcpy(path1, name.n_path, sizeof(path1));
2510
2511     /* Do the directory containing the special files first to pick up link
2512      * counts.
2513      */
2514     (void)strcat(path1, OS_DIRSEP);
2515     (void)strcat(path1, NAMEI_SPECDIR);
2516
2517     linkHandle.fd_fd = INVALID_FD;
2518 #ifdef AFS_SALSRV_ENV
2519     opr_Verify(pthread_once(&wq_once, _namei_wq_keycreate) == 0);
2520
2521     wq = pthread_getspecific(wq_key);
2522     if (!wq) {
2523         ret = -1;
2524         goto error;
2525     }
2526     wq_up = 1;
2527     queue_Init(&resultlist);
2528 #endif
2529
2530     memset(&work, 0, sizeof(work));
2531     work.linkHandle = &linkHandle;
2532     work.IH = &myIH;
2533     work.fp = fp;
2534     work.writeFun = writeFun;
2535     work.judgeFun = judgeFun;
2536     work.singleVolumeNumber = singleVolumeNumber;
2537     work.rock = rock;
2538     work.special = 1;
2539 #ifdef AFS_SALSRV_ENV
2540     work.error = &error;
2541 #endif
2542
2543     dirp1 = opendir(path1);
2544     if (dirp1) {
2545         while ((dp1 = readdir(dirp1))) {
2546             if (*dp1->d_name == '.')
2547                 continue;
2548
2549 #ifdef AFS_SALSRV_ENV
2550             if (error) {
2551                 closedir(dirp1);
2552                 ret = -1;
2553                 goto error;
2554             }
2555 #endif /* AFS_SALSRV_ENV */
2556
2557             code = _namei_examine_file_spawn(&work, path1, dp1->d_name, wq, &resultlist);
2558
2559             switch (code) {
2560             case -1:
2561                 /* fatal error */
2562                 closedir(dirp1);
2563                 ret = -1;
2564                 goto error;
2565
2566             case 1:
2567                 /* count this inode */
2568 #ifndef AFS_SALSRV_ENV
2569                 ninodes++;
2570 #endif
2571                 break;
2572             }
2573         }
2574         closedir(dirp1);
2575     }
2576
2577 #ifdef AFS_SALSRV_ENV
2578     /* effectively a barrier */
2579     code = _namei_listsubdirs_wait(wq, &resultlist);
2580     if (code < 0 || error) {
2581         ret = -1;
2582         goto error;
2583     }
2584     error = 0;
2585     ninodes += code;
2586 #endif
2587
2588     if (linkHandle.fd_fd == INVALID_FD) {
2589         Log("namei_ListAFSSubDirs: warning: VG %" AFS_VOLID_FMT " does not have a link table; "
2590             "salvager will recreate it.\n", afs_printable_VolumeId_lu(dirIH->ih_vid));
2591     }
2592
2593     /* Now run through all the other subdirs */
2594     namei_HandleToVolDir(&name, &myIH);
2595     strlcpy(path1, name.n_path, sizeof(path1));
2596
2597     work.special = 0;
2598
2599     dirp1 = opendir(path1);
2600     if (dirp1) {
2601         while ((dp1 = readdir(dirp1))) {
2602 #ifndef AFS_NT40_ENV
2603             if (*dp1->d_name == '.')
2604                 continue;
2605 #endif
2606             if (!strcmp(dp1->d_name, NAMEI_SPECDIR))
2607                 continue;
2608
2609 #ifndef AFS_NT40_ENV /* This level missing on Windows */
2610             /* Now we've got a next level subdir. */
2611             code = snprintf(path2, sizeof(path2), "%s" OS_DIRSEP "%s",
2612                             path1, dp1->d_name);
2613             if (code < 0 || code >= sizeof(path2)) {
2614                 /* error, or truncated */
2615                 closedir(dirp1);
2616                 ret = -1;
2617                 goto error;
2618             }
2619             dirp2 = opendir(path2);
2620             if (dirp2) {
2621                 while ((dp2 = readdir(dirp2))) {
2622                     if (*dp2->d_name == '.')
2623                         continue;
2624
2625                     /* Now we've got to the actual data */
2626                     code = snprintf(path3, sizeof(path3), "%s" OS_DIRSEP "%s",
2627                                     path2, dp2->d_name);
2628 #else
2629                     /* Now we've got to the actual data */
2630                     code = snprintf(path3, sizeof(path3), "%s" OS_DIRSEP "%s",
2631                                     path1, dp1->d_name);
2632 #endif
2633                     if (code < 0 || code >= sizeof(path3)) {
2634                         /* error, or truncated */
2635 #ifndef AFS_NT40_ENV
2636                         closedir(dirp2);
2637 #endif
2638                         closedir(dirp1);
2639                         ret = -1;
2640                         goto error;
2641                     }
2642                     dirp3 = opendir(path3);
2643                     if (dirp3) {
2644                         while ((dp3 = readdir(dirp3))) {
2645 #ifndef AFS_NT40_ENV
2646                             if (*dp3->d_name == '.')
2647                                 continue;
2648 #endif
2649
2650 #ifdef AFS_SALSRV_ENV
2651                             if (error) {
2652                                 closedir(dirp3);
2653 #ifndef AFS_NT40_ENV
2654                                 closedir(dirp2);
2655 #endif
2656                                 closedir(dirp1);
2657                                 ret = -1;
2658                                 goto error;
2659                             }
2660 #endif /* AFS_SALSRV_ENV */
2661
2662                             code = _namei_examine_file_spawn(&work, path3,
2663                                                              dp3->d_name, wq,
2664                                                              &resultlist);
2665
2666                             switch (code) {
2667                             case -1:
2668                                 closedir(dirp3);
2669 #ifndef AFS_NT40_ENV
2670                                 closedir(dirp2);
2671 #endif
2672                                 closedir(dirp1);
2673                                 ret = -1;
2674                                 goto error;
2675
2676                             case 1:
2677 #ifndef AFS_SALSRV_ENV
2678                                 ninodes++;
2679 #endif
2680                                 break;
2681                             }
2682                         }
2683                         closedir(dirp3);
2684                     }
2685 #ifndef AFS_NT40_ENV /* This level missing on Windows */
2686                 }
2687                 closedir(dirp2);
2688             }
2689 #endif
2690         }
2691         closedir(dirp1);
2692     }
2693
2694 #ifdef AFS_SALSRV_ENV
2695     /* effectively a barrier */
2696     code = _namei_listsubdirs_wait(wq, &resultlist);
2697     if (code < 0 || error) {
2698         ret = -1;
2699         goto error;
2700     }
2701     error = 0;
2702     ninodes += code;
2703     wq_up = 0;
2704 #endif
2705
2706     if (!ninodes) {
2707         /* Then why does this directory exist? Blow it away. */
2708         namei_HandleToVolDir(&name, dirIH);
2709         namei_RemoveDataDirectories(&name);
2710     }
2711
2712  error:
2713 #ifdef AFS_SALSRV_ENV
2714     if (wq_up) {
2715         afs_wq_wait_all(wq);
2716     }
2717     _namei_listsubdirs_cleanup_results(&resultlist);
2718 #endif
2719     if (linkHandle.fd_fd != INVALID_FD)
2720         OS_CLOSE(linkHandle.fd_fd);
2721
2722     if (!ret) {
2723         ret = ninodes;
2724     }
2725     return ret;
2726 }
2727
2728 /*@}*/
2729
2730 #ifdef AFS_NT40_ENV
2731 static int
2732 DecodeVolumeName(char *name, VolumeId *vid)
2733 {
2734     /* Name begins with "Vol_" and ends with .data.  See nt_HandleToVolDir() */
2735     char stmp[32];
2736     size_t len;
2737
2738     len = strlen(name);
2739     if (len <= 9)
2740         return -1;
2741     if (strncmp(name, "Vol_", 4))
2742         return -1;
2743     if (strcmp(name + len - 5, ".data"))
2744         return -1;
2745     strcpy(stmp, name);
2746     stmp[len - 5] = '\0';
2747     *vid = base32_to_int(stmp + 4);
2748     return 0;
2749 }
2750 #else
2751 static int
2752 DecodeVolumeName(char *name, VolumeId *vid)
2753 {
2754     if (strlen(name) < 1)
2755         return -1;
2756     *vid = (unsigned int)flipbase64_to_int64(name);
2757     return 0;
2758 }
2759 #endif
2760
2761
2762 /* DecodeInode
2763  *
2764  * Get the inode number from the name.
2765  *
2766  */
2767 #ifdef AFS_NT40_ENV
2768 static int
2769 DecodeInode(char *dpath, char *name, struct ViceInodeInfo *info,
2770             IHandle_t *myIH)
2771 {
2772     char fpath[512];
2773     int tag, vno;
2774     WIN32_FIND_DATA data;
2775     HANDLE dirH;
2776     char *s, *t;
2777     char stmp[16];
2778     FdHandle_t linkHandle;
2779     char dirl;
2780     VolumeId volid = myIH->ih_vid;
2781
2782     snprintf(fpath, sizeof(fpath), "%s" OS_DIRSEP "%s", dpath, name);
2783
2784     dirH = FindFirstFileEx(fpath, FindExInfoStandard, &data,
2785                            FindExSearchNameMatch, NULL,
2786                            FIND_FIRST_EX_CASE_SENSITIVE);
2787     if (dirH == INVALID_HANDLE_VALUE)
2788         return -1;
2789
2790     (void)strcpy(stmp, name);
2791     s = strrchr(stmp, '_');
2792     if (!s)
2793         return -1;
2794     s++;
2795     t = strrchr(s, '.');
2796     if (!t)
2797         return -1;
2798
2799     *t = '\0';
2800     vno = base32_to_int(s);     /* type for special files */
2801     tag = base32_to_int(t+1);
2802     info->inodeNumber = ((Inode) tag) << NAMEI_TAGSHIFT;
2803     info->inodeNumber |= vno;
2804     info->byteCount = data.nFileSizeLow;
2805
2806     dirl = dpath[strlen(dpath)-1];
2807     if (dirl == NAMEI_SPECDIRC) { /* Special inode. */
2808         info->inodeNumber |= NAMEI_INODESPECIAL;
2809         info->u.param[0] = data.ftCreationTime.dwHighDateTime;
2810         info->u.param[1] = data.ftCreationTime.dwLowDateTime;
2811         info->u.param[2] = vno; /* type */
2812         info->u.param[3] = volid;
2813         if (vno != VI_LINKTABLE)
2814             info->linkCount = 1;
2815         else {
2816             /* Open this handle */
2817             char lpath[1024];
2818             (void)sprintf(lpath, "%s" OS_DIRSEP "%s", fpath, data.cFileName);
2819             linkHandle.fd_fd = OS_OPEN(lpath, O_RDONLY, 0666);
2820             info->linkCount =
2821                 namei_GetLinkCount(&linkHandle, (Inode) 0, 0, 0, 0);
2822         }
2823     } else {
2824         info->linkCount =
2825             namei_GetLinkCount(&linkHandle, info->inodeNumber, 0, 0, 0);
2826         if (info->linkCount == 0) {
2827 #ifdef DELETE_ZLC
2828             Log("Found 0 link count file %s" OS_DIRSEP "%s, deleting it.\n",
2829                 fpath, data.cFileName);
2830             AddToZLCDeleteList(dirl, data.cFileName);
2831 #else
2832             Log("Found 0 link count file %s" OS_DIRSEP "%s.\n", path,
2833                 data.cFileName);
2834 #endif
2835         } else {
2836             info->u.param[2] = data.ftCreationTime.dwHighDateTime;
2837             info->u.param[3] = data.ftCreationTime.dwLowDateTime;
2838             info->u.param[1] = vno;
2839             info->u.param[0] = volid;
2840         }
2841     }
2842     return 0;
2843 }
2844 #else
2845 static int
2846 DecodeInode(char *dpath, char *name, struct ViceInodeInfo *info,
2847             IHandle_t *myIH)
2848 {
2849     char fpath[512];
2850     struct afs_stat_st status;
2851     struct afs_stat_st checkstatus;
2852     int parm, tag;
2853     lb64_string_t check;
2854     VolumeId volid = myIH->ih_vid;
2855     IHandle_t tmpih;
2856     namei_t nameiname;
2857
2858     snprintf(fpath, sizeof(fpath), "%s" OS_DIRSEP "%s", dpath, name);
2859
2860     if (afs_stat(fpath, &status) < 0) {
2861         return -1;
2862     }
2863
2864     info->byteCount = status.st_size;
2865     info->inodeNumber = (Inode) flipbase64_to_int64(name);
2866
2867     int64_to_flipbase64(check, info->inodeNumber);
2868     if (strcmp(name, check))
2869         return -1;
2870
2871     /* Check if the _full_ path is correct, to ensure we can actually open this
2872      * file later. Otherwise, the salvager can choke. */
2873     memset(&tmpih, 0, sizeof(tmpih));
2874     tmpih.ih_dev = myIH->ih_dev;
2875     tmpih.ih_vid = myIH->ih_vid;
2876     tmpih.ih_ino = info->inodeNumber;
2877     namei_HandleToName(&nameiname, &tmpih);
2878     if ((afs_stat(nameiname.n_path, &checkstatus) < 0) ||
2879         checkstatus.st_ino != status.st_ino ||
2880         checkstatus.st_size != status.st_size) {
2881         static int logged;
2882         /* log something for this case, since this means the filename looks
2883          * like a valid inode, but it's just in the wrong place. That's pretty
2884          * strange. */
2885         if (!logged) {
2886             logged = 1;
2887             Log("Note:\n");
2888             Log("  Seemingly-misplaced files have been found, which I am\n");
2889             Log("  ignoring for now. If you cannot salvage the relevant volume,\n");
2890             Log("  you may try manually moving them to their correct location.\n");
2891             Log("  If the relevant volume seems fine, and these files do not\n");
2892             Log("  appear to contain important data, you can probably manually\n");
2893             Log("  delete them, or leave them alone. Contact your local OpenAFS\n");
2894             Log("  expert if you are unsure.\n");
2895         }
2896         Log("Ignoring misplaced file in volume group %u: %s (should be %s)\n",
2897             (unsigned)myIH->ih_vid, fpath, nameiname.n_path);
2898         return -1;
2899     }
2900
2901     if ((info->inodeNumber & NAMEI_INODESPECIAL) == NAMEI_INODESPECIAL) {
2902         parm = ((info->inodeNumber >> NAMEI_UNIQSHIFT) & NAMEI_UNIQMASK);
2903         tag = (int)((info->inodeNumber >> NAMEI_TAGSHIFT) & NAMEI_TAGMASK);
2904
2905         /* p1 - vid, p2 - -1, p3 - type, p4 - rwvid */
2906         info->u.param[0] = parm;
2907         info->u.param[1] = -1;
2908         info->u.param[2] = tag;
2909         info->u.param[3] = volid;
2910     } else {
2911         GetOGMFromStat(&status, &parm, &tag);
2912         /* p1 - vid, p2 - vno, p3 - uniq, p4 - dv */
2913         info->u.param[0] = volid;
2914         info->u.param[1] = (int)(info->inodeNumber & NAMEI_VNODEMASK);
2915         info->u.param[2] = (int)((info->inodeNumber >> NAMEI_UNIQSHIFT)
2916                                  & (Inode) NAMEI_UNIQMASK);
2917         info->u.param[3] = parm;
2918     }
2919     return 0;
2920 }
2921 #endif
2922
2923 /*
2924  * Convert the VolumeInfo file from RO to RW
2925  * this routine is called by namei_convertROtoRWvolume()
2926  */
2927
2928 #ifdef FSSYNC_BUILD_CLIENT
2929 static afs_int32
2930 convertVolumeInfo(FD_t fdr, FD_t fdw, VolumeId vid)
2931 {
2932     struct VolumeDiskData vd;
2933     char *p;
2934
2935     if (OS_READ(fdr, &vd, sizeof(struct VolumeDiskData)) !=
2936         sizeof(struct VolumeDiskData)) {
2937         Log("1 convertVolumeInfo: read failed for %" AFS_VOLID_FMT " with code %d\n",
2938             afs_printable_VolumeId_lu(vid),
2939             errno);
2940         return -1;
2941     }
2942     vd.restoredFromId = vd.id;  /* remember the RO volume here */
2943     vd.cloneId = vd.id;
2944     vd.id = vd.parentId;
2945     vd.type = RWVOL;
2946     vd.dontSalvage = 0;
2947     vd.inUse = 0;
2948     vd.uniquifier += 5000;      /* just in case there are still file copies from
2949                                  * the old RW volume around */
2950
2951     /* For ROs, the copyDate contains the time that the RO volume was actually
2952      * created, and the creationDate just contains the last time the RO was
2953      * copied from the RW data. So, make the new RW creationDate more accurate
2954      * by setting it to copyDate, if copyDate is older. Since, we know the
2955      * volume is at least as old as copyDate. */
2956     if (vd.copyDate < vd.creationDate) {
2957         vd.creationDate = vd.copyDate;
2958     } else {
2959         /* If copyDate is newer, just make copyDate and creationDate the same,
2960          * for consistency with other RWs */
2961         vd.copyDate = vd.creationDate;
2962     }
2963
2964     p = strrchr(vd.name, '.');
2965     if (p && !strcmp(p, ".readonly")) {
2966         memset(p, 0, 9);
2967     }
2968     if (OS_WRITE(fdw, &vd, sizeof(struct VolumeDiskData)) !=
2969         sizeof(struct VolumeDiskData)) {
2970         Log("1 convertVolumeInfo: write failed for %lu with code %d\n",
2971             afs_printable_uint32_lu(vid),
2972             errno);
2973         return -1;
2974     }
2975     return 0;
2976 }
2977 #endif
2978
2979 /*
2980  * Convert a RO-volume into a RW-volume
2981  *
2982  * This function allows to recover very fast from the loss of a partition
2983  * from RO-copies if all RO-Copies exist on another partition.
2984  * Then these RO-volumes can be made to the new RW-volumes.
2985  * Backup of RW-volumes then consists in "vos release".
2986  *
2987  * We must make sure in this partition exists only the RO-volume which
2988  * is typical for remote replicas.
2989  *
2990  * Then the linktable is already ok,
2991  *      the vnode files need to be renamed
2992  *      the volinfo file needs to be replaced by another one with
2993  *                      slightly different contents and new name.
2994  * The volume header file of the RO-volume in the /vicep<x> directory
2995  * is destroyed by this call. A new header file for the RW-volume must
2996  * be created after return from this routine.
2997  */
2998
2999 int
3000 namei_ConvertROtoRWvolume(char *pname, VolumeId volumeId)
3001 {
3002     int code = 0;
3003 #ifdef FSSYNC_BUILD_CLIENT
3004     namei_t n;
3005     char dir_name[512], oldpath[512], newpath[512];
3006     char smallName[64];
3007     char largeName[64];
3008     char infoName[64];
3009     IHandle_t t_ih;
3010     IHandle_t *ih;
3011     char infoSeen = 0;
3012     char smallSeen = 0;
3013     char largeSeen = 0;
3014     char linkSeen = 0;
3015     FD_t fd, fd2;
3016     char *p;
3017     DIR *dirp;
3018     Inode ino;
3019     struct dirent *dp;
3020     struct DiskPartition64 *partP;
3021     struct ViceInodeInfo info;
3022     struct VolumeDiskHeader h;
3023     char *rwpart, *rwname;
3024     Error ec;
3025 # ifdef AFS_DEMAND_ATTACH_FS
3026     int locktype = 0;
3027 # endif /* AFS_DEMAND_ATTACH_FS */
3028
3029     for (partP = DiskPartitionList; partP && strcmp(partP->name, pname);
3030          partP = partP->next);
3031     if (!partP) {
3032         Log("1 namei_ConvertROtoRWvolume: Couldn't find DiskPartition for %s\n", pname);
3033         code = EIO;
3034         goto done;
3035     }
3036
3037 # ifdef AFS_DEMAND_ATTACH_FS
3038     locktype = VVolLockType(V_VOLUPD, 1);
3039     code = VLockVolumeByIdNB(volumeId, partP, locktype);
3040     if (code) {
3041         locktype = 0;
3042         code = EIO;
3043         goto done;
3044     }
3045 # endif /* AFS_DEMAND_ATTACH_FS */
3046
3047     if (VReadVolumeDiskHeader(volumeId, partP, &h)) {
3048         Log("1 namei_ConvertROtoRWvolume: Couldn't read header for RO-volume %lu.\n",
3049             afs_printable_uint32_lu(volumeId));
3050         code = EIO;
3051         goto done;
3052     }
3053
3054     /* check for existing RW on any partition on this server; */
3055     /* if found, return EXDEV - invalid cross-device link */
3056     VOL_LOCK;
3057     VGetVolumePath(&ec, h.parent, &rwpart, &rwname);
3058     if (ec == 0) {
3059         Log("1 namei_ConvertROtoRWvolume: RW volume %lu already exists on server partition %s.\n",
3060             afs_printable_uint32_lu(h.parent), rwpart);
3061         code = EXDEV;
3062         VOL_UNLOCK;
3063         goto done;
3064     }
3065     VOL_UNLOCK;
3066
3067     FSYNC_VolOp(volumeId, pname, FSYNC_VOL_BREAKCBKS, 0, NULL);
3068
3069     ino = namei_MakeSpecIno(h.parent, VI_LINKTABLE);
3070     IH_INIT(ih, partP->device, h.parent, ino);
3071
3072     namei_HandleToName(&n, ih);
3073     strlcpy(dir_name, n.n_path, sizeof(dir_name));
3074     p = strrchr(dir_name, OS_DIRSEPC);
3075     *p = 0;
3076     dirp = opendir(dir_name);
3077     if (!dirp) {
3078         Log("1 namei_ConvertROtoRWvolume: Could not opendir(%s)\n", dir_name);
3079         code = EIO;
3080         goto done;
3081     }
3082
3083     while ((dp = readdir(dirp))) {
3084         /* struct ViceInodeInfo info; */
3085 #ifndef AFS_NT40_ENV
3086         if (*dp->d_name == '.')
3087             continue;
3088 #endif
3089         if (DecodeInode(dir_name, dp->d_name, &info, ih) < 0) {
3090             Log("1 namei_ConvertROtoRWvolume: DecodeInode failed for %s" OS_DIRSEP "%s\n",
3091                 dir_name, dp->d_name);
3092             closedir(dirp);
3093             code = -1;
3094             goto done;
3095         }
3096         if (info.u.param[1] != -1) {
3097             Log("1 namei_ConvertROtoRWvolume: found other than volume special file %s" OS_DIRSEP "%s\n", dir_name, dp->d_name);
3098             closedir(dirp);
3099             code = -1;
3100             goto done;
3101         }
3102         if (info.u.param[0] != volumeId) {
3103             if (info.u.param[0] == ih->ih_vid) {
3104                 if (info.u.param[2] == VI_LINKTABLE) {  /* link table */
3105                     linkSeen = 1;
3106                     continue;
3107                 }
3108             }
3109             Log("1 namei_ConvertROtoRWvolume: found special file %s" OS_DIRSEP "%s"
3110                 " for volume %lu\n", dir_name, dp->d_name,
3111                 afs_printable_uint32_lu(info.u.param[0]));
3112             closedir(dirp);
3113             code = VVOLEXISTS;
3114             goto done;
3115         }
3116         if (info.u.param[2] == VI_VOLINFO) {    /* volume info file */
3117             strlcpy(infoName, dp->d_name, sizeof(infoName));
3118             infoSeen = 1;
3119         } else if (info.u.param[2] == VI_SMALLINDEX) {  /* small vnodes file */
3120             strlcpy(smallName, dp->d_name, sizeof(smallName));
3121             smallSeen = 1;
3122         } else if (info.u.param[2] == VI_LARGEINDEX) {  /* large vnodes file */
3123             strlcpy(largeName, dp->d_name, sizeof(largeName));
3124             largeSeen = 1;
3125         } else {
3126             closedir(dirp);
3127             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);
3128             code = -1;
3129             goto done;
3130         }
3131     }
3132     closedir(dirp);
3133
3134     if (!infoSeen || !smallSeen || !largeSeen || !linkSeen) {
3135         Log("1 namei_ConvertROtoRWvolume: not all special files found in %s\n", dir_name);
3136         code = -1;
3137         goto done;
3138     }
3139
3140     /*
3141      * If we come here then there was only a RO-volume and we can safely
3142      * proceed.
3143      */
3144
3145     memset(&t_ih, 0, sizeof(t_ih));
3146     t_ih.ih_dev = ih->ih_dev;
3147     t_ih.ih_vid = ih->ih_vid;
3148
3149     code = snprintf(oldpath, sizeof oldpath, "%s" OS_DIRSEP "%s", dir_name,
3150                     infoName);
3151     if (code < 0 || code >= sizeof(oldpath)) {
3152         /* error, or truncated */
3153         code = -1;
3154         goto done;
3155     }
3156     fd = OS_OPEN(oldpath, O_RDWR, 0);
3157     if (fd == INVALID_FD) {
3158         Log("1 namei_ConvertROtoRWvolume: could not open RO info file: %s\n",
3159             oldpath);
3160         code = -1;
3161         goto done;
3162     }
3163     t_ih.ih_ino = namei_MakeSpecIno(ih->ih_vid, VI_VOLINFO);
3164     namei_HandleToName(&n, &t_ih);
3165     fd2 = OS_OPEN(n.n_path, O_CREAT | O_EXCL | O_RDWR, 0);
3166     if (fd2 == INVALID_FD) {
3167         Log("1 namei_ConvertROtoRWvolume: could not create RW info file: %s\n", n.n_path);
3168         OS_CLOSE(fd);
3169         code = -1;
3170         goto done;
3171     }
3172     code = convertVolumeInfo(fd, fd2, ih->ih_vid);
3173     OS_CLOSE(fd);
3174     if (code) {
3175         OS_CLOSE(fd2);
3176         OS_UNLINK(n.n_path);
3177         code = -1;
3178         goto done;
3179     }
3180     SetOGM(fd2, ih->ih_vid, 1);
3181     OS_CLOSE(fd2);
3182
3183     t_ih.ih_ino = namei_MakeSpecIno(ih->ih_vid, VI_SMALLINDEX);
3184     namei_HandleToName(&n, &t_ih);
3185     code = snprintf(newpath, sizeof newpath, "%s" OS_DIRSEP "%s", dir_name,
3186                     smallName);
3187     if (code < 0 || code >= sizeof(newpath)) {
3188         /* error, or truncated */
3189         code = -1;
3190         goto done;
3191     }
3192     fd = OS_OPEN(newpath, O_RDWR, 0);
3193     if (fd == INVALID_FD) {
3194         Log("1 namei_ConvertROtoRWvolume: could not open SmallIndex file: %s\n", newpath);
3195         code = -1;
3196         goto done;
3197     }
3198     SetOGM(fd, ih->ih_vid, 2);
3199     OS_CLOSE(fd);
3200 #ifdef AFS_NT40_ENV
3201     MoveFileEx(n.n_path, newpath, MOVEFILE_WRITE_THROUGH);
3202 #else
3203     if (link(newpath, n.n_path)) {
3204         Log("1 namei_ConvertROtoRWvolume: could not move SmallIndex file: %s\n", n.n_path);
3205         code = -1;
3206         goto done;
3207     }
3208     OS_UNLINK(newpath);
3209 #endif
3210
3211     t_ih.ih_ino = namei_MakeSpecIno(ih->ih_vid, VI_LARGEINDEX);
3212     namei_HandleToName(&n, &t_ih);
3213     code = snprintf(newpath, sizeof newpath, "%s" OS_DIRSEP "%s", dir_name,
3214                     largeName);
3215     if (code < 0 || code >= sizeof(newpath)) {
3216         /* error, or truncated */
3217         code = -1;
3218         goto done;
3219     }
3220     fd = OS_OPEN(newpath, O_RDWR, 0);
3221     if (fd == INVALID_FD) {
3222         Log("1 namei_ConvertROtoRWvolume: could not open LargeIndex file: %s\n", newpath);
3223         code = -1;
3224         goto done;
3225     }
3226     SetOGM(fd, ih->ih_vid, 3);
3227     OS_CLOSE(fd);
3228 #ifdef AFS_NT40_ENV
3229     MoveFileEx(n.n_path, newpath, MOVEFILE_WRITE_THROUGH);
3230 #else
3231     if (link(newpath, n.n_path)) {
3232         Log("1 namei_ConvertROtoRWvolume: could not move LargeIndex file: %s\n", n.n_path);
3233         code = -1;
3234         goto done;
3235     }
3236     OS_UNLINK(newpath);
3237 #endif
3238
3239     OS_UNLINK(oldpath);
3240
3241     h.id = h.parent;
3242     h.volumeInfo_hi = h.id;
3243     h.smallVnodeIndex_hi = h.id;
3244     h.largeVnodeIndex_hi = h.id;
3245     h.linkTable_hi = h.id;
3246
3247     if (VCreateVolumeDiskHeader(&h, partP)) {
3248         Log("1 namei_ConvertROtoRWvolume: Couldn't write header for RW-volume %lu\n",
3249             afs_printable_uint32_lu(h.id));
3250         code = EIO;
3251         goto done;
3252     }
3253
3254     if (VDestroyVolumeDiskHeader(partP, volumeId, h.parent)) {
3255         Log("1 namei_ConvertROtoRWvolume: Couldn't unlink header for RO-volume %lu\n",
3256             afs_printable_uint32_lu(volumeId));
3257     }
3258
3259     FSYNC_VolOp(volumeId, pname, FSYNC_VOL_DONE, 0, NULL);
3260     FSYNC_VolOp(h.id, pname, FSYNC_VOL_ON, 0, NULL);
3261
3262     code = 0;
3263  done:
3264 # ifdef AFS_DEMAND_ATTACH_FS
3265     if (locktype) {
3266         VUnlockVolumeById(volumeId, partP);
3267     }
3268 # endif /* AFS_DEMAND_ATTACH_FS */
3269 #endif
3270
3271     return code;
3272 }
3273
3274 /* PrintInode
3275  *
3276  * returns a static string used to print either 32 or 64 bit inode numbers.
3277  */
3278 char *
3279 PrintInode(char *s, Inode ino)
3280 {
3281     static afs_ino_str_t result;
3282     if (!s)
3283         s = result;
3284
3285     snprintf(s, sizeof(afs_ino_str_t), "%llu", (afs_uintmax_t) ino);
3286
3287     return s;
3288 }
3289
3290
3291 #ifdef DELETE_ZLC
3292 /* Routines to facilitate removing zero link count files. */
3293 #define MAX_ZLC_NAMES 32
3294 #define MAX_ZLC_NAMELEN 16
3295 typedef struct zlcList_s {
3296     struct zlcList_s *zlc_next;
3297     int zlc_n;
3298     char zlc_names[MAX_ZLC_NAMES][MAX_ZLC_NAMELEN];
3299 } zlcList_t;
3300
3301 static zlcList_t *zlcAnchor = NULL;
3302 static zlcList_t *zlcCur = NULL;
3303
3304 static void
3305 AddToZLCDeleteList(char dir, char *name)
3306 {
3307     opr_Assert(strlen(name) <= MAX_ZLC_NAMELEN - 3);
3308
3309     if (!zlcCur || zlcCur->zlc_n >= MAX_ZLC_NAMES) {
3310         if (zlcCur && zlcCur->zlc_next)
3311             zlcCur = zlcCur->zlc_next;
3312         else {
3313             zlcList_t *tmp = malloc(sizeof(zlcList_t));
3314             if (!tmp)
3315                 return;
3316             if (!zlcAnchor) {
3317                 zlcAnchor = tmp;
3318             } else {
3319                 zlcCur->zlc_next = tmp;
3320             }
3321             zlcCur = tmp;
3322             zlcCur->zlc_n = 0;
3323             zlcCur->zlc_next = NULL;
3324         }
3325     }
3326
3327     if (dir)
3328         (void)sprintf(zlcCur->zlc_names[zlcCur->zlc_n], "%c" OS_DIRSEP "%s", dir, name);
3329     else
3330         (void)sprintf(zlcCur->zlc_names[zlcCur->zlc_n], "%s", name);
3331
3332     zlcCur->zlc_n++;
3333 }
3334
3335 static void
3336 DeleteZLCFiles(char *path)
3337 {
3338     zlcList_t *z;
3339     int i;
3340     char fname[1024];
3341
3342     for (z = zlcAnchor; z; z = z->zlc_next) {
3343         for (i = 0; i < z->zlc_n; i++) {
3344             if (path)
3345                 (void)sprintf(fname, "%s" OS_DIRSEP "%s", path, z->zlc_names[i]);
3346             else
3347                 (void)sprintf(fname, "%s", z->zlc_names[i]);
3348             if (namei_unlink(fname) < 0) {
3349                 Log("ZLC: Can't unlink %s, dos error = %d\n", fname,
3350                     GetLastError());
3351             }
3352         }
3353         z->zlc_n = 0;           /* Can reuse space. */
3354     }
3355     zlcCur = zlcAnchor;
3356 }
3357
3358 static void
3359 FreeZLCList(void)
3360 {
3361     zlcList_t *tnext;
3362     zlcList_t *i;
3363
3364     i = zlcAnchor;
3365     while (i) {
3366         tnext = i->zlc_next;
3367         free(i);
3368         i = tnext;
3369     }
3370     zlcCur = zlcAnchor = NULL;
3371 }
3372 #endif
3373
3374 /**
3375  * Remove empty directories associated with the volume received
3376  * as an argument.
3377  *
3378  * @param[in] pname    vice partition path
3379  * @param[in] vid      volume id
3380  *
3381  * @return 0 on success
3382  */
3383 int
3384 namei_RemoveDirectories(char *pname, afs_int32 vid)
3385 {
3386     IHandle_t dirIH;
3387     namei_t name;
3388
3389     memset(&dirIH, 0, sizeof(dirIH));
3390
3391     dirIH.ih_vid = vid;
3392
3393 #ifdef AFS_NT40_ENV
3394     dirIH.ih_dev = nt_DriveToDev(pname);
3395 #else
3396     dirIH.ih_dev = volutil_GetPartitionID(pname);
3397 #endif
3398     if (dirIH.ih_dev == -1) {
3399         return -1;
3400     }
3401
3402     namei_HandleToVolDir(&name, &dirIH);
3403
3404     return namei_RemoveDataDirectories(&name);
3405 }
3406
3407 #endif /* AFS_NAMEI_ENV */