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