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