405a62d52cb12bc9341c44d1fc9f61568922dfae
[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 the volume does not exist, create it */
3251     if (!volid || code) {
3252         char volname[64];
3253         char hoststr[16];
3254
3255         if (volid && (code != VNOVOL)) {
3256             PrintError("Failed to start a transaction on the RO volume.\n",
3257                        code);
3258             goto fail;
3259         }
3260
3261         strcpy(volname, vldbEntryPtr->name);
3262         strcat(volname, ".readonly");
3263
3264         if (verbose) {
3265             fprintf(STDOUT,
3266                     "Creating new volume %lu on replication site %s: ",
3267                     (unsigned long)volid,
3268                     noresolve ? afs_inet_ntoa_r(vldbEntryPtr->
3269                                                 serverNumber[index], hoststr) :
3270                     hostutil_GetNameByINet(vldbEntryPtr->
3271                                            serverNumber[index]));
3272             fflush(STDOUT);
3273         }
3274
3275         code =
3276             AFSVolCreateVolume(*connPtr, vldbEntryPtr->serverPartition[index],
3277                                volname, volser_RO,
3278                                vldbEntryPtr->volumeId[RWVOL], &volid,
3279                                transPtr);
3280         if (code) {
3281             PrintError("Failed to create the ro volume: ", code);
3282             goto fail;
3283         }
3284         vldbEntryPtr->volumeId[ROVOL] = volid;
3285
3286         VDONE;
3287
3288         /* The following is a bit redundant, since create sets these flags by default */
3289         code =
3290             AFSVolSetFlags(*connPtr, *transPtr,
3291                            VTDeleteOnSalvage | VTOutOfService);
3292         if (code) {
3293             PrintError("Failed to set flags on the ro volume: ", code);
3294             goto fail;
3295         }
3296     }
3297
3298     /* Otherwise, the transaction did succeed, so get the creation date of the
3299      * latest RO volume on the replication site
3300      */
3301     else {
3302         VPRINT2("Updating existing ro volume %u on %s ...\n", volid,
3303                 noresolve ? afs_inet_ntoa_r(vldbEntryPtr->
3304                                             serverNumber[index], hoststr) :
3305                 hostutil_GetNameByINet(vldbEntryPtr->serverNumber[index]));
3306
3307         code = AFSVolGetStatus(*connPtr, *transPtr, &tstatus);
3308         if (code) {
3309             PrintError("Failed to get status of volume on destination: ",
3310                        code);
3311             goto fail;
3312         }
3313         *crtimePtr = CLOCKADJ(tstatus.creationDate);
3314         *uptimePtr = CLOCKADJ(tstatus.updateDate);
3315     }
3316
3317     return 0;
3318
3319   fail:
3320     if (*transPtr) {
3321         tcode = AFSVolEndTrans(*connPtr, *transPtr, &rcode);
3322         *transPtr = 0;
3323         if (!tcode)
3324             tcode = rcode;
3325         if (tcode)
3326             PrintError("Could not end transaction on a ro volume: ", tcode);
3327     }
3328
3329     return code;
3330 }
3331
3332 static int
3333 SimulateForwardMultiple(struct rx_connection *fromconn, afs_int32 fromtid,
3334                         afs_int32 fromdate, manyDests * tr, afs_int32 flags,
3335                         void *cookie, manyResults * results)
3336 {
3337     unsigned int i;
3338
3339     for (i = 0; i < tr->manyDests_len; i++) {
3340         results->manyResults_val[i] =
3341             AFSVolForward(fromconn, fromtid, fromdate,
3342                           &(tr->manyDests_val[i].server),
3343                           tr->manyDests_val[i].trans, cookie);
3344     }
3345     return 0;
3346 }
3347
3348
3349 /* UV_ReleaseVolume()
3350  *    Release volume <afromvol> on <afromserver> <afrompart> to all
3351  *    its RO sites (full release). Unless the previous release was
3352  *    incomplete: in which case we bring the remaining incomplete
3353  *    volumes up to date with the volumes that were released
3354  *    successfully.
3355  *    forceflag: Performs a full release.
3356  *
3357  *    Will create a clone from the RW, then dump the clone out to
3358  *    the remaining replicas. If there is more than 1 RO sites,
3359  *    ensure that the VLDB says at least one RO is available all
3360  *    the time: Influences when we write back the VLDB entry.
3361  */
3362
3363 int
3364 UV_ReleaseVolume(afs_uint32 afromvol, afs_uint32 afromserver,
3365                  afs_int32 afrompart, int forceflag)
3366 {
3367     char vname[64];
3368     afs_int32 code = 0;
3369     afs_int32 vcode, rcode, tcode;
3370     afs_uint32 cloneVolId, roVolId;
3371     struct replica *replicas = 0;
3372     struct nvldbentry entry, storeEntry;
3373     int i, volcount, m, fullrelease, vldbindex;
3374     int failure;
3375     struct restoreCookie cookie;
3376     struct rx_connection **toconns = 0;
3377     struct release *times = 0;
3378     int nservers = 0;
3379     struct rx_connection *fromconn = (struct rx_connection *)0;
3380     afs_int32 error = 0;
3381     int islocked = 0;
3382     afs_int32 clonetid = 0, onlinetid;
3383     afs_int32 fromtid = 0;
3384     afs_uint32 fromdate = 0;
3385     afs_uint32 thisdate;
3386     time_t tmv;
3387     int s;
3388     manyDests tr;
3389     manyResults results;
3390     int rwindex, roindex, roclone, roexists;
3391     afs_uint32 rwcrdate = 0;
3392     afs_uint32 clcrdate;
3393     struct rtime {
3394         int validtime;
3395         afs_uint32 uptime;
3396     } remembertime[NMAXNSERVERS];
3397     int releasecount = 0;
3398     struct volser_status volstatus;
3399     char hoststr[16];
3400
3401     memset(remembertime, 0, sizeof(remembertime));
3402     memset(&results, 0, sizeof(results));
3403
3404     vcode = ubik_VL_SetLock(cstruct, 0, afromvol, RWVOL, VLOP_RELEASE);
3405     if (vcode != VL_RERELEASE)
3406         ONERROR(vcode, afromvol,
3407                 "Could not lock the VLDB entry for the volume %u.\n");
3408     islocked = 1;
3409
3410     /* Get the vldb entry in readable format */
3411     vcode = VLDB_GetEntryByID(afromvol, RWVOL, &entry);
3412     ONERROR(vcode, afromvol,
3413             "Could not fetch the entry for the volume %u from the VLDB.\n");
3414     MapHostToNetwork(&entry);
3415
3416     if (verbose)
3417         EnumerateEntry(&entry);
3418
3419     if (!ISNAMEVALID(entry.name))
3420         ONERROR(VOLSERBADOP, entry.name,
3421                 "Volume name %s is too long, rename before releasing.\n");
3422     if (entry.volumeId[RWVOL] != afromvol)
3423         ONERROR(VOLSERBADOP, afromvol,
3424                 "The volume %u being released is not a read-write volume.\n");
3425     if (entry.nServers <= 1)
3426         ONERROR(VOLSERBADOP, afromvol,
3427                 "Volume %u has no replicas - release operation is meaningless!\n");
3428     if (strlen(entry.name) > (VOLSER_OLDMAXVOLNAME - 10))
3429         ONERROR(VOLSERBADOP, entry.name,
3430                 "RO volume name %s exceeds (VOLSER_OLDMAXVOLNAME - 10) character limit\n");
3431
3432     /* roclone is true if one of the RO volumes is on the same
3433      * partition as the RW volume. In this case, we make the RO volume
3434      * on the same partition a clone instead of a complete copy.
3435      */
3436
3437     roindex = Lp_ROMatch(afromserver, afrompart, &entry) - 1;
3438     roclone = ((roindex == -1) ? 0 : 1);
3439     rwindex = Lp_GetRwIndex(&entry);
3440     if (rwindex < 0)
3441         ONERROR0(VOLSERNOVOL, "There is no RW volume \n");
3442
3443     /* Make sure we have a RO volume id to work with */
3444     if (entry.volumeId[ROVOL] == INVALID_BID) {
3445         /* need to get a new RO volume id */
3446         vcode = ubik_VL_GetNewVolumeId(cstruct, 0, 1, &roVolId);
3447         ONERROR(vcode, entry.name, "Cant allocate ID for RO volume of %s\n");
3448
3449         entry.volumeId[ROVOL] = roVolId;
3450         MapNetworkToHost(&entry, &storeEntry);
3451         vcode = VLDB_ReplaceEntry(afromvol, RWVOL, &storeEntry, 0);
3452         ONERROR(vcode, entry.name, "Could not update vldb entry for %s.\n");
3453     }
3454
3455     /* Will we be completing a previously unfinished release. -force overrides */
3456     for (s = 0, m = 0, fullrelease=0, i=0; (i<entry.nServers); i++) {
3457         if (entry.serverFlags[i] & ITSROVOL) {
3458             m++;
3459             if (entry.serverFlags[i] & NEW_REPSITE) s++;
3460         }
3461     }
3462     if ((forceflag && !fullrelease) || (s == m) || (s == 0))
3463         fullrelease = 1;
3464
3465     /* Determine which volume id to use and see if it exists */
3466     cloneVolId =
3467         ((fullrelease
3468           || (entry.cloneId == 0)) ? entry.volumeId[ROVOL] : entry.cloneId);
3469     code = VolumeExists(afromserver, afrompart, cloneVolId);
3470     roexists = ((code == ENODEV) ? 0 : 1);
3471
3472     fromconn = UV_Bind(afromserver, AFSCONF_VOLUMEPORT);
3473     if (!fromconn)
3474         ONERROR(-1, afromserver,
3475                 "Cannot establish connection with server 0x%x\n");
3476
3477     if (!fullrelease) {
3478         if (!roexists)
3479             fullrelease = 1;    /* Do a full release if RO clone does not exist */
3480         else {
3481             /* Begin transaction on RW and mark it busy while we query it */
3482             code = AFSVolTransCreate_retry(
3483                         fromconn, afromvol, afrompart, ITBusy, &fromtid
3484                    );
3485             ONERROR(code, afromvol,
3486                     "Failed to start transaction on RW volume %u\n");
3487
3488             /* Query the creation date for the RW */
3489             code = AFSVolGetStatus(fromconn, fromtid, &volstatus);
3490             ONERROR(code, afromvol,
3491                     "Failed to get the status of RW volume %u\n");
3492             rwcrdate = volstatus.creationDate;
3493
3494             /* End transaction on RW */
3495             code = AFSVolEndTrans(fromconn, fromtid, &rcode);
3496             fromtid = 0;
3497             ONERROR((code ? code : rcode), afromvol,
3498                     "Failed to end transaction on RW volume %u\n");
3499
3500             /* Begin transaction on clone and mark it busy while we query it */
3501             code = AFSVolTransCreate_retry(
3502                         fromconn, cloneVolId, afrompart, ITBusy, &clonetid
3503                    );
3504             ONERROR(code, cloneVolId,
3505                     "Failed to start transaction on RW clone %u\n");
3506
3507             /* Query the creation date for the clone */
3508             code = AFSVolGetStatus(fromconn, clonetid, &volstatus);
3509             ONERROR(code, cloneVolId,
3510                     "Failed to get the status of RW clone %u\n");
3511             clcrdate = volstatus.creationDate;
3512
3513             /* End transaction on clone */
3514             code = AFSVolEndTrans(fromconn, clonetid, &rcode);
3515             clonetid = 0;
3516             ONERROR((code ? code : rcode), cloneVolId,
3517                     "Failed to end transaction on RW clone %u\n");
3518
3519             if (rwcrdate > clcrdate)
3520                 fullrelease = 2;/* Do a full release if RO clone older than RW */
3521         }
3522     }
3523
3524     if (verbose) {
3525         switch (fullrelease) {
3526             case 2:
3527                 fprintf(STDOUT, "RW %lu changed, doing a complete release\n",
3528                         (unsigned long)afromvol);
3529                 break;
3530             case 1:
3531                 fprintf(STDOUT, "This is a complete release of volume %lu\n",
3532                         (unsigned long)afromvol);
3533                 break;
3534             case 0:
3535                 fprintf(STDOUT, "This is a completion of a previous release\n");
3536                 break;
3537         }
3538     }
3539
3540     if (fullrelease) {
3541         /* If the RO clone exists, then if the clone is a temporary
3542          * clone, delete it. Or if the RO clone is marked RO_DONTUSE
3543          * (it was recently added), then also delete it. We do not
3544          * want to "reclone" a temporary RO clone.
3545          */
3546         if (roexists
3547             && (!roclone || (entry.serverFlags[roindex] & RO_DONTUSE))) {
3548             code = DelVol(fromconn, cloneVolId, afrompart, ITOffline);
3549             if (code && (code != VNOVOL))
3550                 ERROREXIT(code);
3551             roexists = 0;
3552         }
3553
3554         /* Mark all the ROs in the VLDB entry as RO_DONTUSE. We don't
3555          * write this entry out to the vlserver until after the first
3556          * RO volume is released (temp RO clones don't count).
3557          */
3558         for (i = 0; i < entry.nServers; i++) {
3559             entry.serverFlags[i] &= ~NEW_REPSITE;
3560             entry.serverFlags[i] |= RO_DONTUSE;
3561         }
3562         entry.serverFlags[rwindex] |= NEW_REPSITE;
3563         entry.serverFlags[rwindex] &= ~RO_DONTUSE;
3564
3565         /* Begin transaction on RW and mark it busy while we clone it */
3566         code =
3567             AFSVolTransCreate_retry(fromconn, afromvol, afrompart, ITBusy,
3568                               &clonetid);
3569         ONERROR(code, afromvol, "Failed to start transaction on volume %u\n");
3570
3571         /* Clone or reclone the volume */
3572         if (roexists) {
3573             VPRINT1("Recloning RW volume %u...", cloneVolId);
3574             code = AFSVolReClone(fromconn, clonetid, cloneVolId);
3575             ONERROR(code, afromvol, "Failed to reclone the RW volume %u\n");
3576             VDONE;
3577         } else {
3578             if (roclone) {
3579                 strcpy(vname, entry.name);
3580                 strcat(vname, ".readonly");
3581                 VPRINT1("Cloning RW volume %u to permanent RO...", afromvol);
3582             } else {
3583                 strcpy(vname, "readonly-clone-temp");
3584                 VPRINT1("Cloning RW volume %u to temporary RO...", afromvol);
3585             }
3586             code =
3587                 AFSVolClone(fromconn, clonetid, 0, readonlyVolume, vname,
3588                             &cloneVolId);
3589             ONERROR(code, afromvol, "Failed to clone the RW volume %u\n");
3590             VDONE;
3591         }
3592
3593         /* Get the time the RW was created for future information */
3594         VPRINT1("Getting status of RW volume %u...", afromvol);
3595         code = AFSVolGetStatus(fromconn, clonetid, &volstatus);
3596         ONERROR(code, afromvol,
3597                 "Failed to get the status of the RW volume %u\n");
3598         VDONE;
3599         rwcrdate = volstatus.creationDate;
3600
3601         /* End the transaction on the RW volume */
3602         VPRINT1("Ending cloning transaction on RW volume %u...", afromvol);
3603         code = AFSVolEndTrans(fromconn, clonetid, &rcode);
3604         clonetid = 0;
3605         ONERROR((code ? code : rcode), afromvol,
3606                 "Failed to end cloning transaction on RW %u\n");
3607         VDONE;
3608
3609         /* Remember clone volume ID in case we fail or are interrupted */
3610         entry.cloneId = cloneVolId;
3611
3612         if (roclone) {
3613             /* Bring the RO clone online - though not if it's a temporary clone */
3614             VPRINT1("Starting transaction on RO clone volume %u...",
3615                     cloneVolId);
3616             code =
3617                 AFSVolTransCreate_retry(fromconn, cloneVolId, afrompart, ITOffline,
3618                                   &onlinetid);
3619             ONERROR(code, cloneVolId,
3620                     "Failed to start transaction on volume %u\n");
3621             VDONE;
3622
3623             VPRINT1("Setting volume flags for volume %u...", cloneVolId);
3624             tcode = AFSVolSetFlags(fromconn, onlinetid, 0);
3625             VDONE;
3626
3627             VPRINT1("Ending transaction on volume %u...", cloneVolId);
3628             code = AFSVolEndTrans(fromconn, onlinetid, &rcode);
3629             ONERROR((code ? code : rcode), cloneVolId,
3630                     "Failed to end transaction on RO clone %u\n");
3631             VDONE;
3632
3633             ONERROR(tcode, cloneVolId, "Could not bring volume %u on line\n");
3634
3635             /* Sleep so that a client searching for an online volume won't
3636              * find the clone offline and then the next RO offline while the
3637              * release brings the clone online and the next RO offline (race).
3638              * There is a fix in the 3.4 client that does not need this sleep
3639              * anymore, but we don't know what clients we have.
3640              */
3641             if (entry.nServers > 2)
3642                 sleep(5);
3643
3644             /* Mark the RO clone in the VLDB as a good site (already released) */
3645             entry.serverFlags[roindex] |= NEW_REPSITE;
3646             entry.serverFlags[roindex] &= ~RO_DONTUSE;
3647             entry.flags |= RO_EXISTS;
3648
3649             releasecount++;
3650
3651             /* Write out the VLDB entry only if the clone is not a temporary
3652              * clone. If we did this to a temporary clone then we would end
3653              * up marking all the ROs as "old release" making the ROs
3654              * temporarily unavailable.
3655              */
3656             MapNetworkToHost(&entry, &storeEntry);
3657             VPRINT1("Replacing VLDB entry for %s...", entry.name);
3658             vcode = VLDB_ReplaceEntry(afromvol, RWVOL, &storeEntry, 0);
3659             ONERROR(vcode, entry.name,
3660                     "Could not update vldb entry for %s.\n");
3661             VDONE;
3662         }
3663     }
3664
3665     /* Now we will release from the clone to the remaining RO replicas.
3666      * The first 2 ROs (counting the non-temporary RO clone) are released
3667      * individually: releasecount. This is to reduce the race condition
3668      * of clients trying to find an on-line RO volume. The remaining ROs
3669      * are released in parallel but no more than half the number of ROs
3670      * (rounded up) at a time: nservers.
3671      */
3672
3673     strcpy(vname, entry.name);
3674     strcat(vname, ".readonly");
3675     memset(&cookie, 0, sizeof(cookie));
3676     strncpy(cookie.name, vname, VOLSER_OLDMAXVOLNAME);
3677     cookie.type = ROVOL;
3678     cookie.parent = entry.volumeId[RWVOL];
3679     cookie.clone = 0;
3680
3681     nservers = entry.nServers / 2;      /* how many to do at once, excluding clone */
3682     replicas =
3683         (struct replica *)malloc(sizeof(struct replica) * nservers + 1);
3684     times = (struct release *)malloc(sizeof(struct release) * nservers + 1);
3685     toconns =
3686         (struct rx_connection **)malloc(sizeof(struct rx_connection *) *
3687                                         nservers + 1);
3688     results.manyResults_val =
3689         (afs_int32 *) malloc(sizeof(afs_int32) * nservers + 1);
3690     if (!replicas || !times || !!!results.manyResults_val || !toconns)
3691         ONERROR0(ENOMEM,
3692                 "Failed to create transaction on the release clone\n");
3693
3694     memset(replicas, 0, (sizeof(struct replica) * nservers + 1));
3695     memset(times, 0, (sizeof(struct release) * nservers + 1));
3696     memset(toconns, 0, (sizeof(struct rx_connection *) * nservers + 1));
3697     memset(results.manyResults_val, 0, (sizeof(afs_int32) * nservers + 1));
3698
3699     /* Create a transaction on the cloned volume */
3700     VPRINT1("Starting transaction on cloned volume %u...", cloneVolId);
3701     code =
3702         AFSVolTransCreate_retry(fromconn, cloneVolId, afrompart, ITBusy, &fromtid);
3703     if (!fullrelease && code)
3704         ONERROR(VOLSERNOVOL, afromvol,
3705                 "Old clone is inaccessible. Try vos release -f %u.\n");
3706     ONERROR0(code, "Failed to create transaction on the release clone\n");
3707     VDONE;
3708
3709     /* For each index in the VLDB */
3710     for (vldbindex = 0; vldbindex < entry.nServers;) {
3711
3712         /* Get a transaction on the replicas. Pick replacas which have an old release. */
3713         for (volcount = 0;
3714              ((volcount < nservers) && (vldbindex < entry.nServers));
3715              vldbindex++) {
3716             /* The first two RO volumes will be released individually.
3717              * The rest are then released in parallel. This is a hack
3718              * for clients not recognizing right away when a RO volume
3719              * comes back on-line.
3720              */
3721             if ((volcount == 1) && (releasecount < 2))
3722                 break;
3723
3724             if (vldbindex == roindex)
3725                 continue;       /* the clone    */
3726             if ((entry.serverFlags[vldbindex] & NEW_REPSITE)
3727                 && !(entry.serverFlags[vldbindex] & RO_DONTUSE))
3728                 continue;
3729             if (!(entry.serverFlags[vldbindex] & ITSROVOL))
3730                 continue;       /* not a RO vol */
3731
3732
3733             /* Get a Transaction on this replica. Get a new connection if
3734              * necessary.  Create the volume if necessary.  Return the
3735              * time from which the dump should be made (0 if it's a new
3736              * volume).  Each volume might have a different time.
3737              */
3738             replicas[volcount].server.destHost =
3739                 ntohl(entry.serverNumber[vldbindex]);
3740             replicas[volcount].server.destPort = AFSCONF_VOLUMEPORT;
3741             replicas[volcount].server.destSSID = 1;
3742             times[volcount].vldbEntryIndex = vldbindex;
3743
3744             code =
3745                 GetTrans(&entry, vldbindex, &(toconns[volcount]),
3746                          &(replicas[volcount].trans),
3747                          &(times[volcount].crtime),
3748                          &(times[volcount].uptime));
3749             if (code)
3750                 continue;
3751
3752             /* Thisdate is the date from which we want to pick up all changes */
3753             if (forceflag || !fullrelease
3754                 || (rwcrdate > times[volcount].crtime)) {
3755                 /* If the forceflag is set, then we want to do a full dump.
3756                  * If it's not a full release, we can't be sure that the creation
3757                  *  date is good (so we also do a full dump).
3758                  * If the RW volume was replaced (its creation date is newer than
3759                  *  the last release), then we can't be sure what has changed (so
3760                  *  we do a full dump).
3761                  */
3762                 thisdate = 0;
3763             } else if (remembertime[vldbindex].validtime) {
3764                 /* Trans was prev ended. Use the time from the prev trans
3765                  * because, prev trans may have created the volume. In which
3766                  * case time[volcount].time would be now instead of 0.
3767                  */
3768                 thisdate =
3769                     (remembertime[vldbindex].uptime < times[volcount].uptime)
3770                         ? remembertime[vldbindex].uptime
3771                         : times[volcount].uptime;
3772             } else {
3773                 thisdate = times[volcount].uptime;
3774             }
3775             remembertime[vldbindex].validtime = 1;
3776             remembertime[vldbindex].uptime = thisdate;
3777
3778             if (volcount == 0) {
3779                 fromdate = thisdate;
3780             } else {
3781                 /* Include this volume if it is within 15 minutes of the earliest */
3782                 if (((fromdate >
3783                       thisdate) ? (fromdate - thisdate) : (thisdate -
3784                                                            fromdate)) > 900) {
3785                     AFSVolEndTrans(toconns[volcount],
3786                                    replicas[volcount].trans, &rcode);
3787                     replicas[volcount].trans = 0;
3788                     break;
3789                 }
3790                 if (thisdate < fromdate)
3791                     fromdate = thisdate;
3792             }
3793             volcount++;
3794         }
3795         if (!volcount)
3796             continue;
3797
3798         if (verbose) {
3799             fprintf(STDOUT, "Starting ForwardMulti from %lu to %u on %s",
3800                     (unsigned long)cloneVolId, entry.volumeId[ROVOL],
3801                     noresolve ? afs_inet_ntoa_r(entry.serverNumber[times[0].
3802                                                 vldbEntryIndex], hoststr) :
3803                     hostutil_GetNameByINet(entry.
3804                                            serverNumber[times[0].
3805                                                         vldbEntryIndex]));
3806
3807             for (s = 1; s < volcount; s++) {
3808                 fprintf(STDOUT, " and %s",
3809                         noresolve ? afs_inet_ntoa_r(entry.serverNumber[times[s].
3810                                                     vldbEntryIndex], hoststr) :
3811                         hostutil_GetNameByINet(entry.
3812                                                serverNumber[times[s].
3813                                                             vldbEntryIndex]));
3814             }
3815
3816             if (fromdate == 0)
3817                 fprintf(STDOUT, " (full release)");
3818             else {
3819                 tmv = fromdate;
3820                 fprintf(STDOUT, " (as of %.24s)", ctime(&tmv));
3821             }
3822             fprintf(STDOUT, ".\n");
3823             fflush(STDOUT);
3824         }
3825
3826         /* Release the ones we have collected */
3827         tr.manyDests_val = &(replicas[0]);
3828         tr.manyDests_len = results.manyResults_len = volcount;
3829         code =
3830             AFSVolForwardMultiple(fromconn, fromtid, fromdate, &tr,
3831                                   0 /*spare */ , &cookie, &results);
3832         if (code == RXGEN_OPCODE) {     /* RPC Interface Mismatch */
3833             code =
3834                 SimulateForwardMultiple(fromconn, fromtid, fromdate, &tr,
3835                                         0 /*spare */ , &cookie, &results);
3836             nservers = 1;
3837         }
3838
3839         if (code) {
3840             PrintError("Release failed: ", code);
3841         } else {
3842             for (m = 0; m < volcount; m++) {
3843                 if (results.manyResults_val[m]) {
3844                     if ((m == 0) || (results.manyResults_val[m] != ENOENT)) {
3845                         /* we retry timed out transaction. When it is
3846                          * not the first volume and the transaction wasn't found
3847                          * (assume it timed out and was garbage collected by volser).
3848                          */
3849                         PrintError
3850                             ("Failed to dump volume from clone to a ro site: ",
3851                              results.manyResults_val[m]);
3852                     }
3853                     continue;
3854                 }
3855
3856                 code =
3857                     AFSVolSetIdsTypes(toconns[m], replicas[m].trans, vname,
3858                                       ROVOL, entry.volumeId[RWVOL], 0, 0);
3859                 if (code) {
3860                     if ((m == 0) || (code != ENOENT)) {
3861                         PrintError("Failed to set correct names and ids: ",
3862                                    code);
3863                     }
3864                     continue;
3865                 }
3866
3867                 /* have to clear dest. flags to ensure new vol goes online:
3868                  * because the restore (forwarded) operation copied
3869                  * the V_inService(=0) flag over to the destination.
3870                  */
3871                 code = AFSVolSetFlags(toconns[m], replicas[m].trans, 0);
3872                 if (code) {
3873                     if ((m == 0) || (code != ENOENT)) {
3874                         PrintError("Failed to set flags on ro volume: ",
3875                                    code);
3876                     }
3877                     continue;
3878                 }
3879
3880                 entry.serverFlags[times[m].vldbEntryIndex] |= NEW_REPSITE;
3881                 entry.serverFlags[times[m].vldbEntryIndex] &= ~RO_DONTUSE;
3882                 entry.flags |= RO_EXISTS;
3883                 releasecount++;
3884             }
3885         }
3886
3887         /* End the transactions and destroy the connections */
3888         for (s = 0; s < volcount; s++) {
3889             if (replicas[s].trans)
3890                 code = AFSVolEndTrans(toconns[s], replicas[s].trans, &rcode);
3891             replicas[s].trans = 0;
3892             if (!code)
3893                 code = rcode;
3894             if (code) {
3895                 if ((s == 0) || (code != ENOENT)) {
3896                     PrintError("Could not end transaction on a ro volume: ",
3897                                code);
3898                 } else {
3899                     PrintError
3900                         ("Transaction timed out on a ro volume. Will retry.\n",
3901                          0);
3902                     if (times[s].vldbEntryIndex < vldbindex)
3903                         vldbindex = times[s].vldbEntryIndex;
3904                 }
3905             }
3906
3907             if (toconns[s])
3908                 rx_DestroyConnection(toconns[s]);
3909             toconns[s] = 0;
3910         }
3911
3912         MapNetworkToHost(&entry, &storeEntry);
3913         vcode = VLDB_ReplaceEntry(afromvol, RWVOL, &storeEntry, 0);
3914         ONERROR(vcode, afromvol,
3915                 " Could not update VLDB entry for volume %u\n");
3916     }                           /* for each index in the vldb */
3917
3918     /* End the transaction on the cloned volume */
3919     code = AFSVolEndTrans(fromconn, fromtid, &rcode);
3920     fromtid = 0;
3921     if (!code)
3922         code = rcode;
3923     if (code)
3924         PrintError("Failed to end transaction on rw volume: ", code);
3925
3926     /* Figure out if any volume were not released and say so */
3927     for (failure = 0, i = 0; i < entry.nServers; i++) {
3928         if (!(entry.serverFlags[i] & NEW_REPSITE))
3929             failure++;
3930     }
3931     if (failure) {
3932         char pname[10];
3933         fprintf(STDERR,
3934                 "The volume %lu could not be released to the following %d sites:\n",
3935                 (unsigned long)afromvol, failure);
3936         for (i = 0; i < entry.nServers; i++) {
3937             if (!(entry.serverFlags[i] & NEW_REPSITE)) {
3938                 MapPartIdIntoName(entry.serverPartition[i], pname);
3939                 fprintf(STDERR, "\t%35s %s\n",
3940                         noresolve ? afs_inet_ntoa_r(entry.serverNumber[i], hoststr) :
3941                         hostutil_GetNameByINet(entry.serverNumber[i]), pname);
3942             }
3943         }
3944
3945         MapNetworkToHost(&entry, &storeEntry);
3946         vcode =
3947             VLDB_ReplaceEntry(afromvol, RWVOL, &storeEntry,
3948                               LOCKREL_TIMESTAMP);
3949         ONERROR(vcode, afromvol,
3950                 " Could not update VLDB entry for volume %u\n");
3951
3952         ERROREXIT(VOLSERBADRELEASE);
3953     }
3954
3955     /* All the ROs were release successfully. Remove the temporary clone */
3956     if (!roclone) {
3957         if (verbose) {
3958             fprintf(STDOUT, "Deleting the releaseClone %lu ...",
3959                     (unsigned long)cloneVolId);
3960             fflush(STDOUT);
3961         }
3962         code = DelVol(fromconn, cloneVolId, afrompart, ITOffline);
3963         ONERROR(code, cloneVolId, "Failed to delete volume %u.\n");
3964         VDONE;
3965     }
3966     entry.cloneId = 0;
3967
3968     for (i = 0; i < entry.nServers; i++)
3969         entry.serverFlags[i] &= ~NEW_REPSITE;
3970
3971     /* Update the VLDB */
3972     VPRINT("updating VLDB ...");
3973
3974     MapNetworkToHost(&entry, &storeEntry);
3975     vcode =
3976         VLDB_ReplaceEntry(afromvol, RWVOL, &storeEntry,
3977                           LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
3978     ONERROR(vcode, afromvol, " Could not update VLDB entry for volume %u\n");
3979     VDONE;
3980
3981   rfail:
3982     if (clonetid) {
3983         code = AFSVolEndTrans(fromconn, clonetid, &rcode);
3984         clonetid = 0;
3985         if (code) {
3986             fprintf(STDERR,
3987                     "Failed to end cloning transaction on the RW volume %lu\n",
3988                     (unsigned long)afromvol);
3989             if (!error)
3990                 error = code;
3991         }
3992     }
3993     if (fromtid) {
3994         code = AFSVolEndTrans(fromconn, fromtid, &rcode);
3995         fromtid = 0;
3996         if (code) {
3997             fprintf(STDERR,
3998                     "Failed to end transaction on the release clone %lu\n",
3999                     (unsigned long)cloneVolId);
4000             if (!error)
4001                 error = code;
4002         }
4003     }
4004     for (i = 0; i < nservers; i++) {
4005         if (replicas && replicas[i].trans) {
4006             code = AFSVolEndTrans(toconns[i], replicas[i].trans, &rcode);
4007             replicas[i].trans = 0;
4008             if (code) {
4009                 fprintf(STDERR,
4010                         "Failed to end transaction on ro volume %u at server %s\n",
4011                         entry.volumeId[ROVOL],
4012                         noresolve ? afs_inet_ntoa_r(htonl(replicas[i].server.
4013                                                         destHost), hoststr) :
4014                         hostutil_GetNameByINet(htonl
4015                                                (replicas[i].server.destHost)));
4016                 if (!error)
4017                     error = code;
4018             }
4019         }
4020         if (toconns && toconns[i]) {
4021             rx_DestroyConnection(toconns[i]);
4022             toconns[i] = 0;
4023         }
4024     }
4025     if (islocked) {
4026         vcode =
4027             ubik_VL_ReleaseLock(cstruct, 0, afromvol, RWVOL,
4028                       LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
4029         if (vcode) {
4030             fprintf(STDERR,
4031                     "Could not release lock on the VLDB entry for volume %lu\n",
4032                     (unsigned long)afromvol);
4033             if (!error)
4034                 error = vcode;
4035         }
4036     }
4037
4038     PrintError("", error);
4039
4040     if (fromconn)
4041         rx_DestroyConnection(fromconn);
4042     if (results.manyResults_val)
4043         free(results.manyResults_val);
4044     if (replicas)
4045         free(replicas);
4046     if (toconns)
4047         free(toconns);
4048     if (times)
4049         free(times);
4050     return error;
4051 }
4052
4053
4054 void
4055 dump_sig_handler(int x)
4056 {
4057     fprintf(STDERR, "\nSignal handler: vos dump operation\n");
4058     longjmp(env, 0);
4059 }
4060
4061 /* Dump the volume <afromvol> on <afromserver> and
4062  * <afrompart> to <afilename> starting from <fromdate>.
4063  * DumpFunction does the real work behind the scenes after
4064  * extracting parameters from the rock
4065  */
4066 int
4067 UV_DumpVolume(afs_uint32 afromvol, afs_uint32 afromserver, afs_int32 afrompart,
4068               afs_int32 fromdate,
4069               afs_int32(*DumpFunction) (struct rx_call *, void *), void *rock,
4070               afs_int32 flags)
4071 {
4072     /* declare stuff 'volatile' that may be used from setjmp/longjmp and may
4073      * be changing during the dump */
4074     struct rx_call * volatile fromcall = NULL;
4075     struct rx_connection * volatile fromconn = NULL;
4076     afs_int32 volatile fromtid = 0;
4077
4078     afs_int32 rxError = 0, rcode = 0;
4079     afs_int32 code, error = 0;
4080     afs_int32 tmp;
4081     time_t tmv = fromdate;
4082
4083     if (setjmp(env))
4084         ERROR_EXIT(EPIPE);
4085 #ifndef AFS_NT40_ENV
4086     (void)signal(SIGPIPE, dump_sig_handler);
4087 #endif
4088     (void)signal(SIGINT, dump_sig_handler);
4089
4090     if (!fromdate) {
4091         VEPRINT("Full Dump ...\n");
4092     } else {
4093         VEPRINT1("Incremental Dump (as of %.24s)...\n",
4094                 ctime(&tmv));
4095     }
4096
4097     /* get connections to the servers */
4098     fromconn = UV_Bind(afromserver, AFSCONF_VOLUMEPORT);
4099
4100     VEPRINT1("Starting transaction on volume %u...", afromvol);
4101     tmp = fromtid;
4102     code = AFSVolTransCreate_retry(fromconn, afromvol, afrompart, ITBusy, &tmp);
4103     fromtid = tmp;
4104     EGOTO1(error_exit, code,
4105            "Could not start transaction on the volume %u to be dumped\n",
4106            afromvol);
4107     VEDONE;
4108
4109     fromcall = rx_NewCall(fromconn);
4110
4111     VEPRINT1("Starting volume dump on volume %u...", afromvol);
4112     if (flags & VOLDUMPV2_OMITDIRS)
4113         code = StartAFSVolDumpV2(fromcall, fromtid, fromdate, flags);
4114     else
4115         code = StartAFSVolDump(fromcall, fromtid, fromdate);
4116     EGOTO(error_exit, code, "Could not start the dump process \n");
4117     VEDONE;
4118
4119     VEPRINT1("Dumping volume %u...", afromvol);
4120     code = DumpFunction(fromcall, rock);
4121     if (code == RXGEN_OPCODE)
4122         goto error_exit;
4123     EGOTO(error_exit, code, "Error while dumping volume \n");
4124     VEDONE;
4125
4126   error_exit:
4127     if (fromcall) {
4128         code = rx_EndCall(fromcall, rxError);
4129         if (code && code != RXGEN_OPCODE)
4130             fprintf(STDERR, "Error in rx_EndCall\n");
4131         if (code && !error)
4132             error = code;
4133     }
4134     if (fromtid) {
4135         VEPRINT1("Ending transaction on volume %u...", afromvol);
4136         code = AFSVolEndTrans(fromconn, fromtid, &rcode);
4137         if (code || rcode) {
4138             fprintf(STDERR, "Could not end transaction on the volume %lu\n",
4139                     (unsigned long)afromvol);
4140             if (!error)
4141                 error = (code ? code : rcode);
4142         }
4143         VEDONE;
4144     }
4145     if (fromconn)
4146         rx_DestroyConnection(fromconn);
4147
4148     if (error != RXGEN_OPCODE)
4149         PrintError("", error);
4150     return (error);
4151 }
4152
4153 /* Clone the volume <afromvol> on <afromserver> and
4154  * <afrompart>, and then dump the clone volume to
4155  * <afilename> starting from <fromdate>.
4156  * DumpFunction does the real work behind the scenes after
4157  * extracting parameters from the rock
4158  */
4159 int
4160 UV_DumpClonedVolume(afs_uint32 afromvol, afs_uint32 afromserver,
4161                     afs_int32 afrompart, afs_int32 fromdate,
4162                     afs_int32(*DumpFunction) (struct rx_call *, void *),
4163                     void *rock, afs_int32 flags)
4164 {
4165     /* declare stuff 'volatile' that may be used from setjmp/longjmp and may
4166      * be changing during the dump */
4167     struct rx_connection * volatile fromconn = NULL;
4168     struct rx_call * volatile fromcall = NULL;
4169     afs_int32 volatile clonetid = 0;
4170     afs_uint32 volatile clonevol = 0;
4171
4172     afs_int32 tmp;
4173     afs_int32 fromtid = 0, rxError = 0, rcode = 0;
4174     afs_int32 code = 0, error = 0;
4175     afs_uint32 tmpVol;
4176     char vname[64];
4177     time_t tmv = fromdate;
4178
4179     if (setjmp(env))
4180         ERROR_EXIT(EPIPE);
4181 #ifndef AFS_NT40_ENV
4182     (void)signal(SIGPIPE, dump_sig_handler);
4183 #endif
4184     (void)signal(SIGINT, dump_sig_handler);
4185
4186     if (!fromdate) {
4187         VEPRINT("Full Dump ...\n");
4188     } else {
4189         VEPRINT1("Incremental Dump (as of %.24s)...\n",
4190                 ctime(&tmv));
4191     }
4192
4193     /* get connections to the servers */
4194     fromconn = UV_Bind(afromserver, AFSCONF_VOLUMEPORT);
4195
4196     VEPRINT1("Starting transaction on volume %u...", afromvol);
4197     code = AFSVolTransCreate_retry(fromconn, afromvol, afrompart, ITBusy, &fromtid);
4198     EGOTO1(error_exit, code,
4199            "Could not start transaction on the volume %u to be dumped\n",
4200            afromvol);
4201     VEDONE;
4202
4203     /* Get a clone id */
4204     VEPRINT1("Allocating new volume id for clone of volume %u ...", afromvol);
4205     tmpVol = clonevol;
4206     code = ubik_VL_GetNewVolumeId(cstruct, 0, 1, &tmpVol);
4207     clonevol = tmpVol;
4208     EGOTO1(error_exit, code,
4209            "Could not get an ID for the clone of volume %u from the VLDB\n",
4210            afromvol);
4211     VEDONE;
4212
4213     /* Do the clone. Default flags on clone are set to delete on salvage and out of service */
4214     VEPRINT2("Cloning source volume %u to clone volume %u...", afromvol,
4215             clonevol);
4216     strcpy(vname, "dump-clone-temp");
4217     tmpVol = clonevol;
4218     code =
4219         AFSVolClone(fromconn, fromtid, 0, readonlyVolume, vname, &tmpVol);
4220     clonevol = tmpVol;
4221     EGOTO1(error_exit, code, "Failed to clone the source volume %u\n",
4222            afromvol);
4223     VEDONE;
4224
4225     VEPRINT1("Ending the transaction on the volume %u ...", afromvol);
4226     rcode = 0;
4227     code = AFSVolEndTrans(fromconn, fromtid, &rcode);
4228     fromtid = 0;
4229     if (!code)
4230         code = rcode;
4231     EGOTO1(error_exit, code,
4232            "Failed to end the transaction on the volume %u\n", afromvol);
4233     VEDONE;
4234
4235
4236     VEPRINT1("Starting transaction on the cloned volume %u ...", clonevol);
4237     tmp = clonetid;
4238     code =
4239         AFSVolTransCreate_retry(fromconn, clonevol, afrompart, ITOffline,
4240                           &tmp);
4241     clonetid = tmp;
4242     EGOTO1(error_exit, code,
4243            "Failed to start a transaction on the cloned volume%u\n",
4244            clonevol);
4245     VEDONE;
4246
4247     VEPRINT1("Setting flags on cloned volume %u ...", clonevol);
4248     code = AFSVolSetFlags(fromconn, clonetid, VTDeleteOnSalvage | VTOutOfService);      /*redundant */
4249     EGOTO1(error_exit, code, "Could not set falgs on the cloned volume %u\n",
4250            clonevol);
4251     VEDONE;
4252
4253
4254     fromcall = rx_NewCall(fromconn);
4255
4256     VEPRINT1("Starting volume dump from cloned volume %u...", clonevol);
4257     if (flags & VOLDUMPV2_OMITDIRS)
4258         code = StartAFSVolDumpV2(fromcall, clonetid, fromdate, flags);
4259     else
4260         code = StartAFSVolDump(fromcall, clonetid, fromdate);
4261     EGOTO(error_exit, code, "Could not start the dump process \n");
4262     VEDONE;
4263
4264     VEPRINT1("Dumping volume %u...", afromvol);
4265     code = DumpFunction(fromcall, rock);
4266     EGOTO(error_exit, code, "Error while dumping volume \n");
4267     VEDONE;
4268
4269   error_exit:
4270     /* now delete the clone */
4271     VEPRINT1("Deleting the cloned volume %u ...", clonevol);
4272     code = AFSVolDeleteVolume(fromconn, clonetid);
4273     if (code) {
4274         fprintf(STDERR, "Failed to delete the cloned volume %lu\n",
4275                 (unsigned long)clonevol);
4276     } else {
4277         VEDONE;
4278     }
4279
4280     if (fromcall) {
4281         code = rx_EndCall(fromcall, rxError);
4282         if (code) {
4283             fprintf(STDERR, "Error in rx_EndCall\n");
4284             if (!error)
4285                 error = code;
4286         }
4287     }
4288     if (clonetid) {
4289         VEPRINT1("Ending transaction on cloned volume %u...", clonevol);
4290         code = AFSVolEndTrans(fromconn, clonetid, &rcode);
4291         if (code || rcode) {
4292             fprintf(STDERR,
4293                     "Could not end transaction on the cloned volume %lu\n",
4294                     (unsigned long)clonevol);
4295             if (!error)
4296                 error = (code ? code : rcode);
4297         }
4298         VEDONE;
4299     }
4300     if (fromconn)
4301         rx_DestroyConnection(fromconn);
4302
4303     PrintError("", error);
4304     return (error);
4305 }
4306
4307
4308
4309 /*
4310  * Restore a volume <tovolid> <tovolname> on <toserver> <topart> from
4311  * the dump file <afilename>. WriteData does all the real work
4312  * after extracting params from the rock
4313  */
4314 int
4315 UV_RestoreVolume2(afs_uint32 toserver, afs_int32 topart, afs_uint32 tovolid,
4316                   afs_uint32 toparentid, char tovolname[], int flags,
4317                   afs_int32(*WriteData) (struct rx_call *, void *),
4318                   void *rock)
4319 {
4320     struct rx_connection *toconn, *tempconn;
4321     struct rx_call *tocall;
4322     afs_int32 totid, code, rcode, vcode, terror = 0;
4323     afs_int32 rxError = 0;
4324     struct volser_status tstatus;
4325     struct volintInfo vinfo;
4326     char partName[10];
4327     char tovolreal[VOLSER_OLDMAXVOLNAME];
4328     afs_uint32 pvolid;
4329     afs_int32 temptid, pparentid;
4330     int success;
4331     struct nvldbentry entry, storeEntry;
4332     afs_int32 error;
4333     int islocked;
4334     struct restoreCookie cookie;
4335     int reuseID;
4336     afs_int32 volflag, voltype, volsertype;
4337     afs_int32 oldCreateDate, oldUpdateDate, newCreateDate, newUpdateDate;
4338     int index, same, errcode;
4339     char apartName[10];
4340     char hoststr[16];
4341
4342     memset(&cookie, 0, sizeof(cookie));
4343     islocked = 0;
4344     success = 0;
4345     error = 0;
4346     reuseID = 1;
4347     tocall = (struct rx_call *)0;
4348     toconn = (struct rx_connection *)0;
4349     tempconn = (struct rx_connection *)0;
4350     totid = 0;
4351     temptid = 0;
4352
4353     if (flags & RV_RDONLY) {
4354         voltype = ROVOL;
4355         volsertype = volser_RO;
4356     } else {
4357         voltype = RWVOL;
4358         volsertype = volser_RW;
4359     }
4360
4361     pvolid = tovolid;
4362     pparentid = toparentid;
4363     toconn = UV_Bind(toserver, AFSCONF_VOLUMEPORT);
4364     if (pvolid == 0) {          /*alot a new id if needed */
4365         vcode = VLDB_GetEntryByName(tovolname, &entry);
4366         if (vcode == VL_NOENT) {
4367             vcode = ubik_VL_GetNewVolumeId(cstruct, 0, 1, &pvolid);
4368             if (vcode) {
4369                 fprintf(STDERR, "Could not get an Id for the volume %s\n",
4370                         tovolname);
4371                 error = vcode;
4372                 goto refail;
4373             }
4374             reuseID = 0;
4375         } else if (flags & RV_RDONLY) {
4376             if (entry.flags & RW_EXISTS) {
4377                 fprintf(STDERR,
4378                         "Entry for ReadWrite volume %s already exists!\n",
4379                         entry.name);
4380                 error = VOLSERBADOP;
4381                 goto refail;
4382             }
4383             if (!entry.volumeId[ROVOL]) {
4384                 fprintf(STDERR,
4385                         "Existing entry for volume %s has no ReadOnly ID\n",
4386                         tovolname);
4387                 error = VOLSERBADOP;
4388                 goto refail;
4389             }
4390             pvolid = entry.volumeId[ROVOL];
4391             pparentid = entry.volumeId[RWVOL];
4392         } else {
4393             pvolid = entry.volumeId[RWVOL];
4394             pparentid = entry.volumeId[RWVOL];
4395         }
4396     }
4397     if (!pparentid) pparentid = pvolid;
4398     /* at this point we have a volume id to use/reuse for the volume to be restored */
4399     strncpy(tovolreal, tovolname, VOLSER_OLDMAXVOLNAME);
4400
4401     if (strlen(tovolname) > (VOLSER_OLDMAXVOLNAME - 1)) {
4402         EGOTO1(refail, VOLSERBADOP,
4403                "The volume name %s exceeds the maximum limit of (VOLSER_OLDMAXVOLNAME -1 ) bytes\n",
4404                tovolname);
4405     } else {
4406         if ((pparentid != pvolid) && (flags & RV_RDONLY)) {
4407             if (strlen(tovolname) > (VOLSER_OLDMAXVOLNAME - 10)) {
4408                 EGOTO1(refail, VOLSERBADOP,
4409                        "The volume name %s exceeds the maximum limit of (VOLSER_OLDMAXVOLNAME -1 ) bytes\n", tovolname);
4410             }
4411             snprintf(tovolreal, VOLSER_OLDMAXVOLNAME, "%s.readonly", tovolname);
4412         }
4413     }
4414     MapPartIdIntoName(topart, partName);
4415     fprintf(STDOUT, "Restoring volume %s Id %lu on server %s partition %s ..",
4416             tovolreal, (unsigned long)pvolid,
4417             noresolve ? afs_inet_ntoa_r(toserver, hoststr) :
4418             hostutil_GetNameByINet(toserver), partName);
4419     fflush(STDOUT);
4420     code =
4421         AFSVolCreateVolume(toconn, topart, tovolreal, volsertype, pparentid, &pvolid,
4422                            &totid);
4423     if (code) {
4424         if (flags & RV_FULLRST) {       /* full restore: delete then create anew */
4425             VPRINT1("Deleting the previous volume %u ...", pvolid);
4426
4427             code =
4428                 AFSVolTransCreate_retry(toconn, pvolid, topart, ITOffline, &totid);
4429             EGOTO1(refail, code, "Failed to start transaction on %u\n",
4430                    pvolid);
4431
4432             code = AFSVolGetStatus(toconn, totid, &tstatus);
4433             EGOTO1(refail, code, "Could not get timestamp from volume %u\n",
4434                    pvolid);
4435
4436             oldCreateDate = tstatus.creationDate;
4437             oldUpdateDate = tstatus.updateDate;
4438
4439             code =
4440                 AFSVolSetFlags(toconn, totid,
4441                                VTDeleteOnSalvage | VTOutOfService);
4442             EGOTO1(refail, code, "Could not set flags on volume %u \n",
4443                    pvolid);
4444
4445             code = AFSVolDeleteVolume(toconn, totid);
4446             EGOTO1(refail, code, "Could not delete volume %u\n", pvolid);
4447
4448             code = AFSVolEndTrans(toconn, totid, &rcode);
4449             totid = 0;
4450             if (!code)
4451                 code = rcode;
4452             EGOTO1(refail, code, "Could not end transaction on %u\n", pvolid);
4453
4454             VDONE;
4455
4456             code =
4457                 AFSVolCreateVolume(toconn, topart, tovolreal, volsertype, pparentid,
4458                                    &pvolid, &totid);
4459             EGOTO1(refail, code, "Could not create new volume %u\n", pvolid);
4460         } else {
4461             code =
4462                 AFSVolTransCreate_retry(toconn, pvolid, topart, ITOffline, &totid);
4463             EGOTO1(refail, code, "Failed to start transaction on %u\n",
4464                    pvolid);
4465
4466             code = AFSVolGetStatus(toconn, totid, &tstatus);
4467             EGOTO1(refail, code, "Could not get timestamp from volume %u\n",
4468                    pvolid);
4469
4470             oldCreateDate = tstatus.creationDate;
4471             oldUpdateDate = tstatus.updateDate;
4472         }
4473     } else {
4474         oldCreateDate = 0;
4475         oldUpdateDate = 0;
4476     }
4477
4478     cookie.parent = pparentid;
4479     cookie.type = voltype;
4480     cookie.clone = 0;
4481     strncpy(cookie.name, tovolreal, VOLSER_OLDMAXVOLNAME);
4482
4483     tocall = rx_NewCall(toconn);
4484     terror = StartAFSVolRestore(tocall, totid, 1, &cookie);
4485     if (terror) {
4486         fprintf(STDERR, "Volume restore Failed \n");
4487         error = terror;
4488         goto refail;
4489     }
4490     code = WriteData(tocall, rock);
4491     if (code) {
4492         fprintf(STDERR, "Could not transmit data\n");
4493         error = code;
4494         goto refail;
4495     }
4496     terror = rx_EndCall(tocall, rxError);
4497     tocall = (struct rx_call *)0;
4498     if (terror) {
4499         fprintf(STDERR, "rx_EndCall Failed \n");
4500         error = terror;
4501         goto refail;
4502     }
4503     code = AFSVolGetStatus(toconn, totid, &tstatus);
4504     if (code) {
4505         fprintf(STDERR,
4506                 "Could not get status information about the volume %lu\n",
4507                 (unsigned long)pvolid);
4508         error = code;
4509         goto refail;
4510     }
4511     code = AFSVolSetIdsTypes(toconn, totid, tovolreal, voltype, pparentid, 0, 0);
4512     if (code) {
4513         fprintf(STDERR, "Could not set the right type and ID on %lu\n",
4514                 (unsigned long)pvolid);
4515         error = code;
4516         goto refail;
4517     }
4518
4519     if (flags & RV_CRDUMP)
4520         newCreateDate = tstatus.creationDate;
4521     else if (flags & RV_CRKEEP && oldCreateDate != 0)
4522         newCreateDate = oldCreateDate;
4523     else
4524         newCreateDate = time(0);
4525     if (flags & RV_LUDUMP)
4526         newUpdateDate = tstatus.updateDate;
4527     else if (flags & RV_LUKEEP)
4528         newUpdateDate = oldUpdateDate;
4529     else
4530         newUpdateDate = time(0);
4531     code = AFSVolSetDate(toconn,totid, newCreateDate);
4532     if (code) {
4533         fprintf(STDERR, "Could not set the 'creation' date on %u\n", pvolid);
4534         error = code;
4535         goto refail;
4536     }
4537
4538     init_volintInfo(&vinfo);
4539     vinfo.creationDate = newCreateDate;
4540     vinfo.updateDate = newUpdateDate;
4541     code = AFSVolSetInfo(toconn, totid, &vinfo);
4542     if (code) {
4543         fprintf(STDERR, "Could not set the 'last updated' date on %u\n",
4544                 pvolid);
4545         error = code;
4546         goto refail;
4547     }
4548
4549     volflag = ((flags & RV_OFFLINE) ? VTOutOfService : 0);      /* off or on-line */
4550     code = AFSVolSetFlags(toconn, totid, volflag);
4551     if (code) {
4552         fprintf(STDERR, "Could not mark %lu online\n", (unsigned long)pvolid);
4553         error = code;
4554         goto refail;
4555     }
4556
4557 /* It isn't handled right in refail */
4558     code = AFSVolEndTrans(toconn, totid, &rcode);
4559     totid = 0;
4560     if (!code)
4561         code = rcode;
4562     if (code) {
4563         fprintf(STDERR, "Could not end transaction on %lu\n",
4564                 (unsigned long)pvolid);
4565         error = code;
4566         goto refail;
4567     }
4568
4569     success = 1;
4570     fprintf(STDOUT, " done\n");
4571     fflush(STDOUT);
4572     if (success && (!reuseID || (flags & RV_FULLRST))) {
4573         /* Volume was restored on the file server, update the
4574          * VLDB to reflect the change.
4575          */
4576         vcode = VLDB_GetEntryByID(pvolid, voltype, &entry);
4577         if (vcode && vcode != VL_NOENT && vcode != VL_ENTDELETED) {
4578             fprintf(STDERR,
4579                     "Could not fetch the entry for volume number %lu from VLDB \n",
4580                     (unsigned long)pvolid);
4581             error = vcode;
4582             goto refail;
4583         }
4584         if (!vcode)
4585             MapHostToNetwork(&entry);
4586         if (vcode == VL_NOENT) {        /* it doesnot exist already */
4587             /*make the vldb return this indication specifically */
4588             VPRINT("------- Creating a new VLDB entry ------- \n");
4589             strcpy(entry.name, tovolname);
4590             entry.nServers = 1;
4591             entry.serverNumber[0] = toserver;   /*should be indirect */
4592             entry.serverPartition[0] = topart;
4593             entry.serverFlags[0] = (flags & RV_RDONLY) ? ITSROVOL : ITSRWVOL;
4594             entry.flags = (flags & RV_RDONLY) ? RO_EXISTS : RW_EXISTS;
4595             if (flags & RV_RDONLY)
4596                 entry.volumeId[ROVOL] = pvolid;
4597             else if (tstatus.cloneID != 0) {
4598                 entry.volumeId[ROVOL] = tstatus.cloneID;        /*this should come from status info on the volume if non zero */
4599             } else
4600                 entry.volumeId[ROVOL] = INVALID_BID;
4601             entry.volumeId[RWVOL] = pparentid;
4602             entry.cloneId = 0;
4603             if (tstatus.backupID != 0) {
4604                 entry.volumeId[BACKVOL] = tstatus.backupID;
4605                 /*this should come from status info on the volume if non zero */
4606             } else
4607                 entry.volumeId[BACKVOL] = INVALID_BID;
4608             MapNetworkToHost(&entry, &storeEntry);
4609             vcode = VLDB_CreateEntry(&storeEntry);
4610             if (vcode) {
4611                 fprintf(STDERR,
4612                         "Could not create the VLDB entry for volume number %lu  \n",
4613                         (unsigned long)pvolid);
4614                 error = vcode;
4615                 goto refail;
4616             }
4617             islocked = 0;
4618             if (verbose)
4619                 EnumerateEntry(&entry);
4620         } else {                /*update the existing entry */
4621             if (verbose) {
4622                 fprintf(STDOUT, "Updating the existing VLDB entry\n");
4623                 fprintf(STDOUT, "------- Old entry -------\n");
4624                 EnumerateEntry(&entry);
4625                 fprintf(STDOUT, "------- New entry -------\n");
4626             }
4627             vcode =
4628                 ubik_VL_SetLock(cstruct, 0, pvolid, voltype,
4629                           VLOP_RESTORE);
4630             if (vcode) {
4631                 fprintf(STDERR,
4632                         "Could not lock the entry for volume number %lu \n",
4633                         (unsigned long)pvolid);
4634                 error = vcode;
4635                 goto refail;
4636             }
4637             islocked = 1;
4638             strcpy(entry.name, tovolname);
4639
4640             /* Update the vlentry with the new information */
4641             if (flags & RV_RDONLY)
4642                 index = Lp_ROMatch(toserver, topart, &entry) - 1;
4643             else
4644                 index = Lp_GetRwIndex(&entry);
4645             if (index == -1) {
4646                 /* Add the new site for the volume being restored */
4647                 entry.serverNumber[entry.nServers] = toserver;
4648                 entry.serverPartition[entry.nServers] = topart;
4649                 entry.serverFlags[entry.nServers] =
4650                     (flags & RV_RDONLY) ? ITSROVOL : ITSRWVOL;
4651                 entry.nServers++;
4652             } else {
4653                 /* This volume should be deleted on the old site
4654                  * if its different from new site.
4655                  */
4656                 same =
4657                     VLDB_IsSameAddrs(toserver, entry.serverNumber[index],
4658                                      &errcode);
4659                 if (errcode)
4660                     EPRINT2(errcode,
4661                             "Failed to get info about server's %d address(es) from vlserver (err=%d)\n",
4662                             toserver, errcode);
4663                 if ((!errcode && !same)
4664                     || (entry.serverPartition[index] != topart)) {
4665                     if (flags & RV_NODEL) {
4666                         VPRINT2
4667                             ("Not deleting the previous volume %u on server %s, ...",
4668                              pvolid,
4669                              noresolve ? afs_inet_ntoa_r(entry.serverNumber[index], hoststr) :
4670                              hostutil_GetNameByINet(entry.serverNumber[index]));
4671                     } else {
4672                         tempconn =
4673                             UV_Bind(entry.serverNumber[index],
4674                                     AFSCONF_VOLUMEPORT);
4675
4676                         MapPartIdIntoName(entry.serverPartition[index],
4677                                           apartName);
4678                         VPRINT3
4679                             ("Deleting the previous volume %u on server %s, partition %s ...",
4680                              pvolid,
4681                              noresolve ? afs_inet_ntoa_r(entry.serverNumber[index], hoststr) :
4682                              hostutil_GetNameByINet(entry.serverNumber[index]),
4683                              apartName);
4684                         code =
4685                             AFSVolTransCreate_retry(tempconn, pvolid,
4686                                               entry.serverPartition[index],
4687                                               ITOffline, &temptid);
4688                         if (!code) {
4689                             code =
4690                                 AFSVolSetFlags(tempconn, temptid,
4691                                                VTDeleteOnSalvage |
4692                                                VTOutOfService);
4693                             if (code) {
4694                                 fprintf(STDERR,
4695                                         "Could not set flags on volume %lu on the older site\n",
4696                                         (unsigned long)pvolid);
4697                                 error = code;
4698                                 goto refail;
4699                             }
4700                             code = AFSVolDeleteVolume(tempconn, temptid);
4701                             if (code) {
4702                                 fprintf(STDERR,
4703                                         "Could not delete volume %lu on the older site\n",
4704                                         (unsigned long)pvolid);
4705                                 error = code;
4706                                 goto refail;
4707                             }
4708                             code = AFSVolEndTrans(tempconn, temptid, &rcode);
4709                             temptid = 0;
4710                             if (!code)
4711                                 code = rcode;
4712                             if (code) {
4713                                 fprintf(STDERR,
4714                                         "Could not end transaction on volume %lu on the older site\n",
4715                                         (unsigned long)pvolid);
4716                                 error = code;
4717                                 goto refail;
4718                             }
4719                             VDONE;
4720                             MapPartIdIntoName(entry.serverPartition[index],
4721                                               partName);
4722                         }
4723                     }
4724                 }
4725                 entry.serverNumber[index] = toserver;
4726                 entry.serverPartition[index] = topart;
4727             }
4728
4729             entry.flags |= (flags & RV_RDONLY) ? RO_EXISTS : RW_EXISTS;
4730             MapNetworkToHost(&entry, &storeEntry);
4731             vcode =
4732                 VLDB_ReplaceEntry(pvolid, voltype, &storeEntry,
4733                                   LOCKREL_OPCODE | LOCKREL_AFSID |
4734                                   LOCKREL_TIMESTAMP);
4735             if (vcode) {
4736                 fprintf(STDERR,
4737                         "Could not update the entry for volume number %lu  \n",
4738                         (unsigned long)pvolid);
4739                 error = vcode;
4740                 goto refail;
4741             }
4742             islocked = 0;
4743             if (verbose)
4744                 EnumerateEntry(&entry);
4745         }
4746
4747
4748     }
4749   refail:
4750     if (tocall) {
4751         code = rx_EndCall(tocall, rxError);
4752         if (!error)
4753             error = code;
4754     }
4755     if (islocked) {
4756         vcode =
4757             ubik_VL_ReleaseLock(cstruct, 0, pvolid, voltype,
4758                       LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
4759         if (vcode) {
4760             fprintf(STDERR,
4761                     "Could not release lock on the VLDB entry for the volume %lu\n",
4762                     (unsigned long)pvolid);
4763             if (!error)
4764                 error = vcode;
4765         }
4766     }
4767     if (totid) {
4768         code = AFSVolEndTrans(toconn, totid, &rcode);
4769         if (!code)
4770             code = rcode;
4771         if (code) {
4772             fprintf(STDERR, "Could not end transaction on the volume %lu \n",
4773                     (unsigned long)pvolid);
4774             if (!error)
4775                 error = code;
4776         }
4777     }
4778     if (temptid) {
4779         code = AFSVolEndTrans(toconn, temptid, &rcode);
4780         if (!code)
4781             code = rcode;
4782         if (code) {
4783             fprintf(STDERR, "Could not end transaction on the volume %lu \n",
4784                     (unsigned long)pvolid);
4785             if (!error)
4786                 error = code;
4787         }
4788     }
4789     if (tempconn)
4790         rx_DestroyConnection(tempconn);
4791     if (toconn)
4792         rx_DestroyConnection(toconn);
4793     PrintError("", error);
4794     return error;
4795 }
4796
4797 int
4798 UV_RestoreVolume(afs_uint32 toserver, afs_int32 topart, afs_uint32 tovolid,
4799                  char tovolname[], int flags,
4800                  afs_int32(*WriteData) (struct rx_call *, void *),
4801                  void *rock)
4802 {
4803     return UV_RestoreVolume2(toserver, topart, tovolid, 0, tovolname, flags,
4804                              WriteData, rock);
4805 }
4806
4807
4808 /*unlocks the vldb entry associated with <volid> */
4809 int
4810 UV_LockRelease(afs_uint32 volid)
4811 {
4812     afs_int32 vcode;
4813
4814     VPRINT("Binding to the VLDB server\n");
4815     vcode =
4816         ubik_VL_ReleaseLock(cstruct, 0, volid, -1,
4817                   LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
4818     if (vcode) {
4819         fprintf(STDERR,
4820                 "Could not unlock the entry for volume number %lu in VLDB \n",
4821                 (unsigned long)volid);
4822         PrintError("", vcode);
4823         return (vcode);
4824     }
4825     VPRINT("VLDB updated\n");
4826     return 0;
4827
4828 }
4829
4830 /* old interface to add rosites */
4831 int
4832 UV_AddSite(afs_uint32 server, afs_int32 part, afs_uint32 volid,
4833            afs_int32 valid)
4834 {
4835     return UV_AddSite2(server, part, volid, 0, valid);
4836 }
4837
4838 /*adds <server> and <part> as a readonly replication site for <volid>
4839 *in vldb */
4840 int
4841 UV_AddSite2(afs_uint32 server, afs_int32 part, afs_uint32 volid,
4842             afs_uint32 rovolid, afs_int32 valid)
4843 {
4844     int j, nro = 0, islocked = 0;
4845     struct nvldbentry entry, storeEntry, entry2;
4846     afs_int32 vcode, error = 0;
4847     char apartName[10];
4848
4849     error = ubik_VL_SetLock(cstruct, 0, volid, RWVOL, VLOP_ADDSITE);
4850     if (error) {
4851         fprintf(STDERR,
4852                 " Could not lock the VLDB entry for the volume %lu \n",
4853                 (unsigned long)volid);
4854         goto asfail;
4855     }
4856     islocked = 1;
4857
4858     error = VLDB_GetEntryByID(volid, RWVOL, &entry);
4859     if (error) {
4860         fprintf(STDERR,
4861                 "Could not fetch the VLDB entry for volume number %lu  \n",
4862                 (unsigned long)volid);
4863         goto asfail;
4864
4865     }
4866     if (!ISNAMEVALID(entry.name)) {
4867         fprintf(STDERR,
4868                 "Volume name %s is too long, rename before adding site\n",
4869                 entry.name);
4870         error = VOLSERBADOP;
4871         goto asfail;
4872     }
4873     MapHostToNetwork(&entry);
4874
4875     /* See if it's too many entries */
4876     if (entry.nServers >= NMAXNSERVERS) {
4877         fprintf(STDERR, "Total number of entries will exceed %u\n",
4878                 NMAXNSERVERS);
4879         error = VOLSERBADOP;
4880         goto asfail;
4881     }
4882
4883     /* See if it's on the same server */
4884     for (j = 0; j < entry.nServers; j++) {
4885         if (entry.serverFlags[j] & ITSROVOL) {
4886             nro++;
4887             if (VLDB_IsSameAddrs(server, entry.serverNumber[j], &error)) {
4888                 if (error) {
4889                     fprintf(STDERR,
4890                             "Failed to get info about server's %d address(es) from vlserver (err=%d); aborting call!\n",
4891                             server, error);
4892                 } else {
4893                     MapPartIdIntoName(entry.serverPartition[j], apartName);
4894                     fprintf(STDERR,
4895                             "RO already exists on partition %s. Multiple ROs on a single server aren't allowed\n",
4896                             apartName);
4897                     error = VOLSERBADOP;
4898                 }
4899                 goto asfail;
4900             }
4901         }
4902     }
4903
4904     /* See if it's too many RO sites - leave one for the RW */
4905     if (nro >= NMAXNSERVERS - 1) {
4906         fprintf(STDERR, "Total number of sites will exceed %u\n",
4907                 NMAXNSERVERS - 1);
4908         error = VOLSERBADOP;
4909         goto asfail;
4910     }
4911
4912     /* if rovolid == 0, we leave the RO volume id alone. If the volume doesn't
4913      * have an RO volid at this point (i.e. entry.volumeId[ROVOL] ==
4914      * INVALID_BID) and we leave it alone, it gets an RO volid at release-time.
4915      */
4916     if (rovolid) {
4917         if (entry.volumeId[ROVOL] == INVALID_BID) {
4918             vcode = VLDB_GetEntryByID(rovolid, -1, &entry2);
4919             if (!vcode) {
4920                 fprintf(STDERR, "Volume ID %d already exists\n", rovolid);
4921                 return VVOLEXISTS;
4922             }
4923             VPRINT1("Using RO volume id %d.\n", rovolid);
4924             entry.volumeId[ROVOL] = rovolid;
4925         } else {
4926             fprintf(STDERR, "Ignoring given RO id %d, since volume already has RO id %d\n",
4927                 rovolid, entry.volumeId[ROVOL]);
4928         }
4929     }
4930
4931     VPRINT("Adding a new site ...");
4932     entry.serverNumber[entry.nServers] = server;
4933     entry.serverPartition[entry.nServers] = part;
4934     if (!valid) {
4935         entry.serverFlags[entry.nServers] = (ITSROVOL | RO_DONTUSE);
4936     } else {
4937         entry.serverFlags[entry.nServers] = (ITSROVOL);
4938     }
4939     entry.nServers++;
4940
4941     MapNetworkToHost(&entry, &storeEntry);
4942     error =
4943         VLDB_ReplaceEntry(volid, RWVOL, &storeEntry,
4944                           LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
4945     if (error) {
4946         fprintf(STDERR, "Could not update entry for volume %lu \n",
4947                 (unsigned long)volid);
4948         goto asfail;
4949     }
4950     islocked = 0;
4951     VDONE;
4952
4953   asfail:
4954     if (islocked) {
4955         vcode =
4956             ubik_VL_ReleaseLock(cstruct, 0, volid, RWVOL,
4957                       LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
4958         if (vcode) {
4959             fprintf(STDERR,
4960                     "Could not release lock on volume entry for %lu \n",
4961                     (unsigned long)volid);
4962             PrintError("", vcode);
4963         }
4964     }
4965
4966     PrintError("", error);
4967     return error;
4968 }
4969
4970 /*removes <server> <part> as read only site for <volid> from the vldb */
4971 int
4972 UV_RemoveSite(afs_uint32 server, afs_int32 part, afs_uint32 volid)
4973 {
4974     afs_int32 vcode;
4975     struct nvldbentry entry, storeEntry;
4976
4977     vcode = ubik_VL_SetLock(cstruct, 0, volid, RWVOL, VLOP_ADDSITE);
4978     if (vcode) {
4979         fprintf(STDERR, " Could not lock the VLDB entry for volume %lu \n",
4980                 (unsigned long)volid);
4981         PrintError("", vcode);
4982         return (vcode);
4983     }
4984     vcode = VLDB_GetEntryByID(volid, RWVOL, &entry);
4985     if (vcode) {
4986         fprintf(STDERR,
4987                 "Could not fetch the entry for volume number %lu from VLDB \n",
4988                 (unsigned long)volid);
4989         PrintError("", vcode);
4990         return (vcode);
4991     }
4992     MapHostToNetwork(&entry);
4993     if (!Lp_ROMatch(server, part, &entry)) {
4994         /*this site doesnot exist  */
4995         fprintf(STDERR, "This site is not a replication site \n");
4996         vcode =
4997             ubik_VL_ReleaseLock(cstruct, 0, volid, RWVOL,
4998                       LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
4999         if (vcode) {
5000             fprintf(STDERR, "Could not update entry for volume %lu \n",
5001                     (unsigned long)volid);
5002             PrintError("", vcode);
5003             ubik_VL_ReleaseLock(cstruct, 0, volid, RWVOL,
5004                       LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
5005             return (vcode);
5006         }
5007         return VOLSERBADOP;
5008     } else {                    /*remove the rep site */
5009         Lp_SetROValue(&entry, server, part, 0, 0);
5010         entry.nServers--;
5011         if ((entry.nServers == 1) && (entry.flags & RW_EXISTS))
5012             entry.flags &= ~RO_EXISTS;
5013         if (entry.nServers < 1) {       /*this is the last ref */
5014             VPRINT1("Deleting the VLDB entry for %u ...", volid);
5015             fflush(STDOUT);
5016             vcode = ubik_VL_DeleteEntry(cstruct, 0, volid, ROVOL);
5017             if (vcode) {
5018                 fprintf(STDERR,
5019                         "Could not delete VLDB entry for volume %lu \n",
5020                         (unsigned long)volid);
5021                 PrintError("", vcode);
5022                 return (vcode);
5023             }
5024             VDONE;
5025         }
5026         MapNetworkToHost(&entry, &storeEntry);
5027         fprintf(STDOUT, "Deleting the replication site for volume %lu ...",
5028                 (unsigned long)volid);
5029         fflush(STDOUT);
5030         vcode =
5031             VLDB_ReplaceEntry(volid, RWVOL, &storeEntry,
5032                               LOCKREL_OPCODE | LOCKREL_AFSID |
5033                               LOCKREL_TIMESTAMP);
5034         if (vcode) {
5035             fprintf(STDERR,
5036                     "Could not release lock on volume entry for %lu \n",
5037                     (unsigned long)volid);
5038             PrintError("", vcode);
5039             ubik_VL_ReleaseLock(cstruct, 0, volid, RWVOL,
5040                       LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
5041             return (vcode);
5042         }
5043         VDONE;
5044     }
5045     return 0;
5046 }
5047
5048 /*sets <server> <part> as read/write site for <volid> in the vldb */
5049 int
5050 UV_ChangeLocation(afs_uint32 server, afs_int32 part, afs_uint32 volid)
5051 {
5052     afs_int32 vcode;
5053     struct nvldbentry entry, storeEntry;
5054     int index;
5055
5056     vcode = ubik_VL_SetLock(cstruct, 0, volid, RWVOL, VLOP_ADDSITE);
5057     if (vcode) {
5058         fprintf(STDERR, " Could not lock the VLDB entry for volume %lu \n",
5059                 (unsigned long)volid);
5060         PrintError("", vcode);
5061         return (vcode);
5062     }
5063     vcode = VLDB_GetEntryByID(volid, RWVOL, &entry);
5064     if (vcode) {
5065         fprintf(STDERR,
5066                 "Could not fetch the entry for volume number %lu from VLDB \n",
5067                 (unsigned long)volid);
5068         PrintError("", vcode);
5069         return (vcode);
5070     }
5071     MapHostToNetwork(&entry);
5072     index = Lp_GetRwIndex(&entry);
5073     if (index < 0) {
5074         /* no RW site exists  */
5075         fprintf(STDERR, "No existing RW site for volume %lu",
5076                 (unsigned long)volid);
5077         vcode =
5078             ubik_VL_ReleaseLock(cstruct, 0, volid, RWVOL,
5079                       LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
5080         if (vcode) {
5081             fprintf(STDERR,
5082                     "Could not release lock on entry for volume %lu \n",
5083                     (unsigned long)volid);
5084             PrintError("", vcode);
5085             return (vcode);
5086         }
5087         return VOLSERBADOP;
5088     } else {                    /* change the RW site */
5089         entry.serverNumber[index] = server;
5090         entry.serverPartition[index] = part;
5091         MapNetworkToHost(&entry, &storeEntry);
5092         vcode =
5093             VLDB_ReplaceEntry(volid, RWVOL, &storeEntry,
5094                               LOCKREL_OPCODE | LOCKREL_AFSID |
5095                               LOCKREL_TIMESTAMP);
5096         if (vcode) {
5097             fprintf(STDERR, "Could not update entry for volume %lu \n",
5098                     (unsigned long)volid);
5099             PrintError("", vcode);
5100             ubik_VL_ReleaseLock(cstruct, 0, volid, RWVOL,
5101                       LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
5102             return (vcode);
5103         }
5104         VDONE;
5105     }
5106     return 0;
5107 }
5108
5109 /*list all the partitions on <aserver> */
5110 int
5111 UV_ListPartitions(afs_uint32 aserver, struct partList *ptrPartList,
5112                   afs_int32 * cntp)
5113 {
5114     struct rx_connection *aconn;
5115     struct pIDs partIds;
5116     struct partEntries partEnts;
5117     int i, j = 0, code;
5118
5119     *cntp = 0;
5120     aconn = UV_Bind(aserver, AFSCONF_VOLUMEPORT);
5121
5122     partEnts.partEntries_len = 0;
5123     partEnts.partEntries_val = NULL;
5124     code = AFSVolXListPartitions(aconn, &partEnts);     /* this is available only on new servers */
5125     if (code == RXGEN_OPCODE) {
5126         for (i = 0; i < 26; i++)        /* try old interface */
5127             partIds.partIds[i] = -1;
5128         code = AFSVolListPartitions(aconn, &partIds);
5129         if (!code) {
5130             for (i = 0; i < 26; i++) {
5131                 if ((partIds.partIds[i]) != -1) {
5132                     ptrPartList->partId[j] = partIds.partIds[i];
5133                     ptrPartList->partFlags[j] = PARTVALID;
5134                     j++;
5135                 } else
5136                     ptrPartList->partFlags[i] = 0;
5137             }
5138             *cntp = j;
5139         }
5140     } else if (!code) {
5141         *cntp = partEnts.partEntries_len;
5142         if (*cntp > VOLMAXPARTS) {
5143             fprintf(STDERR,
5144                     "Warning: number of partitions on the server too high %d (process only %d)\n",
5145                     *cntp, VOLMAXPARTS);
5146             *cntp = VOLMAXPARTS;
5147         }
5148         for (i = 0; i < *cntp; i++) {
5149             ptrPartList->partId[i] = partEnts.partEntries_val[i];
5150             ptrPartList->partFlags[i] = PARTVALID;
5151         }
5152         free(partEnts.partEntries_val);
5153     }
5154
5155    /* out: */
5156     if (code)
5157         fprintf(STDERR,
5158                 "Could not fetch the list of partitions from the server\n");
5159     PrintError("", code);
5160     if (aconn)
5161         rx_DestroyConnection(aconn);
5162     return code;
5163 }
5164
5165
5166 /*zap the list of volumes specified by volPtrArray (the volCloneId field).
5167  This is used by the backup system */
5168 int
5169 UV_ZapVolumeClones(afs_uint32 aserver, afs_int32 apart,
5170                    struct volDescription *volPtr, afs_int32 arraySize)
5171 {
5172     struct rx_connection *aconn;
5173     struct volDescription *curPtr;
5174     int curPos;
5175     afs_int32 code = 0;
5176     afs_int32 rcode = 0;
5177     afs_int32 success = 1;
5178     afs_int32 tid;
5179
5180     aconn = (struct rx_connection *)0;
5181     aconn = UV_Bind(aserver, AFSCONF_VOLUMEPORT);
5182     curPos = 0;
5183     for (curPtr = volPtr; curPos < arraySize; curPtr++) {
5184         if (curPtr->volFlags & CLONEVALID) {
5185             curPtr->volFlags &= ~CLONEZAPPED;
5186             success = 1;
5187             code =
5188                 AFSVolTransCreate_retry(aconn, curPtr->volCloneId, apart, ITOffline,
5189                                   &tid);
5190             if (code)
5191                 success = 0;
5192             else {
5193                 code = AFSVolDeleteVolume(aconn, tid);
5194                 if (code)
5195                     success = 0;
5196                 code = AFSVolEndTrans(aconn, tid, &rcode);
5197                 if (code || rcode)
5198                     success = 0;
5199             }
5200             if (success)
5201                 curPtr->volFlags |= CLONEZAPPED;
5202             if (!success)
5203                 fprintf(STDERR, "Could not zap volume %lu\n",
5204                         (unsigned long)curPtr->volCloneId);
5205             if (success)
5206                 VPRINT2("Clone of %s %u deleted\n", curPtr->volName,
5207                         curPtr->volCloneId);
5208             curPos++;
5209             tid = 0;
5210         }
5211     }
5212     if (aconn)
5213         rx_DestroyConnection(aconn);
5214     return 0;
5215 }
5216
5217 /*return a list of clones of the volumes specified by volPtrArray. Used by the
5218  backup system */
5219 int
5220 UV_GenerateVolumeClones(afs_uint32 aserver, afs_int32 apart,
5221                         struct volDescription *volPtr, afs_int32 arraySize)
5222 {
5223     struct rx_connection *aconn;
5224     struct volDescription *curPtr;
5225     int curPos;
5226     afs_int32 code = 0;
5227     afs_int32 rcode = 0;
5228     afs_int32 tid;
5229     int reuseCloneId = 0;
5230     afs_uint32 curCloneId = 0;
5231     char cloneName[256];        /*max vol name */
5232
5233     aconn = (struct rx_connection *)0;
5234     aconn = UV_Bind(aserver, AFSCONF_VOLUMEPORT);
5235     curPos = 0;
5236     if ((volPtr->volFlags & REUSECLONEID) && (volPtr->volFlags & ENTRYVALID))
5237         reuseCloneId = 1;
5238     else {                      /*get a bunch of id's from vldb */
5239         code =
5240             ubik_VL_GetNewVolumeId(cstruct, 0, arraySize, &curCloneId);
5241         if (code) {
5242             fprintf(STDERR, "Could not get ID's for the clone from VLDB\n");
5243             PrintError("", code);
5244             return code;
5245         }
5246     }
5247
5248     for (curPtr = volPtr; curPos < arraySize; curPtr++) {
5249         if (curPtr->volFlags & ENTRYVALID) {
5250
5251             curPtr->volFlags |= CLONEVALID;
5252             /*make a clone of curParentId and record as curPtr->volCloneId */
5253             code =
5254                 AFSVolTransCreate_retry(aconn, curPtr->volId, apart, ITOffline,
5255                                   &tid);
5256             if (code)
5257                 VPRINT2("Clone for volume %s %u failed \n", curPtr->volName,
5258                         curPtr->volId);
5259             if (code) {
5260                 curPtr->volFlags &= ~CLONEVALID;        /*cant clone */
5261                 curPos++;
5262                 continue;
5263             }
5264             if (strlen(curPtr->volName) < (VOLSER_OLDMAXVOLNAME - 9)) {
5265                 strcpy(cloneName, curPtr->volName);
5266                 strcat(cloneName, "-tmpClone-");
5267             } else
5268                 strcpy(cloneName, "-tmpClone");
5269             if (reuseCloneId) {
5270                 curPtr->volCloneId = curCloneId;
5271                 curCloneId++;
5272             }
5273
5274             code =
5275                 AFSVolClone(aconn, tid, 0, readonlyVolume, cloneName,
5276                             &(curPtr->volCloneId));
5277             if (code) {
5278                 curPtr->volFlags &= ~CLONEVALID;
5279                 curPos++;
5280                 fprintf(STDERR, "Could not clone %s due to error %lu\n",
5281                         curPtr->volName, (unsigned long)code);
5282                 code = AFSVolEndTrans(aconn, tid, &rcode);
5283                 if (code)
5284                     fprintf(STDERR, "WARNING: could not end transaction\n");
5285                 continue;
5286             }
5287             VPRINT2("********** Cloned %s temporary %u\n", cloneName,
5288                     curPtr->volCloneId);
5289             code = AFSVolEndTrans(aconn, tid, &rcode);
5290             if (code || rcode) {
5291                 curPtr->volFlags &= ~CLONEVALID;
5292                 curPos++;
5293                 continue;
5294             }
5295
5296             curPos++;
5297         }
5298     }
5299     if (aconn)
5300         rx_DestroyConnection(aconn);
5301     return 0;
5302 }
5303
5304
5305 /*list all the volumes on <aserver> and <apart>. If all = 1, then all the
5306 * relevant fields of the volume are also returned. This is a heavy weight operation.*/
5307 int
5308 UV_ListVolumes(afs_uint32 aserver, afs_int32 apart, int all,
5309                struct volintInfo **resultPtr, afs_int32 * size)
5310 {
5311     struct rx_connection *aconn;
5312     afs_int32 code = 0;
5313     volEntries volumeInfo;
5314
5315     code = 0;
5316     *size = 0;
5317     *resultPtr = (volintInfo *) 0;
5318     volumeInfo.volEntries_val = (volintInfo *) 0;       /*this hints the stub to allocate space */
5319     volumeInfo.volEntries_len = 0;
5320
5321     aconn = UV_Bind(aserver, AFSCONF_VOLUMEPORT);
5322     code = AFSVolListVolumes(aconn, apart, all, &volumeInfo);
5323     if (code) {
5324         fprintf(STDERR,
5325                 "Could not fetch the list of volumes from the server\n");
5326     } else {
5327         *resultPtr = volumeInfo.volEntries_val;
5328         *size = volumeInfo.volEntries_len;
5329     }
5330
5331     if (aconn)
5332         rx_DestroyConnection(aconn);
5333     PrintError("", code);
5334     return code;
5335 }
5336
5337 /*------------------------------------------------------------------------
5338  * EXPORTED UV_XListVolumes
5339  *
5340  * Description:
5341  *      List the extended information for all the volumes on a particular
5342  *      File Server and partition.  We may either return the volume's ID
5343  *      or all of its extended information.
5344  *
5345  * Arguments:
5346  *      a_serverID         : Address of the File Server for which we want
5347  *                              extended volume info.
5348  *      a_partID           : Partition for which we want the extended
5349  *                              volume info.
5350  *      a_all              : If non-zero, fetch ALL the volume info,
5351  *                              otherwise just the volume ID.
5352  *      a_resultPP         : Ptr to the address of the area containing
5353  *                              the returned volume info.
5354  *      a_numEntsInResultP : Ptr for the value we set for the number of
5355  *                              entries returned.
5356  *
5357  * Returns:
5358  *      0 on success,
5359  *      Otherise, the return value of AFSVolXListVolumes.
5360  *
5361  * Environment:
5362  *      This routine is closely related to UV_ListVolumes, which returns
5363  *      only the standard level of detail on AFS volumes. It is a
5364  *      heavyweight operation, zipping through all the volume entries for
5365  *      a given server/partition.
5366  *
5367  * Side Effects:
5368  *      As advertised.
5369  *------------------------------------------------------------------------*/
5370
5371 int
5372 UV_XListVolumes(afs_uint32 a_serverID, afs_int32 a_partID, int a_all,
5373                 struct volintXInfo **a_resultPP,
5374                 afs_int32 * a_numEntsInResultP)
5375 {
5376     struct rx_connection *rxConnP;      /*Ptr to the Rx connection involved */
5377     afs_int32 code;             /*Error code to return */
5378     volXEntries volumeXInfo;    /*Area for returned extended vol info */
5379
5380     /*
5381      * Set up our error code and the area for returned extended volume info.
5382      * We set the val field to a null pointer as a hint for the stub to
5383      * allocate space.
5384      */
5385     code = 0;
5386     *a_numEntsInResultP = 0;
5387     *a_resultPP = (volintXInfo *) 0;
5388     volumeXInfo.volXEntries_val = (volintXInfo *) 0;
5389     volumeXInfo.volXEntries_len = 0;
5390
5391     /*
5392      * Bind to the Volume Server port on the File Server machine in question,
5393      * then go for it.
5394      */
5395     rxConnP = UV_Bind(a_serverID, AFSCONF_VOLUMEPORT);
5396     code = AFSVolXListVolumes(rxConnP, a_partID, a_all, &volumeXInfo);
5397     if (code)
5398         fprintf(STDERR, "[UV_XListVolumes] Couldn't fetch volume list\n");
5399     else {
5400         /*
5401          * We got the info; pull out the pointer to where the results lie
5402          * and how many entries are there.
5403          */
5404         *a_resultPP = volumeXInfo.volXEntries_val;
5405         *a_numEntsInResultP = volumeXInfo.volXEntries_len;
5406     }
5407
5408     /*
5409      * If we got an Rx connection, throw it away.
5410      */
5411     if (rxConnP)
5412         rx_DestroyConnection(rxConnP);
5413
5414     PrintError("", code);
5415     return (code);
5416 }                               /*UV_XListVolumes */
5417
5418 /* get all the information about volume <volid> on <aserver> and <apart> */
5419 int
5420 UV_ListOneVolume(afs_uint32 aserver, afs_int32 apart, afs_uint32 volid,
5421                  struct volintInfo **resultPtr)
5422 {
5423     struct rx_connection *aconn;
5424     afs_int32 code = 0;
5425     volEntries volumeInfo;
5426
5427     code = 0;
5428
5429     *resultPtr = (volintInfo *) 0;
5430     volumeInfo.volEntries_val = (volintInfo *) 0;       /*this hints the stub to allocate space */
5431     volumeInfo.volEntries_len = 0;
5432
5433     aconn = UV_Bind(aserver, AFSCONF_VOLUMEPORT);
5434     code = AFSVolListOneVolume(aconn, apart, volid, &volumeInfo);
5435     if (code) {
5436         fprintf(STDERR,
5437                 "Could not fetch the information about volume %lu from the server\n",
5438                 (unsigned long)volid);
5439     } else {
5440         *resultPtr = volumeInfo.volEntries_val;
5441
5442     }
5443
5444     if (aconn)
5445         rx_DestroyConnection(aconn);
5446     PrintError("", code);
5447     return code;
5448 }
5449
5450 /*------------------------------------------------------------------------
5451  * EXPORTED UV_XListOneVolume
5452  *
5453  * Description:
5454  *      List the extended information for a volume on a particular File
5455  *      Server and partition.
5456  *
5457  * Arguments:
5458  *      a_serverID         : Address of the File Server for which we want
5459  *                              extended volume info.
5460  *      a_partID           : Partition for which we want the extended
5461  *                              volume info.
5462  *      a_volID            : Volume ID for which we want the info.
5463  *      a_resultPP         : Ptr to the address of the area containing
5464  *                              the returned volume info.
5465  *
5466  * Returns:
5467  *      0 on success,
5468  *      Otherise, the return value of AFSVolXListOneVolume.
5469  *
5470  * Environment:
5471  *      This routine is closely related to UV_ListOneVolume, which returns
5472  *      only the standard level of detail on the chosen AFS volume.
5473  *
5474  * Side Effects:
5475  *      As advertised.
5476  *------------------------------------------------------------------------*/
5477
5478 int
5479 UV_XListOneVolume(afs_uint32 a_serverID, afs_int32 a_partID, afs_uint32 a_volID,
5480                   struct volintXInfo **a_resultPP)
5481 {
5482     struct rx_connection *rxConnP;      /*Rx connection to Volume Server */
5483     afs_int32 code;             /*Error code */
5484     volXEntries volumeXInfo;    /*Area for returned info */
5485
5486     /*
5487      * Set up our error code, and the area we're in which we are returning
5488      * the info.  Setting the val field to a null pointer tells the stub
5489      * to allocate space for us.
5490      */
5491     code = 0;
5492     *a_resultPP = (volintXInfo *) 0;
5493     volumeXInfo.volXEntries_val = (volintXInfo *) 0;
5494     volumeXInfo.volXEntries_len = 0;
5495
5496     /*
5497      * Bind to the Volume Server port on the File Server machine in question,
5498      * then go for it.
5499      */
5500     rxConnP = UV_Bind(a_serverID, AFSCONF_VOLUMEPORT);
5501     code = AFSVolXListOneVolume(rxConnP, a_partID, a_volID, &volumeXInfo);
5502     if (code)
5503         fprintf(STDERR,
5504                 "[UV_XListOneVolume] Couldn't fetch the volume information\n");
5505     else
5506         /*
5507          * We got the info; pull out the pointer to where the results lie.
5508          */
5509         *a_resultPP = volumeXInfo.volXEntries_val;
5510
5511     /*
5512      * If we got an Rx connection, throw it away.
5513      */
5514     if (rxConnP)
5515         rx_DestroyConnection(rxConnP);
5516
5517     PrintError("", code);
5518     return code;
5519 }
5520
5521 /* CheckVolume()
5522  *    Given a volume we read from a partition, check if it is
5523  *    represented in the VLDB correctly.
5524  *
5525  *    The VLDB is looked up by the RW volume id (not its name).
5526  *    The RW contains the true name of the volume (BK and RO set
5527  *       the name in the VLDB only on creation of the VLDB entry).
5528  *    We want rules strict enough that when we check all volumes
5529  *       on one partition, it does not need to be done again. IE:
5530  *       two volumes on different partitions won't constantly
5531  *       change a VLDB entry away from what the other set.
5532  *    For RW and BK volumes, we will always check the VLDB to see
5533  *       if the two exist on the server/partition. May seem redundant,
5534  *       but this is an easy check of the VLDB. IE: if the VLDB entry
5535  *       says the BK exists but no BK volume is there, we will detect
5536  *       this when we check the RW volume.
5537  *    VLDB entries are locked only when a change needs to be done.
5538  *    Output changed to look a lot like the "vos syncserv" otuput.
5539  */
5540 static afs_int32
5541 CheckVolume(volintInfo * volumeinfo, afs_uint32 aserver, afs_int32 apart,
5542             afs_int32 * modentry, afs_uint32 * maxvolid,
5543             struct nvldbentry *aentry)
5544 {
5545     int idx = 0;
5546     int j;
5547     afs_int32 code, error = 0;
5548     struct nvldbentry entry, storeEntry;
5549     char pname[10];
5550     int pass = 0, createentry, addvolume, modified, mod, doit = 1;
5551     afs_uint32 rwvolid;
5552     char hoststr[16];
5553
5554     if (modentry) {
5555         if (*modentry == 1)
5556             doit = 0;
5557         *modentry = 0;
5558     }
5559     rwvolid =
5560         ((volumeinfo->type ==
5561           RWVOL) ? volumeinfo->volid : volumeinfo->parentID);
5562
5563   retry:
5564     /* Check to see if the VLDB is ok without locking it (pass 1).
5565      * If it will change, then lock the VLDB entry, read it again,
5566      * then make the changes to it (pass 2).
5567      */
5568     if (++pass == 2) {
5569         code = ubik_VL_SetLock(cstruct, 0, rwvolid, RWVOL, VLOP_DELETE);
5570         if (code) {
5571             fprintf(STDERR, "Could not lock VLDB entry for %lu\n",
5572                     (unsigned long)rwvolid);
5573             ERROR_EXIT(code);
5574         }
5575     }
5576
5577     createentry = 0;            /* Do we need to create a VLDB entry */
5578     addvolume = 0;              /* Add this volume to the VLDB entry */
5579     modified = 0;               /* The VLDB entry was modified */
5580
5581     if (aentry) {
5582         memcpy(&entry, aentry, sizeof(entry));
5583     } else {
5584         /* Read the entry from VLDB by its RW volume id */
5585         code = VLDB_GetEntryByID(rwvolid, RWVOL, &entry);
5586         if (code) {
5587             if (code != VL_NOENT) {
5588                 fprintf(STDOUT,
5589                         "Could not retreive the VLDB entry for volume %lu \n",
5590                         (unsigned long)rwvolid);
5591                 ERROR_EXIT(code);
5592             }
5593
5594             memset(&entry, 0, sizeof(entry));
5595             vsu_ExtractName(entry.name, volumeinfo->name);      /* Store name of RW */
5596
5597             createentry = 1;
5598         } else {
5599             MapHostToNetwork(&entry);
5600         }
5601     }
5602
5603     if (verbose && (pass == 1)) {
5604         fprintf(STDOUT, "_______________________________\n");
5605         fprintf(STDOUT, "\n-- status before -- \n");
5606         if (createentry) {
5607             fprintf(STDOUT, "\n**does not exist**\n");
5608         } else {
5609             if ((entry.flags & RW_EXISTS) || (entry.flags & RO_EXISTS)
5610                 || (entry.flags & BACK_EXISTS))
5611                 EnumerateEntry(&entry);
5612         }
5613         fprintf(STDOUT, "\n");
5614     }
5615
5616     if (volumeinfo->type == RWVOL) {    /* RW volume exists */
5617         if (createentry) {
5618             idx = 0;
5619             entry.nServers = 1;
5620             addvolume++;
5621         } else {
5622             /* Check existence of RW and BK volumes */
5623             code = CheckVldbRWBK(&entry, &mod);
5624             if (code)
5625                 ERROR_EXIT(code);
5626             if (mod)
5627                 modified++;
5628
5629             idx = Lp_GetRwIndex(&entry);
5630             if (idx == -1) {    /* RW index not found in the VLDB entry */
5631                 idx = entry.nServers;   /* put it into next index */
5632                 entry.nServers++;
5633                 addvolume++;
5634             } else {            /* RW index found in the VLDB entry. */
5635                 /* Verify if this volume's location matches where the VLDB says it is */
5636                 if (!Lp_Match(aserver, apart, &entry)) {
5637                     if (entry.flags & RW_EXISTS) {
5638                         /* The RW volume exists elsewhere - report this one a duplicate */
5639                         if (pass == 1) {
5640                             MapPartIdIntoName(apart, pname);
5641                             fprintf(STDERR,
5642                                     "*** Warning: Orphaned RW volume %lu exists on %s %s\n",
5643                                     (unsigned long)rwvolid,
5644                                     noresolve ?
5645                                     afs_inet_ntoa_r(aserver, hoststr) :
5646                                     hostutil_GetNameByINet(aserver), pname);
5647                             MapPartIdIntoName(entry.serverPartition[idx],
5648                                               pname);
5649                             fprintf(STDERR,
5650                                     "    VLDB reports RW volume %lu exists on %s %s\n",
5651                                     (unsigned long)rwvolid,
5652                                     noresolve ?
5653                                     afs_inet_ntoa_r(entry.serverNumber[idx], hoststr) :
5654                                     hostutil_GetNameByINet(entry.
5655                                                            serverNumber[idx]),
5656                                     pname);
5657                         }
5658                     } else {
5659                         /* The RW volume does not exist - have VLDB point to this one */
5660                         addvolume++;
5661
5662                         /* Check for orphaned BK volume on old partition */
5663                         if (entry.flags & BACK_EXISTS) {
5664                             if (pass == 1) {
5665                                 MapPartIdIntoName(entry.serverPartition[idx],
5666                                                   pname);
5667                                 fprintf(STDERR,
5668                                         "*** Warning: Orphaned BK volume %u exists on %s %s\n",
5669                                         entry.volumeId[BACKVOL],
5670                                         noresolve ?
5671                                         afs_inet_ntoa_r(entry.serverNumber[idx], hoststr) :
5672                                         hostutil_GetNameByINet(entry.
5673                                                                serverNumber
5674                                                                [idx]), pname);
5675                                 MapPartIdIntoName(apart, pname);
5676                                 fprintf(STDERR,
5677                                         "    VLDB reports its RW volume %lu exists on %s %s\n",
5678                                         (unsigned long)rwvolid,
5679                                         noresolve ?
5680                                         afs_inet_ntoa_r(aserver, hoststr) :
5681                                         hostutil_GetNameByINet(aserver),
5682                                         pname);
5683                             }
5684                         }
5685                     }
5686                 } else {
5687                     /* Volume location matches the VLDB location */
5688                     if ((volumeinfo->backupID && !entry.volumeId[BACKVOL])
5689                         || (volumeinfo->cloneID && !entry.volumeId[ROVOL])
5690                         ||
5691                         (strncmp
5692                          (entry.name, volumeinfo->name,
5693                           VOLSER_OLDMAXVOLNAME) != 0)) {
5694                         addvolume++;
5695                     }
5696                 }
5697             }
5698         }
5699
5700         if (addvolume) {
5701             entry.flags |= RW_EXISTS;
5702             entry.volumeId[RWVOL] = rwvolid;
5703             if (!entry.volumeId[BACKVOL])
5704                 entry.volumeId[BACKVOL] = volumeinfo->backupID;
5705             if (!entry.volumeId[ROVOL])
5706                 entry.volumeId[ROVOL] = volumeinfo->cloneID;
5707
5708             entry.serverFlags[idx] = ITSRWVOL;
5709             entry.serverNumber[idx] = aserver;
5710             entry.serverPartition[idx] = apart;
5711             strncpy(entry.name, volumeinfo->name, VOLSER_OLDMAXVOLNAME);
5712
5713             modified++;
5714
5715             /* One last check - to update BK if need to */
5716             code = CheckVldbRWBK(&entry, &mod);
5717             if (code)
5718                 ERROR_EXIT(code);
5719             if (mod)
5720                 modified++;
5721         }
5722     }
5723
5724     else if (volumeinfo->type == BACKVOL) {     /* A BK volume */
5725         if (createentry) {
5726             idx = 0;
5727             entry.nServers = 1;
5728             addvolume++;
5729         } else {
5730             /* Check existence of RW and BK volumes */
5731             code = CheckVldbRWBK(&entry, &mod);
5732             if (code)
5733                 ERROR_EXIT(code);
5734             if (mod)
5735                 modified++;
5736
5737             idx = Lp_GetRwIndex(&entry);
5738             if (idx == -1) {    /* RW index not found in the VLDB entry */
5739                 idx = entry.nServers;   /* Put it into next index */
5740                 entry.nServers++;
5741                 addvolume++;
5742             } else {            /* RW index found in the VLDB entry */
5743                 /* Verify if this volume's location matches where the VLDB says it is */
5744                 if (!Lp_Match(aserver, apart, &entry)) {
5745                     /* VLDB says RW and/or BK is elsewhere - report this BK volume orphaned */
5746                     if (pass == 1) {
5747                         MapPartIdIntoName(apart, pname);
5748                         fprintf(STDERR,
5749                                 "*** Warning: Orphaned BK volume %lu exists on %s %s\n",
5750                                 (unsigned long)volumeinfo->volid,
5751                                 noresolve ?
5752                                 afs_inet_ntoa_r(aserver, hoststr) :
5753                                 hostutil_GetNameByINet(aserver), pname);
5754                         MapPartIdIntoName(entry.serverPartition[idx], pname);
5755                         fprintf(STDERR,
5756                                 "    VLDB reports its RW/BK volume %lu exists on %s %s\n",
5757                                 (unsigned long)rwvolid,
5758                                 noresolve ?
5759                                 afs_inet_ntoa_r(entry.serverNumber[idx], hoststr) :
5760                                 hostutil_GetNameByINet(entry.
5761                                                        serverNumber[idx]),
5762                                 pname);
5763                     }
5764                 } else {
5765                     if (volumeinfo->volid != entry.volumeId[BACKVOL]) {
5766                         if (!(entry.flags & BACK_EXISTS)) {
5767                             addvolume++;
5768                         } else if (volumeinfo->volid >
5769                                    entry.volumeId[BACKVOL]) {
5770                             addvolume++;
5771
5772                             if (pass == 1) {
5773                                 MapPartIdIntoName(entry.serverPartition[idx],
5774                                                   pname);
5775                                 fprintf(STDERR,
5776                                         "*** Warning: Orphaned BK volume %u exists on %s %s\n",
5777                                         entry.volumeId[BACKVOL],
5778                                         noresolve ?
5779                                         afs_inet_ntoa_r(aserver, hoststr) :
5780                                         hostutil_GetNameByINet(aserver),
5781                                         pname);
5782                                 fprintf(STDERR,
5783                                         "    VLDB reports its BK volume ID is %lu\n",
5784                                         (unsigned long)volumeinfo->volid);
5785                             }
5786                         } else {
5787                             if (pass == 1) {
5788                                 MapPartIdIntoName(entry.serverPartition[idx],
5789                                                   pname);
5790                                 fprintf(STDERR,
5791                                         "*** Warning: Orphaned BK volume %lu exists on %s %s\n",
5792                                         (unsigned long)volumeinfo->volid,
5793                                         noresolve ?
5794                                         afs_inet_ntoa_r(aserver, hoststr) :
5795                                         hostutil_GetNameByINet(aserver),
5796                                         pname);
5797                                 fprintf(STDERR,
5798                                         "    VLDB reports its BK volume ID is %u\n",
5799                                         entry.volumeId[BACKVOL]);
5800                             }
5801                         }
5802                     } else if (!entry.volumeId[BACKVOL]) {
5803                         addvolume++;
5804                     }
5805                 }
5806             }
5807         }
5808         if (addvolume) {
5809             entry.flags |= BACK_EXISTS;
5810             entry.volumeId[RWVOL] = rwvolid;
5811             entry.volumeId[BACKVOL] = volumeinfo->volid;
5812
5813             entry.serverNumber[idx] = aserver;
5814             entry.serverPartition[idx] = apart;
5815             entry.serverFlags[idx] = ITSBACKVOL;
5816
5817             modified++;
5818         }
5819     }
5820
5821     else if (volumeinfo->type == ROVOL) {       /* A RO volume */
5822         if (volumeinfo->volid == entry.volumeId[ROVOL]) {
5823             /* This is a quick check to see if the RO entry exists in the
5824              * VLDB so we avoid the CheckVldbRO() call (which checks if each
5825              * RO volume listed in the VLDB exists).
5826              */
5827             idx = Lp_ROMatch(aserver, apart, &entry) - 1;
5828             if (idx == -1) {
5829                 idx = entry.nServers;
5830                 entry.nServers++;
5831                 addvolume++;
5832             } else {
5833                 if (!(entry.flags & RO_EXISTS)) {
5834                     addvolume++;
5835                 }
5836             }
5837         } else {
5838             /* Before we correct the VLDB entry, make sure all the
5839              * ROs listed in the VLDB exist.
5840              */
5841             code = CheckVldbRO(&entry, &mod);
5842             if (code)
5843                 ERROR_EXIT(code);
5844             if (mod)
5845                 modified++;
5846
5847             if (!(entry.flags & RO_EXISTS)) {
5848                 /* No RO exists in the VLDB entry - add this one */
5849                 idx = entry.nServers;
5850                 entry.nServers++;
5851                 addvolume++;
5852             } else if (volumeinfo->volid > entry.volumeId[ROVOL]) {
5853                 /* The volume headers's RO ID does not match that in the VLDB entry,
5854                  * and the vol hdr's ID is greater (implies more recent). So delete
5855                  * all the RO volumes listed in VLDB entry and add this volume.
5856                  */
5857                 for (j = 0; j < entry.nServers; j++) {
5858                     if (entry.serverFlags[j] & ITSROVOL) {
5859                         /* Verify this volume exists and print message we are orphaning it */
5860                         if (pass == 1) {
5861                             MapPartIdIntoName(apart, pname);
5862                             fprintf(STDERR,
5863                                     "*** Warning: Orphaned RO volume %u exists on %s %s\n",
5864                                     entry.volumeId[ROVOL],
5865                                     noresolve ?
5866                                     afs_inet_ntoa_r(entry.serverNumber[j], hoststr) :
5867                                     hostutil_GetNameByINet(entry.
5868                                                            serverNumber[j]),
5869                                     pname);
5870                             fprintf(STDERR,
5871                                     "    VLDB reports its RO volume ID is %lu\n",
5872                                     (unsigned long)volumeinfo->volid);
5873                         }
5874
5875                         Lp_SetRWValue(&entry, entry.serverNumber[idx],
5876                                       entry.serverPartition[idx], 0L, 0L);
5877                         entry.nServers--;
5878                         modified++;
5879                         j--;
5880                     }
5881                 }
5882
5883                 idx = entry.nServers;
5884                 entry.nServers++;
5885                 addvolume++;
5886             } else if (volumeinfo->volid < entry.volumeId[ROVOL]) {
5887                 /* The volume headers's RO ID does not match that in the VLDB entry,
5888                  * and the vol hdr's ID is lower (implies its older). So orphan it.
5889                  */
5890                 if (pass == 1) {
5891                     MapPartIdIntoName(apart, pname);
5892                     fprintf(STDERR,
5893                             "*** Warning: Orphaned RO volume %lu exists on %s %s\n",
5894                             (unsigned long)volumeinfo->volid,
5895                             noresolve ?
5896                             afs_inet_ntoa_r(aserver, hoststr) :
5897                             hostutil_GetNameByINet(aserver), pname);
5898                     fprintf(STDERR,
5899                             "    VLDB reports its RO volume ID is %u\n",
5900                             entry.volumeId[ROVOL]);
5901                 }
5902             } else {
5903                 /* The RO volume ID in the volume header match that in the VLDB entry,
5904                  * and there exist RO volumes in the VLDB entry. See if any of them
5905                  * are this one. If not, then we add it.
5906                  */
5907                 idx = Lp_ROMatch(aserver, apart, &entry) - 1;
5908                 if (idx == -1) {
5909                     idx = entry.nServers;
5910                     entry.nServers++;
5911                     addvolume++;
5912                 }
5913             }
5914         }
5915
5916         if (addvolume) {
5917             entry.flags |= RO_EXISTS;
5918             entry.volumeId[RWVOL] = rwvolid;
5919             entry.volumeId[ROVOL] = volumeinfo->volid;
5920
5921             entry.serverNumber[idx] = aserver;
5922             entry.serverPartition[idx] = apart;
5923             entry.serverFlags[idx] = ITSROVOL;
5924
5925             modified++;
5926         }
5927     }
5928
5929     /* Remember largest volume id */
5930     if (entry.volumeId[ROVOL] > *maxvolid)
5931         *maxvolid = entry.volumeId[ROVOL];
5932     if (entry.volumeId[BACKVOL] > *maxvolid)
5933         *maxvolid = entry.volumeId[BACKVOL];
5934     if (entry.volumeId[RWVOL] > *maxvolid)
5935         *maxvolid = entry.volumeId[RWVOL];
5936
5937     if (modified && doit) {
5938         MapNetworkToHost(&entry, &storeEntry);
5939
5940         if (createentry) {
5941             code = VLDB_CreateEntry(&storeEntry);
5942             if (code) {
5943                 fprintf(STDOUT,
5944                         "Could not create a VLDB entry for the volume %lu\n",
5945                         (unsigned long)rwvolid);
5946                 ERROR_EXIT(code);
5947             }
5948         } else {
5949             if (pass == 1)
5950                 goto retry;
5951             code =
5952                 VLDB_ReplaceEntry(rwvolid, RWVOL, &storeEntry,
5953                                   LOCKREL_OPCODE | LOCKREL_AFSID |
5954                                   LOCKREL_TIMESTAMP);
5955             if (code) {
5956                 fprintf(STDERR, "Could not update entry for %lu\n",
5957                         (unsigned long)rwvolid);
5958                 ERROR_EXIT(code);
5959             }
5960         }
5961     } else if (pass == 2) {
5962         code =
5963             ubik_VL_ReleaseLock(cstruct, 0, rwvolid, RWVOL,
5964                       LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
5965         if (code) {
5966             PrintError("Could not unlock VLDB entry ", code);
5967         }
5968     }
5969
5970     if (modified && modentry) {
5971         *modentry = 1;
5972     }
5973
5974     if (aentry) {
5975         memcpy(aentry, &entry, sizeof(entry));
5976     }
5977
5978     if (verbose) {
5979         fprintf(STDOUT, "-- status after --\n");
5980         if (modified)
5981             EnumerateEntry(&entry);
5982         else
5983             fprintf(STDOUT, "\n**no change**\n");
5984     }
5985
5986   error_exit:
5987     VPRINT("\n_______________________________\n");
5988     return (error);
5989 }
5990
5991 int
5992 sortVolumes(const void *a, const void *b)
5993 {
5994     volintInfo *v1 = (volintInfo *) a;
5995     volintInfo *v2 = (volintInfo *) b;
5996     afs_uint32 rwvolid1, rwvolid2;
5997
5998     rwvolid1 = ((v1->type == RWVOL) ? v1->volid : v1->parentID);
5999     rwvolid2 = ((v2->type == RWVOL) ? v2->volid : v2->parentID);
6000
6001     if (rwvolid1 > rwvolid2)
6002         return -1;              /* lower RW id goes first */
6003     if (rwvolid1 < rwvolid2)
6004         return 1;
6005
6006     if (v1->type == RWVOL)
6007         return -1;              /* RW vols go first */
6008     if (v2->type == RWVOL)
6009         return 1;
6010
6011     if ((v1->type == BACKVOL) && (v2->type == ROVOL))
6012         return -1;              /* BK vols next */
6013     if ((v1->type == ROVOL) && (v2->type == BACKVOL))
6014         return 1;
6015
6016     if (v1->volid < v2->volid)
6017         return 1;               /* larger volids first */
6018     if (v1->volid > v2->volid)
6019         return -1;
6020     return 0;
6021 }
6022
6023 /* UV_SyncVolume()
6024  *      Synchronise <aserver> <apart>(if flags = 1) <avolid>.
6025  *      Synchronize an individual volume against a sever and partition.
6026  *      Checks the VLDB entry (similar to syncserv) as well as checks
6027  *      if the volume exists on specified servers (similar to syncvldb).
6028  */
6029 int
6030 UV_SyncVolume(afs_uint32 aserver, afs_int32 apart, char *avolname, int flags)
6031 {
6032     struct rx_connection *aconn = 0;
6033     afs_int32 j, k, code, vcode, error = 0;
6034     afs_int32 tverbose;
6035     afs_int32 mod, modified = 0, deleted = 0;
6036     struct nvldbentry vldbentry;
6037     afs_uint32 volumeid = 0;
6038     volEntries volumeInfo;
6039     struct partList PartList;
6040     afs_int32 pcnt;
6041     afs_uint32 maxvolid = 0;
6042
6043     volumeInfo.volEntries_val = (volintInfo *) 0;
6044     volumeInfo.volEntries_len = 0;
6045
6046     /* Turn verbose logging off and do our own verbose logging */
6047     /* tverbose must be set before we call ERROR_EXIT() */
6048
6049     tverbose = verbose;
6050     if (flags & 2)
6051         tverbose = 1;
6052     verbose = 0;
6053
6054     if (!aserver && (flags & 1)) {
6055         /* fprintf(STDERR,"Partition option requires a server option\n"); */
6056         ERROR_EXIT(EINVAL);
6057     }
6058
6059     /* Read the VLDB entry */
6060     vcode = VLDB_GetEntryByName(avolname, &vldbentry);
6061     if (vcode && (vcode != VL_NOENT)) {
6062         fprintf(STDERR, "Could not access the VLDB for volume %s\n",
6063                 avolname);
6064         ERROR_EXIT(vcode);
6065     } else if (!vcode) {
6066         MapHostToNetwork(&vldbentry);
6067     }
6068
6069     if (tverbose) {
6070         fprintf(STDOUT, "Processing VLDB entry %s ...\n", avolname);
6071         fprintf(STDOUT, "_______________________________\n");
6072         fprintf(STDOUT, "\n-- status before -- \n");
6073         if (vcode) {
6074             fprintf(STDOUT, "\n**does not exist**\n");
6075         } else {
6076             if ((vldbentry.flags & RW_EXISTS) || (vldbentry.flags & RO_EXISTS)
6077                 || (vldbentry.flags & BACK_EXISTS))
6078                 EnumerateEntry(&vldbentry);
6079         }
6080         fprintf(STDOUT, "\n");
6081     }
6082
6083     /* Verify that all of the VLDB entries exist on the repective servers
6084      * and partitions (this does not require that avolname be a volume ID).
6085      * Equivalent to a syncserv.
6086      */
6087     if (!vcode) {
6088         /* Tell CheckVldb not to update if appropriate */
6089         if (flags & 2)
6090             mod = 1;
6091         else
6092             mod = 0;
6093         code = CheckVldb(&vldbentry, &mod, &deleted);
6094         if (code) {
6095             fprintf(STDERR, "Could not process VLDB entry for volume %s\n",
6096                     vldbentry.name);
6097             ERROR_EXIT(code);
6098         }
6099         if (mod)
6100             modified++;
6101     }
6102
6103     /* If aserver is given, we will search for the desired volume on it */
6104     if (aserver) {
6105         /* Generate array of partitions on the server that we will check */
6106         if (!(flags & 1)) {
6107             code = UV_ListPartitions(aserver, &PartList, &pcnt);
6108             if (code) {
6109                 fprintf(STDERR,
6110                         "Could not fetch the list of partitions from the server\n");
6111                 ERROR_EXIT(code);
6112             }
6113         } else {
6114             PartList.partId[0] = apart;
6115             pcnt = 1;
6116         }
6117
6118         aconn = UV_Bind(aserver, AFSCONF_VOLUMEPORT);
6119
6120         /* If a volume ID were given, search for it on each partition */
6121         if ((volumeid = atol(avolname))) {
6122             for (j = 0; j < pcnt; j++) {
6123                 code =
6124                     AFSVolListOneVolume(aconn, PartList.partId[j], volumeid,
6125                                         &volumeInfo);
6126                 if (code) {
6127                     if (code != ENODEV) {
6128                         fprintf(STDERR, "Could not query server\n");
6129                         ERROR_EXIT(code);
6130                     }
6131                 } else {
6132                     if (flags & 2)
6133                         mod = 1;
6134                     else
6135                         mod = 0;
6136                     /* Found one, sync it with VLDB entry */
6137                     code =
6138                         CheckVolume(volumeInfo.volEntries_val, aserver,
6139                                     PartList.partId[j], &mod, &maxvolid, &vldbentry);
6140                     if (code)
6141                         ERROR_EXIT(code);
6142                     if (mod)
6143                         modified++;
6144                 }
6145
6146                 if (volumeInfo.volEntries_val)
6147                     free(volumeInfo.volEntries_val);
6148                 volumeInfo.volEntries_val = (volintInfo *) 0;
6149                 volumeInfo.volEntries_len = 0;
6150             }
6151         }
6152
6153         /* Check to see if the RW, BK, and RO IDs exist on any
6154          * partitions. We get the volume IDs from the VLDB.
6155          */
6156         for (j = 0; j < MAXTYPES; j++) {        /* for RW, RO, and BK IDs */
6157             if (vldbentry.volumeId[j] == 0)
6158                 continue;
6159
6160             for (k = 0; k < pcnt; k++) {        /* For each partition */
6161                 volumeInfo.volEntries_val = (volintInfo *) 0;
6162                 volumeInfo.volEntries_len = 0;
6163                 code =
6164                     AFSVolListOneVolume(aconn, PartList.partId[k],
6165                                         vldbentry.volumeId[j], &volumeInfo);
6166                 if (code) {
6167                     if (code != ENODEV) {
6168                         fprintf(STDERR, "Could not query server\n");
6169                         ERROR_EXIT(code);
6170                     }
6171                 } else {
6172                     if (flags & 2)
6173                         mod = 1;
6174                     else
6175                         mod = 0;
6176                     /* Found one, sync it with VLDB entry */
6177                     code =
6178                         CheckVolume(volumeInfo.volEntries_val, aserver,
6179                                     PartList.partId[k], &mod, &maxvolid, &vldbentry);
6180                     if (code)
6181                         ERROR_EXIT(code);
6182                     if (mod)
6183                         modified++;
6184                 }
6185
6186                 if (volumeInfo.volEntries_val)
6187                     free(volumeInfo.volEntries_val);
6188                 volumeInfo.volEntries_val = (volintInfo *) 0;
6189                 volumeInfo.volEntries_len = 0;
6190             }
6191         }
6192     }
6193
6194     /* if (aserver) */
6195     /* If verbose output, print a summary of what changed */
6196     if (tverbose) {
6197         fprintf(STDOUT, "-- status after --\n");
6198         if (deleted) {
6199             fprintf(STDOUT, "\n**entry deleted**\n");
6200         } else if (modified) {
6201             EnumerateEntry(&vldbentry);
6202         } else {
6203             fprintf(STDOUT, "\n**no change**\n");
6204         }
6205         fprintf(STDOUT, "\n_______________________________\n");
6206     }
6207
6208   error_exit:
6209     /* Now check if the maxvolid is larger than that stored in the VLDB */
6210     if (maxvolid) {
6211         afs_uint32 maxvldbid = 0;
6212         code = ubik_VL_GetNewVolumeId(cstruct, 0, 0, &maxvldbid);
6213         if (code) {
6214             fprintf(STDERR,
6215                     "Could not get the highest allocated volume id from the VLDB\n");
6216             if (!error)
6217                 error = code;
6218         } else if (maxvolid > maxvldbid) {
6219             afs_uint32 id, nid;
6220             id = maxvolid - maxvldbid + 1;
6221             code = ubik_VL_GetNewVolumeId(cstruct, 0, id, &nid);
6222             if (code) {
6223                 fprintf(STDERR,
6224                         "Error in increasing highest allocated volume id in VLDB\n");
6225                 if (!error)
6226                     error = code;
6227             }
6228         }
6229     }
6230
6231     verbose = tverbose;
6232     if (verbose) {
6233         if (error)
6234             fprintf(STDOUT, "...error encountered");
6235         else
6236             fprintf(STDOUT, "...done entry\n");
6237     }
6238     if (aconn)
6239         rx_DestroyConnection(aconn);
6240     if (volumeInfo.volEntries_val)
6241         free(volumeInfo.volEntries_val);
6242
6243     PrintError("", error);
6244     return error;
6245 }
6246
6247 /* UV_SyncVldb()
6248  *      Synchronise vldb with the file server <aserver> and,
6249  *      optionally, <apart>.
6250  */
6251 int
6252 UV_SyncVldb(afs_uint32 aserver, afs_int32 apart, int flags, int force)
6253 {
6254     struct rx_connection *aconn;
6255     afs_int32 code, error = 0;
6256     int i, pfail;
6257     unsigned int j;
6258     volEntries volumeInfo;
6259     struct partList PartList;
6260     afs_int32 pcnt;
6261     char pname[10];
6262     volintInfo *vi;
6263     afs_int32 failures = 0, modifications = 0, tentries = 0;
6264     afs_int32 modified;
6265     afs_uint32 maxvolid = 0;
6266     char hoststr[16];
6267
6268     volumeInfo.volEntries_val = (volintInfo *) 0;
6269     volumeInfo.volEntries_len = 0;
6270
6271     aconn = UV_Bind(aserver, AFSCONF_VOLUMEPORT);
6272
6273     /* Generate array of partitions to check */
6274     if (!(flags & 1)) {
6275         code = UV_ListPartitions(aserver, &PartList, &pcnt);
6276         if (code) {
6277             fprintf(STDERR,
6278                     "Could not fetch the list of partitions from the server\n");
6279             ERROR_EXIT(code);
6280         }
6281     } else {
6282         PartList.partId[0] = apart;
6283         pcnt = 1;
6284     }
6285
6286     VPRINT("Processing volume entries ...\n");
6287
6288     /* Step through the array of partitions */
6289     for (i = 0; i < pcnt; i++) {
6290         apart = PartList.partId[i];
6291         MapPartIdIntoName(apart, pname);
6292
6293         volumeInfo.volEntries_val = (volintInfo *) 0;
6294         volumeInfo.volEntries_len = 0;
6295         code = AFSVolListVolumes(aconn, apart, 1, &volumeInfo);
6296         if (code) {
6297             fprintf(STDERR,
6298                     "Could not fetch the list of volumes from the server\n");
6299             ERROR_EXIT(code);
6300         }
6301
6302         /* May want to sort the entries: RW, BK (high to low), RO (high to low) */
6303         qsort((char *)volumeInfo.volEntries_val, volumeInfo.volEntries_len,
6304               sizeof(volintInfo), sortVolumes);
6305
6306         pfail = 0;
6307         for (vi = volumeInfo.volEntries_val, j = 0;
6308              j < volumeInfo.volEntries_len; j++, vi++) {
6309             if (!vi->status)
6310                 continue;
6311
6312             tentries++;
6313
6314             if (verbose) {
6315                 fprintf(STDOUT,
6316                         "Processing volume entry %d: %s (%lu) on server %s %s...\n",
6317                         j + 1, vi->name, (unsigned long)vi->volid,
6318                         noresolve ?
6319                         afs_inet_ntoa_r(aserver, hoststr) :
6320                         hostutil_GetNameByINet(aserver), pname);
6321                 fflush(STDOUT);
6322             }
6323
6324             if (flags & 2)
6325                 modified = 1;
6326             else
6327                 modified = 0;
6328             code = CheckVolume(vi, aserver, apart, &modified, &maxvolid, NULL);
6329             if (code) {
6330                 PrintError("", code);
6331                 failures++;
6332                 pfail++;
6333             } else if (modified) {
6334                 modifications++;
6335             }
6336
6337             if (verbose) {
6338                 if (code) {
6339                     fprintf(STDOUT, "...error encountered\n\n");
6340                 } else {
6341                     fprintf(STDOUT, "...done entry %d\n\n", j + 1);
6342                 }
6343             }
6344         }
6345
6346         if (pfail) {
6347             fprintf(STDERR,
6348                     "Could not process entries on server %s partition %s\n",
6349                     noresolve ?
6350                     afs_inet_ntoa_r(aserver, hoststr) :
6351                     hostutil_GetNameByINet(aserver), pname);
6352         }
6353         if (volumeInfo.volEntries_val) {
6354             free(volumeInfo.volEntries_val);
6355             volumeInfo.volEntries_val = 0;
6356         }
6357
6358     }                           /* thru all partitions */
6359
6360     if (flags & 2) {
6361         VPRINT3("Total entries: %u, Failed to process %d, Would change %d\n",
6362                 tentries, failures, modifications);
6363     } else {
6364         VPRINT3("Total entries: %u, Failed to process %d, Changed %d\n",
6365                 tentries, failures, modifications);
6366     }
6367
6368   error_exit:
6369     /* Now check if the maxvolid is larger than that stored in the VLDB */
6370     if (maxvolid) {
6371         afs_uint32 maxvldbid = 0;
6372         code = ubik_VL_GetNewVolumeId(cstruct, 0, 0, &maxvldbid);
6373         if (code) {
6374             fprintf(STDERR,
6375                     "Could not get the highest allocated volume id from the VLDB\n");
6376             if (!error)
6377                 error = code;
6378         } else if (maxvolid > maxvldbid) {
6379             afs_uint32 id, nid;
6380             id = maxvolid - maxvldbid + 1;
6381             code = ubik_VL_GetNewVolumeId(cstruct, 0, id, &nid);
6382             if (code) {
6383                 fprintf(STDERR,
6384                         "Error in increasing highest allocated volume id in VLDB\n");
6385                 if (!error)
6386                     error = code;
6387             }
6388         }
6389     }
6390
6391     if (aconn)
6392         rx_DestroyConnection(aconn);
6393     if (volumeInfo.volEntries_val)
6394         free(volumeInfo.volEntries_val);
6395     PrintError("", error);
6396     return (error);
6397 }
6398
6399 /* VolumeExists()
6400  *      Determine if a volume exists on a server and partition.
6401  *      Try creating a transaction on the volume. If we can,
6402  *      the volume exists, if not, then return the error code.
6403  *      Some error codes mean the volume is unavailable but
6404  *      still exists - so we catch these error codes.
6405  */
6406 afs_int32
6407 VolumeExists(afs_uint32 server, afs_int32 partition, afs_uint32 volumeid)
6408 {
6409     struct rx_connection *conn = (struct rx_connection *)0;
6410     afs_int32 code = -1;
6411     volEntries volumeInfo;
6412
6413     conn = UV_Bind(server, AFSCONF_VOLUMEPORT);
6414     if (conn) {
6415         volumeInfo.volEntries_val = (volintInfo *) 0;
6416         volumeInfo.volEntries_len = 0;
6417         code = AFSVolListOneVolume(conn, partition, volumeid, &volumeInfo);
6418         if (volumeInfo.volEntries_val)
6419             free(volumeInfo.volEntries_val);
6420         if (code == VOLSERILLEGAL_PARTITION)
6421             code = ENODEV;
6422         rx_DestroyConnection(conn);
6423     }
6424     return code;
6425 }
6426
6427 /* CheckVldbRWBK()
6428  *
6429  */
6430 afs_int32
6431 CheckVldbRWBK(struct nvldbentry * entry, afs_int32 * modified)
6432 {
6433     int modentry = 0;
6434     int idx;
6435     afs_int32 code, error = 0;
6436     char pname[10];
6437     char hoststr[16];
6438
6439     if (modified)
6440         *modified = 0;
6441     idx = Lp_GetRwIndex(entry);
6442
6443     /* Check to see if the RW volume exists and set the RW_EXISTS
6444      * flag accordingly.
6445      */
6446     if (idx == -1) {            /* Did not find a RW entry */
6447         if (entry->flags & RW_EXISTS) { /* ... yet entry says RW exists */
6448             entry->flags &= ~RW_EXISTS; /* ... so say RW does not exist */
6449             modentry++;
6450         }
6451     } else {
6452         code =
6453             VolumeExists(entry->serverNumber[idx],
6454                          entry->serverPartition[idx], entry->volumeId[RWVOL]);
6455         if (code == 0) {        /* RW volume exists */
6456             if (!(entry->flags & RW_EXISTS)) {  /* ... yet entry says RW does not exist */
6457                 entry->flags |= RW_EXISTS;      /* ... so say RW does exist */
6458                 modentry++;
6459             }
6460         } else if (code == ENODEV) {    /* RW volume does not exist */
6461             if (entry->flags & RW_EXISTS) {     /* ... yet entry says RW exists */
6462                 entry->flags &= ~RW_EXISTS;     /* ... so say RW does not exist */
6463                 modentry++;
6464             }
6465         } else {
6466             /* If VLDB says it didn't exist, then ignore error */
6467             if (entry->flags & RW_EXISTS) {
6468                 MapPartIdIntoName(entry->serverPartition[idx], pname);
6469                 fprintf(STDERR,
6470                         "Transaction call failed for RW volume %u on server %s %s\n",
6471                         entry->volumeId[RWVOL],
6472                         noresolve ?
6473                         afs_inet_ntoa_r(entry->serverNumber[idx], hoststr) :
6474                         hostutil_GetNameByINet(entry->serverNumber[idx]),
6475                         pname);
6476                 ERROR_EXIT(code);
6477             }
6478         }
6479     }
6480
6481     /* Check to see if the BK volume exists and set the BACK_EXISTS
6482      * flag accordingly. idx already ponts to the RW entry.
6483      */
6484     if (idx == -1) {            /* Did not find a RW entry */
6485         if (entry->flags & BACK_EXISTS) {       /* ... yet entry says BK exists */
6486             entry->flags &= ~BACK_EXISTS;       /* ... so say BK does not exist */
6487             modentry++;
6488         }
6489     } else {                    /* Found a RW entry */
6490         code =
6491             VolumeExists(entry->serverNumber[idx],
6492                          entry->serverPartition[idx],
6493                          entry->volumeId[BACKVOL]);
6494         if (code == 0) {        /* BK volume exists */
6495             if (!(entry->flags & BACK_EXISTS)) {        /* ... yet entry says BK does not exist */
6496                 entry->flags |= BACK_EXISTS;    /* ... so say BK does exist */
6497                 modentry++;
6498             }
6499         } else if (code == ENODEV) {    /* BK volume does not exist */
6500             if (entry->flags & BACK_EXISTS) {   /* ... yet entry says BK exists */
6501                 entry->flags &= ~BACK_EXISTS;   /* ... so say BK does not exist */
6502                 modentry++;
6503             }
6504         } else {
6505             /* If VLDB says it didn't exist, then ignore error */
6506             if (entry->flags & BACK_EXISTS) {
6507                 MapPartIdIntoName(entry->serverPartition[idx], pname);
6508                 fprintf(STDERR,
6509                         "Transaction call failed for BK volume %u on server %s %s\n",
6510                         entry->volumeId[BACKVOL],
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     /* If there is an idx but the BK and RW volumes no
6521      * longer exist, then remove the RW entry.
6522      */
6523     if ((idx != -1) && !(entry->flags & RW_EXISTS)
6524         && !(entry->flags & BACK_EXISTS)) {
6525         Lp_SetRWValue(entry, entry->serverNumber[idx],
6526                       entry->serverPartition[idx], 0L, 0L);
6527         entry->nServers--;
6528         modentry++;
6529     }
6530
6531   error_exit:
6532     if (modified)
6533         *modified = modentry;
6534     return (error);
6535 }
6536
6537 int
6538 CheckVldbRO(struct nvldbentry *entry, afs_int32 * modified)
6539 {
6540     int idx;
6541     int foundro = 0, modentry = 0;
6542     afs_int32 code, error = 0;
6543     char pname[10];
6544     char hoststr[16];
6545
6546     if (modified)
6547         *modified = 0;
6548
6549     /* Check to see if the RO volumes exist and set the RO_EXISTS
6550      * flag accordingly.
6551      */
6552     for (idx = 0; idx < entry->nServers; idx++) {
6553         if (!(entry->serverFlags[idx] & ITSROVOL)) {
6554             continue;           /* not a RO */
6555         }
6556
6557         code =
6558             VolumeExists(entry->serverNumber[idx],
6559                          entry->serverPartition[idx], entry->volumeId[ROVOL]);
6560         if (code == 0) {        /* RO volume exists */
6561             foundro++;
6562         } else if (code == ENODEV) {    /* RW volume does not exist */
6563             Lp_SetROValue(entry, entry->serverNumber[idx],
6564                           entry->serverPartition[idx], 0L, 0L);
6565             entry->nServers--;
6566             idx--;
6567             modentry++;
6568         } else {
6569             MapPartIdIntoName(entry->serverPartition[idx], pname);
6570             fprintf(STDERR,
6571                     "Transaction call failed for RO %u on server %s %s\n",
6572                     entry->volumeId[ROVOL],
6573                     noresolve ?
6574                     afs_inet_ntoa_r(entry->serverNumber[idx], hoststr) :
6575                     hostutil_GetNameByINet(entry->serverNumber[idx]), pname);
6576             ERROR_EXIT(code);
6577         }
6578     }
6579
6580     if (foundro) {              /* A RO volume exists */
6581         if (!(entry->flags & RO_EXISTS)) {      /* ... yet entry says RW does not exist */
6582             entry->flags |= RO_EXISTS;  /* ... so say RW does exist */
6583             modentry++;
6584         }
6585     } else {                    /* A RO volume does not exist */
6586         if (entry->flags & RO_EXISTS) { /* ... yet entry says RO exists */
6587             entry->flags &= ~RO_EXISTS; /* ... so say RO does not exist */
6588             modentry++;
6589         }
6590     }
6591
6592   error_exit:
6593     if (modified)
6594         *modified = modentry;
6595     return (error);
6596 }
6597
6598 /* CheckVldb()
6599  *      Ensure that <entry> matches with the info on file servers
6600  */
6601 afs_int32
6602 CheckVldb(struct nvldbentry * entry, afs_int32 * modified, afs_int32 * deleted)
6603 {
6604     afs_int32 code, error = 0;
6605     struct nvldbentry storeEntry;
6606     int islocked = 0, mod, modentry, delentry = 0;
6607     int pass = 0, doit=1;
6608
6609     if (modified) {
6610         if (*modified == 1)
6611             doit = 0;
6612         *modified = 0;
6613     }
6614     if (verbose) {
6615         fprintf(STDOUT, "_______________________________\n");
6616         fprintf(STDOUT, "\n-- status before -- \n");
6617         if ((entry->flags & RW_EXISTS) || (entry->flags & RO_EXISTS)
6618             || (entry->flags & BACK_EXISTS))
6619             EnumerateEntry(entry);
6620         fprintf(STDOUT, "\n");
6621     }
6622
6623     if (strlen(entry->name) > (VOLSER_OLDMAXVOLNAME - 10)) {
6624         fprintf(STDERR, "Volume name %s exceeds limit of %d characters\n",
6625                 entry->name, VOLSER_OLDMAXVOLNAME - 10);
6626     }
6627
6628   retry:
6629     /* Check to see if the VLDB is ok without locking it (pass 1).
6630      * If it will change, then lock the VLDB entry, read it again,
6631      * then make the changes to it (pass 2).
6632      */
6633     if (++pass == 2) {
6634         code =
6635             ubik_VL_SetLock(cstruct, 0, entry->volumeId[RWVOL], RWVOL,
6636                       VLOP_DELETE);
6637         if (code) {
6638             fprintf(STDERR, "Could not lock VLDB entry for %u \n",
6639                     entry->volumeId[RWVOL]);
6640             ERROR_EXIT(code);
6641         }
6642         islocked = 1;
6643
6644         code = VLDB_GetEntryByID(entry->volumeId[RWVOL], RWVOL, entry);
6645         if (code) {
6646             fprintf(STDERR, "Could not read VLDB entry for volume %s\n",
6647                     entry->name);
6648             ERROR_EXIT(code);
6649         } else {
6650             MapHostToNetwork(entry);
6651         }
6652     }
6653
6654     modentry = 0;
6655
6656     /* Check if the RW and BK entries are ok */
6657     code = CheckVldbRWBK(entry, &mod);
6658     if (code)
6659         ERROR_EXIT(code);
6660     if (mod && (pass == 1) && doit)
6661         goto retry;
6662     if (mod)
6663         modentry++;
6664
6665     /* Check if the RO volumes entries are ok */
6666     code = CheckVldbRO(entry, &mod);
6667     if (code)
6668         ERROR_EXIT(code);
6669     if (mod && (pass == 1) && doit)
6670         goto retry;
6671     if (mod)
6672         modentry++;
6673
6674     /* The VLDB entry has been updated. If it as been modified, then
6675      * write the entry back out the the VLDB.
6676      */
6677     if (modentry && doit) {
6678         if (pass == 1)
6679             goto retry;
6680
6681         if (!(entry->flags & RW_EXISTS) && !(entry->flags & BACK_EXISTS)
6682             && !(entry->flags & RO_EXISTS) && doit) {
6683             /* The RW, BK, nor RO volumes do not exist. Delete the VLDB entry */
6684             code =
6685                 ubik_VL_DeleteEntry(cstruct, 0, entry->volumeId[RWVOL],
6686                           RWVOL);
6687             if (code) {
6688                 fprintf(STDERR,
6689                         "Could not delete VLDB entry for volume %u \n",
6690                         entry->volumeId[RWVOL]);
6691                 ERROR_EXIT(code);
6692             }
6693             delentry = 1;
6694         } else {
6695             /* Replace old entry with our new one */
6696             MapNetworkToHost(entry, &storeEntry);
6697             code =
6698                 VLDB_ReplaceEntry(entry->volumeId[RWVOL], RWVOL, &storeEntry,
6699                                   (LOCKREL_OPCODE | LOCKREL_AFSID |
6700                                    LOCKREL_TIMESTAMP));
6701             if (code) {
6702                 fprintf(STDERR, "Could not update VLDB entry for volume %u\n",
6703                         entry->volumeId[RWVOL]);
6704                 ERROR_EXIT(code);
6705             }
6706         }
6707         islocked = 0;
6708     }
6709
6710     if (modified && modentry) {
6711         *modified = 1;
6712     }
6713     if (deleted && delentry) {
6714         *deleted = 1;
6715     }
6716
6717     if (verbose) {
6718         fprintf(STDOUT, "-- status after --\n");
6719         if (delentry)
6720             fprintf(STDOUT, "\n**entry deleted**\n");
6721         else if (modentry)
6722             EnumerateEntry(entry);
6723         else
6724             fprintf(STDOUT, "\n**no change**\n");
6725     }
6726
6727   error_exit:
6728     VPRINT("\n_______________________________\n");
6729
6730     if (islocked) {
6731         code =
6732             ubik_VL_ReleaseLock(cstruct, 0, entry->volumeId[RWVOL],
6733                       RWVOL,
6734                       (LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP));
6735         if (code) {
6736             fprintf(STDERR,
6737                     "Could not release lock on VLDB entry for volume %u\n",
6738                     entry->volumeId[RWVOL]);
6739             if (!error)
6740                 error = code;
6741         }
6742     }
6743     return error;
6744 }
6745
6746 /* UV_SyncServer()
6747  *      Synchronise <aserver> <apart>(if flags = 1) with the VLDB.
6748  */
6749 int
6750 UV_SyncServer(afs_uint32 aserver, afs_int32 apart, int flags, int force)
6751 {
6752     struct rx_connection *aconn;
6753     afs_int32 code, error = 0;
6754     afs_int32 nentries, tentries = 0;
6755     struct VldbListByAttributes attributes;
6756     nbulkentries arrayEntries;
6757     afs_int32 failures = 0, modified, modifications = 0;
6758     struct nvldbentry *vlentry;
6759     afs_int32 si, nsi, j;
6760
6761     if (flags & 2)
6762         verbose = 1;
6763
6764     aconn = UV_Bind(aserver, AFSCONF_VOLUMEPORT);
6765
6766     /* Set up attributes to search VLDB  */
6767     attributes.server = ntohl(aserver);
6768     attributes.Mask = VLLIST_SERVER;
6769     if ((flags & 1)) {
6770         attributes.partition = apart;
6771         attributes.Mask |= VLLIST_PARTITION;
6772     }
6773
6774     VPRINT("Processing VLDB entries ...\n");
6775
6776     /* While we need to collect more VLDB entries */
6777     for (si = 0; si != -1; si = nsi) {
6778         memset(&arrayEntries, 0, sizeof(arrayEntries));
6779
6780         /* Collect set of VLDB entries */
6781         code =
6782             VLDB_ListAttributesN2(&attributes, 0, si, &nentries,
6783                                   &arrayEntries, &nsi);
6784         if (code == RXGEN_OPCODE) {
6785             code = VLDB_ListAttributes(&attributes, &nentries, &arrayEntries);
6786             nsi = -1;
6787         }
6788         if (code) {
6789             fprintf(STDERR, "Could not access the VLDB for attributes\n");
6790             ERROR_EXIT(code);
6791         }
6792         tentries += nentries;
6793
6794         for (j = 0; j < nentries; j++) {
6795             vlentry = &arrayEntries.nbulkentries_val[j];
6796             MapHostToNetwork(vlentry);
6797
6798             VPRINT1("Processing VLDB entry %d ...\n", j + 1);
6799
6800             /* Tell CheckVldb not to update if appropriate */
6801             if (flags & 2)
6802                 modified = 1;
6803             else
6804                 modified = 0;
6805             code = CheckVldb(vlentry, &modified, NULL);
6806             if (code) {
6807                 PrintError("", code);
6808                 fprintf(STDERR,
6809                         "Could not process VLDB entry for volume %s\n",
6810                         vlentry->name);
6811                 failures++;
6812             } else if (modified) {
6813                 modifications++;
6814             }
6815
6816             if (verbose) {
6817                 if (code) {
6818                     fprintf(STDOUT, "...error encountered\n\n");
6819                 } else {
6820                     fprintf(STDOUT, "...done entry %d\n\n", j + 1);
6821                 }
6822             }
6823         }
6824
6825         if (arrayEntries.nbulkentries_val) {
6826             free(arrayEntries.nbulkentries_val);
6827             arrayEntries.nbulkentries_val = 0;
6828         }
6829     }
6830
6831     if (flags & 2) {
6832         VPRINT3("Total entries: %u, Failed to process %d, Would change %d\n",
6833                 tentries, failures, modifications);
6834     } else {
6835         VPRINT3("Total entries: %u, Failed to process %d, Changed %d\n",
6836                 tentries, failures, modifications);
6837     }
6838
6839   error_exit:
6840     if (aconn)
6841         rx_DestroyConnection(aconn);
6842     if (arrayEntries.nbulkentries_val)
6843         free(arrayEntries.nbulkentries_val);
6844
6845     if (failures)
6846         error = VOLSERFAILEDOP;
6847     return error;
6848 }
6849
6850 /*rename volume <oldname> to <newname>, changing the names of the related
6851  *readonly and backup volumes. This operation is also idempotent.
6852  *salvager is capable of recovering from rename operation stopping halfway.
6853  *to recover run syncserver on the affected machines,it will force renaming to completion. name clashes should have been detected before calling this proc */
6854 int
6855 UV_RenameVolume(struct nvldbentry *entry, char oldname[], char newname[])
6856 {
6857     struct nvldbentry storeEntry;
6858     afs_int32 vcode, code, rcode, error;
6859     int i, index;
6860     char nameBuffer[256];
6861     afs_int32 tid;
6862     struct rx_connection *aconn;
6863     int islocked;
6864     char hoststr[16];
6865
6866     error = 0;
6867     aconn = (struct rx_connection *)0;
6868     tid = 0;
6869     islocked = 0;
6870
6871     vcode = ubik_VL_SetLock(cstruct, 0, entry->volumeId[RWVOL], RWVOL, VLOP_ADDSITE);   /*last param is dummy */
6872     if (vcode) {
6873         fprintf(STDERR,
6874                 " Could not lock the VLDB entry for the  volume %u \n",
6875                 entry->volumeId[RWVOL]);
6876         error = vcode;
6877         goto rvfail;
6878     }
6879     islocked = 1;
6880     strncpy(entry->name, newname, VOLSER_OLDMAXVOLNAME);
6881     MapNetworkToHost(entry, &storeEntry);
6882     vcode = VLDB_ReplaceEntry(entry->volumeId[RWVOL], RWVOL, &storeEntry, 0);
6883     if (vcode) {
6884         fprintf(STDERR, "Could not update VLDB entry for %u\n",
6885                 entry->volumeId[RWVOL]);
6886         error = vcode;
6887         goto rvfail;
6888     }
6889     VPRINT1("Recorded the new name %s in VLDB\n", newname);
6890     /*at this stage the intent to rename is recorded in the vldb, as far as the vldb
6891      * is concerned, oldname is lost */
6892     if (entry->flags & RW_EXISTS) {
6893         index = Lp_GetRwIndex(entry);
6894         if (index == -1) {      /* there is a serious discrepancy */
6895             fprintf(STDERR,
6896                     "There is a serious discrepancy in VLDB entry for volume %u\n",
6897                     entry->volumeId[RWVOL]);
6898             fprintf(STDERR, "try building VLDB from scratch\n");
6899             error = VOLSERVLDB_ERROR;
6900             goto rvfail;
6901         }
6902         aconn = UV_Bind(entry->serverNumber[index], AFSCONF_VOLUMEPORT);
6903         code =
6904             AFSVolTransCreate_retry(aconn, entry->volumeId[RWVOL],
6905                               entry->serverPartition[index], ITOffline, &tid);
6906         if (code) {             /*volume doesnot exist */
6907             fprintf(STDERR,
6908                     "Could not start transaction on the rw volume %u\n",
6909                     entry->volumeId[RWVOL]);
6910             error = code;
6911             goto rvfail;
6912         } else {                /*volume exists, process it */
6913
6914             code =
6915                 AFSVolSetIdsTypes(aconn, tid, newname, RWVOL,
6916                                   entry->volumeId[RWVOL],
6917                                   entry->volumeId[ROVOL],
6918                                   entry->volumeId[BACKVOL]);
6919             if (!code) {
6920                 VPRINT2("Renamed rw volume %s to %s\n", oldname, newname);
6921                 code = AFSVolEndTrans(aconn, tid, &rcode);
6922                 tid = 0;
6923                 if (code) {
6924                     fprintf(STDERR,
6925                             "Could not  end transaction on volume %s %u\n",
6926                             entry->name, entry->volumeId[RWVOL]);
6927                     error = code;
6928                     goto rvfail;
6929                 }
6930             } else {
6931                 fprintf(STDERR, "Could not  set parameters on volume %s %u\n",
6932                         entry->name, entry->volumeId[RWVOL]);
6933                 error = code;
6934                 goto rvfail;
6935             }
6936         }
6937         if (aconn)
6938             rx_DestroyConnection(aconn);
6939         aconn = (struct rx_connection *)0;
6940     }
6941     /*end rw volume processing */
6942     if (entry->flags & BACK_EXISTS) {   /*process the backup volume */
6943         index = Lp_GetRwIndex(entry);
6944         if (index == -1) {      /* there is a serious discrepancy */
6945             fprintf(STDERR,
6946                     "There is a serious discrepancy in the VLDB entry for the backup volume %u\n",
6947                     entry->volumeId[BACKVOL]);
6948             fprintf(STDERR, "try building VLDB from scratch\n");
6949             error = VOLSERVLDB_ERROR;
6950             goto rvfail;
6951         }
6952         aconn = UV_Bind(entry->serverNumber[index], AFSCONF_VOLUMEPORT);
6953         code =
6954             AFSVolTransCreate_retry(aconn, entry->volumeId[BACKVOL],
6955                               entry->serverPartition[index], ITOffline, &tid);
6956         if (code) {             /*volume doesnot exist */
6957             fprintf(STDERR,
6958                     "Could not start transaction on the backup volume  %u\n",
6959                     entry->volumeId[BACKVOL]);
6960             error = code;
6961             goto rvfail;
6962         } else {                /*volume exists, process it */
6963             if (strlen(newname) > (VOLSER_OLDMAXVOLNAME - 8)) {
6964                 fprintf(STDERR,
6965                         "Volume name %s.backup exceeds the limit of %u characters\n",
6966                         newname, VOLSER_OLDMAXVOLNAME);
6967                 error = code;
6968                 goto rvfail;
6969             }
6970             strcpy(nameBuffer, newname);
6971             strcat(nameBuffer, ".backup");
6972
6973             code =
6974                 AFSVolSetIdsTypes(aconn, tid, nameBuffer, BACKVOL,
6975                                   entry->volumeId[RWVOL], 0, 0);
6976             if (!code) {
6977                 VPRINT1("Renamed backup volume to %s \n", nameBuffer);
6978                 code = AFSVolEndTrans(aconn, tid, &rcode);
6979                 tid = 0;
6980                 if (code) {
6981                     fprintf(STDERR,
6982                             "Could not  end transaction on the backup volume %u\n",
6983                             entry->volumeId[BACKVOL]);
6984                     error = code;
6985                     goto rvfail;
6986                 }
6987             } else {
6988                 fprintf(STDERR,
6989                         "Could not  set parameters on the backup volume %u\n",
6990                         entry->volumeId[BACKVOL]);
6991                 error = code;
6992                 goto rvfail;
6993             }
6994         }
6995     }                           /* end backup processing */
6996     if (aconn)
6997         rx_DestroyConnection(aconn);
6998     aconn = (struct rx_connection *)0;
6999     if (entry->flags & RO_EXISTS) {     /*process the ro volumes */
7000         for (i = 0; i < entry->nServers; i++) {
7001             if (entry->serverFlags[i] & ITSROVOL) {
7002                 aconn = UV_Bind(entry->serverNumber[i], AFSCONF_VOLUMEPORT);
7003                 code =
7004                     AFSVolTransCreate_retry(aconn, entry->volumeId[ROVOL],
7005                                       entry->serverPartition[i], ITOffline,
7006                                       &tid);
7007                 if (code) {     /*volume doesnot exist */
7008                     fprintf(STDERR,
7009                             "Could not start transaction on the ro volume %u\n",
7010                             entry->volumeId[ROVOL]);
7011                     error = code;
7012                     goto rvfail;
7013                 } else {        /*volume exists, process it */
7014                     strcpy(nameBuffer, newname);
7015                     strcat(nameBuffer, ".readonly");
7016                     if (strlen(nameBuffer) > (VOLSER_OLDMAXVOLNAME - 1)) {
7017                         fprintf(STDERR,
7018                                 "Volume name %s exceeds the limit of %u characters\n",
7019                                 nameBuffer, VOLSER_OLDMAXVOLNAME);
7020                         error = code;
7021                         goto rvfail;
7022                     }
7023                     code =
7024                         AFSVolSetIdsTypes(aconn, tid, nameBuffer, ROVOL,
7025                                           entry->volumeId[RWVOL], 0, 0);
7026                     if (!code) {
7027                         VPRINT2("Renamed RO volume %s on host %s\n",
7028                                 nameBuffer,
7029                                 noresolve ?
7030                                 afs_inet_ntoa_r(entry->serverNumber[i], hoststr) :
7031                                 hostutil_GetNameByINet(entry->
7032                                                        serverNumber[i]));
7033                         code = AFSVolEndTrans(aconn, tid, &rcode);
7034                         tid = 0;
7035                         if (code) {
7036                             fprintf(STDERR,
7037                                     "Could not  end transaction on volume %u\n",
7038                                     entry->volumeId[ROVOL]);
7039                             error = code;
7040                             goto rvfail;
7041                         }
7042                     } else {
7043                         fprintf(STDERR,
7044                                 "Could not  set parameters on the ro volume %u\n",
7045                                 entry->volumeId[ROVOL]);
7046                         error = code;
7047                         goto rvfail;
7048                     }
7049                 }
7050                 if (aconn)
7051                     rx_DestroyConnection(aconn);
7052                 aconn = (struct rx_connection *)0;
7053             }
7054         }
7055     }
7056   rvfail:
7057     if (islocked) {
7058         vcode =
7059             ubik_VL_ReleaseLock(cstruct, 0, entry->volumeId[RWVOL],
7060                       RWVOL,
7061                       LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
7062         if (vcode) {
7063             fprintf(STDERR,
7064                     "Could not unlock the VLDB entry for the volume %s %u\n",
7065                     entry->name, entry->volumeId[RWVOL]);
7066             if (!error)
7067                 error = vcode;
7068         }
7069     }
7070     if (tid) {
7071         code = AFSVolEndTrans(aconn, tid, &rcode);
7072         if (!code)
7073             code = rcode;
7074         if (code) {
7075             fprintf(STDERR, "Failed to end transaction on a volume \n");
7076             if (!error)
7077                 error = code;
7078         }
7079     }
7080     if (aconn)
7081         rx_DestroyConnection(aconn);
7082     PrintError("", error);
7083     return error;
7084
7085 }
7086
7087 /*report on all the active transactions on volser */
7088 int
7089 UV_VolserStatus(afs_uint32 server, transDebugInfo ** rpntr, afs_int32 * rcount)
7090 {
7091     struct rx_connection *aconn;
7092     transDebugEntries transInfo;
7093     afs_int32 code = 0;
7094
7095     aconn = UV_Bind(server, AFSCONF_VOLUMEPORT);
7096     transInfo.transDebugEntries_val = (transDebugInfo *) 0;
7097     transInfo.transDebugEntries_len = 0;
7098     code = AFSVolMonitor(aconn, &transInfo);
7099     if (code) {
7100         fprintf(STDERR,
7101                 "Could not access status information about the server\n");
7102         PrintError("", code);
7103         if (transInfo.transDebugEntries_val)
7104             free(transInfo.transDebugEntries_val);
7105         if (aconn)
7106             rx_DestroyConnection(aconn);
7107         return code;
7108     } else {
7109         *rcount = transInfo.transDebugEntries_len;
7110         *rpntr = transInfo.transDebugEntries_val;
7111         if (aconn)
7112             rx_DestroyConnection(aconn);
7113         return 0;
7114     }
7115
7116
7117 }
7118
7119 /*delete the volume without interacting with the vldb */
7120 int
7121 UV_VolumeZap(afs_uint32 server, afs_int32 part, afs_uint32 volid)
7122 {
7123     afs_int32 rcode, ttid, error, code;
7124     struct rx_connection *aconn;
7125
7126     code = 0;
7127     error = 0;
7128     ttid = 0;
7129
7130     aconn = UV_Bind(server, AFSCONF_VOLUMEPORT);
7131     code = AFSVolTransCreate_retry(aconn, volid, part, ITOffline, &ttid);
7132     if (code) {
7133         fprintf(STDERR, "Could not start transaction on volume %lu\n",
7134                 (unsigned long)volid);
7135         error = code;
7136         goto zfail;
7137     }
7138     code = AFSVolDeleteVolume(aconn, ttid);
7139     if (code) {
7140         fprintf(STDERR, "Could not delete volume %lu\n",
7141                 (unsigned long)volid);
7142         error = code;
7143         goto zfail;
7144     }
7145     code = AFSVolEndTrans(aconn, ttid, &rcode);
7146     ttid = 0;
7147     if (!code)
7148         code = rcode;
7149     if (code) {
7150         fprintf(STDERR, "Could not end transaction on volume %lu\n",
7151                 (unsigned long)volid);
7152         error = code;
7153         goto zfail;
7154     }
7155   zfail:
7156     if (ttid) {
7157         code = AFSVolEndTrans(aconn, ttid, &rcode);
7158         if (!code)
7159             code = rcode;
7160         if (!error)
7161             error = code;
7162     }
7163     PrintError("", error);
7164     if (aconn)
7165         rx_DestroyConnection(aconn);
7166     return error;
7167 }
7168
7169 int
7170 UV_SetVolume(afs_uint32 server, afs_int32 partition, afs_uint32 volid,
7171              afs_int32 transflag, afs_int32 setflag, int sleeptime)
7172 {
7173     struct rx_connection *conn = 0;
7174     afs_int32 tid = 0;
7175     afs_int32 code, error = 0, rcode;
7176
7177     conn = UV_Bind(server, AFSCONF_VOLUMEPORT);
7178     if (!conn) {
7179         fprintf(STDERR, "SetVolumeStatus: Bind Failed");
7180         ERROR_EXIT(-1);
7181     }
7182
7183     code = AFSVolTransCreate_retry(conn, volid, partition, transflag, &tid);
7184     if (code) {
7185         fprintf(STDERR, "SetVolumeStatus: TransCreate Failed\n");
7186         ERROR_EXIT(code);
7187     }
7188
7189     code = AFSVolSetFlags(conn, tid, setflag);
7190     if (code) {
7191         fprintf(STDERR, "SetVolumeStatus: SetFlags Failed\n");
7192         ERROR_EXIT(code);
7193     }
7194
7195     if (sleeptime) {
7196 #ifdef AFS_PTHREAD_ENV
7197         sleep(sleeptime);
7198 #else
7199         IOMGR_Sleep(sleeptime);
7200 #endif
7201     }
7202
7203   error_exit:
7204     if (tid) {
7205         rcode = 0;
7206         code = AFSVolEndTrans(conn, tid, &rcode);
7207         if (code || rcode) {
7208             fprintf(STDERR, "SetVolumeStatus: EndTrans Failed\n");
7209             if (!error)
7210                 error = (code ? code : rcode);
7211         }
7212     }
7213
7214     if (conn)
7215         rx_DestroyConnection(conn);
7216     return (error);
7217 }
7218
7219 int
7220 UV_SetVolumeInfo(afs_uint32 server, afs_int32 partition, afs_uint32 volid,
7221                  volintInfo * infop)
7222 {
7223     struct rx_connection *conn = 0;
7224     afs_int32 tid = 0;
7225     afs_int32 code, error = 0, rcode;
7226
7227     conn = UV_Bind(server, AFSCONF_VOLUMEPORT);
7228     if (!conn) {
7229         fprintf(STDERR, "SetVolumeInfo: Bind Failed");
7230         ERROR_EXIT(-1);
7231     }
7232
7233     code = AFSVolTransCreate_retry(conn, volid, partition, ITOffline, &tid);
7234     if (code) {
7235         fprintf(STDERR, "SetVolumeInfo: TransCreate Failed\n");
7236         ERROR_EXIT(code);
7237     }
7238
7239     code = AFSVolSetInfo(conn, tid, infop);
7240     if (code) {
7241         fprintf(STDERR, "SetVolumeInfo: SetInfo Failed\n");
7242         ERROR_EXIT(code);
7243     }
7244
7245   error_exit:
7246     if (tid) {
7247         rcode = 0;
7248         code = AFSVolEndTrans(conn, tid, &rcode);
7249         if (code || rcode) {
7250             fprintf(STDERR, "SetVolumeInfo: EndTrans Failed\n");
7251             if (!error)
7252                 error = (code ? code : rcode);
7253         }
7254     }
7255
7256     if (conn)
7257         rx_DestroyConnection(conn);
7258     return (error);
7259 }
7260
7261 int
7262 UV_GetSize(afs_uint32 afromvol, afs_uint32 afromserver, afs_int32 afrompart,
7263            afs_int32 fromdate, struct volintSize *vol_size)
7264 {
7265     struct rx_connection *aconn = (struct rx_connection *)0;
7266     afs_int32 tid = 0, rcode = 0;
7267     afs_int32 code, error = 0;
7268
7269
7270     /* get connections to the servers */
7271     aconn = UV_Bind(afromserver, AFSCONF_VOLUMEPORT);
7272
7273     VPRINT1("Starting transaction on volume %u...", afromvol);
7274     code = AFSVolTransCreate_retry(aconn, afromvol, afrompart, ITBusy, &tid);
7275     EGOTO1(error_exit, code,
7276            "Could not start transaction on the volume %u to be measured\n",
7277            afromvol);
7278     VDONE;
7279
7280     VPRINT1("Getting size of volume on volume %u...", afromvol);
7281     code = AFSVolGetSize(aconn, tid, fromdate, vol_size);
7282     EGOTO(error_exit, code, "Could not start the measurement process \n");
7283     VDONE;
7284
7285   error_exit:
7286     if (tid) {
7287         VPRINT1("Ending transaction on volume %u...", afromvol);
7288         code = AFSVolEndTrans(aconn, tid, &rcode);
7289         if (code || rcode) {
7290             fprintf(STDERR, "Could not end transaction on the volume %u\n",
7291                     afromvol);
7292             fprintf(STDERR, "error codes: %d and %d\n", code, rcode);
7293             if (!error)
7294                 error = (code ? code : rcode);
7295         }
7296         VDONE;
7297     }
7298     if (aconn)
7299         rx_DestroyConnection(aconn);
7300
7301     PrintError("", error);
7302     return (error);
7303 }
7304
7305 /*maps the host addresses in <old > (present in network byte order) to
7306  that in< new> (present in host byte order )*/
7307 void
7308 MapNetworkToHost(struct nvldbentry *old, struct nvldbentry *new)
7309 {
7310     int i, count;
7311
7312     /*copy all the fields */
7313     strcpy(new->name, old->name);
7314 /*    new->volumeType = old->volumeType;*/
7315     new->nServers = old->nServers;
7316     count = old->nServers;
7317     if (count < NMAXNSERVERS)
7318         count++;
7319     for (i = 0; i < count; i++) {
7320         new->serverNumber[i] = ntohl(old->serverNumber[i]);
7321         new->serverPartition[i] = old->serverPartition[i];
7322         new->serverFlags[i] = old->serverFlags[i];
7323     }
7324     new->volumeId[RWVOL] = old->volumeId[RWVOL];
7325     new->volumeId[ROVOL] = old->volumeId[ROVOL];
7326     new->volumeId[BACKVOL] = old->volumeId[BACKVOL];
7327     new->cloneId = old->cloneId;
7328     new->flags = old->flags;
7329 }
7330
7331 /*maps the host entries in <entry> which are present in host byte order to network byte order */
7332 void
7333 MapHostToNetwork(struct nvldbentry *entry)
7334 {
7335     int i, count;
7336
7337     count = entry->nServers;
7338     if (count < NMAXNSERVERS)
7339         count++;
7340     for (i = 0; i < count; i++) {
7341         entry->serverNumber[i] = htonl(entry->serverNumber[i]);
7342     }
7343 }