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