2 * Copyright 2000, International Business Machines Corporation and others.
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
10 #include <afsconfig.h>
11 #include <afs/param.h>
14 #include <sys/types.h>
23 #include <netinet/in.h>
24 #include <sys/param.h>
30 #include <afs/cellconfig.h>
32 #define UBIK_INTERNALS
36 #include <lwp.h> /* temporary hack by klm */
38 #define ERROR_EXIT(code) {error=(code); goto error_exit;}
42 * This system is organized in a hierarchical set of related modules. Modules
43 * at one level can only call modules at the same level or below.
45 * At the bottom level (0) we have R, RFTP, LWP and IOMGR, i.e. the basic
46 * operating system primitives.
48 * At the next level (1) we have
50 * \li VOTER--The module responsible for casting votes when asked. It is also
51 * responsible for determining whether this server should try to become
52 * a synchronization site.
53 * \li BEACONER--The module responsible for sending keep-alives out when a
54 * server is actually the sync site, or trying to become a sync site.
55 * \li DISK--The module responsible for representing atomic transactions
56 * on the local disk. It maintains a new-value only log.
57 * \li LOCK--The module responsible for locking byte ranges in the database file.
59 * At the next level (2) we have
61 * \li RECOVERY--The module responsible for ensuring that all members of a quorum
62 * have the same up-to-date database after a new synchronization site is
63 * elected. This module runs only on the synchronization site.
65 * At the next level (3) we have
67 * \li REMOTE--The module responsible for interpreting requests from the sync
68 * site and applying them to the database, after obtaining the appropriate
71 * At the next level (4) we have
73 * \li UBIK--The module users call to perform operations on the database.
78 afs_int32 ubik_quorum = 0;
79 struct ubik_dbase *ubik_dbase = 0;
80 struct ubik_stats ubik_stats;
81 afs_uint32 ubik_host[UBIK_MAX_INTERFACE_ADDR];
82 afs_int32 ubik_epochTime = 0;
83 afs_int32 urecovery_state = 0;
84 int (*ubik_SRXSecurityProc) (void *, struct rx_securityClass **, afs_int32 *);
85 void *ubik_SRXSecurityRock;
86 int (*ubik_SyncWriterCacheProc) (void);
87 struct ubik_server *ubik_servers;
88 short ubik_callPortal;
90 static int BeginTrans(register struct ubik_dbase *dbase, afs_int32 transMode,
91 struct ubik_trans **transPtr, int readAny);
93 struct rx_securityClass *ubik_sc[3];
95 #define CStampVersion 1 /* meaning set ts->version */
98 * \brief Perform an operation at a quorum, handling error conditions.
99 * \return 0 if all worked and a quorum was contacted successfully
100 * \return otherwise mark failing server as down and return #UERROR
102 * \note If any server misses an update, we must wait #BIGTIME seconds before
103 * allowing the transaction to commit, to ensure that the missing and
104 * possibly still functioning server times out and stops handing out old
105 * data. This is done in the commit code, where we wait for a server marked
106 * down to have stayed down for #BIGTIME seconds before we allow a transaction
107 * to commit. A server that fails but comes back up won't give out old data
108 * because it is sent the sync count along with the beacon message that
109 * marks it as \b really up (\p beaconSinceDown).
112 ContactQuorum_NoArguments(afs_int32 (*proc)(struct rx_connection *, ubik_tid *),
113 register struct ubik_trans *atrans, int aflags)
115 register struct ubik_server *ts;
116 register afs_int32 code;
117 afs_int32 rcode, okcalls;
121 for (ts = ubik_servers; ts; ts = ts->next) {
122 /* for each server */
123 if (!ts->up || !ts->currentDB) {
124 ts->currentDB = 0; /* db is no longer current; we just missed an update */
125 continue; /* not up-to-date, don't bother */
127 code = (*proc)(ts->disk_rxcid, &atrans->tid);
128 if (code) { /* failure */
130 ts->up = 0; /* mark as down now; beacons will no longer be sent */
132 ts->beaconSinceDown = 0;
133 urecovery_LostServer(); /* tell recovery to try to resend dbase later */
134 } else { /* success */
136 okcalls++; /* count up how many worked */
137 if (aflags & CStampVersion) {
138 ts->version = atrans->dbase->version;
142 /* return 0 if we successfully contacted a quorum, otherwise return error code. We don't have to contact ourselves (that was done locally) */
143 if (okcalls + 1 >= ubik_quorum)
150 ContactQuorum_DISK_Lock(register struct ubik_trans *atrans, int aflags,afs_int32 file,
151 afs_int32 position, afs_int32 length, afs_int32 type)
153 register struct ubik_server *ts;
154 register afs_int32 code;
155 afs_int32 rcode, okcalls;
159 for (ts = ubik_servers; ts; ts = ts->next) {
160 /* for each server */
161 if (!ts->up || !ts->currentDB) {
162 ts->currentDB = 0; /* db is no longer current; we just missed an update */
163 continue; /* not up-to-date, don't bother */
165 code = DISK_Lock(ts->disk_rxcid, &atrans->tid, file, position, length,
167 if (code) { /* failure */
169 ts->up = 0; /* mark as down now; beacons will no longer be sent */
171 ts->beaconSinceDown = 0;
172 urecovery_LostServer(); /* tell recovery to try to resend dbase later */
173 } else { /* success */
175 okcalls++; /* count up how many worked */
176 if (aflags & CStampVersion) {
177 ts->version = atrans->dbase->version;
181 /* return 0 if we successfully contacted a quorum, otherwise return error code. We don't have to contact ourselves (that was done locally) */
182 if (okcalls + 1 >= ubik_quorum)
189 ContactQuorum_DISK_Write(register struct ubik_trans *atrans, int aflags,
190 afs_int32 file, afs_int32 position, bulkdata *data)
192 register struct ubik_server *ts;
193 register afs_int32 code;
194 afs_int32 rcode, okcalls;
198 for (ts = ubik_servers; ts; ts = ts->next) {
199 /* for each server */
200 if (!ts->up || !ts->currentDB) {
201 ts->currentDB = 0; /* db is no longer current; we just missed an update */
202 continue; /* not up-to-date, don't bother */
204 code = DISK_Write(ts->disk_rxcid, &atrans->tid, file, position, data);
205 if (code) { /* failure */
207 ts->up = 0; /* mark as down now; beacons will no longer be sent */
209 ts->beaconSinceDown = 0;
210 urecovery_LostServer(); /* tell recovery to try to resend dbase later */
211 } else { /* success */
213 okcalls++; /* count up how many worked */
214 if (aflags & CStampVersion) {
215 ts->version = atrans->dbase->version;
219 /* return 0 if we successfully contacted a quorum, otherwise return error code. We don't have to contact ourselves (that was done locally) */
220 if (okcalls + 1 >= ubik_quorum)
227 ContactQuorum_DISK_Truncate(register struct ubik_trans *atrans, int aflags,
228 afs_int32 file, afs_int32 length)
230 register struct ubik_server *ts;
231 register afs_int32 code;
232 afs_int32 rcode, okcalls;
236 for (ts = ubik_servers; ts; ts = ts->next) {
237 /* for each server */
238 if (!ts->up || !ts->currentDB) {
239 ts->currentDB = 0; /* db is no longer current; we just missed an update */
240 continue; /* not up-to-date, don't bother */
242 code = DISK_Truncate(ts->disk_rxcid, &atrans->tid, file, length);
243 if (code) { /* failure */
245 ts->up = 0; /* mark as down now; beacons will no longer be sent */
247 ts->beaconSinceDown = 0;
248 urecovery_LostServer(); /* tell recovery to try to resend dbase later */
249 } else { /* success */
251 okcalls++; /* count up how many worked */
252 if (aflags & CStampVersion) {
253 ts->version = atrans->dbase->version;
257 /* return 0 if we successfully contacted a quorum, otherwise return error code. We don't have to contact ourselves (that was done locally) */
258 if (okcalls + 1 >= ubik_quorum)
265 ContactQuorum_DISK_WriteV(register struct ubik_trans *atrans, int aflags,
266 iovec_wrt * io_vector, iovec_buf *io_buffer)
268 register struct ubik_server *ts;
269 register afs_int32 code;
270 afs_int32 rcode, okcalls;
274 for (ts = ubik_servers; ts; ts = ts->next) {
275 /* for each server */
276 if (!ts->up || !ts->currentDB) {
277 ts->currentDB = 0; /* db is no longer current; we just missed an update */
278 continue; /* not up-to-date, don't bother */
281 code = DISK_WriteV(ts->disk_rxcid, &atrans->tid, io_vector, io_buffer);
283 if ((code <= -450) && (code > -500)) {
284 /* An RPC interface mismatch (as defined in comerr/error_msg.c).
285 * Un-bulk the entries and do individual DISK_Write calls
286 * instead of DISK_WriteV.
288 struct ubik_iovec *iovec =
289 (struct ubik_iovec *)io_vector->iovec_wrt_val;
290 char *iobuf = (char *)io_buffer->iovec_buf_val;
294 for (i = 0, offset = 0; i < io_vector->iovec_wrt_len; i++) {
295 /* Sanity check for going off end of buffer */
296 if ((offset + iovec[i].length) > io_buffer->iovec_buf_len) {
300 tcbs.bulkdata_len = iovec[i].length;
301 tcbs.bulkdata_val = &iobuf[offset];
303 DISK_Write(ts->disk_rxcid, &atrans->tid, iovec[i].file,
304 iovec[i].position, &tcbs);
308 offset += iovec[i].length;
312 if (code) { /* failure */
314 ts->up = 0; /* mark as down now; beacons will no longer be sent */
316 ts->beaconSinceDown = 0;
317 urecovery_LostServer(); /* tell recovery to try to resend dbase later */
318 } else { /* success */
320 okcalls++; /* count up how many worked */
321 if (aflags & CStampVersion) {
322 ts->version = atrans->dbase->version;
326 /* return 0 if we successfully contacted a quorum, otherwise return error code. We don't have to contact ourselves (that was done locally) */
327 if (okcalls + 1 >= ubik_quorum)
334 ContactQuorum_DISK_SetVersion(register struct ubik_trans *atrans, int aflags,
335 ubik_version *OldVersion,
336 ubik_version *NewVersion)
338 register struct ubik_server *ts;
339 register afs_int32 code;
340 afs_int32 rcode, okcalls;
344 for (ts = ubik_servers; ts; ts = ts->next) {
345 /* for each server */
346 if (!ts->up || !ts->currentDB) {
347 ts->currentDB = 0; /* db is no longer current; we just missed an update */
348 continue; /* not up-to-date, don't bother */
350 code = DISK_SetVersion(ts->disk_rxcid, &atrans->tid, OldVersion,
352 if (code) { /* failure */
354 ts->up = 0; /* mark as down now; beacons will no longer be sent */
356 ts->beaconSinceDown = 0;
357 urecovery_LostServer(); /* tell recovery to try to resend dbase later */
358 } else { /* success */
360 okcalls++; /* count up how many worked */
361 if (aflags & CStampVersion) {
362 ts->version = atrans->dbase->version;
366 /* return 0 if we successfully contacted a quorum, otherwise return error code. We don't have to contact ourselves (that was done locally) */
367 if (okcalls + 1 >= ubik_quorum)
374 * \brief This routine initializes the ubik system for a set of servers.
375 * \return 0 for success, or an error code on failure.
376 * \param serverList set of servers specified; nServers gives the number of entries in this array.
377 * \param pathName provides an initial prefix used for naming storage files used by this system.
378 * \param dbase the returned structure representing this instance of an ubik; it is passed to various calls below.
380 * \todo This routine should perhaps be generalized to a low-level disk interface providing read, write, file enumeration and sync operations.
382 * \warning The host named by myHost should not also be listed in serverList.
384 * \see ubik_ServerInit(), ubik_ServerInitByInfo()
387 ubik_ServerInitCommon(afs_int32 myHost, short myPort,
388 struct afsconf_cell *info, char clones[],
389 afs_int32 serverList[], const char *pathName,
390 struct ubik_dbase **dbase)
392 register struct ubik_dbase *tdb;
393 register afs_int32 code;
394 #ifdef AFS_PTHREAD_ENV
395 pthread_t rxServerThread; /* pthread variables */
396 pthread_t ubeacon_InteractThread;
397 pthread_t urecovery_InteractThread;
398 pthread_attr_t rxServer_tattr;
399 pthread_attr_t ubeacon_Interact_tattr;
400 pthread_attr_t urecovery_Interact_tattr;
403 extern int rx_stackSize;
407 struct rx_securityClass *secClass;
409 struct rx_service *tservice;
411 initialize_U_error_table();
413 tdb = (struct ubik_dbase *)malloc(sizeof(struct ubik_dbase));
414 tdb->pathName = (char *)malloc(strlen(pathName) + 1);
415 strcpy(tdb->pathName, pathName);
416 tdb->activeTrans = (struct ubik_trans *)0;
417 memset(&tdb->version, 0, sizeof(struct ubik_version));
418 memset(&tdb->cachedVersion, 0, sizeof(struct ubik_version));
419 #ifdef AFS_PTHREAD_ENV
420 assert(pthread_mutex_init(&tdb->versionLock, NULL) == 0);
422 Lock_Init(&tdb->versionLock);
424 Lock_Init(&tdb->cache_lock);
426 tdb->read = uphys_read;
427 tdb->write = uphys_write;
428 tdb->truncate = uphys_truncate;
429 tdb->open = uphys_invalidate; /* this function isn't used any more */
430 tdb->sync = uphys_sync;
431 tdb->stat = uphys_stat;
432 tdb->getlabel = uphys_getlabel;
433 tdb->setlabel = uphys_setlabel;
434 tdb->getnfiles = uphys_getnfiles;
436 tdb->tidCounter = tdb->writeTidCounter = 0;
438 ubik_dbase = tdb; /* for now, only one db per server; can fix later when we have names for the other dbases */
440 #ifdef AFS_PTHREAD_ENV
441 assert(pthread_cond_init(&tdb->version_cond, NULL) == 0);
442 assert(pthread_cond_init(&tdb->flags_cond, NULL) == 0);
443 #endif /* AFS_PTHREAD_ENV */
447 /* the following call is idempotent so when/if it got called earlier,
448 * by whatever called us, it doesn't really matter -- klm */
449 code = rx_Init(myPort);
453 ubik_callPortal = myPort;
454 /* try to get an additional security object */
455 ubik_sc[0] = rxnull_NewServerSecurityObject();
458 if (ubik_SRXSecurityProc) {
460 (*ubik_SRXSecurityProc) (ubik_SRXSecurityRock, &secClass,
463 ubik_sc[secIndex] = secClass;
466 /* for backwards compat this should keep working as it does now
469 /* This really needs to be up above, where I have put it. It works
470 * here when we're non-pthreaded, but the code above, when using
471 * pthreads may (and almost certainly does) end up calling on a
472 * pthread resource which gets initialized by rx_Init. The end
473 * result is that an assert fails and the program dies. -- klm
475 code = rx_Init(myPort);
481 rx_NewService(0, VOTE_SERVICE_ID, "VOTE", ubik_sc, 3,
482 VOTE_ExecuteRequest);
483 if (tservice == (struct rx_service *)0) {
484 ubik_dprint("Could not create VOTE rx service!\n");
487 rx_SetMinProcs(tservice, 2);
488 rx_SetMaxProcs(tservice, 3);
491 rx_NewService(0, DISK_SERVICE_ID, "DISK", ubik_sc, 3,
492 DISK_ExecuteRequest);
493 if (tservice == (struct rx_service *)0) {
494 ubik_dprint("Could not create DISK rx service!\n");
497 rx_SetMinProcs(tservice, 2);
498 rx_SetMaxProcs(tservice, 3);
500 /* start an rx_ServerProc to handle incoming RPC's in particular the
501 * UpdateInterfaceAddr RPC that occurs in ubeacon_InitServerList. This avoids
502 * the "steplock" problem in ubik initialization. Defect 11037.
504 #ifdef AFS_PTHREAD_ENV
505 /* do assert stuff */
506 assert(pthread_attr_init(&rxServer_tattr) == 0);
507 assert(pthread_attr_setdetachstate(&rxServer_tattr, PTHREAD_CREATE_DETACHED) == 0);
508 /* assert(pthread_attr_setstacksize(&rxServer_tattr, rx_stackSize) == 0); */
510 assert(pthread_create(&rxServerThread, &rxServer_tattr, (void *)rx_ServerProc, NULL) == 0);
512 LWP_CreateProcess(rx_ServerProc, rx_stackSize, RX_PROCESS_PRIORITY,
513 NULL, "rx_ServerProc", &junk);
516 /* do basic initialization */
520 code = urecovery_Initialize(tdb);
524 code = ubeacon_InitServerListByInfo(myHost, info, clones);
526 code = ubeacon_InitServerList(myHost, serverList);
530 /* now start up async processes */
531 #ifdef AFS_PTHREAD_ENV
532 /* do assert stuff */
533 assert(pthread_attr_init(&ubeacon_Interact_tattr) == 0);
534 assert(pthread_attr_setdetachstate(&ubeacon_Interact_tattr, PTHREAD_CREATE_DETACHED) == 0);
535 /* assert(pthread_attr_setstacksize(&ubeacon_Interact_tattr, 16384) == 0); */
536 /* need another attr set here for priority??? - klm */
538 assert(pthread_create(&ubeacon_InteractThread, &ubeacon_Interact_tattr,
539 (void *)ubeacon_Interact, NULL) == 0);
541 code = LWP_CreateProcess(ubeacon_Interact, 16384 /*8192 */ ,
542 LWP_MAX_PRIORITY - 1, (void *)0, "beacon",
548 #ifdef AFS_PTHREAD_ENV
549 /* do assert stuff */
550 assert(pthread_attr_init(&urecovery_Interact_tattr) == 0);
551 assert(pthread_attr_setdetachstate(&urecovery_Interact_tattr, PTHREAD_CREATE_DETACHED) == 0);
552 /* assert(pthread_attr_setstacksize(&urecovery_Interact_tattr, 16384) == 0); */
553 /* need another attr set here for priority??? - klm */
555 assert(pthread_create(&urecovery_InteractThread, &urecovery_Interact_tattr,
556 (void *)urecovery_Interact, NULL) == 0);
558 return 0; /* is this correct? - klm */
560 code = LWP_CreateProcess(urecovery_Interact, 16384 /*8192 */ ,
561 LWP_MAX_PRIORITY - 1, (void *)0, "recovery",
569 * \see ubik_ServerInitCommon()
572 ubik_ServerInitByInfo(afs_int32 myHost, short myPort,
573 struct afsconf_cell *info, char clones[],
574 const char *pathName, struct ubik_dbase **dbase)
579 ubik_ServerInitCommon(myHost, myPort, info, clones, 0, pathName,
585 * \see ubik_ServerInitCommon()
588 ubik_ServerInit(afs_int32 myHost, short myPort, afs_int32 serverList[],
589 const char *pathName, struct ubik_dbase **dbase)
594 ubik_ServerInitCommon(myHost, myPort, (struct afsconf_cell *)0, 0,
595 serverList, pathName, dbase);
600 * \brief This routine begins a read or write transaction on the transaction
601 * identified by transPtr, in the dbase named by dbase.
603 * An open mode of ubik_READTRANS identifies this as a read transaction,
604 * while a mode of ubik_WRITETRANS identifies this as a write transaction.
605 * transPtr is set to the returned transaction control block.
606 * The readAny flag is set to 0 or 1 or 2 by the wrapper functions
607 * ubik_BeginTrans() or ubik_BeginTransReadAny() or
608 * ubik_BeginTransReadAnyWrite() below.
610 * \note We can only begin transaction when we have an up-to-date database.
613 BeginTrans(register struct ubik_dbase *dbase, afs_int32 transMode,
614 struct ubik_trans **transPtr, int readAny)
616 struct ubik_trans *jt;
617 register struct ubik_trans *tt;
618 register afs_int32 code;
619 #if defined(UBIK_PAUSE)
621 #endif /* UBIK_PAUSE */
623 if (readAny > 1 && ubik_SyncWriterCacheProc == NULL) {
624 /* it's not safe to use ubik_BeginTransReadAnyWrite without a
625 * cache-syncing function; fall back to ubik_BeginTransReadAny,
626 * which is safe but slower */
627 ubik_print("ubik_BeginTransReadAnyWrite called, but "
628 "ubik_SyncWriterCacheProc not set; pretending "
629 "ubik_BeginTransReadAny was called instead\n");
633 if ((transMode != UBIK_READTRANS) && readAny)
636 #if defined(UBIK_PAUSE)
637 /* if we're polling the slave sites, wait until the returns
638 * are all in. Otherwise, the urecovery_CheckTid call may
641 if (transMode == UBIK_WRITETRANS)
642 for (count = 75; dbase->flags & DBVOTING; --count) {
644 #ifdef GRAND_PAUSE_DEBUGGING
647 "%ld: myport=%d: BeginTrans is waiting 'cause of voting conflict\n",
648 time(0), ntohs(ubik_callPortal));
654 "%ld: myport=%d: BeginTrans failed because of voting conflict\n",
655 time(0), ntohs(ubik_callPortal));
657 return UNOQUORUM; /* a white lie */
659 #ifdef AFS_PTHREAD_ENV
666 #endif /* UBIK_PAUSE */
667 if (urecovery_AllBetter(dbase, readAny) == 0) {
671 /* otherwise we have a quorum, use it */
673 /* make sure that at most one write transaction occurs at any one time. This
674 * has nothing to do with transaction locking; that's enforced by the lock package. However,
675 * we can't even handle two non-conflicting writes, since our log and recovery modules
676 * don't know how to restore one without possibly picking up some data from the other. */
677 if (transMode == UBIK_WRITETRANS) {
678 /* if we're writing already, wait */
679 while (dbase->flags & DBWRITING) {
680 #ifdef AFS_PTHREAD_ENV
681 assert(pthread_cond_wait(&dbase->flags_cond, &dbase->versionLock) == 0);
684 LWP_WaitProcess(&dbase->flags);
689 if (!ubeacon_AmSyncSite()) {
695 /* create the transaction */
696 code = udisk_begin(dbase, transMode, &jt); /* can't take address of register var */
697 tt = jt; /* move to a register */
698 if (code || tt == (struct ubik_trans *)NULL) {
703 tt->flags |= TRREADANY;
705 tt->flags |= TRREADWRITE;
708 /* label trans and dbase with new tid */
709 tt->tid.epoch = ubik_epochTime;
710 /* bump by two, since tidCounter+1 means trans id'd by tidCounter has finished */
711 tt->tid.counter = (dbase->tidCounter += 2);
713 if (transMode == UBIK_WRITETRANS) {
714 /* for a write trans, we have to keep track of the write tid counter too */
715 #if defined(UBIK_PAUSE)
716 dbase->writeTidCounter = tt->tid.counter;
718 dbase->writeTidCounter += 2;
719 #endif /* UBIK_PAUSE */
721 /* next try to start transaction on appropriate number of machines */
722 code = ContactQuorum_NoArguments(DISK_Begin, tt, 0);
724 /* we must abort the operation */
726 ContactQuorum_NoArguments(DISK_Abort, tt, 0); /* force aborts to the others */
742 ubik_BeginTrans(register struct ubik_dbase *dbase, afs_int32 transMode,
743 struct ubik_trans **transPtr)
745 return BeginTrans(dbase, transMode, transPtr, 0);
752 ubik_BeginTransReadAny(register struct ubik_dbase *dbase, afs_int32 transMode,
753 struct ubik_trans **transPtr)
755 return BeginTrans(dbase, transMode, transPtr, 1);
762 ubik_BeginTransReadAnyWrite(struct ubik_dbase *dbase, afs_int32 transMode,
763 struct ubik_trans **transPtr)
765 return BeginTrans(dbase, transMode, transPtr, 2);
769 * \brief This routine ends a read or write transaction by aborting it.
772 ubik_AbortTrans(register struct ubik_trans *transPtr)
774 register afs_int32 code;
776 register struct ubik_dbase *dbase;
778 dbase = transPtr->dbase;
780 if (transPtr->flags & TRCACHELOCKED) {
781 ReleaseReadLock(&dbase->cache_lock);
782 transPtr->flags &= ~TRCACHELOCKED;
785 ObtainWriteLock(&dbase->cache_lock);
788 memset(&dbase->cachedVersion, 0, sizeof(struct ubik_version));
790 ReleaseWriteLock(&dbase->cache_lock);
792 /* see if we're still up-to-date */
793 if (!urecovery_AllBetter(dbase, transPtr->flags & TRREADANY)) {
794 udisk_abort(transPtr);
800 if (transPtr->type == UBIK_READTRANS) {
801 code = udisk_abort(transPtr);
807 /* below here, we know we're doing a write transaction */
808 if (!ubeacon_AmSyncSite()) {
809 udisk_abort(transPtr);
815 /* now it is safe to try remote abort */
816 code = ContactQuorum_NoArguments(DISK_Abort, transPtr, 0);
817 code2 = udisk_abort(transPtr);
820 return (code ? code : code2);
824 WritebackApplicationCache(struct ubik_dbase *dbase)
827 if (ubik_SyncWriterCacheProc) {
828 code = ubik_SyncWriterCacheProc();
831 /* we failed to sync the local cache, so just invalidate the cache;
832 * we'll try to read the cache in again on the next read */
833 memset(&dbase->cachedVersion, 0, sizeof(dbase->cachedVersion));
835 memcpy(&dbase->cachedVersion, &dbase->version,
836 sizeof(dbase->cachedVersion));
841 * \brief This routine ends a read or write transaction on the open transaction identified by transPtr.
842 * \return an error code.
845 ubik_EndTrans(register struct ubik_trans *transPtr)
847 register afs_int32 code;
850 register struct ubik_server *ts;
853 register struct ubik_dbase *dbase;
855 if (transPtr->type == UBIK_WRITETRANS) {
856 code = ubik_Flush(transPtr);
858 ubik_AbortTrans(transPtr);
863 dbase = transPtr->dbase;
865 if (transPtr->flags & TRCACHELOCKED) {
866 ReleaseReadLock(&dbase->cache_lock);
867 transPtr->flags &= ~TRCACHELOCKED;
870 if (transPtr->type != UBIK_READTRANS) {
871 /* must hold cache_lock before DBHOLD'ing */
872 ObtainWriteLock(&dbase->cache_lock);
878 /* give up if no longer current */
879 if (!urecovery_AllBetter(dbase, transPtr->flags & TRREADANY)) {
880 udisk_abort(transPtr);
887 if (transPtr->type == UBIK_READTRANS) { /* reads are easy */
888 code = udisk_commit(transPtr);
890 goto success; /* update cachedVersion correctly */
896 if (!ubeacon_AmSyncSite()) { /* no longer sync site */
897 udisk_abort(transPtr);
904 /* now it is safe to do commit */
905 code = udisk_commit(transPtr);
907 /* db data has been committed locally; update the local cache so
908 * readers can get at it */
909 WritebackApplicationCache(dbase);
911 ReleaseWriteLock(&dbase->cache_lock);
913 code = ContactQuorum_NoArguments(DISK_Commit, transPtr, CStampVersion);
916 memset(&dbase->cachedVersion, 0, sizeof(struct ubik_version));
917 ReleaseWriteLock(&dbase->cache_lock);
921 /* failed to commit, so must return failure. Try to clear locks first, just for fun
922 * Note that we don't know if this transaction will eventually commit at this point.
923 * If it made it to a site that will be present in the next quorum, we win, otherwise
924 * we lose. If we contact a majority of sites, then we won't be here: contacting
925 * a majority guarantees commit, since it guarantees that one dude will be a
926 * member of the next quorum. */
927 ContactQuorum_NoArguments(DISK_ReleaseLocks, transPtr, 0);
932 /* before we can start sending unlock messages, we must wait until all servers
933 * that are possibly still functioning on the other side of a network partition
934 * have timed out. Check the server structures, compute how long to wait, then
935 * start the unlocks */
936 realStart = FT_ApproxTime();
938 /* wait for all servers to time out */
940 now = FT_ApproxTime();
941 /* check if we're still sync site, the guy should either come up
942 * to us, or timeout. Put safety check in anyway */
943 if (now - realStart > 10 * BIGTIME) {
944 ubik_stats.escapes++;
945 ubik_print("ubik escaping from commit wait\n");
948 for (ts = ubik_servers; ts; ts = ts->next) {
949 if (!ts->beaconSinceDown && now <= ts->lastBeaconSent + BIGTIME) {
950 /* this guy could have some damaged data, wait for him */
952 tv.tv_sec = 1; /* try again after a while (ha ha) */
954 #ifdef AFS_PTHREAD_ENV
955 select(0, 0, 0, 0, &tv);
957 IOMGR_Select(0, 0, 0, 0, &tv); /* poll, should we wait on something? */
963 break; /* no down ones still pseudo-active */
966 /* finally, unlock all the dudes. We can return success independent of the number of servers
967 * that really unlock the dbase; the others will do it if/when they elect a new sync site.
968 * The transaction is committed anyway, since we succeeded in contacting a quorum
969 * at the start (when invoking the DiskCommit function).
971 ContactQuorum_NoArguments(DISK_ReleaseLocks, transPtr, 0);
975 /* don't update cachedVersion here; it should have been updated way back
976 * in ubik_CheckCache, and earlier in this function for writes */
979 ReleaseWriteLock(&dbase->cache_lock);
985 ObtainWriteLock(&dbase->cache_lock);
987 memset(&dbase->cachedVersion, 0, sizeof(struct ubik_version));
988 ReleaseWriteLock(&dbase->cache_lock);
993 * \brief This routine reads length bytes into buffer from the current position in the database.
995 * The file pointer is updated appropriately (by adding the number of bytes actually transferred), and the length actually transferred is stored in the long integer pointed to by length. A short read returns zero for an error code.
997 * \note *length is an INOUT parameter: at the start it represents the size of the buffer, and when done, it contains the number of bytes actually transferred.
1000 ubik_Read(register struct ubik_trans *transPtr, void *buffer,
1003 register afs_int32 code;
1005 /* reads are easy to do: handle locally */
1006 DBHOLD(transPtr->dbase);
1007 if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY)) {
1008 DBRELE(transPtr->dbase);
1013 udisk_read(transPtr, transPtr->seekFile, buffer, transPtr->seekPos,
1016 transPtr->seekPos += length;
1018 DBRELE(transPtr->dbase);
1023 * \brief This routine will flush the io data in the iovec structures.
1025 * It first flushes to the local disk and then uses ContactQuorum to write it
1026 * to the other servers.
1029 ubik_Flush(struct ubik_trans *transPtr)
1031 afs_int32 code, error = 0;
1033 if (transPtr->type != UBIK_WRITETRANS)
1035 if (!transPtr->iovec_info.iovec_wrt_len
1036 || !transPtr->iovec_info.iovec_wrt_val)
1039 DBHOLD(transPtr->dbase);
1040 if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY))
1041 ERROR_EXIT(UNOQUORUM);
1042 if (!ubeacon_AmSyncSite()) /* only sync site can write */
1043 ERROR_EXIT(UNOTSYNC);
1045 /* Update the rest of the servers in the quorum */
1047 ContactQuorum_DISK_WriteV(transPtr, 0, &transPtr->iovec_info,
1048 &transPtr->iovec_data);
1050 udisk_abort(transPtr);
1051 ContactQuorum_NoArguments(DISK_Abort, transPtr, 0); /* force aborts to the others */
1052 transPtr->iovec_info.iovec_wrt_len = 0;
1053 transPtr->iovec_data.iovec_buf_len = 0;
1057 /* Wrote the buffers out, so start at scratch again */
1058 transPtr->iovec_info.iovec_wrt_len = 0;
1059 transPtr->iovec_data.iovec_buf_len = 0;
1062 DBRELE(transPtr->dbase);
1067 ubik_Write(register struct ubik_trans *transPtr, void *vbuffer,
1070 struct ubik_iovec *iovec;
1071 afs_int32 code, error = 0;
1072 afs_int32 pos, len, size;
1073 char * buffer = (char *)vbuffer;
1075 if (transPtr->type != UBIK_WRITETRANS)
1080 if (length > IOVEC_MAXBUF) {
1081 for (pos = 0, len = length; len > 0; len -= size, pos += size) {
1082 size = ((len < IOVEC_MAXBUF) ? len : IOVEC_MAXBUF);
1083 code = ubik_Write(transPtr, buffer+pos, size);
1090 if (!transPtr->iovec_info.iovec_wrt_val) {
1091 transPtr->iovec_info.iovec_wrt_len = 0;
1092 transPtr->iovec_info.iovec_wrt_val =
1093 (struct ubik_iovec *)malloc(IOVEC_MAXWRT *
1094 sizeof(struct ubik_iovec));
1095 transPtr->iovec_data.iovec_buf_len = 0;
1096 transPtr->iovec_data.iovec_buf_val = (char *)malloc(IOVEC_MAXBUF);
1097 if (!transPtr->iovec_info.iovec_wrt_val
1098 || !transPtr->iovec_data.iovec_buf_val) {
1099 if (transPtr->iovec_info.iovec_wrt_val)
1100 free(transPtr->iovec_info.iovec_wrt_val);
1101 transPtr->iovec_info.iovec_wrt_val = 0;
1102 if (transPtr->iovec_data.iovec_buf_val)
1103 free(transPtr->iovec_data.iovec_buf_val);
1104 transPtr->iovec_data.iovec_buf_val = 0;
1109 /* If this write won't fit in the structure, then flush it out and start anew */
1110 if ((transPtr->iovec_info.iovec_wrt_len >= IOVEC_MAXWRT)
1111 || ((length + transPtr->iovec_data.iovec_buf_len) > IOVEC_MAXBUF)) {
1112 code = ubik_Flush(transPtr);
1117 DBHOLD(transPtr->dbase);
1118 if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY))
1119 ERROR_EXIT(UNOQUORUM);
1120 if (!ubeacon_AmSyncSite()) /* only sync site can write */
1121 ERROR_EXIT(UNOTSYNC);
1123 /* Write to the local disk */
1125 udisk_write(transPtr, transPtr->seekFile, buffer, transPtr->seekPos,
1128 udisk_abort(transPtr);
1129 transPtr->iovec_info.iovec_wrt_len = 0;
1130 transPtr->iovec_data.iovec_buf_len = 0;
1131 DBRELE(transPtr->dbase);
1135 /* Collect writes for the other ubik servers (to be done in bulk) */
1136 iovec = (struct ubik_iovec *)transPtr->iovec_info.iovec_wrt_val;
1137 iovec[transPtr->iovec_info.iovec_wrt_len].file = transPtr->seekFile;
1138 iovec[transPtr->iovec_info.iovec_wrt_len].position = transPtr->seekPos;
1139 iovec[transPtr->iovec_info.iovec_wrt_len].length = length;
1141 memcpy(&transPtr->iovec_data.
1142 iovec_buf_val[transPtr->iovec_data.iovec_buf_len], buffer, length);
1144 transPtr->iovec_info.iovec_wrt_len++;
1145 transPtr->iovec_data.iovec_buf_len += length;
1146 transPtr->seekPos += length;
1149 DBRELE(transPtr->dbase);
1154 * \brief This sets the file pointer associated with the current transaction
1155 * to the appropriate file and byte position.
1157 * Unlike Unix files, a transaction is labelled by both a file number \p fileid
1158 * and a byte position relative to the specified file \p position.
1161 ubik_Seek(register struct ubik_trans *transPtr, afs_int32 fileid,
1164 register afs_int32 code;
1166 DBHOLD(transPtr->dbase);
1167 if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY)) {
1170 transPtr->seekFile = fileid;
1171 transPtr->seekPos = position;
1174 DBRELE(transPtr->dbase);
1179 * \brief This call returns the file pointer associated with the specified
1180 * transaction in \p fileid and \p position.
1183 ubik_Tell(register struct ubik_trans *transPtr, afs_int32 * fileid,
1184 afs_int32 * position)
1186 DBHOLD(transPtr->dbase);
1187 *fileid = transPtr->seekFile;
1188 *position = transPtr->seekPos;
1189 DBRELE(transPtr->dbase);
1194 * \brief This sets the file size for the currently-selected file to \p length
1195 * bytes, if length is less than the file's current size.
1198 ubik_Truncate(register struct ubik_trans *transPtr, afs_int32 length)
1200 afs_int32 code, error = 0;
1202 /* Will also catch if not UBIK_WRITETRANS */
1203 code = ubik_Flush(transPtr);
1207 DBHOLD(transPtr->dbase);
1208 /* first, check that quorum is still good, and that dbase is up-to-date */
1209 if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY))
1210 ERROR_EXIT(UNOQUORUM);
1211 if (!ubeacon_AmSyncSite())
1212 ERROR_EXIT(UNOTSYNC);
1214 /* now do the operation locally, and propagate it out */
1215 code = udisk_truncate(transPtr, transPtr->seekFile, length);
1218 ContactQuorum_DISK_Truncate(transPtr, 0, transPtr->seekFile,
1222 /* we must abort the operation */
1223 udisk_abort(transPtr);
1224 ContactQuorum_NoArguments(DISK_Abort, transPtr, 0); /* force aborts to the others */
1229 DBRELE(transPtr->dbase);
1234 * \brief set a lock; all locks are released on transaction end (commit/abort)
1237 ubik_SetLock(struct ubik_trans *atrans, afs_int32 apos, afs_int32 alen,
1240 afs_int32 code = 0, error = 0;
1242 if (atype == LOCKWRITE) {
1243 if (atrans->type == UBIK_READTRANS)
1245 code = ubik_Flush(atrans);
1250 DBHOLD(atrans->dbase);
1251 if (atype == LOCKREAD) {
1252 code = ulock_getLock(atrans, atype, 1);
1256 /* first, check that quorum is still good, and that dbase is up-to-date */
1257 if (!urecovery_AllBetter(atrans->dbase, atrans->flags & TRREADANY))
1258 ERROR_EXIT(UNOQUORUM);
1259 if (!ubeacon_AmSyncSite())
1260 ERROR_EXIT(UNOTSYNC);
1262 /* now do the operation locally, and propagate it out */
1263 code = ulock_getLock(atrans, atype, 1);
1265 code = ContactQuorum_DISK_Lock(atrans, 0, 0, 1 /*unused */ ,
1266 1 /*unused */ , LOCKWRITE);
1269 /* we must abort the operation */
1270 udisk_abort(atrans);
1271 ContactQuorum_NoArguments(DISK_Abort, atrans, 0); /* force aborts to the others */
1277 DBRELE(atrans->dbase);
1282 * \brief utility to wait for a version # to change
1285 ubik_WaitVersion(register struct ubik_dbase *adatabase,
1286 register struct ubik_version *aversion)
1290 /* wait until version # changes, and then return */
1291 if (vcmp(*aversion, adatabase->version) != 0) {
1295 #ifdef AFS_PTHREAD_ENV
1296 assert(pthread_cond_wait(&adatabase->version_cond, &adatabase->versionLock) == 0);
1299 LWP_WaitProcess(&adatabase->version); /* same vers, just wait */
1306 * \brief utility to get the version of the dbase a transaction is dealing with
1309 ubik_GetVersion(register struct ubik_trans *atrans,
1310 register struct ubik_version *avers)
1312 *avers = atrans->dbase->version;
1317 * \brief Facility to simplify database caching.
1318 * \return zero if last trans was done on the local server and was successful.
1319 * \return -1 means bad (NULL) argument.
1321 * If return value is non-zero and the caller is a server caching part of the
1322 * Ubik database, it should invalidate that cache.
1325 ubik_CacheUpdate(register struct ubik_trans *atrans)
1327 if (!(atrans && atrans->dbase))
1329 return vcmp(atrans->dbase->cachedVersion, atrans->dbase->version) != 0;
1333 * check and possibly update cache of ubik db.
1335 * If the version of the cached db data is out of date, this calls (*check) to
1336 * update the cache. If (*check) returns success, we update the version of the
1339 * Checking the version of the cached db data is done under a read lock;
1340 * updating the cache (and thus calling (*check)) is done under a write lock
1341 * so is guaranteed not to interfere with another thread's (*check). On
1342 * successful return, a read lock on the cached db data is obtained, which
1343 * will be released by ubik_EndTrans or ubik_AbortTrans.
1345 * @param[in] atrans ubik transaction
1346 * @param[in] check function to call to check/update cache
1347 * @param[in] rock rock to pass to *check
1349 * @return operation status
1351 * @retval nonzero error; cachedVersion not updated
1353 * @post On success, application cache is read-locked, and cache data is
1357 ubik_CheckCache(struct ubik_trans *atrans, ubik_updatecache_func cbf, void *rock)
1361 if (!(atrans && atrans->dbase))
1364 ObtainReadLock(&atrans->dbase->cache_lock);
1366 while (ubik_CacheUpdate(atrans) != 0) {
1368 ReleaseReadLock(&atrans->dbase->cache_lock);
1369 ObtainSharedLock(&atrans->dbase->cache_lock);
1371 if (ubik_CacheUpdate(atrans) != 0) {
1373 BoostSharedLock(&atrans->dbase->cache_lock);
1375 ret = (*cbf) (atrans, rock);
1377 memcpy(&atrans->dbase->cachedVersion, &atrans->dbase->version,
1378 sizeof(atrans->dbase->cachedVersion));
1382 /* It would be nice if we could convert from a shared lock to a read
1383 * lock... instead, just release the shared and acquire the read */
1384 ReleaseSharedLock(&atrans->dbase->cache_lock);
1387 /* if we have an error, don't retry, and don't hold any locks */
1391 ObtainReadLock(&atrans->dbase->cache_lock);
1394 atrans->flags |= TRCACHELOCKED;
1400 * "Who said anything about panicking?" snapped Arthur.
1401 * "This is still just the culture shock. You wait till I've settled down
1402 * into the situation and found my bearings. \em Then I'll start panicking!"
1405 * \returns There is no return from panic.
1408 panic(char *format, ...)
1412 va_start(ap, format);
1413 ubik_print("Ubik PANIC: ");
1414 ubik_vprint(format, ap);
1418 ubik_print("BACK FROM ABORT\n"); /* shouldn't come back */
1419 exit(1); /* never know, though */
1423 * This function takes an IP addresses as its parameter. It returns the
1424 * the primary IP address that is on the host passed in, or 0 if not found.
1427 ubikGetPrimaryInterfaceAddr(afs_uint32 addr)
1429 struct ubik_server *ts;
1432 for (ts = ubik_servers; ts; ts = ts->next)
1433 for (j = 0; j < UBIK_MAX_INTERFACE_ADDR; j++)
1434 if (ts->addr[j] == addr)
1435 return ts->addr[0]; /* net byte order */
1436 return 0; /* if not in server database, return error */