Improve the VFS Makefile so that it is easier for use out of tree but still works...
[Samba/gebeck_regimport.git] / lib / tdb2 / doc / design-1.3.txt
blobf81ecf78855818529542b5472b9ee468a6443370
1 TDB2: A Redesigning The Trivial DataBase
3 Rusty Russell, IBM Corporation
5 27-April-2010
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 2 API Issues
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
79 tdb_open() will take a linked-list of attributes:
81 enum tdb_attribute {
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
102     tdb_log_func log_fn;
104     void *log_private;
108 struct tdb_attribute_hash {
110     struct tdb_attribute_base base; /* .attr = TDB_ATTRIBUTE_HASH
113     tdb_hash_func hash_fn;
115     void *hash_private;
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
142 the traversal).
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
149 API.
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
209 tdb_repack.
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
217 will become a no-op.
219 2.6 <TDB-Files-Cannot>TDB Files Cannot Be Opened Multiple Times
220   In The Same Process
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
231 error in most cases.
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
268 maintained.
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
276 maintained.
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.
282 2.8 *_nonblock Functions And *_mark Functions Expose
283   Implementation
285 CTDB[footnote:
286 Clustered TDB, see http://ctdb.samba.org
287 ] wishes to operate on TDB in a non-blocking manner. This is
288 currently done as follows:
290 1. Call the _nonblock variant of an API function (eg.
291   tdb_lockall_nonblock). If this fails:
293 2. Fork a child process, and wait for it to call the normal
294   variant (eg. tdb_lockall).
296 3. If the child succeeds, call the _mark variant to indicate we
297   already have the locks (eg. tdb_lockall_mark).
299 4. Upon completion, tell the child to release the locks (eg.
300   tdb_unlockall).
302 5. Indicate to tdb that it should consider the locks removed (eg.
303   tdb_unlockall_mark).
305 There are several issues with this approach. Firstly, adding two
306 new variants of each function clutters the API for an obscure
307 use, and so not all functions have three variants. Secondly, it
308 assumes that all paths of the functions ask for the same locks,
309 otherwise the parent process will have to get a lock which the
310 child doesn't have under some circumstances. I don't believe this
311 is currently the case, but it constrains the implementation.
313 2.8.1 <Proposed-Solution-locking-hook>Proposed Solution
315 Implement a hook for locking methods, so that the caller can
316 control the calls to create and remove fcntl locks. In this
317 scenario, ctdbd would operate as follows:
319 1. Call the normal API function, eg tdb_lockall().
321 2. When the lock callback comes in, check if the child has the
322   lock. Initially, this is always false. If so, return 0.
323   Otherwise, try to obtain it in non-blocking mode. If that
324   fails, return EWOULDBLOCK.
326 3. Release locks in the unlock callback as normal.
328 4. If tdb_lockall() fails, see if we recorded a lock failure; if
329   so, call the child to repeat the operation.
331 5. The child records what locks it obtains, and returns that
332   information to the parent.
334 6. When the child has succeeded, goto 1.
336 This is flexible enough to handle any potential locking scenario,
337 even when lock requirements change. It can be optimized so that
338 the parent does not release locks, just tells the child which
339 locks it doesn't need to obtain.
341 It also keeps the complexity out of the API, and in ctdbd where
342 it is needed.
344 2.9 tdb_chainlock Functions Expose Implementation
346 tdb_chainlock locks some number of records, including the record
347 indicated by the given key. This gave atomicity guarantees;
348 no-one can start a transaction, alter, read or delete that key
349 while the lock is held.
351 It also makes the same guarantee for any other key in the chain,
352 which is an internal implementation detail and potentially a
353 cause for deadlock.
355 2.9.1 Proposed Solution
357 None. It would be nice to have an explicit single entry lock
358 which effected no other keys. Unfortunately, this won't work for
359 an entry which doesn't exist. Thus while chainlock may be
360 implemented more efficiently for the existing case, it will still
361 have overlap issues with the non-existing case. So it is best to
362 keep the current (lack of) guarantee about which records will be
363 effected to avoid constraining our implementation.
365 2.10 Signal Handling is Not Race-Free
367 The tdb_setalarm_sigptr() call allows the caller's signal handler
368 to indicate that the tdb locking code should return with a
369 failure, rather than trying again when a signal is received (and
370 errno == EAGAIN). This is usually used to implement timeouts.
372 Unfortunately, this does not work in the case where the signal is
373 received before the tdb code enters the fcntl() call to place the
374 lock: the code will sleep within the fcntl() code, unaware that
375 the signal wants it to exit. In the case of long timeouts, this
376 does not happen in practice.
378 2.10.1 Proposed Solution
380 The locking hooks proposed in[Proposed-Solution-locking-hook]
381 would allow the user to decide on whether to fail the lock
382 acquisition on a signal. This allows the caller to choose their
383 own compromise: they could narrow the race by checking
384 immediately before the fcntl call.[footnote:
385 It may be possible to make this race-free in some implementations
386 by having the signal handler alter the struct flock to make it
387 invalid. This will cause the fcntl() lock call to fail with
388 EINVAL if the signal occurs before the kernel is entered,
389 otherwise EAGAIN.
392 2.11 The API Uses Gratuitous Typedefs, Capitals
394 typedefs are useful for providing source compatibility when types
395 can differ across implementations, or arguably in the case of
396 function pointer definitions which are hard for humans to parse.
397 Otherwise it is simply obfuscation and pollutes the namespace.
399 Capitalization is usually reserved for compile-time constants and
400 macros.
402   TDB_CONTEXT There is no reason to use this over 'struct
403   tdb_context'; the definition isn't visible to the API user
404   anyway.
406   TDB_DATA There is no reason to use this over struct TDB_DATA;
407   the struct needs to be understood by the API user.
409   struct TDB_DATA This would normally be called 'struct
410   tdb_data'.
412   enum TDB_ERROR Similarly, this would normally be enum
413   tdb_error.
415 2.11.1 Proposed Solution
417 None. Introducing lower case variants would please pedants like
418 myself, but if it were done the existing ones should be kept.
419 There is little point forcing a purely cosmetic change upon tdb
420 users.
422 2.12 <tdb_log_func-Doesnt-Take>tdb_log_func Doesn't Take The
423   Private Pointer
425 For API compatibility reasons, the logging function needs to call
426 tdb_get_logging_private() to retrieve the pointer registered by
427 the tdb_open_ex for logging.
429 2.12.1 Proposed Solution
431 It should simply take an extra argument, since we are prepared to
432 break the API/ABI.
434 2.13 Various Callback Functions Are Not Typesafe
436 The callback functions in tdb_set_logging_function (after [tdb_log_func-Doesnt-Take]
437  is resolved), tdb_parse_record, tdb_traverse, tdb_traverse_read
438 and tdb_check all take void * and must internally convert it to
439 the argument type they were expecting.
441 If this type changes, the compiler will not produce warnings on
442 the callers, since it only sees void *.
444 2.13.1 Proposed Solution
446 With careful use of macros, we can create callback functions
447 which give a warning when used on gcc and the types of the
448 callback and its private argument differ. Unsupported compilers
449 will not give a warning, which is no worse than now. In addition,
450 the callbacks become clearer, as they need not use void * for
451 their parameter.
453 See CCAN's typesafe_cb module at
454 http://ccan.ozlabs.org/info/typesafe_cb.html
456 2.14 TDB_CLEAR_IF_FIRST Must Be Specified On All Opens,
457   tdb_reopen_all Problematic
459 The TDB_CLEAR_IF_FIRST flag to tdb_open indicates that the TDB
460 file should be cleared if the caller discovers it is the only
461 process with the TDB open. However, if any caller does not
462 specify TDB_CLEAR_IF_FIRST it will not be detected, so will have
463 the TDB erased underneath them (usually resulting in a crash).
465 There is a similar issue on fork(); if the parent exits (or
466 otherwise closes the tdb) before the child calls tdb_reopen_all()
467 to establish the lock used to indicate the TDB is opened by
468 someone, a TDB_CLEAR_IF_FIRST opener at that moment will believe
469 it alone has opened the TDB and will erase it.
471 2.14.1 Proposed Solution
473 Remove TDB_CLEAR_IF_FIRST. Other workarounds are possible, but
474 see [TDB_CLEAR_IF_FIRST-Imposes-Performance].
476 3 Performance And Scalability Issues
478 3.1 <TDB_CLEAR_IF_FIRST-Imposes-Performance>TDB_CLEAR_IF_FIRST
479   Imposes Performance Penalty
481 When TDB_CLEAR_IF_FIRST is specified, a 1-byte read lock is
482 placed at offset 4 (aka. the ACTIVE_LOCK). While these locks
483 never conflict in normal tdb usage, they do add substantial
484 overhead for most fcntl lock implementations when the kernel
485 scans to detect if a lock conflict exists. This is often a single
486 linked list, making the time to acquire and release a fcntl lock
487 O(N) where N is the number of processes with the TDB open, not
488 the number actually doing work.
490 In a Samba server it is common to have huge numbers of clients
491 sitting idle, and thus they have weaned themselves off the
492 TDB_CLEAR_IF_FIRST flag.[footnote:
493 There is a flag to tdb_reopen_all() which is used for this
494 optimization: if the parent process will outlive the child, the
495 child does not need the ACTIVE_LOCK. This is a workaround for
496 this very performance issue.
499 3.1.1 Proposed Solution
501 Remove the flag. It was a neat idea, but even trivial servers
502 tend to know when they are initializing for the first time and
503 can simply unlink the old tdb at that point.
505 3.2 TDB Files Have a 4G Limit
507 This seems to be becoming an issue (so much for “trivial”!),
508 particularly for ldb.
510 3.2.1 Proposed Solution
512 A new, incompatible TDB format which uses 64 bit offsets
513 internally rather than 32 bit as now. For simplicity of endian
514 conversion (which TDB does on the fly if required), all values
515 will be 64 bit on disk. In practice, some upper bits may be used
516 for other purposes, but at least 56 bits will be available for
517 file offsets.
519 tdb_open() will automatically detect the old version, and even
520 create them if TDB_VERSION6 is specified to tdb_open.
522 32 bit processes will still be able to access TDBs larger than 4G
523 (assuming that their off_t allows them to seek to 64 bits), they
524 will gracefully fall back as they fail to mmap. This can happen
525 already with large TDBs.
527 Old versions of tdb will fail to open the new TDB files (since 28
528 August 2009, commit 398d0c29290: prior to that any unrecognized
529 file format would be erased and initialized as a fresh tdb!)
531 3.3 TDB Records Have a 4G Limit
533 This has not been a reported problem, and the API uses size_t
534 which can be 64 bit on 64 bit platforms. However, other limits
535 may have made such an issue moot.
537 3.3.1 Proposed Solution
539 Record sizes will be 64 bit, with an error returned on 32 bit
540 platforms which try to access such records (the current
541 implementation would return TDB_ERR_OOM in a similar case). It
542 seems unlikely that 32 bit keys will be a limitation, so the
543 implementation may not support this (see [sub:Records-Incur-A]).
545 3.4 Hash Size Is Determined At TDB Creation Time
547 TDB contains a number of hash chains in the header; the number is
548 specified at creation time, and defaults to 131. This is such a
549 bottleneck on large databases (as each hash chain gets quite
550 long), that LDB uses 10,000 for this hash. In general it is
551 impossible to know what the 'right' answer is at database
552 creation time.
554 3.4.1 Proposed Solution
556 After comprehensive performance testing on various scalable hash
557 variants[footnote:
558 http://rusty.ozlabs.org/?p=89 and http://rusty.ozlabs.org/?p=94
559 This was annoying because I was previously convinced that an
560 expanding tree of hashes would be very close to optimal.
561 ], it became clear that it is hard to beat a straight linear hash
562 table which doubles in size when it reaches saturation. There are
563 three details which become important:
565 1. On encountering a full bucket, we use the next bucket.
567 2. Extra hash bits are stored with the offset, to reduce
568   comparisons.
570 3. A marker entry is used on deleting an entry.
572 The doubling of the table must be done under a transaction; we
573 will not reduce it on deletion, so it will be an unusual case. It
574 will either be placed at the head (other entries will be moved
575 out the way so we can expand). We could have a pointer in the
576 header to the current hashtable location, but that pointer would
577 have to be read frequently to check for hashtable moves.
579 The locking for this is slightly more complex than the chained
580 case; we currently have one lock per bucket, and that means we
581 would need to expand the lock if we overflow to the next bucket.
582 The frequency of such collisions will effect our locking
583 heuristics: we can always lock more buckets than we need.
585 One possible optimization is to only re-check the hash size on an
586 insert or a lookup miss.
588 3.5 <TDB-Freelist-Is>TDB Freelist Is Highly Contended
590 TDB uses a single linked list for the free list. Allocation
591 occurs as follows, using heuristics which have evolved over time:
593 1. Get the free list lock for this whole operation.
595 2. Multiply length by 1.25, so we always over-allocate by 25%.
597 3. Set the slack multiplier to 1.
599 4. Examine the current freelist entry: if it is > length but <
600   the current best case, remember it as the best case.
602 5. Multiply the slack multiplier by 1.05.
604 6. If our best fit so far is less than length * slack multiplier,
605   return it. The slack will be turned into a new free record if
606   it's large enough.
608 7. Otherwise, go onto the next freelist entry.
610 Deleting a record occurs as follows:
612 1. Lock the hash chain for this whole operation.
614 2. Walk the chain to find the record, keeping the prev pointer
615   offset.
617 3. If max_dead is non-zero:
619   (a) Walk the hash chain again and count the dead records.
621   (b) If it's more than max_dead, bulk free all the dead ones
622     (similar to steps 4 and below, but the lock is only obtained
623     once).
625   (c) Simply mark this record as dead and return.
627 4. Get the free list lock for the remainder of this operation.
629 5. <right-merging>Examine the following block to see if it is
630   free; if so, enlarge the current block and remove that block
631   from the free list. This was disabled, as removal from the free
632   list was O(entries-in-free-list).
634 6. Examine the preceeding block to see if it is free: for this
635   reason, each block has a 32-bit tailer which indicates its
636   length. If it is free, expand it to cover our new block and
637   return.
639 7. Otherwise, prepend ourselves to the free list.
641 Disabling right-merging (step [right-merging]) causes
642 fragmentation; the other heuristics proved insufficient to
643 address this, so the final answer to this was that when we expand
644 the TDB file inside a transaction commit, we repack the entire
645 tdb.
647 The single list lock limits our allocation rate; due to the other
648 issues this is not currently seen as a bottleneck.
650 3.5.1 Proposed Solution
652 The first step is to remove all the current heuristics, as they
653 obviously interact, then examine them once the lock contention is
654 addressed.
656 The free list must be split to reduce contention. Assuming
657 perfect free merging, we can at most have 1 free list entry for
658 each entry. This implies that the number of free lists is related
659 to the size of the hash table, but as it is rare to walk a large
660 number of free list entries we can use far fewer, say 1/32 of the
661 number of hash buckets.
663 There are various benefits in using per-size free lists (see [sub:TDB-Becomes-Fragmented]
664 ) but it's not clear this would reduce contention in the common
665 case where all processes are allocating/freeing the same size.
666 Thus we almost certainly need to divide in other ways: the most
667 obvious is to divide the file into zones, and using a free list
668 (or set of free lists) for each. This approximates address
669 ordering.
671 Note that this means we need to split the free lists when we
672 expand the file; this is probably acceptable when we double the
673 hash table size, since that is such an expensive operation
674 already. In the case of increasing the file size, there is an
675 optimization we can use: if we use M in the formula above as the
676 file size rounded up to the next power of 2, we only need
677 reshuffle free lists when the file size crosses a power of 2
678 boundary, and reshuffling the free lists is trivial: we simply
679 merge every consecutive pair of free lists.
681 The basic algorithm is as follows. Freeing is simple:
683 1. Identify the correct zone.
685 2. Lock the corresponding list.
687 3. Re-check the zone (we didn't have a lock, sizes could have
688   changed): relock if necessary.
690 4. Place the freed entry in the list for that zone.
692 Allocation is a little more complicated, as we perform delayed
693 coalescing at this point:
695 1. Pick a zone either the zone we last freed into, or based on a “
696   random” number.
698 2. Lock the corresponding list.
700 3. Re-check the zone: relock if necessary.
702 4. If the top entry is -large enough, remove it from the list and
703   return it.
705 5. Otherwise, coalesce entries in the list.
707   (a)
709   (b)
711   (c)
713   (d)
715 6. If there was no entry large enough, unlock the list and try
716   the next zone.
722 9. If no zone satisfies, expand the file.
724 This optimizes rapid insert/delete of free list entries by not
725 coalescing them all the time.. First-fit address ordering
726 ordering seems to be fairly good for keeping fragmentation low
727 (see [sub:TDB-Becomes-Fragmented]). Note that address ordering
728 does not need a tailer to coalesce, though if we needed one we
729 could have one cheaply: see [sub:Records-Incur-A].
733 I anticipate that the number of entries in each free zone would
734 be small, but it might be worth using one free entry to hold
735 pointers to the others for cache efficiency.
737 3.6 <sub:TDB-Becomes-Fragmented>TDB Becomes Fragmented
739 Much of this is a result of allocation strategy[footnote:
740 The Memory Fragmentation Problem: Solved? Johnstone & Wilson 1995
741 ftp://ftp.cs.utexas.edu/pub/garbage/malloc/ismm98.ps
742 ] and deliberate hobbling of coalescing; internal fragmentation
743 (aka overallocation) is deliberately set at 25%, and external
744 fragmentation is only cured by the decision to repack the entire
745 db when a transaction commit needs to enlarge the file.
747 3.6.1 Proposed Solution
749 The 25% overhead on allocation works in practice for ldb because
750 indexes tend to expand by one record at a time. This internal
751 fragmentation can be resolved by having an “expanded” bit in the
752 header to note entries that have previously expanded, and
753 allocating more space for them.
755 There are is a spectrum of possible solutions for external
756 fragmentation: one is to use a fragmentation-avoiding allocation
757 strategy such as best-fit address-order allocator. The other end
758 of the spectrum would be to use a bump allocator (very fast and
759 simple) and simply repack the file when we reach the end.
761 There are three problems with efficient fragmentation-avoiding
762 allocators: they are non-trivial, they tend to use a single free
763 list for each size, and there's no evidence that tdb allocation
764 patterns will match those recorded for general allocators (though
765 it seems likely).
767 Thus we don't spend too much effort on external fragmentation; we
768 will be no worse than the current code if we need to repack on
769 occasion. More effort is spent on reducing freelist contention,
770 and reducing overhead.
772 3.7 <sub:Records-Incur-A>Records Incur A 28-Byte Overhead
774 Each TDB record has a header as follows:
776 struct tdb_record {
778         tdb_off_t next; /* offset of the next record in the list
781         tdb_len_t rec_len; /* total byte length of record */
783         tdb_len_t key_len; /* byte length of key */
785         tdb_len_t data_len; /* byte length of data */
787         uint32_t full_hash; /* the full 32 bit hash of the key */
789         uint32_t magic;   /* try to catch errors */
791         /* the following union is implied:
793                 union {
795                         char record[rec_len];
797                         struct {
799                                 char key[key_len];
801                                 char data[data_len];
803                         }
805                         uint32_t totalsize; (tailer)
807                 }
809         */
813 Naively, this would double to a 56-byte overhead on a 64 bit
814 implementation.
816 3.7.1 Proposed Solution
818 We can use various techniques to reduce this for an allocated
819 block:
821 1. The 'next' pointer is not required, as we are using a flat
822   hash table.
824 2. 'rec_len' can instead be expressed as an addition to key_len
825   and data_len (it accounts for wasted or overallocated length in
826   the record). Since the record length is always a multiple of 8,
827   we can conveniently fit it in 32 bits (representing up to 35
828   bits).
830 3. 'key_len' and 'data_len' can be reduced. I'm unwilling to
831   restrict 'data_len' to 32 bits, but instead we can combine the
832   two into one 64-bit field and using a 5 bit value which
833   indicates at what bit to divide the two. Keys are unlikely to
834   scale as fast as data, so I'm assuming a maximum key size of 32
835   bits.
837 4. 'full_hash' is used to avoid a memcmp on the “miss” case, but
838   this is diminishing returns after a handful of bits (at 10
839   bits, it reduces 99.9% of false memcmp). As an aside, as the
840   lower bits are already incorporated in the hash table
841   resolution, the upper bits should be used here.
843 5. 'magic' does not need to be enlarged: it currently reflects
844   one of 5 values (used, free, dead, recovery, and
845   unused_recovery). It is useful for quick sanity checking
846   however, and should not be eliminated.
848 6. 'tailer' is only used to coalesce free blocks (so a block to
849   the right can find the header to check if this block is free).
850   This can be replaced by a single 'free' bit in the header of
851   the following block (and the tailer only exists in free
852   blocks).[footnote:
853 This technique from Thomas Standish. Data Structure Techniques.
854 Addison-Wesley, Reading, Massachusetts, 1980.
855 ] The current proposed coalescing algorithm doesn't need this,
856   however.
858 This produces a 16 byte used header like this:
860 struct tdb_used_record {
862         uint32_t magic : 16,
864                  prev_is_free: 1,
866                  key_data_divide: 5,
868                  top_hash: 10;
870         uint32_t extra_octets;
872         uint64_t key_and_data_len;
876 And a free record like this:
878 struct tdb_free_record {
880         uint32_t free_magic;
882         uint64_t total_length;
884         ...
886         uint64_t tailer;
892 3.8 Transaction Commit Requires 4 fdatasync
894 The current transaction algorithm is:
896 1. write_recovery_data();
898 2. sync();
900 3. write_recovery_header();
902 4. sync();
904 5. overwrite_with_new_data();
906 6. sync();
908 7. remove_recovery_header();
910 8. sync();
912 On current ext3, each sync flushes all data to disk, so the next
913 3 syncs are relatively expensive. But this could become a
914 performance bottleneck on other filesystems such as ext4.
916 3.8.1 Proposed Solution
926 Neil Brown points out that this is overzealous, and only one sync
927 is needed:
929 1. Bundle the recovery data, a transaction counter and a strong
930   checksum of the new data.
932 2. Strong checksum that whole bundle.
934 3. Store the bundle in the database.
936 4. Overwrite the oldest of the two recovery pointers in the
937   header (identified using the transaction counter) with the
938   offset of this bundle.
940 5. sync.
942 6. Write the new data to the file.
944 Checking for recovery means identifying the latest bundle with a
945 valid checksum and using the new data checksum to ensure that it
946 has been applied. This is more expensive than the current check,
947 but need only be done at open. For running databases, a separate
948 header field can be used to indicate a transaction in progress;
949 we need only check for recovery if this is set.
951 3.9 TDB Does Not Have Snapshot Support
953 3.9.1 Proposed Solution
955 None. At some point you say “use a real database”.
957 But as a thought experiment, if we implemented transactions to
958 only overwrite free entries (this is tricky: there must not be a
959 header in each entry which indicates whether it is free, but use
960 of presence in metadata elsewhere), and a pointer to the hash
961 table, we could create an entirely new commit without destroying
962 existing data. Then it would be easy to implement snapshots in a
963 similar way.
965 This would not allow arbitrary changes to the database, such as
966 tdb_repack does, and would require more space (since we have to
967 preserve the current and future entries at once). If we used hash
968 trees rather than one big hash table, we might only have to
969 rewrite some sections of the hash, too.
971 We could then implement snapshots using a similar method, using
972 multiple different hash tables/free tables.
974 3.10 Transactions Cannot Operate in Parallel
976 This would be useless for ldb, as it hits the index records with
977 just about every update. It would add significant complexity in
978 resolving clashes, and cause the all transaction callers to write
979 their code to loop in the case where the transactions spuriously
980 failed.
982 3.10.1 Proposed Solution
984 We could solve a small part of the problem by providing read-only
985 transactions. These would allow one write transaction to begin,
986 but it could not commit until all r/o transactions are done. This
987 would require a new RO_TRANSACTION_LOCK, which would be upgraded
988 on commit.
990 3.11 Default Hash Function Is Suboptimal
992 The Knuth-inspired multiplicative hash used by tdb is fairly slow
993 (especially if we expand it to 64 bits), and works best when the
994 hash bucket size is a prime number (which also means a slow
995 modulus). In addition, it is highly predictable which could
996 potentially lead to a Denial of Service attack in some TDB uses.
998 3.11.1 Proposed Solution
1000 The Jenkins lookup3 hash[footnote:
1001 http://burtleburtle.net/bob/c/lookup3.c
1002 ] is a fast and superbly-mixing hash. It's used by the Linux
1003 kernel and almost everything else. This has the particular
1004 properties that it takes an initial seed, and produces two 32 bit
1005 hash numbers, which we can combine into a 64-bit hash.
1007 The seed should be created at tdb-creation time from some random
1008 source, and placed in the header. This is far from foolproof, but
1009 adds a little bit of protection against hash bombing.
1011 3.12 <Reliable-Traversal-Adds>Reliable Traversal Adds Complexity
1013 We lock a record during traversal iteration, and try to grab that
1014 lock in the delete code. If that grab on delete fails, we simply
1015 mark it deleted and continue onwards; traversal checks for this
1016 condition and does the delete when it moves off the record.
1018 If traversal terminates, the dead record may be left
1019 indefinitely.
1021 3.12.1 Proposed Solution
1023 Remove reliability guarantees; see [traverse-Proposed-Solution].
1025 3.13 Fcntl Locking Adds Overhead
1027 Placing a fcntl lock means a system call, as does removing one.
1028 This is actually one reason why transactions can be faster
1029 (everything is locked once at transaction start). In the
1030 uncontended case, this overhead can theoretically be eliminated.
1032 3.13.1 Proposed Solution
1034 None.
1036 We tried this before with spinlock support, in the early days of
1037 TDB, and it didn't make much difference except in manufactured
1038 benchmarks.
1040 We could use spinlocks (with futex kernel support under Linux),
1041 but it means that we lose automatic cleanup when a process dies
1042 with a lock. There is a method of auto-cleanup under Linux, but
1043 it's not supported by other operating systems. We could
1044 reintroduce a clear-if-first-style lock and sweep for dead
1045 futexes on open, but that wouldn't help the normal case of one
1046 concurrent opener dying. Increasingly elaborate repair schemes
1047 could be considered, but they require an ABI change (everyone
1048 must use them) anyway, so there's no need to do this at the same
1049 time as everything else.