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