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