ubik: Introduce new beacon lock
[openafs.git] / src / ubik / ubik.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  *
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 #include <afsconfig.h>
11 #include <afs/param.h>
12
13 #include <roken.h>
14
15 #include <lock.h>
16 #include <rx/xdr.h>
17 #include <rx/rx.h>
18 #include <afs/cellconfig.h>
19
20 #define UBIK_INTERNALS
21 #include "ubik.h"
22 #include "ubik_int.h"
23
24 #include <lwp.h>   /* temporary hack by klm */
25
26 #define ERROR_EXIT(code) do { \
27     error = (code); \
28     goto error_exit; \
29 } while (0)
30
31 /*!
32  * \file
33  * This system is organized in a hierarchical set of related modules.  Modules
34  * at one level can only call modules at the same level or below.
35  *
36  * At the bottom level (0) we have R, RFTP, LWP and IOMGR, i.e. the basic
37  * operating system primitives.
38  *
39  * At the next level (1) we have
40  *
41  * \li VOTER--The module responsible for casting votes when asked.  It is also
42  * responsible for determining whether this server should try to become
43  * a synchronization site.
44  * \li BEACONER--The module responsible for sending keep-alives out when a
45  * server is actually the sync site, or trying to become a sync site.
46  * \li DISK--The module responsible for representing atomic transactions
47  * on the local disk.  It maintains a new-value only log.
48  * \li LOCK--The module responsible for locking byte ranges in the database file.
49  *
50  * At the next level (2) we have
51  *
52  * \li RECOVERY--The module responsible for ensuring that all members of a quorum
53  * have the same up-to-date database after a new synchronization site is
54  * elected.  This module runs only on the synchronization site.
55  *
56  * At the next level (3) we have
57  *
58  * \li REMOTE--The module responsible for interpreting requests from the sync
59  * site and applying them to the database, after obtaining the appropriate
60  * locks.
61  *
62  * At the next level (4) we have
63  *
64  * \li UBIK--The module users call to perform operations on the database.
65  */
66
67
68 /* some globals */
69 afs_int32 ubik_quorum = 0;
70 struct ubik_dbase *ubik_dbase = 0;
71 struct ubik_stats ubik_stats;
72 afs_uint32 ubik_host[UBIK_MAX_INTERFACE_ADDR];
73 afs_int32 ubik_epochTime = 0;
74 afs_int32 urecovery_state = 0;
75 int (*ubik_SyncWriterCacheProc) (void);
76 struct ubik_server *ubik_servers;
77 short ubik_callPortal;
78
79 /* These global variables were used to control the server security layers.
80  * They are retained for backwards compatibility with legacy callers.
81  *
82  * The ubik_SetServerSecurityProcs() interface should be used instead.
83  */
84
85 int (*ubik_SRXSecurityProc) (void *, struct rx_securityClass **, afs_int32 *);
86 void *ubik_SRXSecurityRock;
87 int (*ubik_CheckRXSecurityProc) (void *, struct rx_call *);
88 void *ubik_CheckRXSecurityRock;
89
90
91
92 static int BeginTrans(struct ubik_dbase *dbase, afs_int32 transMode,
93                       struct ubik_trans **transPtr, int readAny);
94
95 static struct rx_securityClass **ubik_sc = NULL;
96 static void (*buildSecClassesProc)(void *, struct rx_securityClass ***,
97                                    afs_int32 *) = NULL;
98 static int (*checkSecurityProc)(void *, struct rx_call *) = NULL;
99 static void *securityRock = NULL;
100
101 #define CStampVersion       1   /* meaning set ts->version */
102
103 static_inline struct rx_connection *
104 Quorum_StartIO(struct ubik_trans *atrans, struct ubik_server *as)
105 {
106     struct rx_connection *conn;
107
108     conn = as->disk_rxcid;
109
110 #ifdef AFS_PTHREAD_ENV
111     rx_GetConnection(conn);
112     DBRELE(atrans->dbase);
113 #endif /* AFS_PTHREAD_ENV */
114
115     return conn;
116 }
117
118 static_inline void
119 Quorum_EndIO(struct ubik_trans *atrans, struct rx_connection *aconn)
120 {
121 #ifdef AFS_PTHREAD_ENV
122     DBHOLD(atrans->dbase);
123     rx_PutConnection(aconn);
124 #endif /* AFS_PTHREAD_ENV */
125 }
126
127
128 /*
129  * Iterate over all servers.  Callers pass in *ts which is used to track
130  * the current server.
131  * - Returns 1 if there are no more servers
132  * - Returns 0 with conn set to the connection for the current server if
133  *   it's up and current
134  */
135 static int
136 ContactQuorum_iterate(struct ubik_trans *atrans, int aflags, struct ubik_server **ts,
137                          struct rx_connection **conn, afs_int32 *rcode,
138                          afs_int32 *okcalls, afs_int32 code)
139 {
140     if (!*ts) {
141         /* Initial call - start iterating over servers */
142         *ts = ubik_servers;
143         *conn = NULL;
144         *rcode = 0;
145         *okcalls = 0;
146     } else {
147         if (*conn) {
148             Quorum_EndIO(atrans, *conn);
149             *conn = NULL;
150             if (code) {         /* failure */
151                 *rcode = code;
152                 UBIK_BEACON_LOCK;
153                 (*ts)->up = 0;          /* mark as down now; beacons will no longer be sent */
154                 (*ts)->beaconSinceDown = 0;
155                 UBIK_BEACON_UNLOCK;
156                 (*ts)->currentDB = 0;
157                 urecovery_LostServer(*ts);      /* tell recovery to try to resend dbase later */
158             } else {            /* success */
159                 if (!(*ts)->isClone)
160                     (*okcalls)++;       /* count up how many worked */
161                 if (aflags & CStampVersion) {
162                     (*ts)->version = atrans->dbase->version;
163                 }
164             }
165         }
166         *ts = (*ts)->next;
167     }
168     if (!(*ts))
169         return 1;
170     UBIK_BEACON_LOCK;
171     if (!(*ts)->up || !(*ts)->currentDB) {
172         UBIK_BEACON_UNLOCK;
173         (*ts)->currentDB = 0;   /* db is no longer current; we just missed an update */
174         return 0;               /* not up-to-date, don't bother.  NULL conn will tell caller not to use */
175     }
176     UBIK_BEACON_UNLOCK;
177     *conn = Quorum_StartIO(atrans, *ts);
178     return 0;
179 }
180
181 static int
182 ContactQuorum_rcode(int okcalls, afs_int32 rcode)
183 {
184     /*
185      * return 0 if we successfully contacted a quorum, otherwise return error code.
186      * We don't have to contact ourselves (that was done locally)
187      */
188     if (okcalls + 1 >= ubik_quorum)
189         return 0;
190     else
191         return rcode;
192 }
193
194 /*!
195  * \brief Perform an operation at a quorum, handling error conditions.
196  * \return 0 if all worked and a quorum was contacted successfully
197  * \return otherwise mark failing server as down and return #UERROR
198  *
199  * \note If any server misses an update, we must wait #BIGTIME seconds before
200  * allowing the transaction to commit, to ensure that the missing and
201  * possibly still functioning server times out and stops handing out old
202  * data.  This is done in the commit code, where we wait for a server marked
203  * down to have stayed down for #BIGTIME seconds before we allow a transaction
204  * to commit.  A server that fails but comes back up won't give out old data
205  * because it is sent the sync count along with the beacon message that
206  * marks it as \b really up (\p beaconSinceDown).
207  */
208 afs_int32
209 ContactQuorum_NoArguments(afs_int32 (*proc)(struct rx_connection *, ubik_tid *),
210                           struct ubik_trans *atrans, int aflags)
211 {
212     struct ubik_server *ts = NULL;
213     afs_int32 code = 0, rcode, okcalls;
214     struct rx_connection *conn;
215     int done;
216
217     done = ContactQuorum_iterate(atrans, aflags, &ts, &conn, &rcode, &okcalls, code);
218     while (!done) {
219         if (conn)
220             code = (*proc)(conn, &atrans->tid);
221         done = ContactQuorum_iterate(atrans, aflags, &ts, &conn, &rcode, &okcalls, code);
222     }
223     return ContactQuorum_rcode(okcalls, rcode);
224 }
225
226
227 afs_int32
228 ContactQuorum_DISK_Lock(struct ubik_trans *atrans, int aflags,afs_int32 file,
229                         afs_int32 position, afs_int32 length, afs_int32 type)
230 {
231     struct ubik_server *ts = NULL;
232     afs_int32 code = 0, rcode, okcalls;
233     struct rx_connection *conn;
234     int done;
235
236     done = ContactQuorum_iterate(atrans, aflags, &ts, &conn, &rcode, &okcalls, code);
237     while (!done) {
238         if (conn)
239             code = DISK_Lock(conn, &atrans->tid, file, position, length, type);
240         done = ContactQuorum_iterate(atrans, aflags, &ts, &conn, &rcode, &okcalls, code);
241     }
242     return ContactQuorum_rcode(okcalls, rcode);
243 }
244
245
246 afs_int32
247 ContactQuorum_DISK_Write(struct ubik_trans *atrans, int aflags,
248                          afs_int32 file, afs_int32 position, bulkdata *data)
249 {
250     struct ubik_server *ts = NULL;
251     afs_int32 code = 0, rcode, okcalls;
252     struct rx_connection *conn;
253     int done;
254
255     done = ContactQuorum_iterate(atrans, aflags, &ts, &conn, &rcode, &okcalls, code);
256     while (!done) {
257         if (conn)
258             code = DISK_Write(conn, &atrans->tid, file, position, data);
259         done = ContactQuorum_iterate(atrans, aflags, &ts, &conn, &rcode, &okcalls, code);
260     }
261     return ContactQuorum_rcode(okcalls, rcode);
262 }
263
264
265 afs_int32
266 ContactQuorum_DISK_Truncate(struct ubik_trans *atrans, int aflags,
267                             afs_int32 file, afs_int32 length)
268 {
269     struct ubik_server *ts = NULL;
270     afs_int32 code = 0, rcode, okcalls;
271     struct rx_connection *conn;
272     int done;
273
274     done = ContactQuorum_iterate(atrans, aflags, &ts, &conn, &rcode, &okcalls, code);
275     while (!done) {
276         if (conn)
277             code = DISK_Truncate(conn, &atrans->tid, file, length);
278         done = ContactQuorum_iterate(atrans, aflags, &ts, &conn, &rcode, &okcalls, code);
279     }
280     return ContactQuorum_rcode(okcalls, rcode);
281 }
282
283
284 afs_int32
285 ContactQuorum_DISK_WriteV(struct ubik_trans *atrans, int aflags,
286                           iovec_wrt * io_vector, iovec_buf *io_buffer)
287 {
288     struct ubik_server *ts = NULL;
289     afs_int32 code = 0, rcode, okcalls;
290     struct rx_connection *conn;
291     int done;
292
293     done = ContactQuorum_iterate(atrans, aflags, &ts, &conn, &rcode, &okcalls, code);
294     while (!done) {
295         if (conn) {
296             code = DISK_WriteV(conn, &atrans->tid, io_vector, io_buffer);
297             if ((code <= -450) && (code > -500)) {
298                 /* An RPC interface mismatch (as defined in comerr/error_msg.c).
299                  * Un-bulk the entries and do individual DISK_Write calls
300                  * instead of DISK_WriteV.
301                  */
302                 struct ubik_iovec *iovec =
303                         (struct ubik_iovec *)io_vector->iovec_wrt_val;
304                 char *iobuf = (char *)io_buffer->iovec_buf_val;
305                 bulkdata tcbs;
306                 afs_int32 i, offset;
307
308                 for (i = 0, offset = 0; i < io_vector->iovec_wrt_len; i++) {
309                     /* Sanity check for going off end of buffer */
310                     if ((offset + iovec[i].length) > io_buffer->iovec_buf_len) {
311                         code = UINTERNAL;
312                         break;
313                     }
314                     tcbs.bulkdata_len = iovec[i].length;
315                     tcbs.bulkdata_val = &iobuf[offset];
316                     code = DISK_Write(conn, &atrans->tid, iovec[i].file,
317                            iovec[i].position, &tcbs);
318                     if (code)
319                         break;
320                     offset += iovec[i].length;
321                 }
322             }
323         }
324         done = ContactQuorum_iterate(atrans, aflags, &ts, &conn, &rcode, &okcalls, code);
325     }
326     return ContactQuorum_rcode(okcalls, rcode);
327 }
328
329
330 afs_int32
331 ContactQuorum_DISK_SetVersion(struct ubik_trans *atrans, int aflags,
332                               ubik_version *OldVersion,
333                               ubik_version *NewVersion)
334 {
335     struct ubik_server *ts = NULL;
336     afs_int32 code = 0, rcode, okcalls;
337     struct rx_connection *conn;
338     int done;
339
340     done = ContactQuorum_iterate(atrans, aflags, &ts, &conn, &rcode, &okcalls, code);
341     while (!done) {
342         if (conn)
343             code = DISK_SetVersion(conn, &atrans->tid, OldVersion, NewVersion);
344         done = ContactQuorum_iterate(atrans, aflags, &ts, &conn, &rcode, &okcalls, code);
345     }
346     return ContactQuorum_rcode(okcalls, rcode);
347 }
348
349 #if defined(AFS_PTHREAD_ENV)
350 static int
351 ubik_thread_create(pthread_attr_t *tattr, pthread_t *thread, void *proc) {
352     osi_Assert(pthread_attr_init(tattr) == 0);
353     osi_Assert(pthread_attr_setdetachstate(tattr, PTHREAD_CREATE_DETACHED) == 0);
354     osi_Assert(pthread_create(thread, tattr, proc, NULL) == 0);
355     return 0;
356 }
357 #endif
358
359 /*!
360  * \brief This routine initializes the ubik system for a set of servers.
361  * \return 0 for success, or an error code on failure.
362  * \param serverList set of servers specified; nServers gives the number of entries in this array.
363  * \param pathName provides an initial prefix used for naming storage files used by this system.
364  * \param dbase the returned structure representing this instance of an ubik; it is passed to various calls below.
365  *
366  * \todo This routine should perhaps be generalized to a low-level disk interface providing read, write, file enumeration and sync operations.
367  *
368  * \warning The host named by myHost should not also be listed in serverList.
369  *
370  * \see ubik_ServerInit(), ubik_ServerInitByInfo()
371  */
372 int
373 ubik_ServerInitCommon(afs_uint32 myHost, short myPort,
374                       struct afsconf_cell *info, char clones[],
375                       afs_uint32 serverList[], const char *pathName,
376                       struct ubik_dbase **dbase)
377 {
378     struct ubik_dbase *tdb;
379     afs_int32 code;
380 #ifdef AFS_PTHREAD_ENV
381     pthread_t rxServerThread;        /* pthread variables */
382     pthread_t ubeacon_InteractThread;
383     pthread_t urecovery_InteractThread;
384     pthread_attr_t rxServer_tattr;
385     pthread_attr_t ubeacon_Interact_tattr;
386     pthread_attr_t urecovery_Interact_tattr;
387 #else
388     PROCESS junk;
389     extern int rx_stackSize;
390 #endif
391
392     afs_int32 secIndex;
393     struct rx_securityClass *secClass;
394     int numClasses;
395
396     struct rx_service *tservice;
397
398     initialize_U_error_table();
399
400     tdb = (struct ubik_dbase *)malloc(sizeof(struct ubik_dbase));
401     tdb->pathName = (char *)malloc(strlen(pathName) + 1);
402     strcpy(tdb->pathName, pathName);
403     tdb->activeTrans = (struct ubik_trans *)0;
404     memset(&tdb->version, 0, sizeof(struct ubik_version));
405     memset(&tdb->cachedVersion, 0, sizeof(struct ubik_version));
406 #ifdef AFS_PTHREAD_ENV
407     MUTEX_INIT(&tdb->versionLock, "version lock", MUTEX_DEFAULT, 0);
408     MUTEX_INIT(&beacon_globals.beacon_lock, "beacon lock", MUTEX_DEFAULT, 0);
409 #else
410     Lock_Init(&tdb->versionLock);
411 #endif
412     Lock_Init(&tdb->cache_lock);
413     tdb->flags = 0;
414     tdb->read = uphys_read;
415     tdb->write = uphys_write;
416     tdb->truncate = uphys_truncate;
417     tdb->open = uphys_invalidate;       /* this function isn't used any more */
418     tdb->sync = uphys_sync;
419     tdb->stat = uphys_stat;
420     tdb->getlabel = uphys_getlabel;
421     tdb->setlabel = uphys_setlabel;
422     tdb->getnfiles = uphys_getnfiles;
423     tdb->readers = 0;
424     tdb->tidCounter = tdb->writeTidCounter = 0;
425     *dbase = tdb;
426     ubik_dbase = tdb;           /* for now, only one db per server; can fix later when we have names for the other dbases */
427
428 #ifdef AFS_PTHREAD_ENV
429     CV_INIT(&tdb->version_cond, "version", CV_DEFAULT, 0);
430     CV_INIT(&tdb->flags_cond, "flags", CV_DEFAULT, 0);
431 #endif /* AFS_PTHREAD_ENV */
432
433     /* initialize RX */
434
435     /* the following call is idempotent so when/if it got called earlier,
436      * by whatever called us, it doesn't really matter -- klm */
437     code = rx_Init(myPort);
438     if (code < 0)
439         return code;
440
441     udisk_Init(ubik_nBuffers);
442     ulock_Init();
443
444     code = uvote_Init();
445     if (code)
446         return code;
447     code = urecovery_Initialize(tdb);
448     if (code)
449         return code;
450     if (info)
451         code = ubeacon_InitServerListByInfo(myHost, info, clones);
452     else
453         code = ubeacon_InitServerList(myHost, serverList);
454     if (code)
455         return code;
456
457     ubik_callPortal = myPort;
458     /* try to get an additional security object */
459     if (buildSecClassesProc == NULL) {
460         numClasses = 3;
461         ubik_sc = calloc(numClasses, sizeof(struct rx_securityClass *));
462         ubik_sc[0] = rxnull_NewServerSecurityObject();
463         if (ubik_SRXSecurityProc) {
464             code = (*ubik_SRXSecurityProc) (ubik_SRXSecurityRock,
465                                             &secClass,
466                                             &secIndex);
467             if (code == 0) {
468                  ubik_sc[secIndex] = secClass;
469             }
470         }
471     } else {
472         (*buildSecClassesProc) (securityRock, &ubik_sc, &numClasses);
473     }
474     /* for backwards compat this should keep working as it does now
475        and not host bind */
476
477     tservice =
478         rx_NewService(0, VOTE_SERVICE_ID, "VOTE", ubik_sc, numClasses,
479                       VOTE_ExecuteRequest);
480     if (tservice == (struct rx_service *)0) {
481         ubik_dprint("Could not create VOTE rx service!\n");
482         return -1;
483     }
484     rx_SetMinProcs(tservice, 2);
485     rx_SetMaxProcs(tservice, 3);
486
487     tservice =
488         rx_NewService(0, DISK_SERVICE_ID, "DISK", ubik_sc, numClasses,
489                       DISK_ExecuteRequest);
490     if (tservice == (struct rx_service *)0) {
491         ubik_dprint("Could not create DISK rx service!\n");
492         return -1;
493     }
494     rx_SetMinProcs(tservice, 2);
495     rx_SetMaxProcs(tservice, 3);
496
497     /* start an rx_ServerProc to handle incoming RPC's in particular the
498      * UpdateInterfaceAddr RPC that occurs in ubeacon_InitServerList. This avoids
499      * the "steplock" problem in ubik initialization. Defect 11037.
500      */
501 #ifdef AFS_PTHREAD_ENV
502     ubik_thread_create(&rxServer_tattr, &rxServerThread, (void *)rx_ServerProc);
503 #else
504     LWP_CreateProcess(rx_ServerProc, rx_stackSize, RX_PROCESS_PRIORITY,
505               NULL, "rx_ServerProc", &junk);
506 #endif
507
508     /* now start up async processes */
509 #ifdef AFS_PTHREAD_ENV
510     ubik_thread_create(&ubeacon_Interact_tattr, &ubeacon_InteractThread,
511                 (void *)ubeacon_Interact);
512 #else
513     code = LWP_CreateProcess(ubeacon_Interact, 16384 /*8192 */ ,
514                              LWP_MAX_PRIORITY - 1, (void *)0, "beacon",
515                              &junk);
516     if (code)
517         return code;
518 #endif
519
520 #ifdef AFS_PTHREAD_ENV
521     ubik_thread_create(&urecovery_Interact_tattr, &urecovery_InteractThread,
522                 (void *)urecovery_Interact);
523     return 0;  /* is this correct?  - klm */
524 #else
525     code = LWP_CreateProcess(urecovery_Interact, 16384 /*8192 */ ,
526                              LWP_MAX_PRIORITY - 1, (void *)0, "recovery",
527                              &junk);
528     return code;
529 #endif
530
531 }
532
533 /*!
534  * \see ubik_ServerInitCommon()
535  */
536 int
537 ubik_ServerInitByInfo(afs_uint32 myHost, short myPort,
538                       struct afsconf_cell *info, char clones[],
539                       const char *pathName, struct ubik_dbase **dbase)
540 {
541     afs_int32 code;
542
543     code =
544         ubik_ServerInitCommon(myHost, myPort, info, clones, 0, pathName,
545                               dbase);
546     return code;
547 }
548
549 /*!
550  * \see ubik_ServerInitCommon()
551  */
552 int
553 ubik_ServerInit(afs_uint32 myHost, short myPort, afs_uint32 serverList[],
554                 const char *pathName, struct ubik_dbase **dbase)
555 {
556     afs_int32 code;
557
558     code =
559         ubik_ServerInitCommon(myHost, myPort, (struct afsconf_cell *)0, 0,
560                               serverList, pathName, dbase);
561     return code;
562 }
563
564 /*!
565  * \brief This routine begins a read or write transaction on the transaction
566  * identified by transPtr, in the dbase named by dbase.
567  *
568  * An open mode of ubik_READTRANS identifies this as a read transaction,
569  * while a mode of ubik_WRITETRANS identifies this as a write transaction.
570  * transPtr is set to the returned transaction control block.
571  * The readAny flag is set to 0 or 1 or 2 by the wrapper functions
572  * ubik_BeginTrans() or ubik_BeginTransReadAny() or
573  * ubik_BeginTransReadAnyWrite() below.
574  *
575  * \note We can only begin transaction when we have an up-to-date database.
576  */
577 static int
578 BeginTrans(struct ubik_dbase *dbase, afs_int32 transMode,
579            struct ubik_trans **transPtr, int readAny)
580 {
581     struct ubik_trans *jt;
582     struct ubik_trans *tt;
583     afs_int32 code;
584
585     if (readAny > 1 && ubik_SyncWriterCacheProc == NULL) {
586         /* it's not safe to use ubik_BeginTransReadAnyWrite without a
587          * cache-syncing function; fall back to ubik_BeginTransReadAny,
588          * which is safe but slower */
589         ubik_print("ubik_BeginTransReadAnyWrite called, but "
590                    "ubik_SyncWriterCacheProc not set; pretending "
591                    "ubik_BeginTransReadAny was called instead\n");
592         readAny = 1;
593     }
594
595     if ((transMode != UBIK_READTRANS) && readAny)
596         return UBADTYPE;
597     DBHOLD(dbase);
598     if (urecovery_AllBetter(dbase, readAny) == 0) {
599         DBRELE(dbase);
600         return UNOQUORUM;
601     }
602     /* otherwise we have a quorum, use it */
603
604     /* make sure that at most one write transaction occurs at any one time.  This
605      * has nothing to do with transaction locking; that's enforced by the lock package.  However,
606      * we can't even handle two non-conflicting writes, since our log and recovery modules
607      * don't know how to restore one without possibly picking up some data from the other. */
608     if (transMode == UBIK_WRITETRANS) {
609         /* if we're writing already, wait */
610         while (dbase->flags & DBWRITING) {
611 #ifdef AFS_PTHREAD_ENV
612             CV_WAIT(&dbase->flags_cond, &dbase->versionLock);
613 #else
614             DBRELE(dbase);
615             LWP_WaitProcess(&dbase->flags);
616             DBHOLD(dbase);
617 #endif
618         }
619
620         if (!ubeacon_AmSyncSite()) {
621             DBRELE(dbase);
622             return UNOTSYNC;
623         }
624     }
625
626     /* create the transaction */
627     code = udisk_begin(dbase, transMode, &jt);  /* can't take address of register var */
628     tt = jt;                    /* move to a register */
629     if (code || tt == (struct ubik_trans *)NULL) {
630         DBRELE(dbase);
631         return code;
632     }
633     if (readAny) {
634         tt->flags |= TRREADANY;
635         if (readAny > 1) {
636             tt->flags |= TRREADWRITE;
637         }
638     }
639     /* label trans and dbase with new tid */
640     tt->tid.epoch = ubik_epochTime;
641     /* bump by two, since tidCounter+1 means trans id'd by tidCounter has finished */
642     tt->tid.counter = (dbase->tidCounter += 2);
643
644     if (transMode == UBIK_WRITETRANS) {
645         /* for a write trans, we have to keep track of the write tid counter too */
646         dbase->writeTidCounter = tt->tid.counter;
647
648         /* next try to start transaction on appropriate number of machines */
649         code = ContactQuorum_NoArguments(DISK_Begin, tt, 0);
650         if (code) {
651             /* we must abort the operation */
652             udisk_abort(tt);
653             ContactQuorum_NoArguments(DISK_Abort, tt, 0); /* force aborts to the others */
654             udisk_end(tt);
655             DBRELE(dbase);
656             return code;
657         }
658     }
659
660     *transPtr = tt;
661     DBRELE(dbase);
662     return 0;
663 }
664
665 /*!
666  * \see BeginTrans()
667  */
668 int
669 ubik_BeginTrans(struct ubik_dbase *dbase, afs_int32 transMode,
670                 struct ubik_trans **transPtr)
671 {
672     return BeginTrans(dbase, transMode, transPtr, 0);
673 }
674
675 /*!
676  * \see BeginTrans()
677  */
678 int
679 ubik_BeginTransReadAny(struct ubik_dbase *dbase, afs_int32 transMode,
680                        struct ubik_trans **transPtr)
681 {
682     return BeginTrans(dbase, transMode, transPtr, 1);
683 }
684
685 /*!
686  * \see BeginTrans()
687  */
688 int
689 ubik_BeginTransReadAnyWrite(struct ubik_dbase *dbase, afs_int32 transMode,
690                             struct ubik_trans **transPtr)
691 {
692     return BeginTrans(dbase, transMode, transPtr, 2);
693 }
694
695 /*!
696  * \brief This routine ends a read or write transaction by aborting it.
697  */
698 int
699 ubik_AbortTrans(struct ubik_trans *transPtr)
700 {
701     afs_int32 code;
702     afs_int32 code2;
703     struct ubik_dbase *dbase;
704
705     dbase = transPtr->dbase;
706
707     if (transPtr->flags & TRCACHELOCKED) {
708         ReleaseReadLock(&dbase->cache_lock);
709         transPtr->flags &= ~TRCACHELOCKED;
710     }
711
712     ObtainWriteLock(&dbase->cache_lock);
713
714     DBHOLD(dbase);
715     memset(&dbase->cachedVersion, 0, sizeof(struct ubik_version));
716
717     ReleaseWriteLock(&dbase->cache_lock);
718
719     /* see if we're still up-to-date */
720     if (!urecovery_AllBetter(dbase, transPtr->flags & TRREADANY)) {
721         udisk_abort(transPtr);
722         udisk_end(transPtr);
723         DBRELE(dbase);
724         return UNOQUORUM;
725     }
726
727     if (transPtr->type == UBIK_READTRANS) {
728         code = udisk_abort(transPtr);
729         udisk_end(transPtr);
730         DBRELE(dbase);
731         return code;
732     }
733
734     /* below here, we know we're doing a write transaction */
735     if (!ubeacon_AmSyncSite()) {
736         udisk_abort(transPtr);
737         udisk_end(transPtr);
738         DBRELE(dbase);
739         return UNOTSYNC;
740     }
741
742     /* now it is safe to try remote abort */
743     code = ContactQuorum_NoArguments(DISK_Abort, transPtr, 0);
744     code2 = udisk_abort(transPtr);
745     udisk_end(transPtr);
746     DBRELE(dbase);
747     return (code ? code : code2);
748 }
749
750 static void
751 WritebackApplicationCache(struct ubik_dbase *dbase)
752 {
753     int code = 0;
754     if (ubik_SyncWriterCacheProc) {
755         code = ubik_SyncWriterCacheProc();
756     }
757     if (code) {
758         /* we failed to sync the local cache, so just invalidate the cache;
759          * we'll try to read the cache in again on the next read */
760         memset(&dbase->cachedVersion, 0, sizeof(dbase->cachedVersion));
761     } else {
762         memcpy(&dbase->cachedVersion, &dbase->version,
763                sizeof(dbase->cachedVersion));
764     }
765 }
766
767 /*!
768  * \brief This routine ends a read or write transaction on the open transaction identified by transPtr.
769  * \return an error code.
770  */
771 int
772 ubik_EndTrans(struct ubik_trans *transPtr)
773 {
774     afs_int32 code;
775     struct timeval tv;
776     afs_int32 realStart;
777     struct ubik_server *ts;
778     afs_int32 now;
779     int cachelocked = 0;
780     struct ubik_dbase *dbase;
781
782     if (transPtr->type == UBIK_WRITETRANS) {
783         code = ubik_Flush(transPtr);
784         if (code) {
785             ubik_AbortTrans(transPtr);
786             return (code);
787         }
788     }
789
790     dbase = transPtr->dbase;
791
792     if (transPtr->flags & TRCACHELOCKED) {
793         ReleaseReadLock(&dbase->cache_lock);
794         transPtr->flags &= ~TRCACHELOCKED;
795     }
796
797     if (transPtr->type != UBIK_READTRANS) {
798         /* must hold cache_lock before DBHOLD'ing */
799         ObtainWriteLock(&dbase->cache_lock);
800         cachelocked = 1;
801     }
802
803     DBHOLD(dbase);
804
805     /* give up if no longer current */
806     if (!urecovery_AllBetter(dbase, transPtr->flags & TRREADANY)) {
807         udisk_abort(transPtr);
808         udisk_end(transPtr);
809         DBRELE(dbase);
810         code = UNOQUORUM;
811         goto error;
812     }
813
814     if (transPtr->type == UBIK_READTRANS) {     /* reads are easy */
815         code = udisk_commit(transPtr);
816         if (code == 0)
817             goto success;       /* update cachedVersion correctly */
818         udisk_end(transPtr);
819         DBRELE(dbase);
820         goto error;
821     }
822
823     if (!ubeacon_AmSyncSite()) {        /* no longer sync site */
824         udisk_abort(transPtr);
825         udisk_end(transPtr);
826         DBRELE(dbase);
827         code = UNOTSYNC;
828         goto error;
829     }
830
831     /* now it is safe to do commit */
832     code = udisk_commit(transPtr);
833     if (code == 0) {
834         /* db data has been committed locally; update the local cache so
835          * readers can get at it */
836         WritebackApplicationCache(dbase);
837
838         ReleaseWriteLock(&dbase->cache_lock);
839
840         code = ContactQuorum_NoArguments(DISK_Commit, transPtr, CStampVersion);
841
842     } else {
843         memset(&dbase->cachedVersion, 0, sizeof(struct ubik_version));
844         ReleaseWriteLock(&dbase->cache_lock);
845     }
846     cachelocked = 0;
847     if (code) {
848         /* failed to commit, so must return failure.  Try to clear locks first, just for fun
849          * Note that we don't know if this transaction will eventually commit at this point.
850          * If it made it to a site that will be present in the next quorum, we win, otherwise
851          * we lose.  If we contact a majority of sites, then we won't be here: contacting
852          * a majority guarantees commit, since it guarantees that one dude will be a
853          * member of the next quorum. */
854         ContactQuorum_NoArguments(DISK_ReleaseLocks, transPtr, 0);
855         udisk_end(transPtr);
856         DBRELE(dbase);
857         goto error;
858     }
859     /* before we can start sending unlock messages, we must wait until all servers
860      * that are possibly still functioning on the other side of a network partition
861      * have timed out.  Check the server structures, compute how long to wait, then
862      * start the unlocks */
863     realStart = FT_ApproxTime();
864     while (1) {
865         /* wait for all servers to time out */
866         code = 0;
867         now = FT_ApproxTime();
868         /* check if we're still sync site, the guy should either come up
869          * to us, or timeout.  Put safety check in anyway */
870         if (now - realStart > 10 * BIGTIME) {
871             ubik_stats.escapes++;
872             ubik_print("ubik escaping from commit wait\n");
873             break;
874         }
875         for (ts = ubik_servers; ts; ts = ts->next) {
876             UBIK_BEACON_LOCK;
877             if (!ts->beaconSinceDown && now <= ts->lastBeaconSent + BIGTIME) {
878                 UBIK_BEACON_UNLOCK;
879
880                 /* this guy could have some damaged data, wait for him */
881                 code = 1;
882                 tv.tv_sec = 1;  /* try again after a while (ha ha) */
883                 tv.tv_usec = 0;
884
885 #ifdef AFS_PTHREAD_ENV
886                 /* we could release the dbase outside of the loop, but we do
887                  * it here, in the loop, to avoid an unnecessary RELE/HOLD
888                  * if all sites are up */
889                 DBRELE(dbase);
890                 select(0, 0, 0, 0, &tv);
891                 DBHOLD(dbase);
892 #else
893                 IOMGR_Select(0, 0, 0, 0, &tv);  /* poll, should we wait on something? */
894 #endif
895
896                 break;
897             }
898             UBIK_BEACON_UNLOCK;
899         }
900         if (code == 0)
901             break;              /* no down ones still pseudo-active */
902     }
903
904     /* finally, unlock all the dudes.  We can return success independent of the number of servers
905      * that really unlock the dbase; the others will do it if/when they elect a new sync site.
906      * The transaction is committed anyway, since we succeeded in contacting a quorum
907      * at the start (when invoking the DiskCommit function).
908      */
909     ContactQuorum_NoArguments(DISK_ReleaseLocks, transPtr, 0);
910
911   success:
912     udisk_end(transPtr);
913     /* don't update cachedVersion here; it should have been updated way back
914      * in ubik_CheckCache, and earlier in this function for writes */
915     DBRELE(dbase);
916     if (cachelocked) {
917         ReleaseWriteLock(&dbase->cache_lock);
918     }
919     return 0;
920
921   error:
922     if (!cachelocked) {
923         ObtainWriteLock(&dbase->cache_lock);
924     }
925     memset(&dbase->cachedVersion, 0, sizeof(struct ubik_version));
926     ReleaseWriteLock(&dbase->cache_lock);
927     return code;
928 }
929
930 /*!
931  * \brief This routine reads length bytes into buffer from the current position in the database.
932  *
933  * 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.
934  *
935  * \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.
936  */
937 int
938 ubik_Read(struct ubik_trans *transPtr, void *buffer,
939           afs_int32 length)
940 {
941     afs_int32 code;
942
943     /* reads are easy to do: handle locally */
944     DBHOLD(transPtr->dbase);
945     if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY)) {
946         DBRELE(transPtr->dbase);
947         return UNOQUORUM;
948     }
949
950     code =
951         udisk_read(transPtr, transPtr->seekFile, buffer, transPtr->seekPos,
952                    length);
953     if (code == 0) {
954         transPtr->seekPos += length;
955     }
956     DBRELE(transPtr->dbase);
957     return code;
958 }
959
960 /*!
961  * \brief This routine will flush the io data in the iovec structures.
962  *
963  * It first flushes to the local disk and then uses ContactQuorum to write it
964  * to the other servers.
965  */
966 int
967 ubik_Flush(struct ubik_trans *transPtr)
968 {
969     afs_int32 code, error = 0;
970
971     if (transPtr->type != UBIK_WRITETRANS)
972         return UBADTYPE;
973     if (!transPtr->iovec_info.iovec_wrt_len
974         || !transPtr->iovec_info.iovec_wrt_val)
975         return 0;
976
977     DBHOLD(transPtr->dbase);
978     if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY))
979         ERROR_EXIT(UNOQUORUM);
980     if (!ubeacon_AmSyncSite())  /* only sync site can write */
981         ERROR_EXIT(UNOTSYNC);
982
983     /* Update the rest of the servers in the quorum */
984     code =
985         ContactQuorum_DISK_WriteV(transPtr, 0, &transPtr->iovec_info,
986                                   &transPtr->iovec_data);
987     if (code) {
988         udisk_abort(transPtr);
989         ContactQuorum_NoArguments(DISK_Abort, transPtr, 0); /* force aborts to the others */
990         transPtr->iovec_info.iovec_wrt_len = 0;
991         transPtr->iovec_data.iovec_buf_len = 0;
992         ERROR_EXIT(code);
993     }
994
995     /* Wrote the buffers out, so start at scratch again */
996     transPtr->iovec_info.iovec_wrt_len = 0;
997     transPtr->iovec_data.iovec_buf_len = 0;
998
999   error_exit:
1000     DBRELE(transPtr->dbase);
1001     return error;
1002 }
1003
1004 int
1005 ubik_Write(struct ubik_trans *transPtr, void *vbuffer,
1006            afs_int32 length)
1007 {
1008     struct ubik_iovec *iovec;
1009     afs_int32 code, error = 0;
1010     afs_int32 pos, len, size;
1011     char * buffer = (char *)vbuffer;
1012
1013     if (transPtr->type != UBIK_WRITETRANS)
1014         return UBADTYPE;
1015     if (!length)
1016         return 0;
1017
1018     if (length > IOVEC_MAXBUF) {
1019         for (pos = 0, len = length; len > 0; len -= size, pos += size) {
1020             size = ((len < IOVEC_MAXBUF) ? len : IOVEC_MAXBUF);
1021             code = ubik_Write(transPtr, buffer+pos, size);
1022             if (code)
1023                 return (code);
1024         }
1025         return 0;
1026     }
1027
1028     if (!transPtr->iovec_info.iovec_wrt_val) {
1029         transPtr->iovec_info.iovec_wrt_len = 0;
1030         transPtr->iovec_info.iovec_wrt_val =
1031             (struct ubik_iovec *)malloc(IOVEC_MAXWRT *
1032                                         sizeof(struct ubik_iovec));
1033         transPtr->iovec_data.iovec_buf_len = 0;
1034         transPtr->iovec_data.iovec_buf_val = (char *)malloc(IOVEC_MAXBUF);
1035         if (!transPtr->iovec_info.iovec_wrt_val
1036             || !transPtr->iovec_data.iovec_buf_val) {
1037             if (transPtr->iovec_info.iovec_wrt_val)
1038                 free(transPtr->iovec_info.iovec_wrt_val);
1039             transPtr->iovec_info.iovec_wrt_val = 0;
1040             if (transPtr->iovec_data.iovec_buf_val)
1041                 free(transPtr->iovec_data.iovec_buf_val);
1042             transPtr->iovec_data.iovec_buf_val = 0;
1043             return UNOMEM;
1044         }
1045     }
1046
1047     /* If this write won't fit in the structure, then flush it out and start anew */
1048     if ((transPtr->iovec_info.iovec_wrt_len >= IOVEC_MAXWRT)
1049         || ((length + transPtr->iovec_data.iovec_buf_len) > IOVEC_MAXBUF)) {
1050         code = ubik_Flush(transPtr);
1051         if (code)
1052             return (code);
1053     }
1054
1055     DBHOLD(transPtr->dbase);
1056     if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY))
1057         ERROR_EXIT(UNOQUORUM);
1058     if (!ubeacon_AmSyncSite())  /* only sync site can write */
1059         ERROR_EXIT(UNOTSYNC);
1060
1061     /* Write to the local disk */
1062     code =
1063         udisk_write(transPtr, transPtr->seekFile, buffer, transPtr->seekPos,
1064                     length);
1065     if (code) {
1066         udisk_abort(transPtr);
1067         transPtr->iovec_info.iovec_wrt_len = 0;
1068         transPtr->iovec_data.iovec_buf_len = 0;
1069         DBRELE(transPtr->dbase);
1070         return (code);
1071     }
1072
1073     /* Collect writes for the other ubik servers (to be done in bulk) */
1074     iovec = (struct ubik_iovec *)transPtr->iovec_info.iovec_wrt_val;
1075     iovec[transPtr->iovec_info.iovec_wrt_len].file = transPtr->seekFile;
1076     iovec[transPtr->iovec_info.iovec_wrt_len].position = transPtr->seekPos;
1077     iovec[transPtr->iovec_info.iovec_wrt_len].length = length;
1078
1079     memcpy(&transPtr->iovec_data.
1080            iovec_buf_val[transPtr->iovec_data.iovec_buf_len], buffer, length);
1081
1082     transPtr->iovec_info.iovec_wrt_len++;
1083     transPtr->iovec_data.iovec_buf_len += length;
1084     transPtr->seekPos += length;
1085
1086   error_exit:
1087     DBRELE(transPtr->dbase);
1088     return error;
1089 }
1090
1091 /*!
1092  * \brief This sets the file pointer associated with the current transaction
1093  * to the appropriate file and byte position.
1094  *
1095  * Unlike Unix files, a transaction is labelled by both a file number \p fileid
1096  * and a byte position relative to the specified file \p position.
1097  */
1098 int
1099 ubik_Seek(struct ubik_trans *transPtr, afs_int32 fileid,
1100           afs_int32 position)
1101 {
1102     afs_int32 code;
1103
1104     DBHOLD(transPtr->dbase);
1105     if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY)) {
1106         code = UNOQUORUM;
1107     } else {
1108         transPtr->seekFile = fileid;
1109         transPtr->seekPos = position;
1110         code = 0;
1111     }
1112     DBRELE(transPtr->dbase);
1113     return code;
1114 }
1115
1116 /*!
1117  * \brief This call returns the file pointer associated with the specified
1118  * transaction in \p fileid and \p position.
1119  */
1120 int
1121 ubik_Tell(struct ubik_trans *transPtr, afs_int32 * fileid,
1122           afs_int32 * position)
1123 {
1124     DBHOLD(transPtr->dbase);
1125     *fileid = transPtr->seekFile;
1126     *position = transPtr->seekPos;
1127     DBRELE(transPtr->dbase);
1128     return 0;
1129 }
1130
1131 /*!
1132  * \brief This sets the file size for the currently-selected file to \p length
1133  * bytes, if length is less than the file's current size.
1134  */
1135 int
1136 ubik_Truncate(struct ubik_trans *transPtr, afs_int32 length)
1137 {
1138     afs_int32 code, error = 0;
1139
1140     /* Will also catch if not UBIK_WRITETRANS */
1141     code = ubik_Flush(transPtr);
1142     if (code)
1143         return (code);
1144
1145     DBHOLD(transPtr->dbase);
1146     /* first, check that quorum is still good, and that dbase is up-to-date */
1147     if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY))
1148         ERROR_EXIT(UNOQUORUM);
1149     if (!ubeacon_AmSyncSite())
1150         ERROR_EXIT(UNOTSYNC);
1151
1152     /* now do the operation locally, and propagate it out */
1153     code = udisk_truncate(transPtr, transPtr->seekFile, length);
1154     if (!code) {
1155         code =
1156             ContactQuorum_DISK_Truncate(transPtr, 0, transPtr->seekFile,
1157                                         length);
1158     }
1159     if (code) {
1160         /* we must abort the operation */
1161         udisk_abort(transPtr);
1162         ContactQuorum_NoArguments(DISK_Abort, transPtr, 0); /* force aborts to the others */
1163         ERROR_EXIT(code);
1164     }
1165
1166   error_exit:
1167     DBRELE(transPtr->dbase);
1168     return error;
1169 }
1170
1171 /*!
1172  * \brief set a lock; all locks are released on transaction end (commit/abort)
1173  */
1174 int
1175 ubik_SetLock(struct ubik_trans *atrans, afs_int32 apos, afs_int32 alen,
1176              int atype)
1177 {
1178     afs_int32 code = 0, error = 0;
1179
1180     if (atype == LOCKWRITE) {
1181         if (atrans->type == UBIK_READTRANS)
1182             return UBADTYPE;
1183         code = ubik_Flush(atrans);
1184         if (code)
1185             return (code);
1186     }
1187
1188     DBHOLD(atrans->dbase);
1189     if (atype == LOCKREAD) {
1190         code = ulock_getLock(atrans, atype, 1);
1191         if (code)
1192             ERROR_EXIT(code);
1193     } else {
1194         /* first, check that quorum is still good, and that dbase is up-to-date */
1195         if (!urecovery_AllBetter(atrans->dbase, atrans->flags & TRREADANY))
1196             ERROR_EXIT(UNOQUORUM);
1197         if (!ubeacon_AmSyncSite())
1198             ERROR_EXIT(UNOTSYNC);
1199
1200         /* now do the operation locally, and propagate it out */
1201         code = ulock_getLock(atrans, atype, 1);
1202         if (code == 0) {
1203             code = ContactQuorum_DISK_Lock(atrans, 0, 0, 1 /*unused */ ,
1204                                            1 /*unused */ , LOCKWRITE);
1205         }
1206         if (code) {
1207             /* we must abort the operation */
1208             udisk_abort(atrans);
1209             ContactQuorum_NoArguments(DISK_Abort, atrans, 0); /* force aborts to the others */
1210             ERROR_EXIT(code);
1211         }
1212     }
1213
1214   error_exit:
1215     DBRELE(atrans->dbase);
1216     return error;
1217 }
1218
1219 /*!
1220  * \brief utility to wait for a version # to change
1221  */
1222 int
1223 ubik_WaitVersion(struct ubik_dbase *adatabase,
1224                  struct ubik_version *aversion)
1225 {
1226     DBHOLD(adatabase);
1227     while (1) {
1228         /* wait until version # changes, and then return */
1229         if (vcmp(*aversion, adatabase->version) != 0) {
1230             DBRELE(adatabase);
1231             return 0;
1232         }
1233 #ifdef AFS_PTHREAD_ENV
1234         CV_WAIT(&adatabase->version_cond, &adatabase->versionLock);
1235 #else
1236         DBRELE(adatabase);
1237         LWP_WaitProcess(&adatabase->version);   /* same vers, just wait */
1238         DBHOLD(adatabase);
1239 #endif
1240     }
1241 }
1242
1243 /*!
1244  * \brief utility to get the version of the dbase a transaction is dealing with
1245  */
1246 int
1247 ubik_GetVersion(struct ubik_trans *atrans,
1248                 struct ubik_version *avers)
1249 {
1250     *avers = atrans->dbase->version;
1251     return 0;
1252 }
1253
1254 /*!
1255  * \brief Facility to simplify database caching.
1256  * \return zero if last trans was done on the local server and was successful.
1257  * \return -1 means bad (NULL) argument.
1258  *
1259  * If return value is non-zero and the caller is a server caching part of the
1260  * Ubik database, it should invalidate that cache.
1261  */
1262 static int
1263 ubik_CacheUpdate(struct ubik_trans *atrans)
1264 {
1265     if (!(atrans && atrans->dbase))
1266         return -1;
1267     return vcmp(atrans->dbase->cachedVersion, atrans->dbase->version) != 0;
1268 }
1269
1270 /**
1271  * check and possibly update cache of ubik db.
1272  *
1273  * If the version of the cached db data is out of date, this calls (*check) to
1274  * update the cache. If (*check) returns success, we update the version of the
1275  * cached db data.
1276  *
1277  * Checking the version of the cached db data is done under a read lock;
1278  * updating the cache (and thus calling (*check)) is done under a write lock
1279  * so is guaranteed not to interfere with another thread's (*check). On
1280  * successful return, a read lock on the cached db data is obtained, which
1281  * will be released by ubik_EndTrans or ubik_AbortTrans.
1282  *
1283  * @param[in] atrans ubik transaction
1284  * @param[in] check  function to call to check/update cache
1285  * @param[in] rock   rock to pass to *check
1286  *
1287  * @return operation status
1288  *   @retval 0       success
1289  *   @retval nonzero error; cachedVersion not updated
1290  *
1291  * @post On success, application cache is read-locked, and cache data is
1292  *       up-to-date
1293  */
1294 int
1295 ubik_CheckCache(struct ubik_trans *atrans, ubik_updatecache_func cbf, void *rock)
1296 {
1297     int ret = 0;
1298
1299     if (!(atrans && atrans->dbase))
1300         return -1;
1301
1302     ObtainReadLock(&atrans->dbase->cache_lock);
1303
1304     while (ubik_CacheUpdate(atrans) != 0) {
1305
1306         ReleaseReadLock(&atrans->dbase->cache_lock);
1307         ObtainSharedLock(&atrans->dbase->cache_lock);
1308
1309         if (ubik_CacheUpdate(atrans) != 0) {
1310
1311             BoostSharedLock(&atrans->dbase->cache_lock);
1312
1313             ret = (*cbf) (atrans, rock);
1314             if (ret == 0) {
1315                 memcpy(&atrans->dbase->cachedVersion, &atrans->dbase->version,
1316                        sizeof(atrans->dbase->cachedVersion));
1317             }
1318         }
1319
1320         /* It would be nice if we could convert from a shared lock to a read
1321          * lock... instead, just release the shared and acquire the read */
1322         ReleaseSharedLock(&atrans->dbase->cache_lock);
1323
1324         if (ret) {
1325             /* if we have an error, don't retry, and don't hold any locks */
1326             return ret;
1327         }
1328
1329         ObtainReadLock(&atrans->dbase->cache_lock);
1330     }
1331
1332     atrans->flags |= TRCACHELOCKED;
1333
1334     return 0;
1335 }
1336
1337 /*!
1338  * "Who said anything about panicking?" snapped Arthur.
1339  * "This is still just the culture shock. You wait till I've settled down
1340  * into the situation and found my bearings. \em Then I'll start panicking!"
1341  * --Authur Dent
1342  *
1343  * \returns There is no return from panic.
1344  */
1345 void
1346 panic(char *format, ...)
1347 {
1348     va_list ap;
1349
1350     va_start(ap, format);
1351     ubik_print("Ubik PANIC: ");
1352     ubik_vprint(format, ap);
1353     va_end(ap);
1354
1355     abort();
1356     ubik_print("BACK FROM ABORT\n");    /* shouldn't come back */
1357     exit(1);                    /* never know, though  */
1358 }
1359
1360 /*!
1361  * This function takes an IP addresses as its parameter. It returns the
1362  * the primary IP address that is on the host passed in, or 0 if not found.
1363  */
1364 afs_uint32
1365 ubikGetPrimaryInterfaceAddr(afs_uint32 addr)
1366 {
1367     struct ubik_server *ts;
1368     int j;
1369
1370     for (ts = ubik_servers; ts; ts = ts->next)
1371         for (j = 0; j < UBIK_MAX_INTERFACE_ADDR; j++)
1372             if (ts->addr[j] == addr)
1373                 return ts->addr[0];     /* net byte order */
1374     return 0;                   /* if not in server database, return error */
1375 }
1376
1377 int
1378 ubik_CheckAuth(struct rx_call *acall)
1379 {
1380     if (checkSecurityProc)
1381         return (*checkSecurityProc) (securityRock, acall);
1382     else if (ubik_CheckRXSecurityProc) {
1383         return (*ubik_CheckRXSecurityProc) (ubik_CheckRXSecurityRock, acall);
1384     } else
1385         return 0;
1386 }
1387
1388 void
1389 ubik_SetServerSecurityProcs(void (*buildproc) (void *,
1390                                                struct rx_securityClass ***,
1391                                                afs_int32 *),
1392                             int (*checkproc) (void *, struct rx_call *),
1393                             void *rock)
1394 {
1395     buildSecClassesProc = buildproc;
1396     checkSecurityProc = checkproc;
1397     securityRock = rock;
1398 }