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