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