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