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