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