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