wafsamba: use additional xml catalog file (bug #9512)
[Samba/gebeck_regimport.git] / lib / ntdb / doc / design.txt
blobbd680f09eeff1bf60be4763768d372bd9e1e458e
1 NTDB: Redesigning The Trivial DataBase
3 Rusty Russell, IBM Corporation
5 19 June 2012
7 Abstract
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.
14 1 Introduction
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 +-----------+----------------+--------------------------------+
38 |   1999    |      13        |              1195              |
39 +-----------+----------------+--------------------------------+
40 |   2000    |      24        |              1725              |
41 +-----------+----------------+--------------------------------+
42 |   2001    |      32        |              2228              |
43 +-----------+----------------+--------------------------------+
44 |   2002    |      35        |              2481              |
45 +-----------+----------------+--------------------------------+
46 |   2003    |      35        |              2552              |
47 +-----------+----------------+--------------------------------+
48 |   2004    |      40        |              2584              |
49 +-----------+----------------+--------------------------------+
50 |   2005    |      38        |              2647              |
51 +-----------+----------------+--------------------------------+
52 |   2006    |      52        |              3754              |
53 +-----------+----------------+--------------------------------+
54 |   2007    |      66        |              4398              |
55 +-----------+----------------+--------------------------------+
56 |   2008    |      71        |              4768              |
57 +-----------+----------------+--------------------------------+
58 |   2009    |      73        |              5715              |
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.
68 Note: the final decision was to make ntdb a separate library,
69 with a separarate 'ntdb' namespace so both can potentially be
70 linked together. This document still refers to “tdb” everywhere,
71 for simplicity.
73 2 API Issues
75 2.1 tdb_open_ex Is Not Expandable
77 The tdb_open() call was expanded to tdb_open_ex(), which added an
78 optional hashing function and an optional logging function
79 argument. Additional arguments to open would require the
80 introduction of a tdb_open_ex2 call etc.
82 2.1.1 Proposed Solution<attributes>
84 tdb_open() will take a linked-list of attributes:
86 enum tdb_attribute {
88     TDB_ATTRIBUTE_LOG = 0,
90     TDB_ATTRIBUTE_HASH = 1
94 struct tdb_attribute_base {
96     enum tdb_attribute attr;
98     union tdb_attribute *next;
102 struct tdb_attribute_log {
104     struct tdb_attribute_base base; /* .attr = TDB_ATTRIBUTE_LOG
107     tdb_log_func log_fn;
109     void *log_private;
113 struct tdb_attribute_hash {
115     struct tdb_attribute_base base; /* .attr = TDB_ATTRIBUTE_HASH
118     tdb_hash_func hash_fn;
120     void *hash_private;
124 union tdb_attribute {
126     struct tdb_attribute_base base;
128     struct tdb_attribute_log log;
130     struct tdb_attribute_hash hash;
134 This allows future attributes to be added, even if this expands
135 the size of the union.
137 2.1.2 Status
139 Complete.
141 2.2 tdb_traverse Makes Impossible Guarantees
143 tdb_traverse (and tdb_firstkey/tdb_nextkey) predate transactions,
144 and it was thought that it was important to guarantee that all
145 records which exist at the start and end of the traversal would
146 be included, and no record would be included twice.
148 This adds complexity (see[Reliable-Traversal-Adds]) and does not
149 work anyway for records which are altered (in particular, those
150 which are expanded may be effectively deleted and re-added behind
151 the traversal).
153 2.2.1 <traverse-Proposed-Solution>Proposed Solution
155 Abandon the guarantee. You will see every record if no changes
156 occur during your traversal, otherwise you will see some subset.
157 You can prevent changes by using a transaction or the locking
158 API.
160 2.2.2 Status
162 Complete. Delete-during-traverse will still delete every record,
163 too (assuming no other changes).
165 2.3 Nesting of Transactions Is Fraught
167 TDB has alternated between allowing nested transactions and not
168 allowing them. Various paths in the Samba codebase assume that
169 transactions will nest, and in a sense they can: the operation is
170 only committed to disk when the outer transaction is committed.
171 There are two problems, however:
173 1. Canceling the inner transaction will cause the outer
174   transaction commit to fail, and will not undo any operations
175   since the inner transaction began. This problem is soluble with
176   some additional internal code.
178 2. An inner transaction commit can be cancelled by the outer
179   transaction. This is desirable in the way which Samba's
180   database initialization code uses transactions, but could be a
181   surprise to any users expecting a successful transaction commit
182   to expose changes to others.
184 The current solution is to specify the behavior at tdb_open(),
185 with the default currently that nested transactions are allowed.
186 This flag can also be changed at runtime.
188 2.3.1 Proposed Solution
190 Given the usage patterns, it seems that the“least-surprise”
191 behavior of disallowing nested transactions should become the
192 default. Additionally, it seems the outer transaction is the only
193 code which knows whether inner transactions should be allowed, so
194 a flag to indicate this could be added to tdb_transaction_start.
195 However, this behavior can be simulated with a wrapper which uses
196 tdb_add_flags() and tdb_remove_flags(), so the API should not be
197 expanded for this relatively-obscure case.
199 2.3.2 Status
201 Complete; the nesting flag has been removed.
203 2.4 Incorrect Hash Function is Not Detected
205 tdb_open_ex() allows the calling code to specify a different hash
206 function to use, but does not check that all other processes
207 accessing this tdb are using the same hash function. The result
208 is that records are missing from tdb_fetch().
210 2.4.1 Proposed Solution
212 The header should contain an example hash result (eg. the hash of
213 0xdeadbeef), and tdb_open_ex() should check that the given hash
214 function produces the same answer, or fail the tdb_open call.
216 2.4.2 Status
218 Complete.
220 2.5 tdb_set_max_dead/TDB_VOLATILE Expose Implementation
222 In response to scalability issues with the free list ([TDB-Freelist-Is]
223 ) two API workarounds have been incorporated in TDB:
224 tdb_set_max_dead() and the TDB_VOLATILE flag to tdb_open. The
225 latter actually calls the former with an argument of“5”.
227 This code allows deleted records to accumulate without putting
228 them in the free list. On delete we iterate through each chain
229 and free them in a batch if there are more than max_dead entries.
230 These are never otherwise recycled except as a side-effect of a
231 tdb_repack.
233 2.5.1 Proposed Solution
235 With the scalability problems of the freelist solved, this API
236 can be removed. The TDB_VOLATILE flag may still be useful as a
237 hint that store and delete of records will be at least as common
238 as fetch in order to allow some internal tuning, but initially
239 will become a no-op.
241 2.5.2 Status
243 Complete. Unknown flags cause tdb_open() to fail as well, so they
244 can be detected at runtime.
246 2.6 <TDB-Files-Cannot>TDB Files Cannot Be Opened Multiple Times
247   In The Same Process
249 No process can open the same TDB twice; we check and disallow it.
250 This is an unfortunate side-effect of fcntl locks, which operate
251 on a per-file rather than per-file-descriptor basis, and do not
252 nest. Thus, closing any file descriptor on a file clears all the
253 locks obtained by this process, even if they were placed using a
254 different file descriptor!
256 Note that even if this were solved, deadlock could occur if
257 operations were nested: this is a more manageable programming
258 error in most cases.
260 2.6.1 Proposed Solution
262 We could lobby POSIX to fix the perverse rules, or at least lobby
263 Linux to violate them so that the most common implementation does
264 not have this restriction. This would be a generally good idea
265 for other fcntl lock users.
267 Samba uses a wrapper which hands out the same tdb_context to
268 multiple callers if this happens, and does simple reference
269 counting. We should do this inside the tdb library, which already
270 emulates lock nesting internally; it would need to recognize when
271 deadlock occurs within a single process. This would create a new
272 failure mode for tdb operations (while we currently handle
273 locking failures, they are impossible in normal use and a process
274 encountering them can do little but give up).
276 I do not see benefit in an additional tdb_open flag to indicate
277 whether re-opening is allowed, as though there may be some
278 benefit to adding a call to detect when a tdb_context is shared,
279 to allow other to create such an API.
281 2.6.2 Status
283 Complete.
285 2.7 TDB API Is Not POSIX Thread-safe
287 The TDB API uses an error code which can be queried after an
288 operation to determine what went wrong. This programming model
289 does not work with threads, unless specific additional guarantees
290 are given by the implementation. In addition, even
291 otherwise-independent threads cannot open the same TDB (as in[TDB-Files-Cannot]
294 2.7.1 Proposed Solution
296 Reachitecting the API to include a tdb_errcode pointer would be a
297 great deal of churn, but fortunately most functions return 0 on
298 success and -1 on error: we can change these to return 0 on
299 success and a negative error code on error, and the API remains
300 similar to previous. The tdb_fetch, tdb_firstkey and tdb_nextkey
301 functions need to take a TDB_DATA pointer and return an error
302 code. It is also simpler to have tdb_nextkey replace its key
303 argument in place, freeing up any old .dptr.
305 Internal locking is required to make sure that fcntl locks do not
306 overlap between threads, and also that the global list of tdbs is
307 maintained.
309 The aim is that building tdb with -DTDB_PTHREAD will result in a
310 pthread-safe version of the library, and otherwise no overhead
311 will exist. Alternatively, a hooking mechanism similar to that
312 proposed for[Proposed-Solution-locking-hook] could be used to
313 enable pthread locking at runtime.
315 2.7.2 Status
317 Incomplete; API has been changed but thread safety has not been
318 implemented.
320 2.8 *_nonblock Functions And *_mark Functions Expose
321   Implementation
323 CTDB[footnote:
324 Clustered TDB, see http://ctdb.samba.org
325 ] wishes to operate on TDB in a non-blocking manner. This is
326 currently done as follows:
328 1. Call the _nonblock variant of an API function (eg.
329   tdb_lockall_nonblock). If this fails:
331 2. Fork a child process, and wait for it to call the normal
332   variant (eg. tdb_lockall).
334 3. If the child succeeds, call the _mark variant to indicate we
335   already have the locks (eg. tdb_lockall_mark).
337 4. Upon completion, tell the child to release the locks (eg.
338   tdb_unlockall).
340 5. Indicate to tdb that it should consider the locks removed (eg.
341   tdb_unlockall_mark).
343 There are several issues with this approach. Firstly, adding two
344 new variants of each function clutters the API for an obscure
345 use, and so not all functions have three variants. Secondly, it
346 assumes that all paths of the functions ask for the same locks,
347 otherwise the parent process will have to get a lock which the
348 child doesn't have under some circumstances. I don't believe this
349 is currently the case, but it constrains the implementation.
351 2.8.1 <Proposed-Solution-locking-hook>Proposed Solution
353 Implement a hook for locking methods, so that the caller can
354 control the calls to create and remove fcntl locks. In this
355 scenario, ctdbd would operate as follows:
357 1. Call the normal API function, eg tdb_lockall().
359 2. When the lock callback comes in, check if the child has the
360   lock. Initially, this is always false. If so, return 0.
361   Otherwise, try to obtain it in non-blocking mode. If that
362   fails, return EWOULDBLOCK.
364 3. Release locks in the unlock callback as normal.
366 4. If tdb_lockall() fails, see if we recorded a lock failure; if
367   so, call the child to repeat the operation.
369 5. The child records what locks it obtains, and returns that
370   information to the parent.
372 6. When the child has succeeded, goto 1.
374 This is flexible enough to handle any potential locking scenario,
375 even when lock requirements change. It can be optimized so that
376 the parent does not release locks, just tells the child which
377 locks it doesn't need to obtain.
379 It also keeps the complexity out of the API, and in ctdbd where
380 it is needed.
382 2.8.2 Status
384 Complete.
386 2.9 tdb_chainlock Functions Expose Implementation
388 tdb_chainlock locks some number of records, including the record
389 indicated by the given key. This gave atomicity guarantees;
390 no-one can start a transaction, alter, read or delete that key
391 while the lock is held.
393 It also makes the same guarantee for any other key in the chain,
394 which is an internal implementation detail and potentially a
395 cause for deadlock.
397 2.9.1 Proposed Solution
399 None. It would be nice to have an explicit single entry lock
400 which effected no other keys. Unfortunately, this won't work for
401 an entry which doesn't exist. Thus while chainlock may be
402 implemented more efficiently for the existing case, it will still
403 have overlap issues with the non-existing case. So it is best to
404 keep the current (lack of) guarantee about which records will be
405 effected to avoid constraining our implementation.
407 2.10 Signal Handling is Not Race-Free
409 The tdb_setalarm_sigptr() call allows the caller's signal handler
410 to indicate that the tdb locking code should return with a
411 failure, rather than trying again when a signal is received (and
412 errno == EAGAIN). This is usually used to implement timeouts.
414 Unfortunately, this does not work in the case where the signal is
415 received before the tdb code enters the fcntl() call to place the
416 lock: the code will sleep within the fcntl() code, unaware that
417 the signal wants it to exit. In the case of long timeouts, this
418 does not happen in practice.
420 2.10.1 Proposed Solution
422 The locking hooks proposed in[Proposed-Solution-locking-hook]
423 would allow the user to decide on whether to fail the lock
424 acquisition on a signal. This allows the caller to choose their
425 own compromise: they could narrow the race by checking
426 immediately before the fcntl call.[footnote:
427 It may be possible to make this race-free in some implementations
428 by having the signal handler alter the struct flock to make it
429 invalid. This will cause the fcntl() lock call to fail with
430 EINVAL if the signal occurs before the kernel is entered,
431 otherwise EAGAIN.
434 2.10.2 Status
436 Complete.
438 2.11 The API Uses Gratuitous Typedefs, Capitals
440 typedefs are useful for providing source compatibility when types
441 can differ across implementations, or arguably in the case of
442 function pointer definitions which are hard for humans to parse.
443 Otherwise it is simply obfuscation and pollutes the namespace.
445 Capitalization is usually reserved for compile-time constants and
446 macros.
448   TDB_CONTEXT There is no reason to use this over 'struct
449   tdb_context'; the definition isn't visible to the API user
450   anyway.
452   TDB_DATA There is no reason to use this over struct TDB_DATA;
453   the struct needs to be understood by the API user.
455   struct TDB_DATA This would normally be called 'struct
456   tdb_data'.
458   enum TDB_ERROR Similarly, this would normally be enum
459   tdb_error.
461 2.11.1 Proposed Solution
463 None. Introducing lower case variants would please pedants like
464 myself, but if it were done the existing ones should be kept.
465 There is little point forcing a purely cosmetic change upon tdb
466 users.
468 2.12 <tdb_log_func-Doesnt-Take>tdb_log_func Doesn't Take The
469   Private Pointer
471 For API compatibility reasons, the logging function needs to call
472 tdb_get_logging_private() to retrieve the pointer registered by
473 the tdb_open_ex for logging.
475 2.12.1 Proposed Solution
477 It should simply take an extra argument, since we are prepared to
478 break the API/ABI.
480 2.12.2 Status
482 Complete.
484 2.13 Various Callback Functions Are Not Typesafe
486 The callback functions in tdb_set_logging_function (after[tdb_log_func-Doesnt-Take]
487  is resolved), tdb_parse_record, tdb_traverse, tdb_traverse_read
488 and tdb_check all take void * and must internally convert it to
489 the argument type they were expecting.
491 If this type changes, the compiler will not produce warnings on
492 the callers, since it only sees void *.
494 2.13.1 Proposed Solution
496 With careful use of macros, we can create callback functions
497 which give a warning when used on gcc and the types of the
498 callback and its private argument differ. Unsupported compilers
499 will not give a warning, which is no worse than now. In addition,
500 the callbacks become clearer, as they need not use void * for
501 their parameter.
503 See CCAN's typesafe_cb module at
504 http://ccan.ozlabs.org/info/typesafe_cb.html
506 2.13.2 Status
508 Complete.
510 2.14 TDB_CLEAR_IF_FIRST Must Be Specified On All Opens,
511   tdb_reopen_all Problematic
513 The TDB_CLEAR_IF_FIRST flag to tdb_open indicates that the TDB
514 file should be cleared if the caller discovers it is the only
515 process with the TDB open. However, if any caller does not
516 specify TDB_CLEAR_IF_FIRST it will not be detected, so will have
517 the TDB erased underneath them (usually resulting in a crash).
519 There is a similar issue on fork(); if the parent exits (or
520 otherwise closes the tdb) before the child calls tdb_reopen_all()
521 to establish the lock used to indicate the TDB is opened by
522 someone, a TDB_CLEAR_IF_FIRST opener at that moment will believe
523 it alone has opened the TDB and will erase it.
525 2.14.1 Proposed Solution
527 Remove TDB_CLEAR_IF_FIRST. Other workarounds are possible, but
528 see[TDB_CLEAR_IF_FIRST-Imposes-Performance].
530 2.14.2 Status
532 Complete. An open hook is provided to replicate this
533 functionality if required.
535 2.15 Extending The Header Is Difficult
537 We have reserved (zeroed) words in the TDB header, which can be
538 used for future features. If the future features are compulsory,
539 the version number must be updated to prevent old code from
540 accessing the database. But if the future feature is optional, we
541 have no way of telling if older code is accessing the database or
542 not.
544 2.15.1 Proposed Solution
546 The header should contain a“format variant” value (64-bit). This
547 is divided into two 32-bit parts:
549 1. The lower part reflects the format variant understood by code
550   accessing the database.
552 2. The upper part reflects the format variant you must understand
553   to write to the database (otherwise you can only open for
554   reading).
556 The latter field can only be written at creation time, the former
557 should be written under the OPEN_LOCK when opening the database
558 for writing, if the variant of the code is lower than the current
559 lowest variant.
561 This should allow backwards-compatible features to be added, and
562 detection if older code (which doesn't understand the feature)
563 writes to the database.
565 2.15.2 Status
567 Complete.
569 2.16 Record Headers Are Not Expandible
571 If we later want to add (say) checksums on keys and data, it
572 would require another format change, which we'd like to avoid.
574 2.16.1 Proposed Solution
576 We often have extra padding at the tail of a record. If we ensure
577 that the first byte (if any) of this padding is zero, we will
578 have a way for future changes to detect code which doesn't
579 understand a new format: the new code would write (say) a 1 at
580 the tail, and thus if there is no tail or the first byte is 0, we
581 would know the extension is not present on that record.
583 2.16.2 Status
585 Complete.
587 2.17 TDB Does Not Use Talloc
589 Many users of TDB (particularly Samba) use the talloc allocator,
590 and thus have to wrap TDB in a talloc context to use it
591 conveniently.
593 2.17.1 Proposed Solution
595 The allocation within TDB is not complicated enough to justify
596 the use of talloc, and I am reluctant to force another
597 (excellent) library on TDB users. Nonetheless a compromise is
598 possible. An attribute (see[attributes]) can be added later to
599 tdb_open() to provide an alternate allocation mechanism,
600 specifically for talloc but usable by any other allocator (which
601 would ignore the“context” argument).
603 This would form a talloc heirarchy as expected, but the caller
604 would still have to attach a destructor to the tdb context
605 returned from tdb_open to close it. All TDB_DATA fields would be
606 children of the tdb_context, and the caller would still have to
607 manage them (using talloc_free() or talloc_steal()).
609 2.17.2 Status
611 Complete, using the NTDB_ATTRIBUTE_ALLOCATOR attribute.
613 3 Performance And Scalability Issues
615 3.1 <TDB_CLEAR_IF_FIRST-Imposes-Performance>TDB_CLEAR_IF_FIRST
616   Imposes Performance Penalty
618 When TDB_CLEAR_IF_FIRST is specified, a 1-byte read lock is
619 placed at offset 4 (aka. the ACTIVE_LOCK). While these locks
620 never conflict in normal tdb usage, they do add substantial
621 overhead for most fcntl lock implementations when the kernel
622 scans to detect if a lock conflict exists. This is often a single
623 linked list, making the time to acquire and release a fcntl lock
624 O(N) where N is the number of processes with the TDB open, not
625 the number actually doing work.
627 In a Samba server it is common to have huge numbers of clients
628 sitting idle, and thus they have weaned themselves off the
629 TDB_CLEAR_IF_FIRST flag.[footnote:
630 There is a flag to tdb_reopen_all() which is used for this
631 optimization: if the parent process will outlive the child, the
632 child does not need the ACTIVE_LOCK. This is a workaround for
633 this very performance issue.
636 3.1.1 Proposed Solution
638 Remove the flag. It was a neat idea, but even trivial servers
639 tend to know when they are initializing for the first time and
640 can simply unlink the old tdb at that point.
642 3.1.2 Status
644 Complete.
646 3.2 TDB Files Have a 4G Limit
648 This seems to be becoming an issue (so much for“trivial”!),
649 particularly for ldb.
651 3.2.1 Proposed Solution
653 A new, incompatible TDB format which uses 64 bit offsets
654 internally rather than 32 bit as now. For simplicity of endian
655 conversion (which TDB does on the fly if required), all values
656 will be 64 bit on disk. In practice, some upper bits may be used
657 for other purposes, but at least 56 bits will be available for
658 file offsets.
660 tdb_open() will automatically detect the old version, and even
661 create them if TDB_VERSION6 is specified to tdb_open.
663 32 bit processes will still be able to access TDBs larger than 4G
664 (assuming that their off_t allows them to seek to 64 bits), they
665 will gracefully fall back as they fail to mmap. This can happen
666 already with large TDBs.
668 Old versions of tdb will fail to open the new TDB files (since 28
669 August 2009, commit 398d0c29290: prior to that any unrecognized
670 file format would be erased and initialized as a fresh tdb!)
672 3.2.2 Status
674 Complete.
676 3.3 TDB Records Have a 4G Limit
678 This has not been a reported problem, and the API uses size_t
679 which can be 64 bit on 64 bit platforms. However, other limits
680 may have made such an issue moot.
682 3.3.1 Proposed Solution
684 Record sizes will be 64 bit, with an error returned on 32 bit
685 platforms which try to access such records (the current
686 implementation would return TDB_ERR_OOM in a similar case). It
687 seems unlikely that 32 bit keys will be a limitation, so the
688 implementation may not support this (see[sub:Records-Incur-A]).
690 3.3.2 Status
692 Complete.
694 3.4 Hash Size Is Determined At TDB Creation Time
696 TDB contains a number of hash chains in the header; the number is
697 specified at creation time, and defaults to 131. This is such a
698 bottleneck on large databases (as each hash chain gets quite
699 long), that LDB uses 10,000 for this hash. In general it is
700 impossible to know what the 'right' answer is at database
701 creation time.
703 3.4.1 <sub:Hash-Size-Solution>Proposed Solution
705 After comprehensive performance testing on various scalable hash
706 variants[footnote:
707 http://rusty.ozlabs.org/?p=89 and http://rusty.ozlabs.org/?p=94
708 This was annoying because I was previously convinced that an
709 expanding tree of hashes would be very close to optimal.
710 ], it became clear that it is hard to beat a straight linear hash
711 table which doubles in size when it reaches saturation.
712 Unfortunately, altering the hash table introduces serious locking
713 complications: the entire hash table needs to be locked to
714 enlarge the hash table, and others might be holding locks.
715 Particularly insidious are insertions done under tdb_chainlock.
717 Thus an expanding layered hash will be used: an array of hash
718 groups, with each hash group exploding into pointers to lower
719 hash groups once it fills, turning into a hash tree. This has
720 implications for locking: we must lock the entire group in case
721 we need to expand it, yet we don't know how deep the tree is at
722 that point.
724 Note that bits from the hash table entries should be stolen to
725 hold more hash bits to reduce the penalty of collisions. We can
726 use the otherwise-unused lower 3 bits. If we limit the size of
727 the database to 64 exabytes, we can use the top 8 bits of the
728 hash entry as well. These 11 bits would reduce false positives
729 down to 1 in 2000 which is more than we need: we can use one of
730 the bits to indicate that the extra hash bits are valid. This
731 means we can choose not to re-hash all entries when we expand a
732 hash group; simply use the next bits we need and mark them
733 invalid.
735 3.4.2 Status
737 Ignore. Scaling the hash automatically proved inefficient at
738 small hash sizes; we default to a 8192-element hash (changable
739 via NTDB_ATTRIBUTE_HASHSIZE), and when buckets clash we expand to
740 an array of hash entries. This scales slightly better than the
741 tdb chain (due to the 8 top bits containing extra hash).
743 3.5 <TDB-Freelist-Is>TDB Freelist Is Highly Contended
745 TDB uses a single linked list for the free list. Allocation
746 occurs as follows, using heuristics which have evolved over time:
748 1. Get the free list lock for this whole operation.
750 2. Multiply length by 1.25, so we always over-allocate by 25%.
752 3. Set the slack multiplier to 1.
754 4. Examine the current freelist entry: if it is > length but <
755   the current best case, remember it as the best case.
757 5. Multiply the slack multiplier by 1.05.
759 6. If our best fit so far is less than length * slack multiplier,
760   return it. The slack will be turned into a new free record if
761   it's large enough.
763 7. Otherwise, go onto the next freelist entry.
765 Deleting a record occurs as follows:
767 1. Lock the hash chain for this whole operation.
769 2. Walk the chain to find the record, keeping the prev pointer
770   offset.
772 3. If max_dead is non-zero:
774   (a) Walk the hash chain again and count the dead records.
776   (b) If it's more than max_dead, bulk free all the dead ones
777     (similar to steps 4 and below, but the lock is only obtained
778     once).
780   (c) Simply mark this record as dead and return.
782 4. Get the free list lock for the remainder of this operation.
784 5. <right-merging>Examine the following block to see if it is
785   free; if so, enlarge the current block and remove that block
786   from the free list. This was disabled, as removal from the free
787   list was O(entries-in-free-list).
789 6. Examine the preceeding block to see if it is free: for this
790   reason, each block has a 32-bit tailer which indicates its
791   length. If it is free, expand it to cover our new block and
792   return.
794 7. Otherwise, prepend ourselves to the free list.
796 Disabling right-merging (step[right-merging]) causes
797 fragmentation; the other heuristics proved insufficient to
798 address this, so the final answer to this was that when we expand
799 the TDB file inside a transaction commit, we repack the entire
800 tdb.
802 The single list lock limits our allocation rate; due to the other
803 issues this is not currently seen as a bottleneck.
805 3.5.1 Proposed Solution
807 The first step is to remove all the current heuristics, as they
808 obviously interact, then examine them once the lock contention is
809 addressed.
811 The free list must be split to reduce contention. Assuming
812 perfect free merging, we can at most have 1 free list entry for
813 each entry. This implies that the number of free lists is related
814 to the size of the hash table, but as it is rare to walk a large
815 number of free list entries we can use far fewer, say 1/32 of the
816 number of hash buckets.
818 It seems tempting to try to reuse the hash implementation which
819 we use for records here, but we have two ways of searching for
820 free entries: for allocation we search by size (and possibly
821 zone) which produces too many clashes for our hash table to
822 handle well, and for coalescing we search by address. Thus an
823 array of doubly-linked free lists seems preferable.
825 There are various benefits in using per-size free lists (see[sub:TDB-Becomes-Fragmented]
826 ) but it's not clear this would reduce contention in the common
827 case where all processes are allocating/freeing the same size.
828 Thus we almost certainly need to divide in other ways: the most
829 obvious is to divide the file into zones, and using a free list
830 (or table of free lists) for each. This approximates address
831 ordering.
833 Unfortunately it is difficult to know what heuristics should be
834 used to determine zone sizes, and our transaction code relies on
835 being able to create a“recovery area” by simply appending to the
836 file (difficult if it would need to create a new zone header).
837 Thus we use a linked-list of free tables; currently we only ever
838 create one, but if there is more than one we choose one at random
839 to use. In future we may use heuristics to add new free tables on
840 contention. We only expand the file when all free tables are
841 exhausted.
843 The basic algorithm is as follows. Freeing is simple:
845 1. Identify the correct free list.
847 2. Lock the corresponding list.
849 3. Re-check the list (we didn't have a lock, sizes could have
850   changed): relock if necessary.
852 4. Place the freed entry in the list.
854 Allocation is a little more complicated, as we perform delayed
855 coalescing at this point:
857 1. Pick a free table; usually the previous one.
859 2. Lock the corresponding list.
861 3. If the top entry is -large enough, remove it from the list and
862   return it.
864 4. Otherwise, coalesce entries in the list.If there was no entry
865   large enough, unlock the list and try the next largest list
867 5. If no list has an entry which meets our needs, try the next
868   free table.
870 6. If no zone satisfies, expand the file.
872 This optimizes rapid insert/delete of free list entries by not
873 coalescing them all the time.. First-fit address ordering
874 ordering seems to be fairly good for keeping fragmentation low
875 (see[sub:TDB-Becomes-Fragmented]). Note that address ordering
876 does not need a tailer to coalesce, though if we needed one we
877 could have one cheaply: see[sub:Records-Incur-A].
879 Each free entry has the free table number in the header: less
880 than 255. It also contains a doubly-linked list for easy
881 deletion.
883 3.6 <sub:TDB-Becomes-Fragmented>TDB Becomes Fragmented
885 Much of this is a result of allocation strategy[footnote:
886 The Memory Fragmentation Problem: Solved? Johnstone & Wilson 1995
887 ftp://ftp.cs.utexas.edu/pub/garbage/malloc/ismm98.ps
888 ] and deliberate hobbling of coalescing; internal fragmentation
889 (aka overallocation) is deliberately set at 25%, and external
890 fragmentation is only cured by the decision to repack the entire
891 db when a transaction commit needs to enlarge the file.
893 3.6.1 Proposed Solution
895 The 25% overhead on allocation works in practice for ldb because
896 indexes tend to expand by one record at a time. This internal
897 fragmentation can be resolved by having an“expanded” bit in the
898 header to note entries that have previously expanded, and
899 allocating more space for them.
901 There are is a spectrum of possible solutions for external
902 fragmentation: one is to use a fragmentation-avoiding allocation
903 strategy such as best-fit address-order allocator. The other end
904 of the spectrum would be to use a bump allocator (very fast and
905 simple) and simply repack the file when we reach the end.
907 There are three problems with efficient fragmentation-avoiding
908 allocators: they are non-trivial, they tend to use a single free
909 list for each size, and there's no evidence that tdb allocation
910 patterns will match those recorded for general allocators (though
911 it seems likely).
913 Thus we don't spend too much effort on external fragmentation; we
914 will be no worse than the current code if we need to repack on
915 occasion. More effort is spent on reducing freelist contention,
916 and reducing overhead.
918 3.7 <sub:Records-Incur-A>Records Incur A 28-Byte Overhead
920 Each TDB record has a header as follows:
922 struct tdb_record {
924         tdb_off_t next; /* offset of the next record in the list
927         tdb_len_t rec_len; /* total byte length of record */
929         tdb_len_t key_len; /* byte length of key */
931         tdb_len_t data_len; /* byte length of data */
933         uint32_t full_hash; /* the full 32 bit hash of the key */
935         uint32_t magic;   /* try to catch errors */
937         /* the following union is implied:
939                 union {
941                         char record[rec_len];
943                         struct {
945                                 char key[key_len];
947                                 char data[data_len];
949                         }
951                         uint32_t totalsize; (tailer)
953                 }
955         */
959 Naively, this would double to a 56-byte overhead on a 64 bit
960 implementation.
962 3.7.1 Proposed Solution
964 We can use various techniques to reduce this for an allocated
965 block:
967 1. The 'next' pointer is not required, as we are using a flat
968   hash table.
970 2. 'rec_len' can instead be expressed as an addition to key_len
971   and data_len (it accounts for wasted or overallocated length in
972   the record). Since the record length is always a multiple of 8,
973   we can conveniently fit it in 32 bits (representing up to 35
974   bits).
976 3. 'key_len' and 'data_len' can be reduced. I'm unwilling to
977   restrict 'data_len' to 32 bits, but instead we can combine the
978   two into one 64-bit field and using a 5 bit value which
979   indicates at what bit to divide the two. Keys are unlikely to
980   scale as fast as data, so I'm assuming a maximum key size of 32
981   bits.
983 4. 'full_hash' is used to avoid a memcmp on the“miss” case, but
984   this is diminishing returns after a handful of bits (at 10
985   bits, it reduces 99.9% of false memcmp). As an aside, as the
986   lower bits are already incorporated in the hash table
987   resolution, the upper bits should be used here. Note that it's
988   not clear that these bits will be a win, given the extra bits
989   in the hash table itself (see[sub:Hash-Size-Solution]).
991 5. 'magic' does not need to be enlarged: it currently reflects
992   one of 5 values (used, free, dead, recovery, and
993   unused_recovery). It is useful for quick sanity checking
994   however, and should not be eliminated.
996 6. 'tailer' is only used to coalesce free blocks (so a block to
997   the right can find the header to check if this block is free).
998   This can be replaced by a single 'free' bit in the header of
999   the following block (and the tailer only exists in free
1000   blocks).[footnote:
1001 This technique from Thomas Standish. Data Structure Techniques.
1002 Addison-Wesley, Reading, Massachusetts, 1980.
1003 ] The current proposed coalescing algorithm doesn't need this,
1004   however.
1006 This produces a 16 byte used header like this:
1008 struct tdb_used_record {
1010         uint32_t used_magic : 16,
1014                  key_data_divide: 5,
1016                  top_hash: 11;
1018         uint32_t extra_octets;
1020         uint64_t key_and_data_len;
1024 And a free record like this:
1026 struct tdb_free_record {
1028         uint64_t free_magic: 8,
1030                    prev : 56;
1034         uint64_t free_table: 8,
1036                  total_length : 56
1038         uint64_t next;;
1042 Note that by limiting valid offsets to 56 bits, we can pack
1043 everything we need into 3 64-byte words, meaning our minimum
1044 record size is 8 bytes.
1046 3.7.2 Status
1048 Complete.
1050 3.8 Transaction Commit Requires 4 fdatasync
1052 The current transaction algorithm is:
1054 1. write_recovery_data();
1056 2. sync();
1058 3. write_recovery_header();
1060 4. sync();
1062 5. overwrite_with_new_data();
1064 6. sync();
1066 7. remove_recovery_header();
1068 8. sync();
1070 On current ext3, each sync flushes all data to disk, so the next
1071 3 syncs are relatively expensive. But this could become a
1072 performance bottleneck on other filesystems such as ext4.
1074 3.8.1 Proposed Solution
1076 Neil Brown points out that this is overzealous, and only one sync
1077 is needed:
1079 1. Bundle the recovery data, a transaction counter and a strong
1080   checksum of the new data.
1082 2. Strong checksum that whole bundle.
1084 3. Store the bundle in the database.
1086 4. Overwrite the oldest of the two recovery pointers in the
1087   header (identified using the transaction counter) with the
1088   offset of this bundle.
1090 5. sync.
1092 6. Write the new data to the file.
1094 Checking for recovery means identifying the latest bundle with a
1095 valid checksum and using the new data checksum to ensure that it
1096 has been applied. This is more expensive than the current check,
1097 but need only be done at open. For running databases, a separate
1098 header field can be used to indicate a transaction in progress;
1099 we need only check for recovery if this is set.
1101 3.8.2 Status
1103 Deferred.
1105 3.9 <sub:TDB-Does-Not>TDB Does Not Have Snapshot Support
1107 3.9.1 Proposed Solution
1109 None. At some point you say“use a real database” (but see[replay-attribute]
1112 But as a thought experiment, if we implemented transactions to
1113 only overwrite free entries (this is tricky: there must not be a
1114 header in each entry which indicates whether it is free, but use
1115 of presence in metadata elsewhere), and a pointer to the hash
1116 table, we could create an entirely new commit without destroying
1117 existing data. Then it would be easy to implement snapshots in a
1118 similar way.
1120 This would not allow arbitrary changes to the database, such as
1121 tdb_repack does, and would require more space (since we have to
1122 preserve the current and future entries at once). If we used hash
1123 trees rather than one big hash table, we might only have to
1124 rewrite some sections of the hash, too.
1126 We could then implement snapshots using a similar method, using
1127 multiple different hash tables/free tables.
1129 3.9.2 Status
1131 Deferred.
1133 3.10 Transactions Cannot Operate in Parallel
1135 This would be useless for ldb, as it hits the index records with
1136 just about every update. It would add significant complexity in
1137 resolving clashes, and cause the all transaction callers to write
1138 their code to loop in the case where the transactions spuriously
1139 failed.
1141 3.10.1 Proposed Solution
1143 None (but see[replay-attribute]). We could solve a small part of
1144 the problem by providing read-only transactions. These would
1145 allow one write transaction to begin, but it could not commit
1146 until all r/o transactions are done. This would require a new
1147 RO_TRANSACTION_LOCK, which would be upgraded on commit.
1149 3.10.2 Status
1151 Deferred.
1153 3.11 Default Hash Function Is Suboptimal
1155 The Knuth-inspired multiplicative hash used by tdb is fairly slow
1156 (especially if we expand it to 64 bits), and works best when the
1157 hash bucket size is a prime number (which also means a slow
1158 modulus). In addition, it is highly predictable which could
1159 potentially lead to a Denial of Service attack in some TDB uses.
1161 3.11.1 Proposed Solution
1163 The Jenkins lookup3 hash[footnote:
1164 http://burtleburtle.net/bob/c/lookup3.c
1165 ] is a fast and superbly-mixing hash. It's used by the Linux
1166 kernel and almost everything else. This has the particular
1167 properties that it takes an initial seed, and produces two 32 bit
1168 hash numbers, which we can combine into a 64-bit hash.
1170 The seed should be created at tdb-creation time from some random
1171 source, and placed in the header. This is far from foolproof, but
1172 adds a little bit of protection against hash bombing.
1174 3.11.2 Status
1176 Complete.
1178 3.12 <Reliable-Traversal-Adds>Reliable Traversal Adds Complexity
1180 We lock a record during traversal iteration, and try to grab that
1181 lock in the delete code. If that grab on delete fails, we simply
1182 mark it deleted and continue onwards; traversal checks for this
1183 condition and does the delete when it moves off the record.
1185 If traversal terminates, the dead record may be left
1186 indefinitely.
1188 3.12.1 Proposed Solution
1190 Remove reliability guarantees; see[traverse-Proposed-Solution].
1192 3.12.2 Status
1194 Complete.
1196 3.13 Fcntl Locking Adds Overhead
1198 Placing a fcntl lock means a system call, as does removing one.
1199 This is actually one reason why transactions can be faster
1200 (everything is locked once at transaction start). In the
1201 uncontended case, this overhead can theoretically be eliminated.
1203 3.13.1 Proposed Solution
1205 None.
1207 We tried this before with spinlock support, in the early days of
1208 TDB, and it didn't make much difference except in manufactured
1209 benchmarks.
1211 We could use spinlocks (with futex kernel support under Linux),
1212 but it means that we lose automatic cleanup when a process dies
1213 with a lock. There is a method of auto-cleanup under Linux, but
1214 it's not supported by other operating systems. We could
1215 reintroduce a clear-if-first-style lock and sweep for dead
1216 futexes on open, but that wouldn't help the normal case of one
1217 concurrent opener dying. Increasingly elaborate repair schemes
1218 could be considered, but they require an ABI change (everyone
1219 must use them) anyway, so there's no need to do this at the same
1220 time as everything else.
1222 3.14 Some Transactions Don't Require Durability
1224 Volker points out that gencache uses a CLEAR_IF_FIRST tdb for
1225 normal (fast) usage, and occasionally empties the results into a
1226 transactional TDB. This kind of usage prioritizes performance
1227 over durability: as long as we are consistent, data can be lost.
1229 This would be more neatly implemented inside tdb: a“soft”
1230 transaction commit (ie. syncless) which meant that data may be
1231 reverted on a crash.
1233 3.14.1 Proposed Solution
1235 None.
1237 Unfortunately any transaction scheme which overwrites old data
1238 requires a sync before that overwrite to avoid the possibility of
1239 corruption.
1241 It seems possible to use a scheme similar to that described in[sub:TDB-Does-Not]
1242 ,where transactions are committed without overwriting existing
1243 data, and an array of top-level pointers were available in the
1244 header. If the transaction is“soft” then we would not need a sync
1245 at all: existing processes would pick up the new hash table and
1246 free list and work with that.
1248 At some later point, a sync would allow recovery of the old data
1249 into the free lists (perhaps when the array of top-level pointers
1250 filled). On crash, tdb_open() would examine the array of top
1251 levels, and apply the transactions until it encountered an
1252 invalid checksum.
1254 3.15 Tracing Is Fragile, Replay Is External
1256 The current TDB has compile-time-enabled tracing code, but it
1257 often breaks as it is not enabled by default. In a similar way,
1258 the ctdb code has an external wrapper which does replay tracing
1259 so it can coordinate cluster-wide transactions.
1261 3.15.1 Proposed Solution<replay-attribute>
1263 Tridge points out that an attribute can be later added to
1264 tdb_open (see[attributes]) to provide replay/trace hooks, which
1265 could become the basis for this and future parallel transactions
1266 and snapshot support.
1268 3.15.2 Status
1270 Deferred.