xref: /6.6.0/forestdb/src/forestdb.cc (revision cc8ad991)
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        // use existing setting for multi KV instance mode
1788        if (kv_info_offset == BLK_NOT_FOUND) {
1789            multi_kv_instances = false;
1790        } else {
1791            multi_kv_instances = true;
1792        }
1793    }
1794
1795    handle->config = *config;
1796    handle->config.seqtree_opt = seqtree_opt;
1797    handle->config.multi_kv_instances = multi_kv_instances;
1798
1799    if (handle->shandle && handle->max_seqnum == FDB_SNAPSHOT_INMEM) {
1800        // Either an in-memory snapshot or cloning from an existing snapshot..
1801        hdr_bid = 0; // This prevents _fdb_restore_wal() as incoming handle's
1802                     // *_open() should have already restored it
1803    } else { // Persisted snapshot or file rollback..
1804
1805        // get the BID of the latest block
1806        // (it is OK if the block is not a DB header)
1807        bool dirty_data_exists = false;
1808        struct superblock *sb = handle->file->sb;
1809
1810        if (sb_bmp_exists(sb)) {
1811            dirty_data_exists = false;
1812            bid_t sb_last_hdr_bid = atomic_get_uint64_t(&sb->last_hdr_bid);
1813            if (sb_last_hdr_bid != BLK_NOT_FOUND) {
1814                // add 1 since we subtract 1 from 'hdr_bid' below soon
1815                hdr_bid = sb_last_hdr_bid + 1;
1816                if (atomic_get_uint64_t(&sb->cur_alloc_bid) != hdr_bid) {
1817                    // seq number has been increased since the last commit
1818                    seqnum = fdb_kvs_get_committed_seqnum(handle);
1819                }
1820            } else {
1821                hdr_bid = BLK_NOT_FOUND;
1822            }
1823        } else {
1824            hdr_bid = filemgr_get_pos(handle->file) / FDB_BLOCKSIZE;
1825            dirty_data_exists = (hdr_bid >
1826                        atomic_get_uint64_t(&handle->last_hdr_bid));
1827        }
1828
1829        if (hdr_bid == BLK_NOT_FOUND ||
1830            (sb && hdr_bid <= sb->config->num_sb)) {
1831            hdr_bid = 0;
1832        } else if (hdr_bid > 0) {
1833            --hdr_bid;
1834        }
1835
1836        if (handle->max_seqnum) {
1837            struct kvs_stat stat_ori;
1838            // backup original stats
1839            if (handle->kvs) {
1840                _kvs_stat_get(handle->file, handle->kvs->id, &stat_ori);
1841            } else {
1842                _kvs_stat_get(handle->file, 0, &stat_ori);
1843            }
1844
1845            if (dirty_data_exists){
1846                // uncommitted data exists beyond the last DB header
1847                // get the last committed seq number
1848                fdb_seqnum_t seq_commit;
1849                seq_commit = fdb_kvs_get_committed_seqnum(handle);
1850                if (seq_commit == 0 || seq_commit < handle->max_seqnum) {
1851                    // In case, snapshot_open is attempted with latest uncommitted
1852                    // sequence number
1853                    header_len = 0;
1854                } else if (seq_commit == handle->max_seqnum) {
1855                    // snapshot/rollback on the latest commit header
1856                    seqnum = seq_commit; // skip file reverse scan
1857                }
1858                hdr_bid = filemgr_get_header_bid(handle->file);
1859            }
1860            // Reverse scan the file to locate the DB header with seqnum marker
1861            header_revnum = latest_header_revnum;
1862            while (header_len && seqnum != handle->max_seqnum) {
1863                hdr_bid = filemgr_fetch_prev_header(handle->file, hdr_bid,
1864                                          header_buf, &header_len, &seqnum,
1865                                          &header_revnum, NULL, &version, NULL,
1866                                          &handle->log_callback);
1867                if (header_len == 0) {
1868                    continue; // header doesn't exist
1869                }
1870                fdb_fetch_header(version, header_buf, &trie_root_bid,
1871                                 &seq_root_bid, &stale_root_bid,
1872                                 &ndocs, &ndeletes, &nlivenodes,
1873                                 &datasize, &last_wal_flush_hdr_bid,
1874                                 &kv_info_offset, &header_flags,
1875                                 &compacted_filename, NULL);
1876                atomic_store_uint64_t(&handle->last_hdr_bid, hdr_bid);
1877
1878                if (!handle->kvs || handle->kvs->id == 0) {
1879                    // single KVS mode OR default KVS
1880                    if (!handle->shandle) {
1881                        // rollback
1882                        struct kvs_stat stat_dst;
1883                        _kvs_stat_get(handle->file, 0, &stat_dst);
1884                        stat_dst.ndocs = ndocs;
1885                        stat_dst.ndeletes = ndeletes;
1886                        stat_dst.datasize = datasize;
1887                        stat_dst.nlivenodes = nlivenodes;
1888                        stat_dst.deltasize = deltasize;
1889                        _kvs_stat_set(handle->file, 0, stat_dst);
1890                    }
1891                    continue;
1892                }
1893
1894                int64_t doc_offset;
1895                struct kvs_header *kv_header;
1896                struct docio_object doc;
1897
1898                _fdb_kvs_header_create(&kv_header);
1899                memset(&doc, 0, sizeof(struct docio_object));
1900                doc_offset = docio_read_doc(handle->dhandle,
1901                                            kv_info_offset, &doc, true);
1902
1903                if (doc_offset <= 0) {
1904                    header_len = 0; // fail
1905                    _fdb_kvs_header_free(kv_header);
1906                } else {
1907                    _fdb_kvs_header_import(kv_header, doc.body,
1908                                           doc.length.bodylen, version, false);
1909                    // get local sequence number for the KV instance
1910                    seqnum = _fdb_kvs_get_seqnum(kv_header,
1911                                                 handle->kvs->id);
1912                    if (!handle->shandle) {
1913                        // rollback: replace kv_header stats
1914                        // read from the current header's kv_header
1915                        struct kvs_stat stat_src, stat_dst;
1916                        _kvs_stat_get_kv_header(kv_header,
1917                                                handle->kvs->id,
1918                                                &stat_src);
1919                        _kvs_stat_get(handle->file,
1920                                      handle->kvs->id,
1921                                      &stat_dst);
1922                        // update ndocs, datasize, nlivenodes
1923                        // into the current file's kv_header
1924                        // Note: stats related to WAL should not be updated
1925                        //       at this time. They will be adjusted through
1926                        //       discard & restore routines below.
1927                        stat_dst.ndocs = stat_src.ndocs;
1928                        stat_dst.datasize = stat_src.datasize;
1929                        stat_dst.nlivenodes = stat_src.nlivenodes;
1930                        _kvs_stat_set(handle->file,
1931                                      handle->kvs->id,
1932                                      stat_dst);
1933                    }
1934                    _fdb_kvs_header_free(kv_header);
1935                    free_docio_object(&doc, 1, 1, 1);
1936                }
1937            }
1938
1939            if (header_len && // header exists
1940                config->block_reusing_threshold > 0 && // block reuse is enabled
1941                config->block_reusing_threshold < 100 &&
1942                header_revnum < sb_get_min_live_revnum(handle->file)) {
1943                // cannot perform rollback/snapshot beyond the last live header
1944                header_len = 0;
1945            }
1946
1947            if (!header_len) { // Marker MUST match that of DB commit!
1948                // rollback original stats
1949                if (handle->kvs) {
1950                    _kvs_stat_get(handle->file, handle->kvs->id, &stat_ori);
1951                } else {
1952                    _kvs_stat_get(handle->file, 0, &stat_ori);
1953                }
1954
1955                docio_free(handle->dhandle);
1956                free(handle->dhandle);
1957                free(handle->filename);
1958                free(prev_filename);
1959                handle->filename = NULL;
1960                filemgr_close(handle->file, false, handle->filename,
1961                              &handle->log_callback);
1962                return FDB_RESULT_NO_DB_INSTANCE;
1963            }
1964
1965            if (!handle->shandle) { // Rollback mode, destroy file WAL..
1966                if (handle->config.multi_kv_instances) {
1967                    // multi KV instance mode
1968                    // clear only WAL items belonging to the instance
1969                    wal_close_kv_ins(handle->file,
1970                                     (handle->kvs)?(handle->kvs->id):(0),
1971                                     &handle->log_callback);
1972                } else {
1973                    wal_shutdown(handle->file, &handle->log_callback);
1974                }
1975            }
1976        } else { // snapshot to sequence number 0 requested..
1977            if (handle->shandle) { // fdb_snapshot_open API call
1978                if (seqnum) {
1979                    // Database currently has a non-zero seq number,
1980                    // but the snapshot was requested with a seq number zero.
1981                    docio_free(handle->dhandle);
1982                    free(handle->dhandle);
1983                    free(handle->filename);
1984                    free(prev_filename);
1985                    handle->filename = NULL;
1986                    filemgr_close(handle->file, false, handle->filename,
1987                                  &handle->log_callback);
1988                    return FDB_RESULT_NO_DB_INSTANCE;
1989                }
1990            } // end of zero max_seqnum but non-rollback check
1991        } // end of zero max_seqnum check
1992    } // end of durable snapshot locating
1993
1994    handle->btreeblkops = btreeblk_get_ops();
1995    handle->bhandle = (struct btreeblk_handle *)
1996                      calloc(1, sizeof(struct btreeblk_handle));
1997    handle->bhandle->log_callback = &handle->log_callback;
1998
1999    handle->dirty_updates = 0;
2000
2001    if (handle->config.compaction_buf_maxsize == 0) {
2002        handle->config.compaction_buf_maxsize = FDB_COMP_BUF_MINSIZE;
2003    }
2004
2005    btreeblk_init(handle->bhandle, handle->file, handle->file->blocksize);
2006
2007    handle->cur_header_revnum = latest_header_revnum;
2008    if (header_revnum) {
2009        if (filemgr_is_rollback_on(handle->file)) {
2010            // rollback mode
2011            // set rollback header revnum
2012            handle->rollback_revnum = header_revnum;
2013        } else {
2014            // snapshot mode (only for snapshot)
2015            handle->cur_header_revnum = header_revnum;
2016        }
2017    }
2018    handle->last_wal_flush_hdr_bid = last_wal_flush_hdr_bid;
2019
2020    memset(&empty_stat, 0x0, sizeof(empty_stat));
2021    _kvs_stat_get(handle->file, 0, &stat);
2022    if (!memcmp(&stat, &empty_stat, sizeof(stat))) { // first open
2023        // sync (default) KVS stat with DB header
2024        stat.nlivenodes = nlivenodes;
2025        stat.ndocs = ndocs;
2026        stat.datasize = datasize;
2027        _kvs_stat_set(handle->file, 0, stat);
2028    }
2029
2030    handle->kv_info_offset = kv_info_offset;
2031    if (handle->config.multi_kv_instances && !handle->shandle) {
2032        // multi KV instance mode
2033        filemgr_mutex_lock(handle->file);
2034        if (kv_info_offset == BLK_NOT_FOUND) {
2035            // there is no KV header .. create & initialize
2036            fdb_kvs_header_create(handle->file);
2037            // TODO: If another handle is opened before the first header is appended,
2038            // an unnecessary KV info doc is appended. We need to address it.
2039            kv_info_offset = fdb_kvs_header_append(handle);
2040        } else if (handle->file->kv_header == NULL) {
2041            // KV header already exists but not loaded .. read & import
2042            fdb_kvs_header_create(handle->file);
2043            fdb_kvs_header_read(handle->file->kv_header, handle->dhandle,
2044                                kv_info_offset, version, false);
2045        }
2046        filemgr_mutex_unlock(handle->file);
2047
2048        // validation check for key order of all KV stores
2049        if (handle == handle->fhandle->root) {
2050            fdb_status fs = fdb_kvs_cmp_check(handle);
2051            if (fs != FDB_RESULT_SUCCESS) { // cmp function mismatch
2052                docio_free(handle->dhandle);
2053                free(handle->dhandle);
2054                btreeblk_free(handle->bhandle);
2055                free(handle->bhandle);
2056                free(handle->filename);
2057                handle->filename = NULL;
2058                filemgr_close(handle->file, false, handle->filename,
2059                              &handle->log_callback);
2060                return fs;
2061            }
2062        }
2063    }
2064    handle->kv_info_offset = kv_info_offset;
2065
2066    if (handle->kv_info_offset != BLK_NOT_FOUND &&
2067        handle->kvs == NULL) {
2068        // multi KV instance mode .. turn on config flag
2069        handle->config.multi_kv_instances = true;
2070        // only super handle can be opened using fdb_open(...)
2071        fdb_kvs_info_create(NULL, handle, handle->file, NULL);
2072    }
2073
2074    if (handle->shandle) { // Populate snapshot stats..
2075        if (kv_info_offset == BLK_NOT_FOUND) { // Single KV mode
2076            memset(&handle->shandle->stat, 0x0,
2077                    sizeof(handle->shandle->stat));
2078            handle->shandle->stat.ndocs = ndocs;
2079            handle->shandle->stat.datasize = datasize;
2080            handle->shandle->stat.nlivenodes = nlivenodes;
2081        } else { // Multi KV instance mode, populate specific kv stats
2082            memset(&handle->shandle->stat, 0x0,
2083                    sizeof(handle->shandle->stat));
2084            _kvs_stat_get(handle->file, handle->kvs->id,
2085                    &handle->shandle->stat);
2086            // Since wal is restored below, we have to reset
2087            // wal stats to zero.
2088            handle->shandle->stat.wal_ndeletes = 0;
2089            handle->shandle->stat.wal_ndocs = 0;
2090        }
2091    }
2092
2093    // initialize pointer to the global operational stats of this KV store
2094    handle->op_stats = filemgr_get_ops_stats(handle->file, handle->kvs);
2095    if (!handle->op_stats) {
2096        const char *msg = "Database open fails due to the error in retrieving "
2097            "the global operational stats of KV store in a database file '%s'\n";
2098        fdb_log(&handle->log_callback, FDB_RESULT_OPEN_FAIL, msg,
2099                handle->file->filename);
2100        return FDB_RESULT_OPEN_FAIL;
2101    }
2102
2103    handle->trie = (struct hbtrie *)malloc(sizeof(struct hbtrie));
2104    hbtrie_init(handle->trie, config->chunksize, OFFSET_SIZE,
2105                handle->file->blocksize, trie_root_bid,
2106                (void *)handle->bhandle, handle->btreeblkops,
2107                (void *)handle->dhandle, _fdb_readkey_wrap);
2108    // set aux for cmp wrapping function
2109    hbtrie_set_leaf_height_limit(handle->trie, 0xff);
2110    hbtrie_set_leaf_cmp(handle->trie, _fdb_custom_cmp_wrap);
2111
2112    if (handle->kvs) {
2113        hbtrie_set_map_function(handle->trie, fdb_kvs_find_cmp_chunk);
2114    }
2115
2116    handle->seqnum = seqnum;
2117    if (handle->config.seqtree_opt == FDB_SEQTREE_USE) {
2118        if (handle->config.multi_kv_instances) {
2119            // multi KV instance mode .. HB+trie
2120            handle->seqtrie = (struct hbtrie *)malloc(sizeof(struct hbtrie));
2121            hbtrie_init(handle->seqtrie, sizeof(fdb_kvs_id_t), OFFSET_SIZE,
2122                        handle->file->blocksize, seq_root_bid,
2123                        (void *)handle->bhandle, handle->btreeblkops,
2124                        (void *)handle->dhandle, _fdb_readseq_wrap);
2125
2126        } else {
2127            // single KV instance mode .. normal B+tree
2128            struct btree_kv_ops *seq_kv_ops =
2129                (struct btree_kv_ops *)malloc(sizeof(struct btree_kv_ops));
2130            seq_kv_ops = btree_kv_get_kb64_vb64(seq_kv_ops);
2131            seq_kv_ops->cmp = _cmp_uint64_t_endian_safe;
2132
2133            handle->seqtree = (struct btree*)malloc(sizeof(struct btree));
2134            if (seq_root_bid == BLK_NOT_FOUND) {
2135                btree_init(handle->seqtree, (void *)handle->bhandle,
2136                           handle->btreeblkops, seq_kv_ops,
2137                           handle->config.blocksize, sizeof(fdb_seqnum_t),
2138                           OFFSET_SIZE, 0x0, NULL);
2139            }else{
2140                btree_init_from_bid(handle->seqtree, (void *)handle->bhandle,
2141                                    handle->btreeblkops, seq_kv_ops,
2142                                    handle->config.blocksize, seq_root_bid);
2143            }
2144        }
2145    }else{
2146        handle->seqtree = NULL;
2147    }
2148
2149    // Stale-block tree (supported since MAGIC_002)
2150    // this tree is independent to multi/single KVS mode option
2151    if (ver_staletree_support(handle->file->version)) {
2152        // normal B+tree
2153        struct btree_kv_ops *stale_kv_ops =
2154            (struct btree_kv_ops *)calloc(1, sizeof(struct btree_kv_ops));
2155        stale_kv_ops = btree_kv_get_kb64_vb64(stale_kv_ops);
2156        stale_kv_ops->cmp = _cmp_uint64_t_endian_safe;
2157
2158        handle->staletree = (struct btree*)calloc(1, sizeof(struct btree));
2159        if (stale_root_bid == BLK_NOT_FOUND) {
2160            btree_init(handle->staletree, (void *)handle->bhandle,
2161                       handle->btreeblkops, stale_kv_ops,
2162                       handle->config.blocksize, sizeof(filemgr_header_revnum_t),
2163                       OFFSET_SIZE, 0x0, NULL);
2164         }else{
2165            btree_init_from_bid(handle->staletree, (void *)handle->bhandle,
2166                                handle->btreeblkops, stale_kv_ops,
2167                                handle->config.blocksize, stale_root_bid);
2168            // prefetch stale info into memory
2169            fdb_load_inmem_stale_info(handle);
2170         }
2171    } else {
2172        handle->staletree = NULL;
2173    }
2174
2175    if (handle->config.multi_kv_instances && handle->max_seqnum) {
2176        // restore only docs belonging to the KV instance
2177        // handle->kvs should not be NULL
2178        _fdb_restore_wal(handle, FDB_RESTORE_KV_INS,
2179                         hdr_bid, (handle->kvs)?(handle->kvs->id):(0));
2180    } else {
2181        // normal restore
2182        _fdb_restore_wal(handle, FDB_RESTORE_NORMAL, hdr_bid, 0);
2183    }
2184
2185    if (compacted_filename &&
2186        filemgr_get_file_status(handle->file) == FILE_NORMAL &&
2187        !(config->flags & FDB_OPEN_FLAG_RDONLY)) { // do not recover read-only
2188        _fdb_recover_compaction(handle, compacted_filename);
2189    }
2190
2191    if (compacted_filename) {
2192        filemgr_update_file_linkage(handle->file, NULL, compacted_filename);
2193    }
2194
2195    if (prev_filename) {
2196        if (!handle->shandle && strcmp(prev_filename, handle->file->filename)) {
2197            // record the old filename into the file handle of current file
2198            // and REMOVE old file on the first open
2199            // WARNING: snapshots must have been opened before this call
2200            if (filemgr_update_file_linkage(handle->file, prev_filename, NULL)) {
2201                // Open the old file with read-only mode.
2202                // (Temporarily disable log callback at this time since
2203                //  the old file might be already removed.)
2204                err_log_callback dummy_cb;
2205                dummy_cb.callback = fdb_dummy_log_callback;
2206                dummy_cb.ctx_data = NULL;
2207                fconfig.options = FILEMGR_READONLY;
2208                filemgr_open_result result = filemgr_open(prev_filename,
2209                                                          handle->fileops,
2210                                                          &fconfig,
2211                                                          &dummy_cb);
2212                if (result.file) {
2213                    filemgr_remove_pending(result.file, handle->file,
2214                                           &handle->log_callback);
2215                    filemgr_close(result.file, 0, handle->filename,
2216                                  &handle->log_callback);
2217                }
2218            }
2219        }
2220        // we allocated a memory region for file->old_filename and
2221        // prev_filename would be copied to there,
2222        // so it is OK to free it here whatever the result is.
2223        free(prev_filename);
2224    }
2225
2226    status = btreeblk_end(handle->bhandle);
2227    if (status != FDB_RESULT_SUCCESS) {
2228        // When fdb_kvs_open() is being issued in parallel with fdb_open()
2229        // it is possible that this call (fdb_open()) hits a write failure
2230        // because the btreeblock to be written was already made immutable
2231        // by the commit from the fdb_kvs_open(). Simpy ignore this error case.
2232        if (status == FDB_RESULT_WRITE_FAIL) {
2233            if (filemgr_get_header_revnum(handle->file)
2234                                             == latest_header_revnum) {
2235                return status;
2236            } else {
2237                status = FDB_RESULT_SUCCESS;
2238            }
2239        } else {
2240            return status;
2241        }
2242    }
2243
2244    // do not register read-only handles
2245    if (!(config->flags & FDB_OPEN_FLAG_RDONLY)) {
2246        if (config->compaction_mode == FDB_COMPACTION_AUTO) {
2247            status = compactor_register_file(handle->file,
2248                                             (fdb_config *)config,
2249                                             &handle->log_callback);
2250        }
2251        if (status == FDB_RESULT_SUCCESS) {
2252            status = bgflusher_register_file(handle->file,
2253                                             (fdb_config *)config,
2254                                             &handle->log_callback);
2255        }
2256    }
2257
2258    return status;
2259}
2260
2261LIBFDB_API
2262fdb_status fdb_set_log_callback(fdb_kvs_handle *handle,
2263                                fdb_log_callback log_callback,
2264                                void *ctx_data)
2265{
2266    if (!handle) {
2267        return FDB_RESULT_INVALID_HANDLE;
2268    }
2269
2270    handle->log_callback.callback = log_callback;
2271    handle->log_callback.ctx_data = ctx_data;
2272    return FDB_RESULT_SUCCESS;
2273}
2274
2275LIBFDB_API
2276void fdb_set_fatal_error_callback(fdb_fatal_error_callback err_callback)
2277{
2278    fatal_error_callback = err_callback;
2279}
2280
2281LIBFDB_API
2282fdb_status fdb_doc_create(fdb_doc **doc, const void *key, size_t keylen,
2283                          const void *meta, size_t metalen,
2284                          const void *body, size_t bodylen)
2285{
2286    if (doc == NULL || keylen > FDB_MAX_KEYLEN ||
2287        metalen > FDB_MAX_METALEN || bodylen > FDB_MAX_BODYLEN) {
2288        return FDB_RESULT_INVALID_ARGS;
2289    }
2290
2291    *doc = (fdb_doc*)calloc(1, sizeof(fdb_doc));
2292    if (*doc == NULL) { // LCOV_EXCL_START
2293        return FDB_RESULT_ALLOC_FAIL;
2294    } // LCOV_EXCL_STOP
2295
2296    (*doc)->seqnum = SEQNUM_NOT_USED;
2297
2298    if (key && keylen > 0) {
2299        (*doc)->key = (void *)malloc(keylen);
2300        if ((*doc)->key == NULL) { // LCOV_EXCL_START
2301            return FDB_RESULT_ALLOC_FAIL;
2302        } // LCOV_EXCL_STOP
2303        memcpy((*doc)->key, key, keylen);
2304        (*doc)->keylen = keylen;
2305    } else {
2306        (*doc)->key = NULL;
2307        (*doc)->keylen = 0;
2308    }
2309
2310    if (meta && metalen > 0) {
2311        (*doc)->meta = (void *)malloc(metalen);
2312        if ((*doc)->meta == NULL) { // LCOV_EXCL_START
2313            return FDB_RESULT_ALLOC_FAIL;
2314        } // LCOV_EXCL_STOP
2315        memcpy((*doc)->meta, meta, metalen);
2316        (*doc)->metalen = metalen;
2317    } else {
2318        (*doc)->meta = NULL;
2319        (*doc)->metalen = 0;
2320    }
2321
2322    if (body && bodylen > 0) {
2323        (*doc)->body = (void *)malloc(bodylen);
2324        if ((*doc)->body == NULL) { // LCOV_EXCL_START
2325            return FDB_RESULT_ALLOC_FAIL;
2326        } // LCOV_EXCL_STOP
2327        memcpy((*doc)->body, body, bodylen);
2328        (*doc)->bodylen = bodylen;
2329    } else {
2330        (*doc)->body = NULL;
2331        (*doc)->bodylen = 0;
2332    }
2333
2334    return FDB_RESULT_SUCCESS;
2335}
2336
2337LIBFDB_API
2338fdb_status fdb_doc_update(fdb_doc **doc,
2339                          const void *meta, size_t metalen,
2340                          const void *body, size_t bodylen)
2341{
2342    if (doc == NULL ||
2343        metalen > FDB_MAX_METALEN || bodylen > FDB_MAX_BODYLEN) {
2344        return FDB_RESULT_INVALID_ARGS;
2345    }
2346    if (*doc == NULL) {
2347        return FDB_RESULT_INVALID_ARGS;
2348    }
2349
2350    if (meta && metalen > 0) {
2351        // free previous metadata
2352        free((*doc)->meta);
2353        // allocate new metadata
2354        (*doc)->meta = (void *)malloc(metalen);
2355        if ((*doc)->meta == NULL) { // LCOV_EXCL_START
2356            return FDB_RESULT_ALLOC_FAIL;
2357        } // LCOV_EXCL_STOP
2358        memcpy((*doc)->meta, meta, metalen);
2359        (*doc)->metalen = metalen;
2360    }
2361
2362    if (body && bodylen > 0) {
2363        // free previous body
2364        free((*doc)->body);
2365        // allocate new body
2366        (*doc)->body = (void *)malloc(bodylen);
2367        if ((*doc)->body == NULL) { // LCOV_EXCL_START
2368            return FDB_RESULT_ALLOC_FAIL;
2369        } // LCOV_EXCL_STOP
2370        memcpy((*doc)->body, body, bodylen);
2371        (*doc)->bodylen = bodylen;
2372    }
2373
2374    (*doc)->seqnum = SEQNUM_NOT_USED;
2375    return FDB_RESULT_SUCCESS;
2376}
2377
2378LIBFDB_API
2379void fdb_doc_set_seqnum(fdb_doc *doc,
2380                        const fdb_seqnum_t seqnum)
2381{
2382    if (doc) {
2383        doc->seqnum = seqnum;
2384        if (seqnum != SEQNUM_NOT_USED) {
2385            doc->flags |= FDB_CUSTOM_SEQNUM; // fdb_set will now use above seqnum
2386        } else { // reset custom seqnum flag, fdb_set will now generate new seqnum
2387            doc->flags &= ~FDB_CUSTOM_SEQNUM;
2388        }
2389    }
2390}
2391
2392// doc MUST BE allocated by malloc
2393LIBFDB_API
2394fdb_status fdb_doc_free(fdb_doc *doc)
2395{
2396    if (doc) {
2397        free(doc->key);
2398        free(doc->meta);
2399        free(doc->body);
2400        free(doc);
2401    }
2402    return FDB_RESULT_SUCCESS;
2403}
2404
2405INLINE uint64_t _fdb_wal_get_old_offset(void *voidhandle,
2406                                        struct wal_item *item)
2407{
2408    fdb_kvs_handle *handle = (fdb_kvs_handle *)voidhandle;
2409    uint64_t old_offset = 0;
2410
2411    if (item->action == WAL_ACT_REMOVE) {
2412        // For immediate remove, old_offset value is critical
2413        // so that we should get an exact value.
2414        hbtrie_find(handle->trie,
2415                    item->header->key,
2416                    item->header->keylen,
2417                    (void*)&old_offset);
2418    } else {
2419        hbtrie_find_offset(handle->trie,
2420                           item->header->key,
2421                           item->header->keylen,
2422                           (void*)&old_offset);
2423    }
2424    btreeblk_end(handle->bhandle);
2425    old_offset = _endian_decode(old_offset);
2426
2427    return old_offset;
2428}
2429
2430// A stale sequence number entry that can be purged from the sequence tree
2431// during the WAL flush.
2432struct wal_stale_seq_entry {
2433    fdb_kvs_id_t kv_id;
2434    fdb_seqnum_t seqnum;
2435    struct avl_node avl_entry;
2436};
2437
2438// Delta changes in KV store stats during the WAL flush
2439struct wal_kvs_delta_stat {
2440    fdb_kvs_id_t kv_id;
2441    int64_t nlivenodes;
2442    int64_t ndocs;
2443    int64_t ndeletes;
2444    int64_t datasize;
2445    int64_t deltasize;
2446    struct avl_node avl_entry;
2447};
2448
2449INLINE int _fdb_seq_entry_cmp(struct avl_node *a, struct avl_node *b, void *aux)
2450{
2451    (void) aux;
2452    struct wal_stale_seq_entry *entry1 = _get_entry(a, struct wal_stale_seq_entry,
2453                                                    avl_entry);
2454    struct wal_stale_seq_entry *entry2 = _get_entry(b, struct wal_stale_seq_entry,
2455                                                    avl_entry);
2456    if (entry1->kv_id < entry2->kv_id) {
2457        return -1;
2458    } else if (entry1->kv_id > entry2->kv_id) {
2459        return 1;
2460    } else {
2461        return _CMP_U64(entry1->seqnum, entry2->seqnum);
2462    }
2463}
2464
2465
2466// Compare function to sort KVS delta stat entries in the AVL tree during WAL flush
2467INLINE int _kvs_delta_stat_cmp(struct avl_node *a, struct avl_node *b, void *aux)
2468{
2469    (void) aux;
2470    struct wal_kvs_delta_stat *stat1 = _get_entry(a, struct wal_kvs_delta_stat,
2471                                                  avl_entry);
2472    struct wal_kvs_delta_stat *stat2 = _get_entry(b, struct wal_kvs_delta_stat,
2473                                                  avl_entry);
2474    if (stat1->kv_id < stat2->kv_id) {
2475        return -1;
2476    } else if (stat1->kv_id > stat2->kv_id) {
2477        return 1;
2478    } else {
2479        return 0;
2480    }
2481}
2482
2483INLINE void _fdb_wal_flush_seq_purge(void *dbhandle,
2484                                     struct avl_tree *stale_seqnum_list,
2485                                     struct avl_tree *kvs_delta_stats)
2486{
2487    fdb_seqnum_t _seqnum;
2488    int64_t nlivenodes;
2489    int64_t ndeltanodes;
2490    int64_t delta;
2491    uint8_t kvid_seqnum[sizeof(fdb_kvs_id_t) + sizeof(fdb_seqnum_t)];
2492    struct wal_stale_seq_entry *seq_entry;
2493    struct wal_kvs_delta_stat *delta_stat;
2494    struct wal_kvs_delta_stat kvs_delta_query;
2495
2496    fdb_kvs_handle *handle = (fdb_kvs_handle *)dbhandle;
2497    struct avl_node *node = avl_first(stale_seqnum_list);
2498    while (node) {
2499        seq_entry = _get_entry(node, struct wal_stale_seq_entry, avl_entry);
2500        node = avl_next(node);
2501        nlivenodes = handle->bhandle->nlivenodes;
2502        ndeltanodes = handle->bhandle->ndeltanodes;
2503        _seqnum = _endian_encode(seq_entry->seqnum);
2504        if (handle->kvs) {
2505            // multi KV instance mode .. HB+trie
2506            kvid2buf(sizeof(fdb_kvs_id_t), seq_entry->kv_id, kvid_seqnum);
2507            memcpy(kvid_seqnum + sizeof(fdb_kvs_id_t), &_seqnum, sizeof(fdb_seqnum_t));
2508            hbtrie_remove(handle->seqtrie, (void*)kvid_seqnum,
2509                          sizeof(fdb_kvs_id_t) + sizeof(fdb_seqnum_t));
2510        } else {
2511            btree_remove(handle->seqtree, (void*)&_seqnum);
2512        }
2513        btreeblk_end(handle->bhandle);
2514
2515        kvs_delta_query.kv_id = seq_entry->kv_id;
2516        avl_node *delta_stat_node = avl_search(kvs_delta_stats,
2517                                               &kvs_delta_query.avl_entry,
2518                                               _kvs_delta_stat_cmp);
2519        if (delta_stat_node) {
2520            delta_stat = _get_entry(delta_stat_node, struct wal_kvs_delta_stat,
2521                                    avl_entry);
2522            delta = handle->bhandle->nlivenodes - nlivenodes;
2523            delta_stat->nlivenodes += delta;
2524            delta = handle->bhandle->ndeltanodes - ndeltanodes;
2525            delta *= handle->config.blocksize;
2526            delta_stat->deltasize += delta;
2527        }
2528        avl_remove(stale_seqnum_list, &seq_entry->avl_entry);
2529        free(seq_entry);
2530    }
2531}
2532
2533INLINE void _fdb_wal_flush_kvs_delta_stats(struct filemgr *file,
2534                                           struct avl_tree *kvs_delta_stats)
2535{
2536    struct avl_node *node;
2537    struct wal_kvs_delta_stat *delta_stat;
2538    node = avl_first(kvs_delta_stats);
2539    while (node) {
2540        delta_stat = _get_entry(node, struct wal_kvs_delta_stat, avl_entry);
2541        node = avl_next(node);
2542        _kvs_stat_update_attr(file, delta_stat->kv_id,
2543                              KVS_STAT_DATASIZE, delta_stat->datasize);
2544        _kvs_stat_update_attr(file, delta_stat->kv_id,
2545                              KVS_STAT_NDOCS, delta_stat->ndocs);
2546        _kvs_stat_update_attr(file, delta_stat->kv_id,
2547                              KVS_STAT_NDELETES, delta_stat->ndeletes);
2548        _kvs_stat_update_attr(file, delta_stat->kv_id,
2549                              KVS_STAT_NLIVENODES, delta_stat->nlivenodes);
2550        _kvs_stat_update_attr(file, delta_stat->kv_id,
2551                              KVS_STAT_DELTASIZE, delta_stat->deltasize);
2552        avl_remove(kvs_delta_stats, &delta_stat->avl_entry);
2553        free(delta_stat);
2554    }
2555}
2556
2557INLINE fdb_status _fdb_wal_flush_func(void *voidhandle,
2558                                      struct wal_item *item,
2559                                      struct avl_tree *stale_seqnum_list,
2560                                      struct avl_tree *kvs_delta_stats)
2561{
2562    hbtrie_result hr;
2563    fdb_kvs_handle *handle = (fdb_kvs_handle *)voidhandle;
2564    fdb_seqnum_t _seqnum;
2565    fdb_kvs_id_t kv_id = 0;
2566    fdb_status fs = FDB_RESULT_SUCCESS;
2567    uint8_t *var_key = alca(uint8_t, handle->config.chunksize);
2568    int size_id, size_seq;
2569    uint8_t *kvid_seqnum;
2570    uint64_t old_offset;
2571    int64_t _offset;
2572    int64_t delta;
2573    struct docio_object _doc;
2574    struct filemgr *file = handle->dhandle->file;
2575
2576    memset(var_key, 0, handle->config.chunksize);
2577    if (handle->kvs) {
2578        buf2kvid(handle->config.chunksize, item->header->key, &kv_id);
2579    } else {
2580        kv_id = 0;
2581    }
2582
2583    struct wal_kvs_delta_stat *kvs_delta_stat;
2584    struct wal_kvs_delta_stat kvs_delta_query;
2585    kvs_delta_query.kv_id = kv_id;
2586    avl_node *delta_stat_node = avl_search(kvs_delta_stats,
2587                                           &kvs_delta_query.avl_entry,
2588                                           _kvs_delta_stat_cmp);
2589    if (delta_stat_node) {
2590        kvs_delta_stat = _get_entry(delta_stat_node, struct wal_kvs_delta_stat,
2591                                    avl_entry);
2592    } else {
2593        kvs_delta_stat = (struct wal_kvs_delta_stat *)
2594            calloc(1, sizeof(struct wal_kvs_delta_stat));
2595        kvs_delta_stat->kv_id = kv_id;
2596        avl_insert(kvs_delta_stats, &kvs_delta_stat->avl_entry,
2597                   _kvs_delta_stat_cmp);
2598    }
2599
2600    int64_t nlivenodes = handle->bhandle->nlivenodes;
2601    int64_t ndeltanodes = handle->bhandle->ndeltanodes;
2602
2603    if (item->action == WAL_ACT_INSERT ||
2604        item->action == WAL_ACT_LOGICAL_REMOVE) {
2605        _offset = _endian_encode(item->offset);
2606
2607        hbtrie_insert(handle->trie,
2608                      item->header->key,
2609                      item->header->keylen,
2610                      (void *)&_offset,
2611                      (void *)&old_offset);
2612
2613        fs = btreeblk_end(handle->bhandle);
2614        if (fs != FDB_RESULT_SUCCESS) {
2615            return fs;
2616        }
2617        old_offset = _endian_decode(old_offset);
2618
2619        if (handle->config.seqtree_opt == FDB_SEQTREE_USE) {
2620            _seqnum = _endian_encode(item->seqnum);
2621            if (handle->kvs) {
2622                // multi KV instance mode .. HB+trie
2623                uint64_t old_offset_local;
2624
2625                size_id = sizeof(fdb_kvs_id_t);
2626                size_seq = sizeof(fdb_seqnum_t);
2627                kvid_seqnum = alca(uint8_t, size_id + size_seq);
2628                kvid2buf(size_id, kv_id, kvid_seqnum);
2629                memcpy(kvid_seqnum + size_id, &_seqnum, size_seq);
2630                hbtrie_insert(handle->seqtrie, kvid_seqnum, size_id + size_seq,
2631                              (void *)&_offset, (void *)&old_offset_local);
2632            } else {
2633                btree_insert(handle->seqtree, (void *)&_seqnum,
2634                             (void *)&_offset);
2635            }
2636            fs = btreeblk_end(handle->bhandle);
2637            if (fs != FDB_RESULT_SUCCESS) {
2638                return fs;
2639            }
2640        }
2641
2642        delta = handle->bhandle->nlivenodes - nlivenodes;
2643        kvs_delta_stat->nlivenodes += delta;
2644        delta = handle->bhandle->ndeltanodes - ndeltanodes;
2645        delta *= handle->config.blocksize;
2646        kvs_delta_stat->deltasize += delta;
2647
2648        if (old_offset == BLK_NOT_FOUND) {
2649            if (item->action == WAL_ACT_INSERT) {
2650                ++kvs_delta_stat->ndocs;
2651            } else { // inserted a logical deleted doc into main index
2652                ++kvs_delta_stat->ndeletes;
2653            }
2654            kvs_delta_stat->datasize += item->doc_size;
2655            kvs_delta_stat->deltasize += item->doc_size;
2656        } else { // update or logical delete
2657            // This block is already cached when we call HBTRIE_INSERT.
2658            // No additional block access.
2659            char dummy_key[FDB_MAX_KEYLEN];
2660            _doc.meta = _doc.body = NULL;
2661            _doc.key = &dummy_key;
2662            _offset = docio_read_doc_key_meta(handle->dhandle, old_offset,
2663                                              &_doc, true);
2664            if (_offset < 0) {
2665                return (fdb_status) _offset;
2666            } else if (_offset == 0) {
2667                // Note that this is not an error as old_offset is pointing to
2668                // the zero-filled region in a document block.
2669                return FDB_RESULT_KEY_NOT_FOUND;
2670            }
2671            free(_doc.meta);
2672            filemgr_mark_stale(file, old_offset, _fdb_get_docsize(_doc.length));
2673
2674            if (!(_doc.length.flag & DOCIO_DELETED)) {//prev doc was not deleted
2675                if (item->action == WAL_ACT_LOGICAL_REMOVE) { // now deleted
2676                    --kvs_delta_stat->ndocs;
2677                    ++kvs_delta_stat->ndeletes;
2678                } // else no change (prev doc was insert, now just an update)
2679            } else { // prev doc in main index was a logically deleted doc
2680                if (item->action == WAL_ACT_INSERT) { // now undeleted
2681                    ++kvs_delta_stat->ndocs;
2682                    --kvs_delta_stat->ndeletes;
2683                } // else no change (prev doc was deleted, now re-deleted)
2684            }
2685
2686            delta = (int)item->doc_size - (int)_fdb_get_docsize(_doc.length);
2687            kvs_delta_stat->datasize += delta;
2688            bid_t last_hdr_bid = atomic_get_uint64_t(&handle->last_hdr_bid);
2689            if (last_hdr_bid * handle->config.blocksize < old_offset) {
2690                kvs_delta_stat->deltasize += delta;
2691            } else {
2692                kvs_delta_stat->deltasize += (int)item->doc_size;
2693            }
2694
2695            // Avoid duplicates (remove previous sequence number)
2696            if (handle->config.seqtree_opt == FDB_SEQTREE_USE) {
2697                struct wal_stale_seq_entry *entry = (struct wal_stale_seq_entry *)
2698                    calloc(1, sizeof(struct wal_stale_seq_entry));
2699                entry->kv_id = kv_id;
2700                entry->seqnum = _doc.seqnum;
2701                avl_insert(stale_seqnum_list, &entry->avl_entry,
2702                           _fdb_seq_entry_cmp);
2703            }
2704        }
2705    } else {
2706        // Immediate remove
2707        old_offset = item->old_offset;
2708        hr = hbtrie_remove(handle->trie, item->header->key,
2709                           item->header->keylen);
2710        fs = btreeblk_end(handle->bhandle);
2711        if (fs != FDB_RESULT_SUCCESS) {
2712            return fs;
2713        }
2714
2715        if (hr == HBTRIE_RESULT_SUCCESS) {
2716            // This block is already cached when we call _fdb_wal_get_old_offset
2717            // No additional block access should be done.
2718            char dummy_key[FDB_MAX_KEYLEN];
2719            _doc.meta = _doc.body = NULL;
2720            _doc.key = &dummy_key;
2721            _offset = docio_read_doc_key_meta(handle->dhandle, old_offset,
2722                                              &_doc, true);
2723            if (_offset < 0) {
2724                return (fdb_status) _offset;
2725            } else if (_offset == 0) {
2726                return FDB_RESULT_KEY_NOT_FOUND;
2727            }
2728            free(_doc.meta);
2729            filemgr_mark_stale(file, old_offset, _fdb_get_docsize(_doc.length));
2730
2731            // Reduce the total number of docs by one
2732            --kvs_delta_stat->ndocs;
2733            if (_doc.length.flag & DOCIO_DELETED) {//prev deleted doc is dropped
2734                --kvs_delta_stat->ndeletes;
2735            }
2736
2737            // Reduce the total datasize by size of previously present doc
2738            delta = -(int)_fdb_get_docsize(_doc.length);
2739            kvs_delta_stat->datasize += delta;
2740            // if multiple wal flushes happen before commit, then it's possible
2741            // that this doc deleted was inserted & flushed after last commit
2742            // In this case we need to update the deltasize too which tracks
2743            // the amount of new data inserted between commits.
2744            bid_t last_hdr_bid = atomic_get_uint64_t(&handle->last_hdr_bid);
2745            if (last_hdr_bid * handle->config.blocksize < old_offset) {
2746                kvs_delta_stat->deltasize += delta;
2747            }
2748
2749            // remove sequence number for the removed doc
2750            if (handle->config.seqtree_opt == FDB_SEQTREE_USE) {
2751                struct wal_stale_seq_entry *entry = (struct wal_stale_seq_entry *)
2752                    calloc(1, sizeof(struct wal_stale_seq_entry));
2753                entry->kv_id = kv_id;
2754                entry->seqnum = _doc.seqnum;
2755                avl_insert(stale_seqnum_list, &entry->avl_entry, _fdb_seq_entry_cmp);
2756            }
2757
2758            // Update index size to new size after the remove operation
2759            delta = handle->bhandle->nlivenodes - nlivenodes;
2760            kvs_delta_stat->nlivenodes += delta;
2761
2762            // ndeltanodes measures number of new index nodes created due to
2763            // this hbtrie_remove() operation
2764            delta = (int)handle->bhandle->ndeltanodes - ndeltanodes;
2765            delta *= handle->config.blocksize;
2766            kvs_delta_stat->deltasize += delta;
2767        }
2768    }
2769    return FDB_RESULT_SUCCESS;
2770}
2771
2772void fdb_sync_db_header(fdb_kvs_handle *handle)
2773{
2774    uint64_t cur_revnum = filemgr_get_header_revnum(handle->file);
2775    if (handle->cur_header_revnum != cur_revnum) {
2776        void *header_buf = NULL;
2777        size_t header_len;
2778        bid_t hdr_bid;
2779        filemgr_header_revnum_t revnum;
2780
2781        header_buf = filemgr_get_header(handle->file, NULL, &header_len,
2782                                        &hdr_bid, NULL, &revnum);
2783        if (header_len > 0) {
2784            uint64_t header_flags, dummy64, version;
2785            bid_t idtree_root;
2786            bid_t new_seq_root;
2787            bid_t new_stale_root;
2788            char *compacted_filename;
2789            char *prev_filename = NULL;
2790
2791            version = handle->file->version;
2792            atomic_store_uint64_t(&handle->last_hdr_bid, hdr_bid);
2793            handle->cur_header_revnum = revnum;
2794
2795            fdb_fetch_header(version, header_buf, &idtree_root,
2796                             &new_seq_root, &new_stale_root, &dummy64,
2797                             &dummy64, &dummy64,
2798                             &dummy64, &handle->last_wal_flush_hdr_bid,
2799                             &handle->kv_info_offset, &header_flags,
2800                             &compacted_filename, &prev_filename);
2801
2802            if (handle->dirty_updates) {
2803                // discard all cached writable b+tree nodes
2804                // to avoid data inconsistency with other writers
2805                btreeblk_discard_blocks(handle->bhandle);
2806            }
2807
2808            handle->trie->root_bid = idtree_root;
2809
2810            if (handle->config.seqtree_opt == FDB_SEQTREE_USE) {
2811                if (new_seq_root != handle->seqtree->root_bid) {
2812                    if (handle->config.multi_kv_instances) {
2813                        handle->seqtrie->root_bid = new_seq_root;
2814                    } else {
2815                        btree_init_from_bid(handle->seqtree,
2816                                            handle->seqtree->blk_handle,
2817                                            handle->seqtree->blk_ops,
2818                                            handle->seqtree->kv_ops,
2819                                            handle->seqtree->blksize,
2820                                            new_seq_root);
2821                    }
2822                }
2823            }
2824
2825            if (ver_staletree_support(version)) {
2826                btree_init_from_bid(handle->staletree,
2827                                    handle->staletree->blk_handle,
2828                                    handle->staletree->blk_ops,
2829                                    handle->staletree->kv_ops,
2830                                    handle->staletree->blksize,
2831                                    new_stale_root);
2832            } else {
2833                handle->staletree = NULL;
2834            }
2835
2836            if (prev_filename) {
2837                free(prev_filename);
2838            }
2839
2840            handle->dirty_updates = 0;
2841            if (handle->kvs) {
2842                // multiple KV instance mode AND sub handle
2843                handle->seqnum = fdb_kvs_get_seqnum(handle->file,
2844                                                    handle->kvs->id);
2845            } else {
2846                // super handle OR single KV instance mode
2847                handle->seqnum = filemgr_get_seqnum(handle->file);
2848            }
2849        } else {
2850            atomic_store_uint64_t(&handle->last_hdr_bid,
2851                                  filemgr_get_header_bid(handle->file));
2852        }
2853
2854        if (header_buf) {
2855            free(header_buf);
2856        }
2857    } else {
2858        if (handle == handle->fhandle->root) {
2859            // MB-20091: Commits use root handle that points to default kv store
2860            // The same default KV Store can have a different user-level handle.
2861            // To ensure that the root handle which will do the commit always
2862            // remains updated with the latest sequence number generated by the
2863            // user KVS Handle, we must always update the root handle's seqnum
2864            // even if there are no new commit headers to sync up in the file.
2865            handle->seqnum = filemgr_get_seqnum(handle->file);
2866        }
2867    }
2868}
2869
2870fdb_status fdb_check_file_reopen(fdb_kvs_handle *handle, file_status_t *status)
2871{
2872    bool fhandle_ret;
2873    fdb_status fs = FDB_RESULT_SUCCESS;
2874    file_status_t fstatus = filemgr_get_file_status(handle->file);
2875    // check whether the compaction is done
2876    if (fstatus == FILE_REMOVED_PENDING) {
2877        uint64_t ndocs, ndeletes, datasize, nlivenodes, last_wal_flush_hdr_bid;
2878        uint64_t kv_info_offset, header_flags;
2879        size_t header_len;
2880        char *new_filename;
2881        uint8_t *buf = alca(uint8_t, handle->config.blocksize);
2882        bid_t trie_root_bid, seq_root_bid, stale_root_bid;
2883        fdb_config config = handle->config;
2884
2885        // close the current file and newly open the new file
2886        if (handle->config.compaction_mode == FDB_COMPACTION_AUTO) {
2887            // compaction daemon mode .. just close and then open
2888            char filename[FDB_MAX_FILENAME_LEN];
2889            strcpy(filename, handle->filename);
2890
2891            // We don't need to maintain fhandle list for the old file
2892            // as there will be no more mutation on the file.
2893            fhandle_ret = filemgr_fhandle_remove(handle->file, handle->fhandle);
2894            fs = _fdb_close(handle);
2895            if (fs != FDB_RESULT_SUCCESS) {
2896                if (fhandle_ret) {
2897                    filemgr_fhandle_add(handle->file, handle->fhandle);
2898                }
2899                return fs;
2900            }
2901
2902            fs = _fdb_open(handle, filename, FDB_VFILENAME, &config);
2903            if (fs != FDB_RESULT_SUCCESS) {
2904                return fs;
2905            }
2906            filemgr_fhandle_add(handle->file, handle->fhandle);
2907
2908        } else {
2909            filemgr_get_header(handle->file, buf, &header_len, NULL, NULL, NULL);
2910            fdb_fetch_header(handle->file->version, buf,
2911                             &trie_root_bid, &seq_root_bid, &stale_root_bid,
2912                             &ndocs, &ndeletes, &nlivenodes, &datasize,
2913                             &last_wal_flush_hdr_bid,
2914                             &kv_info_offset, &header_flags,
2915                             &new_filename, NULL);
2916
2917            fhandle_ret = filemgr_fhandle_remove(handle->file, handle->fhandle);
2918            fs = _fdb_close(handle);
2919            if (fs != FDB_RESULT_SUCCESS) {
2920                if (fhandle_ret) {
2921                    filemgr_fhandle_add(handle->file, handle->fhandle);
2922                }
2923                return fs;
2924            }
2925
2926            fs = _fdb_open(handle, new_filename, FDB_AFILENAME, &config);
2927            if (fs != FDB_RESULT_SUCCESS) {
2928                return fs;
2929            }
2930            filemgr_fhandle_add(handle->file, handle->fhandle);
2931        }
2932    }
2933    if (status) {
2934        *status = fstatus;
2935    }
2936    return fs;
2937}
2938
2939static void _fdb_sync_dirty_root(fdb_kvs_handle *handle)
2940{
2941    bid_t dirty_idtree_root = BLK_NOT_FOUND;
2942    bid_t dirty_seqtree_root = BLK_NOT_FOUND;
2943
2944    if (handle->shandle) {
2945        // skip snapshot
2946        return;
2947    }
2948
2949    struct filemgr_dirty_update_node *dirty_update;
2950    dirty_update = filemgr_dirty_update_get_latest(handle->file);
2951    btreeblk_set_dirty_update(handle->bhandle, dirty_update);
2952
2953    if (dirty_update) {
2954        filemgr_dirty_update_get_root(handle->file, dirty_update,
2955                                      &dirty_idtree_root, &dirty_seqtree_root);
2956        _fdb_import_dirty_root(handle, dirty_idtree_root, dirty_seqtree_root);
2957        btreeblk_discard_blocks(handle->bhandle);
2958    }
2959
2960    return;
2961}
2962
2963static void _fdb_release_dirty_root(fdb_kvs_handle *handle)
2964{
2965    if (!handle->shandle) {
2966        struct filemgr_dirty_update_node *dirty_update;
2967        dirty_update = btreeblk_get_dirty_update(handle->bhandle);
2968        if (dirty_update) {
2969            filemgr_dirty_update_close_node(handle->file, dirty_update);
2970            btreeblk_clear_dirty_update(handle->bhandle);
2971        }
2972    }
2973}
2974
2975LIBFDB_API
2976fdb_status fdb_get(fdb_kvs_handle *handle, fdb_doc *doc)
2977{
2978    uint64_t offset;
2979    int64_t _offset;
2980    struct docio_object _doc;
2981    struct filemgr *wal_file = NULL;
2982    struct docio_handle *dhandle;
2983    struct _fdb_key_cmp_info cmp_info;
2984    fdb_status wr;
2985    hbtrie_result hr = HBTRIE_RESULT_FAIL;
2986    fdb_txn *txn;
2987    fdb_doc doc_kv;
2988    LATENCY_STAT_START();
2989
2990    if (!handle) {
2991        return FDB_RESULT_INVALID_HANDLE;
2992    }
2993
2994    if (!doc || !doc->key || doc->keylen == 0 ||
2995        doc->keylen > FDB_MAX_KEYLEN ||
2996        (handle->kvs_config.custom_cmp &&
2997            doc->keylen > handle->config.blocksize - HBTRIE_HEADROOM)) {
2998        return FDB_RESULT_INVALID_ARGS;
2999    }
3000
3001    if (!atomic_cas_uint8_t(&handle->handle_busy, 0, 1)) {
3002        return FDB_RESULT_HANDLE_BUSY;
3003    }
3004
3005    doc_kv = *doc;
3006
3007    if (handle->kvs) {
3008        // multi KV instance mode
3009        int size_chunk = handle->config.chunksize;
3010        doc_kv.keylen = doc->keylen + size_chunk;
3011        doc_kv.key = alca(uint8_t, doc_kv.keylen);
3012        kvid2buf(size_chunk, handle->kvs->id, doc_kv.key);
3013        memcpy((uint8_t*)doc_kv.key + size_chunk, doc->key, doc->keylen);
3014    }
3015
3016    if (!handle->shandle) {
3017        fdb_check_file_reopen(handle, NULL);
3018        txn = handle->fhandle->root->txn;
3019        if (!txn) {
3020            txn = &handle->file->global_txn;
3021        }
3022    } else {
3023        txn = handle->shandle->snap_txn;
3024    }
3025
3026    cmp_info.kvs_config = handle->kvs_config;
3027    cmp_info.kvs = handle->kvs;
3028    wal_file = handle->file;
3029    dhandle = handle->dhandle;
3030
3031    if (handle->kvs) {
3032        wr = wal_find(txn, wal_file, &cmp_info, handle->shandle, &doc_kv,
3033                      &offset);
3034    } else {
3035        wr = wal_find(txn, wal_file, &cmp_info, handle->shandle, doc,
3036                      &offset);
3037    }
3038
3039    if (!handle->shandle) {
3040        fdb_sync_db_header(handle);
3041    }
3042
3043    atomic_incr_uint64_t(&handle->op_stats->num_gets, std::memory_order_relaxed);
3044
3045    if (wr == FDB_RESULT_KEY_NOT_FOUND) {
3046        _fdb_sync_dirty_root(handle);
3047
3048        if (handle->kvs) {
3049            hr = hbtrie_find(handle->trie, doc_kv.key, doc_kv.keylen,
3050                             (void *)&offset);
3051        } else {
3052            hr = hbtrie_find(handle->trie, doc->key, doc->keylen,
3053                             (void *)&offset);
3054        }
3055        btreeblk_end(handle->bhandle);
3056        offset = _endian_decode(offset);
3057
3058        _fdb_release_dirty_root(handle);
3059    }
3060
3061    if ((wr == FDB_RESULT_SUCCESS && offset != BLK_NOT_FOUND) ||
3062         hr == HBTRIE_RESULT_SUCCESS) {
3063        bool alloced_meta = doc->meta ? false : true;
3064        bool alloced_body = doc->body ? false : true;
3065        if (handle->kvs) {
3066            _doc.key = doc_kv.key;
3067            _doc.length.keylen = doc_kv.keylen;
3068            doc->deleted = doc_kv.deleted; // update deleted field if wal_find
3069        } else {
3070            _doc.key = doc->key;
3071            _doc.length.keylen = doc->keylen;
3072        }
3073        _doc.meta = doc->meta;
3074        _doc.body = doc->body;
3075
3076        if (wr == FDB_RESULT_SUCCESS && doc->deleted) {
3077            atomic_cas_uint8_t(&handle->handle_busy, 1, 0);
3078            return FDB_RESULT_KEY_NOT_FOUND;
3079        }
3080
3081        _offset = docio_read_doc(dhandle, offset, &_doc, true);
3082        if (_offset <= 0) {
3083            atomic_cas_uint8_t(&handle->handle_busy, 1, 0);
3084            return _offset < 0 ? (fdb_status)_offset : FDB_RESULT_KEY_NOT_FOUND;
3085        }
3086
3087        if (_doc.length.keylen != doc_kv.keylen ||
3088            _doc.length.flag & DOCIO_DELETED) {
3089            free_docio_object(&_doc, 0, alloced_meta, alloced_body);
3090            atomic_cas_uint8_t(&handle->handle_busy, 1, 0);
3091            return FDB_RESULT_KEY_NOT_FOUND;
3092        }
3093
3094        doc->seqnum = _doc.seqnum;
3095        doc->metalen = _doc.length.metalen;
3096        doc->bodylen = _doc.length.bodylen;
3097        doc->meta = _doc.meta;
3098        doc->body = _doc.body;
3099        doc->deleted = _doc.length.flag & DOCIO_DELETED;
3100        doc->size_ondisk = _fdb_get_docsize(_doc.length);
3101        doc->offset = offset;
3102
3103        LATENCY_STAT_END(handle->file, FDB_LATENCY_GETS);
3104        atomic_cas_uint8_t(&handle->handle_busy, 1, 0);
3105        return FDB_RESULT_SUCCESS;
3106    }
3107
3108    atomic_cas_uint8_t(&handle->handle_busy, 1, 0);
3109    return FDB_RESULT_KEY_NOT_FOUND;
3110}
3111
3112// search document metadata using key
3113LIBFDB_API
3114fdb_status fdb_get_metaonly(fdb_kvs_handle *handle, fdb_doc *doc)
3115{
3116    uint64_t offset;
3117    struct docio_object _doc;
3118    struct docio_handle *dhandle;
3119    struct filemgr *wal_file = NULL;
3120    fdb_status wr;
3121    hbtrie_result hr = HBTRIE_RESULT_FAIL;
3122    fdb_txn *txn;
3123    struct _fdb_key_cmp_info cmp_info;
3124    fdb_doc doc_kv;
3125    LATENCY_STAT_START();
3126
3127    if (!handle) {
3128        return FDB_RESULT_INVALID_HANDLE;
3129    }
3130
3131    if (!doc || !doc->key ||
3132        doc->keylen == 0 || doc->keylen > FDB_MAX_KEYLEN ||
3133        (handle->kvs_config.custom_cmp &&
3134            doc->keylen > handle->config.blocksize - HBTRIE_HEADROOM)) {
3135        return FDB_RESULT_INVALID_ARGS;
3136    }
3137
3138    doc_kv = *doc;
3139
3140    if (!atomic_cas_uint8_t(&handle->handle_busy, 0, 1)) {
3141        return FDB_RESULT_HANDLE_BUSY;
3142    }
3143
3144    if (handle->kvs) {
3145        // multi KV instance mode
3146        int size_chunk = handle->config.chunksize;
3147        doc_kv.keylen = doc->keylen + size_chunk;
3148        doc_kv.key = alca(uint8_t, doc_kv.keylen);
3149        kvid2buf(size_chunk, handle->kvs->id, doc_kv.key);
3150        memcpy((uint8_t*)doc_kv.key + size_chunk, doc->key, doc->keylen);
3151    }
3152
3153    if (!handle->shandle) {
3154        fdb_check_file_reopen(handle, NULL);
3155        txn = handle->fhandle->root->txn;
3156        if (!txn) {
3157            txn = &handle->file->global_txn;
3158        }
3159    } else {
3160        txn = handle->shandle->snap_txn;
3161    }
3162
3163    cmp_info.kvs_config = handle->kvs_config;
3164    cmp_info.kvs = handle->kvs;
3165    wal_file = handle->file;
3166    dhandle = handle->dhandle;
3167
3168    if (handle->kvs) {
3169        wr = wal_find(txn, wal_file, &cmp_info, handle->shandle, &doc_kv,
3170                      &offset);
3171    } else {
3172        wr = wal_find(txn, wal_file, &cmp_info, handle->shandle, doc, &offset);
3173    }
3174
3175    if (!handle->shandle) {
3176        fdb_sync_db_header(handle);
3177    }
3178    atomic_incr_uint64_t(&handle->op_stats->num_gets, std::memory_order_relaxed);
3179
3180    if (wr == FDB_RESULT_KEY_NOT_FOUND) {
3181        _fdb_sync_dirty_root(handle);
3182
3183        if (handle->kvs) {
3184            hr = hbtrie_find(handle->trie, doc_kv.key, doc_kv.keylen,
3185                             (void *)&offset);
3186        } else {
3187            hr = hbtrie_find(handle->trie, doc->key, doc->keylen,
3188                             (void *)&offset);
3189        }
3190        btreeblk_end(handle->bhandle);
3191        offset = _endian_decode(offset);
3192
3193        _fdb_release_dirty_root(handle);
3194    }
3195
3196    if ((wr == FDB_RESULT_SUCCESS && offset != BLK_NOT_FOUND) ||
3197         hr == HBTRIE_RESULT_SUCCESS) {
3198        if (handle->kvs) {
3199            _doc.key = doc_kv.key;
3200            _doc.length.keylen = doc_kv.keylen;
3201        } else {
3202            _doc.key = doc->key;
3203            _doc.length.keylen = doc->keylen;
3204        }
3205        bool alloced_meta = doc->meta ? false : true;
3206        _doc.meta = doc->meta;
3207        _doc.body = doc->body;
3208
3209        int64_t body_offset = docio_read_doc_key_meta(dhandle, offset, &_doc,
3210                                                       true);
3211        if (body_offset <= 0){
3212            atomic_cas_uint8_t(&handle->handle_busy, 1, 0);
3213            return body_offset < 0 ? (fdb_status)body_offset : FDB_RESULT_KEY_NOT_FOUND;
3214        }
3215
3216        if (_doc.length.keylen != doc_kv.keylen) {
3217            free_docio_object(&_doc, 0, alloced_meta, 0);
3218            atomic_cas_uint8_t(&