9 date 2010.09.09.07.25.12; author rusty; state Exp;
14 date 2010.09.02.02.29.05; author rusty; state Exp;
19 date 2010.09.01.10.58.12; author rusty; state Exp;
24 date 2010.08.02.00.21.43; author rusty; state Exp;
29 date 2010.08.02.00.21.16; author rusty; state Exp;
34 date 2010.05.10.13.09.11; author rusty; state Exp;
39 date 2010.05.10.11.58.37; author rusty; state Exp;
44 date 2010.05.10.05.35.13; author rusty; state Exp;
49 date 2010.05.04.02.29.16; author rusty; state Exp;
64 @#LyX 1.6.5 created this file. For more info see http://www.lyx.org/
69 \use_default_options true
74 \font_typewriter default
75 \font_default_family default
82 \paperfontsize default
90 \paperorientation portrait
93 \paragraph_separation indent
95 \quotes_language english
98 \paperpagestyle default
99 \tracking_changes true
101 \author "Rusty Russell,,,"
108 TDB2: A Redesigning The Trivial DataBase
112 Rusty Russell, IBM Corporation
117 \change_deleted 0 1283307542
119 \change_inserted 0 1284016854
125 \begin_layout Abstract
126 The Trivial DataBase on-disk format is 32 bits; with usage cases heading
127 towards the 4G limit, that must change.
128 This required breakage provides an opportunity to revisit TDB's other design
129 decisions and reassess them.
132 \begin_layout Section
136 \begin_layout Standard
137 The Trivial DataBase was originally written by Andrew Tridgell as a simple
138 key/data pair storage system with the same API as dbm, but allowing multiple
139 readers and writers while being small enough (< 1000 lines of C) to include
141 The simple design created in 1999 has proven surprisingly robust and performant
142 , used in Samba versions 3 and 4 as well as numerous other projects.
143 Its useful life was greatly increased by the (backwards-compatible!) addition
144 of transaction support in 2005.
147 \begin_layout Standard
148 The wider variety and greater demands of TDB-using code has lead to some
149 organic growth of the API, as well as some compromises on the implementation.
150 None of these, by themselves, are seen as show-stoppers, but the cumulative
151 effect is to a loss of elegance over the initial, simple TDB implementation.
152 Here is a table of the approximate number of lines of implementation code
153 and number of API functions at the end of each year:
156 \begin_layout Standard
158 <lyxtabular version="3" rows="12" columns="3">
160 <column alignment="center" valignment="top" width="0">
161 <column alignment="center" valignment="top" width="0">
162 <column alignment="center" valignment="top" width="0">
164 <cell alignment="center" valignment="top" topline="true" bottomline="true" leftline="true" usebox="none">
167 \begin_layout Plain Layout
173 <cell alignment="center" valignment="top" topline="true" bottomline="true" leftline="true" usebox="none">
176 \begin_layout Plain Layout
182 <cell alignment="center" valignment="top" topline="true" bottomline="true" leftline="true" rightline="true" usebox="none">
185 \begin_layout Plain Layout
186 Lines of C Code Implementation
193 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
196 \begin_layout Plain Layout
202 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
205 \begin_layout Plain Layout
211 <cell alignment="center" valignment="top" topline="true" leftline="true" rightline="true" usebox="none">
214 \begin_layout Plain Layout
222 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
225 \begin_layout Plain Layout
231 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
234 \begin_layout Plain Layout
240 <cell alignment="center" valignment="top" topline="true" leftline="true" rightline="true" usebox="none">
243 \begin_layout Plain Layout
251 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
254 \begin_layout Plain Layout
260 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
263 \begin_layout Plain Layout
269 <cell alignment="center" valignment="top" topline="true" leftline="true" rightline="true" usebox="none">
272 \begin_layout Plain Layout
280 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
283 \begin_layout Plain Layout
289 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
292 \begin_layout Plain Layout
298 <cell alignment="center" valignment="top" topline="true" leftline="true" rightline="true" usebox="none">
301 \begin_layout Plain Layout
309 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
312 \begin_layout Plain Layout
318 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
321 \begin_layout Plain Layout
327 <cell alignment="center" valignment="top" topline="true" leftline="true" rightline="true" usebox="none">
330 \begin_layout Plain Layout
338 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
341 \begin_layout Plain Layout
347 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
350 \begin_layout Plain Layout
356 <cell alignment="center" valignment="top" topline="true" leftline="true" rightline="true" usebox="none">
359 \begin_layout Plain Layout
367 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
370 \begin_layout Plain Layout
376 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
379 \begin_layout Plain Layout
385 <cell alignment="center" valignment="top" topline="true" leftline="true" rightline="true" usebox="none">
388 \begin_layout Plain Layout
396 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
399 \begin_layout Plain Layout
405 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
408 \begin_layout Plain Layout
414 <cell alignment="center" valignment="top" topline="true" leftline="true" rightline="true" usebox="none">
417 \begin_layout Plain Layout
425 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
428 \begin_layout Plain Layout
434 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
437 \begin_layout Plain Layout
443 <cell alignment="center" valignment="top" topline="true" leftline="true" rightline="true" usebox="none">
446 \begin_layout Plain Layout
454 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
457 \begin_layout Plain Layout
463 <cell alignment="center" valignment="top" topline="true" leftline="true" usebox="none">
466 \begin_layout Plain Layout
472 <cell alignment="center" valignment="top" topline="true" leftline="true" rightline="true" usebox="none">
475 \begin_layout Plain Layout
483 <cell alignment="center" valignment="top" topline="true" bottomline="true" leftline="true" usebox="none">
486 \begin_layout Plain Layout
492 <cell alignment="center" valignment="top" topline="true" bottomline="true" leftline="true" usebox="none">
495 \begin_layout Plain Layout
501 <cell alignment="center" valignment="top" topline="true" bottomline="true" leftline="true" rightline="true" usebox="none">
504 \begin_layout Plain Layout
518 \begin_layout Standard
519 This review is an attempt to catalog and address all the known issues with
520 TDB and create solutions which address the problems without significantly
521 increasing complexity; all involved are far too aware of the dangers of
522 second system syndrome in rewriting a successful project like this.
525 \begin_layout Section
529 \begin_layout Subsection
530 tdb_open_ex Is Not Expandable
533 \begin_layout Standard
534 The tdb_open() call was expanded to tdb_open_ex(), which added an optional
535 hashing function and an optional logging function argument.
536 Additional arguments to open would require the introduction of a tdb_open_ex2
540 \begin_layout Subsubsection
544 \begin_layout Standard
545 tdb_open() will take a linked-list of attributes:
548 \begin_layout LyX-Code
552 \begin_layout LyX-Code
553 TDB_ATTRIBUTE_LOG = 0,
556 \begin_layout LyX-Code
557 TDB_ATTRIBUTE_HASH = 1
560 \begin_layout LyX-Code
564 \begin_layout LyX-Code
565 struct tdb_attribute_base {
568 \begin_layout LyX-Code
569 enum tdb_attribute attr;
572 \begin_layout LyX-Code
573 union tdb_attribute *next;
576 \begin_layout LyX-Code
580 \begin_layout LyX-Code
581 struct tdb_attribute_log {
584 \begin_layout LyX-Code
585 struct tdb_attribute_base base; /* .attr = TDB_ATTRIBUTE_LOG */
588 \begin_layout LyX-Code
592 \begin_layout LyX-Code
596 \begin_layout LyX-Code
600 \begin_layout LyX-Code
601 struct tdb_attribute_hash {
604 \begin_layout LyX-Code
605 struct tdb_attribute_base base; /* .attr = TDB_ATTRIBUTE_HASH */
608 \begin_layout LyX-Code
609 tdb_hash_func hash_fn;
612 \begin_layout LyX-Code
616 \begin_layout LyX-Code
620 \begin_layout LyX-Code
621 union tdb_attribute {
624 \begin_layout LyX-Code
625 struct tdb_attribute_base base;
628 \begin_layout LyX-Code
629 struct tdb_attribute_log log;
632 \begin_layout LyX-Code
633 struct tdb_attribute_hash hash;
636 \begin_layout LyX-Code
640 \begin_layout Standard
641 This allows future attributes to be added, even if this expands the size
645 \begin_layout Subsection
646 tdb_traverse Makes Impossible Guarantees
649 \begin_layout Standard
650 tdb_traverse (and tdb_firstkey/tdb_nextkey) predate transactions, and it
651 was thought that it was important to guarantee that all records which exist
652 at the start and end of the traversal would be included, and no record
653 would be included twice.
656 \begin_layout Standard
657 This adds complexity (see
658 \begin_inset CommandInset ref
660 reference "Reliable-Traversal-Adds"
664 ) and does not work anyway for records which are altered (in particular,
665 those which are expanded may be effectively deleted and re-added behind
669 \begin_layout Subsubsection
670 \begin_inset CommandInset label
672 name "traverse-Proposed-Solution"
679 \begin_layout Standard
680 Abandon the guarantee.
681 You will see every record if no changes occur during your traversal, otherwise
682 you will see some subset.
683 You can prevent changes by using a transaction or the locking API.
686 \begin_layout Subsection
687 Nesting of Transactions Is Fraught
690 \begin_layout Standard
691 TDB has alternated between allowing nested transactions and not allowing
693 Various paths in the Samba codebase assume that transactions will nest,
694 and in a sense they can: the operation is only committed to disk when the
695 outer transaction is committed.
696 There are two problems, however:
699 \begin_layout Enumerate
700 Canceling the inner transaction will cause the outer transaction commit
701 to fail, and will not undo any operations since the inner transaction began.
702 This problem is soluble with some additional internal code.
705 \begin_layout Enumerate
706 An inner transaction commit can be cancelled by the outer transaction.
707 This is desirable in the way which Samba's database initialization code
708 uses transactions, but could be a surprise to any users expecting a successful
709 transaction commit to expose changes to others.
712 \begin_layout Standard
713 The current solution is to specify the behavior at tdb_open(), with the
714 default currently that nested transactions are allowed.
715 This flag can also be changed at runtime.
718 \begin_layout Subsubsection
722 \begin_layout Standard
723 Given the usage patterns, it seems that the
724 \begin_inset Quotes eld
728 \begin_inset Quotes erd
731 behavior of disallowing nested transactions should become the default.
732 Additionally, it seems the outer transaction is the only code which knows
733 whether inner transactions should be allowed, so a flag to indicate this
734 could be added to tdb_transaction_start.
735 However, this behavior can be simulated with a wrapper which uses tdb_add_flags
736 () and tdb_remove_flags(), so the API should not be expanded for this relatively
740 \begin_layout Subsection
741 Incorrect Hash Function is Not Detected
744 \begin_layout Standard
745 tdb_open_ex() allows the calling code to specify a different hash function
746 to use, but does not check that all other processes accessing this tdb
747 are using the same hash function.
748 The result is that records are missing from tdb_fetch().
751 \begin_layout Subsubsection
755 \begin_layout Standard
756 The header should contain an example hash result (eg.
757 the hash of 0xdeadbeef), and tdb_open_ex() should check that the given
758 hash function produces the same answer, or fail the tdb_open call.
761 \begin_layout Subsection
762 tdb_set_max_dead/TDB_VOLATILE Expose Implementation
765 \begin_layout Standard
766 In response to scalability issues with the free list (
767 \begin_inset CommandInset ref
769 reference "TDB-Freelist-Is"
773 ) two API workarounds have been incorporated in TDB: tdb_set_max_dead()
774 and the TDB_VOLATILE flag to tdb_open.
775 The latter actually calls the former with an argument of
776 \begin_inset Quotes eld
780 \begin_inset Quotes erd
786 \begin_layout Standard
787 This code allows deleted records to accumulate without putting them in the
789 On delete we iterate through each chain and free them in a batch if there
790 are more than max_dead entries.
791 These are never otherwise recycled except as a side-effect of a tdb_repack.
794 \begin_layout Subsubsection
798 \begin_layout Standard
799 With the scalability problems of the freelist solved, this API can be removed.
800 The TDB_VOLATILE flag may still be useful as a hint that store and delete
801 of records will be at least as common as fetch in order to allow some internal
802 tuning, but initially will become a no-op.
805 \begin_layout Subsection
806 \begin_inset CommandInset label
808 name "TDB-Files-Cannot"
812 TDB Files Cannot Be Opened Multiple Times In The Same Process
815 \begin_layout Standard
816 No process can open the same TDB twice; we check and disallow it.
817 This is an unfortunate side-effect of fcntl locks, which operate on a per-file
818 rather than per-file-descriptor basis, and do not nest.
819 Thus, closing any file descriptor on a file clears all the locks obtained
820 by this process, even if they were placed using a different file descriptor!
823 \begin_layout Standard
824 Note that even if this were solved, deadlock could occur if operations were
825 nested: this is a more manageable programming error in most cases.
828 \begin_layout Subsubsection
832 \begin_layout Standard
833 We could lobby POSIX to fix the perverse rules, or at least lobby Linux
834 to violate them so that the most common implementation does not have this
836 This would be a generally good idea for other fcntl lock users.
839 \begin_layout Standard
840 Samba uses a wrapper which hands out the same tdb_context to multiple callers
841 if this happens, and does simple reference counting.
842 We should do this inside the tdb library, which already emulates lock nesting
843 internally; it would need to recognize when deadlock occurs within a single
845 This would create a new failure mode for tdb operations (while we currently
846 handle locking failures, they are impossible in normal use and a process
847 encountering them can do little but give up).
850 \begin_layout Standard
851 I do not see benefit in an additional tdb_open flag to indicate whether
852 re-opening is allowed, as though there may be some benefit to adding a
853 call to detect when a tdb_context is shared, to allow other to create such
857 \begin_layout Subsection
858 TDB API Is Not POSIX Thread-safe
861 \begin_layout Standard
862 The TDB API uses an error code which can be queried after an operation to
863 determine what went wrong.
864 This programming model does not work with threads, unless specific additional
865 guarantees are given by the implementation.
866 In addition, even otherwise-independent threads cannot open the same TDB
868 \begin_inset CommandInset ref
870 reference "TDB-Files-Cannot"
877 \begin_layout Subsubsection
881 \begin_layout Standard
882 Reachitecting the API to include a tdb_errcode pointer would be a great
883 deal of churn; we are better to guarantee that the tdb_errcode is per-thread
884 so the current programming model can be maintained.
887 \begin_layout Standard
888 This requires dynamic per-thread allocations, which is awkward with POSIX
889 threads (pthread_key_create space is limited and we cannot simply allocate
890 a key for every TDB).
893 \begin_layout Standard
894 Internal locking is required to make sure that fcntl locks do not overlap
895 between threads, and also that the global list of tdbs is maintained.
898 \begin_layout Standard
899 The aim is that building tdb with -DTDB_PTHREAD will result in a pthread-safe
900 version of the library, and otherwise no overhead will exist.
902 \change_inserted 0 1284016998
903 Alternatively, a hooking mechanism similar to that proposed for
904 \begin_inset CommandInset ref
906 reference "Proposed-Solution-locking-hook"
910 could be used to enable pthread locking at runtime.
915 \begin_layout Subsection
916 *_nonblock Functions And *_mark Functions Expose Implementation
919 \begin_layout Standard
924 \begin_layout Plain Layout
925 Clustered TDB, see http://ctdb.samba.org
930 wishes to operate on TDB in a non-blocking manner.
931 This is currently done as follows:
934 \begin_layout Enumerate
935 Call the _nonblock variant of an API function (eg.
936 tdb_lockall_nonblock).
940 \begin_layout Enumerate
941 Fork a child process, and wait for it to call the normal variant (eg.
945 \begin_layout Enumerate
946 If the child succeeds, call the _mark variant to indicate we already have
951 \begin_layout Enumerate
952 Upon completion, tell the child to release the locks (eg.
956 \begin_layout Enumerate
957 Indicate to tdb that it should consider the locks removed (eg.
961 \begin_layout Standard
962 There are several issues with this approach.
963 Firstly, adding two new variants of each function clutters the API for
964 an obscure use, and so not all functions have three variants.
965 Secondly, it assumes that all paths of the functions ask for the same locks,
966 otherwise the parent process will have to get a lock which the child doesn't
967 have under some circumstances.
968 I don't believe this is currently the case, but it constrains the implementatio
973 \begin_layout Subsubsection
974 \begin_inset CommandInset label
976 name "Proposed-Solution-locking-hook"
983 \begin_layout Standard
984 Implement a hook for locking methods, so that the caller can control the
985 calls to create and remove fcntl locks.
986 In this scenario, ctdbd would operate as follows:
989 \begin_layout Enumerate
990 Call the normal API function, eg tdb_lockall().
993 \begin_layout Enumerate
994 When the lock callback comes in, check if the child has the lock.
995 Initially, this is always false.
997 Otherwise, try to obtain it in non-blocking mode.
998 If that fails, return EWOULDBLOCK.
1001 \begin_layout Enumerate
1002 Release locks in the unlock callback as normal.
1005 \begin_layout Enumerate
1006 If tdb_lockall() fails, see if we recorded a lock failure; if so, call the
1007 child to repeat the operation.
1010 \begin_layout Enumerate
1011 The child records what locks it obtains, and returns that information to
1015 \begin_layout Enumerate
1016 When the child has succeeded, goto 1.
1019 \begin_layout Standard
1020 This is flexible enough to handle any potential locking scenario, even when
1021 lock requirements change.
1022 It can be optimized so that the parent does not release locks, just tells
1023 the child which locks it doesn't need to obtain.
1026 \begin_layout Standard
1027 It also keeps the complexity out of the API, and in ctdbd where it is needed.
1030 \begin_layout Subsection
1031 tdb_chainlock Functions Expose Implementation
1034 \begin_layout Standard
1035 tdb_chainlock locks some number of records, including the record indicated
1037 This gave atomicity guarantees; no-one can start a transaction, alter,
1038 read or delete that key while the lock is held.
1041 \begin_layout Standard
1042 It also makes the same guarantee for any other key in the chain, which is
1043 an internal implementation detail and potentially a cause for deadlock.
1046 \begin_layout Subsubsection
1050 \begin_layout Standard
1052 It would be nice to have an explicit single entry lock which effected no
1054 Unfortunately, this won't work for an entry which doesn't exist.
1055 Thus while chainlock may be implemented more efficiently for the existing
1056 case, it will still have overlap issues with the non-existing case.
1057 So it is best to keep the current (lack of) guarantee about which records
1058 will be effected to avoid constraining our implementation.
1061 \begin_layout Subsection
1062 Signal Handling is Not Race-Free
1065 \begin_layout Standard
1066 The tdb_setalarm_sigptr() call allows the caller's signal handler to indicate
1067 that the tdb locking code should return with a failure, rather than trying
1068 again when a signal is received (and errno == EAGAIN).
1069 This is usually used to implement timeouts.
1072 \begin_layout Standard
1073 Unfortunately, this does not work in the case where the signal is received
1074 before the tdb code enters the fcntl() call to place the lock: the code
1075 will sleep within the fcntl() code, unaware that the signal wants it to
1077 In the case of long timeouts, this does not happen in practice.
1080 \begin_layout Subsubsection
1084 \begin_layout Standard
1085 The locking hooks proposed in
1086 \begin_inset CommandInset ref
1088 reference "Proposed-Solution-locking-hook"
1092 would allow the user to decide on whether to fail the lock acquisition
1094 This allows the caller to choose their own compromise: they could narrow
1095 the race by checking immediately before the fcntl call.
1099 \begin_layout Plain Layout
1100 It may be possible to make this race-free in some implementations by having
1101 the signal handler alter the struct flock to make it invalid.
1102 This will cause the fcntl() lock call to fail with EINVAL if the signal
1103 occurs before the kernel is entered, otherwise EAGAIN.
1111 \begin_layout Subsection
1112 The API Uses Gratuitous Typedefs, Capitals
1115 \begin_layout Standard
1116 typedefs are useful for providing source compatibility when types can differ
1117 across implementations, or arguably in the case of function pointer definitions
1118 which are hard for humans to parse.
1119 Otherwise it is simply obfuscation and pollutes the namespace.
1122 \begin_layout Standard
1123 Capitalization is usually reserved for compile-time constants and macros.
1126 \begin_layout Description
1127 TDB_CONTEXT There is no reason to use this over 'struct tdb_context'; the
1128 definition isn't visible to the API user anyway.
1131 \begin_layout Description
1132 TDB_DATA There is no reason to use this over struct TDB_DATA; the struct
1133 needs to be understood by the API user.
1136 \begin_layout Description
1138 \begin_inset space ~
1141 TDB_DATA This would normally be called 'struct tdb_data'.
1144 \begin_layout Description
1146 \begin_inset space ~
1149 TDB_ERROR Similarly, this would normally be enum tdb_error.
1152 \begin_layout Subsubsection
1156 \begin_layout Standard
1158 Introducing lower case variants would please pedants like myself, but if
1159 it were done the existing ones should be kept.
1160 There is little point forcing a purely cosmetic change upon tdb users.
1163 \begin_layout Subsection
1164 \begin_inset CommandInset label
1166 name "tdb_log_func-Doesnt-Take"
1170 tdb_log_func Doesn't Take The Private Pointer
1173 \begin_layout Standard
1174 For API compatibility reasons, the logging function needs to call tdb_get_loggin
1175 g_private() to retrieve the pointer registered by the tdb_open_ex for logging.
1178 \begin_layout Subsubsection
1182 \begin_layout Standard
1183 It should simply take an extra argument, since we are prepared to break
1187 \begin_layout Subsection
1188 Various Callback Functions Are Not Typesafe
1191 \begin_layout Standard
1192 The callback functions in tdb_set_logging_function (after
1193 \begin_inset CommandInset ref
1195 reference "tdb_log_func-Doesnt-Take"
1199 is resolved), tdb_parse_record, tdb_traverse, tdb_traverse_read and tdb_check
1200 all take void * and must internally convert it to the argument type they
1204 \begin_layout Standard
1205 If this type changes, the compiler will not produce warnings on the callers,
1206 since it only sees void *.
1209 \begin_layout Subsubsection
1213 \begin_layout Standard
1214 With careful use of macros, we can create callback functions which give
1215 a warning when used on gcc and the types of the callback and its private
1217 Unsupported compilers will not give a warning, which is no worse than now.
1218 In addition, the callbacks become clearer, as they need not use void *
1219 for their parameter.
1222 \begin_layout Standard
1223 See CCAN's typesafe_cb module at http://ccan.ozlabs.org/info/typesafe_cb.html
1226 \begin_layout Subsection
1227 TDB_CLEAR_IF_FIRST Must Be Specified On All Opens, tdb_reopen_all Problematic
1230 \begin_layout Standard
1231 The TDB_CLEAR_IF_FIRST flag to tdb_open indicates that the TDB file should
1232 be cleared if the caller discovers it is the only process with the TDB
1234 However, if any caller does not specify TDB_CLEAR_IF_FIRST it will not
1235 be detected, so will have the TDB erased underneath them (usually resulting
1239 \begin_layout Standard
1240 There is a similar issue on fork(); if the parent exits (or otherwise closes
1241 the tdb) before the child calls tdb_reopen_all() to establish the lock
1242 used to indicate the TDB is opened by someone, a TDB_CLEAR_IF_FIRST opener
1243 at that moment will believe it alone has opened the TDB and will erase
1247 \begin_layout Subsubsection
1251 \begin_layout Standard
1252 Remove TDB_CLEAR_IF_FIRST.
1253 Other workarounds are possible, but see
1254 \begin_inset CommandInset ref
1256 reference "TDB_CLEAR_IF_FIRST-Imposes-Performance"
1261 \change_inserted 0 1284015637
1265 \begin_layout Subsection
1267 \change_inserted 0 1284015716
1268 Extending The Header Is Difficult
1271 \begin_layout Standard
1273 \change_inserted 0 1284015906
1274 We have reserved (zeroed) words in the TDB header, which can be used for
1276 If the future features are compulsory, the version number must be updated
1277 to prevent old code from accessing the database.
1278 But if the future feature is optional, we have no way of telling if older
1279 code is accessing the database or not.
1282 \begin_layout Subsubsection
1284 \change_inserted 0 1284015637
1288 \begin_layout Standard
1290 \change_inserted 0 1284016114
1291 The header should contain a
1292 \begin_inset Quotes eld
1296 \begin_inset Quotes erd
1300 This is divided into two 32-bit parts:
1303 \begin_layout Enumerate
1305 \change_inserted 0 1284016149
1306 The lower part reflects the format variant understood by code accessing
1310 \begin_layout Enumerate
1312 \change_inserted 0 1284016639
1313 The upper part reflects the format variant you must understand to write
1314 to the database (otherwise you can only open for reading).
1317 \begin_layout Standard
1319 \change_inserted 0 1284016821
1320 The latter field can only be written at creation time, the former should
1321 be written under the OPEN_LOCK when opening the database for writing, if
1322 the variant of the code is lower than the current lowest variant.
1325 \begin_layout Standard
1327 \change_inserted 0 1284016803
1328 This should allow backwards-compatible features to be added, and detection
1329 if older code (which doesn't understand the feature) writes to the database.
1330 \change_deleted 0 1284016101
1334 \begin_layout Subsection
1336 \change_inserted 0 1284015634
1337 Record Headers Are Not Expandible
1340 \begin_layout Standard
1342 \change_inserted 0 1284015634
1343 If we later want to add (say) checksums on keys and data, it would require
1344 another format change, which we'd like to avoid.
1347 \begin_layout Subsubsection
1349 \change_inserted 0 1284015634
1353 \begin_layout Standard
1355 \change_inserted 0 1284016847
1356 We often have extra padding at the tail of a record.
1357 If we ensure that the first byte (if any) of this padding is zero, we will
1358 have a way for future changes to detect code which doesn't understand a
1359 new format: the new code would write (say) a 1 at the tail, and thus if
1360 there is no tail or the first byte is 0, we would know the extension is
1361 not present on that record.
1366 \begin_layout Section
1367 Performance And Scalability Issues
1370 \begin_layout Subsection
1371 \begin_inset CommandInset label
1373 name "TDB_CLEAR_IF_FIRST-Imposes-Performance"
1377 TDB_CLEAR_IF_FIRST Imposes Performance Penalty
1380 \begin_layout Standard
1381 When TDB_CLEAR_IF_FIRST is specified, a 1-byte read lock is placed at offset
1384 While these locks never conflict in normal tdb usage, they do add substantial
1385 overhead for most fcntl lock implementations when the kernel scans to detect
1386 if a lock conflict exists.
1387 This is often a single linked list, making the time to acquire and release
1388 a fcntl lock O(N) where N is the number of processes with the TDB open,
1389 not the number actually doing work.
1392 \begin_layout Standard
1393 In a Samba server it is common to have huge numbers of clients sitting idle,
1394 and thus they have weaned themselves off the TDB_CLEAR_IF_FIRST flag.
1398 \begin_layout Plain Layout
1399 There is a flag to tdb_reopen_all() which is used for this optimization:
1400 if the parent process will outlive the child, the child does not need the
1402 This is a workaround for this very performance issue.
1410 \begin_layout Subsubsection
1414 \begin_layout Standard
1416 It was a neat idea, but even trivial servers tend to know when they are
1417 initializing for the first time and can simply unlink the old tdb at that
1421 \begin_layout Subsection
1422 TDB Files Have a 4G Limit
1425 \begin_layout Standard
1426 This seems to be becoming an issue (so much for
1427 \begin_inset Quotes eld
1431 \begin_inset Quotes erd
1434 !), particularly for ldb.
1437 \begin_layout Subsubsection
1441 \begin_layout Standard
1442 A new, incompatible TDB format which uses 64 bit offsets internally rather
1444 For simplicity of endian conversion (which TDB does on the fly if required),
1445 all values will be 64 bit on disk.
1446 In practice, some upper bits may be used for other purposes, but at least
1447 56 bits will be available for file offsets.
1450 \begin_layout Standard
1451 tdb_open() will automatically detect the old version, and even create them
1452 if TDB_VERSION6 is specified to tdb_open.
1455 \begin_layout Standard
1456 32 bit processes will still be able to access TDBs larger than 4G (assuming
1457 that their off_t allows them to seek to 64 bits), they will gracefully
1458 fall back as they fail to mmap.
1459 This can happen already with large TDBs.
1462 \begin_layout Standard
1463 Old versions of tdb will fail to open the new TDB files (since 28 August
1464 2009, commit 398d0c29290: prior to that any unrecognized file format would
1465 be erased and initialized as a fresh tdb!)
1468 \begin_layout Subsection
1469 TDB Records Have a 4G Limit
1472 \begin_layout Standard
1473 This has not been a reported problem, and the API uses size_t which can
1474 be 64 bit on 64 bit platforms.
1475 However, other limits may have made such an issue moot.
1478 \begin_layout Subsubsection
1482 \begin_layout Standard
1483 Record sizes will be 64 bit, with an error returned on 32 bit platforms
1484 which try to access such records (the current implementation would return
1485 TDB_ERR_OOM in a similar case).
1486 It seems unlikely that 32 bit keys will be a limitation, so the implementation
1487 may not support this (see
1488 \begin_inset CommandInset ref
1490 reference "sub:Records-Incur-A"
1497 \begin_layout Subsection
1498 Hash Size Is Determined At TDB Creation Time
1501 \begin_layout Standard
1502 TDB contains a number of hash chains in the header; the number is specified
1503 at creation time, and defaults to 131.
1504 This is such a bottleneck on large databases (as each hash chain gets quite
1505 long), that LDB uses 10,000 for this hash.
1506 In general it is impossible to know what the 'right' answer is at database
1510 \begin_layout Subsubsection
1512 \change_inserted 0 1283336713
1513 \begin_inset CommandInset label
1515 name "sub:Hash-Size-Solution"
1524 \begin_layout Standard
1525 After comprehensive performance testing on various scalable hash variants
1529 \begin_layout Plain Layout
1530 http://rusty.ozlabs.org/?p=89 and http://rusty.ozlabs.org/?p=94 This was annoying
1531 because I was previously convinced that an expanding tree of hashes would
1532 be very close to optimal.
1537 , it became clear that it is hard to beat a straight linear hash table which
1538 doubles in size when it reaches saturation.
1540 \change_deleted 0 1283307675
1541 There are three details which become important:
1544 \begin_layout Enumerate
1546 \change_deleted 0 1283307675
1547 On encountering a full bucket, we use the next bucket.
1550 \begin_layout Enumerate
1552 \change_deleted 0 1283307675
1553 Extra hash bits are stored with the offset, to reduce comparisons.
1556 \begin_layout Enumerate
1558 \change_deleted 0 1283307675
1559 A marker entry is used on deleting an entry.
1562 \begin_layout Standard
1564 \change_deleted 0 1283307675
1565 The doubling of the table must be done under a transaction; we will not
1566 reduce it on deletion, so it will be an unusual case.
1567 It will either be placed at the head (other entries will be moved out the
1568 way so we can expand).
1569 We could have a pointer in the header to the current hashtable location,
1570 but that pointer would have to be read frequently to check for hashtable
1574 \begin_layout Standard
1576 \change_deleted 0 1283307675
1577 The locking for this is slightly more complex than the chained case; we
1578 currently have one lock per bucket, and that means we would need to expand
1579 the lock if we overflow to the next bucket.
1580 The frequency of such collisions will effect our locking heuristics: we
1581 can always lock more buckets than we need.
1584 \begin_layout Standard
1586 \change_deleted 0 1283307675
1587 One possible optimization is to only re-check the hash size on an insert
1590 \change_inserted 0 1283307770
1591 Unfortunately, altering the hash table introduces serious locking complications
1592 : the entire hash table needs to be locked to enlarge the hash table, and
1593 others might be holding locks.
1594 Particularly insidious are insertions done under tdb_chainlock.
1597 \begin_layout Standard
1599 \change_inserted 0 1283336187
1600 Thus an expanding layered hash will be used: an array of hash groups, with
1601 each hash group exploding into pointers to lower hash groups once it fills,
1602 turning into a hash tree.
1603 This has implications for locking: we must lock the entire group in case
1604 we need to expand it, yet we don't know how deep the tree is at that point.
1607 \begin_layout Standard
1609 \change_inserted 0 1283336586
1610 Note that bits from the hash table entries should be stolen to hold more
1611 hash bits to reduce the penalty of collisions.
1612 We can use the otherwise-unused lower 3 bits.
1613 If we limit the size of the database to 64 exabytes, we can use the top
1614 8 bits of the hash entry as well.
1615 These 11 bits would reduce false positives down to 1 in 2000 which is more
1616 than we need: we can use one of the bits to indicate that the extra hash
1618 This means we can choose not to re-hash all entries when we expand a hash
1619 group; simply use the next bits we need and mark them invalid.
1624 \begin_layout Subsection
1625 \begin_inset CommandInset label
1627 name "TDB-Freelist-Is"
1631 TDB Freelist Is Highly Contended
1634 \begin_layout Standard
1635 TDB uses a single linked list for the free list.
1636 Allocation occurs as follows, using heuristics which have evolved over
1640 \begin_layout Enumerate
1641 Get the free list lock for this whole operation.
1644 \begin_layout Enumerate
1645 Multiply length by 1.25, so we always over-allocate by 25%.
1648 \begin_layout Enumerate
1649 Set the slack multiplier to 1.
1652 \begin_layout Enumerate
1653 Examine the current freelist entry: if it is > length but < the current
1654 best case, remember it as the best case.
1657 \begin_layout Enumerate
1658 Multiply the slack multiplier by 1.05.
1661 \begin_layout Enumerate
1662 If our best fit so far is less than length * slack multiplier, return it.
1663 The slack will be turned into a new free record if it's large enough.
1666 \begin_layout Enumerate
1667 Otherwise, go onto the next freelist entry.
1670 \begin_layout Standard
1671 Deleting a record occurs as follows:
1674 \begin_layout Enumerate
1675 Lock the hash chain for this whole operation.
1678 \begin_layout Enumerate
1679 Walk the chain to find the record, keeping the prev pointer offset.
1682 \begin_layout Enumerate
1683 If max_dead is non-zero:
1687 \begin_layout Enumerate
1688 Walk the hash chain again and count the dead records.
1691 \begin_layout Enumerate
1692 If it's more than max_dead, bulk free all the dead ones (similar to steps
1693 4 and below, but the lock is only obtained once).
1696 \begin_layout Enumerate
1697 Simply mark this record as dead and return.
1702 \begin_layout Enumerate
1703 Get the free list lock for the remainder of this operation.
1706 \begin_layout Enumerate
1707 \begin_inset CommandInset label
1709 name "right-merging"
1713 Examine the following block to see if it is free; if so, enlarge the current
1714 block and remove that block from the free list.
1715 This was disabled, as removal from the free list was O(entries-in-free-list).
1718 \begin_layout Enumerate
1719 Examine the preceeding block to see if it is free: for this reason, each
1720 block has a 32-bit tailer which indicates its length.
1721 If it is free, expand it to cover our new block and return.
1724 \begin_layout Enumerate
1725 Otherwise, prepend ourselves to the free list.
1728 \begin_layout Standard
1729 Disabling right-merging (step
1730 \begin_inset CommandInset ref
1732 reference "right-merging"
1736 ) causes fragmentation; the other heuristics proved insufficient to address
1737 this, so the final answer to this was that when we expand the TDB file
1738 inside a transaction commit, we repack the entire tdb.
1741 \begin_layout Standard
1742 The single list lock limits our allocation rate; due to the other issues
1743 this is not currently seen as a bottleneck.
1746 \begin_layout Subsubsection
1748 \change_deleted 0 1283336858
1752 \begin_layout Standard
1753 The first step is to remove all the current heuristics, as they obviously
1754 interact, then examine them once the lock contention is addressed.
1757 \begin_layout Standard
1758 The free list must be split to reduce contention.
1759 Assuming perfect free merging, we can at most have 1 free list entry for
1761 This implies that the number of free lists is related to the size of the
1762 hash table, but as it is rare to walk a large number of free list entries
1763 we can use far fewer, say 1/32 of the number of hash buckets.
1764 \change_inserted 0 1283336910
1768 \begin_layout Standard
1770 \change_inserted 0 1283337052
1771 It seems tempting to try to reuse the hash implementation which we use for
1772 records here, but we have two ways of searching for free entries: for allocatio
1773 n we search by size (and possibly zone) which produces too many clashes
1774 for our hash table to handle well, and for coalescing we search by address.
1775 Thus an array of doubly-linked free lists seems preferable.
1780 \begin_layout Standard
1781 There are various benefits in using per-size free lists (see
1782 \begin_inset CommandInset ref
1784 reference "sub:TDB-Becomes-Fragmented"
1788 ) but it's not clear this would reduce contention in the common case where
1789 all processes are allocating/freeing the same size.
1790 Thus we almost certainly need to divide in other ways: the most obvious
1791 is to divide the file into zones, and using a free list (or set of free
1793 This approximates address ordering.
1796 \begin_layout Standard
1797 Note that this means we need to split the free lists when we expand the
1798 file; this is probably acceptable when we double the hash table size, since
1799 that is such an expensive operation already.
1800 In the case of increasing the file size, there is an optimization we can
1801 use: if we use M in the formula above as the file size rounded up to the
1802 next power of 2, we only need reshuffle free lists when the file size crosses
1803 a power of 2 boundary,
1807 reshuffling the free lists is trivial: we simply merge every consecutive
1811 \begin_layout Standard
1812 The basic algorithm is as follows.
1816 \begin_layout Enumerate
1817 Identify the correct zone.
1820 \begin_layout Enumerate
1821 Lock the corresponding list.
1824 \begin_layout Enumerate
1825 Re-check the zone (we didn't have a lock, sizes could have changed): relock
1829 \begin_layout Enumerate
1830 Place the freed entry in the list for that zone.
1833 \begin_layout Standard
1834 Allocation is a little more complicated, as we perform delayed coalescing
1838 \begin_layout Enumerate
1839 Pick a zone either the zone we last freed into, or based on a
1840 \begin_inset Quotes eld
1844 \begin_inset Quotes erd
1850 \begin_layout Enumerate
1851 Lock the corresponding list.
1854 \begin_layout Enumerate
1855 Re-check the zone: relock if necessary.
1858 \begin_layout Enumerate
1859 If the top entry is -large enough, remove it from the list and return it.
1862 \begin_layout Enumerate
1863 Otherwise, coalesce entries in the list.If there was no entry large enough,
1864 unlock the list and try the next zone.
1867 \begin_layout Enumerate
1868 If no zone satisfies, expand the file.
1871 \begin_layout Standard
1872 This optimizes rapid insert/delete of free list entries by not coalescing
1874 First-fit address ordering ordering seems to be fairly good for keeping
1875 fragmentation low (see
1876 \begin_inset CommandInset ref
1878 reference "sub:TDB-Becomes-Fragmented"
1883 Note that address ordering does not need a tailer to coalesce, though if
1884 we needed one we could have one cheaply: see
1885 \begin_inset CommandInset ref
1887 reference "sub:Records-Incur-A"
1895 \begin_layout Standard
1896 I anticipate that the number of entries in each free zone would be small,
1897 but it might be worth using one free entry to hold pointers to the others
1898 for cache efficiency.
1899 \change_inserted 0 1283309850
1903 \begin_layout Standard
1905 \change_inserted 0 1283337216
1906 \begin_inset CommandInset label
1908 name "freelist-in-zone"
1912 If we want to avoid locking complexity (enlarging the free lists when we
1913 enlarge the file) we could place the array of free lists at the beginning
1915 This means existing array lists never move, but means that a record cannot
1916 be larger than a zone.
1917 That in turn implies that zones should be variable sized (say, power of
1918 2), which makes the question
1919 \begin_inset Quotes eld
1922 what zone is this record in?
1923 \begin_inset Quotes erd
1927 \begin_inset Quotes eld
1931 \begin_inset Quotes erd
1934 , but that's less common).
1935 It could be done with as few as 4 bits from the record header.
1939 \begin_layout Plain Layout
1941 \change_inserted 0 1283310945
1943 \begin_inset Formula $2^{16+N*3}$
1946 means 0 gives a minimal 65536-byte zone, 15 gives the maximal
1947 \begin_inset Formula $2^{61}$
1951 Zones range in factor of 8 steps.
1963 \begin_layout Subsection
1964 \begin_inset CommandInset label
1966 name "sub:TDB-Becomes-Fragmented"
1970 TDB Becomes Fragmented
1973 \begin_layout Standard
1974 Much of this is a result of allocation strategy
1978 \begin_layout Plain Layout
1979 The Memory Fragmentation Problem: Solved? Johnstone & Wilson 1995 ftp://ftp.cs.ute
1980 xas.edu/pub/garbage/malloc/ismm98.ps
1985 and deliberate hobbling of coalescing; internal fragmentation (aka overallocati
1986 on) is deliberately set at 25%, and external fragmentation is only cured
1987 by the decision to repack the entire db when a transaction commit needs
1988 to enlarge the file.
1991 \begin_layout Subsubsection
1995 \begin_layout Standard
1996 The 25% overhead on allocation works in practice for ldb because indexes
1997 tend to expand by one record at a time.
1998 This internal fragmentation can be resolved by having an
1999 \begin_inset Quotes eld
2003 \begin_inset Quotes erd
2006 bit in the header to note entries that have previously expanded, and allocating
2007 more space for them.
2010 \begin_layout Standard
2011 There are is a spectrum of possible solutions for external fragmentation:
2012 one is to use a fragmentation-avoiding allocation strategy such as best-fit
2013 address-order allocator.
2014 The other end of the spectrum would be to use a bump allocator (very fast
2015 and simple) and simply repack the file when we reach the end.
2018 \begin_layout Standard
2019 There are three problems with efficient fragmentation-avoiding allocators:
2020 they are non-trivial, they tend to use a single free list for each size,
2021 and there's no evidence that tdb allocation patterns will match those recorded
2022 for general allocators (though it seems likely).
2025 \begin_layout Standard
2026 Thus we don't spend too much effort on external fragmentation; we will be
2027 no worse than the current code if we need to repack on occasion.
2028 More effort is spent on reducing freelist contention, and reducing overhead.
2031 \begin_layout Subsection
2032 \begin_inset CommandInset label
2034 name "sub:Records-Incur-A"
2038 Records Incur A 28-Byte Overhead
2041 \begin_layout Standard
2042 Each TDB record has a header as follows:
2045 \begin_layout LyX-Code
2049 \begin_layout LyX-Code
2050 tdb_off_t next; /* offset of the next record in the list */
2053 \begin_layout LyX-Code
2054 tdb_len_t rec_len; /* total byte length of record */
2057 \begin_layout LyX-Code
2058 tdb_len_t key_len; /* byte length of key */
2061 \begin_layout LyX-Code
2062 tdb_len_t data_len; /* byte length of data */
2065 \begin_layout LyX-Code
2066 uint32_t full_hash; /* the full 32 bit hash of the key */
2069 \begin_layout LyX-Code
2070 uint32_t magic; /* try to catch errors */
2073 \begin_layout LyX-Code
2074 /* the following union is implied:
2077 \begin_layout LyX-Code
2081 \begin_layout LyX-Code
2082 char record[rec_len];
2085 \begin_layout LyX-Code
2089 \begin_layout LyX-Code
2093 \begin_layout LyX-Code
2094 char data[data_len];
2097 \begin_layout LyX-Code
2101 \begin_layout LyX-Code
2102 uint32_t totalsize; (tailer)
2105 \begin_layout LyX-Code
2109 \begin_layout LyX-Code
2113 \begin_layout LyX-Code
2117 \begin_layout Standard
2118 Naively, this would double to a 56-byte overhead on a 64 bit implementation.
2121 \begin_layout Subsubsection
2125 \begin_layout Standard
2126 We can use various techniques to reduce this for an allocated block:
2129 \begin_layout Enumerate
2130 The 'next' pointer is not required, as we are using a flat hash table.
2133 \begin_layout Enumerate
2134 'rec_len' can instead be expressed as an addition to key_len and data_len
2135 (it accounts for wasted or overallocated length in the record).
2136 Since the record length is always a multiple of 8, we can conveniently
2137 fit it in 32 bits (representing up to 35 bits).
2140 \begin_layout Enumerate
2141 'key_len' and 'data_len' can be reduced.
2142 I'm unwilling to restrict 'data_len' to 32 bits, but instead we can combine
2143 the two into one 64-bit field and using a 5 bit value which indicates at
2144 what bit to divide the two.
2145 Keys are unlikely to scale as fast as data, so I'm assuming a maximum key
2149 \begin_layout Enumerate
2150 'full_hash' is used to avoid a memcmp on the
2151 \begin_inset Quotes eld
2155 \begin_inset Quotes erd
2158 case, but this is diminishing returns after a handful of bits (at 10 bits,
2159 it reduces 99.9% of false memcmp).
2160 As an aside, as the lower bits are already incorporated in the hash table
2161 resolution, the upper bits should be used here.
2163 \change_inserted 0 1283336739
2164 Note that it's not clear that these bits will be a win, given the extra
2165 bits in the hash table itself (see
2166 \begin_inset CommandInset ref
2168 reference "sub:Hash-Size-Solution"
2177 \begin_layout Enumerate
2178 'magic' does not need to be enlarged: it currently reflects one of 5 values
2179 (used, free, dead, recovery, and unused_recovery).
2180 It is useful for quick sanity checking however, and should not be eliminated.
2183 \begin_layout Enumerate
2184 'tailer' is only used to coalesce free blocks (so a block to the right can
2185 find the header to check if this block is free).
2186 This can be replaced by a single 'free' bit in the header of the following
2187 block (and the tailer only exists in free blocks).
2191 \begin_layout Plain Layout
2192 This technique from Thomas Standish.
2193 Data Structure Techniques.
2194 Addison-Wesley, Reading, Massachusetts, 1980.
2199 The current proposed coalescing algorithm doesn't need this, however.
2202 \begin_layout Standard
2203 This produces a 16 byte used header like this:
2206 \begin_layout LyX-Code
2207 struct tdb_used_record {
2210 \begin_layout LyX-Code
2211 uint32_t magic : 16,
2214 \begin_layout LyX-Code
2218 \begin_layout LyX-Code
2222 \begin_layout LyX-Code
2226 \begin_layout LyX-Code
2227 uint32_t extra_octets;
2230 \begin_layout LyX-Code
2231 uint64_t key_and_data_len;
2234 \begin_layout LyX-Code
2238 \begin_layout Standard
2239 And a free record like this:
2242 \begin_layout LyX-Code
2243 struct tdb_free_record {
2246 \begin_layout LyX-Code
2247 uint32_t free_magic;
2250 \begin_layout LyX-Code
2251 uint64_t total_length;
2252 \change_inserted 0 1283337133
2256 \begin_layout LyX-Code
2258 \change_inserted 0 1283337139
2259 uint64_t prev, next;
2264 \begin_layout LyX-Code
2268 \begin_layout LyX-Code
2272 \begin_layout LyX-Code
2276 \begin_layout Standard
2278 \change_inserted 0 1283337235
2279 We might want to take some bits from the used record's top_hash (and the
2280 free record which has 32 bits of padding to spare anyway) if we use variable
2283 \begin_inset CommandInset ref
2285 reference "freelist-in-zone"
2294 \begin_layout Subsection
2295 Transaction Commit Requires 4 fdatasync
2298 \begin_layout Standard
2299 The current transaction algorithm is:
2302 \begin_layout Enumerate
2303 write_recovery_data();
2306 \begin_layout Enumerate
2310 \begin_layout Enumerate
2311 write_recovery_header();
2314 \begin_layout Enumerate
2318 \begin_layout Enumerate
2319 overwrite_with_new_data();
2322 \begin_layout Enumerate
2326 \begin_layout Enumerate
2327 remove_recovery_header();
2330 \begin_layout Enumerate
2334 \begin_layout Standard
2335 On current ext3, each sync flushes all data to disk, so the next 3 syncs
2336 are relatively expensive.
2337 But this could become a performance bottleneck on other filesystems such
2341 \begin_layout Subsubsection
2345 \begin_layout Standard
2346 Neil Brown points out that this is overzealous, and only one sync is needed:
2349 \begin_layout Enumerate
2350 Bundle the recovery data, a transaction counter and a strong checksum of
2354 \begin_layout Enumerate
2355 Strong checksum that whole bundle.
2358 \begin_layout Enumerate
2359 Store the bundle in the database.
2362 \begin_layout Enumerate
2363 Overwrite the oldest of the two recovery pointers in the header (identified
2364 using the transaction counter) with the offset of this bundle.
2367 \begin_layout Enumerate
2371 \begin_layout Enumerate
2372 Write the new data to the file.
2375 \begin_layout Standard
2376 Checking for recovery means identifying the latest bundle with a valid checksum
2377 and using the new data checksum to ensure that it has been applied.
2378 This is more expensive than the current check, but need only be done at
2380 For running databases, a separate header field can be used to indicate
2381 a transaction in progress; we need only check for recovery if this is set.
2384 \begin_layout Subsection
2385 \begin_inset CommandInset label
2387 name "sub:TDB-Does-Not"
2391 TDB Does Not Have Snapshot Support
2394 \begin_layout Subsubsection
2398 \begin_layout Standard
2400 At some point you say
2401 \begin_inset Quotes eld
2405 \begin_inset Quotes erd
2411 \begin_layout Standard
2412 But as a thought experiment, if we implemented transactions to only overwrite
2413 free entries (this is tricky: there must not be a header in each entry
2414 which indicates whether it is free, but use of presence in metadata elsewhere),
2415 and a pointer to the hash table, we could create an entirely new commit
2416 without destroying existing data.
2417 Then it would be easy to implement snapshots in a similar way.
2420 \begin_layout Standard
2421 This would not allow arbitrary changes to the database, such as tdb_repack
2422 does, and would require more space (since we have to preserve the current
2423 and future entries at once).
2424 If we used hash trees rather than one big hash table, we might only have
2425 to rewrite some sections of the hash, too.
2428 \begin_layout Standard
2429 We could then implement snapshots using a similar method, using multiple
2430 different hash tables/free tables.
2433 \begin_layout Subsection
2434 Transactions Cannot Operate in Parallel
2437 \begin_layout Standard
2438 This would be useless for ldb, as it hits the index records with just about
2440 It would add significant complexity in resolving clashes, and cause the
2441 all transaction callers to write their code to loop in the case where the
2442 transactions spuriously failed.
2445 \begin_layout Subsubsection
2449 \begin_layout Standard
2450 We could solve a small part of the problem by providing read-only transactions.
2451 These would allow one write transaction to begin, but it could not commit
2452 until all r/o transactions are done.
2453 This would require a new RO_TRANSACTION_LOCK, which would be upgraded on
2457 \begin_layout Subsection
2458 Default Hash Function Is Suboptimal
2461 \begin_layout Standard
2462 The Knuth-inspired multiplicative hash used by tdb is fairly slow (especially
2463 if we expand it to 64 bits), and works best when the hash bucket size is
2464 a prime number (which also means a slow modulus).
2465 In addition, it is highly predictable which could potentially lead to a
2466 Denial of Service attack in some TDB uses.
2469 \begin_layout Subsubsection
2473 \begin_layout Standard
2474 The Jenkins lookup3 hash
2478 \begin_layout Plain Layout
2479 http://burtleburtle.net/bob/c/lookup3.c
2484 is a fast and superbly-mixing hash.
2485 It's used by the Linux kernel and almost everything else.
2486 This has the particular properties that it takes an initial seed, and produces
2487 two 32 bit hash numbers, which we can combine into a 64-bit hash.
2490 \begin_layout Standard
2491 The seed should be created at tdb-creation time from some random source,
2492 and placed in the header.
2493 This is far from foolproof, but adds a little bit of protection against
2497 \begin_layout Subsection
2498 \begin_inset CommandInset label
2500 name "Reliable-Traversal-Adds"
2504 Reliable Traversal Adds Complexity
2507 \begin_layout Standard
2508 We lock a record during traversal iteration, and try to grab that lock in
2510 If that grab on delete fails, we simply mark it deleted and continue onwards;
2511 traversal checks for this condition and does the delete when it moves off
2515 \begin_layout Standard
2516 If traversal terminates, the dead record may be left indefinitely.
2519 \begin_layout Subsubsection
2523 \begin_layout Standard
2524 Remove reliability guarantees; see
2525 \begin_inset CommandInset ref
2527 reference "traverse-Proposed-Solution"
2534 \begin_layout Subsection
2535 Fcntl Locking Adds Overhead
2538 \begin_layout Standard
2539 Placing a fcntl lock means a system call, as does removing one.
2540 This is actually one reason why transactions can be faster (everything
2541 is locked once at transaction start).
2542 In the uncontended case, this overhead can theoretically be eliminated.
2545 \begin_layout Subsubsection
2549 \begin_layout Standard
2553 \begin_layout Standard
2554 We tried this before with spinlock support, in the early days of TDB, and
2555 it didn't make much difference except in manufactured benchmarks.
2558 \begin_layout Standard
2559 We could use spinlocks (with futex kernel support under Linux), but it means
2560 that we lose automatic cleanup when a process dies with a lock.
2561 There is a method of auto-cleanup under Linux, but it's not supported by
2562 other operating systems.
2563 We could reintroduce a clear-if-first-style lock and sweep for dead futexes
2564 on open, but that wouldn't help the normal case of one concurrent opener
2566 Increasingly elaborate repair schemes could be considered, but they require
2567 an ABI change (everyone must use them) anyway, so there's no need to do
2568 this at the same time as everything else.
2571 \begin_layout Subsection
2572 Some Transactions Don't Require Durability
2575 \begin_layout Standard
2576 Volker points out that gencache uses a CLEAR_IF_FIRST tdb for normal (fast)
2577 usage, and occasionally empties the results into a transactional TDB.
2578 This kind of usage prioritizes performance over durability: as long as
2579 we are consistent, data can be lost.
2582 \begin_layout Standard
2583 This would be more neatly implemented inside tdb: a
2584 \begin_inset Quotes eld
2588 \begin_inset Quotes erd
2591 transaction commit (ie.
2592 syncless) which meant that data may be reverted on a crash.
2595 \begin_layout Subsubsection
2599 \begin_layout Standard
2603 \begin_layout Standard
2604 Unfortunately any transaction scheme which overwrites old data requires
2605 a sync before that overwrite to avoid the possibility of corruption.
2608 \begin_layout Standard
2609 It seems possible to use a scheme similar to that described in
2610 \begin_inset CommandInset ref
2612 reference "sub:TDB-Does-Not"
2616 ,where transactions are committed without overwriting existing data, and
2617 an array of top-level pointers were available in the header.
2618 If the transaction is
2619 \begin_inset Quotes eld
2623 \begin_inset Quotes erd
2626 then we would not need a sync at all: existing processes would pick up
2627 the new hash table and free list and work with that.
2630 \begin_layout Standard
2631 At some later point, a sync would allow recovery of the old data into the
2632 free lists (perhaps when the array of top-level pointers filled).
2633 On crash, tdb_open() would examine the array of top levels, and apply the
2634 transactions until it encountered an invalid checksum.
2644 @Remove bogus footnote
2649 \change_inserted 0 1283307544
2658 @Moving hash table does not work.
2665 \begin_layout Plain Layout
2667 \change_inserted 0 1283336450
2668 If we make the hash offsets zone-relative, then this only restricts the
2669 zone size, not the overall database size.
2691 There are three details which become important:
2706 \begin_layout LyX-Code
2712 @Soft transaction commit
2717 \author "Rusty Russell,,,"
2720 \change_deleted 0 1280141199
2722 \change_inserted 0 1280141202
2728 \change_inserted 0 1280140902
2733 \change_inserted 0 1280140661
2737 \change_inserted 0 1280140703
2740 \change_inserted 0 1280708312
2743 \change_inserted 0 1280708400
2746 \change_inserted 0 1280140836
2749 \change_inserted 0 1280708255
2752 \change_inserted 0 1280708374
2755 \change_inserted 0 1280141181
2758 \change_inserted 0 1280141345
2779 @Transaction and freelist rethink.
2784 \author "Rusty Russell,,,"
2790 behavior of disallowing
2791 \change_inserted 0 1272940179
2794 transactions should become the default.
2796 \change_inserted 0 1272944650
2800 \change_inserted 0 1272944763
2809 \change_inserted 0 1273478114
2816 \change_deleted 0 1273469807
2818 \change_inserted 0 1273469810
2822 \change_deleted 0 1273469815
2825 to reduce contention.
2827 \change_inserted 0 1273470006
2831 \change_inserted 0 1273492055
2834 \change_inserted 0 1273483888
2840 \change_deleted 0 1272942055
2841 There are various ways to organize these lisys, but because we want to be
2842 able to quickly identify which free list an entry is in, and reduce the
2843 number of locks required for merging, we will use zoning (eg.
2844 each free list covers some fixed fraction of the file).
2846 \change_inserted 0 1273484187
2850 \change_deleted 0 1273484194
2852 \change_inserted 0 1273484194
2858 Identify the correct
2859 \change_deleted 0 1273482856
2861 \change_inserted 0 1273482857
2868 \change_inserted 0 1273482895
2872 \change_inserted 0 1273482863
2876 \change_inserted 0 1273482909
2880 \change_deleted 0 1273482885
2882 \change_inserted 0 1273482888
2885 lace the freed entry
2886 \change_deleted 0 1273492415
2888 \change_inserted 0 1273492415
2889 in the list for that zone
2894 Allocation is a little more complicated, as we
2895 \change_deleted 0 1273483240
2896 merge entries as we walk the list:
2897 \change_inserted 0 1273484250
2898 perform delayed coalescing at this point:
2904 \change_deleted 0 1273482955
2906 \change_inserted 0 1273482957
2910 \change_deleted 0 1273482962
2912 \change_inserted 0 1273482962
2916 \change_deleted 0 1273482966
2918 \change_inserted 0 1273482966
2925 \change_inserted 0 1273482980
2927 \change_deleted 0 1273482973
2931 \change_inserted 0 1273482982
2935 \change_inserted 0 1273483084
2941 \begin_layout Enumerate
2943 \change_deleted 0 1273492155
2945 \change_inserted 0 1273492159
2948 remove it from the list and return it.
2951 \begin_layout Enumerate
2953 \change_inserted 0 1273492206
2954 coalesce entries in the list.
2955 \change_deleted 0 1273492200
2956 examine the entry to the right of it in the file.
2961 \begin_layout Enumerate
2963 \change_deleted 0 1273492200
2964 If that entry is in a different list, lock that list too.
2967 \begin_layout Enumerate
2969 \change_deleted 0 1273492200
2970 If we had to place a new lock, re-check that the entry is free.
2973 \begin_layout Enumerate
2975 \change_deleted 0 1273492200
2976 Remove that entry from its free list and expand this entry to cover it.
2979 \begin_layout Enumerate
2981 \change_deleted 0 1273485554
2986 \begin_layout Enumerate
2988 \change_inserted 0 1273485311
2989 If there was no entry large enough, unlock the list and try the next zone.
2993 \change_deleted 0 1273483646
2994 Repeat step 3 with each entry in the list.
3000 \change_deleted 0 1273483668
3001 Unlock the list and repeat step 2 with the next list.
3007 \change_deleted 0 1273483671
3009 \change_inserted 0 1273483671
3012 satisfies, expand the file.
3015 This optimizes rapid insert/delete of free list entries
3016 \change_inserted 0 1273485794
3017 by not coalescing them all the time.
3018 \change_deleted 0 1273483685
3019 , and allows us to get rid of the tailer altogether
3023 \change_inserted 0 1273492299
3026 \change_deleted 0 1273476840
3028 \begin_inset Quotes eld
3032 \begin_inset Quotes erd
3035 free entries is more difficult: the 25% overhead works in practice for
3036 ldb because indexes tend to expand by one record at a time.
3037 This can be resolved by having an
3038 \begin_inset Quotes eld
3042 \begin_inset Quotes erd
3045 bit in the header to note entries that have previously expanded, and allocating
3046 more space for them.
3048 \begin_inset Quotes eld
3052 \begin_inset Quotes erd
3055 algorithm should be implemented or first-fit used is still unknown: we
3056 will determine this once these other ideas are implemented.
3057 \change_inserted 0 1273483750
3061 \begin_layout Standard
3063 \change_inserted 0 1273492450
3066 \change_inserted 0 1273470441
3069 \change_inserted 0 1273476556
3072 \change_inserted 0 1273470423
3078 \change_inserted 0 1273476847
3081 \change_inserted 0 1273476886
3084 \change_inserted 0 1273477233
3087 \change_inserted 0 1273477534
3090 \change_inserted 0 1273482700
3093 \change_inserted 0 1273478079
3096 \change_inserted 0 1273477839
3099 \change_inserted 0 1273477925
3102 \change_inserted 0 1273477925
3105 \change_inserted 0 1273477925
3108 \change_inserted 0 1273477925
3111 \change_inserted 0 1273477925
3114 \change_inserted 0 1273477925
3117 \change_inserted 0 1273477925
3120 \change_inserted 0 1273477925
3123 \change_inserted 0 1273477925
3126 \change_inserted 0 1273477925
3129 \change_inserted 0 1273477925
3132 \change_inserted 0 1273477925
3135 \change_inserted 0 1273477925
3138 \change_inserted 0 1273477925
3141 \change_inserted 0 1273477925
3144 \change_inserted 0 1273477925
3147 \change_inserted 0 1273477925
3150 \change_inserted 0 1273477925
3153 \change_inserted 0 1273492522
3156 \change_inserted 0 1273492530
3159 \change_inserted 0 1273492546
3162 \change_inserted 0 1273478239
3165 \change_inserted 0 1273479960
3168 \change_inserted 0 1273480265
3171 \change_inserted 0 1273480354
3174 \change_inserted 0 1273478968
3177 \change_inserted 0 1273492604
3180 \change_inserted 0 1273479572
3186 \change_inserted 0 1273480282
3189 \change_inserted 0 1273478931
3192 \change_inserted 0 1273481549
3195 \change_inserted 0 1273481557
3198 \change_inserted 0 1273480307
3201 \change_inserted 0 1273480335
3204 \change_inserted 0 1273479897
3207 \change_inserted 0 1273479653
3210 \change_inserted 0 1273480371
3213 \change_inserted 0 1273480464
3216 \change_inserted 0 1273480399
3219 \change_inserted 0 1273480425
3222 \change_inserted 0 1273480453
3225 \change_inserted 0 1273480455
3228 \change_inserted 0 1273480450
3231 \change_inserted 0 1273480452
3233 \change_inserted 0 1273478830
3237 \change_deleted 0 1273481604
3238 In theory, we could get away with 2: one after we write the new data, and
3239 one to somehow atomically change over to it.
3240 \change_inserted 0 1273481632
3243 \change_inserted 0 1273481724
3246 \change_inserted 0 1273481713
3249 \change_inserted 0 1273481717
3252 \change_inserted 0 1273481730
3255 \change_inserted 0 1273481736
3258 \change_inserted 0 1273481744
3261 \change_inserted 0 1273481748
3264 \change_inserted 0 1273482185
3267 \change_inserted 0 1273482259
3270 \change_deleted 0 1273481848
3272 Trying to rewrite the transaction code is a separate experiment, which
3273 I encourage someone else to do.
3274 At some point you say
3275 \begin_inset Quotes eld
3279 \begin_inset Quotes erd
3285 \begin_layout Standard
3287 \change_deleted 0 1273481848
3288 But as a thought experiment:
3293 \begin_layout Standard
3295 \change_deleted 0 1273481788
3296 Say there was a pointer in the header which said where the hash table and
3297 free list tables were, and that no blocks were labeled with whether they
3298 were free or not (it had to be derived from what list they were in).
3299 We could create new hash table and free list in some free space, and populate
3300 it as we want the post-committed state to look.
3301 Then we sync, then we switch the offset in the header, then we sync again.
3304 \begin_layout Standard
3306 \change_deleted 0 1273481788
3307 This would not allow arbitrary changes to the database, such as tdb_repack
3308 does, and would require more space (since we have to preserve the current
3309 and future entries at once).
3310 If we used hash trees rather than one big hash table, we might only have
3311 to rewrite some sections of the hash, too.
3312 \change_inserted 0 1273481854
3316 \begin_layout Standard
3318 \change_inserted 0 1273482102
3321 \change_inserted 0 1273482061
3324 \change_inserted 0 1273482063
3327 \change_inserted 0 1273482072
3330 \change_inserted 0 1273482139
3333 \change_inserted 0 1273482364
3336 \change_inserted 0 1273482163
3339 \change_inserted 0 1273482493
3342 \change_inserted 0 1273482536
3348 \change_inserted 0 1273482641
3351 \change_inserted 0 1273481827
3355 \change_inserted 0 1273481829
3358 implement snapshots using a similar method
3359 \change_deleted 0 1273481838
3361 \change_inserted 0 1273481840
3364 using multiple different hash tables/free tables.
3370 @After first feedback (Ronnie & Volker)
3376 The free list should be split into multiple lists to reduce contention.
3381 The algorithm for freeing is simple:
3384 Identify the correct free list.
3387 Lock the list, and place the freed entry at the head.
3390 Allocation is a little more complicated, as we merge entries as we walk
3394 Pick a free list; either the list we last freed onto, or based on a
3400 If the top entry is well-sized, remove it from the list and return it.
3403 Otherwise, examine the entry to the right of it in the file.
3414 If no list satisfies, expand the file.
3417 This optimizes rapid insert/delete of free list entries, and allows us to
3418 get rid of the tailer altogether.
3422 \change_inserted 0 1272941474
3425 \change_inserted 0 1272942759
3426 There are various ways to organize these lists, but because we want to be
3427 able to quickly identify which free list an entry is in, and reduce the
3428 number of locks required for merging, we will use zoning (eg.
3429 each of the N free lists in a tdb file of size M covers a fixed fraction
3431 Note that this means we need to reshuffle the free lists when we expand
3432 the file; this is probably acceptable when we double the hash table size,
3433 since that is such an expensive operation already.
3434 In the case of increasing the file size, there is an optimization we can
3435 use: if we use M in the formula above as the file size rounded up to the
3436 next power of 2, we only need reshuffle free lists when the file size crosses
3437 a power of 2 boundary,
3441 reshuffling the free lists is trivial: we simply merge every consecutive
3455 We could implement snapshots using a similar method to the above, only using
3456 multiple different hash tables/free tables.
3467 #LyX 1.6.4 created this file. For more info see http://www.lyx.org/
3470 \tracking_changes false
3471 \output_changes false
3475 behavior of disallowing transactions should become the default.
3480 The algorithm for freeing is simple: