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