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