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