ydb.c 178 KB
Newer Older
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1
/* -*- mode: C; c-basic-offset: 4 -*- */
2
#ident "Copyright (c) 2007-2009 Tokutek Inc.  All rights reserved."
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3
 
4 5 6
#ident "The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it."

const char *toku_patent_string = "The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it.";
7
const char *toku_copyright_string = "Copyright (c) 2007-2009 Tokutek Inc.  All rights reserved.";
8

9
#include <toku_portability.h>
10
#include <toku_pthread.h>
11
#include <ctype.h>
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
12 13 14
#include <errno.h>
#include <limits.h>
#include <stdarg.h>
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
15 16 17
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
18
#include <fcntl.h>
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
19
#include <sys/stat.h>
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
20 21
#include <sys/types.h>
#include <unistd.h>
22
#include <db.h>
23
#include "toku_assert.h"
24
#include "ydb.h"
25
#include "ydb-internal.h"
26
#include "brt-internal.h"
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
27
#include "cachetable.h"
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
28 29
#include "log.h"
#include "memory.h"
30
#include "dlmalloc.h"
31
#include "checkpoint.h"
32
#include "key.h"
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
33

Yoni Fogel's avatar
Yoni Fogel committed
34

35 36 37 38 39 40 41 42 43 44
#ifdef TOKUTRACE
 #define DB_ENV_CREATE_FUN db_env_create_toku10
 #define DB_CREATE_FUN db_create_toku10
#else
 #define DB_ENV_CREATE_FUN db_env_create
 #define DB_CREATE_FUN db_create
 int toku_set_trace_file (char *fname __attribute__((__unused__))) { return 0; }
 int toku_close_trace_file (void) { return 0; } 
#endif

45 46 47 48 49 50 51 52 53

// Accountability: operation counters available for debugging and for "show engine status"
static u_int64_t num_inserts;
static u_int64_t num_deletes;
static u_int64_t num_commits;
static u_int64_t num_aborts;
static u_int64_t num_point_queries;
static u_int64_t num_sequential_queries;

54
static int env_get_iname(DB_ENV* env, DBT* dname_dbt, DBT* iname_dbt);
55 56


Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
57 58
/** The default maximum number of persistent locks in a lock tree  */
const u_int32_t __toku_env_default_max_locks = 1000;
Rich Prohaska's avatar
Rich Prohaska committed
59

60 61 62 63 64 65 66
static inline DBT*
init_dbt_realloc(DBT *dbt) {
    memset(dbt, 0, sizeof(*dbt));
    dbt->flags = DB_DBT_REALLOC;
    return dbt;
}

Yoni Fogel's avatar
Yoni Fogel committed
67 68 69 70 71 72 73 74
int toku_ydb_init(void) {
    int r = 0;
    //Lower level must be initialized first.
    if (r==0) 
        r = toku_brt_init(toku_ydb_lock, toku_ydb_unlock);
    if (r==0) 
        r = toku_ydb_lock_init();
    return r;
75 76
}

Yoni Fogel's avatar
Yoni Fogel committed
77 78 79 80 81 82 83 84
int toku_ydb_destroy(void) {
    int r = 0;
    if (r==0)
        r = toku_ydb_lock_destroy();
    //Lower level must be cleaned up last.
    if (r==0)
        r = toku_brt_destroy();
    return r;
85 86
}

87 88 89 90 91
static int
ydb_getf_do_nothing(DBT const* UU(key), DBT const* UU(val), void* UU(extra)) {
    return 0;
}

Rich Prohaska's avatar
Rich Prohaska committed
92 93 94
/* the ydb reference is used to cleanup the library when there are no more references to it */
static int toku_ydb_refs = 0;

95
static inline void ydb_add_ref(void) {
Rich Prohaska's avatar
Rich Prohaska committed
96 97 98
    ++toku_ydb_refs;
}

99
static inline void ydb_unref(void) {
Rich Prohaska's avatar
Rich Prohaska committed
100 101 102 103 104 105 106 107 108
    assert(toku_ydb_refs > 0);
    if (--toku_ydb_refs == 0) {
        /* call global destructors */
        toku_malloc_cleanup();
    }
}

/* env methods */
static int toku_env_close(DB_ENV *env, u_int32_t flags);
109 110 111
static int toku_env_set_data_dir(DB_ENV * env, const char *dir);
static int toku_env_set_lg_dir(DB_ENV * env, const char *dir);
static int toku_env_set_tmp_dir(DB_ENV * env, const char *tmp_dir);
Rich Prohaska's avatar
Rich Prohaska committed
112

113 114
static inline int env_opened(DB_ENV *env) {
    return env->i->cachetable != 0;
Rich Prohaska's avatar
Rich Prohaska committed
115 116
}

117
static void env_init_open_txn(DB_ENV *env) {
118
    toku_list_init(&env->i->open_txns);
Rich Prohaska's avatar
Rich Prohaska committed
119 120
}

121 122
// add a txn to the list of open txn's
static void env_add_open_txn(DB_ENV *env, DB_TXN *txn) {
123
    toku_list_push(&env->i->open_txns, (struct toku_list *) (void *) &txn->open_txns);
124 125 126 127
}

// remove a txn from the list of open txn's
static void env_remove_open_txn(DB_ENV *UU(env), DB_TXN *txn) {
128
    toku_list_remove((struct toku_list *) (void *) &txn->open_txns);
Rich Prohaska's avatar
Rich Prohaska committed
129 130
}

131 132
static int toku_txn_abort(DB_TXN * txn);

Rich Prohaska's avatar
Rich Prohaska committed
133 134
/* db methods */
static inline int db_opened(DB *db) {
135
    return db->i->opened != 0;
Rich Prohaska's avatar
Rich Prohaska committed
136 137 138 139
}

static int toku_db_put(DB * db, DB_TXN * txn, DBT * key, DBT * data, u_int32_t flags);
static int toku_db_get (DB * db, DB_TXN * txn, DBT * key, DBT * data, u_int32_t flags);
140
static int toku_db_cursor(DB *db, DB_TXN * txn, DBC **c, u_int32_t flags, int is_temporary_cursor);
Rich Prohaska's avatar
Rich Prohaska committed
141 142 143

/* txn methods */

144
/* lightweight cursor methods. */
145 146 147
static int toku_c_getf_first(DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra);

static int toku_c_getf_last(DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra);
Yoni Fogel's avatar
Yoni Fogel committed
148

149 150 151
static int toku_c_getf_next(DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra);
static int toku_c_getf_next_nodup(DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra);
static int toku_c_getf_next_dup(DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra);
Yoni Fogel's avatar
Yoni Fogel committed
152

153 154 155
static int toku_c_getf_prev(DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra);
static int toku_c_getf_prev_nodup(DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra);
static int toku_c_getf_prev_dup(DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra);
Yoni Fogel's avatar
Yoni Fogel committed
156

157 158
static int toku_c_getf_current(DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra);
static int toku_c_getf_current_binding(DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra);
Yoni Fogel's avatar
Yoni Fogel committed
159

160 161
static int toku_c_getf_set(DBC *c, u_int32_t flag, DBT *key, YDB_CALLBACK_FUNCTION f, void *extra);
static int toku_c_getf_set_range(DBC *c, u_int32_t flag, DBT *key, YDB_CALLBACK_FUNCTION f, void *extra);
162
static int toku_c_getf_set_range_reverse(DBC *c, u_int32_t flag, DBT *key, YDB_CALLBACK_FUNCTION f, void *extra);
163 164
static int toku_c_getf_get_both(DBC *c, u_int32_t flag, DBT *key, DBT *val, YDB_CALLBACK_FUNCTION f, void *extra);
static int toku_c_getf_get_both_range(DBC *c, u_int32_t flag, DBT *key, DBT *val, YDB_CALLBACK_FUNCTION f, void *extra);
165
static int toku_c_getf_get_both_range_reverse(DBC *c, u_int32_t flag, DBT *key, DBT *val, YDB_CALLBACK_FUNCTION f, void *extra);
166

167 168 169
static int toku_c_getf_heaviside(DBC *c, u_int32_t flags,
                                 YDB_HEAVISIDE_CALLBACK_FUNCTION f, void *extra_f,
                                 YDB_HEAVISIDE_FUNCTION h, void *extra_h, int direction); 
Yoni Fogel's avatar
Yoni Fogel committed
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
// There is a total order on all key/value pairs in the database.
// In a DB_DUPSORT db, let V_i = (Key,Value) refer to the ith element (0 based indexing).
// In a NODUP      db, let V_i = (Key)       refer to the ith element (0 based indexing).
// We define V_{-1}             = -\infty and
//           V_{|V|}            =  \infty and
//           h(-\infty,extra_h) = -1 by definition and
//           h( \infty,extra_h) =  1 by definition
// Requires: Direction != 0
// Effect: 
//    if direction >0 then find the smallest i such that h(V_i,extra_h)>=0.
//    if direction <0 then find the largest  i such that h(V_i,extra_h)<=0.
//    Let signus(r_h) = signus(h(V_i, extra_h)) 
//    If flags&(DB_PRELOCKED|DB_PRELOCKED_WRITE) then skip locking
//      That is, we already own the locks
//    else 
//      if direction >0 then readlock [V_{i-1}, V_i]
//      if direction <0 then readlock [V_i,     V_{i+1}]
//      That is, If we search from the right, lock the element we found, up to the
//           next element to the right.
//      If locking fails, return the locking error code
//    
//    If (0<=i<|V|) then
//      call f(V_i.Key, V_i.Value, extra_f, r_h)
//      Note: The lifetime of V_i.Key and V_i.Value is limited: they may only
//            be referenced until f returns
//      and return 0
//    else
//      return DB_NOTFOUND
// Rationale: Locking
//      If we approach from the left (direction<0) we need to prevent anyone
//      from inserting anything to our right that could change our answer,
//      so we lock the range from the element found, to the next element to the right.
//      The inverse argument applies for approaching from the right.
// Rationale: passing r_h to f
//      We want to save the performance hit of requiring f to call h again to
//      find out what h's return value was.
// Rationale: separate extra_f, extra_h parameters
//      If the same extra parameter is sent to both f and h, then you need a
//      special struct for each tuple (f_i, h_i) you use instead of a struct for each
//      f_i and each h_i.
// Requires: The signum of h is monotically increasing.
//  Requires: f does not create references to key, value, or data within once f
//           exits
// Returns
//      0                   success
//      DB_NOTFOUND         i is not in [0,|V|)
//      DB_LOCK_NOTGRANTED  Failed to obtain a lock.
//  On nonzero return, what c points to becomes undefined, That is, c becomes uninitialized
// Performance: ... TODO
// Implementation Notes:
//      How do we get the extra locking information efficiently?
//        After finding the target, we can copy the cursor, do a DB_NEXT,
//        or do a DB_NEXT+DB_PREV (vice versa for direction<0).
//        Can we have the BRT provide two key/value pairs instead of one?
//        That is, brt_cursor_c_getf_heavi_and_next for direction >0
//        and  brt_cursor_c_getf_heavi_and_prev for direction <0
//      Current suggestion is to make a copy of the cursor, and use the
//        copy to find the next(prev) element by using DB_NEXT(DB_PREV).
//        This has the overhead of needing to make a copy of the cursor,
//        which probably has a memcpy involved.
//        The argument against returning two key/value pairs is that
//        we should not have to pay to retreive both when we're doing something
//        simple like DB_NEXT.
//        This could be mitigated by having two BRT functions (or one with a
//        BOOL parameter) such that it only returns two values when necessary.
// Parameters
//  c           The cursor
//  flags       Additional bool parameters. The current allowed flags are
//              DB_PRELOCKED and DB_PRELOCKED_WRITE (bitwise or'd to use both)
//  h           A heaviside function that, along with direction, defines the query.
//              extra_h is passed to h
//              For additional information on heaviside functions, see omt.h
//              NOTE: In a DB_DUPSORT database, both key and value will be
//              passed to h.  In a NODUP database, only key will be passed to h.
//  f           A callback function (i.e. smart dbts) to provide the result of the
//              query.  key and value are the key/value pair found, extra_f is
//              passed to f, r_h is the return value for h for the key and value returned.
//              This is used as output. That is, we call f with the outputs of the
//              function.
//  direction   Which direction to search in on the heaviside function.  >0
//              means from the right, <0 means from the left.
//  extra_f     Any extra information required for f
//  extra_h     Any extra information required for h
//
// Example:
//  Find the smallest V_i = (key_i,val_i) such that key_i > key_x, assume
//   key.data and val.data are c strings, and print them out.
//      Create a struct to hold key_x, that is extra_h
//      Direction = 1 (We approach from the right, and want the smallest such
//          element).
//      Construct a heaviside function that returns >=0 if the
//      given key > key_x, and -1 otherwise
//          That is, call the comparison function on (key, key_x)
//      Create a struct to hold key_x, that is extra_f
//      construct f to call printf on key_x.data, key_i.data, val_i.data.
//  Find the least upper bound (greatest lower bound)
//      In this case, h can just return the comparison function's answer.
//      direction >0 means upper bound, direction <0 means lower bound.
//      (If you want upper/lower bound of the keyvalue pair, you need
//      to call the comparison function on the values if the key comparison
//      returns 0).
// Handlerton implications:
//  The handlerton needs at most one heaviside function per special query type (where a
//  special query is one that is not directly supported by the bdb api excluding
//  this function).
//  It is possible that more than query type can use the same heaviside function
//  if the extra_h parameter can be used to change its behavior sufficiently.
//
//  That is, part of extra_h can be a boolean strictly_greater
//  You can construct a single heaviside function that converts 0 to -1
//  (strictly greater) from the comparison function, or one that just returns
//  the results of the comparison function (greater or equal).
//
// Implementation Notes:
//  The BRT search function supports the following searches:
//      SEARCH_LEFT(h(V_i))
//          Given a step function b, that goes from 0 to 1
//          find the greatest i such that h_b(V_i) == 1
//          If it does not exist, return not found
//      SEARCH_RIGHT(h(V_i))
//          Given a step function b, that goes from 1 to 0
//          find the smallest i such that h_b(V_i) == 1
//          If it does not exist, return not found
//  We can implement c_getf_heavi using these BRT search functions.
//  A query of direction<0:
//      Create wrapper function B
//          return h(V_i) <=0 ? 1 : 0;
//      SEARCH_RIGHT(B)
//  A query of direction>0:
//      Create wrapper function B
//          return h(V_i) >=0 ? 1 : 0;
//      SEARCH_LEFT(B)

// Effect: Lightweight cursor get

Rich Prohaska's avatar
Rich Prohaska committed
305 306 307 308 309
/* cursor methods */
static int toku_c_get(DBC * c, DBT * key, DBT * data, u_int32_t flag);
static int toku_c_del(DBC *c, u_int32_t flags);
static int toku_c_count(DBC *cursor, db_recno_t *count, u_int32_t flags);
static int toku_c_close(DBC * c);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
310

Rich Prohaska's avatar
Rich Prohaska committed
311
/* misc */
312
static char *construct_full_name(int count, ...);
313 314 315 316 317

static int delete_rolltmp_files(DB_ENV *env) {
    const char *datadir=env->i->dir;
    char *logdir;
    if (env->i->lg_dir) {
318
	logdir = construct_full_name(2, env->i->dir, env->i->lg_dir);
319 320 321 322 323 324 325
    } else {
	logdir = toku_strdup(env->i->dir);
    }
    int r = tokudb_recover_delete_rolltmp_files(datadir, logdir);
    toku_free(logdir);
    return r;
}
Yoni Fogel's avatar
Yoni Fogel committed
326
    
327
static int do_recovery (DB_ENV *env) {
328
    const char *envdir=env->i->dir;
329 330
    char *logdir;
    if (env->i->lg_dir) {
331
	logdir = construct_full_name(2, env->i->dir, env->i->lg_dir);
332
    } else {
333
	logdir = toku_strdup(env->i->dir);
334
    }
335
    toku_ydb_unlock();
336
    int r = tokudb_recover(envdir, logdir, env->i->bt_compare, env->i->dup_compare);
337
    toku_ydb_lock();
338 339
    toku_free(logdir);
    return r;
340 341 342 343 344
}

static int needs_recovery (DB_ENV *env) {
    char *logdir;
    if (env->i->lg_dir) {
345
	logdir = construct_full_name(2, env->i->dir, env->i->lg_dir);
346 347 348
    } else {
	logdir = toku_strdup(env->i->dir);
    }
349
    int recovery_needed = tokudb_needs_recovery(logdir, TRUE);
350 351
    toku_free(logdir);
    return recovery_needed ? DB_RUNRECOVERY : 0;
352 353
}

354 355 356 357 358 359
static int toku_db_create(DB ** db, DB_ENV * env, u_int32_t flags);
static int toku_db_set_bt_compare(DB * db, int (*bt_compare) (DB *, const DBT *, const DBT *));
static int toku_db_set_dup_compare(DB *db, int (*dup_compare)(DB *, const DBT *, const DBT *));
static int toku_db_open(DB * db, DB_TXN * txn, const char *fname, const char *dbname, DBTYPE dbtype, u_int32_t flags, int mode);
static int toku_env_txn_checkpoint(DB_ENV * env, u_int32_t kbyte, u_int32_t min, u_int32_t flags);
static int toku_db_close(DB * db, u_int32_t flags);
360
static int toku_txn_begin(DB_ENV *env, DB_TXN * stxn, DB_TXN ** txn, u_int32_t flags, int internal);
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
static int toku_txn_commit(DB_TXN * txn, u_int32_t flags);
static int db_open_iname(DB * db, DB_TXN * txn, const char *iname, u_int32_t flags, int mode);

static void finalize_file_removal(int fd, void * extra);

// Instruct db to use the default (built-in) key comparison function
// by setting the flag bits in the db and brt structs
static int
db_use_builtin_key_cmp(DB *db) {
    HANDLE_PANICKED_DB(db);
    int r;
    if (db_opened(db))
        r = toku_ydb_do_error(db->dbenv, EINVAL, "Comparison functions cannot be set after DB open.\n");
    else if (db->i->key_compare_was_set)
        r = toku_ydb_do_error(db->dbenv, EINVAL, "Key comparison function already set.\n");
    else {
        u_int32_t tflags;
        r = toku_brt_get_flags(db->i->brt, &tflags);
        if (r!=0) return r;

        tflags |= TOKU_DB_KEYCMP_BUILTIN;
        r = toku_brt_set_flags(db->i->brt, tflags);
        if (!r)
            db->i->key_compare_was_set = TRUE;
    }
    return r;
}

static int
db_use_builtin_val_cmp(DB *db) {
    HANDLE_PANICKED_DB(db);
    int r;
    if (db_opened(db))
        r = toku_ydb_do_error(db->dbenv, EINVAL, "Comparison functions cannot be set after DB open.\n");
    else if (db->i->val_compare_was_set)
        r = toku_ydb_do_error(db->dbenv, EINVAL, "Val comparison function already set.\n");
    else {
        u_int32_t tflags;
        r = toku_brt_get_flags(db->i->brt, &tflags);
        if (r!=0) return r;

        tflags |= TOKU_DB_VALCMP_BUILTIN;
        r = toku_brt_set_flags(db->i->brt, tflags);
        if (!r)
            db->i->val_compare_was_set = TRUE;
    }
    return r;
}


//    DB *directory; //Maps dnames to inames
//    DB *persistent_environment; //Stores environment settings, can be used for upgrade
Rich Prohaska's avatar
Rich Prohaska committed
413
static int toku_env_open(DB_ENV * env, const char *home, u_int32_t flags, int mode) {
414
    HANDLE_PANICKED_ENV(env);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
415
    int r;
416
    u_int32_t unused_flags=flags;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
417

Rich Prohaska's avatar
Rich Prohaska committed
418
    if (env_opened(env)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
419
	return toku_ydb_do_error(env, EINVAL, "The environment is already open\n");
420
    }
Yoni Fogel's avatar
Yoni Fogel committed
421

422 423 424 425
    HANDLE_EXTRA_FLAGS(env, flags, 
                       DB_CREATE|DB_PRIVATE|DB_INIT_LOG|DB_INIT_TXN|DB_RECOVER|DB_INIT_MPOOL|DB_INIT_LOCK|DB_THREAD);


426 427
    // DB_CREATE means create if env does not exist, and Tokudb requires it because
    // Tokudb requries DB_PRIVATE.
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
428 429 430 431
    if ((flags & DB_PRIVATE) && !(flags & DB_CREATE)) {
	return toku_ydb_do_error(env, ENOENT, "DB_PRIVATE requires DB_CREATE (seems gratuitous to us, but that's BDB's behavior\n");
    }

432 433
    if (!(flags & DB_PRIVATE)) {
	return toku_ydb_do_error(env, ENOENT, "TokuDB requires DB_PRIVATE\n");
Yoni Fogel's avatar
Yoni Fogel committed
434
    }
435 436 437

    if ((flags & DB_INIT_LOG) && !(flags & DB_INIT_TXN)) 
	return toku_ydb_do_error(env, EINVAL, "TokuDB requires transactions for logging\n");
438

Yoni Fogel's avatar
Yoni Fogel committed
439
    if (!home) home = ".";
Yoni Fogel's avatar
Yoni Fogel committed
440

Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
441
	// Verify that the home exists.
Yoni Fogel's avatar
Yoni Fogel committed
442
	{
Zardosht Kasheff's avatar
Zardosht Kasheff committed
443 444
	    BOOL made_new_home = FALSE;
        char* new_home = NULL;
445
    	toku_struct_stat buf;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
446 447 448 449 450 451
        if (home[strlen(home)-1] == '\\') {
            new_home = toku_malloc(strlen(home));
            memcpy(new_home, home, strlen(home));
            new_home[strlen(home) - 1] = 0;
            made_new_home = TRUE;
        }
452
    	r = toku_stat(made_new_home? new_home : home, &buf);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
453 454 455 456
        if (made_new_home) {
            toku_free(new_home);
        }
    	if (r!=0) {
457
    	    return toku_ydb_do_error(env, errno, "Error from toku_stat(\"%s\",...)\n", home);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
458
    	}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
459
    }
460
    unused_flags &= ~DB_PRIVATE;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
461 462 463

    if (env->i->dir)
        toku_free(env->i->dir);
Yoni Fogel's avatar
Yoni Fogel committed
464
    env->i->dir = toku_strdup(home);
465
    if (env->i->dir == 0) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
466
	return toku_ydb_do_error(env, ENOMEM, "Out of memory\n");
467
    }
Yoni Fogel's avatar
Yoni Fogel committed
468 469 470 471 472 473
    if (0) {
        died1:
        toku_free(env->i->dir);
        env->i->dir = NULL;
        return r;
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
474 475
    env->i->open_flags = flags;
    env->i->open_mode = mode;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
476

477
    unused_flags &= ~DB_INIT_TXN & ~DB_INIT_LOG;
478

479 480
    if (flags & DB_INIT_TXN) {
        r = delete_rolltmp_files(env);
481
        if (r != 0) return r;
482
    }
483 484 485 486 487 488 489 490 491 492
 
    if (flags & DB_INIT_LOG) {
        if (flags & DB_RECOVER) {
            r = do_recovery(env);
            if (r != 0) return r;
        } else {
            r = needs_recovery(env);
            if (r != 0) return r;
        }
    }
493

Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
494
    if (flags & (DB_INIT_TXN | DB_INIT_LOG)) {
495
        char* full_dir = NULL;
496 497 498 499
        if (env->i->lg_dir) {
            full_dir = construct_full_name(2, env->i->dir, env->i->lg_dir);
            assert(full_dir);
        }
500
	assert(env->i->logger);
501
        toku_logger_write_log_files(env->i->logger, (BOOL)((flags & DB_INIT_LOG) != 0));
502 503 504
        r = toku_logger_open(full_dir ? full_dir : env->i->dir, env->i->logger);
        if (full_dir) toku_free(full_dir);
	if (r!=0) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
505
	    toku_ydb_do_error(env, r, "Could not open logger\n");
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
506
	died2:
507
	    toku_logger_close(&env->i->logger);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
508 509
	    goto died1;
	}
510 511 512
    } else {
	r = toku_logger_close(&env->i->logger); // if no logging system, then kill the logger
	assert(r==0);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
513 514
    }

515 516 517 518 519 520 521 522 523 524 525 526
    unused_flags &= ~DB_INIT_MPOOL; // we always init an mpool.
    unused_flags &= ~DB_CREATE;     // we always do DB_CREATE
    unused_flags &= ~DB_INIT_LOCK;  // we check this later (e.g. in db->open)
    unused_flags &= ~DB_RECOVER;

// This is probably correct, but it will be pain...
//    if ((flags & DB_THREAD)==0) {
//	return toku_ydb_do_error(env, EINVAL, "TokuDB requires DB_THREAD");
//    }
    unused_flags &= ~DB_THREAD;

    if (unused_flags!=0) {
527
	return toku_ydb_do_error(env, EINVAL, "Extra flags not understood by tokudb: %u\n", unused_flags);
528 529
    }

530
    r = toku_brt_create_cachetable(&env->i->cachetable, env->i->cachetable_size, ZERO_LSN, env->i->logger);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
531
    if (r!=0) goto died2;
532

533 534 535 536 537 538
    int using_txns = env->i->open_flags & DB_INIT_TXN;
    if (env->i->logger) {
	assert (using_txns);
	toku_logger_set_cachetable(env->i->logger, env->i->cachetable);
	toku_logger_set_remove_finalize_callback(env->i->logger, finalize_file_removal, env->i->ltm);
    }
539

540 541
    DB_TXN *txn=NULL;
    if (using_txns) {
542
        r = toku_txn_begin(env, 0, &txn, 0, 1);
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
        assert(r==0);//For Now
    }
    //TODO: put environment, directory in environment home instead of in data dir
    {
        r = toku_db_create(&env->i->persistent_environment, env, 0);
        assert(r==0);//For Now
        r = db_use_builtin_key_cmp(env->i->persistent_environment);
        assert(r==0);
        r = db_use_builtin_val_cmp(env->i->persistent_environment);
        assert(r==0);
        r = db_open_iname(env->i->persistent_environment, txn, "tokudb.environment", DB_CREATE, mode);
        assert(r==0);//For Now
        //TODO: Insert environment variables into persistent environment
    }
    {
        r = toku_db_create(&env->i->directory, env, 0);
        assert(r==0);//For Now
        r = db_use_builtin_key_cmp(env->i->directory);
        assert(r==0);
        r = db_use_builtin_val_cmp(env->i->directory);
        assert(r==0);
        r = db_open_iname(env->i->directory, txn, "tokudb.directory", DB_CREATE, mode);
        assert(r==0);//For Now
    }
    if (using_txns) {
        r = toku_txn_commit(txn, 0);
        assert(r==0);//For Now
    }
    toku_ydb_unlock();
    r = toku_checkpoint(env->i->cachetable, env->i->logger, NULL, NULL, NULL, NULL, NULL);
    assert(r==0);//For Now
    toku_ydb_lock();
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
575 576
    return 0;
}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
577

578

Rich Prohaska's avatar
Rich Prohaska committed
579
static int toku_env_close(DB_ENV * env, u_int32_t flags) {
580 581 582
    int r = 0;

    // if panicked, or if any open transactions, or any open dbs, then do nothing.
583

584
    if (toku_env_is_panicked(env)) goto panic_and_quit_early;
585
    if (!toku_list_empty(&env->i->open_txns)) {
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
        r = toku_ydb_do_error(env, EINVAL, "Cannot close environment due to open transactions\n");
        goto panic_and_quit_early;
    }
    if (toku_omt_size(env->i->open_dbs) > 0) {
        r = toku_ydb_do_error(env, EINVAL, "Cannot close environment due to open DBs\n");
        goto panic_and_quit_early;
    }
    {
        if (env->i->persistent_environment) {
            r = toku_db_close(env->i->persistent_environment, 0);
            if (r) {
                toku_ydb_do_error(env, r, "Cannot close persistent environment dictionary (DB->close error)\n");
                goto panic_and_quit_early;
            }
        }
        if (env->i->directory) {
            r = toku_db_close(env->i->directory, 0);
            if (r) {
                toku_ydb_do_error(env, r, "Cannot close Directory dictionary (DB->close error)\n");
                goto panic_and_quit_early;
            }
        }
    }
609

610
    if (env->i->cachetable) {
611 612
	toku_ydb_unlock();  // ydb lock must not be held when shutting down minicron
	toku_cachetable_minicron_shutdown(env->i->cachetable);
613
        if (env->i->logger) {
614 615 616
            if ( flags && DB_CLOSE_DONT_TRIM_LOG ) {
                toku_logger_trim_log_files(env->i->logger, FALSE);
            }
617 618 619 620 621 622 623 624 625 626
            r = toku_checkpoint(env->i->cachetable, env->i->logger, NULL, NULL, NULL, NULL, NULL);
            if (r) {
                toku_ydb_do_error(env, r, "Cannot close environment (error during checkpoint)\n");
                goto panic_and_quit_early;
            }
            r = toku_logger_shutdown(env->i->logger); 
            if (r) {
                toku_ydb_do_error(env, r, "Cannot close environment (error during logger shutdown)\n");
                goto panic_and_quit_early;
            }
627
        }
628
	toku_ydb_lock();
629 630 631 632
        r=toku_cachetable_close(&env->i->cachetable);
	if (r) {
	    toku_ydb_do_error(env, r, "Cannot close environment (cachetable close error)\n");
            goto panic_and_quit_early;
633 634 635
	}
    }
    if (env->i->logger) {
636 637 638 639 640
        r=toku_logger_close(&env->i->logger);
	if (r) {
            env->i->logger = NULL;
	    toku_ydb_do_error(env, r, "Cannot close environment (logger close error)\n");
            goto panic_and_quit_early;
641 642 643 644
	}
    }
    // Even if nothing else went wrong, but we were panicked, then raise an error.
    // But if something else went wrong then raise that error (above)
645 646 647 648
    if (toku_env_is_panicked(env))
        goto panic_and_quit_early;
    else
	assert(env->i->panic_string==0);
649

650 651
    if (env->i->data_dir)
        toku_free(env->i->data_dir);
652 653
    if (env->i->lg_dir)
        toku_free(env->i->lg_dir);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
654 655
    if (env->i->tmp_dir)
        toku_free(env->i->tmp_dir);
656 657
    if (env->i->open_dbs)
        toku_omt_destroy(&env->i->open_dbs);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
658
    toku_free(env->i->dir);
Yoni Fogel's avatar
Yoni Fogel committed
659
    toku_ltm_close(env->i->ltm);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
660
    toku_free(env->i);
661
    env->i = NULL;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
662
    toku_free(env);
663
    env = NULL;
664
    ydb_unref();
665 666 667 668 669 670 671 672 673 674 675 676 677
    if ((flags!=0) && !(flags==DB_CLOSE_DONT_TRIM_LOG))
        r = EINVAL;
    return r;

panic_and_quit_early:
    //r is the panic error
    if (toku_env_is_panicked(env)) {
        char *panic_string = env->i->panic_string;
        r = toku_ydb_do_error(env, toku_env_is_panicked(env), "Cannot close environment due to previous error: %s\n", panic_string);
    }
    else
        env->i->is_panicked = r;
    return r;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
678
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
679

Rich Prohaska's avatar
Rich Prohaska committed
680
static int toku_env_log_archive(DB_ENV * env, char **list[], u_int32_t flags) {
681
    return toku_logger_log_archive(env->i->logger, list, flags);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
682
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
683

684
static int toku_env_log_flush(DB_ENV * env, const DB_LSN * lsn __attribute__((__unused__))) {
685
    HANDLE_PANICKED_ENV(env);
686 687
    // We just flush everything.  MySQL uses lsn==0 which means flush everything.  For anyone else using the log, it is correct to flush too much, so we are OK.
    return toku_logger_fsync(env->i->logger);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
688
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
689

Rich Prohaska's avatar
Rich Prohaska committed
690
static int toku_env_set_cachesize(DB_ENV * env, u_int32_t gbytes, u_int32_t bytes, int ncache) {
691
    HANDLE_PANICKED_ENV(env);
Rich Prohaska's avatar
Rich Prohaska committed
692 693
    if (ncache != 1)
        return EINVAL;
Rich Prohaska's avatar
Rich Prohaska committed
694 695 696 697 698
    u_int64_t cs64 = ((u_int64_t) gbytes << 30) + bytes;
    unsigned long cs = cs64;
    if (cs64 > cs)
        return EINVAL;
    env->i->cachetable_size = cs;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
699 700 701
    return 0;
}

702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
static int toku_env_dbremove(DB_ENV * env, DB_TXN *txn, const char *fname, const char *dbname, u_int32_t flags);

static int
locked_env_dbremove(DB_ENV * env, DB_TXN *txn, const char *fname, const char *dbname, u_int32_t flags) {
    toku_multi_operation_client_lock(); //Cannot begin checkpoint
    toku_ydb_lock();
    int r = toku_env_dbremove(env, txn, fname, dbname, flags);
    toku_ydb_unlock();
    toku_multi_operation_client_unlock(); //Can now begin checkpoint
    return r;
}

static int toku_env_dbrename(DB_ENV *env, DB_TXN *txn, const char *fname, const char *dbname, const char *newname, u_int32_t flags);

static int
locked_env_dbrename(DB_ENV *env, DB_TXN *txn, const char *fname, const char *dbname, const char *newname, u_int32_t flags) {
    toku_multi_operation_client_lock(); //Cannot begin checkpoint
    toku_ydb_lock();
    int r = toku_env_dbrename(env, txn, fname, dbname, newname, flags);
    toku_ydb_unlock();
    toku_multi_operation_client_unlock(); //Can now begin checkpoint
    return r;
}


Rich Prohaska's avatar
Rich Prohaska committed
727 728
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR >= 3

Rich Prohaska's avatar
Rich Prohaska committed
729
static int toku_env_get_cachesize(DB_ENV * env, u_int32_t *gbytes, u_int32_t *bytes, int *ncache) {
730
    HANDLE_PANICKED_ENV(env);
Rich Prohaska's avatar
Rich Prohaska committed
731 732 733 734 735 736
    *gbytes = env->i->cachetable_size >> 30;
    *bytes = env->i->cachetable_size & ((1<<30)-1);
    *ncache = 1;
    return 0;
}

Rich Prohaska's avatar
Rich Prohaska committed
737
static int locked_env_get_cachesize(DB_ENV *env, u_int32_t *gbytes, u_int32_t *bytes, int *ncache) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
738
    toku_ydb_lock(); int r = toku_env_get_cachesize(env, gbytes, bytes, ncache); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
739
}
Rich Prohaska's avatar
Rich Prohaska committed
740 741
#endif

Rich Prohaska's avatar
Rich Prohaska committed
742
static int toku_env_set_data_dir(DB_ENV * env, const char *dir) {
743
    HANDLE_PANICKED_ENV(env);
Yoni Fogel's avatar
Yoni Fogel committed
744 745
    int r;
    
Rich Prohaska's avatar
Rich Prohaska committed
746
    if (env_opened(env) || !dir) {
747
	r = toku_ydb_do_error(env, EINVAL, "You cannot set the data dir after opening the env\n");
748
    }
749 750 751 752 753 754 755
    else if (env->i->data_dir)
	r = toku_ydb_do_error(env, EINVAL, "You cannot set the data dir more than once.\n");
    else {
        env->i->data_dir = toku_strdup(dir);
        if (env->i->data_dir==NULL) {
            assert(errno == ENOMEM);
            r = toku_ydb_do_error(env, ENOMEM, "Out of memory\n");
Yoni Fogel's avatar
Yoni Fogel committed
756
        }
757
        else r = 0;
Yoni Fogel's avatar
Yoni Fogel committed
758
    }
759
    return r;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
760
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
761

Rich Prohaska's avatar
Rich Prohaska committed
762
static void toku_env_set_errcall(DB_ENV * env, toku_env_errcall_t errcall) {
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
763
    env->i->errcall = errcall;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
764
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
765

Rich Prohaska's avatar
Rich Prohaska committed
766
static void toku_env_set_errfile(DB_ENV*env, FILE*errfile) {
767 768 769
    env->i->errfile = errfile;
}

Rich Prohaska's avatar
Rich Prohaska committed
770
static void toku_env_set_errpfx(DB_ENV * env, const char *errpfx) {
771
    env->i->errpfx = errpfx;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
772
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
773

Rich Prohaska's avatar
Rich Prohaska committed
774
static int toku_env_set_flags(DB_ENV * env, u_int32_t flags, int onoff) {
775
    HANDLE_PANICKED_ENV(env);
Yoni Fogel's avatar
Yoni Fogel committed
776 777 778 779 780 781

    u_int32_t change = 0;
    if (flags & DB_AUTO_COMMIT) {
        change |=  DB_AUTO_COMMIT;
        flags  &= ~DB_AUTO_COMMIT;
    }
782
    if (flags != 0 && onoff) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
783
	return toku_ydb_do_error(env, EINVAL, "TokuDB does not (yet) support any nonzero ENV flags other than DB_AUTO_COMMIT\n");
784
    }
Yoni Fogel's avatar
Yoni Fogel committed
785 786
    if   (onoff) env->i->open_flags |=  change;
    else         env->i->open_flags &= ~change;
Rich Prohaska's avatar
Rich Prohaska committed
787
    return 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
788
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
789

Rich Prohaska's avatar
Rich Prohaska committed
790
static int toku_env_set_lg_bsize(DB_ENV * env, u_int32_t bsize) {
791
    HANDLE_PANICKED_ENV(env);
792
    return toku_logger_set_lg_bsize(env->i->logger, bsize);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
793
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
794

Rich Prohaska's avatar
Rich Prohaska committed
795
static int toku_env_set_lg_dir(DB_ENV * env, const char *dir) {
796
    HANDLE_PANICKED_ENV(env);
Rich Prohaska's avatar
Rich Prohaska committed
797
    if (env_opened(env)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
798
	return toku_ydb_do_error(env, EINVAL, "Cannot set log dir after opening the env\n");
799
    }
800 801

    if (env->i->lg_dir) toku_free(env->i->lg_dir);
802 803
    if (dir) {
        env->i->lg_dir = toku_strdup(dir);
804
        if (!env->i->lg_dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
805
	    return toku_ydb_do_error(env, ENOMEM, "Out of memory\n");
806
	}
807
    }
808 809
    else env->i->lg_dir = NULL;
    return 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
810
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
811

Rich Prohaska's avatar
Rich Prohaska committed
812
static int toku_env_set_lg_max(DB_ENV * env, u_int32_t lg_max) {
813
    HANDLE_PANICKED_ENV(env);
814 815 816 817 818 819
    return toku_logger_set_lg_max(env->i->logger, lg_max);
}

static int toku_env_get_lg_max(DB_ENV * env, u_int32_t *lg_maxp) {
    HANDLE_PANICKED_ENV(env);
    return toku_logger_get_lg_max(env->i->logger, lg_maxp);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
820
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
821

Rich Prohaska's avatar
Rich Prohaska committed
822
static int toku_env_set_lk_detect(DB_ENV * env, u_int32_t detect) {
823
    HANDLE_PANICKED_ENV(env);
824
    detect=detect;
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
825
    return toku_ydb_do_error(env, EINVAL, "TokuDB does not (yet) support set_lk_detect\n");
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
826
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
827

Yoni Fogel's avatar
Yoni Fogel committed
828
static int toku_env_set_lk_max_locks(DB_ENV *dbenv, u_int32_t max) {
Yoni Fogel's avatar
Yoni Fogel committed
829
    int r = ENOSYS;
Yoni Fogel's avatar
Yoni Fogel committed
830
    HANDLE_PANICKED_ENV(dbenv);
Yoni Fogel's avatar
Yoni Fogel committed
831
    if (env_opened(dbenv))         { return EINVAL; }
Yoni Fogel's avatar
Yoni Fogel committed
832
    r = toku_ltm_set_max_locks_per_db(dbenv->i->ltm, max);
Yoni Fogel's avatar
Yoni Fogel committed
833
    return r;
Yoni Fogel's avatar
Yoni Fogel committed
834 835
}

836
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR <= 4
Rich Prohaska's avatar
Rich Prohaska committed
837
static int toku_env_set_lk_max(DB_ENV * env, u_int32_t lk_max) {
Yoni Fogel's avatar
Yoni Fogel committed
838
    return toku_env_set_lk_max_locks(env, lk_max);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
839
}
Rich Prohaska's avatar
Rich Prohaska committed
840 841

static int locked_env_set_lk_max(DB_ENV * env, u_int32_t lk_max) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
842
    toku_ydb_lock(); int r = toku_env_set_lk_max(env, lk_max); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
843
}
844
#endif
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
845

846 847
static int toku_env_get_lk_max_locks(DB_ENV *dbenv, u_int32_t *lk_maxp) {
    HANDLE_PANICKED_ENV(dbenv);
Yoni Fogel's avatar
Yoni Fogel committed
848
    return toku_ltm_get_max_locks_per_db(dbenv->i->ltm, lk_maxp);
849 850 851
}

static int locked_env_set_lk_max_locks(DB_ENV *dbenv, u_int32_t max) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
852
    toku_ydb_lock(); int r = toku_env_set_lk_max_locks(dbenv, max); toku_ydb_unlock(); return r;
853 854 855
}

static int __attribute__((unused)) locked_env_get_lk_max_locks(DB_ENV *dbenv, u_int32_t *lk_maxp) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
856
    toku_ydb_lock(); int r = toku_env_get_lk_max_locks(dbenv, lk_maxp); toku_ydb_unlock(); return r;
857 858
}

Yoni Fogel's avatar
Yoni Fogel committed
859
//void toku__env_set_noticecall (DB_ENV *env, void (*noticecall)(DB_ENV *, db_notices)) {
Bradley C. Kuszmaul's avatar
Fixup  
Bradley C. Kuszmaul committed
860 861
//    env->i->noticecall = noticecall;
//}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
862

Rich Prohaska's avatar
Rich Prohaska committed
863
static int toku_env_set_tmp_dir(DB_ENV * env, const char *tmp_dir) {
864
    HANDLE_PANICKED_ENV(env);
Rich Prohaska's avatar
Rich Prohaska committed
865
    if (env_opened(env)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
866
	return toku_ydb_do_error(env, EINVAL, "Cannot set the tmp dir after opening an env\n");
867 868
    }
    if (!tmp_dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
869
	return toku_ydb_do_error(env, EINVAL, "Tmp dir bust be non-null\n");
870
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
871 872
    if (env->i->tmp_dir)
        toku_free(env->i->tmp_dir);
Yoni Fogel's avatar
Yoni Fogel committed
873
    env->i->tmp_dir = toku_strdup(tmp_dir);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
874
    return env->i->tmp_dir ? 0 : ENOMEM;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
875
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
876

Rich Prohaska's avatar
Rich Prohaska committed
877
static int toku_env_set_verbose(DB_ENV * env, u_int32_t which, int onoff) {
878 879
    HANDLE_PANICKED_ENV(env);
    which=which; onoff=onoff;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
880
    return 1;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
881
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
882

883 884 885
// For test purposes only.
static void (*checkpoint_callback_f)(void*) = NULL;
static void * checkpoint_callback_extra     = NULL;
886 887
static void (*checkpoint_callback2_f)(void*) = NULL;
static void * checkpoint_callback2_extra     = NULL;
888

889
static int toku_env_txn_checkpoint(DB_ENV * env, u_int32_t kbyte __attribute__((__unused__)), u_int32_t min __attribute__((__unused__)), u_int32_t flags __attribute__((__unused__))) {
890
    char *error_string = NULL;
891 892 893
    int r = toku_checkpoint(env->i->cachetable, env->i->logger, &error_string, 
			    checkpoint_callback_f,  checkpoint_callback_extra,
			    checkpoint_callback2_f, checkpoint_callback2_extra);
894 895 896 897 898 899 900 901 902 903 904
    if (r) {
	env->i->is_panicked = r; // Panicking the whole environment may be overkill, but I'm not sure what else to do.
	env->i->panic_string = error_string;
	if (error_string) {
	    toku_ydb_do_error(env, r, "%s\n", error_string);
	} else {
	    toku_ydb_do_error(env, r, "Checkpoint\n");
	}
	error_string=NULL;
    }
    return r;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
905 906
}

Rich Prohaska's avatar
Rich Prohaska committed
907
static int toku_env_txn_stat(DB_ENV * env, DB_TXN_STAT ** statp, u_int32_t flags) {
908 909
    HANDLE_PANICKED_ENV(env);
    statp=statp;flags=flags;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
910
    return 1;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
911 912
}

913
#if 0
914
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR == 1
915
static void toku_default_errcall(const char *errpfx, char *msg) {
916 917
    fprintf(stderr, "YDB: %s: %s", errpfx, msg);
}
918
#else
919
static void toku_default_errcall(const DB_ENV *env, const char *errpfx, const char *msg) {
920
    env = env;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
921 922
    fprintf(stderr, "YDB: %s: %s", errpfx, msg);
}
923
#endif
924
#endif
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
925

Rich Prohaska's avatar
Rich Prohaska committed
926
static int locked_env_open(DB_ENV * env, const char *home, u_int32_t flags, int mode) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
927
    toku_ydb_lock(); int r = toku_env_open(env, home, flags, mode); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
928 929 930
}

static int locked_env_close(DB_ENV * env, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
931
    toku_ydb_lock(); int r = toku_env_close(env, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
932 933 934
}

static int locked_env_log_archive(DB_ENV * env, char **list[], u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
935
    toku_ydb_lock(); int r = toku_env_log_archive(env, list, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
936 937 938
}

static int locked_env_log_flush(DB_ENV * env, const DB_LSN * lsn) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
939
    toku_ydb_lock(); int r = toku_env_log_flush(env, lsn); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
940 941 942
}

static int locked_env_set_cachesize(DB_ENV *env, u_int32_t gbytes, u_int32_t bytes, int ncache) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
943
    toku_ydb_lock(); int r = toku_env_set_cachesize(env, gbytes, bytes, ncache); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
944 945 946
}

static int locked_env_set_data_dir(DB_ENV * env, const char *dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
947
    toku_ydb_lock(); int r = toku_env_set_data_dir(env, dir); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
948 949 950
}

static int locked_env_set_flags(DB_ENV * env, u_int32_t flags, int onoff) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
951
    toku_ydb_lock(); int r = toku_env_set_flags(env, flags, onoff); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
952 953 954
}

static int locked_env_set_lg_bsize(DB_ENV * env, u_int32_t bsize) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
955
    toku_ydb_lock(); int r = toku_env_set_lg_bsize(env, bsize); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
956 957 958
}

static int locked_env_set_lg_dir(DB_ENV * env, const char *dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
959
    toku_ydb_lock(); int r = toku_env_set_lg_dir(env, dir); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
960 961 962
}

static int locked_env_set_lg_max(DB_ENV * env, u_int32_t lg_max) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
963
    toku_ydb_lock(); int r = toku_env_set_lg_max(env, lg_max); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
964 965
}

966 967 968 969
static int locked_env_get_lg_max(DB_ENV * env, u_int32_t *lg_maxp) {
    toku_ydb_lock(); int r = toku_env_get_lg_max(env, lg_maxp); toku_ydb_unlock(); return r;
}

Rich Prohaska's avatar
Rich Prohaska committed
970
static int locked_env_set_lk_detect(DB_ENV * env, u_int32_t detect) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
971
    toku_ydb_lock(); int r = toku_env_set_lk_detect(env, detect); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
972 973 974
}

static int locked_env_set_tmp_dir(DB_ENV * env, const char *tmp_dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
975
    toku_ydb_lock(); int r = toku_env_set_tmp_dir(env, tmp_dir); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
976 977 978
}

static int locked_env_set_verbose(DB_ENV * env, u_int32_t which, int onoff) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
979
    toku_ydb_lock(); int r = toku_env_set_verbose(env, which, onoff); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
980 981 982
}

static int locked_env_txn_stat(DB_ENV * env, DB_TXN_STAT ** statp, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
983
    toku_ydb_lock(); int r = toku_env_txn_stat(env, statp, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
984 985
}

986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
static int
env_checkpointing_set_period(DB_ENV * env, u_int32_t seconds) {
    HANDLE_PANICKED_ENV(env);
    int r;
    if (!env_opened(env)) r = EINVAL;
    else
        r = toku_set_checkpoint_period(env->i->cachetable, seconds);
    return r;
}

static int
locked_env_checkpointing_set_period(DB_ENV * env, u_int32_t seconds) {
    toku_ydb_lock(); int r = env_checkpointing_set_period(env, seconds); toku_ydb_unlock(); return r;
}

static int
env_checkpointing_get_period(DB_ENV * env, u_int32_t *seconds) {
    HANDLE_PANICKED_ENV(env);
    int r = 0;
    if (!env_opened(env)) r = EINVAL;
    else 
        *seconds = toku_get_checkpoint_period(env->i->cachetable);
    return r;
}

static int
locked_env_checkpointing_get_period(DB_ENV * env, u_int32_t *seconds) {
    toku_ydb_lock(); int r = env_checkpointing_get_period(env, seconds); toku_ydb_unlock(); return r;
}

1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
static int
env_checkpointing_postpone(DB_ENV * env) {
    HANDLE_PANICKED_ENV(env);
    int r = 0;
    if (!env_opened(env)) r = EINVAL;
    else toku_checkpoint_safe_client_lock();
    return r;
}

static int
env_checkpointing_resume(DB_ENV * env) {
    HANDLE_PANICKED_ENV(env);
    int r = 0;
    if (!env_opened(env)) r = EINVAL;
    else toku_checkpoint_safe_client_unlock();
    return r;
}

static int
env_checkpointing_begin_atomic_operation(DB_ENV * env) {
    HANDLE_PANICKED_ENV(env);
    int r = 0;
    if (!env_opened(env)) r = EINVAL;
    else toku_multi_operation_client_lock();
    return r;
}

static int
env_checkpointing_end_atomic_operation(DB_ENV * env) {
    HANDLE_PANICKED_ENV(env);
    int r = 0;
    if (!env_opened(env)) r = EINVAL;
    else toku_multi_operation_client_unlock();
    return r;
}

static int
env_set_default_dup_compare(DB_ENV * env, int (*dup_compare) (DB *, const DBT *, const DBT *)) {
    HANDLE_PANICKED_ENV(env);
    int r = 0;
    if (env_opened(env)) r = EINVAL;
    else {
        env->i->dup_compare = dup_compare;
    }
    return r;
}

static int
locked_env_set_default_dup_compare(DB_ENV * env, int (*dup_compare) (DB *, const DBT *, const DBT *)) {
    toku_ydb_lock();
    int r = env_set_default_dup_compare(env, dup_compare);
    toku_ydb_unlock();
    return r;
}

static int
env_set_default_bt_compare(DB_ENV * env, int (*bt_compare) (DB *, const DBT *, const DBT *)) {
    HANDLE_PANICKED_ENV(env);
    int r = 0;
    if (env_opened(env)) r = EINVAL;
    else {
        env->i->bt_compare = bt_compare;
    }
    return r;
}

static int
locked_env_set_default_bt_compare(DB_ENV * env, int (*bt_compare) (DB *, const DBT *, const DBT *)) {
    toku_ydb_lock();
    int r = env_set_default_bt_compare(env, bt_compare);
    toku_ydb_unlock();
    return r;
}

1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
static void
format_time(const time_t *timer, char *buf) {
    ctime_r(timer, buf);
    size_t len = strlen(buf);
    assert(len < 26);
    char end;

    assert(len>=1);
    end = buf[len-1];
    while (end == '\n' || end == '\r') {
        buf[len-1] = '\0';
        len--;
        assert(len>=1);
        end = buf[len-1];
    }
}
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117

// Do not take ydb lock around or in this function.  
// If the engine is blocked because some thread is holding the ydb lock, this function
// can help diagnose the problem.
// This function only collects information, and it does not matter if something gets garbled
// because of a race condition.  
static int
env_get_engine_status(DB_ENV * env, ENGINE_STATUS * engstat) {
    HANDLE_PANICKED_ENV(env);
    int r = 0;
    if (!env_opened(env)) r = EINVAL;
    else {
1118 1119
	time_t now = time(NULL);
        format_time(&now, engstat->now);
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140

	engstat->logger_lock_ctr = toku_logger_get_lock_ctr();

	{
	    SCHEDULE_STATUS_S schedstat;
	    toku_ydb_lock_get_status(&schedstat);
	    engstat->ydb_lock_ctr = schedstat.ydb_lock_ctr;                        /* how many times has ydb lock been taken/released */ 
	    engstat->max_possible_sleep = schedstat.max_possible_sleep;            /* max possible sleep time for ydb lock scheduling (constant) */ 
	    engstat->processor_freq_mhz = schedstat.processor_freq_mhz;            /* clock frequency in MHz */
	    engstat->max_requested_sleep = schedstat.max_requested_sleep;          /* max sleep time requested, can be larger than max possible */ 
	    engstat->times_max_sleep_used = schedstat.times_max_sleep_used;        /* number of times the max_possible_sleep was used to sleep */ 
	    engstat->total_sleepers = schedstat.total_sleepers;                    /* total number of times a client slept for ydb lock scheduling */ 
	    engstat->total_sleep_time = schedstat.total_sleep_time;                /* total time spent sleeping for ydb lock scheduling */ 
	    engstat->max_waiters = schedstat.max_waiters;                          /* max number of simultaneous client threads kept waiting for ydb lock  */ 
	    engstat->total_waiters = schedstat.total_waiters;                      /* total number of times a client thread waited for ydb lock  */ 
	    engstat->total_clients = schedstat.total_clients;                      /* total number of separate client threads that use ydb lock  */ 
	    engstat->time_ydb_lock_held_unavailable = schedstat.time_ydb_lock_held_unavailable;  /* number of times a thread migrated and theld is unavailable */ 
	    engstat->total_time_ydb_lock_held = schedstat.total_time_ydb_lock_held;/* total time client threads held the ydb lock  */ 
	    engstat->max_time_ydb_lock_held = schedstat.max_time_ydb_lock_held;    /* max time client threads held the ydb lock  */ 
	}

1141
	env_checkpointing_get_period(env, &(engstat->checkpoint_period));  // do not take ydb lock (take minicron lock, but that's a very ephemeral low-level lock)
1142 1143 1144 1145 1146 1147 1148 1149
	{
            CHECKPOINT_STATUS_S cpstat;
            toku_checkpoint_get_status(&cpstat);
            engstat->checkpoint_footprint = cpstat.footprint;
	    format_time(&cpstat.time_last_checkpoint_begin_complete, engstat->checkpoint_time_begin_complete);
	    format_time(&cpstat.time_last_checkpoint_begin,          engstat->checkpoint_time_begin);
	    format_time(&cpstat.time_last_checkpoint_end,            engstat->checkpoint_time_end);
	}
1150 1151 1152
	{
	    CACHETABLE_STATUS_S ctstat;
	    toku_cachetable_get_status(env->i->cachetable, &ctstat);
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
	    engstat->cachetable_lock_taken    = ctstat.lock_taken;
	    engstat->cachetable_lock_released = ctstat.lock_released;
	    engstat->cachetable_hit           = ctstat.hit;
	    engstat->cachetable_miss          = ctstat.miss;
	    engstat->cachetable_misstime      = ctstat.misstime;
	    engstat->cachetable_waittime      = ctstat.waittime;
	    engstat->cachetable_wait_reading  = ctstat.wait_reading;
	    engstat->cachetable_wait_writing  = ctstat.wait_writing;
	    engstat->puts                     = ctstat.puts;
	    engstat->prefetches               = ctstat.prefetches;
	    engstat->maybe_get_and_pins       = ctstat.maybe_get_and_pins;
	    engstat->maybe_get_and_pin_hits   = ctstat.maybe_get_and_pin_hits;
	    engstat->cachetable_size_current  = ctstat.size_current;
	    engstat->cachetable_size_limit    = ctstat.size_limit;
	    engstat->cachetable_size_writing  = ctstat.size_writing;
	    engstat->get_and_pin_footprint    = ctstat.get_and_pin_footprint;
1169
	}
1170 1171 1172 1173 1174 1175
	{
	    toku_ltm* ltm = env->i->ltm;
	    r = toku_ltm_get_max_locks(ltm, &(engstat->range_locks_max));     assert(r==0);
	    r = toku_ltm_get_max_locks_per_db(ltm, &(engstat->range_locks_max_per_db));  assert(r==0);
	    r = toku_ltm_get_curr_locks(ltm, &(engstat->range_locks_curr));   assert(r==0);
	}
1176 1177 1178 1179 1180 1181 1182 1183
	{
	    engstat->inserts            = num_inserts;
	    engstat->deletes            = num_deletes;
	    engstat->commits            = num_commits;
	    engstat->aborts             = num_aborts;
	    engstat->point_queries      = num_point_queries;
	    engstat->sequential_queries = num_sequential_queries;
	}
1184 1185 1186 1187
    }
    return r;
}

1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
// Fill buff with text description of engine status up to bufsiz bytes.
// Intended for use by test programs that do not have the handlerton available.
static int
env_get_engine_status_text(DB_ENV * env, char * buff, int bufsiz) {
    ENGINE_STATUS engstat;
    int r = env_get_engine_status(env, &engstat);    
    int n = 0;  // number of characters printed so far

    n += snprintf(buff + n, bufsiz - n, "now                              %s \n", engstat.now);
    n += snprintf(buff + n, bufsiz - n, "ydb_lock_ctr                     %"PRIu64"\n", engstat.ydb_lock_ctr);
    n += snprintf(buff + n, bufsiz - n, "max_possible_sleep               %"PRIu64"\n", engstat.max_possible_sleep);
    n += snprintf(buff + n, bufsiz - n, "processor_freq_mhz               %"PRIu64"\n", engstat.processor_freq_mhz);
    n += snprintf(buff + n, bufsiz - n, "max_requested_sleep              %"PRIu64"\n", engstat.max_requested_sleep);
    n += snprintf(buff + n, bufsiz - n, "times_max_sleep_used             %"PRIu64"\n", engstat.times_max_sleep_used);
    n += snprintf(buff + n, bufsiz - n, "total_sleepers                   %"PRIu64"\n", engstat.total_sleepers);
    n += snprintf(buff + n, bufsiz - n, "total_sleep_time                 %"PRIu64"\n", engstat.total_sleep_time);
    n += snprintf(buff + n, bufsiz - n, "max_waiters                      %"PRIu64"\n", engstat.max_waiters);
    n += snprintf(buff + n, bufsiz - n, "total_waiters                    %"PRIu64"\n", engstat.total_waiters);
    n += snprintf(buff + n, bufsiz - n, "total_clients                    %"PRIu64"\n", engstat.total_clients);
    n += snprintf(buff + n, bufsiz - n, "time_ydb_lock_held_unavailable   %"PRIu64"\n", engstat.time_ydb_lock_held_unavailable);
    n += snprintf(buff + n, bufsiz - n, "max_time_ydb_lock_held           %"PRIu64"\n", engstat.max_time_ydb_lock_held);
    n += snprintf(buff + n, bufsiz - n, "total_time_ydb_lock_held         %"PRIu64"\n", engstat.total_time_ydb_lock_held);
    n += snprintf(buff + n, bufsiz - n, "logger_lock_ctr                  %"PRIu64"\n", engstat.logger_lock_ctr);
    n += snprintf(buff + n, bufsiz - n, "checkpoint_period                %d \n", engstat.checkpoint_period);
    n += snprintf(buff + n, bufsiz - n, "checkpoint_footprint             %d \n", engstat.checkpoint_footprint);
    n += snprintf(buff + n, bufsiz - n, "checkpoint_time_begin            %s \n", engstat.checkpoint_time_begin);
    n += snprintf(buff + n, bufsiz - n, "checkpoint_time_begin_complete   %s \n", engstat.checkpoint_time_begin_complete);
    n += snprintf(buff + n, bufsiz - n, "checkpoint_time_end              %s \n", engstat.checkpoint_time_end);
    n += snprintf(buff + n, bufsiz - n, "cachetable_lock_taken            %"PRIu64"\n", engstat.cachetable_lock_taken);
    n += snprintf(buff + n, bufsiz - n, "cachetable_lock_released         %"PRIu64"\n", engstat.cachetable_lock_released);
    n += snprintf(buff + n, bufsiz - n, "cachetable_hit                   %"PRIu64"\n", engstat.cachetable_hit);
    n += snprintf(buff + n, bufsiz - n, "cachetable_miss                  %"PRIu64"\n", engstat.cachetable_miss);
    n += snprintf(buff + n, bufsiz - n, "cachetable_misstime              %"PRIu64"\n", engstat.cachetable_misstime);
    n += snprintf(buff + n, bufsiz - n, "cachetable_waittime              %"PRIu64"\n", engstat.cachetable_waittime);
    n += snprintf(buff + n, bufsiz - n, "cachetable_wait_reading          %"PRIu64"\n", engstat.cachetable_wait_reading);
    n += snprintf(buff + n, bufsiz - n, "cachetable_wait_writing          %"PRIu64"\n", engstat.cachetable_wait_writing);
    n += snprintf(buff + n, bufsiz - n, "puts                             %"PRIu64"\n", engstat.puts);
    n += snprintf(buff + n, bufsiz - n, "prefetches                       %"PRIu64"\n", engstat.prefetches);
    n += snprintf(buff + n, bufsiz - n, "maybe_get_and_pins               %"PRIu64"\n", engstat.maybe_get_and_pins);
    n += snprintf(buff + n, bufsiz - n, "maybe_get_and_pin_hits           %"PRIu64"\n", engstat.maybe_get_and_pin_hits);
    n += snprintf(buff + n, bufsiz - n, "cachetable_size_current          %"PRId64"\n", engstat.cachetable_size_current);
    n += snprintf(buff + n, bufsiz - n, "cachetable_size_limit            %"PRId64"\n", engstat.cachetable_size_limit);
    n += snprintf(buff + n, bufsiz - n, "cachetable_size_writing          %"PRId64"\n", engstat.cachetable_size_writing);
    n += snprintf(buff + n, bufsiz - n, "get_and_pin_footprint            %"PRId64"\n", engstat.get_and_pin_footprint);
    n += snprintf(buff + n, bufsiz - n, "range_locks_max                  %d \n", engstat.range_locks_max);
    n += snprintf(buff + n, bufsiz - n, "range_locks_max_per_db           %d \n", engstat.range_locks_max_per_db);
    n += snprintf(buff + n, bufsiz - n, "range_locks_curr                 %d \n", engstat.range_locks_curr);
    n += snprintf(buff + n, bufsiz - n, "inserts                          %"PRIu64"\n", engstat.inserts);
    n += snprintf(buff + n, bufsiz - n, "deletes                          %"PRIu64"\n", engstat.deletes);
    n += snprintf(buff + n, bufsiz - n, "commits                          %"PRIu64"\n", engstat.commits);
    n += snprintf(buff + n, bufsiz - n, "aborts                           %"PRIu64"\n", engstat.aborts);
    n += snprintf(buff + n, bufsiz - n, "point_queries                    %"PRIu64"\n", engstat.point_queries);
    n += snprintf(buff + n, bufsiz - n, "sequential_queries               %"PRIu64"\n", engstat.sequential_queries);

    //    n += snprintf(buff + n, bufsiz - n, "             %"PRIu64"\n", engstat.);

    if (n > bufsiz) {
	char * errmsg = "BUFFER TOO SMALL\n";
	int len = strlen(errmsg) + 1;
	(void) snprintf(buff + (bufsiz - 1) - len, len, errmsg);
    }

    return r;
}

Rich Prohaska's avatar
Rich Prohaska committed
1253 1254
static int locked_txn_begin(DB_ENV * env, DB_TXN * stxn, DB_TXN ** txn, u_int32_t flags);

Yoni Fogel's avatar
Yoni Fogel committed
1255 1256 1257 1258 1259 1260
static int toku_db_lt_panic(DB* db, int r);

static toku_dbt_cmp toku_db_get_compare_fun(DB* db);

static toku_dbt_cmp toku_db_get_dup_compare(DB* db);

Rich Prohaska's avatar
Rich Prohaska committed
1261
static int toku_env_create(DB_ENV ** envp, u_int32_t flags) {
Yoni Fogel's avatar
Yoni Fogel committed
1262 1263 1264 1265 1266 1267
    int r = ENOSYS;
    DB_ENV* result = NULL;

    if (flags!=0)    { r = EINVAL; goto cleanup; }
    MALLOC(result);
    if (result == 0) { r = ENOMEM; goto cleanup; }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1268
    memset(result, 0, sizeof *result);
1269
    result->err = (void (*)(const DB_ENV * env, int error, const char *fmt, ...)) toku_locked_env_err;
1270 1271 1272 1273 1274 1275 1276
#define SENV(name) result->name = locked_env_ ## name
    SENV(dbremove);
    SENV(dbrename);
    SENV(set_default_bt_compare);
    SENV(set_default_dup_compare);
    SENV(checkpointing_set_period);
    SENV(checkpointing_get_period);
1277 1278 1279 1280
    result->checkpointing_postpone = env_checkpointing_postpone;
    result->checkpointing_resume = env_checkpointing_resume;
    result->checkpointing_begin_atomic_operation = env_checkpointing_begin_atomic_operation;
    result->checkpointing_end_atomic_operation = env_checkpointing_end_atomic_operation;
1281
    result->get_engine_status = env_get_engine_status;
1282
    result->get_engine_status_text = env_get_engine_status_text;
1283 1284 1285
    result->get_iname = env_get_iname;
    SENV(open);
    SENV(close);
1286
    result->txn_checkpoint = toku_env_txn_checkpoint;
1287
    SENV(log_flush);
Rich Prohaska's avatar
Rich Prohaska committed
1288 1289 1290
    result->set_errcall = toku_env_set_errcall;
    result->set_errfile = toku_env_set_errfile;
    result->set_errpfx = toku_env_set_errpfx;
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
    //SENV(set_noticecall);
    SENV(set_flags);
    SENV(set_data_dir);
    SENV(set_tmp_dir);
    SENV(set_verbose);
    SENV(set_lg_bsize);
    SENV(set_lg_dir);
    SENV(set_lg_max);
    SENV(get_lg_max);
    SENV(set_lk_max_locks);
    SENV(get_lk_max_locks);
    SENV(set_cachesize);
Rich Prohaska's avatar
Rich Prohaska committed
1303
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR >= 3
1304
    SENV(get_cachesize);
Rich Prohaska's avatar
Rich Prohaska committed
1305
#endif
1306
    SENV(set_lk_detect);
1307
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR <= 4
1308
    SENV(set_lk_max);
1309
#endif
1310 1311
    SENV(log_archive);
    SENV(txn_stat);
Rich Prohaska's avatar
Rich Prohaska committed
1312
    result->txn_begin = locked_txn_begin;
1313
#undef SENV
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1314

1315
    MALLOC(result->i);
Yoni Fogel's avatar
Yoni Fogel committed
1316
    if (result->i == 0) { r = ENOMEM; goto cleanup; }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1317
    memset(result->i, 0, sizeof *result->i);
1318
    env_init_open_txn(result);
Yoni Fogel's avatar
Yoni Fogel committed
1319 1320

    r = toku_ltm_create(&result->i->ltm, __toku_env_default_max_locks,
Yoni Fogel's avatar
Yoni Fogel committed
1321 1322 1323
                         toku_db_lt_panic, 
                         toku_db_get_compare_fun, toku_db_get_dup_compare, 
                         toku_malloc, toku_free, toku_realloc);
Yoni Fogel's avatar
Yoni Fogel committed
1324
    if (r!=0) { goto cleanup; }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1325

1326
    {
Yoni Fogel's avatar
Yoni Fogel committed
1327 1328
	r = toku_logger_create(&result->i->logger);
	if (r!=0) { goto cleanup; }
1329 1330
	assert(result->i->logger);
    }
1331 1332 1333 1334 1335
    {
        r = toku_omt_create(&result->i->open_dbs);
        if (r!=0) goto cleanup;
        assert(result->i->open_dbs);
    }
1336

1337
    ydb_add_ref();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1338
    *envp = result;
Yoni Fogel's avatar
Yoni Fogel committed
1339 1340 1341 1342 1343 1344 1345 1346
    r = 0;
cleanup:
    if (r!=0) {
        if (result) {
            if (result->i) {
                if (result->i->ltm) {
                    toku_ltm_close(result->i->ltm);
                }
1347 1348
                if (result->i->open_dbs)
                    toku_omt_destroy(&result->i->open_dbs);
Yoni Fogel's avatar
Yoni Fogel committed
1349 1350 1351 1352 1353 1354
                toku_free(result->i);
            }
            toku_free(result);
        }
    }
    return r;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1355 1356
}

1357
int DB_ENV_CREATE_FUN (DB_ENV ** envp, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1358
    toku_ydb_lock(); int r = toku_env_create(envp, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
1359 1360
}

Yoni Fogel's avatar
Yoni Fogel committed
1361
static int toku_txn_release_locks(DB_TXN* txn) {
Yoni Fogel's avatar
Yoni Fogel committed
1362
    assert(txn);
1363
    toku_lth* lth = db_txn_struct_i(txn)->lth;
Yoni Fogel's avatar
Yoni Fogel committed
1364

Yoni Fogel's avatar
Yoni Fogel committed
1365 1366
    int r = ENOSYS;
    int first_error = 0;
Yoni Fogel's avatar
Yoni Fogel committed
1367 1368 1369 1370
    if (lth) {
        toku_lth_start_scan(lth);
        toku_lock_tree* next = toku_lth_next(lth);
        while (next) {
1371
            r = toku_lt_unlock(next, toku_txn_get_txnid(db_txn_struct_i(txn)->tokutxn));
Yoni Fogel's avatar
Yoni Fogel committed
1372 1373 1374 1375 1376
            if (!first_error && r!=0) { first_error = r; }
            if (r == 0) {
                r = toku_lt_remove_ref(next);
                if (!first_error && r!=0) { first_error = r; }
            }
Yoni Fogel's avatar
Yoni Fogel committed
1377 1378 1379
            next = toku_lth_next(lth);
        }
        toku_lth_close(lth);
1380
        db_txn_struct_i(txn)->lth = NULL;
Yoni Fogel's avatar
Yoni Fogel committed
1381
    }
Yoni Fogel's avatar
Yoni Fogel committed
1382 1383
    r = first_error;

Yoni Fogel's avatar
Yoni Fogel committed
1384
    return r;
Yoni Fogel's avatar
Yoni Fogel committed
1385 1386
}

1387 1388
// Yield the lock so someone else can work, and then reacquire the lock.
// Useful while processing commit or rollback logs, to allow others to access the system.
1389
static void ydb_yield (voidfp f, void *UU(v)) {
1390
    toku_ydb_unlock(); 
1391
    if (f) f();
1392 1393 1394
    toku_ydb_lock();
}

Rich Prohaska's avatar
Rich Prohaska committed
1395
static int toku_txn_commit(DB_TXN * txn, u_int32_t flags) {
1396
    if (!txn) return EINVAL;
1397
    HANDLE_PANICKED_ENV(txn->mgrp);
Yoni Fogel's avatar
Yoni Fogel committed
1398
    //Recursively kill off children
1399 1400
    if (db_txn_struct_i(txn)->child) {
        //commit of child sets the child pointer to NULL
1401
        int r_child = toku_txn_commit(db_txn_struct_i(txn)->child, flags);
1402 1403 1404 1405
        if (r_child !=0 && !toku_env_is_panicked(txn->mgrp)) {
            txn->mgrp->i->is_panicked = r_child;
            txn->mgrp->i->panic_string = toku_strdup("Recursive child commit failed during parent commit.\n");
        }
Yoni Fogel's avatar
Yoni Fogel committed
1406 1407
        //In a panicked env, the child may not be removed from the list.
        HANDLE_PANICKED_ENV(txn->mgrp);
Yoni Fogel's avatar
Yoni Fogel committed
1408
    }
1409
    assert(!db_txn_struct_i(txn)->child);
Yoni Fogel's avatar
Yoni Fogel committed
1410 1411
    //Remove from parent
    if (txn->parent) {
1412 1413
        assert(db_txn_struct_i(txn->parent)->child == txn);
        db_txn_struct_i(txn->parent)->child=NULL;
Yoni Fogel's avatar
Yoni Fogel committed
1414
    }
1415
    env_remove_open_txn(txn->mgrp, txn);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1416
    //toku_ydb_notef("flags=%d\n", flags);
1417
    int nosync = (flags & DB_TXN_NOSYNC)!=0 || (db_txn_struct_i(txn)->flags&DB_TXN_NOSYNC);
1418
    flags &= ~DB_TXN_NOSYNC;
Yoni Fogel's avatar
Yoni Fogel committed
1419 1420

    int r;
1421
    if (flags!=0)
1422 1423
	// frees the tokutxn
	// Calls ydb_yield(NULL) occasionally
1424 1425
        //r = toku_logger_abort(db_txn_struct_i(txn)->tokutxn, ydb_yield, NULL);
        r = toku_txn_abort_txn(db_txn_struct_i(txn)->tokutxn, ydb_yield, NULL);
Yoni Fogel's avatar
Yoni Fogel committed
1426
    else
1427 1428
	// frees the tokutxn
	// Calls ydb_yield(NULL) occasionally
1429 1430
        //r = toku_logger_commit(db_txn_struct_i(txn)->tokutxn, nosync, ydb_yield, NULL);
        r = toku_txn_commit_txn(db_txn_struct_i(txn)->tokutxn, nosync, ydb_yield, NULL);
1431

1432 1433 1434 1435 1436 1437 1438 1439
    if (r!=0 && !toku_env_is_panicked(txn->mgrp)) {
        txn->mgrp->i->is_panicked = r;
        txn->mgrp->i->panic_string = toku_strdup("Error during commit.\n");
    }
    //If panicked, we're done.
    HANDLE_PANICKED_ENV(txn->mgrp);
    assert(r==0);

1440
    // Close the logger after releasing the locks
1441
    r = toku_txn_release_locks(txn);
1442 1443
    //toku_logger_txn_close(db_txn_struct_i(txn)->tokutxn);
    toku_txn_close_txn(db_txn_struct_i(txn)->tokutxn);
1444
    // the toxutxn is freed, and we must free the rest. */
Yoni Fogel's avatar
Yoni Fogel committed
1445

1446 1447 1448
    //Promote list to parent (dbs that must close before abort)
    if (txn->parent) {
        //Combine lists.
1449 1450 1451
        while (!toku_list_empty(&db_txn_struct_i(txn)->dbs_that_must_close_before_abort)) {
            struct toku_list *list = toku_list_pop(&db_txn_struct_i(txn)->dbs_that_must_close_before_abort);
            toku_list_push(&db_txn_struct_i(txn->parent)->dbs_that_must_close_before_abort, list);
1452 1453 1454 1455
        }
    }
    else {
        //Empty the list
1456 1457
        while (!toku_list_empty(&db_txn_struct_i(txn)->dbs_that_must_close_before_abort)) {
            toku_list_pop(&db_txn_struct_i(txn)->dbs_that_must_close_before_abort);
1458 1459 1460
        }
    }

1461
    // The txn is no good after the commit even if the commit fails, so free it up.
1462 1463 1464
#if !TOKUDB_NATIVE_H
    toku_free(db_txn_struct_i(txn));
#endif
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1465
    toku_free(txn);
1466
    num_commits++;      // accountability
Yoni Fogel's avatar
Yoni Fogel committed
1467
    if (flags!=0) return EINVAL;
1468
    return r;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1469 1470
}

Rich Prohaska's avatar
Rich Prohaska committed
1471
static u_int32_t toku_txn_id(DB_TXN * txn) {
1472
    HANDLE_PANICKED_ENV(txn->mgrp);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1473
    toku_ydb_barf();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1474
    abort();
Rich Prohaska's avatar
Rich Prohaska committed
1475
    return -1;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1476 1477
}

1478
static int toku_txn_abort(DB_TXN * txn) {
1479
    HANDLE_PANICKED_ENV(txn->mgrp);
1480
    //Recursively kill off children (abort or commit are both correct, commit is cheaper)
1481 1482 1483
    if (db_txn_struct_i(txn)->child) {
        //commit of child sets the child pointer to NULL
        int r_child = toku_txn_commit(db_txn_struct_i(txn)->child, DB_TXN_NOSYNC);
1484 1485 1486 1487
        if (r_child !=0 && !toku_env_is_panicked(txn->mgrp)) {
            txn->mgrp->i->is_panicked = r_child;
            txn->mgrp->i->panic_string = toku_strdup("Recursive child commit failed during parent abort.\n");
        }
Yoni Fogel's avatar
Yoni Fogel committed
1488 1489
        //In a panicked env, the child may not be removed from the list.
        HANDLE_PANICKED_ENV(txn->mgrp);
Yoni Fogel's avatar
Yoni Fogel committed
1490
    }
1491
    assert(!db_txn_struct_i(txn)->child);
Yoni Fogel's avatar
Yoni Fogel committed
1492 1493
    //Remove from parent
    if (txn->parent) {
1494 1495
        assert(db_txn_struct_i(txn->parent)->child == txn);
        db_txn_struct_i(txn->parent)->child=NULL;
Yoni Fogel's avatar
Yoni Fogel committed
1496
    }
1497
    env_remove_open_txn(txn->mgrp, txn);
1498 1499

    //All dbs that must close before abort, must now be closed
1500
    assert(toku_list_empty(&db_txn_struct_i(txn)->dbs_that_must_close_before_abort));
1501

1502 1503
    //int r = toku_logger_abort(db_txn_struct_i(txn)->tokutxn, ydb_yield, NULL);
    int r = toku_txn_abort_txn(db_txn_struct_i(txn)->tokutxn, ydb_yield, NULL);
1504 1505 1506 1507 1508 1509 1510
    if (r!=0 && !toku_env_is_panicked(txn->mgrp)) {
        txn->mgrp->i->is_panicked = r;
        txn->mgrp->i->panic_string = toku_strdup("Error during abort.\n");
    }
    HANDLE_PANICKED_ENV(txn->mgrp);
    assert(r==0);
    r = toku_txn_release_locks(txn);
1511 1512
    //toku_logger_txn_close(db_txn_struct_i(txn)->tokutxn);
    toku_txn_close_txn(db_txn_struct_i(txn)->tokutxn);
Yoni Fogel's avatar
Yoni Fogel committed
1513

1514 1515 1516
#if !TOKUDB_NATIVE_H
    toku_free(db_txn_struct_i(txn));
#endif
1517
    toku_free(txn);
1518
    num_aborts++;    // accountability
1519
    return r;
1520 1521
}

Rich Prohaska's avatar
Rich Prohaska committed
1522
static int locked_txn_begin(DB_ENV *env, DB_TXN * stxn, DB_TXN ** txn, u_int32_t flags) {
1523
    toku_ydb_lock(); int r = toku_txn_begin(env, stxn, txn, flags, 0); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
1524 1525 1526
}

static u_int32_t locked_txn_id(DB_TXN *txn) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1527
    toku_ydb_lock(); u_int32_t r = toku_txn_id(txn); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
1528 1529
}

1530 1531
static int toku_txn_stat (DB_TXN *txn, struct txn_stat **txn_stat) {
    XMALLOC(*txn_stat);
1532
    return toku_logger_txn_rolltmp_raw_count(db_txn_struct_i(txn)->tokutxn, &(*txn_stat)->rolltmp_raw_count);
1533 1534 1535 1536 1537 1538
}

static int locked_txn_stat (DB_TXN *txn, struct txn_stat **txn_stat) {
    toku_ydb_lock(); u_int32_t r = toku_txn_stat(txn, txn_stat); toku_ydb_unlock(); return r;
}

Rich Prohaska's avatar
Rich Prohaska committed
1539
static int locked_txn_commit(DB_TXN *txn, u_int32_t flags) {
1540
    toku_multi_operation_client_lock(); //Cannot checkpoint during a commit.
1541
    toku_ydb_lock(); int r = toku_txn_commit(txn, flags); toku_ydb_unlock();
1542
    toku_multi_operation_client_unlock(); //Cannot checkpoint during a commit.
1543
    return r;
Rich Prohaska's avatar
Rich Prohaska committed
1544 1545 1546
}

static int locked_txn_abort(DB_TXN *txn) {
1547
    toku_multi_operation_client_lock(); //Cannot checkpoint during an abort.
1548
    toku_ydb_lock(); int r = toku_txn_abort(txn); toku_ydb_unlock();
1549
    toku_multi_operation_client_unlock(); //Cannot checkpoint during an abort.
1550
    return r;
Rich Prohaska's avatar
Rich Prohaska committed
1551 1552
}

1553
static int toku_txn_begin(DB_ENV *env, DB_TXN * stxn, DB_TXN ** txn, u_int32_t flags, int internal) {
1554
    HANDLE_PANICKED_ENV(env);
1555
    HANDLE_ILLEGAL_WORKING_PARENT_TXN(env, stxn); //Cannot create child while child already exists.
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1556 1557
    if (!toku_logger_is_open(env->i->logger)) return toku_ydb_do_error(env, EINVAL, "Environment does not have logging enabled\n");
    if (!(env->i->open_flags & DB_INIT_TXN))  return toku_ydb_do_error(env, EINVAL, "Environment does not have transactions enabled\n");
1558 1559
    u_int32_t txn_flags = 0;
    txn_flags |= DB_TXN_NOWAIT; //We do not support blocking locks.
1560 1561 1562 1563
    if (internal && stxn) {
        uint32_t parent_isolation_flags = db_txn_struct_i(stxn)->flags & (DB_READ_UNCOMMITTED); //TODO: #2126 DB_READ_COMMITTED should be added here once supported.
        flags |= parent_isolation_flags;
    }
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
    if (flags&DB_READ_UNCOMMITTED) {
        txn_flags |=  DB_READ_UNCOMMITTED;
        flags     &= ~DB_READ_UNCOMMITTED;
    }
    if (flags&DB_TXN_NOWAIT) {
        txn_flags |=  DB_TXN_NOWAIT;
        flags     &= ~DB_TXN_NOWAIT;
    }
    if (flags&DB_TXN_NOSYNC) {
        txn_flags |=  DB_TXN_NOSYNC;
        flags     &= ~DB_TXN_NOSYNC;
    }
    if (flags!=0) return toku_ydb_do_error(env, EINVAL, "Invalid flags passed to DB_ENV->txn_begin\n");
1577 1578 1579 1580 1581 1582 1583
    if (stxn) {
        //Require child to have same isolation level as parent.
        uint32_t parent_isolation_flags = db_txn_struct_i(stxn)->flags & (DB_READ_UNCOMMITTED); //TODO: #2126 DB_READ_COMMITTED should be added here once supported.
        uint32_t child_isolation_flags  = txn_flags                    & (DB_READ_UNCOMMITTED); //TODO: #2126 DB_READ_COMMITTED should be added here once supported.
        if (parent_isolation_flags != child_isolation_flags)
            return toku_ydb_do_error(env, EINVAL, "DB_ENV->txn_begin: Child transaction isolation level must match parent's isolation level.\n");
    }
1584

1585
    DB_TXN *MALLOC(result);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1586 1587 1588
    if (result == 0)
        return ENOMEM;
    memset(result, 0, sizeof *result);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1589
    //toku_ydb_notef("parent=%p flags=0x%x\n", stxn, flags);
1590
    result->mgrp = env;
Rich Prohaska's avatar
Rich Prohaska committed
1591 1592 1593
    result->abort = locked_txn_abort;
    result->commit = locked_txn_commit;
    result->id = locked_txn_id;
Yoni Fogel's avatar
Yoni Fogel committed
1594
    result->parent = stxn;
1595
    result->txn_stat = locked_txn_stat;
1596 1597 1598
#if !TOKUDB_NATIVE_H
    MALLOC(db_txn_struct_i(result));
    if (!db_txn_struct_i(result)) {
Yoni Fogel's avatar
Yoni Fogel committed
1599 1600 1601
        toku_free(result);
        return ENOMEM;
    }
1602 1603 1604
#endif
    memset(db_txn_struct_i(result), 0, sizeof *db_txn_struct_i(result));
    db_txn_struct_i(result)->flags = txn_flags;
1605
    toku_list_init(&db_txn_struct_i(result)->dbs_that_must_close_before_abort);
Yoni Fogel's avatar
Yoni Fogel committed
1606 1607

    int r;
Yoni Fogel's avatar
Yoni Fogel committed
1608
    if (env->i->open_flags & DB_INIT_LOCK && !stxn) {
1609
        r = toku_lth_create(&db_txn_struct_i(result)->lth,
Yoni Fogel's avatar
Yoni Fogel committed
1610 1611
                            toku_malloc, toku_free, toku_realloc);
        if (r!=0) {
1612 1613 1614
#if !TOKUDB_NATIVE_H
            toku_free(db_txn_struct_i(result));
#endif
Yoni Fogel's avatar
Yoni Fogel committed
1615 1616 1617
            toku_free(result);
            return r;
        }
Yoni Fogel's avatar
Yoni Fogel committed
1618 1619
    }
    
1620 1621
    //r = toku_logger_txn_begin(stxn ? db_txn_struct_i(stxn)->tokutxn : 0, &db_txn_struct_i(result)->tokutxn, env->i->logger);
    r = toku_txn_begin_txn(stxn ? db_txn_struct_i(stxn)->tokutxn : 0, &db_txn_struct_i(result)->tokutxn, env->i->logger);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1622 1623
    if (r != 0)
        return r;
Yoni Fogel's avatar
Yoni Fogel committed
1624 1625
    //Add to the list of children for the parent.
    if (result->parent) {
1626 1627
        assert(!db_txn_struct_i(result->parent)->child);
        db_txn_struct_i(result->parent)->child = result;
Yoni Fogel's avatar
Yoni Fogel committed
1628
    }
1629
    env_add_open_txn(env, result);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1630 1631 1632 1633
    *txn = result;
    return 0;
}

Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
1634
#if 0
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1635 1636
int txn_commit(DB_TXN * txn, u_int32_t flags) {
    fprintf(stderr, "%s:%d\n", __FILE__, __LINE__);
1637
    return toku_logger_log_commit(db_txn_struct_i(txn)->tokutxn);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1638
}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
1639
#endif
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1640

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1641
int log_compare(const DB_LSN * a, const DB_LSN * b) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1642
    toku_ydb_lock();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1643
    fprintf(stderr, "%s:%d log_compare(%p,%p)\n", __FILE__, __LINE__, a, b);
1644
    assert(0);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1645
    toku_ydb_unlock();
1646
    return 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1647 1648
}

1649 1650
static int
db_close_before_brt(DB *db, u_int32_t UU(flags)) {
1651
    char *error_string = 0;
1652
    int r1 = toku_close_brt(db->i->brt, &error_string);
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664
    if (r1) {
	db->dbenv->i->is_panicked = r1; // Panicking the whole environment may be overkill, but I'm not sure what else to do.
	db->dbenv->i->panic_string = error_string;
	if (error_string) {
	    toku_ydb_do_error(db->dbenv, r1, "%s\n", error_string);
	} else {
	    toku_ydb_do_error(db->dbenv, r1, "Closing file\n");
	}
	error_string=0;
    }
    assert(error_string==0);
    int r2 = 0;
1665
    if (db->i->db_id) { toku_db_id_remove_ref(&db->i->db_id); }
Yoni Fogel's avatar
Yoni Fogel committed
1666
    if (db->i->lt) {
1667 1668 1669 1670 1671
        r2 = toku_lt_remove_ref(db->i->lt);
	if (r2) {
	    db->dbenv->i->is_panicked = r2; // Panicking the whole environment may be overkill, but I'm not sure what else to do.
	    db->dbenv->i->panic_string = 0;
	}
Yoni Fogel's avatar
Yoni Fogel committed
1672
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1673
    // printf("%s:%d %d=__toku_db_close(%p)\n", __FILE__, __LINE__, r, db);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1674 1675
    // Even if panicked, let's close as much as we can.
    int is_panicked = toku_env_is_panicked(db->dbenv); 
1676 1677
    toku_sdbt_cleanup(&db->i->skey);
    toku_sdbt_cleanup(&db->i->sval);
1678
    if (db->i->dname) toku_free(db->i->dname);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
1679 1680
    toku_free(db->i);
    toku_free(db);
1681
    ydb_unref();
1682 1683 1684 1685
    if (r1) return r1;
    if (r2) return r2;
    if (is_panicked) return EINVAL;
    return 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1686 1687
}

1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756
// return 0 if v and dbv refer to same db (including same dname)
// return <0 if v is earlier in omt than dbv
// return >0 if v is later in omt than dbv
static int
find_db_by_db (OMTVALUE v, void *dbv) {
    DB *db = v;            // DB* that is stored in the omt
    DB *dbfind = dbv;      // extra, to be compared to v
    int cmp;
    cmp = strcmp(db->i->dname, dbfind->i->dname);
    if (cmp != 0) return cmp;
    if (db < dbfind) return -1;
    if (db > dbfind) return 1;
    return 0;
}

// Tell env that there is a new db handle (with non-unique dname in db->i-dname)
static void
env_note_db_opened(DB_ENV *env, DB *db) {
    assert(db->i->dname);  // internal (non-user) dictionary has no dname
    int r;
    OMTVALUE dbv;
    uint32_t idx;
    r = toku_omt_find_zero(env->i->open_dbs, find_db_by_db, db, &dbv, &idx, NULL);
    assert(r==DB_NOTFOUND); //Must not already be there.
    r = toku_omt_insert_at(env->i->open_dbs, db, idx);
    assert(r==0);
}

static void
env_note_db_closed(DB_ENV *env, DB *db) {
    assert(db->i->dname);
    int r;
    OMTVALUE dbv;
    uint32_t idx;
    r = toku_omt_find_zero(env->i->open_dbs, find_db_by_db, db, &dbv, &idx, NULL);
    assert(r==0); //Must already be there.
    assert((DB*)dbv == db);
    r = toku_omt_delete_at(env->i->open_dbs, idx);
    assert(r==0);
}

static int
find_db_by_dname (OMTVALUE v, void *dnamev) {
    DB *db = v;
    const char *dname     = db->i->dname;
    const char *dnamefind = dnamev;
    return strcmp(dname, dnamefind);
}

// return true if there is any db open with the given dname
static BOOL
env_is_db_with_dname_open(DB_ENV *env, const char *dname) {
    int r;
    BOOL rval;
    OMTVALUE dbv;
    uint32_t idx;
    r = toku_omt_find_zero(env->i->open_dbs, find_db_by_dname, (void*)dname, &dbv, &idx, NULL);
    if (r==0) {
        DB *db = dbv;
        assert(strcmp(dname, db->i->dname) == 0);
        rval = TRUE;
    }
    else {
        assert(r==DB_NOTFOUND);
        rval = FALSE;
    }
    return rval;
}

1757
static int toku_db_close(DB * db, u_int32_t flags) {
1758 1759 1760
    if (db_opened(db) && db->i->dname) // internal (non-user) dictionary has no dname
        env_note_db_closed(db->dbenv, db);  // tell env that this db is no longer in use by the user of this api (user-closed, may still be in use by fractal tree internals)
    //Remove from transaction's list of 'must close' if necessary.
1761 1762
    if (!toku_list_empty(&db->i->dbs_that_must_close_before_abort))
        toku_list_remove(&db->i->dbs_that_must_close_before_abort);
1763

1764 1765 1766 1767 1768
    int r = toku_brt_db_delay_closed(db->i->brt, db, db_close_before_brt, flags);
    return r;
}


1769 1770 1771
//Get the main portion of a cursor flag (excluding the bitwise or'd components).
static int get_main_cursor_flag(u_int32_t flags) {
    return flags & DB_OPFLAGS_MASK;
Yoni Fogel's avatar
Yoni Fogel committed
1772 1773
}

1774 1775
static int get_nonmain_cursor_flags(u_int32_t flags) {
    return flags & ~(DB_OPFLAGS_MASK);
1776 1777
}

1778
static inline BOOL toku_c_uninitialized(DBC* c) {
1779
    return toku_brt_cursor_uninitialized(dbc_struct_i(c)->c);
Yoni Fogel's avatar
Yoni Fogel committed
1780
}            
Yoni Fogel's avatar
Yoni Fogel committed
1781

1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792
typedef struct query_context_wrapped_t {
    DBT               *key;
    DBT               *val;
    struct simple_dbt *skey;
    struct simple_dbt *sval;
} *QUERY_CONTEXT_WRAPPED, QUERY_CONTEXT_WRAPPED_S;

static inline void
query_context_wrapped_init(QUERY_CONTEXT_WRAPPED context, DBC *c, DBT *key, DBT *val) {
    context->key  = key;
    context->val  = val;
1793 1794
    context->skey = dbc_struct_i(c)->skey;
    context->sval = dbc_struct_i(c)->sval;
1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810
}

static int
c_get_wrapper_callback(DBT const *key, DBT const *val, void *extra) {
    QUERY_CONTEXT_WRAPPED context = extra;
    int r;
              r = toku_dbt_set(key->size, key->data, context->key, context->skey);
    if (r==0) r = toku_dbt_set(val->size, val->data, context->val, context->sval);
    return r;
}

static int toku_c_get_current_unconditional(DBC* c, u_int32_t flags, DBT* key, DBT* val) {
    int r;
    QUERY_CONTEXT_WRAPPED_S context; 
    query_context_wrapped_init(&context, c, key, val);
    r = toku_c_getf_current_binding(c, flags, c_get_wrapper_callback, &context);
Yoni Fogel's avatar
Yoni Fogel committed
1811 1812 1813 1814 1815 1816 1817 1818 1819 1820
    return r;
}

static inline void toku_swap_flag(u_int32_t* flag, u_int32_t* get_flag,
                                  u_int32_t new_flag) {
    *flag    -= *get_flag;
    *get_flag =  new_flag;
    *flag    += *get_flag;
}

Yoni Fogel's avatar
Yoni Fogel committed
1821 1822 1823 1824 1825 1826 1827
/*
    Used for partial implementation of nested transactions.
    Work is done by children as normal, but all locking is done by the
    root of the nested txn tree.
    This may hold extra locks, and will not work as expected when
    a node has two non-completed txns at any time.
*/
1828
static inline DB_TXN* toku_txn_ancestor(DB_TXN* txn) {
Yoni Fogel's avatar
Yoni Fogel committed
1829
    while (txn && txn->parent) txn = txn->parent;
Yoni Fogel's avatar
Yoni Fogel committed
1830

Yoni Fogel's avatar
Yoni Fogel committed
1831 1832 1833
    return txn;
}

Yoni Fogel's avatar
Yoni Fogel committed
1834 1835
static int toku_txn_add_lt(DB_TXN* txn, toku_lock_tree* lt);

Yoni Fogel's avatar
Yoni Fogel committed
1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846
/* c_get has many subfunctions with lots of parameters
 * this structure exists to simplify it. */
typedef struct {
    DBC*        c;                  // The cursor
    DB*         db;                 // db the cursor is iterating over
    DB_TXN*     txn_anc;            // The (root) ancestor of the transaction
    TXNID       id_anc;
    DBT         tmp_key;            // Temporary key to protect out param
    DBT         tmp_val;            // Temporary val to protect out param
    u_int32_t   flag;               // The c_get flag
    u_int32_t   op;                 // The operation portion of the c_get flag
Yoni Fogel's avatar
Yoni Fogel committed
1847
    u_int32_t   lock_flags;         // The prelock flags.
Yoni Fogel's avatar
Yoni Fogel committed
1848 1849 1850 1851 1852 1853 1854 1855 1856 1857
    BOOL        cursor_is_write;    // Whether op can change position of cursor
    BOOL        key_is_read;        
    BOOL        key_is_write;
    BOOL        val_is_read;
    BOOL        val_is_write;
    BOOL        duplicates;
    BOOL        tmp_key_malloced;
    BOOL        tmp_val_malloced;
} C_GET_VARS;

1858 1859

static inline u_int32_t get_prelocked_flags(u_int32_t flags, DB_TXN* txn, DB* db) {
1860 1861
    u_int32_t lock_flags = flags & (DB_PRELOCKED | DB_PRELOCKED_WRITE);

1862 1863 1864 1865 1866
    // for internal (non-user) dictionary, do not set DB_PRELOCK
    if (db->i->dname) {
	//DB_READ_UNCOMMITTED transactions 'own' all read locks for user-data dictionaries.
	if (txn && db_txn_struct_i(txn)->flags&DB_READ_UNCOMMITTED) lock_flags |= DB_PRELOCKED;
    }
1867
    return lock_flags;
Yoni Fogel's avatar
Yoni Fogel committed
1868 1869
}

1870 1871 1872 1873
//Return true for NODUP database, false for DUPSORT
static BOOL
db_is_nodup(DB *db) {
    unsigned int brtflags;
Yoni Fogel's avatar
Yoni Fogel committed
1874

1875 1876
    int r = toku_brt_get_flags(db->i->brt, &brtflags);
    assert(r==0);
1877
    BOOL rval = (BOOL)(!(brtflags&TOKU_DB_DUPSORT));
1878
    return rval;
Yoni Fogel's avatar
Yoni Fogel committed
1879
}
Yoni Fogel's avatar
Yoni Fogel committed
1880

1881 1882 1883 1884
static BOOL
c_db_is_nodup(DBC *c) {
    BOOL rval = db_is_nodup(c->dbp);
    return rval;
Yoni Fogel's avatar
Yoni Fogel committed
1885 1886
}

1887 1888
static int
toku_c_get(DBC* c, DBT* key, DBT* val, u_int32_t flag) {
1889 1890 1891
    //This function exists for legacy (test compatibility) purposes/parity with bdb.
    HANDLE_PANICKED_DB(c->dbp);
    HANDLE_CURSOR_ILLEGAL_WORKING_PARENT_TXN(c);
Yoni Fogel's avatar
Yoni Fogel committed
1892

1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904
    u_int32_t main_flag       = get_main_cursor_flag(flag);
    u_int32_t remaining_flags = get_nonmain_cursor_flags(flag);
    int r;
    QUERY_CONTEXT_WRAPPED_S context;
    //Passing in NULL for a key or val means that it is NOT an output.
    //    Both key and val are output:
    //        query_context_wrapped_init(&context, c, key,  val);
    //    Val is output, key is not:
    //            query_context_wrapped_init(&context, c, NULL, val);
    //    Neither key nor val are output:
    //	    query_context_wrapped_init(&context, c, NULL, NULL); // Used for DB_GET_BOTH
    switch (main_flag) {
Yoni Fogel's avatar
Yoni Fogel committed
1905
        case (DB_FIRST):
1906 1907
            query_context_wrapped_init(&context, c, key,  val);
            r = toku_c_getf_first(c, remaining_flags, c_get_wrapper_callback, &context);
Yoni Fogel's avatar
Yoni Fogel committed
1908
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1909
        case (DB_LAST):
1910 1911
            query_context_wrapped_init(&context, c, key,  val);
            r = toku_c_getf_last(c, remaining_flags, c_get_wrapper_callback, &context);
Yoni Fogel's avatar
Yoni Fogel committed
1912
            break;
1913 1914 1915
        case (DB_NEXT):
            query_context_wrapped_init(&context, c, key,  val);
            r = toku_c_getf_next(c, remaining_flags, c_get_wrapper_callback, &context);
Yoni Fogel's avatar
Yoni Fogel committed
1916
            break;
1917 1918 1919
        case (DB_NEXT_DUP):
            query_context_wrapped_init(&context, c, key,  val);
            r = toku_c_getf_next_dup(c, remaining_flags, c_get_wrapper_callback, &context);
Yoni Fogel's avatar
Yoni Fogel committed
1920
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1921
        case (DB_NEXT_NODUP):
1922 1923
            query_context_wrapped_init(&context, c, key,  val);
            r = toku_c_getf_next_nodup(c, remaining_flags, c_get_wrapper_callback, &context);
Yoni Fogel's avatar
Yoni Fogel committed
1924 1925
            break;
        case (DB_PREV):
1926 1927
            query_context_wrapped_init(&context, c, key,  val);
            r = toku_c_getf_prev(c, remaining_flags, c_get_wrapper_callback, &context);
Yoni Fogel's avatar
Yoni Fogel committed
1928 1929
            break;
#ifdef DB_PREV_DUP
Yoni Fogel's avatar
Yoni Fogel committed
1930
        case (DB_PREV_DUP):
1931 1932
            query_context_wrapped_init(&context, c, key,  val);
            r = toku_c_getf_prev_dup(c, remaining_flags, c_get_wrapper_callback, &context);
Yoni Fogel's avatar
Yoni Fogel committed
1933 1934
            break;
#endif
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955
        case (DB_PREV_NODUP):
            query_context_wrapped_init(&context, c, key,  val);
            r = toku_c_getf_prev_nodup(c, remaining_flags, c_get_wrapper_callback, &context);
            break;
        case (DB_CURRENT):
            query_context_wrapped_init(&context, c, key,  val);
            r = toku_c_getf_current(c, remaining_flags, c_get_wrapper_callback, &context);
            break;
        case (DB_CURRENT_BINDING):
            query_context_wrapped_init(&context, c, key,  val);
            r = toku_c_getf_current_binding(c, remaining_flags, c_get_wrapper_callback, &context);
            break;

        case (DB_SET):
            query_context_wrapped_init(&context, c, NULL, val);
            r = toku_c_getf_set(c, remaining_flags, key, c_get_wrapper_callback, &context);
            break;
        case (DB_SET_RANGE):
            query_context_wrapped_init(&context, c, key,  val);
            r = toku_c_getf_set_range(c, remaining_flags, key, c_get_wrapper_callback, &context);
            break;
1956 1957 1958 1959
        case (DB_SET_RANGE_REVERSE):
            query_context_wrapped_init(&context, c, key,  val);
            r = toku_c_getf_set_range_reverse(c, remaining_flags, key, c_get_wrapper_callback, &context);
            break;
1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970
        case (DB_GET_BOTH):
            query_context_wrapped_init(&context, c, NULL, NULL);
            r = toku_c_getf_get_both(c, remaining_flags, key, val, c_get_wrapper_callback, &context);
            break;
        case (DB_GET_BOTH_RANGE):
            //For a nodup database, DB_GET_BOTH_RANGE is an alias for DB_GET_BOTH.
            //DB_GET_BOTH(_RANGE) require different contexts (see case(DB_GET_BOTH)).
            if (c_db_is_nodup(c)) query_context_wrapped_init(&context, c, NULL, NULL);
            else                  query_context_wrapped_init(&context, c, NULL, val);
            r = toku_c_getf_get_both_range(c, remaining_flags, key, val, c_get_wrapper_callback, &context);
            break;
1971 1972 1973 1974 1975 1976 1977
        case (DB_GET_BOTH_RANGE_REVERSE):
            //For a nodup database, DB_GET_BOTH_RANGE_REVERSE is an alias for DB_GET_BOTH.
            //DB_GET_BOTH(_RANGE_REVERSE) require different contexts (see case(DB_GET_BOTH)).
            if (c_db_is_nodup(c)) query_context_wrapped_init(&context, c, NULL, NULL);
            else                  query_context_wrapped_init(&context, c, NULL, val);
            r = toku_c_getf_get_both_range_reverse(c, remaining_flags, key, val, c_get_wrapper_callback, &context);
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1978
        default:
Yoni Fogel's avatar
Yoni Fogel committed
1979
            r = EINVAL;
1980
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1981
    }
Yoni Fogel's avatar
Yoni Fogel committed
1982
    return r;
Yoni Fogel's avatar
Yoni Fogel committed
1983 1984
}

1985 1986
static int locked_c_getf_first(DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra) {
    toku_ydb_lock();  int r = toku_c_getf_first(c, flag, f, extra); toku_ydb_unlock(); return r;
Yoni Fogel's avatar
Yoni Fogel committed
1987 1988
}

1989 1990 1991
static int locked_c_getf_last(DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra) {
    toku_ydb_lock();  int r = toku_c_getf_last(c, flag, f, extra); toku_ydb_unlock(); return r;
}
Yoni Fogel's avatar
Yoni Fogel committed
1992

1993 1994
static int locked_c_getf_next(DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra) {
    toku_ydb_lock();  int r = toku_c_getf_next(c, flag, f, extra); toku_ydb_unlock(); return r;
Yoni Fogel's avatar
Yoni Fogel committed
1995 1996
}

1997 1998 1999
static int locked_c_getf_next_nodup(DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra) {
    toku_ydb_lock();  int r = toku_c_getf_next_nodup(c, flag, f, extra); toku_ydb_unlock(); return r;
}
Yoni Fogel's avatar
Yoni Fogel committed
2000

2001 2002 2003
static int locked_c_getf_next_dup(DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra) {
    toku_ydb_lock();  int r = toku_c_getf_next_dup(c, flag, f, extra); toku_ydb_unlock(); return r;
}
Yoni Fogel's avatar
Yoni Fogel committed
2004

2005 2006
static int locked_c_getf_prev(DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra) {
    toku_ydb_lock();  int r = toku_c_getf_prev(c, flag, f, extra); toku_ydb_unlock(); return r;
Yoni Fogel's avatar
Yoni Fogel committed
2007 2008
}

2009 2010 2011
static int locked_c_getf_prev_nodup(DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra) {
    toku_ydb_lock();  int r = toku_c_getf_prev_nodup(c, flag, f, extra); toku_ydb_unlock(); return r;
}
Yoni Fogel's avatar
Yoni Fogel committed
2012

2013 2014 2015
static int locked_c_getf_prev_dup(DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra) {
    toku_ydb_lock();  int r = toku_c_getf_prev_dup(c, flag, f, extra); toku_ydb_unlock(); return r;
}
Yoni Fogel's avatar
Yoni Fogel committed
2016

2017 2018
static int locked_c_getf_current(DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra) {
    toku_ydb_lock();  int r = toku_c_getf_current(c, flag, f, extra); toku_ydb_unlock(); return r;
Yoni Fogel's avatar
Yoni Fogel committed
2019 2020
}

2021 2022 2023
static int locked_c_getf_current_binding(DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra) {
    toku_ydb_lock();  int r = toku_c_getf_current_binding(c, flag, f, extra); toku_ydb_unlock(); return r;
}
Yoni Fogel's avatar
Yoni Fogel committed
2024

2025 2026 2027
static int locked_c_getf_set(DBC *c, u_int32_t flag, DBT * key, YDB_CALLBACK_FUNCTION f, void *extra) {
    toku_ydb_lock();  int r = toku_c_getf_set(c, flag, key, f, extra); toku_ydb_unlock(); return r;
}
Yoni Fogel's avatar
Yoni Fogel committed
2028

2029 2030 2031
static int locked_c_getf_set_range(DBC *c, u_int32_t flag, DBT * key, YDB_CALLBACK_FUNCTION f, void *extra) {
    toku_ydb_lock();  int r = toku_c_getf_set_range(c, flag, key, f, extra); toku_ydb_unlock(); return r;
}
Yoni Fogel's avatar
Yoni Fogel committed
2032

2033 2034 2035 2036
static int locked_c_getf_set_range_reverse(DBC *c, u_int32_t flag, DBT * key, YDB_CALLBACK_FUNCTION f, void *extra) {
    toku_ydb_lock();  int r = toku_c_getf_set_range_reverse(c, flag, key, f, extra); toku_ydb_unlock(); return r;
}

2037 2038 2039
static int locked_c_getf_get_both(DBC *c, u_int32_t flag, DBT * key, DBT *val, YDB_CALLBACK_FUNCTION f, void *extra) {
    toku_ydb_lock();  int r = toku_c_getf_get_both(c, flag, key, val, f, extra); toku_ydb_unlock(); return r;
}
2040

2041 2042 2043
static int locked_c_getf_get_both_range(DBC *c, u_int32_t flag, DBT * key, DBT *val, YDB_CALLBACK_FUNCTION f, void *extra) {
    toku_ydb_lock();  int r = toku_c_getf_get_both_range(c, flag, key, val, f, extra); toku_ydb_unlock(); return r;
}
Yoni Fogel's avatar
Yoni Fogel committed
2044

2045 2046 2047 2048
static int locked_c_getf_get_both_range_reverse(DBC *c, u_int32_t flag, DBT * key, DBT *val, YDB_CALLBACK_FUNCTION f, void *extra) {
    toku_ydb_lock();  int r = toku_c_getf_get_both_range_reverse(c, flag, key, val, f, extra); toku_ydb_unlock(); return r;
}

2049 2050 2051 2052 2053 2054 2055 2056 2057 2058
typedef struct {
    BOOL            is_read_lock;
    DB_TXN         *txn;
    DB             *db;
    toku_lock_tree *lt;
    DBT const      *left_key;
    DBT const      *left_val;
    DBT const      *right_key;
    DBT const      *right_val;
} *RANGE_LOCK_REQUEST, RANGE_LOCK_REQUEST_S;
Yoni Fogel's avatar
Yoni Fogel committed
2059

2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076
static void
range_lock_request_init(RANGE_LOCK_REQUEST request,
                        BOOL       is_read_lock,
                        DB_TXN    *txn,
                        DB        *db,
                        DBT const *left_key,
                        DBT const *left_val,
                        DBT const *right_key,
                        DBT const *right_val) {
    request->is_read_lock = is_read_lock;
    request->txn = txn;
    request->db = db;
    request->lt = db->i->lt;
    request->left_key = left_key;
    request->left_val = left_val;
    request->right_key = right_key;
    request->right_val = right_val;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2077 2078
}

Yoni Fogel's avatar
Yoni Fogel committed
2079

2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090
static void
read_lock_request_init(RANGE_LOCK_REQUEST request,
                       DB_TXN    *txn,
                       DB        *db,
                       DBT const *left_key,
                       DBT const *left_val,
                       DBT const *right_key,
                       DBT const *right_val) {
    range_lock_request_init(request, TRUE, txn, db,
                            left_key,  left_val,
                            right_key, right_val);
Yoni Fogel's avatar
Yoni Fogel committed
2091 2092
}

2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112
static void
write_lock_request_init(RANGE_LOCK_REQUEST request,
                        DB_TXN    *txn,
                        DB        *db,
                        DBT const *left_key,
                        DBT const *left_val,
                        DBT const *right_key,
                        DBT const *right_val) {
    range_lock_request_init(request, FALSE, txn, db,
                            left_key,  left_val,
                            right_key, right_val);
}

static int
grab_range_lock(RANGE_LOCK_REQUEST request) {
    int r;
    //TODO: (Multithreading) Grab lock protecting lock tree
    DB_TXN *txn_anc = toku_txn_ancestor(request->txn);
    r = toku_txn_add_lt(txn_anc, request->lt);
    if (r==0) {
2113
        TXNID txn_anc_id = toku_txn_get_txnid(db_txn_struct_i(txn_anc)->tokutxn);
2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124
        if (request->is_read_lock)
            r = toku_lt_acquire_range_read_lock(request->lt, request->db, txn_anc_id,
                                                request->left_key,  request->left_val,
                                                request->right_key, request->right_val);
        else 
            r = toku_lt_acquire_range_write_lock(request->lt, request->db, txn_anc_id,
                                                 request->left_key,  request->left_val,
                                                 request->right_key, request->right_val);
    }
    //TODO: (Multithreading) Release lock protecting lock tree
    return r;
Yoni Fogel's avatar
Yoni Fogel committed
2125 2126
}

2127 2128
//This is the user level callback function given to ydb layer functions like
//toku_c_getf_first
Yoni Fogel's avatar
Yoni Fogel committed
2129

2130 2131 2132 2133
typedef struct __toku_is_write_op {
    BOOL is_write_op;
} WRITE_OP;

2134 2135 2136 2137 2138 2139
typedef struct query_context_base_t {
    BRT_CURSOR  c;
    DB_TXN     *txn;
    DB         *db;
    void       *f_extra;
    int         r_user_callback;
2140 2141
    BOOL        do_locking;
    BOOL        is_write_op;
2142
} *QUERY_CONTEXT_BASE, QUERY_CONTEXT_BASE_S;
2143

2144 2145 2146 2147
typedef struct query_context_t {
    QUERY_CONTEXT_BASE_S  base;
    YDB_CALLBACK_FUNCTION f;
} *QUERY_CONTEXT, QUERY_CONTEXT_S;
Yoni Fogel's avatar
Yoni Fogel committed
2148

2149 2150 2151 2152 2153 2154
typedef struct query_context_with_input_t {
    QUERY_CONTEXT_BASE_S  base;
    YDB_CALLBACK_FUNCTION f;
    DBT                  *input_key;
    DBT                  *input_val;
} *QUERY_CONTEXT_WITH_INPUT, QUERY_CONTEXT_WITH_INPUT_S;
Yoni Fogel's avatar
Yoni Fogel committed
2155

2156 2157

static void
2158
query_context_base_init(QUERY_CONTEXT_BASE context, DBC *c, u_int32_t flag, WRITE_OP is_write_op, void *extra) {
2159 2160
    context->c       = dbc_struct_i(c)->c;
    context->txn     = dbc_struct_i(c)->txn;
2161 2162
    context->db      = c->dbp;
    context->f_extra = extra;
2163
    context->is_write_op = is_write_op.is_write_op;
2164
    u_int32_t lock_flags = get_prelocked_flags(flag, dbc_struct_i(c)->txn, c->dbp);
Yoni Fogel's avatar
Yoni Fogel committed
2165
    flag &= ~lock_flags;
2166
    if (context->is_write_op) lock_flags &= DB_PRELOCKED_WRITE; // Only care about whether already locked for write
Yoni Fogel's avatar
Yoni Fogel committed
2167
    assert(flag==0);
2168
    context->do_locking = (BOOL)(context->db->i->lt!=NULL && !lock_flags);
2169
    context->r_user_callback = 0;
Yoni Fogel's avatar
Yoni Fogel committed
2170 2171
}

2172 2173
static void
query_context_init(QUERY_CONTEXT context, DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra) {
2174 2175 2176 2177 2178 2179 2180 2181 2182
    WRITE_OP is_write = {FALSE};
    query_context_base_init(&context->base, c, flag, is_write, extra);
    context->f = f;
}

static void
query_context_init_write_op(QUERY_CONTEXT context, DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra) {
    WRITE_OP is_write = {TRUE};
    query_context_base_init(&context->base, c, flag, is_write, extra);
2183 2184
    context->f = f;
}
Yoni Fogel's avatar
Yoni Fogel committed
2185

2186 2187
static void
query_context_with_input_init(QUERY_CONTEXT_WITH_INPUT context, DBC *c, u_int32_t flag, DBT *key, DBT *val, YDB_CALLBACK_FUNCTION f, void *extra) {
2188 2189
    WRITE_OP is_write = {FALSE};
    query_context_base_init(&context->base, c, flag, is_write, extra);
2190 2191 2192
    context->f         = f;
    context->input_key = key;
    context->input_val = val;
2193 2194
}

2195 2196 2197 2198 2199
static int c_del_callback(DBT const *key, DBT const *val, void *extra);

//Delete whatever the cursor is pointing at.
static int
toku_c_del(DBC * c, u_int32_t flags) {
2200
    HANDLE_PANICKED_DB(c->dbp);
2201
    HANDLE_CURSOR_ILLEGAL_WORKING_PARENT_TXN(c);
2202

2203 2204 2205 2206
    u_int32_t unchecked_flags = flags;
    //DB_DELETE_ANY means delete regardless of whether it exists in the db.
    u_int32_t flag_for_brt = flags&DB_DELETE_ANY;
    unchecked_flags &= ~flag_for_brt;
2207
    u_int32_t lock_flags = get_prelocked_flags(flags, dbc_struct_i(c)->txn, c->dbp);
2208
    unchecked_flags &= ~lock_flags;
2209
    BOOL do_locking = (BOOL)(c->dbp->i->lt && !(lock_flags&DB_PRELOCKED_WRITE));
2210

2211 2212 2213 2214 2215
    int r = 0;
    if (unchecked_flags!=0) r = EINVAL;
    else {
        if (do_locking) {
            QUERY_CONTEXT_S context;
2216
            query_context_init_write_op(&context, c, lock_flags, NULL, NULL);
2217 2218 2219 2220 2221
            //We do not need a read lock, we must already have it.
            r = toku_c_getf_current_binding(c, DB_PRELOCKED, c_del_callback, &context);
        }
        if (r==0) {
            //Do the actual delete.
2222 2223
            TOKUTXN txn = dbc_struct_i(c)->txn ? db_txn_struct_i(dbc_struct_i(c)->txn)->tokutxn : 0;
            r = toku_brt_cursor_delete(dbc_struct_i(c)->c, flag_for_brt, txn);
2224 2225
        }
    }
2226 2227
    return r;
}
2228

2229 2230 2231 2232 2233
//result is the result of the query (i.e. 0 means found, DB_NOTFOUND, etc..)
static int
c_del_callback(DBT const *key, DBT const *val, void *extra) {
    QUERY_CONTEXT_WITH_INPUT super_context = extra;
    QUERY_CONTEXT_BASE       context       = &super_context->base;
Yoni Fogel's avatar
Yoni Fogel committed
2234

2235
    int r;
Yoni Fogel's avatar
Yoni Fogel committed
2236

2237
    assert(context->do_locking);
2238
    assert(context->is_write_op);
2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249
    assert(key!=NULL);
    assert(val!=NULL);
    //Lock:
    //  left(key,val)==right(key,val) == (key, val);
    RANGE_LOCK_REQUEST_S request;
    write_lock_request_init(&request, context->txn, context->db,
                            key, val,
                            key, val);
    r = grab_range_lock(&request);

    //Give brt-layer an error (if any) to return from toku_c_getf_current_binding
Yoni Fogel's avatar
Yoni Fogel committed
2250 2251 2252
    return r;
}

2253 2254 2255 2256 2257
static int c_getf_first_callback(ITEMLEN keylen, bytevec key, ITEMLEN vallen, bytevec val, void *extra);

static int
toku_c_getf_first(DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra) {
    HANDLE_PANICKED_DB(c->dbp);
2258
    HANDLE_CURSOR_ILLEGAL_WORKING_PARENT_TXN(c);
2259
    num_point_queries++;   // accountability
2260 2261 2262
    QUERY_CONTEXT_S context; //Describes the context of this query.
    query_context_init(&context, c, flag, f, extra); 
    //toku_brt_cursor_first will call c_getf_first_callback(..., context) (if query is successful)
2263
    int r = toku_brt_cursor_first(dbc_struct_i(c)->c, c_getf_first_callback, &context);
2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311
    if (r == TOKUDB_USER_CALLBACK_ERROR) r = context.base.r_user_callback;
    return r;
}

//result is the result of the query (i.e. 0 means found, DB_NOTFOUND, etc..)
static int
c_getf_first_callback(ITEMLEN keylen, bytevec key, ITEMLEN vallen, bytevec val, void *extra) {
    QUERY_CONTEXT      super_context = extra;
    QUERY_CONTEXT_BASE context       = &super_context->base;

    int r;

    DBT found_key;
    DBT found_val;
    toku_fill_dbt(&found_key, key, keylen);
    toku_fill_dbt(&found_val, val, vallen);

    if (context->do_locking) {
        RANGE_LOCK_REQUEST_S request;
        if (key!=NULL) {
            read_lock_request_init(&request, context->txn, context->db,
                                   toku_lt_neg_infinity, toku_lt_neg_infinity,
                                   &found_key,           &found_val);
        }
        else {
            read_lock_request_init(&request, context->txn, context->db,
                                   toku_lt_neg_infinity, toku_lt_neg_infinity,
                                   toku_lt_infinity,     toku_lt_infinity);
        }
        r = grab_range_lock(&request);
    }
    else r = 0;

    //Call application-layer callback if found and locks were successfully obtained.
    if (r==0 && key!=NULL) {
        context->r_user_callback = super_context->f(&found_key, &found_val, context->f_extra);
        if (context->r_user_callback) r = TOKUDB_USER_CALLBACK_ERROR;
    }

    //Give brt-layer an error (if any) to return from toku_brt_cursor_first
    return r;
}

static int c_getf_last_callback(ITEMLEN keylen, bytevec key, ITEMLEN vallen, bytevec val, void *extra);

static int
toku_c_getf_last(DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra) {
    HANDLE_PANICKED_DB(c->dbp);
2312
    HANDLE_CURSOR_ILLEGAL_WORKING_PARENT_TXN(c);
2313
    num_point_queries++;   // accountability
2314 2315 2316
    QUERY_CONTEXT_S context; //Describes the context of this query.
    query_context_init(&context, c, flag, f, extra); 
    //toku_brt_cursor_last will call c_getf_last_callback(..., context) (if query is successful)
2317
    int r = toku_brt_cursor_last(dbc_struct_i(c)->c, c_getf_last_callback, &context);
2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366
    if (r == TOKUDB_USER_CALLBACK_ERROR) r = context.base.r_user_callback;
    return r;
}

//result is the result of the query (i.e. 0 means found, DB_NOTFOUND, etc..)
static int
c_getf_last_callback(ITEMLEN keylen, bytevec key, ITEMLEN vallen, bytevec val, void *extra) {
    QUERY_CONTEXT      super_context = extra;
    QUERY_CONTEXT_BASE context       = &super_context->base;

    int r;

    DBT found_key;
    DBT found_val;
    toku_fill_dbt(&found_key, key, keylen);
    toku_fill_dbt(&found_val, val, vallen);

    if (context->do_locking) {
        RANGE_LOCK_REQUEST_S request;
        if (key!=NULL) {
            read_lock_request_init(&request, context->txn, context->db,
                                   &found_key,           &found_val,
                                   toku_lt_infinity,     toku_lt_infinity);
        }
        else {
            read_lock_request_init(&request, context->txn, context->db,
                                   toku_lt_neg_infinity, toku_lt_neg_infinity,
                                   toku_lt_infinity,     toku_lt_infinity);
        }
        r = grab_range_lock(&request);
    }
    else r = 0;

    //Call application-layer callback if found and locks were successfully obtained.
    if (r==0 && key!=NULL) {
        context->r_user_callback = super_context->f(&found_key, &found_val, context->f_extra);
        if (context->r_user_callback) r = TOKUDB_USER_CALLBACK_ERROR;
    }

    //Give brt-layer an error (if any) to return from toku_brt_cursor_last
    return r;
}

static int c_getf_next_callback(ITEMLEN keylen, bytevec key, ITEMLEN vallen, bytevec val, void *extra);

static int
toku_c_getf_next(DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra) {
    int r;
    HANDLE_PANICKED_DB(c->dbp);
2367
    HANDLE_CURSOR_ILLEGAL_WORKING_PARENT_TXN(c);
2368 2369 2370 2371
    if (c_db_is_nodup(c))             r = toku_c_getf_next_nodup(c, flag, f, extra);
    else if (toku_c_uninitialized(c)) r = toku_c_getf_first(c, flag, f, extra);
    else {
        QUERY_CONTEXT_S context; //Describes the context of this query.
2372
        num_sequential_queries++;   // accountability
2373 2374
        query_context_init(&context, c, flag, f, extra); 
        //toku_brt_cursor_next will call c_getf_next_callback(..., context) (if query is successful)
2375
        r = toku_brt_cursor_next(dbc_struct_i(c)->c, c_getf_next_callback, &context);
2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422
        if (r == TOKUDB_USER_CALLBACK_ERROR) r = context.base.r_user_callback;
    }
    return r;
}

//result is the result of the query (i.e. 0 means found, DB_NOTFOUND, etc..)
static int
c_getf_next_callback(ITEMLEN keylen, bytevec key, ITEMLEN vallen, bytevec val, void *extra) {
    QUERY_CONTEXT      super_context = extra;
    QUERY_CONTEXT_BASE context       = &super_context->base;

    int r;

    DBT found_key;
    DBT found_val;
    toku_fill_dbt(&found_key, key, keylen);
    toku_fill_dbt(&found_val, val, vallen);

    if (context->do_locking) {
        RANGE_LOCK_REQUEST_S request;
        const DBT *prevkey;
        const DBT *prevval;
        const DBT *right_key = key==NULL ? toku_lt_infinity : &found_key;
        const DBT *right_val = key==NULL ? toku_lt_infinity : &found_val;

        toku_brt_cursor_peek(context->c, &prevkey, &prevval);
        read_lock_request_init(&request, context->txn, context->db,
                               prevkey,   prevval,
                               right_key, right_val);
        r = grab_range_lock(&request);
    }
    else r = 0;

    //Call application-layer callback if found and locks were successfully obtained.
    if (r==0 && key!=NULL) {
        context->r_user_callback = super_context->f(&found_key, &found_val, context->f_extra);
        if (context->r_user_callback) r = TOKUDB_USER_CALLBACK_ERROR;
    }

    //Give brt-layer an error (if any) to return from toku_brt_cursor_next
    return r;
}

static int
toku_c_getf_next_nodup(DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra) {
    int r;
    HANDLE_PANICKED_DB(c->dbp);
2423
    HANDLE_CURSOR_ILLEGAL_WORKING_PARENT_TXN(c);
2424 2425 2426
    if (toku_c_uninitialized(c)) r = toku_c_getf_first(c, flag, f, extra);
    else {
        QUERY_CONTEXT_S context; //Describes the context of this query.
2427
        num_sequential_queries++;   // accountability
2428 2429
        query_context_init(&context, c, flag, f, extra); 
        //toku_brt_cursor_next will call c_getf_next_callback(..., context) (if query is successful)
2430
        r = toku_brt_cursor_next_nodup(dbc_struct_i(c)->c, c_getf_next_callback, &context);
2431 2432 2433 2434 2435 2436 2437 2438 2439
        if (r == TOKUDB_USER_CALLBACK_ERROR) r = context.base.r_user_callback;
    }
    return r;
}

static int c_getf_next_dup_callback(ITEMLEN keylen, bytevec key, ITEMLEN vallen, bytevec val, void *extra);

static int
toku_c_getf_next_dup(DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra) {
Yoni Fogel's avatar
Yoni Fogel committed
2440
    HANDLE_PANICKED_DB(c->dbp);
2441
    HANDLE_CURSOR_ILLEGAL_WORKING_PARENT_TXN(c);
Yoni Fogel's avatar
Yoni Fogel committed
2442
    if (toku_c_uninitialized(c)) return EINVAL;
2443 2444

    QUERY_CONTEXT_S context; //Describes the context of this query.
2445
    num_sequential_queries++;   // accountability
2446 2447
    query_context_init(&context, c, flag, f, extra); 
    //toku_brt_cursor_next_dup will call c_getf_next_dup_callback(..., context) (if query is successful)
2448
    int r = toku_brt_cursor_next_dup(dbc_struct_i(c)->c, c_getf_next_dup_callback, &context);
2449 2450 2451 2452 2453 2454 2455 2456 2457 2458
    if (r == TOKUDB_USER_CALLBACK_ERROR) r = context.base.r_user_callback;
    return r;
}

//result is the result of the query (i.e. 0 means found, DB_NOTFOUND, etc..)
static int
c_getf_next_dup_callback(ITEMLEN keylen, bytevec key, ITEMLEN vallen, bytevec val, void *extra) {
    QUERY_CONTEXT      super_context = extra;
    QUERY_CONTEXT_BASE context       = &super_context->base;

Yoni Fogel's avatar
Yoni Fogel committed
2459 2460
    int r;

2461 2462 2463 2464
    DBT found_key;
    DBT found_val;
    toku_fill_dbt(&found_key, key, keylen);
    toku_fill_dbt(&found_val, val, vallen);
Yoni Fogel's avatar
Yoni Fogel committed
2465

2466 2467 2468 2469 2470
    if (context->do_locking) {
        RANGE_LOCK_REQUEST_S request;
        const DBT *prevkey;
        const DBT *prevval;
        const DBT *right_val = key==NULL ? toku_lt_infinity : &found_val;
Yoni Fogel's avatar
Yoni Fogel committed
2471

2472 2473 2474 2475 2476 2477 2478
        toku_brt_cursor_peek(context->c, &prevkey, &prevval);
        read_lock_request_init(&request, context->txn, context->db,
                               prevkey,  prevval,
                               prevkey,  right_val); //found_key is same as prevkey for this case
        r = grab_range_lock(&request);
    }
    else r = 0;
Yoni Fogel's avatar
Yoni Fogel committed
2479

2480 2481 2482 2483
    //Call application-layer callback if found and locks were successfully obtained.
    if (r==0 && key!=NULL) {
        context->r_user_callback = super_context->f(&found_key, &found_val, context->f_extra);
        if (context->r_user_callback) r = TOKUDB_USER_CALLBACK_ERROR;
Yoni Fogel's avatar
Yoni Fogel committed
2484
    }
2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495

    //Give brt-layer an error (if any) to return from toku_brt_cursor_next_dup
    return r;
}

static int c_getf_prev_callback(ITEMLEN keylen, bytevec key, ITEMLEN vallen, bytevec val, void *extra);

static int
toku_c_getf_prev(DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra) {
    int r;
    HANDLE_PANICKED_DB(c->dbp);
2496
    HANDLE_CURSOR_ILLEGAL_WORKING_PARENT_TXN(c);
2497 2498 2499 2500
    if (c_db_is_nodup(c))             r = toku_c_getf_prev_nodup(c, flag, f, extra);
    else if (toku_c_uninitialized(c)) r = toku_c_getf_last(c, flag, f, extra);
    else {
        QUERY_CONTEXT_S context; //Describes the context of this query.
2501
        num_sequential_queries++;   // accountability
2502 2503
        query_context_init(&context, c, flag, f, extra); 
        //toku_brt_cursor_prev will call c_getf_prev_callback(..., context) (if query is successful)
2504
        r = toku_brt_cursor_prev(dbc_struct_i(c)->c, c_getf_prev_callback, &context);
2505
        if (r == TOKUDB_USER_CALLBACK_ERROR) r = context.base.r_user_callback;
Yoni Fogel's avatar
Yoni Fogel committed
2506 2507 2508 2509
    }
    return r;
}

2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545
//result is the result of the query (i.e. 0 means found, DB_NOTFOUND, etc..)
static int
c_getf_prev_callback(ITEMLEN keylen, bytevec key, ITEMLEN vallen, bytevec val, void *extra) {
    QUERY_CONTEXT      super_context = extra;
    QUERY_CONTEXT_BASE context       = &super_context->base;

    int r;

    DBT found_key;
    DBT found_val;
    toku_fill_dbt(&found_key, key, keylen);
    toku_fill_dbt(&found_val, val, vallen);

    if (context->do_locking) {
        RANGE_LOCK_REQUEST_S request;
        const DBT *prevkey;
        const DBT *prevval;
        const DBT *left_key = key==NULL ? toku_lt_neg_infinity : &found_key;
        const DBT *left_val = key==NULL ? toku_lt_neg_infinity : &found_val;

        toku_brt_cursor_peek(context->c, &prevkey, &prevval);
        read_lock_request_init(&request, context->txn, context->db,
                               left_key, left_val,
                               prevkey,  prevval);
        r = grab_range_lock(&request);
    }
    else r = 0;

    //Call application-layer callback if found and locks were successfully obtained.
    if (r==0 && key!=NULL) {
        context->r_user_callback = super_context->f(&found_key, &found_val, context->f_extra);
        if (context->r_user_callback) r = TOKUDB_USER_CALLBACK_ERROR;
    }

    //Give brt-layer an error (if any) to return from toku_brt_cursor_prev
    return r;
Yoni Fogel's avatar
Yoni Fogel committed
2546 2547
}

2548 2549
static int
toku_c_getf_prev_nodup(DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra) {
Yoni Fogel's avatar
Yoni Fogel committed
2550
    int r;
2551
    HANDLE_PANICKED_DB(c->dbp);
2552
    HANDLE_CURSOR_ILLEGAL_WORKING_PARENT_TXN(c);
2553 2554 2555
    if (toku_c_uninitialized(c)) r = toku_c_getf_last(c, flag, f, extra);
    else {
        QUERY_CONTEXT_S context; //Describes the context of this query.
2556
        num_sequential_queries++;   // accountability
2557 2558
        query_context_init(&context, c, flag, f, extra); 
        //toku_brt_cursor_prev will call c_getf_prev_callback(..., context) (if query is successful)
2559
        r = toku_brt_cursor_prev_nodup(dbc_struct_i(c)->c, c_getf_prev_callback, &context);
2560 2561 2562 2563
        if (r == TOKUDB_USER_CALLBACK_ERROR) r = context.base.r_user_callback;
    }
    return r;
}
Yoni Fogel's avatar
Yoni Fogel committed
2564

2565 2566 2567 2568 2569
static int c_getf_prev_dup_callback(ITEMLEN keylen, bytevec key, ITEMLEN vallen, bytevec val, void *extra);

static int
toku_c_getf_prev_dup(DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra) {
    HANDLE_PANICKED_DB(c->dbp);
2570
    HANDLE_CURSOR_ILLEGAL_WORKING_PARENT_TXN(c);
2571 2572 2573
    if (toku_c_uninitialized(c)) return EINVAL;

    QUERY_CONTEXT_S context; //Describes the context of this query.
2574
    num_sequential_queries++;   // accountability
2575 2576
    query_context_init(&context, c, flag, f, extra); 
    //toku_brt_cursor_prev_dup will call c_getf_prev_dup_callback(..., context) (if query is successful)
2577
    int r = toku_brt_cursor_prev_dup(dbc_struct_i(c)->c, c_getf_prev_dup_callback, &context);
2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623
    if (r == TOKUDB_USER_CALLBACK_ERROR) r = context.base.r_user_callback;
    return r;
}

//result is the result of the query (i.e. 0 means found, DB_NOTFOUND, etc..)
static int
c_getf_prev_dup_callback(ITEMLEN keylen, bytevec key, ITEMLEN vallen, bytevec val, void *extra) {
    QUERY_CONTEXT      super_context = extra;
    QUERY_CONTEXT_BASE context       = &super_context->base;

    int r;

    DBT found_key;
    DBT found_val;
    toku_fill_dbt(&found_key, key, keylen);
    toku_fill_dbt(&found_val, val, vallen);

    if (context->do_locking) {
        RANGE_LOCK_REQUEST_S request;
        const DBT *prevkey;
        const DBT *prevval;
        const DBT *left_val = key==NULL ? toku_lt_neg_infinity : &found_val;

        toku_brt_cursor_peek(context->c, &prevkey, &prevval);
        read_lock_request_init(&request, context->txn, context->db,
                               prevkey,  left_val, //found_key is same as prevkey for this case
                               prevkey,  prevval);
        r = grab_range_lock(&request);
    }
    else r = 0;

    //Call application-layer callback if found and locks were successfully obtained.
    if (r==0 && key!=NULL) {
        context->r_user_callback = super_context->f(&found_key, &found_val, context->f_extra);
        if (context->r_user_callback) r = TOKUDB_USER_CALLBACK_ERROR;
    }

    //Give brt-layer an error (if any) to return from toku_brt_cursor_prev_dup
    return r;
}

static int c_getf_current_callback(ITEMLEN keylen, bytevec key, ITEMLEN vallen, bytevec val, void *extra);

static int
toku_c_getf_current(DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra) {
    HANDLE_PANICKED_DB(c->dbp);
2624
    HANDLE_CURSOR_ILLEGAL_WORKING_PARENT_TXN(c);
2625 2626

    QUERY_CONTEXT_S context; //Describes the context of this query.
2627
    num_sequential_queries++;   // accountability
2628 2629
    query_context_init(&context, c, flag, f, extra); 
    //toku_brt_cursor_current will call c_getf_current_callback(..., context) (if query is successful)
2630
    int r = toku_brt_cursor_current(dbc_struct_i(c)->c, DB_CURRENT, c_getf_current_callback, &context);
2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659
    if (r == TOKUDB_USER_CALLBACK_ERROR) r = context.base.r_user_callback;
    return r;
}

//result is the result of the query (i.e. 0 means found, DB_NOTFOUND, etc..)
static int
c_getf_current_callback(ITEMLEN keylen, bytevec key, ITEMLEN vallen, bytevec val, void *extra) {
    QUERY_CONTEXT      super_context = extra;
    QUERY_CONTEXT_BASE context       = &super_context->base;

    DBT found_key;
    DBT found_val;
    toku_fill_dbt(&found_key, key, keylen);
    toku_fill_dbt(&found_val, val, vallen);

    int r=0;
    //Call application-layer callback if found.
    if (key!=NULL) {
        context->r_user_callback = super_context->f(&found_key, &found_val, context->f_extra);
        if (context->r_user_callback) r = TOKUDB_USER_CALLBACK_ERROR;
    }

    //Give brt-layer an error (if any) to return from toku_brt_cursor_current
    return r;
}

static int
toku_c_getf_current_binding(DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra) {
    HANDLE_PANICKED_DB(c->dbp);
2660
    HANDLE_CURSOR_ILLEGAL_WORKING_PARENT_TXN(c);
2661 2662

    QUERY_CONTEXT_S context; //Describes the context of this query.
2663
    num_sequential_queries++;   // accountability
2664 2665
    query_context_init(&context, c, flag, f, extra); 
    //toku_brt_cursor_current will call c_getf_current_callback(..., context) (if query is successful)
2666
    int r = toku_brt_cursor_current(dbc_struct_i(c)->c, DB_CURRENT_BINDING, c_getf_current_callback, &context);
2667 2668 2669 2670 2671 2672 2673 2674 2675
    if (r == TOKUDB_USER_CALLBACK_ERROR) r = context.base.r_user_callback;
    return r;
}

static int c_getf_set_callback(ITEMLEN keylen, bytevec key, ITEMLEN vallen, bytevec val, void *extra);

static int
toku_c_getf_set(DBC *c, u_int32_t flag, DBT *key, YDB_CALLBACK_FUNCTION f, void *extra) {
    HANDLE_PANICKED_DB(c->dbp);
2676
    HANDLE_CURSOR_ILLEGAL_WORKING_PARENT_TXN(c);
2677 2678

    QUERY_CONTEXT_WITH_INPUT_S context; //Describes the context of this query.
2679
    num_point_queries++;   // accountability
2680 2681
    query_context_with_input_init(&context, c, flag, key, NULL, f, extra); 
    //toku_brt_cursor_set will call c_getf_set_callback(..., context) (if query is successful)
2682
    int r = toku_brt_cursor_set(dbc_struct_i(c)->c, key, NULL, c_getf_set_callback, &context);
2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733
    if (r == TOKUDB_USER_CALLBACK_ERROR) r = context.base.r_user_callback;
    return r;
}

//result is the result of the query (i.e. 0 means found, DB_NOTFOUND, etc..)
static int
c_getf_set_callback(ITEMLEN keylen, bytevec key, ITEMLEN vallen, bytevec val, void *extra) {
    QUERY_CONTEXT_WITH_INPUT super_context = extra;
    QUERY_CONTEXT_BASE       context       = &super_context->base;

    int r;

    DBT found_key;
    DBT found_val;
    toku_fill_dbt(&found_key, key, keylen);
    toku_fill_dbt(&found_val, val, vallen);

    //Lock:
    //  left(key,val)  = (input_key, -infinity)
    //  right(key,val) = (input_key, found ? found_val : infinity)
    if (context->do_locking) {
        RANGE_LOCK_REQUEST_S request;
        if (key!=NULL) {
            read_lock_request_init(&request, context->txn, context->db,
                                   super_context->input_key, toku_lt_neg_infinity,
                                   super_context->input_key, &found_val);
        }
        else {
            read_lock_request_init(&request, context->txn, context->db,
                                   super_context->input_key, toku_lt_neg_infinity,
                                   super_context->input_key, toku_lt_infinity);
        }
        r = grab_range_lock(&request);
    }
    else r = 0;

    //Call application-layer callback if found and locks were successfully obtained.
    if (r==0 && key!=NULL) {
        context->r_user_callback = super_context->f(&found_key, &found_val, context->f_extra);
        if (context->r_user_callback) r = TOKUDB_USER_CALLBACK_ERROR;
    }

    //Give brt-layer an error (if any) to return from toku_brt_cursor_set
    return r;
}

static int c_getf_set_range_callback(ITEMLEN keylen, bytevec key, ITEMLEN vallen, bytevec val, void *extra);

static int
toku_c_getf_set_range(DBC *c, u_int32_t flag, DBT *key, YDB_CALLBACK_FUNCTION f, void *extra) {
    HANDLE_PANICKED_DB(c->dbp);
2734
    HANDLE_CURSOR_ILLEGAL_WORKING_PARENT_TXN(c);
2735 2736

    QUERY_CONTEXT_WITH_INPUT_S context; //Describes the context of this query.
2737
    num_point_queries++;   // accountability
2738 2739
    query_context_with_input_init(&context, c, flag, key, NULL, f, extra); 
    //toku_brt_cursor_set_range will call c_getf_set_range_callback(..., context) (if query is successful)
2740
    int r = toku_brt_cursor_set_range(dbc_struct_i(c)->c, key, c_getf_set_range_callback, &context);
2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787
    if (r == TOKUDB_USER_CALLBACK_ERROR) r = context.base.r_user_callback;
    return r;
}

//result is the result of the query (i.e. 0 means found, DB_NOTFOUND, etc..)
static int
c_getf_set_range_callback(ITEMLEN keylen, bytevec key, ITEMLEN vallen, bytevec val, void *extra) {
    QUERY_CONTEXT_WITH_INPUT super_context = extra;
    QUERY_CONTEXT_BASE       context       = &super_context->base;

    int r;

    DBT found_key;
    DBT found_val;
    toku_fill_dbt(&found_key, key, keylen);
    toku_fill_dbt(&found_val, val, vallen);

    //Lock:
    //  left(key,val)  = (input_key, -infinity)
    //  right(key) = found ? found_key : infinity
    //  right(val) = found ? found_val : infinity
    if (context->do_locking) {
        RANGE_LOCK_REQUEST_S request;
        if (key!=NULL) {
            read_lock_request_init(&request, context->txn, context->db,
                                   super_context->input_key, toku_lt_neg_infinity,
                                   &found_key,               &found_val);
        }
        else {
            read_lock_request_init(&request, context->txn, context->db,
                                   super_context->input_key, toku_lt_neg_infinity,
                                   toku_lt_infinity,         toku_lt_infinity);
        }
        r = grab_range_lock(&request);
    }
    else r = 0;

    //Call application-layer callback if found and locks were successfully obtained.
    if (r==0 && key!=NULL) {
        context->r_user_callback = super_context->f(&found_key, &found_val, context->f_extra);
        if (context->r_user_callback) r = TOKUDB_USER_CALLBACK_ERROR;
    }

    //Give brt-layer an error (if any) to return from toku_brt_cursor_set_range
    return r;
}

2788 2789 2790 2791 2792 2793 2794 2795
static int c_getf_set_range_reverse_callback(ITEMLEN keylen, bytevec key, ITEMLEN vallen, bytevec val, void *extra);

static int
toku_c_getf_set_range_reverse(DBC *c, u_int32_t flag, DBT *key, YDB_CALLBACK_FUNCTION f, void *extra) {
    HANDLE_PANICKED_DB(c->dbp);
    HANDLE_CURSOR_ILLEGAL_WORKING_PARENT_TXN(c);

    QUERY_CONTEXT_WITH_INPUT_S context; //Describes the context of this query.
2796
    num_point_queries++;   // accountability
2797 2798
    query_context_with_input_init(&context, c, flag, key, NULL, f, extra); 
    //toku_brt_cursor_set_range_reverse will call c_getf_set_range_reverse_callback(..., context) (if query is successful)
2799
    int r = toku_brt_cursor_set_range_reverse(dbc_struct_i(c)->c, key, c_getf_set_range_reverse_callback, &context);
2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846
    if (r == TOKUDB_USER_CALLBACK_ERROR) r = context.base.r_user_callback;
    return r;
}

//result is the result of the query (i.e. 0 means found, DB_NOTFOUND, etc..)
static int
c_getf_set_range_reverse_callback(ITEMLEN keylen, bytevec key, ITEMLEN vallen, bytevec val, void *extra) {
    QUERY_CONTEXT_WITH_INPUT super_context = extra;
    QUERY_CONTEXT_BASE       context       = &super_context->base;

    int r;

    DBT found_key;
    DBT found_val;
    toku_fill_dbt(&found_key, key, keylen);
    toku_fill_dbt(&found_val, val, vallen);

    //Lock:
    //  left(key) = found ? found_key : -infinity
    //  left(val) = found ? found_val : -infinity
    //  right(key,val)  = (input_key, infinity)
    if (context->do_locking) {
        RANGE_LOCK_REQUEST_S request;
        if (key!=NULL) {
            read_lock_request_init(&request, context->txn, context->db,
                                   &found_key,               &found_val,
                                   super_context->input_key, toku_lt_infinity);
        }
        else {
            read_lock_request_init(&request, context->txn, context->db,
                                   toku_lt_neg_infinity,     toku_lt_neg_infinity,
                                   super_context->input_key, toku_lt_infinity);
        }
        r = grab_range_lock(&request);
    }
    else r = 0;

    //Call application-layer callback if found and locks were successfully obtained.
    if (r==0 && key!=NULL) {
        context->r_user_callback = super_context->f(&found_key, &found_val, context->f_extra);
        if (context->r_user_callback) r = TOKUDB_USER_CALLBACK_ERROR;
    }

    //Give brt-layer an error (if any) to return from toku_brt_cursor_set_range_reverse
    return r;
}

2847 2848 2849 2850 2851
static int c_getf_get_both_callback(ITEMLEN keylen, bytevec key, ITEMLEN vallen, bytevec val, void *extra);

static int
toku_c_getf_get_both(DBC *c, u_int32_t flag, DBT *key, DBT *val, YDB_CALLBACK_FUNCTION f, void *extra) {
    HANDLE_PANICKED_DB(c->dbp);
2852
    HANDLE_CURSOR_ILLEGAL_WORKING_PARENT_TXN(c);
2853 2854

    QUERY_CONTEXT_WITH_INPUT_S context; //Describes the context of this query.
2855
    num_point_queries++;   // accountability
2856 2857
    query_context_with_input_init(&context, c, flag, key, val, f, extra); 
    //toku_brt_cursor_get_both will call c_getf_get_both_callback(..., context) (if query is successful)
2858
    int r = toku_brt_cursor_set(dbc_struct_i(c)->c, key, val, c_getf_get_both_callback, &context);
2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902
    if (r == TOKUDB_USER_CALLBACK_ERROR) r = context.base.r_user_callback;
    return r;
}

//result is the result of the query (i.e. 0 means found, DB_NOTFOUND, etc..)
static int
c_getf_get_both_callback(ITEMLEN keylen, bytevec key, ITEMLEN vallen, bytevec val, void *extra) {
    QUERY_CONTEXT_WITH_INPUT super_context = extra;
    QUERY_CONTEXT_BASE       context       = &super_context->base;

    int r;

    DBT found_key;
    DBT found_val;
    toku_fill_dbt(&found_key, key, keylen);
    toku_fill_dbt(&found_val, val, vallen);

    //Lock:
    //  left(key,val)  = (input_key, input_val)
    //  right==left
    if (context->do_locking) {
        RANGE_LOCK_REQUEST_S request;
        read_lock_request_init(&request, context->txn, context->db,
                               super_context->input_key, super_context->input_val,
                               super_context->input_key, super_context->input_val);
        r = grab_range_lock(&request);
    }
    else r = 0;

    //Call application-layer callback if found and locks were successfully obtained.
    if (r==0 && key!=NULL) {
        context->r_user_callback = super_context->f(&found_key, &found_val, context->f_extra);
        if (context->r_user_callback) r = TOKUDB_USER_CALLBACK_ERROR;
    }

    //Give brt-layer an error (if any) to return from toku_brt_cursor_get_both
    return r;
}

static int c_getf_get_both_range_callback(ITEMLEN keylen, bytevec key, ITEMLEN vallen, bytevec val, void *extra);

static int
toku_c_getf_get_both_range(DBC *c, u_int32_t flag, DBT *key, DBT *val, YDB_CALLBACK_FUNCTION f, void *extra) {
    HANDLE_PANICKED_DB(c->dbp);
2903
    HANDLE_CURSOR_ILLEGAL_WORKING_PARENT_TXN(c);
2904 2905 2906 2907
    int r;
    if (c_db_is_nodup(c)) r = toku_c_getf_get_both(c, flag, key, val, f, extra);
    else {
        QUERY_CONTEXT_WITH_INPUT_S context; //Describes the context of this query.
2908
        num_point_queries++;   // accountability
2909 2910
        query_context_with_input_init(&context, c, flag, key, val, f, extra); 
        //toku_brt_cursor_get_both_range will call c_getf_get_both_range_callback(..., context) (if query is successful)
2911
        r = toku_brt_cursor_get_both_range(dbc_struct_i(c)->c, key, val, c_getf_get_both_range_callback, &context);
2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958
        if (r == TOKUDB_USER_CALLBACK_ERROR) r = context.base.r_user_callback;
    }
    return r;
}

//result is the result of the query (i.e. 0 means found, DB_NOTFOUND, etc..)
static int
c_getf_get_both_range_callback(ITEMLEN keylen, bytevec key, ITEMLEN vallen, bytevec val, void *extra) {
    QUERY_CONTEXT_WITH_INPUT super_context = extra;
    QUERY_CONTEXT_BASE       context       = &super_context->base;

    int r;

    DBT found_key;
    DBT found_val;
    toku_fill_dbt(&found_key, key, keylen);
    toku_fill_dbt(&found_val, val, vallen);

    //Lock:
    //  left(key,val)  = (input_key, input_val)
    //  right(key,val) = (input_key, found ? found_val : infinity)
    if (context->do_locking) {
        RANGE_LOCK_REQUEST_S request;
        if (key!=NULL) {
            read_lock_request_init(&request, context->txn, context->db,
                                   super_context->input_key, super_context->input_val,
                                   super_context->input_key, &found_val);
        }
        else {
            read_lock_request_init(&request, context->txn, context->db,
                                   super_context->input_key, super_context->input_val,
                                   super_context->input_key, toku_lt_infinity);
        }
        r = grab_range_lock(&request);
    }
    else r = 0;

    //Call application-layer callback if found and locks were successfully obtained.
    if (r==0 && key!=NULL) {
        context->r_user_callback = super_context->f(&found_key, &found_val, context->f_extra);
        if (context->r_user_callback) r = TOKUDB_USER_CALLBACK_ERROR;
    }

    //Give brt-layer an error (if any) to return from toku_brt_cursor_get_both_range
    return r;
}

2959 2960 2961 2962 2963 2964 2965 2966 2967 2968
static int c_getf_get_both_range_reverse_callback(ITEMLEN keylen, bytevec key, ITEMLEN vallen, bytevec val, void *extra);

static int
toku_c_getf_get_both_range_reverse(DBC *c, u_int32_t flag, DBT *key, DBT *val, YDB_CALLBACK_FUNCTION f, void *extra) {
    HANDLE_PANICKED_DB(c->dbp);
    HANDLE_CURSOR_ILLEGAL_WORKING_PARENT_TXN(c);
    int r;
    if (c_db_is_nodup(c)) r = toku_c_getf_get_both(c, flag, key, val, f, extra);
    else {
        QUERY_CONTEXT_WITH_INPUT_S context; //Describes the context of this query.
2969
        num_point_queries++;   // accountability
2970 2971
        query_context_with_input_init(&context, c, flag, key, val, f, extra); 
        //toku_brt_cursor_get_both_range_reverse will call c_getf_get_both_range_reverse_callback(..., context) (if query is successful)
2972
        r = toku_brt_cursor_get_both_range_reverse(dbc_struct_i(c)->c, key, val, c_getf_get_both_range_reverse_callback, &context);
2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018
        if (r == TOKUDB_USER_CALLBACK_ERROR) r = context.base.r_user_callback;
    }
    return r;
}

//result is the result of the query (i.e. 0 means found, DB_NOTFOUND, etc..)
static int
c_getf_get_both_range_reverse_callback(ITEMLEN keylen, bytevec key, ITEMLEN vallen, bytevec val, void *extra) {
    QUERY_CONTEXT_WITH_INPUT super_context = extra;
    QUERY_CONTEXT_BASE       context       = &super_context->base;

    int r;

    DBT found_key;
    DBT found_val;
    toku_fill_dbt(&found_key, key, keylen);
    toku_fill_dbt(&found_val, val, vallen);

    //Lock:
    //  left(key,val)  = (input_key, found ? found_val : -infinity)
    //  right(key,val) = (input_key, input_val)
    if (context->do_locking) {
        RANGE_LOCK_REQUEST_S request;
        if (key!=NULL) {
            read_lock_request_init(&request, context->txn, context->db,
                                   super_context->input_key, &found_val,
                                   super_context->input_key, super_context->input_val);
        }
        else {
            read_lock_request_init(&request, context->txn, context->db,
                                   super_context->input_key, toku_lt_neg_infinity,
                                   super_context->input_key, super_context->input_val);
        }
        r = grab_range_lock(&request);
    }
    else r = 0;

    //Call application-layer callback if found and locks were successfully obtained.
    if (r==0 && key!=NULL) {
        context->r_user_callback = super_context->f(&found_key, &found_val, context->f_extra);
        if (context->r_user_callback) r = TOKUDB_USER_CALLBACK_ERROR;
    }

    //Give brt-layer an error (if any) to return from toku_brt_cursor_get_both_range_reverse
    return r;
}
3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033

static int locked_c_getf_heaviside(DBC *c, u_int32_t flags,
                               YDB_HEAVISIDE_CALLBACK_FUNCTION f, void *extra_f,
                               YDB_HEAVISIDE_FUNCTION h, void *extra_h, int direction) {
    toku_ydb_lock();  int r = toku_c_getf_heaviside(c, flags, f, extra_f, h, extra_h, direction); toku_ydb_unlock(); return r;
}

typedef struct {
    QUERY_CONTEXT_BASE_S            base;
    YDB_HEAVISIDE_CALLBACK_FUNCTION f;
    HEAVI_WRAPPER                   wrapper;
} *QUERY_CONTEXT_HEAVISIDE, QUERY_CONTEXT_HEAVISIDE_S;

static void
query_context_heaviside_init(QUERY_CONTEXT_HEAVISIDE context, DBC *c, u_int32_t flag, YDB_HEAVISIDE_CALLBACK_FUNCTION f, void *extra, HEAVI_WRAPPER wrapper) {
3034 3035
    WRITE_OP is_write = {FALSE};
    query_context_base_init(&context->base, c, flag, is_write, extra);
3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058
    context->f       = f;
    context->wrapper = wrapper;
}

static void
heavi_wrapper_init(HEAVI_WRAPPER wrapper, int (*h)(const DBT *key, const DBT *value, void *extra_h), void *extra_h, int direction) {
    wrapper->h         = h;
    wrapper->extra_h   = extra_h;
    wrapper->r_h       = direction; //Default value of r_h (may be set to 0 later)->
    wrapper->direction = direction;
}

static int c_getf_heaviside_callback(ITEMLEN found_keylen, bytevec found_key, ITEMLEN found_vallen, bytevec found_val,
                                     ITEMLEN next_keylen,  bytevec next_key,  ITEMLEN next_vallen,  bytevec next_val,
                                     void *extra);

static int
toku_c_getf_heaviside(DBC *c, u_int32_t flag,
                      YDB_HEAVISIDE_CALLBACK_FUNCTION f, void *extra_f,
                      YDB_HEAVISIDE_FUNCTION h, void *extra_h,
                      int direction) {
    int r;
    HANDLE_PANICKED_DB(c->dbp);
3059
    HANDLE_CURSOR_ILLEGAL_WORKING_PARENT_TXN(c);
3060
    num_point_queries++;   // accountability
3061 3062 3063 3064 3065
    HEAVI_WRAPPER_S wrapper;
    heavi_wrapper_init(&wrapper, h, extra_h, direction);
    QUERY_CONTEXT_HEAVISIDE_S context; //Describes the context of this query.
    query_context_heaviside_init(&context, c, flag, f, extra_f, &wrapper); 
    //toku_brt_cursor_heaviside will call c_getf_heaviside_callback(..., context) (if query is successful)
3066
    r = toku_brt_cursor_heaviside(dbc_struct_i(c)->c, c_getf_heaviside_callback, &context, &wrapper);
3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096
    if (r == TOKUDB_USER_CALLBACK_ERROR) r = context.base.r_user_callback;
    return r;
}

//result is the result of the query (i.e. 0 means found, DB_NOTFOUND, etc..)
//bytevec==NULL means not found.
static int c_getf_heaviside_callback(ITEMLEN found_keylen, bytevec found_keyvec, ITEMLEN found_vallen, bytevec found_valvec,
                                 ITEMLEN next_keylen,  bytevec next_keyvec,  ITEMLEN next_vallen,  bytevec next_valvec,
                                 void *extra) {
    QUERY_CONTEXT_HEAVISIDE super_context = extra;
    QUERY_CONTEXT_BASE      context       = &super_context->base;

    int r;
    int r2 = 0;

    DBT found_key;
    DBT found_val;
    toku_fill_dbt(&found_key, found_keyvec, found_keylen);
    toku_fill_dbt(&found_val, found_valvec, found_vallen);

    if (context->do_locking) {
        const DBT *left_key  = toku_lt_neg_infinity;
        const DBT *left_val  = toku_lt_neg_infinity;
        const DBT *right_key = toku_lt_infinity;
        const DBT *right_val = toku_lt_infinity;
        RANGE_LOCK_REQUEST_S request;
#ifdef  BRT_LEVEL_STRADDLE_CALLBACK_LOGIC_NOT_READY
        //Have cursor (base->c)
        //Have txn    (base->txn)
        //Have db     (base->db)
3097
        BOOL found = (BOOL)(found_keyvec != NULL);
3098
        DBC *tmp_cursor; //Temporary cursor to find 'next_key/next_val'
Yoni Fogel's avatar
Yoni Fogel committed
3099 3100
        DBT tmp_key;
        DBT tmp_val;
3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116
        toku_init_dbt(&tmp_key);
        toku_init_dbt(&tmp_val);
        r = toku_db_cursor(context->db, context->txn, &tmp_cursor, 0, 0);
        if (r!=0) goto tmp_cleanup;
        //Find the 'next key and next val'
        //We will do all relevent range locking, so there is no need for any sub-queries to do locking.
        //Pass in DB_PRELOCKED.
        if (super_context->wrapper->direction<0) {
            if (found) {
                //do an 'after'
                //call DB_GET_BOTH to set the temp cursor to the 'found' values
                //then call 'DB_NEXT' to advance it to the values we want
                r = toku_c_getf_get_both(tmp_cursor, DB_PRELOCKED, &found_key, &found_val, ydb_getf_do_nothing, NULL);
                if (r==0) {
                    r = toku_c_get(tmp_cursor, &tmp_key, &tmp_val, DB_NEXT|DB_PRELOCKED);
                    if (r==DB_NOTFOUND) r = 0;
Yoni Fogel's avatar
Yoni Fogel committed
3117 3118 3119
                }
            }
            else {
3120 3121 3122
                //do a 'first'
                r = toku_c_get(tmp_cursor, &tmp_key, &tmp_val, DB_FIRST|DB_PRELOCKED);
                if (r==DB_NOTFOUND) r = 0;
Yoni Fogel's avatar
Yoni Fogel committed
3123 3124 3125
            }
        }
        else {
3126 3127 3128 3129 3130 3131 3132 3133
            if (found) {
                //do a 'before'
                //call DB_GET_BOTH to set the temp cursor to the 'found' values
                //then call 'DB_PREV' to advance it to the values we want
                r = toku_c_getf_get_both(tmp_cursor, DB_PRELOCKED, &found_key, &found_val, ydb_getf_do_nothing, NULL);
                if (r==0) {
                    r = toku_c_get(tmp_cursor, &tmp_key, &tmp_val, DB_PREV|DB_PRELOCKED);
                    if (r==DB_NOTFOUND) r = 0;
Yoni Fogel's avatar
Yoni Fogel committed
3134 3135 3136
                }
            }
            else {
3137 3138 3139
                //do a 'last'
                r = toku_c_get(tmp_cursor, &tmp_key, &tmp_val, DB_LAST|DB_PRELOCKED);
                if (r==DB_NOTFOUND) r = 0;
Yoni Fogel's avatar
Yoni Fogel committed
3140 3141
            }
        }
3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195
        if (r==0) {
            next_keyvec = tmp_key.data;
            next_keylen = tmp_key.size;
            next_valvec = tmp_val.data;
            next_vallen = tmp_val.size;
        }
        else goto temp_cursor_cleanup;
#endif
        DBT next_key;
        DBT next_val;
        toku_fill_dbt(&next_key, next_keyvec, next_keylen);
        toku_fill_dbt(&next_val, next_valvec, next_vallen);
        if (super_context->wrapper->direction<0) {
            if (found_keyvec!=NULL) {
                left_key  = &found_key; 
                left_val  = &found_val; 
            }
            if (next_keyvec!=NULL) {
                right_key = &next_key; 
                right_val = &next_val; 
            }
        }
        else {
            if (next_keyvec!=NULL) {
                left_key  = &next_key; 
                left_val  = &next_val; 
            }
            if (found_keyvec!=NULL) {
                right_key = &found_key; 
                right_val = &found_val; 
            }
        }
        read_lock_request_init(&request, context->txn, context->db,
                               left_key,   left_val,
                               right_key,  right_val);
        r = grab_range_lock(&request);
#ifdef  BRT_LEVEL_STRADDLE_CALLBACK_LOGIC_NOT_READY
temp_cursor_cleanup:
        r2 = toku_c_close(tmp_cursor);
        //cleanup cursor
#endif
    }
    else r = 0;

    //Call application-layer callback if found and locks were successfully obtained.
    if (r==0 && found_keyvec!=NULL) {
        context->r_user_callback = super_context->f(&found_key, &found_val, context->f_extra, super_context->wrapper->r_h);
        if (context->r_user_callback) r = TOKUDB_USER_CALLBACK_ERROR;
    }

#ifdef  BRT_LEVEL_STRADDLE_CALLBACK_LOGIC_NOT_READY
tmp_cleanup:
#endif
    //Give brt-layer an error (if any) to return from toku_brt_cursor_heavi
Yoni Fogel's avatar
Yoni Fogel committed
3196 3197 3198
    return r ? r : r2;
}

3199
static int toku_c_close(DBC * c) {
3200 3201
    HANDLE_PANICKED_DB(c->dbp);
    HANDLE_CURSOR_ILLEGAL_WORKING_PARENT_TXN(c);
3202 3203 3204 3205 3206 3207
    int r = toku_brt_cursor_close(dbc_struct_i(c)->c);
    toku_sdbt_cleanup(&dbc_struct_i(c)->skey_s);
    toku_sdbt_cleanup(&dbc_struct_i(c)->sval_s);
#if !TOKUDB_NATIVE_H
    toku_free(dbc_struct_i(c));
#endif
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
3208
    toku_free(c);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3209 3210 3211
    return r;
}

3212 3213 3214 3215 3216
static inline int keyeq(DBC *c, DBT *a, DBT *b) {
    DB *db = c->dbp;
    return db->i->brt->compare_fun(db, a, b) == 0;
}

3217 3218 3219 3220
// Return the number of entries whose key matches the key currently 
// pointed to by the brt cursor.  
static int 
toku_c_count(DBC *cursor, db_recno_t *count, u_int32_t flags) {
3221 3222
    HANDLE_PANICKED_DB(cursor->dbp);
    HANDLE_CURSOR_ILLEGAL_WORKING_PARENT_TXN(cursor);
Rich Prohaska's avatar
Rich Prohaska committed
3223 3224
    int r;
    DBC *count_cursor = 0;
3225
    DBT currentkey;
Rich Prohaska's avatar
Rich Prohaska committed
3226

3227
    init_dbt_realloc(&currentkey);
3228
    u_int32_t lock_flags = get_prelocked_flags(flags, dbc_struct_i(cursor)->txn, cursor->dbp);
3229
    flags &= ~lock_flags;
Rich Prohaska's avatar
Rich Prohaska committed
3230 3231 3232 3233
    if (flags != 0) {
        r = EINVAL; goto finish;
    }

3234
    r = toku_c_get_current_unconditional(cursor, lock_flags, &currentkey, NULL);
Rich Prohaska's avatar
Rich Prohaska committed
3235
    if (r != 0) goto finish;
3236 3237 3238 3239 3240 3241

    //TODO: Optimization
    //if (do_locking) {
    //   do a lock from currentkey,-infinity to currentkey,infinity
    //   lock_flags |= DB_PRELOCKED
    //}
Rich Prohaska's avatar
Rich Prohaska committed
3242
    
3243
    r = toku_db_cursor(cursor->dbp, dbc_struct_i(cursor)->txn, &count_cursor, 0, 0);
Rich Prohaska's avatar
Rich Prohaska committed
3244 3245 3246
    if (r != 0) goto finish;

    *count = 0;
3247
    r = toku_c_getf_set(count_cursor, lock_flags, &currentkey, ydb_getf_do_nothing, NULL);
Rich Prohaska's avatar
Rich Prohaska committed
3248 3249 3250 3251 3252 3253
    if (r != 0) {
        r = 0; goto finish; /* success, the current key must be deleted and there are no more */
    }

    for (;;) {
        *count += 1;
3254
        r = toku_c_getf_next_dup(count_cursor, lock_flags, ydb_getf_do_nothing, NULL);
Rich Prohaska's avatar
Rich Prohaska committed
3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265
        if (r != 0) break;
    }
    r = 0; /* success, we found at least one before the end */
finish:
    if (currentkey.data) toku_free(currentkey.data);
    if (count_cursor) {
        int rr = toku_c_close(count_cursor); assert(rr == 0);
    }
    return r;
}

Yoni Fogel's avatar
 
Yoni Fogel committed
3266

3267 3268
///////////
//db_getf_XXX is equivalent to c_getf_XXX, without a persistent cursor
Yoni Fogel's avatar
 
Yoni Fogel committed
3269

3270 3271
static int
db_getf_set(DB *db, DB_TXN *txn, u_int32_t flags, DBT *key, YDB_CALLBACK_FUNCTION f, void *extra) {
3272 3273
    HANDLE_PANICKED_DB(db);
    HANDLE_DB_ILLEGAL_WORKING_PARENT_TXN(db, txn);
3274 3275 3276 3277 3278 3279
    DBC *c;
    int r = toku_db_cursor(db, txn, &c, 0, 1);
    if (r==0) {
        r = toku_c_getf_set(c, flags, key, f, extra);
        int r2 = toku_c_close(c);
        if (r==0) r = r2;
Yoni Fogel's avatar
 
Yoni Fogel committed
3280
    }
3281
    return r;
Yoni Fogel's avatar
 
Yoni Fogel committed
3282 3283
}

3284 3285
static int
db_getf_get_both(DB *db, DB_TXN *txn, u_int32_t flags, DBT *key, DBT *val, YDB_CALLBACK_FUNCTION f, void *extra) {
3286 3287
    HANDLE_PANICKED_DB(db);
    HANDLE_DB_ILLEGAL_WORKING_PARENT_TXN(db, txn);
3288 3289 3290 3291 3292 3293
    DBC *c;
    int r = toku_db_cursor(db, txn, &c, 0, 1);
    if (r==0) {
        r = toku_c_getf_get_both(c, flags, key, val, f, extra);
        int r2 = toku_c_close(c);
        if (r==0) r = r2;
Yoni Fogel's avatar
 
Yoni Fogel committed
3294
    }
3295
    return r;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3296
}
3297
////////////
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3298

3299 3300
static int
toku_db_del(DB *db, DB_TXN *txn, DBT *key, u_int32_t flags) {
3301
    HANDLE_PANICKED_DB(db);
3302
    HANDLE_DB_ILLEGAL_WORKING_PARENT_TXN(db, txn);
3303
    num_deletes++;       // accountability 
3304 3305
    u_int32_t unchecked_flags = flags;
    //DB_DELETE_ANY means delete regardless of whether it exists in the db.
3306
    BOOL error_if_missing = (BOOL)(!(flags&DB_DELETE_ANY));
3307
    unchecked_flags &= ~DB_DELETE_ANY;
3308
    u_int32_t lock_flags = get_prelocked_flags(flags, txn, db);
3309
    unchecked_flags &= ~lock_flags;
3310
    BOOL do_locking = (BOOL)(db->i->lt && !(lock_flags&DB_PRELOCKED_WRITE));
3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324
    int r = 0;
    if (unchecked_flags!=0) r = EINVAL;
    if (r==0 && error_if_missing) {
        //Check if the key exists in the db.
        r = db_getf_set(db, txn, lock_flags, key, ydb_getf_do_nothing, NULL);
    }
    if (r==0 && do_locking) {
        //Do locking if necessary.
        RANGE_LOCK_REQUEST_S request;
        //Left end of range == right end of range (point lock)
        write_lock_request_init(&request, txn, db,
                                key, toku_lt_neg_infinity,
                                key, toku_lt_infinity);
        r = grab_range_lock(&request);
3325
    }
3326 3327
    if (r==0) {
        //Do the actual deleting.
3328
        r = toku_brt_delete(db->i->brt, key, txn ? db_txn_struct_i(txn)->tokutxn : 0);
3329
    }
3330
    return r;
Rich Prohaska's avatar
Rich Prohaska committed
3331 3332 3333
}

static int locked_c_get(DBC * c, DBT * key, DBT * data, u_int32_t flag) {
3334 3335 3336 3337
    //{ unsigned int i; printf("cget flags=%d keylen=%d key={", flag, key->size); for(i=0; i<key->size; i++) printf("%d,", ((char*)key->data)[i]); printf("} datalen=%d data={", data->size); for(i=0; i<data->size; i++) printf("%d,", ((char*)data->data)[i]); printf("}\n"); }
    toku_ydb_lock(); int r = toku_c_get(c, key, data, flag); toku_ydb_unlock();
    //{ unsigned int i; printf("cgot r=%d keylen=%d key={", r, key->size); for(i=0; i<key->size; i++) printf("%d,", ((char*)key->data)[i]); printf("} datalen=%d data={", data->size); for(i=0; i<data->size; i++) printf("%d,", ((char*)data->data)[i]); printf("}\n"); }
    return r;
Rich Prohaska's avatar
Rich Prohaska committed
3338 3339 3340
}

static int locked_c_close(DBC * c) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3341
    toku_ydb_lock(); int r = toku_c_close(c); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
3342 3343 3344
}

static int locked_c_count(DBC *cursor, db_recno_t *count, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3345
    toku_ydb_lock(); int r = toku_c_count(cursor, count, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
3346 3347 3348
}

static int locked_c_del(DBC * c, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3349
    toku_ydb_lock(); int r = toku_c_del(c, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
3350 3351
}

3352
static int toku_db_cursor(DB * db, DB_TXN * txn, DBC ** c, u_int32_t flags, int is_temporary_cursor) {
3353
    HANDLE_PANICKED_DB(db);
3354
    HANDLE_DB_ILLEGAL_WORKING_PARENT_TXN(db, txn);
3355 3356
    if (flags != 0)
        return EINVAL;
3357
    DBC *MALLOC(result);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3358 3359 3360
    if (result == 0)
        return ENOMEM;
    memset(result, 0, sizeof *result);
Yoni Fogel's avatar
Yoni Fogel committed
3361 3362 3363 3364 3365
#define SCRS(name) result->name = locked_ ## name
    SCRS(c_get);
    SCRS(c_close);
    SCRS(c_del);
    SCRS(c_count);
Yoni Fogel's avatar
Yoni Fogel committed
3366 3367
    SCRS(c_getf_first);
    SCRS(c_getf_last);
Yoni Fogel's avatar
Yoni Fogel committed
3368
    SCRS(c_getf_next);
3369
    SCRS(c_getf_next_nodup);
Yoni Fogel's avatar
Yoni Fogel committed
3370
    SCRS(c_getf_next_dup);
3371 3372 3373 3374 3375 3376 3377 3378
    SCRS(c_getf_prev);
    SCRS(c_getf_prev_nodup);
    SCRS(c_getf_prev_dup);
    SCRS(c_getf_current);
    SCRS(c_getf_current_binding);
    SCRS(c_getf_heaviside);
    SCRS(c_getf_set);
    SCRS(c_getf_set_range);
3379
    SCRS(c_getf_set_range_reverse);
3380 3381
    SCRS(c_getf_get_both);
    SCRS(c_getf_get_both_range);
3382
    SCRS(c_getf_get_both_range_reverse);
Yoni Fogel's avatar
Yoni Fogel committed
3383
#undef SCRS
3384 3385 3386

#if !TOKUDB_NATIVE_H
    MALLOC(result->i); // otherwise it is allocated as part of result->ii
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3387
    assert(result->i);
3388
#endif
3389
    result->dbp = db;
3390 3391 3392
    dbc_struct_i(result)->txn = txn;
    dbc_struct_i(result)->skey_s = (struct simple_dbt){0,0};
    dbc_struct_i(result)->sval_s = (struct simple_dbt){0,0};
3393
    if (is_temporary_cursor) {
3394 3395
	dbc_struct_i(result)->skey = &db->i->skey;
	dbc_struct_i(result)->sval = &db->i->sval;
3396
    } else {
3397 3398
	dbc_struct_i(result)->skey = &dbc_struct_i(result)->skey_s;
	dbc_struct_i(result)->sval = &dbc_struct_i(result)->sval_s;
3399
    }
3400
    int r = toku_brt_cursor(db->i->brt, &dbc_struct_i(result)->c, db->dbenv->i->logger);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3401
    assert(r == 0);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3402 3403 3404 3405
    *c = result;
    return 0;
}

3406 3407
static int
toku_db_delboth(DB *db, DB_TXN *txn, DBT *key, DBT *val, u_int32_t flags) {
3408
    HANDLE_PANICKED_DB(db);
3409
    HANDLE_DB_ILLEGAL_WORKING_PARENT_TXN(db, txn);
3410
    num_deletes++;   // accountability 
3411 3412
    u_int32_t unchecked_flags = flags;
    //DB_DELETE_ANY means delete regardless of whether it exists in the db.
3413
    BOOL error_if_missing = (BOOL)(!(flags&DB_DELETE_ANY));
3414
    unchecked_flags &= ~DB_DELETE_ANY;
3415
    u_int32_t lock_flags = get_prelocked_flags(flags, txn, db);
3416
    unchecked_flags &= ~lock_flags;
3417
    BOOL do_locking = (BOOL)(db->i->lt && !(lock_flags&DB_PRELOCKED_WRITE));
3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431
    int r = 0;
    if (unchecked_flags!=0) r = EINVAL;
    if (r==0 && error_if_missing) {
        //Check if the key exists in the db.
        r = db_getf_get_both(db, txn, lock_flags, key, val, ydb_getf_do_nothing, NULL);
    }
    if (r==0 && do_locking) {
        //Do locking if necessary.
        RANGE_LOCK_REQUEST_S request;
        //Left end of range == right end of range (point lock)
        write_lock_request_init(&request, txn, db,
                                key, val,
                                key, val);
        r = grab_range_lock(&request);
Yoni Fogel's avatar
Yoni Fogel committed
3432
    }
3433 3434
    if (r==0) {
        //Do the actual deleting.
3435
        r = toku_brt_delete_both(db->i->brt, key, val, txn ? db_txn_struct_i(txn)->tokutxn : NULL);
Yoni Fogel's avatar
Yoni Fogel committed
3436
    }
3437
    return r;
Yoni Fogel's avatar
Yoni Fogel committed
3438 3439
}

Rich Prohaska's avatar
Rich Prohaska committed
3440 3441 3442 3443
static inline int db_thread_need_flags(DBT *dbt) {
    return (dbt->flags & (DB_DBT_MALLOC+DB_DBT_REALLOC+DB_DBT_USERMEM)) == 0;
}

3444
static int toku_db_get (DB * db, DB_TXN * txn, DBT * key, DBT * data, u_int32_t flags) {
3445
    HANDLE_PANICKED_DB(db);
3446
    HANDLE_DB_ILLEGAL_WORKING_PARENT_TXN(db, txn);
Yoni Fogel's avatar
Yoni Fogel committed
3447
    int r;
3448

Rich Prohaska's avatar
Rich Prohaska committed
3449
    if ((db->i->open_flags & DB_THREAD) && db_thread_need_flags(data))
3450 3451
        return EINVAL;

3452
    u_int32_t lock_flags = get_prelocked_flags(flags, txn, db);
Yoni Fogel's avatar
Yoni Fogel committed
3453
    flags &= ~lock_flags;
Yoni Fogel's avatar
Yoni Fogel committed
3454 3455 3456 3457
    if (flags != 0 && flags != DB_GET_BOTH) return EINVAL;
    // We aren't ready to handle flags such as DB_READ_COMMITTED or DB_READ_UNCOMMITTED or DB_RMW

    DBC *dbc;
3458
    r = toku_db_cursor(db, txn, &dbc, 0, 1);
Yoni Fogel's avatar
Yoni Fogel committed
3459
    if (r!=0) return r;
Yoni Fogel's avatar
Yoni Fogel committed
3460 3461
    u_int32_t c_get_flags = (flags == 0) ? DB_SET : DB_GET_BOTH;
    r = toku_c_get(dbc, key, data, c_get_flags | lock_flags);
Yoni Fogel's avatar
Yoni Fogel committed
3462 3463
    int r2 = toku_c_close(dbc);
    return r ? r : r2;
3464 3465
}

Rich Prohaska's avatar
Rich Prohaska committed
3466
#if 0
3467
static int toku_db_key_range(DB * db, DB_TXN * txn, DBT * dbt, DB_KEY_RANGE * kr, u_int32_t flags) {
3468
    HANDLE_PANICKED_DB(db);
3469
    HANDLE_DB_ILLEGAL_WORKING_PARENT_TXN(db, txn);
3470
    txn=txn; dbt=dbt; kr=kr; flags=flags;
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3471
    toku_ydb_barf();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3472
    abort();
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3473
}
Rich Prohaska's avatar
Rich Prohaska committed
3474
#endif
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3475

3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493
static char *construct_full_name(int count, ...) {
    va_list ap;
    char *name = NULL;
    size_t n = 0;
    int i;
    va_start(ap, count);
    for (i=0; i<count; i++) {
        char *arg = va_arg(ap, char *);
        if (arg) {
            n += 1 + strlen(arg) + 1;
            char *newname = toku_malloc(n);
            assert(newname);
            if (name && !toku_os_is_absolute_name(arg))
                snprintf(newname, n, "%s/%s", name, arg);
            else
                snprintf(newname, n, "%s", arg);
            toku_free(name);
            name = newname;
Yoni Fogel's avatar
Yoni Fogel committed
3494 3495 3496
        }
    }

3497
    return name;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3498 3499
}

Yoni Fogel's avatar
Yoni Fogel committed
3500
static int toku_db_lt_panic(DB* db, int r) {
3501
    assert(r!=0);
Yoni Fogel's avatar
Yoni Fogel committed
3502 3503
    assert(db && db->i && db->dbenv && db->dbenv->i);
    DB_ENV* env = db->dbenv;
3504 3505 3506 3507 3508
    env->i->is_panicked = r;

    if (r < 0) env->i->panic_string = toku_strdup(toku_lt_strerror((TOKU_LT_ERROR)r));
    else       env->i->panic_string = toku_strdup("Error in locktree.\n");

3509
    return toku_ydb_do_error(env, r, "%s", env->i->panic_string);
Yoni Fogel's avatar
Yoni Fogel committed
3510 3511
}

Yoni Fogel's avatar
Yoni Fogel committed
3512
static int toku_txn_add_lt(DB_TXN* txn, toku_lock_tree* lt) {
Yoni Fogel's avatar
Yoni Fogel committed
3513
    int r = ENOSYS;
Yoni Fogel's avatar
Yoni Fogel committed
3514
    assert(txn && lt);
3515
    toku_lth* lth = db_txn_struct_i(txn)->lth;
Yoni Fogel's avatar
Yoni Fogel committed
3516 3517 3518 3519 3520
    assert(lth);

    toku_lock_tree* find = toku_lth_find(lth, lt);
    if (find) {
        assert(find == lt);
Yoni Fogel's avatar
Yoni Fogel committed
3521 3522
        r = 0;
        goto cleanup;
Yoni Fogel's avatar
Yoni Fogel committed
3523
    }
Yoni Fogel's avatar
Yoni Fogel committed
3524 3525 3526 3527 3528 3529
    r = toku_lth_insert(lth, lt);
    if (r != 0) { goto cleanup; }
    
    toku_lt_add_ref(lt);
    r = 0;
cleanup:
Yoni Fogel's avatar
Yoni Fogel committed
3530 3531 3532
    return r;
}

Yoni Fogel's avatar
Yoni Fogel committed
3533 3534 3535
static toku_dbt_cmp toku_db_get_compare_fun(DB* db) {
    return db->i->brt->compare_fun;
}
Yoni Fogel's avatar
Yoni Fogel committed
3536

Yoni Fogel's avatar
Yoni Fogel committed
3537 3538
static toku_dbt_cmp toku_db_get_dup_compare(DB* db) {
    return db->i->brt->dup_compare;
Yoni Fogel's avatar
Yoni Fogel committed
3539 3540
}

3541 3542 3543 3544 3545 3546
static int toku_db_fd(DB *db, int *fdp) {
    HANDLE_PANICKED_DB(db);
    if (!db_opened(db)) return EINVAL;
    return toku_brt_get_fd(db->i->brt, fdp);
}

3547 3548 3549 3550 3551
static int
db_open_subdb(DB * db, DB_TXN * txn, const char *fname, const char *dbname, DBTYPE dbtype, u_int32_t flags, int mode) {
    int r;
    if (!fname || !dbname) r = EINVAL;
    else {
3552 3553 3554 3555 3556 3557
        char subdb_full_name[strlen(fname) + sizeof("/") + strlen(dbname)];
        int bytes = snprintf(subdb_full_name, sizeof(subdb_full_name), "%s/%s", fname, dbname);
        assert(bytes==(int)sizeof(subdb_full_name)-1);
        const char *null_subdbname = NULL;
        r = toku_db_open(db, txn, subdb_full_name, null_subdbname, dbtype, flags, mode);
    }
3558 3559
    return r;
}
3560

3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576
static void
create_iname_hint(const char *dname, char *hint) {
    //Requires: size of hint array must be > strlen(dname)
    //Copy alphanumeric characters only.
    //Replace strings of non-alphanumeric characters with a single underscore.
    BOOL underscored = FALSE;
    while (*dname) {
        if (isalnum(*dname)) {
            *hint++ = *dname++;
            underscored = FALSE;
        }
        else {
            if (!underscored)
                *hint++ = '_';
            dname++;
            underscored = TRUE;
3577 3578
        }
    }
3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598
    *hint = '\0';
}

static char *
create_iname(DB_ENV *env, u_int64_t id, char *hint) {
    char inamebase[strlen(hint) +
		   8 +  // hex version
		   16 + // hex id
		   sizeof("__.tokudb")]; // extra pieces
    int bytes = snprintf(inamebase, sizeof(inamebase), "%s_%"PRIx64"_%"PRIx32".tokudb", hint, id, BRT_LAYOUT_VERSION);
    assert(bytes>0);
    assert(bytes<=(int)sizeof(inamebase)-1);
    char *rval;
    //TODO: #2037 add 'tokudb.dictionaries' directory inside data_dir!!!
    if (env->i->data_dir)
        rval = construct_full_name(2, env->i->data_dir, inamebase);
    else
        rval = construct_full_name(1, inamebase);
    assert(rval);
    return rval;
3599 3600
}

3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613

static int db_open_iname(DB * db, DB_TXN * txn, const char *iname, u_int32_t flags, int mode);


// inames are created here.
// algorithm:
//  begin txn
//  convert dname to iname (possibly creating new iname)
//  open file (toku_brt_open() will handle logging)
//  close txn
//  if created a new iname, take full range lock
static int 
toku_db_open(DB * db, DB_TXN * txn, const char *fname, const char *dbname, DBTYPE dbtype, u_int32_t flags, int mode) {
3614
    HANDLE_PANICKED_DB(db);
3615
    HANDLE_DB_ILLEGAL_WORKING_PARENT_TXN(db, txn);
3616
    if (dbname!=NULL) 
3617
        return db_open_subdb(db, txn, fname, dbname, dbtype, flags, mode);
3618

3619
    // at this point fname is the dname
3620 3621
    //This code ONLY supports single-db files.
    assert(dbname==NULL);
3622
    const char * dname = fname;  // db_open_subdb() converts (fname, dbname) to dname
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3623

3624 3625 3626
    ////////////////////////////// do some level of parameter checking.
    u_int32_t unused_flags = flags;
    int using_txns = db->dbenv->i->open_flags & DB_INIT_TXN;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3627
    int r;
Yoni Fogel's avatar
Yoni Fogel committed
3628
    if (dbtype!=DB_BTREE && dbtype!=DB_UNKNOWN) return EINVAL;
3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653
    int is_db_excl    = flags & DB_EXCL;    unused_flags&=~DB_EXCL;
    int is_db_create  = flags & DB_CREATE;  unused_flags&=~DB_CREATE;

    //We support READ_UNCOMMITTED whether or not the flag is provided.
                                            unused_flags&=~DB_READ_UNCOMMITTED;
    if (unused_flags & ~DB_THREAD) return EINVAL; // unknown flags

    if (is_db_excl && !is_db_create) return EINVAL;
    if (dbtype==DB_UNKNOWN && is_db_excl) return EINVAL;

    /* tokudb supports no duplicates and sorted duplicates only */
    unsigned int tflags;
    r = toku_brt_get_flags(db->i->brt, &tflags);
    if (r != 0) 
        return r;
    if ((tflags & TOKU_DB_DUP) && !(tflags & TOKU_DB_DUPSORT))
        return EINVAL;

    if (db_opened(db))
        return EINVAL;              /* It was already open. */
    //////////////////////////////

    DB_TXN *child = NULL;
    // begin child (unless transactionless)
    if (using_txns) {
3654
	r = toku_txn_begin(db->dbenv, txn, &child, DB_TXN_NOSYNC, 1);
3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730
	assert(r==0);
    }

    // convert dname to iname
    //  - look up dname, get iname
    //  - if dname does not exist, create iname and make entry in directory
    DBT dname_dbt;  // holds dname
    DBT iname_dbt;  // holds iname
    toku_fill_dbt(&dname_dbt, dname, strlen(dname)+1);
    init_dbt_realloc(&iname_dbt);  // sets iname_dbt.data = NULL
    r = toku_db_get(db->dbenv->i->directory, child, &dname_dbt, &iname_dbt, 0);  // allocates memory for iname
    char *iname = iname_dbt.data;
    if (r==DB_NOTFOUND && !is_db_create)
        r = ENOENT;
    else if (r==0 && is_db_excl) {
        r = EEXIST;
    }
    else if (r==DB_NOTFOUND) {
	char hint[strlen(dname) + 1];

	// create iname and make entry in directory
	u_int64_t id = 0;
	
	if (using_txns)
	    id = toku_txn_get_txnid(db_txn_struct_i(child)->tokutxn);
	create_iname_hint(dname, hint);
        iname = create_iname(db->dbenv, id, hint);  // allocated memory for iname
        toku_fill_dbt(&iname_dbt, iname, strlen(iname) + 1);
        r = toku_db_put(db->dbenv->i->directory, child, &dname_dbt, &iname_dbt, DB_YESOVERWRITE);  // DB_YESOVERWRITE for performance only, avoid unnecessary query
    }

    // we now have an iname
    if (r == 0) {
	r = db_open_iname(db, child, iname, flags, mode);
        if (r==0) {
            db->i->dname = toku_xstrdup(dname);
            env_note_db_opened(db->dbenv, db);  // tell env that a new db handle is open (using dname)
        }
    }

    // free string holding iname
    if (iname) toku_free(iname);

    if (using_txns) {
	// close txn
	if (r == 0) {  // commit
	    r = toku_txn_commit(child, DB_TXN_NOSYNC);
	    assert(r==0);  // TODO panic
	}
	else {         // abort
	    int r2 = toku_txn_abort(child);
	    assert(r2==0);  // TODO panic
	}
    }

    return r;
}

static int 
db_open_iname(DB * db, DB_TXN * txn, const char *iname, u_int32_t flags, int mode) {
    int r;

    //Set comparison functions if not yet set.
    if (!db->i->key_compare_was_set && db->dbenv->i->bt_compare) {
        r = toku_brt_set_bt_compare(db->i->brt, db->dbenv->i->bt_compare);
        assert(r==0);
        db->i->key_compare_was_set = TRUE;
    }
    if (!db->i->val_compare_was_set && db->dbenv->i->dup_compare) {
        r = toku_brt_set_dup_compare(db->i->brt, db->dbenv->i->dup_compare);
        assert(r==0);
        db->i->val_compare_was_set = TRUE;
    }
    BOOL need_locktree = (BOOL)((db->dbenv->i->open_flags & DB_INIT_LOCK) &&
                                (db->dbenv->i->open_flags & DB_INIT_TXN));

3731 3732
    int is_db_excl    = flags & DB_EXCL;    flags&=~DB_EXCL;
    int is_db_create  = flags & DB_CREATE;  flags&=~DB_CREATE;
3733 3734
    //We support READ_UNCOMMITTED whether or not the flag is provided.
                                            flags&=~DB_READ_UNCOMMITTED;
3735
    if (flags & ~DB_THREAD) return EINVAL; // unknown flags
3736 3737

    if (is_db_excl && !is_db_create) return EINVAL;
3738

3739 3740 3741 3742 3743 3744 3745 3746
    /* tokudb supports no duplicates and sorted duplicates only */
    unsigned int tflags;
    r = toku_brt_get_flags(db->i->brt, &tflags);
    if (r != 0) 
        return r;
    if ((tflags & TOKU_DB_DUP) && !(tflags & TOKU_DB_DUPSORT))
        return EINVAL;

3747
    if (db_opened(db))
3748
        return EINVAL;              /* It was already open. */
Yoni Fogel's avatar
Yoni Fogel committed
3749
    
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3750 3751
    db->i->open_flags = flags;
    db->i->open_mode = mode;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3752

3753 3754 3755
    char *iname_from_cwd = construct_full_name(2, db->dbenv->i->dir, iname); // allocates memory for iname_from_cwd
    assert(iname_from_cwd);
    r = toku_brt_open(db->i->brt, iname_from_cwd, iname,
3756
		      is_db_create, is_db_excl,
3757
		      db->dbenv->i->cachetable,
3758
		      txn ? db_txn_struct_i(txn)->tokutxn : NULL_TXN,
3759
		      db);
3760
    toku_free(iname_from_cwd);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3761 3762 3763
    if (r != 0)
        goto error_cleanup;

3764
    db->i->opened = 1;
Yoni Fogel's avatar
Yoni Fogel committed
3765
    if (need_locktree) {
Yoni Fogel's avatar
Yoni Fogel committed
3766 3767 3768
        unsigned int brtflags;
        BOOL dups;
        toku_brt_get_flags(db->i->brt, &brtflags);
3769
        dups = (BOOL)((brtflags & TOKU_DB_DUPSORT || brtflags & TOKU_DB_DUP));
Yoni Fogel's avatar
Yoni Fogel committed
3770

3771 3772 3773 3774
        int db_fd;
        r = toku_db_fd(db, &db_fd);
        if (r!=0) goto error_cleanup;
        assert(db_fd>=0);
3775
        r = toku_db_id_create(&db->i->db_id, db_fd);
Yoni Fogel's avatar
Yoni Fogel committed
3776 3777 3778
        if (r!=0) { goto error_cleanup; }
        r = toku_ltm_get_lt(db->dbenv->i->ltm, &db->i->lt, dups, db->i->db_id);
        if (r!=0) { goto error_cleanup; }
Yoni Fogel's avatar
Yoni Fogel committed
3779
    }
3780 3781 3782
    //Add to transaction's list of 'must close' if necessary.
    if (txn) {
        //Do last so we don't have to undo.
3783
        toku_list_push(&db_txn_struct_i(txn)->dbs_that_must_close_before_abort,
3784 3785
                  &db->i->dbs_that_must_close_before_abort);
    }
Yoni Fogel's avatar
Yoni Fogel committed
3786

Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3787
    return 0;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3788 3789
 
error_cleanup:
Yoni Fogel's avatar
Yoni Fogel committed
3790
    if (db->i->db_id) {
3791
        toku_db_id_remove_ref(&db->i->db_id);
Yoni Fogel's avatar
Yoni Fogel committed
3792 3793
        db->i->db_id = NULL;
    }
3794
    db->i->opened = 0;
Yoni Fogel's avatar
Yoni Fogel committed
3795
    if (db->i->lt) {
Yoni Fogel's avatar
Yoni Fogel committed
3796
        toku_lt_remove_ref(db->i->lt);
Yoni Fogel's avatar
Yoni Fogel committed
3797 3798
        db->i->lt = NULL;
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3799
    return r;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3800
}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
3801

3802 3803 3804 3805 3806
//Return 0 if proposed pair do not violate size constraints of DB
//(insertion is legal)
//Return non zero otherwise.
static int
db_put_check_size_constraints(DB *db, DBT *key, DBT *val) {
3807
    int r;
3808

3809
    BOOL dupsort = (BOOL)(!db_is_nodup(db));
3810
    //Check limits on size of key and val.
3811
    unsigned int nodesize;
3812
    r = toku_brt_get_nodesize(db->i->brt, &nodesize); assert(r == 0);
3813
    u_int32_t limit;
3814

3815
    if (dupsort) {
3816 3817
        limit = nodesize / BRT_FANOUT;
        if (key->size + val->size > limit)
3818
            r = toku_ydb_do_error(db->dbenv, EINVAL, "The largest row (key + val) allowed is %u bytes", limit);
3819
    } else {
3820
        limit = nodesize / BRT_FANOUT;
3821 3822 3823 3824
        if (key->size > limit)
            r = toku_ydb_do_error(db->dbenv, EINVAL, "The largest key allowed is %u bytes", limit);
        else if (val->size > nodesize)
            r = toku_ydb_do_error(db->dbenv, EINVAL, "The largest value allowed is %u bytes", nodesize);
Yoni Fogel's avatar
Yoni Fogel committed
3825
    }
3826 3827 3828
    return r;
}

3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849
//Return 0 if supported.
//Return ERANGE if out of range.
static int
db_row_size_supported(DB *db, u_int32_t size) {
    DBT key, val;

    toku_fill_dbt(&key, NULL, size);
    toku_fill_dbt(&val, NULL, 0);
    int r = db_put_check_size_constraints(db, &key, &val);
    if (r!=0) r = ERANGE;
    return r;
}

static int
locked_db_row_size_supported(DB *db, u_int32_t size) {
    toku_ydb_lock();
    int r = db_row_size_supported(db, size);
    toku_ydb_unlock();
    return r;
}

3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872
//Return 0 if insert is legal
static int
db_put_check_overwrite_constraint(DB *db, DB_TXN *txn, DBT *key, DBT *UU(val),
                                  u_int32_t lock_flags, u_int32_t overwrite_flag) {
    int r;

    //DB_YESOVERWRITE does not impose constraints.
    if (overwrite_flag==DB_YESOVERWRITE) r = 0;
    else if (overwrite_flag==DB_NOOVERWRITE) {
        //Check if (key,anything) exists in dictionary.
        //If exists, fail.  Otherwise, do insert.
        r = db_getf_set(db, txn, lock_flags, key, ydb_getf_do_nothing, NULL);
        if (r==DB_NOTFOUND) r = 0;
        else if (r==0)      r = DB_KEYEXIST;
        //Any other error is passed through.
    }
    else if (overwrite_flag==0) {
        //in a nodup db:   overwrite_flag==0 is an alias for DB_YESOVERWRITE
        //in a dupsort db: overwrite_flag==0 is an error
        if (db_is_nodup(db)) r = 0;
        else {
            r = toku_ydb_do_error(db->dbenv, EINVAL, "Tokudb requires that db->put specify DB_YESOVERWRITE or DB_NOOVERWRITE on DB_DUPSORT databases");
        }
3873
    }
3874 3875 3876
    else {
        //Other flags are not (yet) supported.
        r = EINVAL;
3877 3878 3879 3880
    }
    return r;
}

3881 3882
static int
toku_db_put(DB *db, DB_TXN *txn, DBT *key, DBT *val, u_int32_t flags) {
3883
    HANDLE_PANICKED_DB(db);
3884
    HANDLE_DB_ILLEGAL_WORKING_PARENT_TXN(db, txn);
3885 3886
    int r;

3887
    num_inserts++;
3888
    u_int32_t lock_flags = get_prelocked_flags(flags, txn, db);
3889
    flags &= ~lock_flags;
3890
    BOOL do_locking = (BOOL)(db->i->lt && !(lock_flags&DB_PRELOCKED_WRITE));
3891

3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904
    r = db_put_check_size_constraints(db, key, val);
    if (r==0) {
        //Do any checking required by the flags.
        r = db_put_check_overwrite_constraint(db, txn, key, val, lock_flags, flags);
    }
    if (r==0 && do_locking) {
        //Do locking if necessary.
        RANGE_LOCK_REQUEST_S request;
        //Left end of range == right end of range (point lock)
        write_lock_request_init(&request, txn, db,
                                key, val,
                                key, val);
        r = grab_range_lock(&request);
3905
    }
3906 3907
    if (r==0) {
        //Insert into the brt.
3908
        r = toku_brt_insert(db->i->brt, key, val, txn ? db_txn_struct_i(txn)->tokutxn : 0);
3909 3910
    }
    return r;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3911
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3912

3913 3914
static int toku_db_remove(DB * db, const char *fname, const char *dbname, u_int32_t flags);

3915 3916

//We do not (yet?) support deleting subdbs by deleting the enclosing 'fname'
3917
static int
3918 3919 3920 3921
env_dbremove_subdb(DB_ENV * env, DB_TXN * txn, const char *fname, const char *dbname, int32_t flags) {
    int r;
    if (!fname || !dbname) r = EINVAL;
    else {
3922 3923 3924 3925
        char subdb_full_name[strlen(fname) + sizeof("/") + strlen(dbname)];
        int bytes = snprintf(subdb_full_name, sizeof(subdb_full_name), "%s/%s", fname, dbname);
        assert(bytes==(int)sizeof(subdb_full_name)-1);
        const char *null_subdbname = NULL;
3926
        r = toku_env_dbremove(env, txn, subdb_full_name, null_subdbname, flags);
3927
    }
3928 3929
    return r;
}
3930

3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974

//Called during committing an fdelete ONLY IF you still have an fd AND it is not connected to /dev/null
//Called during aborting an fcreate (harmless to do, and definitely correct)
static void
finalize_file_removal(int fd, void * extra) {
    int r;
    toku_ltm *ltm = (toku_ltm*) extra;
    if (ltm) {
        toku_db_id *id;
        r = toku_db_id_create(&id, fd);
        assert(r==0);

        //Poison the lock tree to prevent a future file from re-using it.
        toku_ltm_invalidate_lt(ltm, id);
        toku_db_id_remove_ref(&id);
    }
}

static int
toku_env_dbremove(DB_ENV * env, DB_TXN *txn, const char *fname, const char *dbname, u_int32_t flags) {
    int r;
    HANDLE_PANICKED_ENV(env);
    HANDLE_ILLEGAL_WORKING_PARENT_TXN(env, txn);
    if (!env_opened(env)) return EINVAL;
    if (dbname!=NULL) 
        return env_dbremove_subdb(env, txn, fname, dbname, flags);
    // env_dbremove_subdb() converts (fname, dbname) to dname

    const char * dname = fname;
    assert(dbname == NULL);

    if (flags!=0) return EINVAL;
    if (env_is_db_with_dname_open(env, dname))
        return toku_ydb_do_error(env, EINVAL, "Cannot remove dictionary with an open handle.\n");
    
    DBT dname_dbt;  
    DBT iname_dbt;  
    toku_fill_dbt(&dname_dbt, dname, strlen(dname)+1);
    init_dbt_realloc(&iname_dbt);  // sets iname_dbt.data = NULL

    int using_txns = env->i->open_flags & DB_INIT_TXN;
    DB_TXN *child = NULL;
    // begin child (unless transactionless)
    if (using_txns) {
3975
	r = toku_txn_begin(env, txn, &child, DB_TXN_NOSYNC, 1);
3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995
	assert(r==0);
    }

    // get iname
    r = toku_db_get(env->i->directory, child, &dname_dbt, &iname_dbt, 0);  // allocates memory for iname
    char *iname = iname_dbt.data;
    if (r==DB_NOTFOUND)
        r = ENOENT;
    else if (r==0) {
	// remove (dname,iname) from directory
	r = toku_db_del(env->i->directory, child, &dname_dbt, DB_DELETE_ANY);
	if (r == 0) {
	    char *iname_within_cwd = construct_full_name(2, env->i->dir, iname_dbt.data);  
	    assert(iname_within_cwd);
	    DBT iname_within_cwd_dbt;
	    toku_fill_dbt(&iname_within_cwd_dbt, iname_within_cwd, strlen(iname_within_cwd)+1);
            if (using_txns) {
                r = toku_brt_remove_on_commit(db_txn_struct_i(child)->tokutxn,
                                              &iname_dbt, &iname_within_cwd_dbt);
		assert(r==0);
3996 3997 3998
                //Now that we have a writelock on dname, verify that there are still no handles open. (to prevent race conditions)
                if (r==0 && env_is_db_with_dname_open(env, dname))
                    r = toku_ydb_do_error(env, EINVAL, "Cannot remove dictionary with an open handle.\n");
3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017
            }
            else {
                r = toku_brt_remove_now(env->i->cachetable, &iname_dbt, &iname_within_cwd_dbt);
		assert(r==0);
            }
	    toku_free(iname_within_cwd);
	}
    }

    if (using_txns) {
	// close txn
	if (r == 0) {  // commit
	    r = toku_txn_commit(child, DB_TXN_NOSYNC);
	    assert(r==0);  // TODO panic
	}
	else {         // abort
	    int r2 = toku_txn_abort(child);
	    assert(r2==0);  // TODO panic
	}
4018
    }
4019 4020

    if (iname) toku_free(iname);
4021
    return r;
4022

4023 4024
}

4025 4026 4027

static int
toku_db_remove(DB * db, const char *fname, const char *dbname, u_int32_t flags) {
4028
    HANDLE_PANICKED_DB(db);
4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049
    DB_TXN *null_txn = NULL;
    int r  = toku_env_dbremove(db->dbenv, null_txn, fname, dbname, flags);
    int r2 = toku_db_close(db, 0);
    if (r==0) r = r2;
    return r;
}

static int
env_dbrename_subdb(DB_ENV *env, DB_TXN *txn, const char *fname, const char *dbname, const char *newname, u_int32_t flags) {
    int r;
    if (!fname || !dbname || !newname) r = EINVAL;
    else {
        char subdb_full_name[strlen(fname) + sizeof("/") + strlen(dbname)];
        {
            int bytes = snprintf(subdb_full_name, sizeof(subdb_full_name), "%s/%s", fname, dbname);
            assert(bytes==(int)sizeof(subdb_full_name)-1);
        }
        char new_full_name[strlen(fname) + sizeof("/") + strlen(dbname)];
        {
            int bytes = snprintf(new_full_name, sizeof(new_full_name), "%s/%s", fname, dbname);
            assert(bytes==(int)sizeof(new_full_name)-1);
Yoni Fogel's avatar
Yoni Fogel committed
4050
        }
4051 4052
        const char *null_subdbname = NULL;
        r = toku_env_dbrename(env, txn, subdb_full_name, null_subdbname, new_full_name, flags);
Yoni Fogel's avatar
Yoni Fogel committed
4053
    }
4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075
    return r;
}


static int
toku_env_dbrename(DB_ENV *env, DB_TXN *txn, const char *fname, const char *dbname, const char *newname, u_int32_t flags) {
    int r;
    HANDLE_PANICKED_ENV(env);
    HANDLE_ILLEGAL_WORKING_PARENT_TXN(env, txn);
    if (!env_opened(env)) return EINVAL;
    if (dbname!=NULL) 
        return env_dbrename_subdb(env, txn, fname, dbname, newname, flags);
    // env_dbrename_subdb() converts (fname, dbname) to dname and (fname, newname) to newdname

    const char * dname = fname;
    assert(dbname == NULL);

    if (flags!=0) return EINVAL;
    if (env_is_db_with_dname_open(env, dname))
        return toku_ydb_do_error(env, EINVAL, "Cannot rename dictionary with an open handle.\n");
    if (env_is_db_with_dname_open(env, newname))
        return toku_ydb_do_error(env, EINVAL, "Cannot rename dictionary; Dictionary with target name has an open handle.\n");
Yoni Fogel's avatar
Yoni Fogel committed
4076
    
4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087
    DBT old_dname_dbt;  
    DBT new_dname_dbt;  
    DBT iname_dbt;  
    toku_fill_dbt(&old_dname_dbt, dname, strlen(dname)+1);
    toku_fill_dbt(&new_dname_dbt, newname, strlen(newname)+1);
    init_dbt_realloc(&iname_dbt);  // sets iname_dbt.data = NULL

    int using_txns = env->i->open_flags & DB_INIT_TXN;
    DB_TXN *child = NULL;
    // begin child (unless transactionless)
    if (using_txns) {
4088
	r = toku_txn_begin(env, txn, &child, DB_TXN_NOSYNC, 1);
4089 4090
	assert(r==0);
    }
4091

4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105
    r = toku_db_get(env->i->directory, child, &old_dname_dbt, &iname_dbt, 0);  // allocates memory for iname
    char *iname = iname_dbt.data;
    if (r==DB_NOTFOUND)
        r = ENOENT;
    else if (r==0) {
	// verify that newname does not already exist
	r = db_getf_set(env->i->directory, child, 0, &new_dname_dbt, ydb_getf_do_nothing, NULL);
	if (r == 0) 
	    r = EEXIST;
	else if (r == DB_NOTFOUND) {
	    // remove old (dname,iname) and insert (newname,iname) in directory
	    r = toku_db_del(env->i->directory, child, &old_dname_dbt, DB_DELETE_ANY);
	    if (r == 0)
		r = toku_db_put(env->i->directory, child, &new_dname_dbt, &iname_dbt, DB_YESOVERWRITE);
4106 4107 4108 4109 4110
            //Now that we have writelocks on both dnames, verify that there are still no handles open. (to prevent race conditions)
            if (r==0 && env_is_db_with_dname_open(env, dname))
                r = toku_ydb_do_error(env, EINVAL, "Cannot rename dictionary with an open handle.\n");
            if (r==0 && env_is_db_with_dname_open(env, newname))
                r = toku_ydb_do_error(env, EINVAL, "Cannot rename dictionary; Dictionary with target name has an open handle.\n");
4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127
	}
    }

    if (using_txns) {
	// close txn
	if (r == 0) {  // commit
	    r = toku_txn_commit(child, DB_TXN_NOSYNC);
	    assert(r==0);  // TODO panic
	}
	else {         // abort
	    int r2 = toku_txn_abort(child);
	    assert(r2==0);  // TODO panic
	}
    }

    if (iname) toku_free(iname);
    return r;
Yoni Fogel's avatar
Yoni Fogel committed
4128

Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
4129
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
4130

4131 4132
static int
toku_db_rename(DB * db, const char *fname, const char *dbname, const char *newname, u_int32_t flags) {
4133
    HANDLE_PANICKED_DB(db);
4134 4135 4136 4137 4138
    DB_TXN *null_txn = NULL;
    int r  = toku_env_dbrename(db->dbenv, null_txn, fname, dbname, newname, flags);
    int r2 = toku_db_close(db, 0);
    if (r==0) r = r2;
    return r;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
4139
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
4140

4141 4142 4143
// set key comparison function to function provided by user (pre-empting environment key comparison function)
static int
toku_db_set_bt_compare(DB * db, int (*bt_compare) (DB *, const DBT *, const DBT *)) {
4144
    HANDLE_PANICKED_DB(db);
4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156
    int r;
    if (db_opened(db))
        r = toku_ydb_do_error(db->dbenv, EINVAL, "Comparison functions cannot be set after DB open.\n");
    else if (!bt_compare)
        r = toku_ydb_do_error(db->dbenv, EINVAL, "Comparison functions cannot be NULL.\n");
    else if (db->i->key_compare_was_set)
        r = toku_ydb_do_error(db->dbenv, EINVAL, "Key comparison function already set.\n");
    else {
        r = toku_brt_set_bt_compare(db->i->brt, bt_compare);
        if (!r)
            db->i->key_compare_was_set = TRUE;
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
4157 4158 4159
    return r;
}

4160 4161 4162
// set val comparison function to function provided by user (pre-empting environment val comparison function)
static int
toku_db_set_dup_compare(DB *db, int (*dup_compare)(DB *, const DBT *, const DBT *)) {
4163
    HANDLE_PANICKED_DB(db);
4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175
    int r;
    if (db_opened(db))
        r = toku_ydb_do_error(db->dbenv, EINVAL, "Comparison functions cannot be set after DB open.\n");
    else if (!dup_compare)
        r = toku_ydb_do_error(db->dbenv, EINVAL, "Comparison functions cannot be NULL.\n");
    else if (db->i->val_compare_was_set)
        r = toku_ydb_do_error(db->dbenv, EINVAL, "Val comparison function already set.\n");
    else {
        r = toku_brt_set_dup_compare(db->i->brt, dup_compare);
        if (!r)
            db->i->val_compare_was_set = TRUE;
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
4176 4177 4178
    return r;
}

4179
static int toku_db_set_descriptor(DB *db, u_int32_t version, const DBT* descriptor, toku_dbt_upgradef dbt_userformat_upgrade) {
4180 4181 4182 4183 4184
    HANDLE_PANICKED_DB(db);
    int r;
    if (db_opened(db)) return EINVAL;
    else if (!descriptor) r = EINVAL;
    else if (descriptor->size>0 && !descriptor->data) r = EINVAL;
4185
    else r = toku_brt_set_descriptor(db->i->brt, version, descriptor, dbt_userformat_upgrade);
4186 4187 4188
    return r;
}

Rich Prohaska's avatar
Rich Prohaska committed
4189
static int toku_db_set_flags(DB *db, u_int32_t flags) {
4190
    HANDLE_PANICKED_DB(db);
4191

Rich Prohaska's avatar
Rich Prohaska committed
4192
    /* the following matches BDB */
4193 4194
    if (db_opened(db) && flags != 0) return EINVAL;

Yoni Fogel's avatar
Yoni Fogel committed
4195 4196 4197 4198
    u_int32_t tflags;
    int r = toku_brt_get_flags(db->i->brt, &tflags);
    if (r!=0) return r;
    
4199
    if (flags & DB_DUP)
4200
        tflags |= TOKU_DB_DUP;
4201
    if (flags & DB_DUPSORT)
4202
        tflags |= TOKU_DB_DUPSORT;
Yoni Fogel's avatar
Yoni Fogel committed
4203
    r = toku_brt_set_flags(db->i->brt, tflags);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
4204 4205 4206
    return r;
}

4207
static int toku_db_get_flags(DB *db, u_int32_t *pflags) {
4208
    HANDLE_PANICKED_DB(db);
4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221
    if (!pflags) return EINVAL;
    u_int32_t tflags;
    u_int32_t flags = 0;
    int r = toku_brt_get_flags(db->i->brt, &tflags);
    if (r!=0) return r;
    if (tflags & TOKU_DB_DUP) {
        tflags &= ~TOKU_DB_DUP;
        flags  |= DB_DUP;
    }
    if (tflags & TOKU_DB_DUPSORT) {
        tflags &= ~TOKU_DB_DUPSORT;
        flags  |= DB_DUPSORT;
    }
4222 4223 4224 4225
    { // ignore internal flags
        tflags &= ~TOKU_DB_KEYCMP_BUILTIN;
        tflags &= ~TOKU_DB_VALCMP_BUILTIN; 
    }
4226 4227 4228 4229 4230
    assert(tflags == 0);
    *pflags = flags;
    return 0;
}

4231
static int toku_db_set_pagesize(DB *db, u_int32_t pagesize) {
4232
    HANDLE_PANICKED_DB(db);
4233
    int r = toku_brt_set_nodesize(db->i->brt, pagesize);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
4234
    return r;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
4235
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
4236

4237
static int toku_db_stat64(DB * db, DB_TXN *txn, DB_BTREE_STAT64 *s) {
4238
    HANDLE_PANICKED_DB(db);
4239
    HANDLE_DB_ILLEGAL_WORKING_PARENT_TXN(db, txn);
4240 4241 4242 4243 4244 4245 4246 4247 4248
    struct brtstat64_s brtstat;
    int r = toku_brt_stat64(db->i->brt, db_txn_struct_i(txn)->tokutxn, &brtstat);
    if (r==0) {
	s->bt_nkeys = brtstat.nkeys;
	s->bt_ndata = brtstat.ndata;
	s->bt_dsize = brtstat.dsize;
	s->bt_fsize = brtstat.fsize;
    }
    return r;
4249 4250 4251 4252 4253 4254
}
static int locked_db_stat64 (DB *db, DB_TXN *txn, DB_BTREE_STAT64 *s) {
    toku_ydb_lock();
    int r = toku_db_stat64(db, txn, s);
    toku_ydb_unlock();
    return r;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
4255 4256
}

Yoni Fogel's avatar
Yoni Fogel committed
4257
static int toku_db_key_range64(DB* db, DB_TXN* txn __attribute__((__unused__)), DBT* key, u_int64_t* less, u_int64_t* equal, u_int64_t* greater, int* is_exact) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4258
    HANDLE_PANICKED_DB(db);
4259
    HANDLE_DB_ILLEGAL_WORKING_PARENT_TXN(db, txn);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272

    // note that toku_brt_keyrange does not have a txn param
    // this will be fixed later
    // temporarily, because the caller, locked_db_keyrange, 
    // has the ydb lock, we are ok
    int r = toku_brt_keyrange(db->i->brt, key, less, equal, greater);
    if (r != 0) { goto cleanup; }
    // temporarily set is_exact to 0 because brt_keyrange does not have this parameter
    *is_exact = 0;
cleanup:
    return r;
}

4273
static int toku_db_pre_acquire_read_lock(DB *db, DB_TXN *txn, const DBT *key_left, const DBT *val_left, const DBT *key_right, const DBT *val_right) {
Yoni Fogel's avatar
Yoni Fogel committed
4274 4275
    HANDLE_PANICKED_DB(db);
    if (!db->i->lt || !txn) return EINVAL;
4276
    //READ_UNCOMMITTED transactions do not need read locks.
4277
    if (db_txn_struct_i(txn)->flags&DB_READ_UNCOMMITTED) return 0;
Yoni Fogel's avatar
Yoni Fogel committed
4278 4279 4280 4281

    DB_TXN* txn_anc = toku_txn_ancestor(txn);
    int r;
    if ((r=toku_txn_add_lt(txn_anc, db->i->lt))) return r;
4282
    TXNID id_anc = toku_txn_get_txnid(db_txn_struct_i(txn_anc)->tokutxn);
Yoni Fogel's avatar
Yoni Fogel committed
4283 4284 4285 4286 4287 4288 4289

    r = toku_lt_acquire_range_read_lock(db->i->lt, db, id_anc,
                                        key_left,  val_left,
                                        key_right, val_right);
    return r;
}

4290
static int toku_db_pre_acquire_table_lock(DB *db, DB_TXN *txn) {
Yoni Fogel's avatar
Yoni Fogel committed
4291 4292 4293 4294 4295 4296
    HANDLE_PANICKED_DB(db);
    if (!db->i->lt || !txn) return EINVAL;

    DB_TXN* txn_anc = toku_txn_ancestor(txn);
    int r;
    if ((r=toku_txn_add_lt(txn_anc, db->i->lt))) return r;
4297
    TXNID id_anc = toku_txn_get_txnid(db_txn_struct_i(txn_anc)->tokutxn);
Yoni Fogel's avatar
Yoni Fogel committed
4298 4299 4300 4301

    r = toku_lt_acquire_range_write_lock(db->i->lt, db, id_anc,
                                         toku_lt_neg_infinity, toku_lt_neg_infinity,
                                         toku_lt_infinity,     toku_lt_infinity);
4302
    if (r==0) {
4303
	r = toku_brt_note_table_lock(db->i->brt, db_txn_struct_i(txn)->tokutxn); // tell the BRT layer that the table is locked (so that it can reduce the amount of rollback (rolltmp) data.
4304 4305
    }

Yoni Fogel's avatar
Yoni Fogel committed
4306 4307
    return r;
}
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4308

Yoni Fogel's avatar
Yoni Fogel committed
4309 4310 4311
//TODO: DB_AUTO_COMMIT.
//TODO: Nowait only conditionally?
//TODO: NOSYNC change to SYNC if DB_ENV has something in set_flags
4312
static inline int toku_db_construct_autotxn(DB* db, DB_TXN **txn, BOOL* changed,
Yoni Fogel's avatar
Yoni Fogel committed
4313 4314 4315 4316 4317 4318 4319
                                            BOOL force_auto_commit) {
    assert(db && txn && changed);
    DB_ENV* env = db->dbenv;
    if (*txn || !(env->i->open_flags & DB_INIT_TXN)) {
        *changed = FALSE;
        return 0;
    }
4320
    BOOL nosync = (BOOL)(!force_auto_commit && !(env->i->open_flags & DB_AUTO_COMMIT));
Yoni Fogel's avatar
Yoni Fogel committed
4321
    u_int32_t txn_flags = DB_TXN_NOWAIT | (nosync ? DB_TXN_NOSYNC : 0);
4322
    int r = toku_txn_begin(env, NULL, txn, txn_flags, 1);
Yoni Fogel's avatar
Yoni Fogel committed
4323 4324 4325 4326 4327
    if (r!=0) return r;
    *changed = TRUE;
    return 0;
}

4328
static inline int toku_db_destruct_autotxn(DB_TXN *txn, int r, BOOL changed) {
Yoni Fogel's avatar
Yoni Fogel committed
4329 4330 4331 4332 4333 4334
    if (!changed) return r;
    if (r==0) return toku_txn_commit(txn, 0);
    toku_txn_abort(txn);
    return r; 
}

Rich Prohaska's avatar
Rich Prohaska committed
4335
static int locked_db_close(DB * db, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
4336
    toku_ydb_lock(); int r = toku_db_close(db, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
4337 4338
}

4339
static inline int autotxn_db_cursor(DB *db, DB_TXN *txn, DBC **c, u_int32_t flags) {
Yoni Fogel's avatar
Yoni Fogel committed
4340
    if (!txn && (db->dbenv->i->open_flags & DB_INIT_TXN)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
4341
        return toku_ydb_do_error(db->dbenv, EINVAL,
Yoni Fogel's avatar
Yoni Fogel committed
4342 4343
              "Cursors in a transaction environment must have transactions.\n");
    }
4344
    return toku_db_cursor(db, txn, c, flags, 0);
Yoni Fogel's avatar
Yoni Fogel committed
4345 4346
}

Rich Prohaska's avatar
Rich Prohaska committed
4347
static int locked_db_cursor(DB *db, DB_TXN *txn, DBC **c, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
4348
    toku_ydb_lock(); int r = autotxn_db_cursor(db, txn, c, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
4349 4350
}

4351
static inline int autotxn_db_del(DB* db, DB_TXN* txn, DBT* key,
Yoni Fogel's avatar
Yoni Fogel committed
4352 4353 4354 4355 4356 4357 4358 4359
                                 u_int32_t flags) {
    BOOL changed; int r;
    r = toku_db_construct_autotxn(db, &txn, &changed, FALSE);
    if (r!=0) return r;
    r = toku_db_del(db, txn, key, flags);
    return toku_db_destruct_autotxn(txn, r, changed);
}

Rich Prohaska's avatar
Rich Prohaska committed
4360
static int locked_db_del(DB * db, DB_TXN * txn, DBT * key, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
4361
    toku_ydb_lock(); int r = autotxn_db_del(db, txn, key, flags); toku_ydb_unlock(); return r;
Yoni Fogel's avatar
Yoni Fogel committed
4362 4363
}

Yoni Fogel's avatar
Yoni Fogel committed
4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376
static inline int autotxn_db_delboth(DB* db, DB_TXN* txn, DBT* key, DBT* val,
                                 u_int32_t flags) {
    BOOL changed; int r;
    r = toku_db_construct_autotxn(db, &txn, &changed, FALSE);
    if (r!=0) return r;
    r = toku_db_delboth(db, txn, key, val, flags);
    return toku_db_destruct_autotxn(txn, r, changed);
}

static int locked_db_delboth(DB *db, DB_TXN *txn, DBT *key,  DBT *val, u_int32_t flags) {
    toku_ydb_lock(); int r = autotxn_db_delboth(db, txn, key, val, flags); toku_ydb_unlock(); return r;
}

4377
static inline int autotxn_db_get(DB* db, DB_TXN* txn, DBT* key, DBT* data,
Yoni Fogel's avatar
Yoni Fogel committed
4378 4379 4380 4381 4382 4383
                                 u_int32_t flags) {
    BOOL changed; int r;
    r = toku_db_construct_autotxn(db, &txn, &changed, FALSE);
    if (r!=0) return r;
    r = toku_db_get(db, txn, key, data, flags);
    return toku_db_destruct_autotxn(txn, r, changed);
Rich Prohaska's avatar
Rich Prohaska committed
4384 4385 4386
}

static int locked_db_get (DB * db, DB_TXN * txn, DBT * key, DBT * data, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
4387
    toku_ydb_lock(); int r = autotxn_db_get(db, txn, key, data, flags); toku_ydb_unlock(); return r;
Yoni Fogel's avatar
Yoni Fogel committed
4388 4389
}

4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413
static inline int autotxn_db_getf_set (DB *db, DB_TXN *txn, u_int32_t flags, DBT *key, YDB_CALLBACK_FUNCTION f, void *extra) {
    BOOL changed; int r;
    r = toku_db_construct_autotxn(db, &txn, &changed, FALSE);
    if (r!=0) return r;
    r = db_getf_set(db, txn, flags, key, f, extra);
    return toku_db_destruct_autotxn(txn, r, changed);
}

static int locked_db_getf_set (DB *db, DB_TXN *txn, u_int32_t flags, DBT *key, YDB_CALLBACK_FUNCTION f, void *extra) {
    toku_ydb_lock(); int r = autotxn_db_getf_set(db, txn, flags, key, f, extra); toku_ydb_unlock(); return r;
}

static inline int autotxn_db_getf_get_both (DB *db, DB_TXN *txn, u_int32_t flags, DBT *key, DBT *val, YDB_CALLBACK_FUNCTION f, void *extra) {
    BOOL changed; int r;
    r = toku_db_construct_autotxn(db, &txn, &changed, FALSE);
    if (r!=0) return r;
    r = db_getf_get_both(db, txn, flags, key, val, f, extra);
    return toku_db_destruct_autotxn(txn, r, changed);
}

static int locked_db_getf_get_both (DB *db, DB_TXN *txn, u_int32_t flags, DBT *key, DBT *val, YDB_CALLBACK_FUNCTION f, void *extra) {
    toku_ydb_lock(); int r = autotxn_db_getf_get_both(db, txn, flags, key, val, f, extra); toku_ydb_unlock(); return r;
}

4414
static int locked_db_pre_acquire_read_lock(DB *db, DB_TXN *txn, const DBT *key_left, const DBT *val_left, const DBT *key_right, const DBT *val_right) {
Yoni Fogel's avatar
Yoni Fogel committed
4415 4416 4417 4418 4419 4420
    toku_ydb_lock();
    int r = toku_db_pre_acquire_read_lock(db, txn, key_left, val_left, key_right, val_right);
    toku_ydb_unlock();
    return r;
}

4421
static int locked_db_pre_acquire_table_lock(DB *db, DB_TXN *txn) {
Yoni Fogel's avatar
Yoni Fogel committed
4422 4423 4424 4425 4426 4427
    toku_ydb_lock();
    int r = toku_db_pre_acquire_table_lock(db, txn);
    toku_ydb_unlock();
    return r;
}

4428 4429 4430 4431
// truncate a database
// effect: remove all of the rows from a database
static int toku_db_truncate(DB *db, DB_TXN *txn, u_int32_t *row_count, u_int32_t flags) {
    HANDLE_PANICKED_DB(db);
4432
    HANDLE_DB_ILLEGAL_WORKING_PARENT_TXN(db, txn);
4433 4434
    int r;

4435 4436 4437 4438 4439 4440 4441
    u_int32_t unhandled_flags = flags;
    int ignore_cursors = 0;
    if (flags & DB_TRUNCATE_WITHCURSORS) {
        ignore_cursors = 1;
        unhandled_flags &= ~DB_TRUNCATE_WITHCURSORS;
    }

4442
    // dont support flags (yet)
4443
    if (unhandled_flags)
4444
        return EINVAL;
4445 4446
    // dont support cursors unless explicitly told to
    if (!ignore_cursors && toku_brt_get_cursor_count(db->i->brt) > 0)
4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457
        return EINVAL;

    // acquire a table lock
    if (txn) {
        r = toku_db_pre_acquire_table_lock(db, txn);
        if (r != 0)
            return r;
    }

    *row_count = 0;

4458
    r = toku_brt_truncate(db->i->brt);
4459 4460 4461 4462

    return r;
}

4463
static inline int autotxn_db_open(DB* db, DB_TXN* txn, const char *fname, const char *dbname, DBTYPE dbtype, u_int32_t flags, int mode) {
Yoni Fogel's avatar
Yoni Fogel committed
4464
    BOOL changed; int r;
4465
    r = toku_db_construct_autotxn(db, &txn, &changed, (BOOL)((flags & DB_AUTO_COMMIT) != 0));
Yoni Fogel's avatar
Yoni Fogel committed
4466 4467 4468
    if (r!=0) return r;
    r = toku_db_open(db, txn, fname, dbname, dbtype, flags & ~DB_AUTO_COMMIT, mode);
    return toku_db_destruct_autotxn(txn, r, changed);
Rich Prohaska's avatar
Rich Prohaska committed
4469 4470 4471
}

static int locked_db_open(DB *db, DB_TXN *txn, const char *fname, const char *dbname, DBTYPE dbtype, u_int32_t flags, int mode) {
4472 4473 4474 4475
    toku_multi_operation_client_lock(); //Cannot begin checkpoint
    toku_ydb_lock(); int r = autotxn_db_open(db, txn, fname, dbname, dbtype, flags, mode); toku_ydb_unlock();
    toku_multi_operation_client_unlock(); //Can now begin checkpoint
    return r;
Rich Prohaska's avatar
Rich Prohaska committed
4476 4477
}

4478
static inline int autotxn_db_put(DB* db, DB_TXN* txn, DBT* key, DBT* data,
Yoni Fogel's avatar
Yoni Fogel committed
4479
                                 u_int32_t flags) {
4480
    //{ unsigned i; printf("put %p keylen=%d key={", db, key->size); for(i=0; i<key->size; i++) printf("%d,", ((char*)key->data)[i]); printf("} datalen=%d data={", data->size); for(i=0; i<data->size; i++) printf("%d,", ((char*)data->data)[i]); printf("}\n"); }
Yoni Fogel's avatar
Yoni Fogel committed
4481 4482 4483 4484 4485 4486 4487
    BOOL changed; int r;
    r = toku_db_construct_autotxn(db, &txn, &changed, FALSE);
    if (r!=0) return r;
    r = toku_db_put(db, txn, key, data, flags);
    return toku_db_destruct_autotxn(txn, r, changed);
}

Rich Prohaska's avatar
Rich Prohaska committed
4488
static int locked_db_put(DB * db, DB_TXN * txn, DBT * key, DBT * data, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
4489
    toku_ydb_lock(); int r = autotxn_db_put(db, txn, key, data, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
4490 4491 4492
}

static int locked_db_remove(DB * db, const char *fname, const char *dbname, u_int32_t flags) {
4493
    toku_multi_operation_client_lock(); //Cannot begin checkpoint
4494 4495 4496
    toku_ydb_lock();
    int r = toku_db_remove(db, fname, dbname, flags);
    toku_ydb_unlock();
4497
    toku_multi_operation_client_unlock(); //Can now begin checkpoint
4498
    return r;
Rich Prohaska's avatar
Rich Prohaska committed
4499 4500 4501
}

static int locked_db_rename(DB * db, const char *namea, const char *nameb, const char *namec, u_int32_t flags) {
4502
    toku_multi_operation_client_lock(); //Cannot begin checkpoint
4503 4504 4505
    toku_ydb_lock();
    int r = toku_db_rename(db, namea, nameb, namec, flags);
    toku_ydb_unlock();
4506
    toku_multi_operation_client_unlock(); //Can now begin checkpoint
4507
    return r;
Rich Prohaska's avatar
Rich Prohaska committed
4508 4509 4510
}

static int locked_db_set_bt_compare(DB * db, int (*bt_compare) (DB *, const DBT *, const DBT *)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
4511
    toku_ydb_lock(); int r = toku_db_set_bt_compare(db, bt_compare); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
4512 4513 4514
}

static int locked_db_set_dup_compare(DB * db, int (*dup_compare) (DB *, const DBT *, const DBT *)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
4515
    toku_ydb_lock(); int r = toku_db_set_dup_compare(db, dup_compare); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
4516 4517
}

4518 4519 4520 4521 4522
static int locked_db_set_descriptor(DB *db, u_int32_t version, const DBT* descriptor, toku_dbt_upgradef dbt_userformat_upgrade) {
    toku_ydb_lock();
    int r = toku_db_set_descriptor(db, version, descriptor, dbt_userformat_upgrade);
    toku_ydb_unlock();
    return r;
4523 4524
}

Rich Prohaska's avatar
Rich Prohaska committed
4525 4526 4527 4528 4529
static void locked_db_set_errfile (DB *db, FILE *errfile) {
    db->dbenv->set_errfile(db->dbenv, errfile);
}

static int locked_db_set_flags(DB *db, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
4530
    toku_ydb_lock(); int r = toku_db_set_flags(db, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
4531 4532 4533
}

static int locked_db_get_flags(DB *db, u_int32_t *flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
4534
    toku_ydb_lock(); int r = toku_db_get_flags(db, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
4535 4536 4537
}

static int locked_db_set_pagesize(DB *db, u_int32_t pagesize) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
4538
    toku_ydb_lock(); int r = toku_db_set_pagesize(db, pagesize); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
4539 4540 4541
}

static int locked_db_fd(DB *db, int *fdp) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
4542
    toku_ydb_lock(); int r = toku_db_fd(db, fdp); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
4543 4544
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
4545

Yoni Fogel's avatar
Yoni Fogel committed
4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557
static int locked_db_key_range64(DB* db, DB_TXN* txn, DBT* dbt, u_int64_t* less, u_int64_t* equal, u_int64_t* greater, int* is_exact) {
    toku_ydb_lock(); int r = toku_db_key_range64(db, txn, dbt, less, equal, greater, is_exact); toku_ydb_unlock(); return r;
}

static const DBT* toku_db_dbt_pos_infty(void) __attribute__((pure));
static const DBT* toku_db_dbt_pos_infty(void) {
    return toku_lt_infinity;
}

static const DBT* toku_db_dbt_neg_infty(void) __attribute__((pure));
static const DBT* toku_db_dbt_neg_infty(void) {
    return toku_lt_neg_infinity;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
4558 4559
}

4560
static int locked_db_truncate(DB *db, DB_TXN *txn, u_int32_t *row_count, u_int32_t flags) {
4561 4562 4563 4564 4565 4566
    toku_checkpoint_safe_client_lock();
    toku_ydb_lock();
    int r = toku_db_truncate(db, txn, row_count, flags);
    toku_ydb_unlock();
    toku_checkpoint_safe_client_unlock();
    return r;
4567 4568
}

4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589
static int
toku_db_flatten(DB *db, DB_TXN *txn) {
    HANDLE_PANICKED_DB(db);
    TOKULOGGER logger = toku_txn_logger(txn ? db_txn_struct_i(txn)->tokutxn : NULL);
    int r = toku_brt_flatten(db->i->brt, logger);
    return r;
}

static inline int autotxn_db_flatten(DB* db, DB_TXN* txn) {
    BOOL changed; int r;
    r = toku_db_construct_autotxn(db, &txn, &changed, FALSE);
    if (r!=0) return r;
    r = toku_db_flatten(db, txn);
    return toku_db_destruct_autotxn(txn, r, changed);
}


static int locked_db_flatten(DB *db, DB_TXN *txn) {
    toku_ydb_lock(); int r = autotxn_db_flatten(db, txn); toku_ydb_unlock(); return r;
}

Rich Prohaska's avatar
Rich Prohaska committed
4590
static int toku_db_create(DB ** db, DB_ENV * env, u_int32_t flags) {
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
4591 4592
    int r;

4593 4594 4595 4596 4597
    if (flags || env == NULL) 
        return EINVAL;

    if (!env_opened(env))
        return EINVAL;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
4598
    
4599
    DB *MALLOC(result);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
4600 4601
    if (result == 0) {
        return ENOMEM;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
4602
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
4603 4604
    memset(result, 0, sizeof *result);
    result->dbenv = env;
Yoni Fogel's avatar
Yoni Fogel committed
4605 4606 4607 4608 4609
#define SDB(name) result->name = locked_db_ ## name
    SDB(key_range64);
    SDB(close);
    SDB(cursor);
    SDB(del);
Yoni Fogel's avatar
Yoni Fogel committed
4610
    SDB(delboth);
Yoni Fogel's avatar
Yoni Fogel committed
4611 4612 4613 4614 4615 4616 4617 4618
    SDB(get);
    //    SDB(key_range);
    SDB(open);
    SDB(put);
    SDB(remove);
    SDB(rename);
    SDB(set_bt_compare);
    SDB(set_dup_compare);
4619
    SDB(set_descriptor);
Yoni Fogel's avatar
Yoni Fogel committed
4620 4621 4622 4623
    SDB(set_errfile);
    SDB(set_pagesize);
    SDB(set_flags);
    SDB(get_flags);
4624
    SDB(stat64);
Yoni Fogel's avatar
Yoni Fogel committed
4625 4626
    SDB(fd);
    SDB(pre_acquire_read_lock);
Yoni Fogel's avatar
Yoni Fogel committed
4627
    SDB(pre_acquire_table_lock);
4628
    SDB(truncate);
4629
    SDB(row_size_supported);
4630 4631
    SDB(getf_set);
    SDB(getf_get_both);
4632
    SDB(flatten);
Yoni Fogel's avatar
Yoni Fogel committed
4633 4634 4635
#undef SDB
    result->dbt_pos_infty = toku_db_dbt_pos_infty;
    result->dbt_neg_infty = toku_db_dbt_neg_infty;
4636
    MALLOC(result->i);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
4637 4638 4639 4640 4641
    if (result->i == 0) {
        toku_free(result);
        return ENOMEM;
    }
    memset(result->i, 0, sizeof *result->i);
4642
    result->i->db = result;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
4643
    result->i->freed = 0;
4644
    result->i->opened = 0;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
4645 4646 4647
    result->i->open_flags = 0;
    result->i->open_mode = 0;
    result->i->brt = 0;
4648
    toku_list_init(&result->i->dbs_that_must_close_before_abort);
4649
    r = toku_brt_create(&result->i->brt);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
4650 4651 4652
    if (r != 0) {
        toku_free(result->i);
        toku_free(result);
Yoni Fogel's avatar
Yoni Fogel committed
4653
        return r;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
4654
    }
4655
    ydb_add_ref();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
4656 4657
    *db = result;
    return 0;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
4658
}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
4659

4660
int DB_CREATE_FUN (DB ** db, DB_ENV * env, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
4661
    toku_ydb_lock(); int r = toku_db_create(db, env, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
4662 4663 4664 4665
}

/* need db_strerror_r for multiple threads */

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
4666 4667 4668 4669 4670 4671 4672 4673
char *db_strerror(int error) {
    char *errorstr;
    if (error >= 0) {
        errorstr = strerror(error);
        if (errorstr)
            return errorstr;
    }
    
4674 4675 4676
    if (error==DB_BADFORMAT) {
	return "Database Bad Format (probably a corrupted database)";
    }
4677 4678 4679
    if (error==DB_NOTFOUND) {
	return "Not found";
    }
4680

Rich Prohaska's avatar
Rich Prohaska committed
4681
    static char unknown_result[100];    // Race condition if two threads call this at the same time. However even in a bad case, it should be some sort of null-terminated string.
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693
    errorstr = unknown_result;
    snprintf(errorstr, sizeof unknown_result, "Unknown error code: %d", error);
    return errorstr;
}

const char *db_version(int *major, int *minor, int *patch) {
    if (major)
        *major = DB_VERSION_MAJOR;
    if (minor)
        *minor = DB_VERSION_MINOR;
    if (patch)
        *patch = DB_VERSION_PATCH;
4694 4695 4696 4697 4698
#if defined(TOKUDB_REVISION)
#define xstr(X) str(X)
#define str(X) #X
    return "tokudb " xstr(DB_VERSION_MAJOR) "." xstr(DB_VERSION_MINOR) "." xstr(DB_VERSION_PATCH) " build " xstr(TOKUDB_REVISION);
#else
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
4699
    return DB_VERSION_STRING;
4700
#endif
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
4701
}
4702 4703 4704 4705
 
int db_env_set_func_fsync (int (*fsync_function)(int)) {
    return toku_set_func_fsync(fsync_function);
}
Yoni Fogel's avatar
Yoni Fogel committed
4706

4707
int db_env_set_func_pwrite (ssize_t (*pwrite_function)(int, const void *, size_t, toku_off_t)) {
4708 4709 4710 4711 4712 4713
    return toku_set_func_pwrite(pwrite_function);
}
int db_env_set_func_write (ssize_t (*write_function)(int, const void *, size_t)) {
    return toku_set_func_write(write_function);
}

4714 4715 4716 4717 4718 4719
int db_env_set_func_malloc (void *(*f)(size_t)) {
    return toku_set_func_malloc(f);
}
int db_env_set_func_realloc (void *(*f)(void*, size_t)) {
    return toku_set_func_realloc(f);
}
4720
int db_env_set_func_free (void (*f)(void*)) {
4721 4722
    return toku_set_func_free(f);
}
4723 4724 4725 4726 4727 4728
// Got to call dlmalloc, or else it won't get included.
void setup_dlmalloc (void) {
    db_env_set_func_malloc(dlmalloc);
    db_env_set_func_realloc(dlrealloc);
    db_env_set_func_free(dlfree);
}
4729 4730

// For test purposes only.
4731
// With this interface, all checkpoint users get the same callbacks and the same extras.
4732
void db_env_set_checkpoint_callback (void (*callback_f)(void*), void* extra) {
4733
    toku_checkpoint_safe_client_lock();
4734 4735
    checkpoint_callback_f = callback_f;
    checkpoint_callback_extra = extra;
4736
    toku_checkpoint_safe_client_unlock();
4737
    //printf("set callback = %p, extra = %p\n", callback_f, extra);
4738
}
4739 4740 4741 4742 4743 4744 4745
void db_env_set_checkpoint_callback2 (void (*callback_f)(void*), void* extra) {
    toku_checkpoint_safe_client_lock();
    checkpoint_callback2_f = callback_f;
    checkpoint_callback2_extra = extra;
    toku_checkpoint_safe_client_unlock();
    //printf("set callback2 = %p, extra2 = %p\n", callback2_f, extra2);
}
Yoni Fogel's avatar
Yoni Fogel committed
4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756

// HACK: To ensure toku_pthread_yield gets included in the .so
// non-static would require a prototype in a header
// static (since unused) would give a warning
// static + unused would not actually help toku_pthread_yield get in the .so
// static + used avoids all the warnings and makes sure toku_pthread_yield is in the .so
static void __attribute__((__used__))
include_toku_pthread_yield (void) {
    toku_pthread_yield();
}

4757 4758 4759 4760 4761 4762 4763 4764 4765

// For test purposes only, translate dname to iname
static int 
env_get_iname(DB_ENV* env, DBT* dname_dbt, DBT* iname_dbt) {
    DB *directory = env->i->directory;
    int r = autotxn_db_get(directory, NULL, dname_dbt, iname_dbt, DB_PRELOCKED); // allocates memory for iname
    return r;
}