xref: /5.5.2/forestdb/src/forestdb.cc (revision b6e47bcd)
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        atomic_store_uint64_t(&handle->last_hdr_bid,  // do fast rewind
1026                              atomic_get_uint64_t(&handle_in->last_hdr_bid));
1027        fs = wal_snapshot_clone(handle_in->shandle, &handle->shandle, seqnum);
1028        if (fs == FDB_RESULT_SUCCESS) {
1029            clone_snapshot = true;
1030            handle->max_seqnum = FDB_SNAPSHOT_INMEM; // temp value to skip WAL
1031        } else {
1032            fdb_log(&handle_in->log_callback, fs,
1033                    "Warning: Snapshot clone at sequence number %" _F64
1034                    "does not match its snapshot handle %" _F64
1035                    "in file '%s'.", seqnum, handle_in->seqnum,
1036                    handle_in->file->filename);
1037            free(handle);
1038            return fs;
1039        }
1040    }
1041
1042    cmp_info.kvs_config = handle_in->kvs_config;
1043    cmp_info.kvs = handle_in->kvs;
1044
1045    if (!handle->shandle) {
1046        txn = handle_in->fhandle->root->txn;
1047        if (!txn) {
1048            txn = &handle_in->file->global_txn;
1049        }
1050        if (handle_in->kvs) {
1051            kv_id = handle_in->kvs->id;
1052        }
1053        if (seqnum == FDB_SNAPSHOT_INMEM) {
1054            memset(&dummy_shandle, 0, sizeof(struct snap_handle));
1055            // tmp value to denote snapshot & not rollback to _fdb_open
1056            handle->shandle = &dummy_shandle; // dummy
1057        } else {
1058            fs = wal_dur_snapshot_open(seqnum, &cmp_info, file, txn,
1059                                       &handle->shandle);
1060        }
1061        if (fs != FDB_RESULT_SUCCESS) {
1062            free(handle);
1063            return fs;
1064        }
1065    }
1066
1067    if (handle_in->kvs) {
1068        // sub-handle in multi KV instance mode
1069        if (clone_snapshot) {
1070            fs = _fdb_kvs_clone_snapshot(handle_in, handle);
1071        } else {
1072            fs = _fdb_kvs_open(handle_in->kvs->root,
1073                              &config, &kvs_config, file,
1074                              file->filename,
1075                              _fdb_kvs_get_name(handle_in, file),
1076                              handle);
1077        }
1078    } else {
1079        if (clone_snapshot) {
1080            fs = _fdb_clone_snapshot(handle_in, handle);
1081        } else {
1082            fs = _fdb_open(handle, file->filename, FDB_AFILENAME, &config);
1083        }
1084    }
1085
1086    if (fs == FDB_RESULT_SUCCESS) {
1087        if (seqnum == FDB_SNAPSHOT_INMEM &&
1088            !handle_in->shandle) {
1089            handle->max_seqnum = handle_in->seqnum;
1090
1091            // synchronize dirty root nodes if exist
1092            bid_t dirty_idtree_root = BLK_NOT_FOUND;
1093            bid_t dirty_seqtree_root = BLK_NOT_FOUND;
1094            struct filemgr_dirty_update_node *dirty_update;
1095
1096            dirty_update = filemgr_dirty_update_get_latest(handle->file);
1097            btreeblk_set_dirty_update(handle->bhandle, dirty_update);
1098
1099            if (dirty_update) {
1100                filemgr_dirty_update_get_root(handle->file, dirty_update,
1101                                       &dirty_idtree_root, &dirty_seqtree_root);
1102                _fdb_import_dirty_root(handle, dirty_idtree_root,
1103                                       dirty_seqtree_root);
1104                btreeblk_discard_blocks(handle->bhandle);
1105            }
1106            // Having synced the dirty root, make an in-memory WAL snapshot
1107            // TODO: Re-enable WAL sharing once ready...
1108#ifdef _MVCC_WAL_ENABLE
1109            fs = wal_snapshot_open(handle->file, txn, kv_id, seqnum,
1110                                   &cmp_info, &handle->shandle);
1111#else
1112            fs = wal_dur_snapshot_open(handle->seqnum, &cmp_info, file, txn,
1113                                       &handle->shandle);
1114            if (fs == FDB_RESULT_SUCCESS) {
1115                fs = wal_copyto_snapshot(file, handle->shandle,
1116                                        (bool)handle_in->kvs);
1117            }
1118            (void)kv_id;
1119#endif // _MVCC_WAL_ENABLE
1120        } else if (clone_snapshot) {
1121            // Snapshot is created on the other snapshot handle
1122
1123            handle->max_seqnum = handle_in->seqnum;
1124
1125            if (seqnum == FDB_SNAPSHOT_INMEM) {
1126                // in-memory snapshot
1127                // Clone dirty root nodes from the source snapshot by incrementing
1128                // their ref counters
1129                handle->trie->root_bid = handle_in->trie->root_bid;
1130                if (handle->config.seqtree_opt == FDB_SEQTREE_USE) {
1131                    if (handle->kvs) {
1132                        handle->seqtrie->root_bid = handle_in->seqtrie->root_bid;
1133                    } else {
1134                        handle->seqtree->root_bid = handle_in->seqtree->root_bid;
1135                    }
1136                }
1137                btreeblk_discard_blocks(handle->bhandle);
1138
1139                // increase ref count for dirty update
1140                struct filemgr_dirty_update_node *dirty_update;
1141                dirty_update = btreeblk_get_dirty_update(handle_in->bhandle);
1142                filemgr_dirty_update_inc_ref_count(dirty_update);
1143                btreeblk_set_dirty_update(handle->bhandle, dirty_update);
1144            }
1145        }
1146        *ptr_handle = handle;
1147    } else {
1148        *ptr_handle = NULL;
1149        if (clone_snapshot || seqnum != FDB_SNAPSHOT_INMEM) {
1150            wal_snapshot_close(handle->shandle, handle->file);
1151        }
1152        free(handle);
1153        // If compactor thread had finished compaction just before this routine
1154        // calls _fdb_open, then it is possible that the snapshot's DB header
1155        // is only present in the new_file. So we must retry the snapshot
1156        // open attempt IFF _fdb_open indicates FDB_RESULT_NO_DB_INSTANCE..
1157        if (fs == FDB_RESULT_NO_DB_INSTANCE && fstatus == FILE_COMPACT_OLD) {
1158            if (filemgr_get_file_status(file) == FILE_REMOVED_PENDING) {
1159                goto fdb_snapshot_open_start;
1160            }
1161        }
1162    }
1163
1164    if (handle_in->shandle) {
1165        LATENCY_STAT_END(file, FDB_LATENCY_SNAP_CLONE);
1166    } else if (seqnum == FDB_SNAPSHOT_INMEM) {
1167        LATENCY_STAT_END(file, FDB_LATENCY_SNAP_INMEM);
1168    } else {
1169        LATENCY_STAT_END(file, FDB_LATENCY_SNAP_DUR);
1170    }
1171    return fs;
1172}
1173
1174static fdb_status _fdb_reset(fdb_kvs_handle *handle, fdb_kvs_handle *handle_in);
1175
1176LIBFDB_API
1177fdb_status fdb_rollback(fdb_kvs_handle **handle_ptr, fdb_seqnum_t seqnum)
1178{
1179#ifdef _MEMPOOL
1180    mempool_init();
1181#endif
1182
1183    fdb_config config;
1184    fdb_kvs_handle *handle_in, *handle;
1185    fdb_status fs;
1186    fdb_seqnum_t old_seqnum;
1187
1188    if (!handle_ptr) {
1189        return FDB_RESULT_INVALID_HANDLE;
1190    }
1191
1192    handle_in = *handle_ptr;
1193
1194    if (!handle_in) {
1195        return FDB_RESULT_INVALID_HANDLE;
1196    }
1197
1198    config = handle_in->config;
1199
1200    if (handle_in->kvs) {
1201        return fdb_kvs_rollback(handle_ptr, seqnum);
1202    }
1203
1204    if (handle_in->config.flags & FDB_OPEN_FLAG_RDONLY) {
1205        return fdb_log(&handle_in->log_callback, FDB_RESULT_RONLY_VIOLATION,
1206                       "Warning: Rollback is not allowed on the read-only DB file '%s'.",
1207                       handle_in->file->filename);
1208    }
1209
1210    if (!atomic_cas_uint8_t(&handle_in->handle_busy, 0, 1)) {
1211        return FDB_RESULT_HANDLE_BUSY;
1212    }
1213
1214    filemgr_mutex_lock(handle_in->file);
1215    filemgr_set_rollback(handle_in->file, 1); // disallow writes operations
1216    // All transactions should be closed before rollback
1217    if (wal_txn_exists(handle_in->file)) {
1218        filemgr_set_rollback(handle_in->file, 0);
1219        filemgr_mutex_unlock(handle_in->file);
1220        atomic_cas_uint8_t(&handle_in->handle_busy, 1, 0);
1221        return FDB_RESULT_FAIL_BY_TRANSACTION;
1222    }
1223
1224    // If compaction is running, wait until it is aborted.
1225    // TODO: Find a better way of waiting for the compaction abortion.
1226    unsigned int sleep_time = 10000; // 10 ms.
1227    file_status_t fstatus = filemgr_get_file_status(handle_in->file);
1228    while (fstatus == FILE_COMPACT_OLD) {
1229        filemgr_mutex_unlock(handle_in->file);
1230        decaying_usleep(&sleep_time, 1000000);
1231        filemgr_mutex_lock(handle_in->file);
1232        fstatus = filemgr_get_file_status(handle_in->file);
1233    }
1234    if (fstatus == FILE_REMOVED_PENDING) {
1235        filemgr_mutex_unlock(handle_in->file);
1236        fdb_check_file_reopen(handle_in, NULL);
1237    } else {
1238        filemgr_mutex_unlock(handle_in->file);
1239    }
1240
1241    fdb_sync_db_header(handle_in);
1242
1243    // if the max sequence number seen by this handle is lower than the
1244    // requested snapshot marker, it means the snapshot is not yet visible
1245    // even via the current fdb_kvs_handle
1246    if (seqnum > handle_in->seqnum) {
1247        filemgr_set_rollback(handle_in->file, 0); // allow mutations
1248        atomic_cas_uint8_t(&handle_in->handle_busy, 1, 0);
1249        return FDB_RESULT_NO_DB_INSTANCE;
1250    }
1251
1252    handle = (fdb_kvs_handle *) calloc(1, sizeof(fdb_kvs_handle));
1253    if (!handle) { // LCOV_EXCL_START
1254        atomic_cas_uint8_t(&handle_in->handle_busy, 1, 0);
1255        return FDB_RESULT_ALLOC_FAIL;
1256    } // LCOV_EXCL_STOP
1257
1258    atomic_init_uint8_t(&handle->handle_busy, 0);
1259    handle->log_callback = handle_in->log_callback;
1260    handle->fhandle = handle_in->fhandle;
1261    if (seqnum == 0) {
1262        fs = _fdb_reset(handle, handle_in);
1263    } else {
1264        handle->max_seqnum = seqnum;
1265        fs = _fdb_open(handle, handle_in->file->filename, FDB_AFILENAME,
1266                       &config);
1267    }
1268
1269    filemgr_set_rollback(handle_in->file, 0); // allow mutations
1270    if (fs == FDB_RESULT_SUCCESS) {
1271        // rollback the file's sequence number
1272        filemgr_mutex_lock(handle_in->file);
1273        old_seqnum = filemgr_get_seqnum(handle_in->file);
1274        filemgr_set_seqnum(handle_in->file, seqnum);
1275        filemgr_mutex_unlock(handle_in->file);
1276
1277        fs = _fdb_commit(handle, FDB_COMMIT_MANUAL_WAL_FLUSH,
1278                !(handle_in->config.durability_opt & FDB_DRB_ASYNC));
1279        if (fs == FDB_RESULT_SUCCESS) {
1280            if (handle_in->txn) {
1281                handle->txn = handle_in->txn;
1282                handle_in->txn = NULL;
1283            }
1284            // Close, unlink and free the caller's rollback handle.
1285            _fdb_kvs_close(handle_in);
1286            free(handle_in);
1287            // Link the newly opened handle into the file handle's list
1288            _fdb_kvs_createNLinkKVHandle(handle->fhandle, handle);
1289            handle->max_seqnum = 0;
1290            handle->seqnum = seqnum;
1291            // Set the newly opened rolled-back handle as caller's handle
1292            *handle_ptr = handle;
1293        } else {
1294            // cancel the rolling-back of the sequence number
1295            filemgr_mutex_lock(handle_in->file);
1296            filemgr_set_seqnum(handle_in->file, old_seqnum);
1297            filemgr_mutex_unlock(handle_in->file);
1298            free(handle);
1299            atomic_cas_uint8_t(&handle_in->handle_busy, 1, 0);
1300        }
1301    } else {
1302        free(handle);
1303        atomic_cas_uint8_t(&handle_in->handle_busy, 1, 0);
1304    }
1305
1306    return fs;
1307}
1308
1309LIBFDB_API
1310fdb_status fdb_rollback_all(fdb_file_handle *fhandle,
1311                            fdb_snapshot_marker_t marker)
1312{
1313#ifdef _MEMPOOL
1314    mempool_init();
1315#endif
1316
1317    fdb_config config;
1318    fdb_kvs_handle *super_handle;
1319    fdb_kvs_handle rhandle;
1320    fdb_kvs_handle *handle = &rhandle;
1321    struct filemgr *file;
1322    fdb_kvs_config kvs_config;
1323    fdb_status fs;
1324    err_log_callback log_callback;
1325    struct kvs_info *kvs;
1326    struct snap_handle shandle; // dummy snap handle
1327
1328    if (!fhandle) {
1329        return FDB_RESULT_INVALID_HANDLE;
1330    }
1331
1332    super_handle = fhandle->root;
1333    kvs = super_handle->kvs;
1334
1335    // fdb_rollback_all cannot be allowed when there are kv store instances
1336    // still open, because we do not have means of invalidating open kv handles
1337    // which may not be present in the rollback point
1338    if (kvs && _fdb_kvs_is_busy(fhandle)) {
1339        return FDB_RESULT_KV_STORE_BUSY;
1340    }
1341    file = super_handle->file;
1342    config = super_handle->config;
1343    kvs_config = super_handle->kvs_config;
1344    log_callback = super_handle->log_callback;
1345
1346    if (super_handle->config.flags & FDB_OPEN_FLAG_RDONLY) {
1347        return fdb_log(&super_handle->log_callback, FDB_RESULT_RONLY_VIOLATION,
1348                       "Warning: Rollback is not allowed on the read-only DB file '%s'.",
1349                       super_handle->file->filename);
1350    }
1351
1352    filemgr_mutex_lock(super_handle->file);
1353    filemgr_set_rollback(super_handle->file, 1); // disallow writes operations
1354    // All transactions should be closed before rollback
1355    if (wal_txn_exists(super_handle->file)) {
1356        filemgr_set_rollback(super_handle->file, 0);
1357        filemgr_mutex_unlock(super_handle->file);
1358        return FDB_RESULT_FAIL_BY_TRANSACTION;
1359    }
1360
1361    // If compaction is running, wait until it is aborted.
1362    // TODO: Find a better way of waiting for the compaction abortion.
1363    unsigned int sleep_time = 10000; // 10 ms.
1364    file_status_t fstatus = filemgr_get_file_status(super_handle->file);
1365    while (fstatus == FILE_COMPACT_OLD) {
1366        filemgr_mutex_unlock(super_handle->file);
1367        decaying_usleep(&sleep_time, 1000000);
1368        filemgr_mutex_lock(super_handle->file);
1369        fstatus = filemgr_get_file_status(super_handle->file);
1370    }
1371    if (fstatus == FILE_REMOVED_PENDING) {
1372        filemgr_mutex_unlock(super_handle->file);
1373        fdb_check_file_reopen(super_handle, NULL);
1374    } else {
1375        filemgr_mutex_unlock(super_handle->file);
1376    }
1377
1378    fdb_sync_db_header(super_handle);
1379    // Shutdown WAL discarding entries from all KV Stores..
1380    fs = wal_shutdown(super_handle->file, &super_handle->log_callback);
1381    if (fs != FDB_RESULT_SUCCESS) {
1382        return fs;
1383    }
1384
1385    memset(handle, 0, sizeof(fdb_kvs_handle));
1386    memset(&shandle, 0, sizeof(struct snap_handle));
1387    handle->log_callback = log_callback;
1388    handle->fhandle = fhandle;
1389    // Fast rewind on open...
1390    atomic_store_uint64_t(&handle->last_hdr_bid, (bid_t)marker);
1391    handle->max_seqnum = FDB_SNAPSHOT_INMEM; // Prevent WAL restore on open
1392    handle->shandle = &shandle; // a dummy handle to prevent WAL restore
1393    if (kvs) {
1394        fdb_kvs_header_free(file); // KV header will be recreated below.
1395        handle->kvs = kvs; // re-use super_handle's kvs info
1396        handle->kvs_config = kvs_config;
1397    }
1398    handle->config = config;
1399
1400    fs = _fdb_open(handle, file->filename, FDB_AFILENAME, &config);
1401
1402    if (handle->config.multi_kv_instances) {
1403        filemgr_mutex_lock(handle->file);
1404        fdb_kvs_header_create(handle->file);
1405        fdb_kvs_header_read(handle->file->kv_header, handle->dhandle,
1406                            handle->kv_info_offset,
1407                            handle->file->version, false);
1408        filemgr_mutex_unlock(handle->file);
1409    }
1410
1411    filemgr_set_rollback(file, 0); // allow mutations
1412    handle->shandle = NULL; // just a dummy handle never allocated
1413
1414    if (fs == FDB_RESULT_SUCCESS) {
1415        fdb_seqnum_t old_seqnum;
1416        // Restore WAL for all KV instances...
1417        _fdb_restore_wal(handle, FDB_RESTORE_NORMAL, (bid_t)marker, 0);
1418
1419        // rollback the file's sequence number
1420        filemgr_mutex_lock(file);
1421        old_seqnum = filemgr_get_seqnum(file);
1422        filemgr_set_seqnum(file, handle->seqnum);
1423        filemgr_mutex_unlock(file);
1424
1425        fs = _fdb_commit(handle, FDB_COMMIT_NORMAL,
1426                         !(handle->config.durability_opt & FDB_DRB_ASYNC));
1427        if (fs == FDB_RESULT_SUCCESS) {
1428            _fdb_close(super_handle);
1429            *super_handle = *handle;
1430        } else {
1431            filemgr_mutex_lock(file);
1432            filemgr_set_seqnum(file, old_seqnum);
1433            filemgr_mutex_unlock(file);
1434        }
1435    } else { // Rollback failed, restore KV header
1436        fdb_kvs_header_create(file);
1437        fdb_kvs_header_read(file->kv_header, super_handle->dhandle,
1438                            super_handle->kv_info_offset,
1439                            ver_get_latest_magic(),
1440                            false);
1441    }
1442
1443    return fs;
1444}
1445
1446static void _fdb_init_file_config(const fdb_config *config,
1447                                  struct filemgr_config *fconfig) {
1448    fconfig->blocksize = config->blocksize;
1449    fconfig->ncacheblock = config->buffercache_size / config->blocksize;
1450    fconfig->chunksize = config->chunksize;
1451
1452    fconfig->options = 0x0;
1453    fconfig->seqtree_opt = config->seqtree_opt;
1454
1455    if (config->flags & FDB_OPEN_FLAG_CREATE) {
1456        fconfig->options |= FILEMGR_CREATE;
1457    }
1458    if (config->flags & FDB_OPEN_FLAG_RDONLY) {
1459        fconfig->options |= FILEMGR_READONLY;
1460    }
1461    if (!(config->durability_opt & FDB_DRB_ASYNC)) {
1462        fconfig->options |= FILEMGR_SYNC;
1463    }
1464
1465    fconfig->flag = 0x0;
1466    if ((config->durability_opt & FDB_DRB_ODIRECT) &&
1467        config->buffercache_size) {
1468        fconfig->flag |= _ARCH_O_DIRECT;
1469    }
1470
1471    fconfig->prefetch_duration = config->prefetch_duration;
1472    fconfig->num_wal_shards = config->num_wal_partitions;
1473    fconfig->num_bcache_shards = config->num_bcache_partitions;
1474    fconfig->encryption_key = config->encryption_key;
1475    atomic_store_uint64_t(&fconfig->block_reusing_threshold,
1476                          config->block_reusing_threshold,
1477                          std::memory_order_relaxed);
1478    atomic_store_uint64_t(&fconfig->num_keeping_headers,
1479                          config->num_keeping_headers,
1480                          std::memory_order_relaxed);
1481}
1482
1483fdb_status _fdb_clone_snapshot(fdb_kvs_handle *handle_in,
1484                               fdb_kvs_handle *handle_out)
1485{
1486    fdb_status status;
1487
1488    handle_out->config = handle_in->config;
1489    handle_out->kvs_config = handle_in->kvs_config;
1490    handle_out->fileops = handle_in->fileops;
1491    handle_out->file = handle_in->file;
1492    // Note that the file ref count will be decremented when the cloned snapshot
1493    // is closed through filemgr_close().
1494    filemgr_incr_ref_count(handle_out->file);
1495
1496    bool filename_allocated = false;
1497    if (handle_out->filename) {
1498        handle_out->filename = (char *)realloc(handle_out->filename,
1499                                               strlen(handle_in->filename)+1);
1500    } else {
1501        handle_out->filename = (char*)malloc(strlen(handle_in->filename)+1);
1502        filename_allocated = true;
1503    }
1504    strcpy(handle_out->filename, handle_in->filename);
1505
1506    // initialize the docio handle.
1507    handle_out->dhandle = (struct docio_handle *)
1508        calloc(1, sizeof(struct docio_handle));
1509    handle_out->dhandle->log_callback = &handle_out->log_callback;
1510    status = docio_init(handle_out->dhandle, handle_out->file,
1511                        handle_out->config.compress_document_body);
1512    if (status != FDB_RESULT_SUCCESS) {
1513        free(handle_out->dhandle);
1514        if (filename_allocated) {
1515            free(handle_out->filename);
1516        }
1517        return status;
1518    }
1519
1520    // initialize the btree block handle.
1521    handle_out->btreeblkops = btreeblk_get_ops();
1522    handle_out->bhandle = (struct btreeblk_handle *)
1523        calloc(1, sizeof(struct btreeblk_handle));
1524    handle_out->bhandle->log_callback = &handle_out->log_callback;
1525    btreeblk_init(handle_out->bhandle, handle_out->file, handle_out->file->blocksize);
1526
1527    handle_out->dirty_updates = handle_in->dirty_updates;
1528    atomic_store_uint64_t(&handle_out->cur_header_revnum, handle_in->cur_header_revnum);
1529    handle_out->last_wal_flush_hdr_bid = handle_in->last_wal_flush_hdr_bid;
1530    handle_out->kv_info_offset = handle_in->kv_info_offset;
1531    handle_out->op_stats = handle_in->op_stats;
1532
1533    // initialize the trie handle
1534    handle_out->trie = (struct hbtrie *)malloc(sizeof(struct hbtrie));
1535    hbtrie_init(handle_out->trie, handle_out->config.chunksize, OFFSET_SIZE,
1536                handle_out->file->blocksize,
1537                handle_in->trie->root_bid, // Source snapshot's trie root bid
1538                (void *)handle_out->bhandle, handle_out->btreeblkops,
1539                (void *)handle_out->dhandle, _fdb_readkey_wrap);
1540    // set aux for cmp wrapping function
1541    hbtrie_set_leaf_height_limit(handle_out->trie, 0xff);
1542    hbtrie_set_leaf_cmp(handle_out->trie, _fdb_custom_cmp_wrap);
1543
1544    if (handle_out->kvs) {
1545        hbtrie_set_map_function(handle_out->trie, fdb_kvs_find_cmp_chunk);
1546    }
1547
1548    handle_out->seqnum = handle_in->seqnum;
1549    if (handle_out->config.seqtree_opt == FDB_SEQTREE_USE) {
1550        if (handle_out->config.multi_kv_instances) {
1551            // multi KV instance mode .. HB+trie
1552            handle_out->seqtrie = (struct hbtrie *)malloc(sizeof(struct hbtrie));
1553            hbtrie_init(handle_out->seqtrie, sizeof(fdb_kvs_id_t), OFFSET_SIZE,
1554                        handle_out->file->blocksize,
1555                        handle_in->seqtrie->root_bid, // Source snapshot's seqtrie root bid
1556                        (void *)handle_out->bhandle, handle_out->btreeblkops,
1557                        (void *)handle_out->dhandle, _fdb_readseq_wrap);
1558
1559        } else {
1560            // single KV instance mode .. normal B+tree
1561            struct btree_kv_ops *seq_kv_ops =
1562                (struct btree_kv_ops *)malloc(sizeof(struct btree_kv_ops));
1563            seq_kv_ops = btree_kv_get_kb64_vb64(seq_kv_ops);
1564            seq_kv_ops->cmp = _cmp_uint64_t_endian_safe;
1565
1566            handle_out->seqtree = (struct btree*)malloc(sizeof(struct btree));
1567            // Init the seq tree using the root bid of the source snapshot.
1568            btree_init_from_bid(handle_out->seqtree, (void *)handle_out->bhandle,
1569                                handle_out->btreeblkops, seq_kv_ops,
1570                                handle_out->config.blocksize,
1571                                handle_in->seqtree->root_bid);
1572        }
1573    } else{
1574        handle_out->seqtree = NULL;
1575    }
1576
1577    status = btreeblk_end(handle_out->bhandle);
1578    if (status != FDB_RESULT_SUCCESS) {
1579        const char *msg = "Snapshot clone operation fails due to the errors in "
1580            "btreeblk_end() in a database file '%s'\n";
1581        fdb_log(&handle_in->log_callback, status, msg, handle_in->file->filename);
1582    }
1583
1584    return status;
1585}
1586
1587fdb_status _fdb_open(fdb_kvs_handle *handle,
1588                     const char *filename,
1589                     fdb_filename_mode_t filename_mode,
1590                     const fdb_config *config)
1591{
1592    struct filemgr_config fconfig;
1593    struct kvs_stat stat, empty_stat;
1594    bid_t trie_root_bid = BLK_NOT_FOUND;
1595    bid_t seq_root_bid = BLK_NOT_FOUND;
1596    bid_t stale_root_bid = BLK_NOT_FOUND;
1597    fdb_seqnum_t seqnum = 0;
1598    filemgr_header_revnum_t header_revnum = 0;
1599    filemgr_header_revnum_t latest_header_revnum = 0;
1600    fdb_seqtree_opt_t seqtree_opt = config->seqtree_opt;
1601    uint64_t ndocs = 0;
1602    uint64_t ndeletes = 0;
1603    uint64_t datasize = 0;
1604    uint64_t deltasize = 0;
1605    uint64_t last_wal_flush_hdr_bid = BLK_NOT_FOUND;
1606    uint64_t kv_info_offset = BLK_NOT_FOUND;
1607    uint64_t version;
1608    uint64_t header_flags = 0;
1609    uint8_t header_buf[FDB_BLOCKSIZE];
1610    char *compacted_filename = NULL;
1611    char *prev_filename = NULL;
1612    size_t header_len = 0;
1613    bool multi_kv_instances = config->multi_kv_instances;
1614
1615    uint64_t nlivenodes = 0;
1616    bid_t hdr_bid = 0; // initialize to zero for in-memory snapshot
1617    char actual_filename[FDB_MAX_FILENAME_LEN];
1618    char virtual_filename[FDB_MAX_FILENAME_LEN];
1619    char *target_filename = NULL;
1620    fdb_status status;
1621
1622    if (filename == NULL) {
1623        return FDB_RESULT_INVALID_ARGS;
1624    }
1625    if (strlen(filename) > (FDB_MAX_FILENAME_LEN - 8)) {
1626        // filename (including path) length is supported up to
1627        // (FDB_MAX_FILENAME_LEN - 8) bytes.
1628        return FDB_RESULT_TOO_LONG_FILENAME;
1629    }
1630
1631    if (filename_mode == FDB_VFILENAME &&
1632        !compactor_is_valid_mode(filename, (fdb_config *)config)) {
1633        return FDB_RESULT_INVALID_COMPACTION_MODE;
1634    }
1635
1636    _fdb_init_file_config(config, &fconfig);
1637
1638    if (filename_mode == FDB_VFILENAME) {
1639        compactor_get_actual_filename(filename, actual_filename,
1640                                      config->compaction_mode, &handle->log_callback);
1641    } else {
1642        strcpy(actual_filename, filename);
1643    }
1644
1645    if ( config->compaction_mode == FDB_COMPACTION_MANUAL ||
1646         (config->compaction_mode == FDB_COMPACTION_AUTO   &&
1647          filename_mode == FDB_VFILENAME) ) {
1648        // 1) manual compaction mode, OR
1649        // 2) auto compaction mode + 'filename' is virtual filename
1650        // -> copy 'filename'
1651        target_filename = (char *)filename;
1652    } else {
1653        // otherwise (auto compaction mode + 'filename' is actual filename)
1654        // -> copy 'virtual_filename'
1655        compactor_get_virtual_filename(filename, virtual_filename);
1656        target_filename = virtual_filename;
1657    }
1658
1659    // If the user is requesting legacy CRC pass that down to filemgr
1660    if(config->flags & FDB_OPEN_WITH_LEGACY_CRC) {
1661        fconfig.options |= FILEMGR_CREATE_CRC32;
1662    }
1663
1664    handle->fileops = get_filemgr_ops();
1665    filemgr_open_result result = filemgr_open((char *)actual_filename,
1666                                              handle->fileops,
1667                                              &fconfig, &handle->log_callback);
1668    if (result.rv != FDB_RESULT_SUCCESS) {
1669        return (fdb_status) result.rv;
1670    }
1671    handle->file = result.file;
1672
1673    if (config->compaction_mode == FDB_COMPACTION_MANUAL &&
1674        strcmp(filename, actual_filename)) {
1675        // It is in-place compacted file if
1676        // 1) compaction mode is manual, and
1677        // 2) actual filename is different to the filename given by user.
1678        // In this case, set the in-place compaction flag.
1679        filemgr_set_in_place_compaction(handle->file, true);
1680    }
1681    if (filemgr_is_in_place_compaction_set(handle->file)) {
1682        // This file was in-place compacted.
1683        // set 'handle->filename' to the original filename to trigger file renaming
1684        compactor_get_virtual_filename(filename, virtual_filename);
1685        target_filename = virtual_filename;
1686    }
1687
1688    if (handle->filename) {
1689        handle->filename = (char *)realloc(handle->filename,
1690                                           strlen(target_filename)+1);
1691    } else {
1692        handle->filename = (char*)malloc(strlen(target_filename)+1);
1693    }
1694    strcpy(handle->filename, target_filename);
1695
1696    // If cloning from a snapshot handle, fdb_snapshot_open would have already
1697    // set handle->last_hdr_bid to the block id of required header, so rewind..
1698    bid_t last_hdr_bid = atomic_get_uint64_t(&handle->last_hdr_bid);
1699    if (handle->shandle && last_hdr_bid) {
1700        status = filemgr_fetch_header(handle->file, last_hdr_bid,
1701                                      header_buf, &header_len, &seqnum,
1702                                      &latest_header_revnum, &deltasize, &version,
1703                                      NULL, &handle->log_callback);
1704        if (status != FDB_RESULT_SUCCESS) {
1705            free(handle->filename);
1706            handle->filename = NULL;
1707            filemgr_close(handle->file, false, handle->filename,
1708                              &handle->log_callback);
1709            return status;
1710        }
1711    } else { // Normal open
1712        filemgr_get_header(handle->file, header_buf, &header_len,
1713                           &last_hdr_bid, &seqnum, &latest_header_revnum);
1714        atomic_store_uint64_t(&handle->last_hdr_bid, last_hdr_bid);
1715        version = handle->file->version;
1716    }
1717
1718    // initialize the docio handle so kv headers may be read
1719    handle->dhandle = (struct docio_handle *)
1720                      calloc(1, sizeof(struct docio_handle));
1721    handle->dhandle->log_callback = &handle->log_callback;
1722    status = docio_init(handle->dhandle, handle->file,
1723                        config->compress_document_body);
1724    if (status != FDB_RESULT_SUCCESS) {
1725        free(handle->dhandle);
1726        free(handle->filename);
1727        handle->filename = NULL;
1728        filemgr_close(handle->file, false, handle->filename,
1729                          &handle->log_callback);
1730        return status;
1731    }
1732
1733    // fetch previous superblock bitmap info if exists
1734    // (this should be done after 'handle->dhandle' is initialized)
1735    if (handle->file->sb) {
1736        status = sb_bmp_fetch_doc(handle);
1737        if (status != FDB_RESULT_SUCCESS) {
1738            docio_free(handle->dhandle);
1739            free(handle->dhandle);
1740            free(handle->filename);
1741            handle->filename = NULL;
1742            filemgr_close(handle->file, false, handle->filename,
1743                              &handle->log_callback);
1744            return status;
1745        }
1746    }
1747
1748
1749    if (header_len > 0) {
1750        fdb_fetch_header(version, header_buf, &trie_root_bid, &seq_root_bid,
1751                         &stale_root_bid, &ndocs, &ndeletes, &nlivenodes,
1752                         &datasize, &last_wal_flush_hdr_bid, &kv_info_offset,
1753                         &header_flags, &compacted_filename, &prev_filename);
1754        // use existing setting for seqtree_opt
1755        if (header_flags & FDB_FLAG_SEQTREE_USE) {
1756            seqtree_opt = FDB_SEQTREE_USE;
1757        } else {
1758            seqtree_opt = FDB_SEQTREE_NOT_USE;
1759        }
1760        // Retrieve seqnum for multi-kv mode
1761        if (handle->kvs && handle->kvs->id > 0) {
1762            if (kv_info_offset != BLK_NOT_FOUND) {
1763                if (!filemgr_get_kv_header(handle->file)) {
1764                    struct kvs_header *kv_header;
1765                    _fdb_kvs_header_create(&kv_header);
1766                    // KV header already exists but not loaded .. read & import
1767                    fdb_kvs_header_read(kv_header, handle->dhandle,
1768                                        kv_info_offset, version, false);
1769                    if (!filemgr_set_kv_header(handle->file, kv_header,
1770                                               fdb_kvs_header_free)) {
1771                        _fdb_kvs_header_free(kv_header);
1772                    }
1773                }
1774                seqnum = _fdb_kvs_get_seqnum(handle->file->kv_header,
1775                                             handle->kvs->id);
1776            } else { // no kv_info offset, ok to set seqnum to zero
1777                seqnum = 0;
1778            }
1779        }
1780        // other flags
1781        if (header_flags & FDB_FLAG_ROOT_INITIALIZED) {
1782            handle->fhandle->flags |= FHANDLE_ROOT_INITIALIZED;
1783        }
1784        if (header_flags & FDB_FLAG_ROOT_CUSTOM_CMP) {
1785            handle->fhandle->flags |= FHANDLE_ROOT_CUSTOM_CMP;
1786        }
1787        if (header_flags & FDB_FLAG_SUCCESSFULLY_COMPACTED) {
1788            filemgr_set_successfully_compacted(handle->file);
1789        }
1790        // use existing setting for multi KV instance mode
1791        if (kv_info_offset == BLK_NOT_FOUND) {
1792            multi_kv_instances = false;
1793        } else {
1794            multi_kv_instances = true;
1795        }
1796    }
1797
1798    handle->config = *config;
1799    handle->config.seqtree_opt = seqtree_opt;
1800    handle->config.multi_kv_instances = multi_kv_instances;
1801
1802    if (handle->shandle && handle->max_seqnum == FDB_SNAPSHOT_INMEM) {
1803        // Either an in-memory snapshot or cloning from an existing snapshot..
1804        hdr_bid = 0; // This prevents _fdb_restore_wal() as incoming handle's
1805                     // *_open() should have already restored it
1806    } else { // Persisted snapshot or file rollback..
1807
1808        // get the BID of the latest block
1809        // (it is OK if the block is not a DB header)
1810        bool dirty_data_exists = false;
1811        struct superblock *sb = handle->file->sb;
1812
1813        if (sb_bmp_exists(sb)) {
1814            dirty_data_exists = false;
1815            bid_t sb_last_hdr_bid = atomic_get_uint64_t(&sb->last_hdr_bid);
1816            if (sb_last_hdr_bid != BLK_NOT_FOUND) {
1817                // add 1 since we subtract 1 from 'hdr_bid' below soon
1818                hdr_bid = sb_last_hdr_bid + 1;
1819                if (atomic_get_uint64_t(&sb->cur_alloc_bid) != hdr_bid) {
1820                    // seq number has been increased since the last commit
1821                    seqnum = fdb_kvs_get_committed_seqnum(handle);
1822                }
1823            } else {
1824                hdr_bid = BLK_NOT_FOUND;
1825            }
1826        } else {
1827            hdr_bid = filemgr_get_pos(handle->file) / FDB_BLOCKSIZE;
1828            dirty_data_exists = (hdr_bid >
1829                        atomic_get_uint64_t(&handle->last_hdr_bid));
1830        }
1831
1832        if (hdr_bid == BLK_NOT_FOUND ||
1833            (sb && hdr_bid <= sb->config->num_sb)) {
1834            hdr_bid = 0;
1835        } else if (hdr_bid > 0) {
1836            --hdr_bid;
1837        }
1838
1839        if (handle->max_seqnum) {
1840            struct kvs_stat stat_ori;
1841            // backup original stats
1842            if (handle->kvs) {
1843                _kvs_stat_get(handle->file, handle->kvs->id, &stat_ori);
1844            } else {
1845                _kvs_stat_get(handle->file, 0, &stat_ori);
1846            }
1847
1848            if (dirty_data_exists){
1849                // uncommitted data exists beyond the last DB header
1850                // get the last committed seq number
1851                fdb_seqnum_t seq_commit;
1852                seq_commit = fdb_kvs_get_committed_seqnum(handle);
1853                if (seq_commit == 0 || seq_commit < handle->max_seqnum) {
1854                    // In case, snapshot_open is attempted with latest uncommitted
1855                    // sequence number
1856                    header_len = 0;
1857                } else if (seq_commit == handle->max_seqnum) {
1858                    // snapshot/rollback on the latest commit header
1859                    seqnum = seq_commit; // skip file reverse scan
1860                }
1861                hdr_bid = filemgr_get_header_bid(handle->file);
1862            }
1863            // Reverse scan the file to locate the DB header with seqnum marker
1864            header_revnum = latest_header_revnum;
1865            while (header_len && seqnum != handle->max_seqnum) {
1866                hdr_bid = filemgr_fetch_prev_header(handle->file, hdr_bid,
1867                                          header_buf, &header_len, &seqnum,
1868                                          &header_revnum, NULL, &version, NULL,
1869                                          &handle->log_callback);
1870                if (header_len == 0) {
1871                    continue; // header doesn't exist
1872                }
1873                fdb_fetch_header(version, header_buf, &trie_root_bid,
1874                                 &seq_root_bid, &stale_root_bid,
1875                                 &ndocs, &ndeletes, &nlivenodes,
1876                                 &datasize, &last_wal_flush_hdr_bid,
1877                                 &kv_info_offset, &header_flags,
1878                                 &compacted_filename, NULL);
1879                atomic_store_uint64_t(&handle->last_hdr_bid, hdr_bid);
1880
1881                if (!handle->kvs || handle->kvs->id == 0) {
1882                    // single KVS mode OR default KVS
1883                    if (!handle->shandle) {
1884                        // rollback
1885                        struct kvs_stat stat_dst;
1886                        _kvs_stat_get(handle->file, 0, &stat_dst);
1887                        stat_dst.ndocs = ndocs;
1888                        stat_dst.ndeletes = ndeletes;
1889                        stat_dst.datasize = datasize;
1890                        stat_dst.nlivenodes = nlivenodes;
1891                        stat_dst.deltasize = deltasize;
1892                        _kvs_stat_set(handle->file, 0, stat_dst);
1893                    }
1894                    continue;
1895                }
1896
1897                int64_t doc_offset;
1898                struct kvs_header *kv_header;
1899                struct docio_object doc;
1900
1901                _fdb_kvs_header_create(&kv_header);
1902                memset(&doc, 0, sizeof(struct docio_object));
1903                doc_offset = docio_read_doc(handle->dhandle,
1904                                            kv_info_offset, &doc, true);
1905
1906                if (doc_offset <= 0) {
1907                    header_len = 0; // fail
1908                    _fdb_kvs_header_free(kv_header);
1909                } else {
1910                    _fdb_kvs_header_import(kv_header, doc.body,
1911                                           doc.length.bodylen, version, false);
1912                    // get local sequence number for the KV instance
1913                    seqnum = _fdb_kvs_get_seqnum(kv_header,
1914                                                 handle->kvs->id);
1915                    if (!handle->shandle) {
1916                        // rollback: replace kv_header stats
1917                        // read from the current header's kv_header
1918                        struct kvs_stat stat_src, stat_dst;
1919                        _kvs_stat_get_kv_header(kv_header,
1920                                                handle->kvs->id,
1921                                                &stat_src);
1922                        _kvs_stat_get(handle->file,
1923                                      handle->kvs->id,
1924                                      &stat_dst);
1925                        // update ndocs, datasize, nlivenodes
1926                        // into the current file's kv_header
1927                        // Note: stats related to WAL should not be updated
1928                        //       at this time. They will be adjusted through
1929                        //       discard & restore routines below.
1930                        stat_dst.ndocs = stat_src.ndocs;
1931                        stat_dst.datasize = stat_src.datasize;
1932                        stat_dst.nlivenodes = stat_src.nlivenodes;
1933                        _kvs_stat_set(handle->file,
1934                                      handle->kvs->id,
1935                                      stat_dst);
1936                    }
1937                    _fdb_kvs_header_free(kv_header);
1938                    free_docio_object(&doc, 1, 1, 1);
1939                }
1940            }
1941
1942            if (header_len && // header exists
1943                config->block_reusing_threshold > 0 && // block reuse is enabled
1944                config->block_reusing_threshold < 100 &&
1945                header_revnum < sb_get_min_live_revnum(handle->file)) {
1946                // cannot perform rollback/snapshot beyond the last live header
1947                header_len = 0;
1948            }
1949
1950            if (!header_len) { // Marker MUST match that of DB commit!
1951                // rollback original stats
1952                if (handle->kvs) {
1953                    _kvs_stat_get(handle->file, handle->kvs->id, &stat_ori);
1954                } else {
1955                    _kvs_stat_get(handle->file, 0, &stat_ori);
1956                }
1957
1958                docio_free(handle->dhandle);
1959                free(handle->dhandle);
1960                free(handle->filename);
1961                free(prev_filename);
1962                handle->filename = NULL;
1963                filemgr_close(handle->file, false, handle->filename,
1964                              &handle->log_callback);
1965                return FDB_RESULT_NO_DB_INSTANCE;
1966            }
1967
1968            if (!handle->shandle) { // Rollback mode, destroy file WAL..
1969                if (handle->config.multi_kv_instances) {
1970                    // multi KV instance mode
1971                    // clear only WAL items belonging to the instance
1972                    wal_close_kv_ins(handle->file,
1973                                     (handle->kvs)?(handle->kvs->id):(0),
1974                                     &handle->log_callback);
1975                } else {
1976                    wal_shutdown(handle->file, &handle->log_callback);
1977                }
1978            }
1979        } else { // snapshot to sequence number 0 requested..
1980            if (handle->shandle) { // fdb_snapshot_open API call
1981                if (seqnum) {
1982                    // Database currently has a non-zero seq number,
1983                    // but the snapshot was requested with a seq number zero.
1984                    docio_free(handle->dhandle);
1985                    free(handle->dhandle);
1986                    free(handle->filename);
1987                    free(prev_filename);
1988                    handle->filename = NULL;
1989                    filemgr_close(handle->file, false, handle->filename,
1990                                  &handle->log_callback);
1991                    return FDB_RESULT_NO_DB_INSTANCE;
1992                }
1993            } // end of zero max_seqnum but non-rollback check
1994        } // end of zero max_seqnum check
1995    } // end of durable snapshot locating
1996
1997    handle->btreeblkops = btreeblk_get_ops();
1998    handle->bhandle = (struct btreeblk_handle *)
1999                      calloc(1, sizeof(struct btreeblk_handle));
2000    handle->bhandle->log_callback = &handle->log_callback;
2001
2002    handle->dirty_updates = 0;
2003
2004    if (handle->config.compaction_buf_maxsize == 0) {
2005        handle->config.compaction_buf_maxsize = FDB_COMP_BUF_MINSIZE;
2006    }
2007
2008    btreeblk_init(handle->bhandle, handle->file, handle->file->blocksize);
2009
2010    handle->cur_header_revnum = latest_header_revnum;
2011    if (header_revnum) {
2012        if (filemgr_is_rollback_on(handle->file)) {
2013            // rollback mode
2014            // set rollback header revnum
2015            handle->rollback_revnum = header_revnum;
2016        } else {
2017            // snapshot mode (only for snapshot)
2018            handle->cur_header_revnum = header_revnum;
2019        }
2020    }
2021    handle->last_wal_flush_hdr_bid = last_wal_flush_hdr_bid;
2022
2023    memset(&empty_stat, 0x0, sizeof(empty_stat));
2024    _kvs_stat_get(handle->file, 0, &stat);
2025    if (!memcmp(&stat, &empty_stat, sizeof(stat))) { // first open
2026        // sync (default) KVS stat with DB header
2027        stat.nlivenodes = nlivenodes;
2028        stat.ndocs = ndocs;
2029        stat.datasize = datasize;
2030        _kvs_stat_set(handle->file, 0, stat);
2031    }
2032
2033    handle->kv_info_offset = kv_info_offset;
2034    if (handle->config.multi_kv_instances && !handle->shandle) {
2035        // multi KV instance mode
2036        filemgr_mutex_lock(handle->file);
2037        if (kv_info_offset == BLK_NOT_FOUND) {
2038            // there is no KV header .. create & initialize
2039            fdb_kvs_header_create(handle->file);
2040            // TODO: If another handle is opened before the first header is appended,
2041            // an unnecessary KV info doc is appended. We need to address it.
2042            kv_info_offset = fdb_kvs_header_append(handle);
2043        } else if (handle->file->kv_header == NULL) {
2044            // KV header already exists but not loaded .. read & import
2045            fdb_kvs_header_create(handle->file);
2046            fdb_kvs_header_read(handle->file->kv_header, handle->dhandle,
2047                                kv_info_offset, version, false);
2048        }
2049        filemgr_mutex_unlock(handle->file);
2050
2051        // validation check for key order of all KV stores
2052        if (handle == handle->fhandle->root) {
2053            fdb_status fs = fdb_kvs_cmp_check(handle);
2054            if (fs != FDB_RESULT_SUCCESS) { // cmp function mismatch
2055                docio_free(handle->dhandle);
2056                free(handle->dhandle);
2057                btreeblk_free(handle->bhandle);
2058                free(handle->bhandle);
2059                free(handle->filename);
2060                handle->filename = NULL;
2061                filemgr_close(handle->file, false, handle->filename,
2062                              &handle->log_callback);
2063                return fs;
2064            }
2065        }
2066    }
2067    handle->kv_info_offset = kv_info_offset;
2068
2069    if (handle->kv_info_offset != BLK_NOT_FOUND &&
2070        handle->kvs == NULL) {
2071        // multi KV instance mode .. turn on config flag
2072        handle->config.multi_kv_instances = true;
2073        // only super handle can be opened using fdb_open(...)
2074        fdb_kvs_info_create(NULL, handle, handle->file, NULL);
2075    }
2076
2077    if (handle->shandle) { // Populate snapshot stats..
2078        if (kv_info_offset == BLK_NOT_FOUND) { // Single KV mode
2079            memset(&handle->shandle->stat, 0x0,
2080                    sizeof(handle->shandle->stat));
2081            handle->shandle->stat.ndocs = ndocs;
2082            handle->shandle->stat.datasize = datasize;
2083            handle->shandle->stat.nlivenodes = nlivenodes;
2084        } else { // Multi KV instance mode, populate specific kv stats
2085            memset(&handle->shandle->stat, 0x0,
2086                    sizeof(handle->shandle->stat));
2087            _kvs_stat_get(handle->file, handle->kvs->id,
2088                    &handle->shandle->stat);
2089            // Since wal is restored below, we have to reset
2090            // wal stats to zero.
2091            handle->shandle->stat.wal_ndeletes = 0;
2092            handle->shandle->stat.wal_ndocs = 0;
2093        }
2094    }
2095
2096    // initialize pointer to the global operational stats of this KV store
2097    handle->op_stats = filemgr_get_ops_stats(handle->file, handle->kvs);
2098    if (!handle->op_stats) {
2099        const char *msg = "Database open fails due to the error in retrieving "
2100            "the global operational stats of KV store in a database file '%s'\n";
2101        fdb_log(&handle->log_callback, FDB_RESULT_OPEN_FAIL, msg,
2102                handle->file->filename);
2103        return FDB_RESULT_OPEN_FAIL;
2104    }
2105
2106    handle->trie = (struct hbtrie *)malloc(sizeof(struct hbtrie));
2107    hbtrie_init(handle->trie, config->chunksize, OFFSET_SIZE,
2108                handle->file->blocksize, trie_root_bid,
2109                (void *)handle->bhandle, handle->btreeblkops,
2110                (void *)handle->dhandle, _fdb_readkey_wrap);
2111    // set aux for cmp wrapping function
2112    hbtrie_set_leaf_height_limit(handle->trie, 0xff);
2113    hbtrie_set_leaf_cmp(handle->trie, _fdb_custom_cmp_wrap);
2114
2115    if (handle->kvs) {
2116        hbtrie_set_map_function(handle->trie, fdb_kvs_find_cmp_chunk);
2117    }
2118
2119    handle->seqnum = seqnum;
2120    if (handle->config.seqtree_opt == FDB_SEQTREE_USE) {
2121        if (handle->config.multi_kv_instances) {
2122            // multi KV instance mode .. HB+trie
2123            handle->seqtrie = (struct hbtrie *)malloc(sizeof(struct hbtrie));
2124            hbtrie_init(handle->seqtrie, sizeof(fdb_kvs_id_t), OFFSET_SIZE,
2125                        handle->file->blocksize, seq_root_bid,
2126                        (void *)handle->bhandle, handle->btreeblkops,
2127                        (void *)handle->dhandle, _fdb_readseq_wrap);
2128
2129        } else {
2130            // single KV instance mode .. normal B+tree
2131            struct btree_kv_ops *seq_kv_ops =
2132                (struct btree_kv_ops *)malloc(sizeof(struct btree_kv_ops));
2133            seq_kv_ops = btree_kv_get_kb64_vb64(seq_kv_ops);
2134            seq_kv_ops->cmp = _cmp_uint64_t_endian_safe;
2135
2136            handle->seqtree = (struct btree*)malloc(sizeof(struct btree));
2137            if (seq_root_bid == BLK_NOT_FOUND) {
2138                btree_init(handle->seqtree, (void *)handle->bhandle,
2139                           handle->btreeblkops, seq_kv_ops,
2140                           handle->config.blocksize, sizeof(fdb_seqnum_t),
2141                           OFFSET_SIZE, 0x0, NULL);
2142            }else{
2143                btree_init_from_bid(handle->seqtree, (void *)handle->bhandle,
2144                                    handle->btreeblkops, seq_kv_ops,
2145                                    handle->config.blocksize, seq_root_bid);
2146            }
2147        }
2148    }else{
2149        handle->seqtree = NULL;
2150    }
2151
2152    // Stale-block tree (supported since MAGIC_002)
2153    // this tree is independent to multi/single KVS mode option
2154    if (ver_staletree_support(handle->file->version)) {
2155        // normal B+tree
2156        struct btree_kv_ops *stale_kv_ops =
2157            (struct btree_kv_ops *)calloc(1, sizeof(struct btree_kv_ops));
2158        stale_kv_ops = btree_kv_get_kb64_vb64(stale_kv_ops);
2159        stale_kv_ops->cmp = _cmp_uint64_t_endian_safe;
2160
2161        handle->staletree = (struct btree*)calloc(1, sizeof(struct btree));
2162        if (stale_root_bid == BLK_NOT_FOUND) {
2163            btree_init(handle->staletree, (void *)handle->bhandle,
2164                       handle->btreeblkops, stale_kv_ops,
2165                       handle->config.blocksize, sizeof(filemgr_header_revnum_t),
2166                       OFFSET_SIZE, 0x0, NULL);
2167         }else{
2168            btree_init_from_bid(handle->staletree, (void *)handle->bhandle,
2169                                handle->btreeblkops, stale_kv_ops,
2170                                handle->config.blocksize, stale_root_bid);
2171            // prefetch stale info into memory
2172            fdb_load_inmem_stale_info(handle);
2173         }
2174    } else {
2175        handle->staletree = NULL;
2176    }
2177
2178    if (handle->config.multi_kv_instances && handle->max_seqnum) {
2179        // restore only docs belonging to the KV instance
2180        // handle->kvs should not be NULL
2181        _fdb_restore_wal(handle, FDB_RESTORE_KV_INS,
2182                         hdr_bid, (handle->kvs)?(handle->kvs->id):(0));
2183    } else {
2184        // normal restore
2185        _fdb_restore_wal(handle, FDB_RESTORE_NORMAL, hdr_bid, 0);
2186    }
2187
2188    if (compacted_filename &&
2189        filemgr_get_file_status(handle->file) == FILE_NORMAL &&
2190        !(config->flags & FDB_OPEN_FLAG_RDONLY)) { // do not recover read-only
2191        _fdb_recover_compaction(handle, compacted_filename);
2192    }
2193
2194    if (compacted_filename) {
2195        filemgr_update_file_linkage(handle->file, NULL, compacted_filename);
2196    }
2197
2198    if (prev_filename) {
2199        if (!handle->shandle && strcmp(prev_filename, handle->file->filename)) {
2200            // record the old filename into the file handle of current file
2201            // and REMOVE old file on the first open
2202            // WARNING: snapshots must have been opened before this call
2203            if (filemgr_update_file_linkage(handle->file, prev_filename, NULL)) {
2204                // Open the old file with read-only mode.
2205                // (Temporarily disable log callback at this time since
2206                //  the old file might be already removed.)
2207                err_log_callback dummy_cb;
2208                dummy_cb.callback = fdb_dummy_log_callback;
2209                dummy_cb.ctx_data = NULL;
2210                fconfig.options = FILEMGR_READONLY;
2211                filemgr_open_result result = filemgr_open(prev_filename,
2212                                                          handle->fileops,
2213                                                          &fconfig,
2214                                                          &dummy_cb);
2215                if (result.file) {
2216                    filemgr_remove_pending(result.file, handle->file,
2217                                           &handle->log_callback);
2218                    filemgr_close(result.file, 0, handle->filename,
2219                                  &handle->log_callback);
2220                }
2221            }
2222        }
2223        // we allocated a memory region for file->old_filename and
2224        // prev_filename would be copied to there,
2225        // so it is OK to free it here whatever the result is.
2226        free(prev_filename);
2227    }
2228
2229    status = btreeblk_end(handle->bhandle);
2230    if (status != FDB_RESULT_SUCCESS) {
2231        // When fdb_kvs_open() is being issued in parallel with fdb_open()
2232        // it is possible that this call (fdb_open()) hits a write failure
2233        // because the btreeblock to be written was already made immutable
2234        // by the commit from the fdb_kvs_open(). Simpy ignore this error case.
2235        if (status == FDB_RESULT_WRITE_FAIL) {
2236            if (filemgr_get_header_revnum(handle->file)
2237                                             == latest_header_revnum) {
2238                return status;
2239            } else {
2240                status = FDB_RESULT_SUCCESS;
2241            }
2242        } else {
2243            return status;
2244        }
2245    }
2246
2247    // do not register read-only handles
2248    if (!(config->flags & FDB_OPEN_FLAG_RDONLY)) {
2249        if (config->compaction_mode == FDB_COMPACTION_AUTO) {
2250            status = compactor_register_file(handle->file,
2251                                             (fdb_config *)config,
2252                                             &handle->log_callback);
2253        }
2254        if (status == FDB_RESULT_SUCCESS) {
2255            status = bgflusher_register_file(handle->file,
2256                                             (fdb_config *)config,
2257                                             &handle->log_callback);
2258        }
2259    }
2260
2261    return status;
2262}
2263
2264LIBFDB_API
2265fdb_status fdb_set_log_callback(fdb_kvs_handle *handle,
2266                                fdb_log_callback log_callback,
2267                                void *ctx_data)
2268{
2269    if (!handle) {
2270        return FDB_RESULT_INVALID_HANDLE;
2271    }
2272
2273    handle->log_callback.callback = log_callback;
2274    handle->log_callback.ctx_data = ctx_data;
2275    return FDB_RESULT_SUCCESS;
2276}
2277
2278LIBFDB_API
2279void fdb_set_fatal_error_callback(fdb_fatal_error_callback err_callback)
2280{
2281    fatal_error_callback = err_callback;
2282}
2283
2284LIBFDB_API
2285fdb_status fdb_doc_create(fdb_doc **doc, const void *key, size_t keylen,
2286                          const void *meta, size_t metalen,
2287                          const void *body, size_t bodylen)
2288{
2289    if (doc == NULL || keylen > FDB_MAX_KEYLEN ||
2290        metalen > FDB_MAX_METALEN || bodylen > FDB_MAX_BODYLEN) {
2291        return FDB_RESULT_INVALID_ARGS;
2292    }
2293
2294    *doc = (fdb_doc*)calloc(1, sizeof(fdb_doc));
2295    if (*doc == NULL) { // LCOV_EXCL_START
2296        return FDB_RESULT_ALLOC_FAIL;
2297    } // LCOV_EXCL_STOP
2298
2299    (*doc)->seqnum = SEQNUM_NOT_USED;
2300
2301    if (key && keylen > 0) {
2302        (*doc)->key = (void *)malloc(keylen);
2303        if ((*doc)->key == NULL) { // LCOV_EXCL_START
2304            return FDB_RESULT_ALLOC_FAIL;
2305        } // LCOV_EXCL_STOP
2306        memcpy((*doc)->key, key, keylen);
2307        (*doc)->keylen = keylen;
2308    } else {
2309        (*doc)->key = NULL;
2310        (*doc)->keylen = 0;
2311    }
2312
2313    if (meta && metalen > 0) {
2314        (*doc)->meta = (void *)malloc(metalen);
2315        if ((*doc)->meta == NULL) { // LCOV_EXCL_START
2316            return FDB_RESULT_ALLOC_FAIL;
2317        } // LCOV_EXCL_STOP
2318        memcpy((*doc)->meta, meta, metalen);
2319        (*doc)->metalen = metalen;
2320    } else {
2321        (*doc)->meta = NULL;
2322        (*doc)->metalen = 0;
2323    }
2324
2325    if (body && bodylen > 0) {
2326        (*doc)->body = (void *)malloc(bodylen);
2327        if ((*doc)->body == NULL) { // LCOV_EXCL_START
2328            return FDB_RESULT_ALLOC_FAIL;
2329        } // LCOV_EXCL_STOP
2330        memcpy((*doc)->body, body, bodylen);
2331        (*doc)->bodylen = bodylen;
2332    } else {
2333        (*doc)->body = NULL;
2334        (*doc)->bodylen = 0;
2335    }
2336
2337    return FDB_RESULT_SUCCESS;
2338}
2339
2340LIBFDB_API
2341fdb_status fdb_doc_update(fdb_doc **doc,
2342                          const void *meta, size_t metalen,
2343                          const void *body, size_t bodylen)
2344{
2345    if (doc == NULL ||
2346        metalen > FDB_MAX_METALEN || bodylen > FDB_MAX_BODYLEN) {
2347        return FDB_RESULT_INVALID_ARGS;
2348    }
2349    if (*doc == NULL) {
2350        return FDB_RESULT_INVALID_ARGS;
2351    }
2352
2353    if (meta && metalen > 0) {
2354        // free previous metadata
2355        free((*doc)->meta);
2356        // allocate new metadata
2357        (*doc)->meta = (void *)malloc(metalen);
2358        if ((*doc)->meta == NULL) { // LCOV_EXCL_START
2359            return FDB_RESULT_ALLOC_FAIL;
2360        } // LCOV_EXCL_STOP
2361        memcpy((*doc)->meta, meta, metalen);
2362        (*doc)->metalen = metalen;
2363    }
2364
2365    if (body && bodylen > 0) {
2366        // free previous body
2367        free((*doc)->body);
2368        // allocate new body
2369        (*doc)->body = (void *)malloc(bodylen);
2370        if ((*doc)->body == NULL) { // LCOV_EXCL_START
2371            return FDB_RESULT_ALLOC_FAIL;
2372        } // LCOV_EXCL_STOP
2373        memcpy((*doc)->body, body, bodylen);
2374        (*doc)->bodylen = bodylen;
2375    }
2376
2377    (*doc)->seqnum = SEQNUM_NOT_USED;
2378    return FDB_RESULT_SUCCESS;
2379}
2380
2381LIBFDB_API
2382void fdb_doc_set_seqnum(fdb_doc *doc,
2383                        const fdb_seqnum_t seqnum)
2384{
2385    if (doc) {
2386        doc->seqnum = seqnum;
2387        if (seqnum != SEQNUM_NOT_USED) {
2388            doc->flags |= FDB_CUSTOM_SEQNUM; // fdb_set will now use above seqnum
2389        } else { // reset custom seqnum flag, fdb_set will now generate new seqnum
2390            doc->flags &= ~FDB_CUSTOM_SEQNUM;
2391        }
2392    }
2393}
2394
2395// doc MUST BE allocated by malloc
2396LIBFDB_API
2397fdb_status fdb_doc_free(fdb_doc *doc)
2398{
2399    if (doc) {
2400        free(doc->key);
2401        free(doc->meta);
2402        free(doc->body);
2403        free(doc);
2404    }
2405    return FDB_RESULT_SUCCESS;
2406}
2407
2408INLINE uint64_t _fdb_wal_get_old_offset(void *voidhandle,
2409                                        struct wal_item *item)
2410{
2411    fdb_kvs_handle *handle = (fdb_kvs_handle *)voidhandle;
2412    uint64_t old_offset = 0;
2413
2414    if (item->action == WAL_ACT_REMOVE) {
2415        // For immediate remove, old_offset value is critical
2416        // so that we should get an exact value.
2417        hbtrie_find(handle->trie,
2418                    item->header->key,
2419                    item->header->keylen,
2420                    (void*)&old_offset);
2421    } else {
2422        hbtrie_find_offset(handle->trie,
2423                           item->header->key,
2424                           item->header->keylen,
2425                           (void*)&old_offset);
2426    }
2427    btreeblk_end(handle->bhandle);
2428    old_offset = _endian_decode(old_offset);
2429
2430    return old_offset;
2431}
2432
2433// A stale sequence number entry that can be purged from the sequence tree
2434// during the WAL flush.
2435struct wal_stale_seq_entry {
2436    fdb_kvs_id_t kv_id;
2437    fdb_seqnum_t seqnum;
2438    struct avl_node avl_entry;
2439};
2440
2441// Delta changes in KV store stats during the WAL flush
2442struct wal_kvs_delta_stat {
2443    fdb_kvs_id_t kv_id;
2444    int64_t nlivenodes;
2445    int64_t ndocs;
2446    int64_t ndeletes;
2447    int64_t datasize;
2448    int64_t deltasize;
2449    struct avl_node avl_entry;
2450};
2451
2452INLINE int _fdb_seq_entry_cmp(struct avl_node *a, struct avl_node *b, void *aux)
2453{
2454    (void) aux;
2455    struct wal_stale_seq_entry *entry1 = _get_entry(a, struct wal_stale_seq_entry,
2456                                                    avl_entry);
2457    struct wal_stale_seq_entry *entry2 = _get_entry(b, struct wal_stale_seq_entry,
2458                                                    avl_entry);
2459    if (entry1->kv_id < entry2->kv_id) {
2460        return -1;
2461    } else if (entry1->kv_id > entry2->kv_id) {
2462        return 1;
2463    } else {
2464        return _CMP_U64(entry1->seqnum, entry2->seqnum);
2465    }
2466}
2467
2468
2469// Compare function to sort KVS delta stat entries in the AVL tree during WAL flush
2470INLINE int _kvs_delta_stat_cmp(struct avl_node *a, struct avl_node *b, void *aux)
2471{
2472    (void) aux;
2473    struct wal_kvs_delta_stat *stat1 = _get_entry(a, struct wal_kvs_delta_stat,
2474                                                  avl_entry);
2475    struct wal_kvs_delta_stat *stat2 = _get_entry(b, struct wal_kvs_delta_stat,
2476                                                  avl_entry);
2477    if (stat1->kv_id < stat2->kv_id) {
2478        return -1;
2479    } else if (stat1->kv_id > stat2->kv_id) {
2480        return 1;
2481    } else {
2482        return 0;
2483    }
2484}
2485
2486INLINE void _fdb_wal_flush_seq_purge(void *dbhandle,
2487                                     struct avl_tree *stale_seqnum_list,
2488                                     struct avl_tree *kvs_delta_stats)
2489{
2490    fdb_seqnum_t _seqnum;
2491    int64_t nlivenodes;
2492    int64_t ndeltanodes;
2493    int64_t delta;
2494    uint8_t kvid_seqnum[sizeof(fdb_kvs_id_t) + sizeof(fdb_seqnum_t)];
2495    struct wal_stale_seq_entry *seq_entry;
2496    struct wal_kvs_delta_stat *delta_stat;
2497    struct wal_kvs_delta_stat kvs_delta_query;
2498
2499    fdb_kvs_handle *handle = (fdb_kvs_handle *)dbhandle;
2500    struct avl_node *node = avl_first(stale_seqnum_list);
2501    while (node) {
2502        seq_entry = _get_entry(node, struct wal_stale_seq_entry, avl_entry);
2503        node = avl_next(node);
2504        nlivenodes = handle->bhandle->nlivenodes;
2505        ndeltanodes = handle->bhandle->ndeltanodes;
2506        _seqnum = _endian_encode(seq_entry->seqnum);
2507        if (handle->kvs) {
2508            // multi KV instance mode .. HB+trie
2509            kvid2buf(sizeof(fdb_kvs_id_t), seq_entry->kv_id, kvid_seqnum);
2510            memcpy(kvid_seqnum + sizeof(fdb_kvs_id_t), &_seqnum, sizeof(fdb_seqnum_t));
2511            hbtrie_remove(handle->seqtrie, (void*)kvid_seqnum,
2512                          sizeof(fdb_kvs_id_t) + sizeof(fdb_seqnum_t));
2513        } else {
2514            btree_remove(handle->seqtree, (void*)&_seqnum);
2515        }
2516        btreeblk_end(handle->bhandle);
2517
2518        kvs_delta_query.kv_id = seq_entry->kv_id;
2519        avl_node *delta_stat_node = avl_search(kvs_delta_stats,
2520                                               &kvs_delta_query.avl_entry,
2521                                               _kvs_delta_stat_cmp);
2522        if (delta_stat_node) {
2523            delta_stat = _get_entry(delta_stat_node, struct wal_kvs_delta_stat,
2524                                    avl_entry);
2525            delta = handle->bhandle->nlivenodes - nlivenodes;
2526            delta_stat->nlivenodes += delta;
2527            delta = handle->bhandle->ndeltanodes - ndeltanodes;
2528            delta *= handle->config.blocksize;
2529            delta_stat->deltasize += delta;
2530        }
2531        avl_remove(stale_seqnum_list, &seq_entry->avl_entry);
2532        free(seq_entry);
2533    }
2534}
2535
2536INLINE void _fdb_wal_flush_kvs_delta_stats(struct filemgr *file,
2537                                           struct avl_tree *kvs_delta_stats)
2538{
2539    struct avl_node *node;
2540    struct wal_kvs_delta_stat *delta_stat;
2541    node = avl_first(kvs_delta_stats);
2542    while (node) {
2543        delta_stat = _get_entry(node, struct wal_kvs_delta_stat, avl_entry);
2544        node = avl_next(node);
2545        _kvs_stat_update_attr(file, delta_stat->kv_id,
2546                              KVS_STAT_DATASIZE, delta_stat->datasize);
2547        _kvs_stat_update_attr(file, delta_stat->kv_id,
2548                              KVS_STAT_NDOCS, delta_stat->ndocs);
2549        _kvs_stat_update_attr(file, delta_stat->kv_id,
2550                              KVS_STAT_NDELETES, delta_stat->ndeletes);
2551        _kvs_stat_update_attr(file, delta_stat->kv_id,
2552                              KVS_STAT_NLIVENODES, delta_stat->nlivenodes);
2553        _kvs_stat_update_attr(file, delta_stat->kv_id,
2554                              KVS_STAT_DELTASIZE, delta_stat->deltasize);
2555        avl_remove(kvs_delta_stats, &delta_stat->avl_entry);
2556        free(delta_stat);
2557    }
2558}
2559
2560INLINE fdb_status _fdb_wal_flush_func(void *voidhandle,
2561                                      struct wal_item *item,
2562                                      struct avl_tree *stale_seqnum_list,
2563                                      struct avl_tree *kvs_delta_stats)
2564{
2565    hbtrie_result hr;
2566    fdb_kvs_handle *handle = (fdb_kvs_handle *)voidhandle;
2567    fdb_seqnum_t _seqnum;
2568    fdb_kvs_id_t kv_id = 0;
2569    fdb_status fs = FDB_RESULT_SUCCESS;
2570    uint8_t *var_key = alca(uint8_t, handle->config.chunksize);
2571    int size_id, size_seq;
2572    uint8_t *kvid_seqnum;
2573    uint64_t old_offset;
2574    int64_t _offset;
2575    int64_t delta;
2576    struct docio_object _doc;
2577    struct filemgr *file = handle->dhandle->file;
2578
2579    memset(var_key, 0, handle->config.chunksize);
2580    if (handle->kvs) {
2581        buf2kvid(handle->config.chunksize, item->header->key, &kv_id);
2582    } else {
2583        kv_id = 0;
2584    }
2585
2586    struct wal_kvs_delta_stat *kvs_delta_stat;
2587    struct wal_kvs_delta_stat kvs_delta_query;
2588    kvs_delta_query.kv_id = kv_id;
2589    avl_node *delta_stat_node = avl_search(kvs_delta_stats,
2590                                           &kvs_delta_query.avl_entry,
2591                                           _kvs_delta_stat_cmp);
2592    if (delta_stat_node) {
2593        kvs_delta_stat = _get_entry(delta_stat_node, struct wal_kvs_delta_stat,
2594                                    avl_entry);
2595    } else {
2596        kvs_delta_stat = (struct wal_kvs_delta_stat *)
2597            calloc(1, sizeof(struct wal_kvs_delta_stat));
2598        kvs_delta_stat->kv_id = kv_id;
2599        avl_insert(kvs_delta_stats, &kvs_delta_stat->avl_entry,
2600                   _kvs_delta_stat_cmp);
2601    }
2602
2603    int64_t nlivenodes = handle->bhandle->nlivenodes;
2604    int64_t ndeltanodes = handle->bhandle->ndeltanodes;
2605
2606    if (item->action == WAL_ACT_INSERT ||
2607        item->action == WAL_ACT_LOGICAL_REMOVE) {
2608        _offset = _endian_encode(item->offset);
2609
2610        hbtrie_insert(handle->trie,
2611                      item->header->key,
2612                      item->header->keylen,
2613                      (void *)&_offset,
2614                      (void *)&old_offset);
2615
2616        fs = btreeblk_end(handle->bhandle);
2617        if (fs != FDB_RESULT_SUCCESS) {
2618            return fs;
2619        }
2620        old_offset = _endian_decode(old_offset);
2621
2622        if (handle->config.seqtree_opt == FDB_SEQTREE_USE) {
2623            _seqnum = _endian_encode(item->seqnum);
2624            if (handle->kvs) {
2625                // multi KV instance mode .. HB+trie
2626                uint64_t old_offset_local;
2627
2628                size_id = sizeof(fdb_kvs_id_t);
2629                size_seq = sizeof(fdb_seqnum_t);
2630                kvid_seqnum = alca(uint8_t, size_id + size_seq);
2631                kvid2buf(size_id, kv_id, kvid_seqnum);
2632                memcpy(kvid_seqnum + size_id, &_seqnum, size_seq);
2633                hbtrie_insert(handle->seqtrie, kvid_seqnum, size_id + size_seq,
2634                              (void *)&_offset, (void *)&old_offset_local);
2635            } else {
2636                btree_insert(handle->seqtree, (void *)&_seqnum,
2637                             (void *)&_offset);
2638            }
2639            fs = btreeblk_end(handle->bhandle);
2640            if (fs != FDB_RESULT_SUCCESS) {
2641                return fs;
2642            }
2643        }
2644
2645        delta = handle->bhandle->nlivenodes - nlivenodes;
2646        kvs_delta_stat->nlivenodes += delta;
2647        delta = handle->bhandle->ndeltanodes - ndeltanodes;
2648        delta *= handle->config.blocksize;
2649        kvs_delta_stat->deltasize += delta;
2650
2651        if (old_offset == BLK_NOT_FOUND) {
2652            if (item->action == WAL_ACT_INSERT) {
2653                ++kvs_delta_stat->ndocs;
2654            } else { // inserted a logical deleted doc into main index
2655                ++kvs_delta_stat->ndeletes;
2656            }
2657            kvs_delta_stat->datasize += item->doc_size;
2658            kvs_delta_stat->deltasize += item->doc_size;
2659        } else { // update or logical delete
2660            // This block is already cached when we call HBTRIE_INSERT.
2661            // No additional block access.
2662            char dummy_key[FDB_MAX_KEYLEN];
2663            _doc.meta = _doc.body = NULL;
2664            _doc.key = &dummy_key;
2665            _offset = docio_read_doc_key_meta(handle->dhandle, old_offset,
2666                                              &_doc, true);
2667            if (_offset < 0) {
2668                return (fdb_status) _offset;
2669            } else if (_offset == 0) {
2670                // Note that this is not an error as old_offset is pointing to
2671                // the zero-filled region in a document block.
2672                return FDB_RESULT_KEY_NOT_FOUND;
2673            }
2674            free(_doc.meta);
2675            filemgr_mark_stale(file, old_offset, _fdb_get_docsize(_doc.length));
2676
2677            if (!(_doc.length.flag & DOCIO_DELETED)) {//prev doc was not deleted
2678                if (item->action == WAL_ACT_LOGICAL_REMOVE) { // now deleted
2679                    --kvs_delta_stat->ndocs;
2680                    ++kvs_delta_stat->ndeletes;
2681                } // else no change (prev doc was insert, now just an update)
2682            } else { // prev doc in main index was a logically deleted doc
2683                if (item->action == WAL_ACT_INSERT) { // now undeleted
2684                    ++kvs_delta_stat->ndocs;
2685                    --kvs_delta_stat->ndeletes;
2686                } // else no change (prev doc was deleted, now re-deleted)
2687            }
2688
2689            delta = (int)item->doc_size - (int)_fdb_get_docsize(_doc.length);
2690            kvs_delta_stat->datasize += delta;
2691            bid_t last_hdr_bid = atomic_get_uint64_t(&handle->last_hdr_bid);
2692            if (last_hdr_bid * handle->config.blocksize < old_offset) {
2693                kvs_delta_stat->deltasize += delta;
2694            } else {
2695                kvs_delta_stat->deltasize += (int)item->doc_size;
2696            }
2697
2698            // Avoid duplicates (remove previous sequence number)
2699            if (handle->config.seqtree_opt == FDB_SEQTREE_USE) {
2700                struct wal_stale_seq_entry *entry = (struct wal_stale_seq_entry *)
2701                    calloc(1, sizeof(struct wal_stale_seq_entry));
2702                entry->kv_id = kv_id;
2703                entry->seqnum = _doc.seqnum;
2704                avl_insert(stale_seqnum_list, &entry->avl_entry,
2705                           _fdb_seq_entry_cmp);
2706            }
2707        }
2708    } else {
2709        // Immediate remove
2710        old_offset = item->old_offset;
2711        hr = hbtrie_remove(handle->trie, item->header->key,
2712                           item->header->keylen);
2713        fs = btreeblk_end(handle->bhandle);
2714        if (fs != FDB_RESULT_SUCCESS) {
2715            return fs;
2716        }
2717
2718        if (hr == HBTRIE_RESULT_SUCCESS) {
2719            // This block is already cached when we call _fdb_wal_get_old_offset
2720            // No additional block access should be done.
2721            char dummy_key[FDB_MAX_KEYLEN];
2722            _doc.meta = _doc.body = NULL;
2723            _doc.key = &dummy_key;
2724            _offset = docio_read_doc_key_meta(handle->dhandle, old_offset,
2725                                              &_doc, true);
2726            if (_offset < 0) {
2727                return (fdb_status) _offset;
2728            } else if (_offset == 0) {
2729                return FDB_RESULT_KEY_NOT_FOUND;
2730            }
2731            free(_doc.meta);
2732            filemgr_mark_stale(file, old_offset, _fdb_get_docsize(_doc.length));
2733
2734            // Reduce the total number of docs by one
2735            --kvs_delta_stat->ndocs;
2736            if (_doc.length.flag & DOCIO_DELETED) {//prev deleted doc is dropped
2737                --kvs_delta_stat->ndeletes;
2738            }
2739
2740            // Reduce the total datasize by size of previously present doc
2741            delta = -(int)_fdb_get_docsize(_doc.length);
2742            kvs_delta_stat->datasize += delta;
2743            // if multiple wal flushes happen before commit, then it's possible
2744            // that this doc deleted was inserted & flushed after last commit
2745            // In this case we need to update the deltasize too which tracks
2746            // the amount of new data inserted between commits.
2747            bid_t last_hdr_bid = atomic_get_uint64_t(&handle->last_hdr_bid);
2748            if (last_hdr_bid * handle->config.blocksize < old_offset) {
2749                kvs_delta_stat->deltasize += delta;
2750            }
2751
2752            // remove sequence number for the removed doc
2753            if (handle->config.seqtree_opt == FDB_SEQTREE_USE) {
2754                struct wal_stale_seq_entry *entry = (struct wal_stale_seq_entry *)
2755                    calloc(1, sizeof(struct wal_stale_seq_entry));
2756                entry->kv_id = kv_id;
2757                entry->seqnum = _doc.seqnum;
2758                avl_insert(stale_seqnum_list, &entry->avl_entry, _fdb_seq_entry_cmp);
2759            }
2760
2761            // Update index size to new size after the remove operation
2762            delta = handle->bhandle->nlivenodes - nlivenodes;
2763            kvs_delta_stat->nlivenodes += delta;
2764
2765            // ndeltanodes measures number of new index nodes created due to
2766            // this hbtrie_remove() operation
2767            delta = (int)handle->bhandle->ndeltanodes - ndeltanodes;
2768            delta *= handle->config.blocksize;
2769            kvs_delta_stat->deltasize += delta;
2770        }
2771    }
2772    return FDB_RESULT_SUCCESS;
2773}
2774
2775void fdb_sync_db_header(fdb_kvs_handle *handle)
2776{
2777    uint64_t cur_revnum = filemgr_get_header_revnum(handle->file);
2778    if (handle->cur_header_revnum != cur_revnum) {
2779        void *header_buf = NULL;
2780        size_t header_len;
2781        bid_t hdr_bid;
2782        filemgr_header_revnum_t revnum;
2783
2784        header_buf = filemgr_get_header(handle->file, NULL, &header_len,
2785                                        &hdr_bid, NULL, &revnum);
2786        if (header_len > 0) {
2787            uint64_t header_flags, dummy64, version;
2788            bid_t idtree_root;
2789            bid_t new_seq_root;
2790            bid_t new_stale_root;
2791            char *compacted_filename;
2792            char *prev_filename = NULL;
2793
2794            version = handle->file->version;
2795            atomic_store_uint64_t(&handle->last_hdr_bid, hdr_bid);
2796            handle->cur_header_revnum = revnum;
2797
2798            fdb_fetch_header(version, header_buf, &idtree_root,
2799                             &new_seq_root, &new_stale_root, &dummy64,
2800                             &dummy64, &dummy64,
2801                             &dummy64, &handle->last_wal_flush_hdr_bid,
2802                             &handle->kv_info_offset, &header_flags,
2803                             &compacted_filename, &prev_filename);
2804
2805            if (handle->dirty_updates) {
2806                // discard all cached writable b+tree nodes
2807                // to avoid data inconsistency with other writers
2808                btreeblk_discard_blocks(handle->bhandle);
2809            }
2810
2811            handle->trie->root_bid = idtree_root;
2812
2813            if (handle->config.seqtree_opt == FDB_SEQTREE_USE) {
2814                if (new_seq_root != handle->seqtree->root_bid) {
2815                    if (handle->config.multi_kv_instances) {
2816                        handle->seqtrie->root_bid = new_seq_root;
2817                    } else {
2818                        btree_init_from_bid(handle->seqtree,
2819                                            handle->seqtree->blk_handle,
2820                                            handle->seqtree->blk_ops,
2821                                            handle->seqtree->kv_ops,
2822                                            handle->seqtree->blksize,
2823                                            new_seq_root);
2824                    }
2825                }
2826            }
2827
2828            if (ver_staletree_support(version)) {
2829                btree_init_from_bid(handle->staletree,
2830                                    handle->staletree->blk_handle,
2831                                    handle->staletree->blk_ops,
2832                                    handle->staletree->kv_ops,
2833                                    handle->staletree->blksize,
2834                                    new_stale_root);
2835            } else {
2836                handle->staletree = NULL;
2837            }
2838
2839            if (prev_filename) {
2840                free(prev_filename);
2841            }
2842
2843            handle->dirty_updates = 0;
2844            if (handle->kvs) {
2845                // multiple KV instance mode AND sub handle
2846                handle->seqnum = fdb_kvs_get_seqnum(handle->file,
2847                                                    handle->kvs->id);
2848            } else {
2849                // super handle OR single KV instance mode
2850                handle->seqnum = filemgr_get_seqnum(handle->file);
2851            }
2852        } else {
2853            atomic_store_uint64_t(&handle->last_hdr_bid,
2854                                  filemgr_get_header_bid(handle->file));
2855        }
2856
2857        if (header_buf) {
2858            free(header_buf);
2859        }
2860    } else {
2861        if (handle == handle->fhandle->root) {
2862            // MB-20091: Commits use root handle that points to default kv store
2863            // The same default KV Store can have a different user-level handle.
2864            // To ensure that the root handle which will do the commit always
2865            // remains updated with the latest sequence number generated by the
2866            // user KVS Handle, we must always update the root handle's seqnum
2867            // even if there are no new commit headers to sync up in the file.
2868            handle->seqnum = filemgr_get_seqnum(handle->file);
2869        }
2870    }
2871}
2872
2873fdb_status fdb_check_file_reopen(fdb_kvs_handle *handle, file_status_t *status)
2874{
2875    bool fhandle_ret;
2876    fdb_status fs = FDB_RESULT_SUCCESS;
2877    file_status_t fstatus = filemgr_get_file_status(handle->file);
2878    // check whether the compaction is done
2879    if (fstatus == FILE_REMOVED_PENDING) {
2880        uint64_t ndocs, ndeletes, datasize, nlivenodes, last_wal_flush_hdr_bid;
2881        uint64_t kv_info_offset, header_flags;
2882        size_t header_len;
2883        char *new_filename;
2884        uint8_t *buf = alca(uint8_t, handle->config.blocksize);
2885        bid_t trie_root_bid, seq_root_bid, stale_root_bid;
2886        fdb_config config = handle->config;
2887
2888        // close the current file and newly open the new file
2889        if (handle->config.compaction_mode == FDB_COMPACTION_AUTO) {
2890            // compaction daemon mode .. just close and then open
2891            char filename[FDB_MAX_FILENAME_LEN];
2892            strcpy(filename, handle->filename);
2893
2894            // We don't need to maintain fhandle list for the old file
2895            // as there will be no more mutation on the file.
2896            fhandle_ret = filemgr_fhandle_remove(handle->file, handle->fhandle);
2897            fs = _fdb_close(handle);
2898            if (fs != FDB_RESULT_SUCCESS) {
2899                if (fhandle_ret) {
2900                    filemgr_fhandle_add(handle->file, handle->fhandle);
2901                }
2902                return fs;
2903            }
2904
2905            fs = _fdb_open(handle, filename, FDB_VFILENAME, &config);
2906            if (fs != FDB_RESULT_SUCCESS) {
2907                return fs;
2908            }
2909            filemgr_fhandle_add(handle->file, handle->fhandle);
2910
2911        } else {
2912            filemgr_get_header(handle->file, buf, &header_len, NULL, NULL, NULL);
2913            fdb_fetch_header(handle->file->version, buf,
2914                             &trie_root_bid, &seq_root_bid, &stale_root_bid,
2915                             &ndocs, &ndeletes, &nlivenodes, &datasize,
2916                             &last_wal_flush_hdr_bid,
2917                             &kv_info_offset, &header_flags,
2918                             &new_filename, NULL);
2919
2920            fhandle_ret = filemgr_fhandle_remove(handle->file, handle->fhandle);
2921            fs = _fdb_close(handle);
2922            if (fs != FDB_RESULT_SUCCESS) {
2923                if (fhandle_ret) {
2924                    filemgr_fhandle_add(handle->file, handle->fhandle);
2925                }
2926                return fs;
2927            }
2928
2929            fs = _fdb_open(handle, new_filename, FDB_AFILENAME, &config);
2930            if (fs != FDB_RESULT_SUCCESS) {
2931                return fs;
2932            }
2933            filemgr_fhandle_add(handle->file, handle->fhandle);
2934        }
2935    }
2936    if (status) {
2937        *status = fstatus;
2938    }
2939    return fs;
2940}
2941
2942static void _fdb_sync_dirty_root(fdb_kvs_handle *handle)
2943{
2944    bid_t dirty_idtree_root = BLK_NOT_FOUND;
2945    bid_t dirty_seqtree_root = BLK_NOT_FOUND;
2946
2947    if (handle->shandle) {
2948        // skip snapshot
2949        return;
2950    }
2951
2952    struct filemgr_dirty_update_node *dirty_update;
2953    dirty_update = filemgr_dirty_update_get_latest(handle->file);
2954    btreeblk_set_dirty_update(handle->bhandle, dirty_update);
2955
2956    if (dirty_update) {
2957        filemgr_dirty_update_get_root(handle->file, dirty_update,
2958                                      &dirty_idtree_root, &dirty_seqtree_root);
2959        _fdb_import_dirty_root(handle, dirty_idtree_root, dirty_seqtree_root);
2960        btreeblk_discard_blocks(handle->bhandle);
2961    }
2962
2963    return;
2964}
2965
2966static void _fdb_release_dirty_root(fdb_kvs_handle *handle)
2967{
2968    if (!handle->shandle) {
2969        struct filemgr_dirty_update_node *dirty_update;
2970        dirty_update = btreeblk_get_dirty_update(handle->bhandle);
2971        if (dirty_update) {
2972            filemgr_dirty_update_close_node(handle->file, dirty_update);
2973            btreeblk_clear_dirty_update(handle->bhandle);
2974        }
2975    }
2976}
2977
2978LIBFDB_API
2979fdb_status fdb_get(fdb_kvs_handle *handle, fdb_doc *doc)
2980{
2981    uint64_t offset;
2982    int64_t _offset;
2983    struct docio_object _doc;
2984    struct filemgr *wal_file = NULL;
2985    struct docio_handle *dhandle;
2986    struct _fdb_key_cmp_info cmp_info;
2987    fdb_status wr;
2988    hbtrie_result hr = HBTRIE_RESULT_FAIL;
2989    fdb_txn *txn;
2990    fdb_doc doc_kv;
2991    LATENCY_STAT_START();
2992
2993    if (!handle) {
2994        return FDB_RESULT_INVALID_HANDLE;
2995    }
2996
2997    if (!doc || !doc->key || doc->keylen == 0 ||
2998        doc->keylen > FDB_MAX_KEYLEN ||
2999        (handle->kvs_config.custom_cmp &&
3000            doc->keylen > handle->config.blocksize - HBTRIE_HEADROOM)) {
3001        return FDB_RESULT_INVALID_ARGS;
3002    }
3003
3004    if (!atomic_cas_uint8_t(&handle->handle_busy, 0, 1)) {
3005        return FDB_RESULT_HANDLE_BUSY;
3006    }
3007
3008    doc_kv = *doc;
3009
3010    if (handle->kvs) {
3011        // multi KV instance mode
3012        int size_chunk = handle->config.chunksize;
3013        doc_kv.keylen = doc->keylen + size_chunk;
3014        doc_kv.key = alca(uint8_t, doc_kv.keylen);
3015        kvid2buf(size_chunk, handle->kvs->id, doc_kv.key);
3016        memcpy((uint8_t*)doc_kv.key + size_chunk, doc->key, doc->keylen);
3017    }
3018
3019    if (!handle->shandle) {
3020        fdb_check_file_reopen(handle, NULL);
3021        txn = handle->fhandle->root->txn;
3022        if (!txn) {
3023            txn = &handle->file->global_txn;
3024        }
3025    } else {
3026        txn = handle->shandle->snap_txn;
3027    }
3028
3029    cmp_info.kvs_config = handle->kvs_config;
3030    cmp_info.kvs = handle->kvs;
3031    wal_file = handle->file;
3032    dhandle = handle->dhandle;
3033
3034    if (handle->kvs) {
3035        wr = wal_find(txn, wal_file, &cmp_info, handle->shandle, &doc_kv,
3036                      &offset);
3037    } else {
3038        wr = wal_find(txn, wal_file, &cmp_info, handle->shandle, doc,
3039                      &offset);
3040    }
3041
3042    if (!handle->shandle) {
3043        fdb_sync_db_header(handle);
3044    }
3045
3046    atomic_incr_uint64_t(&handle->op_stats->num_gets, std::memory_order_relaxed);
3047
3048    if (wr == FDB_RESULT_KEY_NOT_FOUND) {
3049        _fdb_sync_dirty_root(handle);
3050
3051        if (handle->kvs) {
3052            hr = hbtrie_find(handle->trie, doc_kv.key, doc_kv.keylen,
3053                             (void *)&offset);
3054        } else {
3055            hr = hbtrie_find(handle->trie, doc->key, doc->keylen,
3056                             (void *)&offset);
3057        }
3058        btreeblk_end(handle->bhandle);
3059        offset = _endian_decode(offset);
3060
3061        _fdb_release_dirty_root(handle);
3062    }
3063
3064    if ((wr == FDB_RESULT_SUCCESS && offset != BLK_NOT_FOUND) ||
3065         hr == HBTRIE_RESULT_SUCCESS) {
3066        bool alloced_meta = doc->meta ? false : true;
3067        bool alloced_body = doc->body ? false : true;
3068        if (handle->kvs) {
3069            _doc.key = doc_kv.key;
3070            _doc.length.keylen = doc_kv.keylen;
3071            doc->deleted = doc_kv.deleted; // update deleted field if wal_find
3072        } else {
3073            _doc.key = doc->key;
3074            _doc.length.keylen = doc->keylen;
3075        }
3076        _doc.meta = doc->meta;
3077        _doc.body = doc->body;
3078
3079        if (wr == FDB_RESULT_SUCCESS && doc->deleted) {
3080            atomic_cas_uint8_t(&handle->handle_busy, 1, 0);
3081            return FDB_RESULT_KEY_NOT_FOUND;
3082        }
3083
3084        _offset = docio_read_doc(dhandle, offset, &_doc, true);
3085        if (_offset <= 0) {
3086            atomic_cas_uint8_t(&handle->handle_busy, 1, 0);
3087            return _offset < 0 ? (fdb_status)_offset : FDB_RESULT_KEY_NOT_FOUND;
3088        }
3089
3090        if (_doc.length.keylen != doc_kv.keylen ||
3091            _doc.length.flag & DOCIO_DELETED) {
3092            free_docio_object(&_doc, 0, alloced_meta, alloced_body);
3093            atomic_cas_uint8_t(&handle->handle_busy, 1, 0);
3094            return FDB_RESULT_KEY_NOT_FOUND;
3095        }
3096
3097        doc->seqnum = _doc.seqnum;
3098        doc->metalen = _doc.length.metalen;
3099        doc->bodylen = _doc.length.bodylen;
3100        doc->meta = _doc.meta;
3101        doc->body = _doc.body;
3102        doc->deleted = _doc.length.flag & DOCIO_DELETED;
3103        doc->size_ondisk = _fdb_get_docsize(_doc.length);
3104        doc->offset = offset;
3105
3106        LATENCY_STAT_END(handle->file, FDB_LATENCY_GETS);
3107        atomic_cas_uint8_t(&handle->handle_busy, 1, 0);
3108        return FDB_RESULT_SUCCESS;
3109    }
3110
3111    atomic_cas_uint8_t(&handle->handle_busy, 1, 0);
3112    return FDB_RESULT_KEY_NOT_FOUND;
3113}
3114
3115// search document metadata using key
3116LIBFDB_API
3117fdb_status fdb_get_metaonly(fdb_kvs_handle *handle, fdb_doc *doc)
3118{
3119    uint64_t offset;
3120    struct docio_object _doc;
3121    struct docio_handle *dhandle;
3122    struct filemgr *wal_file = NULL;
3123    fdb_status wr;
3124    hbtrie_result hr = HBTRIE_RESULT_FAIL;
3125    fdb_txn *txn;
3126    struct _fdb_key_cmp_info cmp_info;
3127    fdb_doc doc_kv;
3128    LATENCY_STAT_START();
3129
3130    if (!handle) {
3131        return FDB_RESULT_INVALID_HANDLE;
3132    }
3133
3134    if (!doc || !doc->key ||
3135        doc->keylen == 0 || doc->keylen > FDB_MAX_KEYLEN ||
3136        (handle->kvs_config.custom_cmp &&
3137            doc->keylen > handle->config.blocksize - HBTRIE_HEADROOM)) {
3138        return FDB_RESULT_INVALID_ARGS;
3139    }
3140
3141    doc_kv = *doc;
3142
3143    if (!atomic_cas_uint8_t(&handle->handle_busy, 0, 1)) {
3144        return FDB_RESULT_HANDLE_BUSY;
3145    }
3146
3147    if (handle->kvs) {
3148        // multi KV instance mode
3149        int size_chunk = handle->config.chunksize;
3150        doc_kv.keylen = doc->keylen + size_chunk;
3151        doc_kv.key = alca(uint8_t, doc_kv.keylen);
3152        kvid2buf(size_chunk, handle->kvs->id, doc_kv.key);
3153        memcpy((uint8_t*)doc_kv.key + size_chunk, doc->key, doc->keylen);
3154    }
3155
3156    if (!handle->shandle) {
3157        fdb_check_file_reopen(handle, NULL);
3158        txn = handle->fhandle->root->txn;
3159        if (!txn) {
3160            txn = &handle->file->global_txn;
3161        }
3162    } else {
3163        txn = handle->shandle->snap_txn;
3164    }
3165
3166    cmp_info.kvs_config = handle->kvs_config;
3167    cmp_info.kvs = handle->kvs;
3168    wal_file = handle->file;
3169    dhandle = handle->dhandle;
3170
3171    if (handle->kvs) {
3172        wr = wal_find(txn, wal_file, &cmp_info, handle->shandle, &doc_kv,
3173                      &offset);
3174    } else {
3175        wr = wal_find(txn, wal_file, &cmp_info, handle->shandle, doc, &offset);
3176    }
3177
3178    if (!handle->shandle) {
3179        fdb_sync_db_header(handle);
3180    }
3181    atomic_incr_uint64_t(&handle->op_stats->num_gets, std::memory_order_relaxed);
3182
3183    if (wr == FDB_RESULT_KEY_NOT_FOUND) {
3184        _fdb_sync_dirty_root(handle);
3185
3186        if (handle->kvs) {
3187            hr = hbtrie_find(handle->trie, doc_kv.key, doc_kv.keylen,
3188                             (void *)&offset);
3189        } else {
3190            hr = hbtrie_find(handle->trie, doc->key, doc->keylen,
3191                             (void *)&offset);
3192        }
3193        btreeblk_end(handle->bhandle);
3194        offset = _endian_decode(offset);
3195
3196        _fdb_release_dirty_root(handle);
3197    }
3198
3199    if ((wr == FDB_RESULT_SUCCESS && offset != BLK_NOT_FOUND) ||
3200         hr == HBTRIE_RESULT_SUCCESS) {
3201        if (handle->kvs) {
3202            _doc.key = doc_kv.key;
3203            _doc.length.keylen = doc_kv.keylen;
3204        } else {
3205            _doc.key = doc->key;
3206            _doc.length.keylen = doc->keylen;
3207        }
3208        bool alloced_meta = doc->meta ? false : true;
3209        _doc.meta = doc->meta;
3210        _doc.body = doc->body;
3211
3212        int64_t body_offset = docio_read_doc_key_meta(dhandle, offset, &_doc,
3213                                                       true);
3214        if (body_offset <= 0){
3215            atomic_cas_uint8_t(&handle->handle_busy, 1, 0);
3216            return body_offset < 0 ? (fdb_status)body_offset : FDB_RESULT_KEY_NOT_FOUND;
3217        }
3218
3219        if (_doc.length.keylen !=