12961e390ea5ca8a134de27cae93e4f08e156ad8
[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
4605     /*
4606      * Obtain a transaction and get the status of the target volume. Create a new
4607      * volume if the target volume does not already exist.
4608      */
4609     memset(&tstatus, 0, sizeof(tstatus));
4610     if ((flags & RV_FULLRST) != 0) {
4611         /* Full restore: Delete existing volume then create anew. */
4612         code = DoVolDelete(toconn, pvolid, topart, "the previous", 0, &tstatus, NULL);
4613         if (code && code != VNOVOL) {
4614             error = code;
4615             goto refail;
4616         }
4617         code = AFSVolCreateVolume(toconn, topart, tovolreal, volsertype, pparentid,
4618                                   &pvolid, &totid);
4619         EGOTO1(refail, code, "Could not create new volume %u\n", pvolid);
4620     } else {
4621         /* Incremental restore: Obtain a transaction on the existing volume. */
4622         code = AFSVolTransCreate_retry(toconn, pvolid, topart, ITOffline, &totid);
4623         if (code == 0) {
4624             code = AFSVolGetStatus(toconn, totid, &tstatus);
4625             EGOTO1(refail, code, "Could not get timestamp from volume %u\n", pvolid);
4626         } else if (code == VNOVOL) {
4627             code = AFSVolCreateVolume(toconn, topart, tovolreal, volsertype,
4628                                       pparentid, &pvolid, &totid);
4629             EGOTO1(refail, code, "Could not create new volume %u\n", pvolid);
4630         } else {
4631             EGOTO1(refail, code, "Failed to start transaction on %u\n", pvolid);
4632         }
4633     }
4634     oldCreateDate = tstatus.creationDate;
4635     oldUpdateDate = tstatus.updateDate;
4636     oldCloneId = tstatus.cloneID;
4637     oldBackupId = tstatus.backupID;
4638
4639     cookie.parent = pparentid;
4640     cookie.type = voltype;
4641     cookie.clone = 0;
4642     strncpy(cookie.name, tovolreal, VOLSER_OLDMAXVOLNAME);
4643
4644     tocall = rx_NewCall(toconn);
4645     terror = StartAFSVolRestore(tocall, totid, 1, &cookie);
4646     if (terror) {
4647         fprintf(STDERR, "Volume restore Failed \n");
4648         error = terror;
4649         goto refail;
4650     }
4651     code = WriteData(tocall, rock);
4652     if (code) {
4653         fprintf(STDERR, "Could not transmit data\n");
4654         error = code;
4655         goto refail;
4656     }
4657     terror = rx_EndCall(tocall, 0);
4658     tocall = (struct rx_call *)0;
4659     if (terror) {
4660         fprintf(STDERR, "rx_EndCall Failed \n");
4661         error = terror;
4662         goto refail;
4663     }
4664     code = AFSVolGetStatus(toconn, totid, &tstatus);
4665     if (code) {
4666         fprintf(STDERR,
4667                 "Could not get status information about the volume %lu\n",
4668                 (unsigned long)pvolid);
4669         error = code;
4670         goto refail;
4671     }
4672     code = AFSVolSetIdsTypes(toconn, totid, tovolreal, voltype, pparentid,
4673                                 oldCloneId, oldBackupId);
4674     if (code) {
4675         fprintf(STDERR, "Could not set the right type and IDs on %lu\n",
4676                 (unsigned long)pvolid);
4677         error = code;
4678         goto refail;
4679     }
4680
4681     if (flags & RV_CRDUMP)
4682         newCreateDate = tstatus.creationDate;
4683     else if (flags & RV_CRKEEP && oldCreateDate != 0)
4684         newCreateDate = oldCreateDate;
4685     else
4686         newCreateDate = time(0);
4687     if (flags & RV_LUDUMP)
4688         newUpdateDate = tstatus.updateDate;
4689     else if (flags & RV_LUKEEP)
4690         newUpdateDate = oldUpdateDate;
4691     else
4692         newUpdateDate = time(0);
4693     code = AFSVolSetDate(toconn,totid, newCreateDate);
4694     if (code) {
4695         fprintf(STDERR, "Could not set the 'creation' date on %u\n", pvolid);
4696         error = code;
4697         goto refail;
4698     }
4699
4700     init_volintInfo(&vinfo);
4701     vinfo.creationDate = newCreateDate;
4702     vinfo.updateDate = newUpdateDate;
4703     code = AFSVolSetInfo(toconn, totid, &vinfo);
4704     if (code) {
4705         fprintf(STDERR, "Could not set the 'last updated' date on %u\n",
4706                 pvolid);
4707         error = code;
4708         goto refail;
4709     }
4710
4711     volflag = ((flags & RV_OFFLINE) ? VTOutOfService : 0);      /* off or on-line */
4712     code = AFSVolSetFlags(toconn, totid, volflag);
4713     if (code) {
4714         fprintf(STDERR, "Could not mark %lu online\n", (unsigned long)pvolid);
4715         error = code;
4716         goto refail;
4717     }
4718
4719 /* It isn't handled right in refail */
4720     code = AFSVolEndTrans(toconn, totid, &rcode);
4721     totid = 0;
4722     if (!code)
4723         code = rcode;
4724     if (code) {
4725         fprintf(STDERR, "Could not end transaction on %lu\n",
4726                 (unsigned long)pvolid);
4727         error = code;
4728         goto refail;
4729     }
4730
4731     fprintf(STDOUT, " done\n");
4732     fflush(STDOUT);
4733     if (!reuseID || (flags & RV_FULLRST)) {
4734         /* Volume was restored on the file server, update the
4735          * VLDB to reflect the change.
4736          */
4737         vcode = VLDB_GetEntryByID(pvolid, voltype, &entry);
4738         if (vcode && vcode != VL_NOENT && vcode != VL_ENTDELETED) {
4739             fprintf(STDERR,
4740                     "Could not fetch the entry for volume number %lu from VLDB \n",
4741                     (unsigned long)pvolid);
4742             error = vcode;
4743             goto refail;
4744         }
4745         if (!vcode)
4746             MapHostToNetwork(&entry);
4747         if (vcode == VL_NOENT) {        /* it doesnot exist already */
4748             /*make the vldb return this indication specifically */
4749             VPRINT("------- Creating a new VLDB entry ------- \n");
4750             strcpy(entry.name, tovolname);
4751             entry.nServers = 1;
4752             entry.serverNumber[0] = toserver;   /*should be indirect */
4753             entry.serverPartition[0] = topart;
4754             entry.serverFlags[0] = (flags & RV_RDONLY) ? VLSF_ROVOL : VLSF_RWVOL;
4755             entry.flags = (flags & RV_RDONLY) ? VLF_ROEXISTS : VLF_RWEXISTS;
4756             if (flags & RV_RDONLY)
4757                 entry.volumeId[ROVOL] = pvolid;
4758             else if (tstatus.cloneID != 0) {
4759                 entry.volumeId[ROVOL] = tstatus.cloneID;        /*this should come from status info on the volume if non zero */
4760             } else
4761                 entry.volumeId[ROVOL] = INVALID_BID;
4762             entry.volumeId[RWVOL] = pparentid;
4763             entry.cloneId = 0;
4764             if (tstatus.backupID != 0) {
4765                 entry.volumeId[BACKVOL] = tstatus.backupID;
4766                 /*this should come from status info on the volume if non zero */
4767             } else
4768                 entry.volumeId[BACKVOL] = INVALID_BID;
4769             MapNetworkToHost(&entry, &storeEntry);
4770             vcode = VLDB_CreateEntry(&storeEntry);
4771             if (vcode) {
4772                 fprintf(STDERR,
4773                         "Could not create the VLDB entry for volume number %lu  \n",
4774                         (unsigned long)pvolid);
4775                 error = vcode;
4776                 goto refail;
4777             }
4778             islocked = 0;
4779             if (verbose)
4780                 EnumerateEntry(&entry);
4781         } else {                /*update the existing entry */
4782             if (verbose) {
4783                 fprintf(STDOUT, "Updating the existing VLDB entry\n");
4784                 fprintf(STDOUT, "------- Old entry -------\n");
4785                 EnumerateEntry(&entry);
4786                 fprintf(STDOUT, "------- New entry -------\n");
4787             }
4788             vcode =
4789                 ubik_VL_SetLock(cstruct, 0, pvolid, voltype,
4790                           VLOP_RESTORE);
4791             if (vcode) {
4792                 fprintf(STDERR,
4793                         "Could not lock the entry for volume number %lu \n",
4794                         (unsigned long)pvolid);
4795                 error = vcode;
4796                 goto refail;
4797             }
4798             islocked = 1;
4799             strcpy(entry.name, tovolname);
4800
4801             /* Update the vlentry with the new information */
4802             if (flags & RV_RDONLY)
4803                 index = Lp_ROMatch(toserver, topart, &entry) - 1;
4804             else
4805                 index = Lp_GetRwIndex(&entry);
4806             if (index == -1) {
4807                 /* Add the new site for the volume being restored */
4808                 entry.serverNumber[entry.nServers] = toserver;
4809                 entry.serverPartition[entry.nServers] = topart;
4810                 entry.serverFlags[entry.nServers] =
4811                     (flags & RV_RDONLY) ? VLSF_ROVOL : VLSF_RWVOL;
4812                 entry.nServers++;
4813             } else {
4814                 /* This volume should be deleted on the old site
4815                  * if its different from new site.
4816                  */
4817                 same =
4818                     VLDB_IsSameAddrs(toserver, entry.serverNumber[index],
4819                                      &errcode);
4820                 if (errcode)
4821                     EPRINT2(errcode,
4822                             "Failed to get info about server's %d address(es) from vlserver (err=%d)\n",
4823                             toserver, errcode);
4824                 if ((!errcode && !same)
4825                     || (entry.serverPartition[index] != topart)) {
4826                     if (flags & RV_NODEL) {
4827                         VPRINT2
4828                             ("Not deleting the previous volume %u on server %s, ...",
4829                              pvolid,
4830                              noresolve ? afs_inet_ntoa_r(entry.serverNumber[index], hoststr) :
4831                              hostutil_GetNameByINet(entry.serverNumber[index]));
4832                     } else {
4833                         tempconn =
4834                             UV_Bind(entry.serverNumber[index],
4835                                     AFSCONF_VOLUMEPORT);
4836
4837                         MapPartIdIntoName(entry.serverPartition[index],
4838                                           apartName);
4839                         VPRINT3
4840                             ("Deleting the previous volume %u on server %s, partition %s ...",
4841                              pvolid,
4842                              noresolve ? afs_inet_ntoa_r(entry.serverNumber[index], hoststr) :
4843                              hostutil_GetNameByINet(entry.serverNumber[index]),
4844                              apartName);
4845                         code = DoVolDelete(tempconn, pvolid,
4846                                            entry.serverPartition[index],
4847                                            "the", 0, NULL, NULL);
4848                         if (code && code != VNOVOL) {
4849                             error = code;
4850                             goto refail;
4851                         }
4852                         MapPartIdIntoName(entry.serverPartition[index],
4853                                           partName);
4854                     }
4855                 }
4856                 entry.serverNumber[index] = toserver;
4857                 entry.serverPartition[index] = topart;
4858             }
4859
4860             entry.flags |= (flags & RV_RDONLY) ? VLF_ROEXISTS : VLF_RWEXISTS;
4861             MapNetworkToHost(&entry, &storeEntry);
4862             vcode =
4863                 VLDB_ReplaceEntry(pvolid, voltype, &storeEntry,
4864                                   LOCKREL_OPCODE | LOCKREL_AFSID |
4865                                   LOCKREL_TIMESTAMP);
4866             if (vcode) {
4867                 fprintf(STDERR,
4868                         "Could not update the entry for volume number %lu  \n",
4869                         (unsigned long)pvolid);
4870                 error = vcode;
4871                 goto refail;
4872             }
4873             islocked = 0;
4874             if (verbose)
4875                 EnumerateEntry(&entry);
4876         }
4877
4878
4879     }
4880   refail:
4881     if (tocall) {
4882         code = rx_EndCall(tocall, 0);
4883         if (!error)
4884             error = code;
4885     }
4886     if (islocked) {
4887         vcode =
4888             ubik_VL_ReleaseLock(cstruct, 0, pvolid, voltype,
4889                       LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
4890         if (vcode) {
4891             fprintf(STDERR,
4892                     "Could not release lock on the VLDB entry for the volume %lu\n",
4893                     (unsigned long)pvolid);
4894             if (!error)
4895                 error = vcode;
4896         }
4897     }
4898     if (totid) {
4899         code = AFSVolEndTrans(toconn, totid, &rcode);
4900         if (!code)
4901             code = rcode;
4902         if (code) {
4903             fprintf(STDERR, "Could not end transaction on the volume %lu \n",
4904                     (unsigned long)pvolid);
4905             if (!error)
4906                 error = code;
4907         }
4908     }
4909     if (temptid) {
4910         code = AFSVolEndTrans(toconn, temptid, &rcode);
4911         if (!code)
4912             code = rcode;
4913         if (code) {
4914             fprintf(STDERR, "Could not end transaction on the volume %lu \n",
4915                     (unsigned long)pvolid);
4916             if (!error)
4917                 error = code;
4918         }
4919     }
4920     if (tempconn)
4921         rx_DestroyConnection(tempconn);
4922     if (toconn)
4923         rx_DestroyConnection(toconn);
4924     PrintError("", error);
4925     return error;
4926 }
4927
4928 int
4929 UV_RestoreVolume(afs_uint32 toserver, afs_int32 topart, afs_uint32 tovolid,
4930                  char tovolname[], int flags,
4931                  afs_int32(*WriteData) (struct rx_call *, void *),
4932                  void *rock)
4933 {
4934     return UV_RestoreVolume2(toserver, topart, tovolid, 0, tovolname, flags,
4935                              WriteData, rock);
4936 }
4937
4938
4939 /*unlocks the vldb entry associated with <volid> */
4940 int
4941 UV_LockRelease(afs_uint32 volid)
4942 {
4943     afs_int32 vcode;
4944
4945     VPRINT("Binding to the VLDB server\n");
4946     vcode =
4947         ubik_VL_ReleaseLock(cstruct, 0, volid, -1,
4948                   LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
4949     if (vcode) {
4950         fprintf(STDERR,
4951                 "Could not unlock the entry for volume number %lu in VLDB \n",
4952                 (unsigned long)volid);
4953         PrintError("", vcode);
4954         return (vcode);
4955     }
4956     VPRINT("VLDB updated\n");
4957     return 0;
4958
4959 }
4960
4961 /* old interface to add rosites */
4962 int
4963 UV_AddSite(afs_uint32 server, afs_int32 part, afs_uint32 volid,
4964            afs_int32 valid)
4965 {
4966     return UV_AddSite2(server, part, volid, 0, valid);
4967 }
4968
4969 /*adds <server> and <part> as a readonly replication site for <volid>
4970 *in vldb */
4971 int
4972 UV_AddSite2(afs_uint32 server, afs_int32 part, afs_uint32 volid,
4973             afs_uint32 rovolid, afs_int32 valid)
4974 {
4975     int j, nro = 0, islocked = 0;
4976     struct nvldbentry entry, storeEntry, entry2;
4977     afs_int32 vcode, error = 0;
4978     char apartName[10];
4979
4980     error = ubik_VL_SetLock(cstruct, 0, volid, RWVOL, VLOP_ADDSITE);
4981     if (error) {
4982         fprintf(STDERR,
4983                 " Could not lock the VLDB entry for the volume %lu \n",
4984                 (unsigned long)volid);
4985         goto asfail;
4986     }
4987     islocked = 1;
4988
4989     error = VLDB_GetEntryByID(volid, RWVOL, &entry);
4990     if (error) {
4991         fprintf(STDERR,
4992                 "Could not fetch the VLDB entry for volume number %lu  \n",
4993                 (unsigned long)volid);
4994         goto asfail;
4995
4996     }
4997     if (!ISNAMEVALID(entry.name)) {
4998         fprintf(STDERR,
4999                 "Volume name %s is too long, rename before adding site\n",
5000                 entry.name);
5001         error = VOLSERBADOP;
5002         goto asfail;
5003     }
5004     MapHostToNetwork(&entry);
5005
5006     /* See if it's too many entries */
5007     if (entry.nServers >= NMAXNSERVERS) {
5008         fprintf(STDERR, "Total number of entries will exceed %u\n",
5009                 NMAXNSERVERS);
5010         error = VOLSERBADOP;
5011         goto asfail;
5012     }
5013
5014     /* See if it's on the same server */
5015     for (j = 0; j < entry.nServers; j++) {
5016         if (entry.serverFlags[j] & VLSF_ROVOL) {
5017             nro++;
5018             if (VLDB_IsSameAddrs(server, entry.serverNumber[j], &error)) {
5019                 if (error) {
5020                     fprintf(STDERR,
5021                             "Failed to get info about server's %d address(es) from vlserver (err=%d); aborting call!\n",
5022                             server, error);
5023                 } else {
5024                     MapPartIdIntoName(entry.serverPartition[j], apartName);
5025                     fprintf(STDERR,
5026                             "RO already exists on partition %s. Multiple ROs on a single server aren't allowed\n",
5027                             apartName);
5028                     error = VOLSERBADOP;
5029                 }
5030                 goto asfail;
5031             }
5032         }
5033     }
5034
5035     /* See if it's too many RO sites - leave one for the RW */
5036     if (nro >= NMAXNSERVERS - 1) {
5037         fprintf(STDERR, "Total number of sites will exceed %u\n",
5038                 NMAXNSERVERS - 1);
5039         error = VOLSERBADOP;
5040         goto asfail;
5041     }
5042
5043     /* if rovolid == 0, we leave the RO volume id alone. If the volume doesn't
5044      * have an RO volid at this point (i.e. entry.volumeId[ROVOL] ==
5045      * INVALID_BID) and we leave it alone, it gets an RO volid at release-time.
5046      */
5047     if (rovolid) {
5048         if (entry.volumeId[ROVOL] == INVALID_BID) {
5049             vcode = VLDB_GetEntryByID(rovolid, -1, &entry2);
5050             if (!vcode) {
5051                 fprintf(STDERR, "Volume ID %d already exists\n", rovolid);
5052                 return VVOLEXISTS;
5053             }
5054             VPRINT1("Using RO volume id %d.\n", rovolid);
5055             entry.volumeId[ROVOL] = rovolid;
5056         } else {
5057             fprintf(STDERR, "Ignoring given RO id %d, since volume already has RO id %d\n",
5058                 rovolid, entry.volumeId[ROVOL]);
5059         }
5060     }
5061
5062     VPRINT("Adding a new site ...");
5063     entry.serverNumber[entry.nServers] = server;
5064     entry.serverPartition[entry.nServers] = part;
5065     if (!valid) {
5066         entry.serverFlags[entry.nServers] = (VLSF_ROVOL | VLSF_DONTUSE);
5067     } else {
5068         entry.serverFlags[entry.nServers] = (VLSF_ROVOL);
5069     }
5070     entry.nServers++;
5071
5072     MapNetworkToHost(&entry, &storeEntry);
5073     error =
5074         VLDB_ReplaceEntry(volid, RWVOL, &storeEntry,
5075                           LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
5076     if (error) {
5077         fprintf(STDERR, "Could not update entry for volume %lu \n",
5078                 (unsigned long)volid);
5079         goto asfail;
5080     }
5081     islocked = 0;
5082     VDONE;
5083
5084   asfail:
5085     if (islocked) {
5086         vcode =
5087             ubik_VL_ReleaseLock(cstruct, 0, volid, RWVOL,
5088                       LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
5089         if (vcode) {
5090             fprintf(STDERR,
5091                     "Could not release lock on volume entry for %lu \n",
5092                     (unsigned long)volid);
5093             PrintError("", vcode);
5094         }
5095     }
5096
5097     PrintError("", error);
5098     return error;
5099 }
5100
5101 /*removes <server> <part> as read only site for <volid> from the vldb */
5102 int
5103 UV_RemoveSite(afs_uint32 server, afs_int32 part, afs_uint32 volid)
5104 {
5105     afs_int32 vcode;
5106     struct nvldbentry entry, storeEntry;
5107
5108     vcode = ubik_VL_SetLock(cstruct, 0, volid, RWVOL, VLOP_ADDSITE);
5109     if (vcode) {
5110         fprintf(STDERR, " Could not lock the VLDB entry for volume %lu \n",
5111                 (unsigned long)volid);
5112         PrintError("", vcode);
5113         return (vcode);
5114     }
5115     vcode = VLDB_GetEntryByID(volid, RWVOL, &entry);
5116     if (vcode) {
5117         fprintf(STDERR,
5118                 "Could not fetch the entry for volume number %lu from VLDB \n",
5119                 (unsigned long)volid);
5120         PrintError("", vcode);
5121         return (vcode);
5122     }
5123     MapHostToNetwork(&entry);
5124     if (!Lp_ROMatch(server, part, &entry)) {
5125         /*this site doesnot exist  */
5126         fprintf(STDERR, "This site is not a replication site \n");
5127         vcode =
5128             ubik_VL_ReleaseLock(cstruct, 0, volid, RWVOL,
5129                       LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
5130         if (vcode) {
5131             fprintf(STDERR, "Could not update entry for volume %lu \n",
5132                     (unsigned long)volid);
5133             PrintError("", vcode);
5134             ubik_VL_ReleaseLock(cstruct, 0, volid, RWVOL,
5135                       LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
5136             return (vcode);
5137         }
5138         return VOLSERBADOP;
5139     } else {                    /*remove the rep site */
5140         Lp_SetROValue(&entry, server, part, 0, 0);
5141         entry.nServers--;
5142         if ((entry.nServers == 1) && (entry.flags & VLF_RWEXISTS))
5143             entry.flags &= ~VLF_ROEXISTS;
5144         if (entry.nServers < 1) {       /*this is the last ref */
5145             VPRINT1("Deleting the VLDB entry for %u ...", volid);
5146             fflush(STDOUT);
5147             vcode = ubik_VL_DeleteEntry(cstruct, 0, volid, ROVOL);
5148             if (vcode) {
5149                 fprintf(STDERR,
5150                         "Could not delete VLDB entry for volume %lu \n",
5151                         (unsigned long)volid);
5152                 PrintError("", vcode);
5153                 return (vcode);
5154             }
5155             VDONE;
5156         }
5157         MapNetworkToHost(&entry, &storeEntry);
5158         fprintf(STDOUT, "Deleting the replication site for volume %lu ...",
5159                 (unsigned long)volid);
5160         fflush(STDOUT);
5161         vcode =
5162             VLDB_ReplaceEntry(volid, RWVOL, &storeEntry,
5163                               LOCKREL_OPCODE | LOCKREL_AFSID |
5164                               LOCKREL_TIMESTAMP);
5165         if (vcode) {
5166             fprintf(STDERR,
5167                     "Could not release lock on volume entry for %lu \n",
5168                     (unsigned long)volid);
5169             PrintError("", vcode);
5170             ubik_VL_ReleaseLock(cstruct, 0, volid, RWVOL,
5171                       LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
5172             return (vcode);
5173         }
5174         fprintf(STDOUT, " done\n");
5175         fflush(STDOUT);
5176     }
5177     return 0;
5178 }
5179
5180 /*sets <server> <part> as read/write site for <volid> in the vldb */
5181 int
5182 UV_ChangeLocation(afs_uint32 server, afs_int32 part, afs_uint32 volid)
5183 {
5184     afs_int32 vcode;
5185     struct nvldbentry entry, storeEntry;
5186     int index;
5187
5188     vcode = ubik_VL_SetLock(cstruct, 0, volid, RWVOL, VLOP_ADDSITE);
5189     if (vcode) {
5190         fprintf(STDERR, " Could not lock the VLDB entry for volume %lu \n",
5191                 (unsigned long)volid);
5192         PrintError("", vcode);
5193         return (vcode);
5194     }
5195     vcode = VLDB_GetEntryByID(volid, RWVOL, &entry);
5196     if (vcode) {
5197         fprintf(STDERR,
5198                 "Could not fetch the entry for volume number %lu from VLDB \n",
5199                 (unsigned long)volid);
5200         PrintError("", vcode);
5201         return (vcode);
5202     }
5203     MapHostToNetwork(&entry);
5204     index = Lp_GetRwIndex(&entry);
5205     if (index < 0) {
5206         /* no RW site exists  */
5207         fprintf(STDERR, "No existing RW site for volume %lu",
5208                 (unsigned long)volid);
5209         vcode =
5210             ubik_VL_ReleaseLock(cstruct, 0, volid, RWVOL,
5211                       LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
5212         if (vcode) {
5213             fprintf(STDERR,
5214                     "Could not release lock on entry for volume %lu \n",
5215                     (unsigned long)volid);
5216             PrintError("", vcode);
5217             return (vcode);
5218         }
5219         return VOLSERBADOP;
5220     } else {                    /* change the RW site */
5221         entry.serverNumber[index] = server;
5222         entry.serverPartition[index] = part;
5223         MapNetworkToHost(&entry, &storeEntry);
5224         vcode =
5225             VLDB_ReplaceEntry(volid, RWVOL, &storeEntry,
5226                               LOCKREL_OPCODE | LOCKREL_AFSID |
5227                               LOCKREL_TIMESTAMP);
5228         if (vcode) {
5229             fprintf(STDERR, "Could not update entry for volume %lu \n",
5230                     (unsigned long)volid);
5231             PrintError("", vcode);
5232             ubik_VL_ReleaseLock(cstruct, 0, volid, RWVOL,
5233                       LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
5234             return (vcode);
5235         }
5236         VDONE;
5237     }
5238     return 0;
5239 }
5240
5241 /*list all the partitions on <aserver> */
5242 int
5243 UV_ListPartitions(afs_uint32 aserver, struct partList *ptrPartList,
5244                   afs_int32 * cntp)
5245 {
5246     struct rx_connection *aconn;
5247     struct pIDs partIds;
5248     struct partEntries partEnts;
5249     int i, j = 0, code;
5250
5251     *cntp = 0;
5252     aconn = UV_Bind(aserver, AFSCONF_VOLUMEPORT);
5253
5254     partEnts.partEntries_len = 0;
5255     partEnts.partEntries_val = NULL;
5256     code = AFSVolXListPartitions(aconn, &partEnts);     /* this is available only on new servers */
5257     if (code == RXGEN_OPCODE) {
5258         for (i = 0; i < 26; i++)        /* try old interface */
5259             partIds.partIds[i] = -1;
5260         code = AFSVolListPartitions(aconn, &partIds);
5261         if (!code) {
5262             for (i = 0; i < 26; i++) {
5263                 if ((partIds.partIds[i]) != -1) {
5264                     ptrPartList->partId[j] = partIds.partIds[i];
5265                     ptrPartList->partFlags[j] = PARTVALID;
5266                     j++;
5267                 } else
5268                     ptrPartList->partFlags[i] = 0;
5269             }
5270             *cntp = j;
5271         }
5272     } else if (!code) {
5273         *cntp = partEnts.partEntries_len;
5274         if (*cntp > VOLMAXPARTS) {
5275             fprintf(STDERR,
5276                     "Warning: number of partitions on the server too high %d (process only %d)\n",
5277                     *cntp, VOLMAXPARTS);
5278             *cntp = VOLMAXPARTS;
5279         }
5280         for (i = 0; i < *cntp; i++) {
5281             ptrPartList->partId[i] = partEnts.partEntries_val[i];
5282             ptrPartList->partFlags[i] = PARTVALID;
5283         }
5284         free(partEnts.partEntries_val);
5285     }
5286
5287    /* out: */
5288     if (code)
5289         fprintf(STDERR,
5290                 "Could not fetch the list of partitions from the server\n");
5291     PrintError("", code);
5292     if (aconn)
5293         rx_DestroyConnection(aconn);
5294     return code;
5295 }
5296
5297
5298 /*zap the list of volumes specified by volPtrArray (the volCloneId field).
5299  This is used by the backup system */
5300 int
5301 UV_ZapVolumeClones(afs_uint32 aserver, afs_int32 apart,
5302                    struct volDescription *volPtr, afs_int32 arraySize)
5303 {
5304     struct rx_connection *aconn;
5305     struct volDescription *curPtr;
5306     int curPos;
5307     afs_int32 code = 0;
5308     afs_int32 success = 1;
5309
5310     aconn = UV_Bind(aserver, AFSCONF_VOLUMEPORT);
5311     curPos = 0;
5312     for (curPtr = volPtr; curPos < arraySize; curPtr++) {
5313         if (curPtr->volFlags & CLONEVALID) {
5314             curPtr->volFlags &= ~CLONEZAPPED;
5315             success = 1;
5316
5317             code = DoVolDelete(aconn, curPtr->volCloneId, apart,
5318                                "clone", 0, NULL, NULL);
5319             if (code)
5320                 success = 0;
5321
5322             if (success)
5323                 curPtr->volFlags |= CLONEZAPPED;
5324             if (!success)
5325                 fprintf(STDERR, "Could not zap volume %lu\n",
5326                         (unsigned long)curPtr->volCloneId);
5327             if (success)
5328                 VPRINT2("Clone of %s %u deleted\n", curPtr->volName,
5329                         curPtr->volCloneId);
5330             curPos++;
5331         }
5332     }
5333     if (aconn)
5334         rx_DestroyConnection(aconn);
5335     return 0;
5336 }
5337
5338 /*return a list of clones of the volumes specified by volPtrArray. Used by the
5339  backup system */
5340 int
5341 UV_GenerateVolumeClones(afs_uint32 aserver, afs_int32 apart,
5342                         struct volDescription *volPtr, afs_int32 arraySize)
5343 {
5344     struct rx_connection *aconn;
5345     struct volDescription *curPtr;
5346     int curPos;
5347     afs_int32 code = 0;
5348     afs_int32 rcode = 0;
5349     afs_int32 tid;
5350     int reuseCloneId = 0;
5351     afs_uint32 curCloneId = 0;
5352     char cloneName[256];        /*max vol name */
5353
5354     aconn = UV_Bind(aserver, AFSCONF_VOLUMEPORT);
5355     curPos = 0;
5356     if ((volPtr->volFlags & REUSECLONEID) && (volPtr->volFlags & ENTRYVALID))
5357         reuseCloneId = 1;
5358     else {                      /*get a bunch of id's from vldb */
5359         code =
5360             ubik_VL_GetNewVolumeId(cstruct, 0, arraySize, &curCloneId);
5361         if (code) {
5362             fprintf(STDERR, "Could not get ID's for the clone from VLDB\n");
5363             PrintError("", code);
5364             return code;
5365         }
5366     }
5367
5368     for (curPtr = volPtr; curPos < arraySize; curPtr++) {
5369         if (curPtr->volFlags & ENTRYVALID) {
5370
5371             curPtr->volFlags |= CLONEVALID;
5372             /*make a clone of curParentId and record as curPtr->volCloneId */
5373             code =
5374                 AFSVolTransCreate_retry(aconn, curPtr->volId, apart, ITOffline,
5375                                   &tid);
5376             if (code)
5377                 VPRINT2("Clone for volume %s %u failed \n", curPtr->volName,
5378                         curPtr->volId);
5379             if (code) {
5380                 curPtr->volFlags &= ~CLONEVALID;        /*cant clone */
5381                 curPos++;
5382                 continue;
5383             }
5384             if (strlen(curPtr->volName) < (VOLSER_OLDMAXVOLNAME - 9)) {
5385                 strcpy(cloneName, curPtr->volName);
5386                 strcat(cloneName, "-tmpClone-");
5387             } else
5388                 strcpy(cloneName, "-tmpClone");
5389             if (reuseCloneId) {
5390                 curPtr->volCloneId = curCloneId;
5391                 curCloneId++;
5392             }
5393
5394             code =
5395                 AFSVolClone(aconn, tid, 0, readonlyVolume, cloneName,
5396                             &(curPtr->volCloneId));
5397             if (code) {
5398                 curPtr->volFlags &= ~CLONEVALID;
5399                 curPos++;
5400                 fprintf(STDERR, "Could not clone %s due to error %lu\n",
5401                         curPtr->volName, (unsigned long)code);
5402                 code = AFSVolEndTrans(aconn, tid, &rcode);
5403                 if (code)
5404                     fprintf(STDERR, "WARNING: could not end transaction\n");
5405                 continue;
5406             }
5407             VPRINT2("********** Cloned %s temporary %u\n", cloneName,
5408                     curPtr->volCloneId);
5409             code = AFSVolEndTrans(aconn, tid, &rcode);
5410             if (code || rcode) {
5411                 curPtr->volFlags &= ~CLONEVALID;
5412                 curPos++;
5413                 continue;
5414             }
5415
5416             curPos++;
5417         }
5418     }
5419     if (aconn)
5420         rx_DestroyConnection(aconn);
5421     return 0;
5422 }
5423
5424
5425 /*list all the volumes on <aserver> and <apart>. If all = 1, then all the
5426 * relevant fields of the volume are also returned. This is a heavy weight operation.*/
5427 int
5428 UV_ListVolumes(afs_uint32 aserver, afs_int32 apart, int all,
5429                struct volintInfo **resultPtr, afs_int32 * size)
5430 {
5431     struct rx_connection *aconn;
5432     afs_int32 code = 0;
5433     volEntries volumeInfo;
5434
5435     *size = 0;
5436     *resultPtr = (volintInfo *) 0;
5437     volumeInfo.volEntries_val = (volintInfo *) 0;       /*this hints the stub to allocate space */
5438     volumeInfo.volEntries_len = 0;
5439
5440     aconn = UV_Bind(aserver, AFSCONF_VOLUMEPORT);
5441     code = AFSVolListVolumes(aconn, apart, all, &volumeInfo);
5442     if (code) {
5443         fprintf(STDERR,
5444                 "Could not fetch the list of volumes from the server\n");
5445     } else {
5446         *resultPtr = volumeInfo.volEntries_val;
5447         *size = volumeInfo.volEntries_len;
5448     }
5449
5450     if (aconn)
5451         rx_DestroyConnection(aconn);
5452     PrintError("", code);
5453     return code;
5454 }
5455
5456 /*------------------------------------------------------------------------
5457  * EXPORTED UV_XListVolumes
5458  *
5459  * Description:
5460  *      List the extended information for all the volumes on a particular
5461  *      File Server and partition.  We may either return the volume's ID
5462  *      or all of its extended information.
5463  *
5464  * Arguments:
5465  *      a_serverID         : Address of the File Server for which we want
5466  *                              extended volume info.
5467  *      a_partID           : Partition for which we want the extended
5468  *                              volume info.
5469  *      a_all              : If non-zero, fetch ALL the volume info,
5470  *                              otherwise just the volume ID.
5471  *      a_resultPP         : Ptr to the address of the area containing
5472  *                              the returned volume info.
5473  *      a_numEntsInResultP : Ptr for the value we set for the number of
5474  *                              entries returned.
5475  *
5476  * Returns:
5477  *      0 on success,
5478  *      Otherise, the return value of AFSVolXListVolumes.
5479  *
5480  * Environment:
5481  *      This routine is closely related to UV_ListVolumes, which returns
5482  *      only the standard level of detail on AFS volumes. It is a
5483  *      heavyweight operation, zipping through all the volume entries for
5484  *      a given server/partition.
5485  *
5486  * Side Effects:
5487  *      As advertised.
5488  *------------------------------------------------------------------------*/
5489
5490 int
5491 UV_XListVolumes(afs_uint32 a_serverID, afs_int32 a_partID, int a_all,
5492                 struct volintXInfo **a_resultPP,
5493                 afs_int32 * a_numEntsInResultP)
5494 {
5495     struct rx_connection *rxConnP;      /*Ptr to the Rx connection involved */
5496     afs_int32 code;             /*Error code to return */
5497     volXEntries volumeXInfo;    /*Area for returned extended vol info */
5498
5499     /*
5500      * Set up our error code and the area for returned extended volume info.
5501      * We set the val field to a null pointer as a hint for the stub to
5502      * allocate space.
5503      */
5504     *a_numEntsInResultP = 0;
5505     *a_resultPP = (volintXInfo *) 0;
5506     volumeXInfo.volXEntries_val = (volintXInfo *) 0;
5507     volumeXInfo.volXEntries_len = 0;
5508
5509     /*
5510      * Bind to the Volume Server port on the File Server machine in question,
5511      * then go for it.
5512      */
5513     rxConnP = UV_Bind(a_serverID, AFSCONF_VOLUMEPORT);
5514     code = AFSVolXListVolumes(rxConnP, a_partID, a_all, &volumeXInfo);
5515     if (code)
5516         fprintf(STDERR, "[UV_XListVolumes] Couldn't fetch volume list\n");
5517     else {
5518         /*
5519          * We got the info; pull out the pointer to where the results lie
5520          * and how many entries are there.
5521          */
5522         *a_resultPP = volumeXInfo.volXEntries_val;
5523         *a_numEntsInResultP = volumeXInfo.volXEntries_len;
5524     }
5525
5526     /*
5527      * If we got an Rx connection, throw it away.
5528      */
5529     if (rxConnP)
5530         rx_DestroyConnection(rxConnP);
5531
5532     PrintError("", code);
5533     return (code);
5534 }                               /*UV_XListVolumes */
5535
5536 /* get all the information about volume <volid> on <aserver> and <apart> */
5537 int
5538 UV_ListOneVolume(afs_uint32 aserver, afs_int32 apart, afs_uint32 volid,
5539                  struct volintInfo **resultPtr)
5540 {
5541     struct rx_connection *aconn;
5542     afs_int32 code = 0;
5543     volEntries volumeInfo;
5544
5545     *resultPtr = (volintInfo *) 0;
5546     volumeInfo.volEntries_val = (volintInfo *) 0;       /*this hints the stub to allocate space */
5547     volumeInfo.volEntries_len = 0;
5548
5549     aconn = UV_Bind(aserver, AFSCONF_VOLUMEPORT);
5550     code = AFSVolListOneVolume(aconn, apart, volid, &volumeInfo);
5551     if (code) {
5552         fprintf(STDERR,
5553                 "Could not fetch the information about volume %lu from the server\n",
5554                 (unsigned long)volid);
5555     } else {
5556         *resultPtr = volumeInfo.volEntries_val;
5557
5558     }
5559
5560     if (aconn)
5561         rx_DestroyConnection(aconn);
5562     PrintError("", code);
5563     return code;
5564 }
5565
5566 /*------------------------------------------------------------------------
5567  * EXPORTED UV_XListOneVolume
5568  *
5569  * Description:
5570  *      List the extended information for a volume on a particular File
5571  *      Server and partition.
5572  *
5573  * Arguments:
5574  *      a_serverID         : Address of the File Server for which we want
5575  *                              extended volume info.
5576  *      a_partID           : Partition for which we want the extended
5577  *                              volume info.
5578  *      a_volID            : Volume ID for which we want the info.
5579  *      a_resultPP         : Ptr to the address of the area containing
5580  *                              the returned volume info.
5581  *
5582  * Returns:
5583  *      0 on success,
5584  *      Otherise, the return value of AFSVolXListOneVolume.
5585  *
5586  * Environment:
5587  *      This routine is closely related to UV_ListOneVolume, which returns
5588  *      only the standard level of detail on the chosen AFS volume.
5589  *
5590  * Side Effects:
5591  *      As advertised.
5592  *------------------------------------------------------------------------*/
5593
5594 int
5595 UV_XListOneVolume(afs_uint32 a_serverID, afs_int32 a_partID, afs_uint32 a_volID,
5596                   struct volintXInfo **a_resultPP)
5597 {
5598     struct rx_connection *rxConnP;      /*Rx connection to Volume Server */
5599     afs_int32 code;             /*Error code */
5600     volXEntries volumeXInfo;    /*Area for returned info */
5601
5602     /*
5603      * Set up our error code, and the area we're in which we are returning
5604      * the info.  Setting the val field to a null pointer tells the stub
5605      * to allocate space for us.
5606      */
5607     *a_resultPP = (volintXInfo *) 0;
5608     volumeXInfo.volXEntries_val = (volintXInfo *) 0;
5609     volumeXInfo.volXEntries_len = 0;
5610
5611     /*
5612      * Bind to the Volume Server port on the File Server machine in question,
5613      * then go for it.
5614      */
5615     rxConnP = UV_Bind(a_serverID, AFSCONF_VOLUMEPORT);
5616     code = AFSVolXListOneVolume(rxConnP, a_partID, a_volID, &volumeXInfo);
5617     if (code)
5618         fprintf(STDERR,
5619                 "[UV_XListOneVolume] Couldn't fetch the volume information\n");
5620     else
5621         /*
5622          * We got the info; pull out the pointer to where the results lie.
5623          */
5624         *a_resultPP = volumeXInfo.volXEntries_val;
5625
5626     /*
5627      * If we got an Rx connection, throw it away.
5628      */
5629     if (rxConnP)
5630         rx_DestroyConnection(rxConnP);
5631
5632     PrintError("", code);
5633     return code;
5634 }
5635
5636 /* CheckVolume()
5637  *    Given a volume we read from a partition, check if it is
5638  *    represented in the VLDB correctly.
5639  *
5640  *    The VLDB is looked up by the RW volume id (not its name).
5641  *    The RW contains the true name of the volume (BK and RO set
5642  *       the name in the VLDB only on creation of the VLDB entry).
5643  *    We want rules strict enough that when we check all volumes
5644  *       on one partition, it does not need to be done again. IE:
5645  *       two volumes on different partitions won't constantly
5646  *       change a VLDB entry away from what the other set.
5647  *    For RW and BK volumes, we will always check the VLDB to see
5648  *       if the two exist on the server/partition. May seem redundant,
5649  *       but this is an easy check of the VLDB. IE: if the VLDB entry
5650  *       says the BK exists but no BK volume is there, we will detect
5651  *       this when we check the RW volume.
5652  *    VLDB entries are locked only when a change needs to be done.
5653  *    Output changed to look a lot like the "vos syncserv" otuput.
5654  */
5655 static afs_int32
5656 CheckVolume(volintInfo * volumeinfo, afs_uint32 aserver, afs_int32 apart,
5657             afs_int32 * modentry, afs_uint32 * maxvolid,
5658             struct nvldbentry *aentry)
5659 {
5660     int idx = 0;
5661     int j;
5662     afs_int32 code, error = 0;
5663     struct nvldbentry entry, storeEntry;
5664     char pname[10];
5665     int pass = 0, createentry, addvolume, modified, mod, doit = 1;
5666     afs_uint32 rwvolid;
5667     char hoststr[16];
5668
5669     if (modentry) {
5670         if (*modentry == 1)
5671             doit = 0;
5672         *modentry = 0;
5673     }
5674     rwvolid =
5675         ((volumeinfo->type ==
5676           RWVOL) ? volumeinfo->volid : volumeinfo->parentID);
5677
5678   retry:
5679     /* Check to see if the VLDB is ok without locking it (pass 1).
5680      * If it will change, then lock the VLDB entry, read it again,
5681      * then make the changes to it (pass 2).
5682      */
5683     if (++pass == 2) {
5684         code = ubik_VL_SetLock(cstruct, 0, rwvolid, RWVOL, VLOP_DELETE);
5685         if (code) {
5686             fprintf(STDERR, "Could not lock VLDB entry for %lu\n",
5687                     (unsigned long)rwvolid);
5688             ERROR_EXIT(code);
5689         }
5690     }
5691
5692     createentry = 0;            /* Do we need to create a VLDB entry */
5693     addvolume = 0;              /* Add this volume to the VLDB entry */
5694     modified = 0;               /* The VLDB entry was modified */
5695
5696     if (aentry) {
5697         memcpy(&entry, aentry, sizeof(entry));
5698     } else {
5699         /* Read the entry from VLDB by its RW volume id */
5700         code = VLDB_GetEntryByID(rwvolid, RWVOL, &entry);
5701         if (code) {
5702             if (code != VL_NOENT) {
5703                 fprintf(STDOUT,
5704                         "Could not retrieve the VLDB entry for volume %lu \n",
5705                         (unsigned long)rwvolid);
5706                 ERROR_EXIT(code);
5707             }
5708
5709             memset(&entry, 0, sizeof(entry));
5710             vsu_ExtractName(entry.name, volumeinfo->name);      /* Store name of RW */
5711
5712             createentry = 1;
5713         } else {
5714             MapHostToNetwork(&entry);
5715         }
5716     }
5717
5718     if (verbose && (pass == 1)) {
5719         fprintf(STDOUT, "_______________________________\n");
5720         fprintf(STDOUT, "\n-- status before -- \n");
5721         if (createentry) {
5722             fprintf(STDOUT, "\n**does not exist**\n");
5723         } else {
5724             if ((entry.flags & VLF_RWEXISTS) || (entry.flags & VLF_ROEXISTS)
5725                 || (entry.flags & VLF_BACKEXISTS))
5726                 EnumerateEntry(&entry);
5727         }
5728         fprintf(STDOUT, "\n");
5729     }
5730
5731     if (volumeinfo->type == RWVOL) {    /* RW volume exists */
5732         if (createentry) {
5733             idx = 0;
5734             entry.nServers = 1;
5735             addvolume++;
5736         } else {
5737             /* Check existence of RW and BK volumes */
5738             code = CheckVldbRWBK(&entry, &mod);
5739             if (code)
5740                 ERROR_EXIT(code);
5741             if (mod)
5742                 modified++;
5743
5744             idx = Lp_GetRwIndex(&entry);
5745             if (idx == -1) {    /* RW index not found in the VLDB entry */
5746                 idx = entry.nServers;   /* put it into next index */
5747                 entry.nServers++;
5748                 addvolume++;
5749             } else {            /* RW index found in the VLDB entry. */
5750                 /* Verify if this volume's location matches where the VLDB says it is */
5751                 if (!Lp_Match(aserver, apart, &entry)) {
5752                     if (entry.flags & VLF_RWEXISTS) {
5753                         /* The RW volume exists elsewhere - report this one a duplicate */
5754                         if (pass == 1) {
5755                             MapPartIdIntoName(apart, pname);
5756                             fprintf(STDERR,
5757                                     "*** Warning: Orphaned RW volume %lu exists on %s %s\n",
5758                                     (unsigned long)rwvolid,
5759                                     noresolve ?
5760                                     afs_inet_ntoa_r(aserver, hoststr) :
5761                                     hostutil_GetNameByINet(aserver), pname);
5762                             MapPartIdIntoName(entry.serverPartition[idx],
5763                                               pname);
5764                             fprintf(STDERR,
5765                                     "    VLDB reports RW volume %lu exists on %s %s\n",
5766                                     (unsigned long)rwvolid,
5767                                     noresolve ?
5768                                     afs_inet_ntoa_r(entry.serverNumber[idx], hoststr) :
5769                                     hostutil_GetNameByINet(entry.
5770                                                            serverNumber[idx]),
5771                                     pname);
5772                         }
5773                     } else {
5774                         /* The RW volume does not exist - have VLDB point to this one */
5775                         addvolume++;
5776
5777                         /* Check for orphaned BK volume on old partition */
5778                         if (entry.flags & VLF_BACKEXISTS) {
5779                             if (pass == 1) {
5780                                 MapPartIdIntoName(entry.serverPartition[idx],
5781                                                   pname);
5782                                 fprintf(STDERR,
5783                                         "*** Warning: Orphaned BK volume %u exists on %s %s\n",
5784                                         entry.volumeId[BACKVOL],
5785                                         noresolve ?
5786                                         afs_inet_ntoa_r(entry.serverNumber[idx], hoststr) :
5787                                         hostutil_GetNameByINet(entry.
5788                                                                serverNumber
5789                                                                [idx]), pname);
5790                                 MapPartIdIntoName(apart, pname);
5791                                 fprintf(STDERR,
5792                                         "    VLDB reports its RW volume %lu exists on %s %s\n",
5793                                         (unsigned long)rwvolid,
5794                                         noresolve ?
5795                                         afs_inet_ntoa_r(aserver, hoststr) :
5796                                         hostutil_GetNameByINet(aserver),
5797                                         pname);
5798                             }
5799                         }
5800                     }
5801                 } else {
5802                     /* Volume location matches the VLDB location */
5803                     if ((volumeinfo->backupID && !entry.volumeId[BACKVOL])
5804                         || (volumeinfo->cloneID && !entry.volumeId[ROVOL])
5805                         ||
5806                         (strncmp
5807                          (entry.name, volumeinfo->name,
5808                           VOLSER_OLDMAXVOLNAME) != 0)) {
5809                         addvolume++;
5810                     }
5811                 }
5812             }
5813         }
5814
5815         if (addvolume) {
5816             entry.flags |= VLF_RWEXISTS;
5817             entry.volumeId[RWVOL] = rwvolid;
5818             if (!entry.volumeId[BACKVOL])
5819                 entry.volumeId[BACKVOL] = volumeinfo->backupID;
5820             if (!entry.volumeId[ROVOL])
5821                 entry.volumeId[ROVOL] = volumeinfo->cloneID;
5822
5823             entry.serverFlags[idx] = VLSF_RWVOL;
5824             entry.serverNumber[idx] = aserver;
5825             entry.serverPartition[idx] = apart;
5826             strncpy(entry.name, volumeinfo->name, VOLSER_OLDMAXVOLNAME);
5827
5828             modified++;
5829
5830             /* One last check - to update BK if need to */
5831             code = CheckVldbRWBK(&entry, &mod);
5832             if (code)
5833                 ERROR_EXIT(code);
5834             if (mod)
5835                 modified++;
5836         }
5837     }
5838
5839     else if (volumeinfo->type == BACKVOL) {     /* A BK volume */
5840         if (createentry) {
5841             idx = 0;
5842             entry.nServers = 1;
5843             addvolume++;
5844         } else {
5845             /* Check existence of RW and BK volumes */
5846             code = CheckVldbRWBK(&entry, &mod);
5847             if (code)
5848                 ERROR_EXIT(code);
5849             if (mod)
5850                 modified++;
5851
5852             idx = Lp_GetRwIndex(&entry);
5853             if (idx == -1) {    /* RW index not found in the VLDB entry */
5854                 idx = entry.nServers;   /* Put it into next index */
5855                 entry.nServers++;
5856                 addvolume++;
5857             } else {            /* RW index found in the VLDB entry */
5858                 /* Verify if this volume's location matches where the VLDB says it is */
5859                 if (!Lp_Match(aserver, apart, &entry)) {
5860                     /* VLDB says RW and/or BK is elsewhere - report this BK volume orphaned */
5861                     if (pass == 1) {
5862                         MapPartIdIntoName(apart, pname);
5863                         fprintf(STDERR,
5864                                 "*** Warning: Orphaned BK volume %lu exists on %s %s\n",
5865                                 (unsigned long)volumeinfo->volid,
5866                                 noresolve ?
5867                                 afs_inet_ntoa_r(aserver, hoststr) :
5868                                 hostutil_GetNameByINet(aserver), pname);
5869                         MapPartIdIntoName(entry.serverPartition[idx], pname);
5870                         fprintf(STDERR,
5871                                 "    VLDB reports its RW/BK volume %lu exists on %s %s\n",
5872                                 (unsigned long)rwvolid,
5873                                 noresolve ?
5874                                 afs_inet_ntoa_r(entry.serverNumber[idx], hoststr) :
5875                                 hostutil_GetNameByINet(entry.
5876                                                        serverNumber[idx]),
5877                                 pname);
5878                     }
5879                 } else {
5880                     if (volumeinfo->volid != entry.volumeId[BACKVOL]) {
5881                         if (!(entry.flags & VLF_BACKEXISTS)) {
5882                             addvolume++;
5883                         } else if (volumeinfo->volid >
5884                                    entry.volumeId[BACKVOL]) {
5885                             addvolume++;
5886
5887                             if (pass == 1) {
5888                                 MapPartIdIntoName(entry.serverPartition[idx],
5889                                                   pname);
5890                                 fprintf(STDERR,
5891                                         "*** Warning: Orphaned BK volume %u exists on %s %s\n",
5892                                         entry.volumeId[BACKVOL],
5893                                         noresolve ?
5894                                         afs_inet_ntoa_r(aserver, hoststr) :
5895                                         hostutil_GetNameByINet(aserver),
5896                                         pname);
5897                                 fprintf(STDERR,
5898                                         "    VLDB reports its BK volume ID is %lu\n",
5899                                         (unsigned long)volumeinfo->volid);
5900                             }
5901                         } else {
5902                             if (pass == 1) {
5903                                 MapPartIdIntoName(entry.serverPartition[idx],
5904                                                   pname);
5905                                 fprintf(STDERR,
5906                                         "*** Warning: Orphaned BK volume %lu exists on %s %s\n",
5907                                         (unsigned long)volumeinfo->volid,
5908                                         noresolve ?
5909                                         afs_inet_ntoa_r(aserver, hoststr) :
5910                                         hostutil_GetNameByINet(aserver),
5911                                         pname);
5912                                 fprintf(STDERR,
5913                                         "    VLDB reports its BK volume ID is %u\n",
5914                                         entry.volumeId[BACKVOL]);
5915                             }
5916                         }
5917                     } else if (!entry.volumeId[BACKVOL]) {
5918                         addvolume++;
5919                     }
5920                 }
5921             }
5922         }
5923         if (addvolume) {
5924             entry.flags |= VLF_BACKEXISTS;
5925             entry.volumeId[RWVOL] = rwvolid;
5926             entry.volumeId[BACKVOL] = volumeinfo->volid;
5927
5928             entry.serverNumber[idx] = aserver;
5929             entry.serverPartition[idx] = apart;
5930             entry.serverFlags[idx] = VLSF_RWVOL;
5931
5932             modified++;
5933         }
5934     }
5935
5936     else if (volumeinfo->type == ROVOL) {       /* A RO volume */
5937         if (volumeinfo->volid == entry.volumeId[ROVOL]) {
5938             /* This is a quick check to see if the RO entry exists in the
5939              * VLDB so we avoid the CheckVldbRO() call (which checks if each
5940              * RO volume listed in the VLDB exists).
5941              */
5942             idx = Lp_ROMatch(aserver, apart, &entry) - 1;
5943             if (idx == -1) {
5944                 idx = entry.nServers;
5945                 entry.nServers++;
5946                 addvolume++;
5947             } else {
5948                 if (!(entry.flags & VLF_ROEXISTS)) {
5949                     addvolume++;
5950                 }
5951             }
5952         } else {
5953             /* Before we correct the VLDB entry, make sure all the
5954              * ROs listed in the VLDB exist.
5955              */
5956             code = CheckVldbRO(&entry, &mod);
5957             if (code)
5958                 ERROR_EXIT(code);
5959             if (mod)
5960                 modified++;
5961
5962             if (!(entry.flags & VLF_ROEXISTS)) {
5963                 /* No RO exists in the VLDB entry - add this one */
5964                 idx = entry.nServers;
5965                 entry.nServers++;
5966                 addvolume++;
5967             } else if (volumeinfo->volid > entry.volumeId[ROVOL]) {
5968                 /* The volume headers's RO ID does not match that in the VLDB entry,
5969                  * and the vol hdr's ID is greater (implies more recent). So delete
5970                  * all the RO volumes listed in VLDB entry and add this volume.
5971                  */
5972                 for (j = 0; j < entry.nServers; j++) {
5973                     if (entry.serverFlags[j] & VLSF_ROVOL) {
5974                         /* Verify this volume exists and print message we are orphaning it */
5975                         if (pass == 1) {
5976                             MapPartIdIntoName(apart, pname);
5977                             fprintf(STDERR,
5978                                     "*** Warning: Orphaned RO volume %u exists on %s %s\n",
5979                                     entry.volumeId[ROVOL],
5980                                     noresolve ?
5981                                     afs_inet_ntoa_r(entry.serverNumber[j], hoststr) :
5982                                     hostutil_GetNameByINet(entry.
5983                                                            serverNumber[j]),
5984                                     pname);
5985                             fprintf(STDERR,
5986                                     "    VLDB reports its RO volume ID is %lu\n",
5987                                     (unsigned long)volumeinfo->volid);
5988                         }
5989
5990                         Lp_SetRWValue(&entry, entry.serverNumber[idx],
5991                                       entry.serverPartition[idx], 0L, 0L);
5992                         entry.nServers--;
5993                         modified++;
5994                         j--;
5995                     }
5996                 }
5997
5998                 idx = entry.nServers;
5999                 entry.nServers++;
6000                 addvolume++;
6001             } else if (volumeinfo->volid < entry.volumeId[ROVOL]) {
6002                 /* The volume headers's RO ID does not match that in the VLDB entry,
6003                  * and the vol hdr's ID is lower (implies its older). So orphan it.
6004                  */
6005                 if (pass == 1) {
6006                     MapPartIdIntoName(apart, pname);
6007                     fprintf(STDERR,
6008                             "*** Warning: Orphaned RO volume %lu exists on %s %s\n",
6009                             (unsigned long)volumeinfo->volid,
6010                             noresolve ?
6011                             afs_inet_ntoa_r(aserver, hoststr) :
6012                             hostutil_GetNameByINet(aserver), pname);
6013                     fprintf(STDERR,
6014                             "    VLDB reports its RO volume ID is %u\n",
6015                             entry.volumeId[ROVOL]);
6016                 }
6017             } else {
6018                 /* The RO volume ID in the volume header match that in the VLDB entry,
6019                  * and there exist RO volumes in the VLDB entry. See if any of them
6020                  * are this one. If not, then we add it.
6021                  */
6022                 idx = Lp_ROMatch(aserver, apart, &entry) - 1;
6023                 if (idx == -1) {
6024                     idx = entry.nServers;
6025                     entry.nServers++;
6026                     addvolume++;
6027                 }
6028             }
6029         }
6030
6031         if (addvolume) {
6032             entry.flags |= VLF_ROEXISTS;
6033             entry.volumeId[RWVOL] = rwvolid;
6034             entry.volumeId[ROVOL] = volumeinfo->volid;
6035
6036             entry.serverNumber[idx] = aserver;
6037             entry.serverPartition[idx] = apart;
6038             entry.serverFlags[idx] = VLSF_ROVOL;
6039
6040             modified++;
6041         }
6042     }
6043
6044     /* Remember largest volume id */
6045     if (entry.volumeId[ROVOL] > *maxvolid)
6046         *maxvolid = entry.volumeId[ROVOL];
6047     if (entry.volumeId[BACKVOL] > *maxvolid)
6048         *maxvolid = entry.volumeId[BACKVOL];
6049     if (entry.volumeId[RWVOL] > *maxvolid)
6050         *maxvolid = entry.volumeId[RWVOL];
6051
6052     if (modified && doit) {
6053         MapNetworkToHost(&entry, &storeEntry);
6054
6055         if (createentry) {
6056             code = VLDB_CreateEntry(&storeEntry);
6057             if (code) {
6058                 fprintf(STDOUT,
6059                         "Could not create a VLDB entry for the volume %lu\n",
6060                         (unsigned long)rwvolid);
6061                 ERROR_EXIT(code);
6062             }
6063         } else {
6064             if (pass == 1)
6065                 goto retry;
6066             code =
6067                 VLDB_ReplaceEntry(rwvolid, RWVOL, &storeEntry,
6068                                   LOCKREL_OPCODE | LOCKREL_AFSID |
6069                                   LOCKREL_TIMESTAMP);
6070             if (code) {
6071                 fprintf(STDERR, "Could not update entry for %lu\n",
6072                         (unsigned long)rwvolid);
6073                 ERROR_EXIT(code);
6074             }
6075         }
6076     } else if (pass == 2) {
6077         code =
6078             ubik_VL_ReleaseLock(cstruct, 0, rwvolid, RWVOL,
6079                       LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
6080         if (code) {
6081             PrintError("Could not unlock VLDB entry ", code);
6082         }
6083     }
6084
6085     if (modified && modentry) {
6086         *modentry = 1;
6087     }
6088
6089     if (aentry) {
6090         memcpy(aentry, &entry, sizeof(entry));
6091     }
6092
6093     if (verbose) {
6094         fprintf(STDOUT, "-- status after --\n");
6095         if (modified)
6096             EnumerateEntry(&entry);
6097         else
6098             fprintf(STDOUT, "\n**no change**\n");
6099     }
6100
6101   error_exit:
6102     VPRINT("\n_______________________________\n");
6103     return (error);
6104 }
6105
6106 static int
6107 sortVolumes(const void *a, const void *b)
6108 {
6109     volintInfo *v1 = (volintInfo *) a;
6110     volintInfo *v2 = (volintInfo *) b;
6111     afs_uint32 rwvolid1, rwvolid2;
6112
6113     rwvolid1 = ((v1->type == RWVOL) ? v1->volid : v1->parentID);
6114     rwvolid2 = ((v2->type == RWVOL) ? v2->volid : v2->parentID);
6115
6116     if (rwvolid1 > rwvolid2)
6117         return -1;              /* lower RW id goes first */
6118     if (rwvolid1 < rwvolid2)
6119         return 1;
6120
6121     if (v1->type == RWVOL)
6122         return -1;              /* RW vols go first */
6123     if (v2->type == RWVOL)
6124         return 1;
6125
6126     if ((v1->type == BACKVOL) && (v2->type == ROVOL))
6127         return -1;              /* BK vols next */
6128     if ((v1->type == ROVOL) && (v2->type == BACKVOL))
6129         return 1;
6130
6131     if (v1->volid < v2->volid)
6132         return 1;               /* larger volids first */
6133     if (v1->volid > v2->volid)
6134         return -1;
6135     return 0;
6136 }
6137
6138 /* UV_SyncVolume()
6139  *      Synchronise <aserver> <apart>(if flags = 1) <avolid>.
6140  *      Synchronize an individual volume against a sever and partition.
6141  *      Checks the VLDB entry (similar to syncserv) as well as checks
6142  *      if the volume exists on specified servers (similar to syncvldb).
6143  */
6144 int
6145 UV_SyncVolume(afs_uint32 aserver, afs_int32 apart, char *avolname, int flags)
6146 {
6147     struct rx_connection *aconn = 0;
6148     afs_int32 j, k, code, vcode, error = 0;
6149     afs_int32 tverbose;
6150     afs_int32 mod, modified = 0, deleted = 0;
6151     struct nvldbentry vldbentry;
6152     afs_uint32 volumeid = 0;
6153     volEntries volumeInfo;
6154     struct partList PartList;
6155     afs_int32 pcnt;
6156     afs_uint32 maxvolid = 0;
6157
6158     volumeInfo.volEntries_val = (volintInfo *) 0;
6159     volumeInfo.volEntries_len = 0;
6160
6161     /* Turn verbose logging off and do our own verbose logging */
6162     /* tverbose must be set before we call ERROR_EXIT() */
6163
6164     tverbose = verbose;
6165     if (flags & 2)
6166         tverbose = 1;
6167     verbose = 0;
6168
6169     if (!aserver && (flags & 1)) {
6170         /* fprintf(STDERR,"Partition option requires a server option\n"); */
6171         ERROR_EXIT(EINVAL);
6172     }
6173
6174     /* Read the VLDB entry */
6175     vcode = VLDB_GetEntryByName(avolname, &vldbentry);
6176     if (vcode && (vcode != VL_NOENT)) {
6177         fprintf(STDERR, "Could not access the VLDB for volume %s\n",
6178                 avolname);
6179         ERROR_EXIT(vcode);
6180     } else if (!vcode) {
6181         MapHostToNetwork(&vldbentry);
6182     }
6183
6184     if (tverbose) {
6185         fprintf(STDOUT, "Processing VLDB entry %s ...\n", avolname);
6186         fprintf(STDOUT, "_______________________________\n");
6187         fprintf(STDOUT, "\n-- status before -- \n");
6188         if (vcode) {
6189             fprintf(STDOUT, "\n**does not exist**\n");
6190         } else {
6191             if ((vldbentry.flags & VLF_RWEXISTS) || (vldbentry.flags & VLF_ROEXISTS)
6192                 || (vldbentry.flags & VLF_BACKEXISTS))
6193                 EnumerateEntry(&vldbentry);
6194         }
6195         fprintf(STDOUT, "\n");
6196     }
6197
6198     /* Verify that all of the VLDB entries exist on the repective servers
6199      * and partitions (this does not require that avolname be a volume ID).
6200      * Equivalent to a syncserv.
6201      */
6202     if (!vcode) {
6203         /* Tell CheckVldb not to update if appropriate */
6204         if (flags & 2)
6205             mod = 1;
6206         else
6207             mod = 0;
6208         code = CheckVldb(&vldbentry, &mod, &deleted);
6209         if (code) {
6210             fprintf(STDERR, "Could not process VLDB entry for volume %s\n",
6211                     vldbentry.name);
6212             ERROR_EXIT(code);
6213         }
6214         if (mod)
6215             modified++;
6216     }
6217
6218     /* If aserver is given, we will search for the desired volume on it */
6219     if (aserver) {
6220         /* Generate array of partitions on the server that we will check */
6221         if (!(flags & 1)) {
6222             code = UV_ListPartitions(aserver, &PartList, &pcnt);
6223             if (code) {
6224                 fprintf(STDERR,
6225                         "Could not fetch the list of partitions from the server\n");
6226                 ERROR_EXIT(code);
6227             }
6228         } else {
6229             PartList.partId[0] = apart;
6230             pcnt = 1;
6231         }
6232
6233         aconn = UV_Bind(aserver, AFSCONF_VOLUMEPORT);
6234
6235         /* If a volume ID were given, search for it on each partition */
6236         if ((volumeid = atol(avolname))) {
6237             for (j = 0; j < pcnt; j++) {
6238                 code =
6239                     AFSVolListOneVolume(aconn, PartList.partId[j], volumeid,
6240                                         &volumeInfo);
6241                 if (code) {
6242                     if (code != ENODEV) {
6243                         fprintf(STDERR, "Could not query server\n");
6244                         ERROR_EXIT(code);
6245                     }
6246                 } else {
6247                     if (flags & 2)
6248                         mod = 1;
6249                     else
6250                         mod = 0;
6251                     /* Found one, sync it with VLDB entry */
6252                     code =
6253                         CheckVolume(volumeInfo.volEntries_val, aserver,
6254                                     PartList.partId[j], &mod, &maxvolid, &vldbentry);
6255                     if (code)
6256                         ERROR_EXIT(code);
6257                     if (mod)
6258                         modified++;
6259                 }
6260
6261                 if (volumeInfo.volEntries_val)
6262                     free(volumeInfo.volEntries_val);
6263                 volumeInfo.volEntries_val = (volintInfo *) 0;
6264                 volumeInfo.volEntries_len = 0;
6265             }
6266         }
6267
6268         /* Check to see if the RW, BK, and RO IDs exist on any
6269          * partitions. We get the volume IDs from the VLDB.
6270          */
6271         for (j = 0; j < MAXTYPES; j++) {        /* for RW, RO, and BK IDs */
6272             if (vldbentry.volumeId[j] == 0)
6273                 continue;
6274
6275             for (k = 0; k < pcnt; k++) {        /* For each partition */
6276                 volumeInfo.volEntries_val = (volintInfo *) 0;
6277                 volumeInfo.volEntries_len = 0;
6278                 code =
6279                     AFSVolListOneVolume(aconn, PartList.partId[k],
6280                                         vldbentry.volumeId[j], &volumeInfo);
6281                 if (code) {
6282                     if (code != ENODEV) {
6283                         fprintf(STDERR, "Could not query server\n");
6284                         ERROR_EXIT(code);
6285                     }
6286                 } else {
6287                     if (flags & 2)
6288                         mod = 1;
6289                     else
6290                         mod = 0;
6291                     /* Found one, sync it with VLDB entry */
6292                     code =
6293                         CheckVolume(volumeInfo.volEntries_val, aserver,
6294                                     PartList.partId[k], &mod, &maxvolid, &vldbentry);
6295                     if (code)
6296                         ERROR_EXIT(code);
6297                     if (mod)
6298                         modified++;
6299                 }
6300
6301                 if (volumeInfo.volEntries_val)
6302                     free(volumeInfo.volEntries_val);
6303                 volumeInfo.volEntries_val = (volintInfo *) 0;
6304                 volumeInfo.volEntries_len = 0;
6305             }
6306         }
6307     }
6308
6309     /* if (aserver) */
6310     /* If verbose output, print a summary of what changed */
6311     if (tverbose) {
6312         fprintf(STDOUT, "-- status after --\n");
6313         if (deleted) {
6314             fprintf(STDOUT, "\n**entry deleted**\n");
6315         } else if (modified) {
6316             EnumerateEntry(&vldbentry);
6317         } else {
6318             fprintf(STDOUT, "\n**no change**\n");
6319         }
6320         fprintf(STDOUT, "\n_______________________________\n");
6321     }
6322
6323   error_exit:
6324     /* Now check if the maxvolid is larger than that stored in the VLDB */
6325     if (maxvolid) {
6326         afs_uint32 maxvldbid = 0;
6327         code = ubik_VL_GetNewVolumeId(cstruct, 0, 0, &maxvldbid);
6328         if (code) {
6329             fprintf(STDERR,
6330                     "Could not get the highest allocated volume id from the VLDB\n");
6331             if (!error)
6332                 error = code;
6333         } else if (maxvolid > maxvldbid) {
6334             afs_uint32 id, nid;
6335             id = maxvolid - maxvldbid + 1;
6336             code = ubik_VL_GetNewVolumeId(cstruct, 0, id, &nid);
6337             if (code) {
6338                 fprintf(STDERR,
6339                         "Error in increasing highest allocated volume id in VLDB\n");
6340                 if (!error)
6341                     error = code;
6342             }
6343         }
6344     }
6345
6346     verbose = tverbose;
6347     if (verbose) {
6348         if (error)
6349             fprintf(STDOUT, "...error encountered");
6350         else
6351             fprintf(STDOUT, "...done entry\n");
6352     }
6353     if (aconn)
6354         rx_DestroyConnection(aconn);
6355     if (volumeInfo.volEntries_val)
6356         free(volumeInfo.volEntries_val);
6357
6358     PrintError("", error);
6359     return error;
6360 }
6361
6362 /* UV_SyncVldb()
6363  *      Synchronise vldb with the file server <aserver> and,
6364  *      optionally, <apart>.
6365  */
6366 int
6367 UV_SyncVldb(afs_uint32 aserver, afs_int32 apart, int flags, int force)
6368 {
6369     struct rx_connection *aconn;
6370     afs_int32 code, error = 0;
6371     int i, pfail;
6372     unsigned int j;
6373     volEntries volumeInfo;
6374     struct partList PartList;
6375     afs_int32 pcnt;
6376     char pname[10];
6377     volintInfo *vi;
6378     afs_int32 failures = 0, modifications = 0, tentries = 0;
6379     afs_int32 modified;
6380     afs_uint32 maxvolid = 0;
6381     char hoststr[16];
6382
6383     volumeInfo.volEntries_val = (volintInfo *) 0;
6384     volumeInfo.volEntries_len = 0;
6385
6386     aconn = UV_Bind(aserver, AFSCONF_VOLUMEPORT);
6387
6388     /* Generate array of partitions to check */
6389     if (!(flags & 1)) {
6390         code = UV_ListPartitions(aserver, &PartList, &pcnt);
6391         if (code) {
6392             fprintf(STDERR,
6393                     "Could not fetch the list of partitions from the server\n");
6394             ERROR_EXIT(code);
6395         }
6396     } else {
6397         PartList.partId[0] = apart;
6398         pcnt = 1;
6399     }
6400
6401     VPRINT("Processing volume entries ...\n");
6402
6403     /* Step through the array of partitions */
6404     for (i = 0; i < pcnt; i++) {
6405         apart = PartList.partId[i];
6406         MapPartIdIntoName(apart, pname);
6407
6408         volumeInfo.volEntries_val = (volintInfo *) 0;
6409         volumeInfo.volEntries_len = 0;
6410         code = AFSVolListVolumes(aconn, apart, 1, &volumeInfo);
6411         if (code) {
6412             fprintf(STDERR,
6413                     "Could not fetch the list of volumes from the server\n");
6414             ERROR_EXIT(code);
6415         }
6416
6417         /* May want to sort the entries: RW, BK (high to low), RO (high to low) */
6418         qsort((char *)volumeInfo.volEntries_val, volumeInfo.volEntries_len,
6419               sizeof(volintInfo), sortVolumes);
6420
6421         pfail = 0;
6422         for (vi = volumeInfo.volEntries_val, j = 0;
6423              j < volumeInfo.volEntries_len; j++, vi++) {
6424             if (!vi->status)
6425                 continue;
6426
6427             tentries++;
6428
6429             if (verbose) {
6430                 fprintf(STDOUT,
6431                         "Processing volume entry %d: %s (%lu) on server %s %s...\n",
6432                         j + 1, vi->name, (unsigned long)vi->volid,
6433                         noresolve ?
6434                         afs_inet_ntoa_r(aserver, hoststr) :
6435                         hostutil_GetNameByINet(aserver), pname);
6436                 fflush(STDOUT);
6437             }
6438
6439             if (flags & 2)
6440                 modified = 1;
6441             else
6442                 modified = 0;
6443             code = CheckVolume(vi, aserver, apart, &modified, &maxvolid, NULL);
6444             if (code) {
6445                 PrintError("", code);
6446                 failures++;
6447                 pfail++;
6448             } else if (modified) {
6449                 modifications++;
6450             }
6451
6452             if (verbose) {
6453                 if (code) {
6454                     fprintf(STDOUT, "...error encountered\n\n");
6455                 } else {
6456                     fprintf(STDOUT, "...done entry %d\n\n", j + 1);
6457                 }
6458             }
6459         }
6460
6461         if (pfail) {
6462             fprintf(STDERR,
6463                     "Could not process entries on server %s partition %s\n",
6464                     noresolve ?
6465                     afs_inet_ntoa_r(aserver, hoststr) :
6466                     hostutil_GetNameByINet(aserver), pname);
6467         }
6468         if (volumeInfo.volEntries_val) {
6469             free(volumeInfo.volEntries_val);
6470             volumeInfo.volEntries_val = 0;
6471         }
6472
6473     }                           /* thru all partitions */
6474
6475     if (flags & 2) {
6476         VPRINT3("Total entries: %u, Failed to process %d, Would change %d\n",
6477                 tentries, failures, modifications);
6478     } else {
6479         VPRINT3("Total entries: %u, Failed to process %d, Changed %d\n",
6480                 tentries, failures, modifications);
6481     }
6482
6483   error_exit:
6484     /* Now check if the maxvolid is larger than that stored in the VLDB */
6485     if (maxvolid) {
6486         afs_uint32 maxvldbid = 0;
6487         code = ubik_VL_GetNewVolumeId(cstruct, 0, 0, &maxvldbid);
6488         if (code) {
6489             fprintf(STDERR,
6490                     "Could not get the highest allocated volume id from the VLDB\n");
6491             if (!error)
6492                 error = code;
6493         } else if (maxvolid > maxvldbid) {
6494             afs_uint32 id, nid;
6495             id = maxvolid - maxvldbid + 1;
6496             code = ubik_VL_GetNewVolumeId(cstruct, 0, id, &nid);
6497             if (code) {
6498                 fprintf(STDERR,
6499                         "Error in increasing highest allocated volume id in VLDB\n");
6500                 if (!error)
6501                     error = code;
6502             }
6503         }
6504     }
6505
6506     if (aconn)
6507         rx_DestroyConnection(aconn);
6508     if (volumeInfo.volEntries_val)
6509         free(volumeInfo.volEntries_val);
6510     PrintError("", error);
6511     return (error);
6512 }
6513
6514 /* VolumeExists()
6515  *      Determine if a volume exists on a server and partition.
6516  *      Try creating a transaction on the volume. If we can,
6517  *      the volume exists, if not, then return the error code.
6518  *      Some error codes mean the volume is unavailable but
6519  *      still exists - so we catch these error codes.
6520  */
6521 static afs_int32
6522 VolumeExists(afs_uint32 server, afs_int32 partition, afs_uint32 volumeid)
6523 {
6524     struct rx_connection *conn = (struct rx_connection *)0;
6525     afs_int32 code = -1;
6526     volEntries volumeInfo;
6527
6528     conn = UV_Bind(server, AFSCONF_VOLUMEPORT);
6529     if (conn) {
6530         volumeInfo.volEntries_val = (volintInfo *) 0;
6531         volumeInfo.volEntries_len = 0;
6532         code = AFSVolListOneVolume(conn, partition, volumeid, &volumeInfo);
6533         if (volumeInfo.volEntries_val)
6534             free(volumeInfo.volEntries_val);
6535         if (code == VOLSERILLEGAL_PARTITION)
6536             code = ENODEV;
6537         rx_DestroyConnection(conn);
6538     }
6539     return code;
6540 }
6541
6542 /* CheckVldbRWBK()
6543  *
6544  */
6545 static afs_int32
6546 CheckVldbRWBK(struct nvldbentry * entry, afs_int32 * modified)
6547 {
6548     int modentry = 0;
6549     int idx;
6550     afs_int32 code, error = 0;
6551     char pname[10];
6552     char hoststr[16];
6553
6554     if (modified)
6555         *modified = 0;
6556     idx = Lp_GetRwIndex(entry);
6557
6558     /* Check to see if the RW volume exists and set the VLF_RWEXISTS
6559      * flag accordingly.
6560      */
6561     if (idx == -1) {            /* Did not find a RW entry */
6562         if (entry->flags & VLF_RWEXISTS) {      /* ... yet entry says RW exists */
6563             entry->flags &= ~VLF_RWEXISTS;      /* ... so say RW does not exist */
6564             modentry++;
6565         }
6566     } else {
6567         code =
6568             VolumeExists(entry->serverNumber[idx],
6569                          entry->serverPartition[idx], entry->volumeId[RWVOL]);
6570         if (code == 0) {        /* RW volume exists */
6571             if (!(entry->flags & VLF_RWEXISTS)) {       /* ... yet entry says RW does not exist */
6572                 entry->flags |= VLF_RWEXISTS;   /* ... so say RW does exist */
6573                 modentry++;
6574             }
6575         } else if (code == ENODEV) {    /* RW volume does not exist */
6576             if (entry->flags & VLF_RWEXISTS) {  /* ... yet entry says RW exists */
6577                 entry->flags &= ~VLF_RWEXISTS;  /* ... so say RW does not exist */
6578                 modentry++;
6579             }
6580         } else {
6581             /* If VLDB says it didn't exist, then ignore error */
6582             if (entry->flags & VLF_RWEXISTS) {
6583                 MapPartIdIntoName(entry->serverPartition[idx], pname);
6584                 fprintf(STDERR,
6585                         "Transaction call failed for RW volume %u on server %s %s\n",
6586                         entry->volumeId[RWVOL],
6587                         noresolve ?
6588                         afs_inet_ntoa_r(entry->serverNumber[idx], hoststr) :
6589                         hostutil_GetNameByINet(entry->serverNumber[idx]),
6590                         pname);
6591                 ERROR_EXIT(code);
6592             }
6593         }
6594     }
6595
6596     /* Check to see if the BK volume exists and set the VLF_BACKEXISTS
6597      * flag accordingly. idx already ponts to the RW entry.
6598      */
6599     if (idx == -1) {            /* Did not find a RW entry */
6600         if (entry->flags & VLF_BACKEXISTS) {    /* ... yet entry says BK exists */
6601             entry->flags &= ~VLF_BACKEXISTS;    /* ... so say BK does not exist */
6602             modentry++;
6603         }
6604     } else {                    /* Found a RW entry */
6605         code =
6606             VolumeExists(entry->serverNumber[idx],
6607                          entry->serverPartition[idx],
6608                          entry->volumeId[BACKVOL]);
6609         if (code == 0) {        /* BK volume exists */
6610             if (!(entry->flags & VLF_BACKEXISTS)) {     /* ... yet entry says BK does not exist */
6611                 entry->flags |= VLF_BACKEXISTS; /* ... so say BK does exist */
6612                 modentry++;
6613             }
6614         } else if (code == ENODEV) {    /* BK volume does not exist */
6615             if (entry->flags & VLF_BACKEXISTS) {        /* ... yet entry says BK exists */
6616                 entry->flags &= ~VLF_BACKEXISTS;        /* ... so say BK does not exist */
6617                 modentry++;
6618             }
6619         } else {
6620             /* If VLDB says it didn't exist, then ignore error */
6621             if (entry->flags & VLF_BACKEXISTS) {
6622                 MapPartIdIntoName(entry->serverPartition[idx], pname);
6623                 fprintf(STDERR,
6624                         "Transaction call failed for BK volume %u on server %s %s\n",
6625                         entry->volumeId[BACKVOL],
6626                         noresolve ?
6627                         afs_inet_ntoa_r(entry->serverNumber[idx], hoststr) :
6628                         hostutil_GetNameByINet(entry->serverNumber[idx]),
6629                         pname);
6630                 ERROR_EXIT(code);
6631             }
6632         }
6633     }
6634
6635     /* If there is an idx but the BK and RW volumes no
6636      * longer exist, then remove the RW entry.
6637      */
6638     if ((idx != -1) && !(entry->flags & VLF_RWEXISTS)
6639         && !(entry->flags & VLF_BACKEXISTS)) {
6640         Lp_SetRWValue(entry, entry->serverNumber[idx],
6641                       entry->serverPartition[idx], 0L, 0L);
6642         entry->nServers--;
6643         modentry++;
6644     }
6645
6646   error_exit:
6647     if (modified)
6648         *modified = modentry;
6649     return (error);
6650 }
6651
6652 static afs_int32
6653 CheckVldbRO(struct nvldbentry *entry, afs_int32 * modified)
6654 {
6655     int idx;
6656     int foundro = 0, modentry = 0;
6657     afs_int32 code, error = 0;
6658     char pname[10];
6659     char hoststr[16];
6660
6661     if (modified)
6662         *modified = 0;
6663
6664     /* Check to see if the RO volumes exist and set the VLF_ROEXISTS
6665      * flag accordingly.
6666      */
6667     for (idx = 0; idx < entry->nServers; idx++) {
6668         if (!(entry->serverFlags[idx] & VLSF_ROVOL)) {
6669             continue;           /* not a RO */
6670         }
6671
6672         code =
6673             VolumeExists(entry->serverNumber[idx],
6674                          entry->serverPartition[idx], entry->volumeId[ROVOL]);
6675         if (code == 0) {        /* RO volume exists */
6676             foundro++;
6677         } else if (code == ENODEV) {    /* RW volume does not exist */
6678             Lp_SetROValue(entry, entry->serverNumber[idx],
6679                           entry->serverPartition[idx], 0L, 0L);
6680             entry->nServers--;
6681             idx--;
6682             modentry++;
6683         } else {
6684             MapPartIdIntoName(entry->serverPartition[idx], pname);
6685             fprintf(STDERR,
6686                     "Transaction call failed for RO %u on server %s %s\n",
6687                     entry->volumeId[ROVOL],
6688                     noresolve ?
6689                     afs_inet_ntoa_r(entry->serverNumber[idx], hoststr) :
6690                     hostutil_GetNameByINet(entry->serverNumber[idx]), pname);
6691             ERROR_EXIT(code);
6692         }
6693     }
6694
6695     if (foundro) {              /* A RO volume exists */
6696         if (!(entry->flags & VLF_ROEXISTS)) {   /* ... yet entry says RW does not exist */
6697             entry->flags |= VLF_ROEXISTS;       /* ... so say RW does exist */
6698             modentry++;
6699         }
6700     } else {                    /* A RO volume does not exist */
6701         if (entry->flags & VLF_ROEXISTS) {      /* ... yet entry says RO exists */
6702             entry->flags &= ~VLF_ROEXISTS;      /* ... so say RO does not exist */
6703             modentry++;
6704         }
6705     }
6706
6707   error_exit:
6708     if (modified)
6709         *modified = modentry;
6710     return (error);
6711 }
6712
6713 /* CheckVldb()
6714  *      Ensure that <entry> matches with the info on file servers
6715  */
6716 static afs_int32
6717 CheckVldb(struct nvldbentry * entry, afs_int32 * modified, afs_int32 * deleted)
6718 {
6719     afs_int32 code, error = 0;
6720     struct nvldbentry storeEntry;
6721     int islocked = 0, mod, modentry, delentry = 0;
6722     int pass = 0, doit=1;
6723
6724     if (modified) {
6725         if (*modified == 1)
6726             doit = 0;
6727         *modified = 0;
6728     }
6729     if (verbose) {
6730         fprintf(STDOUT, "_______________________________\n");
6731         fprintf(STDOUT, "\n-- status before -- \n");
6732         if ((entry->flags & VLF_RWEXISTS) || (entry->flags & VLF_ROEXISTS)
6733             || (entry->flags & VLF_BACKEXISTS))
6734             EnumerateEntry(entry);
6735         fprintf(STDOUT, "\n");
6736     }
6737
6738     if (strlen(entry->name) > (VOLSER_OLDMAXVOLNAME - 10)) {
6739         fprintf(STDERR, "Volume name %s exceeds limit of %d characters\n",
6740                 entry->name, VOLSER_OLDMAXVOLNAME - 10);
6741     }
6742
6743   retry:
6744     /* Check to see if the VLDB is ok without locking it (pass 1).
6745      * If it will change, then lock the VLDB entry, read it again,
6746      * then make the changes to it (pass 2).
6747      */
6748     if (++pass == 2) {
6749         code =
6750             ubik_VL_SetLock(cstruct, 0, entry->volumeId[RWVOL], RWVOL,
6751                       VLOP_DELETE);
6752         if (code) {
6753             fprintf(STDERR, "Could not lock VLDB entry for %u \n",
6754                     entry->volumeId[RWVOL]);
6755             ERROR_EXIT(code);
6756         }
6757         islocked = 1;
6758
6759         code = VLDB_GetEntryByID(entry->volumeId[RWVOL], RWVOL, entry);
6760         if (code) {
6761             fprintf(STDERR, "Could not read VLDB entry for volume %s\n",
6762                     entry->name);
6763             ERROR_EXIT(code);
6764         } else {
6765             MapHostToNetwork(entry);
6766         }
6767     }
6768
6769     modentry = 0;
6770
6771     /* Check if the RW and BK entries are ok */
6772     code = CheckVldbRWBK(entry, &mod);
6773     if (code)
6774         ERROR_EXIT(code);
6775     if (mod && (pass == 1) && doit)
6776         goto retry;
6777     if (mod)
6778         modentry++;
6779
6780     /* Check if the RO volumes entries are ok */
6781     code = CheckVldbRO(entry, &mod);
6782     if (code)
6783         ERROR_EXIT(code);
6784     if (mod && (pass == 1) && doit)
6785         goto retry;
6786     if (mod)
6787         modentry++;
6788
6789     /* The VLDB entry has been updated. If it as been modified, then
6790      * write the entry back out the the VLDB.
6791      */
6792     if (modentry && doit) {
6793         if (pass == 1)
6794             goto retry;
6795
6796         if (!(entry->flags & VLF_RWEXISTS) && !(entry->flags & VLF_BACKEXISTS)
6797             && !(entry->flags & VLF_ROEXISTS) && doit) {
6798             /* The RW, BK, nor RO volumes do not exist. Delete the VLDB entry */
6799             code =
6800                 ubik_VL_DeleteEntry(cstruct, 0, entry->volumeId[RWVOL],
6801                           RWVOL);
6802             if (code) {
6803                 fprintf(STDERR,
6804                         "Could not delete VLDB entry for volume %u \n",
6805                         entry->volumeId[RWVOL]);
6806                 ERROR_EXIT(code);
6807             }
6808             delentry = 1;
6809         } else {
6810             /* Replace old entry with our new one */
6811             MapNetworkToHost(entry, &storeEntry);
6812             code =
6813                 VLDB_ReplaceEntry(entry->volumeId[RWVOL], RWVOL, &storeEntry,
6814                                   (LOCKREL_OPCODE | LOCKREL_AFSID |
6815                                    LOCKREL_TIMESTAMP));
6816             if (code) {
6817                 fprintf(STDERR, "Could not update VLDB entry for volume %u\n",
6818                         entry->volumeId[RWVOL]);
6819                 ERROR_EXIT(code);
6820             }
6821         }
6822         islocked = 0;
6823     }
6824
6825     if (modified && modentry) {
6826         *modified = 1;
6827     }
6828     if (deleted && delentry) {
6829         *deleted = 1;
6830     }
6831
6832     if (verbose) {
6833         fprintf(STDOUT, "-- status after --\n");
6834         if (delentry)
6835             fprintf(STDOUT, "\n**entry deleted**\n");
6836         else if (modentry)
6837             EnumerateEntry(entry);
6838         else
6839             fprintf(STDOUT, "\n**no change**\n");
6840     }
6841
6842   error_exit:
6843     VPRINT("\n_______________________________\n");
6844
6845     if (islocked) {
6846         code =
6847             ubik_VL_ReleaseLock(cstruct, 0, entry->volumeId[RWVOL],
6848                       RWVOL,
6849                       (LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP));
6850         if (code) {
6851             fprintf(STDERR,
6852                     "Could not release lock on VLDB entry for volume %u\n",
6853                     entry->volumeId[RWVOL]);
6854             if (!error)
6855                 error = code;
6856         }
6857     }
6858     return error;
6859 }
6860
6861 /* UV_SyncServer()
6862  *      Synchronise <aserver> <apart>(if flags = 1) with the VLDB.
6863  */
6864 int
6865 UV_SyncServer(afs_uint32 aserver, afs_int32 apart, int flags, int force)
6866 {
6867     struct rx_connection *aconn;
6868     afs_int32 code, error = 0;
6869     afs_int32 nentries, tentries = 0;
6870     struct VldbListByAttributes attributes;
6871     nbulkentries arrayEntries;
6872     afs_int32 failures = 0, modified, modifications = 0;
6873     struct nvldbentry *vlentry;
6874     afs_int32 si, nsi, j;
6875
6876     if (flags & 2)
6877         verbose = 1;
6878
6879     aconn = UV_Bind(aserver, AFSCONF_VOLUMEPORT);
6880
6881     /* Set up attributes to search VLDB  */
6882     memset(&attributes, 0, sizeof(attributes));
6883     attributes.server = ntohl(aserver);
6884     attributes.Mask = VLLIST_SERVER;
6885     if ((flags & 1)) {
6886         attributes.partition = apart;
6887         attributes.Mask |= VLLIST_PARTITION;
6888     }
6889
6890     VPRINT("Processing VLDB entries ...\n");
6891
6892     /* While we need to collect more VLDB entries */
6893     for (si = 0; si != -1; si = nsi) {
6894         memset(&arrayEntries, 0, sizeof(arrayEntries));
6895
6896         /* Collect set of VLDB entries */
6897         code =
6898             VLDB_ListAttributesN2(&attributes, 0, si, &nentries,
6899                                   &arrayEntries, &nsi);
6900         if (code == RXGEN_OPCODE) {
6901             code = VLDB_ListAttributes(&attributes, &nentries, &arrayEntries);
6902             nsi = -1;
6903         }
6904         if (code) {
6905             fprintf(STDERR, "Could not access the VLDB for attributes\n");
6906             ERROR_EXIT(code);
6907         }
6908         tentries += nentries;
6909
6910         for (j = 0; j < nentries; j++) {
6911             vlentry = &arrayEntries.nbulkentries_val[j];
6912             MapHostToNetwork(vlentry);
6913
6914             VPRINT1("Processing VLDB entry %d ...\n", j + 1);
6915
6916             /* Tell CheckVldb not to update if appropriate */
6917             if (flags & 2)
6918                 modified = 1;
6919             else
6920                 modified = 0;
6921             code = CheckVldb(vlentry, &modified, NULL);
6922             if (code) {
6923                 PrintError("", code);
6924                 fprintf(STDERR,
6925                         "Could not process VLDB entry for volume %s\n",
6926                         vlentry->name);
6927                 failures++;
6928             } else if (modified) {
6929                 modifications++;
6930             }
6931
6932             if (verbose) {
6933                 if (code) {
6934                     fprintf(STDOUT, "...error encountered\n\n");
6935                 } else {
6936                     fprintf(STDOUT, "...done entry %d\n\n", j + 1);
6937                 }
6938             }
6939         }
6940
6941         if (arrayEntries.nbulkentries_val) {
6942             free(arrayEntries.nbulkentries_val);
6943             arrayEntries.nbulkentries_val = 0;
6944         }
6945     }
6946
6947     if (flags & 2) {
6948         VPRINT3("Total entries: %u, Failed to process %d, Would change %d\n",
6949                 tentries, failures, modifications);
6950     } else {
6951         VPRINT3("Total entries: %u, Failed to process %d, Changed %d\n",
6952                 tentries, failures, modifications);
6953     }
6954
6955   error_exit:
6956     if (aconn)
6957         rx_DestroyConnection(aconn);
6958     if (arrayEntries.nbulkentries_val)
6959         free(arrayEntries.nbulkentries_val);
6960
6961     if (failures)
6962         error = VOLSERFAILEDOP;
6963     return error;
6964 }
6965
6966 /*rename volume <oldname> to <newname>, changing the names of the related
6967  *readonly and backup volumes. This operation is also idempotent.
6968  *salvager is capable of recovering from rename operation stopping halfway.
6969  *to recover run syncserver on the affected machines,it will force renaming to completion. name clashes should have been detected before calling this proc */
6970 int
6971 UV_RenameVolume(struct nvldbentry *entry, char oldname[], char newname[])
6972 {
6973     struct nvldbentry storeEntry;
6974     afs_int32 vcode, code, rcode, error;
6975     int i, index;
6976     char nameBuffer[256];
6977     afs_int32 tid;
6978     struct rx_connection *aconn;
6979     int islocked;
6980     char hoststr[16];
6981
6982     error = 0;
6983     aconn = (struct rx_connection *)0;
6984     tid = 0;
6985     islocked = 0;
6986
6987     vcode = ubik_VL_SetLock(cstruct, 0, entry->volumeId[RWVOL], RWVOL, VLOP_ADDSITE);   /*last param is dummy */
6988     if (vcode) {
6989         fprintf(STDERR,
6990                 " Could not lock the VLDB entry for the  volume %u \n",
6991                 entry->volumeId[RWVOL]);
6992         error = vcode;
6993         goto rvfail;
6994     }
6995     islocked = 1;
6996     strncpy(entry->name, newname, VOLSER_OLDMAXVOLNAME);
6997     MapNetworkToHost(entry, &storeEntry);
6998     vcode = VLDB_ReplaceEntry(entry->volumeId[RWVOL], RWVOL, &storeEntry, 0);
6999     if (vcode) {
7000         fprintf(STDERR, "Could not update VLDB entry for %u\n",
7001                 entry->volumeId[RWVOL]);
7002         error = vcode;
7003         goto rvfail;
7004     }
7005     VPRINT1("Recorded the new name %s in VLDB\n", newname);
7006     /*at this stage the intent to rename is recorded in the vldb, as far as the vldb
7007      * is concerned, oldname is lost */
7008     if (entry->flags & VLF_RWEXISTS) {
7009         index = Lp_GetRwIndex(entry);
7010         if (index == -1) {      /* there is a serious discrepancy */
7011             fprintf(STDERR,
7012                     "There is a serious discrepancy in VLDB entry for volume %u\n",
7013                     entry->volumeId[RWVOL]);
7014             fprintf(STDERR, "try building VLDB from scratch\n");
7015             error = VOLSERVLDB_ERROR;
7016             goto rvfail;
7017         }
7018         aconn = UV_Bind(entry->serverNumber[index], AFSCONF_VOLUMEPORT);
7019         code =
7020             AFSVolTransCreate_retry(aconn, entry->volumeId[RWVOL],
7021                               entry->serverPartition[index], ITOffline, &tid);
7022         if (code) {             /*volume doesnot exist */
7023             fprintf(STDERR,
7024                     "Could not start transaction on the rw volume %u\n",
7025                     entry->volumeId[RWVOL]);
7026             error = code;
7027             goto rvfail;
7028         } else {                /*volume exists, process it */
7029
7030             code =
7031                 AFSVolSetIdsTypes(aconn, tid, newname, RWVOL,
7032                                   entry->volumeId[RWVOL],
7033                                   entry->volumeId[ROVOL],
7034                                   entry->volumeId[BACKVOL]);
7035             if (!code) {
7036                 VPRINT2("Renamed rw volume %s to %s\n", oldname, newname);
7037                 code = AFSVolEndTrans(aconn, tid, &rcode);
7038                 tid = 0;
7039                 if (code) {
7040                     fprintf(STDERR,
7041                             "Could not  end transaction on volume %s %u\n",
7042                             entry->name, entry->volumeId[RWVOL]);
7043                     error = code;
7044                     goto rvfail;
7045                 }
7046             } else {
7047                 fprintf(STDERR, "Could not  set parameters on volume %s %u\n",
7048                         entry->name, entry->volumeId[RWVOL]);
7049                 error = code;
7050                 goto rvfail;
7051             }
7052         }
7053         if (aconn)
7054             rx_DestroyConnection(aconn);
7055         aconn = (struct rx_connection *)0;
7056     }
7057     /*end rw volume processing */
7058     if (entry->flags & VLF_BACKEXISTS) {        /*process the backup volume */
7059         index = Lp_GetRwIndex(entry);
7060         if (index == -1) {      /* there is a serious discrepancy */
7061             fprintf(STDERR,
7062                     "There is a serious discrepancy in the VLDB entry for the backup volume %u\n",
7063                     entry->volumeId[BACKVOL]);
7064             fprintf(STDERR, "try building VLDB from scratch\n");
7065             error = VOLSERVLDB_ERROR;
7066             goto rvfail;
7067         }
7068         aconn = UV_Bind(entry->serverNumber[index], AFSCONF_VOLUMEPORT);
7069         code =
7070             AFSVolTransCreate_retry(aconn, entry->volumeId[BACKVOL],
7071                               entry->serverPartition[index], ITOffline, &tid);
7072         if (code) {             /*volume doesnot exist */
7073             fprintf(STDERR,
7074                     "Could not start transaction on the backup volume  %u\n",
7075                     entry->volumeId[BACKVOL]);
7076             error = code;
7077             goto rvfail;
7078         } else {                /*volume exists, process it */
7079             if (strlen(newname) > (VOLSER_OLDMAXVOLNAME - 8)) {
7080                 fprintf(STDERR,
7081                         "Volume name %s.backup exceeds the limit of %u characters\n",
7082                         newname, VOLSER_OLDMAXVOLNAME);
7083                 error = code;
7084                 goto rvfail;
7085             }
7086             strcpy(nameBuffer, newname);
7087             strcat(nameBuffer, ".backup");
7088
7089             code =
7090                 AFSVolSetIdsTypes(aconn, tid, nameBuffer, BACKVOL,
7091                                   entry->volumeId[RWVOL], 0, 0);
7092             if (!code) {
7093                 VPRINT1("Renamed backup volume to %s \n", nameBuffer);
7094                 code = AFSVolEndTrans(aconn, tid, &rcode);
7095                 tid = 0;
7096                 if (code) {
7097                     fprintf(STDERR,
7098                             "Could not  end transaction on the backup volume %u\n",
7099                             entry->volumeId[BACKVOL]);
7100                     error = code;
7101                     goto rvfail;
7102                 }
7103             } else {
7104                 fprintf(STDERR,
7105                         "Could not  set parameters on the backup volume %u\n",
7106                         entry->volumeId[BACKVOL]);
7107                 error = code;
7108                 goto rvfail;
7109             }
7110         }
7111     }                           /* end backup processing */
7112     if (aconn)
7113         rx_DestroyConnection(aconn);
7114     aconn = (struct rx_connection *)0;
7115     if (entry->flags & VLF_ROEXISTS) {  /*process the ro volumes */
7116         for (i = 0; i < entry->nServers; i++) {
7117             if (entry->serverFlags[i] & VLSF_ROVOL) {
7118                 aconn = UV_Bind(entry->serverNumber[i], AFSCONF_VOLUMEPORT);
7119                 code =
7120                     AFSVolTransCreate_retry(aconn, entry->volumeId[ROVOL],
7121                                       entry->serverPartition[i], ITOffline,
7122                                       &tid);
7123                 if (code) {     /*volume doesnot exist */
7124                     fprintf(STDERR,
7125                             "Could not start transaction on the ro volume %u\n",
7126                             entry->volumeId[ROVOL]);
7127                     error = code;
7128                     goto rvfail;
7129                 } else {        /*volume exists, process it */
7130                     strcpy(nameBuffer, newname);
7131                     strcat(nameBuffer, ".readonly");
7132                     if (strlen(nameBuffer) > (VOLSER_OLDMAXVOLNAME - 1)) {
7133                         fprintf(STDERR,
7134                                 "Volume name %s exceeds the limit of %u characters\n",
7135                                 nameBuffer, VOLSER_OLDMAXVOLNAME);
7136                         error = code;
7137                         goto rvfail;
7138                     }
7139                     code =
7140                         AFSVolSetIdsTypes(aconn, tid, nameBuffer, ROVOL,
7141                                           entry->volumeId[RWVOL], 0, 0);
7142                     if (!code) {
7143                         VPRINT2("Renamed RO volume %s on host %s\n",
7144                                 nameBuffer,
7145                                 noresolve ?
7146                                 afs_inet_ntoa_r(entry->serverNumber[i], hoststr) :
7147                                 hostutil_GetNameByINet(entry->
7148                                                        serverNumber[i]));
7149                         code = AFSVolEndTrans(aconn, tid, &rcode);
7150                         tid = 0;
7151                         if (code) {
7152                             fprintf(STDERR,
7153                                     "Could not  end transaction on volume %u\n",
7154                                     entry->volumeId[ROVOL]);
7155                             error = code;
7156                             goto rvfail;
7157                         }
7158                     } else {
7159                         fprintf(STDERR,
7160                                 "Could not  set parameters on the ro volume %u\n",
7161                                 entry->volumeId[ROVOL]);
7162                         error = code;
7163                         goto rvfail;
7164                     }
7165                 }
7166                 if (aconn)
7167                     rx_DestroyConnection(aconn);
7168                 aconn = (struct rx_connection *)0;
7169             }
7170         }
7171     }
7172   rvfail:
7173     if (islocked) {
7174         vcode =
7175             ubik_VL_ReleaseLock(cstruct, 0, entry->volumeId[RWVOL],
7176                       RWVOL,
7177                       LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
7178         if (vcode) {
7179             fprintf(STDERR,
7180                     "Could not unlock the VLDB entry for the volume %s %u\n",
7181                     entry->name, entry->volumeId[RWVOL]);
7182             if (!error)
7183                 error = vcode;
7184         }
7185     }
7186     if (tid) {
7187         code = AFSVolEndTrans(aconn, tid, &rcode);
7188         if (!code)
7189             code = rcode;
7190         if (code) {
7191             fprintf(STDERR, "Failed to end transaction on a volume \n");
7192             if (!error)
7193                 error = code;
7194         }
7195     }
7196     if (aconn)
7197         rx_DestroyConnection(aconn);
7198     PrintError("", error);
7199     return error;
7200
7201 }
7202
7203 /*report on all the active transactions on volser */
7204 int
7205 UV_VolserStatus(afs_uint32 server, transDebugInfo ** rpntr, afs_int32 * rcount)
7206 {
7207     struct rx_connection *aconn;
7208     transDebugEntries transInfo;
7209     afs_int32 code = 0;
7210
7211     aconn = UV_Bind(server, AFSCONF_VOLUMEPORT);
7212     transInfo.transDebugEntries_val = (transDebugInfo *) 0;
7213     transInfo.transDebugEntries_len = 0;
7214     code = AFSVolMonitor(aconn, &transInfo);
7215     if (code) {
7216         fprintf(STDERR,
7217                 "Could not access status information about the server\n");
7218         PrintError("", code);
7219         if (transInfo.transDebugEntries_val)
7220             free(transInfo.transDebugEntries_val);
7221         if (aconn)
7222             rx_DestroyConnection(aconn);
7223         return code;
7224     } else {
7225         *rcount = transInfo.transDebugEntries_len;
7226         *rpntr = transInfo.transDebugEntries_val;
7227         if (aconn)
7228             rx_DestroyConnection(aconn);
7229         return 0;
7230     }
7231
7232
7233 }
7234
7235 /*delete the volume without interacting with the vldb */
7236 int
7237 UV_VolumeZap(afs_uint32 server, afs_int32 part, afs_uint32 volid)
7238 {
7239     afs_int32 error;
7240     struct rx_connection *aconn;
7241
7242     aconn = UV_Bind(server, AFSCONF_VOLUMEPORT);
7243     error = DoVolDelete(aconn, volid, part,
7244                         "the", 0, NULL, NULL);
7245     if (error == VNOVOL) {
7246         EPRINT1(error, "Failed to start transaction on %u\n", volid);
7247     }
7248
7249     PrintError("", error);
7250     if (aconn)
7251         rx_DestroyConnection(aconn);
7252     return error;
7253 }
7254
7255 int
7256 UV_SetVolume(afs_uint32 server, afs_int32 partition, afs_uint32 volid,
7257              afs_int32 transflag, afs_int32 setflag, int sleeptime)
7258 {
7259     struct rx_connection *conn = 0;
7260     afs_int32 tid = 0;
7261     afs_int32 code, error = 0, rcode;
7262
7263     conn = UV_Bind(server, AFSCONF_VOLUMEPORT);
7264     if (!conn) {
7265         fprintf(STDERR, "SetVolumeStatus: Bind Failed");
7266         ERROR_EXIT(-1);
7267     }
7268
7269     code = AFSVolTransCreate_retry(conn, volid, partition, transflag, &tid);
7270     if (code) {
7271         fprintf(STDERR, "SetVolumeStatus: TransCreate Failed\n");
7272         ERROR_EXIT(code);
7273     }
7274
7275     code = AFSVolSetFlags(conn, tid, setflag);
7276     if (code) {
7277         fprintf(STDERR, "SetVolumeStatus: SetFlags Failed\n");
7278         ERROR_EXIT(code);
7279     }
7280
7281     if (sleeptime) {
7282 #ifdef AFS_PTHREAD_ENV
7283         sleep(sleeptime);
7284 #else
7285         IOMGR_Sleep(sleeptime);
7286 #endif
7287     }
7288
7289   error_exit:
7290     if (tid) {
7291         rcode = 0;
7292         code = AFSVolEndTrans(conn, tid, &rcode);
7293         if (code || rcode) {
7294             fprintf(STDERR, "SetVolumeStatus: EndTrans Failed\n");
7295             if (!error)
7296                 error = (code ? code : rcode);
7297         }
7298     }
7299
7300     if (conn)
7301         rx_DestroyConnection(conn);
7302     return (error);
7303 }
7304
7305 int
7306 UV_SetVolumeInfo(afs_uint32 server, afs_int32 partition, afs_uint32 volid,
7307                  volintInfo * infop)
7308 {
7309     struct rx_connection *conn = 0;
7310     afs_int32 tid = 0;
7311     afs_int32 code, error = 0, rcode;
7312
7313     conn = UV_Bind(server, AFSCONF_VOLUMEPORT);
7314     if (!conn) {
7315         fprintf(STDERR, "SetVolumeInfo: Bind Failed");
7316         ERROR_EXIT(-1);
7317     }
7318
7319     code = AFSVolTransCreate_retry(conn, volid, partition, ITOffline, &tid);
7320     if (code) {
7321         fprintf(STDERR, "SetVolumeInfo: TransCreate Failed\n");
7322         ERROR_EXIT(code);
7323     }
7324
7325     code = AFSVolSetInfo(conn, tid, infop);
7326     if (code) {
7327         fprintf(STDERR, "SetVolumeInfo: SetInfo Failed\n");
7328         ERROR_EXIT(code);
7329     }
7330
7331   error_exit:
7332     if (tid) {
7333         rcode = 0;
7334         code = AFSVolEndTrans(conn, tid, &rcode);
7335         if (code || rcode) {
7336             fprintf(STDERR, "SetVolumeInfo: EndTrans Failed\n");
7337             if (!error)
7338                 error = (code ? code : rcode);
7339         }
7340     }
7341
7342     if (conn)
7343         rx_DestroyConnection(conn);
7344     return (error);
7345 }
7346
7347 int
7348 UV_GetSize(afs_uint32 afromvol, afs_uint32 afromserver, afs_int32 afrompart,
7349            afs_int32 fromdate, struct volintSize *vol_size)
7350 {
7351     struct rx_connection *aconn = (struct rx_connection *)0;
7352     afs_int32 tid = 0, rcode = 0;
7353     afs_int32 code, error = 0;
7354
7355
7356     /* get connections to the servers */
7357     aconn = UV_Bind(afromserver, AFSCONF_VOLUMEPORT);
7358
7359     VPRINT1("Starting transaction on volume %u...", afromvol);
7360     code = AFSVolTransCreate_retry(aconn, afromvol, afrompart, ITBusy, &tid);
7361     EGOTO1(error_exit, code,
7362            "Could not start transaction on the volume %u to be measured\n",
7363            afromvol);
7364     VDONE;
7365
7366     VPRINT1("Getting size of volume on volume %u...", afromvol);
7367     code = AFSVolGetSize(aconn, tid, fromdate, vol_size);
7368     EGOTO(error_exit, code, "Could not start the measurement process \n");
7369     VDONE;
7370
7371   error_exit:
7372     if (tid) {
7373         VPRINT1("Ending transaction on volume %u...", afromvol);
7374         code = AFSVolEndTrans(aconn, tid, &rcode);
7375         if (code || rcode) {
7376             fprintf(STDERR, "Could not end transaction on the volume %u\n",
7377                     afromvol);
7378             fprintf(STDERR, "error codes: %d and %d\n", code, rcode);
7379             if (!error)
7380                 error = (code ? code : rcode);
7381         }
7382         VDONE;
7383     }
7384     if (aconn)
7385         rx_DestroyConnection(aconn);
7386
7387     PrintError("", error);
7388     return (error);
7389 }
7390
7391 /*maps the host addresses in <old > (present in network byte order) to
7392  that in< new> (present in host byte order )*/
7393 void
7394 MapNetworkToHost(struct nvldbentry *old, struct nvldbentry *new)
7395 {
7396     int i, count;
7397
7398     memset(new, 0, sizeof(struct nvldbentry));
7399
7400     /*copy all the fields */
7401     strcpy(new->name, old->name);
7402 /*    new->volumeType = old->volumeType;*/
7403     new->nServers = old->nServers;
7404     count = old->nServers;
7405     if (count < NMAXNSERVERS)
7406         count++;
7407     for (i = 0; i < count; i++) {
7408         new->serverNumber[i] = ntohl(old->serverNumber[i]);
7409         new->serverPartition[i] = old->serverPartition[i];
7410         new->serverFlags[i] = old->serverFlags[i];
7411     }
7412     new->volumeId[RWVOL] = old->volumeId[RWVOL];
7413     new->volumeId[ROVOL] = old->volumeId[ROVOL];
7414     new->volumeId[BACKVOL] = old->volumeId[BACKVOL];
7415     new->cloneId = old->cloneId;
7416     new->flags = old->flags;
7417 }
7418
7419 /*maps the host entries in <entry> which are present in host byte order to network byte order */
7420 void
7421 MapHostToNetwork(struct nvldbentry *entry)
7422 {
7423     int i, count;
7424
7425     count = entry->nServers;
7426     if (count < NMAXNSERVERS)
7427         count++;
7428     for (i = 0; i < count; i++) {
7429         entry->serverNumber[i] = htonl(entry->serverNumber[i]);
7430     }
7431 }