a8bd2e9242a9e3a4d805c438d96521a6219e63ce
[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 = malloc(sizeof(struct ubik_dbase));
410     tdb->pathName = strdup(pathName);
411     tdb->activeTrans = (struct ubik_trans *)0;
412     memset(&tdb->version, 0, sizeof(struct ubik_version));
413     memset(&tdb->cachedVersion, 0, sizeof(struct ubik_version));
414 #ifdef AFS_PTHREAD_ENV
415     opr_mutex_init(&tdb->versionLock);
416     opr_mutex_init(&beacon_globals.beacon_lock);
417     opr_mutex_init(&vote_globals.vote_lock);
418     opr_mutex_init(&addr_globals.addr_lock);
419     opr_mutex_init(&version_globals.version_lock);
420 #else
421     Lock_Init(&tdb->versionLock);
422 #endif
423     Lock_Init(&tdb->cache_lock);
424     tdb->flags = 0;
425     tdb->read = uphys_read;
426     tdb->write = uphys_write;
427     tdb->truncate = uphys_truncate;
428     tdb->open = uphys_invalidate;       /* this function isn't used any more */
429     tdb->sync = uphys_sync;
430     tdb->stat = uphys_stat;
431     tdb->getlabel = uphys_getlabel;
432     tdb->setlabel = uphys_setlabel;
433     tdb->getnfiles = uphys_getnfiles;
434     tdb->readers = 0;
435     tdb->tidCounter = tdb->writeTidCounter = 0;
436     *dbase = tdb;
437     ubik_dbase = tdb;           /* for now, only one db per server; can fix later when we have names for the other dbases */
438
439 #ifdef AFS_PTHREAD_ENV
440     opr_cv_init(&tdb->version_cond);
441     opr_cv_init(&tdb->flags_cond);
442 #endif /* AFS_PTHREAD_ENV */
443
444     /* initialize RX */
445
446     /* the following call is idempotent so when/if it got called earlier,
447      * by whatever called us, it doesn't really matter -- klm */
448     code = rx_Init(myPort);
449     if (code < 0)
450         return code;
451
452     ubik_callPortal = myPort;
453
454     udisk_Init(ubik_nBuffers);
455     ulock_Init();
456
457     code = uvote_Init();
458     if (code)
459         return code;
460     code = urecovery_Initialize(tdb);
461     if (code)
462         return code;
463     if (info)
464         code = ubeacon_InitServerListByInfo(myHost, info, clones);
465     else
466         code = ubeacon_InitServerList(myHost, serverList);
467     if (code)
468         return code;
469
470     /* try to get an additional security object */
471     if (buildSecClassesProc == NULL) {
472         numClasses = 3;
473         ubik_sc = calloc(numClasses, sizeof(struct rx_securityClass *));
474         ubik_sc[0] = rxnull_NewServerSecurityObject();
475         if (ubik_SRXSecurityProc) {
476             code = (*ubik_SRXSecurityProc) (ubik_SRXSecurityRock,
477                                             &secClass,
478                                             &secIndex);
479             if (code == 0) {
480                  ubik_sc[secIndex] = secClass;
481             }
482         }
483     } else {
484         (*buildSecClassesProc) (securityRock, &ubik_sc, &numClasses);
485     }
486     /* for backwards compat this should keep working as it does now
487        and not host bind */
488
489     tservice =
490         rx_NewService(0, VOTE_SERVICE_ID, "VOTE", ubik_sc, numClasses,
491                       VOTE_ExecuteRequest);
492     if (tservice == (struct rx_service *)0) {
493         ViceLog(0, ("Could not create VOTE rx service!\n"));
494         return -1;
495     }
496     rx_SetMinProcs(tservice, 2);
497     rx_SetMaxProcs(tservice, 3);
498
499     tservice =
500         rx_NewService(0, DISK_SERVICE_ID, "DISK", ubik_sc, numClasses,
501                       DISK_ExecuteRequest);
502     if (tservice == (struct rx_service *)0) {
503         ViceLog(0, ("Could not create DISK rx service!\n"));
504         return -1;
505     }
506     rx_SetMinProcs(tservice, 2);
507     rx_SetMaxProcs(tservice, 3);
508
509     /* start an rx_ServerProc to handle incoming RPC's in particular the
510      * UpdateInterfaceAddr RPC that occurs in ubeacon_InitServerList. This avoids
511      * the "steplock" problem in ubik initialization. Defect 11037.
512      */
513 #ifdef AFS_PTHREAD_ENV
514     ubik_thread_create(&rxServer_tattr, &rxServerThread, (void *)rx_ServerProc);
515 #else
516     LWP_CreateProcess(rx_ServerProc, rx_stackSize, RX_PROCESS_PRIORITY,
517               NULL, "rx_ServerProc", &junk);
518 #endif
519
520     /* send addrs to all other servers */
521     code = ubeacon_updateUbikNetworkAddress(ubik_host);
522     if (code)
523         return code;
524
525     /* now start up async processes */
526 #ifdef AFS_PTHREAD_ENV
527     ubik_thread_create(&ubeacon_Interact_tattr, &ubeacon_InteractThread,
528                 (void *)ubeacon_Interact);
529 #else
530     code = LWP_CreateProcess(ubeacon_Interact, 16384 /*8192 */ ,
531                              LWP_MAX_PRIORITY - 1, (void *)0, "beacon",
532                              &junk);
533     if (code)
534         return code;
535 #endif
536
537 #ifdef AFS_PTHREAD_ENV
538     ubik_thread_create(&urecovery_Interact_tattr, &urecovery_InteractThread,
539                 (void *)urecovery_Interact);
540     return 0;  /* is this correct?  - klm */
541 #else
542     code = LWP_CreateProcess(urecovery_Interact, 16384 /*8192 */ ,
543                              LWP_MAX_PRIORITY - 1, (void *)0, "recovery",
544                              &junk);
545     return code;
546 #endif
547
548 }
549
550 /*!
551  * \see ubik_ServerInitCommon()
552  */
553 int
554 ubik_ServerInitByInfo(afs_uint32 myHost, short myPort,
555                       struct afsconf_cell *info, char clones[],
556                       const char *pathName, struct ubik_dbase **dbase)
557 {
558     afs_int32 code;
559
560     code =
561         ubik_ServerInitCommon(myHost, myPort, info, clones, 0, pathName,
562                               dbase);
563     return code;
564 }
565
566 /*!
567  * \see ubik_ServerInitCommon()
568  */
569 int
570 ubik_ServerInit(afs_uint32 myHost, short myPort, afs_uint32 serverList[],
571                 const char *pathName, struct ubik_dbase **dbase)
572 {
573     afs_int32 code;
574
575     code =
576         ubik_ServerInitCommon(myHost, myPort, (struct afsconf_cell *)0, 0,
577                               serverList, pathName, dbase);
578     return code;
579 }
580
581 /*!
582  * \brief This routine begins a read or write transaction on the transaction
583  * identified by transPtr, in the dbase named by dbase.
584  *
585  * An open mode of ubik_READTRANS identifies this as a read transaction,
586  * while a mode of ubik_WRITETRANS identifies this as a write transaction.
587  * transPtr is set to the returned transaction control block.
588  * The readAny flag is set to 0 or 1 or 2 by the wrapper functions
589  * ubik_BeginTrans() or ubik_BeginTransReadAny() or
590  * ubik_BeginTransReadAnyWrite() below.
591  *
592  * \note We can only begin transaction when we have an up-to-date database.
593  */
594 static int
595 BeginTrans(struct ubik_dbase *dbase, afs_int32 transMode,
596            struct ubik_trans **transPtr, int readAny)
597 {
598     struct ubik_trans *jt;
599     struct ubik_trans *tt;
600     afs_int32 code;
601
602     if (readAny > 1 && ubik_SyncWriterCacheProc == NULL) {
603         /* it's not safe to use ubik_BeginTransReadAnyWrite without a
604          * cache-syncing function; fall back to ubik_BeginTransReadAny,
605          * which is safe but slower */
606         ViceLog(0, ("ubik_BeginTransReadAnyWrite called, but "
607                    "ubik_SyncWriterCacheProc not set; pretending "
608                    "ubik_BeginTransReadAny was called instead\n"));
609         readAny = 1;
610     }
611
612     if ((transMode != UBIK_READTRANS) && readAny)
613         return UBADTYPE;
614     DBHOLD(dbase);
615     if (urecovery_AllBetter(dbase, readAny) == 0) {
616         DBRELE(dbase);
617         return UNOQUORUM;
618     }
619     /* otherwise we have a quorum, use it */
620
621     /* make sure that at most one write transaction occurs at any one time.  This
622      * has nothing to do with transaction locking; that's enforced by the lock package.  However,
623      * we can't even handle two non-conflicting writes, since our log and recovery modules
624      * don't know how to restore one without possibly picking up some data from the other. */
625     if (transMode == UBIK_WRITETRANS) {
626         /* if we're writing already, wait */
627         while (dbase->flags & DBWRITING) {
628 #ifdef AFS_PTHREAD_ENV
629             opr_cv_wait(&dbase->flags_cond, &dbase->versionLock);
630 #else
631             DBRELE(dbase);
632             LWP_WaitProcess(&dbase->flags);
633             DBHOLD(dbase);
634 #endif
635         }
636
637         if (!ubeacon_AmSyncSite()) {
638             DBRELE(dbase);
639             return UNOTSYNC;
640         }
641         if (!ubeacon_SyncSiteAdvertised()) {
642             /* i am the sync-site but the remotes are not aware yet */
643             DBRELE(dbase);
644             return UNOQUORUM;
645         }
646     }
647
648     /* create the transaction */
649     code = udisk_begin(dbase, transMode, &jt);  /* can't take address of register var */
650     tt = jt;                    /* move to a register */
651     if (code || tt == NULL) {
652         DBRELE(dbase);
653         return code;
654     }
655     UBIK_VERSION_LOCK;
656     if (readAny) {
657         tt->flags |= TRREADANY;
658         if (readAny > 1) {
659             tt->flags |= TRREADWRITE;
660         }
661     }
662     /* label trans and dbase with new tid */
663     tt->tid.epoch = version_globals.ubik_epochTime;
664     /* bump by two, since tidCounter+1 means trans id'd by tidCounter has finished */
665     tt->tid.counter = (dbase->tidCounter += 2);
666
667     if (transMode == UBIK_WRITETRANS) {
668         /* for a write trans, we have to keep track of the write tid counter too */
669         dbase->writeTidCounter = tt->tid.counter;
670     }
671
672     UBIK_VERSION_UNLOCK;
673
674     if (transMode == UBIK_WRITETRANS) {
675         /* next try to start transaction on appropriate number of machines */
676         code = ContactQuorum_NoArguments(DISK_Begin, tt, CCheckSyncAdvertised, "DISK_Begin");
677         if (code) {
678             /* we must abort the operation */
679             udisk_abort(tt);
680             /* force aborts to the others */
681             ContactQuorum_NoArguments(DISK_Abort, tt, 0, "DISK_Abort");
682             udisk_end(tt);
683             DBRELE(dbase);
684             return code;
685         }
686     }
687
688     *transPtr = tt;
689     DBRELE(dbase);
690     return 0;
691 }
692
693 /*!
694  * \see BeginTrans()
695  */
696 int
697 ubik_BeginTrans(struct ubik_dbase *dbase, afs_int32 transMode,
698                 struct ubik_trans **transPtr)
699 {
700     return BeginTrans(dbase, transMode, transPtr, 0);
701 }
702
703 /*!
704  * \see BeginTrans()
705  */
706 int
707 ubik_BeginTransReadAny(struct ubik_dbase *dbase, afs_int32 transMode,
708                        struct ubik_trans **transPtr)
709 {
710     return BeginTrans(dbase, transMode, transPtr, 1);
711 }
712
713 /*!
714  * \see BeginTrans()
715  */
716 int
717 ubik_BeginTransReadAnyWrite(struct ubik_dbase *dbase, afs_int32 transMode,
718                             struct ubik_trans **transPtr)
719 {
720     return BeginTrans(dbase, transMode, transPtr, 2);
721 }
722
723 /*!
724  * \brief This routine ends a read or write transaction by aborting it.
725  */
726 int
727 ubik_AbortTrans(struct ubik_trans *transPtr)
728 {
729     afs_int32 code;
730     afs_int32 code2;
731     struct ubik_dbase *dbase;
732
733     dbase = transPtr->dbase;
734
735     if (transPtr->flags & TRCACHELOCKED) {
736         ReleaseReadLock(&dbase->cache_lock);
737         transPtr->flags &= ~TRCACHELOCKED;
738     }
739
740     ObtainWriteLock(&dbase->cache_lock);
741
742     DBHOLD(dbase);
743     memset(&dbase->cachedVersion, 0, sizeof(struct ubik_version));
744
745     ReleaseWriteLock(&dbase->cache_lock);
746
747     /* see if we're still up-to-date */
748     if (!urecovery_AllBetter(dbase, transPtr->flags & TRREADANY)) {
749         udisk_abort(transPtr);
750         udisk_end(transPtr);
751         DBRELE(dbase);
752         return UNOQUORUM;
753     }
754
755     if (transPtr->type == UBIK_READTRANS) {
756         code = udisk_abort(transPtr);
757         udisk_end(transPtr);
758         DBRELE(dbase);
759         return code;
760     }
761
762     /* below here, we know we're doing a write transaction */
763     if (!ubeacon_AmSyncSite()) {
764         udisk_abort(transPtr);
765         udisk_end(transPtr);
766         DBRELE(dbase);
767         return UNOTSYNC;
768     }
769
770     /* now it is safe to try remote abort */
771     code = ContactQuorum_NoArguments(DISK_Abort, transPtr, 0, "DISK_Abort");
772     code2 = udisk_abort(transPtr);
773     udisk_end(transPtr);
774     DBRELE(dbase);
775     return (code ? code : code2);
776 }
777
778 static void
779 WritebackApplicationCache(struct ubik_dbase *dbase)
780 {
781     int code = 0;
782     if (ubik_SyncWriterCacheProc) {
783         code = ubik_SyncWriterCacheProc();
784     }
785     if (code) {
786         /* we failed to sync the local cache, so just invalidate the cache;
787          * we'll try to read the cache in again on the next read */
788         memset(&dbase->cachedVersion, 0, sizeof(dbase->cachedVersion));
789     } else {
790         memcpy(&dbase->cachedVersion, &dbase->version,
791                sizeof(dbase->cachedVersion));
792     }
793 }
794
795 /*!
796  * \brief This routine ends a read or write transaction on the open transaction identified by transPtr.
797  * \return an error code.
798  */
799 int
800 ubik_EndTrans(struct ubik_trans *transPtr)
801 {
802     afs_int32 code;
803     struct timeval tv;
804     afs_int32 realStart;
805     struct ubik_server *ts;
806     afs_int32 now;
807     int cachelocked = 0;
808     struct ubik_dbase *dbase;
809
810     if (transPtr->type == UBIK_WRITETRANS) {
811         code = ubik_Flush(transPtr);
812         if (code) {
813             ubik_AbortTrans(transPtr);
814             return (code);
815         }
816     }
817
818     dbase = transPtr->dbase;
819
820     if (transPtr->flags & TRCACHELOCKED) {
821         ReleaseReadLock(&dbase->cache_lock);
822         transPtr->flags &= ~TRCACHELOCKED;
823     }
824
825     if (transPtr->type != UBIK_READTRANS) {
826         /* must hold cache_lock before DBHOLD'ing */
827         ObtainWriteLock(&dbase->cache_lock);
828         cachelocked = 1;
829     }
830
831     DBHOLD(dbase);
832
833     /* give up if no longer current */
834     if (!urecovery_AllBetter(dbase, transPtr->flags & TRREADANY)) {
835         udisk_abort(transPtr);
836         udisk_end(transPtr);
837         DBRELE(dbase);
838         code = UNOQUORUM;
839         goto error;
840     }
841
842     if (transPtr->type == UBIK_READTRANS) {     /* reads are easy */
843         code = udisk_commit(transPtr);
844         if (code == 0)
845             goto success;       /* update cachedVersion correctly */
846         udisk_end(transPtr);
847         DBRELE(dbase);
848         goto error;
849     }
850
851     if (!ubeacon_AmSyncSite()) {        /* no longer sync site */
852         udisk_abort(transPtr);
853         udisk_end(transPtr);
854         DBRELE(dbase);
855         code = UNOTSYNC;
856         goto error;
857     }
858
859     /* now it is safe to do commit */
860     code = udisk_commit(transPtr);
861     if (code == 0) {
862         /* db data has been committed locally; update the local cache so
863          * readers can get at it */
864         WritebackApplicationCache(dbase);
865
866         ReleaseWriteLock(&dbase->cache_lock);
867
868         code = ContactQuorum_NoArguments(DISK_Commit, transPtr, CStampVersion, "DISK_Commit");
869
870     } else {
871         memset(&dbase->cachedVersion, 0, sizeof(struct ubik_version));
872         ReleaseWriteLock(&dbase->cache_lock);
873     }
874     cachelocked = 0;
875     if (code) {
876         /* failed to commit, so must return failure.  Try to clear locks first, just for fun
877          * Note that we don't know if this transaction will eventually commit at this point.
878          * If it made it to a site that will be present in the next quorum, we win, otherwise
879          * we lose.  If we contact a majority of sites, then we won't be here: contacting
880          * a majority guarantees commit, since it guarantees that one dude will be a
881          * member of the next quorum. */
882         ContactQuorum_NoArguments(DISK_ReleaseLocks, transPtr, 0, "DISK_ReleaseLocks");
883         udisk_end(transPtr);
884         DBRELE(dbase);
885         goto error;
886     }
887     /* before we can start sending unlock messages, we must wait until all servers
888      * that are possibly still functioning on the other side of a network partition
889      * have timed out.  Check the server structures, compute how long to wait, then
890      * start the unlocks */
891     realStart = FT_ApproxTime();
892     while (1) {
893         /* wait for all servers to time out */
894         code = 0;
895         now = FT_ApproxTime();
896         /* check if we're still sync site, the guy should either come up
897          * to us, or timeout.  Put safety check in anyway */
898         if (now - realStart > 10 * BIGTIME) {
899             ubik_stats.escapes++;
900             ViceLog(0, ("ubik escaping from commit wait\n"));
901             break;
902         }
903         for (ts = ubik_servers; ts; ts = ts->next) {
904             UBIK_BEACON_LOCK;
905             if (!ts->beaconSinceDown && now <= ts->lastBeaconSent + BIGTIME) {
906                 UBIK_BEACON_UNLOCK;
907
908                 /* this guy could have some damaged data, wait for him */
909                 code = 1;
910                 tv.tv_sec = 1;  /* try again after a while (ha ha) */
911                 tv.tv_usec = 0;
912
913 #ifdef AFS_PTHREAD_ENV
914                 /* we could release the dbase outside of the loop, but we do
915                  * it here, in the loop, to avoid an unnecessary RELE/HOLD
916                  * if all sites are up */
917                 DBRELE(dbase);
918                 select(0, 0, 0, 0, &tv);
919                 DBHOLD(dbase);
920 #else
921                 IOMGR_Select(0, 0, 0, 0, &tv);  /* poll, should we wait on something? */
922 #endif
923
924                 break;
925             }
926             UBIK_BEACON_UNLOCK;
927         }
928         if (code == 0)
929             break;              /* no down ones still pseudo-active */
930     }
931
932     /* finally, unlock all the dudes.  We can return success independent of the number of servers
933      * that really unlock the dbase; the others will do it if/when they elect a new sync site.
934      * The transaction is committed anyway, since we succeeded in contacting a quorum
935      * at the start (when invoking the DiskCommit function).
936      */
937     ContactQuorum_NoArguments(DISK_ReleaseLocks, transPtr, 0, "DISK_ReleaseLocks");
938
939   success:
940     udisk_end(transPtr);
941     /* don't update cachedVersion here; it should have been updated way back
942      * in ubik_CheckCache, and earlier in this function for writes */
943     DBRELE(dbase);
944     if (cachelocked) {
945         ReleaseWriteLock(&dbase->cache_lock);
946     }
947     return 0;
948
949   error:
950     if (!cachelocked) {
951         ObtainWriteLock(&dbase->cache_lock);
952     }
953     memset(&dbase->cachedVersion, 0, sizeof(struct ubik_version));
954     ReleaseWriteLock(&dbase->cache_lock);
955     return code;
956 }
957
958 /*!
959  * \brief This routine reads length bytes into buffer from the current position in the database.
960  *
961  * 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.
962  *
963  * \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.
964  */
965 int
966 ubik_Read(struct ubik_trans *transPtr, void *buffer,
967           afs_int32 length)
968 {
969     afs_int32 code;
970
971     /* reads are easy to do: handle locally */
972     DBHOLD(transPtr->dbase);
973     if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY)) {
974         DBRELE(transPtr->dbase);
975         return UNOQUORUM;
976     }
977
978     code =
979         udisk_read(transPtr, transPtr->seekFile, buffer, transPtr->seekPos,
980                    length);
981     if (code == 0) {
982         transPtr->seekPos += length;
983     }
984     DBRELE(transPtr->dbase);
985     return code;
986 }
987
988 /*!
989  * \brief This routine will flush the io data in the iovec structures.
990  *
991  * It first flushes to the local disk and then uses ContactQuorum to write it
992  * to the other servers.
993  */
994 int
995 ubik_Flush(struct ubik_trans *transPtr)
996 {
997     afs_int32 code, error = 0;
998
999     if (transPtr->type != UBIK_WRITETRANS)
1000         return UBADTYPE;
1001
1002     DBHOLD(transPtr->dbase);
1003     if (!transPtr->iovec_info.iovec_wrt_len
1004         || !transPtr->iovec_info.iovec_wrt_val) {
1005         DBRELE(transPtr->dbase);
1006         return 0;
1007     }
1008
1009     if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY))
1010         ERROR_EXIT(UNOQUORUM);
1011     if (!ubeacon_AmSyncSite())  /* only sync site can write */
1012         ERROR_EXIT(UNOTSYNC);
1013
1014     /* Update the rest of the servers in the quorum */
1015     code =
1016         ContactQuorum_DISK_WriteV(transPtr, 0, &transPtr->iovec_info,
1017                                   &transPtr->iovec_data);
1018     if (code) {
1019         udisk_abort(transPtr);
1020         /* force aborts to the others */
1021         ContactQuorum_NoArguments(DISK_Abort, transPtr, 0, "DISK_Abort");
1022         transPtr->iovec_info.iovec_wrt_len = 0;
1023         transPtr->iovec_data.iovec_buf_len = 0;
1024         ERROR_EXIT(code);
1025     }
1026
1027     /* Wrote the buffers out, so start at scratch again */
1028     transPtr->iovec_info.iovec_wrt_len = 0;
1029     transPtr->iovec_data.iovec_buf_len = 0;
1030
1031   error_exit:
1032     DBRELE(transPtr->dbase);
1033     return error;
1034 }
1035
1036 int
1037 ubik_Write(struct ubik_trans *transPtr, void *vbuffer,
1038            afs_int32 length)
1039 {
1040     struct ubik_iovec *iovec;
1041     afs_int32 code, error = 0;
1042     afs_int32 pos, len, size;
1043     char * buffer = (char *)vbuffer;
1044
1045     if (transPtr->type != UBIK_WRITETRANS)
1046         return UBADTYPE;
1047     if (!length)
1048         return 0;
1049
1050     if (length > IOVEC_MAXBUF) {
1051         for (pos = 0, len = length; len > 0; len -= size, pos += size) {
1052             size = ((len < IOVEC_MAXBUF) ? len : IOVEC_MAXBUF);
1053             code = ubik_Write(transPtr, buffer+pos, size);
1054             if (code)
1055                 return (code);
1056         }
1057         return 0;
1058     }
1059
1060     DBHOLD(transPtr->dbase);
1061     if (!transPtr->iovec_info.iovec_wrt_val) {
1062         transPtr->iovec_info.iovec_wrt_len = 0;
1063         transPtr->iovec_info.iovec_wrt_val =
1064             malloc(IOVEC_MAXWRT * sizeof(struct ubik_iovec));
1065         transPtr->iovec_data.iovec_buf_len = 0;
1066         transPtr->iovec_data.iovec_buf_val = malloc(IOVEC_MAXBUF);
1067         if (!transPtr->iovec_info.iovec_wrt_val
1068             || !transPtr->iovec_data.iovec_buf_val) {
1069             if (transPtr->iovec_info.iovec_wrt_val)
1070                 free(transPtr->iovec_info.iovec_wrt_val);
1071             transPtr->iovec_info.iovec_wrt_val = 0;
1072             if (transPtr->iovec_data.iovec_buf_val)
1073                 free(transPtr->iovec_data.iovec_buf_val);
1074             transPtr->iovec_data.iovec_buf_val = 0;
1075             DBRELE(transPtr->dbase);
1076             return UNOMEM;
1077         }
1078     }
1079
1080     /* If this write won't fit in the structure, then flush it out and start anew */
1081     if ((transPtr->iovec_info.iovec_wrt_len >= IOVEC_MAXWRT)
1082         || ((length + transPtr->iovec_data.iovec_buf_len) > IOVEC_MAXBUF)) {
1083         /* Can't hold the DB lock over ubik_Flush */
1084         DBRELE(transPtr->dbase);
1085         code = ubik_Flush(transPtr);
1086         if (code)
1087             return (code);
1088         DBHOLD(transPtr->dbase);
1089     }
1090
1091     if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY))
1092         ERROR_EXIT(UNOQUORUM);
1093     if (!ubeacon_AmSyncSite())  /* only sync site can write */
1094         ERROR_EXIT(UNOTSYNC);
1095
1096     /* Write to the local disk */
1097     code =
1098         udisk_write(transPtr, transPtr->seekFile, buffer, transPtr->seekPos,
1099                     length);
1100     if (code) {
1101         udisk_abort(transPtr);
1102         transPtr->iovec_info.iovec_wrt_len = 0;
1103         transPtr->iovec_data.iovec_buf_len = 0;
1104         DBRELE(transPtr->dbase);
1105         return (code);
1106     }
1107
1108     /* Collect writes for the other ubik servers (to be done in bulk) */
1109     iovec = (struct ubik_iovec *)transPtr->iovec_info.iovec_wrt_val;
1110     iovec[transPtr->iovec_info.iovec_wrt_len].file = transPtr->seekFile;
1111     iovec[transPtr->iovec_info.iovec_wrt_len].position = transPtr->seekPos;
1112     iovec[transPtr->iovec_info.iovec_wrt_len].length = length;
1113
1114     memcpy(&transPtr->iovec_data.
1115            iovec_buf_val[transPtr->iovec_data.iovec_buf_len], buffer, length);
1116
1117     transPtr->iovec_info.iovec_wrt_len++;
1118     transPtr->iovec_data.iovec_buf_len += length;
1119     transPtr->seekPos += length;
1120
1121   error_exit:
1122     DBRELE(transPtr->dbase);
1123     return error;
1124 }
1125
1126 /*!
1127  * \brief This sets the file pointer associated with the current transaction
1128  * to the appropriate file and byte position.
1129  *
1130  * Unlike Unix files, a transaction is labelled by both a file number \p fileid
1131  * and a byte position relative to the specified file \p position.
1132  */
1133 int
1134 ubik_Seek(struct ubik_trans *transPtr, afs_int32 fileid,
1135           afs_int32 position)
1136 {
1137     afs_int32 code;
1138
1139     DBHOLD(transPtr->dbase);
1140     if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY)) {
1141         code = UNOQUORUM;
1142     } else {
1143         transPtr->seekFile = fileid;
1144         transPtr->seekPos = position;
1145         code = 0;
1146     }
1147     DBRELE(transPtr->dbase);
1148     return code;
1149 }
1150
1151 /*!
1152  * \brief This call returns the file pointer associated with the specified
1153  * transaction in \p fileid and \p position.
1154  */
1155 int
1156 ubik_Tell(struct ubik_trans *transPtr, afs_int32 * fileid,
1157           afs_int32 * position)
1158 {
1159     DBHOLD(transPtr->dbase);
1160     *fileid = transPtr->seekFile;
1161     *position = transPtr->seekPos;
1162     DBRELE(transPtr->dbase);
1163     return 0;
1164 }
1165
1166 /*!
1167  * \brief This sets the file size for the currently-selected file to \p length
1168  * bytes, if length is less than the file's current size.
1169  */
1170 int
1171 ubik_Truncate(struct ubik_trans *transPtr, afs_int32 length)
1172 {
1173     afs_int32 code, error = 0;
1174
1175     /* Will also catch if not UBIK_WRITETRANS */
1176     code = ubik_Flush(transPtr);
1177     if (code)
1178         return (code);
1179
1180     DBHOLD(transPtr->dbase);
1181     /* first, check that quorum is still good, and that dbase is up-to-date */
1182     if (!urecovery_AllBetter(transPtr->dbase, transPtr->flags & TRREADANY))
1183         ERROR_EXIT(UNOQUORUM);
1184     if (!ubeacon_AmSyncSite())
1185         ERROR_EXIT(UNOTSYNC);
1186
1187     /* now do the operation locally, and propagate it out */
1188     code = udisk_truncate(transPtr, transPtr->seekFile, length);
1189     if (!code) {
1190         code =
1191             ContactQuorum_DISK_Truncate(transPtr, 0, transPtr->seekFile,
1192                                         length);
1193     }
1194     if (code) {
1195         /* we must abort the operation */
1196         udisk_abort(transPtr);
1197         /* force aborts to the others */
1198         ContactQuorum_NoArguments(DISK_Abort, transPtr, 0, "DISK_Abort");
1199         ERROR_EXIT(code);
1200     }
1201
1202   error_exit:
1203     DBRELE(transPtr->dbase);
1204     return error;
1205 }
1206
1207 /*!
1208  * \brief set a lock; all locks are released on transaction end (commit/abort)
1209  */
1210 int
1211 ubik_SetLock(struct ubik_trans *atrans, afs_int32 apos, afs_int32 alen,
1212              int atype)
1213 {
1214     afs_int32 code = 0, error = 0;
1215
1216     if (atype == LOCKWRITE) {
1217         if (atrans->type == UBIK_READTRANS)
1218             return UBADTYPE;
1219         code = ubik_Flush(atrans);
1220         if (code)
1221             return (code);
1222     }
1223
1224     DBHOLD(atrans->dbase);
1225     if (atype == LOCKREAD) {
1226         code = ulock_getLock(atrans, atype, 1);
1227         if (code)
1228             ERROR_EXIT(code);
1229     } else {
1230         /* first, check that quorum is still good, and that dbase is up-to-date */
1231         if (!urecovery_AllBetter(atrans->dbase, atrans->flags & TRREADANY))
1232             ERROR_EXIT(UNOQUORUM);
1233         if (!ubeacon_AmSyncSite())
1234             ERROR_EXIT(UNOTSYNC);
1235
1236         /* now do the operation locally, and propagate it out */
1237         code = ulock_getLock(atrans, atype, 1);
1238         if (code == 0) {
1239             code = ContactQuorum_DISK_Lock(atrans, 0, 0, 1 /*unused */ ,
1240                                            1 /*unused */ , LOCKWRITE);
1241         }
1242         if (code) {
1243             /* we must abort the operation */
1244             udisk_abort(atrans);
1245             /* force aborts to the others */
1246             ContactQuorum_NoArguments(DISK_Abort, atrans, 0, "DISK_Abort");
1247             ERROR_EXIT(code);
1248         }
1249     }
1250
1251   error_exit:
1252     DBRELE(atrans->dbase);
1253     return error;
1254 }
1255
1256 /*!
1257  * \brief utility to wait for a version # to change
1258  */
1259 int
1260 ubik_WaitVersion(struct ubik_dbase *adatabase,
1261                  struct ubik_version *aversion)
1262 {
1263     DBHOLD(adatabase);
1264     while (1) {
1265         /* wait until version # changes, and then return */
1266         if (vcmp(*aversion, adatabase->version) != 0) {
1267             DBRELE(adatabase);
1268             return 0;
1269         }
1270 #ifdef AFS_PTHREAD_ENV
1271         opr_cv_wait(&adatabase->version_cond, &adatabase->versionLock);
1272 #else
1273         DBRELE(adatabase);
1274         LWP_WaitProcess(&adatabase->version);   /* same vers, just wait */
1275         DBHOLD(adatabase);
1276 #endif
1277     }
1278 }
1279
1280 /*!
1281  * \brief utility to get the version of the dbase a transaction is dealing with
1282  */
1283 int
1284 ubik_GetVersion(struct ubik_trans *atrans,
1285                 struct ubik_version *avers)
1286 {
1287     DBHOLD(atrans->dbase);
1288     *avers = atrans->dbase->version;
1289     DBRELE(atrans->dbase);
1290     return 0;
1291 }
1292
1293 /*!
1294  * \brief Facility to simplify database caching.
1295  * \return zero if last trans was done on the local server and was successful.
1296  * \return -1 means bad (NULL) argument.
1297  *
1298  * If return value is non-zero and the caller is a server caching part of the
1299  * Ubik database, it should invalidate that cache.
1300  */
1301 static int
1302 ubik_CacheUpdate(struct ubik_trans *atrans)
1303 {
1304     if (!(atrans && atrans->dbase))
1305         return -1;
1306     return vcmp(atrans->dbase->cachedVersion, atrans->dbase->version) != 0;
1307 }
1308
1309 /**
1310  * check and possibly update cache of ubik db.
1311  *
1312  * If the version of the cached db data is out of date, this calls (*check) to
1313  * update the cache. If (*check) returns success, we update the version of the
1314  * cached db data.
1315  *
1316  * Checking the version of the cached db data is done under a read lock;
1317  * updating the cache (and thus calling (*check)) is done under a write lock
1318  * so is guaranteed not to interfere with another thread's (*check). On
1319  * successful return, a read lock on the cached db data is obtained, which
1320  * will be released by ubik_EndTrans or ubik_AbortTrans.
1321  *
1322  * @param[in] atrans ubik transaction
1323  * @param[in] check  function to call to check/update cache
1324  * @param[in] rock   rock to pass to *check
1325  *
1326  * @return operation status
1327  *   @retval 0       success
1328  *   @retval nonzero error; cachedVersion not updated
1329  *
1330  * @post On success, application cache is read-locked, and cache data is
1331  *       up-to-date
1332  */
1333 int
1334 ubik_CheckCache(struct ubik_trans *atrans, ubik_updatecache_func cbf, void *rock)
1335 {
1336     int ret = 0;
1337
1338     if (!(atrans && atrans->dbase))
1339         return -1;
1340
1341     ObtainReadLock(&atrans->dbase->cache_lock);
1342
1343     while (ubik_CacheUpdate(atrans) != 0) {
1344
1345         ReleaseReadLock(&atrans->dbase->cache_lock);
1346         ObtainSharedLock(&atrans->dbase->cache_lock);
1347
1348         if (ubik_CacheUpdate(atrans) != 0) {
1349
1350             BoostSharedLock(&atrans->dbase->cache_lock);
1351
1352             ret = (*cbf) (atrans, rock);
1353             if (ret == 0) {
1354                 memcpy(&atrans->dbase->cachedVersion, &atrans->dbase->version,
1355                        sizeof(atrans->dbase->cachedVersion));
1356             }
1357         }
1358
1359         /* It would be nice if we could convert from a shared lock to a read
1360          * lock... instead, just release the shared and acquire the read */
1361         ReleaseSharedLock(&atrans->dbase->cache_lock);
1362
1363         if (ret) {
1364             /* if we have an error, don't retry, and don't hold any locks */
1365             return ret;
1366         }
1367
1368         ObtainReadLock(&atrans->dbase->cache_lock);
1369     }
1370
1371     atrans->flags |= TRCACHELOCKED;
1372
1373     return 0;
1374 }
1375
1376 /*!
1377  * "Who said anything about panicking?" snapped Arthur.
1378  * "This is still just the culture shock. You wait till I've settled down
1379  * into the situation and found my bearings. \em Then I'll start panicking!"
1380  * --Authur Dent
1381  *
1382  * \returns There is no return from panic.
1383  */
1384 void
1385 panic(char *format, ...)
1386 {
1387     va_list ap;
1388
1389     va_start(ap, format);
1390     ViceLog(0, ("Ubik PANIC:\n"));
1391     vViceLog(0, (format, ap));
1392     va_end(ap);
1393
1394     abort();
1395     ViceLog(0, ("BACK FROM ABORT\n"));  /* shouldn't come back */
1396     exit(1);                    /* never know, though  */
1397 }
1398
1399 /*!
1400  * This function takes an IP addresses as its parameter. It returns the
1401  * the primary IP address that is on the host passed in, or 0 if not found.
1402  */
1403 afs_uint32
1404 ubikGetPrimaryInterfaceAddr(afs_uint32 addr)
1405 {
1406     struct ubik_server *ts;
1407     int j;
1408
1409     UBIK_ADDR_LOCK;
1410     for (ts = ubik_servers; ts; ts = ts->next)
1411         for (j = 0; j < UBIK_MAX_INTERFACE_ADDR; j++)
1412             if (ts->addr[j] == addr) {
1413                 UBIK_ADDR_UNLOCK;
1414                 return ts->addr[0];     /* net byte order */
1415             }
1416     UBIK_ADDR_UNLOCK;
1417     return 0;                   /* if not in server database, return error */
1418 }
1419
1420 int
1421 ubik_CheckAuth(struct rx_call *acall)
1422 {
1423     if (checkSecurityProc)
1424         return (*checkSecurityProc) (securityRock, acall);
1425     else if (ubik_CheckRXSecurityProc) {
1426         return (*ubik_CheckRXSecurityProc) (ubik_CheckRXSecurityRock, acall);
1427     } else
1428         return 0;
1429 }
1430
1431 void
1432 ubik_SetServerSecurityProcs(void (*buildproc) (void *,
1433                                                struct rx_securityClass ***,
1434                                                afs_int32 *),
1435                             int (*checkproc) (void *, struct rx_call *),
1436                             void *rock)
1437 {
1438     buildSecClassesProc = buildproc;
1439     checkSecurityProc = checkproc;
1440     securityRock = rock;
1441 }