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.
132 2.2 tdb_traverse Makes Impossible Guarantees
134 tdb_traverse (and tdb_firstkey/tdb_nextkey) predate transactions,
135 and it was thought that it was important to guarantee that all
136 records which exist at the start and end of the traversal would
137 be included, and no record would be included twice.
139 This adds complexity (see[Reliable-Traversal-Adds]) and does not
140 work anyway for records which are altered (in particular, those
141 which are expanded may be effectively deleted and re-added behind
144 2.2.1 <traverse-Proposed-Solution>Proposed Solution
146 Abandon the guarantee. You will see every record if no changes
147 occur during your traversal, otherwise you will see some subset.
148 You can prevent changes by using a transaction or the locking
151 2.3 Nesting of Transactions Is Fraught
153 TDB has alternated between allowing nested transactions and not
154 allowing them. Various paths in the Samba codebase assume that
155 transactions will nest, and in a sense they can: the operation is
156 only committed to disk when the outer transaction is committed.
157 There are two problems, however:
159 1. Canceling the inner transaction will cause the outer
160 transaction commit to fail, and will not undo any operations
161 since the inner transaction began. This problem is soluble with
162 some additional internal code.
164 2. An inner transaction commit can be cancelled by the outer
165 transaction. This is desirable in the way which Samba's
166 database initialization code uses transactions, but could be a
167 surprise to any users expecting a successful transaction commit
168 to expose changes to others.
170 The current solution is to specify the behavior at tdb_open(),
171 with the default currently that nested transactions are allowed.
172 This flag can also be changed at runtime.
174 2.3.1 Proposed Solution
176 Given the usage patterns, it seems that the “least-surprise”
177 behavior of disallowing nested transactions should become the
178 default. Additionally, it seems the outer transaction is the only
179 code which knows whether inner transactions should be allowed, so
180 a flag to indicate this could be added to tdb_transaction_start.
181 However, this behavior can be simulated with a wrapper which uses
182 tdb_add_flags() and tdb_remove_flags(), so the API should not be
183 expanded for this relatively-obscure case.
185 2.4 Incorrect Hash Function is Not Detected
187 tdb_open_ex() allows the calling code to specify a different hash
188 function to use, but does not check that all other processes
189 accessing this tdb are using the same hash function. The result
190 is that records are missing from tdb_fetch().
192 2.4.1 Proposed Solution
194 The header should contain an example hash result (eg. the hash of
195 0xdeadbeef), and tdb_open_ex() should check that the given hash
196 function produces the same answer, or fail the tdb_open call.
198 2.5 tdb_set_max_dead/TDB_VOLATILE Expose Implementation
200 In response to scalability issues with the free list ([TDB-Freelist-Is]
201 ) two API workarounds have been incorporated in TDB:
202 tdb_set_max_dead() and the TDB_VOLATILE flag to tdb_open. The
203 latter actually calls the former with an argument of “5”.
205 This code allows deleted records to accumulate without putting
206 them in the free list. On delete we iterate through each chain
207 and free them in a batch if there are more than max_dead entries.
208 These are never otherwise recycled except as a side-effect of a
211 2.5.1 Proposed Solution
213 With the scalability problems of the freelist solved, this API
214 can be removed. The TDB_VOLATILE flag may still be useful as a
215 hint that store and delete of records will be at least as common
216 as fetch in order to allow some internal tuning, but initially
219 2.6 <TDB-Files-Cannot>TDB Files Cannot Be Opened Multiple Times
222 No process can open the same TDB twice; we check and disallow it.
223 This is an unfortunate side-effect of fcntl locks, which operate
224 on a per-file rather than per-file-descriptor basis, and do not
225 nest. Thus, closing any file descriptor on a file clears all the
226 locks obtained by this process, even if they were placed using a
227 different file descriptor!
229 Note that even if this were solved, deadlock could occur if
230 operations were nested: this is a more manageable programming
233 2.6.1 Proposed Solution
235 We could lobby POSIX to fix the perverse rules, or at least lobby
236 Linux to violate them so that the most common implementation does
237 not have this restriction. This would be a generally good idea
238 for other fcntl lock users.
240 Samba uses a wrapper which hands out the same tdb_context to
241 multiple callers if this happens, and does simple reference
242 counting. We should do this inside the tdb library, which already
243 emulates lock nesting internally; it would need to recognize when
244 deadlock occurs within a single process. This would create a new
245 failure mode for tdb operations (while we currently handle
246 locking failures, they are impossible in normal use and a process
247 encountering them can do little but give up).
249 I do not see benefit in an additional tdb_open flag to indicate
250 whether re-opening is allowed, as though there may be some
251 benefit to adding a call to detect when a tdb_context is shared,
252 to allow other to create such an API.
254 2.7 TDB API Is Not POSIX Thread-safe
256 The TDB API uses an error code which can be queried after an
257 operation to determine what went wrong. This programming model
258 does not work with threads, unless specific additional guarantees
259 are given by the implementation. In addition, even
260 otherwise-independent threads cannot open the same TDB (as in [TDB-Files-Cannot]
263 2.7.1 Proposed Solution
265 Reachitecting the API to include a tdb_errcode pointer would be a
266 great deal of churn; we are better to guarantee that the
267 tdb_errcode is per-thread so the current programming model can be
270 This requires dynamic per-thread allocations, which is awkward
271 with POSIX threads (pthread_key_create space is limited and we
272 cannot simply allocate a key for every TDB).
274 Internal locking is required to make sure that fcntl locks do not
275 overlap between threads, and also that the global list of tdbs is
278 The aim is that building tdb with -DTDB_PTHREAD will result in a
279 pthread-safe version of the library, and otherwise no overhead
280 will exist. Alternatively, a hooking mechanism similar to that
281 proposed for [Proposed-Solution-locking-hook] could be used to
282 enable pthread locking at runtime.
284 2.8 *_nonblock Functions And *_mark Functions Expose
288 Clustered TDB, see http://ctdb.samba.org
289 ] wishes to operate on TDB in a non-blocking manner. This is
290 currently done as follows:
292 1. Call the _nonblock variant of an API function (eg.
293 tdb_lockall_nonblock). If this fails:
295 2. Fork a child process, and wait for it to call the normal
296 variant (eg. tdb_lockall).
298 3. If the child succeeds, call the _mark variant to indicate we
299 already have the locks (eg. tdb_lockall_mark).
301 4. Upon completion, tell the child to release the locks (eg.
304 5. Indicate to tdb that it should consider the locks removed (eg.
307 There are several issues with this approach. Firstly, adding two
308 new variants of each function clutters the API for an obscure
309 use, and so not all functions have three variants. Secondly, it
310 assumes that all paths of the functions ask for the same locks,
311 otherwise the parent process will have to get a lock which the
312 child doesn't have under some circumstances. I don't believe this
313 is currently the case, but it constrains the implementation.
315 2.8.1 <Proposed-Solution-locking-hook>Proposed Solution
317 Implement a hook for locking methods, so that the caller can
318 control the calls to create and remove fcntl locks. In this
319 scenario, ctdbd would operate as follows:
321 1. Call the normal API function, eg tdb_lockall().
323 2. When the lock callback comes in, check if the child has the
324 lock. Initially, this is always false. If so, return 0.
325 Otherwise, try to obtain it in non-blocking mode. If that
326 fails, return EWOULDBLOCK.
328 3. Release locks in the unlock callback as normal.
330 4. If tdb_lockall() fails, see if we recorded a lock failure; if
331 so, call the child to repeat the operation.
333 5. The child records what locks it obtains, and returns that
334 information to the parent.
336 6. When the child has succeeded, goto 1.
338 This is flexible enough to handle any potential locking scenario,
339 even when lock requirements change. It can be optimized so that
340 the parent does not release locks, just tells the child which
341 locks it doesn't need to obtain.
343 It also keeps the complexity out of the API, and in ctdbd where
346 2.9 tdb_chainlock Functions Expose Implementation
348 tdb_chainlock locks some number of records, including the record
349 indicated by the given key. This gave atomicity guarantees;
350 no-one can start a transaction, alter, read or delete that key
351 while the lock is held.
353 It also makes the same guarantee for any other key in the chain,
354 which is an internal implementation detail and potentially a
357 2.9.1 Proposed Solution
359 None. It would be nice to have an explicit single entry lock
360 which effected no other keys. Unfortunately, this won't work for
361 an entry which doesn't exist. Thus while chainlock may be
362 implemented more efficiently for the existing case, it will still
363 have overlap issues with the non-existing case. So it is best to
364 keep the current (lack of) guarantee about which records will be
365 effected to avoid constraining our implementation.
367 2.10 Signal Handling is Not Race-Free
369 The tdb_setalarm_sigptr() call allows the caller's signal handler
370 to indicate that the tdb locking code should return with a
371 failure, rather than trying again when a signal is received (and
372 errno == EAGAIN). This is usually used to implement timeouts.
374 Unfortunately, this does not work in the case where the signal is
375 received before the tdb code enters the fcntl() call to place the
376 lock: the code will sleep within the fcntl() code, unaware that
377 the signal wants it to exit. In the case of long timeouts, this
378 does not happen in practice.
380 2.10.1 Proposed Solution
382 The locking hooks proposed in[Proposed-Solution-locking-hook]
383 would allow the user to decide on whether to fail the lock
384 acquisition on a signal. This allows the caller to choose their
385 own compromise: they could narrow the race by checking
386 immediately before the fcntl call.[footnote:
387 It may be possible to make this race-free in some implementations
388 by having the signal handler alter the struct flock to make it
389 invalid. This will cause the fcntl() lock call to fail with
390 EINVAL if the signal occurs before the kernel is entered,
394 2.11 The API Uses Gratuitous Typedefs, Capitals
396 typedefs are useful for providing source compatibility when types
397 can differ across implementations, or arguably in the case of
398 function pointer definitions which are hard for humans to parse.
399 Otherwise it is simply obfuscation and pollutes the namespace.
401 Capitalization is usually reserved for compile-time constants and
404 TDB_CONTEXT There is no reason to use this over 'struct
405 tdb_context'; the definition isn't visible to the API user
408 TDB_DATA There is no reason to use this over struct TDB_DATA;
409 the struct needs to be understood by the API user.
411 struct TDB_DATA This would normally be called 'struct
414 enum TDB_ERROR Similarly, this would normally be enum
417 2.11.1 Proposed Solution
419 None. Introducing lower case variants would please pedants like
420 myself, but if it were done the existing ones should be kept.
421 There is little point forcing a purely cosmetic change upon tdb
424 2.12 <tdb_log_func-Doesnt-Take>tdb_log_func Doesn't Take The
427 For API compatibility reasons, the logging function needs to call
428 tdb_get_logging_private() to retrieve the pointer registered by
429 the tdb_open_ex for logging.
431 2.12.1 Proposed Solution
433 It should simply take an extra argument, since we are prepared to
436 2.13 Various Callback Functions Are Not Typesafe
438 The callback functions in tdb_set_logging_function (after [tdb_log_func-Doesnt-Take]
439 is resolved), tdb_parse_record, tdb_traverse, tdb_traverse_read
440 and tdb_check all take void * and must internally convert it to
441 the argument type they were expecting.
443 If this type changes, the compiler will not produce warnings on
444 the callers, since it only sees void *.
446 2.13.1 Proposed Solution
448 With careful use of macros, we can create callback functions
449 which give a warning when used on gcc and the types of the
450 callback and its private argument differ. Unsupported compilers
451 will not give a warning, which is no worse than now. In addition,
452 the callbacks become clearer, as they need not use void * for
455 See CCAN's typesafe_cb module at
456 http://ccan.ozlabs.org/info/typesafe_cb.html
458 2.14 TDB_CLEAR_IF_FIRST Must Be Specified On All Opens,
459 tdb_reopen_all Problematic
461 The TDB_CLEAR_IF_FIRST flag to tdb_open indicates that the TDB
462 file should be cleared if the caller discovers it is the only
463 process with the TDB open. However, if any caller does not
464 specify TDB_CLEAR_IF_FIRST it will not be detected, so will have
465 the TDB erased underneath them (usually resulting in a crash).
467 There is a similar issue on fork(); if the parent exits (or
468 otherwise closes the tdb) before the child calls tdb_reopen_all()
469 to establish the lock used to indicate the TDB is opened by
470 someone, a TDB_CLEAR_IF_FIRST opener at that moment will believe
471 it alone has opened the TDB and will erase it.
473 2.14.1 Proposed Solution
475 Remove TDB_CLEAR_IF_FIRST. Other workarounds are possible, but
476 see [TDB_CLEAR_IF_FIRST-Imposes-Performance].
478 2.15 Extending The Header Is Difficult
480 We have reserved (zeroed) words in the TDB header, which can be
481 used for future features. If the future features are compulsory,
482 the version number must be updated to prevent old code from
483 accessing the database. But if the future feature is optional, we
484 have no way of telling if older code is accessing the database or
487 2.15.1 Proposed Solution
489 The header should contain a “format variant” value (64-bit). This
490 is divided into two 32-bit parts:
492 1. The lower part reflects the format variant understood by code
493 accessing the database.
495 2. The upper part reflects the format variant you must understand
496 to write to the database (otherwise you can only open for
499 The latter field can only be written at creation time, the former
500 should be written under the OPEN_LOCK when opening the database
501 for writing, if the variant of the code is lower than the current
504 This should allow backwards-compatible features to be added, and
505 detection if older code (which doesn't understand the feature)
506 writes to the database.
508 2.16 Record Headers Are Not Expandible
510 If we later want to add (say) checksums on keys and data, it
511 would require another format change, which we'd like to avoid.
513 2.16.1 Proposed Solution
515 We often have extra padding at the tail of a record. If we ensure
516 that the first byte (if any) of this padding is zero, we will
517 have a way for future changes to detect code which doesn't
518 understand a new format: the new code would write (say) a 1 at
519 the tail, and thus if there is no tail or the first byte is 0, we
520 would know the extension is not present on that record.
522 2.17 TDB Does Not Use Talloc
524 Many users of TDB (particularly Samba) use the talloc allocator,
525 and thus have to wrap TDB in a talloc context to use it
528 2.17.1 Proposed Solution
530 The allocation within TDB is not complicated enough to justify
531 the use of talloc, and I am reluctant to force another
532 (excellent) library on TDB users. Nonetheless a compromise is
533 possible. An attribute (see [attributes]) can be added later to
534 tdb_open() to provide an alternate allocation mechanism,
535 specifically for talloc but usable by any other allocator (which
536 would ignore the “context” argument).
538 This would form a talloc heirarchy as expected, but the caller
539 would still have to attach a destructor to the tdb context
540 returned from tdb_open to close it. All TDB_DATA fields would be
541 children of the tdb_context, and the caller would still have to
542 manage them (using talloc_free() or talloc_steal()).
544 3 Performance And Scalability Issues
546 3.1 <TDB_CLEAR_IF_FIRST-Imposes-Performance>TDB_CLEAR_IF_FIRST
547 Imposes Performance Penalty
549 When TDB_CLEAR_IF_FIRST is specified, a 1-byte read lock is
550 placed at offset 4 (aka. the ACTIVE_LOCK). While these locks
551 never conflict in normal tdb usage, they do add substantial
552 overhead for most fcntl lock implementations when the kernel
553 scans to detect if a lock conflict exists. This is often a single
554 linked list, making the time to acquire and release a fcntl lock
555 O(N) where N is the number of processes with the TDB open, not
556 the number actually doing work.
558 In a Samba server it is common to have huge numbers of clients
559 sitting idle, and thus they have weaned themselves off the
560 TDB_CLEAR_IF_FIRST flag.[footnote:
561 There is a flag to tdb_reopen_all() which is used for this
562 optimization: if the parent process will outlive the child, the
563 child does not need the ACTIVE_LOCK. This is a workaround for
564 this very performance issue.
567 3.1.1 Proposed Solution
569 Remove the flag. It was a neat idea, but even trivial servers
570 tend to know when they are initializing for the first time and
571 can simply unlink the old tdb at that point.
573 3.2 TDB Files Have a 4G Limit
575 This seems to be becoming an issue (so much for “trivial”!),
576 particularly for ldb.
578 3.2.1 Proposed Solution
580 A new, incompatible TDB format which uses 64 bit offsets
581 internally rather than 32 bit as now. For simplicity of endian
582 conversion (which TDB does on the fly if required), all values
583 will be 64 bit on disk. In practice, some upper bits may be used
584 for other purposes, but at least 56 bits will be available for
587 tdb_open() will automatically detect the old version, and even
588 create them if TDB_VERSION6 is specified to tdb_open.
590 32 bit processes will still be able to access TDBs larger than 4G
591 (assuming that their off_t allows them to seek to 64 bits), they
592 will gracefully fall back as they fail to mmap. This can happen
593 already with large TDBs.
595 Old versions of tdb will fail to open the new TDB files (since 28
596 August 2009, commit 398d0c29290: prior to that any unrecognized
597 file format would be erased and initialized as a fresh tdb!)
599 3.3 TDB Records Have a 4G Limit
601 This has not been a reported problem, and the API uses size_t
602 which can be 64 bit on 64 bit platforms. However, other limits
603 may have made such an issue moot.
605 3.3.1 Proposed Solution
607 Record sizes will be 64 bit, with an error returned on 32 bit
608 platforms which try to access such records (the current
609 implementation would return TDB_ERR_OOM in a similar case). It
610 seems unlikely that 32 bit keys will be a limitation, so the
611 implementation may not support this (see [sub:Records-Incur-A]).
613 3.4 Hash Size Is Determined At TDB Creation Time
615 TDB contains a number of hash chains in the header; the number is
616 specified at creation time, and defaults to 131. This is such a
617 bottleneck on large databases (as each hash chain gets quite
618 long), that LDB uses 10,000 for this hash. In general it is
619 impossible to know what the 'right' answer is at database
622 3.4.1 <sub:Hash-Size-Solution>Proposed Solution
624 After comprehensive performance testing on various scalable hash
626 http://rusty.ozlabs.org/?p=89 and http://rusty.ozlabs.org/?p=94
627 This was annoying because I was previously convinced that an
628 expanding tree of hashes would be very close to optimal.
629 ], it became clear that it is hard to beat a straight linear hash
630 table which doubles in size when it reaches saturation.
642 Unfortunately, altering the hash table introduces serious
643 locking complications: the entire hash table needs to be locked
644 to enlarge the hash table, and others might be holding locks.
645 Particularly insidious are insertions done under tdb_chainlock.
647 Thus an expanding layered hash will be used: an array of hash
648 groups, with each hash group exploding into pointers to lower
649 hash groups once it fills, turning into a hash tree. This has
650 implications for locking: we must lock the entire group in case
651 we need to expand it, yet we don't know how deep the tree is at
654 Note that bits from the hash table entries should be stolen to
655 hold more hash bits to reduce the penalty of collisions. We can
656 use the otherwise-unused lower 3 bits. If we limit the size of
657 the database to 64 exabytes, we can use the top 8 bits of the
658 hash entry as well. These 11 bits would reduce false positives
659 down to 1 in 2000 which is more than we need: we can use one of
660 the bits to indicate that the extra hash bits are valid. This
661 means we can choose not to re-hash all entries when we expand a
662 hash group; simply use the next bits we need and mark them
665 3.5 <TDB-Freelist-Is>TDB Freelist Is Highly Contended
667 TDB uses a single linked list for the free list. Allocation
668 occurs as follows, using heuristics which have evolved over time:
670 1. Get the free list lock for this whole operation.
672 2. Multiply length by 1.25, so we always over-allocate by 25%.
674 3. Set the slack multiplier to 1.
676 4. Examine the current freelist entry: if it is > length but <
677 the current best case, remember it as the best case.
679 5. Multiply the slack multiplier by 1.05.
681 6. If our best fit so far is less than length * slack multiplier,
682 return it. The slack will be turned into a new free record if
685 7. Otherwise, go onto the next freelist entry.
687 Deleting a record occurs as follows:
689 1. Lock the hash chain for this whole operation.
691 2. Walk the chain to find the record, keeping the prev pointer
694 3. If max_dead is non-zero:
696 (a) Walk the hash chain again and count the dead records.
698 (b) If it's more than max_dead, bulk free all the dead ones
699 (similar to steps 4 and below, but the lock is only obtained
702 (c) Simply mark this record as dead and return.
704 4. Get the free list lock for the remainder of this operation.
706 5. <right-merging>Examine the following block to see if it is
707 free; if so, enlarge the current block and remove that block
708 from the free list. This was disabled, as removal from the free
709 list was O(entries-in-free-list).
711 6. Examine the preceeding block to see if it is free: for this
712 reason, each block has a 32-bit tailer which indicates its
713 length. If it is free, expand it to cover our new block and
716 7. Otherwise, prepend ourselves to the free list.
718 Disabling right-merging (step [right-merging]) causes
719 fragmentation; the other heuristics proved insufficient to
720 address this, so the final answer to this was that when we expand
721 the TDB file inside a transaction commit, we repack the entire
724 The single list lock limits our allocation rate; due to the other
725 issues this is not currently seen as a bottleneck.
727 3.5.1 Proposed Solution
729 The first step is to remove all the current heuristics, as they
730 obviously interact, then examine them once the lock contention is
733 The free list must be split to reduce contention. Assuming
734 perfect free merging, we can at most have 1 free list entry for
735 each entry. This implies that the number of free lists is related
736 to the size of the hash table, but as it is rare to walk a large
737 number of free list entries we can use far fewer, say 1/32 of the
738 number of hash buckets.
740 It seems tempting to try to reuse the hash implementation which
741 we use for records here, but we have two ways of searching for
742 free entries: for allocation we search by size (and possibly
743 zone) which produces too many clashes for our hash table to
744 handle well, and for coalescing we search by address. Thus an
745 array of doubly-linked free lists seems preferable.
747 There are various benefits in using per-size free lists (see [sub:TDB-Becomes-Fragmented]
748 ) but it's not clear this would reduce contention in the common
749 case where all processes are allocating/freeing the same size.
750 Thus we almost certainly need to divide in other ways: the most
751 obvious is to divide the file into zones, and using a free list
752 (or set of free lists) for each. This approximates address
755 Note that this means we need to split the free lists when we
756 expand the file; this is probably acceptable when we double the
757 hash table size, since that is such an expensive operation
758 already. In the case of increasing the file size, there is an
759 optimization we can use: if we use M in the formula above as the
760 file size rounded up to the next power of 2, we only need
761 reshuffle free lists when the file size crosses a power of 2
762 boundary, and reshuffling the free lists is trivial: we simply
763 merge every consecutive pair of free lists.
765 The basic algorithm is as follows. Freeing is simple:
767 1. Identify the correct zone.
769 2. Lock the corresponding list.
771 3. Re-check the zone (we didn't have a lock, sizes could have
772 changed): relock if necessary.
774 4. Place the freed entry in the list for that zone.
776 Allocation is a little more complicated, as we perform delayed
777 coalescing at this point:
779 1. Pick a zone either the zone we last freed into, or based on a “
782 2. Lock the corresponding list.
784 3. Re-check the zone: relock if necessary.
786 4. If the top entry is -large enough, remove it from the list and
789 5. Otherwise, coalesce entries in the list.If there was no entry
790 large enough, unlock the list and try the next zone.
792 6. If no zone satisfies, expand the file.
794 This optimizes rapid insert/delete of free list entries by not
795 coalescing them all the time.. First-fit address ordering
796 ordering seems to be fairly good for keeping fragmentation low
797 (see [sub:TDB-Becomes-Fragmented]). Note that address ordering
798 does not need a tailer to coalesce, though if we needed one we
799 could have one cheaply: see [sub:Records-Incur-A].
801 I anticipate that the number of entries in each free zone would
802 be small, but it might be worth using one free entry to hold
803 pointers to the others for cache efficiency.
805 <freelist-in-zone>If we want to avoid locking complexity
806 (enlarging the free lists when we enlarge the file) we could
807 place the array of free lists at the beginning of each zone. This
808 means existing array lists never move, but means that a record
809 cannot be larger than a zone. That in turn implies that zones
810 should be variable sized (say, power of 2), which makes the
811 question “what zone is this record in?” much harder (and “pick a
812 random zone”, but that's less common). It could be done with as
813 few as 4 bits from the record header.[footnote:
814 Using 2^{16+N*3}means 0 gives a minimal 65536-byte zone, 15 gives
815 the maximal 2^{61} byte zone. Zones range in factor of 8 steps.
816 Given the zone size for the zone the current record is in, we can
817 determine the start of the zone.
820 3.6 <sub:TDB-Becomes-Fragmented>TDB Becomes Fragmented
822 Much of this is a result of allocation strategy[footnote:
823 The Memory Fragmentation Problem: Solved? Johnstone & Wilson 1995
824 ftp://ftp.cs.utexas.edu/pub/garbage/malloc/ismm98.ps
825 ] and deliberate hobbling of coalescing; internal fragmentation
826 (aka overallocation) is deliberately set at 25%, and external
827 fragmentation is only cured by the decision to repack the entire
828 db when a transaction commit needs to enlarge the file.
830 3.6.1 Proposed Solution
832 The 25% overhead on allocation works in practice for ldb because
833 indexes tend to expand by one record at a time. This internal
834 fragmentation can be resolved by having an “expanded” bit in the
835 header to note entries that have previously expanded, and
836 allocating more space for them.
838 There are is a spectrum of possible solutions for external
839 fragmentation: one is to use a fragmentation-avoiding allocation
840 strategy such as best-fit address-order allocator. The other end
841 of the spectrum would be to use a bump allocator (very fast and
842 simple) and simply repack the file when we reach the end.
844 There are three problems with efficient fragmentation-avoiding
845 allocators: they are non-trivial, they tend to use a single free
846 list for each size, and there's no evidence that tdb allocation
847 patterns will match those recorded for general allocators (though
850 Thus we don't spend too much effort on external fragmentation; we
851 will be no worse than the current code if we need to repack on
852 occasion. More effort is spent on reducing freelist contention,
853 and reducing overhead.
855 3.7 <sub:Records-Incur-A>Records Incur A 28-Byte Overhead
857 Each TDB record has a header as follows:
861 tdb_off_t next; /* offset of the next record in the list
864 tdb_len_t rec_len; /* total byte length of record */
866 tdb_len_t key_len; /* byte length of key */
868 tdb_len_t data_len; /* byte length of data */
870 uint32_t full_hash; /* the full 32 bit hash of the key */
872 uint32_t magic; /* try to catch errors */
874 /* the following union is implied:
878 char record[rec_len];
888 uint32_t totalsize; (tailer)
896 Naively, this would double to a 56-byte overhead on a 64 bit
899 3.7.1 Proposed Solution
901 We can use various techniques to reduce this for an allocated
904 1. The 'next' pointer is not required, as we are using a flat
907 2. 'rec_len' can instead be expressed as an addition to key_len
908 and data_len (it accounts for wasted or overallocated length in
909 the record). Since the record length is always a multiple of 8,
910 we can conveniently fit it in 32 bits (representing up to 35
913 3. 'key_len' and 'data_len' can be reduced. I'm unwilling to
914 restrict 'data_len' to 32 bits, but instead we can combine the
915 two into one 64-bit field and using a 5 bit value which
916 indicates at what bit to divide the two. Keys are unlikely to
917 scale as fast as data, so I'm assuming a maximum key size of 32
920 4. 'full_hash' is used to avoid a memcmp on the “miss” case, but
921 this is diminishing returns after a handful of bits (at 10
922 bits, it reduces 99.9% of false memcmp). As an aside, as the
923 lower bits are already incorporated in the hash table
924 resolution, the upper bits should be used here. Note that it's
925 not clear that these bits will be a win, given the extra bits
926 in the hash table itself (see [sub:Hash-Size-Solution]).
928 5. 'magic' does not need to be enlarged: it currently reflects
929 one of 5 values (used, free, dead, recovery, and
930 unused_recovery). It is useful for quick sanity checking
931 however, and should not be eliminated.
933 6. 'tailer' is only used to coalesce free blocks (so a block to
934 the right can find the header to check if this block is free).
935 This can be replaced by a single 'free' bit in the header of
936 the following block (and the tailer only exists in free
938 This technique from Thomas Standish. Data Structure Techniques.
939 Addison-Wesley, Reading, Massachusetts, 1980.
940 ] The current proposed coalescing algorithm doesn't need this,
943 This produces a 16 byte used header like this:
945 struct tdb_used_record {
955 uint32_t extra_octets;
957 uint64_t key_and_data_len;
961 And a free record like this:
963 struct tdb_free_record {
967 uint64_t total_length;
977 We might want to take some bits from the used record's top_hash
978 (and the free record which has 32 bits of padding to spare
979 anyway) if we use variable sized zones. See [freelist-in-zone].
981 3.8 Transaction Commit Requires 4 fdatasync
983 The current transaction algorithm is:
985 1. write_recovery_data();
989 3. write_recovery_header();
993 5. overwrite_with_new_data();
997 7. remove_recovery_header();
1001 On current ext3, each sync flushes all data to disk, so the next
1002 3 syncs are relatively expensive. But this could become a
1003 performance bottleneck on other filesystems such as ext4.
1005 3.8.1 Proposed Solution
1007 Neil Brown points out that this is overzealous, and only one sync
1010 1. Bundle the recovery data, a transaction counter and a strong
1011 checksum of the new data.
1013 2. Strong checksum that whole bundle.
1015 3. Store the bundle in the database.
1017 4. Overwrite the oldest of the two recovery pointers in the
1018 header (identified using the transaction counter) with the
1019 offset of this bundle.
1023 6. Write the new data to the file.
1025 Checking for recovery means identifying the latest bundle with a
1026 valid checksum and using the new data checksum to ensure that it
1027 has been applied. This is more expensive than the current check,
1028 but need only be done at open. For running databases, a separate
1029 header field can be used to indicate a transaction in progress;
1030 we need only check for recovery if this is set.
1032 3.9 <sub:TDB-Does-Not>TDB Does Not Have Snapshot Support
1034 3.9.1 Proposed Solution
1036 None. At some point you say “use a real database” (but see [replay-attribute]
1039 But as a thought experiment, if we implemented transactions to
1040 only overwrite free entries (this is tricky: there must not be a
1041 header in each entry which indicates whether it is free, but use
1042 of presence in metadata elsewhere), and a pointer to the hash
1043 table, we could create an entirely new commit without destroying
1044 existing data. Then it would be easy to implement snapshots in a
1047 This would not allow arbitrary changes to the database, such as
1048 tdb_repack does, and would require more space (since we have to
1049 preserve the current and future entries at once). If we used hash
1050 trees rather than one big hash table, we might only have to
1051 rewrite some sections of the hash, too.
1053 We could then implement snapshots using a similar method, using
1054 multiple different hash tables/free tables.
1056 3.10 Transactions Cannot Operate in Parallel
1058 This would be useless for ldb, as it hits the index records with
1059 just about every update. It would add significant complexity in
1060 resolving clashes, and cause the all transaction callers to write
1061 their code to loop in the case where the transactions spuriously
1064 3.10.1 Proposed Solution
1066 None (but see [replay-attribute]). We could solve a small part of
1067 the problem by providing read-only transactions. These would
1068 allow one write transaction to begin, but it could not commit
1069 until all r/o transactions are done. This would require a new
1070 RO_TRANSACTION_LOCK, which would be upgraded on commit.
1072 3.11 Default Hash Function Is Suboptimal
1074 The Knuth-inspired multiplicative hash used by tdb is fairly slow
1075 (especially if we expand it to 64 bits), and works best when the
1076 hash bucket size is a prime number (which also means a slow
1077 modulus). In addition, it is highly predictable which could
1078 potentially lead to a Denial of Service attack in some TDB uses.
1080 3.11.1 Proposed Solution
1082 The Jenkins lookup3 hash[footnote:
1083 http://burtleburtle.net/bob/c/lookup3.c
1084 ] is a fast and superbly-mixing hash. It's used by the Linux
1085 kernel and almost everything else. This has the particular
1086 properties that it takes an initial seed, and produces two 32 bit
1087 hash numbers, which we can combine into a 64-bit hash.
1089 The seed should be created at tdb-creation time from some random
1090 source, and placed in the header. This is far from foolproof, but
1091 adds a little bit of protection against hash bombing.
1093 3.12 <Reliable-Traversal-Adds>Reliable Traversal Adds Complexity
1095 We lock a record during traversal iteration, and try to grab that
1096 lock in the delete code. If that grab on delete fails, we simply
1097 mark it deleted and continue onwards; traversal checks for this
1098 condition and does the delete when it moves off the record.
1100 If traversal terminates, the dead record may be left
1103 3.12.1 Proposed Solution
1105 Remove reliability guarantees; see [traverse-Proposed-Solution].
1107 3.13 Fcntl Locking Adds Overhead
1109 Placing a fcntl lock means a system call, as does removing one.
1110 This is actually one reason why transactions can be faster
1111 (everything is locked once at transaction start). In the
1112 uncontended case, this overhead can theoretically be eliminated.
1114 3.13.1 Proposed Solution
1118 We tried this before with spinlock support, in the early days of
1119 TDB, and it didn't make much difference except in manufactured
1122 We could use spinlocks (with futex kernel support under Linux),
1123 but it means that we lose automatic cleanup when a process dies
1124 with a lock. There is a method of auto-cleanup under Linux, but
1125 it's not supported by other operating systems. We could
1126 reintroduce a clear-if-first-style lock and sweep for dead
1127 futexes on open, but that wouldn't help the normal case of one
1128 concurrent opener dying. Increasingly elaborate repair schemes
1129 could be considered, but they require an ABI change (everyone
1130 must use them) anyway, so there's no need to do this at the same
1131 time as everything else.
1133 3.14 Some Transactions Don't Require Durability
1135 Volker points out that gencache uses a CLEAR_IF_FIRST tdb for
1136 normal (fast) usage, and occasionally empties the results into a
1137 transactional TDB. This kind of usage prioritizes performance
1138 over durability: as long as we are consistent, data can be lost.
1140 This would be more neatly implemented inside tdb: a “soft”
1141 transaction commit (ie. syncless) which meant that data may be
1142 reverted on a crash.
1144 3.14.1 Proposed Solution
1148 Unfortunately any transaction scheme which overwrites old data
1149 requires a sync before that overwrite to avoid the possibility of
1152 It seems possible to use a scheme similar to that described in [sub:TDB-Does-Not]
1153 ,where transactions are committed without overwriting existing
1154 data, and an array of top-level pointers were available in the
1155 header. If the transaction is “soft” then we would not need a
1156 sync at all: existing processes would pick up the new hash table
1157 and free list and work with that.
1159 At some later point, a sync would allow recovery of the old data
1160 into the free lists (perhaps when the array of top-level pointers
1161 filled). On crash, tdb_open() would examine the array of top
1162 levels, and apply the transactions until it encountered an
1165 3.15 Tracing Is Fragile, Replay Is External
1167 The current TDB has compile-time-enabled tracing code, but it
1168 often breaks as it is not enabled by default. In a similar way,
1169 the ctdb code has an external wrapper which does replay tracing
1170 so it can coordinate cluster-wide transactions.
1172 3.15.1 Proposed Solution<replay-attribute>
1174 Tridge points out that an attribute can be later added to
1175 tdb_open (see [attributes]) to provide replay/trace hooks, which
1176 could become the basis for this and future parallel transactions
1177 and snapshot support.