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