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