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