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