snowleopard 64 bit warning death
[openafs.git] / src / volser / vsprocs.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 #ifdef IGNORE_SOME_GCC_WARNINGS
14 # pragma GCC diagnostic warning "-Wformat-extra-args"
15 #endif
16
17 #include <stdio.h>
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 #include <string.h>
21 #ifdef  AFS_AIX_ENV
22 #include <sys/statfs.h>
23 #endif
24 #ifdef AFS_NT40_ENV
25 #include <fcntl.h>
26 #include <winsock2.h>
27 #else
28 #include <sys/file.h>
29 #include <netinet/in.h>
30 #endif
31
32 #include <lock.h>
33 #include <afs/voldefs.h>
34 #include <rx/xdr.h>
35 #include <rx/rx.h>
36 #include <afs/vlserver.h>
37 #include <afs/nfs.h>
38 #include <afs/cellconfig.h>
39 #include <afs/keys.h>
40 #include <ubik.h>
41 #include <afs/afsint.h>
42 #include "volser.h"
43 #include "volint.h"
44 #include "lockdata.h"
45 #include <afs/com_err.h>
46 #include <rx/rxkad.h>
47 #include <afs/kautils.h>
48 #include <afs/cmd.h>
49 #include <afs/ihandle.h>
50 #ifdef AFS_NT40_ENV
51 #include <afs/ntops.h>
52 #endif
53 #include <afs/vnode.h>
54 #include <afs/volume.h>
55 #include <errno.h>
56 #define ERRCODE_RANGE 8         /* from error_table.h */
57 #define CLOCKSKEW   2           /* not really skew, but resolution */
58 #define CLOCKADJ(x) (((x) < CLOCKSKEW) ? 0 : (x) - CLOCKSKEW)
59
60 /* for UV_MoveVolume() recovery */
61
62 #include <afs/procmgmt.h>       /* signal(), kill(), wait(), etc. */
63 #include <setjmp.h>
64
65 #include "volser_internal.h"
66 #include "volser_prototypes.h"
67 #include "vsutils_prototypes.h"
68 #include "lockprocs_prototypes.h"
69
70 struct ubik_client *cstruct;
71 int verbose = 0, noresolve = 0;
72
73 struct release {
74     afs_uint32 crtime;
75     afs_uint32 uptime;
76     afs_int32 vldbEntryIndex;
77 };
78
79 /* Utility macros used by rest of this source file */
80 #define EPRINT(ec, es) \
81 do { \
82         fprintf(STDERR, "\n"); \
83         fprintf(STDERR, (es)); \
84         PrintError("   ",ec); \
85 } while (0)
86
87 #define EPRINT1(ec, es, ep1) \
88 do { \
89         fprintf(STDERR, "\n"); \
90         fprintf(STDERR, (es), (ep1)); \
91         PrintError("   ",ec); \
92 } while (0)
93
94 #define EPRINT2(ec, es, ep1, ep2) \
95 do { \
96         fprintf(STDERR, "\n"); \
97         fprintf(STDERR, (es), (ep1), (ep2)); \
98         PrintError("   ",ec); \
99 } while (0)
100
101 #define EPRINT3(ec, es, ep1, ep2, ep3) \
102 do { \
103         fprintf(STDERR, "\n"); \
104         fprintf(STDERR, (es), (ep1), (ep2), (ep3)); \
105         PrintError("   ",ec); \
106 } while (0)
107
108 #define EGOTO(where, ec, es) \
109 do { \
110         if (ec) { \
111                 EPRINT((ec),(es)); \
112                 error = (ec); \
113                 goto where; \
114         } \
115 } while (0)
116
117 #define EGOTO1(where, ec, es, ep1) \
118 do { \
119         if (ec) { \
120                 EPRINT1((ec),(es),(ep1)); \
121                 error = (ec); \
122                 goto where; \
123         } \
124 } while (0)
125
126 #define EGOTO2(where, ec, es, ep1, ep2) \
127 do { \
128         if (ec) { \
129                 EPRINT2((ec),(es),(ep1),(ep2)); \
130                 error = (ec); \
131                 goto where; \
132         } \
133 } while (0)
134
135 #define EGOTO3(where, ec, es, ep1, ep2, ep3) \
136 do { \
137         if (ec) { \
138                 EPRINT3((ec),(es),(ep1),(ep2),(ep3)); \
139                 error = (ec); \
140                 goto where; \
141         } \
142 } while (0)
143
144 #define VPRINT(es) \
145         { if (verbose) { fprintf(STDOUT, (es)); fflush(STDOUT); } }
146 #define VPRINT1(es, p) \
147         { if (verbose) { fprintf(STDOUT, (es), (p)); fflush(STDOUT); } }
148 #define VPRINT2(es, p1, p2) \
149         { if (verbose) { fprintf(STDOUT, (es), (p1), (p2)); fflush(STDOUT); } }
150 #define VPRINT3(es, p1, p2, p3) \
151         { if (verbose) { fprintf(STDOUT, (es), (p1), (p2), (p3)); fflush(STDOUT); } }
152 #define VDONE \
153         { if (verbose) { fprintf(STDOUT, " done\n"); fflush(STDOUT); } }
154 #define VEPRINT(es) \
155         { if (verbose) { fprintf(STDERR, (es)); fflush(STDERR); } }
156 #define VEPRINT1(es, p) \
157         { if (verbose) { fprintf(STDERR, (es), (p)); fflush(STDERR); } }
158 #define VEPRINT2(es, p1, p2) \
159         { if (verbose) { fprintf(STDERR, (es), (p1), (p2)); fflush(STDERR); } }
160 #define VEPRINT3(es, p1, p2, p3) \
161         { if (verbose) { fprintf(STDERR, (es), (p1), (p2), (p3)); fflush(STDERR); } }
162 #define VEDONE \
163         { if (verbose) { fprintf(STDERR, " done\n"); fflush(STDERR); } }
164
165
166
167 /* getting rid of this */
168 #define ERROR_EXIT(code) {error=(code); goto error_exit;}
169
170
171 /* Protos for static routines */
172 #if 0
173 static afs_int32 CheckAndDeleteVolume(struct rx_connection *aconn,
174                                       afs_int32 apart, afs_uint32 okvol,
175                                       afs_uint32 delvol);
176 #endif
177 static int DelVol(struct rx_connection *conn, afs_uint32 vid, afs_int32 part,
178                   afs_int32 flags);
179 static int GetTrans(struct nvldbentry *vldbEntryPtr, afs_int32 index,
180                     struct rx_connection **connPtr, afs_int32 * transPtr,
181                     afs_uint32 * crtimePtr, afs_uint32 * uptimePtr);
182 static int SimulateForwardMultiple(struct rx_connection *fromconn,
183                                    afs_int32 fromtid, afs_int32 fromdate,
184                                    manyDests * tr, afs_int32 flags,
185                                    void *cookie, manyResults * results);
186 static afs_int32 CheckVolume(volintInfo * volumeinfo, afs_int32 aserver,
187                              afs_int32 apart, afs_int32 * modentry,
188                              afs_uint32 * maxvolid);
189
190
191 /*map the partition <partId> into partition name <partName>*/
192 void
193 MapPartIdIntoName(afs_int32 partId, char *partName)
194 {
195     if (partId < 26) {          /* what if partId > = 26 ? */
196         strcpy(partName, "/vicep");
197         partName[6] = partId + 'a';
198         partName[7] = '\0';
199         return;
200     } else if (partId < VOLMAXPARTS) {
201         strcpy(partName, "/vicep");
202         partId -= 26;
203         partName[6] = 'a' + (partId / 26);
204         partName[7] = 'a' + (partId % 26);
205         partName[8] = '\0';
206         return;
207     }
208 }
209
210 int
211 yesprompt(char *str)
212 {
213     int response, c;
214     int code;
215
216     fprintf(STDERR, "Do you want to %s? [yn](n): ", str);
217     response = c = getchar();
218     while (!(c == EOF || c == '\n'))
219         c = getchar();          /*skip to end of line */
220     code = (response == 'y' || response == 'Y');
221     return code;
222 }
223
224
225 int
226 PrintError(char *msg, afs_int32 errcode)
227 {
228     fprintf(STDERR, "%s", msg);
229     /*replace by a big switch statement */
230     switch (errcode) {
231     case 0:
232         break;
233     case -1:
234         fprintf(STDERR, "Possible communication failure\n");
235         break;
236     case VSALVAGE:
237         fprintf(STDERR, "Volume needs to be salvaged\n");
238         break;
239     case VNOVNODE:
240         fprintf(STDERR, "Bad vnode number quoted\n");
241         break;
242     case VNOVOL:
243         fprintf(STDERR,
244                 "Volume not attached, does not exist, or not on line\n");
245         break;
246     case VVOLEXISTS:
247         fprintf(STDERR, "Volume already exists\n");
248         break;
249     case VNOSERVICE:
250         fprintf(STDERR, "Volume is not in service\n");
251         break;
252     case VOFFLINE:
253         fprintf(STDERR, "Volume is off line\n");
254         break;
255     case VONLINE:
256         fprintf(STDERR, "Volume is already on line\n");
257         break;
258     case VDISKFULL:
259         fprintf(STDERR, "Partition is full\n");
260         break;
261     case VOVERQUOTA:
262         fprintf(STDERR, "Volume max quota exceeded\n");
263         break;
264     case VBUSY:
265         fprintf(STDERR, "Volume temporarily unavailable\n");
266         break;
267     case VMOVED:
268         fprintf(STDERR, "Volume has moved to another server\n");
269         break;
270     case VL_IDEXIST:
271         fprintf(STDERR, "VLDB: volume Id exists in the vldb\n");
272         break;
273     case VL_IO:
274         fprintf(STDERR, "VLDB: a read terminated too early\n");
275         break;
276     case VL_NAMEEXIST:
277         fprintf(STDERR, "VLDB: volume entry exists in the vldb\n");
278         break;
279     case VL_CREATEFAIL:
280         fprintf(STDERR, "VLDB: internal creation failure\n");
281         break;
282     case VL_NOENT:
283         fprintf(STDERR, "VLDB: no such entry\n");
284         break;
285     case VL_EMPTY:
286         fprintf(STDERR, "VLDB: vldb database is empty\n");
287         break;
288     case VL_ENTDELETED:
289         fprintf(STDERR, "VLDB: entry is deleted (soft delete)\n");
290         break;
291     case VL_BADNAME:
292         fprintf(STDERR, "VLDB: volume name is illegal\n");
293         break;
294     case VL_BADINDEX:
295         fprintf(STDERR, "VLDB: index was out of range\n");
296         break;
297     case VL_BADVOLTYPE:
298         fprintf(STDERR, "VLDB: bad volume type\n");
299         break;
300     case VL_BADSERVER:
301         fprintf(STDERR, "VLDB: illegal server number (not within limits)\n");
302         break;
303     case VL_BADPARTITION:
304         fprintf(STDERR, "VLDB: bad partition number\n");
305         break;
306     case VL_REPSFULL:
307         fprintf(STDERR, "VLDB: run out of space for replication sites\n");
308         break;
309     case VL_NOREPSERVER:
310         fprintf(STDERR, "VLDB: no such repsite server exists\n");
311         break;
312     case VL_DUPREPSERVER:
313         fprintf(STDERR, "VLDB: replication site server already exists\n");
314         break;
315     case VL_RWNOTFOUND:
316         fprintf(STDERR, "VLDB: parent r/w entry not found\n");
317         break;
318     case VL_BADREFCOUNT:
319         fprintf(STDERR, "VLDB: illegal reference count number\n");
320         break;
321     case VL_SIZEEXCEEDED:
322         fprintf(STDERR, "VLDB: vldb size for attributes exceeded\n");
323         break;
324     case VL_BADENTRY:
325         fprintf(STDERR, "VLDB: bad incoming vldb entry\n");
326         break;
327     case VL_BADVOLIDBUMP:
328         fprintf(STDERR, "VLDB: illegal max volid increment\n");
329         break;
330     case VL_IDALREADYHASHED:
331         fprintf(STDERR, "VLDB: (RO/BACK) Id already hashed\n");
332         break;
333     case VL_ENTRYLOCKED:
334         fprintf(STDERR, "VLDB: vldb entry is already locked\n");
335         break;
336     case VL_BADVOLOPER:
337         fprintf(STDERR, "VLDB: bad volume operation code\n");
338         break;
339     case VL_BADRELLOCKTYPE:
340         fprintf(STDERR, "VLDB: bad release lock type\n");
341         break;
342     case VL_RERELEASE:
343         fprintf(STDERR, "VLDB: status report: last release was aborted\n");
344         break;
345     case VL_BADSERVERFLAG:
346         fprintf(STDERR, "VLDB: invalid replication site server flag\n");
347         break;
348     case VL_PERM:
349         fprintf(STDERR, "VLDB: no permission access for call\n");
350         break;
351     case VOLSERREAD_DUMPERROR:
352         fprintf(STDERR,
353                 "VOLSER:  Problems encountered in reading the dump file !\n");
354         break;
355     case VOLSERDUMPERROR:
356         fprintf(STDERR, "VOLSER: Problems encountered in doing the dump !\n");
357         break;
358     case VOLSERATTACH_ERROR:
359         fprintf(STDERR, "VOLSER: Could not attach the volume\n");
360         break;
361     case VOLSERDETACH_ERROR:
362         fprintf(STDERR, "VOLSER: Could not detach the volume\n");
363         break;
364     case VOLSERILLEGAL_PARTITION:
365         fprintf(STDERR, "VOLSER: encountered illegal partition number\n");
366         break;
367     case VOLSERBAD_ACCESS:
368         fprintf(STDERR, "VOLSER: permission denied, not a super user\n");
369         break;
370     case VOLSERVLDB_ERROR:
371         fprintf(STDERR, "VOLSER: error detected in the VLDB\n");
372         break;
373     case VOLSERBADNAME:
374         fprintf(STDERR, "VOLSER: error in volume name\n");
375         break;
376     case VOLSERVOLMOVED:
377         fprintf(STDERR, "VOLSER: volume has moved\n");
378         break;
379     case VOLSERBADOP:
380         fprintf(STDERR, "VOLSER: illegal operation\n");
381         break;
382     case VOLSERBADRELEASE:
383         fprintf(STDERR, "VOLSER: release could not be completed\n");
384         break;
385     case VOLSERVOLBUSY:
386         fprintf(STDERR, "VOLSER: volume is busy\n");
387         break;
388     case VOLSERNO_MEMORY:
389         fprintf(STDERR, "VOLSER: volume server is out of memory\n");
390         break;
391     case VOLSERNOVOL:
392         fprintf(STDERR,
393                 "VOLSER: no such volume - location specified incorrectly or volume does not exist\n");
394         break;
395     case VOLSERMULTIRWVOL:
396         fprintf(STDERR,
397                 "VOLSER: multiple RW volumes with same ID, one of which should be deleted\n");
398         break;
399     case VOLSERFAILEDOP:
400         fprintf(STDERR,
401                 "VOLSER: not all entries were successfully processed\n");
402         break;
403     default:
404         {
405
406             afs_int32 offset;
407
408             initialize_KA_error_table();
409             initialize_RXK_error_table();
410             initialize_KTC_error_table();
411             initialize_ACFG_error_table();
412             initialize_CMD_error_table();
413             initialize_VL_error_table();
414
415             offset = errcode & ((1 << ERRCODE_RANGE) - 1);
416             fprintf(STDERR, "%s: %s\n", afs_error_table_name(errcode),
417                     afs_error_message(errcode));
418             break;
419         }
420     }
421     return 0;
422 }
423
424 void init_volintInfo(struct volintInfo *vinfo) {
425     memset(vinfo, 0, sizeof(struct volintInfo));
426
427     vinfo->maxquota = -1;
428     vinfo->dayUse = -1;
429     vinfo->creationDate = -1;
430     vinfo->updateDate = -1;
431     vinfo->flags = -1;
432     vinfo->spare0 = -1;
433     vinfo->spare1 = -1;
434     vinfo->spare2 = -1;
435     vinfo->spare3 = -1;
436 }
437
438 static struct rx_securityClass *uvclass = 0;
439 static int uvindex = -1;
440 /* called by VLDBClient_Init to set the security module to be used in the RPC */
441 int
442 UV_SetSecurity(register struct rx_securityClass *as, afs_int32 aindex)
443 {
444     uvindex = aindex;
445     uvclass = as;
446     return 0;
447 }
448
449 /* bind to volser on <port> <aserver> */
450 /* takes server address in network order, port in host order.  dumb */
451 struct rx_connection *
452 UV_Bind(afs_int32 aserver, afs_int32 port)
453 {
454     register struct rx_connection *tc;
455
456     tc = rx_NewConnection(aserver, htons(port), VOLSERVICE_ID, uvclass,
457                           uvindex);
458     return tc;
459 }
460
461 static int 
462 AFSVolCreateVolume_retry(struct rx_connection *z_conn,
463                        afs_int32 partition, char *name, afs_int32 type,
464                        afs_int32 parent, afs_uint32 *volid, afs_int32 *trans)
465 {
466     afs_int32 code;
467     int retries = 3;
468     while (retries) {
469         code = AFSVolCreateVolume(z_conn, partition, name, type, parent,
470                                   volid, trans);
471         if (code != VOLSERVOLBUSY)
472             break;
473         retries--;
474 #ifdef AFS_PTHREAD_ENV
475         sleep(3-retries);
476 #else
477         IOMGR_Sleep(3-retries);
478 #endif
479     }
480     return code;
481 }
482
483 static int 
484 AFSVolTransCreate_retry(struct rx_connection *z_conn,
485                         afs_int32 volume, afs_int32 partition, 
486                         afs_int32 flags, afs_int32 * trans) 
487 {
488     afs_int32 code;
489     int retries = 3;
490     while (retries) {
491         code = AFSVolTransCreate(z_conn, volume, partition, flags, trans);
492         if (code != VOLSERVOLBUSY)
493             break;
494         retries--;
495 #ifdef AFS_PTHREAD_ENV
496         sleep(3-retries);
497 #else
498         IOMGR_Sleep(3-retries);
499 #endif
500     }
501     return code;
502 }
503
504 #if 0
505 /* if <okvol> is allright(indicated by beibg able to
506  * start a transaction, delete the <delvol> */
507 static afs_int32
508 CheckAndDeleteVolume(struct rx_connection *aconn, afs_int32 apart,
509                      afs_uint32 okvol, afs_uint32 delvol)
510 {
511     afs_int32 error, code, tid, rcode;
512     error = 0;
513     code = 0;
514
515     if (okvol == 0) {
516         code = AFSVolTransCreate_retry(aconn, delvol, apart, ITOffline, &tid);
517         if (!error && code)
518             error = code;
519         code = AFSVolDeleteVolume(aconn, tid);
520         if (!error && code)
521             error = code;
522         code = AFSVolEndTrans(aconn, tid, &rcode);
523         if (!code)
524             code = rcode;
525         if (!error && code)
526             error = code;
527         return error;
528     } else {
529         code = AFSVolTransCreate_retry(aconn, okvol, apart, ITOffline, &tid);
530         if (!code) {
531             code = AFSVolEndTrans(aconn, tid, &rcode);
532             if (!code)
533                 code = rcode;
534             if (!error && code)
535                 error = code;
536             code = AFSVolTransCreate_retry(aconn, delvol, apart, ITOffline, &tid);
537             if (!error && code)
538                 error = code;
539             code = AFSVolDeleteVolume(aconn, tid);
540             if (!error && code)
541                 error = code;
542             code = AFSVolEndTrans(aconn, tid, &rcode);
543             if (!code)
544                 code = rcode;
545             if (!error && code)
546                 error = code;
547         } else
548             error = code;
549         return error;
550     }
551 }
552
553 #endif
554
555 /* called by EmuerateEntry, show vldb entry in a reasonable format */
556 void
557 SubEnumerateEntry(struct nvldbentry *entry)
558 {
559     int i;
560     char pname[10];
561     int isMixed = 0;
562     char hoststr[16];
563
564 #ifdef notdef
565     fprintf(STDOUT, "   readWriteID %-10u ", entry->volumeId[RWVOL]);
566     if (entry->flags & RW_EXISTS)
567         fprintf(STDOUT, " valid \n");
568     else
569         fprintf(STDOUT, " invalid \n");
570     fprintf(STDOUT, "   readOnlyID  %-10u ", entry->volumeId[ROVOL]);
571     if (entry->flags & RO_EXISTS)
572         fprintf(STDOUT, " valid \n");
573     else
574         fprintf(STDOUT, " invalid \n");
575     fprintf(STDOUT, "   backUpID    %-10u ", entry->volumeId[BACKVOL]);
576     if (entry->flags & BACK_EXISTS)
577         fprintf(STDOUT, " valid \n");
578     else
579         fprintf(STDOUT, " invalid \n");
580     if ((entry->cloneId != 0) && (entry->flags & RO_EXISTS))
581         fprintf(STDOUT, "    releaseClone %-10u \n", entry->cloneId);
582 #else
583     if (entry->flags & RW_EXISTS)
584         fprintf(STDOUT, "    RWrite: %-10u", entry->volumeId[RWVOL]);
585     if (entry->flags & RO_EXISTS)
586         fprintf(STDOUT, "    ROnly: %-10u", entry->volumeId[ROVOL]);
587     if (entry->flags & BACK_EXISTS)
588         fprintf(STDOUT, "    Backup: %-10u", entry->volumeId[BACKVOL]);
589     if ((entry->cloneId != 0) && (entry->flags & RO_EXISTS))
590         fprintf(STDOUT, "    RClone: %-10lu", (unsigned long)entry->cloneId);
591     fprintf(STDOUT, "\n");
592 #endif
593     fprintf(STDOUT, "    number of sites -> %lu\n",
594             (unsigned long)entry->nServers);
595     for (i = 0; i < entry->nServers; i++) {
596         if (entry->serverFlags[i] & NEW_REPSITE)
597             isMixed = 1;
598     }
599     for (i = 0; i < entry->nServers; i++) {
600         MapPartIdIntoName(entry->serverPartition[i], pname);
601         fprintf(STDOUT, "       server %s partition %s ",
602                 noresolve ? afs_inet_ntoa_r(entry->serverNumber[i], hoststr) : 
603                 hostutil_GetNameByINet(entry->serverNumber[i]), pname);
604         if (entry->serverFlags[i] & ITSRWVOL)
605             fprintf(STDOUT, "RW Site ");
606         else
607             fprintf(STDOUT, "RO Site ");
608         if (isMixed) {
609             if (entry->serverFlags[i] & NEW_REPSITE)
610                 fprintf(STDOUT," -- New release");
611             else
612                 if (!(entry->serverFlags[i] & ITSRWVOL))
613                     fprintf(STDOUT," -- Old release");
614         } else {
615             if (entry->serverFlags[i] & RO_DONTUSE)
616                 fprintf(STDOUT, " -- Not released");
617         }
618         fprintf(STDOUT, "\n");
619     }
620
621     return;
622
623 }
624
625 /*enumerate the vldb entry corresponding to <entry> */
626 void
627 EnumerateEntry(struct nvldbentry *entry)
628 {
629
630     fprintf(STDOUT, "\n");
631     fprintf(STDOUT, "%s \n", entry->name);
632     SubEnumerateEntry(entry);
633     return;
634 }
635
636 /* forcibly remove a volume.  Very dangerous call */
637 int
638 UV_NukeVolume(afs_int32 server, afs_int32 partid, afs_uint32 volid)
639 {
640     register struct rx_connection *tconn;
641     register afs_int32 code;
642
643     tconn = UV_Bind(server, AFSCONF_VOLUMEPORT);
644     if (tconn) {
645         code = AFSVolNukeVolume(tconn, partid, volid);
646         rx_DestroyConnection(tconn);
647     } else
648         code = 0;
649     return code;
650 }
651
652 /* like df. Return usage of <pname> on <server> in <partition> */
653 int
654 UV_PartitionInfo64(afs_int32 server, char *pname,
655                    struct diskPartition64 *partition)
656 {
657     register struct rx_connection *aconn;
658     afs_int32 code = 0;
659
660     aconn = (struct rx_connection *)0;
661     aconn = UV_Bind(server, AFSCONF_VOLUMEPORT);
662     code = AFSVolPartitionInfo64(aconn, pname, partition);
663     if (code == RXGEN_OPCODE) {
664         struct diskPartition *dpp = 
665             (struct diskPartition *)malloc(sizeof(struct diskPartition));
666         code = AFSVolPartitionInfo(aconn, pname, dpp);
667         if (!code) {
668             strncpy(partition->name, dpp->name, 32);
669             strncpy(partition->devName, dpp->devName, 32);
670             partition->lock_fd = dpp->lock_fd;
671             partition->free = dpp->free;
672             partition->minFree = dpp->minFree;
673         }
674         free(dpp);
675     } 
676     if (code) {
677         fprintf(STDERR, "Could not get information on partition %s\n", pname);
678         PrintError("", code);
679     }
680     if (aconn)
681         rx_DestroyConnection(aconn);
682     return code;
683 }
684
685 /* old interface to create volumes */
686 int
687 UV_CreateVolume(afs_int32 aserver, afs_int32 apart, char *aname,
688                 afs_uint32 * anewid)
689 {
690     afs_int32 code;
691     *anewid = 0;
692     code = UV_CreateVolume2(aserver, apart, aname, 5000, 0, 0, 0, 0, anewid);
693     return code;
694 }
695
696 /* less old interface to create volumes */
697 int
698 UV_CreateVolume2(afs_int32 aserver, afs_int32 apart, char *aname,
699                  afs_int32 aquota, afs_int32 aspare1, afs_int32 aspare2,
700                  afs_int32 aspare3, afs_int32 aspare4, afs_uint32 * anewid)
701 {
702     afs_uint32 roid = 0, bkid = 0;
703     return UV_CreateVolume3(aserver, apart, aname, aquota, aspare1, aspare2,
704         aspare3, aspare4, anewid, &roid, &bkid);
705 }
706
707 /**
708  * Create a volume on the given server and partition
709  *
710  * @param aserver  server to create volume on
711  * @param spart  partition to create volume on
712  * @param aname  name of new volume
713  * @param aquota  quota for new volume
714  * @param anewid  contains the desired volume id for the new volume. If
715  *                *anewid == 0, a new id will be chosen, and will be placed
716  *                in *anewid when UV_CreateVolume3 returns.
717  * @param aroid  contains the desired RO volume id. If NULL, the RO id entry
718  *               will be unset. If *aroid == 0, an id will be chosen, and
719  *               will be placed in *anewid when UV_CreateVolume3 returns.
720  * @param abkid  same as aroid, except for the BK volume id instead of the
721  *               RO volume id.
722  * @return 0 on success, error code otherwise.
723  */
724 int
725 UV_CreateVolume3(afs_int32 aserver, afs_int32 apart, char *aname,
726                  afs_int32 aquota, afs_int32 aspare1, afs_int32 aspare2,
727                  afs_int32 aspare3, afs_int32 aspare4, afs_uint32 * anewid,
728                  afs_uint32 * aroid, afs_uint32 * abkid)
729 {
730     register struct rx_connection *aconn;
731     afs_int32 tid;
732     register afs_int32 code;
733     afs_int32 error;
734     afs_int32 rcode, vcode;
735     afs_int32 lastid;
736     struct nvldbentry entry, storeEntry;        /*the new vldb entry */
737     struct volintInfo tstatus;
738
739     tid = 0;
740     aconn = (struct rx_connection *)0;
741     error = 0;
742
743     init_volintInfo(&tstatus);
744     tstatus.maxquota = aquota;
745
746     aconn = UV_Bind(aserver, AFSCONF_VOLUMEPORT);
747
748     if (aroid && *aroid) {
749         VPRINT1("Using RO volume ID %d.\n", *aroid);
750     }
751     if (abkid && *abkid) {
752         VPRINT1("Using BK volume ID %d.\n", *abkid);
753     }
754
755     if (*anewid) {
756         vcode = VLDB_GetEntryByID(*anewid, -1, &entry);
757         if (!vcode) {
758             fprintf(STDERR, "Volume ID %d already exists\n", *anewid);
759             return VVOLEXISTS;
760         }
761         VPRINT1("Using volume ID %d.\n", *anewid);
762     } else {
763         vcode = ubik_VL_GetNewVolumeId(cstruct, 0, 1, anewid);
764         EGOTO1(cfail, vcode, "Could not get an Id for volume %s\n", aname);
765
766         if (aroid && *aroid == 0) {
767             vcode = ubik_VL_GetNewVolumeId(cstruct, 0, 1, aroid);
768             EGOTO1(cfail, vcode, "Could not get an RO Id for volume %s\n", aname);
769         }
770
771         if (abkid && *abkid == 0) {
772             vcode = ubik_VL_GetNewVolumeId(cstruct, 0, 1, abkid);
773             EGOTO1(cfail, vcode, "Could not get a BK Id for volume %s\n", aname);
774         }
775     }
776
777     /* rw,ro, bk id are related in the default case */
778     /* If caller specified RW id, but not RO/BK ids, have them be RW+1 and RW+2 */
779     lastid = *anewid;
780     if (aroid && *aroid == 0) {
781         *aroid = ++lastid;
782     }
783     if (abkid && *abkid == 0) {
784         *abkid = ++lastid;
785     }
786
787     code =
788         AFSVolCreateVolume_retry(aconn, apart, aname, volser_RW, 0, anewid, &tid);
789     EGOTO2(cfail, code, "Failed to create the volume %s %u \n", aname,
790            *anewid);
791
792     code = AFSVolSetInfo(aconn, tid, &tstatus);
793     if (code)
794         EPRINT(code, "Could not change quota, continuing...\n");
795
796     code = AFSVolSetFlags(aconn, tid, 0);       /* bring it online (mark it InService */
797     EGOTO2(cfail, code, "Could not bring the volume %s %u online \n", aname,
798            *anewid);
799
800     VPRINT2("Volume %s %u created and brought online\n", aname, *anewid);
801
802     /* set up the vldb entry for this volume */
803     strncpy(entry.name, aname, VOLSER_OLDMAXVOLNAME);
804     entry.nServers = 1;
805     entry.serverNumber[0] = aserver;    /* this should have another 
806                                          * level of indirection later */
807     entry.serverPartition[0] = apart;   /* this should also have 
808                                          * another indirection level */
809     entry.flags = RW_EXISTS;    /* this records that rw volume exists */
810     entry.serverFlags[0] = ITSRWVOL;    /*this rep site has rw  vol */
811     entry.volumeId[RWVOL] = *anewid;
812     entry.volumeId[ROVOL] = aroid ? *aroid : 0;
813     entry.volumeId[BACKVOL] = abkid ? *abkid : 0;
814     entry.cloneId = 0;
815     /*map into right byte order, before passing to xdr, the stuff has to be in host
816      * byte order. Xdr converts it into network order */
817     MapNetworkToHost(&entry, &storeEntry);
818     /* create the vldb entry */
819     vcode = VLDB_CreateEntry(&storeEntry);
820     if (vcode) {
821         fprintf(STDERR,
822                 "Could not create a VLDB entry for the volume %s %lu\n",
823                 aname, (unsigned long)*anewid);
824         /*destroy the created volume */
825         VPRINT1("Deleting the newly created volume %u\n", *anewid);
826         AFSVolDeleteVolume(aconn, tid);
827         error = vcode;
828         goto cfail;
829     }
830     VPRINT2("Created the VLDB entry for the volume %s %u\n", aname, *anewid);
831     /* volume created, now terminate the transaction and release the connection */
832     code = AFSVolEndTrans(aconn, tid, &rcode);  /*if it crashes before this
833                                                  * the volume will come online anyway when transaction timesout , so if
834                                                  * vldb entry exists then the volume is guaranteed to exist too wrt create */
835     tid = 0;
836     if (code) {
837         fprintf(STDERR,
838                 "Failed to end the transaction on the volume %s %lu\n", aname,
839                 (unsigned long)*anewid);
840         error = code;
841         goto cfail;
842     }
843
844   cfail:
845     if (tid) {
846         code = AFSVolEndTrans(aconn, tid, &rcode);
847         if (code)
848             fprintf(STDERR, "WARNING: could not end transaction\n");
849     }
850     if (aconn)
851         rx_DestroyConnection(aconn);
852     PrintError("", error);
853     return error;
854 }
855
856 /* create a volume, given a server, partition number, volume name --> sends
857 * back new vol id in <anewid>*/
858 int
859 UV_AddVLDBEntry(afs_int32 aserver, afs_int32 apart, char *aname,
860                 afs_uint32 aid)
861 {
862     register struct rx_connection *aconn;
863     afs_int32 error;
864     afs_int32 vcode;
865     struct nvldbentry entry, storeEntry;        /*the new vldb entry */
866
867     aconn = (struct rx_connection *)0;
868     error = 0;
869
870     /* set up the vldb entry for this volume */
871     strncpy(entry.name, aname, VOLSER_OLDMAXVOLNAME);
872     entry.nServers = 1;
873     entry.serverNumber[0] = aserver;    /* this should have another 
874                                          * level of indirection later */
875     entry.serverPartition[0] = apart;   /* this should also have 
876                                          * another indirection level */
877     entry.flags = RW_EXISTS;    /* this records that rw volume exists */
878     entry.serverFlags[0] = ITSRWVOL;    /*this rep site has rw  vol */
879     entry.volumeId[RWVOL] = aid;
880 #ifdef notdef
881     entry.volumeId[ROVOL] = anewid + 1; /* rw,ro, bk id are related in the default case */
882     entry.volumeId[BACKVOL] = *anewid + 2;
883 #else
884     entry.volumeId[ROVOL] = 0;
885     entry.volumeId[BACKVOL] = 0;
886 #endif
887     entry.cloneId = 0;
888     /*map into right byte order, before passing to xdr, the stuff has to be in host
889      * byte order. Xdr converts it into network order */
890     MapNetworkToHost(&entry, &storeEntry);
891     /* create the vldb entry */
892     vcode = VLDB_CreateEntry(&storeEntry);
893     if (vcode) {
894         fprintf(STDERR,
895                 "Could not create a VLDB entry for the  volume %s %lu\n",
896                 aname, (unsigned long)aid);
897         error = vcode;
898         goto cfail;
899     }
900     VPRINT2("Created the VLDB entry for the volume %s %u\n", aname, aid);
901
902   cfail:
903     if (aconn)
904         rx_DestroyConnection(aconn);
905     PrintError("", error);
906     return error;
907 }
908
909 /* Delete the volume <volid>on <aserver> <apart>
910  * the physical entry gets removed from the vldb only if the ref count 
911  * becomes zero
912  */
913 int
914 UV_DeleteVolume(afs_int32 aserver, afs_int32 apart, afs_uint32 avolid)
915 {
916     struct rx_connection *aconn = (struct rx_connection *)0;
917     afs_int32 ttid = 0;
918     afs_int32 code, rcode;
919     afs_int32 error = 0;
920     struct nvldbentry entry, storeEntry;
921     int islocked = 0;
922     afs_int32 avoltype = -1, vtype;
923     int notondisk = 0, notinvldb = 0;
924
925     /* Find and read bhe VLDB entry for this volume */
926     code = ubik_VL_SetLock(cstruct, 0, avolid, avoltype, VLOP_DELETE);
927     if (code) {
928         if (code != VL_NOENT) {
929             EGOTO1(error_exit, code,
930                    "Could not lock VLDB entry for the volume %u\n", avolid);
931         }
932         notinvldb = 1;
933     } else {
934         islocked = 1;
935
936         code = VLDB_GetEntryByID(avolid, avoltype, &entry);
937         EGOTO1(error_exit, code, "Could not fetch VLDB entry for volume %u\n",
938                avolid);
939         MapHostToNetwork(&entry);
940
941         if (verbose)
942             EnumerateEntry(&entry);
943     }
944
945     /* Whether volume is in the VLDB or not. Delete the volume on disk */
946     aconn = UV_Bind(aserver, AFSCONF_VOLUMEPORT);
947     code = AFSVolTransCreate_retry(aconn, avolid, apart, ITOffline, &ttid);
948     if (code) {
949         if (code == VNOVOL) {
950             notondisk = 1;
951         } else {
952             EGOTO1(error_exit, code, "Transaction on volume %u failed\n",
953                    avolid);
954         }
955     } else {
956         VPRINT1("Trying to delete the volume %u ...", avolid);
957
958         code = AFSVolDeleteVolume(aconn, ttid);
959         EGOTO1(error_exit, code, "Could not delete the volume %u \n", avolid);
960
961         code = AFSVolEndTrans(aconn, ttid, &rcode);
962         code = (code ? code : rcode);
963         ttid = 0;
964         EGOTO1(error_exit, code,
965                "Could not end the transaction for the volume %u \n", avolid);
966         VDONE;
967     }
968
969     /* Now update the VLDB entry.
970      * But first, verify we have a VLDB entry.
971      * Whether volume is on disk or not. Delete the volume in VLDB.
972      */
973     if (notinvldb)
974         ERROR_EXIT(0);
975
976     if (avolid == entry.volumeId[BACKVOL]) {
977         /* Its a backup volume, modify the VLDB entry. Check that the
978          * backup volume is on the server/partition we asked to delete.
979          */
980         if (!(entry.flags & BACK_EXISTS) || !Lp_Match(aserver, apart, &entry)) {
981             notinvldb = 2;      /* Not on this server and partition */
982             ERROR_EXIT(0);
983         }
984
985         VPRINT1("Marking the backup volume %u deleted in the VLDB\n", avolid);
986
987         entry.flags &= ~BACK_EXISTS;
988         vtype = BACKVOL;
989     }
990
991     else if (avolid == entry.volumeId[ROVOL]) {
992         /* Its a read-only volume, modify the VLDB entry. Check that the
993          * readonly volume is on the server/partition we asked to delete.
994          * If flags does not have RO_EIXSTS set, then this may mean the RO 
995          * hasn't been released (and could exist in VLDB).
996          */
997         if (!Lp_ROMatch(aserver, apart, &entry)) {
998             notinvldb = 2;      /* Not found on this server and partition */
999             ERROR_EXIT(0);
1000         }
1001
1002         if (verbose)
1003             fprintf(STDOUT,
1004                     "Marking the readonly volume %lu deleted in the VLDB\n",
1005                     (unsigned long)avolid);
1006
1007         Lp_SetROValue(&entry, aserver, apart, 0, 0);    /* delete the site */
1008         entry.nServers--;
1009         if (!Lp_ROMatch(0, 0, &entry))
1010             entry.flags &= ~RO_EXISTS;  /* This was the last ro volume */
1011         vtype = ROVOL;
1012     }
1013
1014     else if (avolid == entry.volumeId[RWVOL]) {
1015         /* It's a rw volume, delete the backup volume, modify the VLDB entry.
1016          * Check that the readwrite volumes is on the server/partition we
1017          * asked to delete.
1018          */
1019         if (!(entry.flags & RW_EXISTS) || !Lp_Match(aserver, apart, &entry)) {
1020             notinvldb = 2;      /* Not found on this server and partition */
1021             ERROR_EXIT(0);
1022         }
1023
1024         /* Delete backup if it exists */
1025         code =
1026             AFSVolTransCreate_retry(aconn, entry.volumeId[BACKVOL], apart,
1027                                     ITOffline, &ttid);
1028
1029         if (!code) {
1030             if (verbose) {
1031                 fprintf(STDOUT, "Trying to delete the backup volume %u ...",
1032                         entry.volumeId[BACKVOL]);
1033                 fflush(STDOUT);
1034             }
1035             code = AFSVolDeleteVolume(aconn, ttid);
1036             EGOTO1(error_exit, code, "Could not delete the volume %u \n",
1037                    entry.volumeId[BACKVOL]);
1038
1039             code = AFSVolEndTrans(aconn, ttid, &rcode);
1040             ttid = 0;
1041             code = (code ? code : rcode);
1042             EGOTO1(error_exit, code,
1043                    "Could not end the transaction for the volume %u \n",
1044                    entry.volumeId[BACKVOL]);
1045             if (verbose)
1046                 fprintf(STDOUT, " done\n");
1047         }
1048
1049         if (verbose)
1050             fprintf(STDOUT,
1051                     "Marking the readwrite volume %lu%s deleted in the VLDB\n",
1052                     (unsigned long)avolid,
1053                     ((entry.
1054                       flags & BACK_EXISTS) ? ", and its backup volume," :
1055                      ""));
1056
1057         Lp_SetRWValue(&entry, aserver, apart, 0L, 0L);
1058         entry.nServers--;
1059         entry.flags &= ~(BACK_EXISTS | RW_EXISTS);
1060         vtype = RWVOL;
1061
1062         if (entry.flags & RO_EXISTS)
1063             fprintf(STDERR, "WARNING: ReadOnly copy(s) may still exist\n");
1064     }
1065
1066     else {
1067         notinvldb = 2;          /* Not found on this server and partition */
1068         ERROR_EXIT(0);
1069     }
1070
1071     /* Either delete or replace the VLDB entry */
1072     if ((entry.nServers <= 0) || !(entry.flags & (RO_EXISTS | RW_EXISTS))) {
1073         if (verbose)
1074             fprintf(STDOUT,
1075                     "Last reference to the VLDB entry for %lu - deleting entry\n",
1076                     (unsigned long)avolid);
1077         code = ubik_VL_DeleteEntry(cstruct, 0, avolid, vtype);
1078         EGOTO1(error_exit, code,
1079                "Could not delete the VLDB entry for the volume %u \n",
1080                avolid);
1081     } else {
1082         MapNetworkToHost(&entry, &storeEntry);
1083         code =
1084             VLDB_ReplaceEntry(avolid, vtype, &storeEntry,
1085                               (LOCKREL_OPCODE | LOCKREL_AFSID |
1086                                LOCKREL_TIMESTAMP));
1087         EGOTO1(error_exit, code,
1088                "Could not update the VLDB entry for the volume %u \n",
1089                avolid);
1090     }
1091     islocked = 0;
1092
1093   error_exit:
1094     if (error)
1095         EPRINT(error, "\n");
1096
1097     if (notondisk && notinvldb) {
1098         EPRINT2(VOLSERNOVOL, "Volume %u does not exist %s\n", avolid,
1099                 ((notinvldb == 2) ? "on server and partition" : ""));
1100         if (!error)
1101             error = VOLSERNOVOL;
1102     } else if (notondisk) {
1103         fprintf(STDERR,
1104                 "WARNING: Volume %lu did not exist on the partition\n",
1105                 (unsigned long)avolid);
1106     } else if (notinvldb) {
1107         fprintf(STDERR, "WARNING: Volume %lu does not exist in VLDB %s\n",
1108                 (unsigned long)avolid,
1109                 ((notinvldb == 2) ? "on server and partition" : ""));
1110     }
1111
1112     if (ttid) {
1113         code = AFSVolEndTrans(aconn, ttid, &rcode);
1114         code = (code ? code : rcode);
1115         if (code) {
1116             fprintf(STDERR, "Could not end transaction on the volume %lu\n",
1117                     (unsigned long)avolid);
1118             PrintError("", code);
1119             if (!error)
1120                 error = code;
1121         }
1122     }
1123
1124     if (islocked) {
1125         code =
1126             ubik_VL_ReleaseLock(cstruct, 0, avolid, -1,
1127                                 (LOCKREL_OPCODE | LOCKREL_AFSID | 
1128                                  LOCKREL_TIMESTAMP));
1129         if (code) {
1130             EPRINT1(code,
1131                     "Could not release the lock on the VLDB entry for the volume %u \n",
1132                     avolid);
1133             if (!error)
1134                 error = code;
1135         }
1136     }
1137
1138     if (aconn)
1139         rx_DestroyConnection(aconn);
1140     return error;
1141 }
1142
1143 /* add recovery to UV_MoveVolume */
1144
1145 #define TESTC   0               /* set to test recovery code, clear for production */
1146
1147 jmp_buf env;
1148 int interrupt = 0;
1149
1150 void
1151 sigint_handler(int x)
1152 {
1153     if (interrupt)
1154         longjmp(env, 0);
1155
1156     fprintf(STDOUT, "\nSIGINT handler: vos move operation in progress\n");
1157     fprintf(STDOUT,
1158             "WARNING: may leave AFS storage and metadata in indeterminate state\n");
1159     fprintf(STDOUT, "enter second control-c to exit\n");
1160     fflush(STDOUT);
1161
1162     interrupt = 1;
1163     (void)signal(SIGINT, sigint_handler);
1164
1165     return;
1166 }
1167
1168 /* Move volume <afromvol> on <afromserver> <afrompart> to <atoserver>
1169  * <atopart>.  The operation is almost idempotent.  The following
1170  * flags are recognized:
1171  * 
1172  *     RV_NOCLONE - don't use a copy clone
1173  */
1174
1175 int
1176 UV_MoveVolume2(afs_uint32 afromvol, afs_int32 afromserver, afs_int32 afrompart,
1177                afs_int32 atoserver, afs_int32 atopart, int flags)
1178 {
1179     struct rx_connection *toconn, *fromconn;
1180     afs_int32 fromtid, totid, clonetid;
1181     char vname[64];
1182     char *volName = 0;
1183     char tmpName[VOLSER_MAXVOLNAME + 1];
1184     afs_int32 rcode;
1185     afs_int32 fromDate;
1186     struct restoreCookie cookie;
1187     register afs_int32 vcode, code;
1188     afs_uint32 newVol, volid, backupId;
1189     struct volser_status tstatus;
1190     struct destServer destination;
1191
1192     struct nvldbentry entry, storeEntry;
1193     int i, islocked, pntg;
1194     afs_int32 error;
1195     char in, lf;                /* for test code */
1196     int same;
1197     char hoststr[16];
1198
1199 #ifdef  ENABLE_BUGFIX_1165
1200     volEntries volumeInfo;
1201     struct volintInfo *infop = 0;
1202 #endif
1203
1204     islocked = 0;
1205     fromconn = (struct rx_connection *)0;
1206     toconn = (struct rx_connection *)0;
1207     fromtid = 0;
1208     totid = 0;
1209     clonetid = 0;
1210     error = 0;
1211     volid = 0;
1212     pntg = 0;
1213     backupId = 0;
1214     newVol = 0;
1215
1216     /* support control-c processing */
1217     if (setjmp(env))
1218         goto mfail;
1219     (void)signal(SIGINT, sigint_handler);
1220
1221     if (TESTC) {
1222         fprintf(STDOUT,
1223                 "\nThere are three tests points - verifies all code paths through recovery.\n");
1224         fprintf(STDOUT, "First test point - operation not started.\n");
1225         fprintf(STDOUT, "...test here (y, n)? ");
1226         fflush(STDOUT);
1227         fscanf(stdin, "%c", &in);
1228         fscanf(stdin, "%c", &lf);       /* toss away */
1229         if (in == 'y') {
1230             fprintf(STDOUT, "type control-c\n");
1231             while (1) {
1232                 fprintf(stdout, ".");
1233                 fflush(stdout);
1234                 sleep(1);
1235             }
1236         }
1237         /* or drop through */
1238     }
1239
1240     vcode = VLDB_GetEntryByID(afromvol, -1, &entry);
1241     EGOTO1(mfail, vcode,
1242            "Could not fetch the entry for the volume  %u from the VLDB \n",
1243            afromvol);
1244
1245     if (entry.volumeId[RWVOL] != afromvol) {
1246         fprintf(STDERR, "Only RW volume can be moved\n");
1247         exit(1);
1248     }
1249
1250     vcode = ubik_VL_SetLock(cstruct, 0, afromvol, RWVOL, VLOP_MOVE);
1251     EGOTO1(mfail, vcode, "Could not lock entry for volume %u \n", afromvol);
1252     islocked = 1;
1253
1254     vcode = VLDB_GetEntryByID(afromvol, RWVOL, &entry);
1255     EGOTO1(mfail, vcode,
1256            "Could not fetch the entry for the volume  %u from the VLDB \n",
1257            afromvol);
1258
1259     backupId = entry.volumeId[BACKVOL];
1260     MapHostToNetwork(&entry);
1261
1262     if (!Lp_Match(afromserver, afrompart, &entry)) {
1263         /* the from server and partition do not exist in the vldb entry corresponding to volid */
1264         if (!Lp_Match(atoserver, atopart, &entry)) {
1265             /* the to server and partition do not exist in the vldb entry corresponding to volid */
1266             fprintf(STDERR, "The volume %lu is not on the specified site. \n",
1267                     (unsigned long)afromvol);
1268             fprintf(STDERR, "The current site is :");
1269             for (i = 0; i < entry.nServers; i++) {
1270                 if (entry.serverFlags[i] == ITSRWVOL) {
1271                     char pname[10];
1272                     MapPartIdIntoName(entry.serverPartition[i], pname);
1273                     fprintf(STDERR, " server %s partition %s \n",
1274                             noresolve ? afs_inet_ntoa_r(entry.serverNumber[i], hoststr) :
1275                             hostutil_GetNameByINet(entry.serverNumber[i]),
1276                             pname);
1277                 }
1278             }
1279             vcode =
1280                 ubik_VL_ReleaseLock(cstruct, 0, afromvol, -1,
1281                           (LOCKREL_OPCODE | LOCKREL_AFSID |
1282                            LOCKREL_TIMESTAMP));
1283             EGOTO1(mfail, vcode,
1284                    " Could not release lock on the VLDB entry for the volume %u \n",
1285                    afromvol);
1286
1287             return VOLSERVOLMOVED;
1288         }
1289
1290         /* delete the volume afromvol on src_server */
1291         /* from-info does not exist but to-info does =>
1292          * we have already done the move, but the volume
1293          * may still be existing physically on from fileserver
1294          */
1295         fromconn = UV_Bind(afromserver, AFSCONF_VOLUMEPORT);
1296         fromtid = 0;
1297         pntg = 1;
1298
1299         code =
1300             AFSVolTransCreate_retry(fromconn, afromvol, afrompart, ITOffline,
1301                                     &fromtid);
1302
1303         if (!code) {            /* volume exists - delete it */
1304             VPRINT1("Setting flags on leftover source volume %u ...",
1305                     afromvol);
1306             code =
1307                 AFSVolSetFlags(fromconn, fromtid,
1308                                VTDeleteOnSalvage | VTOutOfService);
1309             EGOTO1(mfail, code,
1310                    "Failed to set flags on the leftover source volume %u\n",
1311                    afromvol);
1312             VDONE;
1313
1314             VPRINT1("Deleting leftover source volume %u ...", afromvol);
1315             code = AFSVolDeleteVolume(fromconn, fromtid);
1316             EGOTO1(mfail, code,
1317                    "Failed to delete the leftover source volume %u\n",
1318                    afromvol);
1319             VDONE;
1320
1321             VPRINT1("Ending transaction on leftover source volume %u ...",
1322                     afromvol);
1323             code = AFSVolEndTrans(fromconn, fromtid, &rcode);
1324             fromtid = 0;
1325             if (!code)
1326                 code = rcode;
1327             EGOTO1(mfail, code,
1328                    "Could not end the transaction for the leftover source volume %u \n",
1329                    afromvol);
1330             VDONE;
1331         }
1332
1333         /*delete the backup volume now */
1334         fromtid = 0;
1335         code =
1336             AFSVolTransCreate_retry(fromconn, backupId, afrompart, ITOffline,
1337                                     &fromtid);
1338
1339         if (!code) {            /* backup volume exists - delete it */
1340             VPRINT1("Setting flags on leftover backup volume %u ...",
1341                     backupId);
1342             code =
1343                 AFSVolSetFlags(fromconn, fromtid,
1344                                VTDeleteOnSalvage | VTOutOfService);
1345             EGOTO1(mfail, code,
1346                    "Failed to set flags on the backup volume %u\n", backupId);
1347             VDONE;
1348
1349             VPRINT1("Deleting leftover backup volume %u ...", backupId);
1350             code = AFSVolDeleteVolume(fromconn, fromtid);
1351             EGOTO1(mfail, code,
1352                    "Could not delete the leftover backup volume %u\n",
1353                    backupId);
1354             VDONE;
1355
1356             VPRINT1("Ending transaction on leftover backup volume %u ...",
1357                     backupId);
1358             code = AFSVolEndTrans(fromconn, fromtid, &rcode);
1359             fromtid = 0;
1360             if (!code)
1361                 code = rcode;
1362             EGOTO1(mfail, code,
1363                    "Could not end the transaction for the leftover backup volume %u\n",
1364                    backupId);
1365             VDONE;
1366         }
1367
1368         fromtid = 0;
1369         error = 0;
1370         goto mfail;
1371     }
1372
1373     /* From-info matches the vldb info about volid,
1374      * its ok start the move operation, the backup volume 
1375      * on the old site is deleted in the process 
1376      */
1377     if (afrompart == atopart) {
1378         same = VLDB_IsSameAddrs(afromserver, atoserver, &error);
1379         EGOTO2(mfail, error,
1380                "Failed to get info about server's %d address(es) from vlserver (err=%d); aborting call!\n",
1381                afromserver, error);
1382
1383         if (same) {
1384             EGOTO1(mfail, VOLSERVOLMOVED,
1385                    "Warning: Moving volume %u to its home partition ignored!\n",
1386                    afromvol);
1387         }
1388     }
1389
1390     pntg = 1;
1391     toconn = UV_Bind(atoserver, AFSCONF_VOLUMEPORT);    /* get connections to the servers */
1392     fromconn = UV_Bind(afromserver, AFSCONF_VOLUMEPORT);
1393     fromtid = totid = 0;        /* initialize to uncreated */
1394
1395     /* ***
1396      * clone the read/write volume locally.
1397      * ***/
1398
1399     VPRINT1("Starting transaction on source volume %u ...", afromvol);
1400     code = AFSVolTransCreate_retry(fromconn, afromvol, afrompart, ITBusy, &fromtid);
1401     EGOTO1(mfail, code, "Failed to create transaction on the volume %u\n",
1402            afromvol);
1403     VDONE;
1404
1405     if (!(flags & RV_NOCLONE)) {
1406         /* Get a clone id */
1407         VPRINT1("Allocating new volume id for clone of volume %u ...",
1408                 afromvol);
1409         newVol = 0;
1410         vcode = ubik_VL_GetNewVolumeId(cstruct, 0, 1, &newVol);
1411         EGOTO1(mfail, vcode,
1412                "Could not get an ID for the clone of volume %u from the VLDB\n",
1413                afromvol);
1414         VDONE;
1415
1416         /* Do the clone. Default flags on clone are set to delete on salvage and out of service */
1417         VPRINT1("Cloning source volume %u ...", afromvol);
1418         strcpy(vname, "move-clone-temp");
1419         code =
1420             AFSVolClone(fromconn, fromtid, 0, readonlyVolume, vname, &newVol);
1421         EGOTO1(mfail, code, "Failed to clone the source volume %u\n",
1422                afromvol);
1423         VDONE;
1424     }
1425
1426     /* lookup the name of the volume we just cloned */
1427     volid = afromvol;
1428     code = AFSVolGetName(fromconn, fromtid, &volName);
1429     EGOTO1(mfail, code, "Failed to get the name of the volume %u\n",
1430            afromvol);
1431
1432     VPRINT1("Ending the transaction on the source volume %u ...", afromvol);
1433     rcode = 0;
1434     code = AFSVolEndTrans(fromconn, fromtid, &rcode);
1435     fromtid = 0;
1436     if (!code)
1437         code = rcode;
1438     EGOTO1(mfail, code,
1439            "Failed to end the transaction on the source volume %u\n",
1440            afromvol);
1441     VDONE;
1442
1443     /* ***
1444      * Create the destination volume
1445      * ***/
1446
1447     if (!(flags & RV_NOCLONE)) {
1448         /* All of this is to get the fromDate */
1449         VPRINT1("Starting transaction on the cloned volume %u ...", newVol);
1450         code =
1451             AFSVolTransCreate_retry(fromconn, newVol, afrompart, ITOffline,
1452                               &clonetid);
1453         EGOTO1(mfail, code,
1454                "Failed to start a transaction on the cloned volume%u\n",
1455                newVol);
1456         VDONE;
1457
1458         VPRINT1("Setting flags on cloned volume %u ...", newVol);
1459         code =
1460             AFSVolSetFlags(fromconn, clonetid,
1461                            VTDeleteOnSalvage | VTOutOfService); /*redundant */
1462         EGOTO1(mfail, code, "Could not set flags on the cloned volume %u\n",
1463                newVol);
1464         VDONE;
1465
1466         /* remember time from which we've dumped the volume */
1467         VPRINT1("Getting status of cloned volume %u ...", newVol);
1468         code = AFSVolGetStatus(fromconn, clonetid, &tstatus);
1469         EGOTO1(mfail, code,
1470                "Failed to get the status of the cloned volume %u\n",
1471                newVol);
1472         VDONE;
1473
1474         fromDate = CLOCKADJ(tstatus.creationDate);
1475     } else {
1476         /* With RV_NOCLONE, just do a full copy from the source */
1477         fromDate = 0;
1478     }
1479
1480
1481 #ifdef  ENABLE_BUGFIX_1165
1482     /*
1483      * Get the internal volume state from the source volume. We'll use such info (i.e. dayUse)
1484      * to copy it to the new volume (via AFSSetInfo later on) so that when we move volumes we
1485      * don't use this information...
1486      */
1487     volumeInfo.volEntries_val = (volintInfo *) 0;       /*this hints the stub to allocate space */
1488     volumeInfo.volEntries_len = 0;
1489     code = AFSVolListOneVolume(fromconn, afrompart, afromvol, &volumeInfo);
1490     EGOTO1(mfail, code,
1491            "Failed to get the volint Info of the cloned volume %u\n",
1492            afromvol);
1493
1494     infop = (volintInfo *) volumeInfo.volEntries_val;
1495     infop->maxquota = -1;       /* Else it will replace the default quota */
1496     infop->creationDate = -1;   /* Else it will use the source creation date */
1497     infop->updateDate = -1;     /* Else it will use the source update date */
1498 #endif
1499
1500     /* create a volume on the target machine */
1501     volid = afromvol;
1502     code = AFSVolTransCreate_retry(toconn, volid, atopart, ITOffline, &totid);
1503     if (!code) {
1504         /* Delete the existing volume.
1505          * While we are deleting the volume in these steps, the transaction
1506          * we started against the cloned volume (clonetid above) will be
1507          * sitting idle. It will get cleaned up after 600 seconds
1508          */
1509         VPRINT1("Deleting pre-existing volume %u on destination ...", volid);
1510         code = AFSVolDeleteVolume(toconn, totid);
1511         EGOTO1(mfail, code,
1512                "Could not delete the pre-existing volume %u on destination\n",
1513                volid);
1514         VDONE;
1515
1516         VPRINT1
1517             ("Ending transaction on pre-existing volume %u on destination ...",
1518              volid);
1519         code = AFSVolEndTrans(toconn, totid, &rcode);
1520         totid = 0;
1521         if (!code)
1522             code = rcode;
1523         EGOTO1(mfail, code,
1524                "Could not end the transaction on pre-existing volume %u on destination\n",
1525                volid);
1526         VDONE;
1527     }
1528
1529     VPRINT1("Creating the destination volume %u ...", volid);
1530     code =
1531         AFSVolCreateVolume(toconn, atopart, volName, volser_RW, volid, &volid,
1532                            &totid);
1533     EGOTO1(mfail, code, "Failed to create the destination volume %u\n",
1534            volid);
1535     VDONE;
1536
1537     strncpy(tmpName, volName, VOLSER_OLDMAXVOLNAME);
1538     free(volName);
1539     volName = NULL;
1540
1541     VPRINT1("Setting volume flags on destination volume %u ...", volid);
1542     code =
1543         AFSVolSetFlags(toconn, totid, (VTDeleteOnSalvage | VTOutOfService));
1544     EGOTO1(mfail, code,
1545            "Failed to set the flags on the destination volume %u\n", volid);
1546     VDONE;
1547
1548     /***
1549      * Now dump the clone to the new volume
1550      ***/
1551
1552     destination.destHost = ntohl(atoserver);
1553     destination.destPort = AFSCONF_VOLUMEPORT;
1554     destination.destSSID = 1;
1555
1556     strncpy(cookie.name, tmpName, VOLSER_OLDMAXVOLNAME);
1557     cookie.type = RWVOL;
1558     cookie.parent = entry.volumeId[RWVOL];
1559     cookie.clone = 0;
1560
1561     if (!(flags & RV_NOCLONE)) {
1562         /* Copy the clone to the new volume */
1563         VPRINT2("Dumping from clone %u on source to volume %u on destination ...",
1564                 newVol, afromvol);
1565         code =
1566             AFSVolForward(fromconn, clonetid, 0, &destination, totid,
1567                           &cookie);
1568         EGOTO1(mfail, code, "Failed to move data for the volume %u\n", volid);
1569         VDONE;
1570
1571         VPRINT1("Ending transaction on cloned volume %u ...", newVol);
1572         code = AFSVolEndTrans(fromconn, clonetid, &rcode);
1573         if (!code)
1574             code = rcode;
1575         clonetid = 0;
1576         EGOTO1(mfail, code,
1577                "Failed to end the transaction on the cloned volume %u\n",
1578                newVol);
1579         VDONE;
1580     }
1581
1582     /* ***
1583      * reattach to the main-line volume, and incrementally dump it.
1584      * ***/
1585
1586     VPRINT1("Starting transaction on source volume %u ...", afromvol);
1587     code = AFSVolTransCreate_retry(fromconn, afromvol, afrompart, ITBusy, &fromtid);
1588     EGOTO1(mfail, code,
1589            "Failed to create a transaction on the source volume %u\n",
1590            afromvol);
1591     VDONE;
1592
1593     /* now do the incremental */
1594     VPRINT2
1595         ("Doing the%s dump from source to destination for volume %u ... ",
1596          (flags & RV_NOCLONE) ? "" : " incremental",
1597          afromvol);
1598     code =
1599         AFSVolForward(fromconn, fromtid, fromDate, &destination, totid,
1600                       &cookie);
1601     EGOTO1(mfail, code,
1602            "Failed to do the%s dump from rw volume on old site to rw volume on newsite\n",
1603           (flags & RV_NOCLONE) ? "" : " incremental");
1604     VDONE;
1605
1606     /* now adjust the flags so that the new volume becomes official */
1607     VPRINT1("Setting volume flags on old source volume %u ...", afromvol);
1608     code = AFSVolSetFlags(fromconn, fromtid, VTOutOfService);
1609     EGOTO(mfail, code,
1610           "Failed to set the flags to make old source volume offline\n");
1611     VDONE;
1612
1613     VPRINT1("Setting volume flags on new source volume %u ...", afromvol);
1614     code = AFSVolSetFlags(toconn, totid, 0);
1615     EGOTO(mfail, code,
1616           "Failed to set the flags to make new source volume online\n");
1617     VDONE;
1618
1619 #ifdef  ENABLE_BUGFIX_1165
1620     VPRINT1("Setting volume status on destination volume %u ...", volid);
1621     code = AFSVolSetInfo(toconn, totid, infop);
1622     EGOTO1(mfail, code,
1623            "Failed to set volume status on the destination volume %u\n",
1624            volid);
1625     VDONE;
1626 #endif
1627
1628     /* put new volume online */
1629     VPRINT1("Ending transaction on destination volume %u ...", afromvol);
1630     code = AFSVolEndTrans(toconn, totid, &rcode);
1631     totid = 0;
1632     if (!code)
1633         code = rcode;
1634     EGOTO1(mfail, code,
1635            "Failed to end the transaction on the volume %u on the new site\n",
1636            afromvol);
1637     VDONE;
1638
1639     Lp_SetRWValue(&entry, afromserver, afrompart, atoserver, atopart);
1640     MapNetworkToHost(&entry, &storeEntry);
1641     storeEntry.flags &= ~BACK_EXISTS;
1642
1643     if (TESTC) {
1644         fprintf(STDOUT,
1645                 "Second test point - operation in progress but not complete.\n");
1646         fprintf(STDOUT, "...test here (y, n)? ");
1647         fflush(STDOUT);
1648         fscanf(stdin, "%c", &in);
1649         fscanf(stdin, "%c", &lf);       /* toss away */
1650         if (in == 'y') {
1651             fprintf(STDOUT, "type control-c\n");
1652             while (1) {
1653                 fprintf(stdout, ".");
1654                 fflush(stdout);
1655                 sleep(1);
1656             }
1657         }
1658         /* or drop through */
1659     }
1660
1661     VPRINT1("Releasing lock on VLDB entry for volume %u ...", afromvol);
1662     vcode =
1663         VLDB_ReplaceEntry(afromvol, -1, &storeEntry,
1664                           (LOCKREL_OPCODE | LOCKREL_AFSID |
1665                            LOCKREL_TIMESTAMP));
1666     if (vcode) {
1667         fprintf(STDERR,
1668                 " Could not release the lock on the VLDB entry for the volume %s %lu \n",
1669                 storeEntry.name, (unsigned long)afromvol);
1670         error = vcode;
1671         goto mfail;
1672     }
1673     islocked = 0;
1674     VDONE;
1675
1676     if (TESTC) {
1677         fprintf(STDOUT,
1678                 "Third test point - operation complete but no cleanup.\n");
1679         fprintf(STDOUT, "...test here (y, n)? ");
1680         fflush(STDOUT);
1681         fscanf(stdin, "%c", &in);
1682         fscanf(stdin, "%c", &lf);       /* toss away */
1683         if (in == 'y') {
1684             fprintf(STDOUT, "type control-c\n");
1685             while (1) {
1686                 fprintf(stdout, ".");
1687                 fflush(stdout);
1688                 sleep(1);
1689             }
1690         }
1691         /* or drop through */
1692     }
1693 #ifdef notdef
1694     /* This is tricky.  File server is very stupid, and if you mark the volume
1695      * as VTOutOfService, it may mark the *good* instance (if you're moving
1696      * between partitions on the same machine) as out of service.  Since
1697      * we're cleaning this code up in DEcorum, we're just going to kludge around
1698      * it for now by removing this call. */
1699     /* already out of service, just zap it now */
1700     code =
1701         AFSVolSetFlags(fromconn, fromtid, VTDeleteOnSalvage | VTOutOfService);
1702     if (code) {
1703         fprintf(STDERR,
1704                 "Failed to set the flags to make the old source volume offline\n");
1705         goto mfail;
1706     }
1707 #endif
1708     if (atoserver != afromserver) {
1709         /* set forwarding pointer for moved volumes */
1710         VPRINT1("Setting forwarding pointer for volume %u ...", afromvol);
1711         code = AFSVolSetForwarding(fromconn, fromtid, atoserver);
1712         EGOTO1(mfail, code,
1713                "Failed to set the forwarding pointer for the volume %u\n",
1714                afromvol);
1715         VDONE;
1716     }
1717
1718     VPRINT1("Deleting old volume %u on source ...", afromvol);
1719     code = AFSVolDeleteVolume(fromconn, fromtid);       /* zap original volume */
1720     EGOTO1(mfail, code, "Failed to delete the old volume %u on source\n",
1721            afromvol);
1722     VDONE;
1723
1724     VPRINT1("Ending transaction on old volume %u on the source ...",
1725             afromvol);
1726     code = AFSVolEndTrans(fromconn, fromtid, &rcode);
1727     fromtid = 0;
1728     if (!code)
1729         code = rcode;
1730     EGOTO1(mfail, code,
1731            "Failed to end the transaction on the old volume %u on the source\n",
1732            afromvol);
1733     VDONE;
1734
1735     /* Delete the backup volume on the original site */
1736     VPRINT1("Creating transaction for backup volume %u on source ...",
1737             backupId);
1738     code =
1739         AFSVolTransCreate_retry(fromconn, backupId, afrompart, ITOffline, &fromtid);
1740     VDONE;
1741     if (!code) {
1742         VPRINT1("Setting flags on backup volume %u on source ...", backupId);
1743         code =
1744             AFSVolSetFlags(fromconn, fromtid,
1745                            VTDeleteOnSalvage | VTOutOfService);
1746         EGOTO1(mfail, code,
1747                "Failed to set the flags on the backup volume %u on the source\n",
1748                backupId);
1749         VDONE;
1750
1751         VPRINT1("Deleting the backup volume %u on the source ...", backupId);
1752         code = AFSVolDeleteVolume(fromconn, fromtid);
1753         EGOTO1(mfail, code,
1754                "Failed to delete the backup volume %u on the source\n",
1755                backupId);
1756         VDONE;
1757
1758         VPRINT1("Ending transaction on backup volume %u on source ...",
1759                 backupId);
1760         code = AFSVolEndTrans(fromconn, fromtid, &rcode);
1761         fromtid = 0;
1762         if (!code)
1763             code = rcode;
1764         EGOTO1(mfail, code,
1765                "Failed to end the transaction on the backup volume %u on the source\n",
1766                backupId);
1767         VDONE;
1768     } else
1769         code = 0;               /* no backup volume? that's okay */
1770
1771     fromtid = 0;
1772     if (!(flags & RV_NOCLONE)) {
1773         VPRINT1("Starting transaction on the cloned volume %u ...", newVol);
1774         code =
1775             AFSVolTransCreate_retry(fromconn, newVol, afrompart, ITOffline,
1776                               &clonetid);
1777         EGOTO1(mfail, code,
1778                "Failed to start a transaction on the cloned volume%u\n",
1779                newVol);
1780         VDONE;
1781
1782         /* now delete the clone */
1783         VPRINT1("Deleting the cloned volume %u ...", newVol);
1784         code = AFSVolDeleteVolume(fromconn, clonetid);
1785         EGOTO1(mfail, code, "Failed to delete the cloned volume %u\n",
1786                newVol);
1787         VDONE;
1788
1789         VPRINT1("Ending transaction on cloned volume %u ...", newVol);
1790         code = AFSVolEndTrans(fromconn, clonetid, &rcode);
1791         if (!code)
1792             code = rcode;
1793         clonetid = 0;
1794         EGOTO1(mfail, code,
1795                "Failed to end the transaction on the cloned volume %u\n",
1796                newVol);
1797         VDONE;
1798     }
1799
1800     /* fall through */
1801     /* END OF MOVE */
1802
1803     if (TESTC) {
1804         fprintf(STDOUT, "Fourth test point - operation complete.\n");
1805         fprintf(STDOUT, "...test here (y, n)? ");
1806         fflush(STDOUT);
1807         fscanf(stdin, "%c", &in);
1808         fscanf(stdin, "%c", &lf);       /* toss away */
1809         if (in == 'y') {
1810             fprintf(STDOUT, "type control-c\n");
1811             while (1) {
1812                 fprintf(stdout, ".");
1813                 fflush(stdout);
1814                 sleep(1);
1815             }
1816         }
1817         /* or drop through */
1818     }
1819
1820     /* normal cleanup code */
1821
1822     if (entry.flags & RO_EXISTS)
1823         fprintf(STDERR, "WARNING : readOnly copies still exist \n");
1824
1825     if (islocked) {
1826         VPRINT1("Cleanup: Releasing VLDB lock on volume %u ...", afromvol);
1827         vcode =
1828             ubik_VL_ReleaseLock(cstruct, 0, afromvol, -1,
1829                       (LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP));
1830         if (vcode) {
1831             VPRINT("\n");
1832             fprintf(STDERR,
1833                     " Could not release the lock on the VLDB entry for the volume %lu \n",
1834                     (unsigned long)afromvol);
1835             if (!error)
1836                 error = vcode;
1837         }
1838         VDONE;
1839     }
1840
1841     if (fromtid) {
1842         VPRINT1("Cleanup: Ending transaction on source volume %u ...",
1843                 afromvol);
1844         code = AFSVolEndTrans(fromconn, fromtid, &rcode);
1845         if (code || rcode) {
1846             VPRINT("\n");
1847             fprintf(STDERR,
1848                     "Could not end transaction on the source volume %lu\n",
1849                     (unsigned long)afromvol);
1850             if (!error)
1851                 error = (code ? code : rcode);
1852         }
1853         VDONE;
1854     }
1855
1856     if (clonetid) {
1857         VPRINT1("Cleanup: Ending transaction on clone volume %u ...", newVol);
1858         code = AFSVolEndTrans(fromconn, clonetid, &rcode);
1859         if (code || rcode) {
1860             VPRINT("\n");
1861             fprintf(STDERR,
1862                     "Could not end transaction on the source's clone volume %lu\n",
1863                     (unsigned long)newVol);
1864             if (!error)
1865                 error = (code ? code : rcode);
1866         }
1867         VDONE;
1868     }
1869
1870     if (totid) {
1871         VPRINT1("Cleanup: Ending transaction on destination volume %u ...",
1872                 afromvol);
1873         code = AFSVolEndTrans(toconn, totid, &rcode);
1874         if (code) {
1875             VPRINT("\n");
1876             fprintf(STDERR,
1877                     "Could not end transaction on destination volume %lu\n",
1878                     (unsigned long)afromvol);
1879             if (!error)
1880                 error = (code ? code : rcode);
1881         }
1882         VDONE;
1883     }
1884     if (volName)
1885         free(volName);
1886 #ifdef  ENABLE_BUGFIX_1165
1887     if (infop)
1888         free(infop);
1889 #endif
1890     if (fromconn)
1891         rx_DestroyConnection(fromconn);
1892     if (toconn)
1893         rx_DestroyConnection(toconn);
1894     PrintError("", error);
1895     return error;
1896
1897     /* come here only when the sky falls */
1898   mfail:
1899
1900     if (pntg) {
1901         fprintf(STDOUT,
1902                 "vos move: operation interrupted, cleanup in progress...\n");
1903         fprintf(STDOUT, "clear transaction contexts\n");
1904         fflush(STDOUT);
1905     }
1906
1907     /* unlock VLDB entry */
1908     if (islocked) {
1909         VPRINT1("Recovery: Releasing VLDB lock on volume %u ...", afromvol);
1910         ubik_VL_ReleaseLock(cstruct, 0, afromvol, -1,
1911                   (LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP));
1912         VDONE;
1913         islocked = 0;
1914     }
1915
1916     if (clonetid) {
1917         VPRINT("Recovery: Ending transaction on clone volume ...");
1918         AFSVolEndTrans(fromconn, clonetid, &rcode);
1919         VDONE;
1920     }
1921     if (totid) {
1922         VPRINT("Recovery: Ending transaction on destination volume ...");
1923         AFSVolEndTrans(toconn, totid, &rcode);
1924         VDONE;
1925     }
1926     if (fromtid) {              /* put it on-line */
1927         VPRINT("Recovery: Setting volume flags on source volume ...");
1928         AFSVolSetFlags(fromconn, fromtid, 0);
1929         VDONE;
1930
1931         VPRINT("Recovery: Ending transaction on source volume ...");
1932         AFSVolEndTrans(fromconn, fromtid, &rcode);
1933         VDONE;
1934     }
1935
1936     VPRINT("Recovery: Accessing VLDB.\n");
1937     vcode = VLDB_GetEntryByID(afromvol, -1, &entry);
1938     if (vcode) {
1939         fprintf(STDOUT, "FATAL: VLDB access error: abort cleanup\n");
1940         fflush(STDOUT);
1941         goto done;
1942     }
1943     MapHostToNetwork(&entry);
1944
1945     /* Delete either the volume on the source location or the target location. 
1946      * If the vldb entry still points to the source location, then we know the
1947      * volume move didn't finish so we remove the volume from the target 
1948      * location. Otherwise, we remove the volume from the source location.
1949      */
1950     if (Lp_Match(afromserver, afrompart, &entry)) {     /* didn't move - delete target volume */
1951         if (pntg) {
1952             fprintf(STDOUT,
1953                     "move incomplete - attempt cleanup of target partition - no guarantee\n");
1954             fflush(STDOUT);
1955         }
1956
1957         if (volid && toconn) {
1958             VPRINT1
1959                 ("Recovery: Creating transaction for destination volume %u ...",
1960                  volid);
1961             code =
1962                 AFSVolTransCreate_retry(toconn, volid, atopart, ITOffline, &totid);
1963
1964             if (!code) {
1965                 VDONE;
1966
1967                 VPRINT1
1968                     ("Recovery: Setting flags on destination volume %u ...",
1969                      volid);
1970                 AFSVolSetFlags(toconn, totid,
1971                                VTDeleteOnSalvage | VTOutOfService);
1972                 VDONE;
1973
1974                 VPRINT1("Recovery: Deleting destination volume %u ...",
1975                         volid);
1976                 AFSVolDeleteVolume(toconn, totid);
1977                 VDONE;
1978
1979                 VPRINT1
1980                     ("Recovery: Ending transaction on destination volume %u ...",
1981                      volid);
1982                 AFSVolEndTrans(toconn, totid, &rcode);
1983                 VDONE;
1984             } else {
1985                 VPRINT1
1986                     ("\nRecovery: Unable to start transaction on destination volume %u.\n",
1987                      afromvol);
1988             }
1989         }
1990
1991         /* put source volume on-line */
1992         if (fromconn) {
1993             VPRINT1("Recovery: Creating transaction on source volume %u ...",
1994                     afromvol);
1995             code =
1996                 AFSVolTransCreate_retry(fromconn, afromvol, afrompart, ITBusy,
1997                                   &fromtid);
1998             if (!code) {
1999                 VDONE;
2000
2001                 VPRINT1("Recovery: Setting flags on source volume %u ...",
2002                         afromvol);
2003                 AFSVolSetFlags(fromconn, fromtid, 0);
2004                 VDONE;
2005
2006                 VPRINT1
2007                     ("Recovery: Ending transaction on source volume %u ...",
2008                      afromvol);
2009                 AFSVolEndTrans(fromconn, fromtid, &rcode);
2010                 VDONE;
2011             } else {
2012                 VPRINT1
2013                     ("\nRecovery: Unable to start transaction on source volume %u.\n",
2014                      afromvol);
2015             }
2016         }
2017     } else {                    /* yep, move complete */
2018         if (pntg) {
2019             fprintf(STDOUT,
2020                     "move complete - attempt cleanup of source partition - no guarantee\n");
2021             fflush(STDOUT);
2022         }
2023
2024         /* delete backup volume */
2025         if (fromconn) {
2026             VPRINT1("Recovery: Creating transaction on backup volume %u ...",
2027                     backupId);
2028             code =
2029                 AFSVolTransCreate_retry(fromconn, backupId, afrompart, ITOffline,
2030                                   &fromtid);
2031             if (!code) {
2032                 VDONE;
2033
2034                 VPRINT1("Recovery: Setting flags on backup volume %u ...",
2035                         backupId);
2036                 AFSVolSetFlags(fromconn, fromtid,
2037                                VTDeleteOnSalvage | VTOutOfService);
2038                 VDONE;
2039
2040                 VPRINT1("Recovery: Deleting backup volume %u ...", backupId);
2041                 AFSVolDeleteVolume(fromconn, fromtid);
2042                 VDONE;
2043
2044                 VPRINT1
2045                     ("Recovery: Ending transaction on backup volume %u ...",
2046                      backupId);
2047                 AFSVolEndTrans(fromconn, fromtid, &rcode);
2048                 VDONE;
2049             } else {
2050                 VPRINT1
2051                     ("\nRecovery: Unable to start transaction on backup volume %u.\n",
2052                      backupId);
2053             }
2054
2055             /* delete source volume */
2056             VPRINT1("Recovery: Creating transaction on source volume %u ...",
2057                     afromvol);
2058             code =
2059                 AFSVolTransCreate_retry(fromconn, afromvol, afrompart, ITBusy,
2060                                   &fromtid);
2061             if (!code) {
2062                 VDONE;
2063
2064                 VPRINT1("Recovery: Setting flags on backup volume %u ...",
2065                         afromvol);
2066                 AFSVolSetFlags(fromconn, fromtid,
2067                                VTDeleteOnSalvage | VTOutOfService);
2068                 VDONE;
2069
2070                 if (atoserver != afromserver) {
2071                     VPRINT("Recovery: Setting volume forwarding pointer ...");
2072                     AFSVolSetForwarding(fromconn, fromtid, atoserver);
2073                     VDONE;
2074                 }
2075
2076                 VPRINT1("Recovery: Deleting source volume %u ...", afromvol);
2077                 AFSVolDeleteVolume(fromconn, fromtid);
2078                 VDONE;
2079
2080                 VPRINT1
2081                     ("Recovery: Ending transaction on source volume %u ...",
2082                      afromvol);
2083                 AFSVolEndTrans(fromconn, fromtid, &rcode);
2084                 VDONE;
2085             } else {
2086                 VPRINT1
2087                     ("\nRecovery: Unable to start transaction on source volume %u.\n",
2088                      afromvol);
2089             }
2090         }
2091     }
2092
2093     /* common cleanup - delete local clone */
2094     if (newVol) {
2095         VPRINT1("Recovery: Creating transaction on clone volume %u ...",
2096                 newVol);
2097         code =
2098             AFSVolTransCreate_retry(fromconn, newVol, afrompart, ITOffline,
2099                               &clonetid);
2100         if (!code) {
2101             VDONE;
2102
2103             VPRINT1("Recovery: Deleting clone volume %u ...", newVol);
2104             AFSVolDeleteVolume(fromconn, clonetid);
2105             VDONE;
2106
2107             VPRINT1("Recovery: Ending transaction on clone volume %u ...",
2108                     newVol);
2109             AFSVolEndTrans(fromconn, clonetid, &rcode);
2110             VDONE;
2111         } else {
2112             VPRINT1
2113                 ("\nRecovery: Unable to start transaction on source volume %u.\n",
2114                  afromvol);
2115         }
2116     }
2117
2118     /* unlock VLDB entry */
2119     if (islocked) {
2120         VPRINT1("Recovery: Releasing lock on VLDB entry for volume %u ...",
2121                 afromvol);
2122         ubik_VL_ReleaseLock(cstruct, 0, afromvol, -1,
2123                             (LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP));
2124         VDONE;
2125         islocked = 0;
2126     }
2127   done:                 /* routine cleanup */
2128     if (volName)
2129         free(volName);
2130 #ifdef  ENABLE_BUGFIX_1165
2131     if (infop)
2132         free(infop);
2133 #endif
2134     if (fromconn)
2135         rx_DestroyConnection(fromconn);
2136     if (toconn)
2137         rx_DestroyConnection(toconn);
2138
2139     if (pntg) {
2140         fprintf(STDOUT, "cleanup complete - user verify desired result\n");
2141         fflush(STDOUT);
2142     }
2143     exit(1);
2144 }
2145
2146
2147 int
2148 UV_MoveVolume(afs_uint32 afromvol, afs_int32 afromserver, afs_int32 afrompart,
2149               afs_int32 atoserver, afs_int32 atopart)
2150 {
2151     return UV_MoveVolume2(afromvol, afromserver, afrompart,
2152                           atoserver, atopart, 0);
2153 }
2154
2155
2156 /* Copy volume <afromvol> from <afromserver> <afrompart> to <atoserver>
2157  * <atopart>.  The new volume is named by <atovolname>.  The new volume
2158  * has ID <atovolid> if that is nonzero; otherwise a new ID is allocated
2159  * from the VLDB.  the following flags are supported:
2160  * 
2161  *     RV_RDONLY  - target volume is RO
2162  *     RV_OFFLINE - leave target volume offline
2163  *     RV_CPINCR  - do incremental dump if target exists
2164  *     RV_NOVLDB  - don't create/update VLDB entry
2165  *     RV_NOCLONE - don't use a copy clone
2166  */
2167 int
2168 UV_CopyVolume2(afs_uint32 afromvol, afs_int32 afromserver, afs_int32 afrompart,
2169                char *atovolname, afs_int32 atoserver, afs_int32 atopart,
2170                afs_uint32 atovolid, int flags)
2171 {
2172     struct rx_connection *toconn, *fromconn;
2173     afs_int32 fromtid, totid, clonetid;
2174     char vname[64];
2175     afs_int32 rcode;
2176     afs_int32 fromDate, cloneFromDate;
2177     struct restoreCookie cookie;
2178     register afs_int32 vcode, code;
2179     afs_uint32 cloneVol, newVol;
2180     afs_int32 volflag;
2181     struct volser_status tstatus;
2182     struct destServer destination;
2183
2184     struct nvldbentry entry, newentry, storeEntry;
2185     int islocked, pntg;
2186     afs_int32 error;
2187     int justclone = 0;
2188
2189     islocked = 0;
2190     fromconn = (struct rx_connection *)0;
2191     toconn = (struct rx_connection *)0;
2192     fromtid = 0;
2193     totid = 0;
2194     clonetid = 0;
2195     error = 0;
2196     pntg = 0;
2197     newVol = 0;
2198
2199     /* support control-c processing */
2200     if (setjmp(env))
2201         goto mfail;
2202     (void)signal(SIGINT, sigint_handler);
2203
2204     vcode = VLDB_GetEntryByID(afromvol, -1, &entry);
2205     EGOTO1(mfail, vcode,
2206            "Could not fetch the entry for the volume  %u from the VLDB \n",
2207            afromvol);
2208     MapHostToNetwork(&entry);
2209
2210     pntg = 1;
2211     toconn = UV_Bind(atoserver, AFSCONF_VOLUMEPORT);    /* get connections to the servers */
2212     fromconn = UV_Bind(afromserver, AFSCONF_VOLUMEPORT);
2213     fromtid = totid = 0;        /* initialize to uncreated */
2214
2215
2216     /* check if we can shortcut and use a local clone instead of a full copy */
2217     if (afromserver == atoserver && afrompart == atopart) {
2218         justclone = 1;
2219     }
2220
2221     /* ***
2222      * clone the read/write volume locally.
2223      * ***/
2224
2225     cloneVol = 0;
2226     if (!(flags & RV_NOCLONE)) {
2227         VPRINT1("Starting transaction on source volume %u ...", afromvol);
2228         code = AFSVolTransCreate_retry(fromconn, afromvol, afrompart, ITBusy,
2229                                  &fromtid);
2230         EGOTO1(mfail, code, "Failed to create transaction on the volume %u\n",
2231                afromvol);
2232         VDONE;
2233
2234         /* Get a clone id */
2235         VPRINT1("Allocating new volume id for clone of volume %u ...",
2236                 afromvol);
2237         cloneVol = 0;
2238         vcode = ubik_VL_GetNewVolumeId(cstruct, 0, 1, &cloneVol);
2239         EGOTO1(mfail, vcode,
2240            "Could not get an ID for the clone of volume %u from the VLDB\n",
2241            afromvol);
2242         VDONE;
2243     }
2244
2245     if (atovolid) {
2246         newVol = atovolid;
2247     } else {
2248         /* Get a new volume id */
2249         VPRINT1("Allocating new volume id for copy of volume %u ...", afromvol);
2250         newVol = 0;
2251         vcode = ubik_VL_GetNewVolumeId(cstruct, 0, 1, &newVol);
2252         EGOTO1(mfail, vcode,
2253                "Could not get an ID for the copy of volume %u from the VLDB\n",
2254                afromvol);
2255         VDONE;
2256     }
2257
2258     if (!(flags & RV_NOCLONE)) {
2259         /* Do the clone. Default flags on clone are set to delete on salvage and out of service */
2260         VPRINT1("Cloning source volume %u ...", afromvol);
2261         strcpy(vname, "copy-clone-temp");
2262         code =
2263             AFSVolClone(fromconn, fromtid, 0, readonlyVolume, vname,
2264                         &cloneVol);
2265         EGOTO1(mfail, code, "Failed to clone the source volume %u\n",
2266                afromvol);
2267         VDONE;
2268
2269         VPRINT1("Ending the transaction on the source volume %u ...", afromvol);
2270         rcode = 0;
2271         code = AFSVolEndTrans(fromconn, fromtid, &rcode);
2272         fromtid = 0;
2273         if (!code)
2274             code = rcode;
2275         EGOTO1(mfail, code,
2276                "Failed to end the transaction on the source volume %u\n",
2277                afromvol);
2278         VDONE;
2279     }
2280
2281     /* ***
2282      * Create the destination volume
2283      * ***/
2284
2285     if (!(flags & RV_NOCLONE)) {
2286         VPRINT1("Starting transaction on the cloned volume %u ...", cloneVol);
2287         code =
2288             AFSVolTransCreate_retry(fromconn, cloneVol, afrompart, ITOffline,
2289                           &clonetid);
2290         EGOTO1(mfail, code,
2291                "Failed to start a transaction on the cloned volume%u\n",
2292                cloneVol);
2293         VDONE;
2294
2295         VPRINT1("Setting flags on cloned volume %u ...", cloneVol);
2296         code =
2297             AFSVolSetFlags(fromconn, clonetid,
2298                            VTDeleteOnSalvage | VTOutOfService); /*redundant */
2299         EGOTO1(mfail, code, "Could not set flags on the cloned volume %u\n",
2300                cloneVol);
2301         VDONE;
2302
2303         /* remember time from which we've dumped the volume */
2304         VPRINT1("Getting status of cloned volume %u ...", cloneVol);
2305         code = AFSVolGetStatus(fromconn, clonetid, &tstatus);
2306         EGOTO1(mfail, code,
2307                "Failed to get the status of the cloned volume %u\n",
2308                cloneVol);
2309         VDONE;
2310
2311         fromDate = CLOCKADJ(tstatus.creationDate);
2312     } else {
2313         fromDate = 0;
2314     }
2315
2316     /* create a volume on the target machine */
2317     cloneFromDate = 0;
2318     code = AFSVolTransCreate_retry(toconn, newVol, atopart, ITOffline, &totid);
2319     if (!code) {
2320         if ((flags & RV_CPINCR)) {
2321             VPRINT1("Getting status of pre-existing volume %u ...", newVol);
2322             code = AFSVolGetStatus(toconn, totid, &tstatus);
2323             EGOTO1(mfail, code,
2324                    "Failed to get the status of the pre-existing volume %u\n",
2325                    newVol);
2326             VDONE;
2327
2328             /* Using the update date should be OK here, but add some fudge */
2329             cloneFromDate = CLOCKADJ(tstatus.updateDate);
2330             if ((flags & RV_NOCLONE))
2331                 fromDate = cloneFromDate;
2332
2333             /* XXX We should check that the source volume's creationDate is
2334              * XXX not newer than the existing target volume, and if not,
2335              * XXX throw away the existing target and do a full dump. */
2336
2337             goto cpincr;
2338         }
2339
2340         /* Delete the existing volume.
2341          * While we are deleting the volume in these steps, the transaction
2342          * we started against the cloned volume (clonetid above) will be
2343          * sitting idle. It will get cleaned up after 600 seconds
2344          */
2345         VPRINT1("Deleting pre-existing volume %u on destination ...", newVol);
2346         code = AFSVolDeleteVolume(toconn, totid);
2347         EGOTO1(mfail, code,
2348                "Could not delete the pre-existing volume %u on destination\n",
2349                newVol);
2350         VDONE;
2351
2352         VPRINT1
2353             ("Ending transaction on pre-existing volume %u on destination ...",
2354              newVol);
2355         code = AFSVolEndTrans(toconn, totid, &rcode);
2356         totid = 0;
2357         if (!code)
2358             code = rcode;
2359         EGOTO1(mfail, code,
2360                "Could not end the transaction on pre-existing volume %u on destination\n",
2361                newVol);
2362         VDONE;
2363     }
2364
2365     VPRINT1("Creating the destination volume %u ...", newVol);
2366     code =
2367         AFSVolCreateVolume(toconn, atopart, atovolname,
2368                            (flags & RV_RDONLY) ? volser_RO : volser_RW,
2369                            newVol, &newVol, &totid);
2370     EGOTO1(mfail, code, "Failed to create the destination volume %u\n",
2371            newVol);
2372     VDONE;
2373
2374     VPRINT1("Setting volume flags on destination volume %u ...", newVol);
2375     code =
2376         AFSVolSetFlags(toconn, totid, (VTDeleteOnSalvage | VTOutOfService));
2377     EGOTO1(mfail, code,
2378            "Failed to set the flags on the destination volume %u\n", newVol);
2379     VDONE;
2380
2381 cpincr:
2382
2383     destination.destHost = ntohl(atoserver);
2384     destination.destPort = AFSCONF_VOLUMEPORT;
2385     destination.destSSID = 1;
2386
2387     strncpy(cookie.name, atovolname, VOLSER_OLDMAXVOLNAME);
2388     cookie.type = (flags & RV_RDONLY) ? ROVOL : RWVOL;
2389     cookie.parent = 0;
2390     cookie.clone = 0;
2391
2392     /***
2393      * Now dump the clone to the new volume
2394      ***/
2395
2396     if (!(flags & RV_NOCLONE)) {
2397         /* XXX probably should have some code here that checks to see if
2398          * XXX we are copying to same server and partition - if so, just
2399          * XXX use a clone to save disk space */
2400
2401         /* Copy the clone to the new volume */
2402         VPRINT2("Dumping from clone %u on source to volume %u on destination ...",
2403             cloneVol, newVol);
2404         code =
2405             AFSVolForward(fromconn, clonetid, cloneFromDate, &destination,
2406                           totid, &cookie);
2407         EGOTO1(mfail, code, "Failed to move data for the volume %u\n",
2408                newVol);
2409         VDONE;
2410
2411         VPRINT1("Ending transaction on cloned volume %u ...", cloneVol);
2412         code = AFSVolEndTrans(fromconn, clonetid, &rcode);
2413         if (!code)
2414             code = rcode;
2415         clonetid = 0;
2416         EGOTO1(mfail, code,
2417                "Failed to end the transaction on the cloned volume %u\n",
2418                cloneVol);
2419         VDONE;
2420     }
2421
2422     /* ***
2423      * reattach to the main-line volume, and incrementally dump it.
2424      * ***/
2425
2426     VPRINT1("Starting transaction on source volume %u ...", afromvol);
2427     code = AFSVolTransCreate_retry(fromconn, afromvol, afrompart, ITBusy, &fromtid);
2428     EGOTO1(mfail, code,
2429            "Failed to create a transaction on the source volume %u\n",
2430            afromvol);
2431     VDONE;
2432
2433     /* now do the incremental */
2434     VPRINT2
2435         ("Doing the%s dump from source to destination for volume %u ... ",
2436          (flags & RV_NOCLONE) ? "" : " incremental",
2437          afromvol);
2438     code =
2439         AFSVolForward(fromconn, fromtid, fromDate, &destination, totid,
2440                       &cookie);
2441     EGOTO1(mfail, code,
2442            "Failed to do the%s dump from old site to new site\n",
2443            (flags & RV_NOCLONE) ? "" : " incremental");
2444     VDONE;
2445
2446     VPRINT1("Setting volume flags on destination volume %u ...", newVol);
2447     volflag = ((flags & RV_OFFLINE) ? VTOutOfService : 0);      /* off or on-line */
2448     code = AFSVolSetFlags(toconn, totid, volflag);
2449     EGOTO(mfail, code,
2450           "Failed to set the flags to make destination volume online\n");
2451     VDONE;
2452
2453     /* put new volume online */
2454     VPRINT1("Ending transaction on destination volume %u ...", newVol);
2455     code = AFSVolEndTrans(toconn, totid, &rcode);
2456     totid = 0;
2457     if (!code)
2458         code = rcode;
2459     EGOTO1(mfail, code,
2460            "Failed to end the transaction on the destination volume %u\n",
2461            newVol);
2462     VDONE;
2463
2464     VPRINT1("Ending transaction on source volume %u ...", afromvol);
2465     code = AFSVolEndTrans(fromconn, fromtid, &rcode);
2466     fromtid = 0;
2467     if (!code)
2468         code = rcode;
2469     EGOTO1(mfail, code,
2470            "Failed to end the transaction on the source volume %u\n",
2471            afromvol);
2472     VDONE;
2473
2474     fromtid = 0;
2475
2476     if (!(flags & RV_NOCLONE)) {
2477         VPRINT1("Starting transaction on the cloned volume %u ...", cloneVol);
2478         code =
2479             AFSVolTransCreate_retry(fromconn, cloneVol, afrompart, ITOffline,
2480                               &clonetid);
2481         EGOTO1(mfail, code,
2482                "Failed to start a transaction on the cloned volume%u\n",
2483                cloneVol);
2484         VDONE;
2485
2486         /* now delete the clone */
2487         VPRINT1("Deleting the cloned volume %u ...", cloneVol);
2488         code = AFSVolDeleteVolume(fromconn, clonetid);
2489         EGOTO1(mfail, code, "Failed to delete the cloned volume %u\n",
2490                cloneVol);
2491         VDONE;
2492
2493         VPRINT1("Ending transaction on cloned volume %u ...", cloneVol);
2494         code = AFSVolEndTrans(fromconn, clonetid, &rcode);
2495         if (!code)
2496             code = rcode;
2497         clonetid = 0;
2498         EGOTO1(mfail, code,
2499                "Failed to end the transaction on the cloned volume %u\n",
2500                cloneVol);
2501         VDONE;
2502     }
2503
2504     if (!(flags & RV_NOVLDB)) {
2505         /* create the vldb entry for the copied volume */
2506         strncpy(newentry.name, atovolname, VOLSER_OLDMAXVOLNAME);
2507         newentry.nServers = 1;
2508         newentry.serverNumber[0] = atoserver;
2509         newentry.serverPartition[0] = atopart;
2510         newentry.flags = (flags & RV_RDONLY) ? RO_EXISTS : RW_EXISTS;
2511         newentry.serverFlags[0] = (flags & RV_RDONLY) ? ITSROVOL : ITSRWVOL;
2512         newentry.volumeId[RWVOL] = newVol;
2513         newentry.volumeId[ROVOL] = (flags & RV_RDONLY) ? newVol : 0;
2514         newentry.volumeId[BACKVOL] = 0;
2515         newentry.cloneId = 0;
2516         /*map into right byte order, before passing to xdr, the stuff has to be in host
2517          * byte order. Xdr converts it into network order */
2518         MapNetworkToHost(&newentry, &storeEntry);
2519         /* create the vldb entry */
2520         vcode = VLDB_CreateEntry(&storeEntry);
2521         if (vcode) {
2522             fprintf(STDERR,
2523                     "Could not create a VLDB entry for the volume %s %lu\n",
2524                     atovolname, (unsigned long)newVol);
2525             /*destroy the created volume */
2526             VPRINT1("Deleting the newly created volume %u\n", newVol);
2527             AFSVolDeleteVolume(toconn, totid);
2528             error = vcode;
2529             goto mfail;
2530         }
2531         VPRINT2("Created the VLDB entry for the volume %s %u\n", atovolname,
2532                 newVol);
2533     }
2534
2535     /* normal cleanup code */
2536
2537     if (fromtid) {
2538         VPRINT1("Cleanup: Ending transaction on source volume %u ...",
2539                 afromvol);
2540         code = AFSVolEndTrans(fromconn, fromtid, &rcode);
2541         if (code || rcode) {
2542             VPRINT("\n");
2543             fprintf(STDERR,
2544                     "Could not end transaction on the source volume %lu\n",
2545                     (unsigned long)afromvol);
2546             if (!error)
2547                 error = (code ? code : rcode);
2548         }
2549         VDONE;
2550     }
2551
2552     if (clonetid) {
2553         VPRINT1("Cleanup: Ending transaction on clone volume %u ...",
2554                 cloneVol);
2555         code = AFSVolEndTrans(fromconn, clonetid, &rcode);
2556         if (code || rcode) {
2557             VPRINT("\n");
2558             fprintf(STDERR,
2559                     "Could not end transaction on the source's clone volume %lu\n",
2560                     (unsigned long)cloneVol);
2561             if (!error)
2562                 error = (code ? code : rcode);
2563         }
2564         VDONE;
2565     }
2566
2567     if (totid) {
2568         VPRINT1("Cleanup: Ending transaction on destination volume %u ...",
2569                 newVol);
2570         code = AFSVolEndTrans(toconn, totid, &rcode);
2571         if (code) {
2572             VPRINT("\n");
2573             fprintf(STDERR,
2574                     "Could not end transaction on destination volume %lu\n",
2575                     (unsigned long)newVol);
2576             if (!error)
2577                 error = (code ? code : rcode);
2578         }
2579         VDONE;
2580     }
2581     if (fromconn)
2582         rx_DestroyConnection(fromconn);
2583     if (toconn)
2584         rx_DestroyConnection(toconn);
2585     PrintError("", error);
2586     return error;
2587
2588     /* come here only when the sky falls */
2589   mfail:
2590
2591     if (pntg) {
2592         fprintf(STDOUT,
2593                 "vos copy: operation interrupted, cleanup in progress...\n");
2594         fprintf(STDOUT, "clear transaction contexts\n");
2595         fflush(STDOUT);
2596     }
2597
2598     if (clonetid) {
2599         VPRINT("Recovery: Ending transaction on clone volume ...");
2600         AFSVolEndTrans(fromconn, clonetid, &rcode);
2601         VDONE;
2602     }
2603     if (totid) {
2604         VPRINT("Recovery: Ending transaction on destination volume ...");
2605         AFSVolEndTrans(toconn, totid, &rcode);
2606         VDONE;
2607     }
2608     if (fromtid) {              /* put it on-line */
2609         VPRINT("Recovery: Ending transaction on source volume ...");
2610         AFSVolEndTrans(fromconn, fromtid, &rcode);
2611         VDONE;
2612     }
2613
2614     VPRINT("Recovery: Accessing VLDB.\n");
2615     vcode = VLDB_GetEntryByID(afromvol, -1, &entry);
2616     if (vcode) {
2617         fprintf(STDOUT, "FATAL: VLDB access error: abort cleanup\n");
2618         fflush(STDOUT);
2619         goto done;
2620     }
2621     MapHostToNetwork(&entry);
2622
2623     /* common cleanup - delete local clone */
2624     if (cloneVol) {
2625         VPRINT1("Recovery: Creating transaction on clone volume %u ...",
2626                 cloneVol);
2627         code =
2628             AFSVolTransCreate_retry(fromconn, cloneVol, afrompart, ITOffline,
2629                               &clonetid);
2630         if (!code) {
2631             VDONE;
2632
2633             VPRINT1("Recovery: Deleting clone volume %u ...", cloneVol);
2634             AFSVolDeleteVolume(fromconn, clonetid);
2635             VDONE;
2636
2637             VPRINT1("Recovery: Ending transaction on clone volume %u ...",
2638                     cloneVol);
2639             AFSVolEndTrans(fromconn, clonetid, &rcode);
2640             VDONE;
2641         } else {
2642             VPRINT1
2643                 ("\nRecovery: Unable to start transaction on clone volume %u.\n",
2644                  cloneVol);
2645         }
2646     }
2647
2648   done:                 /* routine cleanup */
2649     if (fromconn)
2650         rx_DestroyConnection(fromconn);
2651     if (toconn)
2652         rx_DestroyConnection(toconn);
2653
2654     if (pntg) {
2655         fprintf(STDOUT, "cleanup complete - user verify desired result\n");
2656         fflush(STDOUT);
2657     }
2658     exit(1);
2659 }
2660
2661
2662 int
2663 UV_CopyVolume(afs_uint32 afromvol, afs_int32 afromserver, afs_int32 afrompart,
2664               char *atovolname, afs_int32 atoserver, afs_int32 atopart)
2665 {
2666     return UV_CopyVolume2(afromvol, afromserver, afrompart,
2667                           atovolname, atoserver, atopart, 0, 0);
2668 }
2669
2670
2671
2672 /* Make a new backup of volume <avolid> on <aserver> and <apart> 
2673  * if one already exists, update it 
2674  */
2675
2676 int
2677 UV_BackupVolume(afs_int32 aserver, afs_int32 apart, afs_uint32 avolid)
2678 {
2679     struct rx_connection *aconn = (struct rx_connection *)0;
2680     afs_int32 ttid = 0, btid = 0;
2681     afs_uint32 backupID;
2682     afs_int32 code = 0, rcode = 0;
2683     char vname[VOLSER_MAXVOLNAME + 1];
2684     struct nvldbentry entry, storeEntry;
2685     afs_int32 error = 0;
2686     int vldblocked = 0, vldbmod = 0, backexists = 1;
2687
2688     aconn = UV_Bind(aserver, AFSCONF_VOLUMEPORT);
2689
2690     /* the calls to VLDB will succeed only if avolid is a RW volume,
2691      * since we are following the RW hash chain for searching */
2692     code = VLDB_GetEntryByID(avolid, RWVOL, &entry);
2693     if (code) {
2694         fprintf(STDERR,
2695                 "Could not fetch the entry for the volume %lu from the VLDB \n",
2696                 (unsigned long)avolid);
2697         error = code;
2698         goto bfail;
2699     }
2700     MapHostToNetwork(&entry);
2701
2702     /* These operations require the VLDB be locked since it means the VLDB
2703      * will change or the vldb is already locked.
2704      */
2705     if (!(entry.flags & BACK_EXISTS) || /* backup volume doesnt exist */
2706         (entry.flags & VLOP_ALLOPERS) ||        /* vldb lock already held */
2707         (entry.volumeId[BACKVOL] == INVALID_BID)) {     /* no assigned backup volume id */
2708
2709         code = ubik_VL_SetLock(cstruct, 0, avolid, RWVOL, VLOP_BACKUP);
2710         if (code) {
2711             fprintf(STDERR,
2712                     "Could not lock the VLDB entry for the volume %lu\n",
2713                     (unsigned long)avolid);
2714             error = code;
2715             goto bfail;
2716         }
2717         vldblocked = 1;
2718
2719         /* Reread the vldb entry */
2720         code = VLDB_GetEntryByID(avolid, RWVOL, &entry);
2721         if (code) {
2722             fprintf(STDERR,
2723                     "Could not fetch the entry for the volume %lu from the VLDB \n",
2724                     (unsigned long)avolid);
2725             error = code;
2726             goto bfail;
2727         }
2728         MapHostToNetwork(&entry);
2729     }
2730
2731     if (!ISNAMEVALID(entry.name)) {
2732         fprintf(STDERR, "Name of the volume %s exceeds the size limit\n",
2733                 entry.name);
2734         error = VOLSERBADNAME;
2735         goto bfail;
2736     }
2737
2738     backupID = entry.volumeId[BACKVOL];
2739     if (backupID == INVALID_BID) {
2740         /* Get a backup volume id from the VLDB and update the vldb
2741          * entry with it. 
2742          */
2743         code = ubik_VL_GetNewVolumeId(cstruct, 0, 1, &backupID);
2744         if (code) {
2745             fprintf(STDERR,
2746                     "Could not allocate ID for the backup volume of  %lu from the VLDB\n",
2747                     (unsigned long)avolid);
2748             error = code;
2749             goto bfail;
2750         }
2751         entry.volumeId[BACKVOL] = backupID;
2752         vldbmod = 1;
2753     }
2754
2755     /* Test to see if the backup volume exists by trying to create
2756      * a transaction on the backup volume. We've assumed the backup exists.
2757      */
2758     code = AFSVolTransCreate_retry(aconn, backupID, apart, ITOffline, &btid);
2759     if (code) {
2760         if (code != VNOVOL) {
2761             fprintf(STDERR, "Could not reach the backup volume %lu\n",
2762                     (unsigned long)backupID);
2763             error = code;
2764             goto bfail;
2765         }
2766         backexists = 0;         /* backup volume does not exist */
2767     }
2768     if (btid) {
2769         code = AFSVolEndTrans(aconn, btid, &rcode);
2770         btid = 0;
2771         if (code || rcode) {
2772             fprintf(STDERR,
2773                     "Could not end transaction on the previous backup volume %lu\n",
2774                     (unsigned long)backupID);
2775             error = (code ? code : rcode);
2776             goto bfail;
2777         }
2778     }
2779
2780     /* Now go ahead and try to clone the RW volume.
2781      * First start a transaction on the RW volume 
2782      */
2783     code = AFSVolTransCreate_retry(aconn, avolid, apart, ITBusy, &ttid);
2784     if (code) {
2785         fprintf(STDERR, "Could not start a transaction on the volume %lu\n",
2786                 (unsigned long)avolid);
2787         error = code;
2788         goto bfail;
2789     }
2790
2791     /* Clone or reclone the volume, depending on whether the backup 
2792      * volume exists or not
2793      */
2794     if (backexists) {
2795         VPRINT1("Re-cloning backup volume %u ...", backupID);
2796
2797         code = AFSVolReClone(aconn, ttid, backupID);
2798         if (code) {
2799             fprintf(STDERR, "Could not re-clone backup volume %lu\n",
2800                     (unsigned long)backupID);
2801             error = code;
2802             goto bfail;
2803         }
2804     } else {
2805         VPRINT1("Creating a new backup clone %u ...", backupID);
2806
2807         strcpy(vname, entry.name);
2808         strcat(vname, ".backup");
2809
2810         code = AFSVolClone(aconn, ttid, 0, backupVolume, vname, &backupID);
2811         if (code) {
2812             fprintf(STDERR, "Failed to clone the volume %lu\n",
2813                     (unsigned long)avolid);
2814             error = code;
2815             goto bfail;
2816         }
2817     }
2818
2819     /* End the transaction on the RW volume */
2820     code = AFSVolEndTrans(aconn, ttid, &rcode);
2821     ttid = 0;
2822     if (code || rcode) {
2823         fprintf(STDERR,
2824                 "Failed to end the transaction on the rw volume %lu\n",
2825                 (unsigned long)avolid);
2826         error = (code ? code : rcode);
2827         goto bfail;
2828     }
2829
2830     /* Mork vldb as backup exists */
2831     if (!(entry.flags & BACK_EXISTS)) {
2832         entry.flags |= BACK_EXISTS;
2833         vldbmod = 1;
2834     }
2835
2836     /* Now go back to the backup volume and bring it on line */
2837     code = AFSVolTransCreate_retry(aconn, backupID, apart, ITOffline, &btid);
2838     if (code) {
2839         fprintf(STDERR,
2840                 "Failed to start a transaction on the backup volume %lu\n",
2841                 (unsigned long)backupID);
2842         error = code;
2843         goto bfail;
2844     }
2845
2846     code = AFSVolSetFlags(aconn, btid, 0);
2847     if (code) {
2848         fprintf(STDERR, "Could not mark the backup volume %lu on line \n",
2849                 (unsigned long)backupID);
2850         error = code;
2851         goto bfail;
2852     }
2853
2854     code = AFSVolEndTrans(aconn, btid, &rcode);
2855     btid = 0;
2856     if (code || rcode) {
2857         fprintf(STDERR,
2858                 "Failed to end the transaction on the backup volume %lu\n",
2859                 (unsigned long)backupID);
2860         error = (code ? code : rcode);
2861         goto bfail;
2862     }
2863
2864     VDONE;
2865
2866     /* Will update the vldb below */
2867
2868   bfail:
2869     if (ttid) {
2870         code = AFSVolEndTrans(aconn, ttid, &rcode);
2871         if (code || rcode) {
2872             fprintf(STDERR, "Could not end transaction on the volume %lu\n",
2873                     (unsigned long)avolid);
2874             if (!error)
2875                 error = (code ? code : rcode);
2876         }
2877     }
2878
2879     if (btid) {
2880         code = AFSVolEndTrans(aconn, btid, &rcode);
2881         if (code || rcode) {
2882             fprintf(STDERR,
2883                     "Could not end transaction the backup volume %lu\n",
2884                     (unsigned long)backupID);
2885             if (!error)
2886                 error = (code ? code : rcode);
2887         }
2888     }
2889
2890     /* Now update the vldb - if modified */
2891     if (vldblocked) {
2892         if (vldbmod) {
2893             MapNetworkToHost(&entry, &storeEntry);
2894             code =
2895                 VLDB_ReplaceEntry(avolid, RWVOL, &storeEntry,
2896                                   (LOCKREL_OPCODE | LOCKREL_AFSID |
2897                                    LOCKREL_TIMESTAMP));
2898             if (code) {
2899                 fprintf(STDERR,
2900                         "Could not update the VLDB entry for the volume %lu \n",
2901                         (unsigned long)avolid);
2902                 if (!error)
2903                     error = code;
2904             }
2905         } else {
2906             code =
2907                 ubik_VL_ReleaseLock(cstruct, 0, avolid, RWVOL,
2908                           (LOCKREL_OPCODE | LOCKREL_AFSID |
2909                            LOCKREL_TIMESTAMP));
2910             if (code) {
2911                 fprintf(STDERR,
2912                         "Could not unlock the VLDB entry for the volume %lu \n",
2913                         (unsigned long)avolid);
2914                 if (!error)
2915                     error = code;
2916             }
2917         }
2918     }
2919
2920     if (aconn)
2921         rx_DestroyConnection(aconn);
2922
2923     PrintError("", error);
2924     return error;
2925 }
2926
2927 /* Make a new clone of volume <avolid> on <aserver> and <apart> 
2928  * using volume ID <acloneid>, or a new ID allocated from the VLDB.
2929  * The new volume is named by <aname>, or by appending ".clone" to
2930  * the existing name if <aname> is NULL.  The following flags are
2931  * supported:
2932  * 
2933  *     RV_RDONLY  - target volume is RO
2934  *     RV_OFFLINE - leave target volume offline
2935  */
2936
2937 int
2938 UV_CloneVolume(afs_int32 aserver, afs_int32 apart, afs_uint32 avolid,
2939                afs_uint32 acloneid, char *aname, int flags)
2940 {
2941     struct rx_connection *aconn = (struct rx_connection *)0;
2942     afs_int32 ttid = 0, btid = 0;
2943     afs_int32 code = 0, rcode = 0;
2944     char vname[VOLSER_MAXVOLNAME + 1];
2945     afs_int32 error = 0;
2946     int backexists = 1;
2947     volEntries volumeInfo;
2948
2949     aconn = UV_Bind(aserver, AFSCONF_VOLUMEPORT);
2950
2951     if (!aname) {
2952         volumeInfo.volEntries_val = (volintInfo *) 0;
2953         volumeInfo.volEntries_len = 0;
2954         code = AFSVolListOneVolume(aconn, apart, avolid, &volumeInfo);
2955         if (code) {
2956             fprintf(stderr, "Could not get info for volume %lu\n",
2957                     (unsigned long)avolid);
2958             error = code;
2959             goto bfail;
2960         }
2961         strncpy(vname, volumeInfo.volEntries_val[0].name,
2962                 VOLSER_OLDMAXVOLNAME - 7);
2963         vname[VOLSER_OLDMAXVOLNAME - 7] = 0;
2964         strcat(vname, ".clone");
2965         aname = vname;
2966         if (volumeInfo.volEntries_val)
2967             free(volumeInfo.volEntries_val);
2968     }
2969
2970     if (!acloneid) {
2971         /* Get a clone id */
2972         VPRINT1("Allocating new volume id for clone of volume %u ...",
2973                 avolid);
2974         code = ubik_VL_GetNewVolumeId(cstruct, 0, 1, &acloneid);
2975         EGOTO1(bfail, code,
2976            "Could not get an ID for the clone of volume %u from the VLDB\n",
2977            avolid);
2978         VDONE;
2979     }
2980
2981     /* Test to see if the clone volume exists by trying to create
2982      * a transaction on the clone volume. We've assumed the clone exists.
2983      */
2984     /* XXX I wonder what happens if the clone has some other parent... */
2985     code = AFSVolTransCreate_retry(aconn, acloneid, apart, ITOffline, &btid);
2986     if (code) {
2987         if (code != VNOVOL) {
2988             fprintf(STDERR, "Could not reach the clone volume %lu\n",
2989                     (unsigned long)acloneid);
2990             error = code;
2991             goto bfail;
2992         }
2993         backexists = 0;         /* backup volume does not exist */
2994     }
2995     if (btid) {
2996         code = AFSVolEndTrans(aconn, btid, &rcode);
2997         btid = 0;
2998         if (code || rcode) {
2999             fprintf(STDERR,
3000                     "Could not end transaction on the previous clone volume %lu\n",
3001                     (unsigned long)acloneid);
3002             error = (code ? code : rcode);
3003             goto bfail;
3004         }
3005     }
3006
3007     /* Now go ahead and try to clone the RW volume.
3008      * First start a transaction on the RW volume 
3009      */
3010     code = AFSVolTransCreate_retry(aconn, avolid, apart, ITBusy, &ttid);
3011     if (code) {
3012         fprintf(STDERR, "Could not start a transaction on the volume %lu\n",
3013                 (unsigned long)avolid);
3014         error = code;
3015         goto bfail;
3016     }
3017
3018     /* Clone or reclone the volume, depending on whether the backup 
3019      * volume exists or not
3020      */
3021     if (backexists) {
3022         VPRINT1("Re-cloning clone volume %u ...", acloneid);
3023
3024         code = AFSVolReClone(aconn, ttid, acloneid);
3025         if (code) {
3026             fprintf(STDERR, "Could not re-clone backup volume %lu\n",
3027                     (unsigned long)acloneid);
3028             error = code;
3029             goto bfail;
3030         }
3031     } else {
3032         VPRINT1("Creating a new clone %u ...", acloneid);
3033
3034         code = AFSVolClone(aconn, ttid, 0,
3035                            (flags & RV_RDONLY) ? readonlyVolume : backupVolume,
3036                            aname, &acloneid);
3037         if (code) {
3038             fprintf(STDERR, "Failed to clone the volume %lu\n",
3039                     (unsigned long)avolid);
3040             error = code;
3041             goto bfail;
3042         }
3043     }
3044
3045     /* End the transaction on the RW volume */
3046     code = AFSVolEndTrans(aconn, ttid, &rcode);
3047     ttid = 0;
3048     if (code || rcode) {
3049         fprintf(STDERR,
3050                 "Failed to end the transaction on the rw volume %lu\n",
3051                 (unsigned long)avolid);
3052         error = (code ? code : rcode);
3053         goto bfail;
3054     }
3055
3056     /* Now go back to the backup volume and bring it on line */
3057     if (!(flags & RV_OFFLINE)) {
3058         code = AFSVolTransCreate_retry(aconn, acloneid, apart, ITOffline, &btid);
3059         if (code) {
3060             fprintf(STDERR,
3061                     "Failed to start a transaction on the clone volume %lu\n",
3062                     (unsigned long)acloneid);
3063             error = code;
3064             goto bfail;
3065         }
3066
3067         code = AFSVolSetFlags(aconn, btid, 0);
3068         if (code) {
3069             fprintf(STDERR, "Could not mark the clone volume %lu on line \n",
3070                     (unsigned long)acloneid);
3071             error = code;
3072             goto bfail;
3073         }
3074
3075         code = AFSVolEndTrans(aconn, btid, &rcode);
3076         btid = 0;
3077         if (code || rcode) {
3078             fprintf(STDERR,
3079                     "Failed to end the transaction on the clone volume %lu\n",
3080                     (unsigned long)acloneid);
3081             error = (code ? code : rcode);
3082             goto bfail;
3083         }
3084     }
3085
3086     VDONE;
3087
3088   bfail:
3089     if (ttid) {
3090         code = AFSVolEndTrans(aconn, ttid, &rcode);
3091         if (code || rcode) {
3092             fprintf(STDERR, "Could not end transaction on the volume %lu\n",
3093                     (unsigned long)avolid);
3094             if (!error)
3095                 error = (code ? code : rcode);
3096         }
3097     }
3098
3099     if (btid) {
3100         code = AFSVolEndTrans(aconn, btid, &rcode);
3101         if (code || rcode) {
3102             fprintf(STDERR,
3103                     "Could not end transaction on the clone volume %lu\n",
3104                     (unsigned long)acloneid);
3105             if (!error)
3106                 error = (code ? code : rcode);
3107         }
3108     }
3109
3110     if (aconn)
3111         rx_DestroyConnection(aconn);
3112
3113     PrintError("", error);
3114     return error;
3115 }
3116
3117 static int
3118 DelVol(struct rx_connection *conn, afs_uint32 vid, afs_int32 part,
3119        afs_int32 flags)
3120 {
3121     afs_int32 acode, ccode, rcode, tid;
3122     ccode = rcode = tid = 0;
3123
3124     acode = AFSVolTransCreate_retry(conn, vid, part, flags, &tid);
3125     if (!acode) {               /* It really was there */
3126         acode = AFSVolDeleteVolume(conn, tid);
3127         if (acode) {
3128             fprintf(STDERR, "Failed to delete volume %lu.\n",
3129                     (unsigned long)vid);
3130             PrintError("", acode);
3131         }
3132         ccode = AFSVolEndTrans(conn, tid, &rcode);
3133         if (!ccode)
3134             ccode = rcode;
3135         if (ccode) {
3136             fprintf(STDERR, "Failed to end transaction on volume %lu.\n",
3137                     (unsigned long)vid);
3138             PrintError("", ccode);
3139         }
3140     }
3141
3142     return acode;
3143 }
3144
3145 #define ONERROR(ec, ep, es) if (ec) { fprintf(STDERR, (es), (ep)); error = (ec); goto rfail; }
3146 #define ONERROR0(ec, es) if (ec) { fprintf(STDERR, (es)); error = (ec); goto rfail; }
3147 #define ERROREXIT(ec) { error = (ec); goto rfail; }
3148
3149 /* Get a "transaction" on this replica.  Create the volume 
3150  * if necessary.  Return the time from which a dump should
3151  * be made (0 if it's a new volume)
3152  */
3153 static int
3154 GetTrans(struct nvldbentry *vldbEntryPtr, afs_int32 index,
3155          struct rx_connection **connPtr, afs_int32 * transPtr,
3156          afs_uint32 * crtimePtr, afs_uint32 * uptimePtr)
3157 {
3158     afs_uint32 volid;
3159     struct volser_status tstatus;
3160     int code = 0;
3161     int rcode, tcode;
3162     char hoststr[16];
3163
3164     *connPtr = (struct rx_connection *)0;
3165     *transPtr = 0;
3166     *crtimePtr = 0;
3167     *uptimePtr = 0;
3168
3169     /* get connection to the replication site */
3170     *connPtr = UV_Bind(vldbEntryPtr->serverNumber[index], AFSCONF_VOLUMEPORT);
3171     if (!*connPtr)
3172         goto fail;              /* server is down */
3173
3174     volid = vldbEntryPtr->volumeId[ROVOL];
3175     if (volid)
3176         code =
3177             AFSVolTransCreate_retry(*connPtr, volid,
3178                               vldbEntryPtr->serverPartition[index], ITOffline,
3179                               transPtr);
3180
3181     /* If the volume does not exist, create it */
3182     if (!volid || code) {
3183         char volname[64];
3184         char hoststr[16];
3185
3186         if (volid && (code != VNOVOL)) {
3187             PrintError("Failed to start a transaction on the RO volume.\n",
3188                        code);
3189             goto fail;
3190         }
3191
3192         strcpy(volname, vldbEntryPtr->name);
3193         strcat(volname, ".readonly");
3194
3195         if (verbose) {
3196             fprintf(STDOUT,
3197                     "Creating new volume %lu on replication site %s: ",
3198                     (unsigned long)volid,
3199                     noresolve ? afs_inet_ntoa_r(vldbEntryPtr->
3200                                                 serverNumber[index], hoststr) :
3201                     hostutil_GetNameByINet(vldbEntryPtr->
3202                                            serverNumber[index]));
3203             fflush(STDOUT);
3204         }
3205
3206         code =
3207             AFSVolCreateVolume(*connPtr, vldbEntryPtr->serverPartition[index],
3208                                volname, volser_RO,
3209                                vldbEntryPtr->volumeId[RWVOL], &volid,
3210                                transPtr);
3211         if (code) {
3212             PrintError("Failed to create the ro volume: ", code);
3213             goto fail;
3214         }
3215         vldbEntryPtr->volumeId[ROVOL] = volid;
3216
3217         VDONE;
3218
3219         /* The following is a bit redundant, since create sets these flags by default */
3220         code =
3221             AFSVolSetFlags(*connPtr, *transPtr,
3222                            VTDeleteOnSalvage | VTOutOfService);
3223         if (code) {
3224             PrintError("Failed to set flags on the ro volume: ", code);
3225             goto fail;
3226         }
3227     }
3228
3229     /* Otherwise, the transaction did succeed, so get the creation date of the
3230      * latest RO volume on the replication site 
3231      */
3232     else {
3233         VPRINT2("Updating existing ro volume %u on %s ...\n", volid,
3234                 noresolve ? afs_inet_ntoa_r(vldbEntryPtr->
3235                                             serverNumber[index], hoststr) : 
3236                 hostutil_GetNameByINet(vldbEntryPtr->serverNumber[index]));
3237
3238         code = AFSVolGetStatus(*connPtr, *transPtr, &tstatus);
3239         if (code) {
3240             PrintError("Failed to get status of volume on destination: ",
3241                        code);
3242             goto fail;
3243         }
3244         *crtimePtr = CLOCKADJ(tstatus.creationDate);
3245         *uptimePtr = CLOCKADJ(tstatus.updateDate);
3246     }
3247
3248     return 0;
3249
3250   fail:
3251     if (*transPtr) {
3252         tcode = AFSVolEndTrans(*connPtr, *transPtr, &rcode);
3253         *transPtr = 0;
3254         if (!tcode)
3255             tcode = rcode;
3256         if (tcode)
3257             PrintError("Could not end transaction on a ro volume: ", tcode);
3258     }
3259
3260     return code;
3261 }
3262
3263 static int
3264 SimulateForwardMultiple(struct rx_connection *fromconn, afs_int32 fromtid,
3265                         afs_int32 fromdate, manyDests * tr, afs_int32 flags,
3266                         void *cookie, manyResults * results)
3267 {
3268     unsigned int i;
3269
3270     for (i = 0; i < tr->manyDests_len; i++) {
3271         results->manyResults_val[i] =
3272             AFSVolForward(fromconn, fromtid, fromdate,
3273                           &(tr->manyDests_val[i].server),
3274                           tr->manyDests_val[i].trans, cookie);
3275     }
3276     return 0;
3277 }
3278
3279
3280 /* UV_ReleaseVolume()
3281  *    Release volume <afromvol> on <afromserver> <afrompart> to all
3282  *    its RO sites (full release). Unless the previous release was
3283  *    incomplete: in which case we bring the remaining incomplete
3284  *    volumes up to date with the volumes that were released
3285  *    successfully.
3286  *    forceflag: Performs a full release.
3287  *
3288  *    Will create a clone from the RW, then dump the clone out to 
3289  *    the remaining replicas. If there is more than 1 RO sites,
3290  *    ensure that the VLDB says at least one RO is available all
3291  *    the time: Influences when we write back the VLDB entry.
3292  */
3293
3294 int
3295 UV_ReleaseVolume(afs_uint32 afromvol, afs_int32 afromserver,
3296                  afs_int32 afrompart, int forceflag)
3297 {
3298     char vname[64];
3299     afs_int32 code = 0;
3300     afs_int32 vcode, rcode, tcode;
3301     afs_uint32 cloneVolId, roVolId;
3302     struct replica *replicas = 0;
3303     struct nvldbentry entry, storeEntry;
3304     int i, volcount, m, fullrelease, vldbindex;
3305     int failure;
3306     struct restoreCookie cookie;
3307     struct rx_connection **toconns = 0;
3308     struct release *times = 0;
3309     int nservers = 0;
3310     struct rx_connection *fromconn = (struct rx_connection *)0;
3311     afs_int32 error = 0;
3312     int islocked = 0;
3313     afs_int32 clonetid = 0, onlinetid;
3314     afs_int32 fromtid = 0;
3315     afs_uint32 fromdate = 0;
3316     afs_uint32 thisdate;
3317     time_t tmv;
3318     int s;
3319     manyDests tr;
3320     manyResults results;
3321     int rwindex, roindex, roclone, roexists;
3322     afs_uint32 rwcrdate = 0;
3323     afs_uint32 rwupdate, clcrdate;
3324     struct rtime {
3325         int validtime;
3326         afs_uint32 uptime;
3327     } remembertime[NMAXNSERVERS];
3328     int releasecount = 0;
3329     struct volser_status volstatus;
3330     char hoststr[16];
3331
3332     memset((char *)remembertime, 0, sizeof(remembertime));
3333     memset((char *)&results, 0, sizeof(results));
3334
3335     vcode = ubik_VL_SetLock(cstruct, 0, afromvol, RWVOL, VLOP_RELEASE);
3336     if (vcode != VL_RERELEASE)
3337         ONERROR(vcode, afromvol,
3338                 "Could not lock the VLDB entry for the volume %u.\n");
3339     islocked = 1;
3340
3341     /* Get the vldb entry in readable format */
3342     vcode = VLDB_GetEntryByID(afromvol, RWVOL, &entry);
3343     ONERROR(vcode, afromvol,
3344             "Could not fetch the entry for the volume %u from the VLDB.\n");
3345     MapHostToNetwork(&entry);
3346
3347     if (verbose)
3348         EnumerateEntry(&entry);
3349
3350     if (!ISNAMEVALID(entry.name))
3351         ONERROR(VOLSERBADOP, entry.name,
3352                 "Volume name %s is too long, rename before releasing.\n");
3353     if (entry.volumeId[RWVOL] != afromvol)
3354         ONERROR(VOLSERBADOP, afromvol,
3355                 "The volume %u being released is not a read-write volume.\n");
3356     if (entry.nServers <= 1)
3357         ONERROR(VOLSERBADOP, afromvol,
3358                 "Volume %u has no replicas - release operation is meaningless!\n");
3359     if (strlen(entry.name) > (VOLSER_OLDMAXVOLNAME - 10))
3360         ONERROR(VOLSERBADOP, entry.name,
3361                 "RO volume name %s exceeds (VOLSER_OLDMAXVOLNAME - 10) character limit\n");
3362
3363     /* roclone is true if one of the RO volumes is on the same
3364      * partition as the RW volume. In this case, we make the RO volume
3365      * on the same partition a clone instead of a complete copy.
3366      */
3367
3368     roindex = Lp_ROMatch(afromserver, afrompart, &entry) - 1;
3369     roclone = ((roindex == -1) ? 0 : 1);
3370     rwindex = Lp_GetRwIndex(&entry);
3371     if (rwindex < 0)
3372         ONERROR0(VOLSERNOVOL, "There is no RW volume \n");
3373
3374     /* Make sure we have a RO volume id to work with */
3375     if (entry.volumeId[ROVOL] == INVALID_BID) {
3376         /* need to get a new RO volume id */
3377         vcode = ubik_VL_GetNewVolumeId(cstruct, 0, 1, &roVolId);
3378         ONERROR(vcode, entry.name, "Cant allocate ID for RO volume of %s\n");
3379
3380         entry.volumeId[ROVOL] = roVolId;
3381         MapNetworkToHost(&entry, &storeEntry);
3382         vcode = VLDB_ReplaceEntry(afromvol, RWVOL, &storeEntry, 0);
3383         ONERROR(vcode, entry.name, "Could not update vldb entry for %s.\n");
3384     }
3385
3386     /* Will we be completing a previously unfinished release. -force overrides */
3387     for (s = 0, m = 0, fullrelease=0, i=0; (i<entry.nServers); i++) {
3388         if (entry.serverFlags[i] & ITSROVOL) {
3389             m++;
3390             if (entry.serverFlags[i] & NEW_REPSITE) s++;
3391         }
3392     }
3393     if ((forceflag && !fullrelease) || (s == m) || (s == 0))
3394         fullrelease = 1;
3395
3396     /* Determine which volume id to use and see if it exists */
3397     cloneVolId =
3398         ((fullrelease
3399           || (entry.cloneId == 0)) ? entry.volumeId[ROVOL] : entry.cloneId);
3400     code = VolumeExists(afromserver, afrompart, cloneVolId);
3401     roexists = ((code == ENODEV) ? 0 : 1);
3402
3403     fromconn = UV_Bind(afromserver, AFSCONF_VOLUMEPORT);
3404     if (!fromconn)
3405         ONERROR(-1, afromserver,
3406                 "Cannot establish connection with server 0x%x\n");
3407
3408     if (!fullrelease) {
3409         if (!roexists)
3410             fullrelease = 1;    /* Do a full release if RO clone does not exist */
3411         else {
3412             /* Begin transaction on RW and mark it busy while we query it */
3413             code = AFSVolTransCreate_retry(
3414                         fromconn, afromvol, afrompart, ITBusy, &fromtid
3415                    );
3416             ONERROR(code, afromvol,
3417                     "Failed to start transaction on RW volume %u\n");
3418
3419             /* Query the creation date for the RW */
3420             code = AFSVolGetStatus(fromconn, fromtid, &volstatus);
3421             ONERROR(code, afromvol,
3422                     "Failed to get the status of RW volume %u\n");
3423             rwcrdate = volstatus.creationDate;
3424             rwupdate = volstatus.updateDate;
3425
3426             /* End transaction on RW */
3427             code = AFSVolEndTrans(fromconn, fromtid, &rcode);
3428             fromtid = 0;
3429             ONERROR((code ? code : rcode), afromvol,
3430                     "Failed to end transaction on RW volume %u\n");
3431
3432             /* Begin transaction on clone and mark it busy while we query it */
3433             code = AFSVolTransCreate_retry(
3434                         fromconn, cloneVolId, afrompart, ITBusy, &clonetid
3435                    );
3436             ONERROR(code, cloneVolId,
3437                     "Failed to start transaction on RW clone %u\n");
3438
3439             /* Query the creation date for the clone */
3440             code = AFSVolGetStatus(fromconn, clonetid, &volstatus);
3441             ONERROR(code, cloneVolId,
3442                     "Failed to get the status of RW clone %u\n");
3443             clcrdate = volstatus.creationDate;
3444
3445             /* End transaction on clone */
3446             code = AFSVolEndTrans(fromconn, clonetid, &rcode);
3447             clonetid = 0;
3448             ONERROR((code ? code : rcode), cloneVolId,
3449                     "Failed to end transaction on RW clone %u\n");
3450
3451             if (rwcrdate > clcrdate)
3452                 fullrelease = 2;/* Do a full release if RO clone older than RW */
3453         }
3454     }
3455
3456     if (verbose) {
3457         switch (fullrelease) {
3458             case 2:
3459                 fprintf(STDOUT, "RW %lu changed, doing a complete release\n",
3460                         (unsigned long)afromvol);
3461                 break;
3462             case 1:
3463                 fprintf(STDOUT, "This is a complete release of volume %lu\n",
3464                         (unsigned long)afromvol);
3465                 break;
3466             case 0:
3467                 fprintf(STDOUT, "This is a completion of a previous release\n");
3468                 break;
3469         }
3470     }
3471
3472     if (fullrelease) {
3473         /* If the RO clone exists, then if the clone is a temporary
3474          * clone, delete it. Or if the RO clone is marked RO_DONTUSE
3475          * (it was recently added), then also delete it. We do not
3476          * want to "reclone" a temporary RO clone.
3477          */
3478         if (roexists
3479             && (!roclone || (entry.serverFlags[roindex] & RO_DONTUSE))) {
3480             code = DelVol(fromconn, cloneVolId, afrompart, ITOffline);
3481             if (code && (code != VNOVOL))
3482                 ERROREXIT(code);
3483             roexists = 0;
3484         }
3485
3486         /* Mark all the ROs in the VLDB entry as RO_DONTUSE. We don't
3487          * write this entry out to the vlserver until after the first
3488          * RO volume is released (temp RO clones don't count).
3489          */
3490         for (i = 0; i < entry.nServers; i++) {
3491             entry.serverFlags[i] &= ~NEW_REPSITE;
3492             entry.serverFlags[i] |= RO_DONTUSE;
3493         }
3494         entry.serverFlags[rwindex] |= NEW_REPSITE;
3495         entry.serverFlags[rwindex] &= ~RO_DONTUSE;
3496
3497         /* Begin transaction on RW and mark it busy while we clone it */
3498         code =
3499             AFSVolTransCreate_retry(fromconn, afromvol, afrompart, ITBusy,
3500                               &clonetid);
3501         ONERROR(code, afromvol, "Failed to start transaction on volume %u\n");
3502
3503         /* Clone or reclone the volume */
3504         if (roexists) {
3505             VPRINT1("Recloning RW volume %u...", cloneVolId);
3506             code = AFSVolReClone(fromconn, clonetid, cloneVolId);
3507             ONERROR(code, afromvol, "Failed to reclone the RW volume %u\n");
3508             VDONE;
3509         } else {
3510             if (roclone) {
3511                 strcpy(vname, entry.name);
3512                 strcat(vname, ".readonly");
3513                 VPRINT1("Cloning RW volume %u to permanent RO...", afromvol);
3514             } else {
3515                 strcpy(vname, "readonly-clone-temp");
3516                 VPRINT1("Cloning RW volume %u to temporary RO...", afromvol);
3517             }
3518             code =
3519                 AFSVolClone(fromconn, clonetid, 0, readonlyVolume, vname,
3520                             &cloneVolId);
3521             ONERROR(code, afromvol, "Failed to clone the RW volume %u\n");
3522             VDONE;
3523         }
3524
3525         /* Get the time the RW was created for future information */
3526         VPRINT1("Getting status of RW volume %u...", afromvol);
3527         code = AFSVolGetStatus(fromconn, clonetid, &volstatus);
3528         ONERROR(code, afromvol,
3529                 "Failed to get the status of the RW volume %u\n");
3530         VDONE;
3531         rwcrdate = volstatus.creationDate;
3532         rwupdate = volstatus.updateDate;
3533
3534         /* End the transaction on the RW volume */
3535         VPRINT1("Ending cloning transaction on RW volume %u...", afromvol);
3536         code = AFSVolEndTrans(fromconn, clonetid, &rcode);
3537         clonetid = 0;
3538         ONERROR((code ? code : rcode), afromvol,
3539                 "Failed to end cloning transaction on RW %u\n");
3540         VDONE;
3541
3542         /* Remember clone volume ID in case we fail or are interrupted */
3543         entry.cloneId = cloneVolId;
3544
3545         if (roclone) {
3546             /* Bring the RO clone online - though not if it's a temporary clone */
3547             VPRINT1("Starting transaction on RO clone volume %u...",
3548                     cloneVolId);
3549             code =
3550                 AFSVolTransCreate_retry(fromconn, cloneVolId, afrompart, ITOffline,
3551                                   &onlinetid);
3552             ONERROR(code, cloneVolId,
3553                     "Failed to start transaction on volume %u\n");
3554             VDONE;
3555
3556             VPRINT1("Setting volume flags for volume %u...", cloneVolId);
3557             tcode = AFSVolSetFlags(fromconn, onlinetid, 0);
3558             VDONE;
3559
3560             VPRINT1("Ending transaction on volume %u...", cloneVolId);
3561             code = AFSVolEndTrans(fromconn, onlinetid, &rcode);
3562             ONERROR((code ? code : rcode), cloneVolId,
3563                     "Failed to end transaction on RO clone %u\n");
3564             VDONE;
3565
3566             ONERROR(tcode, cloneVolId, "Could not bring volume %u on line\n");
3567
3568             /* Sleep so that a client searching for an online volume won't
3569              * find the clone offline and then the next RO offline while the 
3570              * release brings the clone online and the next RO offline (race).
3571              * There is a fix in the 3.4 client that does not need this sleep
3572              * anymore, but we don't know what clients we have.
3573              */
3574             if (entry.nServers > 2)
3575                 sleep(5);
3576
3577             /* Mark the RO clone in the VLDB as a good site (already released) */
3578             entry.serverFlags[roindex] |= NEW_REPSITE;
3579             entry.serverFlags[roindex] &= ~RO_DONTUSE;
3580             entry.flags |= RO_EXISTS;
3581
3582             releasecount++;
3583
3584             /* Write out the VLDB entry only if the clone is not a temporary
3585              * clone. If we did this to a temporary clone then we would end
3586              * up marking all the ROs as "old release" making the ROs
3587              * temporarily unavailable.
3588              */
3589             MapNetworkToHost(&entry, &storeEntry);
3590             VPRINT1("Replacing VLDB entry for %s...", entry.name);
3591             vcode = VLDB_ReplaceEntry(afromvol, RWVOL, &storeEntry, 0);
3592             ONERROR(vcode, entry.name,
3593                     "Could not update vldb entry for %s.\n");
3594             VDONE;
3595         }
3596     }
3597
3598     /* Now we will release from the clone to the remaining RO replicas.
3599      * The first 2 ROs (counting the non-temporary RO clone) are released
3600      * individually: releasecount. This is to reduce the race condition
3601      * of clients trying to find an on-line RO volume. The remaining ROs
3602      * are released in parallel but no more than half the number of ROs
3603      * (rounded up) at a time: nservers.
3604      */
3605
3606     strcpy(vname, entry.name);
3607     strcat(vname, ".readonly");
3608     memset(&cookie, 0, sizeof(cookie));
3609     strncpy(cookie.name, vname, VOLSER_OLDMAXVOLNAME);
3610     cookie.type = ROVOL;
3611     cookie.parent = entry.volumeId[RWVOL];
3612     cookie.clone = 0;
3613
3614     nservers = entry.nServers / 2;      /* how many to do at once, excluding clone */
3615     replicas =
3616         (struct replica *)malloc(sizeof(struct replica) * nservers + 1);
3617     times = (struct release *)malloc(sizeof(struct release) * nservers + 1);
3618     toconns =
3619         (struct rx_connection **)malloc(sizeof(struct rx_connection *) *
3620                                         nservers + 1);
3621     results.manyResults_val =
3622         (afs_int32 *) malloc(sizeof(afs_int32) * nservers + 1);
3623     if (!replicas || !times || !!!results.manyResults_val || !toconns)
3624         ONERROR0(ENOMEM,
3625                 "Failed to create transaction on the release clone\n");
3626
3627     memset(replicas, 0, (sizeof(struct replica) * nservers + 1));
3628     memset(times, 0, (sizeof(struct release) * nservers + 1));
3629     memset(toconns, 0, (sizeof(struct rx_connection *) * nservers + 1));
3630     memset(results.manyResults_val, 0, (sizeof(afs_int32) * nservers + 1));
3631
3632     /* Create a transaction on the cloned volume */
3633     VPRINT1("Starting transaction on cloned volume %u...", cloneVolId);
3634     code =
3635         AFSVolTransCreate_retry(fromconn, cloneVolId, afrompart, ITBusy, &fromtid);
3636     if (!fullrelease && code)
3637         ONERROR(VOLSERNOVOL, afromvol,
3638                 "Old clone is inaccessible. Try vos release -f %u.\n");
3639     ONERROR0(code, "Failed to create transaction on the release clone\n");
3640     VDONE;
3641
3642     /* For each index in the VLDB */
3643     for (vldbindex = 0; vldbindex < entry.nServers;) {
3644
3645         /* Get a transaction on the replicas. Pick replacas which have an old release. */
3646         for (volcount = 0;
3647              ((volcount < nservers) && (vldbindex < entry.nServers));
3648              vldbindex++) {
3649             /* The first two RO volumes will be released individually.
3650              * The rest are then released in parallel. This is a hack
3651              * for clients not recognizing right away when a RO volume
3652              * comes back on-line.
3653              */
3654             if ((volcount == 1) && (releasecount < 2))
3655                 break;
3656
3657             if (vldbindex == roindex)
3658                 continue;       /* the clone    */
3659             if ((entry.serverFlags[vldbindex] & NEW_REPSITE)
3660                 && !(entry.serverFlags[vldbindex] & RO_DONTUSE))
3661                 continue;
3662             if (!(entry.serverFlags[vldbindex] & ITSROVOL))
3663                 continue;       /* not a RO vol */
3664
3665
3666             /* Get a Transaction on this replica. Get a new connection if
3667              * necessary.  Create the volume if necessary.  Return the
3668              * time from which the dump should be made (0 if it's a new
3669              * volume).  Each volume might have a different time. 
3670              */
3671             replicas[volcount].server.destHost =
3672                 ntohl(entry.serverNumber[vldbindex]);
3673             replicas[volcount].server.destPort = AFSCONF_VOLUMEPORT;
3674             replicas[volcount].server.destSSID = 1;
3675             times[volcount].vldbEntryIndex = vldbindex;
3676
3677             code =
3678                 GetTrans(&entry, vldbindex, &(toconns[volcount]),
3679                          &(replicas[volcount].trans),
3680                          &(times[volcount].crtime),
3681                          &(times[volcount].uptime));
3682             if (code)
3683                 continue;
3684
3685             /* Thisdate is the date from which we want to pick up all changes */
3686             if (forceflag || !fullrelease
3687                 || (rwcrdate > times[volcount].crtime)) {
3688                 /* If the forceflag is set, then we want to do a full dump.
3689                  * If it's not a full release, we can't be sure that the creation
3690                  *  date is good (so we also do a full dump).
3691                  * If the RW volume was replaced (its creation date is newer than
3692                  *  the last release), then we can't be sure what has changed (so
3693                  *  we do a full dump).
3694                  */
3695                 thisdate = 0;
3696             } else if (remembertime[vldbindex].validtime) {
3697                 /* Trans was prev ended. Use the time from the prev trans
3698                  * because, prev trans may have created the volume. In which
3699                  * case time[volcount].time would be now instead of 0.
3700                  */
3701                 thisdate =
3702                     (remembertime[vldbindex].uptime < times[volcount].uptime)
3703                         ? remembertime[vldbindex].uptime
3704                         : times[volcount].uptime;
3705             } else {
3706                 thisdate = times[volcount].uptime;
3707             }
3708             remembertime[vldbindex].validtime = 1;
3709             remembertime[vldbindex].uptime = thisdate;
3710
3711             if (volcount == 0) {
3712                 fromdate = thisdate;
3713             } else {
3714                 /* Include this volume if it is within 15 minutes of the earliest */
3715                 if (((fromdate >
3716                       thisdate) ? (fromdate - thisdate) : (thisdate -
3717                                                            fromdate)) > 900) {
3718                     AFSVolEndTrans(toconns[volcount],
3719                                    replicas[volcount].trans, &rcode);
3720                     replicas[volcount].trans = 0;
3721                     break;
3722                 }
3723                 if (thisdate < fromdate)
3724                     fromdate = thisdate;
3725             }
3726             volcount++;
3727         }
3728         if (!volcount)
3729             continue;
3730
3731         if (verbose) {
3732             fprintf(STDOUT, "Starting ForwardMulti from %lu to %u on %s",
3733                     (unsigned long)cloneVolId, entry.volumeId[ROVOL],
3734                     noresolve ? afs_inet_ntoa_r(entry.serverNumber[times[0].
3735                                                 vldbEntryIndex], hoststr) :
3736                     hostutil_GetNameByINet(entry.
3737                                            serverNumber[times[0].
3738                                                         vldbEntryIndex]));
3739
3740             for (s = 1; s < volcount; s++) {
3741                 fprintf(STDOUT, " and %s",
3742                         noresolve ? afs_inet_ntoa_r(entry.serverNumber[times[s].
3743                                                     vldbEntryIndex], hoststr) :
3744                         hostutil_GetNameByINet(entry.
3745                                                serverNumber[times[s].
3746                                                             vldbEntryIndex]));
3747             }
3748
3749             if (fromdate == 0)
3750                 fprintf(STDOUT, " (full release)");
3751             else {
3752                 tmv = fromdate;
3753                 fprintf(STDOUT, " (as of %.24s)", ctime(&tmv));
3754             }
3755             fprintf(STDOUT, ".\n");
3756             fflush(STDOUT);
3757         }
3758
3759         /* Release the ones we have collected */
3760         tr.manyDests_val = &(replicas[0]);
3761         tr.manyDests_len = results.manyResults_len = volcount;
3762         code =
3763             AFSVolForwardMultiple(fromconn, fromtid, fromdate, &tr,
3764                                   0 /*spare */ , &cookie, &results);
3765         if (code == RXGEN_OPCODE) {     /* RPC Interface Mismatch */
3766             code =
3767                 SimulateForwardMultiple(fromconn, fromtid, fromdate, &tr,
3768                                         0 /*spare */ , &cookie, &results);
3769             nservers = 1;
3770         }
3771
3772         if (code) {
3773             PrintError("Release failed: ", code);
3774         } else {
3775             for (m = 0; m < volcount; m++) {
3776                 if (results.manyResults_val[m]) {
3777                     if ((m == 0) || (results.manyResults_val[m] != ENOENT)) {
3778                         /* we retry timed out transaction. When it is
3779                          * not the first volume and the transaction wasn't found
3780                          * (assume it timed out and was garbage collected by volser).
3781                          */
3782                         PrintError
3783                             ("Failed to dump volume from clone to a ro site: ",
3784                              results.manyResults_val[m]);
3785                     }
3786                     continue;
3787                 }
3788
3789                 code =
3790                     AFSVolSetIdsTypes(toconns[m], replicas[m].trans, vname,
3791                                       ROVOL, entry.volumeId[RWVOL], 0, 0);
3792                 if (code) {
3793                     if ((m == 0) || (code != ENOENT)) {
3794                         PrintError("Failed to set correct names and ids: ",
3795                                    code);
3796                     }
3797                     continue;
3798                 }
3799
3800                 /* have to clear dest. flags to ensure new vol goes online:
3801                  * because the restore (forwarded) operation copied
3802                  * the V_inService(=0) flag over to the destination. 
3803                  */
3804                 code = AFSVolSetFlags(toconns[m], replicas[m].trans, 0);
3805                 if (code) {
3806                     if ((m == 0) || (code != ENOENT)) {
3807                         PrintError("Failed to set flags on ro volume: ",
3808                                    code);
3809                     }
3810                     continue;
3811                 }
3812
3813                 entry.serverFlags[times[m].vldbEntryIndex] |= NEW_REPSITE;
3814                 entry.serverFlags[times[m].vldbEntryIndex] &= ~RO_DONTUSE;
3815                 entry.flags |= RO_EXISTS;
3816                 releasecount++;
3817             }
3818         }
3819
3820         /* End the transactions and destroy the connections */
3821         for (s = 0; s < volcount; s++) {
3822             if (replicas[s].trans)
3823                 code = AFSVolEndTrans(toconns[s], replicas[s].trans, &rcode);
3824             replicas[s].trans = 0;
3825             if (!code)
3826                 code = rcode;
3827             if (code) {
3828                 if ((s == 0) || (code != ENOENT)) {
3829                     PrintError("Could not end transaction on a ro volume: ",
3830                                code);
3831                 } else {
3832                     PrintError
3833                         ("Transaction timed out on a ro volume. Will retry.\n",
3834                          0);
3835                     if (times[s].vldbEntryIndex < vldbindex)
3836                         vldbindex = times[s].vldbEntryIndex;
3837                 }
3838             }
3839
3840             if (toconns[s])
3841                 rx_DestroyConnection(toconns[s]);
3842             toconns[s] = 0;
3843         }
3844
3845         MapNetworkToHost(&entry, &storeEntry);
3846         vcode = VLDB_ReplaceEntry(afromvol, RWVOL, &storeEntry, 0);
3847         ONERROR(vcode, afromvol,
3848                 " Could not update VLDB entry for volume %u\n");
3849     }                           /* for each index in the vldb */
3850
3851     /* End the transaction on the cloned volume */
3852     code = AFSVolEndTrans(fromconn, fromtid, &rcode);
3853     fromtid = 0;
3854     if (!code)
3855         code = rcode;
3856     if (code)
3857         PrintError("Failed to end transaction on rw volume: ", code);
3858
3859     /* Figure out if any volume were not released and say so */
3860     for (failure = 0, i = 0; i < entry.nServers; i++) {
3861         if (!(entry.serverFlags[i] & NEW_REPSITE))
3862             failure++;
3863     }
3864     if (failure) {
3865         char pname[10];
3866         fprintf(STDERR,
3867                 "The volume %lu could not be released to the following %d sites:\n",
3868                 (unsigned long)afromvol, failure);
3869         for (i = 0; i < entry.nServers; i++) {
3870             if (!(entry.serverFlags[i] & NEW_REPSITE)) {
3871                 MapPartIdIntoName(entry.serverPartition[i], pname);
3872                 fprintf(STDERR, "\t%35s %s\n",
3873                         noresolve ? afs_inet_ntoa_r(entry.serverNumber[i], hoststr) :
3874                         hostutil_GetNameByINet(entry.serverNumber[i]), pname);
3875             }
3876         }
3877
3878         MapNetworkToHost(&entry, &storeEntry);
3879         vcode =
3880             VLDB_ReplaceEntry(afromvol, RWVOL, &storeEntry,
3881                               LOCKREL_TIMESTAMP);
3882         ONERROR(vcode, afromvol,
3883                 " Could not update VLDB entry for volume %u\n");
3884
3885         ERROREXIT(VOLSERBADRELEASE);
3886     }
3887
3888     /* All the ROs were release successfully. Remove the temporary clone */
3889     if (!roclone) {
3890         if (verbose) {
3891             fprintf(STDOUT, "Deleting the releaseClone %lu ...",
3892                     (unsigned long)cloneVolId);
3893             fflush(STDOUT);
3894         }
3895         code = DelVol(fromconn, cloneVolId, afrompart, ITOffline);
3896         ONERROR(code, cloneVolId, "Failed to delete volume %u.\n");
3897         VDONE;
3898     }
3899     entry.cloneId = 0;
3900
3901     for (i = 0; i < entry.nServers; i++)
3902         entry.serverFlags[i] &= ~NEW_REPSITE;
3903
3904     /* Update the VLDB */
3905     VPRINT("updating VLDB ...");
3906
3907     MapNetworkToHost(&entry, &storeEntry);
3908     vcode =
3909         VLDB_ReplaceEntry(afromvol, RWVOL, &storeEntry,
3910                           LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
3911     ONERROR(vcode, afromvol, " Could not update VLDB entry for volume %u\n");
3912     VDONE;
3913
3914   rfail:
3915     if (clonetid) {
3916         code = AFSVolEndTrans(fromconn, clonetid, &rcode);
3917         clonetid = 0;
3918         if (code) {
3919             fprintf(STDERR,
3920                     "Failed to end cloning transaction on the RW volume %lu\n",
3921                     (unsigned long)afromvol);
3922             if (!error)
3923                 error = code;
3924         }
3925     }
3926     if (fromtid) {
3927         code = AFSVolEndTrans(fromconn, fromtid, &rcode);
3928         fromtid = 0;
3929         if (code) {
3930             fprintf(STDERR,
3931                     "Failed to end transaction on the release clone %lu\n",
3932                     (unsigned long)cloneVolId);
3933             if (!error)
3934                 error = code;
3935         }
3936     }
3937     for (i = 0; i < nservers; i++) {
3938         if (replicas && replicas[i].trans) {
3939             code = AFSVolEndTrans(toconns[i], replicas[i].trans, &rcode);
3940             replicas[i].trans = 0;
3941             if (code) {
3942                 fprintf(STDERR,
3943                         "Failed to end transaction on ro volume %u at server %s\n",
3944                         entry.volumeId[ROVOL],
3945                         noresolve ? afs_inet_ntoa_r(htonl(replicas[i].server.
3946                                                         destHost), hoststr) :
3947                         hostutil_GetNameByINet(htonl
3948                                                (replicas[i].server.destHost)));
3949                 if (!error)
3950                     error = code;
3951             }
3952         }
3953         if (toconns && toconns[i]) {
3954             rx_DestroyConnection(toconns[i]);
3955             toconns[i] = 0;
3956         }
3957     }
3958     if (islocked) {
3959         vcode =
3960             ubik_VL_ReleaseLock(cstruct, 0, afromvol, RWVOL,
3961                       LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
3962         if (vcode) {
3963             fprintf(STDERR,
3964                     "Could not release lock on the VLDB entry for volume %lu\n",
3965                     (unsigned long)afromvol);
3966             if (!error)
3967                 error = vcode;
3968         }
3969     }
3970
3971     PrintError("", error);
3972
3973     if (fromconn)
3974         rx_DestroyConnection(fromconn);
3975     if (results.manyResults_val)
3976         free(results.manyResults_val);
3977     if (replicas)
3978         free(replicas);
3979     if (toconns)
3980         free(toconns);
3981     if (times)
3982         free(times);
3983     return error;
3984 }
3985
3986
3987 void
3988 dump_sig_handler(int x)
3989 {
3990     fprintf(STDERR, "\nSignal handler: vos dump operation\n");
3991     longjmp(env, 0);
3992 }
3993
3994 /* Dump the volume <afromvol> on <afromserver> and
3995  * <afrompart> to <afilename> starting from <fromdate>.
3996  * DumpFunction does the real work behind the scenes after
3997  * extracting parameters from the rock 
3998  */
3999 int
4000 UV_DumpVolume(afs_uint32 afromvol, afs_int32 afromserver, afs_int32 afrompart,
4001               afs_int32 fromdate,
4002               afs_int32(*DumpFunction) (struct rx_call *, void *), void *rock,
4003               afs_int32 flags)
4004 {
4005     struct rx_connection *fromconn = (struct rx_connection *)0;
4006     struct rx_call *fromcall = (struct rx_call *)0;
4007     afs_int32 fromtid = 0, rxError = 0, rcode = 0;
4008     afs_int32 code, error = 0, retry = 0;
4009     time_t tmv = fromdate;
4010
4011     if (setjmp(env))
4012         ERROR_EXIT(EPIPE);
4013 #ifndef AFS_NT40_ENV
4014     (void)signal(SIGPIPE, dump_sig_handler);
4015 #endif
4016     (void)signal(SIGINT, dump_sig_handler);
4017
4018     if (!fromdate) {
4019         VEPRINT("Full Dump ...\n");
4020     } else {
4021         VEPRINT1("Incremental Dump (as of %.24s)...\n",
4022                 ctime(&tmv));
4023     }
4024
4025     /* get connections to the servers */
4026     fromconn = UV_Bind(afromserver, AFSCONF_VOLUMEPORT);
4027
4028     VEPRINT1("Starting transaction on volume %u...", afromvol);
4029     code = AFSVolTransCreate_retry(fromconn, afromvol, afrompart, ITBusy, &fromtid);
4030     EGOTO1(error_exit, code,
4031            "Could not start transaction on the volume %u to be dumped\n",
4032            afromvol);
4033     VEDONE;
4034
4035     fromcall = rx_NewCall(fromconn);
4036
4037     VEPRINT1("Starting volume dump on volume %u...", afromvol);
4038     if (flags & VOLDUMPV2_OMITDIRS) 
4039         code = StartAFSVolDumpV2(fromcall, fromtid, fromdate, flags);
4040     else
4041       retryold:
4042         code = StartAFSVolDump(fromcall, fromtid, fromdate);
4043     EGOTO(error_exit, code, "Could not start the dump process \n");
4044     VEDONE;
4045
4046     VEPRINT1("Dumping volume %u...", afromvol);
4047     code = DumpFunction(fromcall, rock);
4048     if (code == RXGEN_OPCODE) 
4049         goto error_exit;
4050     EGOTO(error_exit, code, "Error while dumping volume \n");
4051     VEDONE;
4052
4053   error_exit:
4054     if (fromcall) {
4055         code = rx_EndCall(fromcall, rxError);
4056         if (code && code != RXGEN_OPCODE) 
4057             fprintf(STDERR, "Error in rx_EndCall\n");
4058         if (code && !error)
4059             error = code;
4060     }
4061     if (fromtid) {
4062         VEPRINT1("Ending transaction on volume %u...", afromvol);
4063         code = AFSVolEndTrans(fromconn, fromtid, &rcode);
4064         if (code || rcode) {
4065             fprintf(STDERR, "Could not end transaction on the volume %lu\n",
4066                     (unsigned long)afromvol);
4067             if (!error)
4068                 error = (code ? code : rcode);
4069         }
4070         VEDONE;
4071     }
4072     if (fromconn)
4073         rx_DestroyConnection(fromconn);
4074
4075     if (retry)
4076         goto retryold;
4077     if (error != RXGEN_OPCODE)
4078         PrintError("", error);
4079     return (error);
4080 }
4081
4082 /* Clone the volume <afromvol> on <afromserver> and
4083  * <afrompart>, and then dump the clone volume to 
4084  * <afilename> starting from <fromdate>.
4085  * DumpFunction does the real work behind the scenes after
4086  * extracting parameters from the rock 
4087  */
4088 int
4089 UV_DumpClonedVolume(afs_uint32 afromvol, afs_int32 afromserver,
4090                     afs_int32 afrompart, afs_int32 fromdate,
4091                     afs_int32(*DumpFunction) (struct rx_call *, void *),
4092                     void *rock, afs_int32 flags)
4093 {
4094     struct rx_connection *fromconn = (struct rx_connection *)0;
4095     struct rx_call *fromcall = (struct rx_call *)0;
4096     afs_int32 fromtid = 0, rxError = 0, rcode = 0;
4097     afs_int32 clonetid = 0;
4098     afs_int32 code = 0, error = 0;
4099     afs_uint32 clonevol = 0;
4100     char vname[64];
4101     time_t tmv = fromdate;
4102
4103     if (setjmp(env))
4104         ERROR_EXIT(EPIPE);
4105 #ifndef AFS_NT40_ENV
4106     (void)signal(SIGPIPE, dump_sig_handler);
4107 #endif
4108     (void)signal(SIGINT, dump_sig_handler);
4109
4110     if (!fromdate) {
4111         VEPRINT("Full Dump ...\n");
4112     } else {
4113         VEPRINT1("Incremental Dump (as of %.24s)...\n",
4114                 ctime(&tmv));
4115     }
4116
4117     /* get connections to the servers */
4118     fromconn = UV_Bind(afromserver, AFSCONF_VOLUMEPORT);
4119
4120     VEPRINT1("Starting transaction on volume %u...", afromvol);
4121     code = AFSVolTransCreate_retry(fromconn, afromvol, afrompart, ITBusy, &fromtid);
4122     EGOTO1(error_exit, code,
4123            "Could not start transaction on the volume %u to be dumped\n",
4124            afromvol);
4125     VEDONE;
4126
4127     /* Get a clone id */
4128     VEPRINT1("Allocating new volume id for clone of volume %u ...", afromvol);
4129     code = ubik_VL_GetNewVolumeId(cstruct, 0, 1, &clonevol);
4130     EGOTO1(error_exit, code,
4131            "Could not get an ID for the clone of volume %u from the VLDB\n",
4132            afromvol);
4133     VEDONE;
4134
4135     /* Do the clone. Default flags on clone are set to delete on salvage and out of service */
4136     VEPRINT2("Cloning source volume %u to clone volume %u...", afromvol,
4137             clonevol);
4138     strcpy(vname, "dump-clone-temp");
4139     code =
4140         AFSVolClone(fromconn, fromtid, 0, readonlyVolume, vname, &clonevol);
4141     EGOTO1(error_exit, code, "Failed to clone the source volume %u\n",
4142            afromvol);
4143     VEDONE;
4144
4145     VEPRINT1("Ending the transaction on the volume %u ...", afromvol);
4146     rcode = 0;
4147     code = AFSVolEndTrans(fromconn, fromtid, &rcode);
4148     fromtid = 0;
4149     if (!code)
4150         code = rcode;
4151     EGOTO1(error_exit, code,
4152            "Failed to end the transaction on the volume %u\n", afromvol);
4153     VEDONE;
4154
4155
4156     VEPRINT1("Starting transaction on the cloned volume %u ...", clonevol);
4157     code =
4158         AFSVolTransCreate_retry(fromconn, clonevol, afrompart, ITOffline,
4159                           &clonetid);
4160     EGOTO1(error_exit, code,
4161            "Failed to start a transaction on the cloned volume%u\n",
4162            clonevol);
4163     VEDONE;
4164
4165     VEPRINT1("Setting flags on cloned volume %u ...", clonevol);
4166     code = AFSVolSetFlags(fromconn, clonetid, VTDeleteOnSalvage | VTOutOfService);      /*redundant */
4167     EGOTO1(error_exit, code, "Could not set falgs on the cloned volume %u\n",
4168            clonevol);
4169     VEDONE;
4170
4171
4172     fromcall = rx_NewCall(fromconn);
4173
4174     VEPRINT1("Starting volume dump from cloned volume %u...", clonevol);
4175     if (flags & VOLDUMPV2_OMITDIRS) 
4176         code = StartAFSVolDumpV2(fromcall, clonetid, fromdate, flags);
4177     else
4178         code = StartAFSVolDump(fromcall, clonetid, fromdate);
4179     EGOTO(error_exit, code, "Could not start the dump process \n");
4180     VEDONE;
4181
4182     VEPRINT1("Dumping volume %u...", afromvol);
4183     code = DumpFunction(fromcall, rock);
4184     EGOTO(error_exit, code, "Error while dumping volume \n");
4185     VEDONE;
4186
4187   error_exit:
4188     /* now delete the clone */
4189     VEPRINT1("Deleting the cloned volume %u ...", clonevol);
4190     code = AFSVolDeleteVolume(fromconn, clonetid);
4191     if (code) {
4192         fprintf(STDERR, "Failed to delete the cloned volume %lu\n",
4193                 (unsigned long)clonevol);
4194     } else {
4195         VEDONE;
4196     }
4197
4198     if (fromcall) {
4199         code = rx_EndCall(fromcall, rxError);
4200         if (code) {
4201             fprintf(STDERR, "Error in rx_EndCall\n");
4202             if (!error)
4203                 error = code;
4204         }
4205     }
4206     if (clonetid) {
4207         VEPRINT1("Ending transaction on cloned volume %u...", clonevol);
4208         code = AFSVolEndTrans(fromconn, clonetid, &rcode);
4209         if (code || rcode) {
4210             fprintf(STDERR,
4211                     "Could not end transaction on the cloned volume %lu\n",
4212                     (unsigned long)clonevol);
4213             if (!error)
4214                 error = (code ? code : rcode);
4215         }
4216         VEDONE;
4217     }
4218     if (fromconn)
4219         rx_DestroyConnection(fromconn);
4220
4221     PrintError("", error);
4222     return (error);
4223 }
4224
4225
4226
4227 /*
4228  * Restore a volume <tovolid> <tovolname> on <toserver> <topart> from
4229  * the dump file <afilename>. WriteData does all the real work
4230  * after extracting params from the rock 
4231  */
4232 int
4233 UV_RestoreVolume2(afs_int32 toserver, afs_int32 topart, afs_uint32 tovolid,
4234                   afs_int32 toparentid, char tovolname[], int flags,
4235                   afs_int32(*WriteData) (struct rx_call *, void *),
4236                   void *rock)
4237 {
4238     struct rx_connection *toconn, *tempconn;
4239     struct rx_call *tocall;
4240     afs_int32 totid, code, rcode, vcode, terror = 0;
4241     afs_int32 rxError = 0;
4242     struct volser_status tstatus;
4243     struct volintInfo vinfo;
4244     char partName[10];
4245     char tovolreal[VOLSER_OLDMAXVOLNAME];
4246     afs_uint32 pvolid; 
4247     afs_int32 temptid, pparentid;
4248     int success;
4249     struct nvldbentry entry, storeEntry;
4250     afs_int32 error;
4251     int islocked;
4252     struct restoreCookie cookie;
4253     int reuseID;
4254     afs_int32 volflag, voltype, volsertype;
4255     afs_int32 oldCreateDate, oldUpdateDate, newCreateDate, newUpdateDate;
4256     int index, same, errcode;
4257     char apartName[10];
4258     char hoststr[16];
4259
4260     memset(&cookie, 0, sizeof(cookie));
4261     islocked = 0;
4262     success = 0;
4263     error = 0;
4264     reuseID = 1;
4265     tocall = (struct rx_call *)0;
4266     toconn = (struct rx_connection *)0;
4267     tempconn = (struct rx_connection *)0;
4268     totid = 0;
4269     temptid = 0;
4270
4271     if (flags & RV_RDONLY) {
4272         voltype = ROVOL;
4273         volsertype = volser_RO;
4274     } else {
4275         voltype = RWVOL;
4276         volsertype = volser_RW;
4277     }
4278
4279     pvolid = tovolid;
4280     pparentid = toparentid;
4281     toconn = UV_Bind(toserver, AFSCONF_VOLUMEPORT);
4282     if (pvolid == 0) {          /*alot a new id if needed */
4283         vcode = VLDB_GetEntryByName(tovolname, &entry);
4284         if (vcode == VL_NOENT) {
4285             vcode = ubik_VL_GetNewVolumeId(cstruct, 0, 1, &pvolid);
4286             if (vcode) {
4287                 fprintf(STDERR, "Could not get an Id for the volume %s\n",
4288                         tovolname);
4289                 error = vcode;
4290                 goto refail;
4291             }
4292             reuseID = 0;
4293         } else if (flags & RV_RDONLY) {
4294             if (entry.flags & RW_EXISTS) {
4295                 fprintf(STDERR,
4296                         "Entry for ReadWrite volume %s already exists!\n",
4297                         entry.name);
4298                 error = VOLSERBADOP;
4299                 goto refail;
4300             }
4301             if (!entry.volumeId[ROVOL]) {
4302                 fprintf(STDERR,
4303                         "Existing entry for volume %s has no ReadOnly ID\n",
4304                         tovolname);
4305                 error = VOLSERBADOP;
4306                 goto refail;
4307             }
4308             pvolid = entry.volumeId[ROVOL];
4309             pparentid = entry.volumeId[RWVOL];
4310         } else {
4311             pvolid = entry.volumeId[RWVOL];
4312             pparentid = entry.volumeId[RWVOL];
4313         }
4314     }
4315     if (!pparentid) pparentid = pvolid;
4316     /* at this point we have a volume id to use/reuse for the volume to be restored */
4317     strncpy(tovolreal, tovolname, VOLSER_OLDMAXVOLNAME);
4318             
4319     if (strlen(tovolname) > (VOLSER_OLDMAXVOLNAME - 1)) {
4320         EGOTO1(refail, VOLSERBADOP,
4321                "The volume name %s exceeds the maximum limit of (VOLSER_OLDMAXVOLNAME -1 ) bytes\n",
4322                tovolname);
4323     } else {
4324         if ((pparentid != pvolid) && (flags & RV_RDONLY)) {
4325             if (strlen(tovolname) > (VOLSER_OLDMAXVOLNAME - 10)) {
4326                 EGOTO1(refail, VOLSERBADOP,
4327                        "The volume name %s exceeds the maximum limit of (VOLSER_OLDMAXVOLNAME -1 ) bytes\n", tovolname);
4328             }
4329             snprintf(tovolreal, VOLSER_OLDMAXVOLNAME, "%s.readonly", tovolname);
4330         }
4331     }
4332     MapPartIdIntoName(topart, partName);
4333     fprintf(STDOUT, "Restoring volume %s Id %lu on server %s partition %s ..",
4334             tovolreal, (unsigned long)pvolid,
4335             noresolve ? afs_inet_ntoa_r(toserver, hoststr) :
4336             hostutil_GetNameByINet(toserver), partName);
4337     fflush(STDOUT);
4338     code =
4339         AFSVolCreateVolume(toconn, topart, tovolreal, volsertype, pparentid, &pvolid,
4340                            &totid);
4341     if (code) {
4342         if (flags & RV_FULLRST) {       /* full restore: delete then create anew */
4343             VPRINT1("Deleting the previous volume %u ...", pvolid);
4344
4345             code =
4346                 AFSVolTransCreate_retry(toconn, pvolid, topart, ITOffline, &totid);
4347             EGOTO1(refail, code, "Failed to start transaction on %u\n",
4348                    pvolid);
4349
4350             code = AFSVolGetStatus(toconn, totid, &tstatus);
4351             EGOTO1(refail, code, "Could not get timestamp from volume %u\n",
4352                    pvolid);
4353
4354             oldCreateDate = tstatus.creationDate;
4355             oldUpdateDate = tstatus.updateDate;
4356
4357             code =
4358                 AFSVolSetFlags(toconn, totid,
4359                                VTDeleteOnSalvage | VTOutOfService);
4360             EGOTO1(refail, code, "Could not set flags on volume %u \n",
4361                    pvolid);
4362
4363             code = AFSVolDeleteVolume(toconn, totid);
4364             EGOTO1(refail, code, "Could not delete volume %u\n", pvolid);
4365
4366             code = AFSVolEndTrans(toconn, totid, &rcode);
4367             totid = 0;
4368             if (!code)
4369                 code = rcode;
4370             EGOTO1(refail, code, "Could not end transaction on %u\n", pvolid);
4371
4372             VDONE;
4373
4374             code =
4375                 AFSVolCreateVolume(toconn, topart, tovolreal, volsertype, pparentid,
4376                                    &pvolid, &totid);
4377             EGOTO1(refail, code, "Could not create new volume %u\n", pvolid);
4378         } else {
4379             code =
4380                 AFSVolTransCreate_retry(toconn, pvolid, topart, ITOffline, &totid);
4381             EGOTO1(refail, code, "Failed to start transaction on %u\n",
4382                    pvolid);
4383
4384             code = AFSVolGetStatus(toconn, totid, &tstatus);
4385             EGOTO1(refail, code, "Could not get timestamp from volume %u\n",
4386                    pvolid);
4387
4388             oldCreateDate = tstatus.creationDate;
4389             oldUpdateDate = tstatus.updateDate;
4390         }
4391     } else {
4392         oldCreateDate = 0;
4393         oldUpdateDate = 0;
4394     }
4395
4396     cookie.parent = pparentid;
4397     cookie.type = voltype;
4398     cookie.clone = 0;
4399     strncpy(cookie.name, tovolreal, VOLSER_OLDMAXVOLNAME);
4400
4401     tocall = rx_NewCall(toconn);
4402     terror = StartAFSVolRestore(tocall, totid, 1, &cookie);
4403     if (terror) {
4404         fprintf(STDERR, "Volume restore Failed \n");
4405         error = terror;
4406         goto refail;
4407     }
4408     code = WriteData(tocall, rock);
4409     if (code) {
4410         fprintf(STDERR, "Could not transmit data\n");
4411         error = code;
4412         goto refail;
4413     }
4414     terror = rx_EndCall(tocall, rxError);
4415     tocall = (struct rx_call *)0;
4416     if (terror) {
4417         fprintf(STDERR, "rx_EndCall Failed \n");
4418         error = terror;
4419         goto refail;
4420     }
4421     code = AFSVolGetStatus(toconn, totid, &tstatus);
4422     if (code) {
4423         fprintf(STDERR,
4424                 "Could not get status information about the volume %lu\n",
4425                 (unsigned long)pvolid);
4426         error = code;
4427         goto refail;
4428     }
4429     code = AFSVolSetIdsTypes(toconn, totid, tovolreal, voltype, pparentid, 0, 0);
4430     if (code) {
4431         fprintf(STDERR, "Could not set the right type and ID on %lu\n",
4432                 (unsigned long)pvolid);
4433         error = code;
4434         goto refail;
4435     }
4436
4437     if (flags & RV_CRDUMP)
4438         newCreateDate = tstatus.creationDate;
4439     else if (flags & RV_CRKEEP && oldCreateDate != 0)
4440         newCreateDate = oldCreateDate;
4441     else
4442         newCreateDate = time(0);
4443     if (flags & RV_LUDUMP)
4444         newUpdateDate = tstatus.updateDate;
4445     else if (flags & RV_LUKEEP)
4446         newUpdateDate = oldUpdateDate;
4447     else
4448         newUpdateDate = time(0);
4449     code = AFSVolSetDate(toconn,totid, newCreateDate);
4450     if (code) {
4451         fprintf(STDERR, "Could not set the 'creation' date on %u\n", pvolid);
4452         error = code;
4453         goto refail;
4454     }
4455
4456     init_volintInfo(&vinfo);
4457     vinfo.creationDate = newCreateDate;
4458     vinfo.updateDate = newUpdateDate;
4459     code = AFSVolSetInfo(toconn, totid, &vinfo);
4460     if (code) {
4461         fprintf(STDERR, "Could not set the 'last updated' date on %u\n",
4462                 pvolid);
4463         error = code;
4464         goto refail;
4465     }
4466
4467     volflag = ((flags & RV_OFFLINE) ? VTOutOfService : 0);      /* off or on-line */
4468     code = AFSVolSetFlags(toconn, totid, volflag);
4469     if (code) {
4470         fprintf(STDERR, "Could not mark %lu online\n", (unsigned long)pvolid);
4471         error = code;
4472         goto refail;
4473     }
4474
4475 /* It isn't handled right in refail */
4476     code = AFSVolEndTrans(toconn, totid, &rcode);
4477     totid = 0;
4478     if (!code)
4479         code = rcode;
4480     if (code) {
4481         fprintf(STDERR, "Could not end transaction on %lu\n",
4482                 (unsigned long)pvolid);
4483         error = code;
4484         goto refail;
4485     }
4486
4487     success = 1;
4488     fprintf(STDOUT, " done\n");
4489     fflush(STDOUT);
4490     if (success && (!reuseID || (flags & RV_FULLRST))) {
4491         /* Volume was restored on the file server, update the 
4492          * VLDB to reflect the change.
4493          */
4494         vcode = VLDB_GetEntryByID(pvolid, voltype, &entry);
4495         if (vcode && vcode != VL_NOENT && vcode != VL_ENTDELETED) {
4496             fprintf(STDERR,
4497                     "Could not fetch the entry for volume number %lu from VLDB \n",
4498                     (unsigned long)pvolid);
4499             error = vcode;
4500             goto refail;
4501         }
4502         if (!vcode)
4503             MapHostToNetwork(&entry);
4504         if (vcode == VL_NOENT) {        /* it doesnot exist already */
4505             /*make the vldb return this indication specifically */
4506             VPRINT("------- Creating a new VLDB entry ------- \n");
4507             strcpy(entry.name, tovolname);
4508             entry.nServers = 1;
4509             entry.serverNumber[0] = toserver;   /*should be indirect */
4510             entry.serverPartition[0] = topart;
4511             entry.serverFlags[0] = (flags & RV_RDONLY) ? ITSROVOL : ITSRWVOL;
4512             entry.flags = (flags & RV_RDONLY) ? RO_EXISTS : RW_EXISTS;
4513             if (flags & RV_RDONLY)
4514                 entry.volumeId[ROVOL] = pvolid;
4515             else if (tstatus.cloneID != 0) {
4516                 entry.volumeId[ROVOL] = tstatus.cloneID;        /*this should come from status info on the volume if non zero */
4517             } else
4518                 entry.volumeId[ROVOL] = INVALID_BID;
4519             entry.volumeId[RWVOL] = pparentid;
4520             entry.cloneId = 0;
4521             if (tstatus.backupID != 0) {
4522                 entry.volumeId[BACKVOL] = tstatus.backupID;
4523                 /*this should come from status info on the volume if non zero */
4524             } else
4525                 entry.volumeId[BACKVOL] = INVALID_BID;
4526             MapNetworkToHost(&entry, &storeEntry);
4527             vcode = VLDB_CreateEntry(&storeEntry);
4528             if (vcode) {
4529                 fprintf(STDERR,
4530                         "Could not create the VLDB entry for volume number %lu  \n",
4531                         (unsigned long)pvolid);
4532                 error = vcode;
4533                 goto refail;
4534             }
4535             islocked = 0;
4536             if (verbose)
4537                 EnumerateEntry(&entry);
4538         } else {                /*update the existing entry */
4539             if (verbose) {
4540                 fprintf(STDOUT, "Updating the existing VLDB entry\n");
4541                 fprintf(STDOUT, "------- Old entry -------\n");
4542                 EnumerateEntry(&entry);
4543                 fprintf(STDOUT, "------- New entry -------\n");
4544             }
4545             vcode =
4546                 ubik_VL_SetLock(cstruct, 0, pvolid, voltype,
4547                           VLOP_RESTORE);
4548             if (vcode) {
4549                 fprintf(STDERR,
4550                         "Could not lock the entry for volume number %lu \n",
4551                         (unsigned long)pvolid);
4552                 error = vcode;
4553                 goto refail;
4554             }
4555             islocked = 1;
4556             strcpy(entry.name, tovolname);
4557
4558             /* Update the vlentry with the new information */
4559             if (flags & RV_RDONLY)
4560                 index = Lp_ROMatch(toserver, topart, &entry) - 1;
4561             else
4562                 index = Lp_GetRwIndex(&entry);
4563             if (index == -1) {
4564                 /* Add the new site for the volume being restored */
4565                 entry.serverNumber[entry.nServers] = toserver;
4566                 entry.serverPartition[entry.nServers] = topart;
4567                 entry.serverFlags[entry.nServers] =
4568                     (flags & RV_RDONLY) ? ITSROVOL : ITSRWVOL;
4569                 entry.nServers++;
4570             } else {
4571                 /* This volume should be deleted on the old site
4572                  * if its different from new site.
4573                  */
4574                 same =
4575                     VLDB_IsSameAddrs(toserver, entry.serverNumber[index],
4576                                      &errcode);
4577                 if (errcode)
4578                     EPRINT2(errcode,
4579                             "Failed to get info about server's %d address(es) from vlserver (err=%d)\n",
4580                             toserver, errcode);
4581                 if ((!errcode && !same)
4582                     || (entry.serverPartition[index] != topart)) {
4583                     if (flags & RV_NODEL) {
4584                         VPRINT2
4585                             ("Not deleting the previous volume %u on server %s, ...",
4586                              pvolid,
4587                              noresolve ? afs_inet_ntoa_r(entry.serverNumber[index], hoststr) :
4588                              hostutil_GetNameByINet(entry.serverNumber[index]));
4589                     } else {
4590                         tempconn =
4591                             UV_Bind(entry.serverNumber[index],
4592                                     AFSCONF_VOLUMEPORT);
4593                         
4594                         MapPartIdIntoName(entry.serverPartition[index],
4595                                           apartName);
4596                         VPRINT3
4597                             ("Deleting the previous volume %u on server %s, partition %s ...",
4598                              pvolid,
4599                              noresolve ? afs_inet_ntoa_r(entry.serverNumber[index], hoststr) :
4600                              hostutil_GetNameByINet(entry.serverNumber[index]),
4601                              apartName);
4602                         code =
4603                             AFSVolTransCreate_retry(tempconn, pvolid,
4604                                               entry.serverPartition[index],
4605                                               ITOffline, &temptid);
4606                         if (!code) {
4607                             code =
4608                                 AFSVolSetFlags(tempconn, temptid,
4609                                                VTDeleteOnSalvage |
4610                                                VTOutOfService);
4611                             if (code) {
4612                                 fprintf(STDERR,
4613                                         "Could not set flags on volume %lu on the older site\n",
4614                                         (unsigned long)pvolid);
4615                                 error = code;
4616                                 goto refail;
4617                             }
4618                             code = AFSVolDeleteVolume(tempconn, temptid);
4619                             if (code) {
4620                                 fprintf(STDERR,
4621                                         "Could not delete volume %lu on the older site\n",
4622                                         (unsigned long)pvolid);
4623                                 error = code;
4624                                 goto refail;
4625                             }
4626                             code = AFSVolEndTrans(tempconn, temptid, &rcode);
4627                             temptid = 0;
4628                             if (!code)
4629                                 code = rcode;
4630                             if (code) {
4631                                 fprintf(STDERR,
4632                                         "Could not end transaction on volume %lu on the older site\n",
4633                                         (unsigned long)pvolid);
4634                                 error = code;
4635                                 goto refail;
4636                             }
4637                             VDONE;
4638                             MapPartIdIntoName(entry.serverPartition[index],
4639                                               partName);
4640                         }
4641                     }
4642                 }
4643                 entry.serverNumber[index] = toserver;
4644                 entry.serverPartition[index] = topart;
4645             }
4646
4647             entry.flags |= (flags & RV_RDONLY) ? RO_EXISTS : RW_EXISTS;
4648             MapNetworkToHost(&entry, &storeEntry);
4649             vcode =
4650                 VLDB_ReplaceEntry(pvolid, voltype, &storeEntry,
4651                                   LOCKREL_OPCODE | LOCKREL_AFSID |
4652                                   LOCKREL_TIMESTAMP);
4653             if (vcode) {
4654                 fprintf(STDERR,
4655                         "Could not update the entry for volume number %lu  \n",
4656                         (unsigned long)pvolid);
4657                 error = vcode;
4658                 goto refail;
4659             }
4660             islocked = 0;
4661             if (verbose)
4662                 EnumerateEntry(&entry);
4663         }
4664
4665
4666     }
4667   refail:
4668     if (tocall) {
4669         code = rx_EndCall(tocall, rxError);
4670         if (!error)
4671             error = code;
4672     }
4673     if (islocked) {
4674         vcode =
4675             ubik_VL_ReleaseLock(cstruct, 0, pvolid, voltype,
4676                       LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
4677         if (vcode) {
4678             fprintf(STDERR,
4679                     "Could not release lock on the VLDB entry for the volume %lu\n",
4680                     (unsigned long)pvolid);
4681             if (!error)
4682                 error = vcode;
4683         }
4684     }
4685     if (totid) {
4686         code = AFSVolEndTrans(toconn, totid, &rcode);
4687         if (!code)
4688             code = rcode;
4689         if (code) {
4690             fprintf(STDERR, "Could not end transaction on the volume %lu \n",
4691                     (unsigned long)pvolid);
4692             if (!error)
4693                 error = code;
4694         }
4695     }
4696     if (temptid) {
4697         code = AFSVolEndTrans(toconn, temptid, &rcode);
4698         if (!code)
4699             code = rcode;
4700         if (code) {
4701             fprintf(STDERR, "Could not end transaction on the volume %lu \n",
4702                     (unsigned long)pvolid);
4703             if (!error)
4704                 error = code;
4705         }
4706     }
4707     if (tempconn)
4708         rx_DestroyConnection(tempconn);
4709     if (toconn)
4710         rx_DestroyConnection(toconn);
4711     PrintError("", error);
4712     return error;
4713 }
4714
4715 int
4716 UV_RestoreVolume(afs_int32 toserver, afs_int32 topart, afs_uint32 tovolid,
4717                  char tovolname[], int flags,
4718                  afs_int32(*WriteData) (struct rx_call *, void *),
4719                  void *rock)
4720 {
4721     return UV_RestoreVolume2(toserver, topart, tovolid, 0, tovolname, flags,
4722                              WriteData, rock);
4723 }
4724
4725
4726 /*unlocks the vldb entry associated with <volid> */
4727 int
4728 UV_LockRelease(afs_uint32 volid)
4729 {
4730     afs_int32 vcode;
4731
4732     VPRINT("Binding to the VLDB server\n");
4733     vcode =
4734         ubik_VL_ReleaseLock(cstruct, 0, volid, -1,
4735                   LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
4736     if (vcode) {
4737         fprintf(STDERR,
4738                 "Could not unlock the entry for volume number %lu in VLDB \n",
4739                 (unsigned long)volid);
4740         PrintError("", vcode);
4741         return (vcode);
4742     }
4743     VPRINT("VLDB updated\n");
4744     return 0;
4745
4746 }
4747
4748 /* old interface to add rosites */
4749 int
4750 UV_AddSite(afs_int32 server, afs_int32 part, afs_uint32 volid,
4751            afs_int32 valid)
4752 {
4753     return UV_AddSite2(server, part, volid, 0, valid);
4754 }
4755
4756 /*adds <server> and <part> as a readonly replication site for <volid>
4757 *in vldb */
4758 int
4759 UV_AddSite2(afs_int32 server, afs_int32 part, afs_uint32 volid,
4760             afs_uint32 rovolid, afs_int32 valid)
4761 {
4762     int j, nro = 0, islocked = 0;
4763     struct nvldbentry entry, storeEntry, entry2;
4764     afs_int32 vcode, error = 0;
4765     char apartName[10];
4766
4767     error = ubik_VL_SetLock(cstruct, 0, volid, RWVOL, VLOP_ADDSITE);
4768     if (error) {
4769         fprintf(STDERR,
4770                 " Could not lock the VLDB entry for the volume %lu \n",
4771                 (unsigned long)volid);
4772         goto asfail;
4773     }
4774     islocked = 1;
4775
4776     error = VLDB_GetEntryByID(volid, RWVOL, &entry);
4777     if (error) {
4778         fprintf(STDERR,
4779                 "Could not fetch the VLDB entry for volume number %lu  \n",
4780                 (unsigned long)volid);
4781         goto asfail;
4782
4783     }
4784     if (!ISNAMEVALID(entry.name)) {
4785         fprintf(STDERR,
4786                 "Volume name %s is too long, rename before adding site\n",
4787                 entry.name);
4788         error = VOLSERBADOP;
4789         goto asfail;
4790     }
4791     MapHostToNetwork(&entry);
4792
4793     /* See if it's too many entries */
4794     if (entry.nServers >= NMAXNSERVERS) {
4795         fprintf(STDERR, "Total number of entries will exceed %u\n",
4796                 NMAXNSERVERS);
4797         error = VOLSERBADOP;
4798         goto asfail;
4799     }
4800
4801     /* See if it's on the same server */
4802     for (j = 0; j < entry.nServers; j++) {
4803         if (entry.serverFlags[j] & ITSROVOL) {
4804             nro++;
4805             if (VLDB_IsSameAddrs(server, entry.serverNumber[j], &error)) {
4806                 if (error) {
4807                     fprintf(STDERR,
4808                             "Failed to get info about server's %d address(es) from vlserver (err=%d); aborting call!\n",
4809                             server, error);
4810                 } else {
4811                     MapPartIdIntoName(entry.serverPartition[j], apartName);
4812                     fprintf(STDERR,
4813                             "RO already exists on partition %s. Multiple ROs on a single server aren't allowed\n",
4814                             apartName);
4815                     error = VOLSERBADOP;
4816                 }
4817                 goto asfail;
4818             }
4819         }
4820     }
4821
4822     /* See if it's too many RO sites - leave one for the RW */
4823     if (nro >= NMAXNSERVERS - 1) {
4824         fprintf(STDERR, "Total number of sites will exceed %u\n",
4825                 NMAXNSERVERS - 1);
4826         error = VOLSERBADOP;
4827         goto asfail;
4828     }
4829
4830     /* if rovolid == 0, we leave the RO volume id alone. If the volume doesn't
4831      * have an RO volid at this point (i.e. entry.volumeId[ROVOL] ==
4832      * INVALID_BID) and we leave it alone, it gets an RO volid at release-time.
4833      */
4834     if (rovolid) {
4835         if (entry.volumeId[ROVOL] == INVALID_BID) {
4836             vcode = VLDB_GetEntryByID(rovolid, -1, &entry2);
4837             if (!vcode) {
4838                 fprintf(STDERR, "Volume ID %d already exists\n", rovolid);
4839                 return VVOLEXISTS;
4840             }
4841             VPRINT1("Using RO volume id %d.\n", rovolid);
4842             entry.volumeId[ROVOL] = rovolid;
4843         } else {
4844             fprintf(STDERR, "Ignoring given RO id %d, since volume already has RO id %d\n",
4845                 rovolid, entry.volumeId[ROVOL]);
4846         }
4847     }
4848
4849     VPRINT("Adding a new site ...");
4850     entry.serverNumber[entry.nServers] = server;
4851     entry.serverPartition[entry.nServers] = part;
4852     if (!valid) {
4853         entry.serverFlags[entry.nServers] = (ITSROVOL | RO_DONTUSE);
4854     } else {
4855         entry.serverFlags[entry.nServers] = (ITSROVOL);
4856     }
4857     entry.nServers++;
4858
4859     MapNetworkToHost(&entry, &storeEntry);
4860     error =
4861         VLDB_ReplaceEntry(volid, RWVOL, &storeEntry,
4862                           LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
4863     if (error) {
4864         fprintf(STDERR, "Could not update entry for volume %lu \n",
4865                 (unsigned long)volid);
4866         goto asfail;
4867     }
4868     islocked = 0;
4869     VDONE;
4870
4871   asfail:
4872     if (islocked) {
4873         vcode =
4874             ubik_VL_ReleaseLock(cstruct, 0, volid, RWVOL,
4875                       LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
4876         if (vcode) {
4877             fprintf(STDERR,
4878                     "Could not release lock on volume entry for %lu \n",
4879                     (unsigned long)volid);
4880             PrintError("", vcode);
4881         }
4882     }
4883
4884     PrintError("", error);
4885     return error;
4886 }
4887
4888 /*removes <server> <part> as read only site for <volid> from the vldb */
4889 int
4890 UV_RemoveSite(afs_int32 server, afs_int32 part, afs_uint32 volid)
4891 {
4892     afs_int32 vcode;
4893     struct nvldbentry entry, storeEntry;
4894     int islocked;
4895
4896     vcode = ubik_VL_SetLock(cstruct, 0, volid, RWVOL, VLOP_ADDSITE);
4897     if (vcode) {
4898         fprintf(STDERR, " Could not lock the VLDB entry for volume %lu \n",
4899                 (unsigned long)volid);
4900         PrintError("", vcode);
4901         return (vcode);
4902     }
4903     islocked = 1;
4904     vcode = VLDB_GetEntryByID(volid, RWVOL, &entry);
4905     if (vcode) {
4906         fprintf(STDERR,
4907                 "Could not fetch the entry for volume number %lu from VLDB \n",
4908                 (unsigned long)volid);
4909         PrintError("", vcode);
4910         return (vcode);
4911     }
4912     MapHostToNetwork(&entry);
4913     if (!Lp_ROMatch(server, part, &entry)) {
4914         /*this site doesnot exist  */
4915         fprintf(STDERR, "This site is not a replication site \n");
4916         vcode =
4917             ubik_VL_ReleaseLock(cstruct, 0, volid, RWVOL,
4918                       LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
4919         if (vcode) {
4920             fprintf(STDERR, "Could not update entry for volume %lu \n",
4921                     (unsigned long)volid);
4922             PrintError("", vcode);
4923             ubik_VL_ReleaseLock(cstruct, 0, volid, RWVOL,
4924                       LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
4925             return (vcode);
4926         }
4927         return VOLSERBADOP;
4928     } else {                    /*remove the rep site */
4929         Lp_SetROValue(&entry, server, part, 0, 0);
4930         entry.nServers--;
4931         if ((entry.nServers == 1) && (entry.flags & RW_EXISTS))
4932             entry.flags &= ~RO_EXISTS;
4933         if (entry.nServers < 1) {       /*this is the last ref */
4934             VPRINT1("Deleting the VLDB entry for %u ...", volid);
4935             fflush(STDOUT);
4936             vcode = ubik_VL_DeleteEntry(cstruct, 0, volid, ROVOL);
4937             if (vcode) {
4938                 fprintf(STDERR,
4939                         "Could not delete VLDB entry for volume %lu \n",
4940                         (unsigned long)volid);
4941                 PrintError("", vcode);
4942                 return (vcode);
4943             }
4944             VDONE;
4945         }
4946         MapNetworkToHost(&entry, &storeEntry);
4947         fprintf(STDOUT, "Deleting the replication site for volume %lu ...",
4948                 (unsigned long)volid);
4949         fflush(STDOUT);
4950         vcode =
4951             VLDB_ReplaceEntry(volid, RWVOL, &storeEntry,
4952                               LOCKREL_OPCODE | LOCKREL_AFSID |
4953                               LOCKREL_TIMESTAMP);
4954         if (vcode) {
4955             fprintf(STDERR,
4956                     "Could not release lock on volume entry for %lu \n",
4957                     (unsigned long)volid);
4958             PrintError("", vcode);
4959             ubik_VL_ReleaseLock(cstruct, 0, volid, RWVOL,
4960                       LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
4961             return (vcode);
4962         }
4963         VDONE;
4964     }
4965     return 0;
4966 }
4967
4968 /*sets <server> <part> as read/write site for <volid> in the vldb */
4969 int
4970 UV_ChangeLocation(afs_int32 server, afs_int32 part, afs_uint32 volid)
4971 {
4972     afs_int32 vcode;
4973     struct nvldbentry entry, storeEntry;
4974     int index;
4975
4976     vcode = ubik_VL_SetLock(cstruct, 0, volid, RWVOL, VLOP_ADDSITE);
4977     if (vcode) {
4978         fprintf(STDERR, " Could not lock the VLDB entry for volume %lu \n",
4979                 (unsigned long)volid);
4980         PrintError("", vcode);
4981         return (vcode);
4982     }
4983     vcode = VLDB_GetEntryByID(volid, RWVOL, &entry);
4984     if (vcode) {
4985         fprintf(STDERR,
4986                 "Could not fetch the entry for volume number %lu from VLDB \n",
4987                 (unsigned long)volid);
4988         PrintError("", vcode);
4989         return (vcode);
4990     }
4991     MapHostToNetwork(&entry);
4992     index = Lp_GetRwIndex(&entry);
4993     if (index < 0) {
4994         /* no RW site exists  */
4995         fprintf(STDERR, "No existing RW site for volume %lu",
4996                 (unsigned long)volid);
4997         vcode =
4998             ubik_VL_ReleaseLock(cstruct, 0, volid, RWVOL,
4999                       LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
5000         if (vcode) {
5001             fprintf(STDERR,
5002                     "Could not release lock on entry for volume %lu \n",
5003                     (unsigned long)volid);
5004             PrintError("", vcode);
5005             return (vcode);
5006         }
5007         return VOLSERBADOP;
5008     } else {                    /* change the RW site */
5009         entry.serverNumber[index] = server;
5010         entry.serverPartition[index] = part;
5011         MapNetworkToHost(&entry, &storeEntry);
5012         vcode =
5013             VLDB_ReplaceEntry(volid, RWVOL, &storeEntry,
5014                               LOCKREL_OPCODE | LOCKREL_AFSID |
5015                               LOCKREL_TIMESTAMP);
5016         if (vcode) {
5017             fprintf(STDERR, "Could not update entry for volume %lu \n",
5018                     (unsigned long)volid);
5019             PrintError("", vcode);
5020             ubik_VL_ReleaseLock(cstruct, 0, volid, RWVOL,
5021                       LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
5022             return (vcode);
5023         }
5024         VDONE;
5025     }
5026     return 0;
5027 }
5028
5029 /*list all the partitions on <aserver> */
5030 int
5031 UV_ListPartitions(afs_int32 aserver, struct partList *ptrPartList,
5032                   afs_int32 * cntp)
5033 {
5034     struct rx_connection *aconn;
5035     struct pIDs partIds;
5036     struct partEntries partEnts;
5037     register int i, j = 0, code;
5038
5039     *cntp = 0;
5040     aconn = UV_Bind(aserver, AFSCONF_VOLUMEPORT);
5041
5042     partEnts.partEntries_len = 0;
5043     partEnts.partEntries_val = NULL;
5044     code = AFSVolXListPartitions(aconn, &partEnts);     /* this is available only on new servers */
5045     if (code == RXGEN_OPCODE) {
5046         for (i = 0; i < 26; i++)        /* try old interface */
5047             partIds.partIds[i] = -1;
5048         code = AFSVolListPartitions(aconn, &partIds);
5049         if (!code) {
5050             for (i = 0; i < 26; i++) {
5051                 if ((partIds.partIds[i]) != -1) {
5052                     ptrPartList->partId[j] = partIds.partIds[i];
5053                     ptrPartList->partFlags[j] = PARTVALID;
5054                     j++;
5055                 } else
5056                     ptrPartList->partFlags[i] = 0;
5057             }
5058             *cntp = j;
5059         }
5060     } else if (!code) {
5061         *cntp = partEnts.partEntries_len;
5062         if (*cntp > VOLMAXPARTS) {
5063             fprintf(STDERR,
5064                     "Warning: number of partitions on the server too high %d (process only %d)\n",
5065                     *cntp, VOLMAXPARTS);
5066             *cntp = VOLMAXPARTS;
5067         }
5068         for (i = 0; i < *cntp; i++) {
5069             ptrPartList->partId[i] = partEnts.partEntries_val[i];
5070             ptrPartList->partFlags[i] = PARTVALID;
5071         }
5072         free(partEnts.partEntries_val);
5073     }
5074
5075    /* out: */
5076     if (code)
5077         fprintf(STDERR,
5078                 "Could not fetch the list of partitions from the server\n");
5079     PrintError("", code);
5080     if (aconn)
5081         rx_DestroyConnection(aconn);
5082     return code;
5083 }
5084
5085
5086 /*zap the list of volumes specified by volPtrArray (the volCloneId field).
5087  This is used by the backup system */
5088 int
5089 UV_ZapVolumeClones(afs_int32 aserver, afs_int32 apart,
5090                    struct volDescription *volPtr, afs_int32 arraySize)
5091 {
5092     struct rx_connection *aconn;
5093     struct volDescription *curPtr;
5094     int curPos;
5095     afs_int32 code = 0;
5096     afs_int32 rcode = 0;
5097     afs_int32 success = 1;
5098     afs_int32 tid;
5099
5100     aconn = (struct rx_connection *)0;
5101     aconn = UV_Bind(aserver, AFSCONF_VOLUMEPORT);
5102     curPos = 0;
5103     for (curPtr = volPtr; curPos < arraySize; curPtr++) {
5104         if (curPtr->volFlags & CLONEVALID) {
5105             curPtr->volFlags &= ~CLONEZAPPED;
5106             success = 1;
5107             code =
5108                 AFSVolTransCreate_retry(aconn, curPtr->volCloneId, apart, ITOffline,
5109                                   &tid);
5110             if (code)
5111                 success = 0;
5112             else {
5113                 code = AFSVolDeleteVolume(aconn, tid);
5114                 if (code)
5115                     success = 0;
5116                 code = AFSVolEndTrans(aconn, tid, &rcode);
5117                 if (code || rcode)
5118                     success = 0;
5119             }
5120             if (success)
5121                 curPtr->volFlags |= CLONEZAPPED;
5122             if (!success)
5123                 fprintf(STDERR, "Could not zap volume %lu\n",
5124                         (unsigned long)curPtr->volCloneId);
5125             if (success)
5126                 VPRINT2("Clone of %s %u deleted\n", curPtr->volName,
5127                         curPtr->volCloneId);
5128             curPos++;
5129             tid = 0;
5130         }
5131     }
5132     if (aconn)
5133         rx_DestroyConnection(aconn);
5134     return 0;
5135 }
5136
5137 /*return a list of clones of the volumes specified by volPtrArray. Used by the 
5138  backup system */
5139 int
5140 UV_GenerateVolumeClones(afs_int32 aserver, afs_int32 apart,
5141                         struct volDescription *volPtr, afs_int32 arraySize)
5142 {
5143     struct rx_connection *aconn;
5144     struct volDescription *curPtr;
5145     int curPos;
5146     afs_int32 code = 0;
5147     afs_int32 rcode = 0;
5148     afs_int32 tid;
5149     int reuseCloneId = 0;
5150     afs_uint32 curCloneId = 0;
5151     char cloneName[256];        /*max vol name */
5152
5153     aconn = (struct rx_connection *)0;
5154     aconn = UV_Bind(aserver, AFSCONF_VOLUMEPORT);
5155     curPos = 0;
5156     if ((volPtr->volFlags & REUSECLONEID) && (volPtr->volFlags & ENTRYVALID))
5157         reuseCloneId = 1;
5158     else {                      /*get a bunch of id's from vldb */
5159         code =
5160             ubik_VL_GetNewVolumeId(cstruct, 0, arraySize, &curCloneId);
5161         if (code) {
5162             fprintf(STDERR, "Could not get ID's for the clone from VLDB\n");
5163             PrintError("", code);
5164             return code;
5165         }
5166     }
5167
5168     for (curPtr = volPtr; curPos < arraySize; curPtr++) {
5169         if (curPtr->volFlags & ENTRYVALID) {
5170
5171             curPtr->volFlags |= CLONEVALID;
5172             /*make a clone of curParentId and record as curPtr->volCloneId */
5173             code =
5174                 AFSVolTransCreate_retry(aconn, curPtr->volId, apart, ITOffline,
5175                                   &tid);
5176             if (code)
5177                 VPRINT2("Clone for volume %s %u failed \n", curPtr->volName,
5178                         curPtr->volId);
5179             if (code) {
5180                 curPtr->volFlags &= ~CLONEVALID;        /*cant clone */
5181                 curPos++;
5182                 continue;
5183             }
5184             if (strlen(curPtr->volName) < (VOLSER_OLDMAXVOLNAME - 9)) {
5185                 strcpy(cloneName, curPtr->volName);
5186                 strcat(cloneName, "-tmpClone-");
5187             } else
5188                 strcpy(cloneName, "-tmpClone");
5189             if (reuseCloneId) {
5190                 curPtr->volCloneId = curCloneId;
5191                 curCloneId++;
5192             }
5193
5194             code =
5195                 AFSVolClone(aconn, tid, 0, readonlyVolume, cloneName,
5196                             &(curPtr->volCloneId));
5197             if (code) {
5198                 curPtr->volFlags &= ~CLONEVALID;
5199                 curPos++;
5200                 fprintf(STDERR, "Could not clone %s due to error %lu\n",
5201                         curPtr->volName, (unsigned long)code);
5202                 code = AFSVolEndTrans(aconn, tid, &rcode);
5203                 if (code)
5204                     fprintf(STDERR, "WARNING: could not end transaction\n");
5205                 continue;
5206             }
5207             VPRINT2("********** Cloned %s temporary %u\n", cloneName,
5208                     curPtr->volCloneId);
5209             code = AFSVolEndTrans(aconn, tid, &rcode);
5210             if (code || rcode) {
5211                 curPtr->volFlags &= ~CLONEVALID;
5212                 curPos++;
5213                 continue;
5214             }
5215
5216             curPos++;
5217         }
5218     }
5219     if (aconn)
5220         rx_DestroyConnection(aconn);
5221     return 0;
5222 }
5223
5224
5225 /*list all the volumes on <aserver> and <apart>. If all = 1, then all the
5226 * relevant fields of the volume are also returned. This is a heavy weight operation.*/
5227 int
5228 UV_ListVolumes(afs_int32 aserver, afs_int32 apart, int all,
5229                struct volintInfo **resultPtr, afs_int32 * size)
5230 {
5231     struct rx_connection *aconn;
5232     afs_int32 code = 0;
5233     volEntries volumeInfo;
5234
5235     code = 0;
5236     *size = 0;
5237     *resultPtr = (volintInfo *) 0;
5238     volumeInfo.volEntries_val = (volintInfo *) 0;       /*this hints the stub to allocate space */
5239     volumeInfo.volEntries_len = 0;
5240
5241     aconn = UV_Bind(aserver, AFSCONF_VOLUMEPORT);
5242     code = AFSVolListVolumes(aconn, apart, all, &volumeInfo);
5243     if (code) {
5244         fprintf(STDERR,
5245                 "Could not fetch the list of volumes from the server\n");
5246     } else {
5247         *resultPtr = volumeInfo.volEntries_val;
5248         *size = volumeInfo.volEntries_len;
5249     }
5250
5251     if (aconn)
5252         rx_DestroyConnection(aconn);
5253     PrintError("", code);
5254     return code;
5255 }
5256
5257 /*------------------------------------------------------------------------
5258  * EXPORTED UV_XListVolumes
5259  *
5260  * Description:
5261  *      List the extended information for all the volumes on a particular
5262  *      File Server and partition.  We may either return the volume's ID
5263  *      or all of its extended information.
5264  *
5265  * Arguments:
5266  *      a_serverID         : Address of the File Server for which we want
5267  *                              extended volume info.
5268  *      a_partID           : Partition for which we want the extended
5269  *                              volume info.
5270  *      a_all              : If non-zero, fetch ALL the volume info,
5271  *                              otherwise just the volume ID.
5272  *      a_resultPP         : Ptr to the address of the area containing
5273  *                              the returned volume info.
5274  *      a_numEntsInResultP : Ptr for the value we set for the number of
5275  *                              entries returned.
5276  *
5277  * Returns:
5278  *      0 on success,
5279  *      Otherise, the return value of AFSVolXListVolumes.
5280  *
5281  * Environment:
5282  *      This routine is closely related to UV_ListVolumes, which returns
5283  *      only the standard level of detail on AFS volumes. It is a
5284  *      heavyweight operation, zipping through all the volume entries for
5285  *      a given server/partition.
5286  *
5287  * Side Effects:
5288  *      As advertised.
5289  *------------------------------------------------------------------------*/
5290
5291 int
5292 UV_XListVolumes(afs_int32 a_serverID, afs_int32 a_partID, int a_all,
5293                 struct volintXInfo **a_resultPP,
5294                 afs_int32 * a_numEntsInResultP)
5295 {
5296     struct rx_connection *rxConnP;      /*Ptr to the Rx connection involved */
5297     afs_int32 code;             /*Error code to return */
5298     volXEntries volumeXInfo;    /*Area for returned extended vol info */
5299
5300     /*
5301      * Set up our error code and the area for returned extended volume info.
5302      * We set the val field to a null pointer as a hint for the stub to
5303      * allocate space.
5304      */
5305     code = 0;
5306     *a_numEntsInResultP = 0;
5307     *a_resultPP = (volintXInfo *) 0;
5308     volumeXInfo.volXEntries_val = (volintXInfo *) 0;
5309     volumeXInfo.volXEntries_len = 0;
5310
5311     /*
5312      * Bind to the Volume Server port on the File Server machine in question,
5313      * then go for it.
5314      */
5315     rxConnP = UV_Bind(a_serverID, AFSCONF_VOLUMEPORT);
5316     code = AFSVolXListVolumes(rxConnP, a_partID, a_all, &volumeXInfo);
5317     if (code)
5318         fprintf(STDERR, "[UV_XListVolumes] Couldn't fetch volume list\n");
5319     else {
5320         /*
5321          * We got the info; pull out the pointer to where the results lie
5322          * and how many entries are there.
5323          */
5324         *a_resultPP = volumeXInfo.volXEntries_val;
5325         *a_numEntsInResultP = volumeXInfo.volXEntries_len;
5326     }
5327
5328     /*
5329      * If we got an Rx connection, throw it away.
5330      */
5331     if (rxConnP)
5332         rx_DestroyConnection(rxConnP);
5333
5334     PrintError("", code);
5335     return (code);
5336 }                               /*UV_XListVolumes */
5337
5338 /* get all the information about volume <volid> on <aserver> and <apart> */
5339 int
5340 UV_ListOneVolume(afs_int32 aserver, afs_int32 apart, afs_uint32 volid,
5341                  struct volintInfo **resultPtr)
5342 {
5343     struct rx_connection *aconn;
5344     afs_int32 code = 0;
5345     volEntries volumeInfo;
5346
5347     code = 0;
5348
5349     *resultPtr = (volintInfo *) 0;
5350     volumeInfo.volEntries_val = (volintInfo *) 0;       /*this hints the stub to allocate space */
5351     volumeInfo.volEntries_len = 0;
5352
5353     aconn = UV_Bind(aserver, AFSCONF_VOLUMEPORT);
5354     code = AFSVolListOneVolume(aconn, apart, volid, &volumeInfo);
5355     if (code) {
5356         fprintf(STDERR,
5357                 "Could not fetch the information about volume %lu from the server\n",
5358                 (unsigned long)volid);
5359     } else {
5360         *resultPtr = volumeInfo.volEntries_val;
5361
5362     }
5363
5364     if (aconn)
5365         rx_DestroyConnection(aconn);
5366     PrintError("", code);
5367     return code;
5368 }
5369
5370 /*------------------------------------------------------------------------
5371  * EXPORTED UV_XListOneVolume
5372  *
5373  * Description:
5374  *      List the extended information for a volume on a particular File
5375  *      Server and partition.
5376  *
5377  * Arguments:
5378  *      a_serverID         : Address of the File Server for which we want
5379  *                              extended volume info.
5380  *      a_partID           : Partition for which we want the extended
5381  *                              volume info.
5382  *      a_volID            : Volume ID for which we want the info.
5383  *      a_resultPP         : Ptr to the address of the area containing
5384  *                              the returned volume info.
5385  *
5386  * Returns:
5387  *      0 on success,
5388  *      Otherise, the return value of AFSVolXListOneVolume.
5389  *
5390  * Environment:
5391  *      This routine is closely related to UV_ListOneVolume, which returns
5392  *      only the standard level of detail on the chosen AFS volume.
5393  *
5394  * Side Effects:
5395  *      As advertised.
5396  *------------------------------------------------------------------------*/
5397
5398 int
5399 UV_XListOneVolume(afs_int32 a_serverID, afs_int32 a_partID, afs_uint32 a_volID,
5400                   struct volintXInfo **a_resultPP)
5401 {
5402     struct rx_connection *rxConnP;      /*Rx connection to Volume Server */
5403     afs_int32 code;             /*Error code */
5404     volXEntries volumeXInfo;    /*Area for returned info */
5405
5406     /*
5407      * Set up our error code, and the area we're in which we are returning
5408      * the info.  Setting the val field to a null pointer tells the stub
5409      * to allocate space for us.
5410      */
5411     code = 0;
5412     *a_resultPP = (volintXInfo *) 0;
5413     volumeXInfo.volXEntries_val = (volintXInfo *) 0;
5414     volumeXInfo.volXEntries_len = 0;
5415
5416     /*
5417      * Bind to the Volume Server port on the File Server machine in question,
5418      * then go for it.
5419      */
5420     rxConnP = UV_Bind(a_serverID, AFSCONF_VOLUMEPORT);
5421     code = AFSVolXListOneVolume(rxConnP, a_partID, a_volID, &volumeXInfo);
5422     if (code)
5423         fprintf(STDERR,
5424                 "[UV_XListOneVolume] Couldn't fetch the volume information\n");
5425     else
5426         /*
5427          * We got the info; pull out the pointer to where the results lie.
5428          */
5429         *a_resultPP = volumeXInfo.volXEntries_val;
5430
5431     /*
5432      * If we got an Rx connection, throw it away.
5433      */
5434     if (rxConnP)
5435         rx_DestroyConnection(rxConnP);
5436
5437     PrintError("", code);
5438     return code;
5439 }
5440
5441 /* CheckVolume()
5442  *    Given a volume we read from a partition, check if it is 
5443  *    represented in the VLDB correctly.
5444  * 
5445  *    The VLDB is looked up by the RW volume id (not its name).
5446  *    The RW contains the true name of the volume (BK and RO set
5447  *       the name in the VLDB only on creation of the VLDB entry).
5448  *    We want rules strict enough that when we check all volumes
5449  *       on one partition, it does not need to be done again. IE:
5450  *       two volumes on different partitions won't constantly 
5451  *       change a VLDB entry away from what the other set.
5452  *    For RW and BK volumes, we will always check the VLDB to see 
5453  *       if the two exist on the server/partition. May seem redundant,
5454  *       but this is an easy check of the VLDB. IE: if the VLDB entry
5455  *       says the BK exists but no BK volume is there, we will detect
5456  *       this when we check the RW volume.
5457  *    VLDB entries are locked only when a change needs to be done.
5458  *    Output changed to look a lot like the "vos syncserv" otuput.
5459  */
5460 static afs_int32
5461 CheckVolume(volintInfo * volumeinfo, afs_int32 aserver, afs_int32 apart,
5462             afs_int32 * modentry, afs_uint32 * maxvolid)
5463 {
5464     int idx = 0;
5465     int j;
5466     afs_int32 code, error = 0;
5467     struct nvldbentry entry, storeEntry;
5468     char pname[10];
5469     int pass = 0, islocked = 0, createentry, addvolume, modified, mod, doit = 1;
5470     afs_uint32 rwvolid;
5471     char hoststr[16]; 
5472
5473     if (modentry) {
5474         if (*modentry == 1)
5475             doit = 0;
5476         *modentry = 0;
5477     }
5478     rwvolid =
5479         ((volumeinfo->type ==
5480           RWVOL) ? volumeinfo->volid : volumeinfo->parentID);
5481
5482   retry:
5483     /* Check to see if the VLDB is ok without locking it (pass 1).
5484      * If it will change, then lock the VLDB entry, read it again,
5485      * then make the changes to it (pass 2).
5486      */
5487     if (++pass == 2) {
5488         code = ubik_VL_SetLock(cstruct, 0, rwvolid, RWVOL, VLOP_DELETE);
5489         if (code) {
5490             fprintf(STDERR, "Could not lock VLDB entry for %lu\n",
5491                     (unsigned long)rwvolid);
5492             ERROR_EXIT(code);
5493         }
5494         islocked = 1;
5495     }
5496
5497     createentry = 0;            /* Do we need to create a VLDB entry */
5498     addvolume = 0;              /* Add this volume to the VLDB entry */
5499     modified = 0;               /* The VLDB entry was modified */
5500
5501     /* Read the entry from VLDB by its RW volume id */
5502     code = VLDB_GetEntryByID(rwvolid, RWVOL, &entry);
5503     if (code) {
5504         if (code != VL_NOENT) {
5505             fprintf(STDOUT,
5506                     "Could not retreive the VLDB entry for volume %lu \n",
5507                     (unsigned long)rwvolid);
5508             ERROR_EXIT(code);
5509         }
5510
5511         memset(&entry, 0, sizeof(entry));
5512         vsu_ExtractName(entry.name, volumeinfo->name);  /* Store name of RW */
5513
5514         createentry = 1;
5515     } else {
5516         MapHostToNetwork(&entry);
5517     }
5518
5519     if (verbose && (pass == 1)) {
5520         fprintf(STDOUT, "_______________________________\n");
5521         fprintf(STDOUT, "\n-- status before -- \n");
5522         if (createentry) {
5523             fprintf(STDOUT, "\n**does not exist**\n");
5524         } else {
5525             if ((entry.flags & RW_EXISTS) || (entry.flags & RO_EXISTS)
5526                 || (entry.flags & BACK_EXISTS))
5527                 EnumerateEntry(&entry);
5528         }
5529         fprintf(STDOUT, "\n");
5530     }
5531
5532     if (volumeinfo->type == RWVOL) {    /* RW volume exists */
5533         if (createentry) {
5534             idx = 0;
5535             entry.nServers = 1;
5536             addvolume++;
5537         } else {
5538             /* Check existence of RW and BK volumes */
5539             code = CheckVldbRWBK(&entry, &mod);
5540             if (code)
5541                 ERROR_EXIT(code);
5542             if (mod)
5543                 modified++;
5544
5545             idx = Lp_GetRwIndex(&entry);
5546             if (idx == -1) {    /* RW index not found in the VLDB entry */
5547                 idx = entry.nServers;   /* put it into next index */
5548                 entry.nServers++;
5549                 addvolume++;
5550             } else {            /* RW index found in the VLDB entry. */
5551                 /* Verify if this volume's location matches where the VLDB says it is */
5552                 if (!Lp_Match(aserver, apart, &entry)) {
5553                     if (entry.flags & RW_EXISTS) {
5554                         /* The RW volume exists elsewhere - report this one a duplicate */
5555                         if (pass == 1) {
5556                             MapPartIdIntoName(apart, pname);
5557                             fprintf(STDERR,
5558                                     "*** Warning: Orphaned RW volume %lu exists on %s %s\n",
5559                                     (unsigned long)rwvolid,
5560                                     noresolve ?
5561                                     afs_inet_ntoa_r(aserver, hoststr) :
5562                                     hostutil_GetNameByINet(aserver), pname);
5563                             MapPartIdIntoName(entry.serverPartition[idx],
5564                                               pname);
5565                             fprintf(STDERR,
5566                                     "    VLDB reports RW volume %lu exists on %s %s\n",
5567                                     (unsigned long)rwvolid,
5568                                     noresolve ? 
5569                                     afs_inet_ntoa_r(entry.serverNumber[idx], hoststr) :
5570                                     hostutil_GetNameByINet(entry.
5571                                                            serverNumber[idx]),
5572                                     pname);
5573                         }
5574                     } else {
5575                         /* The RW volume does not exist - have VLDB point to this one */
5576                         addvolume++;
5577
5578                         /* Check for orphaned BK volume on old partition */
5579                         if (entry.flags & BACK_EXISTS) {
5580                             if (pass == 1) {
5581                                 MapPartIdIntoName(entry.serverPartition[idx],
5582                                                   pname);
5583                                 fprintf(STDERR,
5584                                         "*** Warning: Orphaned BK volume %u exists on %s %s\n",
5585                                         entry.volumeId[BACKVOL],
5586                                         noresolve ?
5587                                         afs_inet_ntoa_r(entry.serverNumber[idx], hoststr) :
5588                                         hostutil_GetNameByINet(entry.
5589                                                                serverNumber
5590                                                                [idx]), pname);
5591                                 MapPartIdIntoName(apart, pname);
5592                                 fprintf(STDERR,
5593                                         "    VLDB reports its RW volume %lu exists on %s %s\n",
5594                                         (unsigned long)rwvolid,
5595                                         noresolve ? 
5596                                         afs_inet_ntoa_r(aserver, hoststr) :
5597                                         hostutil_GetNameByINet(aserver),
5598                                         pname);
5599                             }
5600                         }
5601                     }
5602                 } else {
5603                     /* Volume location matches the VLDB location */
5604                     if ((volumeinfo->backupID && !entry.volumeId[BACKVOL])
5605                         || (volumeinfo->cloneID && !entry.volumeId[ROVOL])
5606                         ||
5607                         (strncmp
5608                          (entry.name, volumeinfo->name,
5609                           VOLSER_OLDMAXVOLNAME) != 0)) {
5610                         addvolume++;
5611                     }
5612                 }
5613             }
5614         }
5615
5616         if (addvolume) {
5617             entry.flags |= RW_EXISTS;
5618             entry.volumeId[RWVOL] = rwvolid;
5619             if (!entry.volumeId[BACKVOL])
5620                 entry.volumeId[BACKVOL] = volumeinfo->backupID;
5621             if (!entry.volumeId[ROVOL])
5622                 entry.volumeId[ROVOL] = volumeinfo->cloneID;
5623
5624             entry.serverFlags[idx] = ITSRWVOL;
5625             entry.serverNumber[idx] = aserver;
5626             entry.serverPartition[idx] = apart;
5627             strncpy(entry.name, volumeinfo->name, VOLSER_OLDMAXVOLNAME);
5628
5629             modified++;
5630
5631             /* One last check - to update BK if need to */
5632             code = CheckVldbRWBK(&entry, &mod);
5633             if (code)
5634                 ERROR_EXIT(code);
5635             if (mod)
5636                 modified++;
5637         }
5638     }
5639
5640     else if (volumeinfo->type == BACKVOL) {     /* A BK volume */
5641         if (createentry) {
5642             idx = 0;
5643             entry.nServers = 1;
5644             addvolume++;
5645         } else {
5646             /* Check existence of RW and BK volumes */
5647             code = CheckVldbRWBK(&entry, &mod);
5648             if (code)
5649                 ERROR_EXIT(code);
5650             if (mod)
5651                 modified++;
5652
5653             idx = Lp_GetRwIndex(&entry);
5654             if (idx == -1) {    /* RW index not found in the VLDB entry */
5655                 idx = entry.nServers;   /* Put it into next index */
5656                 entry.nServers++;
5657                 addvolume++;
5658             } else {            /* RW index found in the VLDB entry */
5659                 /* Verify if this volume's location matches where the VLDB says it is */
5660                 if (!Lp_Match(aserver, apart, &entry)) {
5661                     /* VLDB says RW and/or BK is elsewhere - report this BK volume orphaned */
5662                     if (pass == 1) {
5663                         MapPartIdIntoName(apart, pname);
5664                         fprintf(STDERR,
5665                                 "*** Warning: Orphaned BK volume %lu exists on %s %s\n",
5666                                 (unsigned long)volumeinfo->volid,
5667                                 noresolve ?
5668                                 afs_inet_ntoa_r(aserver, hoststr) :
5669                                 hostutil_GetNameByINet(aserver), pname);
5670                         MapPartIdIntoName(entry.serverPartition[idx], pname);
5671                         fprintf(STDERR,
5672                                 "    VLDB reports its RW/BK volume %lu exists on %s %s\n",
5673                                 (unsigned long)rwvolid,
5674                                 noresolve ?
5675                                 afs_inet_ntoa_r(entry.serverNumber[idx], hoststr) :
5676                                 hostutil_GetNameByINet(entry.
5677                                                        serverNumber[idx]),
5678                                 pname);
5679                     }
5680                 } else {
5681                     if (volumeinfo->volid != entry.volumeId[BACKVOL]) {
5682                         if (!(entry.flags & BACK_EXISTS)) {
5683                             addvolume++;
5684                         } else if (volumeinfo->volid >
5685                                    entry.volumeId[BACKVOL]) {
5686                             addvolume++;
5687
5688                             if (pass == 1) {
5689                                 MapPartIdIntoName(entry.serverPartition[idx],
5690                                                   pname);
5691                                 fprintf(STDERR,
5692                                         "*** Warning: Orphaned BK volume %u exists on %s %s\n",
5693                                         entry.volumeId[BACKVOL],
5694                                         noresolve ?
5695                                         afs_inet_ntoa_r(aserver, hoststr) :
5696                                         hostutil_GetNameByINet(aserver),
5697                                         pname);
5698                                 fprintf(STDERR,
5699                                         "    VLDB reports its BK volume ID is %lu\n",
5700                                         (unsigned long)volumeinfo->volid);
5701                             }
5702                         } else {
5703                             if (pass == 1) {
5704                                 MapPartIdIntoName(entry.serverPartition[idx],
5705                                                   pname);
5706                                 fprintf(STDERR,
5707                                         "*** Warning: Orphaned BK volume %lu exists on %s %s\n",
5708                                         (unsigned long)volumeinfo->volid,
5709                                         noresolve ?
5710                                         afs_inet_ntoa_r(aserver, hoststr) :
5711                                         hostutil_GetNameByINet(aserver),
5712                                         pname);
5713                                 fprintf(STDERR,
5714                                         "    VLDB reports its BK volume ID is %u\n",
5715                                         entry.volumeId[BACKVOL]);
5716                             }
5717                         }
5718                     } else if (!entry.volumeId[BACKVOL]) {
5719                         addvolume++;
5720                     }
5721                 }
5722             }
5723         }
5724         if (addvolume) {
5725             entry.flags |= BACK_EXISTS;
5726             entry.volumeId[RWVOL] = rwvolid;
5727             entry.volumeId[BACKVOL] = volumeinfo->volid;
5728
5729             entry.serverNumber[idx] = aserver;
5730             entry.serverPartition[idx] = apart;
5731             entry.serverFlags[idx] = ITSBACKVOL;
5732
5733             modified++;
5734         }
5735     }
5736
5737     else if (volumeinfo->type == ROVOL) {       /* A RO volume */
5738         if (volumeinfo->volid == entry.volumeId[ROVOL]) {
5739             /* This is a quick check to see if the RO entry exists in the 
5740              * VLDB so we avoid the CheckVldbRO() call (which checks if each
5741              * RO volume listed in the VLDB exists).
5742              */
5743             idx = Lp_ROMatch(aserver, apart, &entry) - 1;
5744             if (idx == -1) {
5745                 idx = entry.nServers;
5746                 entry.nServers++;
5747                 addvolume++;
5748             } else {
5749                 if (!(entry.flags & RO_EXISTS)) {
5750                     addvolume++;
5751                 }
5752             }
5753         } else {
5754             /* Before we correct the VLDB entry, make sure all the
5755              * ROs listed in the VLDB exist.
5756              */
5757             code = CheckVldbRO(&entry, &mod);
5758             if (code)
5759                 ERROR_EXIT(code);
5760             if (mod)
5761                 modified++;
5762
5763             if (!(entry.flags & RO_EXISTS)) {
5764                 /* No RO exists in the VLDB entry - add this one */
5765                 idx = entry.nServers;
5766                 entry.nServers++;
5767                 addvolume++;
5768             } else if (volumeinfo->volid > entry.volumeId[ROVOL]) {
5769                 /* The volume headers's RO ID does not match that in the VLDB entry,
5770                  * and the vol hdr's ID is greater (implies more recent). So delete
5771                  * all the RO volumes listed in VLDB entry and add this volume.
5772                  */
5773                 for (j = 0; j < entry.nServers; j++) {
5774                     if (entry.serverFlags[j] & ITSROVOL) {
5775                         /* Verify this volume exists and print message we are orphaning it */
5776                         if (pass == 1) {
5777                             MapPartIdIntoName(apart, pname);
5778                             fprintf(STDERR,
5779                                     "*** Warning: Orphaned RO volume %u exists on %s %s\n",
5780                                     entry.volumeId[ROVOL],
5781                                     noresolve ?
5782                                     afs_inet_ntoa_r(entry.serverNumber[j], hoststr) :
5783                                     hostutil_GetNameByINet(entry.
5784                                                            serverNumber[j]),
5785                                     pname);
5786                             fprintf(STDERR,
5787                                     "    VLDB reports its RO volume ID is %lu\n",
5788                                     (unsigned long)volumeinfo->volid);
5789                         }
5790
5791                         Lp_SetRWValue(&entry, entry.serverNumber[idx],
5792                                       entry.serverPartition[idx], 0L, 0L);
5793                         entry.nServers--;
5794                         modified++;
5795                         j--;
5796                     }
5797                 }
5798
5799                 idx = entry.nServers;
5800                 entry.nServers++;
5801                 addvolume++;
5802             } else if (volumeinfo->volid < entry.volumeId[ROVOL]) {
5803                 /* The volume headers's RO ID does not match that in the VLDB entry,
5804                  * and the vol hdr's ID is lower (implies its older). So orphan it.
5805                  */
5806                 if (pass == 1) {
5807                     MapPartIdIntoName(apart, pname);
5808                     fprintf(STDERR,
5809                             "*** Warning: Orphaned RO volume %lu exists on %s %s\n",
5810                             (unsigned long)volumeinfo->volid,
5811                             noresolve ?
5812                             afs_inet_ntoa_r(aserver, hoststr) :
5813                             hostutil_GetNameByINet(aserver), pname);
5814                     fprintf(STDERR,
5815                             "    VLDB reports its RO volume ID is %u\n",
5816                             entry.volumeId[ROVOL]);
5817                 }
5818             } else {
5819                 /* The RO volume ID in the volume header match that in the VLDB entry,
5820                  * and there exist RO volumes in the VLDB entry. See if any of them
5821                  * are this one. If not, then we add it.
5822                  */
5823                 idx = Lp_ROMatch(aserver, apart, &entry) - 1;
5824                 if (idx == -1) {
5825                     idx = entry.nServers;
5826                     entry.nServers++;
5827                     addvolume++;
5828                 }
5829             }
5830         }
5831
5832         if (addvolume) {
5833             entry.flags |= RO_EXISTS;
5834             entry.volumeId[RWVOL] = rwvolid;
5835             entry.volumeId[ROVOL] = volumeinfo->volid;
5836
5837             entry.serverNumber[idx] = aserver;
5838             entry.serverPartition[idx] = apart;
5839             entry.serverFlags[idx] = ITSROVOL;
5840
5841             modified++;
5842         }
5843     }
5844
5845     /* Remember largest volume id */
5846     if (entry.volumeId[ROVOL] > *maxvolid)
5847         *maxvolid = entry.volumeId[ROVOL];
5848     if (entry.volumeId[BACKVOL] > *maxvolid)
5849         *maxvolid = entry.volumeId[BACKVOL];
5850     if (entry.volumeId[RWVOL] > *maxvolid)
5851         *maxvolid = entry.volumeId[RWVOL];
5852
5853     if (modified && doit) {
5854         MapNetworkToHost(&entry, &storeEntry);
5855
5856         if (createentry) {
5857             code = VLDB_CreateEntry(&storeEntry);
5858             if (code) {
5859                 fprintf(STDOUT,
5860                         "Could not create a VLDB entry for the volume %lu\n",
5861                         (unsigned long)rwvolid);
5862                 ERROR_EXIT(code);
5863             }
5864         } else {
5865             if (pass == 1)
5866                 goto retry;
5867             code =
5868                 VLDB_ReplaceEntry(rwvolid, RWVOL, &storeEntry,
5869                                   LOCKREL_OPCODE | LOCKREL_AFSID |
5870                                   LOCKREL_TIMESTAMP);
5871             if (code) {
5872                 fprintf(STDERR, "Could not update entry for %lu\n",
5873                         (unsigned long)rwvolid);
5874                 ERROR_EXIT(code);
5875             }
5876         }
5877         if (modentry)
5878             *modentry = modified;
5879     } else if (pass == 2) {
5880         code =
5881             ubik_VL_ReleaseLock(cstruct, 0, rwvolid, RWVOL,
5882                       LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
5883         if (code) {
5884             PrintError("Could not unlock VLDB entry ", code);
5885         }
5886     }
5887
5888     if (verbose && doit) {
5889         fprintf(STDOUT, "-- status after --\n");
5890         if (modified)
5891             EnumerateEntry(&entry);
5892         else
5893             fprintf(STDOUT, "\n**no change**\n");
5894     }
5895
5896   error_exit:
5897     VPRINT("\n_______________________________\n");
5898     return (error);
5899 }
5900
5901 int
5902 sortVolumes(const void *a, const void *b)
5903 {
5904     volintInfo *v1 = (volintInfo *) a;
5905     volintInfo *v2 = (volintInfo *) b;
5906     afs_uint32 rwvolid1, rwvolid2;
5907
5908     rwvolid1 = ((v1->type == RWVOL) ? v1->volid : v1->parentID);
5909     rwvolid2 = ((v2->type == RWVOL) ? v2->volid : v2->parentID);
5910
5911     if (rwvolid1 > rwvolid2)
5912         return -1;              /* lower RW id goes first */
5913     if (rwvolid1 < rwvolid2)
5914         return 1;
5915
5916     if (v1->type == RWVOL)
5917         return -1;              /* RW vols go first */
5918     if (v2->type == RWVOL)
5919         return 1;
5920
5921     if ((v1->type == BACKVOL) && (v2->type == ROVOL))
5922         return -1;              /* BK vols next */
5923     if ((v1->type == ROVOL) && (v2->type == BACKVOL))
5924         return 1;
5925
5926     if (v1->volid < v2->volid)
5927         return 1;               /* larger volids first */
5928     if (v1->volid > v2->volid)
5929         return -1;
5930     return 0;
5931 }
5932
5933 /* UV_SyncVolume()
5934  *      Synchronise <aserver> <apart>(if flags = 1) <avolid>.
5935  *      Synchronize an individual volume against a sever and partition.
5936  *      Checks the VLDB entry (similar to syncserv) as well as checks
5937  *      if the volume exists on specified servers (similar to syncvldb).
5938  */
5939 int
5940 UV_SyncVolume(afs_int32 aserver, afs_int32 apart, char *avolname, int flags)
5941 {
5942     struct rx_connection *aconn = 0;
5943     afs_int32 j, k, code, vcode, error = 0;
5944     afs_int32 tverbose;
5945     afs_int32 mod, modified = 0;
5946     struct nvldbentry vldbentry;
5947     afs_uint32 volumeid = 0;
5948     volEntries volumeInfo;
5949     struct partList PartList;
5950     afs_int32 pcnt, rv;
5951     afs_uint32 maxvolid = 0;
5952
5953     volumeInfo.volEntries_val = (volintInfo *) 0;
5954     volumeInfo.volEntries_len = 0;
5955
5956     /* Turn verbose logging off and do our own verbose logging */
5957     /* tverbose must be set before we call ERROR_EXIT() */
5958     
5959     tverbose = verbose;
5960     if (flags & 2) 
5961         tverbose = 1;
5962     verbose = 0;
5963
5964     if (!aserver && (flags & 1)) {
5965         /* fprintf(STDERR,"Partition option requires a server option\n"); */
5966         ERROR_EXIT(EINVAL);
5967     }
5968
5969     /* Read the VLDB entry */
5970     vcode = VLDB_GetEntryByName(avolname, &vldbentry);
5971     if (vcode && (vcode != VL_NOENT)) {
5972         fprintf(STDERR, "Could not access the VLDB for volume %s\n",
5973                 avolname);
5974         ERROR_EXIT(vcode);
5975     } else if (!vcode) {
5976         MapHostToNetwork(&vldbentry);
5977     }
5978
5979     if (tverbose) {
5980         fprintf(STDOUT, "Processing VLDB entry %s ...\n", avolname);
5981         fprintf(STDOUT, "_______________________________\n");
5982         fprintf(STDOUT, "\n-- status before -- \n");
5983         if (vcode) {
5984             fprintf(STDOUT, "\n**does not exist**\n");
5985         } else {
5986             if ((vldbentry.flags & RW_EXISTS) || (vldbentry.flags & RO_EXISTS)
5987                 || (vldbentry.flags & BACK_EXISTS))
5988                 EnumerateEntry(&vldbentry);
5989         }
5990         fprintf(STDOUT, "\n");
5991     }
5992
5993     /* Verify that all of the VLDB entries exist on the repective servers 
5994      * and partitions (this does not require that avolname be a volume ID).
5995      * Equivalent to a syncserv.
5996      */
5997     if (!vcode) {
5998         /* Tell CheckVldb not to update if appropriate */
5999         if (flags & 2)
6000             mod = 1;
6001         else
6002             mod = 0;
6003         code = CheckVldb(&vldbentry, &mod);
6004         if (code) {
6005             fprintf(STDERR, "Could not process VLDB entry for volume %s\n",
6006                     vldbentry.name);
6007             ERROR_EXIT(code);
6008         }
6009         if (mod)
6010             modified++;
6011     }
6012
6013     /* If aserver is given, we will search for the desired volume on it */
6014     if (aserver) {
6015         /* Generate array of partitions on the server that we will check */
6016         if (!(flags & 1)) {
6017             code = UV_ListPartitions(aserver, &PartList, &pcnt);
6018             if (code) {
6019                 fprintf(STDERR,
6020                         "Could not fetch the list of partitions from the server\n");
6021                 ERROR_EXIT(code);
6022             }
6023         } else {
6024             PartList.partId[0] = apart;
6025             pcnt = 1;
6026         }
6027
6028         aconn = UV_Bind(aserver, AFSCONF_VOLUMEPORT);
6029
6030         /* If a volume ID were given, search for it on each partition */
6031         if ((volumeid = atol(avolname))) {
6032             for (j = 0; j < pcnt; j++) {
6033                 code =
6034                     AFSVolListOneVolume(aconn, PartList.partId[j], volumeid,
6035                                         &volumeInfo);
6036                 if (code) {
6037                     if (code != ENODEV) {
6038                         fprintf(STDERR, "Could not query server\n");
6039                         ERROR_EXIT(code);
6040                     }
6041                 } else {
6042                     if (flags & 2)
6043                         mod = 1;
6044                     else
6045                         mod = 0;
6046                     /* Found one, sync it with VLDB entry */
6047                     code =
6048                         CheckVolume(volumeInfo.volEntries_val, aserver,
6049                                     PartList.partId[j], &mod, &maxvolid);
6050                     if (code)
6051                         ERROR_EXIT(code);
6052                     if (mod)
6053                         modified++;
6054                 }
6055
6056                 if (volumeInfo.volEntries_val)
6057                     free(volumeInfo.volEntries_val);
6058                 volumeInfo.volEntries_val = (volintInfo *) 0;
6059                 volumeInfo.volEntries_len = 0;
6060             }
6061         }
6062
6063         /* Check to see if the RW, BK, and RO IDs exist on any
6064          * partitions. We get the volume IDs from the VLDB.
6065          */
6066         rv = 1;                 /* Read the VLDB entry ? */
6067         for (j = 0; j < MAXTYPES; j++) {        /* for RW, RO, and BK IDs */
6068             if (rv) {
6069                 vcode = VLDB_GetEntryByName(avolname, &vldbentry);
6070                 if (vcode) {
6071                     if (vcode == VL_NOENT)
6072                         break;
6073                     fprintf(STDERR,
6074                             "Could not access the VLDB for volume %s\n",
6075                             avolname);
6076                     ERROR_EXIT(vcode);
6077                 }
6078                 rv = 0;
6079             }
6080
6081             if (vldbentry.volumeId[j] == 0)
6082                 continue;
6083
6084             for (k = 0; k < pcnt; k++) {        /* For each partition */
6085                 volumeInfo.volEntries_val = (volintInfo *) 0;
6086                 volumeInfo.volEntries_len = 0;
6087                 code =
6088                     AFSVolListOneVolume(aconn, PartList.partId[k],
6089                                         vldbentry.volumeId[j], &volumeInfo);
6090                 if (code) {
6091                     if (code != ENODEV) {
6092                         fprintf(STDERR, "Could not query server\n");
6093                         ERROR_EXIT(code);
6094                     }
6095                 } else {
6096                     if (flags & 2)
6097                         mod = 1;
6098                     else
6099                         mod = 0;
6100                     /* Found one, sync it with VLDB entry */
6101                     code =
6102                         CheckVolume(volumeInfo.volEntries_val, aserver,
6103                                     PartList.partId[k], &mod, &maxvolid);
6104                     if (code)
6105                         ERROR_EXIT(code);
6106                     if (mod)
6107                         modified++, rv++;
6108                 }
6109
6110                 if (volumeInfo.volEntries_val)
6111                     free(volumeInfo.volEntries_val);
6112                 volumeInfo.volEntries_val = (volintInfo *) 0;
6113                 volumeInfo.volEntries_len = 0;
6114             }
6115         }
6116     }
6117
6118     /* if (aserver) */
6119     /* If verbose output, print a summary of what changed */
6120     if (tverbose && !(flags & 2)) {
6121         fprintf(STDOUT, "-- status after --\n");
6122         code = VLDB_GetEntryByName(avolname, &vldbentry);
6123         if (code && (code != VL_NOENT)) {
6124             fprintf(STDERR, "Could not access the VLDB for volume %s\n",
6125                     avolname);
6126             ERROR_EXIT(code);
6127         }
6128         if (modified && (code == VL_NOENT)) {
6129             fprintf(STDOUT, "\n**entry deleted**\n");
6130         } else if (modified) {
6131             EnumerateEntry(&vldbentry);
6132         } else {
6133             fprintf(STDOUT, "\n**no change**\n");
6134         }
6135         fprintf(STDOUT, "\n_______________________________\n");
6136     }
6137
6138   error_exit:
6139     /* Now check if the maxvolid is larger than that stored in the VLDB */
6140     if (maxvolid) {
6141         afs_uint32 maxvldbid = 0;
6142         code = ubik_VL_GetNewVolumeId(cstruct, 0, 0, &maxvldbid);
6143         if (code) {
6144             fprintf(STDERR,
6145                     "Could not get the highest allocated volume id from the VLDB\n");
6146             if (!error)
6147                 error = code;
6148         } else if (maxvolid > maxvldbid) {
6149             afs_uint32 id, nid;
6150             id = maxvolid - maxvldbid + 1;
6151             code = ubik_VL_GetNewVolumeId(cstruct, 0, id, &nid);
6152             if (code) {
6153                 fprintf(STDERR,
6154                         "Error in increasing highest allocated volume id in VLDB\n");
6155                 if (!error)
6156                     error = code;
6157             }
6158         }
6159     }
6160
6161     verbose = tverbose;
6162     if (verbose) {
6163         if (error)
6164             fprintf(STDOUT, "...error encountered");
6165         else
6166             fprintf(STDOUT, "...done entry\n");
6167     }
6168     if (aconn)
6169         rx_DestroyConnection(aconn);
6170     if (volumeInfo.volEntries_val)
6171         free(volumeInfo.volEntries_val);
6172
6173     PrintError("", error);
6174     return error;
6175 }
6176
6177 /* UV_SyncVldb()
6178  *      Synchronise vldb with the file server <aserver> and,
6179  *      optionally, <apart>.
6180  */
6181 int
6182 UV_SyncVldb(afs_int32 aserver, afs_int32 apart, int flags, int force)
6183 {
6184     struct rx_connection *aconn;
6185     afs_int32 code, error = 0;
6186     int i, pfail;
6187     unsigned int j;
6188     volEntries volumeInfo;
6189     struct partList PartList;
6190     afs_int32 pcnt;
6191     char pname[10];
6192     volintInfo *vi;
6193     afs_int32 failures = 0, modifications = 0, tentries = 0;
6194     afs_int32 modified;
6195     afs_uint32 maxvolid = 0;
6196     char hoststr[16];
6197
6198     volumeInfo.volEntries_val = (volintInfo *) 0;
6199     volumeInfo.volEntries_len = 0;
6200
6201     aconn = UV_Bind(aserver, AFSCONF_VOLUMEPORT);
6202
6203     /* Generate array of partitions to check */
6204     if (!(flags & 1)) {
6205         code = UV_ListPartitions(aserver, &PartList, &pcnt);
6206         if (code) {
6207             fprintf(STDERR,
6208                     "Could not fetch the list of partitions from the server\n");
6209             ERROR_EXIT(code);
6210         }
6211     } else {
6212         PartList.partId[0] = apart;
6213         pcnt = 1;
6214     }
6215
6216     VPRINT("Processing volume entries ...\n");
6217
6218     /* Step through the array of partitions */
6219     for (i = 0; i < pcnt; i++) {
6220         apart = PartList.partId[i];
6221         MapPartIdIntoName(apart, pname);
6222
6223         volumeInfo.volEntries_val = (volintInfo *) 0;
6224         volumeInfo.volEntries_len = 0;
6225         code = AFSVolListVolumes(aconn, apart, 1, &volumeInfo);
6226         if (code) {
6227             fprintf(STDERR,
6228                     "Could not fetch the list of volumes from the server\n");
6229             ERROR_EXIT(code);
6230         }
6231
6232         /* May want to sort the entries: RW, BK (high to low), RO (high to low) */
6233         qsort((char *)volumeInfo.volEntries_val, volumeInfo.volEntries_len,
6234               sizeof(volintInfo), sortVolumes);
6235
6236         pfail = 0;
6237         for (vi = volumeInfo.volEntries_val, j = 0;
6238              j < volumeInfo.volEntries_len; j++, vi++) {
6239             if (!vi->status)
6240                 continue;
6241
6242             tentries++;
6243
6244             if (verbose) {
6245                 fprintf(STDOUT,
6246                         "Processing volume entry %d: %s (%lu) on server %s %s...\n",
6247                         j + 1, vi->name, (unsigned long)vi->volid,
6248                         noresolve ?
6249                         afs_inet_ntoa_r(aserver, hoststr) :
6250                         hostutil_GetNameByINet(aserver), pname);
6251                 fflush(STDOUT);
6252             }
6253
6254             if (flags & 2)
6255                 modified = 1;
6256             else
6257                 modified = 0;
6258             code = CheckVolume(vi, aserver, apart, &modified, &maxvolid);
6259             if (code) {
6260                 PrintError("", code);
6261                 failures++;
6262                 pfail++;
6263             } else if (modified) {
6264                 modifications++;
6265             }
6266
6267             if (verbose) {
6268                 if (code) {
6269                     fprintf(STDOUT, "...error encountered\n\n");
6270                 } else {
6271                     fprintf(STDOUT, "...done entry %d\n\n", j + 1);
6272                 }
6273             }
6274         }
6275
6276         if (pfail) {
6277             fprintf(STDERR,
6278                     "Could not process entries on server %s partition %s\n",
6279                     noresolve ?
6280                     afs_inet_ntoa_r(aserver, hoststr) :
6281                     hostutil_GetNameByINet(aserver), pname);
6282         }
6283         if (volumeInfo.volEntries_val) {
6284             free(volumeInfo.volEntries_val);
6285             volumeInfo.volEntries_val = 0;
6286         }
6287
6288     }                           /* thru all partitions */
6289
6290     if (flags & 2) {
6291         VPRINT3("Total entries: %u, Failed to process %d, Would change %d\n", 
6292                 tentries, failures, modifications);
6293     } else {
6294         VPRINT3("Total entries: %u, Failed to process %d, Changed %d\n", 
6295                 tentries, failures, modifications);
6296     }
6297
6298   error_exit:
6299     /* Now check if the maxvolid is larger than that stored in the VLDB */
6300     if (maxvolid) {
6301         afs_uint32 maxvldbid = 0;
6302         code = ubik_VL_GetNewVolumeId(cstruct, 0, 0, &maxvldbid);
6303         if (code) {
6304             fprintf(STDERR,
6305                     "Could not get the highest allocated volume id from the VLDB\n");
6306             if (!error)
6307                 error = code;
6308         } else if (maxvolid > maxvldbid) {
6309             afs_uint32 id, nid;
6310             id = maxvolid - maxvldbid + 1;
6311             code = ubik_VL_GetNewVolumeId(cstruct, 0, id, &nid);
6312             if (code) {
6313                 fprintf(STDERR,
6314                         "Error in increasing highest allocated volume id in VLDB\n");
6315                 if (!error)
6316                     error = code;
6317             }
6318         }
6319     }
6320
6321     if (aconn)
6322         rx_DestroyConnection(aconn);
6323     if (volumeInfo.volEntries_val)
6324         free(volumeInfo.volEntries_val);
6325     PrintError("", error);
6326     return (error);
6327 }
6328
6329 /* VolumeExists()
6330  *      Determine if a volume exists on a server and partition.
6331  *      Try creating a transaction on the volume. If we can,
6332  *      the volume exists, if not, then return the error code.
6333  *      Some error codes mean the volume is unavailable but
6334  *      still exists - so we catch these error codes.
6335  */
6336 afs_int32
6337 VolumeExists(afs_int32 server, afs_int32 partition, afs_uint32 volumeid)
6338 {
6339     struct rx_connection *conn = (struct rx_connection *)0;
6340     afs_int32 code = -1;
6341     volEntries volumeInfo;
6342
6343     conn = UV_Bind(server, AFSCONF_VOLUMEPORT);
6344     if (conn) {
6345         volumeInfo.volEntries_val = (volintInfo *) 0;
6346         volumeInfo.volEntries_len = 0;
6347         code = AFSVolListOneVolume(conn, partition, volumeid, &volumeInfo);
6348         if (volumeInfo.volEntries_val)
6349             free(volumeInfo.volEntries_val);
6350         if (code == VOLSERILLEGAL_PARTITION)
6351             code = ENODEV;
6352         rx_DestroyConnection(conn);
6353     }
6354     return code;
6355 }
6356
6357 /* CheckVldbRWBK()
6358  *
6359  */
6360 afs_int32
6361 CheckVldbRWBK(struct nvldbentry * entry, afs_int32 * modified)
6362 {
6363     int modentry = 0;
6364     int idx;
6365     afs_int32 code, error = 0;
6366     char pname[10];
6367     char hoststr[16];
6368
6369     if (modified)
6370         *modified = 0;
6371     idx = Lp_GetRwIndex(entry);
6372
6373     /* Check to see if the RW volume exists and set the RW_EXISTS
6374      * flag accordingly.
6375      */
6376     if (idx == -1) {            /* Did not find a RW entry */
6377         if (entry->flags & RW_EXISTS) { /* ... yet entry says RW exists */
6378             entry->flags &= ~RW_EXISTS; /* ... so say RW does not exist */
6379             modentry++;
6380         }
6381     } else {
6382         code =
6383             VolumeExists(entry->serverNumber[idx],
6384                          entry->serverPartition[idx], entry->volumeId[RWVOL]);
6385         if (code == 0) {        /* RW volume exists */
6386             if (!(entry->flags & RW_EXISTS)) {  /* ... yet entry says RW does not exist */
6387                 entry->flags |= RW_EXISTS;      /* ... so say RW does exist */
6388                 modentry++;
6389             }
6390         } else if (code == ENODEV) {    /* RW volume does not exist */
6391             if (entry->flags & RW_EXISTS) {     /* ... yet entry says RW exists */
6392                 entry->flags &= ~RW_EXISTS;     /* ... so say RW does not exist */
6393                 modentry++;
6394             }
6395         } else {
6396             /* If VLDB says it didn't exist, then ignore error */
6397             if (entry->flags & RW_EXISTS) {
6398                 MapPartIdIntoName(entry->serverPartition[idx], pname);
6399                 fprintf(STDERR,
6400                         "Transaction call failed for RW volume %u on server %s %s\n",
6401                         entry->volumeId[RWVOL],
6402                         noresolve ?
6403                         afs_inet_ntoa_r(entry->serverNumber[idx], hoststr) :
6404                         hostutil_GetNameByINet(entry->serverNumber[idx]),
6405                         pname);
6406                 ERROR_EXIT(code);
6407             }
6408         }
6409     }
6410
6411     /* Check to see if the BK volume exists and set the BACK_EXISTS
6412      * flag accordingly. idx already ponts to the RW entry.
6413      */
6414     if (idx == -1) {            /* Did not find a RW entry */
6415         if (entry->flags & BACK_EXISTS) {       /* ... yet entry says BK exists */
6416             entry->flags &= ~BACK_EXISTS;       /* ... so say BK does not exist */
6417             modentry++;
6418         }
6419     } else {                    /* Found a RW entry */
6420         code =
6421             VolumeExists(entry->serverNumber[idx],
6422                          entry->serverPartition[idx],
6423                          entry->volumeId[BACKVOL]);
6424         if (code == 0) {        /* BK volume exists */
6425             if (!(entry->flags & BACK_EXISTS)) {        /* ... yet entry says BK does not exist */
6426                 entry->flags |= BACK_EXISTS;    /* ... so say BK does exist */
6427                 modentry++;
6428             }
6429         } else if (code == ENODEV) {    /* BK volume does not exist */
6430             if (entry->flags & BACK_EXISTS) {   /* ... yet entry says BK exists */
6431                 entry->flags &= ~BACK_EXISTS;   /* ... so say BK does not exist */
6432                 modentry++;
6433             }
6434         } else {
6435             /* If VLDB says it didn't exist, then ignore error */
6436             if (entry->flags & BACK_EXISTS) {
6437                 MapPartIdIntoName(entry->serverPartition[idx], pname);
6438                 fprintf(STDERR,
6439                         "Transaction call failed for BK volume %u on server %s %s\n",
6440                         entry->volumeId[BACKVOL],
6441                         noresolve ?
6442                         afs_inet_ntoa_r(entry->serverNumber[idx], hoststr) :
6443                         hostutil_GetNameByINet(entry->serverNumber[idx]),
6444                         pname);
6445                 ERROR_EXIT(code);
6446             }
6447         }
6448     }
6449
6450     /* If there is an idx but the BK and RW volumes no
6451      * longer exist, then remove the RW entry.
6452      */
6453     if ((idx != -1) && !(entry->flags & RW_EXISTS)
6454         && !(entry->flags & BACK_EXISTS)) {
6455         Lp_SetRWValue(entry, entry->serverNumber[idx],
6456                       entry->serverPartition[idx], 0L, 0L);
6457         entry->nServers--;
6458         modentry++;
6459     }
6460
6461   error_exit:
6462     if (modified)
6463         *modified = modentry;
6464     return (error);
6465 }
6466
6467 int
6468 CheckVldbRO(struct nvldbentry *entry, afs_int32 * modified)
6469 {
6470     int idx;
6471     int foundro = 0, modentry = 0;
6472     afs_int32 code, error = 0;
6473     char pname[10];
6474     char hoststr[16];
6475
6476     if (modified)
6477         *modified = 0;
6478
6479     /* Check to see if the RO volumes exist and set the RO_EXISTS
6480      * flag accordingly. 
6481      */
6482     for (idx = 0; idx < entry->nServers; idx++) {
6483         if (!(entry->serverFlags[idx] & ITSROVOL)) {
6484             continue;           /* not a RO */
6485         }
6486
6487         code =
6488             VolumeExists(entry->serverNumber[idx],
6489                          entry->serverPartition[idx], entry->volumeId[ROVOL]);
6490         if (code == 0) {        /* RO volume exists */
6491             foundro++;
6492         } else if (code == ENODEV) {    /* RW volume does not exist */
6493             Lp_SetROValue(entry, entry->serverNumber[idx],
6494                           entry->serverPartition[idx], 0L, 0L);
6495             entry->nServers--;
6496             idx--;
6497             modentry++;
6498         } else {
6499             MapPartIdIntoName(entry->serverPartition[idx], pname);
6500             fprintf(STDERR,
6501                     "Transaction call failed for RO %u on server %s %s\n",
6502                     entry->volumeId[ROVOL],
6503                     noresolve ?
6504                     afs_inet_ntoa_r(entry->serverNumber[idx], hoststr) :
6505                     hostutil_GetNameByINet(entry->serverNumber[idx]), pname);
6506             ERROR_EXIT(code);
6507         }
6508     }
6509
6510     if (foundro) {              /* A RO volume exists */
6511         if (!(entry->flags & RO_EXISTS)) {      /* ... yet entry says RW does not exist */
6512             entry->flags |= RO_EXISTS;  /* ... so say RW does exist */
6513             modentry++;
6514         }
6515     } else {                    /* A RO volume does not exist */
6516         if (entry->flags & RO_EXISTS) { /* ... yet entry says RO exists */
6517             entry->flags &= ~RO_EXISTS; /* ... so say RO does not exist */
6518             modentry++;
6519         }
6520     }
6521
6522   error_exit:
6523     if (modified)
6524         *modified = modentry;
6525     return (error);
6526 }
6527
6528 /* CheckVldb()
6529  *      Ensure that <entry> matches with the info on file servers
6530  */
6531 afs_int32
6532 CheckVldb(struct nvldbentry * entry, afs_int32 * modified)
6533 {
6534     afs_int32 code, error = 0;
6535     struct nvldbentry storeEntry;
6536     int islocked = 0, mod, modentry, delentry = 0;
6537     int pass = 0, doit=1;
6538
6539     if (modified) {
6540         if (*modified == 1) 
6541             doit = 0;
6542         *modified = 0;
6543     }
6544     if (verbose) {
6545         fprintf(STDOUT, "_______________________________\n");
6546         fprintf(STDOUT, "\n-- status before -- \n");
6547         if ((entry->flags & RW_EXISTS) || (entry->flags & RO_EXISTS)
6548             || (entry->flags & BACK_EXISTS))
6549             EnumerateEntry(entry);
6550         fprintf(STDOUT, "\n");
6551     }
6552
6553     if (strlen(entry->name) > (VOLSER_OLDMAXVOLNAME - 10)) {
6554         fprintf(STDERR, "Volume name %s exceeds limit of %d characters\n",
6555                 entry->name, VOLSER_OLDMAXVOLNAME - 10);
6556     }
6557
6558   retry:
6559     /* Check to see if the VLDB is ok without locking it (pass 1).
6560      * If it will change, then lock the VLDB entry, read it again,
6561      * then make the changes to it (pass 2).
6562      */
6563     if (++pass == 2) {
6564         code =
6565             ubik_VL_SetLock(cstruct, 0, entry->volumeId[RWVOL], RWVOL,
6566                       VLOP_DELETE);
6567         if (code) {
6568             fprintf(STDERR, "Could not lock VLDB entry for %u \n",
6569                     entry->volumeId[RWVOL]);
6570             ERROR_EXIT(code);
6571         }
6572         islocked = 1;
6573
6574         code = VLDB_GetEntryByID(entry->volumeId[RWVOL], RWVOL, entry);
6575         if (code) {
6576             fprintf(STDERR, "Could not read VLDB entry for volume %s\n",
6577                     entry->name);
6578             ERROR_EXIT(code);
6579         } else {
6580             MapHostToNetwork(entry);
6581         }
6582     }
6583
6584     modentry = 0;
6585
6586     /* Check if the RW and BK entries are ok */
6587     code = CheckVldbRWBK(entry, &mod);
6588     if (code)
6589         ERROR_EXIT(code);
6590     if (mod && (pass == 1) && doit)
6591         goto retry;
6592     if (mod)
6593         modentry++;
6594
6595     /* Check if the RO volumes entries are ok */
6596     code = CheckVldbRO(entry, &mod);
6597     if (code)
6598         ERROR_EXIT(code);
6599     if (mod && (pass == 1) && doit)
6600         goto retry;
6601     if (mod)
6602         modentry++;
6603
6604     /* The VLDB entry has been updated. If it as been modified, then 
6605      * write the entry back out the the VLDB.
6606      */
6607     if (modentry && doit) {
6608         if (pass == 1)
6609             goto retry;
6610
6611         if (!(entry->flags & RW_EXISTS) && !(entry->flags & BACK_EXISTS)
6612             && !(entry->flags & RO_EXISTS) && doit) {
6613             /* The RW, BK, nor RO volumes do not exist. Delete the VLDB entry */
6614             code =
6615                 ubik_VL_DeleteEntry(cstruct, 0, entry->volumeId[RWVOL],
6616                           RWVOL);
6617             if (code) {
6618                 fprintf(STDERR,
6619                         "Could not delete VLDB entry for volume %u \n",
6620                         entry->volumeId[RWVOL]);
6621                 ERROR_EXIT(code);
6622             }
6623             delentry = 1;
6624         } else {
6625             /* Replace old entry with our new one */
6626             MapNetworkToHost(entry, &storeEntry);
6627             code =
6628                 VLDB_ReplaceEntry(entry->volumeId[RWVOL], RWVOL, &storeEntry,
6629                                   (LOCKREL_OPCODE | LOCKREL_AFSID |
6630                                    LOCKREL_TIMESTAMP));
6631             if (code) {
6632                 fprintf(STDERR, "Could not update VLDB entry for volume %u\n",
6633                         entry->volumeId[RWVOL]);
6634                 ERROR_EXIT(code);
6635             }
6636         }
6637         if (modified)
6638             *modified = 1;
6639         islocked = 0;
6640     }
6641
6642     if (verbose && doit) {
6643         fprintf(STDOUT, "-- status after --\n");
6644         if (delentry)
6645             fprintf(STDOUT, "\n**entry deleted**\n");
6646         else if (modentry)
6647             EnumerateEntry(entry);
6648         else
6649             fprintf(STDOUT, "\n**no change**\n");
6650     }
6651
6652   error_exit:
6653     VPRINT("\n_______________________________\n");
6654
6655     if (islocked) {
6656         code =
6657             ubik_VL_ReleaseLock(cstruct, 0, entry->volumeId[RWVOL],
6658                       RWVOL,
6659                       (LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP));
6660         if (code) {
6661             fprintf(STDERR,
6662                     "Could not release lock on VLDB entry for volume %u\n",
6663                     entry->volumeId[RWVOL]);
6664             if (!error)
6665                 error = code;
6666         }
6667     }
6668     return error;
6669 }
6670
6671 /* UV_SyncServer()
6672  *      Synchronise <aserver> <apart>(if flags = 1) with the VLDB.
6673  */
6674 int
6675 UV_SyncServer(afs_int32 aserver, afs_int32 apart, int flags, int force)
6676 {
6677     struct rx_connection *aconn;
6678     afs_int32 code, error = 0;
6679     afs_int32 nentries, tentries = 0;
6680     struct VldbListByAttributes attributes;
6681     nbulkentries arrayEntries;
6682     afs_int32 failures = 0, modified, modifications = 0;
6683     struct nvldbentry *vlentry;
6684     afs_int32 si, nsi, j;
6685
6686     if (flags & 2) 
6687         verbose = 1;
6688
6689     aconn = UV_Bind(aserver, AFSCONF_VOLUMEPORT);
6690
6691     /* Set up attributes to search VLDB  */
6692     attributes.server = ntohl(aserver);
6693     attributes.Mask = VLLIST_SERVER;
6694     if ((flags & 1)) {
6695         attributes.partition = apart;
6696         attributes.Mask |= VLLIST_PARTITION;
6697     }
6698
6699     VPRINT("Processing VLDB entries ...\n");
6700
6701     /* While we need to collect more VLDB entries */
6702     for (si = 0; si != -1; si = nsi) {
6703         memset(&arrayEntries, 0, sizeof(arrayEntries));
6704
6705         /* Collect set of VLDB entries */
6706         code =
6707             VLDB_ListAttributesN2(&attributes, 0, si, &nentries,
6708                                   &arrayEntries, &nsi);
6709         if (code == RXGEN_OPCODE) {
6710             code = VLDB_ListAttributes(&attributes, &nentries, &arrayEntries);
6711             nsi = -1;
6712         }
6713         if (code) {
6714             fprintf(STDERR, "Could not access the VLDB for attributes\n");
6715             ERROR_EXIT(code);
6716         }
6717         tentries += nentries;
6718
6719         for (j = 0; j < nentries; j++) {
6720             vlentry = &arrayEntries.nbulkentries_val[j];
6721             MapHostToNetwork(vlentry);
6722
6723             VPRINT1("Processing VLDB entry %d ...\n", j + 1);
6724
6725             /* Tell CheckVldb not to update if appropriate */
6726             if (flags & 2)
6727                 modified = 1;
6728             else
6729                 modified = 0;
6730             code = CheckVldb(vlentry, &modified);
6731             if (code) {
6732                 PrintError("", code);
6733                 fprintf(STDERR,
6734                         "Could not process VLDB entry for volume %s\n",
6735                         vlentry->name);
6736                 failures++;
6737             } else if (modified) {
6738                 modifications++;
6739             }
6740
6741             if (verbose) {
6742                 if (code) {
6743                     fprintf(STDOUT, "...error encountered\n\n");
6744                 } else {
6745                     fprintf(STDOUT, "...done entry %d\n\n", j + 1);
6746                 }
6747             }
6748         }
6749
6750         if (arrayEntries.nbulkentries_val) {
6751             free(arrayEntries.nbulkentries_val);
6752             arrayEntries.nbulkentries_val = 0;
6753         }
6754     }
6755
6756     if (flags & 2) {
6757         VPRINT3("Total entries: %u, Failed to process %d, Would change %d\n",
6758                 tentries, failures, modifications);
6759     } else {
6760         VPRINT3("Total entries: %u, Failed to process %d, Changed %d\n", 
6761                 tentries, failures, modifications);
6762     }
6763
6764   error_exit:
6765     if (aconn)
6766         rx_DestroyConnection(aconn);
6767     if (arrayEntries.nbulkentries_val)
6768         free(arrayEntries.nbulkentries_val);
6769
6770     if (failures)
6771         error = VOLSERFAILEDOP;
6772     return error;
6773 }
6774
6775 /*rename volume <oldname> to <newname>, changing the names of the related 
6776  *readonly and backup volumes. This operation is also idempotent.
6777  *salvager is capable of recovering from rename operation stopping halfway.
6778  *to recover run syncserver on the affected machines,it will force renaming to completion. name clashes should have been detected before calling this proc */
6779 int
6780 UV_RenameVolume(struct nvldbentry *entry, char oldname[], char newname[])
6781 {
6782     struct nvldbentry storeEntry;
6783     afs_int32 vcode, code, rcode, error;
6784     int i, index;
6785     char nameBuffer[256];
6786     afs_int32 tid;
6787     struct rx_connection *aconn;
6788     int islocked;
6789     char hoststr[16];
6790
6791     error = 0;
6792     aconn = (struct rx_connection *)0;
6793     tid = 0;
6794     islocked = 0;
6795
6796     vcode = ubik_VL_SetLock(cstruct, 0, entry->volumeId[RWVOL], RWVOL, VLOP_ADDSITE);   /*last param is dummy */
6797     if (vcode) {
6798         fprintf(STDERR,
6799                 " Could not lock the VLDB entry for the  volume %u \n",
6800                 entry->volumeId[RWVOL]);
6801         error = vcode;
6802         goto rvfail;
6803     }
6804     islocked = 1;
6805     strncpy(entry->name, newname, VOLSER_OLDMAXVOLNAME);
6806     MapNetworkToHost(entry, &storeEntry);
6807     vcode = VLDB_ReplaceEntry(entry->volumeId[RWVOL], RWVOL, &storeEntry, 0);
6808     if (vcode) {
6809         fprintf(STDERR, "Could not update VLDB entry for %u\n",
6810                 entry->volumeId[RWVOL]);
6811         error = vcode;
6812         goto rvfail;
6813     }
6814     VPRINT1("Recorded the new name %s in VLDB\n", newname);
6815     /*at this stage the intent to rename is recorded in the vldb, as far as the vldb 
6816      * is concerned, oldname is lost */
6817     if (entry->flags & RW_EXISTS) {
6818         index = Lp_GetRwIndex(entry);
6819         if (index == -1) {      /* there is a serious discrepancy */
6820             fprintf(STDERR,
6821                     "There is a serious discrepancy in VLDB entry for volume %u\n",
6822                     entry->volumeId[RWVOL]);
6823             fprintf(STDERR, "try building VLDB from scratch\n");
6824             error = VOLSERVLDB_ERROR;
6825             goto rvfail;
6826         }
6827         aconn = UV_Bind(entry->serverNumber[index], AFSCONF_VOLUMEPORT);
6828         code =
6829             AFSVolTransCreate_retry(aconn, entry->volumeId[RWVOL],
6830                               entry->serverPartition[index], ITOffline, &tid);
6831         if (code) {             /*volume doesnot exist */
6832             fprintf(STDERR,
6833                     "Could not start transaction on the rw volume %u\n",
6834                     entry->volumeId[RWVOL]);
6835             error = code;
6836             goto rvfail;
6837         } else {                /*volume exists, process it */
6838
6839             code =
6840                 AFSVolSetIdsTypes(aconn, tid, newname, RWVOL,
6841                                   entry->volumeId[RWVOL],
6842                                   entry->volumeId[ROVOL],
6843                                   entry->volumeId[BACKVOL]);
6844             if (!code) {
6845                 VPRINT2("Renamed rw volume %s to %s\n", oldname, newname);
6846                 code = AFSVolEndTrans(aconn, tid, &rcode);
6847                 tid = 0;
6848                 if (code) {
6849                     fprintf(STDERR,
6850                             "Could not  end transaction on volume %s %u\n",
6851                             entry->name, entry->volumeId[RWVOL]);
6852                     error = code;
6853                     goto rvfail;
6854                 }
6855             } else {
6856                 fprintf(STDERR, "Could not  set parameters on volume %s %u\n",
6857                         entry->name, entry->volumeId[RWVOL]);
6858                 error = code;
6859                 goto rvfail;
6860             }
6861         }
6862         if (aconn)
6863             rx_DestroyConnection(aconn);
6864         aconn = (struct rx_connection *)0;
6865     }
6866     /*end rw volume processing */
6867     if (entry->flags & BACK_EXISTS) {   /*process the backup volume */
6868         index = Lp_GetRwIndex(entry);
6869         if (index == -1) {      /* there is a serious discrepancy */
6870             fprintf(STDERR,
6871                     "There is a serious discrepancy in the VLDB entry for the backup volume %u\n",
6872                     entry->volumeId[BACKVOL]);
6873             fprintf(STDERR, "try building VLDB from scratch\n");
6874             error = VOLSERVLDB_ERROR;
6875             goto rvfail;
6876         }
6877         aconn = UV_Bind(entry->serverNumber[index], AFSCONF_VOLUMEPORT);
6878         code =
6879             AFSVolTransCreate_retry(aconn, entry->volumeId[BACKVOL],
6880                               entry->serverPartition[index], ITOffline, &tid);
6881         if (code) {             /*volume doesnot exist */
6882             fprintf(STDERR,
6883                     "Could not start transaction on the backup volume  %u\n",
6884                     entry->volumeId[BACKVOL]);
6885             error = code;
6886             goto rvfail;
6887         } else {                /*volume exists, process it */
6888             if (strlen(newname) > (VOLSER_OLDMAXVOLNAME - 8)) {
6889                 fprintf(STDERR,
6890                         "Volume name %s.backup exceeds the limit of %u characters\n",
6891                         newname, VOLSER_OLDMAXVOLNAME);
6892                 error = code;
6893                 goto rvfail;
6894             }
6895             strcpy(nameBuffer, newname);
6896             strcat(nameBuffer, ".backup");
6897
6898             code =
6899                 AFSVolSetIdsTypes(aconn, tid, nameBuffer, BACKVOL,
6900                                   entry->volumeId[RWVOL], 0, 0);
6901             if (!code) {
6902                 VPRINT1("Renamed backup volume to %s \n", nameBuffer);
6903                 code = AFSVolEndTrans(aconn, tid, &rcode);
6904                 tid = 0;
6905                 if (code) {
6906                     fprintf(STDERR,
6907                             "Could not  end transaction on the backup volume %u\n",
6908                             entry->volumeId[BACKVOL]);
6909                     error = code;
6910                     goto rvfail;
6911                 }
6912             } else {
6913                 fprintf(STDERR,
6914                         "Could not  set parameters on the backup volume %u\n",
6915                         entry->volumeId[BACKVOL]);
6916                 error = code;
6917                 goto rvfail;
6918             }
6919         }
6920     }                           /* end backup processing */
6921     if (aconn)
6922         rx_DestroyConnection(aconn);
6923     aconn = (struct rx_connection *)0;
6924     if (entry->flags & RO_EXISTS) {     /*process the ro volumes */
6925         for (i = 0; i < entry->nServers; i++) {
6926             if (entry->serverFlags[i] & ITSROVOL) {
6927                 aconn = UV_Bind(entry->serverNumber[i], AFSCONF_VOLUMEPORT);
6928                 code =
6929                     AFSVolTransCreate_retry(aconn, entry->volumeId[ROVOL],
6930                                       entry->serverPartition[i], ITOffline,
6931                                       &tid);
6932                 if (code) {     /*volume doesnot exist */
6933                     fprintf(STDERR,
6934                             "Could not start transaction on the ro volume %u\n",
6935                             entry->volumeId[ROVOL]);
6936                     error = code;
6937                     goto rvfail;
6938                 } else {        /*volume exists, process it */
6939                     strcpy(nameBuffer, newname);
6940                     strcat(nameBuffer, ".readonly");
6941                     if (strlen(nameBuffer) > (VOLSER_OLDMAXVOLNAME - 1)) {
6942                         fprintf(STDERR,
6943                                 "Volume name %s exceeds the limit of %u characters\n",
6944                                 nameBuffer, VOLSER_OLDMAXVOLNAME);
6945                         error = code;
6946                         goto rvfail;
6947                     }
6948                     code =
6949                         AFSVolSetIdsTypes(aconn, tid, nameBuffer, ROVOL,
6950                                           entry->volumeId[RWVOL], 0, 0);
6951                     if (!code) {
6952                         VPRINT2("Renamed RO volume %s on host %s\n",
6953                                 nameBuffer,
6954                                 noresolve ?
6955                                 afs_inet_ntoa_r(entry->serverNumber[i], hoststr) :
6956                                 hostutil_GetNameByINet(entry->
6957                                                        serverNumber[i]));
6958                         code = AFSVolEndTrans(aconn, tid, &rcode);
6959                         tid = 0;
6960                         if (code) {
6961                             fprintf(STDERR,
6962                                     "Could not  end transaction on volume %u\n",
6963                                     entry->volumeId[ROVOL]);
6964                             error = code;
6965                             goto rvfail;
6966                         }
6967                     } else {
6968                         fprintf(STDERR,
6969                                 "Could not  set parameters on the ro volume %u\n",
6970                                 entry->volumeId[ROVOL]);
6971                         error = code;
6972                         goto rvfail;
6973                     }
6974                 }
6975                 if (aconn)
6976                     rx_DestroyConnection(aconn);
6977                 aconn = (struct rx_connection *)0;
6978             }
6979         }
6980     }
6981   rvfail:
6982     if (islocked) {
6983         vcode =
6984             ubik_VL_ReleaseLock(cstruct, 0, entry->volumeId[RWVOL],
6985                       RWVOL,
6986                       LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
6987         if (vcode) {
6988             fprintf(STDERR,
6989                     "Could not unlock the VLDB entry for the volume %s %u\n",
6990                     entry->name, entry->volumeId[RWVOL]);
6991             if (!error)
6992                 error = vcode;
6993         }
6994     }
6995     if (tid) {
6996         code = AFSVolEndTrans(aconn, tid, &rcode);
6997         if (!code)
6998             code = rcode;
6999         if (code) {
7000             fprintf(STDERR, "Failed to end transaction on a volume \n");
7001             if (!error)
7002                 error = code;
7003         }
7004     }
7005     if (aconn)
7006         rx_DestroyConnection(aconn);
7007     PrintError("", error);
7008     return error;
7009
7010 }
7011
7012 /*report on all the active transactions on volser */
7013 int
7014 UV_VolserStatus(afs_int32 server, transDebugInfo ** rpntr, afs_int32 * rcount)
7015 {
7016     struct rx_connection *aconn;
7017     transDebugEntries transInfo;
7018     afs_int32 code = 0;
7019
7020     aconn = UV_Bind(server, AFSCONF_VOLUMEPORT);
7021     transInfo.transDebugEntries_val = (transDebugInfo *) 0;
7022     transInfo.transDebugEntries_len = 0;
7023     code = AFSVolMonitor(aconn, &transInfo);
7024     if (code) {
7025         fprintf(STDERR,
7026                 "Could not access status information about the server\n");
7027         PrintError("", code);
7028         if (transInfo.transDebugEntries_val)
7029             free(transInfo.transDebugEntries_val);
7030         if (aconn)
7031             rx_DestroyConnection(aconn);
7032         return code;
7033     } else {
7034         *rcount = transInfo.transDebugEntries_len;
7035         *rpntr = transInfo.transDebugEntries_val;
7036         if (aconn)
7037             rx_DestroyConnection(aconn);
7038         return 0;
7039     }
7040
7041
7042 }
7043
7044 /*delete the volume without interacting with the vldb */
7045 int
7046 UV_VolumeZap(afs_int32 server, afs_int32 part, afs_uint32 volid)
7047 {
7048     afs_int32 rcode, ttid, error, code;
7049     struct rx_connection *aconn;
7050
7051     code = 0;
7052     error = 0;
7053     ttid = 0;
7054
7055     aconn = UV_Bind(server, AFSCONF_VOLUMEPORT);
7056     code = AFSVolTransCreate_retry(aconn, volid, part, ITOffline, &ttid);
7057     if (code) {
7058         fprintf(STDERR, "Could not start transaction on volume %lu\n",
7059                 (unsigned long)volid);
7060         error = code;
7061         goto zfail;
7062     }
7063     code = AFSVolDeleteVolume(aconn, ttid);
7064     if (code) {
7065         fprintf(STDERR, "Could not delete volume %lu\n",
7066                 (unsigned long)volid);
7067         error = code;
7068         goto zfail;
7069     }
7070     code = AFSVolEndTrans(aconn, ttid, &rcode);
7071     ttid = 0;
7072     if (!code)
7073         code = rcode;
7074     if (code) {
7075         fprintf(STDERR, "Could not end transaction on volume %lu\n",
7076                 (unsigned long)volid);
7077         error = code;
7078         goto zfail;
7079     }
7080   zfail:
7081     if (ttid) {
7082         code = AFSVolEndTrans(aconn, ttid, &rcode);
7083         if (!code)
7084             code = rcode;
7085         if (!error)
7086             error = code;
7087     }
7088     PrintError("", error);
7089     if (aconn)
7090         rx_DestroyConnection(aconn);
7091     return error;
7092 }
7093
7094 int
7095 UV_SetVolume(afs_int32 server, afs_int32 partition, afs_uint32 volid,
7096              afs_int32 transflag, afs_int32 setflag, int sleeptime)
7097 {
7098     struct rx_connection *conn = 0;
7099     afs_int32 tid = 0;
7100     afs_int32 code, error = 0, rcode;
7101
7102     conn = UV_Bind(server, AFSCONF_VOLUMEPORT);
7103     if (!conn) {
7104         fprintf(STDERR, "SetVolumeStatus: Bind Failed");
7105         ERROR_EXIT(-1);
7106     }
7107
7108     code = AFSVolTransCreate_retry(conn, volid, partition, transflag, &tid);
7109     if (code) {
7110         fprintf(STDERR, "SetVolumeStatus: TransCreate Failed\n");
7111         ERROR_EXIT(code);
7112     }
7113
7114     code = AFSVolSetFlags(conn, tid, setflag);
7115     if (code) {
7116         fprintf(STDERR, "SetVolumeStatus: SetFlags Failed\n");
7117         ERROR_EXIT(code);
7118     }
7119
7120     if (sleeptime) {
7121 #ifdef AFS_PTHREAD_ENV
7122         sleep(sleeptime);
7123 #else
7124         IOMGR_Sleep(sleeptime);
7125 #endif
7126     }
7127
7128   error_exit:
7129     if (tid) {
7130         rcode = 0;
7131         code = AFSVolEndTrans(conn, tid, &rcode);
7132         if (code || rcode) {
7133             fprintf(STDERR, "SetVolumeStatus: EndTrans Failed\n");
7134             if (!error)
7135                 error = (code ? code : rcode);
7136         }
7137     }
7138
7139     if (conn)
7140         rx_DestroyConnection(conn);
7141     return (error);
7142 }
7143
7144 int
7145 UV_SetVolumeInfo(afs_int32 server, afs_int32 partition, afs_uint32 volid,
7146                  volintInfo * infop)
7147 {
7148     struct rx_connection *conn = 0;
7149     afs_int32 tid = 0;
7150     afs_int32 code, error = 0, rcode;
7151
7152     conn = UV_Bind(server, AFSCONF_VOLUMEPORT);
7153     if (!conn) {
7154         fprintf(STDERR, "SetVolumeInfo: Bind Failed");
7155         ERROR_EXIT(-1);
7156     }
7157
7158     code = AFSVolTransCreate_retry(conn, volid, partition, ITOffline, &tid);
7159     if (code) {
7160         fprintf(STDERR, "SetVolumeInfo: TransCreate Failed\n");
7161         ERROR_EXIT(code);
7162     }
7163
7164     code = AFSVolSetInfo(conn, tid, infop);
7165     if (code) {
7166         fprintf(STDERR, "SetVolumeInfo: SetInfo Failed\n");
7167         ERROR_EXIT(code);
7168     }
7169
7170   error_exit:
7171     if (tid) {
7172         rcode = 0;
7173         code = AFSVolEndTrans(conn, tid, &rcode);
7174         if (code || rcode) {
7175             fprintf(STDERR, "SetVolumeInfo: EndTrans Failed\n");
7176             if (!error)
7177                 error = (code ? code : rcode);
7178         }
7179     }
7180
7181     if (conn)
7182         rx_DestroyConnection(conn);
7183     return (error);
7184 }
7185
7186 int
7187 UV_GetSize(afs_uint32 afromvol, afs_int32 afromserver, afs_int32 afrompart,
7188            afs_int32 fromdate, struct volintSize *vol_size)
7189 {
7190     struct rx_connection *aconn = (struct rx_connection *)0;
7191     afs_int32 tid = 0, rcode = 0;
7192     afs_int32 code, error = 0;
7193
7194
7195     /* get connections to the servers */
7196     aconn = UV_Bind(afromserver, AFSCONF_VOLUMEPORT);
7197
7198     VPRINT1("Starting transaction on volume %u...", afromvol);
7199     code = AFSVolTransCreate_retry(aconn, afromvol, afrompart, ITBusy, &tid);
7200     EGOTO1(error_exit, code,
7201            "Could not start transaction on the volume %u to be measured\n",
7202            afromvol);
7203     VDONE;
7204
7205     VPRINT1("Getting size of volume on volume %u...", afromvol);
7206     code = AFSVolGetSize(aconn, tid, fromdate, vol_size);
7207     EGOTO(error_exit, code, "Could not start the measurement process \n");
7208     VDONE;
7209
7210   error_exit:
7211     if (tid) {
7212         VPRINT1("Ending transaction on volume %u...", afromvol);
7213         code = AFSVolEndTrans(aconn, tid, &rcode);
7214         if (code || rcode) {
7215             fprintf(STDERR, "Could not end transaction on the volume %u\n",
7216                     afromvol);
7217             fprintf(STDERR, "error codes: %d and %d\n", code, rcode);
7218             if (!error)
7219                 error = (code ? code : rcode);
7220         }
7221         VDONE;
7222     }
7223     if (aconn)
7224         rx_DestroyConnection(aconn);
7225
7226     PrintError("", error);
7227     return (error);
7228 }
7229
7230 /*maps the host addresses in <old > (present in network byte order) to
7231  that in< new> (present in host byte order )*/
7232 void
7233 MapNetworkToHost(struct nvldbentry *old, struct nvldbentry *new)
7234 {
7235     int i, count;
7236
7237     /*copy all the fields */
7238     strcpy(new->name, old->name);
7239 /*    new->volumeType = old->volumeType;*/
7240     new->nServers = old->nServers;
7241     count = old->nServers;
7242     if (count < NMAXNSERVERS)
7243         count++;
7244     for (i = 0; i < count; i++) {
7245         new->serverNumber[i] = ntohl(old->serverNumber[i]);
7246         new->serverPartition[i] = old->serverPartition[i];
7247         new->serverFlags[i] = old->serverFlags[i];
7248     }
7249     new->volumeId[RWVOL] = old->volumeId[RWVOL];
7250     new->volumeId[ROVOL] = old->volumeId[ROVOL];
7251     new->volumeId[BACKVOL] = old->volumeId[BACKVOL];
7252     new->cloneId = old->cloneId;
7253     new->flags = old->flags;
7254 }
7255
7256 /*maps the host entries in <entry> which are present in host byte order to network byte order */
7257 void
7258 MapHostToNetwork(struct nvldbentry *entry)
7259 {
7260     int i, count;
7261
7262     count = entry->nServers;
7263     if (count < NMAXNSERVERS)
7264         count++;
7265     for (i = 0; i < count; i++) {
7266         entry->serverNumber[i] = htonl(entry->serverNumber[i]);
7267     }
7268 }