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