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