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