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