1d572f0f7053257864d30544fbf1ee96f3a6928b
[openafs.git] / src / vlserver / vlutils.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
14 #include <sys/types.h>
15 #include <string.h>
16 #ifdef AFS_NT40_ENV
17 #include <winsock2.h>
18 #else
19 #include <netinet/in.h>
20 #endif
21
22 #include <lock.h>
23 #include <rx/xdr.h>
24 #include <ubik.h>
25 #include "vlserver.h"
26 #include "vlserver_internal.h"
27
28 extern struct vlheader cheader;
29 struct vlheader xheader;
30 extern afs_uint32 HostAddress[];
31 extern int maxnservers;
32 struct extentaddr extentaddr;
33 extern struct extentaddr *ex_addr[];
34 int vldbversion = 0;
35
36 static int index_OK(struct ubik_trans *trans, afs_int32 blockindex);
37
38 #define ERROR_EXIT(code) {error=(code); goto error_exit;}
39
40 /* Hashing algorithm based on the volume id; HASHSIZE must be prime */
41 afs_int32
42 IDHash(afs_int32 volumeid)
43 {
44     return ((abs(volumeid)) % HASHSIZE);
45 }
46
47
48 /* Hashing algorithm based on the volume name; name's size is implicit (64 chars) and if changed it should be reflected here. */
49 afs_int32
50 NameHash(register char *volumename)
51 {
52     register unsigned int hash;
53     register int i;
54
55     hash = 0;
56     for (i = strlen(volumename), volumename += i - 1; i--; volumename--)
57         hash = (hash * 63) + (*((unsigned char *)volumename) - 63);
58     return (hash % HASHSIZE);
59 }
60
61
62 /* package up seek and write into one procedure for ease of use */
63 afs_int32
64 vlwrite(struct ubik_trans *trans, afs_int32 offset, void *buffer,
65         afs_int32 length)
66 {
67     afs_int32 errorcode;
68
69     if ((errorcode = ubik_Seek(trans, 0, offset)))
70         return errorcode;
71     return (ubik_Write(trans, buffer, length));
72 }
73
74
75 /* Package up seek and read into one procedure for ease of use */
76 afs_int32
77 vlread(struct ubik_trans *trans, afs_int32 offset, char *buffer,
78        afs_int32 length)
79 {
80     afs_int32 errorcode;
81
82     if ((errorcode = ubik_Seek(trans, 0, offset)))
83         return errorcode;
84     return (ubik_Read(trans, buffer, length));
85 }
86
87
88 /* take entry and convert to network order and write to disk */
89 afs_int32
90 vlentrywrite(struct ubik_trans *trans, afs_int32 offset, void *buffer,
91              afs_int32 length)
92 {
93     struct vlentry oentry;
94     struct nvlentry nentry, *nep;
95     char *bufp;
96     register afs_int32 i;
97
98     if (length != sizeof(oentry))
99         return -1;
100     if (maxnservers == 13) {
101         nep = (struct nvlentry *)buffer;
102         for (i = 0; i < MAXTYPES; i++)
103             nentry.volumeId[i] = htonl(nep->volumeId[i]);
104         nentry.flags = htonl(nep->flags);
105         nentry.LockAfsId = htonl(nep->LockAfsId);
106         nentry.LockTimestamp = htonl(nep->LockTimestamp);
107         nentry.cloneId = htonl(nep->cloneId);
108         for (i = 0; i < MAXTYPES; i++)
109             nentry.nextIdHash[i] = htonl(nep->nextIdHash[i]);
110         nentry.nextNameHash = htonl(nep->nextNameHash);
111         memcpy(nentry.name, nep->name, VL_MAXNAMELEN);
112         memcpy(nentry.serverNumber, nep->serverNumber, NMAXNSERVERS);
113         memcpy(nentry.serverPartition, nep->serverPartition, NMAXNSERVERS);
114         memcpy(nentry.serverFlags, nep->serverFlags, NMAXNSERVERS);
115         bufp = (char *)&nentry;
116     } else {
117         memset(&oentry, 0, sizeof(struct vlentry));
118         nep = (struct nvlentry *)buffer;
119         for (i = 0; i < MAXTYPES; i++)
120             oentry.volumeId[i] = htonl(nep->volumeId[i]);
121         oentry.flags = htonl(nep->flags);
122         oentry.LockAfsId = htonl(nep->LockAfsId);
123         oentry.LockTimestamp = htonl(nep->LockTimestamp);
124         oentry.cloneId = htonl(nep->cloneId);
125         for (i = 0; i < MAXTYPES; i++)
126             oentry.nextIdHash[i] = htonl(nep->nextIdHash[i]);
127         oentry.nextNameHash = htonl(nep->nextNameHash);
128         memcpy(oentry.name, nep->name, VL_MAXNAMELEN);
129         memcpy(oentry.serverNumber, nep->serverNumber, OMAXNSERVERS);
130         memcpy(oentry.serverPartition, nep->serverPartition, OMAXNSERVERS);
131         memcpy(oentry.serverFlags, nep->serverFlags, OMAXNSERVERS);
132         bufp = (char *)&oentry;
133     }
134     return vlwrite(trans, offset, bufp, length);
135 }
136
137 /* read entry and convert to host order and write to disk */
138 afs_int32
139 vlentryread(struct ubik_trans *trans, afs_int32 offset, char *buffer,
140             afs_int32 length)
141 {
142     struct vlentry *oep, tentry;
143     struct nvlentry *nep, *nbufp;
144     char *bufp = (char *)&tentry;
145     register afs_int32 i;
146
147     if (length != sizeof(vlentry))
148         return -1;
149     i = vlread(trans, offset, bufp, length);
150     if (i)
151         return i;
152     if (maxnservers == 13) {
153         nep = (struct nvlentry *)bufp;
154         nbufp = (struct nvlentry *)buffer;
155         for (i = 0; i < MAXTYPES; i++)
156             nbufp->volumeId[i] = ntohl(nep->volumeId[i]);
157         nbufp->flags = ntohl(nep->flags);
158         nbufp->LockAfsId = ntohl(nep->LockAfsId);
159         nbufp->LockTimestamp = ntohl(nep->LockTimestamp);
160         nbufp->cloneId = ntohl(nep->cloneId);
161         for (i = 0; i < MAXTYPES; i++)
162             nbufp->nextIdHash[i] = ntohl(nep->nextIdHash[i]);
163         nbufp->nextNameHash = ntohl(nep->nextNameHash);
164         memcpy(nbufp->name, nep->name, VL_MAXNAMELEN);
165         memcpy(nbufp->serverNumber, nep->serverNumber, NMAXNSERVERS);
166         memcpy(nbufp->serverPartition, nep->serverPartition, NMAXNSERVERS);
167         memcpy(nbufp->serverFlags, nep->serverFlags, NMAXNSERVERS);
168     } else {
169         oep = (struct vlentry *)bufp;
170         nbufp = (struct nvlentry *)buffer;
171         memset(nbufp, 0, sizeof(struct nvlentry));
172         for (i = 0; i < MAXTYPES; i++)
173             nbufp->volumeId[i] = ntohl(oep->volumeId[i]);
174         nbufp->flags = ntohl(oep->flags);
175         nbufp->LockAfsId = ntohl(oep->LockAfsId);
176         nbufp->LockTimestamp = ntohl(oep->LockTimestamp);
177         nbufp->cloneId = ntohl(oep->cloneId);
178         for (i = 0; i < MAXTYPES; i++)
179             nbufp->nextIdHash[i] = ntohl(oep->nextIdHash[i]);
180         nbufp->nextNameHash = ntohl(oep->nextNameHash);
181         memcpy(nbufp->name, oep->name, VL_MAXNAMELEN);
182         memcpy(nbufp->serverNumber, oep->serverNumber, NMAXNSERVERS);
183         memcpy(nbufp->serverPartition, oep->serverPartition, NMAXNSERVERS);
184         memcpy(nbufp->serverFlags, oep->serverFlags, NMAXNSERVERS);
185     }
186     return 0;
187 }
188
189 /* Convenient write of small critical vldb header info to the database. */
190 int
191 write_vital_vlheader(register struct ubik_trans *trans)
192 {
193     if (vlwrite
194         (trans, 0, (char *)&cheader.vital_header, sizeof(vital_vlheader)))
195         return VL_IO;
196     return 0;
197 }
198
199
200 int extent_mod = 0;
201
202 /* This routine reads in the extent blocks for multi-homed servers.
203  * There used to be an initialization bug that would cause the contaddrs
204  * pointers in the first extent block to be bad. Here we will check the
205  * pointers and zero them in the in-memory copy if we find them bad. We
206  * also try to write the extent blocks back out. If we can't, then we
207  * will wait until the next write transaction to write them out
208  * (extent_mod tells us the on-disk copy is bad).
209  */
210 afs_int32
211 readExtents(struct ubik_trans *trans)
212 {
213     afs_uint32 extentAddr;
214     afs_int32 error = 0, code;
215     int i;
216
217     extent_mod = 0;
218     extentAddr = ntohl(cheader.SIT);
219     if (!extentAddr)
220         return 0;
221
222     /* Read the first extension block */
223     if (!ex_addr[0]) {
224         ex_addr[0] = (struct extentaddr *)malloc(VL_ADDREXTBLK_SIZE);
225         if (!ex_addr[0])
226             ERROR_EXIT(VL_NOMEM);
227     }
228     code = vlread(trans, extentAddr, (char *)ex_addr[0], VL_ADDREXTBLK_SIZE);
229     if (code) {
230         free(ex_addr[0]);       /* Not the place to create it */
231         ex_addr[0] = 0;
232         ERROR_EXIT(VL_IO);
233     }
234
235     /* In case more that 64 mh servers are in use they're kept in these
236      * continuation blocks
237      */
238     for (i = 1; i < VL_MAX_ADDREXTBLKS; i++) {
239         if (!ex_addr[0]->ex_contaddrs[i])
240             continue;
241
242         /* Before reading it in, check to see if the address is good */
243         if ((ntohl(ex_addr[0]->ex_contaddrs[i]) <
244              ntohl(ex_addr[0]->ex_contaddrs[i - 1]) + VL_ADDREXTBLK_SIZE)
245             || (ntohl(ex_addr[0]->ex_contaddrs[i]) >
246                 ntohl(cheader.vital_header.eofPtr) - VL_ADDREXTBLK_SIZE)) {
247             extent_mod = 1;
248             ex_addr[0]->ex_contaddrs[i] = 0;
249             continue;
250         }
251
252
253         /* Read the continuation block */
254         if (!ex_addr[i]) {
255             ex_addr[i] = (struct extentaddr *)malloc(VL_ADDREXTBLK_SIZE);
256             if (!ex_addr[i])
257                 ERROR_EXIT(VL_NOMEM);
258         }
259         code =
260             vlread(trans, ntohl(ex_addr[0]->ex_contaddrs[i]),
261                    (char *)ex_addr[i], VL_ADDREXTBLK_SIZE);
262         if (code) {
263             free(ex_addr[i]);   /* Not the place to create it */
264             ex_addr[i] = 0;
265             ERROR_EXIT(VL_IO);
266         }
267
268         /* After reading it in, check to see if its a real continuation block */
269         if (ntohl(ex_addr[i]->ex_flags) != VLCONTBLOCK) {
270             extent_mod = 1;
271             ex_addr[0]->ex_contaddrs[i] = 0;
272             free(ex_addr[i]);   /* Not the place to create it */
273             ex_addr[i] = 0;
274             continue;
275         }
276     }
277
278     if (extent_mod) {
279         code = vlwrite(trans, extentAddr, ex_addr[0], VL_ADDREXTBLK_SIZE);
280         if (!code) {
281             VLog(0, ("Multihome server support modification\n"));
282         }
283         /* Keep extent_mod true in-case the transaction aborts */
284         /* Don't return error so we don't abort transaction */
285     }
286
287   error_exit:
288     return error;
289 }
290
291 /* Check that the database has been initialized.  Be careful to fail in a safe
292    manner, to avoid bogusly reinitializing the db.  */
293 afs_int32
294 CheckInit(struct ubik_trans *trans, int builddb)
295 {
296     afs_int32 error = 0, i, code, ubcode = 0;
297
298     /* ubik_CacheUpdate must be called on every transaction.  It returns 0 if the
299      * previous transaction would have left the cache fine, and non-zero otherwise.
300      * Thus, a local abort or a remote commit will cause this to return non-zero
301      * and force a header re-read.  Necessary for a local abort because we may
302      * have damaged cheader during the operation.  Necessary for a remote commit
303      * since it may have changed cheader. 
304      */
305     if (ubik_CacheUpdate(trans) != 0) {
306         /* if version changed (or first call), read the header */
307         ubcode = vlread(trans, 0, (char *)&cheader, sizeof(cheader));
308         vldbversion = ntohl(cheader.vital_header.vldbversion);
309
310         if (!ubcode && (vldbversion != 0)) {
311             memcpy(HostAddress, cheader.IpMappedAddr,
312                    sizeof(cheader.IpMappedAddr));
313             for (i = 0; i < MAXSERVERID + 1; i++) {     /* cvt HostAddress to host order */
314                 HostAddress[i] = ntohl(HostAddress[i]);
315             }
316
317             code = readExtents(trans);
318             if (code)
319                 ERROR_EXIT(code);
320         }
321     }
322
323     vldbversion = ntohl(cheader.vital_header.vldbversion);
324
325     /* now, if can't read, or header is wrong, write a new header */
326     if (ubcode || vldbversion == 0) {
327         if (builddb) {
328             printf("Can't read VLDB header, re-initialising...\n");
329
330             /* try to write a good header */
331             memset(&cheader, 0, sizeof(cheader));
332             cheader.vital_header.vldbversion = htonl(VLDBVERSION);
333             cheader.vital_header.headersize = htonl(sizeof(cheader));
334             /* DANGER: Must get this from a master place!! */
335             cheader.vital_header.MaxVolumeId = htonl(0x20000000);
336             cheader.vital_header.eofPtr = htonl(sizeof(cheader));
337             for (i = 0; i < MAXSERVERID + 1; i++) {
338                 cheader.IpMappedAddr[i] = 0;
339                 HostAddress[i] = 0;
340             }
341             code = vlwrite(trans, 0, (char *)&cheader, sizeof(cheader));
342             if (code) {
343                 printf("Can't write VLDB header (error = %d)\n", code);
344                 ERROR_EXIT(VL_IO);
345             }
346         } else
347             ERROR_EXIT(VL_EMPTY);
348     } else if ((vldbversion != VLDBVERSION) && (vldbversion != OVLDBVERSION)
349                && (vldbversion != VLDBVERSION_4)) {
350         printf
351             ("VLDB version %d doesn't match this software version(%d, %d or %d), quitting!\n",
352              vldbversion, VLDBVERSION_4, VLDBVERSION, OVLDBVERSION);
353         ERROR_EXIT(VL_BADVERSION);
354     }
355
356     maxnservers = ((vldbversion == 3 || vldbversion == 4) ? 13 : 8);
357
358   error_exit:
359     /* all done */
360     return error;
361 }
362
363
364 afs_int32
365 GetExtentBlock(register struct ubik_trans *trans, register afs_int32 base)
366 {
367     afs_int32 blockindex, code, error = 0;
368
369     /* Base 0 must exist before any other can be created */
370     if ((base != 0) && !ex_addr[0])
371         ERROR_EXIT(VL_CREATEFAIL);      /* internal error */
372
373     if (!ex_addr[0] || !ex_addr[0]->ex_contaddrs[base]) {
374         /* Create a new extension block */
375         if (!ex_addr[base]) {
376             ex_addr[base] = (struct extentaddr *)malloc(VL_ADDREXTBLK_SIZE);
377             if (!ex_addr[base])
378                 ERROR_EXIT(VL_NOMEM);
379         }
380         memset(ex_addr[base], 0, VL_ADDREXTBLK_SIZE);
381
382         /* Write the full extension block at end of vldb */
383         ex_addr[base]->ex_flags = htonl(VLCONTBLOCK);
384         blockindex = ntohl(cheader.vital_header.eofPtr);
385         code =
386             vlwrite(trans, blockindex, (char *)ex_addr[base],
387                     VL_ADDREXTBLK_SIZE);
388         if (code)
389             ERROR_EXIT(VL_IO);
390
391         /* Update the cheader.vitalheader structure on disk */
392         cheader.vital_header.eofPtr = blockindex + VL_ADDREXTBLK_SIZE;
393         cheader.vital_header.eofPtr = htonl(cheader.vital_header.eofPtr);
394         code = write_vital_vlheader(trans);
395         if (code)
396             ERROR_EXIT(VL_IO);
397
398         /* Write the address of the base extension block in the vldb header */
399         if (base == 0) {
400             cheader.SIT = htonl(blockindex);
401             code =
402                 vlwrite(trans, DOFFSET(0, &cheader, &cheader.SIT),
403                         (char *)&cheader.SIT, sizeof(cheader.SIT));
404             if (code)
405                 ERROR_EXIT(VL_IO);
406         }
407
408         /* Write the address of this extension block into the base extension block */
409         ex_addr[0]->ex_contaddrs[base] = htonl(blockindex);
410         code =
411             vlwrite(trans, ntohl(cheader.SIT), ex_addr[0],
412                     sizeof(struct extentaddr));
413         if (code)
414             ERROR_EXIT(VL_IO);
415     }
416
417   error_exit:
418     return error;
419 }
420
421
422 afs_int32
423 FindExtentBlock(register struct ubik_trans *trans, afsUUID *uuidp,
424                 afs_int32 createit, afs_int32 hostslot,
425                 struct extentaddr **expp, afs_int32 *basep)
426 {
427     afsUUID tuuid;
428     struct extentaddr *exp;
429     register afs_int32 i, j, code, base, index, error = 0;
430
431     *expp = NULL;
432     *basep = 0;
433
434     /* Create the first extension block if it does not exist */
435     if (!cheader.SIT) {
436         code = GetExtentBlock(trans, 0);
437         if (code)
438             ERROR_EXIT(code);
439     }
440
441     for (i = 0; i < MAXSERVERID + 1; i++) {
442         if ((HostAddress[i] & 0xff000000) == 0xff000000) {
443             if ((base = (HostAddress[i] >> 16) & 0xff) > VL_MAX_ADDREXTBLKS) {
444                 ERROR_EXIT(VL_INDEXERANGE);
445             }
446             if ((index = HostAddress[i] & 0x0000ffff) > VL_MHSRV_PERBLK) {
447                 ERROR_EXIT(VL_INDEXERANGE);
448             }
449             exp = &ex_addr[base][index];
450             tuuid = exp->ex_hostuuid;
451             afs_ntohuuid(&tuuid);
452             if (afs_uuid_equal(uuidp, &tuuid)) {
453                 *expp = exp;
454                 *basep = base;
455                 ERROR_EXIT(0);
456             }
457         }
458     }
459
460     if (createit) {
461         if (hostslot == -1) {
462             for (i = 0; i < MAXSERVERID + 1; i++) {
463                 if (!HostAddress[i])
464                     break;
465             }
466             if (i > MAXSERVERID)
467                 ERROR_EXIT(VL_REPSFULL);
468         } else {
469             i = hostslot;
470         }
471
472         for (base = 0; base < VL_MAX_ADDREXTBLKS; base++) {
473             if (!ex_addr[0]->ex_contaddrs[base]) {
474                 code = GetExtentBlock(trans, base);
475                 if (code)
476                     ERROR_EXIT(code);
477             }
478             for (j = 1; j < VL_MHSRV_PERBLK; j++) {
479                 exp = &ex_addr[base][j];
480                 tuuid = exp->ex_hostuuid;
481                 afs_ntohuuid(&tuuid);
482                 if (afs_uuid_is_nil(&tuuid)) {
483                     tuuid = *uuidp;
484                     afs_htonuuid(&tuuid);
485                     exp->ex_hostuuid = tuuid;
486                     code =
487                         vlwrite(trans,
488                                 DOFFSET(ntohl(ex_addr[0]->ex_contaddrs[base]),
489                                         (char *)ex_addr[base], (char *)exp),
490                                 (char *)&tuuid, sizeof(tuuid));
491                     if (code)
492                         ERROR_EXIT(VL_IO);
493                     HostAddress[i] =
494                         0xff000000 | ((base << 16) & 0xff0000) | (j & 0xffff);
495                     *expp = exp;
496                     *basep = base;
497                     if (vldbversion != VLDBVERSION_4) {
498                         cheader.vital_header.vldbversion =
499                             htonl(VLDBVERSION_4);
500                         code = write_vital_vlheader(trans);
501                         if (code)
502                             ERROR_EXIT(VL_IO);
503                     }
504                     cheader.IpMappedAddr[i] = htonl(HostAddress[i]);
505                     code =
506                         vlwrite(trans,
507                                 DOFFSET(0, &cheader,
508                                         &cheader.IpMappedAddr[i]),
509                                 (char *)&cheader.IpMappedAddr[i],
510                                 sizeof(afs_int32));
511                     if (code)
512                         ERROR_EXIT(VL_IO);
513                     ERROR_EXIT(0);
514                 }
515             }
516         }
517         ERROR_EXIT(VL_REPSFULL);        /* No reason to utilize a new error code */
518     }
519
520   error_exit:
521     return error;
522 }
523
524 /* Allocate a free block of storage for entry, returning address of a new
525    zeroed entry (or zero if something is wrong).  */
526 afs_int32
527 AllocBlock(register struct ubik_trans *trans, struct nvlentry *tentry)
528 {
529     register afs_int32 blockindex;
530
531     if (cheader.vital_header.freePtr) {
532         /* allocate this dude */
533         blockindex = ntohl(cheader.vital_header.freePtr);
534         if (vlentryread(trans, blockindex, (char *)tentry, sizeof(vlentry)))
535             return 0;
536         cheader.vital_header.freePtr = htonl(tentry->nextIdHash[0]);
537     } else {
538         /* hosed, nothing on free list, grow file */
539         blockindex = ntohl(cheader.vital_header.eofPtr);        /* remember this guy */
540         cheader.vital_header.eofPtr = htonl(blockindex + sizeof(vlentry));
541     }
542     cheader.vital_header.allocs++;
543     if (write_vital_vlheader(trans))
544         return 0;
545     memset(tentry, 0, sizeof(nvlentry));        /* zero new entry */
546     return blockindex;
547 }
548
549
550 /* Free a block given its index.  It must already have been unthreaded. Returns zero for success or an error code on failure. */
551 int
552 FreeBlock(struct ubik_trans *trans, afs_int32 blockindex)
553 {
554     struct nvlentry tentry;
555
556     /* check validity of blockindex just to be on the safe side */
557     if (!index_OK(trans, blockindex))
558         return VL_BADINDEX;
559     memset(&tentry, 0, sizeof(nvlentry));
560     tentry.nextIdHash[0] = cheader.vital_header.freePtr;        /* already in network order */
561     tentry.flags = htonl(VLFREE);
562     cheader.vital_header.freePtr = htonl(blockindex);
563     if (vlwrite(trans, blockindex, (char *)&tentry, sizeof(nvlentry)))
564         return VL_IO;
565     cheader.vital_header.frees++;
566     if (write_vital_vlheader(trans))
567         return VL_IO;
568     return 0;
569 }
570
571
572 /* Look for a block by volid and voltype (if not known use -1 which searches
573  * all 3 volid hash lists. Note that the linked lists are read in first from
574  * the database header.  If found read the block's contents into the area
575  * pointed to by tentry and return the block's index.  If not found return 0.
576  */
577 afs_int32
578 FindByID(struct ubik_trans *trans, afs_uint32 volid, afs_int32 voltype,
579          struct nvlentry *tentry, afs_int32 *error)
580 {
581     register afs_int32 typeindex, hashindex, blockindex;
582
583     *error = 0;
584     hashindex = IDHash(volid);
585     if (voltype == -1) {
586 /* Should we have one big hash table for volids as opposed to the three ones? */
587         for (typeindex = 0; typeindex < MAXTYPES; typeindex++) {
588             for (blockindex = ntohl(cheader.VolidHash[typeindex][hashindex]);
589                  blockindex != NULLO;
590                  blockindex = tentry->nextIdHash[typeindex]) {
591                 if (vlentryread
592                     (trans, blockindex, (char *)tentry, sizeof(nvlentry))) {
593                     *error = VL_IO;
594                     return 0;
595                 }
596                 if (volid == tentry->volumeId[typeindex])
597                     return blockindex;
598             }
599         }
600     } else {
601         for (blockindex = ntohl(cheader.VolidHash[voltype][hashindex]);
602              blockindex != NULLO; blockindex = tentry->nextIdHash[voltype]) {
603             if (vlentryread
604                 (trans, blockindex, (char *)tentry, sizeof(nvlentry))) {
605                 *error = VL_IO;
606                 return 0;
607             }
608             if (volid == tentry->volumeId[voltype])
609                 return blockindex;
610         }
611     }
612     return 0;                   /* no such entry */
613 }
614
615
616 /* Look for a block by volume name. If found read the block's contents into
617  * the area pointed to by tentry and return the block's index.  If not
618  * found return 0.
619  */
620 afs_int32
621 FindByName(struct ubik_trans *trans, char *volname, struct nvlentry *tentry,
622            afs_int32 *error)
623 {
624     register afs_int32 hashindex;
625     register afs_int32 blockindex;
626     char tname[VL_MAXNAMELEN];
627
628     /* remove .backup or .readonly extensions for stupid backwards
629      * compatibility
630      */
631     hashindex = strlen(volname);        /* really string length */
632     if (hashindex >= 8 && strcmp(volname + hashindex - 7, ".backup") == 0) {
633         /* this is a backup volume */
634         strcpy(tname, volname);
635         tname[hashindex - 7] = 0;       /* zap extension */
636     } else if (hashindex >= 10
637                && strcmp(volname + hashindex - 9, ".readonly") == 0) {
638         /* this is a readonly volume */
639         strcpy(tname, volname);
640         tname[hashindex - 9] = 0;       /* zap extension */
641     } else
642         strcpy(tname, volname);
643
644     *error = 0;
645     hashindex = NameHash(tname);
646     for (blockindex = ntohl(cheader.VolnameHash[hashindex]);
647          blockindex != NULLO; blockindex = tentry->nextNameHash) {
648         if (vlentryread(trans, blockindex, (char *)tentry, sizeof(nvlentry))) {
649             *error = VL_IO;
650             return 0;
651         }
652         if (!strcmp(tname, tentry->name))
653             return blockindex;
654     }
655     return 0;                   /* no such entry */
656 }
657
658 /**
659  * Returns whether or not any of the supplied volume IDs already exist
660  * in the vldb.
661  *
662  * @param trans    the ubik transaction
663  * @param ids      an array of volume IDs
664  * @param ids_len  the number of elements in the 'ids' array
665  * @param error    filled in with an error code in case of error
666  *
667  * @return whether any of the volume IDs are already used
668  *  @retval 1  at least one of the volume IDs is already used
669  *  @retval 0  none of the volume IDs are used, or an error occurred
670  */
671 int
672 EntryIDExists(struct ubik_trans *trans, const afs_uint32 *ids,
673               afs_int32 ids_len, afs_int32 *error)
674 {
675     afs_int32 typeindex;
676     struct nvlentry tentry;
677
678     *error = 0;
679
680     for (typeindex = 0; typeindex < ids_len; typeindex++) {
681         if (ids[typeindex]
682             && FindByID(trans, ids[typeindex], -1, &tentry, error)) {
683
684             return 1;
685         } else if (*error) {
686             return 0;
687         }
688     }
689
690     return 0;
691 }
692
693 /**
694  * Finds the next range of unused volume IDs in the vldb.
695  *
696  * @param trans     the ubik transaction
697  * @param maxvolid  the current max vol ID, and where to start looking
698  *                  for an unused volume ID range
699  * @param bump      how many volume IDs we need to be unused
700  * @param error     filled in with an error code in case of error
701  *
702  * @return the next volume ID 'volid' such that the range
703  *         [volid, volid+bump) of volume IDs is unused, or 0 if there's
704  *         an error
705  */
706 afs_uint32
707 NextUnusedID(struct ubik_trans *trans, afs_uint32 maxvolid, afs_uint32 bump,
708              afs_int32 *error)
709 {
710     struct nvlentry tentry;
711     afs_uint32 id;
712     afs_uint32 nfree;
713
714     *error = 0;
715
716      /* we simply start at the given maxvolid, keep a running tally of
717       * how many free volume IDs we've seen in a row, and return when
718       * we've seen 'bump' unused IDs in a row */
719     for (id = maxvolid, nfree = 0; nfree < bump; ++id) {
720         if (FindByID(trans, id, -1, &tentry, error)) {
721             nfree = 0;
722         } else if (*error) {
723             return 0;
724         } else {
725             ++nfree;
726         }
727     }
728
729     /* 'id' is now at the end of the [maxvolid,maxvolid+bump) range,
730      * but we need to return the first unused id, so subtract the
731      * number of current running free IDs to get the beginning */
732     return id - nfree;
733 }
734
735 int
736 HashNDump(struct ubik_trans *trans, int hashindex)
737 {
738     register int i = 0;
739     register int blockindex;
740     struct nvlentry tentry;
741
742     for (blockindex = ntohl(cheader.VolnameHash[hashindex]);
743          blockindex != NULLO; blockindex = tentry.nextNameHash) {
744         if (vlentryread(trans, blockindex, (char *)&tentry, sizeof(nvlentry)))
745             return 0;
746         i++;
747         VLog(0,
748              ("[%d]#%d: %10d %d %d (%s)\n", hashindex, i, tentry.volumeId[0],
749               tentry.nextIdHash[0], tentry.nextNameHash, tentry.name));
750     }
751     return 0;
752 }
753
754
755 int
756 HashIdDump(struct ubik_trans *trans, int hashindex)
757 {
758     register int i = 0;
759     register int blockindex;
760     struct nvlentry tentry;
761
762     for (blockindex = ntohl(cheader.VolidHash[0][hashindex]);
763          blockindex != NULLO; blockindex = tentry.nextIdHash[0]) {
764         if (vlentryread(trans, blockindex, (char *)&tentry, sizeof(nvlentry)))
765             return 0;
766         i++;
767         VLog(0,
768              ("[%d]#%d: %10d %d %d (%s)\n", hashindex, i, tentry.volumeId[0],
769               tentry.nextIdHash[0], tentry.nextNameHash, tentry.name));
770     }
771     return 0;
772 }
773
774
775 /* Add a block to the hash table given a pointer to the block and its index.
776  * The block is threaded onto both hash tables and written to disk.  The
777  * routine returns zero if there were no errors.
778  */
779 int
780 ThreadVLentry(struct ubik_trans *trans, afs_int32 blockindex,
781               struct nvlentry *tentry)
782 {
783     int errorcode;
784
785     if (!index_OK(trans, blockindex))
786         return VL_BADINDEX;
787     /* Insert into volid's hash linked list */
788     if ((errorcode = HashVolid(trans, RWVOL, blockindex, tentry)))
789         return errorcode;
790
791     /* For rw entries we also enter the RO and BACK volume ids (if they
792      * exist) in the hash tables; note all there volids (RW, RO, BACK)
793      * should not be hashed yet! */
794     if (tentry->volumeId[ROVOL]) {
795         if ((errorcode = HashVolid(trans, ROVOL, blockindex, tentry)))
796             return errorcode;
797     }
798     if (tentry->volumeId[BACKVOL]) {
799         if ((errorcode = HashVolid(trans, BACKVOL, blockindex, tentry)))
800             return errorcode;
801     }
802
803     /* Insert into volname's hash linked list */
804     HashVolname(trans, blockindex, tentry);
805
806     /* Update cheader entry */
807     if (write_vital_vlheader(trans))
808         return VL_IO;
809
810     /* Update hash list pointers in the entry itself */
811     if (vlentrywrite(trans, blockindex, (char *)tentry, sizeof(nvlentry)))
812         return VL_IO;
813     return 0;
814 }
815
816
817 /* Remove a block from both the hash tables.  If success return 0, else
818  * return an error code. */
819 int
820 UnthreadVLentry(struct ubik_trans *trans, afs_int32 blockindex,
821                 struct nvlentry *aentry)
822 {
823     register afs_int32 errorcode, typeindex;
824
825     if (!index_OK(trans, blockindex))
826         return VL_BADINDEX;
827     if ((errorcode = UnhashVolid(trans, RWVOL, blockindex, aentry)))
828         return errorcode;
829
830     /* Take the RO/RW entries of their respective hash linked lists. */
831     for (typeindex = ROVOL; typeindex <= BACKVOL; typeindex++) {
832         if ((errorcode = UnhashVolid(trans, typeindex, blockindex, aentry)))
833             return errorcode;
834     }
835
836     /* Take it out of the Volname hash list */
837     if ((errorcode = UnhashVolname(trans, blockindex, aentry)))
838         return errorcode;
839
840     /* Update cheader entry */
841     write_vital_vlheader(trans);
842
843     return 0;
844 }
845
846 /* cheader must have be read before this routine is called. */
847 int
848 HashVolid(struct ubik_trans *trans, afs_int32 voltype, afs_int32 blockindex,
849           struct nvlentry *tentry)
850 {
851     afs_int32 hashindex, errorcode;
852     struct nvlentry ventry;
853
854     if (FindByID
855         (trans, tentry->volumeId[voltype], voltype, &ventry, &errorcode))
856         return VL_IDALREADYHASHED;
857     else if (errorcode)
858         return errorcode;
859     hashindex = IDHash(tentry->volumeId[voltype]);
860     tentry->nextIdHash[voltype] =
861         ntohl(cheader.VolidHash[voltype][hashindex]);
862     cheader.VolidHash[voltype][hashindex] = htonl(blockindex);
863     if (vlwrite
864         (trans, DOFFSET(0, &cheader, &cheader.VolidHash[voltype][hashindex]),
865          (char *)&cheader.VolidHash[voltype][hashindex], sizeof(afs_int32)))
866         return VL_IO;
867     return 0;
868 }
869
870
871 /* cheader must have be read before this routine is called. */
872 int
873 UnhashVolid(struct ubik_trans *trans, afs_int32 voltype, afs_int32 blockindex,
874             struct nvlentry *aentry)
875 {
876     int hashindex, nextblockindex, prevblockindex;
877     struct nvlentry tentry;
878     afs_int32 code;
879     afs_int32 temp;
880
881     if (aentry->volumeId[voltype] == NULLO)     /* Assume no volume id */
882         return 0;
883     /* Take it out of the VolId[voltype] hash list */
884     hashindex = IDHash(aentry->volumeId[voltype]);
885     nextblockindex = ntohl(cheader.VolidHash[voltype][hashindex]);
886     if (nextblockindex == blockindex) {
887         /* First on the hash list; just adjust pointers */
888         cheader.VolidHash[voltype][hashindex] =
889             htonl(aentry->nextIdHash[voltype]);
890         code =
891             vlwrite(trans,
892                     DOFFSET(0, &cheader,
893                             &cheader.VolidHash[voltype][hashindex]),
894                     (char *)&cheader.VolidHash[voltype][hashindex],
895                     sizeof(afs_int32));
896         if (code)
897             return VL_IO;
898     } else {
899         while (nextblockindex != blockindex) {
900             prevblockindex = nextblockindex;    /* always done once */
901             if (vlentryread
902                 (trans, nextblockindex, (char *)&tentry, sizeof(nvlentry)))
903                 return VL_IO;
904             if ((nextblockindex = tentry.nextIdHash[voltype]) == NULLO)
905                 return VL_NOENT;
906         }
907         temp = tentry.nextIdHash[voltype] = aentry->nextIdHash[voltype];
908         temp = htonl(temp);     /* convert to network byte order before writing */
909         if (vlwrite
910             (trans,
911              DOFFSET(prevblockindex, &tentry, &tentry.nextIdHash[voltype]),
912              (char *)&temp, sizeof(afs_int32)))
913             return VL_IO;
914     }
915     aentry->nextIdHash[voltype] = 0;
916     return 0;
917 }
918
919
920 int
921 HashVolname(struct ubik_trans *trans, afs_int32 blockindex,
922             struct nvlentry *aentry)
923 {
924     register afs_int32 hashindex;
925     register afs_int32 code;
926
927     /* Insert into volname's hash linked list */
928     hashindex = NameHash(aentry->name);
929     aentry->nextNameHash = ntohl(cheader.VolnameHash[hashindex]);
930     cheader.VolnameHash[hashindex] = htonl(blockindex);
931     code =
932         vlwrite(trans, DOFFSET(0, &cheader, &cheader.VolnameHash[hashindex]),
933                 (char *)&cheader.VolnameHash[hashindex], sizeof(afs_int32));
934     if (code)
935         return VL_IO;
936     return 0;
937 }
938
939
940 int
941 UnhashVolname(struct ubik_trans *trans, afs_int32 blockindex,
942               struct nvlentry *aentry)
943 {
944     register afs_int32 hashindex, nextblockindex, prevblockindex;
945     struct nvlentry tentry;
946     afs_int32 temp;
947
948     /* Take it out of the Volname hash list */
949     hashindex = NameHash(aentry->name);
950     nextblockindex = ntohl(cheader.VolnameHash[hashindex]);
951     if (nextblockindex == blockindex) {
952         /* First on the hash list; just adjust pointers */
953         cheader.VolnameHash[hashindex] = htonl(aentry->nextNameHash);
954         if (vlwrite
955             (trans, DOFFSET(0, &cheader, &cheader.VolnameHash[hashindex]),
956              (char *)&cheader.VolnameHash[hashindex], sizeof(afs_int32)))
957             return VL_IO;
958     } else {
959         while (nextblockindex != blockindex) {
960             prevblockindex = nextblockindex;    /* always done at least once */
961             if (vlentryread
962                 (trans, nextblockindex, (char *)&tentry, sizeof(nvlentry)))
963                 return VL_IO;
964             if ((nextblockindex = tentry.nextNameHash) == NULLO)
965                 return VL_NOENT;
966         }
967         tentry.nextNameHash = aentry->nextNameHash;
968         temp = htonl(tentry.nextNameHash);
969         if (vlwrite
970             (trans, DOFFSET(prevblockindex, &tentry, &tentry.nextNameHash),
971              (char *)&temp, sizeof(afs_int32)))
972             return VL_IO;
973     }
974     aentry->nextNameHash = 0;
975     return 0;
976 }
977
978
979 /* Returns the vldb entry tentry at offset index; remaining is the number of
980  * entries left; the routine also returns the index of the next sequential
981  * entry in the vldb
982  */
983
984 afs_int32
985 NextEntry(struct ubik_trans *trans, afs_int32 blockindex,
986           struct nvlentry *tentry, afs_int32 *remaining)
987 {
988     register afs_int32 lastblockindex;
989
990     if (blockindex == 0)        /* get first one */
991         blockindex = sizeof(cheader);
992     else {
993         if (!index_OK(trans, blockindex)) {
994             *remaining = -1;    /* error */
995             return 0;
996         }
997         blockindex += sizeof(nvlentry);
998     }
999     /* now search for the first entry that isn't free */
1000     for (lastblockindex = ntohl(cheader.vital_header.eofPtr);
1001          blockindex < lastblockindex;) {
1002         if (vlentryread(trans, blockindex, (char *)tentry, sizeof(nvlentry))) {
1003             *remaining = -1;
1004             return 0;
1005         }
1006         if (tentry->flags == VLCONTBLOCK) {
1007             /*
1008              * This is a special mh extension block just simply skip over it
1009              */
1010             blockindex += VL_ADDREXTBLK_SIZE;
1011         } else {
1012             if (tentry->flags != VLFREE) {
1013                 /* estimate remaining number of entries, not including this one */
1014                 *remaining =
1015                     (lastblockindex - blockindex) / sizeof(nvlentry) - 1;
1016                 return blockindex;
1017             }
1018             blockindex += sizeof(nvlentry);
1019         }
1020     }
1021     *remaining = 0;             /* no more entries */
1022     return 0;
1023 }
1024
1025
1026 /* Routine to verify that index is a legal offset to a vldb entry in the
1027  * table
1028  */
1029 static int
1030 index_OK(struct ubik_trans *trans, afs_int32 blockindex)
1031 {
1032     if ((blockindex < sizeof(cheader))
1033         || (blockindex >= ntohl(cheader.vital_header.eofPtr)))
1034         return 0;
1035     return 1;
1036 }