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