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