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