ydb.c 126 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 <ctype.h>
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
10
#include <errno.h>
11
#include <libgen.h>
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
12
#include <limits.h>
13
#include <pthread.h>
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
14
#include <stdarg.h>
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
15 16 17 18 19
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/fcntl.h>
#include <sys/stat.h>
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
20
#include <sys/types.h>
21
#include <sys/wait.h>
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
22
#include <unistd.h>
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
23

24
#include "toku_assert.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"
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
30

31 32 33 34 35 36 37 38 39 40
#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
41 42
/** 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
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60

/* 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);
61 62 63
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
64 65

static inline void env_add_ref(DB_ENV *env) {
66
    ++env->i->ref_count;
Rich Prohaska's avatar
Rich Prohaska committed
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
}

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);
static int toku_db_pget (DB *db, DB_TXN *txn, DBT *key, DBT *pkey, DBT *data, u_int32_t flags);
88
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
89 90 91

/* txn methods */

92
/* lightweight cursor methods. */
Yoni Fogel's avatar
Yoni Fogel committed
93 94 95 96
static int toku_c_getf_first(DBC *c, u_int32_t flag, void(*f)(DBT const *key, DBT const *data, void *extra), void *extra);

static int toku_c_getf_last(DBC *c, u_int32_t flag, void(*f)(DBT const *key, DBT const *data, void *extra), void *extra);

97
static int toku_c_getf_next(DBC *c, u_int32_t flag, void(*f)(DBT const *key, DBT const *data, void *extra), void *extra);
Yoni Fogel's avatar
Yoni Fogel committed
98 99 100

static int toku_c_getf_prev(DBC *c, u_int32_t flag, void(*f)(DBT const *key, DBT const *data, void *extra), void *extra);

Yoni Fogel's avatar
Yoni Fogel committed
101
static int toku_c_getf_next_dup(DBC *c, u_int32_t flag, void(*f)(DBT const *key, DBT const *data, void *extra), void *extra);
102

Yoni Fogel's avatar
Yoni Fogel committed
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 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
static int toku_c_getf_heavi(DBC *c, u_int32_t flags,
                             void(*f)(DBT const *key, DBT const *value, void *extra_f, int r_h),
                             void *extra_f,
                             int (*h)(const DBT *key, const DBT *value, void *extra_h),
                             void *extra_h, int direction); 
// 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
243 244 245
/* cursor methods */
static int toku_c_get(DBC * c, DBT * key, DBT * data, u_int32_t flag);
static int toku_c_get_noassociate(DBC * c, DBT * key, DBT * data, u_int32_t flag);
Yoni Fogel's avatar
Yoni Fogel committed
246
static int toku_db_delboth_noassociate(DB *db, DB_TXN *txn, DBT *key, DBT *val, u_int32_t flags);
Rich Prohaska's avatar
Rich Prohaska committed
247 248 249 250
static int toku_c_pget(DBC * c, DBT *key, DBT *pkey, 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
251

Rich Prohaska's avatar
Rich Prohaska committed
252
/* misc */
Yoni Fogel's avatar
Yoni Fogel committed
253
static char *construct_full_name(const char *dir, const char *fname);
254
static int do_associated_inserts (DB_TXN *txn, DBT *key, DBT *data, DB *secondary);
Yoni Fogel's avatar
Yoni Fogel committed
255
    
256 257
#if NEED_TEST

Rich Prohaska's avatar
Rich Prohaska committed
258
static int env_parse_config_line(DB_ENV* dbenv, char *command, char *value) {
Yoni Fogel's avatar
Yoni Fogel committed
259 260 261
    int r;
    
    if (!strcmp(command, "set_data_dir")) {
262
        r = toku_env_set_data_dir(dbenv, value);
Yoni Fogel's avatar
Yoni Fogel committed
263 264
    }
    else if (!strcmp(command, "set_tmp_dir")) {
265
        r = toku_env_set_tmp_dir(dbenv, value);
Yoni Fogel's avatar
Yoni Fogel committed
266 267
    }
    else if (!strcmp(command, "set_lg_dir")) {
268
        r = toku_env_set_lg_dir(dbenv, value);
Yoni Fogel's avatar
Yoni Fogel committed
269 270 271 272 273 274
    }
    else r = -1;
        
    return r;
}

Rich Prohaska's avatar
Rich Prohaska committed
275
static int env_read_config(DB_ENV *env) {
276
    HANDLE_PANICKED_ENV(env);
Yoni Fogel's avatar
Yoni Fogel committed
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
    const char* config_name = "DB_CONFIG";
    char* full_name = NULL;
    char* linebuffer = NULL;
    int buffersize;
    FILE* fp = NULL;
    int r = 0;
    int r2 = 0;
    char* command;
    char* value;
    
    full_name = construct_full_name(env->i->dir, config_name);
    if (full_name == 0) {
        r = ENOMEM;
        goto cleanup;
    }
    if ((fp = fopen(full_name, "r")) == NULL) {
        //Config file is optional.
        if (errno == ENOENT) {
            r = EXIT_SUCCESS;
            goto cleanup;
        }
        r = errno;
        goto cleanup;
    }
    //Read each line, applying configuration parameters.
    //After ignoring leading white space, skip any blank lines
    //or comments (starts with #)
    //Command contains no white space.  Value may contain whitespace.
    int linenumber;
    int ch = '\0';
    BOOL eof = FALSE;
    char* temp;
    char* end;
310
    int index;
Yoni Fogel's avatar
Yoni Fogel committed
311 312 313 314 315 316 317
    
    buffersize = 1<<10; //1KB
    linebuffer = toku_malloc(buffersize);
    if (!linebuffer) {
        r = ENOMEM;
        goto cleanup;
    }
318
    for (linenumber = 1; !eof; linenumber++) {
Yoni Fogel's avatar
Yoni Fogel committed
319
        /* Read a single line. */
320
        for (index = 0; TRUE; index++) {
Yoni Fogel's avatar
Yoni Fogel committed
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
            if ((ch = getc(fp)) == EOF) {
                eof = TRUE;
                if (ferror(fp)) {
                    /* Throw away current line and print warning. */
                    r = errno;
                    goto readerror;
                }
                break;
            }
            if (ch == '\n') break;
            if (index + 1 >= buffersize) {
                //Double the buffer.
                buffersize *= 2;
                linebuffer = toku_realloc(linebuffer, buffersize);
                if (!linebuffer) {
                    r = ENOMEM;
                    goto cleanup;
                }
            }
340
            linebuffer[index] = ch;
Yoni Fogel's avatar
Yoni Fogel committed
341 342 343 344 345 346 347 348 349 350 351 352 353 354
        }
        linebuffer[index] = '\0';
        end = &linebuffer[index];

        /* Separate the line into command/value */
        command = linebuffer;
        //Strip leading spaces.
        while (isspace(*command) && command < end) command++;
        //Find end of command.
        temp = command;
        while (!isspace(*temp) && temp < end) temp++;
        *temp++ = '\0'; //Null terminate command.
        value = temp;
        //Strip leading spaces.
355
        while (isspace(*value) && value < end) value++;
Yoni Fogel's avatar
Yoni Fogel committed
356 357 358 359 360 361 362 363 364
        if (value < end) {
            //Strip trailing spaces.
            temp = end;
            while (isspace(*(temp-1))) temp--;
            //Null terminate value.
            *temp = '\0';
        }
        //Parse the line.
        if (strlen(command) == 0 || command[0] == '#') continue; //Ignore Comments.
Rich Prohaska's avatar
Rich Prohaska committed
365
        r = env_parse_config_line(env, command, value < end ? value : "");
Yoni Fogel's avatar
Yoni Fogel committed
366 367 368 369
        if (r != 0) goto parseerror;
    }
    if (0) {
readerror:
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
370
        toku_ydb_do_error(env, r, "Error reading from DB_CONFIG:%d.\n", linenumber);
Yoni Fogel's avatar
Yoni Fogel committed
371 372 373
    }
    if (0) {
parseerror:
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
374
        toku_ydb_do_error(env, r, "Error parsing DB_CONFIG:%d.\n", linenumber);
Yoni Fogel's avatar
Yoni Fogel committed
375 376 377 378 379 380 381 382
    }
cleanup:
    if (full_name) toku_free(full_name);
    if (linebuffer) toku_free(linebuffer);
    if (fp) r2 = fclose(fp);
    return r ? r : r2;
}

383 384
#endif

385 386 387 388 389 390 391 392 393
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 {
	logdir = strdup(env->i->dir);
    }
    
394
#if 0
395 396 397 398 399
    // want to do recovery in its own process
    pid_t pid;
    if ((pid=fork())==0) {
	int r=tokudb_recover(datadir, logdir);
	assert(r==0);
400
	toku_free(logdir); // the child must also free.
401 402 403 404 405
	exit(0);
    }
    int status;
    waitpid(pid, &status, 0);
    if (!WIFEXITED(status) || WEXITSTATUS(status)!=0)  {
406
	toku_free(logdir);
407 408 409 410
	return toku_ydb_do_error(env, -1, "Recovery failed\n");
    }
    toku_free(logdir);
    return 0;
411 412 413 414 415
#else
    int r = tokudb_recover(datadir, logdir);
    toku_free(logdir);
    return r;
#endif
416 417
}

Rich Prohaska's avatar
Rich Prohaska committed
418
static int toku_env_open(DB_ENV * env, const char *home, u_int32_t flags, int mode) {
419
    HANDLE_PANICKED_ENV(env);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
420
    int r;
421
    u_int32_t unused_flags=flags;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
422

Rich Prohaska's avatar
Rich Prohaska committed
423
    if (env_opened(env)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
424
	return toku_ydb_do_error(env, EINVAL, "The environment is already open\n");
425
    }
Yoni Fogel's avatar
Yoni Fogel committed
426

427
    if ((flags & DB_USE_ENVIRON) && (flags & DB_USE_ENVIRON_ROOT)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
428
	return toku_ydb_do_error(env, EINVAL, "DB_USE_ENVIRON and DB_USE_ENVIRON_ROOT are incompatible flags\n");
429
    }
Yoni Fogel's avatar
Yoni Fogel committed
430 431

    if (home) {
432
        if ((flags & DB_USE_ENVIRON) || (flags & DB_USE_ENVIRON_ROOT)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
433
	    return toku_ydb_do_error(env, EINVAL, "DB_USE_ENVIRON and DB_USE_ENVIRON_ROOT are incompatible with specifying a home\n");
434
	}
Yoni Fogel's avatar
Yoni Fogel committed
435 436
    }
    else if ((flags & DB_USE_ENVIRON) ||
Yoni Fogel's avatar
Yoni Fogel committed
437 438
             ((flags & DB_USE_ENVIRON_ROOT) && geteuid() == 0)) home = getenv("DB_HOME");

439 440
    unused_flags &= ~DB_USE_ENVIRON & ~DB_USE_ENVIRON_ROOT; 

Yoni Fogel's avatar
Yoni Fogel committed
441
    if (!home) home = ".";
Yoni Fogel's avatar
Yoni Fogel committed
442

Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
443
	// Verify that the home exists.
Yoni Fogel's avatar
Yoni Fogel committed
444
	{
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
445 446
	struct stat buf;
	r = stat(home, &buf);
447
	if (r!=0) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
448
	    return toku_ydb_do_error(env, errno, "Error from stat(\"%s\",...)\n", home);
449
	}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
450 451
    }

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
452
    if (!(flags & DB_PRIVATE)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
453
	return toku_ydb_do_error(env, EINVAL, "TokuDB requires DB_PRIVATE when opening an env\n");
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
454
    }
455
    unused_flags &= ~DB_PRIVATE;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
456 457 458

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

477 478 479 480 481 482 483
    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
484
    if (flags & (DB_INIT_TXN | DB_INIT_LOG)) {
485 486
        char* full_dir = NULL;
        if (env->i->lg_dir) full_dir = construct_full_name(env->i->dir, env->i->lg_dir);
487
	assert(env->i->logger);
488
        toku_logger_write_log_files(env->i->logger, (flags & DB_INIT_LOG) != 0);
489 490 491
        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
492
	    toku_ydb_do_error(env, r, "Could not open logger\n");
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
493
	died2:
494
	    toku_logger_close(&env->i->logger);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
495 496
	    goto died1;
	}
497 498 499
    } 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
500 501
    }

502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
    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) {
	static char string[100];
	snprintf(string, 100, "Extra flags not understood by tokudb: %d\n", unused_flags);
	return toku_ydb_do_error(env, EINVAL, string);
    }

519
    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
520
    if (r!=0) goto died2;
521

522
    if (env->i->logger) toku_logger_set_cachetable(env->i->logger, env->i->cachetable);
523

Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
524 525
    return 0;
}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
526

Rich Prohaska's avatar
Rich Prohaska committed
527
static int toku_env_close(DB_ENV * env, u_int32_t flags) {
528
    // Even if the env is panicedk, try to close as much as we can.
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
529
    int is_panicked = toku_env_is_panicked(env);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
530
    int r0=0,r1=0;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
531
    if (env->i->cachetable)
532
        r0=toku_cachetable_close(&env->i->cachetable);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
533
    if (env->i->logger)
534
        r1=toku_logger_close(&env->i->logger);
Yoni Fogel's avatar
Yoni Fogel committed
535 536 537 538 539 540 541 542
    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);
    }
543 544
    if (env->i->lg_dir)
        toku_free(env->i->lg_dir);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
545 546
    if (env->i->tmp_dir)
        toku_free(env->i->tmp_dir);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
547
    toku_free(env->i->dir);
Yoni Fogel's avatar
Yoni Fogel committed
548
    toku_ltm_close(env->i->ltm);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
549 550
    toku_free(env->i);
    toku_free(env);
551
    ydb_unref();
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
552 553 554
    if (flags!=0) return EINVAL;
    if (r0) return r0;
    if (r1) return r1;
555
    if (is_panicked) return EINVAL;
556
    return 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
557
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
558

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

563
static int toku_env_log_flush(DB_ENV * env, const DB_LSN * lsn __attribute__((__unused__))) {
564
    HANDLE_PANICKED_ENV(env);
565 566
    // 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
567
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
568

Rich Prohaska's avatar
Rich Prohaska committed
569
static int toku_env_set_cachesize(DB_ENV * env, u_int32_t gbytes, u_int32_t bytes, int ncache) {
570
    HANDLE_PANICKED_ENV(env);
Rich Prohaska's avatar
Rich Prohaska committed
571 572
    if (ncache != 1)
        return EINVAL;
Rich Prohaska's avatar
Rich Prohaska committed
573 574 575 576 577
    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
578 579 580
    return 0;
}

Rich Prohaska's avatar
Rich Prohaska committed
581 582
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR >= 3

Rich Prohaska's avatar
Rich Prohaska committed
583
static int toku_env_get_cachesize(DB_ENV * env, u_int32_t *gbytes, u_int32_t *bytes, int *ncache) {
584
    HANDLE_PANICKED_ENV(env);
Rich Prohaska's avatar
Rich Prohaska committed
585 586 587 588 589 590
    *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
591
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
592
    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
593
}
Rich Prohaska's avatar
Rich Prohaska committed
594 595
#endif

Rich Prohaska's avatar
Rich Prohaska committed
596
static int toku_env_set_data_dir(DB_ENV * env, const char *dir) {
597
    HANDLE_PANICKED_ENV(env);
Yoni Fogel's avatar
Yoni Fogel committed
598 599
    u_int32_t i;
    int r;
600 601
    char** temp;
    char* new_dir;
Yoni Fogel's avatar
Yoni Fogel committed
602
    
Rich Prohaska's avatar
Rich Prohaska committed
603
    if (env_opened(env) || !dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
604
	return toku_ydb_do_error(env, EINVAL, "You cannot set the data dir after opening the env\n");
605
    }
Yoni Fogel's avatar
Yoni Fogel committed
606 607 608 609 610 611 612 613 614 615 616
    
    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);
617 618 619 620
    new_dir = toku_strdup(dir);
    if (0) {
        died1:
        toku_free(new_dir);
Yoni Fogel's avatar
Yoni Fogel committed
621 622
        return r;
    }
623 624
    if (new_dir==NULL) {
	assert(errno == ENOMEM);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
625
	return toku_ydb_do_error(env, errno, "Out of memory\n");
626
    }
627 628 629 630
    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
631 632
    env->i->n_data_dirs++;
    return 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
633
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
634

Rich Prohaska's avatar
Rich Prohaska committed
635
static void toku_env_set_errcall(DB_ENV * env, toku_env_errcall_t errcall) {
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
636
    env->i->errcall = errcall;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
637
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
638

Rich Prohaska's avatar
Rich Prohaska committed
639
static void toku_env_set_errfile(DB_ENV*env, FILE*errfile) {
640 641 642
    env->i->errfile = errfile;
}

Rich Prohaska's avatar
Rich Prohaska committed
643
static void toku_env_set_errpfx(DB_ENV * env, const char *errpfx) {
644
    env->i->errpfx = errpfx;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
645
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
646

Rich Prohaska's avatar
Rich Prohaska committed
647
static int toku_env_set_flags(DB_ENV * env, u_int32_t flags, int onoff) {
648
    HANDLE_PANICKED_ENV(env);
Yoni Fogel's avatar
Yoni Fogel committed
649 650 651 652 653 654

    u_int32_t change = 0;
    if (flags & DB_AUTO_COMMIT) {
        change |=  DB_AUTO_COMMIT;
        flags  &= ~DB_AUTO_COMMIT;
    }
655
    if (flags != 0 && onoff) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
656
	return toku_ydb_do_error(env, EINVAL, "TokuDB does not (yet) support any nonzero ENV flags other than DB_AUTO_COMMIT\n");
657
    }
Yoni Fogel's avatar
Yoni Fogel committed
658 659
    if   (onoff) env->i->open_flags |=  change;
    else         env->i->open_flags &= ~change;
Rich Prohaska's avatar
Rich Prohaska committed
660
    return 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
661
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
662

Rich Prohaska's avatar
Rich Prohaska committed
663
static int toku_env_set_lg_bsize(DB_ENV * env, u_int32_t bsize) {
664
    HANDLE_PANICKED_ENV(env);
665
    bsize=bsize;
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
666
    return toku_ydb_do_error(env, EINVAL, "TokuDB does not (yet) support ENV->set_lg_bsize\n");
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
667
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
668

Rich Prohaska's avatar
Rich Prohaska committed
669
static int toku_env_set_lg_dir(DB_ENV * env, const char *dir) {
670
    HANDLE_PANICKED_ENV(env);
Rich Prohaska's avatar
Rich Prohaska committed
671
    if (env_opened(env)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
672
	return toku_ydb_do_error(env, EINVAL, "Cannot set log dir after opening the env\n");
673
    }
674 675

    if (env->i->lg_dir) toku_free(env->i->lg_dir);
676 677
    if (dir) {
        env->i->lg_dir = toku_strdup(dir);
678
        if (!env->i->lg_dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
679
	    return toku_ydb_do_error(env, ENOMEM, "Out of memory\n");
680
	}
681
    }
682 683
    else env->i->lg_dir = NULL;
    return 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
684
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
685

Rich Prohaska's avatar
Rich Prohaska committed
686
static int toku_env_set_lg_max(DB_ENV * env, u_int32_t lg_max) {
687
    HANDLE_PANICKED_ENV(env);
688 689 690 691 692 693
    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
694
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
695

Rich Prohaska's avatar
Rich Prohaska committed
696
static int toku_env_set_lk_detect(DB_ENV * env, u_int32_t detect) {
697
    HANDLE_PANICKED_ENV(env);
698
    detect=detect;
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
699
    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
700
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
701

Yoni Fogel's avatar
Yoni Fogel committed
702
static int toku_env_set_lk_max_locks(DB_ENV *dbenv, u_int32_t max) {
Yoni Fogel's avatar
Yoni Fogel committed
703
    int r = ENOSYS;
Yoni Fogel's avatar
Yoni Fogel committed
704
    HANDLE_PANICKED_ENV(dbenv);
Yoni Fogel's avatar
Yoni Fogel committed
705
    if (env_opened(dbenv))         { return EINVAL; }
Yoni Fogel's avatar
Yoni Fogel committed
706
    r = toku_ltm_set_max_locks_per_db(dbenv->i->ltm, max);
Yoni Fogel's avatar
Yoni Fogel committed
707
    return r;
Yoni Fogel's avatar
Yoni Fogel committed
708 709
}

710
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR <= 4
Rich Prohaska's avatar
Rich Prohaska committed
711
static int toku_env_set_lk_max(DB_ENV * env, u_int32_t lk_max) {
Yoni Fogel's avatar
Yoni Fogel committed
712
    return toku_env_set_lk_max_locks(env, lk_max);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
713
}
Rich Prohaska's avatar
Rich Prohaska committed
714 715

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

720 721
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
722
    return toku_ltm_get_max_locks_per_db(dbenv->i->ltm, lk_maxp);
723 724 725
}

static int locked_env_set_lk_max_locks(DB_ENV *dbenv, u_int32_t max) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
726
    toku_ydb_lock(); int r = toku_env_set_lk_max_locks(dbenv, max); toku_ydb_unlock(); return r;
727 728 729
}

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
730
    toku_ydb_lock(); int r = toku_env_get_lk_max_locks(dbenv, lk_maxp); toku_ydb_unlock(); return r;
731 732
}

Yoni Fogel's avatar
Yoni Fogel committed
733
//void toku__env_set_noticecall (DB_ENV *env, void (*noticecall)(DB_ENV *, db_notices)) {
Bradley C. Kuszmaul's avatar
Fixup  
Bradley C. Kuszmaul committed
734 735
//    env->i->noticecall = noticecall;
//}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
736

Rich Prohaska's avatar
Rich Prohaska committed
737
static int toku_env_set_tmp_dir(DB_ENV * env, const char *tmp_dir) {
738
    HANDLE_PANICKED_ENV(env);
Rich Prohaska's avatar
Rich Prohaska committed
739
    if (env_opened(env)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
740
	return toku_ydb_do_error(env, EINVAL, "Cannot set the tmp dir after opening an env\n");
741 742
    }
    if (!tmp_dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
743
	return toku_ydb_do_error(env, EINVAL, "Tmp dir bust be non-null\n");
744
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
745 746
    if (env->i->tmp_dir)
        toku_free(env->i->tmp_dir);
Yoni Fogel's avatar
Yoni Fogel committed
747
    env->i->tmp_dir = toku_strdup(tmp_dir);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
748
    return env->i->tmp_dir ? 0 : ENOMEM;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
749
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
750

Rich Prohaska's avatar
Rich Prohaska committed
751
static int toku_env_set_verbose(DB_ENV * env, u_int32_t which, int onoff) {
752 753
    HANDLE_PANICKED_ENV(env);
    which=which; onoff=onoff;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
754
    return 1;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
755
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
756

757 758
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__))) {
    return toku_logger_log_checkpoint(env->i->logger); 
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
759 760
}

Rich Prohaska's avatar
Rich Prohaska committed
761
static int toku_env_txn_stat(DB_ENV * env, DB_TXN_STAT ** statp, u_int32_t flags) {
762 763
    HANDLE_PANICKED_ENV(env);
    statp=statp;flags=flags;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
764
    return 1;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
765 766
}

767
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR == 1
768
void toku_default_errcall(const char *errpfx, char *msg) {
769 770
    fprintf(stderr, "YDB: %s: %s", errpfx, msg);
}
771
#else
772
void toku_default_errcall(const DB_ENV *env, const char *errpfx, const char *msg) {
773
    env = env;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
774 775
    fprintf(stderr, "YDB: %s: %s", errpfx, msg);
}
776
#endif
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
777

Rich Prohaska's avatar
Rich Prohaska committed
778
static int locked_env_open(DB_ENV * env, const char *home, u_int32_t flags, int mode) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
779
    toku_ydb_lock(); int r = toku_env_open(env, home, flags, mode); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
780 781 782
}

static int locked_env_close(DB_ENV * env, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
783
    toku_ydb_lock(); int r = toku_env_close(env, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
784 785 786
}

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

static int locked_env_log_flush(DB_ENV * env, const DB_LSN * lsn) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
791
    toku_ydb_lock(); int r = toku_env_log_flush(env, lsn); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
792 793 794
}

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
795
    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
796 797 798
}

static int locked_env_set_data_dir(DB_ENV * env, const char *dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
799
    toku_ydb_lock(); int r = toku_env_set_data_dir(env, dir); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
800 801 802
}

static int locked_env_set_flags(DB_ENV * env, u_int32_t flags, int onoff) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
803
    toku_ydb_lock(); int r = toku_env_set_flags(env, flags, onoff); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
804 805 806
}

static int locked_env_set_lg_bsize(DB_ENV * env, u_int32_t bsize) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
807
    toku_ydb_lock(); int r = toku_env_set_lg_bsize(env, bsize); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
808 809 810
}

static int locked_env_set_lg_dir(DB_ENV * env, const char *dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
811
    toku_ydb_lock(); int r = toku_env_set_lg_dir(env, dir); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
812 813 814
}

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

818 819 820 821
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
822
static int locked_env_set_lk_detect(DB_ENV * env, u_int32_t detect) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
823
    toku_ydb_lock(); int r = toku_env_set_lk_detect(env, detect); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
824 825 826
}

static int locked_env_set_tmp_dir(DB_ENV * env, const char *tmp_dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
827
    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
828 829 830
}

static int locked_env_set_verbose(DB_ENV * env, u_int32_t which, int onoff) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
831
    toku_ydb_lock(); int r = toku_env_set_verbose(env, which, onoff); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
832 833 834
}

static int locked_env_txn_checkpoint(DB_ENV * env, u_int32_t kbyte, u_int32_t min, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
835
    toku_ydb_lock(); int r = toku_env_txn_checkpoint(env, kbyte, min, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
836 837 838
}

static int locked_env_txn_stat(DB_ENV * env, DB_TXN_STAT ** statp, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
839
    toku_ydb_lock(); int r = toku_env_txn_stat(env, statp, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
840 841 842 843
}

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
844 845 846 847 848 849
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
850
static int toku_env_create(DB_ENV ** envp, u_int32_t flags) {
Yoni Fogel's avatar
Yoni Fogel committed
851 852 853 854 855 856
    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
857
    memset(result, 0, sizeof *result);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
858
    result->err = toku_locked_env_err;
Rich Prohaska's avatar
Rich Prohaska committed
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
    result->open = locked_env_open;
    result->close = locked_env_close;
    result->txn_checkpoint = locked_env_txn_checkpoint;
    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;
874
    result->get_lg_max = locked_env_get_lg_max;
875
    result->set_lk_max_locks = locked_env_set_lk_max_locks;
Rich Prohaska's avatar
Rich Prohaska committed
876
    result->get_lk_max_locks = locked_env_get_lk_max_locks;
Rich Prohaska's avatar
Rich Prohaska committed
877
    result->set_cachesize = locked_env_set_cachesize;
Rich Prohaska's avatar
Rich Prohaska committed
878
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR >= 3
Rich Prohaska's avatar
Rich Prohaska committed
879
    result->get_cachesize = locked_env_get_cachesize;
Rich Prohaska's avatar
Rich Prohaska committed
880
#endif
Rich Prohaska's avatar
Rich Prohaska committed
881
    result->set_lk_detect = locked_env_set_lk_detect;
882
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR <= 4
Rich Prohaska's avatar
Rich Prohaska committed
883
    result->set_lk_max = locked_env_set_lk_max;
884
#endif
Rich Prohaska's avatar
Rich Prohaska committed
885 886 887
    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
888

889
    MALLOC(result->i);
Yoni Fogel's avatar
Yoni Fogel committed
890
    if (result->i == 0) { r = ENOMEM; goto cleanup; }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
891
    memset(result->i, 0, sizeof *result->i);
892
    result->i->is_panicked=0;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
893
    result->i->ref_count = 1;
894 895
    result->i->errcall = 0;
    result->i->errpfx = 0;
896
    result->i->errfile = 0;
Yoni Fogel's avatar
Yoni Fogel committed
897 898

    r = toku_ltm_create(&result->i->ltm, __toku_env_default_max_locks,
Yoni Fogel's avatar
Yoni Fogel committed
899 900 901
                         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
902
    if (r!=0) { goto cleanup; }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
903

904
    {
Yoni Fogel's avatar
Yoni Fogel committed
905 906
	r = toku_logger_create(&result->i->logger);
	if (r!=0) { goto cleanup; }
907 908 909
	assert(result->i->logger);
    }

910
    ydb_add_ref();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
911
    *envp = result;
Yoni Fogel's avatar
Yoni Fogel committed
912 913 914 915 916 917 918 919 920 921 922 923 924 925
    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
926 927
}

928
int DB_ENV_CREATE_FUN (DB_ENV ** envp, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
929
    toku_ydb_lock(); int r = toku_env_create(envp, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
930 931
}

Yoni Fogel's avatar
Yoni Fogel committed
932
static int toku_txn_release_locks(DB_TXN* txn) {
Yoni Fogel's avatar
Yoni Fogel committed
933 934 935
    assert(txn);
    toku_lth* lth = txn->i->lth;

Yoni Fogel's avatar
Yoni Fogel committed
936 937
    int r = ENOSYS;
    int first_error = 0;
Yoni Fogel's avatar
Yoni Fogel committed
938 939 940 941
    if (lth) {
        toku_lth_start_scan(lth);
        toku_lock_tree* next = toku_lth_next(lth);
        while (next) {
Yoni Fogel's avatar
Yoni Fogel committed
942 943 944 945 946 947
            r = toku_lt_unlock(next, toku_txn_get_txnid(txn->i->tokutxn));
            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
948 949 950 951 952
            next = toku_lth_next(lth);
        }
        toku_lth_close(lth);
        txn->i->lth = NULL;
    }
Yoni Fogel's avatar
Yoni Fogel committed
953 954
    r = first_error;

Yoni Fogel's avatar
Yoni Fogel committed
955
    return r;
Yoni Fogel's avatar
Yoni Fogel committed
956 957
}

Rich Prohaska's avatar
Rich Prohaska committed
958
static int toku_txn_commit(DB_TXN * txn, u_int32_t flags) {
959
    if (!txn) return EINVAL;
960
    HANDLE_PANICKED_ENV(txn->mgrp);
Yoni Fogel's avatar
Yoni Fogel committed
961
    //Recursively kill off children
Yoni Fogel's avatar
Yoni Fogel committed
962
    int r_child_first = 0;
Yoni Fogel's avatar
Yoni Fogel committed
963 964
    while (txn->i->child) {
        int r_child = toku_txn_commit(txn->i->child, flags);
Yoni Fogel's avatar
Yoni Fogel committed
965 966 967
        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
968 969 970 971 972 973 974 975 976 977 978 979
    }
    //Remove from parent
    if (txn->parent) {
        if (txn->parent->i->child==txn) txn->parent->i->child=txn->i->next;
        if (txn->parent->i->child==txn) {
            txn->parent->i->child=NULL;
        }
        else {
            txn->i->next->i->prev = txn->i->prev;
            txn->i->prev->i->next = txn->i->next;
        }
    }
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
980
    //toku_ydb_notef("flags=%d\n", flags);
981 982
    int nosync = (flags & DB_TXN_NOSYNC)!=0;
    flags &= ~DB_TXN_NOSYNC;
Yoni Fogel's avatar
Yoni Fogel committed
983

Yoni Fogel's avatar
Yoni Fogel committed
984
    int r2 = toku_txn_release_locks(txn);
Yoni Fogel's avatar
Yoni Fogel committed
985 986 987 988 989
    int r;
    if (r_child_first || flags!=0)
        r = toku_logger_abort(txn->i->tokutxn); // frees the tokutxn
    else
        r = toku_logger_commit(txn->i->tokutxn, nosync); // frees the tokutxn
990
    // the toxutxn is freed, and we must free the rest. */
Yoni Fogel's avatar
Yoni Fogel committed
991 992

    // The txn is no good after the commit even if the commit fails.
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
993 994 995
    if (txn->i)
        toku_free(txn->i);
    toku_free(txn);
Yoni Fogel's avatar
Yoni Fogel committed
996 997
    if (flags!=0) return EINVAL;
    return r ? r : (r2 ? r2 : r_child_first);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
998 999
}

Rich Prohaska's avatar
Rich Prohaska committed
1000
static u_int32_t toku_txn_id(DB_TXN * txn) {
1001
    HANDLE_PANICKED_ENV(txn->mgrp);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1002
    toku_ydb_barf();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1003
    abort();
Rich Prohaska's avatar
Rich Prohaska committed
1004
    return -1;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1005 1006
}

1007
static int toku_txn_abort(DB_TXN * txn) {
1008
    HANDLE_PANICKED_ENV(txn->mgrp);
Yoni Fogel's avatar
Yoni Fogel committed
1009
    //Recursively kill off children
Yoni Fogel's avatar
Yoni Fogel committed
1010
    int r_child_first = 0;
Yoni Fogel's avatar
Yoni Fogel committed
1011 1012
    while (txn->i->child) {
        int r_child = toku_txn_abort(txn->i->child);
Yoni Fogel's avatar
Yoni Fogel committed
1013 1014 1015
        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
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
    }
    //Remove from parent
    if (txn->parent) {
        if (txn->parent->i->child==txn) txn->parent->i->child=txn->i->next;
        if (txn->parent->i->child==txn) {
            txn->parent->i->child=NULL;
        }
        else {
            txn->i->next->i->prev = txn->i->prev;
            txn->i->prev->i->next = txn->i->next;
        }
    }
Yoni Fogel's avatar
Yoni Fogel committed
1028
    int r2 = toku_txn_release_locks(txn);
1029
    int r = toku_logger_abort(txn->i->tokutxn);
Yoni Fogel's avatar
Yoni Fogel committed
1030

1031 1032
    toku_free(txn->i);
    toku_free(txn);
Yoni Fogel's avatar
Yoni Fogel committed
1033
    return r ? r : (r2 ? r2 : r_child_first);
1034 1035
}

Rich Prohaska's avatar
Rich Prohaska committed
1036 1037 1038
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
1039
    toku_ydb_lock(); int r = toku_txn_begin(env, stxn, txn, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
1040 1041 1042
}

static u_int32_t locked_txn_id(DB_TXN *txn) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1043
    toku_ydb_lock(); u_int32_t r = toku_txn_id(txn); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
1044 1045 1046
}

static int locked_txn_commit(DB_TXN *txn, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1047
    toku_ydb_lock(); int r = toku_txn_commit(txn, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
1048 1049 1050
}

static int locked_txn_abort(DB_TXN *txn) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1051
    toku_ydb_lock(); int r = toku_txn_abort(txn); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
1052 1053 1054
}

static int toku_txn_begin(DB_ENV *env, DB_TXN * stxn, DB_TXN ** txn, u_int32_t flags) {
1055
    HANDLE_PANICKED_ENV(env);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1056 1057
    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");
1058
    flags=flags;
1059
    DB_TXN *MALLOC(result);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1060 1061 1062
    if (result == 0)
        return ENOMEM;
    memset(result, 0, sizeof *result);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1063
    //toku_ydb_notef("parent=%p flags=0x%x\n", stxn, flags);
1064
    result->mgrp = env;
Rich Prohaska's avatar
Rich Prohaska committed
1065 1066 1067
    result->abort = locked_txn_abort;
    result->commit = locked_txn_commit;
    result->id = locked_txn_id;
Yoni Fogel's avatar
Yoni Fogel committed
1068
    result->parent = stxn;
1069
    MALLOC(result->i);
Yoni Fogel's avatar
Yoni Fogel committed
1070 1071 1072 1073
    if (!result->i) {
        toku_free(result);
        return ENOMEM;
    }
1074
    memset(result->i, 0, sizeof *result->i);
Yoni Fogel's avatar
Yoni Fogel committed
1075 1076

    int r;
Yoni Fogel's avatar
Yoni Fogel committed
1077
    if (env->i->open_flags & DB_INIT_LOCK && !stxn) {
Yoni Fogel's avatar
Yoni Fogel committed
1078 1079 1080 1081 1082 1083 1084
        r = toku_lth_create(&result->i->lth,
                            toku_malloc, toku_free, toku_realloc);
        if (r!=0) {
            toku_free(result->i);
            toku_free(result);
            return r;
        }
Yoni Fogel's avatar
Yoni Fogel committed
1085 1086
    }
    
1087
    r = toku_logger_txn_begin(stxn ? stxn->i->tokutxn : 0, &result->i->tokutxn, env->i->logger);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1088 1089
    if (r != 0)
        return r;
Yoni Fogel's avatar
Yoni Fogel committed
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
    //Add to the list of children for the parent.
    if (result->parent) {
        if (!result->parent->i->child) {
            result->parent->i->child = result;
            result->i->next = result;
            result->i->prev = result;
        }
        else {
            result->i->prev = result->parent->i->child->i->prev;
            result->i->next = result->parent->i->child;
            result->parent->i->child->i->prev->i->next = result;
            result->parent->i->child->i->prev = result;
        }
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1104 1105 1106 1107
    *txn = result;
    return 0;
}

Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
1108
#if 0
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1109 1110
int txn_commit(DB_TXN * txn, u_int32_t flags) {
    fprintf(stderr, "%s:%d\n", __FILE__, __LINE__);
1111
    return toku_logger_log_commit(txn->i->tokutxn);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1112
}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
1113
#endif
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1114

1115
int log_compare(const DB_LSN * a, const DB_LSN * b) __attribute__((__noreturn__));
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1116
int log_compare(const DB_LSN * a, const DB_LSN * b) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1117
    toku_ydb_lock();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1118 1119
    fprintf(stderr, "%s:%d log_compare(%p,%p)\n", __FILE__, __LINE__, a, b);
    abort();
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1120
    toku_ydb_unlock();
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1121 1122
}

1123 1124
static int maybe_do_associate_create (DB_TXN*txn, DB*primary, DB*secondary) {
    DBC *dbc;
1125
    int r = toku_db_cursor(secondary, txn, &dbc, 0, 0);
1126 1127
    if (r!=0) return r;
    DBT key,data;
Rich Prohaska's avatar
Rich Prohaska committed
1128
    r = toku_c_get(dbc, &key, &data, DB_FIRST);
1129
    {
Rich Prohaska's avatar
Rich Prohaska committed
1130
	int r2=toku_c_close(dbc);
1131 1132 1133 1134 1135
	if (r!=DB_NOTFOUND) {
	    return r2;
	}
    }
    /* Now we know the secondary is empty. */
1136
    r = toku_db_cursor(primary, txn, &dbc, 0, 0);
1137
    if (r!=0) return r;
Rich Prohaska's avatar
Rich Prohaska committed
1138
    for (r = toku_c_get(dbc, &key, &data, DB_FIRST); r==0; r = toku_c_get(dbc, &key, &data, DB_NEXT)) {
1139 1140
	r = do_associated_inserts(txn, &key, &data, secondary);
	if (r!=0) {
Rich Prohaska's avatar
Rich Prohaska committed
1141
	    toku_c_close(dbc);
1142 1143 1144 1145 1146 1147
	    return r;
	}
    }
    return 0;
}

1148 1149 1150
static int toku_db_associate (DB *primary, DB_TXN *txn, DB *secondary,
			      int (*callback)(DB *secondary, const DBT *key, const DBT *data, DBT *result),
			      u_int32_t flags) {
1151 1152
    HANDLE_PANICKED_DB(primary);
    HANDLE_PANICKED_DB(secondary);
1153 1154
    unsigned int brtflags;
    
1155 1156
    if (secondary->i->primary) return EINVAL; // The secondary already has a primary
    if (primary->i->primary)   return EINVAL; // The primary already has a primary
1157 1158 1159 1160 1161

    toku_brt_get_flags(primary->i->brt, &brtflags);
    if (brtflags & TOKU_DB_DUPSORT) return EINVAL;  //The primary may not have duplicate keys.
    if (brtflags & TOKU_DB_DUP)     return EINVAL;  //The primary may not have duplicate keys.

1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
    if (!list_empty(&secondary->i->associated)) return EINVAL; // The secondary is in some list (or it is a primary)
    assert(secondary->i->associate_callback==0);      // Something's wrong if this isn't null we made it this far.
    secondary->i->associate_callback = callback;
#ifdef DB_IMMUTABLE_KEY
    secondary->i->associate_is_immutable = (DB_IMMUTABLE_KEY&flags)!=0;
    flags &= ~DB_IMMUTABLE_KEY;
#else
    secondary->i->associate_is_immutable = 0;
#endif
    if (flags!=0 && flags!=DB_CREATE) return EINVAL; // after removing DB_IMMUTABLE_KEY the flags better be 0 or DB_CREATE
1172 1173
    list_push(&primary->i->associated, &secondary->i->associated);
    secondary->i->primary = primary;
1174
    if (flags==DB_CREATE) {
1175
	// To do this:  If the secondary is empty, then open a cursor on the primary.  Step through it all, doing the callbacks.
1176
	// Then insert each callback result into the secondary.
1177
	return maybe_do_associate_create(txn, primary, secondary);
1178 1179
    }
    return 0;
1180 1181
}

1182
static int toku_db_close(DB * db, u_int32_t flags) {
1183
    if (db->i->primary==0) {
Yoni Fogel's avatar
Yoni Fogel committed
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
        // It is a primary.  Unlink all the secondaries. */
        while (!list_empty(&db->i->associated)) {
            assert(list_struct(list_head(&db->i->associated),
                   struct __toku_db_internal, associated)->primary==db);
            list_remove(list_head(&db->i->associated));
        }
    }
    else {
        // It is a secondary.  Remove it from the list, (which it must be in .*/
        if (!list_empty(&db->i->associated)) {
            list_remove(&db->i->associated);
        }
1196
    }
1197
    flags=flags;
1198
    int r = toku_close_brt(db->i->brt, db->dbenv->i->logger);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1199 1200
    if (r != 0)
        return r;
Yoni Fogel's avatar
Yoni Fogel committed
1201
    if (db->i->db_id) { toku_db_id_remove_ref(db->i->db_id); }
Yoni Fogel's avatar
Yoni Fogel committed
1202
    if (db->i->lt) {
Yoni Fogel's avatar
Yoni Fogel committed
1203 1204
        r = toku_lt_remove_ref(db->i->lt);
        if (r!=0) { return r; }
Yoni Fogel's avatar
Yoni Fogel committed
1205
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1206
    // printf("%s:%d %d=__toku_db_close(%p)\n", __FILE__, __LINE__, r, db);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1207 1208
    // 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
1209
    env_unref(db->dbenv);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
1210
    toku_free(db->i->database_name);
1211
    toku_free(db->i->fname);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
1212 1213 1214
    toku_free(db->i->full_fname);
    toku_free(db->i);
    toku_free(db);
1215
    ydb_unref();
1216
    if (r==0 && is_panicked) return EINVAL;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1217 1218 1219
    return r;
}

Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1220 1221 1222 1223 1224 1225 1226 1227 1228
/* Verify that an element from the secondary database is still consistent
   with the primary.
   \param secondary Secondary database
   \param pkey Primary key
   \param data Primary data
   \param skey Secondary key to test
   
   \return 
*/
Yoni Fogel's avatar
Yoni Fogel committed
1229 1230 1231 1232 1233 1234
static int verify_secondary_key(DB *secondary, DBT *pkey, DBT *data, DBT *skey) {
    int r = 0;
    DBT idx;

    assert(secondary->i->primary != 0);
    memset(&idx, 0, sizeof(idx));
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1235 1236 1237
    r = secondary->i->associate_callback(secondary, pkey, data, &idx);
    if (r==DB_DONOTINDEX) { r = DB_SECONDARY_BAD; goto clean_up; }
    if (r!=0) goto clean_up;
Yoni Fogel's avatar
Yoni Fogel committed
1238 1239
#ifdef DB_DBT_MULTIPLE
    if (idx.flags & DB_DBT_MULTIPLE) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1240 1241
        r = EINVAL; // We aren't ready for this
        goto clean_up;
Yoni Fogel's avatar
Yoni Fogel committed
1242 1243
    }
#endif
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1244 1245 1246 1247 1248
    if (secondary->i->brt->compare_fun(secondary, skey, &idx) != 0) {
        r = DB_SECONDARY_BAD;
        goto clean_up;
    }
    clean_up:
Yoni Fogel's avatar
Yoni Fogel committed
1249
    if (idx.flags & DB_DBT_APPMALLOC) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1250 1251
        /* This should be free because idx.data is allocated by the user */
    	free(idx.data);
Yoni Fogel's avatar
Yoni Fogel committed
1252
    }
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1253
    return r; 
Yoni Fogel's avatar
Yoni Fogel committed
1254 1255
}

1256 1257
//Get the main portion of a cursor flag (excluding the bitwise or'd components).
static int get_main_cursor_flag(u_int32_t flag) {
Yoni Fogel's avatar
Yoni Fogel committed
1258
    return flag & DB_OPFLAGS_MASK;
1259 1260
}

1261
static inline BOOL toku_c_uninitialized(DBC* c) {
Yoni Fogel's avatar
Yoni Fogel committed
1262 1263
    return toku_brt_cursor_uninitialized(c->i->c);
}            
Yoni Fogel's avatar
Yoni Fogel committed
1264 1265 1266

static int toku_c_get_current_unconditional(DBC* c, DBT* key, DBT* data) {
    assert(!toku_c_uninitialized(c));
Yoni Fogel's avatar
Yoni Fogel committed
1267 1268
    memset(key,  0, sizeof(DBT));
    memset(data, 0, sizeof(DBT));
Yoni Fogel's avatar
Yoni Fogel committed
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
    data->flags = key->flags = DB_DBT_MALLOC;
    TOKUTXN txn = c->i->txn ? c->i->txn->i->tokutxn : NULL;
    int r = toku_brt_cursor_get(c->i->c, key, data, DB_CURRENT_BINDING, txn);
    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
1282 1283 1284 1285 1286 1287 1288
/*
    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.
*/
1289
static inline DB_TXN* toku_txn_ancestor(DB_TXN* txn) {
Yoni Fogel's avatar
Yoni Fogel committed
1290
    while (txn && txn->parent) txn = txn->parent;
Yoni Fogel's avatar
Yoni Fogel committed
1291

Yoni Fogel's avatar
Yoni Fogel committed
1292 1293 1294
    return txn;
}

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

Yoni Fogel's avatar
Yoni Fogel committed
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
/* 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
    DBT         tmp_dat;            // Temporary data 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
1309
    u_int32_t   lock_flags;         // The prelock flags.
Yoni Fogel's avatar
Yoni Fogel committed
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
    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        dat_is_read;
    BOOL        dat_is_write;
    BOOL        duplicates;
    BOOL        tmp_key_malloced;
    BOOL        tmp_val_malloced;
    BOOL        tmp_dat_malloced;
} C_GET_VARS;

Yoni Fogel's avatar
Yoni Fogel committed
1323 1324 1325 1326
static inline u_int32_t get_prelocked_flags(u_int32_t flags) {
    return flags & (DB_PRELOCKED | DB_PRELOCKED_WRITE);
}

Yoni Fogel's avatar
Yoni Fogel committed
1327 1328 1329 1330
static void toku_c_get_fix_flags(C_GET_VARS* g) {
    g->op = get_main_cursor_flag(g->flag);

    switch (g->op) {
Yoni Fogel's avatar
Yoni Fogel committed
1331 1332
        case DB_NEXT:
        case DB_NEXT_NODUP:
Yoni Fogel's avatar
Yoni Fogel committed
1333 1334 1335
            if (toku_c_uninitialized(g->c)) toku_swap_flag(&g->flag, &g->op, DB_FIRST);
            else if (!g->duplicates && g->op == DB_NEXT) {
                toku_swap_flag(&g->flag, &g->op, DB_NEXT_NODUP);
Yoni Fogel's avatar
Yoni Fogel committed
1336 1337
            }
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1338 1339
        case DB_PREV:
        case DB_PREV_NODUP:
Yoni Fogel's avatar
Yoni Fogel committed
1340 1341 1342
            if (toku_c_uninitialized(g->c)) toku_swap_flag(&g->flag, &g->op, DB_LAST);
            else if (!g->duplicates && g->op == DB_PREV) {    
                toku_swap_flag(&g->flag, &g->op, DB_PREV_NODUP);
Yoni Fogel's avatar
Yoni Fogel committed
1343 1344
            }
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1345
        case DB_GET_BOTH_RANGE:
Yoni Fogel's avatar
Yoni Fogel committed
1346 1347
            if (!g->duplicates) {
                toku_swap_flag(&g->flag, &g->op, DB_GET_BOTH);
Yoni Fogel's avatar
Yoni Fogel committed
1348 1349
            }
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1350
        default:
Yoni Fogel's avatar
Yoni Fogel committed
1351 1352
            break;
    }
Yoni Fogel's avatar
Yoni Fogel committed
1353 1354
    g->lock_flags = get_prelocked_flags(g->flag);
    g->flag &= ~g->lock_flags;
Yoni Fogel's avatar
Yoni Fogel committed
1355 1356
}

Yoni Fogel's avatar
Yoni Fogel committed
1357 1358 1359 1360
static inline void toku_c_pget_fix_flags(C_GET_VARS* g) {
    toku_c_get_fix_flags(g);
}

Yoni Fogel's avatar
Yoni Fogel committed
1361 1362 1363
static int toku_c_get_pre_acquire_lock_if_possible(C_GET_VARS* g, DBT* key, DBT* data) {
    int r = ENOSYS;
    toku_lock_tree* lt = g->db->i->lt;
Yoni Fogel's avatar
Yoni Fogel committed
1364

Yoni Fogel's avatar
Yoni Fogel committed
1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
    /* We know what to lock ahead of time. */
    if (g->op == DB_GET_BOTH ||
        (g->op == DB_SET && !g->duplicates)) {
        r = toku_txn_add_lt(g->txn_anc, lt);
        if (r!=0) goto cleanup;
        r = toku_lt_acquire_read_lock(lt, g->db, g->id_anc, key, data);
        if (r!=0) goto cleanup;
    }
    r = 0;
cleanup:
    return r;
}
Yoni Fogel's avatar
Yoni Fogel committed
1377

Yoni Fogel's avatar
Yoni Fogel committed
1378 1379
static int toku_c_get_describe_inputs(C_GET_VARS* g) { 
    int r = ENOSYS;
Yoni Fogel's avatar
Yoni Fogel committed
1380 1381 1382
    /* Default for (key|value)_is_(read|write) is FALSE.
     * Default for cursor_is_write is TRUE. */
    g->cursor_is_write = TRUE;
Yoni Fogel's avatar
Yoni Fogel committed
1383 1384 1385 1386
    switch (g->op) {
        case DB_SET:
            g->key_is_read  = TRUE;
            g->val_is_write = TRUE;
Yoni Fogel's avatar
Yoni Fogel committed
1387
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1388 1389 1390 1391
        case DB_SET_RANGE:
            g->key_is_read  = TRUE;
            g->key_is_write = TRUE;
            g->val_is_write = TRUE;
Yoni Fogel's avatar
Yoni Fogel committed
1392
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1393 1394 1395
        case DB_GET_BOTH:
            g->key_is_read  = TRUE;
            g->val_is_read  = TRUE;
Yoni Fogel's avatar
Yoni Fogel committed
1396
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1397 1398 1399 1400 1401
        case DB_GET_BOTH_RANGE:
            assert(g->duplicates);
            g->key_is_read  = TRUE;
            g->val_is_read  = TRUE;
            g->val_is_write = TRUE;
Yoni Fogel's avatar
Yoni Fogel committed
1402
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1403
        case DB_CURRENT:
Yoni Fogel's avatar
Yoni Fogel committed
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
        case DB_CURRENT_BINDING:
            /* Cursor does not change. */
            g->cursor_is_write = FALSE;
            /* Break through to next case on purpose. */
        case DB_NEXT_DUP:
#if defined(DB_PREV_DUP)
        case DB_PREV_DUP:
#endif
            if (toku_c_uninitialized(g->c)) {
               r = EINVAL; goto cleanup;
            }
            /* Break through to next case on purpose. */
Yoni Fogel's avatar
Yoni Fogel committed
1416 1417 1418 1419 1420 1421 1422 1423
        case DB_FIRST:
        case DB_LAST:
        case DB_NEXT:
        case DB_NEXT_NODUP:
        case DB_PREV:
        case DB_PREV_NODUP:
            g->key_is_write = TRUE;
            g->val_is_write = TRUE;
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1424
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1425
        default:
Yoni Fogel's avatar
Yoni Fogel committed
1426
            r = EINVAL;
Yoni Fogel's avatar
Yoni Fogel committed
1427
            goto cleanup;
Yoni Fogel's avatar
Yoni Fogel committed
1428
    }
Yoni Fogel's avatar
Yoni Fogel committed
1429 1430
    r = 0;
cleanup:
Yoni Fogel's avatar
Yoni Fogel committed
1431 1432 1433
    return r;
}

Yoni Fogel's avatar
Yoni Fogel committed
1434 1435 1436 1437 1438 1439
static int toku_c_pget_describe_inputs(C_GET_VARS* g) {
    int r = toku_c_get_describe_inputs(g);
    g->dat_is_read  = FALSE;
    g->dat_is_write = TRUE;
    return r;
}
Yoni Fogel's avatar
Yoni Fogel committed
1440

Yoni Fogel's avatar
Yoni Fogel committed
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
static int toku_c_pget_save_inputs(C_GET_VARS* g, DBT* key, DBT* val, DBT* dat) {
    int r = ENOSYS;

    /* 
     * Readonly:  Copy original struct
     * Writeonly: Set to 0 (already done), DB_DBT_REALLOC, copy back later.
     * ReadWrite: Make a copy of original in new memory, copy back later
     * */
    if (key) {
        assert(g->key_is_read || g->key_is_write);
        if (g->key_is_read && !g->key_is_write) g->tmp_key = *key;
        else {
            /* g->key_is_write */
            g->tmp_key.flags = DB_DBT_REALLOC;
            if (g->key_is_read &&
                (r = toku_brt_dbt_set(&g->tmp_key, key))) goto cleanup;
            g->tmp_key_malloced = TRUE;
        }
Yoni Fogel's avatar
Yoni Fogel committed
1459
    }
Yoni Fogel's avatar
Yoni Fogel committed
1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497
    if (val) {
        assert(g->val_is_read || g->val_is_write);
        if (g->val_is_read && !g->val_is_write) g->tmp_val = *val;
        else {
            /* g->val_is_write */
            g->tmp_val.flags = DB_DBT_REALLOC;
            if (g->val_is_read &&
                (r = toku_brt_dbt_set(&g->tmp_val, val))) goto cleanup;
            g->tmp_val_malloced = TRUE;
        }
    }
    if (dat) {
        assert(g->dat_is_read || g->dat_is_write);
        if (g->dat_is_read && !g->dat_is_write) g->tmp_dat = *dat;
        else {
            /* g->dat_is_write */
            g->tmp_dat.flags = DB_DBT_REALLOC;
            if (g->dat_is_read &&
                (r = toku_brt_dbt_set(&g->tmp_dat, dat))) goto cleanup;
            g->tmp_dat_malloced = TRUE;
        }
    }
    r = 0;
cleanup:
    if (r!=0) {
        /* Cleanup memory allocated if necessary. */
        if (g->tmp_key.data && g->tmp_key_malloced) toku_free(g->tmp_key.data);
        if (g->tmp_val.data && g->tmp_val_malloced) toku_free(g->tmp_val.data);
        if (g->tmp_dat.data && g->tmp_dat_malloced) toku_free(g->tmp_dat.data);                
    }
    return r;
}

static int toku_c_get_save_inputs(C_GET_VARS* g, DBT* key, DBT* val) {
    int r = toku_c_pget_save_inputs(g, key, val, NULL);
    return r;
}

1498
static int toku_c_get_post_lock(C_GET_VARS* g, BOOL found, DBT* orig_key, DBT* orig_val, DBT *prev_key, DBT *prev_val) {
Yoni Fogel's avatar
Yoni Fogel committed
1499 1500 1501
    int r = ENOSYS;
    toku_lock_tree* lt = g->db->i->lt;
    if (!lt) { r = 0; goto cleanup; }
Yoni Fogel's avatar
Yoni Fogel committed
1502 1503 1504 1505

    BOOL lock = TRUE;
    const DBT* key_l;
    const DBT* key_r;
Yoni Fogel's avatar
Yoni Fogel committed
1506 1507 1508 1509
    const DBT* val_l;
    const DBT* val_r;
    switch (g->op) {
        case (DB_CURRENT):
Yoni Fogel's avatar
Yoni Fogel committed
1510 1511 1512 1513
            /* No locking necessary. You already own a lock by virtue
               of having a cursor pointing to this. */
            lock = FALSE;
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1514 1515 1516 1517 1518 1519 1520 1521 1522
        case (DB_SET):
            if (!g->duplicates) {
                /* We acquired the lock before the cursor op. */
                lock = FALSE;
                break;
            }
            key_l = key_r = &g->tmp_key;
            val_l =                       toku_lt_neg_infinity;
            val_r = found ? &g->tmp_val : toku_lt_infinity;
Yoni Fogel's avatar
Yoni Fogel committed
1523
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1524 1525
        case (DB_GET_BOTH):
            /* We acquired the lock before the cursor op. */
Yoni Fogel's avatar
Yoni Fogel committed
1526 1527
            lock = FALSE;
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1528 1529 1530 1531
        case (DB_FIRST):
            key_l = val_l =               toku_lt_neg_infinity;
            key_r = found ? &g->tmp_key : toku_lt_infinity;
            val_r = found ? &g->tmp_val : toku_lt_infinity;
Yoni Fogel's avatar
Yoni Fogel committed
1532
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1533 1534 1535 1536
        case (DB_LAST):
            key_l = found ? &g->tmp_key : toku_lt_neg_infinity;
            val_l = found ? &g->tmp_val : toku_lt_neg_infinity;
            key_r = val_r =               toku_lt_infinity;
Yoni Fogel's avatar
Yoni Fogel committed
1537
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1538 1539 1540 1541 1542
        case (DB_SET_RANGE):
            key_l = orig_key;
            val_l = toku_lt_neg_infinity;
            key_r = found ? &g->tmp_key : toku_lt_infinity;
            val_r = found ? &g->tmp_val : toku_lt_infinity;
Yoni Fogel's avatar
Yoni Fogel committed
1543
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1544 1545 1546 1547
        case (DB_GET_BOTH_RANGE):
            key_l = key_r = &g->tmp_key;
            val_l = orig_val;
            val_r = found ? &g->tmp_val : toku_lt_infinity;
Yoni Fogel's avatar
Yoni Fogel committed
1548 1549
            break;
        case (DB_NEXT):
Yoni Fogel's avatar
Yoni Fogel committed
1550 1551
        case (DB_NEXT_NODUP):
            assert(!toku_c_uninitialized(g->c));
1552 1553
            key_l = prev_key;
            val_l = prev_val;
Yoni Fogel's avatar
Yoni Fogel committed
1554 1555
            key_r = found ? &g->tmp_key : toku_lt_infinity;
            val_r = found ? &g->tmp_val : toku_lt_infinity;
Yoni Fogel's avatar
Yoni Fogel committed
1556 1557
            break;
        case (DB_PREV):
Yoni Fogel's avatar
Yoni Fogel committed
1558 1559 1560 1561
        case (DB_PREV_NODUP):
            assert(!toku_c_uninitialized(g->c));
            key_l = found ? &g->tmp_key : toku_lt_neg_infinity;
            val_l = found ? &g->tmp_val : toku_lt_neg_infinity;
1562 1563
            key_r = prev_key;
            val_r = prev_val;
Yoni Fogel's avatar
Yoni Fogel committed
1564
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1565 1566
        case (DB_NEXT_DUP):
            assert(!toku_c_uninitialized(g->c));
1567 1568
            key_l = key_r = prev_key;
            val_l = prev_val;
Yoni Fogel's avatar
Yoni Fogel committed
1569
            val_r = found ? &g->tmp_val : toku_lt_infinity;
Yoni Fogel's avatar
Yoni Fogel committed
1570 1571
            break;
#ifdef DB_PREV_DUP
Yoni Fogel's avatar
Yoni Fogel committed
1572 1573
        case (DB_PREV_DUP):
            assert(!toku_c_uninitialized(g->c));
1574
            key_l = key_r = prev_key;
Yoni Fogel's avatar
Yoni Fogel committed
1575
            val_l = found ? &g->tmp_val : toku_lt_neg_infinity;
1576
            val_r = prev_val;
Yoni Fogel's avatar
Yoni Fogel committed
1577 1578
            break;
#endif
Yoni Fogel's avatar
Yoni Fogel committed
1579
        default:
Yoni Fogel's avatar
Yoni Fogel committed
1580 1581
            r = EINVAL;
            lock = FALSE;
Yoni Fogel's avatar
Yoni Fogel committed
1582
            goto cleanup;
Yoni Fogel's avatar
Yoni Fogel committed
1583
    }
Yoni Fogel's avatar
Yoni Fogel committed
1584
    if (lock) {
Yoni Fogel's avatar
Yoni Fogel committed
1585 1586 1587 1588
        if ((r = toku_txn_add_lt(g->txn_anc, lt))) goto cleanup;
        r = toku_lt_acquire_range_read_lock(lt, g->db, g->id_anc, key_l, val_l,
                                                                  key_r, val_r);
        if (r!=0) goto cleanup;
Yoni Fogel's avatar
Yoni Fogel committed
1589
    }
Yoni Fogel's avatar
Yoni Fogel committed
1590
    r = 0;
Yoni Fogel's avatar
Yoni Fogel committed
1591
cleanup:
Yoni Fogel's avatar
Yoni Fogel committed
1592
    return r;
Yoni Fogel's avatar
Yoni Fogel committed
1593 1594
}

Yoni Fogel's avatar
Yoni Fogel committed
1595 1596 1597 1598 1599
static int toku_c_pget_assign_outputs(C_GET_VARS* g, DBT* key, DBT* val, DBT* dat) {
    int r = ENOSYS;
    DBT* write_key = g->key_is_write ? key : NULL;
    DBT* write_val = g->val_is_write ? val : NULL;
    DBT* write_dat = g->dat_is_write ? dat : NULL;
Yoni Fogel's avatar
Yoni Fogel committed
1600
    BRT primary = g->db->i->primary->i->brt;
Yoni Fogel's avatar
Yoni Fogel committed
1601

Yoni Fogel's avatar
Yoni Fogel committed
1602 1603 1604 1605
    r = toku_brt_cursor_dbts_set_with_dat(g->c->i->c, primary,
                                          write_key, &g->tmp_key, TRUE,
                                          write_val, &g->tmp_val, TRUE,
                                          write_dat, &g->tmp_dat, TRUE);
Yoni Fogel's avatar
Yoni Fogel committed
1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
    if (r!=0) goto cleanup;
    r = 0;
cleanup:
    return r;
}

static int toku_c_get_assign_outputs(C_GET_VARS* g, DBT* key, DBT* val) {
    int r = ENOSYS;
    DBT* write_key = g->key_is_write ? key : NULL;
    DBT* write_val = g->val_is_write ? val : NULL;

Yoni Fogel's avatar
Yoni Fogel committed
1617 1618 1619
    r = toku_brt_cursor_dbts_set(g->c->i->c,
                                 write_key, &g->tmp_key, TRUE,
                                 write_val, &g->tmp_val, TRUE);
Yoni Fogel's avatar
Yoni Fogel committed
1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
    if (r!=0) goto cleanup;
    r = 0;
cleanup:
    return r;
}

static int toku_c_get_noassociate(DBC * c, DBT * key, DBT * val, u_int32_t flag) {
    HANDLE_PANICKED_DB(c->dbp);
    int r           = ENOSYS;
    C_GET_VARS g;
    memset(&g, 0, sizeof(g));
    /* Initialize variables. */
    g.c    = c;
    g.db   = c->dbp;
    g.flag = flag;
    unsigned int brtflags;
    toku_brt_get_flags(g.db->i->brt, &brtflags);
    g.duplicates   = (brtflags & TOKU_DB_DUPSORT) != 0;

    /* Standardize the op flag. */
    toku_c_get_fix_flags(&g);
Yoni Fogel's avatar
Yoni Fogel committed
1641 1642 1643 1644 1645 1646
    TOKUTXN txn = c->i->txn ? c->i->txn->i->tokutxn : NULL;

    if (!g.db->i->lt || g.lock_flags) {
        r = toku_brt_cursor_get(c->i->c, key, val, g.flag, txn);
        goto cleanup;
    }
Yoni Fogel's avatar
Yoni Fogel committed
1647 1648 1649 1650 1651
    int r_cursor_op = 0;
    if (c->i->txn) {
        g.txn_anc = toku_txn_ancestor(c->i->txn);
        g.id_anc  = toku_txn_get_txnid(g.txn_anc->i->tokutxn);
    }
Yoni Fogel's avatar
Yoni Fogel committed
1652

Yoni Fogel's avatar
Yoni Fogel committed
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669
    /* If we know what to lock before the cursor op, lock now. */
    if ((r = toku_c_get_pre_acquire_lock_if_possible(&g, key, val))) goto cleanup;
    /* Determine whether the key and val parameters are read, write,
     * or both. */
    if ((r = toku_c_get_describe_inputs(&g))) goto cleanup;
    /* Save key and value to temporary local versions. */
    if ((r = toku_c_get_save_inputs(&g, key, val))) goto cleanup;
    /* Run the cursor operation on the brt. */
    r_cursor_op = r = toku_brt_cursor_get(c->i->c, &g.tmp_key, &g.tmp_val, g.flag, txn);
    /* Only DB_CURRENT should possibly retun DB_KEYEMPTY,
     * and DB_CURRENT requires no locking. */
    if (r==DB_KEYEMPTY) { assert(g.op==DB_CURRENT); goto cleanup; }
    /* If we do not find what the query wants, a lock can still fail
     * 'first'. */
    if (r!=0 && r!=DB_NOTFOUND) goto cleanup;
    /* If we have not yet locked, lock now. */
    BOOL found = r_cursor_op==0;
1670 1671
    r = toku_c_get_post_lock(&g, found, key, val,
			     found ? brt_cursor_peek_prev_key(c->i->c) : brt_cursor_peek_current_key(c->i->c),
Zardosht Kasheff's avatar
Zardosht Kasheff committed
1672
			     found ? brt_cursor_peek_prev_val(c->i->c) : brt_cursor_peek_current_val(c->i->c));
1673 1674 1675 1676
    if (r!=0) {
	if (g.cursor_is_write && r_cursor_op==0) brt_cursor_restore_state_from_prev(c->i->c);
	goto cleanup;
    }
Yoni Fogel's avatar
Yoni Fogel committed
1677 1678 1679 1680 1681 1682 1683
    /* if found, write the outputs to the output parameters. */
    if (found && (r = toku_c_get_assign_outputs(&g, key, val))) goto cleanup; 
    r = r_cursor_op;
cleanup:
    /* Cleanup temporary keys. */
    if (g.tmp_key.data && g.tmp_key_malloced) toku_free(g.tmp_key.data);
    if (g.tmp_val.data && g.tmp_val_malloced) toku_free(g.tmp_val.data);
Yoni Fogel's avatar
Yoni Fogel committed
1684 1685 1686 1687
    return r;
}

static int toku_c_del_noassociate(DBC * c, u_int32_t flags) {
Yoni Fogel's avatar
Yoni Fogel committed
1688 1689 1690 1691
    DB* db = c->dbp;
    HANDLE_PANICKED_DB(db);
    if (toku_c_uninitialized(c)) return EINVAL;

Yoni Fogel's avatar
Yoni Fogel committed
1692 1693 1694
    u_int32_t lock_flags = get_prelocked_flags(flags);
    flags &= ~lock_flags;

Yoni Fogel's avatar
Yoni Fogel committed
1695
    int r;
Yoni Fogel's avatar
Yoni Fogel committed
1696
    if (db->i->lt && !(lock_flags&DB_PRELOCKED_WRITE)) {
Yoni Fogel's avatar
Yoni Fogel committed
1697 1698 1699 1700
        DBT saved_key;
        DBT saved_data;
        r = toku_c_get_current_unconditional(c, &saved_key, &saved_data);
        if (r!=0) return r;
Yoni Fogel's avatar
Yoni Fogel committed
1701 1702 1703 1704 1705
        DB_TXN* txn_anc = toku_txn_ancestor(c->i->txn);
        r = toku_txn_add_lt(txn_anc, db->i->lt);
        if (r!=0) { return r; }
        TXNID id_anc = toku_txn_get_txnid(txn_anc->i->tokutxn);
        r = toku_lt_acquire_write_lock(db->i->lt, db, id_anc,
Yoni Fogel's avatar
Yoni Fogel committed
1706 1707 1708 1709 1710 1711
                                       &saved_key, &saved_data);
        if (saved_key.data)  toku_free(saved_key.data);
        if (saved_data.data) toku_free(saved_data.data);
        if (r!=0) return r;
    }
    r = toku_brt_cursor_delete(c->i->c, flags, c->i->txn ? c->i->txn->i->tokutxn : 0);
Yoni Fogel's avatar
Yoni Fogel committed
1712 1713 1714
    return r;
}

Yoni Fogel's avatar
 
Yoni Fogel committed
1715
static int toku_c_pget(DBC * c, DBT *key, DBT *pkey, DBT *data, u_int32_t flag) {
Yoni Fogel's avatar
Yoni Fogel committed
1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728
    HANDLE_PANICKED_DB(c->dbp);
    DB *pdb = c->dbp->i->primary;
    /* c_pget does not work on a primary. */
    if (!pdb) return EINVAL;

    /* If data and primary_key are both zeroed,
     * the temporary storage used to fill in data
     * is different in the two cases because they
     * come from different trees.
     * Make sure they realy are different trees. */
    assert(c->dbp->i->brt!=pdb->i->brt);
    assert(c->dbp!=pdb);

Yoni Fogel's avatar
 
Yoni Fogel committed
1729
    int r;
Yoni Fogel's avatar
Yoni Fogel committed
1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742
    C_GET_VARS g;
    memset(&g, 0, sizeof(g));
    /* Initialize variables. */
    g.c    = c;
    g.db   = c->dbp;
    unsigned int brtflags;
    toku_brt_get_flags(g.db->i->brt, &brtflags);
    g.duplicates   = (brtflags & TOKU_DB_DUPSORT) != 0;

    /* The 'key' from C_GET_VARS is the secondary key, and the 'val'
     * from C_GET_VARS is the primary key.  The 'data' parameter here
     * is ALWAYS write-only */ 

1743
    int r_cursor_op;
1744

Yoni Fogel's avatar
Yoni Fogel committed
1745
    if (0) {
1746
delete_silently_and_retry:
Yoni Fogel's avatar
Yoni Fogel committed
1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759
        /* Free all old 'saved' elements, return to pristine state. */
        if (g.tmp_key.data && g.tmp_key_malloced) toku_free(g.tmp_key.data);                
        memset(&g.tmp_key, 0, sizeof(g.tmp_key));
        g.tmp_key_malloced = FALSE;

        if (g.tmp_val.data && g.tmp_val_malloced) toku_free(g.tmp_val.data);                
        memset(&g.tmp_val, 0, sizeof(g.tmp_val));
        g.tmp_val_malloced = FALSE;

        if (g.tmp_dat.data && g.tmp_dat_malloced) toku_free(g.tmp_dat.data);                
        memset(&g.tmp_dat, 0, sizeof(g.tmp_dat));
        g.tmp_dat_malloced = FALSE;
        /* Silently delete and re-run. */
1760 1761
        if ((r = toku_c_del_noassociate(c, 0))) goto cleanup_after_actual_get;
	if (g.cursor_is_write && r_cursor_op==0) brt_cursor_restore_state_from_prev(c->i->c);
1762
    }
1763 1764 1765 1766 1767 1768 1769 1770

    g.flag = flag;
    /* Standardize the op flag. */
    toku_c_pget_fix_flags(&g);
    /* Determine whether the key, val, and data, parameters are read, write,
     * or both. */
    if ((r = toku_c_pget_describe_inputs(&g))) goto cleanup;

Yoni Fogel's avatar
Yoni Fogel committed
1771 1772 1773
    /* Save the inputs. */
    if ((r = toku_c_pget_save_inputs(&g, key, pkey, data))) goto cleanup;

1774
    if ((r_cursor_op = r = toku_c_get_noassociate(c, &g.tmp_key, &g.tmp_val, g.flag))) goto cleanup;
Yoni Fogel's avatar
Yoni Fogel committed
1775 1776 1777

    r = toku_db_get(pdb, c->i->txn, &g.tmp_val, &g.tmp_dat, 0);
    if (r==DB_NOTFOUND) goto delete_silently_and_retry;
1778 1779 1780 1781 1782
    if (r!=0) {
    cleanup_after_actual_get:
	if (g.cursor_is_write && r_cursor_op==0) brt_cursor_restore_state_from_prev(c->i->c);
	goto cleanup;
    }
Yoni Fogel's avatar
Yoni Fogel committed
1783 1784 1785

    r = verify_secondary_key(g.db, &g.tmp_val, &g.tmp_dat, &g.tmp_key);
    if (r==DB_SECONDARY_BAD) goto delete_silently_and_retry;
1786
    if (r!=0) goto cleanup_after_actual_get;
Yoni Fogel's avatar
Yoni Fogel committed
1787 1788

    /* Atomically assign all 3 outputs. */
1789
    if ((r = toku_c_pget_assign_outputs(&g, key, pkey, data))) goto cleanup_after_actual_get;
Yoni Fogel's avatar
Yoni Fogel committed
1790 1791 1792 1793 1794 1795 1796
    r = 0;
cleanup:
    /* Cleanup temporary keys. */
    if (g.tmp_key.data && g.tmp_key_malloced) toku_free(g.tmp_key.data);
    if (g.tmp_val.data && g.tmp_val_malloced) toku_free(g.tmp_val.data);
    if (g.tmp_dat.data && g.tmp_dat_malloced) toku_free(g.tmp_dat.data);                
    return r;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1797 1798
}

Yoni Fogel's avatar
Yoni Fogel committed
1799
static int toku_c_get(DBC * c, DBT * key, DBT * data, u_int32_t flag) {
1800
    DB *db = c->dbp;
1801
    HANDLE_PANICKED_DB(db);
Yoni Fogel's avatar
Yoni Fogel committed
1802 1803
    int r;

Yoni Fogel's avatar
Yoni Fogel committed
1804 1805
    if (db->i->primary==0) {
        r = toku_c_get_noassociate(c, key, data, flag);
Yoni Fogel's avatar
Yoni Fogel committed
1806
    }
Yoni Fogel's avatar
Yoni Fogel committed
1807 1808 1809 1810 1811 1812 1813
    else {
        // It's a c_get on a secondary.
        DBT primary_key;
        
        /* It is an error to use the DB_GET_BOTH or DB_GET_BOTH_RANGE flag on a
         * cursor that has been opened on a secondary index handle.
         */
Yoni Fogel's avatar
Yoni Fogel committed
1814 1815 1816
        u_int32_t get_flag = get_main_cursor_flag(flag);
        if ((get_flag == DB_GET_BOTH) ||
            (get_flag == DB_GET_BOTH_RANGE)) return EINVAL;
Yoni Fogel's avatar
Yoni Fogel committed
1817 1818 1819 1820 1821 1822
        memset(&primary_key, 0, sizeof(primary_key));
        r = toku_c_pget(c, key, &primary_key, data, flag);
    }
    return r;
}

Yoni Fogel's avatar
Yoni Fogel committed
1823 1824 1825 1826 1827 1828 1829 1830
static int locked_c_getf_first(DBC *c, u_int32_t flag, void(*f)(DBT const *key, DBT const *data, void *extra), void *extra) {
    toku_ydb_lock();  int r = toku_c_getf_first(c, flag, f, extra); toku_ydb_unlock(); return r;
}

static int locked_c_getf_last(DBC *c, u_int32_t flag, void(*f)(DBT const *key, DBT const *data, void *extra), void *extra) {
    toku_ydb_lock();  int r = toku_c_getf_last(c, flag, f, extra); toku_ydb_unlock(); return r;
}

1831
static int locked_c_getf_next(DBC *c, u_int32_t flag, void(*f)(DBT const *key, DBT const *data, void *extra), void *extra) {
1832
    toku_ydb_lock();  int r = toku_c_getf_next(c, flag, f, extra); toku_ydb_unlock(); return r;
1833 1834
}

Yoni Fogel's avatar
Yoni Fogel committed
1835 1836 1837 1838
static int locked_c_getf_prev(DBC *c, u_int32_t flag, void(*f)(DBT const *key, DBT const *data, void *extra), 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
1839 1840 1841 1842
static int locked_c_getf_next_dup(DBC *c, u_int32_t flag, void(*f)(DBT const *key, DBT const *data, void *extra), 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
1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 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
static int toku_c_getf_first(DBC *c, u_int32_t flag, void(*f)(DBT const *key, DBT const *data, void *extra), void *extra) {
    HANDLE_PANICKED_DB(c->dbp);
    u_int32_t lock_flags = get_prelocked_flags(flag);
    flag &= ~lock_flags;
    assert(flag==0);
    TOKUTXN txn = c->i->txn ? c->i->txn->i->tokutxn : NULL;
    const DBT *pkey, *pval;
    pkey = pval = toku_lt_infinity;
    int r;

    DB *db=c->dbp;
    toku_lock_tree* lt = db->i->lt;
    BOOL do_locking = lt!=NULL && !lock_flags;

    int c_get_result = toku_brt_cursor_get(c->i->c, NULL, NULL, DB_FIRST, txn);
    if (c_get_result!=0 && c_get_result!=DB_NOTFOUND) { r = c_get_result; goto cleanup; }
    int found = c_get_result==0;
    if (found) brt_cursor_peek_current(c->i->c, &pkey, &pval);
    if (do_locking) {
        DB_TXN *txn_anc = toku_txn_ancestor(c->i->txn);
        r = toku_txn_add_lt(txn_anc, lt);
        if (r!=0) goto cleanup;
        r = toku_lt_acquire_range_read_lock(lt, db, toku_txn_get_txnid(txn_anc->i->tokutxn),
                                            toku_lt_neg_infinity, toku_lt_neg_infinity,
                                            pkey,                 pval);
        if (r!=0) goto cleanup;
    }
    if (found) {
	f(pkey, pval, extra);
    }
    r = c_get_result;
cleanup:
    return r;
}

static int toku_c_getf_last(DBC *c, u_int32_t flag, void(*f)(DBT const *key, DBT const *data, void *extra), void *extra) {
    HANDLE_PANICKED_DB(c->dbp);
Yoni Fogel's avatar
Yoni Fogel committed
1880 1881
    u_int32_t lock_flags = get_prelocked_flags(flag);
    flag &= ~lock_flags;
1882
    assert(flag==0);
Yoni Fogel's avatar
Yoni Fogel committed
1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909
    TOKUTXN txn = c->i->txn ? c->i->txn->i->tokutxn : NULL;
    const DBT *pkey, *pval;
    pkey = pval = toku_lt_neg_infinity;
    int r;

    DB *db=c->dbp;
    toku_lock_tree* lt = db->i->lt;
    BOOL do_locking = lt!=NULL && !lock_flags;

    int c_get_result = toku_brt_cursor_get(c->i->c, NULL, NULL, DB_LAST, txn);
    if (c_get_result!=0 && c_get_result!=DB_NOTFOUND) { r = c_get_result; goto cleanup; }
    int found = c_get_result==0;
    if (found) brt_cursor_peek_current(c->i->c, &pkey, &pval);
    if (do_locking) {
        DB_TXN *txn_anc = toku_txn_ancestor(c->i->txn);
        r = toku_txn_add_lt(txn_anc, lt);
        if (r!=0) goto cleanup;
        r = toku_lt_acquire_range_read_lock(lt, db, toku_txn_get_txnid(txn_anc->i->tokutxn),
                                            pkey,             pval,
                                            toku_lt_infinity, toku_lt_infinity);
        if (r!=0) goto cleanup;
    }
    if (found) {
	f(pkey, pval, extra);
    }
    r = c_get_result;
cleanup:
1910 1911 1912
    return r;
}

1913 1914
static int toku_c_getf_next(DBC *c, u_int32_t flag, void(*f)(DBT const *key, DBT const *data, void *extra), void *extra) {
    HANDLE_PANICKED_DB(c->dbp);
Yoni Fogel's avatar
Yoni Fogel committed
1915
    if (toku_c_uninitialized(c)) return toku_c_getf_first(c, flag, f, extra);
Yoni Fogel's avatar
Yoni Fogel committed
1916 1917
    u_int32_t lock_flags = get_prelocked_flags(flag);
    flag &= ~lock_flags;
1918 1919
    assert(flag==0);
    TOKUTXN txn = c->i->txn ? c->i->txn->i->tokutxn : NULL;
Yoni Fogel's avatar
Yoni Fogel committed
1920 1921
    const DBT *pkey, *pval;
    pkey = pval = toku_lt_infinity;
Yoni Fogel's avatar
Yoni Fogel committed
1922
    int r;
1923 1924

    DB *db=c->dbp;
Yoni Fogel's avatar
Yoni Fogel committed
1925 1926
    toku_lock_tree* lt = db->i->lt;
    BOOL do_locking = lt!=NULL && !lock_flags;
1927 1928 1929 1930

    unsigned int brtflags;
    toku_brt_get_flags(db->i->brt, &brtflags);

Yoni Fogel's avatar
Yoni Fogel committed
1931
    int c_get_result = toku_brt_cursor_get(c->i->c, NULL, NULL,
Yoni Fogel's avatar
Yoni Fogel committed
1932 1933
                                          (brtflags & TOKU_DB_DUPSORT) ? DB_NEXT : DB_NEXT_NODUP,
                                           txn);
1934 1935
    if (c_get_result!=0 && c_get_result!=DB_NOTFOUND) { r = c_get_result; goto cleanup; }
    int found = c_get_result==0;
Yoni Fogel's avatar
Yoni Fogel committed
1936
    if (found) brt_cursor_peek_current(c->i->c, &pkey, &pval);
Yoni Fogel's avatar
Yoni Fogel committed
1937
    if (do_locking) {
1938 1939

	DBT *prevkey = found ? brt_cursor_peek_prev_key(c->i->c) : brt_cursor_peek_current_key(c->i->c);
Yoni Fogel's avatar
Yoni Fogel committed
1940
	DBT *prevval = found ? brt_cursor_peek_prev_val(c->i->c) : brt_cursor_peek_current_val(c->i->c);
1941

Yoni Fogel's avatar
Yoni Fogel committed
1942 1943 1944 1945
        DB_TXN *txn_anc = toku_txn_ancestor(c->i->txn);
        r = toku_txn_add_lt(txn_anc, lt);
        if (r!=0) goto cleanup;
        r = toku_lt_acquire_range_read_lock(lt, db, toku_txn_get_txnid(txn_anc->i->tokutxn),
1946
                                            prevkey, prevval,
Yoni Fogel's avatar
Yoni Fogel committed
1947
                                            pkey, pval);
Yoni Fogel's avatar
Yoni Fogel committed
1948 1949
        if (r!=0) goto cleanup;
    }
1950
    if (found) {
Yoni Fogel's avatar
Yoni Fogel committed
1951
	f(pkey, pval, extra);
1952 1953 1954 1955 1956
    }
    r = c_get_result;
 cleanup:
    return r;
}
1957

Yoni Fogel's avatar
Yoni Fogel committed
1958 1959
static int toku_c_getf_prev(DBC *c, u_int32_t flag, void(*f)(DBT const *key, DBT const *data, void *extra), void *extra) {
    HANDLE_PANICKED_DB(c->dbp);
Yoni Fogel's avatar
Yoni Fogel committed
1960
    if (toku_c_uninitialized(c)) return toku_c_getf_last(c, flag, f, extra);
Yoni Fogel's avatar
Yoni Fogel committed
1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984
    u_int32_t lock_flags = get_prelocked_flags(flag);
    flag &= ~lock_flags;
    assert(flag==0);
    TOKUTXN txn = c->i->txn ? c->i->txn->i->tokutxn : NULL;
    const DBT *pkey, *pval;
    pkey = pval = toku_lt_neg_infinity;
    int r;

    DB *db=c->dbp;
    toku_lock_tree* lt = db->i->lt;
    BOOL do_locking = lt!=NULL && !lock_flags;

    unsigned int brtflags;
    toku_brt_get_flags(db->i->brt, &brtflags);

    int c_get_result = toku_brt_cursor_get(c->i->c, NULL, NULL,
                                          (brtflags & TOKU_DB_DUPSORT) ? DB_PREV : DB_PREV_NODUP,
                                           txn);
    if (c_get_result!=0 && c_get_result!=DB_NOTFOUND) { r = c_get_result; goto cleanup; }
    int found = c_get_result==0;
    if (found) brt_cursor_peek_current(c->i->c, &pkey, &pval);
    if (do_locking) {

	DBT *prevkey = found ? brt_cursor_peek_prev_key(c->i->c) : brt_cursor_peek_current_key(c->i->c);
Yoni Fogel's avatar
Yoni Fogel committed
1985
	DBT *prevval = found ? brt_cursor_peek_prev_val(c->i->c) : brt_cursor_peek_current_val(c->i->c);
Yoni Fogel's avatar
Yoni Fogel committed
1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002

        DB_TXN *txn_anc = toku_txn_ancestor(c->i->txn);
        r = toku_txn_add_lt(txn_anc, lt);
        if (r!=0) goto cleanup;
        r = toku_lt_acquire_range_read_lock(lt, db, toku_txn_get_txnid(txn_anc->i->tokutxn),
                                            pkey, pval,
                                            prevkey, prevval);
        if (r!=0) goto cleanup;
    }
    if (found) {
	f(pkey, pval, extra);
    }
    r = c_get_result;
 cleanup:
    return r;
}

Yoni Fogel's avatar
Yoni Fogel committed
2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024
static int toku_c_getf_next_dup(DBC *c, u_int32_t flag, void(*f)(DBT const *key, DBT const *data, void *extra), void *extra) {
    HANDLE_PANICKED_DB(c->dbp);
    if (toku_c_uninitialized(c)) return EINVAL;
    u_int32_t lock_flags = get_prelocked_flags(flag);
    flag &= ~lock_flags;
    assert(flag==0);
    TOKUTXN txn = c->i->txn ? c->i->txn->i->tokutxn : NULL;
    const DBT *pkey, *pval;
    pkey = pval = toku_lt_infinity;
    int r;

    DB *db=c->dbp;
    toku_lock_tree* lt = db->i->lt;
    BOOL do_locking = lt!=NULL && !lock_flags;

    int c_get_result = toku_brt_cursor_get(c->i->c, NULL, NULL, DB_NEXT_DUP, txn);
    if (c_get_result!=0 && c_get_result!=DB_NOTFOUND) { r = c_get_result; goto cleanup; }
    int found = c_get_result==0;
    if (found) brt_cursor_peek_current(c->i->c, &pkey, &pval);
    if (do_locking) {

	DBT *prevkey = found ? brt_cursor_peek_prev_key(c->i->c) : brt_cursor_peek_current_key(c->i->c);
Yoni Fogel's avatar
Yoni Fogel committed
2025
	DBT *prevval = found ? brt_cursor_peek_prev_val(c->i->c) : brt_cursor_peek_current_val(c->i->c);
Yoni Fogel's avatar
Yoni Fogel committed
2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042

        DB_TXN *txn_anc = toku_txn_ancestor(c->i->txn);
        r = toku_txn_add_lt(txn_anc, lt);
        if (r!=0) goto cleanup;
        r = toku_lt_acquire_range_read_lock(lt, db, toku_txn_get_txnid(txn_anc->i->tokutxn),
                                            prevkey, prevval,
                                            prevkey, pval);
        if (r!=0) goto cleanup;
    }
    if (found) {
	f(pkey, pval, extra);
    }
    r = c_get_result;
 cleanup:
    return r;
}

Yoni Fogel's avatar
Yoni Fogel committed
2043 2044 2045 2046 2047 2048 2049 2050 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 2102 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 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166
static int locked_c_getf_heavi(DBC *c, u_int32_t flags,
                               void(*f)(DBT const *key, DBT const *value, void *extra_f, int r_h),
                               void *extra_f,
                               int (*h)(const DBT *key, const DBT *value, void *extra_h),
                               void *extra_h, int direction) {
    toku_ydb_lock();  int r = toku_c_getf_heavi(c, flags, f, extra_f, h, extra_h, direction); toku_ydb_unlock(); return r;
}

static int toku_c_getf_heavi(DBC *c, u_int32_t flags,
                             void(*f)(DBT const *key, DBT const *value, void *extra_f, int r_h),
                             void *extra_f,
                             int (*h)(const DBT *key, const DBT *value, void *extra_h),
                             void *extra_h, int direction) {
    if (direction==0) return EINVAL;
    DBC *tmp_c = NULL;
    int r;
    u_int32_t lock_flags = get_prelocked_flags(flags);
    flags &= ~lock_flags;
    assert(flags==0);
    struct heavi_wrapper wrapper;
    wrapper.h       = h;
    wrapper.extra_h = extra_h;
    wrapper.r_h     = direction;

    TOKUTXN txn = c->i->txn ? c->i->txn->i->tokutxn : NULL;
    int c_get_result = toku_brt_cursor_get_heavi(c->i->c, NULL, NULL, txn, direction, &wrapper);
    if (c_get_result!=0 && c_get_result!=DB_NOTFOUND) { r = c_get_result; goto cleanup; }
    BOOL found = c_get_result==0;
    DB *db=c->dbp;
    toku_lock_tree* lt = db->i->lt;
    if (lt!=NULL && !lock_flags) {
        DBT tmp_key;
        DBT tmp_val;
        DBT *left_key, *left_val, *right_key, *right_val;
        if (direction<0) {
            if (!found) {
                r = toku_brt_cursor_get(c->i->c, NULL, NULL, DB_FIRST, txn);
                if (r!=0 && r!=DB_NOTFOUND) goto cleanup;
                if (r==DB_NOTFOUND) right_key = right_val = (DBT*)toku_lt_infinity;
                else {
                    //Restore cursor to the 'uninitialized' state it was just in.
                    brt_cursor_restore_state_from_prev(c->i->c);
                    right_key = brt_cursor_peek_prev_key(c->i->c);
                    right_val = brt_cursor_peek_prev_val(c->i->c);
                }
                left_key = left_val = (DBT*)toku_lt_neg_infinity;
            }
            else {
                left_key = brt_cursor_peek_current_key(c->i->c);
                left_val = brt_cursor_peek_current_val(c->i->c);
                //Try to find right end the fast way.
                r = toku_brt_cursor_peek_next(c->i->c, &tmp_key, &tmp_val);
                if (r==0) {
                    right_key = &tmp_key;
                    right_val = &tmp_val;
                }
                else {
                    //Find the right end the slow way.
                    if ((r = toku_db_cursor(c->dbp, c->i->txn, &tmp_c, 0, 0))) goto cleanup;
                    r=toku_brt_cursor_after(tmp_c->i->c, left_key, left_val,
                                                         NULL,     NULL, txn);
                    if (r!=0 && r!=DB_NOTFOUND) goto cleanup;
                    if (r==DB_NOTFOUND) right_key = right_val = (DBT*)toku_lt_infinity;
                    else {
                        right_key = brt_cursor_peek_current_key(tmp_c->i->c);
                        right_val = brt_cursor_peek_current_val(tmp_c->i->c);
                    }
                }
            }
        }
        else {
            //direction>0
            if (!found) {
                r = toku_brt_cursor_get(c->i->c, NULL, NULL, DB_LAST, txn);
                if (r!=0 && r!=DB_NOTFOUND) goto cleanup;
                if (r==DB_NOTFOUND) left_key = left_val = (DBT*)toku_lt_neg_infinity;
                else {
                    //Restore cursor to the 'uninitialized' state it was just in.
                    brt_cursor_restore_state_from_prev(c->i->c);
                    left_key = brt_cursor_peek_prev_key(c->i->c);
                    left_val = brt_cursor_peek_prev_val(c->i->c);
                }
                right_key = right_val = (DBT*)toku_lt_infinity;
            }
            else {
                right_key = brt_cursor_peek_current_key(c->i->c);
                right_val = brt_cursor_peek_current_val(c->i->c);
                //Try to find left end the fast way.
                r=toku_brt_cursor_peek_prev(c->i->c, &tmp_key, &tmp_val);
                if (r==0) {
                    left_key = &tmp_key;
                    left_val = &tmp_val;
                }
                else {
                    //Find the left end the slow way.
                    if ((r = toku_db_cursor(c->dbp, c->i->txn, &tmp_c, 0, 0))) goto cleanup;
                    r=toku_brt_cursor_before(tmp_c->i->c, right_key, right_val,
                                                          NULL,      NULL, txn);
                    if (r==DB_NOTFOUND) left_key = left_val = (DBT*)toku_lt_neg_infinity;
                    else {
                        left_key = brt_cursor_peek_current_key(tmp_c->i->c);
                        left_val = brt_cursor_peek_current_val(tmp_c->i->c);
                    }
                }
            }
        }
        DB_TXN* txn_anc = toku_txn_ancestor(c->i->txn);
        TXNID id_anc = toku_txn_get_txnid(txn_anc->i->tokutxn);
        if ((r = toku_txn_add_lt(txn_anc, lt))) goto cleanup;
        r = toku_lt_acquire_range_read_lock(lt, db, id_anc,
                                            left_key, left_val,
                                            right_key, right_val);
        if (r!=0) goto cleanup;
    }
    if (found) {
        f(brt_cursor_peek_current_key(c->i->c), brt_cursor_peek_current_val(c->i->c), extra_f, wrapper.r_h);
    }
    r = c_get_result;
cleanup:;
    int r2 = 0;
    if (tmp_c) r2 = toku_c_close(tmp_c);
    return r ? r : r2;
}

2167
static int toku_c_close(DBC * c) {
2168
    int r = toku_brt_cursor_close(c->i->c);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
2169 2170
    toku_free(c->i);
    toku_free(c);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2171 2172 2173
    return r;
}

2174 2175 2176 2177 2178
static inline int keyeq(DBC *c, DBT *a, DBT *b) {
    DB *db = c->dbp;
    return db->i->brt->compare_fun(db, a, b) == 0;
}

Rich Prohaska's avatar
Rich Prohaska committed
2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190
static int toku_c_count(DBC *cursor, db_recno_t *count, u_int32_t flags) {
    int r;
    DBC *count_cursor = 0;
    DBT currentkey; memset(&currentkey, 0, sizeof currentkey); currentkey.flags = DB_DBT_REALLOC;
    DBT currentval; memset(&currentval, 0, sizeof currentval); currentval.flags = DB_DBT_REALLOC;
    DBT key; memset(&key, 0, sizeof key); key.flags = DB_DBT_REALLOC;
    DBT val; memset(&val, 0, sizeof val); val.flags = DB_DBT_REALLOC;

    if (flags != 0) {
        r = EINVAL; goto finish;
    }

2191
    r = toku_c_get(cursor, &currentkey, &currentval, DB_CURRENT_BINDING);
Rich Prohaska's avatar
Rich Prohaska committed
2192 2193
    if (r != 0) goto finish;
    
2194
    r = toku_db_cursor(cursor->dbp, 0, &count_cursor, 0, 0);
Rich Prohaska's avatar
Rich Prohaska committed
2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220
    if (r != 0) goto finish;

    *count = 0;
    r = toku_c_get(count_cursor, &currentkey, &currentval, DB_SET); 
    if (r != 0) {
        r = 0; goto finish; /* success, the current key must be deleted and there are no more */
    }

    for (;;) {
        *count += 1;
        r = toku_c_get(count_cursor, &key, &val, DB_NEXT);
        if (r != 0) break;
        if (!keyeq(count_cursor, &currentkey, &key)) break;
    }
    r = 0; /* success, we found at least one before the end */
finish:
    if (key.data) toku_free(key.data);
    if (val.data) toku_free(val.data);
    if (currentkey.data) toku_free(currentkey.data);
    if (currentval.data) toku_free(currentval.data);
    if (count_cursor) {
        int rr = toku_c_close(count_cursor); assert(rr == 0);
    }
    return r;
}

Yoni Fogel's avatar
 
Yoni Fogel committed
2221 2222
static int toku_db_get_noassociate(DB * db, DB_TXN * txn, DBT * key, DBT * data, u_int32_t flags) {
    int r;
Yoni Fogel's avatar
Yoni Fogel committed
2223 2224
    u_int32_t lock_flags = get_prelocked_flags(flags);
    flags &= ~lock_flags;
2225
    if (flags!=0 && flags!=DB_GET_BOTH) return EINVAL;
2226

Yoni Fogel's avatar
Yoni Fogel committed
2227
    DBC *dbc;
2228
    r = toku_db_cursor(db, txn, &dbc, 0, 1);
Yoni Fogel's avatar
Yoni Fogel committed
2229
    if (r!=0) return r;
Yoni Fogel's avatar
Yoni Fogel committed
2230 2231
    u_int32_t c_get_flags = (flags == 0) ? DB_SET : DB_GET_BOTH;
    r = toku_c_get_noassociate(dbc, key, data, c_get_flags | lock_flags);
Yoni Fogel's avatar
Yoni Fogel committed
2232 2233
    int r2 = toku_c_close(dbc);
    return r ? r : r2;
Yoni Fogel's avatar
 
Yoni Fogel committed
2234 2235 2236 2237
}

static int toku_db_del_noassociate(DB * db, DB_TXN * txn, DBT * key, u_int32_t flags) {
    int r;
Yoni Fogel's avatar
Yoni Fogel committed
2238 2239
    u_int32_t lock_flags = get_prelocked_flags(flags);
    flags &= ~lock_flags;
2240
    if (flags!=0 && flags!=DB_DELETE_ANY) return EINVAL;
Yoni Fogel's avatar
 
Yoni Fogel committed
2241 2242 2243 2244
    //DB_DELETE_ANY supresses the BDB DB->del return value indicating that the key was not found prior to the delete
    if (!(flags & DB_DELETE_ANY)) {
        DBT search_val; memset(&search_val, 0, sizeof search_val); 
        search_val.flags = DB_DBT_MALLOC;
Yoni Fogel's avatar
Yoni Fogel committed
2245
        r = toku_db_get_noassociate(db, txn, key, &search_val, lock_flags);
Yoni Fogel's avatar
 
Yoni Fogel committed
2246 2247
        if (r != 0)
            return r;
2248
        toku_free(search_val.data);
Yoni Fogel's avatar
 
Yoni Fogel committed
2249 2250
    } 
    //Do the actual deleting.
Yoni Fogel's avatar
Yoni Fogel committed
2251
    if (db->i->lt && !(lock_flags&DB_PRELOCKED_WRITE)) {
Yoni Fogel's avatar
Yoni Fogel committed
2252 2253 2254 2255 2256
        DB_TXN* txn_anc = toku_txn_ancestor(txn);
        r = toku_txn_add_lt(txn_anc, db->i->lt);
        if (r!=0) { return r; }
        TXNID id_anc = toku_txn_get_txnid(txn_anc->i->tokutxn);
        r = toku_lt_acquire_range_write_lock(db->i->lt, db, id_anc,
Yoni Fogel's avatar
Yoni Fogel committed
2257 2258 2259 2260
                                             key, toku_lt_neg_infinity,
                                             key, toku_lt_infinity);
        if (r!=0) return r;
    }
2261
    r = toku_brt_delete(db->i->brt, key, txn ? txn->i->tokutxn : 0);
Yoni Fogel's avatar
 
Yoni Fogel committed
2262 2263 2264
    return r;
}

Yoni Fogel's avatar
 
Yoni Fogel committed
2265
static int do_associated_deletes(DB_TXN *txn, DBT *key, DBT *data, DB *secondary) {
2266
    u_int32_t brtflags;
Yoni Fogel's avatar
 
Yoni Fogel committed
2267 2268
    DBT idx;
    memset(&idx, 0, sizeof(idx));
2269
    int r2 = 0;
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2270 2271 2272
    int r = secondary->i->associate_callback(secondary, key, data, &idx);
    if (r==DB_DONOTINDEX) { r = 0; goto clean_up; }
    if (r!=0) goto clean_up;
Yoni Fogel's avatar
 
Yoni Fogel committed
2273 2274
#ifdef DB_DBT_MULTIPLE
    if (idx.flags & DB_DBT_MULTIPLE) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2275 2276
        r = EINVAL; // We aren't ready for this
        goto clean_up;
Yoni Fogel's avatar
 
Yoni Fogel committed
2277 2278
    }
#endif
2279
    toku_brt_get_flags(secondary->i->brt, &brtflags);
Yoni Fogel's avatar
Yoni Fogel committed
2280 2281 2282
    if (brtflags & TOKU_DB_DUPSORT)
        r = toku_db_delboth_noassociate(secondary, txn, &idx, key, DB_DELETE_ANY);
    else 
2283
        r = toku_db_del_noassociate(secondary, txn, &idx, DB_DELETE_ANY);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2284
    clean_up:
Yoni Fogel's avatar
 
Yoni Fogel committed
2285
    if (idx.flags & DB_DBT_APPMALLOC) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2286 2287
        /* This should be free because idx.data is allocated by the user */
    	free(idx.data);
Yoni Fogel's avatar
 
Yoni Fogel committed
2288
    }
2289 2290
    if (r!=0) return r;
    return r2;
Yoni Fogel's avatar
 
Yoni Fogel committed
2291 2292
}

2293
static int toku_c_del(DBC * c, u_int32_t flags) {
Yoni Fogel's avatar
 
Yoni Fogel committed
2294
    int r;
2295
    DB* db = c->dbp;
2296
    HANDLE_PANICKED_DB(db);
Yoni Fogel's avatar
 
Yoni Fogel committed
2297
    
2298
    //It is a primary with secondaries, or is a secondary.
Yoni Fogel's avatar
 
Yoni Fogel committed
2299
    if (db->i->primary != 0 || !list_empty(&db->i->associated)) {
Yoni Fogel's avatar
 
Yoni Fogel committed
2300 2301 2302 2303 2304 2305 2306
        DB* pdb;
        DBT pkey;
        DBT data;
        struct list *h;

        memset(&pkey, 0, sizeof(pkey));
        memset(&data, 0, sizeof(data));
Yoni Fogel's avatar
Yoni Fogel committed
2307 2308
        pkey.flags = DB_DBT_REALLOC;
        data.flags = DB_DBT_REALLOC;
Yoni Fogel's avatar
 
Yoni Fogel committed
2309 2310
        if (db->i->primary == 0) {
            pdb = db;
Rich Prohaska's avatar
Rich Prohaska committed
2311
            r = toku_c_get(c, &pkey, &data, DB_CURRENT);
Yoni Fogel's avatar
Yoni Fogel committed
2312
            if (r != 0) goto assoc_cleanup;
Rich Prohaska's avatar
Rich Prohaska committed
2313
        } else {
Yoni Fogel's avatar
 
Yoni Fogel committed
2314
            DBT skey;
Yoni Fogel's avatar
 
Yoni Fogel committed
2315
            pdb = db->i->primary;
Yoni Fogel's avatar
 
Yoni Fogel committed
2316
            memset(&skey, 0, sizeof(skey));
Yoni Fogel's avatar
Yoni Fogel committed
2317
            skey.flags = DB_DBT_MALLOC;
Yoni Fogel's avatar
 
Yoni Fogel committed
2318
            r = toku_c_pget(c, &skey, &pkey, &data, DB_CURRENT);
Yoni Fogel's avatar
Yoni Fogel committed
2319 2320
            if (r!=0) goto assoc_cleanup;
            if (skey.data) toku_free(skey.data);
Yoni Fogel's avatar
 
Yoni Fogel committed
2321 2322 2323 2324 2325 2326
        }
        
    	for (h = list_head(&pdb->i->associated); h != &pdb->i->associated; h = h->next) {
    	    struct __toku_db_internal *dbi = list_struct(h, struct __toku_db_internal, associated);
    	    if (dbi->db == db) continue;  //Skip current db (if its primary or secondary)
    	    r = do_associated_deletes(c->i->txn, &pkey, &data, dbi->db);
Yoni Fogel's avatar
Yoni Fogel committed
2327
    	    if (r!=0) goto assoc_cleanup;
Yoni Fogel's avatar
 
Yoni Fogel committed
2328 2329 2330
    	}
    	if (db->i->primary != 0) {
    	    //If this is a secondary, we did not delete from the primary.
Yoni Fogel's avatar
 
Yoni Fogel committed
2331 2332
    	    //Primaries cannot have duplicates, (noncursor) del is safe.
    	    r = toku_db_del_noassociate(pdb, c->i->txn, &pkey, DB_DELETE_ANY);
Yoni Fogel's avatar
Yoni Fogel committed
2333
    	    if (r!=0) goto assoc_cleanup;
Yoni Fogel's avatar
 
Yoni Fogel committed
2334
    	}
Yoni Fogel's avatar
Yoni Fogel committed
2335 2336 2337 2338
assoc_cleanup:
        if (pkey.data) toku_free(pkey.data);
        if (data.data) toku_free(data.data);
        if (r!=0) goto cleanup;
Yoni Fogel's avatar
 
Yoni Fogel committed
2339
    }
Yoni Fogel's avatar
 
Yoni Fogel committed
2340
    r = toku_c_del_noassociate(c, flags);
Yoni Fogel's avatar
Yoni Fogel committed
2341 2342 2343
    if (r!=0) goto cleanup;
    r = 0;
cleanup:
Yoni Fogel's avatar
 
Yoni Fogel committed
2344
    return r;    
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2345 2346
}

2347
static int toku_c_put(DBC *dbc, DBT *key, DBT *data, u_int32_t flags) {
2348
    DB* db = dbc->dbp;
2349
    HANDLE_PANICKED_DB(db);
2350 2351 2352 2353 2354 2355
    unsigned int brtflags;
    int r;
    DBT* put_key  = key;
    DBT* put_data = data;
    DBT* get_key  = key;
    DBT* get_data = data;
Yoni Fogel's avatar
Yoni Fogel committed
2356
    DB_TXN* txn = dbc->i->txn;
2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375
    
    //Cannot c_put in a secondary index.
    if (db->i->primary!=0) return EINVAL;
    toku_brt_get_flags(db->i->brt, &brtflags);
    //We do not support duplicates without sorting.
    if (!(brtflags & TOKU_DB_DUPSORT) && (brtflags & TOKU_DB_DUP)) return EINVAL;
    
    if (flags==DB_CURRENT) {
        DBT key_local;
        DBT data_local;
        memset(&key_local, 0, sizeof(DBT));
        memset(&data_local, 0, sizeof(DBT));
        //Can't afford to overwrite the local storage.
        key_local.flags = DB_DBT_MALLOC;
        data_local.flags = DB_DBT_MALLOC;
        r = toku_c_get(dbc, &key_local, &data_local, DB_CURRENT);
        if (0) {
            cleanup:
            if (flags==DB_CURRENT) {
2376 2377
                toku_free(key_local.data);
                toku_free(data_local.data);
2378 2379 2380 2381 2382 2383 2384 2385 2386 2387
            }
            return r;
        }
        if (r==DB_KEYEMPTY) return DB_NOTFOUND;
        if (r!=0) return r;
        if (brtflags & TOKU_DB_DUPSORT) {
            r = db->i->brt->dup_compare(db, &data_local, data);
            if (r!=0) {r = EINVAL; goto cleanup;}
        }
        //Remove old pair.
Yoni Fogel's avatar
Yoni Fogel committed
2388 2389
        if (db->i->lt) {
            /* Acquire all write locks before  */
Yoni Fogel's avatar
Yoni Fogel committed
2390 2391 2392 2393 2394
            DB_TXN* txn_anc = toku_txn_ancestor(txn);
            r = toku_txn_add_lt(txn_anc, db->i->lt);
            if (r!=0) { return r; }
            TXNID id_anc = toku_txn_get_txnid(txn_anc->i->tokutxn);
            r = toku_lt_acquire_write_lock(db->i->lt, db, id_anc,
Yoni Fogel's avatar
Yoni Fogel committed
2395 2396
                                           &key_local, &data_local);
            if (r!=0) goto cleanup;
Yoni Fogel's avatar
Yoni Fogel committed
2397
            r = toku_lt_acquire_write_lock(db->i->lt, db, id_anc,
Yoni Fogel's avatar
Yoni Fogel committed
2398 2399 2400
                                           &key_local, data);
            if (r!=0) goto cleanup;
        }
2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416
        r = toku_c_del(dbc, 0);
        if (r!=0) goto cleanup;
        get_key = put_key  = &key_local;
        goto finish;
    }
    else if (flags==DB_KEYFIRST || flags==DB_KEYLAST) {
        goto finish;        
    }
    else if (flags==DB_NODUPDATA) {
        //Must support sorted duplicates.
        if (!(brtflags & TOKU_DB_DUPSORT)) return EINVAL;
        r = toku_c_get(dbc, key, data, DB_GET_BOTH);
        if (r==0) return DB_KEYEXIST;
        if (r!=DB_NOTFOUND) return r;
        goto finish;
    }
Yoni Fogel's avatar
Yoni Fogel committed
2417
    //Flags must NOT be 0.
2418 2419
    else return EINVAL;
finish:
Rich Prohaska's avatar
Rich Prohaska committed
2420 2421
    //Insert new data with the key we got from c_get
    r = toku_db_put(db, dbc->i->txn, put_key, put_data, DB_YESOVERWRITE); // when doing the put, it should do an overwrite.
2422 2423 2424 2425 2426
    if (r!=0) goto cleanup;
    r = toku_c_get(dbc, get_key, get_data, DB_GET_BOTH);
    goto cleanup;
}

Rich Prohaska's avatar
Rich Prohaska committed
2427
static int locked_c_pget(DBC * c, DBT *key, DBT *pkey, DBT *data, u_int32_t flag) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2428
    toku_ydb_lock(); int r = toku_c_pget(c, key, pkey, data, flag); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
2429 2430 2431
}

static int locked_c_get(DBC * c, DBT * key, DBT * data, u_int32_t flag) {
2432 2433 2434 2435
    //{ 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
2436 2437 2438
}

static int locked_c_close(DBC * c) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2439
    toku_ydb_lock(); int r = toku_c_close(c); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
2440 2441 2442
}

static int locked_c_count(DBC *cursor, db_recno_t *count, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2443
    toku_ydb_lock(); int r = toku_c_count(cursor, count, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
2444 2445 2446
}

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

static int locked_c_put(DBC *dbc, DBT *key, DBT *data, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2451
    toku_ydb_lock(); int r = toku_c_put(dbc, key, data, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
2452 2453
}

2454
static int toku_db_cursor(DB * db, DB_TXN * txn, DBC ** c, u_int32_t flags, int is_temporary_cursor) {
2455
    HANDLE_PANICKED_DB(db);
2456 2457
    if (flags != 0)
        return EINVAL;
2458
    DBC *MALLOC(result);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2459 2460 2461
    if (result == 0)
        return ENOMEM;
    memset(result, 0, sizeof *result);
Yoni Fogel's avatar
Yoni Fogel committed
2462 2463 2464 2465 2466 2467 2468
#define SCRS(name) result->name = locked_ ## name
    SCRS(c_get);
    SCRS(c_pget);
    SCRS(c_put);
    SCRS(c_close);
    SCRS(c_del);
    SCRS(c_count);
Yoni Fogel's avatar
Yoni Fogel committed
2469 2470
    SCRS(c_getf_first);
    SCRS(c_getf_last);
Yoni Fogel's avatar
Yoni Fogel committed
2471
    SCRS(c_getf_next);
Yoni Fogel's avatar
Yoni Fogel committed
2472
    SCRS(c_getf_prev);
Yoni Fogel's avatar
Yoni Fogel committed
2473
    SCRS(c_getf_next_dup);
Yoni Fogel's avatar
Yoni Fogel committed
2474 2475
    SCRS(c_getf_heavi);
#undef SCRS
2476
    MALLOC(result->i);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2477
    assert(result->i);
2478
    result->dbp = db;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
2479
    result->i->txn = txn;
2480
    int r = toku_brt_cursor(db->i->brt, &result->i->c, is_temporary_cursor);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2481
    assert(r == 0);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2482 2483 2484 2485
    *c = result;
    return 0;
}

Rich Prohaska's avatar
Rich Prohaska committed
2486
static int toku_db_del(DB *db, DB_TXN *txn, DBT *key, u_int32_t flags) {
2487
    HANDLE_PANICKED_DB(db);
2488
    int r;
Yoni Fogel's avatar
 
Yoni Fogel committed
2489

Yoni Fogel's avatar
 
Yoni Fogel committed
2490 2491
    //It is a primary with secondaries, or is a secondary.
    if (db->i->primary != 0 || !list_empty(&db->i->associated)) {
Yoni Fogel's avatar
 
Yoni Fogel committed
2492 2493
        DB* pdb;
        DBT data;
Yoni Fogel's avatar
 
Yoni Fogel committed
2494 2495
        DBT pkey;
        DBT *pdb_key;
Yoni Fogel's avatar
 
Yoni Fogel committed
2496
        struct list *h;
2497
        u_int32_t brtflags;
Yoni Fogel's avatar
 
Yoni Fogel committed
2498 2499

        memset(&data, 0, sizeof(data));
Yoni Fogel's avatar
Yoni Fogel committed
2500
        data.flags = DB_DBT_REALLOC;
2501 2502

        toku_brt_get_flags(db->i->brt, &brtflags);
Rich Prohaska's avatar
Rich Prohaska committed
2503
        if (brtflags & TOKU_DB_DUPSORT) {
2504
            int r2;
Yoni Fogel's avatar
Yoni Fogel committed
2505 2506 2507 2508 2509
            DBC *dbc;
            BOOL found = FALSE;
            DBT tmp_key;
            memset(&tmp_key, 0, sizeof(tmp_key));
            tmp_key.flags = DB_DBT_REALLOC;
2510 2511 2512 2513 2514

            /* If we are deleting all copies from a secondary with duplicates,
             * We have to make certain we cascade all the deletes. */

            assert(db->i->primary!=0);    //Primary cannot have duplicates.
2515
            r = toku_db_cursor(db, txn, &dbc, 0, 1);
2516
            if (r!=0) return r;
2517 2518
            r = toku_c_get_noassociate(dbc, key, &data, DB_SET);
            while (r==0) {
Rich Prohaska's avatar
Rich Prohaska committed
2519
                r = toku_c_del(dbc, 0);
Yoni Fogel's avatar
Yoni Fogel committed
2520
                if (r==0) found = TRUE;
2521
                if (r!=0 && r!=DB_KEYEMPTY) break;
Yoni Fogel's avatar
Yoni Fogel committed
2522 2523 2524 2525 2526 2527
                /* key is an input-only parameter.  it can have flags such as
                 * DB_DBT_MALLOC.  If this were the case, we would clobber the
                 * contents of key as well as possibly have a memory leak if we
                 * pass it to toku_c_get_noassociate below.  We use a temporary
                 * junk variable to avoid this. */
                r = toku_c_get_noassociate(dbc, &tmp_key, &data, DB_NEXT_DUP);
2528
                if (r == DB_NOTFOUND) {
Yoni Fogel's avatar
Yoni Fogel committed
2529 2530
                    //If we deleted at least one we're happy.  Quit out.
                    if (found) r = 0;
2531
                    break;
2532 2533
                }
            }
Yoni Fogel's avatar
Yoni Fogel committed
2534 2535
            if (data.data)    toku_free(data.data);
            if (tmp_key.data) toku_free(tmp_key.data);
2536

Rich Prohaska's avatar
Rich Prohaska committed
2537
            r2 = toku_c_close(dbc);
2538 2539 2540 2541
            if (r != 0) return r;
            return r2;
        }

2542 2543 2544 2545 2546 2547 2548 2549
        inline void cleanup() {
            if (data.data) toku_free(data.data);
            if (pkey.data) toku_free(pkey.data);
        }

        memset(&data, 0, sizeof data); data.flags = DB_DBT_REALLOC;
        memset(&pkey, 0, sizeof pkey); pkey.flags = DB_DBT_REALLOC;

Yoni Fogel's avatar
 
Yoni Fogel committed
2550 2551
        if (db->i->primary == 0) {
            pdb = db;
Rich Prohaska's avatar
Rich Prohaska committed
2552
            r = toku_db_get(db, txn, key, &data, 0);
Yoni Fogel's avatar
 
Yoni Fogel committed
2553
            pdb_key = key;
Yoni Fogel's avatar
 
Yoni Fogel committed
2554 2555 2556
        }
        else {
            pdb = db->i->primary;
Rich Prohaska's avatar
Rich Prohaska committed
2557
            r = toku_db_pget(db, txn, key, &pkey, &data, 0);
Yoni Fogel's avatar
 
Yoni Fogel committed
2558
            pdb_key = &pkey;
Yoni Fogel's avatar
 
Yoni Fogel committed
2559
        }
2560 2561 2562
        if (r != 0) { 
            cleanup(); return r; 
        }
Yoni Fogel's avatar
 
Yoni Fogel committed
2563 2564 2565
        
    	for (h = list_head(&pdb->i->associated); h != &pdb->i->associated; h = h->next) {
    	    struct __toku_db_internal *dbi = list_struct(h, struct __toku_db_internal, associated);
Yoni Fogel's avatar
 
Yoni Fogel committed
2566 2567
    	    if (dbi->db == db) continue;                  //Skip current db (if its primary or secondary)
    	    r = do_associated_deletes(txn, pdb_key, &data, dbi->db);
2568 2569 2570
    	    if (r!=0) { 
                cleanup(); return r;
            }
Yoni Fogel's avatar
 
Yoni Fogel committed
2571 2572 2573
    	}
    	if (db->i->primary != 0) {
    	    //If this is a secondary, we did not delete from the primary.
Yoni Fogel's avatar
 
Yoni Fogel committed
2574 2575
    	    //Primaries cannot have duplicates, (noncursor) del is safe.
    	    r = toku_db_del_noassociate(pdb, txn, pdb_key, DB_DELETE_ANY);
2576 2577 2578
    	    if (r!=0) { 
                cleanup(); return r;
            }
Yoni Fogel's avatar
 
Yoni Fogel committed
2579
    	}
2580 2581 2582

        cleanup();

Yoni Fogel's avatar
 
Yoni Fogel committed
2583 2584
    	//We know for certain it was already found, so no need to return DB_NOTFOUND.
    	flags |= DB_DELETE_ANY;
Yoni Fogel's avatar
 
Yoni Fogel committed
2585
    }
Yoni Fogel's avatar
 
Yoni Fogel committed
2586
    r = toku_db_del_noassociate(db, txn, key, flags);
Rich Prohaska's avatar
Rich Prohaska committed
2587
    return r;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2588
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2589

Yoni Fogel's avatar
Yoni Fogel committed
2590 2591 2592 2593 2594 2595
static int toku_db_delboth_noassociate(DB *db, DB_TXN *txn, DBT *key, DBT *val, u_int32_t flags) {
    HANDLE_PANICKED_DB(db);
    int r;

    u_int32_t lock_flags = get_prelocked_flags(flags);
    flags &= ~lock_flags;
2596
    u_int32_t delete_any = flags&DB_DELETE_ANY;
Yoni Fogel's avatar
Yoni Fogel committed
2597 2598 2599 2600
    flags &= ~DB_DELETE_ANY;
    if (flags!=0) return EINVAL;
    //DB_DELETE_ANY supresses the DB_NOTFOUND return value indicating that the key was not found prior to the delete

2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612
    if (delete_any) {
        if (db->i->lt && !(lock_flags&DB_PRELOCKED_WRITE)) {
            DB_TXN* txn_anc = toku_txn_ancestor(txn);
            if ((r = toku_txn_add_lt(txn_anc, db->i->lt))) goto any_cleanup;
            TXNID id_anc = toku_txn_get_txnid(txn_anc->i->tokutxn);
            r = toku_lt_acquire_write_lock(db->i->lt, db, id_anc, key, val);
            if (r!=0) goto any_cleanup;
        }
        r = toku_brt_delete_both(db->i->brt, key, val, txn ? txn->i->tokutxn : NULL);
any_cleanup:
        return r;
    }
Yoni Fogel's avatar
Yoni Fogel committed
2613 2614 2615

    DBC *dbc;
    if ((r = toku_db_cursor(db, txn, &dbc, 0, 0))) goto cursor_cleanup;
2616
    if ((r = toku_c_get_noassociate(dbc, key, val, DB_GET_BOTH))) goto cursor_cleanup;
Yoni Fogel's avatar
Yoni Fogel committed
2617
    r = toku_c_del_noassociate(dbc, lock_flags);
Yoni Fogel's avatar
Yoni Fogel committed
2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635
cursor_cleanup:;
    int r2 = toku_c_close(dbc);
    return r ? r : r2;
}

static int toku_db_delboth(DB *db, DB_TXN *txn, DBT *key, DBT *val, u_int32_t flags) {
    HANDLE_PANICKED_DB(db);

    //It is a primary with secondaries, or is a secondary.
    if (db->i->primary != 0 || !list_empty(&db->i->associated)) {
        //Not yet supported.
        return ENOSYS;
    }
    else {
        return toku_db_delboth_noassociate(db, txn, key, val, flags);
    }
}

Rich Prohaska's avatar
Rich Prohaska committed
2636 2637 2638 2639
static inline int db_thread_need_flags(DBT *dbt) {
    return (dbt->flags & (DB_DBT_MALLOC+DB_DBT_REALLOC+DB_DBT_USERMEM)) == 0;
}

2640
static int toku_db_get (DB * db, DB_TXN * txn, DBT * key, DBT * data, u_int32_t flags) {
2641
    HANDLE_PANICKED_DB(db);
Yoni Fogel's avatar
Yoni Fogel committed
2642
    int r;
2643

Rich Prohaska's avatar
Rich Prohaska committed
2644
    if ((db->i->open_flags & DB_THREAD) && db_thread_need_flags(data))
2645 2646
        return EINVAL;

Yoni Fogel's avatar
Yoni Fogel committed
2647 2648
    u_int32_t lock_flags = get_prelocked_flags(flags);
    flags &= ~lock_flags;
Yoni Fogel's avatar
Yoni Fogel committed
2649 2650 2651 2652
    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;
2653
    r = toku_db_cursor(db, txn, &dbc, 0, 1);
Yoni Fogel's avatar
Yoni Fogel committed
2654
    if (r!=0) return r;
Yoni Fogel's avatar
Yoni Fogel committed
2655 2656
    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
2657 2658
    int r2 = toku_c_close(dbc);
    return r ? r : r2;
2659 2660 2661
}

static int toku_db_pget (DB *db, DB_TXN *txn, DBT *key, DBT *pkey, DBT *data, u_int32_t flags) {
2662
    HANDLE_PANICKED_DB(db);
2663
    int r;
2664 2665
    int r2;
    DBC *dbc;
2666 2667
    if (!db->i->primary) return EINVAL; // pget doesn't work on a primary.
    assert(flags==0); // not ready to handle all those other options
Rich Prohaska's avatar
Rich Prohaska committed
2668
    assert(db->i->brt != db->i->primary->i->brt); // Make sure they realy are different trees.
2669
    assert(db!=db->i->primary);
2670

Rich Prohaska's avatar
Rich Prohaska committed
2671 2672 2673
    if ((db->i->open_flags & DB_THREAD) && (db_thread_need_flags(pkey) || db_thread_need_flags(data)))
        return EINVAL;

2674
    r = toku_db_cursor(db, txn, &dbc, 0, 1);
2675
    if (r!=0) return r;
Rich Prohaska's avatar
Rich Prohaska committed
2676
    r = toku_c_pget(dbc, key, pkey, data, DB_SET);
Yoni Fogel's avatar
Yoni Fogel committed
2677
    if (r==DB_KEYEMPTY) r = DB_NOTFOUND;
Rich Prohaska's avatar
Rich Prohaska committed
2678
    r2 = toku_c_close(dbc);
2679 2680
    if (r!=0) return r;
    return r2;    
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2681 2682
}

Rich Prohaska's avatar
Rich Prohaska committed
2683
#if 0
2684
static int toku_db_key_range(DB * db, DB_TXN * txn, DBT * dbt, DB_KEY_RANGE * kr, u_int32_t flags) {
2685 2686
    HANDLE_PANICKED_DB(db);
    txn=txn; dbt=dbt; kr=kr; flags=flags;
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2687
    toku_ydb_barf();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2688
    abort();
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2689
}
Rich Prohaska's avatar
Rich Prohaska committed
2690
#endif
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2691

Yoni Fogel's avatar
Yoni Fogel committed
2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711
static int construct_full_name_in_buf(const char *dir, const char *fname, char* full, int length) {
    int l;

    if (!full) return EINVAL;
    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;
        }
    }
    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
2712 2713 2714
static char *construct_full_name(const char *dir, const char *fname) {
    if (fname[0] == '/')
        dir = "";
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2715
    {
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2716 2717 2718 2719
        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
2720 2721 2722 2723
        // 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
2724 2725
        }
        return result;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2726 2727 2728
    }
}

2729
static int find_db_file(DB_ENV* dbenv, const char *fname, char** full_name_out) {
Yoni Fogel's avatar
Yoni Fogel committed
2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744
    u_int32_t i;
    int r;
    struct stat statbuf;
    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;
            r = stat(full_name, &statbuf);
            if (r == 0) goto finish;
            else {
                toku_free(full_name);
Rich Prohaska's avatar
Rich Prohaska committed
2745
                r = errno;
Yoni Fogel's avatar
Yoni Fogel committed
2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762
                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
2763 2764 2765 2766
static int toku_db_lt_panic(DB* db, int r) {
    assert(db && db->i && db->dbenv && db->dbenv->i);
    DB_ENV* env = db->dbenv;
    env->i->is_panicked = 1;
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2767 2768
    if (r < 0) toku_ydb_do_error(env, 0, toku_lt_strerror(r));
    else       toku_ydb_do_error(env, r, "Error in locktree.\n");
Yoni Fogel's avatar
Yoni Fogel committed
2769 2770 2771
    return EINVAL;
}

Yoni Fogel's avatar
Yoni Fogel committed
2772
static int toku_txn_add_lt(DB_TXN* txn, toku_lock_tree* lt) {
Yoni Fogel's avatar
Yoni Fogel committed
2773
    int r = ENOSYS;
Yoni Fogel's avatar
Yoni Fogel committed
2774 2775 2776 2777 2778 2779 2780
    assert(txn && lt);
    toku_lth* lth = txn->i->lth;
    assert(lth);

    toku_lock_tree* find = toku_lth_find(lth, lt);
    if (find) {
        assert(find == lt);
Yoni Fogel's avatar
Yoni Fogel committed
2781 2782
        r = 0;
        goto cleanup;
Yoni Fogel's avatar
Yoni Fogel committed
2783
    }
Yoni Fogel's avatar
Yoni Fogel committed
2784 2785 2786 2787 2788 2789
    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
2790 2791 2792
    return r;
}

Yoni Fogel's avatar
Yoni Fogel committed
2793 2794 2795
static toku_dbt_cmp toku_db_get_compare_fun(DB* db) {
    return db->i->brt->compare_fun;
}
Yoni Fogel's avatar
Yoni Fogel committed
2796

Yoni Fogel's avatar
Yoni Fogel committed
2797 2798
static toku_dbt_cmp toku_db_get_dup_compare(DB* db) {
    return db->i->brt->dup_compare;
Yoni Fogel's avatar
Yoni Fogel committed
2799 2800
}

2801
static int toku_db_open(DB * db, DB_TXN * txn, const char *fname, const char *dbname, DBTYPE dbtype, u_int32_t flags, int mode) {
2802
    HANDLE_PANICKED_DB(db);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2803
    // Warning.  Should check arguments.  Should check return codes on malloc and open and so forth.
Yoni Fogel's avatar
Yoni Fogel committed
2804 2805
    BOOL need_locktree = (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
2806

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2807
    int openflags = 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2808
    int r;
Yoni Fogel's avatar
Yoni Fogel committed
2809
    if (dbtype!=DB_BTREE && dbtype!=DB_UNKNOWN) return EINVAL;
2810 2811 2812
    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;
2813
    if (dbtype != DB_UNKNOWN && dbtype != DB_BTREE) return EINVAL;
2814
    if (flags & ~DB_THREAD) return EINVAL; // unknown flags
2815 2816 2817

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

2819 2820 2821 2822 2823 2824 2825 2826
    /* 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;

2827
    if (db_opened(db))
2828
        return EINVAL;              /* It was already open. */
Yoni Fogel's avatar
Yoni Fogel committed
2829 2830 2831
    
    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
2832
    // printf("Full name = %s\n", db->i->full_fname);
2833 2834 2835 2836 2837 2838
    assert(db->i->fname == 0);
    db->i->fname = toku_strdup(fname);
    if (db->i->fname == 0) { 
        r = ENOMEM; goto error_cleanup;
    }
    assert(db->i->database_name == 0);
Yoni Fogel's avatar
Yoni Fogel committed
2839
    db->i->database_name = toku_strdup(dbname ? dbname : "");
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2840
    if (db->i->database_name == 0) {
2841
        r = ENOMEM; goto error_cleanup;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2842
    }
2843
    if (is_db_rdonly)
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2844 2845 2846
        openflags |= O_RDONLY;
    else
        openflags |= O_RDWR;
2847
    
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2848
    {
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2849 2850 2851
        struct stat statbuf;
        if (stat(db->i->full_fname, &statbuf) == 0) {
            /* If the database exists at the file level, and we specified no db_name, then complain here. */
2852 2853
            if (dbname == 0 && is_db_create) {
                if (is_db_excl) {
2854 2855 2856
                    r = EEXIST;
                    goto error_cleanup;
                }
2857
		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
2858 2859
            }
        } else {
2860
            if (!is_db_create) {
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2861 2862 2863 2864
                r = ENOENT;
                goto error_cleanup;
            }
        }
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2865
    }
2866
    if (is_db_create) openflags |= O_CREAT;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2867 2868 2869

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

Yoni Fogel's avatar
Yoni Fogel committed
2871

2872
    r = toku_brt_open(db->i->brt, db->i->full_fname, fname, dbname,
2873
		      is_db_create, is_db_excl,
2874
		      db->dbenv->i->cachetable,
2875 2876
		      txn ? txn->i->tokutxn : NULL_TXN,
		      db);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2877 2878 2879
    if (r != 0)
        goto error_cleanup;

Yoni Fogel's avatar
Yoni Fogel committed
2880
    if (need_locktree) {
Yoni Fogel's avatar
Yoni Fogel committed
2881 2882 2883 2884
        unsigned int brtflags;
        BOOL dups;
        toku_brt_get_flags(db->i->brt, &brtflags);
        dups = (brtflags & TOKU_DB_DUPSORT || brtflags & TOKU_DB_DUP);
Yoni Fogel's avatar
Yoni Fogel committed
2885 2886 2887 2888 2889 2890

        r = toku_db_id_create(&db->i->db_id, db->i->full_fname,
                              db->i->database_name);
        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
2891
    }
Yoni Fogel's avatar
Yoni Fogel committed
2892

Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2893
    return 0;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2894 2895
 
error_cleanup:
Yoni Fogel's avatar
Yoni Fogel committed
2896 2897 2898 2899
    if (db->i->db_id) {
        toku_db_id_remove_ref(db->i->db_id);
        db->i->db_id = NULL;
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2900 2901 2902 2903 2904 2905 2906 2907
    if (db->i->database_name) {
        toku_free(db->i->database_name);
        db->i->database_name = NULL;
    }
    if (db->i->full_fname) {
        toku_free(db->i->full_fname);
        db->i->full_fname = NULL;
    }
2908 2909 2910 2911
    if(db->i->fname) {
        toku_free(db->i->fname);
        db->i->fname = NULL;
    }
Yoni Fogel's avatar
Yoni Fogel committed
2912
    if (db->i->lt) {
Yoni Fogel's avatar
Yoni Fogel committed
2913
        toku_lt_remove_ref(db->i->lt);
Yoni Fogel's avatar
Yoni Fogel committed
2914 2915
        db->i->lt = NULL;
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2916
    return r;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2917
}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
2918

2919 2920
static int toku_db_put_noassociate(DB * db, DB_TXN * txn, DBT * key, DBT * data, u_int32_t flags) {
    int r;
2921

2922
    unsigned int brtflags;
2923
    r = toku_brt_get_flags(db->i->brt, &brtflags); assert(r == 0);
2924 2925 2926

    /* limit the size of key and data */
    unsigned int nodesize;
2927 2928 2929 2930 2931 2932 2933 2934
    r = toku_brt_get_nodesize(db->i->brt, &nodesize); assert(r == 0);
    if (brtflags & TOKU_DB_DUPSORT) {
        unsigned int limit = nodesize / (2*BRT_FANOUT-1);
        if (key->size + data->size >= limit)
            return EINVAL;
    } else {
        unsigned int limit = nodesize / (3*BRT_FANOUT-1);
        if (key->size >= limit || data->size >= limit)
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2935
            return toku_ydb_do_error(db->dbenv, EINVAL, "The largest key or data item allowed is %d bytes", limit);
2936
    }
Yoni Fogel's avatar
Yoni Fogel committed
2937 2938
    u_int32_t lock_flags = get_prelocked_flags(flags);
    flags &= ~lock_flags;
2939 2940 2941 2942 2943 2944 2945

    if (flags == DB_YESOVERWRITE) {
        /* tokudb does insert or replace */
        ;
    } else if (flags == DB_NOOVERWRITE) {
        /* check if the key already exists */
        DBT testfordata;
Yoni Fogel's avatar
Yoni Fogel committed
2946 2947
        memset(&testfordata, 0, sizeof(testfordata));
        testfordata.flags = DB_DBT_MALLOC;
Yoni Fogel's avatar
Yoni Fogel committed
2948
        r = toku_db_get_noassociate(db, txn, key, &testfordata, lock_flags);
Yoni Fogel's avatar
Yoni Fogel committed
2949 2950
        if (r == 0) {
            if (testfordata.data) toku_free(testfordata.data);
2951
            return DB_KEYEXIST;
Yoni Fogel's avatar
Yoni Fogel committed
2952
        }
Yoni Fogel's avatar
Yoni Fogel committed
2953
        if (r != DB_NOTFOUND) return r;
2954 2955 2956 2957
    } else if (flags != 0) {
        /* no other flags are currently supported */
        return EINVAL;
    } else {
2958
        assert(flags == 0);
2959
        if (brtflags & TOKU_DB_DUPSORT) {
2960
#if TDB_EQ_BDB
Yoni Fogel's avatar
Yoni Fogel committed
2961
            r = toku_db_get_noassociate(db, txn, key, data, DB_GET_BOTH | lock_flags);
2962 2963
            if (r == 0)
                return DB_KEYEXIST;
Yoni Fogel's avatar
Yoni Fogel committed
2964
            if (r != DB_NOTFOUND) return r;
2965
#else
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2966
	    return toku_ydb_do_error(db->dbenv, EINVAL, "Tokudb requires that db->put specify DB_YESOVERWRITE or DB_NOOVERWRITE on DB_DUPSORT databases");
2967
#endif
2968 2969
        }
    }
Yoni Fogel's avatar
Yoni Fogel committed
2970
    if (db->i->lt && !(lock_flags&DB_PRELOCKED_WRITE)) {
Yoni Fogel's avatar
Yoni Fogel committed
2971 2972 2973 2974 2975
        DB_TXN* txn_anc = toku_txn_ancestor(txn);
        r = toku_txn_add_lt(txn_anc, db->i->lt);
        if (r!=0) { return r; }
        TXNID id_anc = toku_txn_get_txnid(txn_anc->i->tokutxn);
        r = toku_lt_acquire_write_lock(db->i->lt, db, id_anc, key, data);
Yoni Fogel's avatar
Yoni Fogel committed
2976 2977
        if (r!=0) return r;
    }
2978 2979 2980 2981 2982
    r = toku_brt_insert(db->i->brt, key, data, txn ? txn->i->tokutxn : 0);
    //printf("%s:%d %d=__toku_db_put(...)\n", __FILE__, __LINE__, r);
    return r;
}

2983 2984 2985 2986
static int do_associated_inserts (DB_TXN *txn, DBT *key, DBT *data, DB *secondary) {
    DBT idx;
    memset(&idx, 0, sizeof(idx));
    int r = secondary->i->associate_callback(secondary, key, data, &idx);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2987 2988
    if (r==DB_DONOTINDEX) { r = 0; goto clean_up; }
    if (r != 0) goto clean_up;
2989 2990 2991 2992 2993
#ifdef DB_DBT_MULTIPLE
    if (idx.flags & DB_DBT_MULTIPLE) {
	return EINVAL; // We aren't ready for this
    }
#endif
2994
    r = toku_db_put_noassociate(secondary, txn, &idx, key, DB_YESOVERWRITE);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2995
    clean_up:
2996
    if (idx.flags & DB_DBT_APPMALLOC) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2997 2998
        /* This should be free because idx.data is allocated by the user */
        free(idx.data);
2999 3000 3001 3002
    }
    return r;
}

3003
static int toku_db_put(DB * db, DB_TXN * txn, DBT * key, DBT * data, u_int32_t flags) {
3004
    HANDLE_PANICKED_DB(db);
3005 3006
    int r;

3007
    //Cannot put directly into a secondary.
3008
    if (db->i->primary != 0) return EINVAL;
3009

3010
    r = toku_db_put_noassociate(db, txn, key, data, flags);
3011 3012
    if (r!=0) return r;
    // For each secondary add the relevant records.
Yoni Fogel's avatar
 
Yoni Fogel committed
3013 3014 3015 3016 3017 3018 3019
    assert(db->i->primary==0);
    // Only do it if it is a primary.   This loop would run an unknown number of times if we tried it on a secondary.
    struct list *h;
    for (h=list_head(&db->i->associated); h!=&db->i->associated; h=h->next) {
        struct __toku_db_internal *dbi=list_struct(h, struct __toku_db_internal, associated);
        r=do_associated_inserts(txn, key, data, dbi->db);
        if (r!=0) return r;
3020 3021
    }
    return 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3022
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3023

3024
static int toku_db_remove(DB * db, const char *fname, const char *dbname, u_int32_t flags) {
3025
    HANDLE_PANICKED_DB(db);
Yoni Fogel's avatar
Yoni Fogel committed
3026 3027 3028 3029 3030 3031
    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
3032 3033

    //TODO: Verify DB* db not yet opened
Yoni Fogel's avatar
Yoni Fogel committed
3034
    //TODO: Verify db file not in use. (all dbs in the file must be unused)
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3035
    r = toku_db_open(db, NULL, fname, dbname, DB_UNKNOWN, 0, 0777);
Yoni Fogel's avatar
Yoni Fogel committed
3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048
    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
3049 3050 3051
    if (dbname) {
        //TODO: Verify the target db is not open
        //TODO: Use master database (instead of manual edit) when implemented.
3052
        r = toku_brt_remove_subdb(db->i->brt, dbname, flags);
Yoni Fogel's avatar
Yoni Fogel committed
3053
        if (r!=0) { goto cleanup; }
Yoni Fogel's avatar
Yoni Fogel committed
3054
    }
Yoni Fogel's avatar
Yoni Fogel committed
3055 3056 3057 3058
    if (!dbname) {
        r = find_db_file(db->dbenv, fname, &full_name);
        if (r!=0) { goto cleanup; }
        assert(full_name);
3059 3060 3061
	r = toku_db_close(db, 0);
	need_close = FALSE;
	if (r!=0) { goto cleanup; }
Yoni Fogel's avatar
Yoni Fogel committed
3062
        if (unlink(full_name) != 0) { r = errno; goto cleanup; }
3063 3064 3065 3066
    } else {
	r = toku_db_close(db, 0);
	need_close = FALSE;
	if (r!=0) { goto cleanup; }
3067
    }
3068

Yoni Fogel's avatar
Yoni Fogel committed
3069 3070 3071 3072 3073 3074 3075
    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); }
    if (db_id)      { toku_db_id_remove_ref(db_id); }
Yoni Fogel's avatar
Yoni Fogel committed
3076
    return r ? r : r2;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3077
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3078

Yoni Fogel's avatar
Yoni Fogel committed
3079 3080 3081 3082 3083 3084 3085 3086 3087
/* 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).
*/
3088
static int toku_db_rename(DB * db, const char *namea, const char *nameb, const char *namec, u_int32_t flags) {
3089
    HANDLE_PANICKED_DB(db);
3090
    if (flags!=0) return EINVAL;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
3091 3092
    char afull[PATH_MAX], cfull[PATH_MAX];
    int r;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3093 3094 3095 3096 3097
    assert(nameb == 0);
    r = snprintf(afull, PATH_MAX, "%s%s", db->dbenv->i->dir, namea);
    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
3098
    return rename(afull, cfull);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3099
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3100

3101
static int toku_db_set_bt_compare(DB * db, int (*bt_compare) (DB *, const DBT *, const DBT *)) {
3102
    HANDLE_PANICKED_DB(db);
3103
    int r = toku_brt_set_bt_compare(db->i->brt, bt_compare);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3104 3105 3106
    return r;
}

3107
static int toku_db_set_dup_compare(DB *db, int (*dup_compare)(DB *, const DBT *, const DBT *)) {
3108
    HANDLE_PANICKED_DB(db);
3109
    int r = toku_brt_set_dup_compare(db->i->brt, dup_compare);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3110 3111 3112
    return r;
}

Rich Prohaska's avatar
Rich Prohaska committed
3113
static int toku_db_set_flags(DB *db, u_int32_t flags) {
3114
    HANDLE_PANICKED_DB(db);
3115

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

Yoni Fogel's avatar
Yoni Fogel committed
3119 3120 3121 3122
    u_int32_t tflags;
    int r = toku_brt_get_flags(db->i->brt, &tflags);
    if (r!=0) return r;
    
3123 3124 3125 3126
    if (flags & DB_DUP)
        tflags += TOKU_DB_DUP;
    if (flags & DB_DUPSORT)
        tflags += TOKU_DB_DUPSORT;
Yoni Fogel's avatar
Yoni Fogel committed
3127
    r = toku_brt_set_flags(db->i->brt, tflags);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3128 3129 3130
    return r;
}

3131
static int toku_db_get_flags(DB *db, u_int32_t *pflags) {
3132
    HANDLE_PANICKED_DB(db);
3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150
    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;
}

3151
static int toku_db_set_pagesize(DB *db, u_int32_t pagesize) {
3152
    HANDLE_PANICKED_DB(db);
3153
    int r = toku_brt_set_nodesize(db->i->brt, pagesize);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3154
    return r;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
3155
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3156

Rich Prohaska's avatar
Rich Prohaska committed
3157
#if 0
3158
static int toku_db_stat(DB * db, void *v, u_int32_t flags) {
3159 3160
    HANDLE_PANICKED_DB(db);
    v=v; flags=flags;
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3161
    toku_ydb_barf();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3162 3163
    abort();
}
Rich Prohaska's avatar
Rich Prohaska committed
3164
#endif
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3165

Rich Prohaska's avatar
Rich Prohaska committed
3166 3167 3168 3169 3170 3171
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);
}

Yoni Fogel's avatar
Yoni Fogel committed
3172
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
3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186
    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;
}

Yoni Fogel's avatar
Yoni Fogel committed
3187
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
3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201
    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;
    TXNID id_anc = toku_txn_get_txnid(txn_anc->i->tokutxn);

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

Yoni Fogel's avatar
Yoni Fogel committed
3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215
int toku_db_pre_acquire_table_lock(DB *db, DB_TXN *txn) {
    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;
    TXNID id_anc = toku_txn_get_txnid(txn_anc->i->tokutxn);

    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);
    return r;
}
Zardosht Kasheff's avatar
Zardosht Kasheff committed
3216

Yoni Fogel's avatar
Yoni Fogel committed
3217 3218 3219
//TODO: DB_AUTO_COMMIT.
//TODO: Nowait only conditionally?
//TODO: NOSYNC change to SYNC if DB_ENV has something in set_flags
3220
static inline int toku_db_construct_autotxn(DB* db, DB_TXN **txn, BOOL* changed,
Yoni Fogel's avatar
Yoni Fogel committed
3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235
                                            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;
    }
    BOOL nosync = !force_auto_commit && !(env->i->open_flags & DB_AUTO_COMMIT);
    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;
}

3236
static inline int toku_db_destruct_autotxn(DB_TXN *txn, int r, BOOL changed) {
Yoni Fogel's avatar
Yoni Fogel committed
3237 3238 3239 3240 3241 3242
    if (!changed) return r;
    if (r==0) return toku_txn_commit(txn, 0);
    toku_txn_abort(txn);
    return r; 
}

3243
static inline int autotxn_db_associate(DB *primary, DB_TXN *txn, DB *secondary,
Yoni Fogel's avatar
Yoni Fogel committed
3244 3245 3246 3247 3248 3249 3250 3251
                                       int (*callback)(DB *secondary, const DBT *key, const DBT *data, DBT *result), u_int32_t flags) {
    BOOL changed; int r;
    r = toku_db_construct_autotxn(primary, &txn, &changed, FALSE);
    if (r!=0) return r;
    r = toku_db_associate(primary, txn, secondary, callback, flags);
    return toku_db_destruct_autotxn(txn, r, changed);
}

Rich Prohaska's avatar
Rich Prohaska committed
3252 3253
static int locked_db_associate (DB *primary, DB_TXN *txn, DB *secondary,
                                int (*callback)(DB *secondary, const DBT *key, const DBT *data, DBT *result), u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3254
    toku_ydb_lock(); int r = autotxn_db_associate(primary, txn, secondary, callback, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
3255 3256 3257
}

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

3261
static inline int autotxn_db_cursor(DB *db, DB_TXN *txn, DBC **c, u_int32_t flags) {
Yoni Fogel's avatar
Yoni Fogel committed
3262
    if (!txn && (db->dbenv->i->open_flags & DB_INIT_TXN)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3263
        return toku_ydb_do_error(db->dbenv, EINVAL,
Yoni Fogel's avatar
Yoni Fogel committed
3264 3265
              "Cursors in a transaction environment must have transactions.\n");
    }
3266
    return toku_db_cursor(db, txn, c, flags, 0);
Yoni Fogel's avatar
Yoni Fogel committed
3267 3268
}

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

3273
static inline int autotxn_db_del(DB* db, DB_TXN* txn, DBT* key,
Yoni Fogel's avatar
Yoni Fogel committed
3274 3275 3276 3277 3278 3279 3280 3281
                                 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
3282
static int locked_db_del(DB * db, DB_TXN * txn, DBT * key, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3283
    toku_ydb_lock(); int r = autotxn_db_del(db, txn, key, flags); toku_ydb_unlock(); return r;
Yoni Fogel's avatar
Yoni Fogel committed
3284 3285
}

Yoni Fogel's avatar
Yoni Fogel committed
3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298
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;
}

3299
static inline int autotxn_db_get(DB* db, DB_TXN* txn, DBT* key, DBT* data,
Yoni Fogel's avatar
Yoni Fogel committed
3300 3301 3302 3303 3304 3305
                                 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
3306 3307 3308
}

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
3309
    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
3310 3311
}

Yoni Fogel's avatar
Yoni Fogel committed
3312
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
3313 3314 3315 3316 3317 3318
    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;
}

Yoni Fogel's avatar
Yoni Fogel committed
3319 3320 3321 3322 3323 3324 3325
int locked_db_pre_acquire_table_lock(DB *db, DB_TXN *txn) {
    toku_ydb_lock();
    int r = toku_db_pre_acquire_table_lock(db, txn);
    toku_ydb_unlock();
    return r;
}

3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370
// 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;
    // dont support sub databases (yet)
    if (db->i->database_name != 0 && strcmp(db->i->database_name, "") != 0)
        return EINVAL;
    // dont support associated databases (yet)
    if (!list_empty(&db->i->associated))
        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;

    // flush the cached tree blocks
    r = toku_brt_flush(db->i->brt);
    if (r != 0) 
        return r;

    // rename the db file and log the rename operation (for now, just unlink the file)
    r = unlink(db->i->full_fname);
    if (r == -1) 
        r = errno;
    if (r != 0) 
        return r;

    // reopen the new db file
    r = toku_brt_reopen(db->i->brt, db->i->full_fname, db->i->fname, txn ? txn->i->tokutxn : NULL_TXN);
    return r;
}

3371
static inline int autotxn_db_pget(DB* db, DB_TXN* txn, DBT* key, DBT* pkey,
Yoni Fogel's avatar
Yoni Fogel committed
3372 3373 3374 3375 3376 3377
                                  DBT* data, 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_pget(db, txn, key, pkey, data, flags);
    return toku_db_destruct_autotxn(txn, r, changed);
Rich Prohaska's avatar
Rich Prohaska committed
3378 3379 3380
}

static int locked_db_pget (DB *db, DB_TXN *txn, DBT *key, DBT *pkey, DBT *data, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3381
    toku_ydb_lock(); int r = autotxn_db_pget(db, txn, key, pkey, data, flags); toku_ydb_unlock(); return r;
Yoni Fogel's avatar
Yoni Fogel committed
3382 3383
}

3384
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
3385 3386 3387 3388 3389
    BOOL changed; int r;
    r = toku_db_construct_autotxn(db, &txn, &changed, flags & DB_AUTO_COMMIT);
    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
3390 3391 3392
}

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
3393
    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
3394 3395
}

3396
static inline int autotxn_db_put(DB* db, DB_TXN* txn, DBT* key, DBT* data,
Yoni Fogel's avatar
Yoni Fogel committed
3397
                                 u_int32_t flags) {
3398
    //{ 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
3399 3400 3401 3402 3403 3404 3405
    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
3406
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
3407
    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
3408 3409 3410
}

static int locked_db_remove(DB * db, const char *fname, const char *dbname, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3411
    toku_ydb_lock(); int r = toku_db_remove(db, fname, dbname, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
3412 3413 3414
}

static int locked_db_rename(DB * db, const char *namea, const char *nameb, const char *namec, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3415
    toku_ydb_lock(); int r = toku_db_rename(db, namea, nameb, namec, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
3416 3417 3418
}

static int locked_db_set_bt_compare(DB * db, int (*bt_compare) (DB *, const DBT *, const DBT *)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3419
    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
3420 3421 3422
}

static int locked_db_set_dup_compare(DB * db, int (*dup_compare) (DB *, const DBT *, const DBT *)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3423
    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
3424 3425 3426 3427 3428 3429 3430
}

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
3431
    toku_ydb_lock(); int r = toku_db_set_flags(db, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
3432 3433 3434
}

static int locked_db_get_flags(DB *db, u_int32_t *flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3435
    toku_ydb_lock(); int r = toku_db_get_flags(db, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
3436 3437 3438
}

static int locked_db_set_pagesize(DB *db, u_int32_t pagesize) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3439
    toku_ydb_lock(); int r = toku_db_set_pagesize(db, pagesize); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
3440 3441 3442
}

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

Zardosht Kasheff's avatar
Zardosht Kasheff committed
3446

Yoni Fogel's avatar
Yoni Fogel committed
3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458
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
3459 3460
}

3461 3462 3463 3464 3465
static int locked_db_truncate(DB *db, DB_TXN *txn, u_int32_t *row_count, u_int32_t flags) {
    toku_ydb_lock(); int r = toku_db_truncate(db, txn, row_count, flags); toku_ydb_unlock(); return r\
                                                                                                 ;
}

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

3469 3470
    if (flags) return EINVAL;

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3471 3472 3473
    /* if the env already exists then add a ref to it
       otherwise create one */
    if (env) {
Rich Prohaska's avatar
Rich Prohaska committed
3474
        if (!env_opened(env))
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3475
            return EINVAL;
Rich Prohaska's avatar
Rich Prohaska committed
3476
        env_add_ref(env);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3477
    } else {
Rich Prohaska's avatar
Rich Prohaska committed
3478
        r = toku_env_create(&env, 0);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3479 3480
        if (r != 0)
            return r;
Rich Prohaska's avatar
Rich Prohaska committed
3481
        r = toku_env_open(env, ".", DB_PRIVATE + DB_INIT_MPOOL, 0);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3482
        if (r != 0) {
Rich Prohaska's avatar
Rich Prohaska committed
3483
            toku_env_close(env, 0);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3484 3485
            return r;
        }
Rich Prohaska's avatar
Rich Prohaska committed
3486
        assert(env_opened(env));
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
3487
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3488
    
3489
    DB *MALLOC(result);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3490
    if (result == 0) {
Rich Prohaska's avatar
Rich Prohaska committed
3491
        env_unref(env);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3492
        return ENOMEM;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
3493
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3494 3495
    memset(result, 0, sizeof *result);
    result->dbenv = env;
Yoni Fogel's avatar
Yoni Fogel committed
3496 3497 3498 3499 3500 3501
#define SDB(name) result->name = locked_db_ ## name
    SDB(key_range64);
    SDB(associate);
    SDB(close);
    SDB(cursor);
    SDB(del);
Yoni Fogel's avatar
Yoni Fogel committed
3502
    SDB(delboth);
Yoni Fogel's avatar
Yoni Fogel committed
3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518
    SDB(get);
    //    SDB(key_range);
    SDB(open);
    SDB(pget);
    SDB(put);
    SDB(remove);
    SDB(rename);
    SDB(set_bt_compare);
    SDB(set_dup_compare);
    SDB(set_errfile);
    SDB(set_pagesize);
    SDB(set_flags);
    SDB(get_flags);
    //    SDB(stat);
    SDB(fd);
    SDB(pre_acquire_read_lock);
Yoni Fogel's avatar
Yoni Fogel committed
3519
    SDB(pre_acquire_table_lock);
3520
    SDB(truncate);
Yoni Fogel's avatar
Yoni Fogel committed
3521 3522 3523
#undef SDB
    result->dbt_pos_infty = toku_db_dbt_pos_infty;
    result->dbt_neg_infty = toku_db_dbt_neg_infty;
3524
    MALLOC(result->i);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3525 3526
    if (result->i == 0) {
        toku_free(result);
Rich Prohaska's avatar
Rich Prohaska committed
3527
        env_unref(env);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3528 3529 3530
        return ENOMEM;
    }
    memset(result->i, 0, sizeof *result->i);
3531
    result->i->db = result;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3532 3533 3534 3535 3536 3537 3538 3539
    result->i->freed = 0;
    result->i->header = 0;
    result->i->database_number = 0;
    result->i->full_fname = 0;
    result->i->database_name = 0;
    result->i->open_flags = 0;
    result->i->open_mode = 0;
    result->i->brt = 0;
3540 3541 3542
    list_init(&result->i->associated);
    result->i->primary = 0;
    result->i->associate_callback = 0;
3543
    r = toku_brt_create(&result->i->brt);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3544 3545 3546
    if (r != 0) {
        toku_free(result->i);
        toku_free(result);
Rich Prohaska's avatar
Rich Prohaska committed
3547
        env_unref(env);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3548 3549
        return ENOMEM;
    }
3550
    ydb_add_ref();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3551 3552
    *db = result;
    return 0;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
3553
}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
3554

3555
int DB_CREATE_FUN (DB ** db, DB_ENV * env, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
3556
    toku_ydb_lock(); int r = toku_db_create(db, env, flags); toku_ydb_unlock(); return r;
Rich Prohaska's avatar
Rich Prohaska committed
3557 3558 3559 3560
}

/* need db_strerror_r for multiple threads */

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
3561 3562 3563 3564 3565 3566 3567 3568
char *db_strerror(int error) {
    char *errorstr;
    if (error >= 0) {
        errorstr = strerror(error);
        if (errorstr)
            return errorstr;
    }
    
3569 3570 3571
    if (error==DB_BADFORMAT) {
	return "Database Bad Format (probably a corrupted database)";
    }
3572 3573 3574
    if (error==DB_NOTFOUND) {
	return "Not found";
    }
3575

Rich Prohaska's avatar
Rich Prohaska committed
3576
    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
3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588
    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;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
3589 3590
    return DB_VERSION_STRING;
}
3591 3592 3593 3594
 
int db_env_set_func_fsync (int (*fsync_function)(int)) {
    return toku_set_func_fsync(fsync_function);
}
Yoni Fogel's avatar
Yoni Fogel committed
3595