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