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