2453296b8b99d9ee434fdd6652df4807190071d2
[openafs.git] / src / libadmin / vos / 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 /*
11  * This file is a reimplementation of volser/vsproc.s.  Every attempt
12  * has been made to keep it as similar as possible to aid comprehension
13  * of the code.  For most functions, two parameters have been added
14  * the cell handle, and a status variable.  For those functions that
15  * require one, a server handle may also be added.
16  *
17  * Other changes were made to provide thread safe functions and
18  * eliminate the practice of reporting errors to STDOUT.
19  */
20
21 #include "vsprocs.h"
22 #include "vosutils.h"
23 #include "lockprocs.h"
24 #include "../adminutil/afs_AdminInternal.h"
25 #include <afs/afs_AdminErrors.h>
26 #include "afs_vosAdmin.h"
27 #ifdef AFS_NT40_ENV
28 #include <io.h>
29 #endif
30
31 static GroupEntries();
32
33 struct release {
34   afs_int32 time;
35   afs_int32 vldbEntryIndex;
36 };
37
38 static struct rx_connection *UV_Bind(
39   afs_cell_handle_p cellHandle,
40   afs_int32 aserver,
41   afs_int32 port)
42 {
43     return rx_GetCachedConnection(htonl(aserver), htons(port), VOLSERVICE_ID,
44                                   cellHandle->tokens->afs_sc[cellHandle->tokens->sc_index],
45                                   cellHandle->tokens->sc_index);
46 }
47
48
49 /* if <okvol> is allright(indicated by beibg able to
50  * start a transaction, delete the <delvol> */
51 static afs_int32 CheckAndDeleteVolume(
52   struct rx_connection *aconn,
53   afs_int32 apart,
54   afs_int32 okvol,
55   afs_int32 delvol)
56 {
57     afs_int32 error,code,tid,rcode;
58
59     error = 0;
60     code = 0;
61
62     if(okvol == 0) {
63         code = AFSVolTransCreate(aconn, delvol, apart, ITOffline,&tid);
64         if(!error && code) error = code;
65         code = AFSVolDeleteVolume(aconn,tid);
66         if(!error && code) error = code;
67         code = AFSVolEndTrans(aconn,tid, &rcode);
68         if(!code) code = rcode;
69         if(!error && code) error = code;
70         return error;
71     }
72     else {
73         code = AFSVolTransCreate(aconn, okvol, apart, ITOffline,&tid);
74         if(!code) {
75             code = AFSVolEndTrans(aconn,tid, &rcode);
76             if(!code) code = rcode;
77             if(!error && code) error = code;
78             code = AFSVolTransCreate(aconn, delvol, apart, ITOffline,&tid);
79             if(!error && code) error = code;
80             code = AFSVolDeleteVolume(aconn,tid);
81             if(!error && code) error = code;
82             code = AFSVolEndTrans(aconn,tid, &rcode);
83             if(!code) code = rcode;
84             if(!error && code) error = code;
85         }
86         else 
87             error = code;
88         return error;
89     }
90 }
91
92 /* forcibly remove a volume.  Very dangerous call */
93 int UV_NukeVolume(
94   afs_cell_handle_p cellHandle,
95   struct rx_connection *server,
96   unsigned int partition,
97   unsigned int volumeId,
98   afs_status_p st)
99 {
100     int rc = 0;
101     afs_status_t tst = 0;
102
103     tst = AFSVolNukeVolume(server, partition, volumeId);
104
105     if (!tst) {
106         rc = 1;
107     }
108
109     if (st != NULL) {
110         *st = tst;
111     }
112     return rc;
113 }
114
115 /* create a volume, given a server, partition number, volume name --> sends
116 * back new vol id in <anewid>*/
117 int UV_CreateVolume(
118   afs_cell_handle_p cellHandle,
119   struct rx_connection *server,
120   unsigned int partition,
121   const char *volumeName,
122   unsigned int quota,
123   unsigned int *volumeId,
124   afs_status_p st)
125 {
126     int rc = 0;
127     afs_status_t tst = 0;
128     afs_int32 tid = 0;
129     afs_int32 rcode;
130     struct nvldbentry entry;
131     struct volintInfo tstatus;
132
133     memset (&tstatus, 0, sizeof(tstatus));
134     tstatus.dayUse = -1;
135     tstatus.maxquota = quota;
136
137     /* next the next 3 available ids from the VLDB */
138     tst = ubik_Call(VL_GetNewVolumeId, cellHandle->vos, 0, 3, volumeId);
139     if (tst) {
140         goto fail_UV_CreateVolume;
141     }
142
143     tst = AFSVolCreateVolume(server, partition, volumeName, volser_RW, 0,
144                              volumeId, &tid);
145     if (tst) {
146         goto fail_UV_CreateVolume;
147     }
148
149     AFSVolSetInfo(server, tid, &tstatus);
150
151     tst = AFSVolSetFlags(server, tid, 0);
152     if (tst) {
153         goto fail_UV_CreateVolume;
154     }
155
156     /* set up the vldb entry for this volume */
157     strncpy(entry.name, volumeName,VOLSER_OLDMAXVOLNAME);
158     entry.nServers = 1;
159     entry.serverNumber[0] = ntohl(rx_HostOf(rx_PeerOf(server)));
160     entry.serverPartition[0] = partition;
161     entry.flags = RW_EXISTS;
162     entry.serverFlags[0] = ITSRWVOL;
163     entry.volumeId[RWVOL] = *volumeId;
164     entry.volumeId[ROVOL] = *volumeId + 1;
165     entry.volumeId[BACKVOL] = *volumeId + 2;
166     entry.cloneId = 0;
167
168     if (!VLDB_CreateEntry(cellHandle, &entry, &tst)) {
169         AFSVolDeleteVolume(server,tid);
170         goto fail_UV_CreateVolume;
171     }
172
173     tst = AFSVolEndTrans(server, tid, &rcode);
174     tid = 0;
175     if (tst) {
176         goto fail_UV_CreateVolume;
177     }
178     rc = 1;
179
180 fail_UV_CreateVolume:
181
182     if (tid != 0) {
183         AFSVolEndTrans(server, tid, &rcode);
184     }
185
186     if (st != NULL) {
187         *st = tst;
188     }
189     return rc;
190 }
191
192
193 /* Delete the volume <volid>on <aserver> <apart>
194  * the physical entry gets removed from the vldb only if the ref count 
195  * becomes zero
196  */
197 int UV_DeleteVolume(
198   afs_cell_handle_p cellHandle,
199   struct rx_connection *server,
200   unsigned int partition,
201   unsigned int volumeId,
202   afs_status_p st)
203 {
204     int rc = 0;
205     afs_status_t tst = 0;
206     afs_status_t temp = 0;
207     int serverAddr = ntohl(rx_HostOf(rx_PeerOf(server)));
208
209     afs_int32 ttid = 0;
210     afs_int32 rcode;
211     struct nvldbentry entry;
212     int islocked = 0;
213     afs_int32 avoltype = -1, vtype;
214     int notondisk = 0, notinvldb = 0;
215
216     /* Find and read the VLDB entry for this volume */
217     tst = ubik_Call(VL_SetLock, cellHandle->vos, 0, volumeId, avoltype,
218                     VLOP_DELETE);
219     if (tst) {
220         if (tst != VL_NOENT) {
221             goto fail_UV_DeleteVolume;
222         }
223         notinvldb = 1;
224     } else {
225        islocked = 1;
226
227        if (!VLDB_GetEntryByID(cellHandle, volumeId, avoltype, &entry, &tst)) {
228             goto fail_UV_DeleteVolume;
229        }
230
231     }
232
233     /* Whether volume is in the VLDB or not. Delete the volume on disk */
234     tst = AFSVolTransCreate(server, volumeId, partition, ITOffline, &ttid);
235     if (tst) {
236        if (tst == VNOVOL) {
237           notondisk = 1;
238        } else {
239            goto fail_UV_DeleteVolume;
240        }
241     }
242     else {
243        tst = AFSVolDeleteVolume(server, ttid);
244        if (tst) {
245            goto fail_UV_DeleteVolume;
246        }
247        tst = AFSVolEndTrans(server, ttid, &rcode);
248        tst = (tst ? tst : rcode);
249        ttid = 0;
250        if (tst) {
251            goto fail_UV_DeleteVolume;
252        }
253     }
254
255     if (notinvldb) {
256         goto fail_UV_DeleteVolume;
257     }
258
259     if (volumeId == entry.volumeId[BACKVOL]) {
260         if ( !(entry.flags & BACK_EXISTS) || 
261              !Lp_Match(cellHandle, &entry, serverAddr, partition, &tst)) {
262            notinvldb = 2;
263            goto fail_UV_DeleteVolume;
264         }
265
266         entry.flags &= ~BACK_EXISTS;
267         vtype = BACKVOL;
268     }
269
270     else if (volumeId == entry.volumeId[ROVOL]) {
271         if (!Lp_ROMatch(cellHandle, &entry, serverAddr, partition, &tst)) {
272            notinvldb = 2;
273            goto fail_UV_DeleteVolume;
274         }
275         
276         Lp_SetROValue(cellHandle, &entry, serverAddr, partition, 0, 0);
277         entry.nServers--;
278         if (!Lp_ROMatch(cellHandle, &entry, 0, 0, &tst)) {
279             entry.flags &= ~RO_EXISTS;
280         }
281         vtype = ROVOL;
282     }
283
284     else if (volumeId == entry.volumeId[RWVOL]) {
285         if (!(entry.flags & RW_EXISTS) || 
286             !Lp_Match(cellHandle, &entry, serverAddr, partition, &tst)) {
287            notinvldb = 2;
288            goto fail_UV_DeleteVolume;
289         }
290         
291         /* Delete backup if it exists */
292         tst = AFSVolTransCreate(server, entry.volumeId[BACKVOL], partition,
293                                  ITOffline, &ttid);
294         if (!tst) {
295            tst = AFSVolDeleteVolume(server, ttid);
296            if (tst) {
297               goto fail_UV_DeleteVolume;
298            }
299            tst = AFSVolEndTrans(server, ttid, &rcode);
300            ttid = 0;
301            tst = (tst ? tst : rcode);
302            if (tst) {
303               goto fail_UV_DeleteVolume;
304            }
305         }
306
307         Lp_SetRWValue(cellHandle, &entry, serverAddr, partition, 0L, 0L);
308         entry.nServers--;
309         entry.flags &= ~(BACK_EXISTS | RW_EXISTS);
310         vtype = RWVOL;
311
312     }
313
314     else {
315        notinvldb = 2;         /* Not found on this server and partition */
316        goto fail_UV_DeleteVolume;
317     }
318
319     if ((entry.nServers <= 0) || !(entry.flags & (RO_EXISTS | RW_EXISTS))) {
320        tst = ubik_Call(VL_DeleteEntry, cellHandle->vos, 0, volumeId, vtype);
321        if (tst) {
322           goto fail_UV_DeleteVolume;
323        }
324     } else {
325        if (!VLDB_ReplaceEntry(cellHandle, volumeId, vtype, &entry,
326                         (LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP), 
327                         &tst)) {
328           goto fail_UV_DeleteVolume;
329        }
330     }
331     islocked = 0;
332     rc = 1;
333
334 fail_UV_DeleteVolume:
335
336     if (notondisk && notinvldb) {
337        if (!tst) tst = ADMVOSVOLUMENOEXIST;
338     }
339
340     if (ttid) {
341         temp = AFSVolEndTrans(server, ttid, &rcode);
342         temp = (temp ? temp : rcode);
343         if (temp) {
344             if (!tst) tst = temp;
345         }
346     }
347
348     if (islocked) {
349         temp = ubik_Call(VL_ReleaseLock,cellHandle->vos, 0, volumeId, -1, 
350                          (LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP));
351         if (temp) {
352             if (!tst) tst = temp;
353         }
354     }
355
356     if (st != NULL) {
357         *st = tst;
358     }
359     return rc;
360 }
361
362 #define ONERR(ec, es, ep) if (ec) { fprintf(STDERR, (es), (ep)); error = (ec); goto mfail; }
363
364 /* Move volume <afromvol> on <afromserver> <afrompart> to <atoserver>
365  * <atopart>. The operation is almost idempotent 
366  */
367
368 int UV_MoveVolume(
369   afs_cell_handle_p cellHandle,
370   afs_int32 afromvol,
371   afs_int32 afromserver,
372   afs_int32 afrompart,
373   afs_int32 atoserver,
374   afs_int32 atopart,
375   afs_status_p st)
376 {
377     int rc = 0;
378     afs_status_t tst = 0;
379     afs_status_t etst = 0;
380     struct rx_connection *toconn, *fromconn ;
381     afs_int32                fromtid, totid, clonetid;
382     char                 vname[64];
383     char                 *volName = 0;
384     char                 tmpName[VOLSER_MAXVOLNAME +1];
385     afs_int32                rcode;
386     afs_int32                fromDate;
387     struct restoreCookie cookie;
388     afs_int32                newVol, volid, backupId;
389     struct volser_status tstatus;
390     struct destServer    destination;
391
392     struct nvldbentry    entry;
393     int                  islocked, pntg;
394     afs_int32                error;
395     int                  same;
396     afs_int32            store_flags;
397
398 #ifdef  ENABLE_BUGFIX_1165
399     volEntries volumeInfo;
400     struct volintInfo *infop = 0;
401 #endif
402
403     islocked = 0;
404     fromconn = (struct rx_connection *)0;
405     toconn   = (struct rx_connection *)0;
406     fromtid  = 0;
407     totid    = 0;
408     clonetid = 0;
409     error    = 0;
410     volid    = 0;
411     pntg     = 0;
412     backupId = 0;
413     newVol   = 0;
414
415     if (!VLDB_GetEntryByID(cellHandle, afromvol, -1, &entry, &tst)) {
416         goto fail_UV_MoveVolume;
417     }
418
419     if (entry.volumeId[RWVOL] != afromvol)
420     {
421         tst = ADMVOSVOLUMEMOVERWONLY;
422         goto fail_UV_MoveVolume;
423     }
424
425     tst = ubik_Call(VL_SetLock, cellHandle->vos, 0,afromvol, RWVOL, VLOP_MOVE);
426     if (tst) {
427         goto fail_UV_MoveVolume;
428     }
429     islocked = 1;
430
431     if (!VLDB_GetEntryByID(cellHandle, afromvol, RWVOL, &entry, &tst)) {
432         goto fail_UV_MoveVolume;
433     }
434
435     backupId = entry.volumeId[BACKVOL];
436
437     if ( !Lp_Match(cellHandle, &entry, afromserver, afrompart, &tst) )
438     {
439         /* the from server and partition do not exist in the vldb entry corresponding to volid */
440         if ( !Lp_Match(cellHandle, &entry, atoserver, atopart, &tst) ) 
441         {
442             /* the to server and partition do not exist in the vldb entry corresponding to volid */
443             tst = ubik_Call(VL_ReleaseLock, cellHandle->vos, 0, afromvol, -1,
444                               (LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP));
445             if (tst) {
446                 goto fail_UV_MoveVolume;
447             }
448             tst = VOLSERVOLMOVED;
449             goto fail_UV_MoveVolume;
450         }
451
452         /* delete the volume afromvol on src_server */
453         /* from-info does not exist but to-info does =>
454          * we have already done the move, but the volume
455          * may still be existing physically on from fileserver
456          */
457         fromconn = UV_Bind(cellHandle, afromserver, AFSCONF_VOLUMEPORT);
458         fromtid = 0;
459         pntg = 1;
460
461         tst = AFSVolTransCreate(fromconn, afromvol, afrompart, ITOffline, &fromtid);
462         if (!tst) 
463         {   /* volume exists - delete it */
464             tst = AFSVolSetFlags(fromconn, fromtid, VTDeleteOnSalvage | VTOutOfService);
465             if  (tst) {
466                 goto fail_UV_MoveVolume;
467             }
468
469             tst = AFSVolDeleteVolume(fromconn,fromtid);
470             if  (tst) {
471                 goto fail_UV_MoveVolume;
472             }
473             
474             tst = AFSVolEndTrans(fromconn, fromtid, &rcode);
475             fromtid = 0;
476             if (!tst) tst = rcode;
477             if  (tst) {
478                 goto fail_UV_MoveVolume;
479             }
480         }
481
482         /*delete the backup volume now */
483         fromtid = 0;
484         tst = AFSVolTransCreate(fromconn, backupId, afrompart, ITOffline, &fromtid);
485         if (!tst) 
486         {   /* backup volume exists - delete it */
487             tst = AFSVolSetFlags(fromconn, fromtid, VTDeleteOnSalvage | VTOutOfService);
488             if  (tst) {
489                 goto fail_UV_MoveVolume;
490             }
491
492             tst = AFSVolDeleteVolume(fromconn,fromtid);
493             if  (tst) {
494                 goto fail_UV_MoveVolume;
495             }
496
497             tst = AFSVolEndTrans(fromconn, fromtid, &rcode);
498             fromtid = 0;
499             if (!tst) tst = rcode;
500             if  (tst) {
501                 goto fail_UV_MoveVolume;
502             }
503         }
504
505         fromtid = 0;
506         error = 0;
507         goto fail_UV_MoveVolume;
508     }
509
510     /* From-info matches the vldb info about volid,
511      * its ok start the move operation, the backup volume 
512      * on the old site is deleted in the process 
513      */
514     if (afrompart == atopart) 
515     {
516         if (!VLDB_IsSameAddrs(cellHandle, afromserver, atoserver, &same, &tst)) {
517             goto fail_UV_MoveVolume;
518         }
519         if (same) {
520             tst = VOLSERVOLMOVED;
521             goto fail_UV_MoveVolume;
522         }
523     }
524
525     pntg = 1;
526     toconn   = UV_Bind(cellHandle, atoserver,   AFSCONF_VOLUMEPORT); /* get connections to the servers */
527     fromconn = UV_Bind(cellHandle, afromserver, AFSCONF_VOLUMEPORT);
528     fromtid = totid = 0;        /* initialize to uncreated */
529
530     /* ***
531      * clone the read/write volume locally.
532      * ***/
533
534     tst = AFSVolTransCreate(fromconn, afromvol, afrompart, ITBusy, &fromtid);
535     if (tst) {
536         goto fail_UV_MoveVolume;
537     }
538
539     /* Get a clone id */
540     newVol = 0;
541     tst = ubik_Call (VL_GetNewVolumeId, cellHandle->vos, 0, 1, &newVol);
542     if (tst) {
543         goto fail_UV_MoveVolume;
544     }
545
546     /* Do the clone. Default flags on clone are set to delete on salvage and out of service */
547     strcpy(vname, "move-clone-temp");
548     tst = AFSVolClone(fromconn, fromtid, 0,readonlyVolume, vname, &newVol);
549     if (tst) {
550         goto fail_UV_MoveVolume;
551     }
552
553     /* lookup the name of the volume we just cloned */
554     volid = afromvol;
555     tst = AFSVolGetName(fromconn, fromtid, &volName);
556     if (tst) {
557         goto fail_UV_MoveVolume;
558     }
559
560     rcode = 0;
561     tst = AFSVolEndTrans(fromconn, fromtid, &rcode);
562     fromtid = 0;
563     if (!tst) tst = rcode;
564     if (tst) {
565         goto fail_UV_MoveVolume;
566     }
567
568     /* ***
569      * Create the destination volume
570      * ***/
571
572     tst = AFSVolTransCreate (fromconn, newVol, afrompart, ITOffline, &clonetid);
573     if (tst) {
574         goto fail_UV_MoveVolume;
575     }
576     tst = AFSVolSetFlags (fromconn, clonetid, VTDeleteOnSalvage|VTOutOfService); /*redundant */
577     if (tst) {
578         goto fail_UV_MoveVolume;
579     }
580
581     /* remember time from which we've dumped the volume */
582     tst = AFSVolGetStatus (fromconn, clonetid, &tstatus);
583     if (tst) {
584         goto fail_UV_MoveVolume;
585     }
586
587     fromDate = tstatus.creationDate-CLOCKSKEW;
588
589 #ifdef  ENABLE_BUGFIX_1165
590     /*
591      * Get the internal volume state from the source volume. We'll use such info (i.e. dayUse)
592      * to copy it to the new volume (via AFSSetInfo later on) so that when we move volumes we
593      * don't use this information...
594      */
595     volumeInfo.volEntries_val = (volintInfo *)0;/*this hints the stub to allocate space*/
596     volumeInfo.volEntries_len = 0;
597     tst = AFSVolListOneVolume(fromconn, afrompart, afromvol, &volumeInfo);
598     if (tst) {
599         goto fail_UV_MoveVolume;
600     }
601
602     infop = (volintInfo *) volumeInfo.volEntries_val;
603     infop->maxquota = -1;                       /* Else it will replace the default quota */
604 #endif
605
606     /* create a volume on the target machine */
607     volid = afromvol;
608     tst = AFSVolTransCreate (toconn, volid, atopart, ITOffline, &totid);
609     if (!tst) 
610     {   /*delete the existing volume */
611
612         tst = AFSVolDeleteVolume(toconn, totid);
613         if (tst) {
614             goto fail_UV_MoveVolume;
615         }
616         
617         tst = AFSVolEndTrans(toconn, totid, &rcode);
618         totid = 0;
619         if (!tst) tst = rcode;
620         if (tst) {
621             goto fail_UV_MoveVolume;
622         }
623
624     }
625
626     tst = AFSVolCreateVolume (toconn, atopart, volName, volser_RW, volid, &volid, &totid);
627     if (tst) {
628         goto fail_UV_MoveVolume;
629     }
630
631     strncpy(tmpName, volName, VOLSER_OLDMAXVOLNAME);
632     free(volName);
633     volName = (char *) 0;
634
635     tst = AFSVolSetFlags (toconn, totid, (VTDeleteOnSalvage | VTOutOfService));
636     if (tst) {
637         goto fail_UV_MoveVolume;
638     }
639
640     /***
641      * Now dump the clone to the new volume
642      ***/
643
644     destination.destHost = atoserver;
645     destination.destPort = AFSCONF_VOLUMEPORT;
646     destination.destSSID = 1;
647
648     /* Copy the clone to the new volume */
649     strncpy(cookie.name,tmpName,VOLSER_OLDMAXVOLNAME);
650     cookie.type   = RWVOL;
651     cookie.parent = entry.volumeId[RWVOL];
652     cookie.clone  = 0;
653     tst = AFSVolForward(fromconn, clonetid, 0, &destination, totid, &cookie);
654     if (tst) {
655         goto fail_UV_MoveVolume;
656     }
657
658     tst = AFSVolEndTrans(fromconn, clonetid, &rcode);
659     if (!tst) tst = rcode;
660     clonetid = 0;
661     if (tst) {
662         goto fail_UV_MoveVolume;
663     }
664
665     /* ***
666      * reattach to the main-line volume, and incrementally dump it.
667      * ***/
668
669     tst = AFSVolTransCreate(fromconn, afromvol, afrompart, ITBusy, &fromtid);
670     if (tst) {
671         goto fail_UV_MoveVolume;
672     }
673
674     /* now do the incremental */
675     tst = AFSVolForward(fromconn, fromtid, fromDate, &destination, totid,&cookie);
676     if (tst) {
677         goto fail_UV_MoveVolume;
678     }
679
680     /* now adjust the flags so that the new volume becomes official */
681     tst = AFSVolSetFlags(fromconn, fromtid, VTOutOfService);
682     if (tst) {
683         goto fail_UV_MoveVolume;
684     }
685
686     tst = AFSVolSetFlags(toconn, totid, 0);
687     if (tst) {
688         goto fail_UV_MoveVolume;
689     }
690
691 #ifdef  ENABLE_BUGFIX_1165
692     tst = AFSVolSetInfo(toconn, totid, infop);
693     if (tst) {
694         goto fail_UV_MoveVolume;
695     }
696 #endif
697
698     /* put new volume online */
699     tst = AFSVolEndTrans(toconn, totid, &rcode);
700     totid = 0;
701     if (!tst) tst = rcode;
702     if (tst) {
703         goto fail_UV_MoveVolume;
704     }
705
706     Lp_SetRWValue(cellHandle, &entry, afromserver, afrompart,
707                   atoserver, atopart);
708     store_flags = entry.flags;
709     entry.flags &= ~BACK_EXISTS;
710
711     if (!VLDB_ReplaceEntry(cellHandle, afromvol, -1, &entry, 
712                            (LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP),
713                            &tst)) {
714         goto fail_UV_MoveVolume;
715     }
716     entry.flags = store_flags;
717     islocked=0;
718
719     if (atoserver != afromserver) 
720     {
721         /* set forwarding pointer for moved volumes */
722         tst = AFSVolSetForwarding(fromconn, fromtid, htonl(atoserver));
723         if (tst) {
724             goto fail_UV_MoveVolume;
725         }
726     }
727
728     tst = AFSVolDeleteVolume(fromconn,fromtid); /* zap original volume */
729     if (tst) {
730         goto fail_UV_MoveVolume;
731     }
732     
733     tst = AFSVolEndTrans(fromconn, fromtid, &rcode);
734     fromtid = 0;
735     if (!tst) tst = rcode;
736     if (tst) {
737         goto fail_UV_MoveVolume;
738     }
739
740     /* Delete the backup volume on the original site */
741     tst = AFSVolTransCreate(fromconn, backupId, afrompart, ITOffline, &fromtid);
742     if (!tst) 
743     {
744         tst = AFSVolSetFlags(fromconn, fromtid, VTDeleteOnSalvage | VTOutOfService);
745         if (tst) {
746             goto fail_UV_MoveVolume;
747         }
748
749         tst = AFSVolDeleteVolume(fromconn,fromtid);
750         if (tst) {
751             goto fail_UV_MoveVolume;
752         }
753         
754         tst = AFSVolEndTrans(fromconn,fromtid, &rcode);
755         fromtid = 0;
756         if (!tst) tst = rcode;
757         if (tst) {
758             goto fail_UV_MoveVolume;
759         }
760
761     }
762     else tst = 0;               /* no backup volume? that's okay */
763
764     fromtid = 0;
765
766     tst = AFSVolTransCreate(fromconn, newVol, afrompart, ITOffline, &clonetid);
767     if (tst) {
768         goto fail_UV_MoveVolume;
769     }
770
771     /* now delete the clone */
772
773     tst = AFSVolDeleteVolume(fromconn, clonetid);
774     if (tst) {
775         goto fail_UV_MoveVolume;
776     }
777     
778     tst = AFSVolEndTrans(fromconn, clonetid, &rcode);
779     if (!tst) tst = rcode;
780     clonetid = 0;
781     if (tst) {
782         goto fail_UV_MoveVolume;
783     }
784
785     /* fall through */
786     /* END OF MOVE */
787
788     /* normal cleanup code */
789
790     if (islocked)
791     {
792         etst = ubik_Call(VL_ReleaseLock,cellHandle->vos, 0, afromvol, -1, 
793                           (LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP));
794         if (etst) 
795         {
796             if (!tst) tst = etst;
797         }
798     }
799     
800     if (fromtid) 
801     {
802         etst = AFSVolEndTrans(fromconn, fromtid, &rcode);
803         if (etst || rcode)
804         {
805             if (!tst) tst = (etst ? etst : rcode);
806         }
807     }
808
809     if (clonetid) 
810     {
811         etst = AFSVolEndTrans(fromconn, clonetid, &rcode);
812         if (etst || rcode) 
813         {
814             if (!tst) tst = (etst ? etst : rcode);
815         }
816     }
817
818     if (totid) 
819     {
820         etst = AFSVolEndTrans(toconn, totid, &rcode);
821         if (etst) 
822         {
823             if (!tst) tst = (etst ? etst : rcode);
824         }
825     }
826     if (volName) free(volName);
827 #ifdef  ENABLE_BUGFIX_1165
828     if (infop)   free(infop);
829 #endif
830     if (fromconn) rx_ReleaseCachedConnection(fromconn);
831     if (toconn)   rx_ReleaseCachedConnection(toconn);
832
833     rc = 1;
834     if (st != NULL) {
835         *st = tst;
836     }
837     return rc;
838
839     /* come here only when the sky falls */
840
841 fail_UV_MoveVolume:
842
843     /* unlock VLDB entry */
844     if (islocked)
845         ubik_Call(VL_ReleaseLock, cellHandle->vos, 0, afromvol, -1,
846                   (LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP));
847
848     if (clonetid) AFSVolEndTrans(fromconn, clonetid, &rcode);
849     if (totid)    AFSVolEndTrans(toconn, totid, &rcode);
850     if (fromtid)
851     {  /* put it on-line */
852         AFSVolSetFlags(fromconn,fromtid,0);
853         AFSVolEndTrans(fromconn, fromtid, &rcode);
854     }
855
856     if (!VLDB_GetEntryByID (cellHandle, afromvol, -1, &entry, &tst)) {
857         goto done;
858     }
859
860     /* Delete either the volume on the source location or the target location. 
861      * If the vldb entry still points to the source location, then we know the
862      * volume move didn't finish so we remove the volume from the target 
863      * location. Otherwise, we remove the volume from the source location.
864      */
865     if (Lp_Match(cellHandle, &entry, afromserver,afrompart,&tst)) {  /* didn't move - delete target volume */
866
867         if (volid && toconn) {
868             tst=AFSVolTransCreate(toconn,volid,atopart, ITOffline,&totid);
869             if (!tst) {
870                 AFSVolSetFlags(toconn,totid, VTDeleteOnSalvage | VTOutOfService);
871                 AFSVolDeleteVolume(toconn,totid);
872                 AFSVolEndTrans(toconn,totid,&rcode);
873             }
874         }
875
876         /* put source volume on-line */
877         if (fromconn) {
878             tst=AFSVolTransCreate(fromconn, afromvol, afrompart, ITBusy, &fromtid);
879             if (!tst) {
880                 AFSVolSetFlags(fromconn,fromtid,0);
881                 AFSVolEndTrans(fromconn,fromtid,&rcode);
882             }
883         }
884     }
885     else {      /* yep, move complete */
886         /* delete backup volume */
887         if (fromconn) {
888             tst=AFSVolTransCreate (fromconn,backupId,afrompart, ITOffline,&fromtid);
889             if (!tst) {
890                 AFSVolSetFlags(fromconn,fromtid, VTDeleteOnSalvage | VTOutOfService);
891                 AFSVolDeleteVolume(fromconn,fromtid);
892                 AFSVolEndTrans(fromconn,fromtid,&rcode);
893             }
894
895             /* delete source volume */
896             tst=AFSVolTransCreate (fromconn, afromvol, afrompart, ITBusy, &fromtid);
897             if (!tst) {
898                 AFSVolSetFlags(fromconn,fromtid, VTDeleteOnSalvage | VTOutOfService);
899                 if (atoserver != afromserver)
900                     AFSVolSetForwarding(fromconn,fromtid,htonl(atoserver));
901                 AFSVolDeleteVolume(fromconn,fromtid);
902                 AFSVolEndTrans(fromconn,fromtid,&rcode);
903             }
904         }
905     }
906
907     /* common cleanup - delete local clone */
908     if (newVol) {
909         tst = AFSVolTransCreate (fromconn, newVol, afrompart, ITOffline, &clonetid);
910         if (!tst) {
911             AFSVolDeleteVolume(fromconn,clonetid);
912             AFSVolEndTrans(fromconn,clonetid,&rcode);
913         }
914     }
915
916     /* unlock VLDB entry */
917     ubik_Call (VL_ReleaseLock, cellHandle->vos, 0, afromvol, -1,
918                (LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP));
919
920 done:   /* routine cleanup */
921     if (volName)  free(volName);
922 #ifdef  ENABLE_BUGFIX_1165
923     if (infop)    free(infop);
924 #endif
925     if (fromconn) rx_ReleaseCachedConnection(fromconn);
926     if (toconn)   rx_ReleaseCachedConnection(toconn);
927
928     if (st != NULL) {
929         *st = tst;
930     }
931     return rc;
932 }
933
934 /* Make a new backup of volume <avolid> on <aserver> and <apart> 
935  * if one already exists, update it 
936  */
937
938 int UV_BackupVolume(
939   afs_cell_handle_p cellHandle,
940   afs_int32 aserver,
941   afs_int32 apart,
942   afs_int32 avolid,
943   afs_status_p st)
944 {
945     int rc = 0;
946     afs_status_t tst = 0, temp = 0;
947     afs_int32 ttid = 0, btid = 0;
948     afs_int32 backupID;
949     afs_int32 code = 0, rcode = 0;
950     char vname[VOLSER_MAXVOLNAME +1];
951     struct nvldbentry entry;
952     afs_int32 error = 0;
953     int vldblocked = 0, vldbmod = 0, backexists = 1;
954     struct rx_connection *aconn = UV_Bind(cellHandle, aserver,
955                                           AFSCONF_VOLUMEPORT);
956
957
958     /* the calls to VLDB will succeed only if avolid is a RW volume,
959      * since we are following the RW hash chain for searching */
960     if(!VLDB_GetEntryByID(cellHandle, avolid, RWVOL, &entry, &tst)) {
961         goto fail_UV_BackupVolume;
962     }
963
964     /* These operations require the VLDB be locked since it means the VLDB
965      * will change or the vldb is already locked.
966      */
967     if (!(entry.flags & BACK_EXISTS)   || /* backup volume doesnt exist */
968          (entry.flags & VLOP_ALLOPERS) || /* vldb lock already held */
969          (entry.volumeId[BACKVOL] == INVALID_BID)) {
970         /* no assigned backup volume id */
971
972         tst = ubik_Call(VL_SetLock, cellHandle->vos, 0, avolid, RWVOL,
973                         VLOP_BACKUP);
974         if (tst) {
975             goto fail_UV_BackupVolume;
976         }
977         vldblocked = 1;
978
979         /* Reread the vldb entry */
980         if (!VLDB_GetEntryByID(cellHandle, avolid, RWVOL, &entry, &tst)) {
981             goto fail_UV_BackupVolume;
982         }
983     }
984
985     if (!ISNAMEVALID(entry.name)) {
986         tst = VOLSERBADNAME;
987         goto fail_UV_BackupVolume;
988     }
989
990     backupID = entry.volumeId[BACKVOL];
991     if (backupID == INVALID_BID) {
992         /* Get a backup volume id from the VLDB and update the vldb
993          * entry with it. 
994          */
995         tst = ubik_Call(VL_GetNewVolumeId, cellHandle->vos, 0, 1, &backupID);
996         if (tst) {
997             goto fail_UV_BackupVolume;
998         }
999         entry.volumeId[BACKVOL] = backupID;
1000         vldbmod = 1;
1001     }
1002
1003     /* Test to see if the backup volume exists by trying to create
1004      * a transaction on the backup volume. We've assumed the backup exists.
1005      */
1006     tst = AFSVolTransCreate(aconn, backupID, apart, ITOffline, &btid);
1007     if (tst) {
1008         if (tst != VNOVOL) {
1009             goto fail_UV_BackupVolume;
1010         }
1011         backexists = 0;                 /* backup volume does not exist */
1012     }
1013     if (btid) {
1014         tst = AFSVolEndTrans(aconn, btid, &rcode);
1015         btid = 0;
1016         if (tst || rcode) {
1017             tst = (tst ? tst : rcode);
1018             goto fail_UV_BackupVolume;
1019         }
1020     }
1021
1022     /* Now go ahead and try to clone the RW volume.
1023      * First start a transaction on the RW volume 
1024      */
1025     tst = AFSVolTransCreate(aconn, avolid, apart, ITBusy, &ttid);
1026     if (tst) {
1027         goto fail_UV_BackupVolume;
1028     }
1029
1030     /* Clone or reclone the volume, depending on whether the backup 
1031      * volume exists or not
1032      */
1033     if (backexists) {
1034         tst = AFSVolReClone(aconn, ttid, backupID);
1035         if (tst) {
1036             goto fail_UV_BackupVolume;
1037         }
1038     }
1039     else {
1040        strcpy(vname, entry.name);
1041        strcat(vname,".backup");
1042
1043        tst = AFSVolClone(aconn, ttid, 0,backupVolume, vname, &backupID);
1044        if (tst) {
1045             goto fail_UV_BackupVolume;
1046        }
1047     }
1048
1049     /* End transaction on the RW volume */
1050     tst = AFSVolEndTrans(aconn, ttid, &rcode);
1051     ttid = 0;
1052     if (tst || rcode) {
1053         tst = (tst ? tst : rcode);
1054         goto fail_UV_BackupVolume;
1055     }
1056
1057     /* Mork vldb as backup exists */
1058     if (!(entry.flags & BACK_EXISTS)) {
1059         entry.flags |= BACK_EXISTS;
1060         vldbmod = 1;
1061     }
1062
1063     /* Now go back to the backup volume and bring it on line */
1064     tst = AFSVolTransCreate(aconn, backupID, apart, ITOffline, &btid);
1065     if (tst) {
1066         goto fail_UV_BackupVolume;
1067     }
1068
1069     tst = AFSVolSetFlags(aconn, btid, 0);
1070     if (tst) {
1071         goto fail_UV_BackupVolume;
1072     }
1073
1074     tst = AFSVolEndTrans(aconn, btid, &rcode);
1075     btid = 0;
1076     if (tst || rcode) {
1077         tst = (tst ? tst : rcode);
1078         goto fail_UV_BackupVolume;
1079     }
1080     rc = 1;
1081
1082     /* Will update the vldb below */
1083
1084 fail_UV_BackupVolume:
1085
1086     if (ttid) {
1087        temp =  AFSVolEndTrans(aconn, ttid, &rcode);
1088        if (temp || rcode) {
1089           if (!tst)
1090              tst = (temp ? temp : rcode);
1091        }
1092     }
1093
1094     if (btid) {
1095        temp = AFSVolEndTrans(aconn, btid, &rcode);
1096        if (temp || rcode) {
1097           if (!tst)
1098              tst = (temp ? temp : rcode);
1099        }
1100     }
1101
1102     /* Now update the vldb - if modified */
1103     if (vldblocked) {
1104         if (vldbmod) {
1105             if(!VLDB_ReplaceEntry(cellHandle, avolid, RWVOL, &entry,
1106             (LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP), &temp)) {
1107                 if (!tst) {
1108                     tst = temp;
1109                 }
1110             }
1111         } else {
1112             temp = ubik_Call(VL_ReleaseLock, cellHandle->vos, 0, avolid, RWVOL, 
1113             (LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP));
1114             if (temp) {
1115                 if (!tst) {
1116                     tst = temp;
1117                 }
1118             }
1119         }
1120     }
1121
1122     if (aconn) {
1123        rx_ReleaseCachedConnection(aconn);
1124     }
1125
1126     if (st != NULL) {
1127         *st = tst;
1128     }
1129     return rc;
1130 }
1131
1132 static int DelVol (
1133   struct rx_connection *conn,
1134   afs_int32 vid,
1135   afs_int32 part,
1136   afs_int32 flags)
1137 {
1138     afs_int32 acode, ccode, rcode, tid;
1139     ccode = rcode = tid = 0;
1140
1141     acode = AFSVolTransCreate(conn, vid, part, flags, &tid);
1142     if (!acode) {              /* It really was there */
1143         acode = AFSVolDeleteVolume(conn, tid);
1144         ccode = AFSVolEndTrans(conn, tid, &rcode);
1145         if (!ccode) ccode = rcode;
1146     }
1147
1148     return acode;
1149 }
1150
1151 #define ONERROR(ec, ep, es) if (ec) { fprintf(STDERR, (es), (ep)); error = (ec); goto rfail; }
1152 #define ERROREXIT(ec) { error = (ec); goto rfail; }
1153
1154 static int CloneVol (
1155   afs_cell_handle_p cellHandle,
1156   struct rx_connection *conn,
1157   afs_int32 rwvid,
1158   afs_int32 part,
1159   afs_int32 *rovidp,
1160   int nottemp,
1161   struct nvldbentry *entry,
1162   afs_int32 *vidCreateDate,
1163   afs_status_p st)
1164 {
1165     int rc = 0;
1166     afs_status_t tst = 0, etst = 0;
1167     afs_int32 rcode = 0, tid = 0;
1168     struct volser_status volstatus;
1169     char vname[64];
1170
1171     /* Begin transaction on RW volume marking it busy (clients will wait) */
1172     tst = AFSVolTransCreate(conn, rwvid, part, ITBusy, &tid);
1173     if (tst) {
1174         goto fail_CloneVol;
1175     }
1176
1177     /* Get the RO volume id. Allocate a new one if need to */
1178     *rovidp = entry->volumeId[ROVOL];
1179     if (*rovidp == INVALID_BID) {
1180         tst = ubik_Call(VL_GetNewVolumeId, cellHandle->vos, 0, 1, rovidp);
1181         if (tst) {
1182             goto fail_CloneVol;
1183         }
1184
1185         entry->volumeId[ROVOL] = *rovidp;
1186     }
1187
1188     /* If we are creating the ro clone, what are we calling it.
1189     * Depends on whether its a temporary clone or not.
1190     */
1191     if (nottemp) {
1192         strcpy(vname, entry->name);
1193         strcat(vname, ".readonly");
1194     } else {
1195         strcpy(vname, "readonly-clone-temp"); /* Should be unique? */
1196     }
1197
1198     /* Create the new clone. If it exists, then reclone it */
1199     tst = AFSVolClone(conn, tid, 0, readonlyVolume, vname, rovidp);
1200     if (tst == VVOLEXISTS) {
1201         tst = AFSVolReClone(conn, tid, *rovidp);
1202         if (tst) {
1203             goto fail_CloneVol;
1204         }
1205     }
1206     if (tst) {
1207         goto fail_CloneVol;
1208     }
1209
1210     /* Bring the volume back on-line as soon as possible */
1211     if (nottemp) {
1212         afs_int32 fromtid=0;
1213
1214         /* Now bring the RO clone on-line */
1215         tst = AFSVolTransCreate(conn, *rovidp, part, ITOffline, &fromtid);
1216         if (tst) {
1217             goto fail_CloneVol;
1218         }
1219
1220         tst = AFSVolSetFlags(conn, fromtid, 0);
1221         if (tst) {
1222             goto fail_CloneVol;
1223         }
1224
1225         tst = AFSVolEndTrans(conn, fromtid, &rcode);
1226         fromtid = 0;
1227         if (!tst) tst = rcode;
1228         if (tst) {
1229             goto fail_CloneVol;
1230         }
1231     }
1232
1233     /* Get the time the RW was created for return information */
1234     tst = AFSVolGetStatus(conn, tid, &volstatus);
1235     if (tst) {
1236         goto fail_CloneVol;
1237     }
1238     *vidCreateDate = volstatus.creationDate;
1239     rc = 1;
1240
1241 fail_CloneVol:
1242
1243     if (tid) {
1244         tst = AFSVolEndTrans(conn, tid, &rcode);
1245         tid = 0;
1246         if (!tst) tst = rcode;
1247         if (tst) {
1248             rc = 0;
1249             goto fail_CloneVol;
1250         }
1251     }
1252
1253     if (st != NULL) {
1254         *st = tst;
1255     }
1256     return rc;
1257 }
1258
1259 /* Get a "transaction" on this replica.  Create the volume 
1260  * if necessary.  Return the time from which a dump should
1261  * be made (0 if it's a new volume)
1262  */
1263 static int GetTrans (
1264   afs_cell_handle_p cellHandle,
1265   struct nvldbentry *vldbEntryPtr,
1266   afs_int32 index,
1267   struct rx_connection **connPtr,
1268   afs_int32 *transPtr,
1269   afs_int32 *timePtr,
1270   afs_status_p st)
1271 {
1272     int rc = 0;
1273     afs_status_t tst = 0, etst = 0;
1274     afs_int32 volid;
1275     struct volser_status tstatus;
1276     int rcode;
1277
1278     *connPtr  = (struct rx_connection *)0;
1279     *timePtr  = 0;
1280     *transPtr = 0;
1281
1282     /* get connection to the replication site */
1283     *connPtr = UV_Bind(cellHandle, vldbEntryPtr->serverNumber[index],
1284                        AFSCONF_VOLUMEPORT);
1285     if (!*connPtr) {
1286         /* server is down */
1287         tst = -1;
1288         goto fail_GetTrans;
1289     }
1290
1291     volid = vldbEntryPtr->volumeId[ROVOL];
1292     if (volid) {
1293         tst = AFSVolTransCreate(*connPtr, volid,
1294                                 vldbEntryPtr->serverPartition[index],
1295                                 ITOffline, transPtr);
1296     }
1297
1298     /* If the volume does not exist, create it */
1299     if (!volid || tst) {
1300         char volname[64];
1301
1302         if (volid && (tst != VNOVOL)){
1303             goto fail_GetTrans;
1304         }
1305
1306         strcpy(volname, vldbEntryPtr->name);
1307         strcat(volname, ".readonly");
1308
1309         tst = AFSVolCreateVolume(*connPtr,
1310                                  vldbEntryPtr->serverPartition[index], 
1311                                  volname, volser_RO,
1312                                  vldbEntryPtr->volumeId[RWVOL], &volid,
1313                                  transPtr);
1314         if (tst) {
1315             goto fail_GetTrans;
1316         }
1317         vldbEntryPtr->volumeId[ROVOL] = volid;
1318
1319         /* The following is a bit redundant, since create sets these flags by default */
1320         tst = AFSVolSetFlags(*connPtr, *transPtr,
1321                              VTDeleteOnSalvage | VTOutOfService);
1322         if (tst) {
1323             goto fail_GetTrans;
1324         }
1325     }
1326
1327     /* Otherwise, the transaction did succeed, so get the creation date of the
1328     * latest RO volume on the replication site 
1329     */
1330     else {
1331         tst  = AFSVolGetStatus(*connPtr, *transPtr, &tstatus);
1332         if (tst) {
1333             goto fail_GetTrans;
1334         }
1335         *timePtr = tstatus.creationDate-CLOCKSKEW;
1336     }
1337     rc = 1;
1338
1339 fail_GetTrans:
1340
1341     if ((rc == 0) && (*transPtr)) {
1342         etst = AFSVolEndTrans(*connPtr, *transPtr, &rcode);
1343         *transPtr = 0;
1344         if (!etst) etst = rcode;
1345     }
1346
1347     if (st != NULL) {
1348         *st = tst;
1349     }
1350     return rc;
1351 }
1352
1353 static int SimulateForwardMultiple(
1354   struct rx_connection *fromconn,
1355   afs_int32 fromtid,
1356   afs_int32 fromdate,
1357   manyDests *tr,
1358   afs_int32 flags,
1359   void *cookie,
1360   manyResults *results)
1361 {
1362     int i;
1363
1364     for (i=0; i<tr->manyDests_len; i++) {
1365         results->manyResults_val[i] = 
1366             AFSVolForward(fromconn, fromtid, fromdate,
1367                           &(tr->manyDests_val[i].server),
1368                           tr->manyDests_val[i].trans, cookie);
1369     }
1370     return 0;
1371 }
1372
1373
1374 static int rel_compar (
1375   struct release *r1,
1376   struct release *r2)
1377 {
1378   return (r1->time - r2->time);
1379 }
1380
1381 /* VolumeExists()
1382  *      Determine if a volume exists on a server and partition.
1383  *      Try creating a transaction on the volume. If we can,
1384  *      the volume exists, if not, then return the error code.
1385  *      Some error codes mean the volume is unavailable but
1386  *      still exists - so we catch these error codes.
1387  */
1388 static afs_int32 VolumeExists(
1389   afs_cell_handle_p cellHandle,
1390   afs_int32 server,
1391   afs_int32 partition,
1392   afs_int32 volumeid,
1393   afs_status_p st)
1394 {
1395    int rc = 0;
1396    afs_status_t tst = -1;
1397    struct rx_connection *conn=(struct rx_connection *)0;
1398    volEntries           volumeInfo;
1399  
1400    conn = UV_Bind(cellHandle, server, AFSCONF_VOLUMEPORT);
1401    if (conn) {
1402       volumeInfo.volEntries_val = (volintInfo *)0;
1403       volumeInfo.volEntries_len = 0;
1404       tst = AFSVolListOneVolume(conn, partition, volumeid, &volumeInfo);
1405       if (volumeInfo.volEntries_val)
1406          free(volumeInfo.volEntries_val);
1407       if (tst == VOLSERILLEGAL_PARTITION) {
1408          tst = ENODEV;
1409       }
1410       rx_ReleaseCachedConnection(conn);
1411    }
1412    rc = 1;
1413
1414    if (st != NULL) {
1415        *st = tst;
1416    } 
1417    return rc;
1418 }
1419
1420 /* release volume <afromvol> on <afromserver> <afrompart> to all the
1421  * sites if forceflag is 1.If its 0 complete the release if the previous
1422  * release aborted else start a new release */
1423 int UV_ReleaseVolume(
1424   afs_cell_handle_p cellHandle,
1425   afs_int32 afromvol,
1426   afs_int32 afromserver,
1427   afs_int32 afrompart,
1428   int forceflag,
1429   afs_status_p st)
1430 {
1431     int rc = 0;
1432     afs_status_t tst = 0, etst = 0;
1433
1434   char vname[64];
1435   afs_int32 rcode;
1436   afs_int32 cloneVolId, roVolId;
1437   struct replica *replicas=0;
1438   struct nvldbentry entry;
1439   int i, volcount, m, fullrelease, vldbindex;
1440   int failure;
1441   struct restoreCookie cookie;
1442   struct rx_connection **toconns=0;
1443   struct release *times=0;
1444   int nservers = 0;
1445   struct rx_connection *fromconn = (struct rx_connection *)0;
1446   afs_int32 error = 0;
1447   int islocked = 0;
1448   afs_int32 clonetid=0, onlinetid;
1449   afs_int32 fromtid=0;
1450   afs_uint32 fromdate, thisdate;
1451   int s;
1452   manyDests tr;
1453   manyResults results;
1454   int rwindex, roindex, roclone, roexists;
1455   afs_int32 rwcrdate;
1456   struct rtime {
1457     int     validtime;
1458     afs_uint32 time;
1459   } remembertime[NMAXNSERVERS];
1460   int releasecount = 0;
1461   struct volser_status volstatus;
1462
1463   bzero((char *)remembertime, sizeof(remembertime));
1464   bzero((char *)&results, sizeof(results));
1465
1466   tst = ubik_Call(VL_SetLock, cellHandle->vos, 0, afromvol, RWVOL, VLOP_RELEASE);
1467   if ((tst) && (tst != VL_RERELEASE)) {
1468       goto fail_UV_ReleaseVolume;
1469   }
1470   islocked = 1;
1471
1472   /* Get the vldb entry in readable format */
1473   if (!VLDB_GetEntryByID (cellHandle, afromvol, RWVOL, &entry, &tst)) {
1474       goto fail_UV_ReleaseVolume;
1475   }  
1476
1477   if (!ISNAMEVALID(entry.name)) {
1478       tst = VOLSERBADNAME;
1479       goto fail_UV_ReleaseVolume;
1480   }  
1481
1482   if (entry.volumeId[RWVOL] != afromvol) {
1483       tst = ADMVOSVOLUMERELEASERWONLY;
1484       goto fail_UV_ReleaseVolume;
1485   }  
1486
1487   if (entry.nServers <= 1) {
1488       tst = ADMVOSVOLUMENOREPLICAS;
1489       goto fail_UV_ReleaseVolume;
1490   }  
1491
1492   if (strlen(entry.name) > (VOLSER_OLDMAXVOLNAME - 10)) {
1493       tst = VOLSERBADNAME;
1494       goto fail_UV_ReleaseVolume;
1495   }  
1496
1497   /* roclone is true if one of the RO volumes is on the same
1498    * partition as the RW volume. In this case, we make the RO volume
1499    * on the same partition a clone instead of a complete copy.
1500    */
1501   
1502   roindex = Lp_ROMatch(cellHandle, &entry, afromserver, afrompart, &tst) - 1;
1503   roclone = ((roindex == -1) ? 0 : 1);
1504   rwindex = Lp_GetRwIndex(cellHandle, &entry, 0);
1505   if (rwindex < 0) {
1506       tst = VOLSERNOVOL;
1507       goto fail_UV_ReleaseVolume;
1508   }  
1509
1510   /* Make sure we have a RO volume id to work with */
1511   if (entry.volumeId[ROVOL] == INVALID_BID) {
1512       /* need to get a new RO volume id */
1513       tst = ubik_Call(VL_GetNewVolumeId, cellHandle->vos, 0, 1, &roVolId);
1514       if (tst) {
1515           goto fail_UV_ReleaseVolume;
1516       }
1517
1518       entry.volumeId[ROVOL] = roVolId;
1519       if (!VLDB_ReplaceEntry(cellHandle, afromvol, RWVOL, &entry, 0, &tst)) {
1520           goto fail_UV_ReleaseVolume;
1521       }
1522   }
1523
1524   /* Will we be completing a previously unfinished release. -force overrides */
1525   for (fullrelease=1, i=0; (fullrelease && (i<entry.nServers)); i++) {
1526      if (entry.serverFlags[i] & NEW_REPSITE)
1527         fullrelease = 0;
1528   }
1529   if (forceflag && !fullrelease)
1530     fullrelease = 1;
1531
1532   /* Determine which volume id to use and see if it exists */
1533   cloneVolId = ((fullrelease || (entry.cloneId == 0)) ? entry.volumeId[ROVOL] : entry.cloneId);
1534   VolumeExists(cellHandle, afromserver, afrompart, cloneVolId, &tst);
1535   roexists = ((tst == ENODEV) ? 0 : 1);
1536   if (!roexists && !fullrelease)
1537      fullrelease = 1;      /* Do a full release if RO clone does not exist */
1538
1539   fromconn = UV_Bind(cellHandle, afromserver, AFSCONF_VOLUMEPORT);
1540   if (!fromconn) {
1541       tst = -1;
1542       goto fail_UV_ReleaseVolume;
1543   }
1544   
1545   if (fullrelease) {
1546      /* If the RO clone exists, then if the clone is a temporary
1547       * clone, delete it. Or if the RO clone is marked RO_DONTUSE
1548       * (it was recently added), then also delete it. We do not
1549       * want to "reclone" a temporary RO clone.
1550       */
1551      if ( roexists && 
1552          (!roclone || (entry.serverFlags[roindex] & RO_DONTUSE)) ) {
1553         tst = DelVol(fromconn, cloneVolId, afrompart, ITOffline);
1554         if (tst && (tst != VNOVOL)) {
1555             goto fail_UV_ReleaseVolume;
1556         }
1557         roexists = 0;
1558      }
1559
1560      /* Mark all the ROs in the VLDB entry as RO_DONTUSE. We don't
1561       * write this entry out to the vlserver until after the first
1562       * RO volume is released (temp RO clones don't count).
1563       */
1564      for (i=0; i<entry.nServers; i++) {
1565         entry.serverFlags[i] &= ~NEW_REPSITE;
1566         entry.serverFlags[i] |=  RO_DONTUSE;
1567      }
1568      entry.serverFlags[rwindex] |=  NEW_REPSITE;
1569      entry.serverFlags[rwindex] &= ~RO_DONTUSE;
1570       
1571      /* Begin transaction on RW and mark it busy while we clone it */
1572      tst = AFSVolTransCreate(fromconn, afromvol, afrompart, ITBusy, &clonetid);
1573      if (tst) {
1574          goto fail_UV_ReleaseVolume;
1575      }
1576
1577      /* Clone or reclone the volume */
1578      if (roexists) {
1579         tst = AFSVolReClone(fromconn, clonetid, cloneVolId);
1580         if (tst) {
1581             goto fail_UV_ReleaseVolume;
1582         }
1583      } else {
1584         if (roclone) {
1585            strcpy(vname, entry.name);
1586            strcat(vname, ".readonly");
1587         } else {
1588            strcpy(vname, "readonly-clone-temp");
1589         }
1590         tst = AFSVolClone(fromconn, clonetid, 0, readonlyVolume, vname, &cloneVolId);
1591         if (tst) {
1592             goto fail_UV_ReleaseVolume;
1593         }
1594      }
1595
1596      /* Get the time the RW was created for future information */
1597      tst = AFSVolGetStatus(fromconn, clonetid, &volstatus);
1598      if (tst) {
1599          goto fail_UV_ReleaseVolume;
1600      }
1601      rwcrdate = volstatus.creationDate;
1602
1603      /* End the transaction on the RW volume */
1604      tst = AFSVolEndTrans(fromconn, clonetid, &rcode);
1605      clonetid = 0;
1606      tst = (tst ? tst : rcode);
1607      if (tst) {
1608          goto fail_UV_ReleaseVolume;
1609      }
1610
1611      /* Remember clone volume ID in case we fail or are interrupted */
1612      entry.cloneId = cloneVolId;
1613
1614      if (roclone) {
1615         /* Bring the RO clone online - though not if it's a temporary clone */
1616         tst = AFSVolTransCreate(fromconn, cloneVolId, afrompart, ITOffline, &onlinetid);
1617         if (tst) {
1618             goto fail_UV_ReleaseVolume;
1619         }
1620
1621         etst = AFSVolSetFlags(fromconn, onlinetid, 0);
1622
1623         tst = AFSVolEndTrans(fromconn, onlinetid, &rcode);
1624         tst = (tst ? tst : rcode);
1625         if (tst) {
1626             goto fail_UV_ReleaseVolume;
1627         }
1628         if (etst) {
1629             tst = etst;
1630             goto fail_UV_ReleaseVolume;
1631         }
1632
1633         /* Sleep so that a client searching for an online volume won't
1634          * find the clone offline and then the next RO offline while the 
1635          * release brings the clone online and the next RO offline (race).
1636          * There is a fix in the 3.4 client that does not need this sleep
1637          * anymore, but we don't know what clients we have.
1638          */
1639         if (entry.nServers > 2)
1640            sleep(5);
1641
1642         /* Mark the RO clone in the VLDB as a good site (already released)*/
1643         entry.serverFlags[roindex] |=  NEW_REPSITE;
1644         entry.serverFlags[roindex] &= ~RO_DONTUSE;
1645         entry.flags                |=  RO_EXISTS;
1646
1647         releasecount++;
1648
1649         /* Write out the VLDB entry only if the clone is not a temporary
1650          * clone. If we did this to a temporary clone then we would end
1651          * up marking all the ROs as "old release" making the ROs
1652          * temporarily unavailable.
1653          */
1654         if (!VLDB_ReplaceEntry(cellHandle, afromvol, RWVOL, &entry, 0, &tst)) {
1655             goto fail_UV_ReleaseVolume;
1656         }
1657      }
1658   }  
1659
1660   /* Now we will release from the clone to the remaining RO replicas.
1661    * The first 2 ROs (counting the non-temporary RO clone) are released
1662    * individually: releasecount. This is to reduce the race condition
1663    * of clients trying to find an on-line RO volume. The remaining ROs
1664    * are released in parallel but no more than half the number of ROs
1665    * (rounded up) at a time: nservers.
1666    */
1667
1668   strcpy(vname, entry.name);
1669   strcat(vname, ".readonly");
1670   bzero(&cookie,sizeof(cookie));
1671   strncpy(cookie.name, vname, VOLSER_OLDMAXVOLNAME);
1672   cookie.type   = ROVOL;
1673   cookie.parent = entry.volumeId[RWVOL];
1674   cookie.clone  = 0;
1675
1676   nservers = entry.nServers/2;           /* how many to do at once, excluding clone */
1677   replicas   = (struct replica *)        malloc (sizeof(struct replica)*nservers+1);
1678   times      = (struct release *)        malloc (sizeof(struct release)*nservers+1);
1679   toconns    = (struct rx_connection **) malloc (sizeof(struct rx_connection *)*nservers+1);
1680   results.manyResults_val = (afs_int32 *)    malloc (sizeof(afs_int32)*nservers+1);
1681   if ( !replicas || !times || !! !results.manyResults_val || !toconns ) {
1682       tst = ADMNOMEM;
1683       goto fail_UV_ReleaseVolume;
1684   } 
1685
1686   bzero (replicas,   (sizeof(struct replica)*nservers+1));
1687   bzero (times,      (sizeof(struct release)*nservers+1));
1688   bzero (toconns,    (sizeof(struct rx_connection *)*nservers+1));
1689   bzero (results.manyResults_val, (sizeof(afs_int32)*nservers+1));
1690
1691   /* Create a transaction on the cloned volume */
1692   tst = AFSVolTransCreate(fromconn, cloneVolId, afrompart, ITBusy, &fromtid);
1693   if (tst) {
1694       goto fail_UV_ReleaseVolume;
1695   } 
1696
1697   /* For each index in the VLDB */
1698   for (vldbindex=0; vldbindex<entry.nServers; ) {
1699
1700      /* Get a transaction on the replicas. Pick replacas which have an old release. */
1701      for (volcount=0; ((volcount<nservers) && (vldbindex<entry.nServers)); vldbindex++) {
1702         /* The first two RO volumes will be released individually.
1703          * The rest are then released in parallel. This is a hack
1704          * for clients not recognizing right away when a RO volume
1705          * comes back on-line.
1706          */
1707         if ((volcount == 1) && (releasecount < 2))
1708            break;
1709
1710         if (vldbindex == roindex) continue;              /* the clone    */
1711         if ( (entry.serverFlags[vldbindex] & NEW_REPSITE) &&
1712             !(entry.serverFlags[vldbindex] & RO_DONTUSE) ) continue;
1713         if (!(entry.serverFlags[vldbindex] & ITSROVOL)) continue;  /* not a RO vol */
1714
1715
1716         /* Get a Transaction on this replica. Get a new connection if
1717          * necessary.  Create the volume if necessary.  Return the
1718          * time from which the dump should be made (0 if it's a new
1719          * volume).  Each volume might have a different time. 
1720          */
1721         replicas[volcount].server.destHost = entry.serverNumber[vldbindex];
1722         replicas[volcount].server.destPort = AFSCONF_VOLUMEPORT;
1723         replicas[volcount].server.destSSID = 1;
1724         times[volcount].vldbEntryIndex = vldbindex;
1725         
1726         if(!GetTrans(cellHandle, &entry, vldbindex, &(toconns[volcount]), 
1727                         &(replicas[volcount].trans), &(times[volcount].time),
1728                         &tst)) {
1729             continue;
1730         }
1731
1732         /* Thisdate is the date from which we want to pick up all changes */
1733         if (forceflag || !fullrelease || (rwcrdate > times[volcount].time)) {
1734            /* If the forceflag is set, then we want to do a full dump.
1735             * If it's not a full release, we can't be sure that the creation
1736             *  date is good (so we also do a full dump).
1737             * If the RW volume was replaced (its creation date is newer than
1738             *  the last release), then we can't be sure what has changed (so
1739             *  we do a full dump).
1740             */
1741            thisdate = 0;
1742         } else if (remembertime[vldbindex].validtime) {
1743            /* Trans was prev ended. Use the time from the prev trans
1744             * because, prev trans may have created the volume. In which
1745             * case time[volcount].time would be now instead of 0.
1746             */
1747            thisdate  = (remembertime[vldbindex].time < times[volcount].time) ? 
1748                         remembertime[vldbindex].time : times[volcount].time;
1749         } else {
1750            thisdate = times[volcount].time;
1751         }         
1752         remembertime[vldbindex].validtime = 1;
1753         remembertime[vldbindex].time = thisdate;
1754
1755         if (volcount == 0) {
1756            fromdate = thisdate;
1757         } else {
1758            /* Include this volume if it is within 15 minutes of the earliest */
1759            if (((fromdate>thisdate)?(fromdate-thisdate):(thisdate-fromdate)) > 900) {
1760               AFSVolEndTrans(toconns[volcount], replicas[volcount].trans, &rcode);
1761               replicas[volcount].trans = 0;
1762               break;
1763            }
1764            if (thisdate < fromdate)
1765               fromdate = thisdate;
1766         }
1767         volcount++;
1768      }
1769      if (!volcount) continue;
1770
1771      /* Release the ones we have collected */
1772      tr.manyDests_val = &(replicas[0]);
1773      tr.manyDests_len = results.manyResults_len = volcount;
1774      tst = AFSVolForwardMultiple(fromconn, fromtid, fromdate, &tr, 0/*spare*/, &cookie, &results);
1775      if (tst == RXGEN_OPCODE) {               /* RPC Interface Mismatch */
1776         tst = SimulateForwardMultiple(fromconn, fromtid, fromdate, &tr, 0/*spare*/, &cookie, &results);
1777         nservers = 1;
1778      }
1779
1780      if (tst) {
1781         goto fail_UV_ReleaseVolume;
1782      } else {
1783         for (m=0; m<volcount; m++) {
1784            if (results.manyResults_val[m]) {
1785               continue;
1786            }
1787             
1788            tst = AFSVolSetIdsTypes(toconns[m], replicas[m].trans, 
1789                                     vname, ROVOL, entry.volumeId[RWVOL], 0, 0);
1790            if (tst) {
1791               continue;
1792            }
1793
1794            /* have to clear dest. flags to ensure new vol goes online:
1795             * because the restore (forwarded) operation copied
1796             * the V_inService(=0) flag over to the destination. 
1797             */
1798            tst = AFSVolSetFlags(toconns[m], replicas[m].trans, 0);
1799            if (tst) {
1800               continue;
1801            }
1802
1803            entry.serverFlags[times[m].vldbEntryIndex] |=  NEW_REPSITE;
1804            entry.serverFlags[times[m].vldbEntryIndex] &= ~RO_DONTUSE;
1805            entry.flags                                |=  RO_EXISTS;
1806            releasecount++;
1807         }
1808      }   
1809
1810      /* End the transactions and destroy the connections */
1811      for (s=0; s<volcount; s++) {
1812         if (replicas[s].trans)
1813            tst = AFSVolEndTrans(toconns[s], replicas[s].trans, &rcode);
1814         replicas[s].trans = 0;
1815         if (!tst) tst = rcode;
1816         if (tst) {
1817            if ((s == 0) || (tst != ENOENT)) {
1818            } else {
1819               if (times[s].vldbEntryIndex < vldbindex)
1820                  vldbindex = times[s].vldbEntryIndex;
1821            }
1822         }
1823            
1824         if (toconns[s])
1825            rx_ReleaseCachedConnection(toconns[s]);
1826         toconns[s] = 0;
1827      }
1828    
1829      if (!VLDB_ReplaceEntry(cellHandle, afromvol, RWVOL, &entry, 0, &tst)) {
1830          goto fail_UV_ReleaseVolume;
1831      }
1832   } /* for each index in the vldb */
1833
1834   /* End the transaction on the cloned volume */
1835   tst = AFSVolEndTrans(fromconn, fromtid, &rcode);
1836   fromtid = 0;
1837   
1838   /* Figure out if any volume were not released and say so */
1839   for (failure=0, i=0; i<entry.nServers; i++) {
1840      if (!(entry.serverFlags[i] & NEW_REPSITE))
1841         failure++;
1842   }
1843   if (failure) {
1844      if (!VLDB_ReplaceEntry(cellHandle, afromvol, RWVOL, &entry,
1845                             LOCKREL_TIMESTAMP, &tst)) {
1846          goto fail_UV_ReleaseVolume;
1847      }
1848
1849      tst = VOLSERBADRELEASE;
1850      goto fail_UV_ReleaseVolume;
1851   }
1852
1853   /* All the ROs were release successfully. Remove the temporary clone */
1854   if (!roclone) {
1855       tst = DelVol (fromconn, cloneVolId, afrompart, ITOffline);
1856       if (tst) {
1857           goto fail_UV_ReleaseVolume;
1858       }
1859   }
1860   entry.cloneId = 0;
1861
1862   for (i=0; i<entry.nServers; i++)
1863      entry.serverFlags[i] &= ~NEW_REPSITE;
1864
1865   /* Update the VLDB */
1866   if (!VLDB_ReplaceEntry(cellHandle, afromvol, RWVOL, &entry,
1867                            LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP,
1868                            &tst)) {
1869       goto fail_UV_ReleaseVolume;
1870   }
1871   rc = 1;
1872
1873 fail_UV_ReleaseVolume:
1874
1875   if (clonetid) {
1876       tst = AFSVolEndTrans(fromconn, clonetid, &rcode);
1877       clonetid = 0;
1878       if (tst) {
1879           rc = 0;
1880       }
1881   }
1882   if (fromtid) {
1883       tst = AFSVolEndTrans(fromconn, fromtid, &rcode);
1884       fromtid = 0;
1885       if (tst) {
1886           rc = 0;
1887       }
1888   }
1889   for (i=0; i<nservers; i++) {
1890       if (replicas && replicas[i].trans) {
1891           tst = AFSVolEndTrans(toconns[i], replicas[i].trans, &rcode);
1892           replicas[i].trans = 0;
1893           if (tst) {
1894               rc = 0;
1895           }
1896       }
1897       if (toconns && toconns[i]) {
1898           rx_ReleaseCachedConnection(toconns[i]);
1899           toconns[i] = 0;
1900       }
1901   }
1902   if (islocked) {
1903       tst = ubik_Call(VL_ReleaseLock,cellHandle->vos, 0, afromvol, RWVOL, 
1904                         LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
1905       if (tst) {
1906           rc = 0;
1907       }
1908   }
1909
1910   if (fromconn)                rx_ReleaseCachedConnection(fromconn);
1911   if (results.manyResults_val) free (results.manyResults_val);
1912   if (replicas)                free (replicas);
1913   if (toconns)                 free (toconns);
1914   if (times)                   free (times);
1915
1916   if (st != NULL) {
1917       *st = tst;
1918   }
1919   return rc;
1920 }
1921
1922 static int ReceiveFile(
1923     register int fd,
1924     register struct rx_call *call,
1925     register struct stat *status)
1926 {
1927     register char *buffer = (char*) 0;
1928     register int blockSize;
1929     afs_int32  bytesread, nbytes, bytesleft, w;
1930     fd_set out;
1931     afs_int32 error = 0;
1932  
1933 #ifdef AFS_NT40_ENV
1934     blockSize = 4096;
1935 #else
1936     if(fd != 1) {
1937 #ifdef  AFS_AIX_ENV
1938     struct statfs tstatfs;
1939  
1940 /* Unfortunately in AIX valuable fields such as st_blksize are gone from the sta
1941 t structure!! */
1942     fstatfs(fd, &tstatfs);
1943     blockSize = tstatfs.f_bsize;
1944 #else
1945     blockSize = status->st_blksize;
1946 #endif
1947     }
1948     else{
1949         blockSize = 4096;
1950     }
1951 #endif
1952     nbytes = blockSize;
1953     buffer = (char *)malloc(blockSize);
1954     if (!buffer) {
1955         return ADMNOMEM;
1956     }
1957     bytesread = 1;
1958     while(!error && (bytesread > 0)) {
1959         bytesread = rx_Read(call, buffer, nbytes);
1960         bytesleft = bytesread;
1961         while (!error && (bytesleft > 0)) {
1962             FD_ZERO(&out);
1963             FD_SET(fd, &out);
1964 #ifndef AFS_NT40_ENV  /* NT csn't select on non-socket fd's */
1965             select(fd+1, 0, &out, 0, 0);      /* don't timeout if write bl
1966 ocks */
1967 #endif
1968             w = write(fd, &buffer[bytesread-bytesleft], bytesleft);
1969             if (w < 0) {
1970                 error = ADMVOSDUMPFILEWRITEFAIL;
1971             }
1972             else {
1973                 bytesleft -= w;
1974             }
1975         }
1976     }
1977     if (buffer) free(buffer);
1978     if(fd !=1)
1979         if (!error) fstat(fd, status);
1980     return error;
1981 }
1982
1983
1984 static afs_int32 DumpFunction(
1985   struct rx_call *call,
1986   const char *filename)
1987 {
1988     int fd;
1989     struct stat status;
1990     afs_int32 error,code;
1991  
1992     error = 0;
1993     fd = -1;
1994  
1995     fd = open(filename,O_CREAT|O_TRUNC|O_WRONLY, 0666);
1996     if (fd < 0 || fstat(fd, &status) < 0){
1997         error = VOLSERBADOP;
1998         goto dffail;
1999     }
2000     code = ReceiveFile(fd,call,&status);
2001     if(code) {
2002         error = code;
2003         goto dffail;
2004     }
2005   dffail:
2006     if (fd >= 0) code = close(fd);
2007     else code = 0;
2008     if(code){
2009         if(!error) error = code;
2010     }
2011     return error;
2012 }
2013
2014
2015 /*dump the volume <afromvol> on <afromserver> and
2016 * <afrompart> to <afilename> starting from <fromdate>.
2017 * DumpFunction does the real work behind the scenes after
2018 * extracting parameters from the rock  */
2019 int UV_DumpVolume(
2020   afs_cell_handle_p cellHandle,
2021   afs_int32 afromvol,
2022   afs_int32 afromserver,
2023   afs_int32 afrompart,
2024   afs_int32 fromdate,
2025   const char *filename,
2026   afs_status_p st)
2027 {
2028     int rc = 0;
2029     afs_status_t tst = 0;
2030     afs_status_t etst = 0;
2031     struct rx_connection  *fromconn;
2032     struct rx_call *fromcall;
2033     afs_int32 fromtid;
2034     afs_int32 rxError;
2035     afs_int32 rcode;
2036     
2037     struct nvldbentry entry;
2038     afs_int32 error;
2039     int islocked;
2040
2041     islocked = 0;
2042     error = 0;
2043     rxError = 0;
2044     fromcall = (struct rx_call *)0;
2045     fromconn = (struct rx_connection *)0;
2046     fromtid = 0;
2047     fromcall = (struct rx_call *)0;
2048     
2049     islocked = 0;
2050     if (!VLDB_GetEntryByID(cellHandle, afromvol, -1, &entry, &tst)) {
2051         goto fail_UV_DumpVolume;
2052     }
2053
2054     /* get connections to the servers */
2055     fromconn = UV_Bind(cellHandle, afromserver, AFSCONF_VOLUMEPORT);
2056     tst = AFSVolTransCreate(fromconn, afromvol, afrompart, ITBusy, &fromtid);
2057     if (tst) {
2058         goto fail_UV_DumpVolume;
2059     }
2060     fromcall = rx_NewCall(fromconn);
2061     tst = StartAFSVolDump(fromcall,fromtid, fromdate);
2062     if(tst) {
2063         goto fail_UV_DumpVolume;
2064     }
2065     if (tst = DumpFunction(fromcall,filename)) {
2066         goto fail_UV_DumpVolume;
2067     }
2068     tst = rx_EndCall(fromcall,rxError);
2069     fromcall = (struct rx_call *)0;
2070     if (tst) {
2071         goto fail_UV_DumpVolume;
2072     }
2073     tst = AFSVolEndTrans(fromconn, fromtid, &rcode);
2074     fromtid = 0;
2075     if (!tst) tst = rcode;
2076     if (tst){
2077         goto fail_UV_DumpVolume;
2078     }
2079     rc = 1;
2080
2081 fail_UV_DumpVolume: 
2082
2083     if(islocked) {
2084         etst = ubik_Call(VL_ReleaseLock,cellHandle->vos, 0, afromvol, -1, LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
2085         if(etst) {
2086             if(!tst) tst = etst;
2087         }
2088     }
2089
2090     if(fromcall) {
2091         etst = rx_EndCall(fromcall,rxError);
2092         if(etst){
2093             if(!tst) tst = etst;
2094         }       
2095     }
2096
2097     if (fromtid) {
2098         etst = AFSVolEndTrans(fromconn, fromtid, &rcode);
2099         if(!tst) tst = etst;
2100         if(rcode) {
2101             if(!tst) tst = rcode;
2102         }
2103     }
2104
2105     if (fromconn) {
2106         rx_ReleaseCachedConnection(fromconn);
2107     }
2108
2109     if (st != NULL) {
2110         *st = tst;
2111     }
2112     return rc;
2113 }
2114
2115 int SendFile(
2116   register int fd,
2117   register struct rx_call *call,
2118   register struct stat *status)
2119 {
2120     char *buffer = (char*) 0;
2121     int blockSize;
2122     fd_set in;
2123     afs_int32 error = 0;
2124     int done = 0;
2125     int nbytes;
2126  
2127 #ifdef AFS_NT40_ENV
2128     blockSize = 4096;
2129 #else
2130     if(fd != 0){
2131 #ifdef  AFS_AIX_ENV
2132     struct statfs tstatfs;
2133  
2134 /* Unfortunately in AIX valuable fields such as st_blksize are gone from the sta
2135 t structure!! */
2136     fstatfs(fd, &tstatfs);
2137     blockSize = tstatfs.f_bsize;
2138 #else
2139     blockSize = status->st_blksize;
2140 #endif
2141     }
2142     else{
2143         blockSize = 4096;
2144     }
2145 #endif
2146     buffer = (char *)malloc(blockSize);
2147     if (!buffer) {
2148         return ADMNOMEM;
2149     }
2150  
2151     while (!error && !done) {
2152         FD_ZERO(&in);
2153         FD_SET(fd, &in);
2154 #ifndef AFS_NT40_ENV  /* NT csn't select on non-socket fd's */
2155         select(fd+1, &in, 0, 0, 0);      /* don't timeout if read blocks */
2156 #endif
2157         nbytes = read(fd, buffer, blockSize);
2158         if (nbytes < 0) {
2159             error = ADMVOSRESTOREFILEREADFAIL;
2160             break;
2161         }
2162         if(nbytes == 0){
2163             done = 1;
2164             break;
2165         }
2166         if (rx_Write(call, buffer, nbytes) != nbytes){
2167             error = ADMVOSRESTOREFILEWRITEFAIL;
2168             break;
2169         }
2170     }
2171     if (buffer) free(buffer);
2172     return error;
2173 }
2174
2175 static afs_int32 WriteData(
2176   struct rx_call *call,
2177   const char *filename)
2178 {
2179     int fd;
2180     struct stat status;
2181     afs_int32 error,code;
2182  
2183     error = 0;
2184     fd = -1;
2185  
2186     fd = open(filename,0);
2187     if (fd < 0 || fstat(fd, &status) < 0){
2188         fprintf(STDERR,"Could access file '%s'\n",filename);
2189         error = ADMVOSRESTOREFILEOPENFAIL;
2190         goto fail_WriteData;
2191     }
2192     code = SendFile(fd,call,&status);
2193     if(code) {
2194         error = code;
2195         goto fail_WriteData;
2196     }
2197
2198 fail_WriteData:
2199
2200     if(fd >= 0) code = close(fd);
2201     else code = 0;
2202     if(code){
2203         if(!error) error = ADMVOSRESTOREFILECLOSEFAIL;
2204     }
2205     return error;
2206 }
2207
2208 /*
2209  * Restore a volume <tovolid> <tovolname> on <toserver> <topart> from
2210  * the dump file <afilename>. WriteData does all the real work
2211  * after extracting params from the rock 
2212  */
2213 int UV_RestoreVolume(
2214   afs_cell_handle_p cellHandle,
2215   afs_int32 toserver,
2216   afs_int32 topart,
2217   afs_int32 tovolid,
2218   const char *tovolname,
2219   int flags,
2220   const char *dumpFile,
2221   afs_status_p st)
2222 {
2223     int rc = 0;
2224     afs_status_t tst = 0;
2225     afs_status_t etst = 0;
2226     struct rx_connection *toconn,*tempconn;
2227     struct rx_call *tocall;
2228     afs_int32 totid, rcode, terror = 0;
2229     afs_int32 rxError = 0;
2230     struct volser_status tstatus;
2231     char partName[10];
2232     afs_int32 pvolid;
2233     afs_int32 temptid;
2234     int success;
2235     struct nvldbentry entry;
2236     afs_int32 error;
2237     int islocked;
2238     struct restoreCookie cookie;
2239     int reuseID;
2240     afs_int32 newDate, volflag;
2241     int index, same;
2242
2243
2244     bzero(&cookie,sizeof(cookie));
2245     islocked  = 0;
2246     success = 0;
2247     error = 0;
2248     reuseID = 1;
2249     tocall = (struct rx_call *)0;
2250     toconn = (struct rx_connection *)0;
2251     tempconn = (struct rx_connection *)0;
2252     totid = 0;
2253     temptid = 0;
2254
2255     pvolid = tovolid;
2256     toconn = UV_Bind(cellHandle, toserver, AFSCONF_VOLUMEPORT);
2257     if(pvolid == 0) {/*alot a new id if needed */
2258         VLDB_GetEntryByName(cellHandle, tovolname, &entry, &tst);
2259         if(tst == VL_NOENT) {
2260             tst = ubik_Call(VL_GetNewVolumeId, cellHandle->vos, 0, 1, &pvolid);
2261             if(tst) {
2262                 goto fail_UV_RestoreVolume;
2263             }
2264             reuseID = 0;
2265         }
2266         else{
2267             pvolid = entry.volumeId[RWVOL];
2268         }
2269     }
2270
2271     /* 
2272      * at this point we have a volume id to use/reuse for the
2273      * volume to be restored
2274      */
2275     if(strlen(tovolname) > (VOLSER_OLDMAXVOLNAME - 1)) {
2276         tst = ADMVOSRESTOREVOLUMENAMETOOBIG;
2277         goto fail_UV_RestoreVolume;
2278     }
2279
2280     if (!vos_PartitionIdToName(topart, partName, &tst)) {
2281         goto fail_UV_RestoreVolume;
2282     }
2283     /*what should the volume be restored as ? rw or ro or bk ?
2284       right now the default is rw always */
2285     tst = AFSVolCreateVolume(toconn, topart, tovolname, volser_RW, 0,&pvolid, &totid);
2286     if (tst){
2287         if (flags & RV_FULLRST) { /* full restore: delete then create anew */
2288             tst = AFSVolTransCreate(toconn, pvolid, topart, ITOffline, &totid);
2289             if (tst) {
2290                 goto fail_UV_RestoreVolume;
2291             }
2292             tst = AFSVolSetFlags(toconn, totid, VTDeleteOnSalvage | VTOutOfService);
2293             if (tst){
2294                 goto fail_UV_RestoreVolume;
2295             }
2296             tst = AFSVolDeleteVolume(toconn,totid);
2297             if (tst){
2298                 goto fail_UV_RestoreVolume;
2299             }
2300             tst = AFSVolEndTrans(toconn, totid, &rcode);
2301             totid = 0;
2302             if (!tst) tst = rcode;
2303             if (tst) {
2304                 goto fail_UV_RestoreVolume;
2305             }
2306             tst = AFSVolCreateVolume(toconn, topart, tovolname, volser_RW, 0,&pvolid, &totid);
2307             if (tst){
2308                 goto fail_UV_RestoreVolume;}
2309         } else {
2310             tst = AFSVolTransCreate(toconn, pvolid, topart, ITOffline, &totid);
2311             if (tst) {
2312                 goto fail_UV_RestoreVolume;
2313             }
2314         }
2315     }
2316     cookie.parent = pvolid;
2317     cookie.type = RWVOL;
2318     cookie.clone = 0;
2319     strncpy(cookie.name,tovolname,VOLSER_OLDMAXVOLNAME);
2320
2321     tocall = rx_NewCall(toconn);
2322     tst = StartAFSVolRestore(tocall,totid, 1,&cookie);
2323     if(tst) {
2324         goto fail_UV_RestoreVolume;
2325     }
2326     tst = WriteData(tocall, dumpFile);
2327     if(tst) {
2328         goto fail_UV_RestoreVolume;
2329     }
2330     tst = rx_EndCall(tocall,rxError);
2331     tocall = (struct rx_call *) 0;
2332     if (tst) {
2333         goto fail_UV_RestoreVolume;
2334     }
2335     tst = AFSVolGetStatus(toconn,totid, &tstatus);
2336     if(tst) {
2337         goto fail_UV_RestoreVolume;
2338     }
2339     tst = AFSVolSetIdsTypes(toconn,totid, tovolname, RWVOL, pvolid,0,0);
2340     if(tst) {
2341         goto fail_UV_RestoreVolume;
2342     }
2343     newDate = time(0);
2344     tst = AFSVolSetDate(toconn,totid, newDate);
2345     if(tst) {
2346         goto fail_UV_RestoreVolume;
2347     }
2348
2349     volflag = ((flags & RV_OFFLINE) ? VTOutOfService : 0); /* off or on-line */
2350     tst = AFSVolSetFlags(toconn, totid, volflag);
2351     if (tst){
2352         goto fail_UV_RestoreVolume;
2353     }
2354    
2355 /* It isn't handled right in fail_UV_RestoreVolume */
2356     tst = AFSVolEndTrans(toconn, totid, &rcode);
2357     totid = 0;
2358     if(!tst) tst = rcode;
2359     if(tst) {
2360         goto fail_UV_RestoreVolume;
2361     }
2362
2363     success = 1;
2364     if (success && (!reuseID || (flags & RV_FULLRST))) {
2365         /* Volume was restored on the file server, update the 
2366          * VLDB to reflect the change.
2367          */
2368         VLDB_GetEntryByID(cellHandle, pvolid, RWVOL, &entry, &tst);
2369         if(tst && tst != VL_NOENT && tst != VL_ENTDELETED) {
2370             goto fail_UV_RestoreVolume;
2371         }
2372         if(tst == VL_NOENT) { /* it doesnot exist already */
2373             /*make the vldb return this indication specifically*/
2374             strcpy(entry.name, tovolname);
2375             entry.nServers = 1;
2376             entry.serverNumber[0] = toserver;/*should be indirect */
2377             entry.serverPartition[0] = topart;
2378             entry.serverFlags[0] = ITSRWVOL;
2379             entry.flags = RW_EXISTS;
2380             if(tstatus.cloneID != 0){
2381                 entry.volumeId[ROVOL] = tstatus.cloneID;/*this should come from status info on the volume if non zero */
2382             }
2383             else
2384                 entry.volumeId[ROVOL] = INVALID_BID;
2385             entry.volumeId[RWVOL] = pvolid;
2386             entry.cloneId = 0;
2387             if(tstatus.backupID != 0){
2388                 entry.volumeId[BACKVOL] = tstatus.backupID;
2389                 /*this should come from status info on the volume if non zero */
2390             }
2391             else 
2392                 entry.volumeId[BACKVOL] = INVALID_BID;
2393             if (!VLDB_CreateEntry(cellHandle, &entry, &tst)) {
2394                 goto fail_UV_RestoreVolume;
2395             }
2396             islocked = 0;
2397         }
2398         else {  /*update the existing entry */
2399             tst = ubik_Call(VL_SetLock,cellHandle->vos, 0, pvolid, RWVOL, VLOP_RESTORE);
2400             if(tst) {
2401                 goto fail_UV_RestoreVolume;
2402             }
2403             islocked = 1;
2404             strcpy(entry.name, tovolname);
2405
2406             /* Update the vlentry with the new information */
2407             index = Lp_GetRwIndex(cellHandle, &entry, 0);
2408             if (index == -1) {
2409                /* Add the rw site for the volume being restored */
2410                entry.serverNumber[entry.nServers]    = toserver;
2411                entry.serverPartition[entry.nServers] = topart;
2412                entry.serverFlags[entry.nServers]     = ITSRWVOL;
2413                entry.nServers++;
2414             } else {
2415                /* This volume should be deleted on the old site
2416                 * if its different from new site.
2417                 */
2418                VLDB_IsSameAddrs(cellHandle, toserver, entry.serverNumber[index], &same, &tst);
2419                if ( (!tst && !same) || (entry.serverPartition[index] != topart) ) {
2420                   tempconn = UV_Bind(cellHandle, entry.serverNumber[index], AFSCONF_VOLUMEPORT);
2421                   tst = AFSVolTransCreate(tempconn, pvolid, entry.serverPartition[index], ITOffline, &temptid);
2422                   if (!tst){
2423                      tst = AFSVolSetFlags(tempconn, temptid, VTDeleteOnSalvage | VTOutOfService);
2424                      if(tst) {
2425                         goto fail_UV_RestoreVolume;
2426                      }
2427                      tst = AFSVolDeleteVolume(tempconn,temptid);
2428                      if(tst){
2429                         goto fail_UV_RestoreVolume;
2430                      }
2431                      tst = AFSVolEndTrans(tempconn, temptid, &rcode);
2432                      temptid = 0;
2433                      if(!tst) tst = rcode;
2434                      if(tst){
2435                         goto fail_UV_RestoreVolume;
2436                      }
2437                      vos_PartitionIdToName(entry.serverPartition[index],partName, &tst);
2438                   }
2439                }
2440                entry.serverNumber[index]    = toserver;
2441                entry.serverPartition[index] = topart;
2442             }
2443
2444             entry.flags |= RW_EXISTS;
2445             if (!VLDB_ReplaceEntry(cellHandle, pvolid, RWVOL, &entry,
2446                                    LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP, &tst)) {
2447                 goto fail_UV_RestoreVolume;
2448             }
2449             islocked = 0;
2450         }
2451     }
2452     rc = 1;
2453
2454 fail_UV_RestoreVolume:
2455
2456     if (tocall) {
2457         etst = rx_EndCall(tocall, rxError);
2458         if (!tst) tst = etst;
2459     }
2460     if(islocked) {
2461         etst = ubik_Call(VL_ReleaseLock,cellHandle->vos, 0, pvolid, RWVOL, LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
2462         if(etst) {
2463             if(!tst) tst = etst;
2464         }
2465     }
2466     if(totid) {
2467         etst = AFSVolEndTrans(toconn, totid, &rcode);
2468         if(!etst) etst = rcode;
2469         if(etst) {
2470             if(!tst) tst = etst;
2471         }
2472     }
2473     if(temptid) {
2474         etst = AFSVolEndTrans(toconn, temptid, &rcode);
2475         if(!etst) etst = rcode;
2476         if(etst) {
2477             if(!tst) tst = etst;
2478         }
2479     }
2480
2481     if(tempconn) rx_ReleaseCachedConnection(tempconn);
2482     if(toconn) rx_ReleaseCachedConnection(toconn);
2483
2484     if (st != NULL) {
2485         *st = tst;
2486     }
2487     return rc;
2488 }
2489
2490 /*adds <server> and <part> as a readonly replication site for <volid>
2491 *in vldb */
2492 int UV_AddSite(
2493   afs_cell_handle_p cellHandle,
2494   afs_int32 server,
2495   afs_int32 part,
2496   afs_int32 volid,
2497   afs_status_p st)
2498 {
2499     int rc = 0;
2500     afs_status_t tst = 0;
2501     int j, nro=0, islocked=0;
2502     struct nvldbentry entry;
2503     afs_int32 error=0;
2504     int same = 0;
2505
2506     tst = ubik_Call(VL_SetLock, cellHandle->vos, 0,volid,RWVOL, VLOP_ADDSITE);
2507     if (tst) {
2508         goto fail_UV_AddSite;
2509     }
2510     islocked = 1;
2511
2512     if (!VLDB_GetEntryByID(cellHandle, volid, RWVOL, &entry, &tst)) {
2513         goto fail_UV_AddSite;
2514     }
2515     if (!ISNAMEVALID(entry.name)){
2516         tst = VOLSERBADOP;
2517         goto fail_UV_AddSite;
2518     }
2519
2520     /* See if it's too many entries */
2521     if (entry.nServers >= NMAXNSERVERS){
2522        tst = VOLSERBADOP;
2523        goto fail_UV_AddSite;
2524     }
2525
2526     /* See if it's on the same server */
2527     for (j=0; j < entry.nServers; j++) {
2528        if (entry.serverFlags[j] & ITSROVOL) {
2529           nro++;
2530           if (!VLDB_IsSameAddrs(cellHandle, server, entry.serverNumber[j], &same, &tst)) {
2531               goto fail_UV_AddSite;
2532           }  
2533           if (same) {
2534              tst =  VOLSERBADOP;
2535              goto fail_UV_AddSite;
2536           }
2537        }
2538     }
2539
2540     /* See if it's too many RO sites - leave one for the RW */
2541     if (nro >= NMAXNSERVERS-1){
2542        tst = VOLSERBADOP;
2543        goto fail_UV_AddSite;
2544     }
2545
2546     entry.serverNumber[entry.nServers] = server;
2547     entry.serverPartition[entry.nServers] = part;
2548     entry.serverFlags[entry.nServers] = (ITSROVOL | RO_DONTUSE);
2549     entry.nServers++;
2550         
2551     if (!VLDB_ReplaceEntry(cellHandle, volid, RWVOL, &entry,
2552                            LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP,
2553                            &tst)) {
2554        goto fail_UV_AddSite;
2555     }
2556     islocked = 0;
2557     rc = 1;
2558
2559 fail_UV_AddSite:
2560
2561     if (islocked) {
2562        tst = ubik_Call(VL_ReleaseLock,cellHandle->vos, 0, volid, RWVOL,
2563                        LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
2564     }
2565
2566     if (st != NULL) {
2567         *st = tst;
2568     }
2569     return rc;
2570 }
2571
2572 /*removes <server> <part> as read only site for <volid> from the vldb */
2573 int UV_RemoveSite(
2574   afs_cell_handle_p cellHandle,
2575   afs_int32 server,
2576   afs_int32 part,
2577   afs_int32 volid,
2578   afs_status_p st)
2579 {
2580     int rc = 0;
2581     afs_status_t tst = 0;
2582     struct nvldbentry entry;
2583     int islocked;
2584
2585     tst = ubik_Call(VL_SetLock, cellHandle->vos, 0,volid, RWVOL, VLOP_ADDSITE);
2586     if(tst) {
2587         goto fail_UV_RemoveSite;
2588     }
2589     islocked = 1;
2590
2591     if (!VLDB_GetEntryByID(cellHandle, volid, RWVOL, &entry, &tst)) {
2592         goto fail_UV_RemoveSite;
2593     }
2594     if (!Lp_ROMatch(cellHandle, &entry, server, part, &tst)) {
2595         /*this site doesnot exist  */
2596         goto fail_UV_RemoveSite;
2597     }
2598     else { /*remove the rep site */
2599         Lp_SetROValue(cellHandle, &entry, server, part, 0, 0);
2600         entry.nServers--;
2601         if((entry.nServers == 1) && (entry.flags & RW_EXISTS))
2602             entry.flags &= ~RO_EXISTS;
2603         if(entry.nServers < 1) { /*this is the last ref */
2604             tst = ubik_Call(VL_DeleteEntry, cellHandle->vos, 0,volid, ROVOL);
2605             if(tst) {
2606                 goto fail_UV_RemoveSite;
2607             }
2608         }
2609        if (!VLDB_ReplaceEntry(cellHandle, volid, RWVOL, &entry,
2610                         (LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP), 
2611                         &tst)) {
2612            goto fail_UV_RemoveSite;
2613        }
2614     }
2615     rc = 1;
2616
2617 fail_UV_RemoveSite:
2618
2619     if (islocked) {
2620         afs_status_t t;
2621         t = ubik_Call(VL_ReleaseLock, cellHandle->vos, 0, volid, RWVOL, LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
2622         if (tst == 0) {
2623             tst = t;
2624         }
2625     }
2626
2627     if (st != NULL) {
2628         *st = tst;
2629     }
2630     return rc;
2631 }
2632
2633 /*list all the partitions on <aserver> */
2634 int UV_ListPartitions(
2635   struct rx_connection *server,
2636   struct partList *ptrPartList,
2637   afs_int32 *cntp,
2638   afs_status_p st)
2639 {
2640     int rc = 0;
2641     afs_status_t tst = 0;
2642     struct pIDs partIds;
2643     struct partEntries partEnts;
2644     register int i, j=0;
2645
2646     *cntp = 0;
2647
2648     partEnts.partEntries_len = 0;
2649     partEnts.partEntries_val = (afs_int32 *)0;
2650     /* this is available only on new servers */
2651     tst = AFSVolXListPartitions(server, &partEnts); 
2652
2653     /* next, try old interface */
2654     if (tst == RXGEN_OPCODE) 
2655     {
2656         for(i = 0; i < 26; i++)                         
2657             partIds.partIds[i]  = -1;
2658         tst = AFSVolListPartitions(server, &partIds);
2659         if (!tst) {
2660             for (i = 0;i < 26; i++) {
2661                 if((partIds.partIds[i]) != -1) {
2662                     ptrPartList->partId[j] = partIds.partIds[i];
2663                     ptrPartList->partFlags[j] = PARTVALID;
2664                     j++;
2665                 } else
2666                     ptrPartList->partFlags[i] = 0;
2667             }
2668             *cntp = j;
2669         } else {
2670             goto fail_UV_ListPartitions;
2671         }
2672     }
2673     else if (!tst) 
2674     {
2675         *cntp = partEnts.partEntries_len;
2676         if (*cntp > VOLMAXPARTS) {
2677             *cntp = VOLMAXPARTS;
2678         }
2679         for (i = 0;i < *cntp; i++) {
2680             ptrPartList->partId[i] = partEnts.partEntries_val[i];
2681             ptrPartList->partFlags[i] = PARTVALID;
2682         }
2683         free(partEnts.partEntries_val);
2684     } else {
2685         goto fail_UV_ListPartitions;
2686     }
2687     rc = 1;
2688
2689 fail_UV_ListPartitions:
2690
2691     if (st != NULL) {
2692         *st = tst;
2693     }
2694     return rc;
2695 }
2696
2697 /*------------------------------------------------------------------------
2698  * EXPORTED UV_XListVolumes
2699  *
2700  * Description:
2701  *      List the extended information for all the volumes on a particular
2702  *      File Server and partition.  We may either return the volume's ID
2703  *      or all of its extended information.
2704  *
2705  * Arguments:
2706  *      a_serverID         : Address of the File Server for which we want
2707  *                              extended volume info.
2708  *      a_partID           : Partition for which we want the extended
2709  *                              volume info.
2710  *      a_all              : If non-zero, fetch ALL the volume info,
2711  *                              otherwise just the volume ID.
2712  *      a_resultPP         : Ptr to the address of the area containing
2713  *                              the returned volume info.
2714  *      a_numEntsInResultP : Ptr for the value we set for the number of
2715  *                              entries returned.
2716  *
2717  * Returns:
2718  *      0 on success,
2719  *      Otherise, the return value of AFSVolXListVolumes.
2720  *
2721  * Environment:
2722  *      This routine is closely related to UV_ListVolumes, which returns
2723  *      only the standard level of detail on AFS volumes. It is a
2724  *      heavyweight operation, zipping through all the volume entries for
2725  *      a given server/partition.
2726  *
2727  * Side Effects:
2728  *      As advertised.
2729  *------------------------------------------------------------------------*/
2730
2731 int UV_XListVolumes(
2732   struct rx_connection *server,
2733   afs_int32 a_partID,
2734   int a_all,
2735   struct volintXInfo **a_resultPP,
2736   afs_int32 *a_numEntsInResultP,
2737   afs_status_p st)
2738 {
2739     int rc = 0;
2740     afs_status_t tst = 0;
2741
2742     volXEntries volumeXInfo;            /*Area for returned extended vol info*/
2743
2744     /*
2745      * Set up our error code and the area for returned extended volume info.
2746      * We set the val field to a null pointer as a hint for the stub to
2747      * allocate space.
2748      */
2749     *a_numEntsInResultP = 0;
2750     *a_resultPP = (volintXInfo *)0;
2751     volumeXInfo.volXEntries_val = (volintXInfo *)0;
2752     volumeXInfo.volXEntries_len = 0;
2753
2754     /*
2755      * Bind to the Volume Server port on the File Server machine in question,
2756      * then go for it.
2757      */
2758     tst = AFSVolXListVolumes(server, a_partID, a_all, &volumeXInfo);
2759     if (tst) {
2760         goto fail_UV_XListVolumes;
2761     } else {
2762         /*
2763          * We got the info; pull out the pointer to where the results lie
2764          * and how many entries are there.
2765          */
2766         *a_resultPP = volumeXInfo.volXEntries_val;
2767         *a_numEntsInResultP = volumeXInfo.volXEntries_len;
2768     }
2769     rc = 1;
2770
2771 fail_UV_XListVolumes:
2772
2773     if (st != NULL) {
2774         *st = tst;
2775     }
2776     return rc;
2777 }
2778
2779 /*------------------------------------------------------------------------
2780  * EXPORTED UV_XListOneVolume
2781  *
2782  * Description:
2783  *      List the extended information for a volume on a particular File
2784  *      Server and partition.
2785  *
2786  * Arguments:
2787  *      server     : a handle to the server where the volume resides.
2788  *      a_partID           : Partition for which we want the extended
2789  *                              volume info.
2790  *      a_volID            : Volume ID for which we want the info.
2791  *      a_resultPP         : Ptr to the address of the area containing
2792  *                              the returned volume info.
2793  *
2794  * Returns:
2795  *      0 on success,
2796  *      Otherise, the return value of AFSVolXListOneVolume.
2797  *
2798  * Environment:
2799  *      This routine is closely related to UV_ListOneVolume, which returns
2800  *      only the standard level of detail on the chosen AFS volume.
2801  *
2802  * Side Effects:
2803  *      As advertised.
2804  *------------------------------------------------------------------------*/
2805
2806 int UV_XListOneVolume(
2807   struct rx_connection *server,
2808   afs_int32 a_partID,
2809   afs_int32 a_volID,
2810   struct volintXInfo **a_resultPP,
2811   afs_status_p st)
2812 {
2813     int rc = 0;
2814     afs_status_t tst = 0;
2815     volXEntries volumeXInfo;            /*Area for returned info*/
2816
2817     /*
2818      * Set the area we're in which we are returning
2819      * the info.  Setting the val field to a null pointer tells the stub
2820      * to allocate space for us.
2821      */
2822     *a_resultPP = (volintXInfo *)0;
2823     volumeXInfo.volXEntries_val = (volintXInfo *)0;
2824     volumeXInfo.volXEntries_len = 0;
2825
2826     tst = AFSVolXListOneVolume(server, a_partID, a_volID, &volumeXInfo);
2827
2828     if (tst) {
2829         goto fail_UV_XListOneVolume;
2830     }
2831     else {
2832         /*
2833          * We got the info; pull out the pointer to where the results lie.
2834          */
2835         *a_resultPP = volumeXInfo.volXEntries_val;
2836     }
2837     rc = 1;
2838
2839 fail_UV_XListOneVolume:
2840
2841     if (st != NULL) {
2842         *st = tst;
2843     }
2844     return rc;    
2845
2846 } /*UV_XListOneVolume*/
2847
2848 /*sync vldb with all the entries on <myQueue> on <aserver> and <apart>*/
2849 static afs_int32 ProcessEntries(
2850   afs_cell_handle_p cellHandle,
2851   struct qHead *myQueue,
2852   struct rx_connection *server,
2853   afs_int32 apart,
2854   afs_int32 force)
2855 {
2856     struct aqueue elem;
2857     int success, temp,temp1,temp2;
2858     afs_int32 vcode, maxVolid = 0;
2859     struct nvldbentry entry;
2860     int noError = 1, error, same;
2861     int totalC,totalU,totalCE,totalUE,totalG;
2862     int counter;
2863     int aserver = ntohl(rx_HostOf(rx_PeerOf(server)));
2864     afs_status_t tst;
2865
2866     totalC = totalU = totalCE = totalUE = totalG = 0;
2867     counter = 0;
2868
2869     /* get the next  available id's from the vldb server */
2870     vcode = ubik_Call(VL_GetNewVolumeId,cellHandle->vos, 0, 0, &maxVolid);
2871     if(vcode) {
2872         return (vcode);
2873     }
2874     totalG = myQueue->count;
2875     if(totalG == 0) return 0;
2876     while (1) {
2877         Lp_QEnumerate(myQueue, &success, &elem, 0);
2878         if (!success) break;
2879         counter++;
2880
2881         if(!elem.isValid[RWVOL] && !elem.isValid[ROVOL] && !elem.isValid[BACKVOL]){ /*something is wrong with elem */
2882             noError = 0;
2883             continue;
2884         }
2885         if(maxVolid <= elem.ids[RWVOL]){
2886             temp1 = maxVolid;
2887             temp2 = elem.ids[RWVOL] - maxVolid + 1 ;
2888             maxVolid = 0;
2889             vcode = ubik_Call(VL_GetNewVolumeId,cellHandle->vos, 0, temp2, &maxVolid);
2890             maxVolid += temp2;
2891             
2892             
2893         }
2894         if(maxVolid <= elem.ids[ROVOL]){
2895             
2896             temp1 = maxVolid;
2897             temp2 = elem.ids[ROVOL] - maxVolid + 1;
2898             maxVolid = 0;
2899             vcode = ubik_Call(VL_GetNewVolumeId,cellHandle->vos, 0, temp2, &maxVolid);
2900             maxVolid += temp2;
2901             
2902         }
2903         if(maxVolid <= elem.ids[BACKVOL]){
2904             temp1 = maxVolid;
2905             temp2 = elem.ids[BACKVOL] - temp1 + 1;
2906             maxVolid = 0;
2907             vcode = ubik_Call(VL_GetNewVolumeId,cellHandle->vos, 0, temp2, &maxVolid);
2908             maxVolid += temp2;
2909             
2910         }
2911         VLDB_GetEntryByID(cellHandle, elem.ids[RWVOL], RWVOL, &entry, &tst);
2912         if(tst && (tst != VL_NOENT)){
2913             noError = 0;
2914             totalCE++;
2915         }
2916         else if(tst && (tst == VL_NOENT)) { /*entry doesnot exist */
2917             /*set up a vldb entry for elem */
2918             bzero(&entry, sizeof(entry));
2919             strncpy(entry.name,elem.name,VOLSER_OLDMAXVOLNAME);
2920             if(elem.isValid[RWVOL]) { /*rw exists */
2921                 entry.flags |= RW_EXISTS;
2922                 entry.serverFlags[entry.nServers] = ITSRWVOL;
2923                 entry.serverNumber[entry.nServers] = aserver;
2924                 entry.serverPartition[entry.nServers] = apart;
2925                 entry.nServers += 1;
2926                 entry.volumeId[RWVOL] = elem.ids[RWVOL];
2927                 entry.volumeId[ROVOL] = elem.ids[ROVOL];
2928                 entry.volumeId[BACKVOL] = elem.ids[BACKVOL];
2929             }
2930             if(elem.isValid[ROVOL]) { /*ro volume exists */
2931                 entry.flags |= RO_EXISTS;
2932                 entry.serverFlags[entry.nServers] = ITSROVOL;
2933                 entry.serverNumber[entry.nServers] = aserver;
2934                 entry.serverPartition[entry.nServers] = apart;
2935                 entry.nServers += 1;
2936                 entry.volumeId[RWVOL] = elem.ids[RWVOL];
2937                 entry.volumeId[ROVOL] = elem.ids[ROVOL];
2938                 
2939             }
2940             if(elem.isValid[BACKVOL]) { /*backup volume exists */
2941                 entry.flags |= BACK_EXISTS;
2942                 if(! (entry.flags & RW_EXISTS)) {/*this helps to check for a stray backup if parent moves */
2943                     entry.serverFlags[entry.nServers] = ITSRWVOL;
2944                     entry.serverNumber[entry.nServers] = aserver;
2945                     entry.serverPartition[entry.nServers] = apart;
2946                     entry.nServers += 1;
2947                 }
2948                 
2949                 entry.volumeId[RWVOL] = elem.ids[RWVOL];
2950                 entry.volumeId[BACKVOL] = elem.ids[BACKVOL];
2951                 
2952             }
2953             VLDB_CreateEntry(cellHandle, &entry, &tst);
2954             if(tst) {
2955                 noError = 0;
2956                 totalCE++;
2957             }
2958             else
2959                 totalC++;
2960         }
2961         else { /* Update the existing entry */
2962             strncpy(entry.name,elem.name,VOLSER_OLDMAXVOLNAME); /*the name Could have changed */
2963
2964             if (elem.isValid[RWVOL]) { /* A RW volume */
2965                temp = Lp_GetRwIndex(cellHandle, &entry, 0);
2966                if (temp == -1) {
2967                   /* A RW index is not found in the VLDB entry - will add it */
2968
2969                   entry.flags                          |= RW_EXISTS;
2970                   entry.serverNumber[entry.nServers]    = aserver;
2971                   entry.serverPartition[entry.nServers] = apart;
2972                   entry.serverFlags[entry.nServers]     = ITSRWVOL;
2973                   entry.nServers++;
2974                } else {
2975                   /* A RW index is found in the VLDB entry.
2976                    * Verify that the volume location matches the VLDB location.
2977                    * Fix the VLDB entry if it is not correct.
2978                    */
2979
2980                   error = VLDB_IsSameAddrs(cellHandle, aserver, entry.serverNumber[temp], &same, &tst);
2981                   if (!error) {
2982                      continue;
2983                   }
2984                   if (!same || (apart != entry.serverPartition[temp])) {
2985                      /* VLDB says volume is in another place. Fix the VLDB entry */
2986                      entry.serverNumber[temp]    = aserver;
2987                      entry.serverPartition[temp] = apart;
2988
2989                   }
2990                   entry.flags |= RW_EXISTS;
2991                }
2992                if ((elem.ids[BACKVOL] != 0) && elem.isValid[BACKVOL])
2993                   entry.volumeId[BACKVOL] = elem.ids[BACKVOL];
2994                if ((elem.ids[ROVOL] != 0) && elem.isValid[ROVOL])
2995                   entry.volumeId[ROVOL] = elem.ids[ROVOL];
2996             }
2997
2998             if (elem.isValid[ROVOL]) {
2999                 /*tackle a ro volume */
3000                 
3001                     if(!Lp_ROMatch(cellHandle, &entry, aserver, apart, 0)){
3002                     /*add this site */
3003                         if(elem.ids[ROVOL] > entry.volumeId[ROVOL]) {
3004                             /*there is a conflict of ids, keep the later volume */
3005                             /*delete all the ro volumes listed in vldb entry since they 
3006                              are older */
3007                             
3008                             int j,count, rwsite;
3009
3010
3011                             count = entry.nServers;
3012                             rwsite = -1;
3013                             for(j = 0 ; j < count; j++){
3014                                 if(entry.serverFlags[j] & ITSROVOL){
3015
3016                                     /*delete the site */
3017                                     entry.serverNumber[j] = 0;
3018                                     entry.serverPartition[j] = 0;
3019                                     entry.serverFlags[j] = 0;
3020                                  
3021                                 }
3022                                 else if( entry.serverFlags[j] & ITSRWVOL) 
3023                                     rwsite = j;
3024                             }
3025                             entry.nServers = 0;
3026                             if(rwsite != -1) {
3027                                 entry.serverNumber[entry.nServers] = entry.serverNumber[rwsite];
3028                                 entry.serverPartition[entry.nServers] = entry.serverPartition[rwsite];
3029                                 entry.serverFlags[entry.nServers] = entry.serverFlags[rwsite];
3030                                 entry.nServers++;
3031                             }
3032                             entry.serverNumber[entry.nServers] = aserver;
3033                             entry.serverPartition[entry.nServers] = apart;
3034                             entry.serverFlags[entry.nServers] = ITSROVOL;
3035                             entry.nServers++;
3036                             entry.volumeId[ROVOL] = elem.ids[ROVOL];
3037                             entry.flags |= RO_EXISTS;
3038                             
3039                         }
3040                         else if (elem.ids[ROVOL] < entry.volumeId[ROVOL] ){
3041                             if(!(entry.flags & RO_EXISTS)) {
3042                                 entry.volumeId[ROVOL] = elem.ids[ROVOL];
3043                                 entry.serverNumber[entry.nServers] = aserver;
3044                                 entry.serverPartition[entry.nServers] = apart;
3045                                 entry.serverFlags[entry.nServers] = ITSROVOL;
3046                                 entry.nServers++;
3047                                 entry.flags |= RO_EXISTS;
3048                             }
3049                                 
3050                         }
3051                        
3052                         else if (elem.ids[ROVOL] == entry.volumeId[ROVOL]){
3053                             entry.serverNumber[entry.nServers] = aserver;
3054                             entry.serverPartition[entry.nServers] = apart;
3055                             entry.serverFlags[entry.nServers] = ITSROVOL;
3056                             entry.nServers++;
3057                             entry.flags |= RO_EXISTS;
3058                             entry.volumeId[ROVOL] = elem.ids[ROVOL];
3059                         }
3060                     }
3061                     if(entry.volumeId[ROVOL] == INVALID_BID)
3062                         entry.volumeId[ROVOL] = elem.ids[ROVOL];
3063             }
3064
3065             if (elem.isValid[BACKVOL]) {
3066                 temp = Lp_GetRwIndex(cellHandle, &entry, 0);
3067                 if(temp != -1) { /*check if existing backup site matches with the given arguments */
3068                     error = VLDB_IsSameAddrs(cellHandle, aserver, entry.serverNumber[temp], &same, &tst);
3069                     if (!error) {
3070                         continue;
3071                     }
3072                 }
3073                 else {
3074                     /*tackle the backup volume */
3075                     entry.volumeId[BACKVOL] = elem.ids[BACKVOL];
3076                     entry.flags  |= BACK_EXISTS;
3077                 }
3078                 if(entry.volumeId[BACKVOL] == INVALID_BID) 
3079                     entry.volumeId[BACKVOL] = elem.ids[BACKVOL];
3080            }
3081             
3082            VLDB_ReplaceEntry(cellHandle, elem.ids[RWVOL], RWVOL,
3083                            &entry,
3084                            LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP,
3085                            &tst);
3086            if (tst) {
3087               noError = 0;
3088               totalUE++;
3089
3090               vcode = ubik_Call(VL_ReleaseLock,cellHandle->vos, 0,
3091                                 elem.ids[RWVOL], RWVOL,
3092                                 LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
3093               if(vcode) {
3094                  noError = 0;
3095               }
3096            }
3097         } /* else update the existing entry */
3098
3099     } /* End of while(1) */
3100
3101     if(noError) return 0;
3102     else return VOLSERBADOP;
3103 }
3104
3105 /*synchronise vldb with the file server <aserver> and <apart>(if flags=1).
3106 *else synchronise with all the valid partitions on <aserver>
3107 */
3108 int UV_SyncVldb(
3109   afs_cell_handle_p cellHandle,
3110   struct rx_connection *server,
3111   afs_int32 apart,
3112   int flags,
3113   int force,
3114   afs_status_p st)
3115 {
3116     int rc = 0;
3117     afs_status_t tst = 0;
3118     afs_int32 count;
3119     int i;
3120     volEntries volumeInfo;
3121     volintInfo *pntr;
3122     struct qHead myQueue;
3123     struct partList PartList;
3124     int noError = 1;
3125     afs_int32 cnt;
3126     char pname[10];
3127
3128     /*this hints the stub to allocate space*/
3129     volumeInfo.volEntries_val = (volintInfo *)0;
3130     volumeInfo.volEntries_len = 0;
3131
3132     if(!flags) {/*generate all the valid partitions */
3133         UV_ListPartitions(server, &PartList, &cnt, &tst);
3134         if(tst) {
3135             goto fail_UV_SyncVldb;
3136         }
3137     }  else {
3138         PartList.partId[0] = apart;
3139         cnt = 1;
3140     }
3141
3142     for(i = 0;i < cnt; i++) {
3143             apart = PartList.partId[i];
3144             /*this hints the stub to allocate space*/
3145             volumeInfo.volEntries_val = (volintInfo *)0;
3146             volumeInfo.volEntries_len = 0;
3147             tst = AFSVolListVolumes(server, apart, 1, &volumeInfo);
3148             if(tst) {
3149                 goto fail_UV_SyncVldb;
3150             }
3151             count = volumeInfo.volEntries_len;
3152             pntr = volumeInfo.volEntries_val;
3153  
3154             if (!vos_PartitionIdToName(apart,pname,&tst)) {
3155                 goto fail_UV_SyncVldb;
3156             }
3157             /*collect all vol entries by their parentid */
3158             tst = GroupEntries(server, pntr, count, &myQueue, apart);
3159             if(tst) {
3160                 noError = 0;
3161                 if (volumeInfo.volEntries_val) {
3162                     /*free the space allocated by the stub */
3163                     free(volumeInfo.volEntries_val);
3164                     volumeInfo.volEntries_val = 0;
3165                 }
3166                 continue;
3167             }
3168             tst = ProcessEntries(cellHandle, &myQueue, server, apart, force);
3169             if(tst) {
3170                 tst = VOLSERFAILEDOP;
3171                 if (volumeInfo.volEntries_val) {
3172                     /*free the space allocated by the stub */
3173                     free(volumeInfo.volEntries_val);
3174                     volumeInfo.volEntries_val = 0;
3175                 }
3176                 continue;
3177             }
3178             if(noError) tst = 0;
3179             else tst = VOLSERFAILEDOP;
3180     }/* thru all partitions */
3181     rc = 1;
3182
3183 fail_UV_SyncVldb:
3184
3185     if (volumeInfo.volEntries_val) free(volumeInfo.volEntries_val);
3186
3187     if (tst != 0) {
3188         rc = 0;
3189     }
3190
3191     if (st != NULL) {
3192         *st = tst;
3193     }
3194     return rc;
3195 }
3196
3197 static afs_int32 CheckVldbRWBK(
3198   afs_cell_handle_p cellHandle,
3199   struct nvldbentry *entry,
3200   afs_int32 *modified,
3201   afs_status_p st)
3202 {
3203    int rc = 0;
3204    afs_status_t tst = 0;
3205    int modentry = 0;
3206    int idx;
3207    afs_int32 error = 0;
3208  
3209    if (modified) *modified = 0;
3210    idx = Lp_GetRwIndex(cellHandle, entry, 0);
3211  
3212    /* Check to see if the RW volume exists and set the RW_EXISTS
3213     * flag accordingly.
3214     */
3215    if (idx == -1) {                          /* Did not find a RW entry */
3216       if (entry->flags & RW_EXISTS) {        /* ... yet entry says RW exists */
3217          entry->flags &= ~RW_EXISTS;         /* ... so say RW does not exist */
3218          modentry++;
3219       }
3220    } else {
3221       if (VolumeExists(cellHandle,
3222                           entry->serverNumber[idx],
3223                           entry->serverPartition[idx],
3224                           entry->volumeId[RWVOL], &tst)) {
3225          if (!(entry->flags & RW_EXISTS)) {     /* ... yet entry says RW does no
3226 t exist */
3227             entry->flags |= RW_EXISTS;          /* ... so say RW does exist */
3228             modentry++;
3229          }
3230       }
3231       else if (tst == ENODEV) {                /* RW volume does not exist */
3232          if (entry->flags & RW_EXISTS) {        /* ... yet entry says RW exists
3233 */
3234             entry->flags &= ~RW_EXISTS;         /* ... so say RW does not exist
3235 */
3236             modentry++;
3237          }
3238       }
3239       else {
3240          /* If VLDB says it didn't exist, then ignore error */
3241          if (entry->flags & RW_EXISTS) {
3242              goto fail_CheckVldbRWBK;
3243          }
3244       }
3245    }
3246  
3247    /* Check to see if the BK volume exists and set the BACK_EXISTS
3248     * flag accordingly. idx already ponts to the RW entry.
3249     */
3250    if (idx == -1) {                         /* Did not find a RW entry */
3251       if (entry->flags & BACK_EXISTS) {     /* ... yet entry says BK exists */
3252          entry->flags &= ~BACK_EXISTS;      /* ... so say BK does not exist */
3253          modentry++;
3254       }
3255    }
3256    else {                                            /* Found a RW entry */
3257       if (VolumeExists(cellHandle, entry->serverNumber[idx],
3258                           entry->serverPartition[idx],
3259                           entry->volumeId[BACKVOL], &tst)) {
3260          if (!(entry->flags & BACK_EXISTS)) {    /* ... yet entry says BK does n
3261 ot exist */
3262             entry->flags |= BACK_EXISTS;         /* ... so say BK does exist */
3263             modentry++;
3264          }
3265       }
3266       else if (tst == ENODEV) {                 /* BK volume does not exist */
3267          if (entry->flags & BACK_EXISTS) {       /* ... yet entry says BK exists
3268  */
3269             entry->flags &= ~BACK_EXISTS;        /* ... so say BK does not exist
3270  */
3271             modentry++;
3272          }
3273       }
3274       else {
3275          /* If VLDB says it didn't exist, then ignore error */
3276          if (entry->flags & BACK_EXISTS) {
3277              goto fail_CheckVldbRWBK;
3278          }
3279       }
3280    }
3281  
3282    /* If there is an idx but the BK and RW volumes no
3283     * longer exist, then remove the RW entry.
3284     */
3285    if ((idx != -1) && !(entry->flags & RW_EXISTS) &&
3286                       !(entry->flags & BACK_EXISTS)) {
3287       Lp_SetRWValue(cellHandle, entry, entry->serverNumber[idx],
3288                     entry->serverPartition[idx], 0L, 0L);
3289       entry->nServers--;
3290       modentry++;
3291    }
3292    rc = 1;
3293  
3294  fail_CheckVldbRWBK:
3295
3296    if (modified) *modified = modentry;
3297
3298    if (st != NULL) {
3299       *st = tst;
3300    } 
3301    return rc;
3302 }
3303
3304
3305 static int CheckVldbRO(
3306   afs_cell_handle_p cellHandle,
3307   struct nvldbentry *entry,
3308   afs_int32 *modified,
3309   afs_status_p st)
3310 {
3311    int rc = 0;
3312    afs_status_t tst = 0;
3313    int idx;
3314    int foundro = 0, modentry = 0;
3315    afs_int32 error = 0;
3316  
3317    if (modified) *modified = 0;
3318  
3319    /* Check to see if the RO volumes exist and set the RO_EXISTS
3320     * flag accordingly.
3321     */
3322    for (idx=0; idx < entry->nServers; idx++) {
3323       if (!(entry->serverFlags[idx] & ITSROVOL)) {
3324          continue;   /* not a RO */
3325       }
3326  
3327       if(VolumeExists(cellHandle, entry->serverNumber[idx],
3328                       entry->serverPartition[idx], entry->volumeId[ROVOL],
3329                       &tst)) {
3330          foundro++;
3331       } else if (tst == ENODEV) {                /* RW volume does not exist */
3332          Lp_SetROValue(cellHandle, entry, entry->serverNumber[idx],
3333                        entry->serverPartition[idx], 0L, 0L);
3334          entry->nServers--;
3335          idx--;
3336          modentry++;
3337       }
3338       else {
3339           goto fail_CheckVldbRO;
3340       }
3341    }
3342  
3343    if (foundro) {                            /* A RO volume exists */
3344       if (!(entry->flags & RO_EXISTS)) {     /* ... yet entry says RW does not e
3345 xist */
3346          entry->flags |= RO_EXISTS;          /* ... so say RW does exist */
3347          modentry++;
3348       }
3349    } else {                                  /* A RO volume does not exist */
3350       if (entry->flags & RO_EXISTS) {        /* ... yet entry says RO exists */
3351          entry->flags &= ~RO_EXISTS;         /* ... so say RO does not exist */
3352          modentry++;
3353       }
3354    }
3355    rc = 1;
3356  
3357 fail_CheckVldbRO:
3358
3359    if (modified) *modified = modentry;
3360
3361    if (st != NULL) {
3362        *st = tst;
3363    }
3364    return rc;
3365 }
3366
3367 /*ensure that <entry> matches with the info on file servers */
3368 int CheckVldb(
3369   afs_cell_handle_p cellHandle,
3370   struct nvldbentry *entry,
3371   afs_int32 *modified,
3372   afs_status_p st)
3373 {
3374     int rc = 0;
3375     afs_status_t tst = 0;
3376     afs_int32 vcode;
3377     int islocked;
3378     struct rx_connection *server = NULL;
3379     int pass = 0;
3380     afs_int32 modentry = 0;
3381     afs_int32 delentry = 0;
3382
3383     if (modified) {
3384         *modified = 0;
3385     }
3386
3387     if(strlen(entry->name) > (VOLSER_OLDMAXVOLNAME - 10)) {
3388         tst = VOLSERBADOP;
3389         goto fail_CheckVldb;
3390     }
3391
3392 retry:
3393
3394    /* Check to see if the VLDB is ok without locking it (pass 1).
3395     * If it will change, then lock the VLDB entry, read it again,
3396     * then make the changes to it (pass 2).
3397     */
3398    if (++pass == 2) {
3399       tst = ubik_Call(VL_SetLock, cellHandle->vos, 0,
3400                       entry->volumeId[RWVOL], RWVOL, VLOP_DELETE);
3401       if (tst) {
3402           goto fail_CheckVldb;
3403       }
3404       islocked = 1;
3405  
3406       if (!VLDB_GetEntryByID(cellHandle, entry->volumeId[RWVOL], RWVOL,
3407                              entry, &tst)) {
3408           goto fail_CheckVldb;
3409       }
3410    }
3411  
3412    modentry = 0;
3413  
3414    /* Check if the RW and BK entries are ok */
3415    if (!CheckVldbRWBK(cellHandle, entry, &modentry, &tst)) {
3416       goto fail_CheckVldb;
3417    }
3418    if (modentry && (pass == 1)) goto retry;
3419  
3420    /* Check if the RO volumes entries are ok */
3421    if (!CheckVldbRO(cellHandle, entry, &modentry, &tst)) {
3422       goto fail_CheckVldb;
3423    }
3424    if (modentry && (pass == 1)) goto retry;
3425  
3426    /* The VLDB entry has been updated. If it as been modified, then
3427     * write the entry back out the the VLDB.
3428     */
3429    if (modentry) {
3430       if (pass == 1) goto retry;
3431  
3432       if (!(entry->flags & RW_EXISTS)   &&
3433           !(entry->flags & BACK_EXISTS) &&
3434           !(entry->flags & RO_EXISTS)) {
3435          /* The RW, BK, nor RO volumes do not exist. Delete the VLDB entry */
3436          tst = ubik_Call(VL_DeleteEntry, cellHandle->vos, 0,
3437                          entry->volumeId[RWVOL], RWVOL);
3438          if (tst) {
3439             goto fail_CheckVldb;
3440          }
3441          delentry = 1;
3442       }
3443       else {
3444          /* Replace old entry with our new one */
3445          if (!VLDB_ReplaceEntry(cellHandle, entry->volumeId[RWVOL], RWVOL,
3446                                 entry,
3447                                 (LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP), &tst)) {
3448             goto fail_CheckVldb;
3449          }
3450       }
3451       if (modified) *modified = 1;
3452       islocked = 0;
3453    }
3454    rc = 1;
3455  
3456  fail_CheckVldb:
3457  
3458    if (islocked) {
3459       vcode = ubik_Call(VL_ReleaseLock, cellHandle->vos, 0,
3460                         entry->volumeId[RWVOL], RWVOL,
3461                        (LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP),
3462                        &tst);
3463       if (vcode) {
3464          if (!tst) tst = vcode;
3465       }
3466    }
3467
3468    if (st != NULL) {
3469        *st = tst;
3470    }
3471    return rc;
3472 }
3473
3474 /*synchronise <aserver> <apart>(if flags = 1) with the vldb .
3475 *if flags = 0, synchronise all the valid partitions on <aserver>*/
3476 int UV_SyncServer(
3477   afs_cell_handle_p cellHandle,
3478   struct rx_connection *server,
3479   afs_int32 apart,
3480   int flags,
3481   afs_status_p st)
3482 {
3483     int rc = 0;
3484     afs_status_t tst = 0;
3485     afs_int32 code, vcode;
3486     int noError;
3487     afs_int32 nentries, tentries = 0;
3488     struct VldbListByAttributes attributes;
3489     nbulkentries arrayEntries;
3490     int totalF;
3491     register struct nvldbentry *vllist;
3492     register int j;
3493     afs_int32 si, nsi;
3494     afs_int32 modified = 0;
3495
3496     code = 0;
3497     vcode = 0;
3498     noError = 1;
3499     arrayEntries.nbulkentries_val = 0;
3500
3501     /* Set up attributes to search VLDB  */
3502     attributes.server = ntohl(rx_HostOf(rx_PeerOf(server)));
3503     attributes.Mask = VLLIST_SERVER;
3504     if(flags) {
3505         attributes.partition = apart;
3506         attributes.Mask |= VLLIST_PARTITION;
3507     }
3508
3509     for(si = 0;si != -1; si=nsi) {
3510             /*initialize to hint the stub  to alloc space */
3511             bzero(&arrayEntries, sizeof(arrayEntries)); 
3512             if (!VLDB_ListAttributes(cellHandle, &attributes, &nentries,
3513                                      &arrayEntries, &tst)) {
3514                 goto fail_UV_SyncServer;
3515             }
3516             nsi = -1;
3517             tentries += nentries;
3518             totalF = 0;
3519             for(j=0;j<nentries;j++) {   /* process each entry */
3520                 vllist = &arrayEntries.nbulkentries_val[j];
3521                 if (!CheckVldb(cellHandle, vllist, &modified, &tst)) {
3522                     noError = 0;
3523                     totalF++;
3524                 }
3525             }
3526             if(arrayEntries.nbulkentries_val) {
3527                 free(arrayEntries.nbulkentries_val);
3528                 arrayEntries.nbulkentries_val = 0;
3529             }
3530     }
3531     rc = 1;
3532
3533 fail_UV_SyncServer:    
3534
3535     if(arrayEntries.nbulkentries_val) {
3536         free(arrayEntries.nbulkentries_val);
3537     }
3538     if(!noError) tst = VOLSERFAILEDOP;
3539     if (st != NULL) {
3540         *st = tst;
3541     }
3542     return rc;
3543 }
3544
3545 /*rename volume <oldname> to <newname>, changing the names of the related 
3546  *readonly and backup volumes. This operation is also idempotent.
3547  *salvager is capable of recovering from rename operation stopping halfway.
3548  *to recover run syncserver on the affected machines,it will force renaming to completion. name clashes should have been detected before calling this proc */
3549 int UV_RenameVolume(
3550   afs_cell_handle_p cellHandle,
3551   struct nvldbentry *entry,
3552   const char *newname,
3553   afs_status_p st)
3554 {
3555     int rc = 0;
3556     afs_status_t tst = 0;
3557     afs_status_t etst = 0;
3558     afs_int32 rcode,error;
3559     int i,index;
3560     char nameBuffer[256];
3561     afs_int32 tid;
3562     struct rx_connection *aconn;
3563     int islocked;
3564
3565     error = 0;
3566     aconn = (struct rx_connection *)0;
3567     tid = 0;
3568     islocked = 0;
3569
3570     tst = ubik_Call(VL_SetLock, cellHandle->vos, 0, entry->volumeId[RWVOL],
3571                     RWVOL, VLOP_ADDSITE);/*last param is dummy*/
3572     if(tst){
3573         goto fail_UV_RenameVolume;
3574     }
3575     islocked = 1;
3576
3577     strncpy(entry->name,newname,VOLSER_OLDMAXVOLNAME);
3578
3579     if (!VLDB_ReplaceEntry(cellHandle, entry->volumeId[RWVOL], RWVOL,
3580                            entry, 0, &tst)) {
3581         goto fail_UV_RenameVolume;
3582     }
3583     /*at this stage the intent to rename is recorded in the vldb, as far
3584       as the vldb 
3585       is concerned, oldname is lost */
3586     if(entry->flags & RW_EXISTS) {
3587         index = Lp_GetRwIndex(cellHandle, entry, 0);
3588         if(index == -1){ /* there is a serious discrepancy */
3589             tst = VOLSERVLDB_ERROR;
3590             goto fail_UV_RenameVolume;
3591         }
3592         aconn = UV_Bind(cellHandle, entry->serverNumber[index], 
3593                         AFSCONF_VOLUMEPORT);
3594         tst = AFSVolTransCreate(aconn,entry->volumeId[RWVOL],entry->serverPartition[index],  ITOffline, &tid);
3595         if(tst) { /*volume doesnot exist */
3596             goto fail_UV_RenameVolume;
3597         }
3598         else {/*volume exists, process it */
3599
3600             tst = AFSVolSetIdsTypes(aconn, tid, newname,RWVOL, entry->volumeId[RWVOL],entry->volumeId[ROVOL],entry->volumeId[BACKVOL]);
3601             if(!tst) {
3602                 tst = AFSVolEndTrans(aconn, tid, &rcode);
3603                 tid = 0;
3604                 if(tst) {
3605                     goto fail_UV_RenameVolume;
3606                 }
3607             }
3608             else {
3609                 goto fail_UV_RenameVolume;
3610             }
3611         }
3612         if(aconn) rx_ReleaseCachedConnection(aconn);
3613         aconn = (struct rx_connection *)0;
3614     } /*end rw volume processing */
3615
3616     if(entry->flags & BACK_EXISTS) {/*process the backup volume */
3617         index = Lp_GetRwIndex(cellHandle, entry, 0);
3618         if(index == -1){ /* there is a serious discrepancy */
3619             tst = VOLSERVLDB_ERROR;
3620             goto fail_UV_RenameVolume;
3621         }
3622         aconn = UV_Bind(cellHandle, entry->serverNumber[index],
3623                         AFSCONF_VOLUMEPORT);
3624         tst = AFSVolTransCreate(aconn,entry->volumeId[BACKVOL],entry->serverPartition[index],  ITOffline, &tid);
3625         if(tst) { /*volume doesnot exist */
3626             goto fail_UV_RenameVolume;
3627         }
3628         else {/*volume exists, process it */
3629             if(strlen(newname) > (VOLSER_OLDMAXVOLNAME - 8)){
3630                 goto fail_UV_RenameVolume;
3631             }
3632             strcpy(nameBuffer,newname);
3633             strcat(nameBuffer,".backup");
3634
3635             tst = AFSVolSetIdsTypes(aconn, tid,nameBuffer ,BACKVOL, entry->volumeId[RWVOL],0,0);
3636             if(!tst) {
3637                 tst = AFSVolEndTrans(aconn, tid, &rcode);
3638                 tid = 0;
3639                 if(tst) {
3640                     goto fail_UV_RenameVolume;
3641                 }
3642             }
3643             else {
3644                 goto fail_UV_RenameVolume;
3645             }
3646         }
3647     } /* end backup processing */
3648     if(aconn) rx_ReleaseCachedConnection(aconn);
3649     aconn = (struct rx_connection *)0;
3650     if(entry->flags & RO_EXISTS){  /*process the ro volumes */
3651         for(i = 0; i < entry->nServers; i++){
3652             if(entry->serverFlags[i] & ITSROVOL) {
3653                 aconn = UV_Bind(cellHandle, entry->serverNumber[i],
3654                                 AFSCONF_VOLUMEPORT);
3655                 tst = AFSVolTransCreate(aconn,entry->volumeId[ROVOL],entry->serverPartition[i],  ITOffline, &tid);
3656                 if(tst) { /*volume doesnot exist */
3657                     goto fail_UV_RenameVolume;
3658                 }
3659                 else {/*volume exists, process it */
3660                     strcpy(nameBuffer,newname);
3661                     strcat(nameBuffer,".readonly");
3662                     if(strlen(nameBuffer) > (VOLSER_OLDMAXVOLNAME - 1)){
3663                         goto fail_UV_RenameVolume;
3664                     }
3665                     tst = AFSVolSetIdsTypes(aconn, tid, nameBuffer,ROVOL, entry->volumeId[RWVOL],0,0);
3666                     if(!tst) {
3667                         tst = AFSVolEndTrans(aconn, tid, &rcode);
3668                         tid = 0;
3669                         if (tst) {
3670                             goto fail_UV_RenameVolume;
3671                         }
3672                     }
3673                     else {
3674                         goto fail_UV_RenameVolume;
3675                     }
3676                 }
3677                 if(aconn) rx_ReleaseCachedConnection(aconn);
3678                 aconn = (struct rx_connection *)0;
3679             }
3680         }
3681     }
3682     rc = 1;
3683
3684 fail_UV_RenameVolume:
3685
3686     if(islocked) {
3687         etst = ubik_Call(VL_ReleaseLock, cellHandle->vos, 0,entry->volumeId[RWVOL] , RWVOL, LOCKREL_OPCODE | LOCKREL_AFSID | LOCKREL_TIMESTAMP);
3688         if(etst){
3689             if(!tst) tst = etst;
3690         }
3691     }
3692     if(tid) {
3693         etst = AFSVolEndTrans(aconn, tid, &rcode);
3694         if(etst){
3695             if(!tst) tst = etst;
3696         }
3697     }
3698     if(aconn) rx_ReleaseCachedConnection(aconn);
3699
3700     if (st != NULL) {
3701         *st = tst;
3702     }
3703     return rc;
3704 }
3705
3706 /*group all the volume entries on< apart >by their parentid or by their ids'
3707 *if the volume is rw. <count> is the number of entries to be processesd.
3708 *<pntr> points to the first entry.< myQueue> is the queue with entries 
3709 *grouped */
3710 static int GroupEntries(
3711   struct rx_connection *server,
3712   volintInfo *pntr,
3713   afs_int32 count,
3714   struct qHead *myQueue,
3715   afs_int32 apart)
3716 {
3717     struct aqueue *qPtr;
3718     int success;
3719     afs_int32 curId, code;
3720     int i;
3721     afs_int32 error = 0;
3722     
3723     
3724     Lp_QInit(myQueue);
3725     if(count == 0)
3726         return 0;
3727     for(i = 0; i < count; i++){/*process each entry */
3728         if(pntr->status) {/* entry is valid */
3729             if(pntr->type == RWVOL) curId = pntr->volid;
3730             else curId = pntr->parentID;
3731             Lp_QScan(myQueue,curId, &success, &qPtr, 0);
3732             if(success){ /*entry exists in the queue */
3733                 if(pntr->type == RWVOL) {
3734                     /*check if the rw exists already, if so hang on the
3735                         later version if the present version is ok */
3736                     if(qPtr->isValid[RWVOL]) {
3737                     /*this should not happen, there is a serious error here*/
3738                         if(!error) error  = VOLSERMULTIRWVOL;
3739                     }
3740                     else {
3741                         qPtr->isValid[RWVOL] = 1;
3742                         qPtr->copyDate[RWVOL] = pntr->copyDate;
3743                         if(!qPtr->isValid[BACKVOL]) qPtr->ids[BACKVOL] = pntr->backupID;
3744                         if(!qPtr->isValid[ROVOL]) qPtr->ids[ROVOL] = pntr->cloneID;
3745                     }
3746                 }
3747                 else if(pntr->type == BACKVOL) {
3748                     if(qPtr->isValid[BACKVOL]){
3749                         /*do different checks, delete superflous volume */
3750                         if(qPtr->copyDate[BACKVOL] > pntr->copyDate) {
3751                             /*delete the present volume .*/
3752                             code = CheckAndDeleteVolume(server,apart,0,pntr->volid);
3753                             if(code) {
3754                                 if(!error) error = code;
3755                             }
3756                             
3757                         }
3758                         else {
3759                             /*delete the older volume after making sure, current one is ok*/
3760                             code = CheckAndDeleteVolume(server,apart,pntr->volid,qPtr->ids[BACKVOL]);
3761                             if(code) {
3762                                 if(!error) error = code;
3763                             }
3764                             
3765                             qPtr->copyDate[BACKVOL] = pntr->copyDate;
3766                             qPtr->ids[BACKVOL] = pntr->volid;
3767
3768                         }
3769                     }
3770                     else {
3771                         qPtr->isValid[BACKVOL] = 1;
3772                         qPtr->ids[BACKVOL] = pntr->volid;
3773                         qPtr->copyDate[BACKVOL] = pntr->copyDate;
3774                     }
3775                 }
3776                 else if(pntr->type == ROVOL) {
3777                     if(qPtr->isValid[ROVOL]){
3778                         /*do different checks, delete superflous volume */
3779                         if(qPtr->copyDate[ROVOL] > pntr->copyDate) {
3780                             /*delete the present volume .*/
3781                             /*a hack */
3782                             code = CheckAndDeleteVolume(server,apart,0,pntr->volid);
3783                             if(code) {
3784                                 if(!error) error = code;
3785                             }
3786                         }
3787                         else {
3788                             /*delete the older volume after making sure, current one is ok*/
3789                             code = CheckAndDeleteVolume(server,apart,pntr->volid,qPtr->ids[ROVOL]);
3790                             if(code) {
3791                                 if(!error) error = code;
3792                             }
3793
3794                             qPtr->copyDate[ROVOL] = pntr->copyDate;
3795                             qPtr->ids[ROVOL] = pntr->volid;
3796
3797                         }
3798                     }
3799                     else {
3800                         qPtr->isValid[ROVOL] = 1;
3801                         qPtr->ids[ROVOL] = pntr->volid;
3802                         qPtr->copyDate[ROVOL] = pntr->copyDate;
3803                     }
3804                 }
3805                 else {
3806                     if(!error) error = VOLSERBADOP;
3807                 }
3808             }
3809             else { /*create a fresh entry */
3810                 qPtr = (struct aqueue *) malloc(sizeof(struct aqueue));
3811                 if(pntr->type == RWVOL) {
3812                     qPtr->isValid[RWVOL] = 1;
3813                     qPtr->isValid[BACKVOL] = 0;
3814                     qPtr->isValid[ROVOL] = 0;
3815                     qPtr->ids[RWVOL] = pntr->volid;
3816                     qPtr->ids[BACKVOL] = pntr->backupID;
3817                     qPtr->ids[ROVOL] = pntr->cloneID;
3818                     qPtr->copyDate[RWVOL] = pntr->copyDate;
3819                     strncpy(qPtr->name, pntr->name,VOLSER_OLDMAXVOLNAME);
3820                     qPtr->next = (struct aqueue *)0;
3821                 }
3822                 else if(pntr->type == BACKVOL) {
3823                     qPtr->isValid[RWVOL] = 0;
3824                     qPtr->isValid[BACKVOL] = 1;
3825                     qPtr->isValid[ROVOL] = 0;
3826                     qPtr->ids[RWVOL] = pntr->parentID;
3827                     qPtr->ids[BACKVOL] = pntr->volid;
3828                     qPtr->ids[ROVOL] = 0;
3829                     qPtr->copyDate[BACKVOL] = pntr->copyDate;
3830                     vsu_ExtractName(qPtr->name, pntr->name);
3831                     qPtr->next = (struct aqueue *)0;
3832                 }
3833                 else if(pntr->type == ROVOL) {
3834                     qPtr->isValid[RWVOL] = 0;
3835                     qPtr->isValid[BACKVOL] = 0;
3836                     qPtr->isValid[ROVOL] = 1;
3837                     qPtr->ids[RWVOL] = pntr->parentID;
3838                     qPtr->ids[BACKVOL] = 0;
3839                     qPtr->ids[ROVOL] = pntr->volid;
3840                     qPtr->copyDate[ROVOL] = pntr->copyDate;
3841                     vsu_ExtractName(qPtr->name, pntr->name);
3842                     qPtr->next = (struct aqueue *)0;
3843
3844                 }
3845                 Lp_QAdd(myQueue,qPtr);
3846             }
3847             pntr++;/*get next entry */
3848         }
3849         else {
3850             pntr++;
3851             continue;
3852         }
3853     }/* for loop */
3854
3855     return error;
3856 }
3857
3858 /*report on all the active transactions on volser */
3859 int UV_VolserStatus(
3860   struct rx_connection *server,
3861   transDebugInfo **rpntr,
3862   afs_int32 *rcount,
3863   afs_status_p st)
3864 {
3865     int rc = 0;
3866     afs_status_t tst = 0;
3867     transDebugEntries transInfo;
3868     
3869     transInfo.transDebugEntries_val = (transDebugInfo *) 0;
3870     transInfo.transDebugEntries_len = 0;
3871     tst = AFSVolMonitor(server,&transInfo);
3872     if(tst) {
3873         goto fail_UV_VolserStatus;
3874     }
3875
3876     *rcount = transInfo.transDebugEntries_len;
3877     *rpntr = transInfo.transDebugEntries_val;
3878     rc = 1;
3879
3880 fail_UV_VolserStatus:
3881
3882     if (rc == 0) {
3883         if (transInfo.transDebugEntries_val) {
3884             free(transInfo.transDebugEntries_val);
3885         }
3886     }
3887
3888     if (st != NULL) {
3889         *st = tst;
3890     }
3891     return rc;
3892 }
3893
3894 /*delete the volume without interacting with the vldb */
3895 int UV_VolumeZap(
3896   afs_cell_handle_p cellHandle,
3897   struct rx_connection *server,
3898   unsigned int partition,
3899   unsigned int volumeId,
3900   afs_status_p st)
3901 {
3902     afs_int32 rcode,ttid,error,code;
3903     int rc = 0;
3904     afs_status_t tst = 0;
3905
3906     code = 0;
3907     error = 0;
3908     ttid = 0;
3909  
3910     tst = AFSVolTransCreate(server, volumeId, partition, ITOffline, &ttid);
3911     if(!tst){
3912         tst = AFSVolDeleteVolume(server, ttid);
3913         if (!tst) {
3914             tst = AFSVolEndTrans(server, ttid, &rcode);
3915             if (!tst) {
3916                 if (rcode) {
3917                     tst = rcode;
3918                 }
3919             }
3920         } else {
3921             /*
3922              * We failed to delete the volume, but we still need
3923              * to end the transaction.
3924              */
3925             AFSVolEndTrans(server, ttid, &rcode);
3926         }
3927         rc = 1;
3928     }
3929                 
3930     if (st != NULL) {
3931         *st = tst;
3932     }
3933     return rc;
3934 }
3935
3936 int UV_SetVolume(
3937   struct rx_connection *server,
3938   afs_int32 partition,
3939   afs_int32 volid,
3940   afs_int32 transflag,
3941   afs_int32 setflag,
3942   unsigned int sleepTime,
3943   afs_status_p st)
3944 {
3945     int rc = 0;
3946     afs_status_t tst = 0;
3947     afs_status_t etst = 0;
3948     afs_int32 tid=0;
3949     afs_int32 rcode;
3950
3951     tst = AFSVolTransCreate(server, volid, partition, transflag, &tid);
3952     if (tst) {
3953         goto fail_UV_SetVolume;
3954     }
3955
3956     tst = AFSVolSetFlags(server, tid, setflag);
3957     if (tst) {
3958         goto fail_UV_SetVolume;
3959     }
3960
3961     if (sleepTime) {
3962         sleep(sleepTime);
3963     }
3964     rc = 1;
3965
3966 fail_UV_SetVolume:
3967
3968     if (tid) {
3969         etst = AFSVolEndTrans(server, tid, &rcode);
3970         if (etst || etst) {
3971             if (!tst) tst = (etst ? etst : rcode);
3972         }
3973     }
3974
3975     if (st != NULL) {
3976         *st = tst;
3977     }
3978     return rc;
3979 }