2 * Copyright 2000, International Business Machines Corporation and others.
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
10 #include <afsconfig.h>
11 #include <afs/param.h>
16 #ifdef AFS_PTHREAD_ENV
17 # include <opr/lock.h>
19 # include <opr/lockstub.h>
21 #include <afs/afsutil.h>
23 #define UBIK_INTERNALS
28 static struct buffer {
29 struct ubik_dbase *dbase; /*!< dbase within which the buffer resides */
30 afs_int32 file; /*!< Unique cache key */
31 afs_int32 page; /*!< page number */
32 struct buffer *lru_next;
33 struct buffer *lru_prev;
34 struct buffer *hashNext; /*!< next dude in hash table */
35 char *data; /*!< ptr to the data */
36 char lockers; /*!< usage ref count */
37 char dirty; /*!< is buffer modified */
38 char hashIndex; /*!< back ptr to hash table */
41 #define pHash(page) ((page) & (PHSIZE-1))
43 afs_int32 ubik_nBuffers = NBUFFERS;
44 static struct buffer *phTable[PHSIZE]; /*!< page hash table */
45 static struct buffer *LruBuffer;
47 static int calls = 0, ios = 0, lastb = 0;
48 static char *BufferData;
49 static struct buffer *newslot(struct ubik_dbase *adbase, afs_int32 afid,
51 #define BADFID 0xffffffff
53 static int DTrunc(struct ubik_trans *atrans, afs_int32 fid, afs_int32 length);
55 static struct ubik_trunc *freeTruncList = 0;
58 * \brief Remove a transaction from the database's active transaction list. Don't free it.
61 unthread(struct ubik_trans *atrans)
63 struct ubik_trans **lt, *tt;
64 lt = &atrans->dbase->activeTrans;
65 for (tt = *lt; tt; lt = &tt->next, tt = *lt) {
72 return 2; /* no entry */
76 * \brief some debugging assistance
79 udisk_Debug(struct ubik_debug *aparm)
84 memcpy(&aparm->localVersion, &ubik_dbase->version,
85 sizeof(struct ubik_version));
86 aparm->lockedPages = 0;
87 aparm->writeLockedPages = 0;
89 for (i = 0; i < nbuffers; i++, tb++) {
93 aparm->writeLockedPages++;
99 * \brief Write an opcode to the log.
101 * log format is defined here, and implicitly in recovery.c
103 * 4 byte opcode, followed by parameters, each 4 bytes long. All integers
104 * are in logged in network standard byte order, in case we want to move logs
105 * from machine-to-machine someday.
107 * Begin transaction: opcode \n
108 * Commit transaction: opcode, version (8 bytes) \n
109 * Truncate file: opcode, file number, length \n
110 * Abort transaction: opcode \n
111 * Write data: opcode, file, position, length, <length> data bytes \n
114 udisk_LogOpcode(struct ubik_dbase *adbase, afs_int32 aopcode, int async)
116 struct ubik_stat ustat;
119 /* figure out where to write */
120 code = (*adbase->stat) (adbase, LOGFILE, &ustat);
124 /* setup data and do write */
125 aopcode = htonl(aopcode);
127 (*adbase->write) (adbase, LOGFILE, (char *)&aopcode, ustat.size,
129 if (code != sizeof(afs_int32))
132 /* optionally sync data */
134 code = (*adbase->sync) (adbase, LOGFILE);
141 * \brief Log a commit, never syncing.
144 udisk_LogEnd(struct ubik_dbase *adbase, struct ubik_version *aversion)
148 struct ubik_stat ustat;
150 /* figure out where to write */
151 code = (*adbase->stat) (adbase, LOGFILE, &ustat);
156 data[0] = htonl(LOGEND);
157 data[1] = htonl(aversion->epoch);
158 data[2] = htonl(aversion->counter);
162 (*adbase->write) (adbase, LOGFILE, (char *)data, ustat.size,
163 3 * sizeof(afs_int32));
164 if (code != 3 * sizeof(afs_int32))
167 /* finally sync the log */
168 code = (*adbase->sync) (adbase, LOGFILE);
173 * \brief Log a truncate operation, never syncing.
176 udisk_LogTruncate(struct ubik_dbase *adbase, afs_int32 afile,
181 struct ubik_stat ustat;
183 /* figure out where to write */
184 code = (*adbase->stat) (adbase, LOGFILE, &ustat);
189 data[0] = htonl(LOGTRUNCATE);
190 data[1] = htonl(afile);
191 data[2] = htonl(alength);
195 (*adbase->write) (adbase, LOGFILE, (char *)data, ustat.size,
196 3 * sizeof(afs_int32));
197 if (code != 3 * sizeof(afs_int32))
203 * \brief Write some data to the log, never syncing.
206 udisk_LogWriteData(struct ubik_dbase *adbase, afs_int32 afile, void *abuffer,
207 afs_int32 apos, afs_int32 alen)
209 struct ubik_stat ustat;
214 /* find end of log */
215 code = (*adbase->stat) (adbase, LOGFILE, &ustat);
221 data[0] = htonl(LOGDATA);
222 data[1] = htonl(afile);
223 data[2] = htonl(apos);
224 data[3] = htonl(alen);
228 (*adbase->write) (adbase, LOGFILE, (char *)data, lpos, 4 * sizeof(afs_int32));
229 if (code != 4 * sizeof(afs_int32))
231 lpos += 4 * sizeof(afs_int32);
234 code = (*adbase->write) (adbase, LOGFILE, abuffer, lpos, alen);
241 udisk_Init(int abuffers)
243 /* Initialize the venus buffer system. */
246 Buffers = calloc(abuffers, sizeof(struct buffer));
247 BufferData = malloc(abuffers * UBIK_PAGESIZE);
249 for (i = 0; i < PHSIZE; i++)
251 for (i = 0; i < abuffers; i++) {
252 /* Fill in each buffer with an empty indication. */
254 tb->lru_next = &(Buffers[i + 1]);
255 tb->lru_prev = &(Buffers[i - 1]);
256 tb->data = &BufferData[UBIK_PAGESIZE * i];
259 Buffers[0].lru_prev = &(Buffers[abuffers - 1]);
260 Buffers[abuffers - 1].lru_next = &(Buffers[0]);
261 LruBuffer = &(Buffers[0]);
266 * \brief Take a buffer and mark it as the least recently used buffer.
269 Dlru(struct buffer *abuf)
271 if (LruBuffer == abuf)
274 /* Unthread from where it is in the list */
275 abuf->lru_next->lru_prev = abuf->lru_prev;
276 abuf->lru_prev->lru_next = abuf->lru_next;
278 /* Thread onto beginning of LRU list */
279 abuf->lru_next = LruBuffer;
280 abuf->lru_prev = LruBuffer->lru_prev;
282 LruBuffer->lru_prev->lru_next = abuf;
283 LruBuffer->lru_prev = abuf;
288 * \brief Take a buffer and mark it as the most recently used buffer.
291 Dmru(struct buffer *abuf)
293 if (LruBuffer == abuf) {
294 LruBuffer = LruBuffer->lru_next;
298 /* Unthread from where it is in the list */
299 abuf->lru_next->lru_prev = abuf->lru_prev;
300 abuf->lru_prev->lru_next = abuf->lru_next;
302 /* Thread onto end of LRU list - making it the MRU buffer */
303 abuf->lru_next = LruBuffer;
304 abuf->lru_prev = LruBuffer->lru_prev;
305 LruBuffer->lru_prev->lru_next = abuf;
306 LruBuffer->lru_prev = abuf;
310 MatchBuffer(struct buffer *buf, int page, afs_int32 fid,
311 struct ubik_trans *atrans)
313 if (buf->page != page) {
316 if (buf->file != fid) {
319 if (atrans->type == UBIK_READTRANS && buf->dirty) {
320 /* if 'buf' is dirty, it has uncommitted changes; we do not want to
321 * see uncommitted changes if we are a read transaction, so skip over
325 if (buf->dbase != atrans->dbase) {
332 * \brief Get a pointer to a particular buffer.
335 DRead(struct ubik_trans *atrans, afs_int32 fid, int page)
337 /* Read a page from the disk. */
338 struct buffer *tb, *lastbuffer, *found_tb = NULL;
340 struct ubik_dbase *dbase = atrans->dbase;
343 lastbuffer = LruBuffer->lru_prev;
345 /* Skip for write transactions for a clean page - this may not be the right page to use */
346 if (MatchBuffer(lastbuffer, page, fid, atrans)
347 && (atrans->type == UBIK_READTRANS || lastbuffer->dirty)) {
353 for (tb = phTable[pHash(page)]; tb; tb = tb->hashNext) {
354 if (MatchBuffer(tb, page, fid, atrans)) {
355 if (tb->dirty || atrans->type == UBIK_READTRANS) {
359 /* Remember this clean page - we might use it */
363 /* For a write transaction, use a matching clean page if no dirty one was found */
367 return found_tb->data;
371 tb = newslot(dbase, fid, page);
374 memset(tb->data, 0, UBIK_PAGESIZE);
378 (*dbase->read) (dbase, fid, tb->data, page * UBIK_PAGESIZE,
384 ViceLog(0, ("Ubik: Error reading database file: errno=%d\n", errno));
389 /* Note that findslot sets the page field in the buffer equal to
390 * what it is searching for.
396 * \brief Zap truncated pages.
399 DTrunc(struct ubik_trans *atrans, afs_int32 fid, afs_int32 length)
404 struct ubik_dbase *dbase = atrans->dbase;
406 maxPage = (length + UBIK_PAGESIZE - 1) >> UBIK_LOGPAGESIZE; /* first invalid page now in file */
407 for (i = 0, tb = Buffers; i < nbuffers; i++, tb++) {
408 if (tb->page >= maxPage && tb->file == fid && tb->dbase == dbase) {
417 * \brief Allocate a truncation entry.
419 * We allocate special entries representing truncations, rather than
420 * performing them immediately, so that we can abort a transaction easily by simply purging
421 * the in-core memory buffers and discarding these truncation entries.
423 static struct ubik_trunc *
426 struct ubik_trunc *tt;
427 if (!freeTruncList) {
428 freeTruncList = malloc(sizeof(struct ubik_trunc));
429 freeTruncList->next = (struct ubik_trunc *)0;
432 freeTruncList = tt->next;
437 * \brief Free a truncation entry.
440 PutTrunc(struct ubik_trunc *at)
442 at->next = freeTruncList;
448 * \brief Find a truncation entry for a file, if any.
450 static struct ubik_trunc *
451 FindTrunc(struct ubik_trans *atrans, afs_int32 afile)
453 struct ubik_trunc *tt;
454 for (tt = atrans->activeTruncs; tt; tt = tt->next) {
455 if (tt->file == afile)
458 return (struct ubik_trunc *)0;
462 * \brief Do truncates associated with \p atrans, and free them.
465 DoTruncs(struct ubik_trans *atrans)
467 struct ubik_trunc *tt, *nt;
468 int (*tproc) (struct ubik_dbase *, afs_int32, afs_int32);
469 afs_int32 rcode = 0, code;
471 tproc = atrans->dbase->truncate;
472 for (tt = atrans->activeTruncs; tt; tt = nt) {
474 DTrunc(atrans, tt->file, tt->length); /* zap pages from buffer cache */
475 code = (*tproc) (atrans->dbase, tt->file, tt->length);
480 /* don't unthread, because we do the entire list's worth here */
481 atrans->activeTruncs = (struct ubik_trunc *)0;
486 * \brief Mark an \p fid as invalid.
489 udisk_Invalidate(struct ubik_dbase *adbase, afs_int32 afid)
494 for (i = 0, tb = Buffers; i < nbuffers; i++, tb++) {
495 if (tb->file == afid) {
504 * \brief Move this page into the correct hash bucket.
507 FixupBucket(struct buffer *ap)
509 struct buffer **lp, *tp;
511 /* first try to get it out of its current hash bucket, in which it might not be */
514 for (tp = *lp; tp; tp = tp->hashNext) {
521 /* now figure the new hash bucket */
523 ap->hashIndex = i; /* remember where we are for deletion */
524 ap->hashNext = phTable[i]; /* add us to the list */
530 * \brief Create a new slot for a particular dbase page.
532 static struct buffer *
533 newslot(struct ubik_dbase *adbase, afs_int32 afid, afs_int32 apage)
535 /* Find a usable buffer slot */
537 struct buffer *pp, *tp;
539 pp = 0; /* last pure */
540 for (i = 0, tp = LruBuffer; i < nbuffers; i++, tp = tp->lru_next) {
541 if (!tp->lockers && !tp->dirty) {
548 /* There are no unlocked buffers that don't need to be written to the disk. */
549 ViceLog(0, ("Ubik: Internal Error: Unable to find free buffer in ubik cache\n"));
553 /* Now fill in the header. */
558 FixupBucket(pp); /* move to the right hash bucket */
564 * \brief Release a buffer, specifying whether or not the buffer has been modified by the locker.
567 DRelease(char *ap, int flag)
574 index = (int)(ap - (char *)BufferData) >> UBIK_LOGPAGESIZE;
575 bp = &(Buffers[index]);
583 * \brief Flush all modified buffers, leaves dirty bits set (they're cleared
586 * \note Note interaction with DSync(): you call this thing first,
587 * writing the buffers to the disk. Then you call DSync() to sync all the
588 * files that were written, and to clear the dirty bits. You should
589 * always call DFlush/DSync as a pair.
592 DFlush(struct ubik_trans *atrans)
597 struct ubik_dbase *adbase = atrans->dbase;
600 for (i = 0; i < nbuffers; i++, tb++) {
602 code = tb->page * UBIK_PAGESIZE; /* offset within file */
604 (*adbase->write) (adbase, tb->file, tb->data, code,
606 if (code != UBIK_PAGESIZE)
614 * \brief Flush all modified buffers.
617 DAbort(struct ubik_trans *atrans)
623 for (i = 0; i < nbuffers; i++, tb++) {
634 * Invalidate any buffers that are duplicates of abuf. Duplicate buffers
635 * can appear if a read transaction reads a page that is dirty, then that
636 * dirty page is synced. The read transaction will skip over the dirty page,
637 * and create a new buffer, and when the dirty page is synced, it will be
638 * identical (except for contents) to the read-transaction buffer.
641 DedupBuffer(struct buffer *abuf)
644 for (tb = phTable[pHash(abuf->page)]; tb; tb = tb->hashNext) {
645 if (tb->page == abuf->page && tb != abuf && tb->file == abuf->file
646 && tb->dbase == abuf->dbase) {
655 * \attention DSync() must only be called after DFlush(), due to its interpretation of dirty flag.
658 DSync(struct ubik_trans *atrans)
665 struct ubik_dbase *adbase = atrans->dbase;
670 for (i = 0, tb = Buffers; i < nbuffers; i++, tb++) {
671 if (tb->dirty == 1) {
674 if (file != BADFID && tb->file == file) {
682 /* otherwise we have a file to sync */
683 code = (*adbase->sync) (adbase, file);
691 * \brief Same as DRead(), only do not even try to read the page.
694 DNew(struct ubik_trans *atrans, afs_int32 fid, int page)
697 struct ubik_dbase *dbase = atrans->dbase;
699 if ((tb = newslot(dbase, fid, page)) == 0)
702 memset(tb->data, 0, UBIK_PAGESIZE);
707 * \brief Read data from database.
710 udisk_read(struct ubik_trans *atrans, afs_int32 afile, void *abuffer,
711 afs_int32 apos, afs_int32 alen)
714 afs_int32 offset, len, totalLen;
716 if (atrans->flags & TRDONE)
720 bp = DRead(atrans, afile, apos >> UBIK_LOGPAGESIZE);
723 /* otherwise, min of remaining bytes and end of buffer to user mode */
724 offset = apos & (UBIK_PAGESIZE - 1);
725 len = UBIK_PAGESIZE - offset;
728 memcpy(abuffer, bp + offset, len);
729 abuffer = (char *)abuffer + len;
739 * \brief Truncate file.
742 udisk_truncate(struct ubik_trans *atrans, afs_int32 afile, afs_int32 alength)
745 struct ubik_trunc *tt;
747 if (atrans->flags & TRDONE)
749 if (atrans->type != UBIK_WRITETRANS)
752 /* write a truncate log record */
753 code = udisk_LogTruncate(atrans->dbase, afile, alength);
755 /* don't truncate until commit time */
756 tt = FindTrunc(atrans, afile);
758 /* this file not truncated yet */
760 tt->next = atrans->activeTruncs;
761 atrans->activeTruncs = tt;
763 tt->length = alength;
765 /* already truncated to a certain length */
766 if (tt->length > alength)
767 tt->length = alength;
773 * \brief Write data to database, using logs.
776 udisk_write(struct ubik_trans *atrans, afs_int32 afile, void *abuffer,
777 afs_int32 apos, afs_int32 alen)
780 afs_int32 offset, len, totalLen;
781 struct ubik_trunc *tt;
784 if (atrans->flags & TRDONE)
786 if (atrans->type != UBIK_WRITETRANS)
789 /* first write the data to the log */
790 code = udisk_LogWriteData(atrans->dbase, afile, abuffer, apos, alen);
794 /* expand any truncations of this file */
795 tt = FindTrunc(atrans, afile);
797 if (tt->length < apos + alen) {
798 tt->length = apos + alen;
805 bp = DRead(atrans, afile, apos >> UBIK_LOGPAGESIZE);
807 bp = DNew(atrans, afile, apos >> UBIK_LOGPAGESIZE);
811 /* otherwise, min of remaining bytes and end of buffer to user mode */
812 offset = apos & (UBIK_PAGESIZE - 1);
813 len = UBIK_PAGESIZE - offset;
816 memcpy(bp + offset, abuffer, len);
817 abuffer = (char *)abuffer + len;
821 DRelease(bp, 1); /* buffer modified */
827 * \brief Begin a new local transaction.
830 udisk_begin(struct ubik_dbase *adbase, int atype, struct ubik_trans **atrans)
833 struct ubik_trans *tt;
836 if (atype == UBIK_WRITETRANS) {
837 if (adbase->flags & DBWRITING)
839 code = udisk_LogOpcode(adbase, LOGNEW, 0);
843 tt = calloc(1, sizeof(struct ubik_trans));
845 tt->next = adbase->activeTrans;
846 adbase->activeTrans = tt;
848 if (atype == UBIK_READTRANS)
850 else if (atype == UBIK_WRITETRANS) {
852 adbase->flags |= DBWRITING;
860 * \brief Commit transaction.
863 udisk_commit(struct ubik_trans *atrans)
865 struct ubik_dbase *dbase;
867 struct ubik_version oldversion, newversion;
868 afs_int32 now = FT_ApproxTime();
870 if (atrans->flags & TRDONE)
873 if (atrans->type == UBIK_WRITETRANS) {
874 dbase = atrans->dbase;
876 /* On the first write to the database. We update the versions */
877 if (ubeacon_AmSyncSite() && !(urecovery_state & UBIK_RECLABELDB)) {
879 if (version_globals.ubik_epochTime < UBIK_MILESTONE
880 || version_globals.ubik_epochTime > now) {
882 ("Ubik: New database label %d is out of the valid range (%d - %d)\n",
883 version_globals.ubik_epochTime, UBIK_MILESTONE, now));
884 panic("Writing Ubik DB label\n");
886 oldversion = dbase->version;
887 newversion.epoch = version_globals.ubik_epochTime;
888 newversion.counter = 1;
890 code = (*dbase->setlabel) (dbase, 0, &newversion);
896 dbase->version = newversion;
899 urecovery_state |= UBIK_RECLABELDB;
901 /* Ignore the error here. If the call fails, the site is
902 * marked down and when we detect it is up again, we will
903 * send the entire database to it.
905 ContactQuorum_DISK_SetVersion( atrans, 1 /*CStampVersion */ ,
906 &oldversion, &newversion);
910 dbase->version.counter++; /* bump commit count */
911 #ifdef AFS_PTHREAD_ENV
912 opr_cv_broadcast(&dbase->version_cond);
914 LWP_NoYieldSignal(&dbase->version);
916 code = udisk_LogEnd(dbase, &dbase->version);
918 dbase->version.counter--;
924 /* If we fail anytime after this, then panic and let the
925 * recovery replay the log.
927 code = DFlush(atrans); /* write dirty pages to respective files */
929 panic("Writing Ubik DB modifications\n");
930 code = DSync(atrans); /* sync the files and mark pages not dirty */
932 panic("Synchronizing Ubik DB modifications\n");
934 code = DoTruncs(atrans); /* Perform requested truncations */
936 panic("Truncating Ubik DB\n");
938 /* label the committed dbase */
939 code = (*dbase->setlabel) (dbase, 0, &dbase->version);
941 panic("Truncating Ubik DB\n");
943 code = (*dbase->truncate) (dbase, LOGFILE, 0); /* discard log (optional) */
945 panic("Truncating Ubik logfile\n");
949 /* When the transaction is marked done, it also means the logfile
950 * has been truncated.
952 atrans->flags |= TRDONE;
957 * \brief Abort transaction.
960 udisk_abort(struct ubik_trans *atrans)
962 struct ubik_dbase *dbase;
965 if (atrans->flags & TRDONE)
968 /* Check if we are the write trans before logging abort, lest we
969 * abort a good write trans in progress.
970 * We don't really care if the LOGABORT gets to the log because we
971 * truncate the log next. If the truncate fails, we panic; for
972 * otherwise, the log entries remain. On restart, replay of the log
973 * will do nothing because the abort is there or no LogEnd opcode.
975 dbase = atrans->dbase;
976 if (atrans->type == UBIK_WRITETRANS && dbase->flags & DBWRITING) {
977 udisk_LogOpcode(dbase, LOGABORT, 1);
978 code = (*dbase->truncate) (dbase, LOGFILE, 0);
980 panic("Truncating Ubik logfile during an abort\n");
981 DAbort(atrans); /* remove all dirty pages */
984 /* When the transaction is marked done, it also means the logfile
985 * has been truncated.
987 atrans->flags |= (TRABORT | TRDONE);
992 * \brief Destroy a transaction after it has been committed or aborted.
994 * If it hasn't committed before you call this routine, we'll abort the
995 * transaction for you.
998 udisk_end(struct ubik_trans *atrans)
1000 struct ubik_dbase *dbase;
1002 if (!(atrans->flags & TRDONE))
1003 udisk_abort(atrans);
1004 dbase = atrans->dbase;
1006 ulock_relLock(atrans);
1009 /* check if we are the write trans before unsetting the DBWRITING bit, else
1010 * we could be unsetting someone else's bit.
1012 if (atrans->type == UBIK_WRITETRANS && dbase->flags & DBWRITING) {
1014 dbase->flags &= ~DBWRITING;
1015 UBIK_VERSION_UNLOCK;
1019 if (atrans->iovec_info.iovec_wrt_val)
1020 free(atrans->iovec_info.iovec_wrt_val);
1021 if (atrans->iovec_data.iovec_buf_val)
1022 free(atrans->iovec_data.iovec_buf_val);
1025 /* Wakeup any writers waiting in BeginTrans() */
1026 #ifdef AFS_PTHREAD_ENV
1027 opr_cv_broadcast(&dbase->flags_cond);
1029 LWP_NoYieldSignal(&dbase->flags);