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