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