DAFS: Remove AFS_DEMAND_ATTACH_UTIL
[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 icreate(IHandle_t * lh, char *part, afs_uint32 p1, afs_uint32 p2, afs_uint32 p3, afs_uint32 p4,
956         FD_t *afd, Inode *ainode)
957 {
958     namei_t name;
959     int fd = INVALID_FD;
960     int code = 0;
961     int created_dir = 0;
962     IHandle_t tmp;
963     FdHandle_t *fdP;
964     FdHandle_t tfd;
965     int tag;
966     int ogm_parm;
967
968     memset((void *)&tmp, 0, sizeof(IHandle_t));
969     memset(&tfd, 0, sizeof(FdHandle_t));
970
971     tmp.ih_dev = volutil_GetPartitionID(part);
972     if (tmp.ih_dev == -1) {
973         errno = EINVAL;
974         return -1;
975     }
976
977     if (p2 == -1) {
978         /* Parameters for special file:
979          * p1 - volume id - goes into owner/group/mode
980          * p2 - vnode == -1
981          * p3 - type
982          * p4 - parent volume id
983          */
984         ogm_parm = p1;
985
986         tag = p3;
987         tmp.ih_vid = p4;        /* Use parent volume id, where this file will be. */
988         tmp.ih_ino = namei_MakeSpecIno(p1, p3);
989     } else {
990         int vno = p2 & NAMEI_VNODEMASK;
991         /* Parameters for regular file:
992          * p1 - volume id
993          * p2 - vnode
994          * p3 - uniq
995          * p4 - dv
996          */
997
998         if (vno != p2) {
999             big_vno++;
1000             errno = EINVAL;
1001             return -1;
1002         }
1003         /* If GetFreeTag succeeds, it atomically sets link count to 1. */
1004         tag = GetFreeTag(lh, p2);
1005         if (tag < 0)
1006             goto bad;
1007
1008         tmp.ih_vid = p1;
1009         tmp.ih_ino = (Inode) p2;
1010         /* name is <uniq(p3)><tag><vno(p2)> */
1011         tmp.ih_ino |= ((Inode) tag) << NAMEI_TAGSHIFT;
1012         tmp.ih_ino |= ((Inode) p3) << NAMEI_UNIQSHIFT;
1013
1014         ogm_parm = p4;
1015     }
1016
1017     namei_HandleToName(&name, &tmp);
1018     fd = OS_OPEN(name.n_path, O_CREAT | O_EXCL | O_RDWR, 0);
1019     if (fd == INVALID_FD) {
1020         if (errno == ENOTDIR || errno == ENOENT) {
1021             if (namei_CreateDataDirectories(&name, &created_dir) < 0)
1022                 goto bad;
1023             fd = OS_OPEN(name.n_path, O_CREAT | O_EXCL | O_RDWR,
1024                           0);
1025             if (fd == INVALID_FD)
1026                 goto bad;
1027         } else {
1028             goto bad;
1029         }
1030     }
1031     if (SetOGM(fd, ogm_parm, tag) < 0) {
1032         OS_CLOSE(fd);
1033         fd = INVALID_FD;
1034         goto bad;
1035     }
1036
1037     if (p2 == (afs_uint32)-1 && p3 == VI_LINKTABLE) {
1038         /* hack at tmp to setup for set link count call. */
1039         memset((void *)&tfd, 0, sizeof(FdHandle_t));    /* minimalistic still, but a little cleaner */
1040         tfd.fd_ih = &tmp;
1041         tfd.fd_fd = fd;
1042         code = namei_SetLinkCount(&tfd, (Inode) 0, 1, 0);
1043     }
1044
1045   bad:
1046     if (code || (fd == INVALID_FD)) {
1047         if (p2 != -1) {
1048             fdP = IH_OPEN(lh);
1049             if (fdP) {
1050                 namei_SetLinkCount(fdP, tmp.ih_ino, 0, 0);
1051                 FDH_CLOSE(fdP);
1052             }
1053         }
1054     }
1055
1056     *afd = fd;
1057     *ainode = tmp.ih_ino;
1058
1059     return code;
1060 }
1061
1062 Inode
1063 namei_icreate(IHandle_t * lh, char *part,
1064               afs_uint32 p1, afs_uint32 p2, afs_uint32 p3, afs_uint32 p4)
1065 {
1066     Inode ino = 0;
1067     int fd = INVALID_FD;
1068     int code;
1069
1070     code = icreate(lh, part, p1, p2, p3, p4, &fd, &ino);
1071     if (fd != INVALID_FD) {
1072         close(fd);
1073     }
1074     return (code || (fd == INVALID_FD)) ? (Inode) - 1 : ino;
1075 }
1076
1077 IHandle_t *
1078 namei_icreate_init(IHandle_t * lh, int dev, char *part,
1079                    afs_uint32 p1, afs_uint32 p2, afs_uint32 p3, afs_uint32 p4)
1080 {
1081     Inode ino = 0;
1082     int fd = INVALID_FD;
1083     int code;
1084     IHandle_t *ihP;
1085     FdHandle_t *fdP;
1086
1087     code = icreate(lh, part, p1, p2, p3, p4, &fd, &ino);
1088     if (fd == INVALID_FD) {
1089         return NULL;
1090     }
1091     if (code) {
1092         close(fd);
1093         return NULL;
1094     }
1095
1096     IH_INIT(ihP, dev, p1, ino);
1097     fdP = ih_attachfd(ihP, fd);
1098     if (!fdP) {
1099         close(fd);
1100     } else {
1101         FDH_CLOSE(fdP);
1102     }
1103
1104     return ihP;
1105 }
1106 #endif
1107
1108 /* namei_iopen */
1109 FD_t
1110 namei_iopen(IHandle_t * h)
1111 {
1112     FD_t fd;
1113     namei_t name;
1114
1115     /* Convert handle to file name. */
1116     namei_HandleToName(&name, h);
1117     fd = OS_OPEN((char *)&name.n_path, O_RDWR, 0666);
1118     return fd;
1119 }
1120
1121 /* Need to detect vol special file and just unlink. In those cases, the
1122  * handle passed in _is_ for the inode. We only check p1 for the special
1123  * files.
1124  */
1125 int
1126 namei_dec(IHandle_t * ih, Inode ino, int p1)
1127 {
1128     int count = 0;
1129     namei_t name;
1130     int code = 0;
1131     FdHandle_t *fdP;
1132
1133     if ((ino & NAMEI_INODESPECIAL) == NAMEI_INODESPECIAL) {
1134         IHandle_t *tmp;
1135         int type = (int)((ino >> NAMEI_TAGSHIFT) & NAMEI_TAGMASK);
1136
1137         /* Verify this is the right file. */
1138         IH_INIT(tmp, ih->ih_dev, ih->ih_vid, ino);
1139
1140         namei_HandleToName(&name, tmp);
1141
1142         fdP = IH_OPEN(tmp);
1143         if (fdP == NULL) {
1144             IH_RELEASE(tmp);
1145             errno = OS_ERROR(ENOENT);
1146             return -1;
1147         }
1148
1149         if (CheckOGM(fdP, p1) < 0) {
1150             FDH_REALLYCLOSE(fdP);
1151             IH_RELEASE(tmp);
1152             errno = OS_ERROR(EINVAL);
1153             return -1;
1154         }
1155
1156         /* If it's the link table itself, decrement the link count. */
1157         if (type == VI_LINKTABLE) {
1158           if ((count = namei_GetLinkCount(fdP, (Inode) 0, 1, 0, 1)) < 0) {
1159                 FDH_REALLYCLOSE(fdP);
1160                 IH_RELEASE(tmp);
1161                 return -1;
1162             }
1163
1164             count--;
1165             if (namei_SetLinkCount(fdP, (Inode) 0, count < 0 ? 0 : count, 1) <
1166                 0) {
1167                 FDH_REALLYCLOSE(fdP);
1168                 IH_RELEASE(tmp);
1169                 return -1;
1170             }
1171
1172             if (count > 0) {
1173                 FDH_CLOSE(fdP);
1174                 IH_RELEASE(tmp);
1175                 return 0;
1176             }
1177         }
1178
1179         if ((code = OS_UNLINK(name.n_path)) == 0) {
1180             if (type == VI_LINKTABLE) {
1181                 /* Try to remove directory. If it fails, that's ok.
1182                  * Salvage will clean up.
1183                  */
1184                 char *slash = strrchr(name.n_path, OS_DIRSEPC);
1185                 if (slash) {
1186                     /* avoid an rmdir() on the file we just unlinked */
1187                     *slash = '\0';
1188                 }
1189                 (void)namei_RemoveDataDirectories(&name);
1190             }
1191         }
1192         FDH_REALLYCLOSE(fdP);
1193         IH_RELEASE(tmp);
1194     } else {
1195         /* Get a file descriptor handle for this Inode */
1196         fdP = IH_OPEN(ih);
1197         if (fdP == NULL) {
1198             return -1;
1199         }
1200
1201         if ((count = namei_GetLinkCount(fdP, ino, 1, 0, 1)) < 0) {
1202             FDH_REALLYCLOSE(fdP);
1203             return -1;
1204         }
1205
1206         count--;
1207         if (count >= 0) {
1208             if (namei_SetLinkCount(fdP, ino, count, 1) < 0) {
1209                 FDH_REALLYCLOSE(fdP);
1210                 return -1;
1211             }
1212         } else {
1213             IHandle_t *th;
1214             IH_INIT(th, ih->ih_dev, ih->ih_vid, ino);
1215             Log("Warning: Lost ref on ihandle dev %d vid %" AFS_VOLID_FMT " ino %lld\n",
1216                 th->ih_dev, afs_printable_VolumeId_lu(th->ih_vid), (afs_int64)th->ih_ino);
1217             IH_RELEASE(th);
1218
1219             /* If we're less than 0, someone presumably unlinked;
1220                don't bother setting count to 0, but we need to drop a lock */
1221             if (namei_SetLinkCount(fdP, ino, 0, 1) < 0) {
1222                 FDH_REALLYCLOSE(fdP);
1223                 return -1;
1224             }
1225         }
1226         if (count == 0) {
1227             IHandle_t *th;
1228             IH_INIT(th, ih->ih_dev, ih->ih_vid, ino);
1229
1230             namei_HandleToName(&name, th);
1231             IH_RELEASE(th);
1232             code = OS_UNLINK(name.n_path);
1233         }
1234         FDH_CLOSE(fdP);
1235     }
1236
1237     return code;
1238 }
1239
1240 int
1241 namei_inc(IHandle_t * h, Inode ino, int p1)
1242 {
1243     int count;
1244     int code = 0;
1245     FdHandle_t *fdP;
1246
1247     if ((ino & NAMEI_INODESPECIAL) == NAMEI_INODESPECIAL) {
1248         int type = (int)((ino >> NAMEI_TAGSHIFT) & NAMEI_TAGMASK);
1249         if (type != VI_LINKTABLE)
1250             return 0;
1251         ino = (Inode) 0;
1252     }
1253
1254     /* Get a file descriptor handle for this Inode */
1255     fdP = IH_OPEN(h);
1256     if (fdP == NULL) {
1257         return -1;
1258     }
1259
1260     if ((count = namei_GetLinkCount(fdP, ino, 1, 0, 1)) < 0)
1261         code = -1;
1262     else {
1263         count++;
1264         if (count > 7) {
1265             errno = OS_ERROR(EINVAL);
1266             code = -1;
1267             count = 7;
1268         }
1269         if (namei_SetLinkCount(fdP, ino, count, 1) < 0)
1270             code = -1;
1271     }
1272     if (code) {
1273         FDH_REALLYCLOSE(fdP);
1274     } else {
1275         FDH_CLOSE(fdP);
1276     }
1277     return code;
1278 }
1279
1280 #ifndef AFS_NT40_ENV
1281 int
1282 namei_replace_file_by_hardlink(IHandle_t *hLink, IHandle_t *hTarget)
1283 {
1284     afs_int32 code;
1285     namei_t nameLink;
1286     namei_t nameTarget;
1287
1288     /* Convert handle to file name. */
1289     namei_HandleToName(&nameLink, hLink);
1290     namei_HandleToName(&nameTarget, hTarget);
1291
1292     OS_UNLINK(nameLink.n_path);
1293     code = link(nameTarget.n_path, nameLink.n_path);
1294     return code;
1295 }
1296
1297 int
1298 namei_copy_on_write(IHandle_t *h)
1299 {
1300     afs_int32 code = 0;
1301     FD_t fd;
1302     namei_t name;
1303     FdHandle_t *fdP;
1304     struct afs_stat_st tstat;
1305     afs_foff_t offset;
1306
1307     namei_HandleToName(&name, h);
1308     if (afs_stat(name.n_path, &tstat) < 0)
1309         return EIO;
1310     if (tstat.st_nlink > 1) {                   /* do a copy on write */
1311         char path[259];
1312         char *buf;
1313         afs_size_t size;
1314         ssize_t tlen;
1315
1316         fdP = IH_OPEN(h);
1317         if (!fdP)
1318             return EIO;
1319         snprintf(path, sizeof(path), "%s-tmp", name.n_path);
1320         fd = OS_OPEN(path, O_CREAT | O_EXCL | O_RDWR, 0);
1321         if (fd == INVALID_FD) {
1322             FDH_CLOSE(fdP);
1323             return EIO;
1324         }
1325         buf = malloc(8192);
1326         if (!buf) {
1327             OS_CLOSE(fd);
1328             OS_UNLINK(path);
1329             FDH_CLOSE(fdP);
1330             return ENOMEM;
1331         }
1332         size = tstat.st_size;
1333         offset = 0;
1334         while (size) {
1335             tlen = size > 8192 ? 8192 : size;
1336             if (FDH_PREAD(fdP, buf, tlen, offset) != tlen)
1337                 break;
1338             if (OS_WRITE(fd, buf, tlen) != tlen)
1339                 break;
1340             size -= tlen;
1341             offset += tlen;
1342         }
1343         OS_CLOSE(fd);
1344         FDH_REALLYCLOSE(fdP);
1345         free(buf);
1346         if (size)
1347             code = EIO;
1348         else {
1349             OS_UNLINK(name.n_path);
1350             code = rename(path, name.n_path);
1351         }
1352     }
1353     return code;
1354 }
1355 #endif
1356
1357 /************************************************************************
1358  * File Name Structure
1359  ************************************************************************
1360  *
1361  * Each AFS file needs a unique name and it needs to be findable with
1362  * minimal lookup time. Note that the constraint on the number of files and
1363  * directories in a volume is the size of the vnode index files and the
1364  * max file size AFS supports (for internal files) of 2^31. Since a record
1365  * in the small vnode index file is 64 bytes long, we can have at most
1366  * (2^31)/64 or 33554432 files. A record in the large index file is
1367  * 256 bytes long, giving a maximum of (2^31)/256 = 8388608 directories.
1368  * Another layout parameter is that there is roughly a 16 to 1 ratio between
1369  * the number of files and the number of directories.
1370  *
1371  * Using this information we can see that a layout of 256 directories, each
1372  * with 512 subdirectories and each of those having 512 files gives us
1373  * 256*512*512 = 67108864 AFS files and directories.
1374  *
1375  * The volume, vnode, uniquifier and data version, as well as the tag
1376  * are required, either for finding the file or for salvaging. It's best to
1377  * restrict the name to something that can be mapped into 64 bits so the
1378  * "Inode" is easily comparable (using "==") to other "Inodes". The tag
1379  * is used to distinguish between different versions of the same file
1380  * which are currently in the RW and clones of a volume. See "Link Table
1381  * Organization" below for more information on the tag. The tag is
1382  * required in the name of the file to ensure a unique name.
1383  *
1384  * ifdef AFS_NT40_ENV
1385  * The data for each volume group is in a separate directory. The name of the
1386  * volume is of the form: Vol_NNNNNN.data, where NNNNNN is a base 32
1387  * representation of the RW volume ID (even where the RO is the only volume
1388  * on the partition). Below that are separate subdirectories for the
1389  * AFS directories and special files. There are also 16 directories for files,
1390  * hashed on the low 5 bits (recall bit0 is always 0) of the vnode number.
1391  * These directories are named:
1392  * A - P - 16 file directories.
1393  * Q ----- data directory
1394  * R ----- special files directory
1395  *
1396  * The vnode is hashed into the directory using the low bits of the
1397  * vnode number.
1398  *
1399  * The format of a file name for a regular file is:
1400  * Y:\Vol_NNNNNN.data\X\V_IIIIII.J
1401  * Y - partition encoded as drive letter, starting with D
1402  * NNNNNN - base 32 encoded volume number of RW volume
1403  * X - hash directory, as above
1404  * IIIIII - base 32 encoded vnode number
1405  * J - base 32 encoded tag
1406  *
1407  * uniq is stored in the dwHighDateTime creation time field
1408  * dv is stored in the dwLowDateTime creation time field
1409  *
1410  * Special inodes are always in the R directory, as above, and are
1411  * encoded:
1412  * True child volid is stored in the dwHighDateTime creation time field
1413  * vnode number is always -1 (Special)
1414  * type is the IIIIII part of the filename
1415  * uniq is the J part of the filename
1416  * parent volume id is implied in the containing directory
1417  *
1418  * else
1419  * We can store data in the uid, gid and mode bits of the files, provided
1420  * the directories have root only access. This gives us 15 bits for each
1421  * of uid and gid (GNU chown considers 65535 to mean "don't change").
1422  * There are 9 available mode bits. Adn we need to store a total of
1423  * 32 (volume id) + 26 (vnode) + 32 (uniquifier) + 32 (data-version) + 3 (tag)
1424  * or 131 bits somewhere.
1425  *
1426  * The format of a file name for a regular file is:
1427  * /vicepX/AFSIDat/V1/V2/AA/BB/<tag><uniq><vno>
1428  * V1 - low 8 bits of RW volume id
1429  * V2 - all bits of RW volume id
1430  * AA - high 8 bits of vnode number.
1431  * BB - next 9 bits of vnode number.
1432  * <tag><uniq><vno> - file name
1433  *
1434  * Volume special files are stored in a separate directory:
1435  * /vicepX/AFSIDat/V1/V2/special/<tag><uniq><vno>
1436  *
1437  *
1438  * The vnode is hashed into the directory using the high bits of the
1439  * vnode number. This is so that consecutively created vnodes are in
1440  * roughly the same area on the disk. This will at least be optimal if
1441  * the user is creating many files in the same AFS directory. The name
1442  * should be formed so that the leading characters are different as quickly
1443  * as possible, leading to faster discards of incorrect matches in the
1444  * lookup code.
1445  *
1446  * endif
1447  *
1448  */
1449
1450
1451 /************************************************************************
1452  *  Link Table Organization
1453  ************************************************************************
1454  *
1455  * The link table volume special file is used to hold the link counts that
1456  * are held in the inodes in inode based AFS vice filesystems. For user
1457  * space access, the link counts are being kept in a separate
1458  * volume special file. The file begins with the usual version stamp
1459  * information and is then followed by one row per vnode number. vnode 0
1460  * is used to hold the link count of the link table itself. That is because
1461  * the same link table is shared among all the volumes of the volume group
1462  * and is deleted only when the last volume of a volume group is deleted.
1463  *
1464  * Within each row, the columns are 3 bits wide. They can each hold a 0 based
1465  * link count from 0 through 7. Each colume represents a unique instance of
1466  * that vnode. Say we have a file shared between the RW and a RO and a
1467  * different version of the file (or a different uniquifer) for the BU volume.
1468  * Then one column would be holding the link count of 2 for the RW and RO
1469  * and a different column would hold the link count of 1 for the BU volume.
1470  * # ifdef AFS_NT40_ENV
1471  * The column used is determined for NT by the uniquifier tag applied to
1472  * generate a unique file name in the NTFS namespace. The file name is
1473  * of the form "V_<vno>.<tag>" . And the <tag> is also the column number
1474  * in the link table.
1475  * # else
1476  * Note that we allow only 5 volumes per file, giving 15 bits used in the
1477  * short.
1478  * # endif
1479  */
1480 #define LINKTABLE_WIDTH 2
1481 #define LINKTABLE_SHIFT 1       /* log 2 = 1 */
1482
1483 /**
1484  * compute namei link table file and bit offset from inode number.
1485  *
1486  * @param[in]   ino     inode number
1487  * @param[out]  offset  link table file offset
1488  * @param[out]  index   bit offset within 2-byte record
1489  *
1490  * @internal
1491  */
1492 static void
1493 namei_GetLCOffsetAndIndexFromIno(Inode ino, afs_foff_t * offset, int *index)
1494 {
1495     int toff = (int)(ino & NAMEI_VNODEMASK);
1496     int tindex = (int)((ino >> NAMEI_TAGSHIFT) & NAMEI_TAGMASK);
1497
1498     *offset = (afs_foff_t) ((toff << LINKTABLE_SHIFT) + 8);     /* * 2 + sizeof stamp */
1499     *index = (tindex << 1) + tindex;
1500 }
1501
1502 #ifdef AFS_PTHREAD_ENV
1503 /* XXX do static initializers work for WINNT/pthread? */
1504 pthread_mutex_t _namei_glc_lock = PTHREAD_MUTEX_INITIALIZER;
1505 #define NAMEI_GLC_LOCK opr_mutex_enter(&_namei_glc_lock)
1506 #define NAMEI_GLC_UNLOCK opr_mutex_exit(&_namei_glc_lock)
1507 #else /* !AFS_PTHREAD_ENV */
1508 #define NAMEI_GLC_LOCK
1509 #define NAMEI_GLC_UNLOCK
1510 #endif /* !AFS_PTHREAD_ENV */
1511
1512 /**
1513  * get the link count of an inode.
1514  *
1515  * @param[in]  h        namei link count table file handle
1516  * @param[in]  ino      inode number for which we are requesting a link count
1517  * @param[in]  lockit   if asserted, return with lock held on link table file
1518  * @param[in]  fixup    if asserted, write 1 to link count when read() returns
1519  *                      zero (at EOF)
1520  * @param[in]  nowrite  return success on zero byte read or ZLC
1521  *
1522  * @post if lockit asserted and lookup was successful, will return with write
1523  *       lock on link table file descriptor
1524  *
1525  * @return link count
1526  *    @retval -1 namei link table i/o error
1527  *
1528  * @internal
1529  */
1530 int
1531 namei_GetLinkCount(FdHandle_t * h, Inode ino, int lockit, int fixup, int nowrite)
1532 {
1533     unsigned short row = 0;
1534     afs_foff_t offset;
1535     ssize_t rc;
1536     int index;
1537
1538     /* there's no linktable yet. the salvager will create one later */
1539     if (h->fd_fd == INVALID_FD && fixup)
1540        return 1;
1541     namei_GetLCOffsetAndIndexFromIno(ino, &offset, &index);
1542
1543     if (lockit) {
1544         if (FDH_LOCKFILE(h, offset) != 0)
1545             return -1;
1546     }
1547
1548     rc = FDH_PREAD(h, (char*)&row, sizeof(row), offset);
1549     if (rc == -1)
1550         goto bad_getLinkByte;
1551
1552     if ((rc == 0 || !((row >> index) & NAMEI_TAGMASK)) && fixup && nowrite)
1553         return 1;
1554     if (rc == 0 && fixup) {
1555         /*
1556          * extend link table and write a link count of 1 for ino
1557          *
1558          * in order to make MT-safe, truncation (extension really)
1559          * must happen under a mutex
1560          */
1561         NAMEI_GLC_LOCK;
1562         if (FDH_SIZE(h) >= offset+sizeof(row)) {
1563             NAMEI_GLC_UNLOCK;
1564             goto bad_getLinkByte;
1565         }
1566         FDH_TRUNC(h, offset+sizeof(row));
1567         row = 1 << index;
1568         rc = FDH_PWRITE(h, (char *)&row, sizeof(row), offset);
1569         NAMEI_GLC_UNLOCK;
1570     }
1571     if (rc != sizeof(row)) {
1572         goto bad_getLinkByte;
1573     }
1574
1575     if (fixup && !((row >> index) & NAMEI_TAGMASK)) {
1576         /*
1577          * fix up zlc
1578          *
1579          * in order to make this mt-safe, we need to do the read-modify-write
1580          * under a mutex.  thus, we repeat the read inside the lock.
1581          */
1582         NAMEI_GLC_LOCK;
1583         rc = FDH_PREAD(h, (char *)&row, sizeof(row), offset);
1584         if (rc == sizeof(row)) {
1585             row |= 1<<index;
1586             rc = FDH_PWRITE(h, (char *)&row, sizeof(row), offset);
1587         }
1588         NAMEI_GLC_UNLOCK;
1589         if (rc != sizeof(row))
1590             goto bad_getLinkByte;
1591     }
1592
1593     return (int)((row >> index) & NAMEI_TAGMASK);
1594
1595   bad_getLinkByte:
1596     if (lockit)
1597         FDH_UNLOCKFILE(h, offset);
1598     return -1;
1599 }
1600
1601 int
1602 namei_SetNonZLC(FdHandle_t * h, Inode ino)
1603 {
1604     return namei_GetLinkCount(h, ino, 0, 1, 0);
1605 }
1606
1607 /* Return a free column index for this vnode. */
1608 static int
1609 GetFreeTag(IHandle_t * ih, int vno)
1610 {
1611     FdHandle_t *fdP;
1612     afs_foff_t offset;
1613     int col;
1614     int coldata;
1615     short row;
1616     ssize_t nBytes;
1617
1618
1619     fdP = IH_OPEN(ih);
1620     if (fdP == NULL)
1621         return -1;
1622
1623     /* Only one manipulates at a time. */
1624     if (FDH_LOCKFILE(fdP, offset) != 0) {
1625         FDH_REALLYCLOSE(fdP);
1626         return -1;
1627     }
1628
1629     offset = (vno << LINKTABLE_SHIFT) + 8;      /* * 2 + sizeof stamp */
1630
1631     nBytes = FDH_PREAD(fdP, (char *)&row, sizeof(row), offset);
1632     if (nBytes != sizeof(row)) {
1633         if (nBytes != 0)
1634             goto badGetFreeTag;
1635         row = 0;
1636     }
1637
1638     /* Now find a free column in this row and claim it. */
1639     for (col = 0; col < NAMEI_MAXVOLS; col++) {
1640         coldata = 7 << (col * 3);
1641         if ((row & coldata) == 0)
1642             break;
1643     }
1644     if (col >= NAMEI_MAXVOLS) {
1645         errno = ENOSPC;
1646         goto badGetFreeTag;
1647     }
1648
1649     coldata = 1 << (col * 3);
1650     row |= coldata;
1651
1652     if (FDH_PWRITE(fdP, (char *)&row, sizeof(row), offset) != sizeof(row)) {
1653         goto badGetFreeTag;
1654     }
1655     (void)FDH_SYNC(fdP);
1656     FDH_UNLOCKFILE(fdP, offset);
1657     FDH_CLOSE(fdP);
1658     return col;
1659
1660   badGetFreeTag:
1661     FDH_UNLOCKFILE(fdP, offset);
1662     FDH_REALLYCLOSE(fdP);
1663     return -1;
1664 }
1665
1666
1667
1668 /* namei_SetLinkCount
1669  * If locked is set, assume file is locked. Otherwise, lock file before
1670  * proceeding to modify it.
1671  */
1672 int
1673 namei_SetLinkCount(FdHandle_t * fdP, Inode ino, int count, int locked)
1674 {
1675     afs_foff_t offset;
1676     int index;
1677     unsigned short row;
1678     int bytesRead;
1679     ssize_t nBytes = -1;
1680
1681     namei_GetLCOffsetAndIndexFromIno(ino, &offset, &index);
1682
1683     if (!locked) {
1684         if (FDH_LOCKFILE(fdP, offset) != 0) {
1685             return -1;
1686         }
1687     }
1688
1689     nBytes = FDH_PREAD(fdP, (char *)&row, sizeof(row), offset);
1690     if (nBytes != sizeof(row)) {
1691         if (nBytes != 0) {
1692             errno = OS_ERROR(EBADF);
1693             goto bad_SetLinkCount;
1694         }
1695         row = 0;
1696     }
1697
1698     bytesRead = 7 << index;
1699     count <<= index;
1700     row &= (unsigned short)~bytesRead;
1701     row |= (unsigned short)count;
1702
1703     if (FDH_PWRITE(fdP, (char *)&row, sizeof(short), offset) != sizeof(short)) {
1704         errno = OS_ERROR(EBADF);
1705         goto bad_SetLinkCount;
1706     }
1707     (void)FDH_SYNC(fdP);
1708
1709     nBytes = 0;
1710
1711
1712   bad_SetLinkCount:
1713     FDH_UNLOCKFILE(fdP, offset);
1714
1715     /* disallowed above 7, so... */
1716     return (int)nBytes;
1717 }
1718
1719
1720 /* ListViceInodes - write inode data to a results file. */
1721 static int DecodeInode(char *dpath, char *name, struct ViceInodeInfo *info,
1722                        VolumeId volid);
1723 static int DecodeVolumeName(char *name, VolumeId *vid);
1724 static int namei_ListAFSSubDirs(IHandle_t * dirIH,
1725                                 int (*write_fun) (FD_t,
1726                                                   struct ViceInodeInfo *,
1727                                                   char *, char *), FD_t fp,
1728                                 int (*judgeFun) (struct ViceInodeInfo *,
1729                                                  VolumeId vid, void *),
1730                                 VolumeId singleVolumeNumber, void *rock);
1731
1732
1733 /* WriteInodeInfo
1734  *
1735  * Write the inode data to the results file.
1736  *
1737  * Returns -2 on error, 0 on success.
1738  *
1739  * This is written as a callback simply so that other listing routines
1740  * can use the same inode reading code.
1741  */
1742 static int
1743 WriteInodeInfo(FD_t fp, struct ViceInodeInfo *info, char *dir, char *name)
1744 {
1745     size_t n;
1746     n = OS_WRITE(fp, info, sizeof(*info));
1747     return (n == sizeof(*info)) ? 0 : -2;
1748 }
1749
1750
1751 int mode_errors;                /* Number of errors found in mode bits on directories. */
1752 void
1753 VerifyDirPerms(char *path)
1754 {
1755     struct afs_stat_st status;
1756
1757     if (afs_stat(path, &status) < 0) {
1758         Log("Unable to stat %s. Please manually verify mode bits for this"
1759             " directory\n", path);
1760     } else {
1761         if (((status.st_mode & 0777) != 0700) || (status.st_uid != 0))
1762             mode_errors++;
1763     }
1764 }
1765
1766 /**
1767  * Fill the results file with the requested inode information.
1768  *
1769  * This code optimizes single volume salvages by just looking at that one
1770  * volume's directory.
1771  *
1772  * @param[in]   devname             device name string
1773  * @param[in]   moutnedOn           vice partition mount point
1774  * @param[in]   resultFile          result file in which to write inode
1775  *                                  metadata.  If NULL, write routine is not
1776  *                                  called.
1777  * @param[in]   judgeInode          filter function pointer.  if not NULL, only
1778  *                                  inodes for which this routine returns non-
1779  *                                  zero will be written to the results file.
1780  * @param[in]   singleVolumeNumber  volume id filter
1781  * @param[out]  forcep              always set to 0 for namei impl
1782  * @param[in]   forceR              not used by namei impl
1783  * @param[in]   wpath               not used by namei impl
1784  * @param[in]   rock                opaque pointer passed to judgeInode
1785  *
1786  * @return operation status
1787  *    @retval 0   success
1788  *    @retval -1  complete failure, salvage should terminate.
1789  *    @retval -2  not enough space on partition, salvager has error message
1790  *                for this.
1791  */
1792 int
1793 ListViceInodes(char *devname, char *mountedOn, FD_t inodeFile,
1794                int (*judgeInode) (struct ViceInodeInfo * info, VolumeId vid, void *rock),
1795                VolumeId singleVolumeNumber, int *forcep, int forceR, char *wpath,
1796                void *rock)
1797 {
1798     int ninodes;
1799
1800     *forcep = 0; /* no need to salvage until further notice */
1801
1802     /* Verify protections on directories. */
1803     mode_errors = 0;
1804     VerifyDirPerms(mountedOn);
1805
1806     ninodes =
1807         namei_ListAFSFiles(mountedOn, WriteInodeInfo, inodeFile, judgeInode,
1808                            singleVolumeNumber, rock);
1809
1810     if (inodeFile == INVALID_FD)
1811         return ninodes;
1812
1813     if (ninodes < 0) {
1814         return ninodes;
1815     }
1816
1817     if (OS_SYNC(inodeFile) == -1) {
1818         Log("Unable to successfully fsync inode file for %s\n", mountedOn);
1819         return -2;
1820     }
1821
1822     /*
1823      * Paranoia:  check that the file is really the right size
1824      */
1825     if (OS_SIZE(inodeFile) != ninodes * sizeof(struct ViceInodeInfo)) {
1826         Log("Wrong size (%d instead of %lu) in inode file for %s\n",
1827             (int) OS_SIZE(inodeFile),
1828             (long unsigned int) ninodes * sizeof(struct ViceInodeInfo),
1829             mountedOn);
1830         return -2;
1831     }
1832     return 0;
1833 }
1834
1835
1836 /**
1837  * Collect all the matching AFS files on the drive.
1838  * If singleVolumeNumber is non-zero, just return files for that volume.
1839  *
1840  * @param[in] dev                 vice partition path
1841  * @param[in] writeFun            function pointer to a function which
1842  *                                writes inode information to FILE fp
1843  * @param[in] fp                  file stream where inode metadata is sent
1844  * @param[in] judgeFun            filter function pointer.  if not NULL,
1845  *                                only entries for which a non-zero value
1846  *                                is returned are written to fp
1847  * @param[in] singleVolumeNumber  volume id filter.  if nonzero, only
1848  *                                process files for that specific volume id
1849  * @param[in] rock                opaque pointer passed into writeFun and
1850  *                                judgeFun
1851  *
1852  * @return operation status
1853  *    @retval <0 error
1854  *    @retval >=0 number of matching files found
1855  */
1856 int
1857 namei_ListAFSFiles(char *dev,
1858                    int (*writeFun) (FD_t, struct ViceInodeInfo *, char *,
1859                                     char *),
1860                    FD_t fp,
1861                    int (*judgeFun) (struct ViceInodeInfo *, VolumeId, void *),
1862                    VolumeId singleVolumeNumber, void *rock)
1863 {
1864     IHandle_t ih;
1865     namei_t name;
1866     int ninodes = 0;
1867     DIR *dirp1;
1868     struct dirent *dp1;
1869 #ifndef AFS_NT40_ENV
1870     DIR *dirp2;
1871     struct dirent *dp2;
1872     char path2[512];
1873 #endif
1874 #ifdef DELETE_ZLC
1875     static void FreeZLCList(void);
1876 #endif
1877
1878     memset((void *)&ih, 0, sizeof(IHandle_t));
1879 #ifdef AFS_NT40_ENV
1880     ih.ih_dev = nt_DriveToDev(dev);
1881 #else
1882     ih.ih_dev = volutil_GetPartitionID(dev);
1883 #endif
1884
1885     if (singleVolumeNumber) {
1886         ih.ih_vid = singleVolumeNumber;
1887         namei_HandleToVolDir(&name, &ih);
1888         ninodes =
1889             namei_ListAFSSubDirs(&ih, writeFun, fp, judgeFun,
1890                                  singleVolumeNumber, rock);
1891         if (ninodes < 0)
1892             return ninodes;
1893     } else {
1894         /* Find all volume data directories and descend through them. */
1895         namei_HandleToInodeDir(&name, &ih);
1896         ninodes = 0;
1897         dirp1 = opendir(name.n_path);
1898         if (!dirp1)
1899             return 0;
1900         while ((dp1 = readdir(dirp1))) {
1901 #ifdef AFS_NT40_ENV
1902             /* Heirarchy is one level on Windows */
1903             if (!DecodeVolumeName(dp1->d_name, &ih.ih_vid)) {
1904                 ninodes +=
1905                     namei_ListAFSSubDirs(&ih, writeFun, fp, judgeFun,
1906                                          0, rock);
1907             }
1908 #else
1909             if (*dp1->d_name == '.')
1910                 continue;
1911             snprintf(path2, sizeof(path2), "%s" OS_DIRSEP "%s", name.n_path,
1912                      dp1->d_name);
1913             dirp2 = opendir(path2);
1914             if (dirp2) {
1915                 while ((dp2 = readdir(dirp2))) {
1916                     if (*dp2->d_name == '.')
1917                         continue;
1918                     if (!DecodeVolumeName(dp2->d_name, &ih.ih_vid)) {
1919                         ninodes +=
1920                             namei_ListAFSSubDirs(&ih, writeFun, fp, judgeFun,
1921                                                  0, rock);
1922                     }
1923                 }
1924                 closedir(dirp2);
1925             }
1926 #endif
1927         }
1928         closedir(dirp1);
1929     }
1930 #ifdef DELETE_ZLC
1931     FreeZLCList();
1932 #endif
1933     return ninodes;
1934 }
1935
1936 #ifdef DELETE_ZLC
1937 static void AddToZLCDeleteList(char dir, char *name);
1938 static void DeleteZLCFiles(char *path);
1939 #endif
1940
1941 /**
1942  * examine a namei volume special file.
1943  *
1944  * @param[in] path1               volume special directory path
1945  * @param[in] dname               directory entry name
1946  * @param[in] myIH                inode handle to volume directory
1947  * @param[out] linkHandle         namei link count fd handle.  if
1948  *                                the inode in question is the link
1949  *                                table, then the FdHandle is populated
1950  * @param[in] writeFun            metadata write function pointer
1951  * @param[in] fp                  file pointer where inode metadata
1952  *                                is written by (*writeFun)()
1953  * @param[in] judgeFun            inode filter function pointer.  if
1954  *                                not NULL, only inodes for which this
1955  *                                function returns non-zero are recorded
1956  *                                into fp by writeFun
1957  * @param[in] singleVolumeNumer   volume id filter.  if non-zero, only
1958  *                                inodes associated with this volume id
1959  *                                are recorded by writeFun
1960  * @param[in] rock                opaque pointer passed to writeFun and
1961  *                                judgeFun
1962  *
1963  * @return operation status
1964  *    @retval 1 count this inode
1965  *    @retval 0 don't count this inode
1966  *    @retval -1 failure
1967  *
1968  * @internal
1969  */
1970 static int
1971 _namei_examine_special(char * path1,
1972                        char * dname,
1973                        IHandle_t * myIH,
1974                        FdHandle_t * linkHandle,
1975                        int (*writeFun) (FD_t, struct ViceInodeInfo *, char *,
1976                                         char *),
1977                        FD_t fp,
1978                        int (*judgeFun) (struct ViceInodeInfo *, VolumeId, void *),
1979                        VolumeId singleVolumeNumber,
1980                        void *rock)
1981 {
1982     int ret = 0;
1983     struct ViceInodeInfo info;
1984
1985     if (DecodeInode(path1, dname, &info, myIH->ih_vid) < 0) {
1986         ret = 0;
1987         goto error;
1988     }
1989
1990     if (info.u.param[2] != VI_LINKTABLE) {
1991         info.linkCount = 1;
1992     } else if (info.u.param[0] != myIH->ih_vid) {
1993         /* VGID encoded in linktable filename and/or OGM data isn't
1994          * consistent with VGID encoded in namei path */
1995         Log("namei_ListAFSSubDirs: warning: inconsistent linktable "
1996             "filename \"%s" OS_DIRSEP "%s\"; salvager will delete it "
1997             "(dir_vgid=%" AFS_VOLID_FMT ", inode_vgid=%" AFS_VOLID_FMT ")\n",
1998             path1, dname, afs_printable_VolumeId_lu(myIH->ih_vid),
1999             afs_printable_VolumeId_lu(info.u.param[0]));
2000     } else {
2001         char path2[512];
2002         /* Open this handle */
2003         snprintf(path2, sizeof(path2),
2004                  "%s" OS_DIRSEP "%s", path1, dname);
2005         linkHandle->fd_fd = OS_OPEN(path2, Testing ? O_RDONLY : O_RDWR, 0666);
2006         info.linkCount =
2007             namei_GetLinkCount(linkHandle, (Inode) 0, 1, 1, Testing);
2008     }
2009
2010     if (!judgeFun ||
2011         (*judgeFun) (&info, singleVolumeNumber, rock)) {
2012         ret = (*writeFun) (fp, &info, path1, dname);
2013         if (ret < 0) {
2014             Log("_namei_examine_special: writeFun returned %d\n", ret);
2015             ret = -1;
2016         } else {
2017             ret = 1;
2018         }
2019     }
2020
2021  error:
2022     return ret;
2023 }
2024
2025 /**
2026  * examine a namei file.
2027  *
2028  * @param[in] path3               volume special directory path
2029  * @param[in] dname               directory entry name
2030  * @param[in] myIH                inode handle to volume directory
2031  * @param[in] linkHandle          namei link count fd handle.
2032  * @param[in] writeFun            metadata write function pointer
2033  * @param[in] fp                  file pointer where inode metadata
2034  *                                is written by (*writeFun)()
2035  * @param[in] judgeFun            inode filter function pointer.  if
2036  *                                not NULL, only inodes for which this
2037  *                                function returns non-zero are recorded
2038  *                                into fp by writeFun
2039  * @param[in] singleVolumeNumer   volume id filter.  if non-zero, only
2040  *                                inodes associated with this volume id
2041  *                                are recorded by writeFun
2042  * @param[in] rock                opaque pointer passed to writeFun and
2043  *                                judgeFun
2044  *
2045  * @return operation status
2046  *    @retval 1 count this inode
2047  *    @retval 0 don't count this inode
2048  *    @retval -1 failure
2049  *    @retval -2 request ZLC delete
2050  *
2051  * @internal
2052  */
2053 static int
2054 _namei_examine_reg(char * path3,
2055                    char * dname,
2056                    IHandle_t * myIH,
2057                    FdHandle_t * linkHandle,
2058                    int (*writeFun) (FD_t, struct ViceInodeInfo *, char *,
2059                                     char *),
2060                    FD_t fp,
2061                    int (*judgeFun) (struct ViceInodeInfo *, VolumeId, void *),
2062                    VolumeId singleVolumeNumber,
2063                    void *rock)
2064 {
2065     int ret = 0;
2066     struct ViceInodeInfo info;
2067 #ifdef DELETE_ZLC
2068     int dirl; /* Windows-only (one level hash dir) */
2069 #endif
2070
2071     if (DecodeInode(path3, dname, &info, myIH->ih_vid) < 0) {
2072         goto error;
2073     }
2074
2075     info.linkCount =
2076         namei_GetLinkCount(linkHandle,
2077                             info.inodeNumber, 1, 1, Testing);
2078     if (info.linkCount == 0) {
2079 #ifdef DELETE_ZLC
2080         Log("Found 0 link count file %s" OS_DIRSEP "%s, deleting it.\n", path3, dname);
2081 #ifdef AFS_SALSRV_ENV
2082         /* defer -- the AddToZLCDeleteList() interface is not MT-safe */
2083         ret = -2;
2084 #else /* !AFS_SALSRV_ENV */
2085         dirl = path3[strlen(path3)-1];
2086         AddToZLCDeleteList((char)dirl, dname);
2087 #endif /* !AFS_SALSRV_ENV */
2088 #else /* !DELETE_ZLC */
2089         Log("Found 0 link count file %s" OS_DIRSEP "%s.\n", path3,
2090             dname);
2091 #endif
2092         goto error;
2093     }
2094
2095     if (!judgeFun ||
2096         (*judgeFun) (&info, singleVolumeNumber, rock)) {
2097         ret = (*writeFun) (fp, &info, path3, dname);
2098         if (ret < 0) {
2099             Log("_namei_examine_reg: writeFun returned %d\n", ret);
2100             ret = -1;
2101         } else {
2102             ret = 1;
2103         }
2104     }
2105
2106  error:
2107     return ret;
2108 }
2109
2110 /**
2111  * listsubdirs work queue node.
2112  */
2113 struct listsubdirs_work_node {
2114 #ifdef AFS_SALSRV_ENV
2115     int *error;                         /**< *error set if an error was
2116                                          *   encountered in any listsubdirs
2117                                          *   thread. */
2118 #endif
2119
2120     IHandle_t * IH;                     /**< volume directory handle */
2121     FdHandle_t *linkHandle;             /**< namei link count fd handle. when
2122                                          *   examinining the link table special
2123                                          *   inode, this will be pointed at the
2124                                          *   link table
2125                                          */
2126     FD_t fp;                            /**< file pointer for writeFun */
2127
2128     /** function which will write inode metadata to fp */
2129     int (*writeFun) (FD_t, struct ViceInodeInfo *, char *, char *);
2130
2131     /** inode filter function */
2132     int (*judgeFun) (struct ViceInodeInfo *, VolumeId, void *);
2133     VolumeId singleVolumeNumber;             /**< volume id filter */
2134     void * rock;                        /**< pointer passed to writeFun and judgeFun */
2135     int code;                           /**< return code from examine function */
2136     int special;                        /**< asserted when this is a volume
2137                                          *   special file */
2138 };
2139
2140 /**
2141  * simple wrapper around _namei_examine_special and _namei_examine_reg.
2142  *
2143  * @param[in] work  the struct listsubdirs_work_node for the associated
2144  *                  "list subdirs" job
2145  * @param[in] dir   the directory to examine
2146  * @param[in] filename  the filename in 'dir' to examine
2147  *
2148  * @return operation status
2149  *   @retval 1  count this inode
2150  *   @retval 0  don't count this inode
2151  *   @retval -1 failure
2152  */
2153 static_inline int
2154 _namei_examine_file(const struct listsubdirs_work_node *work, char *dir,
2155                     char *filename)
2156 {
2157     if (work->special) {
2158         return _namei_examine_special(dir, filename, work->IH,
2159                                       work->linkHandle, work->writeFun, work->fp,
2160                                       work->judgeFun, work->singleVolumeNumber,
2161                                       work->rock);
2162     } else {
2163         return _namei_examine_reg(dir, filename, work->IH,
2164                                   work->linkHandle, work->writeFun, work->fp,
2165                                   work->judgeFun, work->singleVolumeNumber,
2166                                   work->rock);
2167     }
2168 }
2169
2170
2171 #ifdef AFS_SALSRV_ENV
2172 /** @addtogroup afs_vol_salsrv_pario */
2173 /*@{*/
2174
2175 /**
2176  * arguments for the _namei_examine_file_cbk callback function.
2177  */
2178 struct listsubdirs_args {
2179     const struct listsubdirs_work_node *work; /**< arguments that are the same
2180                                                *   for all invocations of
2181                                                *   _namei_examine_file_cbk, in
2182                                                *   threads */
2183     int *result;        /**< where we can store the return code of _namei_examine_file */
2184
2185     char dir[512];      /**< directory to examine */
2186     char filename[256]; /**< filename in 'dir' to examine */
2187 };
2188
2189 /**
2190  * a node in the list of results of listsubdir jobs.
2191  */
2192 struct listsubdirs_result {
2193     struct rx_queue q;
2194     int inodes;        /**< return value from _namei_examine_file */
2195 };
2196
2197 /**
2198  * clean up a list of 'struct listsubdirs_result's and interpret the results.
2199  *
2200  * @param[in] resultlist  a list of 'struct listsubdirs_result's
2201  *
2202  * @return number of inodes found
2203  *   @retval -1  error
2204  */
2205 static int
2206 _namei_listsubdirs_cleanup_results(struct rx_queue *resultlist)
2207 {
2208     struct listsubdirs_result *res, *nres;
2209     int ret = 0;
2210
2211     for(queue_Scan(resultlist, res, nres, listsubdirs_result)) {
2212         if (ret < 0) {
2213             /* noop, retain erroneous error code */
2214         } else if (res->inodes < 0) {
2215             ret = -1;
2216         } else {
2217             ret += res->inodes;
2218         }
2219
2220         queue_Remove(res);
2221         free(res);
2222         res = NULL;
2223     }
2224
2225     return ret;
2226 }
2227
2228 /**
2229  * wait for the spawned listsubdirs jobs to finish, and return how many inodes
2230  * they found.
2231  *
2232  * @param[in] queue    queue to wait to finish
2233  * @param[in] resultlist list of 'struct listsubdirs_result's that the queued
2234  *                       jobs are storing their results in
2235  *
2236  * @return number of inodes found
2237  *   @retval -1  error
2238  */
2239 static int
2240 _namei_listsubdirs_wait(struct afs_work_queue *queue, struct rx_queue *resultlist)
2241 {
2242     int code;
2243
2244     code = afs_wq_wait_all(queue);
2245     if (code) {
2246         return -1;
2247     }
2248
2249     return _namei_listsubdirs_cleanup_results(resultlist);
2250 }
2251
2252 /**
2253  * work queue entry point for examining namei files.
2254  *
2255  * @param[in] queue        pointer to struct Vwork_queue
2256  * @param[in] node         pointer to struct Vwork_queue_node
2257  * @param[in] queue_rock   opaque pointer to struct salsrv_pool_state
2258  * @param[in] node_rock    opaque pointer to struct listsubdirs_work_node
2259  * @param[in] caller_rock  opaque pointer to struct salsrv_worker_thread_state
2260  *
2261  * @return operation status
2262  *
2263  * @see Vwork_queue_callback_func_t
2264  *
2265  * @internal
2266  */
2267 static int
2268 _namei_examine_file_cbk(struct afs_work_queue *queue,
2269                         struct afs_work_queue_node *node,
2270                         void *queue_rock,
2271                         void *node_rock,
2272                         void *caller_rock)
2273 {
2274     int code;
2275     struct listsubdirs_args *args = node_rock;
2276     const struct listsubdirs_work_node * work = args->work;
2277     char *dir = args->dir;
2278     char *filename = args->filename;
2279
2280     code = _namei_examine_file(work, dir, filename);
2281
2282     *(args->result) = code;
2283
2284     if (code < 0) {
2285         *(work->error) = 1;
2286         /* we've errored, so no point in letting more jobs continue */
2287         afs_wq_shutdown(queue);
2288     }
2289
2290     return 0;
2291 }
2292
2293 static pthread_once_t wq_once = PTHREAD_ONCE_INIT;
2294 static pthread_key_t wq_key;
2295
2296 /**
2297  * create the wq_key key for storing a work queue.
2298  */
2299 static void
2300 _namei_wq_keycreate(void)
2301 {
2302     opr_Verify(pthread_key_create(&wq_key, NULL) == 0);
2303 }
2304
2305 /**
2306  * set the work queue for this thread to use for backgrounding namei ops.
2307  *
2308  * The work queue will be used in ListAFSSubdirs (called indirectly by
2309  * ListViceInodes) to examine files in parallel.
2310  *
2311  * @param[in] wq  the work queue to use
2312  */
2313 void
2314 namei_SetWorkQueue(struct afs_work_queue *wq)
2315 {
2316     opr_Verify(pthread_once(&wq_once, _namei_wq_keycreate) == 0);
2317
2318     opr_Verify(pthread_setspecific(wq_key, wq) == 0);
2319 }
2320
2321 /**
2322  * enqueue an examine file work unit.
2323  *
2324  * @param[in] work     the _namei_examine_file arguments that are common to
2325  *                     all callers within the same ListAFSFiles operation
2326  * @param[in] dir      the specific directory to look at (string will be
2327  *                     copied; can be stack/temporary memory)
2328  * @param[in] filename the filename to look at (string will be copied; can be
2329  *                     stack/temporary memory)
2330  * @param[in] wq       work queue to enqueue this work unit to
2331  * @param[in] resultlist the list to append the 'struct listsubdirs_result' to
2332  *                       for the enqueued work unit
2333  *
2334  * @return operation status
2335  *    @retval 0 success
2336  *    @retval -1 fatal error
2337  *
2338  * @note errors MUST be indicated by a -1 error code and nothing else, to be
2339  *       compatible with _namei_examine_reg and _namei_examine_special
2340  *
2341  * @internal
2342  */
2343 static int
2344 _namei_examine_file_spawn(const struct listsubdirs_work_node *work,
2345                           const char *dir, const char *filename,
2346                           struct afs_work_queue *wq,
2347                           struct rx_queue *resultlist)
2348 {
2349     int code, ret = 0;
2350     struct listsubdirs_args *args = NULL;
2351     struct listsubdirs_result *result = NULL;
2352     struct afs_work_queue_node *node = NULL;
2353     struct afs_work_queue_add_opts opts;
2354
2355     args = malloc(sizeof(*args));
2356     if (args == NULL) {
2357         ret = -1;
2358         goto error;
2359     }
2360
2361     result = malloc(sizeof(*result));
2362     if (result == NULL) {
2363         ret = -1;
2364         goto error;
2365     }
2366
2367     code = afs_wq_node_alloc(&node);
2368     if (code) {
2369         ret = -1;
2370         goto error;
2371     }
2372     code = afs_wq_node_set_detached(node);
2373     if (code) {
2374         ret = -1;
2375         goto error;
2376     }
2377
2378     args->work = work;
2379     args->result = &result->inodes;
2380     strlcpy(args->dir, dir, sizeof(args->dir));
2381     strlcpy(args->filename, filename, sizeof(args->filename));
2382
2383     code = afs_wq_node_set_callback(node,
2384                                          &_namei_examine_file_cbk,
2385                                          args, &free);
2386     if (code) {
2387         ret = -1;
2388         goto error;
2389     }
2390     args = NULL;
2391
2392     afs_wq_add_opts_init(&opts);
2393     opts.donate = 1;
2394
2395     code = afs_wq_add(wq, node, &opts);
2396     if (code) {
2397         ret = -1;
2398         goto error;
2399     }
2400     node = NULL;
2401
2402     queue_Append(resultlist, result);
2403     result = NULL;
2404
2405  error:
2406     if (node) {
2407         afs_wq_node_put(node);
2408         node = NULL;
2409     }
2410     if (args) {
2411         free(args);
2412         args = NULL;
2413     }
2414     if (result) {
2415         free(result);
2416         result = NULL;
2417     }
2418
2419     return ret;
2420 }
2421
2422 /*@}*/
2423 #else /* !AFS_SALSRV_ENV */
2424 # define _namei_examine_file_spawn(work, dir, file, wq, resultlist) \
2425          _namei_examine_file(work, dir, file)
2426 #endif /* !AFS_SALSRV_ENV */
2427
2428 /**
2429  * traverse and check inodes.
2430  *
2431  * @param[in] dirIH               volume group directory handle
2432  * @param[in] writeFun            function pointer which will write inode
2433  *                                metadata to FILE stream fp
2434  * @param[in] fp                  file stream where inode metadata gets
2435  *                                written
2436  * @param[in] judgeFun            inode filter function.  if not NULL, only
2437  *                                inodes for which the filter returns non-zero
2438  *                                will be written out by writeFun
2439  * @param[in] singleVolumeNumber  volume id filter.  only inodes matching this
2440  *                                filter are written out by writeFun
2441  * @param[in] rock                opaque pointer passed to judgeFun and writeFun
2442  *
2443  * @return operation status
2444  *    @retval <0 error
2445  *    @retval >=0 number of matching inodes found
2446  *
2447  * @todo the salsrv implementation may consume a lot of
2448  *       memory for a large volume.  at some point we should
2449  *       probably write a background thread to asynchronously
2450  *       clean up the resultlist nodes to reduce memory footprint
2451  *
2452  * @internal
2453  */
2454 static int
2455 namei_ListAFSSubDirs(IHandle_t * dirIH,
2456                      int (*writeFun) (FD_t, struct ViceInodeInfo *, char *,
2457                                       char *),
2458                      FD_t fp,
2459                      int (*judgeFun) (struct ViceInodeInfo *, VolumeId, void *),
2460                      VolumeId singleVolumeNumber, void *rock)
2461 {
2462     int code = 0, ret = 0;
2463     IHandle_t myIH = *dirIH;
2464     namei_t name;
2465     char path1[512], path3[512];
2466     DIR *dirp1, *dirp3;
2467 #ifndef AFS_NT40_ENV
2468     DIR *dirp2;
2469     struct dirent *dp2;
2470     char path2[512];
2471 #endif
2472     struct dirent *dp1, *dp3;
2473     FdHandle_t linkHandle;
2474     int ninodes = 0;
2475     struct listsubdirs_work_node work;
2476 #ifdef AFS_SALSRV_ENV
2477     int error = 0;
2478     struct afs_work_queue *wq;
2479     int wq_up = 0;
2480     struct rx_queue resultlist;
2481 #endif
2482
2483     namei_HandleToVolDir(&name, &myIH);
2484     strlcpy(path1, name.n_path, sizeof(path1));
2485
2486     /* Do the directory containing the special files first to pick up link
2487      * counts.
2488      */
2489     (void)strcat(path1, OS_DIRSEP);
2490     (void)strcat(path1, NAMEI_SPECDIR);
2491
2492     linkHandle.fd_fd = INVALID_FD;
2493 #ifdef AFS_SALSRV_ENV
2494     opr_Verify(pthread_once(&wq_once, _namei_wq_keycreate) == 0);
2495
2496     wq = pthread_getspecific(wq_key);
2497     if (!wq) {
2498         ret = -1;
2499         goto error;
2500     }
2501     wq_up = 1;
2502     queue_Init(&resultlist);
2503 #endif
2504
2505     memset(&work, 0, sizeof(work));
2506     work.linkHandle = &linkHandle;
2507     work.IH = &myIH;
2508     work.fp = fp;
2509     work.writeFun = writeFun;
2510     work.judgeFun = judgeFun;
2511     work.singleVolumeNumber = singleVolumeNumber;
2512     work.rock = rock;
2513     work.special = 1;
2514 #ifdef AFS_SALSRV_ENV
2515     work.error = &error;
2516 #endif
2517
2518     dirp1 = opendir(path1);
2519     if (dirp1) {
2520         while ((dp1 = readdir(dirp1))) {
2521             if (*dp1->d_name == '.')
2522                 continue;
2523
2524 #ifdef AFS_SALSRV_ENV
2525             if (error) {
2526                 closedir(dirp1);
2527                 ret = -1;
2528                 goto error;
2529             }
2530 #endif /* AFS_SALSRV_ENV */
2531
2532             code = _namei_examine_file_spawn(&work, path1, dp1->d_name, wq, &resultlist);
2533
2534             switch (code) {
2535             case -1:
2536                 /* fatal error */
2537                 closedir(dirp1);
2538                 ret = -1;
2539                 goto error;
2540
2541             case 1:
2542                 /* count this inode */
2543 #ifndef AFS_SALSRV_ENV
2544                 ninodes++;
2545 #endif
2546                 break;
2547             }
2548         }
2549         closedir(dirp1);
2550     }
2551
2552 #ifdef AFS_SALSRV_ENV
2553     /* effectively a barrier */
2554     code = _namei_listsubdirs_wait(wq, &resultlist);
2555     if (code < 0 || error) {
2556         ret = -1;
2557         goto error;
2558     }
2559     error = 0;
2560     ninodes += code;
2561 #endif
2562
2563     if (linkHandle.fd_fd == INVALID_FD) {
2564         Log("namei_ListAFSSubDirs: warning: VG %" AFS_VOLID_FMT " does not have a link table; "
2565             "salvager will recreate it.\n", afs_printable_VolumeId_lu(dirIH->ih_vid));
2566     }
2567
2568     /* Now run through all the other subdirs */
2569     namei_HandleToVolDir(&name, &myIH);
2570     strlcpy(path1, name.n_path, sizeof(path1));
2571
2572     work.special = 0;
2573
2574     dirp1 = opendir(path1);
2575     if (dirp1) {
2576         while ((dp1 = readdir(dirp1))) {
2577 #ifndef AFS_NT40_ENV
2578             if (*dp1->d_name == '.')
2579                 continue;
2580 #endif
2581             if (!strcmp(dp1->d_name, NAMEI_SPECDIR))
2582                 continue;
2583
2584 #ifndef AFS_NT40_ENV /* This level missing on Windows */
2585             /* Now we've got a next level subdir. */
2586             snprintf(path2, sizeof(path2), "%s" OS_DIRSEP "%s",
2587                      path1, dp1->d_name);
2588             dirp2 = opendir(path2);
2589             if (dirp2) {
2590                 while ((dp2 = readdir(dirp2))) {
2591                     if (*dp2->d_name == '.')
2592                         continue;
2593
2594                     /* Now we've got to the actual data */
2595                     snprintf(path3, sizeof(path3), "%s" OS_DIRSEP "%s",
2596                              path2, dp2->d_name);
2597 #else
2598                     /* Now we've got to the actual data */
2599                     snprintf(path3, sizeof(path3), "%s" OS_DIRSEP "%s",
2600                              path1, dp1->d_name);
2601 #endif
2602                     dirp3 = opendir(path3);
2603                     if (dirp3) {
2604                         while ((dp3 = readdir(dirp3))) {
2605 #ifndef AFS_NT40_ENV
2606                             if (*dp3->d_name == '.')
2607                                 continue;
2608 #endif
2609
2610 #ifdef AFS_SALSRV_ENV
2611                             if (error) {
2612                                 closedir(dirp3);
2613 #ifndef AFS_NT40_ENV
2614                                 closedir(dirp2);
2615 #endif
2616                                 closedir(dirp1);
2617                                 ret = -1;
2618                                 goto error;
2619                             }
2620 #endif /* AFS_SALSRV_ENV */
2621
2622                             code = _namei_examine_file_spawn(&work, path3,
2623                                                              dp3->d_name, wq,
2624                                                              &resultlist);
2625
2626                             switch (code) {
2627                             case -1:
2628                                 closedir(dirp3);
2629 #ifndef AFS_NT40_ENV
2630                                 closedir(dirp2);
2631 #endif
2632                                 closedir(dirp1);
2633                                 ret = -1;
2634                                 goto error;
2635
2636                             case 1:
2637 #ifndef AFS_SALSRV_ENV
2638                                 ninodes++;
2639 #endif
2640                                 break;
2641                             }
2642                         }
2643                         closedir(dirp3);
2644                     }
2645 #ifndef AFS_NT40_ENV /* This level missing on Windows */
2646                 }
2647                 closedir(dirp2);
2648             }
2649 #endif
2650         }
2651         closedir(dirp1);
2652     }
2653
2654 #ifdef AFS_SALSRV_ENV
2655     /* effectively a barrier */
2656     code = _namei_listsubdirs_wait(wq, &resultlist);
2657     if (code < 0 || error) {
2658         ret = -1;
2659         goto error;
2660     }
2661     error = 0;
2662     ninodes += code;
2663     wq_up = 0;
2664 #endif
2665
2666     if (!ninodes) {
2667         /* Then why does this directory exist? Blow it away. */
2668         namei_HandleToVolDir(&name, dirIH);
2669         namei_RemoveDataDirectories(&name);
2670     }
2671
2672  error:
2673 #ifdef AFS_SALSRV_ENV
2674     if (wq_up) {
2675         afs_wq_wait_all(wq);
2676     }
2677     _namei_listsubdirs_cleanup_results(&resultlist);
2678 #endif
2679     if (linkHandle.fd_fd != INVALID_FD)
2680         OS_CLOSE(linkHandle.fd_fd);
2681
2682     if (!ret) {
2683         ret = ninodes;
2684     }
2685     return ret;
2686 }
2687
2688 /*@}*/
2689
2690 #ifdef AFS_NT40_ENV
2691 static int
2692 DecodeVolumeName(char *name, VolumeId *vid)
2693 {
2694     /* Name begins with "Vol_" and ends with .data.  See nt_HandleToVolDir() */
2695     char stmp[32];
2696     size_t len;
2697
2698     len = strlen(name);
2699     if (len <= 9)
2700         return -1;
2701     if (strncmp(name, "Vol_", 4))
2702         return -1;
2703     if (strcmp(name + len - 5, ".data"))
2704         return -1;
2705     strcpy(stmp, name);
2706     stmp[len - 5] = '\0';
2707     *vid = base32_to_int(stmp + 4);
2708     return 0;
2709 }
2710 #else
2711 static int
2712 DecodeVolumeName(char *name, VolumeId *vid)
2713 {
2714     if (strlen(name) < 1)
2715         return -1;
2716     *vid = (unsigned int)flipbase64_to_int64(name);
2717     return 0;
2718 }
2719 #endif
2720
2721
2722 /* DecodeInode
2723  *
2724  * Get the inode number from the name.
2725  *
2726  */
2727 #ifdef AFS_NT40_ENV
2728 static int
2729 DecodeInode(char *dpath, char *name, struct ViceInodeInfo *info,
2730             VolumeId volid)
2731 {
2732     char fpath[512];
2733     int tag, vno;
2734     WIN32_FIND_DATA data;
2735     HANDLE dirH;
2736     char *s, *t;
2737     char stmp[16];
2738     FdHandle_t linkHandle;
2739     char dirl;
2740
2741     snprintf(fpath, sizeof(fpath), "%s" OS_DIRSEP "%s", dpath, name);
2742
2743     dirH = FindFirstFileEx(fpath, FindExInfoStandard, &data,
2744                            FindExSearchNameMatch, NULL,
2745                            FIND_FIRST_EX_CASE_SENSITIVE);
2746     if (dirH == INVALID_HANDLE_VALUE)
2747         return -1;
2748
2749     (void)strcpy(stmp, name);
2750     s = strrchr(stmp, '_');
2751     if (!s)
2752         return -1;
2753     s++;
2754     t = strrchr(s, '.');
2755     if (!t)
2756         return -1;
2757
2758     *t = '\0';
2759     vno = base32_to_int(s);     /* type for special files */
2760     tag = base32_to_int(t+1);
2761     info->inodeNumber = ((Inode) tag) << NAMEI_TAGSHIFT;
2762     info->inodeNumber |= vno;
2763     info->byteCount = data.nFileSizeLow;
2764
2765     dirl = dpath[strlen(dpath)-1];
2766     if (dirl == NAMEI_SPECDIRC) { /* Special inode. */
2767         info->inodeNumber |= NAMEI_INODESPECIAL;
2768         info->u.param[0] = data.ftCreationTime.dwHighDateTime;
2769         info->u.param[1] = data.ftCreationTime.dwLowDateTime;
2770         info->u.param[2] = vno; /* type */
2771         info->u.param[3] = volid;
2772         if (vno != VI_LINKTABLE)
2773             info->linkCount = 1;
2774         else {
2775             /* Open this handle */
2776             char lpath[1024];
2777             (void)sprintf(lpath, "%s" OS_DIRSEP "%s", fpath, data.cFileName);
2778             linkHandle.fd_fd = OS_OPEN(lpath, O_RDONLY, 0666);
2779             info->linkCount =
2780                 namei_GetLinkCount(&linkHandle, (Inode) 0, 0, 0, 0);
2781         }
2782     } else {
2783         info->linkCount =
2784             namei_GetLinkCount(&linkHandle, info->inodeNumber, 0, 0, 0);
2785         if (info->linkCount == 0) {
2786 #ifdef DELETE_ZLC
2787             Log("Found 0 link count file %s" OS_DIRSEP "%s, deleting it.\n",
2788                 fpath, data.cFileName);
2789             AddToZLCDeleteList(dirl, data.cFileName);
2790 #else
2791             Log("Found 0 link count file %s" OS_DIRSEP "%s.\n", path,
2792                 data.cFileName);
2793 #endif
2794         } else {
2795             info->u.param[2] = data.ftCreationTime.dwHighDateTime;
2796             info->u.param[3] = data.ftCreationTime.dwLowDateTime;
2797             info->u.param[1] = vno;
2798             info->u.param[0] = volid;
2799         }
2800     }
2801     return 0;
2802 }
2803 #else
2804 static int
2805 DecodeInode(char *dpath, char *name, struct ViceInodeInfo *info,
2806             VolumeId volid)
2807 {
2808     char fpath[512];
2809     struct afs_stat_st status;
2810     int parm, tag;
2811     lb64_string_t check;
2812
2813     snprintf(fpath, sizeof(fpath), "%s" OS_DIRSEP "%s", dpath, name);
2814
2815     if (afs_stat(fpath, &status) < 0) {
2816         return -1;
2817     }
2818
2819     info->byteCount = status.st_size;
2820     info->inodeNumber = (Inode) flipbase64_to_int64(name);
2821
2822     int64_to_flipbase64(check, info->inodeNumber);
2823     if (strcmp(name, check))
2824         return -1;
2825
2826     if ((info->inodeNumber & NAMEI_INODESPECIAL) == NAMEI_INODESPECIAL) {
2827         parm = ((info->inodeNumber >> NAMEI_UNIQSHIFT) & NAMEI_UNIQMASK);
2828         tag = (int)((info->inodeNumber >> NAMEI_TAGSHIFT) & NAMEI_TAGMASK);
2829
2830         /* p1 - vid, p2 - -1, p3 - type, p4 - rwvid */
2831         info->u.param[0] = parm;
2832         info->u.param[1] = -1;
2833         info->u.param[2] = tag;
2834         info->u.param[3] = volid;
2835     } else {
2836         GetOGMFromStat(&status, &parm, &tag);
2837         /* p1 - vid, p2 - vno, p3 - uniq, p4 - dv */
2838         info->u.param[0] = volid;
2839         info->u.param[1] = (int)(info->inodeNumber & NAMEI_VNODEMASK);
2840         info->u.param[2] = (int)((info->inodeNumber >> NAMEI_UNIQSHIFT)
2841                                  & (Inode) NAMEI_UNIQMASK);
2842         info->u.param[3] = parm;
2843     }
2844     return 0;
2845 }
2846 #endif
2847
2848 /*
2849  * Convert the VolumeInfo file from RO to RW
2850  * this routine is called by namei_convertROtoRWvolume()
2851  */
2852
2853 #ifdef FSSYNC_BUILD_CLIENT
2854 static afs_int32
2855 convertVolumeInfo(FD_t fdr, FD_t fdw, VolumeId vid)
2856 {
2857     struct VolumeDiskData vd;
2858     char *p;
2859
2860     if (OS_READ(fdr, &vd, sizeof(struct VolumeDiskData)) !=
2861         sizeof(struct VolumeDiskData)) {
2862         Log("1 convertVolumeInfo: read failed for %" AFS_VOLID_FMT " with code %d\n",
2863             afs_printable_VolumeId_lu(vid),
2864             errno);
2865         return -1;
2866     }
2867     vd.restoredFromId = vd.id;  /* remember the RO volume here */
2868     vd.cloneId = vd.id;
2869     vd.id = vd.parentId;
2870     vd.type = RWVOL;
2871     vd.dontSalvage = 0;
2872     vd.inUse = 0;
2873     vd.uniquifier += 5000;      /* just in case there are still file copies from
2874                                  * the old RW volume around */
2875
2876     /* For ROs, the copyDate contains the time that the RO volume was actually
2877      * created, and the creationDate just contains the last time the RO was
2878      * copied from the RW data. So, make the new RW creationDate more accurate
2879      * by setting it to copyDate, if copyDate is older. Since, we know the
2880      * volume is at least as old as copyDate. */
2881     if (vd.copyDate < vd.creationDate) {
2882         vd.creationDate = vd.copyDate;
2883     } else {
2884         /* If copyDate is newer, just make copyDate and creationDate the same,
2885          * for consistency with other RWs */
2886         vd.copyDate = vd.creationDate;
2887     }
2888
2889     p = strrchr(vd.name, '.');
2890     if (p && !strcmp(p, ".readonly")) {
2891         memset(p, 0, 9);
2892     }
2893     if (OS_WRITE(fdw, &vd, sizeof(struct VolumeDiskData)) !=
2894         sizeof(struct VolumeDiskData)) {
2895         Log("1 convertVolumeInfo: write failed for %lu with code %d\n",
2896             afs_printable_uint32_lu(vid),
2897             errno);
2898         return -1;
2899     }
2900     return 0;
2901 }
2902 #endif
2903
2904 /*
2905  * Convert a RO-volume into a RW-volume
2906  *
2907  * This function allows to recover very fast from the loss of a partition
2908  * from RO-copies if all RO-Copies exist on another partition.
2909  * Then these RO-volumes can be made to the new RW-volumes.
2910  * Backup of RW-volumes then consists in "vos release".
2911  *
2912  * We must make sure in this partition exists only the RO-volume which
2913  * is typical for remote replicas.
2914  *
2915  * Then the linktable is already ok,
2916  *      the vnode files need to be renamed
2917  *      the volinfo file needs to be replaced by another one with
2918  *                      slightly different contents and new name.
2919  * The volume header file of the RO-volume in the /vicep<x> directory
2920  * is destroyed by this call. A new header file for the RW-volume must
2921  * be created after return from this routine.
2922  */
2923
2924 int
2925 namei_ConvertROtoRWvolume(char *pname, VolumeId volumeId)
2926 {
2927     int code = 0;
2928 #ifdef FSSYNC_BUILD_CLIENT
2929     namei_t n;
2930     char dir_name[512], oldpath[512], newpath[512];
2931     char smallName[64];
2932     char largeName[64];
2933     char infoName[64];
2934     IHandle_t t_ih;
2935     IHandle_t *ih;
2936     char infoSeen = 0;
2937     char smallSeen = 0;
2938     char largeSeen = 0;
2939     char linkSeen = 0;
2940     FD_t fd, fd2;
2941     char *p;
2942     DIR *dirp;
2943     Inode ino;
2944     struct dirent *dp;
2945     struct DiskPartition64 *partP;
2946     struct ViceInodeInfo info;
2947     struct VolumeDiskHeader h;
2948     char *rwpart, *rwname;
2949     Error ec;
2950 # ifdef AFS_DEMAND_ATTACH_FS
2951     int locktype = 0;
2952 # endif /* AFS_DEMAND_ATTACH_FS */
2953
2954     for (partP = DiskPartitionList; partP && strcmp(partP->name, pname);
2955          partP = partP->next);
2956     if (!partP) {
2957         Log("1 namei_ConvertROtoRWvolume: Couldn't find DiskPartition for %s\n", pname);
2958         code = EIO;
2959         goto done;
2960     }
2961
2962 # ifdef AFS_DEMAND_ATTACH_FS
2963     locktype = VVolLockType(V_VOLUPD, 1);
2964     code = VLockVolumeByIdNB(volumeId, partP, locktype);
2965     if (code) {
2966         locktype = 0;
2967         code = EIO;
2968         goto done;
2969     }
2970 # endif /* AFS_DEMAND_ATTACH_FS */
2971
2972     if (VReadVolumeDiskHeader(volumeId, partP, &h)) {
2973         Log("1 namei_ConvertROtoRWvolume: Couldn't read header for RO-volume %lu.\n",
2974             afs_printable_uint32_lu(volumeId));
2975         code = EIO;
2976         goto done;
2977     }
2978
2979     /* check for existing RW on any partition on this server; */
2980     /* if found, return EXDEV - invalid cross-device link */
2981     VOL_LOCK;
2982     VGetVolumePath(&ec, h.parent, &rwpart, &rwname);
2983     if (ec == 0) {
2984         Log("1 namei_ConvertROtoRWvolume: RW volume %lu already exists on server partition %s.\n",
2985             afs_printable_uint32_lu(h.parent), rwpart);
2986         code = EXDEV;
2987         VOL_UNLOCK;
2988         goto done;
2989     }
2990     VOL_UNLOCK;
2991
2992     FSYNC_VolOp(volumeId, pname, FSYNC_VOL_BREAKCBKS, 0, NULL);
2993
2994     ino = namei_MakeSpecIno(h.parent, VI_LINKTABLE);
2995     IH_INIT(ih, partP->device, h.parent, ino);
2996
2997     namei_HandleToName(&n, ih);
2998     strlcpy(dir_name, n.n_path, sizeof(dir_name));
2999     p = strrchr(dir_name, OS_DIRSEPC);
3000     *p = 0;
3001     dirp = opendir(dir_name);
3002     if (!dirp) {
3003         Log("1 namei_ConvertROtoRWvolume: Could not opendir(%s)\n", dir_name);
3004         code = EIO;
3005         goto done;
3006     }
3007
3008     while ((dp = readdir(dirp))) {
3009         /* struct ViceInodeInfo info; */
3010 #ifndef AFS_NT40_ENV
3011         if (*dp->d_name == '.')
3012             continue;
3013 #endif
3014         if (DecodeInode(dir_name, dp->d_name, &info, ih->ih_vid) < 0) {
3015             Log("1 namei_ConvertROtoRWvolume: DecodeInode failed for %s" OS_DIRSEP "%s\n",
3016                 dir_name, dp->d_name);
3017             closedir(dirp);
3018             code = -1;
3019             goto done;
3020         }
3021         if (info.u.param[1] != -1) {
3022             Log("1 namei_ConvertROtoRWvolume: found other than volume special file %s" OS_DIRSEP "%s\n", dir_name, dp->d_name);
3023             closedir(dirp);
3024             code = -1;
3025             goto done;
3026         }
3027         if (info.u.param[0] != volumeId) {
3028             if (info.u.param[0] == ih->ih_vid) {
3029                 if (info.u.param[2] == VI_LINKTABLE) {  /* link table */
3030                     linkSeen = 1;
3031                     continue;
3032                 }
3033             }
3034             Log("1 namei_ConvertROtoRWvolume: found special file %s" OS_DIRSEP "%s"
3035                 " for volume %lu\n", dir_name, dp->d_name,
3036                 afs_printable_uint32_lu(info.u.param[0]));
3037             closedir(dirp);
3038             code = VVOLEXISTS;
3039             goto done;
3040         }
3041         if (info.u.param[2] == VI_VOLINFO) {    /* volume info file */
3042             strlcpy(infoName, dp->d_name, sizeof(infoName));
3043             infoSeen = 1;
3044         } else if (info.u.param[2] == VI_SMALLINDEX) {  /* small vnodes file */
3045             strlcpy(smallName, dp->d_name, sizeof(smallName));
3046             smallSeen = 1;
3047         } else if (info.u.param[2] == VI_LARGEINDEX) {  /* large vnodes file */
3048             strlcpy(largeName, dp->d_name, sizeof(largeName));
3049             largeSeen = 1;
3050         } else {
3051             closedir(dirp);
3052             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);
3053             code = -1;
3054             goto done;
3055         }
3056     }
3057     closedir(dirp);
3058
3059     if (!infoSeen || !smallSeen || !largeSeen || !linkSeen) {
3060         Log("1 namei_ConvertROtoRWvolume: not all special files found in %s\n", dir_name);
3061         code = -1;
3062         goto done;
3063     }
3064
3065     /*
3066      * If we come here then there was only a RO-volume and we can safely
3067      * proceed.
3068      */
3069
3070     memset(&t_ih, 0, sizeof(t_ih));
3071     t_ih.ih_dev = ih->ih_dev;
3072     t_ih.ih_vid = ih->ih_vid;
3073
3074     snprintf(oldpath, sizeof oldpath, "%s" OS_DIRSEP "%s", dir_name,
3075              infoName);
3076     fd = OS_OPEN(oldpath, O_RDWR, 0);
3077     if (fd == INVALID_FD) {
3078         Log("1 namei_ConvertROtoRWvolume: could not open RO info file: %s\n",
3079             oldpath);
3080         code = -1;
3081         goto done;
3082     }
3083     t_ih.ih_ino = namei_MakeSpecIno(ih->ih_vid, VI_VOLINFO);
3084     namei_HandleToName(&n, &t_ih);
3085     fd2 = OS_OPEN(n.n_path, O_CREAT | O_EXCL | O_RDWR, 0);
3086     if (fd2 == INVALID_FD) {
3087         Log("1 namei_ConvertROtoRWvolume: could not create RW info file: %s\n", n.n_path);
3088         OS_CLOSE(fd);
3089         code = -1;
3090         goto done;
3091     }
3092     code = convertVolumeInfo(fd, fd2, ih->ih_vid);
3093     OS_CLOSE(fd);
3094     if (code) {
3095         OS_CLOSE(fd2);
3096         OS_UNLINK(n.n_path);
3097         code = -1;
3098         goto done;
3099     }
3100     SetOGM(fd2, ih->ih_vid, 1);
3101     OS_CLOSE(fd2);
3102
3103     t_ih.ih_ino = namei_MakeSpecIno(ih->ih_vid, VI_SMALLINDEX);
3104     namei_HandleToName(&n, &t_ih);
3105     snprintf(newpath, sizeof newpath, "%s" OS_DIRSEP "%s", dir_name,
3106              smallName);
3107     fd = OS_OPEN(newpath, O_RDWR, 0);
3108     if (fd == INVALID_FD) {
3109         Log("1 namei_ConvertROtoRWvolume: could not open SmallIndex file: %s\n", newpath);
3110         code = -1;
3111         goto done;
3112     }
3113     SetOGM(fd, ih->ih_vid, 2);
3114     OS_CLOSE(fd);
3115 #ifdef AFS_NT40_ENV
3116     MoveFileEx(n.n_path, newpath, MOVEFILE_WRITE_THROUGH);
3117 #else
3118     link(newpath, n.n_path);
3119     OS_UNLINK(newpath);
3120 #endif
3121
3122     t_ih.ih_ino = namei_MakeSpecIno(ih->ih_vid, VI_LARGEINDEX);
3123     namei_HandleToName(&n, &t_ih);
3124     snprintf(newpath, sizeof newpath, "%s" OS_DIRSEP "%s", dir_name,
3125              largeName);
3126     fd = OS_OPEN(newpath, O_RDWR, 0);
3127     if (fd == INVALID_FD) {
3128         Log("1 namei_ConvertROtoRWvolume: could not open LargeIndex file: %s\n", newpath);
3129         code = -1;
3130         goto done;
3131     }
3132     SetOGM(fd, ih->ih_vid, 3);
3133     OS_CLOSE(fd);
3134 #ifdef AFS_NT40_ENV
3135     MoveFileEx(n.n_path, newpath, MOVEFILE_WRITE_THROUGH);
3136 #else
3137     link(newpath, n.n_path);
3138     OS_UNLINK(newpath);
3139 #endif
3140
3141     OS_UNLINK(oldpath);
3142
3143     h.id = h.parent;
3144     h.volumeInfo_hi = h.id;
3145     h.smallVnodeIndex_hi = h.id;
3146     h.largeVnodeIndex_hi = h.id;
3147     h.linkTable_hi = h.id;
3148
3149     if (VCreateVolumeDiskHeader(&h, partP)) {
3150         Log("1 namei_ConvertROtoRWvolume: Couldn't write header for RW-volume %lu\n",
3151             afs_printable_uint32_lu(h.id));
3152         code = EIO;
3153         goto done;
3154     }
3155
3156     if (VDestroyVolumeDiskHeader(partP, volumeId, h.parent)) {
3157         Log("1 namei_ConvertROtoRWvolume: Couldn't unlink header for RO-volume %lu\n",
3158             afs_printable_uint32_lu(volumeId));
3159     }
3160
3161     FSYNC_VolOp(volumeId, pname, FSYNC_VOL_DONE, 0, NULL);
3162     FSYNC_VolOp(h.id, pname, FSYNC_VOL_ON, 0, NULL);
3163
3164  done:
3165 # ifdef AFS_DEMAND_ATTACH_FS
3166     if (locktype) {
3167         VUnlockVolumeById(volumeId, partP);
3168     }
3169 # endif /* AFS_DEMAND_ATTACH_FS */
3170 #endif
3171
3172     return code;
3173 }
3174
3175 /* PrintInode
3176  *
3177  * returns a static string used to print either 32 or 64 bit inode numbers.
3178  */
3179 char *
3180 PrintInode(char *s, Inode ino)
3181 {
3182     static afs_ino_str_t result;
3183     if (!s)
3184         s = result;
3185
3186     snprintf(s, sizeof(afs_ino_str_t), "%llu", (afs_uintmax_t) ino);
3187
3188     return s;
3189 }
3190
3191
3192 #ifdef DELETE_ZLC
3193 /* Routines to facilitate removing zero link count files. */
3194 #define MAX_ZLC_NAMES 32
3195 #define MAX_ZLC_NAMELEN 16
3196 typedef struct zlcList_s {
3197     struct zlcList_s *zlc_next;
3198     int zlc_n;
3199     char zlc_names[MAX_ZLC_NAMES][MAX_ZLC_NAMELEN];
3200 } zlcList_t;
3201
3202 static zlcList_t *zlcAnchor = NULL;
3203 static zlcList_t *zlcCur = NULL;
3204
3205 static void
3206 AddToZLCDeleteList(char dir, char *name)
3207 {
3208     opr_Assert(strlen(name) <= MAX_ZLC_NAMELEN - 3);
3209
3210     if (!zlcCur || zlcCur->zlc_n >= MAX_ZLC_NAMES) {
3211         if (zlcCur && zlcCur->zlc_next)
3212             zlcCur = zlcCur->zlc_next;
3213         else {
3214             zlcList_t *tmp = malloc(sizeof(zlcList_t));
3215             if (!tmp)
3216                 return;
3217             if (!zlcAnchor) {
3218                 zlcAnchor = tmp;
3219             } else {
3220                 zlcCur->zlc_next = tmp;
3221             }
3222             zlcCur = tmp;
3223             zlcCur->zlc_n = 0;
3224             zlcCur->zlc_next = NULL;
3225         }
3226     }
3227
3228     if (dir)
3229         (void)sprintf(zlcCur->zlc_names[zlcCur->zlc_n], "%c" OS_DIRSEP "%s", dir, name);
3230     else
3231         (void)sprintf(zlcCur->zlc_names[zlcCur->zlc_n], "%s", name);
3232
3233     zlcCur->zlc_n++;
3234 }
3235
3236 static void
3237 DeleteZLCFiles(char *path)
3238 {
3239     zlcList_t *z;
3240     int i;
3241     char fname[1024];
3242
3243     for (z = zlcAnchor; z; z = z->zlc_next) {
3244         for (i = 0; i < z->zlc_n; i++) {
3245             if (path)
3246                 (void)sprintf(fname, "%s" OS_DIRSEP "%s", path, z->zlc_names[i]);
3247             else
3248                 (void)sprintf(fname, "%s", z->zlc_names[i]);
3249             if (namei_unlink(fname) < 0) {
3250                 Log("ZLC: Can't unlink %s, dos error = %d\n", fname,
3251                     GetLastError());
3252             }
3253         }
3254         z->zlc_n = 0;           /* Can reuse space. */
3255     }
3256     zlcCur = zlcAnchor;
3257 }
3258
3259 static void
3260 FreeZLCList(void)
3261 {
3262     zlcList_t *tnext;
3263     zlcList_t *i;
3264
3265     i = zlcAnchor;
3266     while (i) {
3267         tnext = i->zlc_next;
3268         free(i);
3269         i = tnext;
3270     }
3271     zlcCur = zlcAnchor = NULL;
3272 }
3273 #endif
3274
3275 #endif /* AFS_NAMEI_ENV */