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