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>
17 #ifdef AFS_PTHREAD_ENV
18 # include <opr/lock.h>
20 # include <opr/lockstub.h>
25 #include <afs/cellconfig.h>
26 #include <afs/afsutil.h>
29 #define UBIK_INTERNALS
33 #include <lwp.h> /* temporary hack by klm */
35 #define ERROR_EXIT(code) do { \
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 urecovery_state = 0;
83 int (*ubik_SyncWriterCacheProc) (void);
84 struct ubik_server *ubik_servers;
85 short ubik_callPortal;
87 /* These global variables were used to control the server security layers.
88 * They are retained for backwards compatibility with legacy callers.
90 * The ubik_SetServerSecurityProcs() interface should be used instead.
93 int (*ubik_SRXSecurityProc) (void *, struct rx_securityClass **, afs_int32 *);
94 void *ubik_SRXSecurityRock;
95 int (*ubik_CheckRXSecurityProc) (void *, struct rx_call *);
96 void *ubik_CheckRXSecurityRock;
100 static int BeginTrans(struct ubik_dbase *dbase, afs_int32 transMode,
101 struct ubik_trans **transPtr, int readAny);
103 static struct rx_securityClass **ubik_sc = NULL;
104 static void (*buildSecClassesProc)(void *, struct rx_securityClass ***,
106 static int (*checkSecurityProc)(void *, struct rx_call *) = NULL;
107 static void *securityRock = NULL;
109 struct version_data version_globals;
111 #define CStampVersion 1 /* meaning set ts->version */
112 #define CCheckSyncAdvertised 2 /* check if the remote knows we are the sync-site */
114 static_inline struct rx_connection *
115 Quorum_StartIO(struct ubik_trans *atrans, struct ubik_server *as)
117 struct rx_connection *conn;
120 conn = as->disk_rxcid;
122 #ifdef AFS_PTHREAD_ENV
123 rx_GetConnection(conn);
125 DBRELE(atrans->dbase);
128 #endif /* AFS_PTHREAD_ENV */
134 Quorum_EndIO(struct ubik_trans *atrans, struct rx_connection *aconn)
136 #ifdef AFS_PTHREAD_ENV
137 DBHOLD(atrans->dbase);
138 rx_PutConnection(aconn);
139 #endif /* AFS_PTHREAD_ENV */
144 * Iterate over all servers. Callers pass in *ts which is used to track
145 * the current server.
146 * - Returns 1 if there are no more servers
147 * - Returns 0 with conn set to the connection for the current server if
148 * it's up and current
151 ContactQuorum_iterate(struct ubik_trans *atrans, int aflags, struct ubik_server **ts,
152 struct rx_connection **conn, afs_int32 *rcode,
153 afs_int32 *okcalls, afs_int32 code, const char *procname)
156 /* Initial call - start iterating over servers */
163 Quorum_EndIO(atrans, *conn);
165 if (code) { /* failure */
170 (*ts)->up = 0; /* mark as down now; beacons will no longer be sent */
171 (*ts)->beaconSinceDown = 0;
173 (*ts)->currentDB = 0;
174 urecovery_LostServer(*ts); /* tell recovery to try to resend dbase later */
175 ViceLog(0, ("Server %s is marked down due to %s code %d\n",
176 afs_inet_ntoa_r((*ts)->addr[0], hoststr), procname, *rcode));
177 } else { /* success */
179 (*okcalls)++; /* count up how many worked */
180 if (aflags & CStampVersion) {
181 (*ts)->version = atrans->dbase->version;
190 if (!(*ts)->up || !(*ts)->currentDB ||
191 /* do not call DISK_Begin until we know that lastYesState is set on the
192 * remote in question; otherwise, DISK_Begin will fail. */
193 ((aflags & CCheckSyncAdvertised) && !((*ts)->beaconSinceDown && (*ts)->lastVote))) {
195 (*ts)->currentDB = 0; /* db is no longer current; we just missed an update */
196 return 0; /* not up-to-date, don't bother. NULL conn will tell caller not to use */
199 *conn = Quorum_StartIO(atrans, *ts);
204 ContactQuorum_rcode(int okcalls, afs_int32 rcode)
207 * return 0 if we successfully contacted a quorum, otherwise return error code.
208 * We don't have to contact ourselves (that was done locally)
210 if (okcalls + 1 >= ubik_quorum)
213 return (rcode != 0) ? rcode : UNOQUORUM;
217 * \brief Perform an operation at a quorum, handling error conditions.
218 * \return 0 if all worked and a quorum was contacted successfully
219 * \return otherwise mark failing server as down and return #UERROR
221 * \note If any server misses an update, we must wait #BIGTIME seconds before
222 * allowing the transaction to commit, to ensure that the missing and
223 * possibly still functioning server times out and stops handing out old
224 * data. This is done in the commit code, where we wait for a server marked
225 * down to have stayed down for #BIGTIME seconds before we allow a transaction
226 * to commit. A server that fails but comes back up won't give out old data
227 * because it is sent the sync count along with the beacon message that
228 * marks it as \b really up (\p beaconSinceDown).
231 ContactQuorum_NoArguments(afs_int32 (*proc)(struct rx_connection *, ubik_tid *),
232 struct ubik_trans *atrans, int aflags, const char *procname)
234 struct ubik_server *ts = NULL;
235 afs_int32 code = 0, rcode, okcalls;
236 struct rx_connection *conn;
239 done = ContactQuorum_iterate(atrans, aflags, &ts, &conn, &rcode, &okcalls, code, procname);
242 code = (*proc)(conn, &atrans->tid);
243 done = ContactQuorum_iterate(atrans, aflags, &ts, &conn, &rcode, &okcalls, code, procname);
245 return ContactQuorum_rcode(okcalls, rcode);
250 ContactQuorum_DISK_Lock(struct ubik_trans *atrans, int aflags,afs_int32 file,
251 afs_int32 position, afs_int32 length, afs_int32 type)
253 struct ubik_server *ts = NULL;
254 afs_int32 code = 0, rcode, okcalls;
255 struct rx_connection *conn;
257 char *procname = "DISK_Lock";
259 done = ContactQuorum_iterate(atrans, aflags, &ts, &conn, &rcode, &okcalls, code, procname);
262 code = DISK_Lock(conn, &atrans->tid, file, position, length, type);
263 done = ContactQuorum_iterate(atrans, aflags, &ts, &conn, &rcode, &okcalls, code, procname);
265 return ContactQuorum_rcode(okcalls, rcode);
269 ContactQuorum_DISK_Truncate(struct ubik_trans *atrans, int aflags,
270 afs_int32 file, afs_int32 length)
272 struct ubik_server *ts = NULL;
273 afs_int32 code = 0, rcode, okcalls;
274 struct rx_connection *conn;
276 char *procname = "DISK_Truncate";
278 done = ContactQuorum_iterate(atrans, aflags, &ts, &conn, &rcode, &okcalls, code, procname);
281 code = DISK_Truncate(conn, &atrans->tid, file, length);
282 done = ContactQuorum_iterate(atrans, aflags, &ts, &conn, &rcode, &okcalls, code, procname);
284 return ContactQuorum_rcode(okcalls, rcode);
289 ContactQuorum_DISK_WriteV(struct ubik_trans *atrans, int aflags,
290 iovec_wrt * io_vector, iovec_buf *io_buffer)
292 struct ubik_server *ts = NULL;
293 afs_int32 code = 0, rcode, okcalls;
294 struct rx_connection *conn;
296 char *procname = "DISK_WriteV";
298 done = ContactQuorum_iterate(atrans, aflags, &ts, &conn, &rcode, &okcalls, code, procname);
301 procname = "DISK_WriteV"; /* in case previous fallback to DISK_Write */
302 code = DISK_WriteV(conn, &atrans->tid, io_vector, io_buffer);
303 if ((code <= -450) && (code > -500)) {
304 /* An RPC interface mismatch (as defined in comerr/error_msg.c).
305 * Un-bulk the entries and do individual DISK_Write calls
306 * instead of DISK_WriteV.
308 struct ubik_iovec *iovec =
309 (struct ubik_iovec *)io_vector->iovec_wrt_val;
310 char *iobuf = (char *)io_buffer->iovec_buf_val;
314 procname = "DISK_Write"; /* for accurate error msg, if any */
315 for (i = 0, offset = 0; i < io_vector->iovec_wrt_len; i++) {
316 /* Sanity check for going off end of buffer */
317 if ((offset + iovec[i].length) > io_buffer->iovec_buf_len) {
321 tcbs.bulkdata_len = iovec[i].length;
322 tcbs.bulkdata_val = &iobuf[offset];
323 code = DISK_Write(conn, &atrans->tid, iovec[i].file,
324 iovec[i].position, &tcbs);
327 offset += iovec[i].length;
331 done = ContactQuorum_iterate(atrans, aflags, &ts, &conn, &rcode, &okcalls, code, procname);
333 return ContactQuorum_rcode(okcalls, rcode);
338 ContactQuorum_DISK_SetVersion(struct ubik_trans *atrans, int aflags,
339 ubik_version *OldVersion,
340 ubik_version *NewVersion)
342 struct ubik_server *ts = NULL;
343 afs_int32 code = 0, rcode, okcalls;
344 struct rx_connection *conn;
346 char *procname = "DISK_SetVersion";
348 done = ContactQuorum_iterate(atrans, aflags, &ts, &conn, &rcode, &okcalls, code, procname);
351 code = DISK_SetVersion(conn, &atrans->tid, OldVersion, NewVersion);
352 done = ContactQuorum_iterate(atrans, aflags, &ts, &conn, &rcode, &okcalls, code, procname);
354 return ContactQuorum_rcode(okcalls, rcode);
357 #if defined(AFS_PTHREAD_ENV)
359 ubik_thread_create(pthread_attr_t *tattr, pthread_t *thread, void *proc) {
360 opr_Verify(pthread_attr_init(tattr) == 0);
361 opr_Verify(pthread_attr_setdetachstate(tattr,
362 PTHREAD_CREATE_DETACHED) == 0);
363 opr_Verify(pthread_create(thread, tattr, proc, NULL) == 0);
369 * \brief This routine initializes the ubik system for a set of servers.
370 * \return 0 for success, or an error code on failure.
371 * \param serverList set of servers specified; nServers gives the number of entries in this array.
372 * \param pathName provides an initial prefix used for naming storage files used by this system.
373 * \param dbase the returned structure representing this instance of an ubik; it is passed to various calls below.
375 * \todo This routine should perhaps be generalized to a low-level disk interface providing read, write, file enumeration and sync operations.
377 * \warning The host named by myHost should not also be listed in serverList.
379 * \see ubik_ServerInit(), ubik_ServerInitByInfo()
382 ubik_ServerInitCommon(afs_uint32 myHost, short myPort,
383 struct afsconf_cell *info, char clones[],
384 afs_uint32 serverList[], const char *pathName,
385 struct ubik_dbase **dbase)
387 struct ubik_dbase *tdb;
389 #ifdef AFS_PTHREAD_ENV
390 pthread_t rxServerThread; /* pthread variables */
391 pthread_t ubeacon_InteractThread;
392 pthread_t urecovery_InteractThread;
393 pthread_attr_t rxServer_tattr;
394 pthread_attr_t ubeacon_Interact_tattr;
395 pthread_attr_t urecovery_Interact_tattr;
398 extern int rx_stackSize;
402 struct rx_securityClass *secClass;
405 struct rx_service *tservice;
407 initialize_U_error_table();
409 tdb = calloc(1, sizeof(*tdb));
410 tdb->pathName = strdup(pathName);
411 #ifdef AFS_PTHREAD_ENV
412 opr_mutex_init(&tdb->versionLock);
413 opr_mutex_init(&beacon_globals.beacon_lock);
414 opr_mutex_init(&vote_globals.vote_lock);
415 opr_mutex_init(&addr_globals.addr_lock);
416 opr_mutex_init(&version_globals.version_lock);
418 Lock_Init(&tdb->versionLock);
420 Lock_Init(&tdb->cache_lock);
421 tdb->read = uphys_read;
422 tdb->write = uphys_write;
423 tdb->truncate = uphys_truncate;
424 tdb->open = uphys_invalidate; /* this function isn't used any more */
425 tdb->sync = uphys_sync;
426 tdb->stat = uphys_stat;
427 tdb->getlabel = uphys_getlabel;
428 tdb->setlabel = uphys_setlabel;
429 tdb->getnfiles = uphys_getnfiles;
430 tdb->buffered_append = uphys_buf_append;
432 ubik_dbase = tdb; /* for now, only one db per server; can fix later when we have names for the other dbases */
434 #ifdef AFS_PTHREAD_ENV
435 opr_cv_init(&tdb->flags_cond);
436 #endif /* AFS_PTHREAD_ENV */
440 /* the following call is idempotent so when/if it got called earlier,
441 * by whatever called us, it doesn't really matter -- klm */
442 code = rx_Init(myPort);
446 ubik_callPortal = myPort;
448 udisk_Init(ubik_nBuffers);
454 code = urecovery_Initialize(tdb);
458 code = ubeacon_InitServerListByInfo(myHost, info, clones);
460 code = ubeacon_InitServerList(myHost, serverList);
464 /* try to get an additional security object */
465 if (buildSecClassesProc == NULL) {
467 ubik_sc = calloc(numClasses, sizeof(struct rx_securityClass *));
468 ubik_sc[0] = rxnull_NewServerSecurityObject();
469 if (ubik_SRXSecurityProc) {
470 code = (*ubik_SRXSecurityProc) (ubik_SRXSecurityRock,
474 ubik_sc[secIndex] = secClass;
478 (*buildSecClassesProc) (securityRock, &ubik_sc, &numClasses);
480 /* for backwards compat this should keep working as it does now
484 rx_NewService(0, VOTE_SERVICE_ID, "VOTE", ubik_sc, numClasses,
485 VOTE_ExecuteRequest);
486 if (tservice == (struct rx_service *)0) {
487 ViceLog(0, ("Could not create VOTE rx service!\n"));
490 rx_SetMinProcs(tservice, 2);
491 rx_SetMaxProcs(tservice, 3);
494 rx_NewService(0, DISK_SERVICE_ID, "DISK", ubik_sc, numClasses,
495 DISK_ExecuteRequest);
496 if (tservice == (struct rx_service *)0) {
497 ViceLog(0, ("Could not create DISK rx service!\n"));
500 rx_SetMinProcs(tservice, 2);
501 rx_SetMaxProcs(tservice, 3);
503 /* start an rx_ServerProc to handle incoming RPC's in particular the
504 * UpdateInterfaceAddr RPC that occurs in ubeacon_InitServerList. This avoids
505 * the "steplock" problem in ubik initialization. Defect 11037.
507 #ifdef AFS_PTHREAD_ENV
508 ubik_thread_create(&rxServer_tattr, &rxServerThread, (void *)rx_ServerProc);
510 LWP_CreateProcess(rx_ServerProc, rx_stackSize, RX_PROCESS_PRIORITY,
511 NULL, "rx_ServerProc", &junk);
514 /* send addrs to all other servers */
515 code = ubeacon_updateUbikNetworkAddress(ubik_host);
519 /* now start up async processes */
520 #ifdef AFS_PTHREAD_ENV
521 ubik_thread_create(&ubeacon_Interact_tattr, &ubeacon_InteractThread,
522 (void *)ubeacon_Interact);
524 code = LWP_CreateProcess(ubeacon_Interact, 16384 /*8192 */ ,
525 LWP_MAX_PRIORITY - 1, (void *)0, "beacon",
531 #ifdef AFS_PTHREAD_ENV
532 ubik_thread_create(&urecovery_Interact_tattr, &urecovery_InteractThread,
533 (void *)urecovery_Interact);
534 return 0; /* is this correct? - klm */
536 code = LWP_CreateProcess(urecovery_Interact, 16384 /*8192 */ ,
537 LWP_MAX_PRIORITY - 1, (void *)0, "recovery",
545 * \see ubik_ServerInitCommon()
548 ubik_ServerInitByInfo(afs_uint32 myHost, short myPort,
549 struct afsconf_cell *info, char clones[],
550 const char *pathName, struct ubik_dbase **dbase)
555 ubik_ServerInitCommon(myHost, myPort, info, clones, 0, pathName,
561 * \see ubik_ServerInitCommon()
564 ubik_ServerInit(afs_uint32 myHost, short myPort, afs_uint32 serverList[],
565 const char *pathName, struct ubik_dbase **dbase)
570 ubik_ServerInitCommon(myHost, myPort, (struct afsconf_cell *)0, 0,
571 serverList, pathName, dbase);
576 * \brief This routine begins a read or write transaction on the transaction
577 * identified by transPtr, in the dbase named by dbase.
579 * An open mode of ubik_READTRANS identifies this as a read transaction,
580 * while a mode of ubik_WRITETRANS identifies this as a write transaction.
581 * transPtr is set to the returned transaction control block.
582 * The readAny flag is set to 0 or 1 or 2 by the wrapper functions
583 * ubik_BeginTrans() or ubik_BeginTransReadAny() or
584 * ubik_BeginTransReadAnyWrite() below.
586 * \note We can only begin transaction when we have an up-to-date database.
589 BeginTrans(struct ubik_dbase *dbase, afs_int32 transMode,
590 struct ubik_trans **transPtr, int readAny)
592 struct ubik_trans *jt;
593 struct ubik_trans *tt;
596 if (readAny > 1 && ubik_SyncWriterCacheProc == NULL) {
597 /* it's not safe to use ubik_BeginTransReadAnyWrite without a
598 * cache-syncing function; fall back to ubik_BeginTransReadAny,
599 * which is safe but slower */
600 ViceLog(0, ("ubik_BeginTransReadAnyWrite called, but "
601 "ubik_SyncWriterCacheProc not set; pretending "
602 "ubik_BeginTransReadAny was called instead\n"));
606 if ((transMode != UBIK_READTRANS) && readAny)
609 if (urecovery_AllBetter(dbase, readAny) == 0) {
613 /* otherwise we have a quorum, use it */
615 /* make sure that at most one write transaction occurs at any one time. This
616 * has nothing to do with transaction locking; that's enforced by the lock package. However,
617 * we can't even handle two non-conflicting writes, since our log and recovery modules
618 * don't know how to restore one without possibly picking up some data from the other. */
619 if (transMode == UBIK_WRITETRANS) {
620 /* if we're writing already, wait */
621 while (dbase->flags & DBWRITING) {
622 #ifdef AFS_PTHREAD_ENV
623 opr_cv_wait(&dbase->flags_cond, &dbase->versionLock);
626 LWP_WaitProcess(&dbase->flags);
631 if (!ubeacon_AmSyncSite()) {
635 if (!ubeacon_SyncSiteAdvertised()) {
636 /* i am the sync-site but the remotes are not aware yet */
642 /* create the transaction */
643 code = udisk_begin(dbase, transMode, &jt); /* can't take address of register var */
644 tt = jt; /* move to a register */
645 if (code || tt == NULL) {
651 tt->flags |= TRREADANY;
653 tt->flags |= TRREADWRITE;
656 /* label trans and dbase with new tid */
657 tt->tid.epoch = version_globals.ubik_epochTime;
658 /* bump by two, since tidCounter+1 means trans id'd by tidCounter has finished */
659 tt->tid.counter = (dbase->tidCounter += 2);
661 if (transMode == UBIK_WRITETRANS) {
662 /* for a write trans, we have to keep track of the write tid counter too */
663 dbase->writeTidCounter = tt->tid.counter;
668 if (transMode == UBIK_WRITETRANS) {
669 /* next try to start transaction on appropriate number of machines */
670 code = ContactQuorum_NoArguments(DISK_Begin, tt, CCheckSyncAdvertised, "DISK_Begin");
672 /* we must abort the operation */
674 /* force aborts to the others */
675 ContactQuorum_NoArguments(DISK_Abort, tt, 0, "DISK_Abort");
691 ubik_BeginTrans(struct ubik_dbase *dbase, afs_int32 transMode,
692 struct ubik_trans **transPtr)
694 return BeginTrans(dbase, transMode, transPtr, 0);
701 ubik_BeginTransReadAny(struct ubik_dbase *dbase, afs_int32 transMode,
702 struct ubik_trans **transPtr)
704 return BeginTrans(dbase, transMode, transPtr, 1);
711 ubik_BeginTransReadAnyWrite(struct ubik_dbase *dbase, afs_int32 transMode,
712 struct ubik_trans **transPtr)
714 return BeginTrans(dbase, transMode, transPtr, 2);
718 * \brief This routine ends a read or write transaction by aborting it.
721 ubik_AbortTrans(struct ubik_trans *transPtr)
725 struct ubik_dbase *dbase;
727 dbase = transPtr->dbase;
729 if (transPtr->flags & TRCACHELOCKED) {
730 ReleaseReadLock(&dbase->cache_lock);
731 transPtr->flags &= ~TRCACHELOCKED;
734 ObtainWriteLock(&dbase->cache_lock);
737 memset(&dbase->cachedVersion, 0, sizeof(struct ubik_version));
739 ReleaseWriteLock(&dbase->cache_lock);
741 /* see if we're still up-to-date */
742 if (!urecovery_AllBetter(dbase, transPtr->flags & TRREADANY)) {
743 udisk_abort(transPtr);
749 if (transPtr->type == UBIK_READTRANS) {
750 code = udisk_abort(transPtr);
756 /* below here, we know we're doing a write transaction */
757 if (!ubeacon_AmSyncSite()) {
758 udisk_abort(transPtr);
764 /* now it is safe to try remote abort */
765 code = ContactQuorum_NoArguments(DISK_Abort, transPtr, 0, "DISK_Abort");
766 code2 = udisk_abort(transPtr);
769 return (code ? code : code2);
773 WritebackApplicationCache(struct ubik_dbase *dbase)
776 if (ubik_SyncWriterCacheProc) {
777 code = ubik_SyncWriterCacheProc();
780 /* we failed to sync the local cache, so just invalidate the cache;
781 * we'll try to read the cache in again on the next read */
782 memset(&dbase->cachedVersion, 0, sizeof(dbase->cachedVersion));
784 memcpy(&dbase->cachedVersion, &dbase->version,
785 sizeof(dbase->cachedVersion));
790 * \brief This routine ends a read or write transaction on the open transaction identified by transPtr.
791 * \return an error code.
794 ubik_EndTrans(struct ubik_trans *transPtr)
799 struct ubik_server *ts;
802 struct ubik_dbase *dbase;
804 if (transPtr->type == UBIK_WRITETRANS) {
805 code = ubik_Flush(transPtr);
807 ubik_AbortTrans(transPtr);
812 dbase = transPtr->dbase;
814 if (transPtr->flags & TRCACHELOCKED) {
815 ReleaseReadLock(&dbase->cache_lock);
816 transPtr->flags &= ~TRCACHELOCKED;
819 if (transPtr->type != UBIK_READTRANS) {
820 /* must hold cache_lock before DBHOLD'ing */
821 ObtainWriteLock(&dbase->cache_lock);
827 /* give up if no longer current */
828 if (!urecovery_AllBetter(dbase, transPtr->flags & TRREADANY)) {
829 udisk_abort(transPtr);
836 if (transPtr->type == UBIK_READTRANS) { /* reads are easy */
837 code = udisk_commit(transPtr);
839 goto success; /* update cachedVersion correctly */
845 if (!ubeacon_AmSyncSite()) { /* no longer sync site */
846 udisk_abort(transPtr);
853 /* now it is safe to do commit */
854 code = udisk_commit(transPtr);
856 /* db data has been committed locally; update the local cache so
857 * readers can get at it */
858 WritebackApplicationCache(dbase);
860 ReleaseWriteLock(&dbase->cache_lock);
862 code = ContactQuorum_NoArguments(DISK_Commit, transPtr, CStampVersion, "DISK_Commit");
865 memset(&dbase->cachedVersion, 0, sizeof(struct ubik_version));
866 ReleaseWriteLock(&dbase->cache_lock);
870 /* failed to commit, so must return failure. Try to clear locks first, just for fun
871 * Note that we don't know if this transaction will eventually commit at this point.
872 * If it made it to a site that will be present in the next quorum, we win, otherwise
873 * we lose. If we contact a majority of sites, then we won't be here: contacting
874 * a majority guarantees commit, since it guarantees that one dude will be a
875 * member of the next quorum. */
876 ContactQuorum_NoArguments(DISK_ReleaseLocks, transPtr, 0, "DISK_ReleaseLocks");
881 /* before we can start sending unlock messages, we must wait until all servers
882 * that are possibly still functioning on the other side of a network partition
883 * have timed out. Check the server structures, compute how long to wait, then
884 * start the unlocks */
885 realStart = FT_ApproxTime();
887 /* wait for all servers to time out */
889 now = FT_ApproxTime();
890 /* check if we're still sync site, the guy should either come up
891 * to us, or timeout. Put safety check in anyway */
892 if (now - realStart > 10 * BIGTIME) {
893 ubik_stats.escapes++;
894 ViceLog(0, ("ubik escaping from commit wait\n"));
897 for (ts = ubik_servers; ts; ts = ts->next) {
899 if (!ts->beaconSinceDown && now <= ts->lastBeaconSent + BIGTIME) {
902 /* this guy could have some damaged data, wait for him */
904 tv.tv_sec = 1; /* try again after a while (ha ha) */
907 #ifdef AFS_PTHREAD_ENV
908 /* we could release the dbase outside of the loop, but we do
909 * it here, in the loop, to avoid an unnecessary RELE/HOLD
910 * if all sites are up */
912 select(0, 0, 0, 0, &tv);
915 IOMGR_Select(0, 0, 0, 0, &tv); /* poll, should we wait on something? */
923 break; /* no down ones still pseudo-active */
926 /* finally, unlock all the dudes. We can return success independent of the number of servers
927 * that really unlock the dbase; the others will do it if/when they elect a new sync site.
928 * The transaction is committed anyway, since we succeeded in contacting a quorum
929 * at the start (when invoking the DiskCommit function).
931 ContactQuorum_NoArguments(DISK_ReleaseLocks, transPtr, 0, "DISK_ReleaseLocks");
935 /* don't update cachedVersion here; it should have been updated way back
936 * in ubik_CheckCache, and earlier in this function for writes */
939 ReleaseWriteLock(&dbase->cache_lock);
945 ObtainWriteLock(&dbase->cache_lock);
947 memset(&dbase->cachedVersion, 0, sizeof(struct ubik_version));
948 ReleaseWriteLock(&dbase->cache_lock);
953 * \brief This routine reads length bytes into buffer from the current position in the database.
955 * 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.
957 * \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.
960 ubik_Read(struct ubik_trans *transPtr, void *buffer,
965 /* reads are easy to do: handle locally */
966 DBHOLD(transPtr->dbase);
967 if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY)) {
968 DBRELE(transPtr->dbase);
973 udisk_read(transPtr, transPtr->seekFile, buffer, transPtr->seekPos,
976 transPtr->seekPos += length;
978 DBRELE(transPtr->dbase);
983 * \brief This routine will flush the io data in the iovec structures.
985 * It first flushes to the local disk and then uses ContactQuorum to write it
986 * to the other servers.
989 ubik_Flush(struct ubik_trans *transPtr)
991 afs_int32 code, error = 0;
993 if (transPtr->type != UBIK_WRITETRANS)
996 DBHOLD(transPtr->dbase);
997 if (!transPtr->iovec_info.iovec_wrt_len
998 || !transPtr->iovec_info.iovec_wrt_val) {
999 DBRELE(transPtr->dbase);
1003 if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY))
1004 ERROR_EXIT(UNOQUORUM);
1005 if (!ubeacon_AmSyncSite()) /* only sync site can write */
1006 ERROR_EXIT(UNOTSYNC);
1008 /* Update the rest of the servers in the quorum */
1010 ContactQuorum_DISK_WriteV(transPtr, 0, &transPtr->iovec_info,
1011 &transPtr->iovec_data);
1013 udisk_abort(transPtr);
1014 /* force aborts to the others */
1015 ContactQuorum_NoArguments(DISK_Abort, transPtr, 0, "DISK_Abort");
1016 transPtr->iovec_info.iovec_wrt_len = 0;
1017 transPtr->iovec_data.iovec_buf_len = 0;
1021 /* Wrote the buffers out, so start at scratch again */
1022 transPtr->iovec_info.iovec_wrt_len = 0;
1023 transPtr->iovec_data.iovec_buf_len = 0;
1026 DBRELE(transPtr->dbase);
1031 ubik_Write(struct ubik_trans *transPtr, void *vbuffer,
1034 struct ubik_iovec *iovec;
1035 afs_int32 code, error = 0;
1036 afs_int32 pos, len, size;
1037 char * buffer = (char *)vbuffer;
1039 if (transPtr->type != UBIK_WRITETRANS)
1044 if (length > IOVEC_MAXBUF) {
1045 for (pos = 0, len = length; len > 0; len -= size, pos += size) {
1046 size = ((len < IOVEC_MAXBUF) ? len : IOVEC_MAXBUF);
1047 code = ubik_Write(transPtr, buffer+pos, size);
1054 DBHOLD(transPtr->dbase);
1055 if (!transPtr->iovec_info.iovec_wrt_val) {
1056 transPtr->iovec_info.iovec_wrt_len = 0;
1057 transPtr->iovec_info.iovec_wrt_val =
1058 malloc(IOVEC_MAXWRT * sizeof(struct ubik_iovec));
1059 transPtr->iovec_data.iovec_buf_len = 0;
1060 transPtr->iovec_data.iovec_buf_val = malloc(IOVEC_MAXBUF);
1061 if (!transPtr->iovec_info.iovec_wrt_val
1062 || !transPtr->iovec_data.iovec_buf_val) {
1063 if (transPtr->iovec_info.iovec_wrt_val)
1064 free(transPtr->iovec_info.iovec_wrt_val);
1065 transPtr->iovec_info.iovec_wrt_val = 0;
1066 if (transPtr->iovec_data.iovec_buf_val)
1067 free(transPtr->iovec_data.iovec_buf_val);
1068 transPtr->iovec_data.iovec_buf_val = 0;
1069 DBRELE(transPtr->dbase);
1074 /* If this write won't fit in the structure, then flush it out and start anew */
1075 if ((transPtr->iovec_info.iovec_wrt_len >= IOVEC_MAXWRT)
1076 || ((length + transPtr->iovec_data.iovec_buf_len) > IOVEC_MAXBUF)) {
1077 /* Can't hold the DB lock over ubik_Flush */
1078 DBRELE(transPtr->dbase);
1079 code = ubik_Flush(transPtr);
1082 DBHOLD(transPtr->dbase);
1085 if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY))
1086 ERROR_EXIT(UNOQUORUM);
1087 if (!ubeacon_AmSyncSite()) /* only sync site can write */
1088 ERROR_EXIT(UNOTSYNC);
1090 /* Write to the local disk */
1092 udisk_write(transPtr, transPtr->seekFile, buffer, transPtr->seekPos,
1095 udisk_abort(transPtr);
1096 transPtr->iovec_info.iovec_wrt_len = 0;
1097 transPtr->iovec_data.iovec_buf_len = 0;
1098 DBRELE(transPtr->dbase);
1102 /* Collect writes for the other ubik servers (to be done in bulk) */
1103 iovec = (struct ubik_iovec *)transPtr->iovec_info.iovec_wrt_val;
1104 iovec[transPtr->iovec_info.iovec_wrt_len].file = transPtr->seekFile;
1105 iovec[transPtr->iovec_info.iovec_wrt_len].position = transPtr->seekPos;
1106 iovec[transPtr->iovec_info.iovec_wrt_len].length = length;
1108 memcpy(&transPtr->iovec_data.
1109 iovec_buf_val[transPtr->iovec_data.iovec_buf_len], buffer, length);
1111 transPtr->iovec_info.iovec_wrt_len++;
1112 transPtr->iovec_data.iovec_buf_len += length;
1113 transPtr->seekPos += length;
1116 DBRELE(transPtr->dbase);
1121 * \brief This sets the file pointer associated with the current transaction
1122 * to the appropriate file and byte position.
1124 * Unlike Unix files, a transaction is labelled by both a file number \p fileid
1125 * and a byte position relative to the specified file \p position.
1128 ubik_Seek(struct ubik_trans *transPtr, afs_int32 fileid,
1133 DBHOLD(transPtr->dbase);
1134 if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY)) {
1137 transPtr->seekFile = fileid;
1138 transPtr->seekPos = position;
1141 DBRELE(transPtr->dbase);
1146 * \brief This call returns the file pointer associated with the specified
1147 * transaction in \p fileid and \p position.
1150 ubik_Tell(struct ubik_trans *transPtr, afs_int32 * fileid,
1151 afs_int32 * position)
1153 DBHOLD(transPtr->dbase);
1154 *fileid = transPtr->seekFile;
1155 *position = transPtr->seekPos;
1156 DBRELE(transPtr->dbase);
1161 * \brief This sets the file size for the currently-selected file to \p length
1162 * bytes, if length is less than the file's current size.
1165 ubik_Truncate(struct ubik_trans *transPtr, afs_int32 length)
1167 afs_int32 code, error = 0;
1169 /* Will also catch if not UBIK_WRITETRANS */
1170 code = ubik_Flush(transPtr);
1174 DBHOLD(transPtr->dbase);
1175 /* first, check that quorum is still good, and that dbase is up-to-date */
1176 if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY))
1177 ERROR_EXIT(UNOQUORUM);
1178 if (!ubeacon_AmSyncSite())
1179 ERROR_EXIT(UNOTSYNC);
1181 /* now do the operation locally, and propagate it out */
1182 code = udisk_truncate(transPtr, transPtr->seekFile, length);
1185 ContactQuorum_DISK_Truncate(transPtr, 0, transPtr->seekFile,
1189 /* we must abort the operation */
1190 udisk_abort(transPtr);
1191 /* force aborts to the others */
1192 ContactQuorum_NoArguments(DISK_Abort, transPtr, 0, "DISK_Abort");
1197 DBRELE(transPtr->dbase);
1202 * \brief set a lock; all locks are released on transaction end (commit/abort)
1205 ubik_SetLock(struct ubik_trans *atrans, afs_int32 apos, afs_int32 alen,
1208 afs_int32 code = 0, error = 0;
1210 if (atype == LOCKWRITE) {
1211 if (atrans->type == UBIK_READTRANS)
1213 code = ubik_Flush(atrans);
1218 DBHOLD(atrans->dbase);
1219 if (atype == LOCKREAD) {
1220 code = ulock_getLock(atrans, atype, 1);
1224 /* first, check that quorum is still good, and that dbase is up-to-date */
1225 if (!urecovery_AllBetter(atrans->dbase, atrans->flags & TRREADANY))
1226 ERROR_EXIT(UNOQUORUM);
1227 if (!ubeacon_AmSyncSite())
1228 ERROR_EXIT(UNOTSYNC);
1230 /* now do the operation locally, and propagate it out */
1231 code = ulock_getLock(atrans, atype, 1);
1233 code = ContactQuorum_DISK_Lock(atrans, 0, 0, 1 /*unused */ ,
1234 1 /*unused */ , LOCKWRITE);
1237 /* we must abort the operation */
1238 udisk_abort(atrans);
1239 /* force aborts to the others */
1240 ContactQuorum_NoArguments(DISK_Abort, atrans, 0, "DISK_Abort");
1246 DBRELE(atrans->dbase);
1251 * \brief Facility to simplify database caching.
1252 * \return zero if last trans was done on the local server and was successful.
1253 * \return -1 means bad (NULL) argument.
1255 * If return value is non-zero and the caller is a server caching part of the
1256 * Ubik database, it should invalidate that cache.
1259 ubik_CacheUpdate(struct ubik_trans *atrans)
1261 if (!(atrans && atrans->dbase))
1263 return vcmp(atrans->dbase->cachedVersion, atrans->dbase->version) != 0;
1267 * check and possibly update cache of ubik db.
1269 * If the version of the cached db data is out of date, this calls (*check) to
1270 * update the cache. If (*check) returns success, we update the version of the
1273 * Checking the version of the cached db data is done under a read lock;
1274 * updating the cache (and thus calling (*check)) is done under a write lock
1275 * so is guaranteed not to interfere with another thread's (*check). On
1276 * successful return, a read lock on the cached db data is obtained, which
1277 * will be released by ubik_EndTrans or ubik_AbortTrans.
1279 * @param[in] atrans ubik transaction
1280 * @param[in] check function to call to check/update cache
1281 * @param[in] rock rock to pass to *check
1283 * @return operation status
1285 * @retval nonzero error; cachedVersion not updated
1287 * @post On success, application cache is read-locked, and cache data is
1291 ubik_CheckCache(struct ubik_trans *atrans, ubik_updatecache_func cbf, void *rock)
1295 if (!(atrans && atrans->dbase))
1298 ObtainReadLock(&atrans->dbase->cache_lock);
1300 while (ubik_CacheUpdate(atrans) != 0) {
1302 ReleaseReadLock(&atrans->dbase->cache_lock);
1303 ObtainSharedLock(&atrans->dbase->cache_lock);
1305 if (ubik_CacheUpdate(atrans) != 0) {
1307 BoostSharedLock(&atrans->dbase->cache_lock);
1309 ret = (*cbf) (atrans, rock);
1311 memcpy(&atrans->dbase->cachedVersion, &atrans->dbase->version,
1312 sizeof(atrans->dbase->cachedVersion));
1316 /* It would be nice if we could convert from a shared lock to a read
1317 * lock... instead, just release the shared and acquire the read */
1318 ReleaseSharedLock(&atrans->dbase->cache_lock);
1321 /* if we have an error, don't retry, and don't hold any locks */
1325 ObtainReadLock(&atrans->dbase->cache_lock);
1328 atrans->flags |= TRCACHELOCKED;
1334 * "Who said anything about panicking?" snapped Arthur.
1335 * "This is still just the culture shock. You wait till I've settled down
1336 * into the situation and found my bearings. \em Then I'll start panicking!"
1339 * \returns There is no return from panic.
1342 panic(char *format, ...)
1346 va_start(ap, format);
1347 ViceLog(0, ("Ubik PANIC:\n"));
1348 vViceLog(0, (format, ap));
1352 AFS_UNREACHED(ViceLog(0, ("BACK FROM ABORT\n")));
1353 AFS_UNREACHED(exit(1));
1357 * This function takes an IP addresses as its parameter. It returns the
1358 * the primary IP address that is on the host passed in, or 0 if not found.
1361 ubikGetPrimaryInterfaceAddr(afs_uint32 addr)
1363 struct ubik_server *ts;
1367 for (ts = ubik_servers; ts; ts = ts->next)
1368 for (j = 0; j < UBIK_MAX_INTERFACE_ADDR; j++)
1369 if (ts->addr[j] == addr) {
1371 return ts->addr[0]; /* net byte order */
1374 return 0; /* if not in server database, return error */
1378 ubik_CheckAuth(struct rx_call *acall)
1380 if (checkSecurityProc)
1381 return (*checkSecurityProc) (securityRock, acall);
1382 else if (ubik_CheckRXSecurityProc) {
1383 return (*ubik_CheckRXSecurityProc) (ubik_CheckRXSecurityRock, acall);
1389 ubik_SetServerSecurityProcs(void (*buildproc) (void *,
1390 struct rx_securityClass ***,
1392 int (*checkproc) (void *, struct rx_call *),
1395 buildSecClassesProc = buildproc;
1396 checkSecurityProc = checkproc;
1397 securityRock = rock;