]> git.ozlabs.org Git - ccan/blob - ccan/tdb2/doc/design.txt
tdb2: document problems with moving or enlarging hash table.
[ccan] / ccan / tdb2 / doc / design.txt
1 TDB2: A Redesigning The Trivial DataBase
2
3 Rusty Russell, IBM Corporation
4
5 1-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.
281
282 2.8 *_nonblock Functions And *_mark Functions Expose 
283   Implementation
284
285 CTDB[footnote:
286 Clustered TDB, see http://ctdb.samba.org
287 ] wishes to operate on TDB in a non-blocking manner. This is 
288 currently done as follows:
289
290 1. Call the _nonblock variant of an API function (eg. 
291   tdb_lockall_nonblock). If this fails:
292
293 2. Fork a child process, and wait for it to call the normal 
294   variant (eg. tdb_lockall).
295
296 3. If the child succeeds, call the _mark variant to indicate we 
297   already have the locks (eg. tdb_lockall_mark).
298
299 4. Upon completion, tell the child to release the locks (eg. 
300   tdb_unlockall).
301
302 5. Indicate to tdb that it should consider the locks removed (eg. 
303   tdb_unlockall_mark).
304
305 There are several issues with this approach. Firstly, adding two 
306 new variants of each function clutters the API for an obscure 
307 use, and so not all functions have three variants. Secondly, it 
308 assumes that all paths of the functions ask for the same locks, 
309 otherwise the parent process will have to get a lock which the 
310 child doesn't have under some circumstances. I don't believe this 
311 is currently the case, but it constrains the implementation. 
312
313 2.8.1 <Proposed-Solution-locking-hook>Proposed Solution
314
315 Implement a hook for locking methods, so that the caller can 
316 control the calls to create and remove fcntl locks. In this 
317 scenario, ctdbd would operate as follows:
318
319 1. Call the normal API function, eg tdb_lockall().
320
321 2. When the lock callback comes in, check if the child has the 
322   lock. Initially, this is always false. If so, return 0. 
323   Otherwise, try to obtain it in non-blocking mode. If that 
324   fails, return EWOULDBLOCK.
325
326 3. Release locks in the unlock callback as normal.
327
328 4. If tdb_lockall() fails, see if we recorded a lock failure; if 
329   so, call the child to repeat the operation.
330
331 5. The child records what locks it obtains, and returns that 
332   information to the parent.
333
334 6. When the child has succeeded, goto 1.
335
336 This is flexible enough to handle any potential locking scenario, 
337 even when lock requirements change. It can be optimized so that 
338 the parent does not release locks, just tells the child which 
339 locks it doesn't need to obtain.
340
341 It also keeps the complexity out of the API, and in ctdbd where 
342 it is needed.
343
344 2.9 tdb_chainlock Functions Expose Implementation
345
346 tdb_chainlock locks some number of records, including the record 
347 indicated by the given key. This gave atomicity guarantees; 
348 no-one can start a transaction, alter, read or delete that key 
349 while the lock is held.
350
351 It also makes the same guarantee for any other key in the chain, 
352 which is an internal implementation detail and potentially a 
353 cause for deadlock.
354
355 2.9.1 Proposed Solution
356
357 None. It would be nice to have an explicit single entry lock 
358 which effected no other keys. Unfortunately, this won't work for 
359 an entry which doesn't exist. Thus while chainlock may be 
360 implemented more efficiently for the existing case, it will still 
361 have overlap issues with the non-existing case. So it is best to 
362 keep the current (lack of) guarantee about which records will be 
363 effected to avoid constraining our implementation.
364
365 2.10 Signal Handling is Not Race-Free
366
367 The tdb_setalarm_sigptr() call allows the caller's signal handler 
368 to indicate that the tdb locking code should return with a 
369 failure, rather than trying again when a signal is received (and 
370 errno == EAGAIN). This is usually used to implement timeouts.
371
372 Unfortunately, this does not work in the case where the signal is 
373 received before the tdb code enters the fcntl() call to place the 
374 lock: the code will sleep within the fcntl() code, unaware that 
375 the signal wants it to exit. In the case of long timeouts, this 
376 does not happen in practice.
377
378 2.10.1 Proposed Solution
379
380 The locking hooks proposed in[Proposed-Solution-locking-hook] 
381 would allow the user to decide on whether to fail the lock 
382 acquisition on a signal. This allows the caller to choose their 
383 own compromise: they could narrow the race by checking 
384 immediately before the fcntl call.[footnote:
385 It may be possible to make this race-free in some implementations 
386 by having the signal handler alter the struct flock to make it 
387 invalid. This will cause the fcntl() lock call to fail with 
388 EINVAL if the signal occurs before the kernel is entered, 
389 otherwise EAGAIN.
390 ]
391
392 2.11 The API Uses Gratuitous Typedefs, Capitals
393
394 typedefs are useful for providing source compatibility when types 
395 can differ across implementations, or arguably in the case of 
396 function pointer definitions which are hard for humans to parse. 
397 Otherwise it is simply obfuscation and pollutes the namespace.
398
399 Capitalization is usually reserved for compile-time constants and 
400 macros.
401
402   TDB_CONTEXT There is no reason to use this over 'struct 
403   tdb_context'; the definition isn't visible to the API user 
404   anyway.
405
406   TDB_DATA There is no reason to use this over struct TDB_DATA; 
407   the struct needs to be understood by the API user.
408
409   struct TDB_DATA This would normally be called 'struct 
410   tdb_data'.
411
412   enum TDB_ERROR Similarly, this would normally be enum 
413   tdb_error.
414
415 2.11.1 Proposed Solution
416
417 None. Introducing lower case variants would please pedants like 
418 myself, but if it were done the existing ones should be kept. 
419 There is little point forcing a purely cosmetic change upon tdb 
420 users.
421
422 2.12 <tdb_log_func-Doesnt-Take>tdb_log_func Doesn't Take The 
423   Private Pointer
424
425 For API compatibility reasons, the logging function needs to call 
426 tdb_get_logging_private() to retrieve the pointer registered by 
427 the tdb_open_ex for logging.
428
429 2.12.1 Proposed Solution
430
431 It should simply take an extra argument, since we are prepared to 
432 break the API/ABI.
433
434 2.13 Various Callback Functions Are Not Typesafe
435
436 The callback functions in tdb_set_logging_function (after [tdb_log_func-Doesnt-Take]
437  is resolved), tdb_parse_record, tdb_traverse, tdb_traverse_read 
438 and tdb_check all take void * and must internally convert it to 
439 the argument type they were expecting.
440
441 If this type changes, the compiler will not produce warnings on 
442 the callers, since it only sees void *.
443
444 2.13.1 Proposed Solution
445
446 With careful use of macros, we can create callback functions 
447 which give a warning when used on gcc and the types of the 
448 callback and its private argument differ. Unsupported compilers 
449 will not give a warning, which is no worse than now. In addition, 
450 the callbacks become clearer, as they need not use void * for 
451 their parameter.
452
453 See CCAN's typesafe_cb module at 
454 http://ccan.ozlabs.org/info/typesafe_cb.html
455
456 2.14 TDB_CLEAR_IF_FIRST Must Be Specified On All Opens, 
457   tdb_reopen_all Problematic
458
459 The TDB_CLEAR_IF_FIRST flag to tdb_open indicates that the TDB 
460 file should be cleared if the caller discovers it is the only 
461 process with the TDB open. However, if any caller does not 
462 specify TDB_CLEAR_IF_FIRST it will not be detected, so will have 
463 the TDB erased underneath them (usually resulting in a crash).
464
465 There is a similar issue on fork(); if the parent exits (or 
466 otherwise closes the tdb) before the child calls tdb_reopen_all() 
467 to establish the lock used to indicate the TDB is opened by 
468 someone, a TDB_CLEAR_IF_FIRST opener at that moment will believe 
469 it alone has opened the TDB and will erase it.
470
471 2.14.1 Proposed Solution
472
473 Remove TDB_CLEAR_IF_FIRST. Other workarounds are possible, but 
474 see [TDB_CLEAR_IF_FIRST-Imposes-Performance].
475
476 3 Performance And Scalability Issues
477
478 3.1 <TDB_CLEAR_IF_FIRST-Imposes-Performance>TDB_CLEAR_IF_FIRST 
479   Imposes Performance Penalty
480
481 When TDB_CLEAR_IF_FIRST is specified, a 1-byte read lock is 
482 placed at offset 4 (aka. the ACTIVE_LOCK). While these locks 
483 never conflict in normal tdb usage, they do add substantial 
484 overhead for most fcntl lock implementations when the kernel 
485 scans to detect if a lock conflict exists. This is often a single 
486 linked list, making the time to acquire and release a fcntl lock 
487 O(N) where N is the number of processes with the TDB open, not 
488 the number actually doing work.
489
490 In a Samba server it is common to have huge numbers of clients 
491 sitting idle, and thus they have weaned themselves off the 
492 TDB_CLEAR_IF_FIRST flag.[footnote:
493 There is a flag to tdb_reopen_all() which is used for this 
494 optimization: if the parent process will outlive the child, the 
495 child does not need the ACTIVE_LOCK. This is a workaround for 
496 this very performance issue.
497 ]
498
499 3.1.1 Proposed Solution
500
501 Remove the flag. It was a neat idea, but even trivial servers 
502 tend to know when they are initializing for the first time and 
503 can simply unlink the old tdb at that point.
504
505 3.2 TDB Files Have a 4G Limit
506
507 This seems to be becoming an issue (so much for “trivial”!), 
508 particularly for ldb.
509
510 3.2.1 Proposed Solution
511
512 A new, incompatible TDB format which uses 64 bit offsets 
513 internally rather than 32 bit as now. For simplicity of endian 
514 conversion (which TDB does on the fly if required), all values 
515 will be 64 bit on disk. In practice, some upper bits may be used 
516 for other purposes, but at least 56 bits will be available for 
517 file offsets.
518
519 tdb_open() will automatically detect the old version, and even 
520 create them if TDB_VERSION6 is specified to tdb_open.
521
522 32 bit processes will still be able to access TDBs larger than 4G 
523 (assuming that their off_t allows them to seek to 64 bits), they 
524 will gracefully fall back as they fail to mmap. This can happen 
525 already with large TDBs.
526
527 Old versions of tdb will fail to open the new TDB files (since 28 
528 August 2009, commit 398d0c29290: prior to that any unrecognized 
529 file format would be erased and initialized as a fresh tdb!)
530
531 3.3 TDB Records Have a 4G Limit
532
533 This has not been a reported problem, and the API uses size_t 
534 which can be 64 bit on 64 bit platforms. However, other limits 
535 may have made such an issue moot.
536
537 3.3.1 Proposed Solution
538
539 Record sizes will be 64 bit, with an error returned on 32 bit 
540 platforms which try to access such records (the current 
541 implementation would return TDB_ERR_OOM in a similar case). It 
542 seems unlikely that 32 bit keys will be a limitation, so the 
543 implementation may not support this (see [sub:Records-Incur-A]).
544
545 3.4 Hash Size Is Determined At TDB Creation Time
546
547 TDB contains a number of hash chains in the header; the number is 
548 specified at creation time, and defaults to 131. This is such a 
549 bottleneck on large databases (as each hash chain gets quite 
550 long), that LDB uses 10,000 for this hash. In general it is 
551 impossible to know what the 'right' answer is at database 
552 creation time.
553
554 3.4.1 <sub:Hash-Size-Solution>Proposed Solution
555
556 After comprehensive performance testing on various scalable hash 
557 variants[footnote:
558 http://rusty.ozlabs.org/?p=89 and http://rusty.ozlabs.org/?p=94 
559 This was annoying because I was previously convinced that an 
560 expanding tree of hashes would be very close to optimal.
561 ], it became clear that it is hard to beat a straight linear hash 
562 table which doubles in size when it reaches saturation. 
563
564 1. 
565
566 2. 
567
568 3. 
569
570
571
572
573
574  Unfortunately, altering the hash table introduces serious 
575 locking complications: the entire hash table needs to be locked 
576 to enlarge the hash table, and others might be holding locks. 
577 Particularly insidious are insertions done under tdb_chainlock.
578
579 Thus an expanding layered hash will be used: an array of hash 
580 groups, with each hash group exploding into pointers to lower 
581 hash groups once it fills, turning into a hash tree. This has 
582 implications for locking: we must lock the entire group in case 
583 we need to expand it, yet we don't know how deep the tree is at 
584 that point.
585
586 Note that bits from the hash table entries should be stolen to 
587 hold more hash bits to reduce the penalty of collisions. We can 
588 use the otherwise-unused lower 3 bits. If we limit the size of 
589 the database to 64 exabytes, we can use the top 8 bits of the 
590 hash entry as well. These 11 bits would reduce false positives 
591 down to 1 in 2000 which is more than we need: we can use one of 
592 the bits to indicate that the extra hash bits are valid. This 
593 means we can choose not to re-hash all entries when we expand a 
594 hash group; simply use the next bits we need and mark them 
595 invalid.
596
597 3.5 <TDB-Freelist-Is>TDB Freelist Is Highly Contended
598
599 TDB uses a single linked list for the free list. Allocation 
600 occurs as follows, using heuristics which have evolved over time:
601
602 1. Get the free list lock for this whole operation.
603
604 2. Multiply length by 1.25, so we always over-allocate by 25%.
605
606 3. Set the slack multiplier to 1.
607
608 4. Examine the current freelist entry: if it is > length but < 
609   the current best case, remember it as the best case.
610
611 5. Multiply the slack multiplier by 1.05.
612
613 6. If our best fit so far is less than length * slack multiplier, 
614   return it. The slack will be turned into a new free record if 
615   it's large enough.
616
617 7. Otherwise, go onto the next freelist entry.
618
619 Deleting a record occurs as follows:
620
621 1. Lock the hash chain for this whole operation.
622
623 2. Walk the chain to find the record, keeping the prev pointer 
624   offset.
625
626 3. If max_dead is non-zero:
627
628   (a) Walk the hash chain again and count the dead records.
629
630   (b) If it's more than max_dead, bulk free all the dead ones 
631     (similar to steps 4 and below, but the lock is only obtained 
632     once).
633
634   (c) Simply mark this record as dead and return. 
635
636 4. Get the free list lock for the remainder of this operation.
637
638 5. <right-merging>Examine the following block to see if it is 
639   free; if so, enlarge the current block and remove that block 
640   from the free list. This was disabled, as removal from the free 
641   list was O(entries-in-free-list).
642
643 6. Examine the preceeding block to see if it is free: for this 
644   reason, each block has a 32-bit tailer which indicates its 
645   length. If it is free, expand it to cover our new block and 
646   return.
647
648 7. Otherwise, prepend ourselves to the free list.
649
650 Disabling right-merging (step [right-merging]) causes 
651 fragmentation; the other heuristics proved insufficient to 
652 address this, so the final answer to this was that when we expand 
653 the TDB file inside a transaction commit, we repack the entire 
654 tdb.
655
656 The single list lock limits our allocation rate; due to the other 
657 issues this is not currently seen as a bottleneck.
658
659 3.5.1 Proposed Solution
660
661 The first step is to remove all the current heuristics, as they 
662 obviously interact, then examine them once the lock contention is 
663 addressed.
664
665 The free list must be split to reduce contention. Assuming 
666 perfect free merging, we can at most have 1 free list entry for 
667 each entry. This implies that the number of free lists is related 
668 to the size of the hash table, but as it is rare to walk a large 
669 number of free list entries we can use far fewer, say 1/32 of the 
670 number of hash buckets.
671
672 It seems tempting to try to reuse the hash implementation which 
673 we use for records here, but we have two ways of searching for 
674 free entries: for allocation we search by size (and possibly 
675 zone) which produces too many clashes for our hash table to 
676 handle well, and for coalescing we search by address. Thus an 
677 array of doubly-linked free lists seems preferable.
678
679 There are various benefits in using per-size free lists (see [sub:TDB-Becomes-Fragmented]
680 ) but it's not clear this would reduce contention in the common 
681 case where all processes are allocating/freeing the same size. 
682 Thus we almost certainly need to divide in other ways: the most 
683 obvious is to divide the file into zones, and using a free list 
684 (or set of free lists) for each. This approximates address 
685 ordering.
686
687 Note that this means we need to split the free lists when we 
688 expand the file; this is probably acceptable when we double the 
689 hash table size, since that is such an expensive operation 
690 already. In the case of increasing the file size, there is an 
691 optimization we can use: if we use M in the formula above as the 
692 file size rounded up to the next power of 2, we only need 
693 reshuffle free lists when the file size crosses a power of 2 
694 boundary, and reshuffling the free lists is trivial: we simply 
695 merge every consecutive pair of free lists.
696
697 The basic algorithm is as follows. Freeing is simple:
698
699 1. Identify the correct zone.
700
701 2. Lock the corresponding list.
702
703 3. Re-check the zone (we didn't have a lock, sizes could have 
704   changed): relock if necessary.
705
706 4. Place the freed entry in the list for that zone.
707
708 Allocation is a little more complicated, as we perform delayed 
709 coalescing at this point:
710
711 1. Pick a zone either the zone we last freed into, or based on a “
712   random” number.
713
714 2. Lock the corresponding list.
715
716 3. Re-check the zone: relock if necessary.
717
718 4. If the top entry is -large enough, remove it from the list and 
719   return it.
720
721 5. Otherwise, coalesce entries in the list.If there was no entry 
722   large enough, unlock the list and try the next zone.
723
724 6. If no zone satisfies, expand the file.
725
726 This optimizes rapid insert/delete of free list entries by not 
727 coalescing them all the time.. First-fit address ordering 
728 ordering seems to be fairly good for keeping fragmentation low 
729 (see [sub:TDB-Becomes-Fragmented]). Note that address ordering 
730 does not need a tailer to coalesce, though if we needed one we 
731 could have one cheaply: see [sub:Records-Incur-A]. 
732
733 I anticipate that the number of entries in each free zone would 
734 be small, but it might be worth using one free entry to hold 
735 pointers to the others for cache efficiency.
736
737 <freelist-in-zone>If we want to avoid locking complexity 
738 (enlarging the free lists when we enlarge the file) we could 
739 place the array of free lists at the beginning of each zone. This 
740 means existing array lists never move, but means that a record 
741 cannot be larger than a zone. That in turn implies that zones 
742 should be variable sized (say, power of 2), which makes the 
743 question “what zone is this record in?” much harder (and “pick a 
744 random zone”, but that's less common). It could be done with as 
745 few as 4 bits from the record header.[footnote:
746 Using 2^{16+N*3}means 0 gives a minimal 65536-byte zone, 15 gives 
747 the maximal 2^{61} byte zone. Zones range in factor of 8 steps.
748 ]
749
750 3.6 <sub:TDB-Becomes-Fragmented>TDB Becomes Fragmented
751
752 Much of this is a result of allocation strategy[footnote:
753 The Memory Fragmentation Problem: Solved? Johnstone & Wilson 1995 
754 ftp://ftp.cs.utexas.edu/pub/garbage/malloc/ismm98.ps
755 ] and deliberate hobbling of coalescing; internal fragmentation 
756 (aka overallocation) is deliberately set at 25%, and external 
757 fragmentation is only cured by the decision to repack the entire 
758 db when a transaction commit needs to enlarge the file.
759
760 3.6.1 Proposed Solution
761
762 The 25% overhead on allocation works in practice for ldb because 
763 indexes tend to expand by one record at a time. This internal 
764 fragmentation can be resolved by having an “expanded” bit in the 
765 header to note entries that have previously expanded, and 
766 allocating more space for them.
767
768 There are is a spectrum of possible solutions for external 
769 fragmentation: one is to use a fragmentation-avoiding allocation 
770 strategy such as best-fit address-order allocator. The other end 
771 of the spectrum would be to use a bump allocator (very fast and 
772 simple) and simply repack the file when we reach the end.
773
774 There are three problems with efficient fragmentation-avoiding 
775 allocators: they are non-trivial, they tend to use a single free 
776 list for each size, and there's no evidence that tdb allocation 
777 patterns will match those recorded for general allocators (though 
778 it seems likely).
779
780 Thus we don't spend too much effort on external fragmentation; we 
781 will be no worse than the current code if we need to repack on 
782 occasion. More effort is spent on reducing freelist contention, 
783 and reducing overhead.
784
785 3.7 <sub:Records-Incur-A>Records Incur A 28-Byte Overhead
786
787 Each TDB record has a header as follows:
788
789 struct tdb_record {
790
791         tdb_off_t next; /* offset of the next record in the list 
792 */
793
794         tdb_len_t rec_len; /* total byte length of record */
795
796         tdb_len_t key_len; /* byte length of key */
797
798         tdb_len_t data_len; /* byte length of data */
799
800         uint32_t full_hash; /* the full 32 bit hash of the key */
801
802         uint32_t magic;   /* try to catch errors */
803
804         /* the following union is implied:
805
806                 union {
807
808                         char record[rec_len];
809
810                         struct {
811
812                                 char key[key_len];
813
814                                 char data[data_len];
815
816                         }
817
818                         uint32_t totalsize; (tailer)
819
820                 }
821
822         */
823
824 };
825
826 Naively, this would double to a 56-byte overhead on a 64 bit 
827 implementation.
828
829 3.7.1 Proposed Solution
830
831 We can use various techniques to reduce this for an allocated 
832 block:
833
834 1. The 'next' pointer is not required, as we are using a flat 
835   hash table.
836
837 2. 'rec_len' can instead be expressed as an addition to key_len 
838   and data_len (it accounts for wasted or overallocated length in 
839   the record). Since the record length is always a multiple of 8, 
840   we can conveniently fit it in 32 bits (representing up to 35 
841   bits).
842
843 3. 'key_len' and 'data_len' can be reduced. I'm unwilling to 
844   restrict 'data_len' to 32 bits, but instead we can combine the 
845   two into one 64-bit field and using a 5 bit value which 
846   indicates at what bit to divide the two. Keys are unlikely to 
847   scale as fast as data, so I'm assuming a maximum key size of 32 
848   bits.
849
850 4. 'full_hash' is used to avoid a memcmp on the “miss” case, but 
851   this is diminishing returns after a handful of bits (at 10 
852   bits, it reduces 99.9% of false memcmp). As an aside, as the 
853   lower bits are already incorporated in the hash table 
854   resolution, the upper bits should be used here. Note that it's 
855   not clear that these bits will be a win, given the extra bits 
856   in the hash table itself (see [sub:Hash-Size-Solution]).
857
858 5. 'magic' does not need to be enlarged: it currently reflects 
859   one of 5 values (used, free, dead, recovery, and 
860   unused_recovery). It is useful for quick sanity checking 
861   however, and should not be eliminated.
862
863 6. 'tailer' is only used to coalesce free blocks (so a block to 
864   the right can find the header to check if this block is free). 
865   This can be replaced by a single 'free' bit in the header of 
866   the following block (and the tailer only exists in free 
867   blocks).[footnote:
868 This technique from Thomas Standish. Data Structure Techniques. 
869 Addison-Wesley, Reading, Massachusetts, 1980.
870 ] The current proposed coalescing algorithm doesn't need this, 
871   however.
872
873 This produces a 16 byte used header like this:
874
875 struct tdb_used_record {
876
877         uint32_t magic : 16,
878
879                  prev_is_free: 1,
880
881                  key_data_divide: 5,
882
883                  top_hash: 10;
884
885         uint32_t extra_octets;
886
887         uint64_t key_and_data_len;
888
889 };
890
891 And a free record like this:
892
893 struct tdb_free_record {
894
895         uint32_t free_magic;
896
897         uint64_t total_length;
898
899         uint64_t prev, next;
900
901         ...
902
903         uint64_t tailer;
904
905 };
906
907 We might want to take some bits from the used record's top_hash 
908 (and the free record which has 32 bits of padding to spare 
909 anyway) if we use variable sized zones. See [freelist-in-zone].
910
911 3.8 Transaction Commit Requires 4 fdatasync
912
913 The current transaction algorithm is:
914
915 1. write_recovery_data();
916
917 2. sync();
918
919 3. write_recovery_header();
920
921 4. sync();
922
923 5. overwrite_with_new_data();
924
925 6. sync();
926
927 7. remove_recovery_header();
928
929 8. sync(); 
930
931 On current ext3, each sync flushes all data to disk, so the next 
932 3 syncs are relatively expensive. But this could become a 
933 performance bottleneck on other filesystems such as ext4.
934
935 3.8.1 Proposed Solution
936
937 Neil Brown points out that this is overzealous, and only one sync 
938 is needed:
939
940 1. Bundle the recovery data, a transaction counter and a strong 
941   checksum of the new data.
942
943 2. Strong checksum that whole bundle.
944
945 3. Store the bundle in the database.
946
947 4. Overwrite the oldest of the two recovery pointers in the 
948   header (identified using the transaction counter) with the 
949   offset of this bundle.
950
951 5. sync.
952
953 6. Write the new data to the file.
954
955 Checking for recovery means identifying the latest bundle with a 
956 valid checksum and using the new data checksum to ensure that it 
957 has been applied. This is more expensive than the current check, 
958 but need only be done at open. For running databases, a separate 
959 header field can be used to indicate a transaction in progress; 
960 we need only check for recovery if this is set.
961
962 3.9 <sub:TDB-Does-Not>TDB Does Not Have Snapshot Support
963
964 3.9.1 Proposed Solution
965
966 None. At some point you say “use a real database”.
967
968 But as a thought experiment, if we implemented transactions to 
969 only overwrite free entries (this is tricky: there must not be a 
970 header in each entry which indicates whether it is free, but use 
971 of presence in metadata elsewhere), and a pointer to the hash 
972 table, we could create an entirely new commit without destroying 
973 existing data. Then it would be easy to implement snapshots in a 
974 similar way.
975
976 This would not allow arbitrary changes to the database, such as 
977 tdb_repack does, and would require more space (since we have to 
978 preserve the current and future entries at once). If we used hash 
979 trees rather than one big hash table, we might only have to 
980 rewrite some sections of the hash, too.
981
982 We could then implement snapshots using a similar method, using 
983 multiple different hash tables/free tables.
984
985 3.10 Transactions Cannot Operate in Parallel
986
987 This would be useless for ldb, as it hits the index records with 
988 just about every update. It would add significant complexity in 
989 resolving clashes, and cause the all transaction callers to write 
990 their code to loop in the case where the transactions spuriously 
991 failed.
992
993 3.10.1 Proposed Solution
994
995 We could solve a small part of the problem by providing read-only 
996 transactions. These would allow one write transaction to begin, 
997 but it could not commit until all r/o transactions are done. This 
998 would require a new RO_TRANSACTION_LOCK, which would be upgraded 
999 on commit.
1000
1001 3.11 Default Hash Function Is Suboptimal
1002
1003 The Knuth-inspired multiplicative hash used by tdb is fairly slow 
1004 (especially if we expand it to 64 bits), and works best when the 
1005 hash bucket size is a prime number (which also means a slow 
1006 modulus). In addition, it is highly predictable which could 
1007 potentially lead to a Denial of Service attack in some TDB uses.
1008
1009 3.11.1 Proposed Solution
1010
1011 The Jenkins lookup3 hash[footnote:
1012 http://burtleburtle.net/bob/c/lookup3.c
1013 ] is a fast and superbly-mixing hash. It's used by the Linux 
1014 kernel and almost everything else. This has the particular 
1015 properties that it takes an initial seed, and produces two 32 bit 
1016 hash numbers, which we can combine into a 64-bit hash.
1017
1018 The seed should be created at tdb-creation time from some random 
1019 source, and placed in the header. This is far from foolproof, but 
1020 adds a little bit of protection against hash bombing.
1021
1022 3.12 <Reliable-Traversal-Adds>Reliable Traversal Adds Complexity
1023
1024 We lock a record during traversal iteration, and try to grab that 
1025 lock in the delete code. If that grab on delete fails, we simply 
1026 mark it deleted and continue onwards; traversal checks for this 
1027 condition and does the delete when it moves off the record.
1028
1029 If traversal terminates, the dead record may be left 
1030 indefinitely.
1031
1032 3.12.1 Proposed Solution
1033
1034 Remove reliability guarantees; see [traverse-Proposed-Solution].
1035
1036 3.13 Fcntl Locking Adds Overhead
1037
1038 Placing a fcntl lock means a system call, as does removing one. 
1039 This is actually one reason why transactions can be faster 
1040 (everything is locked once at transaction start). In the 
1041 uncontended case, this overhead can theoretically be eliminated.
1042
1043 3.13.1 Proposed Solution
1044
1045 None.
1046
1047 We tried this before with spinlock support, in the early days of 
1048 TDB, and it didn't make much difference except in manufactured 
1049 benchmarks.
1050
1051 We could use spinlocks (with futex kernel support under Linux), 
1052 but it means that we lose automatic cleanup when a process dies 
1053 with a lock. There is a method of auto-cleanup under Linux, but 
1054 it's not supported by other operating systems. We could 
1055 reintroduce a clear-if-first-style lock and sweep for dead 
1056 futexes on open, but that wouldn't help the normal case of one 
1057 concurrent opener dying. Increasingly elaborate repair schemes 
1058 could be considered, but they require an ABI change (everyone 
1059 must use them) anyway, so there's no need to do this at the same 
1060 time as everything else.
1061
1062 3.14 Some Transactions Don't Require Durability
1063
1064 Volker points out that gencache uses a CLEAR_IF_FIRST tdb for 
1065 normal (fast) usage, and occasionally empties the results into a 
1066 transactional TDB. This kind of usage prioritizes performance 
1067 over durability: as long as we are consistent, data can be lost.
1068
1069 This would be more neatly implemented inside tdb: a “soft” 
1070 transaction commit (ie. syncless) which meant that data may be 
1071 reverted on a crash.
1072
1073 3.14.1 Proposed Solution
1074
1075 None.
1076
1077 Unfortunately any transaction scheme which overwrites old data 
1078 requires a sync before that overwrite to avoid the possibility of 
1079 corruption.
1080
1081 It seems possible to use a scheme similar to that described in [sub:TDB-Does-Not]
1082 ,where transactions are committed without overwriting existing 
1083 data, and an array of top-level pointers were available in the 
1084 header. If the transaction is “soft” then we would not need a 
1085 sync at all: existing processes would pick up the new hash table 
1086 and free list and work with that.
1087
1088 At some later point, a sync would allow recovery of the old data 
1089 into the free lists (perhaps when the array of top-level pointers 
1090 filled). On crash, tdb_open() would examine the array of top 
1091 levels, and apply the transactions until it encountered an 
1092 invalid checksum.
1093