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