ydb.c 137 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 347

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

Yoni Fogel's avatar
Yoni Fogel committed
358
    if (!home) home = ".";
Yoni Fogel's avatar
Yoni Fogel committed
359

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

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

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

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

436
    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
437
    if (r!=0) goto died2;
438

439
    if (env->i->logger) toku_logger_set_cachetable(env->i->logger, env->i->cachetable);
440

Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
441 442
    return 0;
}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
443

Rich Prohaska's avatar
Rich Prohaska committed
444
static int toku_env_close(DB_ENV * env, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
445
    int is_panicked = toku_env_is_panicked(env);
446 447 448 449
    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
450
    int r0=0,r1=0;
451
    if (env->i->cachetable) {
452 453 454
	toku_ydb_unlock();  // ydb lock must not be held when shutting down minicron
	toku_cachetable_minicron_shutdown(env->i->cachetable);
	toku_ydb_lock();
455
        r0=toku_cachetable_close(&env->i->cachetable);
456 457 458 459 460
	if (r0) {
	    toku_ydb_do_error(env, r0, "Cannot close environment (cachetable close error)\n");
	}
    }
    if (env->i->logger) {
461
        r1=toku_logger_close(&env->i->logger);
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
	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
477 478 479 480 481 482 483 484
    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);
    }
485 486
    if (env->i->lg_dir)
        toku_free(env->i->lg_dir);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
487 488
    if (env->i->tmp_dir)
        toku_free(env->i->tmp_dir);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
489
    toku_free(env->i->dir);
Yoni Fogel's avatar
Yoni Fogel committed
490
    toku_ltm_close(env->i->ltm);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
491 492
    toku_free(env->i);
    toku_free(env);
493
    ydb_unref();
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
494 495 496
    if (flags!=0) return EINVAL;
    if (r0) return r0;
    if (r1) return r1;
497
    return is_panicked;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
498
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
499

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

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

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

Rich Prohaska's avatar
Rich Prohaska committed
522 523
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR >= 3

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

Rich Prohaska's avatar
Rich Prohaska committed
537
static int toku_env_set_data_dir(DB_ENV * env, const char *dir) {
538
    HANDLE_PANICKED_ENV(env);
Yoni Fogel's avatar
Yoni Fogel committed
539 540
    u_int32_t i;
    int r;
541 542
    char** temp;
    char* new_dir;
Yoni Fogel's avatar
Yoni Fogel committed
543
    
Rich Prohaska's avatar
Rich Prohaska committed
544
    if (env_opened(env) || !dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
545
	return toku_ydb_do_error(env, EINVAL, "You cannot set the data dir after opening the env\n");
546
    }
Yoni Fogel's avatar
Yoni Fogel committed
547 548 549 550 551 552 553 554 555 556 557
    
    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);
558 559 560 561
    new_dir = toku_strdup(dir);
    if (0) {
        died1:
        toku_free(new_dir);
Yoni Fogel's avatar
Yoni Fogel committed
562 563
        return r;
    }
564 565
    if (new_dir==NULL) {
	assert(errno == ENOMEM);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
566
	return toku_ydb_do_error(env, errno, "Out of memory\n");
567
    }
568 569 570 571
    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
572 573
    env->i->n_data_dirs++;
    return 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
574
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
575

Rich Prohaska's avatar
Rich Prohaska committed
576
static void toku_env_set_errcall(DB_ENV * env, toku_env_errcall_t errcall) {
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
577
    env->i->errcall = errcall;
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_errfile(DB_ENV*env, FILE*errfile) {
581 582 583
    env->i->errfile = errfile;
}

Rich Prohaska's avatar
Rich Prohaska committed
584
static void toku_env_set_errpfx(DB_ENV * env, const char *errpfx) {
585
    env->i->errpfx = errpfx;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
586
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
587

Rich Prohaska's avatar
Rich Prohaska committed
588
static int toku_env_set_flags(DB_ENV * env, u_int32_t flags, int onoff) {
589
    HANDLE_PANICKED_ENV(env);
Yoni Fogel's avatar
Yoni Fogel committed
590 591 592 593 594 595

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

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

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

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

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

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

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

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

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

660 661
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
662
    return toku_ltm_get_max_locks_per_db(dbenv->i->ltm, lk_maxp);
663 664 665
}

static int locked_env_set_lk_max_locks(DB_ENV *dbenv, u_int32_t max) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
666
    toku_ydb_lock(); int r = toku_env_set_lk_max_locks(dbenv, max); toku_ydb_unlock(); return r;
667 668 669
}

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
670
    toku_ydb_lock(); int r = toku_env_get_lk_max_locks(dbenv, lk_maxp); toku_ydb_unlock(); return r;
671 672
}

Yoni Fogel's avatar
Yoni Fogel committed
673
//void toku__env_set_noticecall (DB_ENV *env, void (*noticecall)(DB_ENV *, db_notices)) {
Bradley C. Kuszmaul's avatar
Fixup  
Bradley C. Kuszmaul committed
674 675
//    env->i->noticecall = noticecall;
//}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
676

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

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

697
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__))) {
698
    char *error_string = NULL;
699
    int r = toku_checkpoint(env->i->cachetable, env->i->logger, &error_string, NULL, NULL);
700 701 702 703 704 705 706 707 708 709 710
    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
711 712
}

Rich Prohaska's avatar
Rich Prohaska committed
713
static int toku_env_txn_stat(DB_ENV * env, DB_TXN_STAT ** statp, u_int32_t flags) {
714 715
    HANDLE_PANICKED_ENV(env);
    statp=statp;flags=flags;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
716
    return 1;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
717 718
}

719
#if 0
720
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR == 1
721
static void toku_default_errcall(const char *errpfx, char *msg) {
722 723
    fprintf(stderr, "YDB: %s: %s", errpfx, msg);
}
724
#else
725
static void toku_default_errcall(const DB_ENV *env, const char *errpfx, const char *msg) {
726
    env = env;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
727 728
    fprintf(stderr, "YDB: %s: %s", errpfx, msg);
}
729
#endif
730
#endif
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
731

Rich Prohaska's avatar
Rich Prohaska committed
732
static int locked_env_open(DB_ENV * env, const char *home, u_int32_t flags, int mode) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
733
    toku_ydb_lock(); int r = toku_env_open(env, home, flags, mode); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
734 735 736
}

static int locked_env_close(DB_ENV * env, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
737
    toku_ydb_lock(); int r = toku_env_close(env, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
738 739 740
}

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

static int locked_env_log_flush(DB_ENV * env, const DB_LSN * lsn) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
745
    toku_ydb_lock(); int r = toku_env_log_flush(env, lsn); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
746 747 748
}

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
749
    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
750 751 752
}

static int locked_env_set_data_dir(DB_ENV * env, const char *dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
753
    toku_ydb_lock(); int r = toku_env_set_data_dir(env, dir); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
754 755 756
}

static int locked_env_set_flags(DB_ENV * env, u_int32_t flags, int onoff) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
757
    toku_ydb_lock(); int r = toku_env_set_flags(env, flags, onoff); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
758 759 760
}

static int locked_env_set_lg_bsize(DB_ENV * env, u_int32_t bsize) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
761
    toku_ydb_lock(); int r = toku_env_set_lg_bsize(env, bsize); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
762 763 764
}

static int locked_env_set_lg_dir(DB_ENV * env, const char *dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
765
    toku_ydb_lock(); int r = toku_env_set_lg_dir(env, dir); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
766 767 768
}

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

772 773 774 775
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
776
static int locked_env_set_lk_detect(DB_ENV * env, u_int32_t detect) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
777
    toku_ydb_lock(); int r = toku_env_set_lk_detect(env, detect); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
778 779 780
}

static int locked_env_set_tmp_dir(DB_ENV * env, const char *tmp_dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
781
    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
782 783 784
}

static int locked_env_set_verbose(DB_ENV * env, u_int32_t which, int onoff) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
785
    toku_ydb_lock(); int r = toku_env_set_verbose(env, which, onoff); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
786 787 788
}

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

792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
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;
}

822 823 824 825 826 827 828 829 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
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
896 897
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
898 899 900 901 902 903
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
904
static int toku_env_create(DB_ENV ** envp, u_int32_t flags) {
Yoni Fogel's avatar
Yoni Fogel committed
905 906 907 908 909 910
    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
911
    memset(result, 0, sizeof *result);
912
    result->err = (void (*)(const DB_ENV * env, int error, const char *fmt, ...)) toku_locked_env_err;
913 914
    result->set_default_bt_compare = locked_env_set_default_bt_compare;
    result->set_default_dup_compare = locked_env_set_default_dup_compare;
915 916
    result->checkpointing_set_period = locked_env_checkpointing_set_period;
    result->checkpointing_get_period = locked_env_checkpointing_get_period;
917 918 919 920
    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
921 922
    result->open = locked_env_open;
    result->close = locked_env_close;
923
    result->txn_checkpoint = toku_env_txn_checkpoint;
Rich Prohaska's avatar
Rich Prohaska committed
924 925 926 927 928 929 930 931 932 933 934 935
    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;
936
    result->get_lg_max = locked_env_get_lg_max;
937
    result->set_lk_max_locks = locked_env_set_lk_max_locks;
Rich Prohaska's avatar
Rich Prohaska committed
938
    result->get_lk_max_locks = locked_env_get_lk_max_locks;
Rich Prohaska's avatar
Rich Prohaska committed
939
    result->set_cachesize = locked_env_set_cachesize;
Rich Prohaska's avatar
Rich Prohaska committed
940
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR >= 3
Rich Prohaska's avatar
Rich Prohaska committed
941
    result->get_cachesize = locked_env_get_cachesize;
Rich Prohaska's avatar
Rich Prohaska committed
942
#endif
Rich Prohaska's avatar
Rich Prohaska committed
943
    result->set_lk_detect = locked_env_set_lk_detect;
944
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR <= 4
Rich Prohaska's avatar
Rich Prohaska committed
945
    result->set_lk_max = locked_env_set_lk_max;
946
#endif
Rich Prohaska's avatar
Rich Prohaska committed
947 948 949
    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
950

951
    MALLOC(result->i);
Yoni Fogel's avatar
Yoni Fogel committed
952
    if (result->i == 0) { r = ENOMEM; goto cleanup; }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
953
    memset(result->i, 0, sizeof *result->i);
954 955
    result->i->bt_compare  = toku_default_compare_fun;
    result->i->dup_compare = toku_default_compare_fun;
956
    result->i->is_panicked=0;
957
    result->i->panic_string = 0;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
958
    result->i->ref_count = 1;
959 960
    result->i->errcall = 0;
    result->i->errpfx = 0;
961
    result->i->errfile = 0;
Yoni Fogel's avatar
Yoni Fogel committed
962 963

    r = toku_ltm_create(&result->i->ltm, __toku_env_default_max_locks,
Yoni Fogel's avatar
Yoni Fogel committed
964 965 966
                         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
967
    if (r!=0) { goto cleanup; }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
968

969
    {
Yoni Fogel's avatar
Yoni Fogel committed
970 971
	r = toku_logger_create(&result->i->logger);
	if (r!=0) { goto cleanup; }
972 973 974
	assert(result->i->logger);
    }

975
    ydb_add_ref();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
976
    *envp = result;
Yoni Fogel's avatar
Yoni Fogel committed
977 978 979 980 981 982 983 984 985 986 987 988 989 990
    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
991 992
}

993
int DB_ENV_CREATE_FUN (DB_ENV ** envp, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
994
    toku_ydb_lock(); int r = toku_env_create(envp, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
995 996
}

Yoni Fogel's avatar
Yoni Fogel committed
997
static int toku_txn_release_locks(DB_TXN* txn) {
Yoni Fogel's avatar
Yoni Fogel committed
998
    assert(txn);
999
    toku_lth* lth = db_txn_struct_i(txn)->lth;
Yoni Fogel's avatar
Yoni Fogel committed
1000

Yoni Fogel's avatar
Yoni Fogel committed
1001 1002
    int r = ENOSYS;
    int first_error = 0;
Yoni Fogel's avatar
Yoni Fogel committed
1003 1004 1005 1006
    if (lth) {
        toku_lth_start_scan(lth);
        toku_lock_tree* next = toku_lth_next(lth);
        while (next) {
1007
            r = toku_lt_unlock(next, toku_txn_get_txnid(db_txn_struct_i(txn)->tokutxn));
Yoni Fogel's avatar
Yoni Fogel committed
1008 1009 1010 1011 1012
            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
1013 1014 1015
            next = toku_lth_next(lth);
        }
        toku_lth_close(lth);
1016
        db_txn_struct_i(txn)->lth = NULL;
Yoni Fogel's avatar
Yoni Fogel committed
1017
    }
Yoni Fogel's avatar
Yoni Fogel committed
1018 1019
    r = first_error;

Yoni Fogel's avatar
Yoni Fogel committed
1020
    return r;
Yoni Fogel's avatar
Yoni Fogel committed
1021 1022
}

1023 1024
// 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.
1025
static void ydb_yield (voidfp f, void *UU(v)) {
1026
    toku_ydb_unlock(); 
1027
    if (f) f();
1028 1029 1030
    toku_ydb_lock();
}

Rich Prohaska's avatar
Rich Prohaska committed
1031
static int toku_txn_commit(DB_TXN * txn, u_int32_t flags) {
1032
    if (!txn) return EINVAL;
1033
    HANDLE_PANICKED_ENV(txn->mgrp);
Yoni Fogel's avatar
Yoni Fogel committed
1034
    //Recursively kill off children
Yoni Fogel's avatar
Yoni Fogel committed
1035
    int r_child_first = 0;
1036 1037
    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
1038 1039 1040
        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
1041 1042 1043
    }
    //Remove from parent
    if (txn->parent) {
1044 1045 1046
        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
1047 1048
        }
        else {
1049 1050
	    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
1051 1052
        }
    }
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1053
    //toku_ydb_notef("flags=%d\n", flags);
1054
    int nosync = (flags & DB_TXN_NOSYNC)!=0 || (db_txn_struct_i(txn)->flags&DB_TXN_NOSYNC);
1055
    flags &= ~DB_TXN_NOSYNC;
Yoni Fogel's avatar
Yoni Fogel committed
1056 1057 1058

    int r;
    if (r_child_first || flags!=0)
1059 1060
	// frees the tokutxn
	// Calls ydb_yield(NULL) occasionally
1061
        r = toku_logger_abort(db_txn_struct_i(txn)->tokutxn, ydb_yield, NULL);
Yoni Fogel's avatar
Yoni Fogel committed
1062
    else
1063 1064
	// frees the tokutxn
	// Calls ydb_yield(NULL) occasionally
1065
        r = toku_logger_commit(db_txn_struct_i(txn)->tokutxn, nosync, ydb_yield, NULL);
1066 1067 1068

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

1072
    // The txn is no good after the commit even if the commit fails, so free it up.
1073 1074 1075
#if !TOKUDB_NATIVE_H
    toku_free(db_txn_struct_i(txn));
#endif
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1076
    toku_free(txn);
Yoni Fogel's avatar
Yoni Fogel committed
1077 1078
    if (flags!=0) return EINVAL;
    return r ? r : (r2 ? r2 : r_child_first);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1079 1080
}

Rich Prohaska's avatar
Rich Prohaska committed
1081
static u_int32_t toku_txn_id(DB_TXN * txn) {
1082
    HANDLE_PANICKED_ENV(txn->mgrp);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1083
    toku_ydb_barf();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1084
    abort();
Rich Prohaska's avatar
Rich Prohaska committed
1085
    return -1;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1086 1087
}

1088
static int toku_txn_abort(DB_TXN * txn) {
1089
    HANDLE_PANICKED_ENV(txn->mgrp);
Yoni Fogel's avatar
Yoni Fogel committed
1090
    //Recursively kill off children
Yoni Fogel's avatar
Yoni Fogel committed
1091
    int r_child_first = 0;
1092 1093
    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
1094 1095 1096
        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
1097 1098 1099
    }
    //Remove from parent
    if (txn->parent) {
1100 1101 1102
        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
1103 1104
        }
        else {
1105 1106
            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
1107 1108
        }
    }
1109
    int r = toku_logger_abort(db_txn_struct_i(txn)->tokutxn, ydb_yield, NULL);
Yoni Fogel's avatar
Yoni Fogel committed
1110
    int r2 = toku_txn_release_locks(txn);
1111
    toku_logger_txn_close(db_txn_struct_i(txn)->tokutxn);
Yoni Fogel's avatar
Yoni Fogel committed
1112

1113 1114 1115
#if !TOKUDB_NATIVE_H
    toku_free(db_txn_struct_i(txn));
#endif
1116
    toku_free(txn);
Yoni Fogel's avatar
Yoni Fogel committed
1117
    return r ? r : (r2 ? r2 : r_child_first);
1118 1119
}

Rich Prohaska's avatar
Rich Prohaska committed
1120 1121 1122
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
1123
    toku_ydb_lock(); int r = toku_txn_begin(env, stxn, txn, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
1124 1125 1126
}

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

1130 1131
static int toku_txn_stat (DB_TXN *txn, struct txn_stat **txn_stat) {
    XMALLOC(*txn_stat);
1132
    return toku_logger_txn_rolltmp_raw_count(db_txn_struct_i(txn)->tokutxn, &(*txn_stat)->rolltmp_raw_count);
1133 1134 1135 1136 1137 1138
}

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
1139
static int locked_txn_commit(DB_TXN *txn, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1140
    toku_ydb_lock(); int r = toku_txn_commit(txn, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
1141 1142 1143
}

static int locked_txn_abort(DB_TXN *txn) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1144
    toku_ydb_lock(); int r = toku_txn_abort(txn); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
1145 1146 1147
}

static int toku_txn_begin(DB_ENV *env, DB_TXN * stxn, DB_TXN ** txn, u_int32_t flags) {
1148
    HANDLE_PANICKED_ENV(env);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1149 1150
    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");
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
    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");

1167
    DB_TXN *MALLOC(result);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1168 1169 1170
    if (result == 0)
        return ENOMEM;
    memset(result, 0, sizeof *result);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1171
    //toku_ydb_notef("parent=%p flags=0x%x\n", stxn, flags);
1172
    result->mgrp = env;
Rich Prohaska's avatar
Rich Prohaska committed
1173 1174 1175
    result->abort = locked_txn_abort;
    result->commit = locked_txn_commit;
    result->id = locked_txn_id;
Yoni Fogel's avatar
Yoni Fogel committed
1176
    result->parent = stxn;
1177
    result->txn_stat = locked_txn_stat;
1178 1179 1180
#if !TOKUDB_NATIVE_H
    MALLOC(db_txn_struct_i(result));
    if (!db_txn_struct_i(result)) {
Yoni Fogel's avatar
Yoni Fogel committed
1181 1182 1183
        toku_free(result);
        return ENOMEM;
    }
1184 1185 1186
#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
1187 1188

    int r;
Yoni Fogel's avatar
Yoni Fogel committed
1189
    if (env->i->open_flags & DB_INIT_LOCK && !stxn) {
1190
        r = toku_lth_create(&db_txn_struct_i(result)->lth,
Yoni Fogel's avatar
Yoni Fogel committed
1191 1192
                            toku_malloc, toku_free, toku_realloc);
        if (r!=0) {
1193 1194 1195
#if !TOKUDB_NATIVE_H
            toku_free(db_txn_struct_i(result));
#endif
Yoni Fogel's avatar
Yoni Fogel committed
1196 1197 1198
            toku_free(result);
            return r;
        }
Yoni Fogel's avatar
Yoni Fogel committed
1199 1200
    }
    
1201
    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
1202 1203
    if (r != 0)
        return r;
Yoni Fogel's avatar
Yoni Fogel committed
1204 1205
    //Add to the list of children for the parent.
    if (result->parent) {
1206 1207 1208 1209
        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
1210 1211
        }
        else {
1212 1213 1214 1215
            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
1216 1217
        }
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1218 1219 1220 1221
    *txn = result;
    return 0;
}

Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
1222
#if 0
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1223 1224
int txn_commit(DB_TXN * txn, u_int32_t flags) {
    fprintf(stderr, "%s:%d\n", __FILE__, __LINE__);
1225
    return toku_logger_log_commit(db_txn_struct_i(txn)->tokutxn);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1226
}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
1227
#endif
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1228

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1229
int log_compare(const DB_LSN * a, const DB_LSN * b) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1230
    toku_ydb_lock();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1231
    fprintf(stderr, "%s:%d log_compare(%p,%p)\n", __FILE__, __LINE__, a, b);
1232
    assert(0);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1233
    toku_ydb_unlock();
1234
    return 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1235 1236
}

1237 1238
static int
db_close_before_brt(DB *db, u_int32_t UU(flags)) {
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
    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;
1253
    if (db->i->db_id) { toku_db_id_remove_ref(&db->i->db_id); }
Yoni Fogel's avatar
Yoni Fogel committed
1254
    if (db->i->lt) {
1255 1256 1257 1258 1259
        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
1260
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1261
    // printf("%s:%d %d=__toku_db_close(%p)\n", __FILE__, __LINE__, r, db);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1262 1263
    // 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
1264
    env_unref(db->dbenv);
1265
    toku_free(db->i->fname);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
1266
    toku_free(db->i->full_fname);
1267 1268
    toku_sdbt_cleanup(&db->i->skey);
    toku_sdbt_cleanup(&db->i->sval);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
1269 1270
    toku_free(db->i);
    toku_free(db);
1271
    ydb_unref();
1272 1273 1274 1275
    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
1276 1277
}

1278 1279 1280 1281 1282 1283
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;
}


1284 1285 1286
//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
1287 1288
}

1289 1290
static int get_nonmain_cursor_flags(u_int32_t flags) {
    return flags & ~(DB_OPFLAGS_MASK);
1291 1292
}

1293
static inline BOOL toku_c_uninitialized(DBC* c) {
1294
    return toku_brt_cursor_uninitialized(dbc_struct_i(c)->c);
Yoni Fogel's avatar
Yoni Fogel committed
1295
}            
Yoni Fogel's avatar
Yoni Fogel committed
1296

1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
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;
1308 1309
    context->skey = dbc_struct_i(c)->skey;
    context->sval = dbc_struct_i(c)->sval;
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
}

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) {
1323
    TOKUTXN txn = dbc_struct_i(c)->txn ? db_txn_struct_i(dbc_struct_i(c)->txn)->tokutxn : NULL;
1324 1325 1326 1327 1328 1329 1330 1331 1332
    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
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
    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
1343 1344 1345 1346 1347 1348 1349
/*
    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.
*/
1350
static inline DB_TXN* toku_txn_ancestor(DB_TXN* txn) {
Yoni Fogel's avatar
Yoni Fogel committed
1351
    while (txn && txn->parent) txn = txn->parent;
Yoni Fogel's avatar
Yoni Fogel committed
1352

Yoni Fogel's avatar
Yoni Fogel committed
1353 1354 1355
    return txn;
}

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

Yoni Fogel's avatar
Yoni Fogel committed
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
/* 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
1369
    u_int32_t   lock_flags;         // The prelock flags.
Yoni Fogel's avatar
Yoni Fogel committed
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
    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;

1380 1381 1382 1383
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.
1384
    if (txn && db_txn_struct_i(txn)->flags&DB_READ_UNCOMMITTED) lock_flags |= DB_PRELOCKED;
1385
    return lock_flags;
Yoni Fogel's avatar
Yoni Fogel committed
1386 1387
}

1388 1389 1390 1391
//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
1392

1393 1394
    int r = toku_brt_get_flags(db->i->brt, &brtflags);
    assert(r==0);
1395
    BOOL rval = (BOOL)(!(brtflags&TOKU_DB_DUPSORT));
1396
    return rval;
Yoni Fogel's avatar
Yoni Fogel committed
1397
}
Yoni Fogel's avatar
Yoni Fogel committed
1398

1399 1400 1401 1402
static BOOL
c_db_is_nodup(DBC *c) {
    BOOL rval = db_is_nodup(c->dbp);
    return rval;
Yoni Fogel's avatar
Yoni Fogel committed
1403 1404
}

1405 1406 1407
static int
toku_c_get(DBC* c, DBT* key, DBT* val, u_int32_t flag) {
    //OW!! SCALDING!
Yoni Fogel's avatar
Yoni Fogel committed
1408

1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
    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
1421
        case (DB_FIRST):
1422 1423
            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
1424
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1425
        case (DB_LAST):
1426 1427
            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
1428
            break;
1429 1430 1431
        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
1432
            break;
1433 1434 1435
        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
1436
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1437
        case (DB_NEXT_NODUP):
1438 1439
            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
1440 1441
            break;
        case (DB_PREV):
1442 1443
            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
1444 1445
            break;
#ifdef DB_PREV_DUP
Yoni Fogel's avatar
Yoni Fogel committed
1446
        case (DB_PREV_DUP):
1447 1448
            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
1449 1450
            break;
#endif
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
        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
1483
        default:
Yoni Fogel's avatar
Yoni Fogel committed
1484
            r = EINVAL;
1485
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1486
    }
Yoni Fogel's avatar
Yoni Fogel committed
1487
    return r;
Yoni Fogel's avatar
Yoni Fogel committed
1488 1489
}

1490 1491
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
1492 1493
}

1494 1495 1496
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
1497

1498 1499
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
1500 1501
}

1502 1503 1504
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
1505

1506 1507 1508
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
1509

1510 1511
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
1512 1513
}

1514 1515 1516
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
1517

1518 1519 1520
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
1521

1522 1523
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
1524 1525
}

1526 1527 1528
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
1529

1530 1531 1532
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
1533

1534 1535 1536
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
1537

1538 1539 1540
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;
}
1541

1542 1543 1544
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
1545

1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
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
1556

1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
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
1574 1575
}

Yoni Fogel's avatar
Yoni Fogel committed
1576

1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587
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
1588 1589
}

1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609
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) {
1610
        TXNID txn_anc_id = toku_txn_get_txnid(db_txn_struct_i(txn_anc)->tokutxn);
1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621
        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
1622 1623
}

1624 1625
//This is the user level callback function given to ydb layer functions like
//toku_c_getf_first
Yoni Fogel's avatar
Yoni Fogel committed
1626

1627 1628 1629 1630 1631 1632 1633 1634
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;
1635

1636 1637 1638 1639
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
1640

1641 1642 1643 1644 1645 1646
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
1647

1648 1649 1650

static void
query_context_base_init(QUERY_CONTEXT_BASE context, DBC *c, u_int32_t flag, void *extra) {
1651 1652
    context->c       = dbc_struct_i(c)->c;
    context->txn     = dbc_struct_i(c)->txn;
1653 1654
    context->db      = c->dbp;
    context->f_extra = extra;
1655
    u_int32_t lock_flags = get_prelocked_flags(flag, dbc_struct_i(c)->txn);
Yoni Fogel's avatar
Yoni Fogel committed
1656 1657
    flag &= ~lock_flags;
    assert(flag==0);
1658
    context->do_locking = (BOOL)(context->db->i->lt!=NULL && !lock_flags);
1659
    context->r_user_callback = 0;
Yoni Fogel's avatar
Yoni Fogel committed
1660 1661
}

1662 1663 1664 1665 1666
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
1667

1668 1669 1670 1671 1672 1673
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;
1674 1675
}

1676 1677 1678 1679 1680
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) {
1681 1682
    HANDLE_PANICKED_DB(c->dbp);

1683 1684 1685 1686
    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;
1687
    u_int32_t lock_flags = get_prelocked_flags(flags, dbc_struct_i(c)->txn);
1688
    unchecked_flags &= ~lock_flags;
1689
    BOOL do_locking = (BOOL)(c->dbp->i->lt && !(lock_flags&DB_PRELOCKED_WRITE));
1690

1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701
    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.
1702 1703
            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);
1704 1705
        }
    }
1706 1707
    return r;
}
1708

1709 1710 1711 1712 1713
//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
1714

1715
    int r;
Yoni Fogel's avatar
Yoni Fogel committed
1716

1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728
    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
1729 1730 1731
    return r;
}

1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
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)
1742
    int r = toku_brt_cursor_first(dbc_struct_i(c)->c, c_getf_first_callback, &context, logger);
1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 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
    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)
1796
    int r = toku_brt_cursor_last(dbc_struct_i(c)->c, c_getf_last_callback, &context, logger);
1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 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
    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)
1853
        r = toku_brt_cursor_next(dbc_struct_i(c)->c, c_getf_next_callback, &context, logger);
1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 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
        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)
1907
        r = toku_brt_cursor_next_nodup(dbc_struct_i(c)->c, c_getf_next_callback, &context, logger);
1908 1909 1910 1911 1912 1913 1914 1915 1916
        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
1917 1918
    HANDLE_PANICKED_DB(c->dbp);
    if (toku_c_uninitialized(c)) return EINVAL;
1919 1920 1921 1922 1923

    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)
1924
    int r = toku_brt_cursor_next_dup(dbc_struct_i(c)->c, c_getf_next_dup_callback, &context, logger);
1925 1926 1927 1928 1929 1930 1931 1932 1933 1934
    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
1935 1936
    int r;

1937 1938 1939 1940
    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
1941

1942 1943 1944 1945 1946
    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
1947

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

1956 1957 1958 1959
    //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
1960
    }
1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978

    //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)
1979
        r = toku_brt_cursor_prev(dbc_struct_i(c)->c, c_getf_prev_callback, &context, logger);
1980
        if (r == TOKUDB_USER_CALLBACK_ERROR) r = context.base.r_user_callback;
Yoni Fogel's avatar
Yoni Fogel committed
1981 1982 1983 1984
    }
    return r;
}

1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020
//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
2021 2022
}

2023 2024
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
2025
    int r;
2026 2027 2028 2029 2030 2031 2032
    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)
2033
        r = toku_brt_cursor_prev_nodup(dbc_struct_i(c)->c, c_getf_prev_callback, &context, logger);
2034 2035 2036 2037
        if (r == TOKUDB_USER_CALLBACK_ERROR) r = context.base.r_user_callback;
    }
    return r;
}
Yoni Fogel's avatar
Yoni Fogel committed
2038

2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049
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)
2050
    int r = toku_brt_cursor_prev_dup(dbc_struct_i(c)->c, c_getf_prev_dup_callback, &context, logger);
2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 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
    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)
2102
    int r = toku_brt_cursor_current(dbc_struct_i(c)->c, DB_CURRENT, c_getf_current_callback, &context, logger);
2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136
    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)
2137
    int r = toku_brt_cursor_current(dbc_struct_i(c)->c, DB_CURRENT_BINDING, c_getf_current_callback, &context, logger);
2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151
    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)
2152
    int r = toku_brt_cursor_set(dbc_struct_i(c)->c, key, NULL, c_getf_set_callback, &context, logger);
2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 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
    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)
2209
    int r = toku_brt_cursor_set_range(dbc_struct_i(c)->c, key, c_getf_set_range_callback, &context, logger);
2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 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
    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)
2267
    int r = toku_brt_cursor_set(dbc_struct_i(c)->c, key, val, c_getf_get_both_callback, &context, logger);
2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318
    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)
2319
        r = toku_brt_cursor_get_both_range(dbc_struct_i(c)->c, key, val, c_getf_get_both_range_callback, &context, logger);
2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 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
        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)
2412
    r = toku_brt_cursor_heaviside(dbc_struct_i(c)->c, c_getf_heaviside_callback, &context, logger, &wrapper);
2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442
    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)
2443
        BOOL found = (BOOL)(found_keyvec != NULL);
2444
        DBC *tmp_cursor; //Temporary cursor to find 'next_key/next_val'
Yoni Fogel's avatar
Yoni Fogel committed
2445 2446
        DBT tmp_key;
        DBT tmp_val;
2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462
        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
2463 2464 2465
                }
            }
            else {
2466 2467 2468
                //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
2469 2470 2471
            }
        }
        else {
2472 2473 2474 2475 2476 2477 2478 2479
            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
2480 2481 2482
                }
            }
            else {
2483 2484 2485
                //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
2486 2487
            }
        }
2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 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
        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
2542 2543 2544
    return r ? r : r2;
}

2545
static int toku_c_close(DBC * c) {
2546 2547 2548 2549 2550 2551
    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
2552
    toku_free(c);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2553 2554 2555
    return r;
}

2556 2557 2558 2559 2560
static inline int keyeq(DBC *c, DBT *a, DBT *b) {
    DB *db = c->dbp;
    return db->i->brt->compare_fun(db, a, b) == 0;
}

2561 2562 2563 2564
// 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
2565 2566
    int r;
    DBC *count_cursor = 0;
2567
    DBT currentkey;
Rich Prohaska's avatar
Rich Prohaska committed
2568

2569
    init_dbt_realloc(&currentkey);
2570
    u_int32_t lock_flags = get_prelocked_flags(flags, dbc_struct_i(cursor)->txn);
2571
    flags &= ~lock_flags;
Rich Prohaska's avatar
Rich Prohaska committed
2572 2573 2574 2575
    if (flags != 0) {
        r = EINVAL; goto finish;
    }

2576
    r = toku_c_get_current_unconditional(cursor, lock_flags, &currentkey, NULL);
Rich Prohaska's avatar
Rich Prohaska committed
2577
    if (r != 0) goto finish;
2578 2579 2580 2581 2582 2583

    //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
2584
    
2585
    r = toku_db_cursor(cursor->dbp, dbc_struct_i(cursor)->txn, &count_cursor, 0, 0);
Rich Prohaska's avatar
Rich Prohaska committed
2586 2587 2588
    if (r != 0) goto finish;

    *count = 0;
2589
    r = toku_c_getf_set(count_cursor, lock_flags, &currentkey, ydb_getf_do_nothing, NULL);
Rich Prohaska's avatar
Rich Prohaska committed
2590 2591 2592 2593 2594 2595
    if (r != 0) {
        r = 0; goto finish; /* success, the current key must be deleted and there are no more */
    }

    for (;;) {
        *count += 1;
2596
        r = toku_c_getf_next_dup(count_cursor, lock_flags, ydb_getf_do_nothing, NULL);
Rich Prohaska's avatar
Rich Prohaska committed
2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607
        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
2608

2609 2610
///////////
//db_getf_XXX is equivalent to c_getf_XXX, without a persistent cursor
Yoni Fogel's avatar
 
Yoni Fogel committed
2611

2612 2613 2614 2615 2616 2617 2618 2619
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
2620
    }
2621
    return r;
Yoni Fogel's avatar
 
Yoni Fogel committed
2622 2623
}

2624 2625 2626 2627 2628 2629 2630 2631
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
2632
    }
2633
    return r;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2634
}
2635
////////////
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2636

2637 2638
static int
toku_db_del(DB *db, DB_TXN *txn, DBT *key, u_int32_t flags) {
2639
    HANDLE_PANICKED_DB(db);
2640 2641
    u_int32_t unchecked_flags = flags;
    //DB_DELETE_ANY means delete regardless of whether it exists in the db.
2642
    BOOL error_if_missing = (BOOL)(!(flags&DB_DELETE_ANY));
2643 2644 2645
    unchecked_flags &= ~DB_DELETE_ANY;
    u_int32_t lock_flags = get_prelocked_flags(flags, txn);
    unchecked_flags &= ~lock_flags;
2646
    BOOL do_locking = (BOOL)(db->i->lt && !(lock_flags&DB_PRELOCKED_WRITE));
2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660
    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);
2661
    }
2662 2663
    if (r==0) {
        //Do the actual deleting.
2664
        r = toku_brt_delete(db->i->brt, key, txn ? db_txn_struct_i(txn)->tokutxn : 0);
2665
    }
2666
    return r;
Rich Prohaska's avatar
Rich Prohaska committed
2667 2668 2669
}

static int locked_c_get(DBC * c, DBT * key, DBT * data, u_int32_t flag) {
2670 2671 2672 2673
    //{ 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
2674 2675 2676
}

static int locked_c_close(DBC * c) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2677
    toku_ydb_lock(); int r = toku_c_close(c); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
2678 2679 2680
}

static int locked_c_count(DBC *cursor, db_recno_t *count, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2681
    toku_ydb_lock(); int r = toku_c_count(cursor, count, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
2682 2683 2684
}

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

2688
static int toku_db_cursor(DB * db, DB_TXN * txn, DBC ** c, u_int32_t flags, int is_temporary_cursor) {
2689
    HANDLE_PANICKED_DB(db);
2690 2691
    if (flags != 0)
        return EINVAL;
2692
    DBC *MALLOC(result);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2693 2694 2695
    if (result == 0)
        return ENOMEM;
    memset(result, 0, sizeof *result);
Yoni Fogel's avatar
Yoni Fogel committed
2696 2697 2698 2699 2700
#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
2701 2702
    SCRS(c_getf_first);
    SCRS(c_getf_last);
Yoni Fogel's avatar
Yoni Fogel committed
2703
    SCRS(c_getf_next);
2704
    SCRS(c_getf_next_nodup);
Yoni Fogel's avatar
Yoni Fogel committed
2705
    SCRS(c_getf_next_dup);
2706 2707 2708 2709 2710 2711 2712 2713 2714 2715
    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
2716
#undef SCRS
2717 2718 2719

#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
2720
    assert(result->i);
2721
#endif
2722
    result->dbp = db;
2723 2724 2725
    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};
2726
    if (is_temporary_cursor) {
2727 2728
	dbc_struct_i(result)->skey = &db->i->skey;
	dbc_struct_i(result)->sval = &db->i->sval;
2729
    } else {
2730 2731
	dbc_struct_i(result)->skey = &dbc_struct_i(result)->skey_s;
	dbc_struct_i(result)->sval = &dbc_struct_i(result)->sval_s;
2732
    }
2733
    int r = toku_brt_cursor(db->i->brt, &dbc_struct_i(result)->c);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2734
    assert(r == 0);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2735 2736 2737 2738
    *c = result;
    return 0;
}

2739 2740
static int
toku_db_delboth(DB *db, DB_TXN *txn, DBT *key, DBT *val, u_int32_t flags) {
2741
    HANDLE_PANICKED_DB(db);
2742 2743
    u_int32_t unchecked_flags = flags;
    //DB_DELETE_ANY means delete regardless of whether it exists in the db.
2744
    BOOL error_if_missing = (BOOL)(!(flags&DB_DELETE_ANY));
2745
    unchecked_flags &= ~DB_DELETE_ANY;
2746
    u_int32_t lock_flags = get_prelocked_flags(flags, txn);
2747
    unchecked_flags &= ~lock_flags;
2748
    BOOL do_locking = (BOOL)(db->i->lt && !(lock_flags&DB_PRELOCKED_WRITE));
2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762
    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
2763
    }
2764 2765
    if (r==0) {
        //Do the actual deleting.
2766
        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
2767
    }
2768
    return r;
Yoni Fogel's avatar
Yoni Fogel committed
2769 2770
}

Rich Prohaska's avatar
Rich Prohaska committed
2771 2772 2773 2774
static inline int db_thread_need_flags(DBT *dbt) {
    return (dbt->flags & (DB_DBT_MALLOC+DB_DBT_REALLOC+DB_DBT_USERMEM)) == 0;
}

2775
static int toku_db_get (DB * db, DB_TXN * txn, DBT * key, DBT * data, u_int32_t flags) {
2776
    HANDLE_PANICKED_DB(db);
Yoni Fogel's avatar
Yoni Fogel committed
2777
    int r;
2778

Rich Prohaska's avatar
Rich Prohaska committed
2779
    if ((db->i->open_flags & DB_THREAD) && db_thread_need_flags(data))
2780 2781
        return EINVAL;

2782
    u_int32_t lock_flags = get_prelocked_flags(flags, txn);
Yoni Fogel's avatar
Yoni Fogel committed
2783
    flags &= ~lock_flags;
Yoni Fogel's avatar
Yoni Fogel committed
2784 2785 2786 2787
    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;
2788
    r = toku_db_cursor(db, txn, &dbc, 0, 1);
Yoni Fogel's avatar
Yoni Fogel committed
2789
    if (r!=0) return r;
Yoni Fogel's avatar
Yoni Fogel committed
2790 2791
    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
2792 2793
    int r2 = toku_c_close(dbc);
    return r ? r : r2;
2794 2795
}

Rich Prohaska's avatar
Rich Prohaska committed
2796
#if 0
2797
static int toku_db_key_range(DB * db, DB_TXN * txn, DBT * dbt, DB_KEY_RANGE * kr, u_int32_t flags) {
2798 2799
    HANDLE_PANICKED_DB(db);
    txn=txn; dbt=dbt; kr=kr; flags=flags;
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2800
    toku_ydb_barf();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2801
    abort();
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2802
}
Rich Prohaska's avatar
Rich Prohaska committed
2803
#endif
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2804

Yoni Fogel's avatar
Yoni Fogel committed
2805 2806 2807 2808
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
2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823
    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
2824 2825 2826 2827 2828 2829 2830
        }
    }
    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
2831
static char *construct_full_name(const char *dir, const char *fname) {
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2832
    if (toku_os_is_absolute_name(fname))
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2833
        dir = "";
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2834
    {
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2835 2836 2837 2838
        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
2839 2840 2841 2842
        // 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
2843 2844
        }
        return result;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2845 2846 2847
    }
}

2848
static int find_db_file(DB_ENV* dbenv, const char *fname, char** full_name_out) {
Yoni Fogel's avatar
Yoni Fogel committed
2849 2850
    u_int32_t i;
    int r;
2851
    toku_struct_stat statbuf;
Yoni Fogel's avatar
Yoni Fogel committed
2852 2853 2854 2855 2856 2857 2858 2859
    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;
2860
            r = toku_stat(full_name, &statbuf);
Yoni Fogel's avatar
Yoni Fogel committed
2861 2862 2863
            if (r == 0) goto finish;
            else {
                toku_free(full_name);
Rich Prohaska's avatar
Rich Prohaska committed
2864
                r = errno;
Yoni Fogel's avatar
Yoni Fogel committed
2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881
                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
2882
static int toku_db_lt_panic(DB* db, int r) {
2883
    assert(r!=0);
Yoni Fogel's avatar
Yoni Fogel committed
2884 2885
    assert(db && db->i && db->dbenv && db->dbenv->i);
    DB_ENV* env = db->dbenv;
2886 2887 2888 2889 2890
    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");

2891
    return toku_ydb_do_error(env, r, "%s", env->i->panic_string);
Yoni Fogel's avatar
Yoni Fogel committed
2892 2893
}

Yoni Fogel's avatar
Yoni Fogel committed
2894
static int toku_txn_add_lt(DB_TXN* txn, toku_lock_tree* lt) {
Yoni Fogel's avatar
Yoni Fogel committed
2895
    int r = ENOSYS;
Yoni Fogel's avatar
Yoni Fogel committed
2896
    assert(txn && lt);
2897
    toku_lth* lth = db_txn_struct_i(txn)->lth;
Yoni Fogel's avatar
Yoni Fogel committed
2898 2899 2900 2901 2902
    assert(lth);

    toku_lock_tree* find = toku_lth_find(lth, lt);
    if (find) {
        assert(find == lt);
Yoni Fogel's avatar
Yoni Fogel committed
2903 2904
        r = 0;
        goto cleanup;
Yoni Fogel's avatar
Yoni Fogel committed
2905
    }
Yoni Fogel's avatar
Yoni Fogel committed
2906 2907 2908 2909 2910 2911
    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
2912 2913 2914
    return r;
}

Yoni Fogel's avatar
Yoni Fogel committed
2915 2916 2917
static toku_dbt_cmp toku_db_get_compare_fun(DB* db) {
    return db->i->brt->compare_fun;
}
Yoni Fogel's avatar
Yoni Fogel committed
2918

Yoni Fogel's avatar
Yoni Fogel committed
2919 2920
static toku_dbt_cmp toku_db_get_dup_compare(DB* db) {
    return db->i->brt->dup_compare;
Yoni Fogel's avatar
Yoni Fogel committed
2921 2922
}

2923 2924 2925 2926 2927 2928
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);
}

2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974
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;
}

2975
static int toku_db_open(DB * db, DB_TXN * txn, const char *fname, const char *dbname, DBTYPE dbtype, u_int32_t flags, int mode) {
2976
    HANDLE_PANICKED_DB(db);
2977 2978 2979 2980 2981
    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
2982
    // Warning.  Should check arguments.  Should check return codes on malloc and open and so forth.
2983 2984
    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
2985

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2986
    int openflags = 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2987
    int r;
Yoni Fogel's avatar
Yoni Fogel committed
2988
    if (dbtype!=DB_BTREE && dbtype!=DB_UNKNOWN) return EINVAL;
2989 2990 2991
    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;
2992 2993
    //We support READ_UNCOMMITTED whether or not the flag is provided.
                                            flags&=~DB_READ_UNCOMMITTED;
2994
    if (dbtype != DB_UNKNOWN && dbtype != DB_BTREE) return EINVAL;
2995
    if (flags & ~DB_THREAD) return EINVAL; // unknown flags
2996 2997 2998

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

3000 3001 3002 3003 3004 3005 3006 3007
    /* 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;

3008
    if (db_opened(db))
3009
        return EINVAL;              /* It was already open. */
Yoni Fogel's avatar
Yoni Fogel committed
3010 3011 3012
    
    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
3013
    // printf("Full name = %s\n", db->i->full_fname);
3014 3015 3016 3017 3018
    assert(db->i->fname == 0);
    db->i->fname = toku_strdup(fname);
    if (db->i->fname == 0) { 
        r = ENOMEM; goto error_cleanup;
    }
3019
    if (is_db_rdonly)
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3020 3021 3022
        openflags |= O_RDONLY;
    else
        openflags |= O_RDWR;
3023
    
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3024
    {
3025 3026
        toku_struct_stat statbuf;
        if (toku_stat(db->i->full_fname, &statbuf) == 0) {
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3027
            /* If the database exists at the file level, and we specified no db_name, then complain here. */
3028 3029
            if (dbname == 0 && is_db_create) {
                if (is_db_excl) {
3030 3031 3032
                    r = EEXIST;
                    goto error_cleanup;
                }
3033
		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
3034 3035
            }
        } else {
3036
            if (!is_db_create) {
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3037 3038 3039 3040
                r = ENOENT;
                goto error_cleanup;
            }
        }
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3041
    }
3042
    if (is_db_create) openflags |= O_CREAT;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3043 3044 3045

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

Yoni Fogel's avatar
Yoni Fogel committed
3047

3048
    r = toku_brt_open(db->i->brt, db->i->full_fname, fname,
3049
		      is_db_create, is_db_excl,
3050
		      db->dbenv->i->cachetable,
3051
		      txn ? db_txn_struct_i(txn)->tokutxn : NULL_TXN,
3052
		      db);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3053 3054 3055
    if (r != 0)
        goto error_cleanup;

Yoni Fogel's avatar
Yoni Fogel committed
3056
    if (need_locktree) {
Yoni Fogel's avatar
Yoni Fogel committed
3057 3058 3059
        unsigned int brtflags;
        BOOL dups;
        toku_brt_get_flags(db->i->brt, &brtflags);
3060
        dups = (BOOL)((brtflags & TOKU_DB_DUPSORT || brtflags & TOKU_DB_DUP));
Yoni Fogel's avatar
Yoni Fogel committed
3061

3062 3063 3064 3065
        int db_fd;
        r = toku_db_fd(db, &db_fd);
        if (r!=0) goto error_cleanup;
        assert(db_fd>=0);
3066
        r = toku_db_id_create(&db->i->db_id, db_fd);
Yoni Fogel's avatar
Yoni Fogel committed
3067 3068 3069
        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
3070
    }
Yoni Fogel's avatar
Yoni Fogel committed
3071

Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3072
    return 0;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3073 3074
 
error_cleanup:
Yoni Fogel's avatar
Yoni Fogel committed
3075
    if (db->i->db_id) {
3076
        toku_db_id_remove_ref(&db->i->db_id);
Yoni Fogel's avatar
Yoni Fogel committed
3077 3078
        db->i->db_id = NULL;
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3079 3080 3081 3082
    if (db->i->full_fname) {
        toku_free(db->i->full_fname);
        db->i->full_fname = NULL;
    }
3083 3084 3085 3086
    if(db->i->fname) {
        toku_free(db->i->fname);
        db->i->fname = NULL;
    }
Yoni Fogel's avatar
Yoni Fogel committed
3087
    if (db->i->lt) {
Yoni Fogel's avatar
Yoni Fogel committed
3088
        toku_lt_remove_ref(db->i->lt);
Yoni Fogel's avatar
Yoni Fogel committed
3089 3090
        db->i->lt = NULL;
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3091
    return r;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3092
}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
3093

3094 3095 3096 3097 3098
//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) {
3099
    int r;
3100

3101
    BOOL dupsort = (BOOL)(!db_is_nodup(db));
3102
    //Check limits on size of key and val.
3103
    unsigned int nodesize;
3104
    r = toku_brt_get_nodesize(db->i->brt, &nodesize); assert(r == 0);
3105
    u_int32_t limit;
3106

3107 3108 3109
    if (dupsort) {
        limit = nodesize / (2*BRT_FANOUT-1);
        if (key->size + val->size >= limit)
Yoni Fogel's avatar
Yoni Fogel committed
3110
            r = toku_ydb_do_error(db->dbenv, EINVAL, "The largest (key + val) item allowed is %u bytes", limit-1);
3111
    } else {
3112 3113
        limit = nodesize / (3*BRT_FANOUT-1);
        if (key->size >= limit || val->size >= limit)
Yoni Fogel's avatar
Yoni Fogel committed
3114
            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
3115
    }
3116 3117 3118
    return r;
}

3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139
//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;
}

3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162
//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");
        }
3163
    }
3164 3165 3166
    else {
        //Other flags are not (yet) supported.
        r = EINVAL;
3167 3168 3169 3170
    }
    return r;
}

3171 3172
static int
toku_db_put(DB *db, DB_TXN *txn, DBT *key, DBT *val, u_int32_t flags) {
3173
    HANDLE_PANICKED_DB(db);
3174 3175
    int r;

3176 3177
    u_int32_t lock_flags = get_prelocked_flags(flags, txn);
    flags &= ~lock_flags;
3178
    BOOL do_locking = (BOOL)(db->i->lt && !(lock_flags&DB_PRELOCKED_WRITE));
3179

3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192
    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);
3193
    }
3194 3195
    if (r==0) {
        //Insert into the brt.
3196
        r = toku_brt_insert(db->i->brt, key, val, txn ? db_txn_struct_i(txn)->tokutxn : 0);
3197 3198
    }
    return r;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3199
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3200

3201 3202 3203 3204
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) {
3205
    BOOL need_close = TRUE;
3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217
    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;
3218
        need_close = FALSE;
3219 3220 3221 3222
        r = toku_db_remove(db, subdb_full_name, null_subdbname, flags);
    }

cleanup:
3223 3224 3225 3226
    if (need_close) {
        int r2 = toku_db_close(db, 0);
        if (r==0) r = r2;
    }
3227 3228 3229 3230 3231
    if (directory_name) toku_free(directory_name);
    return r;
}

//TODO: Maybe delete directory when last 'subdb' is deleted.
3232
static int toku_db_remove(DB * db, const char *fname, const char *dbname, u_int32_t flags) {
3233
    HANDLE_PANICKED_DB(db);
3234 3235
    if (dbname)
        return toku_db_remove_subdb(db, fname, dbname, flags);
Yoni Fogel's avatar
Yoni Fogel committed
3236 3237 3238 3239 3240 3241
    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
3242 3243

    //TODO: Verify DB* db not yet opened
Yoni Fogel's avatar
Yoni Fogel committed
3244
    //TODO: Verify db file not in use. (all dbs in the file must be unused)
3245
    r = toku_db_open(db, NULL, fname, dbname, DB_UNKNOWN, 0, S_IRWXU|S_IRWXG|S_IRWXO);
3246
    if (r==TOKUDB_DICTIONARY_TOO_OLD || r==TOKUDB_DICTIONARY_TOO_NEW || r==TOKUDB_DICTIONARY_NO_HEADER) {
Yoni Fogel's avatar
Yoni Fogel committed
3247 3248 3249
        need_close = FALSE;
        goto delete_db_file;
    }
Yoni Fogel's avatar
Yoni Fogel committed
3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262
    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
3263
delete_db_file:
3264 3265 3266 3267 3268 3269 3270
    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; }
3271

Yoni Fogel's avatar
Yoni Fogel committed
3272 3273 3274 3275 3276 3277
    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); }
3278
    if (db_id)      { toku_db_id_remove_ref(&db_id); }
Yoni Fogel's avatar
Yoni Fogel committed
3279
    return r ? r : r2;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3280
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3281

Yoni Fogel's avatar
Yoni Fogel committed
3282 3283 3284 3285 3286 3287 3288 3289
/* 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).
3290
   TODO: Check the other directories in the environment for the file
3291
TODO: Alert the BRT layer (for logging/recovery purposes)
Yoni Fogel's avatar
Yoni Fogel committed
3292
*/
3293
static int toku_db_rename(DB * db, const char *namea, const char *nameb, const char *namec, u_int32_t flags) {
3294
    HANDLE_PANICKED_DB(db);
3295
    if (flags!=0) return EINVAL;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
3296 3297
    char afull[PATH_MAX], cfull[PATH_MAX];
    int r;
3298 3299 3300 3301
    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
3302 3303 3304
    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
3305
    return rename(afull, cfull);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3306
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3307

3308
static int toku_db_set_bt_compare(DB * db, int (*bt_compare) (DB *, const DBT *, const DBT *)) {
3309
    HANDLE_PANICKED_DB(db);
3310
    int r = toku_brt_set_bt_compare(db->i->brt, bt_compare);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3311 3312 3313
    return r;
}

3314
static int toku_db_set_dup_compare(DB *db, int (*dup_compare)(DB *, const DBT *, const DBT *)) {
3315
    HANDLE_PANICKED_DB(db);
3316
    int r = toku_brt_set_dup_compare(db->i->brt, dup_compare);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3317 3318 3319
    return r;
}

3320
static int toku_db_set_descriptor(DB *db, u_int32_t version, const DBT* descriptor, toku_dbt_upgradef dbt_userformat_upgrade) {
3321 3322 3323 3324 3325
    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;
3326
    else r = toku_brt_set_descriptor(db->i->brt, version, descriptor, dbt_userformat_upgrade);
3327 3328 3329
    return r;
}

Rich Prohaska's avatar
Rich Prohaska committed
3330
static int toku_db_set_flags(DB *db, u_int32_t flags) {
3331
    HANDLE_PANICKED_DB(db);
3332

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

Yoni Fogel's avatar
Yoni Fogel committed
3336 3337 3338 3339
    u_int32_t tflags;
    int r = toku_brt_get_flags(db->i->brt, &tflags);
    if (r!=0) return r;
    
3340 3341 3342 3343
    if (flags & DB_DUP)
        tflags += TOKU_DB_DUP;
    if (flags & DB_DUPSORT)
        tflags += TOKU_DB_DUPSORT;
Yoni Fogel's avatar
Yoni Fogel committed
3344
    r = toku_brt_set_flags(db->i->brt, tflags);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3345 3346 3347
    return r;
}

3348
static int toku_db_get_flags(DB *db, u_int32_t *pflags) {
3349
    HANDLE_PANICKED_DB(db);
3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367
    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;
}

3368
static int toku_db_set_pagesize(DB *db, u_int32_t pagesize) {
3369
    HANDLE_PANICKED_DB(db);
3370
    int r = toku_brt_set_nodesize(db->i->brt, pagesize);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3371
    return r;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3372
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3373

3374
static int toku_db_stat64(DB * db, DB_TXN *txn, DB_BTREE_STAT64 *s) {
3375
    HANDLE_PANICKED_DB(db);
3376
    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);
3377 3378 3379 3380 3381 3382 3383
}
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
3384 3385
}

Yoni Fogel's avatar
Yoni Fogel committed
3386
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
3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400
    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;
}

3401
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
3402 3403
    HANDLE_PANICKED_DB(db);
    if (!db->i->lt || !txn) return EINVAL;
3404
    //READ_UNCOMMITTED transactions do not need read locks.
3405
    if (db_txn_struct_i(txn)->flags&DB_READ_UNCOMMITTED) return 0;
Yoni Fogel's avatar
Yoni Fogel committed
3406 3407 3408 3409

    DB_TXN* txn_anc = toku_txn_ancestor(txn);
    int r;
    if ((r=toku_txn_add_lt(txn_anc, db->i->lt))) return r;
3410
    TXNID id_anc = toku_txn_get_txnid(db_txn_struct_i(txn_anc)->tokutxn);
Yoni Fogel's avatar
Yoni Fogel committed
3411 3412 3413 3414 3415 3416 3417

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

3418
static int toku_db_pre_acquire_table_lock(DB *db, DB_TXN *txn) {
Yoni Fogel's avatar
Yoni Fogel committed
3419 3420 3421 3422 3423 3424
    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;
3425
    TXNID id_anc = toku_txn_get_txnid(db_txn_struct_i(txn_anc)->tokutxn);
Yoni Fogel's avatar
Yoni Fogel committed
3426 3427 3428 3429

    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);
3430
    if (r==0) {
3431
	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.
3432 3433
    }

Yoni Fogel's avatar
Yoni Fogel committed
3434 3435
    return r;
}
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3436

Yoni Fogel's avatar
Yoni Fogel committed
3437 3438 3439
//TODO: DB_AUTO_COMMIT.
//TODO: Nowait only conditionally?
//TODO: NOSYNC change to SYNC if DB_ENV has something in set_flags
3440
static inline int toku_db_construct_autotxn(DB* db, DB_TXN **txn, BOOL* changed,
Yoni Fogel's avatar
Yoni Fogel committed
3441 3442 3443 3444 3445 3446 3447
                                            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;
    }
3448
    BOOL nosync = (BOOL)(!force_auto_commit && !(env->i->open_flags & DB_AUTO_COMMIT));
Yoni Fogel's avatar
Yoni Fogel committed
3449 3450 3451 3452 3453 3454 3455
    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;
}

3456
static inline int toku_db_destruct_autotxn(DB_TXN *txn, int r, BOOL changed) {
Yoni Fogel's avatar
Yoni Fogel committed
3457 3458 3459 3460 3461 3462
    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
3463
static int locked_db_close(DB * db, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3464
    toku_ydb_lock(); int r = toku_db_close(db, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
3465 3466
}

3467
static inline int autotxn_db_cursor(DB *db, DB_TXN *txn, DBC **c, u_int32_t flags) {
Yoni Fogel's avatar
Yoni Fogel committed
3468
    if (!txn && (db->dbenv->i->open_flags & DB_INIT_TXN)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3469
        return toku_ydb_do_error(db->dbenv, EINVAL,
Yoni Fogel's avatar
Yoni Fogel committed
3470 3471
              "Cursors in a transaction environment must have transactions.\n");
    }
3472
    return toku_db_cursor(db, txn, c, flags, 0);
Yoni Fogel's avatar
Yoni Fogel committed
3473 3474
}

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

3479
static inline int autotxn_db_del(DB* db, DB_TXN* txn, DBT* key,
Yoni Fogel's avatar
Yoni Fogel committed
3480 3481 3482 3483 3484 3485 3486 3487
                                 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
3488
static int locked_db_del(DB * db, DB_TXN * txn, DBT * key, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3489
    toku_ydb_lock(); int r = autotxn_db_del(db, txn, key, flags); toku_ydb_unlock(); return r;
Yoni Fogel's avatar
Yoni Fogel committed
3490 3491
}

Yoni Fogel's avatar
Yoni Fogel committed
3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504
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;
}

3505
static inline int autotxn_db_get(DB* db, DB_TXN* txn, DBT* key, DBT* data,
Yoni Fogel's avatar
Yoni Fogel committed
3506 3507 3508 3509 3510 3511
                                 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
3512 3513 3514
}

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
3515
    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
3516 3517
}

3518
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
3519 3520 3521 3522 3523 3524
    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;
}

3525
static int locked_db_pre_acquire_table_lock(DB *db, DB_TXN *txn) {
Yoni Fogel's avatar
Yoni Fogel committed
3526 3527 3528 3529 3530 3531
    toku_ydb_lock();
    int r = toku_db_pre_acquire_table_lock(db, txn);
    toku_ydb_unlock();
    return r;
}

3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553
// 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;

3554
    r = toku_brt_truncate(db->i->brt);
3555 3556 3557 3558

    return r;
}

3559
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
3560
    BOOL changed; int r;
3561
    r = toku_db_construct_autotxn(db, &txn, &changed, (BOOL)((flags & DB_AUTO_COMMIT) != 0));
Yoni Fogel's avatar
Yoni Fogel committed
3562 3563 3564
    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
3565 3566 3567
}

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
3568
    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
3569 3570
}

3571
static inline int autotxn_db_put(DB* db, DB_TXN* txn, DBT* key, DBT* data,
Yoni Fogel's avatar
Yoni Fogel committed
3572
                                 u_int32_t flags) {
3573
    //{ 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
3574 3575 3576 3577 3578 3579 3580
    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
3581
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
3582
    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
3583 3584 3585
}

static int locked_db_remove(DB * db, const char *fname, const char *dbname, u_int32_t flags) {
3586 3587 3588 3589 3590 3591
    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
3592 3593 3594
}

static int locked_db_rename(DB * db, const char *namea, const char *nameb, const char *namec, u_int32_t flags) {
3595 3596 3597 3598 3599 3600
    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
3601 3602 3603
}

static int locked_db_set_bt_compare(DB * db, int (*bt_compare) (DB *, const DBT *, const DBT *)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3604
    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
3605 3606 3607
}

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

3611 3612 3613 3614 3615
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;
3616 3617
}

Rich Prohaska's avatar
Rich Prohaska committed
3618 3619 3620 3621 3622
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
3623
    toku_ydb_lock(); int r = toku_db_set_flags(db, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
3624 3625 3626
}

static int locked_db_get_flags(DB *db, u_int32_t *flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3627
    toku_ydb_lock(); int r = toku_db_get_flags(db, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
3628 3629 3630
}

static int locked_db_set_pagesize(DB *db, u_int32_t pagesize) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3631
    toku_ydb_lock(); int r = toku_db_set_pagesize(db, pagesize); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
3632 3633 3634
}

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

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3638

Yoni Fogel's avatar
Yoni Fogel committed
3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650
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
3651 3652
}

3653
static int locked_db_truncate(DB *db, DB_TXN *txn, u_int32_t *row_count, u_int32_t flags) {
3654
    toku_ydb_lock(); int r = toku_db_truncate(db, txn, row_count, flags); toku_ydb_unlock(); return r;
3655 3656
}

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

3660 3661
    if (flags) return EINVAL;

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3662 3663 3664
    /* if the env already exists then add a ref to it
       otherwise create one */
    if (env) {
Rich Prohaska's avatar
Rich Prohaska committed
3665
        if (!env_opened(env))
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3666
            return EINVAL;
Rich Prohaska's avatar
Rich Prohaska committed
3667
        env_add_ref(env);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3668
    } else {
Rich Prohaska's avatar
Rich Prohaska committed
3669
        r = toku_env_create(&env, 0);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3670 3671
        if (r != 0)
            return r;
Rich Prohaska's avatar
Rich Prohaska committed
3672
        r = toku_env_open(env, ".", DB_PRIVATE + DB_INIT_MPOOL, 0);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3673
        if (r != 0) {
Yoni Fogel's avatar
Yoni Fogel committed
3674
            env_unref(env);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3675 3676
            return r;
        }
Rich Prohaska's avatar
Rich Prohaska committed
3677
        assert(env_opened(env));
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
3678
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3679
    
3680
    DB *MALLOC(result);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3681
    if (result == 0) {
Rich Prohaska's avatar
Rich Prohaska committed
3682
        env_unref(env);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3683
        return ENOMEM;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
3684
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3685 3686
    memset(result, 0, sizeof *result);
    result->dbenv = env;
Yoni Fogel's avatar
Yoni Fogel committed
3687 3688 3689 3690 3691
#define SDB(name) result->name = locked_db_ ## name
    SDB(key_range64);
    SDB(close);
    SDB(cursor);
    SDB(del);
Yoni Fogel's avatar
Yoni Fogel committed
3692
    SDB(delboth);
Yoni Fogel's avatar
Yoni Fogel committed
3693 3694 3695 3696 3697 3698 3699 3700
    SDB(get);
    //    SDB(key_range);
    SDB(open);
    SDB(put);
    SDB(remove);
    SDB(rename);
    SDB(set_bt_compare);
    SDB(set_dup_compare);
3701
    SDB(set_descriptor);
Yoni Fogel's avatar
Yoni Fogel committed
3702 3703 3704 3705
    SDB(set_errfile);
    SDB(set_pagesize);
    SDB(set_flags);
    SDB(get_flags);
3706
    SDB(stat64);
Yoni Fogel's avatar
Yoni Fogel committed
3707 3708
    SDB(fd);
    SDB(pre_acquire_read_lock);
Yoni Fogel's avatar
Yoni Fogel committed
3709
    SDB(pre_acquire_table_lock);
3710
    SDB(truncate);
3711
    SDB(row_size_supported);
Yoni Fogel's avatar
Yoni Fogel committed
3712 3713 3714
#undef SDB
    result->dbt_pos_infty = toku_db_dbt_pos_infty;
    result->dbt_neg_infty = toku_db_dbt_neg_infty;
3715
    MALLOC(result->i);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3716 3717
    if (result->i == 0) {
        toku_free(result);
Rich Prohaska's avatar
Rich Prohaska committed
3718
        env_unref(env);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3719 3720 3721
        return ENOMEM;
    }
    memset(result->i, 0, sizeof *result->i);
3722
    result->i->db = result;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3723 3724 3725 3726 3727
    result->i->freed = 0;
    result->i->full_fname = 0;
    result->i->open_flags = 0;
    result->i->open_mode = 0;
    result->i->brt = 0;
3728
    r = toku_brt_create(&result->i->brt);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3729 3730 3731
    if (r != 0) {
        toku_free(result->i);
        toku_free(result);
Rich Prohaska's avatar
Rich Prohaska committed
3732
        env_unref(env);
Yoni Fogel's avatar
Yoni Fogel committed
3733
        return r;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3734
    }
3735 3736 3737 3738
    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);
3739
    ydb_add_ref();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3740 3741
    *db = result;
    return 0;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
3742
}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
3743

3744
int DB_CREATE_FUN (DB ** db, DB_ENV * env, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3745
    toku_ydb_lock(); int r = toku_db_create(db, env, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
3746 3747 3748 3749
}

/* need db_strerror_r for multiple threads */

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3750 3751 3752 3753 3754 3755 3756 3757
char *db_strerror(int error) {
    char *errorstr;
    if (error >= 0) {
        errorstr = strerror(error);
        if (errorstr)
            return errorstr;
    }
    
3758 3759 3760
    if (error==DB_BADFORMAT) {
	return "Database Bad Format (probably a corrupted database)";
    }
3761 3762 3763
    if (error==DB_NOTFOUND) {
	return "Not found";
    }
3764

Rich Prohaska's avatar
Rich Prohaska committed
3765
    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
3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777
    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;
3778 3779 3780 3781 3782
#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
3783
    return DB_VERSION_STRING;
3784
#endif
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
3785
}
3786 3787 3788 3789
 
int db_env_set_func_fsync (int (*fsync_function)(int)) {
    return toku_set_func_fsync(fsync_function);
}
Yoni Fogel's avatar
Yoni Fogel committed
3790

3791
int db_env_set_func_pwrite (ssize_t (*pwrite_function)(int, const void *, size_t, toku_off_t)) {
3792 3793 3794 3795 3796 3797
    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);
}

3798 3799 3800 3801 3802 3803
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);
}
3804
int db_env_set_func_free (void (*f)(void*)) {
3805 3806
    return toku_set_func_free(f);
}
3807 3808 3809 3810 3811 3812
// 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);
}