fcbaec6d51b657fd0087a324b17b454ba3591595
[openafs.git] / src / ubik / recovery.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  *
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 #include <afsconfig.h>
11 #include <afs/param.h>
12
13 #include <roken.h>
14
15 #include <afs/opr.h>
16
17 #ifdef AFS_PTHREAD_ENV
18 # include <opr/lock.h>
19 #else
20 # include <opr/lockstub.h>
21 #endif
22
23 #include <rx/rx.h>
24 #include <afs/afsutil.h>
25 #include <afs/cellconfig.h>
26
27
28 #define UBIK_INTERNALS
29 #include "ubik.h"
30 #include "ubik_int.h"
31
32 /*! \file
33  * This module is responsible for determining when the system has
34  * recovered to the point that it can handle new transactions.  It
35  * replays logs, polls to determine the current dbase after a crash,
36  * and distributes the new database to the others.
37  *
38  * The sync site associates a version number with each database.  It
39  * broadcasts the version associated with its current dbase in every
40  * one of its beacon messages.  When the sync site send a dbase to a
41  * server, it also sends the db's version.  A non-sync site server can
42  * tell if it has the right dbase version by simply comparing the
43  * version from the beacon message \p uvote_dbVersion with the version
44  * associated with the database \p ubik_dbase->version.  The sync site
45  * itself simply has one counter to keep track of all of this (again
46  * \p ubik_dbase->version).
47  *
48  * sync site: routine called when the sync site loses its quorum; this
49  * procedure is called "up" from the beacon package.  It resyncs the
50  * dbase and nudges the recovery daemon to try to propagate out the
51  * changes.  It also resets the recovery daemon's state, since
52  * recovery must potentially find a new dbase to propagate out.  This
53  * routine should not do anything with variables used by non-sync site
54  * servers.
55  */
56
57 /*!
58  * if this flag is set, then ubik will use only the primary address
59  * (the address specified in the CellServDB) to contact other
60  * ubik servers. Ubik recovery will not try opening connections
61  * to the alternate interface addresses.
62  */
63 int ubikPrimaryAddrOnly;
64
65 int
66 urecovery_ResetState(void)
67 {
68     urecovery_state = 0;
69 #if !defined(AFS_PTHREAD_ENV)
70     /*  No corresponding LWP_WaitProcess found anywhere for this -- klm */
71     LWP_NoYieldSignal(&urecovery_state);
72 #endif
73     return 0;
74 }
75
76 /*!
77  * \brief sync site
78  *
79  * routine called when a non-sync site server goes down; restarts recovery
80  * process to send missing server the new db when it comes back up for
81  * non-sync site servers.
82  *
83  * \note This routine should not do anything with variables used by non-sync site servers.
84  */
85 int
86 urecovery_LostServer(struct ubik_server *ts)
87 {
88     ubeacon_ReinitServer(ts);
89 #if !defined(AFS_PTHREAD_ENV)
90     /*  No corresponding LWP_WaitProcess found anywhere for this -- klm */
91     LWP_NoYieldSignal(&urecovery_state);
92 #endif
93     return 0;
94 }
95
96 /*!
97  * return true iff we have a current database (called by both sync
98  * sites and non-sync sites) How do we determine this?  If we're the
99  * sync site, we wait until recovery has finished fetching and
100  * re-labelling its dbase (it may still be trying to propagate it out
101  * to everyone else; that's THEIR problem).  If we're not the sync
102  * site, then we must have a dbase labelled with the right version,
103  * and we must have a currently-good sync site.
104  */
105 int
106 urecovery_AllBetter(struct ubik_dbase *adbase, int areadAny)
107 {
108     afs_int32 rcode;
109
110     ubik_dprint_25("allbetter checking\n");
111     rcode = 0;
112
113
114     if (areadAny) {
115         if (ubik_dbase->version.epoch > 1)
116             rcode = 1;          /* Happy with any good version of database */
117     }
118
119     /* Check if we're sync site and we've got the right data */
120     else if (ubeacon_AmSyncSite() && (urecovery_state & UBIK_RECHAVEDB)) {
121         rcode = 1;
122     }
123
124     /* next, check if we're aux site, and we've ever been sent the
125      * right data (note that if a dbase update fails, we won't think
126      * that the sync site is still the sync site, 'cause it won't talk
127      * to us until a timeout period has gone by.  When we recover, we
128      * leave this clear until we get a new dbase */
129     else if (uvote_HaveSyncAndVersion(ubik_dbase->version)) {
130         rcode = 1;
131     }
132
133     ubik_dprint_25("allbetter: returning %d\n", rcode);
134     return rcode;
135 }
136
137 /*!
138  * \brief abort all transactions on this database
139  */
140 int
141 urecovery_AbortAll(struct ubik_dbase *adbase)
142 {
143     struct ubik_trans *tt;
144     for (tt = adbase->activeTrans; tt; tt = tt->next) {
145         udisk_abort(tt);
146     }
147     return 0;
148 }
149
150 /*!
151  * \brief this routine aborts the current remote transaction, if any, if the tid is wrong
152  */
153 int
154 urecovery_CheckTid(struct ubik_tid *atid, int abortalways)
155 {
156     if (ubik_currentTrans) {
157         /* there is remote write trans, see if we match, see if this
158          * is a new transaction */
159         if (atid->epoch != ubik_currentTrans->tid.epoch
160             || atid->counter > ubik_currentTrans->tid.counter || abortalways) {
161             /* don't match, abort it */
162             /* If the thread is not waiting for lock - ok to end it */
163             if (ubik_currentTrans->locktype != LOCKWAIT) {
164                 udisk_end(ubik_currentTrans);
165             }
166             ubik_currentTrans = (struct ubik_trans *)0;
167         }
168     }
169     return 0;
170 }
171
172 /*!
173  * \brief replay logs
174  *
175  * log format is defined here, and implicitly in disk.c
176  *
177  * 4 byte opcode, followed by parameters, each 4 bytes long.  All integers
178  * are in logged in network standard byte order, in case we want to move logs
179  * from machine-to-machine someday.
180  *
181  * Begin transaction: opcode \n
182  * Commit transaction: opcode, version (8 bytes) \n
183  * Truncate file: opcode, file number, length \n
184  * Abort transaction: opcode \n
185  * Write data: opcode, file, position, length, <length> data bytes \n
186  *
187  * A very simple routine, it just replays the log.  Note that this is a new-value only log, which
188  * implies that no uncommitted data is written to the dbase: one writes data to the log, including
189  * the commit record, then we allow data to be written through to the dbase.  In our particular
190  * implementation, once a transaction is done, we write out the pages to the database, so that
191  * our buffer package doesn't have to know about stable and uncommitted data in the memory buffers:
192  * any changed data while there is an uncommitted write transaction can be zapped during an
193  * abort and the remaining dbase on the disk is exactly the right dbase, without having to read
194  * the log.
195  */
196 static int
197 ReplayLog(struct ubik_dbase *adbase)
198 {
199     afs_int32 opcode;
200     afs_int32 code, tpos;
201     int logIsGood;
202     afs_int32 len, thisSize, tfile, filePos;
203     afs_int32 buffer[4];
204     afs_int32 syncFile = -1;
205     afs_int32 data[1024];
206
207     /* read the lock twice, once to see whether we have a transaction to deal
208      * with that committed, (theoretically, we should support more than one
209      * trans in the log at once, but not yet), and once replaying the
210      * transactions.  */
211     tpos = 0;
212     logIsGood = 0;
213     /* for now, assume that all ops in log pertain to one transaction; see if there's a commit */
214     while (1) {
215         code =
216             (*adbase->read) (adbase, LOGFILE, (char *)&opcode, tpos,
217                              sizeof(afs_int32));
218         if (code != sizeof(afs_int32))
219             break;
220         opcode = ntohl(opcode);
221         if (opcode == LOGNEW) {
222             /* handle begin trans */
223             tpos += sizeof(afs_int32);
224         } else if (opcode == LOGABORT)
225             break;
226         else if (opcode == LOGEND) {
227             logIsGood = 1;
228             break;
229         } else if (opcode == LOGTRUNCATE) {
230             tpos += 4;
231             code =
232                 (*adbase->read) (adbase, LOGFILE, (char *)buffer, tpos,
233                                  2 * sizeof(afs_int32));
234             if (code != 2 * sizeof(afs_int32))
235                 break;          /* premature eof or io error */
236             tpos += 2 * sizeof(afs_int32);
237         } else if (opcode == LOGDATA) {
238             tpos += 4;
239             code =
240                 (*adbase->read) (adbase, LOGFILE, (char *)buffer, tpos,
241                                  3 * sizeof(afs_int32));
242             if (code != 3 * sizeof(afs_int32))
243                 break;
244             /* otherwise, skip over the data bytes, too */
245             tpos += ntohl(buffer[2]) + 3 * sizeof(afs_int32);
246         } else {
247             ubik_print("corrupt log opcode (%d) at position %d\n", opcode,
248                        tpos);
249             break;              /* corrupt log! */
250         }
251     }
252     if (logIsGood) {
253         /* actually do the replay; log should go all the way through the commit record, since
254          * we just read it above. */
255         tpos = 0;
256         logIsGood = 0;
257         syncFile = -1;
258         while (1) {
259             code =
260                 (*adbase->read) (adbase, LOGFILE, (char *)&opcode, tpos,
261                                  sizeof(afs_int32));
262             if (code != sizeof(afs_int32))
263                 break;
264             opcode = ntohl(opcode);
265             if (opcode == LOGNEW) {
266                 /* handle begin trans */
267                 tpos += sizeof(afs_int32);
268             } else if (opcode == LOGABORT)
269                 panic("log abort\n");
270             else if (opcode == LOGEND) {
271                 struct ubik_version version;
272                 tpos += 4;
273                 code =
274                     (*adbase->read) (adbase, LOGFILE, (char *)buffer, tpos,
275                                      2 * sizeof(afs_int32));
276                 if (code != 2 * sizeof(afs_int32))
277                     return UBADLOG;
278                 version.epoch = ntohl(buffer[0]);
279                 version.counter = ntohl(buffer[1]);
280                 code = (*adbase->setlabel) (adbase, 0, &version);
281                 if (code)
282                     return code;
283                 ubik_print("Successfully replayed log for interrupted "
284                            "transaction; db version is now %ld.%ld\n",
285                            (long) version.epoch, (long) version.counter);
286                 logIsGood = 1;
287                 break;          /* all done now */
288             } else if (opcode == LOGTRUNCATE) {
289                 tpos += 4;
290                 code =
291                     (*adbase->read) (adbase, LOGFILE, (char *)buffer, tpos,
292                                      2 * sizeof(afs_int32));
293                 if (code != 2 * sizeof(afs_int32))
294                     break;      /* premature eof or io error */
295                 tpos += 2 * sizeof(afs_int32);
296                 code =
297                     (*adbase->truncate) (adbase, ntohl(buffer[0]),
298                                          ntohl(buffer[1]));
299                 if (code)
300                     return code;
301             } else if (opcode == LOGDATA) {
302                 tpos += 4;
303                 code =
304                     (*adbase->read) (adbase, LOGFILE, (char *)buffer, tpos,
305                                      3 * sizeof(afs_int32));
306                 if (code != 3 * sizeof(afs_int32))
307                     break;
308                 tpos += 3 * sizeof(afs_int32);
309                 /* otherwise, skip over the data bytes, too */
310                 len = ntohl(buffer[2]); /* total number of bytes to copy */
311                 filePos = ntohl(buffer[1]);
312                 tfile = ntohl(buffer[0]);
313                 /* try to minimize file syncs */
314                 if (syncFile != tfile) {
315                     if (syncFile >= 0)
316                         code = (*adbase->sync) (adbase, syncFile);
317                     else
318                         code = 0;
319                     syncFile = tfile;
320                     if (code)
321                         return code;
322                 }
323                 while (len > 0) {
324                     thisSize = (len > sizeof(data) ? sizeof(data) : len);
325                     /* copy sizeof(data) buffer bytes at a time */
326                     code =
327                         (*adbase->read) (adbase, LOGFILE, (char *)data, tpos,
328                                          thisSize);
329                     if (code != thisSize)
330                         return UBADLOG;
331                     code =
332                         (*adbase->write) (adbase, tfile, (char *)data, filePos,
333                                           thisSize);
334                     if (code != thisSize)
335                         return UBADLOG;
336                     filePos += thisSize;
337                     tpos += thisSize;
338                     len -= thisSize;
339                 }
340             } else {
341                 ubik_print("corrupt log opcode (%d) at position %d\n",
342                            opcode, tpos);
343                 break;          /* corrupt log! */
344             }
345         }
346         if (logIsGood) {
347             if (syncFile >= 0)
348                 code = (*adbase->sync) (adbase, syncFile);
349             if (code)
350                 return code;
351         } else {
352             ubik_print("Log read error on pass 2\n");
353             return UBADLOG;
354         }
355     }
356
357     /* now truncate the log, we're done with it */
358     code = (*adbase->truncate) (adbase, LOGFILE, 0);
359     return code;
360 }
361
362 /*! \brief
363  * Called at initialization to figure out version of the dbase we really have.
364  *
365  * This routine is called after replaying the log; it reads the restored labels.
366  */
367 static int
368 InitializeDB(struct ubik_dbase *adbase)
369 {
370     afs_int32 code;
371
372     code = (*adbase->getlabel) (adbase, 0, &adbase->version);
373     if (code) {
374         /* try setting the label to a new value */
375         UBIK_VERSION_LOCK;
376         adbase->version.epoch = 1;      /* value for newly-initialized db */
377         adbase->version.counter = 1;
378         code = (*adbase->setlabel) (adbase, 0, &adbase->version);
379         if (code) {
380             /* failed, try to set it back */
381             adbase->version.epoch = 0;
382             adbase->version.counter = 0;
383             (*adbase->setlabel) (adbase, 0, &adbase->version);
384         }
385 #ifdef AFS_PTHREAD_ENV
386         opr_cv_broadcast(&adbase->version_cond);
387 #else
388         LWP_NoYieldSignal(&adbase->version);
389 #endif
390         UBIK_VERSION_UNLOCK;
391     }
392     return 0;
393 }
394
395 /*!
396  * \brief initialize the local ubik_dbase
397  *
398  * We replay the logs and then read the resulting file to figure out what version we've really got.
399  */
400 int
401 urecovery_Initialize(struct ubik_dbase *adbase)
402 {
403     afs_int32 code;
404
405     DBHOLD(adbase);
406     code = ReplayLog(adbase);
407     if (code)
408         goto done;
409     code = InitializeDB(adbase);
410 done:
411     DBRELE(adbase);
412     return code;
413 }
414
415 /*!
416  * \brief Main interaction loop for the recovery manager
417  *
418  * The recovery light-weight process only runs when you're the
419  * synchronization site.  It performs the following tasks, if and only
420  * if the prerequisite tasks have been performed successfully (it
421  * keeps track of which ones have been performed in its bit map,
422  * \p urecovery_state).
423  *
424  * First, it is responsible for probing that all servers are up.  This
425  * is the only operation that must be performed even if this is not
426  * yet the sync site, since otherwise this site may not notice that
427  * enough other machines are running to even elect this guy to be the
428  * sync site.
429  *
430  * After that, the recovery process does nothing until the beacon and
431  * voting modules manage to get this site elected sync site.
432  *
433  * After becoming sync site, recovery first attempts to find the best
434  * database available in the network (it must do this in order to
435  * ensure finding the latest committed data).  After finding the right
436  * database, it must fetch this dbase to the sync site.
437  *
438  * After fetching the dbase, it relabels it with a new version number,
439  * to ensure that everyone recognizes this dbase as the most recent
440  * dbase.
441  *
442  * One the dbase has been relabelled, this machine can start handling
443  * requests.  However, the recovery module still has one more task:
444  * propagating the dbase out to everyone who is up in the network.
445  */
446 void *
447 urecovery_Interact(void *dummy)
448 {
449     afs_int32 code;
450     struct ubik_server *bestServer = NULL;
451     struct ubik_server *ts;
452     int dbok, doingRPC, now;
453     afs_int32 lastProbeTime;
454     /* if we're the sync site, the best db version we've found yet */
455     static struct ubik_version bestDBVersion;
456     struct ubik_version tversion;
457     struct timeval tv;
458     int length, tlen, offset, file, nbytes;
459     struct rx_call *rxcall;
460     char tbuffer[1024];
461     struct ubik_stat ubikstat;
462     struct in_addr inAddr;
463     char hoststr[16];
464     char pbuffer[1028];
465     int fd = -1;
466     afs_int32 pass;
467
468     afs_pthread_setname_self("recovery");
469
470     /* otherwise, begin interaction */
471     urecovery_state = 0;
472     lastProbeTime = 0;
473     while (1) {
474         /* Run through this loop every 4 seconds */
475         tv.tv_sec = 4;
476         tv.tv_usec = 0;
477 #ifdef AFS_PTHREAD_ENV
478         select(0, 0, 0, 0, &tv);
479 #else
480         IOMGR_Select(0, 0, 0, 0, &tv);
481 #endif
482
483         ubik_dprint("recovery running in state %x\n", urecovery_state);
484
485         /* Every 30 seconds, check all the down servers and mark them
486          * as up if they respond. When a server comes up or found to
487          * not be current, then re-find the the best database and
488          * propogate it.
489          */
490         if ((now = FT_ApproxTime()) > 30 + lastProbeTime) {
491
492             for (ts = ubik_servers, doingRPC = 0; ts; ts = ts->next) {
493                 UBIK_BEACON_LOCK;
494                 if (!ts->up) {
495                     UBIK_BEACON_UNLOCK;
496                     doingRPC = 1;
497                     code = DoProbe(ts);
498                     if (code == 0) {
499                         UBIK_BEACON_LOCK;
500                         ts->up = 1;
501                         UBIK_BEACON_UNLOCK;
502                         DBHOLD(ubik_dbase);
503                         urecovery_state &= ~UBIK_RECFOUNDDB;
504                         DBRELE(ubik_dbase);
505                     }
506                 } else {
507                     UBIK_BEACON_UNLOCK;
508                     DBHOLD(ubik_dbase);
509                     if (!ts->currentDB)
510                         urecovery_state &= ~UBIK_RECFOUNDDB;
511                     DBRELE(ubik_dbase);
512                 }
513             }
514
515             if (doingRPC)
516                 now = FT_ApproxTime();
517             lastProbeTime = now;
518         }
519
520         /* Mark whether we are the sync site */
521         DBHOLD(ubik_dbase);
522         if (!ubeacon_AmSyncSite()) {
523             urecovery_state &= ~UBIK_RECSYNCSITE;
524             DBRELE(ubik_dbase);
525             continue;           /* nothing to do */
526         }
527         urecovery_state |= UBIK_RECSYNCSITE;
528
529         /* If a server has just come up or if we have not found the
530          * most current database, then go find the most current db.
531          */
532         if (!(urecovery_state & UBIK_RECFOUNDDB)) {
533             DBRELE(ubik_dbase);
534             bestServer = (struct ubik_server *)0;
535             bestDBVersion.epoch = 0;
536             bestDBVersion.counter = 0;
537             for (ts = ubik_servers; ts; ts = ts->next) {
538                 UBIK_BEACON_LOCK;
539                 if (!ts->up) {
540                     UBIK_BEACON_UNLOCK;
541                     continue;   /* don't bother with these guys */
542                 }
543                 UBIK_BEACON_UNLOCK;
544                 if (ts->isClone)
545                     continue;
546                 UBIK_ADDR_LOCK;
547                 code = DISK_GetVersion(ts->disk_rxcid, &ts->version);
548                 UBIK_ADDR_UNLOCK;
549                 if (code == 0) {
550                     /* perhaps this is the best version */
551                     if (vcmp(ts->version, bestDBVersion) > 0) {
552                         /* new best version */
553                         bestDBVersion = ts->version;
554                         bestServer = ts;
555                     }
556                 }
557             }
558             /* take into consideration our version. Remember if we,
559              * the sync site, have the best version. Also note that
560              * we may need to send the best version out.
561              */
562             DBHOLD(ubik_dbase);
563             if (vcmp(ubik_dbase->version, bestDBVersion) >= 0) {
564                 bestDBVersion = ubik_dbase->version;
565                 bestServer = (struct ubik_server *)0;
566                 urecovery_state |= UBIK_RECHAVEDB;
567             } else {
568                 /* Clear the flag only when we know we have to retrieve
569                  * the db. Because urecovery_AllBetter() looks at it.
570                  */
571                 urecovery_state &= ~UBIK_RECHAVEDB;
572             }
573             urecovery_state |= UBIK_RECFOUNDDB;
574             urecovery_state &= ~UBIK_RECSENTDB;
575         }
576         if (!(urecovery_state & UBIK_RECFOUNDDB)) {
577             DBRELE(ubik_dbase);
578             continue;           /* not ready */
579         }
580
581         /* If we, the sync site, do not have the best db version, then
582          * go and get it from the server that does.
583          */
584         if ((urecovery_state & UBIK_RECHAVEDB) || !bestServer) {
585             urecovery_state |= UBIK_RECHAVEDB;
586         } else {
587             /* we don't have the best version; we should fetch it. */
588             urecovery_AbortAll(ubik_dbase);
589
590             /* Rx code to do the Bulk fetch */
591             file = 0;
592             offset = 0;
593             UBIK_ADDR_LOCK;
594             rxcall = rx_NewCall(bestServer->disk_rxcid);
595
596             ubik_print("Ubik: Synchronize database with server %s\n",
597                        afs_inet_ntoa_r(bestServer->addr[0], hoststr));
598             UBIK_ADDR_UNLOCK;
599
600             code = StartDISK_GetFile(rxcall, file);
601             if (code) {
602                 ubik_dprint("StartDiskGetFile failed=%d\n", code);
603                 goto FetchEndCall;
604             }
605             nbytes = rx_Read(rxcall, (char *)&length, sizeof(afs_int32));
606             length = ntohl(length);
607             if (nbytes != sizeof(afs_int32)) {
608                 ubik_dprint("Rx-read length error=%d\n", code = BULK_ERROR);
609                 code = EIO;
610                 goto FetchEndCall;
611             }
612
613             /* give invalid label during file transit */
614             UBIK_VERSION_LOCK;
615             tversion.epoch = 0;
616             code = (*ubik_dbase->setlabel) (ubik_dbase, file, &tversion);
617             UBIK_VERSION_UNLOCK;
618             if (code) {
619                 ubik_dprint("setlabel io error=%d\n", code);
620                 goto FetchEndCall;
621             }
622             snprintf(pbuffer, sizeof(pbuffer), "%s.DB%s%d.TMP",
623                      ubik_dbase->pathName, (file<0)?"SYS":"",
624                      (file<0)?-file:file);
625             fd = open(pbuffer, O_CREAT | O_RDWR | O_TRUNC, 0600);
626             if (fd < 0) {
627                 code = errno;
628                 goto FetchEndCall;
629             }
630             code = lseek(fd, HDRSIZE, 0);
631             if (code != HDRSIZE) {
632                 close(fd);
633                 goto FetchEndCall;
634             }
635
636             pass = 0;
637             while (length > 0) {
638                 tlen = (length > sizeof(tbuffer) ? sizeof(tbuffer) : length);
639 #ifndef AFS_PTHREAD_ENV
640                 if (pass % 4 == 0)
641                     IOMGR_Poll();
642 #endif
643                 nbytes = rx_Read(rxcall, tbuffer, tlen);
644                 if (nbytes != tlen) {
645                     ubik_dprint("Rx-read bulk error=%d\n", code = BULK_ERROR);
646                     code = EIO;
647                     close(fd);
648                     goto FetchEndCall;
649                 }
650                 nbytes = write(fd, tbuffer, tlen);
651                 pass++;
652                 if (nbytes != tlen) {
653                     code = UIOERROR;
654                     close(fd);
655                     goto FetchEndCall;
656                 }
657                 offset += tlen;
658                 length -= tlen;
659             }
660             code = close(fd);
661             if (code)
662                 goto FetchEndCall;
663             code = EndDISK_GetFile(rxcall, &tversion);
664           FetchEndCall:
665             code = rx_EndCall(rxcall, code);
666             if (!code) {
667                 /* we got a new file, set up its header */
668                 urecovery_state |= UBIK_RECHAVEDB;
669                 UBIK_VERSION_LOCK;
670                 memcpy(&ubik_dbase->version, &tversion,
671                        sizeof(struct ubik_version));
672                 snprintf(tbuffer, sizeof(tbuffer), "%s.DB%s%d",
673                          ubik_dbase->pathName, (file<0)?"SYS":"",
674                          (file<0)?-file:file);
675 #ifdef AFS_NT40_ENV
676                 snprintf(pbuffer, sizeof(pbuffer), "%s.DB%s%d.OLD",
677                          ubik_dbase->pathName, (file<0)?"SYS":"",
678                          (file<0)?-file:file);
679                 code = unlink(pbuffer);
680                 if (!code)
681                     code = rename(tbuffer, pbuffer);
682                 snprintf(pbuffer, sizeof(pbuffer), "%s.DB%s%d.TMP",
683                          ubik_dbase->pathName, (file<0)?"SYS":"",
684                          (file<0)?-file:file);
685 #endif
686                 if (!code)
687                     code = rename(pbuffer, tbuffer);
688                 if (!code) {
689                     (*ubik_dbase->open) (ubik_dbase, file);
690                     /* after data is good, sync disk with correct label */
691                     code =
692                         (*ubik_dbase->setlabel) (ubik_dbase, 0,
693                                                  &ubik_dbase->version);
694                 }
695                 UBIK_VERSION_UNLOCK;
696 #ifdef AFS_NT40_ENV
697                 snprintf(pbuffer, sizeof(pbuffer), "%s.DB%s%d.OLD",
698                          ubik_dbase->pathName, (file<0)?"SYS":"",
699                          (file<0)?-file:file);
700                 unlink(pbuffer);
701 #endif
702             }
703             if (code) {
704                 unlink(pbuffer);
705                 /*
706                  * We will effectively invalidate the old data forever now.
707                  * Unclear if we *should* but we do.
708                  */
709                 UBIK_VERSION_LOCK;
710                 ubik_dbase->version.epoch = 0;
711                 ubik_dbase->version.counter = 0;
712                 UBIK_VERSION_UNLOCK;
713                 ubik_print("Ubik: Synchronize database failed (error = %d)\n",
714                            code);
715             } else {
716                 ubik_print("Ubik: Synchronize database completed\n");
717                 urecovery_state |= UBIK_RECHAVEDB;
718             }
719             udisk_Invalidate(ubik_dbase, 0);    /* data has changed */
720 #ifdef AFS_PTHREAD_ENV
721             opr_cv_broadcast(&ubik_dbase->version_cond);
722 #else
723             LWP_NoYieldSignal(&ubik_dbase->version);
724 #endif
725         }
726         if (!(urecovery_state & UBIK_RECHAVEDB)) {
727             DBRELE(ubik_dbase);
728             continue;           /* not ready */
729         }
730
731         /* If the database was newly initialized, then when we establish quorum, write
732          * a new label. This allows urecovery_AllBetter() to allow access for reads.
733          * Setting it to 2 also allows another site to come along with a newer
734          * database and overwrite this one.
735          */
736         if (ubik_dbase->version.epoch == 1) {
737             urecovery_AbortAll(ubik_dbase);
738             UBIK_VERSION_LOCK;
739             version_globals.ubik_epochTime = 2;
740             ubik_dbase->version.epoch = version_globals.ubik_epochTime;
741             ubik_dbase->version.counter = 1;
742             code =
743                 (*ubik_dbase->setlabel) (ubik_dbase, 0, &ubik_dbase->version);
744             UBIK_VERSION_UNLOCK;
745             udisk_Invalidate(ubik_dbase, 0);    /* data may have changed */
746 #ifdef AFS_PTHREAD_ENV
747             opr_cv_broadcast(&ubik_dbase->version_cond);
748 #else
749             LWP_NoYieldSignal(&ubik_dbase->version);
750 #endif
751         }
752
753         /* Check the other sites and send the database to them if they
754          * do not have the current db.
755          */
756         if (!(urecovery_state & UBIK_RECSENTDB)) {
757             /* now propagate out new version to everyone else */
758             dbok = 1;           /* start off assuming they all worked */
759
760             /*
761              * Check if a write transaction is in progress. We can't send the
762              * db when a write is in progress here because the db would be
763              * obsolete as soon as it goes there. Also, ops after the begin
764              * trans would reach the recepient and wouldn't find a transaction
765              * pending there.  Frankly, I don't think it's possible to get past
766              * the write-lock above if there is a write transaction in progress,
767              * but then, it won't hurt to check, will it?
768              */
769             if (ubik_dbase->flags & DBWRITING) {
770                 struct timeval tv;
771                 int safety = 0;
772                 long cur_usec = 50000;
773                 while ((ubik_dbase->flags & DBWRITING) && (safety < 500)) {
774                     DBRELE(ubik_dbase);
775                     /* sleep for a little while */
776                     tv.tv_sec = 0;
777                     tv.tv_usec = cur_usec;
778 #ifdef AFS_PTHREAD_ENV
779                     select(0, 0, 0, 0, &tv);
780 #else
781                     IOMGR_Select(0, 0, 0, 0, &tv);
782 #endif
783                     cur_usec += 10000;
784                     safety++;
785                     DBHOLD(ubik_dbase);
786                 }
787             }
788
789             for (ts = ubik_servers; ts; ts = ts->next) {
790                 UBIK_ADDR_LOCK;
791                 inAddr.s_addr = ts->addr[0];
792                 UBIK_ADDR_UNLOCK;
793                 UBIK_BEACON_LOCK;
794                 if (!ts->up) {
795                     UBIK_BEACON_UNLOCK;
796                     ubik_dprint("recovery cannot send version to %s\n",
797                                 afs_inet_ntoa_r(inAddr.s_addr, hoststr));
798                     dbok = 0;
799                     continue;
800                 }
801                 UBIK_BEACON_UNLOCK;
802                 ubik_dprint("recovery sending version to %s\n",
803                             afs_inet_ntoa_r(inAddr.s_addr, hoststr));
804                 if (vcmp(ts->version, ubik_dbase->version) != 0) {
805                     ubik_dprint("recovery stating local database\n");
806
807                     /* Rx code to do the Bulk Store */
808                     code = (*ubik_dbase->stat) (ubik_dbase, 0, &ubikstat);
809                     if (!code) {
810                         length = ubikstat.size;
811                         file = offset = 0;
812                         UBIK_ADDR_LOCK;
813                         rxcall = rx_NewCall(ts->disk_rxcid);
814                         UBIK_ADDR_UNLOCK;
815                         code =
816                             StartDISK_SendFile(rxcall, file, length,
817                                                &ubik_dbase->version);
818                         if (code) {
819                             ubik_dprint("StartDiskSendFile failed=%d\n",
820                                         code);
821                             goto StoreEndCall;
822                         }
823                         while (length > 0) {
824                             tlen =
825                                 (length >
826                                  sizeof(tbuffer) ? sizeof(tbuffer) : length);
827                             nbytes =
828                                 (*ubik_dbase->read) (ubik_dbase, file,
829                                                      tbuffer, offset, tlen);
830                             if (nbytes != tlen) {
831                                 ubik_dprint("Local disk read error=%d\n",
832                                             code = UIOERROR);
833                                 goto StoreEndCall;
834                             }
835                             nbytes = rx_Write(rxcall, tbuffer, tlen);
836                             if (nbytes != tlen) {
837                                 ubik_dprint("Rx-write bulk error=%d\n", code =
838                                             BULK_ERROR);
839                                 goto StoreEndCall;
840                             }
841                             offset += tlen;
842                             length -= tlen;
843                         }
844                         code = EndDISK_SendFile(rxcall);
845                       StoreEndCall:
846                         code = rx_EndCall(rxcall, code);
847                     }
848                     if (code == 0) {
849                         /* we set a new file, process its header */
850                         ts->version = ubik_dbase->version;
851                         ts->currentDB = 1;
852                     } else
853                         dbok = 0;
854                 } else {
855                     /* mark file up to date */
856                     ts->currentDB = 1;
857                 }
858             }
859             if (dbok)
860                 urecovery_state |= UBIK_RECSENTDB;
861         }
862         DBRELE(ubik_dbase);
863     }
864     return NULL;
865 }
866
867 /*!
868  * \brief send a Probe to all the network address of this server
869  *
870  * \return 0 if success, else return 1
871  */
872 int
873 DoProbe(struct ubik_server *server)
874 {
875     struct rx_connection *conns[UBIK_MAX_INTERFACE_ADDR];
876     struct rx_connection *connSuccess = 0;
877     int i, nconns, success_i = -1;
878     afs_uint32 addr;
879     char buffer[32];
880     char hoststr[16];
881
882     UBIK_ADDR_LOCK;
883     for (i = 0; (i < UBIK_MAX_INTERFACE_ADDR) && (addr = server->addr[i]);
884          i++) {
885         conns[i] =
886             rx_NewConnection(addr, ubik_callPortal, DISK_SERVICE_ID,
887                              addr_globals.ubikSecClass, addr_globals.ubikSecIndex);
888
889         /* user requirement to use only the primary interface */
890         if (ubikPrimaryAddrOnly) {
891             i = 1;
892             break;
893         }
894     }
895     UBIK_ADDR_UNLOCK;
896     nconns = i;
897     opr_Assert(nconns);                 /* at least one interface address for this server */
898
899     multi_Rx(conns, nconns) {
900         multi_DISK_Probe();
901         if (!multi_error) {     /* first success */
902             success_i = multi_i;
903
904             multi_Abort;
905         }
906     } multi_End_Ignore;
907
908     if (success_i >= 0) {
909         UBIK_ADDR_LOCK;
910         addr = server->addr[success_i]; /* successful interface addr */
911
912         if (server->disk_rxcid) /* destroy existing conn */
913             rx_DestroyConnection(server->disk_rxcid);
914         if (server->vote_rxcid)
915             rx_DestroyConnection(server->vote_rxcid);
916
917         /* make new connections */
918         server->disk_rxcid = conns[success_i];
919         server->vote_rxcid = rx_NewConnection(addr, ubik_callPortal,
920                                               VOTE_SERVICE_ID, addr_globals.ubikSecClass,
921                                               addr_globals.ubikSecIndex);
922
923         connSuccess = conns[success_i];
924         strcpy(buffer, afs_inet_ntoa_r(server->addr[0], hoststr));
925
926         ubik_print("ubik:server %s is back up: will be contacted through %s\n",
927              buffer, afs_inet_ntoa_r(addr, hoststr));
928         UBIK_ADDR_UNLOCK;
929     }
930
931     /* Destroy all connections except the one on which we succeeded */
932     for (i = 0; i < nconns; i++)
933         if (conns[i] != connSuccess)
934             rx_DestroyConnection(conns[i]);
935
936     if (!connSuccess)
937         ubik_dprint("ubik:server %s still down\n",
938                     afs_inet_ntoa_r(server->addr[0], hoststr));
939
940     if (connSuccess)
941         return 0;               /* success */
942     else
943         return 1;               /* failure */
944 }