]> git.ozlabs.org Git - ccan/blob - ccan/tdb2/doc/design.txt
tdb2: update design doc.
[ccan] / ccan / tdb2 / doc / design.txt
1 TDB2: A Redesigning The Trivial DataBase
2
3 Rusty Russell, IBM Corporation
4
5 14-September-2010
6
7 Abstract
8
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.
13
14 1 Introduction
15
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.
24
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:
32
33
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 +-----------+----------------+--------------------------------+
60
61
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.
67
68 2 API Issues
69
70 2.1 tdb_open_ex Is Not Expandable
71
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.
76
77 2.1.1 Proposed Solution<attributes>
78
79 tdb_open() will take a linked-list of attributes:
80
81 enum tdb_attribute {
82
83     TDB_ATTRIBUTE_LOG = 0,
84
85     TDB_ATTRIBUTE_HASH = 1
86
87 };
88
89 struct tdb_attribute_base {
90
91     enum tdb_attribute attr;
92
93     union tdb_attribute *next;
94
95 };
96
97 struct tdb_attribute_log {
98
99     struct tdb_attribute_base base; /* .attr = TDB_ATTRIBUTE_LOG 
100 */
101
102     tdb_log_func log_fn;
103
104     void *log_private;
105
106 };
107
108 struct tdb_attribute_hash {
109
110     struct tdb_attribute_base base; /* .attr = TDB_ATTRIBUTE_HASH 
111 */
112
113     tdb_hash_func hash_fn;
114
115     void *hash_private;
116
117 };
118
119 union tdb_attribute {
120
121     struct tdb_attribute_base base;
122
123     struct tdb_attribute_log log;
124
125     struct tdb_attribute_hash hash;
126
127 };
128
129 This allows future attributes to be added, even if this expands 
130 the size of the union.
131
132 2.2 tdb_traverse Makes Impossible Guarantees
133
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.
138
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).
143
144 2.2.1 <traverse-Proposed-Solution>Proposed Solution
145
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.
150
151 2.3 Nesting of Transactions Is Fraught
152
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:
158
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.
163
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.
169
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.
173
174 2.3.1 Proposed Solution
175
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.
184
185 2.4 Incorrect Hash Function is Not Detected
186
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().
191
192 2.4.1 Proposed Solution
193
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.
197
198 2.5 tdb_set_max_dead/TDB_VOLATILE Expose Implementation
199
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”.
204
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.
210
211 2.5.1 Proposed Solution
212
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.
218
219 2.6 <TDB-Files-Cannot>TDB Files Cannot Be Opened Multiple Times 
220   In The Same Process
221
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!
228
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.
232
233 2.6.1 Proposed Solution
234
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.
239
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).
248
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.
253
254 2.7 TDB API Is Not POSIX Thread-safe
255
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]
261 ).
262
263 2.7.1 Proposed Solution
264
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.
269
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).
273
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.
277
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.
283
284 2.8 *_nonblock Functions And *_mark Functions Expose 
285   Implementation
286
287 CTDB[footnote:
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:
291
292 1. Call the _nonblock variant of an API function (eg. 
293   tdb_lockall_nonblock). If this fails:
294
295 2. Fork a child process, and wait for it to call the normal 
296   variant (eg. tdb_lockall).
297
298 3. If the child succeeds, call the _mark variant to indicate we 
299   already have the locks (eg. tdb_lockall_mark).
300
301 4. Upon completion, tell the child to release the locks (eg. 
302   tdb_unlockall).
303
304 5. Indicate to tdb that it should consider the locks removed (eg. 
305   tdb_unlockall_mark).
306
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. 
314
315 2.8.1 <Proposed-Solution-locking-hook>Proposed Solution
316
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:
320
321 1. Call the normal API function, eg tdb_lockall().
322
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.
327
328 3. Release locks in the unlock callback as normal.
329
330 4. If tdb_lockall() fails, see if we recorded a lock failure; if 
331   so, call the child to repeat the operation.
332
333 5. The child records what locks it obtains, and returns that 
334   information to the parent.
335
336 6. When the child has succeeded, goto 1.
337
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.
342
343 It also keeps the complexity out of the API, and in ctdbd where 
344 it is needed.
345
346 2.9 tdb_chainlock Functions Expose Implementation
347
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.
352
353 It also makes the same guarantee for any other key in the chain, 
354 which is an internal implementation detail and potentially a 
355 cause for deadlock.
356
357 2.9.1 Proposed Solution
358
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.
366
367 2.10 Signal Handling is Not Race-Free
368
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.
373
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.
379
380 2.10.1 Proposed Solution
381
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, 
391 otherwise EAGAIN.
392 ]
393
394 2.11 The API Uses Gratuitous Typedefs, Capitals
395
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.
400
401 Capitalization is usually reserved for compile-time constants and 
402 macros.
403
404   TDB_CONTEXT There is no reason to use this over 'struct 
405   tdb_context'; the definition isn't visible to the API user 
406   anyway.
407
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.
410
411   struct TDB_DATA This would normally be called 'struct 
412   tdb_data'.
413
414   enum TDB_ERROR Similarly, this would normally be enum 
415   tdb_error.
416
417 2.11.1 Proposed Solution
418
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 
422 users.
423
424 2.12 <tdb_log_func-Doesnt-Take>tdb_log_func Doesn't Take The 
425   Private Pointer
426
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.
430
431 2.12.1 Proposed Solution
432
433 It should simply take an extra argument, since we are prepared to 
434 break the API/ABI.
435
436 2.13 Various Callback Functions Are Not Typesafe
437
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.
442
443 If this type changes, the compiler will not produce warnings on 
444 the callers, since it only sees void *.
445
446 2.13.1 Proposed Solution
447
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 
453 their parameter.
454
455 See CCAN's typesafe_cb module at 
456 http://ccan.ozlabs.org/info/typesafe_cb.html
457
458 2.14 TDB_CLEAR_IF_FIRST Must Be Specified On All Opens, 
459   tdb_reopen_all Problematic
460
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).
466
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.
472
473 2.14.1 Proposed Solution
474
475 Remove TDB_CLEAR_IF_FIRST. Other workarounds are possible, but 
476 see [TDB_CLEAR_IF_FIRST-Imposes-Performance].
477
478 2.15 Extending The Header Is Difficult
479
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 
485 not.
486
487 2.15.1 Proposed Solution
488
489 The header should contain a “format variant” value (64-bit). This 
490 is divided into two 32-bit parts:
491
492 1. The lower part reflects the format variant understood by code 
493   accessing the database.
494
495 2. The upper part reflects the format variant you must understand 
496   to write to the database (otherwise you can only open for 
497   reading).
498
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 
502 lowest variant.
503
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.
507
508 2.16 Record Headers Are Not Expandible
509
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.
512
513 2.16.1 Proposed Solution
514
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.
521
522 2.17 TDB Does Not Use Talloc
523
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 
526 conveniently.
527
528 2.17.1 Proposed Solution
529
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).
537
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()).
543
544 3 Performance And Scalability Issues
545
546 3.1 <TDB_CLEAR_IF_FIRST-Imposes-Performance>TDB_CLEAR_IF_FIRST 
547   Imposes Performance Penalty
548
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.
557
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.
565 ]
566
567 3.1.1 Proposed Solution
568
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.
572
573 3.2 TDB Files Have a 4G Limit
574
575 This seems to be becoming an issue (so much for “trivial”!), 
576 particularly for ldb.
577
578 3.2.1 Proposed Solution
579
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 
585 file offsets.
586
587 tdb_open() will automatically detect the old version, and even 
588 create them if TDB_VERSION6 is specified to tdb_open.
589
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.
594
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!)
598
599 3.3 TDB Records Have a 4G Limit
600
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.
604
605 3.3.1 Proposed Solution
606
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]).
612
613 3.4 Hash Size Is Determined At TDB Creation Time
614
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 
620 creation time.
621
622 3.4.1 <sub:Hash-Size-Solution>Proposed Solution
623
624 After comprehensive performance testing on various scalable hash 
625 variants[footnote:
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. 
631
632 1. 
633
634 2. 
635
636 3. 
637
638
639
640
641
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.
646
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 
652 that point.
653
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 
663 invalid.
664
665 3.5 <TDB-Freelist-Is>TDB Freelist Is Highly Contended
666
667 TDB uses a single linked list for the free list. Allocation 
668 occurs as follows, using heuristics which have evolved over time:
669
670 1. Get the free list lock for this whole operation.
671
672 2. Multiply length by 1.25, so we always over-allocate by 25%.
673
674 3. Set the slack multiplier to 1.
675
676 4. Examine the current freelist entry: if it is > length but < 
677   the current best case, remember it as the best case.
678
679 5. Multiply the slack multiplier by 1.05.
680
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 
683   it's large enough.
684
685 7. Otherwise, go onto the next freelist entry.
686
687 Deleting a record occurs as follows:
688
689 1. Lock the hash chain for this whole operation.
690
691 2. Walk the chain to find the record, keeping the prev pointer 
692   offset.
693
694 3. If max_dead is non-zero:
695
696   (a) Walk the hash chain again and count the dead records.
697
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 
700     once).
701
702   (c) Simply mark this record as dead and return. 
703
704 4. Get the free list lock for the remainder of this operation.
705
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).
710
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 
714   return.
715
716 7. Otherwise, prepend ourselves to the free list.
717
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 
722 tdb.
723
724 The single list lock limits our allocation rate; due to the other 
725 issues this is not currently seen as a bottleneck.
726
727 3.5.1 Proposed Solution
728
729 The first step is to remove all the current heuristics, as they 
730 obviously interact, then examine them once the lock contention is 
731 addressed.
732
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.
739
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.
746
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 
753 ordering.
754
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.
764
765 The basic algorithm is as follows. Freeing is simple:
766
767 1. Identify the correct zone.
768
769 2. Lock the corresponding list.
770
771 3. Re-check the zone (we didn't have a lock, sizes could have 
772   changed): relock if necessary.
773
774 4. Place the freed entry in the list for that zone.
775
776 Allocation is a little more complicated, as we perform delayed 
777 coalescing at this point:
778
779 1. Pick a zone either the zone we last freed into, or based on a “
780   random” number.
781
782 2. Lock the corresponding list.
783
784 3. Re-check the zone: relock if necessary.
785
786 4. If the top entry is -large enough, remove it from the list and 
787   return it.
788
789 5. Otherwise, coalesce entries in the list.If there was no entry 
790   large enough, unlock the list and try the next zone.
791
792 6. If no zone satisfies, expand the file.
793
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]. 
800
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.
804
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.
818 ]
819
820 3.6 <sub:TDB-Becomes-Fragmented>TDB Becomes Fragmented
821
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.
829
830 3.6.1 Proposed Solution
831
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.
837
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.
843
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 
848 it seems likely).
849
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.
854
855 3.7 <sub:Records-Incur-A>Records Incur A 28-Byte Overhead
856
857 Each TDB record has a header as follows:
858
859 struct tdb_record {
860
861         tdb_off_t next; /* offset of the next record in the list 
862 */
863
864         tdb_len_t rec_len; /* total byte length of record */
865
866         tdb_len_t key_len; /* byte length of key */
867
868         tdb_len_t data_len; /* byte length of data */
869
870         uint32_t full_hash; /* the full 32 bit hash of the key */
871
872         uint32_t magic;   /* try to catch errors */
873
874         /* the following union is implied:
875
876                 union {
877
878                         char record[rec_len];
879
880                         struct {
881
882                                 char key[key_len];
883
884                                 char data[data_len];
885
886                         }
887
888                         uint32_t totalsize; (tailer)
889
890                 }
891
892         */
893
894 };
895
896 Naively, this would double to a 56-byte overhead on a 64 bit 
897 implementation.
898
899 3.7.1 Proposed Solution
900
901 We can use various techniques to reduce this for an allocated 
902 block:
903
904 1. The 'next' pointer is not required, as we are using a flat 
905   hash table.
906
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 
911   bits).
912
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 
918   bits.
919
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]).
927
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.
932
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 
937   blocks).[footnote:
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, 
941   however.
942
943 This produces a 16 byte used header like this:
944
945 struct tdb_used_record {
946
947         uint32_t magic : 16,
948
949                  prev_is_free: 1,
950
951                  key_data_divide: 5,
952
953                  top_hash: 10;
954
955         uint32_t extra_octets;
956
957         uint64_t key_and_data_len;
958
959 };
960
961 And a free record like this:
962
963 struct tdb_free_record {
964
965         uint32_t free_magic;
966
967         uint64_t total_length;
968
969         uint64_t prev, next;
970
971         ...
972
973         uint64_t tailer;
974
975 };
976
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].
980
981 3.8 Transaction Commit Requires 4 fdatasync
982
983 The current transaction algorithm is:
984
985 1. write_recovery_data();
986
987 2. sync();
988
989 3. write_recovery_header();
990
991 4. sync();
992
993 5. overwrite_with_new_data();
994
995 6. sync();
996
997 7. remove_recovery_header();
998
999 8. sync(); 
1000
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.
1004
1005 3.8.1 Proposed Solution
1006
1007 Neil Brown points out that this is overzealous, and only one sync 
1008 is needed:
1009
1010 1. Bundle the recovery data, a transaction counter and a strong 
1011   checksum of the new data.
1012
1013 2. Strong checksum that whole bundle.
1014
1015 3. Store the bundle in the database.
1016
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.
1020
1021 5. sync.
1022
1023 6. Write the new data to the file.
1024
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.
1031
1032 3.9 <sub:TDB-Does-Not>TDB Does Not Have Snapshot Support
1033
1034 3.9.1 Proposed Solution
1035
1036 None. At some point you say “use a real database”  (but see [replay-attribute]
1037 ).
1038
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 
1045 similar way.
1046
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.
1052
1053 We could then implement snapshots using a similar method, using 
1054 multiple different hash tables/free tables.
1055
1056 3.10 Transactions Cannot Operate in Parallel
1057
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 
1062 failed.
1063
1064 3.10.1 Proposed Solution
1065
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.
1071
1072 3.11 Default Hash Function Is Suboptimal
1073
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.
1079
1080 3.11.1 Proposed Solution
1081
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.
1088
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.
1092
1093 3.12 <Reliable-Traversal-Adds>Reliable Traversal Adds Complexity
1094
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.
1099
1100 If traversal terminates, the dead record may be left 
1101 indefinitely.
1102
1103 3.12.1 Proposed Solution
1104
1105 Remove reliability guarantees; see [traverse-Proposed-Solution].
1106
1107 3.13 Fcntl Locking Adds Overhead
1108
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.
1113
1114 3.13.1 Proposed Solution
1115
1116 None.
1117
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 
1120 benchmarks.
1121
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.
1132
1133 3.14 Some Transactions Don't Require Durability
1134
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.
1139
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.
1143
1144 3.14.1 Proposed Solution
1145
1146 None.
1147
1148 Unfortunately any transaction scheme which overwrites old data 
1149 requires a sync before that overwrite to avoid the possibility of 
1150 corruption.
1151
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.
1158
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 
1163 invalid checksum.
1164
1165 3.15 Tracing Is Fragile, Replay Is External
1166
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.
1171
1172 3.15.1 Proposed Solution<replay-attribute>
1173
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.
1178