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