ydb.c 138 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, 2008 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, 2008 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

34 35 36 37 38 39 40 41 42 43
#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

Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
44 45
/** 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
46

47 48 49 50 51 52 53
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
54 55
static void
toku_ydb_init_malloc(void) {
Rich Prohaska's avatar
Rich Prohaska committed
56
#if defined(TOKU_WINDOWS) && TOKU_WINDOWS
Yoni Fogel's avatar
Yoni Fogel committed
57 58 59 60 61 62 63 64
    //Set the heap (malloc/free/realloc) to use the low fragmentation mode.
    ULONG  HeapFragValue = 2;

    int r;
    r = HeapSetInformation(GetProcessHeap(),
                           HeapCompatibilityInformation,
                           &HeapFragValue,
                           sizeof(HeapFragValue));
65 66
    //if (r==0) //Do some error output if necessary.
    assert(r!=0);
Yoni Fogel's avatar
Yoni Fogel committed
67 68 69
#endif
}

70
void toku_ydb_init(void) {
Yoni Fogel's avatar
Yoni Fogel committed
71
    toku_ydb_init_malloc();
72
    toku_brt_init(toku_ydb_lock, toku_ydb_unlock);
73
    toku_ydb_lock_init();
74 75 76
}

void toku_ydb_destroy(void) {
Yoni Fogel's avatar
Yoni Fogel committed
77
    toku_brt_destroy();
78
    toku_ydb_lock_destroy();
79 80
}

81 82 83 84 85
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
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
/* the ydb reference is used to cleanup the library when there are no more references to it */
static int toku_ydb_refs = 0;

static inline void ydb_add_ref() {
    ++toku_ydb_refs;
}

static inline void ydb_unref() {
    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);
103 104 105
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
106 107

static inline void env_add_ref(DB_ENV *env) {
108
    ++env->i->ref_count;
Rich Prohaska's avatar
Rich Prohaska committed
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
}

static inline void env_unref(DB_ENV *env) {
    assert(env->i->ref_count > 0);
    if (--env->i->ref_count == 0)
        toku_env_close(env, 0);
}

static inline int env_opened(DB_ENV *env) {
    return env->i->cachetable != 0;
}


/* db methods */
static inline int db_opened(DB *db) {
    return db->i->full_fname != 0;
}

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);
129
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
130 131 132

/* txn methods */

133
/* lightweight cursor methods. */
134 135 136
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
137

138 139 140
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
141

142 143 144
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
145

146 147
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
148

149 150 151 152
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);
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);
153

154 155 156
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
157 158 159 160 161 162 163 164 165 166 167 168 169 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
// 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
292 293 294 295 296
/* 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
297

Rich Prohaska's avatar
Rich Prohaska committed
298
/* misc */
Yoni Fogel's avatar
Yoni Fogel committed
299 300
static char *construct_full_name(const char *dir, const char *fname);
    
301 302 303 304 305 306
static int do_recovery (DB_ENV *env) {
    const char *datadir=env->i->dir;
    char *logdir;
    if (env->i->lg_dir) {
	logdir = construct_full_name(env->i->dir, env->i->lg_dir);
    } else {
307
	logdir = toku_strdup(env->i->dir);
308 309
    }
    
310
#if 0
311 312 313 314 315
    // want to do recovery in its own process
    pid_t pid;
    if ((pid=fork())==0) {
	int r=tokudb_recover(datadir, logdir);
	assert(r==0);
316
	toku_free(logdir); // the child must also free.
317 318 319 320 321
	exit(0);
    }
    int status;
    waitpid(pid, &status, 0);
    if (!WIFEXITED(status) || WEXITSTATUS(status)!=0)  {
322
	toku_free(logdir);
323 324 325 326
	return toku_ydb_do_error(env, -1, "Recovery failed\n");
    }
    toku_free(logdir);
    return 0;
327 328 329 330 331
#else
    int r = tokudb_recover(datadir, logdir);
    toku_free(logdir);
    return r;
#endif
332 333
}

Rich Prohaska's avatar
Rich Prohaska committed
334
static int toku_env_open(DB_ENV * env, const char *home, u_int32_t flags, int mode) {
335
    HANDLE_PANICKED_ENV(env);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
336
    int r;
337
    u_int32_t unused_flags=flags;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
338

Rich Prohaska's avatar
Rich Prohaska committed
339
    if (env_opened(env)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
340
	return toku_ydb_do_error(env, EINVAL, "The environment is already open\n");
341
    }
Yoni Fogel's avatar
Yoni Fogel committed
342

343
    if ((flags & DB_USE_ENVIRON) && (flags & DB_USE_ENVIRON_ROOT)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
344
	return toku_ydb_do_error(env, EINVAL, "DB_USE_ENVIRON and DB_USE_ENVIRON_ROOT are incompatible flags\n");
345
    }
Yoni Fogel's avatar
Yoni Fogel committed
346

Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
347 348 349 350
    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");
    }

Yoni Fogel's avatar
Yoni Fogel committed
351
    if (home) {
352
        if ((flags & DB_USE_ENVIRON) || (flags & DB_USE_ENVIRON_ROOT)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
353
	    return toku_ydb_do_error(env, EINVAL, "DB_USE_ENVIRON and DB_USE_ENVIRON_ROOT are incompatible with specifying a home\n");
354
	}
Yoni Fogel's avatar
Yoni Fogel committed
355
    }
356
    else if ((flags & DB_USE_ENVIRON)) home = getenv("DB_HOME");
357
#if !TOKU_WINDOWS
358
    else if ((flags & DB_USE_ENVIRON_ROOT) && geteuid() == 0) home = getenv("DB_HOME");
359
#endif
360 361
    unused_flags &= ~DB_USE_ENVIRON & ~DB_USE_ENVIRON_ROOT; 

Yoni Fogel's avatar
Yoni Fogel committed
362
    if (!home) home = ".";
Yoni Fogel's avatar
Yoni Fogel committed
363

Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
364
	// Verify that the home exists.
Yoni Fogel's avatar
Yoni Fogel committed
365
	{
Zardosht Kasheff's avatar
Zardosht Kasheff committed
366 367
	    BOOL made_new_home = FALSE;
        char* new_home = NULL;
368
    	toku_struct_stat buf;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
369 370 371 372 373 374
        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;
        }
375
    	r = toku_stat(made_new_home? new_home : home, &buf);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
376 377 378 379
        if (made_new_home) {
            toku_free(new_home);
        }
    	if (r!=0) {
380
    	    return toku_ydb_do_error(env, errno, "Error from toku_stat(\"%s\",...)\n", home);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
381
    	}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
382
    }
383
    unused_flags &= ~DB_PRIVATE;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
384 385 386

    if (env->i->dir)
        toku_free(env->i->dir);
Yoni Fogel's avatar
Yoni Fogel committed
387
    env->i->dir = toku_strdup(home);
388
    if (env->i->dir == 0) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
389
	return toku_ydb_do_error(env, ENOMEM, "Out of memory\n");
390
    }
Yoni Fogel's avatar
Yoni Fogel committed
391 392 393 394 395 396
    if (0) {
        died1:
        toku_free(env->i->dir);
        env->i->dir = NULL;
        return r;
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
397 398
    env->i->open_flags = flags;
    env->i->open_mode = mode;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
399

400 401 402 403 404 405 406
    unused_flags &= ~DB_INIT_TXN & ~DB_INIT_LOG; 

    if (flags&DB_RECOVER) {
	r=do_recovery(env);
	if (r!=0) return r;
    }

Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
407
    if (flags & (DB_INIT_TXN | DB_INIT_LOG)) {
408 409
        char* full_dir = NULL;
        if (env->i->lg_dir) full_dir = construct_full_name(env->i->dir, env->i->lg_dir);
410
	assert(env->i->logger);
411
        toku_logger_write_log_files(env->i->logger, (flags & DB_INIT_LOG) != 0);
412 413 414
        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
415
	    toku_ydb_do_error(env, r, "Could not open logger\n");
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
416
	died2:
417
	    toku_logger_close(&env->i->logger);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
418 419
	    goto died1;
	}
420 421 422
    } 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
423 424
    }

425 426 427 428 429 430 431 432 433 434 435 436
    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) {
437
	return toku_ydb_do_error(env, EINVAL, "Extra flags not understood by tokudb: %u\n", unused_flags);
438 439
    }

440
    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
441
    if (r!=0) goto died2;
442

443
    if (env->i->logger) toku_logger_set_cachetable(env->i->logger, env->i->cachetable);
444

Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
445 446
    return 0;
}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
447

Rich Prohaska's avatar
Rich Prohaska committed
448
static int toku_env_close(DB_ENV * env, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
449
    int is_panicked = toku_env_is_panicked(env);
450 451 452 453
    char *panic_string = env->i->panic_string;
    env->i->panic_string = 0;

    // Even if the env is panicked, try to close as much as we can.
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
454
    int r0=0,r1=0;
455
    if (env->i->cachetable) {
456 457 458
	toku_ydb_unlock();  // ydb lock must not be held when shutting down minicron
	toku_cachetable_minicron_shutdown(env->i->cachetable);
	toku_ydb_lock();
459
        r0=toku_cachetable_close(&env->i->cachetable);
460 461 462 463 464
	if (r0) {
	    toku_ydb_do_error(env, r0, "Cannot close environment (cachetable close error)\n");
	}
    }
    if (env->i->logger) {
465
        r1=toku_logger_close(&env->i->logger);
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
	if (r0==0 && r1) {
	    toku_ydb_do_error(env, r0, "Cannot close environment (logger close error)\n");
	}
    }
    // 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)
    if (is_panicked) {
	if (r0==0 && r1==0) {
	    toku_ydb_do_error(env, is_panicked, "Cannot close environment due to previous error: %s\n", panic_string);
	}
	if (panic_string) toku_free(panic_string);
    } else {
	assert(panic_string==0);
    }

Yoni Fogel's avatar
Yoni Fogel committed
481 482 483 484 485 486 487 488
    if (env->i->data_dirs) {
        u_int32_t i;
        assert(env->i->n_data_dirs > 0);
        for (i = 0; i < env->i->n_data_dirs; i++) {
            toku_free(env->i->data_dirs[i]);
        }
        toku_free(env->i->data_dirs);
    }
489 490
    if (env->i->lg_dir)
        toku_free(env->i->lg_dir);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
491 492
    if (env->i->tmp_dir)
        toku_free(env->i->tmp_dir);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
493
    toku_free(env->i->dir);
Yoni Fogel's avatar
Yoni Fogel committed
494
    toku_ltm_close(env->i->ltm);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
495 496
    toku_free(env->i);
    toku_free(env);
497
    ydb_unref();
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
498 499 500
    if (flags!=0) return EINVAL;
    if (r0) return r0;
    if (r1) return r1;
501
    return is_panicked;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
502
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
503

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

508
static int toku_env_log_flush(DB_ENV * env, const DB_LSN * lsn __attribute__((__unused__))) {
509
    HANDLE_PANICKED_ENV(env);
510 511
    // 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
512
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
513

Rich Prohaska's avatar
Rich Prohaska committed
514
static int toku_env_set_cachesize(DB_ENV * env, u_int32_t gbytes, u_int32_t bytes, int ncache) {
515
    HANDLE_PANICKED_ENV(env);
Rich Prohaska's avatar
Rich Prohaska committed
516 517
    if (ncache != 1)
        return EINVAL;
Rich Prohaska's avatar
Rich Prohaska committed
518 519 520 521 522
    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
523 524 525
    return 0;
}

Rich Prohaska's avatar
Rich Prohaska committed
526 527
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR >= 3

Rich Prohaska's avatar
Rich Prohaska committed
528
static int toku_env_get_cachesize(DB_ENV * env, u_int32_t *gbytes, u_int32_t *bytes, int *ncache) {
529
    HANDLE_PANICKED_ENV(env);
Rich Prohaska's avatar
Rich Prohaska committed
530 531 532 533 534 535
    *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
536
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
537
    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
538
}
Rich Prohaska's avatar
Rich Prohaska committed
539 540
#endif

Rich Prohaska's avatar
Rich Prohaska committed
541
static int toku_env_set_data_dir(DB_ENV * env, const char *dir) {
542
    HANDLE_PANICKED_ENV(env);
Yoni Fogel's avatar
Yoni Fogel committed
543 544
    u_int32_t i;
    int r;
545 546
    char** temp;
    char* new_dir;
Yoni Fogel's avatar
Yoni Fogel committed
547
    
Rich Prohaska's avatar
Rich Prohaska committed
548
    if (env_opened(env) || !dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
549
	return toku_ydb_do_error(env, EINVAL, "You cannot set the data dir after opening the env\n");
550
    }
Yoni Fogel's avatar
Yoni Fogel committed
551 552 553 554 555 556 557 558 559 560 561
    
    if (env->i->data_dirs) {
        assert(env->i->n_data_dirs > 0);
        for (i = 0; i < env->i->n_data_dirs; i++) {
            if (!strcmp(dir, env->i->data_dirs[i])) {
                //It is already in the list.  We're done.
                return 0;
            }
        }
    }
    else assert(env->i->n_data_dirs == 0);
562 563 564 565
    new_dir = toku_strdup(dir);
    if (0) {
        died1:
        toku_free(new_dir);
Yoni Fogel's avatar
Yoni Fogel committed
566 567
        return r;
    }
568 569
    if (new_dir==NULL) {
	assert(errno == ENOMEM);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
570
	return toku_ydb_do_error(env, errno, "Out of memory\n");
571
    }
572 573 574 575
    temp = (char**) toku_realloc(env->i->data_dirs, (1 + env->i->n_data_dirs) * sizeof(char*));
    if (temp==NULL) {assert(errno == ENOMEM); r = ENOMEM; goto died1;}
    else env->i->data_dirs = temp;
    env->i->data_dirs[env->i->n_data_dirs] = new_dir;
Yoni Fogel's avatar
Yoni Fogel committed
576 577
    env->i->n_data_dirs++;
    return 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
578
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
579

Rich Prohaska's avatar
Rich Prohaska committed
580
static void toku_env_set_errcall(DB_ENV * env, toku_env_errcall_t errcall) {
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
581
    env->i->errcall = errcall;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
582
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
583

Rich Prohaska's avatar
Rich Prohaska committed
584
static void toku_env_set_errfile(DB_ENV*env, FILE*errfile) {
585 586 587
    env->i->errfile = errfile;
}

Rich Prohaska's avatar
Rich Prohaska committed
588
static void toku_env_set_errpfx(DB_ENV * env, const char *errpfx) {
589
    env->i->errpfx = errpfx;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
590
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
591

Rich Prohaska's avatar
Rich Prohaska committed
592
static int toku_env_set_flags(DB_ENV * env, u_int32_t flags, int onoff) {
593
    HANDLE_PANICKED_ENV(env);
Yoni Fogel's avatar
Yoni Fogel committed
594 595 596 597 598 599

    u_int32_t change = 0;
    if (flags & DB_AUTO_COMMIT) {
        change |=  DB_AUTO_COMMIT;
        flags  &= ~DB_AUTO_COMMIT;
    }
600
    if (flags != 0 && onoff) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
601
	return toku_ydb_do_error(env, EINVAL, "TokuDB does not (yet) support any nonzero ENV flags other than DB_AUTO_COMMIT\n");
602
    }
Yoni Fogel's avatar
Yoni Fogel committed
603 604
    if   (onoff) env->i->open_flags |=  change;
    else         env->i->open_flags &= ~change;
Rich Prohaska's avatar
Rich Prohaska committed
605
    return 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
606
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
607

Rich Prohaska's avatar
Rich Prohaska committed
608
static int toku_env_set_lg_bsize(DB_ENV * env, u_int32_t bsize) {
609
    HANDLE_PANICKED_ENV(env);
610
    return toku_logger_set_lg_bsize(env->i->logger, bsize);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
611
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
612

Rich Prohaska's avatar
Rich Prohaska committed
613
static int toku_env_set_lg_dir(DB_ENV * env, const char *dir) {
614
    HANDLE_PANICKED_ENV(env);
Rich Prohaska's avatar
Rich Prohaska committed
615
    if (env_opened(env)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
616
	return toku_ydb_do_error(env, EINVAL, "Cannot set log dir after opening the env\n");
617
    }
618 619

    if (env->i->lg_dir) toku_free(env->i->lg_dir);
620 621
    if (dir) {
        env->i->lg_dir = toku_strdup(dir);
622
        if (!env->i->lg_dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
623
	    return toku_ydb_do_error(env, ENOMEM, "Out of memory\n");
624
	}
625
    }
626 627
    else env->i->lg_dir = NULL;
    return 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
628
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
629

Rich Prohaska's avatar
Rich Prohaska committed
630
static int toku_env_set_lg_max(DB_ENV * env, u_int32_t lg_max) {
631
    HANDLE_PANICKED_ENV(env);
632 633 634 635 636 637
    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
638
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
639

Rich Prohaska's avatar
Rich Prohaska committed
640
static int toku_env_set_lk_detect(DB_ENV * env, u_int32_t detect) {
641
    HANDLE_PANICKED_ENV(env);
642
    detect=detect;
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
643
    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
644
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
645

Yoni Fogel's avatar
Yoni Fogel committed
646
static int toku_env_set_lk_max_locks(DB_ENV *dbenv, u_int32_t max) {
Yoni Fogel's avatar
Yoni Fogel committed
647
    int r = ENOSYS;
Yoni Fogel's avatar
Yoni Fogel committed
648
    HANDLE_PANICKED_ENV(dbenv);
Yoni Fogel's avatar
Yoni Fogel committed
649
    if (env_opened(dbenv))         { return EINVAL; }
Yoni Fogel's avatar
Yoni Fogel committed
650
    r = toku_ltm_set_max_locks_per_db(dbenv->i->ltm, max);
Yoni Fogel's avatar
Yoni Fogel committed
651
    return r;
Yoni Fogel's avatar
Yoni Fogel committed
652 653
}

654
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR <= 4
Rich Prohaska's avatar
Rich Prohaska committed
655
static int toku_env_set_lk_max(DB_ENV * env, u_int32_t lk_max) {
Yoni Fogel's avatar
Yoni Fogel committed
656
    return toku_env_set_lk_max_locks(env, lk_max);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
657
}
Rich Prohaska's avatar
Rich Prohaska committed
658 659

static int locked_env_set_lk_max(DB_ENV * env, u_int32_t lk_max) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
660
    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
661
}
662
#endif
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
663

664 665
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
666
    return toku_ltm_get_max_locks_per_db(dbenv->i->ltm, lk_maxp);
667 668 669
}

static int locked_env_set_lk_max_locks(DB_ENV *dbenv, u_int32_t max) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
670
    toku_ydb_lock(); int r = toku_env_set_lk_max_locks(dbenv, max); toku_ydb_unlock(); return r;
671 672 673
}

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
674
    toku_ydb_lock(); int r = toku_env_get_lk_max_locks(dbenv, lk_maxp); toku_ydb_unlock(); return r;
675 676
}

Yoni Fogel's avatar
Yoni Fogel committed
677
//void toku__env_set_noticecall (DB_ENV *env, void (*noticecall)(DB_ENV *, db_notices)) {
Bradley C. Kuszmaul's avatar
Fixup  
Bradley C. Kuszmaul committed
678 679
//    env->i->noticecall = noticecall;
//}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
680

Rich Prohaska's avatar
Rich Prohaska committed
681
static int toku_env_set_tmp_dir(DB_ENV * env, const char *tmp_dir) {
682
    HANDLE_PANICKED_ENV(env);
Rich Prohaska's avatar
Rich Prohaska committed
683
    if (env_opened(env)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
684
	return toku_ydb_do_error(env, EINVAL, "Cannot set the tmp dir after opening an env\n");
685 686
    }
    if (!tmp_dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
687
	return toku_ydb_do_error(env, EINVAL, "Tmp dir bust be non-null\n");
688
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
689 690
    if (env->i->tmp_dir)
        toku_free(env->i->tmp_dir);
Yoni Fogel's avatar
Yoni Fogel committed
691
    env->i->tmp_dir = toku_strdup(tmp_dir);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
692
    return env->i->tmp_dir ? 0 : ENOMEM;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
693
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
694

Rich Prohaska's avatar
Rich Prohaska committed
695
static int toku_env_set_verbose(DB_ENV * env, u_int32_t which, int onoff) {
696 697
    HANDLE_PANICKED_ENV(env);
    which=which; onoff=onoff;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
698
    return 1;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
699
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
700

701 702 703 704
// For test purposes only.
static void (*checkpoint_callback_f)(void*) = NULL;
static void * checkpoint_callback_extra     = NULL;

705
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__))) {
706
    char *error_string = NULL;
707
    int r = toku_checkpoint(env->i->cachetable, env->i->logger, &error_string, checkpoint_callback_f, checkpoint_callback_extra);
708 709 710 711 712 713 714 715 716 717 718
    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
719 720
}

Rich Prohaska's avatar
Rich Prohaska committed
721
static int toku_env_txn_stat(DB_ENV * env, DB_TXN_STAT ** statp, u_int32_t flags) {
722 723
    HANDLE_PANICKED_ENV(env);
    statp=statp;flags=flags;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
724
    return 1;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
725 726
}

727
#if 0
728
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR == 1
729
static void toku_default_errcall(const char *errpfx, char *msg) {
730 731
    fprintf(stderr, "YDB: %s: %s", errpfx, msg);
}
732
#else
733
static void toku_default_errcall(const DB_ENV *env, const char *errpfx, const char *msg) {
734
    env = env;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
735 736
    fprintf(stderr, "YDB: %s: %s", errpfx, msg);
}
737
#endif
738
#endif
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
739

Rich Prohaska's avatar
Rich Prohaska committed
740
static int locked_env_open(DB_ENV * env, const char *home, u_int32_t flags, int mode) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
741
    toku_ydb_lock(); int r = toku_env_open(env, home, flags, mode); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
742 743 744
}

static int locked_env_close(DB_ENV * env, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
745
    toku_ydb_lock(); int r = toku_env_close(env, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
746 747 748
}

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

static int locked_env_log_flush(DB_ENV * env, const DB_LSN * lsn) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
753
    toku_ydb_lock(); int r = toku_env_log_flush(env, lsn); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
754 755 756
}

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
757
    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
758 759 760
}

static int locked_env_set_data_dir(DB_ENV * env, const char *dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
761
    toku_ydb_lock(); int r = toku_env_set_data_dir(env, dir); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
762 763 764
}

static int locked_env_set_flags(DB_ENV * env, u_int32_t flags, int onoff) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
765
    toku_ydb_lock(); int r = toku_env_set_flags(env, flags, onoff); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
766 767 768
}

static int locked_env_set_lg_bsize(DB_ENV * env, u_int32_t bsize) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
769
    toku_ydb_lock(); int r = toku_env_set_lg_bsize(env, bsize); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
770 771 772
}

static int locked_env_set_lg_dir(DB_ENV * env, const char *dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
773
    toku_ydb_lock(); int r = toku_env_set_lg_dir(env, dir); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
774 775 776
}

static int locked_env_set_lg_max(DB_ENV * env, u_int32_t lg_max) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
777
    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
778 779
}

780 781 782 783
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
784
static int locked_env_set_lk_detect(DB_ENV * env, u_int32_t detect) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
785
    toku_ydb_lock(); int r = toku_env_set_lk_detect(env, detect); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
786 787 788
}

static int locked_env_set_tmp_dir(DB_ENV * env, const char *tmp_dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
789
    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
790 791 792
}

static int locked_env_set_verbose(DB_ENV * env, u_int32_t which, int onoff) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
793
    toku_ydb_lock(); int r = toku_env_set_verbose(env, which, onoff); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
794 795 796
}

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

800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
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;
}

830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
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;
}

Rich Prohaska's avatar
Rich Prohaska committed
904 905
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
906 907 908 909 910 911
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
912
static int toku_env_create(DB_ENV ** envp, u_int32_t flags) {
Yoni Fogel's avatar
Yoni Fogel committed
913 914 915 916 917 918
    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
919
    memset(result, 0, sizeof *result);
920
    result->err = (void (*)(const DB_ENV * env, int error, const char *fmt, ...)) toku_locked_env_err;
921 922
    result->set_default_bt_compare = locked_env_set_default_bt_compare;
    result->set_default_dup_compare = locked_env_set_default_dup_compare;
923 924
    result->checkpointing_set_period = locked_env_checkpointing_set_period;
    result->checkpointing_get_period = locked_env_checkpointing_get_period;
925 926 927 928
    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;
Rich Prohaska's avatar
Rich Prohaska committed
929 930
    result->open = locked_env_open;
    result->close = locked_env_close;
931
    result->txn_checkpoint = toku_env_txn_checkpoint;
Rich Prohaska's avatar
Rich Prohaska committed
932 933 934 935 936 937 938 939 940 941 942 943
    result->log_flush = locked_env_log_flush;
    result->set_errcall = toku_env_set_errcall;
    result->set_errfile = toku_env_set_errfile;
    result->set_errpfx = toku_env_set_errpfx;
    //result->set_noticecall = locked_env_set_noticecall;
    result->set_flags = locked_env_set_flags;
    result->set_data_dir = locked_env_set_data_dir;
    result->set_tmp_dir = locked_env_set_tmp_dir;
    result->set_verbose = locked_env_set_verbose;
    result->set_lg_bsize = locked_env_set_lg_bsize;
    result->set_lg_dir = locked_env_set_lg_dir;
    result->set_lg_max = locked_env_set_lg_max;
944
    result->get_lg_max = locked_env_get_lg_max;
945
    result->set_lk_max_locks = locked_env_set_lk_max_locks;
Rich Prohaska's avatar
Rich Prohaska committed
946
    result->get_lk_max_locks = locked_env_get_lk_max_locks;
Rich Prohaska's avatar
Rich Prohaska committed
947
    result->set_cachesize = locked_env_set_cachesize;
Rich Prohaska's avatar
Rich Prohaska committed
948
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR >= 3
Rich Prohaska's avatar
Rich Prohaska committed
949
    result->get_cachesize = locked_env_get_cachesize;
Rich Prohaska's avatar
Rich Prohaska committed
950
#endif
Rich Prohaska's avatar
Rich Prohaska committed
951
    result->set_lk_detect = locked_env_set_lk_detect;
952
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR <= 4
Rich Prohaska's avatar
Rich Prohaska committed
953
    result->set_lk_max = locked_env_set_lk_max;
954
#endif
Rich Prohaska's avatar
Rich Prohaska committed
955 956 957
    result->log_archive = locked_env_log_archive;
    result->txn_stat = locked_env_txn_stat;
    result->txn_begin = locked_txn_begin;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
958

959
    MALLOC(result->i);
Yoni Fogel's avatar
Yoni Fogel committed
960
    if (result->i == 0) { r = ENOMEM; goto cleanup; }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
961
    memset(result->i, 0, sizeof *result->i);
962 963
    result->i->bt_compare  = toku_default_compare_fun;
    result->i->dup_compare = toku_default_compare_fun;
964
    result->i->is_panicked=0;
965
    result->i->panic_string = 0;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
966
    result->i->ref_count = 1;
967 968
    result->i->errcall = 0;
    result->i->errpfx = 0;
969
    result->i->errfile = 0;
Yoni Fogel's avatar
Yoni Fogel committed
970 971

    r = toku_ltm_create(&result->i->ltm, __toku_env_default_max_locks,
Yoni Fogel's avatar
Yoni Fogel committed
972 973 974
                         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
975
    if (r!=0) { goto cleanup; }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
976

977
    {
Yoni Fogel's avatar
Yoni Fogel committed
978 979
	r = toku_logger_create(&result->i->logger);
	if (r!=0) { goto cleanup; }
980 981 982
	assert(result->i->logger);
    }

983
    ydb_add_ref();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
984
    *envp = result;
Yoni Fogel's avatar
Yoni Fogel committed
985 986 987 988 989 990 991 992 993 994 995 996 997 998
    r = 0;
cleanup:
    if (r!=0) {
        if (result) {
            if (result->i) {
                if (result->i->ltm) {
                    toku_ltm_close(result->i->ltm);
                }
                toku_free(result->i);
            }
            toku_free(result);
        }
    }
    return r;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
999 1000
}

1001
int DB_ENV_CREATE_FUN (DB_ENV ** envp, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1002
    toku_ydb_lock(); int r = toku_env_create(envp, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
1003 1004
}

Yoni Fogel's avatar
Yoni Fogel committed
1005
static int toku_txn_release_locks(DB_TXN* txn) {
Yoni Fogel's avatar
Yoni Fogel committed
1006
    assert(txn);
1007
    toku_lth* lth = db_txn_struct_i(txn)->lth;
Yoni Fogel's avatar
Yoni Fogel committed
1008

Yoni Fogel's avatar
Yoni Fogel committed
1009 1010
    int r = ENOSYS;
    int first_error = 0;
Yoni Fogel's avatar
Yoni Fogel committed
1011 1012 1013 1014
    if (lth) {
        toku_lth_start_scan(lth);
        toku_lock_tree* next = toku_lth_next(lth);
        while (next) {
1015
            r = toku_lt_unlock(next, toku_txn_get_txnid(db_txn_struct_i(txn)->tokutxn));
Yoni Fogel's avatar
Yoni Fogel committed
1016 1017 1018 1019 1020
            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
1021 1022 1023
            next = toku_lth_next(lth);
        }
        toku_lth_close(lth);
1024
        db_txn_struct_i(txn)->lth = NULL;
Yoni Fogel's avatar
Yoni Fogel committed
1025
    }
Yoni Fogel's avatar
Yoni Fogel committed
1026 1027
    r = first_error;

Yoni Fogel's avatar
Yoni Fogel committed
1028
    return r;
Yoni Fogel's avatar
Yoni Fogel committed
1029 1030
}

1031 1032
// 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.
1033
static void ydb_yield (voidfp f, void *UU(v)) {
1034
    toku_ydb_unlock(); 
1035
    if (f) f();
1036 1037 1038
    toku_ydb_lock();
}

Rich Prohaska's avatar
Rich Prohaska committed
1039
static int toku_txn_commit(DB_TXN * txn, u_int32_t flags) {
1040
    if (!txn) return EINVAL;
1041
    HANDLE_PANICKED_ENV(txn->mgrp);
Yoni Fogel's avatar
Yoni Fogel committed
1042
    //Recursively kill off children
Yoni Fogel's avatar
Yoni Fogel committed
1043
    int r_child_first = 0;
1044 1045
    while (db_txn_struct_i(txn)->child) {
        int r_child = toku_txn_commit(db_txn_struct_i(txn)->child, flags);
Yoni Fogel's avatar
Yoni Fogel committed
1046 1047 1048
        if (!r_child_first) r_child_first = r_child;
        //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
1049 1050 1051
    }
    //Remove from parent
    if (txn->parent) {
1052 1053 1054
        if (db_txn_struct_i(txn->parent)->child==txn) db_txn_struct_i(txn->parent)->child=db_txn_struct_i(txn)->next;
        if (db_txn_struct_i(txn->parent)->child==txn) {
            db_txn_struct_i(txn->parent)->child=NULL;
Yoni Fogel's avatar
Yoni Fogel committed
1055 1056
        }
        else {
1057 1058
	    db_txn_struct_i(db_txn_struct_i(txn)->next)->prev = db_txn_struct_i(txn)->prev;
            db_txn_struct_i(db_txn_struct_i(txn)->prev)->next = db_txn_struct_i(txn)->next;
Yoni Fogel's avatar
Yoni Fogel committed
1059 1060
        }
    }
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1061
    //toku_ydb_notef("flags=%d\n", flags);
1062
    int nosync = (flags & DB_TXN_NOSYNC)!=0 || (db_txn_struct_i(txn)->flags&DB_TXN_NOSYNC);
1063
    flags &= ~DB_TXN_NOSYNC;
Yoni Fogel's avatar
Yoni Fogel committed
1064 1065 1066

    int r;
    if (r_child_first || flags!=0)
1067 1068
	// frees the tokutxn
	// Calls ydb_yield(NULL) occasionally
1069
        r = toku_logger_abort(db_txn_struct_i(txn)->tokutxn, ydb_yield, NULL);
Yoni Fogel's avatar
Yoni Fogel committed
1070
    else
1071 1072
	// frees the tokutxn
	// Calls ydb_yield(NULL) occasionally
1073
        r = toku_logger_commit(db_txn_struct_i(txn)->tokutxn, nosync, ydb_yield, NULL);
1074 1075 1076

    // Close the logger after releasing the locks
    int r2 = toku_txn_release_locks(txn);
1077
    toku_logger_txn_close(db_txn_struct_i(txn)->tokutxn);
1078
    // the toxutxn is freed, and we must free the rest. */
Yoni Fogel's avatar
Yoni Fogel committed
1079

1080
    // The txn is no good after the commit even if the commit fails, so free it up.
1081 1082 1083
#if !TOKUDB_NATIVE_H
    toku_free(db_txn_struct_i(txn));
#endif
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1084
    toku_free(txn);
Yoni Fogel's avatar
Yoni Fogel committed
1085 1086
    if (flags!=0) return EINVAL;
    return r ? r : (r2 ? r2 : r_child_first);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1087 1088
}

Rich Prohaska's avatar
Rich Prohaska committed
1089
static u_int32_t toku_txn_id(DB_TXN * txn) {
1090
    HANDLE_PANICKED_ENV(txn->mgrp);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1091
    toku_ydb_barf();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1092
    abort();
Rich Prohaska's avatar
Rich Prohaska committed
1093
    return -1;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1094 1095
}

1096
static int toku_txn_abort(DB_TXN * txn) {
1097
    HANDLE_PANICKED_ENV(txn->mgrp);
Yoni Fogel's avatar
Yoni Fogel committed
1098
    //Recursively kill off children
Yoni Fogel's avatar
Yoni Fogel committed
1099
    int r_child_first = 0;
1100 1101
    while (db_txn_struct_i(txn)->child) {
        int r_child = toku_txn_abort(db_txn_struct_i(txn)->child);
Yoni Fogel's avatar
Yoni Fogel committed
1102 1103 1104
        if (!r_child_first) r_child_first = r_child;
        //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
1105 1106 1107
    }
    //Remove from parent
    if (txn->parent) {
1108 1109 1110
        if (db_txn_struct_i(txn->parent)->child==txn) db_txn_struct_i(txn->parent)->child=db_txn_struct_i(txn)->next;
        if (db_txn_struct_i(txn->parent)->child==txn) {
            db_txn_struct_i(txn->parent)->child=NULL;
Yoni Fogel's avatar
Yoni Fogel committed
1111 1112
        }
        else {
1113 1114
            db_txn_struct_i(db_txn_struct_i(txn)->next)->prev = db_txn_struct_i(txn)->prev;
            db_txn_struct_i(db_txn_struct_i(txn)->prev)->next = db_txn_struct_i(txn)->next;
Yoni Fogel's avatar
Yoni Fogel committed
1115 1116
        }
    }
1117
    int r = toku_logger_abort(db_txn_struct_i(txn)->tokutxn, ydb_yield, NULL);
Yoni Fogel's avatar
Yoni Fogel committed
1118
    int r2 = toku_txn_release_locks(txn);
1119
    toku_logger_txn_close(db_txn_struct_i(txn)->tokutxn);
Yoni Fogel's avatar
Yoni Fogel committed
1120

1121 1122 1123
#if !TOKUDB_NATIVE_H
    toku_free(db_txn_struct_i(txn));
#endif
1124
    toku_free(txn);
Yoni Fogel's avatar
Yoni Fogel committed
1125
    return r ? r : (r2 ? r2 : r_child_first);
1126 1127
}

Rich Prohaska's avatar
Rich Prohaska committed
1128 1129 1130
static int toku_txn_begin(DB_ENV *env, DB_TXN * stxn, DB_TXN ** txn, u_int32_t flags);

static int locked_txn_begin(DB_ENV *env, DB_TXN * stxn, DB_TXN ** txn, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1131
    toku_ydb_lock(); int r = toku_txn_begin(env, stxn, txn, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
1132 1133 1134
}

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

1138 1139
static int toku_txn_stat (DB_TXN *txn, struct txn_stat **txn_stat) {
    XMALLOC(*txn_stat);
1140
    return toku_logger_txn_rolltmp_raw_count(db_txn_struct_i(txn)->tokutxn, &(*txn_stat)->rolltmp_raw_count);
1141 1142 1143 1144 1145 1146
}

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
1147
static int locked_txn_commit(DB_TXN *txn, u_int32_t flags) {
1148
    toku_multi_operation_client_lock(); //Cannot checkpoint during a commit.
1149
    toku_ydb_lock(); int r = toku_txn_commit(txn, flags); toku_ydb_unlock();
1150
    toku_multi_operation_client_unlock(); //Cannot checkpoint during a commit.
1151
    return r;
Rich Prohaska's avatar
Rich Prohaska committed
1152 1153 1154
}

static int locked_txn_abort(DB_TXN *txn) {
1155
    toku_multi_operation_client_lock(); //Cannot checkpoint during an abort.
1156
    toku_ydb_lock(); int r = toku_txn_abort(txn); toku_ydb_unlock();
1157
    toku_multi_operation_client_unlock(); //Cannot checkpoint during an abort.
1158
    return r;
Rich Prohaska's avatar
Rich Prohaska committed
1159 1160 1161
}

static int toku_txn_begin(DB_ENV *env, DB_TXN * stxn, DB_TXN ** txn, u_int32_t flags) {
1162
    HANDLE_PANICKED_ENV(env);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1163 1164
    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");
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
    u_int32_t txn_flags = 0;
    txn_flags |= DB_TXN_NOWAIT; //We do not support blocking locks.
    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");

1181
    DB_TXN *MALLOC(result);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1182 1183 1184
    if (result == 0)
        return ENOMEM;
    memset(result, 0, sizeof *result);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1185
    //toku_ydb_notef("parent=%p flags=0x%x\n", stxn, flags);
1186
    result->mgrp = env;
Rich Prohaska's avatar
Rich Prohaska committed
1187 1188 1189
    result->abort = locked_txn_abort;
    result->commit = locked_txn_commit;
    result->id = locked_txn_id;
Yoni Fogel's avatar
Yoni Fogel committed
1190
    result->parent = stxn;
1191
    result->txn_stat = locked_txn_stat;
1192 1193 1194
#if !TOKUDB_NATIVE_H
    MALLOC(db_txn_struct_i(result));
    if (!db_txn_struct_i(result)) {
Yoni Fogel's avatar
Yoni Fogel committed
1195 1196 1197
        toku_free(result);
        return ENOMEM;
    }
1198 1199 1200
#endif
    memset(db_txn_struct_i(result), 0, sizeof *db_txn_struct_i(result));
    db_txn_struct_i(result)->flags = txn_flags;
Yoni Fogel's avatar
Yoni Fogel committed
1201 1202

    int r;
Yoni Fogel's avatar
Yoni Fogel committed
1203
    if (env->i->open_flags & DB_INIT_LOCK && !stxn) {
1204
        r = toku_lth_create(&db_txn_struct_i(result)->lth,
Yoni Fogel's avatar
Yoni Fogel committed
1205 1206
                            toku_malloc, toku_free, toku_realloc);
        if (r!=0) {
1207 1208 1209
#if !TOKUDB_NATIVE_H
            toku_free(db_txn_struct_i(result));
#endif
Yoni Fogel's avatar
Yoni Fogel committed
1210 1211 1212
            toku_free(result);
            return r;
        }
Yoni Fogel's avatar
Yoni Fogel committed
1213 1214
    }
    
1215
    r = toku_logger_txn_begin(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
1216 1217
    if (r != 0)
        return r;
Yoni Fogel's avatar
Yoni Fogel committed
1218 1219
    //Add to the list of children for the parent.
    if (result->parent) {
1220 1221 1222 1223
        if (!db_txn_struct_i(result->parent)->child) {
            db_txn_struct_i(result->parent)->child = result;
            db_txn_struct_i(result)->next = result;
            db_txn_struct_i(result)->prev = result;
Yoni Fogel's avatar
Yoni Fogel committed
1224 1225
        }
        else {
1226 1227 1228 1229
            db_txn_struct_i(result)->prev = db_txn_struct_i(db_txn_struct_i(result->parent)->child)->prev;
            db_txn_struct_i(result)->next = db_txn_struct_i(result->parent)->child;
            db_txn_struct_i(db_txn_struct_i(db_txn_struct_i(result->parent)->child)->prev)->next = result;
            db_txn_struct_i(db_txn_struct_i(result->parent)->child)->prev = result;
Yoni Fogel's avatar
Yoni Fogel committed
1230 1231
        }
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1232 1233 1234 1235
    *txn = result;
    return 0;
}

Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
1236
#if 0
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1237 1238
int txn_commit(DB_TXN * txn, u_int32_t flags) {
    fprintf(stderr, "%s:%d\n", __FILE__, __LINE__);
1239
    return toku_logger_log_commit(db_txn_struct_i(txn)->tokutxn);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1240
}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
1241
#endif
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1242

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1243
int log_compare(const DB_LSN * a, const DB_LSN * b) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1244
    toku_ydb_lock();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1245
    fprintf(stderr, "%s:%d log_compare(%p,%p)\n", __FILE__, __LINE__, a, b);
1246
    assert(0);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1247
    toku_ydb_unlock();
1248
    return 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1249 1250
}

1251 1252
static int
db_close_before_brt(DB *db, u_int32_t UU(flags)) {
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
    char *error_string = 0;
    int r1 = toku_close_brt(db->i->brt, db->dbenv->i->logger, &error_string);
    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;
1267
    if (db->i->db_id) { toku_db_id_remove_ref(&db->i->db_id); }
Yoni Fogel's avatar
Yoni Fogel committed
1268
    if (db->i->lt) {
1269 1270 1271 1272 1273
        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
1274
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1275
    // printf("%s:%d %d=__toku_db_close(%p)\n", __FILE__, __LINE__, r, db);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1276 1277
    // Even if panicked, let's close as much as we can.
    int is_panicked = toku_env_is_panicked(db->dbenv); 
Rich Prohaska's avatar
Rich Prohaska committed
1278
    env_unref(db->dbenv);
1279
    toku_free(db->i->fname);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
1280
    toku_free(db->i->full_fname);
1281 1282
    toku_sdbt_cleanup(&db->i->skey);
    toku_sdbt_cleanup(&db->i->sval);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
1283 1284
    toku_free(db->i);
    toku_free(db);
1285
    ydb_unref();
1286 1287 1288 1289
    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
1290 1291
}

1292 1293 1294 1295 1296 1297
static int toku_db_close(DB * db, u_int32_t flags) {
    int r = toku_brt_db_delay_closed(db->i->brt, db, db_close_before_brt, flags);
    return r;
}


1298 1299 1300
//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
1301 1302
}

1303 1304
static int get_nonmain_cursor_flags(u_int32_t flags) {
    return flags & ~(DB_OPFLAGS_MASK);
1305 1306
}

1307
static inline BOOL toku_c_uninitialized(DBC* c) {
1308
    return toku_brt_cursor_uninitialized(dbc_struct_i(c)->c);
Yoni Fogel's avatar
Yoni Fogel committed
1309
}            
Yoni Fogel's avatar
Yoni Fogel committed
1310

1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
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;
1322 1323
    context->skey = dbc_struct_i(c)->skey;
    context->sval = dbc_struct_i(c)->sval;
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
}

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 TOKULOGGER
c_get_logger(DBC *c) {
1337
    TOKUTXN txn = dbc_struct_i(c)->txn ? db_txn_struct_i(dbc_struct_i(c)->txn)->tokutxn : NULL;
1338 1339 1340 1341 1342 1343 1344 1345 1346
    TOKULOGGER logger = toku_txn_logger(txn);
    return logger;
}

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
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
    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
1357 1358 1359 1360 1361 1362 1363
/*
    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.
*/
1364
static inline DB_TXN* toku_txn_ancestor(DB_TXN* txn) {
Yoni Fogel's avatar
Yoni Fogel committed
1365
    while (txn && txn->parent) txn = txn->parent;
Yoni Fogel's avatar
Yoni Fogel committed
1366

Yoni Fogel's avatar
Yoni Fogel committed
1367 1368 1369
    return txn;
}

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

Yoni Fogel's avatar
Yoni Fogel committed
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
/* 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
1383
    u_int32_t   lock_flags;         // The prelock flags.
Yoni Fogel's avatar
Yoni Fogel committed
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
    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;

1394 1395 1396 1397
static inline u_int32_t get_prelocked_flags(u_int32_t flags, DB_TXN* txn) {
    u_int32_t lock_flags = flags & (DB_PRELOCKED | DB_PRELOCKED_WRITE);

    //DB_READ_UNCOMMITTED transactions 'own' all read locks.
1398
    if (txn && db_txn_struct_i(txn)->flags&DB_READ_UNCOMMITTED) lock_flags |= DB_PRELOCKED;
1399
    return lock_flags;
Yoni Fogel's avatar
Yoni Fogel committed
1400 1401
}

1402 1403 1404 1405
//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
1406

1407 1408
    int r = toku_brt_get_flags(db->i->brt, &brtflags);
    assert(r==0);
1409
    BOOL rval = (BOOL)(!(brtflags&TOKU_DB_DUPSORT));
1410
    return rval;
Yoni Fogel's avatar
Yoni Fogel committed
1411
}
Yoni Fogel's avatar
Yoni Fogel committed
1412

1413 1414 1415 1416
static BOOL
c_db_is_nodup(DBC *c) {
    BOOL rval = db_is_nodup(c->dbp);
    return rval;
Yoni Fogel's avatar
Yoni Fogel committed
1417 1418
}

1419 1420 1421
static int
toku_c_get(DBC* c, DBT* key, DBT* val, u_int32_t flag) {
    //OW!! SCALDING!
Yoni Fogel's avatar
Yoni Fogel committed
1422

1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
    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
1435
        case (DB_FIRST):
1436 1437
            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
1438
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1439
        case (DB_LAST):
1440 1441
            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
1442
            break;
1443 1444 1445
        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
1446
            break;
1447 1448 1449
        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
1450
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1451
        case (DB_NEXT_NODUP):
1452 1453
            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
1454 1455
            break;
        case (DB_PREV):
1456 1457
            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
1458 1459
            break;
#ifdef DB_PREV_DUP
Yoni Fogel's avatar
Yoni Fogel committed
1460
        case (DB_PREV_DUP):
1461 1462
            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
1463 1464
            break;
#endif
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
        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;
        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;
Yoni Fogel's avatar
Yoni Fogel committed
1497
        default:
Yoni Fogel's avatar
Yoni Fogel committed
1498
            r = EINVAL;
1499
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1500
    }
Yoni Fogel's avatar
Yoni Fogel committed
1501
    return r;
Yoni Fogel's avatar
Yoni Fogel committed
1502 1503
}

1504 1505
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
1506 1507
}

1508 1509 1510
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
1511

1512 1513
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
1514 1515
}

1516 1517 1518
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
1519

1520 1521 1522
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
1523

1524 1525
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
1526 1527
}

1528 1529 1530
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
1531

1532 1533 1534
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
1535

1536 1537
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
1538 1539
}

1540 1541 1542
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
1543

1544 1545 1546
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
1547

1548 1549 1550
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
1551

1552 1553 1554
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;
}
1555

1556 1557 1558
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
1559

1560 1561 1562 1563 1564 1565 1566 1567 1568 1569
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
1570

1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587
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
1588 1589
}

Yoni Fogel's avatar
Yoni Fogel committed
1590

1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601
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
1602 1603
}

1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
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) {
1624
        TXNID txn_anc_id = toku_txn_get_txnid(db_txn_struct_i(txn_anc)->tokutxn);
1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
        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
1636 1637
}

1638 1639
//This is the user level callback function given to ydb layer functions like
//toku_c_getf_first
Yoni Fogel's avatar
Yoni Fogel committed
1640

1641 1642 1643 1644 1645 1646 1647 1648
typedef struct query_context_base_t {
    BRT_CURSOR  c;
    DB_TXN     *txn;
    DB         *db;
    void       *f_extra;
    BOOL        do_locking;
    int         r_user_callback;
} *QUERY_CONTEXT_BASE, QUERY_CONTEXT_BASE_S;
1649

1650 1651 1652 1653
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
1654

1655 1656 1657 1658 1659 1660
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
1661

1662 1663 1664

static void
query_context_base_init(QUERY_CONTEXT_BASE context, DBC *c, u_int32_t flag, void *extra) {
1665 1666
    context->c       = dbc_struct_i(c)->c;
    context->txn     = dbc_struct_i(c)->txn;
1667 1668
    context->db      = c->dbp;
    context->f_extra = extra;
1669
    u_int32_t lock_flags = get_prelocked_flags(flag, dbc_struct_i(c)->txn);
Yoni Fogel's avatar
Yoni Fogel committed
1670 1671
    flag &= ~lock_flags;
    assert(flag==0);
1672
    context->do_locking = (BOOL)(context->db->i->lt!=NULL && !lock_flags);
1673
    context->r_user_callback = 0;
Yoni Fogel's avatar
Yoni Fogel committed
1674 1675
}

1676 1677 1678 1679 1680
static void
query_context_init(QUERY_CONTEXT context, DBC *c, u_int32_t flag, YDB_CALLBACK_FUNCTION f, void *extra) {
    query_context_base_init(&context->base, c, flag, extra);
    context->f = f;
}
Yoni Fogel's avatar
Yoni Fogel committed
1681

1682 1683 1684 1685 1686 1687
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) {
    query_context_base_init(&context->base, c, flag, extra);
    context->f         = f;
    context->input_key = key;
    context->input_val = val;
1688 1689
}

1690 1691 1692 1693 1694
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) {
1695 1696
    HANDLE_PANICKED_DB(c->dbp);

1697 1698 1699 1700
    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;
1701
    u_int32_t lock_flags = get_prelocked_flags(flags, dbc_struct_i(c)->txn);
1702
    unchecked_flags &= ~lock_flags;
1703
    BOOL do_locking = (BOOL)(c->dbp->i->lt && !(lock_flags&DB_PRELOCKED_WRITE));
1704

1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715
    int r = 0;
    if (unchecked_flags!=0) r = EINVAL;
    else {
        if (do_locking) {
            QUERY_CONTEXT_S context;
            query_context_init(&context, c, lock_flags, NULL, NULL);
            //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.
1716 1717
            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);
1718 1719
        }
    }
1720 1721
    return r;
}
1722

1723 1724 1725 1726 1727
//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
1728

1729
    int r;
Yoni Fogel's avatar
Yoni Fogel committed
1730

1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742
    assert(context->do_locking);
    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
1743 1744 1745
    return r;
}

1746 1747 1748 1749 1750 1751 1752 1753 1754 1755
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);

    QUERY_CONTEXT_S context; //Describes the context of this query.
    query_context_init(&context, c, flag, f, extra); 
    TOKULOGGER logger = c_get_logger(c);
    //toku_brt_cursor_first will call c_getf_first_callback(..., context) (if query is successful)
1756
    int r = toku_brt_cursor_first(dbc_struct_i(c)->c, c_getf_first_callback, &context, logger);
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809
    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);

    QUERY_CONTEXT_S context; //Describes the context of this query.
    query_context_init(&context, c, flag, f, extra); 
    TOKULOGGER logger = c_get_logger(c);
    //toku_brt_cursor_last will call c_getf_last_callback(..., context) (if query is successful)
1810
    int r = toku_brt_cursor_last(dbc_struct_i(c)->c, c_getf_last_callback, &context, logger);
1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866
    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);
    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.
        query_context_init(&context, c, flag, f, extra); 
        TOKULOGGER logger = c_get_logger(c);
        //toku_brt_cursor_next will call c_getf_next_callback(..., context) (if query is successful)
1867
        r = toku_brt_cursor_next(dbc_struct_i(c)->c, c_getf_next_callback, &context, logger);
1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920
        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);
    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.
        query_context_init(&context, c, flag, f, extra); 
        TOKULOGGER logger = c_get_logger(c);
        //toku_brt_cursor_next will call c_getf_next_callback(..., context) (if query is successful)
1921
        r = toku_brt_cursor_next_nodup(dbc_struct_i(c)->c, c_getf_next_callback, &context, logger);
1922 1923 1924 1925 1926 1927 1928 1929 1930
        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
1931 1932
    HANDLE_PANICKED_DB(c->dbp);
    if (toku_c_uninitialized(c)) return EINVAL;
1933 1934 1935 1936 1937

    QUERY_CONTEXT_S context; //Describes the context of this query.
    query_context_init(&context, c, flag, f, extra); 
    TOKULOGGER logger = c_get_logger(c);
    //toku_brt_cursor_next_dup will call c_getf_next_dup_callback(..., context) (if query is successful)
1938
    int r = toku_brt_cursor_next_dup(dbc_struct_i(c)->c, c_getf_next_dup_callback, &context, logger);
1939 1940 1941 1942 1943 1944 1945 1946 1947 1948
    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
1949 1950
    int r;

1951 1952 1953 1954
    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
1955

1956 1957 1958 1959 1960
    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
1961

1962 1963 1964 1965 1966 1967 1968
        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
1969

1970 1971 1972 1973
    //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
1974
    }
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992

    //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);
    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.
        query_context_init(&context, c, flag, f, extra); 
        TOKULOGGER logger = c_get_logger(c);
        //toku_brt_cursor_prev will call c_getf_prev_callback(..., context) (if query is successful)
1993
        r = toku_brt_cursor_prev(dbc_struct_i(c)->c, c_getf_prev_callback, &context, logger);
1994
        if (r == TOKUDB_USER_CALLBACK_ERROR) r = context.base.r_user_callback;
Yoni Fogel's avatar
Yoni Fogel committed
1995 1996 1997 1998
    }
    return r;
}

1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034
//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
2035 2036
}

2037 2038
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
2039
    int r;
2040 2041 2042 2043 2044 2045 2046
    HANDLE_PANICKED_DB(c->dbp);
    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.
        query_context_init(&context, c, flag, f, extra); 
        TOKULOGGER logger = c_get_logger(c);
        //toku_brt_cursor_prev will call c_getf_prev_callback(..., context) (if query is successful)
2047
        r = toku_brt_cursor_prev_nodup(dbc_struct_i(c)->c, c_getf_prev_callback, &context, logger);
2048 2049 2050 2051
        if (r == TOKUDB_USER_CALLBACK_ERROR) r = context.base.r_user_callback;
    }
    return r;
}
Yoni Fogel's avatar
Yoni Fogel committed
2052

2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063
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);
    if (toku_c_uninitialized(c)) return EINVAL;

    QUERY_CONTEXT_S context; //Describes the context of this query.
    query_context_init(&context, c, flag, f, extra); 
    TOKULOGGER logger = c_get_logger(c);
    //toku_brt_cursor_prev_dup will call c_getf_prev_dup_callback(..., context) (if query is successful)
2064
    int r = toku_brt_cursor_prev_dup(dbc_struct_i(c)->c, c_getf_prev_dup_callback, &context, logger);
2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115
    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);

    QUERY_CONTEXT_S context; //Describes the context of this query.
    query_context_init(&context, c, flag, f, extra); 
    TOKULOGGER logger = c_get_logger(c);
    //toku_brt_cursor_current will call c_getf_current_callback(..., context) (if query is successful)
2116
    int r = toku_brt_cursor_current(dbc_struct_i(c)->c, DB_CURRENT, c_getf_current_callback, &context, logger);
2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150
    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);

    QUERY_CONTEXT_S context; //Describes the context of this query.
    query_context_init(&context, c, flag, f, extra); 
    TOKULOGGER logger = c_get_logger(c);
    //toku_brt_cursor_current will call c_getf_current_callback(..., context) (if query is successful)
2151
    int r = toku_brt_cursor_current(dbc_struct_i(c)->c, DB_CURRENT_BINDING, c_getf_current_callback, &context, logger);
2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165
    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);

    QUERY_CONTEXT_WITH_INPUT_S context; //Describes the context of this query.
    query_context_with_input_init(&context, c, flag, key, NULL, f, extra); 
    TOKULOGGER logger = c_get_logger(c);
    //toku_brt_cursor_set will call c_getf_set_callback(..., context) (if query is successful)
2166
    int r = toku_brt_cursor_set(dbc_struct_i(c)->c, key, NULL, c_getf_set_callback, &context, logger);
2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222
    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);

    QUERY_CONTEXT_WITH_INPUT_S context; //Describes the context of this query.
    query_context_with_input_init(&context, c, flag, key, NULL, f, extra); 
    TOKULOGGER logger = c_get_logger(c);
    //toku_brt_cursor_set_range will call c_getf_set_range_callback(..., context) (if query is successful)
2223
    int r = toku_brt_cursor_set_range(dbc_struct_i(c)->c, key, c_getf_set_range_callback, &context, logger);
2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280
    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;
}

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);

    QUERY_CONTEXT_WITH_INPUT_S context; //Describes the context of this query.
    query_context_with_input_init(&context, c, flag, key, val, f, extra); 
    TOKULOGGER logger = c_get_logger(c);
    //toku_brt_cursor_get_both will call c_getf_get_both_callback(..., context) (if query is successful)
2281
    int r = toku_brt_cursor_set(dbc_struct_i(c)->c, key, val, c_getf_get_both_callback, &context, logger);
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 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332
    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);
    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.
        query_context_with_input_init(&context, c, flag, key, val, f, extra); 
        TOKULOGGER logger = c_get_logger(c);
        //toku_brt_cursor_get_both_range will call c_getf_get_both_range_callback(..., context) (if query is successful)
2333
        r = toku_brt_cursor_get_both_range(dbc_struct_i(c)->c, key, val, c_getf_get_both_range_callback, &context, logger);
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 2367 2368 2369 2370 2371 2372 2373 2374 2375 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 2423 2424 2425
        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;
}


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) {
    query_context_base_init(&context->base, c, flag, extra);
    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);
    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); 
    TOKULOGGER logger = c_get_logger(c);
    //toku_brt_cursor_heaviside will call c_getf_heaviside_callback(..., context) (if query is successful)
2426
    r = toku_brt_cursor_heaviside(dbc_struct_i(c)->c, c_getf_heaviside_callback, &context, logger, &wrapper);
2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456
    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)
2457
        BOOL found = (BOOL)(found_keyvec != NULL);
2458
        DBC *tmp_cursor; //Temporary cursor to find 'next_key/next_val'
Yoni Fogel's avatar
Yoni Fogel committed
2459 2460
        DBT tmp_key;
        DBT tmp_val;
2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476
        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
2477 2478 2479
                }
            }
            else {
2480 2481 2482
                //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
2483 2484 2485
            }
        }
        else {
2486 2487 2488 2489 2490 2491 2492 2493
            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
2494 2495 2496
                }
            }
            else {
2497 2498 2499
                //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
2500 2501
            }
        }
2502 2503 2504 2505 2506 2507 2508 2509 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 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555
        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
2556 2557 2558
    return r ? r : r2;
}

2559
static int toku_c_close(DBC * c) {
2560 2561 2562 2563 2564 2565
    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
2566
    toku_free(c);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2567 2568 2569
    return r;
}

2570 2571 2572 2573 2574
static inline int keyeq(DBC *c, DBT *a, DBT *b) {
    DB *db = c->dbp;
    return db->i->brt->compare_fun(db, a, b) == 0;
}

2575 2576 2577 2578
// 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) {
Rich Prohaska's avatar
Rich Prohaska committed
2579 2580
    int r;
    DBC *count_cursor = 0;
2581
    DBT currentkey;
Rich Prohaska's avatar
Rich Prohaska committed
2582

2583
    init_dbt_realloc(&currentkey);
2584
    u_int32_t lock_flags = get_prelocked_flags(flags, dbc_struct_i(cursor)->txn);
2585
    flags &= ~lock_flags;
Rich Prohaska's avatar
Rich Prohaska committed
2586 2587 2588 2589
    if (flags != 0) {
        r = EINVAL; goto finish;
    }

2590
    r = toku_c_get_current_unconditional(cursor, lock_flags, &currentkey, NULL);
Rich Prohaska's avatar
Rich Prohaska committed
2591
    if (r != 0) goto finish;
2592 2593 2594 2595 2596 2597

    //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
2598
    
2599
    r = toku_db_cursor(cursor->dbp, dbc_struct_i(cursor)->txn, &count_cursor, 0, 0);
Rich Prohaska's avatar
Rich Prohaska committed
2600 2601 2602
    if (r != 0) goto finish;

    *count = 0;
2603
    r = toku_c_getf_set(count_cursor, lock_flags, &currentkey, ydb_getf_do_nothing, NULL);
Rich Prohaska's avatar
Rich Prohaska committed
2604 2605 2606 2607 2608 2609
    if (r != 0) {
        r = 0; goto finish; /* success, the current key must be deleted and there are no more */
    }

    for (;;) {
        *count += 1;
2610
        r = toku_c_getf_next_dup(count_cursor, lock_flags, ydb_getf_do_nothing, NULL);
Rich Prohaska's avatar
Rich Prohaska committed
2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621
        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
2622

2623 2624
///////////
//db_getf_XXX is equivalent to c_getf_XXX, without a persistent cursor
Yoni Fogel's avatar
 
Yoni Fogel committed
2625

2626 2627 2628 2629 2630 2631 2632 2633
static int
db_getf_set(DB *db, DB_TXN *txn, u_int32_t flags, DBT *key, YDB_CALLBACK_FUNCTION f, void *extra) {
    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
2634
    }
2635
    return r;
Yoni Fogel's avatar
 
Yoni Fogel committed
2636 2637
}

2638 2639 2640 2641 2642 2643 2644 2645
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) {
    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
2646
    }
2647
    return r;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2648
}
2649
////////////
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2650

2651 2652
static int
toku_db_del(DB *db, DB_TXN *txn, DBT *key, u_int32_t flags) {
2653
    HANDLE_PANICKED_DB(db);
2654 2655
    u_int32_t unchecked_flags = flags;
    //DB_DELETE_ANY means delete regardless of whether it exists in the db.
2656
    BOOL error_if_missing = (BOOL)(!(flags&DB_DELETE_ANY));
2657 2658 2659
    unchecked_flags &= ~DB_DELETE_ANY;
    u_int32_t lock_flags = get_prelocked_flags(flags, txn);
    unchecked_flags &= ~lock_flags;
2660
    BOOL do_locking = (BOOL)(db->i->lt && !(lock_flags&DB_PRELOCKED_WRITE));
2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674
    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);
2675
    }
2676 2677
    if (r==0) {
        //Do the actual deleting.
2678
        r = toku_brt_delete(db->i->brt, key, txn ? db_txn_struct_i(txn)->tokutxn : 0);
2679
    }
2680
    return r;
Rich Prohaska's avatar
Rich Prohaska committed
2681 2682 2683
}

static int locked_c_get(DBC * c, DBT * key, DBT * data, u_int32_t flag) {
2684 2685 2686 2687
    //{ 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
2688 2689 2690
}

static int locked_c_close(DBC * c) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2691
    toku_ydb_lock(); int r = toku_c_close(c); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
2692 2693 2694
}

static int locked_c_count(DBC *cursor, db_recno_t *count, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2695
    toku_ydb_lock(); int r = toku_c_count(cursor, count, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
2696 2697 2698
}

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

2702
static int toku_db_cursor(DB * db, DB_TXN * txn, DBC ** c, u_int32_t flags, int is_temporary_cursor) {
2703
    HANDLE_PANICKED_DB(db);
2704 2705
    if (flags != 0)
        return EINVAL;
2706
    DBC *MALLOC(result);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2707 2708 2709
    if (result == 0)
        return ENOMEM;
    memset(result, 0, sizeof *result);
Yoni Fogel's avatar
Yoni Fogel committed
2710 2711 2712 2713 2714
#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
2715 2716
    SCRS(c_getf_first);
    SCRS(c_getf_last);
Yoni Fogel's avatar
Yoni Fogel committed
2717
    SCRS(c_getf_next);
2718
    SCRS(c_getf_next_nodup);
Yoni Fogel's avatar
Yoni Fogel committed
2719
    SCRS(c_getf_next_dup);
2720 2721 2722 2723 2724 2725 2726 2727 2728 2729
    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);
    SCRS(c_getf_get_both);
    SCRS(c_getf_get_both_range);
Yoni Fogel's avatar
Yoni Fogel committed
2730
#undef SCRS
2731 2732 2733

#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
2734
    assert(result->i);
2735
#endif
2736
    result->dbp = db;
2737 2738 2739
    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};
2740
    if (is_temporary_cursor) {
2741 2742
	dbc_struct_i(result)->skey = &db->i->skey;
	dbc_struct_i(result)->sval = &db->i->sval;
2743
    } else {
2744 2745
	dbc_struct_i(result)->skey = &dbc_struct_i(result)->skey_s;
	dbc_struct_i(result)->sval = &dbc_struct_i(result)->sval_s;
2746
    }
2747
    int r = toku_brt_cursor(db->i->brt, &dbc_struct_i(result)->c);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2748
    assert(r == 0);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2749 2750 2751 2752
    *c = result;
    return 0;
}

2753 2754
static int
toku_db_delboth(DB *db, DB_TXN *txn, DBT *key, DBT *val, u_int32_t flags) {
2755
    HANDLE_PANICKED_DB(db);
2756 2757
    u_int32_t unchecked_flags = flags;
    //DB_DELETE_ANY means delete regardless of whether it exists in the db.
2758
    BOOL error_if_missing = (BOOL)(!(flags&DB_DELETE_ANY));
2759
    unchecked_flags &= ~DB_DELETE_ANY;
2760
    u_int32_t lock_flags = get_prelocked_flags(flags, txn);
2761
    unchecked_flags &= ~lock_flags;
2762
    BOOL do_locking = (BOOL)(db->i->lt && !(lock_flags&DB_PRELOCKED_WRITE));
2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776
    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
2777
    }
2778 2779
    if (r==0) {
        //Do the actual deleting.
2780
        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
2781
    }
2782
    return r;
Yoni Fogel's avatar
Yoni Fogel committed
2783 2784
}

Rich Prohaska's avatar
Rich Prohaska committed
2785 2786 2787 2788
static inline int db_thread_need_flags(DBT *dbt) {
    return (dbt->flags & (DB_DBT_MALLOC+DB_DBT_REALLOC+DB_DBT_USERMEM)) == 0;
}

2789
static int toku_db_get (DB * db, DB_TXN * txn, DBT * key, DBT * data, u_int32_t flags) {
2790
    HANDLE_PANICKED_DB(db);
Yoni Fogel's avatar
Yoni Fogel committed
2791
    int r;
2792

Rich Prohaska's avatar
Rich Prohaska committed
2793
    if ((db->i->open_flags & DB_THREAD) && db_thread_need_flags(data))
2794 2795
        return EINVAL;

2796
    u_int32_t lock_flags = get_prelocked_flags(flags, txn);
Yoni Fogel's avatar
Yoni Fogel committed
2797
    flags &= ~lock_flags;
Yoni Fogel's avatar
Yoni Fogel committed
2798 2799 2800 2801
    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;
2802
    r = toku_db_cursor(db, txn, &dbc, 0, 1);
Yoni Fogel's avatar
Yoni Fogel committed
2803
    if (r!=0) return r;
Yoni Fogel's avatar
Yoni Fogel committed
2804 2805
    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
2806 2807
    int r2 = toku_c_close(dbc);
    return r ? r : r2;
2808 2809
}

Rich Prohaska's avatar
Rich Prohaska committed
2810
#if 0
2811
static int toku_db_key_range(DB * db, DB_TXN * txn, DBT * dbt, DB_KEY_RANGE * kr, u_int32_t flags) {
2812 2813
    HANDLE_PANICKED_DB(db);
    txn=txn; dbt=dbt; kr=kr; flags=flags;
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2814
    toku_ydb_barf();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2815
    abort();
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2816
}
Rich Prohaska's avatar
Rich Prohaska committed
2817
#endif
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2818

Yoni Fogel's avatar
Yoni Fogel committed
2819 2820 2821 2822
static int construct_full_name_in_buf(const char *dir, const char *fname, char* full, int length) {
    int l;

    if (!full) return EINVAL;
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837
    if (toku_os_is_absolute_name(fname)) {
        l = 0;
        full[0] = '\0';
    }
    else {
        l = snprintf(full, length, "%s", dir);
        if (l >= length) return ENAMETOOLONG;
        if (l == 0 || full[l - 1] != '/') {
            if (l + 1 == length) return ENAMETOOLONG;
                
            /* Didn't put a slash down. */
            if (fname[0] != '/') {
                full[l++] = '/';
                full[l] = 0;
            }
Yoni Fogel's avatar
Yoni Fogel committed
2838 2839 2840 2841 2842 2843 2844
        }
    }
    l += snprintf(full + l, length - l, "%s", fname);
    if (l >= length) return ENAMETOOLONG;
    return 0;
}

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2845
static char *construct_full_name(const char *dir, const char *fname) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2846
    if (toku_os_is_absolute_name(fname))
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2847
        dir = "";
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2848
    {
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2849 2850 2851 2852
        int dirlen = strlen(dir);
        int fnamelen = strlen(fname);
        int len = dirlen + fnamelen + 2;        // One for the / between (which may not be there).  One for the trailing null.
        char *result = toku_malloc(len);
Yoni Fogel's avatar
Yoni Fogel committed
2853 2854 2855 2856
        // printf("%s:%d len(%d)=%d+%d+2\n", __FILE__, __LINE__, len, dirlen, fnamelen);
        if (construct_full_name_in_buf(dir, fname, result, len) != 0) {
            toku_free(result);
            result = NULL;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2857 2858
        }
        return result;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2859 2860 2861
    }
}

2862
static int find_db_file(DB_ENV* dbenv, const char *fname, char** full_name_out) {
Yoni Fogel's avatar
Yoni Fogel committed
2863 2864
    u_int32_t i;
    int r;
2865
    toku_struct_stat statbuf;
Yoni Fogel's avatar
Yoni Fogel committed
2866 2867 2868 2869 2870 2871 2872 2873
    char* full_name;
    
    assert(full_name_out);    
    if (dbenv->i->data_dirs!=NULL) {
        assert(dbenv->i->n_data_dirs > 0);
        for (i = 0; i < dbenv->i->n_data_dirs; i++) {
            full_name = construct_full_name(dbenv->i->data_dirs[0], fname);
            if (!full_name) return ENOMEM;
2874
            r = toku_stat(full_name, &statbuf);
Yoni Fogel's avatar
Yoni Fogel committed
2875 2876 2877
            if (r == 0) goto finish;
            else {
                toku_free(full_name);
Rich Prohaska's avatar
Rich Prohaska committed
2878
                r = errno;
Yoni Fogel's avatar
Yoni Fogel committed
2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895
                if (r != ENOENT) return r;
            }
        }
        //Did not find it at all.  Return the first data dir.
        full_name = construct_full_name(dbenv->i->data_dirs[0], fname);
        goto finish;
    }
    //Default without data_dirs is the environment directory.
    full_name = construct_full_name(dbenv->i->dir, fname);
    goto finish;

finish:
    if (!full_name) return ENOMEM;
    *full_name_out = full_name;
    return 0;    
}

Yoni Fogel's avatar
Yoni Fogel committed
2896
static int toku_db_lt_panic(DB* db, int r) {
2897
    assert(r!=0);
Yoni Fogel's avatar
Yoni Fogel committed
2898 2899
    assert(db && db->i && db->dbenv && db->dbenv->i);
    DB_ENV* env = db->dbenv;
2900 2901 2902 2903 2904
    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");

2905
    return toku_ydb_do_error(env, r, "%s", env->i->panic_string);
Yoni Fogel's avatar
Yoni Fogel committed
2906 2907
}

Yoni Fogel's avatar
Yoni Fogel committed
2908
static int toku_txn_add_lt(DB_TXN* txn, toku_lock_tree* lt) {
Yoni Fogel's avatar
Yoni Fogel committed
2909
    int r = ENOSYS;
Yoni Fogel's avatar
Yoni Fogel committed
2910
    assert(txn && lt);
2911
    toku_lth* lth = db_txn_struct_i(txn)->lth;
Yoni Fogel's avatar
Yoni Fogel committed
2912 2913 2914 2915 2916
    assert(lth);

    toku_lock_tree* find = toku_lth_find(lth, lt);
    if (find) {
        assert(find == lt);
Yoni Fogel's avatar
Yoni Fogel committed
2917 2918
        r = 0;
        goto cleanup;
Yoni Fogel's avatar
Yoni Fogel committed
2919
    }
Yoni Fogel's avatar
Yoni Fogel committed
2920 2921 2922 2923 2924 2925
    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
2926 2927 2928
    return r;
}

Yoni Fogel's avatar
Yoni Fogel committed
2929 2930 2931
static toku_dbt_cmp toku_db_get_compare_fun(DB* db) {
    return db->i->brt->compare_fun;
}
Yoni Fogel's avatar
Yoni Fogel committed
2932

Yoni Fogel's avatar
Yoni Fogel committed
2933 2934
static toku_dbt_cmp toku_db_get_dup_compare(DB* db) {
    return db->i->brt->dup_compare;
Yoni Fogel's avatar
Yoni Fogel committed
2935 2936
}

2937 2938 2939 2940 2941 2942
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);
}

2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988
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 multiple_db_open(DB * db, DB_TXN * txn, const char *fname, const char *dbname, DBTYPE dbtype, u_int32_t flags, int mode) {
    //Only flag we look at is create.  If create is there, we create directory if necessary.
    //If create is not set and directory not exists, we quit out with errors.
    int is_db_create  = flags & DB_CREATE;

    char *directory_name = NULL;
    BOOL created_directory = FALSE;
    int r = find_db_file(db->dbenv, fname, &directory_name);
    if (r!=0) goto cleanup;
    toku_struct_stat statbuf;
    r = toku_stat(directory_name, &statbuf);
    if (r!=0) { r = errno; assert(r!=0); }
    if (r==0 && !S_ISDIR(statbuf.st_mode)) { r = ENOTDIR; goto cleanup; } //File exists, but is not a directory.
    if (r!=0 && r!=ENOENT) goto cleanup;
    if (r==ENOENT && is_db_create) {
        //Try to create the directory.
        r = toku_os_mkdir(directory_name, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH);
        if (r==0) created_directory = TRUE;
        else { r = errno; assert(r!=0); }
    }
    if (r!=0) goto cleanup;
    {
        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);
    }

cleanup:
    if (r!=0) {
        if (created_directory) {
            //Failure on create, and directory did not previously exist.
            //Lets delete the directory.
            //TODO: Since we failed the db create, perhaps we should delete
            //the directory (it was only made for this).
            //Possible race conditions could exist if we do this.
            //Files may still be there.
        }
    }
    if (directory_name) toku_free(directory_name);
    return r;
}

2989
static int toku_db_open(DB * db, DB_TXN * txn, const char *fname, const char *dbname, DBTYPE dbtype, u_int32_t flags, int mode) {
2990
    HANDLE_PANICKED_DB(db);
2991 2992 2993 2994 2995
    if (dbname!=NULL) 
        return multiple_db_open(db, txn, fname, dbname, dbtype, flags, mode);

    //This code ONLY supports single-db files.
    assert(dbname==NULL);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2996
    // Warning.  Should check arguments.  Should check return codes on malloc and open and so forth.
2997 2998
    BOOL need_locktree = (BOOL)((db->dbenv->i->open_flags & DB_INIT_LOCK) &&
                                (db->dbenv->i->open_flags & DB_INIT_TXN));
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2999

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3000
    int openflags = 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3001
    int r;
Yoni Fogel's avatar
Yoni Fogel committed
3002
    if (dbtype!=DB_BTREE && dbtype!=DB_UNKNOWN) return EINVAL;
3003 3004 3005
    int is_db_excl    = flags & DB_EXCL;    flags&=~DB_EXCL;
    int is_db_create  = flags & DB_CREATE;  flags&=~DB_CREATE;
    int is_db_rdonly  = flags & DB_RDONLY;  flags&=~DB_RDONLY;
3006 3007
    //We support READ_UNCOMMITTED whether or not the flag is provided.
                                            flags&=~DB_READ_UNCOMMITTED;
3008
    if (dbtype != DB_UNKNOWN && dbtype != DB_BTREE) return EINVAL;
3009
    if (flags & ~DB_THREAD) return EINVAL; // unknown flags
3010 3011 3012

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

3014 3015 3016 3017 3018 3019 3020 3021
    /* 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;

3022
    if (db_opened(db))
3023
        return EINVAL;              /* It was already open. */
Yoni Fogel's avatar
Yoni Fogel committed
3024 3025 3026
    
    r = find_db_file(db->dbenv, fname, &db->i->full_fname);
    if (r != 0) goto error_cleanup;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3027
    // printf("Full name = %s\n", db->i->full_fname);
3028 3029 3030 3031 3032
    assert(db->i->fname == 0);
    db->i->fname = toku_strdup(fname);
    if (db->i->fname == 0) { 
        r = ENOMEM; goto error_cleanup;
    }
3033
    if (is_db_rdonly)
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3034 3035 3036
        openflags |= O_RDONLY;
    else
        openflags |= O_RDWR;
3037
    
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3038
    {
3039 3040
        toku_struct_stat statbuf;
        if (toku_stat(db->i->full_fname, &statbuf) == 0) {
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3041
            /* If the database exists at the file level, and we specified no db_name, then complain here. */
3042 3043
            if (dbname == 0 && is_db_create) {
                if (is_db_excl) {
3044 3045 3046
                    r = EEXIST;
                    goto error_cleanup;
                }
3047
		is_db_create = 0; // It's not a create after all, since the file exists.
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3048 3049
            }
        } else {
3050
            if (!is_db_create) {
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3051 3052 3053 3054
                r = ENOENT;
                goto error_cleanup;
            }
        }
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3055
    }
3056
    if (is_db_create) openflags |= O_CREAT;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3057 3058 3059

    db->i->open_flags = flags;
    db->i->open_mode = mode;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3060

Yoni Fogel's avatar
Yoni Fogel committed
3061

3062
    r = toku_brt_open(db->i->brt, db->i->full_fname, fname,
3063
		      is_db_create, is_db_excl,
3064
		      db->dbenv->i->cachetable,
3065
		      txn ? db_txn_struct_i(txn)->tokutxn : NULL_TXN,
3066
		      db);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3067 3068 3069
    if (r != 0)
        goto error_cleanup;

Yoni Fogel's avatar
Yoni Fogel committed
3070
    if (need_locktree) {
Yoni Fogel's avatar
Yoni Fogel committed
3071 3072 3073
        unsigned int brtflags;
        BOOL dups;
        toku_brt_get_flags(db->i->brt, &brtflags);
3074
        dups = (BOOL)((brtflags & TOKU_DB_DUPSORT || brtflags & TOKU_DB_DUP));
Yoni Fogel's avatar
Yoni Fogel committed
3075

3076 3077 3078 3079
        int db_fd;
        r = toku_db_fd(db, &db_fd);
        if (r!=0) goto error_cleanup;
        assert(db_fd>=0);
3080
        r = toku_db_id_create(&db->i->db_id, db_fd);
Yoni Fogel's avatar
Yoni Fogel committed
3081 3082 3083
        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
3084
    }
Yoni Fogel's avatar
Yoni Fogel committed
3085

Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3086
    return 0;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3087 3088
 
error_cleanup:
Yoni Fogel's avatar
Yoni Fogel committed
3089
    if (db->i->db_id) {
3090
        toku_db_id_remove_ref(&db->i->db_id);
Yoni Fogel's avatar
Yoni Fogel committed
3091 3092
        db->i->db_id = NULL;
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3093 3094 3095 3096
    if (db->i->full_fname) {
        toku_free(db->i->full_fname);
        db->i->full_fname = NULL;
    }
3097 3098 3099 3100
    if(db->i->fname) {
        toku_free(db->i->fname);
        db->i->fname = NULL;
    }
Yoni Fogel's avatar
Yoni Fogel committed
3101
    if (db->i->lt) {
Yoni Fogel's avatar
Yoni Fogel committed
3102
        toku_lt_remove_ref(db->i->lt);
Yoni Fogel's avatar
Yoni Fogel committed
3103 3104
        db->i->lt = NULL;
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3105
    return r;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3106
}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
3107

3108 3109 3110 3111 3112
//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) {
3113
    int r;
3114

3115
    BOOL dupsort = (BOOL)(!db_is_nodup(db));
3116
    //Check limits on size of key and val.
3117
    unsigned int nodesize;
3118
    r = toku_brt_get_nodesize(db->i->brt, &nodesize); assert(r == 0);
3119
    u_int32_t limit;
3120

3121 3122 3123
    if (dupsort) {
        limit = nodesize / (2*BRT_FANOUT-1);
        if (key->size + val->size >= limit)
Yoni Fogel's avatar
Yoni Fogel committed
3124
            r = toku_ydb_do_error(db->dbenv, EINVAL, "The largest (key + val) item allowed is %u bytes", limit-1);
3125
    } else {
3126 3127
        limit = nodesize / (3*BRT_FANOUT-1);
        if (key->size >= limit || val->size >= limit)
Yoni Fogel's avatar
Yoni Fogel committed
3128
            r = toku_ydb_do_error(db->dbenv, EINVAL, "The largest key or val item allowed is %u bytes", limit-1);
Yoni Fogel's avatar
Yoni Fogel committed
3129
    }
3130 3131 3132
    return r;
}

3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153
//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;
}

3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176
//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");
        }
3177
    }
3178 3179 3180
    else {
        //Other flags are not (yet) supported.
        r = EINVAL;
3181 3182 3183 3184
    }
    return r;
}

3185 3186
static int
toku_db_put(DB *db, DB_TXN *txn, DBT *key, DBT *val, u_int32_t flags) {
3187
    HANDLE_PANICKED_DB(db);
3188 3189
    int r;

3190 3191
    u_int32_t lock_flags = get_prelocked_flags(flags, txn);
    flags &= ~lock_flags;
3192
    BOOL do_locking = (BOOL)(db->i->lt && !(lock_flags&DB_PRELOCKED_WRITE));
3193

3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206
    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);
3207
    }
3208 3209
    if (r==0) {
        //Insert into the brt.
3210
        r = toku_brt_insert(db->i->brt, key, val, txn ? db_txn_struct_i(txn)->tokutxn : 0);
3211 3212
    }
    return r;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3213
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3214

3215 3216 3217 3218
static int toku_db_remove(DB * db, const char *fname, const char *dbname, u_int32_t flags);

static int
toku_db_remove_subdb(DB * db, const char *fname, const char *dbname, u_int32_t flags) {
3219
    BOOL need_close = TRUE;
3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231
    char *directory_name = NULL;
    int r = find_db_file(db->dbenv, fname, &directory_name);
    if (r!=0) goto cleanup;
    toku_struct_stat statbuf;
    r = toku_stat(directory_name, &statbuf);
    if (r==0 && !S_ISDIR(statbuf.st_mode)) { r = ENOTDIR; goto cleanup; } //File exists, but is not a directory.
    if (r!=0) { r = errno; assert(r!=0); goto cleanup; }
    {
        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;
3232
        need_close = FALSE;
3233 3234 3235 3236
        r = toku_db_remove(db, subdb_full_name, null_subdbname, flags);
    }

cleanup:
3237 3238 3239 3240
    if (need_close) {
        int r2 = toku_db_close(db, 0);
        if (r==0) r = r2;
    }
3241 3242 3243 3244 3245
    if (directory_name) toku_free(directory_name);
    return r;
}

//TODO: Maybe delete directory when last 'subdb' is deleted.
3246
static int toku_db_remove(DB * db, const char *fname, const char *dbname, u_int32_t flags) {
3247
    HANDLE_PANICKED_DB(db);
3248 3249
    if (dbname)
        return toku_db_remove_subdb(db, fname, dbname, flags);
Yoni Fogel's avatar
Yoni Fogel committed
3250 3251 3252 3253 3254 3255
    int r = ENOSYS;
    int r2 = 0;
    toku_db_id* db_id = NULL;
    BOOL need_close   = TRUE;
    char* full_name   = NULL;
    toku_ltm* ltm     = NULL;
Yoni Fogel's avatar
Yoni Fogel committed
3256 3257

    //TODO: Verify DB* db not yet opened
Yoni Fogel's avatar
Yoni Fogel committed
3258
    //TODO: Verify db file not in use. (all dbs in the file must be unused)
3259
    r = toku_db_open(db, NULL, fname, dbname, DB_UNKNOWN, 0, S_IRWXU|S_IRWXG|S_IRWXO);
3260
    if (r==TOKUDB_DICTIONARY_TOO_OLD || r==TOKUDB_DICTIONARY_TOO_NEW || r==TOKUDB_DICTIONARY_NO_HEADER) {
Yoni Fogel's avatar
Yoni Fogel committed
3261 3262 3263
        need_close = FALSE;
        goto delete_db_file;
    }
Yoni Fogel's avatar
Yoni Fogel committed
3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276
    if (r!=0) { goto cleanup; }
    if (db->i->lt) {
        /* Lock tree exists, therefore:
           * Non-private environment (since we are using transactions)
           * Environment will exist after db->close */
        if (db->i->db_id) {
            /* 'copy' the db_id */
            db_id = db->i->db_id;
            toku_db_id_add_ref(db_id);
        }
        if (db->dbenv->i->ltm) { ltm = db->dbenv->i->ltm; }
    }
    
Yoni Fogel's avatar
Yoni Fogel committed
3277
delete_db_file:
3278 3279 3280 3281 3282 3283 3284
    r = find_db_file(db->dbenv, fname, &full_name);
    if (r!=0) { goto cleanup; }
    assert(full_name);
    r = toku_db_close(db, 0);
    need_close = FALSE;
    if (r!=0) { goto cleanup; }
    if (unlink(full_name) != 0) { r = errno; goto cleanup; }
3285

Yoni Fogel's avatar
Yoni Fogel committed
3286 3287 3288 3289 3290 3291
    if (ltm && db_id) { toku_ltm_invalidate_lt(ltm, db_id); }

    r = 0;
cleanup:
    if (need_close) { r2 = toku_db_close(db, 0); }
    if (full_name)  { toku_free(full_name); }
3292
    if (db_id)      { toku_db_id_remove_ref(&db_id); }
Yoni Fogel's avatar
Yoni Fogel committed
3293
    return r ? r : r2;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3294
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3295

Yoni Fogel's avatar
Yoni Fogel committed
3296 3297 3298 3299 3300 3301 3302 3303
/* TODO: Either
    -find a way for the DB_ID to survive this rename (i.e. be
     the same before and after
    or
    -Go through all DB_IDs in the ltm, and rename them so we
     have the correct unique ids.
   TODO: Verify the DB file is not in use (either a single db file or
         a file with multi-databases).
3304
   TODO: Check the other directories in the environment for the file
3305
TODO: Alert the BRT layer (for logging/recovery purposes)
Yoni Fogel's avatar
Yoni Fogel committed
3306
*/
3307
static int toku_db_rename(DB * db, const char *namea, const char *nameb, const char *namec, u_int32_t flags) {
3308
    HANDLE_PANICKED_DB(db);
3309
    if (flags!=0) return EINVAL;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
3310 3311
    char afull[PATH_MAX], cfull[PATH_MAX];
    int r;
3312 3313 3314 3315
    if (nameb)
        r = snprintf(afull, PATH_MAX, "%s%s/%s", db->dbenv->i->dir, namea, nameb);
    else
        r = snprintf(afull, PATH_MAX, "%s%s", db->dbenv->i->dir, namea);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3316 3317 3318
    assert(r < PATH_MAX);
    r = snprintf(cfull, PATH_MAX, "%s%s", db->dbenv->i->dir, namec);
    assert(r < PATH_MAX);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
3319
    return rename(afull, cfull);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3320
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3321

3322
static int toku_db_set_bt_compare(DB * db, int (*bt_compare) (DB *, const DBT *, const DBT *)) {
3323
    HANDLE_PANICKED_DB(db);
3324
    int r = toku_brt_set_bt_compare(db->i->brt, bt_compare);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3325 3326 3327
    return r;
}

3328
static int toku_db_set_dup_compare(DB *db, int (*dup_compare)(DB *, const DBT *, const DBT *)) {
3329
    HANDLE_PANICKED_DB(db);
3330
    int r = toku_brt_set_dup_compare(db->i->brt, dup_compare);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3331 3332 3333
    return r;
}

3334
static int toku_db_set_descriptor(DB *db, u_int32_t version, const DBT* descriptor, toku_dbt_upgradef dbt_userformat_upgrade) {
3335 3336 3337 3338 3339
    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;
3340
    else r = toku_brt_set_descriptor(db->i->brt, version, descriptor, dbt_userformat_upgrade);
3341 3342 3343
    return r;
}

Rich Prohaska's avatar
Rich Prohaska committed
3344
static int toku_db_set_flags(DB *db, u_int32_t flags) {
3345
    HANDLE_PANICKED_DB(db);
3346

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

Yoni Fogel's avatar
Yoni Fogel committed
3350 3351 3352 3353
    u_int32_t tflags;
    int r = toku_brt_get_flags(db->i->brt, &tflags);
    if (r!=0) return r;
    
3354 3355 3356 3357
    if (flags & DB_DUP)
        tflags += TOKU_DB_DUP;
    if (flags & DB_DUPSORT)
        tflags += TOKU_DB_DUPSORT;
Yoni Fogel's avatar
Yoni Fogel committed
3358
    r = toku_brt_set_flags(db->i->brt, tflags);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3359 3360 3361
    return r;
}

3362
static int toku_db_get_flags(DB *db, u_int32_t *pflags) {
3363
    HANDLE_PANICKED_DB(db);
3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381
    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;
    }
    assert(tflags == 0);
    *pflags = flags;
    return 0;
}

3382
static int toku_db_set_pagesize(DB *db, u_int32_t pagesize) {
3383
    HANDLE_PANICKED_DB(db);
3384
    int r = toku_brt_set_nodesize(db->i->brt, pagesize);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3385
    return r;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3386
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3387

3388
static int toku_db_stat64(DB * db, DB_TXN *txn, DB_BTREE_STAT64 *s) {
3389
    HANDLE_PANICKED_DB(db);
3390
    return toku_brt_stat64(db->i->brt, db_txn_struct_i(txn)->tokutxn, &s->bt_nkeys, &s->bt_ndata, &s->bt_dsize, &s->bt_fsize);
3391 3392 3393 3394 3395 3396 3397
}
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
3398 3399
}

Yoni Fogel's avatar
Yoni Fogel committed
3400
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
3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414
    HANDLE_PANICKED_DB(db);

    // 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;
}

3415
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
3416 3417
    HANDLE_PANICKED_DB(db);
    if (!db->i->lt || !txn) return EINVAL;
3418
    //READ_UNCOMMITTED transactions do not need read locks.
3419
    if (db_txn_struct_i(txn)->flags&DB_READ_UNCOMMITTED) return 0;
Yoni Fogel's avatar
Yoni Fogel committed
3420 3421 3422 3423

    DB_TXN* txn_anc = toku_txn_ancestor(txn);
    int r;
    if ((r=toku_txn_add_lt(txn_anc, db->i->lt))) return r;
3424
    TXNID id_anc = toku_txn_get_txnid(db_txn_struct_i(txn_anc)->tokutxn);
Yoni Fogel's avatar
Yoni Fogel committed
3425 3426 3427 3428 3429 3430 3431

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

3432
static int toku_db_pre_acquire_table_lock(DB *db, DB_TXN *txn) {
Yoni Fogel's avatar
Yoni Fogel committed
3433 3434 3435 3436 3437 3438
    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;
3439
    TXNID id_anc = toku_txn_get_txnid(db_txn_struct_i(txn_anc)->tokutxn);
Yoni Fogel's avatar
Yoni Fogel committed
3440 3441 3442 3443

    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);
3444
    if (r==0) {
3445
	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.
3446 3447
    }

Yoni Fogel's avatar
Yoni Fogel committed
3448 3449
    return r;
}
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3450

Yoni Fogel's avatar
Yoni Fogel committed
3451 3452 3453
//TODO: DB_AUTO_COMMIT.
//TODO: Nowait only conditionally?
//TODO: NOSYNC change to SYNC if DB_ENV has something in set_flags
3454
static inline int toku_db_construct_autotxn(DB* db, DB_TXN **txn, BOOL* changed,
Yoni Fogel's avatar
Yoni Fogel committed
3455 3456 3457 3458 3459 3460 3461
                                            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;
    }
3462
    BOOL nosync = (BOOL)(!force_auto_commit && !(env->i->open_flags & DB_AUTO_COMMIT));
Yoni Fogel's avatar
Yoni Fogel committed
3463 3464 3465 3466 3467 3468 3469
    u_int32_t txn_flags = DB_TXN_NOWAIT | (nosync ? DB_TXN_NOSYNC : 0);
    int r = toku_txn_begin(env, NULL, txn, txn_flags);
    if (r!=0) return r;
    *changed = TRUE;
    return 0;
}

3470
static inline int toku_db_destruct_autotxn(DB_TXN *txn, int r, BOOL changed) {
Yoni Fogel's avatar
Yoni Fogel committed
3471 3472 3473 3474 3475 3476
    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
3477
static int locked_db_close(DB * db, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3478
    toku_ydb_lock(); int r = toku_db_close(db, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
3479 3480
}

3481
static inline int autotxn_db_cursor(DB *db, DB_TXN *txn, DBC **c, u_int32_t flags) {
Yoni Fogel's avatar
Yoni Fogel committed
3482
    if (!txn && (db->dbenv->i->open_flags & DB_INIT_TXN)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3483
        return toku_ydb_do_error(db->dbenv, EINVAL,
Yoni Fogel's avatar
Yoni Fogel committed
3484 3485
              "Cursors in a transaction environment must have transactions.\n");
    }
3486
    return toku_db_cursor(db, txn, c, flags, 0);
Yoni Fogel's avatar
Yoni Fogel committed
3487 3488
}

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

3493
static inline int autotxn_db_del(DB* db, DB_TXN* txn, DBT* key,
Yoni Fogel's avatar
Yoni Fogel committed
3494 3495 3496 3497 3498 3499 3500 3501
                                 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
3502
static int locked_db_del(DB * db, DB_TXN * txn, DBT * key, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3503
    toku_ydb_lock(); int r = autotxn_db_del(db, txn, key, flags); toku_ydb_unlock(); return r;
Yoni Fogel's avatar
Yoni Fogel committed
3504 3505
}

Yoni Fogel's avatar
Yoni Fogel committed
3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518
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;
}

3519
static inline int autotxn_db_get(DB* db, DB_TXN* txn, DBT* key, DBT* data,
Yoni Fogel's avatar
Yoni Fogel committed
3520 3521 3522 3523 3524 3525
                                 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
3526 3527 3528
}

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
3529
    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
3530 3531
}

3532
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
3533 3534 3535 3536 3537 3538
    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;
}

3539
static int locked_db_pre_acquire_table_lock(DB *db, DB_TXN *txn) {
Yoni Fogel's avatar
Yoni Fogel committed
3540 3541 3542 3543 3544 3545
    toku_ydb_lock();
    int r = toku_db_pre_acquire_table_lock(db, txn);
    toku_ydb_unlock();
    return r;
}

3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567
// 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);
    int r;

    // dont support flags (yet)
    if (flags)
        return EINVAL;
    // dont support cursors 
    if (toku_brt_get_cursor_count(db->i->brt) > 0)
        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;

3568
    r = toku_brt_truncate(db->i->brt);
3569 3570 3571 3572

    return r;
}

3573
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
3574
    BOOL changed; int r;
3575
    r = toku_db_construct_autotxn(db, &txn, &changed, (BOOL)((flags & DB_AUTO_COMMIT) != 0));
Yoni Fogel's avatar
Yoni Fogel committed
3576 3577 3578
    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
3579 3580 3581
}

static int locked_db_open(DB *db, DB_TXN *txn, const char *fname, const char *dbname, DBTYPE dbtype, u_int32_t flags, int mode) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3582
    toku_ydb_lock(); int r = autotxn_db_open(db, txn, fname, dbname, dbtype, flags, mode); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
3583 3584
}

3585
static inline int autotxn_db_put(DB* db, DB_TXN* txn, DBT* key, DBT* data,
Yoni Fogel's avatar
Yoni Fogel committed
3586
                                 u_int32_t flags) {
3587
    //{ 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
3588 3589 3590 3591 3592 3593 3594
    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
3595
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
3596
    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
3597 3598 3599
}

static int locked_db_remove(DB * db, const char *fname, const char *dbname, u_int32_t flags) {
3600 3601 3602 3603 3604 3605
    toku_checkpoint_safe_client_lock();
    toku_ydb_lock();
    int r = toku_db_remove(db, fname, dbname, flags);
    toku_ydb_unlock();
    toku_checkpoint_safe_client_unlock();
    return r;
Rich Prohaska's avatar
Rich Prohaska committed
3606 3607 3608
}

static int locked_db_rename(DB * db, const char *namea, const char *nameb, const char *namec, u_int32_t flags) {
3609 3610 3611 3612 3613 3614
    toku_checkpoint_safe_client_lock();
    toku_ydb_lock();
    int r = toku_db_rename(db, namea, nameb, namec, flags);
    toku_ydb_unlock();
    toku_checkpoint_safe_client_unlock();
    return r;
Rich Prohaska's avatar
Rich Prohaska committed
3615 3616 3617
}

static int locked_db_set_bt_compare(DB * db, int (*bt_compare) (DB *, const DBT *, const DBT *)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3618
    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
3619 3620 3621
}

static int locked_db_set_dup_compare(DB * db, int (*dup_compare) (DB *, const DBT *, const DBT *)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3622
    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
3623 3624
}

3625 3626 3627 3628 3629
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;
3630 3631
}

Rich Prohaska's avatar
Rich Prohaska committed
3632 3633 3634 3635 3636
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
3637
    toku_ydb_lock(); int r = toku_db_set_flags(db, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
3638 3639 3640
}

static int locked_db_get_flags(DB *db, u_int32_t *flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3641
    toku_ydb_lock(); int r = toku_db_get_flags(db, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
3642 3643 3644
}

static int locked_db_set_pagesize(DB *db, u_int32_t pagesize) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3645
    toku_ydb_lock(); int r = toku_db_set_pagesize(db, pagesize); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
3646 3647 3648
}

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

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3652

Yoni Fogel's avatar
Yoni Fogel committed
3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664
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
3665 3666
}

3667
static int locked_db_truncate(DB *db, DB_TXN *txn, u_int32_t *row_count, u_int32_t flags) {
3668 3669 3670 3671 3672 3673
    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;
3674 3675
}

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

3679 3680
    if (flags) return EINVAL;

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3681 3682 3683
    /* if the env already exists then add a ref to it
       otherwise create one */
    if (env) {
Rich Prohaska's avatar
Rich Prohaska committed
3684
        if (!env_opened(env))
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3685
            return EINVAL;
Rich Prohaska's avatar
Rich Prohaska committed
3686
        env_add_ref(env);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3687
    } else {
Rich Prohaska's avatar
Rich Prohaska committed
3688
        r = toku_env_create(&env, 0);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3689 3690
        if (r != 0)
            return r;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
3691
        r = toku_env_open(env, ".", DB_CREATE | DB_PRIVATE | DB_INIT_MPOOL, 0);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3692
        if (r != 0) {
Yoni Fogel's avatar
Yoni Fogel committed
3693
            env_unref(env);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3694 3695
            return r;
        }
Rich Prohaska's avatar
Rich Prohaska committed
3696
        assert(env_opened(env));
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
3697
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3698
    
3699
    DB *MALLOC(result);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3700
    if (result == 0) {
Rich Prohaska's avatar
Rich Prohaska committed
3701
        env_unref(env);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3702
        return ENOMEM;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
3703
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3704 3705
    memset(result, 0, sizeof *result);
    result->dbenv = env;
Yoni Fogel's avatar
Yoni Fogel committed
3706 3707 3708 3709 3710
#define SDB(name) result->name = locked_db_ ## name
    SDB(key_range64);
    SDB(close);
    SDB(cursor);
    SDB(del);
Yoni Fogel's avatar
Yoni Fogel committed
3711
    SDB(delboth);
Yoni Fogel's avatar
Yoni Fogel committed
3712 3713 3714 3715 3716 3717 3718 3719
    SDB(get);
    //    SDB(key_range);
    SDB(open);
    SDB(put);
    SDB(remove);
    SDB(rename);
    SDB(set_bt_compare);
    SDB(set_dup_compare);
3720
    SDB(set_descriptor);
Yoni Fogel's avatar
Yoni Fogel committed
3721 3722 3723 3724
    SDB(set_errfile);
    SDB(set_pagesize);
    SDB(set_flags);
    SDB(get_flags);
3725
    SDB(stat64);
Yoni Fogel's avatar
Yoni Fogel committed
3726 3727
    SDB(fd);
    SDB(pre_acquire_read_lock);
Yoni Fogel's avatar
Yoni Fogel committed
3728
    SDB(pre_acquire_table_lock);
3729
    SDB(truncate);
3730
    SDB(row_size_supported);
Yoni Fogel's avatar
Yoni Fogel committed
3731 3732 3733
#undef SDB
    result->dbt_pos_infty = toku_db_dbt_pos_infty;
    result->dbt_neg_infty = toku_db_dbt_neg_infty;
3734
    MALLOC(result->i);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3735 3736
    if (result->i == 0) {
        toku_free(result);
Rich Prohaska's avatar
Rich Prohaska committed
3737
        env_unref(env);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3738 3739 3740
        return ENOMEM;
    }
    memset(result->i, 0, sizeof *result->i);
3741
    result->i->db = result;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3742 3743 3744 3745 3746
    result->i->freed = 0;
    result->i->full_fname = 0;
    result->i->open_flags = 0;
    result->i->open_mode = 0;
    result->i->brt = 0;
3747
    r = toku_brt_create(&result->i->brt);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3748 3749 3750
    if (r != 0) {
        toku_free(result->i);
        toku_free(result);
Rich Prohaska's avatar
Rich Prohaska committed
3751
        env_unref(env);
Yoni Fogel's avatar
Yoni Fogel committed
3752
        return r;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3753
    }
3754 3755 3756 3757
    r = toku_brt_set_bt_compare(result->i->brt, env->i->bt_compare);
    assert(r==0);
    r = toku_brt_set_dup_compare(result->i->brt, env->i->dup_compare);
    assert(r==0);
3758
    ydb_add_ref();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3759 3760
    *db = result;
    return 0;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
3761
}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
3762

3763
int DB_CREATE_FUN (DB ** db, DB_ENV * env, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3764
    toku_ydb_lock(); int r = toku_db_create(db, env, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
3765 3766 3767 3768
}

/* need db_strerror_r for multiple threads */

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3769 3770 3771 3772 3773 3774 3775 3776
char *db_strerror(int error) {
    char *errorstr;
    if (error >= 0) {
        errorstr = strerror(error);
        if (errorstr)
            return errorstr;
    }
    
3777 3778 3779
    if (error==DB_BADFORMAT) {
	return "Database Bad Format (probably a corrupted database)";
    }
3780 3781 3782
    if (error==DB_NOTFOUND) {
	return "Not found";
    }
3783

Rich Prohaska's avatar
Rich Prohaska committed
3784
    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
3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796
    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;
3797 3798 3799 3800 3801
#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
3802
    return DB_VERSION_STRING;
3803
#endif
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
3804
}
3805 3806 3807 3808
 
int db_env_set_func_fsync (int (*fsync_function)(int)) {
    return toku_set_func_fsync(fsync_function);
}
Yoni Fogel's avatar
Yoni Fogel committed
3809

3810
int db_env_set_func_pwrite (ssize_t (*pwrite_function)(int, const void *, size_t, toku_off_t)) {
3811 3812 3813 3814 3815 3816
    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);
}

3817 3818 3819 3820 3821 3822
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);
}
3823
int db_env_set_func_free (void (*f)(void*)) {
3824 3825
    return toku_set_func_free(f);
}
3826 3827 3828 3829 3830 3831
// 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);
}
3832 3833 3834 3835

// For test purposes only.
// With this interface, all checkpoint users get the same callback and the same extra.
void db_env_set_checkpoint_callback (void (*callback_f)(void*), void* extra) {
3836
    toku_checkpoint_safe_client_lock();
3837 3838
    checkpoint_callback_f = callback_f;
    checkpoint_callback_extra = extra;
3839
    toku_checkpoint_safe_client_unlock();
3840
    //printf("set callback = %p, extra = %p\n", callback_f, extra);
3841
}