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