1 TDB2: A Redesigning The Trivial DataBase
3 Rusty Russell, IBM Corporation
9 The Trivial DataBase on-disk format is 32 bits; with usage cases
10 heading towards the 4G limit, that must change. This required
11 breakage provides an opportunity to revisit TDB's other design
12 decisions and reassess them.
16 The Trivial DataBase was originally written by Andrew Tridgell as
17 a simple key/data pair storage system with the same API as dbm,
18 but allowing multiple readers and writers while being small
19 enough (< 1000 lines of C) to include in SAMBA. The simple design
20 created in 1999 has proven surprisingly robust and performant,
21 used in Samba versions 3 and 4 as well as numerous other
22 projects. Its useful life was greatly increased by the
23 (backwards-compatible!) addition of transaction support in 2005.
25 The wider variety and greater demands of TDB-using code has lead
26 to some organic growth of the API, as well as some compromises on
27 the implementation. None of these, by themselves, are seen as
28 show-stoppers, but the cumulative effect is to a loss of elegance
29 over the initial, simple TDB implementation. Here is a table of
30 the approximate number of lines of implementation code and number
31 of API functions at the end of each year:
34 +-----------+----------------+--------------------------------+
35 | Year End | API Functions | Lines of C Code Implementation |
36 +-----------+----------------+--------------------------------+
37 +-----------+----------------+--------------------------------+
39 +-----------+----------------+--------------------------------+
41 +-----------+----------------+--------------------------------+
43 +-----------+----------------+--------------------------------+
45 +-----------+----------------+--------------------------------+
47 +-----------+----------------+--------------------------------+
49 +-----------+----------------+--------------------------------+
51 +-----------+----------------+--------------------------------+
53 +-----------+----------------+--------------------------------+
55 +-----------+----------------+--------------------------------+
57 +-----------+----------------+--------------------------------+
59 +-----------+----------------+--------------------------------+
62 This review is an attempt to catalog and address all the known
63 issues with TDB and create solutions which address the problems
64 without significantly increasing complexity; all involved are far
65 too aware of the dangers of second system syndrome in rewriting a
66 successful project like this.
70 2.1 tdb_open_ex Is Not Expandable
72 The tdb_open() call was expanded to tdb_open_ex(), which added an
73 optional hashing function and an optional logging function
74 argument. Additional arguments to open would require the
75 introduction of a tdb_open_ex2 call etc.
77 2.1.1 Proposed Solution<attributes>
79 tdb_open() will take a linked-list of attributes:
83 TDB_ATTRIBUTE_LOG = 0,
85 TDB_ATTRIBUTE_HASH = 1
89 struct tdb_attribute_base {
91 enum tdb_attribute attr;
93 union tdb_attribute *next;
97 struct tdb_attribute_log {
99 struct tdb_attribute_base base; /* .attr = TDB_ATTRIBUTE_LOG
108 struct tdb_attribute_hash {
110 struct tdb_attribute_base base; /* .attr = TDB_ATTRIBUTE_HASH
113 tdb_hash_func hash_fn;
119 union tdb_attribute {
121 struct tdb_attribute_base base;
123 struct tdb_attribute_log log;
125 struct tdb_attribute_hash hash;
129 This allows future attributes to be added, even if this expands
130 the size of the union.
136 2.2 tdb_traverse Makes Impossible Guarantees
138 tdb_traverse (and tdb_firstkey/tdb_nextkey) predate transactions,
139 and it was thought that it was important to guarantee that all
140 records which exist at the start and end of the traversal would
141 be included, and no record would be included twice.
143 This adds complexity (see[Reliable-Traversal-Adds]) and does not
144 work anyway for records which are altered (in particular, those
145 which are expanded may be effectively deleted and re-added behind
148 2.2.1 <traverse-Proposed-Solution>Proposed Solution
150 Abandon the guarantee. You will see every record if no changes
151 occur during your traversal, otherwise you will see some subset.
152 You can prevent changes by using a transaction or the locking
157 Complete. Delete-during-traverse will still delete every record,
158 too (assuming no other changes).
160 2.3 Nesting of Transactions Is Fraught
162 TDB has alternated between allowing nested transactions and not
163 allowing them. Various paths in the Samba codebase assume that
164 transactions will nest, and in a sense they can: the operation is
165 only committed to disk when the outer transaction is committed.
166 There are two problems, however:
168 1. Canceling the inner transaction will cause the outer
169 transaction commit to fail, and will not undo any operations
170 since the inner transaction began. This problem is soluble with
171 some additional internal code.
173 2. An inner transaction commit can be cancelled by the outer
174 transaction. This is desirable in the way which Samba's
175 database initialization code uses transactions, but could be a
176 surprise to any users expecting a successful transaction commit
177 to expose changes to others.
179 The current solution is to specify the behavior at tdb_open(),
180 with the default currently that nested transactions are allowed.
181 This flag can also be changed at runtime.
183 2.3.1 Proposed Solution
185 Given the usage patterns, it seems that the “least-surprise”
186 behavior of disallowing nested transactions should become the
187 default. Additionally, it seems the outer transaction is the only
188 code which knows whether inner transactions should be allowed, so
189 a flag to indicate this could be added to tdb_transaction_start.
190 However, this behavior can be simulated with a wrapper which uses
191 tdb_add_flags() and tdb_remove_flags(), so the API should not be
192 expanded for this relatively-obscure case.
196 Incomplete; nesting flag is still defined as per tdb1.
198 2.4 Incorrect Hash Function is Not Detected
200 tdb_open_ex() allows the calling code to specify a different hash
201 function to use, but does not check that all other processes
202 accessing this tdb are using the same hash function. The result
203 is that records are missing from tdb_fetch().
205 2.4.1 Proposed Solution
207 The header should contain an example hash result (eg. the hash of
208 0xdeadbeef), and tdb_open_ex() should check that the given hash
209 function produces the same answer, or fail the tdb_open call.
215 2.5 tdb_set_max_dead/TDB_VOLATILE Expose Implementation
217 In response to scalability issues with the free list ([TDB-Freelist-Is]
218 ) two API workarounds have been incorporated in TDB:
219 tdb_set_max_dead() and the TDB_VOLATILE flag to tdb_open. The
220 latter actually calls the former with an argument of “5”.
222 This code allows deleted records to accumulate without putting
223 them in the free list. On delete we iterate through each chain
224 and free them in a batch if there are more than max_dead entries.
225 These are never otherwise recycled except as a side-effect of a
228 2.5.1 Proposed Solution
230 With the scalability problems of the freelist solved, this API
231 can be removed. The TDB_VOLATILE flag may still be useful as a
232 hint that store and delete of records will be at least as common
233 as fetch in order to allow some internal tuning, but initially
238 Incomplete. TDB_VOLATILE still defined, but implementation should
239 fail on unknown flags to be future-proof.
241 2.6 <TDB-Files-Cannot>TDB Files Cannot Be Opened Multiple Times
244 No process can open the same TDB twice; we check and disallow it.
245 This is an unfortunate side-effect of fcntl locks, which operate
246 on a per-file rather than per-file-descriptor basis, and do not
247 nest. Thus, closing any file descriptor on a file clears all the
248 locks obtained by this process, even if they were placed using a
249 different file descriptor!
251 Note that even if this were solved, deadlock could occur if
252 operations were nested: this is a more manageable programming
255 2.6.1 Proposed Solution
257 We could lobby POSIX to fix the perverse rules, or at least lobby
258 Linux to violate them so that the most common implementation does
259 not have this restriction. This would be a generally good idea
260 for other fcntl lock users.
262 Samba uses a wrapper which hands out the same tdb_context to
263 multiple callers if this happens, and does simple reference
264 counting. We should do this inside the tdb library, which already
265 emulates lock nesting internally; it would need to recognize when
266 deadlock occurs within a single process. This would create a new
267 failure mode for tdb operations (while we currently handle
268 locking failures, they are impossible in normal use and a process
269 encountering them can do little but give up).
271 I do not see benefit in an additional tdb_open flag to indicate
272 whether re-opening is allowed, as though there may be some
273 benefit to adding a call to detect when a tdb_context is shared,
274 to allow other to create such an API.
280 2.7 TDB API Is Not POSIX Thread-safe
282 The TDB API uses an error code which can be queried after an
283 operation to determine what went wrong. This programming model
284 does not work with threads, unless specific additional guarantees
285 are given by the implementation. In addition, even
286 otherwise-independent threads cannot open the same TDB (as in [TDB-Files-Cannot]
289 2.7.1 Proposed Solution
291 Reachitecting the API to include a tdb_errcode pointer would be a
292 great deal of churn; we are better to guarantee that the
293 tdb_errcode is per-thread so the current programming model can be
296 This requires dynamic per-thread allocations, which is awkward
297 with POSIX threads (pthread_key_create space is limited and we
298 cannot simply allocate a key for every TDB).
300 Internal locking is required to make sure that fcntl locks do not
301 overlap between threads, and also that the global list of tdbs is
304 The aim is that building tdb with -DTDB_PTHREAD will result in a
305 pthread-safe version of the library, and otherwise no overhead
306 will exist. Alternatively, a hooking mechanism similar to that
307 proposed for [Proposed-Solution-locking-hook] could be used to
308 enable pthread locking at runtime.
314 2.8 *_nonblock Functions And *_mark Functions Expose
318 Clustered TDB, see http://ctdb.samba.org
319 ] wishes to operate on TDB in a non-blocking manner. This is
320 currently done as follows:
322 1. Call the _nonblock variant of an API function (eg.
323 tdb_lockall_nonblock). If this fails:
325 2. Fork a child process, and wait for it to call the normal
326 variant (eg. tdb_lockall).
328 3. If the child succeeds, call the _mark variant to indicate we
329 already have the locks (eg. tdb_lockall_mark).
331 4. Upon completion, tell the child to release the locks (eg.
334 5. Indicate to tdb that it should consider the locks removed (eg.
337 There are several issues with this approach. Firstly, adding two
338 new variants of each function clutters the API for an obscure
339 use, and so not all functions have three variants. Secondly, it
340 assumes that all paths of the functions ask for the same locks,
341 otherwise the parent process will have to get a lock which the
342 child doesn't have under some circumstances. I don't believe this
343 is currently the case, but it constrains the implementation.
345 2.8.1 <Proposed-Solution-locking-hook>Proposed Solution
347 Implement a hook for locking methods, so that the caller can
348 control the calls to create and remove fcntl locks. In this
349 scenario, ctdbd would operate as follows:
351 1. Call the normal API function, eg tdb_lockall().
353 2. When the lock callback comes in, check if the child has the
354 lock. Initially, this is always false. If so, return 0.
355 Otherwise, try to obtain it in non-blocking mode. If that
356 fails, return EWOULDBLOCK.
358 3. Release locks in the unlock callback as normal.
360 4. If tdb_lockall() fails, see if we recorded a lock failure; if
361 so, call the child to repeat the operation.
363 5. The child records what locks it obtains, and returns that
364 information to the parent.
366 6. When the child has succeeded, goto 1.
368 This is flexible enough to handle any potential locking scenario,
369 even when lock requirements change. It can be optimized so that
370 the parent does not release locks, just tells the child which
371 locks it doesn't need to obtain.
373 It also keeps the complexity out of the API, and in ctdbd where
380 2.9 tdb_chainlock Functions Expose Implementation
382 tdb_chainlock locks some number of records, including the record
383 indicated by the given key. This gave atomicity guarantees;
384 no-one can start a transaction, alter, read or delete that key
385 while the lock is held.
387 It also makes the same guarantee for any other key in the chain,
388 which is an internal implementation detail and potentially a
391 2.9.1 Proposed Solution
393 None. It would be nice to have an explicit single entry lock
394 which effected no other keys. Unfortunately, this won't work for
395 an entry which doesn't exist. Thus while chainlock may be
396 implemented more efficiently for the existing case, it will still
397 have overlap issues with the non-existing case. So it is best to
398 keep the current (lack of) guarantee about which records will be
399 effected to avoid constraining our implementation.
401 2.10 Signal Handling is Not Race-Free
403 The tdb_setalarm_sigptr() call allows the caller's signal handler
404 to indicate that the tdb locking code should return with a
405 failure, rather than trying again when a signal is received (and
406 errno == EAGAIN). This is usually used to implement timeouts.
408 Unfortunately, this does not work in the case where the signal is
409 received before the tdb code enters the fcntl() call to place the
410 lock: the code will sleep within the fcntl() code, unaware that
411 the signal wants it to exit. In the case of long timeouts, this
412 does not happen in practice.
414 2.10.1 Proposed Solution
416 The locking hooks proposed in[Proposed-Solution-locking-hook]
417 would allow the user to decide on whether to fail the lock
418 acquisition on a signal. This allows the caller to choose their
419 own compromise: they could narrow the race by checking
420 immediately before the fcntl call.[footnote:
421 It may be possible to make this race-free in some implementations
422 by having the signal handler alter the struct flock to make it
423 invalid. This will cause the fcntl() lock call to fail with
424 EINVAL if the signal occurs before the kernel is entered,
432 2.11 The API Uses Gratuitous Typedefs, Capitals
434 typedefs are useful for providing source compatibility when types
435 can differ across implementations, or arguably in the case of
436 function pointer definitions which are hard for humans to parse.
437 Otherwise it is simply obfuscation and pollutes the namespace.
439 Capitalization is usually reserved for compile-time constants and
442 TDB_CONTEXT There is no reason to use this over 'struct
443 tdb_context'; the definition isn't visible to the API user
446 TDB_DATA There is no reason to use this over struct TDB_DATA;
447 the struct needs to be understood by the API user.
449 struct TDB_DATA This would normally be called 'struct
452 enum TDB_ERROR Similarly, this would normally be enum
455 2.11.1 Proposed Solution
457 None. Introducing lower case variants would please pedants like
458 myself, but if it were done the existing ones should be kept.
459 There is little point forcing a purely cosmetic change upon tdb
462 2.12 <tdb_log_func-Doesnt-Take>tdb_log_func Doesn't Take The
465 For API compatibility reasons, the logging function needs to call
466 tdb_get_logging_private() to retrieve the pointer registered by
467 the tdb_open_ex for logging.
469 2.12.1 Proposed Solution
471 It should simply take an extra argument, since we are prepared to
478 2.13 Various Callback Functions Are Not Typesafe
480 The callback functions in tdb_set_logging_function (after [tdb_log_func-Doesnt-Take]
481 is resolved), tdb_parse_record, tdb_traverse, tdb_traverse_read
482 and tdb_check all take void * and must internally convert it to
483 the argument type they were expecting.
485 If this type changes, the compiler will not produce warnings on
486 the callers, since it only sees void *.
488 2.13.1 Proposed Solution
490 With careful use of macros, we can create callback functions
491 which give a warning when used on gcc and the types of the
492 callback and its private argument differ. Unsupported compilers
493 will not give a warning, which is no worse than now. In addition,
494 the callbacks become clearer, as they need not use void * for
497 See CCAN's typesafe_cb module at
498 http://ccan.ozlabs.org/info/typesafe_cb.html
504 2.14 TDB_CLEAR_IF_FIRST Must Be Specified On All Opens,
505 tdb_reopen_all Problematic
507 The TDB_CLEAR_IF_FIRST flag to tdb_open indicates that the TDB
508 file should be cleared if the caller discovers it is the only
509 process with the TDB open. However, if any caller does not
510 specify TDB_CLEAR_IF_FIRST it will not be detected, so will have
511 the TDB erased underneath them (usually resulting in a crash).
513 There is a similar issue on fork(); if the parent exits (or
514 otherwise closes the tdb) before the child calls tdb_reopen_all()
515 to establish the lock used to indicate the TDB is opened by
516 someone, a TDB_CLEAR_IF_FIRST opener at that moment will believe
517 it alone has opened the TDB and will erase it.
519 2.14.1 Proposed Solution
521 Remove TDB_CLEAR_IF_FIRST. Other workarounds are possible, but
522 see [TDB_CLEAR_IF_FIRST-Imposes-Performance].
526 Incomplete, TDB_CLEAR_IF_FIRST still defined, but not
529 2.15 Extending The Header Is Difficult
531 We have reserved (zeroed) words in the TDB header, which can be
532 used for future features. If the future features are compulsory,
533 the version number must be updated to prevent old code from
534 accessing the database. But if the future feature is optional, we
535 have no way of telling if older code is accessing the database or
538 2.15.1 Proposed Solution
540 The header should contain a “format variant” value (64-bit). This
541 is divided into two 32-bit parts:
543 1. The lower part reflects the format variant understood by code
544 accessing the database.
546 2. The upper part reflects the format variant you must understand
547 to write to the database (otherwise you can only open for
550 The latter field can only be written at creation time, the former
551 should be written under the OPEN_LOCK when opening the database
552 for writing, if the variant of the code is lower than the current
555 This should allow backwards-compatible features to be added, and
556 detection if older code (which doesn't understand the feature)
557 writes to the database.
563 2.16 Record Headers Are Not Expandible
565 If we later want to add (say) checksums on keys and data, it
566 would require another format change, which we'd like to avoid.
568 2.16.1 Proposed Solution
570 We often have extra padding at the tail of a record. If we ensure
571 that the first byte (if any) of this padding is zero, we will
572 have a way for future changes to detect code which doesn't
573 understand a new format: the new code would write (say) a 1 at
574 the tail, and thus if there is no tail or the first byte is 0, we
575 would know the extension is not present on that record.
581 2.17 TDB Does Not Use Talloc
583 Many users of TDB (particularly Samba) use the talloc allocator,
584 and thus have to wrap TDB in a talloc context to use it
587 2.17.1 Proposed Solution
589 The allocation within TDB is not complicated enough to justify
590 the use of talloc, and I am reluctant to force another
591 (excellent) library on TDB users. Nonetheless a compromise is
592 possible. An attribute (see [attributes]) can be added later to
593 tdb_open() to provide an alternate allocation mechanism,
594 specifically for talloc but usable by any other allocator (which
595 would ignore the “context” argument).
597 This would form a talloc heirarchy as expected, but the caller
598 would still have to attach a destructor to the tdb context
599 returned from tdb_open to close it. All TDB_DATA fields would be
600 children of the tdb_context, and the caller would still have to
601 manage them (using talloc_free() or talloc_steal()).
607 3 Performance And Scalability Issues
609 3.1 <TDB_CLEAR_IF_FIRST-Imposes-Performance>TDB_CLEAR_IF_FIRST
610 Imposes Performance Penalty
612 When TDB_CLEAR_IF_FIRST is specified, a 1-byte read lock is
613 placed at offset 4 (aka. the ACTIVE_LOCK). While these locks
614 never conflict in normal tdb usage, they do add substantial
615 overhead for most fcntl lock implementations when the kernel
616 scans to detect if a lock conflict exists. This is often a single
617 linked list, making the time to acquire and release a fcntl lock
618 O(N) where N is the number of processes with the TDB open, not
619 the number actually doing work.
621 In a Samba server it is common to have huge numbers of clients
622 sitting idle, and thus they have weaned themselves off the
623 TDB_CLEAR_IF_FIRST flag.[footnote:
624 There is a flag to tdb_reopen_all() which is used for this
625 optimization: if the parent process will outlive the child, the
626 child does not need the ACTIVE_LOCK. This is a workaround for
627 this very performance issue.
630 3.1.1 Proposed Solution
632 Remove the flag. It was a neat idea, but even trivial servers
633 tend to know when they are initializing for the first time and
634 can simply unlink the old tdb at that point.
638 Incomplete; TDB_CLEAR_IF_FIRST still defined, but does nothing.
640 3.2 TDB Files Have a 4G Limit
642 This seems to be becoming an issue (so much for “trivial”!),
643 particularly for ldb.
645 3.2.1 Proposed Solution
647 A new, incompatible TDB format which uses 64 bit offsets
648 internally rather than 32 bit as now. For simplicity of endian
649 conversion (which TDB does on the fly if required), all values
650 will be 64 bit on disk. In practice, some upper bits may be used
651 for other purposes, but at least 56 bits will be available for
654 tdb_open() will automatically detect the old version, and even
655 create them if TDB_VERSION6 is specified to tdb_open.
657 32 bit processes will still be able to access TDBs larger than 4G
658 (assuming that their off_t allows them to seek to 64 bits), they
659 will gracefully fall back as they fail to mmap. This can happen
660 already with large TDBs.
662 Old versions of tdb will fail to open the new TDB files (since 28
663 August 2009, commit 398d0c29290: prior to that any unrecognized
664 file format would be erased and initialized as a fresh tdb!)
670 3.3 TDB Records Have a 4G Limit
672 This has not been a reported problem, and the API uses size_t
673 which can be 64 bit on 64 bit platforms. However, other limits
674 may have made such an issue moot.
676 3.3.1 Proposed Solution
678 Record sizes will be 64 bit, with an error returned on 32 bit
679 platforms which try to access such records (the current
680 implementation would return TDB_ERR_OOM in a similar case). It
681 seems unlikely that 32 bit keys will be a limitation, so the
682 implementation may not support this (see [sub:Records-Incur-A]).
688 3.4 Hash Size Is Determined At TDB Creation Time
690 TDB contains a number of hash chains in the header; the number is
691 specified at creation time, and defaults to 131. This is such a
692 bottleneck on large databases (as each hash chain gets quite
693 long), that LDB uses 10,000 for this hash. In general it is
694 impossible to know what the 'right' answer is at database
697 3.4.1 <sub:Hash-Size-Solution>Proposed Solution
699 After comprehensive performance testing on various scalable hash
701 http://rusty.ozlabs.org/?p=89 and http://rusty.ozlabs.org/?p=94
702 This was annoying because I was previously convinced that an
703 expanding tree of hashes would be very close to optimal.
704 ], it became clear that it is hard to beat a straight linear hash
705 table which doubles in size when it reaches saturation.
706 Unfortunately, altering the hash table introduces serious locking
707 complications: the entire hash table needs to be locked to
708 enlarge the hash table, and others might be holding locks.
709 Particularly insidious are insertions done under tdb_chainlock.
711 Thus an expanding layered hash will be used: an array of hash
712 groups, with each hash group exploding into pointers to lower
713 hash groups once it fills, turning into a hash tree. This has
714 implications for locking: we must lock the entire group in case
715 we need to expand it, yet we don't know how deep the tree is at
718 Note that bits from the hash table entries should be stolen to
719 hold more hash bits to reduce the penalty of collisions. We can
720 use the otherwise-unused lower 3 bits. If we limit the size of
721 the database to 64 exabytes, we can use the top 8 bits of the
722 hash entry as well. These 11 bits would reduce false positives
723 down to 1 in 2000 which is more than we need: we can use one of
724 the bits to indicate that the extra hash bits are valid. This
725 means we can choose not to re-hash all entries when we expand a
726 hash group; simply use the next bits we need and mark them
733 3.5 <TDB-Freelist-Is>TDB Freelist Is Highly Contended
735 TDB uses a single linked list for the free list. Allocation
736 occurs as follows, using heuristics which have evolved over time:
738 1. Get the free list lock for this whole operation.
740 2. Multiply length by 1.25, so we always over-allocate by 25%.
742 3. Set the slack multiplier to 1.
744 4. Examine the current freelist entry: if it is > length but <
745 the current best case, remember it as the best case.
747 5. Multiply the slack multiplier by 1.05.
749 6. If our best fit so far is less than length * slack multiplier,
750 return it. The slack will be turned into a new free record if
753 7. Otherwise, go onto the next freelist entry.
755 Deleting a record occurs as follows:
757 1. Lock the hash chain for this whole operation.
759 2. Walk the chain to find the record, keeping the prev pointer
762 3. If max_dead is non-zero:
764 (a) Walk the hash chain again and count the dead records.
766 (b) If it's more than max_dead, bulk free all the dead ones
767 (similar to steps 4 and below, but the lock is only obtained
770 (c) Simply mark this record as dead and return.
772 4. Get the free list lock for the remainder of this operation.
774 5. <right-merging>Examine the following block to see if it is
775 free; if so, enlarge the current block and remove that block
776 from the free list. This was disabled, as removal from the free
777 list was O(entries-in-free-list).
779 6. Examine the preceeding block to see if it is free: for this
780 reason, each block has a 32-bit tailer which indicates its
781 length. If it is free, expand it to cover our new block and
784 7. Otherwise, prepend ourselves to the free list.
786 Disabling right-merging (step [right-merging]) causes
787 fragmentation; the other heuristics proved insufficient to
788 address this, so the final answer to this was that when we expand
789 the TDB file inside a transaction commit, we repack the entire
792 The single list lock limits our allocation rate; due to the other
793 issues this is not currently seen as a bottleneck.
795 3.5.1 Proposed Solution
797 The first step is to remove all the current heuristics, as they
798 obviously interact, then examine them once the lock contention is
801 The free list must be split to reduce contention. Assuming
802 perfect free merging, we can at most have 1 free list entry for
803 each entry. This implies that the number of free lists is related
804 to the size of the hash table, but as it is rare to walk a large
805 number of free list entries we can use far fewer, say 1/32 of the
806 number of hash buckets.
808 It seems tempting to try to reuse the hash implementation which
809 we use for records here, but we have two ways of searching for
810 free entries: for allocation we search by size (and possibly
811 zone) which produces too many clashes for our hash table to
812 handle well, and for coalescing we search by address. Thus an
813 array of doubly-linked free lists seems preferable.
815 There are various benefits in using per-size free lists (see [sub:TDB-Becomes-Fragmented]
816 ) but it's not clear this would reduce contention in the common
817 case where all processes are allocating/freeing the same size.
818 Thus we almost certainly need to divide in other ways: the most
819 obvious is to divide the file into zones, and using a free list
820 (or table of free lists) for each. This approximates address
823 Unfortunately it is difficult to know what heuristics should be
824 used to determine zone sizes, and our transaction code relies on
825 being able to create a “recovery area” by simply appending to the
826 file (difficult if it would need to create a new zone header).
827 Thus we use a linked-list of free tables; currently we only ever
828 create one, but if there is more than one we choose one at random
829 to use. In future we may use heuristics to add new free tables on
830 contention. We only expand the file when all free tables are
833 The basic algorithm is as follows. Freeing is simple:
835 1. Identify the correct free list.
837 2. Lock the corresponding list.
839 3. Re-check the list (we didn't have a lock, sizes could have
840 changed): relock if necessary.
842 4. Place the freed entry in the list.
844 Allocation is a little more complicated, as we perform delayed
845 coalescing at this point:
847 1. Pick a free table; usually the previous one.
849 2. Lock the corresponding list.
851 3. If the top entry is -large enough, remove it from the list and
854 4. Otherwise, coalesce entries in the list.If there was no entry
855 large enough, unlock the list and try the next largest list
857 5. If no list has an entry which meets our needs, try the next
860 6. If no zone satisfies, expand the file.
862 This optimizes rapid insert/delete of free list entries by not
863 coalescing them all the time.. First-fit address ordering
864 ordering seems to be fairly good for keeping fragmentation low
865 (see [sub:TDB-Becomes-Fragmented]). Note that address ordering
866 does not need a tailer to coalesce, though if we needed one we
867 could have one cheaply: see [sub:Records-Incur-A].
869 Each free entry has the free table number in the header: less
870 than 255. It also contains a doubly-linked list for easy
873 3.6 <sub:TDB-Becomes-Fragmented>TDB Becomes Fragmented
875 Much of this is a result of allocation strategy[footnote:
876 The Memory Fragmentation Problem: Solved? Johnstone & Wilson 1995
877 ftp://ftp.cs.utexas.edu/pub/garbage/malloc/ismm98.ps
878 ] and deliberate hobbling of coalescing; internal fragmentation
879 (aka overallocation) is deliberately set at 25%, and external
880 fragmentation is only cured by the decision to repack the entire
881 db when a transaction commit needs to enlarge the file.
883 3.6.1 Proposed Solution
885 The 25% overhead on allocation works in practice for ldb because
886 indexes tend to expand by one record at a time. This internal
887 fragmentation can be resolved by having an “expanded” bit in the
888 header to note entries that have previously expanded, and
889 allocating more space for them.
891 There are is a spectrum of possible solutions for external
892 fragmentation: one is to use a fragmentation-avoiding allocation
893 strategy such as best-fit address-order allocator. The other end
894 of the spectrum would be to use a bump allocator (very fast and
895 simple) and simply repack the file when we reach the end.
897 There are three problems with efficient fragmentation-avoiding
898 allocators: they are non-trivial, they tend to use a single free
899 list for each size, and there's no evidence that tdb allocation
900 patterns will match those recorded for general allocators (though
903 Thus we don't spend too much effort on external fragmentation; we
904 will be no worse than the current code if we need to repack on
905 occasion. More effort is spent on reducing freelist contention,
906 and reducing overhead.
908 3.7 <sub:Records-Incur-A>Records Incur A 28-Byte Overhead
910 Each TDB record has a header as follows:
914 tdb_off_t next; /* offset of the next record in the list
917 tdb_len_t rec_len; /* total byte length of record */
919 tdb_len_t key_len; /* byte length of key */
921 tdb_len_t data_len; /* byte length of data */
923 uint32_t full_hash; /* the full 32 bit hash of the key */
925 uint32_t magic; /* try to catch errors */
927 /* the following union is implied:
931 char record[rec_len];
941 uint32_t totalsize; (tailer)
949 Naively, this would double to a 56-byte overhead on a 64 bit
952 3.7.1 Proposed Solution
954 We can use various techniques to reduce this for an allocated
957 1. The 'next' pointer is not required, as we are using a flat
960 2. 'rec_len' can instead be expressed as an addition to key_len
961 and data_len (it accounts for wasted or overallocated length in
962 the record). Since the record length is always a multiple of 8,
963 we can conveniently fit it in 32 bits (representing up to 35
966 3. 'key_len' and 'data_len' can be reduced. I'm unwilling to
967 restrict 'data_len' to 32 bits, but instead we can combine the
968 two into one 64-bit field and using a 5 bit value which
969 indicates at what bit to divide the two. Keys are unlikely to
970 scale as fast as data, so I'm assuming a maximum key size of 32
973 4. 'full_hash' is used to avoid a memcmp on the “miss” case, but
974 this is diminishing returns after a handful of bits (at 10
975 bits, it reduces 99.9% of false memcmp). As an aside, as the
976 lower bits are already incorporated in the hash table
977 resolution, the upper bits should be used here. Note that it's
978 not clear that these bits will be a win, given the extra bits
979 in the hash table itself (see [sub:Hash-Size-Solution]).
981 5. 'magic' does not need to be enlarged: it currently reflects
982 one of 5 values (used, free, dead, recovery, and
983 unused_recovery). It is useful for quick sanity checking
984 however, and should not be eliminated.
986 6. 'tailer' is only used to coalesce free blocks (so a block to
987 the right can find the header to check if this block is free).
988 This can be replaced by a single 'free' bit in the header of
989 the following block (and the tailer only exists in free
991 This technique from Thomas Standish. Data Structure Techniques.
992 Addison-Wesley, Reading, Massachusetts, 1980.
993 ] The current proposed coalescing algorithm doesn't need this,
996 This produces a 16 byte used header like this:
998 struct tdb_used_record {
1000 uint32_t used_magic : 16,
1008 uint32_t extra_octets;
1010 uint64_t key_and_data_len;
1014 And a free record like this:
1016 struct tdb_free_record {
1018 uint64_t free_magic: 8,
1024 uint64_t free_table: 8,
1032 Note that by limiting valid offsets to 56 bits, we can pack
1033 everything we need into 3 64-byte words, meaning our minimum
1034 record size is 8 bytes.
1040 3.8 Transaction Commit Requires 4 fdatasync
1042 The current transaction algorithm is:
1044 1. write_recovery_data();
1048 3. write_recovery_header();
1052 5. overwrite_with_new_data();
1056 7. remove_recovery_header();
1060 On current ext3, each sync flushes all data to disk, so the next
1061 3 syncs are relatively expensive. But this could become a
1062 performance bottleneck on other filesystems such as ext4.
1064 3.8.1 Proposed Solution
1066 Neil Brown points out that this is overzealous, and only one sync
1069 1. Bundle the recovery data, a transaction counter and a strong
1070 checksum of the new data.
1072 2. Strong checksum that whole bundle.
1074 3. Store the bundle in the database.
1076 4. Overwrite the oldest of the two recovery pointers in the
1077 header (identified using the transaction counter) with the
1078 offset of this bundle.
1082 6. Write the new data to the file.
1084 Checking for recovery means identifying the latest bundle with a
1085 valid checksum and using the new data checksum to ensure that it
1086 has been applied. This is more expensive than the current check,
1087 but need only be done at open. For running databases, a separate
1088 header field can be used to indicate a transaction in progress;
1089 we need only check for recovery if this is set.
1095 3.9 <sub:TDB-Does-Not>TDB Does Not Have Snapshot Support
1097 3.9.1 Proposed SolutionNone. At some point you say “use a real
1098 database” (but see [replay-attribute]).
1100 But as a thought experiment, if we implemented transactions to
1101 only overwrite free entries (this is tricky: there must not be a
1102 header in each entry which indicates whether it is free, but use
1103 of presence in metadata elsewhere), and a pointer to the hash
1104 table, we could create an entirely new commit without destroying
1105 existing data. Then it would be easy to implement snapshots in a
1108 This would not allow arbitrary changes to the database, such as
1109 tdb_repack does, and would require more space (since we have to
1110 preserve the current and future entries at once). If we used hash
1111 trees rather than one big hash table, we might only have to
1112 rewrite some sections of the hash, too.
1114 We could then implement snapshots using a similar method, using
1115 multiple different hash tables/free tables.
1121 3.10 Transactions Cannot Operate in Parallel
1123 This would be useless for ldb, as it hits the index records with
1124 just about every update. It would add significant complexity in
1125 resolving clashes, and cause the all transaction callers to write
1126 their code to loop in the case where the transactions spuriously
1129 3.10.1 Proposed Solution
1131 None (but see [replay-attribute]). We could solve a small part of
1132 the problem by providing read-only transactions. These would
1133 allow one write transaction to begin, but it could not commit
1134 until all r/o transactions are done. This would require a new
1135 RO_TRANSACTION_LOCK, which would be upgraded on commit.
1141 3.11 Default Hash Function Is Suboptimal
1143 The Knuth-inspired multiplicative hash used by tdb is fairly slow
1144 (especially if we expand it to 64 bits), and works best when the
1145 hash bucket size is a prime number (which also means a slow
1146 modulus). In addition, it is highly predictable which could
1147 potentially lead to a Denial of Service attack in some TDB uses.
1149 3.11.1 Proposed Solution
1151 The Jenkins lookup3 hash[footnote:
1152 http://burtleburtle.net/bob/c/lookup3.c
1153 ] is a fast and superbly-mixing hash. It's used by the Linux
1154 kernel and almost everything else. This has the particular
1155 properties that it takes an initial seed, and produces two 32 bit
1156 hash numbers, which we can combine into a 64-bit hash.
1158 The seed should be created at tdb-creation time from some random
1159 source, and placed in the header. This is far from foolproof, but
1160 adds a little bit of protection against hash bombing.
1166 3.12 <Reliable-Traversal-Adds>Reliable Traversal Adds Complexity
1168 We lock a record during traversal iteration, and try to grab that
1169 lock in the delete code. If that grab on delete fails, we simply
1170 mark it deleted and continue onwards; traversal checks for this
1171 condition and does the delete when it moves off the record.
1173 If traversal terminates, the dead record may be left
1176 3.12.1 Proposed Solution
1178 Remove reliability guarantees; see [traverse-Proposed-Solution].
1184 3.13 Fcntl Locking Adds Overhead
1186 Placing a fcntl lock means a system call, as does removing one.
1187 This is actually one reason why transactions can be faster
1188 (everything is locked once at transaction start). In the
1189 uncontended case, this overhead can theoretically be eliminated.
1191 3.13.1 Proposed Solution
1195 We tried this before with spinlock support, in the early days of
1196 TDB, and it didn't make much difference except in manufactured
1199 We could use spinlocks (with futex kernel support under Linux),
1200 but it means that we lose automatic cleanup when a process dies
1201 with a lock. There is a method of auto-cleanup under Linux, but
1202 it's not supported by other operating systems. We could
1203 reintroduce a clear-if-first-style lock and sweep for dead
1204 futexes on open, but that wouldn't help the normal case of one
1205 concurrent opener dying. Increasingly elaborate repair schemes
1206 could be considered, but they require an ABI change (everyone
1207 must use them) anyway, so there's no need to do this at the same
1208 time as everything else.
1210 3.14 Some Transactions Don't Require Durability
1212 Volker points out that gencache uses a CLEAR_IF_FIRST tdb for
1213 normal (fast) usage, and occasionally empties the results into a
1214 transactional TDB. This kind of usage prioritizes performance
1215 over durability: as long as we are consistent, data can be lost.
1217 This would be more neatly implemented inside tdb: a “soft”
1218 transaction commit (ie. syncless) which meant that data may be
1219 reverted on a crash.
1221 3.14.1 Proposed Solution
1225 Unfortunately any transaction scheme which overwrites old data
1226 requires a sync before that overwrite to avoid the possibility of
1229 It seems possible to use a scheme similar to that described in [sub:TDB-Does-Not]
1230 ,where transactions are committed without overwriting existing
1231 data, and an array of top-level pointers were available in the
1232 header. If the transaction is “soft” then we would not need a
1233 sync at all: existing processes would pick up the new hash table
1234 and free list and work with that.
1236 At some later point, a sync would allow recovery of the old data
1237 into the free lists (perhaps when the array of top-level pointers
1238 filled). On crash, tdb_open() would examine the array of top
1239 levels, and apply the transactions until it encountered an
1242 3.15 Tracing Is Fragile, Replay Is External
1244 The current TDB has compile-time-enabled tracing code, but it
1245 often breaks as it is not enabled by default. In a similar way,
1246 the ctdb code has an external wrapper which does replay tracing
1247 so it can coordinate cluster-wide transactions.
1249 3.15.1 Proposed Solution<replay-attribute>
1251 Tridge points out that an attribute can be later added to
1252 tdb_open (see [attributes]) to provide replay/trace hooks, which
1253 could become the basis for this and future parallel transactions
1254 and snapshot support.