1 #LyX 1.6.5 created this file. For more info see http://www.lyx.org/
6 \use_default_options true
11 \font_typewriter default
12 \font_default_family default
19 \paperfontsize default
27 \paperorientation portrait
30 \paragraph_separation indent
32 \quotes_language english
35 \paperpagestyle default
36 \tracking_changes true
38 \author "Rusty Russell,,,"
45 TDB2: A Redesigning The Trivial DataBase
49 Rusty Russell, IBM Corporation
54 \change_deleted 0 1283307542
56 \change_inserted 0 1284016854
62 \begin_layout Abstract
63 The Trivial DataBase on-disk format is 32 bits; with usage cases heading
64 towards the 4G limit, that must change.
65 This required breakage provides an opportunity to revisit TDB's other design
66 decisions and reassess them.
73 \begin_layout Standard
74 The Trivial DataBase was originally written by Andrew Tridgell as a simple
75 key/data pair storage system with the same API as dbm, but allowing multiple
76 readers and writers while being small enough (< 1000 lines of C) to include
78 The simple design created in 1999 has proven surprisingly robust and performant
79 , used in Samba versions 3 and 4 as well as numerous other projects.
80 Its useful life was greatly increased by the (backwards-compatible!) addition
81 of transaction support in 2005.
84 \begin_layout Standard
85 The wider variety and greater demands of TDB-using code has lead to some
86 organic growth of the API, as well as some compromises on the implementation.
87 None of these, by themselves, are seen as show-stoppers, but the cumulative
88 effect is to a loss of elegance over the initial, simple TDB implementation.
89 Here is a table of the approximate number of lines of implementation code
90 and number of API functions at the end of each year:
93 \begin_layout Standard
95 <lyxtabular version="3" rows="12" columns="3">
97 <column alignment="center" valignment="top" width="0">
98 <column alignment="center" valignment="top" width="0">
99 <column alignment="center" valignment="top" width="0">
101 <cell alignment="center" valignment="top" topline="true" bottomline="true" leftline="true" usebox="none">
104 \begin_layout Plain Layout
110 <cell alignment="center" valignment="top" topline="true" bottomline="true" leftline="true" usebox="none">
113 \begin_layout Plain Layout
119 <cell alignment="center" valignment="top" topline="true" bottomline="true" leftline="true" rightline="true" usebox="none">
122 \begin_layout Plain Layout
123 Lines of C Code Implementation
130 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
133 \begin_layout Plain Layout
139 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
142 \begin_layout Plain Layout
148 <cell alignment="center" valignment="top" topline="true" leftline="true" rightline="true" usebox="none">
151 \begin_layout Plain Layout
159 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
162 \begin_layout Plain Layout
168 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
171 \begin_layout Plain Layout
177 <cell alignment="center" valignment="top" topline="true" leftline="true" rightline="true" usebox="none">
180 \begin_layout Plain Layout
188 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
191 \begin_layout Plain Layout
197 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
200 \begin_layout Plain Layout
206 <cell alignment="center" valignment="top" topline="true" leftline="true" rightline="true" usebox="none">
209 \begin_layout Plain Layout
217 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
220 \begin_layout Plain Layout
226 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
229 \begin_layout Plain Layout
235 <cell alignment="center" valignment="top" topline="true" leftline="true" rightline="true" usebox="none">
238 \begin_layout Plain Layout
246 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
249 \begin_layout Plain Layout
255 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
258 \begin_layout Plain Layout
264 <cell alignment="center" valignment="top" topline="true" leftline="true" rightline="true" usebox="none">
267 \begin_layout Plain Layout
275 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
278 \begin_layout Plain Layout
284 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
287 \begin_layout Plain Layout
293 <cell alignment="center" valignment="top" topline="true" leftline="true" rightline="true" usebox="none">
296 \begin_layout Plain Layout
304 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
307 \begin_layout Plain Layout
313 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
316 \begin_layout Plain Layout
322 <cell alignment="center" valignment="top" topline="true" leftline="true" rightline="true" usebox="none">
325 \begin_layout Plain Layout
333 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
336 \begin_layout Plain Layout
342 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
345 \begin_layout Plain Layout
351 <cell alignment="center" valignment="top" topline="true" leftline="true" rightline="true" usebox="none">
354 \begin_layout Plain Layout
362 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
365 \begin_layout Plain Layout
371 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
374 \begin_layout Plain Layout
380 <cell alignment="center" valignment="top" topline="true" leftline="true" rightline="true" usebox="none">
383 \begin_layout Plain Layout
391 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
394 \begin_layout Plain Layout
400 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
403 \begin_layout Plain Layout
409 <cell alignment="center" valignment="top" topline="true" leftline="true" rightline="true" usebox="none">
412 \begin_layout Plain Layout
420 <cell alignment="center" valignment="top" topline="true" bottomline="true" leftline="true" usebox="none">
423 \begin_layout Plain Layout
429 <cell alignment="center" valignment="top" topline="true" bottomline="true" leftline="true" usebox="none">
432 \begin_layout Plain Layout
438 <cell alignment="center" valignment="top" topline="true" bottomline="true" leftline="true" rightline="true" usebox="none">
441 \begin_layout Plain Layout
455 \begin_layout Standard
456 This review is an attempt to catalog and address all the known issues with
457 TDB and create solutions which address the problems without significantly
458 increasing complexity; all involved are far too aware of the dangers of
459 second system syndrome in rewriting a successful project like this.
462 \begin_layout Section
466 \begin_layout Subsection
467 tdb_open_ex Is Not Expandable
470 \begin_layout Standard
471 The tdb_open() call was expanded to tdb_open_ex(), which added an optional
472 hashing function and an optional logging function argument.
473 Additional arguments to open would require the introduction of a tdb_open_ex2
477 \begin_layout Subsubsection
481 \begin_layout Standard
482 tdb_open() will take a linked-list of attributes:
485 \begin_layout LyX-Code
489 \begin_layout LyX-Code
490 TDB_ATTRIBUTE_LOG = 0,
493 \begin_layout LyX-Code
494 TDB_ATTRIBUTE_HASH = 1
497 \begin_layout LyX-Code
501 \begin_layout LyX-Code
502 struct tdb_attribute_base {
505 \begin_layout LyX-Code
506 enum tdb_attribute attr;
509 \begin_layout LyX-Code
510 union tdb_attribute *next;
513 \begin_layout LyX-Code
517 \begin_layout LyX-Code
518 struct tdb_attribute_log {
521 \begin_layout LyX-Code
522 struct tdb_attribute_base base; /* .attr = TDB_ATTRIBUTE_LOG */
525 \begin_layout LyX-Code
529 \begin_layout LyX-Code
533 \begin_layout LyX-Code
537 \begin_layout LyX-Code
538 struct tdb_attribute_hash {
541 \begin_layout LyX-Code
542 struct tdb_attribute_base base; /* .attr = TDB_ATTRIBUTE_HASH */
545 \begin_layout LyX-Code
546 tdb_hash_func hash_fn;
549 \begin_layout LyX-Code
553 \begin_layout LyX-Code
557 \begin_layout LyX-Code
558 union tdb_attribute {
561 \begin_layout LyX-Code
562 struct tdb_attribute_base base;
565 \begin_layout LyX-Code
566 struct tdb_attribute_log log;
569 \begin_layout LyX-Code
570 struct tdb_attribute_hash hash;
573 \begin_layout LyX-Code
577 \begin_layout Standard
578 This allows future attributes to be added, even if this expands the size
582 \begin_layout Subsection
583 tdb_traverse Makes Impossible Guarantees
586 \begin_layout Standard
587 tdb_traverse (and tdb_firstkey/tdb_nextkey) predate transactions, and it
588 was thought that it was important to guarantee that all records which exist
589 at the start and end of the traversal would be included, and no record
590 would be included twice.
593 \begin_layout Standard
594 This adds complexity (see
595 \begin_inset CommandInset ref
597 reference "Reliable-Traversal-Adds"
601 ) and does not work anyway for records which are altered (in particular,
602 those which are expanded may be effectively deleted and re-added behind
606 \begin_layout Subsubsection
607 \begin_inset CommandInset label
609 name "traverse-Proposed-Solution"
616 \begin_layout Standard
617 Abandon the guarantee.
618 You will see every record if no changes occur during your traversal, otherwise
619 you will see some subset.
620 You can prevent changes by using a transaction or the locking API.
623 \begin_layout Subsection
624 Nesting of Transactions Is Fraught
627 \begin_layout Standard
628 TDB has alternated between allowing nested transactions and not allowing
630 Various paths in the Samba codebase assume that transactions will nest,
631 and in a sense they can: the operation is only committed to disk when the
632 outer transaction is committed.
633 There are two problems, however:
636 \begin_layout Enumerate
637 Canceling the inner transaction will cause the outer transaction commit
638 to fail, and will not undo any operations since the inner transaction began.
639 This problem is soluble with some additional internal code.
642 \begin_layout Enumerate
643 An inner transaction commit can be cancelled by the outer transaction.
644 This is desirable in the way which Samba's database initialization code
645 uses transactions, but could be a surprise to any users expecting a successful
646 transaction commit to expose changes to others.
649 \begin_layout Standard
650 The current solution is to specify the behavior at tdb_open(), with the
651 default currently that nested transactions are allowed.
652 This flag can also be changed at runtime.
655 \begin_layout Subsubsection
659 \begin_layout Standard
660 Given the usage patterns, it seems that the
661 \begin_inset Quotes eld
665 \begin_inset Quotes erd
668 behavior of disallowing nested transactions should become the default.
669 Additionally, it seems the outer transaction is the only code which knows
670 whether inner transactions should be allowed, so a flag to indicate this
671 could be added to tdb_transaction_start.
672 However, this behavior can be simulated with a wrapper which uses tdb_add_flags
673 () and tdb_remove_flags(), so the API should not be expanded for this relatively
677 \begin_layout Subsection
678 Incorrect Hash Function is Not Detected
681 \begin_layout Standard
682 tdb_open_ex() allows the calling code to specify a different hash function
683 to use, but does not check that all other processes accessing this tdb
684 are using the same hash function.
685 The result is that records are missing from tdb_fetch().
688 \begin_layout Subsubsection
692 \begin_layout Standard
693 The header should contain an example hash result (eg.
694 the hash of 0xdeadbeef), and tdb_open_ex() should check that the given
695 hash function produces the same answer, or fail the tdb_open call.
698 \begin_layout Subsection
699 tdb_set_max_dead/TDB_VOLATILE Expose Implementation
702 \begin_layout Standard
703 In response to scalability issues with the free list (
704 \begin_inset CommandInset ref
706 reference "TDB-Freelist-Is"
710 ) two API workarounds have been incorporated in TDB: tdb_set_max_dead()
711 and the TDB_VOLATILE flag to tdb_open.
712 The latter actually calls the former with an argument of
713 \begin_inset Quotes eld
717 \begin_inset Quotes erd
723 \begin_layout Standard
724 This code allows deleted records to accumulate without putting them in the
726 On delete we iterate through each chain and free them in a batch if there
727 are more than max_dead entries.
728 These are never otherwise recycled except as a side-effect of a tdb_repack.
731 \begin_layout Subsubsection
735 \begin_layout Standard
736 With the scalability problems of the freelist solved, this API can be removed.
737 The TDB_VOLATILE flag may still be useful as a hint that store and delete
738 of records will be at least as common as fetch in order to allow some internal
739 tuning, but initially will become a no-op.
742 \begin_layout Subsection
743 \begin_inset CommandInset label
745 name "TDB-Files-Cannot"
749 TDB Files Cannot Be Opened Multiple Times In The Same Process
752 \begin_layout Standard
753 No process can open the same TDB twice; we check and disallow it.
754 This is an unfortunate side-effect of fcntl locks, which operate on a per-file
755 rather than per-file-descriptor basis, and do not nest.
756 Thus, closing any file descriptor on a file clears all the locks obtained
757 by this process, even if they were placed using a different file descriptor!
760 \begin_layout Standard
761 Note that even if this were solved, deadlock could occur if operations were
762 nested: this is a more manageable programming error in most cases.
765 \begin_layout Subsubsection
769 \begin_layout Standard
770 We could lobby POSIX to fix the perverse rules, or at least lobby Linux
771 to violate them so that the most common implementation does not have this
773 This would be a generally good idea for other fcntl lock users.
776 \begin_layout Standard
777 Samba uses a wrapper which hands out the same tdb_context to multiple callers
778 if this happens, and does simple reference counting.
779 We should do this inside the tdb library, which already emulates lock nesting
780 internally; it would need to recognize when deadlock occurs within a single
782 This would create a new failure mode for tdb operations (while we currently
783 handle locking failures, they are impossible in normal use and a process
784 encountering them can do little but give up).
787 \begin_layout Standard
788 I do not see benefit in an additional tdb_open flag to indicate whether
789 re-opening is allowed, as though there may be some benefit to adding a
790 call to detect when a tdb_context is shared, to allow other to create such
794 \begin_layout Subsection
795 TDB API Is Not POSIX Thread-safe
798 \begin_layout Standard
799 The TDB API uses an error code which can be queried after an operation to
800 determine what went wrong.
801 This programming model does not work with threads, unless specific additional
802 guarantees are given by the implementation.
803 In addition, even otherwise-independent threads cannot open the same TDB
805 \begin_inset CommandInset ref
807 reference "TDB-Files-Cannot"
814 \begin_layout Subsubsection
818 \begin_layout Standard
819 Reachitecting the API to include a tdb_errcode pointer would be a great
820 deal of churn; we are better to guarantee that the tdb_errcode is per-thread
821 so the current programming model can be maintained.
824 \begin_layout Standard
825 This requires dynamic per-thread allocations, which is awkward with POSIX
826 threads (pthread_key_create space is limited and we cannot simply allocate
827 a key for every TDB).
830 \begin_layout Standard
831 Internal locking is required to make sure that fcntl locks do not overlap
832 between threads, and also that the global list of tdbs is maintained.
835 \begin_layout Standard
836 The aim is that building tdb with -DTDB_PTHREAD will result in a pthread-safe
837 version of the library, and otherwise no overhead will exist.
839 \change_inserted 0 1284016998
840 Alternatively, a hooking mechanism similar to that proposed for
841 \begin_inset CommandInset ref
843 reference "Proposed-Solution-locking-hook"
847 could be used to enable pthread locking at runtime.
852 \begin_layout Subsection
853 *_nonblock Functions And *_mark Functions Expose Implementation
856 \begin_layout Standard
861 \begin_layout Plain Layout
862 Clustered TDB, see http://ctdb.samba.org
867 wishes to operate on TDB in a non-blocking manner.
868 This is currently done as follows:
871 \begin_layout Enumerate
872 Call the _nonblock variant of an API function (eg.
873 tdb_lockall_nonblock).
877 \begin_layout Enumerate
878 Fork a child process, and wait for it to call the normal variant (eg.
882 \begin_layout Enumerate
883 If the child succeeds, call the _mark variant to indicate we already have
888 \begin_layout Enumerate
889 Upon completion, tell the child to release the locks (eg.
893 \begin_layout Enumerate
894 Indicate to tdb that it should consider the locks removed (eg.
898 \begin_layout Standard
899 There are several issues with this approach.
900 Firstly, adding two new variants of each function clutters the API for
901 an obscure use, and so not all functions have three variants.
902 Secondly, it assumes that all paths of the functions ask for the same locks,
903 otherwise the parent process will have to get a lock which the child doesn't
904 have under some circumstances.
905 I don't believe this is currently the case, but it constrains the implementatio
910 \begin_layout Subsubsection
911 \begin_inset CommandInset label
913 name "Proposed-Solution-locking-hook"
920 \begin_layout Standard
921 Implement a hook for locking methods, so that the caller can control the
922 calls to create and remove fcntl locks.
923 In this scenario, ctdbd would operate as follows:
926 \begin_layout Enumerate
927 Call the normal API function, eg tdb_lockall().
930 \begin_layout Enumerate
931 When the lock callback comes in, check if the child has the lock.
932 Initially, this is always false.
934 Otherwise, try to obtain it in non-blocking mode.
935 If that fails, return EWOULDBLOCK.
938 \begin_layout Enumerate
939 Release locks in the unlock callback as normal.
942 \begin_layout Enumerate
943 If tdb_lockall() fails, see if we recorded a lock failure; if so, call the
944 child to repeat the operation.
947 \begin_layout Enumerate
948 The child records what locks it obtains, and returns that information to
952 \begin_layout Enumerate
953 When the child has succeeded, goto 1.
956 \begin_layout Standard
957 This is flexible enough to handle any potential locking scenario, even when
958 lock requirements change.
959 It can be optimized so that the parent does not release locks, just tells
960 the child which locks it doesn't need to obtain.
963 \begin_layout Standard
964 It also keeps the complexity out of the API, and in ctdbd where it is needed.
967 \begin_layout Subsection
968 tdb_chainlock Functions Expose Implementation
971 \begin_layout Standard
972 tdb_chainlock locks some number of records, including the record indicated
974 This gave atomicity guarantees; no-one can start a transaction, alter,
975 read or delete that key while the lock is held.
978 \begin_layout Standard
979 It also makes the same guarantee for any other key in the chain, which is
980 an internal implementation detail and potentially a cause for deadlock.
983 \begin_layout Subsubsection
987 \begin_layout Standard
989 It would be nice to have an explicit single entry lock which effected no
991 Unfortunately, this won't work for an entry which doesn't exist.
992 Thus while chainlock may be implemented more efficiently for the existing
993 case, it will still have overlap issues with the non-existing case.
994 So it is best to keep the current (lack of) guarantee about which records
995 will be effected to avoid constraining our implementation.
998 \begin_layout Subsection
999 Signal Handling is Not Race-Free
1002 \begin_layout Standard
1003 The tdb_setalarm_sigptr() call allows the caller's signal handler to indicate
1004 that the tdb locking code should return with a failure, rather than trying
1005 again when a signal is received (and errno == EAGAIN).
1006 This is usually used to implement timeouts.
1009 \begin_layout Standard
1010 Unfortunately, this does not work in the case where the signal is received
1011 before the tdb code enters the fcntl() call to place the lock: the code
1012 will sleep within the fcntl() code, unaware that the signal wants it to
1014 In the case of long timeouts, this does not happen in practice.
1017 \begin_layout Subsubsection
1021 \begin_layout Standard
1022 The locking hooks proposed in
1023 \begin_inset CommandInset ref
1025 reference "Proposed-Solution-locking-hook"
1029 would allow the user to decide on whether to fail the lock acquisition
1031 This allows the caller to choose their own compromise: they could narrow
1032 the race by checking immediately before the fcntl call.
1036 \begin_layout Plain Layout
1037 It may be possible to make this race-free in some implementations by having
1038 the signal handler alter the struct flock to make it invalid.
1039 This will cause the fcntl() lock call to fail with EINVAL if the signal
1040 occurs before the kernel is entered, otherwise EAGAIN.
1048 \begin_layout Subsection
1049 The API Uses Gratuitous Typedefs, Capitals
1052 \begin_layout Standard
1053 typedefs are useful for providing source compatibility when types can differ
1054 across implementations, or arguably in the case of function pointer definitions
1055 which are hard for humans to parse.
1056 Otherwise it is simply obfuscation and pollutes the namespace.
1059 \begin_layout Standard
1060 Capitalization is usually reserved for compile-time constants and macros.
1063 \begin_layout Description
1064 TDB_CONTEXT There is no reason to use this over 'struct tdb_context'; the
1065 definition isn't visible to the API user anyway.
1068 \begin_layout Description
1069 TDB_DATA There is no reason to use this over struct TDB_DATA; the struct
1070 needs to be understood by the API user.
1073 \begin_layout Description
1075 \begin_inset space ~
1078 TDB_DATA This would normally be called 'struct tdb_data'.
1081 \begin_layout Description
1083 \begin_inset space ~
1086 TDB_ERROR Similarly, this would normally be enum tdb_error.
1089 \begin_layout Subsubsection
1093 \begin_layout Standard
1095 Introducing lower case variants would please pedants like myself, but if
1096 it were done the existing ones should be kept.
1097 There is little point forcing a purely cosmetic change upon tdb users.
1100 \begin_layout Subsection
1101 \begin_inset CommandInset label
1103 name "tdb_log_func-Doesnt-Take"
1107 tdb_log_func Doesn't Take The Private Pointer
1110 \begin_layout Standard
1111 For API compatibility reasons, the logging function needs to call tdb_get_loggin
1112 g_private() to retrieve the pointer registered by the tdb_open_ex for logging.
1115 \begin_layout Subsubsection
1119 \begin_layout Standard
1120 It should simply take an extra argument, since we are prepared to break
1124 \begin_layout Subsection
1125 Various Callback Functions Are Not Typesafe
1128 \begin_layout Standard
1129 The callback functions in tdb_set_logging_function (after
1130 \begin_inset CommandInset ref
1132 reference "tdb_log_func-Doesnt-Take"
1136 is resolved), tdb_parse_record, tdb_traverse, tdb_traverse_read and tdb_check
1137 all take void * and must internally convert it to the argument type they
1141 \begin_layout Standard
1142 If this type changes, the compiler will not produce warnings on the callers,
1143 since it only sees void *.
1146 \begin_layout Subsubsection
1150 \begin_layout Standard
1151 With careful use of macros, we can create callback functions which give
1152 a warning when used on gcc and the types of the callback and its private
1154 Unsupported compilers will not give a warning, which is no worse than now.
1155 In addition, the callbacks become clearer, as they need not use void *
1156 for their parameter.
1159 \begin_layout Standard
1160 See CCAN's typesafe_cb module at http://ccan.ozlabs.org/info/typesafe_cb.html
1163 \begin_layout Subsection
1164 TDB_CLEAR_IF_FIRST Must Be Specified On All Opens, tdb_reopen_all Problematic
1167 \begin_layout Standard
1168 The TDB_CLEAR_IF_FIRST flag to tdb_open indicates that the TDB file should
1169 be cleared if the caller discovers it is the only process with the TDB
1171 However, if any caller does not specify TDB_CLEAR_IF_FIRST it will not
1172 be detected, so will have the TDB erased underneath them (usually resulting
1176 \begin_layout Standard
1177 There is a similar issue on fork(); if the parent exits (or otherwise closes
1178 the tdb) before the child calls tdb_reopen_all() to establish the lock
1179 used to indicate the TDB is opened by someone, a TDB_CLEAR_IF_FIRST opener
1180 at that moment will believe it alone has opened the TDB and will erase
1184 \begin_layout Subsubsection
1188 \begin_layout Standard
1189 Remove TDB_CLEAR_IF_FIRST.
1190 Other workarounds are possible, but see
1191 \begin_inset CommandInset ref
1193 reference "TDB_CLEAR_IF_FIRST-Imposes-Performance"
1198 \change_inserted 0 1284015637
1202 \begin_layout Subsection
1204 \change_inserted 0 1284015716
1205 Extending The Header Is Difficult
1208 \begin_layout Standard
1210 \change_inserted 0 1284015906
1211 We have reserved (zeroed) words in the TDB header, which can be used for
1213 If the future features are compulsory, the version number must be updated
1214 to prevent old code from accessing the database.
1215 But if the future feature is optional, we have no way of telling if older
1216 code is accessing the database or not.
1219 \begin_layout Subsubsection
1221 \change_inserted 0 1284015637
1225 \begin_layout Standard
1227 \change_inserted 0 1284016114
1228 The header should contain a
1229 \begin_inset Quotes eld
1233 \begin_inset Quotes erd
1237 This is divided into two 32-bit parts:
1240 \begin_layout Enumerate
1242 \change_inserted 0 1284016149
1243 The lower part reflects the format variant understood by code accessing
1247 \begin_layout Enumerate
1249 \change_inserted 0 1284016639
1250 The upper part reflects the format variant you must understand to write
1251 to the database (otherwise you can only open for reading).
1254 \begin_layout Standard
1256 \change_inserted 0 1284016821
1257 The latter field can only be written at creation time, the former should
1258 be written under the OPEN_LOCK when opening the database for writing, if
1259 the variant of the code is lower than the current lowest variant.
1262 \begin_layout Standard
1264 \change_inserted 0 1284016803
1265 This should allow backwards-compatible features to be added, and detection
1266 if older code (which doesn't understand the feature) writes to the database.
1267 \change_deleted 0 1284016101
1271 \begin_layout Subsection
1273 \change_inserted 0 1284015634
1274 Record Headers Are Not Expandible
1277 \begin_layout Standard
1279 \change_inserted 0 1284015634
1280 If we later want to add (say) checksums on keys and data, it would require
1281 another format change, which we'd like to avoid.
1284 \begin_layout Subsubsection
1286 \change_inserted 0 1284015634
1290 \begin_layout Standard
1292 \change_inserted 0 1284016847
1293 We often have extra padding at the tail of a record.
1294 If we ensure that the first byte (if any) of this padding is zero, we will
1295 have a way for future changes to detect code which doesn't understand a
1296 new format: the new code would write (say) a 1 at the tail, and thus if
1297 there is no tail or the first byte is 0, we would know the extension is
1298 not present on that record.
1303 \begin_layout Section
1304 Performance And Scalability Issues
1307 \begin_layout Subsection
1308 \begin_inset CommandInset label
1310 name "TDB_CLEAR_IF_FIRST-Imposes-Performance"
1314 TDB_CLEAR_IF_FIRST Imposes Performance Penalty
1317 \begin_layout Standard
1318 When TDB_CLEAR_IF_FIRST is specified, a 1-byte read lock is placed at offset
1321 While these locks never conflict in normal tdb usage, they do add substantial
1322 overhead for most fcntl lock implementations when the kernel scans to detect
1323 if a lock conflict exists.
1324 This is often a single linked list, making the time to acquire and release
1325 a fcntl lock O(N) where N is the number of processes with the TDB open,
1326 not the number actually doing work.
1329 \begin_layout Standard
1330 In a Samba server it is common to have huge numbers of clients sitting idle,
1331 and thus they have weaned themselves off the TDB_CLEAR_IF_FIRST flag.
1335 \begin_layout Plain Layout
1336 There is a flag to tdb_reopen_all() which is used for this optimization:
1337 if the parent process will outlive the child, the child does not need the
1339 This is a workaround for this very performance issue.
1347 \begin_layout Subsubsection
1351 \begin_layout Standard
1353 It was a neat idea, but even trivial servers tend to know when they are
1354 initializing for the first time and can simply unlink the old tdb at that
1358 \begin_layout Subsection
1359 TDB Files Have a 4G Limit
1362 \begin_layout Standard
1363 This seems to be becoming an issue (so much for
1364 \begin_inset Quotes eld
1368 \begin_inset Quotes erd
1371 !), particularly for ldb.
1374 \begin_layout Subsubsection
1378 \begin_layout Standard
1379 A new, incompatible TDB format which uses 64 bit offsets internally rather
1381 For simplicity of endian conversion (which TDB does on the fly if required),
1382 all values will be 64 bit on disk.
1383 In practice, some upper bits may be used for other purposes, but at least
1384 56 bits will be available for file offsets.
1387 \begin_layout Standard
1388 tdb_open() will automatically detect the old version, and even create them
1389 if TDB_VERSION6 is specified to tdb_open.
1392 \begin_layout Standard
1393 32 bit processes will still be able to access TDBs larger than 4G (assuming
1394 that their off_t allows them to seek to 64 bits), they will gracefully
1395 fall back as they fail to mmap.
1396 This can happen already with large TDBs.
1399 \begin_layout Standard
1400 Old versions of tdb will fail to open the new TDB files (since 28 August
1401 2009, commit 398d0c29290: prior to that any unrecognized file format would
1402 be erased and initialized as a fresh tdb!)
1405 \begin_layout Subsection
1406 TDB Records Have a 4G Limit
1409 \begin_layout Standard
1410 This has not been a reported problem, and the API uses size_t which can
1411 be 64 bit on 64 bit platforms.
1412 However, other limits may have made such an issue moot.
1415 \begin_layout Subsubsection
1419 \begin_layout Standard
1420 Record sizes will be 64 bit, with an error returned on 32 bit platforms
1421 which try to access such records (the current implementation would return
1422 TDB_ERR_OOM in a similar case).
1423 It seems unlikely that 32 bit keys will be a limitation, so the implementation
1424 may not support this (see
1425 \begin_inset CommandInset ref
1427 reference "sub:Records-Incur-A"
1434 \begin_layout Subsection
1435 Hash Size Is Determined At TDB Creation Time
1438 \begin_layout Standard
1439 TDB contains a number of hash chains in the header; the number is specified
1440 at creation time, and defaults to 131.
1441 This is such a bottleneck on large databases (as each hash chain gets quite
1442 long), that LDB uses 10,000 for this hash.
1443 In general it is impossible to know what the 'right' answer is at database
1447 \begin_layout Subsubsection
1449 \change_inserted 0 1283336713
1450 \begin_inset CommandInset label
1452 name "sub:Hash-Size-Solution"
1461 \begin_layout Standard
1462 After comprehensive performance testing on various scalable hash variants
1466 \begin_layout Plain Layout
1467 http://rusty.ozlabs.org/?p=89 and http://rusty.ozlabs.org/?p=94 This was annoying
1468 because I was previously convinced that an expanding tree of hashes would
1469 be very close to optimal.
1474 , it became clear that it is hard to beat a straight linear hash table which
1475 doubles in size when it reaches saturation.
1477 \change_deleted 0 1283307675
1478 There are three details which become important:
1481 \begin_layout Enumerate
1483 \change_deleted 0 1283307675
1484 On encountering a full bucket, we use the next bucket.
1487 \begin_layout Enumerate
1489 \change_deleted 0 1283307675
1490 Extra hash bits are stored with the offset, to reduce comparisons.
1493 \begin_layout Enumerate
1495 \change_deleted 0 1283307675
1496 A marker entry is used on deleting an entry.
1499 \begin_layout Standard
1501 \change_deleted 0 1283307675
1502 The doubling of the table must be done under a transaction; we will not
1503 reduce it on deletion, so it will be an unusual case.
1504 It will either be placed at the head (other entries will be moved out the
1505 way so we can expand).
1506 We could have a pointer in the header to the current hashtable location,
1507 but that pointer would have to be read frequently to check for hashtable
1511 \begin_layout Standard
1513 \change_deleted 0 1283307675
1514 The locking for this is slightly more complex than the chained case; we
1515 currently have one lock per bucket, and that means we would need to expand
1516 the lock if we overflow to the next bucket.
1517 The frequency of such collisions will effect our locking heuristics: we
1518 can always lock more buckets than we need.
1521 \begin_layout Standard
1523 \change_deleted 0 1283307675
1524 One possible optimization is to only re-check the hash size on an insert
1527 \change_inserted 0 1283307770
1528 Unfortunately, altering the hash table introduces serious locking complications
1529 : the entire hash table needs to be locked to enlarge the hash table, and
1530 others might be holding locks.
1531 Particularly insidious are insertions done under tdb_chainlock.
1534 \begin_layout Standard
1536 \change_inserted 0 1283336187
1537 Thus an expanding layered hash will be used: an array of hash groups, with
1538 each hash group exploding into pointers to lower hash groups once it fills,
1539 turning into a hash tree.
1540 This has implications for locking: we must lock the entire group in case
1541 we need to expand it, yet we don't know how deep the tree is at that point.
1544 \begin_layout Standard
1546 \change_inserted 0 1283336586
1547 Note that bits from the hash table entries should be stolen to hold more
1548 hash bits to reduce the penalty of collisions.
1549 We can use the otherwise-unused lower 3 bits.
1550 If we limit the size of the database to 64 exabytes, we can use the top
1551 8 bits of the hash entry as well.
1552 These 11 bits would reduce false positives down to 1 in 2000 which is more
1553 than we need: we can use one of the bits to indicate that the extra hash
1555 This means we can choose not to re-hash all entries when we expand a hash
1556 group; simply use the next bits we need and mark them invalid.
1561 \begin_layout Subsection
1562 \begin_inset CommandInset label
1564 name "TDB-Freelist-Is"
1568 TDB Freelist Is Highly Contended
1571 \begin_layout Standard
1572 TDB uses a single linked list for the free list.
1573 Allocation occurs as follows, using heuristics which have evolved over
1577 \begin_layout Enumerate
1578 Get the free list lock for this whole operation.
1581 \begin_layout Enumerate
1582 Multiply length by 1.25, so we always over-allocate by 25%.
1585 \begin_layout Enumerate
1586 Set the slack multiplier to 1.
1589 \begin_layout Enumerate
1590 Examine the current freelist entry: if it is > length but < the current
1591 best case, remember it as the best case.
1594 \begin_layout Enumerate
1595 Multiply the slack multiplier by 1.05.
1598 \begin_layout Enumerate
1599 If our best fit so far is less than length * slack multiplier, return it.
1600 The slack will be turned into a new free record if it's large enough.
1603 \begin_layout Enumerate
1604 Otherwise, go onto the next freelist entry.
1607 \begin_layout Standard
1608 Deleting a record occurs as follows:
1611 \begin_layout Enumerate
1612 Lock the hash chain for this whole operation.
1615 \begin_layout Enumerate
1616 Walk the chain to find the record, keeping the prev pointer offset.
1619 \begin_layout Enumerate
1620 If max_dead is non-zero:
1624 \begin_layout Enumerate
1625 Walk the hash chain again and count the dead records.
1628 \begin_layout Enumerate
1629 If it's more than max_dead, bulk free all the dead ones (similar to steps
1630 4 and below, but the lock is only obtained once).
1633 \begin_layout Enumerate
1634 Simply mark this record as dead and return.
1639 \begin_layout Enumerate
1640 Get the free list lock for the remainder of this operation.
1643 \begin_layout Enumerate
1644 \begin_inset CommandInset label
1646 name "right-merging"
1650 Examine the following block to see if it is free; if so, enlarge the current
1651 block and remove that block from the free list.
1652 This was disabled, as removal from the free list was O(entries-in-free-list).
1655 \begin_layout Enumerate
1656 Examine the preceeding block to see if it is free: for this reason, each
1657 block has a 32-bit tailer which indicates its length.
1658 If it is free, expand it to cover our new block and return.
1661 \begin_layout Enumerate
1662 Otherwise, prepend ourselves to the free list.
1665 \begin_layout Standard
1666 Disabling right-merging (step
1667 \begin_inset CommandInset ref
1669 reference "right-merging"
1673 ) causes fragmentation; the other heuristics proved insufficient to address
1674 this, so the final answer to this was that when we expand the TDB file
1675 inside a transaction commit, we repack the entire tdb.
1678 \begin_layout Standard
1679 The single list lock limits our allocation rate; due to the other issues
1680 this is not currently seen as a bottleneck.
1683 \begin_layout Subsubsection
1685 \change_deleted 0 1283336858
1689 \begin_layout Standard
1690 The first step is to remove all the current heuristics, as they obviously
1691 interact, then examine them once the lock contention is addressed.
1694 \begin_layout Standard
1695 The free list must be split to reduce contention.
1696 Assuming perfect free merging, we can at most have 1 free list entry for
1698 This implies that the number of free lists is related to the size of the
1699 hash table, but as it is rare to walk a large number of free list entries
1700 we can use far fewer, say 1/32 of the number of hash buckets.
1701 \change_inserted 0 1283336910
1705 \begin_layout Standard
1707 \change_inserted 0 1283337052
1708 It seems tempting to try to reuse the hash implementation which we use for
1709 records here, but we have two ways of searching for free entries: for allocatio
1710 n we search by size (and possibly zone) which produces too many clashes
1711 for our hash table to handle well, and for coalescing we search by address.
1712 Thus an array of doubly-linked free lists seems preferable.
1717 \begin_layout Standard
1718 There are various benefits in using per-size free lists (see
1719 \begin_inset CommandInset ref
1721 reference "sub:TDB-Becomes-Fragmented"
1725 ) but it's not clear this would reduce contention in the common case where
1726 all processes are allocating/freeing the same size.
1727 Thus we almost certainly need to divide in other ways: the most obvious
1728 is to divide the file into zones, and using a free list (or set of free
1730 This approximates address ordering.
1733 \begin_layout Standard
1734 Note that this means we need to split the free lists when we expand the
1735 file; this is probably acceptable when we double the hash table size, since
1736 that is such an expensive operation already.
1737 In the case of increasing the file size, there is an optimization we can
1738 use: if we use M in the formula above as the file size rounded up to the
1739 next power of 2, we only need reshuffle free lists when the file size crosses
1740 a power of 2 boundary,
1744 reshuffling the free lists is trivial: we simply merge every consecutive
1748 \begin_layout Standard
1749 The basic algorithm is as follows.
1753 \begin_layout Enumerate
1754 Identify the correct zone.
1757 \begin_layout Enumerate
1758 Lock the corresponding list.
1761 \begin_layout Enumerate
1762 Re-check the zone (we didn't have a lock, sizes could have changed): relock
1766 \begin_layout Enumerate
1767 Place the freed entry in the list for that zone.
1770 \begin_layout Standard
1771 Allocation is a little more complicated, as we perform delayed coalescing
1775 \begin_layout Enumerate
1776 Pick a zone either the zone we last freed into, or based on a
1777 \begin_inset Quotes eld
1781 \begin_inset Quotes erd
1787 \begin_layout Enumerate
1788 Lock the corresponding list.
1791 \begin_layout Enumerate
1792 Re-check the zone: relock if necessary.
1795 \begin_layout Enumerate
1796 If the top entry is -large enough, remove it from the list and return it.
1799 \begin_layout Enumerate
1800 Otherwise, coalesce entries in the list.If there was no entry large enough,
1801 unlock the list and try the next zone.
1804 \begin_layout Enumerate
1805 If no zone satisfies, expand the file.
1808 \begin_layout Standard
1809 This optimizes rapid insert/delete of free list entries by not coalescing
1811 First-fit address ordering ordering seems to be fairly good for keeping
1812 fragmentation low (see
1813 \begin_inset CommandInset ref
1815 reference "sub:TDB-Becomes-Fragmented"
1820 Note that address ordering does not need a tailer to coalesce, though if
1821 we needed one we could have one cheaply: see
1822 \begin_inset CommandInset ref
1824 reference "sub:Records-Incur-A"
1832 \begin_layout Standard
1833 I anticipate that the number of entries in each free zone would be small,
1834 but it might be worth using one free entry to hold pointers to the others
1835 for cache efficiency.
1836 \change_inserted 0 1283309850
1840 \begin_layout Standard
1842 \change_inserted 0 1283337216
1843 \begin_inset CommandInset label
1845 name "freelist-in-zone"
1849 If we want to avoid locking complexity (enlarging the free lists when we
1850 enlarge the file) we could place the array of free lists at the beginning
1852 This means existing array lists never move, but means that a record cannot
1853 be larger than a zone.
1854 That in turn implies that zones should be variable sized (say, power of
1855 2), which makes the question
1856 \begin_inset Quotes eld
1859 what zone is this record in?
1860 \begin_inset Quotes erd
1864 \begin_inset Quotes eld
1868 \begin_inset Quotes erd
1871 , but that's less common).
1872 It could be done with as few as 4 bits from the record header.
1876 \begin_layout Plain Layout
1878 \change_inserted 0 1283310945
1880 \begin_inset Formula $2^{16+N*3}$
1883 means 0 gives a minimal 65536-byte zone, 15 gives the maximal
1884 \begin_inset Formula $2^{61}$
1888 Zones range in factor of 8 steps.
1900 \begin_layout Subsection
1901 \begin_inset CommandInset label
1903 name "sub:TDB-Becomes-Fragmented"
1907 TDB Becomes Fragmented
1910 \begin_layout Standard
1911 Much of this is a result of allocation strategy
1915 \begin_layout Plain Layout
1916 The Memory Fragmentation Problem: Solved? Johnstone & Wilson 1995 ftp://ftp.cs.ute
1917 xas.edu/pub/garbage/malloc/ismm98.ps
1922 and deliberate hobbling of coalescing; internal fragmentation (aka overallocati
1923 on) is deliberately set at 25%, and external fragmentation is only cured
1924 by the decision to repack the entire db when a transaction commit needs
1925 to enlarge the file.
1928 \begin_layout Subsubsection
1932 \begin_layout Standard
1933 The 25% overhead on allocation works in practice for ldb because indexes
1934 tend to expand by one record at a time.
1935 This internal fragmentation can be resolved by having an
1936 \begin_inset Quotes eld
1940 \begin_inset Quotes erd
1943 bit in the header to note entries that have previously expanded, and allocating
1944 more space for them.
1947 \begin_layout Standard
1948 There are is a spectrum of possible solutions for external fragmentation:
1949 one is to use a fragmentation-avoiding allocation strategy such as best-fit
1950 address-order allocator.
1951 The other end of the spectrum would be to use a bump allocator (very fast
1952 and simple) and simply repack the file when we reach the end.
1955 \begin_layout Standard
1956 There are three problems with efficient fragmentation-avoiding allocators:
1957 they are non-trivial, they tend to use a single free list for each size,
1958 and there's no evidence that tdb allocation patterns will match those recorded
1959 for general allocators (though it seems likely).
1962 \begin_layout Standard
1963 Thus we don't spend too much effort on external fragmentation; we will be
1964 no worse than the current code if we need to repack on occasion.
1965 More effort is spent on reducing freelist contention, and reducing overhead.
1968 \begin_layout Subsection
1969 \begin_inset CommandInset label
1971 name "sub:Records-Incur-A"
1975 Records Incur A 28-Byte Overhead
1978 \begin_layout Standard
1979 Each TDB record has a header as follows:
1982 \begin_layout LyX-Code
1986 \begin_layout LyX-Code
1987 tdb_off_t next; /* offset of the next record in the list */
1990 \begin_layout LyX-Code
1991 tdb_len_t rec_len; /* total byte length of record */
1994 \begin_layout LyX-Code
1995 tdb_len_t key_len; /* byte length of key */
1998 \begin_layout LyX-Code
1999 tdb_len_t data_len; /* byte length of data */
2002 \begin_layout LyX-Code
2003 uint32_t full_hash; /* the full 32 bit hash of the key */
2006 \begin_layout LyX-Code
2007 uint32_t magic; /* try to catch errors */
2010 \begin_layout LyX-Code
2011 /* the following union is implied:
2014 \begin_layout LyX-Code
2018 \begin_layout LyX-Code
2019 char record[rec_len];
2022 \begin_layout LyX-Code
2026 \begin_layout LyX-Code
2030 \begin_layout LyX-Code
2031 char data[data_len];
2034 \begin_layout LyX-Code
2038 \begin_layout LyX-Code
2039 uint32_t totalsize; (tailer)
2042 \begin_layout LyX-Code
2046 \begin_layout LyX-Code
2050 \begin_layout LyX-Code
2054 \begin_layout Standard
2055 Naively, this would double to a 56-byte overhead on a 64 bit implementation.
2058 \begin_layout Subsubsection
2062 \begin_layout Standard
2063 We can use various techniques to reduce this for an allocated block:
2066 \begin_layout Enumerate
2067 The 'next' pointer is not required, as we are using a flat hash table.
2070 \begin_layout Enumerate
2071 'rec_len' can instead be expressed as an addition to key_len and data_len
2072 (it accounts for wasted or overallocated length in the record).
2073 Since the record length is always a multiple of 8, we can conveniently
2074 fit it in 32 bits (representing up to 35 bits).
2077 \begin_layout Enumerate
2078 'key_len' and 'data_len' can be reduced.
2079 I'm unwilling to restrict 'data_len' to 32 bits, but instead we can combine
2080 the two into one 64-bit field and using a 5 bit value which indicates at
2081 what bit to divide the two.
2082 Keys are unlikely to scale as fast as data, so I'm assuming a maximum key
2086 \begin_layout Enumerate
2087 'full_hash' is used to avoid a memcmp on the
2088 \begin_inset Quotes eld
2092 \begin_inset Quotes erd
2095 case, but this is diminishing returns after a handful of bits (at 10 bits,
2096 it reduces 99.9% of false memcmp).
2097 As an aside, as the lower bits are already incorporated in the hash table
2098 resolution, the upper bits should be used here.
2100 \change_inserted 0 1283336739
2101 Note that it's not clear that these bits will be a win, given the extra
2102 bits in the hash table itself (see
2103 \begin_inset CommandInset ref
2105 reference "sub:Hash-Size-Solution"
2114 \begin_layout Enumerate
2115 'magic' does not need to be enlarged: it currently reflects one of 5 values
2116 (used, free, dead, recovery, and unused_recovery).
2117 It is useful for quick sanity checking however, and should not be eliminated.
2120 \begin_layout Enumerate
2121 'tailer' is only used to coalesce free blocks (so a block to the right can
2122 find the header to check if this block is free).
2123 This can be replaced by a single 'free' bit in the header of the following
2124 block (and the tailer only exists in free blocks).
2128 \begin_layout Plain Layout
2129 This technique from Thomas Standish.
2130 Data Structure Techniques.
2131 Addison-Wesley, Reading, Massachusetts, 1980.
2136 The current proposed coalescing algorithm doesn't need this, however.
2139 \begin_layout Standard
2140 This produces a 16 byte used header like this:
2143 \begin_layout LyX-Code
2144 struct tdb_used_record {
2147 \begin_layout LyX-Code
2148 uint32_t magic : 16,
2151 \begin_layout LyX-Code
2155 \begin_layout LyX-Code
2159 \begin_layout LyX-Code
2163 \begin_layout LyX-Code
2164 uint32_t extra_octets;
2167 \begin_layout LyX-Code
2168 uint64_t key_and_data_len;
2171 \begin_layout LyX-Code
2175 \begin_layout Standard
2176 And a free record like this:
2179 \begin_layout LyX-Code
2180 struct tdb_free_record {
2183 \begin_layout LyX-Code
2184 uint32_t free_magic;
2187 \begin_layout LyX-Code
2188 uint64_t total_length;
2189 \change_inserted 0 1283337133
2193 \begin_layout LyX-Code
2195 \change_inserted 0 1283337139
2196 uint64_t prev, next;
2201 \begin_layout LyX-Code
2205 \begin_layout LyX-Code
2209 \begin_layout LyX-Code
2213 \begin_layout Standard
2215 \change_inserted 0 1283337235
2216 We might want to take some bits from the used record's top_hash (and the
2217 free record which has 32 bits of padding to spare anyway) if we use variable
2220 \begin_inset CommandInset ref
2222 reference "freelist-in-zone"
2231 \begin_layout Subsection
2232 Transaction Commit Requires 4 fdatasync
2235 \begin_layout Standard
2236 The current transaction algorithm is:
2239 \begin_layout Enumerate
2240 write_recovery_data();
2243 \begin_layout Enumerate
2247 \begin_layout Enumerate
2248 write_recovery_header();
2251 \begin_layout Enumerate
2255 \begin_layout Enumerate
2256 overwrite_with_new_data();
2259 \begin_layout Enumerate
2263 \begin_layout Enumerate
2264 remove_recovery_header();
2267 \begin_layout Enumerate
2271 \begin_layout Standard
2272 On current ext3, each sync flushes all data to disk, so the next 3 syncs
2273 are relatively expensive.
2274 But this could become a performance bottleneck on other filesystems such
2278 \begin_layout Subsubsection
2282 \begin_layout Standard
2283 Neil Brown points out that this is overzealous, and only one sync is needed:
2286 \begin_layout Enumerate
2287 Bundle the recovery data, a transaction counter and a strong checksum of
2291 \begin_layout Enumerate
2292 Strong checksum that whole bundle.
2295 \begin_layout Enumerate
2296 Store the bundle in the database.
2299 \begin_layout Enumerate
2300 Overwrite the oldest of the two recovery pointers in the header (identified
2301 using the transaction counter) with the offset of this bundle.
2304 \begin_layout Enumerate
2308 \begin_layout Enumerate
2309 Write the new data to the file.
2312 \begin_layout Standard
2313 Checking for recovery means identifying the latest bundle with a valid checksum
2314 and using the new data checksum to ensure that it has been applied.
2315 This is more expensive than the current check, but need only be done at
2317 For running databases, a separate header field can be used to indicate
2318 a transaction in progress; we need only check for recovery if this is set.
2321 \begin_layout Subsection
2322 \begin_inset CommandInset label
2324 name "sub:TDB-Does-Not"
2328 TDB Does Not Have Snapshot Support
2331 \begin_layout Subsubsection
2335 \begin_layout Standard
2337 At some point you say
2338 \begin_inset Quotes eld
2342 \begin_inset Quotes erd
2348 \begin_layout Standard
2349 But as a thought experiment, if we implemented transactions to only overwrite
2350 free entries (this is tricky: there must not be a header in each entry
2351 which indicates whether it is free, but use of presence in metadata elsewhere),
2352 and a pointer to the hash table, we could create an entirely new commit
2353 without destroying existing data.
2354 Then it would be easy to implement snapshots in a similar way.
2357 \begin_layout Standard
2358 This would not allow arbitrary changes to the database, such as tdb_repack
2359 does, and would require more space (since we have to preserve the current
2360 and future entries at once).
2361 If we used hash trees rather than one big hash table, we might only have
2362 to rewrite some sections of the hash, too.
2365 \begin_layout Standard
2366 We could then implement snapshots using a similar method, using multiple
2367 different hash tables/free tables.
2370 \begin_layout Subsection
2371 Transactions Cannot Operate in Parallel
2374 \begin_layout Standard
2375 This would be useless for ldb, as it hits the index records with just about
2377 It would add significant complexity in resolving clashes, and cause the
2378 all transaction callers to write their code to loop in the case where the
2379 transactions spuriously failed.
2382 \begin_layout Subsubsection
2386 \begin_layout Standard
2387 We could solve a small part of the problem by providing read-only transactions.
2388 These would allow one write transaction to begin, but it could not commit
2389 until all r/o transactions are done.
2390 This would require a new RO_TRANSACTION_LOCK, which would be upgraded on
2394 \begin_layout Subsection
2395 Default Hash Function Is Suboptimal
2398 \begin_layout Standard
2399 The Knuth-inspired multiplicative hash used by tdb is fairly slow (especially
2400 if we expand it to 64 bits), and works best when the hash bucket size is
2401 a prime number (which also means a slow modulus).
2402 In addition, it is highly predictable which could potentially lead to a
2403 Denial of Service attack in some TDB uses.
2406 \begin_layout Subsubsection
2410 \begin_layout Standard
2411 The Jenkins lookup3 hash
2415 \begin_layout Plain Layout
2416 http://burtleburtle.net/bob/c/lookup3.c
2421 is a fast and superbly-mixing hash.
2422 It's used by the Linux kernel and almost everything else.
2423 This has the particular properties that it takes an initial seed, and produces
2424 two 32 bit hash numbers, which we can combine into a 64-bit hash.
2427 \begin_layout Standard
2428 The seed should be created at tdb-creation time from some random source,
2429 and placed in the header.
2430 This is far from foolproof, but adds a little bit of protection against
2434 \begin_layout Subsection
2435 \begin_inset CommandInset label
2437 name "Reliable-Traversal-Adds"
2441 Reliable Traversal Adds Complexity
2444 \begin_layout Standard
2445 We lock a record during traversal iteration, and try to grab that lock in
2447 If that grab on delete fails, we simply mark it deleted and continue onwards;
2448 traversal checks for this condition and does the delete when it moves off
2452 \begin_layout Standard
2453 If traversal terminates, the dead record may be left indefinitely.
2456 \begin_layout Subsubsection
2460 \begin_layout Standard
2461 Remove reliability guarantees; see
2462 \begin_inset CommandInset ref
2464 reference "traverse-Proposed-Solution"
2471 \begin_layout Subsection
2472 Fcntl Locking Adds Overhead
2475 \begin_layout Standard
2476 Placing a fcntl lock means a system call, as does removing one.
2477 This is actually one reason why transactions can be faster (everything
2478 is locked once at transaction start).
2479 In the uncontended case, this overhead can theoretically be eliminated.
2482 \begin_layout Subsubsection
2486 \begin_layout Standard
2490 \begin_layout Standard
2491 We tried this before with spinlock support, in the early days of TDB, and
2492 it didn't make much difference except in manufactured benchmarks.
2495 \begin_layout Standard
2496 We could use spinlocks (with futex kernel support under Linux), but it means
2497 that we lose automatic cleanup when a process dies with a lock.
2498 There is a method of auto-cleanup under Linux, but it's not supported by
2499 other operating systems.
2500 We could reintroduce a clear-if-first-style lock and sweep for dead futexes
2501 on open, but that wouldn't help the normal case of one concurrent opener
2503 Increasingly elaborate repair schemes could be considered, but they require
2504 an ABI change (everyone must use them) anyway, so there's no need to do
2505 this at the same time as everything else.
2508 \begin_layout Subsection
2509 Some Transactions Don't Require Durability
2512 \begin_layout Standard
2513 Volker points out that gencache uses a CLEAR_IF_FIRST tdb for normal (fast)
2514 usage, and occasionally empties the results into a transactional TDB.
2515 This kind of usage prioritizes performance over durability: as long as
2516 we are consistent, data can be lost.
2519 \begin_layout Standard
2520 This would be more neatly implemented inside tdb: a
2521 \begin_inset Quotes eld
2525 \begin_inset Quotes erd
2528 transaction commit (ie.
2529 syncless) which meant that data may be reverted on a crash.
2532 \begin_layout Subsubsection
2536 \begin_layout Standard
2540 \begin_layout Standard
2541 Unfortunately any transaction scheme which overwrites old data requires
2542 a sync before that overwrite to avoid the possibility of corruption.
2545 \begin_layout Standard
2546 It seems possible to use a scheme similar to that described in
2547 \begin_inset CommandInset ref
2549 reference "sub:TDB-Does-Not"
2553 ,where transactions are committed without overwriting existing data, and
2554 an array of top-level pointers were available in the header.
2555 If the transaction is
2556 \begin_inset Quotes eld
2560 \begin_inset Quotes erd
2563 then we would not need a sync at all: existing processes would pick up
2564 the new hash table and free list and work with that.
2567 \begin_layout Standard
2568 At some later point, a sync would allow recovery of the old data into the
2569 free lists (perhaps when the array of top-level pointers filled).
2570 On crash, tdb_open() would examine the array of top levels, and apply the
2571 transactions until it encountered an invalid checksum.