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) {error=(code); goto error_exit;}
43 * This system is organized in a hierarchical set of related modules. Modules
44 * at one level can only call modules at the same level or below.
46 * At the bottom level (0) we have R, RFTP, LWP and IOMGR, i.e. the basic
47 * operating system primitives.
49 * At the next level (1) we have
51 * \li VOTER--The module responsible for casting votes when asked. It is also
52 * responsible for determining whether this server should try to become
53 * a synchronization site.
54 * \li BEACONER--The module responsible for sending keep-alives out when a
55 * server is actually the sync site, or trying to become a sync site.
56 * \li DISK--The module responsible for representing atomic transactions
57 * on the local disk. It maintains a new-value only log.
58 * \li LOCK--The module responsible for locking byte ranges in the database file.
60 * At the next level (2) we have
62 * \li RECOVERY--The module responsible for ensuring that all members of a quorum
63 * have the same up-to-date database after a new synchronization site is
64 * elected. This module runs only on the synchronization site.
66 * At the next level (3) we have
68 * \li REMOTE--The module responsible for interpreting requests from the sync
69 * site and applying them to the database, after obtaining the appropriate
72 * At the next level (4) we have
74 * \li UBIK--The module users call to perform operations on the database.
79 afs_int32 ubik_quorum = 0;
80 struct ubik_dbase *ubik_dbase = 0;
81 struct ubik_stats ubik_stats;
82 afs_uint32 ubik_host[UBIK_MAX_INTERFACE_ADDR];
83 afs_int32 ubik_epochTime = 0;
84 afs_int32 urecovery_state = 0;
85 int (*ubik_SRXSecurityProc) (void *, struct rx_securityClass **, afs_int32 *);
86 void *ubik_SRXSecurityRock;
87 int (*ubik_SyncWriterCacheProc) (void);
88 struct ubik_server *ubik_servers;
89 short ubik_callPortal;
91 static int BeginTrans(struct ubik_dbase *dbase, afs_int32 transMode,
92 struct ubik_trans **transPtr, int readAny);
94 struct rx_securityClass *ubik_sc[3];
96 #define CStampVersion 1 /* meaning set ts->version */
98 static_inline struct rx_connection *
99 Quorum_StartIO(struct ubik_trans *atrans, struct ubik_server *as)
101 struct rx_connection *conn;
103 conn = as->disk_rxcid;
105 #ifdef AFS_PTHREAD_ENV
106 rx_GetConnection(conn);
107 DBRELE(atrans->dbase);
108 #endif /* AFS_PTHREAD_ENV */
114 Quorum_EndIO(struct ubik_trans *atrans, struct rx_connection *aconn)
116 #ifdef AFS_PTHREAD_ENV
117 DBHOLD(atrans->dbase);
118 rx_PutConnection(aconn);
119 #endif /* AFS_PTHREAD_ENV */
123 * \brief Perform an operation at a quorum, handling error conditions.
124 * \return 0 if all worked and a quorum was contacted successfully
125 * \return otherwise mark failing server as down and return #UERROR
127 * \note If any server misses an update, we must wait #BIGTIME seconds before
128 * allowing the transaction to commit, to ensure that the missing and
129 * possibly still functioning server times out and stops handing out old
130 * data. This is done in the commit code, where we wait for a server marked
131 * down to have stayed down for #BIGTIME seconds before we allow a transaction
132 * to commit. A server that fails but comes back up won't give out old data
133 * because it is sent the sync count along with the beacon message that
134 * marks it as \b really up (\p beaconSinceDown).
137 ContactQuorum_NoArguments(afs_int32 (*proc)(struct rx_connection *, ubik_tid *),
138 struct ubik_trans *atrans, int aflags)
140 struct ubik_server *ts;
142 afs_int32 rcode, okcalls;
143 struct rx_connection *conn;
147 for (ts = ubik_servers; ts; ts = ts->next) {
148 /* for each server */
149 if (!ts->up || !ts->currentDB) {
150 ts->currentDB = 0; /* db is no longer current; we just missed an update */
151 continue; /* not up-to-date, don't bother */
154 conn = Quorum_StartIO(atrans, ts);
156 code = (*proc)(conn, &atrans->tid);
158 Quorum_EndIO(atrans, conn);
161 if (code) { /* failure */
163 ts->up = 0; /* mark as down now; beacons will no longer be sent */
165 ts->beaconSinceDown = 0;
166 urecovery_LostServer(); /* tell recovery to try to resend dbase later */
167 } else { /* success */
169 okcalls++; /* count up how many worked */
170 if (aflags & CStampVersion) {
171 ts->version = atrans->dbase->version;
175 /* return 0 if we successfully contacted a quorum, otherwise return error code. We don't have to contact ourselves (that was done locally) */
176 if (okcalls + 1 >= ubik_quorum)
183 ContactQuorum_DISK_Lock(struct ubik_trans *atrans, int aflags,afs_int32 file,
184 afs_int32 position, afs_int32 length, afs_int32 type)
186 struct ubik_server *ts;
188 afs_int32 rcode, okcalls;
189 struct rx_connection *conn;
193 for (ts = ubik_servers; ts; ts = ts->next) {
194 /* for each server */
195 if (!ts->up || !ts->currentDB) {
196 ts->currentDB = 0; /* db is no longer current; we just missed an update */
197 continue; /* not up-to-date, don't bother */
200 conn = Quorum_StartIO(atrans, ts);
202 code = DISK_Lock(conn, &atrans->tid, file, position, length, type);
204 Quorum_EndIO(atrans, conn);
207 if (code) { /* failure */
209 ts->up = 0; /* mark as down now; beacons will no longer be sent */
211 ts->beaconSinceDown = 0;
212 urecovery_LostServer(); /* tell recovery to try to resend dbase later */
213 } else { /* success */
215 okcalls++; /* count up how many worked */
216 if (aflags & CStampVersion) {
217 ts->version = atrans->dbase->version;
221 /* return 0 if we successfully contacted a quorum, otherwise return error code. We don't have to contact ourselves (that was done locally) */
222 if (okcalls + 1 >= ubik_quorum)
229 ContactQuorum_DISK_Write(struct ubik_trans *atrans, int aflags,
230 afs_int32 file, afs_int32 position, bulkdata *data)
232 struct ubik_server *ts;
234 afs_int32 rcode, okcalls;
235 struct rx_connection *conn;
239 for (ts = ubik_servers; ts; ts = ts->next) {
240 /* for each server */
241 if (!ts->up || !ts->currentDB) {
242 ts->currentDB = 0; /* db is no longer current; we just missed an update */
243 continue; /* not up-to-date, don't bother */
246 conn = Quorum_StartIO(atrans, ts);
248 code = DISK_Write(conn, &atrans->tid, file, position, data);
250 Quorum_EndIO(atrans, conn);
253 if (code) { /* failure */
255 ts->up = 0; /* mark as down now; beacons will no longer be sent */
257 ts->beaconSinceDown = 0;
258 urecovery_LostServer(); /* tell recovery to try to resend dbase later */
259 } else { /* success */
261 okcalls++; /* count up how many worked */
262 if (aflags & CStampVersion) {
263 ts->version = atrans->dbase->version;
267 /* return 0 if we successfully contacted a quorum, otherwise return error code. We don't have to contact ourselves (that was done locally) */
268 if (okcalls + 1 >= ubik_quorum)
275 ContactQuorum_DISK_Truncate(struct ubik_trans *atrans, int aflags,
276 afs_int32 file, afs_int32 length)
278 struct ubik_server *ts;
280 afs_int32 rcode, okcalls;
281 struct rx_connection *conn;
285 for (ts = ubik_servers; ts; ts = ts->next) {
286 /* for each server */
287 if (!ts->up || !ts->currentDB) {
288 ts->currentDB = 0; /* db is no longer current; we just missed an update */
289 continue; /* not up-to-date, don't bother */
292 conn = Quorum_StartIO(atrans, ts);
294 code = DISK_Truncate(conn, &atrans->tid, file, length);
296 Quorum_EndIO(atrans, conn);
299 if (code) { /* failure */
301 ts->up = 0; /* mark as down now; beacons will no longer be sent */
303 ts->beaconSinceDown = 0;
304 urecovery_LostServer(); /* tell recovery to try to resend dbase later */
305 } else { /* success */
307 okcalls++; /* count up how many worked */
308 if (aflags & CStampVersion) {
309 ts->version = atrans->dbase->version;
313 /* return 0 if we successfully contacted a quorum, otherwise return error code. We don't have to contact ourselves (that was done locally) */
314 if (okcalls + 1 >= ubik_quorum)
321 ContactQuorum_DISK_WriteV(struct ubik_trans *atrans, int aflags,
322 iovec_wrt * io_vector, iovec_buf *io_buffer)
324 struct ubik_server *ts;
326 afs_int32 rcode, okcalls;
327 struct rx_connection *conn;
331 for (ts = ubik_servers; ts; ts = ts->next) {
332 /* for each server */
333 if (!ts->up || !ts->currentDB) {
334 ts->currentDB = 0; /* db is no longer current; we just missed an update */
335 continue; /* not up-to-date, don't bother */
338 conn = Quorum_StartIO(atrans, ts);
340 code = DISK_WriteV(conn, &atrans->tid, io_vector, io_buffer);
342 Quorum_EndIO(atrans, conn);
345 if ((code <= -450) && (code > -500)) {
346 /* An RPC interface mismatch (as defined in comerr/error_msg.c).
347 * Un-bulk the entries and do individual DISK_Write calls
348 * instead of DISK_WriteV.
350 struct ubik_iovec *iovec =
351 (struct ubik_iovec *)io_vector->iovec_wrt_val;
352 char *iobuf = (char *)io_buffer->iovec_buf_val;
356 conn = Quorum_StartIO(atrans, ts);
358 for (i = 0, offset = 0; i < io_vector->iovec_wrt_len; i++) {
359 /* Sanity check for going off end of buffer */
360 if ((offset + iovec[i].length) > io_buffer->iovec_buf_len) {
364 tcbs.bulkdata_len = iovec[i].length;
365 tcbs.bulkdata_val = &iobuf[offset];
368 DISK_Write(conn, &atrans->tid, iovec[i].file,
369 iovec[i].position, &tcbs);
373 offset += iovec[i].length;
376 Quorum_EndIO(atrans, conn);
380 if (code) { /* failure */
382 ts->up = 0; /* mark as down now; beacons will no longer be sent */
384 ts->beaconSinceDown = 0;
385 urecovery_LostServer(); /* tell recovery to try to resend dbase later */
386 } else { /* success */
388 okcalls++; /* count up how many worked */
389 if (aflags & CStampVersion) {
390 ts->version = atrans->dbase->version;
394 /* return 0 if we successfully contacted a quorum, otherwise return error code. We don't have to contact ourselves (that was done locally) */
395 if (okcalls + 1 >= ubik_quorum)
402 ContactQuorum_DISK_SetVersion(struct ubik_trans *atrans, int aflags,
403 ubik_version *OldVersion,
404 ubik_version *NewVersion)
406 struct ubik_server *ts;
408 afs_int32 rcode, okcalls;
409 struct rx_connection *conn;
413 for (ts = ubik_servers; ts; ts = ts->next) {
414 /* for each server */
415 if (!ts->up || !ts->currentDB) {
416 ts->currentDB = 0; /* db is no longer current; we just missed an update */
417 continue; /* not up-to-date, don't bother */
420 conn = Quorum_StartIO(atrans, ts);
422 code = DISK_SetVersion(conn, &atrans->tid, OldVersion, NewVersion);
424 Quorum_EndIO(atrans, conn);
427 if (code) { /* failure */
429 ts->up = 0; /* mark as down now; beacons will no longer be sent */
431 ts->beaconSinceDown = 0;
432 urecovery_LostServer(); /* tell recovery to try to resend dbase later */
433 } else { /* success */
435 okcalls++; /* count up how many worked */
436 if (aflags & CStampVersion) {
437 ts->version = atrans->dbase->version;
441 /* return 0 if we successfully contacted a quorum, otherwise return error code. We don't have to contact ourselves (that was done locally) */
442 if (okcalls + 1 >= ubik_quorum)
449 * \brief This routine initializes the ubik system for a set of servers.
450 * \return 0 for success, or an error code on failure.
451 * \param serverList set of servers specified; nServers gives the number of entries in this array.
452 * \param pathName provides an initial prefix used for naming storage files used by this system.
453 * \param dbase the returned structure representing this instance of an ubik; it is passed to various calls below.
455 * \todo This routine should perhaps be generalized to a low-level disk interface providing read, write, file enumeration and sync operations.
457 * \warning The host named by myHost should not also be listed in serverList.
459 * \see ubik_ServerInit(), ubik_ServerInitByInfo()
462 ubik_ServerInitCommon(afs_uint32 myHost, short myPort,
463 struct afsconf_cell *info, char clones[],
464 afs_uint32 serverList[], const char *pathName,
465 struct ubik_dbase **dbase)
467 struct ubik_dbase *tdb;
469 #ifdef AFS_PTHREAD_ENV
470 pthread_t rxServerThread; /* pthread variables */
471 pthread_t ubeacon_InteractThread;
472 pthread_t urecovery_InteractThread;
473 pthread_attr_t rxServer_tattr;
474 pthread_attr_t ubeacon_Interact_tattr;
475 pthread_attr_t urecovery_Interact_tattr;
478 extern int rx_stackSize;
482 struct rx_securityClass *secClass;
484 struct rx_service *tservice;
486 initialize_U_error_table();
488 tdb = (struct ubik_dbase *)malloc(sizeof(struct ubik_dbase));
489 tdb->pathName = (char *)malloc(strlen(pathName) + 1);
490 strcpy(tdb->pathName, pathName);
491 tdb->activeTrans = (struct ubik_trans *)0;
492 memset(&tdb->version, 0, sizeof(struct ubik_version));
493 memset(&tdb->cachedVersion, 0, sizeof(struct ubik_version));
494 #ifdef AFS_PTHREAD_ENV
495 MUTEX_INIT(&tdb->versionLock, "version lock", MUTEX_DEFAULT, 0);
497 Lock_Init(&tdb->versionLock);
499 Lock_Init(&tdb->cache_lock);
501 tdb->read = uphys_read;
502 tdb->write = uphys_write;
503 tdb->truncate = uphys_truncate;
504 tdb->open = uphys_invalidate; /* this function isn't used any more */
505 tdb->sync = uphys_sync;
506 tdb->stat = uphys_stat;
507 tdb->getlabel = uphys_getlabel;
508 tdb->setlabel = uphys_setlabel;
509 tdb->getnfiles = uphys_getnfiles;
511 tdb->tidCounter = tdb->writeTidCounter = 0;
513 ubik_dbase = tdb; /* for now, only one db per server; can fix later when we have names for the other dbases */
515 #ifdef AFS_PTHREAD_ENV
516 CV_INIT(&tdb->version_cond, "version", CV_DEFAULT, 0);
517 CV_INIT(&tdb->flags_cond, "flags", CV_DEFAULT, 0);
518 #endif /* AFS_PTHREAD_ENV */
522 /* the following call is idempotent so when/if it got called earlier,
523 * by whatever called us, it doesn't really matter -- klm */
524 code = rx_Init(myPort);
528 ubik_callPortal = myPort;
529 /* try to get an additional security object */
530 ubik_sc[0] = rxnull_NewServerSecurityObject();
533 if (ubik_SRXSecurityProc) {
535 (*ubik_SRXSecurityProc) (ubik_SRXSecurityRock, &secClass,
538 ubik_sc[secIndex] = secClass;
541 /* for backwards compat this should keep working as it does now
544 /* This really needs to be up above, where I have put it. It works
545 * here when we're non-pthreaded, but the code above, when using
546 * pthreads may (and almost certainly does) end up calling on a
547 * pthread resource which gets initialized by rx_Init. The end
548 * result is that an assert fails and the program dies. -- klm
550 code = rx_Init(myPort);
556 rx_NewService(0, VOTE_SERVICE_ID, "VOTE", ubik_sc, 3,
557 VOTE_ExecuteRequest);
558 if (tservice == (struct rx_service *)0) {
559 ubik_dprint("Could not create VOTE rx service!\n");
562 rx_SetMinProcs(tservice, 2);
563 rx_SetMaxProcs(tservice, 3);
566 rx_NewService(0, DISK_SERVICE_ID, "DISK", ubik_sc, 3,
567 DISK_ExecuteRequest);
568 if (tservice == (struct rx_service *)0) {
569 ubik_dprint("Could not create DISK rx service!\n");
572 rx_SetMinProcs(tservice, 2);
573 rx_SetMaxProcs(tservice, 3);
575 /* start an rx_ServerProc to handle incoming RPC's in particular the
576 * UpdateInterfaceAddr RPC that occurs in ubeacon_InitServerList. This avoids
577 * the "steplock" problem in ubik initialization. Defect 11037.
579 #ifdef AFS_PTHREAD_ENV
580 /* do assert stuff */
581 osi_Assert(pthread_attr_init(&rxServer_tattr) == 0);
582 osi_Assert(pthread_attr_setdetachstate(&rxServer_tattr, PTHREAD_CREATE_DETACHED) == 0);
583 /* osi_Assert(pthread_attr_setstacksize(&rxServer_tattr, rx_stackSize) == 0); */
585 osi_Assert(pthread_create(&rxServerThread, &rxServer_tattr, (void *)rx_ServerProc, NULL) == 0);
587 LWP_CreateProcess(rx_ServerProc, rx_stackSize, RX_PROCESS_PRIORITY,
588 NULL, "rx_ServerProc", &junk);
591 /* do basic initialization */
595 code = urecovery_Initialize(tdb);
599 code = ubeacon_InitServerListByInfo(myHost, info, clones);
601 code = ubeacon_InitServerList(myHost, serverList);
605 /* now start up async processes */
606 #ifdef AFS_PTHREAD_ENV
607 /* do assert stuff */
608 osi_Assert(pthread_attr_init(&ubeacon_Interact_tattr) == 0);
609 osi_Assert(pthread_attr_setdetachstate(&ubeacon_Interact_tattr, PTHREAD_CREATE_DETACHED) == 0);
610 /* osi_Assert(pthread_attr_setstacksize(&ubeacon_Interact_tattr, 16384) == 0); */
611 /* need another attr set here for priority??? - klm */
613 osi_Assert(pthread_create(&ubeacon_InteractThread, &ubeacon_Interact_tattr,
614 (void *)ubeacon_Interact, NULL) == 0);
616 code = LWP_CreateProcess(ubeacon_Interact, 16384 /*8192 */ ,
617 LWP_MAX_PRIORITY - 1, (void *)0, "beacon",
623 #ifdef AFS_PTHREAD_ENV
624 /* do assert stuff */
625 osi_Assert(pthread_attr_init(&urecovery_Interact_tattr) == 0);
626 osi_Assert(pthread_attr_setdetachstate(&urecovery_Interact_tattr, PTHREAD_CREATE_DETACHED) == 0);
627 /* osi_Assert(pthread_attr_setstacksize(&urecovery_Interact_tattr, 16384) == 0); */
628 /* need another attr set here for priority??? - klm */
630 osi_Assert(pthread_create(&urecovery_InteractThread, &urecovery_Interact_tattr,
631 (void *)urecovery_Interact, NULL) == 0);
633 return 0; /* is this correct? - klm */
635 code = LWP_CreateProcess(urecovery_Interact, 16384 /*8192 */ ,
636 LWP_MAX_PRIORITY - 1, (void *)0, "recovery",
644 * \see ubik_ServerInitCommon()
647 ubik_ServerInitByInfo(afs_uint32 myHost, short myPort,
648 struct afsconf_cell *info, char clones[],
649 const char *pathName, struct ubik_dbase **dbase)
654 ubik_ServerInitCommon(myHost, myPort, info, clones, 0, pathName,
660 * \see ubik_ServerInitCommon()
663 ubik_ServerInit(afs_uint32 myHost, short myPort, afs_uint32 serverList[],
664 const char *pathName, struct ubik_dbase **dbase)
669 ubik_ServerInitCommon(myHost, myPort, (struct afsconf_cell *)0, 0,
670 serverList, pathName, dbase);
675 * \brief This routine begins a read or write transaction on the transaction
676 * identified by transPtr, in the dbase named by dbase.
678 * An open mode of ubik_READTRANS identifies this as a read transaction,
679 * while a mode of ubik_WRITETRANS identifies this as a write transaction.
680 * transPtr is set to the returned transaction control block.
681 * The readAny flag is set to 0 or 1 or 2 by the wrapper functions
682 * ubik_BeginTrans() or ubik_BeginTransReadAny() or
683 * ubik_BeginTransReadAnyWrite() below.
685 * \note We can only begin transaction when we have an up-to-date database.
688 BeginTrans(struct ubik_dbase *dbase, afs_int32 transMode,
689 struct ubik_trans **transPtr, int readAny)
691 struct ubik_trans *jt;
692 struct ubik_trans *tt;
694 #if defined(UBIK_PAUSE)
696 #endif /* UBIK_PAUSE */
698 if (readAny > 1 && ubik_SyncWriterCacheProc == NULL) {
699 /* it's not safe to use ubik_BeginTransReadAnyWrite without a
700 * cache-syncing function; fall back to ubik_BeginTransReadAny,
701 * which is safe but slower */
702 ubik_print("ubik_BeginTransReadAnyWrite called, but "
703 "ubik_SyncWriterCacheProc not set; pretending "
704 "ubik_BeginTransReadAny was called instead\n");
708 if ((transMode != UBIK_READTRANS) && readAny)
711 #if defined(UBIK_PAUSE)
712 /* if we're polling the slave sites, wait until the returns
713 * are all in. Otherwise, the urecovery_CheckTid call may
716 if (transMode == UBIK_WRITETRANS)
717 for (count = 75; dbase->flags & DBVOTING; --count) {
719 #ifdef GRAND_PAUSE_DEBUGGING
722 "%ld: myport=%d: BeginTrans is waiting 'cause of voting conflict\n",
723 time(0), ntohs(ubik_callPortal));
729 "%ld: myport=%d: BeginTrans failed because of voting conflict\n",
730 time(0), ntohs(ubik_callPortal));
732 return UNOQUORUM; /* a white lie */
734 #ifdef AFS_PTHREAD_ENV
741 #endif /* UBIK_PAUSE */
742 if (urecovery_AllBetter(dbase, readAny) == 0) {
746 /* otherwise we have a quorum, use it */
748 /* make sure that at most one write transaction occurs at any one time. This
749 * has nothing to do with transaction locking; that's enforced by the lock package. However,
750 * we can't even handle two non-conflicting writes, since our log and recovery modules
751 * don't know how to restore one without possibly picking up some data from the other. */
752 if (transMode == UBIK_WRITETRANS) {
753 /* if we're writing already, wait */
754 while (dbase->flags & DBWRITING) {
755 #ifdef AFS_PTHREAD_ENV
756 CV_WAIT(&dbase->flags_cond, &dbase->versionLock);
759 LWP_WaitProcess(&dbase->flags);
764 if (!ubeacon_AmSyncSite()) {
770 /* create the transaction */
771 code = udisk_begin(dbase, transMode, &jt); /* can't take address of register var */
772 tt = jt; /* move to a register */
773 if (code || tt == (struct ubik_trans *)NULL) {
778 tt->flags |= TRREADANY;
780 tt->flags |= TRREADWRITE;
783 /* label trans and dbase with new tid */
784 tt->tid.epoch = ubik_epochTime;
785 /* bump by two, since tidCounter+1 means trans id'd by tidCounter has finished */
786 tt->tid.counter = (dbase->tidCounter += 2);
788 if (transMode == UBIK_WRITETRANS) {
789 /* for a write trans, we have to keep track of the write tid counter too */
790 dbase->writeTidCounter = tt->tid.counter;
792 /* next try to start transaction on appropriate number of machines */
793 code = ContactQuorum_NoArguments(DISK_Begin, tt, 0);
795 /* we must abort the operation */
797 ContactQuorum_NoArguments(DISK_Abort, tt, 0); /* force aborts to the others */
813 ubik_BeginTrans(struct ubik_dbase *dbase, afs_int32 transMode,
814 struct ubik_trans **transPtr)
816 return BeginTrans(dbase, transMode, transPtr, 0);
823 ubik_BeginTransReadAny(struct ubik_dbase *dbase, afs_int32 transMode,
824 struct ubik_trans **transPtr)
826 return BeginTrans(dbase, transMode, transPtr, 1);
833 ubik_BeginTransReadAnyWrite(struct ubik_dbase *dbase, afs_int32 transMode,
834 struct ubik_trans **transPtr)
836 return BeginTrans(dbase, transMode, transPtr, 2);
840 * \brief This routine ends a read or write transaction by aborting it.
843 ubik_AbortTrans(struct ubik_trans *transPtr)
847 struct ubik_dbase *dbase;
849 dbase = transPtr->dbase;
851 if (transPtr->flags & TRCACHELOCKED) {
852 ReleaseReadLock(&dbase->cache_lock);
853 transPtr->flags &= ~TRCACHELOCKED;
856 ObtainWriteLock(&dbase->cache_lock);
859 memset(&dbase->cachedVersion, 0, sizeof(struct ubik_version));
861 ReleaseWriteLock(&dbase->cache_lock);
863 /* see if we're still up-to-date */
864 if (!urecovery_AllBetter(dbase, transPtr->flags & TRREADANY)) {
865 udisk_abort(transPtr);
871 if (transPtr->type == UBIK_READTRANS) {
872 code = udisk_abort(transPtr);
878 /* below here, we know we're doing a write transaction */
879 if (!ubeacon_AmSyncSite()) {
880 udisk_abort(transPtr);
886 /* now it is safe to try remote abort */
887 code = ContactQuorum_NoArguments(DISK_Abort, transPtr, 0);
888 code2 = udisk_abort(transPtr);
891 return (code ? code : code2);
895 WritebackApplicationCache(struct ubik_dbase *dbase)
898 if (ubik_SyncWriterCacheProc) {
899 code = ubik_SyncWriterCacheProc();
902 /* we failed to sync the local cache, so just invalidate the cache;
903 * we'll try to read the cache in again on the next read */
904 memset(&dbase->cachedVersion, 0, sizeof(dbase->cachedVersion));
906 memcpy(&dbase->cachedVersion, &dbase->version,
907 sizeof(dbase->cachedVersion));
912 * \brief This routine ends a read or write transaction on the open transaction identified by transPtr.
913 * \return an error code.
916 ubik_EndTrans(struct ubik_trans *transPtr)
921 struct ubik_server *ts;
924 struct ubik_dbase *dbase;
926 if (transPtr->type == UBIK_WRITETRANS) {
927 code = ubik_Flush(transPtr);
929 ubik_AbortTrans(transPtr);
934 dbase = transPtr->dbase;
936 if (transPtr->flags & TRCACHELOCKED) {
937 ReleaseReadLock(&dbase->cache_lock);
938 transPtr->flags &= ~TRCACHELOCKED;
941 if (transPtr->type != UBIK_READTRANS) {
942 /* must hold cache_lock before DBHOLD'ing */
943 ObtainWriteLock(&dbase->cache_lock);
949 /* give up if no longer current */
950 if (!urecovery_AllBetter(dbase, transPtr->flags & TRREADANY)) {
951 udisk_abort(transPtr);
958 if (transPtr->type == UBIK_READTRANS) { /* reads are easy */
959 code = udisk_commit(transPtr);
961 goto success; /* update cachedVersion correctly */
967 if (!ubeacon_AmSyncSite()) { /* no longer sync site */
968 udisk_abort(transPtr);
975 /* now it is safe to do commit */
976 code = udisk_commit(transPtr);
978 /* db data has been committed locally; update the local cache so
979 * readers can get at it */
980 WritebackApplicationCache(dbase);
982 ReleaseWriteLock(&dbase->cache_lock);
984 code = ContactQuorum_NoArguments(DISK_Commit, transPtr, CStampVersion);
987 memset(&dbase->cachedVersion, 0, sizeof(struct ubik_version));
988 ReleaseWriteLock(&dbase->cache_lock);
992 /* failed to commit, so must return failure. Try to clear locks first, just for fun
993 * Note that we don't know if this transaction will eventually commit at this point.
994 * If it made it to a site that will be present in the next quorum, we win, otherwise
995 * we lose. If we contact a majority of sites, then we won't be here: contacting
996 * a majority guarantees commit, since it guarantees that one dude will be a
997 * member of the next quorum. */
998 ContactQuorum_NoArguments(DISK_ReleaseLocks, transPtr, 0);
1003 /* before we can start sending unlock messages, we must wait until all servers
1004 * that are possibly still functioning on the other side of a network partition
1005 * have timed out. Check the server structures, compute how long to wait, then
1006 * start the unlocks */
1007 realStart = FT_ApproxTime();
1009 /* wait for all servers to time out */
1011 now = FT_ApproxTime();
1012 /* check if we're still sync site, the guy should either come up
1013 * to us, or timeout. Put safety check in anyway */
1014 if (now - realStart > 10 * BIGTIME) {
1015 ubik_stats.escapes++;
1016 ubik_print("ubik escaping from commit wait\n");
1019 for (ts = ubik_servers; ts; ts = ts->next) {
1020 if (!ts->beaconSinceDown && now <= ts->lastBeaconSent + BIGTIME) {
1022 /* this guy could have some damaged data, wait for him */
1024 tv.tv_sec = 1; /* try again after a while (ha ha) */
1027 #ifdef AFS_PTHREAD_ENV
1028 /* we could release the dbase outside of the loop, but we do
1029 * it here, in the loop, to avoid an unnecessary RELE/HOLD
1030 * if all sites are up */
1032 select(0, 0, 0, 0, &tv);
1035 IOMGR_Select(0, 0, 0, 0, &tv); /* poll, should we wait on something? */
1042 break; /* no down ones still pseudo-active */
1045 /* finally, unlock all the dudes. We can return success independent of the number of servers
1046 * that really unlock the dbase; the others will do it if/when they elect a new sync site.
1047 * The transaction is committed anyway, since we succeeded in contacting a quorum
1048 * at the start (when invoking the DiskCommit function).
1050 ContactQuorum_NoArguments(DISK_ReleaseLocks, transPtr, 0);
1053 udisk_end(transPtr);
1054 /* don't update cachedVersion here; it should have been updated way back
1055 * in ubik_CheckCache, and earlier in this function for writes */
1058 ReleaseWriteLock(&dbase->cache_lock);
1064 ObtainWriteLock(&dbase->cache_lock);
1066 memset(&dbase->cachedVersion, 0, sizeof(struct ubik_version));
1067 ReleaseWriteLock(&dbase->cache_lock);
1072 * \brief This routine reads length bytes into buffer from the current position in the database.
1074 * 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.
1076 * \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.
1079 ubik_Read(struct ubik_trans *transPtr, void *buffer,
1084 /* reads are easy to do: handle locally */
1085 DBHOLD(transPtr->dbase);
1086 if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY)) {
1087 DBRELE(transPtr->dbase);
1092 udisk_read(transPtr, transPtr->seekFile, buffer, transPtr->seekPos,
1095 transPtr->seekPos += length;
1097 DBRELE(transPtr->dbase);
1102 * \brief This routine will flush the io data in the iovec structures.
1104 * It first flushes to the local disk and then uses ContactQuorum to write it
1105 * to the other servers.
1108 ubik_Flush(struct ubik_trans *transPtr)
1110 afs_int32 code, error = 0;
1112 if (transPtr->type != UBIK_WRITETRANS)
1114 if (!transPtr->iovec_info.iovec_wrt_len
1115 || !transPtr->iovec_info.iovec_wrt_val)
1118 DBHOLD(transPtr->dbase);
1119 if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY))
1120 ERROR_EXIT(UNOQUORUM);
1121 if (!ubeacon_AmSyncSite()) /* only sync site can write */
1122 ERROR_EXIT(UNOTSYNC);
1124 /* Update the rest of the servers in the quorum */
1126 ContactQuorum_DISK_WriteV(transPtr, 0, &transPtr->iovec_info,
1127 &transPtr->iovec_data);
1129 udisk_abort(transPtr);
1130 ContactQuorum_NoArguments(DISK_Abort, transPtr, 0); /* force aborts to the others */
1131 transPtr->iovec_info.iovec_wrt_len = 0;
1132 transPtr->iovec_data.iovec_buf_len = 0;
1136 /* Wrote the buffers out, so start at scratch again */
1137 transPtr->iovec_info.iovec_wrt_len = 0;
1138 transPtr->iovec_data.iovec_buf_len = 0;
1141 DBRELE(transPtr->dbase);
1146 ubik_Write(struct ubik_trans *transPtr, void *vbuffer,
1149 struct ubik_iovec *iovec;
1150 afs_int32 code, error = 0;
1151 afs_int32 pos, len, size;
1152 char * buffer = (char *)vbuffer;
1154 if (transPtr->type != UBIK_WRITETRANS)
1159 if (length > IOVEC_MAXBUF) {
1160 for (pos = 0, len = length; len > 0; len -= size, pos += size) {
1161 size = ((len < IOVEC_MAXBUF) ? len : IOVEC_MAXBUF);
1162 code = ubik_Write(transPtr, buffer+pos, size);
1169 if (!transPtr->iovec_info.iovec_wrt_val) {
1170 transPtr->iovec_info.iovec_wrt_len = 0;
1171 transPtr->iovec_info.iovec_wrt_val =
1172 (struct ubik_iovec *)malloc(IOVEC_MAXWRT *
1173 sizeof(struct ubik_iovec));
1174 transPtr->iovec_data.iovec_buf_len = 0;
1175 transPtr->iovec_data.iovec_buf_val = (char *)malloc(IOVEC_MAXBUF);
1176 if (!transPtr->iovec_info.iovec_wrt_val
1177 || !transPtr->iovec_data.iovec_buf_val) {
1178 if (transPtr->iovec_info.iovec_wrt_val)
1179 free(transPtr->iovec_info.iovec_wrt_val);
1180 transPtr->iovec_info.iovec_wrt_val = 0;
1181 if (transPtr->iovec_data.iovec_buf_val)
1182 free(transPtr->iovec_data.iovec_buf_val);
1183 transPtr->iovec_data.iovec_buf_val = 0;
1188 /* If this write won't fit in the structure, then flush it out and start anew */
1189 if ((transPtr->iovec_info.iovec_wrt_len >= IOVEC_MAXWRT)
1190 || ((length + transPtr->iovec_data.iovec_buf_len) > IOVEC_MAXBUF)) {
1191 code = ubik_Flush(transPtr);
1196 DBHOLD(transPtr->dbase);
1197 if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY))
1198 ERROR_EXIT(UNOQUORUM);
1199 if (!ubeacon_AmSyncSite()) /* only sync site can write */
1200 ERROR_EXIT(UNOTSYNC);
1202 /* Write to the local disk */
1204 udisk_write(transPtr, transPtr->seekFile, buffer, transPtr->seekPos,
1207 udisk_abort(transPtr);
1208 transPtr->iovec_info.iovec_wrt_len = 0;
1209 transPtr->iovec_data.iovec_buf_len = 0;
1210 DBRELE(transPtr->dbase);
1214 /* Collect writes for the other ubik servers (to be done in bulk) */
1215 iovec = (struct ubik_iovec *)transPtr->iovec_info.iovec_wrt_val;
1216 iovec[transPtr->iovec_info.iovec_wrt_len].file = transPtr->seekFile;
1217 iovec[transPtr->iovec_info.iovec_wrt_len].position = transPtr->seekPos;
1218 iovec[transPtr->iovec_info.iovec_wrt_len].length = length;
1220 memcpy(&transPtr->iovec_data.
1221 iovec_buf_val[transPtr->iovec_data.iovec_buf_len], buffer, length);
1223 transPtr->iovec_info.iovec_wrt_len++;
1224 transPtr->iovec_data.iovec_buf_len += length;
1225 transPtr->seekPos += length;
1228 DBRELE(transPtr->dbase);
1233 * \brief This sets the file pointer associated with the current transaction
1234 * to the appropriate file and byte position.
1236 * Unlike Unix files, a transaction is labelled by both a file number \p fileid
1237 * and a byte position relative to the specified file \p position.
1240 ubik_Seek(struct ubik_trans *transPtr, afs_int32 fileid,
1245 DBHOLD(transPtr->dbase);
1246 if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY)) {
1249 transPtr->seekFile = fileid;
1250 transPtr->seekPos = position;
1253 DBRELE(transPtr->dbase);
1258 * \brief This call returns the file pointer associated with the specified
1259 * transaction in \p fileid and \p position.
1262 ubik_Tell(struct ubik_trans *transPtr, afs_int32 * fileid,
1263 afs_int32 * position)
1265 DBHOLD(transPtr->dbase);
1266 *fileid = transPtr->seekFile;
1267 *position = transPtr->seekPos;
1268 DBRELE(transPtr->dbase);
1273 * \brief This sets the file size for the currently-selected file to \p length
1274 * bytes, if length is less than the file's current size.
1277 ubik_Truncate(struct ubik_trans *transPtr, afs_int32 length)
1279 afs_int32 code, error = 0;
1281 /* Will also catch if not UBIK_WRITETRANS */
1282 code = ubik_Flush(transPtr);
1286 DBHOLD(transPtr->dbase);
1287 /* first, check that quorum is still good, and that dbase is up-to-date */
1288 if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY))
1289 ERROR_EXIT(UNOQUORUM);
1290 if (!ubeacon_AmSyncSite())
1291 ERROR_EXIT(UNOTSYNC);
1293 /* now do the operation locally, and propagate it out */
1294 code = udisk_truncate(transPtr, transPtr->seekFile, length);
1297 ContactQuorum_DISK_Truncate(transPtr, 0, transPtr->seekFile,
1301 /* we must abort the operation */
1302 udisk_abort(transPtr);
1303 ContactQuorum_NoArguments(DISK_Abort, transPtr, 0); /* force aborts to the others */
1308 DBRELE(transPtr->dbase);
1313 * \brief set a lock; all locks are released on transaction end (commit/abort)
1316 ubik_SetLock(struct ubik_trans *atrans, afs_int32 apos, afs_int32 alen,
1319 afs_int32 code = 0, error = 0;
1321 if (atype == LOCKWRITE) {
1322 if (atrans->type == UBIK_READTRANS)
1324 code = ubik_Flush(atrans);
1329 DBHOLD(atrans->dbase);
1330 if (atype == LOCKREAD) {
1331 code = ulock_getLock(atrans, atype, 1);
1335 /* first, check that quorum is still good, and that dbase is up-to-date */
1336 if (!urecovery_AllBetter(atrans->dbase, atrans->flags & TRREADANY))
1337 ERROR_EXIT(UNOQUORUM);
1338 if (!ubeacon_AmSyncSite())
1339 ERROR_EXIT(UNOTSYNC);
1341 /* now do the operation locally, and propagate it out */
1342 code = ulock_getLock(atrans, atype, 1);
1344 code = ContactQuorum_DISK_Lock(atrans, 0, 0, 1 /*unused */ ,
1345 1 /*unused */ , LOCKWRITE);
1348 /* we must abort the operation */
1349 udisk_abort(atrans);
1350 ContactQuorum_NoArguments(DISK_Abort, atrans, 0); /* force aborts to the others */
1356 DBRELE(atrans->dbase);
1361 * \brief utility to wait for a version # to change
1364 ubik_WaitVersion(struct ubik_dbase *adatabase,
1365 struct ubik_version *aversion)
1369 /* wait until version # changes, and then return */
1370 if (vcmp(*aversion, adatabase->version) != 0) {
1374 #ifdef AFS_PTHREAD_ENV
1375 CV_WAIT(&adatabase->version_cond, &adatabase->versionLock);
1378 LWP_WaitProcess(&adatabase->version); /* same vers, just wait */
1385 * \brief utility to get the version of the dbase a transaction is dealing with
1388 ubik_GetVersion(struct ubik_trans *atrans,
1389 struct ubik_version *avers)
1391 *avers = atrans->dbase->version;
1396 * \brief Facility to simplify database caching.
1397 * \return zero if last trans was done on the local server and was successful.
1398 * \return -1 means bad (NULL) argument.
1400 * If return value is non-zero and the caller is a server caching part of the
1401 * Ubik database, it should invalidate that cache.
1404 ubik_CacheUpdate(struct ubik_trans *atrans)
1406 if (!(atrans && atrans->dbase))
1408 return vcmp(atrans->dbase->cachedVersion, atrans->dbase->version) != 0;
1412 * check and possibly update cache of ubik db.
1414 * If the version of the cached db data is out of date, this calls (*check) to
1415 * update the cache. If (*check) returns success, we update the version of the
1418 * Checking the version of the cached db data is done under a read lock;
1419 * updating the cache (and thus calling (*check)) is done under a write lock
1420 * so is guaranteed not to interfere with another thread's (*check). On
1421 * successful return, a read lock on the cached db data is obtained, which
1422 * will be released by ubik_EndTrans or ubik_AbortTrans.
1424 * @param[in] atrans ubik transaction
1425 * @param[in] check function to call to check/update cache
1426 * @param[in] rock rock to pass to *check
1428 * @return operation status
1430 * @retval nonzero error; cachedVersion not updated
1432 * @post On success, application cache is read-locked, and cache data is
1436 ubik_CheckCache(struct ubik_trans *atrans, ubik_updatecache_func cbf, void *rock)
1440 if (!(atrans && atrans->dbase))
1443 ObtainReadLock(&atrans->dbase->cache_lock);
1445 while (ubik_CacheUpdate(atrans) != 0) {
1447 ReleaseReadLock(&atrans->dbase->cache_lock);
1448 ObtainSharedLock(&atrans->dbase->cache_lock);
1450 if (ubik_CacheUpdate(atrans) != 0) {
1452 BoostSharedLock(&atrans->dbase->cache_lock);
1454 ret = (*cbf) (atrans, rock);
1456 memcpy(&atrans->dbase->cachedVersion, &atrans->dbase->version,
1457 sizeof(atrans->dbase->cachedVersion));
1461 /* It would be nice if we could convert from a shared lock to a read
1462 * lock... instead, just release the shared and acquire the read */
1463 ReleaseSharedLock(&atrans->dbase->cache_lock);
1466 /* if we have an error, don't retry, and don't hold any locks */
1470 ObtainReadLock(&atrans->dbase->cache_lock);
1473 atrans->flags |= TRCACHELOCKED;
1479 * "Who said anything about panicking?" snapped Arthur.
1480 * "This is still just the culture shock. You wait till I've settled down
1481 * into the situation and found my bearings. \em Then I'll start panicking!"
1484 * \returns There is no return from panic.
1487 panic(char *format, ...)
1491 va_start(ap, format);
1492 ubik_print("Ubik PANIC: ");
1493 ubik_vprint(format, ap);
1497 ubik_print("BACK FROM ABORT\n"); /* shouldn't come back */
1498 exit(1); /* never know, though */
1502 * This function takes an IP addresses as its parameter. It returns the
1503 * the primary IP address that is on the host passed in, or 0 if not found.
1506 ubikGetPrimaryInterfaceAddr(afs_uint32 addr)
1508 struct ubik_server *ts;
1511 for (ts = ubik_servers; ts; ts = ts->next)
1512 for (j = 0; j < UBIK_MAX_INTERFACE_ADDR; j++)
1513 if (ts->addr[j] == addr)
1514 return ts->addr[0]; /* net byte order */
1515 return 0; /* if not in server database, return error */