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