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