xref: /6.0.3/forestdb/src/forestdb.cc (revision e6c55053)
1/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
2/*
3 *     Copyright 2010 Couchbase, Inc
4 *
5 *   Licensed under the Apache License, Version 2.0 (the "License");
6 *   you may not use this file except in compliance with the License.
7 *   You may obtain a copy of the License at
8 *
9 *       http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *   Unless required by applicable law or agreed to in writing, software
12 *   distributed under the License is distributed on an "AS IS" BASIS,
13 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *   See the License for the specific language governing permissions and
15 *   limitations under the License.
16 */
17
18#include <stdio.h>
19#include <stdlib.h>
20#include <string.h>
21#include <fcntl.h>
22#include <time.h>
23#if !defined(WIN32) && !defined(_WIN32)
24#include <sys/time.h>
25#endif
26
27#include "libforestdb/forestdb.h"
28#include "fdb_internal.h"
29#include "filemgr.h"
30#include "hbtrie.h"
31#include "list.h"
32#include "breakpad.h"
33#include "btree.h"
34#include "btree_kv.h"
35#include "btree_var_kv_ops.h"
36#include "docio.h"
37#include "btreeblock.h"
38#include "common.h"
39#include "wal.h"
40#include "filemgr_ops.h"
41#include "configuration.h"
42#include "internal_types.h"
43#include "bgflusher.h"
44#include "compactor.h"
45#include "memleak.h"
46#include "time_utils.h"
47#include "timing.h"
48#include "system_resource_stats.h"
49#include "version.h"
50#include "staleblock.h"
51
52#ifdef __DEBUG
53#ifndef __DEBUG_FDB
54    #undef DBG
55    #undef DBGCMD
56    #undef DBGSW
57    #define DBG(...)
58    #define DBGCMD(...)
59    #define DBGSW(n, ...)
60#endif
61#endif
62
63
64static atomic_uint8_t fdb_initialized(0);
65static volatile uint32_t fdb_open_inprog = 0;
66#ifdef SPIN_INITIALIZER
67static spin_t initial_lock = SPIN_INITIALIZER;
68#else
69static volatile unsigned int initial_lock_status = 0;
70static spin_t initial_lock;
71#endif
72
73INLINE int _cmp_uint64_t_endian_safe(void *key1, void *key2, void *aux)
74{
75    (void) aux;
76    uint64_t a,b;
77    a = *(uint64_t*)key1;
78    b = *(uint64_t*)key2;
79    a = _endian_decode(a);
80    b = _endian_decode(b);
81    return _CMP_U64(a, b);
82}
83
84size_t _fdb_readkey_wrap(void *handle, uint64_t offset, void *buf)
85{
86    fdb_status fs;
87    keylen_t keylen;
88    struct docio_handle *dhandle = (struct docio_handle*)handle;
89
90    offset = _endian_decode(offset);
91    fs = docio_read_doc_key(dhandle, offset, &keylen, buf);
92    if (fs == FDB_RESULT_SUCCESS) {
93        return keylen;
94    } else {
95        const char *msg = "docio_read_doc_key error: read failure on "
96            "offset %" _F64 " in a database file '%s' "
97            ": FDB status %d, lastbid 0x%" _X64 ", "
98            "curblock 0x%" _X64 ", curpos 0x%x\n";
99        fdb_log(NULL, FDB_RESULT_READ_FAIL, msg, offset,
100                dhandle->file->filename, fs, dhandle->lastbid,
101                dhandle->curblock, dhandle->curpos);
102        dbg_print_buf(dhandle->readbuffer, dhandle->file->blocksize, true, 16);
103        return 0;
104    }
105}
106
107size_t _fdb_readseq_wrap(void *handle, uint64_t offset, void *buf)
108{
109    int size_id, size_seq, size_chunk;
110    fdb_seqnum_t _seqnum;
111    struct docio_object doc;
112    struct docio_handle *dhandle = (struct docio_handle *)handle;
113
114    size_id = sizeof(fdb_kvs_id_t);
115    size_seq = sizeof(fdb_seqnum_t);
116    size_chunk = dhandle->file->config->chunksize;
117    memset(&doc, 0, sizeof(struct docio_object));
118
119    offset = _endian_decode(offset);
120    if (docio_read_doc_key_meta((struct docio_handle *)handle, offset,
121                                &doc, true) <= 0) {
122        return 0;
123    }
124    buf2buf(size_chunk, doc.key, size_id, buf);
125    _seqnum = _endian_encode(doc.seqnum);
126    memcpy((uint8_t*)buf + size_id, &_seqnum, size_seq);
127
128    free(doc.key);
129    free(doc.meta);
130
131    return size_id + size_seq;
132}
133
134int _fdb_custom_cmp_wrap(void *key1, void *key2, void *aux)
135{
136    int is_key1_inf, is_key2_inf;
137    uint8_t *keystr1 = alca(uint8_t, FDB_MAX_KEYLEN_INTERNAL);
138    uint8_t *keystr2 = alca(uint8_t, FDB_MAX_KEYLEN_INTERNAL);
139    size_t keylen1, keylen2;
140    btree_cmp_args *args = (btree_cmp_args *)aux;
141    fdb_custom_cmp_variable cmp = (fdb_custom_cmp_variable)args->aux;
142
143    is_key1_inf = _is_inf_key(key1);
144    is_key2_inf = _is_inf_key(key2);
145    if (is_key1_inf && is_key2_inf) { // both are infinite
146        return 0;
147    } else if (!is_key1_inf && is_key2_inf) { // key2 is infinite
148        return -1;
149    } else if (is_key1_inf && !is_key2_inf) { // key1 is infinite
150        return 1;
151    }
152
153    _get_var_key(key1, (void*)keystr1, &keylen1);
154    _get_var_key(key2, (void*)keystr2, &keylen2);
155
156    if (keylen1 == 0 && keylen2 == 0) {
157        return 0;
158    } else if (keylen1 ==0 && keylen2 > 0) {
159        return -1;
160    } else if (keylen1 > 0 && keylen2 == 0) {
161        return 1;
162    }
163
164    return cmp(keystr1, keylen1, keystr2, keylen2);
165}
166
167void fdb_fetch_header(uint64_t version,
168                      void *header_buf,
169                      bid_t *trie_root_bid,
170                      bid_t *seq_root_bid,
171                      bid_t *stale_root_bid,
172                      uint64_t *ndocs,
173                      uint64_t *ndeletes,
174                      uint64_t *nlivenodes,
175                      uint64_t *datasize,
176                      uint64_t *last_wal_flush_hdr_bid,
177                      uint64_t *kv_info_offset,
178                      uint64_t *header_flags,
179                      char **new_filename,
180                      char **old_filename)
181{
182    size_t offset = 0;
183    uint16_t new_filename_len;
184    uint16_t old_filename_len;
185
186    seq_memcpy(trie_root_bid, (uint8_t *)header_buf + offset,
187               sizeof(bid_t), offset);
188    *trie_root_bid = _endian_decode(*trie_root_bid);
189
190    seq_memcpy(seq_root_bid, (uint8_t *)header_buf + offset,
191               sizeof(bid_t), offset);
192    *seq_root_bid = _endian_decode(*seq_root_bid);
193
194    if (ver_staletree_support(version)) {
195        seq_memcpy(stale_root_bid, (uint8_t *)header_buf + offset,
196                   sizeof(bid_t), offset);
197        *stale_root_bid = _endian_decode(*stale_root_bid);
198    } else {
199        *stale_root_bid = BLK_NOT_FOUND;
200    }
201
202    seq_memcpy(ndocs, (uint8_t *)header_buf + offset,
203               sizeof(uint64_t), offset);
204    *ndocs = _endian_decode(*ndocs);
205    if (ver_is_atleast_magic_001(version)) {
206        seq_memcpy(ndeletes, (uint8_t *)header_buf + offset,
207                   sizeof(uint64_t), offset);
208        *ndeletes = _endian_decode(*ndeletes);
209    } else {
210        *ndeletes = 0;
211    }
212
213    seq_memcpy(nlivenodes, (uint8_t *)header_buf + offset,
214               sizeof(uint64_t), offset);
215    *nlivenodes = _endian_decode(*nlivenodes);
216
217    seq_memcpy(datasize, (uint8_t *)header_buf + offset,
218               sizeof(uint64_t), offset);
219    *datasize = _endian_decode(*datasize);
220
221    seq_memcpy(last_wal_flush_hdr_bid, (uint8_t *)header_buf + offset,
222               sizeof(uint64_t), offset);
223    *last_wal_flush_hdr_bid = _endian_decode(*last_wal_flush_hdr_bid);
224
225    seq_memcpy(kv_info_offset, (uint8_t *)header_buf + offset,
226               sizeof(uint64_t), offset);
227    *kv_info_offset = _endian_decode(*kv_info_offset);
228
229    seq_memcpy(header_flags, (uint8_t *)header_buf + offset,
230               sizeof(uint64_t), offset);
231    *header_flags = _endian_decode(*header_flags);
232
233    seq_memcpy(&new_filename_len, (uint8_t *)header_buf + offset,
234               sizeof(new_filename_len), offset);
235    new_filename_len = _endian_decode(new_filename_len);
236    seq_memcpy(&old_filename_len, (uint8_t *)header_buf + offset,
237               sizeof(old_filename_len), offset);
238    old_filename_len = _endian_decode(old_filename_len);
239    if (new_filename_len) {
240        *new_filename = (char*)((uint8_t *)header_buf + offset);
241    } else {
242        *new_filename = NULL;
243    }
244    offset += new_filename_len;
245    if (old_filename && old_filename_len) {
246        *old_filename = (char *) malloc(old_filename_len);
247        seq_memcpy(*old_filename,
248                   (uint8_t *)header_buf + offset,
249                   old_filename_len, offset);
250    }
251}
252
253// read the revnum of the given header of BID
254INLINE filemgr_header_revnum_t _fdb_get_header_revnum(fdb_kvs_handle *handle, bid_t bid)
255{
256    uint8_t *buf = alca(uint8_t, handle->file->blocksize);
257    uint64_t version;
258    size_t header_len;
259    fdb_seqnum_t seqnum;
260    filemgr_header_revnum_t revnum = 0;
261    fdb_status fs;
262
263    fs = filemgr_fetch_header(handle->file, bid, buf, &header_len,
264                              &seqnum, &revnum, NULL, &version, NULL,
265                              &handle->log_callback);
266    if (fs != FDB_RESULT_SUCCESS) {
267        return 0;
268    }
269    return revnum;
270}
271
272INLINE filemgr_header_revnum_t _fdb_get_bmp_revnum(fdb_kvs_handle *handle, bid_t bid)
273{
274    uint8_t *buf = alca(uint8_t, handle->file->blocksize);
275    uint64_t version, bmp_revnum = 0;
276    size_t header_len;
277    fdb_seqnum_t seqnum;
278    filemgr_header_revnum_t revnum;
279    fdb_status fs;
280
281    fs = filemgr_fetch_header(handle->file, bid, buf, &header_len,
282                              &seqnum, &revnum, NULL, &version, &bmp_revnum,
283                              &handle->log_callback);
284    if (fs != FDB_RESULT_SUCCESS) {
285        return 0;
286    }
287    return bmp_revnum;
288}
289
290void fdb_dummy_log_callback(int err_code, const char *err_msg, void *ctx_data)
291{
292    (void)err_code;
293    (void)err_msg;
294    (void)ctx_data;
295    return;
296}
297
298INLINE void _fdb_restore_wal(fdb_kvs_handle *handle,
299                             fdb_restore_mode_t mode,
300                             bid_t hdr_bid,
301                             fdb_kvs_id_t kv_id_req)
302{
303    struct filemgr *file = handle->file;
304    uint32_t blocksize = handle->file->blocksize;
305    uint64_t last_wal_flush_hdr_bid = handle->last_wal_flush_hdr_bid;
306    uint64_t hdr_off = hdr_bid * FDB_BLOCKSIZE;
307    uint64_t offset = 0; //assume everything from first block needs restoration
308    uint64_t filesize = filemgr_get_pos(handle->file);
309    uint64_t doc_scan_limit;
310    uint64_t start_bmp_revnum, stop_bmp_revnum;
311    uint64_t cur_bmp_revnum = (uint64_t)-1;
312    bid_t next_doc_block = BLK_NOT_FOUND;
313    struct _fdb_key_cmp_info cmp_info;
314    err_log_callback *log_callback;
315
316    if (mode == FDB_RESTORE_NORMAL && !handle->shandle &&
317        !wal_try_restore(handle->file)) { // Atomically try to restore WAL
318        // Some other thread or previous open had successfully initialized WAL
319        // We can simply return here
320        return;
321    }
322
323    if (!hdr_off) { // Nothing to do if we don't have a header block offset
324        return;
325    }
326
327    if (last_wal_flush_hdr_bid != BLK_NOT_FOUND) {
328        offset = (last_wal_flush_hdr_bid + 1) * blocksize;
329    }
330
331    // If a valid last header was retrieved and it matches the current header
332    if (hdr_off == offset || hdr_bid == last_wal_flush_hdr_bid) {
333        return; // No WAL section in the file
334    }
335
336    if (mode == FDB_RESTORE_NORMAL && !handle->shandle) {
337        // for normal WAL restore, set status to dirty
338        // (only when the previous status is clean or dirty)
339        wal_set_dirty_status(handle->file, FDB_WAL_DIRTY, true);
340    }
341
342    // Temporarily disable the error logging callback as there are false positive
343    // checksum errors in docio_read_doc.
344    // TODO: Need to adapt docio_read_doc to separate false checksum errors.
345    err_log_callback dummy_cb;
346    log_callback = handle->dhandle->log_callback;
347    dummy_cb.callback = fdb_dummy_log_callback;
348    dummy_cb.ctx_data = NULL;
349    handle->dhandle->log_callback = &dummy_cb;
350
351    if (!handle->shandle) {
352        filemgr_mutex_lock(file);
353    }
354    cmp_info.kvs_config = handle->kvs_config;
355    cmp_info.kvs = handle->kvs;
356
357    start_bmp_revnum = _fdb_get_bmp_revnum(handle, last_wal_flush_hdr_bid);
358    stop_bmp_revnum= _fdb_get_bmp_revnum(handle, hdr_bid);
359    cur_bmp_revnum = start_bmp_revnum;
360
361    // A: reused blocks during the 1st block reclaim (bmp_revnum: 1)
362    // B: reused blocks during the 2nd block reclaim (bmp_revnum: 2)
363    // otherwise: live block (bmp_revnum: 0)
364    //  1 2   3    4    5 6  7  8   9  10
365    // +-------------------------------------------+
366    // |  BBBBAAAAABBBBB  AAABBB    AAA            |
367    // +-------------------------------------------+
368    //              ^                     ^
369    //              hdr_bid               last_wal_flush
370    //
371    // scan order: 1 -> 5 -> 8 -> 10 -> 3 -> 6 -> 9 -> 2 -> 4 -> 7
372    // iteration #1: scan docs with bmp_revnum==0 in [last_wal_flush ~ filesize]
373    // iteration #2: scan docs with bmp_revnum==1 in [0 ~ filesize]
374    // iteration #3: scan docs with bmp_revnum==2 in [0 ~ hdr_bid]
375
376    do {
377        if (cur_bmp_revnum > stop_bmp_revnum) {
378            break;
379        } else if (cur_bmp_revnum == stop_bmp_revnum) {
380
381            bid_t sb_last_hdr_bid = BLK_NOT_FOUND;
382            if (handle->file->sb) {
383                sb_last_hdr_bid = atomic_get_uint64_t(&handle->file->sb->last_hdr_bid);
384            }
385            if (!handle->shandle && handle->file->sb &&
386                sb_last_hdr_bid != BLK_NOT_FOUND) {
387                hdr_off = (sb_last_hdr_bid+1) * blocksize;
388            }
389
390            doc_scan_limit = hdr_off;
391            if (offset >= hdr_off) {
392                break;
393            }
394        } else {
395            doc_scan_limit = filesize;
396        }
397
398        if (!docio_check_buffer(handle->dhandle, offset / blocksize,
399                                cur_bmp_revnum)) {
400            // not a document block .. move to next block
401        } else {
402            do {
403                struct docio_object doc;
404                int64_t _offset;
405                uint64_t doc_offset;
406                memset(&doc, 0, sizeof(doc));
407                _offset = docio_read_doc(handle->dhandle, offset, &doc, true);
408                if (_offset <= 0) { // reached unreadable doc, skip block
409                    // TODO: Need to have this function return fdb_status, so that
410                    // WAL restore operation should fail if offset < 0
411                    break;
412                } else if ((uint64_t)_offset < offset) {
413                    // If more than one writer is appending docs concurrently,
414                    // they have their own doc block linked list and doc blocks
415                    // may not be consecutive. For example,
416                    //
417                    // Writer 1): 100 -> 102 -> 2 -> 4     | commit
418                    // Writer 2):    101 - > 103 -> 3 -> 5 |
419                    //
420                    // In this case, if we read doc BID 102, then 'offset' will jump
421                    // to doc BID 2, without reading BID 103.
422                    //
423                    // To address this issue, in case that 'offset' decreases,
424                    // remember the next doc block, and follow the doc linked list
425                    // first. After the linked list ends, 'offset' cursor will be
426                    // reset to 'next_doc_block'.
427                    next_doc_block = (offset / blocksize) + 1;
428                }
429                if (doc.key || (doc.length.flag & DOCIO_TXN_COMMITTED)) {
430                    // check if the doc is transactional or not, and
431                    // also check if the doc contains system info
432                    if (!(doc.length.flag & DOCIO_TXN_DIRTY) &&
433                        !(doc.length.flag & DOCIO_SYSTEM)) {
434                        if (doc.length.flag & DOCIO_TXN_COMMITTED) {
435                            // commit mark .. read doc offset
436                            doc_offset = doc.doc_offset;
437                            // read the previously skipped doc
438                            if (docio_read_doc(handle->dhandle, doc_offset, &doc, true) <= 0) {
439                                // doc read error
440                                free(doc.key);
441                                free(doc.meta);
442                                free(doc.body);
443                                offset = _offset;
444                                continue;
445                            }
446                        } else {
447                            doc_offset = offset;
448                        }
449
450                        // If say a snapshot is taken on a db handle after
451                        // rollback, then skip WAL items after rollback point
452                        if ((mode == FDB_RESTORE_KV_INS || !handle->kvs) &&
453                            doc.seqnum > handle->seqnum) {
454                            free(doc.key);
455                            free(doc.meta);
456                            free(doc.body);
457                            offset = _offset;
458                            continue;
459                        }
460
461                        // restore document
462                        fdb_doc wal_doc;
463                        wal_doc.keylen = doc.length.keylen;
464                        wal_doc.bodylen = doc.length.bodylen;
465                        wal_doc.key = doc.key;
466                        wal_doc.seqnum = doc.seqnum;
467                        wal_doc.deleted = doc.length.flag & DOCIO_DELETED;
468
469                        if (!handle->shandle) {
470                            wal_doc.metalen = doc.length.metalen;
471                            wal_doc.meta = doc.meta;
472                            wal_doc.size_ondisk = _fdb_get_docsize(doc.length);
473
474                            if (handle->kvs) {
475                                // check seqnum before insert
476                                fdb_kvs_id_t kv_id;
477                                fdb_seqnum_t kv_seqnum;
478                                buf2kvid(handle->config.chunksize,
479                                         wal_doc.key, &kv_id);
480
481                                kv_seqnum = fdb_kvs_get_seqnum(handle->file, kv_id);
482                                if (doc.seqnum <= kv_seqnum &&
483                                        ((mode == FDB_RESTORE_KV_INS &&
484                                            kv_id == kv_id_req) ||
485                                         (mode == FDB_RESTORE_NORMAL)) ) {
486                                    // if mode is NORMAL, restore all items
487                                    // if mode is KV_INS, restore items matching ID
488                                    wal_insert(&file->global_txn, file, &cmp_info,
489                                               &wal_doc, doc_offset,
490                                               WAL_INS_WRITER);
491                                }
492                            } else {
493                                wal_insert(&file->global_txn, file, &cmp_info,
494                                           &wal_doc, doc_offset,
495                                           WAL_INS_WRITER);
496                            }
497                            if (doc.key) free(doc.key);
498                        } else {
499                            // snapshot
500                            if (handle->kvs) {
501                                fdb_kvs_id_t kv_id;
502                                buf2kvid(handle->config.chunksize,
503                                         wal_doc.key, &kv_id);
504                                if (kv_id == handle->kvs->id) {
505                                    // snapshot: insert ID matched documents only
506                                    wal_snap_insert(handle->shandle,
507                                                    &wal_doc, doc_offset);
508                                } else {
509                                    free(doc.key);
510                                }
511                            } else {
512                                wal_snap_insert(handle->shandle, &wal_doc,
513                                                doc_offset);
514                            }
515                        }
516                        free(doc.meta);
517                        free(doc.body);
518                        offset = _offset;
519                    } else {
520                        // skip transactional document or system document
521                        free(doc.key);
522                        free(doc.meta);
523                        free(doc.body);
524                        offset = _offset;
525                        // do not break.. read next doc
526                    }
527                } else {
528                    free(doc.key);
529                    free(doc.meta);
530                    free(doc.body);
531                    offset = _offset;
532                    break;
533                }
534            } while (offset + sizeof(struct docio_length) < doc_scan_limit);
535        }
536
537        if (next_doc_block != BLK_NOT_FOUND) {
538            offset = next_doc_block * blocksize;
539            next_doc_block = BLK_NOT_FOUND;
540        } else {
541            offset = ((offset / blocksize) + 1) * blocksize;
542        }
543        if (ver_superblock_support(handle->file->version) &&
544            offset >= filesize) {
545            // circular scan
546            struct superblock *sb = handle->file->sb;
547            if (sb && sb->config) {
548                offset = blocksize * sb->config->num_sb;
549                cur_bmp_revnum++;
550            }
551        }
552    } while(true);
553
554    // wal commit
555    if (!handle->shandle) {
556        wal_commit(&file->global_txn, file, NULL, &handle->log_callback);
557        filemgr_mutex_unlock(file);
558    }
559    handle->dhandle->log_callback = log_callback;
560}
561
562INLINE fdb_status _fdb_recover_compaction(fdb_kvs_handle *handle,
563                                          const char *new_filename)
564{
565    fdb_kvs_handle new_db;
566    fdb_config config = handle->config;
567    struct filemgr *new_file;
568
569    // As partially compacted file may contain various errors,
570    // we temporarily disable log callback for compaction recovery.
571    memset(&new_db, 0, sizeof(new_db));
572    new_db.log_callback.callback = NULL;
573    new_db.log_callback.ctx_data = NULL;
574    config.flags |= FDB_OPEN_FLAG_RDONLY;
575    new_db.fhandle = handle->fhandle;
576    new_db.kvs_config = handle->kvs_config;
577    fdb_status status = _fdb_open(&new_db, new_filename,
578                                  FDB_AFILENAME, &config);
579    if (status != FDB_RESULT_SUCCESS) {
580        return fdb_log(&handle->log_callback, status,
581                       "Error in opening a partially compacted file '%s' for recovery.",
582                       new_filename);
583    }
584
585    new_file = new_db.file;
586
587    if (new_file->old_filename &&
588        !strncmp(new_file->old_filename, handle->file->filename,
589                 FDB_MAX_FILENAME_LEN)) {
590        struct filemgr *old_file = handle->file;
591        // If new file has a recorded old_filename then it means that
592        // compaction has completed successfully. Mark self for deletion
593        filemgr_mutex_lock(new_file);
594
595        status = btreeblk_end(handle->bhandle);
596        if (status != FDB_RESULT_SUCCESS) {
597            filemgr_mutex_unlock(new_file);
598            _fdb_close(&new_db);
599            return status;
600        }
601        btreeblk_free(handle->bhandle);
602        free(handle->bhandle);
603        handle->bhandle = new_db.bhandle;
604
605        docio_free(handle->dhandle);
606        free(handle->dhandle);
607        handle->dhandle = new_db.dhandle;
608
609        hbtrie_free(handle->trie);
610        free(handle->trie);
611        handle->trie = new_db.trie;
612
613        wal_shutdown(handle->file, &handle->log_callback);
614        handle->file = new_file;
615
616        if (handle->config.seqtree_opt == FDB_SEQTREE_USE) {
617            if (handle->kvs) {
618                // multi KV instance mode
619                hbtrie_free(handle->seqtrie);
620                free(handle->seqtrie);
621                if (new_db.config.seqtree_opt == FDB_SEQTREE_USE) {
622                    handle->seqtrie = new_db.seqtrie;
623                }
624            } else {
625                free(handle->seqtree->kv_ops);
626                free(handle->seqtree);
627                if (new_db.config.seqtree_opt == FDB_SEQTREE_USE) {
628                    handle->seqtree = new_db.seqtree;
629                }
630            }
631        }
632        handle->staletree = new_db.staletree;
633
634        filemgr_mutex_unlock(new_file);
635        if (new_db.kvs) {
636            fdb_kvs_info_free(&new_db);
637        }
638        // remove self: WARNING must not close this handle if snapshots
639        // are yet to open this file
640        filemgr_remove_pending(old_file, new_db.file, &new_db.log_callback);
641        filemgr_close(old_file, 0, handle->filename, &handle->log_callback);
642        free(new_db.filename);
643        return FDB_RESULT_FAIL_BY_COMPACTION;
644    }
645
646    // As the new file is partially compacted, it should be removed upon close.
647    // Just in-case the new file gets opened before removal, point it to the old
648    // file to ensure availability of data.
649    filemgr_remove_pending(new_db.file, handle->file, &handle->log_callback);
650    _fdb_close(&new_db);
651
652    return FDB_RESULT_SUCCESS;
653}
654
655#ifndef SPIN_INITIALIZER
656INLINE void init_initial_lock_status() {
657    // Note that only Windows passes through this routine
658    if (!fdb_initialized) {
659        if (InterlockedCompareExchange(&initial_lock_status, 1, 0) == 0) {
660            // atomically initialize spin lock only once
661            spin_init(&initial_lock);
662            initial_lock_status = 2;
663        } else {
664            // the others .. wait until initializing 'initial_lock' is done
665            // TODO: Need to devise a better way of synchronization on Windows
666            while (initial_lock_status != 2) {
667                Sleep(1);
668            }
669        }
670    }
671}
672#endif
673
674LIBFDB_API
675fdb_status fdb_init(fdb_config *config)
676{
677    fdb_config _config;
678    compactor_config c_config;
679    bgflusher_config bgf_config;
680    struct filemgr_config f_config;
681
682    if (config) {
683        if (validate_fdb_config(config)) {
684            _config = *config;
685        } else {
686            return FDB_RESULT_INVALID_CONFIG;
687        }
688    } else {
689        _config = get_default_config();
690    }
691
692    // global initialization
693    // initialized only once at first time
694    if (!fdb_initialized) {
695
696#ifndef SPIN_INITIALIZER
697        init_initial_lock_status();
698#endif
699
700    }
701    spin_lock(&initial_lock);
702    if (!fdb_initialized) {
703#if !defined(_ANDROID_) && !defined(__ANDROID__)
704        // Some Android devices (e.g., Nexus 6) return incorrect RAM size.
705        // We temporarily disable validity checking of block cache size
706        // on Android platform at this time.
707        double ram_size = (double) get_memory_size();
708        if (ram_size * BCACHE_MEMORY_THRESHOLD < (double) _config.buffercache_size) {
709            spin_unlock(&initial_lock);
710            return FDB_RESULT_TOO_BIG_BUFFER_CACHE;
711        }
712#endif
713        // initialize file manager and block cache
714        f_config.blocksize = _config.blocksize;
715        f_config.ncacheblock = _config.buffercache_size / _config.blocksize;
716        f_config.seqtree_opt = _config.seqtree_opt;
717        filemgr_init(&f_config);
718        filemgr_set_lazy_file_deletion(true,
719                                       compactor_register_file_removing,
720                                       compactor_is_file_removed);
721        if (ver_superblock_support(ver_get_latest_magic())) {
722            struct sb_ops sb_ops = {sb_init, sb_get_default_config,
723                                    sb_read_latest, sb_alloc_block,
724                                    sb_bmp_is_writable, sb_get_bmp_revnum,
725                                    sb_get_min_live_revnum, sb_free};
726            filemgr_set_sb_operation(sb_ops);
727            sb_bmp_mask_init();
728        }
729
730        // initialize compaction daemon
731        c_config.sleep_duration = _config.compactor_sleep_duration;
732        c_config.num_threads = _config.num_compactor_threads;
733        compactor_init(&c_config);
734        // initialize background flusher daemon
735        // Temporarily disable background flushers until blockcache contention
736        // issue is resolved.
737        bgf_config.num_threads = 0; //_config.num_bgflusher_threads;
738        bgflusher_init(&bgf_config);
739
740        // Initialize breakpad
741        _dbg_handle_crashes(config->breakpad_minidump_dir);
742
743        fdb_initialized = 1;
744    }
745    spin_unlock(&initial_lock);
746
747    return FDB_RESULT_SUCCESS;
748}
749
750LIBFDB_API
751fdb_config fdb_get_default_config(void) {
752    return get_default_config();
753}
754
755LIBFDB_API
756fdb_kvs_config fdb_get_default_kvs_config(void) {
757    return get_default_kvs_config();
758}
759
760LIBFDB_API
761fdb_status fdb_open(fdb_file_handle **ptr_fhandle,
762                    const char *filename,
763                    fdb_config *fconfig)
764{
765#ifdef _MEMPOOL
766    mempool_init();
767#endif
768
769    fdb_config config;
770    fdb_file_handle *fhandle;
771    fdb_kvs_handle *handle;
772    LATENCY_STAT_START();
773
774    if (fconfig) {
775        if (validate_fdb_config(fconfig)) {
776            config = *fconfig;
777        } else {
778            return FDB_RESULT_INVALID_CONFIG;
779        }
780    } else {
781        config = get_default_config();
782    }
783
784    fhandle = (fdb_file_handle*)calloc(1, sizeof(fdb_file_handle));
785    if (!fhandle) { // LCOV_EXCL_START
786        return FDB_RESULT_ALLOC_FAIL;
787    } // LCOV_EXCL_STOP
788
789    handle = (fdb_kvs_handle *) calloc(1, sizeof(fdb_kvs_handle));
790    if (!handle) { // LCOV_EXCL_START
791        free(fhandle);
792        return FDB_RESULT_ALLOC_FAIL;
793    } // LCOV_EXCL_STOP
794
795#ifndef SPIN_INITIALIZER
796    init_initial_lock_status();
797#endif
798
799    spin_lock(&initial_lock);
800    fdb_open_inprog++;
801    spin_unlock(&initial_lock);
802
803    atomic_init_uint8_t(&handle->handle_busy, 0);
804    handle->shandle = NULL;
805    handle->kvs_config = get_default_kvs_config();
806
807    fdb_status fs = fdb_init(fconfig);
808    if (fs != FDB_RESULT_SUCCESS) {
809        free(handle);
810        free(fhandle);
811        spin_lock(&initial_lock);
812        fdb_open_inprog--;
813        spin_unlock(&initial_lock);
814        return fs;
815    }
816    fdb_file_handle_init(fhandle, handle);
817
818    fs = _fdb_open(handle, filename, FDB_VFILENAME, &config);
819    if (fs == FDB_RESULT_SUCCESS) {
820        *ptr_fhandle = fhandle;
821        filemgr_fhandle_add(handle->file, fhandle);
822        LATENCY_STAT_END(handle->file, FDB_LATENCY_OPEN);
823    } else {
824        *ptr_fhandle = NULL;
825        free(handle);
826        fdb_file_handle_free(fhandle);
827    }
828    spin_lock(&initial_lock);
829    fdb_open_inprog--;
830    spin_unlock(&initial_lock);
831    return fs;
832}
833
834LIBFDB_API
835fdb_status fdb_open_custom_cmp(fdb_file_handle **ptr_fhandle,
836                               const char *filename,
837                               fdb_config *fconfig,
838                               size_t num_functions,
839                               char **kvs_names,
840                               fdb_custom_cmp_variable *functions)
841{
842#ifdef _MEMPOOL
843    mempool_init();
844#endif
845
846    fdb_config config;
847    fdb_file_handle *fhandle;
848    fdb_kvs_handle *handle;
849
850    if (fconfig) {
851        if (validate_fdb_config(fconfig)) {
852            config = *fconfig;
853        } else {
854            return FDB_RESULT_INVALID_CONFIG;
855        }
856    } else {
857        config = get_default_config();
858    }
859
860    if (config.multi_kv_instances == false) {
861        // single KV instance mode does not support customized cmp function
862        return FDB_RESULT_INVALID_CONFIG;
863    }
864
865    fhandle = (fdb_file_handle*)calloc(1, sizeof(fdb_file_handle));
866    if (!fhandle) { // LCOV_EXCL_START
867        return FDB_RESULT_ALLOC_FAIL;
868    } // LCOV_EXCL_STOP
869
870    handle = (fdb_kvs_handle *) calloc(1, sizeof(fdb_kvs_handle));
871    if (!handle) { // LCOV_EXCL_START
872        free(fhandle);
873        return FDB_RESULT_ALLOC_FAIL;
874    } // LCOV_EXCL_STOP
875
876#ifndef SPIN_INITIALIZER
877    init_initial_lock_status();
878#endif
879
880    spin_lock(&initial_lock);
881    fdb_open_inprog++;
882    spin_unlock(&initial_lock);
883
884    atomic_init_uint8_t(&handle->handle_busy, 0);
885    handle->shandle = NULL;
886    handle->kvs_config = get_default_kvs_config();
887
888    fdb_status fs = fdb_init(fconfig);
889    if (fs != FDB_RESULT_SUCCESS) {
890        free(handle);
891        free(fhandle);
892        spin_lock(&initial_lock);
893        fdb_open_inprog--;
894        spin_unlock(&initial_lock);
895        return fs;
896    }
897    fdb_file_handle_init(fhandle, handle);
898
899    // insert kvs_names and functions into fhandle's list
900    fdb_file_handle_parse_cmp_func(fhandle, num_functions,
901                                   kvs_names, functions);
902
903    fs = _fdb_open(handle, filename, FDB_VFILENAME, &config);
904    if (fs == FDB_RESULT_SUCCESS) {
905        *ptr_fhandle = fhandle;
906        filemgr_fhandle_add(handle->file, fhandle);
907    } else {
908        *ptr_fhandle = NULL;
909        free(handle);
910        fdb_file_handle_free(fhandle);
911    }
912    spin_lock(&initial_lock);
913    fdb_open_inprog--;
914    spin_unlock(&initial_lock);
915    return fs;
916}
917
918fdb_status fdb_open_for_compactor(fdb_file_handle **ptr_fhandle,
919                                  const char *filename,
920                                  fdb_config *fconfig,
921                                  struct list *cmp_func_list)
922{
923#ifdef _MEMPOOL
924    mempool_init();
925#endif
926
927    fdb_file_handle *fhandle;
928    fdb_kvs_handle *handle;
929
930    fhandle = (fdb_file_handle*)calloc(1, sizeof(fdb_file_handle));
931    if (!fhandle) { // LCOV_EXCL_START
932        return FDB_RESULT_ALLOC_FAIL;
933    } // LCOV_EXCL_STOP
934
935    handle = (fdb_kvs_handle *) calloc(1, sizeof(fdb_kvs_handle));
936    if (!handle) { // LCOV_EXCL_START
937        free(fhandle);
938        return FDB_RESULT_ALLOC_FAIL;
939    } // LCOV_EXCL_STOP
940
941    atomic_init_uint8_t(&handle->handle_busy, 0);
942    handle->shandle = NULL;
943
944    fdb_file_handle_init(fhandle, handle);
945    if (cmp_func_list && list_begin(cmp_func_list)) {
946        fdb_file_handle_clone_cmp_func_list(fhandle, cmp_func_list);
947    }
948    fdb_status fs = _fdb_open(handle, filename, FDB_VFILENAME, fconfig);
949    if (fs == FDB_RESULT_SUCCESS) {
950        *ptr_fhandle = fhandle;
951        filemgr_fhandle_add(handle->file, fhandle);
952    } else {
953        *ptr_fhandle = NULL;
954        free(handle);
955        fdb_file_handle_free(fhandle);
956    }
957    return fs;
958}
959
960LIBFDB_API
961fdb_status fdb_snapshot_open(fdb_kvs_handle *handle_in,
962                             fdb_kvs_handle **ptr_handle, fdb_seqnum_t seqnum)
963{
964#ifdef _MEMPOOL
965    mempool_init();
966#endif
967
968    if (!handle_in || !ptr_handle) {
969        return FDB_RESULT_INVALID_HANDLE;
970    }
971
972    fdb_config config = handle_in->config;
973    fdb_kvs_config kvs_config = handle_in->kvs_config;
974    fdb_kvs_id_t kv_id = 0;
975    fdb_kvs_handle *handle;
976    fdb_txn *txn = NULL;
977    fdb_status fs = FDB_RESULT_SUCCESS;
978    filemgr *file;
979    file_status_t fstatus = FILE_NORMAL;
980    struct snap_handle dummy_shandle;
981    struct _fdb_key_cmp_info cmp_info;
982    LATENCY_STAT_START();
983
984fdb_snapshot_open_start:
985    if (!handle_in->shandle) {
986        fdb_check_file_reopen(handle_in, &fstatus);
987        fdb_sync_db_header(handle_in);
988        file = handle_in->file;
989
990        if (handle_in->kvs && handle_in->kvs->type == KVS_SUB) {
991            handle_in->seqnum = fdb_kvs_get_seqnum(file,
992                                                   handle_in->kvs->id);
993        } else {
994            handle_in->seqnum = filemgr_get_seqnum(file);
995        }
996    } else {
997        file = handle_in->file;
998    }
999
1000    // if the max sequence number seen by this handle is lower than the
1001    // requested snapshot marker, it means the snapshot is not yet visible
1002    // even via the current fdb_kvs_handle
1003    if (seqnum != FDB_SNAPSHOT_INMEM && seqnum > handle_in->seqnum) {
1004        return FDB_RESULT_NO_DB_INSTANCE;
1005    }
1006
1007    handle = (fdb_kvs_handle *) calloc(1, sizeof(fdb_kvs_handle));
1008    if (!handle) { // LCOV_EXCL_START
1009        return FDB_RESULT_ALLOC_FAIL;
1010    } // LCOV_EXCL_STOP
1011
1012    atomic_init_uint8_t(&handle->handle_busy, 0);
1013    handle->log_callback = handle_in->log_callback;
1014    handle->max_seqnum = seqnum;
1015    handle->fhandle = handle_in->fhandle;
1016
1017    config.flags |= FDB_OPEN_FLAG_RDONLY;
1018    // do not perform compaction for snapshot
1019    config.compaction_mode = FDB_COMPACTION_MANUAL;
1020
1021    // If cloning an existing snapshot handle, then rewind indexes
1022    // to its last DB header and point its avl tree to existing snapshot's tree
1023    bool clone_snapshot = false;
1024    if (handle_in->shandle) {
1025        handle->last_hdr_bid = handle_in->last_hdr_bid; // do fast rewind
1026        fs = wal_snapshot_clone(handle_in->shandle, &handle->shandle, seqnum);
1027        if (fs == FDB_RESULT_SUCCESS) {
1028            clone_snapshot = true;
1029            handle->max_seqnum = FDB_SNAPSHOT_INMEM; // temp value to skip WAL
1030        } else {
1031            fdb_log(&handle_in->log_callback, fs,
1032                    "Warning: Snapshot clone at sequence number %" _F64
1033                    "does not match its snapshot handle %" _F64
1034                    "in file '%s'.", seqnum, handle_in->seqnum,
1035                    handle_in->file->filename);
1036            free(handle);
1037            return fs;
1038        }
1039    }
1040
1041    cmp_info.kvs_config = handle_in->kvs_config;
1042    cmp_info.kvs = handle_in->kvs;
1043
1044    if (!handle->shandle) {
1045        txn = handle_in->fhandle->root->txn;
1046        if (!txn) {
1047            txn = &handle_in->file->global_txn;
1048        }
1049        if (handle_in->kvs) {
1050            kv_id = handle_in->kvs->id;
1051        }
1052        if (seqnum == FDB_SNAPSHOT_INMEM) {
1053            memset(&dummy_shandle, 0, sizeof(struct snap_handle));
1054            // tmp value to denote snapshot & not rollback to _fdb_open
1055            handle->shandle = &dummy_shandle; // dummy
1056        } else {
1057            fs = wal_dur_snapshot_open(seqnum, &cmp_info, file, txn,
1058                                       &handle->shandle);
1059        }
1060        if (fs != FDB_RESULT_SUCCESS) {
1061            free(handle);
1062            return fs;
1063        }
1064    }
1065
1066    if (handle_in->kvs) {
1067        // sub-handle in multi KV instance mode
1068        if (clone_snapshot) {
1069            fs = _fdb_kvs_clone_snapshot(handle_in, handle);
1070        } else {
1071            fs = _fdb_kvs_open(handle_in->kvs->root,
1072                              &config, &kvs_config, file,
1073                              file->filename,
1074                              _fdb_kvs_get_name(handle_in, file),
1075                              handle);
1076        }
1077    } else {
1078        if (clone_snapshot) {
1079            fs = _fdb_clone_snapshot(handle_in, handle);
1080        } else {
1081            fs = _fdb_open(handle, file->filename, FDB_AFILENAME, &config);
1082        }
1083    }
1084
1085    if (fs == FDB_RESULT_SUCCESS) {
1086        if (seqnum == FDB_SNAPSHOT_INMEM &&
1087            !handle_in->shandle) {
1088            handle->max_seqnum = handle_in->seqnum;
1089
1090            // synchronize dirty root nodes if exist
1091            bid_t dirty_idtree_root = BLK_NOT_FOUND;
1092            bid_t dirty_seqtree_root = BLK_NOT_FOUND;
1093            struct filemgr_dirty_update_node *dirty_update;
1094
1095            dirty_update = filemgr_dirty_update_get_latest(handle->file);
1096            btreeblk_set_dirty_update(handle->bhandle, dirty_update);
1097
1098            if (dirty_update) {
1099                filemgr_dirty_update_get_root(handle->file, dirty_update,
1100                                       &dirty_idtree_root, &dirty_seqtree_root);
1101                _fdb_import_dirty_root(handle, dirty_idtree_root,
1102                                       dirty_seqtree_root);
1103                btreeblk_discard_blocks(handle->bhandle);
1104            }
1105            // Having synced the dirty root, make an in-memory WAL snapshot
1106            // TODO: Re-enable WAL sharing once ready...
1107#ifdef _MVCC_WAL_ENABLE
1108            fs = wal_snapshot_open(handle->file, txn, kv_id, seqnum,
1109                                   &cmp_info, &handle->shandle);
1110#else
1111            fs = wal_dur_snapshot_open(handle->seqnum, &cmp_info, file, txn,
1112                                       &handle->shandle);
1113            if (fs == FDB_RESULT_SUCCESS) {
1114                fs = wal_copyto_snapshot(file, handle->shandle,
1115                                        (bool)handle_in->kvs);
1116            }
1117            (void)kv_id;
1118#endif // _MVCC_WAL_ENABLE
1119        } else if (clone_snapshot) {
1120            // Snapshot is created on the other snapshot handle
1121
1122            handle->max_seqnum = handle_in->seqnum;
1123
1124            if (seqnum == FDB_SNAPSHOT_INMEM) {
1125                // in-memory snapshot
1126                // Clone dirty root nodes from the source snapshot by incrementing
1127                // their ref counters
1128                handle->trie->root_bid = handle_in->trie->root_bid;
1129                if (handle->config.seqtree_opt == FDB_SEQTREE_USE) {
1130                    if (handle->kvs) {
1131                        handle->seqtrie->root_bid = handle_in->seqtrie->root_bid;
1132                    } else {
1133                        handle->seqtree->root_bid = handle_in->seqtree->root_bid;
1134                    }
1135                }
1136                btreeblk_discard_blocks(handle->bhandle);
1137
1138                // increase ref count for dirty update
1139                struct filemgr_dirty_update_node *dirty_update;
1140                dirty_update = btreeblk_get_dirty_update(handle_in->bhandle);
1141                filemgr_dirty_update_inc_ref_count(dirty_update);
1142                btreeblk_set_dirty_update(handle->bhandle, dirty_update);
1143            }
1144        }
1145        *ptr_handle = handle;
1146    } else {
1147        *ptr_handle = NULL;
1148        if (clone_snapshot || seqnum != FDB_SNAPSHOT_INMEM) {
1149            wal_snapshot_close(handle->shandle, handle->file);
1150        }
1151        free(handle);
1152        // If compactor thread had finished compaction just before this routine
1153        // calls _fdb_open, then it is possible that the snapshot's DB header
1154        // is only present in the new_file. So we must retry the snapshot
1155        // open attempt IFF _fdb_open indicates FDB_RESULT_NO_DB_INSTANCE..
1156        if (fs == FDB_RESULT_NO_DB_INSTANCE && fstatus == FILE_COMPACT_OLD) {
1157            if (filemgr_get_file_status(file) == FILE_REMOVED_PENDING) {
1158                goto fdb_snapshot_open_start;
1159            }
1160        }
1161    }
1162
1163    if (handle_in->shandle) {
1164        LATENCY_STAT_END(file, FDB_LATENCY_SNAP_CLONE);
1165    } else if (seqnum == FDB_SNAPSHOT_INMEM) {
1166        LATENCY_STAT_END(file, FDB_LATENCY_SNAP_INMEM);
1167    } else {
1168        LATENCY_STAT_END(file, FDB_LATENCY_SNAP_DUR);
1169    }
1170    return fs;
1171}
1172
1173static fdb_status _fdb_reset(fdb_kvs_handle *handle, fdb_kvs_handle *handle_in);
1174
1175LIBFDB_API
1176fdb_status fdb_rollback(fdb_kvs_handle **handle_ptr, fdb_seqnum_t seqnum)
1177{
1178#ifdef _MEMPOOL
1179    mempool_init();
1180#endif
1181
1182    fdb_config config;
1183    fdb_kvs_handle *handle_in, *handle;
1184    fdb_status fs;
1185    fdb_seqnum_t old_seqnum;
1186
1187    if (!handle_ptr) {
1188        return FDB_RESULT_INVALID_HANDLE;
1189    }
1190
1191    handle_in = *handle_ptr;
1192
1193    if (!handle_in) {
1194        return FDB_RESULT_INVALID_HANDLE;
1195    }
1196
1197    config = handle_in->config;
1198
1199    if (handle_in->kvs) {
1200        return fdb_kvs_rollback(handle_ptr, seqnum);
1201    }
1202
1203    if (handle_in->config.flags & FDB_OPEN_FLAG_RDONLY) {
1204        return fdb_log(&handle_in->log_callback, FDB_RESULT_RONLY_VIOLATION,
1205                       "Warning: Rollback is not allowed on the read-only DB file '%s'.",
1206                       handle_in->file->filename);
1207    }
1208
1209    if (!atomic_cas_uint8_t(&handle_in->handle_busy, 0, 1)) {
1210        return FDB_RESULT_HANDLE_BUSY;
1211    }
1212
1213    filemgr_mutex_lock(handle_in->file);
1214    filemgr_set_rollback(handle_in->file, 1); // disallow writes operations
1215    // All transactions should be closed before rollback
1216    if (wal_txn_exists(handle_in->file)) {
1217        filemgr_set_rollback(handle_in->file, 0);
1218        filemgr_mutex_unlock(handle_in->file);
1219        atomic_cas_uint8_t(&handle_in->handle_busy, 1, 0);
1220        return FDB_RESULT_FAIL_BY_TRANSACTION;
1221    }
1222
1223    // If compaction is running, wait until it is aborted.
1224    // TODO: Find a better way of waiting for the compaction abortion.
1225    unsigned int sleep_time = 10000; // 10 ms.
1226    file_status_t fstatus = filemgr_get_file_status(handle_in->file);
1227    while (fstatus == FILE_COMPACT_OLD) {
1228        filemgr_mutex_unlock(handle_in->file);
1229        decaying_usleep(&sleep_time, 1000000);
1230        filemgr_mutex_lock(handle_in->file);
1231        fstatus = filemgr_get_file_status(handle_in->file);
1232    }
1233    if (fstatus == FILE_REMOVED_PENDING) {
1234        filemgr_mutex_unlock(handle_in->file);
1235        fdb_check_file_reopen(handle_in, NULL);
1236    } else {
1237        filemgr_mutex_unlock(handle_in->file);
1238    }
1239
1240    fdb_sync_db_header(handle_in);
1241
1242    // if the max sequence number seen by this handle is lower than the
1243    // requested snapshot marker, it means the snapshot is not yet visible
1244    // even via the current fdb_kvs_handle
1245    if (seqnum > handle_in->seqnum) {
1246        filemgr_set_rollback(handle_in->file, 0); // allow mutations
1247        atomic_cas_uint8_t(&handle_in->handle_busy, 1, 0);
1248        return FDB_RESULT_NO_DB_INSTANCE;
1249    }
1250
1251    handle = (fdb_kvs_handle *) calloc(1, sizeof(fdb_kvs_handle));
1252    if (!handle) { // LCOV_EXCL_START
1253        atomic_cas_uint8_t(&handle_in->handle_busy, 1, 0);
1254        return FDB_RESULT_ALLOC_FAIL;
1255    } // LCOV_EXCL_STOP
1256
1257    atomic_init_uint8_t(&handle->handle_busy, 0);
1258    handle->log_callback = handle_in->log_callback;
1259    handle->fhandle = handle_in->fhandle;
1260    if (seqnum == 0) {
1261        fs = _fdb_reset(handle, handle_in);
1262    } else {
1263        handle->max_seqnum = seqnum;
1264        fs = _fdb_open(handle, handle_in->file->filename, FDB_AFILENAME,
1265                       &config);
1266    }
1267
1268    filemgr_set_rollback(handle_in->file, 0); // allow mutations
1269    if (fs == FDB_RESULT_SUCCESS) {
1270        // rollback the file's sequence number
1271        filemgr_mutex_lock(handle_in->file);
1272        old_seqnum = filemgr_get_seqnum(handle_in->file);
1273        filemgr_set_seqnum(handle_in->file, seqnum);
1274        filemgr_mutex_unlock(handle_in->file);
1275
1276        fs = _fdb_commit(handle, FDB_COMMIT_MANUAL_WAL_FLUSH,
1277                !(handle_in->config.durability_opt & FDB_DRB_ASYNC));
1278        if (fs == FDB_RESULT_SUCCESS) {
1279            if (handle_in->txn) {
1280                handle->txn = handle_in->txn;
1281                handle_in->txn = NULL;
1282            }
1283            handle_in->fhandle->root = handle;
1284            _fdb_close_root(handle_in);
1285            handle->max_seqnum = 0;
1286            handle->seqnum = seqnum;
1287            *handle_ptr = handle;
1288        } else {
1289            // cancel the rolling-back of the sequence number
1290            filemgr_mutex_lock(handle_in->file);
1291            filemgr_set_seqnum(handle_in->file, old_seqnum);
1292            filemgr_mutex_unlock(handle_in->file);
1293            free(handle);
1294            atomic_cas_uint8_t(&handle_in->handle_busy, 1, 0);
1295        }
1296    } else {
1297        free(handle);
1298        atomic_cas_uint8_t(&handle_in->handle_busy, 1, 0);
1299    }
1300
1301    return fs;
1302}
1303
1304LIBFDB_API
1305fdb_status fdb_rollback_all(fdb_file_handle *fhandle,
1306                            fdb_snapshot_marker_t marker)
1307{
1308#ifdef _MEMPOOL
1309    mempool_init();
1310#endif
1311
1312    fdb_config config;
1313    fdb_kvs_handle *super_handle;
1314    fdb_kvs_handle rhandle;
1315    fdb_kvs_handle *handle = &rhandle;
1316    struct filemgr *file;
1317    fdb_kvs_config kvs_config;
1318    fdb_status fs;
1319    err_log_callback log_callback;
1320    struct kvs_info *kvs;
1321    struct snap_handle shandle; // dummy snap handle
1322
1323    if (!fhandle) {
1324        return FDB_RESULT_INVALID_HANDLE;
1325    }
1326
1327    super_handle = fhandle->root;
1328    kvs = super_handle->kvs;
1329
1330    // fdb_rollback_all cannot be allowed when there are kv store instances
1331    // still open, because we do not have means of invalidating open kv handles
1332    // which may not be present in the rollback point
1333    if (kvs && _fdb_kvs_is_busy(fhandle)) {
1334        return FDB_RESULT_KV_STORE_BUSY;
1335    }
1336    file = super_handle->file;
1337    config = super_handle->config;
1338    kvs_config = super_handle->kvs_config;
1339    log_callback = super_handle->log_callback;
1340
1341    if (super_handle->config.flags & FDB_OPEN_FLAG_RDONLY) {
1342        return fdb_log(&super_handle->log_callback, FDB_RESULT_RONLY_VIOLATION,
1343                       "Warning: Rollback is not allowed on the read-only DB file '%s'.",
1344                       super_handle->file->filename);
1345    }
1346
1347    filemgr_mutex_lock(super_handle->file);
1348    filemgr_set_rollback(super_handle->file, 1); // disallow writes operations
1349    // All transactions should be closed before rollback
1350    if (wal_txn_exists(super_handle->file)) {
1351        filemgr_set_rollback(super_handle->file, 0);
1352        filemgr_mutex_unlock(super_handle->file);
1353        return FDB_RESULT_FAIL_BY_TRANSACTION;
1354    }
1355
1356    // If compaction is running, wait until it is aborted.
1357    // TODO: Find a better way of waiting for the compaction abortion.
1358    unsigned int sleep_time = 10000; // 10 ms.
1359    file_status_t fstatus = filemgr_get_file_status(super_handle->file);
1360    while (fstatus == FILE_COMPACT_OLD) {
1361        filemgr_mutex_unlock(super_handle->file);
1362        decaying_usleep(&sleep_time, 1000000);
1363        filemgr_mutex_lock(super_handle->file);
1364        fstatus = filemgr_get_file_status(super_handle->file);
1365    }
1366    if (fstatus == FILE_REMOVED_PENDING) {
1367        filemgr_mutex_unlock(super_handle->file);
1368        fdb_check_file_reopen(super_handle, NULL);
1369    } else {
1370        filemgr_mutex_unlock(super_handle->file);
1371    }
1372
1373    fdb_sync_db_header(super_handle);
1374    // Shutdown WAL discarding entries from all KV Stores..
1375    fs = wal_shutdown(super_handle->file, &super_handle->log_callback);
1376    if (fs != FDB_RESULT_SUCCESS) {
1377        return fs;
1378    }
1379
1380    memset(handle, 0, sizeof(fdb_kvs_handle));
1381    memset(&shandle, 0, sizeof(struct snap_handle));
1382    handle->log_callback = log_callback;
1383    handle->fhandle = fhandle;
1384    handle->last_hdr_bid = (bid_t)marker; // Fast rewind on open
1385    handle->max_seqnum = FDB_SNAPSHOT_INMEM; // Prevent WAL restore on open
1386    handle->shandle = &shandle; // a dummy handle to prevent WAL restore
1387    if (kvs) {
1388        fdb_kvs_header_free(file); // KV header will be recreated below.
1389        handle->kvs = kvs; // re-use super_handle's kvs info
1390        handle->kvs_config = kvs_config;
1391    }
1392    handle->config = config;
1393
1394    fs = _fdb_open(handle, file->filename, FDB_AFILENAME, &config);
1395
1396    if (handle->config.multi_kv_instances) {
1397        filemgr_mutex_lock(handle->file);
1398        fdb_kvs_header_create(handle->file);
1399        fdb_kvs_header_read(handle->file->kv_header, handle->dhandle,
1400                            handle->kv_info_offset,
1401                            handle->file->version, false);
1402        filemgr_mutex_unlock(handle->file);
1403    }
1404
1405    filemgr_set_rollback(file, 0); // allow mutations
1406    handle->shandle = NULL; // just a dummy handle never allocated
1407
1408    if (fs == FDB_RESULT_SUCCESS) {
1409        fdb_seqnum_t old_seqnum;
1410        // Restore WAL for all KV instances...
1411        _fdb_restore_wal(handle, FDB_RESTORE_NORMAL, (bid_t)marker, 0);
1412
1413        // rollback the file's sequence number
1414        filemgr_mutex_lock(file);
1415        old_seqnum = filemgr_get_seqnum(file);
1416        filemgr_set_seqnum(file, handle->seqnum);
1417        filemgr_mutex_unlock(file);
1418
1419        fs = _fdb_commit(handle, FDB_COMMIT_NORMAL,
1420                         !(handle->config.durability_opt & FDB_DRB_ASYNC));
1421        if (fs == FDB_RESULT_SUCCESS) {
1422            _fdb_close(super_handle);
1423            *super_handle = *handle;
1424        } else {
1425            filemgr_mutex_lock(file);
1426            filemgr_set_seqnum(file, old_seqnum);
1427            filemgr_mutex_unlock(file);
1428        }
1429    } else { // Rollback failed, restore KV header
1430        fdb_kvs_header_create(file);
1431        fdb_kvs_header_read(file->kv_header, super_handle->dhandle,
1432                            super_handle->kv_info_offset,
1433                            ver_get_latest_magic(),
1434                            false);
1435    }
1436
1437    return fs;
1438}
1439
1440static void _fdb_init_file_config(const fdb_config *config,
1441                                  struct filemgr_config *fconfig) {
1442    fconfig->blocksize = config->blocksize;
1443    fconfig->ncacheblock = config->buffercache_size / config->blocksize;
1444    fconfig->chunksize = config->chunksize;
1445
1446    fconfig->options = 0x0;
1447    fconfig->seqtree_opt = config->seqtree_opt;
1448
1449    if (config->flags & FDB_OPEN_FLAG_CREATE) {
1450        fconfig->options |= FILEMGR_CREATE;
1451    }
1452    if (config->flags & FDB_OPEN_FLAG_RDONLY) {
1453        fconfig->options |= FILEMGR_READONLY;
1454    }
1455    if (!(config->durability_opt & FDB_DRB_ASYNC)) {
1456        fconfig->options |= FILEMGR_SYNC;
1457    }
1458
1459    fconfig->flag = 0x0;
1460    if ((config->durability_opt & FDB_DRB_ODIRECT) &&
1461        config->buffercache_size) {
1462        fconfig->flag |= _ARCH_O_DIRECT;
1463    }
1464
1465    fconfig->prefetch_duration = config->prefetch_duration;
1466    fconfig->num_wal_shards = config->num_wal_partitions;
1467    fconfig->num_bcache_shards = config->num_bcache_partitions;
1468    fconfig->encryption_key = config->encryption_key;
1469    atomic_store_uint64_t(&fconfig->block_reusing_threshold,
1470                          config->block_reusing_threshold,
1471                          std::memory_order_relaxed);
1472    atomic_store_uint64_t(&fconfig->num_keeping_headers,
1473                          config->num_keeping_headers,
1474                          std::memory_order_relaxed);
1475}
1476
1477fdb_status _fdb_clone_snapshot(fdb_kvs_handle *handle_in,
1478                               fdb_kvs_handle *handle_out)
1479{
1480    fdb_status status;
1481
1482    handle_out->config = handle_in->config;
1483    handle_out->kvs_config = handle_in->kvs_config;
1484    handle_out->fileops = handle_in->fileops;
1485    handle_out->file = handle_in->file;
1486    // Note that the file ref count will be decremented when the cloned snapshot
1487    // is closed through filemgr_close().
1488    filemgr_incr_ref_count(handle_out->file);
1489
1490    if (handle_out->filename) {
1491        handle_out->filename = (char *)realloc(handle_out->filename,
1492                                               strlen(handle_in->filename)+1);
1493    } else {
1494        handle_out->filename = (char*)malloc(strlen(handle_in->filename)+1);
1495    }
1496    strcpy(handle_out->filename, handle_in->filename);
1497
1498    // initialize the docio handle.
1499    handle_out->dhandle = (struct docio_handle *)
1500        calloc(1, sizeof(struct docio_handle));
1501    handle_out->dhandle->log_callback = &handle_out->log_callback;
1502    docio_init(handle_out->dhandle, handle_out->file,
1503               handle_out->config.compress_document_body);
1504
1505    // initialize the btree block handle.
1506    handle_out->btreeblkops = btreeblk_get_ops();
1507    handle_out->bhandle = (struct btreeblk_handle *)
1508        calloc(1, sizeof(struct btreeblk_handle));
1509    handle_out->bhandle->log_callback = &handle_out->log_callback;
1510    btreeblk_init(handle_out->bhandle, handle_out->file, handle_out->file->blocksize);
1511
1512    handle_out->dirty_updates = handle_in->dirty_updates;
1513    atomic_store_uint64_t(&handle_out->cur_header_revnum, handle_in->cur_header_revnum);
1514    handle_out->last_wal_flush_hdr_bid = handle_in->last_wal_flush_hdr_bid;
1515    handle_out->kv_info_offset = handle_in->kv_info_offset;
1516    handle_out->op_stats = handle_in->op_stats;
1517
1518    // initialize the trie handle
1519    handle_out->trie = (struct hbtrie *)malloc(sizeof(struct hbtrie));
1520    hbtrie_init(handle_out->trie, handle_out->config.chunksize, OFFSET_SIZE,
1521                handle_out->file->blocksize,
1522                handle_in->trie->root_bid, // Source snapshot's trie root bid
1523                (void *)handle_out->bhandle, handle_out->btreeblkops,
1524                (void *)handle_out->dhandle, _fdb_readkey_wrap);
1525    // set aux for cmp wrapping function
1526    hbtrie_set_leaf_height_limit(handle_out->trie, 0xff);
1527    hbtrie_set_leaf_cmp(handle_out->trie, _fdb_custom_cmp_wrap);
1528
1529    if (handle_out->kvs) {
1530        hbtrie_set_map_function(handle_out->trie, fdb_kvs_find_cmp_chunk);
1531    }
1532
1533    handle_out->seqnum = handle_in->seqnum;
1534    if (handle_out->config.seqtree_opt == FDB_SEQTREE_USE) {
1535        if (handle_out->config.multi_kv_instances) {
1536            // multi KV instance mode .. HB+trie
1537            handle_out->seqtrie = (struct hbtrie *)malloc(sizeof(struct hbtrie));
1538            hbtrie_init(handle_out->seqtrie, sizeof(fdb_kvs_id_t), OFFSET_SIZE,
1539                        handle_out->file->blocksize,
1540                        handle_in->seqtrie->root_bid, // Source snapshot's seqtrie root bid
1541                        (void *)handle_out->bhandle, handle_out->btreeblkops,
1542                        (void *)handle_out->dhandle, _fdb_readseq_wrap);
1543
1544        } else {
1545            // single KV instance mode .. normal B+tree
1546            struct btree_kv_ops *seq_kv_ops =
1547                (struct btree_kv_ops *)malloc(sizeof(struct btree_kv_ops));
1548            seq_kv_ops = btree_kv_get_kb64_vb64(seq_kv_ops);
1549            seq_kv_ops->cmp = _cmp_uint64_t_endian_safe;
1550
1551            handle_out->seqtree = (struct btree*)malloc(sizeof(struct btree));
1552            // Init the seq tree using the root bid of the source snapshot.
1553            btree_init_from_bid(handle_out->seqtree, (void *)handle_out->bhandle,
1554                                handle_out->btreeblkops, seq_kv_ops,
1555                                handle_out->config.blocksize,
1556                                handle_in->seqtree->root_bid);
1557        }
1558    } else{
1559        handle_out->seqtree = NULL;
1560    }
1561
1562    status = btreeblk_end(handle_out->bhandle);
1563    if (status != FDB_RESULT_SUCCESS) {
1564        const char *msg = "Snapshot clone operation fails due to the errors in "
1565            "btreeblk_end() in a database file '%s'\n";
1566        fdb_log(&handle_in->log_callback, status, msg, handle_in->file->filename);
1567    }
1568
1569    return status;
1570}
1571
1572fdb_status _fdb_open(fdb_kvs_handle *handle,
1573                     const char *filename,
1574                     fdb_filename_mode_t filename_mode,
1575                     const fdb_config *config)
1576{
1577    struct filemgr_config fconfig;
1578    struct kvs_stat stat, empty_stat;
1579    bid_t trie_root_bid = BLK_NOT_FOUND;
1580    bid_t seq_root_bid = BLK_NOT_FOUND;
1581    bid_t stale_root_bid = BLK_NOT_FOUND;
1582    fdb_seqnum_t seqnum = 0;
1583    filemgr_header_revnum_t header_revnum = 0;
1584    filemgr_header_revnum_t latest_header_revnum = 0;
1585    fdb_seqtree_opt_t seqtree_opt = config->seqtree_opt;
1586    uint64_t ndocs = 0;
1587    uint64_t ndeletes = 0;
1588    uint64_t datasize = 0;
1589    uint64_t deltasize = 0;
1590    uint64_t last_wal_flush_hdr_bid = BLK_NOT_FOUND;
1591    uint64_t kv_info_offset = BLK_NOT_FOUND;
1592    uint64_t version;
1593    uint64_t header_flags = 0;
1594    uint8_t header_buf[FDB_BLOCKSIZE];
1595    char *compacted_filename = NULL;
1596    char *prev_filename = NULL;
1597    size_t header_len = 0;
1598    bool multi_kv_instances = config->multi_kv_instances;
1599
1600    uint64_t nlivenodes = 0;
1601    bid_t hdr_bid = 0; // initialize to zero for in-memory snapshot
1602    char actual_filename[FDB_MAX_FILENAME_LEN];
1603    char virtual_filename[FDB_MAX_FILENAME_LEN];
1604    char *target_filename = NULL;
1605    fdb_status status;
1606
1607    if (filename == NULL) {
1608        return FDB_RESULT_INVALID_ARGS;
1609    }
1610    if (strlen(filename) > (FDB_MAX_FILENAME_LEN - 8)) {
1611        // filename (including path) length is supported up to
1612        // (FDB_MAX_FILENAME_LEN - 8) bytes.
1613        return FDB_RESULT_TOO_LONG_FILENAME;
1614    }
1615
1616    if (filename_mode == FDB_VFILENAME &&
1617        !compactor_is_valid_mode(filename, (fdb_config *)config)) {
1618        return FDB_RESULT_INVALID_COMPACTION_MODE;
1619    }
1620
1621    _fdb_init_file_config(config, &fconfig);
1622
1623    if (filename_mode == FDB_VFILENAME) {
1624        compactor_get_actual_filename(filename, actual_filename,
1625                                      config->compaction_mode, &handle->log_callback);
1626    } else {
1627        strcpy(actual_filename, filename);
1628    }
1629
1630    if ( config->compaction_mode == FDB_COMPACTION_MANUAL ||
1631         (config->compaction_mode == FDB_COMPACTION_AUTO   &&
1632          filename_mode == FDB_VFILENAME) ) {
1633        // 1) manual compaction mode, OR
1634        // 2) auto compaction mode + 'filename' is virtual filename
1635        // -> copy 'filename'
1636        target_filename = (char *)filename;
1637    } else {
1638        // otherwise (auto compaction mode + 'filename' is actual filename)
1639        // -> copy 'virtual_filename'
1640        compactor_get_virtual_filename(filename, virtual_filename);
1641        target_filename = virtual_filename;
1642    }
1643
1644    // If the user is requesting legacy CRC pass that down to filemgr
1645    if(config->flags & FDB_OPEN_WITH_LEGACY_CRC) {
1646        fconfig.options |= FILEMGR_CREATE_CRC32;
1647    }
1648
1649    handle->fileops = get_filemgr_ops();
1650    filemgr_open_result result = filemgr_open((char *)actual_filename,
1651                                              handle->fileops,
1652                                              &fconfig, &handle->log_callback);
1653    if (result.rv != FDB_RESULT_SUCCESS) {
1654        return (fdb_status) result.rv;
1655    }
1656    handle->file = result.file;
1657
1658    if (config->compaction_mode == FDB_COMPACTION_MANUAL &&
1659        strcmp(filename, actual_filename)) {
1660        // It is in-place compacted file if
1661        // 1) compaction mode is manual, and
1662        // 2) actual filename is different to the filename given by user.
1663        // In this case, set the in-place compaction flag.
1664        filemgr_set_in_place_compaction(handle->file, true);
1665    }
1666    if (filemgr_is_in_place_compaction_set(handle->file)) {
1667        // This file was in-place compacted.
1668        // set 'handle->filename' to the original filename to trigger file renaming
1669        compactor_get_virtual_filename(filename, virtual_filename);
1670        target_filename = virtual_filename;
1671    }
1672
1673    if (handle->filename) {
1674        handle->filename = (char *)realloc(handle->filename,
1675                                           strlen(target_filename)+1);
1676    } else {
1677        handle->filename = (char*)malloc(strlen(target_filename)+1);
1678    }
1679    strcpy(handle->filename, target_filename);
1680
1681    // If cloning from a snapshot handle, fdb_snapshot_open would have already
1682    // set handle->last_hdr_bid to the block id of required header, so rewind..
1683    if (handle->shandle && handle->last_hdr_bid) {
1684        status = filemgr_fetch_header(handle->file, handle->last_hdr_bid,
1685                                      header_buf, &header_len, &seqnum,
1686                                      &latest_header_revnum, &deltasize, &version,
1687                                      NULL, &handle->log_callback);
1688        if (status != FDB_RESULT_SUCCESS) {
1689            free(handle->filename);
1690            handle->filename = NULL;
1691            filemgr_close(handle->file, false, handle->filename,
1692                              &handle->log_callback);
1693            return status;
1694        }
1695    } else { // Normal open
1696        filemgr_get_header(handle->file, header_buf, &header_len,
1697                           &handle->last_hdr_bid, &seqnum, &latest_header_revnum);
1698        version = handle->file->version;
1699    }
1700
1701    // initialize the docio handle so kv headers may be read
1702    handle->dhandle = (struct docio_handle *)
1703                      calloc(1, sizeof(struct docio_handle));
1704    handle->dhandle->log_callback = &handle->log_callback;
1705    docio_init(handle->dhandle, handle->file, config->compress_document_body);
1706
1707    // fetch previous superblock bitmap info if exists
1708    // (this should be done after 'handle->dhandle' is initialized)
1709    if (handle->file->sb) {
1710        status = sb_bmp_fetch_doc(handle);
1711        if (status != FDB_RESULT_SUCCESS) {
1712            docio_free(handle->dhandle);
1713            free(handle->dhandle);
1714            free(handle->filename);
1715            handle->filename = NULL;
1716            filemgr_close(handle->file, false, handle->filename,
1717                              &handle->log_callback);
1718            return status;
1719        }
1720    }
1721
1722
1723    if (header_len > 0) {
1724        fdb_fetch_header(version, header_buf, &trie_root_bid, &seq_root_bid,
1725                         &stale_root_bid, &ndocs, &ndeletes, &nlivenodes,
1726                         &datasize, &last_wal_flush_hdr_bid, &kv_info_offset,
1727                         &header_flags, &compacted_filename, &prev_filename);
1728        // use existing setting for seqtree_opt
1729        if (header_flags & FDB_FLAG_SEQTREE_USE) {
1730            seqtree_opt = FDB_SEQTREE_USE;
1731        } else {
1732            seqtree_opt = FDB_SEQTREE_NOT_USE;
1733        }
1734        // Retrieve seqnum for multi-kv mode
1735        if (handle->kvs && handle->kvs->id > 0) {
1736            if (kv_info_offset != BLK_NOT_FOUND) {
1737                if (!filemgr_get_kv_header(handle->file)) {
1738                    struct kvs_header *kv_header;
1739                    _fdb_kvs_header_create(&kv_header);
1740                    // KV header already exists but not loaded .. read & import
1741                    fdb_kvs_header_read(kv_header, handle->dhandle,
1742                                        kv_info_offset, version, false);
1743                    if (!filemgr_set_kv_header(handle->file, kv_header,
1744                                               fdb_kvs_header_free)) {
1745                        _fdb_kvs_header_free(kv_header);
1746                    }
1747                }
1748                seqnum = _fdb_kvs_get_seqnum(handle->file->kv_header,
1749                                             handle->kvs->id);
1750            } else { // no kv_info offset, ok to set seqnum to zero
1751                seqnum = 0;
1752            }
1753        }
1754        // other flags
1755        if (header_flags & FDB_FLAG_ROOT_INITIALIZED) {
1756            handle->fhandle->flags |= FHANDLE_ROOT_INITIALIZED;
1757        }
1758        if (header_flags & FDB_FLAG_ROOT_CUSTOM_CMP) {
1759            handle->fhandle->flags |= FHANDLE_ROOT_CUSTOM_CMP;
1760        }
1761        // use existing setting for multi KV instance mode
1762        if (kv_info_offset == BLK_NOT_FOUND) {
1763            multi_kv_instances = false;
1764        } else {
1765            multi_kv_instances = true;
1766        }
1767    }
1768
1769    handle->config = *config;
1770    handle->config.seqtree_opt = seqtree_opt;
1771    handle->config.multi_kv_instances = multi_kv_instances;
1772
1773    if (handle->shandle && handle->max_seqnum == FDB_SNAPSHOT_INMEM) {
1774        // Either an in-memory snapshot or cloning from an existing snapshot..
1775        hdr_bid = 0; // This prevents _fdb_restore_wal() as incoming handle's
1776                     // *_open() should have already restored it
1777    } else { // Persisted snapshot or file rollback..
1778
1779        // get the BID of the latest block
1780        // (it is OK if the block is not a DB header)
1781        bool dirty_data_exists = false;
1782        struct superblock *sb = handle->file->sb;
1783
1784        if (sb_bmp_exists(sb)) {
1785            dirty_data_exists = false;
1786            bid_t sb_last_hdr_bid = atomic_get_uint64_t(&sb->last_hdr_bid);
1787            if (sb_last_hdr_bid != BLK_NOT_FOUND) {
1788                // add 1 since we subtract 1 from 'hdr_bid' below soon
1789                hdr_bid = sb_last_hdr_bid + 1;
1790                if (atomic_get_uint64_t(&sb->cur_alloc_bid) != hdr_bid) {
1791                    // seq number has been increased since the last commit
1792                    seqnum = fdb_kvs_get_committed_seqnum(handle);
1793                }
1794            } else {
1795                hdr_bid = BLK_NOT_FOUND;
1796            }
1797        } else {
1798            hdr_bid = filemgr_get_pos(handle->file) / FDB_BLOCKSIZE;
1799            dirty_data_exists = (hdr_bid > handle->last_hdr_bid);
1800        }
1801
1802        if (hdr_bid == BLK_NOT_FOUND ||
1803            (sb && hdr_bid <= sb->config->num_sb)) {
1804            hdr_bid = 0;
1805        } else if (hdr_bid > 0) {
1806            --hdr_bid;
1807        }
1808
1809        if (handle->max_seqnum) {
1810            struct kvs_stat stat_ori;
1811            // backup original stats
1812            if (handle->kvs) {
1813                _kvs_stat_get(handle->file, handle->kvs->id, &stat_ori);
1814            } else {
1815                _kvs_stat_get(handle->file, 0, &stat_ori);
1816            }
1817
1818            if (dirty_data_exists){
1819                // uncommitted data exists beyond the last DB header
1820                // get the last committed seq number
1821                fdb_seqnum_t seq_commit;
1822                seq_commit = fdb_kvs_get_committed_seqnum(handle);
1823                if (seq_commit == 0 || seq_commit < handle->max_seqnum) {
1824                    // In case, snapshot_open is attempted with latest uncommitted
1825                    // sequence number
1826                    header_len = 0;
1827                } else if (seq_commit == handle->max_seqnum) {
1828                    // snapshot/rollback on the latest commit header
1829                    seqnum = seq_commit; // skip file reverse scan
1830                }
1831                hdr_bid = filemgr_get_header_bid(handle->file);
1832            }
1833            // Reverse scan the file to locate the DB header with seqnum marker
1834            header_revnum = latest_header_revnum;
1835            while (header_len && seqnum != handle->max_seqnum) {
1836                hdr_bid = filemgr_fetch_prev_header(handle->file, hdr_bid,
1837                                          header_buf, &header_len, &seqnum,
1838                                          &header_revnum, NULL, &version, NULL,
1839                                          &handle->log_callback);
1840                if (header_len == 0) {
1841                    continue; // header doesn't exist
1842                }
1843                fdb_fetch_header(version, header_buf, &trie_root_bid,
1844                                 &seq_root_bid, &stale_root_bid,
1845                                 &ndocs, &ndeletes, &nlivenodes,
1846                                 &datasize, &last_wal_flush_hdr_bid,
1847                                 &kv_info_offset, &header_flags,
1848                                 &compacted_filename, NULL);
1849                handle->last_hdr_bid = hdr_bid;
1850
1851                if (!handle->kvs || handle->kvs->id == 0) {
1852                    // single KVS mode OR default KVS
1853                    if (!handle->shandle) {
1854                        // rollback
1855                        struct kvs_stat stat_dst;
1856                        _kvs_stat_get(handle->file, 0, &stat_dst);
1857                        stat_dst.ndocs = ndocs;
1858                        stat_dst.ndeletes = ndeletes;
1859                        stat_dst.datasize = datasize;
1860                        stat_dst.nlivenodes = nlivenodes;
1861                        stat_dst.deltasize = deltasize;
1862                        _kvs_stat_set(handle->file, 0, stat_dst);
1863                    }
1864                    continue;
1865                }
1866
1867                int64_t doc_offset;
1868                struct kvs_header *kv_header;
1869                struct docio_object doc;
1870
1871                _fdb_kvs_header_create(&kv_header);
1872                memset(&doc, 0, sizeof(struct docio_object));
1873                doc_offset = docio_read_doc(handle->dhandle,
1874                                            kv_info_offset, &doc, true);
1875
1876                if (doc_offset <= 0) {
1877                    header_len = 0; // fail
1878                    _fdb_kvs_header_free(kv_header);
1879                } else {
1880                    _fdb_kvs_header_import(kv_header, doc.body,
1881                                           doc.length.bodylen, version, false);
1882                    // get local sequence number for the KV instance
1883                    seqnum = _fdb_kvs_get_seqnum(kv_header,
1884                                                 handle->kvs->id);
1885                    if (!handle->shandle) {
1886                        // rollback: replace kv_header stats
1887                        // read from the current header's kv_header
1888                        struct kvs_stat stat_src, stat_dst;
1889                        _kvs_stat_get_kv_header(kv_header,
1890                                                handle->kvs->id,
1891                                                &stat_src);
1892                        _kvs_stat_get(handle->file,
1893                                      handle->kvs->id,
1894                                      &stat_dst);
1895                        // update ndocs, datasize, nlivenodes
1896                        // into the current file's kv_header
1897                        // Note: stats related to WAL should not be updated
1898                        //       at this time. They will be adjusted through
1899                        //       discard & restore routines below.
1900                        stat_dst.ndocs = stat_src.ndocs;
1901                        stat_dst.datasize = stat_src.datasize;
1902                        stat_dst.nlivenodes = stat_src.nlivenodes;
1903                        _kvs_stat_set(handle->file,
1904                                      handle->kvs->id,
1905                                      stat_dst);
1906                    }
1907                    _fdb_kvs_header_free(kv_header);
1908                    free_docio_object(&doc, 1, 1, 1);
1909                }
1910            }
1911
1912            if (header_len && // header exists
1913                config->block_reusing_threshold > 0 && // block reuse is enabled
1914                config->block_reusing_threshold < 100 &&
1915                header_revnum < sb_get_min_live_revnum(handle->file)) {
1916                // cannot perform rollback/snapshot beyond the last live header
1917                header_len = 0;
1918            }
1919
1920            if (!header_len) { // Marker MUST match that of DB commit!
1921                // rollback original stats
1922                if (handle->kvs) {
1923                    _kvs_stat_get(handle->file, handle->kvs->id, &stat_ori);
1924                } else {
1925                    _kvs_stat_get(handle->file, 0, &stat_ori);
1926                }
1927
1928                docio_free(handle->dhandle);
1929                free(handle->dhandle);
1930                free(handle->filename);
1931                free(prev_filename);
1932                handle->filename = NULL;
1933                filemgr_close(handle->file, false, handle->filename,
1934                              &handle->log_callback);
1935                return FDB_RESULT_NO_DB_INSTANCE;
1936            }
1937
1938            if (!handle->shandle) { // Rollback mode, destroy file WAL..
1939                if (handle->config.multi_kv_instances) {
1940                    // multi KV instance mode
1941                    // clear only WAL items belonging to the instance
1942                    wal_close_kv_ins(handle->file,
1943                                     (handle->kvs)?(handle->kvs->id):(0),
1944                                     &handle->log_callback);
1945                } else {
1946                    wal_shutdown(handle->file, &handle->log_callback);
1947                }
1948            }
1949        } else { // snapshot to sequence number 0 requested..
1950            if (handle->shandle) { // fdb_snapshot_open API call
1951                if (seqnum) {
1952                    // Database currently has a non-zero seq number,
1953                    // but the snapshot was requested with a seq number zero.
1954                    docio_free(handle->dhandle);
1955                    free(handle->dhandle);
1956                    free(handle->filename);
1957                    free(prev_filename);
1958                    handle->filename = NULL;
1959                    filemgr_close(handle->file, false, handle->filename,
1960                                  &handle->log_callback);
1961                    return FDB_RESULT_NO_DB_INSTANCE;
1962                }
1963            } // end of zero max_seqnum but non-rollback check
1964        } // end of zero max_seqnum check
1965    } // end of durable snapshot locating
1966
1967    handle->btreeblkops = btreeblk_get_ops();
1968    handle->bhandle = (struct btreeblk_handle *)
1969                      calloc(1, sizeof(struct btreeblk_handle));
1970    handle->bhandle->log_callback = &handle->log_callback;
1971
1972    handle->dirty_updates = 0;
1973
1974    if (handle->config.compaction_buf_maxsize == 0) {
1975        handle->config.compaction_buf_maxsize = FDB_COMP_BUF_MINSIZE;
1976    }
1977
1978    btreeblk_init(handle->bhandle, handle->file, handle->file->blocksize);
1979
1980    handle->cur_header_revnum = latest_header_revnum;
1981    if (header_revnum) {
1982        if (filemgr_is_rollback_on(handle->file)) {
1983            // rollback mode
1984            // set rollback header revnum
1985            handle->rollback_revnum = header_revnum;
1986        } else {
1987            // snapshot mode (only for snapshot)
1988            handle->cur_header_revnum = header_revnum;
1989        }
1990    }
1991    handle->last_wal_flush_hdr_bid = last_wal_flush_hdr_bid;
1992
1993    memset(&empty_stat, 0x0, sizeof(empty_stat));
1994    _kvs_stat_get(handle->file, 0, &stat);
1995    if (!memcmp(&stat, &empty_stat, sizeof(stat))) { // first open
1996        // sync (default) KVS stat with DB header
1997        stat.nlivenodes = nlivenodes;
1998        stat.ndocs = ndocs;
1999        stat.datasize = datasize;
2000        _kvs_stat_set(handle->file, 0, stat);
2001    }
2002
2003    handle->kv_info_offset = kv_info_offset;
2004    if (handle->config.multi_kv_instances && !handle->shandle) {
2005        // multi KV instance mode
2006        filemgr_mutex_lock(handle->file);
2007        if (kv_info_offset == BLK_NOT_FOUND) {
2008            // there is no KV header .. create & initialize
2009            fdb_kvs_header_create(handle->file);
2010            // TODO: If another handle is opened before the first header is appended,
2011            // an unnecessary KV info doc is appended. We need to address it.
2012            kv_info_offset = fdb_kvs_header_append(handle);
2013        } else if (handle->file->kv_header == NULL) {
2014            // KV header already exists but not loaded .. read & import
2015            fdb_kvs_header_create(handle->file);
2016            fdb_kvs_header_read(handle->file->kv_header, handle->dhandle,
2017                                kv_info_offset, version, false);
2018        }
2019        filemgr_mutex_unlock(handle->file);
2020
2021        // validation check for key order of all KV stores
2022        if (handle == handle->fhandle->root) {
2023            fdb_status fs = fdb_kvs_cmp_check(handle);
2024            if (fs != FDB_RESULT_SUCCESS) { // cmp function mismatch
2025                docio_free(handle->dhandle);
2026                free(handle->dhandle);
2027                btreeblk_free(handle->bhandle);
2028                free(handle->bhandle);
2029                free(handle->filename);
2030                handle->filename = NULL;
2031                filemgr_close(handle->file, false, handle->filename,
2032                              &handle->log_callback);
2033                return fs;
2034            }
2035        }
2036    }
2037    handle->kv_info_offset = kv_info_offset;
2038
2039    if (handle->kv_info_offset != BLK_NOT_FOUND &&
2040        handle->kvs == NULL) {
2041        // multi KV instance mode .. turn on config flag
2042        handle->config.multi_kv_instances = true;
2043        // only super handle can be opened using fdb_open(...)
2044        fdb_kvs_info_create(NULL, handle, handle->file, NULL);
2045    }
2046
2047    if (handle->shandle) { // Populate snapshot stats..
2048        if (kv_info_offset == BLK_NOT_FOUND) { // Single KV mode
2049            memset(&handle->shandle->stat, 0x0,
2050                    sizeof(handle->shandle->stat));
2051            handle->shandle->stat.ndocs = ndocs;
2052            handle->shandle->stat.datasize = datasize;
2053            handle->shandle->stat.nlivenodes = nlivenodes;
2054        } else { // Multi KV instance mode, populate specific kv stats
2055            memset(&handle->shandle->stat, 0x0,
2056                    sizeof(handle->shandle->stat));
2057            _kvs_stat_get(handle->file, handle->kvs->id,
2058                    &handle->shandle->stat);
2059            // Since wal is restored below, we have to reset
2060            // wal stats to zero.
2061            handle->shandle->stat.wal_ndeletes = 0;
2062            handle->shandle->stat.wal_ndocs = 0;
2063        }
2064    }
2065
2066    // initialize pointer to the global operational stats of this KV store
2067    handle->op_stats = filemgr_get_ops_stats(handle->file, handle->kvs);
2068    if (!handle->op_stats) {
2069        const char *msg = "Database open fails due to the error in retrieving "
2070            "the global operational stats of KV store in a database file '%s'\n";
2071        fdb_log(&handle->log_callback, FDB_RESULT_OPEN_FAIL, msg,
2072                handle->file->filename);
2073        return FDB_RESULT_OPEN_FAIL;
2074    }
2075
2076    handle->trie = (struct hbtrie *)malloc(sizeof(struct hbtrie));
2077    hbtrie_init(handle->trie, config->chunksize, OFFSET_SIZE,
2078                handle->file->blocksize, trie_root_bid,
2079                (void *)handle->bhandle, handle->btreeblkops,
2080                (void *)handle->dhandle, _fdb_readkey_wrap);
2081    // set aux for cmp wrapping function
2082    hbtrie_set_leaf_height_limit(handle->trie, 0xff);
2083    hbtrie_set_leaf_cmp(handle->trie, _fdb_custom_cmp_wrap);
2084
2085    if (handle->kvs) {
2086        hbtrie_set_map_function(handle->trie, fdb_kvs_find_cmp_chunk);
2087    }
2088
2089    handle->seqnum = seqnum;
2090    if (handle->config.seqtree_opt == FDB_SEQTREE_USE) {
2091        if (handle->config.multi_kv_instances) {
2092            // multi KV instance mode .. HB+trie
2093            handle->seqtrie = (struct hbtrie *)malloc(sizeof(struct hbtrie));
2094            hbtrie_init(handle->seqtrie, sizeof(fdb_kvs_id_t), OFFSET_SIZE,
2095                        handle->file->blocksize, seq_root_bid,
2096                        (void *)handle->bhandle, handle->btreeblkops,
2097                        (void *)handle->dhandle, _fdb_readseq_wrap);
2098
2099        } else {
2100            // single KV instance mode .. normal B+tree
2101            struct btree_kv_ops *seq_kv_ops =
2102                (struct btree_kv_ops *)malloc(sizeof(struct btree_kv_ops));
2103            seq_kv_ops = btree_kv_get_kb64_vb64(seq_kv_ops);
2104            seq_kv_ops->cmp = _cmp_uint64_t_endian_safe;
2105
2106            handle->seqtree = (struct btree*)malloc(sizeof(struct btree));
2107            if (seq_root_bid == BLK_NOT_FOUND) {
2108                btree_init(handle->seqtree, (void *)handle->bhandle,
2109                           handle->btreeblkops, seq_kv_ops,
2110                           handle->config.blocksize, sizeof(fdb_seqnum_t),
2111                           OFFSET_SIZE, 0x0, NULL);
2112            }else{
2113                btree_init_from_bid(handle->seqtree, (void *)handle->bhandle,
2114                                    handle->btreeblkops, seq_kv_ops,
2115                                    handle->config.blocksize, seq_root_bid);
2116            }
2117        }
2118    }else{
2119        handle->seqtree = NULL;
2120    }
2121
2122    // Stale-block tree (supported since MAGIC_002)
2123    // this tree is independent to multi/single KVS mode option
2124    if (ver_staletree_support(handle->file->version)) {
2125        // normal B+tree
2126        struct btree_kv_ops *stale_kv_ops =
2127            (struct btree_kv_ops *)calloc(1, sizeof(struct btree_kv_ops));
2128        stale_kv_ops = btree_kv_get_kb64_vb64(stale_kv_ops);
2129        stale_kv_ops->cmp = _cmp_uint64_t_endian_safe;
2130
2131        handle->staletree = (struct btree*)calloc(1, sizeof(struct btree));
2132        if (stale_root_bid == BLK_NOT_FOUND) {
2133            btree_init(handle->staletree, (void *)handle->bhandle,
2134                       handle->btreeblkops, stale_kv_ops,
2135                       handle->config.blocksize, sizeof(filemgr_header_revnum_t),
2136                       OFFSET_SIZE, 0x0, NULL);
2137         }else{
2138            btree_init_from_bid(handle->staletree, (void *)handle->bhandle,
2139                                handle->btreeblkops, stale_kv_ops,
2140                                handle->config.blocksize, stale_root_bid);
2141            // prefetch stale info into memory
2142            fdb_load_inmem_stale_info(handle);
2143         }
2144    } else {
2145        handle->staletree = NULL;
2146    }
2147
2148    if (handle->config.multi_kv_instances && handle->max_seqnum) {
2149        // restore only docs belonging to the KV instance
2150        // handle->kvs should not be NULL
2151        _fdb_restore_wal(handle, FDB_RESTORE_KV_INS,
2152                         hdr_bid, (handle->kvs)?(handle->kvs->id):(0));
2153    } else {
2154        // normal restore
2155        _fdb_restore_wal(handle, FDB_RESTORE_NORMAL, hdr_bid, 0);
2156    }
2157
2158    if (compacted_filename &&
2159        filemgr_get_file_status(handle->file) == FILE_NORMAL &&
2160        !(config->flags & FDB_OPEN_FLAG_RDONLY)) { // do not recover read-only
2161        _fdb_recover_compaction(handle, compacted_filename);
2162    }
2163
2164    if (prev_filename) {
2165        if (!handle->shandle && strcmp(prev_filename, handle->file->filename)) {
2166            // record the old filename into the file handle of current file
2167            // and REMOVE old file on the first open
2168            // WARNING: snapshots must have been opened before this call
2169            if (filemgr_update_file_status(handle->file,
2170                                           filemgr_get_file_status(handle->file),
2171                                           prev_filename)) {
2172                // Open the old file with read-only mode.
2173                // (Temporarily disable log callback at this time since
2174                //  the old file might be already removed.)
2175                err_log_callback dummy_cb;
2176                dummy_cb.callback = fdb_dummy_log_callback;
2177                dummy_cb.ctx_data = NULL;
2178                fconfig.options = FILEMGR_READONLY;
2179                filemgr_open_result result = filemgr_open(prev_filename,
2180                                                          handle->fileops,
2181                                                          &fconfig,
2182                                                          &dummy_cb);
2183                if (result.file) {
2184                    filemgr_remove_pending(result.file, handle->file,
2185                                           &handle->log_callback);
2186                    filemgr_close(result.file, 0, handle->filename,
2187                                  &handle->log_callback);
2188                }
2189            } else {
2190                free(prev_filename);
2191            }
2192        } else {
2193            free(prev_filename);
2194        }
2195    }
2196
2197    status = btreeblk_end(handle->bhandle);
2198    if (status != FDB_RESULT_SUCCESS) {
2199        // When fdb_kvs_open() is being issued in parallel with fdb_open()
2200        // it is possible that this call (fdb_open()) hits a write failure
2201        // because the btreeblock to be written was already made immutable
2202        // by the commit from the fdb_kvs_open(). Simpy ignore this error case.
2203        if (status == FDB_RESULT_WRITE_FAIL) {
2204            if (filemgr_get_header_revnum(handle->file)
2205                                             == latest_header_revnum) {
2206                return status;
2207            } else {
2208                status = FDB_RESULT_SUCCESS;
2209            }
2210        } else {
2211            return status;
2212        }
2213    }
2214
2215    // do not register read-only handles
2216    if (!(config->flags & FDB_OPEN_FLAG_RDONLY)) {
2217        if (config->compaction_mode == FDB_COMPACTION_AUTO) {
2218            status = compactor_register_file(handle->file,
2219                                             (fdb_config *)config,
2220                                             &handle->log_callback);
2221        }
2222        if (status == FDB_RESULT_SUCCESS) {
2223            status = bgflusher_register_file(handle->file,
2224                                             (fdb_config *)config,
2225                                             &handle->log_callback);
2226        }
2227    }
2228
2229    return status;
2230}
2231
2232LIBFDB_API
2233fdb_status fdb_set_log_callback(fdb_kvs_handle *handle,
2234                                fdb_log_callback log_callback,
2235                                void *ctx_data)
2236{
2237    if (!handle) {
2238        return FDB_RESULT_INVALID_HANDLE;
2239    }
2240
2241    handle->log_callback.callback = log_callback;
2242    handle->log_callback.ctx_data = ctx_data;
2243    return FDB_RESULT_SUCCESS;
2244}
2245
2246LIBFDB_API
2247void fdb_set_fatal_error_callback(fdb_fatal_error_callback err_callback)
2248{
2249    fatal_error_callback = err_callback;
2250}
2251
2252LIBFDB_API
2253fdb_status fdb_doc_create(fdb_doc **doc, const void *key, size_t keylen,
2254                          const void *meta, size_t metalen,
2255                          const void *body, size_t bodylen)
2256{
2257    if (doc == NULL || keylen > FDB_MAX_KEYLEN ||
2258        metalen > FDB_MAX_METALEN || bodylen > FDB_MAX_BODYLEN) {
2259        return FDB_RESULT_INVALID_ARGS;
2260    }
2261
2262    *doc = (fdb_doc*)calloc(1, sizeof(fdb_doc));
2263    if (*doc == NULL) { // LCOV_EXCL_START
2264        return FDB_RESULT_ALLOC_FAIL;
2265    } // LCOV_EXCL_STOP
2266
2267    (*doc)->seqnum = SEQNUM_NOT_USED;
2268
2269    if (key && keylen > 0) {
2270        (*doc)->key = (void *)malloc(keylen);
2271        if ((*doc)->key == NULL) { // LCOV_EXCL_START
2272            return FDB_RESULT_ALLOC_FAIL;
2273        } // LCOV_EXCL_STOP
2274        memcpy((*doc)->key, key, keylen);
2275        (*doc)->keylen = keylen;
2276    } else {
2277        (*doc)->key = NULL;
2278        (*doc)->keylen = 0;
2279    }
2280
2281    if (meta && metalen > 0) {
2282        (*doc)->meta = (void *)malloc(metalen);
2283        if ((*doc)->meta == NULL) { // LCOV_EXCL_START
2284            return FDB_RESULT_ALLOC_FAIL;
2285        } // LCOV_EXCL_STOP
2286        memcpy((*doc)->meta, meta, metalen);
2287        (*doc)->metalen = metalen;
2288    } else {
2289        (*doc)->meta = NULL;
2290        (*doc)->metalen = 0;
2291    }
2292
2293    if (body && bodylen > 0) {
2294        (*doc)->body = (void *)malloc(bodylen);
2295        if ((*doc)->body == NULL) { // LCOV_EXCL_START
2296            return FDB_RESULT_ALLOC_FAIL;
2297        } // LCOV_EXCL_STOP
2298        memcpy((*doc)->body, body, bodylen);
2299        (*doc)->bodylen = bodylen;
2300    } else {
2301        (*doc)->body = NULL;
2302        (*doc)->bodylen = 0;
2303    }
2304
2305    return FDB_RESULT_SUCCESS;
2306}
2307
2308LIBFDB_API
2309fdb_status fdb_doc_update(fdb_doc **doc,
2310                          const void *meta, size_t metalen,
2311                          const void *body, size_t bodylen)
2312{
2313    if (doc == NULL ||
2314        metalen > FDB_MAX_METALEN || bodylen > FDB_MAX_BODYLEN) {
2315        return FDB_RESULT_INVALID_ARGS;
2316    }
2317    if (*doc == NULL) {
2318        return FDB_RESULT_INVALID_ARGS;
2319    }
2320
2321    if (meta && metalen > 0) {
2322        // free previous metadata
2323        free((*doc)->meta);
2324        // allocate new metadata
2325        (*doc)->meta = (void *)malloc(metalen);
2326        if ((*doc)->meta == NULL) { // LCOV_EXCL_START
2327            return FDB_RESULT_ALLOC_FAIL;
2328        } // LCOV_EXCL_STOP
2329        memcpy((*doc)->meta, meta, metalen);
2330        (*doc)->metalen = metalen;
2331    }
2332
2333    if (body && bodylen > 0) {
2334        // free previous body
2335        free((*doc)->body);
2336        // allocate new body
2337        (*doc)->body = (void *)malloc(bodylen);
2338        if ((*doc)->body == NULL) { // LCOV_EXCL_START
2339            return FDB_RESULT_ALLOC_FAIL;
2340        } // LCOV_EXCL_STOP
2341        memcpy((*doc)->body, body, bodylen);
2342        (*doc)->bodylen = bodylen;
2343    }
2344
2345    (*doc)->seqnum = SEQNUM_NOT_USED;
2346    return FDB_RESULT_SUCCESS;
2347}
2348
2349LIBFDB_API
2350void fdb_doc_set_seqnum(fdb_doc *doc,
2351                        const fdb_seqnum_t seqnum)
2352{
2353    if (doc) {
2354        doc->seqnum = seqnum;
2355        if (seqnum != SEQNUM_NOT_USED) {
2356            doc->flags |= FDB_CUSTOM_SEQNUM; // fdb_set will now use above seqnum
2357        } else { // reset custom seqnum flag, fdb_set will now generate new seqnum
2358            doc->flags &= ~FDB_CUSTOM_SEQNUM;
2359        }
2360    }
2361}
2362
2363// doc MUST BE allocated by malloc
2364LIBFDB_API
2365fdb_status fdb_doc_free(fdb_doc *doc)
2366{
2367    if (doc) {
2368        free(doc->key);
2369        free(doc->meta);
2370        free(doc->body);
2371        free(doc);
2372    }
2373    return FDB_RESULT_SUCCESS;
2374}
2375
2376INLINE uint64_t _fdb_wal_get_old_offset(void *voidhandle,
2377                                        struct wal_item *item)
2378{
2379    fdb_kvs_handle *handle = (fdb_kvs_handle *)voidhandle;
2380    uint64_t old_offset = 0;
2381
2382    if (item->action == WAL_ACT_REMOVE) {
2383        // For immediate remove, old_offset value is critical
2384        // so that we should get an exact value.
2385        hbtrie_find(handle->trie,
2386                    item->header->key,
2387                    item->header->keylen,
2388                    (void*)&old_offset);
2389    } else {
2390        hbtrie_find_offset(handle->trie,
2391                           item->header->key,
2392                           item->header->keylen,
2393                           (void*)&old_offset);
2394    }
2395    btreeblk_end(handle->bhandle);
2396    old_offset = _endian_decode(old_offset);
2397
2398    return old_offset;
2399}
2400
2401// A stale sequence number entry that can be purged from the sequence tree
2402// during the WAL flush.
2403struct wal_stale_seq_entry {
2404    fdb_kvs_id_t kv_id;
2405    fdb_seqnum_t seqnum;
2406    struct avl_node avl_entry;
2407};
2408
2409// Delta changes in KV store stats during the WAL flush
2410struct wal_kvs_delta_stat {
2411    fdb_kvs_id_t kv_id;
2412    int64_t nlivenodes;
2413    int64_t ndocs;
2414    int64_t ndeletes;
2415    int64_t datasize;
2416    int64_t deltasize;
2417    struct avl_node avl_entry;
2418};
2419
2420INLINE int _fdb_seq_entry_cmp(struct avl_node *a, struct avl_node *b, void *aux)
2421{
2422    (void) aux;
2423    struct wal_stale_seq_entry *entry1 = _get_entry(a, struct wal_stale_seq_entry,
2424                                                    avl_entry);
2425    struct wal_stale_seq_entry *entry2 = _get_entry(b, struct wal_stale_seq_entry,
2426                                                    avl_entry);
2427    if (entry1->kv_id < entry2->kv_id) {
2428        return -1;
2429    } else if (entry1->kv_id > entry2->kv_id) {
2430        return 1;
2431    } else {
2432        return _CMP_U64(entry1->seqnum, entry2->seqnum);
2433    }
2434}
2435
2436
2437// Compare function to sort KVS delta stat entries in the AVL tree during WAL flush
2438INLINE int _kvs_delta_stat_cmp(struct avl_node *a, struct avl_node *b, void *aux)
2439{
2440    (void) aux;
2441    struct wal_kvs_delta_stat *stat1 = _get_entry(a, struct wal_kvs_delta_stat,
2442                                                  avl_entry);
2443    struct wal_kvs_delta_stat *stat2 = _get_entry(b, struct wal_kvs_delta_stat,
2444                                                  avl_entry);
2445    if (stat1->kv_id < stat2->kv_id) {
2446        return -1;
2447    } else if (stat1->kv_id > stat2->kv_id) {
2448        return 1;
2449    } else {
2450        return 0;
2451    }
2452}
2453
2454INLINE void _fdb_wal_flush_seq_purge(void *dbhandle,
2455                                     struct avl_tree *stale_seqnum_list,
2456                                     struct avl_tree *kvs_delta_stats)
2457{
2458    fdb_seqnum_t _seqnum;
2459    int64_t nlivenodes;
2460    int64_t ndeltanodes;
2461    int64_t delta;
2462    uint8_t kvid_seqnum[sizeof(fdb_kvs_id_t) + sizeof(fdb_seqnum_t)];
2463    struct wal_stale_seq_entry *seq_entry;
2464    struct wal_kvs_delta_stat *delta_stat;
2465    struct wal_kvs_delta_stat kvs_delta_query;
2466
2467    fdb_kvs_handle *handle = (fdb_kvs_handle *)dbhandle;
2468    struct avl_node *node = avl_first(stale_seqnum_list);
2469    while (node) {
2470        seq_entry = _get_entry(node, struct wal_stale_seq_entry, avl_entry);
2471        node = avl_next(node);
2472        nlivenodes = handle->bhandle->nlivenodes;
2473        ndeltanodes = handle->bhandle->ndeltanodes;
2474        _seqnum = _endian_encode(seq_entry->seqnum);
2475        if (handle->kvs) {
2476            // multi KV instance mode .. HB+trie
2477            kvid2buf(sizeof(fdb_kvs_id_t), seq_entry->kv_id, kvid_seqnum);
2478            memcpy(kvid_seqnum + sizeof(fdb_kvs_id_t), &_seqnum, sizeof(fdb_seqnum_t));
2479            hbtrie_remove(handle->seqtrie, (void*)kvid_seqnum,
2480                          sizeof(fdb_kvs_id_t) + sizeof(fdb_seqnum_t));
2481        } else {
2482            btree_remove(handle->seqtree, (void*)&_seqnum);
2483        }
2484        btreeblk_end(handle->bhandle);
2485
2486        kvs_delta_query.kv_id = seq_entry->kv_id;
2487        avl_node *delta_stat_node = avl_search(kvs_delta_stats,
2488                                               &kvs_delta_query.avl_entry,
2489                                               _kvs_delta_stat_cmp);
2490        if (delta_stat_node) {
2491            delta_stat = _get_entry(delta_stat_node, struct wal_kvs_delta_stat,
2492                                    avl_entry);
2493            delta = handle->bhandle->nlivenodes - nlivenodes;
2494            delta_stat->nlivenodes += delta;
2495            delta = handle->bhandle->ndeltanodes - ndeltanodes;
2496            delta *= handle->config.blocksize;
2497            delta_stat->deltasize += delta;
2498        }
2499        avl_remove(stale_seqnum_list, &seq_entry->avl_entry);
2500        free(seq_entry);
2501    }
2502}
2503
2504INLINE void _fdb_wal_flush_kvs_delta_stats(struct filemgr *file,
2505                                           struct avl_tree *kvs_delta_stats)
2506{
2507    struct avl_node *node;
2508    struct wal_kvs_delta_stat *delta_stat;
2509    node = avl_first(kvs_delta_stats);
2510    while (node) {
2511        delta_stat = _get_entry(node, struct wal_kvs_delta_stat, avl_entry);
2512        node = avl_next(node);
2513        _kvs_stat_update_attr(file, delta_stat->kv_id,
2514                              KVS_STAT_DATASIZE, delta_stat->datasize);
2515        _kvs_stat_update_attr(file, delta_stat->kv_id,
2516                              KVS_STAT_NDOCS, delta_stat->ndocs);
2517        _kvs_stat_update_attr(file, delta_stat->kv_id,
2518                              KVS_STAT_NDELETES, delta_stat->ndeletes);
2519        _kvs_stat_update_attr(file, delta_stat->kv_id,
2520                              KVS_STAT_NLIVENODES, delta_stat->nlivenodes);
2521        _kvs_stat_update_attr(file, delta_stat->kv_id,
2522                              KVS_STAT_DELTASIZE, delta_stat->deltasize);
2523        avl_remove(kvs_delta_stats, &delta_stat->avl_entry);
2524        free(delta_stat);
2525    }
2526}
2527
2528INLINE fdb_status _fdb_wal_flush_func(void *voidhandle,
2529                                      struct wal_item *item,
2530                                      struct avl_tree *stale_seqnum_list,
2531                                      struct avl_tree *kvs_delta_stats)
2532{
2533    hbtrie_result hr;
2534    fdb_kvs_handle *handle = (fdb_kvs_handle *)voidhandle;
2535    fdb_seqnum_t _seqnum;
2536    fdb_kvs_id_t kv_id = 0;
2537    fdb_status fs = FDB_RESULT_SUCCESS;
2538    uint8_t *var_key = alca(uint8_t, handle->config.chunksize);
2539    int size_id, size_seq;
2540    uint8_t *kvid_seqnum;
2541    uint64_t old_offset;
2542    int64_t _offset;
2543    int64_t delta;
2544    struct docio_object _doc;
2545    struct filemgr *file = handle->dhandle->file;
2546
2547    memset(var_key, 0, handle->config.chunksize);
2548    if (handle->kvs) {
2549        buf2kvid(handle->config.chunksize, item->header->key, &kv_id);
2550    } else {
2551        kv_id = 0;
2552    }
2553
2554    struct wal_kvs_delta_stat *kvs_delta_stat;
2555    struct wal_kvs_delta_stat kvs_delta_query;
2556    kvs_delta_query.kv_id = kv_id;
2557    avl_node *delta_stat_node = avl_search(kvs_delta_stats,
2558                                           &kvs_delta_query.avl_entry,
2559                                           _kvs_delta_stat_cmp);
2560    if (delta_stat_node) {
2561        kvs_delta_stat = _get_entry(delta_stat_node, struct wal_kvs_delta_stat,
2562                                    avl_entry);
2563    } else {
2564        kvs_delta_stat = (struct wal_kvs_delta_stat *)
2565            calloc(1, sizeof(struct wal_kvs_delta_stat));
2566        kvs_delta_stat->kv_id = kv_id;
2567        avl_insert(kvs_delta_stats, &kvs_delta_stat->avl_entry,
2568                   _kvs_delta_stat_cmp);
2569    }
2570
2571    int64_t nlivenodes = handle->bhandle->nlivenodes;
2572    int64_t ndeltanodes = handle->bhandle->ndeltanodes;
2573
2574    if (item->action == WAL_ACT_INSERT ||
2575        item->action == WAL_ACT_LOGICAL_REMOVE) {
2576        _offset = _endian_encode(item->offset);
2577
2578        hbtrie_insert(handle->trie,
2579                      item->header->key,
2580                      item->header->keylen,
2581                      (void *)&_offset,
2582                      (void *)&old_offset);
2583
2584        fs = btreeblk_end(handle->bhandle);
2585        if (fs != FDB_RESULT_SUCCESS) {
2586            return fs;
2587        }
2588        old_offset = _endian_decode(old_offset);
2589
2590        if (handle->config.seqtree_opt == FDB_SEQTREE_USE) {
2591            _seqnum = _endian_encode(item->seqnum);
2592            if (handle->kvs) {
2593                // multi KV instance mode .. HB+trie
2594                uint64_t old_offset_local;
2595
2596                size_id = sizeof(fdb_kvs_id_t);
2597                size_seq = sizeof(fdb_seqnum_t);
2598                kvid_seqnum = alca(uint8_t, size_id + size_seq);
2599                kvid2buf(size_id, kv_id, kvid_seqnum);
2600                memcpy(kvid_seqnum + size_id, &_seqnum, size_seq);
2601                hbtrie_insert(handle->seqtrie, kvid_seqnum, size_id + size_seq,
2602                              (void *)&_offset, (void *)&old_offset_local);
2603            } else {
2604                btree_insert(handle->seqtree, (void *)&_seqnum,
2605                             (void *)&_offset);
2606            }
2607            fs = btreeblk_end(handle->bhandle);
2608            if (fs != FDB_RESULT_SUCCESS) {
2609                return fs;
2610            }
2611        }
2612
2613        delta = handle->bhandle->nlivenodes - nlivenodes;
2614        kvs_delta_stat->nlivenodes += delta;
2615        delta = handle->bhandle->ndeltanodes - ndeltanodes;
2616        delta *= handle->config.blocksize;
2617        kvs_delta_stat->deltasize += delta;
2618
2619        if (old_offset == BLK_NOT_FOUND) {
2620            if (item->action == WAL_ACT_INSERT) {
2621                ++kvs_delta_stat->ndocs;
2622            } else { // inserted a logical deleted doc into main index
2623                ++kvs_delta_stat->ndeletes;
2624            }
2625            kvs_delta_stat->datasize += item->doc_size;
2626            kvs_delta_stat->deltasize += item->doc_size;
2627        } else { // update or logical delete
2628            // This block is already cached when we call HBTRIE_INSERT.
2629            // No additional block access.
2630            char dummy_key[FDB_MAX_KEYLEN];
2631            _doc.meta = _doc.body = NULL;
2632            _doc.key = &dummy_key;
2633            _offset = docio_read_doc_key_meta(handle->dhandle, old_offset,
2634                                              &_doc, true);
2635            if (_offset < 0) {
2636                return (fdb_status) _offset;
2637            } else if (_offset == 0) {
2638                // Note that this is not an error as old_offset is pointing to
2639                // the zero-filled region in a document block.
2640                return FDB_RESULT_KEY_NOT_FOUND;
2641            }
2642            free(_doc.meta);
2643            filemgr_mark_stale(file, old_offset, _fdb_get_docsize(_doc.length));
2644
2645            if (!(_doc.length.flag & DOCIO_DELETED)) {//prev doc was not deleted
2646                if (item->action == WAL_ACT_LOGICAL_REMOVE) { // now deleted
2647                    --kvs_delta_stat->ndocs;
2648                    ++kvs_delta_stat->ndeletes;
2649                } // else no change (prev doc was insert, now just an update)
2650            } else { // prev doc in main index was a logically deleted doc
2651                if (item->action == WAL_ACT_INSERT) { // now undeleted
2652                    ++kvs_delta_stat->ndocs;
2653                    --kvs_delta_stat->ndeletes;
2654                } // else no change (prev doc was deleted, now re-deleted)
2655            }
2656
2657            delta = (int)item->doc_size - (int)_fdb_get_docsize(_doc.length);
2658            kvs_delta_stat->datasize += delta;
2659            if (handle->last_hdr_bid * handle->config.blocksize < old_offset) {
2660                kvs_delta_stat->deltasize += delta;
2661            } else {
2662                kvs_delta_stat->deltasize += (int)item->doc_size;
2663            }
2664
2665            // Avoid duplicates (remove previous sequence number)
2666            if (handle->config.seqtree_opt == FDB_SEQTREE_USE) {
2667                struct wal_stale_seq_entry *entry = (struct wal_stale_seq_entry *)
2668                    calloc(1, sizeof(struct wal_stale_seq_entry));
2669                entry->kv_id = kv_id;
2670                entry->seqnum = _doc.seqnum;
2671                avl_insert(stale_seqnum_list, &entry->avl_entry,
2672                           _fdb_seq_entry_cmp);
2673            }
2674        }
2675    } else {
2676        // Immediate remove
2677        old_offset = item->old_offset;
2678        hr = hbtrie_remove(handle->trie, item->header->key,
2679                           item->header->keylen);
2680        fs = btreeblk_end(handle->bhandle);
2681        if (fs != FDB_RESULT_SUCCESS) {
2682            return fs;
2683        }
2684
2685        if (hr == HBTRIE_RESULT_SUCCESS) {
2686            // This block is already cached when we call _fdb_wal_get_old_offset
2687            // No additional block access should be done.
2688            char dummy_key[FDB_MAX_KEYLEN];
2689            _doc.meta = _doc.body = NULL;
2690            _doc.key = &dummy_key;
2691            _offset = docio_read_doc_key_meta(handle->dhandle, old_offset,
2692                                              &_doc, true);
2693            if (_offset < 0) {
2694                return (fdb_status) _offset;
2695            } else if (_offset == 0) {
2696                return FDB_RESULT_KEY_NOT_FOUND;
2697            }
2698            free(_doc.meta);
2699            filemgr_mark_stale(file, old_offset, _fdb_get_docsize(_doc.length));
2700
2701            // Reduce the total number of docs by one
2702            --kvs_delta_stat->ndocs;
2703            if (_doc.length.flag & DOCIO_DELETED) {//prev deleted doc is dropped
2704                --kvs_delta_stat->ndeletes;
2705            }
2706
2707            // Reduce the total datasize by size of previously present doc
2708            delta = -(int)_fdb_get_docsize(_doc.length);
2709            kvs_delta_stat->datasize += delta;
2710            // if multiple wal flushes happen before commit, then it's possible
2711            // that this doc deleted was inserted & flushed after last commit
2712            // In this case we need to update the deltasize too which tracks
2713            // the amount of new data inserted between commits.
2714            if (handle->last_hdr_bid * handle->config.blocksize < old_offset) {
2715                kvs_delta_stat->deltasize += delta;
2716            }
2717
2718            // remove sequence number for the removed doc
2719            if (handle->config.seqtree_opt == FDB_SEQTREE_USE) {
2720                struct wal_stale_seq_entry *entry = (struct wal_stale_seq_entry *)
2721                    calloc(1, sizeof(struct wal_stale_seq_entry));
2722                entry->kv_id = kv_id;
2723                entry->seqnum = _doc.seqnum;
2724                avl_insert(stale_seqnum_list, &entry->avl_entry, _fdb_seq_entry_cmp);
2725            }
2726
2727            // Update index size to new size after the remove operation
2728            delta = handle->bhandle->nlivenodes - nlivenodes;
2729            kvs_delta_stat->nlivenodes += delta;
2730
2731            // ndeltanodes measures number of new index nodes created due to
2732            // this hbtrie_remove() operation
2733            delta = (int)handle->bhandle->ndeltanodes - ndeltanodes;
2734            delta *= handle->config.blocksize;
2735            kvs_delta_stat->deltasize += delta;
2736        }
2737    }
2738    return FDB_RESULT_SUCCESS;
2739}
2740
2741void fdb_sync_db_header(fdb_kvs_handle *handle)
2742{
2743    uint64_t cur_revnum = filemgr_get_header_revnum(handle->file);
2744    if (handle->cur_header_revnum != cur_revnum) {
2745        void *header_buf = NULL;
2746        size_t header_len;
2747        bid_t hdr_bid;
2748        filemgr_header_revnum_t revnum;
2749
2750        header_buf = filemgr_get_header(handle->file, NULL, &header_len,
2751                                        &hdr_bid, NULL, &revnum);
2752        if (header_len > 0) {
2753            uint64_t header_flags, dummy64, version;
2754            bid_t idtree_root;
2755            bid_t new_seq_root;
2756            bid_t new_stale_root;
2757            char *compacted_filename;
2758            char *prev_filename = NULL;
2759
2760            version = handle->file->version;
2761            handle->last_hdr_bid = hdr_bid;
2762            handle->cur_header_revnum = revnum;
2763
2764            fdb_fetch_header(version, header_buf, &idtree_root,
2765                             &new_seq_root, &new_stale_root, &dummy64,
2766                             &dummy64, &dummy64,
2767                             &dummy64, &handle->last_wal_flush_hdr_bid,
2768                             &handle->kv_info_offset, &header_flags,
2769                             &compacted_filename, &prev_filename);
2770
2771            if (handle->dirty_updates) {
2772                // discard all cached writable b+tree nodes
2773                // to avoid data inconsistency with other writers
2774                btreeblk_discard_blocks(handle->bhandle);
2775            }
2776
2777            handle->trie->root_bid = idtree_root;
2778
2779            if (handle->config.seqtree_opt == FDB_SEQTREE_USE) {
2780                if (new_seq_root != handle->seqtree->root_bid) {
2781                    if (handle->config.multi_kv_instances) {
2782                        handle->seqtrie->root_bid = new_seq_root;
2783                    } else {
2784                        btree_init_from_bid(handle->seqtree,
2785                                            handle->seqtree->blk_handle,
2786                                            handle->seqtree->blk_ops,
2787                                            handle->seqtree->kv_ops,
2788                                            handle->seqtree->blksize,
2789                                            new_seq_root);
2790                    }
2791                }
2792            }
2793
2794            if (ver_staletree_support(version)) {
2795                btree_init_from_bid(handle->staletree,
2796                                    handle->staletree->blk_handle,
2797                                    handle->staletree->blk_ops,
2798                                    handle->staletree->kv_ops,
2799                                    handle->staletree->blksize,
2800                                    new_stale_root);
2801            } else {
2802                handle->staletree = NULL;
2803            }
2804
2805            if (prev_filename) {
2806                free(prev_filename);
2807            }
2808
2809            handle->dirty_updates = 0;
2810            if (handle->kvs) {
2811                // multiple KV instance mode AND sub handle
2812                handle->seqnum = fdb_kvs_get_seqnum(handle->file,
2813                                                    handle->kvs->id);
2814            } else {
2815                // super handle OR single KV instance mode
2816                handle->seqnum = filemgr_get_seqnum(handle->file);
2817            }
2818        } else {
2819            handle->last_hdr_bid = filemgr_get_header_bid(handle->file);
2820        }
2821
2822        if (header_buf) {
2823            free(header_buf);
2824        }
2825    }
2826}
2827
2828fdb_status fdb_check_file_reopen(fdb_kvs_handle *handle, file_status_t *status)
2829{
2830    bool fhandle_ret;
2831    fdb_status fs = FDB_RESULT_SUCCESS;
2832    file_status_t fstatus = filemgr_get_file_status(handle->file);
2833    // check whether the compaction is done
2834    if (fstatus == FILE_REMOVED_PENDING) {
2835        uint64_t ndocs, ndeletes, datasize, nlivenodes, last_wal_flush_hdr_bid;
2836        uint64_t kv_info_offset, header_flags;
2837        size_t header_len;
2838        char *new_filename;
2839        uint8_t *buf = alca(uint8_t, handle->config.blocksize);
2840        bid_t trie_root_bid, seq_root_bid, stale_root_bid;
2841        fdb_config config = handle->config;
2842
2843        // close the current file and newly open the new file
2844        if (handle->config.compaction_mode == FDB_COMPACTION_AUTO) {
2845            // compaction daemon mode .. just close and then open
2846            char filename[FDB_MAX_FILENAME_LEN];
2847            strcpy(filename, handle->filename);
2848
2849            // We don't need to maintain fhandle list for the old file
2850            // as there will be no more mutation on the file.
2851            fhandle_ret = filemgr_fhandle_remove(handle->file, handle->fhandle);
2852            fs = _fdb_close(handle);
2853            if (fs != FDB_RESULT_SUCCESS) {
2854                if (fhandle_ret) {
2855                    filemgr_fhandle_add(handle->file, handle->fhandle);
2856                }
2857                return fs;
2858            }
2859
2860            fs = _fdb_open(handle, filename, FDB_VFILENAME, &config);
2861            if (fs != FDB_RESULT_SUCCESS) {
2862                return fs;
2863            }
2864            filemgr_fhandle_add(handle->file, handle->fhandle);
2865
2866        } else {
2867            filemgr_get_header(handle->file, buf, &header_len, NULL, NULL, NULL);
2868            fdb_fetch_header(handle->file->version, buf,
2869                             &trie_root_bid, &seq_root_bid, &stale_root_bid,
2870                             &ndocs, &ndeletes, &nlivenodes, &datasize,
2871                             &last_wal_flush_hdr_bid,
2872                             &kv_info_offset, &header_flags,
2873                             &new_filename, NULL);
2874
2875            fhandle_ret = filemgr_fhandle_remove(handle->file, handle->fhandle);
2876            fs = _fdb_close(handle);
2877            if (fs != FDB_RESULT_SUCCESS) {
2878                if (fhandle_ret) {
2879                    filemgr_fhandle_add(handle->file, handle->fhandle);
2880                }
2881                return fs;
2882            }
2883
2884            fs = _fdb_open(handle, new_filename, FDB_AFILENAME, &config);
2885            if (fs != FDB_RESULT_SUCCESS) {
2886                return fs;
2887            }
2888            filemgr_fhandle_add(handle->file, handle->fhandle);
2889        }
2890    }
2891    if (status) {
2892        *status = fstatus;
2893    }
2894    return fs;
2895}
2896
2897static void _fdb_sync_dirty_root(fdb_kvs_handle *handle)
2898{
2899    bid_t dirty_idtree_root = BLK_NOT_FOUND;
2900    bid_t dirty_seqtree_root = BLK_NOT_FOUND;
2901
2902    if (handle->shandle) {
2903        // skip snapshot
2904        return;
2905    }
2906
2907    struct filemgr_dirty_update_node *dirty_update;
2908    dirty_update = filemgr_dirty_update_get_latest(handle->file);
2909    btreeblk_set_dirty_update(handle->bhandle, dirty_update);
2910
2911    if (dirty_update) {
2912        filemgr_dirty_update_get_root(handle->file, dirty_update,
2913                                      &dirty_idtree_root, &dirty_seqtree_root);
2914        _fdb_import_dirty_root(handle, dirty_idtree_root, dirty_seqtree_root);
2915        btreeblk_discard_blocks(handle->bhandle);
2916    }
2917
2918    return;
2919}
2920
2921static void _fdb_release_dirty_root(fdb_kvs_handle *handle)
2922{
2923    if (!handle->shandle) {
2924        struct filemgr_dirty_update_node *dirty_update;
2925        dirty_update = btreeblk_get_dirty_update(handle->bhandle);
2926        if (dirty_update) {
2927            filemgr_dirty_update_close_node(handle->file, dirty_update);
2928            btreeblk_clear_dirty_update(handle->bhandle);
2929        }
2930    }
2931}
2932
2933LIBFDB_API
2934fdb_status fdb_get(fdb_kvs_handle *handle, fdb_doc *doc)
2935{
2936    uint64_t offset;
2937    int64_t _offset;
2938    struct docio_object _doc;
2939    struct filemgr *wal_file = NULL;
2940    struct docio_handle *dhandle;
2941    struct _fdb_key_cmp_info cmp_info;
2942    fdb_status wr;
2943    hbtrie_result hr = HBTRIE_RESULT_FAIL;
2944    fdb_txn *txn;
2945    fdb_doc doc_kv;
2946    LATENCY_STAT_START();
2947
2948    if (!handle) {
2949        return FDB_RESULT_INVALID_HANDLE;
2950    }
2951
2952    if (!doc || !doc->key || doc->keylen == 0 ||
2953        doc->keylen > FDB_MAX_KEYLEN ||
2954        (handle->kvs_config.custom_cmp &&
2955            doc->keylen > handle->config.blocksize - HBTRIE_HEADROOM)) {
2956        return FDB_RESULT_INVALID_ARGS;
2957    }
2958
2959    if (!atomic_cas_uint8_t(&handle->handle_busy, 0, 1)) {
2960        return FDB_RESULT_HANDLE_BUSY;
2961    }
2962
2963    doc_kv = *doc;
2964
2965    if (handle->kvs) {
2966        // multi KV instance mode
2967        int size_chunk = handle->config.chunksize;
2968        doc_kv.keylen = doc->keylen + size_chunk;
2969        doc_kv.key = alca(uint8_t, doc_kv.keylen);
2970        kvid2buf(size_chunk, handle->kvs->id, doc_kv.key);
2971        memcpy((uint8_t*)doc_kv.key + size_chunk, doc->key, doc->keylen);
2972    }
2973
2974    if (!handle->shandle) {
2975        fdb_check_file_reopen(handle, NULL);
2976        txn = handle->fhandle->root->txn;
2977        if (!txn) {
2978            txn = &handle->file->global_txn;
2979        }
2980    } else {
2981        txn = handle->shandle->snap_txn;
2982    }
2983
2984    cmp_info.kvs_config = handle->kvs_config;
2985    cmp_info.kvs = handle->kvs;
2986    wal_file = handle->file;
2987    dhandle = handle->dhandle;
2988
2989    if (handle->kvs) {
2990        wr = wal_find(txn, wal_file, &cmp_info, handle->shandle, &doc_kv,
2991                      &offset);
2992    } else {
2993        wr = wal_find(txn, wal_file, &cmp_info, handle->shandle, doc,
2994                      &offset);
2995    }
2996
2997    if (!handle->shandle) {
2998        fdb_sync_db_header(handle);
2999    }
3000
3001    atomic_incr_uint64_t(&handle->op_stats->num_gets, std::memory_order_relaxed);
3002
3003    if (wr == FDB_RESULT_KEY_NOT_FOUND) {
3004        _fdb_sync_dirty_root(handle);
3005
3006        if (handle->kvs) {
3007            hr = hbtrie_find(handle->trie, doc_kv.key, doc_kv.keylen,
3008                             (void *)&offset);
3009        } else {
3010            hr = hbtrie_find(handle->trie, doc->key, doc->keylen,
3011                             (void *)&offset);
3012        }
3013        btreeblk_end(handle->bhandle);
3014        offset = _endian_decode(offset);
3015
3016        _fdb_release_dirty_root(handle);
3017    }
3018
3019    if ((wr == FDB_RESULT_SUCCESS && offset != BLK_NOT_FOUND) ||
3020         hr == HBTRIE_RESULT_SUCCESS) {
3021        bool alloced_meta = doc->meta ? false : true;
3022        bool alloced_body = doc->body ? false : true;
3023        if (handle->kvs) {
3024            _doc.key = doc_kv.key;
3025            _doc.length.keylen = doc_kv.keylen;
3026            doc->deleted = doc_kv.deleted; // update deleted field if wal_find
3027        } else {
3028            _doc.key = doc->key;
3029            _doc.length.keylen = doc->keylen;
3030        }
3031        _doc.meta = doc->meta;
3032        _doc.body = doc->body;
3033
3034        if (wr == FDB_RESULT_SUCCESS && doc->deleted) {
3035            atomic_cas_uint8_t(&handle->handle_busy, 1, 0);
3036            return FDB_RESULT_KEY_NOT_FOUND;
3037        }
3038
3039        _offset = docio_read_doc(dhandle, offset, &_doc, true);
3040        if (_offset <= 0) {
3041            atomic_cas_uint8_t(&handle->handle_busy, 1, 0);
3042            return _offset < 0 ? (fdb_status)_offset : FDB_RESULT_KEY_NOT_FOUND;
3043        }
3044
3045        if (_doc.length.keylen != doc_kv.keylen ||
3046            _doc.length.flag & DOCIO_DELETED) {
3047            free_docio_object(&_doc, 0, alloced_meta, alloced_body);
3048            atomic_cas_uint8_t(&handle->handle_busy, 1, 0);
3049            return FDB_RESULT_KEY_NOT_FOUND;
3050        }
3051
3052        doc->seqnum = _doc.seqnum;
3053        doc->metalen = _doc.length.metalen;
3054        doc->bodylen = _doc.length.bodylen;
3055        doc->meta = _doc.meta;
3056        doc->body = _doc.body;
3057        doc->deleted = _doc.length.flag & DOCIO_DELETED;
3058        doc->size_ondisk = _fdb_get_docsize(_doc.length);
3059        doc->offset = offset;
3060
3061        LATENCY_STAT_END(handle->file, FDB_LATENCY_GETS);
3062        atomic_cas_uint8_t(&handle->handle_busy, 1, 0);
3063        return FDB_RESULT_SUCCESS;
3064    }
3065
3066    atomic_cas_uint8_t(&handle->handle_busy, 1, 0);
3067    return FDB_RESULT_KEY_NOT_FOUND;
3068}
3069
3070// search document metadata using key
3071LIBFDB_API
3072fdb_status fdb_get_metaonly(fdb_kvs_handle *handle, fdb_doc *doc)
3073{
3074    uint64_t offset;
3075    struct docio_object _doc;
3076    struct docio_handle *dhandle;
3077    struct filemgr *wal_file = NULL;
3078    fdb_status wr;
3079    hbtrie_result hr = HBTRIE_RESULT_FAIL;
3080    fdb_txn *txn;
3081    struct _fdb_key_cmp_info cmp_info;
3082    fdb_doc doc_kv;
3083    LATENCY_STAT_START();
3084
3085    if (!handle) {
3086        return FDB_RESULT_INVALID_HANDLE;
3087    }
3088
3089    if (!doc || !doc->key ||
3090        doc->keylen == 0 || doc->keylen > FDB_MAX_KEYLEN ||
3091        (handle->kvs_config.custom_cmp &&
3092            doc->keylen > handle->config.blocksize - HBTRIE_HEADROOM)) {
3093        return FDB_RESULT_INVALID_ARGS;
3094    }
3095
3096    doc_kv = *doc;
3097
3098    if (!atomic_cas_uint8_t(&handle->handle_busy, 0, 1)) {
3099        return FDB_RESULT_HANDLE_BUSY;
3100    }
3101
3102    if (handle->kvs) {
3103        // multi KV instance mode
3104        int size_chunk = handle->config.chunksize;
3105        doc_kv.keylen = doc->keylen + size_chunk;
3106        doc_kv.key = alca(uint8_t, doc_kv.keylen);
3107        kvid2buf(size_chunk, handle->kvs->id, doc_kv.key);
3108        memcpy((uint8_t*)doc_kv.key + size_chunk, doc->key, doc->keylen);
3109    }
3110
3111    if (!handle->shandle) {
3112        fdb_check_file_reopen(handle, NULL);
3113        txn = handle->fhandle->root->txn;
3114        if (!txn) {
3115            txn = &handle->file->global_txn;
3116        }
3117    } else {
3118        txn = handle->shandle->snap_txn;
3119    }
3120
3121    cmp_info.kvs_config = handle->kvs_config;
3122    cmp_info.kvs = handle->kvs;
3123    wal_file = handle->file;
3124    dhandle = handle->dhandle;
3125
3126    if (handle->kvs) {
3127        wr = wal_find(txn, wal_file, &cmp_info, handle->shandle, &doc_kv,
3128                      &offset);
3129    } else {
3130        wr = wal_find(txn, wal_file, &cmp_info, handle->shandle, doc, &offset);
3131    }
3132
3133    if (!handle->shandle) {
3134        fdb_sync_db_header(handle);
3135    }
3136    atomic_incr_uint64_t(&handle->op_stats->num_gets, std::memory_order_relaxed);
3137
3138    if (wr == FDB_RESULT_KEY_NOT_FOUND) {
3139        _fdb_sync_dirty_root(handle);
3140
3141        if (handle->kvs) {
3142            hr = hbtrie_find(handle->trie, doc_kv.key, doc_kv.keylen,
3143                             (void *)&offset);
3144        } else {
3145            hr = hbtrie_find(handle->trie, doc->key, doc->keylen,
3146                             (void *)&offset);
3147        }
3148        btreeblk_end(handle->bhandle);
3149        offset = _endian_decode(offset);
3150
3151        _fdb_release_dirty_root(handle);
3152    }
3153
3154    if ((wr == FDB_RESULT_SUCCESS && offset != BLK_NOT_FOUND) ||
3155         hr == HBTRIE_RESULT_SUCCESS) {
3156        if (handle->kvs) {
3157            _doc.key = doc_kv.key;
3158            _doc.length.keylen = doc_kv.keylen;
3159        } else {
3160            _doc.key = doc->key;
3161            _doc.length.keylen = doc->keylen;
3162        }
3163        bool alloced_meta = doc->meta ? false : true;
3164        _doc.meta = doc->meta;
3165        _doc.body = doc->body;
3166
3167        int64_t body_offset = docio_read_doc_key_meta(dhandle, offset, &_doc,
3168                                                       true);
3169        if (body_offset <= 0){
3170            atomic_cas_uint8_t(&handle->handle_busy, 1, 0);
3171            return body_offset < 0 ? (fdb_status)body_offset : FDB_RESULT_KEY_NOT_FOUND;
3172        }
3173
3174        if (_doc.length.keylen != doc_kv.keylen) {
3175            free_docio_object(&_doc, 0, alloced_meta, 0);
3176            atomic_cas_uint8_t(&handle->handle_busy, 1, 0);
3177            return FDB_RESULT_KEY_NOT_FOUND;
3178        }
3179
3180        doc->seqnum = _doc.seqnum;
3181        doc->metalen = _doc.length.metalen;
3182        doc->bodylen = _doc.length.bodylen;
3183        doc->meta = _doc.meta;
3184        doc->body = _doc.body;
3185        doc->deleted = _doc.length.flag & DOCIO_DELETED;
3186        doc->size_ondisk = _fdb_get_docsize(_doc.length);
3187        doc->offset = offset;
3188
3189        LATENCY_STAT_END(handle->file, FDB_LATENCY_GETS);
3190        atomic_cas_uint8_t(&handle->handle_busy, 1, 0);
3191        return FDB_RESULT_SUCCESS;
3192    }
3193
3194    atomic_cas_uint8_t(&handle->handle_busy, 1, 0);
3195    return FDB_RESULT_KEY_NOT_FOUND;
3196}
3197
3198// search document using sequence number
3199LIBFDB_API
3200fdb_status fdb_get_byseq(fdb_kvs_handle *handle, fdb_doc *doc)
3201{
3202    uint64_t offset;
3203    int64_t _offset;
3204    struct docio_object _doc;
3205    struct docio_handle *dhandle;
3206    struct filemgr *wal_file = NULL;
3207    fdb_status wr;
3208    btree_result br = BTREE_RESULT_FAIL;
3209    fdb_seqnum_t _seqnum;
3210    fdb_txn *txn;
3211    struct _fdb_key_cmp_info cmp_info;
3212