ydb.c 97.7 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;
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);
64 65

static inline void env_add_ref(DB_ENV *env) {
66
    ++env->i->ref_count;
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);
89 90 91 92 93 94 95 96 97 98

/* txn methods */

/* 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);
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
99

100
/* misc */
Yoni Fogel's avatar
Yoni Fogel committed
101
static char *construct_full_name(const char *dir, const char *fname);
102
static int do_associated_inserts (DB_TXN *txn, DBT *key, DBT *data, DB *secondary);
Yoni Fogel's avatar
Yoni Fogel committed
103
    
104 105
#if NEED_TEST

106
static int env_parse_config_line(DB_ENV* dbenv, char *command, char *value) {
Yoni Fogel's avatar
Yoni Fogel committed
107 108 109
    int r;
    
    if (!strcmp(command, "set_data_dir")) {
110
        r = toku_env_set_data_dir(dbenv, value);
Yoni Fogel's avatar
Yoni Fogel committed
111 112
    }
    else if (!strcmp(command, "set_tmp_dir")) {
113
        r = toku_env_set_tmp_dir(dbenv, value);
Yoni Fogel's avatar
Yoni Fogel committed
114 115
    }
    else if (!strcmp(command, "set_lg_dir")) {
116
        r = toku_env_set_lg_dir(dbenv, value);
Yoni Fogel's avatar
Yoni Fogel committed
117 118 119 120 121 122
    }
    else r = -1;
        
    return r;
}

123
static int env_read_config(DB_ENV *env) {
124
    HANDLE_PANICKED_ENV(env);
Yoni Fogel's avatar
Yoni Fogel committed
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
    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;
158
    int index;
Yoni Fogel's avatar
Yoni Fogel committed
159 160 161 162 163 164 165
    
    buffersize = 1<<10; //1KB
    linebuffer = toku_malloc(buffersize);
    if (!linebuffer) {
        r = ENOMEM;
        goto cleanup;
    }
166
    for (linenumber = 1; !eof; linenumber++) {
Yoni Fogel's avatar
Yoni Fogel committed
167
        /* Read a single line. */
168
        for (index = 0; TRUE; index++) {
Yoni Fogel's avatar
Yoni Fogel committed
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
            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;
                }
            }
188
            linebuffer[index] = ch;
Yoni Fogel's avatar
Yoni Fogel committed
189 190 191 192 193 194 195 196 197 198 199 200 201 202
        }
        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.
203
        while (isspace(*value) && value < end) value++;
Yoni Fogel's avatar
Yoni Fogel committed
204 205 206 207 208 209 210 211 212
        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.
213
        r = env_parse_config_line(env, command, value < end ? value : "");
Yoni Fogel's avatar
Yoni Fogel committed
214 215 216 217
        if (r != 0) goto parseerror;
    }
    if (0) {
readerror:
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
218
        toku_ydb_do_error(env, r, "Error reading from DB_CONFIG:%d.\n", linenumber);
Yoni Fogel's avatar
Yoni Fogel committed
219 220 221
    }
    if (0) {
parseerror:
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
222
        toku_ydb_do_error(env, r, "Error parsing DB_CONFIG:%d.\n", linenumber);
Yoni Fogel's avatar
Yoni Fogel committed
223 224 225 226 227 228 229 230
    }
cleanup:
    if (full_name) toku_free(full_name);
    if (linebuffer) toku_free(linebuffer);
    if (fp) r2 = fclose(fp);
    return r ? r : r2;
}

231 232
#endif

233 234 235 236 237 238 239 240 241
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);
    }
    
242
#if 0
243 244 245 246 247
    // want to do recovery in its own process
    pid_t pid;
    if ((pid=fork())==0) {
	int r=tokudb_recover(datadir, logdir);
	assert(r==0);
248
	toku_free(logdir); // the child must also free.
249 250 251 252 253
	exit(0);
    }
    int status;
    waitpid(pid, &status, 0);
    if (!WIFEXITED(status) || WEXITSTATUS(status)!=0)  {
254
	toku_free(logdir);
255 256 257 258
	return toku_ydb_do_error(env, -1, "Recovery failed\n");
    }
    toku_free(logdir);
    return 0;
259 260 261 262 263
#else
    int r = tokudb_recover(datadir, logdir);
    toku_free(logdir);
    return r;
#endif
264 265
}

266
static int toku_env_open(DB_ENV * env, const char *home, u_int32_t flags, int mode) {
267
    HANDLE_PANICKED_ENV(env);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
268
    int r;
269
    u_int32_t unused_flags=flags;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
270

271
    if (env_opened(env)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
272
	return toku_ydb_do_error(env, EINVAL, "The environment is already open\n");
273
    }
Yoni Fogel's avatar
Yoni Fogel committed
274

275
    if ((flags & DB_USE_ENVIRON) && (flags & DB_USE_ENVIRON_ROOT)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
276
	return toku_ydb_do_error(env, EINVAL, "DB_USE_ENVIRON and DB_USE_ENVIRON_ROOT are incompatible flags\n");
277
    }
Yoni Fogel's avatar
Yoni Fogel committed
278 279

    if (home) {
280
        if ((flags & DB_USE_ENVIRON) || (flags & DB_USE_ENVIRON_ROOT)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
281
	    return toku_ydb_do_error(env, EINVAL, "DB_USE_ENVIRON and DB_USE_ENVIRON_ROOT are incompatible with specifying a home\n");
282
	}
Yoni Fogel's avatar
Yoni Fogel committed
283 284
    }
    else if ((flags & DB_USE_ENVIRON) ||
285 286
             ((flags & DB_USE_ENVIRON_ROOT) && geteuid() == 0)) home = getenv("DB_HOME");

287 288
    unused_flags &= ~DB_USE_ENVIRON & ~DB_USE_ENVIRON_ROOT; 

289
    if (!home) home = ".";
Yoni Fogel's avatar
Yoni Fogel committed
290

291
	// Verify that the home exists.
Yoni Fogel's avatar
Yoni Fogel committed
292
	{
293 294
	struct stat buf;
	r = stat(home, &buf);
295
	if (r!=0) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
296
	    return toku_ydb_do_error(env, errno, "Error from stat(\"%s\",...)\n", home);
297
	}
298 299
    }

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
300
    if (!(flags & DB_PRIVATE)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
301
	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
302
    }
303
    unused_flags &= ~DB_PRIVATE;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
304 305 306

    if (env->i->dir)
        toku_free(env->i->dir);
Yoni Fogel's avatar
Yoni Fogel committed
307
    env->i->dir = toku_strdup(home);
308
    if (env->i->dir == 0) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
309
	return toku_ydb_do_error(env, ENOMEM, "Out of memory\n");
310
    }
Yoni Fogel's avatar
Yoni Fogel committed
311 312 313 314 315 316
    if (0) {
        died1:
        toku_free(env->i->dir);
        env->i->dir = NULL;
        return r;
    }
317
#if NEED_TEST
318
    if ((r = env_read_config(env)) != 0) {
319 320
	goto died1;
    }
321
#endif
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
322 323
    env->i->open_flags = flags;
    env->i->open_mode = mode;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
324

325 326 327 328 329 330 331
    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
332
    if (flags & (DB_INIT_TXN | DB_INIT_LOG)) {
333 334
        char* full_dir = NULL;
        if (env->i->lg_dir) full_dir = construct_full_name(env->i->dir, env->i->lg_dir);
335
	assert(env->i->logger);
336
        toku_logger_write_log_files(env->i->logger, (flags & DB_INIT_LOG) != 0);
337 338 339
        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
340
	    toku_ydb_do_error(env, r, "Could not open logger\n");
341
	died2:
342
	    toku_logger_close(&env->i->logger);
343 344
	    goto died1;
	}
345 346 347
    } 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
348 349
    }

350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
    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);
    }

367
    r = toku_brt_create_cachetable(&env->i->cachetable, env->i->cachetable_size, ZERO_LSN, env->i->logger);
368
    if (r!=0) goto died2;
369

370
    if (env->i->logger) toku_logger_set_cachetable(env->i->logger, env->i->cachetable);
371

Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
372 373
    return 0;
}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
374

375
static int toku_env_close(DB_ENV * env, u_int32_t flags) {
376
    // Even if the env is panicedk, try to close as much as we can.
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
377
    int is_panicked = toku_env_is_panicked(env);
378
    int r0=0,r1=0;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
379
    if (env->i->cachetable)
380
        r0=toku_cachetable_close(&env->i->cachetable);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
381
    if (env->i->logger)
382
        r1=toku_logger_close(&env->i->logger);
Yoni Fogel's avatar
Yoni Fogel committed
383 384 385 386 387 388 389 390
    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);
    }
391 392
    if (env->i->lg_dir)
        toku_free(env->i->lg_dir);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
393 394
    if (env->i->tmp_dir)
        toku_free(env->i->tmp_dir);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
395
    toku_free(env->i->dir);
Yoni Fogel's avatar
Yoni Fogel committed
396
    toku_ltm_close(env->i->ltm);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
397 398
    toku_free(env->i);
    toku_free(env);
399
    ydb_unref();
400 401 402
    if (flags!=0) return EINVAL;
    if (r0) return r0;
    if (r1) return r1;
403
    if (is_panicked) return EINVAL;
404
    return 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
405
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
406

407
static int toku_env_log_archive(DB_ENV * env, char **list[], u_int32_t flags) {
408
    return toku_logger_log_archive(env->i->logger, list, flags);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
409
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
410

411
static int toku_env_log_flush(DB_ENV * env, const DB_LSN * lsn __attribute__((__unused__))) {
412
    HANDLE_PANICKED_ENV(env);
413 414
    // 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
415
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
416

417
static int toku_env_set_cachesize(DB_ENV * env, u_int32_t gbytes, u_int32_t bytes, int ncache) {
418
    HANDLE_PANICKED_ENV(env);
419 420
    if (ncache != 1)
        return EINVAL;
421 422 423 424 425
    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
426 427 428
    return 0;
}

Rich Prohaska's avatar
Rich Prohaska committed
429 430
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR >= 3

431
static int toku_env_get_cachesize(DB_ENV * env, u_int32_t *gbytes, u_int32_t *bytes, int *ncache) {
432
    HANDLE_PANICKED_ENV(env);
Rich Prohaska's avatar
Rich Prohaska committed
433 434 435 436 437 438
    *gbytes = env->i->cachetable_size >> 30;
    *bytes = env->i->cachetable_size & ((1<<30)-1);
    *ncache = 1;
    return 0;
}

439
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
440
    toku_ydb_lock(); int r = toku_env_get_cachesize(env, gbytes, bytes, ncache); toku_ydb_unlock(); return r;
441 442
}

Rich Prohaska's avatar
Rich Prohaska committed
443 444
#endif

445
static int toku_env_set_data_dir(DB_ENV * env, const char *dir) {
446
    HANDLE_PANICKED_ENV(env);
Yoni Fogel's avatar
Yoni Fogel committed
447 448
    u_int32_t i;
    int r;
449 450
    char** temp;
    char* new_dir;
Yoni Fogel's avatar
Yoni Fogel committed
451
    
452
    if (env_opened(env) || !dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
453
	return toku_ydb_do_error(env, EINVAL, "You cannot set the data dir after opening the env\n");
454
    }
Yoni Fogel's avatar
Yoni Fogel committed
455 456 457 458 459 460 461 462 463 464 465
    
    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);
466 467 468 469
    new_dir = toku_strdup(dir);
    if (0) {
        died1:
        toku_free(new_dir);
Yoni Fogel's avatar
Yoni Fogel committed
470 471
        return r;
    }
472 473
    if (new_dir==NULL) {
	assert(errno == ENOMEM);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
474
	return toku_ydb_do_error(env, errno, "Out of memory\n");
475
    }
476 477 478 479
    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
480 481
    env->i->n_data_dirs++;
    return 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
482
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
483

484
static void toku_env_set_errcall(DB_ENV * env, toku_env_errcall_t errcall) {
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
485
    env->i->errcall = errcall;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
486
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
487

488
static void toku_env_set_errfile(DB_ENV*env, FILE*errfile) {
489 490 491
    env->i->errfile = errfile;
}

492
static void toku_env_set_errpfx(DB_ENV * env, const char *errpfx) {
493
    env->i->errpfx = errpfx;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
494
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
495

496
static int toku_env_set_flags(DB_ENV * env, u_int32_t flags, int onoff) {
497
    HANDLE_PANICKED_ENV(env);
Yoni Fogel's avatar
Yoni Fogel committed
498 499 500 501 502 503

    u_int32_t change = 0;
    if (flags & DB_AUTO_COMMIT) {
        change |=  DB_AUTO_COMMIT;
        flags  &= ~DB_AUTO_COMMIT;
    }
504
    if (flags != 0 && onoff) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
505
	return toku_ydb_do_error(env, EINVAL, "TokuDB does not (yet) support any nonzero ENV flags other than DB_AUTO_COMMIT\n");
506
    }
Yoni Fogel's avatar
Yoni Fogel committed
507 508
    if   (onoff) env->i->open_flags |=  change;
    else         env->i->open_flags &= ~change;
Rich Prohaska's avatar
Rich Prohaska committed
509
    return 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
510
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
511

512
static int toku_env_set_lg_bsize(DB_ENV * env, u_int32_t bsize) {
513
    HANDLE_PANICKED_ENV(env);
514
    bsize=bsize;
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
515
    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
516
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
517

518
static int toku_env_set_lg_dir(DB_ENV * env, const char *dir) {
519
    HANDLE_PANICKED_ENV(env);
520
    if (env_opened(env)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
521
	return toku_ydb_do_error(env, EINVAL, "Cannot set log dir after opening the env\n");
522
    }
523 524

    if (env->i->lg_dir) toku_free(env->i->lg_dir);
525 526
    if (dir) {
        env->i->lg_dir = toku_strdup(dir);
527
        if (!env->i->lg_dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
528
	    return toku_ydb_do_error(env, ENOMEM, "Out of memory\n");
529
	}
530
    }
531 532
    else env->i->lg_dir = NULL;
    return 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
533
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
534

535
static int toku_env_set_lg_max(DB_ENV * env, u_int32_t lg_max) {
536
    HANDLE_PANICKED_ENV(env);
537 538 539 540 541 542
    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
543
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
544

545
static int toku_env_set_lk_detect(DB_ENV * env, u_int32_t detect) {
546
    HANDLE_PANICKED_ENV(env);
547
    detect=detect;
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
548
    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
549
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
550

Yoni Fogel's avatar
Yoni Fogel committed
551
static int toku_env_set_lk_max_locks(DB_ENV *dbenv, u_int32_t max) {
Yoni Fogel's avatar
Yoni Fogel committed
552
    int r = ENOSYS;
Yoni Fogel's avatar
Yoni Fogel committed
553
    HANDLE_PANICKED_ENV(dbenv);
Yoni Fogel's avatar
Yoni Fogel committed
554
    if (env_opened(dbenv))         { return EINVAL; }
Yoni Fogel's avatar
Yoni Fogel committed
555
    r = toku_ltm_set_max_locks_per_db(dbenv->i->ltm, max);
Yoni Fogel's avatar
Yoni Fogel committed
556
    return r;
Yoni Fogel's avatar
Yoni Fogel committed
557 558
}

559
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR <= 4
560
static int toku_env_set_lk_max(DB_ENV * env, u_int32_t lk_max) {
Yoni Fogel's avatar
Yoni Fogel committed
561
    return toku_env_set_lk_max_locks(env, lk_max);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
562
}
563 564

static int locked_env_set_lk_max(DB_ENV * env, u_int32_t lk_max) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
565
    toku_ydb_lock(); int r = toku_env_set_lk_max(env, lk_max); toku_ydb_unlock(); return r;
566
}
567
#endif
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
568

569 570
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
571
    return toku_ltm_get_max_locks_per_db(dbenv->i->ltm, lk_maxp);
572 573 574
}

static int locked_env_set_lk_max_locks(DB_ENV *dbenv, u_int32_t max) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
575
    toku_ydb_lock(); int r = toku_env_set_lk_max_locks(dbenv, max); toku_ydb_unlock(); return r;
576 577 578
}

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
579
    toku_ydb_lock(); int r = toku_env_get_lk_max_locks(dbenv, lk_maxp); toku_ydb_unlock(); return r;
580 581
}

Yoni Fogel's avatar
Yoni Fogel committed
582
//void toku__env_set_noticecall (DB_ENV *env, void (*noticecall)(DB_ENV *, db_notices)) {
Bradley C. Kuszmaul's avatar
Fixup  
Bradley C. Kuszmaul committed
583 584
//    env->i->noticecall = noticecall;
//}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
585

586
static int toku_env_set_tmp_dir(DB_ENV * env, const char *tmp_dir) {
587
    HANDLE_PANICKED_ENV(env);
588
    if (env_opened(env)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
589
	return toku_ydb_do_error(env, EINVAL, "Cannot set the tmp dir after opening an env\n");
590 591
    }
    if (!tmp_dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
592
	return toku_ydb_do_error(env, EINVAL, "Tmp dir bust be non-null\n");
593
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
594 595
    if (env->i->tmp_dir)
        toku_free(env->i->tmp_dir);
Yoni Fogel's avatar
Yoni Fogel committed
596
    env->i->tmp_dir = toku_strdup(tmp_dir);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
597
    return env->i->tmp_dir ? 0 : ENOMEM;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
598
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
599

600
static int toku_env_set_verbose(DB_ENV * env, u_int32_t which, int onoff) {
601 602
    HANDLE_PANICKED_ENV(env);
    which=which; onoff=onoff;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
603
    return 1;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
604
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
605

606 607
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
608 609
}

610
static int toku_env_txn_stat(DB_ENV * env, DB_TXN_STAT ** statp, u_int32_t flags) {
611 612
    HANDLE_PANICKED_ENV(env);
    statp=statp;flags=flags;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
613
    return 1;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
614 615
}

616
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR == 1
617
void toku_default_errcall(const char *errpfx, char *msg) {
618 619
    fprintf(stderr, "YDB: %s: %s", errpfx, msg);
}
620
#else
621
void toku_default_errcall(const DB_ENV *env, const char *errpfx, const char *msg) {
622
    env = env;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
623 624
    fprintf(stderr, "YDB: %s: %s", errpfx, msg);
}
625
#endif
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
626

627
static int locked_env_open(DB_ENV * env, const char *home, u_int32_t flags, int mode) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
628
    toku_ydb_lock(); int r = toku_env_open(env, home, flags, mode); toku_ydb_unlock(); return r;
629 630 631
}

static int locked_env_close(DB_ENV * env, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
632
    toku_ydb_lock(); int r = toku_env_close(env, flags); toku_ydb_unlock(); return r;
633 634 635
}

static int locked_env_log_archive(DB_ENV * env, char **list[], u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
636
    toku_ydb_lock(); int r = toku_env_log_archive(env, list, flags); toku_ydb_unlock(); return r;
637 638 639
}

static int locked_env_log_flush(DB_ENV * env, const DB_LSN * lsn) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
640
    toku_ydb_lock(); int r = toku_env_log_flush(env, lsn); toku_ydb_unlock(); return r;
641 642 643
}

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
644
    toku_ydb_lock(); int r = toku_env_set_cachesize(env, gbytes, bytes, ncache); toku_ydb_unlock(); return r;
645 646 647
}

static int locked_env_set_data_dir(DB_ENV * env, const char *dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
648
    toku_ydb_lock(); int r = toku_env_set_data_dir(env, dir); toku_ydb_unlock(); return r;
649 650 651
}

static int locked_env_set_flags(DB_ENV * env, u_int32_t flags, int onoff) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
652
    toku_ydb_lock(); int r = toku_env_set_flags(env, flags, onoff); toku_ydb_unlock(); return r;
653 654 655
}

static int locked_env_set_lg_bsize(DB_ENV * env, u_int32_t bsize) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
656
    toku_ydb_lock(); int r = toku_env_set_lg_bsize(env, bsize); toku_ydb_unlock(); return r;
657 658 659
}

static int locked_env_set_lg_dir(DB_ENV * env, const char *dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
660
    toku_ydb_lock(); int r = toku_env_set_lg_dir(env, dir); toku_ydb_unlock(); return r;
661 662 663
}

static int locked_env_set_lg_max(DB_ENV * env, u_int32_t lg_max) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
664
    toku_ydb_lock(); int r = toku_env_set_lg_max(env, lg_max); toku_ydb_unlock(); return r;
665 666
}

667 668 669 670
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;
}

671
static int locked_env_set_lk_detect(DB_ENV * env, u_int32_t detect) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
672
    toku_ydb_lock(); int r = toku_env_set_lk_detect(env, detect); toku_ydb_unlock(); return r;
673 674 675
}

static int locked_env_set_tmp_dir(DB_ENV * env, const char *tmp_dir) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
676
    toku_ydb_lock(); int r = toku_env_set_tmp_dir(env, tmp_dir); toku_ydb_unlock(); return r;
677 678 679
}

static int locked_env_set_verbose(DB_ENV * env, u_int32_t which, int onoff) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
680
    toku_ydb_lock(); int r = toku_env_set_verbose(env, which, onoff); toku_ydb_unlock(); return r;
681 682 683
}

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
684
    toku_ydb_lock(); int r = toku_env_txn_checkpoint(env, kbyte, min, flags); toku_ydb_unlock(); return r;
685 686 687
}

static int locked_env_txn_stat(DB_ENV * env, DB_TXN_STAT ** statp, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
688
    toku_ydb_lock(); int r = toku_env_txn_stat(env, statp, flags); toku_ydb_unlock(); return r;
689 690 691 692
}

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
693 694 695 696 697 698
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);

699
static int toku_env_create(DB_ENV ** envp, u_int32_t flags) {
Yoni Fogel's avatar
Yoni Fogel committed
700 701 702 703 704 705
    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
706
    memset(result, 0, sizeof *result);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
707
    result->err = toku_locked_env_err;
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
    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;
723
    result->get_lg_max = locked_env_get_lg_max;
724
    result->set_lk_max_locks = locked_env_set_lk_max_locks;
Rich Prohaska's avatar
Rich Prohaska committed
725
    result->get_lk_max_locks = locked_env_get_lk_max_locks;
726
    result->set_cachesize = locked_env_set_cachesize;
Rich Prohaska's avatar
Rich Prohaska committed
727
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR >= 3
728
    result->get_cachesize = locked_env_get_cachesize;
Rich Prohaska's avatar
Rich Prohaska committed
729
#endif
730
    result->set_lk_detect = locked_env_set_lk_detect;
731
#if DB_VERSION_MAJOR == 4 && DB_VERSION_MINOR <= 4
732
    result->set_lk_max = locked_env_set_lk_max;
733
#endif
734 735 736
    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
737

738
    MALLOC(result->i);
Yoni Fogel's avatar
Yoni Fogel committed
739
    if (result->i == 0) { r = ENOMEM; goto cleanup; }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
740
    memset(result->i, 0, sizeof *result->i);
741
    result->i->is_panicked=0;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
742
    result->i->ref_count = 1;
743 744
    result->i->errcall = 0;
    result->i->errpfx = 0;
745
    result->i->errfile = 0;
Yoni Fogel's avatar
Yoni Fogel committed
746 747

    r = toku_ltm_create(&result->i->ltm, __toku_env_default_max_locks,
Yoni Fogel's avatar
Yoni Fogel committed
748 749 750
                         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
751
    if (r!=0) { goto cleanup; }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
752

753
    {
Yoni Fogel's avatar
Yoni Fogel committed
754 755
	r = toku_logger_create(&result->i->logger);
	if (r!=0) { goto cleanup; }
756 757 758
	assert(result->i->logger);
    }

759
    ydb_add_ref();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
760
    *envp = result;
Yoni Fogel's avatar
Yoni Fogel committed
761 762 763 764 765 766 767 768 769 770 771 772 773 774
    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
775 776
}

777
int DB_ENV_CREATE_FUN (DB_ENV ** envp, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
778
    toku_ydb_lock(); int r = toku_env_create(envp, flags); toku_ydb_unlock(); return r;
779 780
}

Yoni Fogel's avatar
Yoni Fogel committed
781
static int toku_txn_release_locks(DB_TXN* txn) {
Yoni Fogel's avatar
Yoni Fogel committed
782 783 784
    assert(txn);
    toku_lth* lth = txn->i->lth;

Yoni Fogel's avatar
Yoni Fogel committed
785 786
    int r = ENOSYS;
    int first_error = 0;
Yoni Fogel's avatar
Yoni Fogel committed
787 788 789 790
    if (lth) {
        toku_lth_start_scan(lth);
        toku_lock_tree* next = toku_lth_next(lth);
        while (next) {
Yoni Fogel's avatar
Yoni Fogel committed
791 792 793 794 795 796
            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
797 798 799 800 801
            next = toku_lth_next(lth);
        }
        toku_lth_close(lth);
        txn->i->lth = NULL;
    }
Yoni Fogel's avatar
Yoni Fogel committed
802 803
    r = first_error;

Yoni Fogel's avatar
Yoni Fogel committed
804
    return r;
Yoni Fogel's avatar
Yoni Fogel committed
805 806
}

807
static int toku_txn_commit(DB_TXN * txn, u_int32_t flags) {
808
    if (!txn) return EINVAL;
809
    HANDLE_PANICKED_ENV(txn->mgrp);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
810
    //toku_ydb_notef("flags=%d\n", flags);
811 812
    int nosync = (flags & DB_TXN_NOSYNC)!=0;
    flags &= ~DB_TXN_NOSYNC;
813
    if (flags!=0) {
Yoni Fogel's avatar
Yoni Fogel committed
814
        //TODO: Release locks perhaps?
815 816
	if (txn->i) {
	    if (txn->i->tokutxn)
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
817
		toku_logger_abort(txn->i->tokutxn);
818 819 820 821
	    toku_free(txn->i);
	}
	toku_free(txn);
	return EINVAL;
822
    }
Yoni Fogel's avatar
Yoni Fogel committed
823
    int r2 = toku_txn_release_locks(txn);
824 825
    int r = toku_logger_commit(txn->i->tokutxn, nosync); // frees the tokutxn
    // the toxutxn is freed, and we must free the rest. */
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
826 827 828
    if (txn->i)
        toku_free(txn->i);
    toku_free(txn);
829
    return r2 ? r2 : r; // The txn is no good after the commit even if the commit fails.
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
830 831
}

832
static u_int32_t toku_txn_id(DB_TXN * txn) {
833
    HANDLE_PANICKED_ENV(txn->mgrp);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
834
    toku_ydb_barf();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
835
    abort();
836
    return -1;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
837 838
}

839
static int toku_txn_abort(DB_TXN * txn) {
840
    HANDLE_PANICKED_ENV(txn->mgrp);
Yoni Fogel's avatar
Yoni Fogel committed
841
    int r2 = toku_txn_release_locks(txn);
842
    int r = toku_logger_abort(txn->i->tokutxn);
Yoni Fogel's avatar
Yoni Fogel committed
843

844 845
    toku_free(txn->i);
    toku_free(txn);
Yoni Fogel's avatar
Yoni Fogel committed
846
    return r ? r : r2;
847 848
}

849 850 851
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
852
    toku_ydb_lock(); int r = toku_txn_begin(env, stxn, txn, flags); toku_ydb_unlock(); return r;
853 854 855
}

static u_int32_t locked_txn_id(DB_TXN *txn) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
856
    toku_ydb_lock(); u_int32_t r = toku_txn_id(txn); toku_ydb_unlock(); return r;
857 858 859
}

static int locked_txn_commit(DB_TXN *txn, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
860
    toku_ydb_lock(); int r = toku_txn_commit(txn, flags); toku_ydb_unlock(); return r;
861 862 863
}

static int locked_txn_abort(DB_TXN *txn) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
864
    toku_ydb_lock(); int r = toku_txn_abort(txn); toku_ydb_unlock(); return r;
865 866 867
}

static int toku_txn_begin(DB_ENV *env, DB_TXN * stxn, DB_TXN ** txn, u_int32_t flags) {
868
    HANDLE_PANICKED_ENV(env);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
869 870
    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");
871
    flags=flags;
872
    DB_TXN *MALLOC(result);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
873 874 875
    if (result == 0)
        return ENOMEM;
    memset(result, 0, sizeof *result);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
876
    //toku_ydb_notef("parent=%p flags=0x%x\n", stxn, flags);
877
    result->mgrp = env;
878 879 880
    result->abort = locked_txn_abort;
    result->commit = locked_txn_commit;
    result->id = locked_txn_id;
881
    MALLOC(result->i);
Yoni Fogel's avatar
Yoni Fogel committed
882 883 884 885
    if (!result->i) {
        toku_free(result);
        return ENOMEM;
    }
886
    memset(result->i, 0, sizeof *result->i);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
887
    result->i->parent = stxn;
Yoni Fogel's avatar
Yoni Fogel committed
888 889 890 891 892 893 894 895 896 897

    int r;
    if (env->i->open_flags & DB_INIT_LOCK) {
        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
898 899
    }
    
900
    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
901 902 903 904 905 906
    if (r != 0)
        return r;
    *txn = result;
    return 0;
}

Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
907
#if 0
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
908 909
int txn_commit(DB_TXN * txn, u_int32_t flags) {
    fprintf(stderr, "%s:%d\n", __FILE__, __LINE__);
910
    return toku_logger_log_commit(txn->i->tokutxn);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
911
}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
912
#endif
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
913

914
int log_compare(const DB_LSN * a, const DB_LSN * b) __attribute__((__noreturn__));
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
915
int log_compare(const DB_LSN * a, const DB_LSN * b) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
916
    toku_ydb_lock();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
917 918
    fprintf(stderr, "%s:%d log_compare(%p,%p)\n", __FILE__, __LINE__, a, b);
    abort();
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
919
    toku_ydb_unlock();
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
920 921
}

922 923
static int maybe_do_associate_create (DB_TXN*txn, DB*primary, DB*secondary) {
    DBC *dbc;
924
    int r = toku_db_cursor(secondary, txn, &dbc, 0, 0);
925 926
    if (r!=0) return r;
    DBT key,data;
927
    r = toku_c_get(dbc, &key, &data, DB_FIRST);
928
    {
929
	int r2=toku_c_close(dbc);
930 931 932 933 934
	if (r!=DB_NOTFOUND) {
	    return r2;
	}
    }
    /* Now we know the secondary is empty. */
935
    r = toku_db_cursor(primary, txn, &dbc, 0, 0);
936
    if (r!=0) return r;
937
    for (r = toku_c_get(dbc, &key, &data, DB_FIRST); r==0; r = toku_c_get(dbc, &key, &data, DB_NEXT)) {
938 939
	r = do_associated_inserts(txn, &key, &data, secondary);
	if (r!=0) {
940
	    toku_c_close(dbc);
941 942 943 944 945 946
	    return r;
	}
    }
    return 0;
}

947 948 949
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) {
950 951
    HANDLE_PANICKED_DB(primary);
    HANDLE_PANICKED_DB(secondary);
952 953
    unsigned int brtflags;
    
954 955
    if (secondary->i->primary) return EINVAL; // The secondary already has a primary
    if (primary->i->primary)   return EINVAL; // The primary already has a primary
956 957 958 959 960

    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.

961 962 963 964 965 966 967 968 969 970
    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
971 972
    list_push(&primary->i->associated, &secondary->i->associated);
    secondary->i->primary = primary;
973
    if (flags==DB_CREATE) {
974
	// To do this:  If the secondary is empty, then open a cursor on the primary.  Step through it all, doing the callbacks.
975
	// Then insert each callback result into the secondary.
976
	return maybe_do_associate_create(txn, primary, secondary);
977 978
    }
    return 0;
979 980
}

981
static int toku_db_close(DB * db, u_int32_t flags) {
982
    if (db->i->primary==0) {
Yoni Fogel's avatar
Yoni Fogel committed
983 984 985 986 987 988 989 990 991 992 993 994
        // 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);
        }
995
    }
996
    flags=flags;
997
    int r = toku_close_brt(db->i->brt, db->dbenv->i->logger);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
998 999
    if (r != 0)
        return r;
Yoni Fogel's avatar
Yoni Fogel committed
1000
    if (db->i->db_id) { toku_db_id_remove_ref(db->i->db_id); }
Yoni Fogel's avatar
Yoni Fogel committed
1001
    if (db->i->lt) {
Yoni Fogel's avatar
Yoni Fogel committed
1002 1003
        r = toku_lt_remove_ref(db->i->lt);
        if (r!=0) { return r; }
Yoni Fogel's avatar
Yoni Fogel committed
1004
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1005
    // printf("%s:%d %d=__toku_db_close(%p)\n", __FILE__, __LINE__, r, db);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1006 1007
    // Even if panicked, let's close as much as we can.
    int is_panicked = toku_env_is_panicked(db->dbenv); 
1008
    env_unref(db->dbenv);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
1009 1010 1011 1012
    toku_free(db->i->database_name);
    toku_free(db->i->full_fname);
    toku_free(db->i);
    toku_free(db);
1013
    ydb_unref();
1014
    if (r==0 && is_panicked) return EINVAL;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1015 1016 1017
    return r;
}

Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1018 1019 1020 1021 1022 1023 1024 1025 1026
/* 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
1027 1028 1029 1030 1031 1032
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
1033 1034 1035
    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
1036 1037
#ifdef DB_DBT_MULTIPLE
    if (idx.flags & DB_DBT_MULTIPLE) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1038 1039
        r = EINVAL; // We aren't ready for this
        goto clean_up;
Yoni Fogel's avatar
Yoni Fogel committed
1040 1041
    }
#endif
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1042 1043 1044 1045 1046
    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
1047
    if (idx.flags & DB_DBT_APPMALLOC) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1048 1049
        /* This should be free because idx.data is allocated by the user */
    	free(idx.data);
Yoni Fogel's avatar
Yoni Fogel committed
1050
    }
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1051
    return r; 
Yoni Fogel's avatar
Yoni Fogel committed
1052 1053
}

1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
//Get the main portion of a cursor flag (excluding the bitwise or'd components).
static int get_main_cursor_flag(u_int32_t flag) {
#ifdef DB_READ_UNCOMMITTED
    flag &= ~DB_READ_UNCOMMITTED;
#endif    
#ifdef DB_MULTIPLE
    flag &= ~DB_MULTIPLE;
#endif
#ifdef DB_MULTIPLE_KEY
    flag &= ~DB_MULTIPLE_KEY;
#endif    
    flag &= ~DB_RMW;
    return flag;
}

1069
static inline BOOL toku_c_uninitialized(DBC* c) {
Yoni Fogel's avatar
Yoni Fogel committed
1070 1071
    return toku_brt_cursor_uninitialized(c->i->c);
}            
Yoni Fogel's avatar
Yoni Fogel committed
1072 1073 1074

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
1075 1076
    memset(key,  0, sizeof(DBT));
    memset(data, 0, sizeof(DBT));
Yoni Fogel's avatar
Yoni Fogel committed
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
    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;
}

static inline int toku_uninitialized_swap(DBC* c, DBT* key, DBT* data,
                                          u_int32_t* flag, u_int32_t* get_flag,
                                          u_int32_t new_flag) {
    /* DB_FIRST/DB_LAST do nothing in pre_lock so we can skip the goto.  */
    if (toku_c_uninitialized(c)) toku_swap_flag(flag, get_flag, new_flag);
    else return toku_c_get_current_unconditional(c, key, data);
    return 0;
}

Yoni Fogel's avatar
Yoni Fogel committed
1099 1100 1101 1102 1103 1104 1105
/*
    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.
*/
1106
static inline DB_TXN* toku_txn_ancestor(DB_TXN* txn) {
Yoni Fogel's avatar
Yoni Fogel committed
1107
    while (txn && txn->i->parent) txn = txn->i->parent;
Yoni Fogel's avatar
Yoni Fogel committed
1108

Yoni Fogel's avatar
Yoni Fogel committed
1109 1110 1111
    return txn;
}

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

Yoni Fogel's avatar
Yoni Fogel committed
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
/* 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         cursor_key;         // Original position of cursor (key portion)
    DBT         cursor_val;         // Original position of cursor (val portion)
    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
    BOOL        cursor_is_write;    // Whether op can change position of cursor
    BOOL        cursor_was_saved;   // Whether we saved the cursor yet.
    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        cursor_malloced;
    BOOL        tmp_key_malloced;
    BOOL        tmp_val_malloced;
    BOOL        tmp_dat_malloced;
} C_GET_VARS;

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
1147 1148
        case DB_NEXT:
        case DB_NEXT_NODUP:
Yoni Fogel's avatar
Yoni Fogel committed
1149 1150 1151
            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
1152 1153
            }
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1154 1155
        case DB_PREV:
        case DB_PREV_NODUP:
Yoni Fogel's avatar
Yoni Fogel committed
1156 1157 1158
            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
1159 1160
            }
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1161
        case DB_GET_BOTH_RANGE:
Yoni Fogel's avatar
Yoni Fogel committed
1162 1163
            if (!g->duplicates) {
                toku_swap_flag(&g->flag, &g->op, DB_GET_BOTH);
Yoni Fogel's avatar
Yoni Fogel committed
1164 1165
            }
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1166
        default:
Yoni Fogel's avatar
Yoni Fogel committed
1167 1168 1169 1170
            break;
    }
}

Yoni Fogel's avatar
Yoni Fogel committed
1171 1172 1173 1174
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
1175 1176 1177 1178
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;
    if (!lt) { r = 0; goto cleanup; }
Yoni Fogel's avatar
Yoni Fogel committed
1179

Yoni Fogel's avatar
Yoni Fogel committed
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
    /* 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
1192

Yoni Fogel's avatar
Yoni Fogel committed
1193 1194
static int toku_c_get_describe_inputs(C_GET_VARS* g) { 
    int r = ENOSYS;
Yoni Fogel's avatar
Yoni Fogel committed
1195 1196 1197
    /* 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
1198 1199 1200 1201
    switch (g->op) {
        case DB_SET:
            g->key_is_read  = TRUE;
            g->val_is_write = TRUE;
Yoni Fogel's avatar
Yoni Fogel committed
1202
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1203 1204 1205 1206
        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
1207
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1208 1209 1210
        case DB_GET_BOTH:
            g->key_is_read  = TRUE;
            g->val_is_read  = TRUE;
Yoni Fogel's avatar
Yoni Fogel committed
1211
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1212 1213 1214 1215 1216
        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
1217
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1218
        case DB_CURRENT:
Yoni Fogel's avatar
Yoni Fogel committed
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
        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
1231 1232 1233 1234 1235 1236 1237 1238
        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
1239
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1240
        default:
Yoni Fogel's avatar
Yoni Fogel committed
1241
            r = EINVAL;
Yoni Fogel's avatar
Yoni Fogel committed
1242
            goto cleanup;
Yoni Fogel's avatar
Yoni Fogel committed
1243
    }
Yoni Fogel's avatar
Yoni Fogel committed
1244 1245
    r = 0;
cleanup:
Yoni Fogel's avatar
Yoni Fogel committed
1246 1247 1248
    return r;
}

Yoni Fogel's avatar
Yoni Fogel committed
1249 1250 1251 1252 1253 1254
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
1255

Yoni Fogel's avatar
Yoni Fogel committed
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
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
1274
    }
Yoni Fogel's avatar
Yoni Fogel committed
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
    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;
}

static int toku_c_get_post_lock(C_GET_VARS* g, BOOL found, DBT* orig_key, DBT* orig_val) {
    int r = ENOSYS;
    toku_lock_tree* lt = g->db->i->lt;
    if (!lt) { r = 0; goto cleanup; }
Yoni Fogel's avatar
Yoni Fogel committed
1317 1318 1319 1320

    BOOL lock = TRUE;
    const DBT* key_l;
    const DBT* key_r;
Yoni Fogel's avatar
Yoni Fogel committed
1321 1322 1323 1324
    const DBT* val_l;
    const DBT* val_r;
    switch (g->op) {
        case (DB_CURRENT):
Yoni Fogel's avatar
Yoni Fogel committed
1325 1326 1327 1328
            /* 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
1329 1330 1331 1332 1333 1334 1335 1336 1337
        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
1338
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1339 1340
        case (DB_GET_BOTH):
            /* We acquired the lock before the cursor op. */
Yoni Fogel's avatar
Yoni Fogel committed
1341 1342
            lock = FALSE;
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1343 1344 1345 1346
        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
1347
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1348 1349 1350 1351
        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
1352
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1353 1354 1355 1356 1357
        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
1358
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1359 1360 1361 1362
        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
1363 1364
            break;
        case (DB_NEXT):
Yoni Fogel's avatar
Yoni Fogel committed
1365 1366 1367 1368 1369 1370
        case (DB_NEXT_NODUP):
            assert(!toku_c_uninitialized(g->c));
            key_l = &g->cursor_key;
            val_l = &g->cursor_val;
            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
1371 1372
            break;
        case (DB_PREV):
Yoni Fogel's avatar
Yoni Fogel committed
1373 1374 1375 1376 1377 1378
        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;
            key_r = &g->cursor_key;
            val_r = &g->cursor_val;
Yoni Fogel's avatar
Yoni Fogel committed
1379
            break;
Yoni Fogel's avatar
Yoni Fogel committed
1380 1381 1382 1383 1384
        case (DB_NEXT_DUP):
            assert(!toku_c_uninitialized(g->c));
            key_l = key_r = &g->cursor_key;
            val_l = &g->cursor_val;
            val_r = found ? &g->tmp_val : toku_lt_infinity;
Yoni Fogel's avatar
Yoni Fogel committed
1385 1386
            break;
#ifdef DB_PREV_DUP
Yoni Fogel's avatar
Yoni Fogel committed
1387 1388 1389 1390 1391
        case (DB_PREV_DUP):
            assert(!toku_c_uninitialized(g->c));
            key_l = key_r = &g->cursor_key;
            val_l = found ? &g->tmp_val : toku_lt_neg_infinity;
            val_r = &g->cursor_val;
Yoni Fogel's avatar
Yoni Fogel committed
1392 1393
            break;
#endif
Yoni Fogel's avatar
Yoni Fogel committed
1394
        default:
Yoni Fogel's avatar
Yoni Fogel committed
1395 1396
            r = EINVAL;
            lock = FALSE;
Yoni Fogel's avatar
Yoni Fogel committed
1397
            goto cleanup;
Yoni Fogel's avatar
Yoni Fogel committed
1398
    }
Yoni Fogel's avatar
Yoni Fogel committed
1399
    if (lock) {
Yoni Fogel's avatar
Yoni Fogel committed
1400 1401 1402 1403
        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
1404
    }
Yoni Fogel's avatar
Yoni Fogel committed
1405
    r = 0;
Yoni Fogel's avatar
Yoni Fogel committed
1406
cleanup:
Yoni Fogel's avatar
Yoni Fogel committed
1407
    return r;
Yoni Fogel's avatar
Yoni Fogel committed
1408 1409
}

Yoni Fogel's avatar
Yoni Fogel committed
1410 1411
/* Used to save the state of a cursor. */
int brt_cursor_save_key_val(BRT_CURSOR cursor, DBT* key, DBT* val);
Yoni Fogel's avatar
Yoni Fogel committed
1412

Yoni Fogel's avatar
Yoni Fogel committed
1413 1414
/* Used to restore the state of a cursor. */
void brt_cursor_set_key_val_manually(BRT_CURSOR cursor, DBT* key, DBT* val);
Yoni Fogel's avatar
Yoni Fogel committed
1415

Yoni Fogel's avatar
Yoni Fogel committed
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
static int toku_c_get_save_cursor(C_GET_VARS* g) {
    int r = ENOSYS;
    if (!g->cursor_is_write) { r = 0; goto cleanup; }
    if (!toku_c_uninitialized(g->c)) {
        g->cursor_key.flags = DB_DBT_MALLOC;
        g->cursor_val.flags = DB_DBT_MALLOC;
    }
    if ((r = brt_cursor_save_key_val(g->c->i->c, &g->cursor_key, &g->cursor_val))) goto cleanup;
    if (!toku_c_uninitialized(g->c)) g->cursor_malloced = TRUE;
    g->cursor_was_saved = TRUE;
    r = 0;
cleanup:
    return r;
}
Yoni Fogel's avatar
Yoni Fogel committed
1430

Yoni Fogel's avatar
Yoni Fogel committed
1431 1432 1433 1434 1435 1436 1437 1438 1439
static int toku_c_pget_save_cursor(C_GET_VARS* g) {
    return toku_c_get_save_cursor(g);
}

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
1440
    BRT primary = g->db->i->primary->i->brt;
Yoni Fogel's avatar
Yoni Fogel committed
1441

Yoni Fogel's avatar
Yoni Fogel committed
1442 1443
    r = toku_brt_cursor_copyout_with_dat(g->c->i->c, write_key, write_val,
                                         primary,    write_dat, &g->tmp_dat);
Yoni Fogel's avatar
Yoni Fogel committed
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
    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
1455
    r = toku_brt_cursor_copyout(g->c->i->c, write_key, write_val);
Yoni Fogel's avatar
Yoni Fogel committed
1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
    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;
    int r_cursor_op = 0;
    C_GET_VARS g;
    memset(&g, 0, sizeof(g));
    /* Initialize variables. */
    g.c    = c;
    g.db   = c->dbp;
    g.flag = flag;
    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);
    }
    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);
    /* 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 the cursor position if the op can modify the cursor position. */
    if ((r = toku_c_get_save_cursor(&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. */
Yoni Fogel's avatar
Yoni Fogel committed
1492
    TOKUTXN txn = c->i->txn ? c->i->txn->i->tokutxn : NULL;
Yoni Fogel's avatar
Yoni Fogel committed
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
    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;
    r = toku_c_get_post_lock(&g, found, key, val);
    if (r!=0) goto cleanup;
    /* 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:
    if (g.cursor_was_saved && g.cursor_malloced) {
        /* We saved the cursor.  We either need to restore it, or free
         * the saved version. */
        if (r!=0 && r!=DB_NOTFOUND) {
            /* Failure since 0 and DB_NOTFOUND are 'successes';
             * Restore the cursor. */
            brt_cursor_set_key_val_manually(c->i->c, &g.cursor_key, &g.cursor_val);
            /* cursor_key/val will be zeroed out. */
        }
        else {
            /* Delete the saved cursor. */
            if (g.cursor_key.data) toku_free(g.cursor_key.data);
            if (g.cursor_val.data) toku_free(g.cursor_val.data);
        }
    }
    /* 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
1526 1527 1528 1529
    return r;
}

static int toku_c_del_noassociate(DBC * c, u_int32_t flags) {
Yoni Fogel's avatar
Yoni Fogel committed
1530 1531 1532 1533 1534 1535 1536 1537 1538 1539
    DB* db = c->dbp;
    HANDLE_PANICKED_DB(db);
    if (toku_c_uninitialized(c)) return EINVAL;

    int r;
    if (db->i->lt) {
        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
1540 1541 1542 1543 1544
        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
1545 1546 1547 1548 1549 1550
                                       &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
1551 1552 1553
    return r;
}

Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1554
static int toku_c_pget(DBC * c, DBT *key, DBT *pkey, DBT *data, u_int32_t flag) {
Yoni Fogel's avatar
Yoni Fogel committed
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
    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
1568
    int r;
Yoni Fogel's avatar
Yoni Fogel committed
1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579
    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. */
Yoni Fogel's avatar
Yoni Fogel committed
1580
    toku_c_pget_fix_flags(&g);
Yoni Fogel's avatar
Yoni Fogel committed
1581 1582 1583 1584 1585 1586 1587 1588 1589 1590
    /* Determine whether the key, val, and data, parameters are read, write,
     * or both. */
    if ((r = toku_c_pget_describe_inputs(&g))) goto cleanup;
 
    /* 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 */ 

    /* Save the cursor position if the op can modify the cursor position. */
    if ((r = toku_c_pget_save_cursor(&g))) goto cleanup;;
1591

Yoni Fogel's avatar
Yoni Fogel committed
1592
    if (0) {
1593
delete_silently_and_retry:
Yoni Fogel's avatar
Yoni Fogel committed
1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607
        /* 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. */
        if ((r = toku_c_del_noassociate(c, 0))) goto cleanup;
1608
    }
Yoni Fogel's avatar
Yoni Fogel committed
1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
    /* Save the inputs. */
    if ((r = toku_c_pget_save_inputs(&g, key, pkey, data))) goto cleanup;

    if ((r = toku_c_get_noassociate(c, &g.tmp_key, &g.tmp_val, flag))) goto cleanup;

    r = toku_db_get(pdb, c->i->txn, &g.tmp_val, &g.tmp_dat, 0);
    if (r==DB_NOTFOUND) goto delete_silently_and_retry;
    if (r!=0) goto cleanup;

    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;
    if (r!=0) goto cleanup;

    /* Atomically assign all 3 outputs. */
    if ((r = toku_c_pget_assign_outputs(&g, key, pkey, data))) goto cleanup;
    r = 0;
cleanup:
    if (g.cursor_was_saved && g.cursor_malloced) {
        /* We saved the cursor.  We either need to restore it, or free
         * the saved version. */
        if (r!=0) {
            /* Restore the cursor. */
            brt_cursor_set_key_val_manually(c->i->c, &g.cursor_key, &g.cursor_val);
            /* cursor_key/val will be zeroed out. */
        }
        else {
            /* Delete the saved cursor. */
            if (g.cursor_key.data) toku_free(g.cursor_key.data);
            if (g.cursor_val.data) toku_free(g.cursor_val.data);
        }
1639
    }
Yoni Fogel's avatar
Yoni Fogel committed
1640 1641 1642 1643 1644
    /* 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
1645 1646
}

Yoni Fogel's avatar
Yoni Fogel committed
1647
static int toku_c_get(DBC * c, DBT * key, DBT * data, u_int32_t flag) {
1648
    DB *db = c->dbp;
1649
    HANDLE_PANICKED_DB(db);
Yoni Fogel's avatar
Yoni Fogel committed
1650 1651
    int r;

Yoni Fogel's avatar
Yoni Fogel committed
1652 1653
    if (db->i->primary==0) {
        r = toku_c_get_noassociate(c, key, data, flag);
Yoni Fogel's avatar
Yoni Fogel committed
1654
    }
Yoni Fogel's avatar
Yoni Fogel committed
1655 1656 1657 1658 1659 1660 1661
    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
1662 1663 1664
        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
1665 1666 1667 1668 1669 1670
        memset(&primary_key, 0, sizeof(primary_key));
        r = toku_c_pget(c, key, &primary_key, data, flag);
    }
    return r;
}

1671
static int toku_c_close(DBC * c) {
1672
    int r = toku_brt_cursor_close(c->i->c);
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
1673 1674
    toku_free(c->i);
    toku_free(c);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1675 1676 1677
    return r;
}

1678 1679 1680 1681 1682
static inline int keyeq(DBC *c, DBT *a, DBT *b) {
    DB *db = c->dbp;
    return db->i->brt->compare_fun(db, a, b) == 0;
}

1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694
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;
    }

1695
    r = toku_c_get(cursor, &currentkey, &currentval, DB_CURRENT_BINDING);
1696 1697
    if (r != 0) goto finish;
    
1698
    r = toku_db_cursor(cursor->dbp, 0, &count_cursor, 0, 0);
1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724
    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;
}

1725 1726
static int toku_db_get_noassociate(DB * db, DB_TXN * txn, DBT * key, DBT * data, u_int32_t flags) {
    int r;
1727
    if (flags!=0 && flags!=DB_GET_BOTH) return EINVAL;
1728

Yoni Fogel's avatar
Yoni Fogel committed
1729
    DBC *dbc;
1730
    r = toku_db_cursor(db, txn, &dbc, 0, 1);
Yoni Fogel's avatar
Yoni Fogel committed
1731 1732 1733 1734 1735
    if (r!=0) return r;
    r = toku_c_get_noassociate(dbc, key, data,
                               (flags == 0) ? DB_SET : DB_GET_BOTH);
    int r2 = toku_c_close(dbc);
    return r ? r : r2;
1736 1737 1738 1739
}

static int toku_db_del_noassociate(DB * db, DB_TXN * txn, DBT * key, u_int32_t flags) {
    int r;
1740
    if (flags!=0 && flags!=DB_DELETE_ANY) return EINVAL;
1741 1742 1743 1744 1745 1746 1747
    //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;
        r = toku_db_get_noassociate(db, txn, key, &search_val, 0);
        if (r != 0)
            return r;
1748
        toku_free(search_val.data);
1749 1750
    } 
    //Do the actual deleting.
Yoni Fogel's avatar
Yoni Fogel committed
1751
    if (db->i->lt) {
Yoni Fogel's avatar
Yoni Fogel committed
1752 1753 1754 1755 1756
        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
1757 1758 1759 1760
                                             key, toku_lt_neg_infinity,
                                             key, toku_lt_infinity);
        if (r!=0) return r;
    }
1761
    r = toku_brt_delete(db->i->brt, key, txn ? txn->i->tokutxn : 0);
1762 1763 1764
    return r;
}

Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1765
static int do_associated_deletes(DB_TXN *txn, DBT *key, DBT *data, DB *secondary) {
1766
    u_int32_t brtflags;
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1767 1768
    DBT idx;
    memset(&idx, 0, sizeof(idx));
1769
    int r2 = 0;
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1770 1771 1772
    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
1773 1774
#ifdef DB_DBT_MULTIPLE
    if (idx.flags & DB_DBT_MULTIPLE) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1775 1776
        r = EINVAL; // We aren't ready for this
        goto clean_up;
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1777 1778
    }
#endif
1779 1780
    toku_brt_get_flags(secondary->i->brt, &brtflags);
    if (brtflags & TOKU_DB_DUPSORT) {
1781
        //If the secondary has duplicates we need to use cursor deletes.
1782
        DBC *dbc;
1783
        r = toku_db_cursor(secondary, txn, &dbc, 0, 0);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1784
        if (r!=0) goto cursor_cleanup;
1785
        r = toku_c_get_noassociate(dbc, &idx, key, DB_GET_BOTH);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1786
        if (r!=0) goto cursor_cleanup;
1787
        r = toku_c_del_noassociate(dbc, 0);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1788
    cursor_cleanup:
1789
        r2 = toku_c_close(dbc);
1790 1791
    } else 
        r = toku_db_del_noassociate(secondary, txn, &idx, DB_DELETE_ANY);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1792
    clean_up:
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1793
    if (idx.flags & DB_DBT_APPMALLOC) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1794 1795
        /* This should be free because idx.data is allocated by the user */
    	free(idx.data);
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1796
    }
1797 1798
    if (r!=0) return r;
    return r2;
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1799 1800
}

1801
static int toku_c_del(DBC * c, u_int32_t flags) {
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1802
    int r;
1803
    DB* db = c->dbp;
1804
    HANDLE_PANICKED_DB(db);
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1805
    
1806
    //It is a primary with secondaries, or is a secondary.
1807
    if (db->i->primary != 0 || !list_empty(&db->i->associated)) {
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1808 1809 1810 1811 1812 1813 1814
        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
1815 1816
        pkey.flags = DB_DBT_REALLOC;
        data.flags = DB_DBT_REALLOC;
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1817 1818
        if (db->i->primary == 0) {
            pdb = db;
1819
            r = toku_c_get(c, &pkey, &data, DB_CURRENT);
Yoni Fogel's avatar
Yoni Fogel committed
1820
            if (r != 0) goto assoc_cleanup;
1821
        } else {
1822
            DBT skey;
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1823
            pdb = db->i->primary;
1824
            memset(&skey, 0, sizeof(skey));
Yoni Fogel's avatar
Yoni Fogel committed
1825
            skey.flags = DB_DBT_MALLOC;
1826
            r = toku_c_pget(c, &skey, &pkey, &data, DB_CURRENT);
Yoni Fogel's avatar
Yoni Fogel committed
1827 1828
            if (r!=0) goto assoc_cleanup;
            if (skey.data) toku_free(skey.data);
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1829 1830 1831 1832 1833 1834
        }
        
    	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
1835
    	    if (r!=0) goto assoc_cleanup;
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1836 1837 1838
    	}
    	if (db->i->primary != 0) {
    	    //If this is a secondary, we did not delete from the primary.
1839 1840
    	    //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
1841
    	    if (r!=0) goto assoc_cleanup;
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1842
    	}
Yoni Fogel's avatar
Yoni Fogel committed
1843 1844 1845 1846
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
1847
    }
1848
    r = toku_c_del_noassociate(c, flags);
Yoni Fogel's avatar
Yoni Fogel committed
1849 1850 1851
    if (r!=0) goto cleanup;
    r = 0;
cleanup:
1852
    return r;    
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1853 1854
}

1855
static int toku_c_put(DBC *dbc, DBT *key, DBT *data, u_int32_t flags) {
1856
    DB* db = dbc->dbp;
1857
    HANDLE_PANICKED_DB(db);
1858 1859 1860 1861 1862 1863
    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
1864
    DB_TXN* txn = dbc->i->txn;
1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883
    
    //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) {
1884 1885
                toku_free(key_local.data);
                toku_free(data_local.data);
1886 1887 1888 1889 1890 1891 1892 1893 1894 1895
            }
            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
1896 1897
        if (db->i->lt) {
            /* Acquire all write locks before  */
Yoni Fogel's avatar
Yoni Fogel committed
1898 1899 1900 1901 1902
            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
1903 1904
                                           &key_local, &data_local);
            if (r!=0) goto cleanup;
Yoni Fogel's avatar
Yoni Fogel committed
1905
            r = toku_lt_acquire_write_lock(db->i->lt, db, id_anc,
Yoni Fogel's avatar
Yoni Fogel committed
1906 1907 1908
                                           &key_local, data);
            if (r!=0) goto cleanup;
        }
1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924
        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
1925
    //Flags must NOT be 0.
1926 1927
    else return EINVAL;
finish:
1928 1929
    //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.
1930 1931 1932 1933 1934
    if (r!=0) goto cleanup;
    r = toku_c_get(dbc, get_key, get_data, DB_GET_BOTH);
    goto cleanup;
}

1935
static int locked_c_pget(DBC * c, DBT *key, DBT *pkey, DBT *data, u_int32_t flag) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1936
    toku_ydb_lock(); int r = toku_c_pget(c, key, pkey, data, flag); toku_ydb_unlock(); return r;
1937 1938 1939
}

static int locked_c_get(DBC * c, DBT * key, DBT * data, u_int32_t flag) {
1940 1941 1942 1943
    //{ 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;
1944 1945 1946
}

static int locked_c_close(DBC * c) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1947
    toku_ydb_lock(); int r = toku_c_close(c); toku_ydb_unlock(); return r;
1948 1949 1950
}

static int locked_c_count(DBC *cursor, db_recno_t *count, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1951
    toku_ydb_lock(); int r = toku_c_count(cursor, count, flags); toku_ydb_unlock(); return r;
1952 1953 1954
}

static int locked_c_del(DBC * c, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1955
    toku_ydb_lock(); int r = toku_c_del(c, flags); toku_ydb_unlock(); return r;
1956 1957 1958
}

static int locked_c_put(DBC *dbc, DBT *key, DBT *data, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
1959
    toku_ydb_lock(); int r = toku_c_put(dbc, key, data, flags); toku_ydb_unlock(); return r;
1960 1961
}

1962
static int toku_db_cursor(DB * db, DB_TXN * txn, DBC ** c, u_int32_t flags, int is_temporary_cursor) {
1963
    HANDLE_PANICKED_DB(db);
1964 1965
    if (flags != 0)
        return EINVAL;
1966
    DBC *MALLOC(result);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1967 1968 1969
    if (result == 0)
        return ENOMEM;
    memset(result, 0, sizeof *result);
1970 1971 1972 1973 1974 1975
    result->c_get = locked_c_get;
    result->c_pget = locked_c_pget;
    result->c_put = locked_c_put;
    result->c_close = locked_c_close;
    result->c_del = locked_c_del;
    result->c_count = locked_c_count;
1976
    MALLOC(result->i);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1977
    assert(result->i);
1978
    result->dbp = db;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
1979
    result->i->txn = txn;
1980
    int r = toku_brt_cursor(db->i->brt, &result->i->c, is_temporary_cursor);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
1981
    assert(r == 0);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
1982 1983 1984 1985
    *c = result;
    return 0;
}

1986
static int toku_db_del(DB *db, DB_TXN *txn, DBT *key, u_int32_t flags) {
1987
    HANDLE_PANICKED_DB(db);
1988
    int r;
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1989

1990 1991
    //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
1992 1993
        DB* pdb;
        DBT data;
1994 1995
        DBT pkey;
        DBT *pdb_key;
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1996
        struct list *h;
1997
        u_int32_t brtflags;
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
1998 1999

        memset(&data, 0, sizeof(data));
Yoni Fogel's avatar
Yoni Fogel committed
2000
        data.flags = DB_DBT_REALLOC;
2001 2002

        toku_brt_get_flags(db->i->brt, &brtflags);
Rich Prohaska's avatar
Rich Prohaska committed
2003
        if (brtflags & TOKU_DB_DUPSORT) {
2004
            int r2;
Yoni Fogel's avatar
Yoni Fogel committed
2005 2006 2007 2008 2009
            DBC *dbc;
            BOOL found = FALSE;
            DBT tmp_key;
            memset(&tmp_key, 0, sizeof(tmp_key));
            tmp_key.flags = DB_DBT_REALLOC;
2010 2011 2012 2013 2014

            /* 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.
2015
            r = toku_db_cursor(db, txn, &dbc, 0, 1);
2016
            if (r!=0) return r;
2017 2018
            r = toku_c_get_noassociate(dbc, key, &data, DB_SET);
            while (r==0) {
2019
                r = toku_c_del(dbc, 0);
Yoni Fogel's avatar
Yoni Fogel committed
2020
                if (r==0) found = TRUE;
2021
                if (r!=0 && r!=DB_KEYEMPTY) break;
Yoni Fogel's avatar
Yoni Fogel committed
2022 2023 2024 2025 2026 2027
                /* 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);
2028
                if (r == DB_NOTFOUND) {
Yoni Fogel's avatar
Yoni Fogel committed
2029 2030
                    //If we deleted at least one we're happy.  Quit out.
                    if (found) r = 0;
2031
                    break;
2032 2033
                }
            }
Yoni Fogel's avatar
Yoni Fogel committed
2034 2035
            if (data.data)    toku_free(data.data);
            if (tmp_key.data) toku_free(tmp_key.data);
2036

2037
            r2 = toku_c_close(dbc);
2038 2039 2040 2041
            if (r != 0) return r;
            return r2;
        }

2042 2043 2044 2045 2046 2047 2048 2049
        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
2050 2051
        if (db->i->primary == 0) {
            pdb = db;
2052
            r = toku_db_get(db, txn, key, &data, 0);
2053
            pdb_key = key;
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
2054 2055 2056
        }
        else {
            pdb = db->i->primary;
2057
            r = toku_db_pget(db, txn, key, &pkey, &data, 0);
2058
            pdb_key = &pkey;
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
2059
        }
2060 2061 2062
        if (r != 0) { 
            cleanup(); return r; 
        }
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
2063 2064 2065
        
    	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);
2066 2067
    	    if (dbi->db == db) continue;                  //Skip current db (if its primary or secondary)
    	    r = do_associated_deletes(txn, pdb_key, &data, dbi->db);
2068 2069 2070
    	    if (r!=0) { 
                cleanup(); return r;
            }
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
2071 2072 2073
    	}
    	if (db->i->primary != 0) {
    	    //If this is a secondary, we did not delete from the primary.
2074 2075
    	    //Primaries cannot have duplicates, (noncursor) del is safe.
    	    r = toku_db_del_noassociate(pdb, txn, pdb_key, DB_DELETE_ANY);
2076 2077 2078
    	    if (r!=0) { 
                cleanup(); return r;
            }
Yoni Fogel's avatar
{{{  
Yoni Fogel committed
2079
    	}
2080 2081 2082

        cleanup();

2083 2084
    	//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
2085
    }
2086
    r = toku_db_del_noassociate(db, txn, key, flags);
Rich Prohaska's avatar
Rich Prohaska committed
2087
    return r;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2088
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2089

Rich Prohaska's avatar
Rich Prohaska committed
2090 2091 2092 2093
static inline int db_thread_need_flags(DBT *dbt) {
    return (dbt->flags & (DB_DBT_MALLOC+DB_DBT_REALLOC+DB_DBT_USERMEM)) == 0;
}

2094
static int toku_db_get (DB * db, DB_TXN * txn, DBT * key, DBT * data, u_int32_t flags) {
2095
    HANDLE_PANICKED_DB(db);
Yoni Fogel's avatar
Yoni Fogel committed
2096
    int r;
2097

Rich Prohaska's avatar
Rich Prohaska committed
2098
    if ((db->i->open_flags & DB_THREAD) && db_thread_need_flags(data))
2099 2100
        return EINVAL;

Yoni Fogel's avatar
Yoni Fogel committed
2101 2102 2103 2104
    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;
2105
    r = toku_db_cursor(db, txn, &dbc, 0, 1);
Yoni Fogel's avatar
Yoni Fogel committed
2106 2107 2108 2109
    if (r!=0) return r;
    r = toku_c_get(dbc, key, data, (flags == 0) ? DB_SET : DB_GET_BOTH);
    int r2 = toku_c_close(dbc);
    return r ? r : r2;
2110 2111 2112
}

static int toku_db_pget (DB *db, DB_TXN *txn, DBT *key, DBT *pkey, DBT *data, u_int32_t flags) {
2113
    HANDLE_PANICKED_DB(db);
2114
    int r;
2115 2116
    int r2;
    DBC *dbc;
2117 2118
    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
2119
    assert(db->i->brt != db->i->primary->i->brt); // Make sure they realy are different trees.
2120
    assert(db!=db->i->primary);
2121

Rich Prohaska's avatar
Rich Prohaska committed
2122 2123 2124
    if ((db->i->open_flags & DB_THREAD) && (db_thread_need_flags(pkey) || db_thread_need_flags(data)))
        return EINVAL;

2125
    r = toku_db_cursor(db, txn, &dbc, 0, 1);
2126
    if (r!=0) return r;
2127
    r = toku_c_pget(dbc, key, pkey, data, DB_SET);
Yoni Fogel's avatar
Yoni Fogel committed
2128
    if (r==DB_KEYEMPTY) r = DB_NOTFOUND;
2129
    r2 = toku_c_close(dbc);
2130 2131
    if (r!=0) return r;
    return r2;    
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2132 2133
}

2134
#if 0
2135
static int toku_db_key_range(DB * db, DB_TXN * txn, DBT * dbt, DB_KEY_RANGE * kr, u_int32_t flags) {
2136 2137
    HANDLE_PANICKED_DB(db);
    txn=txn; dbt=dbt; kr=kr; flags=flags;
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2138
    toku_ydb_barf();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2139
    abort();
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2140
}
2141
#endif
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2142

Yoni Fogel's avatar
Yoni Fogel committed
2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162
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
2163 2164 2165
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
2166
    {
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2167 2168 2169 2170
        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
2171 2172 2173 2174
        // 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
2175 2176
        }
        return result;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2177 2178 2179
    }
}

2180
static int find_db_file(DB_ENV* dbenv, const char *fname, char** full_name_out) {
Yoni Fogel's avatar
Yoni Fogel committed
2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195
    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
2196
                r = errno;
Yoni Fogel's avatar
Yoni Fogel committed
2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213
                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
2214 2215 2216 2217
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
2218 2219
    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
2220 2221 2222
    return EINVAL;
}

Yoni Fogel's avatar
Yoni Fogel committed
2223
static int toku_txn_add_lt(DB_TXN* txn, toku_lock_tree* lt) {
Yoni Fogel's avatar
Yoni Fogel committed
2224
    int r = ENOSYS;
Yoni Fogel's avatar
Yoni Fogel committed
2225 2226 2227 2228 2229 2230 2231
    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
2232 2233
        r = 0;
        goto cleanup;
Yoni Fogel's avatar
Yoni Fogel committed
2234
    }
Yoni Fogel's avatar
Yoni Fogel committed
2235 2236 2237 2238 2239 2240
    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
2241 2242 2243
    return r;
}

Yoni Fogel's avatar
Yoni Fogel committed
2244 2245 2246
static toku_dbt_cmp toku_db_get_compare_fun(DB* db) {
    return db->i->brt->compare_fun;
}
Yoni Fogel's avatar
Yoni Fogel committed
2247

Yoni Fogel's avatar
Yoni Fogel committed
2248 2249
static toku_dbt_cmp toku_db_get_dup_compare(DB* db) {
    return db->i->brt->dup_compare;
Yoni Fogel's avatar
Yoni Fogel committed
2250 2251
}

2252
static int toku_db_open(DB * db, DB_TXN * txn, const char *fname, const char *dbname, DBTYPE dbtype, u_int32_t flags, int mode) {
2253
    HANDLE_PANICKED_DB(db);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2254
    // Warning.  Should check arguments.  Should check return codes on malloc and open and so forth.
Yoni Fogel's avatar
Yoni Fogel committed
2255 2256
    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
2257

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2258
    int openflags = 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2259
    int r;
Yoni Fogel's avatar
Yoni Fogel committed
2260
    if (dbtype!=DB_BTREE && dbtype!=DB_UNKNOWN) return EINVAL;
2261 2262 2263
    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;
Rich Prohaska's avatar
Rich Prohaska committed
2264
    int is_db_unknown = dbtype == DB_UNKNOWN;
2265
    if (flags & ~DB_THREAD) return EINVAL; // unknown flags
2266 2267 2268

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

2270 2271 2272 2273 2274 2275 2276 2277
    /* 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;

2278
    if (db_opened(db))
2279
        return EINVAL;              /* It was already open. */
Yoni Fogel's avatar
Yoni Fogel committed
2280 2281 2282
    
    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
2283
    // printf("Full name = %s\n", db->i->full_fname);
Yoni Fogel's avatar
Yoni Fogel committed
2284
    db->i->database_name = toku_strdup(dbname ? dbname : "");
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2285 2286 2287 2288
    if (db->i->database_name == 0) {
        r = ENOMEM;
        goto error_cleanup;
    }
2289
    if (is_db_rdonly)
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2290 2291 2292
        openflags |= O_RDONLY;
    else
        openflags |= O_RDWR;
2293
    
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2294
    {
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2295 2296 2297
        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. */
2298 2299
            if (dbname == 0 && is_db_create) {
                if (is_db_excl) {
2300 2301 2302
                    r = EEXIST;
                    goto error_cleanup;
                }
2303
		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
2304 2305
            }
        } else {
2306
            if (!is_db_create) {
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2307 2308 2309 2310
                r = ENOENT;
                goto error_cleanup;
            }
        }
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2311
    }
2312
    if (is_db_create) openflags |= O_CREAT;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2313 2314 2315

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

Yoni Fogel's avatar
Yoni Fogel committed
2317

2318
    r = toku_brt_open(db->i->brt, db->i->full_fname, fname, dbname,
2319 2320
		      is_db_create, is_db_excl, is_db_unknown,
		      db->dbenv->i->cachetable,
2321 2322
		      txn ? txn->i->tokutxn : NULL_TXN,
		      db);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2323 2324 2325
    if (r != 0)
        goto error_cleanup;

Yoni Fogel's avatar
Yoni Fogel committed
2326
    if (need_locktree) {
Yoni Fogel's avatar
Yoni Fogel committed
2327 2328 2329 2330
        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
2331 2332 2333 2334 2335 2336

        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
2337
    }
Yoni Fogel's avatar
Yoni Fogel committed
2338

Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2339
    return 0;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2340 2341
 
error_cleanup:
Yoni Fogel's avatar
Yoni Fogel committed
2342 2343 2344 2345
    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
2346 2347 2348 2349 2350 2351 2352 2353
    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;
    }
Yoni Fogel's avatar
Yoni Fogel committed
2354
    if (db->i->lt) {
Yoni Fogel's avatar
Yoni Fogel committed
2355
        toku_lt_remove_ref(db->i->lt);
Yoni Fogel's avatar
Yoni Fogel committed
2356 2357
        db->i->lt = NULL;
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2358
    return r;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2359
}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
2360

2361 2362
static int toku_db_put_noassociate(DB * db, DB_TXN * txn, DBT * key, DBT * data, u_int32_t flags) {
    int r;
2363

2364
    unsigned int brtflags;
2365
    r = toku_brt_get_flags(db->i->brt, &brtflags); assert(r == 0);
2366 2367 2368

    /* limit the size of key and data */
    unsigned int nodesize;
2369 2370 2371 2372 2373 2374 2375 2376
    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
2377
            return toku_ydb_do_error(db->dbenv, EINVAL, "The largest key or data item allowed is %d bytes", limit);
2378
    }
2379 2380 2381 2382 2383 2384 2385

    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
2386 2387 2388 2389 2390
        memset(&testfordata, 0, sizeof(testfordata));
        testfordata.flags = DB_DBT_MALLOC;
        r = toku_db_get_noassociate(db, txn, key, &testfordata, 0);
        if (r == 0) {
            if (testfordata.data) toku_free(testfordata.data);
2391
            return DB_KEYEXIST;
Yoni Fogel's avatar
Yoni Fogel committed
2392
        }
Yoni Fogel's avatar
Yoni Fogel committed
2393
        if (r != DB_NOTFOUND) return r;
2394 2395 2396 2397
    } else if (flags != 0) {
        /* no other flags are currently supported */
        return EINVAL;
    } else {
2398
        assert(flags == 0);
2399
        if (brtflags & TOKU_DB_DUPSORT) {
2400
#if TDB_EQ_BDB
2401
            r = toku_db_get_noassociate(db, txn, key, data, DB_GET_BOTH);
2402 2403
            if (r == 0)
                return DB_KEYEXIST;
Yoni Fogel's avatar
Yoni Fogel committed
2404
            if (r != DB_NOTFOUND) return r;
2405
#else
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2406
	    return toku_ydb_do_error(db->dbenv, EINVAL, "Tokudb requires that db->put specify DB_YESOVERWRITE or DB_NOOVERWRITE on DB_DUPSORT databases");
2407
#endif
2408 2409
        }
    }
Yoni Fogel's avatar
Yoni Fogel committed
2410
    if (db->i->lt) {
Yoni Fogel's avatar
Yoni Fogel committed
2411 2412 2413 2414 2415
        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
2416 2417
        if (r!=0) return r;
    }
2418 2419 2420 2421 2422
    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;
}

2423 2424 2425 2426
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
2427 2428
    if (r==DB_DONOTINDEX) { r = 0; goto clean_up; }
    if (r != 0) goto clean_up;
2429 2430 2431 2432 2433
#ifdef DB_DBT_MULTIPLE
    if (idx.flags & DB_DBT_MULTIPLE) {
	return EINVAL; // We aren't ready for this
    }
#endif
2434
    r = toku_db_put_noassociate(secondary, txn, &idx, key, DB_YESOVERWRITE);
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2435
    clean_up:
2436
    if (idx.flags & DB_DBT_APPMALLOC) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2437 2438
        /* This should be free because idx.data is allocated by the user */
        free(idx.data);
2439 2440 2441 2442
    }
    return r;
}

2443
static int toku_db_put(DB * db, DB_TXN * txn, DBT * key, DBT * data, u_int32_t flags) {
2444
    HANDLE_PANICKED_DB(db);
2445 2446
    int r;

2447
    //Cannot put directly into a secondary.
2448
    if (db->i->primary != 0) return EINVAL;
2449

2450
    r = toku_db_put_noassociate(db, txn, key, data, flags);
2451 2452
    if (r!=0) return r;
    // For each secondary add the relevant records.
2453 2454 2455 2456 2457 2458 2459
    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;
2460 2461
    }
    return 0;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2462
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2463

2464
static int toku_db_remove(DB * db, const char *fname, const char *dbname, u_int32_t flags) {
2465
    HANDLE_PANICKED_DB(db);
Yoni Fogel's avatar
Yoni Fogel committed
2466 2467 2468 2469 2470 2471
    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
2472 2473

    //TODO: Verify DB* db not yet opened
Yoni Fogel's avatar
Yoni Fogel committed
2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488
    //TODO: Verify db file not in use. (all dbs in the file must be unused)
    r = toku_db_open(db, NULL, fname, dbname, DB_BTREE, 0, 0777);
    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
2489 2490 2491
    if (dbname) {
        //TODO: Verify the target db is not open
        //TODO: Use master database (instead of manual edit) when implemented.
2492
        r = toku_brt_remove_subdb(db->i->brt, dbname, flags);
Yoni Fogel's avatar
Yoni Fogel committed
2493
        if (r!=0) { goto cleanup; }
Yoni Fogel's avatar
Yoni Fogel committed
2494
    }
Yoni Fogel's avatar
Yoni Fogel committed
2495 2496 2497 2498
    if (!dbname) {
        r = find_db_file(db->dbenv, fname, &full_name);
        if (r!=0) { goto cleanup; }
        assert(full_name);
2499 2500 2501
	r = toku_db_close(db, 0);
	need_close = FALSE;
	if (r!=0) { goto cleanup; }
Yoni Fogel's avatar
Yoni Fogel committed
2502
        if (unlink(full_name) != 0) { r = errno; goto cleanup; }
2503 2504 2505 2506
    } else {
	r = toku_db_close(db, 0);
	need_close = FALSE;
	if (r!=0) { goto cleanup; }
2507
    }
2508

Yoni Fogel's avatar
Yoni Fogel committed
2509 2510 2511 2512 2513 2514 2515
    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
2516
    return r ? r : r2;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2517
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2518

Yoni Fogel's avatar
Yoni Fogel committed
2519 2520 2521 2522 2523 2524 2525 2526 2527
/* 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).
*/
2528
static int toku_db_rename(DB * db, const char *namea, const char *nameb, const char *namec, u_int32_t flags) {
2529
    HANDLE_PANICKED_DB(db);
2530
    if (flags!=0) return EINVAL;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
2531 2532
    char afull[PATH_MAX], cfull[PATH_MAX];
    int r;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2533 2534 2535 2536 2537
    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
2538
    return rename(afull, cfull);
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2539
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2540

2541
static int toku_db_set_bt_compare(DB * db, int (*bt_compare) (DB *, const DBT *, const DBT *)) {
2542
    HANDLE_PANICKED_DB(db);
2543
    int r = toku_brt_set_bt_compare(db->i->brt, bt_compare);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2544 2545 2546
    return r;
}

2547
static int toku_db_set_dup_compare(DB *db, int (*dup_compare)(DB *, const DBT *, const DBT *)) {
2548
    HANDLE_PANICKED_DB(db);
2549
    int r = toku_brt_set_dup_compare(db->i->brt, dup_compare);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2550 2551 2552
    return r;
}

2553
static int toku_db_set_flags(DB *db, u_int32_t flags) {
2554
    HANDLE_PANICKED_DB(db);
2555

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

Yoni Fogel's avatar
Yoni Fogel committed
2559 2560 2561 2562
    u_int32_t tflags;
    int r = toku_brt_get_flags(db->i->brt, &tflags);
    if (r!=0) return r;
    
2563 2564 2565 2566
    if (flags & DB_DUP)
        tflags += TOKU_DB_DUP;
    if (flags & DB_DUPSORT)
        tflags += TOKU_DB_DUPSORT;
Yoni Fogel's avatar
Yoni Fogel committed
2567
    r = toku_brt_set_flags(db->i->brt, tflags);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2568 2569 2570
    return r;
}

2571
static int toku_db_get_flags(DB *db, u_int32_t *pflags) {
2572
    HANDLE_PANICKED_DB(db);
2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590
    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;
}

2591
static int toku_db_set_pagesize(DB *db, u_int32_t pagesize) {
2592
    HANDLE_PANICKED_DB(db);
2593
    int r = toku_brt_set_nodesize(db->i->brt, pagesize);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2594
    return r;
Bradley C. Kuszmaul's avatar
Rename  
Bradley C. Kuszmaul committed
2595
}
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2596

2597
#if 0
2598
static int toku_db_stat(DB * db, void *v, u_int32_t flags) {
2599 2600
    HANDLE_PANICKED_DB(db);
    v=v; flags=flags;
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2601
    toku_ydb_barf();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2602 2603
    abort();
}
2604
#endif
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2605

Rich Prohaska's avatar
Rich Prohaska committed
2606 2607 2608 2609 2610 2611
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);
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627
static int toku_db_keyrange64(DB* db, DB_TXN* txn __attribute__((__unused__)), DBT* key, u_int64_t* less, u_int64_t* equal, u_int64_t* greater, int* is_exact) {
    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
2628 2629 2630
//TODO: DB_AUTO_COMMIT.
//TODO: Nowait only conditionally?
//TODO: NOSYNC change to SYNC if DB_ENV has something in set_flags
2631
static inline int toku_db_construct_autotxn(DB* db, DB_TXN **txn, BOOL* changed,
Yoni Fogel's avatar
Yoni Fogel committed
2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646
                                            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;
}

2647
static inline int toku_db_destruct_autotxn(DB_TXN *txn, int r, BOOL changed) {
Yoni Fogel's avatar
Yoni Fogel committed
2648 2649 2650 2651 2652 2653
    if (!changed) return r;
    if (r==0) return toku_txn_commit(txn, 0);
    toku_txn_abort(txn);
    return r; 
}

2654
static inline int autotxn_db_associate(DB *primary, DB_TXN *txn, DB *secondary,
Yoni Fogel's avatar
Yoni Fogel committed
2655 2656 2657 2658 2659 2660 2661 2662
                                       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);
}

2663 2664
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
2665
    toku_ydb_lock(); int r = autotxn_db_associate(primary, txn, secondary, callback, flags); toku_ydb_unlock(); return r;
2666 2667 2668
}

static int locked_db_close(DB * db, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2669
    toku_ydb_lock(); int r = toku_db_close(db, flags); toku_ydb_unlock(); return r;
2670 2671
}

2672
static inline int autotxn_db_cursor(DB *db, DB_TXN *txn, DBC **c, u_int32_t flags) {
Yoni Fogel's avatar
Yoni Fogel committed
2673
    if (!txn && (db->dbenv->i->open_flags & DB_INIT_TXN)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2674
        return toku_ydb_do_error(db->dbenv, EINVAL,
Yoni Fogel's avatar
Yoni Fogel committed
2675 2676
              "Cursors in a transaction environment must have transactions.\n");
    }
2677
    return toku_db_cursor(db, txn, c, flags, 0);
Yoni Fogel's avatar
Yoni Fogel committed
2678 2679
}

2680
static int locked_db_cursor(DB *db, DB_TXN *txn, DBC **c, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2681
    toku_ydb_lock(); int r = autotxn_db_cursor(db, txn, c, flags); toku_ydb_unlock(); return r;
2682 2683
}

2684
static inline int autotxn_db_del(DB* db, DB_TXN* txn, DBT* key,
Yoni Fogel's avatar
Yoni Fogel committed
2685 2686 2687 2688 2689 2690 2691 2692
                                 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);
}

2693
static int locked_db_del(DB * db, DB_TXN * txn, DBT * key, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2694
    toku_ydb_lock(); int r = autotxn_db_del(db, txn, key, flags); toku_ydb_unlock(); return r;
Yoni Fogel's avatar
Yoni Fogel committed
2695 2696
}

2697
static inline int autotxn_db_get(DB* db, DB_TXN* txn, DBT* key, DBT* data,
Yoni Fogel's avatar
Yoni Fogel committed
2698 2699 2700 2701 2702 2703
                                 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);
2704 2705 2706
}

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
2707
    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
2708 2709
}

2710
static inline int autotxn_db_pget(DB* db, DB_TXN* txn, DBT* key, DBT* pkey,
Yoni Fogel's avatar
Yoni Fogel committed
2711 2712 2713 2714 2715 2716
                                  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);
2717 2718 2719
}

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
2720
    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
2721 2722
}

2723
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
2724 2725 2726 2727 2728
    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);
2729 2730 2731
}

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
2732
    toku_ydb_lock(); int r = autotxn_db_open(db, txn, fname, dbname, dbtype, flags, mode); toku_ydb_unlock(); return r;
2733 2734
}

2735
static inline int autotxn_db_put(DB* db, DB_TXN* txn, DBT* key, DBT* data,
Yoni Fogel's avatar
Yoni Fogel committed
2736
                                 u_int32_t flags) {
2737
    //{ 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
2738 2739 2740 2741 2742 2743 2744
    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);
}

2745
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
2746
    toku_ydb_lock(); int r = autotxn_db_put(db, txn, key, data, flags); toku_ydb_unlock(); return r;
2747 2748 2749
}

static int locked_db_remove(DB * db, const char *fname, const char *dbname, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2750
    toku_ydb_lock(); int r = toku_db_remove(db, fname, dbname, flags); toku_ydb_unlock(); return r;
2751 2752 2753
}

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
2754
    toku_ydb_lock(); int r = toku_db_rename(db, namea, nameb, namec, flags); toku_ydb_unlock(); return r;
2755 2756 2757
}

static int locked_db_set_bt_compare(DB * db, int (*bt_compare) (DB *, const DBT *, const DBT *)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2758
    toku_ydb_lock(); int r = toku_db_set_bt_compare(db, bt_compare); toku_ydb_unlock(); return r;
2759 2760 2761
}

static int locked_db_set_dup_compare(DB * db, int (*dup_compare) (DB *, const DBT *, const DBT *)) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2762
    toku_ydb_lock(); int r = toku_db_set_dup_compare(db, dup_compare); toku_ydb_unlock(); return r;
2763 2764 2765 2766 2767 2768 2769
}

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
2770
    toku_ydb_lock(); int r = toku_db_set_flags(db, flags); toku_ydb_unlock(); return r;
2771 2772 2773
}

static int locked_db_get_flags(DB *db, u_int32_t *flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2774
    toku_ydb_lock(); int r = toku_db_get_flags(db, flags); toku_ydb_unlock(); return r;
2775 2776 2777
}

static int locked_db_set_pagesize(DB *db, u_int32_t pagesize) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2778
    toku_ydb_lock(); int r = toku_db_set_pagesize(db, pagesize); toku_ydb_unlock(); return r;
2779 2780 2781
}

static int locked_db_fd(DB *db, int *fdp) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2782
    toku_ydb_lock(); int r = toku_db_fd(db, fdp); toku_ydb_unlock(); return r;
2783 2784
}

Zardosht Kasheff's avatar
Zardosht Kasheff committed
2785 2786 2787 2788 2789

static int locked_db_keyrange64(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_keyrange64(db, txn, dbt, less, equal, greater, is_exact); toku_ydb_unlock(); return r;
}

2790
static int toku_db_create(DB ** db, DB_ENV * env, u_int32_t flags) {
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2791 2792
    int r;

2793 2794
    if (flags) return EINVAL;

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2795 2796 2797
    /* if the env already exists then add a ref to it
       otherwise create one */
    if (env) {
2798
        if (!env_opened(env))
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2799
            return EINVAL;
2800
        env_add_ref(env);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2801
    } else {
2802
        r = toku_env_create(&env, 0);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2803 2804
        if (r != 0)
            return r;
2805
        r = toku_env_open(env, ".", DB_PRIVATE + DB_INIT_MPOOL, 0);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2806
        if (r != 0) {
2807
            toku_env_close(env, 0);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2808 2809
            return r;
        }
2810
        assert(env_opened(env));
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
2811
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2812
    
2813
    DB *MALLOC(result);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2814
    if (result == 0) {
2815
        env_unref(env);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2816
        return ENOMEM;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
2817
    }
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2818
    memset(result, 0, sizeof *result);
Zardosht Kasheff's avatar
Zardosht Kasheff committed
2819
    result->key_range64 = locked_db_keyrange64;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2820
    result->dbenv = env;
2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839
    result->associate = locked_db_associate;
    result->close = locked_db_close;
    result->cursor = locked_db_cursor;
    result->del = locked_db_del;
    result->get = locked_db_get;
    //    result->key_range = locked_db_key_range;
    result->open = locked_db_open;
    result->pget = locked_db_pget;
    result->put = locked_db_put;
    result->remove = locked_db_remove;
    result->rename = locked_db_rename;
    result->set_bt_compare = locked_db_set_bt_compare;
    result->set_dup_compare = locked_db_set_dup_compare;
    result->set_errfile = locked_db_set_errfile;
    result->set_pagesize = locked_db_set_pagesize;
    result->set_flags = locked_db_set_flags;
    result->get_flags = locked_db_get_flags;
    //    result->stat = locked_db_stat;
    result->fd = locked_db_fd;
2840
    MALLOC(result->i);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2841 2842
    if (result->i == 0) {
        toku_free(result);
2843
        env_unref(env);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2844 2845 2846
        return ENOMEM;
    }
    memset(result->i, 0, sizeof *result->i);
2847
    result->i->db = result;
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2848 2849 2850 2851 2852 2853 2854 2855
    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;
2856 2857 2858
    list_init(&result->i->associated);
    result->i->primary = 0;
    result->i->associate_callback = 0;
2859
    r = toku_brt_create(&result->i->brt);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2860 2861 2862
    if (r != 0) {
        toku_free(result->i);
        toku_free(result);
2863
        env_unref(env);
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2864 2865
        return ENOMEM;
    }
2866
    ydb_add_ref();
Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2867 2868
    *db = result;
    return 0;
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
2869
}
Bradley C. Kuszmaul's avatar
Bradley C. Kuszmaul committed
2870

2871
int DB_CREATE_FUN (DB ** db, DB_ENV * env, u_int32_t flags) {
Vincenzo Liberatore's avatar
Vincenzo Liberatore committed
2872
    toku_ydb_lock(); int r = toku_db_create(db, env, flags); toku_ydb_unlock(); return r;
2873 2874 2875 2876
}

/* need db_strerror_r for multiple threads */

Bradley C. Kuszmaul's avatar
up  
Bradley C. Kuszmaul committed
2877 2878 2879 2880 2881 2882 2883 2884
char *db_strerror(int error) {
    char *errorstr;
    if (error >= 0) {
        errorstr = strerror(error);
        if (errorstr)
            return errorstr;
    }
    
2885 2886 2887
    if (error==DB_BADFORMAT) {
	return "Database Bad Format (probably a corrupted database)";
    }
2888 2889 2890
    if (error==DB_NOTFOUND) {
	return "Not found";
    }
2891

2892
    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
2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904
    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
2905 2906
    return DB_VERSION_STRING;
}
2907 2908 2909 2910
 
int db_env_set_func_fsync (int (*fsync_function)(int)) {
    return toku_set_func_fsync(fsync_function);
}
Yoni Fogel's avatar
Yoni Fogel committed
2911