]> git.ozlabs.org Git - ccan/blob - ccan/tdb2/doc/design.txt
967c0b0970491bd014062f1432c525e3f4df0b32
[ccan] / ccan / tdb2 / doc / design.txt
1 TDB2: A Redesigning The Trivial DataBase
2
3 Rusty Russell, IBM Corporation
4
5 9-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
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 3 Performance And Scalability Issues
523
524 3.1 <TDB_CLEAR_IF_FIRST-Imposes-Performance>TDB_CLEAR_IF_FIRST 
525   Imposes Performance Penalty
526
527 When TDB_CLEAR_IF_FIRST is specified, a 1-byte read lock is 
528 placed at offset 4 (aka. the ACTIVE_LOCK). While these locks 
529 never conflict in normal tdb usage, they do add substantial 
530 overhead for most fcntl lock implementations when the kernel 
531 scans to detect if a lock conflict exists. This is often a single 
532 linked list, making the time to acquire and release a fcntl lock 
533 O(N) where N is the number of processes with the TDB open, not 
534 the number actually doing work.
535
536 In a Samba server it is common to have huge numbers of clients 
537 sitting idle, and thus they have weaned themselves off the 
538 TDB_CLEAR_IF_FIRST flag.[footnote:
539 There is a flag to tdb_reopen_all() which is used for this 
540 optimization: if the parent process will outlive the child, the 
541 child does not need the ACTIVE_LOCK. This is a workaround for 
542 this very performance issue.
543 ]
544
545 3.1.1 Proposed Solution
546
547 Remove the flag. It was a neat idea, but even trivial servers 
548 tend to know when they are initializing for the first time and 
549 can simply unlink the old tdb at that point.
550
551 3.2 TDB Files Have a 4G Limit
552
553 This seems to be becoming an issue (so much for “trivial”!), 
554 particularly for ldb.
555
556 3.2.1 Proposed Solution
557
558 A new, incompatible TDB format which uses 64 bit offsets 
559 internally rather than 32 bit as now. For simplicity of endian 
560 conversion (which TDB does on the fly if required), all values 
561 will be 64 bit on disk. In practice, some upper bits may be used 
562 for other purposes, but at least 56 bits will be available for 
563 file offsets.
564
565 tdb_open() will automatically detect the old version, and even 
566 create them if TDB_VERSION6 is specified to tdb_open.
567
568 32 bit processes will still be able to access TDBs larger than 4G 
569 (assuming that their off_t allows them to seek to 64 bits), they 
570 will gracefully fall back as they fail to mmap. This can happen 
571 already with large TDBs.
572
573 Old versions of tdb will fail to open the new TDB files (since 28 
574 August 2009, commit 398d0c29290: prior to that any unrecognized 
575 file format would be erased and initialized as a fresh tdb!)
576
577 3.3 TDB Records Have a 4G Limit
578
579 This has not been a reported problem, and the API uses size_t 
580 which can be 64 bit on 64 bit platforms. However, other limits 
581 may have made such an issue moot.
582
583 3.3.1 Proposed Solution
584
585 Record sizes will be 64 bit, with an error returned on 32 bit 
586 platforms which try to access such records (the current 
587 implementation would return TDB_ERR_OOM in a similar case). It 
588 seems unlikely that 32 bit keys will be a limitation, so the 
589 implementation may not support this (see [sub:Records-Incur-A]).
590
591 3.4 Hash Size Is Determined At TDB Creation Time
592
593 TDB contains a number of hash chains in the header; the number is 
594 specified at creation time, and defaults to 131. This is such a 
595 bottleneck on large databases (as each hash chain gets quite 
596 long), that LDB uses 10,000 for this hash. In general it is 
597 impossible to know what the 'right' answer is at database 
598 creation time.
599
600 3.4.1 <sub:Hash-Size-Solution>Proposed Solution
601
602 After comprehensive performance testing on various scalable hash 
603 variants[footnote:
604 http://rusty.ozlabs.org/?p=89 and http://rusty.ozlabs.org/?p=94 
605 This was annoying because I was previously convinced that an 
606 expanding tree of hashes would be very close to optimal.
607 ], it became clear that it is hard to beat a straight linear hash 
608 table which doubles in size when it reaches saturation. 
609
610 1. 
611
612 2. 
613
614 3. 
615
616
617
618
619
620  Unfortunately, altering the hash table introduces serious 
621 locking complications: the entire hash table needs to be locked 
622 to enlarge the hash table, and others might be holding locks. 
623 Particularly insidious are insertions done under tdb_chainlock.
624
625 Thus an expanding layered hash will be used: an array of hash 
626 groups, with each hash group exploding into pointers to lower 
627 hash groups once it fills, turning into a hash tree. This has 
628 implications for locking: we must lock the entire group in case 
629 we need to expand it, yet we don't know how deep the tree is at 
630 that point.
631
632 Note that bits from the hash table entries should be stolen to 
633 hold more hash bits to reduce the penalty of collisions. We can 
634 use the otherwise-unused lower 3 bits. If we limit the size of 
635 the database to 64 exabytes, we can use the top 8 bits of the 
636 hash entry as well. These 11 bits would reduce false positives 
637 down to 1 in 2000 which is more than we need: we can use one of 
638 the bits to indicate that the extra hash bits are valid. This 
639 means we can choose not to re-hash all entries when we expand a 
640 hash group; simply use the next bits we need and mark them 
641 invalid.
642
643 3.5 <TDB-Freelist-Is>TDB Freelist Is Highly Contended
644
645 TDB uses a single linked list for the free list. Allocation 
646 occurs as follows, using heuristics which have evolved over time:
647
648 1. Get the free list lock for this whole operation.
649
650 2. Multiply length by 1.25, so we always over-allocate by 25%.
651
652 3. Set the slack multiplier to 1.
653
654 4. Examine the current freelist entry: if it is > length but < 
655   the current best case, remember it as the best case.
656
657 5. Multiply the slack multiplier by 1.05.
658
659 6. If our best fit so far is less than length * slack multiplier, 
660   return it. The slack will be turned into a new free record if 
661   it's large enough.
662
663 7. Otherwise, go onto the next freelist entry.
664
665 Deleting a record occurs as follows:
666
667 1. Lock the hash chain for this whole operation.
668
669 2. Walk the chain to find the record, keeping the prev pointer 
670   offset.
671
672 3. If max_dead is non-zero:
673
674   (a) Walk the hash chain again and count the dead records.
675
676   (b) If it's more than max_dead, bulk free all the dead ones 
677     (similar to steps 4 and below, but the lock is only obtained 
678     once).
679
680   (c) Simply mark this record as dead and return. 
681
682 4. Get the free list lock for the remainder of this operation.
683
684 5. <right-merging>Examine the following block to see if it is 
685   free; if so, enlarge the current block and remove that block 
686   from the free list. This was disabled, as removal from the free 
687   list was O(entries-in-free-list).
688
689 6. Examine the preceeding block to see if it is free: for this 
690   reason, each block has a 32-bit tailer which indicates its 
691   length. If it is free, expand it to cover our new block and 
692   return.
693
694 7. Otherwise, prepend ourselves to the free list.
695
696 Disabling right-merging (step [right-merging]) causes 
697 fragmentation; the other heuristics proved insufficient to 
698 address this, so the final answer to this was that when we expand 
699 the TDB file inside a transaction commit, we repack the entire 
700 tdb.
701
702 The single list lock limits our allocation rate; due to the other 
703 issues this is not currently seen as a bottleneck.
704
705 3.5.1 Proposed Solution
706
707 The first step is to remove all the current heuristics, as they 
708 obviously interact, then examine them once the lock contention is 
709 addressed.
710
711 The free list must be split to reduce contention. Assuming 
712 perfect free merging, we can at most have 1 free list entry for 
713 each entry. This implies that the number of free lists is related 
714 to the size of the hash table, but as it is rare to walk a large 
715 number of free list entries we can use far fewer, say 1/32 of the 
716 number of hash buckets.
717
718 It seems tempting to try to reuse the hash implementation which 
719 we use for records here, but we have two ways of searching for 
720 free entries: for allocation we search by size (and possibly 
721 zone) which produces too many clashes for our hash table to 
722 handle well, and for coalescing we search by address. Thus an 
723 array of doubly-linked free lists seems preferable.
724
725 There are various benefits in using per-size free lists (see [sub:TDB-Becomes-Fragmented]
726 ) but it's not clear this would reduce contention in the common 
727 case where all processes are allocating/freeing the same size. 
728 Thus we almost certainly need to divide in other ways: the most 
729 obvious is to divide the file into zones, and using a free list 
730 (or set of free lists) for each. This approximates address 
731 ordering.
732
733 Note that this means we need to split the free lists when we 
734 expand the file; this is probably acceptable when we double the 
735 hash table size, since that is such an expensive operation 
736 already. In the case of increasing the file size, there is an 
737 optimization we can use: if we use M in the formula above as the 
738 file size rounded up to the next power of 2, we only need 
739 reshuffle free lists when the file size crosses a power of 2 
740 boundary, and reshuffling the free lists is trivial: we simply 
741 merge every consecutive pair of free lists.
742
743 The basic algorithm is as follows. Freeing is simple:
744
745 1. Identify the correct zone.
746
747 2. Lock the corresponding list.
748
749 3. Re-check the zone (we didn't have a lock, sizes could have 
750   changed): relock if necessary.
751
752 4. Place the freed entry in the list for that zone.
753
754 Allocation is a little more complicated, as we perform delayed 
755 coalescing at this point:
756
757 1. Pick a zone either the zone we last freed into, or based on a “
758   random” number.
759
760 2. Lock the corresponding list.
761
762 3. Re-check the zone: relock if necessary.
763
764 4. If the top entry is -large enough, remove it from the list and 
765   return it.
766
767 5. Otherwise, coalesce entries in the list.If there was no entry 
768   large enough, unlock the list and try the next zone.
769
770 6. If no zone satisfies, expand the file.
771
772 This optimizes rapid insert/delete of free list entries by not 
773 coalescing them all the time.. First-fit address ordering 
774 ordering seems to be fairly good for keeping fragmentation low 
775 (see [sub:TDB-Becomes-Fragmented]). Note that address ordering 
776 does not need a tailer to coalesce, though if we needed one we 
777 could have one cheaply: see [sub:Records-Incur-A]. 
778
779 I anticipate that the number of entries in each free zone would 
780 be small, but it might be worth using one free entry to hold 
781 pointers to the others for cache efficiency.
782
783 <freelist-in-zone>If we want to avoid locking complexity 
784 (enlarging the free lists when we enlarge the file) we could 
785 place the array of free lists at the beginning of each zone. This 
786 means existing array lists never move, but means that a record 
787 cannot be larger than a zone. That in turn implies that zones 
788 should be variable sized (say, power of 2), which makes the 
789 question “what zone is this record in?” much harder (and “pick a 
790 random zone”, but that's less common). It could be done with as 
791 few as 4 bits from the record header.[footnote:
792 Using 2^{16+N*3}means 0 gives a minimal 65536-byte zone, 15 gives 
793 the maximal 2^{61} byte zone. Zones range in factor of 8 steps.
794 ]
795
796 3.6 <sub:TDB-Becomes-Fragmented>TDB Becomes Fragmented
797
798 Much of this is a result of allocation strategy[footnote:
799 The Memory Fragmentation Problem: Solved? Johnstone & Wilson 1995 
800 ftp://ftp.cs.utexas.edu/pub/garbage/malloc/ismm98.ps
801 ] and deliberate hobbling of coalescing; internal fragmentation 
802 (aka overallocation) is deliberately set at 25%, and external 
803 fragmentation is only cured by the decision to repack the entire 
804 db when a transaction commit needs to enlarge the file.
805
806 3.6.1 Proposed Solution
807
808 The 25% overhead on allocation works in practice for ldb because 
809 indexes tend to expand by one record at a time. This internal 
810 fragmentation can be resolved by having an “expanded” bit in the 
811 header to note entries that have previously expanded, and 
812 allocating more space for them.
813
814 There are is a spectrum of possible solutions for external 
815 fragmentation: one is to use a fragmentation-avoiding allocation 
816 strategy such as best-fit address-order allocator. The other end 
817 of the spectrum would be to use a bump allocator (very fast and 
818 simple) and simply repack the file when we reach the end.
819
820 There are three problems with efficient fragmentation-avoiding 
821 allocators: they are non-trivial, they tend to use a single free 
822 list for each size, and there's no evidence that tdb allocation 
823 patterns will match those recorded for general allocators (though 
824 it seems likely).
825
826 Thus we don't spend too much effort on external fragmentation; we 
827 will be no worse than the current code if we need to repack on 
828 occasion. More effort is spent on reducing freelist contention, 
829 and reducing overhead.
830
831 3.7 <sub:Records-Incur-A>Records Incur A 28-Byte Overhead
832
833 Each TDB record has a header as follows:
834
835 struct tdb_record {
836
837         tdb_off_t next; /* offset of the next record in the list 
838 */
839
840         tdb_len_t rec_len; /* total byte length of record */
841
842         tdb_len_t key_len; /* byte length of key */
843
844         tdb_len_t data_len; /* byte length of data */
845
846         uint32_t full_hash; /* the full 32 bit hash of the key */
847
848         uint32_t magic;   /* try to catch errors */
849
850         /* the following union is implied:
851
852                 union {
853
854                         char record[rec_len];
855
856                         struct {
857
858                                 char key[key_len];
859
860                                 char data[data_len];
861
862                         }
863
864                         uint32_t totalsize; (tailer)
865
866                 }
867
868         */
869
870 };
871
872 Naively, this would double to a 56-byte overhead on a 64 bit 
873 implementation.
874
875 3.7.1 Proposed Solution
876
877 We can use various techniques to reduce this for an allocated 
878 block:
879
880 1. The 'next' pointer is not required, as we are using a flat 
881   hash table.
882
883 2. 'rec_len' can instead be expressed as an addition to key_len 
884   and data_len (it accounts for wasted or overallocated length in 
885   the record). Since the record length is always a multiple of 8, 
886   we can conveniently fit it in 32 bits (representing up to 35 
887   bits).
888
889 3. 'key_len' and 'data_len' can be reduced. I'm unwilling to 
890   restrict 'data_len' to 32 bits, but instead we can combine the 
891   two into one 64-bit field and using a 5 bit value which 
892   indicates at what bit to divide the two. Keys are unlikely to 
893   scale as fast as data, so I'm assuming a maximum key size of 32 
894   bits.
895
896 4. 'full_hash' is used to avoid a memcmp on the “miss” case, but 
897   this is diminishing returns after a handful of bits (at 10 
898   bits, it reduces 99.9% of false memcmp). As an aside, as the 
899   lower bits are already incorporated in the hash table 
900   resolution, the upper bits should be used here. Note that it's 
901   not clear that these bits will be a win, given the extra bits 
902   in the hash table itself (see [sub:Hash-Size-Solution]).
903
904 5. 'magic' does not need to be enlarged: it currently reflects 
905   one of 5 values (used, free, dead, recovery, and 
906   unused_recovery). It is useful for quick sanity checking 
907   however, and should not be eliminated.
908
909 6. 'tailer' is only used to coalesce free blocks (so a block to 
910   the right can find the header to check if this block is free). 
911   This can be replaced by a single 'free' bit in the header of 
912   the following block (and the tailer only exists in free 
913   blocks).[footnote:
914 This technique from Thomas Standish. Data Structure Techniques. 
915 Addison-Wesley, Reading, Massachusetts, 1980.
916 ] The current proposed coalescing algorithm doesn't need this, 
917   however.
918
919 This produces a 16 byte used header like this:
920
921 struct tdb_used_record {
922
923         uint32_t magic : 16,
924
925                  prev_is_free: 1,
926
927                  key_data_divide: 5,
928
929                  top_hash: 10;
930
931         uint32_t extra_octets;
932
933         uint64_t key_and_data_len;
934
935 };
936
937 And a free record like this:
938
939 struct tdb_free_record {
940
941         uint32_t free_magic;
942
943         uint64_t total_length;
944
945         uint64_t prev, next;
946
947         ...
948
949         uint64_t tailer;
950
951 };
952
953 We might want to take some bits from the used record's top_hash 
954 (and the free record which has 32 bits of padding to spare 
955 anyway) if we use variable sized zones. See [freelist-in-zone].
956
957 3.8 Transaction Commit Requires 4 fdatasync
958
959 The current transaction algorithm is:
960
961 1. write_recovery_data();
962
963 2. sync();
964
965 3. write_recovery_header();
966
967 4. sync();
968
969 5. overwrite_with_new_data();
970
971 6. sync();
972
973 7. remove_recovery_header();
974
975 8. sync(); 
976
977 On current ext3, each sync flushes all data to disk, so the next 
978 3 syncs are relatively expensive. But this could become a 
979 performance bottleneck on other filesystems such as ext4.
980
981 3.8.1 Proposed Solution
982
983 Neil Brown points out that this is overzealous, and only one sync 
984 is needed:
985
986 1. Bundle the recovery data, a transaction counter and a strong 
987   checksum of the new data.
988
989 2. Strong checksum that whole bundle.
990
991 3. Store the bundle in the database.
992
993 4. Overwrite the oldest of the two recovery pointers in the 
994   header (identified using the transaction counter) with the 
995   offset of this bundle.
996
997 5. sync.
998
999 6. Write the new data to the file.
1000
1001 Checking for recovery means identifying the latest bundle with a 
1002 valid checksum and using the new data checksum to ensure that it 
1003 has been applied. This is more expensive than the current check, 
1004 but need only be done at open. For running databases, a separate 
1005 header field can be used to indicate a transaction in progress; 
1006 we need only check for recovery if this is set.
1007
1008 3.9 <sub:TDB-Does-Not>TDB Does Not Have Snapshot Support
1009
1010 3.9.1 Proposed Solution
1011
1012 None. At some point you say “use a real database”.
1013
1014 But as a thought experiment, if we implemented transactions to 
1015 only overwrite free entries (this is tricky: there must not be a 
1016 header in each entry which indicates whether it is free, but use 
1017 of presence in metadata elsewhere), and a pointer to the hash 
1018 table, we could create an entirely new commit without destroying 
1019 existing data. Then it would be easy to implement snapshots in a 
1020 similar way.
1021
1022 This would not allow arbitrary changes to the database, such as 
1023 tdb_repack does, and would require more space (since we have to 
1024 preserve the current and future entries at once). If we used hash 
1025 trees rather than one big hash table, we might only have to 
1026 rewrite some sections of the hash, too.
1027
1028 We could then implement snapshots using a similar method, using 
1029 multiple different hash tables/free tables.
1030
1031 3.10 Transactions Cannot Operate in Parallel
1032
1033 This would be useless for ldb, as it hits the index records with 
1034 just about every update. It would add significant complexity in 
1035 resolving clashes, and cause the all transaction callers to write 
1036 their code to loop in the case where the transactions spuriously 
1037 failed.
1038
1039 3.10.1 Proposed Solution
1040
1041 We could solve a small part of the problem by providing read-only 
1042 transactions. These would allow one write transaction to begin, 
1043 but it could not commit until all r/o transactions are done. This 
1044 would require a new RO_TRANSACTION_LOCK, which would be upgraded 
1045 on commit.
1046
1047 3.11 Default Hash Function Is Suboptimal
1048
1049 The Knuth-inspired multiplicative hash used by tdb is fairly slow 
1050 (especially if we expand it to 64 bits), and works best when the 
1051 hash bucket size is a prime number (which also means a slow 
1052 modulus). In addition, it is highly predictable which could 
1053 potentially lead to a Denial of Service attack in some TDB uses.
1054
1055 3.11.1 Proposed Solution
1056
1057 The Jenkins lookup3 hash[footnote:
1058 http://burtleburtle.net/bob/c/lookup3.c
1059 ] is a fast and superbly-mixing hash. It's used by the Linux 
1060 kernel and almost everything else. This has the particular 
1061 properties that it takes an initial seed, and produces two 32 bit 
1062 hash numbers, which we can combine into a 64-bit hash.
1063
1064 The seed should be created at tdb-creation time from some random 
1065 source, and placed in the header. This is far from foolproof, but 
1066 adds a little bit of protection against hash bombing.
1067
1068 3.12 <Reliable-Traversal-Adds>Reliable Traversal Adds Complexity
1069
1070 We lock a record during traversal iteration, and try to grab that 
1071 lock in the delete code. If that grab on delete fails, we simply 
1072 mark it deleted and continue onwards; traversal checks for this 
1073 condition and does the delete when it moves off the record.
1074
1075 If traversal terminates, the dead record may be left 
1076 indefinitely.
1077
1078 3.12.1 Proposed Solution
1079
1080 Remove reliability guarantees; see [traverse-Proposed-Solution].
1081
1082 3.13 Fcntl Locking Adds Overhead
1083
1084 Placing a fcntl lock means a system call, as does removing one. 
1085 This is actually one reason why transactions can be faster 
1086 (everything is locked once at transaction start). In the 
1087 uncontended case, this overhead can theoretically be eliminated.
1088
1089 3.13.1 Proposed Solution
1090
1091 None.
1092
1093 We tried this before with spinlock support, in the early days of 
1094 TDB, and it didn't make much difference except in manufactured 
1095 benchmarks.
1096
1097 We could use spinlocks (with futex kernel support under Linux), 
1098 but it means that we lose automatic cleanup when a process dies 
1099 with a lock. There is a method of auto-cleanup under Linux, but 
1100 it's not supported by other operating systems. We could 
1101 reintroduce a clear-if-first-style lock and sweep for dead 
1102 futexes on open, but that wouldn't help the normal case of one 
1103 concurrent opener dying. Increasingly elaborate repair schemes 
1104 could be considered, but they require an ABI change (everyone 
1105 must use them) anyway, so there's no need to do this at the same 
1106 time as everything else.
1107
1108 3.14 Some Transactions Don't Require Durability
1109
1110 Volker points out that gencache uses a CLEAR_IF_FIRST tdb for 
1111 normal (fast) usage, and occasionally empties the results into a 
1112 transactional TDB. This kind of usage prioritizes performance 
1113 over durability: as long as we are consistent, data can be lost.
1114
1115 This would be more neatly implemented inside tdb: a “soft” 
1116 transaction commit (ie. syncless) which meant that data may be 
1117 reverted on a crash.
1118
1119 3.14.1 Proposed Solution
1120
1121 None.
1122
1123 Unfortunately any transaction scheme which overwrites old data 
1124 requires a sync before that overwrite to avoid the possibility of 
1125 corruption.
1126
1127 It seems possible to use a scheme similar to that described in [sub:TDB-Does-Not]
1128 ,where transactions are committed without overwriting existing 
1129 data, and an array of top-level pointers were available in the 
1130 header. If the transaction is “soft” then we would not need a 
1131 sync at all: existing processes would pick up the new hash table 
1132 and free list and work with that.
1133
1134 At some later point, a sync would allow recovery of the old data 
1135 into the free lists (perhaps when the array of top-level pointers 
1136 filled). On crash, tdb_open() would examine the array of top 
1137 levels, and apply the transactions until it encountered an 
1138 invalid checksum.
1139