99a44405dd7b929bd3ae497af353fd69876dd512
[openafs.git] / src / vlserver / vldb_check.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 /* Read a VLDB file and verify it for correctness */
11
12 #define VL  0x001               /* good volume entry */
13 #define FR  0x002               /* free volume entry */
14 #define MH  0x004               /* multi-homed entry */
15
16 #define RWH 0x010               /* on rw hash chain */
17 #define ROH 0x020               /* on ro hash chain */
18 #define BKH 0x040               /* on bk hash chain */
19 #define NH  0x080               /* on name hash chain */
20
21 #define MHC 0x100               /* on multihomed chain */
22 #define FRC 0x200               /* on free chain */
23
24 #define REFRW 0x1000            /* linked from something (RW) */
25 #define REFRO 0x2000            /* linked from something (RO) */
26 #define REFBK 0x4000            /* linked from something (BK) */
27 #define REFN  0x8000            /* linked from something (name) */
28
29 #define MULTRW 0x10000         /* multiply-chained (RW) */
30 #define MULTRO 0x20000         /* multiply-chained (RO) */
31 #define MULTBK 0x40000         /* multiply-chained (BK) */
32 #define MULTN  0x80000         /* multiply-chained (name) */
33
34 #define MISRWH 0x100000          /* mischained (RW) */
35 #define MISROH 0x200000          /* mischained (RO) */
36 #define MISBKH 0x400000          /* mischained (BK) */
37 #define MISNH  0x800000          /* mischained (name) */
38
39 #define VLDB_CHECK_NO_VLDB_CHECK_ERROR 0
40 #define VLDB_CHECK_WARNING  1
41 #define VLDB_CHECK_ERROR    2
42 #define VLDB_CHECK_FATAL    4
43 #define vldbread(x,y,z) vldbio(x,y,z,0)
44 #define vldbwrite(x,y,z) vldbio(x,y,z,1)
45
46 #include <afsconfig.h>
47 #include <afs/param.h>
48
49 #include <roken.h>
50
51 #include <stdlib.h>
52 #include <sys/types.h>
53 #include <sys/stat.h>
54 #include <fcntl.h>
55 #include <errno.h>
56 #include <string.h>
57 #ifdef AFS_NT40_ENV
58 #include <winsock2.h>
59 #include <WINNT/afsevent.h>
60 #include <io.h>
61 #else
62 #include <sys/socket.h>
63 #include <netdb.h>
64 #include <netinet/in.h>
65 #endif
66
67 #include "vlserver.h"
68 #include "vldbint.h"
69 #include <ubik.h>
70 #include <afs/afsutil.h>
71 #include <afs/cmd.h>
72
73 #define ADDR(x) (x/sizeof(struct nvlentry))
74
75 int fd;
76 int listentries, listservers, listheader, listuheader, verbose, quiet;
77
78 int fix = 0;
79 int passes = 0;
80 /* if quiet, don't send anything to stdout */
81 int quiet = 0;
82 /*  error level. 0 = no error, 1 = warning, 2 = error, 4 = fatal */
83 int error_level  = 0;
84
85 struct er {
86     long addr;
87     int type;
88 } *record;
89 afs_int32 maxentries;
90 int serveraddrs[MAXSERVERID + 2];
91
92 /*  Used to control what goes to stdout based on quiet flag */
93 void
94 quiet_println(const char *fmt,...) {
95     va_list args;
96     if (!quiet) {
97         va_start(args, fmt);
98         vfprintf(stdout, fmt, args);
99         va_end(args);
100     }
101 }
102
103 /*  Used to set the error level and ship messages to stderr */
104 void
105 log_error(int eval, const char *fmt, ...)
106 {
107     va_list args;
108     if (error_level < eval) error_level  = eval ;  /*  bump up the severity */
109     va_start(args, fmt);
110     vfprintf(stderr, fmt, args);
111     va_end(args);
112
113     if (error_level  == VLDB_CHECK_FATAL) exit(VLDB_CHECK_FATAL);
114 }
115
116
117 #if 0
118 int
119 writeUbikHeader()
120 {
121     /* Bump the version number?? We could cheat and push a new db... */
122 }
123 #endif
124
125 #define HDRSIZE 64
126 int
127 readUbikHeader(void)
128 {
129     int offset, r;
130     struct ubik_hdr uheader;
131
132     offset = lseek(fd, 0, 0);
133     if (offset != 0) {
134         log_error(VLDB_CHECK_FATAL,"error: lseek to 0 failed: %d %d\n", offset, errno);
135         return (VLDB_CHECK_FATAL);
136     }
137
138     /* now read the info */
139     r = read(fd, &uheader, sizeof(uheader));
140     if (r != sizeof(uheader)) {
141         log_error(VLDB_CHECK_FATAL,"error: read of %lu bytes failed: %d %d\n", sizeof(uheader), r,
142                errno);
143         return (VLDB_CHECK_FATAL);
144     }
145
146     uheader.magic = ntohl(uheader.magic);
147     uheader.size = ntohs(uheader.size);
148     uheader.version.epoch = ntohl(uheader.version.epoch);
149     uheader.version.counter = ntohl(uheader.version.counter);
150
151     if (listuheader) {
152         quiet_println("Ubik Header\n");
153         quiet_println("   Magic           = 0x%x\n", uheader.magic);
154         quiet_println("   Size            = %u\n", uheader.size);
155         quiet_println("   Version.epoch   = %u\n", uheader.version.epoch);
156         quiet_println("   Version.counter = %u\n", uheader.version.counter);
157     }
158
159     if (uheader.size != HDRSIZE)
160         log_error(VLDB_CHECK_WARNING,"VLDB_CHECK_WARNING: Ubik header size is %u (should be %u)\n", uheader.size,
161                HDRSIZE);
162     if (uheader.magic != UBIK_MAGIC)
163         log_error(VLDB_CHECK_ERROR,"Ubik header magic is 0x%x (should be 0x%x)\n", uheader.magic,
164                UBIK_MAGIC);
165
166     return (0);
167 }
168
169 int
170 vldbio(int position, void *buffer, int size, int rdwr)
171 {
172     int offset, r, p;
173
174     /* seek to the correct spot. skip ubik stuff */
175     p = position + HDRSIZE;
176     offset = lseek(fd, p, 0);
177     if (offset != p) {
178         log_error(VLDB_CHECK_FATAL,"error: lseek to %d failed: %d %d\n", p, offset, errno);
179         return (-1);
180     }
181
182     if (rdwr == 1)
183         r = write(fd, buffer, size);
184     else
185         r = read(fd, buffer, size);
186
187     if (r != size) {
188         log_error(VLDB_CHECK_FATAL,"error: %s of %d bytes failed: %d %d\n", rdwr==1?"write":"read",
189                size, r, errno);
190         return (-1);
191     }
192     return (0);
193 }
194
195 char *
196 vtype(int type)
197 {
198     static char Type[3];
199
200     if (type == 0)
201         strcpy(Type, "rw");
202     else if (type == 1)
203         strcpy(Type, "ro");
204     else if (type == 2)
205         strcpy(Type, "bk");
206     else
207         strcpy(Type, "??");
208     return (Type);
209 }
210
211 afs_int32
212 NameHash(char *volname)
213 {
214     unsigned int hash;
215     char *vchar;
216
217     hash = 0;
218     for (vchar = volname + strlen(volname) - 1; vchar >= volname; vchar--)
219         hash = (hash * 63) + (*((unsigned char *)vchar) - 63);
220     return (hash % HASHSIZE);
221 }
222
223 afs_int32
224 IdHash(afs_uint32 volid)
225 {
226     return ((abs(volid)) % HASHSIZE);
227 }
228
229 #define LEGALCHARS ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
230 int
231 InvalidVolname(char *volname)
232 {
233     char *map;
234     size_t slen;
235
236     map = LEGALCHARS;
237     slen = strlen(volname);
238     if (slen >= VL_MAXNAMELEN)
239         return 1;
240     return (slen != strspn(volname, map));
241 }
242
243 int
244 validVolumeAddr(afs_uint32 fileOffset)
245 {
246     if (ADDR(fileOffset) >= maxentries) {
247         /* Are we in range */
248         return 0;
249     }
250     /*
251      * We cannot test whether the offset is aligned
252      * since the vl entries are not in a regular array
253      */
254     return 1;
255 }
256
257 void
258 readheader(struct vlheader *headerp)
259 {
260     int i, j;
261
262     vldbread(0, (char *)headerp, sizeof(*headerp));
263
264     headerp->vital_header.vldbversion =
265         ntohl(headerp->vital_header.vldbversion);
266     headerp->vital_header.headersize =
267         ntohl(headerp->vital_header.headersize);
268     headerp->vital_header.freePtr = ntohl(headerp->vital_header.freePtr);
269     headerp->vital_header.eofPtr = ntohl(headerp->vital_header.eofPtr);
270     headerp->vital_header.allocs = ntohl(headerp->vital_header.allocs);
271     headerp->vital_header.frees = ntohl(headerp->vital_header.frees);
272     headerp->vital_header.MaxVolumeId =
273         ntohl(headerp->vital_header.MaxVolumeId);
274     headerp->vital_header.totalEntries[0] =
275         ntohl(headerp->vital_header.totalEntries[0]);
276     for (i = 0; i < MAXTYPES; i++)
277         headerp->vital_header.totalEntries[i] =
278             ntohl(headerp->vital_header.totalEntries[1]);
279
280     headerp->SIT = ntohl(headerp->SIT);
281     for (i = 0; i < MAXSERVERID; i++)
282         headerp->IpMappedAddr[i] = ntohl(headerp->IpMappedAddr[i]);
283     for (i = 0; i < HASHSIZE; i++)
284         headerp->VolnameHash[i] = ntohl(headerp->VolnameHash[i]);
285     for (i = 0; i < MAXTYPES; i++)
286         for (j = 0; j < HASHSIZE; j++)
287             headerp->VolidHash[i][j] = ntohl(headerp->VolidHash[i][j]);
288
289     if (listheader) {
290         quiet_println("vldb header\n");
291         quiet_println("   vldbversion      = %u\n",
292                headerp->vital_header.vldbversion);
293         quiet_println("   headersize       = %u [actual=%lu]\n",
294                headerp->vital_header.headersize, sizeof(*headerp));
295         quiet_println("   freePtr          = 0x%x\n", headerp->vital_header.freePtr);
296         quiet_println("   eofPtr           = %u\n", headerp->vital_header.eofPtr);
297         quiet_println("   allocblock calls = %10u\n", headerp->vital_header.allocs);
298         quiet_println("   freeblock  calls = %10u\n", headerp->vital_header.frees);
299         quiet_println("   MaxVolumeId      = %u\n",
300                headerp->vital_header.MaxVolumeId);
301         quiet_println("   rw vol entries   = %u\n",
302                headerp->vital_header.totalEntries[0]);
303         quiet_println("   ro vol entries   = %u\n",
304                headerp->vital_header.totalEntries[1]);
305         quiet_println("   bk vol entries   = %u\n",
306                headerp->vital_header.totalEntries[2]);
307         quiet_println("   multihome info   = 0x%x (%u)\n", headerp->SIT,
308                headerp->SIT);
309         quiet_println("   server ip addr   table: size = %d entries\n",
310                MAXSERVERID + 1);
311         quiet_println("   volume name hash table: size = %d buckets\n", HASHSIZE);
312         quiet_println("   volume id   hash table: %d tables with %d buckets each\n",
313                MAXTYPES, HASHSIZE);
314     }
315
316     /* Check the header size */
317     if (headerp->vital_header.headersize != sizeof(*headerp))
318         log_error(VLDB_CHECK_WARNING,"Header reports its size as %d (should be %lu)\n",
319                headerp->vital_header.headersize, sizeof(*headerp));
320     return;
321 }
322
323 void
324 writeheader(struct vlheader *headerp)
325 {
326     int i, j;
327
328     headerp->vital_header.vldbversion =
329         htonl(headerp->vital_header.vldbversion);
330     headerp->vital_header.headersize =
331         htonl(headerp->vital_header.headersize);
332     headerp->vital_header.freePtr = htonl(headerp->vital_header.freePtr);
333     headerp->vital_header.eofPtr = htonl(headerp->vital_header.eofPtr);
334     headerp->vital_header.allocs = htonl(headerp->vital_header.allocs);
335     headerp->vital_header.frees = htonl(headerp->vital_header.frees);
336     headerp->vital_header.MaxVolumeId =
337         htonl(headerp->vital_header.MaxVolumeId);
338     headerp->vital_header.totalEntries[0] =
339         htonl(headerp->vital_header.totalEntries[0]);
340     for (i = 0; i < MAXTYPES; i++)
341         headerp->vital_header.totalEntries[i] =
342             htonl(headerp->vital_header.totalEntries[1]);
343
344     headerp->SIT = htonl(headerp->SIT);
345     for (i = 0; i < MAXSERVERID; i++)
346         headerp->IpMappedAddr[i] = htonl(headerp->IpMappedAddr[i]);
347     for (i = 0; i < HASHSIZE; i++)
348         headerp->VolnameHash[i] = htonl(headerp->VolnameHash[i]);
349     for (i = 0; i < MAXTYPES; i++)
350         for (j = 0; j < HASHSIZE; j++)
351             headerp->VolidHash[i][j] = htonl(headerp->VolidHash[i][j]);
352
353     vldbwrite(0, (char *)headerp, sizeof(*headerp));
354 }
355
356 void
357 readMH(afs_int32 addr, struct extentaddr *mhblockP)
358 {
359     int i, j;
360     struct extentaddr *e;
361
362     vldbread(addr, (char *)mhblockP, VL_ADDREXTBLK_SIZE);
363
364     mhblockP->ex_count = ntohl(mhblockP->ex_count);
365     mhblockP->ex_flags = ntohl(mhblockP->ex_flags);
366     for (i = 0; i < VL_MAX_ADDREXTBLKS; i++)
367         mhblockP->ex_contaddrs[i] = ntohl(mhblockP->ex_contaddrs[i]);
368
369     for (i = 1; i < VL_MHSRV_PERBLK; i++) {
370         e = &(mhblockP[i]);
371
372         /* won't convert hostuuid */
373         e->ex_uniquifier = ntohl(e->ex_uniquifier);
374         for (j = 0; j < VL_MAXIPADDRS_PERMH; j++)
375             e->ex_addrs[j] = ntohl(e->ex_addrs[j]);
376     }
377     return;
378 }
379
380 void
381 readentry(afs_int32 addr, struct nvlentry *vlentryp, afs_int32 *type)
382 {
383     int i;
384
385     vldbread(addr, (char *)vlentryp, sizeof(*vlentryp));
386
387     for (i = 0; i < MAXTYPES; i++)
388         vlentryp->volumeId[i] = ntohl(vlentryp->volumeId[i]);
389     vlentryp->flags = ntohl(vlentryp->flags);
390     vlentryp->LockAfsId = ntohl(vlentryp->LockAfsId);
391     vlentryp->LockTimestamp = ntohl(vlentryp->LockTimestamp);
392     vlentryp->cloneId = ntohl(vlentryp->cloneId);
393     for (i = 0; i < MAXTYPES; i++)
394         vlentryp->nextIdHash[i] = ntohl(vlentryp->nextIdHash[i]);
395     vlentryp->nextNameHash = ntohl(vlentryp->nextNameHash);
396     for (i = 0; i < NMAXNSERVERS; i++) {
397         /* make sure not to ntohl these, as they're chars, not ints */
398         vlentryp->serverNumber[i] = vlentryp->serverNumber[i];
399         vlentryp->serverPartition[i] = vlentryp->serverPartition[i];
400         vlentryp->serverFlags[i] = vlentryp->serverFlags[i];
401     }
402
403     if (vlentryp->flags == VLCONTBLOCK) {
404         *type = MH;
405     } else if (vlentryp->flags == VLFREE) {
406         *type = FR;
407     } else {
408         *type = VL;
409     }
410
411     if (listentries) {
412         quiet_println("address %u: ", addr);
413         if (vlentryp->flags == VLCONTBLOCK) {
414             quiet_println("mh extension block\n");
415         } else if (vlentryp->flags == VLFREE) {
416             quiet_println("free vlentry\n");
417         } else {
418             quiet_println("vlentry %s\n", vlentryp->name);
419             quiet_println("   rw id = %u ; ro id = %u ; bk id = %u\n",
420                    vlentryp->volumeId[0], vlentryp->volumeId[1],
421                    vlentryp->volumeId[2]);
422             quiet_println("   flags         =");
423             if (vlentryp->flags & VLF_RWEXISTS)
424                 quiet_println(" rw");
425             if (vlentryp->flags & VLF_ROEXISTS)
426                 quiet_println(" ro");
427             if (vlentryp->flags & VLF_BACKEXISTS)
428                 quiet_println(" bk");
429             if (vlentryp->flags & VLOP_MOVE)
430                 quiet_println(" lock_move");
431             if (vlentryp->flags & VLOP_RELEASE)
432                 quiet_println(" lock_release");
433             if (vlentryp->flags & VLOP_BACKUP)
434                 quiet_println(" lock_backup");
435             if (vlentryp->flags & VLOP_DELETE)
436                 quiet_println(" lock_delete");
437             if (vlentryp->flags & VLOP_DUMP)
438                 quiet_println(" lock_dump");
439
440             /* all bits not covered by VLF_* and VLOP_* constants */
441             if (vlentryp->flags & 0xffff8e0f)
442                 quiet_println(" errorflag(0x%x)", vlentryp->flags);
443             quiet_println("\n");
444             quiet_println("   LockAfsId     = %d\n", vlentryp->LockAfsId);
445             quiet_println("   LockTimestamp = %d\n", vlentryp->LockTimestamp);
446             quiet_println("   cloneId       = %u\n", vlentryp->cloneId);
447             quiet_println
448                 ("   next hash for rw = %u ; ro = %u ; bk = %u ; name = %u\n",
449                  vlentryp->nextIdHash[0], vlentryp->nextIdHash[1],
450                  vlentryp->nextIdHash[2], vlentryp->nextNameHash);
451             for (i = 0; i < NMAXNSERVERS; i++) {
452                 if (vlentryp->serverNumber[i] != 255) {
453                     quiet_println("   server %d ; partition %d ; flags =",
454                            vlentryp->serverNumber[i],
455                            vlentryp->serverPartition[i]);
456                     if (vlentryp->serverFlags[i] & VLSF_RWVOL)
457                         quiet_println(" rw");
458                     if (vlentryp->serverFlags[i] & VLSF_ROVOL)
459                         quiet_println(" ro");
460                     if (vlentryp->serverFlags[i] & VLSF_BACKVOL)
461                         quiet_println(" bk");
462                     if (vlentryp->serverFlags[i] & VLSF_NEWREPSITE)
463                         quiet_println(" newro");
464                     quiet_println("\n");
465                 }
466             }
467         }
468     }
469     return;
470 }
471
472 void
473 writeentry(afs_int32 addr, struct nvlentry *vlentryp)
474 {
475     int i;
476
477     if (verbose) quiet_println("Writing back entry at addr %u\n", addr);
478     for (i = 0; i < MAXTYPES; i++)
479         vlentryp->volumeId[i] = htonl(vlentryp->volumeId[i]);
480     vlentryp->flags = htonl(vlentryp->flags);
481     vlentryp->LockAfsId = htonl(vlentryp->LockAfsId);
482     vlentryp->LockTimestamp = htonl(vlentryp->LockTimestamp);
483     vlentryp->cloneId = htonl(vlentryp->cloneId);
484     for (i = 0; i < MAXTYPES; i++)
485         vlentryp->nextIdHash[i] = htonl(vlentryp->nextIdHash[i]);
486     vlentryp->nextNameHash = htonl(vlentryp->nextNameHash);
487     for (i = 0; i < NMAXNSERVERS; i++) {
488         /* make sure not to htonl these, as they're chars, not ints */
489         vlentryp->serverNumber[i] =  vlentryp->serverNumber[i] ;
490         vlentryp->serverPartition[i] = vlentryp->serverPartition[i] ;
491         vlentryp->serverFlags[i] = vlentryp->serverFlags[i] ;
492     }
493     vldbwrite(addr, (char *)vlentryp, sizeof(*vlentryp));
494 }
495
496 void
497 readSIT(int base, int addr)
498 {
499     int i, j, a;
500     char sitbuf[VL_ADDREXTBLK_SIZE];
501     struct extentaddr *extent;
502
503     if (!addr)
504         return;
505     vldbread(addr, sitbuf, VL_ADDREXTBLK_SIZE);
506     extent = (struct extentaddr *)sitbuf;
507
508     quiet_println("multihome info block: base %d\n", base);
509     if (base == 0) {
510         quiet_println("   count = %u\n", ntohl(extent->ex_count));
511         quiet_println("   flags = %u\n", ntohl(extent->ex_flags));
512         for (i = 0; i < VL_MAX_ADDREXTBLKS; i++) {
513             quiet_println("   contaddrs[%d] = %u\n", i,
514                    ntohl(extent->ex_contaddrs[i]));
515         }
516     }
517     for (i = 1; i < VL_MHSRV_PERBLK; i++) {
518         /* should we skip this entry */
519         for (j = 0; j < VL_MAX_ADDREXTBLKS; j++) {
520             if (extent[i].ex_addrs[j])
521                 break;
522         }
523         if (j >= VL_MAX_ADDREXTBLKS)
524             continue;
525
526         quiet_println("   base %d index %d:\n", base, i);
527
528         quiet_println("       afsuuid    = (%x %x %x /%d/%d/ /%x/%x/%x/%x/%x/%x/)\n",
529                ntohl(extent[i].ex_hostuuid.time_low),
530                ntohl(extent[i].ex_hostuuid.time_mid),
531                ntohl(extent[i].ex_hostuuid.time_hi_and_version),
532                ntohl(extent[i].ex_hostuuid.clock_seq_hi_and_reserved),
533                ntohl(extent[i].ex_hostuuid.clock_seq_low),
534                ntohl(extent[i].ex_hostuuid.node[0]),
535                ntohl(extent[i].ex_hostuuid.node[1]),
536                ntohl(extent[i].ex_hostuuid.node[2]),
537                ntohl(extent[i].ex_hostuuid.node[3]),
538                ntohl(extent[i].ex_hostuuid.node[4]),
539                ntohl(extent[i].ex_hostuuid.node[5]));
540         quiet_println("       uniquifier = %u\n", ntohl(extent[i].ex_uniquifier));
541         for (j = 0; j < VL_MAXIPADDRS_PERMH; j++) {
542             a = ntohl(extent[i].ex_addrs[j]);
543             if (a) {
544                 quiet_println("       %d.%d.%d.%d\n", (a >> 24) & 0xff,
545                        (a >> 16) & 0xff, (a >> 8) & 0xff, (a) & 0xff);
546             }
547         }
548     }
549 }
550
551 /*
552  * Read each entry in the database:
553  * Record what type of entry it is and its address in the record array.
554  * Remember what the maximum volume id we found is and check against the header.
555  */
556 void
557 ReadAllEntries(struct vlheader *header)
558 {
559     afs_int32 type, rindex, i, j, e;
560     int freecount = 0, mhcount = 0, vlcount = 0;
561     int rwcount = 0, rocount = 0, bkcount = 0;
562     struct nvlentry vlentry;
563     afs_uint32 addr;
564     afs_uint32 entrysize = 0;
565     afs_uint32 maxvolid = 0;
566
567     if (verbose) quiet_println("Read each entry in the database\n");
568     for (addr = header->vital_header.headersize;
569          addr < header->vital_header.eofPtr; addr += entrysize) {
570
571         /* Remember the highest volume id */
572         readentry(addr, &vlentry, &type);
573         if (type == VL) {
574             if (!(vlentry.flags & VLF_RWEXISTS))
575                 log_error(VLDB_CHECK_WARNING,"VLDB_CHECK_WARNING: VLDB entry '%s' has no RW volume\n",
576                        vlentry.name);
577
578             for (i = 0; i < MAXTYPES; i++)
579                 if (maxvolid < vlentry.volumeId[i])
580                     maxvolid = vlentry.volumeId[i];
581
582             e = 1;
583             for (j = 0; j < NMAXNSERVERS; j++) {
584                 if (vlentry.serverNumber[j] == 255)
585                     continue;
586                 if (vlentry.serverFlags[j] & (VLSF_ROVOL | VLSF_NEWREPSITE)) {
587                     rocount++;
588                     continue;
589                 }
590                 if (vlentry.serverFlags[j] & VLSF_RWVOL) {
591                     rwcount++;
592                     if (vlentry.flags & VLF_BACKEXISTS)
593                         bkcount++;
594                     continue;
595                 }
596                 if (!vlentry.serverFlags[j]) {
597                     /*e = 0;*/
598                     continue;
599                 }
600                 if (e) {
601                    log_error
602                         (VLDB_CHECK_ERROR,"VLDB entry '%s' contains an unknown RW/RO index serverFlag\n",
603                          vlentry.name);
604                     e = 0;
605                 }
606                 quiet_println
607                     ("   index %d : serverNumber %d : serverPartition %d : serverFlag %d\n",
608                      j, vlentry.serverNumber[j], vlentry.serverPartition[j],
609                      vlentry.serverFlags[j]);
610             }
611         }
612
613         rindex = addr / sizeof(vlentry);
614         if (record[rindex].type) {
615             log_error(VLDB_CHECK_ERROR,"INTERNAL VLDB_CHECK_ERROR: record holder %d already in use\n",
616                    rindex);
617             return;
618         }
619         record[rindex].addr = addr;
620         record[rindex].type = type;
621
622         /* Determine entrysize and keep count */
623         if (type == VL) {
624             entrysize = sizeof(vlentry);
625             vlcount++;
626         } else if (type == FR) {
627             entrysize = sizeof(vlentry);
628             freecount++;
629         } else if (type == MH) {
630             entrysize = VL_ADDREXTBLK_SIZE;
631             mhcount++;
632         } else {
633             log_error(VLDB_CHECK_ERROR, "Unknown entry at %u. Aborting\n", addr);
634             break;
635         }
636     }
637     if (verbose) {
638         quiet_println("Found %d entries, %d free entries, %d multihomed blocks\n",
639                vlcount, freecount, mhcount);
640         quiet_println("Found %d RW volumes, %d BK volumes, %d RO volumes\n", rwcount,
641                bkcount, rocount);
642     }
643
644     /* Check the maxmimum volume id in the header */
645     if (maxvolid != header->vital_header.MaxVolumeId - 1)
646         quiet_println
647             ("Header's maximum volume id is %u and largest id found in VLDB is %u\n",
648              header->vital_header.MaxVolumeId, maxvolid);
649 }
650
651 /*
652  * Follow each Name hash bucket marking it as read in the record array.
653  * Record we found it in the name hash within the record array.
654  * Check that the name is hashed correctly.
655  */
656 void
657 FollowNameHash(struct vlheader *header)
658 {
659     int count = 0, longest = 0, shortest = -1, chainlength;
660     struct nvlentry vlentry;
661     afs_uint32 addr;
662     afs_int32 i, type, rindex;
663
664     /* Now follow the Name Hash Table */
665     if (verbose) quiet_println("Check Volume Name Hash\n");
666     for (i = 0; i < HASHSIZE; i++) {
667         chainlength = 0;
668
669         if (!validVolumeAddr(header->VolnameHash[i])) {
670             log_error(VLDB_CHECK_ERROR,"Name Hash %d: Bad entry %u is out of range\n",
671                       i, header->VolnameHash[i]);
672             continue;
673         }
674
675         for (addr = header->VolnameHash[i]; addr; addr = vlentry.nextNameHash) {
676             readentry(addr, &vlentry, &type);
677             if (type != VL) {
678                 log_error(VLDB_CHECK_ERROR,"Name Hash %d: Bad entry at %u: Not a valid vlentry\n",
679                        i, addr);
680                 continue;
681             }
682
683             rindex = ADDR(addr);
684
685             /*
686              * we know that the address is valid because we
687              * checked it either above or below
688              */
689             if (record[rindex].addr != addr && record[rindex].addr) {
690                 log_error
691                     (VLDB_CHECK_ERROR,"INTERNAL VLDB_CHECK_ERROR: addresses %ld and %u use same record slot %d\n",
692                      record[rindex].addr, addr, rindex);
693             }
694             if (record[rindex].type & NH) {
695                 log_error
696                     (VLDB_CHECK_ERROR,"Name Hash %d: Bad entry '%s': Already in the name hash\n",
697                      i, vlentry.name);
698                 record[rindex].type |= MULTN;
699                 break;
700             }
701
702             if (!validVolumeAddr(vlentry.nextNameHash)) {
703                 log_error(VLDB_CHECK_ERROR,"Name Hash forward link of '%s' is out of range\n",
704                           vlentry.name);
705                 record[rindex].type |= MULTN;
706                 break;
707             }
708
709             record[rindex].type |= NH;
710             record[rindex].type |= REFN;
711
712             chainlength++;
713             count++;
714
715             /* Hash the name and check if in correct hash table */
716             if (NameHash(vlentry.name) != i) {
717                 log_error
718                     (VLDB_CHECK_ERROR,"Name Hash %d: Bad entry '%s': Incorrect name hash chain (should be in %d)\n",
719                      i, vlentry.name, NameHash(vlentry.name));
720                 record[rindex].type |= MULTN;
721             }
722         }
723         if (chainlength > longest)
724             longest = chainlength;
725         if ((shortest == -1) || (chainlength < shortest))
726             shortest = chainlength;
727     }
728     if (verbose) {
729         quiet_println
730             ("%d entries in name hash, longest is %d, shortest is %d, average length is %f\n",
731              count, longest, shortest, ((float)count / (float)HASHSIZE));
732     }
733     return;
734 }
735
736 /*
737  * Follow the ID hash chains for the RW, RO, and BK hash tables.
738  * Record we found it in the id hash within the record array.
739  * Check that the ID is hashed correctly.
740  */
741 void
742 FollowIdHash(struct vlheader *header)
743 {
744     int count = 0, longest = 0, shortest = -1, chainlength;
745     struct nvlentry vlentry;
746     afs_uint32 addr;
747     afs_int32 i, j, hash, type, rindex, ref, badref, badhash;
748
749     /* Now follow the RW, RO, and BK Hash Tables */
750     if (verbose) quiet_println("Check RW, RO, and BK id Hashes\n");
751     for (i = 0; i < MAXTYPES; i++) {
752         hash = ((i == 0) ? RWH : ((i == 1) ? ROH : BKH));
753         ref = ((i == 0) ? REFRW : ((i == 1) ? REFRO : REFBK));
754         badref = ((i == 0) ? MULTRW : ((i == 1) ? MULTRO : MULTBK));
755         badhash = ((i == 0) ? MULTRW : ((i == 1) ? MULTRO : MULTBK));
756         count = longest = 0;
757         shortest = -1;
758
759         for (j = 0; j < HASHSIZE; j++) {
760             chainlength = 0;
761             if (!validVolumeAddr(header->VolidHash[i][j])) {
762                 log_error(VLDB_CHECK_ERROR,"%s Hash %d: Bad entry %u is out of range\n",
763                           vtype(i), j, header->VolidHash[i][j]);
764                 continue;
765             }
766
767             for (addr = header->VolidHash[i][j]; addr;
768                  addr = vlentry.nextIdHash[i]) {
769                 readentry(addr, &vlentry, &type);
770                 if (type != VL) {
771                     log_error
772                         (VLDB_CHECK_ERROR,"%s Id Hash %d: Bad entry at %u: Not a valid vlentry\n",
773                          vtype(i), j, addr);
774                     continue;
775                 }
776
777                 rindex = ADDR(addr);
778                 if (record[rindex].addr != addr && record[rindex].addr) {
779                     log_error
780                         (VLDB_CHECK_ERROR,"INTERNAL VLDB_CHECK_ERROR: addresses %ld and %u use same record slot %d\n",
781                          record[rindex].addr, addr, rindex);
782                 }
783                 if (record[rindex].type & hash) {
784                     log_error
785                         (VLDB_CHECK_ERROR,"%s Id Hash %d: Bad entry '%s': Already in the hash table\n",
786                          vtype(i), j, vlentry.name);
787                     record[rindex].type |= badref;
788                     break;
789                 }
790
791                 if (!validVolumeAddr(vlentry.nextIdHash[i])) {
792                     log_error(VLDB_CHECK_ERROR,"%s Id Hash forward link of '%s' is out of range\n",
793                               vtype(i), vlentry.name);
794                     record[rindex].type |= badref;
795                     break;
796                 }
797
798                 record[rindex].type |= hash;
799                 record[rindex].type |= ref;
800
801                 chainlength++;
802                 count++;
803
804                 /* Hash the id and check if in correct hash table */
805                 if (IdHash(vlentry.volumeId[i]) != j) {
806                    log_error
807                         (VLDB_CHECK_ERROR,"%s Id Hash %d: Bad entry '%s': Incorrect Id hash chain (should be in %d)\n",
808                          vtype(i), j, vlentry.name,
809                          IdHash(vlentry.volumeId[i]));
810                     record[rindex].type |= badhash;
811                 }
812             }
813
814             if (chainlength > longest)
815                 longest = chainlength;
816             if ((shortest == -1) || (chainlength < shortest))
817                 shortest = chainlength;
818         }
819         if (verbose) {
820             quiet_println
821                 ("%d entries in %s hash, longest is %d, shortest is %d, average length is %f\n",
822                  count, vtype(i), longest, shortest,((float)count / (float)HASHSIZE));
823         }
824     }
825     return;
826 }
827
828 /*
829  * Follow the free chain.
830  * Record we found it in the free chain within the record array.
831  */
832 void
833 FollowFreeChain(struct vlheader *header)
834 {
835     afs_int32 count = 0;
836     struct nvlentry vlentry;
837     afs_uint32 addr;
838     afs_int32 type, rindex;
839
840     /* Now follow the Free Chain */
841     if (verbose) quiet_println("Check Volume Free Chain\n");
842     for (addr = header->vital_header.freePtr; addr;
843          addr = vlentry.nextIdHash[0]) {
844         readentry(addr, &vlentry, &type);
845         if (type != FR) {
846            log_error
847                 (VLDB_CHECK_ERROR,"Free Chain %d: Bad entry at %u: Not a valid free vlentry (0x%x)\n",
848                  count, addr, type);
849             continue;
850         }
851
852         rindex = addr / sizeof(vlentry);
853         if (record[rindex].addr != addr && record[rindex].addr) {
854            log_error
855                 (VLDB_CHECK_ERROR,"INTERNAL VLDB_CHECK_ERROR: addresses %u and %ld use same record slot %d\n",
856                  record[rindex].addr, addr, rindex);
857         }
858         if (record[rindex].type & FRC) {
859             log_error(VLDB_CHECK_ERROR,"Free Chain: Bad entry at %u: Already in the free chain\n",
860                    addr);
861             break;
862         }
863         record[rindex].type |= FRC;
864
865         count++;
866     }
867     if (verbose)
868      quiet_println("%d entries on free chain\n", count);
869     return;
870 }
871
872 /*
873  * Read each multihomed block and mark it as found in the record.
874  * Read each entry in each multihomed block and mark the serveraddrs
875  * array with the number of ip addresses found for this entry.
876  *
877  * Then read the IpMappedAddr array in the header.
878  * Verify that multihomed entries base and index are valid and points to
879  * a good multhomed entry.
880  * Mark the serveraddrs array with 1 ip address for regular entries.
881  *
882  * By the end, the severaddrs array will have a 0 if the entry has no
883  * IP addresses in it or the count of the number of IP addresses.
884  *
885  * The code does not verify if there are duplicate IP addresses in the
886  * list. The vlserver does this when a fileserver registeres itself.
887  */
888 void
889 CheckIpAddrs(struct vlheader *header)
890 {
891     int mhblocks = 0;
892     afs_int32 i, j, m, rindex;
893     afs_int32 mhentries, regentries;
894     afs_uint32 caddrs[VL_MAX_ADDREXTBLKS];
895     char mhblock[VL_ADDREXTBLK_SIZE];
896     struct extentaddr *MHblock = (struct extentaddr *)mhblock;
897     struct extentaddr *e;
898     int ipindex, ipaddrs;
899     afsUUID nulluuid;
900
901     memset(&nulluuid, 0, sizeof(nulluuid));
902
903     if (verbose)
904         quiet_println("Check Multihomed blocks\n");
905
906     if (header->SIT) {
907         /* Read the first MH block and from it, gather the
908          * addresses of all the mh blocks.
909          */
910         readMH(header->SIT, MHblock);
911         if (MHblock->ex_flags != VLCONTBLOCK) {
912            log_error
913                 (VLDB_CHECK_ERROR,"Multihomed Block 0: Bad entry at %u: Not a valid multihomed block\n",
914                  header->SIT);
915         }
916
917         for (i = 0; i < VL_MAX_ADDREXTBLKS; i++) {
918             caddrs[i] = MHblock->ex_contaddrs[i];
919         }
920
921         if (header->SIT != caddrs[0]) {
922            log_error
923                 (VLDB_CHECK_ERROR,"MH block does not point to self %u in header, %u in block\n",
924                  header->SIT, caddrs[0]);
925         }
926
927         /* Now read each MH block and record it in the record array */
928         for (i = 0; i < VL_MAX_ADDREXTBLKS; i++) {
929             if (!caddrs[i])
930                 continue;
931
932             readMH(caddrs[i], MHblock);
933             if (MHblock->ex_flags != VLCONTBLOCK) {
934                 log_error
935                     (VLDB_CHECK_ERROR,"Multihomed Block 0: Bad entry at %u: Not a valid multihomed block\n",
936                      header->SIT);
937             }
938
939             rindex = caddrs[i] / sizeof(vlentry);
940             if (record[rindex].addr != caddrs[i] && record[rindex].addr) {
941                 log_error
942                     (VLDB_CHECK_ERROR,"INTERNAL VLDB_CHECK_ERROR: addresses %u and %u use same record slot %d\n",
943                      record[rindex].addr, caddrs[i], rindex);
944             }
945             if (record[rindex].type & FRC) {
946                 log_error
947                     (VLDB_CHECK_ERROR,"MH Blocks Chain %d: Bad entry at %ld: Already a MH block\n",
948                      i, record[rindex].addr);
949                 break;
950             }
951             record[rindex].type |= MHC;
952
953             mhblocks++;
954
955             /* Read each entry in a multihomed block.
956              * Find the pointer to the entry in the IpMappedAddr array and
957              * verify that the entry is good (has IP addresses in it).
958              */
959             mhentries = 0;
960             for (j = 1; j < VL_MHSRV_PERBLK; j++) {
961                 e = (struct extentaddr *)&(MHblock[j]);
962
963                 /* Search the IpMappedAddr array for the reference to this entry */
964                 for (ipindex = 0; ipindex < MAXSERVERID; ipindex++) {
965                     if (((header->IpMappedAddr[ipindex] & 0xff000000) ==
966                          0xff000000)
967                         &&
968                         (((header->
969                            IpMappedAddr[ipindex] & 0x00ff0000) >> 16) == i)
970                         && ((header->IpMappedAddr[ipindex] & 0x0000ffff) ==
971                             j)) {
972                         break;
973                     }
974                 }
975                 if (ipindex >= MAXSERVERID)
976                     ipindex = -1;
977                 else
978                     serveraddrs[ipindex] = -1;
979
980                 if (memcmp(&e->ex_hostuuid, &nulluuid, sizeof(afsUUID)) == 0) {
981                     if (ipindex != -1) {
982                         log_error
983                             (VLDB_CHECK_ERROR,"Server Addrs index %d references null MH block %d, index %d\n",
984                              ipindex, i, j);
985                         serveraddrs[ipindex] = 0;       /* avoids printing 2nd error below */
986                     }
987                     continue;
988                 }
989
990                 /* Step through each ip address and count the good addresses */
991                 ipaddrs = 0;
992                 for (m = 0; m < VL_MAXIPADDRS_PERMH; m++) {
993                     if (e->ex_addrs[m])
994                         ipaddrs++;
995                 }
996
997                 /* If we found any good ip addresses, mark it in the serveraddrs record */
998                 if (ipaddrs) {
999                     mhentries++;
1000                     if (ipindex == -1) {
1001                         log_error
1002                             (VLDB_CHECK_ERROR,"MH block %d, index %d: Not referenced by server addrs\n",
1003                              i, j);
1004                     } else {
1005                         serveraddrs[ipindex] = ipaddrs; /* It is good */
1006                     }
1007                 }
1008
1009                 if (listservers && ipaddrs) {
1010                     quiet_println("MH block %d, index %d:", i, j);
1011                     for (m = 0; m < VL_MAXIPADDRS_PERMH; m++) {
1012                         if (!e->ex_addrs[m])
1013                             continue;
1014                         quiet_println(" %d.%d.%d.%d",
1015                                (e->ex_addrs[m] & 0xff000000) >> 24,
1016                                (e->ex_addrs[m] & 0x00ff0000) >> 16,
1017                                (e->ex_addrs[m] & 0x0000ff00) >> 8,
1018                                (e->ex_addrs[m] & 0x000000ff));
1019                     }
1020                     quiet_println("\n");
1021                 }
1022             }
1023 /*
1024  *      if (mhentries != MHblock->ex_count) {
1025  *         quiet_println("MH blocks says it has %d entries (found %d)\n",
1026  *                MHblock->ex_count, mhentries);
1027  *      }
1028  */
1029         }
1030     }
1031     if (verbose)
1032         quiet_println("%d multihomed blocks\n", mhblocks);
1033
1034     /* Check the server addresses */
1035     if (verbose)
1036         quiet_println("Check server addresses\n");
1037     mhentries = regentries = 0;
1038     for (i = 0; i <= MAXSERVERID; i++) {
1039         if (header->IpMappedAddr[i]) {
1040             if ((header->IpMappedAddr[i] & 0xff000000) == 0xff000000) {
1041                 mhentries++;
1042                 if (((header->IpMappedAddr[i] & 0x00ff0000) >> 16) >
1043                     VL_MAX_ADDREXTBLKS)
1044                    log_error
1045                         (VLDB_CHECK_ERROR,"IP Addr for entry %d: Multihome block is bad (%d)\n",
1046                          i, ((header->IpMappedAddr[i] & 0x00ff0000) >> 16));
1047                 if (((header->IpMappedAddr[i] & 0x0000ffff) > VL_MHSRV_PERBLK)
1048                     || ((header->IpMappedAddr[i] & 0x0000ffff) < 1))
1049                     log_error
1050                         (VLDB_CHECK_ERROR,"IP Addr for entry %d: Multihome index is bad (%d)\n",
1051                          i, (header->IpMappedAddr[i] & 0x0000ffff));
1052                 if (serveraddrs[i] == -1) {
1053                     log_error
1054                         (VLDB_CHECK_WARNING,"warning: IP Addr for entry %d: Multihome entry has no ip addresses\n",
1055                          i);
1056                     serveraddrs[i] = 0;
1057                 }
1058                 if (listservers) {
1059                     quiet_println("   Server ip addr %d = MH block %d, index %d\n",
1060                            i, (header->IpMappedAddr[i] & 0x00ff0000) >> 16,
1061                            (header->IpMappedAddr[i] & 0x0000ffff));
1062                 }
1063             } else {
1064                 regentries++;
1065                 serveraddrs[i] = 1;     /* It is good */
1066                 if (listservers) {
1067                     quiet_println("   Server ip addr %d = %d.%d.%d.%d\n", i,
1068                            (header->IpMappedAddr[i] & 0xff000000) >> 24,
1069                            (header->IpMappedAddr[i] & 0x00ff0000) >> 16,
1070                            (header->IpMappedAddr[i] & 0x0000ff00) >> 8,
1071                            (header->IpMappedAddr[i] & 0x000000ff));
1072                 }
1073             }
1074         }
1075     }
1076     if (verbose) {
1077         quiet_println("%d simple entries, %d multihomed entries, Total = %d\n",
1078                regentries, mhentries, mhentries + regentries);
1079     }
1080     return;
1081 }
1082
1083 char *
1084 nameForAddr(afs_uint32 addr, int hashtype, afs_uint32 *hash, char *buffer)
1085 {
1086     /*
1087      * We need to simplify the reporting, while retaining
1088      * legible messages.  This is a helper function.  The return address
1089      * is either a fixed char or the provided buffer - so don't use the
1090      * name after the valid lifetime of the buffer.
1091      */
1092     afs_int32 type;
1093     struct nvlentry entry;
1094     if (!addr) {
1095         /* Distinguished, invalid, hash */
1096         *hash = 0xFFFFFFFF;
1097         return "empty";
1098     } else if (!validVolumeAddr(addr)) {
1099         /* Different, invalid, hash */
1100         *hash = 0XFFFFFFFE;
1101         return "invalid";
1102     }
1103     readentry(addr, &entry, &type);
1104     if (VL != type) {
1105         *hash = 0XFFFFFFFE;
1106         return "invalid";
1107     }
1108     if (hashtype >= MAXTYPES) {
1109         *hash = NameHash(entry.name);
1110     } else {
1111         *hash = IdHash(entry.volumeId[hashtype]);
1112     }
1113     sprintf(buffer, "for '%s'", entry.name);
1114     return buffer;
1115 }
1116
1117 void
1118 reportHashChanges(struct vlheader *header, afs_uint32 oldnamehash[HASHSIZE], afs_uint32 oldidhash[MAXTYPES][HASHSIZE])
1119 {
1120     int i, j;
1121     afs_uint32 oldhash, newhash;
1122     char oldNameBuffer[10 + VL_MAXNAMELEN];
1123     char newNameBuffer[10 + VL_MAXNAMELEN];
1124     char *oldname, *newname;
1125     /*
1126      * report hash changes
1127      */
1128
1129     for (i = 0; i < HASHSIZE; i++) {
1130         if (oldnamehash[i] != header->VolnameHash[i]) {
1131
1132             oldname = nameForAddr(oldnamehash[i], MAXTYPES, &oldhash, oldNameBuffer);
1133             newname = nameForAddr(header->VolnameHash[i], MAXTYPES, &newhash, newNameBuffer);
1134             if (verbose || (oldhash != newhash)) {
1135                 quiet_println("FIX: Name hash header at %d was %s, is now %s\n", i, oldname, newname);
1136             }
1137         }
1138         for (j = 0; j < MAXTYPES; j++) {
1139             if (oldidhash[j][i] != header->VolidHash[j][i]) {
1140
1141                 oldname = nameForAddr(oldidhash[j][i], j, &oldhash, oldNameBuffer);
1142                 newname = nameForAddr(header->VolidHash[j][i], j, &newhash, newNameBuffer);
1143                 if (verbose || (oldhash != newhash)) {
1144                     quiet_println("FIX: %s hash header at %d was %s, is now %s\n", vtype(j), i, oldname, newname);
1145                 }
1146             }
1147         }
1148     }
1149 }
1150
1151 int
1152 WorkerBee(struct cmd_syndesc *as, void *arock)
1153 {
1154     char *dbfile;
1155     afs_int32 type;
1156     struct vlheader header;
1157     struct nvlentry vlentry, vlentry2;
1158     int i, j;
1159     afs_uint32 oldnamehash[HASHSIZE];
1160     afs_uint32 oldidhash[MAXTYPES][HASHSIZE];
1161
1162     error_level = 0;  /*  start clean with no error status */
1163     dbfile = as->parms[0].items->data;  /* -database */
1164     listuheader = (as->parms[1].items ? 1 : 0); /* -uheader  */
1165     listheader = (as->parms[2].items ? 1 : 0);  /* -vheader  */
1166     listservers = (as->parms[3].items ? 1 : 0); /* -servers  */
1167     listentries = (as->parms[4].items ? 1 : 0); /* -entries  */
1168     verbose = (as->parms[5].items ? 1 : 0);     /* -verbose  */
1169     quiet = (as->parms[6].items ? 1 : 0);  /* -quiet */
1170     fix = (as->parms[7].items ? 1 : 0);    /* -fix  */
1171
1172     /* sanity check */
1173     if (quiet && (verbose || listuheader || listheader ||listservers \
1174                 || listentries)) {
1175         log_error(VLDB_CHECK_FATAL," -quiet cannot be used other display flags\n");
1176         return VLDB_CHECK_FATAL;
1177     }
1178
1179
1180     /* open the vldb database file */
1181     fd = open(dbfile, (fix > 0)?O_RDWR:O_RDONLY, 0);
1182     if (fd < 0) {
1183         log_error(VLDB_CHECK_FATAL,"can't open file '%s'. error = %d\n", dbfile, errno);
1184         return 0;
1185     }
1186
1187     /* read the ubik header and the vldb database header */
1188     readUbikHeader();
1189     readheader(&header);
1190     if (header.vital_header.vldbversion < 3) {
1191         log_error(VLDB_CHECK_FATAL,"does not support vldb with version less than 3\n");
1192         return VLDB_CHECK_FATAL;
1193     }
1194
1195     maxentries = (header.vital_header.eofPtr / sizeof(vlentry)) + 1;
1196     record = (struct er *)malloc(maxentries * sizeof(struct er));
1197     memset(record, 0, (maxentries * sizeof(struct er)));
1198     memset(serveraddrs, 0, sizeof(serveraddrs));
1199
1200     /* Will fill in the record array of entries it found */
1201     ReadAllEntries(&header);
1202     listentries = 0;            /* Listed all the entries */
1203
1204     /* Check the multihomed blocks for valid entries as well as
1205      * the IpMappedAddrs array in the header for valid entries.
1206      */
1207     CheckIpAddrs(&header);
1208
1209     /* Follow the hash tables */
1210     FollowNameHash(&header);
1211     FollowIdHash(&header);
1212
1213     /* Follow the chain of free entries */
1214     FollowFreeChain(&header);
1215
1216     /* Now check the record we have been keeping for inconsistencies
1217      * For valid vlentries, also check that the server we point to is
1218      * valid (the serveraddrs array).
1219      */
1220     if (verbose)
1221         quiet_println("Verify each volume entry\n");
1222     for (i = 0; i < maxentries; i++) {
1223         int hash = 0;
1224         int nexthash = 0;
1225         char *which = NULL;
1226
1227         if (record[i].type == 0)
1228             continue;
1229
1230         /* If a vlentry, verify that its name is valid, its name and ids are
1231          * on the hash chains, and its server numbers are good.
1232          */
1233         if (record[i].type & VL) {
1234             int foundbad = 0;
1235             int foundbroken = 0;
1236             char volidbuf[256];
1237
1238             readentry(record[i].addr, &vlentry, &type);
1239
1240             if (InvalidVolname(vlentry.name))
1241                 log_error(VLDB_CHECK_ERROR,"Volume '%s' at addr %ld has an invalid name\n",
1242                        vlentry.name, record[i].addr);
1243
1244             if (!(record[i].type & NH)) {
1245                 hash = NameHash(vlentry.name);
1246                 which = "name";
1247                 volidbuf[0]='\0';
1248                 foundbad = 1;
1249             }
1250
1251             if (vlentry.volumeId[0] && !(record[i].type & RWH)) {
1252                 hash = IdHash(vlentry.volumeId[0]);
1253                 which = "RW";
1254                 sprintf(volidbuf, "id %u ", vlentry.volumeId[0]);
1255                 foundbad = 1;
1256             }
1257
1258             if (vlentry.volumeId[1] && !(record[i].type & ROH)) {
1259                 hash = IdHash(vlentry.volumeId[1]);
1260                 which = "RO";
1261                 sprintf(volidbuf, "id %u ", vlentry.volumeId[1]);
1262                 foundbad = 1;
1263             }
1264
1265             if (vlentry.volumeId[2] && !(record[i].type & BKH)) {
1266                 hash = IdHash(vlentry.volumeId[2]);
1267                 which = "BK";
1268                 sprintf(volidbuf, "id %u ", vlentry.volumeId[2]);
1269                 foundbad = 1;
1270             }
1271
1272             if (!validVolumeAddr(vlentry.nextNameHash) ||
1273                 record[ADDR(vlentry.nextNameHash)].type & MULTN) {
1274                 hash = NameHash(vlentry.name);
1275                 which = "name";
1276                 volidbuf[0]='\0';
1277                 if (validVolumeAddr(vlentry.nextNameHash)) {
1278                     readentry(vlentry.nextNameHash, &vlentry2, &type);
1279                     nexthash = NameHash(vlentry2.name);
1280                 } else {
1281                     nexthash = 0xFFFFFFFF;
1282                 }
1283                 if (hash != nexthash)
1284                     foundbroken = 1;
1285             }
1286
1287             if (!validVolumeAddr(vlentry.nextIdHash[0]) ||
1288                 record[ADDR(vlentry.nextIdHash[0])].type & MULTRW) {
1289                 hash = IdHash(vlentry.volumeId[0]);
1290                 which = "RW";
1291                 sprintf(volidbuf, "id %u ", vlentry.volumeId[0]);
1292                 if (validVolumeAddr(vlentry.nextIdHash[0])) {
1293                     readentry(vlentry.nextIdHash[0], &vlentry2, &type);
1294                     nexthash = IdHash(vlentry2.volumeId[0]);
1295                 } else {
1296                     nexthash = 0xFFFFFFFF;
1297                 }
1298                 if (hash != nexthash)
1299                     foundbroken = 1;
1300             }
1301
1302             if (!validVolumeAddr(vlentry.nextIdHash[1]) ||
1303                 record[ADDR(vlentry.nextIdHash[1])].type & MULTRO) {
1304                 hash = IdHash(vlentry.volumeId[1]);
1305                 which = "RO";
1306                 sprintf(volidbuf, "id %u ", vlentry.volumeId[1]);
1307                 if (validVolumeAddr(vlentry.nextIdHash[1])) {
1308                     readentry(vlentry.nextIdHash[1], &vlentry2, &type);
1309                     nexthash = IdHash(vlentry2.volumeId[1]);
1310                 } else {
1311                     nexthash = 0xFFFFFFFF;
1312                 }
1313                 if (hash != nexthash)
1314                     foundbroken = 1;
1315             }
1316
1317             if (!validVolumeAddr(vlentry.nextIdHash[2]) ||
1318                 record[ADDR(vlentry.nextIdHash[2])].type & MULTBK) {
1319                 hash = IdHash(vlentry.volumeId[2]);
1320                 which = "BK";
1321                 sprintf(volidbuf, "id %u ", vlentry.volumeId[2]);
1322                 if (validVolumeAddr(vlentry.nextIdHash[2])) {
1323                     readentry(vlentry.nextIdHash[2], &vlentry2, &type);
1324                     nexthash = IdHash(vlentry2.volumeId[2]);
1325                 } else {
1326                     nexthash = 0xFFFFFFFF;
1327                 }
1328                 if (hash != nexthash)
1329                     foundbroken = 1;
1330             }
1331
1332             if (foundbroken) {
1333                 log_error(VLDB_CHECK_ERROR, "%d: Volume '%s' %s forward link in %s hash chain is broken (hash %d != %d)\n", i,
1334                           vlentry.name, volidbuf, which, hash, nexthash);
1335             } else if (foundbad) {
1336                 log_error(VLDB_CHECK_ERROR, "%d: Volume '%s' %snot found in %s hash %d\n", i,
1337                        vlentry.name, volidbuf, which, hash);
1338             }
1339
1340             for (j = 0; j < NMAXNSERVERS; j++) {
1341                 if ((vlentry.serverNumber[j] != 255)
1342                     && (serveraddrs[vlentry.serverNumber[j]] == 0)) {
1343                    log_error
1344                         (VLDB_CHECK_ERROR,"Volume '%s', index %d points to empty server entry %d\n",
1345                          vlentry.name, j, vlentry.serverNumber[j]);
1346                 }
1347             }
1348
1349             if (record[i].type & 0xffff0f00)
1350                 log_error
1351                     (VLDB_CHECK_ERROR,"Volume '%s' id %u also found on other chains (0x%x)\n",
1352                      vlentry.name, vlentry.volumeId[0], record[i].type);
1353
1354             /* A free entry */
1355         } else if (record[i].type & FR) {
1356             if (!(record[i].type & FRC))
1357                 log_error(VLDB_CHECK_ERROR,"Free vlentry at %ld not on free chain\n",
1358                        record[i].addr);
1359
1360             if (record[i].type & 0xfffffdf0)
1361                 log_error
1362                     (VLDB_CHECK_ERROR,"Free vlentry at %ld also found on other chains (0x%x)\n",
1363                      record[i].addr, record[i].type);
1364
1365             /* A multihomed entry */
1366         } else if (record[i].type & MH) {
1367             if (!(record[i].type & MHC))
1368                 log_error(VLDB_CHECK_ERROR,"Multihomed block at %ld is orphaned\n",
1369                        record[i].addr);
1370
1371             if (record[i].type & 0xfffffef0)
1372                 log_error
1373                     (VLDB_CHECK_ERROR,"Multihomed block at %ld also found on other chains (0x%x)\n",
1374                      record[i].addr, record[i].type);
1375
1376         } else {
1377             log_error(VLDB_CHECK_ERROR,"Unknown entry type at %u (0x%x)\n", record[i].addr,
1378                    record[i].type);
1379         }
1380     }
1381
1382     if (fix) {
1383         /*
1384          * If we are fixing we will rebuild all the hash lists from the ground up
1385          */
1386         memcpy(oldnamehash, header.VolnameHash, sizeof(oldnamehash));
1387         memset(header.VolnameHash, 0, sizeof(header.VolnameHash));
1388
1389         memcpy(oldidhash, header.VolidHash, sizeof(oldidhash));
1390         memset(header.VolidHash, 0, sizeof(header.VolidHash));
1391         quiet_println("Rebuilding %u entries\n", maxentries);
1392     } else {
1393         quiet_println("Scanning %u entries for possible repairs\n", maxentries);
1394     }
1395     for (i = 0; i < maxentries; i++) {
1396         afs_uint32 hash;
1397         if (record[i].type & VL) {
1398             readentry(record[i].addr, &vlentry, &type);
1399             if (!(record[i].type & REFN)) {
1400                 log_error(VLDB_CHECK_ERROR,"%d: Record %ld (type 0x%x) not in a name chain\n", i,
1401                        record[i].addr, record[i].type);
1402             }
1403             if (vlentry.volumeId[0] && !(record[i].type & REFRW)) {
1404                 log_error(VLDB_CHECK_ERROR,"%d: Record %ld (type 0x%x) not in a RW chain\n", i,
1405                        record[i].addr, record[i].type);
1406             }
1407             if (vlentry.volumeId[1] && !(record[i].type & REFRO)) {
1408                 log_error(VLDB_CHECK_ERROR,"%d: Record %ld (type 0x%x) not in a RO chain\n", i,
1409                        record[i].addr, record[i].type);
1410             }
1411             if (vlentry.volumeId[2] && !(record[i].type & REFBK)) {
1412                 log_error(VLDB_CHECK_ERROR,"%d: Record %ld (type 0x%x) not in a BK chain\n", i,
1413                        record[i].addr, record[i].type);
1414             }
1415             if (fix) {
1416                 afs_uint32 oldhash, newhash;
1417                 char oldNameBuffer[10 + VL_MAXNAMELEN];
1418                 char newNameBuffer[10 + VL_MAXNAMELEN];
1419                 char *oldname, *newname;
1420
1421                 /*
1422                  * Put the current hash table contexts into our 'next'
1423                  * and our address into the hash table.
1424                  */
1425                 hash = NameHash(vlentry.name);
1426
1427                 if (vlentry.nextNameHash != header.VolnameHash[hash]) {
1428                     oldname = nameForAddr(vlentry.nextNameHash, MAXTYPES, &oldhash, oldNameBuffer);
1429                     newname = nameForAddr(header.VolnameHash[hash], MAXTYPES, &newhash, newNameBuffer);
1430                     if (verbose || ((oldhash != newhash) &&
1431                                     (0 != vlentry.nextNameHash) &&
1432                                     (0 != header.VolnameHash[hash]))) {
1433                         /*
1434                          * That is, only report if we are verbose
1435                          * or the hash is changing (and one side wasn't NULL
1436                          */
1437                         quiet_println("FIX: Name hash link for '%s' was %s, is now %s\n",
1438                               vlentry.name, oldname, newname);
1439                     }
1440                 }
1441
1442                 vlentry.nextNameHash = header.VolnameHash[hash];
1443                 header.VolnameHash[hash] = record[i].addr;
1444
1445                 for (j = 0; j < MAXTYPES; j++) {
1446
1447                     if (0 == vlentry.volumeId[j]) {
1448                         /*
1449                          * No volume of that type.  Continue
1450                          */
1451                         continue;
1452                     }
1453                     hash = IdHash(vlentry.volumeId[j]);
1454
1455                     if (vlentry.nextIdHash[j] != header.VolidHash[j][hash]) {
1456                         oldname = nameForAddr(vlentry.nextIdHash[j], j, &oldhash, oldNameBuffer);
1457                         newname = nameForAddr(header.VolidHash[j][hash], j, &newhash, newNameBuffer);
1458                         if (verbose || ((oldhash != newhash) &&
1459                                         (0 != vlentry.nextIdHash[j]) &&
1460                                         (0 != header.VolidHash[j][hash]))) {
1461                             quiet_println("FIX: %s hash link for '%s' was %s, is now %s\n",
1462                                           vtype(j), vlentry.name, oldname, newname);
1463                         }
1464                     }
1465
1466                     vlentry.nextIdHash[j] = header.VolidHash[j][hash];
1467                     header.VolidHash[j][hash] = record[i].addr;
1468                 }
1469                 writeentry(record[i].addr, &vlentry);
1470             }
1471         }
1472     }
1473     if (fix) {
1474         reportHashChanges(&header, oldnamehash, oldidhash);
1475         writeheader(&header);
1476     }
1477
1478     close(fd);
1479
1480     return error_level;
1481 }
1482
1483 int
1484 main(int argc, char **argv)
1485 {
1486     struct cmd_syndesc *ts;
1487
1488     setlinebuf(stdout);
1489
1490     ts = cmd_CreateSyntax(NULL, WorkerBee, NULL, "vldb check");
1491     cmd_AddParm(ts, "-database", CMD_SINGLE, CMD_REQUIRED, "vldb_file");
1492     cmd_AddParm(ts, "-uheader", CMD_FLAG, CMD_OPTIONAL,
1493                 "Display UBIK header");
1494     cmd_AddParm(ts, "-vheader", CMD_FLAG, CMD_OPTIONAL,
1495                 "Display VLDB header");
1496     cmd_AddParm(ts, "-servers", CMD_FLAG, CMD_OPTIONAL,
1497                 "Display server list");
1498     cmd_AddParm(ts, "-entries", CMD_FLAG, CMD_OPTIONAL, "Display entries");
1499     cmd_AddParm(ts, "-verbose", CMD_FLAG, CMD_OPTIONAL, "verbose");
1500     cmd_AddParm(ts, "-quiet", CMD_FLAG, CMD_OPTIONAL, "quiet");
1501     cmd_AddParm(ts, "-fix", CMD_FLAG, CMD_OPTIONAL, "attempt to patch the database (potentially dangerous)");
1502
1503     return cmd_Dispatch(argc, argv);
1504 }