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