d3d0b99188a82c7c11816731e8b12b27279a482b
[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     MUTEX_INIT(&vote_globals.vote_lock, "vote lock", MUTEX_DEFAULT, 0);
410 #else
411     Lock_Init(&tdb->versionLock);
412 #endif
413     Lock_Init(&tdb->cache_lock);
414     tdb->flags = 0;
415     tdb->read = uphys_read;
416     tdb->write = uphys_write;
417     tdb->truncate = uphys_truncate;
418     tdb->open = uphys_invalidate;       /* this function isn't used any more */
419     tdb->sync = uphys_sync;
420     tdb->stat = uphys_stat;
421     tdb->getlabel = uphys_getlabel;
422     tdb->setlabel = uphys_setlabel;
423     tdb->getnfiles = uphys_getnfiles;
424     tdb->readers = 0;
425     tdb->tidCounter = tdb->writeTidCounter = 0;
426     *dbase = tdb;
427     ubik_dbase = tdb;           /* for now, only one db per server; can fix later when we have names for the other dbases */
428
429 #ifdef AFS_PTHREAD_ENV
430     CV_INIT(&tdb->version_cond, "version", CV_DEFAULT, 0);
431     CV_INIT(&tdb->flags_cond, "flags", CV_DEFAULT, 0);
432 #endif /* AFS_PTHREAD_ENV */
433
434     /* initialize RX */
435
436     /* the following call is idempotent so when/if it got called earlier,
437      * by whatever called us, it doesn't really matter -- klm */
438     code = rx_Init(myPort);
439     if (code < 0)
440         return code;
441
442     udisk_Init(ubik_nBuffers);
443     ulock_Init();
444
445     code = uvote_Init();
446     if (code)
447         return code;
448     code = urecovery_Initialize(tdb);
449     if (code)
450         return code;
451     if (info)
452         code = ubeacon_InitServerListByInfo(myHost, info, clones);
453     else
454         code = ubeacon_InitServerList(myHost, serverList);
455     if (code)
456         return code;
457
458     ubik_callPortal = myPort;
459     /* try to get an additional security object */
460     if (buildSecClassesProc == NULL) {
461         numClasses = 3;
462         ubik_sc = calloc(numClasses, sizeof(struct rx_securityClass *));
463         ubik_sc[0] = rxnull_NewServerSecurityObject();
464         if (ubik_SRXSecurityProc) {
465             code = (*ubik_SRXSecurityProc) (ubik_SRXSecurityRock,
466                                             &secClass,
467                                             &secIndex);
468             if (code == 0) {
469                  ubik_sc[secIndex] = secClass;
470             }
471         }
472     } else {
473         (*buildSecClassesProc) (securityRock, &ubik_sc, &numClasses);
474     }
475     /* for backwards compat this should keep working as it does now
476        and not host bind */
477
478     tservice =
479         rx_NewService(0, VOTE_SERVICE_ID, "VOTE", ubik_sc, numClasses,
480                       VOTE_ExecuteRequest);
481     if (tservice == (struct rx_service *)0) {
482         ubik_dprint("Could not create VOTE rx service!\n");
483         return -1;
484     }
485     rx_SetMinProcs(tservice, 2);
486     rx_SetMaxProcs(tservice, 3);
487
488     tservice =
489         rx_NewService(0, DISK_SERVICE_ID, "DISK", ubik_sc, numClasses,
490                       DISK_ExecuteRequest);
491     if (tservice == (struct rx_service *)0) {
492         ubik_dprint("Could not create DISK rx service!\n");
493         return -1;
494     }
495     rx_SetMinProcs(tservice, 2);
496     rx_SetMaxProcs(tservice, 3);
497
498     /* start an rx_ServerProc to handle incoming RPC's in particular the
499      * UpdateInterfaceAddr RPC that occurs in ubeacon_InitServerList. This avoids
500      * the "steplock" problem in ubik initialization. Defect 11037.
501      */
502 #ifdef AFS_PTHREAD_ENV
503     ubik_thread_create(&rxServer_tattr, &rxServerThread, (void *)rx_ServerProc);
504 #else
505     LWP_CreateProcess(rx_ServerProc, rx_stackSize, RX_PROCESS_PRIORITY,
506               NULL, "rx_ServerProc", &junk);
507 #endif
508
509     /* now start up async processes */
510 #ifdef AFS_PTHREAD_ENV
511     ubik_thread_create(&ubeacon_Interact_tattr, &ubeacon_InteractThread,
512                 (void *)ubeacon_Interact);
513 #else
514     code = LWP_CreateProcess(ubeacon_Interact, 16384 /*8192 */ ,
515                              LWP_MAX_PRIORITY - 1, (void *)0, "beacon",
516                              &junk);
517     if (code)
518         return code;
519 #endif
520
521 #ifdef AFS_PTHREAD_ENV
522     ubik_thread_create(&urecovery_Interact_tattr, &urecovery_InteractThread,
523                 (void *)urecovery_Interact);
524     return 0;  /* is this correct?  - klm */
525 #else
526     code = LWP_CreateProcess(urecovery_Interact, 16384 /*8192 */ ,
527                              LWP_MAX_PRIORITY - 1, (void *)0, "recovery",
528                              &junk);
529     return code;
530 #endif
531
532 }
533
534 /*!
535  * \see ubik_ServerInitCommon()
536  */
537 int
538 ubik_ServerInitByInfo(afs_uint32 myHost, short myPort,
539                       struct afsconf_cell *info, char clones[],
540                       const char *pathName, struct ubik_dbase **dbase)
541 {
542     afs_int32 code;
543
544     code =
545         ubik_ServerInitCommon(myHost, myPort, info, clones, 0, pathName,
546                               dbase);
547     return code;
548 }
549
550 /*!
551  * \see ubik_ServerInitCommon()
552  */
553 int
554 ubik_ServerInit(afs_uint32 myHost, short myPort, afs_uint32 serverList[],
555                 const char *pathName, struct ubik_dbase **dbase)
556 {
557     afs_int32 code;
558
559     code =
560         ubik_ServerInitCommon(myHost, myPort, (struct afsconf_cell *)0, 0,
561                               serverList, pathName, dbase);
562     return code;
563 }
564
565 /*!
566  * \brief This routine begins a read or write transaction on the transaction
567  * identified by transPtr, in the dbase named by dbase.
568  *
569  * An open mode of ubik_READTRANS identifies this as a read transaction,
570  * while a mode of ubik_WRITETRANS identifies this as a write transaction.
571  * transPtr is set to the returned transaction control block.
572  * The readAny flag is set to 0 or 1 or 2 by the wrapper functions
573  * ubik_BeginTrans() or ubik_BeginTransReadAny() or
574  * ubik_BeginTransReadAnyWrite() below.
575  *
576  * \note We can only begin transaction when we have an up-to-date database.
577  */
578 static int
579 BeginTrans(struct ubik_dbase *dbase, afs_int32 transMode,
580            struct ubik_trans **transPtr, int readAny)
581 {
582     struct ubik_trans *jt;
583     struct ubik_trans *tt;
584     afs_int32 code;
585
586     if (readAny > 1 && ubik_SyncWriterCacheProc == NULL) {
587         /* it's not safe to use ubik_BeginTransReadAnyWrite without a
588          * cache-syncing function; fall back to ubik_BeginTransReadAny,
589          * which is safe but slower */
590         ubik_print("ubik_BeginTransReadAnyWrite called, but "
591                    "ubik_SyncWriterCacheProc not set; pretending "
592                    "ubik_BeginTransReadAny was called instead\n");
593         readAny = 1;
594     }
595
596     if ((transMode != UBIK_READTRANS) && readAny)
597         return UBADTYPE;
598     DBHOLD(dbase);
599     if (urecovery_AllBetter(dbase, readAny) == 0) {
600         DBRELE(dbase);
601         return UNOQUORUM;
602     }
603     /* otherwise we have a quorum, use it */
604
605     /* make sure that at most one write transaction occurs at any one time.  This
606      * has nothing to do with transaction locking; that's enforced by the lock package.  However,
607      * we can't even handle two non-conflicting writes, since our log and recovery modules
608      * don't know how to restore one without possibly picking up some data from the other. */
609     if (transMode == UBIK_WRITETRANS) {
610         /* if we're writing already, wait */
611         while (dbase->flags & DBWRITING) {
612 #ifdef AFS_PTHREAD_ENV
613             CV_WAIT(&dbase->flags_cond, &dbase->versionLock);
614 #else
615             DBRELE(dbase);
616             LWP_WaitProcess(&dbase->flags);
617             DBHOLD(dbase);
618 #endif
619         }
620
621         if (!ubeacon_AmSyncSite()) {
622             DBRELE(dbase);
623             return UNOTSYNC;
624         }
625     }
626
627     /* create the transaction */
628     code = udisk_begin(dbase, transMode, &jt);  /* can't take address of register var */
629     tt = jt;                    /* move to a register */
630     if (code || tt == (struct ubik_trans *)NULL) {
631         DBRELE(dbase);
632         return code;
633     }
634     if (readAny) {
635         tt->flags |= TRREADANY;
636         if (readAny > 1) {
637             tt->flags |= TRREADWRITE;
638         }
639     }
640     /* label trans and dbase with new tid */
641     tt->tid.epoch = ubik_epochTime;
642     /* bump by two, since tidCounter+1 means trans id'd by tidCounter has finished */
643     tt->tid.counter = (dbase->tidCounter += 2);
644
645     if (transMode == UBIK_WRITETRANS) {
646         /* for a write trans, we have to keep track of the write tid counter too */
647         dbase->writeTidCounter = tt->tid.counter;
648
649         /* next try to start transaction on appropriate number of machines */
650         code = ContactQuorum_NoArguments(DISK_Begin, tt, 0);
651         if (code) {
652             /* we must abort the operation */
653             udisk_abort(tt);
654             ContactQuorum_NoArguments(DISK_Abort, tt, 0); /* force aborts to the others */
655             udisk_end(tt);
656             DBRELE(dbase);
657             return code;
658         }
659     }
660
661     *transPtr = tt;
662     DBRELE(dbase);
663     return 0;
664 }
665
666 /*!
667  * \see BeginTrans()
668  */
669 int
670 ubik_BeginTrans(struct ubik_dbase *dbase, afs_int32 transMode,
671                 struct ubik_trans **transPtr)
672 {
673     return BeginTrans(dbase, transMode, transPtr, 0);
674 }
675
676 /*!
677  * \see BeginTrans()
678  */
679 int
680 ubik_BeginTransReadAny(struct ubik_dbase *dbase, afs_int32 transMode,
681                        struct ubik_trans **transPtr)
682 {
683     return BeginTrans(dbase, transMode, transPtr, 1);
684 }
685
686 /*!
687  * \see BeginTrans()
688  */
689 int
690 ubik_BeginTransReadAnyWrite(struct ubik_dbase *dbase, afs_int32 transMode,
691                             struct ubik_trans **transPtr)
692 {
693     return BeginTrans(dbase, transMode, transPtr, 2);
694 }
695
696 /*!
697  * \brief This routine ends a read or write transaction by aborting it.
698  */
699 int
700 ubik_AbortTrans(struct ubik_trans *transPtr)
701 {
702     afs_int32 code;
703     afs_int32 code2;
704     struct ubik_dbase *dbase;
705
706     dbase = transPtr->dbase;
707
708     if (transPtr->flags & TRCACHELOCKED) {
709         ReleaseReadLock(&dbase->cache_lock);
710         transPtr->flags &= ~TRCACHELOCKED;
711     }
712
713     ObtainWriteLock(&dbase->cache_lock);
714
715     DBHOLD(dbase);
716     memset(&dbase->cachedVersion, 0, sizeof(struct ubik_version));
717
718     ReleaseWriteLock(&dbase->cache_lock);
719
720     /* see if we're still up-to-date */
721     if (!urecovery_AllBetter(dbase, transPtr->flags & TRREADANY)) {
722         udisk_abort(transPtr);
723         udisk_end(transPtr);
724         DBRELE(dbase);
725         return UNOQUORUM;
726     }
727
728     if (transPtr->type == UBIK_READTRANS) {
729         code = udisk_abort(transPtr);
730         udisk_end(transPtr);
731         DBRELE(dbase);
732         return code;
733     }
734
735     /* below here, we know we're doing a write transaction */
736     if (!ubeacon_AmSyncSite()) {
737         udisk_abort(transPtr);
738         udisk_end(transPtr);
739         DBRELE(dbase);
740         return UNOTSYNC;
741     }
742
743     /* now it is safe to try remote abort */
744     code = ContactQuorum_NoArguments(DISK_Abort, transPtr, 0);
745     code2 = udisk_abort(transPtr);
746     udisk_end(transPtr);
747     DBRELE(dbase);
748     return (code ? code : code2);
749 }
750
751 static void
752 WritebackApplicationCache(struct ubik_dbase *dbase)
753 {
754     int code = 0;
755     if (ubik_SyncWriterCacheProc) {
756         code = ubik_SyncWriterCacheProc();
757     }
758     if (code) {
759         /* we failed to sync the local cache, so just invalidate the cache;
760          * we'll try to read the cache in again on the next read */
761         memset(&dbase->cachedVersion, 0, sizeof(dbase->cachedVersion));
762     } else {
763         memcpy(&dbase->cachedVersion, &dbase->version,
764                sizeof(dbase->cachedVersion));
765     }
766 }
767
768 /*!
769  * \brief This routine ends a read or write transaction on the open transaction identified by transPtr.
770  * \return an error code.
771  */
772 int
773 ubik_EndTrans(struct ubik_trans *transPtr)
774 {
775     afs_int32 code;
776     struct timeval tv;
777     afs_int32 realStart;
778     struct ubik_server *ts;
779     afs_int32 now;
780     int cachelocked = 0;
781     struct ubik_dbase *dbase;
782
783     if (transPtr->type == UBIK_WRITETRANS) {
784         code = ubik_Flush(transPtr);
785         if (code) {
786             ubik_AbortTrans(transPtr);
787             return (code);
788         }
789     }
790
791     dbase = transPtr->dbase;
792
793     if (transPtr->flags & TRCACHELOCKED) {
794         ReleaseReadLock(&dbase->cache_lock);
795         transPtr->flags &= ~TRCACHELOCKED;
796     }
797
798     if (transPtr->type != UBIK_READTRANS) {
799         /* must hold cache_lock before DBHOLD'ing */
800         ObtainWriteLock(&dbase->cache_lock);
801         cachelocked = 1;
802     }
803
804     DBHOLD(dbase);
805
806     /* give up if no longer current */
807     if (!urecovery_AllBetter(dbase, transPtr->flags & TRREADANY)) {
808         udisk_abort(transPtr);
809         udisk_end(transPtr);
810         DBRELE(dbase);
811         code = UNOQUORUM;
812         goto error;
813     }
814
815     if (transPtr->type == UBIK_READTRANS) {     /* reads are easy */
816         code = udisk_commit(transPtr);
817         if (code == 0)
818             goto success;       /* update cachedVersion correctly */
819         udisk_end(transPtr);
820         DBRELE(dbase);
821         goto error;
822     }
823
824     if (!ubeacon_AmSyncSite()) {        /* no longer sync site */
825         udisk_abort(transPtr);
826         udisk_end(transPtr);
827         DBRELE(dbase);
828         code = UNOTSYNC;
829         goto error;
830     }
831
832     /* now it is safe to do commit */
833     code = udisk_commit(transPtr);
834     if (code == 0) {
835         /* db data has been committed locally; update the local cache so
836          * readers can get at it */
837         WritebackApplicationCache(dbase);
838
839         ReleaseWriteLock(&dbase->cache_lock);
840
841         code = ContactQuorum_NoArguments(DISK_Commit, transPtr, CStampVersion);
842
843     } else {
844         memset(&dbase->cachedVersion, 0, sizeof(struct ubik_version));
845         ReleaseWriteLock(&dbase->cache_lock);
846     }
847     cachelocked = 0;
848     if (code) {
849         /* failed to commit, so must return failure.  Try to clear locks first, just for fun
850          * Note that we don't know if this transaction will eventually commit at this point.
851          * If it made it to a site that will be present in the next quorum, we win, otherwise
852          * we lose.  If we contact a majority of sites, then we won't be here: contacting
853          * a majority guarantees commit, since it guarantees that one dude will be a
854          * member of the next quorum. */
855         ContactQuorum_NoArguments(DISK_ReleaseLocks, transPtr, 0);
856         udisk_end(transPtr);
857         DBRELE(dbase);
858         goto error;
859     }
860     /* before we can start sending unlock messages, we must wait until all servers
861      * that are possibly still functioning on the other side of a network partition
862      * have timed out.  Check the server structures, compute how long to wait, then
863      * start the unlocks */
864     realStart = FT_ApproxTime();
865     while (1) {
866         /* wait for all servers to time out */
867         code = 0;
868         now = FT_ApproxTime();
869         /* check if we're still sync site, the guy should either come up
870          * to us, or timeout.  Put safety check in anyway */
871         if (now - realStart > 10 * BIGTIME) {
872             ubik_stats.escapes++;
873             ubik_print("ubik escaping from commit wait\n");
874             break;
875         }
876         for (ts = ubik_servers; ts; ts = ts->next) {
877             UBIK_BEACON_LOCK;
878             if (!ts->beaconSinceDown && now <= ts->lastBeaconSent + BIGTIME) {
879                 UBIK_BEACON_UNLOCK;
880
881                 /* this guy could have some damaged data, wait for him */
882                 code = 1;
883                 tv.tv_sec = 1;  /* try again after a while (ha ha) */
884                 tv.tv_usec = 0;
885
886 #ifdef AFS_PTHREAD_ENV
887                 /* we could release the dbase outside of the loop, but we do
888                  * it here, in the loop, to avoid an unnecessary RELE/HOLD
889                  * if all sites are up */
890                 DBRELE(dbase);
891                 select(0, 0, 0, 0, &tv);
892                 DBHOLD(dbase);
893 #else
894                 IOMGR_Select(0, 0, 0, 0, &tv);  /* poll, should we wait on something? */
895 #endif
896
897                 break;
898             }
899             UBIK_BEACON_UNLOCK;
900         }
901         if (code == 0)
902             break;              /* no down ones still pseudo-active */
903     }
904
905     /* finally, unlock all the dudes.  We can return success independent of the number of servers
906      * that really unlock the dbase; the others will do it if/when they elect a new sync site.
907      * The transaction is committed anyway, since we succeeded in contacting a quorum
908      * at the start (when invoking the DiskCommit function).
909      */
910     ContactQuorum_NoArguments(DISK_ReleaseLocks, transPtr, 0);
911
912   success:
913     udisk_end(transPtr);
914     /* don't update cachedVersion here; it should have been updated way back
915      * in ubik_CheckCache, and earlier in this function for writes */
916     DBRELE(dbase);
917     if (cachelocked) {
918         ReleaseWriteLock(&dbase->cache_lock);
919     }
920     return 0;
921
922   error:
923     if (!cachelocked) {
924         ObtainWriteLock(&dbase->cache_lock);
925     }
926     memset(&dbase->cachedVersion, 0, sizeof(struct ubik_version));
927     ReleaseWriteLock(&dbase->cache_lock);
928     return code;
929 }
930
931 /*!
932  * \brief This routine reads length bytes into buffer from the current position in the database.
933  *
934  * 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.
935  *
936  * \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.
937  */
938 int
939 ubik_Read(struct ubik_trans *transPtr, void *buffer,
940           afs_int32 length)
941 {
942     afs_int32 code;
943
944     /* reads are easy to do: handle locally */
945     DBHOLD(transPtr->dbase);
946     if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY)) {
947         DBRELE(transPtr->dbase);
948         return UNOQUORUM;
949     }
950
951     code =
952         udisk_read(transPtr, transPtr->seekFile, buffer, transPtr->seekPos,
953                    length);
954     if (code == 0) {
955         transPtr->seekPos += length;
956     }
957     DBRELE(transPtr->dbase);
958     return code;
959 }
960
961 /*!
962  * \brief This routine will flush the io data in the iovec structures.
963  *
964  * It first flushes to the local disk and then uses ContactQuorum to write it
965  * to the other servers.
966  */
967 int
968 ubik_Flush(struct ubik_trans *transPtr)
969 {
970     afs_int32 code, error = 0;
971
972     if (transPtr->type != UBIK_WRITETRANS)
973         return UBADTYPE;
974     if (!transPtr->iovec_info.iovec_wrt_len
975         || !transPtr->iovec_info.iovec_wrt_val)
976         return 0;
977
978     DBHOLD(transPtr->dbase);
979     if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY))
980         ERROR_EXIT(UNOQUORUM);
981     if (!ubeacon_AmSyncSite())  /* only sync site can write */
982         ERROR_EXIT(UNOTSYNC);
983
984     /* Update the rest of the servers in the quorum */
985     code =
986         ContactQuorum_DISK_WriteV(transPtr, 0, &transPtr->iovec_info,
987                                   &transPtr->iovec_data);
988     if (code) {
989         udisk_abort(transPtr);
990         ContactQuorum_NoArguments(DISK_Abort, transPtr, 0); /* force aborts to the others */
991         transPtr->iovec_info.iovec_wrt_len = 0;
992         transPtr->iovec_data.iovec_buf_len = 0;
993         ERROR_EXIT(code);
994     }
995
996     /* Wrote the buffers out, so start at scratch again */
997     transPtr->iovec_info.iovec_wrt_len = 0;
998     transPtr->iovec_data.iovec_buf_len = 0;
999
1000   error_exit:
1001     DBRELE(transPtr->dbase);
1002     return error;
1003 }
1004
1005 int
1006 ubik_Write(struct ubik_trans *transPtr, void *vbuffer,
1007            afs_int32 length)
1008 {
1009     struct ubik_iovec *iovec;
1010     afs_int32 code, error = 0;
1011     afs_int32 pos, len, size;
1012     char * buffer = (char *)vbuffer;
1013
1014     if (transPtr->type != UBIK_WRITETRANS)
1015         return UBADTYPE;
1016     if (!length)
1017         return 0;
1018
1019     if (length > IOVEC_MAXBUF) {
1020         for (pos = 0, len = length; len > 0; len -= size, pos += size) {
1021             size = ((len < IOVEC_MAXBUF) ? len : IOVEC_MAXBUF);
1022             code = ubik_Write(transPtr, buffer+pos, size);
1023             if (code)
1024                 return (code);
1025         }
1026         return 0;
1027     }
1028
1029     if (!transPtr->iovec_info.iovec_wrt_val) {
1030         transPtr->iovec_info.iovec_wrt_len = 0;
1031         transPtr->iovec_info.iovec_wrt_val =
1032             (struct ubik_iovec *)malloc(IOVEC_MAXWRT *
1033                                         sizeof(struct ubik_iovec));
1034         transPtr->iovec_data.iovec_buf_len = 0;
1035         transPtr->iovec_data.iovec_buf_val = (char *)malloc(IOVEC_MAXBUF);
1036         if (!transPtr->iovec_info.iovec_wrt_val
1037             || !transPtr->iovec_data.iovec_buf_val) {
1038             if (transPtr->iovec_info.iovec_wrt_val)
1039                 free(transPtr->iovec_info.iovec_wrt_val);
1040             transPtr->iovec_info.iovec_wrt_val = 0;
1041             if (transPtr->iovec_data.iovec_buf_val)
1042                 free(transPtr->iovec_data.iovec_buf_val);
1043             transPtr->iovec_data.iovec_buf_val = 0;
1044             return UNOMEM;
1045         }
1046     }
1047
1048     /* If this write won't fit in the structure, then flush it out and start anew */
1049     if ((transPtr->iovec_info.iovec_wrt_len >= IOVEC_MAXWRT)
1050         || ((length + transPtr->iovec_data.iovec_buf_len) > IOVEC_MAXBUF)) {
1051         code = ubik_Flush(transPtr);
1052         if (code)
1053             return (code);
1054     }
1055
1056     DBHOLD(transPtr->dbase);
1057     if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY))
1058         ERROR_EXIT(UNOQUORUM);
1059     if (!ubeacon_AmSyncSite())  /* only sync site can write */
1060         ERROR_EXIT(UNOTSYNC);
1061
1062     /* Write to the local disk */
1063     code =
1064         udisk_write(transPtr, transPtr->seekFile, buffer, transPtr->seekPos,
1065                     length);
1066     if (code) {
1067         udisk_abort(transPtr);
1068         transPtr->iovec_info.iovec_wrt_len = 0;
1069         transPtr->iovec_data.iovec_buf_len = 0;
1070         DBRELE(transPtr->dbase);
1071         return (code);
1072     }
1073
1074     /* Collect writes for the other ubik servers (to be done in bulk) */
1075     iovec = (struct ubik_iovec *)transPtr->iovec_info.iovec_wrt_val;
1076     iovec[transPtr->iovec_info.iovec_wrt_len].file = transPtr->seekFile;
1077     iovec[transPtr->iovec_info.iovec_wrt_len].position = transPtr->seekPos;
1078     iovec[transPtr->iovec_info.iovec_wrt_len].length = length;
1079
1080     memcpy(&transPtr->iovec_data.
1081            iovec_buf_val[transPtr->iovec_data.iovec_buf_len], buffer, length);
1082
1083     transPtr->iovec_info.iovec_wrt_len++;
1084     transPtr->iovec_data.iovec_buf_len += length;
1085     transPtr->seekPos += length;
1086
1087   error_exit:
1088     DBRELE(transPtr->dbase);
1089     return error;
1090 }
1091
1092 /*!
1093  * \brief This sets the file pointer associated with the current transaction
1094  * to the appropriate file and byte position.
1095  *
1096  * Unlike Unix files, a transaction is labelled by both a file number \p fileid
1097  * and a byte position relative to the specified file \p position.
1098  */
1099 int
1100 ubik_Seek(struct ubik_trans *transPtr, afs_int32 fileid,
1101           afs_int32 position)
1102 {
1103     afs_int32 code;
1104
1105     DBHOLD(transPtr->dbase);
1106     if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY)) {
1107         code = UNOQUORUM;
1108     } else {
1109         transPtr->seekFile = fileid;
1110         transPtr->seekPos = position;
1111         code = 0;
1112     }
1113     DBRELE(transPtr->dbase);
1114     return code;
1115 }
1116
1117 /*!
1118  * \brief This call returns the file pointer associated with the specified
1119  * transaction in \p fileid and \p position.
1120  */
1121 int
1122 ubik_Tell(struct ubik_trans *transPtr, afs_int32 * fileid,
1123           afs_int32 * position)
1124 {
1125     DBHOLD(transPtr->dbase);
1126     *fileid = transPtr->seekFile;
1127     *position = transPtr->seekPos;
1128     DBRELE(transPtr->dbase);
1129     return 0;
1130 }
1131
1132 /*!
1133  * \brief This sets the file size for the currently-selected file to \p length
1134  * bytes, if length is less than the file's current size.
1135  */
1136 int
1137 ubik_Truncate(struct ubik_trans *transPtr, afs_int32 length)
1138 {
1139     afs_int32 code, error = 0;
1140
1141     /* Will also catch if not UBIK_WRITETRANS */
1142     code = ubik_Flush(transPtr);
1143     if (code)
1144         return (code);
1145
1146     DBHOLD(transPtr->dbase);
1147     /* first, check that quorum is still good, and that dbase is up-to-date */
1148     if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY))
1149         ERROR_EXIT(UNOQUORUM);
1150     if (!ubeacon_AmSyncSite())
1151         ERROR_EXIT(UNOTSYNC);
1152
1153     /* now do the operation locally, and propagate it out */
1154     code = udisk_truncate(transPtr, transPtr->seekFile, length);
1155     if (!code) {
1156         code =
1157             ContactQuorum_DISK_Truncate(transPtr, 0, transPtr->seekFile,
1158                                         length);
1159     }
1160     if (code) {
1161         /* we must abort the operation */
1162         udisk_abort(transPtr);
1163         ContactQuorum_NoArguments(DISK_Abort, transPtr, 0); /* force aborts to the others */
1164         ERROR_EXIT(code);
1165     }
1166
1167   error_exit:
1168     DBRELE(transPtr->dbase);
1169     return error;
1170 }
1171
1172 /*!
1173  * \brief set a lock; all locks are released on transaction end (commit/abort)
1174  */
1175 int
1176 ubik_SetLock(struct ubik_trans *atrans, afs_int32 apos, afs_int32 alen,
1177              int atype)
1178 {
1179     afs_int32 code = 0, error = 0;
1180
1181     if (atype == LOCKWRITE) {
1182         if (atrans->type == UBIK_READTRANS)
1183             return UBADTYPE;
1184         code = ubik_Flush(atrans);
1185         if (code)
1186             return (code);
1187     }
1188
1189     DBHOLD(atrans->dbase);
1190     if (atype == LOCKREAD) {
1191         code = ulock_getLock(atrans, atype, 1);
1192         if (code)
1193             ERROR_EXIT(code);
1194     } else {
1195         /* first, check that quorum is still good, and that dbase is up-to-date */
1196         if (!urecovery_AllBetter(atrans->dbase, atrans->flags & TRREADANY))
1197             ERROR_EXIT(UNOQUORUM);
1198         if (!ubeacon_AmSyncSite())
1199             ERROR_EXIT(UNOTSYNC);
1200
1201         /* now do the operation locally, and propagate it out */
1202         code = ulock_getLock(atrans, atype, 1);
1203         if (code == 0) {
1204             code = ContactQuorum_DISK_Lock(atrans, 0, 0, 1 /*unused */ ,
1205                                            1 /*unused */ , LOCKWRITE);
1206         }
1207         if (code) {
1208             /* we must abort the operation */
1209             udisk_abort(atrans);
1210             ContactQuorum_NoArguments(DISK_Abort, atrans, 0); /* force aborts to the others */
1211             ERROR_EXIT(code);
1212         }
1213     }
1214
1215   error_exit:
1216     DBRELE(atrans->dbase);
1217     return error;
1218 }
1219
1220 /*!
1221  * \brief utility to wait for a version # to change
1222  */
1223 int
1224 ubik_WaitVersion(struct ubik_dbase *adatabase,
1225                  struct ubik_version *aversion)
1226 {
1227     DBHOLD(adatabase);
1228     while (1) {
1229         /* wait until version # changes, and then return */
1230         if (vcmp(*aversion, adatabase->version) != 0) {
1231             DBRELE(adatabase);
1232             return 0;
1233         }
1234 #ifdef AFS_PTHREAD_ENV
1235         CV_WAIT(&adatabase->version_cond, &adatabase->versionLock);
1236 #else
1237         DBRELE(adatabase);
1238         LWP_WaitProcess(&adatabase->version);   /* same vers, just wait */
1239         DBHOLD(adatabase);
1240 #endif
1241     }
1242 }
1243
1244 /*!
1245  * \brief utility to get the version of the dbase a transaction is dealing with
1246  */
1247 int
1248 ubik_GetVersion(struct ubik_trans *atrans,
1249                 struct ubik_version *avers)
1250 {
1251     *avers = atrans->dbase->version;
1252     return 0;
1253 }
1254
1255 /*!
1256  * \brief Facility to simplify database caching.
1257  * \return zero if last trans was done on the local server and was successful.
1258  * \return -1 means bad (NULL) argument.
1259  *
1260  * If return value is non-zero and the caller is a server caching part of the
1261  * Ubik database, it should invalidate that cache.
1262  */
1263 static int
1264 ubik_CacheUpdate(struct ubik_trans *atrans)
1265 {
1266     if (!(atrans && atrans->dbase))
1267         return -1;
1268     return vcmp(atrans->dbase->cachedVersion, atrans->dbase->version) != 0;
1269 }
1270
1271 /**
1272  * check and possibly update cache of ubik db.
1273  *
1274  * If the version of the cached db data is out of date, this calls (*check) to
1275  * update the cache. If (*check) returns success, we update the version of the
1276  * cached db data.
1277  *
1278  * Checking the version of the cached db data is done under a read lock;
1279  * updating the cache (and thus calling (*check)) is done under a write lock
1280  * so is guaranteed not to interfere with another thread's (*check). On
1281  * successful return, a read lock on the cached db data is obtained, which
1282  * will be released by ubik_EndTrans or ubik_AbortTrans.
1283  *
1284  * @param[in] atrans ubik transaction
1285  * @param[in] check  function to call to check/update cache
1286  * @param[in] rock   rock to pass to *check
1287  *
1288  * @return operation status
1289  *   @retval 0       success
1290  *   @retval nonzero error; cachedVersion not updated
1291  *
1292  * @post On success, application cache is read-locked, and cache data is
1293  *       up-to-date
1294  */
1295 int
1296 ubik_CheckCache(struct ubik_trans *atrans, ubik_updatecache_func cbf, void *rock)
1297 {
1298     int ret = 0;
1299
1300     if (!(atrans && atrans->dbase))
1301         return -1;
1302
1303     ObtainReadLock(&atrans->dbase->cache_lock);
1304
1305     while (ubik_CacheUpdate(atrans) != 0) {
1306
1307         ReleaseReadLock(&atrans->dbase->cache_lock);
1308         ObtainSharedLock(&atrans->dbase->cache_lock);
1309
1310         if (ubik_CacheUpdate(atrans) != 0) {
1311
1312             BoostSharedLock(&atrans->dbase->cache_lock);
1313
1314             ret = (*cbf) (atrans, rock);
1315             if (ret == 0) {
1316                 memcpy(&atrans->dbase->cachedVersion, &atrans->dbase->version,
1317                        sizeof(atrans->dbase->cachedVersion));
1318             }
1319         }
1320
1321         /* It would be nice if we could convert from a shared lock to a read
1322          * lock... instead, just release the shared and acquire the read */
1323         ReleaseSharedLock(&atrans->dbase->cache_lock);
1324
1325         if (ret) {
1326             /* if we have an error, don't retry, and don't hold any locks */
1327             return ret;
1328         }
1329
1330         ObtainReadLock(&atrans->dbase->cache_lock);
1331     }
1332
1333     atrans->flags |= TRCACHELOCKED;
1334
1335     return 0;
1336 }
1337
1338 /*!
1339  * "Who said anything about panicking?" snapped Arthur.
1340  * "This is still just the culture shock. You wait till I've settled down
1341  * into the situation and found my bearings. \em Then I'll start panicking!"
1342  * --Authur Dent
1343  *
1344  * \returns There is no return from panic.
1345  */
1346 void
1347 panic(char *format, ...)
1348 {
1349     va_list ap;
1350
1351     va_start(ap, format);
1352     ubik_print("Ubik PANIC: ");
1353     ubik_vprint(format, ap);
1354     va_end(ap);
1355
1356     abort();
1357     ubik_print("BACK FROM ABORT\n");    /* shouldn't come back */
1358     exit(1);                    /* never know, though  */
1359 }
1360
1361 /*!
1362  * This function takes an IP addresses as its parameter. It returns the
1363  * the primary IP address that is on the host passed in, or 0 if not found.
1364  */
1365 afs_uint32
1366 ubikGetPrimaryInterfaceAddr(afs_uint32 addr)
1367 {
1368     struct ubik_server *ts;
1369     int j;
1370
1371     for (ts = ubik_servers; ts; ts = ts->next)
1372         for (j = 0; j < UBIK_MAX_INTERFACE_ADDR; j++)
1373             if (ts->addr[j] == addr)
1374                 return ts->addr[0];     /* net byte order */
1375     return 0;                   /* if not in server database, return error */
1376 }
1377
1378 int
1379 ubik_CheckAuth(struct rx_call *acall)
1380 {
1381     if (checkSecurityProc)
1382         return (*checkSecurityProc) (securityRock, acall);
1383     else if (ubik_CheckRXSecurityProc) {
1384         return (*ubik_CheckRXSecurityProc) (ubik_CheckRXSecurityRock, acall);
1385     } else
1386         return 0;
1387 }
1388
1389 void
1390 ubik_SetServerSecurityProcs(void (*buildproc) (void *,
1391                                                struct rx_securityClass ***,
1392                                                afs_int32 *),
1393                             int (*checkproc) (void *, struct rx_call *),
1394                             void *rock)
1395 {
1396     buildSecClassesProc = buildproc;
1397     checkSecurityProc = checkproc;
1398     securityRock = rock;
1399 }