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