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