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