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