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