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>
15 #include <sys/types.h>
24 #include <netinet/in.h>
25 #include <sys/param.h>
31 #include <afs/cellconfig.h>
33 #define UBIK_INTERNALS
37 #include <lwp.h> /* temporary hack by klm */
39 #define ERROR_EXIT(code) do { \
46 * This system is organized in a hierarchical set of related modules. Modules
47 * at one level can only call modules at the same level or below.
49 * At the bottom level (0) we have R, RFTP, LWP and IOMGR, i.e. the basic
50 * operating system primitives.
52 * At the next level (1) we have
54 * \li VOTER--The module responsible for casting votes when asked. It is also
55 * responsible for determining whether this server should try to become
56 * a synchronization site.
57 * \li BEACONER--The module responsible for sending keep-alives out when a
58 * server is actually the sync site, or trying to become a sync site.
59 * \li DISK--The module responsible for representing atomic transactions
60 * on the local disk. It maintains a new-value only log.
61 * \li LOCK--The module responsible for locking byte ranges in the database file.
63 * At the next level (2) we have
65 * \li RECOVERY--The module responsible for ensuring that all members of a quorum
66 * have the same up-to-date database after a new synchronization site is
67 * elected. This module runs only on the synchronization site.
69 * At the next level (3) we have
71 * \li REMOTE--The module responsible for interpreting requests from the sync
72 * site and applying them to the database, after obtaining the appropriate
75 * At the next level (4) we have
77 * \li UBIK--The module users call to perform operations on the database.
82 afs_int32 ubik_quorum = 0;
83 struct ubik_dbase *ubik_dbase = 0;
84 struct ubik_stats ubik_stats;
85 afs_uint32 ubik_host[UBIK_MAX_INTERFACE_ADDR];
86 afs_int32 ubik_epochTime = 0;
87 afs_int32 urecovery_state = 0;
88 int (*ubik_SRXSecurityProc) (void *, struct rx_securityClass **, afs_int32 *);
89 void *ubik_SRXSecurityRock;
90 int (*ubik_SyncWriterCacheProc) (void);
91 struct ubik_server *ubik_servers;
92 short ubik_callPortal;
94 static int BeginTrans(struct ubik_dbase *dbase, afs_int32 transMode,
95 struct ubik_trans **transPtr, int readAny);
97 struct rx_securityClass *ubik_sc[3];
99 #define CStampVersion 1 /* meaning set ts->version */
101 static_inline struct rx_connection *
102 Quorum_StartIO(struct ubik_trans *atrans, struct ubik_server *as)
104 struct rx_connection *conn;
106 conn = as->disk_rxcid;
108 #ifdef AFS_PTHREAD_ENV
109 rx_GetConnection(conn);
110 DBRELE(atrans->dbase);
111 #endif /* AFS_PTHREAD_ENV */
117 Quorum_EndIO(struct ubik_trans *atrans, struct rx_connection *aconn)
119 #ifdef AFS_PTHREAD_ENV
120 DBHOLD(atrans->dbase);
121 rx_PutConnection(aconn);
122 #endif /* AFS_PTHREAD_ENV */
126 * \brief Perform an operation at a quorum, handling error conditions.
127 * \return 0 if all worked and a quorum was contacted successfully
128 * \return otherwise mark failing server as down and return #UERROR
130 * \note If any server misses an update, we must wait #BIGTIME seconds before
131 * allowing the transaction to commit, to ensure that the missing and
132 * possibly still functioning server times out and stops handing out old
133 * data. This is done in the commit code, where we wait for a server marked
134 * down to have stayed down for #BIGTIME seconds before we allow a transaction
135 * to commit. A server that fails but comes back up won't give out old data
136 * because it is sent the sync count along with the beacon message that
137 * marks it as \b really up (\p beaconSinceDown).
140 ContactQuorum_NoArguments(afs_int32 (*proc)(struct rx_connection *, ubik_tid *),
141 struct ubik_trans *atrans, int aflags)
143 struct ubik_server *ts;
145 afs_int32 rcode, okcalls;
146 struct rx_connection *conn;
150 for (ts = ubik_servers; ts; ts = ts->next) {
151 /* for each server */
152 if (!ts->up || !ts->currentDB) {
153 ts->currentDB = 0; /* db is no longer current; we just missed an update */
154 continue; /* not up-to-date, don't bother */
157 conn = Quorum_StartIO(atrans, ts);
159 code = (*proc)(conn, &atrans->tid);
161 Quorum_EndIO(atrans, conn);
164 if (code) { /* failure */
166 ts->up = 0; /* mark as down now; beacons will no longer be sent */
168 ts->beaconSinceDown = 0;
169 urecovery_LostServer(ts); /* tell recovery to try to resend dbase later */
170 } else { /* success */
172 okcalls++; /* count up how many worked */
173 if (aflags & CStampVersion) {
174 ts->version = atrans->dbase->version;
178 /* return 0 if we successfully contacted a quorum, otherwise return error code. We don't have to contact ourselves (that was done locally) */
179 if (okcalls + 1 >= ubik_quorum)
186 ContactQuorum_DISK_Lock(struct ubik_trans *atrans, int aflags,afs_int32 file,
187 afs_int32 position, afs_int32 length, afs_int32 type)
189 struct ubik_server *ts;
191 afs_int32 rcode, okcalls;
192 struct rx_connection *conn;
196 for (ts = ubik_servers; ts; ts = ts->next) {
197 /* for each server */
198 if (!ts->up || !ts->currentDB) {
199 ts->currentDB = 0; /* db is no longer current; we just missed an update */
200 continue; /* not up-to-date, don't bother */
203 conn = Quorum_StartIO(atrans, ts);
205 code = DISK_Lock(conn, &atrans->tid, file, position, length, type);
207 Quorum_EndIO(atrans, conn);
210 if (code) { /* failure */
212 ts->up = 0; /* mark as down now; beacons will no longer be sent */
214 ts->beaconSinceDown = 0;
215 urecovery_LostServer(ts); /* tell recovery to try to resend dbase later */
216 } else { /* success */
218 okcalls++; /* count up how many worked */
219 if (aflags & CStampVersion) {
220 ts->version = atrans->dbase->version;
224 /* return 0 if we successfully contacted a quorum, otherwise return error code. We don't have to contact ourselves (that was done locally) */
225 if (okcalls + 1 >= ubik_quorum)
232 ContactQuorum_DISK_Write(struct ubik_trans *atrans, int aflags,
233 afs_int32 file, afs_int32 position, bulkdata *data)
235 struct ubik_server *ts;
237 afs_int32 rcode, okcalls;
238 struct rx_connection *conn;
242 for (ts = ubik_servers; ts; ts = ts->next) {
243 /* for each server */
244 if (!ts->up || !ts->currentDB) {
245 ts->currentDB = 0; /* db is no longer current; we just missed an update */
246 continue; /* not up-to-date, don't bother */
249 conn = Quorum_StartIO(atrans, ts);
251 code = DISK_Write(conn, &atrans->tid, file, position, data);
253 Quorum_EndIO(atrans, conn);
256 if (code) { /* failure */
258 ts->up = 0; /* mark as down now; beacons will no longer be sent */
260 ts->beaconSinceDown = 0;
261 urecovery_LostServer(ts); /* tell recovery to try to resend dbase later */
262 } else { /* success */
264 okcalls++; /* count up how many worked */
265 if (aflags & CStampVersion) {
266 ts->version = atrans->dbase->version;
270 /* return 0 if we successfully contacted a quorum, otherwise return error code. We don't have to contact ourselves (that was done locally) */
271 if (okcalls + 1 >= ubik_quorum)
278 ContactQuorum_DISK_Truncate(struct ubik_trans *atrans, int aflags,
279 afs_int32 file, afs_int32 length)
281 struct ubik_server *ts;
283 afs_int32 rcode, okcalls;
284 struct rx_connection *conn;
288 for (ts = ubik_servers; ts; ts = ts->next) {
289 /* for each server */
290 if (!ts->up || !ts->currentDB) {
291 ts->currentDB = 0; /* db is no longer current; we just missed an update */
292 continue; /* not up-to-date, don't bother */
295 conn = Quorum_StartIO(atrans, ts);
297 code = DISK_Truncate(conn, &atrans->tid, file, length);
299 Quorum_EndIO(atrans, conn);
302 if (code) { /* failure */
304 ts->up = 0; /* mark as down now; beacons will no longer be sent */
306 ts->beaconSinceDown = 0;
307 urecovery_LostServer(ts); /* tell recovery to try to resend dbase later */
308 } else { /* success */
310 okcalls++; /* count up how many worked */
311 if (aflags & CStampVersion) {
312 ts->version = atrans->dbase->version;
316 /* return 0 if we successfully contacted a quorum, otherwise return error code. We don't have to contact ourselves (that was done locally) */
317 if (okcalls + 1 >= ubik_quorum)
324 ContactQuorum_DISK_WriteV(struct ubik_trans *atrans, int aflags,
325 iovec_wrt * io_vector, iovec_buf *io_buffer)
327 struct ubik_server *ts;
329 afs_int32 rcode, okcalls;
330 struct rx_connection *conn;
334 for (ts = ubik_servers; ts; ts = ts->next) {
335 /* for each server */
336 if (!ts->up || !ts->currentDB) {
337 ts->currentDB = 0; /* db is no longer current; we just missed an update */
338 continue; /* not up-to-date, don't bother */
341 conn = Quorum_StartIO(atrans, ts);
343 code = DISK_WriteV(conn, &atrans->tid, io_vector, io_buffer);
345 Quorum_EndIO(atrans, conn);
348 if ((code <= -450) && (code > -500)) {
349 /* An RPC interface mismatch (as defined in comerr/error_msg.c).
350 * Un-bulk the entries and do individual DISK_Write calls
351 * instead of DISK_WriteV.
353 struct ubik_iovec *iovec =
354 (struct ubik_iovec *)io_vector->iovec_wrt_val;
355 char *iobuf = (char *)io_buffer->iovec_buf_val;
359 conn = Quorum_StartIO(atrans, ts);
361 for (i = 0, offset = 0; i < io_vector->iovec_wrt_len; i++) {
362 /* Sanity check for going off end of buffer */
363 if ((offset + iovec[i].length) > io_buffer->iovec_buf_len) {
367 tcbs.bulkdata_len = iovec[i].length;
368 tcbs.bulkdata_val = &iobuf[offset];
371 DISK_Write(conn, &atrans->tid, iovec[i].file,
372 iovec[i].position, &tcbs);
376 offset += iovec[i].length;
379 Quorum_EndIO(atrans, conn);
383 if (code) { /* failure */
385 ts->up = 0; /* mark as down now; beacons will no longer be sent */
387 ts->beaconSinceDown = 0;
388 urecovery_LostServer(ts); /* tell recovery to try to resend dbase later */
389 } else { /* success */
391 okcalls++; /* count up how many worked */
392 if (aflags & CStampVersion) {
393 ts->version = atrans->dbase->version;
397 /* return 0 if we successfully contacted a quorum, otherwise return error code. We don't have to contact ourselves (that was done locally) */
398 if (okcalls + 1 >= ubik_quorum)
405 ContactQuorum_DISK_SetVersion(struct ubik_trans *atrans, int aflags,
406 ubik_version *OldVersion,
407 ubik_version *NewVersion)
409 struct ubik_server *ts;
411 afs_int32 rcode, okcalls;
412 struct rx_connection *conn;
416 for (ts = ubik_servers; ts; ts = ts->next) {
417 /* for each server */
418 if (!ts->up || !ts->currentDB) {
419 ts->currentDB = 0; /* db is no longer current; we just missed an update */
420 continue; /* not up-to-date, don't bother */
423 conn = Quorum_StartIO(atrans, ts);
425 code = DISK_SetVersion(conn, &atrans->tid, OldVersion, NewVersion);
427 Quorum_EndIO(atrans, conn);
430 if (code) { /* failure */
432 ts->up = 0; /* mark as down now; beacons will no longer be sent */
434 ts->beaconSinceDown = 0;
435 urecovery_LostServer(ts); /* tell recovery to try to resend dbase later */
436 } else { /* success */
438 okcalls++; /* count up how many worked */
439 if (aflags & CStampVersion) {
440 ts->version = atrans->dbase->version;
444 /* return 0 if we successfully contacted a quorum, otherwise return error code. We don't have to contact ourselves (that was done locally) */
445 if (okcalls + 1 >= ubik_quorum)
452 * \brief This routine initializes the ubik system for a set of servers.
453 * \return 0 for success, or an error code on failure.
454 * \param serverList set of servers specified; nServers gives the number of entries in this array.
455 * \param pathName provides an initial prefix used for naming storage files used by this system.
456 * \param dbase the returned structure representing this instance of an ubik; it is passed to various calls below.
458 * \todo This routine should perhaps be generalized to a low-level disk interface providing read, write, file enumeration and sync operations.
460 * \warning The host named by myHost should not also be listed in serverList.
462 * \see ubik_ServerInit(), ubik_ServerInitByInfo()
465 ubik_ServerInitCommon(afs_uint32 myHost, short myPort,
466 struct afsconf_cell *info, char clones[],
467 afs_uint32 serverList[], const char *pathName,
468 struct ubik_dbase **dbase)
470 struct ubik_dbase *tdb;
472 #ifdef AFS_PTHREAD_ENV
473 pthread_t rxServerThread; /* pthread variables */
474 pthread_t ubeacon_InteractThread;
475 pthread_t urecovery_InteractThread;
476 pthread_attr_t rxServer_tattr;
477 pthread_attr_t ubeacon_Interact_tattr;
478 pthread_attr_t urecovery_Interact_tattr;
481 extern int rx_stackSize;
485 struct rx_securityClass *secClass;
487 struct rx_service *tservice;
489 initialize_U_error_table();
491 tdb = (struct ubik_dbase *)malloc(sizeof(struct ubik_dbase));
492 tdb->pathName = (char *)malloc(strlen(pathName) + 1);
493 strcpy(tdb->pathName, pathName);
494 tdb->activeTrans = (struct ubik_trans *)0;
495 memset(&tdb->version, 0, sizeof(struct ubik_version));
496 memset(&tdb->cachedVersion, 0, sizeof(struct ubik_version));
497 #ifdef AFS_PTHREAD_ENV
498 MUTEX_INIT(&tdb->versionLock, "version lock", MUTEX_DEFAULT, 0);
500 Lock_Init(&tdb->versionLock);
502 Lock_Init(&tdb->cache_lock);
504 tdb->read = uphys_read;
505 tdb->write = uphys_write;
506 tdb->truncate = uphys_truncate;
507 tdb->open = uphys_invalidate; /* this function isn't used any more */
508 tdb->sync = uphys_sync;
509 tdb->stat = uphys_stat;
510 tdb->getlabel = uphys_getlabel;
511 tdb->setlabel = uphys_setlabel;
512 tdb->getnfiles = uphys_getnfiles;
514 tdb->tidCounter = tdb->writeTidCounter = 0;
516 ubik_dbase = tdb; /* for now, only one db per server; can fix later when we have names for the other dbases */
518 #ifdef AFS_PTHREAD_ENV
519 CV_INIT(&tdb->version_cond, "version", CV_DEFAULT, 0);
520 CV_INIT(&tdb->flags_cond, "flags", CV_DEFAULT, 0);
521 #endif /* AFS_PTHREAD_ENV */
525 /* the following call is idempotent so when/if it got called earlier,
526 * by whatever called us, it doesn't really matter -- klm */
527 code = rx_Init(myPort);
531 ubik_callPortal = myPort;
532 /* try to get an additional security object */
533 ubik_sc[0] = rxnull_NewServerSecurityObject();
536 if (ubik_SRXSecurityProc) {
538 (*ubik_SRXSecurityProc) (ubik_SRXSecurityRock, &secClass,
541 ubik_sc[secIndex] = secClass;
544 /* for backwards compat this should keep working as it does now
547 /* This really needs to be up above, where I have put it. It works
548 * here when we're non-pthreaded, but the code above, when using
549 * pthreads may (and almost certainly does) end up calling on a
550 * pthread resource which gets initialized by rx_Init. The end
551 * result is that an assert fails and the program dies. -- klm
553 code = rx_Init(myPort);
559 rx_NewService(0, VOTE_SERVICE_ID, "VOTE", ubik_sc, 3,
560 VOTE_ExecuteRequest);
561 if (tservice == (struct rx_service *)0) {
562 ubik_dprint("Could not create VOTE rx service!\n");
565 rx_SetMinProcs(tservice, 2);
566 rx_SetMaxProcs(tservice, 3);
569 rx_NewService(0, DISK_SERVICE_ID, "DISK", ubik_sc, 3,
570 DISK_ExecuteRequest);
571 if (tservice == (struct rx_service *)0) {
572 ubik_dprint("Could not create DISK rx service!\n");
575 rx_SetMinProcs(tservice, 2);
576 rx_SetMaxProcs(tservice, 3);
578 /* start an rx_ServerProc to handle incoming RPC's in particular the
579 * UpdateInterfaceAddr RPC that occurs in ubeacon_InitServerList. This avoids
580 * the "steplock" problem in ubik initialization. Defect 11037.
582 #ifdef AFS_PTHREAD_ENV
583 /* do assert stuff */
584 osi_Assert(pthread_attr_init(&rxServer_tattr) == 0);
585 osi_Assert(pthread_attr_setdetachstate(&rxServer_tattr, PTHREAD_CREATE_DETACHED) == 0);
586 /* osi_Assert(pthread_attr_setstacksize(&rxServer_tattr, rx_stackSize) == 0); */
588 osi_Assert(pthread_create(&rxServerThread, &rxServer_tattr, (void *)rx_ServerProc, NULL) == 0);
590 LWP_CreateProcess(rx_ServerProc, rx_stackSize, RX_PROCESS_PRIORITY,
591 NULL, "rx_ServerProc", &junk);
594 /* do basic initialization */
598 code = urecovery_Initialize(tdb);
602 code = ubeacon_InitServerListByInfo(myHost, info, clones);
604 code = ubeacon_InitServerList(myHost, serverList);
608 /* now start up async processes */
609 #ifdef AFS_PTHREAD_ENV
610 /* do assert stuff */
611 osi_Assert(pthread_attr_init(&ubeacon_Interact_tattr) == 0);
612 osi_Assert(pthread_attr_setdetachstate(&ubeacon_Interact_tattr, PTHREAD_CREATE_DETACHED) == 0);
613 /* osi_Assert(pthread_attr_setstacksize(&ubeacon_Interact_tattr, 16384) == 0); */
614 /* need another attr set here for priority??? - klm */
616 osi_Assert(pthread_create(&ubeacon_InteractThread, &ubeacon_Interact_tattr,
617 (void *)ubeacon_Interact, NULL) == 0);
619 code = LWP_CreateProcess(ubeacon_Interact, 16384 /*8192 */ ,
620 LWP_MAX_PRIORITY - 1, (void *)0, "beacon",
626 #ifdef AFS_PTHREAD_ENV
627 /* do assert stuff */
628 osi_Assert(pthread_attr_init(&urecovery_Interact_tattr) == 0);
629 osi_Assert(pthread_attr_setdetachstate(&urecovery_Interact_tattr, PTHREAD_CREATE_DETACHED) == 0);
630 /* osi_Assert(pthread_attr_setstacksize(&urecovery_Interact_tattr, 16384) == 0); */
631 /* need another attr set here for priority??? - klm */
633 osi_Assert(pthread_create(&urecovery_InteractThread, &urecovery_Interact_tattr,
634 (void *)urecovery_Interact, NULL) == 0);
636 return 0; /* is this correct? - klm */
638 code = LWP_CreateProcess(urecovery_Interact, 16384 /*8192 */ ,
639 LWP_MAX_PRIORITY - 1, (void *)0, "recovery",
647 * \see ubik_ServerInitCommon()
650 ubik_ServerInitByInfo(afs_uint32 myHost, short myPort,
651 struct afsconf_cell *info, char clones[],
652 const char *pathName, struct ubik_dbase **dbase)
657 ubik_ServerInitCommon(myHost, myPort, info, clones, 0, pathName,
663 * \see ubik_ServerInitCommon()
666 ubik_ServerInit(afs_uint32 myHost, short myPort, afs_uint32 serverList[],
667 const char *pathName, struct ubik_dbase **dbase)
672 ubik_ServerInitCommon(myHost, myPort, (struct afsconf_cell *)0, 0,
673 serverList, pathName, dbase);
678 * \brief This routine begins a read or write transaction on the transaction
679 * identified by transPtr, in the dbase named by dbase.
681 * An open mode of ubik_READTRANS identifies this as a read transaction,
682 * while a mode of ubik_WRITETRANS identifies this as a write transaction.
683 * transPtr is set to the returned transaction control block.
684 * The readAny flag is set to 0 or 1 or 2 by the wrapper functions
685 * ubik_BeginTrans() or ubik_BeginTransReadAny() or
686 * ubik_BeginTransReadAnyWrite() below.
688 * \note We can only begin transaction when we have an up-to-date database.
691 BeginTrans(struct ubik_dbase *dbase, afs_int32 transMode,
692 struct ubik_trans **transPtr, int readAny)
694 struct ubik_trans *jt;
695 struct ubik_trans *tt;
697 #if defined(UBIK_PAUSE)
699 #endif /* UBIK_PAUSE */
701 if (readAny > 1 && ubik_SyncWriterCacheProc == NULL) {
702 /* it's not safe to use ubik_BeginTransReadAnyWrite without a
703 * cache-syncing function; fall back to ubik_BeginTransReadAny,
704 * which is safe but slower */
705 ubik_print("ubik_BeginTransReadAnyWrite called, but "
706 "ubik_SyncWriterCacheProc not set; pretending "
707 "ubik_BeginTransReadAny was called instead\n");
711 if ((transMode != UBIK_READTRANS) && readAny)
714 #if defined(UBIK_PAUSE)
715 /* if we're polling the slave sites, wait until the returns
716 * are all in. Otherwise, the urecovery_CheckTid call may
719 if (transMode == UBIK_WRITETRANS)
720 for (count = 75; dbase->flags & DBVOTING; --count) {
722 #ifdef GRAND_PAUSE_DEBUGGING
725 "%ld: myport=%d: BeginTrans is waiting 'cause of voting conflict\n",
726 time(0), ntohs(ubik_callPortal));
732 "%ld: myport=%d: BeginTrans failed because of voting conflict\n",
733 time(0), ntohs(ubik_callPortal));
735 return UNOQUORUM; /* a white lie */
737 #ifdef AFS_PTHREAD_ENV
744 #endif /* UBIK_PAUSE */
745 if (urecovery_AllBetter(dbase, readAny) == 0) {
749 /* otherwise we have a quorum, use it */
751 /* make sure that at most one write transaction occurs at any one time. This
752 * has nothing to do with transaction locking; that's enforced by the lock package. However,
753 * we can't even handle two non-conflicting writes, since our log and recovery modules
754 * don't know how to restore one without possibly picking up some data from the other. */
755 if (transMode == UBIK_WRITETRANS) {
756 /* if we're writing already, wait */
757 while (dbase->flags & DBWRITING) {
758 #ifdef AFS_PTHREAD_ENV
759 CV_WAIT(&dbase->flags_cond, &dbase->versionLock);
762 LWP_WaitProcess(&dbase->flags);
767 if (!ubeacon_AmSyncSite()) {
773 /* create the transaction */
774 code = udisk_begin(dbase, transMode, &jt); /* can't take address of register var */
775 tt = jt; /* move to a register */
776 if (code || tt == (struct ubik_trans *)NULL) {
781 tt->flags |= TRREADANY;
783 tt->flags |= TRREADWRITE;
786 /* label trans and dbase with new tid */
787 tt->tid.epoch = ubik_epochTime;
788 /* bump by two, since tidCounter+1 means trans id'd by tidCounter has finished */
789 tt->tid.counter = (dbase->tidCounter += 2);
791 if (transMode == UBIK_WRITETRANS) {
792 /* for a write trans, we have to keep track of the write tid counter too */
793 dbase->writeTidCounter = tt->tid.counter;
795 /* next try to start transaction on appropriate number of machines */
796 code = ContactQuorum_NoArguments(DISK_Begin, tt, 0);
798 /* we must abort the operation */
800 ContactQuorum_NoArguments(DISK_Abort, tt, 0); /* force aborts to the others */
816 ubik_BeginTrans(struct ubik_dbase *dbase, afs_int32 transMode,
817 struct ubik_trans **transPtr)
819 return BeginTrans(dbase, transMode, transPtr, 0);
826 ubik_BeginTransReadAny(struct ubik_dbase *dbase, afs_int32 transMode,
827 struct ubik_trans **transPtr)
829 return BeginTrans(dbase, transMode, transPtr, 1);
836 ubik_BeginTransReadAnyWrite(struct ubik_dbase *dbase, afs_int32 transMode,
837 struct ubik_trans **transPtr)
839 return BeginTrans(dbase, transMode, transPtr, 2);
843 * \brief This routine ends a read or write transaction by aborting it.
846 ubik_AbortTrans(struct ubik_trans *transPtr)
850 struct ubik_dbase *dbase;
852 dbase = transPtr->dbase;
854 if (transPtr->flags & TRCACHELOCKED) {
855 ReleaseReadLock(&dbase->cache_lock);
856 transPtr->flags &= ~TRCACHELOCKED;
859 ObtainWriteLock(&dbase->cache_lock);
862 memset(&dbase->cachedVersion, 0, sizeof(struct ubik_version));
864 ReleaseWriteLock(&dbase->cache_lock);
866 /* see if we're still up-to-date */
867 if (!urecovery_AllBetter(dbase, transPtr->flags & TRREADANY)) {
868 udisk_abort(transPtr);
874 if (transPtr->type == UBIK_READTRANS) {
875 code = udisk_abort(transPtr);
881 /* below here, we know we're doing a write transaction */
882 if (!ubeacon_AmSyncSite()) {
883 udisk_abort(transPtr);
889 /* now it is safe to try remote abort */
890 code = ContactQuorum_NoArguments(DISK_Abort, transPtr, 0);
891 code2 = udisk_abort(transPtr);
894 return (code ? code : code2);
898 WritebackApplicationCache(struct ubik_dbase *dbase)
901 if (ubik_SyncWriterCacheProc) {
902 code = ubik_SyncWriterCacheProc();
905 /* we failed to sync the local cache, so just invalidate the cache;
906 * we'll try to read the cache in again on the next read */
907 memset(&dbase->cachedVersion, 0, sizeof(dbase->cachedVersion));
909 memcpy(&dbase->cachedVersion, &dbase->version,
910 sizeof(dbase->cachedVersion));
915 * \brief This routine ends a read or write transaction on the open transaction identified by transPtr.
916 * \return an error code.
919 ubik_EndTrans(struct ubik_trans *transPtr)
924 struct ubik_server *ts;
927 struct ubik_dbase *dbase;
929 if (transPtr->type == UBIK_WRITETRANS) {
930 code = ubik_Flush(transPtr);
932 ubik_AbortTrans(transPtr);
937 dbase = transPtr->dbase;
939 if (transPtr->flags & TRCACHELOCKED) {
940 ReleaseReadLock(&dbase->cache_lock);
941 transPtr->flags &= ~TRCACHELOCKED;
944 if (transPtr->type != UBIK_READTRANS) {
945 /* must hold cache_lock before DBHOLD'ing */
946 ObtainWriteLock(&dbase->cache_lock);
952 /* give up if no longer current */
953 if (!urecovery_AllBetter(dbase, transPtr->flags & TRREADANY)) {
954 udisk_abort(transPtr);
961 if (transPtr->type == UBIK_READTRANS) { /* reads are easy */
962 code = udisk_commit(transPtr);
964 goto success; /* update cachedVersion correctly */
970 if (!ubeacon_AmSyncSite()) { /* no longer sync site */
971 udisk_abort(transPtr);
978 /* now it is safe to do commit */
979 code = udisk_commit(transPtr);
981 /* db data has been committed locally; update the local cache so
982 * readers can get at it */
983 WritebackApplicationCache(dbase);
985 ReleaseWriteLock(&dbase->cache_lock);
987 code = ContactQuorum_NoArguments(DISK_Commit, transPtr, CStampVersion);
990 memset(&dbase->cachedVersion, 0, sizeof(struct ubik_version));
991 ReleaseWriteLock(&dbase->cache_lock);
995 /* failed to commit, so must return failure. Try to clear locks first, just for fun
996 * Note that we don't know if this transaction will eventually commit at this point.
997 * If it made it to a site that will be present in the next quorum, we win, otherwise
998 * we lose. If we contact a majority of sites, then we won't be here: contacting
999 * a majority guarantees commit, since it guarantees that one dude will be a
1000 * member of the next quorum. */
1001 ContactQuorum_NoArguments(DISK_ReleaseLocks, transPtr, 0);
1002 udisk_end(transPtr);
1006 /* before we can start sending unlock messages, we must wait until all servers
1007 * that are possibly still functioning on the other side of a network partition
1008 * have timed out. Check the server structures, compute how long to wait, then
1009 * start the unlocks */
1010 realStart = FT_ApproxTime();
1012 /* wait for all servers to time out */
1014 now = FT_ApproxTime();
1015 /* check if we're still sync site, the guy should either come up
1016 * to us, or timeout. Put safety check in anyway */
1017 if (now - realStart > 10 * BIGTIME) {
1018 ubik_stats.escapes++;
1019 ubik_print("ubik escaping from commit wait\n");
1022 for (ts = ubik_servers; ts; ts = ts->next) {
1023 if (!ts->beaconSinceDown && now <= ts->lastBeaconSent + BIGTIME) {
1025 /* this guy could have some damaged data, wait for him */
1027 tv.tv_sec = 1; /* try again after a while (ha ha) */
1030 #ifdef AFS_PTHREAD_ENV
1031 /* we could release the dbase outside of the loop, but we do
1032 * it here, in the loop, to avoid an unnecessary RELE/HOLD
1033 * if all sites are up */
1035 select(0, 0, 0, 0, &tv);
1038 IOMGR_Select(0, 0, 0, 0, &tv); /* poll, should we wait on something? */
1045 break; /* no down ones still pseudo-active */
1048 /* finally, unlock all the dudes. We can return success independent of the number of servers
1049 * that really unlock the dbase; the others will do it if/when they elect a new sync site.
1050 * The transaction is committed anyway, since we succeeded in contacting a quorum
1051 * at the start (when invoking the DiskCommit function).
1053 ContactQuorum_NoArguments(DISK_ReleaseLocks, transPtr, 0);
1056 udisk_end(transPtr);
1057 /* don't update cachedVersion here; it should have been updated way back
1058 * in ubik_CheckCache, and earlier in this function for writes */
1061 ReleaseWriteLock(&dbase->cache_lock);
1067 ObtainWriteLock(&dbase->cache_lock);
1069 memset(&dbase->cachedVersion, 0, sizeof(struct ubik_version));
1070 ReleaseWriteLock(&dbase->cache_lock);
1075 * \brief This routine reads length bytes into buffer from the current position in the database.
1077 * 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.
1079 * \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.
1082 ubik_Read(struct ubik_trans *transPtr, void *buffer,
1087 /* reads are easy to do: handle locally */
1088 DBHOLD(transPtr->dbase);
1089 if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY)) {
1090 DBRELE(transPtr->dbase);
1095 udisk_read(transPtr, transPtr->seekFile, buffer, transPtr->seekPos,
1098 transPtr->seekPos += length;
1100 DBRELE(transPtr->dbase);
1105 * \brief This routine will flush the io data in the iovec structures.
1107 * It first flushes to the local disk and then uses ContactQuorum to write it
1108 * to the other servers.
1111 ubik_Flush(struct ubik_trans *transPtr)
1113 afs_int32 code, error = 0;
1115 if (transPtr->type != UBIK_WRITETRANS)
1117 if (!transPtr->iovec_info.iovec_wrt_len
1118 || !transPtr->iovec_info.iovec_wrt_val)
1121 DBHOLD(transPtr->dbase);
1122 if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY))
1123 ERROR_EXIT(UNOQUORUM);
1124 if (!ubeacon_AmSyncSite()) /* only sync site can write */
1125 ERROR_EXIT(UNOTSYNC);
1127 /* Update the rest of the servers in the quorum */
1129 ContactQuorum_DISK_WriteV(transPtr, 0, &transPtr->iovec_info,
1130 &transPtr->iovec_data);
1132 udisk_abort(transPtr);
1133 ContactQuorum_NoArguments(DISK_Abort, transPtr, 0); /* force aborts to the others */
1134 transPtr->iovec_info.iovec_wrt_len = 0;
1135 transPtr->iovec_data.iovec_buf_len = 0;
1139 /* Wrote the buffers out, so start at scratch again */
1140 transPtr->iovec_info.iovec_wrt_len = 0;
1141 transPtr->iovec_data.iovec_buf_len = 0;
1144 DBRELE(transPtr->dbase);
1149 ubik_Write(struct ubik_trans *transPtr, void *vbuffer,
1152 struct ubik_iovec *iovec;
1153 afs_int32 code, error = 0;
1154 afs_int32 pos, len, size;
1155 char * buffer = (char *)vbuffer;
1157 if (transPtr->type != UBIK_WRITETRANS)
1162 if (length > IOVEC_MAXBUF) {
1163 for (pos = 0, len = length; len > 0; len -= size, pos += size) {
1164 size = ((len < IOVEC_MAXBUF) ? len : IOVEC_MAXBUF);
1165 code = ubik_Write(transPtr, buffer+pos, size);
1172 if (!transPtr->iovec_info.iovec_wrt_val) {
1173 transPtr->iovec_info.iovec_wrt_len = 0;
1174 transPtr->iovec_info.iovec_wrt_val =
1175 (struct ubik_iovec *)malloc(IOVEC_MAXWRT *
1176 sizeof(struct ubik_iovec));
1177 transPtr->iovec_data.iovec_buf_len = 0;
1178 transPtr->iovec_data.iovec_buf_val = (char *)malloc(IOVEC_MAXBUF);
1179 if (!transPtr->iovec_info.iovec_wrt_val
1180 || !transPtr->iovec_data.iovec_buf_val) {
1181 if (transPtr->iovec_info.iovec_wrt_val)
1182 free(transPtr->iovec_info.iovec_wrt_val);
1183 transPtr->iovec_info.iovec_wrt_val = 0;
1184 if (transPtr->iovec_data.iovec_buf_val)
1185 free(transPtr->iovec_data.iovec_buf_val);
1186 transPtr->iovec_data.iovec_buf_val = 0;
1191 /* If this write won't fit in the structure, then flush it out and start anew */
1192 if ((transPtr->iovec_info.iovec_wrt_len >= IOVEC_MAXWRT)
1193 || ((length + transPtr->iovec_data.iovec_buf_len) > IOVEC_MAXBUF)) {
1194 code = ubik_Flush(transPtr);
1199 DBHOLD(transPtr->dbase);
1200 if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY))
1201 ERROR_EXIT(UNOQUORUM);
1202 if (!ubeacon_AmSyncSite()) /* only sync site can write */
1203 ERROR_EXIT(UNOTSYNC);
1205 /* Write to the local disk */
1207 udisk_write(transPtr, transPtr->seekFile, buffer, transPtr->seekPos,
1210 udisk_abort(transPtr);
1211 transPtr->iovec_info.iovec_wrt_len = 0;
1212 transPtr->iovec_data.iovec_buf_len = 0;
1213 DBRELE(transPtr->dbase);
1217 /* Collect writes for the other ubik servers (to be done in bulk) */
1218 iovec = (struct ubik_iovec *)transPtr->iovec_info.iovec_wrt_val;
1219 iovec[transPtr->iovec_info.iovec_wrt_len].file = transPtr->seekFile;
1220 iovec[transPtr->iovec_info.iovec_wrt_len].position = transPtr->seekPos;
1221 iovec[transPtr->iovec_info.iovec_wrt_len].length = length;
1223 memcpy(&transPtr->iovec_data.
1224 iovec_buf_val[transPtr->iovec_data.iovec_buf_len], buffer, length);
1226 transPtr->iovec_info.iovec_wrt_len++;
1227 transPtr->iovec_data.iovec_buf_len += length;
1228 transPtr->seekPos += length;
1231 DBRELE(transPtr->dbase);
1236 * \brief This sets the file pointer associated with the current transaction
1237 * to the appropriate file and byte position.
1239 * Unlike Unix files, a transaction is labelled by both a file number \p fileid
1240 * and a byte position relative to the specified file \p position.
1243 ubik_Seek(struct ubik_trans *transPtr, afs_int32 fileid,
1248 DBHOLD(transPtr->dbase);
1249 if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY)) {
1252 transPtr->seekFile = fileid;
1253 transPtr->seekPos = position;
1256 DBRELE(transPtr->dbase);
1261 * \brief This call returns the file pointer associated with the specified
1262 * transaction in \p fileid and \p position.
1265 ubik_Tell(struct ubik_trans *transPtr, afs_int32 * fileid,
1266 afs_int32 * position)
1268 DBHOLD(transPtr->dbase);
1269 *fileid = transPtr->seekFile;
1270 *position = transPtr->seekPos;
1271 DBRELE(transPtr->dbase);
1276 * \brief This sets the file size for the currently-selected file to \p length
1277 * bytes, if length is less than the file's current size.
1280 ubik_Truncate(struct ubik_trans *transPtr, afs_int32 length)
1282 afs_int32 code, error = 0;
1284 /* Will also catch if not UBIK_WRITETRANS */
1285 code = ubik_Flush(transPtr);
1289 DBHOLD(transPtr->dbase);
1290 /* first, check that quorum is still good, and that dbase is up-to-date */
1291 if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY))
1292 ERROR_EXIT(UNOQUORUM);
1293 if (!ubeacon_AmSyncSite())
1294 ERROR_EXIT(UNOTSYNC);
1296 /* now do the operation locally, and propagate it out */
1297 code = udisk_truncate(transPtr, transPtr->seekFile, length);
1300 ContactQuorum_DISK_Truncate(transPtr, 0, transPtr->seekFile,
1304 /* we must abort the operation */
1305 udisk_abort(transPtr);
1306 ContactQuorum_NoArguments(DISK_Abort, transPtr, 0); /* force aborts to the others */
1311 DBRELE(transPtr->dbase);
1316 * \brief set a lock; all locks are released on transaction end (commit/abort)
1319 ubik_SetLock(struct ubik_trans *atrans, afs_int32 apos, afs_int32 alen,
1322 afs_int32 code = 0, error = 0;
1324 if (atype == LOCKWRITE) {
1325 if (atrans->type == UBIK_READTRANS)
1327 code = ubik_Flush(atrans);
1332 DBHOLD(atrans->dbase);
1333 if (atype == LOCKREAD) {
1334 code = ulock_getLock(atrans, atype, 1);
1338 /* first, check that quorum is still good, and that dbase is up-to-date */
1339 if (!urecovery_AllBetter(atrans->dbase, atrans->flags & TRREADANY))
1340 ERROR_EXIT(UNOQUORUM);
1341 if (!ubeacon_AmSyncSite())
1342 ERROR_EXIT(UNOTSYNC);
1344 /* now do the operation locally, and propagate it out */
1345 code = ulock_getLock(atrans, atype, 1);
1347 code = ContactQuorum_DISK_Lock(atrans, 0, 0, 1 /*unused */ ,
1348 1 /*unused */ , LOCKWRITE);
1351 /* we must abort the operation */
1352 udisk_abort(atrans);
1353 ContactQuorum_NoArguments(DISK_Abort, atrans, 0); /* force aborts to the others */
1359 DBRELE(atrans->dbase);
1364 * \brief utility to wait for a version # to change
1367 ubik_WaitVersion(struct ubik_dbase *adatabase,
1368 struct ubik_version *aversion)
1372 /* wait until version # changes, and then return */
1373 if (vcmp(*aversion, adatabase->version) != 0) {
1377 #ifdef AFS_PTHREAD_ENV
1378 CV_WAIT(&adatabase->version_cond, &adatabase->versionLock);
1381 LWP_WaitProcess(&adatabase->version); /* same vers, just wait */
1388 * \brief utility to get the version of the dbase a transaction is dealing with
1391 ubik_GetVersion(struct ubik_trans *atrans,
1392 struct ubik_version *avers)
1394 *avers = atrans->dbase->version;
1399 * \brief Facility to simplify database caching.
1400 * \return zero if last trans was done on the local server and was successful.
1401 * \return -1 means bad (NULL) argument.
1403 * If return value is non-zero and the caller is a server caching part of the
1404 * Ubik database, it should invalidate that cache.
1407 ubik_CacheUpdate(struct ubik_trans *atrans)
1409 if (!(atrans && atrans->dbase))
1411 return vcmp(atrans->dbase->cachedVersion, atrans->dbase->version) != 0;
1415 * check and possibly update cache of ubik db.
1417 * If the version of the cached db data is out of date, this calls (*check) to
1418 * update the cache. If (*check) returns success, we update the version of the
1421 * Checking the version of the cached db data is done under a read lock;
1422 * updating the cache (and thus calling (*check)) is done under a write lock
1423 * so is guaranteed not to interfere with another thread's (*check). On
1424 * successful return, a read lock on the cached db data is obtained, which
1425 * will be released by ubik_EndTrans or ubik_AbortTrans.
1427 * @param[in] atrans ubik transaction
1428 * @param[in] check function to call to check/update cache
1429 * @param[in] rock rock to pass to *check
1431 * @return operation status
1433 * @retval nonzero error; cachedVersion not updated
1435 * @post On success, application cache is read-locked, and cache data is
1439 ubik_CheckCache(struct ubik_trans *atrans, ubik_updatecache_func cbf, void *rock)
1443 if (!(atrans && atrans->dbase))
1446 ObtainReadLock(&atrans->dbase->cache_lock);
1448 while (ubik_CacheUpdate(atrans) != 0) {
1450 ReleaseReadLock(&atrans->dbase->cache_lock);
1451 ObtainSharedLock(&atrans->dbase->cache_lock);
1453 if (ubik_CacheUpdate(atrans) != 0) {
1455 BoostSharedLock(&atrans->dbase->cache_lock);
1457 ret = (*cbf) (atrans, rock);
1459 memcpy(&atrans->dbase->cachedVersion, &atrans->dbase->version,
1460 sizeof(atrans->dbase->cachedVersion));
1464 /* It would be nice if we could convert from a shared lock to a read
1465 * lock... instead, just release the shared and acquire the read */
1466 ReleaseSharedLock(&atrans->dbase->cache_lock);
1469 /* if we have an error, don't retry, and don't hold any locks */
1473 ObtainReadLock(&atrans->dbase->cache_lock);
1476 atrans->flags |= TRCACHELOCKED;
1482 * "Who said anything about panicking?" snapped Arthur.
1483 * "This is still just the culture shock. You wait till I've settled down
1484 * into the situation and found my bearings. \em Then I'll start panicking!"
1487 * \returns There is no return from panic.
1490 panic(char *format, ...)
1494 va_start(ap, format);
1495 ubik_print("Ubik PANIC: ");
1496 ubik_vprint(format, ap);
1500 ubik_print("BACK FROM ABORT\n"); /* shouldn't come back */
1501 exit(1); /* never know, though */
1505 * This function takes an IP addresses as its parameter. It returns the
1506 * the primary IP address that is on the host passed in, or 0 if not found.
1509 ubikGetPrimaryInterfaceAddr(afs_uint32 addr)
1511 struct ubik_server *ts;
1514 for (ts = ubik_servers; ts; ts = ts->next)
1515 for (j = 0; j < UBIK_MAX_INTERFACE_ADDR; j++)
1516 if (ts->addr[j] == addr)
1517 return ts->addr[0]; /* net byte order */
1518 return 0; /* if not in server database, return error */