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