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